mandrel 2.119.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.
@@ -86,7 +86,7 @@ Project identity, filesystem roots, planner docs context, and the commands the c
86
86
  | `docsContextFiles` | No | `array<string>` | `["architecture.md","data-dictionary.md","decisions.md","patterns.md"]` | Files under `paths.docsRoot` the planner treats as standing context. Read digest-first — the docs digest names the file and the line range, and only the named section is pulled. |
87
87
  | `commands` | No | `object` | — | Shell commands the close-validation chain spawns, each run from the repo root. One tri-state per key: absent uses the default shown; an explicit `null` disables an optional gate (`typecheck`, `lint`, `formatCheck`) — close reports it as skipped (`<gate>-disabled`) and runs nothing; a string is that command. Like every command here it must be a single argv (no `;`, `&&`, pipes or substitution), so wrap a multi-tool pair in one script and name that. |
88
88
  | `commands.test` | No | `string` | `"npm test"` | Full test-suite command close's `test` gate spawns, and the identity its `test` credit is hashed under — the deposit `run-tests.js` makes, close's credit probe and `verify[]` credit all key on it, as does `mandrel doctor`'s `test-credit-path` check. Set it for a non-npm project (e.g. `python3 scripts/validation.py`). Mandatory: `null` is rejected. |
89
- | `commands.testChanged` | No | `string` \| `null` | — | Optional changed-tests command for the delta re-credit: when close's base sync merged sibling landings into a branch whose pre-sync head holds `test` credit, close's `test` gate runs this instead of the full suite, with the credited commit in the `MANDREL_CHANGED_SINCE` environment variable and in place of a literal `$MANDREL_CHANGED_SINCE` argument (e.g. `pnpm vitest run --changed $MANDREL_CHANGED_SINCE`; no shell runs it), and a green run re-credits the merged tree. Ineligible when coverage-capture runs the suite, an incoming path is a coverage-config file or one of the Story's own files, or no incoming path is a suite input. The overlap rule ignores baseline (`baselines/`) and coverage-directory paths, and paths matching `delivery.quality.gates.coverage.nonInputGlobs`; those globs never change the incoming count or the emptiness rule, and a config file refuses under either value of `captureHandlesConfigChanges`. It is also the skip-branch first-credit depositor: when coverage-capture is active but takes its incremental skip (no changed file under `crap.targetDirs`), handoff and close run it keyed on the `origin/<baseBranch>` merge-base, credited as the full suite. It MUST therefore select any test that reads a non-module input by path (a docs registry, a fixture file) — `--changed` cannot see that edge, so a break only such a test catches surfaces only where the full suite runs later. Prefer reading `MANDREL_CHANGED_SINCE` from the env over the argv token, so the spawned argv stays constant and declarable in `delivery.execution.workloads[]`. Absent or `null` keeps the full re-run and the full skip-branch suite. |
89
+ | `commands.testChanged` | No | `string` \| `null` | — | Optional changed-tests command for the delta re-credit: when close's base sync merged sibling landings into a branch whose pre-sync head holds `test` credit, close's `test` gate runs this instead of the full suite, with the credited commit in the `MANDREL_CHANGED_SINCE` environment variable and in place of a literal `$MANDREL_CHANGED_SINCE` argument (e.g. `pnpm vitest run --changed $MANDREL_CHANGED_SINCE`; no shell runs it), and a green run re-credits the merged tree. Ineligible when coverage-capture runs the suite, an incoming path is a coverage-config file or one of the Story's own files, or no incoming path is a suite input. The overlap rule ignores baseline (`baselines/`) and coverage-directory paths, and paths matching `delivery.quality.gates.coverage.nonInputGlobs`; those globs never change the incoming count or the emptiness rule, and a config file refuses under either value of `captureHandlesConfigChanges`. It is also the skip-branch first-credit depositor: when coverage-capture is active but takes its incremental skip (no changed file under `crap.targetDirs`), handoff and close run it keyed on the `origin/<baseBranch>` merge-base, credited as the full suite. It MUST therefore select any test that reads a non-module input by path (a docs registry, a fixture file) — `--changed` cannot see that edge, so a break only such a test catches surfaces only where the full suite runs later. Prefer reading `MANDREL_CHANGED_SINCE` from the env over the argv token, so the spawned argv stays constant and declarable in `delivery.execution.workloads[]`. It is also the handoff's changed-tests guard under `delivery.quality.gates.coverage.suiteOfRecord: ci` (see § Deferring coverage to CI). Absent or `null` keeps the full re-run and the full skip-branch suite. |
90
90
  | `commands.typecheck` | No | `string` \| `null` | `"npm run typecheck"` | Static type-check command run as a close-validation gate. An explicit `null` disables the gate for projects with no type layer (skip reason `typecheck-disabled`). The empty string is rejected so a typo cannot silently disable it. |
91
91
  | `commands.lint` | No | `string` \| `null` | `"npm run lint"` | Lint command run as a close-validation gate and by the handoff preflight. An explicit `null` disables both (skip reason `lint-disabled`). Point it at the scoped command your hooks already run to stop paying for a third whole-repo lint at close — the gate still lints the diff, and CI still owns whole-repo drift. |
