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.
@@ -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
+ }
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.86.0](https://github.com/dsj1984/mandrel/compare/mandrel-v2.85.0...mandrel-v2.86.0) (2026-10-14)
19
+
20
+
21
+ ### Added
22
+
23
+ * admit declared focused validation alongside full suites under a repo-scoped capacity budget ([#5668](https://github.com/dsj1984/mandrel/issues/5668)) ([#5669](https://github.com/dsj1984/mandrel/issues/5669)) ([318c132](https://github.com/dsj1984/mandrel/commit/318c132ed6964fcb4b6f3330ff0b3ae08cf39809))
24
+
18
25
  ## [2.85.0](https://github.com/dsj1984/mandrel/compare/mandrel-v2.84.0...mandrel-v2.85.0) (2026-10-13)
19
26
 
20
27
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mandrel",
3
- "version": "2.85.0",
3
+ "version": "2.86.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/",