@williacj/rigger 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +370 -2
  3. package/package.json +56 -4
  4. package/scripts/doc-reference-check.mjs +59 -0
  5. package/scripts/gate-check.mjs +249 -0
  6. package/scripts/lib/pack-result.mjs +9 -0
  7. package/scripts/record-commit.mjs +67 -0
  8. package/src/cli/doctor.mjs +1021 -0
  9. package/src/cli/init.mjs +384 -0
  10. package/src/cli/once.mjs +489 -0
  11. package/src/cli/pause.mjs +56 -0
  12. package/src/cli/plan.mjs +106 -0
  13. package/src/cli/recording.mjs +52 -0
  14. package/src/cli/report.mjs +242 -0
  15. package/src/cli/resume.mjs +96 -0
  16. package/src/cli/rigger.mjs +12 -0
  17. package/src/cli/run.mjs +10 -0
  18. package/src/cli/setup-board.mjs +108 -0
  19. package/src/cli/verbs.mjs +82 -0
  20. package/src/cli/verdict.mjs +180 -0
  21. package/src/config/validate.mjs +960 -0
  22. package/src/execution/groups.mjs +185 -0
  23. package/src/execution/kept-output.mjs +21 -0
  24. package/src/execution/role.mjs +171 -0
  25. package/src/execution/run.mjs +490 -0
  26. package/src/execution/step.mjs +26 -0
  27. package/src/execution/workspace.mjs +866 -0
  28. package/src/observation/push.mjs +103 -0
  29. package/src/observation/report.mjs +415 -0
  30. package/src/observation/sink.mjs +271 -0
  31. package/src/package-commit.json +1 -0
  32. package/src/scheduling/admission.mjs +390 -0
  33. package/src/scheduling/clock.mjs +98 -0
  34. package/src/scheduling/lane.mjs +160 -0
  35. package/src/scheduling/loop.mjs +1738 -0
  36. package/src/scheduling/pull-order.mjs +46 -0
  37. package/src/substrate/data-ref.mjs +147 -0
  38. package/src/substrate/forge/assets.mjs +5 -0
  39. package/src/substrate/forge/graphql.mjs +258 -0
  40. package/src/substrate/forge/item-write.mjs +74 -0
  41. package/src/substrate/forge/read.mjs +998 -0
  42. package/src/substrate/forge/repository-write.mjs +152 -0
  43. package/src/substrate/forge/runners.mjs +510 -0
  44. package/src/substrate/forge/schema-write.mjs +70 -0
  45. package/src/substrate/forge/write-made.mjs +40 -0
  46. package/src/substrate/git-environment.mjs +54 -0
  47. package/src/substrate/host.mjs +23 -0
  48. package/src/substrate/launchd.mjs +23 -0
  49. package/src/substrate/process-table.sh +48 -0
  50. package/src/substrate/process.mjs +2474 -0
  51. package/src/substrate/providers/adapters.mjs +8 -0
  52. package/src/substrate/providers/claude.mjs +427 -0
  53. package/src/substrate/providers/codex.mjs +349 -0
  54. package/src/substrate/standard-error.mjs +134 -0
  55. package/src/substrate/worktrees.mjs +517 -0
  56. package/src/workflow/clock-mark.mjs +40 -0
  57. package/src/workflow/escalation.mjs +110 -0
  58. package/src/workflow/facts.mjs +92 -0
  59. package/src/workflow/first-above.mjs +17 -0
  60. package/src/workflow/form-check.mjs +88 -0
  61. package/src/workflow/gate.mjs +62 -0
  62. package/src/workflow/judges.mjs +695 -0
  63. package/src/workflow/marker.mjs +265 -0
  64. package/src/workflow/next-action.mjs +456 -0
  65. package/src/workflow/status-issue.mjs +268 -0
  66. package/src/workflow/transitions.mjs +588 -0
  67. package/templates/claude/agents/architect.md +116 -0
  68. package/templates/claude/agents/engineer.md +57 -0
  69. package/templates/claude/agents/pm.md +114 -0
  70. package/templates/claude/agents/reviewer.md +37 -0
  71. package/templates/claude/agents/spike-engineer.md +80 -0
  72. package/templates/claude/hooks/refuse-reserved-git-commands.mjs +909 -0
  73. package/templates/claude/settings.json +50 -0
  74. package/templates/claude/skills/acceptance/SKILL.md +275 -0
  75. package/templates/claude/skills/agent-style/SKILL.md +78 -0
  76. package/templates/claude/skills/code-review/SKILL.md +242 -0
  77. package/templates/claude/skills/proposal/SKILL.md +175 -0
  78. package/templates/claude/skills/spec-style/SKILL.md +112 -0
  79. package/templates/claude/skills/tdd/SKILL.md +230 -0
  80. package/templates/codex/config.toml +19 -0
  81. package/templates/doc-reference-check.md +25 -0
  82. package/templates/githooks/pre-push +24 -0
  83. package/templates/github/workflows/rigger-gate.yml +209 -0
  84. package/templates/launchd/com.williacj.rigger.plist +31 -0
  85. package/templates/rigger.config.mjs +78 -0
