mandrel 2.107.0 → 2.108.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.
@@ -403,6 +403,35 @@ A config still carrying the retired key is a hard validation failure; the
403
403
  reporters. `coverage-capture.js` fails a green run that leaves no artifact
404
404
  there (and writes no capture stamp), and a full-scope coverage or CRAP
405
405
  refresh with no artifact exits non-zero naming the path.
406
+ - **Admission for a script you run by hand.** Every suite spawn Mandrel
407
+ admits under `execution.fullSuiteLock` carries `MANDREL_SUITE_RESERVATION`,
408
+ the absolute path of the lockfile or reservation it holds, and every
409
+ descendant inherits it. A consumer script that may also be started by hand
410
+ (say `test:coverage:affected`, run from an agent shell) admits itself
411
+ through the materialized lock library rather than bypassing admission:
412
+
413
+ ```js
414
+ import { withSuiteAdmission } from '../.agents/scripts/lib/full-suite-lock.js';
415
+
416
+ const code = await withSuiteAdmission(
417
+ { argv: ['pnpm', 'run', 'test:coverage:affected'], cwd: process.cwd() },
418
+ ({ env }) => runSuite({ env: { ...process.env, ...env } }),
419
+ );
420
+ process.exit(code);
421
+ ```
422
+
423
+ Pass `argv` exactly as it appears in `execution.workloads[]`. `env` (default
424
+ `process.env`), `log` and `config` (default: resolved from `cwd`) are
425
+ optional. When the environment already names a live reservation in this
426
+ repository's lock home, the callback runs at once inside it and nothing new
427
+ is reserved. Otherwise, including when that reservation's file is gone,
428
+ its holder has died or its heartbeat is stale, the run queues for its
429
+ declared workload, or exclusively when the argv is undeclared, exactly as a
430
+ Mandrel caller would. The callback's `env` names the reservation that
431
+ admitted it; merge it into the child's environment. The helper resolves to
432
+ the callback's result, `75` when the wait expires, or `78` when the
433
+ declared weight exceeds `capacity`. With `MANDREL_FULL_SUITE_LOCK=0` or
434
+ `fullSuiteLock: false` it calls the callback directly with an empty `env`.
406
435
  - **Duplication needs jscpd.** The duplication gate scans with `jscpd` 4, an
407
436
  **optional peer dependency** of `mandrel`: a project that enables
408
437
  `quality.gates.duplication` installs it itself — `npm i -D jscpd@^4`.
@@ -240,13 +240,13 @@ export function runLockedSuite(
240
240
  onLockProgress: lockHooks.onLockProgress,
241
241
  ...lockOptions,
242
242
  },