92
92
  | `commands.formatCheck` | No | `string` \| `null` | `"npx biome format ."` | Non-mutating format verification run as a close-validation gate. An explicit `null` disables the gate (skip reason `format-disabled`). |
@@ -183,7 +183,7 @@ Everything `/mandrel-deliver` and `single-story-close` consume: worktree isolati
183
183
  | `quality.gates.coverage.captureScope` | No | `"full"` \| `"affected"` | `"full"` | What coverage-capture runs. `full` (default) runs `captureScript`. `affected` runs the consumer-owned `test:coverage:affected` script with the base ref in `MANDREL_COVERAGE_BASE_REF`, merges its rows over the prior artifact and stamps it `affected`; baseline rows the scoped run did not measure are treated as unmeasured, never removed. Falls back to `full` with a warning when the script is absent. Meant for consumers whose CI already enforces coverage on the full suite. |
184
184
  | `quality.gates.coverage.timeoutMs` | No | `integer` | `600000` | Kill bound (ms) for one full-suite run — the coverage capture, the close-validation full-suite gate and the full-suite lock-wait budget all read it. The clock starts at spawn, never while queued on the host lock; a suite that signals `MANDREL_SUITE_READY_FILE` gets a fresh bound for its test phase, so worst-case wall is lock wait + 2 × timeoutMs. On expiry the run exits 124 so callers can tell a hang from a failure. |
185
185
  | `quality.gates.coverage.onOverBudget` | No | `"block"` \| `"defer-to-ci"` | `"block"` | What handoff and close do when the capture script — or the `test` command (`project.commands.test`, or `testChanged` on the skip branch and the delta re-credit) — exits 76: the consumer-declared signal that the selected slice is over this host's budget and no test ran. `block` (default) stops the handoff (`blocked`) and fails close, naming this key. `defer-to-ci` settles the coverage gate as deferred to CI: no artifact is written or stamped and no credit is recorded, the coverage-reading gates (CRAP preview, coverage and CRAP baselines) are skipped, and handoff and close proceed — the terminal envelope and the PR body say coverage was deferred. Set it only when the consumer's CI runs the deferred suite with a coverage floor. A timeout (124) is never deferred, under either value. |
186
- | `quality.gates.coverage.suiteOfRecord` | No | `"local"` \| `"ci"` | `"local"` | Where the coverage capture runs. `local` (default) changes nothing. `ci` — meant for a small host's `.agentrc.local.json` — makes CI the coverage and CRAP ratchet of record: handoff and close settle the coverage gate as deferred (reason `suite-of-record-ci`) without spawning the capture, the PR body carries the `Coverage-deferred:` key line, and confirm-merge waits for `ciRatchetCheck` to go green. Requires `ciRatchetCheck`; without it handoff blocks and close fails. |
186
+ | `quality.gates.coverage.suiteOfRecord` | No | `"local"` \| `"ci"` | `"local"` | Where the coverage capture runs. `local` (default) changes nothing. `ci` — meant for a small host's `.agentrc.local.json` — makes CI the coverage and CRAP ratchet of record: handoff and close settle the coverage gate as deferred (reason `suite-of-record-ci`) without spawning the capture, the PR body carries the `Coverage-deferred:` key line, and confirm-merge waits for `ciRatchetCheck` to go green. When `project.commands.testChanged` is set, the handoff first runs it as a changed-tests guard. Requires `ciRatchetCheck`; without it handoff blocks and close fails. |
187
187
  | `quality.gates.coverage.ciRatchetCheck` | No | `string` \| `null` | `null` | Name of the consumer's CI check (check-run or status context) that runs `coverage-ratchet.js` on a deferred PR. Required by `suiteOfRecord: ci`; when set, confirm-merge holds `agent::done` on a PR carrying the `Coverage-deferred:` key line until this check is green on the PR head. Default `null`. |
188
188
  | `quality.gates.coverage.nonInputGlobs` | No | `array<string>` | `[]` | Repo-relative picomatch globs naming paths no test reads. A matching path is dropped from both sides of the coverage delta-refresh overlap check and from the re-measured set — a delta of only matching, baseline and coverage-directory paths restamps without a run — and from the overlap check of close's `test` delta re-credit (its incoming count and emptiness test are unchanged). It never changes the suite-input filter, the tree digest or stamp freshness. Default `[]`: nothing is built in, so Markdown counts as an input unless declared here. |
189
189
  | `quality.gates.coverage.captureHandlesConfigChanges` | No | `boolean` | `false` | Declares that the affected capture script, given `MANDREL_COVERAGE_BASE_REF`, widens its own selection when a coverage-determining config file (`package.json`, a lockfile, `tsconfig*.json`, a test-runner config) changes. When `true`, such a file in the coverage delta no longer refuses the delta refresh. Close's `test` delta re-credit refuses on a config file under either value. Default `false`. |
@@ -672,6 +672,16 @@ place.
672
672
  depositor; under the `test` depositor it changes nothing. It needs
