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
@@ -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,17 +1,18 @@
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 {
13
13
  emitReviewBlockedFriction,
14
14
  recordCloseTelemetry,
15
+ resolveWorkerModel,
15
16
  resolveWorkerTokens,
16
17
  } from '../../observability/close-telemetry.js';
17
18
  import { emitTerminalFriction } from '../../observability/runtime-friction.js';
@@ -30,7 +31,7 @@ import {
30
31
  terminalFromWaitOutcome,
31
32
  } from '../story-deliver-terminal.js';
32
33
  import { deriveCloseNote } from './close-note.js';
33
- import { runAutoMergePhase } from './phases/auto-merge.js';
34
+ import { closeArmedPr, runAutoMergePhase } from './phases/auto-merge.js';
34
35
  import { runBaseSyncPhase } from './phases/base-sync.js';
35
36
  import { runCloseValidationPhase } from './phases/close-validation.js';
36
37
  import { parsePrNumber } from './phases/code-review.js';
@@ -39,11 +40,17 @@ import { runGraphqlPreflight } from './phases/graphql-preflight.js';
39
40
  import { lockWaitPending } from './phases/lock-wait-pending.js';
40
41
  import { parseCloseOptions, resolveWaitForMerge } from './phases/options.js';
41
42
  import { runPostLandTail } from './phases/post-land.js';
42
- import { ensurePullRequestWith } from './phases/pull-request.js';
43
+ import {
44
+ ensurePullRequestWith,
45
+ pickHeadPullRequest,
46
+ } from './phases/pull-request.js';
43
47
  import { pushStoryBranch } from './phases/push.js';
44
48
  import { handleCriticalReviewBlock } from './phases/review-block.js';
45
49
  import { handleOverriddenReviewBlock } from './phases/review-override.js';
46
- import { reapWorktreePhase } from './phases/worktree-reap.js';
50
+ import {
51
+ existingWorktreePath,
52
+ resolveStoryWorktree,
53
+ } from './phases/worktree-restore.js';
47
54
  import { runWrongTreeGuardPhase } from './phases/wrong-tree-guard.js';
