mandrel 2.87.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 (156) 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 +12 -8
  5. package/.agents/docs/workflows.md +1 -1
  6. package/.agents/schemas/agentrc.schema.json +11 -5
  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/deliver-run.js +11 -0
  17. package/.agents/scripts/diagnose-friction.js +3 -3
  18. package/.agents/scripts/lib/baselines/coverage-updater-cli.js +6 -14
  19. package/.agents/scripts/lib/baselines/crap-updater-cli.js +36 -26
  20. package/.agents/scripts/lib/baselines/duplication-scanner.js +20 -1
  21. package/.agents/scripts/lib/baselines/env-overrides.js +39 -34
  22. package/.agents/scripts/lib/baselines/kernel.js +3 -2
  23. package/.agents/scripts/lib/baselines/kinds/crap.js +14 -38
  24. package/.agents/scripts/lib/baselines/preview-gates.js +4 -1
  25. package/.agents/scripts/lib/baselines/refresh-service.js +65 -22
  26. package/.agents/scripts/lib/baselines/writer.js +5 -1
  27. package/.agents/scripts/lib/bdd-runner-detect.js +7 -10
  28. package/.agents/scripts/lib/child-exec.js +14 -1
  29. package/.agents/scripts/lib/child-stream.js +122 -0
  30. package/.agents/scripts/lib/clean-temp.js +19 -13
  31. package/.agents/scripts/lib/cli-args.js +49 -0
  32. package/.agents/scripts/lib/codex/skills-projection.js +1 -12
  33. package/.agents/scripts/lib/config/gates/mutation.schema.js +2 -2
  34. package/.agents/scripts/lib/config/gh-config-dir.js +63 -0
  35. package/.agents/scripts/lib/config/github.js +2 -0
  36. package/.agents/scripts/lib/config/paths.js +14 -3
  37. package/.agents/scripts/lib/config-resolver.js +78 -64
  38. package/.agents/scripts/lib/config-settings-schema-delivery.js +4 -3
  39. package/.agents/scripts/lib/config-settings-schema.js +7 -0
  40. package/.agents/scripts/lib/coverage-baseline.js +2 -2
  41. package/.agents/scripts/lib/coverage-capture.js +16 -1
  42. package/.agents/scripts/lib/crap-utils.js +59 -47
  43. package/.agents/scripts/lib/full-suite-lock.js +1 -10
  44. package/.agents/scripts/lib/gates/baseline-store.js +10 -0
  45. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  46. package/.agents/scripts/lib/gh-exec.js +45 -2
  47. package/.agents/scripts/lib/gh-transport.js +27 -0
  48. package/.agents/scripts/lib/git-utils.js +16 -9
  49. package/.agents/scripts/lib/maintainability-engine.js +27 -6
  50. package/.agents/scripts/lib/maintainability-utils.js +14 -1
  51. package/.agents/scripts/lib/orchestration/check-baselines/phases/evaluate.js +4 -1
  52. package/.agents/scripts/lib/orchestration/evidence-stream.js +186 -0
  53. package/.agents/scripts/lib/orchestration/file-assumptions.js +2 -19
  54. package/.agents/scripts/lib/orchestration/git-cleanup/phases/branches-reap.js +3 -7
  55. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes-ff.js +34 -40
  56. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes.js +4 -3
  57. package/.agents/scripts/lib/orchestration/plan-persist/persist-helpers.js +2 -19
  58. package/.agents/scripts/lib/orchestration/pr-watch.js +1 -5
  59. package/.agents/scripts/lib/orchestration/project-meta-cache.js +17 -4
  60. package/.agents/scripts/lib/orchestration/reassert-status-column.js +1 -8
  61. package/.agents/scripts/lib/orchestration/resolve-stories.js +1 -0
  62. package/.agents/scripts/lib/orchestration/review-providers/native.js +2 -2
  63. package/.agents/scripts/lib/orchestration/single-story-close/phase-timer.js +43 -0
  64. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +37 -13
  65. package/.agents/scripts/lib/orchestration/single-story-close/phases/finish.js +264 -0
  66. package/.agents/scripts/lib/orchestration/single-story-close/phases/open-pr.js +68 -0
  67. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +106 -0
  68. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +43 -35
  69. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-halt.js +52 -0
  70. package/.agents/scripts/lib/orchestration/single-story-close/result.js +273 -0
  71. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +68 -776
  72. package/.agents/scripts/lib/orchestration/story-close/context-budget-writeback.js +20 -9
  73. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +2 -2
  74. package/.agents/scripts/lib/orchestration/story-close/ratchet-shrink-writeback.js +20 -12
  75. package/.agents/scripts/lib/orchestration/story-handoff.js +50 -21
  76. package/.agents/scripts/lib/orchestration/story-progress.js +32 -12
  77. package/.agents/scripts/lib/orchestration/ticket-validator.js +3 -13
  78. package/.agents/scripts/lib/qa/resolve-selection.js +1 -8
  79. package/.agents/scripts/lib/single-story/confirm-and-land.js +33 -0
  80. package/.agents/scripts/lib/single-story-sweep/reconcile-closing.js +43 -11
  81. package/.agents/scripts/lib/single-story-sweep/sweep-lock.js +130 -30
  82. package/.agents/scripts/lib/skills/parse-skill.js +1 -4
  83. package/.agents/scripts/lib/story-body/story-body.js +12 -1
  84. package/.agents/scripts/lib/suite-admission.js +3 -11
  85. package/.agents/scripts/lib/temp-retention.js +25 -11
  86. package/.agents/scripts/lib/test-run-credit.js +2 -5
  87. package/.agents/scripts/lib/transpile.js +193 -31
  88. package/.agents/scripts/lib/util/paths.js +31 -0
  89. package/.agents/scripts/lib/util/sleep.js +15 -0
  90. package/.agents/scripts/lib/validation-evidence.js +29 -3
  91. package/.agents/scripts/lib/wave-runner/live-probe.js +24 -0
  92. package/.agents/scripts/lib/workers/crap-worker.js +23 -12
  93. package/.agents/scripts/lib/workers/maintainability-report-worker.js +18 -12
  94. package/.agents/scripts/lib/workflow-closure.js +1 -8
  95. package/.agents/scripts/notify.js +83 -90
  96. package/.agents/scripts/plan-context.js +8 -4
  97. package/.agents/scripts/providers/github/auth.js +14 -30
  98. package/.agents/scripts/providers/github/blocked-by-add.js +11 -27
  99. package/.agents/scripts/providers/github/compose.js +1 -0
  100. package/.agents/scripts/providers/github/gh-token-diagnostics.js +130 -0
  101. package/.agents/scripts/providers/github/identity.js +158 -0
  102. package/.agents/scripts/providers/github/issues.js +2 -2
  103. package/.agents/scripts/providers/github/mappers.js +16 -19
  104. package/.agents/scripts/providers/github/projects-v2-graphql.js +4 -36
  105. package/.agents/scripts/providers/github/request-helpers.js +44 -0
  106. package/.agents/scripts/providers/github/sub-issue-add.js +11 -28
  107. package/.agents/scripts/providers/github.js +10 -2
  108. package/.agents/scripts/quality-preview.js +6 -19
  109. package/.agents/scripts/single-story-confirm-merge.js +8 -20
  110. package/.agents/scripts/single-story-init.js +0 -1
  111. package/.agents/scripts/stories-wave-tick.js +60 -46
  112. package/.agents/scripts/story-handoff.js +2 -23
  113. package/.agents/scripts/story-review-compute.js +3 -22
  114. package/.agents/scripts/sync-claude-agents.js +1 -12
  115. package/.agents/scripts/sync-claude-commands.js +1 -12
  116. package/.agents/scripts/update-crap-baseline.js +10 -19
  117. package/.agents/scripts/update-ticket-state.js +44 -45
  118. package/.agents/templates/docs/audit-sweep-runbook.md +1 -1
  119. package/.agents/workflows/audit-accessibility.md +1 -1
  120. package/.agents/workflows/audit-adrs.md +1 -1
  121. package/.agents/workflows/audit-architecture.md +1 -1
  122. package/.agents/workflows/audit-baselines.md +2 -2
  123. package/.agents/workflows/audit-clean-code.md +1 -1
  124. package/.agents/workflows/audit-data-model.md +1 -1
  125. package/.agents/workflows/audit-dependencies.md +1 -1
  126. package/.agents/workflows/audit-devops.md +1 -1
  127. package/.agents/workflows/audit-documentation.md +1 -1
  128. package/.agents/workflows/audit-exceptions.md +2 -2
  129. package/.agents/workflows/audit-mobile.md +1 -1
  130. package/.agents/workflows/audit-navigability.md +1 -1
  131. package/.agents/workflows/audit-performance.md +1 -1
  132. package/.agents/workflows/audit-privacy.md +1 -1
  133. package/.agents/workflows/audit-quality.md +1 -1
  134. package/.agents/workflows/audit-security.md +1 -1
  135. package/.agents/workflows/audit-seo.md +1 -1
  136. package/.agents/workflows/audit-sre.md +1 -1
  137. package/.agents/workflows/audit-to-stories.md +9 -7
  138. package/.agents/workflows/audit-ux-ui.md +1 -1
  139. package/.agents/workflows/helpers/audit-lens-core.md +8 -5
  140. package/.agents/workflows/helpers/deliver-digest.md +4 -5
  141. package/.agents/workflows/helpers/deliver-story-reference.md +4 -4
  142. package/.agents/workflows/mandrel-deliver.md +3 -1
  143. package/README.md +6 -3
  144. package/docs/CHANGELOG.md +29 -0
  145. package/lib/cli/doctor-checks/codex.js +240 -0
  146. package/lib/cli/doctor-checks/merge-driver.js +79 -0
  147. package/lib/cli/doctor-checks/payload.js +201 -0
  148. package/lib/cli/doctor-checks/read-json.js +16 -0
  149. package/lib/cli/doctor-checks/runtime-deps.js +146 -0
  150. package/lib/cli/doctor-checks/spawn.js +18 -0
  151. package/lib/cli/doctor-checks/sync-parity.js +205 -0
  152. package/lib/cli/doctor-checks/test-credit-path.js +270 -0
  153. package/lib/cli/doctor-checks/toolchain.js +137 -0
  154. package/lib/cli/doctor-checks/version-current.js +82 -0
  155. package/lib/cli/registry.js +40 -1330
  156. package/package.json +1 -1
