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
@@ -1,64 +1,76 @@
1
1
  /**
2
- * phases/worktree-reap.js — best-effort reap of the per-Story worktree once
3
- * the PR is open. `reap` refuses by RETURNING `{ removed: false }`, so report
4
- * what happened, never merely that the call did not throw.
2
+ * phases/worktree-reap.js — best-effort reap of the per-Story worktree, run
3
+ * only by the post-land tail. `reap` refuses by RETURNING
4
+ * `{ removed: false }`, so report what happened, not that nothing threw.
5
5
  */
6
6
 
7
7
  import { Logger } from '../../../Logger.js';
8
8
  import { WorktreeManager as DefaultWorktreeManager } from '../../../worktree-manager.js';
9
9
 
10
+ function skippedOutcome(worktreePath) {
11
+ const reason = worktreePath ? 'reap-disabled' : 'no-worktree';
12
+ return { removed: false, skipped: true, reason };
13
+ }
14
+
15
+ function reapOutcome(result) {
16
+ const removed = result?.removed === true;
17
+ return {
18
+ removed,
19
+ skipped: result?.skipped === true,
20
+ reason: result?.reason ?? null,
21
+ };
22
+ }
23
+
24
+ function failedOutcome(err) {
25
+ const reason = String(err?.message ?? err);
26
+ Logger.error(`[worktree-reap] ⚠️ Failed to reap worktree: ${reason}`);
27
+ return { removed: false, skipped: false, reason };
28
+ }
29
+
30
+ function reportReap(outcome, { storyId, worktreePath, progress }) {
31
+ if (outcome.removed) {
32
+ progress('WORKTREE', `🧹 Reaped worktree for story-${storyId}.`);
33
+ return;
34
+ }
35
+ progress(
36
+ 'WORKTREE',
37
+ `⚠️ Worktree for story-${storyId} not reaped (${outcome.reason ?? 'unknown reason'}) — ` +
38
+ `${worktreePath} left in place for the next sweep.`,
39
+ );
40
+ }
41
+
42
+ function createManager({ WorktreeManager, cwd, wtIsolation, progress }) {
43
+ return new WorktreeManager({
44
+ repoRoot: cwd,
45
+ config: wtIsolation,
46
+ logger: {
47
+ info: (m) => progress('WORKTREE', m),
48
+ warn: (m) => progress('WORKTREE', `⚠️ ${m}`),
49
+ error: (m) => Logger.error(`[worktree-reap] ${m}`),
50
+ },
51
+ });
52
+ }
53
+
54
+ async function reapNow(args) {
55
+ const wm = createManager(args);
56
+ // NO base ref: a squash merge never makes the branch reachable from the
57
+ // base. Safe because the work is merged; a dirty tree is still refused.
58
+ const outcome = reapOutcome(await wm.reap(args.storyId));
59
+ reportReap(outcome, args);
60
+ return outcome;
61
+ }
62
+
10
63
  /**
11
- * @param {{
12
- * cwd: string,
13
- * storyId: number,
14
- * worktreePath: string|null,
15
- * wtIsolation: object|undefined,
16
- * progress: (tag: string, msg: string) => void,
17
- * }} args
18
- * @returns {Promise<boolean>} `true` only when the worktree was actually
19
- * removed — never merely because the call did not throw.
64
+ * `skipped`: nothing to do (no worktree, reap disabled, isolation off).
65
+ *
66
+ * @returns {Promise<{ removed: boolean, skipped: boolean, reason: string|null }>}
20
67
  */
