@orkestrel/scaffold 0.0.121 → 0.0.123

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 (85) hide show
  1. package/dist/agents/skills/orkestrel-dispatch/scripts/brief.js +57 -9
  2. package/dist/agents/skills/orkestrel-dispatch/scripts/chain.js +22 -2
  3. package/dist/agents/skills/orkestrel-harden/scripts/interleave.js +539 -0
  4. package/dist/agents/skills/orkestrel-parallel/scripts/lane.js +1163 -0
  5. package/dist/agents/skills/orkestrel-publish/scripts/pins.js +5 -5
  6. package/dist/agents/skills/orkestrel-publish/scripts/wave.js +67 -5
  7. package/dist/bin/main.js +8 -6
  8. package/dist/bin/main.js.map +1 -1
  9. package/dist/host/agents/orchestration.md +29 -18
  10. package/dist/host/agents/skills/orkestrel-dispatch/SKILL.md +7 -6
  11. package/dist/host/agents/skills/orkestrel-dispatch/references/launch.md +3 -2
  12. package/dist/host/agents/skills/orkestrel-dispatch/scripts/brief.ts +65 -9
  13. package/dist/host/agents/skills/orkestrel-dispatch/scripts/chain.ts +28 -2
  14. package/dist/host/agents/skills/orkestrel-falsify/SKILL.md +4 -2
  15. package/dist/host/agents/skills/orkestrel-falsify/references/brief.md +3 -2
  16. package/dist/host/agents/skills/orkestrel-harden/SKILL.md +24 -11
  17. package/dist/host/agents/skills/orkestrel-harden/references/bindings.md +18 -12
  18. package/dist/host/agents/skills/orkestrel-harden/references/document.md +1 -0
  19. package/dist/host/agents/skills/orkestrel-harden/references/equivalence.md +2 -1
  20. package/dist/host/agents/skills/orkestrel-harden/references/hardening.md +4 -4
  21. package/dist/host/agents/skills/orkestrel-harden/references/methods.md +642 -0
  22. package/dist/host/agents/skills/orkestrel-harden/scripts/interleave.ts +665 -0
  23. package/dist/host/agents/skills/orkestrel-parallel/SKILL.md +16 -15
  24. package/dist/host/agents/skills/orkestrel-parallel/references/{claude.md → claude-code.md} +13 -13
  25. package/dist/host/agents/skills/orkestrel-parallel/references/t3.md +1 -0
  26. package/dist/host/agents/skills/orkestrel-parallel/scripts/lane.ts +1433 -0
  27. package/dist/host/agents/skills/orkestrel-publish/SKILL.md +12 -9
  28. package/dist/host/agents/skills/orkestrel-publish/references/release.md +2 -2
  29. package/dist/host/agents/skills/orkestrel-publish/references/wave.md +39 -8
  30. package/dist/host/agents/skills/orkestrel-publish/references/window.md +5 -1
  31. package/dist/host/agents/skills/orkestrel-publish/scripts/pins.ts +5 -5
  32. package/dist/host/agents/skills/orkestrel-publish/scripts/wave.ts +86 -7
  33. package/dist/host/claude/AGENTS.md +2 -2
  34. package/dist/host/claude/agents/analyst.md +1 -1
  35. package/dist/host/claude/agents/builder.md +1 -1
  36. package/dist/host/claude/agents/distiller.md +2 -1
  37. package/dist/host/claude/agents/grok.md +2 -2
  38. package/dist/host/claude/agents/opus.md +8 -7
  39. package/dist/host/claude/agents/orkestrel.md +7 -7
  40. package/dist/host/claude/agents/planner.md +3 -3
  41. package/dist/host/claude/agents/reviewer.md +3 -3
  42. package/dist/host/claude/agents/scout.md +2 -1
  43. package/dist/host/claude/agents/verifier.md +2 -2
  44. package/dist/host/claude/rules/campaign.md +15 -13
  45. package/dist/host/claude/rules/documentation.md +1 -0
  46. package/dist/host/claude/rules/names.md +13 -7
  47. package/dist/host/claude/rules/patterns.md +14 -0
  48. package/dist/host/claude/rules/quality.md +4 -1
  49. package/dist/host/claude/rules/tests.md +5 -1
  50. package/dist/host/claude/rules/workspace.md +9 -0
  51. package/dist/host/claude/rules/writing.md +1 -1
  52. package/dist/host/claude/skills/orkestrel-harden/SKILL.md +1 -1
  53. package/dist/host/claude/skills/orkestrel-parallel/SKILL.md +1 -1
  54. package/dist/host/codex/agents/analyst.toml +6 -6
  55. package/dist/host/codex/agents/astra.toml +1 -1
  56. package/dist/host/codex/agents/builder.toml +1 -1
  57. package/dist/host/codex/agents/distiller.toml +4 -2
  58. package/dist/host/codex/agents/grok.toml +5 -2
  59. package/dist/host/codex/agents/opus.toml +6 -4
  60. package/dist/host/codex/agents/planner.toml +6 -5
  61. package/dist/host/codex/agents/reviewer.toml +9 -8
  62. package/dist/host/codex/agents/scout.toml +5 -1
  63. package/dist/host/codex/agents/verifier.toml +8 -3
  64. package/dist/host/dotfiles/gitignore +1 -2
  65. package/dist/host/guides/agent.md +1119 -457
  66. package/dist/host/guides/ndjson.md +81 -21
  67. package/dist/host/guides/ollama.md +22 -18
  68. package/dist/host/guides/probe.md +29 -27
  69. package/dist/host/guides/scaffold.md +42 -15
  70. package/dist/host/guides/study.md +538 -450
  71. package/dist/host/manifest.json +81 -63
  72. package/dist/host/tests/config.test.ts +7 -0
  73. package/dist/src/core/index.cjs +14 -8
  74. package/dist/src/core/index.cjs.map +1 -1
  75. package/dist/src/core/index.d.cts +1 -4
  76. package/dist/src/core/index.d.ts +1 -4
  77. package/dist/src/core/index.js +14 -8
  78. package/dist/src/core/index.js.map +1 -1
  79. package/dist/src/server/index.cjs +87 -8
  80. package/dist/src/server/index.cjs.map +1 -1
  81. package/dist/src/server/index.d.cts +50 -6
  82. package/dist/src/server/index.d.ts +50 -6
  83. package/dist/src/server/index.js +87 -10
  84. package/dist/src/server/index.js.map +1 -1
  85. package/package.json +2 -2
