@gadicc/loom 2.3.1 → 2.5.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 (68) hide show
  1. package/.loom-source-manifest.json +10 -1
  2. package/esm/src/cli/machineSlots.d.ts +149 -0
  3. package/esm/src/cli/machineSlots.d.ts.map +1 -0
  4. package/esm/src/cli/machineSlots.js +417 -0
  5. package/esm/src/cli/machineSlots.js.map +1 -0
  6. package/esm/src/cli/machineSlotsCommand.d.ts +24 -0
  7. package/esm/src/cli/machineSlotsCommand.d.ts.map +1 -0
  8. package/esm/src/cli/machineSlotsCommand.js +431 -0
  9. package/esm/src/cli/machineSlotsCommand.js.map +1 -0
  10. package/esm/src/cli/machineSlotsHost.d.ts +50 -0
  11. package/esm/src/cli/machineSlotsHost.d.ts.map +1 -0
  12. package/esm/src/cli/machineSlotsHost.js +192 -0
  13. package/esm/src/cli/machineSlotsHost.js.map +1 -0
  14. package/esm/src/cli/mod.d.ts.map +1 -1
  15. package/esm/src/cli/mod.js +39 -1
  16. package/esm/src/cli/mod.js.map +1 -1
  17. package/esm/src/cli/testResourceLaunch.d.ts +29 -1
  18. package/esm/src/cli/testResourceLaunch.d.ts.map +1 -1
  19. package/esm/src/cli/testResourceLaunch.js +49 -12
  20. package/esm/src/cli/testResourceLaunch.js.map +1 -1
  21. package/esm/src/geo/client.d.ts +74 -0
  22. package/esm/src/geo/client.d.ts.map +1 -0
  23. package/esm/src/geo/client.js +135 -0
  24. package/esm/src/geo/client.js.map +1 -0
  25. package/esm/src/geo/mod.d.ts +5 -0
  26. package/esm/src/geo/mod.d.ts.map +1 -0
  27. package/esm/src/geo/mod.js +5 -0
  28. package/esm/src/geo/mod.js.map +1 -0
  29. package/esm/src/geo/place.d.ts +28 -0
  30. package/esm/src/geo/place.d.ts.map +1 -0
  31. package/esm/src/geo/place.js +41 -0
  32. package/esm/src/geo/place.js.map +1 -0
  33. package/esm/src/geo/places.d.ts +16 -0
  34. package/esm/src/geo/places.d.ts.map +1 -0
  35. package/esm/src/geo/places.js +154 -0
  36. package/esm/src/geo/places.js.map +1 -0
  37. package/esm/src/geo/placesFormat.d.ts +49 -0
  38. package/esm/src/geo/placesFormat.d.ts.map +1 -0
  39. package/esm/src/geo/placesFormat.js +38 -0
  40. package/esm/src/geo/placesFormat.js.map +1 -0
  41. package/esm/src/geo/preference.d.ts +15 -0
  42. package/esm/src/geo/preference.d.ts.map +1 -0
  43. package/esm/src/geo/preference.js +21 -0
  44. package/esm/src/geo/preference.js.map +1 -0
  45. package/esm/src/geo/timeZone.d.ts +20 -0
  46. package/esm/src/geo/timeZone.d.ts.map +1 -0
  47. package/esm/src/geo/timeZone.js +65 -0
  48. package/esm/src/geo/timeZone.js.map +1 -0
  49. package/esm/src/geo/vercel.d.ts +15 -0
  50. package/esm/src/geo/vercel.d.ts.map +1 -0
  51. package/esm/src/geo/vercel.js +64 -0
  52. package/esm/src/geo/vercel.js.map +1 -0
  53. package/package.json +26 -2
  54. package/skills/loom/SKILL.md +43 -15
  55. package/skills/loom/references/verification-workflow.md +128 -0
  56. package/source/src/cli/machineSlots.ts +543 -0
  57. package/source/src/cli/machineSlotsCommand.ts +549 -0
  58. package/source/src/cli/machineSlotsHost.ts +215 -0
  59. package/source/src/cli/mod.ts +53 -1
  60. package/source/src/cli/testResourceLaunch.ts +71 -9
  61. package/source/src/geo/client.ts +241 -0
  62. package/source/src/geo/mod.ts +12 -0
  63. package/source/src/geo/place.ts +61 -0
  64. package/source/src/geo/places.ts +195 -0
  65. package/source/src/geo/placesFormat.ts +58 -0
  66. package/source/src/geo/preference.ts +24 -0
  67. package/source/src/geo/timeZone.ts +78 -0
  68. package/source/src/geo/vercel.ts +78 -0
