@orkestrel/scaffold 0.0.133 → 0.0.134

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 (82) hide show
  1. package/dist/agents/skills/orkestrel-dispatch/scripts/bench.js +61 -96
  2. package/dist/agents/skills/orkestrel-dispatch/scripts/brief.js +48 -76
  3. package/dist/agents/skills/orkestrel-dispatch/scripts/chain.js +27 -66
  4. package/dist/agents/skills/orkestrel-dispatch/scripts/cite.js +31 -64
  5. package/dist/agents/skills/orkestrel-dispatch/scripts/launch.js +43 -57
  6. package/dist/agents/skills/orkestrel-dispatch/scripts/login.js +43 -86
  7. package/dist/agents/skills/orkestrel-dispatch/scripts/patch.js +68 -104
  8. package/dist/agents/skills/orkestrel-dispatch/scripts/result.js +35 -69
  9. package/dist/agents/skills/orkestrel-dispatch/scripts/sweep.js +47 -84
  10. package/dist/agents/skills/orkestrel-falsify/scripts/mutate.js +134 -116
  11. package/dist/agents/skills/orkestrel-harden/scripts/discovery.js +38 -90
  12. package/dist/agents/skills/orkestrel-harden/scripts/interleave.js +39 -103
  13. package/dist/agents/skills/orkestrel-harden/scripts/measure.js +40 -89
  14. package/dist/agents/skills/orkestrel-harden/scripts/titles.js +41 -87
  15. package/dist/agents/skills/orkestrel-parallel/scripts/cases.js +43 -88
  16. package/dist/agents/skills/orkestrel-parallel/scripts/lane.js +1018 -194
  17. package/dist/agents/skills/orkestrel-publish/scripts/compare.js +40 -60
  18. package/dist/agents/skills/orkestrel-publish/scripts/pins.js +47 -81
  19. package/dist/agents/skills/orkestrel-publish/scripts/steps.js +66 -104
  20. package/dist/agents/skills/orkestrel-publish/scripts/swap.js +74 -88
  21. package/dist/agents/skills/orkestrel-publish/scripts/wave.js +95 -108
  22. package/dist/agents/skills/orkestrel-publish/scripts/window.js +55 -96
  23. package/dist/agents/skills/orkestrel-scout/scripts/map.js +54 -101
  24. package/dist/bin/main.js +27 -3
  25. package/dist/bin/main.js.map +1 -1
  26. package/dist/host/agents/skills/orkestrel-dispatch/scripts/bench.ts +81 -97
  27. package/dist/host/agents/skills/orkestrel-dispatch/scripts/brief.ts +64 -72
  28. package/dist/host/agents/skills/orkestrel-dispatch/scripts/chain.ts +41 -63
  29. package/dist/host/agents/skills/orkestrel-dispatch/scripts/cite.ts +56 -79
  30. package/dist/host/agents/skills/orkestrel-dispatch/scripts/launch.ts +61 -74
  31. package/dist/host/agents/skills/orkestrel-dispatch/scripts/login.ts +59 -89
  32. package/dist/host/agents/skills/orkestrel-dispatch/scripts/patch.ts +87 -106
  33. package/dist/host/agents/skills/orkestrel-dispatch/scripts/result.ts +57 -76
  34. package/dist/host/agents/skills/orkestrel-dispatch/scripts/sweep.ts +73 -88
  35. package/dist/host/agents/skills/orkestrel-falsify/SKILL.md +2 -2
  36. package/dist/host/agents/skills/orkestrel-falsify/scripts/mutate.ts +167 -119
  37. package/dist/host/agents/skills/orkestrel-harden/references/methods.md +1 -1
  38. package/dist/host/agents/skills/orkestrel-harden/scripts/discovery.ts +58 -75
  39. package/dist/host/agents/skills/orkestrel-harden/scripts/interleave.ts +55 -99
  40. package/dist/host/agents/skills/orkestrel-harden/scripts/measure.ts +59 -90
  41. package/dist/host/agents/skills/orkestrel-harden/scripts/titles.ts +60 -80
  42. package/dist/host/agents/skills/orkestrel-parallel/SKILL.md +4 -4
  43. package/dist/host/agents/skills/orkestrel-parallel/scripts/cases.ts +71 -108
  44. package/dist/host/agents/skills/orkestrel-parallel/scripts/lane.ts +1288 -239
  45. package/dist/host/agents/skills/orkestrel-publish/references/wave.md +10 -6
  46. package/dist/host/agents/skills/orkestrel-publish/scripts/compare.ts +58 -79
  47. package/dist/host/agents/skills/orkestrel-publish/scripts/pins.ts +66 -87
  48. package/dist/host/agents/skills/orkestrel-publish/scripts/steps.ts +84 -102
  49. package/dist/host/agents/skills/orkestrel-publish/scripts/swap.ts +92 -99
  50. package/dist/host/agents/skills/orkestrel-publish/scripts/wave.ts +130 -126
  51. package/dist/host/agents/skills/orkestrel-publish/scripts/window.ts +82 -120
  52. package/dist/host/agents/skills/orkestrel-scout/SKILL.md +3 -3
  53. package/dist/host/agents/skills/orkestrel-scout/scripts/map.ts +85 -112
  54. package/dist/host/claude/agents/orkestrel.md +4 -4
  55. package/dist/host/claude/rules/documentation.md +1 -1
  56. package/dist/host/claude/rules/patterns.md +5 -4
  57. package/dist/host/claude/rules/styles.md +1 -1
  58. package/dist/host/claude/rules/tests.md +3 -3
  59. package/dist/host/claude/rules/workspace.md +47 -35
  60. package/dist/host/configs/helpers.ts +40 -15
  61. package/dist/host/dotfiles/oxlintrc.json +62 -0
  62. package/dist/host/guides/form.md +79 -4
  63. package/dist/host/guides/scaffold.md +93 -65
  64. package/dist/host/guides/table.md +20 -6
  65. package/dist/host/guides/test.md +9 -7
  66. package/dist/host/manifest.json +44 -44
  67. package/dist/host/tests/config.test.ts +201 -11
  68. package/dist/host/tests/policy.test.ts +14 -21
  69. package/dist/host/tests/setupPolicy.ts +43 -36
  70. package/dist/src/core/index.cjs +191 -93
  71. package/dist/src/core/index.cjs.map +1 -1
  72. package/dist/src/core/index.d.cts +27 -13
  73. package/dist/src/core/index.d.ts +27 -13
  74. package/dist/src/core/index.js +189 -93
  75. package/dist/src/core/index.js.map +1 -1
  76. package/dist/src/server/index.cjs +8 -9
  77. package/dist/src/server/index.cjs.map +1 -1
  78. package/dist/src/server/index.d.cts +1 -1
  79. package/dist/src/server/index.d.ts +1 -1
  80. package/dist/src/server/index.js +8 -9
  81. package/dist/src/server/index.js.map +1 -1
  82. package/package.json +2 -2
@@ -1,31 +1,56 @@
1
1
  import { spawn, spawnSync } from 'node:child_process';
2
- import { randomUUID } from 'node:crypto';
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { once } from 'node:events';
3
4
  import { existsSync, linkSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync, } from 'node:fs';
4
5
  import { connect, createServer } from 'node:net';
5
- import { hostname, userInfo } from 'node:os';
6
- import { dirname, extname, join } from 'node:path';
6
+ import { constants, hostname, setPriority, userInfo } from 'node:os';
7
+ import { basename, dirname, extname, isAbsolute, join } from 'node:path';
7
8
  import { createInterface } from 'node:readline';
8
9
  import { fileURLToPath } from 'node:url';
10
+ import { parseArgs } from 'node:util';
9
11
  /** Holds the protocol version a ticket carries, so a process refuses a ticket it cannot read. */
10
12
  export const PROTOCOL = 1;
11
- /** Lists the flags that take a value. */
12
- export const VALUE_FLAGS = [
13
- '--label',
14
- '--journal',
15
- '--errors',
16
- '--cap',
17
- '--root',
18
- ];
19
- /** Lists the flags only a run reads, which `--status` refuses. */
20
- export const RUN_FLAGS = ['--label', '--journal', '--errors', '--cap'];
21
- /** Lists every flag the script reads, value flags and switches alike. */
22
- export const FLAGS = [...VALUE_FLAGS, '--status', '--json'];
13
+ /** Lists the flags only a run reads, which `--status` refuses, by the name `parseArgs` reads them under. */
14
+ export const RUN_OPTIONS = ['label', 'journal', 'errors', 'cap', 'solo'];
23
15
  /** Holds the usage line printed on a usage refusal. */
24
- export const USAGE = 'usage: lane.ts --label NAME --journal PATH --errors PATH --cap SECONDS [--root DIR] -- COMMAND [ARGS...] | lane.ts --status [--root DIR] [--json]; the journal and the errors file differ, and the cap is a number of seconds above 0 up to 2147483';
16
+ export const USAGE = 'usage: lane.ts --label NAME --journal PATH --errors PATH --cap SECONDS [--root DIR] [--solo] -- COMMAND [ARGS...] | lane.ts --status [--root DIR] [--json]; the journal and the errors file differ, and the cap is a number of seconds above 0 up to 2147483';
17
+ /** Declares every flag the script reads, for `parseArgs`. */
18
+ export const OPTIONS = Object.freeze({
19
+ label: Object.freeze({ type: 'string' }),
20
+ journal: Object.freeze({ type: 'string' }),
21
+ errors: Object.freeze({ type: 'string' }),
22
+ cap: Object.freeze({ type: 'string' }),
23
+ root: Object.freeze({ type: 'string' }),
24
+ status: Object.freeze({ type: 'boolean' }),
25
+ json: Object.freeze({ type: 'boolean' }),
26
+ solo: Object.freeze({ type: 'boolean' }),
27
+ });
28
+ /**
29
+ * Parses the arguments in strict mode against `OPTIONS`.
30
+ *
31
+ * @param argv - The arguments after the script path.
32
+ * @returns The values and positionals, or the message `parseArgs` refused the arguments with.
33
+ */
34
+ export function parseArguments(argv) {
35
+ try {
36
+ const { values, positionals } = parseArgs({
37
+ args: [...argv],
38
+ options: OPTIONS,
39
+ strict: true,
40
+ allowPositionals: false,
41
+ });
42
+ return { success: true, value: { values, positionals } };
43
+ }
44
+ catch (error) {
45
+ return { success: false, error: error instanceof Error ? error.message : String(error) };
46
+ }
47
+ }
25
48
  /** Holds the longest cap in whole seconds, equal to the limit of the sibling launcher. */
