mandrel 2.110.0 → 2.112.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 (190) hide show
  1. package/.agents/agents/acceptance-critic.md +14 -0
  2. package/.agents/agents/auditor.md +14 -0
  3. package/.agents/agents/plan-critic.md +5 -0
  4. package/.agents/agents/story-worker.md +4 -1
  5. package/.agents/audit-checklists/state-machines.md +21 -0
  6. package/.agents/docs/agentrc-reference.json +23 -10
  7. package/.agents/docs/configuration.md +362 -15
  8. package/.agents/docs/execution-reference.md +11 -0
  9. package/.agents/docs/workflows.md +2 -1
  10. package/.agents/rules/ci-remediation.md +28 -4
  11. package/.agents/rules/git-conventions-reference.md +7 -0
  12. package/.agents/schemas/agentrc.schema.json +179 -13
  13. package/.agents/schemas/audit-rules.json +28 -0
  14. package/.agents/schemas/baselines/baseline-envelope.schema.json +16 -4
  15. package/.agents/schemas/baselines/bundle-size.schema.json +1 -0
  16. package/.agents/schemas/baselines/coverage.schema.json +1 -0
  17. package/.agents/schemas/baselines/crap.schema.json +37 -10
  18. package/.agents/schemas/baselines/duplication.schema.json +1 -0
  19. package/.agents/schemas/baselines/maintainability.schema.json +1 -0
  20. package/.agents/schemas/baselines/mutation.schema.json +1 -0
  21. package/.agents/schemas/crap-report.schema.json +6 -5
  22. package/.agents/schemas/story-deliver-terminal.schema.json +49 -3
  23. package/.agents/schemas/story-progress.schema.json +1 -1
  24. package/.agents/schemas/validation-evidence.schema.json +2 -2
  25. package/.agents/scripts/boot-sweep.js +41 -3
  26. package/.agents/scripts/coverage-capture.js +39 -3
  27. package/.agents/scripts/coverage-ratchet.js +106 -0
  28. package/.agents/scripts/evidence-gate.js +84 -21
  29. package/.agents/scripts/file-ci-gap.js +220 -10
  30. package/.agents/scripts/lib/audit-baselines/read.js +8 -1
  31. package/.agents/scripts/lib/audit-baselines/trend.js +2 -1
  32. package/.agents/scripts/lib/audit-to-stories/audit-lenses.js +1 -0
  33. package/.agents/scripts/lib/baseline-loader.js +4 -2
  34. package/.agents/scripts/lib/baselines/codec.js +57 -0
  35. package/.agents/scripts/lib/baselines/crap-preview-incremental.js +8 -3
  36. package/.agents/scripts/lib/baselines/crap-preview-scan.js +10 -16
  37. package/.agents/scripts/lib/baselines/crap-updater-cli.js +4 -13
  38. package/.agents/scripts/lib/baselines/kernel.js +19 -1
  39. package/.agents/scripts/lib/baselines/kinds/_crap-codec.js +171 -0
  40. package/.agents/scripts/lib/baselines/kinds/_crap-read.js +56 -16
  41. package/.agents/scripts/lib/baselines/kinds/_shared-metric.js +0 -59
  42. package/.agents/scripts/lib/baselines/kinds/crap.js +283 -319
  43. package/.agents/scripts/lib/baselines/preview-gates.js +29 -10
  44. package/.agents/scripts/lib/baselines/reader.js +36 -9
  45. package/.agents/scripts/lib/baselines/refresh-service.js +79 -18
  46. package/.agents/scripts/lib/baselines/seat-missing.js +173 -7
  47. package/.agents/scripts/lib/baselines/writer.js +36 -21
  48. package/.agents/scripts/lib/changed-files.js +70 -6
  49. package/.agents/scripts/lib/child-exec.js +10 -0
  50. package/.agents/scripts/lib/claude/agents-projection.js +5 -5
  51. package/.agents/scripts/lib/close-lock-events.js +8 -3
  52. package/.agents/scripts/lib/close-validation/ci-deferral.js +40 -0
  53. package/.agents/scripts/lib/close-validation/gates.js +156 -32
  54. package/.agents/scripts/lib/close-validation/process.js +16 -7
  55. package/.agents/scripts/lib/close-validation/projections/crap.js +43 -10
  56. package/.agents/scripts/lib/close-validation/runner.js +160 -41
  57. package/.agents/scripts/lib/close-validation/skip-branch-test.js +144 -0
  58. package/.agents/scripts/lib/close-validation/test-delta.js +33 -8
  59. package/.agents/scripts/lib/codex/agents-projection.js +6 -0
  60. package/.agents/scripts/lib/config/agentrc-overlay.js +9 -5
  61. package/.agents/scripts/lib/config/explain.js +5 -2
  62. package/.agents/scripts/lib/config/gates/coverage.schema.js +53 -0
  63. package/.agents/scripts/lib/config/gates/crap-incremental-coverage.schema.js +1 -1
  64. package/.agents/scripts/lib/config/git-roots.js +38 -4
  65. package/.agents/scripts/lib/config/handoff.js +24 -0
  66. package/.agents/scripts/lib/config/quality.js +28 -12
  67. package/.agents/scripts/lib/config/worktree-isolation.js +2 -5
  68. package/.agents/scripts/lib/config-resolver.js +22 -2
  69. package/.agents/scripts/lib/config-settings-schema-delivery.js +87 -4
  70. package/.agents/scripts/lib/config-settings-schema-quality.js +36 -1
  71. package/.agents/scripts/lib/config-settings-schema.js +1 -1
  72. package/.agents/scripts/lib/coverage-capture-affected.js +1 -0
  73. package/.agents/scripts/lib/coverage-capture-delta.js +164 -32
  74. package/.agents/scripts/lib/coverage-capture-own-fix.js +232 -0
  75. package/.agents/scripts/lib/coverage-capture-usage.js +2 -2
  76. package/.agents/scripts/lib/coverage-capture.js +31 -0
  77. package/.agents/scripts/lib/coverage-deferral.js +96 -0
  78. package/.agents/scripts/lib/coverage-ratchet.js +187 -0
  79. package/.agents/scripts/lib/crap-baseline-join.js +5 -5
  80. package/.agents/scripts/lib/crap-engine.js +3 -3
  81. package/.agents/scripts/lib/crap-method-identity.js +104 -48
  82. package/.agents/scripts/lib/escomplex-anchor.js +135 -0
  83. package/.agents/scripts/lib/escomplex-kernel.js +30 -1
  84. package/.agents/scripts/lib/failure-rows.js +121 -0
  85. package/.agents/scripts/lib/full-suite-lock.js +44 -4
  86. package/.agents/scripts/lib/full-suite-queue.js +89 -13
  87. package/.agents/scripts/lib/generated/agentrc-validator.js +8 -2
  88. package/.agents/scripts/lib/gh-env.js +3 -6
  89. package/.agents/scripts/lib/gh-pr-rest.js +1 -0
  90. package/.agents/scripts/lib/git/base-sync-probe.js +182 -0
  91. package/.agents/scripts/lib/git-branch-lifecycle.js +9 -0
  92. package/.agents/scripts/lib/observability/close-telemetry.js +37 -2
  93. package/.agents/scripts/lib/observability/handoff-telemetry.js +170 -0
  94. package/.agents/scripts/lib/observability/review-dispositions.js +23 -6
  95. package/.agents/scripts/lib/observability/runtime-friction.js +17 -4
  96. package/.agents/scripts/lib/observability/source-classifier.js +3 -0
  97. package/.agents/scripts/lib/observability/story-outcome.js +393 -0
  98. package/.agents/scripts/lib/orchestration/check-baselines/phases/compare.js +2 -1
  99. package/.agents/scripts/lib/orchestration/check-baselines/phases/evaluate.js +19 -1
  100. package/.agents/scripts/lib/orchestration/check-baselines/phases/fail-detail.js +84 -0
  101. package/.agents/scripts/lib/orchestration/check-baselines/phases/pipeline.js +14 -5
  102. package/.agents/scripts/lib/orchestration/check-baselines/phases/refresh-ack.js +3 -2
  103. package/.agents/scripts/lib/orchestration/check-baselines/phases/report.js +26 -6
  104. package/.agents/scripts/lib/orchestration/ci-rerun-guard.js +124 -23
  105. package/.agents/scripts/lib/orchestration/code-review.js +223 -19
  106. package/.agents/scripts/lib/orchestration/handoff-gates.js +217 -44
  107. package/.agents/scripts/lib/orchestration/handoff-rescore.js +169 -0
  108. package/.agents/scripts/lib/orchestration/handoff-suite-of-record.js +45 -0
  109. package/.agents/scripts/lib/orchestration/plan-persist/run-plan-persist.js +5 -1
  110. package/.agents/scripts/lib/orchestration/plan-persist/source-rewrite.js +76 -4
  111. package/.agents/scripts/lib/orchestration/plan-persist/story-ops.js +2 -2
  112. package/.agents/scripts/lib/orchestration/preflight-lanes.js +208 -0
  113. package/.agents/scripts/lib/orchestration/review-base-ref.js +40 -17
  114. package/.agents/scripts/lib/orchestration/review-deposit.js +38 -12
  115. package/.agents/scripts/lib/orchestration/review-depth.js +21 -0
  116. package/.agents/scripts/lib/orchestration/review-history.js +124 -20
  117. package/.agents/scripts/lib/orchestration/review-providers/claude-verdict.js +23 -8
  118. package/.agents/scripts/lib/orchestration/review-providers/code-review.js +82 -39
  119. package/.agents/scripts/lib/orchestration/review-providers/critical-verifier.js +64 -11
  120. package/.agents/scripts/lib/orchestration/review-providers/degraded-gates.js +98 -3
  121. package/.agents/scripts/lib/orchestration/review-providers/finding-identity.js +6 -2
  122. package/.agents/scripts/lib/orchestration/review-providers/findings-renderer.js +55 -8
  123. package/.agents/scripts/lib/orchestration/review-providers/review-guidance.js +1 -0
  124. package/.agents/scripts/lib/orchestration/review-providers/review-provider-factory.js +42 -15
  125. package/.agents/scripts/lib/orchestration/review-providers/types.js +6 -0
  126. package/.agents/scripts/lib/orchestration/single-story-close/failed-terminal.js +10 -1
  127. package/.agents/scripts/lib/orchestration/single-story-close/gate-log.js +10 -0
  128. package/.agents/scripts/lib/orchestration/single-story-close/phases/base-sync.js +7 -4
  129. package/.agents/scripts/lib/orchestration/single-story-close/phases/close-validation.js +17 -2
  130. package/.agents/scripts/lib/orchestration/single-story-close/phases/code-review.js +59 -2
  131. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +13 -1
  132. package/.agents/scripts/lib/orchestration/single-story-close/phases/finish.js +15 -4
  133. package/.agents/scripts/lib/orchestration/single-story-close/phases/land-review-record.js +213 -0
  134. package/.agents/scripts/lib/orchestration/single-story-close/phases/normalize-pr-title.js +17 -2
  135. package/.agents/scripts/lib/orchestration/single-story-close/phases/open-pr.js +42 -20
  136. package/.agents/scripts/lib/orchestration/single-story-close/phases/post-land.js +51 -26
  137. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +3 -1
  138. package/.agents/scripts/lib/orchestration/single-story-close/phases/pull-request.js +51 -15
  139. package/.agents/scripts/lib/orchestration/single-story-close/phases/push.js +59 -11
  140. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +1 -0
  141. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-block.js +31 -13
  142. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-halt.js +29 -6
  143. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-outcome.js +10 -12
  144. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-override.js +19 -4
  145. package/.agents/scripts/lib/orchestration/single-story-close/result.js +43 -13
  146. package/.agents/scripts/lib/orchestration/single-story-close/review-overlap.js +73 -39
  147. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +11 -2
  148. package/.agents/scripts/lib/orchestration/story-close/baseline-upward-writeback.js +3 -2
  149. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +20 -8
  150. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +7 -0
  151. package/.agents/scripts/lib/orchestration/story-handoff.js +789 -196
  152. package/.agents/scripts/lib/orchestration/ticketing/reads.js +2 -0
  153. package/.agents/scripts/lib/pr-body-lines.js +32 -0
  154. package/.agents/scripts/lib/single-story/ci-ratchet-gate.js +140 -0
  155. package/.agents/scripts/lib/single-story/confirm-and-land.js +17 -7
  156. package/.agents/scripts/lib/single-story/confirm-merge.js +12 -3
  157. package/.agents/scripts/lib/single-story-sweep/report-stalled-executing.js +202 -0
  158. package/.agents/scripts/lib/standalone-ratchets.js +37 -0
  159. package/.agents/scripts/lib/suite-admission.js +20 -8
  160. package/.agents/scripts/lib/suite-sizing.js +146 -0
  161. package/.agents/scripts/lib/workspace-provisioner.js +2 -2
  162. package/.agents/scripts/merge-baseline.js +14 -3
  163. package/.agents/scripts/providers/github/comments.js +19 -3
  164. package/.agents/scripts/providers/github.js +1 -0
  165. package/.agents/scripts/review-dispositions-report.js +1 -1
  166. package/.agents/scripts/role-scope-guard.js +267 -0
  167. package/.agents/scripts/single-story-close.js +4 -4
  168. package/.agents/scripts/single-story-confirm-merge.js +31 -5
  169. package/.agents/scripts/single-story-init.js +24 -4
  170. package/.agents/scripts/story-handoff.js +3 -3
  171. package/.agents/scripts/story-outcomes-report.js +231 -0
  172. package/.agents/scripts/story-review-compute.js +9 -5
  173. package/.agents/scripts/update-coverage-baseline.js +12 -2
  174. package/.agents/scripts/update-crap-baseline.js +9 -1
  175. package/.agents/workflows/audit-state-machines.md +213 -0
  176. package/.agents/workflows/helpers/code-review.md +63 -9
  177. package/.agents/workflows/helpers/deliver-digest.md +53 -54
  178. package/.agents/workflows/helpers/deliver-reference.md +236 -63
  179. package/.agents/workflows/helpers/deliver-story-reference.md +19 -8
  180. package/.agents/workflows/helpers/deliver-story.md +7 -2
  181. package/.agents/workflows/helpers/parallel-tooling.md +29 -0
  182. package/.agents/workflows/helpers/plan-reference.md +10 -2
  183. package/docs/CHANGELOG.md +56 -0
  184. package/lib/cli/doctor-checks/coverage-ratchet.js +54 -0
  185. package/lib/cli/doctor-checks/effective-agentrc.js +23 -0
  186. package/lib/cli/doctor-checks/llm-review.js +2 -11
  187. package/lib/cli/doctor-checks/sync-parity.js +5 -1
  188. package/lib/cli/doctor-checks/test-credit-path.js +7 -2
  189. package/lib/cli/registry.js +5 -0
  190. package/package.json +1 -1
