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,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
+ }
@@ -110,11 +110,27 @@ export function assertNoRetiredFlags(argv) {
110
110
  }
111
111
  }
112
112
 
113
+ /**
114
+ * The story-worker figures close records in its telemetry. Raw: validated
115
+ * best-effort by the runner, never thrown on.
116
+ *
117
+ * @param {unknown} tokensParam
118
+ * @param {unknown} modelParam
119
+ * @param {{ workerTokens?: unknown, workerModel?: unknown }} parsed
120
+ * @returns {{ workerTokens: unknown, workerModel: unknown }}
121
+ */
122
+ function workerFlags(tokensParam, modelParam, parsed) {
123
+ return {
124
+ workerTokens: resolveFlag(tokensParam, parsed.workerTokens),
125
+ workerModel: resolveFlag(modelParam, parsed.workerModel),
126
+ };
127
+ }
128
+
113
129
  /**
114
130
  * Returns raw wait-for-merge intent; the runner resolves it after the arm.
115
131
  *
116
- * @param {{ storyIdParam, cwdParam, skipValidationParam, skipSyncParam, noAutoMergeParam, waitForMergeParam, noWaitForMergeParam, maxWaitSecondsParam, mergeWatchModeParam, rerunAdvisoryParam, overrideReviewBlockParam, workerTokensParam }} raw
117
- * @returns {{ storyId, cwd, skipValidation, skipSync, noAutoMerge, waitForMergeExplicit, noWaitForMerge, maxWaitSeconds, mergeWatchMode, rerunAdvisory, overrideReviewBlock, workerTokens }}
132
+ * @param {{ storyIdParam, cwdParam, skipValidationParam, skipSyncParam, noAutoMergeParam, waitForMergeParam, noWaitForMergeParam, maxWaitSecondsParam, mergeWatchModeParam, rerunAdvisoryParam, overrideReviewBlockParam, workerTokensParam, workerModelParam }} raw
133
+ * @returns {{ storyId, cwd, skipValidation, skipSync, noAutoMerge, waitForMergeExplicit, noWaitForMerge, maxWaitSeconds, mergeWatchMode, rerunAdvisory, overrideReviewBlock, workerTokens, workerModel }}
118
134
  */
119
135
  export function parseCloseOptions({
120
136
  storyIdParam,
@@ -129,6 +145,7 @@ export function parseCloseOptions({
129
145
  rerunAdvisoryParam,
130
146
  overrideReviewBlockParam,
131
147
  workerTokensParam,
148
+ workerModelParam,
132
149
  }) {
133
150
  // An injecting caller never reads argv (the host's flags are not its
134
151
  // business), so `parsed` stays empty and the retired-flag guard is skipped.
@@ -169,7 +186,6 @@ export function parseCloseOptions({
169
186
  overrideReviewBlock: parseOverrideReviewBlock(
170
187
  resolveFlag(overrideReviewBlockParam, parsed.overrideReviewBlock),
171
188
  ),
172
- // Raw: validated best-effort by the runner, never thrown on.
173
- workerTokens: resolveFlag(workerTokensParam, parsed.workerTokens),
189
+ ...workerFlags(workerTokensParam, workerModelParam, parsed),
174
190
  };
175
191
  }
@@ -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
+ }
@@ -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
  }