@@ -0,0 +1,549 @@
1
+ /**
2
+ * `loom slots run|pin|status` (docs/machine-slots.md). `run` waits in line for
3
+ * a grant of CPUs from the machine-wide pool, then runs a command pinned to
4
+ * them; `pin` pins a light command to the pool, or to the grant it is in,
5
+ * without admission.
6
+ */
7
+ import process from "node:process";
8
+ import {
9
+ ancestorGrant,
10
+ dropTicket,
11
+ FlockSlotLocks,
12
+ holderAlive,
13
+ isHead,
14
+ liveWaiters,
15
+ newLease,
16
+ ownLabel,
17
+ readSlots,
18
+ resolveSlotRequest,
19
+ scanForGrant,
20
+ scanOrder,
21
+ SLOTS_SPEC,
22
+ SlotsInterrupted,
23
+ takeTicket,
24
+ verifyLease,
25
+ type SlotRequest,
26
+ type Ticket,
27
+ } from "./machineSlots.ts";
28
+ import {
29
+ readCoreTypes,
30
+ readProcessStat,
31
+ resolveSlotDirectory,
32
+ } from "./machineSlotsHost.ts";
33
+ import {
34
+ inspectTestResources,
35
+ type TestResourceReport,
36
+ } from "./testResourceHost.ts";
37
+ import { executable, launch } from "./testResourceLaunch.ts";
38
+
39
+ /** Agent-session markers; such a session is local even when `CI` is set. */
40
+ const AGENT_SESSION_ENV_NAMES = [
41
+ "CLAUDECODE",
42
+ "CLAUDE_CODE_ENTRYPOINT",
43
+ "AI_AGENT",
44
+ "CODEX_SANDBOX",
45
+ "CURSOR_AGENT",
46
+ "GEMINI_CLI",
47
+ ] as const;
48
+
49
+ const CI_ENV_NAMES = [
50
+ "CI",
51
+ "GITHUB_ACTIONS",
52
+ "GITLAB_CI",
53
+ "BUILDKITE",
54
+ "TF_BUILD",
55
+ ] as const;
56
+
57
+ /** Default deadline for waiting in line. */
58
+ const DEFAULT_WAIT_MINUTES = 60;
59
+ /** How long the wrapper waits for a finished job's process group. */
60
+ const GROUP_GRACE_MS = 30_000;
61
+ const POLL_MS = 250;
62
+ const REPORT_EVERY_MS = 30_000;
63
+
64
+ /** Options `loom slots` accepts. */
65
+ export interface SlotsOptions {
66
+ min?: string;
67
+ max?: string;
68
+ label?: string;
69
+ waitTimeout?: string;
70
+ allowUnpooled?: boolean;
71
+ quiet?: boolean;
72
+ json?: boolean;
73
+ }
74
+
75
+ type Io = { out: (line: string) => void; err: (line: string) => void };
76
+
77
+ /** Whether this is CI: a CI variable set, and no agent-session marker. */
78
+ export function slotsProfile(
79
+ env: Readonly<Record<string, string | undefined>>,
80
+ ): "local" | "ci" {
81
+ const set = (name: string) => {
82
+ const value = env[name]?.trim();
83
+ return Boolean(value && !/^(0|false)$/i.test(value));
84
+ };
85
+ if (AGENT_SESSION_ENV_NAMES.some(set)) return "local";
86
+ return CI_ENV_NAMES.some(set) ? "ci" : "local";
87
+ }
88
+
89
+ /** The label text a job shows other waiters: never its command line. */
90
+ export function jobLabel(
91
+ explicit: string | undefined,
92
+ env: Readonly<Record<string, string | undefined>>,
93
+ ): string {
94
+ if (explicit) return explicit.slice(0, 80);
95
+ const parts = [env.npm_package_name, env.npm_lifecycle_event].filter(Boolean);
96
+ return parts.length ? parts.join(" ").slice(0, 80) : "unlabelled";
97
+ }
98
+
99
+ /** Which flags each subcommand accepts; anything else is a usage error. */
100
+ export function slotsFlagProblem(
101
+ sub: string | undefined,
102
+ options: SlotsOptions,
103
+ ): string | null {
104
+ const given = (
105
+ [
106
+ ["--min", options.min !== undefined],
107
+ ["--max", options.max !== undefined],
108
+ ["--label", options.label !== undefined],
109
+ ["--wait-timeout", options.waitTimeout !== undefined],
110
+ ["--allow-unpooled", Boolean(options.allowUnpooled)],
111
+ ["--quiet", Boolean(options.quiet)],
112
+ ["--json", Boolean(options.json)],
113
+ ] as const
114
+ )
115
+ .filter(([, set]) => set)
116
+ .map(([name]) => name);
117
+ const allowed: Record<string, readonly string[]> = {
118
+ run: [
119
+ "--min",
120
+ "--max",
121
+ "--label",
122
+ "--wait-timeout",
123
+ "--allow-unpooled",
124
+ "--quiet",
125
+ ],
126
+ pin: ["--quiet"],
127
+ status: ["--json"],
128
+ };
129
+ const permitted = allowed[sub ?? ""];
130
+ if (!permitted) return null;
131
+ const stray = given.filter((flag) => !permitted.includes(flag));
132
+ return stray.length
133
+ ? `${stray.join(", ")} ${stray.length === 1 ? "does" : "do"} not apply to loom slots ${sub}`
134
+ : null;
135
+ }
136
+
137
+ /**
138
+ * The pool's CPUs (respecting inherited affinity), the machine's whole pool
139
+ * (for `status`), and the largest grant a known quota allows.
140
+ */
141
+ function poolOf(report: TestResourceReport) {
142
+ const reserved = report.cpu.exclusion?.reservedCpus ?? [];
143
+ const quota =
144
+ report.cpu.quota.status === "known"
145
+ ? Math.max(1, Math.ceil(report.cpu.quota.cpus))
146
+ : undefined;
147
+ return {
148
+ pool: report.cpu.exclusion?.testCpus ?? [],
149
+ machine: report.cpu.online.filter((cpu) => !reserved.includes(cpu)),
150
+ quota,
151
+ reserved,
152
+ };
153
+ }
154
+
155
+ /**
156
+ * Test seam: a fixed pool instead of the machine's, honoured only together
157
+ * with `LOOM_SLOTS_DIR` and only for online CPUs, so a stray variable can
158
+ * neither split the real pool nor reach the reserved cores.
159
+ */
160
+ function testPool(
161
+ env: Readonly<Record<string, string | undefined>>,
162
+ online: readonly number[],
163
+ ): number[] | null {
164
+ const text = env.LOOM_SLOTS_TEST_POOL;
165
+ if (!text || !env.LOOM_SLOTS_DIR) return null;
166
+ const cpus = text.split(",").map((part) => Number(part.trim()));
167
+ if (
168
+ cpus.length === 0 ||
169
+ cpus.some((cpu) => !Number.isSafeInteger(cpu) || !online.includes(cpu))
170
+ )
171
+ throw new Error("LOOM_SLOTS_TEST_POOL must list online CPUs");
172
+ return [...new Set(cpus)];
173
+ }
174
+
175
+ function describe(cpus: readonly number[]): string {
176
+ return [...cpus].sort((a, b) => a - b).join(",");
177
+ }
178
+
179
+ async function runDirect(
180
+ cwd: string,
181
+ command: string[],
182
+ env: NodeJS.ProcessEnv,
183
+ ): Promise<number> {
184
+ const result = await launch(command[0], command.slice(1), cwd, {
185
+ env,
186
+ name: "Loom slots",
187
+ holdInterrupts: true,
188
+ });
189
+ if (result.signal) process.kill(process.pid, result.signal);
190
+ return result.code;
191
+ }
192
+
193
+ /** Strips grant variables so an unpooled child does not claim one. */
194
+ function withoutGrant(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
195
+ const copy = { ...env };
196
+ delete copy.LOOM_SLOTS;
197
+ delete copy.LOOM_SLOT_CPUS;
198
+ delete copy.LOOM_SLOTS_LEASE;
199
+ return copy;
200
+ }
201
+
202
+ /** The variables a job inside a grant receives. */
203
+ function grantEnv(
204
+ env: NodeJS.ProcessEnv,
205
+ lease: string,
206
+ cpus: readonly number[],
207
+ ): NodeJS.ProcessEnv {
208
+ return {
209
+ ...env,
210
+ LOOM_SLOTS: String(cpus.length),
211
+ LOOM_SLOT_CPUS: describe(cpus),
212
+ LOOM_SLOTS_LEASE: lease,
213
+ };
214
+ }
215
+
216
+ /** Entry point for `loom slots <sub> [-- command]`. */
217
+ export async function runSlotsCommand(
218
+ cwd: string,
219
+ sub: string | undefined,
220
+ command: string[],
221
+ options: SlotsOptions,
222
+ io: Io,
223
+ ): Promise<number> {
224
+ const env = process.env;
225
+ const flagProblem = slotsFlagProblem(sub, options);
226
+ if (flagProblem) {
227
+ io.err(`Loom slots: ${flagProblem}; nothing ran.`);
228
+ return 120;
229
+ }
230
+ if (sub === "status") return await slotsStatus(options, io);
231
+ if ((sub !== "run" && sub !== "pin") || command.length === 0) {
232
+ io.err(
233
+ "Usage: loom slots run [--min n] [--max n] [--label text] [--wait-timeout minutes] [--allow-unpooled] [--quiet] -- <command> [args]\n loom slots pin [--quiet] -- <command> [args]\n loom slots status [--json]",
234
+ );
235
+ return 120;
236
+ }
237
+ const note = (line: string) => {
238
+ if (!options.quiet) io.err(`Loom slots: ${line}`);
239
+ };
240
+
241
+ if (slotsProfile(env) === "ci") {
242
+ note("CI profile; running without the machine pool.");
243
+ return await runDirect(cwd, command, withoutGrant(env));
244
+ }
245
+ if (process.platform !== "linux") {
246
+ note(
247
+ `no machine-wide pool on ${process.platform}; this run is uncoordinated.`,
248
+ );
249
+ return await runDirect(cwd, command, withoutGrant(env));
250
+ }
251
+
252
+ // Linux: the pool, or a refusal unless the operator allowed a bypass.
253
+ const unavailable = async (reason: string) => {
254
+ if (!options.allowUnpooled) {
255
+ io.err(
256
+ `Loom slots: the machine pool is unavailable (${reason}); nothing ran (exit 121). Pass --allow-unpooled to run uncoordinated.`,
257
+ );
258
+ return 121;
259
+ }
260
+ note(`${reason}; running uncoordinated (--allow-unpooled).`);
261
+ return await runDirect(cwd, command, withoutGrant(env));
262
+ };
263
+ const directory = resolveSlotDirectory(env);
264
+ if (directory.status !== "ready") return await unavailable(directory.reason);
265
+ let flock: string;
266
+ let taskset: string;
267
+ try {
268
+ flock = await executable("flock");
269
+ taskset = await executable("taskset");
270
+ } catch (error) {
271
+ return await unavailable(
272
+ error instanceof Error ? error.message : String(error),
273
+ );
274
+ }
275
+ // Optional: the job is sent SIGTERM if the wrapper itself dies.
276
+ const setpriv = await executable("setpriv").catch(() => null);
277
+ const report = await inspectTestResources({ profile: "local" });
278
+ const { pool: machinePool, quota } = poolOf(report);
279
+ let pool: number[];
280
+ try {
281
+ const test = testPool(env, report.cpu.online);
282
+ if (test) note(`test pool ${describe(test)} (LOOM_SLOTS_TEST_POOL).`);
283
+ pool = test ?? machinePool;
284
+ } catch (error) {
285
+ io.err(
286
+ `Loom slots: ${error instanceof Error ? error.message : String(error)}; nothing ran.`,
287
+ );
288
+ return 120;
289
+ }
290
+ if (pool.length === 0) return await unavailable("the pool has no CPUs");
291
+ const pinned = (cpus: readonly number[], args: readonly string[]) =>
292
+ setpriv
293
+ ? {
294
+ file: setpriv,
295
+ args: ["--pdeathsig", "TERM", taskset, "-c", describe(cpus), ...args],
296
+ }
297
+ : { file: taskset, args: ["-c", describe(cpus), ...args] };
298
+
299
+ // Already inside a grant: by its variables, or by an ancestor holding it.
300
+ const byVariables = verifyLease(
301
+ directory.path,
302
+ env,
303
+ report.cpu.inherited,
304
+ flock,
305
+ );
306
+ const grantInside = byVariables
307
+ ? { lease: env.LOOM_SLOTS_LEASE as string, cpus: byVariables }
308
+ : ancestorGrant(directory.path, pool, flock);
309
+
310
+ if (sub === "pin") {
311
+ const cpus = grantInside?.cpus ?? pool;
312
+ note(
313
+ grantInside
314
+ ? `pinned to this job's grant (${describe(cpus)}).`
315
+ : `pinned to the pool (${describe(cpus)}), no admission.`,
316
+ );
317
+ const { file, args } = pinned(cpus, command);
318
+ const result = await launch(file, args, cwd, {
319
+ env: grantInside
320
+ ? grantEnv(env, grantInside.lease, grantInside.cpus)
321
+ : withoutGrant(env),
322
+ name: "Loom slots",
323
+ holdInterrupts: true,
324
+ });
325
+ if (result.signal) process.kill(process.pid, result.signal);
326
+ return result.code;
327
+ }
328
+
329
+ // Inside a grant, reuse it: no acquisition, nothing to deadlock on.
330
+ if (grantInside) {
331
+ note(`reusing this job's grant of ${grantInside.cpus.length} CPUs.`);
332
+ return await runDirect(
333
+ cwd,
334
+ command,
335
+ grantEnv(env, grantInside.lease, grantInside.cpus),
336
+ );
337
+ }
338
+
339
+ let request: SlotRequest;
340
+ let waitMs: number;
341
+ try {
342
+ request = resolveSlotRequest(pool.length, options.min, options.max, {
343
+ quota,
344
+ });
345
+ const minutes =
346
+ options.waitTimeout === undefined
347
+ ? DEFAULT_WAIT_MINUTES
348
+ : Number(options.waitTimeout);
349
+ if (!Number.isFinite(minutes) || minutes <= 0)
350
+ throw new Error("--wait-timeout must be a positive number of minutes");
351
+ waitMs = minutes * 60_000;
352
+ } catch (error) {
353
+ io.err(
354
+ `Loom slots: ${error instanceof Error ? error.message : String(error)}`,
355
+ );
356
+ return 120;
357
+ }
358
+
359
+ const lease = newLease();
360
+ const text = jobLabel(options.label, env);
361
+ const locks = new FlockSlotLocks(directory.path, flock);
362
+ const order = scanOrder(pool, readCoreTypes());
363
+ let ticket: Ticket | null = null;
364
+ let interrupted: NodeJS.Signals | null = null;
365
+ const onSignal = (signal: NodeJS.Signals) => {
366
+ interrupted = signal;
367
+ };
368
+ const signals: NodeJS.Signals[] = ["SIGINT", "SIGTERM", "SIGHUP"];
369
+ for (const signal of signals) process.on(signal, onSignal);
370
+ const started = Date.now();
371
+ let grant: number[] | null = null;
372
+ try {
373
+ const ticketLabel = ownLabel("ticket", lease, text, request);
374
+ ticket = takeTicket(directory.path, ticketLabel, flock);
375
+ let reported = 0;
376
+ while (!interrupted) {
377
+ const waiters = liveWaiters(directory.path, ticket.name, flock);
378
+ if (!waiters.some((one) => one.name === ticket?.name)) {
379
+ // Our ticket vanished (removed by hand, or the directory recreated):
380
+ // take a new one rather than wait unseen until the deadline.
381
+ dropTicket(directory.path, ticket);
382
+ ticket = null;
383
+ ticket = takeTicket(directory.path, ticketLabel, flock);
384
+ continue;
385
+ }
386
+ if (isHead(waiters, ticket.name))
387
+ grant = await scanForGrant(order, request, locks);
388
+ if (grant || interrupted) break;
389
+ const waited = Date.now() - started;
390
+ if (waited >= waitMs) {
391
+ io.err(
392
+ `Loom slots: no grant of ${request.min} CPUs within ${Math.round(waitMs / 60_000)} min; nothing ran (exit 122).`,
393
+ );
394
+ return 122;
395
+ }
396
+ if (!options.quiet && waited >= reported) {
397
+ const held = readSlots(directory.path, pool, flock).filter(
398
+ (slot) => slot.state === "held",
399
+ );
400
+ const holders = new Map<string, number>();
401
+ for (const slot of held) {
402
+ const name = slot.label
403
+ ? `${slot.label.label} (pid ${slot.label.pid})`
404
+ : "unlabelled";
405
+ holders.set(name, (holders.get(name) ?? 0) + 1);
406
+ }
407
+ const ahead = waiters.findIndex((one) => one.name === ticket?.name);
408
+ io.err(
409
+ `Loom slots: waiting ${Math.round(waited / 1000)} s for ${request.min} of ${pool.length} CPUs` +
410
+ (ahead > 0 ? `, ${ahead} ahead in line` : "") +
411
+ (holders.size
412
+ ? `; held by ${[...holders].map(([name, count]) => `${name}: ${count}`).join(", ")}`
413
+ : "") +
414
+ ".",
415
+ );
416
+ reported = waited + REPORT_EVERY_MS;
417
+ }
418
+ await new Promise((resolve) => setTimeout(resolve, POLL_MS));
419
+ }
420
+ } catch (error) {
421
+ if (!(error instanceof SlotsInterrupted)) {
422
+ locks.releaseAll();
423
+ io.err(
424
+ `Loom slots: ${error instanceof Error ? error.message : String(error)} (exit 121).`,
425
+ );
426
+ return 121;
427
+ }
428
+ interrupted ??= "SIGINT";
429
+ } finally {
430
+ if (ticket) dropTicket(directory.path, ticket);
431
+ for (const signal of signals) process.off(signal, onSignal);
432
+ if (!grant || interrupted) locks.releaseAll();
433
+ }
434
+ if (!grant || interrupted) {
435
+ // Interrupted while waiting (or as the grant arrived): nothing runs.
436
+ process.kill(process.pid, interrupted ?? "SIGINT");
437
+ return 130;
438
+ }
439
+
440
+ locks.label(ownLabel("slot", lease, text, request));
441
+ note(
442
+ `${grant.length} CPU${grant.length === 1 ? "" : "s"} (${describe(grant)}) after ${Math.round((Date.now() - started) / 1000)} s.`,
443
+ );
444
+ try {
445
+ const { file, args } = pinned(grant, command);
446
+ const result = await launch(file, args, cwd, {
447
+ env: grantEnv(env, lease, grant),
448
+ groupGraceMs: GROUP_GRACE_MS,
449
+ name: "Loom slots",
450
+ holdInterrupts: true,
451
+ });
452
+ locks.releaseAll();
453
+ if (result.signal) process.kill(process.pid, result.signal);
454
+ return result.code;
455
+ } finally {
456
+ locks.releaseAll();
457
+ }
458
+ }
459
+
460
+ async function slotsStatus(options: SlotsOptions, io: Io): Promise<number> {
461
+ if (process.platform !== "linux") {
462
+ io.out(`No machine-wide slot pool on ${process.platform}.`);
463
+ return 0;
464
+ }
465
+ const directory = resolveSlotDirectory(process.env);
466
+ if (directory.status !== "ready") {
467
+ io.err(`Loom slots: the pool is unavailable: ${directory.reason}.`);
468
+ return 121;
469
+ }
470
+ let flock: string;
471
+ try {
472
+ flock = await executable("flock");
473
+ } catch {
474
+ io.err("Loom slots: flock(1) is unavailable.");
475
+ return 121;
476
+ }
477
+ const report = await inspectTestResources({ profile: "local" });
478
+ const { machine, reserved, quota } = poolOf(report);
479
+ let pool: number[];
480
+ try {
481
+ pool = testPool(process.env, report.cpu.online) ?? machine;
482
+ } catch (error) {
483
+ io.err(
484
+ `Loom slots: ${error instanceof Error ? error.message : String(error)}.`,
485
+ );
486
+ return 120;
487
+ }
488
+ const slots = readSlots(directory.path, pool, flock).map((slot) => ({
489
+ ...slot,
490
+ holder:
491
+ slot.state !== "held" || !slot.label
492
+ ? null
493
+ : !holderAlive(slot.label)
494
+ ? ("label stale" as const)
495
+ : /^[Tt]$/.test(readProcessStat(slot.label.pid)?.state ?? "")
496
+ ? ("stopped" as const)
497
+ : ("running" as const),
498
+ }));
499
+ const waiters = liveWaiters(directory.path, null, flock);
500
+ if (options.json) {
501
+ io.out(
502
+ JSON.stringify({
503
+ spec: SLOTS_SPEC,
504
+ directory: directory.path,
505
+ reserved,
506
+ pool,
507
+ quota: quota ?? null,
508
+ slots,
509
+ waiters,
510
+ }),
511
+ );
512
+ return 0;
513
+ }
514
+ const held = slots.filter((slot) => slot.state === "held");
515
+ io.out(
516
+ `${SLOTS_SPEC} in ${directory.path}: ${pool.length} CPUs (${describe(pool)}), reserved ${describe(reserved) || "none"}; ${held.length} held.`,
517
+ );
518
+ const byLease = new Map<
519
+ string,
520
+ { label: string; pid: number; cpus: number[]; since: string; note: string }
521
+ >();
522
+ for (const slot of held) {
523
+ const key = slot.label?.lease ?? `unlabelled-${slot.cpu}`;
524
+ const entry = byLease.get(key) ?? {
525
+ label: slot.label?.label ?? "unlabelled",
526
+ pid: slot.label?.pid ?? 0,
527
+ cpus: [],
528
+ since: slot.label?.startedAt ?? "",
529
+ note: slot.holder && slot.holder !== "running" ? ` [${slot.holder}]` : "",
530
+ };
531
+ entry.cpus.push(slot.cpu);
532
+ byLease.set(key, entry);
533
+ }
534
+ for (const entry of byLease.values())
535
+ io.out(
536
+ ` held: ${entry.label} (pid ${entry.pid}), ${entry.cpus.length} CPUs (${describe(entry.cpus)}), since ${entry.since}${entry.note}`,
537
+ );
538
+ const unknown = slots.filter((slot) => slot.state === "unknown");
539
+ if (unknown.length)
540
+ io.out(
541
+ ` unreadable: ${describe(unknown.map((slot) => slot.cpu))} (could not be probed)`,
542
+ );
543
+ waiters.forEach((waiter, index) =>
544
+ io.out(
545
+ ` waiting ${index + 1}: ${waiter.label?.label ?? "unlabelled"} (pid ${waiter.label?.pid ?? "?"}), wants ${waiter.label?.request ? `${waiter.label.request.min}–${waiter.label.request.max}` : "?"}, since ${waiter.label?.startedAt ?? "?"}${waiter.stopped ? " [stopped, skipped]" : ""}`,
546
+ ),
547
+ );
548
+ return 0;
549
+ }