@@ -1,16 +1,80 @@
1
1
  import { createGitInterface } from './git-utils.js';
2
2
 
3
+ /**
4
+ * `main` → `origin/main`; already-qualified input passes through.
5
+ *
6
+ * @param {unknown} baseBranch
7
+ * @returns {string|null} the remote-tracking ref, or `null` when unnameable.
8
+ */
9
+ export function remoteBaseRef(baseBranch) {
10
+ const base = trimmedName(baseBranch);
11
+ return base ? base.replace(/^(?!origin\/)/, 'origin/') : null;
12
+ }
13
+
14
+ function trimmedName(value) {
15
+ return typeof value === 'string' ? value.trim() : '';
16
+ }
17
+
3
18
  /**
4
19
  * The single rule for the ref a pre-push step diffs against: a named ref
5
- * wins, then `crap.incrementalCoverage.baseRef`, then `main`. The named ref
6
- * must win so coverage capture and the CRAP preview score the same change
7
- * set. Every consumer routes through here rather than reading `baseRef`.
20
+ * wins, then `crap.incrementalCoverage.baseRef`, then `origin/<baseBranch>`
21
+ * (never the bare local base, which may trail the remote and widen the set).
22
+ * Pure: no git call. Every consumer routes through here.
8
23
  *
9
- * @param {{ crap: object, ref: string | null | undefined }} opts
24
+ * @param {{ crap: object, ref: string | null | undefined, baseBranch?: string }} opts
10
25
  * @returns {string}
11
26
  */
