mandrel 2.111.0 → 2.113.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 (183) 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/docs/agentrc-reference.json +22 -10
  6. package/.agents/docs/configuration.md +367 -37
  7. package/.agents/docs/execution-reference.md +11 -0
  8. package/.agents/rules/git-conventions-reference.md +7 -0
  9. package/.agents/schemas/agentrc.schema.json +174 -14
  10. package/.agents/schemas/baselines/baseline-envelope.schema.json +16 -4
  11. package/.agents/schemas/baselines/bundle-size.schema.json +1 -0
  12. package/.agents/schemas/baselines/coverage.schema.json +1 -0
  13. package/.agents/schemas/baselines/crap.schema.json +37 -10
  14. package/.agents/schemas/baselines/duplication.schema.json +1 -0
  15. package/.agents/schemas/baselines/maintainability.schema.json +1 -0
  16. package/.agents/schemas/baselines/mutation.schema.json +1 -0
  17. package/.agents/schemas/crap-report.schema.json +6 -5
  18. package/.agents/schemas/story-deliver-terminal.schema.json +41 -2
  19. package/.agents/schemas/story-progress.schema.json +1 -1
  20. package/.agents/schemas/validation-evidence.schema.json +2 -2
  21. package/.agents/scripts/boot-sweep.js +41 -3
  22. package/.agents/scripts/coverage-capture.js +37 -3
  23. package/.agents/scripts/coverage-ratchet.js +106 -0
  24. package/.agents/scripts/evidence-gate.js +84 -21
  25. package/.agents/scripts/lib/audit-baselines/read.js +8 -1
  26. package/.agents/scripts/lib/audit-baselines/trend.js +2 -1
  27. package/.agents/scripts/lib/baseline-loader.js +4 -2
  28. package/.agents/scripts/lib/baselines/codec.js +57 -0
  29. package/.agents/scripts/lib/baselines/crap-preview-incremental.js +8 -3
  30. package/.agents/scripts/lib/baselines/crap-preview-scan.js +10 -16
  31. package/.agents/scripts/lib/baselines/crap-updater-cli.js +4 -13
  32. package/.agents/scripts/lib/baselines/kernel.js +19 -1
  33. package/.agents/scripts/lib/baselines/kinds/_crap-codec.js +171 -0
  34. package/.agents/scripts/lib/baselines/kinds/_crap-read.js +56 -16
  35. package/.agents/scripts/lib/baselines/kinds/_shared-metric.js +0 -59
  36. package/.agents/scripts/lib/baselines/kinds/crap.js +283 -319
  37. package/.agents/scripts/lib/baselines/merge-envelopes.js +46 -1
  38. package/.agents/scripts/lib/baselines/preview-gates.js +29 -10
  39. package/.agents/scripts/lib/baselines/reader.js +36 -9
  40. package/.agents/scripts/lib/baselines/refresh-service.js +93 -21
  41. package/.agents/scripts/lib/baselines/seat-missing.js +173 -7
  42. package/.agents/scripts/lib/baselines/writer.js +36 -21
  43. package/.agents/scripts/lib/changed-files.js +70 -6
  44. package/.agents/scripts/lib/child-exec.js +10 -0
  45. package/.agents/scripts/lib/claude/agents-projection.js +5 -5
  46. package/.agents/scripts/lib/close-lock-events.js +8 -3
  47. package/.agents/scripts/lib/close-validation/ci-deferral.js +40 -0
  48. package/.agents/scripts/lib/close-validation/gates.js +111 -35
  49. package/.agents/scripts/lib/close-validation/process.js +16 -7
  50. package/.agents/scripts/lib/close-validation/projections/crap.js +43 -10
  51. package/.agents/scripts/lib/close-validation/runner.js +55 -23
  52. package/.agents/scripts/lib/close-validation/skip-branch-test.js +144 -0
  53. package/.agents/scripts/lib/close-validation/test-delta.js +33 -8
  54. package/.agents/scripts/lib/codex/agents-projection.js +6 -0
  55. package/.agents/scripts/lib/config/agentrc-overlay.js +9 -5
  56. package/.agents/scripts/lib/config/explain.js +5 -2
  57. package/.agents/scripts/lib/config/gates/coverage.schema.js +45 -1
  58. package/.agents/scripts/lib/config/gates/crap-incremental-coverage.schema.js +1 -1
  59. package/.agents/scripts/lib/config/git-roots.js +38 -4
  60. package/.agents/scripts/lib/config/handoff.js +24 -0
  61. package/.agents/scripts/lib/config/quality.js +26 -13
  62. package/.agents/scripts/lib/config/worktree-isolation.js +2 -5
  63. package/.agents/scripts/lib/config-resolver.js +22 -2
  64. package/.agents/scripts/lib/config-settings-schema-delivery.js +87 -4
  65. package/.agents/scripts/lib/config-settings-schema-quality.js +36 -1
  66. package/.agents/scripts/lib/config-settings-schema.js +1 -1
  67. package/.agents/scripts/lib/coverage-capture-affected.js +1 -0
  68. package/.agents/scripts/lib/coverage-capture-delta.js +164 -32
  69. package/.agents/scripts/lib/coverage-capture-own-fix.js +232 -0
  70. package/.agents/scripts/lib/coverage-capture-usage.js +2 -2
  71. package/.agents/scripts/lib/coverage-capture.js +15 -0
  72. package/.agents/scripts/lib/coverage-deferral.js +96 -0
  73. package/.agents/scripts/lib/coverage-ratchet.js +187 -0
  74. package/.agents/scripts/lib/crap-baseline-join.js +5 -5
  75. package/.agents/scripts/lib/crap-engine.js +3 -3
  76. package/.agents/scripts/lib/crap-method-identity.js +104 -48
  77. package/.agents/scripts/lib/error-redactor.js +20 -0
  78. package/.agents/scripts/lib/escomplex-anchor.js +135 -0
  79. package/.agents/scripts/lib/escomplex-kernel.js +30 -1
  80. package/.agents/scripts/lib/failure-rows.js +121 -0
  81. package/.agents/scripts/lib/full-suite-lock.js +44 -4
  82. package/.agents/scripts/lib/full-suite-queue.js +89 -13
  83. package/.agents/scripts/lib/generated/agentrc-validator.js +8 -2
  84. package/.agents/scripts/lib/gh-env.js +3 -6
  85. package/.agents/scripts/lib/gh-pr-rest.js +1 -0
  86. package/.agents/scripts/lib/git/base-sync-probe.js +182 -0
  87. package/.agents/scripts/lib/git/baseline-conflict-rows.js +60 -0
  88. package/.agents/scripts/lib/git/sync-from-base.js +18 -9
  89. package/.agents/scripts/lib/git-branch-lifecycle.js +9 -0
  90. package/.agents/scripts/lib/observability/close-telemetry.js +37 -2
  91. package/.agents/scripts/lib/observability/handoff-telemetry.js +170 -0
  92. package/.agents/scripts/lib/observability/review-dispositions.js +23 -6
  93. package/.agents/scripts/lib/observability/runtime-friction.js +17 -4
  94. package/.agents/scripts/lib/observability/source-classifier.js +3 -0
  95. package/.agents/scripts/lib/observability/story-outcome.js +393 -0
  96. package/.agents/scripts/lib/orchestration/check-baselines/phases/compare.js +2 -1
  97. package/.agents/scripts/lib/orchestration/check-baselines/phases/evaluate.js +19 -1
  98. package/.agents/scripts/lib/orchestration/check-baselines/phases/fail-detail.js +84 -0
  99. package/.agents/scripts/lib/orchestration/check-baselines/phases/pipeline.js +14 -5
  100. package/.agents/scripts/lib/orchestration/check-baselines/phases/refresh-ack.js +3 -2
  101. package/.agents/scripts/lib/orchestration/check-baselines/phases/report.js +26 -6
  102. package/.agents/scripts/lib/orchestration/code-review.js +223 -19
  103. package/.agents/scripts/lib/orchestration/handoff-gates.js +129 -62
  104. package/.agents/scripts/lib/orchestration/handoff-rescore.js +170 -0
  105. package/.agents/scripts/lib/orchestration/handoff-suite-of-record.js +45 -0
  106. package/.agents/scripts/lib/orchestration/preflight-lanes.js +208 -0
  107. package/.agents/scripts/lib/orchestration/review-base-ref.js +40 -17
  108. package/.agents/scripts/lib/orchestration/review-deposit.js +38 -12
  109. package/.agents/scripts/lib/orchestration/review-depth.js +21 -0
  110. package/.agents/scripts/lib/orchestration/review-history.js +124 -20
  111. package/.agents/scripts/lib/orchestration/review-providers/claude-verdict.js +41 -12
  112. package/.agents/scripts/lib/orchestration/review-providers/code-review.js +90 -39
  113. package/.agents/scripts/lib/orchestration/review-providers/critical-verifier.js +64 -11
  114. package/.agents/scripts/lib/orchestration/review-providers/degraded-gates.js +102 -3
  115. package/.agents/scripts/lib/orchestration/review-providers/finding-identity.js +6 -2
  116. package/.agents/scripts/lib/orchestration/review-providers/findings-renderer.js +55 -8
  117. package/.agents/scripts/lib/orchestration/review-providers/review-guidance.js +1 -0
  118. package/.agents/scripts/lib/orchestration/review-providers/review-provider-factory.js +42 -15
  119. package/.agents/scripts/lib/orchestration/review-providers/types.js +6 -0
  120. package/.agents/scripts/lib/orchestration/single-story-close/failed-terminal.js +10 -1
  121. package/.agents/scripts/lib/orchestration/single-story-close/gate-log.js +10 -0
  122. package/.agents/scripts/lib/orchestration/single-story-close/phases/base-sync.js +7 -4
  123. package/.agents/scripts/lib/orchestration/single-story-close/phases/close-validation.js +16 -3
  124. package/.agents/scripts/lib/orchestration/single-story-close/phases/code-review.js +59 -2
  125. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +6 -0
  126. package/.agents/scripts/lib/orchestration/single-story-close/phases/finish.js +15 -4
  127. package/.agents/scripts/lib/orchestration/single-story-close/phases/land-review-record.js +213 -0
  128. package/.agents/scripts/lib/orchestration/single-story-close/phases/normalize-pr-title.js +9 -12
  129. package/.agents/scripts/lib/orchestration/single-story-close/phases/open-pr.js +26 -12
  130. package/.agents/scripts/lib/orchestration/single-story-close/phases/post-land.js +51 -26
  131. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-gate-steps.js +2 -1
  132. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +3 -2
  133. package/.agents/scripts/lib/orchestration/single-story-close/phases/pull-request.js +50 -17
  134. package/.agents/scripts/lib/orchestration/single-story-close/phases/push.js +59 -11
  135. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +1 -0
  136. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-block.js +31 -13
  137. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-halt.js +29 -6
  138. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-outcome.js +10 -12
  139. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-override.js +19 -4
  140. package/.agents/scripts/lib/orchestration/single-story-close/result.js +30 -13
  141. package/.agents/scripts/lib/orchestration/single-story-close/review-overlap.js +73 -39
  142. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +11 -3
  143. package/.agents/scripts/lib/orchestration/story-close/baseline-upward-writeback.js +3 -2
  144. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +77 -15
  145. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +7 -0
  146. package/.agents/scripts/lib/orchestration/story-handoff.js +796 -196
  147. package/.agents/scripts/lib/orchestration/ticketing/reads.js +2 -0
  148. package/.agents/scripts/lib/pr-body-lines.js +32 -0
  149. package/.agents/scripts/lib/single-story/ci-ratchet-gate.js +140 -0
  150. package/.agents/scripts/lib/single-story/confirm-and-land.js +17 -7
  151. package/.agents/scripts/lib/single-story/confirm-merge.js +12 -3
  152. package/.agents/scripts/lib/single-story-sweep/report-stalled-executing.js +202 -0
  153. package/.agents/scripts/lib/standalone-ratchets.js +37 -0
  154. package/.agents/scripts/lib/suite-admission.js +20 -8
  155. package/.agents/scripts/lib/suite-sizing.js +146 -0
  156. package/.agents/scripts/lib/workspace-provisioner.js +2 -2
  157. package/.agents/scripts/merge-baseline.js +14 -3
  158. package/.agents/scripts/providers/github/comments.js +19 -3
  159. package/.agents/scripts/providers/github.js +1 -0
  160. package/.agents/scripts/review-dispositions-report.js +1 -1
  161. package/.agents/scripts/role-scope-guard.js +267 -0
  162. package/.agents/scripts/single-story-close.js +4 -4
  163. package/.agents/scripts/single-story-confirm-merge.js +31 -5
  164. package/.agents/scripts/single-story-init.js +24 -4
  165. package/.agents/scripts/story-handoff.js +3 -3
  166. package/.agents/scripts/story-outcomes-report.js +231 -0
  167. package/.agents/scripts/story-review-compute.js +9 -5
  168. package/.agents/scripts/update-coverage-baseline.js +12 -2
  169. package/.agents/scripts/update-crap-baseline.js +9 -1
  170. package/.agents/workflows/helpers/code-review.md +63 -9
  171. package/.agents/workflows/helpers/deliver-digest.md +53 -54
  172. package/.agents/workflows/helpers/deliver-reference.md +233 -67
  173. package/.agents/workflows/helpers/deliver-story-reference.md +19 -8
  174. package/.agents/workflows/helpers/deliver-story.md +7 -2
  175. package/.agents/workflows/helpers/parallel-tooling.md +29 -0
  176. package/docs/CHANGELOG.md +55 -0
  177. package/lib/cli/doctor-checks/coverage-ratchet.js +54 -0
  178. package/lib/cli/doctor-checks/effective-agentrc.js +23 -0
  179. package/lib/cli/doctor-checks/llm-review.js +2 -11
  180. package/lib/cli/doctor-checks/sync-parity.js +5 -1
  181. package/lib/cli/doctor-checks/test-credit-path.js +7 -2
  182. package/lib/cli/registry.js +5 -0
  183. package/package.json +1 -1