48
55
  import {
49
56
  discardHeldReview,
@@ -95,6 +102,9 @@ function createPhaseTimer(nowMs = Date.now) {
95
102
 
96
103
  const UNTIMED = Object.freeze({ stamp() {} });
97
104
 
105
+ /** No worker figures: an inline close, or an ending before they resolve. */
106
+ const NO_WORKER = Object.freeze({ workerTokens: null, workerModel: null });
107
+
98
108
  /**
99
109
  * The single terminal writer: the retry signal, the result summary (with its
100
110
  * `telemetry`), the envelope callers parse, and terminal friction — so no
@@ -106,10 +116,10 @@ async function emitTerminal({
106
116
  result,
107
117
  config,
108
118
  phaseTimer = UNTIMED,
109
- workerTokens = null,
119
+ worker = NO_WORKER,
110
120
  }) {
111
121
  phaseTimer.stamp(terminal);
112
- await recordCloseTelemetry({ terminal, result, config, workerTokens });
122
+ await recordCloseTelemetry({ terminal, result, config, ...worker });
113
123
  if (result) {
114
124
  emitTerseResult({
115
125
  label: 'STORY CLOSE RESULT',
@@ -146,7 +156,7 @@ async function alreadyClosedResult(
146
156
  storyId,
147
157
  stateReason = null,
148
158
  config,
149
- workerTokens = null,
159
+ worker = NO_WORKER,
150
160
  ) {
151
161
  if (stateReason === 'not_planned') {
152
162
  progress(
@@ -166,7 +176,7 @@ async function alreadyClosedResult(
166
176
  nextCommand: null,
167
177
  elapsedSeconds: 0,
168
178
  });
169
- await emitTerminal({ terminal, result, config, workerTokens });
179
+ await emitTerminal({ terminal, result, config, worker });
170
180
  return { success: false, result, terminal };
171
181
  }
172
182
 
@@ -179,7 +189,7 @@ async function alreadyClosedResult(
179
189
  nextCommand: null,
180
190
  elapsedSeconds: 0,
181
191
  });
182
- await emitTerminal({ terminal, result, config, workerTokens });
192
+ await emitTerminal({ terminal, result, config, worker });
183
193
  return { success: true, result, terminal };
184
194
  }
185
195
 
@@ -202,7 +212,7 @@ async function preflightBlockedResult({
202
212
  preflight,
203
213
  config,
204
214
  startedAtMs,
205
- workerTokens = null,
215
+ worker = NO_WORKER,
206
216
  }) {
207
217
  const result = noopResult(storyId, `graphql-preflight-${preflight.verdict}`);
208
218
  const terminal = buildTerminalEnvelope({
@@ -217,7 +227,7 @@ async function preflightBlockedResult({
217
227
  nextCommand: NEXT_COMMANDS.close(storyId),
218
228
  elapsedSeconds: elapsedSecondsSince(startedAtMs),
219
229
  });
220
- await emitTerminal({ terminal, result, config, workerTokens });
230
+ await emitTerminal({ terminal, result, config, worker });
221
231
  return { success: false, result, terminal };
222
232
  }
223
233
 
@@ -252,12 +262,6 @@ function closeEnvelopeGates(options, validationGates, reviewOverride) {
252
262
  };
253
263
  }
254
264
 
255
- function resolveWorktreePath({ cwd, config, storyId }) {
256
- const root = config.delivery?.worktreeIsolation?.root ?? '.worktrees';
257
- const candidate = path.resolve(cwd, root, `story-${storyId}`);
258
- return nodeFs.existsSync(candidate) ? candidate : null;
259
- }
260
-
261
265
  /**
262
266
  * wrong-tree guard → base-sync → close-validation. Validation runs last so
263
267
  * the validated tree is the pushed tree (base-sync's merge commit included),
@@ -517,7 +521,7 @@ function closeResult({
517
521
  prNumber,
518
522
  autoMergeEnabled,
519
523
  autoMergeReason,
520
- worktreeReaped,
524
+ worktreeReaped = false,
521
525
  leaseReleased,
522
526
  localCleanupDeferred = false,
523
527
  directMerged = false,
@@ -589,6 +593,7 @@ export async function runSingleStoryClose({
589
593
  rerunAdvisory: rerunAdvisoryParam,
590
594
  overrideReviewBlock: overrideReviewBlockParam,
591
595
  workerTokens: workerTokensParam,
596
+ workerModel: workerModelParam,
592
597
  ...injected
593
598
  } = {}) {
594
599
  const options = parseCloseOptions({
@@ -604,10 +609,11 @@ export async function runSingleStoryClose({
604
609
  rerunAdvisoryParam,
605
610
  overrideReviewBlockParam,
606
611
  workerTokensParam,
612
+ workerModelParam,
607
613
  });
608
614
  if (!options.storyId) {
609
615
  throw new Error(
610
- 'Usage: node single-story-close.js --story <STORY_ID> [--cwd <main-repo>] [--skip-validation] [--skip-sync] [--no-auto-merge] [--wait-merge|--no-wait-merge] [--max-wait-seconds <n>] [--merge-watch-mode <sync|async>] [--rerun-advisory <n>] [--override-review-block <reason>] [--worker-tokens <n>]',
616
+ 'Usage: node single-story-close.js --story <STORY_ID> [--cwd <main-repo>] [--skip-validation] [--skip-sync] [--no-auto-merge] [--wait-merge|--no-wait-merge] [--max-wait-seconds <n>] [--merge-watch-mode <sync|async>] [--rerun-advisory <n>] [--override-review-block <reason>] [--worker-tokens <n>] [--worker-model <model>]',
611
617
  );
612
618
  }
613
619
 
@@ -660,30 +666,51 @@ async function resolveAutoMergeOutcome({ alreadyMerged, ...phaseArgs }) {
660
666
  return await runAutoMergePhase(phaseArgs);
661
667
  }
662
668
 
663
- /**
664
- * @param {{ status: string, nextCommand: string, blocked?: {blockClass?: string} }} terminal
665
- * @param {{ storyId: number, prUrl: string|null }} ctx
666
- * @returns {void}
667
- */
668
- function reportWaitTerminal(terminal, { storyId, prUrl }) {
669
- if (terminal.status === 'landed') {
670
- progress('DONE', `✅ Story #${storyId}: PR merged → ${prUrl}`);
671
- return;
672
- }
673
- if (terminal.status === 'pending') {
674
- // Not a failure: resumable, with its own CLI exit code.
675
- progress(
676
- 'PENDING',
677
- `⏸ Story #${storyId}: PR ${prUrl} still in flight — resume with: ${terminal.nextCommand}`,
678
- );
679
- return;
680
- }
681
- 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 }) => [
682
681
  'BLOCKED',
683
682
  `🛑 Story #${storyId}: PR ${prUrl} did not land ` +
684
683
  `(blockClass=${terminal.blocked?.blockClass}). Story is at agent::blocked. ` +
685
684
  `Next: ${terminal.nextCommand}`,
686
- );
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;
687
714
  }
