@orkestrel/scaffold 0.0.134 → 0.0.136

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 (53) hide show
  1. package/dist/agents/skills/orkestrel-parallel/scripts/lane.js +777 -83
  2. package/dist/agents/skills/orkestrel-publish/scripts/wave.js +327 -21
  3. package/dist/bin/main.js +254 -36
  4. package/dist/bin/main.js.map +1 -1
  5. package/dist/host/AGENTS.md +2 -2
  6. package/dist/host/agents/orchestration.md +2 -2
  7. package/dist/host/agents/skills/orkestrel-parallel/SKILL.md +1 -1
  8. package/dist/host/agents/skills/orkestrel-parallel/scripts/lane.ts +983 -123
  9. package/dist/host/agents/skills/orkestrel-publish/references/release.md +1 -0
  10. package/dist/host/agents/skills/orkestrel-publish/references/wave.md +22 -5
  11. package/dist/host/agents/skills/orkestrel-publish/scripts/wave.ts +403 -32
  12. package/dist/host/claude/agents/orkestrel.md +17 -17
  13. package/dist/host/claude/agents/reviewer.md +1 -1
  14. package/dist/host/claude/rules/architecture.md +1 -1
  15. package/dist/host/claude/rules/documentation.md +1 -1
  16. package/dist/host/claude/rules/patterns.md +4 -2
  17. package/dist/host/claude/rules/workspace.md +73 -67
  18. package/dist/host/configs/helpers.ts +109 -73
  19. package/dist/host/dotfiles/oxlintrc.json +1 -57
  20. package/dist/host/guides/agent.md +989 -395
  21. package/dist/host/guides/contract.md +198 -163
  22. package/dist/host/guides/database.md +978 -503
  23. package/dist/host/guides/indexeddb.md +80 -66
  24. package/dist/host/guides/middleware.md +5 -5
  25. package/dist/host/guides/ollama.md +41 -42
  26. package/dist/host/guides/relation.md +56 -32
  27. package/dist/host/guides/scaffold.md +185 -107
  28. package/dist/host/guides/sqlite.md +44 -23
  29. package/dist/host/guides/study.md +12 -12
  30. package/dist/host/guides/test.md +163 -47
  31. package/dist/host/guides/toolbox.md +127 -81
  32. package/dist/host/guides/workspace.md +21 -14
  33. package/dist/host/manifest.json +30 -30
  34. package/dist/host/scripts/browsers.sh +0 -0
  35. package/dist/host/scripts/codex.sh +0 -0
  36. package/dist/host/scripts/cursor.sh +0 -0
  37. package/dist/host/scripts/deps.sh +0 -0
  38. package/dist/host/scripts/npm.sh +0 -0
  39. package/dist/host/scripts/ollama.sh +0 -0
  40. package/dist/host/tests/config.test.ts +237 -115
  41. package/dist/src/core/index.cjs +591 -218
  42. package/dist/src/core/index.cjs.map +1 -1
  43. package/dist/src/core/index.d.cts +248 -29
  44. package/dist/src/core/index.d.ts +248 -29
  45. package/dist/src/core/index.js +581 -216
  46. package/dist/src/core/index.js.map +1 -1
  47. package/dist/src/server/index.cjs +18 -8
  48. package/dist/src/server/index.cjs.map +1 -1
  49. package/dist/src/server/index.d.cts +4 -3
  50. package/dist/src/server/index.d.ts +4 -3
  51. package/dist/src/server/index.js +19 -9
  52. package/dist/src/server/index.js.map +1 -1
  53. package/package.json +3 -3
@@ -12,25 +12,48 @@
12
12
  // Lanes: a ticket is heavy unless its arrival reads it light, and the reading is frozen in the
13
13
  // ticket. A heavy ticket holds when it is the earliest live non-light ticket; a `--solo` ticket is
14
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.
15
+ // ticket that the directory rule does not block holds, no earlier `--solo` ticket is live, and the
16
+ // earlier light tickets' summed peaks with its own fit `slots` and each budget; the earliest light
17
+ // ticket always fits. A light holder runs at below-normal priority, and its holder ends it and exits
18
+ // 69 when a sample taken before the launcher exits passes the memory or process threshold; a sample
19
+ // after the exit reads no member created after it and ends nothing.
20
+ // Directories: a run of the falsify skill's `mutate` script, `--restore` included, publishes
21
+ // `edits` in its ticket, because it edits source in its working directory. Every ticket also waits
22
+ // on the nearest earlier ticket that carries `edits` and shares its working directory, and a ticket
23
+ // that carries `edits` also waits on the nearest earlier ticket of its working directory in either
24
+ // lane, and on an earlier ticket it cannot read. That last wait is the lane's existing refusal,
25
+ // because a ticket's endpoint token lives in its record, so a mutation exits 75 on any unreadable
26
+ // earlier ticket, one a writer has not finished included. Two directories share source when their
27
+ // real paths, as the file system stores them, are equal or one sits inside the other. Every wait
28
+ // names an earlier ticket, so no cycle of waits forms, and each process derives from the earlier
29
+ // tickets alone which light tickets the rule blocks.
19
30
  // Light reading: `<root>/limits.json` holds `slots`, the `budget` and the per-run `threshold`; while
20
31
  // 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.
32
+ // and no record is written. Otherwise each run starts one PowerShell sampler at arrival, which readies
33
+ // while the ticket waits, with no timer until its first sample, and exits when its stdin closes. The
34
+ // holder starts its command after the sampler readies, or unmeasured once `READY_MS` passes, samples
35
+ // the tree back to back through the command's first second and once a second after, and reads the
36
+ // handover through one more sample; when that sample lists a member or no sampler answers, the
37
+ // handover reads, kills, and reads again through fresh snapshots, each a second PowerShell. The
38
+ // holder writes one record per run under `<root>/history/<key>/`, keyed by the working directory and
39
+ // the command, keeping the latest runs. A record that opens a key prunes the history after the
40
+ // release, keeping only the keys written inside `HISTORY_AGE_MS` (7 days), and of those at most the
41
+ // `HISTORY_KEYS` (512) written last; a
42
+ // name it cannot list or remove stays, one stderr line names it, and the exit stays the run's. The
43
+ // command's kind seeds the reading: a format check, a lint check, a type check, and a scoped test run
44
+ // read light until a record breaches; a full suite, a run of several projects, an install, a
45
+ // pack-and-install suite, a release chain, a journey, a study, a capture, and a live-service run read
46
+ // heavy; `npx` and a package manager's `exec`, `x`, or `dlx` verb read as the tool they run; any other
47
+ // command reads light only when its latest runs each sit inside the threshold, none capped and none
48
+ // ending 69 or 70. A `mutate` run is keyed without its edits file and seeded by the command after its
49
+ // own `--`, so it reads light when that command's records allow; a `mutate --restore` run wraps no
50
+ // command and reads heavy.
28
51
  // `--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.
52
+ // lane, `edits` for a `mutate` run, and `holding` for a holder, and names the heavy holder and every
53
+ // light holder. It writes nothing, removes nothing, and creates no root; an absent root reads as an
54
+ // empty queue. The root is `.orkestrel/lane` under the account's home directory, read from the
55
+ // account record and never from an environment variable; `--root DIR` is for a proof. Bench execs
56
+ // stay outside the lane, because the host bound counts process-running commands.
34
57
  // Exit: the launcher's code (the command's code, 124 when capped, 127 when the command could not
35
58
  // start); 1 when a signal ended the launcher; 64 on usage; 69 when a light run passed its threshold
36
59
  // and its holder ended it; 75 when the lane refused before the command ran; 70 when the command ran
@@ -44,9 +67,9 @@
44
67
  // owner closes that connection, because a connection its synchronous allocation left unaccepted
45
68
  // would otherwise stay parked on a process that waits behind it. A light waiter writes `h` to an
46
69
  // 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.
70
+ // so the waiter decides again; a byte that reaches an owner that is releasing parks until it ends.
71
+ // The protocol stays 1: the `light`, `solo`, and `edits` ticket fields are optional, a ticket
72
+ // without them reads as heavy, and a process of the first release holds only as the earliest ticket.
50
73
  // Limits:
51
74
  // - Process-identifier reuse, Windows. A row is matched by id and creation date, bounded by a clock
52
75
  // comparison, so a reuse of an exited seed's id inside the clock allowance can misattribute a row.
@@ -64,20 +87,55 @@
64
87
  // - An owner ended between the run record and the launcher id. The tree cannot be identified. Arrivals
65
88
  // exit 75 until a person deletes the named files. An owner ended between the launcher id and the
66
89
  // 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.
90
+ // - A dead light holder with a live tree. Light arrivals exit 75 until that tree is gone. A heavy
91
+ // arrival passes it, unless the directory rule points the arrival at it; that arrival waits on it,
92
+ // then exits 75 while its tree lives.
69
93
  // - 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.