@@ -9,6 +9,7 @@ import fs from 'node:fs';
9
9
  import path from 'node:path';
10
10
  import { deepEqual, isObject } from '../json-utils.js';
11
11
  import { writeFileAtomic } from '../util/atomic-write.js';
12
+ import { encodeEnvelope } from './codec.js';
12
13
  import { assertEnvelope, buildEnvelope } from './envelope.js';
13
14
  import { currentKernelVersion, getKindModule } from './kernel.js';
14
15
  import { assertCanonical } from './path-canon.js';
@@ -73,12 +74,18 @@ export function write({
73
74
  });
74
75
  }
75
76
 
77
+ const priorEnv = resolvePriorEnvelope(priorEnvelope, prior);
78
+ const extras =
79
+ typeof mod.envelopeExtras === 'function'
80
+ ? mod.envelopeExtras(extrasContext)
81
+ : null;
82
+ assertScopedSemantics(kind, scope, priorEnv, extras);
83
+
76
84
  const merged = scopeMergeRows(mod, projected, prior, scope);
77
85
  const stabilised = stabiliseRows(mod, merged, prior, epsilon);
78
86
 
79
87
  const sortedRows = mod.sortRows(stabilised);
80
88
 
81
- const priorEnv = resolvePriorEnvelope(priorEnvelope, prior);
82
89
  if (priorEnv && deepEqual(sortedRows, priorEnv.rows)) {
83
90
  // No smuggling an invalid envelope through the short-circuit.
84
91
  assertEnvelope(priorEnv);
@@ -89,15 +96,30 @@ export function write({
89
96
  kind,
90
97
  rows: sortedRows,
91
98
  kernelVersion: kernelVersion ?? currentKernelVersion(kind),
92
- extras:
93
- typeof mod.envelopeExtras === 'function'
94
- ? mod.envelopeExtras(extrasContext)
95
- : null,
99
+ extras,
96
100
  });
97
101
  assertEnvelope(envelope);
98
102
  return envelope;
99
103
  }
