mandrel 2.85.0 → 2.87.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 (30) hide show
  1. package/.agents/docs/agentrc-reference.json +2 -1
  2. package/.agents/docs/configuration.md +36 -14
  3. package/.agents/schemas/agentrc.schema.json +48 -9
  4. package/.agents/scripts/coverage-capture.js +23 -3
  5. package/.agents/scripts/evidence-gate.js +2 -2
  6. package/.agents/scripts/lib/baselines/bundle-size-scorer.js +115 -0
  7. package/.agents/scripts/lib/baselines/coverage-updater-cli.js +129 -28
  8. package/.agents/scripts/lib/baselines/crap-updater-cli.js +31 -10
  9. package/.agents/scripts/lib/baselines/duplication-scanner.js +25 -1
  10. package/.agents/scripts/lib/baselines/refresh-service.js +55 -19
  11. package/.agents/scripts/lib/close-validation/process.js +6 -0
  12. package/.agents/scripts/lib/close-validation/runner.js +22 -6
  13. package/.agents/scripts/lib/config/gates/coverage.schema.js +1 -1
  14. package/.agents/scripts/lib/config/gates/shared.js +1 -1
  15. package/.agents/scripts/lib/config/quality.js +6 -2
  16. package/.agents/scripts/lib/config-settings-schema-delivery.js +41 -2
  17. package/.agents/scripts/lib/coverage-baseline.js +7 -6
  18. package/.agents/scripts/lib/coverage-capture.js +44 -0
  19. package/.agents/scripts/lib/full-suite-lock.js +98 -38
  20. package/.agents/scripts/lib/full-suite-queue.js +45 -18
  21. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  22. package/.agents/scripts/lib/observability/source-classifier.js +1 -0
  23. package/.agents/scripts/lib/orchestration/check-baselines/phases/evaluate.js +29 -2
  24. package/.agents/scripts/lib/orchestration/story-handoff.js +19 -1
  25. package/.agents/scripts/lib/suite-admission.js +410 -0
  26. package/.agents/scripts/update-bundle-size-baseline.js +56 -0
  27. package/.agents/scripts/update-coverage-baseline.js +16 -41
  28. package/.agents/scripts/update-duplication-baseline.js +13 -3
  29. package/docs/CHANGELOG.md +14 -0
  30. package/package.json +7 -1
@@ -1,13 +1,41 @@
1
1
  /**
2
2
  * The `update-coverage-baseline` CLI's testable logic. The scorer stays
3
3
  * bespoke (not the refresh-service default) because it logs when the coverage
4
- * artifact is missing: `refreshBaseline` has no empty-rows guard, so that line
5
- * is the only signal a full-scope refresh just wrote an empty baseline.
4
+ * artifact is missing on a scoped refresh; a full-scope refresh rethrows, since
5
+ * `refreshBaseline` has no empty-rows guard and would write an empty baseline.
6
6
  */
7
7
 
8
+ import fs from 'node:fs';
9
+ import { createRequire } from 'node:module';
10
+ import path from 'node:path';
11
+ import { getBaselineEpsilon } from '../config/quality.js';
12
+ import {
13
+ buildScopePredicate,
14
+ readCoverageFinal,
15
+ scoreCoverageFinal,
16
+ } from '../coverage-baseline.js';
8
17
  import { Logger } from '../Logger.js';
9
18
  import { parseDiffScopeFlag } from './diff-scope-cli.js';
10
19
 