12
- export function resolveChangedFilesRef({ crap, ref }) {
13
- return ref ?? crap?.incrementalCoverage?.baseRef ?? 'main';
27
+ export function resolveChangedFilesRef({ crap, ref, baseBranch }) {
28
+ return (
29
+ ref ??
30
+ crap?.incrementalCoverage?.baseRef ??
31
+ remoteBaseRef(baseBranch) ??
32
+ 'origin/main'
33
+ );
34
+ }
35
+
36
+ /**
37
+ * {@link resolveChangedFilesRef} plus a probe of the default only. An
38
+ * unresolvable `origin/<base>` falls back to the local base: its three-dot
39
+ * diff is never narrower than the Story's, so no gate is lost.
40
+ *
41
+ * @param {{ crap: object, ref?: string | null, baseBranch?: string, cwd?: string, gitSpawnFn?: Function }} opts
42
+ * @returns {{ ref: string, source: 'flag' | 'config' | 'remote' | 'local-fallback', unresolved?: string }}
43
+ */
44
+ export function resolveCaptureBaseRef({
45
+ crap,
46
+ ref,
47
+ baseBranch,
48
+ cwd = process.cwd(),
49
+ gitSpawnFn = createGitInterface({}).gitSpawn,
50
+ }) {
51
+ const named = namedRef(crap, ref);
52
+ if (named) return named;
53
+ const remote = resolveChangedFilesRef({ crap: null, ref: null, baseBranch });
54
+ return refResolves(gitSpawnFn, cwd, remote)
55
+ ? { ref: remote, source: 'remote' }
56
+ : localFallback(remote);
57
+ }
58
+
59
+ function localFallback(remote) {
60
+ const ref = remote.slice('origin/'.length);
61
+ return { ref, source: 'local-fallback', unresolved: remote };
62
+ }
63
+
64
+ function namedRef(crap, ref) {
65
+ if (ref != null) return { ref, source: 'flag' };
66
+ const configured = crap?.incrementalCoverage?.baseRef;
67
+ return configured == null ? null : { ref: configured, source: 'config' };
68
+ }
69
+
70
+ /** A spawn failure means the same as a missing ref. */
71
+ function refResolves(spawnFn, cwd, ref) {
72
+ try {
73
+ const args = ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`];
74
+ return spawnFn(cwd, ...args)?.status === 0;
75
+ } catch {
76
+ return false;
77
+ }
14
78
  }
15
79
 
16
80
  /**
@@ -149,6 +149,16 @@ export async function spawnCaptureAsync(file, args, opts = {}) {
149
149
  );
150
150
  }
151
151
 
152
+ /**
153
+ * `spawnCaptureAsync`, but a timeout, kill or spawn error stays `status: null`.
154
+ *
155
+ * @returns {Promise<{ status: number|null, stdout: string, stderr: string }>}
156
+ */
157
+ export async function spawnCaptureNullableAsync(file, args, opts = {}) {
158
+ const raw = await spawnChild(file, args, { run: execCollect, ...opts });
159
+ return { ...normalizeCapture(raw), status: raw?.status ?? null };
160
+ }
161
+
152
162
  /**
153
163
  * Spawn and stream each output chunk to `opts.onChunk` while retaining a
154
164
  * bounded tail; see `child-stream.js` for the contract.
@@ -10,6 +10,7 @@ import path from 'node:path';
10
10
 
11
11
  import { applyHeader } from '../command-header.js';
12
12
  import { applyAgentModel, getAgentModels } from '../config/agent-models.js';
13
+ import { overlayRoot } from '../config/git-roots.js';
13
14
  import { readJsonOrNull } from '../json-utils.js';
14
15
  import { dirExists } from '../util/paths.js';
15
16
 
@@ -41,12 +42,11 @@ function agentFilesIn(dir) {
41
42
  * @returns {Record<string, string>}
42
43
  */
43
44
  function readAgentModels(projectRoot) {
44
- const modelsIn = (file) =>
45
- readJsonOrNull(path.join(projectRoot, file))?.delivery?.routing
46
- ?.agentModels;
45
+ const modelsIn = (dir, file) =>
46
+ readJsonOrNull(path.join(dir, file))?.delivery?.routing?.agentModels;
47
47
  const merged = {
48
- ...(modelsIn('.agentrc.json') ?? {}),
49
- ...(modelsIn('.agentrc.local.json') ?? {}),
48
+ ...(modelsIn(projectRoot, '.agentrc.json') ?? {}),
49
+ ...(modelsIn(overlayRoot(projectRoot), '.agentrc.local.json') ?? {}),
50
50
  };
51
51
  return getAgentModels({ delivery: { routing: { agentModels: merged } } });
52
52
  }
@@ -91,7 +91,7 @@ export function claimLockEventSink(env = process.env, { fsImpl = fs } = {}) {
91
91
  }
92
92
 
93
93
  /**
94
- * Waits sum, an expiry sticks, the last holder wins; `spawns` keeps every
94
+ * Waits sum, an expiry sticks, the last holder and admission win; `spawns` keeps every
95
95
  * suite's timings in order and `suiteTimings` is the last of them.
96
96
  *
97
97
  * @param {object[]} events
@@ -120,14 +120,19 @@ export function sourcedTimings({ suiteTimings, spawns }, source) {
120
120
  }
121
121
 
122
122
  function mergeLockWait(tally, event) {
123
- const holder = event.holder ?? tally?.holder;
124
123
  return {
125
124
  waitedSeconds: (tally?.waitedSeconds ?? 0) + Number(event.waitedSeconds),
126
125
  expired: Boolean(tally?.expired) || event.expired === true,
127
- ...(holder ? { holder } : {}),
126
+ ...latest('holder', tally, event),
127
+ ...latest('admission', tally, event),
128
128
  };
129
129
  }
130
130
 
131
+ function latest(key, tally, event) {
132
+ const value = event[key] ?? tally?.[key];
133
+ return value ? { [key]: value } : {};
134
+ }
135
+
131
136
  function timingsOf({ lockWaitMs, hostWaitMs, testRunMs }) {
132
137
  return { lockWaitMs, hostWaitMs: hostWaitMs ?? null, testRunMs };
133
138
  }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * ci-deferral.js — close's coverage capture under `coverage.suiteOfRecord:
3
+ * "ci"`: settled before the serial runner spawns anything.
4
+ */
5
+
6
+ import { COVERAGE_DEFERRED_REASONS } from '../coverage-deferral.js';
7
+ import { CI_RATCHET_UNDECLARED_HINT } from './gates.js';
8
+
9
+ /**
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`.
12
+ *
13
+ * @param {import('./gates.js').Gate} gate
14
+ * @param {{ deferred: object[], failed: object[], log: (m: string) => void, spawnCwd: string }} acc
15
+ * @returns {'deferred'|'stop'|null} `null` for any other gate.
16
+ */
17
+ export function presetCiDeferral(gate, { deferred, failed, log, spawnCwd }) {
18
+ const posture = gate.suiteOfRecordCi;
19
+ if (!posture) return null;
20
+ if (!posture.ciRatchetCheck) {
21
+ log(
22
+ `[close-validation] ✖ ${gate.name}: suiteOfRecord "ci" names no ciRatchetCheck — nothing spawned in ${spawnCwd}`,
23
+ );
24
+ log(`[close-validation] hint: ${CI_RATCHET_UNDECLARED_HINT}`);
25
+ const failedGate = { ...gate, hint: CI_RATCHET_UNDECLARED_HINT };
26
+ failed.push({
27
+ gate: failedGate,
28
+ status: 1,
29
+ cwd: spawnCwd,
30
+ outcome: 'failed',
31
+ });
32
+ return 'stop';
33
+ }
34
+ log(
35
+ `[close-validation] ⏭ ${gate.name} deferred to CI (suiteOfRecord: ci, ratchet check "${posture.ciRatchetCheck}") — nothing spawned in ${spawnCwd}`,
36
+ );
37
+ const reason = COVERAGE_DEFERRED_REASONS.suiteOfRecordCi;
38
+ deferred.push({ gate, status: null, reason });
39
+ return 'deferred';
40
+ }
@@ -3,7 +3,11 @@
3
3
  import { existsSync } from 'node:fs';
4
4
 
5
5
  import { _internals as baselineReaderInternals } from '../baselines/reader.js';
6
- import { getChangedFiles } from '../changed-files.js';
6
+ import {
7
+ getChangedFiles,
8
+ remoteBaseRef,
9
+ resolveCaptureBaseRef,
10
+ } from '../changed-files.js';
7
11
  import {
8
12
  COVERAGE_GATE_DEFAULTS,
9
13
  getQuality,
@@ -22,8 +26,8 @@ import {
22
26
  isDefaultFormatCheck,
23
27
  resolveFormatWriteCommand,
24
28
  resolveGateCommand,
25
- resolveTestGateArgv,
26
29
  } from './commands.js';
30
+ import { closeTestGate, closeTestScope } from './skip-branch-test.js';
27
31
 
28
32
  /**
29
33
  * @typedef {Object} Gate
@@ -35,6 +39,9 @@ import {
35
39
  * @property {{ reason: string }} [skip] - Pre-decided skip: recorded, never spawned.
36
40
  * @property {Record<string, string>} [env] - Overlay merged over `process.env` for this gate's child only.
37
41
  * @property {boolean} [lockEventChannel] - The child reports on close's lock-event channel.
42
+ * @property {boolean} [deferOnOverBudget] - An exit 76 defers to CI instead of failing.
43
+ * @property {{ ciRatchetCheck: string|null }} [suiteOfRecordCi] - Deferred to CI without spawning; fails when no check is declared.
44
+ * @property {boolean} [readsCoverageArtifact] - Skipped once the capture deferred.
38
45
  * @property {{ cmd: string, args: string[] }} [evidenceIdentity] - Evidence argv, if not the spawned one.
39
46
  * @property {{ scope: 'delta', since: string }} [evidenceNote]
40
47
  * @property {string} [label]
@@ -53,13 +60,16 @@ function buildChangedFileScope(baseRef) {
53
60
  /**
54
61
  * Pin the `check-baselines` compare base to `origin/<baseBranch>` via
55
62
  * `BASELINE_REF`, so drift outside the Story's diff is not a phantom
56
- * regression; matches the attribution and auto-refresh bases. `null` keeps
57
- * the gate's default ref.
63
+ * regression; matches the attribution and auto-refresh bases. A skipped
64
+ * base sync passes the merge-base as `baselineRef`: the branch lacks main's
65
+ * later baseline moves. `null` keeps the gate's default ref.
58
66
  *
59
67
  * @param {string|undefined|null} baseBranch
68
+ * @param {string} [baselineRef]
60
69
  * @returns {{ BASELINE_REF: string } | null}
61
70
  */
62
- function buildBaselinesGateEnv(baseBranch) {
71
+ function buildBaselinesGateEnv(baseBranch, baselineRef) {
72
+ if (baselineRef) return { BASELINE_REF: baselineRef };
63
73
  if (typeof baseBranch !== 'string' || baseBranch.length === 0) return null;
64
74
  return { BASELINE_REF: `origin/${baseBranch}` };
65
75
  }
@@ -89,6 +99,53 @@ function captureQuality(config) {
89
99
  return resolveQuality({ gates: { crap, coverage } });
90
100
  }
91
101
 
102
+ /**
103
+ * What a suite's over-budget exit (76) — the capture's or `test`'s — means here and in the handoff.
104
+ *
105
+ * @param {object|undefined|null} config - Canonical resolved config.
106
+ * @returns {'block'|'defer-to-ci'}
107
+ */
108
+ export function overBudgetPolicy(config) {
109
+ return captureQuality(config).coverage.onOverBudget;
110
+ }
111
+
112
+ /** @param {object|undefined|null} config @returns {{ deferOnOverBudget?: true }} */
113
+ function overBudgetFlag(config) {
114
+ return overBudgetPolicy(config) === 'defer-to-ci'
115
+ ? { deferOnOverBudget: true }
116
+ : {};
117
+ }
118
+
119
+ /**
120
+ * Is CI the suite of record here? Under it the capture is deferred before
121
+ * anything spawns, and `ciRatchetCheck` names the CI check that ratchets.
122
+ *
123
+ * @param {object|undefined|null} config - Canonical resolved config.
124
+ * @returns {{ ci: boolean, ciRatchetCheck: string|null }}
125
+ */
126
+ export function suiteOfRecord(config) {
127
+ const { suiteOfRecord: posture, ciRatchetCheck } =
128
+ captureQuality(config).coverage;
129
+ return { ci: posture === 'ci', ciRatchetCheck };
130
+ }
131
+
132
+ /** @param {object|undefined|null} config @returns {{ suiteOfRecordCi?: { ciRatchetCheck: string|null } }} */
133
+ function suiteOfRecordFlag(config) {
134
+ const { ci, ciRatchetCheck } = suiteOfRecord(config);
135
+ return ci ? { suiteOfRecordCi: { ciRatchetCheck } } : {};
136
+ }
137
+
138
+ /** Shown when `suiteOfRecord: "ci"` has no ratchet check to hand the ratchet to. */
139
+ export const CI_RATCHET_UNDECLARED_HINT =
140
+ '`delivery.quality.gates.coverage.suiteOfRecord: "ci"` defers the coverage capture to CI, but `delivery.quality.gates.coverage.ciRatchetCheck` is unset, so nothing would ratchet coverage or CRAP. Name the CI check that runs `coverage-ratchet.js`, or set `suiteOfRecord` back to `"local"`.';
141
+
142
+ /** Skip reason for a gate that would read the artifact a deferral never wrote. */
143
+ export const COVERAGE_DEFERRED_SKIP_REASON = 'coverage-deferred-ci';
144
+
145
+ /** Shown when a suite gate (the capture or `test`) exits 76 and the policy blocks. */
146
+ export const OVER_BUDGET_BLOCK_HINT =
147
+ 'The suite declared its slice over this host\'s budget (exit 76) and ran no tests. Run the delivery on a larger host, or — when CI runs the suite with a coverage floor — set `delivery.quality.gates.coverage.onOverBudget: "defer-to-ci"`.';
148
+
92
149
  /**
93
150
  * Coverage-capture registers when the coverage or CRAP gate is on AND the
94
151
  * primary capture script exists (the coverage gate's `captureScript`, or an
@@ -119,18 +176,30 @@ function isCoverageCaptureActive(config, scripts) {
119
176
  * @param {object|undefined|null} config - Canonical resolved config.
120
177
  * @returns {Gate[]}
121
178
  */
122
- function buildTestGateEntry(coverageCaptureRunsSuite, config) {
179
+ function buildTestGateEntry(coverageCaptureRunsSuite, config, scope) {
123
180
  if (coverageCaptureRunsSuite) return [];
124
181
  // `fullSuiteLock` serializes this suite behind the host lock; when
125
182
  // coverage-capture runs instead, `runCapture` takes the lock itself.
126
- return [
127
- { name: 'test', ...resolveTestGateArgv(config), fullSuiteLock: true },
128
- ];
183
+ return [{ ...closeTestGate(config, scope), ...overBudgetFlag(config) }];
129
184
  }
130
185
 
131
186
  const CHECK_BASELINES_HINT =
132
187
  'Unified baselines gate breached. Inspect the JSON report (`node .agents/scripts/check-baselines.js`) to see which kind/component/axis fell below floor; remediate the underlying file(s) or — when the regression is intentional — refresh the relevant baseline through its per-kind update script and commit with a `baseline-refresh:` tagged subject.';
133
188
 
189
+ /**
190
+ * A failed gate whose hint quotes the baselines rows it printed; unchanged
191
+ * (its fixed hint) when none was retained.
192
+ *
193
+ * @param {Gate} gate
194
+ * @param {string[]} [rows]
195
+ * @returns {Gate}
196
+ */
197
+ export function withFailureRows(gate, rows) {
198
+ if (!rows?.length) return gate;
199
+ const hint = `Baselines gate failed: ${rows.join('; ')} — full report: node .agents/scripts/check-baselines.js --format json`;
200
+ return { ...gate, hint };
201
+ }
202
+
134
203
  /**
135
204
  * Baselines gate names. `single` is the unsplit fail-closed fallback;
136
205
  * `independent` runs in the parallel partition, `coverage` stays serial
@@ -235,6 +304,19 @@ function probeBaselinesGate({
235
304
  * @param {{ decision: { register: boolean, hint?: string }, kinds: string[]|null, env: { BASELINE_REF: string }|null }} args
236
305
  * @returns {Gate[]}
237
306
  */
307
+ /**
308
+ * The unsplit gate (`null` kinds) scores every kind, coverage ones included.
309
+ *
310
+ * @param {string[]|null} gateKinds
311
+ * @returns {{ readsCoverageArtifact?: true }}
312
+ */
313
+ function coverageReaderFlag(gateKinds) {
314
+ const reads =
315
+ gateKinds === null ||
316
+ gateKinds.some((k) => COVERAGE_CONSUMING_KINDS.has(k));
317
+ return reads ? { readsCoverageArtifact: true } : {};
318
+ }
319
+
238
320
  function buildBaselinesGateEntries({ decision, kinds, env }) {
239
321
  if (!decision.register) return [];
240
322
  const entry = (name, gateKinds) => ({
@@ -247,7 +329,10 @@ function buildBaselinesGateEntries({ decision, kinds, env }) {
247
329
  'text',
248
330
  ],
249
331
  hint: decision.hint ?? CHECK_BASELINES_HINT,
332
+ // A registration hint stays as-is; the fixed hint yields to quoted rows.
333
+ retainFailureRows: !decision.hint,
250
334
  ...(env ? { env } : {}),
335
+ ...coverageReaderFlag(gateKinds),
251
336
  });
252
337
  if (!Array.isArray(kinds) || kinds.length === 0) {
253
338
  return [entry(BASELINES_GATE_NAMES.single, null)];
@@ -281,13 +366,15 @@ function disabledSkip(command, gateName) {
281
366
  * Will coverage-capture take its incremental skip (no changed file under
282
367
  * `crap.targetDirs`)? If so the close would otherwise have no test gate at all.
283
368
  * Every uncertainty resolves to `false`: a wrong `false` costs one redundant
284
- * capture, a wrong `true` runs the suite twice.
369
+ * capture, a wrong `true` runs the suite twice. The ref comes from the
370
+ * capture's own resolver, so the prediction and the capture score one set.
285
371
  *
286
372
  * @param {{
287
373
  * config?: object,
288
374
  * cwd?: string,
289
375
  * baseBranch?: string,
290
376
  * getChangedFilesImpl?: typeof getChangedFiles,
377
+ * resolveBaseRefImpl?: typeof resolveCaptureBaseRef,
291
378
  * }} opts
292
379
  * @returns {boolean}
293
380
  */
@@ -296,14 +383,14 @@ function predictsIncrementalCaptureSkip({
296
383
  cwd,
297
384
  baseBranch,
298
385
  getChangedFilesImpl = getChangedFiles,
386
+ resolveBaseRefImpl = resolveCaptureBaseRef,
299
387
  }) {
300
388
  // No cwd is the module-load `DEFAULT_GATES` case: never spawn git at import.
301
389
  if (typeof cwd !== 'string' || cwd.length === 0) return false;
302
390
  const { crap } = getQuality(config);
303
391
  if (crap?.incrementalCoverage?.skipWhenUnchanged !== true) return false;
304
- const ref = crap.incrementalCoverage.baseRef || baseBranch;
305
- if (typeof ref !== 'string' || ref.length === 0) return false;
306
392
  try {
393
+ const { ref } = resolveBaseRefImpl({ crap, ref: null, baseBranch, cwd });
307
394
  const changed = getChangedFilesImpl({ ref, cwd });
308
395
  // Non-array is "unknown", which `filterFilesUnderTargets` would flatten to
309
396
  // `[]` and misread as a skip.
@@ -314,9 +401,16 @@ function predictsIncrementalCaptureSkip({
314
401
  }
315
402
  }
316
403
 
404
+ /** Capture-active and not skipping → the capture deposits; else `test`. */
405
+ function depositorShape(active, skipBranch) {
406
+ const depositor = active && !skipBranch ? 'coverage-capture' : 'test';
407
+ return { depositor, skipBranch };
408
+ }
409
+
317
410
  /**
318
411
  * The credited-run depositor, shared by close and `story-handoff.js`: a
319
412
  * predicted incremental skip runs no suite, so it is never the depositor.
413
+ * `skipBranch` tells that `test` depositor apart from an inactive capture's.
320
414
  *
321
415
  * @param {{
322
416
  * config?: object,
@@ -324,8 +418,9 @@ function predictsIncrementalCaptureSkip({
324
418
  * cwd?: string,
325
419
  * baseBranch?: string,
326
420
  * getChangedFilesImpl?: typeof getChangedFiles,
421
+ * resolveBaseRefImpl?: typeof resolveCaptureBaseRef,
327
422
  * }} opts
328
- * @returns {'coverage-capture'|'test'}
423
+ * @returns {{ depositor: 'coverage-capture'|'test', skipBranch: boolean }}
329
424
  */
330
425
  export function resolveCreditedDepositor({
331
426
  config,
@@ -333,15 +428,19 @@ export function resolveCreditedDepositor({
333
428
  cwd,
334
429
  baseBranch,
335
430
  getChangedFilesImpl,
431
+ resolveBaseRefImpl,
336
432
  }) {
337
- if (!isCoverageCaptureActive(config, scripts)) return 'test';
338
- const skip = predictsIncrementalCaptureSkip({
339
- config,
340
- cwd,
341
- baseBranch,
342
- ...(getChangedFilesImpl ? { getChangedFilesImpl } : {}),
343
- });
344
- return skip ? 'test' : 'coverage-capture';
433
+ const active = isCoverageCaptureActive(config, scripts);
434
+ const skipBranch =
435
+ active &&
436
+ predictsIncrementalCaptureSkip({
437
+ config,
438
+ cwd,
439
+ baseBranch,
440
+ ...(getChangedFilesImpl ? { getChangedFilesImpl } : {}),
441
+ resolveBaseRefImpl,
442
+ });
443
+ return depositorShape(active, skipBranch);
345
444
  }
346
445
 
347
446
  /**
@@ -401,6 +500,12 @@ export const QUALITY_PREVIEW_GATE_NAMES = Object.freeze({
401
500
  crap: 'quality-preview-crap',
402
501
  });
403
502
 
503
+ /** The CRAP half reads the coverage artifact; the MI half does not. */
504
+ const PREVIEW_ARTIFACT_FLAGS = Object.freeze({
505
+ maintainability: {},
506
+ crap: { readsCoverageArtifact: true },
507
+ });
508
+
404
509
  const QUALITY_PREVIEW_HINTS = Object.freeze({
405
510
  maintainability:
406
511
  'Maintainability preview failed — the per-file MI check the `pre-push` hook runs, scored against the base branch. Simplify the flagged file(s), then re-run close; this gate runs before coverage-capture, so no suite was spent.',
@@ -417,7 +522,7 @@ const QUALITY_PREVIEW_HINTS = Object.freeze({
417
522
  */
418
523
  function buildQualityPreviewGateEntries({ coverageCaptureActive, baseBranch }) {
419
524
  if (!coverageCaptureActive) return { maintainability: [], crap: [] };
420
- const ref = `origin/${baseBranch || 'main'}`;
525
+ const ref = remoteBaseRef(baseBranch || 'main');
421
526
  const entry = (half, only) => [
422
527
  {
423
528
  name: QUALITY_PREVIEW_GATE_NAMES[half],
@@ -430,6 +535,7 @@ function buildQualityPreviewGateEntries({ coverageCaptureActive, baseBranch }) {
430
535
  ref,
431
536
  ],
432
537
  hint: QUALITY_PREVIEW_HINTS[half],
538
+ ...PREVIEW_ARTIFACT_FLAGS[half],
433
539
  },
434
540
  ];
435
541
  return {
@@ -451,7 +557,7 @@ export const GATE_TIMEOUT_HINT = `The gate outran the suite timeout (\`delivery.
451
557
  * enabled AND its capture script (`gates.coverage.captureScript`) exists; it then carries test-failure signalling and
452
558
  * the plain `test` gate is dropped, so there is always exactly one test gate.
453
559
  *
454
- * @param {{ config?: object, baseBranch?: string, cwd?: string, packageScripts?: Record<string, string>, presentBaselines?: string[]|Set<string>, log?: (message: string) => void, getChangedFilesImpl?: typeof getChangedFiles }} [opts]
560
+ * @param {{ config?: object, baseBranch?: string, baselineRef?: string, cwd?: string, packageScripts?: Record<string, string>, presentBaselines?: string[]|Set<string>, log?: (message: string) => void, getChangedFilesImpl?: typeof getChangedFiles, resolveBaseRefImpl?: typeof resolveCaptureBaseRef }} [opts]
455
561
  * `cwd` is where the `package.json` and baseline-presence probes read;
456
562
  * `packageScripts` / `presentBaselines` inject those probes (tests).
457
563
  * @returns {Gate[]}
@@ -459,11 +565,13 @@ export const GATE_TIMEOUT_HINT = `The gate outran the suite timeout (\`delivery.
459
565
  export function buildDefaultGates({
460
566
  config,
461
567
  baseBranch,
568
+ baselineRef,
462
569
  cwd,
463
570
  packageScripts,
464
571
  presentBaselines,
465
572
  log,
466
573
  getChangedFilesImpl,
574
+ resolveBaseRefImpl,
467
575
  storyId,
468
576
  evidenceCwd,
469
577
  gitSpawnImpl,
@@ -493,12 +601,16 @@ export function buildDefaultGates({
493
601
  cwd,
494
602
  baseBranch,
495
603
  getChangedFilesImpl,
496
- }) === 'test';
497
- if (captureSkipPredicted) {
498
- log?.(
499
- '[close-validation] coverage-capture will take the incremental skip (no changed file under the CRAP target dirs) — registering the plain `test` gate so this close still runs the suite.',
500
- );
501
- }
604
+ resolveBaseRefImpl,
605
+ }).skipBranch;
606
+ const testScope = closeTestScope({
607
+ skipBranch: captureSkipPredicted,
608
+ config,
609
+ cwd,
610
+ baseBranch,
611
+ gitSpawnImpl,
612
+ log,
613
+ });
502
614
  const typecheck = resolveGateCommand(config, 'typecheck');
503
615
  const lint = resolveGateCommand(config, 'lint');
504
616
  const format = resolveGateCommand(config, 'formatCheck');
@@ -506,7 +618,7 @@ export function buildDefaultGates({
506
618
  const formatChangedFileScope = isDefaultFormatCheck(format.raw)
507
619
  ? buildChangedFileScope(baseBranch)
508
620
  : null;
509
- const baselinesGateEnv = buildBaselinesGateEnv(baseBranch);
621
+ const baselinesGateEnv = buildBaselinesGateEnv(baseBranch, baselineRef);
510
622
  const baselineKinds = enabledBaselineKinds(config);
511
623
  const baselinesDecision = probeBaselinesGate({
512
624
  config,
@@ -544,6 +656,7 @@ export function buildDefaultGates({
544
656
  testCredited,
545
657
  }),
546
658
  config,
659
+ testScope,
547
660
  ),
548
661
  {
549
662
  name: 'format',
@@ -564,9 +677,10 @@ export function buildDefaultGates({
564
677
  args: [...COVERAGE_CAPTURE_ARGS],
565
678
  hint: coverageCaptureHint(config),
566
679
  lockEventChannel: true,
680
+ ...overBudgetFlag(config),
567
681
  ...(captureSkipPredicted
568
682
  ? { skip: { reason: 'incremental-no-crap-changes' } }
569
- : {}),
683
+ : suiteOfRecordFlag(config)),
570
684
  },
571
685
  ]
572
686
  : []),
@@ -598,6 +712,16 @@ const INDEPENDENT_GATE_NAMES = new Set([
598
712
  QUALITY_PREVIEW_GATE_NAMES.maintainability,
599
713
  ]);
600
714
 
715
+ /**
716
+ * Does close run this gate in its concurrent bucket?
717
+ *
718
+ * @param {string} name
719
+ * @returns {boolean}
720
+ */
721
+ export function isIndependentGate(name) {
722
+ return INDEPENDENT_GATE_NAMES.has(name);
723
+ }
724
+
601
725
  /**
602
726
  * Order is preserved within each bucket.
603
727
  *
@@ -608,7 +732,7 @@ export function partitionGates(gates) {
608
732
  const independent = [];
609
733
  const serial = [];
610
734
  for (const gate of gates) {
611
- if (INDEPENDENT_GATE_NAMES.has(gate.name)) independent.push(gate);
735
+ if (isIndependentGate(gate.name)) independent.push(gate);
612
736
  else serial.push(gate);
613
737
  }
614
738
  return { independent, serial };
@@ -2,6 +2,8 @@
2
2
 
3
3
  import { spawn } from 'node:child_process';
4
4
 
5
+ import { tapFailureRows } from '../failure-rows.js';
6
+
5
7
  import {
6
8
  ADMISSION_REFUSED_EXIT_CODE,
7
9
  LOCK_WAIT_EXPIRED_EXIT_CODE,
@@ -91,8 +93,8 @@ export function isBiomeNoFilesProcessed(output) {
91
93
  *
92
94
  * @param {string} cmd
93
95
  * @param {string[]} args
94
- * @param {{ cwd: string, signal?: AbortSignal, gateName?: string, log?: (m: string) => void, env?: Record<string, string>, tolerateNoFilesProcessed?: boolean, fullSuiteLock?: boolean, timeoutMs?: number, lockOptions?: object, onLockEvent?: (event: object) => void, skipIfSatisfied?: () => {status: number}|undefined, spawnImpl?: typeof spawn }} opts
95
- * @returns {Promise<{ status: number }>}
96
+ * @param {{ cwd: string, signal?: AbortSignal, gateName?: string, log?: (m: string) => void, env?: Record<string, string>, tolerateNoFilesProcessed?: boolean, retainFailureRows?: boolean, fullSuiteLock?: boolean, timeoutMs?: number, lockOptions?: object, onLockEvent?: (event: object) => void, skipIfSatisfied?: () => {status: number}|undefined, spawnImpl?: typeof spawn }} opts
97
+ * @returns {Promise<{ status: number, failureRows?: string[] }>}
96
98
  */
97
99
  export function defaultGateRunner(cmd, args, opts = {}) {
98
100
  if (!opts.fullSuiteLock) return spawnGate(cmd, args, opts);
@@ -151,6 +153,7 @@ function spawnGate(cmd, args, opts, lock) {
151
153
  supervisor.release();
152
154
  resolve({
153
155
  status: settledGateStatus({ code, sig, supervisor, opts, output }),
156
+ ...output.rowsResult(),
154
157
  });
155
158
  });
156
159
  child.on('error', () => {
@@ -181,17 +184,23 @@ function spawnGateChild(cmd, args, cwd, env, spawnImpl = spawn) {
181
184
  }
182
185
 
183
186
  /**
184
- * Retains a bounded tail only when the biome marker may need inspecting.
187
+ * Retains a bounded tail only when the biome marker may need inspecting, and
188
+ * only the capped failure rows of a `retainFailureRows` gate.
185
189
  *
186
- * @param {{ gateName?: string, log?: (m: string) => void, tolerateNoFilesProcessed?: boolean }} opts
190
+ * @param {{ gateName?: string, log?: (m: string) => void, tolerateNoFilesProcessed?: boolean, retainFailureRows?: boolean }} opts
187
191
  */
188
- function gateOutput({ gateName, log, tolerateNoFilesProcessed }) {
192
+ function gateOutput({
193
+ gateName,
194
+ log,
195
+ tolerateNoFilesProcessed,
196
+ retainFailureRows,
197
+ }) {
189
198
  const prefix = gateName ? `[${gateName}] ` : '';
190
199
  const emit =
191
200
  typeof log === 'function' ? log : (m) => process.stdout.write(`${m}\n`);
192
201
  const recent = [];
193
- const tap = tolerateNoFilesProcessed ? retainTail(recent, emit) : emit;
194
- return { prefix, emit, tap, recent };
202
+ const tail = tolerateNoFilesProcessed ? retainTail(recent, emit) : emit;
203
+ return { prefix, emit, recent, ...tapFailureRows(retainFailureRows, tail) };
195
204
  }
196
205
 
197
206
  function retainTail(recent, emit) {