71
- // - An unreaped member. On a host whose init does not reap, a killed member can keep reading as
72
- // present. The lane exits 70 and stays held.
94
+ // exits between samples is lost, and disk input and output are not measured. A command that ends
95
+ // before one process query answers, about 140 ms on the Windows host measured 2026-11-12, can
96
+ // record zero, so it counts nothing until a later run is read.
97
+ // - Transition. A process of an earlier release reads no `edits` field: it does not wait on a mutation
98
+ // of its directory, a `mutate` run it carries publishes no `edits`, so the directory rule cannot see
99
+ // that run, and as a light ticket it counts a directory-blocked light ticket of this release as one
100
+ // that has not held, so it queues behind it. Every checkout on an earlier `@orkestrel/scaffold`
101
+ // keeps starting such processes on the shared root until that checkout adopts this release, so the
102
+ // bound is the last adoption, not one process's exit. A mutation of this release does wait on an
103
+ // earlier ticket of its directory, whichever release wrote it.
104
+ // - Heavy throughput. A heavy ticket that the directory rule blocks still keeps every later heavy
105
+ // ticket out, from every directory, because passing it would let two heavy tickets hold at once.
106
+ // - Light budget. A light ticket that the directory rule blocks is not one later light tickets wait to
107
+ // hold, but its footprint still counts in their budget sums and their slot count. Where the per-run
108
+ // threshold is over the budget, as in the live `limits.json` of 2026-11-12, one blocked ticket with
109
+ // fewer than `RECENT_RUNS` records fills the budget, so every later light ticket on the host queues
110
+ // until the mutation ends and that ticket has run and left. The count stays, because leaving the ticket out and
111
+ // counting later holders when it unblocks would race two processes on one budget.
112
+ // - The ready wait. A holder waits for its sampler before it writes its run record and signals that
113
+ // it holds, so later light tickets count it as one that has not held for up to `READY_MS` when its
114
+ // sampler never reports ready.
115
+ // - The idle sampler. Each queued measured ticket keeps its PowerShell sampler from arrival, about
116
+ // 75 MB of private memory once ready on the Windows host measured 2026-11-13, and no budget counts
117
+ // that memory, so a long queue of measured tickets costs that much per ticket.
118
+ // - A prune beside a write. A holder that writes a record to an existing key that is past a bound can
119
+ // lose that record to another holder's prune, which removes the key with the record in it.
120
+ // - An unreaped member. A group reads as ended when two readings of the process table at `/proc`,
121
+ // one after the other, show the same threads of its members and every one exited (`Z` or `X`),
122
+ // whether or not the host's init has reaped them; a member whose main thread exited while another
123
+ // thread runs reads as present. An empty reading reads as present, and so does any reading that
124
+ // cannot list the table, a member's threads, or an entry's `stat` for a reason other than the
125
+ // entry being gone. Three cases are outside the reading: a process that joins the group from
126
+ // outside it through `setpgid` during the second listing; a chain of members that each fork,
127
+ // exit, and are reaped between the listing and the read, in both readings; and a member the host
128
+ // hides from `/proc` entirely (`hidepid=2`). On a host without that table, a killed member its
129
+ // parent has not reaped keeps reading as present, and the lane exits 70 and stays held.
73
130
  // - Listing completeness. No probe proves that a listing returns every stable entry. The design takes
74
131
  // it from the documented directory-read contract.
75
132
  // - Queue scope. The queue is one per user account per host. A wiped root, a second account, or a
76
133
  // `--root` outside a proof gives a second queue that does not see the first.
77
134
  // - A denied root. A sandbox that refuses the root or the endpoint exits 75; no sandboxed bench exec
78
135
  // has run this script.
79
- // - Linux. Every non-Windows branch is unread on this host and needs a Linux run: the socket file, the
80
- // process group, and the signal handling.
136
+ // - Linux. The socket file, the process group, and the zombie reading were read on a Linux container
137
+ // on 2026-11-14 (Node 22.23.5, an init that does not reap as a child ends); the signal handling is
138
+ // unread on Linux.
81
139
  // Migration stop: a second queue does not see the first, so while a host's sessions run another
82
140
  // serializer, no caller moves. After a scaffold release carries this script and no command runs on the
83
141
  // host, move every caller in one step and delete the serializer this replaces.
@@ -95,11 +153,20 @@ import {
95
153
  readFileSync,
96
154
  realpathSync,
97
155
  rmSync,
156
+ statSync,
98
157
  writeFileSync,
99
158
  } from 'node:fs'
100
159
  import { connect, createServer } from 'node:net'
101
160
  import { constants, hostname, setPriority, userInfo } from 'node:os'
102
- import { basename, dirname, extname, isAbsolute, join } from 'node:path'
161
+ import {
162
+ basename,
163
+ dirname,
164
+ extname,
165
+ isAbsolute,
166
+ join,
167
+ resolve as resolvePath,
168
+ sep,
169
+ } from 'node:path'
103
170
  import { createInterface } from 'node:readline'
104
171
  import { fileURLToPath } from 'node:url'
105
172
  import { parseArgs } from 'node:util'
@@ -189,6 +256,15 @@ export const TICKET_PATTERN = /^(\d+)\.ticket$/u
189
256
  /** Matches one snapshot row: process id, parent id, and creation time in milliseconds. */
190
257
  export const ROW_PATTERN = /^(\d+) (\d+) (\d+)$/u
191
258
 
259
+ /** Names the directory where a Linux host publishes its process table. */
260
+ export const PROCESS_TABLE = '/proc'
261
+
262
+ /**
263
+ * Lists the process-table states of a member that has exited and that its parent has not reaped:
264
+ * `Z` for a zombie, and `X` for a process the kernel is releasing.
265
+ */
266
+ export const ENDED_STATES: readonly string[] = ['Z', 'X']
267
+
192
268
  /** Lists the signals that interrupt a lane on a host that delivers them. */
193
269
  export const STOP_SIGNALS: readonly NodeJS.Signals[] = ['SIGINT', 'SIGTERM', 'SIGHUP']
194
270
 
@@ -243,6 +319,33 @@ export const ENDED_WIDTH = 15
243
319
  /** Holds the count of latest records the light reading takes, which is also the count each key keeps. */
244
320
  export const RECENT_RUNS = 3
245
321
 
322
+ /** Holds the age in milliseconds past which a history key is pruned. */
323
+ export const HISTORY_AGE_MS = 7 * 24 * 60 * 60 * 1000
324
+
325
+ /** Holds the count of history keys kept, the latest by their newest record. */
326
+ export const HISTORY_KEYS = 512
327
+
328
+ /**
329
+ * Holds the longest wait in milliseconds for a sampler to ready before its holder starts the command
330
+ * unmeasured.
331
+ *
332
+ * @remarks
333
+ * The wait outlasts a sampler's start on a loaded host, and it bounds what a sampler that neither
334
+ * readies nor exits costs the lane.
335
+ */
336
+ export const READY_MS = 5000
337
+
338
+ /**
339
+ * Holds the longest wait in milliseconds for a sampler's handover sample and for its exit after its
340
+ * stdin closes.
341
+ *
342
+ * @remarks
343
+ * A warm process query answered in about 140 ms on the Windows host measured 2026-11-12, so the wait
344
+ * outlasts a query on a loaded host, and it bounds what a sampler that hangs after it readied costs
345
+ * the lane at handover.
346
+ */
347
+ export const HANDOVER_MS = 5000
348
+
246
349
  /** Holds the pause in milliseconds between two samples of a holder's tree. */
247
350
  export const SAMPLE_MS = 1000
248
351
 
@@ -306,6 +409,49 @@ export const DOTTED_FLAG = /^--[^=.]+\.[^=]+$/u
306
409
  /** Lists the package managers whose verbs and scripts a seed reads. */
307
410
  export const MANAGERS: readonly string[] = ['npm', 'pnpm', 'yarn', 'bun']
308
411
 
412
+ /** Lists the package-manager verbs that run a tool, which a seed reads through to the tool. */
413
+ export const EXEC_VERBS: readonly string[] = ['exec', 'x', 'dlx']
414
+
415
+ /** Lists, by tool, the exec flags that take a separate value, so a seed reads no flag value as the tool. */
416
+ export const EXEC_VALUE_FLAGS: Readonly<Record<string, readonly string[]>> = Object.freeze({
417
+ npm: Object.freeze(['--package', '-p', '--workspace', '-w']),
418
+ npx: Object.freeze(['--package', '-p', '--workspace', '-w']),
419
+ pnpm: Object.freeze(['--package']),
420
+ pnpx: Object.freeze(['--package']),
421
+ yarn: Object.freeze(['--package']),
422
+ bun: Object.freeze(['--package']),
423
+ bunx: Object.freeze(['--package']),
424
+ })
425
+
426
+ /**
427
+ * Lists, by package manager, the flags before the verb that take a separate value, so a seed reads no
428
+ * flag value as the verb.
429
+ *
430
+ * @remarks
431
+ * npm's `-w` names a workspace and takes a value; pnpm's `-w` is the boolean `--workspace-root`.
432
+ */
433
+ export const MANAGER_VALUE_FLAGS: Readonly<Record<string, readonly string[]>> = Object.freeze({
434
+ npm: Object.freeze(['--prefix', '--workspace', '-w']),
435
+ pnpm: Object.freeze(['--dir', '-C', '--filter', '-F']),
436
+ yarn: Object.freeze(['--cwd']),
437
+ bun: Object.freeze(['--cwd']),
438
+ })
439
+
440
+ /** Lists the tools that run another tool the way `npx` does. */
441
+ export const NPX_TOOLS: readonly string[] = ['npx', 'pnpx', 'bunx']
442
+
443
+ /** Lists the `npm exec` and `npx` flags that run inline shell text, which names no tool a seed reads. */
444
+ export const EXEC_INLINE_FLAGS: readonly string[] = ['-c', '--call']
445
+
446
+ /** Holds the tool name of the falsify skill's `mutate` script, whose run a seed reads by its wrapped command. */
447
+ export const MUTATION_TOOL = 'mutate'
448
+
449
+ /** Holds the `mutate` flag that names the edits file, which a run's key leaves out. */
450
+ export const MUTATION_FLAG = '--edits'
451
+
452
+ /** Holds the `mutate` flag that writes saved originals back, which edits source and wraps no command. */
453
+ export const RESTORE_FLAG = '--restore'
454
+
309
455
  /** Lists the tools a seed reads heavy by name: the release chain's step runner. */
310
456
  export const HEAVY_TOOLS: readonly string[] = ['steps']
311
457
 
@@ -344,8 +490,23 @@ export const SCOPED_SCRIPT = /^test:/u
344
490
  /** Matches one sampler row: process id, parent id, creation time in milliseconds, CPU time in 100 ns units, and private bytes. */
345
491
  export const GAUGE_PATTERN = /^(\d+) (\d+) (\d+) (\d+) (\d+)$/u