@@ -1,7 +1,4 @@
1
- import {
2
- BASELINES_GATE_NAMES,
3
- buildDefaultGates,
4
- } from '../../close-validation/gates.js';
1
+ import { buildDefaultGates } from '../../close-validation/gates.js';
5
2
  import { runCloseValidation } from '../../close-validation/runner.js';
6
3
  import { getCiDelivery } from '../../config/ci.js';
7
4
  import { resolveWorktreeEnabled } from '../../config/runtime.js';
@@ -10,490 +7,50 @@ import { gh as defaultGh } from '../../gh-exec.js';
10
7
  import { getStoryBranch, gitSpawn, gitSync } from '../../git-utils.js';
11
8
  import { Logger } from '../../Logger.js';
12
9
  import {
13
- emitReviewBlockedFriction,
14
- recordCloseTelemetry,
15
10
  resolveWorkerEffort,
16
11
  resolveWorkerModel,
17
12
  resolveWorkerTokens,
18
13
  } from '../../observability/close-telemetry.js';
19
- import { emitTerminalFriction } from '../../observability/runtime-friction.js';
20
- import { emitTerseResult } from '../../observability/terse-result.js';
21
14
  import { createProvider } from '../../provider-factory.js';
22
15
  import { flipLabelAndNotify } from '../../single-story/story-merged-notify.js';
23
16
  import { WorktreeManager } from '../../worktree-manager.js';
24
17
  import { runCodeReview as runCodeReviewDefault } from '../code-review.js';
