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
@@ -229,7 +229,8 @@
229
229
  "maxBudgetSeconds": 3600
230
230
  },
231
231
  "close": {
232
- "baseSync": "always"
232
+ "baseSync": "always",
233
+ "revalidateAfterBaseSync": "full"
233
234
  },
234
235
  "codeReview": {
235
236
  "providers": [
@@ -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`). |
@@ -146,7 +146,7 @@ Everything `/mandrel-deliver` and `single-story-close` consume: worktree isolati
146
146
  | `execution.fullSuiteLock` | No | `boolean` | `true` | Serialize full-suite spawns (`npm test` / the coverage gate's `captureScript`) behind a repository-level advisory lock shared by every worktree, so two concurrent deliveries do not run two suites against the same cores (see `capacity` / `workloads` for declared runs that may overlap). The lock queues, it never overlaps: a wait that expires with a live holder spawns nothing and exits 75 (resumable), naming the holder. A dead or non-heartbeating holder is taken over, and a broken lockfile proceeds unserialized, so the lock can never fail a delivery. Set false — or export `MANDREL_FULL_SUITE_LOCK=0` for one invocation — to disable. |
147
147
  | `execution.capacity` | No | `integer` | — | Story #5668. The admission budget, in weight units (CPU workers), shared by every suite spawn across this repository's worktrees and sessions — runs in other repositories on the host are not counted. Unset → the host's `os.availableParallelism()`. A declared workload is admitted while the live weights plus its own fit, first-in-first-out: nothing overtakes an earlier live waiter, so a queued full suite is never starved — except a `workloads[].backfill` run, which may pass earlier declared waiters it fits beside, only while the oldest has waited under 300 s. |
148
148
  | `execution.workloads[]` | No | `array<object>` | `[]` | Story #5668. Suite commands declared safe to run alongside others. A spawn whose argv (whitespace-normalized) EXACTLY equals `command` takes that `weight` and `resources`; anything else — and every spawn when this list is empty, the default — runs exclusively (full capacity, today's serialization). Isolation is never inferred from a flag or prefix; a weight comes from the entry, or from its `tiers` as sized by its own `sizeCommand`. `weight` must count the run's nested worker pool (`--workers 4` → 4), and a full suite needs its own entry before anything can overlap it. Two runs naming a common `resources` entry (a database fixture, a shared coverage file) never overlap; worktree-local outputs need none. A weight above `capacity` refuses the run with exit 78 — nothing spawns, no credit is recorded. An expired wait still exits 75, resumably. Scheduling never changes a run's credit identity. `MANDREL_FULL_SUITE_LOCK=0` (one invocation) or `fullSuiteLock: false` turns admission off entirely; reach for the env hatch only when you have checked the runs share nothing. Each item has: command, weight, resources, tiers, sizeCommand, backfill. |
149
- | `execution.preflightConcurrency` | No | `integer` | `1` | Story #5997. The most handoff preflight checks that may run at once. `1` (the default) is the serial preflight. Above 1, typecheck, lint and format (close's independent gates) may also run in up to N − 1 extra lanes, each admitted through suite admission with no wait under close's argv for that gate; a miss hands the check back to the serial lane. Set it per host in `.agentrc.local.json`: whether a host can afford a second CPU-heavy check is a per-host fact. |
149
+ | `execution.preflightConcurrency` | No | `integer` | `1` | Story #5997. The most handoff preflight checks that may run at once. `1` (the default) is the serial preflight. Above 1, typecheck, lint and format (close's independent gates) may also run in up to N − 1 extra lanes, each admitted through suite admission with no wait under close's argv for that gate; a miss hands the check back to the serial lane. When lanes are admitted (and not under `--report-all`), the handoff's duplication re-score scan also overlaps preflight instead of running before it: a moved row is committed at a join before the independent baseline compare runs, and the preflight credits re-key onto that commit. Set it per host in `.agentrc.local.json`: whether a host can afford a second CPU-heavy check is a per-host fact. |
150
150
  | `docsFreshness` | No | `object` | — | Documentation-freshness scope: the files a change of consequence is expected to touch. Read by the audit-documentation lens to seed its target set; no delivery gate enforces it. |
151
151
  | `docsFreshness.paths` | No | `array<string>` | `["README.md"]` | Repo-relative documentation paths the audit-documentation lens adds to its target set. |
152
152
  | `tempRetention` | No | `object` | — | Story #4794. Auto-purge of spent temp artifacts once their Story lands. Classification is an allowlist: only the declared classes below are ever deleted, so unrecognized files under tempRoot are reported with their size and left alone (`/clean-temp` is the operator path for them). signals.ndjson is never purged by any path. |
@@ -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`. |
@@ -256,8 +256,11 @@ Everything `/mandrel-deliver` and `single-story-close` consume: worktree isolati
256
256
  | `mergeWatch.mode` | No | `"sync"` \| `"async"` | — | Close-time merge-wait posture (Story #4698). `sync` (default) keeps the in-close foreground merge wait unchanged. `async` caps the per-invocation wait to a short ~60s probe window — long enough to catch an instant merge and, via the head-anchored required-check predicate, an instantly-red required check — then returns the resumable `pending` terminal (exit 3) with a `nextCommand`. Opt in when slow CI makes the foreground wait routinely expire: the worker launches `nextCommand` in the background instead of burning the host tool slot polling. `maxBudgetSeconds` (the cumulative give-up) is unchanged. |
257
257
  | `mergeWatch.maxWaitSeconds` | No | `integer` | — | Per-invocation merge-wait bound (seconds). Default 300 (5 minutes) — chosen to fit inside a single host tool invocation (~10 min ceiling) alongside the close gates that precede the wait. Expiry yields `pending` (exit 3), never a block. Headless callers with no host ceiling raise this to land in one block. |
258
258
  | `mergeWatch.maxBudgetSeconds` | No | `integer` | `3600` | Cumulative wall-clock budget (seconds) across merge-wait resumes, anchored at the later of the PR's createdAt and its latest auto-merge arm (`autoMergeRequest.enabledAt`), so a re-close that re-arms starts a fresh budget; without an arm time it falls back to createdAt, then to the invocation start. Default 3600 (60 minutes). Exhausting this classifies the block and transitions the Story to agent::blocked. |
259
- | `close` | No | `object` | — | Close-time posture (Story #5954). `baseSync` decides whether close and a handoff re-run merge `origin/<baseBranch>` before validating. |
259
+ | `close` | No | `object` | — | Close-time posture (Story #5954). `baseSync` decides whether close and a handoff re-run merge `origin/<baseBranch>` before validating; the `revalidate*` keys decide what close re-runs after that merge. |
260
260
  | `close.baseSync` | No | `"always"` \| `"on-conflict"` | `"always"` | `always` (default) merges `origin/<baseBranch>` on every close, as before. `on-conflict` first runs a conflict-only probe and skips the merge when it is conflict-free (`git merge-tree --write-tree`) and the incoming and Story paths are disjoint (raw paths, `baselines/` and renames included); `check-baselines` then compares against the merge-base and the terminal envelope's `baseSync` says why. Any other probe answer merges as today. A handoff applies the probe only on a re-run. Opt in only behind a merge queue that re-tests the merged tree and with no up-to-date-branch requirement: a semantic conflict the probe cannot see surfaces in CI, and coverage is measured on the pre-merge tree. |
261
+ | `close.revalidateAfterBaseSync` | No | `"full"` \| `"ci"` | `"full"` | What close re-runs after base-sync merged `origin/<baseBranch>`. `full` (default) re-runs every gate, as before. `ci` defers `typecheck`, `lint` and the coverage capture to the CI checks named in `revalidateCiChecks` — never spawned, reported `deferred`, the capture writing `Coverage-deferred: base-sync-ci` — but only for a conflict-free merge commit whose pre-sync head carries `typecheck` and `lint` pass evidence, with no incoming path under `revalidateAlwaysPaths` and, when the capture is registered, a `coverage.ciRatchetCheck`. Any other close re-runs everything and the terminal envelope's `revalidation` names why. |
262
+ | `close.revalidateCiChecks` | No | `array<string>` | — | The CI check names (check-run or status context) a `revalidateAfterBaseSync: "ci"` deferral leans on. Absent or empty, the mode falls back to a full re-run. |
263
+ | `close.revalidateAlwaysPaths` | No | `array<string>` | — | Globs (picomatch, dotfiles included) for whole-repo invariants: a base merge bringing in any matching path always re-runs every gate under `revalidateAfterBaseSync: "ci"`. |
261
264
  | `codeReview` | No | `object` | — | Review-provider chain and on-branch remediation threshold for the /mandrel-deliver code-review ceremony. |
262
265
  | `codeReview.providers[]` | No | `array<object>` | `[{"name":"native"},{"name":"llm-review","scopes":["story"],"optional":true}]` | Review-provider chain (Story #2871). When unset or empty, falls back to this default: `native` (maintainability scoring of the changed files) then an optional story-scoped `llm-review` — the first available of `code-review` (a `claude --print` bug review, at the effort `effortByDepth` maps its depth to, whose every finding is critical and halts close before auto-merge) and `codex` (`codex exec`), so a host with both CLIs runs one LLM review and a host with neither skips it. Pin `code-review` or `codex` to choose the CLI. `security-review` and `ultrareview` are opt-in. The orchestrator iterates inline entries in declaration order and merges their Finding[] before posting one structured comment; manual-prompt entries (e.g. ultrareview) contribute a trailing 'Manual review suggestions' section. Selecting an adapter whose probe fails hard-fails at factory construction unless declared `optional: true` in the chain. Each item has: name, scopes, optional, manualPrompt, when. |
263
266
  | `codeReview.autoFixSeverity` | No | `"high"` \| `"medium"` | `"medium"` | Severity threshold for on-branch remediation in /mandrel-deliver Phase 5 (code-review). `medium` (default) routes 🔴/🟠/🟡 findings into the host-LLM focused-fix routing (Mediums batched per lens: one commit per lens, a single validation + rescan at the end) while 🟢 suggestions still graduate to follow-up issues; `high` reproduces the pre-4399 Critical/High-only routing. Hard cutover — no back-compat flag. |
@@ -669,6 +672,20 @@ place.
669
672
  depositor; under the `test` depositor it changes nothing. It needs
670
673
  `ciRatchetCheck`. Without one the handoff settles `blocked`
671
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.
685
+ - **`delivery.close.revalidateAfterBaseSync: "ci"`.** After a conflict-free
686
+ base merge, close defers the capture (with `typecheck` and `lint`) to the
687
+ checks in `delivery.close.revalidateCiChecks`, reason `base-sync-ci`. It
688
+ needs `ciRatchetCheck` too; without one close re-runs every gate.
672
689
  - **What a deferral does.** The handoff settles `ready` with
673
690
  `coverage: { status: "deferred", reason, policy }` (`policy` is
674
691
  `defer-to-ci` or `suite-of-record`) and records no credit. It skips the CRAP
@@ -678,8 +695,8 @@ place.
678
695
  (`coverage-deferred-ci`), then opens the PR and arms auto-merge. Every other
679
696
  gate still runs.
680
697
  - **The marker.** A deferred PR's body carries the prose line and, directly
681
- beneath it, the key line `Coverage-deferred: <reason>` (`over-budget` or
682
- `suite-of-record-ci`). Both tokens are a stable contract that CI workflows
698
+ beneath it, the key line `Coverage-deferred: <reason>` (`over-budget`,
699
+ `suite-of-record-ci` or `base-sync-ci`). Both tokens are a stable contract that CI workflows
683
700
  and confirm-merge route on.
684
701
  - **The hand-back: `coverage-ratchet.js`.** The CI job named by
685
702
  `ciRatchetCheck` runs it on the merge ref, after CI has produced and merged
@@ -711,7 +728,11 @@ place.
711
728
  - **Doctor.** `mandrel doctor`'s `coverage-ratchet` check reads
712
729
  `.agentrc.json` with `.agentrc.local.json` over it. It fails when
713
730
  `suiteOfRecord` is `ci`, or `onOverBudget` is `defer-to-ci`, and
714
- `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.
715
736
  - **Nothing sticks.** A deferral writes no artifact, stamp or credit, so a
716
737
  later run on a bigger host captures, seats and scores as usual.
717
738
  - **A timeout is not a deferral.** Exit 124 can hide a hang, so it keeps its
@@ -1107,7 +1128,9 @@ your own token. Close detects that during `init` and runs the pull-request
1107
1128
  surface over repo-scoped REST instead: it opens the PR, arms auto-merge
1108
1129
  through the proxy's route or, when that route refuses, squash-merges the PR
1109
1130
  itself once it is CLEAN with green checks, and confirms the land. A base
1110
- branch behind a merge queue still needs a session that reaches GraphQL.
1131
+ branch behind a merge queue is armed through the same route, and GitHub
1132
+ enqueues the PR once it is green; when that route refuses, close blocks
1133
+ instead of merging around the queue.
1111
1134
  Projects v2 is GraphQL-only, so board Status never syncs from a cloud
1112
1135
  session. Labels stay authoritative, and each skipped Status flip is reported
1113
1136
  as a warning.
@@ -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"],
@@ -493,7 +493,7 @@
493
493
  "type": "integer",
494
494
  "minimum": 1,
495
495
  "default": 1,
496
- "description": "Story #5997. The most handoff preflight checks that may run at once. `1` (the default) is the serial preflight. Above 1, typecheck, lint and format (close's independent gates) may also run in up to N − 1 extra lanes, each admitted through suite admission with no wait under close's argv for that gate; a miss hands the check back to the serial lane. Set it per host in `.agentrc.local.json`: whether a host can afford a second CPU-heavy check is a per-host fact."
496
+ "description": "Story #5997. The most handoff preflight checks that may run at once. `1` (the default) is the serial preflight. Above 1, typecheck, lint and format (close's independent gates) may also run in up to N − 1 extra lanes, each admitted through suite admission with no wait under close's argv for that gate; a miss hands the check back to the serial lane. When lanes are admitted (and not under `--report-all`), the handoff's duplication re-score scan also overlaps preflight instead of running before it: a moved row is committed at a join before the independent baseline compare runs, and the preflight credits re-key onto that commit. Set it per host in `.agentrc.local.json`: whether a host can afford a second CPU-heavy check is a per-host fact."
497
497
  }
498
498
  },
499
499
  "additionalProperties": false
@@ -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": {
@@ -1429,13 +1429,36 @@
1429
1429
  },
1430
1430
  "close": {
1431
1431
  "type": "object",
1432
- "description": "Close-time posture (Story #5954). `baseSync` decides whether close and a handoff re-run merge `origin/<baseBranch>` before validating.",
1432
+ "description": "Close-time posture (Story #5954). `baseSync` decides whether close and a handoff re-run merge `origin/<baseBranch>` before validating; the `revalidate*` keys decide what close re-runs after that merge.",
1433
1433
  "properties": {
1434
1434
  "baseSync": {
1435
1435
  "type": "string",
1436
1436
  "enum": ["always", "on-conflict"],
1437
1437
  "description": "`always` (default) merges `origin/<baseBranch>` on every close, as before. `on-conflict` first runs a conflict-only probe and skips the merge when it is conflict-free (`git merge-tree --write-tree`) and the incoming and Story paths are disjoint (raw paths, `baselines/` and renames included); `check-baselines` then compares against the merge-base and the terminal envelope's `baseSync` says why. Any other probe answer merges as today. A handoff applies the probe only on a re-run. Opt in only behind a merge queue that re-tests the merged tree and with no up-to-date-branch requirement: a semantic conflict the probe cannot see surfaces in CI, and coverage is measured on the pre-merge tree.",
1438
1438
  "default": "always"
1439
+ },
1440
+ "revalidateAfterBaseSync": {
1441
+ "type": "string",
1442
+ "enum": ["full", "ci"],
1443
+ "description": "What close re-runs after base-sync merged `origin/<baseBranch>`. `full` (default) re-runs every gate, as before. `ci` defers `typecheck`, `lint` and the coverage capture to the CI checks named in `revalidateCiChecks` — never spawned, reported `deferred`, the capture writing `Coverage-deferred: base-sync-ci` — but only for a conflict-free merge commit whose pre-sync head carries `typecheck` and `lint` pass evidence, with no incoming path under `revalidateAlwaysPaths` and, when the capture is registered, a `coverage.ciRatchetCheck`. Any other close re-runs everything and the terminal envelope's `revalidation` names why.",
1444
+ "default": "full"
1445
+ },
1446
+ "revalidateCiChecks": {
1447
+ "type": "array",
1448
+ "items": {
1449
+ "type": "string",
1450
+ "minLength": 1
1451
+ },
1452
+ "uniqueItems": true,
1453
+ "description": "The CI check names (check-run or status context) a `revalidateAfterBaseSync: \"ci\"` deferral leans on. Absent or empty, the mode falls back to a full re-run."
1454
+ },
1455
+ "revalidateAlwaysPaths": {
1456
+ "type": "array",
1457
+ "items": {
1458
+ "type": "string",
1459
+ "minLength": 1
1460
+ },
1461
+ "description": "Globs (picomatch, dotfiles included) for whole-repo invariants: a base merge bringing in any matching path always re-runs every gate under `revalidateAfterBaseSync: \"ci\"`."
1439
1462
  }
1440
1463
  },
1441
1464
  "additionalProperties": false
@@ -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 },
@@ -77,7 +77,7 @@
77
77
  },
78
78
  "gates": {
79
79
  "type": "object",
80
- "description": "Outcome of each close gate this invocation was responsible for. A gate the run skipped (--skip-validation, or a phase it never reached) reports \"skipped\" rather than being omitted, so a missing gate is never mistaken for a passing one. \"overridden\" is distinct from both: the gate ran, it FAILED, and an operator authorized delivery anyway via --override-review-block with a recorded reason. Reporting that as \"passed\" would erase the one fact a reader of this envelope most needs, and reporting it as \"skipped\" would claim the gate never ran. codeReview alone also reports \"unreviewed\" (a review produced no verdict at all: CLI not logged in, out of quota, unparseable output, a skipped optional reviewer, an unresolvable base), \"partial\" (part of the diff went unreviewed) and \"degraded\" (the diff was reviewed with reduced context only), with precedence overridden > unreviewed > partial > degraded > passed. All three are reported, not blocking, unless delivery.codeReview.onNoVerdict is \"block\", which halts on unreviewed or partial. \"deferred\" (coverage-capture only, Story #5949) means the capture script declared its slice over this host's budget (exit 76) under coverage.onOverBudget: defer-to-ci, or that coverage.suiteOfRecord: ci (Story #5955) deferred it before anything spawned — no suite ran, the coverage-reading gates report \"skipped\", and CI owns the run.",
80
+ "description": "Outcome of each close gate this invocation was responsible for. A gate the run skipped (--skip-validation, or a phase it never reached) reports \"skipped\" rather than being omitted, so a missing gate is never mistaken for a passing one. \"overridden\" is distinct from both: the gate ran, it FAILED, and an operator authorized delivery anyway via --override-review-block with a recorded reason. Reporting that as \"passed\" would erase the one fact a reader of this envelope most needs, and reporting it as \"skipped\" would claim the gate never ran. codeReview alone also reports \"unreviewed\" (a review produced no verdict at all: CLI not logged in, out of quota, unparseable output, a skipped optional reviewer, an unresolvable base), \"partial\" (part of the diff went unreviewed) and \"degraded\" (the diff was reviewed with reduced context only), with precedence overridden > unreviewed > partial > degraded > passed. All three are reported, not blocking, unless delivery.codeReview.onNoVerdict is \"block\", which halts on unreviewed or partial. \"deferred\" means CI owns the gate and nothing ran here: the coverage capture declared its slice over this host's budget (exit 76) under coverage.onOverBudget: defer-to-ci, or coverage.suiteOfRecord: ci (Story #5955) deferred it before anything spawned, or — for typecheck, lint and coverage-capture — delivery.close.revalidateAfterBaseSync: ci (Story #6050) handed them to CI after a conflict-free base merge. A deferred capture leaves the coverage-reading gates \"skipped\"; a typecheck or lint deferral alone does not.",
81
81
  "additionalProperties": {
82
82
  "type": "string",
83
83
  "enum": [
@@ -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
  },
@@ -305,6 +306,20 @@
305
306
  "enum": ["pushed", "skipped-already-at-head", null],
306
307
  "description": "Story #5967 — whether close's PR-opening push ran or was skipped because origin already held the Story-branch tip (read phaseDurations.push against it). Optional and additive; absent on every non-close envelope, null when the PR had already landed."
307
308
  },
309
+ "revalidation": {
310
+ "type": "object",
311
+ "description": "Story #6050 — what close re-ran after base-sync under delivery.close.revalidateAfterBaseSync: ci. applied is deferred-to-ci (reason conflict-free-merge; deferredGates names the gates handed to CI) or full (every gate re-ran; reason names the first failing rule: no-base-merge, conflict-resolved, always-revalidate-path, no-ci-checks, no-ci-ratchet-check, no-preflight-credit, with detail naming the path or gate). ciChecks are the configured revalidateCiChecks. Absent unless the mode is ci.",
312
+ "required": ["mode", "applied", "reason", "deferredGates", "ciChecks"],
313
+ "properties": {
314
+ "mode": { "const": "ci" },
315
+ "applied": { "enum": ["full", "deferred-to-ci"] },
316
+ "reason": { "type": "string", "minLength": 1 },
317
+ "detail": { "type": "string", "minLength": 1 },
318
+ "deferredGates": { "type": "array", "items": { "type": "string" } },
319
+ "ciChecks": { "type": "array", "items": { "type": "string" } }
320
+ },
321
+ "additionalProperties": false
322
+ },
308
323
  "timestamp": { "type": "string", "format": "date-time" }
309
324
  },
310
325
  "allOf": [
@@ -0,0 +1,17 @@
1
+ import path from 'node:path';
2
+ import { loadCoverage } from '../coverage-utils.js';
3
+ import { previewCoveragePath, previewNotRun } from './crap-preview-touched.js';
4
+
5
+ /** The coverage to score, or the not-run result; a named artifact skips the stamp check. */
6
+ export function resolvePreviewCoverage({
7
+ coverageArtifact,
8
+ crap,
9
+ cwd,
10
+ ...rest
11
+ }) {
12
+ if (coverageArtifact) return { coverage: loadCoverage(coverageArtifact) };
13
+ const notRun = previewNotRun({ crap, cwd, ...rest });
14
+ if (notRun) return { notRun };
15
+ const configured = path.resolve(cwd, previewCoveragePath(crap));
16
+ return { coverage: loadCoverage(configured) };
17
+ }
@@ -3,19 +3,16 @@
3
3
  * its baseline is loaded and judged compatible.
4
4
  */
5
5
 
6
- import path from 'node:path';
7
- import { loadCoverage } from '../coverage-utils.js';
8
6
  import {
9
7
  KERNEL_VERSION,
10
8
  resolveEscomplexVersion,
11
9
  scanAndScore,
12
10
  } from '../crap-utils.js';
13
11
  import { CYCLOMATIC_CEILING } from '../cyclomatic-ceiling.js';
12
+ import { resolvePreviewCoverage } from './crap-preview-coverage.js';
14
13
  import { resolveCrapPreviewIncremental } from './crap-preview-incremental.js';
15
14
  import {
16
15
  outsideDiffDiagnostics,
17
- previewCoveragePath,
18
- previewNotRun,
19
16
  resolveIsJudged,
20
17
  } from './crap-preview-touched.js';
21
18
  import { resolveCrapEnvOverrides } from './env-overrides.js';
@@ -72,6 +69,7 @@ export function listCyclomaticAdvisories(rows) {
72
69
  * baseline: { rows: object[] },
73
70
  * baseBranch?: string,
74
71
  * git?: Function,
72
+ * coverageArtifact?: string|null,
75
73
  * }} opts
76
74
  * @returns {Promise<{ exitCode: number, envelope: object }>}
77
75
  */
@@ -84,6 +82,7 @@ export async function computeCrapPreviewScan({
84
82
  baseline,
85
83
  baseBranch,
86
84
  git,
85
+ coverageArtifact = null,
87
86
  }) {
88
87
  const targetDirs = Array.isArray(crap.targetDirs) ? crap.targetDirs : [];
89
88
  const crapIgnoreGlobs = Array.isArray(crap.ignoreGlobs)
@@ -96,9 +95,15 @@ export async function computeCrapPreviewScan({
96
95
  crap,
97
96
  process.env,
98
97
  );
99
- const notRun = previewNotRun({ crap, targetDirs, cwd, scope, diffRef });
98
+ const { notRun, coverage } = resolvePreviewCoverage({
99
+ coverageArtifact,
100
+ crap,
101
+ targetDirs,
102
+ cwd,
103
+ scope,
104
+ diffRef,
105
+ });
100
106
  if (notRun) return notRun;
101
- const coverage = loadCoverage(path.resolve(cwd, previewCoveragePath(crap)));
102
107
  const incremental = resolveCrapPreviewIncremental({
103
108
  crap,
104
109
  diffRef,
@@ -215,6 +215,7 @@ export async function runCrapPreview({
215
215
  cwd = process.cwd(),
216
216
  changedSinceRef = null,
217
217
  staged = false,
218
+ coverageArtifact = null,
218
219
  } = {}) {
219
220
  const { scopeSet, scope, diffRef } = resolvePreviewScope({
220
221
  staged,
@@ -256,5 +257,6 @@ export async function runCrapPreview({
256
257
  diffRef,
257
258
  baseline,
258
259
  baseBranch: config?.project?.baseBranch,
260
+ coverageArtifact,
259
261
  });
260
262
  }
@@ -312,7 +312,8 @@ function requireScorer(kind, scorer, cwd) {
312
312
  * `fullScope` derives scope from `git diff baseRef..headRef`; `fullScope`
313
313
  * requires `scopeFiles: null`. `requireRowsForScopeFiles` fails loud when a
314
314
  * scoped file produced no row. A scoped refresh never rewrites an
315
- * `excludeWriteFiles` row.
315
+ * `excludeWriteFiles` row. `write: false` computes the envelope and reports
316
+ * `changed` without touching the file.
316
317
  *
317
318
  * @param {{
318
319
  * kind: 'maintainability' | 'crap' | 'coverage' | 'duplication' | 'bundle-size',
@@ -330,6 +331,7 @@ function requireScorer(kind, scorer, cwd) {
330
331
  * requiredScopeFilePredicate?: (file: string) => boolean,
331
332
  * extrasContext?: { cwd?: string, targetDirs?: string[] },
332
333
  * excludeWriteFiles?: string[],
334
+ * write?: boolean,
333
335
  * }} opts
334
336
  * @returns {Promise<{
335
337
  * kind: string,
@@ -337,6 +339,7 @@ function requireScorer(kind, scorer, cwd) {
337
339
  * scope: { mode: 'full' | 'diff' | 'explicit', ref?: string, files: string[] },
338
340
  * envelope: object | null,
339
341
  * wrote: boolean,
342
+ * changed?: boolean,
340
343
  * partners?: Record<string, string[]>,
341
344
  * ahead?: object,
342
345
  * }>} `partners`: each write-scope file's scored clone partners. `ahead` (with a null `envelope`): a narrower-than-full refresh left a
@@ -359,6 +362,7 @@ export async function refreshBaseline(opts = {}) {
359
362
  requiredScopeFilePredicate,
360
363
  extrasContext,
361
364
  excludeWriteFiles = [],
365
+ write = true,
362
366
  } = opts;
363
367
 
364
368
  validateOptions({ kind, scopeFiles, fullScope, writePath });
@@ -433,11 +437,13 @@ export async function refreshBaseline(opts = {}) {
433
437
 
434
438
  // The writer returns the prior object itself when nothing changed; skip the
435
439
  // write so on-disk bytes stay verbatim.
436
- let wrote = false;
437
- if (priorEnvelope === null || envelope !== priorEnvelope) {
438
- writeEnvelopeFile(writePath, envelope, { fsImpl: fs });
439
- wrote = true;
440
- }
440
+ const { changed, wrote } = persistEnvelope({
441
+ priorEnvelope,
442
+ envelope,
443
+ write,
444
+ writePath,
445
+ fs,
446
+ });
441
447
 
442
448
  return {
443
449
  kind,
@@ -449,10 +455,19 @@ export async function refreshBaseline(opts = {}) {
449
455
  },
450
456
  envelope,
451
457
  wrote,
458
+ changed,
452
459
  partners: partnersOf(canonicalRows, writeFiles),
453
460
  };
454
461
  }
455
462
 
463
+ /** Write a changed envelope unless `write` is off. */
464
+ function persistEnvelope({ priorEnvelope, envelope, write, writePath, fs }) {
465
+ const changed = priorEnvelope === null || envelope !== priorEnvelope;
466
+ const wrote = changed && write;
467
+ if (wrote) writeEnvelopeFile(writePath, envelope, { fsImpl: fs });
468
+ return { changed, wrote };
469
+ }
470
+
456
471
  /** Each listed file's scored clone partners; the envelope never stores them. */
457
472
  function partnersOf(rows, files) {
458
473
  const byPath = new Map(rows.map((row) => [row.path, row.partners]));
@@ -0,0 +1,152 @@
1
+ /**
2
+ * base-sync-revalidation.js — `delivery.close.revalidateAfterBaseSync: "ci"`:
3
+ * after a conflict-free base merge, hand typecheck, lint and the coverage
4
+ * capture to the named CI checks instead of re-running them. All or nothing;
5
+ * the first failing rule is the reason the close re-runs everything.
6
+ */
7
+
8
+ import picomatch from 'picomatch';
9
+ import { COVERAGE_DEFERRED_REASONS } from '../coverage-deferral.js';
10
+ import {
11
+ shouldSkip as defaultShouldSkip,
12
+ hashCommandConfig,
13
+ } from '../validation-evidence.js';
14
+
15
+ const DEFERRABLE_GATES = new Set(['typecheck', 'lint', 'coverage-capture']);
16
+ const PREFLIGHT_GATES = ['typecheck', 'lint'];
17
+
18
+ /** @param {object|null|undefined} config @returns {'full'|'ci'} */
19
+ function revalidationMode(config) {
20
+ return config?.delivery?.close?.revalidateAfterBaseSync === 'ci'
21
+ ? 'ci'
22
+ : 'full';
23
+ }
24
+
25
+ /** Registered and not decided-skipped when the list was built. */
26
+ const isLive = (gate) => !gate.skip;
27
+
28
+ /** Does `gate` carry pass evidence at `sha` under its own config hash? */
29
+ function hasPassAt(gate, { sha, storyId, cwd, evidenceCwd, shouldSkipImpl }) {
30
+ try {
31
+ const verdict = shouldSkipImpl(
32
+ {
33
+ storyId,
34
+ gateName: gate.name,
35
+ currentSha: sha,
36
+ configHash: hashCommandConfig({ cmd: gate.cmd, args: gate.args, cwd }),
37
+ },
38
+ { cwd: evidenceCwd ?? cwd, standalone: true },
39
+ );
40
+ return verdict?.skip === true;
41
+ } catch {
42
+ return false;
43
+ }
44
+ }
45
+
46
+ /** Rules 1–3: is this a conflict-free merge with no always-revalidate path? */
47
+ function mergeIneligibility(baseSync, alwaysPaths) {
48
+ const incoming = baseSync?.changedPaths ?? [];
49
+ if (baseSync?.kind !== 'merge-commit' || incoming.length === 0) {
50
+ return { reason: 'no-base-merge' };
51
+ }
52
+ if ((baseSync.resolvedBaselineFiles ?? []).length > 0) {
53
+ return { reason: 'conflict-resolved' };
54
+ }
55
+ if (alwaysPaths.length === 0) return null;
56
+ const matches = picomatch(alwaysPaths, { dot: true });
57
+ const hit = incoming.find((path) => matches(path));
58
+ return hit ? { reason: 'always-revalidate-path', detail: hit } : null;
59
+ }
60
+
61
+ /** Rules 4–6: does CI own the deferral and did handoff credit the pre-sync head? */
62
+ function ciIneligibility(gates, { ciChecks, config, ...probe }) {
63
+ if (ciChecks.length === 0) return { reason: 'no-ci-checks' };
64
+ const capture = gates.find(
65
+ (g) => g.name === 'coverage-capture' && isLive(g) && !g.suiteOfRecordCi,
66
+ );
67
+ if (capture && !config.delivery.quality?.gates?.coverage?.ciRatchetCheck) {
68
+ return { reason: 'no-ci-ratchet-check' };
69
+ }
70
+ for (const name of PREFLIGHT_GATES) {
71
+ const gate = gates.find((g) => g.name === name && isLive(g));
72
+ if (gate && !hasPassAt(gate, probe)) {
73
+ return { reason: 'no-preflight-credit', detail: name };
74
+ }
75
+ }
76
+ return null;
77
+ }
78
+
79
+ /**
80
+ * Mark typecheck, lint and the capture `ciDeferred` when every rule holds;
81
+ * otherwise return `gates` untouched with the failing rule as the reason.
82
+ * `revalidation` is `null` unless the mode is `ci`.
83
+ *
84
+ * @param {import('./gates.js').Gate[]} gates
85
+ * @param {{ baseSync: object|null, config: object|null, storyId: number, cwd: string, evidenceCwd?: string, log?: (m: string) => void, shouldSkipImpl?: typeof defaultShouldSkip }} opts
86
+ * @returns {{ gates: import('./gates.js').Gate[], revalidation: object|null }}
87
+ */
88
+ export function applyBaseSyncCiDeferral(
89
+ gates,
90
+ {
91
+ baseSync,
92
+ config,
93
+ storyId,
94
+ cwd,
95
+ evidenceCwd,
96
+ log,
97
+ shouldSkipImpl = defaultShouldSkip,
98
+ },
99
+ ) {
100
+ if (revalidationMode(config) !== 'ci') return { gates, revalidation: null };
101
+ const close = config.delivery.close;
102
+ const ciChecks = close.revalidateCiChecks ?? [];
103
+ const fallback =
104
+ mergeIneligibility(baseSync, close.revalidateAlwaysPaths ?? []) ??
105
+ ciIneligibility(gates, {
106
+ ciChecks,
107
+ config,
108
+ sha: baseSync.creditedCommit,
109
+ storyId,
110
+ cwd,
111
+ evidenceCwd,
112
+ shouldSkipImpl,
113
+ });
114
+ if (fallback) {
115
+ log?.(
116
+ `[close-validation] base-sync revalidation: running every gate (${fallback.reason}${fallback.detail ? `: ${fallback.detail}` : ''})`,
117
+ );
118
+ return {
119
+ gates,
120
+ revalidation: {
121
+ mode: 'ci',
122
+ applied: 'full',
123
+ ...fallback,
124
+ deferredGates: [],
125
+ ciChecks,
126
+ },
127
+ };
128
+ }
129
+ const deferredGates = [];
130
+ const ciDeferred = {
131
+ reason: COVERAGE_DEFERRED_REASONS.baseSyncCi,
132
+ checks: ciChecks,
133
+ };
134
+ const marked = gates.map((gate) => {
135
+ if (!(DEFERRABLE_GATES.has(gate.name) && isLive(gate))) return gate;
136
+ deferredGates.push(gate.name);
137
+ return gate.suiteOfRecordCi ? gate : { ...gate, ciDeferred };
138
+ });
139
+ log?.(
140
+ `[close-validation] base-sync revalidation: ${deferredGates.join(', ')} deferred to CI (${ciChecks.join(', ')})`,
141
+ );
142
+ return {
143
+ gates: marked,
144
+ revalidation: {
145
+ mode: 'ci',
146
+ applied: 'deferred-to-ci',
147
+ reason: 'conflict-free-merge',
148
+ deferredGates,
149
+ ciChecks,
150
+ },
151
+ };
152
+ }
@@ -1,20 +1,38 @@
1
1
  /**
2
- * ci-deferral.js — close's coverage capture under `coverage.suiteOfRecord:
3
- * "ci"`: settled before the serial runner spawns anything.
2
+ * ci-deferral.js — close gates CI owns: the capture under
3
+ * `coverage.suiteOfRecord: "ci"` and any gate marked `ciDeferred` after a
4
+ * conflict-free base merge, settled before the runner spawns anything.
4
5
  */
5
6
 
6
7
  import { COVERAGE_DEFERRED_REASONS } from '../coverage-deferral.js';
7
8
  import { CI_RATCHET_UNDECLARED_HINT } from './gates.js';
8
9
 
9
10
  /**
10
- * A capture CI owns: deferred without spawning, or failed with a hint naming
11
- * both keys when no ratchet check is declared. Mutates `deferred` / `failed`.
11
+ * A gate CI owns: deferred without spawning, or — a `suiteOfRecordCi` capture
12
+ * with no ratchet check — failed with a hint naming both keys. Mutates
13
+ * `deferred` / `failed`.
12
14
  *
13
15
  * @param {import('./gates.js').Gate} gate
14
16
  * @param {{ deferred: object[], failed: object[], log: (m: string) => void, spawnCwd: string }} acc
15
17
  * @returns {'deferred'|'stop'|null} `null` for any other gate.
16
18
  */
17
- export function presetCiDeferral(gate, { deferred, failed, log, spawnCwd }) {
19
+ export function presetCiDeferral(gate, acc) {
20
+ if (gate.ciDeferred) return deferToChecks(gate, acc);
21
+ return presetSuiteOfRecord(gate, acc);
22
+ }
23
+
24
+ /** A `ciDeferred` gate: settled deferred, naming the checks that own it. */
25
+ function deferToChecks(gate, { deferred, log, spawnCwd }) {
26
+ const { reason, checks } = gate.ciDeferred;
27
+ log(
28
+ `[close-validation] ⏭ ${gate.name} deferred to CI (${reason}, checks: ${checks.join(', ')}) — nothing spawned in ${spawnCwd}`,
29
+ );
30
+ deferred.push({ gate, status: null, reason });
31
+ return 'deferred';
32
+ }
33
+
34
+ /** A capture under `suiteOfRecord: "ci"`, else `null`. */
35
+ function presetSuiteOfRecord(gate, { deferred, failed, log, spawnCwd }) {
18
36
  const posture = gate.suiteOfRecordCi;
19
37
  if (!posture) return null;
20
38
  if (!posture.ciRatchetCheck) {