mandrel 2.70.0 → 2.72.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 (79) hide show
  1. package/.agents/README.md +8 -9
  2. package/.agents/agents/acceptance-critic.md +1 -0
  3. package/.agents/agents/auditor.md +1 -0
  4. package/.agents/agents/plan-critic.md +1 -0
  5. package/.agents/agents/story-worker.md +63 -64
  6. package/.agents/docs/agentrc-reference.json +2 -1
  7. package/.agents/docs/configuration.md +7 -8
  8. package/.agents/rules/git-conventions-reference.md +2 -2
  9. package/.agents/schemas/agentrc.schema.json +19 -2
  10. package/.agents/schemas/story-deliver-terminal.schema.json +10 -1
  11. package/.agents/scripts/acceptance-eval.js +194 -15
  12. package/.agents/scripts/deliver-run.js +92 -43
  13. package/.agents/scripts/lib/audit-suite/index.js +1 -1
  14. package/.agents/scripts/lib/audit-suite/story-checklist.js +65 -0
  15. package/.agents/scripts/lib/audit-to-stories/audit-label-taxonomy.js +2 -2
  16. package/.agents/scripts/lib/bootstrap/issue-forms-template.js +1 -1
  17. package/.agents/scripts/lib/cli-args.js +22 -0
  18. package/.agents/scripts/lib/close-validation/gates.js +17 -3
  19. package/.agents/scripts/lib/config/agent-models.js +117 -0
  20. package/.agents/scripts/lib/config-settings-schema-delivery.js +13 -1
  21. package/.agents/scripts/lib/config-settings-schema-quality.js +1 -1
  22. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  23. package/.agents/scripts/lib/git/sync-from-base.js +89 -17
  24. package/.agents/scripts/lib/label-taxonomy.js +13 -3
  25. package/.agents/scripts/lib/notifications/notifier.js +11 -15
  26. package/.agents/scripts/lib/observability/close-telemetry.js +19 -3
  27. package/.agents/scripts/lib/observability/source-classifier.js +1 -0
  28. package/.agents/scripts/lib/orchestration/cancelled-run-discount.js +129 -0
  29. package/.agents/scripts/lib/orchestration/code-review.js +2 -2
  30. package/.agents/scripts/lib/orchestration/deliver-recover.js +166 -34
  31. package/.agents/scripts/lib/orchestration/file-assumptions.js +45 -11
  32. package/.agents/scripts/lib/orchestration/plan-context.js +17 -10
  33. package/.agents/scripts/lib/orchestration/plan-persist/changes-repair.js +130 -24
  34. package/.agents/scripts/lib/orchestration/plan-persist/run-plan-persist.js +19 -16
  35. package/.agents/scripts/lib/orchestration/plan-persist/story-ops.js +1 -0
  36. package/.agents/scripts/lib/orchestration/plan-persist/summary.js +4 -3
  37. package/.agents/scripts/lib/orchestration/pr-watch.js +14 -3
  38. package/.agents/scripts/lib/orchestration/resolve-stories.js +10 -2
  39. package/.agents/scripts/lib/orchestration/review-providers/native.js +5 -165
  40. package/.agents/scripts/lib/orchestration/single-story-close/failed-terminal.js +14 -2
  41. package/.agents/scripts/lib/orchestration/single-story-close/phases/auto-merge.js +45 -0
  42. package/.agents/scripts/lib/orchestration/single-story-close/phases/base-sync.js +162 -58
  43. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +58 -6
  44. package/.agents/scripts/lib/orchestration/single-story-close/phases/merge-wait-recovery.js +296 -0
  45. package/.agents/scripts/lib/orchestration/single-story-close/phases/options.js +20 -4
  46. package/.agents/scripts/lib/orchestration/single-story-close/phases/post-land.js +52 -6
  47. package/.agents/scripts/lib/orchestration/single-story-close/phases/pull-request.js +2 -2
  48. package/.agents/scripts/lib/orchestration/single-story-close/phases/story-branch-catch-up.js +50 -0
  49. package/.agents/scripts/lib/orchestration/single-story-close/phases/worktree-reap.js +64 -52
  50. package/.agents/scripts/lib/orchestration/single-story-close/phases/worktree-restore.js +133 -0
  51. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +187 -74
  52. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +46 -6
  53. package/.agents/scripts/lib/orchestration/story-handoff.js +849 -0
  54. package/.agents/scripts/lib/orchestration/story-init-result.js +83 -0
  55. package/.agents/scripts/lib/orchestration/task-body-validator.js +35 -5
  56. package/.agents/scripts/lib/orchestration/ticket-validator-sizing.js +1 -1
  57. package/.agents/scripts/lib/orchestration/ticket-validator.js +20 -2
  58. package/.agents/scripts/lib/single-story/confirm-merge.js +44 -7
  59. package/.agents/scripts/lib/story-body/story-body.js +40 -5
  60. package/.agents/scripts/lib/templates/decomposer-prompts.js +33 -36
  61. package/.agents/scripts/pr-watch-with-update.js +5 -0
  62. package/.agents/scripts/single-story-close.js +8 -0
  63. package/.agents/scripts/single-story-confirm-merge.js +34 -3
  64. package/.agents/scripts/single-story-init.js +17 -32
  65. package/.agents/scripts/story-handoff.js +112 -0
  66. package/.agents/scripts/sync-claude-agents.js +58 -27
  67. package/.agents/workflows/helpers/acceptance-self-eval.md +24 -18
  68. package/.agents/workflows/helpers/code-review.md +3 -3
  69. package/.agents/workflows/helpers/deliver-digest.md +79 -80
  70. package/.agents/workflows/helpers/deliver-light.md +9 -7
  71. package/.agents/workflows/helpers/deliver-reference.md +38 -22
  72. package/.agents/workflows/helpers/deliver-story-reference.md +39 -18
  73. package/.agents/workflows/helpers/deliver-story.md +30 -23
  74. package/.agents/workflows/helpers/plan-reference.md +24 -9
  75. package/.agents/workflows/helpers/worktree-lifecycle.md +5 -5
  76. package/docs/CHANGELOG.md +31 -0
  77. package/lib/cli/registry.js +7 -0
  78. package/package.json +4 -3
  79. package/.agents/scripts/lib/orchestration/review-providers/scoped-lint.js +0 -272