20
+ /** CommonJS `require`, for the `.c8rc.cjs` scope config. */
21
+ const require = createRequire(import.meta.url);
22
+
23
+ /**
24
+ * The c8 include/exclude scope from `<cwd>/.c8rc.cjs` — the one
25
+ * environment-bound step, which the scorer takes as a seam so a test never
26
+ * touches a real config. A consumer measuring with another runner has no
27
+ * `.c8rc.cjs`: that is an unscoped artifact, mirroring the refresh-service
28
+ * default scorer.
29
+ *
30
+ * @param {string} cwd
31
+ * @returns {{ include?: string[], exclude?: string[] }}
32
+ */
33
+ export function loadC8ScopeConfig(cwd) {
34
+ const c8rcPath = path.resolve(cwd, '.c8rc.cjs');
35
+ if (!fs.existsSync(c8rcPath)) return {};
36
+ return require(c8rcPath);
37
+ }
38
+
11
39
  /**
12
40
  * Throws when both scope flags are present.
13
41
  *
@@ -25,6 +53,22 @@ export function resolveCoverageUpdaterScope(argv = []) {
25
53
  return { fullScope, diffScopeRef };
26
54
  }
27
55
 
56
+ /**
57
+ * A full-scope refresh rethrows a read failure — over zero rows it would
58
+ * write an empty baseline; a scoped one logs it and yields `null`.
59
+ *
60
+ * @returns {object|null}
61
+ */
62
+ function readOrReport(readCoverage, cwd, opts, logger) {
63
+ try {
64
+ return readCoverage(cwd);
65
+ } catch (err) {
66
+ if (opts?.fullScope) throw err;
67
+ logger.error(`[Coverage] ❌ ${err.message}`);
68
+ return null;
69
+ }
70
+ }
71
+
28
72
  /**
29
73
  * Narrows to the c8 include/exclude scope, and in diff mode to the in-scope
30
74
  * files so untouched rows are preserved rather than re-scored.
@@ -34,20 +78,14 @@ export function resolveCoverageUpdaterScope(argv = []) {
34
78
  * score: Function, logger?: object}} deps
35
79
  * @returns {(files: string[], opts: object) => object[]}
36
80
  */
37
- export function buildCoverageUpdaterScorer(
81
+ function buildCoverageUpdaterScorer(
38
82
  cwd,
39
83
  { readCoverage, loadScope, buildScope, score, logger = Logger } = {},
40
84
  ) {
41
85
  return (files, opts) => {
42
86
  const effectiveCwd = opts?.cwd ?? cwd;
43
- let raw;
44
- try {
45
- raw = readCoverage(effectiveCwd);
46
- } catch (err) {
47
- logger.error(`[Coverage] ❌ ${err.message}`);
48
- return [];
49
- }
50
-
87
+ const raw = readOrReport(readCoverage, effectiveCwd, opts, logger);
88
+ if (raw === null) return [];
51
89
  const c8Config = loadScope(effectiveCwd);
52
90
  const scores = score({
53
91
  raw,
@@ -57,25 +95,88 @@ export function buildCoverageUpdaterScorer(
57
95
  exclude: c8Config.exclude ?? [],
58
96
  }),
59
97
  });
98
+ return projectScoredRows(scores, files, opts, logger);
99
+ };
100
+ }
60
101
 
61
- const inScope =
62
- !opts?.fullScope && Array.isArray(files) && files.length > 0
63
- ? new Set(files)
64
- : null;
102
+ /**
103
+ * Baseline rows from per-file scores; in diff mode only the in-scope files,
104
+ * so untouched rows are preserved rather than re-scored.
105
+ *
106
+ * @param {Record<string, object>} scores
107
+ * @param {string[]} files
108
+ * @param {{ fullScope?: boolean } | undefined} opts
109
+ * @param {{ info: Function }} logger
110
+ * @returns {object[]}
111
+ */
112
+ function projectScoredRows(scores, files, opts, logger) {
113
+ const inScope =
114
+ !opts?.fullScope && Array.isArray(files) && files.length > 0
115
+ ? new Set(files)
116
+ : null;
117
+ const rows = Object.entries(scores)
118
+ .filter(([relPath]) => inScope === null || inScope.has(relPath))
119
+ .map(([relPath, s]) => ({
120
+ path: relPath,
121
+ lines: s?.lines ?? 0,
122
+ branches: s?.branches ?? 0,
123
+ functions: s?.functions ?? 0,
124
+ }));
125
+ logger.info(
126
+ `[Coverage] Scored ${Object.keys(scores).length} file(s)${inScope ? ` (${rows.length} in scope)` : ''}.`,
127
+ );
128
+ return rows;
129
+ }
65
130
 
66
- const rows = Object.entries(scores)
67
- .filter(([relPath]) => inScope === null || inScope.has(relPath))
68
- .map(([relPath, s]) => ({
69
- path: relPath,
70
- lines: s?.lines ?? 0,
71
- branches: s?.branches ?? 0,
72
- functions: s?.functions ?? 0,
73
- }));
131
+ /**
132
+ * The configured artifact the refresh reads and the baseline it writes —
133
+ * `coveragePath` / `baselinePath` from the resolved coverage gate, never a
134
+ * hardcoded default.
135
+ *
136
+ * @param {{ coveragePath: string, baselinePath: string }} coverageGate
137
+ * @param {string} cwd
138
+ * @returns {{ coveragePath: string, baselinePath: string,
139
+ * absBaselinePath: string, readCoverage: (dir: string) => object }}
140
+ */
141
+ export function coverageUpdaterTargets({ coveragePath, baselinePath }, cwd) {
142
+ return {
143
+ coveragePath,
144
+ baselinePath,
145
+ absBaselinePath: path.resolve(cwd, baselinePath),
146
+ readCoverage: (dir) => readCoverageFinal(dir, { coveragePath }),
147
+ };
148
+ }
74
149
 