673
673
  `ciRatchetCheck`. Without one the handoff settles `blocked`
674
674
  (`ci-ratchet-undeclared`) and close fails, both naming the two keys.
675
+ - **The changed-tests guard.** Under `suiteOfRecord: "ci"`, when
676
+ `project.commands.testChanged` is set, the handoff's credited-run step runs
677
+ it in the Story worktree (keyed on the `origin/<baseBranch>` merge-base)
678
+ before it settles the deferral. It takes no full-suite lock and deposits no
679
+ `test` or coverage credit; the deferral and the PR marker are unchanged.
680
+ Exit 0 settles deferred; exit 76 skips the guard and settles deferred; any
681
+ other exit settles `fix-required` with cause `changed-tests` and pushes
682
+ nothing. `timeoutMs` bounds it, and a timeout is `fix-required` too. A
683
+ held-review CRITICAL aborts it, as it aborts a credited run. A re-run at a
684
+ HEAD whose guard passed skips it. Unset, no test runs before the PR.
675
685
  - **`delivery.close.revalidateAfterBaseSync: "ci"`.** After a conflict-free
676
686
  base merge, close defers the capture (with `typecheck` and `lint`) to the
677
687
  checks in `delivery.close.revalidateCiChecks`, reason `base-sync-ci`. It
@@ -718,7 +728,11 @@ place.
718
728
  - **Doctor.** `mandrel doctor`'s `coverage-ratchet` check reads
719
729
  `.agentrc.json` with `.agentrc.local.json` over it. It fails when
720
730
  `suiteOfRecord` is `ci`, or `onOverBudget` is `defer-to-ci`, and
721
- `ciRatchetCheck` is unset.
731
+ `ciRatchetCheck` is unset. Its `suite-ownership` advisory never fails:
732
+ with `ciRatchetCheck` set and the posture local it reports the suite owned
733
+ by both the handoff and CI, naming `suiteOfRecord: "ci"` and
734
+ `project.commands.testChanged`; under `ci` without `testChanged` it reports
735
+ that no test runs before the PR.
722
736
  - **Nothing sticks.** A deferral writes no artifact, stamp or credit, so a
723
737
  later run on a bigger host captures, seats and scores as usual.
724
738
  - **A timeout is not a deferral.** Exit 124 can hide a hang, so it keeps its
@@ -91,7 +91,7 @@
91
91
  "type": "string",
92
92
  "pattern": "([;&|`]|\\$\\()"
93
93
  },
94
- "description": "Optional changed-tests command for the delta re-credit: when close's base sync merged sibling landings into a branch whose pre-sync head holds `test` credit, close's `test` gate runs this instead of the full suite, with the credited commit in the `MANDREL_CHANGED_SINCE` environment variable and in place of a literal `$MANDREL_CHANGED_SINCE` argument (e.g. `pnpm vitest run --changed $MANDREL_CHANGED_SINCE`; no shell runs it), and a green run re-credits the merged tree. Ineligible when coverage-capture runs the suite, an incoming path is a coverage-config file or one of the Story's own files, or no incoming path is a suite input. The overlap rule ignores baseline (`baselines/`) and coverage-directory paths, and paths matching `delivery.quality.gates.coverage.nonInputGlobs`; those globs never change the incoming count or the emptiness rule, and a config file refuses under either value of `captureHandlesConfigChanges`. It is also the skip-branch first-credit depositor: when coverage-capture is active but takes its incremental skip (no changed file under `crap.targetDirs`), handoff and close run it keyed on the `origin/<baseBranch>` merge-base, credited as the full suite. It MUST therefore select any test that reads a non-module input by path (a docs registry, a fixture file) — `--changed` cannot see that edge, so a break only such a test catches surfaces only where the full suite runs later. Prefer reading `MANDREL_CHANGED_SINCE` from the env over the argv token, so the spawned argv stays constant and declarable in `delivery.execution.workloads[]`. Absent or `null` keeps the full re-run and the full skip-branch suite."
94
+ "description": "Optional changed-tests command for the delta re-credit: when close's base sync merged sibling landings into a branch whose pre-sync head holds `test` credit, close's `test` gate runs this instead of the full suite, with the credited commit in the `MANDREL_CHANGED_SINCE` environment variable and in place of a literal `$MANDREL_CHANGED_SINCE` argument (e.g. `pnpm vitest run --changed $MANDREL_CHANGED_SINCE`; no shell runs it), and a green run re-credits the merged tree. Ineligible when coverage-capture runs the suite, an incoming path is a coverage-config file or one of the Story's own files, or no incoming path is a suite input. The overlap rule ignores baseline (`baselines/`) and coverage-directory paths, and paths matching `delivery.quality.gates.coverage.nonInputGlobs`; those globs never change the incoming count or the emptiness rule, and a config file refuses under either value of `captureHandlesConfigChanges`. It is also the skip-branch first-credit depositor: when coverage-capture is active but takes its incremental skip (no changed file under `crap.targetDirs`), handoff and close run it keyed on the `origin/<baseBranch>` merge-base, credited as the full suite. It MUST therefore select any test that reads a non-module input by path (a docs registry, a fixture file) — `--changed` cannot see that edge, so a break only such a test catches surfaces only where the full suite runs later. Prefer reading `MANDREL_CHANGED_SINCE` from the env over the argv token, so the spawned argv stays constant and declarable in `delivery.execution.workloads[]`. It is also the handoff's changed-tests guard under `delivery.quality.gates.coverage.suiteOfRecord: ci` (see § Deferring coverage to CI). Absent or `null` keeps the full re-run and the full skip-branch suite."
95
95
  },
