@orkestrel/scaffold 0.0.132 → 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 (86) 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 +30 -6
  25. package/dist/bin/main.js.map +1 -1
  26. package/dist/host/agents/orchestration.md +1 -0
  27. package/dist/host/agents/skills/orkestrel-dispatch/scripts/bench.ts +81 -97
  28. package/dist/host/agents/skills/orkestrel-dispatch/scripts/brief.ts +64 -72
  29. package/dist/host/agents/skills/orkestrel-dispatch/scripts/chain.ts +41 -63
  30. package/dist/host/agents/skills/orkestrel-dispatch/scripts/cite.ts +56 -79
  31. package/dist/host/agents/skills/orkestrel-dispatch/scripts/launch.ts +61 -74
  32. package/dist/host/agents/skills/orkestrel-dispatch/scripts/login.ts +59 -89
  33. package/dist/host/agents/skills/orkestrel-dispatch/scripts/patch.ts +87 -106
  34. package/dist/host/agents/skills/orkestrel-dispatch/scripts/result.ts +57 -76
  35. package/dist/host/agents/skills/orkestrel-dispatch/scripts/sweep.ts +73 -88
  36. package/dist/host/agents/skills/orkestrel-falsify/SKILL.md +2 -2
  37. package/dist/host/agents/skills/orkestrel-falsify/scripts/mutate.ts +167 -119
  38. package/dist/host/agents/skills/orkestrel-harden/references/methods.md +1 -1
  39. package/dist/host/agents/skills/orkestrel-harden/scripts/discovery.ts +58 -75
  40. package/dist/host/agents/skills/orkestrel-harden/scripts/interleave.ts +55 -99
  41. package/dist/host/agents/skills/orkestrel-harden/scripts/measure.ts +59 -90
  42. package/dist/host/agents/skills/orkestrel-harden/scripts/titles.ts +60 -80
  43. package/dist/host/agents/skills/orkestrel-parallel/SKILL.md +4 -4
  44. package/dist/host/agents/skills/orkestrel-parallel/scripts/cases.ts +71 -108
  45. package/dist/host/agents/skills/orkestrel-parallel/scripts/lane.ts +1288 -239
  46. package/dist/host/agents/skills/orkestrel-publish/references/wave.md +10 -6
  47. package/dist/host/agents/skills/orkestrel-publish/scripts/compare.ts +58 -79
  48. package/dist/host/agents/skills/orkestrel-publish/scripts/pins.ts +66 -87
  49. package/dist/host/agents/skills/orkestrel-publish/scripts/steps.ts +84 -102
  50. package/dist/host/agents/skills/orkestrel-publish/scripts/swap.ts +92 -99
  51. package/dist/host/agents/skills/orkestrel-publish/scripts/wave.ts +130 -126
  52. package/dist/host/agents/skills/orkestrel-publish/scripts/window.ts +82 -120
  53. package/dist/host/agents/skills/orkestrel-scout/SKILL.md +3 -3
  54. package/dist/host/agents/skills/orkestrel-scout/scripts/map.ts +85 -112
  55. package/dist/host/claude/agents/orkestrel.md +54 -54
  56. package/dist/host/claude/rules/documentation.md +1 -1
  57. package/dist/host/claude/rules/patterns.md +5 -4
  58. package/dist/host/claude/rules/styles.md +1 -1
  59. package/dist/host/claude/rules/tests.md +8 -3
  60. package/dist/host/claude/rules/workspace.md +47 -35
  61. package/dist/host/configs/helpers.ts +40 -15
  62. package/dist/host/dotfiles/oxlintrc.json +62 -0
  63. package/dist/host/guides/browser.md +1 -1
  64. package/dist/host/guides/form.md +79 -4
  65. package/dist/host/guides/queue.md +3 -1
  66. package/dist/host/guides/scaffold.md +95 -67
  67. package/dist/host/guides/table.md +20 -6
  68. package/dist/host/guides/test.md +342 -202
  69. package/dist/host/guides/workflow.md +4 -2
  70. package/dist/host/manifest.json +48 -48
  71. package/dist/host/tests/config.test.ts +201 -11
  72. package/dist/host/tests/policy.test.ts +15 -22
  73. package/dist/host/tests/setupPolicy.ts +43 -36
  74. package/dist/src/core/index.cjs +194 -97
  75. package/dist/src/core/index.cjs.map +1 -1
  76. package/dist/src/core/index.d.cts +27 -13
  77. package/dist/src/core/index.d.ts +27 -13
  78. package/dist/src/core/index.js +192 -97
  79. package/dist/src/core/index.js.map +1 -1
  80. package/dist/src/server/index.cjs +8 -9
  81. package/dist/src/server/index.cjs.map +1 -1
  82. package/dist/src/server/index.d.cts +1 -1
  83. package/dist/src/server/index.d.ts +1 -1
  84. package/dist/src/server/index.js +8 -9
  85. package/dist/src/server/index.js.map +1 -1
  86. package/package.json +5 -5
@@ -1,29 +1,52 @@
1
- // Run one process-running command at a time on this host, in arrival order, across every checkout
2
- // and shell of one user account. Run from the checkout root:
3
- // node .agents/skills/orkestrel-parallel/scripts/lane.ts --label NAME --journal PATH --errors PATH --cap SECONDS [--root DIR] -- COMMAND [ARGS...]
1
+ // Run process-running commands on this host in one heavy lane and several light lanes, in arrival
2
+ // order, across every checkout and shell of one user account. Run from the checkout root:
3
+ // node .agents/skills/orkestrel-parallel/scripts/lane.ts --label NAME --journal PATH --errors PATH --cap SECONDS [--root DIR] [--solo] -- COMMAND [ARGS...]
4
4
  // node .agents/skills/orkestrel-parallel/scripts/lane.ts --status [--root DIR] [--json]
5
- // A run takes a ticket, waits for every earlier ticket, runs the command through the dispatch skill's
6
- // `launch` script, reads the process tree, and releases. The launcher owns the cap, the journal, and
7
- // the errors file; its stdout lines pass through verbatim, and the cap must be above 0. The two forms
8
- // are two operation modes, so `--status` with a run's flag or a bare `--` is refused, and `--json`
9
- // belongs to `--status` alone. A run therefore cannot ask the launcher for its own `--status` files.
10
- // `--status` prints each ticket in arrival order with its label and
11
- // `live`, `dead`, or `unread`, and names the holder: the earliest live ticket with a run record. It
12
- // writes nothing, removes nothing, and creates no root; an absent root reads as an empty queue. The
13
- // root is `.orkestrel/lane` under the account's home directory, read from the account record and
14
- // never from an environment variable; `--root DIR` is for a proof. Bench execs stay outside the lane,
15
- // because the host bound counts process-running commands.
5
+ // A run takes a ticket, waits for its turn, runs the command through the dispatch skill's `launch`
6
+ // script, reads the process tree, and releases. The launcher owns the cap, the journal, and the
7
+ // errors file; its stdout lines pass through verbatim, and the cap must be above 0. The script reads
8
+ // its flags before the first bare `--` with `parseArgs` in strict mode, and passes every argument
9
+ // after it to the command. The two forms are two operation modes, so `--status` with a run's flag
10
+ // (`--solo` included) or a bare `--` is refused, and `--json` belongs to `--status` alone. A run
11
+ // therefore cannot ask the launcher for its own `--status` files.
12
+ // Lanes: a ticket is heavy unless its arrival reads it light, and the reading is frozen in the
13
+ // ticket. A heavy ticket holds when it is the earliest live non-light ticket; a `--solo` ticket is
14
+ // heavy and also waits out every earlier light ticket. A light ticket holds when every earlier light
15
+ // ticket holds, no earlier `--solo` ticket is live, and the light holders' summed peaks with its own
16
+ // fit `slots` and each budget; the earliest light ticket always fits. A light holder runs at
17
+ // below-normal priority, and its holder ends it and exits 69 when a sample passes the memory or
18
+ // process threshold.
19
+ // Light reading: `<root>/limits.json` holds `slots`, the `budget` and the per-run `threshold`; while
20
+ // it is absent or malformed, or on a host other than Windows, every ticket is heavy, no sampler runs,
21
+ // and no record is written. Otherwise each holder samples its tree through one PowerShell child that
22
+ // exits when its stdin closes, and writes one record per run under `<root>/history/<key>/`, keyed by
23
+ // the working directory and the command, keeping the latest runs. The command's kind seeds the
24
+ // reading: a format check, a lint check, a type check, and a scoped test run read light until a
25
+ // record breaches; a full suite, a run of several projects, an install, a pack-and-install suite, a
26
+ // release chain, a journey, a study, a capture, and a live-service run read heavy; any other command reads light only when its latest runs each sit
27
+ // inside the threshold, none capped and none ending 69 or 70.
28
+ // `--status` prints each ticket in arrival order with its label, `live`, `dead`, or `unread`, its
29
+ // lane, and `holding` for a holder, and names the heavy holder and every light holder. It writes
30
+ // nothing, removes nothing, and creates no root; an absent root reads as an empty queue. The root is
31
+ // `.orkestrel/lane` under the account's home directory, read from the account record and never from
32
+ // an environment variable; `--root DIR` is for a proof. Bench execs stay outside the lane, because
33
+ // the host bound counts process-running commands.
16
34
  // Exit: the launcher's code (the command's code, 124 when capped, 127 when the command could not
17
- // start); 1 when a signal ended the launcher; 64 on usage; 75 when the lane refused before the
18
- // command ran; 70 when the command ran and its tree still reads as present, or its ticket could not
19
- // be removed. `--status` exits 0 on a read and 75 when the root cannot be listed. A command that itself
20
- // exits 64, 70, or 75 reads like the lane's own code.
35
+ // start); 1 when a signal ended the launcher; 64 on usage; 69 when a light run passed its threshold
36
+ // and its holder ended it; 75 when the lane refused before the command ran; 70 when the command ran
37
+ // and its tree still reads as present, or its ticket could not be removed. `--status` exits 0 on a
38
+ // read and 75 when the root cannot be listed. A command that itself exits 64, 69, 70, or 75 reads
39
+ // like the lane's own code.
21
40
  // Protocol: a process listens on an endpoint named by a random token, writes the complete ticket to
22
41
  // `<token>.stage`, and hard-links that file to `<sequence>.ticket`, which publishes it in one step.
23
- // A waiter parks on the `close` of the nearest earlier ticket's endpoint with no timer, and a refused
24
- // connect means that owner is gone. A waiter on a stage file writes one byte, and a published owner
25
- // closes that connection, because a connection its synchronous allocation left unaccepted would
26
- // otherwise stay parked on a process that waits behind it.
42
+ // A waiter parks on the `close` of each earlier ticket's endpoint it waits on with no timer, and a
43
+ // refused connect means that owner is gone. A waiter on a stage file writes one byte, and a published
44
+ // owner closes that connection, because a connection its synchronous allocation left unaccepted
45
+ // would otherwise stay parked on a process that waits behind it. A light waiter writes `h` to an
46
+ // earlier light ticket that did not hold yet, and that owner closes the connection when it holds,
47
+ // so the waiter decides again; a byte that reaches an owner that is releasing parks until it ends. The protocol stays 1: the `light` and `solo` ticket fields are
48
+ // optional, a ticket without them reads as heavy, and a process of the first release holds only as
49
+ // the earliest ticket.
27
50
  // Limits:
28
51
  // - Process-identifier reuse, Windows. A row is matched by id and creation date, bounded by a clock
29
52
  // comparison, so a reuse of an exited seed's id inside the clock allowance can misattribute a row.
@@ -41,6 +64,10 @@
41
64
  // - An owner ended between the run record and the launcher id. The tree cannot be identified. Arrivals
42
65
  // exit 75 until a person deletes the named files. An owner ended between the launcher id and the
43
66
  // command id leaves the command as no seed, so its tree reads through the launcher alone.
67
+ // - A dead light holder with a live tree. Light arrivals exit 75 until that tree is gone; heavy
68
+ // arrivals do not wait on it.
69
+ // - Sampling. A process that lives between two samples goes uncounted, the CPU time of a member that
70
+ // exits between samples is lost, and disk input and output are not measured.
44
71
  // - An unreaped member. On a host whose init does not reap, a killed member can keep reading as
45
72
  // present. The lane exits 70 and stays held.
46
73
  // - Listing completeness. No probe proves that a listing returns every stable entry. The design takes