25
- import { MERGED_FLIP_FAILED_BLOCK_CLASS } from '../lifecycle/emit-merge-flip-failed.js';
18
+ import { resolveOperatorFromCandidates } from '../lease-guard-shared.js';
26
19
  import { resolveRunScopedConfig } from '../run-scoped-config.js';
27
- import { releaseStoryLease } from '../single-story-lease-guard.js';
28
20
  import {
29
- buildTerminalEnvelope,
30
- emitTerminalEnvelope,
31
- NEXT_COMMANDS,
32
- terminalFromWaitOutcome,
33
- } from '../story-deliver-terminal.js';
21
+ acquireStoryLease,
22
+ releaseStoryLease,
23
+ } from '../single-story-lease-guard.js';
34
24
  import { createStoryProgress } from '../story-progress.js';
35
- import { deriveCloseNote } from './close-note.js';
36
- import { closeArmedPr, runAutoMergePhase } from './phases/auto-merge.js';
37
- import { runBaseSyncPhase } from './phases/base-sync.js';
38
- import { runCloseValidationPhase } from './phases/close-validation.js';
25
+ import { createPhaseTimer } from './phase-timer.js';
39
26
  import { parsePrNumber } from './phases/code-review.js';
40
27
  import { runConfirmMergePhase } from './phases/confirm-merge.js';
28
+ import {
29
+ finishDeferred,
30
+ finishWithMergeWait,
31
+ finishWithoutMergeWait,
32
+ reportOperatorMergeSkip,
33
+ resolveAutoMergeOutcome,
34
+ } from './phases/finish.js';
41
35
  import { runGraphqlPreflight } from './phases/graphql-preflight.js';
42
- import { lockWaitPending } from './phases/lock-wait-pending.js';
36
+ import { openAndReviewPr } from './phases/open-pr.js';
43
37
  import { parseCloseOptions, resolveWaitForMerge } from './phases/options.js';
44
- import { runPostLandTail } from './phases/post-land.js';
45
- import {
46
- ensurePullRequestWith,
47
- pickHeadPullRequest,
48
- } from './phases/pull-request.js';
49
- import { pushStoryBranch } from './phases/push.js';
38
+ import { runPrePushPhases } from './phases/pre-push.js';
39
+ import { pickHeadPullRequest } from './phases/pull-request.js';
50
40
  import { reconcileDoneLabel } from './phases/reconcile-done.js';
51
- import { handleCriticalReviewBlock } from './phases/review-block.js';
52
- import { handleOverriddenReviewBlock } from './phases/review-override.js';
53
41
  import {
54
42
  existingWorktreePath,
55
43
  resolveStoryWorktree,
56
44
  } from './phases/worktree-restore.js';
57
- import { runWrongTreeGuardPhase } from './phases/wrong-tree-guard.js';
58
45
  import {
59
- discardHeldReview,
60
- reviewAfterPrOpen,
61
- startHeldReview,
62
- } from './review-overlap.js';
46
+ alreadyClosedResult,
47
+ closeEnvelopeGates,
48
+ preflightBlockedResult,
49
+ } from './result.js';
50
+ import { discardHeldReview } from './review-overlap.js';
63
51
 
64
52
  const progress = Logger.createProgress('single-story-close', { stderr: true });
65
53
 