26
49
  export const MAX_CAP_SECONDS = 2_147_483;
27
50
  /** Holds the digit count of a ticket name, which keeps a directory listing readable in order. */
28
51
  export const SEQUENCE_WIDTH = 12;
52
+ /** Holds the byte a light waiter writes to an earlier light ticket that does not hold yet. */
53
+ export const HOLD_BYTE = 'h';
29
54
  /** Holds the name ending of a stage file. */
30
55
  export const STAGE_SUFFIX = '.stage';
31
56
  /** Holds the name ending of a ticket. */
@@ -71,6 +96,103 @@ export const REMOVAL_RETRIES = 10;
71
96
  export const REMOVAL_DELAY_MS = 100;
72
97
  /** Holds the PowerShell text that prints one row per process with a creation date. */
73
98
  export const SNAPSHOT_COMMAND = "Get-CimInstance Win32_Process -Property ProcessId,ParentProcessId,CreationDate | Where-Object { $_.CreationDate } | ForEach-Object { '{0} {1} {2}' -f $_.ProcessId, $_.ParentProcessId, ([DateTimeOffset]$_.CreationDate).ToUnixTimeMilliseconds() }";
99
+ /** Holds the name of the file under the root that holds the light lanes' limits. */
100
+ export const LIMITS_FILE = 'limits.json';
101
+ /** Holds the name of the directory under the root that holds each command's run records. */
102
+ export const HISTORY_DIRECTORY = 'history';
103
+ /** Holds the name ending of a run record under the history directory. */
104
+ export const OUTCOME_SUFFIX = '.json';
105
+ /** Holds the digit count of the end time that opens a record's name, which keeps a listing in time order. */
106
+ export const ENDED_WIDTH = 15;
107
+ /** Holds the count of latest records the light reading takes, which is also the count each key keeps. */
108
+ export const RECENT_RUNS = 3;
109
+ /** Holds the pause in milliseconds between two samples of a holder's tree. */
110
+ export const SAMPLE_MS = 1000;
111
+ /** Holds the exit code of a light run its holder ended at a threshold. */
112
+ export const BREACH_CODE = 69;
113
+ /** Holds the exit code of a run whose tree still reads as present at handover. */
114
+ export const HELD_CODE = 70;
115
+ /** Holds the launcher's exit code at the cap. */
116
+ export const CAPPED_CODE = 124;
117
+ /** Lists the words that seed a command heavy: a journey, a study, a capture, a live-service run, and a release chain. */
118
+ export const HEAVY_WORDS = [
119
+ 'journey',
120
+ 'journeys',
121
+ 'study',
122
+ 'studies',
123
+ 'capture',
124
+ 'captures',
125
+ 'live',
126
+ 'prepublishonly',
127
+ ];
128
+ /** Lists the package-manager verbs that seed a command heavy: an install, a full suite, and a publish. */
129
+ export const HEAVY_VERBS = [
130
+ 'ci',
131
+ 'i',
132
+ 'install',
133
+ 'add',
134
+ 'update',
135
+ 'rebuild',
136
+ 'uninstall',
137
+ 'publish',
138
+ 'test',
139
+ 't',
140
+ ];
141
+ /**
142
+ * Lists the package scripts a seed reads heavy: the full suite, the aggregates that build and run
143
+ * several projects, the pack-and-install suite, the live-service suite, and the benchmark run.
144
+ */
145
+ export const HEAVY_SCRIPTS = [
146
+ 'test',
147
+ 'test:src',
148
+ 'test:app',
149
+ 'test:distribution',
150
+ 'test:service',
151
+ 'test:bench',
152
+ ];
153
+ /** Lists the Vitest projects a seed reads heavy: the pack-and-install project and the live-service project. */
154
+ export const HEAVY_PROJECTS = ['distribution', 'service'];
155
+ /** Matches a browser face's Vitest project, whose whole run a seed reads heavy: `src:browser`, `app:vue`. */
156
+ export const BROWSER_PROJECT = /(?:^|:)(?:browser|vue)$/u;
157
+ /** Matches a dotted flag such as `--outputFile.json`, whose separate value a seed skips. */
158
+ export const DOTTED_FLAG = /^--[^=.]+\.[^=]+$/u;
159
+ /** Lists the package managers whose verbs and scripts a seed reads. */
160
+ export const MANAGERS = ['npm', 'pnpm', 'yarn', 'bun'];
161
+ /** Lists the tools a seed reads heavy by name: the release chain's step runner. */
162
+ export const HEAVY_TOOLS = ['steps'];
163
+ /** Lists the Vitest flags that take a separate value, so a seed reads no flag value as a file. */
164
+ export const VITEST_VALUE_FLAGS = [
165
+ '--config',
166
+ '-c',
167
+ '--project',
168
+ '--reporter',
169
+ '--mode',
170
+ '--root',
171
+ '-r',
172
+ '--dir',
173
+ '--outputFile',
174
+ '--pool',
175
+ '--environment',
176
+ '--shard',
177
+ '--testNamePattern',
178
+ '-t',
179
+ '--bail',
180
+ '--retry',
181
+ '--maxWorkers',
182
+ '--minWorkers',
183
+ '--testTimeout',
184
+ '--hookTimeout',
185
+ '--exclude',
186
+ '--include',
187
+ ];
188
+ /** Matches a package script that runs a type check: `check`, `typecheck`, `check:<scope>`, or `<tool>:check`. */
189
+ export const CHECK_SCRIPT = /^(?:check|typecheck|type-check)(?::|$)|:check$/u;
190
+ /** Matches a package script that runs one project's suite. */
191
+ export const SCOPED_SCRIPT = /^test:/u;
192
+ /** Matches one sampler row: process id, parent id, creation time in milliseconds, CPU time in 100 ns units, and private bytes. */
193
+ export const GAUGE_PATTERN = /^(\d+) (\d+) (\d+) (\d+) (\d+)$/u;
194
+ /** Holds the PowerShell text that prints one line of rows per sample until its stdin closes. */
195
+ export const SAMPLER_COMMAND = `$i=[Console]::OpenStandardInput();$b=New-Object byte[] 1;$t=$i.ReadAsync($b,0,1);while(-not $t.IsCompleted){$r=Get-CimInstance Win32_Process -Property ProcessId,ParentProcessId,CreationDate,KernelModeTime,UserModeTime,PrivatePageCount | Where-Object { $_.CreationDate } | ForEach-Object { '{0} {1} {2} {3} {4}' -f $_.ProcessId,$_.ParentProcessId,([DateTimeOffset]$_.CreationDate).ToUnixTimeMilliseconds(),($_.KernelModeTime+$_.UserModeTime),$_.PrivatePageCount };[Console]::Out.WriteLine($r -join ';');[Console]::Out.Flush();Start-Sleep -Milliseconds ${String(SAMPLE_MS)}}`;
74
196
  /**
75
197
  * Holds a process's endpoint, whose existence is the process's liveness.
76
198
  *
@@ -81,8 +203,10 @@ export const SNAPSHOT_COMMAND = "Get-CimInstance Win32_Process -Property Process
81
203
  */