75
- const fileCount = Object.keys(scores).length;
76
- logger.info(
77
- `[Coverage] Scored ${fileCount} file(s)${inScope ? ` (${rows.length} in scope)` : ''}.`,
78
- );
79
- return rows;
150
+ /**
151
+ * `refreshBaseline` options for the coverage updater. `deps` substitutes the
152
+ * scorer's scope and scoring seams so a test never touches a real artifact.
153
+ *
154
+ * @param {string} cwd
155
+ * @param {{ absBaselinePath: string, readCoverage: Function }} targets
156
+ * @param {{ loadScope?: Function, buildScope?: Function, score?: Function,
157
+ * logger?: object }} [deps]
158
+ * @returns {object}
159
+ */
160
+ export function buildCoverageRefreshOpts(
161
+ cwd,
162
+ { absBaselinePath, readCoverage },
163
+ {
164
+ loadScope = loadC8ScopeConfig,
165
+ buildScope = buildScopePredicate,
166
+ score = scoreCoverageFinal,
167
+ logger,
168
+ } = {},
169
+ ) {
170
+ return {
171
+ kind: 'coverage',
172
+ writePath: absBaselinePath,
173
+ epsilon: getBaselineEpsilon('coverage'),
174
+ scorer: buildCoverageUpdaterScorer(cwd, {
175
+ readCoverage,
176
+ loadScope,
177
+ buildScope,
178
+ score,
179
+ logger,
180
+ }),
80
181
  };
81
182
  }
@@ -7,7 +7,10 @@
7
7
 
8
8
  import path from 'node:path';
9
9
  import { getBaselines, getQuality, resolveConfig } from '../config-resolver.js';
10
- import { isCoverageFresh } from '../coverage-capture.js';
10
+ import {
11
+ isCoverageFresh,
12
+ missingCoverageArtifactMessage,
13
+ } from '../coverage-capture.js';
11
14
  import { loadCoverage as loadCoverageDefault } from '../coverage-utils.js';
12
15
  import { checkResolutionFloor, scanAndScore } from '../crap-utils.js';
13
16
  import { Logger } from '../Logger.js';
@@ -134,8 +137,32 @@ function reportScanSummary(summary, logger = Logger) {
134
137
  }
135
138
 
136
139
  /**
137
- * Fails closed on a missing coverage artifact under `requireCoverage` (warn,
138
- * no rows) and on a resolution rate below the floor (throws before anything is
140
+ * No artifact under `requireCoverage`: a full-scope refresh throws naming the
141
+ * capture contract (zero rows would write an empty baseline); a scoped one
142
+ * warns and yields no rows.
143
+ *
144
+ * @param {string} coverageAbs
145
+ * @param {{ coveragePath: string }} options
146
+ * @param {{ fullScope?: boolean } | undefined} opts
147
+ * @param {{ warn: Function }} logger
148
+ * @returns {object[]}
149
+ */
150
+ function noCoverageRows(coverageAbs, options, opts, logger) {
151
+ if (opts?.fullScope) {
152
+ throw new Error(`[CRAP] ${missingCoverageArtifactMessage(coverageAbs)}`);
153
+ }
154
+ logger.warn(
155
+ `[CRAP] ⚠ No coverage artifact at ${options.coveragePath}. All files will be skipped under requireCoverage=true.`,
156
+ );
157
+ logger.warn(
158
+ "[CRAP] ⚠ Run 'npm run test:coverage' before 'npm run crap:update'.",
159
+ );
160
+ return [];
161
+ }
162
+
163
+ /**
164
+ * Fails closed on a missing coverage artifact under `requireCoverage` (throws
165
+ * on a full-scope refresh; warns with no rows on a scoped one) and on a resolution rate below the floor (throws before anything is
139
166
  * written: a broken join is wrong, not sparse).
140
167
  *
141
168
  * @param {ReturnType<typeof resolveCrapUpdaterOptions>} options
@@ -153,13 +180,7 @@ export function buildCrapUpdaterScorer(
153
180
  : path.resolve(effectiveCwd, options.coveragePath);
154
181
  const coverage = loadCoverage(coverageAbs);
155
182
  if (!coverage && options.requireCoverage) {
156
- logger.warn(
157
- `[CRAP] ⚠ No coverage artifact at ${options.coveragePath}. All files will be skipped under requireCoverage=true.`,
158
- );
159
- logger.warn(
160
- "[CRAP] ⚠ Run 'npm run test:coverage' before 'npm run crap:update'.",
161
- );
162
- return [];
183
+ return noCoverageRows(coverageAbs, options, opts, logger);
163
184
  }
164
185
 
165
186
  const summary = await scan({
@@ -21,6 +21,30 @@ const require = createRequire(import.meta.url);
21
21
  /** jscpd 5 is a Rust rewrite with no Node API; only major 4 exposes one. */
