mandrel 2.92.0 → 2.94.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 (31) hide show
  1. package/.agents/docs/configuration.md +40 -1
  2. package/.agents/schemas/lifecycle/merge.unlanded.schema.json +2 -1
  3. package/.agents/schemas/story-deliver-terminal.schema.json +1 -0
  4. package/.agents/scripts/lib/config/github.js +18 -0
  5. package/.agents/scripts/lib/config-resolver.js +2 -2
  6. package/.agents/scripts/lib/duplicate-search.js +52 -18
  7. package/.agents/scripts/lib/feedback-loop/prior-feedback-fetcher.js +47 -20
  8. package/.agents/scripts/lib/gh-exec.js +94 -24
  9. package/.agents/scripts/lib/gh-pr-rest.js +371 -0
  10. package/.agents/scripts/lib/orchestration/board-graphql-latch.js +75 -0
  11. package/.agents/scripts/lib/orchestration/ci-rerun-guard.js +73 -29
  12. package/.agents/scripts/lib/orchestration/column-sync.js +23 -21
  13. package/.agents/scripts/lib/orchestration/lease-guard-shared.js +2 -2
  14. package/.agents/scripts/lib/orchestration/merge-block-class.js +3 -1
  15. package/.agents/scripts/lib/orchestration/merge-queue.js +49 -4
  16. package/.agents/scripts/lib/orchestration/project-meta-resolver.js +2 -2
  17. package/.agents/scripts/lib/orchestration/required-checks.js +72 -12
  18. package/.agents/scripts/lib/orchestration/single-story-close/phases/auto-merge.js +132 -58
  19. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +92 -9
  20. package/.agents/scripts/lib/orchestration/single-story-close/phases/graphql-preflight.js +41 -18
  21. package/.agents/scripts/lib/orchestration/single-story-lease-guard.js +2 -1
  22. package/.agents/scripts/lib/orchestration/ticket-lease.js +69 -18
  23. package/.agents/scripts/lib/orchestration/ticketing/transition.js +1 -1
  24. package/.agents/scripts/providers/github/board-add.js +3 -3
  25. package/.agents/scripts/providers/github/compose.js +2 -0
  26. package/.agents/scripts/providers/github/errors.js +41 -0
  27. package/.agents/scripts/providers/github/sub-issues-rest.js +55 -0
  28. package/.agents/scripts/providers/github/sub-issues.js +9 -1
  29. package/.agents/scripts/single-story-confirm-merge.js +2 -0
  30. package/docs/CHANGELOG.md +19 -0
  31. package/package.json +1 -1
