@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,490 @@
1
+ // ABOUTME: L1 records each dispatch around L0's process adapter, sweeps its provider folder after
2
+ // L0 settles, and kills groups a dead engine left in its record.
3
+
4
+ import { existsSync, realpathSync } from 'node:fs';
5
+ import { isAbsolute, join, sep } from 'node:path';
6
+
7
+ import { addGroup, addTracked, holdsDispatch, recordPath, partialPath, readGroups, writeGroups } from './groups.mjs';
8
+ import { failedWriteSigns, readPartial, entrySigns, signFailure, settleGroup } from './groups.mjs';
9
+ import { listCliFolder, sweepCliFolder } from './workspace.mjs';
10
+ import { gitEnvironment } from '../substrate/git-environment.mjs';
11
+ import { EVENT_REFUSED, NOT_STARTED, identityOf, killRecordedGroup, runCommand } from '../substrate/process.mjs';
12
+ import { processSigns } from '../substrate/process.mjs';
13
+ import { startFailure } from '../substrate/process.mjs';
14
+
15
+ /**
16
+ * The `code` of the failure a dispatch rejects with when its command ran and the record refused
17
+ * its entry's removal, so its caller tells it from a command that never started and from a refused
18
+ * event without reading the message.
19
+ */
20
+ export const RECORD_REFUSED = 'RECORD_REFUSED';
21
+
22
+ /**
23
+ * Runs dispatch `id`'s `command` with `args` in `cwd` under exactly `env`, for at most `timeout`
24
+ * milliseconds, and settles on L0's result for it: the exit code `exit`, whether the timeout
25
+ * ended it, and the output as bytes, `stdout` and `stderr`. `input`, where the caller gives it, is
26
+ * written to the command's standard input. `card` is the dispatch's card, where
27
+ * it has one. `directory` is the state directory of the repository the dispatch serves, and `sink`
28
+ * is L5's, through which L1 records the dispatch and L0 what it kills, under this dispatch and its
29
+ * card. `clock` reads milliseconds for the dispatch's duration, and is the process's own unless a
30
+ * test gives one. `host` supplies L0's operating-system answers where a test gives one; `readTimeout` bounds its reads.
31
+ *
32
+ * `workspace`, where the caller gives one, is the card's workspace the dispatch runs in, and `cwd`
33
+ * is then its working directory there. `dispatch.start` names the workspace, the command's
34
+ * environment is `env` less every variable that redirects git (`gitEnvironment`), and a `cwd`
35
+ * whose real path lies outside the workspace starts nothing, as a command that never started
36
+ * (the architect's ruling 1, A7 and A8, on #423). Every `dispatch.start` carries the timeout.
37
+ *
38
+ * The workspace's real path is the dispatch's directory. L1 hands it to L0, whose census kills
39
+ * every process of Rigger's own user working there once the group is empty, and records it in the
40
+ * entry, so a later start does the same (`ARCHITECTURE.md`, "Failure model"). `scratch`, which
41
+ * `roleDispatch` hands for a role's dispatch and a step's lacks, is the dispatch's scratch
42
+ * directory, and L1 does the same with its real path, recording it in the entry with its device
43
+ * and inode as `scratch` (the architect's ruling 20 on #467). One that cannot be read starts
44
+ * nothing, as a command that never started. A workspace that is
45
+ * an entry's directory, or lies under one, or holds one, starts nothing, as a command that never
46
+ * started, naming the directory. The same L0 host supplies the directory-census tool where a test gives one.
47
+ *
48
+ * For a role's dispatch, `roleDispatch` also hands `facts`, the facts L2 attached to identify the
49
+ * work, and `digest`, a digest of the evidence L2 composed, and `dispatch.start` carries each it is
50
+ * given as given (`ARCHITECTURE.md`, "Telemetry").
51
+ * It may also hand `folder`, the adapter's `{ home, name }` for a CLI session folder under
52
+ * `<home>/projects/`. L1 lists it before L0 starts the command and removes only paths absent from
53
+ * that listing once L0 settles. `dispatch.end` names paths or a reason in `folderLeft` only where
54
+ * a sweep left something or could not safely run.
55
+ *
56
+ * The order is fixed (the architect's ruling 2, §4, on #332): L1 appends `dispatch.start`; shows
57
+ * the record writable; has L0 spawn the command, and writes the entry; L0 runs the command, kills
58
+ * what is left of its group, and settles; L1 retains any signs or removes the sign-free entry,
59
+ * appends `dispatch.timeout` where the timeout ended the command, then `dispatch.end`, and settles. Every start L1 records gets
60
+ * exactly one end, which carries the exit code and the duration where the command ran, and why it
61
+ * did not start where it never did.
62
+ *
63
+ * On Rigger's own exit before L1 has recorded the end, whether the command is still running or has
64
+ * exited while the call is in flight, the order is L0's exit cleanup's: L0 kills what is left of
65
+ * the group and records each kill; L1 retains any signs or removes the sign-free entry and
66
+ * appends `dispatch.end`, carrying the exit code L0 hands it, which is the command's own where it had exited. Where L0 could not read
67
+ * the command's status, the end carries no exit code, and says as `unread` why. Where the record
68
+ * refuses the removal, the end still goes, saying as `kept` which entry was kept and why, and so it
69
+ * does where L0 left the group's directories unsearched, whose entry L1 keeps for the next start
70
+ * (`R-STATE-28`). The sink's
71
+ * refusal of that end has no caller left to reach, so L0 writes it to standard error, on a line
72
+ * naming the event, the dispatch and its card. A process kept running past its ending has the call
73
+ * settle as before, and records nothing more of the dispatch.
74
+ *
75
+ * A refused start starts nothing, and the call rejects with an `EVENT_REFUSED` failure naming it.
76
+ * Before L0's synchronous spawn, L1 reads its record and failed-write memory. A standing sign
77
+ * rejects with `SIGN_STOPPED`, naming each sign, without starting the command or classing an
78
+ * environment failure. Each dispatch outcome carries the signs still standing when it settles.
79
+ * L0 hands its containment signs to L1 before emitting events, so a refused event loses none.
80
+ * An environment failure that keeps the command from starting rejects with `NOT_STARTED`, a
81
+ * state directory whose record cannot be written included. Where the sink refuses the timeout or the end, every append is
82
+ * still tried, and the call rejects with an `EVENT_REFUSED` failure naming the dispatch, its card
83
+ * and each unrecorded event, carrying the result where the command ran. L0's own refusal takes
84
+ * those events onto it; any other failure becomes the refusal's `cause`.
85
+ *
86
+ * While the command runs, the record in `directory` holds an entry naming its process group, the
87
+ * dispatch and the card (`ARCHITECTURE.md`, "Failure model"). Once whole containment settles,
88
+ * L1 retains each `unended` or `unread` sign in that entry, marked `settled`, until a read shows
89
+ * it gone. A sign-free entry goes. Exit cleanup past its budget keeps the entry unmarked for
90
+ * the next start's whole cleanup. Any other rejection leaves the entry it wrote, and so does
91
+ * an ending that runs no code, for a later start to settle. Where the record
92
+ * refuses the removal after a refused event, the refusal still reaches the caller, carrying the
93
+ * record's failure as `recordFailure`. Where it refuses the removal after the command settled, the
94
+ * call rejects with a `RECORD_REFUSED` failure carrying the result, and the record's failure as
95
+ * `recordFailure`.
96
+ */
97
+ export async function dispatch({ id, card, directory, sink, provider, command, args, input, cwd, workspace, scratch, env, folder, timeout, facts, digest, host, readTimeout, clock = () => performance.now() }) {
98
+ // L3 allocates the id (the architect's ruling 1, P4 on #332), and an entry without one could
99
+ // not be told from another dispatch's. Null and the empty string are no id either.
100
+ if (id === undefined || id === null || id === '') throw startFailure(Object.assign(new Error(`L1 was given no dispatch id, so it did not start ${command}`), { code: NOT_STARTED }), 'dispatch-identity');
101
+ // An id or card the record would refuse on its next read would refuse every later dispatch and
102
+ // start, so it is refused here, before anything is recorded or started.
103
+ if (!holdsDispatch(id, card)) throw startFailure(Object.assign(new Error(`L1's record of process groups cannot hold dispatch id ${JSON.stringify(id)} with card ${JSON.stringify(card)}, so it did not start ${command}`), { code: NOT_STARTED }), 'dispatch-identity');
104
+ const events = sink.emitter({ layer: 'L1', card, dispatch: id });
105
+ const began = clock();
106
+ const start = { command, timeout, ...(workspace === undefined ? {} : { workspace }), ...(facts === undefined ? {} : { facts }), ...(digest === undefined ? {} : { digest }) };
107
+ try {
108
+ events.emit('dispatch.start', start);
109
+ } catch (cause) {
110
+ throw refused(id, card, [{ event: 'dispatch.start', ...start, cause }]);
111
+ }
112
+ let recorded;
113
+ let attemptedEntry;
114
+ let folderListing;
115
+ let result;
116
+ let failure;
117
+ let containmentSigns;
118
+ // Whether L1 has recorded the dispatch's end, or is about to in the step it is taking.
119
+ let ended = false;
120
+ try {
121
+ // The record is shown writable before anything starts, by writing it back as it stands, so a
122
+ // dispatch whose group could not be recorded runs no command.
123
+ const entries = startingGroups(directory, { host, readTimeout });
124
+ try {
125
+ writeGroups(directory, entries);
126
+ } catch (cause) {
127
+ throw startFailure(Object.assign(new Error(`L1 cannot write its record of process groups in the state directory ${directory}, so dispatch ${id} did not start ${command}: ${cause.message}`, { cause }), { code: NOT_STARTED }), 'groups-unwritable');
128
+ }
129
+ // The dispatch's directory, its workspace's real path, as the record names it and L0's census
130
+ // of it compares.
131
+ const { escape, place, identity, startCause } = workspace === undefined ? {} : dispatchPlacement(cwd, workspace, directory);
132
+ if (escape !== undefined) throw Object.assign(new Error(`dispatch ${id} did not start ${command}: ${escape}`), { code: NOT_STARTED, startCause });
133
+ // A role's scratch directory, by its real path, device and inode, as the record names it and
134
+ // L0's census of it compares (the architect's ruling 20 on #467).
135
+ const { unread, held } = scratch === undefined ? {} : scratchHeld(scratch);
136
+ if (unread !== undefined) throw startFailure(Object.assign(new Error(`dispatch ${id} did not start ${command}: ${unread}`), { code: NOT_STARTED }), 'directory-unusable');
137
+ if (folder !== undefined) folderListing = listCliFolder(folder);
138
+ result = await runCommand({
139
+ command,
140
+ args,
141
+ input,
142
+ cwd,
143
+ // In a card's workspace, an inherited redirecting variable would send the command's git to
144
+ // another repository, which is #151's fault (the architect's ruling 1, A7, on #423).
145
+ env: workspace === undefined ? env : gitEnvironment(env),
146
+ timeout,
147
+ host,
148
+ readTimeout,
149
+ track: true,
150
+ directory: place,
151
+ scratch: held?.path,
152
+ emitter: sink.emitter({ layer: 'L0', card, dispatch: id }),
153
+ onGroup: (group, started) => {
154
+ // The window this leaves open. L0 spawns, then hands the group over in the same step, and
155
+ // this writes the entry before anything else runs. So between the spawn and the write
156
+ // there is one synchronous step, and no await. An engine killed by SIGKILL inside it leaves
157
+ // a group that no entry names, and no later start ends it. The dispatch's start event,
158
+ // which L1 appended before the spawn, still shows that dispatch, as a start with no end
159
+ // and no kill.
160
+ // The window is left open, not closed by holding the spawn until the write (the owner,
161
+ // round 4, and the architect's ruling 3, §6, on #332). Either of two findings reverses
162
+ // that: a production incident, in which an unpaired start's processes outlive a restart;
163
+ // or #335 (M2-S1) finding that an environment marker read through `ps` reaches a
164
+ // dispatch's processes, so a restart could find them without the record. #335 read the
165
+ // marker only from binaries that are not Apple's, and every survivor the Claude CLI left
166
+ // was one of Apple's (`docs/spikes/what-leaves-the-process-group.md`).
167
+ attemptedEntry = { group, started, dispatch: id, card, ...(place === undefined ? {} : { workspace: place, ...identity }), ...(held === undefined ? {} : { scratch: held }) };
168
+ addGroup(directory, attemptedEntry);
169
+ recorded = group;
170
+ },
171
+ // Each process L0's tracker adds is named in the entry, so a later start ends it after Rigger
172
+ // was killed outright or its exit ran past its budget. A rewrite that fails leaves it
173
+ // tracked in L0's memory alone ("Failure model").
174
+ onTracked: (group, added) => addTracked(directory, group, added, { host, readTimeout }),
175
+ onSigns: (group, signs) => {
176
+ containmentSigns = signs;
177
+ if (recorded === undefined && attemptedEntry !== undefined) {
178
+ try { writeGroups(directory, [...readGroups(directory), { ...attemptedEntry, ...signs, settled: true }], { host, readTimeout }); }
179
+ catch { /* The writer retains the omitted processes in its failed-write memory. */ }
180
+ }
181
+ },
182
+ // On Rigger's own exit, L0 kills and records the group, and then hands it here with how the
183
+ // command ended, its exit code or why its status could not be read, to retain its signs or remove its sign-free entry and
184
+ // record the dispatch's end, which says why the entry was kept where the record refused its
185
+ // removal. No caller is left to hear of a
186
+ // refused end, so L0 writes this refusal to standard error. L0 can hand over a dispatch
187
+ // whose end L1 has already recorded, which is left as it is.
188
+ onExit: (group, { unswept, ...ending }) => {
189
+ if (ended) return;
190
+ ended = true;
191
+ const fields = { ...ending, ms: Math.round(clock() - began) };
192
+ if (folder !== undefined) fields.folderLeft = [unsweptFolder(folder, folderListing, 'Rigger exited before the CLI folder sweep')];
193
+ try {
194
+ // A group L0 killed bare has directories nothing swept, so the next start's kill needs its entry.
195
+ if (unswept === undefined) settleGroup(directory, group, containmentSigns);
196
+ else fields.kept = keptEntry(directory, group, { message: unswept });
197
+ } catch (cause) {
198
+ fields.kept = keptEntry(directory, group, cause);
199
+ }
200
+ try {
201
+ events.emit('dispatch.end', fields);
202
+ } catch (cause) {
203
+ throw refused(id, card, [{ event: 'dispatch.end', ...fields, cause }]);
204
+ }
205
+ },
206
+ });
207
+ } catch (thrown) {
208
+ failure = thrown;
209
+ if (failure.startCause?.command !== undefined) {
210
+ const { command: named, ...cause } = failure.startCause;
211
+ failure.startCause = { ...cause, provider: provider ?? named };
212
+ }
213
+ result = thrown.result;
214
+ }
215
+ // The exit cleanup has ended the dispatch, and a process kept running past its ending records
216
+ // nothing more of it.
217
+ if (ended) {
218
+ if (failure !== undefined) throw failure;
219
+ return result;
220
+ }
221
+ ended = true;
222
+ // Whole containment keeps only the dispatch's remaining signs. A failure before containment
223
+ // settles keeps the running entry for the next start. A refused rewrite accompanies the
224
+ // original event refusal, or carries the result where the command ran.
225
+ if (recorded !== undefined && (failure === undefined || failure.code === EVENT_REFUSED)) {
226
+ try {
227
+ settleGroup(directory, recorded, containmentSigns);
228
+ } catch (recordFailure) {
229
+ const kept = keptEntry(directory, recorded, recordFailure);
230
+ if (failure === undefined) {
231
+ failure = Object.assign(new Error(`${named(id, card)} ran ${command}, which exited ${result.exit}, and ${kept}`), { code: RECORD_REFUSED, result, recordFailure });
232
+ } else {
233
+ failure.message += `\nand ${kept}`;
234
+ failure.recordFailure = recordFailure;
235
+ }
236
+ }
237
+ }
238
+ // Every append is tried whatever became of those before it, so a refused timeout event still
239
+ // leaves the dispatch its end.
240
+ const unrecorded = [];
241
+ const record = (event, fields) => {
242
+ try {
243
+ events.emit(event, fields);
244
+ } catch (cause) {
245
+ unrecorded.push({ event, ...fields, cause });
246
+ }
247
+ };
248
+ if (result?.timedOut) record('dispatch.timeout', { timeout });
249
+ // One end for every start L1 recorded, carrying the exit code where the command ran, or why it
250
+ // did not start (the architect's ruling 2, §4, on #332).
251
+ const ms = Math.round(clock() - began);
252
+ const folderLeft = folder === undefined ? [] : folderListing === undefined
253
+ ? [unsweptFolder(folder, folderListing, `L1 did not list or sweep its CLI folder: ${failure.message}`)]
254
+ : result === undefined
255
+ ? [unsweptFolder(folder, folderListing, `the command did not start or settle, so its CLI folder was not swept: ${failure.message}`)]
256
+ : sweepCliFolder(folderListing);
257
+ const folderFields = folderLeft.length === 0 ? {} : { folderLeft };
258
+ record('dispatch.end', result === undefined ? { reason: failure.message, ms, ...folderFields } : { exit: result.exit, ms, ...folderFields });
259
+ if (unrecorded.length > 0) failure = alongside(failure, refused(id, card, unrecorded, result));
260
+ const signs = failure?.signs ?? signsStanding(directory, { host, readTimeout });
261
+ if (signs.length > 0) {
262
+ if (failure !== undefined) failure.signs = signs;
263
+ else result = { ...result, signs };
264
+ }
265
+ if (failure !== undefined) throw failure;
266
+ return result;
267
+ }
268
+
269
+ /** The safe folder path, where one can be named, and why L1 left it without a sweep. */
270
+ function unsweptFolder(folder, listing, reason) {
271
+ const { home, name } = folder;
272
+ const path = listing?.path ?? (typeof home === 'string' && isAbsolute(home) && typeof name === 'string' && name !== '' && name !== '.' && name !== '..' && !name.includes(sep)
273
+ ? join(home, 'projects', name) : undefined);
274
+ return { ...(path === undefined ? {} : { path }), reason };
275
+ }
276
+
277
+ /**
278
+ * Why `cwd` is no directory in `workspace`, or nothing where it is one: its real path is the
279
+ * workspace's, or lies under it. Paths are compared by real path, so a symbolic link out of the
280
+ * workspace is caught, and so is macOS's `/tmp` read as `/private/tmp`.
281
+ *
282
+ * The check and the spawn read the directory at two moments, so a link made between them is not
283
+ * caught, as `unusable` in L0's process adapter says of its own check.
284
+ */
285
+ function escapes(cwd, workspace) {
286
+ let real;
287
+ let root;
288
+ try {
289
+ real = realpathSync(cwd);
290
+ root = realpathSync(workspace);
291
+ } catch (cause) {
292
+ return { escape: `its working directory ${cwd} in the workspace ${workspace} cannot be read: ${cause.message}`, startCause: { kind: 'directory-unusable' } };
293
+ }
294
+ if (within(real, root)) return undefined;
295
+ return { escape: `its working directory ${cwd} is ${real}, which lies outside the workspace ${workspace}`, startCause: { kind: 'working-directory-outside' } };
296
+ }
297
+
298
+ /**
299
+ * The real path of `workspace` as `place`, the directory of a dispatch working in `cwd` there, with
300
+ * its device and inode as `identity`, which a later start checks before it sweeps it; or
301
+ * as `escape` why it cannot be one now: `cwd` is no directory in it (`escapes`), the workspace
302
+ * cannot be resolved, or an entry in the record in `directory` names a directory that is it, or
303
+ * that it lies under, or that lies under it. L0's census of either would end the other's processes
304
+ * (`ARCHITECTURE.md`, "Failure model"). Paths are compared by real path, as `escapes` compares them.
305
+ */
306
+ function dispatchPlacement(cwd, workspace, directory) {
307
+ const escape = escapes(cwd, workspace);
308
+ if (escape !== undefined) return escape;
309
+ let place;
310
+ let identity;
311
+ try {
312
+ place = realpathSync.native(workspace);
313
+ identity = identityOf(place);
314
+ } catch (cause) {
315
+ return { escape: `its workspace ${workspace} cannot be read: ${cause.message}`, startCause: { kind: 'directory-unusable' } };
316
+ }
317
+ const entries = startingGroups(directory);
318
+ const holder = entries.find((entry) => entry.workspace !== undefined && (within(place, entry.workspace) || within(entry.workspace, place)));
319
+ if (holder === undefined) return { place, identity };
320
+ return { escape: `its directory ${place} is held by ${named(holder.dispatch, holder.card)}, whose entry in the record names ${holder.workspace}`, startCause: { kind: 'directory-occupied' } };
321
+ }
322
+
323
+ /** Reads the groups before a dispatch starts, including a reread after the writability check. */
324
+ function startingGroups(directory, options = {}) {
325
+ try {
326
+ const entries = readGroups(directory);
327
+ const signs = [...entrySigns(entries), ...failedWriteSigns(directory, options)];
328
+ if (signs.length > 0) throw signFailure(signs);
329
+ return entries;
330
+ } catch (cause) {
331
+ if (cause.signs !== undefined) throw cause;
332
+ throw signFailure([{ kind: 'record', path: recordPath(directory), reason: cause.message }]);
333
+ }
334
+ }
335
+
336
+ /**
337
+ * The scratch directory `scratch` as `held`, its real path as `path` with its device and inode,
338
+ * which a later start checks before it sweeps it, or as `unread` why it cannot be read.
339
+ */
340
+ function scratchHeld(scratch) {
341
+ try {
342
+ const path = realpathSync.native(scratch);
343
+ return { held: { path, ...identityOf(path) } };
344
+ } catch (cause) {
345
+ return { unread: `its scratch directory ${scratch} cannot be read: ${cause.message}` };
346
+ }
347
+ }
348
+
349
+ /** Whether the path `inner` is `outer` or lies under it, each a real path. */
350
+ export const within = (inner, outer) => inner === outer || inner.startsWith(`${outer}${sep}`);
351
+
352
+ /**
353
+ * `refusal`, L1's failure for its unrecorded events, carried alongside the `failure` the dispatch
354
+ * already had, where it had one. L0's own refusal takes L1's unrecorded events onto it, so the
355
+ * caller reads every unrecorded event in one place. Any other failure becomes the refusal's cause,
356
+ * and its message leads the refusal's.
357
+ */
358
+ function alongside(failure, refusal) {
359
+ if (failure === undefined) return refusal;
360
+ if (failure.code === EVENT_REFUSED) {
361
+ failure.message += `\n${refusal.message}`;
362
+ failure.unrecorded.push(...refusal.unrecorded);
363
+ return failure;
364
+ }
365
+ refusal.message = `${failure.message}\nand ${refusal.message}`;
366
+ refusal.cause = failure;
367
+ return refusal;
368
+ }
369
+
370
+ /** What L1 says of the record in `directory` keeping `group`'s entry, its removal refused by `failure`. */
371
+ const keptEntry = (directory, group, failure) => `the record of process groups in ${directory} kept the entry for group ${group}: ${failure.message}`;
372
+
373
+ /** Dispatch `id` as a failure names it, with its card where it has one. */
374
+ const named = (id, card) => `dispatch ${id}${card === undefined ? '' : `, card #${card}`}`;
375
+
376
+ /**
377
+ * The failure for dispatch `id`, of `card` where it has one, whose `unrecorded` L1 events the sink
378
+ * refused, each on a line of its own naming the dispatch and card, its fields and why, carrying the
379
+ * dispatch's `result` where its command ran. Its `code` tells the caller it from a command that
380
+ * never started without reading the message.
381
+ */
382
+ function refused(id, card, unrecorded, result) {
383
+ const under = named(id, card);
384
+ const lines = unrecorded.map(({ event, cause, ...fields }) => `${event} of ${under} ${JSON.stringify(fields)}: ${cause.message}`);
385
+ return Object.assign(new Error(`the sink refused ${unrecorded.length} L1 event(s) of ${under}, so they went unrecorded:\n${lines.join('\n')}`), { code: EVENT_REFUSED, unrecorded, result });
386
+ }
387
+
388
+ /**
389
+ * Ends what a dead engine left: each process group the record in `directory` names, where L0
390
+ * confirms the group is the one recorded, recording each kill through `sink` under the entry's
391
+ * dispatch and card (`ARCHITECTURE.md`, "Failure model"), and where the entry names the dispatch's
392
+ * directory, every process working there. `host` supplies L0's operating-system answers and `readTimeout` bounds its reads
393
+ * where the caller gives them.
394
+ *
395
+ * L1 reads the record and any unfinished write before acting on either. An unreadable file
396
+ * fails whole, naming its path, before anything is killed or rewritten. A readable unfinished
397
+ * write contributes each extra process or group to the entries the start reaps.
398
+ * Every entry is tried whatever became of those before it. An entry marked `settled` owes only
399
+ * its signs; every other entry owes its whole cleanup. Afterwards the record keeps entries
400
+ * whose group L0 could not confirm, because a later start may, and every sign not shown gone.
401
+ * The call rejects naming each unconfirmed entry, each sign and each kill the sink refused,
402
+ * with its dispatch id and card. A refused kill event alone keeps no entry whose cleanup
403
+ * settled without a sign. Where the record refuses its rewrite, that failure accompanies any
404
+ * existing rejection as `recordFailure`, preserving the unconfirmed groups and refused kills.
405
+ *
406
+ * The successful rewrite replaces the unfinished write, retaining every sign its reap left.
407
+ * A standing sign refuses all work at this start. ARCHITECTURE.md, "Signs of an earlier
408
+ * dispatch's process", gives the start's ordering and removal conditions.
409
+ */
410
+ export async function killRecordedGroups({ directory, sink, host, readTimeout }) {
411
+ let entries;
412
+ let partial;
413
+ let path = recordPath(directory);
414
+ try {
415
+ entries = readGroups(directory);
416
+ path = partialPath(directory);
417
+ if (existsSync(path)) partial = readPartial(directory);
418
+ } catch (cause) { throw signFailure([{ kind: 'record', path, reason: cause.message }]); }
419
+ if (partial !== undefined) {
420
+ for (const added of partial) {
421
+ const at = entries.findIndex((entry) => entry.group === added.group);
422
+ if (at < 0) entries.push(added);
423
+ else {
424
+ const entry = entries[at];
425
+ entries[at] = { ...entry, ...added };
426
+ for (const field of ['tracked', 'unended', 'unread']) if (entry[field] !== undefined || added[field] !== undefined) entries[at][field] = [...new Map([...(entry[field] ?? []), ...(added[field] ?? [])].map((each) => [JSON.stringify(each), each])).values()];
427
+ }
428
+ }
429
+ }
430
+ try { await killEntries({ directory, sink, host, readTimeout, entries, partial }); }
431
+ catch (failure) {
432
+ if (partial !== undefined && failure.signs !== undefined) {
433
+ failure.signs.push({ kind: 'write', path: recordPath(directory), reason: 'an unfinished write named processes not shown gone' });
434
+ failure.message = signFailure(failure.signs).message;
435
+ }
436
+ throw failure;
437
+ }
438
+ }
439
+
440
+ /** Acts on each of the record's `entries`, as `killRecordedGroups` says. */
441
+ async function killEntries({ directory, sink, host, readTimeout, entries, partial }) {
442
+ if (entries.length === 0 && partial === undefined) return;
443
+ const kept = [];
444
+ const unconfirmed = [];
445
+ const unrecorded = [];
446
+ for (const entry of entries) {
447
+ const { group, started, dispatch, card, workspace, device, inode, scratch, tracked } = entry;
448
+ const under = named(dispatch, card);
449
+ let observed = {};
450
+ try {
451
+ await killRecordedGroup({ group, started, tracked, settled: entry.settled, unended: entry.unended, unread: entry.unread, onSigns: (_group, signs) => { observed = signs; }, directory: workspace, identity: { device, inode }, scratch, host, readTimeout, emitter: sink.emitter({ layer: 'L0', card, dispatch }) });
452
+ } catch (failure) {
453
+ if (failure.code !== EVENT_REFUSED) {
454
+ kept.push(entry);
455
+ unconfirmed.push(`the entry for group ${group}, ${under}: ${failure.message}`);
456
+ continue;
457
+ }
458
+ for (const { event, cause, ...fields } of failure.unrecorded) unrecorded.push(`${under}: ${event} ${JSON.stringify(fields)}: ${cause.message}`);
459
+ }
460
+ const candidates = [...(entry.unended ?? []), ...(observed.unended ?? [])];
461
+ const unended = candidates.length === 0 ? [] : processSigns([...new Map(candidates.map((each) => [each.pid, each])).values()], { host, readTimeout }).unended;
462
+ const unread = observed.unread ?? [];
463
+ if (unended.length + unread.length > 0) kept.push({ ...entry, settled: true, unended, unread });
464
+ }
465
+ const failures = [];
466
+ if (unconfirmed.length > 0) failures.push(`L1 could not confirm ${unconfirmed.length} recorded group(s) as the one recorded, so it killed nothing in them and kept their entries:`, ...unconfirmed);
467
+ if (unrecorded.length > 0) failures.push(`the sink refused ${unrecorded.length} kill(s) of recorded groups, so they went unrecorded:`, ...unrecorded);
468
+ // A rewrite the record refuses rides on the failure rather than replacing it, so the caller
469
+ // still learns which kills went unrecorded and which groups went unconfirmed.
470
+ let recordFailure;
471
+ try {
472
+ writeGroups(directory, kept);
473
+ } catch (cause) {
474
+ if (failures.length === 0) throw cause;
475
+ recordFailure = cause;
476
+ failures.push(`and the record of process groups in ${directory} was not rewritten, so it still holds every entry it held: ${cause.message}`);
477
+ }
478
+ const signs = entrySigns(kept);
479
+ if (signs.length > 0) failures.push(signFailure(signs).message);
480
+ if (failures.length > 0) throw Object.assign(new Error(failures.join('\n')), { recordFailure, ...(signs.length > 0 ? { signs } : {}) });
481
+ }
482
+
483
+ /** L1's synchronous read at a claim or after a dispatch, including an unreadable record itself. */
484
+ export function signsStanding(directory, options = {}) {
485
+ try {
486
+ return [...entrySigns(readGroups(directory).map((entry) => ({ ...entry, unended: entry.unended?.length > 0 ? processSigns(entry.unended, options).unended : [] }))), ...failedWriteSigns(directory, options)];
487
+ } catch (cause) {
488
+ return [{ kind: 'record', path: recordPath(directory), reason: cause.message }];
489
+ }
490
+ }
@@ -0,0 +1,26 @@
1
+ // ABOUTME: L1's step runner: what L1's dispatching function is handed to run one provisioning step
2
+ // under `/bin/sh` in a card's workspace, or in the step's `cwd` under it, for the step's time.
3
+
4
+ import { join } from 'node:path';
5
+
6
+ import { stepTimeout } from '../config/validate.mjs';
7
+
8
+ /**
9
+ * What L1's `dispatch` is handed to run `step`, a provisioning step as the config declares it, in
10
+ * the card's `workspace`, under `env`, the engine's own environment unless the caller gives one.
11
+ * The caller adds the dispatch's id, card, state directory and sink.
12
+ *
13
+ * The step's `run` line runs as `/bin/sh -c`, never under the user's `$SHELL`, so a step behaves
14
+ * the same whatever the login shell (the architect's ruling 1, A7, on #423). Its working directory
15
+ * is `cwd` joined under the workspace, or the workspace itself, and is joined here so that
16
+ * `dispatch` derives nothing (A9). The workspace is handed on as well, which is what `dispatch`
17
+ * records the step as running in, and holds its working directory to.
18
+ */
19
+ export const stepDispatch = (step, workspace, env = process.env) => ({
20
+ command: '/bin/sh',
21
+ args: ['-c', step.run],
22
+ cwd: join(workspace, step.cwd ?? '.'),
23
+ workspace,
24
+ env,
25
+ timeout: stepTimeout(step),
26
+ });