mandrel 2.86.0 → 2.88.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/.agents/README.md +29 -0
  2. package/.agents/agents/auditor.md +4 -3
  3. package/.agents/docs/agentrc-reference.json +2 -1
  4. package/.agents/docs/configuration.md +44 -20
  5. package/.agents/docs/workflows.md +1 -1
  6. package/.agents/schemas/agentrc.schema.json +18 -12
  7. package/.agents/schemas/story-deliver-terminal.schema.json +1 -1
  8. package/.agents/schemas/story-progress.schema.json +5 -0
  9. package/.agents/scripts/audit-to-stories.js +3 -2
  10. package/.agents/scripts/boot-sweep.js +3 -2
  11. package/.agents/scripts/check-arch-cycles.js +19 -41
  12. package/.agents/scripts/check-context-budget.js +16 -44
  13. package/.agents/scripts/check-cyclomatic.js +13 -37
  14. package/.agents/scripts/check-dead-exports.js +16 -46
  15. package/.agents/scripts/clean-worktrees.js +1 -6
  16. package/.agents/scripts/coverage-capture.js +23 -3
  17. package/.agents/scripts/deliver-run.js +11 -0
  18. package/.agents/scripts/diagnose-friction.js +3 -3
  19. package/.agents/scripts/lib/baselines/bundle-size-scorer.js +115 -0
  20. package/.agents/scripts/lib/baselines/coverage-updater-cli.js +122 -29
  21. package/.agents/scripts/lib/baselines/crap-updater-cli.js +45 -14
  22. package/.agents/scripts/lib/baselines/duplication-scanner.js +45 -2
  23. package/.agents/scripts/lib/baselines/env-overrides.js +39 -34
  24. package/.agents/scripts/lib/baselines/kernel.js +3 -2
  25. package/.agents/scripts/lib/baselines/kinds/crap.js +14 -38
  26. package/.agents/scripts/lib/baselines/preview-gates.js +4 -1
  27. package/.agents/scripts/lib/baselines/refresh-service.js +101 -22
  28. package/.agents/scripts/lib/baselines/writer.js +5 -1
  29. package/.agents/scripts/lib/bdd-runner-detect.js +7 -10
  30. package/.agents/scripts/lib/child-exec.js +14 -1
  31. package/.agents/scripts/lib/child-stream.js +122 -0
  32. package/.agents/scripts/lib/clean-temp.js +19 -13
  33. package/.agents/scripts/lib/cli-args.js +49 -0
  34. package/.agents/scripts/lib/codex/skills-projection.js +1 -12
  35. package/.agents/scripts/lib/config/gates/coverage.schema.js +1 -1
  36. package/.agents/scripts/lib/config/gates/mutation.schema.js +2 -2
  37. package/.agents/scripts/lib/config/gates/shared.js +1 -1
  38. package/.agents/scripts/lib/config/gh-config-dir.js +63 -0
  39. package/.agents/scripts/lib/config/github.js +2 -0
  40. package/.agents/scripts/lib/config/paths.js +14 -3
  41. package/.agents/scripts/lib/config/quality.js +6 -2
  42. package/.agents/scripts/lib/config-resolver.js +78 -64
  43. package/.agents/scripts/lib/config-settings-schema-delivery.js +4 -3
  44. package/.agents/scripts/lib/config-settings-schema.js +7 -0
  45. package/.agents/scripts/lib/coverage-baseline.js +7 -6
  46. package/.agents/scripts/lib/coverage-capture.js +59 -0
  47. package/.agents/scripts/lib/crap-utils.js +59 -47
  48. package/.agents/scripts/lib/full-suite-lock.js +1 -10
  49. package/.agents/scripts/lib/gates/baseline-store.js +10 -0
  50. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  51. package/.agents/scripts/lib/gh-exec.js +45 -2
  52. package/.agents/scripts/lib/gh-transport.js +27 -0
  53. package/.agents/scripts/lib/git-utils.js +16 -9
  54. package/.agents/scripts/lib/maintainability-engine.js +27 -6
  55. package/.agents/scripts/lib/maintainability-utils.js +14 -1
  56. package/.agents/scripts/lib/observability/source-classifier.js +1 -0
  57. package/.agents/scripts/lib/orchestration/check-baselines/phases/evaluate.js +33 -3
  58. package/.agents/scripts/lib/orchestration/evidence-stream.js +186 -0
  59. package/.agents/scripts/lib/orchestration/file-assumptions.js +2 -19
  60. package/.agents/scripts/lib/orchestration/git-cleanup/phases/branches-reap.js +3 -7
  61. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes-ff.js +34 -40
  62. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes.js +4 -3
  63. package/.agents/scripts/lib/orchestration/plan-persist/persist-helpers.js +2 -19
  64. package/.agents/scripts/lib/orchestration/pr-watch.js +1 -5
  65. package/.agents/scripts/lib/orchestration/project-meta-cache.js +17 -4
  66. package/.agents/scripts/lib/orchestration/reassert-status-column.js +1 -8
  67. package/.agents/scripts/lib/orchestration/resolve-stories.js +1 -0
  68. package/.agents/scripts/lib/orchestration/review-providers/native.js +2 -2
  69. package/.agents/scripts/lib/orchestration/single-story-close/phase-timer.js +43 -0
  70. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +37 -13
  71. package/.agents/scripts/lib/orchestration/single-story-close/phases/finish.js +264 -0
  72. package/.agents/scripts/lib/orchestration/single-story-close/phases/open-pr.js +68 -0
  73. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +106 -0
  74. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +43 -35
  75. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-halt.js +52 -0
  76. package/.agents/scripts/lib/orchestration/single-story-close/result.js +273 -0
  77. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +68 -776
  78. package/.agents/scripts/lib/orchestration/story-close/context-budget-writeback.js +20 -9
  79. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +2 -2
  80. package/.agents/scripts/lib/orchestration/story-close/ratchet-shrink-writeback.js +20 -12
  81. package/.agents/scripts/lib/orchestration/story-handoff.js +50 -21
  82. package/.agents/scripts/lib/orchestration/story-progress.js +32 -12
  83. package/.agents/scripts/lib/orchestration/ticket-validator.js +3 -13
  84. package/.agents/scripts/lib/qa/resolve-selection.js +1 -8
  85. package/.agents/scripts/lib/single-story/confirm-and-land.js +33 -0
  86. package/.agents/scripts/lib/single-story-sweep/reconcile-closing.js +43 -11
  87. package/.agents/scripts/lib/single-story-sweep/sweep-lock.js +130 -30
  88. package/.agents/scripts/lib/skills/parse-skill.js +1 -4
  89. package/.agents/scripts/lib/story-body/story-body.js +12 -1
  90. package/.agents/scripts/lib/suite-admission.js +3 -11
  91. package/.agents/scripts/lib/temp-retention.js +25 -11
  92. package/.agents/scripts/lib/test-run-credit.js +2 -5
  93. package/.agents/scripts/lib/transpile.js +193 -31
  94. package/.agents/scripts/lib/util/paths.js +31 -0
  95. package/.agents/scripts/lib/util/sleep.js +15 -0
  96. package/.agents/scripts/lib/validation-evidence.js +29 -3
  97. package/.agents/scripts/lib/wave-runner/live-probe.js +24 -0
  98. package/.agents/scripts/lib/workers/crap-worker.js +23 -12
  99. package/.agents/scripts/lib/workers/maintainability-report-worker.js +18 -12
  100. package/.agents/scripts/lib/workflow-closure.js +1 -8
  101. package/.agents/scripts/notify.js +83 -90
  102. package/.agents/scripts/plan-context.js +8 -4
  103. package/.agents/scripts/providers/github/auth.js +14 -30
  104. package/.agents/scripts/providers/github/blocked-by-add.js +11 -27
  105. package/.agents/scripts/providers/github/compose.js +1 -0
  106. package/.agents/scripts/providers/github/gh-token-diagnostics.js +130 -0
  107. package/.agents/scripts/providers/github/identity.js +158 -0
  108. package/.agents/scripts/providers/github/issues.js +2 -2
  109. package/.agents/scripts/providers/github/mappers.js +16 -19
  110. package/.agents/scripts/providers/github/projects-v2-graphql.js +4 -36
  111. package/.agents/scripts/providers/github/request-helpers.js +44 -0
  112. package/.agents/scripts/providers/github/sub-issue-add.js +11 -28
  113. package/.agents/scripts/providers/github.js +10 -2
  114. package/.agents/scripts/quality-preview.js +6 -19
  115. package/.agents/scripts/single-story-confirm-merge.js +8 -20
  116. package/.agents/scripts/single-story-init.js +0 -1
  117. package/.agents/scripts/stories-wave-tick.js +60 -46
  118. package/.agents/scripts/story-handoff.js +2 -23
  119. package/.agents/scripts/story-review-compute.js +3 -22
  120. package/.agents/scripts/sync-claude-agents.js +1 -12
  121. package/.agents/scripts/sync-claude-commands.js +1 -12
  122. package/.agents/scripts/update-bundle-size-baseline.js +56 -0
  123. package/.agents/scripts/update-coverage-baseline.js +16 -41
  124. package/.agents/scripts/update-crap-baseline.js +10 -19
  125. package/.agents/scripts/update-duplication-baseline.js +13 -3
  126. package/.agents/scripts/update-ticket-state.js +44 -45
  127. package/.agents/templates/docs/audit-sweep-runbook.md +1 -1
  128. package/.agents/workflows/audit-accessibility.md +1 -1
  129. package/.agents/workflows/audit-adrs.md +1 -1
  130. package/.agents/workflows/audit-architecture.md +1 -1
  131. package/.agents/workflows/audit-baselines.md +2 -2
  132. package/.agents/workflows/audit-clean-code.md +1 -1
  133. package/.agents/workflows/audit-data-model.md +1 -1
  134. package/.agents/workflows/audit-dependencies.md +1 -1
  135. package/.agents/workflows/audit-devops.md +1 -1
  136. package/.agents/workflows/audit-documentation.md +1 -1
  137. package/.agents/workflows/audit-exceptions.md +2 -2
  138. package/.agents/workflows/audit-mobile.md +1 -1
  139. package/.agents/workflows/audit-navigability.md +1 -1
  140. package/.agents/workflows/audit-performance.md +1 -1
  141. package/.agents/workflows/audit-privacy.md +1 -1
  142. package/.agents/workflows/audit-quality.md +1 -1
  143. package/.agents/workflows/audit-security.md +1 -1
  144. package/.agents/workflows/audit-seo.md +1 -1
  145. package/.agents/workflows/audit-sre.md +1 -1
  146. package/.agents/workflows/audit-to-stories.md +9 -7
  147. package/.agents/workflows/audit-ux-ui.md +1 -1
  148. package/.agents/workflows/helpers/audit-lens-core.md +8 -5
  149. package/.agents/workflows/helpers/deliver-digest.md +4 -5
  150. package/.agents/workflows/helpers/deliver-story-reference.md +4 -4
  151. package/.agents/workflows/mandrel-deliver.md +3 -1
  152. package/README.md +6 -3
  153. package/docs/CHANGELOG.md +36 -0
  154. package/lib/cli/doctor-checks/codex.js +240 -0
  155. package/lib/cli/doctor-checks/merge-driver.js +79 -0
  156. package/lib/cli/doctor-checks/payload.js +201 -0
  157. package/lib/cli/doctor-checks/read-json.js +16 -0
  158. package/lib/cli/doctor-checks/runtime-deps.js +146 -0
  159. package/lib/cli/doctor-checks/spawn.js +18 -0
  160. package/lib/cli/doctor-checks/sync-parity.js +205 -0
  161. package/lib/cli/doctor-checks/test-credit-path.js +270 -0
  162. package/lib/cli/doctor-checks/toolchain.js +137 -0
  163. package/lib/cli/doctor-checks/version-current.js +82 -0
  164. package/lib/cli/registry.js +40 -1330
  165. package/package.json +7 -1