100
104
 
105
+ /**
106
+ * A scoped write keeps out-of-scope prior rows verbatim but stamps the
107
+ * running semantics, so across a semantics boundary it would hide a
108
+ * half-migrated baseline behind a current stamp. Refuse it.
109
+ */
110
+ function assertScopedSemantics(kind, scope, priorEnv, extras) {
111
+ const running = extras?.scoringSemantics;
112
+ if (!scope || scope.mode === 'full' || !priorEnv || !running) return;
113
+ const stamped = priorEnv.scoringSemantics ?? null;
114
+ if (stamped === running) return;
115
+ throw new Error(
116
+ `writer.write: refusing a scoped ${kind} refresh across a scoring-semantics ` +
117
+ `change (baseline=${stamped ?? '<unstamped>'} running=${running}): ` +
118
+ 'out-of-scope rows would keep the old semantics under the new stamp. ' +
119
+ 'Re-seed the whole baseline with a --full-scope refresh.',
120
+ );
121
+ }
122
+
101
123
  /** `priorEnvelope`, else `prior` when it is a whole envelope, else null. */
102
124
  function resolvePriorEnvelope(priorEnvelope, prior) {
103
125
  if (isEnvelopeObject(priorEnvelope)) return priorEnvelope;
@@ -110,8 +132,8 @@ function isEnvelopeObject(value) {
110
132
  }
111
133
 
112
134
  /**
113
- * Serialise deterministically (fixed top-level key order, two-space indent,
114
- * trailing newline) and atomically (tmp + rename).
135
+ * Serialise through the layout codec deterministically (fixed top-level key
136
+ * order, two-space indent, trailing newline) and atomically (tmp + rename).
115
137
  *
116
138
  * @param {string} absPath
117
139
  * @param {object} envelope
@@ -129,20 +151,13 @@ export function writeFile(absPath, envelope, opts = {}) {
129
151
 
130
152
  const fsImpl = opts?.fsImpl ? opts.fsImpl : fs;
131
153
 
132
- // A kind's envelope stamp reaches disk only if named here — add every new
133
- // `envelopeExtras()` key. Unset stamps are undefined and JSON omits them.
134
- const canonical = {
135
- $schema: envelope.$schema,
136
- kernelVersion: envelope.kernelVersion,
137
- scoringSemantics: envelope.scoringSemantics,
138
- tsTranspilerVersion: envelope.tsTranspilerVersion,
139
- provenanceStamped: envelope.provenanceStamped,
140
- rows: envelope.rows,
141
- };
142
-
143
- writeFileAtomic(absPath, `${JSON.stringify(canonical, null, 2)}\n`, {
144
- fsImpl,
145
- });
154
+ writeFileAtomic(
155
+ absPath,
156
+ `${JSON.stringify(encodeEnvelope(envelope), null, 2)}\n`,
157
+ {
158
+ fsImpl,
159
+ },
160
+ );
146
161
  return absPath;
147
162
  }
148
163
 
@@ -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
@@ -36,6 +40,7 @@ import {
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.
38
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.
39
44
  * @property {boolean} [readsCoverageArtifact] - Skipped once the capture deferred.
40
45
  * @property {{ cmd: string, args: string[] }} [evidenceIdentity] - Evidence argv, if not the spawned one.
41
46
  * @property {{ scope: 'delta', since: string }} [evidenceNote]
@@ -55,13 +60,16 @@ function buildChangedFileScope(baseRef) {
55
60
  /**
56
61
  * Pin the `check-baselines` compare base to `origin/<baseBranch>` via
57
62
  * `BASELINE_REF`, so drift outside the Story's diff is not a phantom
58
- * regression; matches the attribution and auto-refresh bases. `null` keeps
59
- * 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.
60
66
  *
61
67
  * @param {string|undefined|null} baseBranch
68
+ * @param {string} [baselineRef]
62
69
  * @returns {{ BASELINE_REF: string } | null}
63
70
  */
64
- function buildBaselinesGateEnv(baseBranch) {
71
+ function buildBaselinesGateEnv(baseBranch, baselineRef) {
72
+ if (baselineRef) return { BASELINE_REF: baselineRef };
65
73
  if (typeof baseBranch !== 'string' || baseBranch.length === 0) return null;
66
74
  return { BASELINE_REF: `origin/${baseBranch}` };
67
75
  }
@@ -92,7 +100,7 @@ function captureQuality(config) {
92
100
  }
93
101
 
94
102
  /**
95
- * What a capture script's over-budget exit (76) means here and in the handoff.
103
+ * What a suite's over-budget exit (76) — the capture's or `test`'s — means here and in the handoff.
96
104
  *
97
105
  * @param {object|undefined|null} config - Canonical resolved config.
98
106
  * @returns {'block'|'defer-to-ci'}
@@ -108,12 +116,35 @@ function overBudgetFlag(config) {
108
116
  : {};
109
117
  }
110
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
+
111
142
  /** Skip reason for a gate that would read the artifact a deferral never wrote. */
112
143
  export const COVERAGE_DEFERRED_SKIP_REASON = 'coverage-deferred-ci';
113
144
 
114
- /** Shown when a capture exits 76 and the policy blocks. */
145
+ /** Shown when a suite gate (the capture or `test`) exits 76 and the policy blocks. */
115
146
  export const OVER_BUDGET_BLOCK_HINT =
116
- 'The capture script 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"`.';
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"`.';
117
148
 
118
149
  /**
119
150
  * Coverage-capture registers when the coverage or CRAP gate is on AND the
@@ -145,18 +176,30 @@ function isCoverageCaptureActive(config, scripts) {
145
176
  * @param {object|undefined|null} config - Canonical resolved config.
146
177
  * @returns {Gate[]}
147
178
  */
148
- function buildTestGateEntry(coverageCaptureRunsSuite, config) {
179
+ function buildTestGateEntry(coverageCaptureRunsSuite, config, scope) {
149
180
  if (coverageCaptureRunsSuite) return [];
150
181
  // `fullSuiteLock` serializes this suite behind the host lock; when
151
182
  // coverage-capture runs instead, `runCapture` takes the lock itself.
152
- return [
153
- { name: 'test', ...resolveTestGateArgv(config), fullSuiteLock: true },
154
- ];
183
+ return [{ ...closeTestGate(config, scope), ...overBudgetFlag(config) }];
155
184
  }
156
185
 
157
186
  const CHECK_BASELINES_HINT =
158
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.';
159
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
+
160
203
  /**
161
204
  * Baselines gate names. `single` is the unsplit fail-closed fallback;
162
205
  * `independent` runs in the parallel partition, `coverage` stays serial
@@ -286,6 +329,8 @@ function buildBaselinesGateEntries({ decision, kinds, env }) {
286
329
  'text',
287
330
  ],
288
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,
289
334
  ...(env ? { env } : {}),
290
335
  ...coverageReaderFlag(gateKinds),
291
336
  });
@@ -321,13 +366,15 @@ function disabledSkip(command, gateName) {
321
366
  * Will coverage-capture take its incremental skip (no changed file under
322
367
  * `crap.targetDirs`)? If so the close would otherwise have no test gate at all.
323
368
  * Every uncertainty resolves to `false`: a wrong `false` costs one redundant
324
- * 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.
325
371
  *
326
372
  * @param {{
327
373
  * config?: object,
328
374
  * cwd?: string,
329
375
  * baseBranch?: string,
330
376
  * getChangedFilesImpl?: typeof getChangedFiles,
377
+ * resolveBaseRefImpl?: typeof resolveCaptureBaseRef,
331
378
  * }} opts
332
379
  * @returns {boolean}
333
380
  */
@@ -336,14 +383,14 @@ function predictsIncrementalCaptureSkip({
336
383
  cwd,
337
384
  baseBranch,
338
385
  getChangedFilesImpl = getChangedFiles,
386
+ resolveBaseRefImpl = resolveCaptureBaseRef,
339
387
  }) {
340
388
  // No cwd is the module-load `DEFAULT_GATES` case: never spawn git at import.
341
389
  if (typeof cwd !== 'string' || cwd.length === 0) return false;
342
390
  const { crap } = getQuality(config);
343
391
  if (crap?.incrementalCoverage?.skipWhenUnchanged !== true) return false;
344
- const ref = crap.incrementalCoverage.baseRef || baseBranch;
345
- if (typeof ref !== 'string' || ref.length === 0) return false;
346
392
  try {
393
+ const { ref } = resolveBaseRefImpl({ crap, ref: null, baseBranch, cwd });
347
394
  const changed = getChangedFilesImpl({ ref, cwd });
348
395
  // Non-array is "unknown", which `filterFilesUnderTargets` would flatten to
349
396
  // `[]` and misread as a skip.
@@ -354,9 +401,16 @@ function predictsIncrementalCaptureSkip({
354
401
  }
355
402
  }
356
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
+
357
410
  /**
358
411
  * The credited-run depositor, shared by close and `story-handoff.js`: a
359
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.
360
414
  *
361
415
  * @param {{
362
416
  * config?: object,
@@ -364,8 +418,9 @@ function predictsIncrementalCaptureSkip({
364
418
  * cwd?: string,
365
419
  * baseBranch?: string,
366
420
  * getChangedFilesImpl?: typeof getChangedFiles,
421
+ * resolveBaseRefImpl?: typeof resolveCaptureBaseRef,
367
422
  * }} opts
368
- * @returns {'coverage-capture'|'test'}
423
+ * @returns {{ depositor: 'coverage-capture'|'test', skipBranch: boolean }}
369
424
  */
370
425
  export function resolveCreditedDepositor({
371
426
  config,
@@ -373,15 +428,19 @@ export function resolveCreditedDepositor({
373
428
  cwd,
374
429
  baseBranch,
375
430
  getChangedFilesImpl,
431
+ resolveBaseRefImpl,
376
432
  }) {
377
- if (!isCoverageCaptureActive(config, scripts)) return 'test';
378
- const skip = predictsIncrementalCaptureSkip({
379
- config,
380
- cwd,
381
- baseBranch,
382
- ...(getChangedFilesImpl ? { getChangedFilesImpl } : {}),
383
- });
384
- 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);
385
444
  }
386
445
 
387
446
  /**
@@ -463,7 +522,7 @@ const QUALITY_PREVIEW_HINTS = Object.freeze({
463
522
  */
464
523
  function buildQualityPreviewGateEntries({ coverageCaptureActive, baseBranch }) {
465
524
  if (!coverageCaptureActive) return { maintainability: [], crap: [] };
466
- const ref = `origin/${baseBranch || 'main'}`;
525
+ const ref = remoteBaseRef(baseBranch || 'main');
467
526
  const entry = (half, only) => [
468
527
  {
469
528
  name: QUALITY_PREVIEW_GATE_NAMES[half],
@@ -498,7 +557,7 @@ export const GATE_TIMEOUT_HINT = `The gate outran the suite timeout (\`delivery.
498
557
  * enabled AND its capture script (`gates.coverage.captureScript`) exists; it then carries test-failure signalling and
499
558
  * the plain `test` gate is dropped, so there is always exactly one test gate.
500
559
  *
501
- * @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]
502
561
  * `cwd` is where the `package.json` and baseline-presence probes read;
503
562
  * `packageScripts` / `presentBaselines` inject those probes (tests).
504
563
  * @returns {Gate[]}
@@ -506,11 +565,13 @@ export const GATE_TIMEOUT_HINT = `The gate outran the suite timeout (\`delivery.
506
565
  export function buildDefaultGates({
507
566
  config,
508
567
  baseBranch,
568
+ baselineRef,
509
569
  cwd,
510
570
  packageScripts,
511
571
  presentBaselines,
512
572
  log,
513
573
  getChangedFilesImpl,
574
+ resolveBaseRefImpl,
514
575
  storyId,
515
576
  evidenceCwd,
516
577
  gitSpawnImpl,
@@ -540,12 +601,16 @@ export function buildDefaultGates({
540
601
  cwd,
541
602
  baseBranch,
542
603
  getChangedFilesImpl,
543
- }) === 'test';
544
- if (captureSkipPredicted) {
545
- log?.(
546
- '[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.',
547
- );
548
- }
604
+ resolveBaseRefImpl,
605
+ }).skipBranch;
606
+ const testScope = closeTestScope({
607
+ skipBranch: captureSkipPredicted,
608
+ config,
609
+ cwd,
610
+ baseBranch,
611
+ gitSpawnImpl,
612
+ log,
613
+ });
549
614
  const typecheck = resolveGateCommand(config, 'typecheck');
550
615
  const lint = resolveGateCommand(config, 'lint');
551
616
  const format = resolveGateCommand(config, 'formatCheck');
@@ -553,7 +618,7 @@ export function buildDefaultGates({
553
618
  const formatChangedFileScope = isDefaultFormatCheck(format.raw)
554
619
  ? buildChangedFileScope(baseBranch)
555
620
  : null;
556
- const baselinesGateEnv = buildBaselinesGateEnv(baseBranch);
621
+ const baselinesGateEnv = buildBaselinesGateEnv(baseBranch, baselineRef);
557
622
  const baselineKinds = enabledBaselineKinds(config);
558
623
  const baselinesDecision = probeBaselinesGate({
559
624
  config,
@@ -591,6 +656,7 @@ export function buildDefaultGates({
591
656
  testCredited,
592
657
  }),
593
658
  config,
659
+ testScope,
594
660
  ),
595
661
  {
596
662
  name: 'format',
@@ -614,7 +680,7 @@ export function buildDefaultGates({
614
680
  ...overBudgetFlag(config),
615
681
  ...(captureSkipPredicted
616
682
  ? { skip: { reason: 'incremental-no-crap-changes' } }
617
- : {}),
683
+ : suiteOfRecordFlag(config)),
618
684
  },
619
685
  ]
620
686
  : []),
@@ -646,6 +712,16 @@ const INDEPENDENT_GATE_NAMES = new Set([
646
712
  QUALITY_PREVIEW_GATE_NAMES.maintainability,
647
713
  ]);
648
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
+
649
725
  /**
650
726
  * Order is preserved within each bucket.
651
727
  *
@@ -656,7 +732,7 @@ export function partitionGates(gates) {
656
732
  const independent = [];
657
733
  const serial = [];
658
734
  for (const gate of gates) {
659
- if (INDEPENDENT_GATE_NAMES.has(gate.name)) independent.push(gate);
735
+ if (isIndependentGate(gate.name)) independent.push(gate);
660
736
  else serial.push(gate);
661
737
  }
662
738
  return { independent, serial };