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
@@ -84,6 +84,7 @@ const FRAMEWORK_SCRIPT_BASENAMES = Object.freeze([
84
84
  'sync-codex-agents.js',
85
85
  'sync-codex-skills.js',
86
86
  'test-wrapper.js',
87
+ 'update-bundle-size-baseline.js',
87
88
  'update-coverage-baseline.js',
88
89
  'update-crap-baseline.js',
89
90
  'update-duplication-baseline.js',
@@ -5,6 +5,7 @@
5
5
  * @module lib/orchestration/check-baselines/phases/evaluate
6
6
  */
7
7
 
8
+ import { groupRows, resolveComponents } from '../../../baselines/components.js';
8
9
  import {
9
10
  checkBaselineSemantics,
10
11
  checkKernelVersion,
@@ -25,7 +26,7 @@ import { applyRefreshAcknowledgment } from './refresh-ack.js';
25
26
  * @param {{ kind: string, baseline: { rows?: object[] }, ignoreGlobs?: string[], cwd?: string }} args
26
27
  * @returns {object}
27
28
  */
28
- function floorRollupOf({ kind, baseline, ignoreGlobs, cwd }) {
29
+ function floorRollupOf({ kind, baseline, ignoreGlobs, components, cwd }) {
29
30
  const mod = getKindModule(kind);
30
31
  const rows = Array.isArray(baseline?.rows) ? baseline.rows : [];
31
32
  const filterIgnored =
@@ -38,7 +39,32 @@ function floorRollupOf({ kind, baseline, ignoreGlobs, cwd }) {
38
39
  return typeof p !== 'string' || !isIgnoredByGlobs(p, ignoreGlobs, cwd);
39
40
  })
40
41
  : rows;
41
- return mod.rollup(kept);
42
+ return withComponentRollups(mod, kept, components);
43
+ }
44
+
45
+ /**
46
+ * `*` stays the kind's own whole-repo rollup; each configured component adds
47
+ * the same aggregate over the rows its globs match, keyed on the kind's
48
+ * `keyField`. A component matching no rows is omitted — there is nothing to
49
+ * hold to a floor.
50
+ *
51
+ * @param {{ keyField: string, rollup: (rows: object[]) => Record<string, object> }} mod
52
+ * @param {object[]} rows
53
+ * @param {Record<string, string[]> | undefined} components
54
+ * @returns {Record<string, object>}
55
+ */
56
+ function withComponentRollups(mod, rows, components) {
57
+ const out = mod.rollup(rows);
58
+ const buckets = groupRows(
59
+ rows,
60
+ resolveComponents({ components }),
61
+ mod.keyField,
62
+ );
63
+ for (const [name, matched] of Object.entries(buckets)) {
64
+ if (name === '*' || matched.length === 0) continue;
65
+ out[name] = mod.rollup(matched)['*'];
66
+ }
67
+ return out;
42
68
  }
43
69
 
44
70
  function loadHeadBaseline(kind, cwd, configPath) {
@@ -111,6 +137,7 @@ export async function evaluateKind({
111
137
  kind,
112
138
  baseline,
113
139
  ignoreGlobs: gateBlock.ignoreGlobs,
140
+ components: gateBlock.components,
114
141
  cwd,
115
142
  });
116
143
  const findings = applyFloors(kind, floorRollup, gateBlock.floors ?? {});
@@ -36,11 +36,15 @@ import {
36
36
  orchestrationLogDir,
37
37
  storyReviewDepositPath,
38
38
  } from '../config/temp-paths.js';
39
- import { LOCK_WAIT_EXPIRED_EXIT_CODE } from '../full-suite-lock.js';
39
+ import {
40
+ ADMISSION_REFUSED_EXIT_CODE,
41
+ LOCK_WAIT_EXPIRED_EXIT_CODE,
42
+ } from '../full-suite-lock.js';
40
43
  import { syncBranchFromBase } from '../git/sync-from-base.js';
41
44
  import { getStoryBranch, gitSpawn } from '../git-utils.js';
42
45
  import { readPackageScripts } from '../npm-scripts.js';
43
46
  import { TIMEOUT_EXIT_CODE } from '../process-group.js';
47
+ import { describeBlocking } from '../suite-admission.js';
44
48
  import { probeHeldReviewDiff } from './review-deposit.js';
45
49
  import { createStoryProgress, handoffStepName } from './story-progress.js';
46
50
  import {
@@ -197,16 +201,22 @@ async function runLogged(ctx, logName, cmd, args, env) {
197
201
  const LOCK_PHASE_TEXT = Object.freeze({
198
202
  waiting: 'waiting for the full-suite lock',
199
203
  'still-waiting': 'still waiting for the full-suite lock',
204
+ admitted: 'admitted — suite running',
205
+ // Older children report `acquired`, the same state as `admitted`.
200
206
  acquired: 'acquired the full-suite lock',
207
+ completed: 'suite completed',
201
208
  expired: 'gave up waiting for the full-suite lock',
202
209
  });
203
210
 
204
211
  /** @param {import('../full-suite-queue.js').LockProgress} event */
205
212
  function describeLockProgress(event) {
206
213
  const head = LOCK_PHASE_TEXT[event.phase] ?? `lock ${event.phase}`;
214
+ if (event.phase === 'completed') return `${head} (${durations(event)})`;
207
215
  const parts = [
208
216
  `waited ${event.waitedSeconds}s of a ${event.waitBudgetSeconds}s budget`,
209
217
  ];
218
+ if (event.blocking)
219
+ parts.push(`blocked: ${describeBlocking(event.blocking)}`);
210
220
  const { holder, queueAhead } = event;
211
221
  if (holder) {
212
222
  parts.push(
@@ -217,6 +227,11 @@ function describeLockProgress(event) {
217
227
  return `${head} (${parts.join('; ')})`;
218
228
  }
219
229
 
230
+ function durations({ waitMs, executionMs }) {
231
+ const seconds = (ms) => `${Math.round((ms ?? 0) / 1000)}s`;
232
+ return `waited ${seconds(waitMs)}, ran ${seconds(executionMs)}`;
233
+ }
234
+
220
235
  /**
221
236
  * Tail a fresh lock-event channel while `run(env)` runs, forwarding each
222
237
  * `lock-progress` event once; never the child's output, which can be forged.
@@ -257,6 +272,9 @@ function describeSuiteFailure(status) {
257
272
  if (status === LOCK_WAIT_EXPIRED_EXIT_CODE) {
258
273
  return `suite deferred (exit ${status}): another full suite holds the host lock — re-run the handoff once it frees`;
259
274
  }
275
+ if (status === ADMISSION_REFUSED_EXIT_CODE) {
276
+ return `suite refused (exit ${status}): its declared delivery.execution.workloads weight exceeds capacity — fix the declaration, then re-run`;
277
+ }
260
278
  if (status === TIMEOUT_EXIT_CODE) {
261
279
  return `suite timed out (exit ${status}) — usually host contention; re-run the handoff`;
262
280
  }
@@ -0,0 +1,410 @@
1
+ /**
2
+ * suite-admission.js — capacity admission for the suite spawns the
3
+ * full-suite lock guards.
4
+ *
5
+ * A spawn is classified by its exact argv against
6
+ * `delivery.execution.workloads[]`. A declared workload holds a
7
+ * weight-carrying reservation under the main checkout's `.git`, admitted while
8
+ * live weights fit `capacity` and no live reservation shares a resource. An
9
+ * undeclared spawn is exclusive: it takes the legacy lockfile (so older
10
+ * Mandrel versions still queue behind it) and drains every reservation first.
11
+ * Check-then-reserve runs under a short admission mutex, so two processes can
12
+ * never both take the last slot.
13
+ */
14
+ import crypto from 'node:crypto';
15
+ import os from 'node:os';
16
+ import path from 'node:path';
17
+
18
+ import {
19
+ acquireSweepLock,
20
+ isHolderAlive,
21
+ readLockHolderPid,
22
+ } from './single-story-sweep/sweep-lock.js';
23
+
24
+ /** `EX_CONFIG`: a declared weight the capacity can never admit. */
25
+ export const ADMISSION_REFUSED_EXIT_CODE = 78;
26
+
27
+ /**
28
+ * Staleness for every holder, reservation and ticket — fixed, so no waiter's
29
+ * own wait budget can read a live holder stale. A dead pid is stale at once.
30
+ */
31
+ export const FULL_SUITE_STALE_MS = 1_800_000;
32
+
33
+ /** Holders refresh well inside every stale threshold, old or new. */
34
+ const HOLDER_HEARTBEAT_MS = 20_000;
35
+
36
+ const MUTEX_STALE_MS = 30_000;
37
+
38
+ const RESERVATION_RE = /^w(\d+)~([a-z0-9+-]*)~[^~]+\.lock$/;
39
+
40
+ /**
41
+ * @typedef {{ kind: 'exclusive' }
42
+ * | { kind: 'declared', command: string, weight: number, resources: string[] }
43
+ * | { kind: 'refused', command: string, weight: number, capacity: number }} SuiteWorkload
44
+ */
45
+
46
+ /** @param {string|string[]} argv */
47
+ function normalizeCommand(argv) {
48
+ const text = Array.isArray(argv) ? argv.join(' ') : String(argv ?? '');
49
+ return text.split(/\s+/).filter(Boolean).join(' ');
50
+ }
51
+
52
+ /**
53
+ * @param {object} [config]
54
+ * @param {{ availableParallelism?: () => number }} [osImpl]
55
+ * @returns {number}
56
+ */
57
+ export function resolveSuiteCapacity(config, osImpl = os) {
58
+ const configured = config?.delivery?.execution?.capacity;
59
+ if (Number.isInteger(configured) && configured >= 1) return configured;
60
+ return Math.max(1, Number(osImpl.availableParallelism?.()) || 1);
61
+ }
62
+
63
+ /**
64
+ * Exact argv equality only — never a prefix, flag or diff-size inference.
65
+ *
66
+ * @param {{ config?: object, argv?: string|string[], capacity?: number }} opts
67
+ * @returns {SuiteWorkload}
68
+ */
69
+ function classifySuiteWorkload({ config, argv, capacity }) {
70
+ const workloads = config?.delivery?.execution?.workloads;
71
+ if (!Array.isArray(workloads) || argv === undefined) {
72
+ return { kind: 'exclusive' };
73
+ }
74
+ const command = normalizeCommand(argv);
75
+ const entry = workloads.find(
76
+ (w) => normalizeCommand(w?.command) === command && command !== '',
77
+ );
78
+ if (!entry) return { kind: 'exclusive' };
79
+ const limit = capacity ?? resolveSuiteCapacity(config);
80
+ if (entry.weight > limit) {
81
+ return { kind: 'refused', command, weight: entry.weight, capacity: limit };
82
+ }
83
+ return {
84
+ kind: 'declared',
85
+ command,
86
+ weight: entry.weight,
87
+ resources: [...(entry.resources ?? [])],
88
+ };
89
+ }
90
+
91
+ /**
92
+ * @param {object} [config]
93
+ * @param {string[]} [argv]
94
+ * @returns {{ capacity: number, workload: SuiteWorkload }}
95
+ */
96
+ export function resolveAdmission(config, argv) {
97
+ const capacity = resolveSuiteCapacity(config);
98
+ return {
99
+ capacity,
100
+ workload: classifySuiteWorkload({ config, argv, capacity }),
101
+ };
102
+ }
103
+
104
+ /** @param {{ workload?: SuiteWorkload }} opts */
105
+ export function createAttempt(opts) {
106
+ return opts.workload?.kind === 'declared'
107
+ ? createDeclaredAttempt(opts)
108
+ : createExclusiveAttempt(opts);
109
+ }
110
+
111
+ /** The `completed` progress event: wait and execution kept apart. */
112
+ export function completedProgress(waitMs, budgetMs, executionMs) {
113
+ return {
114
+ phase: 'completed',
115
+ waitedSeconds: Math.round(waitMs / 1000),
116
+ waitBudgetSeconds: Math.round(Math.max(0, budgetMs) / 1000),
117
+ waitMs,
118
+ executionMs: Math.max(0, executionMs),
119
+ };
120
+ }
121
+
122
+ /** @param {SuiteWorkload} workload */
123
+ export function describeRefusal({ command, weight, capacity }) {
124
+ return `[full-suite-lock] ✖ \`${command}\` declares weight ${weight}, above delivery.execution.capacity ${capacity} — it can never be admitted, so nothing ran and no credit was recorded. Lower its weight or raise capacity. Exiting ${ADMISSION_REFUSED_EXIT_CODE}.`;
125
+ }
126
+
127
+ function reservationsDir(lockPath) {
128
+ return `${lockPath}.reservations`;
129
+ }
130
+
131
+ function ageOf(file, fsImpl, nowFn) {
132
+ try {
133
+ return nowFn() - fsImpl.statSync(file).mtimeMs;
134
+ } catch {
135
+ return null;
136
+ }
137
+ }
138
+
139
+ /**
140
+ * Dead pid → stale now; otherwise a heartbeat older than `staleMs`.
141
+ *
142
+ * @returns {{ live: boolean, exists: boolean, pid: number|null, ageMs: number|null }}
143
+ */
144
+ function holderState(file, { fsImpl, nowFn, staleMs, killFn }) {
145
+ const ageMs = ageOf(file, fsImpl, nowFn);
146
+ if (ageMs === null) return { live: false, exists: false, pid: null, ageMs };
147
+ const pid = readLockHolderPid(file, fsImpl);
148
+ const dead = isHolderAlive(pid, killFn) === false;
149
+ return { live: !dead && ageMs <= staleMs, exists: true, pid, ageMs };
150
+ }
151
+
152
+ function holderOf(file, state) {
153
+ return {
154
+ ownerId: path.basename(file),
155
+ pid: state.pid,
156
+ ageSeconds: Math.max(0, Math.round(state.ageMs / 1000)),
157
+ };
158
+ }
159
+
160
+ /**
161
+ * Live reservations; a dead-pid entry is unlinked (callers hold the mutex).
162
+ *
163
+ * @returns {Array<{ weight: number, resources: string[], holder: object }>|null}
164
+ * `null` when the directory is absent.
165
+ */
166
+ function readLiveReservations({ lockPath, ...probe }) {
167
+ const dir = reservationsDir(lockPath);
168
+ let names;
169
+ try {
170
+ names = probe.fsImpl.readdirSync(dir).map(String).sort();
171
+ } catch {
172
+ return null;
173
+ }
174
+ return names.flatMap((name) => liveReservation(dir, name, probe));
175
+ }
176
+
177
+ function liveReservation(dir, name, probe) {
178
+ const match = RESERVATION_RE.exec(name);
179
+ if (!match) return [];
180
+ const file = path.join(dir, name);
181
+ const state = holderState(file, probe);
182
+ if (!state.live) {
183
+ if (state.exists && isHolderAlive(state.pid, probe.killFn) === false) {
184
+ unlinkQuietly(file, probe.fsImpl);
185
+ }
186
+ return [];
187
+ }
188
+ return [
189
+ {
190
+ weight: Number(match[1]),
191
+ resources: match[2] ? match[2].split('+') : [],
192
+ holder: holderOf(file, state),
193
+ },
194
+ ];
195
+ }
196
+
197
+ function unlinkQuietly(file, fsImpl) {
198
+ try {
199
+ fsImpl.unlinkSync(file);
200
+ } catch {}
201
+ }
202
+
203
+ /** @returns {object|null} the live legacy holder, if any. */
204
+ function liveLegacyHolder({ lockPath, ...probe }) {
205
+ const state = holderState(lockPath, probe);
206
+ return state.live ? holderOf(lockPath, state) : null;
207
+ }
208
+
209
+ /**
210
+ * Runs `fn` under the admission mutex. `busy` retries next poll; `error`
211
+ * fails open, as every lockfile I/O error does.
212
+ */
213
+ function underAdmissionMutex({ lockPath, fsImpl }, fn) {
214
+ const mutex = acquireSweepLock({
215
+ lockPath: `${lockPath}.admission`,
216
+ timeoutMs: MUTEX_STALE_MS,
217
+ heartbeatMs: 0,
218
+ fsImpl,
219
+ processImpl: null,
220
+ });
221
+ if (!mutex.acquired) {
222
+ return mutex.reason === 'error'
223
+ ? { acquired: false, reason: 'error' }
224
+ : { acquired: false, blocking: { reason: 'admission' } };
225
+ }
226
+ try {
227
+ return fn();
228
+ } finally {
229
+ mutex.release();
230
+ }
231
+ }
232
+
233
+ function blocked(blocking) {
234
+ return { acquired: false, blocking };
235
+ }
236
+
237
+ function sharedResource(live, resources) {
238
+ for (const reservation of live) {
239
+ const shared = reservation.resources.find((r) => resources.includes(r));
240
+ if (shared) return { shared, holder: reservation.holder };
241
+ }
242
+ return null;
243
+ }
244
+
245
+ function reservationName({ weight, resources }) {
246
+ const rand = crypto.randomBytes(4).toString('hex');
247
+ return `w${weight}~${resources.join('+')}~${process.pid}-${rand}.lock`;
248
+ }
249
+
250
+ /**
251
+ * A declared run: admitted when no exclusive holder is live, no live
252
+ * reservation shares a resource, and the live weights plus its own fit.
253
+ *
254
+ * @param {{ lockPath: string, workload: SuiteWorkload, capacity: number,
255
+ * staleMs: number, fsImpl: object, nowFn: () => number, killFn?: Function,
256
+ * acquireReservationFn?: typeof acquireSweepLock }} opts
257
+ */
258
+ function createDeclaredAttempt(opts) {
259
+ const { workload, capacity } = opts;
260
+ const acquire = opts.acquireReservationFn ?? acquireSweepLock;
261
+ let held = null;
262
+ const admit = () => {
263
+ const legacy = liveLegacyHolder(opts);
264
+ if (legacy) return blocked({ reason: 'exclusive', holder: legacy });
265
+ const live = readLiveReservations(opts) ?? [];
266
+ const clash = sharedResource(live, workload.resources);
267
+ if (clash) {
268
+ return blocked({
269
+ reason: 'resource',
270
+ resource: clash.shared,
271
+ holder: clash.holder,
272
+ });
273
+ }
274
+ const used = live.reduce((sum, r) => sum + r.weight, 0);
275
+ if (used + workload.weight > capacity) {
276
+ return blocked({
277
+ reason: 'capacity',
278
+ used,
279
+ requested: workload.weight,
280
+ capacity,
281
+ });
282
+ }
283
+ return reserve();
284
+ };
285
+ const reserve = () => {
286
+ const dir = reservationsDir(opts.lockPath);
287
+ try {
288
+ opts.fsImpl.mkdirSync(dir, { recursive: true });
289
+ } catch {
290
+ return { acquired: false, reason: 'error' };
291
+ }
292
+ const result = acquire({
293
+ lockPath: path.join(dir, reservationName(workload)),
294
+ timeoutMs: opts.staleMs,
295
+ heartbeatMs: HOLDER_HEARTBEAT_MS,
296
+ fsImpl: opts.fsImpl,
297
+ });
298
+ if (result.acquired) held = result;
299
+ return result.acquired ? result : { acquired: false, reason: 'error' };
300
+ };
301
+ return {
302
+ tryOnce: () => underAdmissionMutex(opts, admit),
303
+ release: () => held?.release(),
304
+ };
305
+ }
306
+
307
+ /**
308
+ * An undeclared run: take the legacy lockfile, then wait (still holding it,
309
+ * so nothing new is admitted) until every live reservation has drained.
310
+ *
311
+ * @param {{ lockPath: string, capacity: number, staleMs: number,
312
+ * fsImpl: object, nowFn: () => number, killFn?: Function,
313
+ * acquireOnceFn: typeof acquireSweepLock }} opts
314
+ */
315
+ function createExclusiveAttempt(opts) {
316
+ let held = null;
317
+ const drained = () => {
318
+ const live = readLiveReservations(opts);
319
+ if (live === null || live.length === 0) return held;
320
+ return blocked({
321
+ reason: 'capacity',
322
+ used: live.reduce((sum, r) => sum + r.weight, 0),
323
+ requested: opts.capacity,
324
+ capacity: opts.capacity,
325
+ holder: live[0].holder,
326
+ });
327
+ };
328
+ const tryOnce = () => {
329
+ if (!held) {
330
+ const first = opts.acquireOnceFn({
331
+ lockPath: opts.lockPath,
332
+ timeoutMs: opts.staleMs,
333
+ heartbeatMs: HOLDER_HEARTBEAT_MS,
334
+ fsImpl: opts.fsImpl,
335
+ });
336
+ if (!first.acquired) return first;
337
+ held = first;
338
+ }
339
+ if (!hasReservations(opts)) return held;
340
+ const verdict = underAdmissionMutex(opts, drained);
341
+ return verdict.reason === 'error' ? held : verdict;
342
+ };
343
+ return {
344
+ tryOnce,
345
+ release: () => held?.release(),
346
+ };
347
+ }
348
+
349
+ function hasReservations({ lockPath, fsImpl }) {
350
+ try {
351
+ return fsImpl.readdirSync(reservationsDir(lockPath)).length > 0;
352
+ } catch {
353
+ return false;
354
+ }
355
+ }
356
+
357
+ const LOCK_TAG = '[full-suite-lock]';
358
+
359
+ /** The declared-run wait line; `null` leaves the exclusive wording. */
360
+ export function admissionWaitLine(workload, blocking, waitMs) {
361
+ if (workload?.kind !== 'declared') return null;
362
+ return `${LOCK_TAG} ⏳ waiting for admission of \`${workload.command}\` (weight ${workload.weight}; ${describeBlocking(blocking)}) — waiting up to ${Math.round(waitMs / 1000)}s before spawning.`;
363
+ }
364
+
365
+ /** The declared-run admitted line; `null` leaves the exclusive wording. */
366
+ export function admittedLine(workload, waited) {
367
+ if (workload?.kind !== 'declared') return null;
368
+ return `${LOCK_TAG} ✅ admitted \`${workload.command}\` (weight ${workload.weight}, waited ${waited}s).`;
369
+ }
370
+
371
+ /** A reason worth naming over the holder pid; `null` for a plain queue. */
372
+ export function blockingLabel(blocking) {
373
+ return blocking && blocking.reason !== 'queue'
374
+ ? describeBlocking(blocking)
375
+ : null;
376
+ }
377
+
378
+ /** The progress-event `blocking` field, without the holder it duplicates. */
379
+ export function publicBlocking(blocking, queueAhead) {
380
+ if (!blocking) return {};
381
+ const { holder: _holder, ...rest } = blocking;
382
+ return {
383
+ blocking:
384
+ rest.reason === 'queue' && Number.isInteger(queueAhead)
385
+ ? { ...rest, queueAhead }
386
+ : rest,
387
+ };
388
+ }
389
+
390
+ /**
391
+ * @param {{ reason: string, used?: number, requested?: number,
392
+ * capacity?: number, resource?: string, queueAhead?: number }} blocking
393
+ * @returns {string}
394
+ */
395
+ export function describeBlocking(blocking) {
396
+ switch (blocking?.reason) {
397
+ case 'capacity':
398
+ return `capacity ${blocking.used}/${blocking.capacity} in use, ${blocking.requested} requested`;
399
+ case 'resource':
400
+ return `resource "${blocking.resource}" is held`;
401
+ case 'exclusive':
402
+ return 'an exclusive full suite holds the lock';
403
+ case 'queue':
404
+ return 'an earlier waiter is first in line';
405
+ case 'admission':
406
+ return 'another process is mid-admission';
407
+ default:
408
+ return 'blocked';
409
+ }
410
+ }
@@ -0,0 +1,56 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Refresh the bundle-size baseline via `refreshBaseline({ kind:
4
+ * 'bundle-size' })`: weigh every `gates['bundle-size'].bundles[]` artifact
5
+ * already on disk. Scope is always full — bundle names are not paths, so no
6
+ * diff can narrow it. Never builds the project.
7
+ */
8
+
9
+ // Must be the first import: fails fast before any third-party import loads.
10
+ import './lib/runtime-deps/ensure-installed.js';
11
+ import path from 'node:path';
12
+ import { refreshBaseline } from './lib/baselines/refresh-service.js';
13
+ import { runAsCli } from './lib/cli-utils.js';
14
+ import { getBaselineEpsilon } from './lib/config/quality.js';
15
+ import { getQuality, resolveConfig } from './lib/config-resolver.js';
16
+ import { Logger } from './lib/Logger.js';
17
+
18
+ const DEFAULT_BASELINE_PATH = 'baselines/bundle-size.json';
19
+
20
+ /** `runAsCli` answers `--help` before `main`, so a usage probe never writes. */
21
+ const USAGE = {
22
+ invocation: 'node .agents/scripts/update-bundle-size-baseline.js',
23
+ summary:
24
+ 'Weigh → write the bundle-size baseline: one row per `delivery.quality.gates.bundle-size.bundles[]` entry, with the raw and gzipped KB of every file its `path` glob matches. Always a full refresh.',
25
+ notes: [
26
+ 'Build the project first — this script never builds, and a declared bundle that matches no file fails the refresh rather than recording 0 KB.',
27
+ ],
28
+ };
29
+
30
+ async function main() {
31
+ const cwd = process.cwd();
32
+ const gate = getQuality(resolveConfig({ cwd })).gates?.['bundle-size'] ?? {};
33
+ const baselinePath = gate.baselinePath ?? DEFAULT_BASELINE_PATH;
34
+ const writePath = path.resolve(cwd, baselinePath);
35
+
36
+ Logger.info('[BundleSize] Updating baseline...');
37
+ const result = await refreshBaseline({
38
+ kind: 'bundle-size',
39
+ cwd,
40
+ fullScope: true,
41
+ writePath,
42
+ epsilon: getBaselineEpsilon('bundle-size'),
43
+ });
44
+ Logger.info(
45
+ `[BundleSize] ✅ Baseline updated: ${result.envelope.rows.length} bundle(s) recorded at ${baselinePath}, wrote=${result.wrote}.`,
46
+ );
47
+ }
48
+
49
+ runAsCli(import.meta.url, main, {
50
+ source: 'bundle-size-baseline',
51
+ usage: USAGE,
52
+ onError: (err) => {
53
+ Logger.error(`[BundleSize] ❌ Fatal error: ${err?.message ?? err}`);
54
+ process.exitCode = 1;
55
+ },
56
+ });
@@ -1,26 +1,21 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * Refresh the coverage baseline from the `coverage-final.json` on disk via
3
+ * Refresh the coverage baseline from the configured `coverage.coveragePath`
4
+ * artifact (Istanbul `coverage-final.json`) on disk via
4
5
  * `refreshBaseline({ kind: 'coverage' })`. Never runs the suite, so the
5
6
  * refresh is idempotent and the output can be inspected first.
6
7
  */
7
8
 
8
- import { createRequire } from 'node:module';
9
- import path from 'node:path';
10
9
  import { resolveUpdaterRefreshScope } from './lib/baselines/coverage-refresh-scope.js';
11
10
  import {
12
- buildCoverageUpdaterScorer,
11
+ buildCoverageRefreshOpts,
12
+ coverageUpdaterTargets,
13
+ loadC8ScopeConfig,
13
14
  resolveCoverageUpdaterScope,
14
15
  } from './lib/baselines/coverage-updater-cli.js';
15
16
  import { refreshBaseline } from './lib/baselines/refresh-service.js';
16
17
  import { runAsCli } from './lib/cli-utils.js';
17
- import { getBaselineEpsilon } from './lib/config/quality.js';
18
- import {
19
- buildScopePredicate,
20
- COVERAGE_BASELINE_PATH,
21
- readCoverageFinal,
22
- scoreCoverageFinal,
23
- } from './lib/coverage-baseline.js';
18
+ import { getQuality, resolveConfig } from './lib/config-resolver.js';
24
19
  import { Logger } from './lib/Logger.js';
25
20
 
26
21
  /** `runAsCli` answers `--help` before `main`, so a usage probe never writes. */
@@ -28,7 +23,7 @@ const USAGE = {
28
23
  invocation:
29
24
  'node .agents/scripts/update-coverage-baseline.js [--full-scope | --diff-scope <ref>]',
30
25
  summary:
31
- 'Score → write the coverage baseline from the coverage-final.json already on disk. With no scope flag the refresh is scoped to the files changed in `origin/main..HEAD`; out-of-scope rows are preserved verbatim.',
26
+ 'Score → write the coverage baseline from the coverage artifact (`delivery.quality.gates.coverage.coveragePath`, Istanbul coverage-final.json) already on disk. With no scope flag the refresh is scoped to the files changed in `origin/main..HEAD`; out-of-scope rows are preserved verbatim.',
32
27
  flags: [
33
28
  [
34
29
  '--full-scope',
@@ -45,49 +40,29 @@ const USAGE = {
45
40
  ],
46
41
  };
47
42
 
48
- /** CommonJS `require`, for the `.c8rc.cjs` scope config below. */
49
- const require = createRequire(import.meta.url);
50
-
51
- /**
52
- * Load the c8 include/exclude scope. Kept in the CLI rather than the extracted
53
- * scorer because it is the one genuinely environment-bound step — a CJS
54
- * `require` of a config file resolved against the working tree — and the
55
- * scorer takes it as a seam so a test never touches the real `.c8rc.cjs`.
56
- */
57
- function loadC8Scope(cwd) {
58
- return require(path.resolve(cwd, '.c8rc.cjs'));
59
- }
60
-
61
43
  function main() {
62
44
  const cwd = process.cwd();
63
45
  const { fullScope, diffScopeRef } = resolveCoverageUpdaterScope(
64
46
  process.argv.slice(2),
65
47
  );
66
- Logger.info('[Coverage] Updating baseline from coverage-final.json...');
67
-
68
- const absBaselinePath = path.resolve(cwd, COVERAGE_BASELINE_PATH);
69
- const refreshOpts = {
70
- kind: 'coverage',
71
- writePath: absBaselinePath,
72
- epsilon: getBaselineEpsilon('coverage'),
73
- scorer: buildCoverageUpdaterScorer(cwd, {
74
- readCoverage: readCoverageFinal,
75
- loadScope: loadC8Scope,
76
- buildScope: buildScopePredicate,
77
- score: scoreCoverageFinal,
78
- }),
79
- };
48
+ const targets = coverageUpdaterTargets(
49
+ getQuality(resolveConfig({ cwd })).coverage,
50
+ cwd,
51
+ );
52
+ Logger.info(`[Coverage] Updating baseline from ${targets.coveragePath}...`);
53
+ const refreshOpts = buildCoverageRefreshOpts(cwd, targets);
80
54
  // No flag and a full artifact -> the service derives the diff via
81
55
  // `origin/main..HEAD` (its default baseRef/headRef).
82
56
  return resolveUpdaterRefreshScope(cwd, {
83
57
  fullScope,
84
58
  diffScopeRef,
85
- loadScope: loadC8Scope,
59
+ loadScope: loadC8ScopeConfig,
60
+ readCoverage: targets.readCoverage,
86
61
  })
87
62
  .then((scope) => refreshBaseline({ ...refreshOpts, ...scope }))
88
63
  .then((result) => {
89
64
  Logger.info(
90
- `[Coverage] ✅ Baseline updated: ${result.envelope.rows.length} file(s) recorded at ${COVERAGE_BASELINE_PATH} (${absBaselinePath}). scope=${result.scope.mode}, wrote=${result.wrote}.`,
65
+ `[Coverage] ✅ Baseline updated: ${result.envelope.rows.length} file(s) recorded at ${targets.baselinePath} (${targets.absBaselinePath}). scope=${result.scope.mode}, wrote=${result.wrote}.`,
91
66
  );
92
67
  });
93
68
  }