@@ -54,10 +81,12 @@
54
81
  // Migration stop: a second queue does not see the first, so while a host's sessions run another
55
82
  // serializer, no caller moves. After a scaffold release carries this script and no command runs on the
56
83
  // host, move every caller in one step and delete the serializer this replaces.
84
+ import type { ParseArgsOptionsConfig } from 'node:util'
57
85
  import type { ChildProcess } from 'node:child_process'
58
86
  import type { Server, Socket } from 'node:net'
59
87
  import { spawn, spawnSync } from 'node:child_process'
60
- import { randomUUID } from 'node:crypto'
88
+ import { createHash, randomUUID } from 'node:crypto'
89
+ import { once } from 'node:events'
61
90
  import {
62
91
  existsSync,
63
92
  linkSync,
@@ -69,32 +98,66 @@ import {
69
98
  writeFileSync,
70
99
  } from 'node:fs'
71
100
  import { connect, createServer } from 'node:net'
72
- import { hostname, userInfo } from 'node:os'
73
- import { dirname, extname, join } from 'node:path'
101
+ import { constants, hostname, setPriority, userInfo } from 'node:os'
102
+ import { basename, dirname, extname, isAbsolute, join } from 'node:path'
74
103
  import { createInterface } from 'node:readline'
75
104
  import { fileURLToPath } from 'node:url'
105
+ import { parseArgs } from 'node:util'
76
106
 
77
107
  /** Holds the protocol version a ticket carries, so a process refuses a ticket it cannot read. */
78
108
  export const PROTOCOL = 1
79
109
 
80
- /** Lists the flags that take a value. */
81
- export const VALUE_FLAGS: readonly string[] = [
82
- '--label',
83
- '--journal',
84
- '--errors',
85
- '--cap',
86
- '--root',
87
- ]
88
-
89
- /** Lists the flags only a run reads, which `--status` refuses. */
90
- export const RUN_FLAGS: readonly string[] = ['--label', '--journal', '--errors', '--cap']
91
-
92
- /** Lists every flag the script reads, value flags and switches alike. */
93
- export const FLAGS: readonly string[] = [...VALUE_FLAGS, '--status', '--json']
110
+ /** Lists the flags only a run reads, which `--status` refuses, by the name `parseArgs` reads them under. */
111
+ export const RUN_OPTIONS: readonly string[] = ['label', 'journal', 'errors', 'cap', 'solo']
94
112
 
95
113
  /** Holds the usage line printed on a usage refusal. */
96
114
  export const USAGE =
97
- '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'
115
+ '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'
116
+
117
+ /** Declares every flag the script reads, for `parseArgs`. */
118
+ export const OPTIONS: ParseArgsOptionsConfig = Object.freeze({
119
+ label: Object.freeze({ type: 'string' }),
120
+ journal: Object.freeze({ type: 'string' }),
121
+ errors: Object.freeze({ type: 'string' }),
122
+ cap: Object.freeze({ type: 'string' }),
123
+ root: Object.freeze({ type: 'string' }),
124
+ status: Object.freeze({ type: 'boolean' }),
125
+ json: Object.freeze({ type: 'boolean' }),
126
+ solo: Object.freeze({ type: 'boolean' }),
127
+ })
128
+
129
+ /** Describes the arguments `parseArgs` read: each flag's value by name, and the positionals. */
130
+ export interface Arguments {
131
+ readonly values: Readonly<
132
+ Record<string, string | boolean | ReadonlyArray<string | boolean> | undefined>
133
+ >
134
+ readonly positionals: readonly string[]
135
+ }
136
+
137
+ /** Describes how `parseArgs` read the arguments: the arguments, or the message it refused them with. */
138
+ export type ArgumentsResult =
139
+ | { readonly success: true; readonly value: Arguments }
140
+ | { readonly success: false; readonly error: string }
141
+
142
+ /**
143
+ * Parses the arguments in strict mode against `OPTIONS`.
144
+ *
145
+ * @param argv - The arguments after the script path.
146
+ * @returns The values and positionals, or the message `parseArgs` refused the arguments with.
147
+ */
148
+ export function parseArguments(argv: readonly string[]): ArgumentsResult {
149
+ try {
150
+ const { values, positionals } = parseArgs({
151
+ args: [...argv],
152
+ options: OPTIONS,
153
+ strict: true,
154
+ allowPositionals: false,
155
+ })
156
+ return { success: true, value: { values, positionals } }
157
+ } catch (error) {
158
+ return { success: false, error: error instanceof Error ? error.message : String(error) }
159
+ }
160
+ }
98
161
 
99
162
  /** Holds the longest cap in whole seconds, equal to the limit of the sibling launcher. */
100
163
  export const MAX_CAP_SECONDS = 2_147_483
@@ -102,6 +165,9 @@ export const MAX_CAP_SECONDS = 2_147_483
102
165
  /** Holds the digit count of a ticket name, which keeps a directory listing readable in order. */
103
166
  export const SEQUENCE_WIDTH = 12
104
167
 
168
+ /** Holds the byte a light waiter writes to an earlier light ticket that does not hold yet. */
169
+ export const HOLD_BYTE = 'h'
170
+
105
171
  /** Holds the name ending of a stage file. */
106
172
  export const STAGE_SUFFIX = '.stage'
107
173
 
@@ -162,7 +228,178 @@ export const REMOVAL_DELAY_MS = 100
162
228
  export const SNAPSHOT_COMMAND =
163
229
  "Get-CimInstance Win32_Process -Property ProcessId,ParentProcessId,CreationDate | Where-Object { $_.CreationDate } | ForEach-Object { '{0} {1} {2}' -f $_.ProcessId, $_.ParentProcessId, ([DateTimeOffset]$_.CreationDate).ToUnixTimeMilliseconds() }"
164
230
 
165
- /** Describes the complete record a stage file holds and a ticket publishes. */
231
+ /** Holds the name of the file under the root that holds the light lanes' limits. */
232
+ export const LIMITS_FILE = 'limits.json'
233
+
234
+ /** Holds the name of the directory under the root that holds each command's run records. */
235
+ export const HISTORY_DIRECTORY = 'history'
236
+
237
+ /** Holds the name ending of a run record under the history directory. */
238
+ export const OUTCOME_SUFFIX = '.json'
239
+
240
+ /** Holds the digit count of the end time that opens a record's name, which keeps a listing in time order. */
241
+ export const ENDED_WIDTH = 15
242
+
243
+ /** Holds the count of latest records the light reading takes, which is also the count each key keeps. */
244
+ export const RECENT_RUNS = 3
245
+
246
+ /** Holds the pause in milliseconds between two samples of a holder's tree. */
247
+ export const SAMPLE_MS = 1000
248
+
249
+ /** Holds the exit code of a light run its holder ended at a threshold. */
250
+ export const BREACH_CODE = 69
251
+
252
+ /** Holds the exit code of a run whose tree still reads as present at handover. */
253
+ export const HELD_CODE = 70
254
+
255
+ /** Holds the launcher's exit code at the cap. */
256
+ export const CAPPED_CODE = 124
257
+
258
+ /** Lists the words that seed a command heavy: a journey, a study, a capture, a live-service run, and a release chain. */
259
+ export const HEAVY_WORDS: readonly string[] = [
260
+ 'journey',
261
+ 'journeys',
262
+ 'study',
263
+ 'studies',
264
+ 'capture',
265
+ 'captures',
266
+ 'live',
267
+ 'prepublishonly',
268
+ ]
269
+
270
+ /** Lists the package-manager verbs that seed a command heavy: an install, a full suite, and a publish. */
271
+ export const HEAVY_VERBS: readonly string[] = [
272
+ 'ci',
273
+ 'i',
274
+ 'install',
275
+ 'add',
276
+ 'update',
277
+ 'rebuild',
278
+ 'uninstall',
279
+ 'publish',
280
+ 'test',
281
+ 't',
282
+ ]
283
+
284
+ /**
285
+ * Lists the package scripts a seed reads heavy: the full suite, the aggregates that build and run
286
+ * several projects, the pack-and-install suite, the live-service suite, and the benchmark run.
287
+ */
288
+ export const HEAVY_SCRIPTS: readonly string[] = [
289
+ 'test',
290
+ 'test:src',
291
+ 'test:app',
292
+ 'test:distribution',
293
+ 'test:service',
294
+ 'test:bench',
295
+ ]
296
+
297
+ /** Lists the Vitest projects a seed reads heavy: the pack-and-install project and the live-service project. */
298
+ export const HEAVY_PROJECTS: readonly string[] = ['distribution', 'service']
299
+
300
+ /** Matches a browser face's Vitest project, whose whole run a seed reads heavy: `src:browser`, `app:vue`. */
301
+ export const BROWSER_PROJECT = /(?:^|:)(?:browser|vue)$/u
302
+
303
+ /** Matches a dotted flag such as `--outputFile.json`, whose separate value a seed skips. */
304
+ export const DOTTED_FLAG = /^--[^=.]+\.[^=]+$/u
305
+
306
+ /** Lists the package managers whose verbs and scripts a seed reads. */
307
+ export const MANAGERS: readonly string[] = ['npm', 'pnpm', 'yarn', 'bun']
308
+
309
+ /** Lists the tools a seed reads heavy by name: the release chain's step runner. */
310
+ export const HEAVY_TOOLS: readonly string[] = ['steps']
311
+
312
+ /** Lists the Vitest flags that take a separate value, so a seed reads no flag value as a file. */
313
+ export const VITEST_VALUE_FLAGS: readonly string[] = [
314
+ '--config',
315
+ '-c',
316
+ '--project',
317
+ '--reporter',
318
+ '--mode',
319
+ '--root',
320
+ '-r',
321
+ '--dir',
322
+ '--outputFile',
323
+ '--pool',
324
+ '--environment',
325
+ '--shard',
326
+ '--testNamePattern',
327
+ '-t',
328
+ '--bail',
329
+ '--retry',
330
+ '--maxWorkers',
331
+ '--minWorkers',
332
+ '--testTimeout',
333
+ '--hookTimeout',
334
+ '--exclude',
335
+ '--include',
336
+ ]
337
+
338
+ /** Matches a package script that runs a type check: `check`, `typecheck`, `check:<scope>`, or `<tool>:check`. */
339
+ export const CHECK_SCRIPT = /^(?:check|typecheck|type-check)(?::|$)|:check$/u
340
+
341
+ /** Matches a package script that runs one project's suite. */
342
+ export const SCOPED_SCRIPT = /^test:/u
343
+
344
+ /** Matches one sampler row: process id, parent id, creation time in milliseconds, CPU time in 100 ns units, and private bytes. */
345
+ export const GAUGE_PATTERN = /^(\d+) (\d+) (\d+) (\d+) (\d+)$/u
346
+
347
+ /** Holds the PowerShell text that prints one line of rows per sample until its stdin closes. */
348
+ 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)}}`
349
+
350
+ /** Describes the footprint the light lanes add up: average cores, peak private bytes, and peak processes. */
351
+ export interface Usage {
352
+ readonly cores: number
353
+ readonly memory: number
354
+ readonly processes: number
355
+ }
356
+
357
+ /** Describes the per-run threshold of a light run: a footprint and a duration in milliseconds. */
358
+ export interface Threshold extends Usage {
359
+ readonly duration: number
360
+ }
361
+
362
+ /** Describes `limits.json`: the light holders allowed at once, their summed budget, and the per-run threshold. */
363
+ export interface Limits {
364
+ readonly slots: number
365
+ readonly budget: Usage
366
+ readonly threshold: Threshold
367
+ }
368
+
369
+ /** Describes one run's record: its duration and CPU time in milliseconds, its peaks, and its exit code. */
370
+ export interface Outcome {
371
+ readonly duration: number
372
+ readonly cpu: number
373
+ readonly memory: number
374
+ readonly processes: number
375
+ readonly code: number
376
+ }
377
+
378
+ /** Names the lane a command's kind seeds. */
379
+ export type Seed = 'light' | 'heavy'
380
+
381
+ /** Describes one process in a sampler row: a snapshot row with its CPU time and private bytes. */
382
+ export interface Gauge extends Row {
383
+ readonly cpu: number
384
+ readonly memory: number
385
+ }
386
+
387
+ /** Describes what a sampler has read: each member's latest CPU time by id and creation date, and the peaks. */
388
+ export interface Tally {
389
+ readonly cpu: ReadonlyMap<string, number>
390
+ readonly memory: number
391
+ readonly processes: number
392
+ }
393
+
394
+ /** Describes what a measured holder needs: the limits, the command's key, its token, and its light footprint, undefined for a heavy run. */
395
+ export interface Measure {
396
+ readonly limits: Limits
397
+ readonly key: string
398
+ readonly token: string
399
+ readonly light: Usage | undefined
400
+ }
401
+
402
+ /** Describes the complete record a stage file holds and a ticket publishes; `light` holds the footprint a light ticket counts. */
166
403
  export interface Ticket {
167
404
  readonly protocol: number
168
405
  readonly token: string
@@ -172,6 +409,8 @@ export interface Ticket {
172
409
  readonly platform: string
173
410
  readonly cwd: string
174
411
  readonly arrived: string
412
+ readonly light?: Usage
413
+ readonly solo?: boolean
175
414
  }
176
415
 
177
416
  /** Describes one ticket in the queue: its sequence and its record, undefined when unreadable. */
@@ -194,11 +433,19 @@ export interface Row {
194
433
  readonly created: number
195
434
  }
196
435
 
197
- /** Describes what a process does next on the queue. */
436
+ /**
437
+ * Describes what a process does next on the queue; a light waiter that parks on several earlier
438
+ * tickets is `queued`, and `pending` names the earlier light tickets that did not hold yet.
439
+ */
198
440
  export type Turn =
199
441
  | { readonly state: 'holder' }
200
442
  | { readonly state: 'staged'; readonly name: string }
201
443
  | { readonly state: 'behind'; readonly entry: Entry }
444
+ | {
445
+ readonly state: 'queued'
446
+ readonly entries: readonly Entry[]
447
+ readonly pending: readonly number[]
448
+ }
202
449
  | { readonly state: 'refused'; readonly reason: string }
203
450
 
204
451
  /** Describes what a sweep confirmed: whether the tree reads as gone, and the members it left. */
@@ -207,15 +454,18 @@ export interface Sweep {
207
454
  readonly members: readonly number[]
208
455
  }
209
456
 
210
- /** Describes one ticket as `--status` reports it. */
457
+ /** Describes one ticket as `--status` reports it; `holding` marks a live ticket with a run record. */
211
458
  export interface StatusRow {
212
459
  readonly sequence: number
213
460
  readonly label: string | undefined
214
461
  readonly pid: number | undefined
215
462
  readonly state: 'live' | 'dead' | 'unread'
463
+ readonly light: boolean
464
+ readonly solo: boolean
465
+ readonly holding: boolean
216
466
  }
217
467
 
218
- /** Describes what `--status` reads: every ticket in arrival order and the holder among them. */
468
+ /** Describes what `--status` reads: every ticket in arrival order and the heavy holder among them. */
219
469
  export interface Status {
220
470
  readonly tickets: readonly StatusRow[]
221
471
  readonly holder: StatusRow | undefined
@@ -228,6 +478,7 @@ export interface LaneOptions {
228
478
  readonly journal: string
229
479
  readonly errors: string
230
480
  readonly cap: number
481
+ readonly solo: boolean
231
482
  readonly command: readonly string[]
232
483
  }
233
484
 
@@ -241,8 +492,10 @@ export interface LaneOptions {
241
492
  */
242
493
  export class Token {
243
494
  readonly #sockets = new Set<Socket>()
495
+ readonly #waiters = new Set<Socket>()
244
496
  readonly #server: Server
245
497
  #published = false
498
+ #holding = false
246
499
 
247
500
  constructor() {
248
501
  this.#server = createServer((socket) => this.#admit(socket))
@@ -255,14 +508,9 @@ export class Token {
255
508
  * @returns A promise that resolves when the endpoint accepts connections, and rejects with the
256
509
  * listen failure.
257
510
  */
258
- listen(endpoint: string): Promise<void> {
259
- return new Promise((resolve, reject) => {
260
- this.#server.once('error', reject)
261
- this.#server.listen(endpoint, () => {
262
- this.#server.removeListener('error', reject)
263
- resolve()
264
- })
265
- })
511
+ async listen(endpoint: string): Promise<void> {
512
+ this.#server.listen(endpoint)
513
+ await once(this.#server, 'listening')
266
514
  }
267
515
 
268
516
  /** Marks the stage as ended and closes every accepted connection, which wakes each waiter. */
@@ -271,98 +519,48 @@ export class Token {
271
519
  for (const socket of this.#sockets) socket.destroy()
272
520
  }
273
521
 
522
+ /** Marks the process as a holder and closes every connection that waits for it to hold. */
523
+ hold(): void {
524
+ this.#holding = true
525
+ for (const socket of this.#waiters) socket.destroy()
526
+ }
527
+
528
+ /** Marks the process as leaving, so a hold waiter that arrives later parks until the process ends. */
529
+ leave(): void {
530
+ this.#holding = false
531
+ }
532
+
274
533
  /**
275
534
  * Closes the endpoint and every connection.
276
535
  *
277
536
  * @returns A promise that resolves when the server has closed.
278
537
  */
279
- destroy(): Promise<void> {
538
+ async destroy(): Promise<void> {
280
539
  for (const socket of this.#sockets) socket.destroy()
281
- return new Promise((resolve) => {
282
- this.#server.close(() => resolve())
283
- })
540
+ this.#server.close()
541
+ await once(this.#server, 'close')
284
542
  }
285
543
 
286
- // A byte after the publish comes from a stage waiter whose connection the allocation left unaccepted.
544
+ // Another byte after the publish comes from a stage waiter whose connection the allocation left unaccepted.
287
545
  #admit(socket: Socket): void {
288
546
  this.#sockets.add(socket)
289
547
  socket.on('error', () => undefined)
290
- socket.on('close', () => this.#sockets.delete(socket))
291
- socket.on('data', () => {
292
- if (this.#published) socket.destroy()
548
+ socket.on('close', () => {
549
+ this.#sockets.delete(socket)
550
+ this.#waiters.delete(socket)
551
+ })
552
+ socket.on('data', (data: Buffer) => {
553
+ if (!data.includes(HOLD_BYTE)) {
554
+ if (this.#published) socket.destroy()
555
+ } else if (this.#holding) {
556
+ socket.destroy()
557
+ } else {
558
+ this.#waiters.add(socket)
559
+ }
293
560
  })
294
561
  }
295
562
  }
296
563
 
297
- /**
298
- * Reads the value that follows a flag.
299
- *
300
- * @remarks
301
- * The first occurrence of a flag wins, a following value that opens with `--` is a missing value,
302
- * and the `--flag=value` form is not read.
303
- *
304
- * @param argv - The arguments before the bare `--`.
305
- * @param name - The flag, such as `--label`.
306
- * @returns The value after the flag, or undefined when the flag is absent, last, or followed by
307
- * another flag.
308
- */
309
- export function readOption(argv: readonly string[], name: string): string | undefined {
310
- const index = argv.indexOf(name)
311
- const value = index === -1 ? undefined : argv[index + 1]
312
- return value === undefined || value.startsWith('--') ? undefined : value
313
- }
314
-
315
- /**
316
- * Names the value flags a caller gave with no value.
317
- *
318
- * @param argv - The arguments before the bare `--`.
319
- * @param names - The flags that take a value.
320
- * @returns Each named flag that appears last or is followed by another flag, in argument order.
321
- */
322
- export function readMissingFlags(
323
- argv: readonly string[],
324
- names: readonly string[],
325
- ): readonly string[] {
326
- return names.filter((name) => argv.includes(name) && readOption(argv, name) === undefined)
327
- }
328
-
329
- /**
330
- * Names the flags a caller gave that the script does not read.
331
- *
332
- * @remarks
333
- * A `--flag=value` argument is unknown, because the script reads no such form. A bare `--` ends the
334
- * scan, so the command after it keeps every argument.
335
- *
336
- * @param argv - The arguments after the script path.
337
- * @param flags - Every flag the script reads, value flags and switches alike.
338
- * @returns Each argument that opens with `--` and is not a read flag, in argument order.
339
- */
340
- export function readUnknownFlags(
341
- argv: readonly string[],
342
- flags: readonly string[],
343
- ): readonly string[] {
344
- const end = argv.indexOf('--')
345
- return (end === -1 ? argv : argv.slice(0, end)).filter(
346
- (argument) => argument.startsWith('--') && !flags.includes(argument),
347
- )
348
- }
349
-
350
- /**
351
- * Reads the arguments that are neither a flag nor the value of a value flag.
352
- *
353
- * @param argv - The arguments before the bare `--`.
354
- * @param valueFlags - The flags that take a value.
355
- * @returns The positional arguments in order.
356
- */
357
- export function readPositionals(
358
- argv: readonly string[],
359
- valueFlags: readonly string[],
360
- ): readonly string[] {
361
- return argv.filter(
362
- (argument, index) => !argument.startsWith('--') && !valueFlags.includes(argv[index - 1] ?? ''),
363
- )
364
- }
365
-
366
564
  /**
367
565
  * Quotes an untrusted text for a diagnostic, JSON-encoded and cut to a bounded length.
368
566
  *
@@ -428,23 +626,14 @@ export function renderEndpoint(root: string, token: string): string {
428
626
  }
429
627
 
430
628
  /**
431
- * Renders the name of a ticket.
432
- *
433
- * @param sequence - The ticket's sequence.
434
- * @returns The file name, at a fixed width.
435
- */
436
- export function renderTicketName(sequence: number): string {
437
- return `${String(sequence).padStart(SEQUENCE_WIDTH, '0')}${TICKET_SUFFIX}`
438
- }
439
-
440
- /**
441
- * Renders the name of a run record.
629
+ * Renders the name of a ticket or a run record.
442
630
  *
443
631
  * @param sequence - The ticket's sequence.
632
+ * @param suffix - The name ending: `TICKET_SUFFIX` for a ticket, `RUN_SUFFIX` for its run record.
444
633
  * @returns The file name, at a fixed width.
445
634
  */
446
- export function renderRunName(sequence: number): string {
447
- return `${String(sequence).padStart(SEQUENCE_WIDTH, '0')}${RUN_SUFFIX}`
635
+ export function renderName(sequence: number, suffix: string): string {
636
+ return `${String(sequence).padStart(SEQUENCE_WIDTH, '0')}${suffix}`
448
637
  }
449
638
 
450
639
  /**
@@ -479,7 +668,8 @@ export function readSequences(names: readonly string[]): readonly number[] {
479
668
  * Checks whether a value is a ticket record.
480
669
  *
481
670
  * @param value - The parsed JSON value.
482
- * @returns True when every field has its type and the token has the token's form; false otherwise.
671
+ * @returns True when every field has its type, each present optional field too, and the token has
672
+ * the token's form; false otherwise.
483
673
  */
484
674
  export function isTicket(value: unknown): value is Ticket {
485
675
  return (
@@ -501,7 +691,87 @@ export function isTicket(value: unknown): value is Ticket {
501
691
  'cwd' in value &&
502
692
  typeof value.cwd === 'string' &&
503
693
  'arrived' in value &&
504
- typeof value.arrived === 'string'
694
+ typeof value.arrived === 'string' &&
695
+ (!('light' in value) || isUsage(value.light)) &&
696
+ (!('solo' in value) || typeof value.solo === 'boolean')
697
+ )
698
+ }
699
+
700
+ /**
701
+ * Checks whether a value is a footprint.
702
+ *
703
+ * @param value - The parsed JSON value.
704
+ * @returns True when `cores`, `memory`, and `processes` are finite numbers of at least 0; false
705
+ * otherwise.
706
+ */
707
+ export function isUsage(value: unknown): value is Usage {
708
+ return (
709
+ typeof value === 'object' &&
710
+ value !== null &&
711
+ 'cores' in value &&
712
+ isAmount(value.cores) &&
713
+ 'memory' in value &&
714
+ isAmount(value.memory) &&
715
+ 'processes' in value &&
716
+ isAmount(value.processes)
717
+ )
718
+ }
719
+
720
+ /**
721
+ * Checks whether a value is a finite number of at least 0.
722
+ *
723
+ * @param value - The value.
724
+ * @returns True for a finite number of at least 0; false otherwise.
725
+ */
726
+ export function isAmount(value: unknown): value is number {
727
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0
728
+ }
729
+
730
+ /**
731
+ * Checks whether a value is the content of `limits.json`.
732
+ *
733
+ * @param value - The parsed JSON value.
734
+ * @returns True when `slots` is an integer of at least 1, `budget` is a footprint, and `threshold` is
735
+ * a footprint with a `duration`; false otherwise.
736
+ */
737
+ export function isLimits(value: unknown): value is Limits {
738
+ return (
739
+ typeof value === 'object' &&
740
+ value !== null &&
741
+ 'slots' in value &&
742
+ Number.isSafeInteger(value.slots) &&
743
+ typeof value.slots === 'number' &&
744
+ value.slots >= 1 &&
745
+ 'budget' in value &&
746
+ isUsage(value.budget) &&
747
+ 'threshold' in value &&
748
+ isUsage(value.threshold) &&
749
+ 'duration' in value.threshold &&
750
+ isAmount(value.threshold.duration)
751
+ )
752
+ }
753
+
754
+ /**
755
+ * Checks whether a value is a run's record.
756
+ *
757
+ * @param value - The parsed JSON value.
758
+ * @returns True when the measures are finite numbers of at least 0 and `code` is an integer; false
759
+ * otherwise.
760
+ */
761
+ export function isOutcome(value: unknown): value is Outcome {
762
+ return (
763
+ typeof value === 'object' &&
764
+ value !== null &&
765
+ 'duration' in value &&
766
+ isAmount(value.duration) &&
767
+ 'cpu' in value &&
768
+ isAmount(value.cpu) &&
769
+ 'memory' in value &&
770
+ isAmount(value.memory) &&
771
+ 'processes' in value &&
772
+ isAmount(value.processes) &&
773
+ 'code' in value &&
774
+ Number.isSafeInteger(value.code)
505
775
  )
506
776
  }
507
777
 
@@ -547,7 +817,7 @@ export function parseText(text: string): unknown {
547
817
  */
548
818
  export function readEntry(root: string, sequence: number): readonly Entry[] {
549
819
  try {
550
- const parsed = parseText(readFileSync(join(root, renderTicketName(sequence)), 'utf8'))
820
+ const parsed = parseText(readFileSync(join(root, renderName(sequence, TICKET_SUFFIX)), 'utf8'))
551
821
  return [{ sequence, ticket: isTicket(parsed) ? parsed : undefined }]
552
822
  } catch (error) {
553
823
  return readCode(error) === 'ENOENT' ? [] : [{ sequence, ticket: undefined }]
@@ -585,7 +855,7 @@ export function readQueue(root: string): readonly Entry[] {
585
855
  */
586
856
  export function readRun(root: string, sequence: number): Run | 'absent' | 'unread' {
587
857
  try {
588
- const parsed = parseText(readFileSync(join(root, renderRunName(sequence)), 'utf8'))
858
+ const parsed = parseText(readFileSync(join(root, renderName(sequence, RUN_SUFFIX)), 'utf8'))
589
859
  return isRun(parsed)
590
860
  ? {
591
861
  started: parsed.started,
@@ -606,7 +876,7 @@ export function readRun(root: string, sequence: number): Run | 'absent' | 'unrea
606
876
  * @param run - The record.
607
877
  */
608
878
  export function writeRun(root: string, sequence: number, run: Run): void {
609
- writeFileSync(join(root, renderRunName(sequence)), JSON.stringify(run))
879
+ writeFileSync(join(root, renderName(sequence, RUN_SUFFIX)), JSON.stringify(run))
610
880
  }
611
881
 
612
882
  /**
@@ -623,9 +893,12 @@ export function removeFile(path: string): void {
623
893
  *
624
894
  * @param token - The process's token.
625
895
  * @param label - The run's label.
626
- * @returns The complete ticket.
896
+ * @param light - The footprint a light ticket counts, or undefined for a heavy ticket.
897
+ * @param solo - If `true`, marks a ticket that waits out every earlier light ticket; if `false`, omits
898
+ * the field.
899
+ * @returns The complete ticket, carrying `light` and `solo` only when they are set.
627
900
  */
628
- export function buildTicket(token: string, label: string): Ticket {
901
+ export function buildTicket(token: string, label: string, light?: Usage, solo = false): Ticket {
629
902
  return {
630
903
  protocol: PROTOCOL,
631
904
  token,
@@ -635,9 +908,347 @@ export function buildTicket(token: string, label: string): Ticket {
635
908
  platform: process.platform,
636
909
  cwd: process.cwd(),
637
910
  arrived: new Date().toISOString(),
911
+ ...(light === undefined ? {} : { light }),
912
+ ...(solo ? { solo } : {}),
638
913
  }
639
914
  }
640
915
 
916
+ /**
917
+ * Reads `limits.json` under the root.
918
+ *
919
+ * @param root - The queue root.
920
+ * @returns The limits; `absent` when the file does not exist; `unread` when it cannot be read as
921
+ * limits.
922
+ */
923
+ export function readLimits(root: string): Limits | 'absent' | 'unread' {
924
+ try {
925
+ const parsed = parseText(readFileSync(join(root, LIMITS_FILE), 'utf8'))
926
+ return isLimits(parsed) ? parsed : 'unread'
927
+ } catch (error) {
928
+ return readCode(error) === 'ENOENT' ? 'absent' : 'unread'
929
+ }
930
+ }
931
+
932
+ /**
933
+ * Renders the key of a command's run records.
934
+ *
935
+ * @param cwd - The real working directory.
936
+ * @param command - The command and its arguments.
937
+ * @returns The hex sha256 of the directory and the arguments.
938
+ */
939
+ export function renderKey(cwd: string, command: readonly string[]): string {
940
+ return createHash('sha256')
941
+ .update(JSON.stringify([cwd, ...command]))
942
+ .digest('hex')
943
+ }
944
+
945
+ /**
946
+ * Renders the name of a run's record.
947
+ *
948
+ * @param ended - When the run ended, in epoch milliseconds.
949
+ * @param token - The run's token, which keeps two records of one key and one millisecond apart.
950
+ * @returns The file name, opening with the end time at a fixed width.
951
+ */
952
+ export function renderOutcomeName(ended: number, token: string): string {
953
+ return `${String(ended).padStart(ENDED_WIDTH, '0')}-${token}${OUTCOME_SUFFIX}`
954
+ }
955
+
956
+ /**
957
+ * Reads the names of a key's records, oldest first.
958
+ *
959
+ * @param root - The queue root.
960
+ * @param key - The command's key.
961
+ * @returns Every record name under the key, sorted by end time.
962
+ */
963
+ export function readOutcomeNames(root: string, key: string): readonly string[] {
964
+ return readNames(join(root, HISTORY_DIRECTORY, key))
965
+ .filter((name) => name.endsWith(OUTCOME_SUFFIX))
966
+ .toSorted()
967
+ }
968
+
969
+ /**
970
+ * Reads a key's latest records.
971
+ *
972
+ * @param root - The queue root.
973
+ * @param key - The command's key.
974
+ * @returns Up to {@link RECENT_RUNS} records, oldest first, each undefined when it cannot be read as
975
+ * a record; a record removed while it is read is skipped.
976
+ */
977
+ export function readOutcomes(root: string, key: string): ReadonlyArray<Outcome | undefined> {
978
+ return readOutcomeNames(root, key)
979
+ .slice(-RECENT_RUNS)
980
+ .flatMap((name) => {
981
+ try {
982
+ const parsed = parseText(readFileSync(join(root, HISTORY_DIRECTORY, key, name), 'utf8'))
983
+ return [isOutcome(parsed) ? parsed : undefined]
984
+ } catch (error) {
985
+ return readCode(error) === 'ENOENT' ? [] : [undefined]
986
+ }
987
+ })
988
+ }
989
+
990
+ /**
991
+ * Writes a run's record once and prunes its key to the latest {@link RECENT_RUNS} records.
992
+ *
993
+ * @param root - The queue root.
994
+ * @param key - The command's key.
995
+ * @param name - The record's name.
996
+ * @param outcome - The record.
997
+ */
998
+ export function writeOutcome(root: string, key: string, name: string, outcome: Outcome): void {
999
+ const directory = join(root, HISTORY_DIRECTORY, key)
1000
+ mkdirSync(directory, { recursive: true })
1001
+ writeFileSync(join(directory, name), JSON.stringify(outcome), { flag: 'wx' })
1002
+ for (const stale of readOutcomeNames(root, key).slice(0, -RECENT_RUNS)) {
1003
+ removeFile(join(directory, stale))
1004
+ }
1005
+ }
1006
+
1007
+ /**
1008
+ * Reads the average cores a run used.
1009
+ *
1010
+ * @param outcome - The run's record.
1011
+ * @returns The CPU time over the duration; 0 for a run of no duration.
1012
+ */
1013
+ export function readCores(outcome: Outcome): number {
1014
+ return outcome.duration > 0 ? outcome.cpu / outcome.duration : 0
1015
+ }
1016
+
1017
+ /**
1018
+ * Checks whether a run's record breaches the per-run threshold.
1019
+ *
1020
+ * @param outcome - The run's record, or undefined when it cannot be read.
1021
+ * @param threshold - The per-run threshold.
1022
+ * @returns True for an unreadable record, a capped run, an exit of 69 or 70, and a measure past the
1023
+ * threshold; false otherwise.
1024
+ */
1025
+ export function isBreach(outcome: Outcome | undefined, threshold: Threshold): boolean {
1026
+ return (
1027
+ outcome === undefined ||
1028
+ outcome.code === CAPPED_CODE ||
1029
+ outcome.code === HELD_CODE ||
1030
+ outcome.code === BREACH_CODE ||
1031
+ outcome.duration > threshold.duration ||
1032
+ readCores(outcome) > threshold.cores ||
1033
+ outcome.memory > threshold.memory ||
1034
+ outcome.processes > threshold.processes
1035
+ )
1036
+ }
1037
+
1038
+ /**
1039
+ * Reads the footprint a light ticket counts from its command's records.
1040
+ *
1041
+ * @param outcomes - The records, none of which breaches.
1042
+ * @returns The largest cores, memory, and process count across the records.
1043
+ */
1044
+ export function measurePeak(outcomes: readonly Outcome[]): Usage {
1045
+ return {
1046
+ cores: Math.max(0, ...outcomes.map(readCores)),
1047
+ memory: Math.max(0, ...outcomes.map((outcome) => outcome.memory)),
1048
+ processes: Math.max(0, ...outcomes.map((outcome) => outcome.processes)),
1049
+ }
1050
+ }
1051
+
1052
+ /**
1053
+ * Reads whether a command runs light, from its seed and its latest records.
1054
+ *
1055
+ * @remarks
1056
+ * A seeded heavy command is heavy whatever its records hold. A seeded light command is light until a
1057
+ * record breaches, and counts the threshold until {@link RECENT_RUNS} records exist. Any other
1058
+ * command is light only when {@link RECENT_RUNS} records exist and none breaches.
1059
+ *
1060
+ * @param seed - The lane the command's kind seeds, or undefined when no kind names it.
1061
+ * @param outcomes - The command's latest records.
1062
+ * @param limits - The limits.
1063
+ * @returns The footprint the ticket counts, or undefined when the command runs heavy.
1064
+ */
1065
+ export function classifyLight(
1066
+ seed: Seed | undefined,
1067
+ outcomes: ReadonlyArray<Outcome | undefined>,
1068
+ limits: Limits,
1069
+ ): Usage | undefined {
1070
+ if (seed === 'heavy') return undefined
1071
+ const clean = outcomes.flatMap((outcome) =>
1072
+ outcome === undefined || isBreach(outcome, limits.threshold) ? [] : [outcome],
1073
+ )
1074
+ if (clean.length < outcomes.length) return undefined
1075
+ if (clean.length >= RECENT_RUNS) return measurePeak(clean)
1076
+ const { cores, memory, processes } = limits.threshold
1077
+ return seed === 'light' ? { cores, memory, processes } : undefined
1078
+ }
1079
+
1080
+ /**
1081
+ * Checks whether light footprints fit the slots and every budget together.
1082
+ *
1083
+ * @param usages - The footprints of the light holders and the arrival.
1084
+ * @param limits - The limits.
1085
+ * @returns True when the count fits `slots` and each summed measure fits its budget; false otherwise.
1086
+ */
1087
+ export function fitsBudget(usages: readonly Usage[], limits: Limits): boolean {
1088
+ const total = usages.reduce(
1089
+ (sum, usage) => ({
1090
+ cores: sum.cores + usage.cores,
1091
+ memory: sum.memory + usage.memory,
1092
+ processes: sum.processes + usage.processes,
1093
+ }),
1094
+ { cores: 0, memory: 0, processes: 0 },
1095
+ )
1096
+ return (
1097
+ usages.length <= limits.slots &&
1098
+ total.cores <= limits.budget.cores &&
1099
+ total.memory <= limits.budget.memory &&
1100
+ total.processes <= limits.budget.processes
1101
+ )
1102
+ }
1103
+
1104
+ /**
1105
+ * Splits a command into the words a seed reads.
1106
+ *
1107
+ * @remarks
1108
+ * An absolute path contributes its base name alone, so a checkout's location never seeds a command.
1109
+ *
1110
+ * @param args - The arguments after the executable.
1111
+ * @returns The lowercase alphanumeric words.
1112
+ */
1113
+ export function readWords(args: readonly string[]): readonly string[] {
1114
+ return args.flatMap((argument) =>
1115
+ (isAbsolute(argument) ? basename(argument) : argument)
1116
+ .toLowerCase()
1117
+ .split(/[^a-z0-9]+/u)
1118
+ .filter((word) => word !== ''),
1119
+ )
1120
+ }
1121
+
1122
+ /**
1123
+ * Reads a tool's name from an executable or script path.
1124
+ *
1125
+ * @param path - The path.
1126
+ * @returns The lowercase base name without its extension, `npm-cli` and `npx-cli` read as `npm` and
1127
+ * `npx`.
1128
+ */
1129
+ export function readToolName(path: string): string {
1130
+ const name = basename(path.replaceAll('\\', '/'))
1131
+ .toLowerCase()
1132
+ .replace(/\.(?:exe|cmd|bat|ps1|js|mjs|cjs|ts|mts|cts)$/u, '')
1133
+ return name.replace(/-cli$/u, '')
1134
+ }
1135
+
1136
+ /**
1137
+ * Reads the tool a command runs and the tool's arguments, past Node and `npx`.
1138
+ *
1139
+ * @param command - The command and its arguments.
1140
+ * @returns The tool's name followed by its arguments; empty for inline Node code or no script.
1141
+ */
1142
+ export function readTool(command: readonly string[]): readonly string[] {
1143
+ const [executable, ...rest] = command
1144
+ if (executable === undefined) return []
1145
+ const name = readToolName(executable)
1146
+ if (name === 'node') {
1147
+ const script = rest.findIndex((argument) => !argument.startsWith('-'))
1148
+ const flags = script === -1 ? rest : rest.slice(0, script)
1149
+ if (script === -1 || flags.some((flag) => ['-e', '--eval', '-p', '--print'].includes(flag))) {
1150
+ return []
1151
+ }
1152
+ return readTool(rest.slice(script))
1153
+ }
1154
+ if (name === 'npx') {
1155
+ const tool = rest.findIndex((argument) => !argument.startsWith('-'))
1156
+ return tool === -1 ? [] : readTool(rest.slice(tool))
1157
+ }
1158
+ return [name, ...rest]
1159
+ }
1160
+
1161
+ /**
1162
+ * Reads the positional arguments of a command, skipping each value of a value-taking flag.
1163
+ *
1164
+ * @param args - The arguments.
1165
+ * @param valueFlags - The flags that take a separate value.
1166
+ * @returns The arguments that are neither a flag nor the value of a listed or dotted flag.
1167
+ */
1168
+ export function readOperands(
1169
+ args: readonly string[],
1170
+ valueFlags: readonly string[],
1171
+ ): readonly string[] {
1172
+ return args.filter(
1173
+ (argument, index) =>
1174
+ !argument.startsWith('-') &&
1175
+ !valueFlags.includes(args[index - 1] ?? '') &&
1176
+ !DOTTED_FLAG.test(args[index - 1] ?? ''),
1177
+ )
1178
+ }
1179
+
1180
+ /**
1181
+ * Reads the lane a package script's name seeds.
1182
+ *
1183
+ * @param name - The script's name.
1184
+ * @returns `heavy` for a script {@link HEAVY_SCRIPTS} names, `light` for a type, format, or lint
1185
+ * check and any other `test:` suite, and undefined for any other script.
1186
+ */
1187
+ export function readScriptSeed(name: string): Seed | undefined {
1188
+ if (HEAVY_SCRIPTS.includes(name)) return 'heavy'
1189
+ return CHECK_SCRIPT.test(name) || SCOPED_SCRIPT.test(name) ? 'light' : undefined
1190
+ }
1191
+
1192
+ /**
1193
+ * Reads the lane a Vitest command seeds.
1194
+ *
1195
+ * @param args - The arguments after `vitest`.
1196
+ * @returns `heavy` for a run of every project, of several projects, of a project
1197
+ * {@link HEAVY_PROJECTS} names, or of a whole browser project; `light` for a run of named test files
1198
+ * or one other project; undefined for any other run or mode.
1199
+ */
1200
+ export function readVitestSeed(args: readonly string[]): Seed | undefined {
1201
+ const [mode, ...operands] = readOperands(args, VITEST_VALUE_FLAGS)
1202
+ if (mode !== 'run') return undefined
1203
+ const projects = args.flatMap((argument, index) => {
1204
+ if (argument.startsWith('--project=')) return [argument.slice('--project='.length)]
1205
+ return args[index - 1] === '--project' ? [argument] : []
1206
+ })
1207
+ if (
1208
+ projects.length > 1 ||
1209
+ projects.some((project) => project.includes('*') || HEAVY_PROJECTS.includes(project))
1210
+ ) {
1211
+ return 'heavy'
1212
+ }
1213
+ const files = operands.filter((operand) => /\.(?:test|spec)\./u.test(operand))
1214
+ if (files.length === 0 && projects.some((project) => BROWSER_PROJECT.test(project)))
1215
+ return 'heavy'
1216
+ if (files.length > 0 || projects.length === 1) return 'light'
1217
+ return projects.length === 0 && operands.length === 0 ? 'heavy' : undefined
1218
+ }
1219
+
1220
+ /**
1221
+ * Reads the lane a command's kind seeds.
1222
+ *
1223
+ * @remarks
1224
+ * Heavy wins: a word that names a journey, a study, a capture, a live-service run, or the release
1225
+ * chain seeds heavy wherever it appears, before any light kind is read.
1226
+ *
1227
+ * @param command - The command and its arguments.
1228
+ * @returns The seeded lane, or undefined when no kind names the command.
1229
+ */
1230
+ export function readSeed(command: readonly string[]): Seed | undefined {
1231
+ if (readWords(command.slice(1)).some((word) => HEAVY_WORDS.includes(word))) return 'heavy'
1232
+ const [tool, ...args] = readTool(command)
1233
+ if (tool === undefined) return undefined
1234
+ if (HEAVY_TOOLS.includes(tool)) return 'heavy'
1235
+ if (MANAGERS.includes(tool)) {
1236
+ const [verb, script] = readOperands(args, [])
1237
+ if (verb === undefined) return undefined
1238
+ if (HEAVY_VERBS.includes(verb)) return 'heavy'
1239
+ return (verb === 'run' || verb === 'run-script') && script !== undefined
1240
+ ? readScriptSeed(script)
1241
+ : undefined
1242
+ }
1243
+ if (tool === 'vitest') return readVitestSeed(args)
1244
+ if (tool === 'oxfmt' || tool === 'prettier') return args.includes('--check') ? 'light' : undefined
1245
+ if (tool === 'oxlint' || tool === 'eslint') {
1246
+ return args.some((argument) => argument.startsWith('--fix')) ? undefined : 'light'
1247
+ }
1248
+ if (tool === 'tsc' || tool === 'vue-tsc') return args.includes('--noEmit') ? 'light' : undefined
1249
+ return undefined
1250
+ }
1251
+
641
1252
  /**
642
1253
  * Writes the complete ticket to the stage file, which also marks this process as choosing.
643
1254
  *
@@ -679,7 +1290,10 @@ export function tryLink(from: string, to: string): boolean {
679
1290
  */
680
1291
  export function linkStage(root: string, token: string): number {
681
1292
  const sequence = Math.max(0, ...readSequences(readNames(root))) + 1
682
- return tryLink(join(root, `${token}${STAGE_SUFFIX}`), join(root, renderTicketName(sequence)))
1293
+ return tryLink(
1294
+ join(root, `${token}${STAGE_SUFFIX}`),
1295
+ join(root, renderName(sequence, TICKET_SUFFIX)),
1296
+ )
683
1297
  ? sequence
684
1298
  : linkStage(root, token)
685
1299
  }
@@ -695,9 +1309,11 @@ export function linkStage(root: string, token: string): number {
695
1309
  * @param root - The queue root.
696
1310
  * @param sequence - This process's sequence.
697
1311
  * @param token - This process's token.
698
- * @returns The holder state, the stage file to wait on, the nearest earlier ticket, or a refusal.
1312
+ * @param limits - The limits this process read at arrival, which a light ticket's admission needs.
1313
+ * @returns The holder state, the stage file to wait on, the earlier ticket or tickets to wait on, or
1314
+ * a refusal.
699
1315
  */
700
- export function decideTurn(root: string, sequence: number, token: string): Turn {
1316
+ export function decideTurn(root: string, sequence: number, token: string, limits?: Limits): Turn {
701
1317
  const stage = readNames(root).find(
702
1318
  (name) => name.endsWith(STAGE_SUFFIX) && name !== `${token}${STAGE_SUFFIX}`,
703
1319
  )
@@ -705,12 +1321,72 @@ export function decideTurn(root: string, sequence: number, token: string): Turn
705
1321
  const entries = readQueue(root)
706
1322
  const position = entries.findIndex((entry) => entry.sequence === sequence)
707
1323
  if (position === -1) {
708
- return { state: 'refused', reason: `ticket ${renderTicketName(sequence)} is gone` }
1324
+ return { state: 'refused', reason: `ticket ${renderName(sequence, TICKET_SUFFIX)} is gone` }
709
1325
  }
710
- const lower = entries[position - 1]
1326
+ const own = entries[position]?.ticket
1327
+ const earlier = entries.slice(0, position)
1328
+ return own?.light === undefined || limits === undefined
1329
+ ? decideHeavy(earlier, own?.solo === true)
1330
+ : decideLight(root, earlier, own.light, limits)
1331
+ }
1332
+
1333
+ /**
1334
+ * Decides what a heavy ticket does next.
1335
+ *
1336
+ * @remarks
1337
+ * A heavy ticket waits on the nearest earlier ticket that is not light, an unreadable one included. A
1338
+ * `--solo` ticket waits on the nearest earlier ticket of either lane, so it holds with no light
1339
+ * holder beside it.
1340
+ *
1341
+ * @param earlier - The tickets before this one, in arrival order.
1342
+ * @param solo - If `true`, waits on light tickets too; if `false`, passes them.
1343
+ * @returns The holder state or the ticket to wait on.
1344
+ */
1345
+ export function decideHeavy(earlier: readonly Entry[], solo: boolean): Turn {
1346
+ const lower = earlier.findLast((entry) => solo || entry.ticket?.light === undefined)
711
1347
  return lower === undefined ? { state: 'holder' } : { state: 'behind', entry: lower }
712
1348
  }
713
1349
 
1350
+ /**
1351
+ * Decides what a light ticket does next.
1352
+ *
1353
+ * @remarks
1354
+ * A light ticket holds when every earlier light ticket holds, no earlier `--solo` ticket remains, and
1355
+ * the earlier light footprints with its own fit the limits; the earliest light ticket always fits.
1356
+ * The rule reads only earlier tickets, which can only leave, so an admission is never revoked. An
1357
+ * earlier ticket this process cannot read is waited on alone, which refuses.
1358
+ *
1359
+ * @param root - The queue root.
1360
+ * @param earlier - The tickets before this one, in arrival order.
1361
+ * @param light - This ticket's footprint.
1362
+ * @param limits - The limits.
1363
+ * @returns The holder state, the unreadable ticket to wait on, or every earlier light and `--solo`
1364
+ * ticket to wait on at once, with the light tickets that do not hold yet.
1365
+ */
1366
+ export function decideLight(
1367
+ root: string,
1368
+ earlier: readonly Entry[],
1369
+ light: Usage,
1370
+ limits: Limits,
1371
+ ): Turn {
1372
+ const unread = earlier.find(
1373
+ (entry) => entry.ticket === undefined || describeForeign(entry.ticket) !== undefined,
1374
+ )
1375
+ if (unread !== undefined) return { state: 'behind', entry: unread }
1376
+ const lights = earlier.filter((entry) => entry.ticket?.light !== undefined)
1377
+ const solos = earlier.filter((entry) => entry.ticket?.solo === true)
1378
+ const pending = lights.flatMap((entry) =>
1379
+ readRun(root, entry.sequence) === 'absent' ? [entry.sequence] : [],
1380
+ )
1381
+ const usages = lights.flatMap((entry) =>
1382
+ entry.ticket?.light === undefined ? [] : [entry.ticket.light],
1383
+ )
1384
+ const fits = usages.length === 0 || fitsBudget([...usages, light], limits)
1385
+ return solos.length === 0 && pending.length === 0 && fits
1386
+ ? { state: 'holder' }
1387
+ : { state: 'queued', entries: orderEntries([...lights, ...solos]), pending }
1388
+ }
1389
+
714
1390
  /**
715
1391
  * Connects to an endpoint and parks until the connection closes.
716
1392
  *
@@ -718,15 +1394,25 @@ export function decideTurn(root: string, sequence: number, token: string): Turn
718
1394
  * @param stage - If `true`, writes the one byte a published owner closes the connection on; if
719
1395
  * `false`, writes nothing.
720
1396
  * @param parked - Called when the connection is open and the wait starts.
721
- * @returns The connect failure's code, or undefined after a connection opened and closed.
1397
+ * @param signal - Ends the wait and the connection when it aborts.
1398
+ * @param hold - If `true`, writes the byte a ticket closes the connection on when it holds; if
1399
+ * `false`, waits only for the process to end.
1400
+ * @returns The connect failure's code, or undefined after a connection opened and closed or the
1401
+ * signal aborted.
722
1402
  */
723
1403
  export function parkOn(
724
1404
  endpoint: string,
725
1405
  stage: boolean,
726
1406
  parked: () => void,
1407
+ signal?: AbortSignal,
1408
+ hold = false,
727
1409
  ): Promise<string | undefined> {
728
1410
  return new Promise((resolve) => {
729
1411
  const socket = connect(endpoint)
1412
+ signal?.addEventListener('abort', () => {
1413
+ socket.destroy()
1414
+ resolve(undefined)
1415
+ })
730
1416
  socket.once('error', (error) => resolve(readCode(error)))
731
1417
  socket.once('connect', () => {
732
1418
  socket.removeAllListeners('error')
@@ -734,28 +1420,12 @@ export function parkOn(
734
1420
  socket.once('close', () => resolve(undefined))
735
1421
  socket.resume()
736
1422
  if (stage) socket.write('s')
1423
+ if (hold) socket.write(HOLD_BYTE)
737
1424
  parked()
738
1425
  })
739
1426
  })
740
1427
  }
741
1428
 
742
- /**
743
- * Connects to an endpoint and leaves at once.
744
- *
745
- * @param endpoint - The endpoint.
746
- * @returns The connect failure's code, or undefined when the connection opened.
747
- */
748
- export function probeEndpoint(endpoint: string): Promise<string | undefined> {
749
- return new Promise((resolve) => {
750
- const socket = connect(endpoint)
751
- socket.once('error', (error) => resolve(readCode(error)))
752
- socket.once('connect', () => {
753
- socket.destroy()
754
- resolve(undefined)
755
- })
756
- })
757
- }
758
-
759
1429
  /**
760
1430
  * Checks whether a connect failure means the endpoint's owner is gone.
761
1431
  *
@@ -828,12 +1498,12 @@ export function readSnapshot(): readonly Row[] | undefined {
828
1498
  * @param ceiling - The latest creation date a row of an exited seed can carry.
829
1499
  * @returns The members.
830
1500
  */
831
- export function selectMembers(
832
- rows: readonly Row[],
1501
+ export function selectMembers<T extends Row>(
1502
+ rows: readonly T[],
833
1503
  seeds: readonly number[],
834
1504
  floor: number,
835
1505
  ceiling: number,
836
- ): readonly Row[] {
1506
+ ): readonly T[] {
837
1507
  const roots = seeds.flatMap((seed) => {
838
1508
  const own = rows.find((row) => row.pid === seed)
839
1509
  return own !== undefined && own.created >= floor && own.created <= ceiling
@@ -958,7 +1628,7 @@ export function sweepTree(
958
1628
  */
959
1629
  export function reclaimTicket(root: string, sequence: number, ticket: Ticket): string | undefined {
960
1630
  const run = readRun(root, sequence)
961
- const files = `${renderTicketName(sequence)} and ${renderRunName(sequence)} under ${root}`
1631
+ const files = `${renderName(sequence, TICKET_SUFFIX)} and ${renderName(sequence, RUN_SUFFIX)} under ${root}`
962
1632
  if (run === 'unread' || (run !== 'absent' && run.launcher === undefined)) {
963
1633
  return `the owner of ${quote(ticket.label)} (pid ${String(ticket.pid)}) ended before its tree could be identified; end its tree, then delete ${files}`
964
1634
  }
@@ -967,9 +1637,9 @@ export function reclaimTicket(root: string, sequence: number, ticket: Ticket): s
967
1637
  if (members === undefined || members.length > 0) {
968
1638
  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}`