66
- /**
67
- * Wall-clock seconds per named phase; each transition logs the phase it ends.
68
- * Overlapping work `pause`s the clock and `record`s its own time.
69
- *
70
- * @param {() => number} [nowMs]
71
- */
72
- function createPhaseTimer(nowMs = Date.now) {
73
- const durations = {};
74
- let current = null;
75
- let since = 0;
76
- const record = (phase, ms) => {
77
- const seconds = Math.round(Math.max(0, ms) / 100) / 10;
78
- durations[phase] = (durations[phase] ?? 0) + seconds;
79
- progress('TIMING', `⏱ ${phase}: ${seconds}s`);
80
- };
81
- const end = () => {
82
- if (current === null) return;
83
- record(current, nowMs() - since);
84
- current = null;
85
- };
86
- return {
87
- enter(phase) {
88
- end();
89
- if (phase === 'init') return;
90
- current = phase;
91
- since = nowMs();
92
- },
93
- record,
94
- pause: end,
95
- finish() {
96
- end();
97
- return Object.keys(durations).length > 0 ? { ...durations } : null;
98
- },
99
- stamp(terminal) {
100
- const phaseDurations = this.finish();
101
- if (phaseDurations) terminal.phaseDurations = phaseDurations;
102
- },
103
- };
104
- }
105
-
106
- const UNTIMED = Object.freeze({ stamp() {} });
107
-
108
- /** No worker figures: an inline close, or an ending before they resolve. */
109
- const NO_WORKER = Object.freeze({
110
- workerTokens: null,
111
- workerModel: null,
112
- workerEffort: null,
113
- });
114
-
115
- /**
116
- * The single terminal writer: the retry signal, the result summary (with its
117
- * `telemetry`), the envelope callers parse, and terminal friction — so no
118
- * ending can forget one. Must be awaited: the CLI `process.exit`s as soon as
119
- * `main` resolves.
120
- */
121
- async function emitTerminal({
122
- terminal,
123
- result,
124
- config,
125
- phaseTimer = UNTIMED,
126
- worker = NO_WORKER,
127
- }) {
128
- phaseTimer.stamp(terminal);
129
- await recordCloseTelemetry({ terminal, result, config, ...worker });
130
- if (result) {
131
- emitTerseResult({
132
- label: 'STORY CLOSE RESULT',
133
- result,
134
- scope: result.storyId,
135
- summary: {
136
- storyId: result.storyId,
137
- action: result.action,
138
- reason: result.reason,
139
- prNumber: result.prNumber,
140
- status: terminal?.status,
141
- },
142
- });
143
- }
144
- emitTerminalEnvelope(terminal, { config });
145
- await emitTerminalFriction({ envelope: terminal, config });
146
- }
147
-
148
- /**
149
- * @param {number} storyId
150
- * @param {string} reason
151
- * @returns {{ storyId: number, standalone: true, action: 'noop', reason: string }}
152
- */
153
- function noopResult(storyId, reason) {
154
- return { storyId, standalone: true, action: 'noop', reason };
155
- }
156
-
157
- /** Close reasons meaning nothing merged — superseded or abandoned. */
158
- const UNLANDED_CLOSE_REASONS = new Set(['not_planned', 'duplicate']);
159
-
160
- /**
161
- * Terminal for an already-closed Story. `not_planned` / `duplicate` mean
162
- * nothing merged, so it fails rather than reporting `landed` (which would
163
- * also unblock dependents); `completed` or null (GitHub's default) reads as
164
- * landed.
165
- */
166
- async function alreadyClosedResult(
167
- storyId,
168
- stateReason = null,
169
- config,
170
- worker = NO_WORKER,
171
- ) {
172
- if (UNLANDED_CLOSE_REASONS.has(stateReason)) {
173
- progress(
174
- 'NOOP',
175
- `Story #${storyId} is closed as not planned — nothing to land.`,
176
- );
177
- const result = noopResult(storyId, 'closed-not-planned');
178
- const terminal = buildTerminalEnvelope({
179
- storyId,
180
- status: 'failed',
181
- phase: 'init',
182
- failure: {
183
- reason:
184
- `Story #${storyId} is closed as not planned (superseded or abandoned) — ` +
185
- 'there is nothing to land. Re-plan it as a new Story, or pass a Story that is still open.',
186
- },
187
- nextCommand: null,
188
- elapsedSeconds: 0,
189
- });
190
- await emitTerminal({ terminal, result, config, worker });
191
- return { success: false, result, terminal };
192
- }
193
-
194
- progress('NOOP', `Story #${storyId} is already closed. Nothing to do.`);
195
- const result = noopResult(storyId, 'already-closed');
196
- const terminal = buildTerminalEnvelope({
197
- storyId,
198
- status: 'landed',
199
- phase: 'done',
200
- nextCommand: null,
201
- elapsedSeconds: 0,
202
- });
203
- await emitTerminal({ terminal, result, config, worker });
204
- return { success: true, result, terminal };
205
- }
206
-
207
- /**
208
- * Reuses the classifier's fallback class: the vocabulary is pinned by the
209
- * terminal schema, so `reason` names the blocker instead.
210
- */
211
- const PREFLIGHT_BLOCK_CLASS = 'api-race-other';
212
-
213
- /**
214
- * Returned, not thrown: a classified block, not a crash (a throw surfaces as
215
- * `failed`). The next command is the same close.
216
- *
217
- * @param {{ storyId: number, preflight: { verdict: string, reason: string },
218
- * config: object, startedAtMs: number }} args
219
- * @returns {Promise<{ success: false, result: object, terminal: object }>}
220
- */
221
- async function preflightBlockedResult({
222
- storyId,
223
- preflight,
224
- config,
225
- startedAtMs,
226
- worker = NO_WORKER,
227
- }) {
228
- const result = noopResult(storyId, `graphql-preflight-${preflight.verdict}`);
229
- const terminal = buildTerminalEnvelope({
230
- storyId,
231
- status: 'blocked',
232
- phase: 'init',
233
- blocked: {
234
- blockClass: PREFLIGHT_BLOCK_CLASS,
235
- reason: preflight.reason,
236
- frictionCommentId: null,
237
- },
238
- nextCommand: NEXT_COMMANDS.close(storyId),
239
- elapsedSeconds: elapsedSecondsSince(startedAtMs),
240
- });
241
- await emitTerminal({ terminal, result, config, worker });
242
- return { success: false, result, terminal };
243
- }
244
-
245
- /**
246
- * The split baselines gates, by name; only registered ones, never a phantom key.
247
- *
248
- * @param {Record<string, string>|null|undefined} validationGates
249
- * @returns {Record<string, string>}
250
- */
251
- function baselinesEnvelopeGates(validationGates) {
252
- const registered = Object.values(BASELINES_GATE_NAMES);
253
- const out = {};
254
- for (const [name, outcome] of Object.entries(validationGates ?? {})) {
255
- if (registered.includes(name)) out[name] = outcome;
256
- }
257
- return out;
258
- }
259
-
260
- /**
261
- * `overridden` > `degraded` > `passed`: an override records the human
262
- * decision on a failed review; `degraded` says a review surface produced no
263
- * verdict (reported, not blocking — a secondary review does not gate merge).
264
- *
265
- * @param {object|null} reviewOverride
266
- * @param {boolean} [reviewDegraded]
267
- * @returns {'overridden'|'degraded'|'passed'}
268
- */
269
- function codeReviewGate(reviewOverride, reviewDegraded) {
270
- if (reviewOverride) return 'overridden';
271
- return reviewDegraded ? 'degraded' : 'passed';
272
- }
273
-
274
- /**
275
- * @param {{ skipValidation?: boolean, skipSync?: boolean }} options
276
- * @param {Record<string, string>|null} validationGates
277
- * @param {object|null} reviewOverride
278
- * @param {boolean} [reviewDegraded]
279
- * @returns {Record<string, string>}
280
- */
281
- function closeEnvelopeGates(
282
- options,
283
- validationGates,
284
- reviewOverride,
285
- reviewDegraded,
286
- ) {
287
- return {
288
- validation: options.skipValidation ? 'skipped' : 'passed',
289
- ...baselinesEnvelopeGates(validationGates),
290
- baseSync: options.skipSync ? 'skipped' : 'passed',
291
- codeReview: codeReviewGate(reviewOverride, reviewDegraded),
292
- };
293
- }
294
-
295
- /**
296
- * wrong-tree guard → base-sync → close-validation. Validation runs last so
297
- * the validated tree is the pushed tree (base-sync's merge commit included),
298
- * and a cheap conflict is found before the expensive gates.
299
- *
300
- * @param {object} ctx
301
- * @param {object} deps
302
- * @returns {Promise<{
303
- * validationGates: Record<string, string>|null,
304
- * lockWait: { waitedSeconds: number, expired: boolean }|null,
305
- * suiteTimings: object|null,
306
- * pending: boolean,
307
- * }>} `validationGates` is null when skipped; `pending` means a full-suite
308
- * lock wait expired and the gates deferred.
309
- */
310
- async function runPrePushPhases(ctx, deps) {
311
- const { options, worktreePath, baseBranch, storyBranch, storyId, setPhase } =
312
- ctx;
313
- const { cwd } = options;
314
- setPhase('wrong-tree-guard');
315
- await runWrongTreeGuardPhase({
316
- cwd,
317
- worktreePath,
318
- baseBranch,
319
- storyId,
320
- provider: deps.provider,
321
- progress,
322
- gitSpawn: deps.gitSpawn,
323
- });
324
- if (!options.skipSync) {
325
- setPhase('base-sync');
326
- await runBaseSyncPhase({
327
- cwd,
328
- worktreePath,
329
- baseBranch,
330
- baseConfirmed: ctx.baseConfirmed,
331
- storyBranch,
332
- storyId,
333
- provider: deps.provider,
334
- injectedSync: deps.sync,
335
- progress,
336
- });
337
- } else {
338
- progress('SYNC', '⏭ Skipped (--skip-sync).');
339
- }
340
- if (options.skipValidation) {
341
- progress('VALIDATE', '⏭ Skipped (--skip-validation).');
342
- return {
343
- validationGates: null,
344
- lockWait: null,
345
- suiteTimings: null,
346
- pending: false,
347
- };
348
- }
349
- setPhase('close-validation');
350
- let validation;
351
- try {
352
- validation = await runCloseValidationPhase({
353
- cwd,
354
- worktreePath,
355
- config: deps.config,
356
- baseBranch,
357
- storyBranch,
358
- storyId,
359
- progress,
360
- runCloseValidation,
361
- buildDefaultGates,
362
- onPreGateStepsDone: () => {
363
- ctx.heldReview = startHeldReview({
364
- cwd,
365
- storyId,
366
- storyBranch,
367
- baseBranch,
368
- provider: deps.provider,
369
- runCodeReviewFn: deps.runCodeReview,
370
- gitSpawnFn: gitSpawn,
371
- progress,
372
- config: deps.config,
373
- });
374
- },
375
- });
376
- } catch (err) {
377
- discardHeldReview(ctx.heldReview, 'validation failed', progress);
378
- // The gate that died is all this run observed; the envelope claims no more.
379
- if (typeof err?.closeGate === 'string') {
380
- ctx.setObservedGates({ [err.closeGate]: 'failed' });
381
- }
382
- throw err;
383
- }
384
- const gates = validation?.gates ?? null;
385
- ctx.setObservedGates(gates);
386
- return {
387
- validationGates: gates,
388
- lockWait: validation?.lockWait ?? null,
389
- suiteTimings: validation?.suiteTimings ?? null,
390
- pending: validation?.pending === true,
391
- };
392
- }
393
-
394
- /**
395
- * An overridden Story proceeds; anything else emits friction, blocks, throws.
396
- *
397
- * @param {object} ctx
398
- * @param {object} deps
399
- * @param {{ prUrl: string, prNumber: number|null, reviewOutcome: object }} pr
400
- * @returns {Promise<object>}
401
- */
402
- async function resolveReviewHalt(
403
- ctx,
404
- deps,
405
- { prUrl, prNumber, reviewOutcome },
406
- ) {
407
- const { storyId } = ctx;
408
- const criticalCount = reviewOutcome.severity?.critical ?? 0;
409
- // Checked before the blocked transition: an overridden Story proceeds.
410
- if (ctx.options.overrideReviewBlock) {
411
- return await handleOverriddenReviewBlock({
412
- provider: deps.provider,
413
- storyId,
414
- prUrl,
415
- prNumber,
416
- criticalCount,
417
- criticalByProvider: reviewOutcome.criticalByProvider,
418
- reason: ctx.options.overrideReviewBlock,
419
- config: deps.config,
420
- });
421
- }
422
- await emitReviewBlockedFriction({
423
- storyId,
424
- prNumber,
425
- criticalCount,
426
- criticalByProvider: reviewOutcome.criticalByProvider,
427
- config: deps.config,
428
- });
429
- await handleCriticalReviewBlock({
430
- provider: deps.provider,
431
- storyId,
432
- prUrl,
433
- criticalCount,
434
- });
435
- throw new Error(
436
- `[single-story-close] Story-scope review reported ${criticalCount} critical blocker(s) on PR ${prUrl}. ` +
437
- 'Auto-merge was not enabled. Remediate the findings posted to the PR and re-run `/mandrel-deliver`. ' +
438
- 'If you have reviewed a finding and judged it wrong, re-run with ' +
439
- '`--override-review-block "<reason>"` rather than merging by hand.',
440
- );
441
- }
442
-
443
- async function openAndReviewPr(ctx, deps) {
444
- const { options, worktreePath, story, storyId, storyBranch, baseBranch } =
445
- ctx;
446
- const { cwd } = options;
447
- ctx.setPhase('push');
448
- // Push from the worktree so `pre-push` measures the tree being sent; the
449
- // ref-based reads below resolve identically from the shared `.git`.
450
- pushStoryBranch({ cwd, worktreePath, storyBranch, gitSync, progress });
451
- ctx.setPhase('pull-request');
452
- const { url: prUrl, alreadyMerged } = await ensurePullRequestWith({
453
- cwd,
454
- storyId,
455
- storyTitle: story.title,
456
- storyBody: story.body,
457
- storyBranch,
458
- baseBranch,
459
- gh: deps.gh,
460
- progress,
461
- });
462
- const prNumber = parsePrNumber(prUrl);
463
- ctx.recordPrNumber(prNumber);
464
- // Already merged (landed between invocations): skip review and arm; confirm observes it.
465
- if (alreadyMerged) {
466
- discardHeldReview(ctx.heldReview, 'PR already merged', progress);
467
- return { prUrl, prNumber, alreadyMerged: true };
468
- }
469
- const reviewOutcome = await reviewAfterPrOpen({
470
- held: ctx.heldReview,
471
- cwd,
472
- storyId,
473
- storyBranch,
474
- baseBranch,
475
- prUrl,
476
- prNumber,
477
- provider: deps.provider,
478
- runCodeReviewFn: deps.runCodeReview,
479
- gitSpawnFn: gitSpawn,
480
- progress,
481
- setPhase: ctx.setPhase,
482
- pauseTimer: ctx.phaseTimer.pause,
483
- recordDuration: ctx.phaseTimer.record,
484
- });
485
- const reviewOverride = reviewOutcome.halted
486
- ? await resolveReviewHalt(ctx, deps, { prUrl, prNumber, reviewOutcome })
487
- : null;
488
- return {
489
- prUrl,
490
- prNumber,
491
- alreadyMerged: false,
492
- reviewOverride,
493
- reviewDegraded: reviewOutcome.degraded === true,
494
- };
495
- }
496
-
497
54
  async function releaseLease({ storyId }, deps) {
498
55
  try {
499
56
  const outcome = await deps.releaseLease({
@@ -517,6 +74,37 @@ async function releaseLease({ storyId }, deps) {
517
74
  }
518
75
  }
519
76
 
77
+ /**
78
+ * Re-take the Story lease before any gate, push or PR write: a block released
79
+ * it, and init is the only other acquirer, so a re-close would otherwise run
80
+ * unassigned and unguarded. No steal — a foreign holder throws init's
81
+ * refusal. No configured operator handle skips the acquire (release is
82
+ * best-effort for the same reason), so close never newly hard-fails on it.
83
+ */
84
+ async function acquireLease({ storyId }, deps) {
85
+ const operator = resolveOperatorFromCandidates({
86
+ candidates: [deps.config?.github?.operatorHandle],
87
+ });
88
+ if (operator === null) {
89
+ progress(
90
+ 'LEASE',
91
+ `⚠️ Story #${storyId} lease not taken: github.operatorHandle is unset.`,
92
+ );
93
+ return null;
94
+ }
95
+ const lease = await deps.acquireLease({
96
+ provider: deps.provider,
97
+ storyId,
98
+ config: deps.config,
99
+ operator,
100
+ });
101
+ progress(
102
+ 'LEASE',
103
+ `🔒 Story #${storyId} lease ${lease.reason} (owner=@${lease.owner}).`,
104
+ );
105
+ return lease;
106
+ }
107
+
520
108
  /**
521
109
  * Release the lease best-effort before re-throwing a blocked-prone phase's
522
110
  * error verbatim. The lease has no TTL, so a stranded claim would refuse the
@@ -536,63 +124,15 @@ async function releaseLeaseOnBlock(run, ctx, deps) {
536
124
  }
537
125
 
538
126
  /**
539
- * Did this run OBSERVE the merge — confirmed, merged-but-flip-failed, or
540
- * direct-merged? Observation only, never intent.
541
- *
542
- * @param {{ waitOutcome?: object|null, directMerged?: boolean }} args
543
- * @returns {boolean}
127
+ * Tests mock these at their module URLs and re-import only this module, so
128
+ * they are bound here and handed to the phases rather than imported there.
544
129
  */
545
- function deriveObservedMerge({ waitOutcome = null, directMerged = false }) {
546
- return (
547
- waitOutcome?.confirmed === true ||
548
- waitOutcome?.blockClass === MERGED_FLIP_FAILED_BLOCK_CLASS ||
549
- directMerged === true
550
- );
551
- }
552
-
553
- function closeResult({
554
- storyId,
555
- storyBranch,
556
- baseBranch,
557
- prUrl,
558
- prNumber,
559
- autoMergeEnabled,
560
- autoMergeReason,
561
- worktreeReaped = false,
562
- leaseReleased,
563
- localCleanupDeferred = false,
564
- directMerged = false,
565
- waitedForMerge = false,
566
- merged = false,
567
- landCompleted = merged,
568
- }) {
569
- return {
570
- storyId,
571
- standalone: true,
572
- storyBranch,
573
- baseBranch,
574
- prUrl,
575
- prNumber,
576
- pushed: true,
577
- autoMergeEnabled,
578
- autoMergeReason,
579
- worktreeReaped,
580
- leaseReleased,
581
- // `gh`'s local branch delete failed while the remote merge/arm stood.
582
- localCleanupDeferred,
583
- // No native auto-merge, so the arm squash-merged directly.
584
- directMerged,
585
- waitedForMerge,
586
- merged,
587
- // Never from `waitedForMerge`; `merged` can be true without a completed land.
588
- note: deriveCloseNote({
589
- merged,
590
- directMerged,
591
- autoMergeEnabled,
592
- landCompleted,
593
- }),
594
- };
595
- }
130
+ const MODULE_SEAMS = Object.freeze({
131
+ runCloseValidation,
132
+ buildDefaultGates,
133
+ git: Object.freeze({ gitSpawn, gitSync }),
134
+ runConfirmMergePhase,
135
+ });
596
136
 
597
137
  /**
598
138
  * An injected double wins, else the real one; an absent optional seam stays
@@ -605,6 +145,7 @@ function closeResult({
605
145
  function resolveCloseDeps(options, injected) {
606
146
  const config = injected.injectedConfig || resolveConfig({ cwd: options.cwd });
607
147
  return {
148
+ ...MODULE_SEAMS,
608
149
  config,
609
150
  provider: injected.injectedProvider || createProvider(config),
610
151
  notify: injected.injectedNotify,
@@ -612,9 +153,11 @@ function resolveCloseDeps(options, injected) {
612
153
  runCodeReview: injected.injectedRunCodeReview ?? runCodeReviewDefault,
613
154
  gh: injected.injectedGh,
614
155
  gitSpawn: injected.injectedGitSpawn,
156
+ acquireLease: injected.injectedAcquireLease ?? acquireStoryLease,
615
157
  releaseLease: injected.injectedReleaseLease ?? releaseStoryLease,
616
158
  graphqlProbe: injected.injectedGraphqlProbe,
617
159
  sleep: injected.injectedSleep,
160
+ runPostLandTail: injected.injectedRunPostLandTail,
618
161
  };
619
162
  }
620
163
 
@@ -702,265 +245,13 @@ export async function runSingleStoryClose({
702
245
  }
703
246
  }
704
247
 
705
- /**
706
- * An already-merged PR skips the arm (`gh pr merge` would fail and block it).
707
- *
708
- * @param {object} args
709
- * @returns {Promise<{ autoMergeEnabled: boolean, autoMergeReason: string|null,
710
- * localCleanupDeferred: boolean, directMerged: boolean }>}
711
- */
712
- async function resolveAutoMergeOutcome({ alreadyMerged, ...phaseArgs }) {
713
- if (alreadyMerged) {
714
- return {
715
- autoMergeEnabled: true,
716
- autoMergeReason: null,
717
- localCleanupDeferred: false,
718
- directMerged: false,
719
- advisoryGate: null,
720
- };
721
- }
722
- return await runAutoMergePhase(phaseArgs);
723
- }
724
-
725
- /** One console line per non-landed wait ending, keyed by status. */
726
- const WAIT_TERMINAL_LINES = Object.freeze({
727
- pending: (terminal, { storyId, prUrl }) => [
728
- 'PENDING',
729
- `⏸ Story #${storyId}: PR ${prUrl} still in flight — resume with: ${terminal.nextCommand}`,
730
- ],
731
- failed: (terminal, { storyId, prUrl }) => [
732
- 'FAILED',
733
- `🛑 Story #${storyId}: PR ${prUrl} did not land (${terminal.phase}): ` +
734
- `${terminal.failure?.reason}. Labels unchanged. Next: ${terminal.nextCommand}`,
735
- ],
736
- blocked: (terminal, { storyId, prUrl }) => [
737
- 'BLOCKED',
738
- `🛑 Story #${storyId}: PR ${prUrl} did not land ` +
739
- `(blockClass=${terminal.blocked?.blockClass}). Story is at agent::blocked. ` +
740
- `Next: ${terminal.nextCommand}`,
741
- ],
742
- landed: (_terminal, { storyId, prUrl }) => [
743
- 'DONE',
744
- `✅ Story #${storyId}: PR merged → ${prUrl}`,
745
- ],
746
- });
747
-
748
- /**
749
- * `pending` is not a failure: resumable, with its own CLI exit code.
750
- *
751
- * @param {{ status: string, nextCommand: string }} terminal
752
- * @param {{ storyId: number, prUrl: string|null }} ctx
753
- * @returns {void}
754
- */
755
- function reportWaitTerminal(terminal, ctx) {
756
- const line =
757
- WAIT_TERMINAL_LINES[terminal.status] ?? WAIT_TERMINAL_LINES.blocked;
758
- progress(...line(terminal, ctx));
759
- }
760
-
761
- /**
762
- * Reaped only by the post-land tail, and only when it actually removed the
763
- * tree (a skipped reap reports ok with a detail).
764
- *
765
- * @param {object|null|undefined} tail
766
- * @returns {boolean}
767
- */
768
- function tailReapedWorktree(tail) {
769
- return tail?.worktreeReap === true && !tail?.details?.worktreeReap;
770
- }
771
-
772
- /**
773
- * @param {object} prCtx
774
- * @param {object} deps
775
- * @returns {Promise<{ success: boolean, result: object, terminal: object }>}
776
- */
777
- async function finishWithMergeWait(prCtx, deps) {
778
- deps.setPhase('confirm-merge');
779
- const waitOutcome = await runConfirmMergePhase({
780
- cwd: deps.cwd,
781
- worktreePath: prCtx.worktreePath,
782
- storyId: prCtx.storyId,
783
- storyBranch: prCtx.storyBranch,
784
- baseBranch: prCtx.baseBranch,
785
- prNumber: prCtx.prNumber,
786
- prUrl: prCtx.prUrl,
787
- autoMergeEnabled: prCtx.autoMergeEnabled,
788
- autoMergeReason: prCtx.autoMergeReason,
789
- // Positive evidence for the re-arm rule: this close armed the PR.
790
- closeArmed: closeArmedPr(prCtx),
791
- advisoryGate: prCtx.advisoryGate,
792
- provider: deps.provider,
793
- config: prCtx.config,
794
- maxWaitSeconds: deps.maxWaitSeconds,
795
- mergeWatchMode: deps.mergeWatchMode,
796
- rerunAdvisory: deps.rerunAdvisory,
797
- progress,
798
- injectedGh: deps.injectedGh,
799
- injectedNotify: deps.injectedNotify,
800
- runPostLandTailFn: (args) => {
801
- deps.setPhase('post-land');
802
- return runPostLandTail(args);
803
- },
804
- });
805
- const terminal = terminalFromWaitOutcome({
806
- waitOutcome,
807
- storyId: prCtx.storyId,
808
- storyBranch: prCtx.storyBranch,
809
- baseBranch: prCtx.baseBranch,
810
- prNumber: prCtx.prNumber,
811
- prUrl: prCtx.prUrl,
812
- autoMergeEnabled: prCtx.autoMergeEnabled,
813
- autoMergeReason: prCtx.autoMergeReason,
814
- gates: prCtx.gates,
815
- lockWait: prCtx.lockWait,
816
- suiteTimings: prCtx.suiteTimings,
817
- elapsedSeconds: elapsedSecondsSince(prCtx.startedAtMs),
818
- });
819
- const result = closeResult({
820
- storyId: prCtx.storyId,
821
- storyBranch: prCtx.storyBranch,
822
- baseBranch: prCtx.baseBranch,
823
- prUrl: prCtx.prUrl,
824
- prNumber: prCtx.prNumber,
825
- autoMergeEnabled: prCtx.autoMergeEnabled,
826
- autoMergeReason: prCtx.autoMergeReason,
827
- worktreeReaped: tailReapedWorktree(waitOutcome.tail),
828
- // Released by the post-land tail only; any other ending keeps the claim.
829
- leaseReleased: waitOutcome.tail?.leaseRelease === true,
830
- localCleanupDeferred: prCtx.localCleanupDeferred,
831
- directMerged: prCtx.directMerged,
832
- waitedForMerge: true,
833
- merged: deriveObservedMerge({
834
- waitOutcome,
835
- directMerged: prCtx.directMerged,
836
- }),
837
- landCompleted: waitOutcome.confirmed === true,
838
- });
839
- await emitTerminal({
840
- terminal,
841
- result,
842
- config: prCtx.config,
843
- phaseTimer: prCtx.phaseTimer,
844
- worker: prCtx.worker,
845
- });
846
- reportWaitTerminal(terminal, { storyId: prCtx.storyId, prUrl: prCtx.prUrl });
847
- return { success: terminal.status === 'landed', result, terminal };
848
- }
849
-
850
- /**
851
- * The no-wait ending: a human owns the land, so it is `pending` with one
852
- * command to finish it. A direct merge by the arm is still observed.
853
- *
854
- * @param {object} prCtx
855
- * @param {string} waitForMergeReason
856
- * @returns {Promise<{ success: boolean, result: object, terminal: object }>}
857
- */
858
- async function finishWithoutMergeWait(prCtx, waitForMergeReason) {
859
- const merged = deriveObservedMerge({ directMerged: prCtx.directMerged });
860
- const result = closeResult({
861
- storyId: prCtx.storyId,
862
- storyBranch: prCtx.storyBranch,
863
- baseBranch: prCtx.baseBranch,
864
- prUrl: prCtx.prUrl,
865
- prNumber: prCtx.prNumber,
866
- autoMergeEnabled: prCtx.autoMergeEnabled,
867
- autoMergeReason: prCtx.autoMergeReason,
868
- leaseReleased: false,
869
- localCleanupDeferred: prCtx.localCleanupDeferred,
870
- directMerged: prCtx.directMerged,
871
- merged,
872
- // The flip, issue close and tail belong to `nextCommand`.
873
- landCompleted: false,
874
- });
875
- const terminal = buildTerminalEnvelope({
876
- storyId: prCtx.storyId,
877
- status: 'pending',
878
- phase: 'auto-merge',
879
- storyBranch: prCtx.storyBranch,
880
- baseBranch: prCtx.baseBranch,
881
- pr: {
882
- number: prCtx.prNumber,
883
- url: prCtx.prUrl ?? null,
884
- state: merged ? 'MERGED' : 'OPEN',
885
- autoMergeEnabled: Boolean(prCtx.autoMergeEnabled),
886
- autoMergeReason: prCtx.autoMergeReason ?? null,
887
- },
888
- gates: prCtx.gates,
889
- lockWait: prCtx.lockWait,
890
- suiteTimings: prCtx.suiteTimings,
891
- nextCommand: NEXT_COMMANDS.confirmMerge(prCtx.storyId),
892
- elapsedSeconds: elapsedSecondsSince(prCtx.startedAtMs),
893
- });
894
- await emitTerminal({
895
- terminal,
896
- result,
897
- config: prCtx.config,
898
- phaseTimer: prCtx.phaseTimer,
899
- worker: prCtx.worker,
900
- });
901
- progress(
902
- 'DONE',
903
- `✅ Story #${prCtx.storyId}: PR ready → ${prCtx.prUrl} (${waitForMergeReason})`,
904
- );
905
- return { success: true, result, terminal };
906
- }
907
-
908
- /**
909
- * A full-suite lock wait expired: `pending`, nothing pushed.
910
- *
911
- * @param {{ waitedSeconds: number, expired: boolean }|null} lockWait
912
- * @param {{ storyId: number, storyBranch: string, baseBranch: string,
913
- * config: object, startedAtMs: number }} ctx
914
- * @returns {Promise<{ success: false, result: object, terminal: object }>}
915
- */
916
- async function finishDeferred(
917
- lockWait,
918
- { config, startedAtMs, phaseTimer, worker, ...ids },
919
- ) {
920
- const { result, terminal, note } = lockWaitPending({
921
- ...ids,
922
- lockWait,
923
- elapsedSeconds: elapsedSecondsSince(startedAtMs),
924
- });
925
- await emitTerminal({ terminal, result, config, phaseTimer, worker });
926
- progress('PENDING', note);
927
- return { success: false, result, terminal };
928
- }
929
-
930
- /**
931
- * @param {number} startedAtMs
932
- * @returns {number}
933
- */
934
- function elapsedSecondsSince(startedAtMs) {
935
- return Math.round((Date.now() - startedAtMs) / 1000);
936
- }
937
-
938
- /**
939
- * @param {{ waitForMergeReason: string, autoMergeReason: string|null,
940
- * storyId: number, waitForMergeExplicit?: boolean }} args
941
- * @returns {void}
942
- */
943
- function reportOperatorMergeSkip({
944
- waitForMergeReason,
945
- autoMergeReason,
946
- storyId,
947
- waitForMergeExplicit,
948
- }) {
949
- if (waitForMergeReason !== 'operator-merge') return;
950
- progress(
951
- 'MERGE',
952
- `⏭ Not waiting for merge (${autoMergeReason}) — the operator owns this merge; ` +
953
- `Story #${storyId} rests at agent::closing.` +
954
- (waitForMergeExplicit === true
955
- ? ' --wait-merge cannot land a PR that was deliberately left un-armed.'
956
- : ''),
957
- );
958
- }
959
-
960
248
  async function loadStoryPhase(ctx, deps) {
961
249
  progress('INIT', `Closing standalone Story #${ctx.storyId}...`);
962
250
  ctx.story = await deps.provider.getTicket(ctx.storyId);
963
- if (ctx.story.state !== 'closed') return null;
251
+ if (ctx.story.state !== 'closed') {
252
+ await acquireLease(ctx, deps);
253
+ return null;
254
+ }
964
255
  await reconcileDoneLabel(ctx, deps, progress);
965
256
  return await alreadyClosedResult(
966
257
  ctx.storyId,
@@ -1221,6 +512,7 @@ async function finishPhase(ctx, deps) {
1221
512
  setPhase: ctx.setPhase,
1222
513
  injectedGh: deps.gh,
1223
514
  injectedNotify: deps.notify,
515
+ runConfirmMergePhase: deps.runConfirmMergePhase,
1224
516
  });
1225
517
  }
1226
518