22
22
  const SUPPORTED_JSCPD_MAJOR = '^4';
23
23
 
24
+ /** `err.code` of the missing-install refusal, so a CLI prints it stackless. */
25
+ export const JSCPD_MISSING = 'JSCPD_MISSING';
26
+
27
+ /**
28
+ * jscpd is an optional peer dependency: only a consumer that enables the
29
+ * duplication gate installs it. A missing install names the fix rather than
30
+ * surfacing `MODULE_NOT_FOUND`; any other load failure propagates as-is.
31
+ *
32
+ * @param {NodeJS.Require} requireFn
33
+ * @returns {object}
34
+ */
35
+ function loadJscpd(requireFn) {
36
+ try {
37
+ return requireFn('jscpd');
38
+ } catch (err) {
39
+ if (err?.code !== 'MODULE_NOT_FOUND') throw err;
40
+ const missing = new Error(
41
+ `[Duplication] jscpd is not installed. The duplication gate scans with jscpd ${SUPPORTED_JSCPD_MAJOR}, an optional peer dependency of mandrel — install it in this project: npm i -D jscpd@${SUPPORTED_JSCPD_MAJOR}`,
42
+ );
43
+ missing.code = JSCPD_MISSING;
44
+ throw missing;
45
+ }
46
+ }
47
+
24
48
  /**
25
49
  * Lazy CJS load: jscpd's ESM entry has a broken transitive `colors/safe`
26
50
  * specifier under strict ESM resolution, and importers that never scan should
@@ -32,7 +56,7 @@ const SUPPORTED_JSCPD_MAJOR = '^4';
32
56
  * @returns {(opts: object) => Promise<Array<object>>}
33
57
  */