96
96
  "typecheck": {
97
97
  "type": ["string", "null"],
@@ -758,7 +758,7 @@
758
758
  "suiteOfRecord": {
759
759
  "type": "string",
760
760
  "enum": ["local", "ci"],
761
- "description": "Where the coverage capture runs. `local` (default) changes nothing. `ci` — meant for a small host's `.agentrc.local.json` — makes CI the coverage and CRAP ratchet of record: handoff and close settle the coverage gate as deferred (reason `suite-of-record-ci`) without spawning the capture, the PR body carries the `Coverage-deferred:` key line, and confirm-merge waits for `ciRatchetCheck` to go green. Requires `ciRatchetCheck`; without it handoff blocks and close fails.",
761
+ "description": "Where the coverage capture runs. `local` (default) changes nothing. `ci` — meant for a small host's `.agentrc.local.json` — makes CI the coverage and CRAP ratchet of record: handoff and close settle the coverage gate as deferred (reason `suite-of-record-ci`) without spawning the capture, the PR body carries the `Coverage-deferred:` key line, and confirm-merge waits for `ciRatchetCheck` to go green. When `project.commands.testChanged` is set, the handoff first runs it as a changed-tests guard. Requires `ciRatchetCheck`; without it handoff blocks and close fails.",
762
762
  "default": "local"
763
763
  },
764
764
  "ciRatchetCheck": {
@@ -32,7 +32,8 @@
32
32
  "predicate-refused",
33
33
  "advisory-gate-red",
34
34
  "advisory-gate-inconclusive",
35
- "merge-queue-rest-unsupported"
35
+ "merge-queue-rest-unsupported",
36
+ "queue-ejected"
36
37
  ]
37
38
  },
38
39
  "reason": { "type": "string", "minLength": 1 },
@@ -159,6 +159,7 @@
159
159
  "advisory-gate-red",
160
160
  "advisory-gate-inconclusive",
161
161
  "merge-queue-rest-unsupported",
162
+ "queue-ejected",
162
163
  "merged-flip-failed"
163
164
  ]
164
165
  },
@@ -100,7 +100,7 @@ export const COVERAGE_GATE = {
100
100
  type: 'string',
101
101
  enum: ['local', 'ci'],
102
102
  description:
103
- "Where the coverage capture runs. `local` (default) changes nothing. `ci` — meant for a small host's `.agentrc.local.json` — makes CI the coverage and CRAP ratchet of record: handoff and close settle the coverage gate as deferred (reason `suite-of-record-ci`) without spawning the capture, the PR body carries the `Coverage-deferred:` key line, and confirm-merge waits for `ciRatchetCheck` to go green. Requires `ciRatchetCheck`; without it handoff blocks and close fails.",
103
+ "Where the coverage capture runs. `local` (default) changes nothing. `ci` — meant for a small host's `.agentrc.local.json` — makes CI the coverage and CRAP ratchet of record: handoff and close settle the coverage gate as deferred (reason `suite-of-record-ci`) without spawning the capture, the PR body carries the `Coverage-deferred:` key line, and confirm-merge waits for `ciRatchetCheck` to go green. When `project.commands.testChanged` is set, the handoff first runs it as a changed-tests guard. Requires `ciRatchetCheck`; without it handoff blocks and close fails.",
104
104
  default: COVERAGE_GATE_DEFAULTS.suiteOfRecord,
105
105
  },
