mandrel 2.85.0 → 2.86.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.
@@ -76,7 +76,8 @@
76
76
  },
77
77
  "delivery": {
78
78
  "execution": {
79
- "fullSuiteLock": true
79
+ "fullSuiteLock": true,
80
+ "workloads": []
80
81
  },
81
82
  "docsFreshness": {
82
83
  "paths": ["README.md"]
@@ -135,8 +135,10 @@ Everything `/mandrel-deliver` and `single-story-close` consume: worktree isolati
135
135
 
136
136
  | Key | Required | Type | Default | Description |
137
137
  | --- | --- | --- | --- | --- |
138
- | `execution` | No | `object` | — | Serialization of the full-suite spawns delivery drives. |
139
- | `execution.fullSuiteLock` | No | `boolean` | `true` | 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. |
138
+ | `execution` | No | `object` | — | Serialization and capacity admission of the suite spawns delivery drives. |
139
+ | `execution.fullSuiteLock` | No | `boolean` | `true` | 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. |
140
+ | `execution.capacity` | No | `integer` | — | 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. |
141
+ | `execution.workloads[]` | No | `array<object>` | `[]` | 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. Each item has: command, weight, resources. |
140
142
  | `docsFreshness` | No | `object` | — | Documentation-freshness scope: the files a change of consequence is expected to touch. Read by the audit-documentation lens to seed its target set; no delivery gate enforces it. |
141
143
  | `docsFreshness.paths` | No | `array<string>` | `["README.md"]` | Repo-relative documentation paths the audit-documentation lens adds to its target set. |
142
144
  | `tempRetention` | No | `object` | — | Story #4794. Auto-purge of spent temp artifacts once their Story lands. Classification is an allowlist: only the declared classes below are ever deleted, so unrecognized files under tempRoot are reported with their size and left alone (`/clean-temp` is the operator path for them). signals.ndjson is never purged by any path. |
@@ -355,12 +355,51 @@
355
355
  "properties": {
356
356
  "execution": {
357
357
  "type": "object",
358
- "description": "Serialization of the full-suite spawns delivery drives.",
358
+ "description": "Serialization and capacity admission of the suite spawns delivery drives.",
359
359
  "properties": {
360
360
  "fullSuiteLock": {
361
361
  "type": "boolean",
362
- "description": "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.",
362
+ "description": "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.",
363
363
  "default": true
364
+ },
365
+ "capacity": {
366
+ "type": "integer",
367
+ "minimum": 1,
368
+ "description": "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."
369
+ },
370
+ "workloads": {
371
+ "type": "array",
372
+ "description": "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.",
373
+ "items": {
374
+ "type": "object",
375
+ "required": ["command", "weight"],
376
+ "properties": {
377
+ "command": {
378
+ "type": "string",
379
+ "not": {
380
+ "pattern": "([;&|`]|\\$\\()"
381
+ },
382
+ "minLength": 1,
383
+ "description": "The exact suite argv, as `project.commands.test` spells it (or `npm run test:coverage` for coverage capture)."
384
+ },
385
+ "weight": {
386
+ "type": "integer",
387
+ "minimum": 1,
388
+ "description": "CPU workers the run occupies, including its nested pool."
389
+ },
390
+ "resources": {
391
+ "type": "array",
392
+ "uniqueItems": true,
393
+ "items": {
394
+ "type": "string",
395
+ "pattern": "^[a-z0-9][a-z0-9-]*$"
396
+ },
397
+ "description": "Names of shared resources this run needs exclusively."
398
+ }
399
+ },
400
+ "additionalProperties": false
401
+ },
402
+ "default": []
364
403
  }
365
404
  },
366
405
  "additionalProperties": false
@@ -5,7 +5,7 @@
5
5
  * passed for the current HEAD and tree, and recording a pass for the next
6
6
  * caller. `--standalone` is required: it keys evidence by Story id, the same
7
7
  * keyspace close consults, so worker-side verify[] runs credit the close.
8
- * `--gate test` takes the host full-suite lock.
8
+ * `--gate test` is admitted through the full-suite lock.
9
9
  */
10
10
 
11
11
  import { spawnSync } from 'node:child_process';
@@ -232,7 +232,7 @@ export function runLockedSuite(
232
232
  const lockHooks = lockEventHooks(claimLockEventSink(env));
233
233
  return withFullSuiteLockAsync(
234
234
  {
235
- ...fullSuiteLockPolicy(config, env),
235
+ ...fullSuiteLockPolicy(config, env, [cmd, ...args]),
236
236
  cwd,
237
237
  log,
238
238
  rerunCommand: ['node', ...process.argv.slice(1)].join(' '),
@@ -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,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
  };
@@ -1,7 +1,8 @@
1
1
  /**
2
- * full-suite-lock.js — serialize full-suite spawns across one host's
3
- * worktrees (they contend for cores and a shared coverage artifact), over
4
- * the `sweep-lock.js` primitive.
2
+ * full-suite-lock.js — admit suite spawns across one repository's worktrees
3
+ * (they contend for cores and shared artifacts), over the `sweep-lock.js`
4
+ * primitive. An undeclared spawn runs exclusively; a declared one is admitted
5
+ * against a capacity budget by `suite-admission.js`.
5
6
  *
6
7
  * It queues, never overlaps: an expired wait behind a live holder spawns
7
8
  * nothing ({@link LOCK_WAIT_EXPIRED_EXIT_CODE}). A dead holder is taken over
@@ -16,6 +17,17 @@ import { getQuality } from './config/quality.js';
16
17
  import { mainCheckoutRoot } from './config/temp-paths.js';
17
18
  import { isFirstInLine, waitInLine } from './full-suite-queue.js';
18
19
  import { acquireSweepLock } from './single-story-sweep/sweep-lock.js';
20
+ import {
21
+ ADMISSION_REFUSED_EXIT_CODE,
22
+ completedProgress,
23
+ createAttempt,
24
+ describeRefusal,
25
+ FULL_SUITE_STALE_MS,
26
+ resolveAdmission,
27
+ resolveSuiteCapacity,
28
+ } from './suite-admission.js';
29
+
30
+ export { ADMISSION_REFUSED_EXIT_CODE };
19
31
 
20
32
  /** Environment escape hatch: set to `0`/`false`/`off`/`no` to disable. */
21
33
  export const FULL_SUITE_LOCK_ENV = 'MANDREL_FULL_SUITE_LOCK';
@@ -38,6 +50,9 @@ const FALSEY = /^(0|false|off|no)$/i;
38
50
 
39
51
  const LOCK_TAG = '[full-suite-lock]';
40
52
 
53
+ /** The argv coverage capture spawns — its workload identity. */
54
+ const COVERAGE_CAPTURE_ARGV = Object.freeze(['npm', 'run', 'test:coverage']);
55
+
41
56
  const LOCK_DEFAULTS = Object.freeze({
42
57
  enabled: true,
43
58
  log: () => {},
@@ -49,24 +64,26 @@ const LOCK_DEFAULTS = Object.freeze({
49
64
  sleepFn: (ms) => defaultSleep(ms),
50
65
  acquireOnceFn: (opts) => acquireSweepLock(opts),
51
66
  onWaitExpired: () => LOCK_WAIT_EXPIRED_EXIT_CODE,
67
+ onAdmissionRefused: () => ADMISSION_REFUSED_EXIT_CODE,
68
+ workload: Object.freeze({ kind: 'exclusive' }),
69
+ capacity: resolveSuiteCapacity(),
52
70
  onLockOutcome: () => {},
53
71
  onLockProgress: () => {},
54
72
  rerunCommand: 'the same command',
55
73
  });
56
74
 
57
75
  /**
58
- * The one wait budget every full-suite lock taker uses. A holder's suite is
59
- * killed at its supervisor's `killBoundMs` (the coverage gate's `timeoutMs`),
60
- * so waiting that long always observes a release or a death. The stale
61
- * threshold is four fifths of the wait: never above the budget, and a live
62
- * holder (heartbeating at a third of its own threshold) is never read stale.
76
+ * The one wait budget every lock taker uses: a holder's suite is killed at
77
+ * its supervisor's `killBoundMs` (the coverage gate's `timeoutMs`). Staleness
78
+ * is fixed, never derived from the waiter's budget — a waiter with a shorter
79
+ * budget than the holder's timeout must not read a live holder stale.
63
80
  *
64
81
  * @param {number} [killBoundMs]
65
82
  * @returns {{ waitMs: number, staleMs: number }}
66
83
  */
67
84
  export function resolveFullSuiteLockBudget(killBoundMs) {
68
85
  const waitMs = Math.max(MIN_WAIT_MS, Number(killBoundMs) || 0);
69
- return { waitMs, staleMs: waitMs - waitMs / 5 };
86
+ return { waitMs, staleMs: FULL_SUITE_STALE_MS };
70
87
  }
71
88
 
72
89
  /**
@@ -101,28 +118,34 @@ export function resolveFullSuiteLockPath({
101
118
  /**
102
119
  * Uncontended fast path, skipped when waiters are queued (no overtaking).
103
120
  *
104
- * @returns {{ lock: object|null, lockPath: string|null }} null `lock` with a
105
- * `lockPath` means wait; both null means no lock.
121
+ * @returns {{ attempt: object|null, lock: object|null, lockPath: string|null,
122
+ * blocking?: object }} null `lock` with a `lockPath` means wait; a null
123
+ * `lockPath` means no lock.
106
124
  */
107
- function beginLock({ staleMs, fsImpl, acquireOnceFn, ...where }) {
108
- const resolved = lockHome(where);
109
- if (resolved === null) return NO_LOCK;
110
- if (!isFirstInLine({ lockPath: resolved, ticket: null, staleMs, fsImpl })) {
111
- return { lock: null, lockPath: resolved };
125
+ function beginLock(opts) {
126
+ const lockPath = lockHome(opts);
127
+ if (lockPath === null) return NO_LOCK;
128
+ const attempt = createAttempt({ ...opts, lockPath });
129
+ return { attempt, lockPath, ...firstTry(opts, attempt, lockPath) };
130
+ }
131
+
132
+ const NO_LOCK = Object.freeze({ attempt: null, lock: null, lockPath: null });
133
+
134
+ const QUEUED = Object.freeze({ reason: 'queue' });
135
+
136
+ function firstTry({ staleMs, fsImpl }, attempt, lockPath) {
137
+ if (!isFirstInLine({ lockPath, ticket: null, staleMs, fsImpl })) {
138
+ return { lock: null, blocking: QUEUED };
112
139
  }
113
- const first = acquireOnceFn({
114
- lockPath: resolved,
115
- timeoutMs: staleMs,
116
- fsImpl,
117
- });
118
- if (first.acquired) return { lock: first, lockPath: resolved };
119
- // A hard I/O error will not resolve by waiting — proceed unserialized.
120
- return first.reason === 'error'
121
- ? NO_LOCK
122
- : { lock: null, lockPath: resolved };
140
+ return afterFirst(attempt.tryOnce());
123
141
  }
124
142
 
125
- const NO_LOCK = Object.freeze({ lock: null, lockPath: null });
143
+ /** A hard I/O error will not resolve by waiting — proceed unserialized. */
144
+ function afterFirst(first) {
145
+ if (first.acquired) return { lock: first };
146
+ if (first.reason === 'error') return { lock: null, lockPath: null };
147
+ return { lock: null, blocking: first.blocking };
148
+ }
126
149
 
127
150
  /**
128
151
  * @param {{ enabled: boolean, cwd: string, lockPath?: string }} where
@@ -179,19 +202,33 @@ function consult(probe, applies) {
179
202
  */
180
203
  export async function withFullSuiteLockAsync(options, spawn) {
181
204
  const opts = withDefaults(options);
182
- const { lock, lockPath } = beginLock(opts);
183
- const wait =
184
- lock === null && lockPath !== null
185
- ? await waitInLine({ ...opts, lockPath })
186
- : { held: lock, expired: false, waited: false, waitedMs: 0 };
187
- reportOutcome(opts.onLockOutcome, wait);
205
+ if (isRefused(opts)) return refuse(opts);
206
+ const begun = beginLock(opts);
188
207
  try {
208
+ const wait = await awaitTurn(opts, begun);
209
+ reportOutcome(opts.onLockOutcome, wait);
189
210
  return await spawnOrStandIn(opts, wait, spawn);
190
211
  } finally {
191
- if (wait.held?.acquired) wait.held.release();
212
+ begun.attempt?.release();
192
213
  }
193
214
  }
194
215
 
216
+ function isRefused({ enabled, workload }) {
217
+ return enabled && workload?.kind === 'refused';
218
+ }
219
+
220
+ function refuse(opts) {
221
+ opts.log(describeRefusal(opts.workload));
222
+ return opts.onAdmissionRefused(opts.workload);
223
+ }
224
+
225
+ function awaitTurn(opts, { attempt, lock, lockPath, blocking }) {
226
+ if (lock !== null || lockPath === null) {
227
+ return { held: lock, expired: false, waited: false, waitedMs: 0 };
228
+ }
229
+ return waitInLine({ ...opts, lockPath, attempt, blocking });
230
+ }
231
+
195
232
  /** An I/O-error wait is no outcome; a throwing callback never costs the spawn. */
196
233
  function reportOutcome(onLockOutcome, wait) {
197
234
  if (!isFinishedWait(wait)) return;
@@ -225,8 +262,23 @@ async function spawnOrStandIn(opts, wait, spawn) {
225
262
  );
226
263
  return probe.value;
227
264
  }
228
- if (wait.expired) return opts.onWaitExpired(wait.holder);
229
- return await spawn({ lockWaitMs: wait.waitedMs ?? 0 });
265
+ return wait.expired
266
+ ? opts.onWaitExpired(wait.holder)
267
+ : await timedSpawn(opts, wait, spawn);
268
+ }
269
+
270
+ /** Wait and execution reach progress as separate figures. */
271
+ async function timedSpawn(opts, wait, spawn) {
272
+ const startedAt = opts.nowFn();
273
+ const result = await spawn({ lockWaitMs: wait.waitedMs ?? 0 });
274
+ if (wait.waited) reportCompleted(opts, wait, opts.nowFn() - startedAt);
275
+ return result;
276
+ }
277
+
278
+ function reportCompleted(opts, wait, ranMs) {
279
+ try {
280
+ opts.onLockProgress(completedProgress(wait.waitedMs, opts.waitMs, ranMs));
281
+ } catch {}
230
282
  }
231
283
 
232
284
  /**
@@ -240,14 +292,19 @@ function defaultSleep(ms) {
240
292
  }
241
293
 
242
294
  /**
295
+ * The one admission policy every caller resolves: enablement, budget,
296
+ * capacity, and the workload `argv` classifies to.
297
+ *
243
298
  * @param {object} [config]
244
299
  * @param {Record<string, string|undefined>} [env]
300
+ * @param {string[]} [argv]
245
301
  */
246
- export function fullSuiteLockPolicy(config, env = process.env) {
302
+ export function fullSuiteLockPolicy(config, env = process.env, argv) {
247
303
  return {
248
304
  ...resolveFullSuiteLockBudget(getQuality(config).coverage?.timeoutMs),
249
305
  enabled: isFullSuiteLockEnabled({ config, env }),
250
306
  onWaitExpired: () => LOCK_WAIT_EXPIRED_EXIT_CODE,
307
+ ...resolveAdmission(config, argv),
251
308
  };
252
309
  }
253
310
 
@@ -267,7 +324,10 @@ export function lockedCapture(
267
324
  env = process.env,
268
325
  lockOptions = {},
269
326
  ) {
270
- const policy = { ...fullSuiteLockPolicy(config, env), ...lockOptions };
327
+ const policy = {
328
+ ...fullSuiteLockPolicy(config, env, COVERAGE_CAPTURE_ARGV),
329
+ ...lockOptions,
330
+ };
271
331
  return (captureOpts = {}) =>
272
332
  withFullSuiteLockAsync(
273
333
  {
@@ -12,6 +12,12 @@ import {
12
12
  isHolderAlive,
13
13
  readLockHolderPid,
14
14
  } from './single-story-sweep/sweep-lock.js';
15
+ import {
16
+ admissionWaitLine,
17
+ admittedLine,
18
+ blockingLabel,
19
+ publicBlocking,
20
+ } from './suite-admission.js';
15
21
 
16
22
  const LOCK_TAG = '[full-suite-lock]';
17
23
 
@@ -177,9 +183,10 @@ function holderLabel(lockPath, fsImpl) {
177
183
 
178
184
  /**
179
185
  * @typedef {{
180
- * phase: 'waiting'|'still-waiting'|'acquired'|'expired',
186
+ * phase: 'waiting'|'still-waiting'|'admitted'|'completed'|'expired',
181
187
  * waitedSeconds: number, waitBudgetSeconds: number,
182
- * holder?: LockHolder, queueAhead?: number,
188
+ * holder?: LockHolder, queueAhead?: number, blocking?: object,
189
+ * waitMs?: number, executionMs?: number,
183
190
  * }} LockProgress
184
191
  */
185
192
 
@@ -187,7 +194,8 @@ function holderLabel(lockPath, fsImpl) {
187
194
  * @param {{
188
195
  * lockPath: string, waitMs: number, pollMs: number, staleMs: number,
189
196
  * reportMs: number, fsImpl: object, nowFn: () => number,
190
- * sleepFn: (ms: number) => Promise<void>, acquireOnceFn: Function,
197
+ * sleepFn: (ms: number) => Promise<void>,
198
+ * attempt: { tryOnce: () => object }, workload?: object,
191
199
  * log: (m: string) => void, rerunCommand: string,
192
200
  * onLockProgress?: (progress: LockProgress) => void,
193
201
  * }} opts A throwing `onLockProgress` is swallowed.
@@ -196,6 +204,7 @@ function holderLabel(lockPath, fsImpl) {
196
204
  export async function waitInLine(opts) {
197
205
  const { lockPath, fsImpl, nowFn } = opts;
198
206
  const clock = waitClock(opts);
207
+ clock.blocking = opts.blocking ?? null;
199
208
  announceWait(opts);
200
209
  reportProgress(opts, clock, 'waiting', null);
201
210
  const ticket = enqueueWaiter({ lockPath, nowFn, fsImpl });
@@ -225,25 +234,36 @@ function reportProgress(opts, clock, phase, ticket, knownHolder) {
225
234
  phase,
226
235
  waitedSeconds: clock.waited(),
227
236
  waitBudgetSeconds: Math.round(Math.max(0, opts.waitMs) / 1000),
228
- ...(phase === 'acquired' ? {} : waitContext(opts, ticket, knownHolder)),
237
+ ...(phase === 'admitted'
238
+ ? {}
239
+ : waitContext(opts, ticket, knownHolder, clock.blocking)),
229
240
  });
230
241
  } catch {}
231
242
  }
232
243
 
233
- /** Holder and queue position, each only when readable. */
234
- function waitContext({ lockPath, staleMs, fsImpl, nowFn }, ticket, known) {
235
- const holder = known ?? readLockHolder(lockPath, { fsImpl, nowFn });
244
+ /** Holder, queue position and what blocks admission, each when known. */
245
+ function waitContext(opts, ticket, known, blocking) {
246
+ const { lockPath, staleMs, fsImpl, nowFn } = opts;
247
+ const holder = known ?? waitHolder(opts, blocking);
236
248
  const queueAhead = countAhead({ lockPath, ticket, staleMs, nowFn, fsImpl });
237
249
  return {
238
250
  ...(holder.ownerId === null && holder.pid === null ? {} : { holder }),
239
251
  ...(queueAhead === null ? {} : { queueAhead }),
252
+ ...publicBlocking(blocking, queueAhead),
240
253
  };
241
254
  }
242
255
 
243
- function announceWait({ lockPath, waitMs, fsImpl, log }) {
244
- log(
245
- `${LOCK_TAG} ⏳ another full suite is already running on this host (${holderLabel(lockPath, fsImpl)}) — waiting up to ${Math.round(waitMs / 1000)}s for it to finish before spawning.`,
246
- );
256
+ function waitHolder({ lockPath, fsImpl, nowFn }, blocking) {
257
+ return blocking?.holder ?? readLockHolder(lockPath, { fsImpl, nowFn });
258
+ }
259
+
260
+ function announceWait(opts) {
261
+ const line = admissionWaitLine(opts.workload, opts.blocking, opts.waitMs);
262
+ opts.log(line ?? exclusiveWaitLine(opts));
263
+ }
264
+
265
+ function exclusiveWaitLine({ lockPath, waitMs, fsImpl }) {
266
+ return `${LOCK_TAG} ⏳ another full suite is already running on this host (${holderLabel(lockPath, fsImpl)}) — waiting up to ${Math.round(waitMs / 1000)}s for it to finish before spawning.`;
247
267
  }
248
268
 
249
269
  function giveUp(opts, clock) {
@@ -269,13 +289,12 @@ async function pollForTurn(opts, ticket, clock) {
269
289
  await opts.sleepFn(Math.max(0, opts.pollMs));
270
290
  refreshTicket(ticket, { nowFn, fsImpl });
271
291
  const attempt = isFirstInLine({ lockPath, ticket, staleMs, nowFn, fsImpl })
272
- ? opts.acquireOnceFn({ lockPath, timeoutMs: staleMs, fsImpl })
273
- : { acquired: false };
292
+ ? opts.attempt.tryOnce()
293
+ : { acquired: false, blocking: { reason: 'queue' } };
294
+ clock.blocking = attempt.blocking ?? null;
274
295
  if (attempt.acquired) {
275
- log(
276
- `${LOCK_TAG} ✅ acquired the full-suite lock (waited ${clock.waited()}s).`,
277
- );
278
- reportProgress(opts, clock, 'acquired', ticket);
296
+ log(acquiredLine(opts.workload, clock.waited()));
297
+ reportProgress(opts, clock, 'admitted', ticket);
279
298
  return { held: attempt, expired: false };
280
299
  }
281
300
  // A hard I/O error will not resolve by waiting; it is not an expiry.
@@ -285,11 +304,19 @@ async function pollForTurn(opts, ticket, clock) {
285
304
  return null;
286
305
  }
287
306
 
307
+ function acquiredLine(workload, waited) {
308
+ return (
309
+ admittedLine(workload, waited) ??
310
+ `${LOCK_TAG} ✅ acquired the full-suite lock (waited ${waited}s).`
311
+ );
312
+ }
313
+
288
314
  function reportStillWaiting(opts, clock, ticket) {
289
315
  const { lockPath, fsImpl, nowFn, log, reportMs } = opts;
290
316
  if (nowFn() < clock.nextReport) return;
317
+ const reason = blockingLabel(clock.blocking) ?? holderLabel(lockPath, fsImpl);
291
318
  log(
292
- `${LOCK_TAG} ⏳ still waiting for the full-suite lock (${holderLabel(lockPath, fsImpl)}, waited ${clock.waited()}s).`,
319
+ `${LOCK_TAG} ⏳ still waiting for the full-suite lock (${reason}, waited ${clock.waited()}s).`,
293
320
  );
294
321
  reportProgress(opts, clock, 'still-waiting', ticket);
295
322
  clock.nextReport += reportMs;