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
@@ -9,11 +9,7 @@
9
9
  * repo's `delete_branch_on_merge` owns the remote branch reap.
10
10
  */
11
11
 
12
- import {
13
- gh as defaultGh,
14
- describeGhFailure,
15
- prTransportOf,
16
- } from '../../../gh-exec.js';
12
+ import { gh as defaultGh, describeGhFailure } from '../../../gh-exec.js';
17
13
  import { REST_MERGE_ON_GREEN } from '../../../gh-pr-rest.js';
18
14
  import { resolveAutoMergeArmCwd } from '../../auto-merge-cwd.js';
19
15
  import {
@@ -24,7 +20,6 @@ import {
24
20
  armForMergeQueue,
25
21
  disarmByDequeue,
26
22
  MERGE_QUEUE_REFUSAL,
27
- MERGE_QUEUE_REST_BLOCK_CLASS,
28
23
  readMergeQueueState,
29
24
  } from '../../merge-queue.js';
30
25
 
@@ -145,30 +140,12 @@ export async function enableAutoMergeWith({
145
140
  resolveArmCwd = resolveAutoMergeArmCwd,
146
141
  queueRequired = false,
147
142
  }) {
148
- const facade = gh ?? defaultGh;
149
- const refused = await refuseQueueOverRest(facade, queueRequired);
150
- if (refused) return refused;
151
- const exec = runner ?? makeDefaultGhAutoMergeRunner(facade);
143
+ const exec = runner ?? makeDefaultGhAutoMergeRunner(gh ?? defaultGh);
152
144
  const armCwd = resolveArmCwd(cwd);
153
145
  const arm = queueRequired ? armForMergeQueue : armNativeAutoMerge;
154
146
  return arm({ exec, prNumber, armCwd });
155
147
  }
156
148
 
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
-
172
149
  /** The hand-run equivalent of the arm, for an operator-facing remedy. */
173
150
  export function manualArmCommand({ prNumber, queueRequired = false }) {
174
151
  return queueRequired
@@ -35,7 +35,7 @@ import {
35
35
  * resolveConfigImpl?: typeof resolveConfig,
36
36
  * progress: (tag: string, msg: string) => void,
37
37
  * }} args
38
- * @returns {Promise<{ changedPaths: string[], creditedCommit: string|null, baselineRef?: string, decision: object|null }>}
38
+ * @returns {Promise<{ changedPaths: string[], creditedCommit: string|null, baselineRef?: string, decision: object|null, kind: string, resolvedBaselineFiles: string[] }>}
39
39
  * The pre-sync head is the credited commit; a skipped sync pins `baselineRef`.
40
40
  */
41
41
  export async function runBaseSyncPhase({
@@ -91,6 +91,11 @@ export async function runBaseSyncPhase({
91
91
  })) {
92
92
  progress('SYNC', line);
93
93
  }
94
+ return phaseResult(syncResult, resolved);
95
+ }
96
+
97
+ /** What the gate chain reads from a completed sync. */
98
+ function phaseResult(syncResult, resolvedBaselineFiles) {
94
99
  return {
95
100
  changedPaths: Array.isArray(syncResult.changedPaths)
96
101
  ? syncResult.changedPaths
@@ -98,6 +103,8 @@ export async function runBaseSyncPhase({
98
103
  creditedCommit: syncResult.preSyncHead ?? null,
99
104
  baselineRef: syncResult.baselineRef,
100
105
  decision: syncResult.decision ?? null,
106
+ kind: syncResult.kind,
107
+ resolvedBaselineFiles,
101
108
  };
102
109
  }
103
110
 
@@ -14,12 +14,14 @@ import {
14
14
  sourcedTimings,
15
15
  summarizeLockEvents,
16
16
  } from '../../../close-lock-events.js';
17
+ import { applyBaseSyncCiDeferral as defaultApplyBaseSyncCiDeferral } from '../../../close-validation/base-sync-revalidation.js';
17
18
  import {
18
19
  BASELINES_GATE_NAMES,
19
20
  buildDefaultGates as defaultBuildDefaultGates,
20
21
  } from '../../../close-validation/gates.js';
21
22
  import { runCloseValidation as defaultRunCloseValidation } from '../../../close-validation/runner.js';
22
23
  import { applyTestDelta as defaultApplyTestDelta } from '../../../close-validation/test-delta.js';
24
+ import { suiteGateDeferral } from '../../../coverage-deferral.js';
23
25
  import { LOCK_WAIT_EXPIRED_EXIT_CODE } from '../../../full-suite-lock.js';
24
26
  import { createGateLogSink as defaultCreateGateLogSink } from '../gate-log.js';
25
27
  import { runPreGateSteps as defaultRunPreGateSteps } from './pre-gate-steps.js';
@@ -36,11 +38,12 @@ import { runPreGateSteps as defaultRunPreGateSteps } from './pre-gate-steps.js';
36
38
  * baseBranch: string,
37
39
  * storyBranch?: string,
38
40
  * storyId: number,
39
- * baseSync?: { changedPaths: string[], creditedCommit: string|null, baselineRef?: string }|null,
41
+ * baseSync?: { changedPaths: string[], creditedCommit: string|null, baselineRef?: string, kind?: string, resolvedBaselineFiles?: string[] }|null,
40
42
  * progress: (tag: string, msg: string) => void,
41
43
  * runCloseValidation?: typeof defaultRunCloseValidation,
42
44
  * buildDefaultGates?: typeof defaultBuildDefaultGates,
43
45
  * applyTestDelta?: typeof defaultApplyTestDelta,
46
+ * applyBaseSyncCiDeferral?: typeof defaultApplyBaseSyncCiDeferral,
44
47
  * runPreGateSteps?: typeof defaultRunPreGateSteps,
45
48
  * runScopedFormatAutofix?: Function,
46
49
  * runBaselineUpwardWriteback?: Function,
@@ -54,8 +57,11 @@ import { runPreGateSteps as defaultRunPreGateSteps } from './pre-gate-steps.js';
54
57
  * lockWait: { waitedSeconds: number, expired: boolean, holder?: object }|null,
55
58
  * suiteTimings: { lockWaitMs: number, hostWaitMs: number|null, testRunMs: number, source: 'close', spawns: object[] }|null,
56
59
  * pending: boolean,
60
+ * coverageDeferred?: string|null,
61
+ * revalidation?: object|null,
57
62
  * }>} `pending` (with `gates: null`) when a lock wait expired; any other
58
- * failure throws with `err.closeGate` naming the gate.
63
+ * failure throws with `err.closeGate` naming the gate. `revalidation` is
64
+ * non-null only under `revalidateAfterBaseSync: "ci"`.
59
65
  */
60
66
  export async function runCloseValidationPhase({
61
67
  cwd,
@@ -69,6 +75,7 @@ export async function runCloseValidationPhase({
69
75
  runCloseValidation = defaultRunCloseValidation,
70
76
  buildDefaultGates = defaultBuildDefaultGates,
71
77
  applyTestDelta = defaultApplyTestDelta,
78
+ applyBaseSyncCiDeferral = defaultApplyBaseSyncCiDeferral,
72
79
  runPreGateSteps = defaultRunPreGateSteps,
73
80
  runScopedFormatAutofix,
74
81
  runBaselineUpwardWriteback,
@@ -106,10 +113,10 @@ export async function runCloseValidationPhase({
106
113
  evidenceCwd: cwd,
107
114
  baselineRef: baseSync?.baselineRef,
108
115
  };
109
- const gateList = applyTestDelta(buildDefaultGates(gateOpts), {
110
- ...gateOpts,
111
- baseSync,
112
- });
116
+ const { gates: gateList, revalidation } = buildGateList(
117
+ { buildDefaultGates, applyTestDelta, applyBaseSyncCiDeferral },
118
+ { ...gateOpts, baseSync },
119
+ );
113
120
  reportGateLabels(gateList, progress);
114
121
  const { validation, lockWait, ...timings } = await runGateChain({
115
122
  runCloseValidation,
@@ -139,10 +146,22 @@ export async function runCloseValidationPhase({
139
146
  lockWait,
140
147
  suiteTimings: sourcedTimings(timings, 'close'),
141
148
  pending: false,
142
- coverageDeferred: validation.deferred?.[0]?.reason ?? null,
149
+ coverageDeferred: coverageDeferralReason(validation),
150
+ revalidation,
143
151
  };
144
152
  }
145
153
 
154
+ /** Built gates, then the `test` delta, then the post-merge CI deferral. */
155
+ function buildGateList(build, opts) {
156
+ const gates = build.applyTestDelta(build.buildDefaultGates(opts), opts);
157
+ return build.applyBaseSyncCiDeferral(gates, opts);
158
+ }
159
+
160
+ /** The suite gate's deferral reason; a typecheck or lint deferral is not one. */
161
+ function coverageDeferralReason(validation) {
162
+ return suiteGateDeferral(validation.deferred)?.reason ?? null;
163
+ }
164
+
146
165
  /** A labelled gate (the `test` delta re-credit) names itself on the progress line. */
147
166
  function reportGateLabels(gateList, progress) {
148
167
  for (const gate of gateList) {
@@ -38,6 +38,7 @@ import {
38
38
  isRerunPermitted,
39
39
  } from '../../check-state.js';
40
40
  import { recordRequiredRed as defaultRecordRequiredRed } from '../../ci-red-handling.js';
41
+ import { writeCiDigest } from '../../ci-rerun-guard.js';
41
42
  import {
42
43
  emitMergeFlipFailed as defaultEmitMergeFlipFailed,
43
44
  MERGED_FLIP_FAILED_BLOCK_CLASS,
@@ -48,6 +49,7 @@ import {
48
49
  ADVISORY_GATE_INCONCLUSIVE_CLASS,
49
50
  ADVISORY_GATE_RED_CLASS,
50
51
  CHECKS_FAILED_CLASS,
52
+ CHECKS_STATUSES,
51
53
  DEFAULT_INTERVAL_SECONDS,
52
54
  DEFAULT_MAX_BUDGET_SECONDS,
53
55
  decideAdvisoryGateBlock,
@@ -66,7 +68,9 @@ import {
66
68
  import {
67
69
  MERGE_QUEUE_REST_BLOCK_CLASS,
68
70
  MERGE_QUEUE_REST_REMEDY,
71
+ QUEUE_EJECTED_BLOCK_CLASS,
69
72
  readMergeQueueState,
73
+ readQueueEjection,
70
74
  } from '../../merge-queue.js';
71
75
  import { readProbeRunEvidence } from '../../required-checks.js';
72
76
  import { NEXT_COMMANDS } from '../../story-deliver-terminal.js';
@@ -274,6 +278,7 @@ export async function readPrWaitProbe({
274
278
  redHeadRuns: deriveRedHeadRuns(view?.statusCheckRollup),
275
279
  checkStates: deriveCheckStates(view?.statusCheckRollup),
276
280
  headSha: readString(view?.headRefOid),
281
+ prNodeId: readString(view?.id),
277
282
  autoMergeArmed: readAutoMergeArmed(view),
278
283
  };
279
284
  } catch (err) {
@@ -405,16 +410,10 @@ function disarmedOn(redRecord) {
405
410
  * @param {{ storyId: number, prNumber: number|null, blockClass: string }} args
406
411
  * @returns {string}
407
412
  */
408
- function unlandedRemedy({ storyId, prNumber, blockClass, redRecord }) {
409
- if (blockClass === CHECKS_FAILED_CLASS) {
410
- return checksFailedRemedy({ storyId, prNumber, redRecord });
411
- }
412
- if (
413
- blockClass === ADVISORY_GATE_INCONCLUSIVE_CLASS ||
414
- blockClass === ADVISORY_GATE_RED_CLASS
415
- ) {
416
- return advisoryGateRemedy({ storyId, blockClass, redRecord });
417
- }
413
+ function unlandedRemedy(args) {
414
+ const remedy = REMEDY_OF_CLASS[args.blockClass];
415
+ if (remedy) return remedy(args);
416
+ const { storyId } = args;
418
417
  return (
419
418
  `Resolve the underlying condition (branch protection, required checks, ` +
420
419
  `or a manual merge), then resume the land:\n\n` +
@@ -422,6 +421,13 @@ function unlandedRemedy({ storyId, prNumber, blockClass, redRecord }) {
422
421
  );
423
422
  }
424
423
 
424
+ const REMEDY_OF_CLASS = Object.freeze({
425
+ [CHECKS_FAILED_CLASS]: checksFailedRemedy,
426
+ [QUEUE_EJECTED_BLOCK_CLASS]: queueEjectedRemedy,
427
+ [ADVISORY_GATE_INCONCLUSIVE_CLASS]: advisoryGateRemedy,
428
+ [ADVISORY_GATE_RED_CLASS]: advisoryGateRemedy,
429
+ });
430
+
425
431
  /**
426
432
  * States what the red handling actually did — never claims a disarm or a
427
433
  * digest that did not happen — then names both ci-remediation routes.
@@ -437,11 +443,8 @@ function checksFailedRemedy({ storyId, prNumber, redRecord }) {
437
443
  : 'Auto-merge was **disarmed**; only a green on a new head SHA, or the one rerun a filed `capacity` / `unreproducible-tier` verdict admits, re-arms it.'
438
444
  : `⚠️ Auto-merge could **not** be disarmed (${disarm?.detail ?? 'the red handling did not run'}) — GitHub may still land the PR when the checks read green. Disarm it by hand.`;
439
445
  const watch = NEXT_COMMANDS.watchCi(storyId, prNumber);
440
- const digestLine = redRecord?.digestPaths
441
- ? `CI digest (run link + failure signature): \`${redRecord.digestPaths.jsonPath}\`.`
442
- : `⚠️ No CI digest was written (${redRecord?.digestError ?? 'no Story scope'}); \`${watch}\` rewrites it.`;
443
446
  return (
444
- `A required check is **red**. ${armLine}\n\n${digestLine}\n\n` +
447
+ `A required check is **red**. ${armLine}\n\n${digestLineOf(redRecord, watch)}\n\n` +
445
448
  `Per \`.agents/rules/ci-remediation.md\`, either fix the failure and push a new commit on ` +
446
449
  `\`story-${storyId}\` (re-running the failed job is forbidden), or — when the root cause is ` +
447
450
  `outside this delivery — file it:\n\n` +
@@ -451,6 +454,27 @@ function checksFailedRemedy({ storyId, prNumber, redRecord }) {
451
454
  );
452
455
  }
453
456
 
457
+ function digestLineOf(redRecord, rewrite) {
458
+ return redRecord?.digestPaths
459
+ ? `CI digest (run link + failure signature): \`${redRecord.digestPaths.jsonPath}\`.`
460
+ : `⚠️ No CI digest was written (${redRecord?.digestError ?? 'no Story scope'}); \`${rewrite}\` rewrites it.`;
461
+ }
462
+
463
+ /** The queue run's own failure: fix on the Story branch, hand off again. */
464
+ function queueEjectedRemedy({ storyId, prNumber, redRecord }) {
465
+ const run = redRecord?.queueRun ?? {};
466
+ return (
467
+ `The merge queue **ejected** PR #${prNumber}: queue run ${run.url ?? `#${run.id}`} ` +
468
+ `concluded \`${run.conclusion}\` and the entry it was built on did not fail, so the ` +
469
+ `failure is this change's own. Auto-merge was not re-armed.\n\n` +
470
+ `${digestLineOf(redRecord, NEXT_COMMANDS.watchCi(storyId, prNumber))}\n\n` +
471
+ `Fix it on \`story-${storyId}\` in the Story worktree, commit, and re-run the hand-off, ` +
472
+ `which pushes the new head:\n\n` +
473
+ `\`\`\`bash\nnode .agents/scripts/story-handoff.js --story ${storyId} --cwd <worktree>\n\`\`\`\n\n` +
474
+ `Then resume the land:\n\n\`\`\`bash\n${NEXT_COMMANDS.resumeLand(storyId)}\n\`\`\``
475
+ );
476
+ }
477
+
454
478
  function formatUnlandedFriction({
455
479
  storyId,
456
480
  prNumber,
@@ -851,7 +875,7 @@ function queuedExhaustionVerdict(probe, cumulativeMs) {
851
875
  *
852
876
  * @returns {Promise<object>} the `recordRequiredRed` outcome.
853
877
  */
854
- async function recordRed(ctx, probe, failures) {
878
+ async function recordRed(ctx, probe, failures, run = null) {
855
879
  const {
856
880
  storyId,
857
881
  prNumber,
@@ -872,6 +896,7 @@ async function recordRed(ctx, probe, failures) {
872
896
  cwd,
873
897
  headSha: probe?.headSha ?? null,
874
898
  disarmFn: () => disarmAutoMergeFn({ prNumber, gh, progress }),
899
+ ...pinnedRun(run),
875
900
  });
876
901
  if (record.digestPaths) {
877
902
  progress?.(
@@ -895,6 +920,13 @@ async function recordRed(ctx, probe, failures) {
895
920
  }
896
921
  }
897
922
 
923
+ /** A queue run is not on the PR head, so the digest is pinned to it. */
924
+ function pinnedRun(run) {
925
+ if (!run) return {};
926
+ const checkRunFn = () => ({ runId: String(run.id), url: run.url });
927
+ return { writeDigestFn: (args) => writeCiDigest({ ...args, checkRunFn }) };
928
+ }
929
+
898
930
  /** Classify, emit `merge.unlanded`, post friction, block — all best-effort. */
899
931
  async function blockOnUnlanded({
900
932
  storyId,
@@ -1159,9 +1191,20 @@ function singleProbeOrContinue(limits, overBudget, checksStatus) {
1159
1191
  return settles ? 'single-probe' : 'continue';
1160
1192
  }
1161
1193
 
1194
+ /** A verdict no budget changes: merged, closed, or a status outside the closed vocabulary. */
1195
+ function settledVerdictOf(probe) {
1196
+ if (isPrMerged(probe)) return 'merged';
1197
+ if (probe.state === 'CLOSED') return 'closed';
1198
+ const status = probe.checksStatus;
1199
+ if (status != null && !CHECKS_STATUSES.includes(status)) {
1200
+ return 'checks-status-unrecognised';
1201
+ }
1202
+ return null;
1203
+ }
1204
+
1162
1205
  /**
1163
- * Pure: state + probe + clock → next state and verdict. `merged`, `closed`
1164
- * and `checks-failed` are definitive; `budget-exhausted`, `wait-bound`,
1206
+ * Pure: state + probe + clock → next state and verdict. `merged`, `closed`,
1207
+ * `checks-status-unrecognised` and `checks-failed` are definitive; `budget-exhausted`, `wait-bound`,
1165
1208
  * `single-probe` and `continue` hold only if the loop's advisory check does not block first.
1166
1209
  * The two clock reads (wait bound, then budget) keep a stepping test clock's
1167
1210
  * call sequence.
@@ -1202,10 +1245,8 @@ export function decideMergeWaitPoll({
1202
1245
  maxBudgetSeconds: limits.maxBudgetSeconds,
1203
1246
  },
1204
1247
  };
1205
- if (isPrMerged(probe)) return { state: polled, verdict: 'merged', ...timing };
1206
- if (probe.state === 'CLOSED') {
1207
- return { state: polled, verdict: 'closed', ...timing };
1208
- }
1248
+ const settled = settledVerdictOf(probe);
1249
+ if (settled) return { state: polled, verdict: settled, ...timing };
1209
1250
  // No remaining budget turns a red required check green; fail fast.
1210
1251
  const failFast = decideMergeWaitFailFast({
1211
1252
  probe,
@@ -1280,9 +1321,44 @@ async function settleChecksFailed(ctx, decision, probe) {
1280
1321
  });
1281
1322
  }
1282
1323
 
1324
+ /** An own queue failure settles at once, its digest written from the queue run. */
1325
+ async function settleQueueEjected(ctx, decision, probe, ejection) {
1326
+ const { run } = ejection;
1327
+ const names = ejection.failedJobs?.length
1328
+ ? ejection.failedJobs
1329
+ : [run.name ?? 'merge queue'];
1330
+ const failures = names.map((name) => ({
1331
+ name,
1332
+ outcome: run.conclusion,
1333
+ runId: run.id,
1334
+ }));
1335
+ ctx.progress?.(
1336
+ 'CONFIRM',
1337
+ `🛑 PR #${ctx.prNumber}: the merge queue ejected it on its own failure (${run.url ?? run.id}) — handing back.`,
1338
+ );
1339
+ const redRecord = await recordRed(ctx, probe, failures, run);
1340
+ return blockWith(ctx, {
1341
+ prProbe: probe,
1342
+ budget: { exhausted: false, elapsedSeconds: decision.elapsedSeconds },
1343
+ blockClassOverride: QUEUE_EJECTED_BLOCK_CLASS,
1344
+ reasonOverride: `merge queue run ${run.url ?? run.id} concluded ${run.conclusion}: ${describeFailures(failures)}`,
1345
+ redRecord: { ...redRecord, queueRun: run },
1346
+ });
1347
+ }
1348
+
1349
+ function settleUnrecognisedChecks(ctx, decision, probe) {
1350
+ return blockWith(ctx, {
1351
+ prProbe: probe,
1352
+ budget: { exhausted: false, elapsedSeconds: decision.elapsedSeconds },
1353
+ blockClassOverride: CLOSED_UNMERGED_BLOCK_CLASS,
1354
+ reasonOverride: `unrecognised checks status (${probe.checksStatus})`,
1355
+ });
1356
+ }
1357
+
1283
1358
  const DEFINITIVE_SETTLERS = Object.freeze({
1284
1359
  merged: settleMerged,
1285
1360
  closed: settleClosed,
1361
+ 'checks-status-unrecognised': settleUnrecognisedChecks,
1286
1362
  'checks-failed': settleChecksFailed,
1287
1363
  });
1288
1364
 
@@ -1347,9 +1423,8 @@ async function recoverOpenPr(ctx, decision, probe) {
1347
1423
  if (advisory) {
1348
1424
  return { state: decision.state, outcome: await blockWith(ctx, advisory) };
1349
1425
  }
1350
- const landed = await maybeMergeOnGreen(ctx, decision, probe);
1351
- if (landed) return { state: decision.state, outcome: landed };
1352
- await maybeRearmPr(ctx, probe);
1426
+ const settled = await settleOpenPr(ctx, decision, probe);
1427
+ if (settled) return { state: decision.state, outcome: settled };
1353
1428
  const updated = await maybeUpdateBehindPr({
1354
1429
  probe,
1355
1430
  prNumber: ctx.prNumber,
@@ -1365,15 +1440,73 @@ async function recoverOpenPr(ctx, decision, probe) {
1365
1440
  return { state, outcome: null };
1366
1441
  }
1367
1442
 
1443
+ /** Merge-on-green lands; an own ejection blocks; otherwise the re-arm rule runs. */
1444
+ async function settleOpenPr(ctx, decision, probe) {
1445
+ const landed = await maybeMergeOnGreen(ctx, decision, probe);
1446
+ if (landed) return landed;
1447
+ const ejection = await readEjection(ctx, probe);
1448
+ if (ejection?.verdict === 'own') {
1449
+ return settleQueueEjected(ctx, decision, probe, ejection);
1450
+ }
1451
+ if (await admitsRearm(ctx, ejection)) await maybeRearmPr(ctx, probe);
1452
+ return null;
1453
+ }
1454
+
1455
+ /**
1456
+ * A queue ejection, read only for a close-armed, un-armed PR that GraphQL
1457
+ * reads out of the queue (`inMergeQueue` is only read on a green open PR).
1458
+ */
1459
+ async function readEjection(ctx, probe) {
1460
+ const unarmed = ctx.closeArmed === true && probe.autoMergeArmed === false;
1461
+ if (probe.inMergeQueue !== false || !unarmed || !probe.headSha) return null;
1462
+ return ctx.readQueueEjectionFn({
1463
+ prNodeId: probe.prNodeId,
1464
+ prNumber: ctx.prNumber,
1465
+ headSha: probe.headSha,
1466
+ gh: ctx.waitGh,
1467
+ timeoutMs: ctx.ghTimeoutMs,
1468
+ });
1469
+ }
1470
+
1471
+ /**
1472
+ * Each distinct inherited ejecting run frees one more re-arm on the head
1473
+ * (the once-per-head record is reset); a held release veto admits none.
1474
+ */
1475
+ async function admitsRearm(ctx, ejection) {
1476
+ if (ejection?.verdict !== 'inherited') return true;
1477
+ const labels = ejection.labels ?? [];
1478
+ if (await ctx.releaseVetoFn({ config: ctx.config, labels, cwd: ctx.cwd })) {
1479
+ return false;
1480
+ }
1481
+ if (!ctx.ejectionRuns.has(ejection.run?.id)) {
1482
+ ctx.ejectionRuns.add(ejection.run?.id);
1483
+ ctx.rearmedHeads.clear();
1484
+ }
1485
+ return true;
1486
+ }
1487
+
1488
+ /** Loaded on use: the inventory's import graph is not close's to carry. */
1489
+ async function releaseVetoHolds(args) {
1490
+ const inventory = await import('../../../orchestrate/inventory.js');
1491
+ return inventory.releaseVetoHolds(args);
1492
+ }
1493
+
1368
1494
  /**
1369
1495
  * Close owns the merge when the CCR route would not arm it: the arm said so,
1370
1496
  * or (a `--wait` resume, which has no arm outcome) the PR transport is REST
1371
- * and GitHub holds no auto-merge request. Only a PR close itself armed.
1497
+ * and GitHub holds no auto-merge request. Only a PR close itself armed, and
1498
+ * never on a queue base: GitHub clears the request when it enqueues.
1372
1499
  *
1373
1500
  * @returns {Promise<boolean>}
1374
1501
  */
1375
1502
  async function closeOwnsMerge(ctx, probe) {
1376
- if (ctx.closeArmed !== true) return false;
1503
+ if (ctx.closeArmed !== true || !(await restOwnsMerge(ctx, probe))) {
1504
+ return false;
1505
+ }
1506
+ return !(await baseRequiresQueue(ctx));
1507
+ }
1508
+
1509
+ async function restOwnsMerge(ctx, probe) {
1377
1510
  if (ctx.autoMergeReason === REST_MERGE_ON_GREEN) return true;
1378
1511
  return (
1379
1512
  probe.autoMergeArmed !== true &&
@@ -1381,6 +1514,18 @@ async function closeOwnsMerge(ctx, probe) {
1381
1514
  );
1382
1515
  }
1383
1516
 
1517
+ /** Read once per invocation; a failed read (`null`) is not a queue. */
1518
+ function baseRequiresQueue(ctx) {
1519
+ ctx.queueRequiredRead ??= ctx
1520
+ .readMergeQueueStateFn({
1521
+ prNumber: ctx.prNumber,
1522
+ gh: ctx.waitGh,
1523
+ timeoutMs: ctx.ghTimeoutMs,
1524
+ })
1525
+ .then((queue) => queue?.queueRequired === true);
1526
+ return ctx.queueRequiredRead;
1527
+ }
1528
+
1384
1529
  function isCleanAndGreen(probe) {
1385
1530
  return (
1386
1531
  probe?.state === 'OPEN' &&
@@ -1557,6 +1702,9 @@ function neverArmedOverride(autoMergeReason, advisoryGate) {
1557
1702
  * @param {Function} [args.disarmAutoMergeFn]
1558
1703
  * @param {Function} [args.recordRequiredRedFn] The shared first-red handling (disarm + CI digest).
1559
1704
  * @param {Function} [args.mergeOnGreenFn] The merge-on-green squash-merge (`auto-merge.js#mergeOnGreen`).
1705
+ * @param {Function} [args.readMergeQueueStateFn] Whether the base requires a merge queue.
1706
+ * @param {Function} [args.readQueueEjectionFn] Why the merge queue ejected the PR.
1707
+ * @param {Function} [args.releaseVetoFn] Whether `orchestrate.releaseVeto` holds the PR.
1560
1708
  * @param {object} [args.recoverySeams] DIRTY-sync / re-arm seams (`mergeWaitRecoverySeams`).
1561
1709
  * @param {(ms: number) => Promise<void>} [args.sleepFn]
1562
1710
  * @param {() => number} [args.nowMsFn]
@@ -1577,6 +1725,9 @@ export async function runConfirmMergePhase({
1577
1725
  disarmAutoMergeFn = disarmAutoMerge,
1578
1726
  recordRequiredRedFn = defaultRecordRequiredRed,
1579
1727
  mergeOnGreenFn = mergeOnGreen,
1728
+ readMergeQueueStateFn = readMergeQueueState,
1729
+ readQueueEjectionFn = readQueueEjection,
1730
+ releaseVetoFn = releaseVetoHolds,
1580
1731
  sleepFn = defaultSleep,
1581
1732
  nowMsFn = Date.now,
1582
1733
  ghTimeoutMs = MERGE_WAIT_GH_TIMEOUT_MS,
@@ -1625,6 +1776,10 @@ export async function runConfirmMergePhase({
1625
1776
  disarmAutoMergeFn,
1626
1777
  recordRequiredRedFn,
1627
1778
  mergeOnGreenFn,
1779
+ readMergeQueueStateFn,
1780
+ readQueueEjectionFn,
1781
+ releaseVetoFn,
1782
+ ejectionRuns: new Set(),
1628
1783
  nowMsFn,
1629
1784
  ghTimeoutMs,
1630
1785
  waitGh: args.injectedGh ?? defaultGh,
@@ -165,14 +165,15 @@ export async function finishWithMergeWait(prCtx, deps) {
165
165
  return { success: terminal.status === 'landed', result, terminal };
166
166
  }
167
167
 
168
- /** The close-only envelope fields both finishes carry. */
168
+ /** The close-only envelope fields both finishes carry; an undefined one is dropped. */
169
169
  function closeEnvelopeFields({
170
170
  lockWait,
171
171
  suiteTimings,
172
172
  baseSync,
173
173
  pushOutcome,
174
+ revalidation,
174
175
  }) {
175
- return { lockWait, suiteTimings, baseSync, pushOutcome };
176
+ return { lockWait, suiteTimings, baseSync, pushOutcome, revalidation };
176
177
  }
177
178
 
178
179
  /**
@@ -104,13 +104,19 @@ export async function runPrePushPhases(ctx, deps) {
104
104
  }
105
105
  throw err;
106
106
  }
107
- const gates = validation?.gates ?? null;
108
- ctx.setObservedGates(gates);
107
+ ctx.setObservedGates(validation?.gates ?? null);
108
+ return validatedResult(validation);
109
+ }
110
+
111
+ /** The pre-push result of a gate chain that ran. */
112
+ function validatedResult(validation) {
109
113
  return {
110
- validationGates: gates,
114
+ validationGates: validation?.gates ?? null,
111
115
  lockWait: validation?.lockWait ?? null,
112
116
  suiteTimings: validation?.suiteTimings ?? null,
113
117
  pending: validation?.pending === true,
114
118
  coverageDeferred: validation?.coverageDeferred ?? null,
119
+ // Undefined, not null, so the envelope omits it outside the `ci` mode.
120
+ revalidation: validation?.revalidation ?? undefined,
115
121
  };
116
122
  }
@@ -170,15 +170,18 @@ function baselinesEnvelopeGates(validationGates) {
170
170
  }
171
171
 
172
172
  /**
173
- * A capture deferred to CI is the one capture outcome a reviewer must see.
173
+ * Every gate deferred to CI (typecheck, lint, coverage-capture): the one
174
+ * outcome of those gates a reviewer must see.
174
175
  *
175
176
  * @param {Record<string, string>|null|undefined} validationGates
176
177
  * @returns {Record<string, string>}
177
178
  */
178
- function deferredCaptureGate(validationGates) {
179
- return validationGates?.['coverage-capture'] === 'deferred'
180
- ? { 'coverage-capture': 'deferred' }
181
- : {};
179
+ function deferredGates(validationGates) {
180
+ const out = {};
181
+ for (const [name, outcome] of Object.entries(validationGates ?? {})) {
182
+ if (outcome === 'deferred') out[name] = outcome;
183
+ }
184
+ return out;
182
185
  }
183
186
 
184
187
  /**
@@ -220,7 +223,7 @@ export function closeEnvelopeGates(
220
223
  return {
221
224
  validation: options.skipValidation ? 'skipped' : 'passed',
222
225
  ...baselinesEnvelopeGates(validationGates),
223
- ...deferredCaptureGate(validationGates),
226
+ ...deferredGates(validationGates),
224
227
  baseSync: options.skipSync ? 'skipped' : 'passed',
225
228
  codeReview: codeReviewGate(
226
229
  reviewOverride,
@@ -456,6 +456,7 @@ function buildPrContext(ctx, deps) {
456
456
  lockWait: ctx.prePush.lockWait,
457
457
  baseSync: ctx.baseSync?.decision ?? null,
458
458
  pushOutcome: ctx.pr.pushOutcome ?? null,
459
+ revalidation: ctx.prePush.revalidation,
459
460
  suiteTimings: envelopeSuiteTimings(ctx, deps),
460
461
  gates: closeEnvelopeGates(
461
462
  options,