21
- export async function reapWorktreePhase({
22
- cwd,
23
- storyId,
24
- worktreePath,
25
- wtIsolation,
26
- progress,
68
+ export function reapWorktreePhase({
27
69
  WorktreeManager = DefaultWorktreeManager,
70
+ ...args
28
71
  }) {
29
- let worktreeReaped = false;
30
- const reapEnabled = wtIsolation?.reapOnSuccess !== false;
31
- if (worktreePath && reapEnabled) {
32
- try {
33
- const wm = new WorktreeManager({
34
- repoRoot: cwd,
35
- config: wtIsolation,
36
- logger: {
37
- info: (m) => progress('WORKTREE', m),
38
- warn: (m) => progress('WORKTREE', `⚠️ ${m}`),
39
- error: (m) => Logger.error(`[single-story-close] ${m}`),
40
- },
41
- });
42
- // NO base ref: this runs before the merge, so a merge-reachability
43
- // check would refuse every reap. Safe because the work is pushed, and
44
- // a dirty tree is still refused.
45
- const result = await wm.reap(storyId);
46
- worktreeReaped = result?.removed === true;
47
- if (worktreeReaped) {
48
- progress('WORKTREE', `🧹 Reaped worktree for story-${storyId}.`);
49
- } else {
50
- progress(
51
- 'WORKTREE',
52
- `⚠️ Worktree for story-${storyId} not reaped (${result?.reason ?? 'unknown reason'}) — ` +
53
- `${worktreePath} left in place for the next sweep.`,
54
- );
55
- }
56
- } catch (err) {
57
- Logger.error(
58
- `[single-story-close] ⚠️ Failed to reap worktree: ${err?.message ?? err}`,
59
- );
60
- }
72
+ if (!args.worktreePath || args.wtIsolation?.reapOnSuccess === false) {
73
+ return Promise.resolve(skippedOutcome(args.worktreePath));
61
74
  }
62
-
63
- return worktreeReaped;
75
+ return reapNow({ ...args, WorktreeManager }).catch(failedOutcome);
64
76
  }
@@ -0,0 +1,133 @@
1
+ /**
2
+ * phases/worktree-restore.js — the Story worktree a close or a `--wait`
3
+ * resume runs in, recreated from `story-<id>` when missing. Never falls back
4
+ * to the main checkout while isolation is enabled.
5
+ */
6
+
7
+ import nodeFs from 'node:fs';
8
+ import path from 'node:path';
9
+
10
+ import { resolveWorktreeEnabled } from '../../../config/runtime.js';
11
+ import { gitSpawn as defaultGitSpawn } from '../../../git-utils.js';
12
+ import { Logger } from '../../../Logger.js';
13
+ import { WorktreeManager as DefaultWorktreeManager } from '../../../worktree-manager.js';
14
+ import { catchUpWithOrigin } from './story-branch-catch-up.js';
15
+
16
+ /** `<cwd>/<root>/story-<id>` when it exists on disk, else `null`. */
17
+ export function existingWorktreePath({
18
+ cwd,
19
+ wtIsolation,
20
+ storyId,
21
+ existsSync = nodeFs.existsSync,
22
+ }) {
23
+ const root = wtIsolation?.root ?? '.worktrees';
24
+ const candidate = path.resolve(cwd, root, `story-${storyId}`);
25
+ return existsSync(candidate) ? candidate : null;
26
+ }
27
+
28
+ /** Fetch `story-<id>` from origin when no local ref exists; throws on failure. */
29
+ function ensureLocalStoryRef({ cwd, storyBranch, gitSpawn, progress }) {
30
+ const local = gitSpawn(
31
+ cwd,
32
+ 'show-ref',
33
+ '--verify',
34
+ '--quiet',
35
+ `refs/heads/${storyBranch}`,
36
+ );
37
+ if (local.status === 0) return;
38
+ progress('WORKTREE', `Fetching origin ${storyBranch} (no local ref)...`);
39
+ const fetched = gitSpawn(
40
+ cwd,
41
+ 'fetch',
42
+ 'origin',
43
+ `${storyBranch}:${storyBranch}`,
44
+ );
45
+ if (fetched.status !== 0) {
46
+ throw new Error(
47
+ `[worktree-restore] cannot recreate the ${storyBranch} worktree: no local ref, ` +
48
+ `and \`git fetch origin ${storyBranch}\` failed: ${String(fetched.stderr ?? '').trim() || '(no stderr)'}`,
49
+ );
50
+ }
51
+ }
52
+
53
+ function createManager({ WorktreeManager, cwd, wtIsolation, progress }) {
54
+ return new WorktreeManager({
55
+ repoRoot: cwd,
56
+ config: wtIsolation,
57
+ logger: {
58
+ info: (m) => progress('WORKTREE', m),
59
+ warn: (m) => progress('WORKTREE', `⚠️ ${m}`),
60
+ error: (m) => Logger.error(`[worktree-restore] ${m}`),
61
+ },
62
+ });
63
+ }
64
+
65
+ /** `ensure` the worktree from the (fetched if needed) local story ref. */
66
+ /**
67
+ * A deleted-but-registered worktree makes `ensure` take its reuse branch and
68
+ * return a path that is not there, so the stale entry is pruned first.
69
+ */
70
+ async function ensureFresh(args) {
71
+ const wm = createManager(args);
72
+ await wm.prune();
73
+ return await wm.ensure(args.storyId, args.storyBranch);
74
+ }
75
+
76
+ function onDisk(ensured, existsSync = nodeFs.existsSync) {
77
+ return Boolean(ensured?.path) && existsSync(ensured.path);
78
+ }
79
+
80
+ function notRecreated(storyBranch, ensured) {
81
+ return new Error(
82
+ `[worktree-restore] worktree isolation is enabled but the ${storyBranch} worktree ` +
83
+ `could not be recreated (${ensured?.reason ?? 'no path on disk'}) — refusing to run in the main checkout.`,
84
+ );
85
+ }
86
+
87
+ async function recreateWorktree(args) {
88
+ const { storyBranch, progress } = args;
89
+ ensureLocalStoryRef(args);
90
+ const ensured = await ensureFresh(args);
91
+ if (!onDisk(ensured, args.existsSync))
92
+ throw notRecreated(storyBranch, ensured);
93
+ progress(
94
+ 'WORKTREE',
95
+ `♻️ Recreated the missing ${storyBranch} worktree at ${ensured.path}.`,
96
+ );
97
+ return ensured.path;
98
+ }
99
+
100
+ /**
101
+ * The existing worktree, a recreated one, or `null` when isolation is off
102
+ * and none exists. `cwd` is the MAIN checkout.
103
+ *
104
+ * @returns {Promise<string|null>}
105
+ */
106
+ export async function resolveStoryWorktree({
107
+ gitSpawn = defaultGitSpawn,
108
+ WorktreeManager = DefaultWorktreeManager,
109
+ existsSync,
110
+ env = process.env,
111
+ ...args
112
+ }) {
113
+ const wtIsolation = args.config?.delivery?.worktreeIsolation;
114
+ const existing = existingWorktreePath({
115
+ cwd: args.cwd,
116
+ wtIsolation,
117
+ storyId: args.storyId,
118
+ ...(existsSync ? { existsSync } : {}),
119
+ });
120
+ if (!existing && !resolveWorktreeEnabled({ config: args.config }, env)) {
121
+ return null;
122
+ }
123
+ const worktreePath =
124
+ existing ??
125
+ (await recreateWorktree({
126
+ ...args,
127
+ wtIsolation,
128
+ gitSpawn,
129
+ WorktreeManager,
130
+ ...(existsSync ? { existsSync } : {}),
131
+ }));
132
+ return catchUpWithOrigin({ ...args, worktreePath, gitSpawn });
133
+ }
@@ -1,12 +1,12 @@
1
- import nodeFs from 'node:fs';
2
- import path from 'node:path';
3
1
  import {
4
2
  BASELINES_GATE_NAMES,
5
3
  buildDefaultGates,
6
4
  } from '../../close-validation/gates.js';
7
5
  import { runCloseValidation } from '../../close-validation/runner.js';
8
6
  import { getCiDelivery } from '../../config/ci.js';
7
+ import { resolveWorktreeEnabled } from '../../config/runtime.js';
9
8
  import { resolveConfig } from '../../config-resolver.js';
9
+ import { gh as defaultGh } from '../../gh-exec.js';
10
10
  import { getStoryBranch, gitSpawn, gitSync } from '../../git-utils.js';
11
11
  import { Logger } from '../../Logger.js';
12
12
  import {
@@ -31,7 +31,7 @@ import {
31
31
  terminalFromWaitOutcome,
32
32
  } from '../story-deliver-terminal.js';
33
33
  import { deriveCloseNote } from './close-note.js';
34
- import { runAutoMergePhase } from './phases/auto-merge.js';
34
+ import { closeArmedPr, runAutoMergePhase } from './phases/auto-merge.js';
35
35
  import { runBaseSyncPhase } from './phases/base-sync.js';
36
36
  import { runCloseValidationPhase } from './phases/close-validation.js';
37
37
  import { parsePrNumber } from './phases/code-review.js';
@@ -40,11 +40,17 @@ import { runGraphqlPreflight } from './phases/graphql-preflight.js';
40
40
  import { lockWaitPending } from './phases/lock-wait-pending.js';
41
41
  import { parseCloseOptions, resolveWaitForMerge } from './phases/options.js';
42
42
  import { runPostLandTail } from './phases/post-land.js';
43
- import { ensurePullRequestWith } from './phases/pull-request.js';
43
+ import {
44
+ ensurePullRequestWith,
45
+ pickHeadPullRequest,
46
+ } from './phases/pull-request.js';
44
47
  import { pushStoryBranch } from './phases/push.js';
45
48
  import { handleCriticalReviewBlock } from './phases/review-block.js';
46
49
  import { handleOverriddenReviewBlock } from './phases/review-override.js';
47
- import { reapWorktreePhase } from './phases/worktree-reap.js';
50
+ import {
51
+ existingWorktreePath,
52
+ resolveStoryWorktree,
53
+ } from './phases/worktree-restore.js';
48
54
  import { runWrongTreeGuardPhase } from './phases/wrong-tree-guard.js';
49
55
  import {
50
56
  discardHeldReview,
@@ -256,12 +262,6 @@ function closeEnvelopeGates(options, validationGates, reviewOverride) {
256
262
  };
257
263
  }
258
264
 
259
- function resolveWorktreePath({ cwd, config, storyId }) {
260
- const root = config.delivery?.worktreeIsolation?.root ?? '.worktrees';
261
- const candidate = path.resolve(cwd, root, `story-${storyId}`);
262
- return nodeFs.existsSync(candidate) ? candidate : null;
263
- }
264
-
265
265
  /**
266
266
  * wrong-tree guard → base-sync → close-validation. Validation runs last so
267
267
  * the validated tree is the pushed tree (base-sync's merge commit included),
@@ -521,7 +521,7 @@ function closeResult({
521
521
  prNumber,
522
522
  autoMergeEnabled,
523
523
  autoMergeReason,
524
- worktreeReaped,
524
+ worktreeReaped = false,
525
525
  leaseReleased,
526
526
  localCleanupDeferred = false,
527
527
  directMerged = false,
@@ -666,30 +666,51 @@ async function resolveAutoMergeOutcome({ alreadyMerged, ...phaseArgs }) {
666
666
  return await runAutoMergePhase(phaseArgs);
667
667
  }
668
668
 
669
- /**
670
- * @param {{ status: string, nextCommand: string, blocked?: {blockClass?: string} }} terminal
671
- * @param {{ storyId: number, prUrl: string|null }} ctx
672
- * @returns {void}
673
- */
674
- function reportWaitTerminal(terminal, { storyId, prUrl }) {
675
- if (terminal.status === 'landed') {
676
- progress('DONE', `✅ Story #${storyId}: PR merged → ${prUrl}`);
677
- return;
678
- }
679
- if (terminal.status === 'pending') {
680
- // Not a failure: resumable, with its own CLI exit code.
681
- progress(
682
- 'PENDING',
683
- `⏸ Story #${storyId}: PR ${prUrl} still in flight — resume with: ${terminal.nextCommand}`,
684
- );
685
- return;
686
- }
687
- progress(
669
+ /** One console line per non-landed wait ending, keyed by status. */
670
+ const WAIT_TERMINAL_LINES = Object.freeze({
671
+ pending: (terminal, { storyId, prUrl }) => [
672
+ 'PENDING',
673
+ `⏸ Story #${storyId}: PR ${prUrl} still in flight — resume with: ${terminal.nextCommand}`,
674
+ ],
675
+ failed: (terminal, { storyId, prUrl }) => [
676
+ 'FAILED',
677
+ `🛑 Story #${storyId}: PR ${prUrl} did not land (${terminal.phase}): ` +
678
+ `${terminal.failure?.reason}. Labels unchanged. Next: ${terminal.nextCommand}`,
679
+ ],
680
+ blocked: (terminal, { storyId, prUrl }) => [
688
681
  'BLOCKED',
689
682
  `🛑 Story #${storyId}: PR ${prUrl} did not land ` +
690
683
  `(blockClass=${terminal.blocked?.blockClass}). Story is at agent::blocked. ` +
691
684
  `Next: ${terminal.nextCommand}`,
692
- );
685
+ ],
686
+ landed: (_terminal, { storyId, prUrl }) => [
687
+ 'DONE',
688
+ `✅ Story #${storyId}: PR merged → ${prUrl}`,
689
+ ],
690
+ });
691
+
692
+ /**
693
+ * `pending` is not a failure: resumable, with its own CLI exit code.
694
+ *
695
+ * @param {{ status: string, nextCommand: string }} terminal
696
+ * @param {{ storyId: number, prUrl: string|null }} ctx
697
+ * @returns {void}
698
+ */
699
+ function reportWaitTerminal(terminal, ctx) {
700
+ const line =
701
+ WAIT_TERMINAL_LINES[terminal.status] ?? WAIT_TERMINAL_LINES.blocked;
702
+ progress(...line(terminal, ctx));
703
+ }
704
+
705
+ /**
706
+ * Reaped only by the post-land tail, and only when it actually removed the
707
+ * tree (a skipped reap reports ok with a detail).
708
+ *
709
+ * @param {object|null|undefined} tail
710
+ * @returns {boolean}
711
+ */
712
+ function tailReapedWorktree(tail) {
713
+ return tail?.worktreeReap === true && !tail?.details?.worktreeReap;
693
714
  }
694
715
 
695
716
  /**
@@ -701,6 +722,7 @@ async function finishWithMergeWait(prCtx, deps) {
701
722
  deps.setPhase('confirm-merge');
702
723
  const waitOutcome = await runConfirmMergePhase({
703
724
  cwd: deps.cwd,
725
+ worktreePath: prCtx.worktreePath,
704
726
  storyId: prCtx.storyId,
705
727
  storyBranch: prCtx.storyBranch,
706
728
  baseBranch: prCtx.baseBranch,
@@ -708,6 +730,8 @@ async function finishWithMergeWait(prCtx, deps) {
708
730
  prUrl: prCtx.prUrl,
709
731
  autoMergeEnabled: prCtx.autoMergeEnabled,
710
732
  autoMergeReason: prCtx.autoMergeReason,
733
+ // Positive evidence for the re-arm rule: this close armed the PR.
734
+ closeArmed: closeArmedPr(prCtx),
711
735
  advisoryGate: prCtx.advisoryGate,
712
736
  provider: deps.provider,
713
737
  config: prCtx.config,
@@ -730,6 +754,7 @@ async function finishWithMergeWait(prCtx, deps) {
730
754
  prNumber: prCtx.prNumber,
731
755
  prUrl: prCtx.prUrl,
732
756
  autoMergeEnabled: prCtx.autoMergeEnabled,
757
+ autoMergeReason: prCtx.autoMergeReason,
733
758
  gates: prCtx.gates,
734
759
  lockWait: prCtx.lockWait,
735
760
  suiteTimings: prCtx.suiteTimings,
@@ -743,7 +768,7 @@ async function finishWithMergeWait(prCtx, deps) {
743
768
  prNumber: prCtx.prNumber,
744
769
  autoMergeEnabled: prCtx.autoMergeEnabled,
745
770
  autoMergeReason: prCtx.autoMergeReason,
746
- worktreeReaped: prCtx.worktreeReaped,
771
+ worktreeReaped: tailReapedWorktree(waitOutcome.tail),
747
772
  // Released by the post-land tail only; any other ending keeps the claim.
748
773
  leaseReleased: waitOutcome.tail?.leaseRelease === true,
749
774
  localCleanupDeferred: prCtx.localCleanupDeferred,
@@ -784,7 +809,6 @@ async function finishWithoutMergeWait(prCtx, waitForMergeReason) {
784
809
  prNumber: prCtx.prNumber,
785
810
  autoMergeEnabled: prCtx.autoMergeEnabled,
786
811
  autoMergeReason: prCtx.autoMergeReason,
787
- worktreeReaped: prCtx.worktreeReaped,
788
812
  leaseReleased: false,
789
813
  localCleanupDeferred: prCtx.localCleanupDeferred,
790
814
  directMerged: prCtx.directMerged,
@@ -803,6 +827,7 @@ async function finishWithoutMergeWait(prCtx, waitForMergeReason) {
803
827
  url: prCtx.prUrl ?? null,
804
828
  state: merged ? 'MERGED' : 'OPEN',
805
829
  autoMergeEnabled: Boolean(prCtx.autoMergeEnabled),
830
+ autoMergeReason: prCtx.autoMergeReason ?? null,
806
831
  },
807
832
  gates: prCtx.gates,
808
833
  lockWait: prCtx.lockWait,
@@ -910,7 +935,8 @@ async function graphqlPreflightPhase(ctx, deps) {
910
935
 
911
936
  /**
912
937
  * The base the run was SEEDED from (init receipt); throws before any merge
913
- * when it disagrees with current config.
938
+ * when it disagrees with current config. Also the Story worktree every later
939
+ * phase runs in — recreated before any git operation when it is missing.
914
940
  */
915
941
  async function resolveBasePhase(ctx, deps) {
916
942
  const { values, confirmed } = await resolveRunScopedConfig({
@@ -920,11 +946,101 @@ async function resolveBasePhase(ctx, deps) {
920
946
  });
921
947
  ctx.baseBranch = values.baseBranch;
922
948
  ctx.baseConfirmed = confirmed;
923
- ctx.worktreePath = resolveWorktreePath({
924
- cwd: ctx.options.cwd,
949
+ ctx.worktreePath = await resolveCloseWorktree(ctx, deps);
950
+ return null;
951
+ }
952
+
953
+ /**
954
+ * A surviving local ref, or a branch still on origin, may carry work no PR
955
+ * holds yet. Only `ls-remote`'s "no such ref" (exit 2) proves the remote
956
+ * branch gone — a read failure counts as surviving.
957
+ */
958
+ function storyBranchSurvives(ctx) {
959
+ const cwd = ctx.options.cwd;
960
+ const ref = `refs/heads/${ctx.storyBranch}`;
961
+ const local = gitSpawn(cwd, 'show-ref', '--verify', '--quiet', ref);
962
+ if (local.status === 0) return true;
963
+ const remote = gitSpawn(
964
+ cwd,
965
+ 'ls-remote',
966
+ '--exit-code',
967
+ '--heads',
968
+ 'origin',
969
+ ctx.storyBranch,
970
+ );
971
+ return remote.status !== 2;
972
+ }
973
+
974
+ /**
975
+ * The Story's PR, when it already merged and nothing newer is in flight — a
976
+ * re-run after the land, whose branch `--delete-branch` and a sweep removed.
977
+ * An OPEN PR on the head wins (a re-delivery), as `ensurePullRequestWith`
978
+ * decides, and a surviving branch means there may be work to deliver.
979
+ * Any read failure reads as "not merged": the normal path then decides.
980
+ *
981
+ * @returns {Promise<{ prUrl: string, prNumber: number|null }|null>}
982
+ */
983
+ async function findLandedPr(ctx, deps) {
984
+ if (storyBranchSurvives(ctx)) return null;
985
+ try {
986
+ const rows = await (deps.gh ?? defaultGh).pr.list(
987
+ ['--head', ctx.storyBranch, '--state', 'all'],
988
+ ['url', 'state', 'mergedAt'],
989
+ );
990
+ const head = pickHeadPullRequest(rows);
991
+ return head?.state === 'MERGED'
992
+ ? { prUrl: head.url, prNumber: parsePrNumber(head.url) }
993
+ : null;
994
+ } catch {
995
+ return null;
996
+ }
997
+ }
998
+
999
+ /**
1000
+ * A missing worktree is recreated — unless the PR already merged, which
1001
+ * short-circuits to the confirm before any restore is attempted.
1002
+ */
1003
+ async function resolveCloseWorktree(ctx, deps) {
1004
+ const cwd = ctx.options.cwd;
1005
+ const wtIsolation = deps.config.delivery?.worktreeIsolation;
1006
+ const missing =
1007
+ !existingWorktreePath({ cwd, wtIsolation, storyId: ctx.storyId }) &&
1008
+ resolveWorktreeEnabled({ config: deps.config });
1009
+ ctx.landedPr = missing ? await findLandedPr(ctx, deps) : null;
1010
+ if (ctx.landedPr) return null;
1011
+ return await resolveStoryWorktree({
1012
+ cwd,
925
1013
  config: deps.config,
926
1014
  storyId: ctx.storyId,
1015
+ storyBranch: ctx.storyBranch,
1016
+ progress,
1017
+ gitSpawn,
1018
+ WorktreeManager,
927
1019
  });
1020
+ }
1021
+
1022
+ /** A landed PR has nothing left to validate, push or open. */
1023
+ function unlessLanded(phase, onLanded) {
1024
+ return (ctx, deps) => (ctx.landedPr ? onLanded(ctx) : phase(ctx, deps));
1025
+ }
1026
+
1027
+ function landedPrePush(ctx) {
1028
+ progress(
1029
+ 'INIT',
1030
+ `⏭ PR ${ctx.landedPr.prUrl} already merged — skipping validation, sync and push.`,
1031
+ );
1032
+ ctx.options = { ...ctx.options, skipValidation: true, skipSync: true };
1033
+ ctx.prePush = {
1034
+ validationGates: null,
1035
+ lockWait: null,
1036
+ suiteTimings: null,
1037
+ pending: false,
1038
+ };
1039
+ return null;
1040
+ }
1041
+
1042
+ function landedPr(ctx) {
1043
+ ctx.pr = { ...ctx.landedPr, alreadyMerged: true, reviewOverride: null };
928
1044
  return null;
929
1045
  }
930
1046
 
@@ -957,23 +1073,12 @@ async function openPrPhase(ctx, deps) {
957
1073
  }
958
1074
 
959
1075
  /**
960
- * Reap BEFORE the arm: `gh pr merge --delete-branch` may merge at once and
961
- * then fail deleting a branch a live worktree holds, reading as a failed arm.
962
- * Safe — the work is pushed, and a dirty tree is still refused.
1076
+ * No lease release here: only the post-land tail releases it. The Story
1077
+ * worktree is still live at the arm, and that is safe: a `gh pr merge
1078
+ * --delete-branch` whose only failure is the LOCAL delete of a branch the
1079
+ * worktree holds is classified `localCleanupDeferred` (`LOCAL_CLEANUP_FAILURE`
1080
+ * in `phases/auto-merge.js`), and the tail reaps the worktree, then the ref.
963
1081
  */
964
- async function reapWorktreePhaseStep(ctx, deps) {
965
- ctx.worktreeReaped = await reapWorktreePhase({
966
- cwd: ctx.options.cwd,
967
- storyId: ctx.storyId,
968
- worktreePath: ctx.worktreePath,
969
- wtIsolation: deps.config.delivery?.worktreeIsolation,
970
- progress,
971
- WorktreeManager,
972
- });
973
- return null;
974
- }
975
-
976
- /** No lease release here: only the post-land tail releases it. */
977
1082
  async function armPhase(ctx, deps) {
978
1083
  ctx.setPhase('auto-merge');
979
1084
  const ciDelivery = getCiDelivery(deps.config);
@@ -1028,7 +1133,7 @@ async function finishPhase(ctx, deps) {
1028
1133
  autoMergeEnabled: arm.autoMergeEnabled,
1029
1134
  autoMergeReason: arm.autoMergeReason,
1030
1135
  advisoryGate: arm.advisoryGate,
1031
- worktreeReaped: ctx.worktreeReaped,
1136
+ worktreePath: ctx.worktreePath,
1032
1137
  localCleanupDeferred: arm.localCleanupDeferred,
1033
1138
  directMerged: arm.directMerged,
1034
1139
  config: deps.config,
@@ -1063,9 +1168,8 @@ const CLOSE_PIPELINE = Object.freeze([
1063
1168
  loadStoryPhase,
1064
1169
  graphqlPreflightPhase,
1065
1170
  resolveBasePhase,
1066
- prePushPhase,
1067
- openPrPhase,
1068
- reapWorktreePhaseStep,
1171
+ unlessLanded(prePushPhase, landedPrePush),
1172
+ unlessLanded(openPrPhase, landedPr),
1069
1173
  armPhase,
1070
1174
  finishPhase,
1071
1175
  ]);
@@ -326,6 +326,34 @@ export function emitTerminalEnvelope(
326
326
  );
327
327
  }
328
328
 
329
+ /**
330
+ * The PR facts every wait ending carries. `autoMergeReason` rides along only
331
+ * when the caller knows it — it is the evidence a later re-arm reads.
332
+ */
333
+ function prBaseFor({ prNumber, prUrl, autoMergeEnabled, autoMergeReason }) {
334
+ const base = {
335
+ number: prNumber,
336
+ url: prUrl ?? null,
337
+ autoMergeEnabled: Boolean(autoMergeEnabled),
338
+ };
339
+ return autoMergeReason === undefined ? base : { ...base, autoMergeReason };
340
+ }
341
+
342
+ /**
343
+ * A DIRTY PR the wait could not sync: labels untouched, and re-running close
344
+ * (which re-syncs in the worktree) is the remedy.
345
+ */
346
+ function failedFromWaitOutcome(waitOutcome, prBase, common) {
347
+ return buildTerminalEnvelope({
348
+ ...common,
349
+ status: 'failed',
350
+ phase: waitOutcome.phase ?? 'base-sync',
351
+ pr: { ...prBase, state: waitOutcome.prProbe?.state ?? 'OPEN' },
352
+ failure: { reason: waitOutcome.reason },
353
+ nextCommand: NEXT_COMMANDS.close(common.storyId),
354
+ });
355
+ }
356
+
329
357
  /**
330
358
  * Map a `runConfirmMergePhase` outcome onto the terminal envelope; the other
331
359
  * fields pass through.
@@ -337,14 +365,16 @@ export function terminalFromWaitOutcome({
337
365
  prNumber,
338
366
  prUrl,
339
367
  autoMergeEnabled,
368
+ autoMergeReason,
340
369
  ...common
341
370
  }) {
342
371
  const { storyId } = common;
343
- const prBase = {
344
- number: prNumber,
345
- url: prUrl ?? null,
346
- autoMergeEnabled: Boolean(autoMergeEnabled),
347
- };
372
+ const prBase = prBaseFor({
373
+ prNumber,
374
+ prUrl,
375
+ autoMergeEnabled,
376
+ autoMergeReason,
377
+ });
348
378
 
349
379
  if (waitOutcome.terminal === 'landed') {
350
380
  return buildTerminalEnvelope({
@@ -377,7 +407,17 @@ export function terminalFromWaitOutcome({
377
407
  });
378
408
  }
379
409
 
380
- // blocked — mirror the classifier's remediation, never a second opinion.
410
+ if (waitOutcome.terminal === 'failed') {
411
+ return failedFromWaitOutcome(waitOutcome, prBase, common);
412
+ }
413
+
414
+ return blockedFromWaitOutcome(waitOutcome, prBase, common);
415
+ }
416
+
417
+ /** Mirrors the classifier's remediation, never a second opinion. */
418
+ function blockedFromWaitOutcome(waitOutcome, prBase, common) {
419
+ const { storyId } = common;
420
+ const prNumber = prBase.number;
381
421
  const nextCommand =
382
422
  waitOutcome.blockClass === 'checks-failed'
383
423
  ? NEXT_COMMANDS.watchCi(storyId, prNumber)