mandrel 2.118.0 → 2.120.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 (44) hide show
  1. package/.agents/docs/agentrc-reference.json +2 -1
  2. package/.agents/docs/configuration.md +31 -8
  3. package/.agents/schemas/agentrc.schema.json +27 -4
  4. package/.agents/schemas/lifecycle/merge.unlanded.schema.json +2 -1
  5. package/.agents/schemas/story-deliver-terminal.schema.json +16 -1
  6. package/.agents/scripts/lib/baselines/crap-preview-coverage.js +17 -0
  7. package/.agents/scripts/lib/baselines/crap-preview-scan.js +11 -6
  8. package/.agents/scripts/lib/baselines/preview-gates.js +2 -0
  9. package/.agents/scripts/lib/baselines/refresh-service.js +21 -6
  10. package/.agents/scripts/lib/close-validation/base-sync-revalidation.js +152 -0
  11. package/.agents/scripts/lib/close-validation/ci-deferral.js +23 -5
  12. package/.agents/scripts/lib/close-validation/gates.js +8 -2
  13. package/.agents/scripts/lib/close-validation/runner.js +8 -10
  14. package/.agents/scripts/lib/config/gates/coverage.schema.js +1 -1
  15. package/.agents/scripts/lib/config-settings-schema-delivery.js +22 -2
  16. package/.agents/scripts/lib/config-settings-schema.js +1 -1
  17. package/.agents/scripts/lib/coverage-deferral.js +17 -0
  18. package/.agents/scripts/lib/generated/agentrc-validator.js +2 -2
  19. package/.agents/scripts/lib/observability/handoff-telemetry.js +1 -0
  20. package/.agents/scripts/lib/observability/story-outcome.js +5 -4
  21. package/.agents/scripts/lib/orchestrate/inventory.js +15 -0
  22. package/.agents/scripts/lib/orchestration/handoff-changed-tests.js +67 -0
  23. package/.agents/scripts/lib/orchestration/handoff-rescore.js +95 -25
  24. package/.agents/scripts/lib/orchestration/handoff-suite-of-record.js +25 -10
  25. package/.agents/scripts/lib/orchestration/merge-block-class.js +13 -1
  26. package/.agents/scripts/lib/orchestration/merge-poll.js +9 -0
  27. package/.agents/scripts/lib/orchestration/merge-queue.js +169 -21
  28. package/.agents/scripts/lib/orchestration/single-story-close/phases/auto-merge.js +2 -25
  29. package/.agents/scripts/lib/orchestration/single-story-close/phases/base-sync.js +8 -1
  30. package/.agents/scripts/lib/orchestration/single-story-close/phases/close-validation.js +26 -7
  31. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +181 -26
  32. package/.agents/scripts/lib/orchestration/single-story-close/phases/finish.js +3 -2
  33. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +9 -3
  34. package/.agents/scripts/lib/orchestration/single-story-close/result.js +9 -6
  35. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +1 -0
  36. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +158 -71
  37. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +4 -0
  38. package/.agents/scripts/lib/orchestration/story-handoff.js +124 -26
  39. package/.agents/scripts/quality-preview.js +57 -8
  40. package/.agents/workflows/helpers/deliver-reference.md +27 -1
  41. package/docs/CHANGELOG.md +18 -0
  42. package/lib/cli/doctor-checks/suite-ownership.js +42 -0
  43. package/lib/cli/registry.js +6 -10
  44. package/package.json +1 -1
