mandrel 2.111.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 (178) 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 +351 -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/preview-gates.js +29 -10
  38. package/.agents/scripts/lib/baselines/reader.js +36 -9
  39. package/.agents/scripts/lib/baselines/refresh-service.js +79 -18
  40. package/.agents/scripts/lib/baselines/seat-missing.js +173 -7
  41. package/.agents/scripts/lib/baselines/writer.js +36 -21
  42. package/.agents/scripts/lib/changed-files.js +70 -6
  43. package/.agents/scripts/lib/child-exec.js +10 -0
  44. package/.agents/scripts/lib/claude/agents-projection.js +5 -5
  45. package/.agents/scripts/lib/close-lock-events.js +8 -3
  46. package/.agents/scripts/lib/close-validation/ci-deferral.js +40 -0
  47. package/.agents/scripts/lib/close-validation/gates.js +111 -35
  48. package/.agents/scripts/lib/close-validation/process.js +16 -7
  49. package/.agents/scripts/lib/close-validation/projections/crap.js +43 -10
  50. package/.agents/scripts/lib/close-validation/runner.js +55 -23
  51. package/.agents/scripts/lib/close-validation/skip-branch-test.js +144 -0
  52. package/.agents/scripts/lib/close-validation/test-delta.js +33 -8
  53. package/.agents/scripts/lib/codex/agents-projection.js +6 -0
  54. package/.agents/scripts/lib/config/agentrc-overlay.js +9 -5
  55. package/.agents/scripts/lib/config/explain.js +5 -2
  56. package/.agents/scripts/lib/config/gates/coverage.schema.js +45 -1
  57. package/.agents/scripts/lib/config/gates/crap-incremental-coverage.schema.js +1 -1
  58. package/.agents/scripts/lib/config/git-roots.js +38 -4
  59. package/.agents/scripts/lib/config/handoff.js +24 -0
  60. package/.agents/scripts/lib/config/quality.js +26 -13
  61. package/.agents/scripts/lib/config/worktree-isolation.js +2 -5
  62. package/.agents/scripts/lib/config-resolver.js +22 -2
  63. package/.agents/scripts/lib/config-settings-schema-delivery.js +87 -4
  64. package/.agents/scripts/lib/config-settings-schema-quality.js +36 -1
  65. package/.agents/scripts/lib/config-settings-schema.js +1 -1
  66. package/.agents/scripts/lib/coverage-capture-affected.js +1 -0
  67. package/.agents/scripts/lib/coverage-capture-delta.js +164 -32
  68. package/.agents/scripts/lib/coverage-capture-own-fix.js +232 -0
  69. package/.agents/scripts/lib/coverage-capture-usage.js +2 -2
  70. package/.agents/scripts/lib/coverage-capture.js +15 -0
  71. package/.agents/scripts/lib/coverage-deferral.js +96 -0
  72. package/.agents/scripts/lib/coverage-ratchet.js +187 -0
  73. package/.agents/scripts/lib/crap-baseline-join.js +5 -5
  74. package/.agents/scripts/lib/crap-engine.js +3 -3
  75. package/.agents/scripts/lib/crap-method-identity.js +104 -48
  76. package/.agents/scripts/lib/escomplex-anchor.js +135 -0
  77. package/.agents/scripts/lib/escomplex-kernel.js +30 -1
  78. package/.agents/scripts/lib/failure-rows.js +121 -0
  79. package/.agents/scripts/lib/full-suite-lock.js +44 -4
  80. package/.agents/scripts/lib/full-suite-queue.js +89 -13
  81. package/.agents/scripts/lib/generated/agentrc-validator.js +8 -2
  82. package/.agents/scripts/lib/gh-env.js +3 -6
  83. package/.agents/scripts/lib/gh-pr-rest.js +1 -0
  84. package/.agents/scripts/lib/git/base-sync-probe.js +182 -0
  85. package/.agents/scripts/lib/git-branch-lifecycle.js +9 -0
  86. package/.agents/scripts/lib/observability/close-telemetry.js +37 -2
  87. package/.agents/scripts/lib/observability/handoff-telemetry.js +170 -0
  88. package/.agents/scripts/lib/observability/review-dispositions.js +23 -6
  89. package/.agents/scripts/lib/observability/runtime-friction.js +17 -4
  90. package/.agents/scripts/lib/observability/source-classifier.js +3 -0
  91. package/.agents/scripts/lib/observability/story-outcome.js +393 -0
  92. package/.agents/scripts/lib/orchestration/check-baselines/phases/compare.js +2 -1
  93. package/.agents/scripts/lib/orchestration/check-baselines/phases/evaluate.js +19 -1
  94. package/.agents/scripts/lib/orchestration/check-baselines/phases/fail-detail.js +84 -0
  95. package/.agents/scripts/lib/orchestration/check-baselines/phases/pipeline.js +14 -5
  96. package/.agents/scripts/lib/orchestration/check-baselines/phases/refresh-ack.js +3 -2
  97. package/.agents/scripts/lib/orchestration/check-baselines/phases/report.js +26 -6
  98. package/.agents/scripts/lib/orchestration/code-review.js +223 -19
  99. package/.agents/scripts/lib/orchestration/handoff-gates.js +129 -62
  100. package/.agents/scripts/lib/orchestration/handoff-rescore.js +169 -0
  101. package/.agents/scripts/lib/orchestration/handoff-suite-of-record.js +45 -0
  102. package/.agents/scripts/lib/orchestration/preflight-lanes.js +208 -0
  103. package/.agents/scripts/lib/orchestration/review-base-ref.js +40 -17
  104. package/.agents/scripts/lib/orchestration/review-deposit.js +38 -12
  105. package/.agents/scripts/lib/orchestration/review-depth.js +21 -0
  106. package/.agents/scripts/lib/orchestration/review-history.js +124 -20
  107. package/.agents/scripts/lib/orchestration/review-providers/claude-verdict.js +23 -8
  108. package/.agents/scripts/lib/orchestration/review-providers/code-review.js +82 -39
  109. package/.agents/scripts/lib/orchestration/review-providers/critical-verifier.js +64 -11
  110. package/.agents/scripts/lib/orchestration/review-providers/degraded-gates.js +98 -3
  111. package/.agents/scripts/lib/orchestration/review-providers/finding-identity.js +6 -2
  112. package/.agents/scripts/lib/orchestration/review-providers/findings-renderer.js +55 -8
  113. package/.agents/scripts/lib/orchestration/review-providers/review-guidance.js +1 -0
  114. package/.agents/scripts/lib/orchestration/review-providers/review-provider-factory.js +42 -15
  115. package/.agents/scripts/lib/orchestration/review-providers/types.js +6 -0
  116. package/.agents/scripts/lib/orchestration/single-story-close/failed-terminal.js +10 -1
  117. package/.agents/scripts/lib/orchestration/single-story-close/gate-log.js +10 -0
  118. package/.agents/scripts/lib/orchestration/single-story-close/phases/base-sync.js +7 -4
  119. package/.agents/scripts/lib/orchestration/single-story-close/phases/close-validation.js +15 -3
  120. package/.agents/scripts/lib/orchestration/single-story-close/phases/code-review.js +59 -2
  121. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +6 -0
  122. package/.agents/scripts/lib/orchestration/single-story-close/phases/finish.js +15 -4
  123. package/.agents/scripts/lib/orchestration/single-story-close/phases/land-review-record.js +213 -0
  124. package/.agents/scripts/lib/orchestration/single-story-close/phases/normalize-pr-title.js +9 -12
  125. package/.agents/scripts/lib/orchestration/single-story-close/phases/open-pr.js +26 -12
  126. package/.agents/scripts/lib/orchestration/single-story-close/phases/post-land.js +51 -26
  127. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +3 -2
  128. package/.agents/scripts/lib/orchestration/single-story-close/phases/pull-request.js +50 -17
  129. package/.agents/scripts/lib/orchestration/single-story-close/phases/push.js +59 -11
  130. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +1 -0
  131. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-block.js +31 -13
  132. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-halt.js +29 -6
  133. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-outcome.js +10 -12
  134. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-override.js +19 -4
  135. package/.agents/scripts/lib/orchestration/single-story-close/result.js +30 -13
  136. package/.agents/scripts/lib/orchestration/single-story-close/review-overlap.js +73 -39
  137. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +11 -3
  138. package/.agents/scripts/lib/orchestration/story-close/baseline-upward-writeback.js +3 -2
  139. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +20 -8
  140. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +7 -0
  141. package/.agents/scripts/lib/orchestration/story-handoff.js +774 -196
  142. package/.agents/scripts/lib/orchestration/ticketing/reads.js +2 -0
  143. package/.agents/scripts/lib/pr-body-lines.js +32 -0
  144. package/.agents/scripts/lib/single-story/ci-ratchet-gate.js +140 -0
  145. package/.agents/scripts/lib/single-story/confirm-and-land.js +17 -7
  146. package/.agents/scripts/lib/single-story/confirm-merge.js +12 -3
  147. package/.agents/scripts/lib/single-story-sweep/report-stalled-executing.js +202 -0
  148. package/.agents/scripts/lib/standalone-ratchets.js +37 -0
  149. package/.agents/scripts/lib/suite-admission.js +20 -8
  150. package/.agents/scripts/lib/suite-sizing.js +146 -0
  151. package/.agents/scripts/lib/workspace-provisioner.js +2 -2
  152. package/.agents/scripts/merge-baseline.js +14 -3
  153. package/.agents/scripts/providers/github/comments.js +19 -3
  154. package/.agents/scripts/providers/github.js +1 -0
  155. package/.agents/scripts/review-dispositions-report.js +1 -1
  156. package/.agents/scripts/role-scope-guard.js +267 -0
  157. package/.agents/scripts/single-story-close.js +4 -4
  158. package/.agents/scripts/single-story-confirm-merge.js +31 -5
  159. package/.agents/scripts/single-story-init.js +24 -4
  160. package/.agents/scripts/story-handoff.js +3 -3
  161. package/.agents/scripts/story-outcomes-report.js +231 -0
  162. package/.agents/scripts/story-review-compute.js +9 -5
  163. package/.agents/scripts/update-coverage-baseline.js +12 -2
  164. package/.agents/scripts/update-crap-baseline.js +9 -1
  165. package/.agents/workflows/helpers/code-review.md +63 -9
  166. package/.agents/workflows/helpers/deliver-digest.md +53 -54
  167. package/.agents/workflows/helpers/deliver-reference.md +233 -67
  168. package/.agents/workflows/helpers/deliver-story-reference.md +19 -8
  169. package/.agents/workflows/helpers/deliver-story.md +7 -2
  170. package/.agents/workflows/helpers/parallel-tooling.md +29 -0
  171. package/docs/CHANGELOG.md +46 -0
  172. package/lib/cli/doctor-checks/coverage-ratchet.js +54 -0
  173. package/lib/cli/doctor-checks/effective-agentrc.js +23 -0
  174. package/lib/cli/doctor-checks/llm-review.js +2 -11
  175. package/lib/cli/doctor-checks/sync-parity.js +5 -1
  176. package/lib/cli/doctor-checks/test-credit-path.js +7 -2
  177. package/lib/cli/registry.js +5 -0
  178. package/package.json +1 -1