243
- ({ lockWaitMs }) =>
243
+ (lock) =>
244
244
  runSuiteImpl({
245
245
  cmd,
246
246
  args,
247
247
  cwd,
248
248
  timeoutMs,
249
- lockWaitMs,
249
+ ...lock,
250
250
  onTimings: (t) => {
251
251
  log(`[evidence-gate] ${formatSuiteTimings(t)}`);
252
252
  lockHooks.onTimings(t);
@@ -99,7 +99,7 @@ export function defaultGateRunner(cmd, args, opts = {}) {
99
99
  // `skipIfSatisfied` re-probes after the wait: evidence another suite
100
100
  // deposited meanwhile is returned instead of spawning.
101
101
  return withFullSuiteLockAsync(gateLockOptions(opts), (lock) =>
102
- spawnGate(cmd, args, opts, lock),
102
+ spawnGate(cmd, args, { ...opts, env: { ...opts.env, ...lock.env } }, lock),
103
103
  );
104
104
  }
105
105
 
@@ -15,6 +15,7 @@ import path from 'node:path';
15
15
 
16
16
  import { getQuality } from './config/quality.js';
17
17
  import { mainCheckoutRoot } from './config/temp-paths.js';
18
+ import { resolveConfig } from './config-resolver.js';
18
19
  import { packageScriptArgv } from './detect-package-manager.js';
19
20
  import { isFirstInLine, waitInLine } from './full-suite-queue.js';
20
21
  import { acquireSweepLock } from './single-story-sweep/sweep-lock.js';
@@ -24,12 +25,15 @@ import {
24
25
  createAttempt,
25
26
  describeRefusal,
26
27
  FULL_SUITE_STALE_MS,
28
+ inheritedReservation,
29
+ reservationEnv,
27
30
  resolveAdmission,
28
31
  resolveSuiteCapacity,
32
+ SUITE_RESERVATION_ENV,
29
33
  } from './suite-admission.js';
30
34
  import { defaultSleep } from './util/sleep.js';
31
35
 
32
- export { ADMISSION_REFUSED_EXIT_CODE };
36
+ export { ADMISSION_REFUSED_EXIT_CODE, SUITE_RESERVATION_ENV };
33
37
 
34
38
  /** Environment escape hatch: set to `0`/`false`/`off`/`no` to disable. */
35
39
  export const FULL_SUITE_LOCK_ENV = 'MANDREL_FULL_SUITE_LOCK';
@@ -59,6 +63,7 @@ const LOCK_DEFAULTS = Object.freeze({
59
63
  pollMs: DEFAULT_POLL_MS,
60
64
  reportMs: DEFAULT_REPORT_MS,
61
65
  fsImpl: fs,
66
+ env: process.env,
62
67
  nowFn: Date.now,
63
68
  sleepFn: (ms) => defaultSleep(ms),
64
69
  acquireOnceFn: (opts) => acquireSweepLock(opts),
@@ -180,6 +185,7 @@ function consult(probe, applies) {
180
185
  * @param {{
181
186
  * cwd: string,
182
187
  * enabled?: boolean,
188
+ * env?: Record<string, string|undefined>,
183
189
  * log?: (m: string) => void,
184
190
  * waitMs?: number,
185
191
  * pollMs?: number,
@@ -196,22 +202,46 @@ function consult(probe, applies) {
196
202
  * onLockProgress?: (progress: import('./full-suite-queue.js').LockProgress) => void,
197
203
  * rerunCommand?: string,
198
204
  * }} opts A non-`undefined` `skipIfSatisfied` return stands in for the spawn.
199
- * @param {(timing: { lockWaitMs: number }) => Promise<T>} spawn
205
+ * `env` naming a live holder in this lock home spawns at once, inside it.
206
+ * @param {(lock: { lockWaitMs: number, env: Record<string, string> }) => Promise<T>} spawn
207
+ * `env` carries {@link SUITE_RESERVATION_ENV} for the child; merge it in.
200
208
  * @returns {Promise<T>}
201
209
  */
202
210
  export async function withFullSuiteLockAsync(options, spawn) {
203
211
  const opts = withDefaults(options);
204
212
  if (isRefused(opts)) return refuse(opts);
213
+ return admitAndSpawn(opts, spawn);
214
+ }
215
+
216
+ function admitAndSpawn(opts, spawn) {
217
+ const inherited = inheritedMarker(opts);
218
+ return inherited === null
219
+ ? lockAndSpawn(opts, spawn)
220
+ : spawnInside(opts, inherited, spawn);
221
+ }
222
+
223
+ async function lockAndSpawn(opts, spawn) {
205
224
  const begun = beginLock(opts);
206
225
  try {
207
226
  const wait = await awaitTurn(opts, begun);
208
227
  reportOutcome(opts.onLockOutcome, wait);
209
- return await spawnOrStandIn(opts, wait, spawn);
228
+ return await spawnOrStandIn(opts, wait, spawn, begun.attempt);
210
229
  } finally {
211
230
  begun.attempt?.release();
212
231
  }
213
232
  }
214
233
 
234
+ function inheritedMarker(opts) {
235
+ return inheritedReservation({ ...opts, lockHomeFn: () => lockHome(opts) });
236
+ }
237
+
238
+ function spawnInside(opts, marker, spawn) {
239
+ opts.log(
240
+ `${LOCK_TAG} ↪ already admitted under ${path.basename(marker)} — spawning inside it.`,
241
+ );
242
+ return spawn({ lockWaitMs: 0, env: reservationEnv(marker) });
243
+ }
244
+
215
245
  function isRefused({ enabled, workload }) {
216
246
  return enabled && workload?.kind === 'refused';
217
247
  }
@@ -253,7 +283,7 @@ function withDefaults(options) {
253
283
  return opts;
254
284
  }
255
285
 
256
- async function spawnOrStandIn(opts, wait, spawn) {
286
+ async function spawnOrStandIn(opts, wait, spawn, attempt) {
257
287
  const probe = consult(opts.skipIfSatisfied, wait.waited);
258
288
  if (probe.satisfied) {
259
289
  opts.log(
@@ -263,13 +293,16 @@ async function spawnOrStandIn(opts, wait, spawn) {
263
293
  }
264
294
  return wait.expired
265
295
  ? opts.onWaitExpired(wait.holder)
266
- : await timedSpawn(opts, wait, spawn);
296
+ : await timedSpawn(opts, wait, spawn, attempt);
267
297
  }
268
298
 
269
299
  /** Wait and execution reach progress as separate figures. */
270
- async function timedSpawn(opts, wait, spawn) {
300
+ async function timedSpawn(opts, wait, spawn, attempt) {
271
301
  const startedAt = opts.nowFn();
272
- const result = await spawn({ lockWaitMs: wait.waitedMs ?? 0 });
302
+ const result = await spawn({
303
+ lockWaitMs: wait.waitedMs ?? 0,
304
+ env: reservationEnv(attempt?.heldPath?.()),
305
+ });
273
306
  if (wait.waited) reportCompleted(opts, wait, opts.nowFn() - startedAt);
274
307
  return result;
275
308
  }
@@ -338,15 +371,55 @@ export function lockedCapture(
338
371
  env,
339
372
  coverageCaptureArgv(config, captureOpts),
340
373
  ),
374
+ env,
341
375
  ...lockOptions,
342
376
  cwd: captureOpts.cwd,
343
377
  log: captureOpts.log,
344
378
  skipIfSatisfied: freshnessProbe(captureOpts),
345
379
  },
346
- ({ lockWaitMs }) => runCaptureFn({ ...captureOpts, lockWaitMs }),
380
+ captureInLock(runCaptureFn, captureOpts),
347
381
  );
348
382
  }
349
383
 
384
+ /** The lock's marker joins the capture's own `env`, never replacing it. */
385
+ function captureInLock(runCaptureFn, captureOpts) {
386
+ return ({ lockWaitMs, env }) =>
387
+ runCaptureFn({
388
+ ...captureOpts,
389
+ env: { ...captureOpts.env, ...env },
390
+ lockWaitMs,
391
+ });
392
+ }
393
+
394
+ /**
395
+ * The consumer entry point: admit `argv` exactly as an in-framework caller
396
+ * would, or — when `env` already names a live holder — run inside it.
397
+ * Resolves to `spawn`'s result, 75 on an expired wait, or 78 on a refusal.
398
+ *
399
+ * @template T
400
+ * @param {{ argv: string[], cwd: string,
401
+ * env?: Record<string, string|undefined>, log?: (m: string) => void,
402
+ * config?: object, lockOptions?: object }} opts `lockOptions`: test seams.
403
+ * @param {(lock: { lockWaitMs: number, env: Record<string, string> }) => Promise<T>} spawn
404
+ * @returns {Promise<T|number>}
405
+ */
406
+ export function withSuiteAdmission(
407
+ { argv, cwd, env = process.env, log, config, lockOptions },
408
+ spawn,
409
+ ) {
410
+ const resolved = config ?? resolveConfig({ cwd });
411
+ return withFullSuiteLockAsync(
412
+ {
413
+ ...fullSuiteLockPolicy(resolved, env, argv),
414
+ ...lockOptions,
415
+ cwd,
416
+ env,
417
+ log,
418
+ },
419
+ spawn,
420
+ );
421
+ }
422
+
350
423
  /**
351
424
  * A fresh recheck means exit 0 without spawning.
352
425
  *
@@ -21,6 +21,12 @@ import {
21
21
  readLockHolderPid,
22
22
  } from './single-story-sweep/sweep-lock.js';
23
23
 
24
+ /**
25
+ * Set on every spawn made under a held lockfile or reservation, naming it, so
26
+ * a descendant that asks for admission runs inside its parent's.
27
+ */
28
+ export const SUITE_RESERVATION_ENV = 'MANDREL_SUITE_RESERVATION';
29
+
24
30
  /** `EX_CONFIG`: a declared weight the capacity can never admit. */
25
31
  export const ADMISSION_REFUSED_EXIT_CODE = 78;
26
32
 
@@ -259,6 +265,7 @@ function createDeclaredAttempt(opts) {
259
265
  const { workload, capacity } = opts;
260
266
  const acquire = opts.acquireReservationFn ?? acquireSweepLock;
261
267
  let held = null;
268
+ let heldPath = null;
262
269
  const admit = () => {
263
270
  const legacy = liveLegacyHolder(opts);
264
271
  if (legacy) return blocked({ reason: 'exclusive', holder: legacy });
@@ -289,18 +296,22 @@ function createDeclaredAttempt(opts) {
289
296
  } catch {
290
297
  return { acquired: false, reason: 'error' };
291
298
  }
299
+ const file = path.join(dir, reservationName(workload));
292
300
  const result = acquire({
293
- lockPath: path.join(dir, reservationName(workload)),
301
+ lockPath: file,
294
302
  timeoutMs: opts.staleMs,
295
303
  heartbeatMs: HOLDER_HEARTBEAT_MS,
296
304
  fsImpl: opts.fsImpl,
297
305
  });
298
- if (result.acquired) held = result;
299
- return result.acquired ? result : { acquired: false, reason: 'error' };
306
+ if (!result.acquired) return { acquired: false, reason: 'error' };
307
+ held = result;
308
+ heldPath = file;
309
+ return result;
300
310
  };
301
311
  return {
302
312
  tryOnce: () => underAdmissionMutex(opts, admit),
303
313
  release: () => held?.release(),
314
+ heldPath: () => heldPath,
304
315
  };
305
316
  }
306
317
 
@@ -315,6 +326,7 @@ function createDeclaredAttempt(opts) {
315
326
  */
316
327
  function createExclusiveAttempt(opts) {
317
328
  let held = null;
329
+ let heldPath = null;
318
330
  const drained = () => {
319
331
  const live = readLiveReservations(opts);
320
332
  if (live === null || live.length === 0) return held;
@@ -336,6 +348,7 @@ function createExclusiveAttempt(opts) {
336
348
  });
337
349
  if (!first.acquired) return first;
338
350
  held = first;
351
+ heldPath = opts.lockPath;
339
352
  }
340
353
  const verdict = underAdmissionMutex(opts, drained);
341
354
  return verdict.reason === 'error' ? held : verdict;
@@ -343,9 +356,38 @@ function createExclusiveAttempt(opts) {
343
356
  return {
344
357
  tryOnce,
345
358
  release: () => held?.release(),
359
+ heldPath: () => heldPath,
346
360
  };
347
361
  }
348
362
 
363
+ /** The child environment naming `heldPath`; empty when nothing is held. */
364
+ export function reservationEnv(heldPath) {
365
+ return heldPath ? { [SUITE_RESERVATION_ENV]: heldPath } : {};
366
+ }
367
+
368
+ /**
369
+ * The marker `env` inherits, when it names a live holder in this lock home:
370
+ * the legacy lockfile or one of its reservations, with a live pid and a fresh
371
+ * heartbeat. Any other path — another repository's, a stray file — is `null`.
372
+ *
373
+ * @param {{ env?: Record<string, string|undefined>,
374
+ * lockHomeFn: () => string|null, staleMs: number, fsImpl: object,
375
+ * nowFn: () => number, killFn?: Function }} probe
376
+ * @returns {string|null}
377
+ */
378
+ export function inheritedReservation({ env, lockHomeFn, ...probe }) {
379
+ const marker = env?.[SUITE_RESERVATION_ENV];
380
+ if (typeof marker !== 'string' || !path.isAbsolute(marker)) return null;
381
+ const home = lockHomeFn();
382
+ if (home === null) return null;
383
+ const file = path.resolve(marker);
384
+ const inHome =
385
+ file === path.resolve(home) ||
386
+ (path.dirname(file) === reservationsDir(path.resolve(home)) &&
387
+ RESERVATION_RE.test(path.basename(file)));
388
+ return inHome && holderState(file, probe).live ? marker : null;
389
+ }
390
+
349
391
  const LOCK_TAG = '[full-suite-lock]';
350
392
 
351
393
  /** The declared-run wait line; `null` leaves the exclusive wording. */
package/docs/CHANGELOG.md CHANGED
@@ -15,6 +15,13 @@ All notable changes to this project will be documented in this file.
15
15
  -->
16
16
  <!-- markdownlint-disable-file MD004 MD012 MD037 -->
17
17
 
18
+ ## [2.108.0](https://github.com/dsj1984/mandrel/compare/mandrel-v2.107.0...mandrel-v2.108.0) (2026-10-27)
19
+
20
+
21
+ ### Added
22
+
23
+ * mark admitted suite spawns and export a self-admitting wrapper so hand-run consumer scripts cannot bypass or double-book suite admission ([#5929](https://github.com/dsj1984/mandrel/issues/5929)) ([#5930](https://github.com/dsj1984/mandrel/issues/5930)) ([ed43efc](https://github.com/dsj1984/mandrel/commit/ed43efcc573ac2171f1c59654b2c58bd8059761c))
24
+
18
25
  ## [2.107.0](https://github.com/dsj1984/mandrel/compare/mandrel-v2.106.0...mandrel-v2.107.0) (2026-10-27)
19
26
 
20
27
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mandrel",
3
- "version": "2.107.0",
3
+ "version": "2.108.0",
4
4
  "description": "Claude Code-first opinionated workflow framework: instructions, skills, rules, and SDLC workflows that govern AI coding assistants.",
5
5
  "files": [
6
6
  ".agents/",