@@ -30,6 +30,7 @@ const HANDOFF_CAUSES = Object.freeze(
30
30
  'host-admission',
31
31
  'suite-timeout',
32
32
  'red-suite',
33
+ 'changed-tests',
33
34
  'capture-over-budget',
34
35
  'no-credit-signal',
35
36
  'seat-refused',
@@ -70,10 +70,10 @@ function resolveMandrelVersion(root = PROJECT_ROOT) {
70
70
  return typeof pkg?.version === 'string' ? pkg.version : null;
71
71
  }
72
72
 
73
- /** @param {Record<string, string>|null|undefined} gates */
74
- function failedGateNames(gates) {
73
+ /** @param {Record<string, string>|null|undefined} gates @param {string} wanted */
74
+ function gateNamesWith(gates, wanted) {
75
75
  return Object.entries(gates ?? {})
76
- .filter(([, outcome]) => outcome === 'failed')
76
+ .filter(([, outcome]) => outcome === wanted)
77
77
  .map(([name]) => name)
78
78
  .sort();
79
79
  }
@@ -130,7 +130,8 @@ function buildAttempt({
130
130
  phase: envelope.phase ?? null,
131
131
  cause: retryCauseForTerminal(envelope),
132
132
  blockClass: envelope.blocked?.blockClass ?? null,
133
- failedGates: failedGateNames(envelope.gates),
133
+ failedGates: gateNamesWith(envelope.gates, 'failed'),
134
+ deferredGates: gateNamesWith(envelope.gates, 'deferred'),
134
135
  prNumber: intOrNull(envelope.pr?.number),
135
136
  mandrelVersion,
136
137
  workerModel: clip(worker.workerModel),
@@ -310,6 +310,21 @@ function orchestrateConfig(config) {
310
310
  const runVetoCommand = ({ cmd, args }, cwd) =>
311
311
  spawnCapture(cmd, args, { cwd }).status !== 0;
312
312
 
313
+ /** Whether `delivery.orchestrate.releaseVeto` holds a PR carrying `labels`. */
314
+ export function releaseVetoHolds({
315
+ config,
316
+ labels,
317
+ cwd,
318
+ runVeto = runVetoCommand,
319
+ }) {
320
+ const { releaseVeto } = orchestrateConfig(config);
321
+ return Boolean(
322
+ releaseVeto &&
323
+ labels.includes(releaseVeto.prLabel) &&
324
+ runVeto(releaseVeto, cwd),
325
+ );
326
+ }
327
+
313
328
  /**
314
329
  * One sweep: read, resolve conflicts and the veto, classify, and with a
315
330
  * run id append the sweep and fill `changes[]`.
@@ -0,0 +1,67 @@
1
+ /**
2
+ * handoff-changed-tests.js — the `ci` posture's changed-tests guard:
3
+ * `project.commands.testChanged` run before the deferral settles, with no
4
+ * lock and no credit.
5
+ */
6
+
7
+ import { resolveTestChangedCommand } from '../close-validation/test-delta.js';
8
+ import { TIMEOUT_EXIT_CODE } from '../process-group.js';
9
+ import { isOverBudgetExit } from './handoff-gates.js';
10
+
11
+ /** Why a guard exit other than 0 or 76 stops the handoff. */
12
+ function guardFailure(raw, status) {
13
+ return status === TIMEOUT_EXIT_CODE
14
+ ? `changed-tests guard timed out (exit ${status}) — usually host contention; re-run the handoff`
15
+ : `changed-tests guard \`${raw}\` failed (exit ${status}) — fix the failing tests, commit, re-run`;
16
+ }
17
+
18
+ /** A guard exit as `{ stop }`, else the `note` the deferral detail carries. */
19
+ function settleGuard(ctx, name, { status, raw, extra }) {
20
+ if (status === 0) {
21
+ ctx.state.changedTestsHead = ctx.head;
22
+ return { note: '; changed-tests guard passed', extra };
23
+ }
24
+ if (isOverBudgetExit(status)) {
25
+ return {
26
+ note: `; changed-tests guard skipped (over budget, exit ${status})`,
27
+ extra,
28
+ };
29
+ }
30
+ const detail = guardFailure(raw, status);
31
+ return {
32
+ stop: {
33
+ name,
34
+ outcome: 'failed',
35
+ detail,
36
+ stop: 'fix-required',
37
+ cause: 'changed-tests',
38
+ ...extra,
39
+ },
40
+ };
41
+ }
42
+
43
+ /**
44
+ * Run `testChanged` unless unset or already passed at HEAD.
45
+ *
46
+ * @param {{ config: object, head: string, state: object, depositor: string }} ctx
47
+ * @param {string} name
48
+ * @param {{ run: (cmd: object) => Promise<{ status: number, evidencePath: string }>, signal: AbortSignal }} guard
49
+ * @returns {Promise<{ stop?: object, note?: string, extra?: object }>}
50
+ */
51
+ export async function changedTestsGuard(ctx, name, guard) {
52
+ const testChanged = resolveTestChangedCommand(ctx.config);
53
+ if (testChanged.disabled) return { note: '' };
54
+ if (ctx.state.changedTestsHead === ctx.head) {
55
+ return {
56
+ note: `; changed-tests guard already passed at ${ctx.head.slice(0, 12)}`,
57
+ };
58
+ }
59
+ const { status, evidencePath } = await guard.run(testChanged);
60
+ const extra = { evidencePath, depositor: ctx.depositor };
61
+ if (!guard.signal.aborted) {
62
+ return settleGuard(ctx, name, { status, raw: testChanged.raw, extra });
63
+ }
64
+ const detail =
65
+ 'aborted: the held review found a CRITICAL mid-guard; no deferral';
66
+ return { stop: { name, outcome: 'aborted', detail, ...extra } };
67
+ }
@@ -1,7 +1,9 @@
1
1
  /**
2
2
  * handoff-rescore.js — the handoff runs close's own duplication re-score
3
3
  * before any credit, so close's later re-score over the same tree no-ops;
4
- * and names the duplication rows a branch raised in a post-capture finding.
4
+ * under admitted preflight lanes it scans beside preflight and commits at a
5
+ * join instead. Also names the duplication rows a branch raised in a
6
+ * post-capture finding.
5
7
  */
6
8
 
7
9
  import fs from 'node:fs';
@@ -43,6 +45,42 @@ function settle(ctx, result, readHead) {
43
45
  return { outcome: 'error', detail: result?.reason ?? 'no result' };
44
46
  }
45
47
 
48
+ /** Close's re-score inputs for this handoff. */
49
+ function rescoreInput(ctx) {
50
+ const log = (m) => ctx.progress('duplication-rescore', m);
51
+ return {
52
+ cwd: ctx.cwd,
53
+ worktreePath: ctx.cwd,
54
+ storyId: ctx.storyId,
55
+ baseBranch: ctx.baseBranch,
56
+ storyBranch: ctx.branch,
57
+ baselineRef: ctx.baselineRef,
58
+ config: ctx.config,
59
+ logger: { info: log, warn: log },
60
+ };
61
+ }
62
+
63
+ /** Settle `result`; anything but an `error` records the re-score at HEAD. */
64
+ function record(ctx, result, readHead) {
65
+ const settled = settle(ctx, result, readHead);
66
+ if (settled.outcome !== 'error') {
67
+ ctx.state.duplicationRescore = {
68
+ head: ctx.head,
69
+ partners: result?.partners ?? {},
70
+ };
71
+ }
72
+ return settled;
73
+ }
74
+
75
+ /** The skip a HEAD already re-scored settles; `null` when it was not. */
76
+ function alreadyRescored(ctx) {
77
+ if (ctx.state.duplicationRescore?.head !== ctx.head) return null;
78
+ return {
79
+ outcome: 'skipped',
80
+ detail: `already re-scored at ${ctx.head.slice(0, 12)}`,
81
+ };
82
+ }
83
+
46
84
  /**
47
85
  * Run the re-score once per HEAD; best-effort, it never stops the run. An
48
86
  * `error` records nothing, so a re-run retries.
@@ -53,37 +91,69 @@ function settle(ctx, result, readHead) {
53
91
  * @returns {Promise<{ outcome: string, detail: string }>}
54
92
  */
55
93
  export async function rescoreDuplication(ctx, readHead) {
56
- const prior = ctx.state.duplicationRescore;
57
- if (prior?.head === ctx.head) {
58
- return {
59
- outcome: 'skipped',
60
- detail: `already re-scored at ${ctx.head.slice(0, 12)}`,
61
- };
62
- }
63
- const log = (m) => ctx.progress('duplication-rescore', m);
94
+ const already = alreadyRescored(ctx);
95
+ if (already) return already;
64
96
  let result;
65
97
  try {
66
- result = await ctx.runDuplicationRescore({
67
- cwd: ctx.cwd,
68
- worktreePath: ctx.cwd,
69
- storyId: ctx.storyId,
70
- baseBranch: ctx.baseBranch,
71
- storyBranch: ctx.branch,
72
- baselineRef: ctx.baselineRef,
73
- config: ctx.config,
74
- logger: { info: log, warn: log },
75
- });
98
+ result = await ctx.runDuplicationRescore(rescoreInput(ctx));
76
99
  } catch (err) {
77
100
  return { outcome: 'error', detail: `threw: ${err?.message ?? err}` };
78
101
  }
79
- const settled = settle(ctx, result, readHead);
80
- if (settled.outcome !== 'error') {
81
- ctx.state.duplicationRescore = {
82
- head: ctx.head,
83
- partners: result?.partners ?? {},
102
+ return record(ctx, result, readHead);
103
+ }
104
+
105
+ /**
106
+ * Start close's scan beside preflight at `ctx.head`; it writes nothing.
107
+ *
108
+ * @param {object} ctx `ctx.scanDuplicationRescore` is close's scan.
109
+ * @returns {{ already?: object, input?: object, done?: Promise<{ scan?: object, error?: string, durationMs: number }> }}
110
+ */
111
+ export function startDuplicationScan(ctx) {
112
+ const already = alreadyRescored(ctx);
113
+ if (already) return { already };
114
+ const input = rescoreInput(ctx);
115
+ const startedAt = ctx.now();
116
+ const done = Promise.resolve()
117
+ .then(() => ctx.scanDuplicationRescore(input))
118
+ .then(
119
+ (scan) => ({ scan }),
120
+ (err) => ({ error: `threw: ${err?.message ?? err}` }),
121
+ )
122
+ .then((out) => ({ ...out, durationMs: ctx.now() - startedAt }));
123
+ return { input, done };
124
+ }
125
+
126
+ /**
127
+ * Await the scan and, when rows moved, apply them through close's commit.
128
+ * The result carries the scan's own wall time and its concurrency marker.
129
+ *
130
+ * @param {object} ctx `ctx.applyDuplicationRescore` is close's apply.
131
+ * @param {ReturnType<typeof startDuplicationScan>} started
132
+ * @param {() => string|null} readHead
133
+ * @returns {Promise<{ name: string, outcome: string, detail: string, concurrentWith: string, durationMs: number }>}
134
+ */
135
+ export async function joinDuplicationScan(ctx, started, readHead) {
136
+ const step = { name: 'duplication-rescore', concurrentWith: 'preflight' };
137
+ if (started.already) return { ...step, ...started.already, durationMs: 0 };
138
+ const { scan, error, durationMs } = await started.done;
139
+ const base = { ...step, durationMs };
140
+ if (error) return { ...base, outcome: 'error', detail: error };
141
+ if (!scan?.changed) {
142
+ const result = scan?.reason
143
+ ? scan
144
+ : { reason: 'unchanged', partners: scan?.partners };
145
+ return { ...base, ...record(ctx, result, readHead) };
146
+ }
147
+ try {
148
+ const result = await ctx.applyDuplicationRescore(scan, started.input);
149
+ return { ...base, ...record(ctx, result, readHead) };
150
+ } catch (err) {
151
+ return {
152
+ ...base,
153
+ outcome: 'error',
154
+ detail: `threw: ${err?.message ?? err}`,
84
155
  };
85
156
  }
86
- return settled;
87
157
  }
88
158
 
89
159
  /** @returns {string} the configured duplication baseline path. */
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * handoff-suite-of-record.js — the credited-run step under
3
- * `coverage.suiteOfRecord: "ci"`, decided from config before any lock or spawn.
3
+ * `coverage.suiteOfRecord: "ci"`, decided from config before any lock or spawn
4
+ * but the changed-tests guard.
4
5
  */
5
6
 
6
7
  import { suiteOfRecord } from '../close-validation/gates.js';
@@ -8,10 +9,28 @@ import {
8
9
  COVERAGE_DEFERRED_REASONS,
9
10
  deferCoverage,
10
11
  } from '../coverage-deferral.js';
12
+ import { changedTestsGuard } from './handoff-changed-tests.js';
11
13
 
12
14
  const UNDECLARED_DETAIL =
13
15
  'delivery.quality.gates.coverage.suiteOfRecord is "ci" but delivery.quality.gates.coverage.ciRatchetCheck is unset — name the CI check that runs coverage-ratchet.js, or set suiteOfRecord to "local"';
14
16
 
17
+ /**
18
+ * The deferred step, once the changed-tests guard did not stop the run.
19
+ *
20
+ * @param {object} ctx @param {string} name @param {string} ciRatchetCheck
21
+ * @param {{ note: string, extra?: object }} checked
22
+ */
23
+ function deferred(ctx, name, ciRatchetCheck, checked) {
24
+ deferCoverage(ctx.state, ctx.head, COVERAGE_DEFERRED_REASONS.suiteOfRecordCi);
25
+ return {
26
+ name,
27
+ outcome: 'deferred',
28
+ detail: `coverage deferred to CI (suiteOfRecord: ci, ratchet check "${ciRatchetCheck}") — no capture spawned and no credit was deposited${checked.note}`,
29
+ depositor: ctx.depositor,
30
+ ...checked.extra,
31
+ };
32
+ }
33
+
15
34
  /**
16
35
  * The capture depositor's step under the `ci` posture: deferred to CI, or
17
36
  * `blocked` when no `ciRatchetCheck` would take the ratchet. `null` when the
@@ -19,9 +38,10 @@ const UNDECLARED_DETAIL =
19
38
  *
20
39
  * @param {{ config: object, depositor: string, head: string, state: object }} ctx
21
40
  * @param {string} name
22
- * @returns {object|null}
41
+ * @param {{ run: Function, signal: AbortSignal }} guard runs `testChanged`.
42
+ * @returns {Promise<object|null>}
23
43
  */
24
- export function settleSuiteOfRecord(ctx, name) {
44
+ export async function settleSuiteOfRecord(ctx, name, guard) {
25
45
  const { ci, ciRatchetCheck } = suiteOfRecord(ctx.config);
26
46
  if (!ci || ctx.depositor !== 'coverage-capture') return null;
27
47
  const extra = { depositor: ctx.depositor };
@@ -35,11 +55,6 @@ export function settleSuiteOfRecord(ctx, name) {
35
55
  ...extra,
36
56
  };
37
57
  }
38
- deferCoverage(ctx.state, ctx.head, COVERAGE_DEFERRED_REASONS.suiteOfRecordCi);
39
- return {
40
- name,
41
- outcome: 'deferred',
42
- detail: `coverage deferred to CI (suiteOfRecord: ci, ratchet check "${ciRatchetCheck}") — nothing spawned and no credit was deposited`,
43
- ...extra,
44
- };
58
+ const checked = await changedTestsGuard(ctx, name, guard);
59
+ return checked.stop ?? deferred(ctx, name, ciRatchetCheck, checked);
45
60
  }
@@ -29,6 +29,7 @@ export const MERGE_UNLANDED_BLOCK_CLASSES = Object.freeze([
29
29
  ADVISORY_GATE_RED_CLASS,
30
30
  ADVISORY_GATE_INCONCLUSIVE_CLASS,
31
31
  'merge-queue-rest-unsupported',
32
+ 'queue-ejected',
32
33
  ]);
33
34
 
34
35
  const BLOCK_CLASS_SET = new Set(MERGE_UNLANDED_BLOCK_CLASSES);
@@ -56,6 +57,17 @@ function textIncludesAny(text, markers) {
56
57
  return markers.some((marker) => lower.includes(marker));
57
58
  }
58
59
 
60
+ function describeExhaustion(prProbe) {
61
+ const mergeState = `mergeStateStatus=${prProbe?.mergeStateStatus ?? 'n/a'}`;
62
+ if (prProbe?.checksStatus === 'success') {
63
+ return `watch budget exhausted with every check green but the PR did not land (${mergeState}, autoMergeArmed=${prProbe?.autoMergeArmed ?? 'unknown'}, inMergeQueue=${prProbe?.inMergeQueue ?? 'unknown'})`;
64
+ }
65
+ if (prProbe?.checksStatus === 'unknown') {
66
+ return `watch budget exhausted with no checks reported (${mergeState})`;
67
+ }
68
+ return `watch budget exhausted with an unrecognised checks status (${prProbe?.checksStatus ?? 'unknown'})`;
69
+ }
70
+
59
71
  /** The most specific `api-race-other` reason the signals allow. */
60
72
  function describeApiRaceFallback(prProbe, budget) {
61
73
  if (prProbe?.error) {
@@ -67,7 +79,7 @@ function describeApiRaceFallback(prProbe, budget) {
67
79
  return `PR did not land although its failing checks are not required (mergeStateStatus=${prProbe?.mergeStateStatus ?? 'n/a'}); the red checks are not the block — check that auto-merge is still armed`;
68
80
  }
69
81
  if (budget && budget.exhausted === true) {
70
- return `watch budget exhausted with an unrecognised checks status (${prProbe?.checksStatus ?? 'unknown'})`;
82
+ return describeExhaustion(prProbe);
71
83
  }
72
84
  return 'no definitive block signal observed; classified as a transient API race or other condition';
73
85
  }
@@ -31,6 +31,15 @@ export function probeSettlesAsyncWait(checksStatus) {
31
31
  return checksStatus !== 'success' && checksStatus !== 'failure';
32
32
  }
33
33
 
34
+ /** Every `checksStatus` a merge-wait probe carries: the rollup's four, plus `pending` on a probe error. */
35
+ export const CHECKS_STATUSES = Object.freeze([
36
+ 'success',
37
+ 'failure',
38
+ 'still-running',
39
+ 'pending',
40
+ 'unknown',
41
+ ]);
42
+
34
43
  /** Bounds every `gh` spawn so a hang degrades to the probe-error path. */
35
44
  export const MERGE_WAIT_GH_TIMEOUT_MS = 60_000;
36
45
 
@@ -10,7 +10,7 @@ import {
10
10
  describeGhFailure,
11
11
  prTransportOf,
12
12
  } from '../gh-exec.js';
13
- import { readBranchRules } from '../gh-pr-rest.js';
13
+ import { parseApiJson, readBranchRules } from '../gh-pr-rest.js';
14
14
 
15
15
  /** Bound on each merge-queue GraphQL call, so a wedged `gh` cannot stall close. */
16
16
  const MERGE_QUEUE_GH_TIMEOUT_MS = 30_000;
@@ -21,19 +21,33 @@ const MERGE_QUEUE_STATE_QUERY =
21
21
  const DEQUEUE_MUTATION =
22
22
  'mutation($id: ID!) { dequeuePullRequest(input: { id: $id }) { mergeQueueEntry { id } } }';
23
23
 
24
+ const EJECTION_QUERY =
25
+ 'query($id: ID!) { node(id: $id) { ... on PullRequest { baseRefName labels(first: 20) { nodes { name } } ' +
26
+ 'timelineItems(last: 1, itemTypes: [ADDED_TO_MERGE_QUEUE_EVENT, REMOVED_FROM_MERGE_QUEUE_EVENT]) { nodes { __typename ' +
27
+ '... on RemovedFromMergeQueueEvent { createdAt reason beforeCommit { oid } } } } ' +
28
+ 'commits(last: 1) { nodes { commit { committedDate } } } } } }';
29
+
30
+ const QUEUE_RUNS = 'repos/{owner}/{repo}/actions/runs?event=merge_group';
31
+
32
+ /** Inherited ejections re-armed per head; the next one counts as own. */
33
+ const MAX_INHERITED_REARMS = 3;
34
+
35
+ /** Block class: the merge queue ejected the PR on its own failure. */
36
+ export const QUEUE_EJECTED_BLOCK_CLASS = 'queue-ejected';
37
+
24
38
  /** `gh` stderr when the base requires a merge queue and the arm spelling is wrong. */
25
39
  export const MERGE_QUEUE_REFUSAL = /when merge queue enabled/i;
26
40
 
27
41
  /** Block class: a merge-queue base reached over the REST transport. */
28
42
  export const MERGE_QUEUE_REST_BLOCK_CLASS = 'merge-queue-rest-unsupported';
29
43
 
30
- /** The remedy that block carries: enqueueing is GraphQL-only. */
44
+ /** The remedy that block carries: the CCR route refused to arm the queue base. */
31
45
  export const MERGE_QUEUE_REST_REMEDY =
32
46
  "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>`.';
47
+ 'repo-scoped REST only (GraphQL answers 403). The CCR auto-merge route refused this PR, ' +
48
+ 'and a direct merge would bypass the queue, so close did not merge. Enqueue the PR from a ' +
49
+ 'session that can reach GraphQL (arm auto-merge there) or from the GitHub UI, then confirm ' +
50
+ 'with `node .agents/scripts/single-story-confirm-merge.js --story <id>`.';
37
51
 
38
52
  /**
39
53
  * REST reading: the base's active rulesets name a `merge_queue` rule.
@@ -70,6 +84,25 @@ export function parseGraphqlData(result) {
70
84
  return parsed?.data ?? null;
71
85
  }
72
86
 
87
+ async function resolvePrNodeId(facade, prNodeId, prRef) {
88
+ if (prNodeId) return prNodeId;
89
+ const view = await facade.pr.view(String(prRef), ['id']);
90
+ if (typeof view?.id === 'string' && view.id) return view.id;
91
+ throw new Error('PR node id unavailable');
92
+ }
93
+
94
+ async function queryPrNode(facade, query, id, timeoutMs) {
95
+ const data = parseGraphqlData(
96
+ await facade.api({
97
+ method: 'POST',
98
+ endpoint: 'graphql',
99
+ body: { query, variables: { id } },
100
+ execOpts: { timeoutMs },
101
+ }),
102
+ );
103
+ return data?.node;
104
+ }
105
+
73
106
  /**
74
107
  * Whether the PR's base requires a merge queue, and whether the PR sits in
75
108
  * it now. Keyed on the PR node, so it needs no owner/repo. Never throws: any
@@ -99,20 +132,13 @@ export async function readMergeQueueState({
99
132
  timeoutMs,
100
133
  });
101
134
  }
102
- if (!id) {
103
- const view = await facade.pr.view(String(prRef ?? prNumber), ['id']);
104
- id = typeof view?.id === 'string' && view.id ? view.id : null;
105
- }
106
- if (!id) throw new Error('PR node id unavailable');
107
- const data = parseGraphqlData(
108
- await facade.api({
109
- method: 'POST',
110
- endpoint: 'graphql',
111
- body: { query: MERGE_QUEUE_STATE_QUERY, variables: { id } },
112
- execOpts: { timeoutMs },
113
- }),
135
+ id = await resolvePrNodeId(facade, id, prRef ?? prNumber);
136
+ const node = await queryPrNode(
137
+ facade,
138
+ MERGE_QUEUE_STATE_QUERY,
139
+ id,
140
+ timeoutMs,
114
141
  );
115
- const node = data?.node;
116
142
  if (typeof node?.isMergeQueueEnabled !== 'boolean') {
117
143
  throw new Error('merge-queue fields absent from the GraphQL response');
118
144
  }
@@ -131,6 +157,121 @@ export async function readMergeQueueState({
131
157
  }
132
158
  }
133
159
 
160
+ const RED_RUN = new Set(['failure', 'cancelled']);
161
+ const byNewest = (a, b) =>
162
+ String(b.created_at ?? '').localeCompare(String(a.created_at ?? ''));
163
+
164
+ /** The last queue event removed this head without merging it. */
165
+ function ejectedHead(pr, headSha) {
166
+ const event = pr?.timelineItems?.nodes?.at(-1);
167
+ if (event?.__typename !== 'RemovedFromMergeQueueEvent') return false;
168
+ if (/merged/i.test(event.reason ?? '')) return false;
169
+ const removed = event.beforeCommit?.oid;
170
+ if (removed) return removed === headSha;
171
+ const pushedAt = pr.commits?.nodes?.[0]?.commit?.committedDate;
172
+ return !(Date.parse(event.createdAt) < Date.parse(pushedAt));
173
+ }
174
+
175
+ /** The newest entry's completed run, a red one first. */
176
+ function ejectingRunOf(runs) {
177
+ const latest = runs[0]?.head_sha;
178
+ const done = runs.filter(
179
+ (r) => r.head_sha === latest && r.status === 'completed',
180
+ );
181
+ return (
182
+ done.find((r) => r.conclusion === 'failure') ??
183
+ done.find((r) => r.conclusion === 'cancelled') ??
184
+ done[0] ??
185
+ null
186
+ );
187
+ }
188
+
189
+ /** First rule wins: inherited (capped), own, unknown. */
190
+ function classifyEjection({ ejecting, parentRuns, entries }) {
191
+ const inherited =
192
+ ejecting.conclusion === 'cancelled' ||
193
+ parentRuns.some((r) => RED_RUN.has(r.conclusion));
194
+ if (inherited) return entries > MAX_INHERITED_REARMS ? 'own' : 'inherited';
195
+ return ejecting.conclusion === 'failure' ? 'own' : 'unknown';
196
+ }
197
+
198
+ /**
199
+ * Why the merge queue ejected `headSha`, read from the `merge_group` run on
200
+ * its `gh-readonly-queue/<base>/pr-<n>-<parentSha>` ref and the run of the
201
+ * entry it was built on. GraphQL only; never throws (a failed read is
202
+ * `unknown`). `verdict: null` means the last queue event is no ejection.
203
+ *
204
+ * @returns {Promise<{ verdict: 'inherited'|'own'|'unknown'|null,
205
+ * labels: string[], run?: object, failedJobs?: string[], detail?: string }>}
206
+ */
207
+ export async function readQueueEjection({
208
+ prNodeId,
209
+ prNumber,
210
+ headSha,
211
+ gh,
212
+ timeoutMs = MERGE_QUEUE_GH_TIMEOUT_MS,
213
+ }) {
214
+ const facade = gh ?? defaultGh;
215
+ const get = async (endpoint) =>
216
+ parseApiJson(
217
+ await facade.api({ method: 'GET', endpoint, execOpts: { timeoutMs } }),
218
+ );
219
+ let labels = [];
220
+ try {
221
+ const id = await resolvePrNodeId(facade, prNodeId, prNumber);
222
+ const pr = await queryPrNode(facade, EJECTION_QUERY, id, timeoutMs);
223
+ labels = (pr?.labels?.nodes ?? []).map((l) => l.name);
224
+ if (!ejectedHead(pr, headSha)) return { verdict: null, labels };
225
+ const prefix = `gh-readonly-queue/${pr.baseRefName}/pr-${prNumber}-`;
226
+ const pushedAt = Date.parse(pr.commits?.nodes?.[0]?.commit?.committedDate);
227
+ // shortcut: the newest 100 queue runs; page further if a queue outgrows it.
228
+ const runs = (
229
+ (await get(`${QUEUE_RUNS}&per_page=100`))?.workflow_runs ?? []
230
+ )
231
+ .filter((r) => String(r.head_branch ?? '').startsWith(prefix))
232
+ .filter((r) => !(Date.parse(r.created_at) < pushedAt))
233
+ .sort(byNewest);
234
+ const ejecting = ejectingRunOf(runs);
235
+ if (!ejecting) {
236
+ return { verdict: 'unknown', labels, detail: 'no completed queue run' };
237
+ }
238
+ const parentSha = ejecting.head_branch.slice(prefix.length);
239
+ const parentRuns = (
240
+ (await get(`${QUEUE_RUNS}&head_sha=${parentSha}`))?.workflow_runs ?? []
241
+ ).filter((r) => r.head_sha === parentSha);
242
+ const verdict = classifyEjection({
243
+ ejecting,
244
+ parentRuns,
245
+ entries: new Set(runs.map((r) => r.head_sha)).size,
246
+ });
247
+ const run = {
248
+ id: ejecting.id,
249
+ name: ejecting.name ?? null,
250
+ url: ejecting.html_url ?? null,
251
+ conclusion: ejecting.conclusion,
252
+ };
253
+ const failedJobs =
254
+ verdict === 'own' ? await readFailedJobs(get, ejecting.id) : [];
255
+ return { verdict, labels, run, failedJobs };
256
+ } catch (err) {
257
+ return { verdict: 'unknown', labels, detail: describeGhFailure(err) };
258
+ }
259
+ }
260
+
261
+ /** Failed job names of a run; `[]` when unreadable. */
262
+ async function readFailedJobs(get, runId) {
263
+ try {
264
+ const body = await get(
265
+ `repos/{owner}/{repo}/actions/runs/${runId}/jobs?filter=latest&per_page=100`,
266
+ );
267
+ return (body?.jobs ?? [])
268
+ .filter((j) => j.conclusion === 'failure')
269
+ .map((j) => j.name);
270
+ } catch {
271
+ return [];
272
+ }
273
+ }
274
+
134
275
  /**
135
276
  * Take an enqueued PR out of the merge queue. `--disable-auto` cannot: GitHub
136
277
  * clears the auto-merge request on enqueue, so it reads as never armed.
@@ -153,10 +294,17 @@ async function dequeuePullRequest({ prNodeId, gh }) {
153
294
  }
154
295
  }
155
296
 
297
+ function queueArmOutcome(result) {
298
+ return result.mergeOnGreen
299
+ ? { enabled: false, mergeQueue: true, reason: MERGE_QUEUE_REST_BLOCK_CLASS }
300
+ : { enabled: true, mergeQueue: true };
301
+ }
302
+
156
303
  /**
157
304
  * Arm on a merge-queue base: a bare `--auto`, and never the direct-merge
158
305
  * fallback — a merge that bypassed the queue would defeat the protection it
159
- * exists for.
306
+ * exists for. Over REST a CCR refusal resolves with `mergeOnGreen`, which on
307
+ * a queue base is the REST block, never an arm.
160
308
  *
161
309
  * @returns {Promise<{ enabled: boolean, mergeQueue: true, reason?: string }>}
162
310
  */
@@ -165,7 +313,7 @@ export async function armForMergeQueue({ exec, prNumber, armCwd }) {
165
313
  const result = await exec(['pr', 'merge', String(prNumber), '--auto'], {
166
314
  cwd: armCwd,
167
315
  });
168
- if (result.status === 0) return { enabled: true, mergeQueue: true };
316
+ if (result.status === 0) return queueArmOutcome(result);
169
317
  return {
170
318
  enabled: false,
171
319
  mergeQueue: true,