106
106
  ciRatchetCheck: {
@@ -89,7 +89,7 @@ const COMMANDS_SCHEMA = {
89
89
  testChanged: {
90
90
  ...NULLABLE_NONEMPTY_SAFE_STRING,
91
91
  description:
92
- "Optional changed-tests command for the delta re-credit: when close's base sync merged sibling landings into a branch whose pre-sync head holds `test` credit, close's `test` gate runs this instead of the full suite, with the credited commit in the `MANDREL_CHANGED_SINCE` environment variable and in place of a literal `$MANDREL_CHANGED_SINCE` argument (e.g. `pnpm vitest run --changed $MANDREL_CHANGED_SINCE`; no shell runs it), and a green run re-credits the merged tree. Ineligible when coverage-capture runs the suite, an incoming path is a coverage-config file or one of the Story's own files, or no incoming path is a suite input. The overlap rule ignores baseline (`baselines/`) and coverage-directory paths, and paths matching `delivery.quality.gates.coverage.nonInputGlobs`; those globs never change the incoming count or the emptiness rule, and a config file refuses under either value of `captureHandlesConfigChanges`. It is also the skip-branch first-credit depositor: when coverage-capture is active but takes its incremental skip (no changed file under `crap.targetDirs`), handoff and close run it keyed on the `origin/<baseBranch>` merge-base, credited as the full suite. It MUST therefore select any test that reads a non-module input by path (a docs registry, a fixture file) — `--changed` cannot see that edge, so a break only such a test catches surfaces only where the full suite runs later. Prefer reading `MANDREL_CHANGED_SINCE` from the env over the argv token, so the spawned argv stays constant and declarable in `delivery.execution.workloads[]`. Absent or `null` keeps the full re-run and the full skip-branch suite.",
92
+ "Optional changed-tests command for the delta re-credit: when close's base sync merged sibling landings into a branch whose pre-sync head holds `test` credit, close's `test` gate runs this instead of the full suite, with the credited commit in the `MANDREL_CHANGED_SINCE` environment variable and in place of a literal `$MANDREL_CHANGED_SINCE` argument (e.g. `pnpm vitest run --changed $MANDREL_CHANGED_SINCE`; no shell runs it), and a green run re-credits the merged tree. Ineligible when coverage-capture runs the suite, an incoming path is a coverage-config file or one of the Story's own files, or no incoming path is a suite input. The overlap rule ignores baseline (`baselines/`) and coverage-directory paths, and paths matching `delivery.quality.gates.coverage.nonInputGlobs`; those globs never change the incoming count or the emptiness rule, and a config file refuses under either value of `captureHandlesConfigChanges`. It is also the skip-branch first-credit depositor: when coverage-capture is active but takes its incremental skip (no changed file under `crap.targetDirs`), handoff and close run it keyed on the `origin/<baseBranch>` merge-base, credited as the full suite. It MUST therefore select any test that reads a non-module input by path (a docs registry, a fixture file) — `--changed` cannot see that edge, so a break only such a test catches surfaces only where the full suite runs later. Prefer reading `MANDREL_CHANGED_SINCE` from the env over the argv token, so the spawned argv stays constant and declarable in `delivery.execution.workloads[]`. It is also the handoff's changed-tests guard under `delivery.quality.gates.coverage.suiteOfRecord: ci` (see § Deferring coverage to CI). Absent or `null` keeps the full re-run and the full skip-branch suite.",
93
93
  },
94
94
  typecheck: {
95
95
  ...NULLABLE_NONEMPTY_SAFE_STRING,
@@ -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',
@@ -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,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);
@@ -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,6 +21,20 @@ 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
 
@@ -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.
@@ -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,
@@ -67,7 +68,9 @@ import {
67
68
  import {
68
69
  MERGE_QUEUE_REST_BLOCK_CLASS,
69
70
  MERGE_QUEUE_REST_REMEDY,
71
+ QUEUE_EJECTED_BLOCK_CLASS,
70
72
  readMergeQueueState,
73
+ readQueueEjection,
71
74
  } from '../../merge-queue.js';
72
75
  import { readProbeRunEvidence } from '../../required-checks.js';
73
76
  import { NEXT_COMMANDS } from '../../story-deliver-terminal.js';
@@ -275,6 +278,7 @@ export async function readPrWaitProbe({
275
278
  redHeadRuns: deriveRedHeadRuns(view?.statusCheckRollup),
276
279
  checkStates: deriveCheckStates(view?.statusCheckRollup),
277
280
  headSha: readString(view?.headRefOid),
281
+ prNodeId: readString(view?.id),
278
282
  autoMergeArmed: readAutoMergeArmed(view),
279
283
  };
280
284
  } catch (err) {
@@ -406,16 +410,10 @@ function disarmedOn(redRecord) {
406
410
  * @param {{ storyId: number, prNumber: number|null, blockClass: string }} args
407
411
  * @returns {string}
408
412
  */
409
- function unlandedRemedy({ storyId, prNumber, blockClass, redRecord }) {
410
- if (blockClass === CHECKS_FAILED_CLASS) {
411
- return checksFailedRemedy({ storyId, prNumber, redRecord });
412
- }
413
- if (
414
- blockClass === ADVISORY_GATE_INCONCLUSIVE_CLASS ||
415
- blockClass === ADVISORY_GATE_RED_CLASS
416
- ) {
417
- return advisoryGateRemedy({ storyId, blockClass, redRecord });
418
- }
413
+ function unlandedRemedy(args) {
414
+ const remedy = REMEDY_OF_CLASS[args.blockClass];
415
+ if (remedy) return remedy(args);
416
+ const { storyId } = args;
419
417
  return (
420
418
  `Resolve the underlying condition (branch protection, required checks, ` +
421
419
  `or a manual merge), then resume the land:\n\n` +
@@ -423,6 +421,13 @@ function unlandedRemedy({ storyId, prNumber, blockClass, redRecord }) {
423
421
  );
424
422
  }
425
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
+
426
431
  /**
427
432
  * States what the red handling actually did — never claims a disarm or a
428
433
  * digest that did not happen — then names both ci-remediation routes.
@@ -438,11 +443,8 @@ function checksFailedRemedy({ storyId, prNumber, redRecord }) {
438
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.'
439
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.`;
440
445
  const watch = NEXT_COMMANDS.watchCi(storyId, prNumber);
441
- const digestLine = redRecord?.digestPaths
442
- ? `CI digest (run link + failure signature): \`${redRecord.digestPaths.jsonPath}\`.`
443
- : `⚠️ No CI digest was written (${redRecord?.digestError ?? 'no Story scope'}); \`${watch}\` rewrites it.`;
444
446
  return (
445
- `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` +
446
448
  `Per \`.agents/rules/ci-remediation.md\`, either fix the failure and push a new commit on ` +
447
449
  `\`story-${storyId}\` (re-running the failed job is forbidden), or — when the root cause is ` +
448
450
  `outside this delivery — file it:\n\n` +
@@ -452,6 +454,27 @@ function checksFailedRemedy({ storyId, prNumber, redRecord }) {
452
454
  );
453
455
  }
454
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
+
455
478
  function formatUnlandedFriction({
456
479
  storyId,
457
480
  prNumber,
@@ -852,7 +875,7 @@ function queuedExhaustionVerdict(probe, cumulativeMs) {
852
875
  *
853
876
  * @returns {Promise<object>} the `recordRequiredRed` outcome.
854
877
  */
855
- async function recordRed(ctx, probe, failures) {
878
+ async function recordRed(ctx, probe, failures, run = null) {
856
879
  const {
857
880
  storyId,
858
881
  prNumber,
@@ -873,6 +896,7 @@ async function recordRed(ctx, probe, failures) {
873
896
  cwd,
874
897
  headSha: probe?.headSha ?? null,
875
898
  disarmFn: () => disarmAutoMergeFn({ prNumber, gh, progress }),
899
+ ...pinnedRun(run),
876
900
  });
877
901
  if (record.digestPaths) {
878
902
  progress?.(
@@ -896,6 +920,13 @@ async function recordRed(ctx, probe, failures) {
896
920
  }
897
921
  }
898
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
+
899
930
  /** Classify, emit `merge.unlanded`, post friction, block — all best-effort. */
900
931
  async function blockOnUnlanded({
901
932
  storyId,
@@ -1290,6 +1321,31 @@ async function settleChecksFailed(ctx, decision, probe) {
1290
1321
  });
1291
1322
  }
1292
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
+
1293
1349
  function settleUnrecognisedChecks(ctx, decision, probe) {
1294
1350
  return blockWith(ctx, {
1295
1351
  prProbe: probe,
@@ -1367,9 +1423,8 @@ async function recoverOpenPr(ctx, decision, probe) {
1367
1423
  if (advisory) {
1368
1424
  return { state: decision.state, outcome: await blockWith(ctx, advisory) };
1369
1425
  }
1370
- const landed = await maybeMergeOnGreen(ctx, decision, probe);
1371
- if (landed) return { state: decision.state, outcome: landed };
1372
- await maybeRearmPr(ctx, probe);
1426
+ const settled = await settleOpenPr(ctx, decision, probe);
1427
+ if (settled) return { state: decision.state, outcome: settled };
1373
1428
  const updated = await maybeUpdateBehindPr({
1374
1429
  probe,
1375
1430
  prNumber: ctx.prNumber,
@@ -1385,6 +1440,57 @@ async function recoverOpenPr(ctx, decision, probe) {
1385
1440
  return { state, outcome: null };
1386
1441
  }
1387
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
+
1388
1494
  /**
1389
1495
  * Close owns the merge when the CCR route would not arm it: the arm said so,
1390
1496
  * or (a `--wait` resume, which has no arm outcome) the PR transport is REST
@@ -1597,6 +1703,8 @@ function neverArmedOverride(autoMergeReason, advisoryGate) {
1597
1703
  * @param {Function} [args.recordRequiredRedFn] The shared first-red handling (disarm + CI digest).
1598
1704
  * @param {Function} [args.mergeOnGreenFn] The merge-on-green squash-merge (`auto-merge.js#mergeOnGreen`).
1599
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.
1600
1708
  * @param {object} [args.recoverySeams] DIRTY-sync / re-arm seams (`mergeWaitRecoverySeams`).
1601
1709
  * @param {(ms: number) => Promise<void>} [args.sleepFn]
1602
1710
  * @param {() => number} [args.nowMsFn]
@@ -1618,6 +1726,8 @@ export async function runConfirmMergePhase({
1618
1726
  recordRequiredRedFn = defaultRecordRequiredRed,
1619
1727
  mergeOnGreenFn = mergeOnGreen,
1620
1728
  readMergeQueueStateFn = readMergeQueueState,
1729
+ readQueueEjectionFn = readQueueEjection,
1730
+ releaseVetoFn = releaseVetoHolds,
1621
1731
  sleepFn = defaultSleep,
1622
1732
  nowMsFn = Date.now,
1623
1733
  ghTimeoutMs = MERGE_WAIT_GH_TIMEOUT_MS,
@@ -1667,6 +1777,9 @@ export async function runConfirmMergePhase({
1667
1777
  recordRequiredRedFn,
1668
1778
  mergeOnGreenFn,
1669
1779
  readMergeQueueStateFn,
1780
+ readQueueEjectionFn,
1781
+ releaseVetoFn,
1782
+ ejectionRuns: new Set(),
1670
1783
  nowMsFn,
1671
1784
  ghTimeoutMs,
1672
1785
  waitGh: args.injectedGh ?? defaultGh,
@@ -38,6 +38,7 @@ import {
38
38
  import { isBiomeNoFilesProcessed } from '../close-validation/process.js';
39
39
  import { applyChangedFileScope } from '../close-validation/runner.js';
40
40
  import { skipBranchDeposit } from '../close-validation/skip-branch-test.js';
41
+ import { substituteChangedSince } from '../close-validation/test-delta.js';
41
42
  import { getBaselines } from '../config/baselines.js';
42
43
  import { getPostSeatChecks } from '../config/handoff.js';
43
44
  import { getQuality } from '../config/quality.js';
@@ -738,6 +739,27 @@ function depositorArgv(ctx) {
738
739
  return { args, label: deposit.label };
739
740
  }
740
741
 
742
+ /**
743
+ * The `ci` posture's changed-tests guard: `testChanged` keyed on the
744
+ * `origin/<base>` merge-base, outside the full-suite lock, bounded by
745
+ * `coverage.timeoutMs`.
746
+ */
747
+ function runChangedTests(ctx, testChanged, signal) {
748
+ const base = `origin/${ctx.baseBranch}`;
749
+ const since = gitLine(ctx.git, ctx.cwd, ['merge-base', 'HEAD', base]) || base;
750
+ const { cmd, args, env } = substituteChangedSince(testChanged, since);
751
+ const timeoutMs = getQuality(ctx.config).coverage.timeoutMs;
752
+ const bounded = { ...ctx, stream: { ...ctx.stream, timeoutMs } };
753
+ return runLogged(
754
+ bounded,
755
+ 'changed-tests',
756
+ cmd,
757
+ args,
758
+ { ...ctx.env, ...env },
759
+ signal,
760
+ );
761
+ }
762
+
741
763
  /** @param {object} ctx @param {AbortSignal} signal @returns {Promise<StepResult>} */
742
764
  async function creditedRun(ctx, signal) {
743
765
  const name = 'credited-run';
@@ -748,7 +770,8 @@ async function creditedRun(ctx, signal) {
748
770
  { depositor: ctx.depositor },
749
771
  );
750
772
  }
751
- const ciOwned = settleSuiteOfRecord(ctx, name);
773
+ const guard = { run: (cmd) => runChangedTests(ctx, cmd, signal), signal };
774
+ const ciOwned = await settleSuiteOfRecord(ctx, name, guard);
752
775
  if (ciOwned) return ciOwned;
753
776
  const capture = ctx.depositor === 'coverage-capture';
754
777
  const { args, label } = depositorArgv(ctx);
@@ -374,6 +374,23 @@ in the foreground, now bounded to the gates plus the ~60s probe, and the long
374
374
  merge wait moves into the background confirm that carries the explicit
375
375
  timeout. A local session need not pass the flag.
376
376
 
377
+ **A merge-queue ejection is settled from one probe.** When a close-armed PR
378
+ reads out of the queue with no auto-merge request (GraphQL only — over REST
379
+ queue membership is unreadable and the wait is unchanged), the wait reads
380
+ the `merge_group` run that ejected it, on the
381
+ `gh-readonly-queue/<base>/pr-<n>-<parentSha>` ref, and the run of the entry
382
+ it was built on. An **inherited** ejection (the run was cancelled, or the
383
+ entry ahead failed or was cancelled) re-arms once per ejecting run, at most
384
+ three times per head; the fourth counts as the PR's own. An **own** ejection
385
+ blocks at once with block class `queue-ejected`: the CI digest is written
386
+ from the queue run (run link, failed jobs, failure signature) and nothing is
387
+ re-armed. To resume, fix the failure on `story-<id>` in the Story worktree,
388
+ commit, re-run `story-handoff.js` to push the new head, then run the
389
+ friction comment's resume command. An unreadable ejecting run keeps today's
390
+ one blind re-arm per head. The ejection path never re-arms a PR close did
391
+ not arm, under `ci.autoMerge: strict`, or one `orchestrate.releaseVeto`
392
+ holds.
393
+
377
394
  ## Close-out audit {#closeout-audit}
378
395
 
379
396
  `deliver-recover.js` names the next command for one stranded Story;
package/docs/CHANGELOG.md CHANGED
@@ -15,6 +15,14 @@ All notable changes to this project will be documented in this file.
15
15
  -->
16
16
  <!-- markdownlint-disable-file MD004 MD012 MD037 -->
17
17
 
18
+ ## [2.120.0](https://github.com/dsj1984/mandrel/compare/mandrel-v2.119.0...mandrel-v2.120.0) (2026-11-12)
19
+
20
+
21
+ ### Added
22
+
23
+ * merge wait settles a merge-queue ejection: re-queue an inherited failure, hand back an own failure with the queue run's digest ([#6060](https://github.com/dsj1984/mandrel/issues/6060)) ([#6064](https://github.com/dsj1984/mandrel/issues/6064)) ([d6efd90](https://github.com/dsj1984/mandrel/commit/d6efd90a332636761bed253dfe726e9342562c43))
24
+ * under suiteOfRecord ci the handoff runs the changed-tests command as a guard, and doctor reports a suite run in both places ([#6061](https://github.com/dsj1984/mandrel/issues/6061)) ([#6062](https://github.com/dsj1984/mandrel/issues/6062)) ([1ecbfb9](https://github.com/dsj1984/mandrel/commit/1ecbfb9d377523335a8ae4d6d4ebcea0f7da383e))
25
+
18
26
  ## [2.119.0](https://github.com/dsj1984/mandrel/compare/mandrel-v2.118.0...mandrel-v2.119.0) (2026-11-11)
19
27
 
20
28
 
@@ -0,0 +1,42 @@
1
+ // lib/cli/doctor-checks/suite-ownership.js — Doctor check: suite-ownership.
2
+
3
+ import fs from 'node:fs';
4
+ import { readEffectiveAgentrc } from './effective-agentrc.js';
5
+
6
+ const KEY = 'delivery.quality.gates.coverage';
7
+
8
+ const isSet = (value) => typeof value === 'string' && value.trim().length > 0;
9
+
10
+ /**
11
+ * Advisory: who runs the suite before a PR. Reports a suite owned by both the
12
+ * handoff and CI (`ciRatchetCheck` set, posture local), and a `ci` posture
13
+ * with no `project.commands.testChanged` guard. Never fails.
14
+ *
15
+ * @param {{ projectRoot?: string, cwd?: () => string, fsImpl?: { readFileSync: Function, existsSync: Function } }} [opts]
16
+ * @returns {Promise<{ ok: true, detail: string }>}
17
+ */
18
+ export async function runSuiteOwnership({
19
+ projectRoot,
20
+ cwd,
21
+ fsImpl = fs,
22
+ } = {}) {
23
+ const root = projectRoot ?? (cwd ?? (() => process.cwd()))();
24
+ const agentrc = readEffectiveAgentrc(root, fsImpl);
25
+ const gate = agentrc?.delivery?.quality?.gates?.coverage ?? {};
26
+ const guard = agentrc?.project?.commands?.testChanged;
27
+ if (gate.suiteOfRecord === 'ci') {
28
+ return {
29
+ ok: true,
30
+ detail: isSet(guard)
31
+ ? `CI owns the suite; the handoff runs \`${guard.trim()}\` (project.commands.testChanged) as a changed-tests guard`
32
+ : 'CI owns the suite and no test runs before the PR — set project.commands.testChanged to run a changed-tests guard at the handoff',
33
+ };
34
+ }
35
+ if (isSet(gate.ciRatchetCheck)) {
36
+ return {
37
+ ok: true,
38
+ detail: `the suite is owned by both the handoff and CI ("${gate.ciRatchetCheck}") — set ${KEY}.suiteOfRecord: "ci" to make CI its owner, plus project.commands.testChanged for a changed-tests guard`,
39
+ };
40
+ }
41
+ return { ok: true, detail: 'the handoff owns the suite' };
42
+ }
@@ -27,6 +27,7 @@ import {
27
27
  runRuntimeDeps,
28
28
  } from './doctor-checks/runtime-deps.js';
29
29
  import { spawn } from './doctor-checks/spawn.js';
30
+ import { runSuiteOwnership } from './doctor-checks/suite-ownership.js';
30
31
  import {
31
32
  runAgentsInSync,
32
33
  runCommandsInSync,
@@ -53,6 +54,8 @@ export {
53
54
  };
54
55
 
55
56
  /** `advisory: true` marks a check whose `run()` never fails. */
57
+ const advisory = (name, run) => ({ name, advisory: true, run });
58
+
56
59
  export const registry = [
57
60
  {
58
61
  name: 'node-version',
@@ -129,20 +132,13 @@ export const registry = [
129
132
  name: 'pin-current',
130
133
  run: (opts) => runPinCurrent(opts),
131
134
  },
132
- {
133
- name: 'version-current',
134
- advisory: true,
135
- run: (opts) => runVersionCurrent(opts),
136
- },
137
- {
138
- name: 'test-credit-path',
139
- advisory: true,
140
- run: (opts) => runTestCreditPath(opts),
141
- },
135
+ advisory('version-current', (opts) => runVersionCurrent(opts)),
136
+ advisory('test-credit-path', (opts) => runTestCreditPath(opts)),
142
137
  {
143
138
  name: 'coverage-ratchet',
144
139
  run: (opts) => runCoverageRatchet(opts),
145
140
  },
141
+ advisory('suite-ownership', (opts) => runSuiteOwnership(opts)),
146
142
  ];
147
143
 
148
144
  export default registry;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mandrel",
3
- "version": "2.119.0",
3
+ "version": "2.120.0",
4
4
  "description": "Claude Code-first opinionated workflow framework: instructions, skills, rules, and SDLC workflows that govern AI coding assistants.",
5
5
  "files": [
6
6
  ".agents/",