@@ -1,8 +1,10 @@
1
1
  /**
2
2
  * phases/base-sync.js — sync the Story branch from `origin/<baseBranch>`
3
3
  * before push, so a PR does not open behind a base a sibling's merge just
4
- * moved. Runs in the worktree (else the main checkout); a failure blocks the
5
- * Story and throws.
4
+ * moved. Runs in the worktree (else the main checkout). A baseline-only
5
+ * conflict resolves inside the sync; any other conflict against a confirmed
6
+ * base goes back to the delivering agent (friction, labels unchanged); every
7
+ * other failure blocks the Story. All failures throw.
6
8
  */
7
9
 
8
10
  import { getQuality } from '../../../config/quality.js';
@@ -11,6 +13,7 @@ import { filterFilesUnderTargets } from '../../../coverage-capture.js';
11
13
  import { syncBranchFromBase } from '../../../git/sync-from-base.js';
12
14
  import { Logger } from '../../../Logger.js';
13
15
  import { AGENT_LABELS } from '../../../label-constants.js';
16
+ import { NEXT_COMMANDS } from '../../story-deliver-terminal.js';
14
17
  import {
15
18
  STATE_LABELS,
16
19
  transitionTicketState,
@@ -57,7 +60,7 @@ export async function runBaseSyncPhase({
57
60
  log: (tag, msg) => progress(tag, msg),
58
61
  });
59
62
  if (!syncResult.synced) {
60
- await handleSyncFailure({
63
+ const { handedBack } = await handleSyncFailure({
61
64
  provider,
62
65
  storyId,
63
66
  syncCwd,
@@ -67,17 +70,18 @@ export async function runBaseSyncPhase({
67
70
  result: syncResult,
68
71
  progress,
69
72
  });
70
- throw new Error(
71
- `[single-story-close] Base-sync failed (${syncResult.kind})` +
72
- (syncResult.conflictFiles
73
- ? `: conflicting files = ${syncResult.conflictFiles.join(', ')}`
74
- : syncResult.stderr
75
- ? `: ${syncResult.stderr.slice(0, 200)}`
76
- : '') +
77
- `. Story transitioned to ${AGENT_LABELS.BLOCKED}; resolve in ${syncCwd} and re-run \`/mandrel-deliver ${storyId}\`.`,
78
- );
73
+ throw buildSyncFailureError({ storyId, syncCwd, syncResult, handedBack });
79
74
  }
80
75
  progress('SYNC', `✅ Synced from origin/${baseBranch} (${syncResult.kind}).`);
76
+ const resolved = syncResult.resolvedBaselineFiles ?? [];
77
+ if (resolved.length > 0) {
78
+ progress(
79
+ 'SYNC',
80
+ `♻️ Baseline-only conflict resolved to origin/${baseBranch}'s version ` +
81
+ `(the insert-only seat and close's gates re-derive this Story's rows): ` +
82
+ resolved.join(', '),
83
+ );
84
+ }
81
85
  for (const line of buildStampInvalidatedWarning({
82
86
  baseBranch,
83
87
  result: syncResult,
@@ -87,6 +91,41 @@ export async function runBaseSyncPhase({
87
91
  }
88
92
  }
89
93
 
94
+ /** A handed-back conflict re-runs close next (`closeNextCommand`). */
95
+ function buildSyncFailureError({ storyId, syncCwd, syncResult, handedBack }) {
96
+ const err = new Error(
97
+ `[single-story-close] Base-sync failed (${syncResult.kind})` +
98
+ syncFailureDetail(syncResult) +
99
+ (handedBack
100
+ ? `. Labels unchanged — resolve the conflict in ${syncCwd}, commit, and re-run close.`
101
+ : `. Story transitioned to ${AGENT_LABELS.BLOCKED}; resolve in ${syncCwd} and re-run \`/mandrel-deliver ${storyId}\`.`),
102
+ );
103
+ if (handedBack) err.closeNextCommand = NEXT_COMMANDS.close(storyId);
104
+ return err;
105
+ }
106
+
107
+ function syncFailureDetail({ conflictFiles, stderr }) {
108
+ if (conflictFiles) return `: conflicting files = ${conflictFiles.join(', ')}`;
109
+ return stderr ? `: ${stderr.slice(0, 200)}` : '';
110
+ }
111
+
112
+ /**
113
+ * A source conflict against a confirmed base is the delivering agent's to
114
+ * resolve; every other sync failure needs a human.
115
+ *
116
+ * @param {{ kind: string }} result
117
+ * @param {boolean} baseConfirmed
118
+ * @returns {boolean}
119
+ */
120
+ function isHandedBack(result, baseConfirmed) {
121
+ return result.kind === 'conflict' && baseConfirmed === true;
122
+ }
123
+
124
+ /** `handBack`: the merge wait, whose PR is open, hands every failure back. */
125
+ function resolveHandedBack({ result, baseConfirmed, handBack }) {
126
+ return handBack === true || isHandedBack(result, baseConfirmed);
127
+ }
128
+
90
129
  /**
91
130
  * The CRAP scoring scope, or `[]` when unresolvable.
92
131
  *
@@ -142,7 +181,8 @@ function buildStampInvalidatedWarning({ baseBranch, result, targetDirs }) {
142
181
  }
143
182
 
144
183
  /**
145
- * Post a `friction` comment and block the Story; both best-effort.
184
+ * Post a `friction` comment, then block the Story unless the failure is
185
+ * handed back to the delivering agent; both best-effort.
146
186
  *
147
187
  * @param {{
148
188
  * provider: object,
@@ -152,8 +192,10 @@ function buildStampInvalidatedWarning({ baseBranch, result, targetDirs }) {
152
192
  * baseConfirmed?: boolean,
153
193
  * storyBranch: string,
154
194
  * result: { kind: string, conflictFiles?: string[], stderr?: string },
195
+ * handBack?: boolean,
155
196
  * progress: (tag: string, msg: string) => void,
156
- * }} args
197
+ * }} args `handBack` leaves the labels alone for every failure kind.
198
+ * @returns {Promise<{ handedBack: boolean }>}
157
199
  */
158
200
  export async function handleSyncFailure({
159
201
  provider,
@@ -163,6 +205,7 @@ export async function handleSyncFailure({
163
205
  baseConfirmed = false,
164
206
  storyBranch,
165
207
  result,
208
+ handBack = false,
166
209
  progress,
167
210
  }) {
168
211
  const body = buildSyncFailureCommentBody({
@@ -172,6 +215,7 @@ export async function handleSyncFailure({
172
215
  baseConfirmed,
173
216
  syncCwd,
174
217
  result,
218
+ handBack,
175
219
  });
176
220
 
177
221
  // Comment first so the recovery surface lands even if the flip fails; a
@@ -185,6 +229,25 @@ export async function handleSyncFailure({
185
229
  );
186
230
  }
187
231
 
232
+ const handedBack = resolveHandedBack({ result, baseConfirmed, handBack });
233
+ await settleSyncFailureLabels({ provider, storyId, handedBack, progress });
234
+ return { handedBack };
235
+ }
236
+
237
+ /** A handed-back conflict leaves the labels alone; anything else blocks. */
238
+ async function settleSyncFailureLabels({
239
+ provider,
240
+ storyId,
241
+ handedBack,
242
+ progress,
243
+ }) {
244
+ if (handedBack) {
245
+ progress(
246
+ 'SYNC',
247
+ `↩️ Conflict handed back to the delivering agent; Story #${storyId} labels unchanged.`,
248
+ );
249
+ return;
250
+ }
188
251
  // The canonical mutator: a bare label write skips the Projects v2 sync.
189
252
  try {
190
253
  await transitionTicketState(provider, storyId, STATE_LABELS.BLOCKED, {});
@@ -196,12 +259,86 @@ export async function handleSyncFailure({
196
259
  }
197
260
  }
198
261
 
262
+ const CLOSE_RERUN = (storyId) =>
263
+ `node .agents/scripts/single-story-close.js --story ${storyId}`;
264
+
265
+ function commentLede(handedBack, baseBranch) {
266
+ if (handedBack) {
267
+ return [
268
+ `**For the delivering agent:** the pre-push sync against \`origin/${baseBranch}\``,
269
+ 'conflicts. Labels are unchanged — this is not a block. Resolve the',
270
+ 'conflict in the worktree, commit, and re-run close:',
271
+ ];
272
+ }
273
+ return [
274
+ `The pre-push sync against \`origin/${baseBranch}\` could not complete. The`,
275
+ 'Story has been transitioned to `agent::blocked`. To resume:',
276
+ ];
277
+ }
278
+
279
+ function mergeAdvice({ storyId, syncCwd, baseBranch, handedBack }) {
280
+ const lines = [
281
+ '```bash',
282
+ `cd ${syncCwd}`,
283
+ `git fetch origin ${baseBranch}`,
284
+ `git merge --no-edit origin/${baseBranch}`,
285
+ '# resolve any conflicts, then:',
286
+ `git add -A ; git commit --no-edit`,
287
+ '# re-run close:',
288
+ CLOSE_RERUN(storyId),
289
+ '```',
290
+ ];
291
+ if (!handedBack) return lines;
292
+ return [
293
+ ...lines,
294
+ '',
295
+ 'Only an agent that cannot resolve it takes the blocked path: post why,',
296
+ `then \`node .agents/scripts/update-ticket-state.js --ticket ${storyId} --state agent::blocked\`.`,
297
+ ];
298
+ }
299
+
300
+ function unconfirmedBaseAdvice({ storyId, storyBranch, baseBranch }) {
301
+ return [
302
+ `⚠️ **No merge advice: \`${baseBranch}\` is unconfirmed.** This close could not`,
303
+ `read the base branch \`${storyBranch}\` was seeded from off the run's`,
304
+ 'init receipt, so merging that base in could contaminate the branch',
305
+ 'and its PR diff with an unrelated base. Establish the real base first —',
306
+ `check \`temp/orchestration/story-init-result-${storyId}.log\` and \`project.baseBranch\` in`,
307
+ '`.agentrc.json` / `.agentrc.local.json` — then merge that base and re-run:',
308
+ '',
309
+ '```bash',
310
+ CLOSE_RERUN(storyId),
311
+ '```',
312
+ ];
313
+ }
314
+
315
+ function failureEvidence(kind, result) {
316
+ const files = result.conflictFiles ?? [];
317
+ if (kind === 'conflict' && files.length > 0) {
318
+ return [
319
+ '',
320
+ '**Conflicting files:**',
321
+ '',
322
+ ...files.map((f) => `- \`${f}\``),
323
+ ];
324
+ }
325
+ if (!result.stderr) return [];
326
+ return [
327
+ '',
328
+ '**git stderr:**',
329
+ '',
330
+ '```',
331
+ result.stderr.slice(0, 1000),
332
+ '```',
333
+ ];
334
+ }
335
+
199
336
  /**
200
337
  * `baseConfirmed` (default false, fail-closed) gates the merge-the-base
201
338
  * advice: merging a base the Story was not seeded from contaminates the
202
339
  * branch and PR diff, so an unconfirmed base gets "establish it first".
203
340
  *
204
- * @param {{ storyId: number, storyBranch: string, baseBranch: string, baseConfirmed?: boolean, syncCwd: string, result: { kind: string, conflictFiles?: string[], stderr?: string } }} args
341
+ * @param {{ storyId: number, storyBranch: string, baseBranch: string, baseConfirmed?: boolean, syncCwd: string, result: { kind: string, conflictFiles?: string[], stderr?: string }, handBack?: boolean }} args
205
342
  * @returns {string}
206
343
  */
207
344
  export function buildSyncFailureCommentBody({
@@ -211,56 +348,23 @@ export function buildSyncFailureCommentBody({
211
348
  baseConfirmed = false,
212
349
  syncCwd,
213
350
  result,
351
+ handBack = false,
214
352
  }) {
215
353
  const kind = result.kind ?? 'unknown';
354
+ const handedBack = resolveHandedBack({ result, baseConfirmed, handBack });
216
355
  const heading =
217
356
  kind === 'conflict'
218
357
  ? `Base-sync conflict on close: ${storyBranch} ↔ origin/${baseBranch}`
219
358
  : `Base-sync failed on close (${kind}): ${storyBranch} ↔ origin/${baseBranch}`;
220
- const fileList = (result.conflictFiles ?? []).map((f) => `- \`${f}\``);
221
- const lines = [
359
+ const advice = baseConfirmed
360
+ ? mergeAdvice({ storyId, syncCwd, baseBranch, handedBack })
361
+ : unconfirmedBaseAdvice({ storyId, storyBranch, baseBranch });
362
+ return [
222
363
  `### ${heading}`,
223
364
  '',
224
- '`/mandrel-deliver` close-validation passed, but the pre-push',
225
- `sync against \`origin/${baseBranch}\` could not complete. The Story has`,
226
- `been transitioned to \`agent::blocked\`. To resume:`,
365
+ ...commentLede(handedBack, baseBranch),
227
366
  '',
228
- ...(baseConfirmed
229
- ? [
230
- '```bash',
231
- `cd ${syncCwd}`,
232
- `git fetch origin ${baseBranch}`,
233
- `git merge --no-edit origin/${baseBranch}`,
234
- '# resolve any conflicts, then:',
235
- `git add -A ; git commit --no-edit`,
236
- '# re-run close:',
237
- `node .agents/scripts/single-story-close.js --story ${storyId}`,
238
- '```',
239
- ]
240
- : [
241
- `⚠️ **No merge advice: \`${baseBranch}\` is unconfirmed.** This close could not`,
242
- `read the base branch \`${storyBranch}\` was seeded from off the run's`,
243
- 'init receipt, so merging that base in could contaminate the branch',
244
- 'and its PR diff with an unrelated base. Establish the real base first —',
245
- `check \`temp/orchestration/story-init-result-${storyId}.log\` and \`project.baseBranch\` in`,
246
- '`.agentrc.json` / `.agentrc.local.json` — then merge that base and re-run:',
247
- '',
248
- '```bash',
249
- `node .agents/scripts/single-story-close.js --story ${storyId}`,
250
- '```',
251
- ]),
252
- ];
253
- if (kind === 'conflict' && fileList.length > 0) {
254
- lines.push('', '**Conflicting files:**', '', ...fileList);
255
- } else if (result.stderr) {
256
- lines.push(
257
- '',
258
- '**git stderr:**',
259
- '',
260
- '```',
261
- result.stderr.slice(0, 1000),
262
- '```',
263
- );
264
- }
265
- return lines.join('\n');
367
+ ...advice,
368
+ ...failureEvidence(kind, result),
369
+ ].join('\n');
266
370
  }
@@ -61,6 +61,11 @@ import {
61
61
  transitionTicketState,
62
62
  } from '../../ticketing.js';
63
63
  import { disarmAutoMerge } from './auto-merge.js';
64
+ import {
65
+ maybeRearmPr,
66
+ mergeWaitRecoverySeams,
67
+ settleDirtyPr,
68
+ } from './merge-wait-recovery.js';
64
69
  import { runPostLandTail as defaultRunPostLandTail } from './post-land.js';
65
70
 
66
71
  /** Per-invocation bound; fits the host's ~10-min tool ceiling after the gates. */
@@ -122,6 +127,18 @@ function readString(value, absent = undefined) {
122
127
  return typeof value === 'string' && value ? value : absent;
123
128
  }
124
129
 
130
+ /**
131
+ * Whether the PR carries an auto-merge request; `undefined` when the payload
132
+ * has no such field, so an unread field is never mistaken for a disarm.
133
+ *
134
+ * @param {object|null|undefined} view
135
+ * @returns {boolean|undefined}
136
+ */
137
+ function readAutoMergeArmed(view) {
138
+ if (!view || !Object.hasOwn(view, 'autoMergeRequest')) return undefined;
139
+ return view.autoMergeRequest != null;
140
+ }
141
+
125
142
  /**
126
143
  * `inMergeQueue` for a green open PR, the only state GitHub enqueues from;
127
144
  * `undefined` otherwise, so the common poll pays no extra call. An enqueued
@@ -170,6 +187,7 @@ export async function readPrWaitProbe({
170
187
  'reviewDecision',
171
188
  'statusCheckRollup',
172
189
  'headRefOid',
190
+ 'autoMergeRequest',
173
191
  ]),
174
192
  ghTimeoutMs,
175
193
  `gh pr view ${prNumber}`,
@@ -201,6 +219,7 @@ export async function readPrWaitProbe({
201
219
  }),
202
220
  redHeadRuns: deriveRedHeadRuns(view?.statusCheckRollup),
203
221
  headSha: readString(view?.headRefOid),
222
+ autoMergeArmed: readAutoMergeArmed(view),
204
223
  };
205
224
  } catch (err) {
206
225
  return {
@@ -942,6 +961,7 @@ async function onMergeObserved({
942
961
  emitMergeFlipFailedFn,
943
962
  prProbe,
944
963
  elapsedSeconds,
964
+ sleepFn,
945
965
  }) {
946
966
  const confirmation = await confirmStoryMergedFn({
947
967
  provider,
@@ -956,6 +976,8 @@ async function onMergeObserved({
956
976
  readPrMergeStateFn,
957
977
  // Saves confirmation a second `gh pr view`.
958
978
  prState: prProbe,
979
+ // The done-flip retry backs off on the wait's own clock.
980
+ sleepFn,
959
981
  });
960
982
 
961
983
  if (confirmation.merged && confirmation.action === 'flip-failed') {
@@ -1197,12 +1219,31 @@ function pendingAtWaitBound(ctx, decision, probe) {
1197
1219
  }
1198
1220
 
1199
1221
  /**
1200
- * Advisory gates are usually still QUEUED at arm time, so they redden here,
1201
- * mid-wait, before auto-merge lands over them.
1222
+ * A DIRTY PR is synced (or handed back) before anything else reads the
1223
+ * probe; a synced one skips the rest of this poll's recovery, since the
1224
+ * probe describes the head it just replaced.
1202
1225
  *
1203
1226
  * @returns {Promise<{ state: object, outcome: object|null }>}
1204
1227
  */
1205
1228
  async function settleProvisional(ctx, decision, probe) {
1229
+ const dirty = await settleDirtyPr(ctx, decision.state, probe);
1230
+ if (dirty?.outcome) return dirty;
1231
+ const recovered = dirty ?? (await recoverOpenPr(ctx, decision, probe));
1232
+ if (recovered.outcome) return recovered;
1233
+ return {
1234
+ state: recovered.state,
1235
+ outcome: await settleVerdict(ctx, decision, probe),
1236
+ };
1237
+ }
1238
+
1239
+ /**
1240
+ * Advisory gates are usually still QUEUED at arm time, so they redden here,
1241
+ * mid-wait, before auto-merge lands over them. Then the re-arm rule, then the
1242
+ * BEHIND update.
1243
+ *
1244
+ * @returns {Promise<{ state: object, outcome: object|null }>}
1245
+ */
1246
+ async function recoverOpenPr(ctx, decision, probe) {
1206
1247
  const advisory = await resolveAdvisoryUnlanded({
1207
1248
  probe,
1208
1249
  blockOnAdvisoryFailure: ctx.blockOnAdvisoryFailure,
@@ -1218,6 +1259,7 @@ async function settleProvisional(ctx, decision, probe) {
1218
1259
  if (advisory) {
1219
1260
  return { state: decision.state, outcome: await blockWith(ctx, advisory) };
1220
1261
  }
1262
+ await maybeRearmPr(ctx, probe);
1221
1263
  const updated = await maybeUpdateBehindPr({
1222
1264
  probe,
1223
1265
  prNumber: ctx.prNumber,
@@ -1230,8 +1272,13 @@ async function settleProvisional(ctx, decision, probe) {
1230
1272
  const state = updated
1231
1273
  ? { ...decision.state, updatesUsed: decision.state.updatesUsed + 1 }
1232
1274
  : decision.state;
1275
+ return { state, outcome: null };
1276
+ }
1277
+
1278
+ /** The provisional verdict's own ending: budget block, `pending`, or none. */
1279
+ async function settleVerdict(ctx, decision, probe) {
1233
1280
  if (decision.verdict === 'budget-exhausted') {
1234
- const outcome = await blockWith(ctx, {
1281
+ return await blockWith(ctx, {
1235
1282
  prProbe: probe,
1236
1283
  budget: {
1237
1284
  exhausted: true,
@@ -1239,12 +1286,11 @@ async function settleProvisional(ctx, decision, probe) {
1239
1286
  },
1240
1287
  ...queuedExhaustionVerdict(probe, decision.cumulativeMs),
1241
1288
  });
1242
- return { state, outcome };
1243
1289
  }
1244
1290
  if (Object.hasOwn(PENDING_HEADLINES, decision.verdict)) {
1245
- return { state, outcome: pendingAtWaitBound(ctx, decision, probe) };
1291
+ return pendingAtWaitBound(ctx, decision, probe);
1246
1292
  }
1247
- return { state, outcome: null };
1293
+ return null;
1248
1294
  }
1249
1295
 
1250
1296
  /** @returns {Promise<{ state: object, done: boolean, outcome?: object }>} */
@@ -1324,6 +1370,7 @@ function blockNeverArmed({
1324
1370
  *
1325
1371
  * @param {object} args
1326
1372
  * @param {string} args.cwd The MAIN checkout.
1373
+ * @param {string|null} [args.worktreePath] The Story worktree a DIRTY sync runs in.
1327
1374
  * @param {number} args.storyId
1328
1375
  * @param {string} [args.storyBranch]
1329
1376
  * @param {string} [args.baseBranch]
@@ -1346,6 +1393,7 @@ function blockNeverArmed({
1346
1393
  * @param {Function} [args.runPostLandTailFn]
1347
1394
  * @param {Function} [args.disarmAutoMergeFn]
1348
1395
  * @param {Function} [args.recordRequiredRedFn] The shared first-red handling (disarm + CI digest).
1396
+ * @param {object} [args.recoverySeams] DIRTY-sync / re-arm seams (`mergeWaitRecoverySeams`).
1349
1397
  * @param {(ms: number) => Promise<void>} [args.sleepFn]
1350
1398
  * @param {() => number} [args.nowMsFn]
1351
1399
  * @param {number} [args.ghTimeoutMs] Test seam only, not config.
@@ -1367,6 +1415,7 @@ export async function runConfirmMergePhase({
1367
1415
  sleepFn = defaultSleep,
1368
1416
  nowMsFn = Date.now,
1369
1417
  ghTimeoutMs = MERGE_WAIT_GH_TIMEOUT_MS,
1418
+ recoverySeams,
1370
1419
  ...args
1371
1420
  }) {
1372
1421
  if (!args.autoMergeEnabled) {
@@ -1401,6 +1450,7 @@ export async function runConfirmMergePhase({
1401
1450
  issued: new Set(),
1402
1451
  },
1403
1452
  confirmStoryMergedFn,
1453
+ sleepFn,
1404
1454
  readPrWaitProbeFn,
1405
1455
  readPrMergeStateFn,
1406
1456
  classifyMergeBlockFn,
@@ -1411,6 +1461,8 @@ export async function runConfirmMergePhase({
1411
1461
  recordRequiredRedFn,
1412
1462
  nowMsFn,
1413
1463
  ghTimeoutMs,
1464
+ waitGh: args.injectedGh ?? defaultGh,
1465
+ ...mergeWaitRecoverySeams(recoverySeams),
1414
1466
  };
1415
1467
  let state = createMergeWaitState({
1416
1468
  startedAtMs: nowMsFn(),