@@ -0,0 +1,264 @@
1
+ import { Logger } from '../../../Logger.js';
2
+ import {
3
+ buildTerminalEnvelope,
4
+ NEXT_COMMANDS,
5
+ terminalFromWaitOutcome,
6
+ } from '../../story-deliver-terminal.js';
7
+ import {
8
+ closeResult,
9
+ deriveObservedMerge,
10
+ elapsedSecondsSince,
11
+ emitTerminal,
12
+ } from '../result.js';
13
+ import { closeArmedPr, runAutoMergePhase } from './auto-merge.js';
14
+ import { lockWaitPending } from './lock-wait-pending.js';
15
+ import { runPostLandTail } from './post-land.js';
16
+
17
+ const progress = Logger.createProgress('single-story-close', { stderr: true });
18
+
19
+ /**
20
+ * An already-merged PR skips the arm (`gh pr merge` would fail and block it).
21
+ *
22
+ * @param {object} args
23
+ * @returns {Promise<{ autoMergeEnabled: boolean, autoMergeReason: string|null,
24
+ * localCleanupDeferred: boolean, directMerged: boolean }>}
25
+ */
26
+ export async function resolveAutoMergeOutcome({ alreadyMerged, ...phaseArgs }) {
27
+ if (alreadyMerged) {
28
+ return {
29
+ autoMergeEnabled: true,
30
+ autoMergeReason: null,
31
+ localCleanupDeferred: false,
32
+ directMerged: false,
33
+ advisoryGate: null,
34
+ };
35
+ }
36
+ return await runAutoMergePhase(phaseArgs);
37
+ }
38
+
39
+ /** One console line per non-landed wait ending, keyed by status. */
40
+ const WAIT_TERMINAL_LINES = Object.freeze({
41
+ pending: (terminal, { storyId, prUrl }) => [
42
+ 'PENDING',
43
+ `⏸ Story #${storyId}: PR ${prUrl} still in flight — resume with: ${terminal.nextCommand}`,
44
+ ],
45
+ failed: (terminal, { storyId, prUrl }) => [
46
+ 'FAILED',
47
+ `🛑 Story #${storyId}: PR ${prUrl} did not land (${terminal.phase}): ` +
48
+ `${terminal.failure?.reason}. Labels unchanged. Next: ${terminal.nextCommand}`,
49
+ ],
50
+ blocked: (terminal, { storyId, prUrl }) => [
51
+ 'BLOCKED',
52
+ `🛑 Story #${storyId}: PR ${prUrl} did not land ` +
53
+ `(blockClass=${terminal.blocked?.blockClass}). Story is at agent::blocked. ` +
54
+ `Next: ${terminal.nextCommand}`,
55
+ ],
56
+ landed: (_terminal, { storyId, prUrl }) => [
57
+ 'DONE',
58
+ `✅ Story #${storyId}: PR merged → ${prUrl}`,
59
+ ],
60
+ });
61
+
62
+ /**
63
+ * `pending` is not a failure: resumable, with its own CLI exit code.
64
+ *
65
+ * @param {{ status: string, nextCommand: string }} terminal
66
+ * @param {{ storyId: number, prUrl: string|null }} ctx
67
+ * @returns {void}
68
+ */
69
+ function reportWaitTerminal(terminal, ctx) {
70
+ const line =
71
+ WAIT_TERMINAL_LINES[terminal.status] ?? WAIT_TERMINAL_LINES.blocked;
72
+ progress(...line(terminal, ctx));
73
+ }
74
+
75
+ /**
76
+ * Reaped only by the post-land tail, and only when it actually removed the
77
+ * tree (a skipped reap reports ok with a detail).
78
+ *
79
+ * @param {object|null|undefined} tail
80
+ * @returns {boolean}
81
+ */
82
+ function tailReapedWorktree(tail) {
83
+ return tail?.worktreeReap === true && !tail?.details?.worktreeReap;
84
+ }
85
+
86
+ /**
87
+ * @param {object} prCtx
88
+ * @param {object} deps
89
+ * @returns {Promise<{ success: boolean, result: object, terminal: object }>}
90
+ */
91
+ export async function finishWithMergeWait(prCtx, deps) {
92
+ deps.setPhase('confirm-merge');
93
+ const waitOutcome = await deps.runConfirmMergePhase({
94
+ cwd: deps.cwd,
95
+ worktreePath: prCtx.worktreePath,
96
+ storyId: prCtx.storyId,
97
+ storyBranch: prCtx.storyBranch,
98
+ baseBranch: prCtx.baseBranch,
99
+ prNumber: prCtx.prNumber,
100
+ prUrl: prCtx.prUrl,
101
+ autoMergeEnabled: prCtx.autoMergeEnabled,
102
+ autoMergeReason: prCtx.autoMergeReason,
103
+ // Positive evidence for the re-arm rule: this close armed the PR.
104
+ closeArmed: closeArmedPr(prCtx),
105
+ advisoryGate: prCtx.advisoryGate,
106
+ provider: deps.provider,
107
+ config: prCtx.config,
108
+ maxWaitSeconds: deps.maxWaitSeconds,
109
+ mergeWatchMode: deps.mergeWatchMode,
110
+ rerunAdvisory: deps.rerunAdvisory,
111
+ progress,
112
+ injectedGh: deps.injectedGh,
113
+ injectedNotify: deps.injectedNotify,
114
+ runPostLandTailFn: (args) => {
115
+ deps.setPhase('post-land');
116
+ return runPostLandTail(args);
117
+ },
118
+ });
119
+ const terminal = terminalFromWaitOutcome({
120
+ waitOutcome,
121
+ storyId: prCtx.storyId,
122
+ storyBranch: prCtx.storyBranch,
123
+ baseBranch: prCtx.baseBranch,
124
+ prNumber: prCtx.prNumber,
125
+ prUrl: prCtx.prUrl,
126
+ autoMergeEnabled: prCtx.autoMergeEnabled,
127
+ autoMergeReason: prCtx.autoMergeReason,
128
+ gates: prCtx.gates,
129
+ lockWait: prCtx.lockWait,
130
+ suiteTimings: prCtx.suiteTimings,
131
+ elapsedSeconds: elapsedSecondsSince(prCtx.startedAtMs),
132
+ });
133
+ const result = closeResult({
134
+ storyId: prCtx.storyId,
135
+ storyBranch: prCtx.storyBranch,
136
+ baseBranch: prCtx.baseBranch,
137
+ prUrl: prCtx.prUrl,
138
+ prNumber: prCtx.prNumber,
139
+ autoMergeEnabled: prCtx.autoMergeEnabled,
140
+ autoMergeReason: prCtx.autoMergeReason,
141
+ worktreeReaped: tailReapedWorktree(waitOutcome.tail),
142
+ // Released by the post-land tail only; any other ending keeps the claim.
143
+ leaseReleased: waitOutcome.tail?.leaseRelease === true,
144
+ localCleanupDeferred: prCtx.localCleanupDeferred,
145
+ directMerged: prCtx.directMerged,
146
+ waitedForMerge: true,
147
+ merged: deriveObservedMerge({
148
+ waitOutcome,
149
+ directMerged: prCtx.directMerged,
150
+ }),
151
+ landCompleted: waitOutcome.confirmed === true,
152
+ });
153
+ await emitTerminal({
154
+ terminal,
155
+ result,
156
+ config: prCtx.config,
157
+ phaseTimer: prCtx.phaseTimer,
158
+ worker: prCtx.worker,
159
+ });
160
+ reportWaitTerminal(terminal, { storyId: prCtx.storyId, prUrl: prCtx.prUrl });
161
+ return { success: terminal.status === 'landed', result, terminal };
162
+ }
163
+
164
+ /**
165
+ * The no-wait ending: a human owns the land, so it is `pending` with one
166
+ * command to finish it. A direct merge by the arm is still observed.
167
+ *
168
+ * @param {object} prCtx
169
+ * @param {string} waitForMergeReason
170
+ * @returns {Promise<{ success: boolean, result: object, terminal: object }>}
171
+ */
172
+ export async function finishWithoutMergeWait(prCtx, waitForMergeReason) {
173
+ const merged = deriveObservedMerge({ directMerged: prCtx.directMerged });
174
+ const result = closeResult({
175
+ storyId: prCtx.storyId,
176
+ storyBranch: prCtx.storyBranch,
177
+ baseBranch: prCtx.baseBranch,
178
+ prUrl: prCtx.prUrl,
179
+ prNumber: prCtx.prNumber,
180
+ autoMergeEnabled: prCtx.autoMergeEnabled,
181
+ autoMergeReason: prCtx.autoMergeReason,
182
+ leaseReleased: false,
183
+ localCleanupDeferred: prCtx.localCleanupDeferred,
184
+ directMerged: prCtx.directMerged,
185
+ merged,
186
+ // The flip, issue close and tail belong to `nextCommand`.
187
+ landCompleted: false,
188
+ });
189
+ const terminal = buildTerminalEnvelope({
190
+ storyId: prCtx.storyId,
191
+ status: 'pending',
192
+ phase: 'auto-merge',
193
+ storyBranch: prCtx.storyBranch,
194
+ baseBranch: prCtx.baseBranch,
195
+ pr: {
196
+ number: prCtx.prNumber,
197
+ url: prCtx.prUrl ?? null,
198
+ state: merged ? 'MERGED' : 'OPEN',
199
+ autoMergeEnabled: Boolean(prCtx.autoMergeEnabled),
200
+ autoMergeReason: prCtx.autoMergeReason ?? null,
201
+ },
202
+ gates: prCtx.gates,
203
+ lockWait: prCtx.lockWait,
204
+ suiteTimings: prCtx.suiteTimings,
205
+ nextCommand: NEXT_COMMANDS.confirmMerge(prCtx.storyId),
206
+ elapsedSeconds: elapsedSecondsSince(prCtx.startedAtMs),
207
+ });
208
+ await emitTerminal({
209
+ terminal,
210
+ result,
211
+ config: prCtx.config,
212
+ phaseTimer: prCtx.phaseTimer,
213
+ worker: prCtx.worker,
214
+ });
215
+ progress(
216
+ 'DONE',
217
+ `✅ Story #${prCtx.storyId}: PR ready → ${prCtx.prUrl} (${waitForMergeReason})`,
218
+ );
219
+ return { success: true, result, terminal };
220
+ }
221
+
222
+ /**
223
+ * A full-suite lock wait expired: `pending`, nothing pushed.
224
+ *
225
+ * @param {{ waitedSeconds: number, expired: boolean }|null} lockWait
226
+ * @param {{ storyId: number, storyBranch: string, baseBranch: string,
227
+ * config: object, startedAtMs: number }} ctx
228
+ * @returns {Promise<{ success: false, result: object, terminal: object }>}
229
+ */
230
+ export async function finishDeferred(
231
+ lockWait,
232
+ { config, startedAtMs, phaseTimer, worker, ...ids },
233
+ ) {
234
+ const { result, terminal, note } = lockWaitPending({
235
+ ...ids,
236
+ lockWait,
237
+ elapsedSeconds: elapsedSecondsSince(startedAtMs),
238
+ });
239
+ await emitTerminal({ terminal, result, config, phaseTimer, worker });
240
+ progress('PENDING', note);
241
+ return { success: false, result, terminal };
242
+ }
243
+
244
+ /**
245
+ * @param {{ waitForMergeReason: string, autoMergeReason: string|null,
246
+ * storyId: number, waitForMergeExplicit?: boolean }} args
247
+ * @returns {void}
248
+ */
249
+ export function reportOperatorMergeSkip({
250
+ waitForMergeReason,
251
+ autoMergeReason,
252
+ storyId,
253
+ waitForMergeExplicit,
254
+ }) {
255
+ if (waitForMergeReason !== 'operator-merge') return;
256
+ progress(
257
+ 'MERGE',
258
+ `⏭ Not waiting for merge (${autoMergeReason}) — the operator owns this merge; ` +
259
+ `Story #${storyId} rests at agent::closing.` +
260
+ (waitForMergeExplicit === true
261
+ ? ' --wait-merge cannot land a PR that was deliberately left un-armed.'
262
+ : ''),
263
+ );
264
+ }
@@ -0,0 +1,68 @@
1
+ import { Logger } from '../../../Logger.js';
2
+ import { discardHeldReview, reviewAfterPrOpen } from '../review-overlap.js';
3
+ import { parsePrNumber } from './code-review.js';
4
+ import { ensurePullRequestWith } from './pull-request.js';
5
+ import { pushStoryBranch } from './push.js';
6
+ import { resolveReviewHalt } from './review-halt.js';
7
+
8
+ const progress = Logger.createProgress('single-story-close', { stderr: true });
9
+
10
+ export async function openAndReviewPr(ctx, deps) {
11
+ const { options, worktreePath, story, storyId, storyBranch, baseBranch } =
12
+ ctx;
13
+ const { cwd } = options;
14
+ ctx.setPhase('push');
15
+ // Push from the worktree so `pre-push` measures the tree being sent; the
16
+ // ref-based reads below resolve identically from the shared `.git`.
17
+ pushStoryBranch({
18
+ cwd,
19
+ worktreePath,
20
+ storyBranch,
21
+ gitSync: deps.git.gitSync,
22
+ progress,
23
+ });
24
+ ctx.setPhase('pull-request');
25
+ const { url: prUrl, alreadyMerged } = await ensurePullRequestWith({
26
+ cwd,
27
+ storyId,
28
+ storyTitle: story.title,
29
+ storyBody: story.body,
30
+ storyBranch,
31
+ baseBranch,
32
+ gh: deps.gh,
33
+ progress,
34
+ });
35
+ const prNumber = parsePrNumber(prUrl);
36
+ ctx.recordPrNumber(prNumber);
37
+ // Already merged (landed between invocations): skip review and arm; confirm observes it.
38
+ if (alreadyMerged) {
39
+ discardHeldReview(ctx.heldReview, 'PR already merged', progress);
40
+ return { prUrl, prNumber, alreadyMerged: true };
41
+ }
42
+ const reviewOutcome = await reviewAfterPrOpen({
43
+ held: ctx.heldReview,
44
+ cwd,
45
+ storyId,
46
+ storyBranch,
47
+ baseBranch,
48
+ prUrl,
49
+ prNumber,
50
+ provider: deps.provider,
51
+ runCodeReviewFn: deps.runCodeReview,
52
+ gitSpawnFn: deps.git.gitSpawn,
53
+ progress,
54
+ setPhase: ctx.setPhase,
55
+ pauseTimer: ctx.phaseTimer.pause,
56
+ recordDuration: ctx.phaseTimer.record,
57
+ });
58
+ const reviewOverride = reviewOutcome.halted
59
+ ? await resolveReviewHalt(ctx, deps, { prUrl, prNumber, reviewOutcome })
60
+ : null;
61
+ return {
62
+ prUrl,
63
+ prNumber,
64
+ alreadyMerged: false,
65
+ reviewOverride,
66
+ reviewDegraded: reviewOutcome.degraded === true,
67
+ };
68
+ }
@@ -0,0 +1,106 @@
1
+ import { Logger } from '../../../Logger.js';
2
+ import { discardHeldReview, startHeldReview } from '../review-overlap.js';
3
+ import { runBaseSyncPhase } from './base-sync.js';
4
+ import { runCloseValidationPhase } from './close-validation.js';
5
+ import { runWrongTreeGuardPhase } from './wrong-tree-guard.js';
6
+
7
+ const progress = Logger.createProgress('single-story-close', { stderr: true });
8
+
9
+ /**
10
+ * wrong-tree guard → base-sync → close-validation. Validation runs last so
11
+ * the validated tree is the pushed tree (base-sync's merge commit included),
12
+ * and a cheap conflict is found before the expensive gates.
13
+ *
14
+ * @param {object} ctx
15
+ * @param {object} deps
16
+ * @returns {Promise<{
17
+ * validationGates: Record<string, string>|null,
18
+ * lockWait: { waitedSeconds: number, expired: boolean }|null,
19
+ * suiteTimings: object|null,
20
+ * pending: boolean,
21
+ * }>} `validationGates` is null when skipped; `pending` means a full-suite
22
+ * lock wait expired and the gates deferred.
23
+ */
24
+ export async function runPrePushPhases(ctx, deps) {
25
+ const { options, worktreePath, baseBranch, storyBranch, storyId, setPhase } =
26
+ ctx;
27
+ const { cwd } = options;
28
+ setPhase('wrong-tree-guard');
29
+ await runWrongTreeGuardPhase({
30
+ cwd,
31
+ worktreePath,
32
+ baseBranch,
33
+ storyId,
34
+ provider: deps.provider,
35
+ progress,
36
+ gitSpawn: deps.gitSpawn,
37
+ });
38
+ if (!options.skipSync) {
39
+ setPhase('base-sync');
40
+ await runBaseSyncPhase({
41
+ cwd,
42
+ worktreePath,
43
+ baseBranch,
44
+ baseConfirmed: ctx.baseConfirmed,
45
+ storyBranch,
46
+ storyId,
47
+ provider: deps.provider,
48
+ injectedSync: deps.sync,
49
+ progress,
50
+ });
51
+ } else {
52
+ progress('SYNC', '⏭ Skipped (--skip-sync).');
53
+ }
54
+ if (options.skipValidation) {
55
+ progress('VALIDATE', '⏭ Skipped (--skip-validation).');
56
+ return {
57
+ validationGates: null,
58
+ lockWait: null,
59
+ suiteTimings: null,
60
+ pending: false,
61
+ };
62
+ }
63
+ setPhase('close-validation');
64
+ let validation;
65
+ try {
66
+ validation = await runCloseValidationPhase({
67
+ cwd,
68
+ worktreePath,
69
+ config: deps.config,
70
+ baseBranch,
71
+ storyBranch,
72
+ storyId,
73
+ progress,
74
+ runCloseValidation: deps.runCloseValidation,
75
+ buildDefaultGates: deps.buildDefaultGates,
76
+ onPreGateStepsDone: () => {
77
+ ctx.heldReview = startHeldReview({
78
+ cwd,
79
+ storyId,
80
+ storyBranch,
81
+ baseBranch,
82
+ provider: deps.provider,
83
+ runCodeReviewFn: deps.runCodeReview,
84
+ gitSpawnFn: deps.git.gitSpawn,
85
+ progress,
86
+ config: deps.config,
87
+ });
88
+ },
89
+ });
90
+ } catch (err) {
91
+ discardHeldReview(ctx.heldReview, 'validation failed', progress);
92
+ // The gate that died is all this run observed; the envelope claims no more.
93
+ if (typeof err?.closeGate === 'string') {
94
+ ctx.setObservedGates({ [err.closeGate]: 'failed' });
95
+ }
96
+ throw err;
97
+ }
98
+ const gates = validation?.gates ?? null;
99
+ ctx.setObservedGates(gates);
100
+ return {
101
+ validationGates: gates,
102
+ lockWait: validation?.lockWait ?? null,
103
+ suiteTimings: validation?.suiteTimings ?? null,
104
+ pending: validation?.pending === true,
105
+ };
106
+ }
@@ -1,16 +1,11 @@
1
1
  /**
2
- * phases/reconcile-done.js — a Story closed as completed can still carry a
3
- * stale lifecycle label: a close that blocked before auto-merge landed its
4
- * PR leaves `agent::blocked` on the closed issue, and the re-run takes the
5
- * already-closed early return. With merge evidence on the Story branch, this
6
- * finishes the flip through the shared `agent::done` confirm. Best-effort —
7
- * the land already happened, so nothing here may change the `landed`
8
- * terminal; every failure is logged and swallowed.
2
+ * phases/reconcile-done.js — finish a closed Story's stale label: with a
3
+ * MERGED PR, flip and run the land tail. Best-effort; failures are logged.
9
4
  */