@@ -0,0 +1,2474 @@
1
+ // ABOUTME: L0's process adapter: it runs one command in a process group of its own, ends the group at
2
+ // the command's timeout, and once the command exits, kills what is left of that group and, for a
3
+ // dispatch, every process of its user working in the dispatch's directory, records each process it
4
+ // killed, and stops reading output a process outside the group holds open. On a start, it kills a
5
+ // group a dead engine recorded, once it has confirmed that group is the one recorded, and what works
6
+ // in its dispatch's directory. On the process's own exit it kills every group it holds.
7
+
8
+ import { once } from 'node:events';
9
+ import { constants } from 'node:os';
10
+ import { inspect } from 'node:util';
11
+
12
+ import { realHost } from './host.mjs';
13
+ import { writeWhole } from './standard-error.mjs';
14
+
15
+ /** Refuses an incomplete L0 clock before an adapter entry point performs host operations. */
16
+ function requireClock(clock) {
17
+ if (clock === undefined || clock === null) throw new TypeError('the process adapter requires a host clock');
18
+ for (const method of ['now', 'pause', 'schedule', 'cancel']) {
19
+ if (typeof clock[method] !== 'function') throw new TypeError(`the host clock requires callable ${method}`);
20
+ }
21
+ }
22
+
23
+ /**
24
+ * The process-table tool, by absolute path, so it is found whatever `PATH` the caller runs under:
25
+ * the installed engine runs under one holding only node, git and `gh` (`test/package.test.mjs`).
26
+ */
27
+ export const PS = realHost.ps;
28
+
29
+ /**
30
+ * The whole environment `ps` runs under: a UTF-8 locale, so text outside ASCII reads unchanged,
31
+ * and UTC, so a start time reads the same whatever zone the host is in. See `census`.
32
+ */
33
+ const PS_ENV = { LC_ALL: 'C.UTF-8', TZ: 'UTC0' };
34
+
35
+ /**
36
+ * How long L0 waits for one read of the process table before it gives up on the census and kills
37
+ * the group unnamed. A judgment, not a measurement. Its premise is a measurement: 20 reads of one
38
+ * four-process group, the census's own `ps -ww -g <group> -o pid=,ucomm=,command=` with macOS
39
+ * 27.0's `ps` on 2026-09-27, took 1.0 to 1.6 ms each. Five seconds is over a thousand times that, room for a loaded host, while a
40
+ * read that hangs holds a kill back by no more than five seconds.
41
+ */
42
+ export const READ_TIMEOUT = 5_000;
43
+
44
+ /**
45
+ * How long L0 reads a command's output once its group is empty before it stops, because a process
46
+ * that left the group holds a pipe open. A judgment, not a measurement. Its premise: once the group
47
+ * is empty, every byte the group wrote is already in the pipes, and the output is only what the
48
+ * group wrote (the Failure model), so the bound waits for nothing of the command's own but a read
49
+ * of what is buffered. That read is measured: with no process outside the group holding a pipe,
50
+ * both pipes closed at most 0.129 ms after the group was empty, over 400 calls of this adapter
51
+ * writing 300,000 bytes, half of them leaving a survivor on both pipes, with Node 26.5.0 on macOS
52
+ * 27.0 on 2026-09-27. One second is over seven thousand times that, room for a loaded host, and
53
+ * costs a command whose output a detached process holds one second.
54
+ *
55
+ * A process that left the group and holds a pipe is outside containment (the owner's Q6 on #332),
56
+ * so what it writes is not the group's, and the bound does not keep it out. What it writes before
57
+ * the bound passes is in the result, among the group's own bytes where it wrote while the group
58
+ * ran; what it writes after is dropped, because L0 closes the pipes then. How much lands depends on when it writes: the engineer judge on
59
+ * #361 saw a holder printing a line every millisecond put 198 lines into standard output.
60
+ */
61
+ export const OUTPUT_BOUND = 1_000;
62
+
63
+ /**
64
+ * How long L0 goes on killing a group that holds nothing but zombies before it settles. A zombie
65
+ * cannot run, but it keeps its group in being, so a process can still join the group, and L0 kills
66
+ * any that does within the bound. A zombie whose parent never reaps it is left behind once the
67
+ * bound passes. A judgment, not a measurement. Its premise is a measurement: over 30 calls of this
68
+ * adapter, 10 each of the three tests in `test/process-adapter.test.mjs` whose group holds a zombie
69
+ * that is reaped (the forkers, the process that joins after the kill, and the zombie left out of
70
+ * the census), 12 read only zombies before the group was empty, and each was empty 2 to 5 ms
71
+ * later, with Node 26.5.0 on macOS 27.0 on 2026-09-27. One second is 200 times that, room for a
72
+ * loaded host, and costs a group whose zombie is never reaped one second.
73
+ */
74
+ export const UNREAPED_BOUND = 1_000;
75
+
76
+ /**
77
+ * The longest L0 pauses between two looks at a group it is waiting on. The pause starts at one
78
+ * millisecond and doubles up to this, so a wait costs next to no processor time however long it
79
+ * lasts. A judgment, not a measurement.
80
+ */
81
+ const LONGEST_PAUSE = 50;
82
+
83
+ /**
84
+ * How long after its first kill of a group L0 goes on killing a member that is still alive, and how
85
+ * long after its kill of a process working in a dispatch's directory it waits for that process to
86
+ * end, before it records the process as one it could not end and settles (`R-STATE-19`). A member
87
+ * L0 may not signal is recorded once two looks in a row find it so (`unended`). The exit cleanup
88
+ * waits on its own bound, the read timeout, in its place. A judgment, not a measurement, set by the
89
+ * architect (ruling 15). Its premise is that it stays at least ten times above the kill loop's
90
+ * worst case, measured from its first kill of the group to its last, with Node 26.5.0 on macOS 27.0
91
+ * (#539):
92
+ *
93
+ * - worst 94.6 ms, in 6 rounds, over 10 runs of the 250-deep chain test in
94
+ * `test/process-adapter.test.mjs` at `7a67ffd`, each started at a one-minute load of 24 or less,
95
+ * on 2026-10-03;
96
+ * - one round in each of the 12 calls whose group was still occupied at the kill, over 22 runs of
97
+ * 300 `git fetch`es each through this adapter at `1bbd7ec`, started at loads of 60.97 to 125.82,
98
+ * on 2026-10-02.
99
+ *
100
+ * Ten seconds is over 100 times the worst of those. How long the loop takes against a group that
101
+ * forks rapidly without bound was not measured (`ended`).
102
+ */
103
+ export const KILL_BOUND = 10_000;
104
+
105
+ /**
106
+ * How long from its start the exit cleanup goes on ending groups with their census and sweep. Past
107
+ * it, each group it has not reached has the kill of the group alone (`killedBare`). A group it has
108
+ * begun, it finishes. A judgment, not a measurement. Its premises: the architect's reading on
109
+ * #1240 that nine ordinary cleanups fit in about 3 s, and Q-e2's slowest cleanup of 5.5 s, the cost
110
+ * of a process table that hangs, which is paid once (`unanswered`).
111
+ */
112
+ export const EXIT_CARE_BOUND = 15_000;
113
+
114
+ /**
115
+ * The longest the exit cleanup's reads can hold the process's ending: `EXIT_CARE_BOUND`, and 40 s
116
+ * for the one dispatch that can be in progress when it passes. A reading of the deadlines, which
117
+ * `test/exit-cleanup.test.mjs` bounds with a host that answers each read at its last moment: 5 s each for
118
+ * the tracker and its post-kill reads, 5 for `containNow`'s census, 5 and 5 spare before its
119
+ * kill, 5 for its confirmation, and 5 and 5 for the shared sweep of both directories. It bounds reads alone: a hung sink write, or a process stuck in
120
+ * the kernel, is outside it. It stays below the 60 s launchd allows on macOS 27.2
121
+ * (`ARCHITECTURE.md`, "Supervising `run`"). L0 answers it here, since these deadlines are L0's, and
122
+ * `launchdExitTimeout` hands it on.
123
+ */
124
+ export const EXIT_BOUND = 55_000;
125
+
126
+ /** The pause after `wait`, doubling it up to `LONGEST_PAUSE`. */
127
+ const longer = (wait) => Math.min(Math.max(1, 2 * wait), LONGEST_PAUSE);
128
+
129
+ /**
130
+ * The `code` of the failure a call rejects with when the sink refused an event it had to record,
131
+ * so its caller tells it from a command that never started without reading the message.
132
+ */
133
+ export const EVENT_REFUSED = 'EVENT_REFUSED';
134
+
135
+ /**
136
+ * The signals L0's exit cleanup handles: every signal whose default action ends a Node process and
137
+ * that Node lets a listener handle safely (`ARCHITECTURE.md`, "Failure model"). Node and the OS
138
+ * decide which those are, and `test/exit-cleanup.test.mjs` asks both, for every signal Node names
139
+ * (`D16` rule 2).
140
+ */
141
+ const namedSignal = (name) => Object.hasOwn(constants.signals, name);
142
+ // Linux ends a process on SIGIO by default; macOS leaves it running. The signal probes ask both.
143
+ const ioTerminates = process.platform === 'linux';
144
+ export const HANDLED = ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGTRAP', 'SIGABRT', 'SIGUSR2', 'SIGALRM', 'SIGTERM', 'SIGXCPU', 'SIGVTALRM', 'SIGSYS', 'SIGPWR', 'SIGSTKFLT', ...(ioTerminates ? ['SIGIO'] : [])].filter(namedSignal);
145
+
146
+ /**
147
+ * Every other signal Node names, by why the cleanup leaves it out. An ending by one of the first
148
+ * three kinds is being killed outright, and a later start's kill of the recorded groups answers it.
149
+ */
150
+ export const LEFT_OUT = {
151
+ // No process can catch these, and Node refuses a listener for either.
152
+ uncatchable: ['SIGKILL', 'SIGSTOP'],
153
+ // Node's documentation: after a real one, not raised by `kill`, the process is in a state from
154
+ // which it is not safe to call a listener.
155
+ unsafe: ['SIGSEGV', 'SIGBUS', 'SIGFPE', 'SIGILL'],
156
+ // V8's sampling profiler sends it to the process itself. Under `--cpu-prof`, a Node process with
157
+ // a listener for it was ended by it, where one without a listener exited 0: 5 runs of each on
158
+ // Node 26.5.0 and 1 on 20.20.2, macOS 27.0, 2026-09-27.
159
+ profiler: ['SIGPROF'],
160
+ // Node reserves it to start its inspector, and it does not end a Node process.
161
+ inspector: ['SIGUSR1'],
162
+ // Its default action, or Node's own disposition, does not end a Node process: it ignores the
163
+ // signal, or stops the process.
164
+ harmless: ['SIGPIPE', 'SIGCHLD', 'SIGCONT', 'SIGTSTP', 'SIGTTIN', 'SIGTTOU', 'SIGURG', 'SIGXFSZ', 'SIGWINCH', 'SIGINFO', ...(ioTerminates ? [] : ['SIGIO'])].filter(namedSignal),
165
+ // Other names for handled signals: SIGABRT, and on Linux SIGIO.
166
+ alias: ['SIGIOT', 'SIGPOLL'].filter(namedSignal),
167
+ };
168
+
169
+ /**
170
+ * Every call L0 has in flight, by its group, from the step that creates the group until a turn
171
+ * after the call settles, with what the exit cleanup needs to end and record it: the call's `L0`
172
+ * emitter, its `ps` and read timeout, the step its caller handed it for the exit, the command's
173
+ * child process, which says how the command ended where Node has reaped it, the kills the call has
174
+ * made and not yet recorded, and whether the call has emptied the group.
175
+ */
176
+ const calls = new Map();
177
+
178
+ /** Hosts have separate clocks; each host serializes whole-table reads for all its dispatches. */
179
+ const trackers = new WeakMap();
180
+ const active = (host) => [...calls.values()].filter((call) => call.host === host && call.tracking);
181
+ function trackerOf(host) {
182
+ if (!trackers.has(host)) trackers.set(host, { queue: [] });
183
+ return trackers.get(host);
184
+ }
185
+
186
+ /** All reads serve running dispatches; a final read queues without moving periodic service. */
187
+ function scan(host, dispatches) {
188
+ const tracker = trackerOf(host);
189
+ // A queued periodic read also serves a dispatch admitted after an idle interval.
190
+ if (dispatches === undefined && tracker.queue.some((request) => request.dispatches === undefined)) return;
191
+ return new Promise((resolve) => {
192
+ tracker.queue.push({ dispatches, resolve });
193
+ serviceTracker(host);
194
+ });
195
+ }
196
+
197
+ /**
198
+ * One owner advances the tracker: at most one read is in flight and one timer pending.
199
+ * Only a settling read arms the next period, with the last periodic start's remaining time
200
+ * (zero when overdue). Queued first/final reads run before arming. A final read never moves
201
+ * that start or cancels a peer's timer. Every answer serves its starting recipients and all
202
+ * dispatches whose final read has not settled, including those admitted and ended during
203
+ * this read. Stopping periodic service does not revoke an answer owed before the final read.
204
+ */
205
+ function serviceTracker(host) {
206
+ const tracker = trackerOf(host);
207
+ if (tracker.reading) return;
208
+ const request = tracker.queue.shift();
209
+ if (request !== undefined) {
210
+ tracker.reading = true;
211
+ Promise.resolve().then(async () => {
212
+ if (request.dispatches === undefined) tracker.began = host.clock.now();
213
+ const serving = [...new Set([...(request.dispatches ?? []), ...active(host)])];
214
+ await reading(tracking(serving, host), host.ps, serving[0]?.readTimeout ?? READ_TIMEOUT, undefined, serving[0]?.trace, host);
215
+ tracker.reading = false;
216
+ request.resolve();
217
+ serviceTracker(host);
218
+ });
219
+ } else if (tracker.timer === undefined && active(host).length > 0) {
220
+ tracker.timer = host.clock.schedule(Object.assign(() => {
221
+ tracker.timer = undefined;
222
+ return scan(host);
223
+ }, { tracker: true }), Math.max(0, 1000 - (host.clock.now() - tracker.began)));
224
+ tracker.timer?.unref?.();
225
+ }
226
+ }
227
+
228
+ /** Stops this dispatch's periodic service, preserving the cadence of any other dispatch. */
229
+ function stopTracking(call) {
230
+ call.tracking = false;
231
+ const tracker = trackerOf(call.host);
232
+ if (active(call.host).length === 0 && tracker.timer !== undefined) {
233
+ call.host.clock.cancel(tracker.timer);
234
+ tracker.timer = undefined;
235
+ }
236
+ }
237
+
238
+ /** One whole-table observation closes each dispatch's descendant set, retaining its first identity. */
239
+ function* tracking(dispatches, host) {
240
+ if (dispatches.length === 0) return;
241
+ const recipients = () => [...new Set([...dispatches, ...(host === undefined ? [] : [...calls.values()].filter((call) => call.host === host && call.tracked !== undefined && !call.trackerEnded))])];
242
+ try {
243
+ const table = [...rowsOf(yield ['-A', '-o', 'pid=,ppid=,pgid=,lstart='])].map(([pid, row]) => {
244
+ const fields = /^\s*(\d+)\s+(\d+)\s+(.+)$/.exec(row);
245
+ if (!fields) throw new Error(`the tracker cannot read process ${pid}: ${row}`);
246
+ return { pid, parent: Number(fields[1]), group: Number(fields[2]), started: secondsOf(fields[3]) };
247
+ });
248
+ for (const call of recipients()) {
249
+ // A retained pid establishes ancestry only while this read shows its original identity.
250
+ // Its replacement cannot add children or overwrite that identity; earlier descendants stay.
251
+ const matching = table.filter(({ pid, started }) => !call.tracked.has(pid) || call.tracked.get(pid) === started);
252
+ const parents = new Set(matching.filter(({ group }) => group === call.child.pid).map(({ pid }) => pid));
253
+ for (const { pid } of matching) if (call.tracked.has(pid)) parents.add(pid);
254
+ const added = [];
255
+ let grew;
256
+ do {
257
+ grew = false;
258
+ for (const member of matching) {
259
+ if (parents.has(member.pid) || !parents.has(member.parent)) continue;
260
+ parents.add(member.pid);
261
+ call.tracked.set(member.pid, member.started);
262
+ added.push({ pid: member.pid, started: member.started });
263
+ grew = true;
264
+ }
265
+ } while (grew);
266
+ // A caller that cannot record what this read added leaves it tracked here alone, so the
267
+ // dispatch's ending still ends it ("Failure model"), and its failure fails no read.
268
+ try {
269
+ if (added.length > 0) call.onTracked?.(call.child.pid, added);
270
+ } catch {
271
+ // Kept in memory; the record names it no more than the caller managed to write.
272
+ }
273
+ }
274
+ } catch (error) {
275
+ for (const call of recipients()) call.trackerUnread = error.message;
276
+ }
277
+ }
278
+
279
+ /**
280
+ * Selects recorded identities by pid, and confirms them again while the sweep holds them stopped.
281
+ * Given `unended`, as a later start's sweep is, it names there each pid it drops and why, and takes
282
+ * a start time it cannot read, or a read that fails, as one that no longer matches.
283
+ */
284
+ function* trackedIn(tracked, pids = [...tracked.keys()], unended) {
285
+ if (pids.length === 0) return [];
286
+ let rows;
287
+ try {
288
+ rows = rowsOf(yield ['-p', pids.join(','), '-o', 'pid=,lstart=']);
289
+ } catch (error) {
290
+ // A later start takes a start time it cannot read as one that no longer matches, each read's
291
+ // failure as each pid's unreadable start.
292
+ if (unended === undefined) throw error;
293
+ rows = new Map(pids.map((pid) => [pid, error.message]));
294
+ }
295
+ return [...rows].filter(([pid, start]) => {
296
+ let seconds;
297
+ try {
298
+ seconds = secondsOf(start);
299
+ } catch (error) {
300
+ if (unended === undefined) throw error;
301
+ }
302
+ if (seconds === tracked.get(pid)) return true;
303
+ unended?.set(pid, `L0 could not confirm it is the process recorded as started at ${tracked.get(pid)}, so it left it: ${seconds === undefined ? `its start time could not be read: ${start}` : `its start time is ${seconds}`}`);
304
+ tracked.delete(pid);
305
+ return false;
306
+ }).map(([pid]) => pid);
307
+ }
308
+
309
+ /** Every read of the process table a census has in flight, so the exit cleanup can end it. */
310
+ const reads = new Map();
311
+
312
+ /**
313
+ * Each `ps` a read of which the exit cleanup gave up on as it ran, by the timeout it waited out.
314
+ * The cleanup reads it no more, so a process table that never answers holds the process's ending
315
+ * back by one read timeout, and not by one for each read of each group it holds (`runNow`). One
316
+ * exception: a census of a dispatch's directory that gave up on it at its own bound before it sent
317
+ * its kill reads it again in its wait on what it killed, which has a bound of its own (`sweptNow`).
318
+ */
319
+ const unanswered = new Map();
320
+
321
+ /**
322
+ * When the exit cleanup's reads of the process table began to fail, where the last one failed: the
323
+ * start of the first read of the run that failed. So it waits out `UNREAPED_BOUND` on a table it
324
+ * cannot read once, whatever the groups it holds, and a read that hung for that long uses it up
325
+ * (`emptied`, `runNow`).
326
+ */
327
+ let unreadSince;
328
+
329
+ /** The synchronous steps the exit cleanup takes last, once it has made its kills. */
330
+ const steps = [];
331
+
332
+ /**
333
+ * Hands L0 a synchronous `step` its exit cleanup takes last, after it has killed every group it
334
+ * holds, recorded each kill and taken each caller's own step. A verb hands over its sink's end
335
+ * when it opens the sink, so the kills are among what the sink writes (ruling 3, §3, on #332).
336
+ */
337
+ export function atExit(step) {
338
+ steps.push(step);
339
+ }
340
+
341
+ /**
342
+ * Whether the exit cleanup is installed, which L0 does before it creates its first group. Before,
343
+ * because a signal with no listener ends the process by the signal's default action at once, so
344
+ * one that landed between the spawn and the install would leave the new group running, unkilled
345
+ * and unrecorded.
346
+ */
347
+ let installed = false;
348
+
349
+ /**
350
+ * Installs the exit cleanup, once: on `exit`, and ahead of every other listener on every signal in
351
+ * `HANDLED`. It stays ahead: a listener put ahead of it later has it put back in front before
352
+ * anything else runs, because a signal is only ever emitted from the event loop.
353
+ */
354
+ function install() {
355
+ if (installed) return;
356
+ installed = true;
357
+ process.on('exit', cleanup);
358
+ for (const name of HANDLED) process.prependListener(name, onSignal);
359
+ process.on('newListener', (name) => {
360
+ if (HANDLED.includes(name)) queueMicrotask(() => ahead(name));
361
+ });
362
+ }
363
+
364
+ /** Puts `onSignal` first among `name`'s listeners, where it is there at all. */
365
+ function ahead(name) {
366
+ const listeners = process.listeners(name);
367
+ if (!listeners.includes(onSignal) || listeners[0] === onSignal) return;
368
+ // Node removes the last instance of a listener added twice, which is the one behind.
369
+ process.prependListener(name, onSignal);
370
+ process.removeListener(name, onSignal);
371
+ }
372
+
373
+ /**
374
+ * On signal `name`, cleans up first, and then leaves the process to end as it would have with no
375
+ * cleanup. So it takes itself off the signal before any other listener runs: they then find only
376
+ * each other, as they would have. Where none is left, Node gives the signal its default action
377
+ * again, and raising it ends the process by it. Where one is left, the process ends as that
378
+ * listener has it, and a process it keeps running has the cleanup back on the signal a turn later.
379
+ *
380
+ * It runs ahead of every other listener, so a `once` listener that has not yet run is still
381
+ * counted, and no listener can end the process before the cleanup has run.
382
+ */
383
+ function onSignal(name) {
384
+ cleanup();
385
+ process.removeListener(name, onSignal);
386
+ if (process.listenerCount(name) === 0) realHost.signal(process.pid, name);
387
+ else setImmediate(() => process.listeners(name).includes(onSignal) || process.prependListener(name, onSignal));
388
+ }
389
+
390
+ /**
391
+ * L0's exit cleanup, synchronous because Node runs an `exit` listener synchronously. It ends every
392
+ * read of the process table still in flight; then, for every call in flight whose group the call
393
+ * has not emptied, it ends the group as the call would have, and confirms it (`containNow`), until
394
+ * `EXIT_CARE_BOUND` has passed since it reached its first call, by that call's host clock, and past
395
+ * that it kills each remaining group bare (`killedBare`); and only then records
396
+ * each kill, the call's own unrecorded kills first, and writes to standard error every kill the
397
+ * sink refused, since no caller is left to report it to. It then takes each caller's step for its
398
+ * group, handing it how the command ended (`endingOf`), which is L1's removal of the group's
399
+ * entry and its record of the dispatch's end; and last the steps handed to `atExit`. A failure in any of these is
400
+ * written to standard error and never stops the rest, nor changes how the process ends.
401
+ *
402
+ * It ends only the calls in flight when it runs, and lets each go, so a process that a signal
403
+ * listener of its caller keeps running has the groups it starts later ended at its next ending.
404
+ * So it can run more than once, and each step handed to `atExit` must bear being taken again, as
405
+ * the sink's end does. Each time it runs, it reads again a process table it gave up on before
406
+ * (`unanswered`).
407
+ */
408
+ function cleanup() {
409
+ for (const [read, host] of reads) host.killChild(read, 'SIGKILL');
410
+ unanswered.clear();
411
+ unreadSince = undefined;
412
+ const ended = [];
413
+ let began;
414
+ for (const [group, call] of calls) {
415
+ calls.delete(group);
416
+ if (call.tracked !== undefined) stopTracking(call);
417
+ attempt(() => {
418
+ const now = call.host.clock.now();
419
+ began ??= now;
420
+ ended.push([group, call, call.contained ? {} : now - began < EXIT_CARE_BOUND ? endedNow(group, call) : killedBare(group, call)]);
421
+ });
422
+ }
423
+ const unrecorded = ended.flatMap(([, call, { kills = [] }]) => {
424
+ const events = [...call.events.splice(0), ...kills];
425
+ handSigns(call, events);
426
+ return record(call.emitter, events);
427
+ });
428
+ if (unrecorded.length > 0) attempt(() => writeWhole(`${refused(unrecorded).message}\n`));
429
+ for (const [group, { onExit, child }, look] of ended) attempt(() => onExit?.(group, { ...endingOf(child, look), ...(look.unswept === undefined ? {} : { unswept: look.unswept }) }));
430
+ for (const step of steps) attempt(step);
431
+ }
432
+
433
+ /**
434
+ * Kills `group` for the exit cleanup once `EXIT_CARE_BOUND` has passed: the group's kill and nothing
435
+ * else, so no read, and no search of the call's directories. Hands back the kill of the group to
436
+ * record, where signal 0 still reaches the group, and as `unread` and `unswept` why it did no more
437
+ * (`R-STATE-28`). `unswept` tells the caller's step to keep the group's entry, so that the next
438
+ * start sweeps those directories, which it does whether the group is still there or not.
439
+ */
440
+ function killedBare(group, { kill }) {
441
+ const why = `the exit cleanup had run for ${EXIT_CARE_BOUND} ms, so it killed the group without reading it or searching its directories`;
442
+ if (!occupied(group, kill)) return { kills: [], unread: why, unswept: why };
443
+ signal(group, 'SIGKILL', kill);
444
+ return { kills: [['group.killed', { group, census: why }]], unread: why, unswept: why };
445
+ }
446
+
447
+ /**
448
+ * How the command `child` ran ended, as the exit cleanup finds it: `{ exit }`, its exit code, or
449
+ * `{ unread }`, why its status could not be read. Where Node has reaped the command, Node says how
450
+ * it ended. Otherwise the command is a zombie, since Node reaps no child while the cleanup runs,
451
+ * and `leader` is the wait status `ps` read for it as `xstat` on the kill's last look: its own
452
+ * exit where it had exited, or the cleanup's kill. Only a read shows how it ended: where the reads
453
+ * after the kill failed, or answered without listing the leader, a leader signal 0 still reaches is
454
+ * not shown to have ended (`containNow`), and `unread` says so and why. Otherwise `unread`
455
+ * says why, and nothing tells the command's own exit from the kill: the command may have exited
456
+ * before the cleanup ran, and where the census's reads failed too, even a command the cleanup
457
+ * killed cannot be told from one that exited.
458
+ */
459
+ function endingOf(child, { leader, unread }) {
460
+ if (child.exitCode !== null) return { exit: child.exitCode };
461
+ if (child.signalCode !== null) return { exit: signalled(child.signalCode) };
462
+ if (leader === undefined) return { unread: `the exit cleanup could not read the command's status: ${unread}` };
463
+ // `ps` prints the wait status in hexadecimal. Its low seven bits are the signal that ended the
464
+ // process, where one did, and the byte above them its exit code (wait(2): WTERMSIG, WEXITSTATUS).
465
+ const status = Number.parseInt(leader, 16);
466
+ const ending = status & 0x7f;
467
+ return { exit: ending === 0 ? (status >> 8) & 0xff : 128 + ending };
468
+ }
469
+
470
+ /**
471
+ * The exit code of a process signal `name` ended. It has none of its own, so it takes the one a
472
+ * shell gives it: 128 and the signal's number, which is never 0.
473
+ */
474
+ const signalled = (name) => 128 + constants.signals[name];
475
+
476
+ /** Takes `step`, writing to standard error why it failed, where it does. */
477
+ function attempt(step) {
478
+ try {
479
+ step();
480
+ } catch (failure) {
481
+ try {
482
+ writeWhole(`L0's exit cleanup: ${failure.stack ?? failure}\n`);
483
+ } catch {
484
+ // Standard error is gone, and nothing is left to tell.
485
+ }
486
+ }
487
+ }
488
+
489
+ /**
490
+ * The largest delay, in milliseconds, one of Node's timers keeps. Node owns this fact and exports
491
+ * no name for it. Past it, Node warns with a `TimeoutOverflowWarning` and sets the delay to 1 ms,
492
+ * which would end at once a command given more time than that, so a longer delay is kept over
493
+ * several timers (`whenElapsed`). This copy is tied to Node by a test that asks Node's timer
494
+ * (`D16` rule 2).
495
+ */
496
+ export const TIMER_MAX = 2 ** 31 - 1;
497
+
498
+ /**
499
+ * The `code` of the failure a call rejects with when its command never started, so its caller
500
+ * tells it from a refused event without reading the message.
501
+ */
502
+ export const NOT_STARTED = 'NOT_STARTED';
503
+
504
+ /** Every chunk `stream` carries, as one buffer, once the stream has closed. */
505
+ async function drained(stream) {
506
+ const chunks = [];
507
+ stream.on('data', (chunk) => chunks.push(chunk));
508
+ await once(stream, 'close');
509
+ return Buffer.concat(chunks);
510
+ }
511
+
512
+ /**
513
+ * Whether any process is left in `group`: signal 0 reaches a group while it has a member.
514
+ *
515
+ * `EPERM` counts as a member left. Measured with Node 26.5.0 on macOS 27.0 on 2026-09-27, over
516
+ * 200 groups each SIGKILLed with two members: the kernel answered `EPERM` once in every one of
517
+ * them while its members were exiting, and `ESRCH` on a later poll.
518
+ */
519
+ const occupied = (group, kill = SIGNAL) => answers(-group, kill);
520
+
521
+ /**
522
+ * The host's signal call takes a
523
+ * pid, or a group's id negated, and a signal, and throws as `process.kill` throws.
524
+ */
525
+ const SIGNAL = realHost.signal;
526
+
527
+ /** Whether signal 0 reaches `target`, a pid or a group's id negated, through `kill`, `EPERM` counting as reached. */
528
+ function answers(target, kill = SIGNAL) {
529
+ try {
530
+ kill(target, 0);
531
+ return true;
532
+ } catch (error) {
533
+ if (error.code === 'ESRCH') return false;
534
+ if (error.code === 'EPERM') return true;
535
+ throw error;
536
+ }
537
+ }
538
+
539
+ /**
540
+ * Kills every process left in `group` through `kill`, and settles once the group is empty, or once
541
+ * `UNREAPED_BOUND` has passed with no read of its states finding a member that is not a zombie, and
542
+ * hands back as `stuck` each member L0 could not end, by pid, with why: `EPERM` where L0 may not
543
+ * signal it, or that it was still alive `bound` milliseconds after the first kill; and as `joined`
544
+ * whether a read after the kill listed a process, alive or a zombie, that `listed`, every process
545
+ * the read just before the kill listed, did not hold; and as `unread` why a read after the kill
546
+ * failed, where one did, since the kill of the group may then have ended a process no read listed;
547
+ * and as `unlisted` why, where every read after the kill failed, so none showed any member's state;
548
+ * and as `unconfirmed`, where a read after the kill succeeded and the last read failed, the pids the
549
+ * last read that succeeded found alive, as `alive`, and why a read after it failed, as `why`.
550
+ * A look that finds every member still alive answering `EPERM` to signal 0, asked of each by its
551
+ * pid, settles at once, because no kill can reach any of them. The wait is on those conditions, looked at after each pause, so
552
+ * nothing else in Rigger stops meanwhile, and it takes no cap on its rounds: a cap that stopped
553
+ * killing while a member lived would leave it alive (ruling 14).
554
+ *
555
+ * A read that fails, or times out, finds no such member, so the call settles whatever the process
556
+ * table does. A group whose table L0 cannot read is still sent the kill on every look until
557
+ * `UNREAPED_BOUND` passes.
558
+ *
559
+ * The kill is sent again on every look, because a process can be in the group without having
560
+ * received it. One forked while the kernel delivers a group kill can miss it and run on: the
561
+ * engineer judge on #354 saw that in 9 of 12 runs of a survivor forking in a loop, macOS 27.0,
562
+ * 2026-09-27, where the group was running at the kill. And a process outside the group can join it
563
+ * after the kill while a zombie keeps it in being.
564
+ *
565
+ * Where the loop's end can be wrong (`D16` rule 3): how long it takes to end a group that forks
566
+ * rapidly without bound, such as a fan-out of hundreds of children, was not measured (the owner's
567
+ * O66 on #539), and that case is a known gap. `bound` is what ends the wait there, with each member
568
+ * still alive recorded as not ended.
569
+ */
570
+ async function ended(group, { ps, readTimeout, kill, host }, bound, listed) {
571
+ const since = host.clock.now();
572
+ const refused = new Set();
573
+ let unreapedSince;
574
+ let joined = false;
575
+ // Why a read after the kill failed, where one did, and whether one after the kill succeeded.
576
+ let unread;
577
+ let read = false;
578
+ // The pids the last read that succeeded found alive, and why a read after it failed, where one did.
579
+ let shown = [];
580
+ let lastFailure;
581
+ const settled = (stuck) => ({ stuck, joined, unread, unlisted: read ? undefined : unread, unconfirmed: read && lastFailure !== undefined ? { alive: new Set(shown), why: lastFailure } : undefined });
582
+ for (let wait = 0; ; wait = longer(wait)) {
583
+ if (wait > 0) await host.clock.pause(wait);
584
+ signal(group, 'SIGKILL', kill);
585
+ if (!occupied(group, kill)) return settled([]);
586
+ if (wait === 0) continue;
587
+ const looked = host.clock.now();
588
+ let rows;
589
+ try {
590
+ rows = rowsOf(await run(ps, ['-g', String(group), '-o', 'pid=,stat='], readTimeout, readTimeout, host));
591
+ read = true;
592
+ lastFailure = undefined;
593
+ } catch (error) {
594
+ unread ??= error.message;
595
+ lastFailure ??= error.message;
596
+ rows = new Map();
597
+ }
598
+ if (listed !== undefined && [...rows.keys()].some((pid) => !listed.has(pid))) joined = true;
599
+ const living = [...rows].filter(([, state]) => live(state)).map(([pid]) => pid);
600
+ if (lastFailure === undefined) shown = living;
601
+ if (living.length > 0) {
602
+ unreapedSince = undefined;
603
+ const stuck = unended(living, kill, host.clock.now() - since >= bound, bound, refused);
604
+ if (stuck !== undefined) return settled(stuck);
605
+ } else {
606
+ unreapedSince ??= looked;
607
+ if (host.clock.now() - unreapedSince >= UNREAPED_BOUND) return settled([]);
608
+ }
609
+ }
610
+ }
611
+
612
+ /**
613
+ * Each of `live`, the members a look found alive, by pid and why L0 could not end it, where L0 is
614
+ * done waiting on them: where every one answers `EPERM` to signal 0 through `kill` on this look and
615
+ * on the look before it, which `refused` holds and this updates, or where `late` says `bound` has
616
+ * passed. Nothing where it waits on.
617
+ *
618
+ * One answer of `EPERM` is not enough (`D16` rule 3). The kernel answers signal 0 to a group with
619
+ * `EPERM` while its members are exiting (`occupied`), and a member being killed can answer so for
620
+ * a moment too: taking one such answer for good had the exit cleanup record a killed command as
621
+ * having exited 0, in macOS CI's Node 20 job on #553, which the suite's stand-in forces. Not seen on
622
+ * this host: 1,000 groups of two killed at once, each pid asked signal 0 at once, answered `EPERM`
623
+ * none of the times, with Node 26.5.0 on macOS 27.0 on 2026-10-03. So a member counts as one L0 may not signal only once two looks in a row have found it so, with
624
+ * L0's kill sent between them. A process that answers `EPERM` for a moment on each of two looks in
625
+ * a row is taken as refused all the same.
626
+ */
627
+ function unended(live, kill, late, bound, refused) {
628
+ const now = new Set(live.filter((pid) => forbidden(pid, kill)));
629
+ const lasting = live.every((pid) => now.has(pid) && refused.has(pid));
630
+ refused.clear();
631
+ for (const pid of now) refused.add(pid);
632
+ if (!lasting && !late) return undefined;
633
+ return live.map((pid) => ({ pid, reason: now.has(pid) ? 'EPERM' : `still alive ${bound} ms after L0's first kill` }));
634
+ }
635
+
636
+ /**
637
+ * The failure for a read of the group after the exit cleanup's kill that answered but left out its
638
+ * leader while signal 0 still reached the leader's pid. Node reaps no child while the cleanup runs,
639
+ * so a leader killed there stays in the group as a zombie, and a read that tells the truth lists it:
640
+ * such a read could not say what the group held (`emptied`).
641
+ */
642
+ const leaderUnlisted = (group) => new Error(`the read of the group after its kill did not list its leader, ${group}, while signal 0 still reached its pid`);
643
+
644
+ /** Why the exit cleanup records a process no read after its kill showed had ended, before why the reads failed. */
645
+ const NOT_SHOWN = 'not shown to have ended';
646
+
647
+ /**
648
+ * Whether the leader of `group`, whose pid is the group's id, answers `EPERM` to signal 0 through
649
+ * `kill` on two looks in a row with L0's kill of the group sent between them, as `unended` takes a
650
+ * member L0 may not signal.
651
+ */
652
+ function refusedAcross(group, kill) {
653
+ if (!forbidden(group, kill)) return false;
654
+ signal(group, 'SIGKILL', kill);
655
+ return forbidden(group, kill);
656
+ }
657
+
658
+ /** Whether signal 0 sent through `kill` to `pid` answers `EPERM`: L0 may not signal it. */
659
+ function forbidden(pid, kill) {
660
+ try {
661
+ kill(pid, 0);
662
+ return false;
663
+ } catch (error) {
664
+ if (error.code === 'EPERM') return true;
665
+ if (error.code === 'ESRCH') return false;
666
+ throw error;
667
+ }
668
+ }
669
+
670
+ /**
671
+ * The live members of `group` just before its kill: `named`, each complete identity from the
672
+ * census's current members or earlier sightings still alive by the confirming read, and `listed`,
673
+ * every pid that read listed. An earlier sighting that the confirming read omits still counts where
674
+ * signal 0 reaches its pid. A member that is a zombie there, or that no longer answers signal 0,
675
+ * exited on its own and is not recorded as killed (`there`). Where any read showed a member but
676
+ * no complete name and command line were obtained, `left` records why the group's kill may have
677
+ * ended it. A new live member in the confirming read is named through `namedNow`. The generator
678
+ * yields each read and pause so both the call and exit cleanup can take it.
679
+ *
680
+ * A read that lists no process while signal 0 still reaches the group is taken again, because a
681
+ * member that is exiting still answers signal 0 (`occupied`) and may not be listed, until the group
682
+ * no longer answers or `deadline`, `timeout` after it began, has passed. Then, or where the read
683
+ * fails, every pid the census saw is read by pid in its place, so one that exited on its own is still
684
+ * told apart, and the kill of the group is recorded beside them with why, since a member the census
685
+ * had not named may have been ended. Where that read fails too, it throws, and the group's kill is
686
+ * recorded alone, with why its processes went unnamed.
687
+ *
688
+ * So one class of read is left unrecorded, and nothing but the process table can close it (`D16`
689
+ * rule 3): a read that exits 0, lists at least one row, and consistently leaves out a live member of
690
+ * the group other than the leader, of the census and this one alike. Such a read is taken as
691
+ * complete, so the group's kill ends that hidden member unrecorded. Two instances: a read that
692
+ * lists only the group's zombies while its leader is dead, and one that lists only a member started
693
+ * after the leader while the leader has been reaped.
694
+ *
695
+ * The leader is left out of the class because the census asks signal 0 of the leader's pid, which
696
+ * is the group's id, and reads again while a read leaves out a leader that still answers
697
+ * (`census`). The start-time read catches a hidden live leader the same way, and the note beside it
698
+ * (`startsIn`) records this same class.
699
+ *
700
+ * No read of the table can find another member it consistently hides, because the table is the
701
+ * only thing that says which pids the group holds. The leader alone is known without it, since its
702
+ * pid is the group's id. Signal 0 to the group says only that some process is in it, live or a
703
+ * zombie, not which: measured with Node 26.5.0 on macOS 27.0 on 2026-09-27,
704
+ * `process.kill(pid, 0)` succeeded on a zombie, and a group left holding only a zombie its parent
705
+ * outside the group never reaps kept answering signal 0 (`UNREAPED_BOUND`). So a read hiding a live
706
+ * member while listing zombies is exactly what the table gives for a group holding only zombies,
707
+ * and one hiding it while listing a later member is exactly what it gives for that member alone.
708
+ * Recording the group's kill whenever signal 0 reaches the group would record the kill of every
709
+ * group left holding only zombies, which L0 did not end.
710
+ */
711
+ function* beforeKill(group, members, sightings, kill, timeout, deadline, now = realHost.clock.now) {
712
+ // A settled last round does not erase identities an earlier read obtained.
713
+ const known = [...new Map([...sightings.values()].filter(Boolean).concat(members).map((member) => [member.pid, member])).values()];
714
+ let why;
715
+ for (let wait = 0; why === undefined; wait = longer(wait)) {
716
+ if (wait > 0) yield wait;
717
+ if (!occupied(group, kill)) return { named: [] };
718
+ if (now() >= deadline) {
719
+ why = `the reads of the group just before its kill listed no process for ${timeout} ms while signal 0 still reached it`;
720
+ continue;
721
+ }
722
+ let states;
723
+ try {
724
+ states = rowsOf(yield ['-g', String(group), '-o', 'pid=,stat=']);
725
+ } catch (error) {
726
+ why = `the read of the group just before its kill failed while signal 0 still reached it: ${error.message}`;
727
+ continue;
728
+ }
729
+ if (states.size === 0) continue;
730
+ const named = known.filter(({ pid }) => there(states, pid, kill));
731
+ const listed = new Set(states.keys());
732
+ const extra = [...states].filter(([pid, state]) => live(state) && !known.some((member) => member.pid === pid)).map(([pid]) => pid);
733
+ // A live member the census did not name is named here, before the kill, as the census names one.
734
+ const late = extra.length === 0 ? [] : yield* namedNow(extra);
735
+ const identified = new Set([...named, ...late].map(({ pid }) => pid));
736
+ // Signal 0 checks an omitted sighting; a pid already reaped before this read contributes none.
737
+ const unresolved = new Set([...sightings.keys(), ...extra]);
738
+ const left = [...unresolved].some((pid) => !identified.has(pid) && there(states, pid, kill))
739
+ ? 'a pre-kill read showed a member whose complete name and command line were unavailable, so the group kill may have ended it'
740
+ : undefined;
741
+ return { named: [...named, ...late], left, listed };
742
+ }
743
+ const left = `${why}, so the kill of the group may have ended a process the census had not named`;
744
+ if (sightings.size === 0) return { named: [], left };
745
+ try {
746
+ const states = rowsOf(yield ['-p', [...sightings.keys()].join(','), '-o', 'pid=,stat=']);
747
+ return { named: known.filter(({ pid }) => there(states, pid, kill)), left };
748
+ } catch (error) {
749
+ throw new Error(`${why}, and the read of the census's processes by pid failed too: ${error.message}`);
750
+ }
751
+ }
752
+
753
+ /**
754
+ * Each of `pids` by pid, name and command line, read as the census reads them, leaving out one a
755
+ * read misses, or none where a read fails. It yields each read as `census` does.
756
+ */
757
+ function* namedNow(pids) {
758
+ try {
759
+ const names = yield* namesOf(pids, function* (args) { return yield args; });
760
+ const commands = rowsOf(yield ['-ww', '-p', pids.join(','), '-o', 'pid=,command=']);
761
+ return pids.filter((pid) => names.has(pid) && commands.has(pid)).map((pid) => ({ pid, name: names.get(pid), cmd: commands.get(pid) }));
762
+ } catch {
763
+ return [];
764
+ }
765
+ }
766
+
767
+ /** Whether a process's `state`, as a read of states holds it, is a live one's: not a zombie's. */
768
+ const live = (state) => !state.startsWith('Z');
769
+
770
+ /**
771
+ * Whether `pid` is alive by `states`, a read of states by pid: listed as live, or left out while
772
+ * signal 0 through `kill` still reaches it. A read can leave out a live process, even one that exits
773
+ * 1 and prints nothing (`run`), so a process a read leaves out is gone only where signal 0 no longer
774
+ * reaches it, and one whose pid the system has handed on meanwhile is taken as alive.
775
+ */
776
+ const there = (states, pid, kill) => (states.has(pid) ? live(states.get(pid)) : answers(pid, kill));
777
+
778
+ /** Sends `name` through `kill` to every process in `group`, and to none where the group has emptied. */
779
+ function signal(group, name, kill = SIGNAL) {
780
+ try {
781
+ kill(-group, name);
782
+ } catch (error) {
783
+ // `EPERM` is the answer `occupied` reads as members still exiting, so a later turn retries.
784
+ if (error.code !== 'ESRCH' && error.code !== 'EPERM') throw error;
785
+ }
786
+ }
787
+
788
+ /**
789
+ * Every live process in `group`, each with its pid, its name, which is the executable's name, and
790
+ * its command line. It yields each read of the process table it makes, as the arguments `ps` is
791
+ * given, and takes back what `ps` printed, and each pause before it tries again, as milliseconds.
792
+ * So one census serves the call, which waits on each read and each pause, and the exit cleanup,
793
+ * which can wait on none, and tries again at once (`reading` and `readingNow`).
794
+ *
795
+ * L0 never stops the group to read it (the owner's O62 on #539): a group held stopped while a
796
+ * child of it calls `setsid` leaves that child stopped outside the group for good, as #528's probe
797
+ * found with `git maintenance --detach`. So a process can exec between the reads. One `ps` run
798
+ * reads a process's name from the process table and its arguments a moment later, so a process
799
+ * that execs in between is named by one image and described by the other: the engineer judge on
800
+ * #354 measured that in 16 of 3,000 direct reads. A round first reads the states. Once a whole
801
+ * round has supplied members, a later first state read containing `?` stops that round there: it
802
+ * cannot agree, so the census keeps the last whole round. Otherwise the round reads the command
803
+ * lines, each name in a `ps` run of its own, then the command lines and the states again. It agrees
804
+ * only where both state reads find the same processes, none caught mid-exec (state `?`), and each
805
+ * live one's two command lines agree, with its name read between them. A zombie is left out,
806
+ * because it is already dead. After a round or skipped first read, where the time left can hold
807
+ * another attempt as long as that one took, the next requested pause is capped to leave that time;
808
+ * it never exceeds the uncapped pause. Then the census reads again. Where `deadline` passes first,
809
+ * it keeps the members of the last whole round, each live process that round's final state read
810
+ * found, by the name and command line read in that round. A skipped first read does not replace
811
+ * them. Alongside those members it carries every pid a completed round's state or command read
812
+ * showed, with its name and second command line where both answered. The confirming read decides
813
+ * whether an earlier sighting is still alive.
814
+ *
815
+ * So a name and a command line can come from two images (`D16` rule 3): a process that went on
816
+ * exec'ing past `deadline`, or that exec'd between the two command-line reads into one with the same
817
+ * arguments, is recorded by the name of one image and the command line of another. Measured with
818
+ * Node 26.5.0 on macOS 27.0 on 2026-10-02, against the suite's survivor that re-executes inside the
819
+ * first read of command lines: over 10 runs, the census recorded the image it became, by its name
820
+ * and command line alike, since its name is read after that read.
821
+ * A member can exec after the last whole round; if later first state reads report `?`, the
822
+ * deadline result still carries that earlier round's name and command line. How old that kept
823
+ * identity can be relative to the last read has not been measured.
824
+ *
825
+ * Reads that agree on no process at all are kept only where signal 0 no longer reaches the group,
826
+ * because a read that failed can list nothing, even one that exits 1 and prints nothing (`run`).
827
+ * While the group still answers, the census reads again, and where `timeout` passes first it fails
828
+ * saying so, and the group is killed unnamed.
829
+ *
830
+ * Reads that agree and leave out the group's leader are kept only where signal 0 no longer reaches
831
+ * the leader's pid, which is the group's id, as the start-time read holds (`startsIn`). A leader
832
+ * that has exited and not been reaped is listed as a zombie, so a leader left out while its pid
833
+ * still answers was left out by a read that failed. The census then reads again the same way, and
834
+ * where `timeout` passes first the group is killed unnamed, so a live leader every read hides is
835
+ * recorded as the kill of the group, not ended unrecorded.
836
+ *
837
+ * A read of states or command lines holds the pid and that one column, so no field of varying
838
+ * width comes before the one split it takes. `ps` pads a column by display width, and a name of
839
+ * wide characters is padded to fewer characters than a narrow one, so splitting after it misread
840
+ * the row (the engineer judge on #354, with `日本語日本` run as `exec -a Tx`). Each name is read in
841
+ * a `ps` run for that pid alone, because a name can hold a newline, and in a read of the group it
842
+ * then prints as a line of its own that reads as another process's row.
843
+ *
844
+ * Where `ps`'s answer can differ from the process's own (`D16` rule 3), measured with `ps` from
845
+ * adv_cmds-240 on macOS 27.0 (26A428) on 2026-09-27:
846
+ *
847
+ * - `ucomm` is the executable's name as the kernel holds it, cut to 16 bytes, so a name longer
848
+ * than that is recorded as its first 16 bytes, less any spaces they end in: `abcdefghijklmnopq`
849
+ * is recorded as `abcdefghijklmnop`, and `abcdefghijklmno xyz` as `abcdefghijklmno`. A cut can fall inside a character and leave bytes that are not UTF-8 (the
850
+ * engineer judge on #354 saw `日本語テール` recorded as `日本語テー` and U+FFFD).
851
+ * - `ucomm` is padded with spaces to 16 columns, even as the last column, so a name's own trailing
852
+ * spaces cannot be recovered, and are not recorded. `sp` and `sp` with a space print the same
853
+ * 17 bytes, and so do `abcdefghijklmno`, the same with a space, and the same with a space and
854
+ * `x`, under every `ucomm` form and locale tried. Other trailing whitespace is the name's own:
855
+ * a trailing newline or tab is recorded.
856
+ * - `ucomm` prints control characters raw, a newline included, so a name `x`, newline,
857
+ * `<pid> evil` read in the group's table named that other pid's process `evil` (the engineer
858
+ * judge on #354). It names what runs, not what was asked for: a script run by `/bin/sh` is
859
+ * named `bash`.
860
+ * - `-c` makes `command` argv[0]'s last part, not the executable's name: `exec -a Tx` shows `Tx`.
861
+ * - `stat`'s first character is the process's state: `T` stopped, `Z` a zombie, `?` caught
862
+ * mid-exec.
863
+ * - `xstat` is a zombie's wait status in hexadecimal: `0` for a process that exited 0, `300` for
864
+ * one that exited 3, `9` for one `SIGKILL` ended and `f` for one `SIGTERM` ended. It is there to
865
+ * read only while the zombie's parent has not reaped it.
866
+ * - `comm` is argv[0], so `exec -a <anything>` names the process `<anything>`. It is cut to 16
867
+ * characters, measured with an ASCII name, unless it is the last column. The command line
868
+ * already begins with argv[0], so the name is the executable's.
869
+ * - `command` writes control characters escaped, a newline as `\012` (the engineer judge on #354),
870
+ * so each process's command line is one line of the group's read.
871
+ * - `command` is the process's arguments joined by spaces, so arguments holding spaces cannot be
872
+ * told apart from more arguments. A process caught mid-exec, or a zombie, shows `(name)` or
873
+ * `<defunct>` in its place.
874
+ * - Under no locale, `ps` writes each byte outside ASCII in `vis` form, so `ü` reads `M-CM-<`.
875
+ * Under `LC_ALL=C.UTF-8`, which `ps` is given here, UTF-8 text reads unchanged. So `ps` gets
876
+ * that locale, the zone `startOf` gives it, and nothing else of the caller's environment.
877
+ * - The engineer measured a whole-table read (`ps -A`) cutting command lines at about 1,160
878
+ * characters where a read of one pid returned all 10,031 (card #336, engineer's round 4 on
879
+ * #332). On this host and date it did not reproduce: `ps -A`, `ps -g` and `ps -p` each returned
880
+ * whole a command line carrying one argument of 10,031 characters, with `COLUMNS` unset, 80 or
881
+ * 1160, and one carrying an argument of 100,000. The cause of the engineer's cut is not known,
882
+ * so this reads one group rather than the whole table, with `-ww`, which the manual says uses
883
+ * as many columns as are needed.
884
+ * - `-g` lists the processes whose group is `group`. A process that leaves the group before the
885
+ * read is not listed, and one that joins it after the read is recorded only as the kill of the
886
+ * group, where the read before the kill finds it (`beforeKill`, `contain`).
887
+ * - `ps` exits 1, printing nothing, when no process matches, and writes to standard error when a
888
+ * read fails (`run`).
889
+ */
890
+ export function* census(group, kill, deadline, now = realHost.clock.now, trace) {
891
+ // Why the census's last reads that agreed were not kept: they left out what signal 0 reached.
892
+ let unseen;
893
+ // What the last round held, kept where `deadline` passes before a round agrees.
894
+ let last;
895
+ // Retain every pid a fully parsed column showed, even where a later round settles without it.
896
+ const sightings = new Map();
897
+ const read = function* (args) {
898
+ try {
899
+ return yield args;
900
+ } catch (error) {
901
+ throw unseen ? Object.assign(new Error(`the census's reads ${unseen}: ${error.message}`), { code: error.code }) : error;
902
+ }
903
+ };
904
+ const column = function* (name) {
905
+ const rows = rowsOf(yield* read(['-ww', '-g', String(group), '-o', `pid=,${name}=`]));
906
+ for (const pid of rows.keys()) if (!sightings.has(pid)) sightings.set(pid, undefined);
907
+ return rows;
908
+ };
909
+ let took = 0;
910
+ let serial = 0;
911
+ for (let wait = 0; ; wait = longer(wait)) {
912
+ const left = deadline - now();
913
+ const requested = left >= took ? Math.min(wait, left - took) : wait;
914
+ trace?.({ phase: 'wait.decision', round: serial + 1, clock: now(), deadline, left, took, baseWait: wait, requested });
915
+ if (requested > 0) yield requested;
916
+ if (last !== undefined && now() >= deadline) {
917
+ trace?.({ phase: 'census.deadline', clock: now(), deadline, members: last });
918
+ return { members: last, sightings };
919
+ }
920
+ const began = now();
921
+ serial += 1;
922
+ trace?.({ phase: 'round.start', round: serial, clock: began, deadline });
923
+ let round;
924
+ try {
925
+ const before = yield* column('stat');
926
+ // A mid-exec state cannot make this round agree. Keep the last whole round while one exists.
927
+ if (last !== undefined && [...before.values()].some((state) => state.startsWith('?'))) {
928
+ took = now() - began;
929
+ trace?.({ phase: 'round.skip', round: serial, clock: now(), took, reason: 'mid-exec first state', before: [...before] });
930
+ continue;
931
+ }
932
+ const lines = yield* column('command');
933
+ const names = yield* namesOf([...before].filter(([, state]) => live(state)).map(([pid]) => pid), read);
934
+ const commands = yield* column('command');
935
+ const after = yield* column('stat');
936
+ round = { before, lines, names, commands, after };
937
+ took = now() - began;
938
+ trace?.({ phase: 'round.read', round: serial, clock: now(), took, before: [...before], after: [...after], names: [...names], lines: [...lines], commands: [...commands] });
939
+ } catch (error) {
940
+ trace?.({ phase: 'round.failure', round: serial, clock: now(), code: error.code, message: error.message });
941
+ // A read given up on at `deadline` leaves the last round to keep, where there is one.
942
+ if (last !== undefined && (error.code === 'ETIMEDOUT' || error.code === LATE)) return { members: last, sightings };
943
+ throw error;
944
+ }
945
+ const { before, lines, names, commands, after } = round;
946
+ for (const pid of new Set([...before.keys(), ...lines.keys(), ...commands.keys(), ...after.keys()])) {
947
+ if (!sightings.has(pid)) sightings.set(pid, undefined);
948
+ // The first command read tests consistency; the second supplies the recorded command line.
949
+ if (names.has(pid) && commands.has(pid)) sightings.set(pid, { pid, name: names.get(pid), cmd: commands.get(pid) });
950
+ }
951
+ unseen = after.size === 0 && occupied(group, kill) ? 'named no process of the group while it still had one'
952
+ : !after.has(group) && answers(group, kill) ? `left out the group's leader, ${group}, while signal 0 still reached its pid`
953
+ : undefined;
954
+ if (unseen) {
955
+ trace?.({ phase: 'round.unseen', round: serial, clock: now(), reason: unseen });
956
+ continue;
957
+ }
958
+ const living = [...after].filter(([, state]) => live(state)).map(([pid]) => pid);
959
+ last = living.filter((pid) => names.has(pid) && commands.has(pid)).map((pid) => ({ pid, name: names.get(pid), cmd: commands.get(pid) }));
960
+ const settled = [before, after].every((states) => [...states.values()].every((state) => !state.startsWith('?')));
961
+ const agreed = settled && samePids(before, after) && living.every((pid) => names.has(pid) && commands.has(pid) && lines.get(pid) === commands.get(pid));
962
+ trace?.({ phase: 'round.decision', round: serial, clock: now(), deadline, agreed, settled, members: last });
963
+ if (agreed) return { members: last, sightings };
964
+ }
965
+ }
966
+
967
+ /** Whether every process a read of states holds is stopped, or is a zombie. */
968
+ const stopped = (states) => [...states.values()].every((state) => state.startsWith('T') || state.startsWith('Z'));
969
+
970
+ /** Whether two reads hold the same processes. */
971
+ const samePids = (one, other) => one.size === other.size && [...one.keys()].every((pid) => other.has(pid));
972
+
973
+ /**
974
+ * Each of `pids`' names, read in a `ps` run of its own, so the whole of that run's output is that
975
+ * one process's name, whatever bytes it holds. A process no longer there is left out.
976
+ *
977
+ * So the census grows with the group. Measured with `/bin/ps` from adv_cmds-240 and Node 26.5.0
978
+ * on macOS 27.0 (26A428) on 2026-09-27, on 12 cores: 300 such reads, one per `tail` in one group,
979
+ * took 1.09 to 1.23 ms each over three runs at a load average of about 23, and 2.13 to 3.29 ms
980
+ * each over three more at about 9. One read of that group's command lines took 9 to 15 ms. At
981
+ * 3.29 ms a survivor, the names alone reach `READ_TIMEOUT` at about 1,500 survivors, and fewer
982
+ * once the group's other reads are counted. Such a group is killed unnamed.
983
+ */
984
+ function* namesOf(pids, read) {
985
+ const names = new Map();
986
+ for (const pid of pids) {
987
+ const printed = yield* read(['-p', String(pid), '-o', 'ucomm=']);
988
+ // `ps` ends the name with its padding, spaces alone, and a newline, which are not the name's own.
989
+ const name = printed.replace(/ *\n$/, '');
990
+ if (name !== '') names.set(pid, name);
991
+ }
992
+ return names;
993
+ }
994
+
995
+ /** Each line of a read of one column, by the pid it begins with. */
996
+ function rowsOf(printed) {
997
+ const rows = new Map();
998
+ for (const line of printed.split('\n').filter(Boolean)) {
999
+ // The pid is right-aligned and followed by one space, so the rest of the line is the column.
1000
+ const row = /^\s*(\d+) (.*)$/.exec(line);
1001
+ // A row this cannot read is a process it cannot name, so the census fails rather than
1002
+ // leave that process out of it.
1003
+ if (!row) throw new Error(`the process table held a row the census cannot read: ${JSON.stringify(line)}`);
1004
+ rows.set(Number(row[1]), row[2]);
1005
+ }
1006
+ return rows;
1007
+ }
1008
+
1009
+ /**
1010
+ * Runs each read of the process table `looks` yields in `ps`, one at a time, and waits out each
1011
+ * pause it yields, and hands back what `looks` returns. The reads are given up at `deadline`,
1012
+ * which is `timeout` milliseconds after the first starts where the caller gives none.
1013
+ */
1014
+ async function reading(looks, ps, timeout, deadline, trace, host = realHost) {
1015
+ deadline ??= host.clock.now() + timeout;
1016
+ let look = looks.next();
1017
+ while (!look.done) {
1018
+ if (typeof look.value === 'number') {
1019
+ trace?.({ phase: 'pause.start', clock: host.clock.now(), requested: look.value, cpu: process.cpuUsage() });
1020
+ await host.clock.pause(look.value);
1021
+ trace?.({ phase: 'pause.end', clock: host.clock.now(), cpu: process.cpuUsage() });
1022
+ look = looks.next();
1023
+ } else {
1024
+ let printed;
1025
+ const args = look.value;
1026
+ const started = host.clock.now();
1027
+ trace?.({ phase: 'read.start', clock: started, deadline, remaining: deadline - started, args, cpu: process.cpuUsage() });
1028
+ try {
1029
+ printed = await run(...toolOf(look.value, ps), deadline - host.clock.now(), timeout, host);
1030
+ } catch (error) {
1031
+ trace?.({ phase: 'read.failure', clock: host.clock.now(), args, code: error.code, message: error.message, cpu: process.cpuUsage() });
1032
+ look = looks.throw(error);
1033
+ continue;
1034
+ }
1035
+ trace?.({ phase: 'read.answer', clock: host.clock.now(), args, length: printed.length, prefix: printed.slice(0, 100), suffix: printed.slice(-100), cpu: process.cpuUsage() });
1036
+ look = looks.next(printed);
1037
+ }
1038
+ }
1039
+ return look.value;
1040
+ }
1041
+
1042
+ /** The tool a read `looks` yields runs in, and its arguments: `ps` for a list of them, or the `tool` it names. */
1043
+ const toolOf = (read, ps) => (Array.isArray(read) ? [ps, read] : [read.tool, read.args]);
1044
+
1045
+ /** `reading`, synchronously, for the exit cleanup, which passes over each pause. */
1046
+ function readingNow(looks, ps, timeout, deadline, now = realHost.clock.now, spawn = realHost.spawnSync) {
1047
+ if (deadline === undefined) deadline = now() + timeout;
1048
+ let look = looks.next();
1049
+ while (!look.done) {
1050
+ if (typeof look.value === 'number') {
1051
+ look = looks.next();
1052
+ continue;
1053
+ }
1054
+ let printed;
1055
+ try {
1056
+ printed = runNow(...toolOf(look.value, ps), deadline - now(), timeout, now, spawn);
1057
+ } catch (error) {
1058
+ look = looks.throw(error);
1059
+ continue;
1060
+ }
1061
+ look = looks.next(printed);
1062
+ }
1063
+ return look.value;
1064
+ }
1065
+
1066
+ /**
1067
+ * How `ps` and `lsof` are run besides their environment: synchronous reads are killed outright at
1068
+ * `remaining` milliseconds, or at `TIMER_MAX` where that is less, since Node runs a longer timeout
1069
+ * out at once. The asynchronous `run` owns the same deadline and overrides this option's timeout.
1070
+ * Each read works in `/`, so the census of working directories never lists a read of its own, nor
1071
+ * one of another call's, as working in a dispatch's directory.
1072
+ */
1073
+ const reader = (remaining) => ({ timeout: Math.min(remaining, TIMER_MAX), killSignal: 'SIGKILL', maxBuffer: Infinity, encoding: 'utf8', cwd: '/' });
1074
+
1075
+ /** The `code` of the failure for reads of the process table that ran out of time between reads. */
1076
+ const LATE = 'LATE';
1077
+
1078
+ /** The failure for reads of the process table that ran out of time between reads. */
1079
+ const late = (timeout) => Object.assign(new Error(`the reads of the process table did not finish within ${timeout} ms`), { code: LATE });
1080
+
1081
+ /** The failure for a read of the process table that wrote `stderr`, which `ps` does only on a failure (`run`). */
1082
+ const failed = (stderr) => new Error(`the process-table read failed: ${stderr.trim()}`);
1083
+
1084
+ /** The failure for a read of the process table that ran out of time, with Node's code for one. */
1085
+ const timedOut = (timeout) => Object.assign(new Error(`the process-table read timed out after ${timeout} ms`), { code: 'ETIMEDOUT' });
1086
+
1087
+ /** The failure for a run of `tool` given `args` that ended with `status`, an exit code or a signal, other than as `ps` ends when no process matched (`run`). */
1088
+ const exited = (tool, args, status) => new Error(`${tool} ${args.join(' ')} ended with ${status}`);
1089
+
1090
+ /**
1091
+ * What one run of `ps`, at the path `ps` names, prints given `args`, or nothing where no process
1092
+ * matches. It is given up on after `remaining` milliseconds of the census's `timeout`. A run that
1093
+ * writes anything to standard error has failed, whatever its exit code.
1094
+ *
1095
+ * How `ps` reports that no process matched, against a read that failed (`D16` rule 3), measured
1096
+ * with `ps` from adv_cmds-240 on macOS 27.0 (26A428) on 2026-09-28: each of the adapter's five
1097
+ * forms of read, given a group or pid that holds no process, exits 1 and writes nothing to either
1098
+ * stream. Given a group `x`, a group `999999` or an unknown keyword, it exits 1 and writes why to
1099
+ * standard error. The source of adv_cmds-237, the latest Apple publishes, agrees: `ps` exits 1
1100
+ * with nothing written only once it kept no process, and every failure it reports is written to
1101
+ * standard error, one of them, a failed read of the kernel's table, with exit 0 and nothing on
1102
+ * standard output. So exit 1 with nothing on either stream is the one answer that shows no process
1103
+ * matched.
1104
+ *
1105
+ * Node 26.5.0's `execFile` can call back without an error after its timeout fires when the child
1106
+ * exited 0 first but a descendant still holds its output open: the callback carries only the
1107
+ * output read before the pipe closed. Measured by running `test/read-deadline.test.mjs` over base
1108
+ * source `78554e7` on macOS 27.0 on 2026-10-06. This run owns its deadline and closes the read's
1109
+ * pipes when it fires, so it settles without waiting for a descendant and never accepts that
1110
+ * partial answer (`D16` rule 3).
1111
+ *
1112
+ * What `ps` cannot show is that the kernel handed it every process there is, so neither the census
1113
+ * nor the kill takes a process as gone because a read left it out (`census`, `beforeKill`), and the
1114
+ * start-time read takes neither an empty read nor a missing leader as the group's (`startsIn`).
1115
+ */
1116
+ function run(ps, args, remaining, timeout, host = realHost) {
1117
+ return new Promise((resolve, reject) => {
1118
+ if (remaining <= 0) return reject(late(timeout));
1119
+ let expired = false;
1120
+ const read = host.execFile(ps, args, { env: PS_ENV, ...reader(remaining), timeout: 0 }, (error, stdout, stderr) => {
1121
+ host.clock.cancel(deadline);
1122
+ reads.delete(read);
1123
+ if (expired) return reject(timedOut(timeout));
1124
+ if (stderr !== '') return reject(failed(stderr));
1125
+ if (error && !(error.code === 1 && stdout === '')) return reject(typeof error.code === 'number' || error.signal ? exited(ps, args, error.code ?? error.signal) : error);
1126
+ resolve(stdout);
1127
+ });
1128
+ const deadline = host.clock.schedule(() => {
1129
+ expired = true;
1130
+ host.killChild(read, 'SIGKILL');
1131
+ read.stdout?.destroy();
1132
+ read.stderr?.destroy();
1133
+ reject(timedOut(timeout));
1134
+ }, Math.min(remaining, TIMER_MAX));
1135
+ reads.set(read, host);
1136
+ });
1137
+ }
1138
+
1139
+ /**
1140
+ * `run`, synchronously, for the exit cleanup. A synchronous run returns only once every holder of
1141
+ * its pipe has closed it, and `ps` starts nothing that outlives it, so its own kill at `remaining`
1142
+ * milliseconds ends the wait.
1143
+ */
1144
+ function runNow(ps, args, remaining, timeout, now = realHost.clock.now, spawn = realHost.spawnSync) {
1145
+ const began = now();
1146
+ try {
1147
+ const printed = runOnce(ps, args, remaining, timeout, spawn);
1148
+ unreadSince = undefined;
1149
+ return printed;
1150
+ } catch (error) {
1151
+ unreadSince ??= began;
1152
+ throw error;
1153
+ }
1154
+ }
1155
+
1156
+ /** `runNow`'s one run, each failure as it arose. */
1157
+ function runOnce(ps, args, remaining, timeout, spawn = realHost.spawnSync) {
1158
+ if (remaining <= 0) throw late(timeout);
1159
+ if (unanswered.has(ps)) throw new Error(`${timedOut(unanswered.get(ps)).message} earlier in the exit cleanup, which does not wait on it again`);
1160
+ const { error, status, signal: ending, stdout, stderr } = spawn(ps, args, { env: PS_ENV, ...reader(remaining) });
1161
+ if (error?.code === 'ETIMEDOUT') {
1162
+ unanswered.set(ps, timeout);
1163
+ throw timedOut(timeout);
1164
+ }
1165
+ if (error) throw error;
1166
+ if (stderr !== '') throw failed(stderr);
1167
+ if (status !== 0 && !(status === 1 && stdout === '')) throw exited(ps, args, status ?? ending);
1168
+ return stdout;
1169
+ }
1170
+
1171
+ /**
1172
+ * Ends what is left of `group`, once its command has exited or at its timeout, and hands back the
1173
+ * `L0` events to record, without ever stopping the group (`census`). In order:
1174
+ *
1175
+ * 1. the census reads which processes the group holds, retaining each sighting and any complete
1176
+ * name and command line it found;
1177
+ * 2. a read of states just before the kill checks which of those sightings remain alive
1178
+ * (`beforeKill`);
1179
+ * 3. L0 kills the group whole, through `kill`;
1180
+ * 4. L0 kills it and reads it again until no member is left alive (`ended`);
1181
+ * 5. and only then it hands back a `killed` event for each still-live member whose name and
1182
+ * command line were read, and the group kill where a shown member could not be named. Each
1183
+ * member still alive at `KILL_BOUND`, or that L0 may not signal, is handed
1184
+ * back as a process it could not end, with why, in place of a kill.
1185
+ *
1186
+ * A census or a read before the kill that fails still has the group killed, and hands back the
1187
+ * kill of the group with why its processes went unnamed.
1188
+ *
1189
+ * Where this can be wrong (`D16` rule 3):
1190
+ *
1191
+ * - A member that exits on its own between the read before the kill and the kill is recorded as
1192
+ * killed: nothing after the kill tells its own exit from the kill. Measured with Node 26.5.0 on
1193
+ * macOS 27.0 on 2026-10-02, against the suite's quitter that exits inside that read: it was
1194
+ * recorded as killed in each of 10 runs.
1195
+ * - A name and a command line can come from two images (`census`).
1196
+ * - A process that joins the group after the read before the kill is recorded as the kill of the
1197
+ * group where a read after the kill lists it, alive or a zombie (`ended`), though a zombie may
1198
+ * have exited on its own. Where a read after the kill fails, the kill of the group is recorded in
1199
+ * place of what it could not list (`R-STATE-19`). Only one the kill ends and a parent outside the
1200
+ * group reaps before any such read is ended unrecorded. No read can tell that joiner from a group holding only zombies:
1201
+ * signal 0 reaches both, and once its parent has reaped it, the table holds only the zombies both
1202
+ * leave behind. Recording the kill of the group whenever that could have happened would record it
1203
+ * for every group left holding only zombies.
1204
+ * - Where every read after the kill fails, each member the read before the kill found alive that
1205
+ * signal 0 still reaches is recorded as not shown to have ended, though it may be a zombie the
1206
+ * kill ended; and where the last read after the kill fails, so is each the last read that
1207
+ * succeeded found alive, though a later kill may have ended it (`reachedUnread`).
1208
+ */
1209
+ async function contain(group, { ps, readTimeout, kill = SIGNAL, trace, host = realHost }, killed) {
1210
+ if (!occupied(group, kill)) return [];
1211
+ // Each step ends `readTimeout` after it begins, and its reads are given up `spare` after that.
1212
+ const within = (step, spare = 0) => {
1213
+ const deadline = host.clock.now() + readTimeout;
1214
+ return reading(step(deadline), ps, readTimeout, deadline + spare, trace, host);
1215
+ };
1216
+ let named;
1217
+ let left;
1218
+ let listed;
1219
+ let unnamed;
1220
+ try {
1221
+ const { members, sightings } = await within((deadline) => census(group, kill, deadline, host.clock.now, trace));
1222
+ ({ named, left, listed } = await within((deadline) => beforeKill(group, members, sightings, kill, readTimeout, deadline, host.clock.now), readTimeout));
1223
+ } catch (error) {
1224
+ unnamed = error.message;
1225
+ }
1226
+ const { stuck, joined, unread, unlisted, unconfirmed } = await ended(group, { ps, readTimeout, kill, host }, KILL_BOUND, listed);
1227
+ if (joined && unnamed === undefined) left ??= 'a read after the kill found a process in the group, alive or exited, that the read just before the kill had not listed: the kill of the group was sent while it may have been a member, though it may have exited on its own';
1228
+ if (unread !== undefined && unnamed === undefined) left ??= `the reads of the group after its kill failed, so the kill of the group may have ended a process no read before it had listed: ${unread}`;
1229
+ const unshown = [...stuck, ...reachedUnread(named, stuck, { unlisted, unconfirmed }, kill)];
1230
+ const unended = await reading(described(unshown, named), ps, readTimeout, undefined, undefined, host).catch(() => unshown);
1231
+ return killsOf(group, { named, unnamed, left, unended }, killed);
1232
+ }
1233
+
1234
+ /**
1235
+ * Each of `named`, the members the read before the kill found alive, that `stuck` does not hold and
1236
+ * that signal 0, sent through `kill` to its pid, still reaches once `ended` has settled, by pid and
1237
+ * why: `EPERM` where L0 may not signal it, and otherwise that it was not shown to have ended. It
1238
+ * takes each such member where `unlisted` says every read of the group after its kill failed, and
1239
+ * only those `unconfirmed` says the last read that succeeded found alive, where a read after the
1240
+ * kill succeeded and the last read failed. No read listed it ended after the kill, so nothing shows
1241
+ * the kill ended it, and it is not recorded as killed (`R-STATE-19`). Where the last read after the
1242
+ * kill succeeded, this adds none: what the reads listed decides.
1243
+ *
1244
+ * Where this can be wrong (`D16` rule 3):
1245
+ * - Signal 0 reaches a zombie as it reaches a live process, and a process given the pid of a member
1246
+ * the kill ended, so where every read after the kill failed, either is recorded here as not shown
1247
+ * to have ended though the kill may have ended it. Only a read of the table tells a zombie from a
1248
+ * live process, and no read after the kill could be made.
1249
+ * - Where a read after the kill succeeded and every later one failed, a member the last read that
1250
+ * succeeded showed alive, that signal 0 still reaches, is recorded as not shown to have ended,
1251
+ * though a kill sent after that read may have ended it and left it a zombie, or its pid may have
1252
+ * been given to another process: no later read could tell.
1253
+ * - Where a read after the kill succeeded and every later one failed, a member the last read that
1254
+ * succeeded showed a zombie, or did not list, is recorded as killed: a zombie has ended, and a
1255
+ * later failure does not undo what that read showed.
1256
+ * - One answer of `EPERM` is taken as refused here, unlike in `unended`, because it is asked once
1257
+ * `ended` has settled, after the kill was sent on more than one look, and not while a member is
1258
+ * being killed: that this is long enough is a judgment, not a measurement.
1259
+ */
1260
+ function reachedUnread(named = [], stuck, { unlisted, unconfirmed }, kill) {
1261
+ const held = new Set(stuck.map(({ pid }) => pid));
1262
+ const unshown = unlisted !== undefined ? named : named.filter(({ pid }) => unconfirmed?.alive.has(pid));
1263
+ const why = unlisted !== undefined ? `signal 0 still reaches it, alive or a zombie, and the reads of the group after its kill failed: ${unlisted}` : `the last read of the group that answered after its kill showed it alive, and later reads failed: ${unconfirmed?.why}`;
1264
+ return unshown.filter(({ pid }) => !held.has(pid) && answers(pid, kill)).map(({ pid }) => ({ pid, reason: forbidden(pid, kill) ? 'EPERM' : `not shown to have ended: ${why}` }));
1265
+ }
1266
+
1267
+ /**
1268
+ * `contain`, synchronously, for the exit cleanup, with the kill confirmed by `emptied`. Its census,
1269
+ * its read before the kill and its record are `contain`'s own, and it waits on no bound longer than
1270
+ * its own, `readTimeout`: a member still alive that long after its first kill is handed back as a
1271
+ * process it could not end, in place of a kill at `KILL_BOUND`. Unlike `contain`, it also records
1272
+ * the kill of the group where a process joined the group after the read before the kill and the
1273
+ * confirmation read it live, which it reads before its first kill (`emptied`).
1274
+ *
1275
+ * A joiner one confirmation read finds alive, and that exits on its own and is reaped before L0's
1276
+ * next kill reaches the group, is recorded in the kill of the group. No read can tell its own exit
1277
+ * from L0's kill once it has been reaped (`D16` rule 3): the table shows how a process ended only as
1278
+ * its zombie's `xstat`, which `ps` shows until the parent reaps it and never after, and a joiner's
1279
+ * parent outside the group can reap it before any read.
1280
+ *
1281
+ * One window is also excluded, as in `contain`: a process that joins the group after L0's last read
1282
+ * of it, is ended by L0's next kill, and is reaped by a parent outside the group before any read
1283
+ * lists it, is ended unrecorded. A read after a kill that fails has the kill of the group recorded
1284
+ * in place of what it could not list (`emptied`).
1285
+ * A failed first confirmation read, before the kill, is also retained: a later read can omit a
1286
+ * joiner whose outside parent already reaped it, or the failure can end this cleanup's reads.
1287
+ *
1288
+ * Where the confirmation's reads fail or run out of time, the group has the kill on every look until
1289
+ * `UNREAPED_BOUND` has passed, and the cleanup goes on: it cannot wait longer on a process table it
1290
+ * cannot read.
1291
+ */
1292
+ export function containNow(group, { readTimeout, host = realHost }) {
1293
+ requireClock(host.clock);
1294
+ const { ps } = host;
1295
+ const { now } = host.clock;
1296
+ const spawn = host.spawnSync;
1297
+ const kill = host.signal;
1298
+ if (!occupied(group, kill)) return { kills: [] };
1299
+ // Each step ends `readTimeout` after it begins, and its reads are given up `spare` after that.
1300
+ const within = (step, spare = 0) => {
1301
+ const deadline = now() + readTimeout;
1302
+ return readingNow(step(deadline), ps, readTimeout, deadline + spare, now, spawn);
1303
+ };
1304
+ let named;
1305
+ let left;
1306
+ let listed;
1307
+ let unnamed;
1308
+ try {
1309
+ const { members, sightings } = within((deadline) => census(group, kill, deadline, now));
1310
+ ({ named, left, listed } = within((deadline) => beforeKill(group, members, sightings, kill, readTimeout, deadline, now), readTimeout));
1311
+ } catch (error) {
1312
+ unnamed = error.message;
1313
+ }
1314
+ // Where the group is already recorded as killed whole, the confirmation kills before it reads.
1315
+ const seen = { live: false, first: unnamed === undefined && left === undefined, listed: listed ?? new Set((named ?? []).map(({ pid }) => pid)), named: new Map(), asked: new Set() };
1316
+ let leader;
1317
+ let unread;
1318
+ let stuck = [];
1319
+ try {
1320
+ ({ leader, stuck } = readingNow(emptied(group, seen, kill, readTimeout, now), ps, readTimeout, undefined, now, spawn));
1321
+ if (leader === undefined && stuck.length === 0) unread = 'the process table did not list it';
1322
+ } catch (error) {
1323
+ // A failed first look is retained in seen.beforeUnread; send its pending group kill now.
1324
+ if (!seen.sent) signal(group, 'SIGKILL', kill);
1325
+ unread = error.message;
1326
+ // No read after the kill showed the members ended, so each the read before it found alive that
1327
+ // signal 0 still reaches is not shown to have ended, the leader among them. Where this can be
1328
+ // wrong (`D16` rule 3): a zombie answers signal 0 as a live process does, and Node reaps the
1329
+ // leader's only once this process exits, so a leader or member the kill did end is counted too.
1330
+ // A leader that answers `EPERM` is not that zombie, so it is one L0 may not signal.
1331
+ const why = `the process table could not be read after the kill: ${error.message}`;
1332
+ stuck = (named ?? []).filter(({ pid }) => answers(pid, kill)).map(({ pid }) => ({ pid, reason: pid === group && refusedAcross(group, kill) ? 'EPERM' : `${NOT_SHOWN}: ${why}` }));
1333
+ }
1334
+ // The first confirmation's failure may be the only evidence of a member that joined after
1335
+ // beforeKill. Keep it even if every later read omits that member or no later read runs.
1336
+ if (unnamed === undefined && seen.beforeUnread !== undefined) left ??= `the first read of the group before its kill failed, so the kill of the group may have ended a process no read before it had listed: ${seen.beforeUnread}`;
1337
+ if (unnamed === undefined && seen.unread !== undefined) left ??= `the reads of the group after its kill failed, so the kill of the group may have ended a process no read before it had listed: ${seen.unread}`;
1338
+ if (unnamed === undefined && seen.live) left ??= 'a read after the kill found a process in the group, alive or exited, that the read just before the kill had not listed: the kill of the group was sent while it may have been a member, though it may have exited on its own';
1339
+ // A member the census named is recorded by its name and command line, and so is one that joined
1340
+ // after the read before the kill, where the confirmation read both while it lived (`emptied`).
1341
+ // Otherwise it is recorded by its pid alone, since the cleanup reads nothing past its own bound
1342
+ // (`D16` rule 3): those reads can fail, and the bound can run out before them.
1343
+ const known = new Map([...(named ?? []).map((member) => [member.pid, member]), ...[...seen.named.values()].map((member) => [member.pid, member])]);
1344
+ const unended = stuck.map(({ pid, reason }) => ({ ...known.get(pid), pid, reason }));
1345
+ // A leader the kill could not end, or that no read after it showed ended, is handed to the caller's
1346
+ // step as why its ending is unread.
1347
+ const leaderUnended = stuck.find(({ pid }) => pid === group);
1348
+ if (leaderUnended !== undefined) unread = leaderUnended.reason.startsWith(NOT_SHOWN) ? `the command was ${leaderUnended.reason}` : `the exit cleanup could not end the command: ${leaderUnended.reason}`;
1349
+ return { kills: killsOf(group, { named, unnamed, left, unended }, 'survivor.killed'), leader, unread };
1350
+ }
1351
+
1352
+ /**
1353
+ * Kills every process left in `group` through `kill` until it holds nothing but zombies, for the
1354
+ * exit cleanup, and hands back the wait status `ps` reads for the group's leader as `leader`, where
1355
+ * it is still there, and as `stuck` each member L0 could not end (`ended` says which). Node reaps no
1356
+ * child while synchronous code runs, so a leader killed here stays in the group as a zombie until
1357
+ * this process exits, and the group never empties while the cleanup runs. So each look reads the
1358
+ * group's states, and a group of zombies is ended: none of them can run again.
1359
+ *
1360
+ * Its reads end at the cleanup's own bound, `bound`, the read timeout from the start of its first
1361
+ * read, as every step of the cleanup's do. A member the last read after a kill found alive, when the
1362
+ * next read can no longer be made, is one L0 could not end, and so is each still alive where every
1363
+ * one answers `EPERM`. A read that fails is taken again, with the kill sent on every look, until
1364
+ * `UNREAPED_BOUND` has passed since the cleanup's reads began to fail, or the bound has, and then
1365
+ * its failure is thrown. That clock is the cleanup's, not the group's (`unreadSince`), so a process
1366
+ * table that cannot be read holds the process's ending back once, and not once for each group.
1367
+ *
1368
+ * Where `seen.first` is set, it reads the group once before its first kill, so a process that
1369
+ * joined the group after the reads before it is read live before the kill ends it. It sets
1370
+ * `seen.sent` once it has sent a kill. A failure of that first read is kept in
1371
+ * `seen.beforeUnread`, including when the bound prevents any later read. Where a look lists a
1372
+ * process, alive or a zombie, that is not
1373
+ * among `seen.listed`, every process the read before the kill listed, it sets `seen.live`, even
1374
+ * where a later read fails, because the kill of the group may then have ended a process that no
1375
+ * read before it had named. Where a read after a kill fails, it keeps why in `seen.unread`, since the
1376
+ * kill of the group may then have ended a process no read listed. A read after a kill that answers
1377
+ * but leaves out a leader signal 0 still reaches fails so too (`leaderUnlisted`). It names in `seen.named`, once,
1378
+ * each live process a read after a kill finds that no read before it listed (`namedNow`), and keeps
1379
+ * in `seen.asked` each it has tried to name.
1380
+ */
1381
+ function* emptied(group, seen, kill, bound, now = realHost.clock.now) {
1382
+ // What the last read after a kill found: the leader's wait status, and each member alive.
1383
+ let last;
1384
+ const refused = new Set();
1385
+ for (let sent = !seen.first; ; sent = true) {
1386
+ if (sent) {
1387
+ signal(group, 'SIGKILL', kill);
1388
+ seen.sent = true;
1389
+ }
1390
+ if (!occupied(group, kill)) return { stuck: [] };
1391
+ let states;
1392
+ try {
1393
+ states = rowsOf(yield ['-g', String(group), '-o', 'pid=,stat=,xstat=']);
1394
+ if (sent && !states.has(group) && answers(group, kill)) throw leaderUnlisted(group);
1395
+ } catch (error) {
1396
+ if (sent) seen.unread ??= error.message;
1397
+ else seen.beforeUnread ??= error.message;
1398
+ // A read the bound cut short leaves each member the last read found alive not ended.
1399
+ if (last !== undefined && (error.code === LATE || error.code === 'ETIMEDOUT')) return { leader: last.leader, stuck: last.living.map((pid) => ({ pid, reason: `still alive when the exit cleanup's read bound of ${bound} ms ran out` })) };
1400
+ if (error.code === LATE || unreadSince === undefined || now() - unreadSince >= UNREAPED_BOUND) throw error;
1401
+ continue;
1402
+ }
1403
+ const living = [...states].filter(([, state]) => live(state)).map(([pid]) => pid);
1404
+ if ([...states.keys()].some((pid) => !seen.listed.has(pid))) seen.live = true;
1405
+ // A wait status is the leader's own only once it has exited: a live process's reads 0.
1406
+ const leader = living.includes(group) ? undefined : states.get(group)?.split(/\s+/)[1];
1407
+ if (living.length === 0 && sent) return { leader, stuck: [] };
1408
+ if (!sent) continue;
1409
+ last = { leader, living };
1410
+ // A live process no read before the kill listed is named once, as the census names one, within
1411
+ // the cleanup's own bound, so one the kill cannot end is recorded by name and command line.
1412
+ const unlisted = living.filter((pid) => !seen.listed.has(pid) && !seen.asked.has(pid));
1413
+ for (const pid of unlisted) seen.asked.add(pid);
1414
+ if (unlisted.length > 0) for (const member of yield* namedNow(unlisted)) seen.named.set(member.pid, member);
1415
+ const stuck = unended(living, kill, false, bound, refused);
1416
+ if (stuck !== undefined) return { leader, stuck };
1417
+ }
1418
+ }
1419
+
1420
+ /**
1421
+ * Each of `stuck`, the processes L0 could not end, by pid and why, with its name and command line:
1422
+ * as `named` holds them where the census named it, and otherwise read as the census reads them,
1423
+ * while the process is still alive. It yields each read as `census` does.
1424
+ */
1425
+ function* described(stuck, named = []) {
1426
+ const known = new Map(named.map((member) => [member.pid, member]));
1427
+ const unknown = stuck.filter(({ pid }) => !known.has(pid)).map(({ pid }) => pid);
1428
+ const names = unknown.length === 0 ? new Map() : yield* namesOf(unknown, function* (args) { return yield args; });
1429
+ const commands = unknown.length === 0 ? new Map() : rowsOf(yield ['-ww', '-p', unknown.join(','), '-o', 'pid=,command=']);
1430
+ return stuck.map(({ pid, reason }) => ({ pid, name: known.get(pid)?.name ?? names.get(pid), cmd: known.get(pid)?.cmd ?? commands.get(pid), reason }));
1431
+ }
1432
+
1433
+ /**
1434
+ * The `L0` events for `group`'s kill: a `killed` event for each of `named`, the members the read
1435
+ * before the kill found alive, and the kill of the group whole beside them where that read found it
1436
+ * could have ended a process unnamed, `left`; or only the kill of the group whole, where the census
1437
+ * or that read failed as `unnamed`. Each of `unended`, the members L0 could not end, is handed back
1438
+ * as such, with why, and not as killed.
1439
+ */
1440
+ function killsOf(group, { named, unnamed, left, unended }, killed) {
1441
+ const notEnded = unended.map((member) => [killed.replace(/\.killed$/, '.unended'), member]);
1442
+ if (unnamed !== undefined) return [['group.killed', { group, census: unnamed }], ...notEnded];
1443
+ const stuck = new Set(unended.map(({ pid }) => pid));
1444
+ const ends = named.filter(({ pid }) => !stuck.has(pid)).map((member) => [killed, member]);
1445
+ return [...ends, ...(left === undefined ? [] : [['group.killed', { group, census: left }]]), ...notEnded];
1446
+ }
1447
+
1448
+ /**
1449
+ * The identity of the directory at `path`, by which a later start tells it from another made at the
1450
+ * same path since: its device and inode, as decimal strings, read by `stat` through any link.
1451
+ *
1452
+ * Where it can fail to tell them apart (`D16` rule 3): a directory made at a path after another
1453
+ * there was removed could take the same device and inode. Measured on this host's APFS volume
1454
+ * (`/System/Volumes/Data`, macOS 27.0, 26A428) on 2026-10-01: of 200 directories each removed and
1455
+ * made again at once at the same path, none took the inode it had (`316037766` became
1456
+ * `316037792` on the last), on the same device. That APFS gives inodes out from a counter that
1457
+ * only grows is the architect's judgment (ruling 7), not a measurement.
1458
+ */
1459
+ export function identityOf(path, host = realHost) {
1460
+ const { dev, ino } = host.stat(path, { bigint: true });
1461
+ return { device: String(dev), inode: String(ino) };
1462
+ }
1463
+
1464
+ /**
1465
+ * Why the directory at `directory` may not be the one recorded with `identity`, or nothing where it
1466
+ * is: the record carries no identity for it, its identity cannot be read at the path, as where it
1467
+ * no longer exists, or the path now names another directory.
1468
+ */
1469
+ function unconfirmed(directory, identity, host = realHost) {
1470
+ if (identity?.device === undefined || identity?.inode === undefined) return { reason: 'the record carries no device and inode for it, so the start cannot tell it is the directory recorded', gone: false };
1471
+ let now;
1472
+ try {
1473
+ now = identityOf(directory, host);
1474
+ } catch (error) {
1475
+ return { reason: `its device and inode cannot be read: ${error.message}`, gone: error.code === 'ENOENT' };
1476
+ }
1477
+ if (now.device === identity.device && now.inode === identity.inode) return undefined;
1478
+ return { reason: `it is not the directory recorded: it is device ${now.device}, inode ${now.inode}, where the record names device ${identity.device}, inode ${identity.inode}`, gone: true };
1479
+ }
1480
+
1481
+ /**
1482
+ * The census of working directories' tool, by absolute path, for the same reason as `PS`. It runs
1483
+ * under `PS_ENV` too, whose UTF-8 locale it needs to print `ü` as itself (`listing`).
1484
+ */
1485
+ export const LSOF = realHost.lsof;
1486
+
1487
+ /**
1488
+ * The real path of `directory`, which the census of working directories compares with, or why it
1489
+ * cannot be one. A path that cannot be resolved is refused, never taken as holding no process, and
1490
+ * so is one `illegible` refuses.
1491
+ */
1492
+ function placed(directory, host = realHost) {
1493
+ let real;
1494
+ try {
1495
+ real = host.realpath(directory);
1496
+ } catch (error) {
1497
+ return { why: `its directory ${directory} cannot be resolved: ${error.message}` };
1498
+ }
1499
+ return { real, why: illegible(real) };
1500
+ }
1501
+
1502
+ /**
1503
+ * Why the census cannot compare with `real`, or nothing where it can: it holds a character `lsof`
1504
+ * does not print as itself, or `\` or `^`, which begin what it prints in a character's place. Of
1505
+ * such a path, what `lsof` prints is not the path, and a path it prints could be another
1506
+ * directory's (`listing`). Only printable ASCII is known to print as itself. The root is refused
1507
+ * too, since every process works under it.
1508
+ */
1509
+ const illegible = (real) => (/^\/[\x20-\x5b\x5d\x5f-\x7e]+$/.test(real) ? undefined
1510
+ : `the directory ${JSON.stringify(real)} is not an absolute path below the root, of printable ASCII without \\ or ^, which alone the census of working directories can read back`);
1511
+
1512
+ /**
1513
+ * What `lsof` is given to list the working directory of each process of Rigger's own user, or of
1514
+ * `pids` among them: `-a` lists a process only where it is the user's, by `-u` and its real user
1515
+ * id, and the file is its working directory, and `-F pun` prints each as lines of a field each.
1516
+ *
1517
+ * Where `lsof`'s answer can differ from a process's true working directory (`D16` rule 3), measured
1518
+ * with `lsof` 4.91 on macOS 27.0 (26A428) on 2026-10-01:
1519
+ *
1520
+ * - It prints the path the kernel names the directory by now: one renamed after a process began
1521
+ * working in it printed its new name. One removed after printed the path it had, with nothing to
1522
+ * mark it removed. One a process entered through a symbolic link printed the link's target, so
1523
+ * the census compares with the real path (`placed`).
1524
+ * - It prints a character it holds unprintable in its place: a newline as `\n`, a tab as `\t`, a
1525
+ * backslash as `\\`, U+0001 as `^A`, which a path holding `^A` prints too, and U+007F and
1526
+ * U+200B as `\x` and the hexadecimal of each byte. It printed `ü` as itself under this locale.
1527
+ * So a path is compared only where it holds printable ASCII but `\` and `^` (`placed`), and then
1528
+ * a path printed under it is one lying under it.
1529
+ * - It exits 1, printing nothing on either stream, where no process matched, as `ps` does (`run`),
1530
+ * and it lists itself, working where it was started, which is `/` (`reader`).
1531
+ *
1532
+ * One call listing every process of the user took 164 to 186 ms over 20 calls, with Node 26.5.0,
1533
+ * at a load average of about 11.5 on 12 cores, with 658 processes of the user's.
1534
+ */
1535
+ const listing = (pids, host = realHost) => ['-w', '-n', '-P', '-a', '-d', 'cwd', '-u', String(host.uid()), ...(pids ? ['-p', pids.join(',')] : []), '-F', 'pun'];
1536
+
1537
+ /**
1538
+ * The pid of each process `lsof`'s `printed` lists working in `directory`, a real path: its
1539
+ * working directory is that directory or lies under it. A process of another user is left out
1540
+ * whatever `lsof` was asked, and so is this one. A line it cannot read fails the census.
1541
+ */
1542
+ function workingIn(printed, directory, host = realHost) {
1543
+ const pids = [];
1544
+ let listed;
1545
+ for (const line of printed.split('\n').filter(Boolean)) {
1546
+ const [, field, value] = /^([pufn])(.*)$/.exec(line) ?? [];
1547
+ if (field === undefined || ((field === 'p' || field === 'u') && !/^\d+$/.test(value)) || (field !== 'p' && listed === undefined)) {
1548
+ throw new Error(`the census of working directories held a line it cannot read: ${JSON.stringify(line)}`);
1549
+ }
1550
+ if (field === 'p') listed = { pid: Number(value) };
1551
+ if (field === 'u') listed.uid = Number(value);
1552
+ const there = value === directory || value.startsWith(`${directory}/`);
1553
+ if (field === 'n' && there && listed.uid === host.uid() && listed.pid !== host.pid()) pids.push(listed.pid);
1554
+ }
1555
+ return pids;
1556
+ }
1557
+
1558
+ /** Sends `SIGSTOP` through `kill` to the process `pid`: `sent`, or `ESRCH` where it has gone, or `EPERM` where Rigger may not signal it. */
1559
+ function halt(pid, kill) {
1560
+ try {
1561
+ kill(pid, 'SIGSTOP');
1562
+ return 'sent';
1563
+ } catch (error) {
1564
+ if (error.code !== 'ESRCH' && error.code !== 'EPERM') throw error;
1565
+ return error.code;
1566
+ }
1567
+ }
1568
+
1569
+ /** Sends `name` through `kill` to the process `pid`, and whether it reached it. */
1570
+ function sent(pid, name, kill) {
1571
+ try {
1572
+ kill(pid, name);
1573
+ return true;
1574
+ } catch (error) {
1575
+ if (error.code !== 'ESRCH' && error.code !== 'EPERM') throw error;
1576
+ return false;
1577
+ }
1578
+ }
1579
+
1580
+ /**
1581
+ * What `sweeping` `found`, once each process it killed has ended: each still alive `bound`
1582
+ * milliseconds after its kill is taken out of the kills and the unnamed, resumed, since the census
1583
+ * stopped it, and handed back in `unended` with why, as is each process Rigger may not signal,
1584
+ * which `found` holds as `refused`, with its name and command line where they can be read. Each
1585
+ * process `found` holds as `unnamed`, which the census killed before it could read its name, is read
1586
+ * by name and command line before the wait, within the wait's own bound, so one the kill does not
1587
+ * end is recorded by them (#579). It yields each read and each pause, as `census` does.
1588
+ * A read cut at its deadline in that wait records the last answer that showed a process alive;
1589
+ * without an answer, it records that the process table could not show it ended (`reaped`).
1590
+ *
1591
+ * The census lists only processes whose real uid is Rigger's, and macOS lets a process signal
1592
+ * those, so a process it may not signal is not one this host has shown it (`D16` rule 3): the
1593
+ * branch is proven through a stand-in for the signal call alone (#545's engineer judge, N2).
1594
+ */
1595
+ function* settled(found, kill, bound, now = realHost.clock.now) {
1596
+ // Each process killed unnamed is read by name and command line at once, while one the kill does
1597
+ // not end is still stopped, so its name is that of the process the census listed.
1598
+ let unnamed = (found.unnamed ?? []).map((pid) => ({ pid }));
1599
+ try {
1600
+ unnamed = yield* described(unnamed);
1601
+ } catch {
1602
+ // The process table cannot be read, so each is recorded by its pid alone.
1603
+ }
1604
+ const why = new Map(yield* reaped([...found.kills.map(({ pid }) => pid), ...(found.unnamed ?? [])], kill, bound, found.observed, now));
1605
+ const stuck = new Set(why.keys());
1606
+ for (const pid of stuck) sent(pid, 'SIGCONT', kill);
1607
+ let refused = (found.refused ?? []).map((pid) => ({ pid, reason: 'EPERM' }));
1608
+ try {
1609
+ refused = yield* described(refused);
1610
+ } catch {
1611
+ // The process table cannot be read, so each is recorded by its pid and why alone.
1612
+ }
1613
+ return {
1614
+ ...found,
1615
+ kills: found.kills.filter(({ pid }) => !stuck.has(pid)),
1616
+ unnamed: (found.unnamed ?? []).filter((pid) => !stuck.has(pid)),
1617
+ unended: [...[...found.kills, ...unnamed].filter(({ pid }) => stuck.has(pid)).map((each) => ({ ...each, reason: why.get(each.pid) })), ...refused],
1618
+ };
1619
+ }
1620
+
1621
+ /**
1622
+ * Each of `pids`, each one the census killed through `kill`, that L0 cannot show has ended, as a
1623
+ * pair of its pid and why, or none: it settles once none answers signal 0, or a read of their states
1624
+ * finds only zombies, yielding each pause. A killed process answers until its parent reaps it, and
1625
+ * the census kills a process whatever its parent, so a zombie whose parent never reaps it is taken
1626
+ * as ended. One a read finds alive `bound` milliseconds after it began is still alive at the bound.
1627
+ * Where the reads fail, it settles once `UNREAPED_BOUND` has passed, and each that still answers
1628
+ * signal 0 is one the table could not show has ended: the census stopped it, so `settled` resumes it
1629
+ * rather than leave it stopped (`R-STATE-18`), though a zombie answers signal 0 too (`D16` rule 3).
1630
+ * A read cut at its deadline, whether `run` or `runNow` reports `ETIMEDOUT` or the driver reports
1631
+ * `LATE`, uses the last answer where one showed a process alive, including a synchronous sweep's
1632
+ * answer immediately after the kill. Where none answered, the table could not show it ended.
1633
+ */
1634
+ function* reaped(pids, kill, bound, observed = new Map(), now = realHost.clock.now) {
1635
+ const since = now();
1636
+ let last;
1637
+ for (let wait = 1; ; wait = longer(wait)) {
1638
+ const left = pids.filter((pid) => observed.get(pid) !== 'ended' && answers(pid, kill));
1639
+ if (left.length === 0) return [];
1640
+ let living;
1641
+ try {
1642
+ living = [...rowsOf(yield ['-p', left.join(','), '-o', 'pid=,stat='])].filter(([, state]) => live(state)).map(([pid]) => pid);
1643
+ last = living;
1644
+ } catch (error) {
1645
+ // Past the reads' deadline no read can be made: what a post-kill read found alive is not
1646
+ // ended, and the rest the table could not show had ended.
1647
+ if (error.code === LATE || error.code === 'ETIMEDOUT') {
1648
+ const pending = last ?? left;
1649
+ return pending.map((pid) => [pid, last || observed.get(pid) === 'live'
1650
+ ? `still alive when L0's read bound ran out after its kill`
1651
+ : 'not shown to have ended: the process table could not be read']);
1652
+ }
1653
+ living = undefined;
1654
+ }
1655
+ if (living?.length === 0) return [];
1656
+ if (living !== undefined && now() - since >= bound) return living.map((pid) => [pid, `still alive ${bound} ms after L0's kill`]);
1657
+ if (living === undefined && now() - since >= UNREAPED_BOUND) return left.map((pid) => [pid, `not shown to have ended ${UNREAPED_BOUND} ms after L0's kill: the process table could not be read`]);
1658
+ yield wait;
1659
+ }
1660
+ }
1661
+
1662
+ /**
1663
+ * Kills every process of Rigger's own user working in `directory`, a real path `illegible` admits,
1664
+ * read through `lsof` at the path `lsof` names, signalling each through `kill`, and hands back the
1665
+ * `kills`, each by its pid, name and command line, read as the group's census reads them. Where the
1666
+ * census could not be read, it hands back why as `unread`, and as `unnamed` the pid of each process
1667
+ * it had found working there and stopped, which it then killed unnamed. It yields each read and each
1668
+ * pause, as `census` does, so the call and the exit cleanup both take it. Each process Rigger may not
1669
+ * signal is handed back as `refused`, by pid, for `settled` to record as one it could not end, and
1670
+ * when it first sent a process the kill as `killedAt`, where it sent one.
1671
+ *
1672
+ * Each round lists the directory's processes and stops them, because a stopped process can neither
1673
+ * exec, nor fork, nor leave the directory. It lists them again, stopped, and resumes any no longer
1674
+ * working there: a pid handed on to another process between the list and the stop. It reads the
1675
+ * rest's names and command lines, then their states again, keeping them only where each is still
1676
+ * stopped, and kills them. It ends only at a list holding no process but those Rigger may not
1677
+ * signal. It stops processes one pid at a time, never a group, so a process it stopped that then
1678
+ * leaves its group is still killed or resumed by its pid (ruling 14). A listed process that has
1679
+ * gone before the stop is listed again, so one it forked between the list and the stop is killed in
1680
+ * a later round. One it has sent the kill and lists again is still ending, or outlives the kill,
1681
+ * and is neither stopped nor killed again. A directory whose processes go on forking
1682
+ * successors faster than a round ends holds the census until its read timeout, and is then recorded
1683
+ * as unread.
1684
+ *
1685
+ * On the synchronous exit path, it also reads killed processes' states before another directory
1686
+ * listing can spend the remaining read bound. A failed optional state read leaves the sweep going.
1687
+ *
1688
+ * It resumes a process it stopped only where a later list no longer finds it working there, or where
1689
+ * the census gives up before it has listed that process again: a failed read leaves nothing it
1690
+ * stopped stopped. A process it has listed again, stopped, it kills, by name or, where a later read
1691
+ * fails, unnamed.
1692
+ *
1693
+ * Where the exit cleanup's census runs while the call's is reading, it kills what the call's had
1694
+ * stopped in the directory. A process the call's had stopped and not yet listed again, which can
1695
+ * only be a pid handed on to a process outside it between a list and the stop, stays stopped.
1696
+ */
1697
+ function* sweeping(directory, lsof, kill, observeAfterKill = false, host = realHost, tracked, unended) {
1698
+ const kills = [];
1699
+ const observed = new Map();
1700
+ // Stopped and not yet listed again; and listed again, stopped, and not yet killed.
1701
+ const held = new Set();
1702
+ const ours = new Set();
1703
+ // Sent the kill, and listed again only while it is still ending, or where it outlives the kill,
1704
+ // which `settled` waits on: it is not stopped or killed again.
1705
+ const killed = new Set();
1706
+ const forbidden = new Set();
1707
+ const locations = new Map();
1708
+ // When it first sent a process the kill.
1709
+ let killedAt;
1710
+ const list = function* (pids) {
1711
+ if (tracked !== undefined) return yield* trackedIn(tracked, pids, unended);
1712
+ const printed = yield { tool: lsof, args: listing(pids, host) };
1713
+ return (Array.isArray(directory) ? directory : [directory]).flatMap((place) => workingIn(printed, place, host).map((pid) => { locations.set(pid, place); return pid; }));
1714
+ };
1715
+ const resume = (pids) => {
1716
+ for (const pid of pids) {
1717
+ held.delete(pid);
1718
+ sent(pid, 'SIGCONT', kill);
1719
+ }
1720
+ };
1721
+ try {
1722
+ for (let wait = 0; ; wait = longer(wait)) {
1723
+ if (wait > 0) yield wait;
1724
+ const found = yield* list();
1725
+ resume([...held].filter((pid) => !found.includes(pid)));
1726
+ // A process the stop could not reach either has gone, and is listed again, since it may have
1727
+ // forked first, or is one Rigger may not signal, as a set-user-id program's is, and so not
1728
+ // this user's to end. So the census ends at a list holding only processes of the second kind.
1729
+ for (const pid of found) {
1730
+ if (ours.has(pid) || killed.has(pid) || forbidden.has(pid)) continue;
1731
+ const stop = halt(pid, kill);
1732
+ if (stop === 'sent') held.add(pid);
1733
+ if (stop === 'EPERM') forbidden.add(pid);
1734
+ }
1735
+ const pids = [...held, ...ours];
1736
+ if (pids.length === 0 && found.every((pid) => forbidden.has(pid) || killed.has(pid))) return { kills, refused: [...forbidden], killedAt, observed, locations };
1737
+ if (pids.length === 0) continue;
1738
+ const before = rowsOf(yield ['-p', pids.join(','), '-o', 'pid=,stat=']);
1739
+ for (const pid of ours) if (!before.get(pid)?.startsWith('T')) ours.delete(pid);
1740
+ if (!stopped(before)) continue;
1741
+ const there = yield* list(pids);
1742
+ resume([...held].filter((pid) => !there.includes(pid)));
1743
+ for (const pid of held) ours.add(pid);
1744
+ held.clear();
1745
+ const names = yield* namesOf([...before.keys()], function* (args) { return yield args; });
1746
+ const commands = rowsOf(yield ['-ww', '-p', pids.join(','), '-o', 'pid=,command=']);
1747
+ const after = rowsOf(yield ['-p', pids.join(','), '-o', 'pid=,stat=']);
1748
+ if (!stopped(after) || ![before, names, commands].every((each) => samePids(each, after))) continue;
1749
+ const killedNow = [];
1750
+ for (const [pid, state] of after) {
1751
+ if (!ours.has(pid) || !state.startsWith('T')) continue;
1752
+ ours.delete(pid);
1753
+ let accepted = false;
1754
+ try {
1755
+ if (!sent(pid, 'SIGKILL', kill)) continue;
1756
+ accepted = true;
1757
+ } finally {
1758
+ if (!accepted) { forbidden.add(pid); resume([pid]); }
1759
+ }
1760
+ killed.add(pid);
1761
+ killedNow.push(pid);
1762
+ killedAt ??= host.clock.now();
1763
+ kills.push({ pid, name: names.get(pid), cmd: commands.get(pid) });
1764
+ }
1765
+ if (observeAfterKill && killedNow.length > 0) {
1766
+ try {
1767
+ const state = rowsOf(yield ['-p', killedNow.join(','), '-o', 'pid=,stat=']);
1768
+ for (const pid of killedNow) observed.set(pid, state.has(pid) ? (live(state.get(pid)) ? 'live' : 'ended') : 'ended');
1769
+ } catch {
1770
+ // A failed optional look does not prevent the directory sweep from completing.
1771
+ }
1772
+ }
1773
+ }
1774
+ } catch (error) {
1775
+ const unnamed = [...ours].filter((pid) => sent(pid, 'SIGKILL', kill));
1776
+ if (unnamed.length > 0) killedAt ??= host.clock.now();
1777
+ return { kills, unread: error.message, unnamed, killedAt, observed, locations };
1778
+ } finally {
1779
+ resume([...held]);
1780
+ }
1781
+ }
1782
+
1783
+ /**
1784
+ * The `L0` events for the census of `directory`, a real path, read through the call's `ps`, `lsof`
1785
+ * and read timeout,
1786
+ * with `killed` naming each kill as a survivor's: each kill by name, and where the census could not
1787
+ * be read, a `directory.unread` event naming the directory and why, and each process it then
1788
+ * killed unnamed. Of a directory `illegible` refuses, that event says why, and nothing is killed.
1789
+ */
1790
+ async function swept(directory, { ps, lsof, readTimeout, kill = SIGNAL, host = realHost }, killed, tracked, unended) {
1791
+ const why = tracked === undefined ? illegible(directory) : undefined;
1792
+ if (why !== undefined) return sweptEvents(directory, { kills: [], unread: why, unnamed: [], unended: [] }, killed);
1793
+ const found = await reading(sweeping(directory, lsof, kill, false, host, tracked, unended), ps, readTimeout, undefined, undefined, host);
1794
+ return sweptEvents(directory, await reading(settled(found, kill, KILL_BOUND, host.clock.now), ps, readTimeout, host.clock.now() + KILL_BOUND + readTimeout, undefined, host), killed);
1795
+ }
1796
+
1797
+ /**
1798
+ * `swept`, synchronously, for the exit cleanup, which waits on no bound longer than its own, one
1799
+ * read timeout: the census lists and kills within it from its first read, and waits on what it
1800
+ * killed within it from its first kill, so it reads nothing past its own bound of that kill. Reads
1801
+ * before the kill that take the rest of the first bound so still leave the wait its reads of what
1802
+ * the kill left, and a process the kill does not end is read alive after it rather than recorded as
1803
+ * one the table could not be read for. Where it killed nothing, it waits within the first bound.
1804
+ */
1805
+ function sweptNow(directory, { ps, lsof, readTimeout, kill = SIGNAL, host = realHost }, killed, tracked, began = host.clock.now()) {
1806
+ const why = tracked === undefined && !Array.isArray(directory) ? illegible(directory) : undefined;
1807
+ if (why !== undefined) return sweptEvents(directory, { kills: [], unread: why, unnamed: [], unended: [] }, killed);
1808
+ const answered = !unanswered.has(ps);
1809
+ const found = readingNow(sweeping(directory, lsof, kill, true, host, tracked), ps, readTimeout, began + readTimeout, host.clock.now, host.spawnSync);
1810
+ // A read of `ps` this census gave up on at its own bound, before its kill, is made again in the
1811
+ // wait on what it killed, which has a bound of its own; a table that does not answer that either
1812
+ // is given up on again.
1813
+ if (answered && found.killedAt !== undefined) unanswered.delete(ps);
1814
+ return sweptEvents(directory, readingNow(settled(found, kill, readTimeout, host.clock.now), ps, readTimeout, (found.killedAt ?? began) + readTimeout, host.clock.now, host.spawnSync), killed);
1815
+ }
1816
+
1817
+ /** The events `swept` hands back, from what `sweeping` found in `directory`: each process it could not end among them, as such. */
1818
+ const sweptEvents = (directory, { kills, unread, unnamed, unended, locations }, killed) => [
1819
+ ...kills.map((kill) => [killed, { ...kill, directory: Array.isArray(directory) ? locations.get(kill.pid) : directory }]),
1820
+ ...(unread === undefined ? [] : (Array.isArray(directory) ? directory : [directory]).map((place) => ['directory.unread', { directory: place, census: unread, ...(unnamed.length > 0 ? { killed: unnamed } : {}) }])),
1821
+ ...unended.map((each) => [killed.replace(/\.killed$/, '.unended'), { ...each, directory: Array.isArray(directory) ? locations.get(each.pid) : directory }]),
1822
+ ];
1823
+
1824
+ /** The directories `call` sweeps: the dispatch's directory and its scratch directory, each where it holds one. */
1825
+ const sweptBy = (call) => [call.directory, call.scratch].filter((directory) => directory !== undefined);
1826
+
1827
+ /** The final whole-table read and the tracked set's sweep precede the group's kill. */
1828
+ async function descendants(call) {
1829
+ if (call.tracked === undefined) return [];
1830
+ stopTracking(call);
1831
+ await scan(call.host, [call]);
1832
+ call.trackerEnded = true;
1833
+ return [...(await swept(undefined, call, 'survivor.killed', call.tracked)),
1834
+ ...(call.trackerUnread === undefined ? [] : [['descendants.unread', { group: call.child.pid, census: call.trackerUnread }]])];
1835
+ }
1836
+
1837
+ /** Exit's final table read and tracked-set kill share one deadline, followed by the post-kill wait. */
1838
+ function descendantsNow(call) {
1839
+ if (call.tracked === undefined) return [];
1840
+ const began = call.host.clock.now();
1841
+ readingNow(tracking([call], call.host), call.ps, call.readTimeout, began + call.readTimeout, call.host.clock.now, call.host.spawnSync);
1842
+ call.trackerEnded = true;
1843
+ return [...sweptNow(undefined, call, 'survivor.killed', call.tracked, began),
1844
+ ...(call.trackerUnread === undefined ? [] : [['descendants.unread', { group: call.child.pid, census: call.trackerUnread }]])];
1845
+ }
1846
+
1847
+ /**
1848
+ * The `L0` events for the census of each directory `call` sweeps, once its group is empty, each
1849
+ * kill named as a survivor's; none where the call is not a dispatch's.
1850
+ */
1851
+ async function censused(call) {
1852
+ const events = [];
1853
+ for (const directory of sweptBy(call)) events.push(...(await swept(directory, call, 'survivor.killed')));
1854
+ return events;
1855
+ }
1856
+
1857
+ /**
1858
+ * `containNow` for the exit cleanup, followed by the census of each directory `call` sweeps, whose
1859
+ * kills are recorded after the group's.
1860
+ */
1861
+ function endedNow(group, call) {
1862
+ const tracked = descendantsNow(call);
1863
+ const look = containNow(group, call);
1864
+ look.kills.unshift(...tracked);
1865
+ // One selector covers both directories under one pair of read deadlines at exit.
1866
+ const directories = sweptBy(call).filter((directory) => {
1867
+ const why = illegible(directory);
1868
+ if (why === undefined) return true;
1869
+ look.kills.push(['directory.unread', { directory, census: why }]);
1870
+ return false;
1871
+ });
1872
+ if (directories.length > 0) look.kills.push(...sweptNow(directories, call, 'survivor.killed'));
1873
+ return look;
1874
+ }
1875
+
1876
+ /**
1877
+ * Appends each of `events` through `emitter`, trying every one whatever became of those before
1878
+ * it, and hands back each the sink refused, with its fields and why.
1879
+ */
1880
+ function record(emitter, events) {
1881
+ const unrecorded = [];
1882
+ for (const [event, fields] of events) {
1883
+ try {
1884
+ emitter.emit(event, fields);
1885
+ } catch (cause) {
1886
+ unrecorded.push({ event, ...fields, cause });
1887
+ }
1888
+ }
1889
+ return unrecorded;
1890
+ }
1891
+
1892
+ /**
1893
+ * The failure for a call whose `unrecorded` events the sink refused, carrying its `result`, its
1894
+ * message opening with `ending` where that says how the command ended.
1895
+ */
1896
+ function refused(unrecorded, result, ending = '') {
1897
+ const lines = unrecorded.map(({ event, cause, ...fields }) => `${event} ${JSON.stringify(fields)}: ${cause.message}`);
1898
+ const error = new Error(`${ending}the sink refused ${unrecorded.length} L0 event(s), so they went unrecorded:\n${lines.join('\n')}`);
1899
+ return Object.assign(error, { code: EVENT_REFUSED, unrecorded, result });
1900
+ }
1901
+
1902
+ /**
1903
+ * Runs `command` with `args` in `cwd` under exactly `env`, in a process group of its own, for at
1904
+ * most `timeout` milliseconds, and settles on its exit code, whether the timeout ended it, and the
1905
+ * bytes it wrote to standard output and standard error.
1906
+ *
1907
+ * `input`, where the caller gives it, is written to the command's standard input, which is then
1908
+ * closed. A command given none reads end of file at once.
1909
+ *
1910
+ * The order is fixed: the command exits, or at its timeout L0 kills its whole group, the command
1911
+ * with it, and confirms the group is empty; L0 kills what is left of its group and confirms it is
1912
+ * empty; L0 reads both pipes until they close, or until `outputBound` milliseconds have passed,
1913
+ * where a process outside the group holds one open; L0 records each kill, and any such hold; the
1914
+ * call settles. So the output is everything the group wrote until that kill, and neither a
1915
+ * survivor nor a process that left the group holds the call open.
1916
+ *
1917
+ * A command the timeout or any signal ended has a non-zero exit code, so it never reads as
1918
+ * returned. A command that never started has no result: the call rejects with a `NOT_STARTED`
1919
+ * failure naming what failed.
1920
+ *
1921
+ * A refused event never stops a kill, because every kill is done before any is recorded. Every
1922
+ * append is tried, and where the sink refused any, the call rejects with an `EVENT_REFUSED`
1923
+ * failure naming each unrecorded event and carrying the result.
1924
+ *
1925
+ * `directory`, where the caller gives one, is the directory of the dispatch the command is, and the
1926
+ * call is then a dispatch's (`ARCHITECTURE.md`, "Failure model"). Once L0 has emptied the group,
1927
+ * it kills every process of Rigger's own user working in that directory, by its real path, and
1928
+ * records each as a survivor (`swept`). A directory that cannot be resolved, or whose real path the
1929
+ * census cannot read back (`illegible`), starts nothing, as a command that never started. `scratch`,
1930
+ * where the caller gives one, is the dispatch's scratch directory, which the census sweeps after
1931
+ * the dispatch's directory, on the same terms (the architect's ruling 20 on #467). A call
1932
+ * given no directory has its group as its
1933
+ * whole containment.
1934
+ *
1935
+ * `host`, where the caller gives one, supplies L0's process starts, process-table reads,
1936
+ * directory listings, signals, paths, user identity and clock. A process L0 may not signal, or that
1937
+ * outlives its kill for `KILL_BOUND`, is recorded as one it could not end, with why, and the call
1938
+ * settles (`R-STATE-19`).
1939
+ *
1940
+ * `onGroup`, where the caller gives one, is handed the group's id in the step that creates the
1941
+ * group, before the call first yields (`ARCHITECTURE.md`, "Failure model"). L1 records a
1942
+ * dispatch's group there. A command that never started has no group, and `onGroup` is not called.
1943
+ * Where `onGroup` throws, L0 ends and records the group, and the call rejects with what it threw,
1944
+ * or, where the sink refused a kill event, with the `EVENT_REFUSED` failure, caused by it.
1945
+ *
1946
+ * L0 holds the call from the step that creates the group until a turn after the call settles. Where
1947
+ * the process exits meanwhile, L0's exit cleanup kills the group where the call has not emptied
1948
+ * it, records every kill, and then hands the group and how the command ended to `onExit`, where
1949
+ * the caller gives one: `{ exit }`, its exit code, or `{ unread }`, why it could not be read, and
1950
+ * `unswept`, why, where the cleanup left the call's directories unsearched (`killedBare`).
1951
+ * `onExit` is a synchronous step, which is how L1 removes a dispatch's entry and records its end.
1952
+ * The step can come after the call has settled, in the turn it settled, and must then do
1953
+ * nothing for a call its caller has finished. A process kept running past its ending still has the
1954
+ * call settle, on the command's result.
1955
+ *
1956
+ * `onTracked`, where the caller gives one, is handed the group's id and each process a read of the
1957
+ * tracker adds to a dispatch's tracked set, by pid and start time, in the read that adds it. L1
1958
+ * names them in the dispatch's entry there. Where it throws, each stays tracked in L0's memory
1959
+ * alone, and the dispatch's ending still ends it ("Failure model").
1960
+ */
1961
+ export async function runCommand({ command, args, cwd, env, input, timeout, emitter, onGroup, onExit, onTracked, onSigns, directory, scratch, track = false, host = realHost, readTimeout = READ_TIMEOUT, outputBound = OUTPUT_BOUND, trace }) {
1962
+ requireClock(host.clock);
1963
+ const { ps, lsof, signal: kill } = host;
1964
+ // The caller opens the emitter, so an `L0` event carries the card L0 never knows. There is no
1965
+ // default: a kill with nowhere to be recorded is refused before anything starts, and an emitter
1966
+ // is only one that has an `emit` to call.
1967
+ if (typeof emitter?.emit !== 'function') throw startFailure(Object.assign(new Error(`the process adapter was given no L0 emitter, so it did not start ${command}`), { code: NOT_STARTED }), 'event-emitter-missing');
1968
+ if (typeof timeout !== 'number' || !Number.isFinite(timeout) || timeout <= 0) {
1969
+ // The type is named because a string, a bigint or a boxed number prints as the number it holds.
1970
+ const type = timeout === null ? 'null' : typeof timeout;
1971
+ throw startFailure(Object.assign(new Error(`the process adapter was given the timeout ${shown(timeout)} (of type ${type}), which is not a positive finite number of milliseconds, so it did not start ${command}`), { code: NOT_STARTED }), 'dispatch-timeout');
1972
+ }
1973
+ const unfit = unusable(cwd, host);
1974
+ if (unfit !== undefined) throw startFailure(notStarted(command, unfit), 'directory-unusable');
1975
+ // A dispatch's directory the census could not read would leave every process working there
1976
+ // alive, so a command given one runs only where the census can read it.
1977
+ const { real, why } = directory === undefined ? {} : placed(directory, host);
1978
+ if (why !== undefined) throw startFailure(notStarted(command, why), real === undefined ? 'directory-unusable' : 'directory-illegible', real === undefined ? {} : { path: real });
1979
+ const { real: scratchReal, why: scratchWhy } = scratch === undefined ? {} : placed(scratch, host);
1980
+ if (scratchWhy !== undefined) throw startFailure(notStarted(command, scratchWhy), scratchReal === undefined ? 'directory-unusable' : 'scratch-illegible', scratchReal === undefined ? {} : { path: scratchReal });
1981
+ install();
1982
+ const stdin = input === undefined ? 'ignore' : 'pipe';
1983
+ const child = spawned(command, () => host.spawn(command, args, { cwd, env, detached: true, stdio: [stdin, 'pipe', 'pipe'] }), cwd, host);
1984
+ // Where the spawn failed after it returned, Node gives the child no pid and emits why after.
1985
+ if (child.pid === undefined) {
1986
+ const [error] = await once(child, 'error');
1987
+ throw spawnFailure(command, error, cwd, host);
1988
+ }
1989
+ if (input !== undefined) {
1990
+ // A command that exits without reading all of its input closes the pipe under the write,
1991
+ // which Node reports as an error on standard input. What the command read is its own
1992
+ // business, and its result is its exit code and output, so the error is let go.
1993
+ child.stdin.on('error', () => {});
1994
+ child.stdin.end(input);
1995
+ }
1996
+ const output = Promise.all([drained(child.stdout), drained(child.stderr)]);
1997
+ const call = { emitter, host, ps, lsof, readTimeout, kill, onExit, onTracked, onSigns, trace, directory: real, scratch: scratchReal, child, events: [], contained: false };
1998
+ if (track) call.tracked = new Map();
1999
+ calls.set(child.pid, call);
2000
+ // A call the exit cleanup took is one it has ended and recorded, so the call records nothing
2001
+ // more of it.
2002
+ const taken = () => !calls.has(child.pid);
2003
+ // The call is let go a turn after it settles, and not as it settles, because the caller's code
2004
+ // after its await runs in the turn it settles: an ending in that turn still reaches the caller's
2005
+ // step, which must then do nothing for a call it has finished.
2006
+ const release = () => setImmediate(() => calls.get(child.pid) === call && calls.delete(child.pid)).unref();
2007
+ try {
2008
+ if (onGroup) onGroup(child.pid, startOf(ps, child.pid, readTimeout, host));
2009
+ } catch (refusal) {
2010
+ // A group the caller could not take runs no further: it is ended, and recorded, as a
2011
+ // survivor would be, before the caller hears why.
2012
+ // Nothing reads the output of a command that runs no further, so its pipes are let go.
2013
+ const kills = [...(await descendants(call)), ...(await contain(child.pid, call, 'survivor.killed')), ...(await censused(call))];
2014
+ call.contained = true;
2015
+ handSigns(call, kills);
2016
+ const unrecorded = record(emitter, taken() ? [] : kills);
2017
+ release();
2018
+ child.stdout.destroy();
2019
+ child.stderr.destroy();
2020
+ if (unrecorded.length > 0) throw Object.assign(refused(unrecorded), { cause: refusal });
2021
+ throw refusal;
2022
+ }
2023
+ if (track) {
2024
+ call.tracking = true;
2025
+ if (active(host).length === 1) scan(host);
2026
+ }
2027
+ const { events } = call;
2028
+ const exited = once(child, 'exit');
2029
+ const expired = await outlasts(exited, timeout, host);
2030
+ // The kills at the timeout wait among the call's unrecorded kills, so an exit meanwhile records
2031
+ // them.
2032
+ if (expired) events.push(...(await descendants(call)), ...(await contain(child.pid, call, 'timeout.killed')));
2033
+ const [code, signal] = await exited;
2034
+ // The timeout ended the command only where the kill did. One that exited on its own between the
2035
+ // timer and the kill ended itself, with its own exit code.
2036
+ const timedOut = expired && signal !== null;
2037
+ // A command that exited on its own did so before the containment's kill reached it, so every
2038
+ // process that containment killed, or could not end, outlived the command.
2039
+ if (!timedOut) for (const ending of events) ending[0] = ending[0].replace(/^timeout\./, 'survivor.');
2040
+ const exit = signal === null ? code : signalled(signal);
2041
+ if (!expired) events.push(...(await descendants(call)));
2042
+ events.push(...(await contain(child.pid, call, 'survivor.killed')));
2043
+ events.push(...(await censused(call)));
2044
+ call.contained = true;
2045
+ if (await outlasts(output, outputBound, host)) {
2046
+ // Closing the pipes lets go of their handles, which would otherwise hold this process open.
2047
+ child.stdout.destroy();
2048
+ child.stderr.destroy();
2049
+ events.push(['output.held', { group: child.pid, bound: outputBound }]);
2050
+ }
2051
+ const [stdout, stderr] = await output;
2052
+ const result = { exit, timedOut, stdout, stderr };
2053
+ if (!taken()) handSigns(call, events);
2054
+ const unrecorded = record(emitter, taken() ? [] : events.splice(0));
2055
+ release();
2056
+ if (unrecorded.length > 0) throw refused(unrecorded, result, timedOut ? `the timeout of ${timeout} ms ended ${command}, and ` : '');
2057
+ return result;
2058
+ }
2059
+
2060
+ /**
2061
+ * Kills the process group `group` that L1 recorded with a leader that started at `started`, once
2062
+ * it has confirmed from each live process's start time that the group is the one recorded. It
2063
+ * leaves a group it finds is not, and does nothing where the group has no live process. A kill
2064
+ * runs as `runCommand`'s does, census first, and records each process it killed as
2065
+ * `recorded.killed` through `emitter`, and each it could not end as `recorded.unended`, signalling
2066
+ * through the host's signal call. Where the sink refused any of those, it rejects with an
2067
+ * `EVENT_REFUSED` failure, once the group is empty. Where the start times cannot be read, it
2068
+ * rejects having killed nothing.
2069
+ *
2070
+ * Where L1 recorded the dispatch's `directory`, a real path, the census of that directory follows,
2071
+ * whether or not the group was the one recorded: the directory was made for that dispatch alone,
2072
+ * and the dead engine's dispatch can have left a process working there whatever became of its
2073
+ * group. It follows only where the directory at that path is still the one L1 recorded, by the
2074
+ * `identity` it recorded (`unconfirmed`). Where it is not, or that cannot be told, it sweeps nothing
2075
+ * there and records a `directory.skipped` event naming the path and why, and the group's kill
2076
+ * stands as it is (the architect's ruling 7 on #467). Where L1 recorded the dispatch's `scratch`
2077
+ * directory, as its `path`, `device` and `inode`, its census follows on the same terms (ruling 20).
2078
+ *
2079
+ * Before the group's kill, it ends each of the dispatch's `tracked` processes, each by its `pid`
2080
+ * and `started`, whether or not the group is the one recorded, through the sweep's stop and
2081
+ * start-time confirmation, recording each it killed as `recorded.killed`. One whose start time no
2082
+ * longer matches, or cannot be read, it leaves alive and running, and records as
2083
+ * `recorded.unended` with why. One no read lists has already ended, and it records nothing of it
2084
+ * (`ARCHITECTURE.md`, "Failure model").
2085
+ */
2086
+ export async function killRecordedGroup({ group, started, tracked = [], emitter, directory, identity, scratch, settled = false, unended: signProcesses = [], unread = [], onSigns, host = realHost, readTimeout = READ_TIMEOUT }) {
2087
+ requireClock(host.clock);
2088
+ const { ps, lsof, signal: kill } = host;
2089
+ const groupRead = !settled || unread.some(({ kind }) => kind === 'group' || kind === 'dispatch');
2090
+ const starts = groupRead ? await startsIn(ps, group, readTimeout, host) : new Map();
2091
+ const standing = signProcesses.length === 0 ? { tracked: [] } : processSigns(signProcesses, { host, readTimeout });
2092
+ tracked = [...(!settled || unread.some(({ kind }) => kind === 'dispatch') ? tracked : []), ...standing.tracked];
2093
+ const pendingReads = [];
2094
+ const retainRead = (events, matches) => { if (events.some(([event]) => event.endsWith('.unended'))) pendingReads.push(...unread.filter(matches)); };
2095
+ const unended = new Map();
2096
+ const kills = await swept(undefined, { ps, lsof, readTimeout, kill, host }, 'recorded.killed', new Map(tracked.map(({ pid, started: start }) => [pid, start])), unended);
2097
+ const misses = [...unended].map(([pid, reason]) => ['recorded.unended', { pid, reason }]);
2098
+ // A start-time read that cannot match a tracked pid shows nothing gone; only a successful read of
2099
+ // the whole table can (`R-STATE-38`), so only a pid it cannot show gone keeps the dispatch's sign.
2100
+ const unshown = misses.length === 0 || !unread.some(({ kind }) => kind === 'dispatch') ? [] : processSigns(tracked.filter(({ pid }) => unended.has(pid)), { host, readTimeout }).unended;
2101
+ retainRead([...kills, ...misses.filter(([, { pid }]) => unshown.some((each) => each.pid === pid))], ({ kind }) => kind === 'dispatch');
2102
+ kills.push(...misses);
2103
+ if (groupRead && recorded(group, started, starts)) {
2104
+ const ended = await contain(group, { ps, readTimeout, kill, host }, 'recorded.killed');
2105
+ retainRead(ended, ({ kind }) => kind === 'group' || kind === 'dispatch');
2106
+ kills.push(...ended);
2107
+ }
2108
+ const recordedDirectories = [[directory, identity], ...(scratch === undefined ? [] : [[scratch.path, scratch]])];
2109
+ for (const [each, held] of recordedDirectories) {
2110
+ if (each === undefined || (settled && !unread.some((sign) => sign.kind === 'dispatch' || sign.directory === each))) continue;
2111
+ const replaced = unconfirmed(each, held, host);
2112
+ if (replaced !== undefined) {
2113
+ kills.push(['directory.skipped', { directory: each, reason: replaced.reason }]);
2114
+ if (!replaced.gone) pendingReads.push(...unread.filter((sign) => sign.kind === 'dispatch' || sign.directory === each).map((sign) => ({ ...sign, reason: replaced.reason })));
2115
+ }
2116
+ else {
2117
+ const ended = await swept(each, { ps, lsof, readTimeout, kill, host }, 'recorded.killed');
2118
+ retainRead(ended, (sign) => sign.kind === 'dispatch' || sign.directory === each);
2119
+ kills.push(...ended);
2120
+ }
2121
+ }
2122
+ handSigns({ child: { pid: group }, onSigns, unreadSigns: pendingReads, tracked: new Map([...starts, ...tracked.map(({ pid, started }) => [pid, started])]) }, kills);
2123
+ const unrecorded = record(emitter, kills);
2124
+ if (unrecorded.length > 0) throw refused(unrecorded);
2125
+ }
2126
+
2127
+ /**
2128
+ * Whether the live processes of `group`, by their `starts`, are the group recorded with a leader
2129
+ * that started at `started`. With its leader alive, the group is the one recorded where the
2130
+ * leader's start is the one recorded. A leader that is a zombie is dead, and `starts` holds none.
2131
+ *
2132
+ * With its leader dead, the leaderless rule decides (the owner's Q5 on #332): the group is the
2133
+ * one recorded where every live member started no earlier than the recorded leader. The rule
2134
+ * rests on two premises (the architect's ruling 1, B3, on #332):
2135
+ *
2136
+ * - a group id is not given out again while the group has a member;
2137
+ * - every member of a group Rigger created descends from the leader it recorded, so started no
2138
+ * earlier than it.
2139
+ *
2140
+ * It admits one wrong kill. The recorded group empties, its id is given to a later group of
2141
+ * processes Rigger did not start, that group's leader dies, and its members live on until the
2142
+ * start. Each of them started after the recorded leader, so the rule kills them.
2143
+ * `test/kill-recorded.test.mjs` shows it with a fabricated entry naming a group the test started
2144
+ * outside Rigger ("the wrong kill the leaderless rule admits"). That is an inference from the two
2145
+ * premises and the rule, not a measurement: no host run waits for an id to be given again.
2146
+ */
2147
+ function recorded(group, started, starts) {
2148
+ if (starts.has(group)) return starts.get(group) === started;
2149
+ return [...starts.values()].every((start) => start >= started);
2150
+ }
2151
+
2152
+ /**
2153
+ * The start time of process `pid`, read in the step that spawned it, before the caller yields,
2154
+ * and given up on after `timeout` milliseconds. L0 reads it only for a caller that takes the
2155
+ * group, to tell the group from a later one given the same id. It blocks the event loop while
2156
+ * `ps` runs: one read took 0.95 ms at the median and 1.55 ms at most, over 200 reads in the tick
2157
+ * that spawned the process, with Node 26.5.0 on macOS 27.0 on 2026-09-27.
2158
+ *
2159
+ * So a read that stalls blocks the event loop, and everything else in the process, for up to
2160
+ * `timeout`, which is `READ_TIMEOUT` unless the caller gives another. The engineer judge on #365
2161
+ * measured it (N2): with a `ps` that never answered and a timeout of 2,000 ms, a 20 ms timer fired
2162
+ * 1,985 ms late, and the call rejected with the group killed.
2163
+ *
2164
+ * The read is synchronous all the same, because L1 writes a dispatch's entry, its leader's start
2165
+ * time included, in the step that creates the group, before the call yields (the architect's
2166
+ * ruling 1, P2, on #332). A read that waited on the event loop would yield first.
2167
+ *
2168
+ * Where `ps`'s start time can differ from the process's true start (`D16` rule 3), measured with
2169
+ * `ps` from adv_cmds-240 on macOS 27.0 (26A428) on 2026-09-27:
2170
+ *
2171
+ * - `lstart` is whole seconds: 100 of 100 pairs of processes Node spawned one after the other
2172
+ * read the same `lstart`. So two processes started at one group id within one second are not
2173
+ * told apart, and the second is taken for the first. That needs the id given out twice within
2174
+ * one second. 2,001 processes Node spawned one after another, at 1,255 a second, were given
2175
+ * pids rising from 52,223 to 54,266. That the kernel hands pids out rising until they wrap is
2176
+ * an inference from that run, not a measurement; on it, an id is given again only once every
2177
+ * other free id has been.
2178
+ * - It is the time the process was forked, which comes before it runs its command.
2179
+ * - It prints in the local zone unless `ps` is given one, and with no zone in the text, so it is
2180
+ * given UTC (`PS_ENV`): one process read `Sun Sep 27 22:50:08 2026` under the host's zone and
2181
+ * `Mon Sep 28 03:50:08 2026` under UTC.
2182
+ * - A zombie, a process that has exited and not been reaped, still reads its start time, in a
2183
+ * read of its group and in a read of its pid alone. So does a leader that exited at once, read
2184
+ * in the tick that spawned it (the engineer's round 1 on #332).
2185
+ * - It is read from the wall clock at the fork. How a change to the host's clock after the fork
2186
+ * moves it is not measured here.
2187
+ */
2188
+ function startOf(ps, pid, timeout, host = realHost) {
2189
+ const read = host.spawnSync(ps, ['-p', String(pid), '-o', 'lstart='], { env: PS_ENV, timeout, killSignal: 'SIGKILL', encoding: 'utf8' });
2190
+ // A read that wrote to standard error has failed whatever its exit code, as `run` holds.
2191
+ const failure = read.error?.message ?? (read.stderr !== '' ? read.stderr.trim() : undefined) ?? (read.status !== 0 ? `${ps} ended with ${read.status ?? read.signal}` : undefined);
2192
+ if (failure !== undefined) throw new Error(`L0 could not read when the leader of group ${pid} started, so it ended the group: ${failure}`);
2193
+ return secondsOf(read.stdout.replace(/\n$/, ''));
2194
+ }
2195
+
2196
+ /**
2197
+ * The start time of each live process in `group`, by its pid, read as `startOf` reads one. A
2198
+ * zombie is left out: it has exited, though `ps` still lists it, with its start time, until its
2199
+ * parent reaps it. So a leader that has exited reads as dead whether or not it has been reaped.
2200
+ *
2201
+ * A read that lists no process is kept only where signal 0 no longer reaches the group, because a
2202
+ * read that failed can list nothing, even one that exits 1 and prints nothing (`run`), and the
2203
+ * leaderless rule would take that empty table as a group to kill (`recorded`). A read that leaves
2204
+ * out the leader is kept only where signal 0 no longer reaches the leader's pid, which is the
2205
+ * group's id: a leader that has exited and not been reaped is listed as a zombie, so a leader left
2206
+ * out while its pid still answers was left out by a read that failed, and the leaderless rule
2207
+ * would otherwise judge the group without the one start that can show it is not the one
2208
+ * recorded. While either holds, it reads again, since a process that is exiting answers signal 0
2209
+ * and may not be listed (`occupied`), and where `timeout` passes first it fails, so nothing in the
2210
+ * group is killed. That failure says what the last read that answered left out, even where the
2211
+ * read after it was still running when `timeout` passed, so a read that answered short is never
2212
+ * reported as one that only timed out. Where `timeout` passes before any read has answered, it
2213
+ * fails saying the reads did not finish. A leader that has left the group for another holds the read to `timeout` the
2214
+ * same way, which kills nothing.
2215
+ *
2216
+ * So one class of read is left, and nothing but the process table can close it (`D16` rule 3), the
2217
+ * same class as on the kill (`beforeKill`): a read that exits 0, lists at least one row, and
2218
+ * consistently leaves out a live member other than the leader. Such a read is taken as complete.
2219
+ * Where the leader is dead, the leaderless rule then judges the group without that member's start,
2220
+ * so the hidden member is killed even where it started before the recorded leader. Two instances:
2221
+ * a read that lists only the group's zombies, its dead leader among them, and one that lists only
2222
+ * a member started after the recorded leader while the leader has been reaped.
2223
+ *
2224
+ * A read that lists no row is outside that class. This read takes an empty table again while
2225
+ * signal 0 still reaches the group, and where it stays empty until `timeout` it fails, so nothing
2226
+ * in the group is killed.
2227
+ *
2228
+ * No read of the table can find a member it consistently hides, because the table is the only
2229
+ * thing that says which pids the group holds. The leader alone is known without it, since its pid
2230
+ * is the group's id, and that is why a missing leader can be checked. Signal 0 to the group says
2231
+ * only that some process is in it, live or a zombie, not which: it reaches a zombie, and a group
2232
+ * holding only zombies, as it reaches a live process (`beforeKill`). So a read hiding a live member
2233
+ * while listing zombies is exactly what the table gives for a group holding only zombies, and one
2234
+ * hiding it while listing a later member is exactly what it gives for that member alone. Refusing
2235
+ * every read that could be one of these would keep for ever the entry of every leaderless group a
2236
+ * dead engine left, whether it holds zombies alone or live members of its own.
2237
+ *
2238
+ * How `ps` reports a group with no process in it, against a read that failed (`D16` rule 3),
2239
+ * measured with `/bin/ps` from adv_cmds-240 on macOS 27.0 (26A428) on 2026-09-28, 20 times each,
2240
+ * with this read's arguments and `PS_ENV`: a group whose one process had exited and been reaped
2241
+ * exited 1 and wrote nothing to either stream; a group `x` exited 1 and wrote `ps: Invalid process
2242
+ * group: x` to standard error; a live group exited 0 and printed its row. So a read that failed
2243
+ * and wrote nothing, as the stand-in for `ps` in `test/kill-recorded.test.mjs` does, gives the
2244
+ * same answer as an empty group, and only signal 0 tells the two apart.
2245
+ */
2246
+ async function startsIn(ps, group, timeout, host = realHost) {
2247
+ const deadline = host.clock.now() + timeout;
2248
+ // What the last read that answered left out, while signal 0 still reached it.
2249
+ let short;
2250
+ const failure = () => new Error(`the reads of the group's start times ${short}, for ${timeout} ms`);
2251
+ for (let wait = 0; ; wait = longer(wait)) {
2252
+ if (wait > 0) await host.clock.pause(wait);
2253
+ const remaining = deadline - host.clock.now();
2254
+ if (remaining <= 0) throw short === undefined ? late(timeout) : failure();
2255
+ let rows;
2256
+ try {
2257
+ rows = rowsOf(await run(ps, ['-ww', '-g', String(group), '-o', 'pid=,stat=,lstart='], remaining, timeout, host));
2258
+ } catch (error) {
2259
+ // A read given up at the deadline, after reads that answered short, ends the reads for why they did.
2260
+ if (short === undefined || error.code !== 'ETIMEDOUT') throw error;
2261
+ throw new Error(`${failure().message}, and the read running at that point was given up: ${error.message}`);
2262
+ }
2263
+ if (rows.size === 0 && occupied(group, host.signal)) short = 'listed no process of the group while signal 0 still reached it';
2264
+ else if (!rows.has(group) && answers(group, host.signal)) short = `left out its leader, pid ${group}, while signal 0 still reached that pid`;
2265
+ else short = undefined;
2266
+ if (short !== undefined) continue;
2267
+ const live = [...rows].map(([pid, row]) => [pid, /^(\S+)\s+(.*)$/.exec(row)]).filter(([, row]) => !row?.[1].startsWith('Z'));
2268
+ return new Map(live.map(([pid, row]) => [pid, secondsOf(row?.[2] ?? '')]));
2269
+ }
2270
+ }
2271
+
2272
+ const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
2273
+ const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
2274
+
2275
+ /**
2276
+ * A start time as `ps` prints it under `PS_ENV`, such as `Mon Sep 28 03:50:08 2026`, in whole
2277
+ * seconds since the epoch. Only a start that the second it names prints back as, byte for byte,
2278
+ * is read, so a malformed one of any kind is refused: a wrong weekday, a day, hour, minute or
2279
+ * second past its range, which `Date.UTC` would carry into the next, or padding `ps` never
2280
+ * prints. Each could otherwise name a recorded start.
2281
+ *
2282
+ * How `ps` prints it, from the source of adv_cmds's `ps/print.c` (`lstarted`), on 2026-09-28:
2283
+ * the C library's `%c`, left-justified in its column with spaces. Under `PS_ENV`'s locale `%c` is
2284
+ * `%a %b %e %T %Y`, measured with `/bin/ps` from adv_cmds-240 and `/bin/date +%c` on macOS 27.0
2285
+ * (26A428) on 2026-09-28: `ps` printed `Mon Sep 28 23:47:11 2026` and four spaces, and `date`
2286
+ * printed `Tue Sep 1 00:00:00 2026` for a one-digit day, padded with a space. So the column's
2287
+ * trailing spaces are its padding, and are not the time's own.
2288
+ */
2289
+ function secondsOf(printed) {
2290
+ const text = printed.replace(/ +$/, '');
2291
+ const at = /^\S+ (\S+) +(\d+) (\d+):(\d+):(\d+) (\d+)$/.exec(text);
2292
+ const seconds = at ? Date.UTC(Number(at[6]), MONTHS.indexOf(at[1]), Number(at[2]), Number(at[3]), Number(at[4]), Number(at[5])) / 1000 : NaN;
2293
+ if (Number.isNaN(seconds) || lstartOf(seconds) !== text) throw new Error(`the process table held a start time L0 cannot read: ${JSON.stringify(printed)}`);
2294
+ return seconds;
2295
+ }
2296
+
2297
+ /** The second `seconds` as `ps` prints a start under `PS_ENV`, less its column's padding: `%a %b %e %T %Y` in UTC. */
2298
+ function lstartOf(seconds) {
2299
+ const time = new Date(seconds * 1000);
2300
+ const two = (field) => String(field).padStart(2, '0');
2301
+ const clock = [time.getUTCHours(), time.getUTCMinutes(), time.getUTCSeconds()].map(two).join(':');
2302
+ return `${WEEKDAYS[time.getUTCDay()]} ${MONTHS[time.getUTCMonth()]} ${String(time.getUTCDate()).padStart(2, ' ')} ${clock} ${time.getUTCFullYear()}`;
2303
+ }
2304
+
2305
+ /**
2306
+ * The child `spawning` makes to run `command`. Where the spawn throws, which Node does for some
2307
+ * of the causes of a command that never starts, a `NOT_STARTED` failure naming the command and why.
2308
+ */
2309
+ function spawned(command, spawning, cwd, host = realHost) {
2310
+ try {
2311
+ return spawning();
2312
+ } catch (error) {
2313
+ throw spawnFailure(command, error, cwd, host);
2314
+ }
2315
+ }
2316
+
2317
+ /** The host's spawn errors that name a cause, with whether the cause concerns the executable. */
2318
+ const SPAWN_CAUSES = {
2319
+ ERR_INVALID_ARG_VALUE: ['command-character'],
2320
+ ENOENT: ['command-missing', true],
2321
+ ENFILE: ['file-descriptors', false],
2322
+ EMFILE: ['file-descriptors', false],
2323
+ ENOMEM: ['process-resources', false],
2324
+ EAGAIN: ['process-resources', false],
2325
+ E2BIG: ['command-too-long', false],
2326
+ EACCES: ['command-not-executable', true],
2327
+ };
2328
+
2329
+ /** A failed spawn: recheck cwd for every errno, since OS and filesystem errors are not a closed list. */
2330
+ function spawnFailure(command, error, cwd, host = realHost) {
2331
+ const failure = notStarted(command, error.message);
2332
+ const classified = SPAWN_CAUSES[error.code] ?? ['host-error'];
2333
+ const [kind, executable] = classified;
2334
+ failure.startCause = unusable(cwd, host) !== undefined
2335
+ ? { kind: 'directory-unusable' } : { kind, ...(executable ? { command } : {}) };
2336
+ return failure;
2337
+ }
2338
+
2339
+ /**
2340
+ * Why `cwd` cannot be a command's working directory, or nothing where it can. The file system
2341
+ * decides, and is asked before the spawn because Node reports a missing `cwd` as
2342
+ * `spawn <command> ENOENT`, naming the command and not the directory.
2343
+ *
2344
+ * Where this answer can differ from what the spawn would have found, measured with Node 26.5.0
2345
+ * on macOS 27.0 (26A428) on 2026-09-27, spawning `/bin/pwd` detached with both outputs piped:
2346
+ *
2347
+ * - The check and the spawn read the directory at two moments, so one removed or replaced between
2348
+ * them passes the check and fails the spawn. That spawn then reports what Node reports, which
2349
+ * for a missing directory is `spawn /bin/pwd ENOENT`, naming the command alone. The call still
2350
+ * rejects as a failure to start.
2351
+ * - Every `cwd` the spawn reads as unset, the check refuses, while the spawn runs the command in
2352
+ * the caller's own working directory. This covers the whole class the spawn so reads, as far as
2353
+ * it was measured: `undefined` and `null` (`ERR_INVALID_ARG_TYPE` from the check), and `''` and
2354
+ * an empty `Buffer` (`ENOENT`). For each, `/bin/pwd` exited 0 and printed the caller's
2355
+ * directory. Of the other values tried, `false`, `0`, `NaN`, `[]` and `{}` made the spawn
2356
+ * throw `ERR_INVALID_ARG_TYPE` too, and `' '` failed it with `ENOENT`, so for those the two
2357
+ * agree.
2358
+ * - Elsewhere the two agreed: a missing directory and a dangling link (`ENOENT` from both), a file
2359
+ * (not a directory here, `ENOTDIR` from the spawn), a link loop (`ELOOP` from both), a
2360
+ * directory of mode 000 or 444 (`EACCES` from both), and one of mode 111, which both accept.
2361
+ */
2362
+ function unusable(cwd, host = realHost) {
2363
+ try {
2364
+ if (!host.stat(cwd).isDirectory()) return `its working directory ${cwd} is not a directory`;
2365
+ host.access(cwd);
2366
+ return undefined;
2367
+ } catch (error) {
2368
+ return `its working directory ${cwd} cannot be used: ${error.message}`;
2369
+ }
2370
+ }
2371
+
2372
+ /**
2373
+ * `value` as text for a refusal, never blank, which no value can make throw. It is the first of
2374
+ * these that prints something: its own conversion; Node's `inspect`; and `inspect` ignoring the
2375
+ * value's own hook for it, which prints what an object holds. A conversion can throw, as a
2376
+ * Symbol's does in a template literal and a null-prototype object's does anywhere, or print
2377
+ * nothing, as `[]` and `''` do, and a value's own hook can do either. Where every one fails, the
2378
+ * refusal says so; no value tried reached that.
2379
+ */
2380
+ function shown(value) {
2381
+ const ways = [() => String(value), () => inspect(value, { breakLength: Infinity }), () => inspect(value, { breakLength: Infinity, customInspect: false })];
2382
+ for (const way of ways) {
2383
+ try {
2384
+ const text = way();
2385
+ if (text.trim() !== '') return text;
2386
+ } catch {
2387
+ // The next way is tried.
2388
+ }
2389
+ }
2390
+ return 'that cannot be printed';
2391
+ }
2392
+
2393
+ /** The failure for a call whose `command` never started, saying `why`. */
2394
+ const notStarted = (command, why) => Object.assign(new Error(`the process adapter did not start ${command}: ${why}`), { code: NOT_STARTED });
2395
+
2396
+ /** Attaches the cause a start could not pass, in substrate terms, with only the identity it concerns. */
2397
+ export const startFailure = (failure, kind, identity = {}) => Object.assign(failure, { startCause: { kind, ...identity } });
2398
+
2399
+ /** Names the cause of a synchronous preparation operation at the site that raised it. */
2400
+ export function atStart(kind, operation, identity = {}) {
2401
+ try {
2402
+ return operation();
2403
+ } catch (failure) {
2404
+ throw startFailure(failure, kind, identity);
2405
+ }
2406
+ }
2407
+
2408
+ /**
2409
+ * Calls `done` once `delay` milliseconds have passed, and hands back what cancels that. A delay
2410
+ * past `TIMER_MAX` is kept over a chain of timers, each of at most `TIMER_MAX`, adding up to it.
2411
+ * `schedule` and `cancel` are Node's timers unless a test gives its own.
2412
+ *
2413
+ * By default no timer holds the process open: what a delay races must do that itself. A caller
2414
+ * waiting for a forge read passes `hold`, since no child process need remain open during its wait.
2415
+ */
2416
+ export function whenElapsed(delay, done, { schedule = realHost.clock.schedule, cancel = realHost.clock.cancel, hold = false } = {}) {
2417
+ let timer;
2418
+ const arm = (left) => {
2419
+ const step = Math.min(left, TIMER_MAX);
2420
+ timer = schedule(() => (left > step ? arm(left - step) : done()), step);
2421
+ if (!hold) timer.unref?.();
2422
+ };
2423
+ arm(delay);
2424
+ return () => cancel(timer);
2425
+ }
2426
+
2427
+ /** Whether `promise` is still unsettled once `bound` milliseconds have passed. */
2428
+ async function outlasts(promise, bound, host = realHost) {
2429
+ let stop;
2430
+ const schedule = host.clock.schedule;
2431
+ const cancel = host.clock.cancel;
2432
+ const passed = new Promise((resolve) => { stop = whenElapsed(bound, () => resolve(true), { schedule, cancel }); });
2433
+ const outlasted = await Promise.race([promise.then(() => false), passed]);
2434
+ stop();
2435
+ return outlasted;
2436
+ }
2437
+
2438
+ /** Hands containment's signs to L1 before a sink can refuse their events. */
2439
+ function handSigns(call, events) {
2440
+ if (call.onSigns === undefined) return;
2441
+ const unended = events.filter(([event]) => event.endsWith('.unended')).map(([, fields]) => ({ ...fields, ...(call.tracked?.has(fields.pid) ? { started: call.tracked.get(fields.pid) } : {}) }));
2442
+ const unread = [...(call.unreadSigns ?? []), ...events.flatMap(([event, fields]) => event === 'group.killed' ? [{ kind: 'group', group: fields.group, reason: fields.census }]
2443
+ : event === 'directory.unread' ? [fields.directory === undefined ? { kind: 'dispatch', reason: fields.census } : { kind: 'directory', directory: fields.directory, reason: fields.census }]
2444
+ : event === 'descendants.unread' ? [{ kind: 'dispatch', reason: fields.census }] : [])];
2445
+ if (unended.length > 0 || unread.length > 0) call.onSigns(call.child.pid, { unended, unread });
2446
+ }
2447
+
2448
+ /** A successful whole-table read alone shows an identity gone; signal answers never do. */
2449
+ export function processSigns(processes, { host = realHost, readTimeout = READ_TIMEOUT } = {}) {
2450
+ let rows;
2451
+ try {
2452
+ const args = ['-A', '-o', 'pid=,stat=,lstart='];
2453
+ const answer = host.spawnSync(host.ps, args, { env: PS_ENV, ...reader(readTimeout) });
2454
+ if (answer.error || answer.status !== 0 || answer.stderr !== '') throw new Error('the whole process table could not be read');
2455
+ rows = new Map([...rowsOf(answer.stdout)].map(([pid, row]) => {
2456
+ const fields = /^(\S+)\s+(.*)$/.exec(row);
2457
+ if (!fields) throw new Error('the process state could not be read');
2458
+ let started;
2459
+ try { started = secondsOf(fields[2]); } catch { /* An unreadable identity proves nothing. */ }
2460
+ return [pid, { state: fields[1], started }];
2461
+ }));
2462
+ } catch { return { unended: processes, tracked: [] }; }
2463
+ let unended = processes.filter(({ pid, started }) => {
2464
+ const row = rows.get(pid);
2465
+ return row !== undefined && !row.state.startsWith('Z') && (started === undefined || row.started === undefined || started === row.started);
2466
+ });
2467
+ if (unended.some(({ name, cmd }) => name === undefined || cmd === undefined)) {
2468
+ try {
2469
+ const named = readingNow(described(unended, unended.filter(({ name, cmd }) => name !== undefined && cmd !== undefined)), host.ps, readTimeout, undefined, host.clock.now, host.spawnSync);
2470
+ unended = unended.map((each, at) => ({ ...each, ...named[at] }));
2471
+ } catch { /* A failed name read cannot show an identity gone. */ }
2472
+ }
2473
+ return { unended, tracked: unended.filter(({ pid, started }) => started !== undefined && started === rows.get(pid).started) };
2474
+ }