688
715
 
689
716
  /**
@@ -695,6 +722,7 @@ async function finishWithMergeWait(prCtx, deps) {
695
722
  deps.setPhase('confirm-merge');
696
723
  const waitOutcome = await runConfirmMergePhase({
697
724
  cwd: deps.cwd,
725
+ worktreePath: prCtx.worktreePath,
698
726
  storyId: prCtx.storyId,
699
727
  storyBranch: prCtx.storyBranch,
700
728
  baseBranch: prCtx.baseBranch,
@@ -702,6 +730,8 @@ async function finishWithMergeWait(prCtx, deps) {
702
730
  prUrl: prCtx.prUrl,
703
731
  autoMergeEnabled: prCtx.autoMergeEnabled,
704
732
  autoMergeReason: prCtx.autoMergeReason,
733
+ // Positive evidence for the re-arm rule: this close armed the PR.
734
+ closeArmed: closeArmedPr(prCtx),
705
735
  advisoryGate: prCtx.advisoryGate,
706
736
  provider: deps.provider,
707
737
  config: prCtx.config,
@@ -724,6 +754,7 @@ async function finishWithMergeWait(prCtx, deps) {
724
754
  prNumber: prCtx.prNumber,
725
755
  prUrl: prCtx.prUrl,
726
756
  autoMergeEnabled: prCtx.autoMergeEnabled,
757
+ autoMergeReason: prCtx.autoMergeReason,
727
758
  gates: prCtx.gates,
728
759
  lockWait: prCtx.lockWait,
729
760
  suiteTimings: prCtx.suiteTimings,
@@ -737,7 +768,7 @@ async function finishWithMergeWait(prCtx, deps) {
737
768
  prNumber: prCtx.prNumber,
738
769
  autoMergeEnabled: prCtx.autoMergeEnabled,
739
770
  autoMergeReason: prCtx.autoMergeReason,
740
- worktreeReaped: prCtx.worktreeReaped,
771
+ worktreeReaped: tailReapedWorktree(waitOutcome.tail),
741
772
  // Released by the post-land tail only; any other ending keeps the claim.
742
773
  leaseReleased: waitOutcome.tail?.leaseRelease === true,
743
774
  localCleanupDeferred: prCtx.localCleanupDeferred,
@@ -754,7 +785,7 @@ async function finishWithMergeWait(prCtx, deps) {
754
785
  result,
755
786
  config: prCtx.config,
756
787
  phaseTimer: prCtx.phaseTimer,
757
- workerTokens: prCtx.workerTokens,
788
+ worker: prCtx.worker,
758
789
  });
759
790
  reportWaitTerminal(terminal, { storyId: prCtx.storyId, prUrl: prCtx.prUrl });
760
791
  return { success: terminal.status === 'landed', result, terminal };
@@ -778,7 +809,6 @@ async function finishWithoutMergeWait(prCtx, waitForMergeReason) {
778
809
  prNumber: prCtx.prNumber,
779
810
  autoMergeEnabled: prCtx.autoMergeEnabled,
780
811
  autoMergeReason: prCtx.autoMergeReason,
781
- worktreeReaped: prCtx.worktreeReaped,
782
812
  leaseReleased: false,
783
813
  localCleanupDeferred: prCtx.localCleanupDeferred,
784
814
  directMerged: prCtx.directMerged,
@@ -797,6 +827,7 @@ async function finishWithoutMergeWait(prCtx, waitForMergeReason) {
797
827
  url: prCtx.prUrl ?? null,
798
828
  state: merged ? 'MERGED' : 'OPEN',
799
829
  autoMergeEnabled: Boolean(prCtx.autoMergeEnabled),
830
+ autoMergeReason: prCtx.autoMergeReason ?? null,
800
831
  },
801
832
  gates: prCtx.gates,
802
833
  lockWait: prCtx.lockWait,
@@ -809,7 +840,7 @@ async function finishWithoutMergeWait(prCtx, waitForMergeReason) {
809
840
  result,
810
841
  config: prCtx.config,
811
842
  phaseTimer: prCtx.phaseTimer,
812
- workerTokens: prCtx.workerTokens,
843
+ worker: prCtx.worker,
813
844
  });
814
845
  progress(
815
846
  'DONE',
@@ -828,14 +859,14 @@ async function finishWithoutMergeWait(prCtx, waitForMergeReason) {
828
859
  */