10
5
 
11
6
  import { gh as defaultGh } from '../../../gh-exec.js';
12
7
  import { Logger } from '../../../Logger.js';
13
- import { confirmStoryMerged } from '../../../single-story/confirm-merge.js';
8
+ import { confirmAndLand } from '../../../single-story/confirm-and-land.js';
14
9
  import { STATE_LABELS } from '../../ticketing.js';
15
10
  import { parsePrNumber } from './code-review.js';
16
11
  import { pickHeadPullRequest } from './pull-request.js';
@@ -22,13 +17,13 @@ const UNLANDED_CLOSE_REASONS = new Set(['not_planned', 'duplicate']);
22
17
  * @param {{ storyId: number, storyBranch: string, options: { cwd: string },
23
18
  * story: { labels?: string[], stateReason?: string|null } }} ctx
24
19
  * @param {{ provider: object, config: object, gh?: object,
25
- * notify?: Function, sleep?: Function }} deps
20
+ * notify?: Function, sleep?: Function, runPostLandTail?: Function }} deps
26
21
  * @param {(tag: string, msg: string) => void} progress
27
22
  * @returns {Promise<string>} `skipped` | `no-merged-pr` | `error` | the
28
23
  * `confirmStoryMerged` action.
29
24
  */
30
25
  export async function reconcileDoneLabel(ctx, deps, progress) {
31
- const { storyId, story, storyBranch } = ctx;
26
+ const { storyId, story } = ctx;
32
27
  if (
33
28
  UNLANDED_CLOSE_REASONS.has(story.stateReason) ||
34
29
  story.labels?.includes(STATE_LABELS.DONE)
@@ -36,31 +31,7 @@ export async function reconcileDoneLabel(ctx, deps, progress) {
36
31
  return 'skipped';
37
32
  }
38
33
  try {
39
- const rows = await (deps.gh ?? defaultGh).pr.list(
40
- ['--head', storyBranch, '--state', 'all'],
41
- ['url', 'state', 'mergedAt'],
42
- );
43
- const head = pickHeadPullRequest(rows);
44
- if (head?.state !== 'MERGED') {
45
- progress(
46
- 'NOOP',
47
- `No merged PR on ${storyBranch} — leaving Story #${storyId}'s labels as they are.`,
48
- );
49
- return 'no-merged-pr';
50
- }
51
- const confirmed = await confirmStoryMerged({
52
- provider: deps.provider,
53
- storyId,
54
- prNumber: parsePrNumber(head.url),
55
- prUrl: head.url,
56
- cwd: ctx.options.cwd,
57
- config: deps.config,
58
- progress,
59
- injectedNotify: deps.notify,
60
- prState: { state: 'MERGED', mergedAt: null },
61
- sleepFn: deps.sleep,
62
- });
63
- return confirmed.action;
34
+ return await reconcileFromMergedHead(ctx, deps, progress);
64
35
  } catch (err) {
65
36
  Logger.warn(
66
37
  `[single-story-close] ⚠️ Could not reconcile Story #${storyId} to agent::done: ${err?.message ?? err}`,
@@ -68,3 +39,40 @@ export async function reconcileDoneLabel(ctx, deps, progress) {
68
39
  return 'error';
69
40
  }
70
41
  }
42
+
43
+ /** The Story branch's head PR, or `null` when it is not MERGED. */
44
+ async function readMergedHead(storyBranch, gh) {
45
+ const rows = await (gh ?? defaultGh).pr.list(
46
+ ['--head', storyBranch, '--state', 'all'],
47
+ ['url', 'state', 'mergedAt'],
48
+ );
49
+ const head = pickHeadPullRequest(rows);
50
+ return head?.state === 'MERGED' ? head : null;
51
+ }
52
+
53
+ async function reconcileFromMergedHead(ctx, deps, progress) {
54
+ const { storyId, storyBranch } = ctx;
55
+ const head = await readMergedHead(storyBranch, deps.gh);
56
+ if (!head) {
57
+ progress(
58
+ 'NOOP',
59
+ `No merged PR on ${storyBranch} — leaving Story #${storyId}'s labels as they are.`,
60
+ );
61
+ return 'no-merged-pr';
62
+ }
63
+ const { confirmation } = await confirmAndLand({
64
+ provider: deps.provider,
65
+ storyId,
66
+ prNumber: parsePrNumber(head.url),
67
+ prUrl: head.url,
68
+ cwd: ctx.options.cwd,
69
+ config: deps.config,
70
+ progress,
71
+ injectedNotify: deps.notify,
72
+ prState: { state: 'MERGED', mergedAt: null },
73
+ sleepFn: deps.sleep,
74
+ storyBranch,
75
+ runPostLandTailFn: deps.runPostLandTail,
76
+ });
77
+ return confirmation.action;
78
+ }
@@ -0,0 +1,52 @@
1
+ import { emitReviewBlockedFriction } from '../../../observability/close-telemetry.js';
2
+ import { handleCriticalReviewBlock } from './review-block.js';
3
+ import { handleOverriddenReviewBlock } from './review-override.js';
4
+
5
+ /**
6
+ * An overridden Story proceeds; anything else emits friction, blocks, throws.
7
+ *
8
+ * @param {object} ctx
9
+ * @param {object} deps
10
+ * @param {{ prUrl: string, prNumber: number|null, reviewOutcome: object }} pr
11
+ * @returns {Promise<object>}
12
+ */
13
+ export async function resolveReviewHalt(
14
+ ctx,
15
+ deps,
16
+ { prUrl, prNumber, reviewOutcome },
17
+ ) {
18
+ const { storyId } = ctx;
19
+ const criticalCount = reviewOutcome.severity?.critical ?? 0;
20
+ // Checked before the blocked transition: an overridden Story proceeds.
21
+ if (ctx.options.overrideReviewBlock) {
22
+ return await handleOverriddenReviewBlock({
23
+ provider: deps.provider,
24
+ storyId,
25
+ prUrl,
26
+ prNumber,
27
+ criticalCount,
28
+ criticalByProvider: reviewOutcome.criticalByProvider,
29
+ reason: ctx.options.overrideReviewBlock,
30
+ config: deps.config,
31
+ });
32
+ }
33
+ await emitReviewBlockedFriction({
34
+ storyId,
35
+ prNumber,
36
+ criticalCount,
37
+ criticalByProvider: reviewOutcome.criticalByProvider,
38
+ config: deps.config,
39
+ });
40
+ await handleCriticalReviewBlock({
41
+ provider: deps.provider,
42
+ storyId,
43
+ prUrl,
44
+ criticalCount,
45
+ });
46
+ throw new Error(
47
+ `[single-story-close] Story-scope review reported ${criticalCount} critical blocker(s) on PR ${prUrl}. ` +
48
+ 'Auto-merge was not enabled. Remediate the findings posted to the PR and re-run `/mandrel-deliver`. ' +
49
+ 'If you have reviewed a finding and judged it wrong, re-run with ' +
50
+ '`--override-review-block "<reason>"` rather than merging by hand.',
51
+ );
52
+ }