82
204
  export class Token {
83
205
  #sockets = new Set();
206
+ #waiters = new Set();
84
207
  #server;
85
208
  #published = false;
209
+ #holding = false;
86
210
  constructor() {
87
211
  this.#server = createServer((socket) => this.#admit(socket));
88
212
  }
@@ -93,14 +217,9 @@ export class Token {
93
217
  * @returns A promise that resolves when the endpoint accepts connections, and rejects with the
94
218
  * listen failure.
95
219
  */
96
- listen(endpoint) {
97
- return new Promise((resolve, reject) => {
98
- this.#server.once('error', reject);
99
- this.#server.listen(endpoint, () => {
100
- this.#server.removeListener('error', reject);
101
- resolve();
102
- });
103
- });
220
+ async listen(endpoint) {
221
+ this.#server.listen(endpoint);
222
+ await once(this.#server, 'listening');
104
223
  }
105
224
  /** Marks the stage as ended and closes every accepted connection, which wakes each waiter. */
106
225
  publish() {
@@ -108,81 +227,49 @@ export class Token {
108
227
  for (const socket of this.#sockets)
109
228
  socket.destroy();
110
229
  }
230
+ /** Marks the process as a holder and closes every connection that waits for it to hold. */
231
+ hold() {
232
+ this.#holding = true;
233
+ for (const socket of this.#waiters)
234
+ socket.destroy();
235
+ }
236
+ /** Marks the process as leaving, so a hold waiter that arrives later parks until the process ends. */
237
+ leave() {
238
+ this.#holding = false;
239
+ }
111
240
  /**
112
241
  * Closes the endpoint and every connection.
113
242
  *
114
243
  * @returns A promise that resolves when the server has closed.
115
244
  */
116
- destroy() {
245
+ async destroy() {
117
246
  for (const socket of this.#sockets)
118
247
  socket.destroy();
119
- return new Promise((resolve) => {
120
- this.#server.close(() => resolve());
121
- });
248
+ this.#server.close();
249
+ await once(this.#server, 'close');
122
250
  }
123
- // A byte after the publish comes from a stage waiter whose connection the allocation left unaccepted.
251
+ // Another byte after the publish comes from a stage waiter whose connection the allocation left unaccepted.
124
252
  #admit(socket) {
125
253
  this.#sockets.add(socket);
126
254
  socket.on('error', () => undefined);
127
- socket.on('close', () => this.#sockets.delete(socket));
128
- socket.on('data', () => {
129
- if (this.#published)
255
+ socket.on('close', () => {
256
+ this.#sockets.delete(socket);
257
+ this.#waiters.delete(socket);
258
+ });
259
+ socket.on('data', (data) => {
260
+ if (!data.includes(HOLD_BYTE)) {
261
+ if (this.#published)
262
+ socket.destroy();
263
+ }
264
+ else if (this.#holding) {
130
265
  socket.destroy();
266
+ }
267
+ else {
268
+ this.#waiters.add(socket);
269
+ }
131
270
  });
132
271
  }
133
272
  }
134
- /**
135
- * Reads the value that follows a flag.
136
- *
137
- * @remarks
138
- * The first occurrence of a flag wins, a following value that opens with `--` is a missing value,
139
- * and the `--flag=value` form is not read.
140
- *
141
- * @param argv - The arguments before the bare `--`.
142
- * @param name - The flag, such as `--label`.
143
- * @returns The value after the flag, or undefined when the flag is absent, last, or followed by
144
- * another flag.
145
- */
146
- export function readOption(argv, name) {
147
- const index = argv.indexOf(name);
148
- const value = index === -1 ? undefined : argv[index + 1];
149
- return value === undefined || value.startsWith('--') ? undefined : value;
150
- }
151
- /**
152
- * Names the value flags a caller gave with no value.
153
- *
154
- * @param argv - The arguments before the bare `--`.
155
- * @param names - The flags that take a value.
156
- * @returns Each named flag that appears last or is followed by another flag, in argument order.
157
- */
158
- export function readMissingFlags(argv, names) {
159
- return names.filter((name) => argv.includes(name) && readOption(argv, name) === undefined);
160
- }
161
- /**
162
- * Names the flags a caller gave that the script does not read.
163
- *
164
- * @remarks
165
- * A `--flag=value` argument is unknown, because the script reads no such form. A bare `--` ends the
166
- * scan, so the command after it keeps every argument.
167
- *
168
- * @param argv - The arguments after the script path.
169
- * @param flags - Every flag the script reads, value flags and switches alike.
170
- * @returns Each argument that opens with `--` and is not a read flag, in argument order.
171
- */
172
- export function readUnknownFlags(argv, flags) {
173
- const end = argv.indexOf('--');
174
- return (end === -1 ? argv : argv.slice(0, end)).filter((argument) => argument.startsWith('--') && !flags.includes(argument));
175
- }
176
- /**
177
- * Reads the arguments that are neither a flag nor the value of a value flag.
178
- *
179
- * @param argv - The arguments before the bare `--`.
180
- * @param valueFlags - The flags that take a value.
181
- * @returns The positional arguments in order.
182
- */
183
- export function readPositionals(argv, valueFlags) {
184
- return argv.filter((argument, index) => !argument.startsWith('--') && !valueFlags.includes(argv[index - 1] ?? ''));
185
- }
186
273
  /**
187
274
  * Quotes an untrusted text for a diagnostic, JSON-encoded and cut to a bounded length.
188
275
  *
@@ -243,22 +330,14 @@ export function renderEndpoint(root, token) {
243
330
  : join(root, `${token}${SOCKET_SUFFIX}`);
244
331
  }
245
332
  /**
246
- * Renders the name of a ticket.
333
+ * Renders the name of a ticket or a run record.
247
334
  *
248
335
  * @param sequence - The ticket's sequence.
336
+ * @param suffix - The name ending: `TICKET_SUFFIX` for a ticket, `RUN_SUFFIX` for its run record.
249
337
  * @returns The file name, at a fixed width.
250
338
  */
251
- export function renderTicketName(sequence) {
252
- return `${String(sequence).padStart(SEQUENCE_WIDTH, '0')}${TICKET_SUFFIX}`;
253
- }
254
- /**
255
- * Renders the name of a run record.
256
- *
257
- * @param sequence - The ticket's sequence.
258
- * @returns The file name, at a fixed width.
259
- */
260
- export function renderRunName(sequence) {
261
- return `${String(sequence).padStart(SEQUENCE_WIDTH, '0')}${RUN_SUFFIX}`;
339
+ export function renderName(sequence, suffix) {
340
+ return `${String(sequence).padStart(SEQUENCE_WIDTH, '0')}${suffix}`;
262
341
  }
263
342
  /**
264
343
  * Lists a directory's names.
@@ -292,7 +371,8 @@ export function readSequences(names) {
292
371
  * Checks whether a value is a ticket record.
293
372
  *
294
373
  * @param value - The parsed JSON value.
295
- * @returns True when every field has its type and the token has the token's form; false otherwise.
374
+ * @returns True when every field has its type, each present optional field too, and the token has
375
+ * the token's form; false otherwise.
296
376
  */
297
377
  export function isTicket(value) {
298
378
  return (typeof value === 'object' &&
@@ -313,7 +393,77 @@ export function isTicket(value) {
313
393
  'cwd' in value &&
314
394
  typeof value.cwd === 'string' &&
315
395
  'arrived' in value &&
316
- typeof value.arrived === 'string');
396
+ typeof value.arrived === 'string' &&
397
+ (!('light' in value) || isUsage(value.light)) &&
398
+ (!('solo' in value) || typeof value.solo === 'boolean'));
399
+ }
400
+ /**
401
+ * Checks whether a value is a footprint.
402
+ *
403
+ * @param value - The parsed JSON value.
404
+ * @returns True when `cores`, `memory`, and `processes` are finite numbers of at least 0; false
405
+ * otherwise.
406
+ */
407
+ export function isUsage(value) {
408
+ return (typeof value === 'object' &&
409
+ value !== null &&
410
+ 'cores' in value &&
411
+ isAmount(value.cores) &&
412
+ 'memory' in value &&
413
+ isAmount(value.memory) &&
414
+ 'processes' in value &&
415
+ isAmount(value.processes));
416
+ }
417
+ /**
418
+ * Checks whether a value is a finite number of at least 0.
419
+ *
420
+ * @param value - The value.
421
+ * @returns True for a finite number of at least 0; false otherwise.
422
+ */
423
+ export function isAmount(value) {
424
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0;
425
+ }
426
+ /**
427
+ * Checks whether a value is the content of `limits.json`.
428
+ *
429
+ * @param value - The parsed JSON value.
430
+ * @returns True when `slots` is an integer of at least 1, `budget` is a footprint, and `threshold` is
431
+ * a footprint with a `duration`; false otherwise.
432
+ */
433
+ export function isLimits(value) {
434
+ return (typeof value === 'object' &&
435
+ value !== null &&
436
+ 'slots' in value &&
437
+ Number.isSafeInteger(value.slots) &&
438
+ typeof value.slots === 'number' &&
439
+ value.slots >= 1 &&
440
+ 'budget' in value &&
441
+ isUsage(value.budget) &&
442
+ 'threshold' in value &&
443
+ isUsage(value.threshold) &&
444
+ 'duration' in value.threshold &&
445
+ isAmount(value.threshold.duration));
446
+ }
447
+ /**
448
+ * Checks whether a value is a run's record.
449
+ *
450
+ * @param value - The parsed JSON value.
451
+ * @returns True when the measures are finite numbers of at least 0 and `code` is an integer; false
452
+ * otherwise.
453
+ */
454
+ export function isOutcome(value) {
455
+ return (typeof value === 'object' &&
456
+ value !== null &&
457
+ 'duration' in value &&
458
+ isAmount(value.duration) &&
459
+ 'cpu' in value &&
460
+ isAmount(value.cpu) &&
461
+ 'memory' in value &&
462
+ isAmount(value.memory) &&
463
+ 'processes' in value &&
464
+ isAmount(value.processes) &&
465
+ 'code' in value &&
466
+ Number.isSafeInteger(value.code));
317
467
  }
318
468
  /**
319
469
  * Checks whether a value is a run record.
@@ -354,7 +504,7 @@ export function parseText(text) {
354
504
  */
355
505
  export function readEntry(root, sequence) {
356
506
  try {
357
- const parsed = parseText(readFileSync(join(root, renderTicketName(sequence)), 'utf8'));
507
+ const parsed = parseText(readFileSync(join(root, renderName(sequence, TICKET_SUFFIX)), 'utf8'));
358
508
  return [{ sequence, ticket: isTicket(parsed) ? parsed : undefined }];
359
509
  }
360
510
  catch (error) {
@@ -388,7 +538,7 @@ export function readQueue(root) {
388
538
  */
389
539
  export function readRun(root, sequence) {
390
540
  try {
391
- const parsed = parseText(readFileSync(join(root, renderRunName(sequence)), 'utf8'));
541
+ const parsed = parseText(readFileSync(join(root, renderName(sequence, RUN_SUFFIX)), 'utf8'));
392
542
  return isRun(parsed)
393
543
  ? {
394
544
  started: parsed.started,
@@ -409,7 +559,7 @@ export function readRun(root, sequence) {
409
559
  * @param run - The record.
410
560
  */
411
561
  export function writeRun(root, sequence, run) {
412
- writeFileSync(join(root, renderRunName(sequence)), JSON.stringify(run));
562
+ writeFileSync(join(root, renderName(sequence, RUN_SUFFIX)), JSON.stringify(run));
413
563
  }
414
564
  /**
415
565
  * Removes a file inside the removal budget.
@@ -424,9 +574,12 @@ export function removeFile(path) {
424
574
  *
425
575
  * @param token - The process's token.
426
576
  * @param label - The run's label.
427
- * @returns The complete ticket.
577
+ * @param light - The footprint a light ticket counts, or undefined for a heavy ticket.
578
+ * @param solo - If `true`, marks a ticket that waits out every earlier light ticket; if `false`, omits
579
+ * the field.
580
+ * @returns The complete ticket, carrying `light` and `solo` only when they are set.
428
581
  */
429
- export function buildTicket(token, label) {
582
+ export function buildTicket(token, label, light, solo = false) {
430
583
  return {
431
584
  protocol: PROTOCOL,
432
585
  token,
@@ -436,8 +589,323 @@ export function buildTicket(token, label) {
436
589
  platform: process.platform,
437
590
  cwd: process.cwd(),
438
591
  arrived: new Date().toISOString(),
592
+ ...(light === undefined ? {} : { light }),
593
+ ...(solo ? { solo } : {}),
439
594
  };
440
595
  }
596
+ /**
597
+ * Reads `limits.json` under the root.
598
+ *
599
+ * @param root - The queue root.
600
+ * @returns The limits; `absent` when the file does not exist; `unread` when it cannot be read as
601
+ * limits.
602
+ */
603
+ export function readLimits(root) {
604
+ try {
605
+ const parsed = parseText(readFileSync(join(root, LIMITS_FILE), 'utf8'));
606
+ return isLimits(parsed) ? parsed : 'unread';
607
+ }
608
+ catch (error) {
609
+ return readCode(error) === 'ENOENT' ? 'absent' : 'unread';
610
+ }
611
+ }
612
+ /**
613
+ * Renders the key of a command's run records.
614
+ *
615
+ * @param cwd - The real working directory.
616
+ * @param command - The command and its arguments.
617
+ * @returns The hex sha256 of the directory and the arguments.
618
+ */
619
+ export function renderKey(cwd, command) {
620
+ return createHash('sha256')
621
+ .update(JSON.stringify([cwd, ...command]))
622
+ .digest('hex');
623
+ }
624
+ /**
625
+ * Renders the name of a run's record.
626
+ *
627
+ * @param ended - When the run ended, in epoch milliseconds.
628
+ * @param token - The run's token, which keeps two records of one key and one millisecond apart.
629
+ * @returns The file name, opening with the end time at a fixed width.
630
+ */
631
+ export function renderOutcomeName(ended, token) {
632
+ return `${String(ended).padStart(ENDED_WIDTH, '0')}-${token}${OUTCOME_SUFFIX}`;
633
+ }
634
+ /**
635
+ * Reads the names of a key's records, oldest first.
636
+ *
637
+ * @param root - The queue root.
638
+ * @param key - The command's key.
639
+ * @returns Every record name under the key, sorted by end time.
640
+ */
641
+ export function readOutcomeNames(root, key) {
642
+ return readNames(join(root, HISTORY_DIRECTORY, key))
643
+ .filter((name) => name.endsWith(OUTCOME_SUFFIX))
644
+ .toSorted();
645
+ }
646
+ /**
647
+ * Reads a key's latest records.
648
+ *
649
+ * @param root - The queue root.
650
+ * @param key - The command's key.
651
+ * @returns Up to {@link RECENT_RUNS} records, oldest first, each undefined when it cannot be read as
652
+ * a record; a record removed while it is read is skipped.
653
+ */
654
+ export function readOutcomes(root, key) {
655
+ return readOutcomeNames(root, key)
656
+ .slice(-RECENT_RUNS)
657
+ .flatMap((name) => {
658
+ try {
659
+ const parsed = parseText(readFileSync(join(root, HISTORY_DIRECTORY, key, name), 'utf8'));
660
+ return [isOutcome(parsed) ? parsed : undefined];
661
+ }
662
+ catch (error) {
663
+ return readCode(error) === 'ENOENT' ? [] : [undefined];
664
+ }
665
+ });
666
+ }
667
+ /**
668
+ * Writes a run's record once and prunes its key to the latest {@link RECENT_RUNS} records.
669
+ *
670
+ * @param root - The queue root.
671
+ * @param key - The command's key.
672
+ * @param name - The record's name.
673
+ * @param outcome - The record.
674
+ */
675
+ export function writeOutcome(root, key, name, outcome) {
676
+ const directory = join(root, HISTORY_DIRECTORY, key);
677
+ mkdirSync(directory, { recursive: true });
678
+ writeFileSync(join(directory, name), JSON.stringify(outcome), { flag: 'wx' });
679
+ for (const stale of readOutcomeNames(root, key).slice(0, -RECENT_RUNS)) {
680
+ removeFile(join(directory, stale));
681
+ }
682
+ }
683
+ /**
684
+ * Reads the average cores a run used.
685
+ *
686
+ * @param outcome - The run's record.
687
+ * @returns The CPU time over the duration; 0 for a run of no duration.
688
+ */
689
+ export function readCores(outcome) {
690
+ return outcome.duration > 0 ? outcome.cpu / outcome.duration : 0;
691
+ }
692
+ /**
693
+ * Checks whether a run's record breaches the per-run threshold.
694
+ *
695
+ * @param outcome - The run's record, or undefined when it cannot be read.
696
+ * @param threshold - The per-run threshold.
697
+ * @returns True for an unreadable record, a capped run, an exit of 69 or 70, and a measure past the
698
+ * threshold; false otherwise.
699
+ */
700
+ export function isBreach(outcome, threshold) {
701
+ return (outcome === undefined ||
702
+ outcome.code === CAPPED_CODE ||
703
+ outcome.code === HELD_CODE ||
704
+ outcome.code === BREACH_CODE ||
705
+ outcome.duration > threshold.duration ||
706
+ readCores(outcome) > threshold.cores ||
707
+ outcome.memory > threshold.memory ||
708
+ outcome.processes > threshold.processes);
709
+ }
710
+ /**
711
+ * Reads the footprint a light ticket counts from its command's records.
712
+ *
713
+ * @param outcomes - The records, none of which breaches.
714
+ * @returns The largest cores, memory, and process count across the records.
715
+ */
716
+ export function measurePeak(outcomes) {
717
+ return {
718
+ cores: Math.max(0, ...outcomes.map(readCores)),
719
+ memory: Math.max(0, ...outcomes.map((outcome) => outcome.memory)),
720
+ processes: Math.max(0, ...outcomes.map((outcome) => outcome.processes)),
721
+ };
722
+ }
723
+ /**
724
+ * Reads whether a command runs light, from its seed and its latest records.
725
+ *
726
+ * @remarks
727
+ * A seeded heavy command is heavy whatever its records hold. A seeded light command is light until a
728
+ * record breaches, and counts the threshold until {@link RECENT_RUNS} records exist. Any other
729
+ * command is light only when {@link RECENT_RUNS} records exist and none breaches.
730
+ *
731
+ * @param seed - The lane the command's kind seeds, or undefined when no kind names it.
732
+ * @param outcomes - The command's latest records.
733
+ * @param limits - The limits.
734
+ * @returns The footprint the ticket counts, or undefined when the command runs heavy.
735
+ */
736
+ export function classifyLight(seed, outcomes, limits) {
737
+ if (seed === 'heavy')
738
+ return undefined;
739
+ const clean = outcomes.flatMap((outcome) => outcome === undefined || isBreach(outcome, limits.threshold) ? [] : [outcome]);
740
+ if (clean.length < outcomes.length)
741
+ return undefined;
742
+ if (clean.length >= RECENT_RUNS)
743
+ return measurePeak(clean);
744
+ const { cores, memory, processes } = limits.threshold;
745
+ return seed === 'light' ? { cores, memory, processes } : undefined;
746
+ }
747
+ /**
748
+ * Checks whether light footprints fit the slots and every budget together.
749
+ *
750
+ * @param usages - The footprints of the light holders and the arrival.
751
+ * @param limits - The limits.
752
+ * @returns True when the count fits `slots` and each summed measure fits its budget; false otherwise.
753
+ */
754
+ export function fitsBudget(usages, limits) {
755
+ const total = usages.reduce((sum, usage) => ({
756
+ cores: sum.cores + usage.cores,
757
+ memory: sum.memory + usage.memory,
758
+ processes: sum.processes + usage.processes,
759
+ }), { cores: 0, memory: 0, processes: 0 });
760
+ return (usages.length <= limits.slots &&
761
+ total.cores <= limits.budget.cores &&
762
+ total.memory <= limits.budget.memory &&
763
+ total.processes <= limits.budget.processes);
764
+ }
765
+ /**
766
+ * Splits a command into the words a seed reads.
767
+ *
768
+ * @remarks
769
+ * An absolute path contributes its base name alone, so a checkout's location never seeds a command.
770
+ *
771
+ * @param args - The arguments after the executable.
772
+ * @returns The lowercase alphanumeric words.
773
+ */
774
+ export function readWords(args) {
775
+ return args.flatMap((argument) => (isAbsolute(argument) ? basename(argument) : argument)
776
+ .toLowerCase()
777
+ .split(/[^a-z0-9]+/u)
778
+ .filter((word) => word !== ''));
779
+ }
780
+ /**
781
+ * Reads a tool's name from an executable or script path.
782
+ *
783
+ * @param path - The path.
784
+ * @returns The lowercase base name without its extension, `npm-cli` and `npx-cli` read as `npm` and
785
+ * `npx`.
786
+ */
787
+ export function readToolName(path) {
788
+ const name = basename(path.replaceAll('\\', '/'))
789
+ .toLowerCase()
790
+ .replace(/\.(?:exe|cmd|bat|ps1|js|mjs|cjs|ts|mts|cts)$/u, '');
791
+ return name.replace(/-cli$/u, '');
792
+ }
793
+ /**
794
+ * Reads the tool a command runs and the tool's arguments, past Node and `npx`.
795
+ *
796
+ * @param command - The command and its arguments.
797
+ * @returns The tool's name followed by its arguments; empty for inline Node code or no script.
798
+ */
799
+ export function readTool(command) {
800
+ const [executable, ...rest] = command;
801
+ if (executable === undefined)
802
+ return [];
803
+ const name = readToolName(executable);
804
+ if (name === 'node') {
805
+ const script = rest.findIndex((argument) => !argument.startsWith('-'));
806
+ const flags = script === -1 ? rest : rest.slice(0, script);
807
+ if (script === -1 || flags.some((flag) => ['-e', '--eval', '-p', '--print'].includes(flag))) {
808
+ return [];
809
+ }
810
+ return readTool(rest.slice(script));
811
+ }
812
+ if (name === 'npx') {
813
+ const tool = rest.findIndex((argument) => !argument.startsWith('-'));
814
+ return tool === -1 ? [] : readTool(rest.slice(tool));
815
+ }
816
+ return [name, ...rest];
817
+ }
818
+ /**
819
+ * Reads the positional arguments of a command, skipping each value of a value-taking flag.
820
+ *
821
+ * @param args - The arguments.
822
+ * @param valueFlags - The flags that take a separate value.
823
+ * @returns The arguments that are neither a flag nor the value of a listed or dotted flag.
824
+ */
825
+ export function readOperands(args, valueFlags) {
826
+ return args.filter((argument, index) => !argument.startsWith('-') &&
827
+ !valueFlags.includes(args[index - 1] ?? '') &&
828
+ !DOTTED_FLAG.test(args[index - 1] ?? ''));
829
+ }
830
+ /**
831
+ * Reads the lane a package script's name seeds.
832
+ *
833
+ * @param name - The script's name.
834
+ * @returns `heavy` for a script {@link HEAVY_SCRIPTS} names, `light` for a type, format, or lint
835
+ * check and any other `test:` suite, and undefined for any other script.
836
+ */
837
+ export function readScriptSeed(name) {
838
+ if (HEAVY_SCRIPTS.includes(name))
839
+ return 'heavy';
840
+ return CHECK_SCRIPT.test(name) || SCOPED_SCRIPT.test(name) ? 'light' : undefined;
841
+ }
842
+ /**
843
+ * Reads the lane a Vitest command seeds.
844
+ *
845
+ * @param args - The arguments after `vitest`.
846
+ * @returns `heavy` for a run of every project, of several projects, of a project
847
+ * {@link HEAVY_PROJECTS} names, or of a whole browser project; `light` for a run of named test files
848
+ * or one other project; undefined for any other run or mode.
849
+ */
850
+ export function readVitestSeed(args) {
851
+ const [mode, ...operands] = readOperands(args, VITEST_VALUE_FLAGS);
852
+ if (mode !== 'run')
853
+ return undefined;
854
+ const projects = args.flatMap((argument, index) => {
855
+ if (argument.startsWith('--project='))
856
+ return [argument.slice('--project='.length)];
857
+ return args[index - 1] === '--project' ? [argument] : [];
858
+ });
859
+ if (projects.length > 1 ||
860
+ projects.some((project) => project.includes('*') || HEAVY_PROJECTS.includes(project))) {
861
+ return 'heavy';
862
+ }
863
+ const files = operands.filter((operand) => /\.(?:test|spec)\./u.test(operand));
864
+ if (files.length === 0 && projects.some((project) => BROWSER_PROJECT.test(project)))
865
+ return 'heavy';
866
+ if (files.length > 0 || projects.length === 1)
867
+ return 'light';
868
+ return projects.length === 0 && operands.length === 0 ? 'heavy' : undefined;
869
+ }
870
+ /**
871
+ * Reads the lane a command's kind seeds.
872
+ *
873
+ * @remarks
874
+ * Heavy wins: a word that names a journey, a study, a capture, a live-service run, or the release
875
+ * chain seeds heavy wherever it appears, before any light kind is read.
876
+ *
877
+ * @param command - The command and its arguments.
878
+ * @returns The seeded lane, or undefined when no kind names the command.
879
+ */
880
+ export function readSeed(command) {
881
+ if (readWords(command.slice(1)).some((word) => HEAVY_WORDS.includes(word)))
882
+ return 'heavy';
883
+ const [tool, ...args] = readTool(command);
884
+ if (tool === undefined)
885
+ return undefined;
886
+ if (HEAVY_TOOLS.includes(tool))
887
+ return 'heavy';
888
+ if (MANAGERS.includes(tool)) {
889
+ const [verb, script] = readOperands(args, []);
890
+ if (verb === undefined)
891
+ return undefined;
892
+ if (HEAVY_VERBS.includes(verb))
893
+ return 'heavy';
894
+ return (verb === 'run' || verb === 'run-script') && script !== undefined
895
+ ? readScriptSeed(script)
896
+ : undefined;
897
+ }
898
+ if (tool === 'vitest')
899
+ return readVitestSeed(args);
900
+ if (tool === 'oxfmt' || tool === 'prettier')
901
+ return args.includes('--check') ? 'light' : undefined;
902
+ if (tool === 'oxlint' || tool === 'eslint') {
903
+ return args.some((argument) => argument.startsWith('--fix')) ? undefined : 'light';
904
+ }
905
+ if (tool === 'tsc' || tool === 'vue-tsc')
906
+ return args.includes('--noEmit') ? 'light' : undefined;
907
+ return undefined;
908
+ }
441
909
  /**
442
910
  * Writes the complete ticket to the stage file, which also marks this process as choosing.
443
911
  *
@@ -479,7 +947,7 @@ export function tryLink(from, to) {
479
947
  */
480
948
  export function linkStage(root, token) {
481
949
  const sequence = Math.max(0, ...readSequences(readNames(root))) + 1;
482
- return tryLink(join(root, `${token}${STAGE_SUFFIX}`), join(root, renderTicketName(sequence)))
950
+ return tryLink(join(root, `${token}${STAGE_SUFFIX}`), join(root, renderName(sequence, TICKET_SUFFIX)))
483
951
  ? sequence
484
952
  : linkStage(root, token);
485
953
  }
@@ -494,20 +962,70 @@ export function linkStage(root, token) {
494
962
  * @param root - The queue root.
495
963
  * @param sequence - This process's sequence.
496
964
  * @param token - This process's token.
497
- * @returns The holder state, the stage file to wait on, the nearest earlier ticket, or a refusal.
965
+ * @param limits - The limits this process read at arrival, which a light ticket's admission needs.
966
+ * @returns The holder state, the stage file to wait on, the earlier ticket or tickets to wait on, or
967
+ * a refusal.
498
968
  */
499
- export function decideTurn(root, sequence, token) {
969
+ export function decideTurn(root, sequence, token, limits) {
500
970
  const stage = readNames(root).find((name) => name.endsWith(STAGE_SUFFIX) && name !== `${token}${STAGE_SUFFIX}`);
501
971
  if (stage !== undefined)
502
972
  return { state: 'staged', name: stage };
503
973
  const entries = readQueue(root);
504
974
  const position = entries.findIndex((entry) => entry.sequence === sequence);
505
975
  if (position === -1) {
506
- return { state: 'refused', reason: `ticket ${renderTicketName(sequence)} is gone` };
976
+ return { state: 'refused', reason: `ticket ${renderName(sequence, TICKET_SUFFIX)} is gone` };
507
977
  }
508
- const lower = entries[position - 1];
978
+ const own = entries[position]?.ticket;
979
+ const earlier = entries.slice(0, position);
980
+ return own?.light === undefined || limits === undefined
981
+ ? decideHeavy(earlier, own?.solo === true)
982
+ : decideLight(root, earlier, own.light, limits);
983
+ }
984
+ /**
985
+ * Decides what a heavy ticket does next.
986
+ *
987
+ * @remarks
988
+ * A heavy ticket waits on the nearest earlier ticket that is not light, an unreadable one included. A
989
+ * `--solo` ticket waits on the nearest earlier ticket of either lane, so it holds with no light
990
+ * holder beside it.
991
+ *
992
+ * @param earlier - The tickets before this one, in arrival order.
993
+ * @param solo - If `true`, waits on light tickets too; if `false`, passes them.
994
+ * @returns The holder state or the ticket to wait on.
995
+ */
996
+ export function decideHeavy(earlier, solo) {
997
+ const lower = earlier.findLast((entry) => solo || entry.ticket?.light === undefined);
509
998
  return lower === undefined ? { state: 'holder' } : { state: 'behind', entry: lower };
510
999
  }
1000
+ /**
1001
+ * Decides what a light ticket does next.
1002
+ *
1003
+ * @remarks
1004
+ * A light ticket holds when every earlier light ticket holds, no earlier `--solo` ticket remains, and
1005
+ * the earlier light footprints with its own fit the limits; the earliest light ticket always fits.
1006
+ * The rule reads only earlier tickets, which can only leave, so an admission is never revoked. An
1007
+ * earlier ticket this process cannot read is waited on alone, which refuses.
1008
+ *
1009
+ * @param root - The queue root.
1010
+ * @param earlier - The tickets before this one, in arrival order.
1011
+ * @param light - This ticket's footprint.
1012
+ * @param limits - The limits.
1013
+ * @returns The holder state, the unreadable ticket to wait on, or every earlier light and `--solo`
1014
+ * ticket to wait on at once, with the light tickets that do not hold yet.
1015
+ */
1016
+ export function decideLight(root, earlier, light, limits) {
1017
+ const unread = earlier.find((entry) => entry.ticket === undefined || describeForeign(entry.ticket) !== undefined);
1018
+ if (unread !== undefined)
1019
+ return { state: 'behind', entry: unread };
1020
+ const lights = earlier.filter((entry) => entry.ticket?.light !== undefined);
1021
+ const solos = earlier.filter((entry) => entry.ticket?.solo === true);
1022
+ const pending = lights.flatMap((entry) => readRun(root, entry.sequence) === 'absent' ? [entry.sequence] : []);
1023
+ const usages = lights.flatMap((entry) => entry.ticket?.light === undefined ? [] : [entry.ticket.light]);
1024
+ const fits = usages.length === 0 || fitsBudget([...usages, light], limits);
1025
+ return solos.length === 0 && pending.length === 0 && fits
1026
+ ? { state: 'holder' }
1027
+ : { state: 'queued', entries: orderEntries([...lights, ...solos]), pending };
1028
+ }
511
1029
  /**
512
1030
  * Connects to an endpoint and parks until the connection closes.
513
1031
  *
@@ -515,11 +1033,19 @@ export function decideTurn(root, sequence, token) {
515
1033
  * @param stage - If `true`, writes the one byte a published owner closes the connection on; if
516
1034
  * `false`, writes nothing.
517
1035
  * @param parked - Called when the connection is open and the wait starts.
518
- * @returns The connect failure's code, or undefined after a connection opened and closed.
1036
+ * @param signal - Ends the wait and the connection when it aborts.
1037
+ * @param hold - If `true`, writes the byte a ticket closes the connection on when it holds; if
1038
+ * `false`, waits only for the process to end.
1039
+ * @returns The connect failure's code, or undefined after a connection opened and closed or the
1040
+ * signal aborted.
519
1041
  */
520
- export function parkOn(endpoint, stage, parked) {
1042
+ export function parkOn(endpoint, stage, parked, signal, hold = false) {
521
1043
  return new Promise((resolve) => {
522
1044
  const socket = connect(endpoint);
1045
+ signal?.addEventListener('abort', () => {
1046
+ socket.destroy();
1047
+ resolve(undefined);
1048
+ });
523
1049
  socket.once('error', (error) => resolve(readCode(error)));
524
1050
  socket.once('connect', () => {
525
1051
  socket.removeAllListeners('error');
@@ -528,26 +1054,12 @@ export function parkOn(endpoint, stage, parked) {
528
1054
  socket.resume();
529
1055
  if (stage)
530
1056
  socket.write('s');
1057
+ if (hold)
1058
+ socket.write(HOLD_BYTE);
531
1059
  parked();
532
1060
  });
533
1061
  });
534
1062
  }
535
- /**
536
- * Connects to an endpoint and leaves at once.
537
- *
538
- * @param endpoint - The endpoint.
539
- * @returns The connect failure's code, or undefined when the connection opened.
540
- */
541
- export function probeEndpoint(endpoint) {
542
- return new Promise((resolve) => {
543
- const socket = connect(endpoint);
544
- socket.once('error', (error) => resolve(readCode(error)));
545
- socket.once('connect', () => {
546
- socket.destroy();
547
- resolve(undefined);
548
- });
549
- });
550
- }
551
1063
  /**
552
1064
  * Checks whether a connect failure means the endpoint's owner is gone.
553
1065
  *
@@ -730,7 +1242,7 @@ export function sweepTree(read, kill, budget) {
730
1242
  */
731
1243
  export function reclaimTicket(root, sequence, ticket) {
732
1244
  const run = readRun(root, sequence);
733
- const files = `${renderTicketName(sequence)} and ${renderRunName(sequence)} under ${root}`;
1245
+ const files = `${renderName(sequence, TICKET_SUFFIX)} and ${renderName(sequence, RUN_SUFFIX)} under ${root}`;
734
1246
  if (run === 'unread' || (run !== 'absent' && run.launcher === undefined)) {
735
1247
  return `the owner of ${quote(ticket.label)} (pid ${String(ticket.pid)}) ended before its tree could be identified; end its tree, then delete ${files}`;
736
1248
  }
@@ -739,9 +1251,9 @@ export function reclaimTicket(root, sequence, ticket) {
739
1251
  if (members === undefined || members.length > 0) {
740
1252
  return `the owner of ${quote(ticket.label)} (pid ${String(ticket.pid)}) is gone and its tree reads as ${members === undefined ? 'unread' : `present: ${members.join(', ')}`}; launcher ${String(run.launcher)}, command ${String(run.command)}, files ${files}`;
741
1253
  }
742
- removeFile(join(root, renderRunName(sequence)));
1254
+ removeFile(join(root, renderName(sequence, RUN_SUFFIX)));
743
1255
  }
744
- removeFile(join(root, renderTicketName(sequence)));
1256
+ removeFile(join(root, renderName(sequence, TICKET_SUFFIX)));
745
1257
  removeFile(join(root, `${ticket.token}${SOCKET_SUFFIX}`));
746
1258
  return undefined;
747
1259
  }
@@ -774,7 +1286,7 @@ export async function waitOnStage(root, name) {
774
1286
  * @returns The refusal, or undefined when the wait ended.
775
1287
  */
776
1288
  export async function waitOnTicket(root, entry, announced) {
777
- const name = renderTicketName(entry.sequence);
1289
+ const name = renderName(entry.sequence, TICKET_SUFFIX);
778
1290
  const ticket = entry.ticket;
779
1291
  if (ticket === undefined)
780
1292
  return `ticket ${name} under ${root} cannot be read`;
@@ -791,27 +1303,65 @@ export async function waitOnTicket(root, entry, announced) {
791
1303
  ? reclaimTicket(root, entry.sequence, ticket)
792
1304
  : `the endpoint of ticket ${name} reported ${code}`;
793
1305
  }
1306
+ /**
1307
+ * Waits on several earlier tickets at once, until the first leaves or a pending one holds, and
1308
+ * reclaims a ticket whose owner is gone.
1309
+ *
1310
+ * @param root - The queue root.
1311
+ * @param entries - The earlier tickets, each readable and of this host.
1312
+ * @param pending - The sequences of the light tickets among them that did not hold yet, whose hold
1313
+ * also ends the wait.
1314
+ * @param announced - The tokens this process last printed a waiting line for, joined by commas.
1315
+ * @returns The refusal, or undefined when the wait ended.
1316
+ */
1317
+ export async function waitOnTickets(root, entries, pending, announced) {
1318
+ const tickets = entries.flatMap((entry) => entry.ticket === undefined ? [] : [{ sequence: entry.sequence, ticket: entry.ticket }]);
1319
+ const key = tickets.map((item) => item.ticket.token).join(',');
1320
+ const controller = new AbortController();
1321
+ const opened = tickets.map(() => Promise.withResolvers());
1322
+ const waits = tickets.map((item, index) => parkOn(renderEndpoint(root, item.ticket.token), false, () => opened[index]?.resolve(), controller.signal, pending.includes(item.sequence)).then((code) => ({ ...item, code })));
1323
+ void Promise.all(opened.map((resolvers) => resolvers.promise)).then(() => {
1324
+ if (announced !== key && !controller.signal.aborted) {
1325
+ console.error(`lane: waiting behind ${tickets.map((item) => quote(item.ticket.label)).join(', ')}`);
1326
+ }
1327
+ });
1328
+ const first = await Promise.race(waits);
1329
+ controller.abort();
1330
+ if (first.code === undefined)
1331
+ return undefined;
1332
+ return isGone(first.code)
1333
+ ? reclaimTicket(root, first.sequence, first.ticket)
1334
+ : `the endpoint of ticket ${renderName(first.sequence, TICKET_SUFFIX)} reported ${first.code}`;
1335
+ }
794
1336
  /**
795
1337
  * Waits for this process's turn, parked on events with no timer.
796
1338
  *
797
1339
  * @param root - The queue root.
798
1340
  * @param sequence - This process's sequence.
799
1341
  * @param token - This process's token.
800
- * @param announced - The token this process last printed a waiting line for.
1342
+ * @param limits - The limits this process read at arrival.
1343
+ * @param announced - The token or tokens this process last printed a waiting line for.
801
1344
  * @returns The refusal, or undefined when this process holds the lane.
802
1345
  */
803
- export async function waitForTurn(root, sequence, token, announced) {
804
- const turn = decideTurn(root, sequence, token);
1346
+ export async function waitForTurn(root, sequence, token, limits, announced) {
1347
+ const turn = decideTurn(root, sequence, token, limits);
805
1348
  if (turn.state === 'holder')
806
1349
  return undefined;
807
1350
  if (turn.state === 'refused')
808
1351
  return turn.reason;
1352
+ if (turn.state === 'queued') {
1353
+ const refusal = await waitOnTickets(root, turn.entries, turn.pending, announced);
1354
+ if (refusal !== undefined)
1355
+ return refusal;
1356
+ const key = turn.entries.map((entry) => entry.ticket?.token).join(',');
1357
+ return waitForTurn(root, sequence, token, limits, key);
1358
+ }
809
1359
  const refusal = turn.state === 'staged'
810
1360
  ? await waitOnStage(root, turn.name)
811
1361
  : await waitOnTicket(root, turn.entry, announced);
812
1362
  if (refusal !== undefined)
813
1363
  return refusal;
814
- return waitForTurn(root, sequence, token, turn.state === 'behind' ? turn.entry.ticket?.token : announced);
1364
+ return waitForTurn(root, sequence, token, limits, turn.state === 'behind' ? turn.entry.ticket?.token : announced);
815
1365
  }
816
1366
  /**
817
1367
  * Reads the command id from a launcher line.
@@ -915,35 +1465,233 @@ export function tryWriteRun(root, sequence, run) {
915
1465
  */
916
1466
  export function releaseTicket(root, sequence) {
917
1467
  try {
918
- removeFile(join(root, renderRunName(sequence)));
919
- removeFile(join(root, renderTicketName(sequence)));
1468
+ removeFile(join(root, renderName(sequence, RUN_SUFFIX)));
1469
+ removeFile(join(root, renderName(sequence, TICKET_SUFFIX)));
920
1470
  return undefined;
921
1471
  }
922
1472
  catch (error) {
923
1473
  return readCode(error);
924
1474
  }
925
1475
  }
1476
+ /**
1477
+ * Parses one sampler line.
1478
+ *
1479
+ * @param line - One line of the sampler's stdout, its rows separated by semicolons.
1480
+ * @returns One gauge per row that has the row's form, its CPU time in milliseconds.
1481
+ */
1482
+ export function parseGauges(line) {
1483
+ return line.split(';').flatMap((item) => {
1484
+ const match = GAUGE_PATTERN.exec(item.trim());
1485
+ return match === null
1486
+ ? []
1487
+ : [
1488
+ {
1489
+ pid: Number(match[1]),
1490
+ parent: Number(match[2]),
1491
+ created: Number(match[3]),
1492
+ cpu: Number(match[4]) / 10_000,
1493
+ memory: Number(match[5]),
1494
+ },
1495
+ ];
1496
+ });
1497
+ }
1498
+ /**
1499
+ * Folds one sample's members into a tally.
1500
+ *
1501
+ * @param tally - The tally so far.
1502
+ * @param members - The members one sample read.
1503
+ * @returns The tally with each member's latest CPU time, keyed by id and creation date, and the
1504
+ * larger of each peak.
1505
+ */
1506
+ export function tallySample(tally, members) {
1507
+ return {
1508
+ cpu: new Map([
1509
+ ...tally.cpu,
1510
+ ...members.map((member) => {
1511
+ const key = `${String(member.pid)}:${String(member.created)}`;
1512
+ return [key, Math.max(member.cpu, tally.cpu.get(key) ?? 0)];
1513
+ }),
1514
+ ]),
1515
+ memory: Math.max(tally.memory, members.reduce((sum, member) => sum + member.memory, 0)),
1516
+ processes: Math.max(tally.processes, members.length),
1517
+ };
1518
+ }
1519
+ /**
1520
+ * Builds a run's record from its tally.
1521
+ *
1522
+ * @param tally - The sampler's tally.
1523
+ * @param duration - The run's duration in milliseconds.
1524
+ * @param code - The lane's exit code for the run.
1525
+ * @returns The record, its CPU time summed across every member the samples read.
1526
+ */
1527
+ export function buildOutcome(tally, duration, code) {
1528
+ return {
1529
+ duration,
1530
+ cpu: [...tally.cpu.values()].reduce((sum, value) => sum + value, 0),
1531
+ memory: tally.memory,
1532
+ processes: tally.processes,
1533
+ code,
1534
+ };
1535
+ }
1536
+ /**
1537
+ * Sets a process to below-normal priority, which a Windows child inherits.
1538
+ *
1539
+ * @param pid - The process id.
1540
+ * @returns True when the host took the priority; false when it refused.
1541
+ */
1542
+ export function lowerPriority(pid) {
1543
+ try {
1544
+ setPriority(pid, constants.priority.PRIORITY_BELOW_NORMAL);
1545
+ return true;
1546
+ }
1547
+ catch {
1548
+ return false;
1549
+ }
1550
+ }
1551
+ /**
1552
+ * Writes a run's record, leaving a write the host refuses unrecorded.
1553
+ *
1554
+ * @param root - The queue root.
1555
+ * @param key - The command's key.
1556
+ * @param name - The record's name.
1557
+ * @param outcome - The record.
1558
+ * @returns True when the record was written; false otherwise.
1559
+ */
1560
+ export function tryWriteOutcome(root, key, name, outcome) {
1561
+ try {
1562
+ writeOutcome(root, key, name, outcome);
1563
+ return true;
1564
+ }
1565
+ catch {
1566
+ return false;
1567
+ }
1568
+ }
1569
+ /**
1570
+ * Samples one holder's process tree through one PowerShell child at below-normal priority.
1571
+ *
1572
+ * @remarks
1573
+ * The child exits when its stdin closes, which {@link Sampler.stop} and the end of this process both
1574
+ * do. A threshold, given for a light run, calls the breach handler once, on the first sample whose
1575
+ * memory or process count passes it.
1576
+ */
1577
+ export class Sampler {
1578
+ #child;
1579
+ #closed;
1580
+ #floor;
1581
+ #threshold;
1582
+ #breach;
1583
+ #seeds = [];
1584
+ #tally = { cpu: new Map(), memory: 0, processes: 0 };
1585
+ #breached = false;
1586
+ /**
1587
+ * Starts the sampler.
1588
+ *
1589
+ * @param floor - The earliest creation date the tree can carry.
1590
+ * @param threshold - The light run's threshold, or undefined for a heavy run.
1591
+ * @param breach - Called once when a sample passes the threshold.
1592
+ */
1593
+ constructor(floor, threshold, breach) {
1594
+ this.#floor = floor;
1595
+ this.#threshold = threshold;
1596
+ this.#breach = breach;
1597
+ this.#child = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', SAMPLER_COMMAND], { stdio: ['pipe', 'pipe', 'ignore'], windowsHide: true });
1598
+ this.#closed = waitForClose(this.#child).then(() => undefined);
1599
+ this.#child.stdin?.on('error', () => undefined);
1600
+ if (this.#child.pid !== undefined)
1601
+ lowerPriority(this.#child.pid);
1602
+ if (this.#child.stdout !== null) {
1603
+ const lines = createInterface({ input: this.#child.stdout, crlfDelay: Infinity });
1604
+ lines.on('error', () => undefined);
1605
+ lines.on('line', (line) => this.#read(line));
1606
+ }
1607
+ }
1608
+ /** Holds the sampler's process id, undefined when it could not start. */
1609
+ get pid() {
1610
+ return this.#child.pid;
1611
+ }
1612
+ /** Holds what the samples read so far. */
1613
+ get tally() {
1614
+ return this.#tally;
1615
+ }
1616
+ /** Holds whether a sample passed the threshold. */
1617
+ get breached() {
1618
+ return this.#breached;
1619
+ }
1620
+ /**
1621
+ * Names the ids whose trees later samples read.
1622
+ *
1623
+ * @param seeds - The launcher id and, once known, the command id.
1624
+ */
1625
+ seed(seeds) {
1626
+ this.#seeds = seeds;
1627
+ }
1628
+ /**
1629
+ * Closes the sampler's stdin, which ends it.
1630
+ *
1631
+ * @returns A promise that resolves when the sampler has exited.
1632
+ */
1633
+ stop() {
1634
+ this.#child.stdin?.end();
1635
+ return this.#closed;
1636
+ }
1637
+ #read(line) {
1638
+ const members = selectMembers(parseGauges(line), this.#seeds, this.#floor, Date.now());
1639
+ this.#tally = tallySample(this.#tally, members);
1640
+ const threshold = this.#threshold;
1641
+ if (threshold === undefined ||
1642
+ this.#breached ||
1643
+ (this.#tally.memory <= threshold.memory && this.#tally.processes <= threshold.processes)) {
1644
+ return;
1645
+ }
1646
+ this.#breached = true;
1647
+ this.#breach();
1648
+ }
1649
+ }
926
1650
  /**
927
1651
  * Runs the command as the holder, reads the tree at handover, and releases.
928
1652
  *
1653
+ * @remarks
1654
+ * A measured holder samples its tree and writes the run's record before it releases, so the
1655
+ * command's next arrival reads it. A light holder lowers its own priority before the spawn, and ends
1656
+ * its tree when a sample passes the threshold.
1657
+ *
929
1658
  * @param options - The run.
930
1659
  * @param launcher - The launcher's path.
931
1660
  * @param sequence - This process's sequence.
932
- * @returns The launcher's code; 1 when a signal ended it; 70 when the tree still reads as present or
933
- * the ticket could not be removed; 75 when the launcher could not start.
1661
+ * @param measure - What a measured holder needs, or undefined when no limits apply.
1662
+ * @param token - This process's endpoint, which holds after the run record exists and leaves before
1663
+ * the run record is removed.
1664
+ * @returns The launcher's code; 1 when a signal ended it; 69 when a light run passed its threshold;
1665
+ * 70 when the tree still reads as present or the ticket could not be removed; 75 when the launcher
1666
+ * could not start, the priority could not be lowered, or the run record could not be written.
934
1667
  */
935
- export async function runHolder(options, launcher, sequence) {
1668
+ export async function runHolder(options, launcher, sequence, measure, token) {
936
1669
  const { root } = options;
1670
+ if (measure?.light !== undefined && !lowerPriority(process.pid)) {
1671
+ releaseTicket(root, sequence);
1672
+ console.error('lane: the host refused the light run its below-normal priority');
1673
+ return 75;
1674
+ }
937
1675
  const started = Date.now();
938
- writeRun(root, sequence, { started, launcher: undefined, command: undefined });
1676
+ if (!tryWriteRun(root, sequence, { started, launcher: undefined, command: undefined })) {
1677
+ const refusal = releaseTicket(root, sequence);
1678
+ console.error(`lane: the run record ${renderName(sequence, RUN_SUFFIX)} under ${root} could not be written; ${refusal === undefined ? 'the ticket was removed' : `removing the ticket reported ${refusal}`}`);
1679
+ return refusal === undefined ? 75 : HELD_CODE;
1680
+ }
1681
+ token?.hold();
939
1682
  const child = startLauncher(launcher, options);
940
1683
  const id = child.pid;
941
1684
  if (id === undefined) {
1685
+ token?.leave();
942
1686
  releaseTicket(root, sequence);
943
1687
  console.error(`lane: ${quote(launcher)} could not start`);
944
1688
  return 75;
945
1689
  }
946
1690
  tryWriteRun(root, sequence, { started, launcher: id, command: undefined });
1691
+ const sampler = measure === undefined
1692
+ ? undefined
1693
+ : new Sampler(started - CLOCK_ALLOWANCE_MS, measure.light === undefined ? undefined : measure.limits.threshold, () => killMembers([id]));
1694
+ sampler?.seed([id]);
947
1695
  const unwatch = watchSignals(() => killMembers([id]));
948
1696
  const closed = waitForClose(child);
949
1697
  if (child.stdout !== null) {
@@ -952,27 +1700,68 @@ export async function runHolder(options, launcher, sequence) {
952
1700
  lines.on('line', (line) => {
953
1701
  console.log(line);
954
1702
  const command = readCommandId(line);
955
- if (command !== undefined)
956
- tryWriteRun(root, sequence, { started, launcher: id, command });
1703
+ if (command === undefined)
1704
+ return;
1705
+ tryWriteRun(root, sequence, { started, launcher: id, command });
1706
+ sampler?.seed([id, command]);
957
1707
  });
958
1708
  }
959
1709
  const code = await closed;
960
1710
  unwatch();
961
1711
  const ended = Date.now();
1712
+ const stopped = sampler?.stop();
962
1713
  const run = readRun(root, sequence);
963
1714
  const sweep = run === 'absent' || run === 'unread'
964
1715
  ? { gone: false, members: [] }
965
1716
  : sweepTree(() => readTree(run, ended), killMembers, KILL_BUDGET);
1717
+ const breached = sampler?.breached === true;
1718
+ const result = !sweep.gone ? HELD_CODE : breached ? BREACH_CODE : (code ?? 1);
1719
+ if (measure !== undefined && sampler !== undefined) {
1720
+ tryWriteOutcome(root, measure.key, renderOutcomeName(ended, measure.token), buildOutcome(sampler.tally, ended - started, result));
1721
+ }
966
1722
  if (!sweep.gone) {
967
- console.error(`lane: the tree of ${quote(options.label)} still reads as ${sweep.members.length === 0 ? 'unread' : `present: ${sweep.members.join(', ')}`}; the lane stays held by ${renderTicketName(sequence)} and ${renderRunName(sequence)} under ${root}`);
968
- return 70;
1723
+ console.error(`lane: the tree of ${quote(options.label)} still reads as ${sweep.members.length === 0 ? 'unread' : `present: ${sweep.members.join(', ')}`}; the lane stays held by ${renderName(sequence, TICKET_SUFFIX)} and ${renderName(sequence, RUN_SUFFIX)} under ${root}`);
1724
+ await stopped;
1725
+ return HELD_CODE;
969
1726
  }
1727
+ token?.leave();
970
1728
  const refusal = releaseTicket(root, sequence);
1729
+ await stopped;
971
1730
  if (refusal !== undefined) {
972
- console.error(`lane: removing ${renderTicketName(sequence)} reported ${refusal}`);
973
- return 70;
1731
+ console.error(`lane: removing ${renderName(sequence, TICKET_SUFFIX)} reported ${refusal}`);
1732
+ return HELD_CODE;
1733
+ }
1734
+ if (breached) {
1735
+ console.error(`lane: ${quote(options.label)} passed the light threshold and was ended; its next arrival runs heavy`);
974
1736
  }
975
- return code ?? 1;
1737
+ return result;
1738
+ }
1739
+ /**
1740
+ * Reads what a run measures at arrival: the limits, the command's key, and its light footprint.
1741
+ *
1742
+ * @remarks
1743
+ * A host other than Windows has no sampler, so it measures nothing and every ticket there is heavy.
1744
+ * A `--solo` run is heavy whatever its command reads.
1745
+ *
1746
+ * @param options - The run.
1747
+ * @param token - This process's token.
1748
+ * @returns What the holder measures, or undefined when `limits.json` is absent or malformed or the
1749
+ * host has no sampler.
1750
+ */
1751
+ export function readMeasure(options, token) {
1752
+ if (process.platform !== 'win32')
1753
+ return undefined;
1754
+ const limits = readLimits(options.root);
1755
+ if (limits === 'unread') {
1756
+ console.error(`lane: ${LIMITS_FILE} under ${options.root} cannot be read as limits; the ticket runs heavy`);
1757
+ }
1758
+ if (limits === 'absent' || limits === 'unread')
1759
+ return undefined;
1760
+ const key = renderKey(realpathSync(process.cwd()), options.command);
1761
+ const light = options.solo
1762
+ ? undefined
1763
+ : classifyLight(readSeed(options.command), readOutcomes(options.root, key), limits);
1764
+ return { limits, key, token, light };
976
1765
  }
977
1766
  /**
978
1767
  * Takes a ticket, waits for this process's turn, and runs the command.
@@ -987,21 +1776,23 @@ export async function enterLane(options, launcher, tokenId, token) {
987
1776
  const { root } = options;
988
1777
  try {
989
1778
  mkdirSync(root, { recursive: true });
1779
+ const measure = readMeasure(options, tokenId);
990
1780
  await token.listen(renderEndpoint(root, tokenId));
991
- writeStage(root, buildTicket(tokenId, options.label));
1781
+ writeStage(root, buildTicket(tokenId, options.label, measure?.light, options.solo));
992
1782
  const sequence = linkStage(root, tokenId);
993
1783
  removeFile(join(root, `${tokenId}${STAGE_SUFFIX}`));
994
1784
  token.publish();
995
1785
  const unwatch = watchSignals(() => {
996
- removeFile(join(root, renderTicketName(sequence)));
1786
+ removeFile(join(root, renderName(sequence, TICKET_SUFFIX)));
997
1787
  removeFile(renderEndpoint(root, tokenId));
998
1788
  process.exit(75);
999
1789
  });
1000
- const refusal = await waitForTurn(root, sequence, tokenId);
1790
+ const refusal = await waitForTurn(root, sequence, tokenId, measure?.limits);
1001
1791
  unwatch();
1002
- if (refusal === undefined)
1003
- return await runHolder(options, launcher, sequence);
1004
- removeFile(join(root, renderTicketName(sequence)));
1792
+ if (refusal === undefined) {
1793
+ return await runHolder(options, launcher, sequence, measure, token);
1794
+ }
1795
+ removeFile(join(root, renderName(sequence, TICKET_SUFFIX)));
1005
1796
  console.error(`lane: ${refusal}`);
1006
1797
  return 75;
1007
1798
  }
@@ -1036,40 +1827,60 @@ export async function runLane(options) {
1036
1827
  */
1037
1828
  export async function readStatusRow(root, entry) {
1038
1829
  const ticket = entry.ticket;
1039
- const fields = { sequence: entry.sequence, label: ticket?.label, pid: ticket?.pid };
1830
+ const fields = {
1831
+ sequence: entry.sequence,
1832
+ label: ticket?.label,
1833
+ pid: ticket?.pid,
1834
+ light: ticket?.light !== undefined,
1835
+ solo: ticket?.solo === true,
1836
+ };
1040
1837
  if (ticket === undefined || describeForeign(ticket) !== undefined) {
1041
- return { ...fields, state: 'unread' };
1838
+ return { ...fields, state: 'unread', holding: false };
1042
1839
  }
1043
- const code = await probeEndpoint(renderEndpoint(root, ticket.token));
1044
- if (code === undefined)
1045
- return { ...fields, state: 'live' };
1046
- return { ...fields, state: isGone(code) ? 'dead' : 'unread' };
1840
+ const probe = new AbortController();
1841
+ const code = await parkOn(renderEndpoint(root, ticket.token), false, () => probe.abort(), probe.signal);
1842
+ if (code === undefined) {
1843
+ const holding = existsSync(join(root, renderName(entry.sequence, RUN_SUFFIX)));
1844
+ return { ...fields, state: 'live', holding };
1845
+ }
1846
+ return { ...fields, state: isGone(code) ? 'dead' : 'unread', holding: false };
1047
1847
  }
1048
1848
  /**
1049
1849
  * Reads the queue for `--status`.
1050
1850
  *
1051
1851
  * @param root - The queue root.
1052
- * @returns Every ticket in arrival order, and the earliest live ticket with a run record.
1852
+ * @returns Every ticket in arrival order, and the earliest holding ticket that is not light.
1053
1853
  */
1054
1854
  export async function readStatus(root) {
1055
1855
  const tickets = await Promise.all(readQueue(root).map((entry) => readStatusRow(root, entry)));
1056
- return {
1057
- tickets,
1058
- holder: tickets.find((row) => row.state === 'live' && existsSync(join(root, renderRunName(row.sequence)))),
1059
- };
1856
+ return { tickets, holder: tickets.find((row) => row.holding && !row.light) };
1060
1857
  }
1061
1858
  /**
1062
1859
  * Renders the queue as text.
1063
1860
  *
1064
1861
  * @param status - What `--status` read.
1065
- * @returns One line for the holder and one per ticket, in arrival order.
1862
+ * @returns One line for the heavy holder, one naming every light holder, and one per ticket with its
1863
+ * lane, in arrival order.
1066
1864
  */
1067
1865
  export function renderStatus(status) {
1866
+ const lights = status.tickets.filter((row) => row.holding && row.light);
1068
1867
  return [
1069
1868
  `holder: ${status.holder === undefined ? 'none' : quote(status.holder.label ?? 'unread')}`,
1070
- ...status.tickets.map((row) => `${renderTicketName(row.sequence)} ${row.state} ${quote(row.label ?? 'unread')} pid ${String(row.pid)}`),
1869
+ `light: ${lights.length === 0 ? 'none' : lights.map((row) => quote(row.label ?? 'unread')).join(', ')}`,
1870
+ ...status.tickets.map((row) => `${renderName(row.sequence, TICKET_SUFFIX)} ${row.state} ${renderLane(row)}${row.holding ? ' holding' : ''} ${quote(row.label ?? 'unread')} pid ${String(row.pid)}`),
1071
1871
  ].join('\n');
1072
1872
  }
1873
+ /**
1874
+ * Names a ticket's lane for `--status`.
1875
+ *
1876
+ * @param row - The ticket's row.
1877
+ * @returns `solo`, `light`, or `heavy`.
1878
+ */
1879
+ export function renderLane(row) {
1880
+ if (row.solo)
1881
+ return 'solo';
1882
+ return row.light ? 'light' : 'heavy';
1883
+ }
1073
1884
  /**
1074
1885
  * Prints the queue, writing nothing under the root.
1075
1886
  *
@@ -1088,31 +1899,48 @@ export async function runStatus(root, json) {
1088
1899
  return 75;
1089
1900
  }
1090
1901
  }
1902
+ /**
1903
+ * Parses a cap given in seconds.
1904
+ *
1905
+ * @param text - The value after `--cap`.
1906
+ * @returns The cap, or undefined when the text is absent, not a finite number, not above 0, or past
1907
+ * the launcher's limit.
1908
+ */
1909
+ export function parseCap(text) {
1910
+ const cap = Number(text ?? Number.NaN);
1911
+ return Number.isFinite(cap) && cap > 0 && cap <= MAX_CAP_SECONDS ? cap : undefined;
1912
+ }
1091
1913
  /**
1092
1914
  * Validates a run's arguments.
1093
1915
  *
1094
- * @param own - The arguments before the bare `--`.
1916
+ * @param values - The flag values `parseArgs` read before the bare `--`.
1095
1917
  * @param command - The arguments after the bare `--`.
1096
1918
  * @returns The run, or undefined when a flag or the command is missing or out of range.
1097
1919
  */
1098
- export function readLaneOptions(own, command) {
1099
- const label = readOption(own, '--label');
1100
- const journal = readOption(own, '--journal');
1101
- const errors = readOption(own, '--errors');
1102
- const cap = Number(readOption(own, '--cap') ?? Number.NaN);
1920
+ export function readLaneOptions(values, command) {
1921
+ const label = typeof values.label === 'string' ? values.label : undefined;
1922
+ const journal = typeof values.journal === 'string' ? values.journal : undefined;
1923
+ const errors = typeof values.errors === 'string' ? values.errors : undefined;
1924
+ const cap = parseCap(typeof values.cap === 'string' ? values.cap : undefined);
1103
1925
  if (label === undefined ||
1104
1926
  label === '' ||
1105
1927
  journal === undefined ||
1106
1928
  errors === undefined ||
1107
1929
  journal === errors ||
1108
- !Number.isFinite(cap) ||
1109
- cap <= 0 ||
1110
- cap > MAX_CAP_SECONDS ||
1930
+ cap === undefined ||
1111
1931
  command[0] === undefined ||
1112
1932
  command[0] === '') {
1113
1933
  return undefined;
1114
1934
  }
1115
- return { root: resolveRoot(readOption(own, '--root')), label, journal, errors, cap, command };
1935
+ return {
1936
+ root: resolveRoot(typeof values.root === 'string' ? values.root : undefined),
1937
+ label,
1938
+ journal,
1939
+ errors,
1940
+ cap,
1941
+ solo: values.solo === true,
1942
+ command,
1943
+ };
1116
1944
  }
1117
1945
  /**
1118
1946
  * Runs the script on its arguments.
@@ -1125,31 +1953,27 @@ export function readLaneOptions(own, command) {
1125
1953
  */
1126
1954
  export async function main(argv) {
1127
1955
  const end = argv.indexOf('--');
1128
- const own = end === -1 ? argv : argv.slice(0, end);
1129
1956
  const command = end === -1 ? [] : argv.slice(end + 1);
1130
- const unknown = readUnknownFlags(argv, FLAGS);
1131
- if (unknown.length > 0) {
1132
- console.error(`lane: ${unknown.join(', ')} is not a flag this script reads; ${USAGE}`);
1133
- return 64;
1134
- }
1135
- const missing = readMissingFlags(own, VALUE_FLAGS);
1136
- if (missing.length > 0) {
1137
- console.error(`lane: ${missing.join(', ')} given with no value; ${USAGE}`);
1957
+ const parsed = parseArguments(end === -1 ? argv : argv.slice(0, end));
1958
+ if (!parsed.success) {
1959
+ console.error(`lane: ${parsed.error}; ${USAGE}`);
1138
1960
  return 64;
1139
1961
  }
1140
- if (readPositionals(own, VALUE_FLAGS).length > 0) {
1141
- console.error(USAGE);
1142
- return 64;
1143
- }
1144
- const status = own.includes('--status');
1145
- if (status) {
1146
- if (end !== -1 || RUN_FLAGS.some((flag) => own.includes(flag))) {
1962
+ const { values } = parsed.value;
1963
+ const root = typeof values.root === 'string' ? values.root : undefined;
1964
+ if (values.status === true) {
1965
+ if (end !== -1 || RUN_OPTIONS.some((name) => values[name] !== undefined)) {
1147
1966
  console.error(`lane: --status and a run are two modes; ${USAGE}`);
1148
1967
  return 64;
1149
1968
  }
1150
- return runStatus(resolveRoot(readOption(own, '--root')), own.includes('--json'));
1969
+ return runStatus(resolveRoot(root), values.json === true);
1970
+ }
1971
+ const cap = typeof values.cap === 'string' ? values.cap : undefined;
1972
+ if (cap !== undefined && parseCap(cap) === undefined) {
1973
+ console.error(`lane: --cap takes a number of seconds above 0 up to ${String(MAX_CAP_SECONDS)}, not ${quote(cap)}; ${USAGE}`);
1974
+ return 64;
1151
1975
  }
1152
- const options = own.includes('--json') ? undefined : readLaneOptions(own, command);
1976
+ const options = values.json === true ? undefined : readLaneOptions(values, command);
1153
1977
  if (options === undefined) {
1154
1978
  console.error(USAGE);
1155
1979
  return 64;