969
1639
  }
970
- removeFile(join(root, renderRunName(sequence)))
1640
+ removeFile(join(root, renderName(sequence, RUN_SUFFIX)))
971
1641
  }
972
- removeFile(join(root, renderTicketName(sequence)))
1642
+ removeFile(join(root, renderName(sequence, TICKET_SUFFIX)))
973
1643
  removeFile(join(root, `${ticket.token}${SOCKET_SUFFIX}`))
974
1644
  return undefined
975
1645
  }
@@ -1007,7 +1677,7 @@ export async function waitOnTicket(
1007
1677
  entry: Entry,
1008
1678
  announced: string | undefined,
1009
1679
  ): Promise<string | undefined> {
1010
- const name = renderTicketName(entry.sequence)
1680
+ const name = renderName(entry.sequence, TICKET_SUFFIX)
1011
1681
  const ticket = entry.ticket
1012
1682
  if (ticket === undefined) return `ticket ${name} under ${root} cannot be read`
1013
1683
  const foreign = describeForeign(ticket)
@@ -1021,24 +1691,79 @@ export async function waitOnTicket(
1021
1691
  : `the endpoint of ticket ${name} reported ${code}`
1022
1692
  }
1023
1693
 
1694
+ /**
1695
+ * Waits on several earlier tickets at once, until the first leaves or a pending one holds, and
1696
+ * reclaims a ticket whose owner is gone.
1697
+ *
1698
+ * @param root - The queue root.
1699
+ * @param entries - The earlier tickets, each readable and of this host.
1700
+ * @param pending - The sequences of the light tickets among them that did not hold yet, whose hold
1701
+ * also ends the wait.
1702
+ * @param announced - The tokens this process last printed a waiting line for, joined by commas.
1703
+ * @returns The refusal, or undefined when the wait ended.
1704
+ */
1705
+ export async function waitOnTickets(
1706
+ root: string,
1707
+ entries: readonly Entry[],
1708
+ pending: readonly number[],
1709
+ announced: string | undefined,
1710
+ ): Promise<string | undefined> {
1711
+ const tickets = entries.flatMap((entry) =>
1712
+ entry.ticket === undefined ? [] : [{ sequence: entry.sequence, ticket: entry.ticket }],
1713
+ )
1714
+ const key = tickets.map((item) => item.ticket.token).join(',')
1715
+ const controller = new AbortController()
1716
+ const opened = tickets.map(() => Promise.withResolvers<void>())
1717
+ const waits = tickets.map((item, index) =>
1718
+ parkOn(
1719
+ renderEndpoint(root, item.ticket.token),
1720
+ false,
1721
+ () => opened[index]?.resolve(),
1722
+ controller.signal,
1723
+ pending.includes(item.sequence),
1724
+ ).then((code) => ({ ...item, code })),
1725
+ )
1726
+ void Promise.all(opened.map((resolvers) => resolvers.promise)).then(() => {
1727
+ if (announced !== key && !controller.signal.aborted) {
1728
+ console.error(
1729
+ `lane: waiting behind ${tickets.map((item) => quote(item.ticket.label)).join(', ')}`,
1730
+ )
1731
+ }
1732
+ })
1733
+ const first = await Promise.race(waits)
1734
+ controller.abort()
1735
+ if (first.code === undefined) return undefined
1736
+ return isGone(first.code)
1737
+ ? reclaimTicket(root, first.sequence, first.ticket)
1738
+ : `the endpoint of ticket ${renderName(first.sequence, TICKET_SUFFIX)} reported ${first.code}`
1739
+ }
1740
+
1024
1741
  /**
1025
1742
  * Waits for this process's turn, parked on events with no timer.
1026
1743
  *
1027
1744
  * @param root - The queue root.
1028
1745
  * @param sequence - This process's sequence.
1029
1746
  * @param token - This process's token.
1030
- * @param announced - The token this process last printed a waiting line for.
1747
+ * @param limits - The limits this process read at arrival.
1748
+ * @param announced - The token or tokens this process last printed a waiting line for.
1031
1749
  * @returns The refusal, or undefined when this process holds the lane.
1032
1750
  */
1033
1751
  export async function waitForTurn(
1034
1752
  root: string,
1035
1753
  sequence: number,
1036
1754
  token: string,
1755
+ limits: Limits | undefined,
1037
1756
  announced?: string,
1038
1757
  ): Promise<string | undefined> {
1039
- const turn = decideTurn(root, sequence, token)
1758
+ const turn = decideTurn(root, sequence, token, limits)
1040
1759
  if (turn.state === 'holder') return undefined
1041
1760
  if (turn.state === 'refused') return turn.reason
1761
+ if (turn.state === 'queued') {
1762
+ const refusal = await waitOnTickets(root, turn.entries, turn.pending, announced)
1763
+ if (refusal !== undefined) return refusal
1764
+ const key = turn.entries.map((entry) => entry.ticket?.token).join(',')
1765
+ return waitForTurn(root, sequence, token, limits, key)
1766
+ }
1042
1767
  const refusal =
1043
1768
  turn.state === 'staged'
1044
1769
  ? await waitOnStage(root, turn.name)
@@ -1048,6 +1773,7 @@ export async function waitForTurn(
1048
1773
  root,
1049
1774
  sequence,
1050
1775
  token,
1776
+ limits,
1051
1777
  turn.state === 'behind' ? turn.entry.ticket?.token : announced,
1052
1778
  )
1053
1779
  }
@@ -1159,39 +1885,270 @@ export function tryWriteRun(root: string, sequence: number, run: Run): boolean {
1159
1885
  */
1160
1886
  export function releaseTicket(root: string, sequence: number): string | undefined {
1161
1887
  try {
1162
- removeFile(join(root, renderRunName(sequence)))
1163
- removeFile(join(root, renderTicketName(sequence)))
1888
+ removeFile(join(root, renderName(sequence, RUN_SUFFIX)))
1889
+ removeFile(join(root, renderName(sequence, TICKET_SUFFIX)))
1164
1890
  return undefined
1165
1891
  } catch (error) {
1166
1892
  return readCode(error)
1167
1893
  }
1168
1894
  }
1169
1895
 
1896
+ /**
1897
+ * Parses one sampler line.
1898
+ *
1899
+ * @param line - One line of the sampler's stdout, its rows separated by semicolons.
1900
+ * @returns One gauge per row that has the row's form, its CPU time in milliseconds.
1901
+ */
1902
+ export function parseGauges(line: string): readonly Gauge[] {
1903
+ return line.split(';').flatMap((item) => {
1904
+ const match = GAUGE_PATTERN.exec(item.trim())
1905
+ return match === null
1906
+ ? []
1907
+ : [
1908
+ {
1909
+ pid: Number(match[1]),
1910
+ parent: Number(match[2]),
1911
+ created: Number(match[3]),
1912
+ cpu: Number(match[4]) / 10_000,
1913
+ memory: Number(match[5]),
1914
+ },
1915
+ ]
1916
+ })
1917
+ }
1918
+
1919
+ /**
1920
+ * Folds one sample's members into a tally.
1921
+ *
1922
+ * @param tally - The tally so far.
1923
+ * @param members - The members one sample read.
1924
+ * @returns The tally with each member's latest CPU time, keyed by id and creation date, and the
1925
+ * larger of each peak.
1926
+ */
1927
+ export function tallySample(tally: Tally, members: readonly Gauge[]): Tally {
1928
+ return {
1929
+ cpu: new Map([
1930
+ ...tally.cpu,
1931
+ ...members.map((member): [string, number] => {
1932
+ const key = `${String(member.pid)}:${String(member.created)}`
1933
+ return [key, Math.max(member.cpu, tally.cpu.get(key) ?? 0)]
1934
+ }),
1935
+ ]),
1936
+ memory: Math.max(
1937
+ tally.memory,
1938
+ members.reduce((sum, member) => sum + member.memory, 0),
1939
+ ),
1940
+ processes: Math.max(tally.processes, members.length),
1941
+ }
1942
+ }
1943
+
1944
+ /**
1945
+ * Builds a run's record from its tally.
1946
+ *
1947
+ * @param tally - The sampler's tally.
1948
+ * @param duration - The run's duration in milliseconds.
1949
+ * @param code - The lane's exit code for the run.
1950
+ * @returns The record, its CPU time summed across every member the samples read.
1951
+ */
1952
+ export function buildOutcome(tally: Tally, duration: number, code: number): Outcome {
1953
+ return {
1954
+ duration,
1955
+ cpu: [...tally.cpu.values()].reduce((sum, value) => sum + value, 0),
1956
+ memory: tally.memory,
1957
+ processes: tally.processes,
1958
+ code,
1959
+ }
1960
+ }
1961
+
1962
+ /**
1963
+ * Sets a process to below-normal priority, which a Windows child inherits.
1964
+ *
1965
+ * @param pid - The process id.
1966
+ * @returns True when the host took the priority; false when it refused.
1967
+ */
1968
+ export function lowerPriority(pid: number): boolean {
1969
+ try {
1970
+ setPriority(pid, constants.priority.PRIORITY_BELOW_NORMAL)
1971
+ return true
1972
+ } catch {
1973
+ return false
1974
+ }
1975
+ }
1976
+
1977
+ /**
1978
+ * Writes a run's record, leaving a write the host refuses unrecorded.
1979
+ *
1980
+ * @param root - The queue root.
1981
+ * @param key - The command's key.
1982
+ * @param name - The record's name.
1983
+ * @param outcome - The record.
1984
+ * @returns True when the record was written; false otherwise.
1985
+ */
1986
+ export function tryWriteOutcome(
1987
+ root: string,
1988
+ key: string,
1989
+ name: string,
1990
+ outcome: Outcome,
1991
+ ): boolean {
1992
+ try {
1993
+ writeOutcome(root, key, name, outcome)
1994
+ return true
1995
+ } catch {
1996
+ return false
1997
+ }
1998
+ }
1999
+
2000
+ /**
2001
+ * Samples one holder's process tree through one PowerShell child at below-normal priority.
2002
+ *
2003
+ * @remarks
2004
+ * The child exits when its stdin closes, which {@link Sampler.stop} and the end of this process both
2005
+ * do. A threshold, given for a light run, calls the breach handler once, on the first sample whose
2006
+ * memory or process count passes it.
2007
+ */
2008
+ export class Sampler {
2009
+ readonly #child: ChildProcess
2010
+ readonly #closed: Promise<void>
2011
+ readonly #floor: number
2012
+ readonly #threshold: Usage | undefined
2013
+ readonly #breach: () => void
2014
+ #seeds: readonly number[] = []
2015
+ #tally: Tally = { cpu: new Map(), memory: 0, processes: 0 }
2016
+ #breached = false
2017
+
2018
+ /**
2019
+ * Starts the sampler.
2020
+ *
2021
+ * @param floor - The earliest creation date the tree can carry.
2022
+ * @param threshold - The light run's threshold, or undefined for a heavy run.
2023
+ * @param breach - Called once when a sample passes the threshold.
2024
+ */
2025
+ constructor(floor: number, threshold: Usage | undefined, breach: () => void) {
2026
+ this.#floor = floor
2027
+ this.#threshold = threshold
2028
+ this.#breach = breach
2029
+ this.#child = spawn(
2030
+ 'powershell.exe',
2031
+ ['-NoProfile', '-NonInteractive', '-Command', SAMPLER_COMMAND],
2032
+ { stdio: ['pipe', 'pipe', 'ignore'], windowsHide: true },
2033
+ )
2034
+ this.#closed = waitForClose(this.#child).then(() => undefined)
2035
+ this.#child.stdin?.on('error', () => undefined)
2036
+ if (this.#child.pid !== undefined) lowerPriority(this.#child.pid)
2037
+ if (this.#child.stdout !== null) {
2038
+ const lines = createInterface({ input: this.#child.stdout, crlfDelay: Infinity })
2039
+ lines.on('error', () => undefined)
2040
+ lines.on('line', (line) => this.#read(line))
2041
+ }
2042
+ }
2043
+
2044
+ /** Holds the sampler's process id, undefined when it could not start. */
2045
+ get pid(): number | undefined {
2046
+ return this.#child.pid
2047
+ }
2048
+
2049
+ /** Holds what the samples read so far. */
2050
+ get tally(): Tally {
2051
+ return this.#tally
2052
+ }
2053
+
2054
+ /** Holds whether a sample passed the threshold. */
2055
+ get breached(): boolean {
2056
+ return this.#breached
2057
+ }
2058
+
2059
+ /**
2060
+ * Names the ids whose trees later samples read.
2061
+ *
2062
+ * @param seeds - The launcher id and, once known, the command id.
2063
+ */
2064
+ seed(seeds: readonly number[]): void {
2065
+ this.#seeds = seeds
2066
+ }
2067
+
2068
+ /**
2069
+ * Closes the sampler's stdin, which ends it.
2070
+ *
2071
+ * @returns A promise that resolves when the sampler has exited.
2072
+ */
2073
+ stop(): Promise<void> {
2074
+ this.#child.stdin?.end()
2075
+ return this.#closed
2076
+ }
2077
+
2078
+ #read(line: string): void {
2079
+ const members = selectMembers(parseGauges(line), this.#seeds, this.#floor, Date.now())
2080
+ this.#tally = tallySample(this.#tally, members)
2081
+ const threshold = this.#threshold
2082
+ if (
2083
+ threshold === undefined ||
2084
+ this.#breached ||
2085
+ (this.#tally.memory <= threshold.memory && this.#tally.processes <= threshold.processes)
2086
+ ) {
2087
+ return
2088
+ }
2089
+ this.#breached = true
2090
+ this.#breach()
2091
+ }
2092
+ }
2093
+
1170
2094
  /**
1171
2095
  * Runs the command as the holder, reads the tree at handover, and releases.
1172
2096
  *
2097
+ * @remarks
2098
+ * A measured holder samples its tree and writes the run's record before it releases, so the
2099
+ * command's next arrival reads it. A light holder lowers its own priority before the spawn, and ends
2100
+ * its tree when a sample passes the threshold.
2101
+ *
1173
2102
  * @param options - The run.
1174
2103
  * @param launcher - The launcher's path.
1175
2104
  * @param sequence - This process's sequence.
1176
- * @returns The launcher's code; 1 when a signal ended it; 70 when the tree still reads as present or
1177
- * the ticket could not be removed; 75 when the launcher could not start.
2105
+ * @param measure - What a measured holder needs, or undefined when no limits apply.
2106
+ * @param token - This process's endpoint, which holds after the run record exists and leaves before
2107
+ * the run record is removed.
2108
+ * @returns The launcher's code; 1 when a signal ended it; 69 when a light run passed its threshold;
2109
+ * 70 when the tree still reads as present or the ticket could not be removed; 75 when the launcher
2110
+ * could not start, the priority could not be lowered, or the run record could not be written.
1178
2111
  */
1179
2112
  export async function runHolder(
1180
2113
  options: LaneOptions,
1181
2114
  launcher: string,
1182
2115
  sequence: number,
2116
+ measure?: Measure,
2117
+ token?: Token,
1183
2118
  ): Promise<number> {
1184
2119
  const { root } = options
2120
+ if (measure?.light !== undefined && !lowerPriority(process.pid)) {
2121
+ releaseTicket(root, sequence)
2122
+ console.error('lane: the host refused the light run its below-normal priority')
2123
+ return 75
2124
+ }
1185
2125
  const started = Date.now()
1186
- writeRun(root, sequence, { started, launcher: undefined, command: undefined })
2126
+ if (!tryWriteRun(root, sequence, { started, launcher: undefined, command: undefined })) {
2127
+ const refusal = releaseTicket(root, sequence)
2128
+ console.error(
2129
+ `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}`}`,
2130
+ )
2131
+ return refusal === undefined ? 75 : HELD_CODE
2132
+ }
2133
+ token?.hold()
1187
2134
  const child = startLauncher(launcher, options)
1188
2135
  const id = child.pid
1189
2136
  if (id === undefined) {
2137
+ token?.leave()
1190
2138
  releaseTicket(root, sequence)
1191
2139
  console.error(`lane: ${quote(launcher)} could not start`)
1192
2140
  return 75
1193
2141
  }
1194
2142
  tryWriteRun(root, sequence, { started, launcher: id, command: undefined })
2143
+ const sampler =
2144
+ measure === undefined
2145
+ ? undefined
2146
+ : new Sampler(
2147
+ started - CLOCK_ALLOWANCE_MS,
2148
+ measure.light === undefined ? undefined : measure.limits.threshold,
2149
+ () => killMembers([id]),
2150
+ )
2151
+ sampler?.seed([id])
1195
2152
  const unwatch = watchSignals(() => killMembers([id]))
1196
2153
  const closed = waitForClose(child)
1197
2154
  if (child.stdout !== null) {
@@ -1200,29 +2157,78 @@ export async function runHolder(
1200
2157
  lines.on('line', (line) => {
1201
2158
  console.log(line)
1202
2159
  const command = readCommandId(line)
1203
- if (command !== undefined) tryWriteRun(root, sequence, { started, launcher: id, command })
2160
+ if (command === undefined) return
2161
+ tryWriteRun(root, sequence, { started, launcher: id, command })
2162
+ sampler?.seed([id, command])
1204
2163
  })
1205
2164
  }
1206
2165
  const code = await closed
1207
2166
  unwatch()
1208
2167
  const ended = Date.now()
2168
+ const stopped = sampler?.stop()
1209
2169
  const run = readRun(root, sequence)
1210
2170
  const sweep =
1211
2171
  run === 'absent' || run === 'unread'
1212
2172
  ? { gone: false, members: [] }
1213
2173
  : sweepTree(() => readTree(run, ended), killMembers, KILL_BUDGET)
2174
+ const breached = sampler?.breached === true
2175
+ const result = !sweep.gone ? HELD_CODE : breached ? BREACH_CODE : (code ?? 1)
2176
+ if (measure !== undefined && sampler !== undefined) {
2177
+ tryWriteOutcome(
2178
+ root,
2179
+ measure.key,
2180
+ renderOutcomeName(ended, measure.token),
2181
+ buildOutcome(sampler.tally, ended - started, result),
2182
+ )
2183
+ }
1214
2184
  if (!sweep.gone) {
1215
2185
  console.error(
1216
- `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}`,
2186
+ `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}`,
1217
2187
  )
1218
- return 70
2188
+ await stopped
2189
+ return HELD_CODE
1219
2190
  }
2191
+ token?.leave()
1220
2192
  const refusal = releaseTicket(root, sequence)
2193
+ await stopped
1221
2194
  if (refusal !== undefined) {
1222
- console.error(`lane: removing ${renderTicketName(sequence)} reported ${refusal}`)
1223
- return 70
2195
+ console.error(`lane: removing ${renderName(sequence, TICKET_SUFFIX)} reported ${refusal}`)
2196
+ return HELD_CODE
2197
+ }
2198
+ if (breached) {
2199
+ console.error(
2200
+ `lane: ${quote(options.label)} passed the light threshold and was ended; its next arrival runs heavy`,
2201
+ )
1224
2202
  }
1225
- return code ?? 1
2203
+ return result
2204
+ }
2205
+
2206
+ /**
2207
+ * Reads what a run measures at arrival: the limits, the command's key, and its light footprint.
2208
+ *
2209
+ * @remarks
2210
+ * A host other than Windows has no sampler, so it measures nothing and every ticket there is heavy.
2211
+ * A `--solo` run is heavy whatever its command reads.
2212
+ *
2213
+ * @param options - The run.
2214
+ * @param token - This process's token.
2215
+ * @returns What the holder measures, or undefined when `limits.json` is absent or malformed or the
2216
+ * host has no sampler.
2217
+ */
2218
+ export function readMeasure(options: LaneOptions, token: string): Measure | undefined {
2219
+ if (process.platform !== 'win32') return undefined
2220
+ const limits = readLimits(options.root)
2221
+ if (limits === 'unread') {
2222
+ console.error(
2223
+ `lane: ${LIMITS_FILE} under ${options.root} cannot be read as limits; the ticket runs heavy`,
2224
+ )
2225
+ }
2226
+ if (limits === 'absent' || limits === 'unread') return undefined
2227
+ const key = renderKey(realpathSync(process.cwd()), options.command)
2228
+ const light = options.solo
2229
+ ? undefined
2230
+ : classifyLight(readSeed(options.command), readOutcomes(options.root, key), limits)
2231
+ return { limits, key, token, light }
1226
2232
  }
1227
2233
 
1228
2234
  /**
@@ -1243,20 +2249,23 @@ export async function enterLane(
1243
2249
  const { root } = options
1244
2250
  try {
1245
2251
  mkdirSync(root, { recursive: true })
2252
+ const measure = readMeasure(options, tokenId)
1246
2253
  await token.listen(renderEndpoint(root, tokenId))
1247
- writeStage(root, buildTicket(tokenId, options.label))
2254
+ writeStage(root, buildTicket(tokenId, options.label, measure?.light, options.solo))
1248
2255
  const sequence = linkStage(root, tokenId)
1249
2256
  removeFile(join(root, `${tokenId}${STAGE_SUFFIX}`))
1250
2257
  token.publish()
1251
2258
  const unwatch = watchSignals(() => {
1252
- removeFile(join(root, renderTicketName(sequence)))
2259
+ removeFile(join(root, renderName(sequence, TICKET_SUFFIX)))
1253
2260
  removeFile(renderEndpoint(root, tokenId))
1254
2261
  process.exit(75)
1255
2262
  })
1256
- const refusal = await waitForTurn(root, sequence, tokenId)
2263
+ const refusal = await waitForTurn(root, sequence, tokenId, measure?.limits)
1257
2264
  unwatch()
1258
- if (refusal === undefined) return await runHolder(options, launcher, sequence)
1259
- removeFile(join(root, renderTicketName(sequence)))
2265
+ if (refusal === undefined) {
2266
+ return await runHolder(options, launcher, sequence, measure, token)
2267
+ }
2268
+ removeFile(join(root, renderName(sequence, TICKET_SUFFIX)))
1260
2269
  console.error(`lane: ${refusal}`)
1261
2270
  return 75
1262
2271
  } catch (error) {
@@ -1292,47 +2301,71 @@ export async function runLane(options: LaneOptions): Promise<number> {
1292
2301
  */
1293
2302
  export async function readStatusRow(root: string, entry: Entry): Promise<StatusRow> {
1294
2303
  const ticket = entry.ticket
1295
- const fields = { sequence: entry.sequence, label: ticket?.label, pid: ticket?.pid }
2304
+ const fields = {
2305
+ sequence: entry.sequence,
2306
+ label: ticket?.label,
2307
+ pid: ticket?.pid,
2308
+ light: ticket?.light !== undefined,
2309
+ solo: ticket?.solo === true,
2310
+ }
1296
2311
  if (ticket === undefined || describeForeign(ticket) !== undefined) {
1297
- return { ...fields, state: 'unread' }
2312
+ return { ...fields, state: 'unread', holding: false }
2313
+ }
2314
+ const probe = new AbortController()
2315
+ const code = await parkOn(
2316
+ renderEndpoint(root, ticket.token),
2317
+ false,
2318
+ () => probe.abort(),
2319
+ probe.signal,
2320
+ )
2321
+ if (code === undefined) {
2322
+ const holding = existsSync(join(root, renderName(entry.sequence, RUN_SUFFIX)))
2323
+ return { ...fields, state: 'live', holding }
1298
2324
  }
1299
- const code = await probeEndpoint(renderEndpoint(root, ticket.token))
1300
- if (code === undefined) return { ...fields, state: 'live' }
1301
- return { ...fields, state: isGone(code) ? 'dead' : 'unread' }
2325
+ return { ...fields, state: isGone(code) ? 'dead' : 'unread', holding: false }
1302
2326
  }
1303
2327
 
1304
2328
  /**
1305
2329
  * Reads the queue for `--status`.
1306
2330
  *
1307
2331
  * @param root - The queue root.
1308
- * @returns Every ticket in arrival order, and the earliest live ticket with a run record.
2332
+ * @returns Every ticket in arrival order, and the earliest holding ticket that is not light.
1309
2333
  */
1310
2334
  export async function readStatus(root: string): Promise<Status> {
1311
2335
  const tickets = await Promise.all(readQueue(root).map((entry) => readStatusRow(root, entry)))
1312
- return {
1313
- tickets,
1314
- holder: tickets.find(
1315
- (row) => row.state === 'live' && existsSync(join(root, renderRunName(row.sequence))),
1316
- ),
1317
- }
2336
+ return { tickets, holder: tickets.find((row) => row.holding && !row.light) }
1318
2337
  }
1319
2338
 
1320
2339
  /**
1321
2340
  * Renders the queue as text.
1322
2341
  *
1323
2342
  * @param status - What `--status` read.
1324
- * @returns One line for the holder and one per ticket, in arrival order.
2343
+ * @returns One line for the heavy holder, one naming every light holder, and one per ticket with its
2344
+ * lane, in arrival order.
1325
2345
  */
1326
2346
  export function renderStatus(status: Status): string {
2347
+ const lights = status.tickets.filter((row) => row.holding && row.light)
1327
2348
  return [
1328
2349
  `holder: ${status.holder === undefined ? 'none' : quote(status.holder.label ?? 'unread')}`,
2350
+ `light: ${lights.length === 0 ? 'none' : lights.map((row) => quote(row.label ?? 'unread')).join(', ')}`,
1329
2351
  ...status.tickets.map(
1330
2352
  (row) =>
1331
- `${renderTicketName(row.sequence)} ${row.state} ${quote(row.label ?? 'unread')} pid ${String(row.pid)}`,
2353
+ `${renderName(row.sequence, TICKET_SUFFIX)} ${row.state} ${renderLane(row)}${row.holding ? ' holding' : ''} ${quote(row.label ?? 'unread')} pid ${String(row.pid)}`,
1332
2354
  ),
1333
2355
  ].join('\n')
1334
2356
  }
1335
2357
 
2358
+ /**
2359
+ * Names a ticket's lane for `--status`.
2360
+ *
2361
+ * @param row - The ticket's row.
2362
+ * @returns `solo`, `light`, or `heavy`.
2363
+ */
2364
+ export function renderLane(row: StatusRow): string {
2365
+ if (row.solo) return 'solo'
2366
+ return row.light ? 'light' : 'heavy'
2367
+ }
2368
+
1336
2369
  /**
1337
2370
  * Prints the queue, writing nothing under the root.
1338
2371
  *
@@ -1351,36 +2384,54 @@ export async function runStatus(root: string, json: boolean): Promise<number> {
1351
2384
  }
1352
2385
  }
1353
2386
 
2387
+ /**
2388
+ * Parses a cap given in seconds.
2389
+ *
2390
+ * @param text - The value after `--cap`.
2391
+ * @returns The cap, or undefined when the text is absent, not a finite number, not above 0, or past
2392
+ * the launcher's limit.
2393
+ */
2394
+ export function parseCap(text: string | undefined): number | undefined {
2395
+ const cap = Number(text ?? Number.NaN)
2396
+ return Number.isFinite(cap) && cap > 0 && cap <= MAX_CAP_SECONDS ? cap : undefined
2397
+ }
2398
+
1354
2399
  /**
1355
2400
  * Validates a run's arguments.
1356
2401
  *
1357
- * @param own - The arguments before the bare `--`.
2402
+ * @param values - The flag values `parseArgs` read before the bare `--`.
1358
2403
  * @param command - The arguments after the bare `--`.
1359
2404
  * @returns The run, or undefined when a flag or the command is missing or out of range.
1360
2405
  */
1361
2406
  export function readLaneOptions(
1362
- own: readonly string[],
2407
+ values: Arguments['values'],
1363
2408
  command: readonly string[],
1364
2409
  ): LaneOptions | undefined {
1365
- const label = readOption(own, '--label')
1366
- const journal = readOption(own, '--journal')
1367
- const errors = readOption(own, '--errors')
1368
- const cap = Number(readOption(own, '--cap') ?? Number.NaN)
2410
+ const label = typeof values.label === 'string' ? values.label : undefined
2411
+ const journal = typeof values.journal === 'string' ? values.journal : undefined
2412
+ const errors = typeof values.errors === 'string' ? values.errors : undefined
2413
+ const cap = parseCap(typeof values.cap === 'string' ? values.cap : undefined)
1369
2414
  if (
1370
2415
  label === undefined ||
1371
2416
  label === '' ||
1372
2417
  journal === undefined ||
1373
2418
  errors === undefined ||
1374
2419
  journal === errors ||
1375
- !Number.isFinite(cap) ||
1376
- cap <= 0 ||
1377
- cap > MAX_CAP_SECONDS ||
2420
+ cap === undefined ||
1378
2421
  command[0] === undefined ||
1379
2422
  command[0] === ''
1380
2423
  ) {
1381
2424
  return undefined
1382
2425
  }
1383
- return { root: resolveRoot(readOption(own, '--root')), label, journal, errors, cap, command }
2426
+ return {
2427
+ root: resolveRoot(typeof values.root === 'string' ? values.root : undefined),
2428
+ label,
2429
+ journal,
2430
+ errors,
2431
+ cap,
2432
+ solo: values.solo === true,
2433
+ command,
2434
+ }
1384
2435
  }
1385
2436
 
1386
2437
  /**
@@ -1394,31 +2445,29 @@ export function readLaneOptions(
1394
2445
  */
1395
2446
  export async function main(argv: readonly string[]): Promise<number> {
1396
2447
  const end = argv.indexOf('--')
1397
- const own = end === -1 ? argv : argv.slice(0, end)
1398
2448
  const command = end === -1 ? [] : argv.slice(end + 1)
1399
- const unknown = readUnknownFlags(argv, FLAGS)
1400
- if (unknown.length > 0) {
1401
- console.error(`lane: ${unknown.join(', ')} is not a flag this script reads; ${USAGE}`)
1402
- return 64
1403
- }
1404
- const missing = readMissingFlags(own, VALUE_FLAGS)
1405
- if (missing.length > 0) {
1406
- console.error(`lane: ${missing.join(', ')} given with no value; ${USAGE}`)
2449
+ const parsed = parseArguments(end === -1 ? argv : argv.slice(0, end))
2450
+ if (!parsed.success) {
2451
+ console.error(`lane: ${parsed.error}; ${USAGE}`)
1407
2452
  return 64
1408
2453
  }
1409
- if (readPositionals(own, VALUE_FLAGS).length > 0) {
1410
- console.error(USAGE)
1411
- return 64
1412
- }
1413
- const status = own.includes('--status')
1414
- if (status) {
1415
- if (end !== -1 || RUN_FLAGS.some((flag) => own.includes(flag))) {
2454
+ const { values } = parsed.value
2455
+ const root = typeof values.root === 'string' ? values.root : undefined
2456
+ if (values.status === true) {
2457
+ if (end !== -1 || RUN_OPTIONS.some((name) => values[name] !== undefined)) {
1416
2458
  console.error(`lane: --status and a run are two modes; ${USAGE}`)
1417
2459
  return 64
1418
2460
  }
1419
- return runStatus(resolveRoot(readOption(own, '--root')), own.includes('--json'))
2461
+ return runStatus(resolveRoot(root), values.json === true)
2462
+ }
2463
+ const cap = typeof values.cap === 'string' ? values.cap : undefined
2464
+ if (cap !== undefined && parseCap(cap) === undefined) {
2465
+ console.error(
2466
+ `lane: --cap takes a number of seconds above 0 up to ${String(MAX_CAP_SECONDS)}, not ${quote(cap)}; ${USAGE}`,
2467
+ )
2468
+ return 64
1420
2469
  }
1421
- const options = own.includes('--json') ? undefined : readLaneOptions(own, command)
2470
+ const options = values.json === true ? undefined : readLaneOptions(values, command)
1422
2471
  if (options === undefined) {
1423
2472
  console.error(USAGE)
1424
2473
  return 64