346
492
 
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)}}`
493
+ /** Holds the line a sampler prints when its first process query has run, which readies it. */
494
+ export const READY_LINE = 'ready'
495
+
496
+ /** Holds the byte a holder writes to its sampler to ask for one sample at once. */
497
+ export const SAMPLE_BYTE = 's'
498
+
499
+ /**
500
+ * Holds the PowerShell text of a sampler.
501
+ *
502
+ * @remarks
503
+ * The child runs one process query, the one a sample runs, so its first sample answers warm, and
504
+ * prints {@link READY_LINE}. Until the first byte it waits on its
505
+ * stdin with no timer. Each byte on its stdin starts one sample at once, and after the first byte it
506
+ * also samples every {@link SAMPLE_MS}. A sample prints one line: `1` for a sample a byte asked for or `0`, a `|`,
507
+ * and the rows separated by semicolons. The child exits when its stdin closes.
508
+ */
509
+ export const SAMPLER_COMMAND = `$i=[Console]::OpenStandardInput();$b=New-Object byte[] 1;$t=$i.ReadAsync($b,0,1);$null=Get-CimInstance Win32_Process -Property ProcessId,ParentProcessId,CreationDate,KernelModeTime,UserModeTime,PrivatePageCount;[Console]::Out.WriteLine('${READY_LINE}');[Console]::Out.Flush();$a=$false;$q=0;$d=-1;while($true){if($a){$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([string]$q+'|'+($r -join ';'));[Console]::Out.Flush();$q=0};if($t.Wait($d)){if($t.Status -ne 'RanToCompletion' -or $t.Result -eq 0){break};$a=$true;$q=1;$d=${String(SAMPLE_MS)};$t=$i.ReadAsync($b,0,1)}}`
349
510
 
350
511
  /** Describes the footprint the light lanes add up: average cores, peak private bytes, and peak processes. */
351
512
  export interface Usage {
@@ -384,6 +545,18 @@ export interface Gauge extends Row {
384
545
  readonly memory: number
385
546
  }
386
547
 
548
+ /** Describes what a history prune did: the keys it removed and the names it skipped. */
549
+ export interface Prune {
550
+ readonly removed: readonly string[]
551
+ readonly skipped: readonly string[]
552
+ }
553
+
554
+ /** Describes one sample line: whether a byte asked for it, and its rows. */
555
+ export interface Sample {
556
+ readonly requested: boolean
557
+ readonly gauges: readonly Gauge[]
558
+ }
559
+
387
560
  /** Describes what a sampler has read: each member's latest CPU time by id and creation date, and the peaks. */
388
561
  export interface Tally {
389
562
  readonly cpu: ReadonlyMap<string, number>
@@ -399,7 +572,10 @@ export interface Measure {
399
572
  readonly light: Usage | undefined
400
573
  }
401
574
 
402
- /** Describes the complete record a stage file holds and a ticket publishes; `light` holds the footprint a light ticket counts. */
575
+ /**
576
+ * Describes the complete record a stage file holds and a ticket publishes; `light` holds the footprint
577
+ * a light ticket counts, and `edits` marks a `mutate` run that edits source in its working directory.
578
+ */
403
579
  export interface Ticket {
404
580
  readonly protocol: number
405
581
  readonly token: string
@@ -411,6 +587,7 @@ export interface Ticket {
411
587
  readonly arrived: string
412
588
  readonly light?: Usage
413
589
  readonly solo?: boolean
590
+ readonly edits?: boolean
414
591
  }
415
592
 
416
593
  /** Describes one ticket in the queue: its sequence and its record, undefined when unreadable. */
@@ -448,13 +625,25 @@ export type Turn =
448
625
  }
449
626
  | { readonly state: 'refused'; readonly reason: string }
450
627
 
628
+ /** Describes one process-table entry the group reading needs: its state and its process group. */
629
+ export interface Stat {
630
+ readonly state: string
631
+ readonly group: number
632
+ }
633
+
634
+ /** Describes one thread of a group member: its `<pid>/<tid>` key and its process-table state. */
635
+ export interface Task {
636
+ readonly id: string
637
+ readonly state: string
638
+ }
639
+
451
640
  /** Describes what a sweep confirmed: whether the tree reads as gone, and the members it left. */
452
641
  export interface Sweep {
453
642
  readonly gone: boolean
454
643
  readonly members: readonly number[]
455
644
  }
456
645
 
457
- /** Describes one ticket as `--status` reports it; `holding` marks a live ticket with a run record. */
646
+ /** Describes one ticket as `--status` reports it; `edits` marks a `mutate` run, and `holding` a live ticket with a run record. */
458
647
  export interface StatusRow {
459
648
  readonly sequence: number
460
649
  readonly label: string | undefined
@@ -462,6 +651,7 @@ export interface StatusRow {
462
651
  readonly state: 'live' | 'dead' | 'unread'
463
652
  readonly light: boolean
464
653
  readonly solo: boolean
654
+ readonly edits: boolean
465
655
  readonly holding: boolean
466
656
  }
467
657
 
@@ -693,7 +883,8 @@ export function isTicket(value: unknown): value is Ticket {
693
883
  'arrived' in value &&
694
884
  typeof value.arrived === 'string' &&
695
885
  (!('light' in value) || isUsage(value.light)) &&
696
- (!('solo' in value) || typeof value.solo === 'boolean')
886
+ (!('solo' in value) || typeof value.solo === 'boolean') &&
887
+ (!('edits' in value) || typeof value.edits === 'boolean')
697
888
  )
698
889
  }
699
890
 
@@ -896,9 +1087,17 @@ export function removeFile(path: string): void {
896
1087
  * @param light - The footprint a light ticket counts, or undefined for a heavy ticket.
897
1088
  * @param solo - If `true`, marks a ticket that waits out every earlier light ticket; if `false`, omits
898
1089
  * the field.
899
- * @returns The complete ticket, carrying `light` and `solo` only when they are set.
1090
+ * @param edits - If `true`, marks a `mutate` run that edits source in its working directory; if
1091
+ * `false`, omits the field.
1092
+ * @returns The complete ticket, carrying `light`, `solo`, and `edits` only when they are set.
900
1093
  */
901
- export function buildTicket(token: string, label: string, light?: Usage, solo = false): Ticket {
1094
+ export function buildTicket(
1095
+ token: string,
1096
+ label: string,
1097
+ light?: Usage,
1098
+ solo = false,
1099
+ edits = false,
1100
+ ): Ticket {
902
1101
  return {
903
1102
  protocol: PROTOCOL,
904
1103
  token,
@@ -910,6 +1109,7 @@ export function buildTicket(token: string, label: string, light?: Usage, solo =
910
1109
  arrived: new Date().toISOString(),
911
1110
  ...(light === undefined ? {} : { light }),
912
1111
  ...(solo ? { solo } : {}),
1112
+ ...(edits ? { edits } : {}),
913
1113
  }
914
1114
  }
915
1115
 
@@ -994,14 +1194,98 @@ export function readOutcomes(root: string, key: string): ReadonlyArray<Outcome |
994
1194
  * @param key - The command's key.
995
1195
  * @param name - The record's name.
996
1196
  * @param outcome - The record.
1197
+ * @returns True when the write created the key's directory; false when the key existed.
997
1198
  */
998
- export function writeOutcome(root: string, key: string, name: string, outcome: Outcome): void {
1199
+ export function writeOutcome(root: string, key: string, name: string, outcome: Outcome): boolean {
999
1200
  const directory = join(root, HISTORY_DIRECTORY, key)
1000
- mkdirSync(directory, { recursive: true })
1201
+ const created = mkdirSync(directory, { recursive: true }) !== undefined
1001
1202
  writeFileSync(join(directory, name), JSON.stringify(outcome), { flag: 'wx' })
1002
1203
  for (const stale of readOutcomeNames(root, key).slice(0, -RECENT_RUNS)) {
1003
1204
  removeFile(join(directory, stale))
1004
1205
  }
1206
+ return created
1207
+ }
1208
+
1209
+ /**
1210
+ * Reads when a history key was last written.
1211
+ *
1212
+ * @param root - The queue root.
1213
+ * @param key - The key.
1214
+ * @returns The end time its newest record's name opens with; the directory's modification time when
1215
+ * it holds no record; `gone` when the entry no longer exists; `unread` when the host refuses to list
1216
+ * it, as it does for a file that is no directory.
1217
+ */
1218
+ export function readKeyTime(root: string, key: string): number | 'gone' | 'unread' {
1219
+ try {
1220
+ const newest = readOutcomeNames(root, key).at(-1)
1221
+ if (newest !== undefined) return Number(newest.slice(0, ENDED_WIDTH))
1222
+ return statSync(join(root, HISTORY_DIRECTORY, key)).mtimeMs
1223
+ } catch (error) {
1224
+ return readCode(error) === 'ENOENT' ? 'gone' : 'unread'
1225
+ }
1226
+ }
1227
+
1228
+ /**
1229
+ * Lists the names under the history directory.
1230
+ *
1231
+ * @param root - The queue root.
1232
+ * @returns The names, empty when the directory is absent; undefined when the host refuses to list it.
1233
+ */
1234
+ export function readHistoryNames(root: string): readonly string[] | undefined {
1235
+ try {
1236
+ return readNames(join(root, HISTORY_DIRECTORY))
1237
+ } catch {
1238
+ return undefined
1239
+ }
1240
+ }
1241
+
1242
+ /**
1243
+ * Removes one history key inside the removal budget.
1244
+ *
1245
+ * @param root - The queue root.
1246
+ * @param key - The key.
1247
+ * @returns True when the key is gone; false when the host refused the removal.
1248
+ */
1249
+ export function removeKey(root: string, key: string): boolean {
1250
+ try {
1251
+ rmSync(join(root, HISTORY_DIRECTORY, key), {
1252
+ recursive: true,
1253
+ force: true,
1254
+ maxRetries: REMOVAL_RETRIES,
1255
+ retryDelay: REMOVAL_DELAY_MS,
1256
+ })
1257
+ return true
1258
+ } catch {
1259
+ return false
1260
+ }
1261
+ }
1262
+
1263
+ /**
1264
+ * Prunes the history to the keys written inside {@link HISTORY_AGE_MS}, at most the
1265
+ * {@link HISTORY_KEYS} written last.
1266
+ *
1267
+ * @remarks
1268
+ * The prune throws nothing, so it never changes the lane's exit: a name the host refuses to list or
1269
+ * remove stays and is reported as skipped.
1270
+ *
1271
+ * @param root - The queue root.
1272
+ * @param now - The current time in epoch milliseconds.
1273
+ * @returns The keys removed, and the names skipped: `history` itself when it cannot be listed.
1274
+ */
1275
+ export function pruneHistory(root: string, now: number): Prune {
1276
+ const names = readHistoryNames(root)
1277
+ if (names === undefined) return { removed: [], skipped: [HISTORY_DIRECTORY] }
1278
+ const times = names.map((key) => ({ key, time: readKeyTime(root, key) }))
1279
+ const unread = times.flatMap((item) => (item.time === 'unread' ? [item.key] : []))
1280
+ const results = times
1281
+ .flatMap((item) => (typeof item.time === 'number' ? [{ key: item.key, time: item.time }] : []))
1282
+ .toSorted((left, right) => right.time - left.time)
1283
+ .filter((item, index) => index >= HISTORY_KEYS || item.time < now - HISTORY_AGE_MS)
1284
+ .map((item) => ({ key: item.key, removed: removeKey(root, item.key) }))
1285
+ return {
1286
+ removed: results.flatMap((item) => (item.removed ? [item.key] : [])),
1287
+ skipped: [...unread, ...results.flatMap((item) => (item.removed ? [] : [item.key]))],
1288
+ }
1005
1289
  }
1006
1290
 
1007
1291
  /**
@@ -1134,10 +1418,12 @@ export function readToolName(path: string): string {
1134
1418
  }
1135
1419
 
1136
1420
  /**
1137
- * Reads the tool a command runs and the tool's arguments, past Node and `npx`.
1421
+ * Reads the tool a command runs and the tool's arguments, past Node, `npx`, `pnpx`, `bunx`, and a
1422
+ * package manager's `exec`, `x`, or `dlx` verb.
1138
1423
  *
1139
1424
  * @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.
1425
+ * @returns The tool's name followed by its arguments; empty for inline Node code, inline exec text,
1426
+ * or no script.
1141
1427
  */
1142
1428
  export function readTool(command: readonly string[]): readonly string[] {
1143
1429
  const [executable, ...rest] = command
@@ -1151,13 +1437,166 @@ export function readTool(command: readonly string[]): readonly string[] {
1151
1437
  }
1152
1438
  return readTool(rest.slice(script))
1153
1439
  }
1154
- if (name === 'npx') {
1155
- const tool = rest.findIndex((argument) => !argument.startsWith('-'))
1156
- return tool === -1 ? [] : readTool(rest.slice(tool))
1440
+ if (NPX_TOOLS.includes(name)) return readExecTool(rest, EXEC_VALUE_FLAGS[name])
1441
+ if (MANAGERS.includes(name)) {
1442
+ const flags = MANAGER_VALUE_FLAGS[name] ?? []
1443
+ const verb = rest.findIndex(
1444
+ (argument, index) => !argument.startsWith('-') && !flags.includes(rest[index - 1] ?? ''),
1445
+ )
1446
+ if (EXEC_VERBS.includes(rest[verb] ?? '')) {
1447
+ return readExecTool(rest.slice(verb + 1), EXEC_VALUE_FLAGS[name])
1448
+ }
1157
1449
  }
1158
1450
  return [name, ...rest]
1159
1451
  }
1160
1452
 
1453
+ /**
1454
+ * Reads the tool an `npx` or `npm exec` call runs, from the arguments after the verb.
1455
+ *
1456
+ * @remarks
1457
+ * The tool is the first argument before a bare `--` that is neither a flag nor the value of a
1458
+ * listed flag, else the first argument after the bare `--`. A flag {@link EXEC_INLINE_FLAGS} names
1459
+ * before the tool runs shell text instead.
1460
+ *
1461
+ * @param args - The arguments after `npx` or after the exec verb.
1462
+ * @param valueFlags - The flags that take a separate value, from {@link EXEC_VALUE_FLAGS}. Default:
1463
+ * none.
1464
+ * @returns The tool's name followed by its arguments; empty for inline text or no tool.
1465
+ */
1466
+ export function readExecTool(
1467
+ args: readonly string[],
1468
+ valueFlags: readonly string[] = [],
1469
+ ): readonly string[] {
1470
+ const end = args.indexOf('--')
1471
+ const named = args.findIndex(
1472
+ (argument, index) =>
1473
+ (end === -1 || index < end) &&
1474
+ !argument.startsWith('-') &&
1475
+ !valueFlags.includes(args[index - 1] ?? ''),
1476
+ )
1477
+ const start = named !== -1 ? named : end === -1 ? -1 : end + 1
1478
+ if (start === -1 || start >= args.length) return []
1479
+ const inline = args
1480
+ .slice(0, start)
1481
+ .some(
1482
+ (flag) =>
1483
+ EXEC_INLINE_FLAGS.includes(flag) ||
1484
+ EXEC_INLINE_FLAGS.some((name) => flag.startsWith(`${name}=`)),
1485
+ )
1486
+ return inline ? [] : readTool(args.slice(start))
1487
+ }
1488
+
1489
+ /**
1490
+ * Checks whether a command is a `mutate --restore` run, which writes source files back.
1491
+ *
1492
+ * @param command - The command and its arguments.
1493
+ * @returns True for a `mutate` call with its restore flag before any bare `--`; false otherwise.
1494
+ */
1495
+ export function matchesRestore(command: readonly string[]): boolean {
1496
+ const [tool, ...args] = readTool(command)
1497
+ if (tool !== MUTATION_TOOL) return false
1498
+ const end = args.indexOf('--')
1499
+ return (end === -1 ? args : args.slice(0, end)).some(
1500
+ (flag) => flag === RESTORE_FLAG || flag.startsWith(`${RESTORE_FLAG}=`),
1501
+ )
1502
+ }
1503
+
1504
+ /**
1505
+ * Extracts the command a `mutate` run wraps.
1506
+ *
1507
+ * @param command - The command and its arguments.
1508
+ * @returns The arguments after the run's own bare `--`; undefined for any other command, or a
1509
+ * `mutate` call with no edits file or no wrapped command.
1510
+ */
1511
+ export function extractMutation(command: readonly string[]): readonly string[] | undefined {
1512
+ const [tool, ...args] = readTool(command)
1513
+ if (tool !== MUTATION_TOOL) return undefined
1514
+ const end = args.indexOf('--')
1515
+ if (end === -1) return undefined
1516
+ const edits = args
1517
+ .slice(0, end)
1518
+ .some((flag) => flag === MUTATION_FLAG || flag.startsWith(`${MUTATION_FLAG}=`))
1519
+ const wrapped = args.slice(end + 1)
1520
+ return edits && wrapped.length > 0 ? wrapped : undefined
1521
+ }
1522
+
1523
+ /**
1524
+ * Normalizes a command to the arguments its key hashes.
1525
+ *
1526
+ * @remarks
1527
+ * A `mutate` run names a fresh edits file each time, so its key leaves the edits flag and its value
1528
+ * out, and every run of one wrapped command from one directory shares a key. The cut reads only the
1529
+ * script's own flags, between the script and its own bare `--`, so a launcher's `--` before the
1530
+ * script moves nothing.
1531
+ *
1532
+ * @param command - The command and its arguments.
1533
+ * @returns A `mutate` run without its edits flag and value; any other command unchanged.
1534
+ */
1535
+ export function normalizeCommand(command: readonly string[]): readonly string[] {
1536
+ if (extractMutation(command) === undefined) return command
1537
+ const start = command.length - readTool(command).length + 1
1538
+ const end = command.indexOf('--', start)
1539
+ return command.filter(
1540
+ (argument, index) =>
1541
+ index < start ||
1542
+ index >= end ||
1543
+ !(
1544
+ argument === MUTATION_FLAG ||
1545
+ argument.startsWith(`${MUTATION_FLAG}=`) ||
1546
+ command[index - 1] === MUTATION_FLAG
1547
+ ),
1548
+ )
1549
+ }
1550
+
1551
+ /**
1552
+ * Normalizes a working directory for the comparison that decides whether two tickets share it.
1553
+ *
1554
+ * @remarks
1555
+ * Every side of the comparison passes through this one function. It reads the real path through
1556
+ * `realpathSync.native`, which returns the name and the case the file system stores, so two
1557
+ * spellings of one directory compare equal without folding case.
1558
+ *
1559
+ * @param path - The directory.
1560
+ * @returns The real path; the resolved path when it cannot be read, as for a vanished directory.
1561
+ */
1562
+ export function normalizeDirectory(path: string): string {
1563
+ try {
1564
+ return realpathSync.native(path)
1565
+ } catch {
1566
+ return resolvePath(path)
1567
+ }
1568
+ }
1569
+
1570
+ /**
1571
+ * Checks whether two working directories share source.
1572
+ *
1573
+ * @remarks
1574
+ * Both sides pass through {@link normalizeDirectory}, so a child directory, such as a check run from
1575
+ * `packages/a`, shares source with a mutation at the checkout root, and the reverse.
1576
+ *
1577
+ * @param left - One directory.
1578
+ * @param right - The other directory.
1579
+ * @returns True when the two normalize to one directory or one sits inside the other at a separator
1580
+ * boundary; false otherwise.
1581
+ */
1582
+ export function sharesDirectory(left: string, right: string): boolean {
1583
+ const one = normalizeDirectory(left)
1584
+ const other = normalizeDirectory(right)
1585
+ return one === other || matchesInside(one, other) || matchesInside(other, one)
1586
+ }
1587
+
1588
+ /**
1589
+ * Checks whether a normalized path sits inside another at a separator boundary.
1590
+ *
1591
+ * @param inner - The path that might sit inside.
1592
+ * @param outer - The path that might contain it.
1593
+ * @returns True when `inner` opens with `outer` and a separator; false otherwise, the same path
1594
+ * included.
1595
+ */
1596
+ export function matchesInside(inner: string, outer: string): boolean {
1597
+ return inner.startsWith(outer.endsWith(sep) ? outer : `${outer}${sep}`)
1598
+ }
1599
+
1161
1600
  /**
1162
1601
  * Reads the positional arguments of a command, skipping each value of a value-taking flag.
1163
1602
  *
@@ -1222,7 +1661,8 @@ export function readVitestSeed(args: readonly string[]): Seed | undefined {
1222
1661
  *
1223
1662
  * @remarks
1224
1663
  * 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.
1664
+ * chain seeds heavy wherever it appears, before any light kind is read. A `mutate --restore` run,
1665
+ * which writes source files back and wraps no command, seeds heavy.
1226
1666
  *
1227
1667
  * @param command - The command and its arguments.
1228
1668
  * @returns The seeded lane, or undefined when no kind names the command.
@@ -1231,9 +1671,9 @@ export function readSeed(command: readonly string[]): Seed | undefined {
1231
1671
  if (readWords(command.slice(1)).some((word) => HEAVY_WORDS.includes(word))) return 'heavy'
1232
1672
  const [tool, ...args] = readTool(command)
1233
1673
  if (tool === undefined) return undefined
1234
- if (HEAVY_TOOLS.includes(tool)) return 'heavy'
1674
+ if (HEAVY_TOOLS.includes(tool) || matchesRestore(command)) return 'heavy'
1235
1675
  if (MANAGERS.includes(tool)) {
1236
- const [verb, script] = readOperands(args, [])
1676
+ const [verb, script] = readOperands(args, MANAGER_VALUE_FLAGS[tool] ?? [])
1237
1677
  if (verb === undefined) return undefined
1238
1678
  if (HEAVY_VERBS.includes(verb)) return 'heavy'
1239
1679
  return (verb === 'run' || verb === 'run-script') && script !== undefined
@@ -1304,7 +1744,10 @@ export function linkStage(root: string, token: string): number {
1304
1744
  * @remarks
1305
1745
  * The two listings are separate, because one listing can miss both a ticket linked and a stage file
1306
1746
  * removed while it runs. A stage file absent from the first listing belongs to a process whose own
1307
- * listing sees this ticket, or to a ticket the second listing sees.
1747
+ * listing sees this ticket, or to a ticket the second listing sees. A ticket holds only when the
1748
+ * directory rule of {@link decideDirectory} names no ticket to wait on and its own lane's rule admits
1749
+ * it. Every rule names only an earlier ticket, and an earlier ticket can only leave, so no two tickets
1750
+ * wait on each other and no cycle of waits can form.
1308
1751
  *
1309
1752
  * @param root - The queue root.
1310
1753
  * @param sequence - This process's sequence.
@@ -1325,18 +1768,46 @@ export function decideTurn(root: string, sequence: number, token: string, limits
1325
1768
  }
1326
1769
  const own = entries[position]?.ticket
1327
1770
  const earlier = entries.slice(0, position)
1771
+ const shared = own === undefined ? undefined : decideDirectory(earlier, own)
1772
+ if (shared !== undefined) return shared
1328
1773
  return own?.light === undefined || limits === undefined
1329
1774
  ? decideHeavy(earlier, own?.solo === true)
1330
1775
  : decideLight(root, earlier, own.light, limits)
1331
1776
  }
1332
1777
 
1778
+ /**
1779
+ * Decides which earlier ticket the directory rule makes a ticket wait on, whatever its lane.
1780
+ *
1781
+ * @remarks
1782
+ * Every ticket waits on the nearest earlier ticket that carries `edits` and shares its working
1783
+ * directory, because a `mutate` run edits source that ticket reads. A ticket that carries `edits`
1784
+ * also waits on the nearest earlier ticket of its working directory in either lane, and on an
1785
+ * earlier ticket it cannot read, which might share the directory; that wait refuses. The rule names
1786
+ * only earlier tickets, which can only leave, so it adds no cycle of waits. {@link normalizeDirectory}
1787
+ * reads both sides of every comparison.
1788
+ *
1789
+ * @param earlier - The tickets before this one, in arrival order.
1790
+ * @param own - This process's ticket.
1791
+ * @returns The ticket to wait on; undefined when the rule names none.
1792
+ */
1793
+ export function decideDirectory(earlier: readonly Entry[], own: Ticket): Turn | undefined {
1794
+ const entry = earlier.findLast((item) => {
1795
+ if (item.ticket === undefined) return own.edits === true
1796
+ return (
1797
+ (own.edits === true || item.ticket.edits === true) &&
1798
+ sharesDirectory(own.cwd, item.ticket.cwd)
1799
+ )
1800
+ })
1801
+ return entry === undefined ? undefined : { state: 'behind', entry }
1802
+ }
1803
+
1333
1804
  /**
1334
1805
  * Decides what a heavy ticket does next.
1335
1806
  *
1336
1807
  * @remarks
1337
1808
  * A heavy ticket waits on the nearest earlier ticket that is not light, an unreadable one included. A
1338
1809
  * `--solo` ticket waits on the nearest earlier ticket of either lane, so it holds with no light
1339
- * holder beside it.
1810
+ * holder beside it. The rule names only an earlier ticket, so it adds no cycle of waits.
1340
1811
  *
1341
1812
  * @param earlier - The tickets before this one, in arrival order.
1342
1813
  * @param solo - If `true`, waits on light tickets too; if `false`, passes them.
@@ -1375,9 +1846,12 @@ export function decideLight(
1375
1846
  if (unread !== undefined) return { state: 'behind', entry: unread }
1376
1847
  const lights = earlier.filter((entry) => entry.ticket?.light !== undefined)
1377
1848
  const solos = earlier.filter((entry) => entry.ticket?.solo === true)
1378
- const pending = lights.flatMap((entry) =>
1379
- readRun(root, entry.sequence) === 'absent' ? [entry.sequence] : [],
1380
- )
1849
+ const pending = lights.flatMap((entry) => {
1850
+ const blocked =
1851
+ entry.ticket !== undefined &&
1852
+ decideDirectory(earlier.slice(0, earlier.indexOf(entry)), entry.ticket) !== undefined
1853
+ return !blocked && readRun(root, entry.sequence) === 'absent' ? [entry.sequence] : []
1854
+ })
1381
1855
  const usages = lights.flatMap((entry) =>
1382
1856
  entry.ticket?.light === undefined ? [] : [entry.ticket.light],
1383
1857
  )
@@ -1528,18 +2002,181 @@ export function selectMembers<T extends Row>(
1528
2002
  }
1529
2003
 
1530
2004
  /**
1531
- * Reads whether a process group still has a member.
2005
+ * Parses one process-table `stat` line into its state and its process group.
2006
+ *
2007
+ * @remarks
2008
+ * The command name sits in parentheses and can hold spaces and parentheses itself, so the fields
2009
+ * are read after the last `)`: the state, the parent id, then the group id.
2010
+ *
2011
+ * @param text - The content of `/proc/<pid>/stat`.
2012
+ * @returns The state and the group, or undefined when the text does not have that form.
2013
+ */
2014
+ export function parseStat(text: string): Stat | undefined {
2015
+ const close = text.lastIndexOf(')')
2016
+ if (close === -1) return undefined
2017
+ const [state, , group] = text.slice(close + 2).split(' ')
2018
+ return state === undefined || state === '' || group === undefined || !/^\d+$/u.test(group)
2019
+ ? undefined
2020
+ : { state, group: Number(group) }
2021
+ }
2022
+
2023
+ /**
2024
+ * Lists the entries of one process-table directory.
1532
2025
  *
2026
+ * @param path - The directory.
2027
+ * @returns The entry names, or undefined when the listing fails.
2028
+ */
2029
+ export function readListing(path: string): readonly string[] | undefined {
2030
+ try {
2031
+ return readdirSync(path)
2032
+ } catch {
2033
+ return undefined
2034
+ }
2035
+ }
2036
+
2037
+ /**
2038
+ * Reads one thread's state from its own process-table entry.
2039
+ *
2040
+ * @param pid - The process id, as its process-table entry names it.
2041
+ * @param tid - The thread id, as the process's `task` listing names it.
2042
+ * @param table - The process table's root. Default: {@link PROCESS_TABLE}.
2043
+ * @returns The task keyed `<pid>/<tid>`, or undefined when its `stat` cannot be read or parsed.
2044
+ */
2045
+ export function readTask(pid: string, tid: string, table = PROCESS_TABLE): Task | undefined {
2046
+ try {
2047
+ const stat = parseStat(readFileSync(join(table, pid, 'task', tid, 'stat'), 'utf8'))
2048
+ return stat === undefined ? undefined : { id: `${pid}/${tid}`, state: stat.state }
2049
+ } catch {
2050
+ return undefined
2051
+ }
2052
+ }
2053
+
2054
+ /**
2055
+ * Reads the state of every thread of one process from the process table.
2056
+ *
2057
+ * @param pid - The process id, as its process-table entry names it.
2058
+ * @returns One task per thread, keyed `<pid>/<tid>`, or undefined when the `task` listing fails,
2059
+ * lists no thread, or holds a thread whose `stat` cannot be read: what the reading cannot read
2060
+ * counts as present.
2061
+ * @param table - The process table's root. Default: {@link PROCESS_TABLE}.
2062
+ */
2063
+ export function readThreads(pid: string, table = PROCESS_TABLE): readonly Task[] | undefined {
2064
+ const tids = readListing(join(table, pid, 'task'))
2065
+ if (tids === undefined || tids.length === 0) return undefined
2066
+ const tasks = tids.map((tid) => readTask(pid, tid, table))
2067
+ return tasks.includes(undefined)
2068
+ ? undefined
2069
+ : tasks.flatMap((task) => (task === undefined ? [] : [task]))
2070
+ }
2071
+
2072
+ /**
2073
+ * Reads the threads of one process-table entry when it belongs to a process group.
2074
+ *
2075
+ * @param name - The process id, as the process-table listing names it.
1533
2076
  * @param group - The group id.
1534
- * @returns The group id while the host reports the group; empty when it reports none.
2077
+ * @returns The entry's threads when it belongs to the group, none when it belongs to another group
2078
+ * or its `stat` is gone (`ENOENT`, a process that ended), or undefined when its `stat` cannot be
2079
+ * read for any other reason or cannot be parsed, or its threads cannot be read.
2080
+ * @param table - The process table's root. Default: {@link PROCESS_TABLE}.
1535
2081
  */
1536
- export function readGroup(group: number): readonly number[] {
2082
+ export function readMember(
2083
+ name: string,
2084
+ group: number,
2085
+ table = PROCESS_TABLE,
2086
+ ): readonly Task[] | undefined {
2087
+ try {
2088
+ const stat = parseStat(readFileSync(join(table, name, 'stat'), 'utf8'))
2089
+ if (stat === undefined) return undefined
2090
+ return stat.group === group ? readThreads(name, table) : []
2091
+ } catch (error) {
2092
+ return readCode(error) === 'ENOENT' ? [] : undefined
2093
+ }
2094
+ }
2095
+
2096
+ /**
2097
+ * Reads every thread of every member of a process group from the process table.
2098
+ *
2099
+ * @param group - The group id.
2100
+ * @returns One task per thread of each member, or undefined when the host publishes no process
2101
+ * table, the table cannot be listed, or any entry cannot be read; a process whose `stat` is gone
2102
+ * is skipped.
2103
+ * @param table - The process table's root. Default: {@link PROCESS_TABLE}.
2104
+ */
2105
+ export function readTasks(group: number, table = PROCESS_TABLE): readonly Task[] | undefined {
2106
+ if (!existsSync(join(table, 'self', 'stat'))) return undefined
2107
+ const names = readListing(table)
2108
+ if (names === undefined) return undefined
2109
+ const members = names
2110
+ .filter((name) => /^\d+$/u.test(name))
2111
+ .map((name) => readMember(name, group, table))
2112
+ return members.includes(undefined)
2113
+ ? undefined
2114
+ : members.flatMap((member) => (member === undefined ? [] : member))
2115
+ }
2116
+
2117
+ /**
2118
+ * Checks whether two readings of one group show the same threads, every one of them exited.
2119
+ *
2120
+ * @remarks
2121
+ * A thread read as exited cannot start another process or thread after that read, so every process
2122
+ * that joined the group and every thread created before the first reading finished exists when the
2123
+ * second listing starts. A second reading of the same tasks therefore leaves none of them out, and a
2124
+ * member that forked between its listing and its read shows up as a task the first reading lacks.
2125
+ * An empty reading reads as not ended, because the probe signal reached a member the table did not
2126
+ * show, as a table from another PID namespace does.
2127
+ *
2128
+ * @param first - The first reading.
2129
+ * @param second - The reading taken after the first finished.
2130
+ * @returns True if both readings hold at least one task, list the same task ids, and show every
2131
+ * task as {@link ENDED_STATES}; false otherwise.
2132
+ */
2133
+ export function matchesEnded(first: readonly Task[], second: readonly Task[]): boolean {
2134
+ return (
2135
+ first.length > 0 &&
2136
+ first
2137
+ .map((task) => task.id)
2138
+ .toSorted()
2139
+ .join(' ') ===
2140
+ second
2141
+ .map((task) => task.id)
2142
+ .toSorted()
2143
+ .join(' ') &&
2144
+ [...first, ...second].every((task) => ENDED_STATES.includes(task.state))
2145
+ )
2146
+ }
2147
+
2148
+ /**
2149
+ * Reads whether a process group still has a member that has not exited.
2150
+ *
2151
+ * @remarks
2152
+ * A signal reaches a zombie, so a group whose members have all exited still answers the probe
2153
+ * signal until their parent reaps them, which an init that does not reap as a child ends leaves
2154
+ * for later. Where the host publishes a process table, a group reads as ended when two readings
2155
+ * taken one after the other show the same threads of its members, every one {@link ENDED_STATES},
2156
+ * per {@link matchesEnded}. A zombie whose threads have all exited holds no CPU, memory, or file
2157
+ * handle; a process whose main thread exited while another thread runs shows `Z` for itself and
2158
+ * reads as present through that thread. A host without that table, and a reading that cannot read
2159
+ * part of it, read such a group as present.
2160
+ *
2161
+ * @param group - The group id.
2162
+ * @param read - Takes one reading of the group's threads; undefined means the reading could not
2163
+ * read the table. Default: {@link readTasks}.
2164
+ * @returns The group id while the host reports a member that has not exited or the reading
2165
+ * cannot read the table; empty when it reports none.
2166
+ */
2167
+ export function readGroup(
2168
+ group: number,
2169
+ read: (group: number) => readonly Task[] | undefined = readTasks,
2170
+ ): readonly number[] {
1537
2171
  try {
1538
2172
  process.kill(-group, 0)
1539
- return [group]
1540
2173
  } catch (error) {
1541
2174
  return readCode(error) === 'ESRCH' ? [] : [group]
1542
2175
  }
2176
+ const first = read(group)
2177
+ if (first === undefined) return [group]
2178
+ const second = read(group)
2179
+ return second !== undefined && matchesEnded(first, second) ? [] : [group]
1543
2180
  }
1544
2181
 
1545
2182
  /**
@@ -1557,14 +2194,29 @@ export function readTree(run: Run, ceiling: number): readonly number[] | undefin
1557
2194
  if (run.launcher === undefined) return undefined
1558
2195
  if (process.platform !== 'win32') return readGroup(run.launcher)
1559
2196
  const rows = readSnapshot()
1560
- return rows === undefined
1561
- ? undefined
1562
- : selectMembers(
1563
- rows,
1564
- run.command === undefined ? [run.launcher] : [run.launcher, run.command],
1565
- run.started - CLOCK_ALLOWANCE_MS,
1566
- ceiling,
1567
- ).map((row) => row.pid)
2197
+ return rows === undefined ? undefined : selectTree(rows, run, ceiling)
2198
+ }
2199
+
2200
+ /**
2201
+ * Selects the members of one run's process tree from a Windows snapshot.
2202
+ *
2203
+ * @param rows - The snapshot.
2204
+ * @param run - The run record.
2205
+ * @param ceiling - The latest creation date a row of an exited seed can carry.
2206
+ * @returns The members' ids, or undefined when the record names no launcher.
2207
+ */
2208
+ export function selectTree(
2209
+ rows: readonly Row[],
2210
+ run: Run,
2211
+ ceiling: number,
2212
+ ): readonly number[] | undefined {
2213
+ if (run.launcher === undefined) return undefined
2214
+ return selectMembers(
2215
+ rows,
2216
+ run.command === undefined ? [run.launcher] : [run.launcher, run.command],
2217
+ run.started - CLOCK_ALLOWANCE_MS,
2218
+ ceiling,
2219
+ ).map((row) => row.pid)
1568
2220
  }
1569
2221
 
1570
2222
  /**
@@ -1859,6 +2511,19 @@ export function waitForClose(child: ChildProcess): Promise<number | undefined> {
1859
2511
  })
1860
2512
  }
1861
2513
 
2514
+ /**
2515
+ * Waits for a started launcher to exit, which precedes the close of its streams.
2516
+ *
2517
+ * @param child - The started launcher.
2518
+ * @returns When it exited or failed, in epoch milliseconds.
2519
+ */
2520
+ export function waitForExit(child: ChildProcess): Promise<number> {
2521
+ return new Promise((resolve) => {
2522
+ child.once('error', () => resolve(Date.now()))
2523
+ child.once('exit', () => resolve(Date.now()))
2524
+ })
2525
+ }
2526
+
1862
2527
  /**
1863
2528
  * Writes a run record, leaving an unwritten id to the handover reading.
1864
2529
  *
@@ -1916,6 +2581,36 @@ export function parseGauges(line: string): readonly Gauge[] {
1916
2581
  })
1917
2582
  }
1918
2583
 
2584
+ /**
2585
+ * Waits for a promise within a bound.
2586
+ *
2587
+ * @param promise - The promise.
2588
+ * @param budget - The longest wait in milliseconds.
2589
+ * @returns The promise's value; undefined when the budget runs out first.
2590
+ */
2591
+ export async function waitForBound<T>(promise: Promise<T>, budget: number): Promise<T | undefined> {
2592
+ const timer = Promise.withResolvers<undefined>()
2593
+ const handle = setTimeout(() => timer.resolve(undefined), budget)
2594
+ try {
2595
+ return await Promise.race([promise, timer.promise])
2596
+ } finally {
2597
+ clearTimeout(handle)
2598
+ }
2599
+ }
2600
+
2601
+ /**
2602
+ * Parses one sample line of a sampler.
2603
+ *
2604
+ * @param line - One line of the sampler's stdout: `1` or `0`, a `|`, and the rows.
2605
+ * @returns Whether a byte asked for the sample, with its gauges; undefined for a line without the
2606
+ * marker, such as {@link READY_LINE}.
2607
+ */
2608
+ export function parseSample(line: string): Sample | undefined {
2609
+ const split = line.indexOf('|')
2610
+ if (split === -1) return undefined
2611
+ return { requested: line.slice(0, split) === '1', gauges: parseGauges(line.slice(split + 1)) }
2612
+ }
2613
+
1919
2614
  /**
1920
2615
  * Folds one sample's members into a tally.
1921
2616
  *
@@ -1981,7 +2676,8 @@ export function lowerPriority(pid: number): boolean {
1981
2676
  * @param key - The command's key.
1982
2677
  * @param name - The record's name.
1983
2678
  * @param outcome - The record.
1984
- * @returns True when the record was written; false otherwise.
2679
+ * @returns True when the write created the key's directory; false when the key existed or the host
2680
+ * refused the write.
1985
2681
  */
1986
2682
  export function tryWriteOutcome(
1987
2683
  root: string,
@@ -1990,8 +2686,7 @@ export function tryWriteOutcome(
1990
2686
  outcome: Outcome,
1991
2687
  ): boolean {
1992
2688
  try {
1993
- writeOutcome(root, key, name, outcome)
1994
- return true
2689
+ return writeOutcome(root, key, name, outcome)
1995
2690
  } catch {
1996
2691
  return false
1997
2692
  }
@@ -2001,37 +2696,54 @@ export function tryWriteOutcome(
2001
2696
  * Samples one holder's process tree through one PowerShell child at below-normal priority.
2002
2697
  *
2003
2698
  * @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.
2699
+ * The child starts at arrival and readies while the ticket waits, so a holder starts its command
2700
+ * only after the child can answer at once. A {@link Sampler.sample} call starts one sample at once;
2701
+ * after the first, the child also samples every {@link SAMPLE_MS}. The child exits when its stdin
2702
+ * closes, which {@link Sampler.stop} and the end of this process both do. A threshold, given for a
2703
+ * light run, calls the breach handler once with the launcher's id, on the first sample before
2704
+ * {@link Sampler.seal} whose memory or process count passes it.
2007
2705
  */
2008
2706
  export class Sampler {
2009
2707
  readonly #child: ChildProcess
2010
2708
  readonly #closed: Promise<void>
2011
- readonly #floor: number
2709
+ readonly #ready = Promise.withResolvers<boolean>()
2710
+ readonly #waiters = new Map<number, (gauges: readonly Gauge[] | undefined) => void>()
2012
2711
  readonly #threshold: Usage | undefined
2013
- readonly #breach: () => void
2712
+ readonly #breach: (launcher: number) => void
2014
2713
  #seeds: readonly number[] = []
2714
+ #floor: number | undefined
2715
+ #ceiling: number | undefined
2015
2716
  #tally: Tally = { cpu: new Map(), memory: 0, processes: 0 }
2016
2717
  #breached = false
2718
+ #asked = 0
2719
+ #answered = 0
2017
2720
 
2018
2721
  /**
2019
2722
  * Starts the sampler.
2020
2723
  *
2021
- * @param floor - The earliest creation date the tree can carry.
2022
2724
  * @param threshold - The light run's threshold, or undefined for a heavy run.
2023
- * @param breach - Called once when a sample passes the threshold.
2725
+ * @param breach - Called once with the launcher's id when a sample passes the threshold. The
2726
+ * launcher is the one seed the lane holds a live handle on until it exits, so ending its tree
2727
+ * reaches the command and never a reused id.
2728
+ * @param command - The PowerShell text the child runs, for a proof. Default: {@link SAMPLER_COMMAND}.
2024
2729
  */
2025
- constructor(floor: number, threshold: Usage | undefined, breach: () => void) {
2026
- this.#floor = floor
2730
+ constructor(
2731
+ threshold: Usage | undefined,
2732
+ breach: (launcher: number) => void,
2733
+ command = SAMPLER_COMMAND,
2734
+ ) {
2027
2735
  this.#threshold = threshold
2028
2736
  this.#breach = breach
2029
2737
  this.#child = spawn(
2030
2738
  'powershell.exe',
2031
- ['-NoProfile', '-NonInteractive', '-Command', SAMPLER_COMMAND],
2739
+ ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', command],
2032
2740
  { stdio: ['pipe', 'pipe', 'ignore'], windowsHide: true },
2033
2741
  )
2034
- this.#closed = waitForClose(this.#child).then(() => undefined)
2742
+ this.#closed = waitForClose(this.#child).then(() => {
2743
+ this.#ready.resolve(false)
2744
+ for (const resolve of this.#waiters.values()) resolve(undefined)
2745
+ this.#waiters.clear()
2746
+ })
2035
2747
  this.#child.stdin?.on('error', () => undefined)
2036
2748
  if (this.#child.pid !== undefined) lowerPriority(this.#child.pid)
2037
2749
  if (this.#child.stdout !== null) {
@@ -2056,38 +2768,135 @@ export class Sampler {
2056
2768
  return this.#breached
2057
2769
  }
2058
2770
 
2771
+ /**
2772
+ * Waits until the child can sample at once, within a budget.
2773
+ *
2774
+ * @param budget - The longest wait in milliseconds.
2775
+ * @returns A promise of true when the child readied; false when it ended first or the budget ran out.
2776
+ */
2777
+ async ready(budget: number): Promise<boolean> {
2778
+ return (await waitForBound(this.#ready.promise, budget)) ?? false
2779
+ }
2780
+
2059
2781
  /**
2060
2782
  * Names the ids whose trees later samples read.
2061
2783
  *
2062
2784
  * @param seeds - The launcher id and, once known, the command id.
2785
+ * @param floor - The earliest creation date the tree can carry.
2063
2786
  */
2064
- seed(seeds: readonly number[]): void {
2787
+ seed(seeds: readonly number[], floor: number): void {
2065
2788
  this.#seeds = seeds
2789
+ this.#floor = floor
2790
+ }
2791
+
2792
+ /**
2793
+ * Marks the launcher's exit: a later sample reads no member created after it and triggers no
2794
+ * breach, so a reused id after the exit is never ended.
2795
+ *
2796
+ * @param ceiling - When the launcher exited, in epoch milliseconds.
2797
+ */
2798
+ seal(ceiling: number): void {
2799
+ this.#ceiling = ceiling
2800
+ }
2801
+
2802
+ /**
2803
+ * Starts one sample at once.
2804
+ *
2805
+ * @param budget - The longest wait in milliseconds for the answer. Default: no bound.
2806
+ * @returns A promise of every row the sample read, taken after this call; undefined when the
2807
+ * child ends first, cannot take the request, or does not answer within the budget.
2808
+ */
2809
+ sample(budget?: number): Promise<readonly Gauge[] | undefined> {
2810
+ const stdin = this.#child.stdin
2811
+ if (
2812
+ stdin === null ||
2813
+ stdin.writableEnded ||
2814
+ this.#child.pid === undefined ||
2815
+ this.#child.exitCode !== null ||
2816
+ this.#child.signalCode !== null
2817
+ ) {
2818
+ return Promise.resolve(undefined)
2819
+ }
2820
+ this.#asked += 1
2821
+ const answer = Promise.withResolvers<readonly Gauge[] | undefined>()
2822
+ this.#waiters.set(this.#asked, answer.resolve)
2823
+ stdin.write(SAMPLE_BYTE)
2824
+ return budget === undefined ? answer.promise : waitForBound(answer.promise, budget)
2825
+ }
2826
+
2827
+ /**
2828
+ * Samples back to back until a time or an abort, one sample after the previous one answers.
2829
+ *
2830
+ * @param until - The epoch millisecond after which no further sample starts.
2831
+ * @param signal - Ends the burst after the sample in flight.
2832
+ * @returns A promise that resolves when the burst ends.
2833
+ */
2834
+ async burst(until: number, signal: AbortSignal): Promise<void> {
2835
+ const rows = await this.sample()
2836
+ if (rows === undefined || signal.aborted || Date.now() >= until) return
2837
+ await this.burst(until, signal)
2066
2838
  }
2067
2839
 
2068
2840
  /**
2069
- * Closes the sampler's stdin, which ends it.
2841
+ * Closes the sampler's stdin, which ends it, and ends the child at once when it has not exited
2842
+ * within {@link HANDOVER_MS}.
2070
2843
  *
2071
2844
  * @returns A promise that resolves when the sampler has exited.
2072
2845
  */
2073
- stop(): Promise<void> {
2846
+ async stop(): Promise<void> {
2074
2847
  this.#child.stdin?.end()
2848
+ const exited = await waitForBound(
2849
+ this.#closed.then(() => true),
2850
+ HANDOVER_MS,
2851
+ )
2852
+ if (exited === undefined) await this.destroy()
2853
+ }
2854
+
2855
+ /**
2856
+ * Ends the child at once, for a sampler that did not ready and might not read its stdin.
2857
+ *
2858
+ * @returns A promise that resolves when the child has exited.
2859
+ */
2860
+ destroy(): Promise<void> {
2861
+ this.#child.stdin?.end()
2862
+ this.#child.kill()
2075
2863
  return this.#closed
2076
2864
  }
2077
2865
 
2866
+ // A sample a byte asked for answers the oldest open request, because the child answers bytes in order.
2078
2867
  #read(line: string): void {
2079
- const members = selectMembers(parseGauges(line), this.#seeds, this.#floor, Date.now())
2868
+ if (line === READY_LINE) {
2869
+ this.#ready.resolve(true)
2870
+ return
2871
+ }
2872
+ const sample = parseSample(line)
2873
+ if (sample === undefined) return
2874
+ if (sample.requested) {
2875
+ this.#answered += 1
2876
+ this.#waiters.get(this.#answered)?.(sample.gauges)
2877
+ this.#waiters.delete(this.#answered)
2878
+ }
2879
+ if (this.#floor === undefined) return
2880
+ const members = selectMembers(
2881
+ sample.gauges,
2882
+ this.#seeds,
2883
+ this.#floor,
2884
+ this.#ceiling ?? Date.now(),
2885
+ )
2080
2886
  this.#tally = tallySample(this.#tally, members)
2081
2887
  const threshold = this.#threshold
2082
2888
  if (
2083
2889
  threshold === undefined ||
2890
+ this.#ceiling !== undefined ||
2084
2891
  this.#breached ||
2085
2892
  (this.#tally.memory <= threshold.memory && this.#tally.processes <= threshold.processes)
2086
2893
  ) {
2087
2894
  return
2088
2895
  }
2896
+ const [launcher] = this.#seeds
2897
+ if (launcher === undefined) return
2089
2898
  this.#breached = true
2090
- this.#breach()
2899
+ this.#breach(launcher)
2091
2900
  }
2092
2901
  }
2093
2902
 
@@ -2095,9 +2904,14 @@ export class Sampler {
2095
2904
  * Runs the command as the holder, reads the tree at handover, and releases.
2096
2905
  *
2097
2906
  * @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.
2907
+ * A measured holder starts its command after its sampler readies, samples the tree back to back
2908
+ * through the command's first {@link SAMPLE_MS} and once every {@link SAMPLE_MS} after, reads the
2909
+ * handover through one more sample, and writes the run's record before it releases, so the command's
2910
+ * next arrival reads it. When that sample lists a member, the handover reads, kills, and reads again
2911
+ * through fresh snapshots, each a second PowerShell. A sampler that does not ready within
2912
+ * {@link READY_MS} is destroyed, and the command runs unmeasured and records nothing. A record that
2913
+ * opened a key prunes the history after the release. A light holder lowers its own priority before
2914
+ * the spawn, and ends its tree when a sample passes the threshold.
2101
2915
  *
2102
2916
  * @param options - The run.
2103
2917
  * @param launcher - The launcher's path.
@@ -2105,6 +2919,7 @@ export class Sampler {
2105
2919
  * @param measure - What a measured holder needs, or undefined when no limits apply.
2106
2920
  * @param token - This process's endpoint, which holds after the run record exists and leaves before
2107
2921
  * the run record is removed.
2922
+ * @param sampler - The measured holder's sampler, started at arrival; the caller stops it.
2108
2923
  * @returns The launcher's code; 1 when a signal ended it; 69 when a light run passed its threshold;
2109
2924
  * 70 when the tree still reads as present or the ticket could not be removed; 75 when the launcher
2110
2925
  * could not start, the priority could not be lowered, or the run record could not be written.
@@ -2115,6 +2930,7 @@ export async function runHolder(
2115
2930
  sequence: number,
2116
2931
  measure?: Measure,
2117
2932
  token?: Token,
2933
+ sampler?: Sampler,
2118
2934
  ): Promise<number> {
2119
2935
  const { root } = options
2120
2936
  if (measure?.light !== undefined && !lowerPriority(process.pid)) {
@@ -2122,6 +2938,14 @@ export async function runHolder(
2122
2938
  console.error('lane: the host refused the light run its below-normal priority')
2123
2939
  return 75
2124
2940
  }
2941
+ const measured = sampler !== undefined && (await sampler.ready(READY_MS))
2942
+ if (sampler !== undefined && !measured) {
2943
+ await sampler.destroy()
2944
+ console.error(
2945
+ `lane: the sampler did not ready within ${String(READY_MS)} ms; ${quote(options.label)} runs unmeasured`,
2946
+ )
2947
+ }
2948
+ const active = measured ? sampler : undefined
2125
2949
  const started = Date.now()
2126
2950
  if (!tryWriteRun(root, sequence, { started, launcher: undefined, command: undefined })) {
2127
2951
  const refusal = releaseTicket(root, sequence)
@@ -2140,17 +2964,15 @@ export async function runHolder(
2140
2964
  return 75
2141
2965
  }
2142
2966
  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])
2967
+ const floor = started - CLOCK_ALLOWANCE_MS
2968
+ const early = new AbortController()
2969
+ active?.seed([id], floor)
2152
2970
  const unwatch = watchSignals(() => killMembers([id]))
2153
2971
  const closed = waitForClose(child)
2972
+ const exited = waitForExit(child).then((at) => {
2973
+ active?.seal(at)
2974
+ return at
2975
+ })
2154
2976
  if (child.stdout !== null) {
2155
2977
  const lines = createInterface({ input: child.stdout, crlfDelay: Infinity })
2156
2978
  lines.on('error', () => undefined)
@@ -2159,28 +2981,44 @@ export async function runHolder(
2159
2981
  const command = readCommandId(line)
2160
2982
  if (command === undefined) return
2161
2983
  tryWriteRun(root, sequence, { started, launcher: id, command })
2162
- sampler?.seed([id, command])
2984
+ active?.seed([id, command], floor)
2985
+ void active?.burst(Date.now() + SAMPLE_MS, early.signal)
2163
2986
  })
2164
2987
  }
2165
2988
  const code = await closed
2989
+ const ended = await exited
2990
+ early.abort()
2166
2991
  unwatch()
2167
- const ended = Date.now()
2168
- const stopped = sampler?.stop()
2169
2992
  const run = readRun(root, sequence)
2993
+ const rows = typeof run === 'object' ? await active?.sample(HANDOVER_MS) : undefined
2994
+ const hung = active !== undefined && typeof run === 'object' && rows === undefined
2995
+ if (hung) {
2996
+ await active.destroy()
2997
+ console.error(
2998
+ `lane: the sampler did not answer the handover within ${String(HANDOVER_MS)} ms; ${quote(options.label)} records nothing`,
2999
+ )
3000
+ }
3001
+ const quick =
3002
+ rows !== undefined && typeof run === 'object' ? selectTree(rows, run, ended) : undefined
2170
3003
  const sweep =
2171
- run === 'absent' || run === 'unread'
3004
+ typeof run !== 'object'
2172
3005
  ? { gone: false, members: [] }
2173
- : sweepTree(() => readTree(run, ended), killMembers, KILL_BUDGET)
2174
- const breached = sampler?.breached === true
3006
+ : quick?.length === 0
3007
+ ? { gone: true, members: [] }
3008
+ : sweepTree(() => readTree(run, ended), killMembers, KILL_BUDGET)
3009
+ const stopped = active?.stop()
3010
+ const breached = active?.breached === true
2175
3011
  const result = !sweep.gone ? HELD_CODE : breached ? BREACH_CODE : (code ?? 1)
2176
- if (measure !== undefined && sampler !== undefined) {
3012
+ const opened =
3013
+ measure !== undefined &&
3014
+ active !== undefined &&
3015
+ !hung &&
2177
3016
  tryWriteOutcome(
2178
3017
  root,
2179
3018
  measure.key,
2180
3019
  renderOutcomeName(ended, measure.token),
2181
- buildOutcome(sampler.tally, ended - started, result),
3020
+ buildOutcome(active.tally, ended - started, result),
2182
3021
  )
2183
- }
2184
3022
  if (!sweep.gone) {
2185
3023
  console.error(
2186
3024
  `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}`,
@@ -2190,6 +3028,12 @@ export async function runHolder(
2190
3028
  }
2191
3029
  token?.leave()
2192
3030
  const refusal = releaseTicket(root, sequence)
3031
+ const prune = opened ? pruneHistory(root, Date.now()) : undefined
3032
+ if (prune !== undefined && prune.skipped.length > 0) {
3033
+ console.error(
3034
+ `lane: the history prune under ${root} skipped ${String(prune.skipped.length)} entries it could not list or remove, such as ${quote(prune.skipped.join(', '))}`,
3035
+ )
3036
+ }
2193
3037
  await stopped
2194
3038
  if (refusal !== undefined) {
2195
3039
  console.error(`lane: removing ${renderName(sequence, TICKET_SUFFIX)} reported ${refusal}`)
@@ -2208,7 +3052,9 @@ export async function runHolder(
2208
3052
  *
2209
3053
  * @remarks
2210
3054
  * 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.
3055
+ * A `--solo` run is heavy whatever its command reads. A `mutate` run is keyed without its edits
3056
+ * file and seeded by its wrapped command; {@link decideDirectory} keeps it apart from the tickets of
3057
+ * its working directory.
2212
3058
  *
2213
3059
  * @param options - The run.
2214
3060
  * @param token - This process's token.
@@ -2224,10 +3070,11 @@ export function readMeasure(options: LaneOptions, token: string): Measure | unde
2224
3070
  )
2225
3071
  }
2226
3072
  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)
3073
+ const key = renderKey(normalizeDirectory(process.cwd()), normalizeCommand(options.command))
3074
+ if (options.solo) return { limits, key, token, light: undefined }
3075
+ const mutation = extractMutation(options.command)
3076
+ const seed = readSeed(mutation ?? options.command)
3077
+ const light = classifyLight(seed, readOutcomes(options.root, key), limits)
2231
3078
  return { limits, key, token, light }
2232
3079
  }
2233
3080
 
@@ -2250,24 +3097,36 @@ export async function enterLane(
2250
3097
  try {
2251
3098
  mkdirSync(root, { recursive: true })
2252
3099
  const measure = readMeasure(options, tokenId)
2253
- await token.listen(renderEndpoint(root, tokenId))
2254
- writeStage(root, buildTicket(tokenId, options.label, measure?.light, options.solo))
2255
- const sequence = linkStage(root, tokenId)
2256
- removeFile(join(root, `${tokenId}${STAGE_SUFFIX}`))
2257
- token.publish()
2258
- const unwatch = watchSignals(() => {
3100
+ const sampler =
3101
+ measure === undefined
3102
+ ? undefined
3103
+ : new Sampler(measure.light === undefined ? undefined : measure.limits.threshold, (pid) =>
3104
+ killMembers([pid]),
3105
+ )
3106
+ try {
3107
+ await token.listen(renderEndpoint(root, tokenId))
3108
+ const edits =
3109
+ extractMutation(options.command) !== undefined || matchesRestore(options.command)
3110
+ writeStage(root, buildTicket(tokenId, options.label, measure?.light, options.solo, edits))
3111
+ const sequence = linkStage(root, tokenId)
3112
+ removeFile(join(root, `${tokenId}${STAGE_SUFFIX}`))
3113
+ token.publish()
3114
+ const unwatch = watchSignals(() => {
3115
+ removeFile(join(root, renderName(sequence, TICKET_SUFFIX)))
3116
+ removeFile(renderEndpoint(root, tokenId))
3117
+ process.exit(75)
3118
+ })
3119
+ const refusal = await waitForTurn(root, sequence, tokenId, measure?.limits)
3120
+ unwatch()
3121
+ if (refusal === undefined) {
3122
+ return await runHolder(options, launcher, sequence, measure, token, sampler)
3123
+ }
2259
3124
  removeFile(join(root, renderName(sequence, TICKET_SUFFIX)))
2260
- removeFile(renderEndpoint(root, tokenId))
2261
- process.exit(75)
2262
- })
2263
- const refusal = await waitForTurn(root, sequence, tokenId, measure?.limits)
2264
- unwatch()
2265
- if (refusal === undefined) {
2266
- return await runHolder(options, launcher, sequence, measure, token)
3125
+ console.error(`lane: ${refusal}`)
3126
+ return 75
3127
+ } finally {
3128
+ await sampler?.stop()
2267
3129
  }
2268
- removeFile(join(root, renderName(sequence, TICKET_SUFFIX)))
2269
- console.error(`lane: ${refusal}`)
2270
- return 75
2271
3130
  } catch (error) {
2272
3131
  console.error(`lane: the queue under ${root} refused the run: ${String(error)}`)
2273
3132
  return 75
@@ -2307,6 +3166,7 @@ export async function readStatusRow(root: string, entry: Entry): Promise<StatusR
2307
3166
  pid: ticket?.pid,
2308
3167
  light: ticket?.light !== undefined,
2309
3168
  solo: ticket?.solo === true,
3169
+ edits: ticket?.edits === true,
2310
3170
  }
2311
3171
  if (ticket === undefined || describeForeign(ticket) !== undefined) {
2312
3172
  return { ...fields, state: 'unread', holding: false }
@@ -2350,7 +3210,7 @@ export function renderStatus(status: Status): string {
2350
3210
  `light: ${lights.length === 0 ? 'none' : lights.map((row) => quote(row.label ?? 'unread')).join(', ')}`,
2351
3211
  ...status.tickets.map(
2352
3212
  (row) =>
2353
- `${renderName(row.sequence, TICKET_SUFFIX)} ${row.state} ${renderLane(row)}${row.holding ? ' holding' : ''} ${quote(row.label ?? 'unread')} pid ${String(row.pid)}`,
3213
+ `${renderName(row.sequence, TICKET_SUFFIX)} ${row.state} ${renderLane(row)}${row.edits ? ' edits' : ''}${row.holding ? ' holding' : ''} ${quote(row.label ?? 'unread')} pid ${String(row.pid)}`,
2354
3214
  ),
2355
3215
  ].join('\n')
2356
3216
  }