@@ -1,11 +1,13 @@
1
1
  /**
2
2
  * Delta refresh for `captureScope: "affected"`: after a base-sync merges main
3
- * commits that share no file with the Story, re-measure only those commits'
4
- * tests instead of re-running the Story's whole affected scope. Every
3
+ * commits, re-measure only those commits' tests instead of re-running the
4
+ * Story's whole affected scope. A delta sharing a file with the Story
5
+ * qualifies only when no Story commit landed since the stamp. Every
5
6
  * uncertainty fails closed to an ordinary capture.
6
7
  */
7
8
  import fs from 'node:fs';
8
9
  import path from 'node:path';
10
+ import picomatch from 'picomatch';
9
11
  import { getQuality } from './config/quality.js';
10
12
  import {
11
13
  captureStampPath,
@@ -14,6 +16,7 @@ import {
14
16
  filterSuiteInputPaths,
15
17
  stampIsStale,
16
18
  } from './coverage-capture.js';
19
+ import { judgeOwnFix } from './coverage-capture-own-fix.js';
17
20
  import { gitSpawn } from './git-utils.js';
18
21
 
19
22
  /** Basenames whose change moves coverage beyond the files it names. */
@@ -121,12 +124,25 @@ function treeIneligibility({ cwd, commit, spawn }) {
121
124
  return null;
122
125
  }
123
126
 
124
- function overlapReason(suite, storyFiles, coveragePath) {
125
- const story = new Set(filterSuiteInputPaths(storyFiles, coveragePath));
126
- const shared = suite.find((f) => story.has(f));
127
- if (shared) return `delta shares ${shared} with the Story's change set`;
128
- const config = suite.find(isCoverageConfigFile);
129
- return config ? `delta touches coverage-determining config ${config}` : null;
127
+ /** `nonInputGlobs` as a predicate; an unset list matches nothing. */
128
+ function nonInputMatcher(globs) {
129
+ return Array.isArray(globs) && globs.length > 0
130
+ ? picomatch(globs, { dot: true })
131
+ : () => false;
132
+ }
133
+
134
+ /** Suite inputs with the consumer's non-input globs dropped. */
135
+ function ruleInputs({ delta, storyFiles, coveragePath, nonInputGlobs }) {
136
+ const isNonInput = nonInputMatcher(nonInputGlobs);
137
+ const keep = (files) =>
138
+ filterSuiteInputPaths(files, coveragePath).filter((f) => !isNonInput(f));
139
+ const suite = filterSuiteInputPaths(delta, coveragePath);
140
+ const inputs = suite.filter((f) => !isNonInput(f));
141
+ const dropped = {
142
+ baseline: delta.length - suite.length,
143
+ globs: suite.length - inputs.length,
144
+ };
145
+ return { suite, inputs, story: new Set(keep(storyFiles)), dropped };
130
146
  }
131
147
 
132
148
  function emptinessReason(delta, suite) {
@@ -134,28 +150,85 @@ function emptinessReason(delta, suite) {
134
150
  return suite.length === 0 ? 'delta has no suite-input path' : null;
135
151
  }
136
152
 
153
+ function ownCommitsWhy(commits) {
154
+ if (!commits) {
155
+ return "the base ref is unresolvable, so the Story's own commits since the stamp cannot be ruled out";
156
+ }
157
+ const shas = commits.map((c) => c.slice(0, 12)).join(', ');
158
+ return `the Story's own commit(s) since the stamp: ${shas}`;
159
+ }
160
+
161
+ /** Without an `ownCommits` probe (close) any overlap refuses. */
162
+ function overlapRule(shared, ownCommits) {
163
+ const reason = `delta shares ${shared} with the Story's change set`;
164
+ if (!ownCommits) return { rule: 'overlap', reason };
165
+ const commits = ownCommits();
166
+ if (commits?.length === 0) return null;
167
+ return {
168
+ rule: 'own-commits',
169
+ reason: `${reason} and ${ownCommitsWhy(commits)}`,
170
+ };
171
+ }
172
+
173
+ function configRule(suite, configHandled) {
174
+ const config = configHandled ? null : suite.find(isCoverageConfigFile);
175
+ if (!config) return null;
176
+ return {
177
+ rule: 'config',
178
+ reason: `delta touches coverage-determining config ${config}`,
179
+ };
180
+ }
181
+
137
182
  /**
138
183
  * Shared with close's `test` delta re-credit. Only suite inputs count, so
139
- * baseline and coverage-directory paths never overlap.
184
+ * baseline and coverage-directory paths never overlap; `nonInputGlobs`
185
+ * paths never overlap either.
140
186
  *
141
- * @returns {{ reason: string | null, delta: string[], dropped: number }}
187
+ * @returns {{ rule: string, reason: string | null, delta: string[], dropped: { baseline: number, globs: number }, overlap: number }}
142
188
  */
143
- function deltaIneligibility({ delta, storyFiles, coveragePath }) {
144
- const suite = filterSuiteInputPaths(delta, coveragePath);
145
- const reason =
146
- emptinessReason(delta, suite) ??
147
- overlapReason(suite, storyFiles, coveragePath);
148
- return { reason, delta: suite, dropped: delta.length - suite.length };
189
+ function deltaIneligibility({
190
+ delta,
191
+ storyFiles,
192
+ coveragePath,
193
+ nonInputGlobs,
194
+ configHandled = false,
195
+ ownCommits,
196
+ }) {
197
+ const f = ruleInputs({ delta, storyFiles, coveragePath, nonInputGlobs });
198
+ const shared = f.inputs.filter((p) => f.story.has(p));
199
+ const empty = emptinessReason(delta, f.suite);
200
+ const decided =
201
+ (empty && { rule: 'empty', reason: empty }) ||
202
+ (shared.length > 0 && overlapRule(shared[0], ownCommits)) ||
203
+ configRule(f.suite, configHandled);
204
+ const pass = {
205
+ rule: shared.length > 0 ? 'overlap' : 'disjoint',
206
+ reason: null,
207
+ };
208
+ return {
209
+ delta: f.inputs,
210
+ dropped: f.dropped,
211
+ overlap: shared.length,
212
+ ...(decided || pass),
213
+ };
149
214
  }
150
215
 
151
- /** The rule's reason for close, on the configured coverage path. */
216
+ /** The rule's reason for close, on the configured coverage path; config always refuses. */
152
217
  export function closeDeltaIneligibility({ delta, storyFiles, config }) {
153
- const coveragePath = getQuality(config)?.crap?.coveragePath;
154
- return deltaIneligibility({ delta, storyFiles, coveragePath }).reason;
218
+ const quality = getQuality(config);
219
+ return deltaIneligibility({
220
+ delta,
221
+ storyFiles,
222
+ coveragePath: quality?.crap?.coveragePath,
223
+ nonInputGlobs: quality?.coverage?.nonInputGlobs,
224
+ }).reason;
155
225
  }
156
226
 
157
- function droppedSuffix(dropped) {
158
- return dropped > 0 ? `, ${dropped} non-suite-input path(s) dropped` : '';
227
+ /** Which rule decided, the delta size and what each filter dropped. */
228
+ function ruleCounts(rule, name = rule.rule) {
229
+ const overlap =
230
+ rule.overlap > 0 ? `; ${rule.overlap} Story file(s) overlapped` : '';
231
+ return `rule: ${name}; delta: ${rule.delta.length} file(s); dropped: ${rule.dropped.baseline} baseline/coverage-dir, ${rule.dropped.globs} nonInputGlobs${overlap}`;
159
232
  }
160
233
 
161
234
  function parseNames(stdout) {
@@ -172,19 +245,65 @@ function stampStale({ stamp, cwd, crap, computeContentDigestImpl }) {
172
245
  return stampIsStale({ stamp, current, cwd, coveragePath: crap.coveragePath });
173
246
  }
174
247
 
248
+ /** Non-merge commits since the stamp that the base lacks; `null` when unknown. */
249
+ function storyOwnCommits({ cwd, commit, baseRef, spawn }) {
250
+ if (typeof baseRef !== 'string' || baseRef.length === 0) return null;
251
+ const res = git(
252
+ cwd,
253
+ ['rev-list', '--no-merges', `${commit}..HEAD`, `^${baseRef}`],
254
+ spawn,
255
+ );
256
+ return res?.status === 0 ? parseNames(res.stdout) : null;
257
+ }
258
+
259
+ /** Today's refusal unless the opt-in own-fix split accepts the delta. */
260
+ function refusedUnlessOwnFix(opts) {
261
+ const isConfig = isCoverageConfigFile;
262
+ return judgeOwnFix({ ...opts, isConfig, formatFreshnessDetail });
263
+ }
264
+
265
+ /** A config-free delta the rule fully excused only needs a re-stamp. */
266
+ function canRestamp(rule, delta) {
267
+ if (rule.delta.length > 0 || delta.length === 0) return false;
268
+ return !delta.some(isCoverageConfigFile);
269
+ }
270
+
175
271
  /** Main's committed delta since the stamp, judged by the shared rule. */
176
- function classifyCommittedDelta({ cwd, crap, storyFiles, stamp, spawn }) {
272
+ function classifyCommittedDelta({
273
+ cwd,
274
+ crap,
275
+ coverage,
276
+ storyFiles,
277
+ stamp,
278
+ baseRef,
279
+ spawn,
280
+ }) {
177
281
  const { commit } = stamp;
178
282
  const no = (reason, rule) => ({ eligible: false, reason, stamp, rule });
179
283
  const diff = git(cwd, ['diff', '--name-only', commit, 'HEAD'], spawn);
180
284
  if (diff?.status !== 0) return no('git diff failed');
285
+ const delta = parseNames(diff.stdout);
181
286
  const rule = deltaIneligibility({
182
- delta: parseNames(diff.stdout),
287
+ delta,
183
288
  storyFiles,
184
289
  coveragePath: crap.coveragePath,
290
+ nonInputGlobs: coverage?.nonInputGlobs,
291
+ configHandled: coverage?.captureHandlesConfigChanges === true,
292
+ ownCommits: () => storyOwnCommits({ cwd, commit, baseRef, spawn }),
185
293
  });
186
- const restamp = rule.delta.length === 0 && rule.dropped > 0;
187
- if (rule.reason && !restamp) return no(rule.reason, rule);
294
+ const restamp = canRestamp(rule, delta);
295
+ const opts = {
296
+ cwd,
297
+ crap,
298
+ coverage,
299
+ storyFiles,
300
+ stamp,
301
+ rule,
302
+ baseRef,
303
+ spawn,
304
+ no,
305
+ };
306
+ if (rule.reason && !restamp) return refusedUnlessOwnFix(opts);
188
307
  return { eligible: true, restamp, commit, rule, stamp };
189
308
  }
190
309
 
@@ -192,8 +311,10 @@ function classifyCommittedDelta({ cwd, crap, storyFiles, stamp, spawn }) {
192
311
  function classifyDeltaRefresh({
193
312
  cwd,
194
313
  crap,
314
+ coverage,
195
315
  storyFiles,
196
316
  prior,
317
+ baseRef,
197
318
  gitSpawnImpl: spawn = gitSpawn,
198
319
  readFileSync = fs.readFileSync,
199
320
  computeContentDigestImpl = computeContentDigest,
@@ -207,12 +328,20 @@ function classifyDeltaRefresh({
207
328
  if (!prior) return no('no prior artifact to merge over');
208
329
  const treeReason = treeIneligibility({ cwd, commit: stamp.commit, spawn });
209
330
  if (treeReason) return no(treeReason);
210
- return classifyCommittedDelta({ cwd, crap, storyFiles, stamp, spawn });
331
+ return classifyCommittedDelta({
332
+ cwd,
333
+ crap,
334
+ coverage,
335
+ storyFiles,
336
+ stamp,
337
+ baseRef,
338
+ spawn,
339
+ });
211
340
  }
212
341
 
342
+ /** A refusal before any delta was read names the `precondition` rule. */
213
343
  function deltaCounts(rule) {
214
- if (!rule) return '';
215
- return `; delta: ${rule.delta.length} file(s)${droppedSuffix(rule.dropped)}`;
344
+ return `; ${rule ? ruleCounts(rule) : 'rule: precondition'}`;
216
345
  }
217
346
 
218
347
  const skipRun = async () => 0;
@@ -220,10 +349,10 @@ const skipRun = async () => 0;
220
349
  function reportPlan(plan, crap, logger) {
221
350
  const at = `[coverage-capture] Coverage at ${crap.coveragePath}`;
222
351
  const since = plan.commit.slice(0, 12);
223
- const dropped = droppedSuffix(plan.rule.dropped);
352
+ const counts = ruleCounts(plan.rule, plan.restamp ? 'restamp' : undefined);
224
353
  if (plan.restamp) {
225
354
  logger.info(
226
- `${at} needs only a restamp — every path changed since ${since} is a non-suite input (delta: 0 file(s)${dropped}).`,
355
+ `${at} needs only a restamp — every path changed since ${since} is a non-suite input (${counts}).`,
227
356
  );
228
357
  // A no-op run over the prior artifact only rewrites the stamp.
229
358
  return { baseRef: plan.commit, dropFiles: [], runCaptureImpl: skipRun };
@@ -236,7 +365,7 @@ function reportPlan(plan, crap, logger) {
236
365
  deltaFiles: files.length,
237
366
  });
238
367
  logger.info(
239
- `${at} needs a delta refresh — re-measuring ${files.length} file(s) changed since ${since}${dropped}. ${detail}`,
368
+ `${at} needs a delta refresh — re-measuring ${files.length} file(s) changed since ${since} (${counts}). ${detail}`,
240
369
  );
241
370
  return { baseRef: plan.commit, dropFiles: files };
242
371
  }
@@ -251,6 +380,7 @@ function reportPlan(plan, crap, logger) {
251
380
  export function planDeltaRefresh({
252
381
  freshness,
253
382
  crap,
383
+ coverage,
254
384
  args,
255
385
  changed,
256
386
  prior,
@@ -261,10 +391,12 @@ export function planDeltaRefresh({
261
391
  const plan = classifyDeltaRefreshImpl({
262
392
  cwd: args.cwd,
263
393
  crap,
394
+ coverage,
264
395
  storyFiles: changed,
265
396
  prior,
397
+ baseRef: args.baseBranchRef,
266
398
  });
267
- if (plan.eligible) return reportPlan(plan, crap, logger);
399
+ if (plan.eligible) return (plan.report ?? reportPlan)(plan, crap, logger);
268
400
  logger.info(
269
401
  `[coverage-capture] Affected mode: delta refresh not eligible (${plan.reason}${deltaCounts(plan.rule)}) — capturing the Story's affected scope.`,
270
402
  );
@@ -0,0 +1,232 @@
1
+ /**
2
+ * Own-fix split for the affected coverage delta refresh, opted into by
3
+ * `coverage.ownFixDeltaMaxFiles`. HEAD's first-parent chain back to the
4
+ * stamp splits into base-sync merges (the base part) and the Story's own
5
+ * non-merge commits (the own part); only a narrow, guarded shape is
6
+ * eligible, and every uncertainty refuses.
7
+ */
8
+
9
+ import picomatch from 'picomatch';
10
+ import { filterSuiteInputPaths } from './coverage-capture.js';
11
+
12
+ const TEST_FILE_RE = /\.(test|spec)\.[cm]?[jt]sx?$/;
13
+ const TEST_DIR_RE = /(^|\/)(tests?|__tests__|spec|e2e)\//;
14
+
15
+ /** Mirrors the audit-suite selector's test-file predicate. */
16
+ function isTestPath(file) {
17
+ return TEST_FILE_RE.test(file) || TEST_DIR_RE.test(file);
18
+ }
19
+
20
+ function refuse(reason) {
21
+ throw new Error(reason);
22
+ }
23
+
24
+ function lines(stdout) {
25
+ return String(stdout ?? '')
26
+ .split('\n')
27
+ .map((l) => l.trim().replace(/\\/g, '/'))
28
+ .filter((l) => l.length > 0);
29
+ }
30
+
31
+ function git(ctx, args) {
32
+ const res = ctx.spawn(ctx.cwd, ...args);
33
+ return { status: res?.status ?? 1, stdout: res?.stdout ?? '' };
34
+ }
35
+
36
+ /** stdout of a git call that must succeed. */
37
+ function must(ctx, args) {
38
+ const res = git(ctx, args);
39
+ if (res.status !== 0) refuse(`git ${args[0]} failed`);
40
+ return res.stdout;
41
+ }
42
+
43
+ const short = (sha) => sha.slice(0, 12);
44
+
45
+ /** `[sha, ...parents]` per step, newest first, rooted on the stamp. */
46
+ function firstParentChain(ctx) {
47
+ const steps = lines(
48
+ must(ctx, [
49
+ 'rev-list',
50
+ '--first-parent',
51
+ '--parents',
52
+ `${ctx.commit}..HEAD`,
53
+ ]),
54
+ ).map((l) => l.split(/\s+/));
55
+ if (steps.at(-1)?.[1] !== ctx.commit) {
56
+ refuse("stamp is not on HEAD's first-parent chain");
57
+ }
58
+ return steps;
59
+ }
60
+
61
+ /** A non-merge commit the base already holds was fast-forwarded in. */
62
+ function assertNotOnBase(ctx, sha) {
63
+ if (!ctx.ref) refuse('no base ref to attribute own commits against');
64
+ const { status } = git(ctx, ['merge-base', '--is-ancestor', sha, ctx.ref]);
65
+ if (status === 0)
66
+ refuse(`own commit ${short(sha)} is reachable from ${ctx.ref}`);
67
+ if (status !== 1)
68
+ refuse(`cannot test own commit ${short(sha)} against ${ctx.ref}`);
69
+ }
70
+
71
+ function ownChanges(ctx, sha) {
72
+ assertNotOnBase(ctx, sha);
73
+ const out = must(ctx, [
74
+ 'diff-tree',
75
+ '-r',
76
+ '-M',
77
+ '--name-status',
78
+ '--no-commit-id',
79
+ sha,
80
+ ]);
81
+ return lines(out).map((l) => {
82
+ const [status, ...paths] = l.split('\t');
83
+ return { sha, status: status.charAt(0), paths };
84
+ });
85
+ }
86
+
87
+ function splitParts(ctx) {
88
+ const base = new Set();
89
+ const own = [];
90
+ for (const [sha, ...parents] of firstParentChain(ctx)) {
91
+ if (parents.length > 1) {
92
+ for (const f of lines(
93
+ must(ctx, ['diff', '--name-only', parents[0], sha]),
94
+ ))
95
+ base.add(f);
96
+ } else {
97
+ own.push(...ownChanges(ctx, sha));
98
+ }
99
+ }
100
+ return { base: [...base], own };
101
+ }
102
+
103
+ function judgeBase(ctx, base) {
104
+ const shared = ctx.inputs(base).find((f) => ctx.story.has(f));
105
+ if (shared) refuse(`base part shares ${shared} with the Story's change set`);
106
+ const config = ctx.configHandled ? null : ctx.suite(base).find(ctx.isConfig);
107
+ if (config) refuse(`base part touches coverage-determining config ${config}`);
108
+ }
109
+
110
+ function judgeOwnChanges(ctx, own) {
111
+ const paths = [...new Set(own.flatMap((c) => c.paths))];
112
+ const config = ctx.suite(paths).find(ctx.isConfig);
113
+ if (config) refuse(`own part touches coverage-determining config ${config}`);
114
+ for (const c of own) {
115
+ const moved = c.status === 'D' || c.status === 'R';
116
+ const input = moved && ctx.suite(c.paths)[0];
117
+ if (input) refuse(`own commit ${short(c.sha)} deletes or renames ${input}`);
118
+ }
119
+ return ctx.inputs(paths).filter((f) => ctx.delta.has(f));
120
+ }
121
+
122
+ /** A weakened test is how a row outside the delta goes stale high. */
123
+ function judgeOwnTests(ctx, files) {
124
+ const tests = files.filter(isTestPath);
125
+ if (tests.length === 0) return;
126
+ const out = must(ctx, [
127
+ 'diff',
128
+ '--numstat',
129
+ ctx.commit,
130
+ 'HEAD',
131
+ '--',
132
+ ...tests,
133
+ ]);
134
+ for (const [added, deleted, file] of lines(out).map((l) => l.split('\t'))) {
135
+ if (added === '-' || Number(deleted) > Number(added)) {
136
+ refuse(`own part removes lines from test file ${file}`);
137
+ }
138
+ }
139
+ }
140
+
141
+ function judge(ctx, { base, own }) {
142
+ judgeBase(ctx, base);
143
+ const ownFiles = judgeOwnChanges(ctx, own);
144
+ if (ownFiles.length > ctx.max) {
145
+ refuse(
146
+ `own part has ${ownFiles.length} suite-input file(s), over ownFixDeltaMaxFiles ${ctx.max}`,
147
+ );
148
+ }
149
+ judgeOwnTests(ctx, ownFiles);
150
+ const baseFiles = ctx.inputs(base).filter((f) => ctx.delta.has(f));
151
+ return { own: ownFiles.length, base: baseFiles.length };
152
+ }
153
+
154
+ /**
155
+ * @param {{ cwd: string, commit: string, ref: string | null, spawn: Function, max: number, delta: Set<string>, story: Set<string>, suite: (f: string[]) => string[], inputs: (f: string[]) => string[], isConfig: (f: string) => boolean, configHandled: boolean }} ctx
156
+ * @returns {{ ok: true, own: number, base: number } | { ok: false, reason: string }}
157
+ */
158
+ function classifyOwnFix(ctx) {
159
+ try {
160
+ return { ok: true, ...judge(ctx, splitParts(ctx)) };
161
+ } catch (err) {
162
+ return { ok: false, reason: `own-fix: ${err?.message ?? err}` };
163
+ }
164
+ }
165
+
166
+ /** Refusals the split may re-judge; any other refusal stands. */
167
+ const REJUDGED = new Set(['overlap', 'own-commits', 'config']);
168
+
169
+ function ownFixContext({
170
+ cwd,
171
+ crap,
172
+ coverage,
173
+ storyFiles,
174
+ stamp,
175
+ rule,
176
+ baseRef,
177
+ spawn,
178
+ isConfig,
179
+ }) {
180
+ const isNonInput =
181
+ coverage.nonInputGlobs?.length > 0
182
+ ? picomatch(coverage.nonInputGlobs, { dot: true })
183
+ : () => false;
184
+ const suite = (files) => filterSuiteInputPaths(files, crap.coveragePath);
185
+ return {
186
+ cwd,
187
+ commit: stamp.commit,
188
+ ref: baseRef,
189
+ spawn,
190
+ max: coverage.ownFixDeltaMaxFiles,
191
+ delta: new Set(rule.delta),
192
+ story: new Set(storyFiles),
193
+ suite,
194
+ inputs: (files) => suite(files).filter((f) => !isNonInput(f)),
195
+ isConfig,
196
+ configHandled: coverage.captureHandlesConfigChanges === true,
197
+ };
198
+ }
199
+
200
+ /** The eligible plan's log line, distinct so the hit rate is countable. */
201
+ function reportOwnFix(plan, crap, logger, formatFreshnessDetail) {
202
+ const files = plan.rule.delta;
203
+ const detail = formatFreshnessDetail({
204
+ stamp: plan.stamp,
205
+ requiredScope: 'affected',
206
+ verdict: 'own-fix-delta-refresh',
207
+ deltaFiles: files.length,
208
+ });
209
+ logger.info(
210
+ `[coverage-capture] Coverage at ${crap.coveragePath} needs an own-fix delta refresh — re-measuring ${files.length} file(s) changed since ${short(plan.commit)} (${plan.ownFix.own} own file(s), ${plan.ownFix.base} base file(s)). ${detail}`,
211
+ );
212
+ return { baseRef: plan.commit, dropFiles: files };
213
+ }
214
+
215
+ /**
216
+ * The verdict on a delta today's rule refused: that refusal stands, with no
217
+ * git command run, unless `ownFixDeltaMaxFiles` is set and the refusal was
218
+ * a Story overlap or config; then the own-fix split decides.
219
+ */
220
+ export function judgeOwnFix(opts) {
221
+ const { coverage, rule, stamp } = opts;
222
+ const no = (reason) => opts.no(reason, rule);
223
+ if (!(coverage?.ownFixDeltaMaxFiles >= 1) || !REJUDGED.has(rule.rule)) {
224
+ return no(rule.reason);
225
+ }
226
+ const own = classifyOwnFix(ownFixContext(opts));
227
+ if (!own.ok) return no(own.reason);
228
+ const plan = { eligible: true, restamp: false, commit: stamp.commit };
229
+ const report = (p, crap, logger) =>
230
+ reportOwnFix(p, crap, logger, opts.formatFreshnessDetail);
231
+ return { ...plan, rule, stamp, ownFix: own, report };
232
+ }
@@ -14,7 +14,7 @@ const COVERAGE_CAPTURE_USAGE = {
14
14
  invocation:
15
15
  'node .agents/scripts/coverage-capture.js [--skip-when-no-crap-files] [--require-credited] [--ref <git-ref>] [--cwd <path>]',
16
16
  summary:
17
- 'Ensure the coverage artifact (delivery.quality.gates.coverage.coveragePath) is present and fresh before the coverage and CRAP gates fire, spawning `<pm> run <delivery.quality.gates.coverage.captureScript>` under the detected package manager only when it is stale (the affected capture script, with the base ref in MANDREL_COVERAGE_BASE_REF, under delivery.quality.gates.coverage.captureScope="affected"). Writes a content-digest capture stamp beside the artifact that close-validation reads to skip a redundant re-run. When delivery.quality.gates.crap.coveragePath names its own artifact, that artifact is then refreshed full-scope with `<pm> run <delivery.quality.gates.crap.captureScript>` and stamped beside itself. A capture script that exits 76 declares its slice over this host\'s budget: nothing is stamped, no later pass runs, and the CLI exits 76 for delivery.quality.gates.coverage.onOverBudget to settle.',
17
+ 'Ensure the coverage artifact (delivery.quality.gates.coverage.coveragePath) is present and fresh before the coverage and CRAP gates fire, spawning `<pm> run <delivery.quality.gates.coverage.captureScript>` under the detected package manager only when it is stale (the affected capture script, with the base ref in MANDREL_COVERAGE_BASE_REF, under delivery.quality.gates.coverage.captureScope="affected"). Writes a content-digest capture stamp beside the artifact that close-validation reads to skip a redundant re-run. When delivery.quality.gates.crap.coveragePath names its own artifact, that artifact is then refreshed full-scope with `<pm> run <delivery.quality.gates.crap.captureScript>` and stamped beside itself. A capture script that exits 76 declares its slice over this host\'s budget: nothing is stamped, no later pass runs, and the CLI exits 76 for delivery.quality.gates.coverage.onOverBudget to settle. A capture script that exits 77 declares the run lost workers to host memory with no failing test: nothing is stamped, no later pass runs, and the CLI exits 77, which handoff and close settle as blocked host-resources.',
18
18
  flags: [
19
19
  [
20
20
  '--skip-when-no-crap-files',
@@ -26,7 +26,7 @@ const COVERAGE_CAPTURE_USAGE = {
26
26
  ],
27
27
  [
28
28
  '--ref <git-ref>',
29
- 'Git ref the changed-file set is computed against. Passing it wins over delivery.quality.gates.crap.incrementalCoverage.baseRef, so a caller that anchors another gate on the same ref gets one scope for both.',
29
+ 'Git ref the changed-file set is computed against. Passing it wins over delivery.quality.gates.crap.incrementalCoverage.baseRef, so a caller that anchors another gate on the same ref gets one scope for both. Default: origin/<project.baseBranch> (local <project.baseBranch> with a warning when the remote ref does not resolve).',
30
30
  ],
31
31
  ['--cwd <path>', 'Repository root the capture runs in.'],
32
32
  ],
@@ -694,6 +694,12 @@ export const COVERAGE_TIMEOUT_EXIT_CODE = TIMEOUT_EXIT_CODE;
694
694
  */
695
695
  export const COVERAGE_OVER_BUDGET_EXIT_CODE = 76;
696
696
 
697
+ /**
698
+ * A consumer script's declaration that the run lost workers to host memory
699
+ * and no assertion failed — no code verdict; handoff and close block on it.
700
+ */
701
+ export const COVERAGE_HOST_RESOURCES_EXIT_CODE = 77;
702
+
697
703
  /**
698
704
  * Spawn `<pm> run <script>` (the detected package manager, see
699
705
  * `packageScriptArgv`) asynchronously as its own process group, so
@@ -757,6 +763,14 @@ function overBudgetMessage(code, script) {
757
763
  return `[coverage-capture] ⏭ the ${script} capture script declared its slice over this host's budget (exit ${code}) — no suite ran and nothing was stamped. delivery.quality.gates.coverage.onOverBudget decides whether this defers to CI or blocks.`;
758
764
  }
759
765
 
766
+ /**
767
+ * @param {number} code
768
+ * @param {string} script
769
+ */
770
+ function hostResourcesMessage(code, script) {
771
+ return `[coverage-capture] ⛔ the ${script} capture script lost test workers to host memory (exit ${code}) — no test failed and nothing was stamped. Do not re-run unchanged on this host: use fewer workers or a larger host.`;
772
+ }
773
+
760
774
  /**
761
775
  * @param {number} code
762
776
  * @param {string} script
@@ -775,6 +789,7 @@ const NON_FAILURE_CAPTURE_EXITS = Object.freeze({
775
789
  [LOCK_WAIT_EXPIRED_EXIT_CODE]: ['info', lockWaitExpiredMessage],
776
790
  [COVERAGE_TIMEOUT_EXIT_CODE]: ['error', timeoutMessage],
777
791
  [COVERAGE_OVER_BUDGET_EXIT_CODE]: ['info', overBudgetMessage],
792
+ [COVERAGE_HOST_RESOURCES_EXIT_CODE]: ['error', hostResourcesMessage],
778
793
  });
779
794
 
780
795
  const FAILING_SUITE_REPORT = Object.freeze(['error', failingSuiteMessage]);
@@ -0,0 +1,96 @@
1
+ /**
2
+ * coverage-deferral.js — the vocabulary of a coverage capture deferred to CI:
3
+ * its reasons, the PR-body marker CI workflows and confirm-merge route on,
4
+ * and the handoff envelope's `coverage` field.
5
+ */
6
+
7
+ import { replaceBeneathCloses } from './pr-body-lines.js';
8
+
9
+ /** The PR-body key line's key — a stable contract. */
10
+ const COVERAGE_DEFERRED_KEY = 'Coverage-deferred';
11
+
12
+ /** The deferral reasons the key line carries — a stable contract. */
13
+ export const COVERAGE_DEFERRED_REASONS = Object.freeze({
14
+ overBudget: 'over-budget',
15
+ suiteOfRecordCi: 'suite-of-record-ci',
16
+ });
17
+
18
+ /** The prose line each reason adds beneath `Closes #<id>`. */
19
+ const PROSE = Object.freeze({
20
+ [COVERAGE_DEFERRED_REASONS.overBudget]:
21
+ "Coverage deferred to CI: the capture slice was over this host's budget (exit 76, onOverBudget: defer-to-ci).",
22
+ [COVERAGE_DEFERRED_REASONS.suiteOfRecordCi]:
23
+ 'Coverage deferred to CI: CI is the coverage and CRAP ratchet of record (suiteOfRecord: ci).',
24
+ });
25
+
26
+ const PROSE_LINES = new Set(Object.values(PROSE));
27
+
28
+ /** The handoff envelope's `policy` for each reason. */
29
+ const POLICY = Object.freeze({
30
+ [COVERAGE_DEFERRED_REASONS.overBudget]: 'defer-to-ci',
31
+ [COVERAGE_DEFERRED_REASONS.suiteOfRecordCi]: 'suite-of-record',
32
+ });
33
+
34
+ /**
35
+ * The prose line, then the key line directly beneath it; none without a reason.
36
+ *
37
+ * @param {string|null|undefined} reason
38
+ * @returns {string[]}
39
+ */
40
+ export function deferralLines(reason) {
41
+ if (!reason) return [];
42
+ return ['', PROSE[reason], `${COVERAGE_DEFERRED_KEY}: ${reason}`];
43
+ }
44
+
45
+ /**
46
+ * The reason a PR body's key line carries, else `null`.
47
+ *
48
+ * @param {string|null|undefined} body
49
+ * @returns {string|null}
50
+ */
51
+ export function readDeferralMarker(body) {
52
+ const match = new RegExp(
53
+ `^${COVERAGE_DEFERRED_KEY}:[ \\t]*(\\S+)[ \\t]*$`,
54
+ 'm',
55
+ ).exec(String(body ?? ''));
56
+ return match ? match[1] : null;
57
+ }
58
+
59
+ /**
60
+ * `body` with its deferral lines replaced by `reason`'s, placed beneath
61
+ * `Closes #<id>` (appended when that line is missing).
62
+ *
63
+ * @param {string|null|undefined} body @param {string} reason
64
+ * @returns {string}
65
+ */
66
+ export function rewriteDeferralLines(body, reason) {
67
+ return replaceBeneathCloses(body, isDeferralLine, deferralLines(reason));
68
+ }
69
+
70
+ /** A prose or key line of any deferral reason. */
71
+ function isDeferralLine(line) {
72
+ return PROSE_LINES.has(line) || line.startsWith(`${COVERAGE_DEFERRED_KEY}:`);
73
+ }
74
+
75
+ /**
76
+ * Record a deferral and its reason at `head`.
77
+ *
78
+ * @param {{ coverageDeferredHead?: string, coverageDeferredReason?: string }} state
79
+ * @param {string} head @param {string} reason
80
+ */
81
+ export function deferCoverage(state, head, reason) {
82
+ state.coverageDeferredHead = head;
83
+ state.coverageDeferredReason = reason;
84
+ }
85
+
86
+ /**
87
+ * The envelope's `coverage` field for a recorded deferral.
88
+ *
89
+ * @param {string|undefined} reason
90
+ * @returns {{ status: 'deferred', reason: string, policy: string }}
91
+ */
92
+ export function deferralEnvelope(
93
+ reason = COVERAGE_DEFERRED_REASONS.overBudget,
94
+ ) {
95
+ return { status: 'deferred', reason, policy: POLICY[reason] };
96
+ }