34
58
  export function resolveDetectClones(requireFn = require) {
35
- const jscpd = requireFn('jscpd');
59
+ const jscpd = loadJscpd(requireFn);
36
60
  if (typeof jscpd?.detectClones !== 'function') {
37
61
  const version = resolveDependencyVersion('jscpd', requireFn) ?? 'unknown';
38
62
  throw new Error(
@@ -11,11 +11,13 @@ import nodeFs from 'node:fs';
11
11
  import { createRequire } from 'node:module';
12
12
  import path from 'node:path';
13
13
  import { execFileCaptureAsync } from '../child-exec.js';
14
+ import { COVERAGE_GATE_DEFAULTS } from '../config/quality.js';
14
15
  import { getQuality, resolveConfig } from '../config-resolver.js';
15
16
  import {
16
17
  buildScopePredicate,
17
18
  scoreCoverageFinal,
18
19
  } from '../coverage-baseline.js';
20
+ import { missingCoverageArtifactMessage } from '../coverage-capture.js';
19
21
  import { loadCoverage } from '../coverage-utils.js';
20
22
  import {
21
23
  resolveEscomplexVersion,
@@ -27,7 +29,9 @@ import {
27
29
  isIgnoredByGlobs as isIgnoredByGlobsMi,
28
30
  scanDirectory as scanDirectoryMi,
29
31
  } from '../maintainability-utils.js';
32
+ import { buildBundleSizeScorer } from './bundle-size-scorer.js';
30
33
  import { resolveDetectClones, scanDuplication } from './duplication-scanner.js';
34
+ import { getKindModule } from './kernel.js';
31
35
  import { filterExcludedRows } from './kinds/maintainability.js';
32
36
  import { canonicalizeBaselinePath } from './path-canon.js';
33
37
  import {
@@ -42,6 +46,7 @@ const SUPPORTED_KINDS = Object.freeze([
42
46
  'crap',
43
47
  'coverage',
44
48
  'duplication',
49
+ 'bundle-size',
45
50
  ]);
46
51
 
47
52
  /**
@@ -56,6 +61,8 @@ const KIND_FILE_PREDICATES = Object.freeze({
56
61
  // Over-inclusive is inert for JS-only jscpd; under-inclusive would pin a
57
62
  // changed file's prior row.
58
63
  duplication: (p) => /\.(?:m?[jt]sx?)$/i.test(p),
64
+ // Bundle names are not paths: no changed file scopes a bundle row.
65
+ 'bundle-size': () => false,
59
66
  });
60
67
 
61
68
  /**
@@ -71,6 +78,22 @@ function resolveQualityBlock({ quality, config } = {}) {
71
78
  return {};
72
79
  }
73
80
 
81
+ /**
82
+ * No coverage artifact: a full-scope refresh over zero rows would read as
83
+ * "nothing to score", so it throws naming the capture contract; a scoped one
84
+ * yields no rows and `refreshBaseline` refuses the missing in-scope files.
85
+ *
86
+ * @param {string} absPath
87
+ * @param {{ fullScope?: boolean } | undefined} opts
88
+ * @returns {object[]}
89
+ */
90
+ function noArtifactRows(absPath, opts) {
91
+ if (opts?.fullScope) {
92
+ throw new Error(missingCoverageArtifactMessage(absPath));
93
+ }
94
+ return [];
95
+ }
96
+
74
97
  /**
75
98
  * @param {{ cwd: string, config?: object, quality?: object }} opts
76
99
  * @returns {(files: string[], opts: object) => Promise<object[]>}
@@ -92,7 +115,7 @@ function buildDefaultCrapScorer({ cwd, config, quality } = {}) {
92
115
  ? coverageRelPath
93
116
  : path.resolve(effectiveCwd, coverageRelPath);
94
117
  const coverage = loadCoverage(coverageAbs);
95
- if (!coverage && requireCoverage) return [];
118
+ if (!coverage && requireCoverage) return noArtifactRows(coverageAbs, opts);
96
119
  const scopeFiles = opts?.fullScope ? null : (files ?? null);
97
120
  const { rows } = await scanAndScore({
98
121
  targetDirs,
@@ -111,24 +134,24 @@ function buildDefaultCrapScorer({ cwd, config, quality } = {}) {
111
134
  }
112
135
 
113
136
  /**
114
- * Coverage rows from coverage-final.json, scoped by the optional `.c8rc.cjs`.
137
+ * Coverage rows from the configured `coverage.coveragePath` artifact, scoped by
138
+ * the optional `.c8rc.cjs`. A missing artifact throws on a full-scope refresh:
139
+ * an empty row set would otherwise read as "nothing measured".
115
140
  *
116
- * @param {{ cwd: string }} opts
141
+ * @param {{ cwd: string, config?: object, quality?: object }} opts
117
142
  * @returns {(files: string[], opts: object) => object[]}
118
143
  */
119
- function buildDefaultCoverageScorer({ cwd } = {}) {
144
+ function buildDefaultCoverageScorer({ cwd, config, quality } = {}) {
145
+ const coverageRelPath =
146
+ resolveQualityBlock({ quality, config })?.coverage?.coveragePath ??
147
+ COVERAGE_GATE_DEFAULTS.coveragePath;
120
148
  return (files, opts) => {
121
149
  const effectiveCwd = opts?.cwd ?? cwd ?? process.cwd();
122
- const coverageFinalPath = path.resolve(
123
- effectiveCwd,
124
- 'coverage/coverage-final.json',
125
- );
126
- let raw;
127
- try {
128
- raw = JSON.parse(nodeFs.readFileSync(coverageFinalPath, 'utf-8'));
129
- } catch {
130
- return [];
150
+ const coverageFinalPath = path.resolve(effectiveCwd, coverageRelPath);
151
+ if (!nodeFs.existsSync(coverageFinalPath)) {
152
+ return noArtifactRows(coverageFinalPath, opts);
131
153
  }
154
+ const raw = JSON.parse(nodeFs.readFileSync(coverageFinalPath, 'utf-8'));
132
155
  let c8Scope;
133
156
  try {
134
157
  const c8rcPath = path.resolve(effectiveCwd, '.c8rc.cjs');
@@ -217,6 +240,7 @@ const KIND_SCORER_BUILDERS = Object.freeze({
217
240
  crap: buildDefaultCrapScorer,
218
241
  coverage: buildDefaultCoverageScorer,
219
242
  duplication: buildDefaultDuplicationScorer,
243
+ 'bundle-size': buildBundleSizeScorer,
220
244
  });
221
245
 
222
246
  /**
@@ -249,7 +273,7 @@ export function resolveDefaultScorer(kind, { cwd } = {}) {
249
273
  * scoped file produced no row.
250
274
  *
251
275
  * @param {{
252
- * kind: 'maintainability' | 'crap' | 'coverage' | 'duplication',
276
+ * kind: 'maintainability' | 'crap' | 'coverage' | 'duplication' | 'bundle-size',
253
277
  * baseRef?: string,
254
278
  * headRef?: string,
255
279
  * scopeFiles?: string[] | null,
@@ -321,11 +345,7 @@ export async function refreshBaseline(opts = {}) {
321
345
  );
322
346
  }
323
347
 
324
- // Rows leave the service canonical whatever scorer produced them.
325
- const canonicalRows = scoredRows.map((row) => ({
326
- ...row,
327
- path: canonicalizeBaselinePath(row.path ?? row.file),
328
- }));
348
+ const canonicalRows = canonicalizeRows(kind, scoredRows);
329
349
 
330
350
  assertRequiredScopeRows({
331
351
  kind,
@@ -370,6 +390,22 @@ export async function refreshBaseline(opts = {}) {
370
390
  };
371
391
  }
372
392
 
393
+ /**
394
+ * Rows leave the service canonical whatever scorer produced them. Only
395
+ * path-keyed kinds carry a path; bundle-size rows are keyed on a name.
396
+ *
397
+ * @param {string} kind
398
+ * @param {object[]} rows
399
+ * @returns {object[]}
400
+ */
401
+ function canonicalizeRows(kind, rows) {
402
+ if (getKindModule(kind).keyField !== 'path') return rows;
403
+ return rows.map((row) => ({
404
+ ...row,
405
+ path: canonicalizeBaselinePath(row.path ?? row.file),
406
+ }));
407
+ }
408
+
373
409
  function assertRequiredScopeRows({
374
410
  kind,
375
411
  scope,
@@ -3,6 +3,7 @@
3
3
  import { spawn } from 'node:child_process';
4
4
 
5
5
  import {
6
+ ADMISSION_REFUSED_EXIT_CODE,
6
7
  LOCK_WAIT_EXPIRED_EXIT_CODE,
7
8
  resolveFullSuiteLockBudget,
8
9
  withFullSuiteLockAsync,
@@ -106,6 +107,7 @@ function gateLockOptions(opts) {
106
107
  log: opts.log,
107
108
  skipIfSatisfied: opts.skipIfSatisfied,
108
109
  onWaitExpired: deferredGateStatus,
110
+ onAdmissionRefused: refusedGateStatus,
109
111
  onLockOutcome: opts.onLockEvent
110
112
  ? (outcome) => opts.onLockEvent({ kind: 'lock-wait', ...outcome })
111
113
  : undefined,
@@ -117,6 +119,10 @@ function deferredGateStatus() {
117
119
  return { status: LOCK_WAIT_EXPIRED_EXIT_CODE };
118
120
  }
119
121
 
122
+ function refusedGateStatus() {
123
+ return { status: ADMISSION_REFUSED_EXIT_CODE };
124
+ }
125
+
120
126
  /**
121
127
  * @param {string} cmd
122
128
  * @param {string[]} args
@@ -5,7 +5,10 @@
5
5
 
6
6
  import { getQuality } from '../config/quality.js';
7
7
  import { COVERAGE_TIMEOUT_EXIT_CODE } from '../coverage-capture.js';
8
- import { LOCK_WAIT_EXPIRED_EXIT_CODE } from '../full-suite-lock.js';
8
+ import {
9
+ fullSuiteLockPolicy,
10
+ LOCK_WAIT_EXPIRED_EXIT_CODE,
11
+ } from '../full-suite-lock.js';
9
12
  import { gitSpawn } from '../git-utils.js';
10
13
  import {
11
14
  recordPass as defaultRecordPass,
@@ -372,7 +375,9 @@ function fullSuiteLockOptions({ config, lockEvents }) {
372
375
  return {
373
376
  ...(env ? { env } : {}),
374
377
  ...(lockEvents ? { onLockEvent: lockEvents.emit } : {}),
375
- ...(gate.fullSuiteLock ? fullSuiteGateOptions(gate, timeoutMs) : {}),
378
+ ...(gate.fullSuiteLock
379
+ ? fullSuiteGateOptions(gate, timeoutMs, config)
380
+ : {}),
376
381
  };
377
382
  },
378
383
  };
@@ -385,14 +390,25 @@ function gateEnv(gate, lockEvents) {
385
390
  }
386
391
 
387
392
  /**
388
- * A full-suite gate's kill bound, and the command its lock-expiry line names.
393
+ * A full-suite gate's kill bound, the command its lock-expiry line names, and
394
+ * the admission policy evidence-gate and coverage-capture resolve too — so
395
+ * `fullSuiteLock: false` / `MANDREL_FULL_SUITE_LOCK=0` reach close as well.
389
396
  *
390
397
  * @param {{ cmd: string, args?: string[] }} gate
391
398
  * @param {number} timeoutMs
399
+ * @param {object|null} config
392
400
  */
393
- function fullSuiteGateOptions(gate, timeoutMs) {
394
- const rerunCommand = [gate.cmd, ...(gate.args ?? [])].join(' ');
395
- return { timeoutMs, lockOptions: { rerunCommand } };
401
+ function fullSuiteGateOptions(gate, timeoutMs, config) {
402
+ const argv = [gate.cmd, ...(gate.args ?? [])];
403
+ const { enabled, capacity, workload } = fullSuiteLockPolicy(
404
+ config,
405
+ process.env,
406
+ argv,
407
+ );
408
+ return {
409
+ timeoutMs,
410
+ lockOptions: { rerunCommand: argv.join(' '), enabled, capacity, workload },
411
+ };
396
412
  }
397
413
 
398
414
  /**
@@ -24,7 +24,7 @@ export const COVERAGE_GATE = {
24
24
  ...SAFE_STRING,
25
25
  minLength: 1,
26
26
  description:
27
- 'Repo-relative path to the Istanbul `coverage-final.json` the capture step writes and the gate reads.',
27
+ 'Repo-relative path to the Istanbul `coverage-final.json` the capture step writes and the gate reads. The capture contract: `npm run test:coverage` MUST write Istanbul per-file JSON (the `json` reporter) here — the coverage and CRAP refreshes both read it. A `json-summary` (`coverage-summary.json`) alone cannot feed them, so a green capture that leaves no file here fails and a full-scope refresh refuses to run.',
28
28
  default: COVERAGE_GATE_DEFAULTS.coveragePath,
29
29
  },
30
30
  captureScope: {
@@ -60,7 +60,7 @@ const FLOORS_SCHEMA = {
60
60
  const COMPONENTS_SCHEMA = {
61
61
  type: 'object',
62
62
  description:
63
- 'Per-gate component map — component name to the glob list whose files roll up under it. Defaults to `{ "*": ["**"] }` at the resolver layer.',
63
+ 'Per-gate component map — component name to the glob list whose rows roll up under it (matched against the row key: the file path, or the bundle name for bundle-size). `check-baselines` reports one rollup per component that matches a row and holds it to `floors.<component>`, falling back to `floors["*"]`. Defaults to `{ "*": ["**"] }` at the resolver layer.',
64
64
  additionalProperties: {
65
65
  type: 'array',
66
66
  items: { type: 'string', minLength: 1 },
@@ -89,6 +89,7 @@ const CRAP_GATE_KEYS = new Set([
89
89
  'baselinePath',
90
90
  'tolerance',
91
91
  'floors',
92
+ 'components',
92
93
  'targetDirs',
93
94
  'newMethodCeiling',
94
95
  'requireCoverage',
@@ -102,6 +103,7 @@ const COVERAGE_GATE_KEYS = new Set([
102
103
  'baselinePath',
103
104
  'tolerance',
104
105
  'floors',
106
+ 'components',
105
107
  'coveragePath',
106
108
  'captureScope',
107
109
  'timeoutMs',
@@ -112,6 +114,7 @@ const MI_GATE_KEYS = new Set([
112
114
  'baselinePath',
113
115
  'tolerance',
114
116
  'floors',
117
+ 'components',
115
118
  'targetDirs',
116
119
  'ignoreGlobs',
117
120
  ]);
@@ -400,14 +403,15 @@ export function resolveQuality(userQuality) {
400
403
 
401
404
  /**
402
405
  * The writer folds sub-epsilon row deltas back to the prior bytes so env
403
- * variance never rewrites a baseline. bundle-size is bytes.
406
+ * variance never rewrites a baseline. Each value is in its kind's row unit:
407
+ * bundle-size rows are KB, so 1 means "ignore sub-KB jitter".
404
408
  */
405
409
  const BASELINE_EPSILON = Object.freeze({
406
410
  maintainability: 0.5,
407
411
  crap: 0.5,
408
412
  coverage: 0.1,
409
413
  mutation: 0.5,
410
- 'bundle-size': 1024,
414
+ 'bundle-size': 1,
411
415
  duplication: 0.5,
412
416
  });
413
417
 
@@ -24,14 +24,53 @@ const SAFE_STRING = {
24
24
 
25
25
  const EXECUTION_SCHEMA = {
26
26
  type: 'object',
27
- description: 'Serialization of the full-suite spawns delivery drives.',
27
+ description:
28
+ 'Serialization and capacity admission of the suite spawns delivery drives.',
28
29
  properties: {
29
30
  fullSuiteLock: {
30
31
  type: 'boolean',
31
32
  description:
32
- 'Serialize full-suite spawns (`npm test` / `npm run test:coverage`) behind a host-level advisory lock, so two concurrent deliveries on one checkout do not run two suites against the same cores. The lock queues, it never overlaps: a wait that expires with a live holder spawns nothing and exits 75 (resumable), naming the holder. A dead or non-heartbeating holder is taken over, and a broken lockfile proceeds unserialized, so the lock can never fail a delivery. Set false — or export `MANDREL_FULL_SUITE_LOCK=0` for one invocation — to disable.',
33
+ 'Serialize full-suite spawns (`npm test` / `npm run test:coverage`) behind a repository-level advisory lock shared by every worktree, so two concurrent deliveries do not run two suites against the same cores (see `capacity` / `workloads` for declared runs that may overlap). The lock queues, it never overlaps: a wait that expires with a live holder spawns nothing and exits 75 (resumable), naming the holder. A dead or non-heartbeating holder is taken over, and a broken lockfile proceeds unserialized, so the lock can never fail a delivery. Set false — or export `MANDREL_FULL_SUITE_LOCK=0` for one invocation — to disable.',
33
34
  default: true,
34
35
  },
36
+ capacity: {
37
+ type: 'integer',
38
+ minimum: 1,
39
+ description:
40
+ "Story #5668. The admission budget, in weight units (CPU workers), shared by every suite spawn across this repository's worktrees and sessions — runs in other repositories on the host are not counted. Unset → the host's `os.availableParallelism()`. A declared workload is admitted while the live weights plus its own fit, strictly first-in-first-out: nothing overtakes an earlier live waiter, so a queued full suite is never starved.",
41
+ },
42
+ workloads: {
43
+ type: 'array',
44
+ description:
45
+ "Story #5668. Suite commands declared safe to run alongside others. A spawn whose argv (whitespace-normalized) EXACTLY equals `command` takes that `weight` and `resources`; anything else — and every spawn when this list is empty, the default — runs exclusively (full capacity, today's serialization). Isolation is never inferred from a flag, prefix or diff size. `weight` must count the run's nested worker pool (`--workers 4` → 4), and a full suite needs its own entry before anything can overlap it. Two runs naming a common `resources` entry (a database fixture, a shared coverage file) never overlap; worktree-local outputs need none. A weight above `capacity` refuses the run with exit 78 — nothing spawns, no credit is recorded. An expired wait still exits 75, resumably. Scheduling never changes a run's credit identity. `MANDREL_FULL_SUITE_LOCK=0` (one invocation) or `fullSuiteLock: false` turns admission off entirely; reach for the env hatch only when you have checked the runs share nothing.",
46
+ items: {
47
+ type: 'object',
48
+ required: ['command', 'weight'],
49
+ properties: {
50
+ command: {
51
+ ...SAFE_STRING,
52
+ minLength: 1,
53
+ description:
54
+ 'The exact suite argv, as `project.commands.test` spells it (or `npm run test:coverage` for coverage capture).',
55
+ },
56
+ weight: {
57
+ type: 'integer',
58
+ minimum: 1,
59
+ description:
60
+ 'CPU workers the run occupies, including its nested pool.',
61
+ },
62
+ resources: {
63
+ type: 'array',
64
+ uniqueItems: true,
65
+ items: { type: 'string', pattern: '^[a-z0-9][a-z0-9-]*$' },
66
+ description:
67
+ 'Names of shared resources this run needs exclusively.',
68
+ },
69
+ },
70
+ additionalProperties: false,
71
+ },
72
+ default: [],
73
+ },
35
74
  },
36
75
  additionalProperties: false,
37
76
  };