829
860
  async function finishDeferred(
830
861
  lockWait,
831
- { config, startedAtMs, phaseTimer, workerTokens, ...ids },
862
+ { config, startedAtMs, phaseTimer, worker, ...ids },
832
863
  ) {
833
864
  const { result, terminal, note } = lockWaitPending({
834
865
  ...ids,
835
866
  lockWait,
836
867
  elapsedSeconds: elapsedSecondsSince(startedAtMs),
837
868
  });
838
- await emitTerminal({ terminal, result, config, phaseTimer, workerTokens });
869
+ await emitTerminal({ terminal, result, config, phaseTimer, worker });
839
870
  progress('PENDING', note);
840
871
  return { success: false, result, terminal };
841
872
  }
@@ -878,7 +909,7 @@ async function loadStoryPhase(ctx, deps) {
878
909
  ctx.storyId,
879
910
  ctx.story.stateReason,
880
911
  deps.config,
881
- ctx.workerTokens,
912
+ ctx.worker,
882
913
  );
883
914
  }
884
915
 
@@ -898,13 +929,14 @@ async function graphqlPreflightPhase(ctx, deps) {
898
929
  preflight,
899
930
  config: deps.config,
900
931
  startedAtMs: ctx.startedAtMs,
901
- workerTokens: ctx.workerTokens,
932
+ worker: ctx.worker,
902
933
  });
903
934
  }
904
935
 
905
936
  /**
906
937
  * The base the run was SEEDED from (init receipt); throws before any merge
907
- * 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.
908
940
  */
