mandrel 2.71.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 (21) hide show
  1. package/.agents/schemas/story-deliver-terminal.schema.json +10 -1
  2. package/.agents/scripts/lib/orchestration/cancelled-run-discount.js +129 -0
  3. package/.agents/scripts/lib/orchestration/deliver-recover.js +166 -34
  4. package/.agents/scripts/lib/orchestration/pr-watch.js +14 -3
  5. package/.agents/scripts/lib/orchestration/single-story-close/phases/auto-merge.js +45 -0
  6. package/.agents/scripts/lib/orchestration/single-story-close/phases/base-sync.js +13 -4
  7. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +54 -6
  8. package/.agents/scripts/lib/orchestration/single-story-close/phases/merge-wait-recovery.js +296 -0
  9. package/.agents/scripts/lib/orchestration/single-story-close/phases/post-land.js +52 -6
  10. package/.agents/scripts/lib/orchestration/single-story-close/phases/pull-request.js +2 -2
  11. package/.agents/scripts/lib/orchestration/single-story-close/phases/story-branch-catch-up.js +50 -0
  12. package/.agents/scripts/lib/orchestration/single-story-close/phases/worktree-reap.js +64 -52
  13. package/.agents/scripts/lib/orchestration/single-story-close/phases/worktree-restore.js +133 -0
  14. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +161 -57
  15. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +46 -6
  16. package/.agents/scripts/pr-watch-with-update.js +5 -0
  17. package/.agents/scripts/single-story-confirm-merge.js +34 -3
  18. package/.agents/workflows/helpers/deliver-story-reference.md +28 -9
  19. package/.agents/workflows/helpers/worktree-lifecycle.md +5 -5
  20. package/docs/CHANGELOG.md +12 -0
  21. package/package.json +1 -1
