mandrel 2.88.0 → 2.90.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 (40) hide show
  1. package/.agents/docs/agentrc-reference.json +3 -1
  2. package/.agents/docs/configuration.md +9 -0
  3. package/.agents/schemas/agentrc.schema.json +13 -0
  4. package/.agents/scripts/board-backfill.js +253 -0
  5. package/.agents/scripts/coverage-capture.js +32 -49
  6. package/.agents/scripts/lib/audit-baselines/gate-surface.js +24 -11
  7. package/.agents/scripts/lib/audit-baselines/read.js +4 -2
  8. package/.agents/scripts/lib/audit-baselines/surface-entry.js +95 -11
  9. package/.agents/scripts/lib/baselines/crap-preview-scan.js +3 -1
  10. package/.agents/scripts/lib/baselines/crap-updater-cli.js +2 -0
  11. package/.agents/scripts/lib/baselines/kinds/crap.js +37 -16
  12. package/.agents/scripts/lib/baselines/preview-gates.js +1 -0
  13. package/.agents/scripts/lib/close-validation/gates.js +40 -9
  14. package/.agents/scripts/lib/close-validation/process.js +5 -1
  15. package/.agents/scripts/lib/config/gates/crap.schema.js +15 -0
  16. package/.agents/scripts/lib/config/quality.js +49 -1
  17. package/.agents/scripts/lib/coverage-capture-affected.js +2 -1
  18. package/.agents/scripts/lib/coverage-capture-fullscope.js +2 -2
  19. package/.agents/scripts/lib/coverage-capture-incremental.js +1 -1
  20. package/.agents/scripts/lib/coverage-capture-passes.js +143 -0
  21. package/.agents/scripts/lib/coverage-capture-usage.js +1 -1
  22. package/.agents/scripts/lib/coverage-capture.js +79 -38
  23. package/.agents/scripts/lib/crap-utils.js +6 -2
  24. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  25. package/.agents/scripts/lib/maintainability-utils.js +6 -1
  26. package/.agents/scripts/lib/observability/source-classifier.js +1 -0
  27. package/.agents/scripts/lib/orchestration/board-access-latch.js +101 -0
  28. package/.agents/scripts/lib/orchestration/check-baselines/phases/evaluate.js +1 -1
  29. package/.agents/scripts/lib/orchestration/column-sync.js +107 -52
  30. package/.agents/scripts/lib/orchestration/project-meta-resolver.js +44 -17
  31. package/.agents/scripts/lib/orchestration/story-handoff.js +14 -1
  32. package/.agents/scripts/lib/orchestration/verify-credit.js +4 -1
  33. package/.agents/scripts/providers/github/board-add.js +18 -9
  34. package/.agents/scripts/providers/github/projects-v2-graphql.js +15 -3
  35. package/.agents/scripts/update-crap-baseline.js +2 -2
  36. package/.agents/workflows/audit-baselines.md +7 -2
  37. package/docs/CHANGELOG.md +26 -0
  38. package/lib/cli/doctor-checks/project-access.js +114 -0
  39. package/lib/cli/registry.js +6 -0
  40. package/package.json +1 -1
@@ -420,7 +420,7 @@ export const INCOMPATIBLE_BASELINE_DIAGNOSTIC = 'crap-baseline-incompatible';
420
420
  *
421
421
  * @param {{total?: number, comparable?: number, provenanceMismatched?: number,
422
422
  * incomparable?: number}} compareResult
423
- * @param {{ratio?: number, minSample?: number}} [opts]
423
+ * @param {{ratio?: number, minSample?: number, captureScript?: string}} [opts]
424
424
  */
