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
@@ -67,7 +67,11 @@
67
67
  null
68
68
  ]
69
69
  },
70
- "autoMergeEnabled": { "type": ["boolean", "null"] }
70
+ "autoMergeEnabled": { "type": ["boolean", "null"] },
71
+ "autoMergeReason": {
72
+ "type": ["string", "null"],
73
+ "description": "Story #5533 — why close did not arm (disabled-by-flag, disabled-by-policy-strict, an arm failure), or null when it armed. With autoMergeEnabled it is the evidence a resumed wait needs before it may re-arm a PR a new head disarmed: an operator-owned merge is never re-armed."
74
+ }
71
75
  },
72
76
  "additionalProperties": false
73
77
  },
@@ -85,6 +89,7 @@
85
89
  "required": [
86
90
  "followUps",
87
91
  "statusResync",
92
+ "worktreeReap",
88
93
  "refCleanup",
89
94
  "baseFastForward",
90
95
  "tempPurge",
@@ -94,6 +99,10 @@
94
99
  "properties": {
95
100
  "followUps": { "type": "boolean" },
96
101
  "statusResync": { "type": "boolean" },
102
+ "worktreeReap": {
103
+ "type": "boolean",
104
+ "description": "Story #5533 — the Story worktree was reaped. Worktree lifetime is Story lifetime: the close pipeline no longer reaps, so a pending, blocked or failed close keeps its working copy, and this step — run under the post-land lock BEFORE refCleanup, because git branch -D refuses a branch a live worktree holds — is the one place it is removed. Nothing to reap, or delivery.worktreeIsolation.reapOnSuccess false, reports true (details.worktreeReap says which); a refused reap (a dirty tree) reports false, and like every tail step that degrades the report, never the land."
105
+ },
97
106
  "refCleanup": { "type": "boolean" },
98
107
  "baseFastForward": { "type": "boolean" },
99
108
  "tempPurge": {
@@ -0,0 +1,129 @@
1
+ // .agents/scripts/lib/orchestration/cancelled-run-discount.js
2
+ /**
3
+ * cancelled-run-discount.js — a red required check from a run that concluded
4
+ * `cancelled` takes the verdict of the newest other run of its workflow on
5
+ * the same head SHA. Every read fails closed: the red stands.
6
+ */
7
+
8
+ import { gh } from '../gh-exec.js';
9
+ import { checkVerdict } from './check-state.js';
10
+ import { parseWorkflowRunId } from './merge-poll.js';
11
+
12
+ const REPO_PLACEHOLDER = '{owner}/{repo}';
13
+
14
+ async function defaultGhApi(endpoint) {
15
+ const { stdout } = await gh.api({ endpoint });
16
+ return JSON.parse(stdout);
17
+ }
18
+
19
+ function repoSegment(repo) {
20
+ const trimmed = String(repo ?? '').trim();
21
+ return trimmed.length > 0 ? trimmed : REPO_PLACEHOLDER;
22
+ }
23
+
24
+ async function readJson(ghApiFn, endpoint) {
25
+ try {
26
+ const body = await ghApiFn(endpoint);
27
+ return body && typeof body === 'object' ? body : null;
28
+ } catch {
29
+ return null;
30
+ }
31
+ }
32
+
33
+ function parseCancelledRun(body) {
34
+ if (body?.conclusion !== 'cancelled') return null;
35
+ const headSha = body.head_sha;
36
+ const workflowId = body.workflow_id;
37
+ if (typeof headSha !== 'string' || headSha.length === 0) return null;
38
+ if (!Number.isInteger(workflowId) || workflowId < 1) return null;
39
+ return { headSha, workflowId };
40
+ }
41
+
42
+ /** Newest sibling by run id, never start time (the cancelled job starts later). */
43
+ function pickLiveSibling(body, cancelledRunId) {
44
+ const runs = Array.isArray(body?.workflow_runs) ? body.workflow_runs : [];
45
+ let newest = null;
46
+ for (const run of runs) {
47
+ const id = run?.id;
48
+ if (!Number.isInteger(id) || id === cancelledRunId) continue;
49
+ if (newest === null || id > newest.id) {
50
+ newest = {
51
+ id,
52
+ status: String(run.status ?? ''),
53
+ conclusion: String(run.conclusion ?? ''),
54
+ };
55
+ }
56
+ }
57
+ return newest;
58
+ }
59
+
60
+ /** @returns {'pending'|'success'|'failure'} */
61
+ function siblingOutcome(sibling) {
62
+ if (sibling.status !== 'completed') return 'pending';
63
+ return sibling.conclusion === 'success' ? 'success' : 'failure';
64
+ }
65
+
66
+ function lastEntryByName(entries) {
67
+ const byName = new Map();
68
+ for (const e of entries) byName.set(e.name, e);
69
+ return byName;
70
+ }
71
+
72
+ /**
73
+ * One per watcher invocation: a `cancelled` read is final, so it is cached
74
+ * per run id; the sibling list is re-read on every call.
75
+ *
76
+ * @returns {(entries: object[], outcomes: object) => Promise<object>}
77
+ */
78
+ export function createCancelledRunDiscount({
79
+ repo = null,
80
+ ghApiFn = defaultGhApi,
81
+ logger = {},
82
+ } = {}) {
83
+ const base = `repos/${repoSegment(repo)}/actions`;
84
+ const cancelledRuns = new Map();
85
+
86
+ async function readCancelledRun(runId) {
87
+ if (cancelledRuns.has(runId)) return cancelledRuns.get(runId);
88
+ const run = parseCancelledRun(
89
+ await readJson(ghApiFn, `${base}/runs/${runId}`),
90
+ );
91
+ if (run) cancelledRuns.set(runId, run);
92
+ return run;
93
+ }
94
+
95
+ async function discountOne(name, entry) {
96
+ const runId = parseWorkflowRunId(entry?.link);
97
+ if (runId === null) return null;
98
+ const run = await readCancelledRun(runId);
99
+ if (!run) return null;
100
+ const sibling = pickLiveSibling(
101
+ await readJson(
102
+ ghApiFn,
103
+ `${base}/workflows/${run.workflowId}/runs?head_sha=${run.headSha}`,
104
+ ),
105
+ runId,
106
+ );
107
+ if (!sibling) return null;
108
+ const outcome = siblingOutcome(sibling);
109
+ logger.info?.(
110
+ `[Watcher] required check "${name}" failed in concurrency-cancelled run ${runId}; ` +
111
+ `reading live run ${sibling.id} instead (${outcome}).`,
112
+ );
113
+ return outcome;
114
+ }
115
+
116
+ return async function discount(entries, outcomes) {
117
+ const red = Object.keys(outcomes).filter(
118
+ (name) => checkVerdict(outcomes[name]) === 'fail',
119
+ );
120
+ if (red.length === 0) return outcomes;
121
+ const byName = lastEntryByName(entries);
122
+ const out = { ...outcomes };
123
+ for (const name of red) {
124
+ const outcome = await discountOne(name, byName.get(name));
125
+ if (outcome !== null) out[name] = outcome;
126
+ }
127
+ return out;
128
+ };
129
+ }
@@ -18,6 +18,11 @@ import {
18
18
  deriveChecksStatus,
19
19
  isPrMerged,
20
20
  } from './merge-poll.js';
21
+ import { readMergeQueueState as defaultReadMergeQueueState } from './merge-queue.js';
22
+ import {
23
+ closeArmedPr,
24
+ manualArmCommand,
25
+ } from './single-story-close/phases/auto-merge.js';
21
26
  import { NEXT_COMMANDS } from './story-deliver-terminal.js';
22
27
  import { STATE_LABELS } from './ticketing.js';
23
28
 
@@ -87,25 +92,82 @@ export function probeBranch({ cwd, storyBranch, config, gitSpawnFn }) {
87
92
  };
88
93
  }
89
94
 
95
+ /**
96
+ * Whether the row carries an auto-merge request; `undefined` when the field
97
+ * was not returned, so an unread field never reads as a disarm.
98
+ *
99
+ * @param {object|null|undefined} row
100
+ * @returns {boolean|undefined}
101
+ */
102
+ function readAutoMergeArmed(row) {
103
+ if (!row || !Object.hasOwn(row, 'autoMergeRequest')) return undefined;
104
+ return row.autoMergeRequest != null;
105
+ }
106
+
107
+ /**
108
+ * Merge-queue facts for an open, un-armed PR only: GitHub clears the
109
+ * auto-merge request on enqueue, so a queued PR looks un-armed. A read.
110
+ *
111
+ * @returns {Promise<{ inMergeQueue?: boolean|null, queueRequired?: boolean|null }>}
112
+ */
113
+ async function probePrQueue({ pr, nodeId, gh, readMergeQueueStateFn }) {
114
+ if (pr.state !== 'OPEN' || pr.autoMergeArmed !== false) return {};
115
+ const queue = await readMergeQueueStateFn({
116
+ prNumber: pr.number,
117
+ prNodeId: typeof nodeId === 'string' && nodeId ? nodeId : undefined,
118
+ gh,
119
+ });
120
+ return {
121
+ inMergeQueue: queue?.inQueue ?? null,
122
+ queueRequired: queue?.queueRequired ?? null,
123
+ };
124
+ }
125
+
90
126
  /**
91
127
  * `--state all`: the merged-but-label-stale strand needs the merged PR.
92
128
  *
93
129
  * @returns {Promise<object|null>}
94
130
  */
95
- export async function probePr({ storyBranch, gh = defaultGh }) {
131
+ export async function probePr({
132
+ storyBranch,
133
+ gh = defaultGh,
134
+ readMergeQueueStateFn = defaultReadMergeQueueState,
135
+ }) {
96
136
  try {
97
137
  const rows = await gh.pr.list(
98
138
  ['--head', storyBranch, '--state', 'all'],
99
- ['number', 'url', 'state', 'mergedAt', 'statusCheckRollup'],
139
+ [
140
+ 'number',
141
+ 'url',
142
+ 'state',
143
+ 'mergedAt',
144
+ 'statusCheckRollup',
145
+ 'mergeStateStatus',
146
+ 'autoMergeRequest',
147
+ 'headRefOid',
148
+ 'id',
149
+ ],
100
150
  );
101
151
  if (!Array.isArray(rows) || rows.length === 0) return null;
102
152
  const row = rows[0];
103
- return {
153
+ const pr = {
104
154
  number: Number(row?.number) || null,
105
155
  url: row?.url ?? null,
106
156
  state: row?.state ?? null,
107
157
  mergedAt: row?.mergedAt ?? null,
108
158
  checksStatus: deriveChecksStatus(row?.statusCheckRollup),
159
+ mergeStateStatus: row?.mergeStateStatus ?? null,
160
+ autoMergeArmed: readAutoMergeArmed(row),
161
+ headSha: row?.headRefOid ?? null,
162
+ };
163
+ return {
164
+ ...pr,
165
+ ...(await probePrQueue({
166
+ pr,
167
+ nodeId: row?.id,
168
+ gh,
169
+ readMergeQueueStateFn,
170
+ })),
109
171
  };
110
172
  } catch (err) {
111
173
  return { error: String(err?.message ?? err) };
@@ -380,6 +442,8 @@ export function decideRecovery({
380
442
  `issue=${ticket?.issueState ?? 'unknown'}`,
381
443
  `pr=${pr?.number ? `#${pr.number} ${pr.state ?? '?'}` : 'none'}`,
382
444
  `checks=${pr?.checksStatus ?? 'n/a'}`,
445
+ `mergeState=${pr?.mergeStateStatus ?? 'n/a'}`,
446
+ `autoMerge=${pr?.autoMergeArmed === undefined ? 'n/a' : pr.autoMergeArmed ? 'armed' : 'unarmed'}`,
383
447
  `branch.local=${branch?.local ?? false}`,
384
448
  `branch.remote=${branch?.remote ?? false}`,
385
449
  `worktree=${branch?.worktreePath ?? 'none'}`,
@@ -427,37 +491,7 @@ export function decideRecovery({
427
491
  }
428
492
 
429
493
  if (label === STATE_LABELS.CLOSING) {
430
- if (pr?.checksStatus === 'failure') {
431
- return {
432
- shape: 'closing-pr-red',
433
- nextCommand: NEXT_COMMANDS.watchCi(storyId, pr.number),
434
- detail:
435
- `PR #${pr.number} has a red required check. Waiting cannot help — fix the ` +
436
- `failure and push a new commit on \`story-${storyId}\`; the red disarmed ` +
437
- `auto-merge, and only a green on a new head SHA re-arms it.`,
438
- evidence,
439
- };
440
- }
441
- if (pr?.number) {
442
- return {
443
- shape: 'closing-pr-pending',
444
- nextCommand: NEXT_COMMANDS.resumeLand(storyId),
445
- detail:
446
- `PR #${pr.number} is open and healthy. This is the normal resumable shape after ` +
447
- `a bounded merge wait returned \`pending\`. The confirm CLI polls it to a ` +
448
- `confirmed merge and runs the land tail.`,
449
- evidence,
450
- };
451
- }
452
- return {
453
- shape: 'closing-no-pr',
454
- nextCommand: NEXT_COMMANDS.close(storyId),
455
- detail:
456
- `Story is at \`agent::closing\` but no PR exists for \`story-${storyId}\`. The ` +
457
- `close did not reach the pull-request phase; re-run it (close is idempotent and ` +
458
- `reuses an existing PR when one is found).`,
459
- evidence,
460
- };
494
+ return decideClosing({ storyId, branch, pr, closeArtifacts, evidence });
461
495
  }
462
496
 
463
497
  if (label === STATE_LABELS.EXECUTING) {
@@ -474,6 +508,104 @@ export function decideRecovery({
474
508
  };
475
509
  }
476
510
 
511
+ /**
512
+ * `main` moved under the PR and it no longer merges cleanly. Close re-syncs
513
+ * in the Story worktree (recreating it when missing).
514
+ */
515
+ function conflictedVerdict({ storyId, branch, pr, evidence }) {
516
+ const worktree = branch?.worktreePath ?? `.worktrees/story-${storyId}`;
517
+ return {
518
+ shape: 'closing-pr-conflicted',
519
+ nextCommand: NEXT_COMMANDS.close(storyId),
520
+ detail:
521
+ `PR #${pr.number} is DIRTY: its base moved and it no longer merges cleanly, so ` +
522
+ `waiting cannot land it. Re-run close: it merges origin/<base> into \`story-${storyId}\` ` +
523
+ `in the Story worktree (\`${worktree}\`), recreating that worktree when it is missing, ` +
524
+ `and pushes a clean merge. If close reports conflicted files, resolve exactly those in ` +
525
+ `the worktree, commit, and re-run close.`,
526
+ evidence,
527
+ };
528
+ }
529
+
530
+ /** A new head disarmed auto-merge; the resumed wait re-arms it. */
531
+ function unarmedVerdict({ storyId, pr, evidence }) {
532
+ const command = `\`${manualArmCommand({ prNumber: pr.number, queueRequired: pr.queueRequired === true })}\``;
533
+ const manual =
534
+ pr.queueRequired === true
535
+ ? `${command} (the base requires a merge queue, so the queue rule picks the strategy)`
536
+ : command;
537
+ return {
538
+ shape: 'closing-pr-unarmed',
539
+ nextCommand: NEXT_COMMANDS.resumeLand(storyId),
540
+ detail:
541
+ `PR #${pr.number} is open with no red check, but it has NO auto-merge request — a new ` +
542
+ `head disarmed it, so nothing will ever merge it. The resumed merge wait re-arms it ` +
543
+ `(once per head SHA, unless a CI red was recorded against this same head). The manual ` +
544
+ `equivalent is ${manual}.`,
545
+ evidence,
546
+ };
547
+ }
548
+
549
+ /**
550
+ * Un-armed by a new head — only when the last close's envelope proves close
551
+ * armed it; an operator-owned PR (`--no-auto-merge`, `strict`) is never one.
552
+ */
553
+ function isUnarmed(pr, closeArtifacts) {
554
+ const envelope = closeArtifacts?.envelope;
555
+ return (
556
+ closeArmedPr(envelope?.pr) &&
557
+ pr?.state === 'OPEN' &&
558
+ pr.autoMergeArmed === false &&
559
+ pr.inMergeQueue !== true &&
560
+ pr.checksStatus !== 'failure'
561
+ );
562
+ }
563
+
564
+ /**
565
+ * The `agent::closing` rows; conflicted and un-armed come before red.
566
+ *
567
+ * @returns {{ shape: string, nextCommand: string, detail: string, evidence: string[] }}
568
+ */
569
+ function decideClosing({ storyId, branch, pr, closeArtifacts, evidence }) {
570
+ if (pr?.number && pr.mergeStateStatus === 'DIRTY') {
571
+ return conflictedVerdict({ storyId, branch, pr, evidence });
572
+ }
573
+ if (pr?.number && isUnarmed(pr, closeArtifacts)) {
574
+ return unarmedVerdict({ storyId, pr, evidence });
575
+ }
576
+ if (pr?.checksStatus === 'failure') {
577
+ return {
578
+ shape: 'closing-pr-red',
579
+ nextCommand: NEXT_COMMANDS.watchCi(storyId, pr.number),
580
+ detail:
581
+ `PR #${pr.number} has a red required check. Waiting cannot help — fix the ` +
582
+ `failure and push a new commit on \`story-${storyId}\`; the red disarmed ` +
583
+ `auto-merge, and only a green on a new head SHA re-arms it.`,
584
+ evidence,
585
+ };
586
+ }
587
+ if (pr?.number) {
588
+ return {
589
+ shape: 'closing-pr-pending',
590
+ nextCommand: NEXT_COMMANDS.resumeLand(storyId),
591
+ detail:
592
+ `PR #${pr.number} is open and healthy. This is the normal resumable shape after ` +
593
+ `a bounded merge wait returned \`pending\`. The confirm CLI polls it to a ` +
594
+ `confirmed merge and runs the land tail.`,
595
+ evidence,
596
+ };
597
+ }
598
+ return {
599
+ shape: 'closing-no-pr',
600
+ nextCommand: NEXT_COMMANDS.close(storyId),
601
+ detail:
602
+ `Story is at \`agent::closing\` but no PR exists for \`story-${storyId}\`. The ` +
603
+ `close did not reach the pull-request phase; re-run it (close is idempotent and ` +
604
+ `reuses an existing PR when one is found).`,
605
+ evidence,
606
+ };
607
+ }
608
+
477
609
  /**
478
610
  * Shapes a live delivery may be mutating (e.g. a PR about to open), so they
479
611
  * earn a stability re-probe; the other shapes are settled.
@@ -8,6 +8,7 @@
8
8
  import { spawnSync } from 'node:child_process';
9
9
 
10
10
  import { applyBehindUpdate } from './behind-recovery.js';
11
+ import { createCancelledRunDiscount } from './cancelled-run-discount.js';
11
12
  import { checkVerdict, classifyRequiredCheck } from './check-state.js';
12
13
 
13
14
  /**
@@ -32,7 +33,7 @@ function ghPrChecks({ prUrl, cwd, repo, spawnFn = spawnSync }) {
32
33
  prUrl,
33
34
  '--required',
34
35
  '--json',
35
- 'name,state,bucket,workflow',
36
+ 'name,state,bucket,workflow,link',
36
37
  ...ghRepoFlag(repo),
37
38
  ],
38
39
  { cwd, encoding: 'utf-8', shell: false },
@@ -144,6 +145,10 @@ export function hasFailingCheck(outcomes) {
144
145
  return Object.values(outcomes).some((v) => checkVerdict(v) === 'fail');
145
146
  }
146
147
 
148
+ async function identityDiscount(_entries, outcomes) {
149
+ return outcomes;
150
+ }
151
+
147
152
  function defaultSleep(ms) {
148
153
  return new Promise((resolve) => setTimeout(resolve, ms));
149
154
  }
@@ -161,6 +166,7 @@ function defaultSleep(ms) {
161
166
  * @param {Function} opts.ghPrChecksFn
162
167
  * @param {number} opts.pollIntervalMs
163
168
  * @param {Function} opts.sleepFn
169
+ * @param {Function} [opts.discountFn]
164
170
  * @param {{ warn?: Function }} opts.logger
165
171
  * @returns {Promise<{ outcomes: object, polls: number }>}
166
172
  */
@@ -174,6 +180,7 @@ export async function pollUntilTerminal({
174
180
  ghPrChecksFn,
175
181
  pollIntervalMs,
176
182
  sleepFn,
183
+ discountFn = identityDiscount,
177
184
  logger,
178
185
  }) {
179
186
  let currentOutcomes = outcomes;
@@ -189,7 +196,7 @@ export async function pollUntilTerminal({
189
196
  );
190
197
  continue;
191
198
  }
192
- currentOutcomes = reduceOutcomes(entries);
199
+ currentOutcomes = await discountFn(entries, reduceOutcomes(entries));
193
200
  }
194
201
  return { outcomes: currentOutcomes, polls: currentPolls };
195
202
  }
@@ -212,6 +219,7 @@ export async function pollUntilTerminal({
212
219
  * @param {Function} [opts.ghPrViewFn]
213
220
  * @param {Function} [opts.ghPrUpdateBranchFn]
214
221
  * @param {Function} [opts.sleepFn]
222
+ * @param {Function} [opts.ghApiFn]
215
223
  * @param {{ info?: Function, warn?: Function, debug?: Function }} opts.logger
216
224
  * @param {{status:number,stdout:string,stderr:string}} [opts.firstProbe]
217
225
  * An already-issued `gh pr checks` result, so the first call is not
@@ -243,6 +251,7 @@ export async function watchPrToTerminal({
243
251
  ghPrViewFn = ghPrView,
244
252
  ghPrUpdateBranchFn = ghPrUpdateBranch,
245
253
  sleepFn = defaultSleep,
254
+ ghApiFn,
246
255
  logger,
247
256
  firstProbe,
248
257
  }) {
@@ -277,7 +286,8 @@ export async function watchPrToTerminal({
277
286
 
278
287
  const requiredChecks = firstEntries.map((e) => e.name);
279
288
 
280
- let outcomes = reduceOutcomes(firstEntries);
289
+ const discountFn = createCancelledRunDiscount({ repo, ghApiFn, logger });
290
+ let outcomes = await discountFn(firstEntries, reduceOutcomes(firstEntries));
281
291
  let polls = 0;
282
292
  let updatesApplied = 0;
283
293
  let resumesApplied = 0;
@@ -294,6 +304,7 @@ export async function watchPrToTerminal({
294
304
  ghPrChecksFn,
295
305
  pollIntervalMs,
296
306
  sleepFn,
307
+ discountFn,
297
308
  logger,
298
309
  }));
299
310
  // BEHIND recovery only when all green; `maxUpdates` stops a racing
@@ -39,6 +39,19 @@ export function isOperatorMergeReason(reason) {
39
39
  return OPERATOR_MERGE_ARM_REASONS.includes(reason);
40
40
  }
41
41
 
42
+ /**
43
+ * Positive evidence that close itself armed this PR — never an operator-owned
44
+ * merge (`--no-auto-merge`, `strict`), and never an envelope that says nothing.
45
+ *
46
+ * @param {{ autoMergeEnabled?: boolean|null, autoMergeReason?: string|null }|null|undefined} pr
47
+ * @returns {boolean}
48
+ */
49
+ export function closeArmedPr(pr) {
50
+ return (
51
+ pr?.autoMergeEnabled === true && !isOperatorMergeReason(pr?.autoMergeReason)
52
+ );
53
+ }
54
+
42
55
  /**
43
56
  * A `gh pr merge --delete-branch` failure whose only casualty is the LOCAL
44
57
  * head-branch delete after the remote merge/arm already happened. Deliberately
@@ -132,6 +145,38 @@ export async function enableAutoMergeWith({
132
145
  return arm({ exec, prNumber, armCwd });
133
146
  }
134
147
 
148
+ /** The hand-run equivalent of the arm, for an operator-facing remedy. */
149
+ export function manualArmCommand({ prNumber, queueRequired = false }) {
150
+ return queueRequired
151
+ ? `gh pr merge ${prNumber} --auto`
152
+ : `gh pr merge ${prNumber} --auto --squash --delete-branch`;
153
+ }
154
+
155
+ /**
156
+ * Re-arm a PR a new head disarmed, from the merge wait. Same merge-queue
157
+ * detection as the arm phase, so a queue base gets the bare `--auto`. Lives
158
+ * here because `lifecycle-lint` confines `gh pr merge` to this module.
159
+ * Non-fatal, like the arm.
160
+ *
161
+ * @param {{ cwd: string, prNumber: number, gh?: object,
162
+ * readMergeQueueStateFn?: typeof readMergeQueueState }} args
163
+ * @returns {Promise<{ enabled: boolean, reason?: string }>}
164
+ */
165
+ export async function rearmAutoMerge({
166
+ cwd,
167
+ prNumber,
168
+ gh,
169
+ readMergeQueueStateFn = readMergeQueueState,
170
+ }) {
171
+ const queue = await readMergeQueueStateFn({ prNumber, gh });
172
+ return enableAutoMergeWith({
173
+ cwd,
174
+ prNumber,
175
+ gh,
176
+ queueRequired: queue?.queueRequired === true,
177
+ });
178
+ }
179
+
135
180
  /**
136
181
  * `--auto --squash --delete-branch`, falling back to a direct squash-merge
137
182
  * only when native auto-merge is unavailable.
@@ -121,6 +121,11 @@ function isHandedBack(result, baseConfirmed) {
121
121
  return result.kind === 'conflict' && baseConfirmed === true;
122
122
  }
123
123
 
124
+ /** `handBack`: the merge wait, whose PR is open, hands every failure back. */
125
+ function resolveHandedBack({ result, baseConfirmed, handBack }) {
126
+ return handBack === true || isHandedBack(result, baseConfirmed);
127
+ }
128
+
124
129
  /**
125
130
  * The CRAP scoring scope, or `[]` when unresolvable.
126
131
  *
@@ -187,8 +192,9 @@ function buildStampInvalidatedWarning({ baseBranch, result, targetDirs }) {
187
192
  * baseConfirmed?: boolean,
188
193
  * storyBranch: string,
189
194
  * result: { kind: string, conflictFiles?: string[], stderr?: string },
195
+ * handBack?: boolean,
190
196
  * progress: (tag: string, msg: string) => void,
191
- * }} args
197
+ * }} args `handBack` leaves the labels alone for every failure kind.
192
198
  * @returns {Promise<{ handedBack: boolean }>}
193
199
  */
194
200
  export async function handleSyncFailure({
@@ -199,6 +205,7 @@ export async function handleSyncFailure({
199
205
  baseConfirmed = false,
200
206
  storyBranch,
201
207
  result,
208
+ handBack = false,
202
209
  progress,
203
210
  }) {
204
211
  const body = buildSyncFailureCommentBody({
@@ -208,6 +215,7 @@ export async function handleSyncFailure({
208
215
  baseConfirmed,
209
216
  syncCwd,
210
217
  result,
218
+ handBack,
211
219
  });
212
220
 
213
221
  // Comment first so the recovery surface lands even if the flip fails; a
@@ -221,7 +229,7 @@ export async function handleSyncFailure({
221
229
  );
222
230
  }
223
231
 
224
- const handedBack = isHandedBack(result, baseConfirmed);
232
+ const handedBack = resolveHandedBack({ result, baseConfirmed, handBack });
225
233
  await settleSyncFailureLabels({ provider, storyId, handedBack, progress });
226
234
  return { handedBack };
227
235
  }
@@ -330,7 +338,7 @@ function failureEvidence(kind, result) {
330
338
  * advice: merging a base the Story was not seeded from contaminates the
331
339
  * branch and PR diff, so an unconfirmed base gets "establish it first".
332
340
  *
333
- * @param {{ storyId: number, storyBranch: string, baseBranch: string, baseConfirmed?: boolean, syncCwd: string, result: { kind: string, conflictFiles?: string[], stderr?: string } }} args
341
+ * @param {{ storyId: number, storyBranch: string, baseBranch: string, baseConfirmed?: boolean, syncCwd: string, result: { kind: string, conflictFiles?: string[], stderr?: string }, handBack?: boolean }} args
334
342
  * @returns {string}
335
343
  */
336
344
  export function buildSyncFailureCommentBody({
@@ -340,9 +348,10 @@ export function buildSyncFailureCommentBody({
340
348
  baseConfirmed = false,
341
349
  syncCwd,
342
350
  result,
351
+ handBack = false,
343
352
  }) {
344
353
  const kind = result.kind ?? 'unknown';
345
- const handedBack = isHandedBack(result, baseConfirmed);
354
+ const handedBack = resolveHandedBack({ result, baseConfirmed, handBack });
346
355
  const heading =
347
356
  kind === 'conflict'
348
357
  ? `Base-sync conflict on close: ${storyBranch} ↔ origin/${baseBranch}`