909
941
  async function resolveBasePhase(ctx, deps) {
910
942
  const { values, confirmed } = await resolveRunScopedConfig({
@@ -914,11 +946,101 @@ async function resolveBasePhase(ctx, deps) {
914
946
  });
915
947
  ctx.baseBranch = values.baseBranch;
916
948
  ctx.baseConfirmed = confirmed;
917
- ctx.worktreePath = resolveWorktreePath({
918
- 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,
919
1013
  config: deps.config,
920
1014
  storyId: ctx.storyId,
1015
+ storyBranch: ctx.storyBranch,
1016
+ progress,
1017
+ gitSpawn,
1018
+ WorktreeManager,
921
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 };
922
1044
  return null;
923
1045
  }
924
1046
 
@@ -937,7 +1059,7 @@ async function prePushPhase(ctx, deps) {
937
1059
  config: deps.config,
938
1060
  startedAtMs: ctx.startedAtMs,
939
1061
  phaseTimer: ctx.phaseTimer,
940
- workerTokens: ctx.workerTokens,
1062
+ worker: ctx.worker,
941
1063
  });
942
1064
  }
943
1065
 
@@ -951,23 +1073,12 @@ async function openPrPhase(ctx, deps) {
951
1073
  }
952
1074
 
953
1075
  /**
954
- * Reap BEFORE the arm: `gh pr merge --delete-branch` may merge at once and
955
- * then fail deleting a branch a live worktree holds, reading as a failed arm.
956
- * 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.
957
1081
  */
958
- async function reapWorktreePhaseStep(ctx, deps) {
959
- ctx.worktreeReaped = await reapWorktreePhase({
960
- cwd: ctx.options.cwd,
961
- storyId: ctx.storyId,
962
- worktreePath: ctx.worktreePath,
963
- wtIsolation: deps.config.delivery?.worktreeIsolation,
964
- progress,
965
- WorktreeManager,
966
- });
967
- return null;
968
- }
969
-
970
- /** No lease release here: only the post-land tail releases it. */
971
1082
  async function armPhase(ctx, deps) {
972
1083
  ctx.setPhase('auto-merge');
973
1084
  const ciDelivery = getCiDelivery(deps.config);
@@ -1022,13 +1133,13 @@ async function finishPhase(ctx, deps) {
1022
1133
  autoMergeEnabled: arm.autoMergeEnabled,
1023
1134
  autoMergeReason: arm.autoMergeReason,
1024
1135
  advisoryGate: arm.advisoryGate,
1025
- worktreeReaped: ctx.worktreeReaped,
1136
+ worktreePath: ctx.worktreePath,
1026
1137
  localCleanupDeferred: arm.localCleanupDeferred,
1027
1138
  directMerged: arm.directMerged,
1028
1139
  config: deps.config,
1029
1140
  startedAtMs: ctx.startedAtMs,
1030
1141
  phaseTimer: ctx.phaseTimer,
1031
- workerTokens: ctx.workerTokens,
1142
+ worker: ctx.worker,
1032
1143
  lockWait: ctx.prePush.lockWait,
1033
1144
  suiteTimings: ctx.prePush.suiteTimings,
1034
1145
  gates: closeEnvelopeGates(
@@ -1057,9 +1168,8 @@ const CLOSE_PIPELINE = Object.freeze([
1057
1168
  loadStoryPhase,
1058
1169
  graphqlPreflightPhase,
1059
1170
  resolveBasePhase,
1060
- prePushPhase,
1061
- openPrPhase,
1062
- reapWorktreePhaseStep,
1171
+ unlessLanded(prePushPhase, landedPrePush),
1172
+ unlessLanded(openPrPhase, landedPr),
1063
1173
  armPhase,
1064
1174
  finishPhase,
1065
1175
  ]);
@@ -1074,7 +1184,10 @@ async function runClosePipeline(run, deps) {
1074
1184
  ...run,
1075
1185
  storyId: run.options.storyId,
1076
1186
  storyBranch: getStoryBranch(run.options.storyId),
1077
- workerTokens: resolveWorkerTokens(run.options.workerTokens),
1187
+ worker: {
1188
+ workerTokens: resolveWorkerTokens(run.options.workerTokens),
1189
+ workerModel: resolveWorkerModel(run.options.workerModel),
1190
+ },
1078
1191
  };
1079
1192
  for (const phase of CLOSE_PIPELINE) {
1080
1193
  const ending = await phase(ctx, deps);