425
425
  export function assessComparisonBasis(compareResult, opts = {}) {
426
426
  const ratio = Number.isFinite(opts.ratio)
@@ -451,7 +451,7 @@ export function assessComparisonBasis(compareResult, opts = {}) {
451
451
  'the same line coordinates, so every per-method verdict below would ' +
452
452
  'be derived from a mis-keyed join rather than from your change. ' +
453
453
  'They are suppressed.\n' +
454
- " Re-seed the baseline: run 'npm run test:coverage' then " +
454
+ ` Re-seed the baseline: run 'npm run ${captureScriptOf(opts)}' then ` +
455
455
  "'npm run crap:update -- --full-scope' and commit the result with a " +
456
456
  "'baseline-refresh:' subject. The authoritative check-baselines gate " +
457
457
  'still gates the merge.',
@@ -459,10 +459,27 @@ export function assessComparisonBasis(compareResult, opts = {}) {
459
459
  };
460
460
  }
461
461
 
462
- const RESEED_REMEDY =
463
- "Re-derive the baseline: run 'npm run test:coverage' then " +
464
- "'npm run crap:update -- --full-scope' and commit the result with a " +
465
- "'baseline-refresh:' subject.";
462
+ /**
463
+ * The CRAP capture script an operator hint names — the resolved
464
+ * `gates.crap.captureScript` when the caller passes it, else the default.
465
+ *
466
+ * @param {{ captureScript?: string } | undefined} ctx
467
+ * @returns {string}
468
+ */
469
+ function captureScriptOf(ctx) {
470
+ return typeof ctx?.captureScript === 'string' && ctx.captureScript.length > 0
471
+ ? ctx.captureScript
472
+ : 'test:coverage';
473
+ }
474
+
475
+ /** @param {{ captureScript?: string } | undefined} ctx */
476
+ function reseedRemedy(ctx) {
477
+ return (
478
+ `Re-derive the baseline: run 'npm run ${captureScriptOf(ctx)}' then ` +
479
+ "'npm run crap:update -- --full-scope' and commit the result with a " +
480
+ "'baseline-refresh:' subject."
481
+ );
482
+ }
466
483
 
467
484
  /**
468
485
  * Compat axes for `evaluateBaselineCompatibility`: `{ name, severity, check }`,
@@ -477,7 +494,7 @@ export const CRAP_COMPAT_AXES = [
477
494
  {
478
495
  name: 'scoring-semantics-drift',
479
496
  severity: 'fatal',
480
- check: ({ baseline }) => {
497
+ check: ({ baseline, captureScript }) => {
481
498
  if (!baseline) return null;
482
499
  const stamped = baseline.scoringSemantics ?? null;
483
500
  if (stamped === SCORING_SEMANTICS) return null;
@@ -485,14 +502,14 @@ export const CRAP_COMPAT_AXES = [
485
502
  `[CRAP] scoring semantics changed: baseline=${stamped ?? '<unstamped>'} ` +
486
503
  `running=${SCORING_SEMANTICS}. Rows scored by the previous per-method ` +
487
504
  'coverage join are not comparable to rows scored by the current one, ' +
488
- `so this baseline cannot be compared. ${RESEED_REMEDY}`
505
+ `so this baseline cannot be compared. ${reseedRemedy({ captureScript })}`
489
506
  );
490
507
  },
491
508
  },
492
509
  {
493
510
  name: 'ts-transpiler-drift',
494
511
  severity: 'fatal',
495
- check: ({ baseline, runningTsTranspilerVersion }) => {
512
+ check: ({ baseline, runningTsTranspilerVersion, captureScript }) => {
496
513
  if (!baseline) return null;
497
514
  if (!isKnownVersion(runningTsTranspilerVersion)) return null;
498
515
  const baselineTs = baseline.tsTranspilerVersion;
@@ -505,7 +522,7 @@ export const CRAP_COMPAT_AXES = [
505
522
  `[CRAP] tsTranspilerVersion changed: baseline=${baselineTs} running=${runningTsTranspilerVersion}. ` +
506
523
  "A TS row's startLine is an original-source coordinate only because the transpiler's " +
507
524
  'sourcemap said so, and that coordinate is half the row identity key — so rows scored ' +
508
- `under the previous transpiler are not comparable to rows scored under this one. ${RESEED_REMEDY}`
525
+ `under the previous transpiler are not comparable to rows scored under this one. ${reseedRemedy({ captureScript })}`
509
526
  );
510
527
  },
511
528
  },
@@ -515,7 +532,7 @@ export const CRAP_COMPAT_AXES = [
515
532
  // scoped to transpiled rows because pure-JS coordinates coincide.
516
533
  name: 'provenance-unstamped',
517
534
  severity: 'fatal',
518
- check: ({ baseline }) =>
535
+ check: ({ baseline, captureScript }) =>
519
536
  baseline &&
520
537
  baseline.provenanceStamped !== true &&
521
538
  hasTranspiledRows(baseline)
@@ -524,7 +541,7 @@ export const CRAP_COMPAT_AXES = [
524
541
  'asserts by omission that every row is an original-source coordinate. ' +
525
542
  '`startLine` is half the row identity key, so the comparator would ' +
526
543
  'key those rows against a coordinate space they are not in and ' +
527
- `report regressions no edit can satisfy. ${RESEED_REMEDY}`
544
+ `report regressions no edit can satisfy. ${reseedRemedy({ captureScript })}`
528
545
  : null,
529
546
  },
530
547
  {
@@ -534,7 +551,7 @@ export const CRAP_COMPAT_AXES = [
534
551
  // `anonymous` marker.
535
552
  name: 'anon-identity-unstamped',
536
553
  severity: 'fatal',
537
- check: ({ baseline }) => {
554
+ check: ({ baseline, captureScript }) => {
538
555
  if (!baseline) return null;
539
556
  const stale = (baseline.rows ?? []).filter(
540
557
  (row) => isAnonymousMethodLabel(row?.method) && row?.anonymous !== true,
@@ -547,7 +564,7 @@ export const CRAP_COMPAT_AXES = [
547
564
  'envelope claims the current scoring semantics. Those ordinals ' +
548
565
  'renumber whenever any anonymous function is added or removed, so the ' +
549
566
  'comparator would score the live methods against the new-method ' +
550
- `ceiling instead of their own baseline. ${RESEED_REMEDY}`
567
+ `ceiling instead of their own baseline. ${reseedRemedy({ captureScript })}`
551
568
  );
552
569
  },
553
570
  },
@@ -597,7 +614,7 @@ const LOADED_ENVELOPE_AXES = [
597
614
  *
598
615
  * @param {object|null} baseline A loaded v2 baseline envelope.
599
616
  * @param {{runningTsTranspilerVersion?: string, cwd?: string,
600
- * targetDirs?: string[]}} [ctx]
617
+ * targetDirs?: string[], captureScript?: string}} [ctx]
601
618
  * @returns {string|null} Operator-facing message, or null when compatible.
602
619
  */
603
620
  export function assertBaselineCompatible(baseline, ctx = {}) {
@@ -606,7 +623,11 @@ export function assertBaselineCompatible(baseline, ctx = {}) {
606
623
  ctx.runningTsTranspilerVersion ?? resolveTsTranspilerVersion(ctx);
607
624
  for (const name of LOADED_ENVELOPE_AXES) {
608
625
  const axis = CRAP_COMPAT_AXES.find((a) => a.name === name);
609
- const message = axis?.check({ baseline, runningTsTranspilerVersion });
626
+ const message = axis?.check({
627
+ baseline,
628
+ runningTsTranspilerVersion,
629
+ captureScript: ctx.captureScript,
630
+ });
610
631
  if (message) return message;
611
632
  }
612
633
  return null;
@@ -218,6 +218,7 @@ export async function runCrapPreview({
218
218
  const incompatible = assertBaselineCompatible(baseline, {
219
219
  cwd,
220
220
  targetDirs: crap.targetDirs,
221
+ captureScript: crap.captureScript,
221
222
  });
222
223
  if (incompatible) {
223
224
  return {
@@ -4,7 +4,11 @@ import { existsSync } from 'node:fs';
4
4
 
5
5
  import { _internals as baselineReaderInternals } from '../baselines/reader.js';
6
6
  import { getChangedFiles } from '../changed-files.js';
7
- import { COVERAGE_GATE_DEFAULTS, getQuality } from '../config/quality.js';
7
+ import {
8
+ COVERAGE_GATE_DEFAULTS,
9
+ CRAP_GATE_DEFAULTS,
10
+ getQuality,
11
+ } from '../config/quality.js';
8
12
  import { filterFilesUnderTargets } from '../coverage-capture.js';
9
13
  import { hasNpmScript, readPackageScripts } from '../npm-scripts.js';
10
14
  import { KNOWN_KINDS } from '../orchestration/check-baselines/phases/parse-args.js';
@@ -70,7 +74,22 @@ export function isCrapGateEnabled(config) {
70
74
  }
71
75
 
72
76
  /**
73
- * Coverage-capture registers when the CRAP gate is on AND a `test:coverage`
77
+ * The npm script that writes the CRAP coverage artifact —
78
+ * `gates.crap.captureScript`, default `test:coverage`. Read
79
+ * from the unresolved block for the same reason as {@link isCrapGateEnabled}.
80
+ *
81
+ * @param {object|undefined|null} config - Canonical resolved config.
82
+ * @returns {string}
83
+ */
84
+ function crapCaptureScript(config) {
85
+ const script = config?.delivery?.quality?.gates?.crap?.captureScript;
86
+ return typeof script === 'string' && script.trim().length > 0
87
+ ? script.trim()
88
+ : CRAP_GATE_DEFAULTS.captureScript;
89
+ }
90
+
91
+ /**
92
+ * Coverage-capture registers when the CRAP gate is on AND the CRAP capture
74
93
  * script exists; {@link resolveCreditedDepositor} builds on it.
75
94
  *
76
95
  * @param {object|undefined|null} config - Canonical resolved config.
@@ -78,7 +97,10 @@ export function isCrapGateEnabled(config) {
78
97
  * @returns {boolean}
79
98
  */
80
99
  function isCoverageCaptureActive(config, scripts) {
81
- return isCrapGateEnabled(config) && hasNpmScript(scripts, 'test:coverage');
100
+ return (
101
+ isCrapGateEnabled(config) &&
102
+ hasNpmScript(scripts, crapCaptureScript(config))
103
+ );
82
104
  }
83
105
 
84
106
  /**
@@ -341,10 +363,19 @@ function coverageCaptureRunsSuite({
341
363
 
342
364
  /**
343
365
  * Names every suite the capture can run: under `captureScope: "affected"` a
344
- * red may come from a delta refresh the base-sync triggered, not the Story.
366
+ * red may come from a delta refresh the base-sync triggered, not the Story;
367
+ * a non-default `gates.crap.captureScript` is named beside `test:coverage`.
368
+ *
369
+ * @param {string} captureScript The CRAP capture script ({@link crapCaptureScript}).
370
+ * @returns {string}
345
371
  */
346
- const COVERAGE_CAPTURE_HINT =
347
- 'Coverage capture failed — its suite run (`npm run test:coverage`, or `npm run test:coverage:affected` under `captureScope: "affected"`, including a delta refresh keyed on the stamped commit after a base-sync) exited non-zero. The coverage-capture log names which ran; fix the failing tests or coverage-threshold breaches, then re-run close.';
372
+ function coverageCaptureHint(captureScript) {
373
+ const crapScript =
374
+ captureScript === CRAP_GATE_DEFAULTS.captureScript
375
+ ? ''
376
+ : `, the CRAP gate's own \`npm run ${captureScript}\` (\`gates.crap.captureScript\`)`;
377
+ return `Coverage capture failed — its suite run (\`npm run test:coverage\`${crapScript}, or \`npm run test:coverage:affected\` under \`captureScope: "affected"\`, including a delta refresh keyed on the stamped commit after a base-sync) exited non-zero. The coverage-capture log names which ran; fix the failing tests or coverage-threshold breaches, then re-run close.`;
378
+ }
348
379
 
349
380
  const COVERAGE_CAPTURE_ARGS = Object.freeze([
350
381
  '.agents/scripts/coverage-capture.js',
@@ -407,8 +438,8 @@ export const GATE_TIMEOUT_HINT = `The gate outran the suite timeout (\`delivery.
407
438
  /**
408
439
  * Build the close-validation gate list, cheapest fast-fail first: typecheck →
409
440
  * lint → [test] → format → [quality-preview-mi] → [coverage-capture →
410
- * quality-preview-crap] → check-baselines. Coverage-capture registers only when CRAP is enabled AND a
411
- * `test:coverage` script exists; it then carries test-failure signalling and
441
+ * quality-preview-crap] → check-baselines. Coverage-capture registers only when CRAP is enabled AND its
442
+ * capture script (`gates.crap.captureScript`, default `test:coverage`) exists; it then carries test-failure signalling and
412
443
  * the plain `test` gate is dropped, so there is always exactly one test gate.
413
444
  *
414
445
  * @param {{ config?: object, baseBranch?: string, cwd?: string, packageScripts?: Record<string, string>, presentBaselines?: string[]|Set<string>, log?: (message: string) => void, getChangedFilesImpl?: typeof getChangedFiles }} [opts]
@@ -520,7 +551,7 @@ export function buildDefaultGates({
520
551
  name: 'coverage-capture',
521
552
  cmd: 'node',
522
553
  args: [...COVERAGE_CAPTURE_ARGS],
523
- hint: COVERAGE_CAPTURE_HINT,
554
+ hint: coverageCaptureHint(crapCaptureScript(config)),
524
555
  lockEventChannel: true,
525
556
  ...(captureSkipPredicted
526
557
  ? { skip: { reason: 'incremental-no-crap-changes' } }
@@ -153,6 +153,10 @@ function spawnGate(cmd, args, opts, lock) {
153
153
  }
154
154
 
155
155
  /**
156
+ * The child always gets an env: `AP_AGENTRC_CWD` is pinned to `cwd` (layered
157
+ * last) so every gate and its `npm run` grandchildren resolve the worktree's
158
+ * `.agentrc.json`, not the config of the checkout holding the scripts.
159
+ *
156
160
  * @param {string} cmd
157
161
  * @param {string[]} args
158
162
  * @param {string} cwd
@@ -164,7 +168,7 @@ function spawnGateChild(cmd, args, cwd, env) {
164
168
  shell: process.platform === 'win32',
165
169
  stdio: ['ignore', 'pipe', 'pipe'],
166
170
  ...groupSpawnOptions(),
167
- ...(env ? { env: { ...process.env, ...env } } : {}),
171
+ env: { ...process.env, ...env, AP_AGENTRC_CWD: cwd },
168
172
  });
169
173
  }
170
174
 
@@ -49,6 +49,21 @@ export const CRAP_GATE = {
49
49
  default: [...CRAP_GATE_DEFAULTS.ignoreGlobs],
50
50
  },
51
51
  incrementalCoverage: INCREMENTAL_COVERAGE_SCHEMA,
52
+ coveragePath: {
53
+ type: ['string', 'null'],
54
+ minLength: 1,
55
+ description:
56
+ "Repo-relative Istanbul `coverage-final.json` the CRAP gate joins against (Story #5717). `null` or unset falls back to `delivery.quality.gates.coverage.coveragePath`. When it differs from that path the CRAP gate has its OWN coverage source: `coverage-capture.js` refreshes it full-scope via `captureScript`, and the handoff seat, close preview and `update-crap-baseline.js` read it. It must live in a different directory from the coverage gate's artifact (the capture stamp is per directory); a same-directory path is refused at config resolution.",
57
+ default: null,
58
+ },
59
+ captureScript: {
60
+ type: 'string',
61
+ minLength: 1,
62
+ pattern: '^[A-Za-z0-9@:._/-]+$',
63
+ description:
64
+ 'npm script name (run as `npm run <script>`, never a shell command) that writes the CRAP coverage artifact. Close registers the coverage-capture gate, and the capture refusal and credited-run probe key, on this script.',
65
+ default: CRAP_GATE_DEFAULTS.captureScript,
66
+ },
52
67
  },
53
68
  additionalProperties: false,
54
69
  };
@@ -58,6 +58,8 @@ export const CRAP_GATE_DEFAULTS = Object.freeze({
58
58
  // Healthy runs resolve ~98%; a coordinate mismatch resolves 4–6%.
59
59
  minMethodResolutionRate: 0.75,
60
60
  incrementalCoverage: DEFAULT_INCREMENTAL_COVERAGE,
61
+ // npm script that writes the CRAP coverage artifact (never a shell command).
62
+ captureScript: 'test:coverage',
61
63
  });
62
64
 
63
65
  export const COVERAGE_GATE_DEFAULTS = Object.freeze({
@@ -96,6 +98,8 @@ const CRAP_GATE_KEYS = new Set([
96
98
  'ignoreGlobs',
97
99
  'minMethodResolutionRate',
98
100
  'incrementalCoverage',
101
+ 'coveragePath',
102
+ 'captureScript',
99
103
  ]);
100
104
 
101
105
  const COVERAGE_GATE_KEYS = new Set([
@@ -176,6 +180,48 @@ function resolveIncrementalCoverage(user, defaults) {
176
180
  };
177
181
  }
178
182
 
183
+ function nonEmptyString(value) {
184
+ return typeof value === 'string' && value.trim().length > 0
185
+ ? value.trim()
186
+ : null;
187
+ }
188
+
189
+ /** Directory part of a repo-relative path, separator-agnostic. */
190
+ function artifactDir(relPath) {
191
+ const parts = relPath.replace(/\\/g, '/').split('/').filter(Boolean);
192
+ parts.pop();
193
+ return parts.filter((p) => p !== '.').join('/');
194
+ }
195
+
196
+ /**
197
+ * The CRAP gate's coverage source. A user `coveragePath` that
198
+ * differs from the coverage gate's is an OWN source; one in the same
199
+ * directory would share the per-directory capture stamp and cross-credit
200
+ * freshness, so it is refused here rather than silently falling back.
201
+ *
202
+ * @param {{ coveragePath?: unknown, captureScript?: unknown }} userCrap
203
+ * @param {string} coverageGatePath
204
+ * @returns {{ coveragePath: string, captureScript: string, ownCoverageSource: boolean }}
205
+ */
206
+ function resolveCrapCoverageSource(userCrap, coverageGatePath) {
207
+ const userPath = nonEmptyString(userCrap?.coveragePath);
208
+ const captureScript =
209
+ nonEmptyString(userCrap?.captureScript) ?? CRAP_GATE_DEFAULTS.captureScript;
210
+ const coveragePath = userPath ?? coverageGatePath;
211
+ const ownCoverageSource =
212
+ userPath !== null &&
213
+ userPath.replace(/\\/g, '/') !== coverageGatePath.replace(/\\/g, '/');
214
+ if (
215
+ ownCoverageSource &&
216
+ artifactDir(userPath) === artifactDir(coverageGatePath)
217
+ ) {
218
+ throw new Error(
219
+ `[config] delivery.quality.gates.crap.coveragePath '${userPath}' sits in the same directory as delivery.quality.gates.coverage.coveragePath '${coverageGatePath}'. The capture stamp is per directory, so an own CRAP coverage source must live in its own directory.`,
220
+ );
221
+ }
222
+ return { coveragePath, captureScript, ownCoverageSource };
223
+ }
224
+
179
225
  /**
180
226
  * @param {object | undefined} userCrap
181
227
  * @param {{ coveragePath: string }} coverageGate
@@ -195,6 +241,8 @@ export function resolveMaintainabilityCrap(userCrap, coverageGate) {
195
241
  targetDirs: [...defaults.targetDirs],
196
242
  newMethodCeiling: defaults.newMethodCeiling,
197
243
  coveragePath: coverage.coveragePath,
244
+ captureScript: defaults.captureScript,
245
+ ownCoverageSource: false,
198
246
  tolerance: toleranceScalar(
199
247
  defaults.tolerance,
200
248
  DEFAULT_CRAP_TOLERANCE.value,
@@ -213,7 +261,7 @@ export function resolveMaintainabilityCrap(userCrap, coverageGate) {
213
261
  enabled: userCrap.enabled ?? defaults.enabled,
214
262
  targetDirs: resolveListValue(defaults.targetDirs, userCrap.targetDirs),
215
263
  newMethodCeiling: userCrap.newMethodCeiling ?? defaults.newMethodCeiling,
216
- coveragePath: coverage.coveragePath,
264
+ ...resolveCrapCoverageSource(userCrap, coverage.coveragePath),
217
265
  tolerance: toleranceScalar(
218
266
  userCrap.tolerance,
219
267
  toleranceScalar(defaults.tolerance, DEFAULT_CRAP_TOLERANCE.value),
@@ -185,7 +185,8 @@ function writeMerged({
185
185
  */
186
186
  async function captureAndMerge(opts) {
187
187
  const run = await runScoped(opts);
188
- if (run.code !== 0) return reportCaptureFailure(run.code, opts.logger);
188
+ if (run.code !== 0)
189
+ return reportCaptureFailure(run.code, opts.logger, AFFECTED_CAPTURE_SCRIPT);
189
190
  if (!writeMerged(opts)) return 1;
190
191
  stampCapturedTree({
191
192
  ...opts,
@@ -96,7 +96,7 @@ export async function runFullScopeCapture({
96
96
  }
97
97
 
98
98
  logger.info(
99
- `[coverage-capture] Coverage at ${crap.coveragePath} is ${describeFreshness(freshness, crap.targetDirs)}; running npm run test:coverage… ${detail}`,
99
+ `[coverage-capture] Coverage at ${crap.coveragePath} is ${describeFreshness(freshness, crap.targetDirs)}; running npm run ${crap.captureScript ?? 'test:coverage'}… ${detail}`,
100
100
  );
101
101
  const tree = snapshotCapturedTree({
102
102
  cwd: args.cwd,
@@ -112,7 +112,7 @@ export async function runFullScopeCapture({
112
112
  // After queueing behind another suite, which may have stamped this tree.
113
113
  recheckFresh: () => probe().fresh === true,
114
114
  });
115
- if (code !== 0) return reportCaptureFailure(code, logger);
115
+ if (code !== 0) return reportCaptureFailure(code, logger, crap.captureScript);
116
116
 
117
117
  stampCapturedTree({
118
118
  ...tree,
@@ -113,7 +113,7 @@ export async function tryIncrementalCapture({
113
113
  log: (m) => logger.info(m),
114
114
  recheckFresh: () => probe().fresh === true,
115
115
  });
116
- if (code !== 0) return reportCaptureFailure(code, logger);
116
+ if (code !== 0) return reportCaptureFailure(code, logger, crap.captureScript);
117
117
 
118
118
  stampCapturedTree({
119
119
  ...tree,
@@ -0,0 +1,143 @@
1
+ /**
2
+ * The ordered capture passes for `coverage-capture.js` and the capture-script
3
+ * refusal. A shared source is one pass: the existing pipeline, scoped modes
4
+ * included. An own CRAP source (`crap.ownCoverageSource`) first refreshes the
5
+ * coverage gate's artifact exactly as before, then gives the CRAP artifact
6
+ * its own full-scope pass via `crap.captureScript`, stamped in its own
7
+ * directory. Scoped capture modes never apply to the own source.
8
+ */
9
+ import { runFullScopeCapture } from './coverage-capture-fullscope.js';
10
+
11
+ const COVERAGE_GATE_SCRIPT = 'test:coverage';
12
+ const COVERAGE_PATH_KEY = 'delivery.quality.gates.coverage.coveragePath';
13
+ const CRAP_PATH_KEY = 'delivery.quality.gates.crap.coveragePath';
14
+ const CRAP_SCRIPT_KEY = 'delivery.quality.gates.crap.captureScript';
15
+
16
+ /**
17
+ * The exit code when no capture may run: the CRAP gate is off (0), or its
18
+ * capture script is missing from `package.json` (1, naming the fix).
19
+ *
20
+ * @param {{ crap: object, scripts: object, hasNpmScriptImpl: Function, logger: object }} opts
21
+ * @returns {number|null}
22
+ */
23
+ export function captureRefusal({ crap, scripts, hasNpmScriptImpl, logger }) {
24
+ if (crap.enabled === false) {
25
+ logger.info('[coverage-capture] CRAP gate disabled — skipping capture.');
26
+ return 0;
27
+ }
28
+ const script = crap.captureScript ?? COVERAGE_GATE_SCRIPT;
29
+ if (hasNpmScriptImpl(scripts, script)) return null;
30
+ // Name the fix rather than propagate npm's opaque "Missing script" exit.
31
+ logger.error(
32
+ `[coverage-capture] ✖ No "${script}" script in package.json (the CRAP capture script, set by ${CRAP_SCRIPT_KEY}). ` +
33
+ `Add one (e.g. "${script}": "node --test --experimental-test-coverage"), ` +
34
+ `point ${CRAP_SCRIPT_KEY} at an existing script, ` +
35
+ 'or disable the CRAP gate via delivery.quality.gates.crap.enabled=false.',
36
+ );
37
+ return 1;
38
+ }
39
+
40
+ /**
41
+ * @param {{ crap: object, coverage: object, scripts: object, hasNpmScriptImpl: Function, logger: object }} opts
42
+ * @returns {Array<{ crap: object, configKey: string, own: boolean }>}
43
+ */
44
+ function planPasses({ crap, coverage, scripts, hasNpmScriptImpl, logger }) {
45
+ if (crap.ownCoverageSource !== true) {
46
+ return [{ crap, configKey: COVERAGE_PATH_KEY, own: false }];
47
+ }
48
+ const ownPass = { crap, configKey: CRAP_PATH_KEY, own: true };
49
+ if (!hasNpmScriptImpl(scripts, COVERAGE_GATE_SCRIPT)) {
50
+ logger.info(
51
+ `[coverage-capture] No "${COVERAGE_GATE_SCRIPT}" script — skipping the coverage gate's capture; only the CRAP source at ${crap.coveragePath} is refreshed.`,
52
+ );
53
+ return [ownPass];
54
+ }
55
+ const gateCrap = {
56
+ ...crap,
57
+ coveragePath: coverage.coveragePath,
58
+ captureScript: COVERAGE_GATE_SCRIPT,
59
+ };
60
+ return [
61
+ { crap: gateCrap, configKey: COVERAGE_PATH_KEY, own: false },
62
+ ownPass,
63
+ ];
64
+ }
65
+
66
+ /**
67
+ * A capture runner that defaults `script` to the pass's capture script; an
68
+ * explicit `script` (the affected scope's) still wins.
69
+ *
70
+ * @param {Function} capture
71
+ * @param {string|undefined} script
72
+ * @returns {Function}
73
+ */
74
+ function withDefaultScript(capture, script) {
75
+ return script ? (opts) => capture({ script, ...opts }) : capture;
76
+ }
77
+
78
+ /**
79
+ * Run each planned pass; the first non-zero pass wins and no later pass runs.
80
+ *
81
+ * @param {{
82
+ * crap: object,
83
+ * coverage: object,
84
+ * args: object,
85
+ * scripts: object,
86
+ * hasNpmScriptImpl: Function,
87
+ * makeCapture: (source: { coveragePath: string, script?: string, configKey: string }) => Function,
88
+ * runShared: (opts: object) => Promise<number>,
89
+ * deps: object,
90
+ * }} opts
91
+ * @returns {Promise<number>}
92
+ */
93
+ export async function runCapturePasses({
94
+ crap,
95
+ coverage,
96
+ args,
97
+ scripts,
98
+ hasNpmScriptImpl,
99
+ makeCapture,
100
+ runShared,
101
+ deps,
102
+ }) {
103
+ const { logger } = deps;
104
+ const passes = planPasses({
105
+ crap,
106
+ coverage,
107
+ scripts,
108
+ hasNpmScriptImpl,
109
+ logger,
110
+ });
111
+ for (const pass of passes) {
112
+ const capture = withDefaultScript(
113
+ makeCapture({
114
+ coveragePath: pass.crap.coveragePath,
115
+ script: pass.crap.captureScript,
116
+ configKey: pass.configKey,
117
+ }),
118
+ pass.crap.captureScript,
119
+ );
120
+ const code = pass.own
121
+ ? await runOwnSource({ crap: pass.crap, coverage, args, capture, deps })
122
+ : await runShared({ crap: pass.crap, coverage, args, capture, deps });
123
+ if (code !== 0) return code;
124
+ }
125
+ return 0;
126
+ }
127
+
128
+ /**
129
+ * @param {{ crap: object, coverage: object, args: object, capture: Function, deps: object }} opts
130
+ * @returns {Promise<number>}
131
+ */
132
+ function runOwnSource({ crap, coverage, args, capture, deps }) {
133
+ deps.logger.info(
134
+ `[coverage-capture] CRAP gate has its own coverage source (${CRAP_PATH_KEY}=${crap.coveragePath}, npm run ${crap.captureScript}).`,
135
+ );
136
+ return runFullScopeCapture({
137
+ ...deps,
138
+ crap,
139
+ coverage,
140
+ args,
141
+ runCaptureImpl: capture,
142
+ });
143
+ }
@@ -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 coverage/coverage-final.json is present and fresh before the CRAP gate fires, spawning `npm run test:coverage` only when it is stale (`npm run test:coverage:affected`, with the base ref in MANDREL_COVERAGE_BASE_REF, under delivery.quality.gates.coverage.captureScope="affected"). Writes a content-digest capture stamp that close-validation reads to skip a redundant re-run.',
17
+ 'Ensure coverage/coverage-final.json is present and fresh before the CRAP gate fires, spawning `npm run test:coverage` only when it is stale (`npm run test:coverage:affected`, with the base ref in MANDREL_COVERAGE_BASE_REF, under delivery.quality.gates.coverage.captureScope="affected"). Writes a content-digest capture stamp 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 `npm run <delivery.quality.gates.crap.captureScript>` and stamped in its own directory.',
18
18
  flags: [
19
19
  [
20
20
  '--skip-when-no-crap-files',