@@ -0,0 +1,1163 @@
1
+ import { spawn, spawnSync } from 'node:child_process';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { existsSync, linkSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync, } from 'node:fs';
4
+ import { connect, createServer } from 'node:net';
5
+ import { hostname, userInfo } from 'node:os';
6
+ import { dirname, extname, join } from 'node:path';
7
+ import { createInterface } from 'node:readline';
8
+ import { fileURLToPath } from 'node:url';
9
+ /** Holds the protocol version a ticket carries, so a process refuses a ticket it cannot read. */
10
+ export const PROTOCOL = 1;
11
+ /** Lists the flags that take a value. */
12
+ export const VALUE_FLAGS = [
13
+ '--label',
14
+ '--journal',
15
+ '--errors',
16
+ '--cap',
17
+ '--root',
18
+ ];
19
+ /** Lists the flags only a run reads, which `--status` refuses. */
20
+ export const RUN_FLAGS = ['--label', '--journal', '--errors', '--cap'];
21
+ /** Lists every flag the script reads, value flags and switches alike. */
22
+ export const FLAGS = [...VALUE_FLAGS, '--status', '--json'];
23
+ /** Holds the usage line printed on a usage refusal. */
24
+ export const USAGE = 'usage: lane.ts --label NAME --journal PATH --errors PATH --cap SECONDS [--root DIR] -- COMMAND [ARGS...] | lane.ts --status [--root DIR] [--json]; the journal and the errors file differ, and the cap is a number of seconds above 0 up to 2147483';
25
+ /** Holds the longest cap in whole seconds, equal to the limit of the sibling launcher. */
26
+ export const MAX_CAP_SECONDS = 2_147_483;
27
+ /** Holds the digit count of a ticket name, which keeps a directory listing readable in order. */
28
+ export const SEQUENCE_WIDTH = 12;
29
+ /** Holds the name ending of a stage file. */
30
+ export const STAGE_SUFFIX = '.stage';
31
+ /** Holds the name ending of a ticket. */
32
+ export const TICKET_SUFFIX = '.ticket';
33
+ /** Holds the name ending of a run record. */
34
+ export const RUN_SUFFIX = '.run';
35
+ /** Holds the name ending of a token's socket file on a host without named pipes. */
36
+ export const SOCKET_SUFFIX = '.sock';
37
+ /** Matches a token, which every endpoint name and stage file name is built from. */
38
+ export const TOKEN_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;
39
+ /** Matches a ticket name and captures its sequence. */
40
+ export const TICKET_PATTERN = /^(\d+)\.ticket$/u;
41
+ /** Matches one snapshot row: process id, parent id, and creation time in milliseconds. */
42
+ export const ROW_PATTERN = /^(\d+) (\d+) (\d+)$/u;
43
+ /** Lists the signals that interrupt a lane on a host that delivers them. */
44
+ export const STOP_SIGNALS = ['SIGINT', 'SIGTERM', 'SIGHUP'];
45
+ /**
46
+ * Holds the clock allowance in milliseconds between `Date.now` and a process's creation date.
47
+ *
48
+ * @remarks
49
+ * The allowance is one default clock tick of 15.625 ms, rounded up, in case the kernel stamps from
50
+ * the tick.
51
+ */
52
+ export const CLOCK_ALLOWANCE_MS = 16;
53
+ /**
54
+ * Holds the kill attempts the handover reading makes before it stays held.
55
+ *
56
+ * @remarks
57
+ * Each attempt on Windows is a synchronous `taskkill` per member and a process snapshot. A member
58
+ * that outlives this many forced kills is a defect a person reads rather than a wait the queue absorbs.
59
+ */
60
+ export const KILL_BUDGET = 5;
61
+ /** Holds the pause in milliseconds after a group signal, because no event reports a group's end. */
62
+ export const KILL_PAUSE_MS = 200;
63
+ /**
64
+ * Holds the removal retries, each `rmSync` delay growing by {@link REMOVAL_DELAY_MS}.
65
+ *
66
+ * @remarks
67
+ * The retries outlast a scanner holding a file.
68
+ */
69
+ export const REMOVAL_RETRIES = 10;
70
+ /** Holds the base delay in milliseconds between removal retries. */
71
+ export const REMOVAL_DELAY_MS = 100;
72
+ /** Holds the PowerShell text that prints one row per process with a creation date. */
73
+ export const SNAPSHOT_COMMAND = "Get-CimInstance Win32_Process -Property ProcessId,ParentProcessId,CreationDate | Where-Object { $_.CreationDate } | ForEach-Object { '{0} {1} {2}' -f $_.ProcessId, $_.ParentProcessId, ([DateTimeOffset]$_.CreationDate).ToUnixTimeMilliseconds() }";
74
+ /**
75
+ * Holds a process's endpoint, whose existence is the process's liveness.
76
+ *
77
+ * @remarks
78
+ * The host closes the endpoint however the process ends. The server sends nothing. A stage waiter
79
+ * writes one byte, and a published owner closes that connection on reading it; the connection of a
80
+ * ticket waiter stays open until the process ends.
81
+ */
82
+ export class Token {
83
+ #sockets = new Set();
84
+ #server;
85
+ #published = false;
86
+ constructor() {
87
+ this.#server = createServer((socket) => this.#admit(socket));
88
+ }
89
+ /**
90
+ * Starts listening.
91
+ *
92
+ * @param endpoint - The endpoint to listen on.
93
+ * @returns A promise that resolves when the endpoint accepts connections, and rejects with the
94
+ * listen failure.
95
+ */
96
+ listen(endpoint) {
97
+ return new Promise((resolve, reject) => {
98
+ this.#server.once('error', reject);
99
+ this.#server.listen(endpoint, () => {
100
+ this.#server.removeListener('error', reject);
101
+ resolve();
102
+ });
103
+ });
104
+ }
105
+ /** Marks the stage as ended and closes every accepted connection, which wakes each waiter. */
106
+ publish() {
107
+ this.#published = true;
108
+ for (const socket of this.#sockets)
109
+ socket.destroy();
110
+ }
111
+ /**
112
+ * Closes the endpoint and every connection.
113
+ *
114
+ * @returns A promise that resolves when the server has closed.
115
+ */
116
+ destroy() {
117
+ for (const socket of this.#sockets)
118
+ socket.destroy();
119
+ return new Promise((resolve) => {
120
+ this.#server.close(() => resolve());
121
+ });
122
+ }
123
+ // A byte after the publish comes from a stage waiter whose connection the allocation left unaccepted.
124
+ #admit(socket) {
125
+ this.#sockets.add(socket);
126
+ socket.on('error', () => undefined);
127
+ socket.on('close', () => this.#sockets.delete(socket));
128
+ socket.on('data', () => {
129
+ if (this.#published)
130
+ socket.destroy();
131
+ });
132
+ }
133
+ }
134
+ /**
135
+ * Reads the value that follows a flag.
136
+ *
137
+ * @remarks
138
+ * The first occurrence of a flag wins, a following value that opens with `--` is a missing value,
139
+ * and the `--flag=value` form is not read.
140
+ *
141
+ * @param argv - The arguments before the bare `--`.
142
+ * @param name - The flag, such as `--label`.
143
+ * @returns The value after the flag, or undefined when the flag is absent, last, or followed by
144
+ * another flag.
145
+ */
146
+ export function readOption(argv, name) {
147
+ const index = argv.indexOf(name);
148
+ const value = index === -1 ? undefined : argv[index + 1];
149
+ return value === undefined || value.startsWith('--') ? undefined : value;
150
+ }
151
+ /**
152
+ * Names the value flags a caller gave with no value.
153
+ *
154
+ * @param argv - The arguments before the bare `--`.
155
+ * @param names - The flags that take a value.
156
+ * @returns Each named flag that appears last or is followed by another flag, in argument order.
157
+ */
158
+ export function readMissingFlags(argv, names) {
159
+ return names.filter((name) => argv.includes(name) && readOption(argv, name) === undefined);
160
+ }
161
+ /**
162
+ * Names the flags a caller gave that the script does not read.
163
+ *
164
+ * @remarks
165
+ * A `--flag=value` argument is unknown, because the script reads no such form. A bare `--` ends the
166
+ * scan, so the command after it keeps every argument.
167
+ *
168
+ * @param argv - The arguments after the script path.
169
+ * @param flags - Every flag the script reads, value flags and switches alike.
170
+ * @returns Each argument that opens with `--` and is not a read flag, in argument order.
171
+ */
172
+ export function readUnknownFlags(argv, flags) {
173
+ const end = argv.indexOf('--');
174
+ return (end === -1 ? argv : argv.slice(0, end)).filter((argument) => argument.startsWith('--') && !flags.includes(argument));
175
+ }
176
+ /**
177
+ * Reads the arguments that are neither a flag nor the value of a value flag.
178
+ *
179
+ * @param argv - The arguments before the bare `--`.
180
+ * @param valueFlags - The flags that take a value.
181
+ * @returns The positional arguments in order.
182
+ */
183
+ export function readPositionals(argv, valueFlags) {
184
+ return argv.filter((argument, index) => !argument.startsWith('--') && !valueFlags.includes(argv[index - 1] ?? ''));
185
+ }
186
+ /**
187
+ * Quotes an untrusted text for a diagnostic, JSON-encoded and cut to a bounded length.
188
+ *
189
+ * @param text - The text to quote.
190
+ * @returns The JSON string literal of the text, ending in an ellipsis inside the quotes when cut.
191
+ */
192
+ export function quote(text) {
193
+ return JSON.stringify(text.length > 80 ? `${text.slice(0, 80)}…` : text);
194
+ }
195
+ /**
196
+ * Reads the system error code a thrown value carries.
197
+ *
198
+ * @param error - The thrown value.
199
+ * @returns The code, or the value's text when it carries none.
200
+ */
201
+ export function readCode(error) {
202
+ return error instanceof Error && 'code' in error && typeof error.code === 'string'
203
+ ? error.code
204
+ : String(error);
205
+ }
206
+ /**
207
+ * Resolves the queue root.
208
+ *
209
+ * @remarks
210
+ * `os.userInfo` reads the account record rather than `HOME`, `USERPROFILE`, or `TEMP`, so every
211
+ * checkout and shell of one account resolves one directory.
212
+ *
213
+ * @param argument - The `--root` value, for a proof.
214
+ * @returns The directory that holds the queue.
215
+ */
216
+ export function resolveRoot(argument) {
217
+ return argument ?? join(userInfo().homedir, '.orkestrel', 'lane');
218
+ }
219
+ /**
220
+ * Resolves the sibling launcher from the running file, so a built twin spawns its `.js` sibling.
221
+ *
222
+ * @returns The path of the dispatch skill's `launch` script.
223
+ */
224
+ export function resolveLauncher() {
225
+ const self = fileURLToPath(import.meta.url);
226
+ return join(dirname(self), '..', '..', 'orkestrel-dispatch', 'scripts', `launch${extname(self)}`);
227
+ }
228
+ /**
229
+ * Renders the endpoint a token names.
230
+ *
231
+ * @remarks
232
+ * The form is platform-defined: Windows has named pipes, and any other host takes a socket file
233
+ * under the root. The Windows host closes a pipe with its process, and a socket file outlives its
234
+ * process, so a reclaimer removes it.
235
+ *
236
+ * @param root - The queue root.
237
+ * @param token - The token.
238
+ * @returns The path `net.listen` and `net.connect` take.
239
+ */
240
+ export function renderEndpoint(root, token) {
241
+ return process.platform === 'win32'
242
+ ? `\\\\.\\pipe\\orkestrel-lane-${token}`
243
+ : join(root, `${token}${SOCKET_SUFFIX}`);
244
+ }
245
+ /**
246
+ * Renders the name of a ticket.
247
+ *
248
+ * @param sequence - The ticket's sequence.
249
+ * @returns The file name, at a fixed width.
250
+ */
251
+ export function renderTicketName(sequence) {
252
+ return `${String(sequence).padStart(SEQUENCE_WIDTH, '0')}${TICKET_SUFFIX}`;
253
+ }
254
+ /**
255
+ * Renders the name of a run record.
256
+ *
257
+ * @param sequence - The ticket's sequence.
258
+ * @returns The file name, at a fixed width.
259
+ */
260
+ export function renderRunName(sequence) {
261
+ return `${String(sequence).padStart(SEQUENCE_WIDTH, '0')}${RUN_SUFFIX}`;
262
+ }
263
+ /**
264
+ * Lists a directory's names.
265
+ *
266
+ * @param root - The queue root.
267
+ * @returns The names; empty when the directory is absent.
268
+ */
269
+ export function readNames(root) {
270
+ try {
271
+ return readdirSync(root);
272
+ }
273
+ catch (error) {
274
+ if (readCode(error) === 'ENOENT')
275
+ return [];
276
+ throw error;
277
+ }
278
+ }
279
+ /**
280
+ * Reads the sequences a listing holds.
281
+ *
282
+ * @param names - The directory's names.
283
+ * @returns Each ticket's sequence, in no promised order.
284
+ */
285
+ export function readSequences(names) {
286
+ return names.flatMap((name) => {
287
+ const match = TICKET_PATTERN.exec(name);
288
+ return match?.[1] === undefined ? [] : [Number(match[1])];
289
+ });
290
+ }
291
+ /**
292
+ * Checks whether a value is a ticket record.
293
+ *
294
+ * @param value - The parsed JSON value.
295
+ * @returns True when every field has its type and the token has the token's form; false otherwise.
296
+ */
297
+ export function isTicket(value) {
298
+ return (typeof value === 'object' &&
299
+ value !== null &&
300
+ 'protocol' in value &&
301
+ typeof value.protocol === 'number' &&
302
+ 'token' in value &&
303
+ typeof value.token === 'string' &&
304
+ TOKEN_PATTERN.test(value.token) &&
305
+ 'label' in value &&
306
+ typeof value.label === 'string' &&
307
+ 'pid' in value &&
308
+ typeof value.pid === 'number' &&
309
+ 'host' in value &&
310
+ typeof value.host === 'string' &&
311
+ 'platform' in value &&
312
+ typeof value.platform === 'string' &&
313
+ 'cwd' in value &&
314
+ typeof value.cwd === 'string' &&
315
+ 'arrived' in value &&
316
+ typeof value.arrived === 'string');
317
+ }
318
+ /**
319
+ * Checks whether a value is a run record.
320
+ *
321
+ * @param value - The parsed JSON value.
322
+ * @returns True when `started` is a number and each present id is a number; false otherwise.
323
+ */
324
+ export function isRun(value) {
325
+ return (typeof value === 'object' &&
326
+ value !== null &&
327
+ 'started' in value &&
328
+ typeof value.started === 'number' &&
329
+ (!('launcher' in value) || typeof value.launcher === 'number') &&
330
+ (!('command' in value) || typeof value.command === 'number'));
331
+ }
332
+ /**
333
+ * Parses text as JSON.
334
+ *
335
+ * @param text - The text.
336
+ * @returns The parsed value, or undefined when the text is not JSON.
337
+ */
338
+ export function parseText(text) {
339
+ try {
340
+ const parsed = JSON.parse(text);
341
+ return parsed;
342
+ }
343
+ catch {
344
+ return undefined;
345
+ }
346
+ }
347
+ /**
348
+ * Reads one queue entry.
349
+ *
350
+ * @param root - The queue root.
351
+ * @param sequence - The ticket's sequence.
352
+ * @returns The entry, its ticket undefined when the file is unreadable or malformed; empty when the
353
+ * ticket is gone.
354
+ */
355
+ export function readEntry(root, sequence) {
356
+ try {
357
+ const parsed = parseText(readFileSync(join(root, renderTicketName(sequence)), 'utf8'));
358
+ return [{ sequence, ticket: isTicket(parsed) ? parsed : undefined }];
359
+ }
360
+ catch (error) {
361
+ return readCode(error) === 'ENOENT' ? [] : [{ sequence, ticket: undefined }];
362
+ }
363
+ }
364
+ /**
365
+ * Orders entries by arrival.
366
+ *
367
+ * @param entries - The entries in any order.
368
+ * @returns The entries by ascending sequence, which the exclusive link allocated.
369
+ */
370
+ export function orderEntries(entries) {
371
+ return entries.toSorted((left, right) => left.sequence - right.sequence);
372
+ }
373
+ /**
374
+ * Reads the queue in arrival order.
375
+ *
376
+ * @param root - The queue root.
377
+ * @returns Every ticket that exists when it is read.
378
+ */
379
+ export function readQueue(root) {
380
+ return orderEntries(readSequences(readNames(root)).flatMap((sequence) => readEntry(root, sequence)));
381
+ }
382
+ /**
383
+ * Reads a run record.
384
+ *
385
+ * @param root - The queue root.
386
+ * @param sequence - The ticket's sequence.
387
+ * @returns The record; `absent` when no record exists; `unread` when it cannot be read as a record.
388
+ */
389
+ export function readRun(root, sequence) {
390
+ try {
391
+ const parsed = parseText(readFileSync(join(root, renderRunName(sequence)), 'utf8'));
392
+ return isRun(parsed)
393
+ ? {
394
+ started: parsed.started,
395
+ launcher: parsed.launcher,
396
+ command: parsed.command,
397
+ }
398
+ : 'unread';
399
+ }
400
+ catch (error) {
401
+ return readCode(error) === 'ENOENT' ? 'absent' : 'unread';
402
+ }
403
+ }
404
+ /**
405
+ * Writes a run record.
406
+ *
407
+ * @param root - The queue root.
408
+ * @param sequence - The ticket's sequence.
409
+ * @param run - The record.
410
+ */
411
+ export function writeRun(root, sequence, run) {
412
+ writeFileSync(join(root, renderRunName(sequence)), JSON.stringify(run));
413
+ }
414
+ /**
415
+ * Removes a file inside the removal budget.
416
+ *
417
+ * @param path - The file; a file that is already gone is not an error.
418
+ */
419
+ export function removeFile(path) {
420
+ rmSync(path, { force: true, maxRetries: REMOVAL_RETRIES, retryDelay: REMOVAL_DELAY_MS });
421
+ }
422
+ /**
423
+ * Builds the ticket of this process.
424
+ *
425
+ * @param token - The process's token.
426
+ * @param label - The run's label.
427
+ * @returns The complete ticket.
428
+ */
429
+ export function buildTicket(token, label) {
430
+ return {
431
+ protocol: PROTOCOL,
432
+ token,
433
+ label,
434
+ pid: process.pid,
435
+ host: hostname(),
436
+ platform: process.platform,
437
+ cwd: process.cwd(),
438
+ arrived: new Date().toISOString(),
439
+ };
440
+ }
441
+ /**
442
+ * Writes the complete ticket to the stage file, which also marks this process as choosing.
443
+ *
444
+ * @param root - The queue root.
445
+ * @param ticket - The ticket.
446
+ */
447
+ export function writeStage(root, ticket) {
448
+ writeFileSync(join(root, `${ticket.token}${STAGE_SUFFIX}`), JSON.stringify(ticket));
449
+ }
450
+ /**
451
+ * Links a file to a name, reporting a name another process took.
452
+ *
453
+ * @param from - The existing file.
454
+ * @param to - The name to take.
455
+ * @returns True when this call took the name; false when the name exists. Thrown when the host
456
+ * refuses the link for any other reason.
457
+ */
458
+ export function tryLink(from, to) {
459
+ try {
460
+ linkSync(from, to);
461
+ return true;
462
+ }
463
+ catch (error) {
464
+ if (readCode(error) === 'EEXIST')
465
+ return false;
466
+ throw error;
467
+ }
468
+ }
469
+ /**
470
+ * Publishes a stage file as the next ticket in one step.
471
+ *
472
+ * @remarks
473
+ * The sequence comes from a listing and the exclusive link, never from a clock, so tickets in one
474
+ * millisecond cannot tie. A lost link lists again.
475
+ *
476
+ * @param root - The queue root.
477
+ * @param token - The token that names the stage file.
478
+ * @returns The sequence this process took.
479
+ */
480
+ export function linkStage(root, token) {
481
+ const sequence = Math.max(0, ...readSequences(readNames(root))) + 1;
482
+ return tryLink(join(root, `${token}${STAGE_SUFFIX}`), join(root, renderTicketName(sequence)))
483
+ ? sequence
484
+ : linkStage(root, token);
485
+ }
486
+ /**
487
+ * Decides what a process with a ticket does next.
488
+ *
489
+ * @remarks
490
+ * The two listings are separate, because one listing can miss both a ticket linked and a stage file
491
+ * removed while it runs. A stage file absent from the first listing belongs to a process whose own
492
+ * listing sees this ticket, or to a ticket the second listing sees.
493
+ *
494
+ * @param root - The queue root.
495
+ * @param sequence - This process's sequence.
496
+ * @param token - This process's token.
497
+ * @returns The holder state, the stage file to wait on, the nearest earlier ticket, or a refusal.
498
+ */
499
+ export function decideTurn(root, sequence, token) {
500
+ const stage = readNames(root).find((name) => name.endsWith(STAGE_SUFFIX) && name !== `${token}${STAGE_SUFFIX}`);
501
+ if (stage !== undefined)
502
+ return { state: 'staged', name: stage };
503
+ const entries = readQueue(root);
504
+ const position = entries.findIndex((entry) => entry.sequence === sequence);
505
+ if (position === -1) {
506
+ return { state: 'refused', reason: `ticket ${renderTicketName(sequence)} is gone` };
507
+ }
508
+ const lower = entries[position - 1];
509
+ return lower === undefined ? { state: 'holder' } : { state: 'behind', entry: lower };
510
+ }
511
+ /**
512
+ * Connects to an endpoint and parks until the connection closes.
513
+ *
514
+ * @param endpoint - The endpoint.
515
+ * @param stage - If `true`, writes the one byte a published owner closes the connection on; if
516
+ * `false`, writes nothing.
517
+ * @param parked - Called when the connection is open and the wait starts.
518
+ * @returns The connect failure's code, or undefined after a connection opened and closed.
519
+ */
520
+ export function parkOn(endpoint, stage, parked) {
521
+ return new Promise((resolve) => {
522
+ const socket = connect(endpoint);
523
+ socket.once('error', (error) => resolve(readCode(error)));
524
+ socket.once('connect', () => {
525
+ socket.removeAllListeners('error');
526
+ socket.on('error', () => undefined);
527
+ socket.once('close', () => resolve(undefined));
528
+ socket.resume();
529
+ if (stage)
530
+ socket.write('s');
531
+ parked();
532
+ });
533
+ });
534
+ }
535
+ /**
536
+ * Connects to an endpoint and leaves at once.
537
+ *
538
+ * @param endpoint - The endpoint.
539
+ * @returns The connect failure's code, or undefined when the connection opened.
540
+ */
541
+ export function probeEndpoint(endpoint) {
542
+ return new Promise((resolve) => {
543
+ const socket = connect(endpoint);
544
+ socket.once('error', (error) => resolve(readCode(error)));
545
+ socket.once('connect', () => {
546
+ socket.destroy();
547
+ resolve(undefined);
548
+ });
549
+ });
550
+ }
551
+ /**
552
+ * Checks whether a connect failure means the endpoint's owner is gone.
553
+ *
554
+ * @remarks
555
+ * A token is unique and its endpoint listens before any file names it, so only a refused connect on
556
+ * that name reads as gone. A busy endpoint or any other failure proves nothing.
557
+ *
558
+ * @param code - The connect failure's code.
559
+ * @returns True for `ENOENT` and `ECONNREFUSED`; false otherwise.
560
+ */
561
+ export function isGone(code) {
562
+ return code === 'ENOENT' || code === 'ECONNREFUSED';
563
+ }
564
+ /**
565
+ * Names what makes a ticket unreadable to this process.
566
+ *
567
+ * @param ticket - The ticket.
568
+ * @returns A description of the differing protocol, host, or platform; undefined when it matches.
569
+ */
570
+ export function describeForeign(ticket) {
571
+ if (ticket.protocol !== PROTOCOL)
572
+ return `protocol ${String(ticket.protocol)}`;
573
+ if (ticket.host !== hostname())
574
+ return `host ${quote(ticket.host)}`;
575
+ return ticket.platform === process.platform ? undefined : `platform ${quote(ticket.platform)}`;
576
+ }
577
+ /**
578
+ * Parses the snapshot's text.
579
+ *
580
+ * @param text - The snapshot's standard output.
581
+ * @returns One row per line that has the row's form.
582
+ */
583
+ export function parseRows(text) {
584
+ return text.split(/\r\n|\n/u).flatMap((line) => {
585
+ const match = ROW_PATTERN.exec(line.trim());
586
+ return match === null
587
+ ? []
588
+ : [{ pid: Number(match[1]), parent: Number(match[2]), created: Number(match[3]) }];
589
+ });
590
+ }
591
+ /**
592
+ * Reads one snapshot of the host's processes.
593
+ *
594
+ * @returns The rows, or undefined when the snapshot cannot be read.
595
+ */
596
+ export function readSnapshot() {
597
+ const result = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', SNAPSHOT_COMMAND], { encoding: 'utf8', windowsHide: true, maxBuffer: 64 * 1024 * 1024 });
598
+ const rows = result.status === 0 ? parseRows(result.stdout) : [];
599
+ return rows.length === 0 ? undefined : rows;
600
+ }
601
+ /**
602
+ * Selects the rows of one run's process tree from a snapshot.
603
+ *
604
+ * @remarks
605
+ * A seed row inside the bounds is a member. A seed row outside them reused an exited seed's id and
606
+ * is excluded with its children. An exited seed's child keeps the seed's id as its parent, so it
607
+ * counts inside the bounds, and earlier than any row that reused the id. Below that, a row counts
608
+ * when its creation date is no earlier than its parent's. A process whose parent exited and is no
609
+ * seed is outside the reading.
610
+ *
611
+ * @param rows - The snapshot.
612
+ * @param seeds - The launcher id and the command id.
613
+ * @param floor - The earliest creation date a seed's tree can carry.
614
+ * @param ceiling - The latest creation date a row of an exited seed can carry.
615
+ * @returns The members.
616
+ */
617
+ export function selectMembers(rows, seeds, floor, ceiling) {
618
+ const roots = seeds.flatMap((seed) => {
619
+ const own = rows.find((row) => row.pid === seed);
620
+ return own !== undefined && own.created >= floor && own.created <= ceiling
621
+ ? [own]
622
+ : rows.filter((row) => row.parent === seed &&
623
+ row.created >= floor &&
624
+ row.created <= ceiling &&
625
+ (own === undefined || row.created < own.created));
626
+ });
627
+ const members = new Map(roots.map((row) => [row.pid, row]));
628
+ for (const member of members.values()) {
629
+ for (const row of rows) {
630
+ if (row.parent === member.pid && row.created >= member.created && !members.has(row.pid)) {
631
+ members.set(row.pid, row);
632
+ }
633
+ }
634
+ }
635
+ return [...members.values()];
636
+ }
637
+ /**
638
+ * Reads whether a process group still has a member.
639
+ *
640
+ * @param group - The group id.
641
+ * @returns The group id while the host reports the group; empty when it reports none.
642
+ */
643
+ export function readGroup(group) {
644
+ try {
645
+ process.kill(-group, 0);
646
+ return [group];
647
+ }
648
+ catch (error) {
649
+ return readCode(error) === 'ESRCH' ? [] : [group];
650
+ }
651
+ }
652
+ /**
653
+ * Reads the members of one run's process tree.
654
+ *
655
+ * @remarks
656
+ * The reading is platform-defined: Windows has no process group a descendant inherits, so it reads
657
+ * parent links, and any other host reads the launcher's group.
658
+ *
659
+ * @param run - The run record.
660
+ * @param ceiling - The latest creation date a row of an exited seed can carry.
661
+ * @returns The ids to kill, or undefined when the tree cannot be read.
662
+ */
663
+ export function readTree(run, ceiling) {
664
+ if (run.launcher === undefined)
665
+ return undefined;
666
+ if (process.platform !== 'win32')
667
+ return readGroup(run.launcher);
668
+ const rows = readSnapshot();
669
+ return rows === undefined
670
+ ? undefined
671
+ : selectMembers(rows, run.command === undefined ? [run.launcher] : [run.launcher, run.command], run.started - CLOCK_ALLOWANCE_MS, ceiling).map((row) => row.pid);
672
+ }
673
+ /**
674
+ * Kills each listed member.
675
+ *
676
+ * @remarks
677
+ * The kill is platform-defined: Windows ends a process by id with `taskkill`, whose `/T` ends
678
+ * nothing under a root that exited, so each member takes its own kill. Any other host signals the
679
+ * group, and a pause follows, because no event reports the end of a foreign group.
680
+ *
681
+ * @param members - The ids a reading returned.
682
+ */
683
+ export function killMembers(members) {
684
+ for (const member of members) {
685
+ if (process.platform === 'win32') {
686
+ spawnSync('taskkill', ['/pid', String(member), '/T', '/F'], {
687
+ stdio: 'ignore',
688
+ windowsHide: true,
689
+ });
690
+ }
691
+ else {
692
+ try {
693
+ process.kill(-member, 'SIGKILL');
694
+ }
695
+ catch { }
696
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, KILL_PAUSE_MS);
697
+ }
698
+ }
699
+ }
700
+ /**
701
+ * Reads a tree, kills what it lists, and reads again, inside a bounded budget.
702
+ *
703
+ * @param read - Takes one reading; undefined means the tree cannot be read.
704
+ * @param kill - Kills what a reading listed.
705
+ * @param budget - The kills left.
706
+ * @returns Gone only after a reading lists no member; otherwise the members the last reading listed.
707
+ */
708
+ export function sweepTree(read, kill, budget) {
709
+ const members = read();
710
+ if (members === undefined)
711
+ return { gone: false, members: [] };
712
+ if (members.length === 0)
713
+ return { gone: true, members };
714
+ if (budget <= 0)
715
+ return { gone: false, members };
716
+ kill(members);
717
+ return sweepTree(read, kill, budget - 1);
718
+ }
719
+ /**
720
+ * Reclaims the ticket of an owner whose endpoint refused a connect.
721
+ *
722
+ * @remarks
723
+ * A reclaimer never kills, because the parallel skill forbids ending another session's process.
724
+ *
725
+ * @param root - The queue root.
726
+ * @param sequence - The dead ticket's sequence.
727
+ * @param ticket - The dead ticket.
728
+ * @returns The refusal when the owner's tree reads as present or cannot be identified; undefined
729
+ * after the ticket and its files are removed.
730
+ */
731
+ export function reclaimTicket(root, sequence, ticket) {
732
+ const run = readRun(root, sequence);
733
+ const files = `${renderTicketName(sequence)} and ${renderRunName(sequence)} under ${root}`;
734
+ if (run === 'unread' || (run !== 'absent' && run.launcher === undefined)) {
735
+ return `the owner of ${quote(ticket.label)} (pid ${String(ticket.pid)}) ended before its tree could be identified; end its tree, then delete ${files}`;
736
+ }
737
+ if (run !== 'absent') {
738
+ const members = readTree(run, Date.now());
739
+ if (members === undefined || members.length > 0) {
740
+ return `the owner of ${quote(ticket.label)} (pid ${String(ticket.pid)}) is gone and its tree reads as ${members === undefined ? 'unread' : `present: ${members.join(', ')}`}; launcher ${String(run.launcher)}, command ${String(run.command)}, files ${files}`;
741
+ }
742
+ removeFile(join(root, renderRunName(sequence)));
743
+ }
744
+ removeFile(join(root, renderTicketName(sequence)));
745
+ removeFile(join(root, `${ticket.token}${SOCKET_SUFFIX}`));
746
+ return undefined;
747
+ }
748
+ /**
749
+ * Waits on one stage file and removes it when its owner is gone.
750
+ *
751
+ * @param root - The queue root.
752
+ * @param name - The stage file's name.
753
+ * @returns The refusal, or undefined when the stage ended.
754
+ */
755
+ export async function waitOnStage(root, name) {
756
+ const token = name.slice(0, -STAGE_SUFFIX.length);
757
+ if (!TOKEN_PATTERN.test(token))
758
+ return `stage file ${quote(name)} under ${root} names no token`;
759
+ const code = await parkOn(renderEndpoint(root, token), true, () => console.error('lane: waiting behind an arrival'));
760
+ if (code === undefined)
761
+ return undefined;
762
+ if (!isGone(code))
763
+ return `the endpoint of ${quote(name)} reported ${code}`;
764
+ removeFile(join(root, name));
765
+ removeFile(join(root, `${token}${SOCKET_SUFFIX}`));
766
+ return undefined;
767
+ }
768
+ /**
769
+ * Waits on the nearest earlier ticket and reclaims it when its owner is gone.
770
+ *
771
+ * @param root - The queue root.
772
+ * @param entry - The earlier ticket.
773
+ * @param announced - The token this process last printed a waiting line for.
774
+ * @returns The refusal, or undefined when the wait ended.
775
+ */
776
+ export async function waitOnTicket(root, entry, announced) {
777
+ const name = renderTicketName(entry.sequence);
778
+ const ticket = entry.ticket;
779
+ if (ticket === undefined)
780
+ return `ticket ${name} under ${root} cannot be read`;
781
+ const foreign = describeForeign(ticket);
782
+ if (foreign !== undefined)
783
+ return `ticket ${name} under ${root} carries ${foreign}`;
784
+ const code = await parkOn(renderEndpoint(root, ticket.token), false, () => {
785
+ if (announced !== ticket.token)
786
+ console.error(`lane: waiting behind ${quote(ticket.label)}`);
787
+ });
788
+ if (code === undefined)
789
+ return undefined;
790
+ return isGone(code)
791
+ ? reclaimTicket(root, entry.sequence, ticket)
792
+ : `the endpoint of ticket ${name} reported ${code}`;
793
+ }
794
+ /**
795
+ * Waits for this process's turn, parked on events with no timer.
796
+ *
797
+ * @param root - The queue root.
798
+ * @param sequence - This process's sequence.
799
+ * @param token - This process's token.
800
+ * @param announced - The token this process last printed a waiting line for.
801
+ * @returns The refusal, or undefined when this process holds the lane.
802
+ */
803
+ export async function waitForTurn(root, sequence, token, announced) {
804
+ const turn = decideTurn(root, sequence, token);
805
+ if (turn.state === 'holder')
806
+ return undefined;
807
+ if (turn.state === 'refused')
808
+ return turn.reason;
809
+ const refusal = turn.state === 'staged'
810
+ ? await waitOnStage(root, turn.name)
811
+ : await waitOnTicket(root, turn.entry, announced);
812
+ if (refusal !== undefined)
813
+ return refusal;
814
+ return waitForTurn(root, sequence, token, turn.state === 'behind' ? turn.entry.ticket?.token : announced);
815
+ }
816
+ /**
817
+ * Reads the command id from a launcher line.
818
+ *
819
+ * @param line - One line of the launcher's stdout.
820
+ * @returns The pid of the spawn line; undefined for any other line.
821
+ */
822
+ export function readCommandId(line) {
823
+ const parsed = parseText(line);
824
+ return typeof parsed === 'object' &&
825
+ parsed !== null &&
826
+ 'pid' in parsed &&
827
+ typeof parsed.pid === 'number' &&
828
+ !('exit' in parsed)
829
+ ? parsed.pid
830
+ : undefined;
831
+ }
832
+ /**
833
+ * Registers a handler on every stop signal, on a host that delivers them.
834
+ *
835
+ * @remarks
836
+ * Windows runs no signal handler for a forced kill, so an ended lane process there is the reclaim
837
+ * case.
838
+ *
839
+ * @param handler - The handler.
840
+ * @returns The call that removes the handler.
841
+ */
842
+ export function watchSignals(handler) {
843
+ if (process.platform === 'win32')
844
+ return () => undefined;
845
+ for (const signal of STOP_SIGNALS)
846
+ process.on(signal, handler);
847
+ return () => {
848
+ for (const signal of STOP_SIGNALS)
849
+ process.removeListener(signal, handler);
850
+ };
851
+ }
852
+ /**
853
+ * Starts the sibling launcher.
854
+ *
855
+ * @remarks
856
+ * A host other than Windows starts it as a group leader, so the launcher's id is the group a
857
+ * handover reads.
858
+ *
859
+ * @param launcher - The launcher's path.
860
+ * @param options - The run.
861
+ * @returns The started launcher.
862
+ */
863
+ export function startLauncher(launcher, options) {
864
+ return spawn(process.execPath, [
865
+ launcher,
866
+ '--journal',
867
+ options.journal,
868
+ '--errors',
869
+ options.errors,
870
+ '--cap',
871
+ String(options.cap),
872
+ '--',
873
+ ...options.command,
874
+ ], {
875
+ stdio: ['ignore', 'pipe', 'inherit'],
876
+ windowsHide: true,
877
+ detached: process.platform !== 'win32',
878
+ });
879
+ }
880
+ /**
881
+ * Waits for a started launcher to close.
882
+ *
883
+ * @param child - The started launcher.
884
+ * @returns Its exit code, or undefined when a signal ended it or it could not start.
885
+ */
886
+ export function waitForClose(child) {
887
+ return new Promise((resolve) => {
888
+ child.once('error', () => resolve(undefined));
889
+ child.once('close', (code) => resolve(code ?? undefined));
890
+ });
891
+ }
892
+ /**
893
+ * Writes a run record, leaving an unwritten id to the handover reading.
894
+ *
895
+ * @param root - The queue root.
896
+ * @param sequence - The ticket's sequence.
897
+ * @param run - The record.
898
+ * @returns True when the record was written; false otherwise.
899
+ */
900
+ export function tryWriteRun(root, sequence, run) {
901
+ try {
902
+ writeRun(root, sequence, run);
903
+ return true;
904
+ }
905
+ catch {
906
+ return false;
907
+ }
908
+ }
909
+ /**
910
+ * Removes a holder's run record and ticket.
911
+ *
912
+ * @param root - The queue root.
913
+ * @param sequence - The ticket's sequence.
914
+ * @returns The host's refusal when the removal budget ended; undefined after both are gone.
915
+ */
916
+ export function releaseTicket(root, sequence) {
917
+ try {
918
+ removeFile(join(root, renderRunName(sequence)));
919
+ removeFile(join(root, renderTicketName(sequence)));
920
+ return undefined;
921
+ }
922
+ catch (error) {
923
+ return readCode(error);
924
+ }
925
+ }
926
+ /**
927
+ * Runs the command as the holder, reads the tree at handover, and releases.
928
+ *
929
+ * @param options - The run.
930
+ * @param launcher - The launcher's path.
931
+ * @param sequence - This process's sequence.
932
+ * @returns The launcher's code; 1 when a signal ended it; 70 when the tree still reads as present or
933
+ * the ticket could not be removed; 75 when the launcher could not start.
934
+ */
935
+ export async function runHolder(options, launcher, sequence) {
936
+ const { root } = options;
937
+ const started = Date.now();
938
+ writeRun(root, sequence, { started, launcher: undefined, command: undefined });
939
+ const child = startLauncher(launcher, options);
940
+ const id = child.pid;
941
+ if (id === undefined) {
942
+ releaseTicket(root, sequence);
943
+ console.error(`lane: ${quote(launcher)} could not start`);
944
+ return 75;
945
+ }
946
+ tryWriteRun(root, sequence, { started, launcher: id, command: undefined });
947
+ const unwatch = watchSignals(() => killMembers([id]));
948
+ const closed = waitForClose(child);
949
+ if (child.stdout !== null) {
950
+ const lines = createInterface({ input: child.stdout, crlfDelay: Infinity });
951
+ lines.on('error', () => undefined);
952
+ lines.on('line', (line) => {
953
+ console.log(line);
954
+ const command = readCommandId(line);
955
+ if (command !== undefined)
956
+ tryWriteRun(root, sequence, { started, launcher: id, command });
957
+ });
958
+ }
959
+ const code = await closed;
960
+ unwatch();
961
+ const ended = Date.now();
962
+ const run = readRun(root, sequence);
963
+ const sweep = run === 'absent' || run === 'unread'
964
+ ? { gone: false, members: [] }
965
+ : sweepTree(() => readTree(run, ended), killMembers, KILL_BUDGET);
966
+ if (!sweep.gone) {
967
+ console.error(`lane: the tree of ${quote(options.label)} still reads as ${sweep.members.length === 0 ? 'unread' : `present: ${sweep.members.join(', ')}`}; the lane stays held by ${renderTicketName(sequence)} and ${renderRunName(sequence)} under ${root}`);
968
+ return 70;
969
+ }
970
+ const refusal = releaseTicket(root, sequence);
971
+ if (refusal !== undefined) {
972
+ console.error(`lane: removing ${renderTicketName(sequence)} reported ${refusal}`);
973
+ return 70;
974
+ }
975
+ return code ?? 1;
976
+ }
977
+ /**
978
+ * Takes a ticket, waits for this process's turn, and runs the command.
979
+ *
980
+ * @param options - The run.
981
+ * @param launcher - The launcher's path.
982
+ * @param tokenId - This process's token.
983
+ * @param token - This process's listening endpoint.
984
+ * @returns The exit code.
985
+ */
986
+ export async function enterLane(options, launcher, tokenId, token) {
987
+ const { root } = options;
988
+ try {
989
+ mkdirSync(root, { recursive: true });
990
+ await token.listen(renderEndpoint(root, tokenId));
991
+ writeStage(root, buildTicket(tokenId, options.label));
992
+ const sequence = linkStage(root, tokenId);
993
+ removeFile(join(root, `${tokenId}${STAGE_SUFFIX}`));
994
+ token.publish();
995
+ const unwatch = watchSignals(() => {
996
+ removeFile(join(root, renderTicketName(sequence)));
997
+ removeFile(renderEndpoint(root, tokenId));
998
+ process.exit(75);
999
+ });
1000
+ const refusal = await waitForTurn(root, sequence, tokenId);
1001
+ unwatch();
1002
+ if (refusal === undefined)
1003
+ return await runHolder(options, launcher, sequence);
1004
+ removeFile(join(root, renderTicketName(sequence)));
1005
+ console.error(`lane: ${refusal}`);
1006
+ return 75;
1007
+ }
1008
+ catch (error) {
1009
+ console.error(`lane: the queue under ${root} refused the run: ${String(error)}`);
1010
+ return 75;
1011
+ }
1012
+ }
1013
+ /**
1014
+ * Runs one validated command on the lane.
1015
+ *
1016
+ * @param options - The run.
1017
+ * @returns The exit code.
1018
+ */
1019
+ export async function runLane(options) {
1020
+ const launcher = resolveLauncher();
1021
+ if (!existsSync(launcher)) {
1022
+ console.error(`lane: the launcher ${quote(launcher)} does not exist`);
1023
+ return 75;
1024
+ }
1025
+ const token = new Token();
1026
+ const code = await enterLane(options, launcher, randomUUID(), token);
1027
+ await token.destroy();
1028
+ return code;
1029
+ }
1030
+ /**
1031
+ * Reads one ticket's state for `--status`, connecting to its endpoint and writing nothing.
1032
+ *
1033
+ * @param root - The queue root.
1034
+ * @param entry - The ticket.
1035
+ * @returns The ticket's row.
1036
+ */
1037
+ export async function readStatusRow(root, entry) {
1038
+ const ticket = entry.ticket;
1039
+ const fields = { sequence: entry.sequence, label: ticket?.label, pid: ticket?.pid };
1040
+ if (ticket === undefined || describeForeign(ticket) !== undefined) {
1041
+ return { ...fields, state: 'unread' };
1042
+ }
1043
+ const code = await probeEndpoint(renderEndpoint(root, ticket.token));
1044
+ if (code === undefined)
1045
+ return { ...fields, state: 'live' };
1046
+ return { ...fields, state: isGone(code) ? 'dead' : 'unread' };
1047
+ }
1048
+ /**
1049
+ * Reads the queue for `--status`.
1050
+ *
1051
+ * @param root - The queue root.
1052
+ * @returns Every ticket in arrival order, and the earliest live ticket with a run record.
1053
+ */
1054
+ export async function readStatus(root) {
1055
+ const tickets = await Promise.all(readQueue(root).map((entry) => readStatusRow(root, entry)));
1056
+ return {
1057
+ tickets,
1058
+ holder: tickets.find((row) => row.state === 'live' && existsSync(join(root, renderRunName(row.sequence)))),
1059
+ };
1060
+ }
1061
+ /**
1062
+ * Renders the queue as text.
1063
+ *
1064
+ * @param status - What `--status` read.
1065
+ * @returns One line for the holder and one per ticket, in arrival order.
1066
+ */
1067
+ export function renderStatus(status) {
1068
+ return [
1069
+ `holder: ${status.holder === undefined ? 'none' : quote(status.holder.label ?? 'unread')}`,
1070
+ ...status.tickets.map((row) => `${renderTicketName(row.sequence)} ${row.state} ${quote(row.label ?? 'unread')} pid ${String(row.pid)}`),
1071
+ ].join('\n');
1072
+ }
1073
+ /**
1074
+ * Prints the queue, writing nothing under the root.
1075
+ *
1076
+ * @param root - The queue root.
1077
+ * @param json - If `true`, prints JSON; if `false`, prints text.
1078
+ * @returns 0 on a read; 75 when the root cannot be listed.
1079
+ */
1080
+ export async function runStatus(root, json) {
1081
+ try {
1082
+ const status = await readStatus(root);
1083
+ console.log(json ? JSON.stringify(status) : renderStatus(status));
1084
+ return 0;
1085
+ }
1086
+ catch (error) {
1087
+ console.error(`lane: the queue under ${root} cannot be read: ${readCode(error)}`);
1088
+ return 75;
1089
+ }
1090
+ }
1091
+ /**
1092
+ * Validates a run's arguments.
1093
+ *
1094
+ * @param own - The arguments before the bare `--`.
1095
+ * @param command - The arguments after the bare `--`.
1096
+ * @returns The run, or undefined when a flag or the command is missing or out of range.
1097
+ */
1098
+ export function readLaneOptions(own, command) {
1099
+ const label = readOption(own, '--label');
1100
+ const journal = readOption(own, '--journal');
1101
+ const errors = readOption(own, '--errors');
1102
+ const cap = Number(readOption(own, '--cap') ?? Number.NaN);
1103
+ if (label === undefined ||
1104
+ label === '' ||
1105
+ journal === undefined ||
1106
+ errors === undefined ||
1107
+ journal === errors ||
1108
+ !Number.isFinite(cap) ||
1109
+ cap <= 0 ||
1110
+ cap > MAX_CAP_SECONDS ||
1111
+ command[0] === undefined ||
1112
+ command[0] === '') {
1113
+ return undefined;
1114
+ }
1115
+ return { root: resolveRoot(readOption(own, '--root')), label, journal, errors, cap, command };
1116
+ }
1117
+ /**
1118
+ * Runs the script on its arguments.
1119
+ *
1120
+ * @remarks
1121
+ * Every usage fault returns before a ticket exists, so none surfaces after a wait.
1122
+ *
1123
+ * @param argv - The arguments after the script path.
1124
+ * @returns The exit code the opening comment names.
1125
+ */
1126
+ export async function main(argv) {
1127
+ const end = argv.indexOf('--');
1128
+ const own = end === -1 ? argv : argv.slice(0, end);
1129
+ const command = end === -1 ? [] : argv.slice(end + 1);
1130
+ const unknown = readUnknownFlags(argv, FLAGS);
1131
+ if (unknown.length > 0) {
1132
+ console.error(`lane: ${unknown.join(', ')} is not a flag this script reads; ${USAGE}`);
1133
+ return 64;
1134
+ }
1135
+ const missing = readMissingFlags(own, VALUE_FLAGS);
1136
+ if (missing.length > 0) {
1137
+ console.error(`lane: ${missing.join(', ')} given with no value; ${USAGE}`);
1138
+ return 64;
1139
+ }
1140
+ if (readPositionals(own, VALUE_FLAGS).length > 0) {
1141
+ console.error(USAGE);
1142
+ return 64;
1143
+ }
1144
+ const status = own.includes('--status');
1145
+ if (status) {
1146
+ if (end !== -1 || RUN_FLAGS.some((flag) => own.includes(flag))) {
1147
+ console.error(`lane: --status and a run are two modes; ${USAGE}`);
1148
+ return 64;
1149
+ }
1150
+ return runStatus(resolveRoot(readOption(own, '--root')), own.includes('--json'));
1151
+ }
1152
+ const options = own.includes('--json') ? undefined : readLaneOptions(own, command);
1153
+ if (options === undefined) {
1154
+ console.error(USAGE);
1155
+ return 64;
1156
+ }
1157
+ return runLane(options);
1158
+ }
1159
+ if (process.argv[1] !== undefined && realpathSync(process.argv[1]) === import.meta.filename) {
1160
+ main(process.argv.slice(2)).then((code) => {
1161
+ process.exitCode = code;
1162
+ });
1163
+ }