@boyingliu01/xp-gate 0.15.5 → 0.18.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 (165) hide show
  1. package/adapter-common.sh +0 -0
  2. package/adapters/cpp.sh +0 -0
  3. package/adapters/dart.sh +0 -0
  4. package/adapters/flutter.sh +0 -0
  5. package/adapters/go.sh +0 -0
  6. package/adapters/iac.sh +0 -0
  7. package/adapters/java.sh +0 -0
  8. package/adapters/kotlin.sh +0 -0
  9. package/adapters/objectivec.sh +0 -0
  10. package/adapters/plugins/book299-20132-python/scripts/install-gradle.sh +0 -0
  11. package/adapters/plugins/book299-20132-python/scripts/install-maven.sh +0 -0
  12. package/adapters/plugins/book299-4081-c/scripts/install-gradle.sh +0 -0
  13. package/adapters/plugins/book299-4081-c/scripts/install-maven.sh +0 -0
  14. package/adapters/plugins/book299-4083-javascriptes5/scripts/install-gradle.sh +0 -0
  15. package/adapters/plugins/book299-4083-javascriptes5/scripts/install-maven.sh +0 -0
  16. package/adapters/powershell.sh +0 -0
  17. package/adapters/python.sh +0 -0
  18. package/adapters/shell.sh +0 -0
  19. package/adapters/swift.sh +0 -0
  20. package/adapters/typescript.sh +0 -0
  21. package/bin/xp-gate.js +29 -1
  22. package/gate-3.sh +0 -0
  23. package/gate-4.sh +0 -0
  24. package/gate-7.sh +0 -0
  25. package/gate-8.sh +0 -0
  26. package/gate-9.sh +0 -0
  27. package/hooks/adapter-common.sh +0 -0
  28. package/hooks/gate-3.sh +0 -0
  29. package/hooks/gate-4.sh +0 -0
  30. package/hooks/gate-7.sh +0 -0
  31. package/hooks/gate-8.sh +0 -0
  32. package/hooks/gate-9.sh +0 -0
  33. package/hooks/lib/now-ms.sh +33 -0
  34. package/hooks/pre-commit +63 -47
  35. package/hooks/pre-push +0 -0
  36. package/hooks/sprint-gate.sh +291 -0
  37. package/lib/__tests__/check-version.test.js +122 -0
  38. package/lib/__tests__/doctor.test.js +13 -15
  39. package/lib/__tests__/gate-audit.test.ts +38 -0
  40. package/lib/__tests__/phase-transition.test.js +512 -272
  41. package/lib/__tests__/retro.test.js +131 -0
  42. package/lib/__tests__/sprint-audit.test.js +207 -207
  43. package/lib/__tests__/sprint-status-rework.test.js +184 -0
  44. package/lib/check-version.js +9 -0
  45. package/lib/doctor-tui.js +268 -198
  46. package/lib/doctor.js +15 -3
  47. package/lib/gate-audit.ts +18 -7
  48. package/lib/gate-runner.js +77 -30
  49. package/lib/init.js +10 -0
  50. package/lib/language-tools.js +833 -833
  51. package/lib/mattpocock-license-verdict.json +7 -0
  52. package/lib/phase-transition.js +499 -249
  53. package/lib/retro.js +222 -0
  54. package/lib/shared-utils.js +7 -0
  55. package/lib/sprint-audit.js +235 -235
  56. package/lib/sprint-init.js +207 -0
  57. package/lib/sprint-state-migrator.js +1 -0
  58. package/lib/sprint-status.js +111 -0
  59. package/mock-policy/AGENTS.md +3 -3
  60. package/mutation/AGENTS.md +3 -3
  61. package/package.json +3 -2
  62. package/plugins/claude-code/.claude-plugin/plugin.json +1 -1
  63. package/plugins/claude-code/bin/delphi-review-guard.sh +0 -0
  64. package/plugins/claude-code/bin/xp-gate-check +0 -0
  65. package/plugins/claude-code/skills/batch-grill-me/SKILL.md +15 -0
  66. package/plugins/claude-code/skills/delphi-review/AGENTS.md +3 -3
  67. package/plugins/claude-code/skills/delphi-review/SKILL.md +59 -4
  68. package/plugins/claude-code/skills/delphi-review/references/requirements.md +390 -0
  69. package/plugins/claude-code/skills/delphi-review/references/round-templates.md +67 -0
  70. package/plugins/claude-code/skills/domain-modeling/ADR-FORMAT.md +64 -0
  71. package/plugins/claude-code/skills/domain-modeling/CONTEXT-FORMAT.md +60 -0
  72. package/plugins/claude-code/skills/domain-modeling/SKILL.md +74 -0
  73. package/plugins/claude-code/skills/grill-with-docs/SKILL.md +7 -0
  74. package/plugins/claude-code/skills/grilling/SKILL.md +12 -0
  75. package/plugins/claude-code/skills/sprint-flow/AGENTS.md +3 -3
  76. package/plugins/claude-code/skills/sprint-flow/SKILL.md +168 -43
  77. package/plugins/claude-code/skills/sprint-flow/references/components/memory.md +1 -1
  78. package/plugins/claude-code/skills/sprint-flow/references/components/middleware.md +1 -1
  79. package/plugins/claude-code/skills/sprint-flow/references/components/skill-invocations.md +21 -20
  80. package/plugins/claude-code/skills/sprint-flow/references/components/tool-descriptions.md +22 -23
  81. package/plugins/claude-code/skills/sprint-flow/references/orchestration-rules.md +14 -12
  82. package/plugins/claude-code/skills/sprint-flow/references/phase-2-design.md +145 -133
  83. package/plugins/claude-code/skills/sprint-flow/references/phase-3-build.md +69 -2
  84. package/plugins/claude-code/skills/sprint-flow/references/phase-4-verify.md +93 -31
  85. package/plugins/claude-code/skills/sprint-flow/references/phase-5-ship.md +99 -14
  86. package/plugins/claude-code/skills/sprint-flow/references/phase-6-close.md +37 -5
  87. package/plugins/claude-code/skills/sprint-flow/references/phase-overview.md +58 -53
  88. package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +3 -3
  89. package/plugins/claude-code/skills/test-specification-alignment/SKILL.md +8 -3
  90. package/plugins/claude-code/skills/to-issues/SKILL.md +1 -1
  91. package/plugins/opencode/index.ts +1 -0
  92. package/plugins/opencode/package.json +1 -1
  93. package/plugins/opencode/skills/batch-grill-me/SKILL.md +15 -0
  94. package/plugins/opencode/skills/delphi-review/AGENTS.md +3 -3
  95. package/plugins/opencode/skills/delphi-review/SKILL.md +59 -4
  96. package/plugins/opencode/skills/delphi-review/references/requirements.md +390 -0
  97. package/plugins/opencode/skills/delphi-review/references/round-templates.md +67 -0
  98. package/plugins/opencode/skills/domain-modeling/ADR-FORMAT.md +64 -0
  99. package/plugins/opencode/skills/domain-modeling/CONTEXT-FORMAT.md +60 -0
  100. package/plugins/opencode/skills/domain-modeling/SKILL.md +74 -0
  101. package/plugins/opencode/skills/grill-with-docs/SKILL.md +7 -0
  102. package/plugins/opencode/skills/grilling/SKILL.md +12 -0
  103. package/plugins/opencode/skills/sprint-flow/AGENTS.md +3 -3
  104. package/plugins/opencode/skills/sprint-flow/SKILL.md +168 -43
  105. package/plugins/opencode/skills/sprint-flow/references/components/memory.md +1 -1
  106. package/plugins/opencode/skills/sprint-flow/references/components/middleware.md +1 -1
  107. package/plugins/opencode/skills/sprint-flow/references/components/skill-invocations.md +21 -20
  108. package/plugins/opencode/skills/sprint-flow/references/components/tool-descriptions.md +22 -23
  109. package/plugins/opencode/skills/sprint-flow/references/orchestration-rules.md +14 -12
  110. package/plugins/opencode/skills/sprint-flow/references/phase-2-design.md +145 -133
  111. package/plugins/opencode/skills/sprint-flow/references/phase-3-build.md +69 -2
  112. package/plugins/opencode/skills/sprint-flow/references/phase-4-verify.md +93 -31
  113. package/plugins/opencode/skills/sprint-flow/references/phase-5-ship.md +99 -14
  114. package/plugins/opencode/skills/sprint-flow/references/phase-6-close.md +37 -5
  115. package/plugins/opencode/skills/sprint-flow/references/phase-overview.md +58 -53
  116. package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +3 -3
  117. package/plugins/opencode/skills/test-specification-alignment/SKILL.md +8 -3
  118. package/plugins/opencode/skills/to-issues/SKILL.md +1 -1
  119. package/plugins/qoder/agents/delphi-architecture.md +48 -48
  120. package/plugins/qoder/agents/delphi-feasibility.md +48 -48
  121. package/plugins/qoder/agents/delphi-technical.md +48 -48
  122. package/plugins/qoder/bin/sprint-flow-guard.sh +0 -0
  123. package/plugins/qoder/bin/xp-gate-check +0 -0
  124. package/plugins/qoder/plugin.json +1 -1
  125. package/plugins/qoder/skills/delphi-review/AGENTS.md +3 -3
  126. package/plugins/qoder/skills/sprint-flow/AGENTS.md +3 -3
  127. package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +3 -3
  128. package/principles/AGENTS.md +3 -3
  129. package/scripts/__tests__/check-mattpocock-license.test.js +229 -0
  130. package/scripts/__tests__/sync-package-content.test.js +50 -0
  131. package/scripts/check-mattpocock-license.cjs +302 -0
  132. package/scripts/delphi-external-review.cjs +432 -432
  133. package/scripts/migrate-audit-anomalies.mjs +78 -0
  134. package/scripts/sync-package-content.js +52 -5
  135. package/skills/batch-grill-me/SKILL.md +15 -0
  136. package/skills/delphi-review/AGENTS.md +3 -3
  137. package/skills/delphi-review/SKILL.md +59 -4
  138. package/skills/delphi-review/references/requirements.md +390 -0
  139. package/skills/delphi-review/references/round-templates.md +67 -0
  140. package/skills/domain-modeling/ADR-FORMAT.md +64 -0
  141. package/skills/domain-modeling/CONTEXT-FORMAT.md +60 -0
  142. package/skills/domain-modeling/SKILL.md +74 -0
  143. package/skills/grill-with-docs/SKILL.md +7 -0
  144. package/skills/grilling/SKILL.md +12 -0
  145. package/skills/sprint-flow/AGENTS.md +3 -3
  146. package/skills/sprint-flow/SKILL.md +168 -43
  147. package/skills/sprint-flow/references/components/memory.md +1 -1
  148. package/skills/sprint-flow/references/components/middleware.md +1 -1
  149. package/skills/sprint-flow/references/components/skill-invocations.md +21 -20
  150. package/skills/sprint-flow/references/components/tool-descriptions.md +22 -23
  151. package/skills/sprint-flow/references/orchestration-rules.md +14 -12
  152. package/skills/sprint-flow/references/phase-2-design.md +145 -133
  153. package/skills/sprint-flow/references/phase-3-build.md +69 -2
  154. package/skills/sprint-flow/references/phase-4-verify.md +93 -31
  155. package/skills/sprint-flow/references/phase-5-ship.md +99 -14
  156. package/skills/sprint-flow/references/phase-6-close.md +37 -5
  157. package/skills/sprint-flow/references/phase-overview.md +58 -53
  158. package/skills/test-specification-alignment/AGENTS.md +3 -3
  159. package/skills/test-specification-alignment/SKILL.md +8 -3
  160. package/skills/to-issues/SKILL.md +1 -1
  161. package/adapters/gate-3.sh +0 -68
  162. package/adapters/gate-4.sh +0 -80
  163. package/adapters/gate-7.sh +0 -45
  164. package/adapters/gate-8.sh +0 -56
  165. package/adapters/gate-9.sh +0 -104