@@ -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 {
@@ -1200,12 +1219,31 @@ function pendingAtWaitBound(ctx, decision, probe) {
1200
1219
  }
1201
1220
 
1202
1221
  /**
1203
- * Advisory gates are usually still QUEUED at arm time, so they redden here,
1204
- * 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.
1205
1225
  *
1206
1226
  * @returns {Promise<{ state: object, outcome: object|null }>}
1207
1227
  */
1208
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) {
1209
1247
  const advisory = await resolveAdvisoryUnlanded({
1210
1248
  probe,
1211
1249
  blockOnAdvisoryFailure: ctx.blockOnAdvisoryFailure,
@@ -1221,6 +1259,7 @@ async function settleProvisional(ctx, decision, probe) {
1221
1259
  if (advisory) {
1222
1260
  return { state: decision.state, outcome: await blockWith(ctx, advisory) };
1223
1261
  }
1262
+ await maybeRearmPr(ctx, probe);
1224
1263
  const updated = await maybeUpdateBehindPr({
1225
1264
  probe,
1226
1265
  prNumber: ctx.prNumber,
@@ -1233,8 +1272,13 @@ async function settleProvisional(ctx, decision, probe) {
1233
1272
  const state = updated
1234
1273
  ? { ...decision.state, updatesUsed: decision.state.updatesUsed + 1 }
1235
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) {
1236
1280
  if (decision.verdict === 'budget-exhausted') {
1237
- const outcome = await blockWith(ctx, {
1281
+ return await blockWith(ctx, {
1238
1282
  prProbe: probe,
1239
1283
  budget: {
1240
1284
  exhausted: true,
@@ -1242,12 +1286,11 @@ async function settleProvisional(ctx, decision, probe) {
1242
1286
  },
1243
1287
  ...queuedExhaustionVerdict(probe, decision.cumulativeMs),
1244
1288
  });
1245
- return { state, outcome };
1246
1289
  }
1247
1290
  if (Object.hasOwn(PENDING_HEADLINES, decision.verdict)) {
1248
- return { state, outcome: pendingAtWaitBound(ctx, decision, probe) };
1291
+ return pendingAtWaitBound(ctx, decision, probe);
1249
1292
  }
1250
- return { state, outcome: null };
1293
+ return null;
1251
1294
  }
1252
1295
 
1253
1296
  /** @returns {Promise<{ state: object, done: boolean, outcome?: object }>} */
@@ -1327,6 +1370,7 @@ function blockNeverArmed({
1327
1370
  *
1328
1371
  * @param {object} args
1329
1372
  * @param {string} args.cwd The MAIN checkout.
1373
+ * @param {string|null} [args.worktreePath] The Story worktree a DIRTY sync runs in.
1330
1374
  * @param {number} args.storyId
1331
1375
  * @param {string} [args.storyBranch]
1332
1376
  * @param {string} [args.baseBranch]
@@ -1349,6 +1393,7 @@ function blockNeverArmed({
1349
1393
  * @param {Function} [args.runPostLandTailFn]
1350
1394
  * @param {Function} [args.disarmAutoMergeFn]
1351
1395
  * @param {Function} [args.recordRequiredRedFn] The shared first-red handling (disarm + CI digest).
1396
+ * @param {object} [args.recoverySeams] DIRTY-sync / re-arm seams (`mergeWaitRecoverySeams`).
1352
1397
  * @param {(ms: number) => Promise<void>} [args.sleepFn]
1353
1398
  * @param {() => number} [args.nowMsFn]
1354
1399
  * @param {number} [args.ghTimeoutMs] Test seam only, not config.
@@ -1370,6 +1415,7 @@ export async function runConfirmMergePhase({
1370
1415
  sleepFn = defaultSleep,
1371
1416
  nowMsFn = Date.now,
1372
1417
  ghTimeoutMs = MERGE_WAIT_GH_TIMEOUT_MS,
1418
+ recoverySeams,
1373
1419
  ...args
1374
1420
  }) {
1375
1421
  if (!args.autoMergeEnabled) {
@@ -1415,6 +1461,8 @@ export async function runConfirmMergePhase({
1415
1461
  recordRequiredRedFn,
1416
1462
  nowMsFn,
1417
1463
  ghTimeoutMs,
1464
+ waitGh: args.injectedGh ?? defaultGh,
1465
+ ...mergeWaitRecoverySeams(recoverySeams),
1418
1466
  };
1419
1467
  let state = createMergeWaitState({
1420
1468
  startedAtMs: nowMsFn(),
@@ -0,0 +1,296 @@
1
+ /**
2
+ * phases/merge-wait-recovery.js — the merge wait's answer to a PR `main`
3
+ * moved under. DIRTY: sync in the Story worktree and push, spending the
4
+ * BEHIND budget; any failure hands back a `failed` / `base-sync` outcome,
5
+ * labels untouched. Un-armed: re-arm once per head SHA, behind the red-fix
6
+ * guard and the arm policy.
7
+ */
8
+
9
+ import { getCiDelivery } from '../../../config/ci.js';
10
+ import { syncBranchFromBase as defaultSyncBranchFromBase } from '../../../git/sync-from-base.js';
11
+ import { gitSpawn } from '../../../git-utils.js';
12
+ import {
13
+ classifyGreenVerdict,
14
+ readCiDigest as defaultReadCiDigest,
15
+ } from '../../ci-rerun-guard.js';
16
+ import { rearmAutoMerge as defaultRearmAutoMerge } from './auto-merge.js';
17
+ import { handleSyncFailure as defaultHandleSyncFailure } from './base-sync.js';
18
+ import { pushStoryBranch as defaultPushStoryBranch } from './push.js';
19
+ import { integrateRemoteStoryBranch as defaultIntegrateRemote } from './story-branch-catch-up.js';
20
+
21
+ /** The red-fix guard verdicts under which a re-arm is allowed. */
22
+ const REARM_VERDICTS = Object.freeze([
23
+ 'clean',
24
+ 'fix-at-source',
25
+ 'rerun-permitted',
26
+ ]);
27
+
28
+ function defaultCurrentBranch(cwd) {
29
+ const head = gitSpawn(cwd, 'rev-parse', '--abbrev-ref', 'HEAD');
30
+ return head.status === 0 ? String(head.stdout ?? '').trim() : null;
31
+ }
32
+
33
+ /** Defaults for every seam this module reads off the wait's `ctx`. */
34
+ export function mergeWaitRecoverySeams({
35
+ syncBranchFromBaseFn = defaultSyncBranchFromBase,
36
+ pushStoryBranchFn = defaultPushStoryBranch,
37
+ handleSyncFailureFn = defaultHandleSyncFailure,
38
+ rearmAutoMergeFn = defaultRearmAutoMerge,
39
+ readCiDigestFn = defaultReadCiDigest,
40
+ integrateRemoteFn = defaultIntegrateRemote,
41
+ currentBranchFn = defaultCurrentBranch,
42
+ } = {}) {
43
+ return {
44
+ integrateRemoteFn,
45
+ currentBranchFn,
46
+ syncBranchFromBaseFn,
47
+ pushStoryBranchFn,
48
+ handleSyncFailureFn,
49
+ rearmAutoMergeFn,
50
+ readCiDigestFn,
51
+ rearmedHeads: new Set(),
52
+ };
53
+ }
54
+
55
+ function isOpenDirty(probe) {
56
+ return (
57
+ probe?.state === 'OPEN' &&
58
+ !probe?.mergedAt &&
59
+ probe?.mergeStateStatus === 'DIRTY'
60
+ );
61
+ }
62
+
63
+ function syncCwdOf(ctx) {
64
+ return ctx.worktreePath ?? ctx.cwd;
65
+ }
66
+
67
+ function describeSyncFailure({
68
+ storyId,
69
+ prNumber,
70
+ baseBranch,
71
+ syncCwd,
72
+ result,
73
+ }) {
74
+ const files = result.conflictFiles ?? [];
75
+ const evidence =
76
+ files.length > 0
77
+ ? `conflicting files = ${files.join(', ')}`
78
+ : String(result.stderr ?? '')
79
+ .trim()
80
+ .slice(0, 300) || 'no detail';
81
+ return (
82
+ `PR #${prNumber} is DIRTY against origin/${baseBranch} and the merge-wait base sync ` +
83
+ `could not land it (${result.kind}): ${evidence}. Labels unchanged — resolve it in the ` +
84
+ `Story worktree ${syncCwd} (git merge --no-edit origin/${baseBranch}, fix, commit), ` +
85
+ `then re-run close for Story #${storyId}.`
86
+ );
87
+ }
88
+
89
+ /**
90
+ * The Story worktree, resolved only when a DIRTY sync needs it, so a missing
91
+ * one never stands between a resume and an already-merged PR.
92
+ *
93
+ * @returns {Promise<object|null>} a failed sync result, or null when ready.
94
+ */
95
+ async function resolveDirtyWorktree(ctx) {
96
+ const resolve = ctx.resolveWorktree;
97
+ if (typeof resolve !== 'function') return null;
98
+ ctx.resolveWorktree = null;
99
+ try {
100
+ ctx.worktreePath = await resolve();
101
+ return null;
102
+ } catch (err) {
103
+ return {
104
+ synced: false,
105
+ kind: 'worktree-unavailable',
106
+ stderr: String(err?.message ?? err),
107
+ };
108
+ }
109
+ }
110
+
111
+ /**
112
+ * Merge only into `story-<id>`: with no worktree the sync runs in the main
113
+ * checkout, which a `--wait` resume may find on `main` or anything else.
114
+ *
115
+ * @returns {object|null} a failed sync result, or null when on the branch.
116
+ */
117
+ function refuseWrongTree(ctx) {
118
+ const branch = ctx.currentBranchFn(syncCwdOf(ctx));
119
+ if (branch === ctx.storyBranch) return null;
120
+ return {
121
+ synced: false,
122
+ kind: 'wrong-tree',
123
+ stderr: `${syncCwdOf(ctx)} has ${branch ?? 'no readable branch'} checked out, not ${ctx.storyBranch} — nothing was merged`,
124
+ };
125
+ }
126
+
127
+ /**
128
+ * `origin/<story>` first (a BEHIND update merged there only), then the base.
129
+ *
130
+ * @returns {Promise<object>} a `syncBranchFromBase`-shaped result.
131
+ */
132
+ async function syncDirtyHead(ctx) {
133
+ const unavailable = await resolveDirtyWorktree(ctx);
134
+ if (unavailable) return unavailable;
135
+ const wrongTree = refuseWrongTree(ctx);
136
+ if (wrongTree) return wrongTree;
137
+ const remote = ctx.integrateRemoteFn({
138
+ cwd: syncCwdOf(ctx),
139
+ storyBranch: ctx.storyBranch,
140
+ });
141
+ if (!remote.ok) {
142
+ return { synced: false, kind: 'remote-diverged', stderr: remote.stderr };
143
+ }
144
+ return ctx.syncBranchFromBaseFn({
145
+ cwd: syncCwdOf(ctx),
146
+ baseBranch: ctx.baseBranch,
147
+ log: (tag, msg) => ctx.progress?.(tag, msg),
148
+ });
149
+ }
150
+
151
+ /** Friction through the pre-PR SYNC's own path, labels left alone. */
152
+ async function handBackDirty(ctx, probe, result) {
153
+ const syncCwd = syncCwdOf(ctx);
154
+ await ctx.handleSyncFailureFn({
155
+ provider: ctx.provider,
156
+ storyId: ctx.storyId,
157
+ syncCwd,
158
+ baseBranch: ctx.baseBranch,
159
+ baseConfirmed: true,
160
+ storyBranch: ctx.storyBranch,
161
+ result,
162
+ handBack: true,
163
+ progress: (tag, msg) => ctx.progress?.(tag, msg),
164
+ });
165
+ return {
166
+ confirmed: false,
167
+ terminal: 'failed',
168
+ phase: 'base-sync',
169
+ reason: describeSyncFailure({
170
+ storyId: ctx.storyId,
171
+ prNumber: ctx.prNumber,
172
+ baseBranch: ctx.baseBranch,
173
+ syncCwd,
174
+ result,
175
+ }),
176
+ prProbe: probe,
177
+ };
178
+ }
179
+
180
+ /** @returns {{ ok: true }|{ ok: false, result: object }} */
181
+ function pushSynced(ctx) {
182
+ try {
183
+ ctx.pushStoryBranchFn({
184
+ cwd: ctx.cwd,
185
+ worktreePath: ctx.worktreePath ?? null,
186
+ storyBranch: ctx.storyBranch,
187
+ progress: (tag, msg) => ctx.progress?.(tag, msg),
188
+ });
189
+ return { ok: true };
190
+ } catch (err) {
191
+ return {
192
+ ok: false,
193
+ result: { kind: 'push-failed', stderr: String(err?.message ?? err) },
194
+ };
195
+ }
196
+ }
197
+
198
+ /**
199
+ * `null` when the PR is not DIRTY; else the next state and a `null` outcome
200
+ * (synced and pushed) or the `failed` one.
201
+ *
202
+ * @returns {Promise<{ state: object, outcome: object|null }|null>}
203
+ */
204
+ export async function settleDirtyPr(ctx, state, probe) {
205
+ if (!isOpenDirty(probe)) return null;
206
+ const budget = ctx.limits.updateAttempts;
207
+ if (state.updatesUsed >= budget) {
208
+ return {
209
+ state,
210
+ outcome: await handBackDirty(ctx, probe, {
211
+ kind: 'conflict',
212
+ conflictFiles: [],
213
+ stderr: `the PR is still DIRTY after ${budget} merge-wait base sync(s) — the update budget is spent`,
214
+ }),
215
+ };
216
+ }
217
+ ctx.progress?.(
218
+ 'CONFIRM',
219
+ `🔀 PR #${ctx.prNumber} is DIRTY — merging origin/${ctx.baseBranch} in the Story worktree ` +
220
+ `(attempt ${state.updatesUsed + 1}/${budget}).`,
221
+ );
222
+ const result = await syncDirtyHead(ctx);
223
+ // An already-current branch spends nothing: GitHub is still recomputing.
224
+ const spent =
225
+ result.kind === 'noop-already-current'
226
+ ? state
227
+ : { ...state, updatesUsed: state.updatesUsed + 1 };
228
+ if (!result.synced) {
229
+ return { state: spent, outcome: await handBackDirty(ctx, probe, result) };
230
+ }
231
+ const pushed = pushSynced(ctx);
232
+ if (!pushed.ok) {
233
+ return {
234
+ state: spent,
235
+ outcome: await handBackDirty(ctx, probe, pushed.result),
236
+ };
237
+ }
238
+ ctx.progress?.(
239
+ 'CONFIRM',
240
+ `✅ PR #${ctx.prNumber}: synced from origin/${ctx.baseBranch} (${result.kind}) and pushed — still waiting.`,
241
+ );
242
+ return { state: spent, outcome: null };
243
+ }
244
+
245
+ /** Re-arm only a PR close itself armed (`ctx.closeArmed`), never an operator's. */
246
+ function isUnarmedOpenPr(probe, ctx) {
247
+ return (
248
+ ctx.closeArmed === true &&
249
+ probe?.state === 'OPEN' &&
250
+ !probe?.mergedAt &&
251
+ probe?.inMergeQueue !== true &&
252
+ probe?.autoMergeArmed === false &&
253
+ probe?.checksStatus !== 'failure'
254
+ );
255
+ }
256
+
257
+ /** The red-fix guard: a CI digest recorded against this head blocks it. */
258
+ function rearmGuard(ctx, headSha) {
259
+ const digest = ctx.readCiDigestFn({
260
+ storyId: ctx.storyId,
261
+ tempRoot: ctx.config?.project?.paths?.tempRoot ?? 'temp',
262
+ cwd: ctx.cwd,
263
+ });
264
+ return classifyGreenVerdict({ digest, headSha });
265
+ }
266
+
267
+ /** Re-arm an open, un-armed, not-red PR once per head; never a terminal. */
268
+ export async function maybeRearmPr(ctx, probe) {
269
+ const headSha = probe?.headSha;
270
+ if (
271
+ !isUnarmedOpenPr(probe, ctx) ||
272
+ !headSha ||
273
+ ctx.rearmedHeads.has(headSha)
274
+ ) {
275
+ return;
276
+ }
277
+ ctx.rearmedHeads.add(headSha);
278
+ if (getCiDelivery(ctx.config).autoMerge === 'strict') return;
279
+ const guard = rearmGuard(ctx, headSha);
280
+ if (!REARM_VERDICTS.includes(guard.verdict)) {
281
+ ctx.progress?.(
282
+ 'CONFIRM',
283
+ `⏭ PR #${ctx.prNumber} has no auto-merge request, but it is not re-armed (${guard.verdict}: ${guard.reason}).`,
284
+ );
285
+ return;
286
+ }
287
+ const armed = await ctx
288
+ .rearmAutoMergeFn({ cwd: ctx.cwd, prNumber: ctx.prNumber, gh: ctx.waitGh })
289
+ .catch((err) => ({ enabled: false, reason: String(err?.message ?? err) }));
290
+ ctx.progress?.(
291
+ 'CONFIRM',
292
+ armed?.enabled
293
+ ? `🔁 PR #${ctx.prNumber} lost its auto-merge request on head ${headSha.slice(0, 7)} — re-armed.`
294
+ : `⚠️ PR #${ctx.prNumber} re-arm failed (${armed?.reason ?? 'unknown'}) — still waiting.`,
295
+ );
296
+ }
@@ -28,6 +28,8 @@ import { reapPlanRunLabelsForStory as defaultReapPlanRunLabelsForStory } from '.
28
28
  import { reassertStatusColumn as defaultReassertStatusColumn } from '../../reassert-status-column.js';
29
29
  import { releaseStoryLease as defaultReleaseStoryLease } from '../../single-story-lease-guard.js';
30
30
  import { captureStoryFollowUps as defaultCaptureStoryFollowUps } from '../../story-follow-ups.js';
31
+ import { reapWorktreePhase as defaultReapWorktreePhase } from './worktree-reap.js';
32
+ import { existingWorktreePath } from './worktree-restore.js';
31
33
 
32
34
  /**
33
35
  * Under the MAIN checkout's `.git`, so every concurrent close contends on one file.
@@ -119,6 +121,31 @@ async function stepStatusResync({
119
121
  };
120
122
  }
121
123
 
124
+ /**
125
+ * The one place the Story worktree is reaped. Nothing to reap is success
126
+ * (detail says why); a refusal degrades. `detail` is null only on removal.
127
+ */
128
+ async function stepWorktreeReap({
129
+ cwd,
130
+ storyId,
131
+ config,
132
+ progress,
133
+ reapWorktreePhaseFn,
134
+ }) {
135
+ const wtIsolation = config?.delivery?.worktreeIsolation;
136
+ const outcome = await reapWorktreePhaseFn({
137
+ cwd,
138
+ storyId,
139
+ worktreePath: existingWorktreePath({ cwd, wtIsolation, storyId }),
140
+ wtIsolation,
141
+ progress: (tag, msg) => progress?.(tag, msg),
142
+ });
143
+ return {
144
+ ok: outcome?.removed === true || outcome?.skipped === true,
145
+ detail: outcome?.removed === true ? null : (outcome?.reason ?? 'unknown'),
146
+ };
147
+ }
148
+
122
149
  /** Reap the local `story-<id>` ref; already absent is success. */
123
150
  async function stepRefCleanup({ cwd, storyBranch, progress, gitSpawnFn }) {
124
151
  const exists = gitSpawnFn(
@@ -282,9 +309,11 @@ async function stepPlanRunLabelReap({
282
309
  }
283
310
 
284
311
  /**
285
- * The local-checkout mutations (ref reap first, then fast-forward) under a
286
- * cross-process lock on the main checkout, since concurrent closes race on
287
- * the base ref and worktree registry. Best-effort: on timeout they run anyway.
312
+ * The local-checkout mutations (worktree reap, then ref reap, then
313
+ * fast-forward) under a cross-process lock on the main checkout, since
314
+ * concurrent closes race on the base ref and worktree registry. The worktree
315
+ * goes first: `git branch -D` refuses a branch a live worktree holds.
316
+ * Best-effort: on timeout they run anyway.
288
317
  */
289
318
  async function runLockedLocalSteps({
290
319
  storyId,
@@ -297,6 +326,7 @@ async function runLockedLocalSteps({
297
326
  planFastForwardFn,
298
327
  executeFastForwardFn,
299
328
  acquireLockWithWaitFn,
329
+ reapWorktreePhaseFn,
300
330
  }) {
301
331
  const lockCfg = config?.delivery?.postLandLock ?? {};
302
332
  const lock = await acquireLockWithWaitFn({
@@ -313,6 +343,17 @@ async function runLockedLocalSteps({
313
343
  );
314
344
  }
315
345
  try {
346
+ const worktreeReap = await step(
347
+ () =>
348
+ stepWorktreeReap({
349
+ cwd,
350
+ storyId,
351
+ config,
352
+ progress,
353
+ reapWorktreePhaseFn,
354
+ }),
355
+ { name: 'worktree reap', progress },
356
+ );
316
357
  const refCleanup = await step(
317
358
  () => stepRefCleanup({ cwd, storyBranch, progress, gitSpawnFn }),
318
359
  { name: 'local ref cleanup', progress },
@@ -328,7 +369,7 @@ async function runLockedLocalSteps({
328
369
  }),
329
370
  { name: 'base fast-forward', progress },
330
371
  );
331
- return { refCleanup, baseFastForward };
372
+ return { worktreeReap, refCleanup, baseFastForward };
332
373
  } finally {
333
374
  if (lock.acquired) lock.release();
334
375
  }
@@ -358,7 +399,8 @@ async function runLockedLocalSteps({
358
399
  * @param {Function} [args.releaseStoryLeaseFn]
359
400
  * @param {Function} [args.reapPlanRunLabelsForStoryFn]
360
401
  * @param {Function} [args.rollUpEpicForStoryFn]
361
- * @returns {Promise<{ followUps: boolean, statusResync: boolean, refCleanup: boolean, baseFastForward: boolean, tempPurge: boolean, leaseRelease: boolean, epicRollup: boolean, details: Record<string, string|null> }>}
402
+ * @param {Function} [args.reapWorktreePhaseFn]
403
+ * @returns {Promise<{ followUps: boolean, statusResync: boolean, worktreeReap: boolean, refCleanup: boolean, baseFastForward: boolean, tempPurge: boolean, leaseRelease: boolean, epicRollup: boolean, details: Record<string, string|null> }>}
362
404
  */
363
405
  export async function runPostLandTail({
364
406
  storyId,
@@ -380,6 +422,7 @@ export async function runPostLandTail({
380
422
  releaseStoryLeaseFn = defaultReleaseStoryLease,
381
423
  reapPlanRunLabelsForStoryFn = defaultReapPlanRunLabelsForStory,
382
424
  rollUpEpicForStoryFn = defaultRollUpEpicForStory,
425
+ reapWorktreePhaseFn = defaultReapWorktreePhase,
383
426
  }) {
384
427
  progress?.('POST-LAND', `🧾 Running land tail for Story #${storyId}...`);
385
428
 
@@ -456,9 +499,10 @@ export async function runPostLandTail({
456
499
  planFastForwardFn,
457
500
  executeFastForwardFn,
458
501
  acquireLockWithWaitFn,
502
+ reapWorktreePhaseFn,
459
503
  }),
460
504
  ]);
461
- const { refCleanup, baseFastForward } = local;
505
+ const { worktreeReap, refCleanup, baseFastForward } = local;
462
506
 
463
507
  // After every step that reads the temp artifacts; `signals.ndjson` survives.
464
508
  const tempPurge = await step(
@@ -481,6 +525,7 @@ export async function runPostLandTail({
481
525
  const tail = {
482
526
  followUps: followUps.ok,
483
527
  statusResync: statusResync.ok,
528
+ worktreeReap: worktreeReap.ok,
484
529
  refCleanup: refCleanup.ok,
485
530
  baseFastForward: baseFastForward.ok,
486
531
  tempPurge: tempPurge.ok,
@@ -489,6 +534,7 @@ export async function runPostLandTail({
489
534
  details: {
490
535
  followUps: followUps.detail,
491
536
  statusResync: statusResync.detail,
537
+ worktreeReap: worktreeReap.detail,
492
538
  refCleanup: refCleanup.detail,
493
539
  baseFastForward: baseFastForward.detail,
494
540
  tempPurge: tempPurge.detail,
@@ -15,12 +15,12 @@ import { buildPullRequestFields } from './normalize-pr-title.js';
15
15
  /**
16
16
  * OPEN wins, then the first MERGED; CLOSED-only resolves to null. A row with
17
17
  * no recognizable `state` reads as live, since guessing "no PR" opens a
18
- * duplicate. Module-private: a test-only export would trip dead-exports.
18
+ * duplicate. Close's landed short-circuit reads heads the same way.
19
19
  *
20
20
  * @param {Array<{url?: string, state?: string, mergedAt?: string}>} rows
21
21
  * @returns {{ url: string, state: 'OPEN'|'MERGED' }|null}
22
22
  */
23
- function pickHeadPullRequest(rows) {
23
+ export function pickHeadPullRequest(rows) {
24
24
  if (!Array.isArray(rows)) return null;
25
25
  let merged = null;
26
26
  for (const row of rows) {
@@ -0,0 +1,50 @@
1
+ /**
2
+ * phases/story-branch-catch-up.js — keep the Story worktree's branch level
3
+ * with `origin/story-<id>` before close or the merge wait pushes from it.
4
+ */
5
+
6
+ import { gitSpawn as defaultGitSpawn } from '../../../git-utils.js';
7
+
8
+ /**
9
+ * Bring the worktree's branch up to `origin/<branch>`: a remote
10
+ * `gh pr update-branch` merge lands only there, and a push from behind it is
11
+ * rejected. `ffOnly` never creates a merge; a failed merge is aborted.
12
+ *
13
+ * @returns {{ ok: boolean, skipped?: boolean, stderr?: string }}
14
+ */
15
+ export function integrateRemoteStoryBranch({
16
+ cwd,
17
+ storyBranch,
18
+ gitSpawn = defaultGitSpawn,
19
+ ffOnly = false,
20
+ }) {
21
+ const fetched = gitSpawn(cwd, 'fetch', 'origin', storyBranch);
22
+ if (fetched.status !== 0) return { ok: true, skipped: true };
23
+ const mode = ffOnly ? '--ff-only' : '--no-edit';
24
+ const merged = gitSpawn(cwd, 'merge', mode, `origin/${storyBranch}`);
25
+ if (merged.status === 0) return { ok: true };
26
+ if (!ffOnly) gitSpawn(cwd, 'merge', '--abort');
27
+ return { ok: false, stderr: String(merged.stderr ?? '') };
28
+ }
29
+
30
+ /** Best-effort ff-only catch-up; a refusal is one warning line. */
31
+ export function catchUpWithOrigin({
32
+ worktreePath,
33
+ storyBranch,
34
+ gitSpawn,
35
+ progress,
36
+ }) {
37
+ const caught = integrateRemoteStoryBranch({
38
+ cwd: worktreePath,
39
+ storyBranch,
40
+ gitSpawn,
41
+ ffOnly: true,
42
+ });
43
+ if (!caught.ok) {
44
+ progress(
45
+ 'WORKTREE',
46
+ `⚠️ ${storyBranch} could not fast-forward to origin/${storyBranch}: ${caught.stderr.trim()}`,
47
+ );
48
+ }
49
+ return worktreePath;
50
+ }