@@ -26,7 +26,8 @@ export const BLOCK_CLASSES = Object.freeze([
26
26
 
27
27
  /**
28
28
  * Plus classes emitted directly, never by the classifier: `predicate-refused`
29
- * (kept so archived records validate) and the advisory-gate pair.
29
+ * (kept so archived records validate), the advisory-gate pair, and the REST
30
+ * transport's merge-queue refusal (`merge-queue.js` owns its constant).
30
31
  */
31
32
  export const MERGE_UNLANDED_BLOCK_CLASSES = Object.freeze([
32
33
  ...BLOCK_CLASSES,
@@ -34,6 +35,7 @@ export const MERGE_UNLANDED_BLOCK_CLASSES = Object.freeze([
34
35
  // Sourced from the gate's own constants so the vocabulary cannot drift.
35
36
  ADVISORY_GATE_RED_CLASS,
36
37
  ADVISORY_GATE_INCONCLUSIVE_CLASS,
38
+ 'merge-queue-rest-unsupported',
37
39
  ]);
38
40
 
39
41
  const BLOCK_CLASS_SET = new Set(MERGE_UNLANDED_BLOCK_CLASSES);
@@ -1,10 +1,16 @@
1
1
  /**
2
- * merge-queue.js — the one GraphQL seam for a merge-queue-protected base:
3
- * whether the PR's base requires a queue, whether the PR sits in it, and the
4
- * dequeue. Keyed on the PR node, so no owner/repo is needed.
2
+ * merge-queue.js — the one seam for a merge-queue-protected base: whether the
3
+ * PR's base requires a queue, whether the PR sits in it, and the dequeue.
4
+ * GraphQL keys on the PR node, so no owner/repo is needed; the REST transport
5
+ * reads the base's rulesets and cannot see queue membership.
5
6
  */
6
7
 
7
- import { gh as defaultGh, describeGhFailure } from '../gh-exec.js';
8
+ import {
9
+ gh as defaultGh,
10
+ describeGhFailure,
11
+ prTransportOf,
12
+ } from '../gh-exec.js';
13
+ import { readBranchRules } from '../gh-pr-rest.js';
8
14
 
9
15
  /** Bound on each merge-queue GraphQL call, so a wedged `gh` cannot stall close. */
10
16
  const MERGE_QUEUE_GH_TIMEOUT_MS = 30_000;
@@ -18,6 +24,37 @@ const DEQUEUE_MUTATION =
18
24
  /** `gh` stderr when the base requires a merge queue and the arm spelling is wrong. */
19
25
  export const MERGE_QUEUE_REFUSAL = /when merge queue enabled/i;
20
26
 
27
+ /** Block class: a merge-queue base reached over the REST transport. */
28
+ export const MERGE_QUEUE_REST_BLOCK_CLASS = 'merge-queue-rest-unsupported';
29
+
30
+ /** The remedy that block carries: enqueueing is GraphQL-only. */
31
+ export const MERGE_QUEUE_REST_REMEDY =
32
+ "The PR's base branch requires a merge queue, and this session reaches GitHub over " +
33
+ 'repo-scoped REST only (GraphQL answers 403). Enqueueing is GraphQL-only, and a direct ' +
34
+ 'merge would bypass the queue, so close did not merge. Enqueue the PR from a session ' +
35
+ 'that can reach GraphQL (arm auto-merge there) or from the GitHub UI, then confirm with ' +
36
+ '`node .agents/scripts/single-story-confirm-merge.js --story <id>`.';
37
+
38
+ /**
39
+ * REST reading: the base's active rulesets name a `merge_queue` rule.
40
+ * Whether the PR sits in the queue is unreadable, so `inQueue` is null.
41
+ */
42
+ async function readMergeQueueStateRest({ prRef, prNodeId, facade, timeoutMs }) {
43
+ if (!prRef)
44
+ throw new Error('PR number unavailable for the REST merge-queue read');
45
+ const view = await facade.pr.view(String(prRef), ['id', 'baseRefName']);
46
+ const rules = await readBranchRules({
47
+ api: facade.api,
48
+ base: view?.baseRefName,
49
+ timeoutMs,
50
+ });
51
+ return {
52
+ queueRequired: rules.some((rule) => rule?.type === 'merge_queue'),
53
+ inQueue: null,
54
+ prNodeId: prNodeId ?? view?.id ?? null,
55
+ };
56
+ }
57
+
21
58
  /**
22
59
  * @param {{ stdout?: string }|string|undefined} result
23
60
  * @returns {object|null}
@@ -54,6 +91,14 @@ export async function readMergeQueueState({
54
91
  const facade = gh ?? defaultGh;
55
92
  let id = prNodeId ?? null;
56
93
  try {
94
+ if ((await prTransportOf(facade)) === 'rest') {
95
+ return await readMergeQueueStateRest({
96
+ prRef: prRef ?? prNumber,
97
+ prNodeId: id,
98
+ facade,
99
+ timeoutMs,
100
+ });
101
+ }
57
102
  if (!id) {
58
103
  const view = await facade.pr.view(String(prRef ?? prNumber), ['id']);
59
104
  id = typeof view?.id === 'string' && view.id ? view.id : null;
@@ -6,10 +6,10 @@
6
6
  */
7
7
 
8
8
  import {
9
- isProjectAccessFailure,
10
9
  ProjectAccessError,
11
10
  toProjectAccessError,
12
11
  } from './board-access-latch.js';
12
+ import { isBoardAccessFailure } from './board-graphql-latch.js';
13
13
 
14
14
  export { ProjectAccessError };
15
15
 
@@ -69,7 +69,7 @@ async function queryRung(
69
69
  );
70
70
  return data?.[scope.root]?.projectV2 ?? null;
71
71
  } catch (err) {
72
- if (isProjectAccessFailure(err)) throw toProjectAccessError(err);
72
+ if (isBoardAccessFailure(err)) throw toProjectAccessError(err);
73
73
  return null;
74
74
  }
75
75
  }
@@ -1,8 +1,11 @@
1
1
  /**
2
- * GitHub's per-PR required-check attribution (GraphQL `isRequired`), not
2
+ * GitHub's per-PR required-check attribution (GraphQL `isRequired`, or over
3
+ * the REST transport the base's rulesets plus classic protection), not
3
4
  * `.agentrc` requiredChecks, which are local command names.
4
5
  */
5
6
 
7
+ import { GhNotFoundError, prTransportOf } from '../gh-exec.js';
8
+ import { parseApiJson, readBranchRules } from '../gh-pr-rest.js';
6
9
  import {
7
10
  deriveRequiredRunEvidence,
8
11
  failingChecksBlockMerge,
@@ -71,6 +74,69 @@ function parseRequiredNames(result) {
71
74
  return names;
72
75
  }
73
76
 
77
+ /**
78
+ * Classic branch protection's required contexts; no protection (404) is none.
79
+ *
80
+ * @returns {Promise<string[]>}
81
+ */
82
+ async function readProtectionContexts({ api, base, timeoutMs }) {
83
+ try {
84
+ const body = parseApiJson(
85
+ await api({
86
+ method: 'GET',
87
+ endpoint: `repos/{owner}/{repo}/branches/${encodeURIComponent(base)}/protection/required_status_checks`,
88
+ execOpts: { timeoutMs },
89
+ }),
90
+ );
91
+ return [
92
+ ...(body?.contexts ?? []),
93
+ ...(body?.checks ?? []).map((check) => check?.context),
94
+ ];
95
+ } catch (err) {
96
+ if (err instanceof GhNotFoundError) return [];
97
+ throw err;
98
+ }
99
+ }
100
+
101
+ /**
102
+ * REST required names: `required_status_checks` rules on the base, unioned
103
+ * with classic protection.
104
+ *
105
+ * @returns {Promise<Set<string>>}
106
+ */
107
+ async function readRequiredNamesRest({ prNumber, gh, timeoutMs }) {
108
+ const view = await gh.pr.view(String(prNumber), ['baseRefName']);
109
+ const base = view?.baseRefName;
110
+ if (!base) throw new Error('PR base branch unreadable');
111
+ const [rules, contexts] = await Promise.all([
112
+ readBranchRules({ api: gh.api, base, timeoutMs }),
113
+ readProtectionContexts({ api: gh.api, base, timeoutMs }),
114
+ ]);
115
+ const names = new Set(contexts.filter(Boolean));
116
+ for (const rule of rules) {
117
+ if (rule?.type !== 'required_status_checks') continue;
118
+ for (const check of rule.parameters?.required_status_checks ?? []) {
119
+ if (check?.context) names.add(check.context);
120
+ }
121
+ }
122
+ return names;
123
+ }
124
+
125
+ /** @returns {Promise<Set<string>>} */
126
+ async function readRequiredNamesGraphql({ prNodeId, prNumber, gh, timeoutMs }) {
127
+ return parseRequiredNames(
128
+ await gh.api({
129
+ method: 'POST',
130
+ endpoint: 'graphql',
131
+ body: {
132
+ query: REQUIRED_CHECKS_QUERY,
133
+ variables: { id: prNodeId, n: Number(prNumber) },
134
+ },
135
+ execOpts: { timeoutMs },
136
+ }),
137
+ );
138
+ }
139
+
74
140
  /** Per-head cache: required attribution is read at most once per PR head. */
75
141
  const requiredNamesCache = new Map();
76
142
 
@@ -92,17 +158,11 @@ async function readRequiredCheckNames({
92
158
  const key = `${prNodeId}@${headSha}`;
93
159
  if (requiredNamesCache.has(key)) return requiredNamesCache.get(key);
94
160
  try {
95
- const names = parseRequiredNames(
96
- await gh.api({
97
- method: 'POST',
98
- endpoint: 'graphql',
99
- body: {
100
- query: REQUIRED_CHECKS_QUERY,
101
- variables: { id: prNodeId, n: Number(prNumber) },
102
- },
103
- execOpts: { timeoutMs },
104
- }),
105
- );
161
+ const read =
162
+ (await prTransportOf(gh)) === 'rest'
163
+ ? readRequiredNamesRest
164
+ : readRequiredNamesGraphql;
165
+ const names = await read({ prNodeId, prNumber, gh, timeoutMs });
106
166
  requiredNamesCache.set(key, names);
107
167
  return names;
108
168
  } catch {
@@ -9,7 +9,12 @@
9
9
  * repo's `delete_branch_on_merge` owns the remote branch reap.
10
10
  */
11
11
 
12
- import { gh as defaultGh, describeGhFailure } from '../../../gh-exec.js';
12
+ import {
13
+ gh as defaultGh,
14
+ describeGhFailure,
15
+ prTransportOf,
16
+ } from '../../../gh-exec.js';
17
+ import { REST_MERGE_ON_GREEN } from '../../../gh-pr-rest.js';
13
18
  import { resolveAutoMergeArmCwd } from '../../auto-merge-cwd.js';
14
19
  import {
15
20
  decideAdvisoryGateBlock,
@@ -19,6 +24,7 @@ import {
19
24
  armForMergeQueue,
20
25
  disarmByDequeue,
21
26
  MERGE_QUEUE_REFUSAL,
27
+ MERGE_QUEUE_REST_BLOCK_CLASS,
22
28
  readMergeQueueState,
23
29
  } from '../../merge-queue.js';
24
30
 
@@ -139,12 +145,30 @@ export async function enableAutoMergeWith({
139
145
  resolveArmCwd = resolveAutoMergeArmCwd,
140
146
  queueRequired = false,
141
147
  }) {
142
- const exec = runner ?? makeDefaultGhAutoMergeRunner(gh ?? defaultGh);
148
+ const facade = gh ?? defaultGh;
149
+ const refused = await refuseQueueOverRest(facade, queueRequired);
150
+ if (refused) return refused;
151
+ const exec = runner ?? makeDefaultGhAutoMergeRunner(facade);
143
152
  const armCwd = resolveArmCwd(cwd);
144
153
  const arm = queueRequired ? armForMergeQueue : armNativeAutoMerge;
145
154
  return arm({ exec, prNumber, armCwd });
146
155
  }
147
156
 
157
+ /**
158
+ * A merge-queue base over the REST transport: enqueueing is GraphQL-only, and
159
+ * a direct merge would bypass the queue, so the arm refuses.
160
+ *
161
+ * @returns {Promise<{ enabled: false, mergeQueue: true, reason: string }|null>}
162
+ */
163
+ async function refuseQueueOverRest(facade, queueRequired) {
164
+ if (!queueRequired || (await prTransportOf(facade)) !== 'rest') return null;
165
+ return {
166
+ enabled: false,
167
+ mergeQueue: true,
168
+ reason: MERGE_QUEUE_REST_BLOCK_CLASS,
169
+ };
170
+ }
171
+
148
172
  /** The hand-run equivalent of the arm, for an operator-facing remedy. */
149
173
  export function manualArmCommand({ prNumber, queueRequired = false }) {
150
174
  return queueRequired
@@ -177,6 +201,37 @@ export async function rearmAutoMerge({
177
201
  });
178
202
  }
179
203
 
204
+ /**
205
+ * The merge wait's own squash-merge for a PR the CCR route would not arm,
206
+ * pinned to the head SHA it saw green (a moved head is refused), with the
207
+ * head ref reaped. Lives here because `lifecycle-lint` confines `gh pr merge`
208
+ * to this module. Never throws.
209
+ *
210
+ * @param {{ prNumber: number, headSha: string, gh?: object }} args
211
+ * @returns {Promise<{ merged: boolean, detail: string }>}
212
+ */
213
+ export async function mergeOnGreen({ prNumber, headSha, gh }) {
214
+ try {
215
+ const result = await (gh ?? defaultGh).pr.merge(String(prNumber), [
216
+ '--squash',
217
+ '--delete-branch',
218
+ '--match-head-commit',
219
+ headSha,
220
+ ]);
221
+ const merged = result?.merged !== false;
222
+ return { merged, detail: merged ? 'merged' : 'merge not performed' };
223
+ } catch (err) {
224
+ return { merged: false, detail: describeGhFailure(err) };
225
+ }
226
+ }
227
+
228
+ /** A zero-exit arm; the REST transport's CCR refusal hands the merge to the wait. */
229
+ function armedOutcome(result) {
230
+ return result.mergeOnGreen
231
+ ? { enabled: true, mergeOnGreen: true, reason: result.stderr }
232
+ : { enabled: true };
233
+ }
234
+
180
235
  /**
181
236
  * `--auto --squash --delete-branch`, falling back to a direct squash-merge
182
237
  * only when native auto-merge is unavailable.
@@ -194,7 +249,7 @@ async function armNativeAutoMerge({ exec, prNumber, armCwd }) {
194
249
  ],
195
250
  { cwd: armCwd },
196
251
  );
197
- if (result.status === 0) return { enabled: true };
252
+ if (result.status === 0) return armedOutcome(result);
198
253
  const detail = `gh-exit-${result.status}: ${(result.stderr ?? '').trim().slice(0, 200)}`;
199
254
  if (isLocalCleanupOnlyFailure(result.stderr)) {
200
255
  // The remote side stands; the land tail finishes the local ref reap.
@@ -218,6 +273,21 @@ async function armNativeAutoMerge({ exec, prNumber, armCwd }) {
218
273
  }
219
274
  }
220
275
 
276
+ /**
277
+ * A resolved `gh.pr.merge` as the runner envelope. The REST transport's CCR
278
+ * refusal resolves too, carrying `mergeOnGreen` and its detail as `stderr`.
279
+ */
280
+ function successEnvelope(result) {
281
+ if (result?.mergeOnGreen) {
282
+ return { status: 0, stdout: '', stderr: result.detail, mergeOnGreen: true };
283
+ }
284
+ return {
285
+ status: 0,
286
+ stdout: result?.stdout ?? '',
287
+ stderr: result?.stderr ?? '',
288
+ };
289
+ }
290
+
221
291
  /**
222
292
  * Adapt `gh.pr.merge` into the `{ status, stdout, stderr }` envelope,
223
293
  * mapping non-zero exits back to that envelope rather than throwing.
@@ -226,12 +296,7 @@ function makeDefaultGhAutoMergeRunner(gh) {
226
296
  return async function defaultGhAutoMergeRunner(args, _opts) {
227
297
  const [, , prIdStr, ...flags] = args;
228
298
  try {
229
- const result = await gh.pr.merge(prIdStr, flags);
230
- return {
231
- status: 0,
232
- stdout: result?.stdout ?? '',
233
- stderr: result?.stderr ?? '',
234
- };
299
+ return successEnvelope(await gh.pr.merge(prIdStr, flags));
235
300
  } catch (err) {
236
301
  // Any error with a numeric `.code`/`.status` maps to the envelope;
237
302
  // a codeless Error falls through to the caller's spawn-error reason.
@@ -392,60 +457,69 @@ async function evaluateAdvisoryGate({
392
457
  };
393
458
  }
394
459
 
460
+ /** The fields every standing arm reports. */
461
+ const ARMED = Object.freeze({ autoMergeEnabled: true, autoMergeReason: null });
462
+
463
+ /** How each kind of standing arm reports, and the outcome it returns. */
464
+ const ARMED_REPORTS = Object.freeze({
465
+ mergeOnGreen: ({ result, prNumber }) => [
466
+ `↪ The CCR auto-merge route refused PR #${prNumber} (${result.reason || 'no detail'}) — ` +
467
+ 'the merge wait squash-merges it, pinned to the head SHA, once it is CLEAN with green checks.',
468
+ {
469
+ ...ARMED,
470
+ autoMergeReason: REST_MERGE_ON_GREEN,
471
+ localCleanupDeferred: false,
472
+ },
473
+ ],
474
+ mergeQueue: ({ prNumber }) => [
475
+ `✅ Auto-merge enabled on PR #${prNumber} (merge queue — the queue rule picks the strategy).`,
476
+ { ...ARMED, localCleanupDeferred: false, mergeQueue: true },
477
+ ],
478
+ directMerged: ({ result, prNumber }) => [
479
+ `✅ Native auto-merge unavailable on PR #${prNumber} — direct squash-merge landed it` +
480
+ (result.localCleanupDeferred
481
+ ? " (gh's LOCAL branch cleanup deferred to the land tail; the merge stands)."
482
+ : '.'),
483
+ {
484
+ ...ARMED,
485
+ directMerged: true,
486
+ localCleanupDeferred: Boolean(result.localCleanupDeferred),
487
+ },
488
+ ],
489
+ localCleanupDeferred: ({ result, prNumber }) => [
490
+ `⚠️ Auto-merge armed on PR #${prNumber}, but gh's LOCAL branch cleanup failed ` +
491
+ `(${result.reason}) — deferring the local ref reap to the land tail; the merge stands.`,
492
+ { ...ARMED, localCleanupDeferred: true },
493
+ ],
494
+ plain: ({ prNumber }) => [
495
+ `✅ Auto-merge enabled on PR #${prNumber} (squash, delete-branch).`,
496
+ { ...ARMED, localCleanupDeferred: false },
497
+ ],
498
+ });
499
+
500
+ /** The first flag a standing arm carries, in precedence order. */
501
+ function armedKind(result) {
502
+ const kinds = [
503
+ 'mergeOnGreen',
504
+ 'mergeQueue',
505
+ 'directMerged',
506
+ 'localCleanupDeferred',
507
+ ];
508
+ return kinds.find((kind) => result[kind]) ?? 'plain';
509
+ }
510
+
395
511
  /**
396
512
  * Report an arm that stood, naming how it will land.
397
513
  *
398
- * @returns {{ autoMergeEnabled: true, autoMergeReason: null, localCleanupDeferred: boolean, directMerged?: boolean, mergeQueue?: boolean }}
514
+ * @returns {{ autoMergeEnabled: true, autoMergeReason: string|null, localCleanupDeferred: boolean, directMerged?: boolean, mergeQueue?: boolean }}
399
515
  */
400
516
  function reportArmed({ result, prNumber, progress }) {
401
- if (result.mergeQueue) {
402
- progress(
403
- 'PR',
404
- `✅ Auto-merge enabled on PR #${prNumber} (merge queue — the queue rule picks the strategy).`,
405
- );
406
- return {
407
- autoMergeEnabled: true,
408
- autoMergeReason: null,
409
- localCleanupDeferred: false,
410
- mergeQueue: true,
411
- };
412
- }
413
- if (result.directMerged) {
414
- progress(
415
- 'PR',
416
- `✅ Native auto-merge unavailable on PR #${prNumber} — direct squash-merge landed it` +
417
- (result.localCleanupDeferred
418
- ? " (gh's LOCAL branch cleanup deferred to the land tail; the merge stands)."
419
- : '.'),
420
- );
421
- return {
422
- autoMergeEnabled: true,
423
- autoMergeReason: null,
424
- directMerged: true,
425
- localCleanupDeferred: Boolean(result.localCleanupDeferred),
426
- };
427
- }
428
- if (result.localCleanupDeferred) {
429
- progress(
430
- 'PR',
431
- `⚠️ Auto-merge armed on PR #${prNumber}, but gh's LOCAL branch cleanup failed ` +
432
- `(${result.reason}) — deferring the local ref reap to the land tail; the merge stands.`,
433
- );
434
- return {
435
- autoMergeEnabled: true,
436
- autoMergeReason: null,
437
- localCleanupDeferred: true,
438
- };
439
- }
440
- progress(
441
- 'PR',
442
- `✅ Auto-merge enabled on PR #${prNumber} (squash, delete-branch).`,
443
- );
444
- return {
445
- autoMergeEnabled: true,
446
- autoMergeReason: null,
447
- localCleanupDeferred: false,
448
- };
517
+ const [line, outcome] = ARMED_REPORTS[armedKind(result)]({
518
+ result,
519
+ prNumber,
520
+ });
521
+ progress('PR', line);
522
+ return outcome;
449
523
  }
450
524
 
451
525
  /**
@@ -22,7 +22,8 @@
22
22
  */
23
23
 
24
24
  import { getCiDelivery } from '../../../config/ci.js';
25
- import { createGh } from '../../../gh-exec.js';
25
+ import { createGh, prTransportOf } from '../../../gh-exec.js';
26
+ import { REST_MERGE_ON_GREEN } from '../../../gh-pr-rest.js';
26
27
  import {
27
28
  confirmStoryMerged as defaultConfirmStoryMerged,
28
29
  readPrMergeState as defaultReadPrMergeState,
@@ -56,7 +57,11 @@ import {
56
57
  readRunSummary,
57
58
  resolveAdvisoryGateVerdict,
58
59
  } from '../../merge-poll.js';
59
- import { readMergeQueueState } from '../../merge-queue.js';
60
+ import {
61
+ MERGE_QUEUE_REST_BLOCK_CLASS,
62
+ MERGE_QUEUE_REST_REMEDY,
63
+ readMergeQueueState,
64
+ } from '../../merge-queue.js';
60
65
  import { readProbeRunEvidence } from '../../required-checks.js';
61
66
  import { NEXT_COMMANDS } from '../../story-deliver-terminal.js';
62
67
  import {
@@ -64,7 +69,7 @@ import {
64
69
  STATE_LABELS,
65
70
  transitionTicketState,
66
71
  } from '../../ticketing.js';
67
- import { disarmAutoMerge } from './auto-merge.js';
72
+ import { disarmAutoMerge, mergeOnGreen } from './auto-merge.js';
68
73
  import {
69
74
  maybeRearmPr,
70
75
  mergeWaitRecoverySeams,
@@ -1283,6 +1288,8 @@ async function recoverOpenPr(ctx, decision, probe) {
1283
1288
  if (advisory) {
1284
1289
  return { state: decision.state, outcome: await blockWith(ctx, advisory) };
1285
1290
  }
1291
+ const landed = await maybeMergeOnGreen(ctx, decision, probe);
1292
+ if (landed) return { state: decision.state, outcome: landed };
1286
1293
  await maybeRearmPr(ctx, probe);
1287
1294
  const updated = await maybeUpdateBehindPr({
1288
1295
  probe,
@@ -1299,6 +1306,67 @@ async function recoverOpenPr(ctx, decision, probe) {
1299
1306
  return { state, outcome: null };
1300
1307
  }
1301
1308
 
1309
+ /**
1310
+ * Close owns the merge when the CCR route would not arm it: the arm said so,
1311
+ * or (a `--wait` resume, which has no arm outcome) the PR transport is REST
1312
+ * and GitHub holds no auto-merge request. Only a PR close itself armed.
1313
+ *
1314
+ * @returns {Promise<boolean>}
1315
+ */
1316
+ async function closeOwnsMerge(ctx, probe) {
1317
+ if (ctx.closeArmed !== true) return false;
1318
+ if (ctx.autoMergeReason === REST_MERGE_ON_GREEN) return true;
1319
+ return (
1320
+ probe.autoMergeArmed !== true &&
1321
+ (await prTransportOf(ctx.waitGh)) === 'rest'
1322
+ );
1323
+ }
1324
+
1325
+ function isCleanAndGreen(probe) {
1326
+ return (
1327
+ probe?.state === 'OPEN' &&
1328
+ !probe?.mergedAt &&
1329
+ probe?.inMergeQueue !== true &&
1330
+ probe?.mergeStateStatus === 'CLEAN' &&
1331
+ probe?.checksStatus === 'success' &&
1332
+ Boolean(probe?.headSha)
1333
+ );
1334
+ }
1335
+
1336
+ /**
1337
+ * Merge-on-green: squash-merge a CLEAN, green PR pinned to the head SHA this
1338
+ * poll saw, and settle it as merged. A refused merge (the head moved, GitHub
1339
+ * still recomputing) is not a terminal; the next poll re-reads.
1340
+ *
1341
+ * @returns {Promise<object|null>} the landed outcome, or null to keep polling.
1342
+ */
1343
+ async function maybeMergeOnGreen(ctx, decision, probe) {
1344
+ if (!isCleanAndGreen(probe) || !(await closeOwnsMerge(ctx, probe))) {
1345
+ return null;
1346
+ }
1347
+ const merge = await ctx.mergeOnGreenFn({
1348
+ prNumber: ctx.prNumber,
1349
+ headSha: probe.headSha,
1350
+ gh: ctx.waitGh,
1351
+ });
1352
+ if (!merge.merged) {
1353
+ ctx.progress?.(
1354
+ 'CONFIRM',
1355
+ `⚠️ PR #${ctx.prNumber} is CLEAN and green but the merge was refused (${merge.detail}) — still waiting.`,
1356
+ );
1357
+ return null;
1358
+ }
1359
+ ctx.progress?.(
1360
+ 'CONFIRM',
1361
+ `🔀 PR #${ctx.prNumber} was CLEAN and green — squash-merged at ${probe.headSha.slice(0, 7)}.`,
1362
+ );
1363
+ return settleMerged(ctx, decision, {
1364
+ ...probe,
1365
+ state: 'MERGED',
1366
+ mergedAt: new Date(ctx.nowMsFn()).toISOString(),
1367
+ });
1368
+ }
1369
+
1302
1370
  /** The provisional verdict's own ending: budget block, `pending`, or none. */
1303
1371
  async function settleVerdict(ctx, decision, probe) {
1304
1372
  if (decision.verdict === 'budget-exhausted') {
@@ -1379,15 +1447,27 @@ function blockNeverArmed({
1379
1447
  progress,
1380
1448
  classifyMergeBlockFn,
1381
1449
  emitMergeUnlandedFn,
1382
- ...(autoMergeReason === 'advisory-gate-red'
1383
- ? {
1384
- blockClassOverride: advisoryGate?.blockClass ?? 'advisory-gate-red',
1385
- reasonOverride: advisoryGate?.reason,
1386
- }
1387
- : {}),
1450
+ ...neverArmedOverride(autoMergeReason, advisoryGate),
1388
1451
  });
1389
1452
  }
1390
1453
 
1454
+ /** An arm refusal that names its own class rather than a generic `arm-failure`. */
1455
+ function neverArmedOverride(autoMergeReason, advisoryGate) {
1456
+ if (autoMergeReason === 'advisory-gate-red') {
1457
+ return {
1458
+ blockClassOverride: advisoryGate?.blockClass ?? 'advisory-gate-red',
1459
+ reasonOverride: advisoryGate?.reason,
1460
+ };
1461
+ }
1462
+ if (autoMergeReason === MERGE_QUEUE_REST_BLOCK_CLASS) {
1463
+ return {
1464
+ blockClassOverride: MERGE_QUEUE_REST_BLOCK_CLASS,
1465
+ reasonOverride: MERGE_QUEUE_REST_REMEDY,
1466
+ };
1467
+ }
1468
+ return {};
1469
+ }
1470
+
1391
1471
  /**
1392
1472
  * Poll an armed Story PR to merge confirmation, a resumable `pending`
1393
1473
  * expiry, or a classified `agent::blocked` terminal.
@@ -1417,6 +1497,7 @@ function blockNeverArmed({
1417
1497
  * @param {Function} [args.runPostLandTailFn]
1418
1498
  * @param {Function} [args.disarmAutoMergeFn]
1419
1499
  * @param {Function} [args.recordRequiredRedFn] The shared first-red handling (disarm + CI digest).
1500
+ * @param {Function} [args.mergeOnGreenFn] The merge-on-green squash-merge (`auto-merge.js#mergeOnGreen`).
1420
1501
  * @param {object} [args.recoverySeams] DIRTY-sync / re-arm seams (`mergeWaitRecoverySeams`).
1421
1502
  * @param {(ms: number) => Promise<void>} [args.sleepFn]
1422
1503
  * @param {() => number} [args.nowMsFn]
@@ -1436,6 +1517,7 @@ export async function runConfirmMergePhase({
1436
1517
  runPostLandTailFn = defaultRunPostLandTail,
1437
1518
  disarmAutoMergeFn = disarmAutoMerge,
1438
1519
  recordRequiredRedFn = defaultRecordRequiredRed,
1520
+ mergeOnGreenFn = mergeOnGreen,
1439
1521
  sleepFn = defaultSleep,
1440
1522
  nowMsFn = Date.now,
1441
1523
  ghTimeoutMs = MERGE_WAIT_GH_TIMEOUT_MS,
@@ -1483,6 +1565,7 @@ export async function runConfirmMergePhase({
1483
1565
  runPostLandTailFn,
1484
1566
  disarmAutoMergeFn,
1485
1567
  recordRequiredRedFn,
1568
+ mergeOnGreenFn,
1486
1569
  nowMsFn,
1487
1570
  ghTimeoutMs,
1488
1571
  waitGh: args.injectedGh ?? defaultGh,