@@ -1,249 +1,499 @@
1
- /**
2
- * xp-gate phase-transition — Programmatic sprint phase transition
3
- *
4
- * Resolves #338 (dashboard never auto-renders) and #146 (sprint-state enforcement).
5
- *
6
- * This CLI command is the programmatic entry point for sprint phase transitions.
7
- * The sprint-flow SKILL.md MUST instruct the orchestrator to call this command
8
- * after each phase completion, replacing text-level MUST instructions with
9
- * a concrete CLI invocation.
10
- *
11
- * Usage:
12
- * xp-gate phase-transition <phase> <status> [--outputs <json>] [--render]
13
- *
14
- * Examples:
15
- * xp-gate phase-transition 1 completed
16
- * xp-gate phase-transition 2 in_progress
17
- * xp-gate phase-transition 3 completed --outputs '{"spec":"path/to/spec.yaml"}'
18
- * xp-gate phase-transition 3 completed --render (auto-render dashboard)
19
- *
20
- * @module phase-transition
21
- */
22
-
23
- 'use strict';
24
-
25
- const path = require('path');
26
- const fs = require('fs');
27
- const { SprintStateManager } = require('./sprint-state-manager');
28
-
29
- /**
30
- * Shared phase name lookup — single source of truth.
31
- * Used by renderDashboard, sprint-audit, and Layer 1 gate check.
32
- */
33
- const PHASE_NAMES = {
34
- 1: 'PREP', 2: 'DESIGN', 3: 'BUILD',
35
- 4: 'VERIFY', 5: 'SHIP', 6: 'CLOSE',
36
- };
37
-
38
- /**
39
- * Render ASCII dashboard from sprint state.
40
- * Reuses the formatSprintTable logic from sprint-status.
41
- * @param {object} state - Sprint state object
42
- * @returns {string} Rendered dashboard
43
- */
44
- function renderDashboard(state) {
45
- if (!state) return 'No sprint state found';
46
-
47
- const PHASE_NAMES_LOCAL = PHASE_NAMES;
48
-
49
- function statusIcon(status) {
50
- switch (status) {
51
- case 'completed': return '✅';
52
- case 'in_progress': return '🔄';
53
- case 'skipped': return '⏭️';
54
- case 'failed': return '❌';
55
- case 'paused': return '⏸️';
56
- default: return '⏳';
57
- }
58
- }
59
-
60
- function formatDuration(seconds) {
61
- if (seconds == null || seconds === 0) return '-';
62
- if (seconds < 60) return `${seconds}s`;
63
- const mins = Math.floor(seconds / 60);
64
- if (mins < 60) return `${mins}m`;
65
- const hrs = Math.floor(mins / 60);
66
- if (hrs < 24) return `${hrs}h ${mins % 60}m`;
67
- return `${Math.floor(hrs / 24)}d ${hrs % 24}h`;
68
- }
69
-
70
- const branch = state.isolation?.branch || 'unknown';
71
- const sprintId = state.id || 'unknown';
72
- const taskDesc = state.task_description || state.issue_title || '-';
73
- const overallStatus = state.status || 'running';
74
- const startedAt = state.started_at ? state.started_at.slice(0, 16).replace('T', ' ') : '-';
75
-
76
- // Build phase history lookup
77
- const historyLookup = {};
78
- if (Array.isArray(state.phase_history)) {
79
- for (const ph of state.phase_history) {
80
- historyLookup[String(ph.phase)] = ph;
81
- }
82
- }
83
-
84
- const currentPhase = state.phase || 1;
85
- const currentPhaseName = PHASE_NAMES_LOCAL[String(currentPhase)] || `Phase ${currentPhase}`;
86
-
87
- // Progress bar
88
- const completedCount = Object.values(historyLookup).filter(h => h.status === 'completed').length;
89
- const pct = Math.round((completedCount / 6) * 100);
90
- const filled = '█'.repeat(completedCount);
91
- const current = currentPhase <= 6 ? '▓' : '';
92
- const empty = '░'.repeat(Math.max(0, 6 - completedCount - (current ? 1 : 0)));
93
- const progressBar = `[${filled}${current}${empty}] ${pct}%`;
94
-
95
- // Build lines
96
- const lines = [];
97
- lines.push('+============================================================+');
98
- lines.push(`| SPRINT PROGRESS ${sprintId.padEnd(20)}|`);
99
- lines.push('+============================================================+');
100
- lines.push(`| 需求: ${(taskDesc).slice(0, 54).padEnd(54)}|`);
101
- lines.push(`| 分支: ${(branch).slice(0, 54).padEnd(54)}|`);
102
- lines.push(`| 状态: ${(overallStatus).slice(0, 15).padEnd(15)} 启动: ${startedAt.slice(0, 19).padEnd(19)}|`);
103
- lines.push('+============================================================+');
104
- lines.push('| |');
105
-
106
- for (let i = 1; i <= 6; i++) {
107
- const entry = historyLookup[String(i)];
108
- const icon = statusIcon(entry?.status || (i < currentPhase ? 'completed' : i === currentPhase ? 'in_progress' : 'pending'));
109
- const name = (PHASE_NAMES_LOCAL[String(i)] || `Phase ${i}`).padEnd(10);
110
- const dur = formatDuration(entry?.duration_seconds).padEnd(8);
111
- lines.push(`| ${icon} Phase ${i}/6 ${name} ${dur} |`);
112
- }
113
-
114
- lines.push('| |');
115
- lines.push(`| ${progressBar.padEnd(58)}|`);
116
- lines.push('+============================================================+');
117
- lines.push(`| > 当前: Phase ${currentPhase}/6 ${currentPhaseName}`.padEnd(59) + '|');
118
- lines.push(`| 状态: ${(entry_status(currentPhase, historyLookup)).padEnd(50)}|`);
119
- lines.push('+============================================================+');
120
-
121
- // Outputs section
122
- if (state.outputs && Object.keys(state.outputs).length > 0) {
123
- lines.push('| 输出物: |');
124
- for (const [key, val] of Object.entries(state.outputs)) {
125
- lines.push(`| ${(`${key}: ${val}`).slice(0, 55).padEnd(55)}|`);
126
- }
127
- lines.push('+============================================================+');
128
- }
129
-
130
- return lines.join('\n');
131
-
132
- function entry_status(phaseNum, lookup) {
133
- const e = lookup[String(phaseNum)];
134
- return e?.status || (phaseNum < currentPhase ? 'completed' : phaseNum === currentPhase ? 'in_progress' : 'pending');
135
- }
136
- }
137
-
138
- /**
139
- * CLI entry point for phase-transition command.
140
- * @param {string[]} args - CLI arguments
141
- * @returns {Promise<number>} Exit code
142
- */
143
- async function handlePhaseTransition(args = []) {
144
- if (args.includes('--help')) {
145
- console.log('Usage: xp-gate phase-transition <phase> <status> [options]');
146
- console.log('');
147
- console.log('Arguments:');
148
- console.log(' phase Phase number (1-6)');
149
- console.log(' status Status: in_progress | completed | skipped | failed | paused');
150
- console.log('');
151
- console.log('Options:');
152
- console.log(' --outputs <json> JSON object of outputs to record');
153
- console.log(' --render Render ASCII dashboard after transition');
154
- console.log(' --dir <path> Project directory (default: cwd)');
155
- console.log('');
156
- console.log('Examples:');
157
- console.log(' xp-gate phase-transition 1 completed');
158
- console.log(' xp-gate phase-transition 3 completed --render');
159
- console.log(' xp-gate phase-transition 2 in_progress --outputs \'{"spec":"path.yaml"}\'');
160
- return 0;
161
- }
162
-
163
- if (args.length < 2) {
164
- console.error('Error: Missing required arguments. Usage: xp-gate phase-transition <phase> <status>');
165
- return 1;
166
- }
167
-
168
- const phase = parseInt(args[0], 10);
169
- const status = args[1];
170
- const renderFlag = args.includes('--render');
171
- const dirIdx = args.indexOf('--dir');
172
- const projectDir = dirIdx >= 0 ? args[dirIdx + 1] : process.cwd();
173
-
174
- const outputsIdx = args.indexOf('--outputs');
175
- let outputs = {};
176
- if (outputsIdx >= 0 && args[outputsIdx + 1]) {
177
- try {
178
- outputs = JSON.parse(args[outputsIdx + 1]);
179
- } catch (err) {
180
- console.error(`Error: Invalid JSON for --outputs: ${err.message}`);
181
- return 1;
182
- }
183
- }
184
-
185
- // Validate inputs
186
- if (phase < 1 || phase > 6) {
187
- console.error(`Error: Phase must be 1-6, got ${phase}`);
188
- return 1;
189
- }
190
-
191
- const validStatuses = ['in_progress', 'completed', 'skipped', 'failed', 'paused'];
192
- if (!validStatuses.includes(status)) {
193
- console.error(`Error: Status must be one of: ${validStatuses.join(', ')}`);
194
- return 1;
195
- }
196
-
197
- // Execute transition
198
- try {
199
- const manager = new SprintStateManager(projectDir);
200
-
201
- // ── Layer 1: Pre-transition gate check ──
202
- // Check BEFORE transitionPhase() to validate previous phase completion.
203
- // Runs when status === 'in_progress' and phase >= 2.
204
- // No side effects — only outputs WARNING, does not modify state.
205
- if (status === 'in_progress' && phase >= 2) {
206
- const preState = manager.read();
207
- if (preState && Array.isArray(preState.phase_history)) {
208
- const prevPhase = phase - 1;
209
- const prevEntry = preState.phase_history.find(e => e.phase === prevPhase);
210
- const prevName = PHASE_NAMES[prevPhase] || `Phase ${prevPhase}`;
211
- // 'completed' and 'skipped' are both valid predecessor statuses
212
- if (!prevEntry || (prevEntry.status !== 'completed' && prevEntry.status !== 'skipped')) {
213
- console.warn(
214
- `⚠️ [sprint-audit] Phase ${prevPhase} (${prevName}) not recorded as 'completed'`
215
- );
216
- console.warn(
217
- ` Previous phase may have been skipped. Run: xp-gate phase-transition ${prevPhase} completed`
218
- );
219
- }
220
- }
221
- // If no sprint-state.json exists yet, skip check (no previous phase to validate)
222
- }
223
-
224
- const newState = manager.transitionPhase(phase, status, { outputs });
225
-
226
- console.log(`✅ Phase ${phase} transitioned to '${status}'`);
227
-
228
- // ── Layer 1.5: Auto-trigger Layer 2 reminder on Phase 6 completed ──
229
- if (phase === 6 && status === 'completed') {
230
- console.log('');
231
- console.log('📋 [sprint-audit] Sprint complete — run final coverage audit:');
232
- console.log(' npx xp-gate sprint-audit');
233
- }
234
-
235
- // Auto-render dashboard if --render flag is set
236
- if (renderFlag) {
237
- console.log('');
238
- const dashboard = renderDashboard(newState);
239
- console.log(dashboard);
240
- }
241
-
242
- return 0;
243
- } catch (err) {
244
- console.error(`Error: Phase transition failed: ${err.message}`);
245
- return 1;
246
- }
247
- }
248
-
249
- module.exports = { handlePhaseTransition, renderDashboard, PHASE_NAMES };
1
+ /**
2
+ * xp-gate phase-transition — Programmatic sprint phase transition
3
+ *
4
+ * Resolves #338 (dashboard never auto-renders) and #146 (sprint-state enforcement).
5
+ *
6
+ * This CLI command is the programmatic entry point for sprint phase transitions.
7
+ * The sprint-flow SKILL.md MUST instruct the orchestrator to call this command
8
+ * after each phase completion, replacing text-level MUST instructions with
9
+ * a concrete CLI invocation.
10
+ *
11
+ * Usage:
12
+ * xp-gate phase-transition <phase> <status> [--outputs <json>] [--render]
13
+ *
14
+ * Examples:
15
+ * xp-gate phase-transition 1 completed
16
+ * xp-gate phase-transition 2 in_progress
17
+ * xp-gate phase-transition 3 completed --outputs '{"spec":"path/to/spec.yaml"}'
18
+ * xp-gate phase-transition 3 completed --render (auto-render dashboard)
19
+ *
20
+ * @module phase-transition
21
+ */
22
+
23
+ 'use strict';
24
+
25
+ const path = require('path');
26
+ const fs = require('fs');
27
+ const crypto = require('crypto');
28
+ const { execSync } = require('child_process');
29
+ const { SprintStateManager } = require('./sprint-state-manager');
30
+
31
+ /**
32
+ * Shared phase name lookup — single source of truth.
33
+ * Used by renderDashboard, sprint-audit, and Layer 1 gate check.
34
+ */
35
+ const PHASE_NAMES = {
36
+ 1: 'PREP', 2: 'DESIGN', 3: 'BUILD',
37
+ 4: 'VERIFY', 5: 'SHIP', 6: 'CLOSE',
38
+ };
39
+
40
+ /**
41
+ * Phase-specific evidence file requirements.
42
+ * Each entry defines the evidence file path, required fields, and a blocking check.
43
+ * Phases NOT in this map require no evidence validation in v0.17.1.
44
+ */
45
+ const EVIDENCE_FILES = {
46
+ 2: {
47
+ path: '.sprint-state/phase-outputs/requirements-reviewed.json',
48
+ requiredFields: ['verdict', 'requirements_hash'],
49
+ blockingCheck: (data) => data.verdict === 'APPROVED',
50
+ blockingMessage: 'Requirements review verdict is not APPROVED',
51
+ },
52
+ 4: {
53
+ path: '.sprint-state/phase-outputs/test-alignment-report.json',
54
+ requiredFields: ['alignment_status', 'head_commit', 'spec_hash'],
55
+ blockingCheck: (data) => data.alignment_status === 'PASS',
56
+ blockingMessage: 'Test alignment status is not PASS',
57
+ },
58
+ };
59
+
60
+ /**
61
+ * Get current HEAD commit hash from a project directory.
62
+ * Returns 'unknown' if not in a git repo.
63
+ * @param {string} projectDir
64
+ * @returns {string}
65
+ */
66
+ function getCurrentHeadCommit(projectDir) {
67
+ try {
68
+ return execSync('git rev-parse HEAD', {
69
+ cwd: projectDir,
70
+ encoding: 'utf8',
71
+ stdio: ['pipe', 'pipe', 'pipe'],
72
+ }).trim();
73
+ } catch {
74
+ return 'unknown';
75
+ }
76
+ }
77
+
78
+ /**
79
+ * Compute SHA-256 hash of a file's contents.
80
+ * @param {string} filePath
81
+ * @returns {string} hex digest
82
+ */
83
+ function computeFileHash(filePath) {
84
+ const content = fs.readFileSync(filePath, 'utf8');
85
+ return crypto.createHash('sha256').update(content, 'utf8').digest('hex');
86
+ }
87
+
88
+ /**
89
+ * Validate phase evidence files for a given phase transition.
90
+ *
91
+ * Returns { ok: boolean, errors: string[], warnings: string[] }.
92
+ * - For phases not in EVIDENCE_FILES: ok=true, no errors.
93
+ * - For phases with evidence requirements:
94
+ * - If evidence_schema_version >= 2 (new sprint): missing/invalid evidence → ok=false (BLOCK)
95
+ * - If evidence_schema_version missing or < 2 (legacy sprint): missing/invalid → ok=true with WARNING
96
+ *
97
+ * @param {number} phase - Phase number (1-6)
98
+ * @param {string} projectDir - Project root directory
99
+ * @returns {{ ok: boolean, errors: string[], warnings: string[] }}
100
+ */
101
+ function validateEvidence(phase, projectDir) {
102
+ const evidenceConfig = EVIDENCE_FILES[phase];
103
+ if (!evidenceConfig) {
104
+ return { ok: true, errors: [], warnings: [] };
105
+ }
106
+
107
+ // Read sprint state to determine evidence_schema_version
108
+ let evidenceSchemaVersion = 0;
109
+ try {
110
+ const manager = new SprintStateManager(projectDir);
111
+ const state = manager.read();
112
+ if (state && typeof state.evidence_schema_version === 'number') {
113
+ evidenceSchemaVersion = state.evidence_schema_version;
114
+ }
115
+ } catch {
116
+ // If state can't be read, treat as legacy (version 0)
117
+ }
118
+
119
+ const isLegacySprint = evidenceSchemaVersion < 2;
120
+ const errors = [];
121
+ const warnings = [];
122
+
123
+ const evidenceFilePath = path.join(projectDir, evidenceConfig.path);
124
+ const fileName = path.basename(evidenceConfig.path);
125
+
126
+ // Check file existence
127
+ if (!fs.existsSync(evidenceFilePath)) {
128
+ const msg = `Evidence file missing: ${evidenceConfig.path}`;
129
+ if (isLegacySprint) {
130
+ warnings.push(`WARNING: ${msg}. Upgrade sprint with evidence_schema_version >= 2 to enforce.`);
131
+ return { ok: true, errors: [], warnings };
132
+ }
133
+ errors.push(msg);
134
+ return { ok: false, errors, warnings };
135
+ }
136
+
137
+ // Parse JSON
138
+ let data;
139
+ try {
140
+ const raw = fs.readFileSync(evidenceFilePath, 'utf8');
141
+ data = JSON.parse(raw);
142
+ } catch {
143
+ const msg = `${fileName} is malformed JSON`;
144
+ if (isLegacySprint) {
145
+ warnings.push(`WARNING: ${msg}. Upgrade sprint with evidence_schema_version >= 2 to enforce.`);
146
+ return { ok: true, errors: [], warnings };
147
+ }
148
+ errors.push(msg);
149
+ return { ok: false, errors, warnings };
150
+ }
151
+
152
+ // Check required fields
153
+ for (const field of evidenceConfig.requiredFields) {
154
+ if (!(field in data)) {
155
+ const msg = `${fileName} is missing required field: ${field}`;
156
+ if (isLegacySprint) {
157
+ warnings.push(`WARNING: ${msg}. Upgrade sprint with evidence_schema_version >= 2 to enforce.`);
158
+ } else {
159
+ errors.push(msg);
160
+ }
161
+ }
162
+ }
163
+
164
+ // If any required fields missing for new sprint, block early
165
+ if (errors.length > 0) {
166
+ return { ok: false, errors, warnings };
167
+ }
168
+
169
+ // Run blocking check
170
+ if (!evidenceConfig.blockingCheck(data)) {
171
+ const msg = `${fileName}: ${evidenceConfig.blockingMessage} (got: ${JSON.stringify(data[evidenceConfig.requiredFields[0]])})`;
172
+ if (isLegacySprint) {
173
+ warnings.push(`WARNING: ${msg}. Upgrade sprint with evidence_schema_version >= 2 to enforce.`);
174
+ return { ok: true, errors: [], warnings };
175
+ }
176
+ errors.push(msg);
177
+ return { ok: false, errors, warnings };
178
+ }
179
+
180
+ // Phase-specific anti-staleness checks
181
+ if (phase === 4) {
182
+ // head_commit check
183
+ const currentHead = getCurrentHeadCommit(projectDir);
184
+ if (data.head_commit !== currentHead) {
185
+ const msg = `${fileName}: head_commit mismatch — report has "${data.head_commit}", current HEAD is "${currentHead}"`;
186
+ if (isLegacySprint) {
187
+ warnings.push(`WARNING: ${msg}. Upgrade sprint with evidence_schema_version >= 2 to enforce.`);
188
+ } else {
189
+ errors.push(msg);
190
+ }
191
+ }
192
+
193
+ // spec_hash check (only if specification.yaml exists)
194
+ const specPath = path.join(projectDir, 'specification.yaml');
195
+ if (fs.existsSync(specPath)) {
196
+ const expectedHash = computeFileHash(specPath);
197
+ if (data.spec_hash !== expectedHash) {
198
+ const msg = `${fileName}: spec_hash mismatch — specification.yaml has changed since report was generated`;
199
+ if (isLegacySprint) {
200
+ warnings.push(`WARNING: ${msg}. Upgrade sprint with evidence_schema_version >= 2 to enforce.`);
201
+ } else {
202
+ errors.push(msg);
203
+ }
204
+ }
205
+ }
206
+ }
207
+
208
+ // Phase 2: requirements_hash existence check (full verification in v0.18.0)
209
+ if (phase === 2) {
210
+ if (typeof data.requirements_hash !== 'string' || data.requirements_hash.length === 0) {
211
+ const msg = `${fileName}: requirements_hash must be a non-empty string`;
212
+ if (isLegacySprint) {
213
+ warnings.push(`WARNING: ${msg}. Upgrade sprint with evidence_schema_version >= 2 to enforce.`);
214
+ } else {
215
+ errors.push(msg);
216
+ }
217
+ }
218
+ }
219
+
220
+ if (errors.length > 0) {
221
+ return { ok: false, errors, warnings };
222
+ }
223
+
224
+ return { ok: true, errors: [], warnings };
225
+ }
226
+
227
+ /**
228
+ * Append an evidence-skipped audit entry to .xp-gate/audit.jsonl.
229
+ * @param {string} projectDir
230
+ * @param {number} phase
231
+ * @param {string} reason
232
+ */
233
+ function logEvidenceSkip(projectDir, phase, reason) {
234
+ const auditDir = path.join(projectDir, '.xp-gate');
235
+ if (!fs.existsSync(auditDir)) {
236
+ fs.mkdirSync(auditDir, { recursive: true });
237
+ }
238
+ const entry = {
239
+ timestamp: new Date().toISOString(),
240
+ event: 'evidence_skipped',
241
+ phase,
242
+ reason,
243
+ commit_hash: getCurrentHeadCommit(projectDir),
244
+ };
245
+ fs.appendFileSync(path.join(auditDir, 'audit.jsonl'), JSON.stringify(entry) + '\n', 'utf8');
246
+ }
247
+
248
+ /**
249
+ * Render ASCII dashboard from sprint state.
250
+ * Reuses the formatSprintTable logic from sprint-status.
251
+ * @param {object} state - Sprint state object
252
+ * @returns {string} Rendered dashboard
253
+ */
254
+ function renderDashboard(state) {
255
+ if (!state) return 'No sprint state found';
256
+
257
+ const PHASE_NAMES_LOCAL = PHASE_NAMES;
258
+
259
+ function statusIcon(status) {
260
+ switch (status) {
261
+ case 'completed': return '✅';
262
+ case 'in_progress': return '🔄';
263
+ case 'skipped': return '⏭️';
264
+ case 'failed': return '❌';
265
+ case 'paused': return '⏸️';
266
+ default: return '⏳';
267
+ }
268
+ }
269
+
270
+ function formatDuration(seconds) {
271
+ if (seconds == null || seconds === 0) return '-';
272
+ if (seconds < 60) return `${seconds}s`;
273
+ const mins = Math.floor(seconds / 60);
274
+ if (mins < 60) return `${mins}m`;
275
+ const hrs = Math.floor(mins / 60);
276
+ if (hrs < 24) return `${hrs}h ${mins % 60}m`;
277
+ return `${Math.floor(hrs / 24)}d ${hrs % 24}h`;
278
+ }
279
+
280
+ const branch = state.isolation?.branch || 'unknown';
281
+ const sprintId = state.id || 'unknown';
282
+ const taskDesc = state.task_description || state.issue_title || '-';
283
+ const overallStatus = state.status || 'running';
284
+ const startedAt = state.started_at ? state.started_at.slice(0, 16).replace('T', ' ') : '-';
285
+
286
+ // Build phase history lookup
287
+ const historyLookup = {};
288
+ if (Array.isArray(state.phase_history)) {
289
+ for (const ph of state.phase_history) {
290
+ historyLookup[String(ph.phase)] = ph;
291
+ }
292
+ }
293
+
294
+ const currentPhase = state.phase || 1;
295
+ const currentPhaseName = PHASE_NAMES_LOCAL[String(currentPhase)] || `Phase ${currentPhase}`;
296
+
297
+ // Progress bar
298
+ const completedCount = Object.values(historyLookup).filter(h => h.status === 'completed').length;
299
+ const pct = Math.round((completedCount / 6) * 100);
300
+ const filled = '█'.repeat(completedCount);
301
+ const current = currentPhase <= 6 ? '▓' : '';
302
+ const empty = '░'.repeat(Math.max(0, 6 - completedCount - (current ? 1 : 0)));
303
+ const progressBar = `[${filled}${current}${empty}] ${pct}%`;
304
+
305
+ // Build lines
306
+ const lines = [];
307
+ lines.push('+============================================================+');
308
+ lines.push(`| SPRINT PROGRESS ${sprintId.padEnd(20)}|`);
309
+ lines.push('+============================================================+');
310
+ lines.push(`| 需求: ${(taskDesc).slice(0, 54).padEnd(54)}|`);
311
+ lines.push(`| 分支: ${(branch).slice(0, 54).padEnd(54)}|`);
312
+ lines.push(`| 状态: ${(overallStatus).slice(0, 15).padEnd(15)} 启动: ${startedAt.slice(0, 19).padEnd(19)}|`);
313
+ lines.push('+============================================================+');
314
+ lines.push('| |');
315
+
316
+ for (let i = 1; i <= 6; i++) {
317
+ const entry = historyLookup[String(i)];
318
+ const icon = statusIcon(entry?.status || (i < currentPhase ? 'completed' : i === currentPhase ? 'in_progress' : 'pending'));
319
+ const name = (PHASE_NAMES_LOCAL[String(i)] || `Phase ${i}`).padEnd(10);
320
+ const dur = formatDuration(entry?.duration_seconds).padEnd(8);
321
+ lines.push(`| ${icon} Phase ${i}/6 ${name} ${dur} |`);
322
+ }
323
+
324
+ lines.push('| |');
325
+ lines.push(`| ${progressBar.padEnd(58)}|`);
326
+ lines.push('+============================================================+');
327
+ lines.push(`| > 当前: Phase ${currentPhase}/6 ${currentPhaseName}`.padEnd(59) + '|');
328
+ lines.push(`| 状态: ${(entry_status(currentPhase, historyLookup)).padEnd(50)}|`);
329
+ lines.push('+============================================================+');
330
+
331
+ // Outputs section
332
+ if (state.outputs && Object.keys(state.outputs).length > 0) {
333
+ lines.push('| 输出物: |');
334
+ for (const [key, val] of Object.entries(state.outputs)) {
335
+ lines.push(`| ${(`${key}: ${val}`).slice(0, 55).padEnd(55)}|`);
336
+ }
337
+ lines.push('+============================================================+');
338
+ }
339
+
340
+ return lines.join('\n');
341
+
342
+ function entry_status(phaseNum, lookup) {
343
+ const e = lookup[String(phaseNum)];
344
+ return e?.status || (phaseNum < currentPhase ? 'completed' : phaseNum === currentPhase ? 'in_progress' : 'pending');
345
+ }
346
+ }
347
+
348
+ /**
349
+ * CLI entry point for phase-transition command.
350
+ * @param {string[]} args - CLI arguments
351
+ * @returns {Promise<number>} Exit code
352
+ */
353
+ async function handlePhaseTransition(args = []) {
354
+ if (args.includes('--help')) {
355
+ console.log('Usage: xp-gate phase-transition <phase> <status> [options]');
356
+ console.log('');
357
+ console.log('Arguments:');
358
+ console.log(' phase Phase number (1-6)');
359
+ console.log(' status Status: in_progress | completed | skipped | failed | paused');
360
+ console.log('');
361
+ console.log('Options:');
362
+ console.log(' --outputs <json> JSON object of outputs to record');
363
+ console.log(' --render Render ASCII dashboard after transition');
364
+ console.log(' --dir <path> Project directory (default: cwd)');
365
+ console.log(' --skip-evidence <reason> Skip evidence validation (requires reason)');
366
+ console.log('');
367
+ console.log('Examples:');
368
+ console.log(' xp-gate phase-transition 1 completed');
369
+ console.log(' xp-gate phase-transition 3 completed --render');
370
+ console.log(' xp-gate phase-transition 2 in_progress --outputs \'{"spec":"path.yaml"}\'');
371
+ console.log(' xp-gate phase-transition 4 completed --skip-evidence "Emergency hotfix"');
372
+ return 0;
373
+ }
374
+
375
+ if (args.length < 2) {
376
+ console.error('Error: Missing required arguments. Usage: xp-gate phase-transition <phase> <status>');
377
+ return 1;
378
+ }
379
+
380
+ const phase = parseInt(args[0], 10);
381
+ const status = args[1];
382
+ const renderFlag = args.includes('--render');
383
+ const dirIdx = args.indexOf('--dir');
384
+ const projectDir = dirIdx >= 0 ? args[dirIdx + 1] : process.cwd();
385
+
386
+ const outputsIdx = args.indexOf('--outputs');
387
+ let outputs = {};
388
+ if (outputsIdx >= 0 && args[outputsIdx + 1]) {
389
+ try {
390
+ outputs = JSON.parse(args[outputsIdx + 1]);
391
+ } catch (err) {
392
+ console.error(`Error: Invalid JSON for --outputs: ${err.message}`);
393
+ return 1;
394
+ }
395
+ }
396
+
397
+ // Parse --skip-evidence flag
398
+ const skipEvidenceIdx = args.indexOf('--skip-evidence');
399
+ let skipEvidence = false;
400
+ let skipEvidenceReason = '';
401
+ if (skipEvidenceIdx >= 0) {
402
+ skipEvidence = true;
403
+ const nextArg = args[skipEvidenceIdx + 1];
404
+ // Reason is the next arg if it exists and doesn't start with '--'
405
+ if (nextArg && !nextArg.startsWith('--')) {
406
+ skipEvidenceReason = nextArg;
407
+ }
408
+ }
409
+
410
+ // Validate inputs
411
+ if (phase < 1 || phase > 6) {
412
+ console.error(`Error: Phase must be 1-6, got ${phase}`);
413
+ return 1;
414
+ }
415
+
416
+ const validStatuses = ['in_progress', 'completed', 'skipped', 'failed', 'paused'];
417
+ if (!validStatuses.includes(status)) {
418
+ console.error(`Error: Status must be one of: ${validStatuses.join(', ')}`);
419
+ return 1;
420
+ }
421
+
422
+ // Execute transition
423
+ try {
424
+ const manager = new SprintStateManager(projectDir);
425
+
426
+ // ── Layer 1: Pre-transition gate check ──
427
+ // Check BEFORE transitionPhase() to validate previous phase completion.
428
+ // Runs when status === 'in_progress' and phase >= 2.
429
+ // No side effects — only outputs WARNING, does not modify state.
430
+ if (status === 'in_progress' && phase >= 2) {
431
+ const preState = manager.read();
432
+ if (preState && Array.isArray(preState.phase_history)) {
433
+ const prevPhase = phase - 1;
434
+ const prevEntry = preState.phase_history.find(e => e.phase === prevPhase);
435
+ const prevName = PHASE_NAMES[prevPhase] || `Phase ${prevPhase}`;
436
+ // 'completed' and 'skipped' are both valid predecessor statuses
437
+ if (!prevEntry || (prevEntry.status !== 'completed' && prevEntry.status !== 'skipped')) {
438
+ console.warn(
439
+ `⚠️ [sprint-audit] Phase ${prevPhase} (${prevName}) not recorded as 'completed'`
440
+ );
441
+ console.warn(
442
+ ` Previous phase may have been skipped. Run: xp-gate phase-transition ${prevPhase} completed`
443
+ );
444
+ }
445
+ }
446
+ // If no sprint-state.json exists yet, skip check (no previous phase to validate)
447
+ }
448
+
449
+ // ── Layer 2: Evidence validation (blocks on status === 'completed') ──
450
+ if (status === 'completed' && EVIDENCE_FILES[phase]) {
451
+ if (skipEvidence) {
452
+ if (!skipEvidenceReason) {
453
+ console.error('Error: --skip-evidence requires --reason "<text>" to be provided');
454
+ return 1;
455
+ }
456
+ logEvidenceSkip(projectDir, phase, skipEvidenceReason);
457
+ console.warn('⚠️ Evidence skipped. This will appear in retro reports. Single-sprint limit: >2 skips per sprint will trigger an alert.');
458
+ } else {
459
+ const evidence = validateEvidence(phase, projectDir);
460
+ for (const w of evidence.warnings) {
461
+ console.warn(`⚠️ [sprint-audit] ${w}`);
462
+ }
463
+ if (!evidence.ok) {
464
+ for (const e of evidence.errors) {
465
+ console.error(`❌ [sprint-audit] ${e}`);
466
+ }
467
+ console.error(` Phase ${phase} (${PHASE_NAMES[phase]}) cannot transition to 'completed' without valid evidence.`);
468
+ console.error(` Use --skip-evidence "<reason>" to bypass (audited).`);
469
+ return 1;
470
+ }
471
+ }
472
+ }
473
+
474
+ const newState = manager.transitionPhase(phase, status, { outputs });
475
+
476
+ console.log(`✅ Phase ${phase} transitioned to '${status}'`);
477
+
478
+ // ── Layer 1.5: Auto-trigger Layer 2 reminder on Phase 6 completed ──
479
+ if (phase === 6 && status === 'completed') {
480
+ console.log('');
481
+ console.log('📋 [sprint-audit] Sprint complete — run final coverage audit:');
482
+ console.log(' npx xp-gate sprint-audit');
483
+ }
484
+
485
+ // Auto-render dashboard if --render flag is set
486
+ if (renderFlag) {
487
+ console.log('');
488
+ const dashboard = renderDashboard(newState);
489
+ console.log(dashboard);
490
+ }
491
+
492
+ return 0;
493
+ } catch (err) {
494
+ console.error(`Error: Phase transition failed: ${err.message}`);
495
+ return 1;
496
+ }
497
+ }
498
+
499
+ module.exports = { handlePhaseTransition, renderDashboard, PHASE_NAMES, validateEvidence };