@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,1738 @@
1
+ // ABOUTME: L3's loop: the pull trigger that reads the board, claims up to N cards in pull order
2
+ // before any await, has L2 carry each claimed answer, and drives its attempts: L1 makes the workspace,
3
+ // L3 dispatches each step L2 names one at a time, then the maker through L1, or attempts the card again as L2
4
+ // says, and then the judges or escalation role L2 names, under the one claim and slot; the run that fires that trigger
5
+ // again each time a slot frees, setting aside stopped cards and withheld judges for that run; the merge claims
6
+ // it hands the repo lane; the drain trigger; and L3's events.
7
+
8
+ import { randomUUID } from 'node:crypto';
9
+
10
+ import { roleDispatch } from '../execution/role.mjs';
11
+ import { keepOutput } from '../execution/kept-output.mjs';
12
+ import { LINE_DELETED, LINE_MOVED, SCRATCH_REFUSED } from '../execution/workspace.mjs';
13
+ import { signsStanding } from '../execution/run.mjs';
14
+ import { SIGN_STOPPED, signFailure } from '../execution/groups.mjs';
15
+ import { dispatch as dispatchOnL1 } from '../execution/run.mjs';
16
+ import { stepDispatch } from '../execution/step.mjs';
17
+ import { EVENT_REFUSED, NOT_STARTED, whenElapsed } from '../substrate/process.mjs';
18
+ import { judgeIdentity } from '../workflow/judges.mjs';
19
+ import { actionIdentity, makerAction } from '../workflow/next-action.mjs';
20
+ import { dispatchedEscalation } from '../workflow/escalation.mjs';
21
+ import { causeOf } from '../workflow/status-issue.mjs';
22
+ import { admission, admissionPath, admissions } from './admission.mjs';
23
+ import { lane } from './lane.mjs';
24
+ import { pullOrder } from './pull-order.mjs';
25
+ import { DEFAULT_CONCURRENCY } from '../config/validate.mjs';
26
+ import { schedule } from '../config/validate.mjs';
27
+ import { report as deriveReport } from '../observation/report.mjs';
28
+ import { clockWakes } from './clock.mjs';
29
+
30
+ /** The states an issue's state read answers. */
31
+ const ISSUE_STATES = ['open', 'closed', 'none'];
32
+
33
+ /** The failure `sentence` names, retaining the producer's original cause. */
34
+ const noOutcome = (sentence, reason) => {
35
+ const cause = reason;
36
+ return new Error(`${sentence}: ${causeOf(cause)}`, { cause });
37
+ };
38
+
39
+ /** L3 selects its notice fields while retaining the producer's made mark and refused events. */
40
+ function noticeAnswer({ failed, issue, closed }) {
41
+ return {
42
+ ...(failed === undefined ? {} : { failed: noticeFailed(failed) }),
43
+ ...(Number.isSafeInteger(issue) ? { issue } : {}),
44
+ ...(closed === true ? { closed: true } : {}),
45
+ };
46
+ }
47
+
48
+ /** The failed step's printable text and original made mark and unrecorded list. */
49
+ function noticeFailed({ step, cause, made, unrecorded }) {
50
+ return { step: causeOf(step), cause: causeOf(cause), ...(made === undefined ? {} : { made, unrecorded }) };
51
+ }
52
+
53
+ /**
54
+ * The failure L3 reports for hold `id`'s notice, as its caller would otherwise answer it under a
55
+ * closed admission's `notices`: a step L2's notice failed to take, and its cause, or a step the
56
+ * forge made whose record the sink refused, with its unrecorded events. It carries the notice as
57
+ * `notice`, so nothing of it is lost where admission is open or a later read fails.
58
+ */
59
+ const noticeFailure = ({ id, step, cause, made, unrecorded }) => Object.assign(new Error(made === undefined
60
+ ? `the notice for hold ${id} failed to ${step}: ${cause}`
61
+ : `the notice for hold ${id} made its step to ${step}, but the sink refused its record, so these events went unrecorded: ${eventsOf(unrecorded)}: ${cause}`), { notice: { id, step, cause, ...(made === undefined ? {} : { made, unrecorded }) } });
62
+
63
+ /** Every unrecorded event's name, in producer order, as one printable list. */
64
+ function eventsOf(unrecorded) {
65
+ return unrecorded.map(({ event }) => causeOf(event)).join(', ');
66
+ }
67
+
68
+ /** L2's newly selected action, omitting only identities this no-clock invocation already remembers. */
69
+ function eligible(card, next, memory) {
70
+ if (memory?.barred.has(card.number) && makerAction(next)) next = { action: 'ignore' };
71
+ if (memory !== undefined && next.action === 'judge') {
72
+ const judges = next.judges.filter((judge) => !memory.actions.has(`${card.number}:${judgeIdentity(judge)}`) && !memory.deferred.has(`${card.number}:${judgeIdentity(judge)}`));
73
+ next = judges.length === 0 ? { action: 'ignore' } : { ...next, judges };
74
+ }
75
+ if (memory !== undefined && makerAction(next) && (memory.actions.has(`${card.number}:${actionIdentity(next)}`) || memory.deferred.has(`${card.number}:${actionIdentity(next)}`))) next = { action: 'ignore' };
76
+ return next;
77
+ }
78
+
79
+ /**
80
+ * A `run`'s memory of the cards it set aside ("Cards this run set aside"): each card's number and
81
+ * how many reads of the board had begun when the run set it aside, and, for every card it claimed,
82
+ * set aside or not, its compared columns, the columns Rigger can have last known it in. At the
83
+ * claim, they are the column the claiming read showed and the target of each run-owned change the
84
+ * board accepted while that read was in flight; each accepted change since makes its target the one
85
+ * compared column. A read is in flight from when its pull takes it until that pull has compared and
86
+ * claimed from it, and keeps the compared columns as it began and the target of each run-owned change
87
+ * accepted meanwhile. Beside it, how many times L2 stopped each card because its line of work moved
88
+ * or was deleted since L2 read it, counted from the invocation's start or the end of the card's last
89
+ * skip ("Failure model"). Where no clock trigger keeps the run up, `clockHeld` is false and no skip ends.
90
+ */
91
+ function setAside(clockHeld) {
92
+ const cards = new Map();
93
+ const compared = new Map();
94
+ const reading = new Set();
95
+ const lineStops = new Map();
96
+ // The number of the read that last collapsed each card's compared columns.
97
+ const collapsed = new Map();
98
+ let reads = 0;
99
+ return {
100
+ /** Begins a read of the board, answering it: its number, the compared columns as it began, and what this run changes while it is in flight. */
101
+ read: () => {
102
+ reads += 1;
103
+ const read = { number: reads, began: new Map(compared), changes: new Map(), ends: new Map() };
104
+ reading.add(read);
105
+ return read;
106
+ },
107
+ /**
108
+ * Ends `read`, so changes after it no longer reach it, once its pull has compared and claimed, or
109
+ * failed: each skip a comparison of it ended is removed then, with the card's line-stop count,
110
+ * unless a run change the read overlapped has since targeted the column it compared, or the card
111
+ * was set aside afresh meanwhile.
112
+ */
113
+ done: (read) => {
114
+ reading.delete(read);
115
+ for (const [number, end] of read.ends) {
116
+ if (cards.get(number) !== end.entry || read.changes.get(number)?.has(end.column)) continue;
117
+ cards.delete(number);
118
+ lineStops.delete(number);
119
+ }
120
+ },
121
+ /** Takes `column`, the column claiming `read` showed card `number` in, and each change `read` overlapped, as its compared columns. */
122
+ claimed: (number, column, read) => compared.set(number, new Set([column, ...(read?.changes.get(number) ?? [])])),
123
+ /**
124
+ * Takes `column`, where it names one, as the target of a run-owned change of card `number` the
125
+ * board accepted, whatever holds the card: its one compared column, and kept for each read now in flight.
126
+ */
127
+ placed: (number, column) => {
128
+ if (typeof column !== 'string') return;
129
+ for (const read of reading) read.changes.set(number, new Set([...(read.changes.get(number) ?? []), column]));
130
+ compared.set(number, new Set([column]));
131
+ },
132
+ /** Sets card `number` aside, against its compared columns. */
133
+ add: (number) => cards.set(number, { reads }),
134
+ /**
135
+ * Whether `read` skips `item`. A card in no column stays skipped, its compared columns as they
136
+ * were. Otherwise, a read begun after the setting aside ends the skip only where it
137
+ * finds the card outside its compared columns as the read began and outside the target of each
138
+ * run-owned change accepted while the read was in flight. A comparison that ends it records so on
139
+ * the read, and `done` removes the skip, weighing every change the read overlapped by then, so a
140
+ * change accepted before the pull claims, or fails, still counts. One that keeps the skip, having overlapped no such change, makes the column it shows the
141
+ * one compared column, unless it began before the last read to do so. No other read writes them.
142
+ */
143
+ skips: (item, read) => {
144
+ const entry = cards.get(item.number);
145
+ if (entry === undefined) return false;
146
+ if (item.column == null) return true;
147
+ const after = clockHeld && read.number > entry.reads;
148
+ const changes = read.changes.get(item.number) ?? new Set();
149
+ const ends = after && !read.began.get(item.number)?.has(item.column) && !changes.has(item.column);
150
+ if (ends) {
151
+ read.ends.set(item.number, { entry, column: item.column });
152
+ return false;
153
+ }
154
+ if (after && changes.size === 0 && read.number > (collapsed.get(item.number) ?? 0)) {
155
+ compared.set(item.number, new Set([item.column]));
156
+ collapsed.set(item.number, read.number);
157
+ }
158
+ return true;
159
+ },
160
+ /** Counts a stop of card `number` for its line of work moved or deleted, answering whether it is a second. */
161
+ lineStopped: (number) => {
162
+ const count = (lineStops.get(number) ?? 0) + 1;
163
+ lineStops.set(number, count);
164
+ return count > 1;
165
+ },
166
+ };
167
+ }
168
+
169
+ /**
170
+ * What the loop holds over the board `config` names: N, the claims held
171
+ * in memory, L3's events, the start's kill, and the steps that take a claim, start it and release
172
+ * it. The arguments are `loop`'s, less those only a dispatch reads.
173
+ *
174
+ * `follow` is L3's act on the hold closers naming an issue, which `take` awaits at each trigger.
175
+ *
176
+ * `kill` is L1's kill of the process groups a dead engine left, injected. A handle is refused
177
+ * where it is not a function, when the handle is built, because a start that could not kill has
178
+ * nothing to stop it recording and reading over what the dead engine left (`ARCHITECTURE.md`,
179
+ * "Failure model").
180
+ */
181
+ function claiming({ config, board, facts, l2, sink, kill, readAdmission, follow, halted, hasSigns }) {
182
+ if (typeof kill !== 'function') throw new Error(`L3 was handed no kill of recorded process groups, so it cannot start: kill is ${typeof kill}`);
183
+ if (typeof facts !== 'function') throw new Error(`L3 was handed no facts call of L2's, so it cannot ask L2 about a card before claiming it: the facts call is ${typeof facts}`);
184
+ const concurrency = config.concurrency ?? DEFAULT_CONCURRENCY;
185
+ const claims = new Set();
186
+ const slots = new Set();
187
+ const generations = new Map();
188
+ let order = 0;
189
+ let killing;
190
+
191
+ /**
192
+ * Settles once the start's kill has settled, calling it on this handle's first call and never
193
+ * again, and rejects with its failure on that call and every later one: a kill that failed
194
+ * stops the start, and nothing on this handle then records or reads.
195
+ */
196
+ const killed = () => {
197
+ killing ??= (async () => kill())();
198
+ return killing;
199
+ };
200
+
201
+ /**
202
+ * Appends one of L3's events, under `card` where it concerns one. An append the sink refuses
203
+ * throws the sink's own error, and no caller here drops it (`ARCHITECTURE.md`, "Telemetry").
204
+ */
205
+ const record = (event, fields, card) => sink.emitter({ layer: 'L3', card }).emit(event, fields);
206
+
207
+ /** The failure L3 reports for an append the sink refused: `sentence`, then the sink's error, kept as the cause. */
208
+ const refused = noOutcome;
209
+
210
+ /**
211
+ * The rest of a trigger's read once `take` has recorded the trigger and `follow` has acted:
212
+ * reads the board, awaits L2's facts call, reads admission and takes the claims, answering as
213
+ * `take` does with `failures` and `notices` beside them.
214
+ */
215
+ const claim = async (limit, setAsides, read, failures, notices, memory) => {
216
+ const columns = await board.readColumns();
217
+ const { items, declared } = await board.readPriority();
218
+ /** A board item neither claimed nor skipped by this run's memory of the cards it set aside. */
219
+ const available = (item) => !claims.has(item.number) && !setAsides?.skips(item, read);
220
+ const offered = items.filter(available);
221
+ const offeredAt = new Map(offered.map(({ number }) => [number, generations.get(number)]));
222
+ const decide = await facts(offered);
223
+ // Only this read's original offer at its original generation can reach decide, even if an
224
+ // intervening claim already released or its start failed before this read finished.
225
+ const unclaimed = offered.filter((item) => available(item) && generations.get(item.number) === offeredAt.get(item.number));
226
+ // Each card's answer is kept as L2 gave it at the pull, so L3 asks nothing again to begin.
227
+ const answers = new Map();
228
+ const { pulls } = pullOrder({ items: unclaimed, columns, declared }, (card) => {
229
+ const next = eligible(card, decide(card), memory);
230
+ answers.set(card.number, next);
231
+ return next;
232
+ });
233
+ if (halted()) return { claims: [], failures, notices };
234
+ const admissionState = readAdmission();
235
+ if (admissionState.state === 'unreadable') {
236
+ const { unreadable } = admissionState;
237
+ throw Object.assign(new Error(`admission cannot be read, so this pull claims nothing: ${unreadable.map(({ path, cause }) => `${path} (${cause})`).join(', ')}`), { unreadable });
238
+ }
239
+ if (admissionState.state === 'closed') return { claims: [], failures, admission: admissionState, notices };
240
+ const taken = [];
241
+ for (const pull of pulls) {
242
+ if (limit !== undefined && taken.length >= limit) break;
243
+ const next = answers.get(pull.card);
244
+ // A merge claim holds no slot, so N does not bound it (the architect's r2 ruling 3); a limit
245
+ // given counts every card claimed, since each claim finishes a card.
246
+ const merge = next.action === 'merge';
247
+ if (!merge && slots.size >= concurrency) continue;
248
+ claims.add(pull.card);
249
+ generations.set(pull.card, (generations.get(pull.card) ?? 0) + 1);
250
+ if (!merge) slots.add(pull.card);
251
+ const card = unclaimed.find((item) => item.number === pull.card);
252
+ setAsides?.claimed(card.number, card.column, read);
253
+ taken.push({ ...pull, card, next, decide, order: order++, scope: memory === undefined ? undefined : { memory }, queueDepth: pulls.length - taken.length - 1, inFlight: slots.size });
254
+ }
255
+ return { claims: taken, failures, notices };
256
+ };
257
+
258
+ return {
259
+ concurrency,
260
+ claims,
261
+ killed,
262
+ record,
263
+ refused,
264
+
265
+ /**
266
+ * Fires the pull trigger's read: records the trigger, acts on each hold's closer naming an issue
267
+ * through `follow`, whose failed notices it answers as `notices`, reads the board, awaits L2's facts call
268
+ * over the cards no claim holds, and claims as many cards as there are free slots and no more
269
+ * than `limit` where one is given, first pulled first, deciding each with the `decide` that call
270
+ * answered. A card L2 answered `merge` holds no slot, so N does not bound it (the architect's r2
271
+ * ruling 3), and a limit given counts it like any other claim. L3
272
+ * reads nothing of that answer but calls it (the architect's ruling 2, P2, on #467). Every
273
+ * claim is taken in the same synchronous step as the pull order it follows, so no other trigger
274
+ * can claim a card between the two. Admission is read after L2 answers and before a claim is
275
+ * taken. A closed admission answers its closers with no claims; an unreadable one rejects,
276
+ * naming each path and cause, and carrying as `unreadable` the entries admission's read
277
+ * answered, unchanged, for the verb to print as it prints them (the architect's placement
278
+ * ruling on #981). Otherwise answers `claims`, each with its pull, its card, L2's answer
279
+ * for it, the `decide` the facts call answered, as `queueDepth` the pullable cards it left
280
+ * unclaimed as it took this one, whatever L2 answered them, and as `inFlight` the slots held, and
281
+ * `failures`, holding the trigger
282
+ * event's refusal where the sink refused it. A trigger is no start, so its refusal stops
283
+ * nothing: each start still tries its own event, which is what names the cards not started,
284
+ * and the refusal is reported beside theirs. A `poll`, a clock-held run's idle pull, is the
285
+ * exception: where its trigger event is refused it claims nothing. A read that fails, the facts call's included,
286
+ * rejects with the read's own error, and no card is claimed. It first awaits the start's kill,
287
+ * as `killed` says. `setAsides`, a run's memory of the cards it set aside, omits each card it
288
+ * skips, as `setAside` says, and a single pull has none. `memory` is a no-clock run's action memory.
289
+ */
290
+ take: async (limit, setAsides, poll = false, memory) => {
291
+ await killed();
292
+ if (hasSigns?.()) return { claims: [], failures: [], notices: [] };
293
+ const failures = [];
294
+ let unrecorded = false;
295
+ try {
296
+ record('trigger', { trigger: 'pull' });
297
+ } catch (refusal) {
298
+ unrecorded = true;
299
+ failures.push(refused('the event sink refused to record the pull trigger', refusal));
300
+ }
301
+ const { notices, unrecorded: unwritten } = await follow();
302
+ failures.push(...unwritten);
303
+ // A poll whose trigger the sink refused claims nothing ("A poll in each idle state").
304
+ if (poll && unrecorded) return { claims: [], failures, notices };
305
+ const read = setAsides?.read();
306
+ try {
307
+ return await claim(limit, setAsides, read, failures, notices, memory);
308
+ } catch (thrown) {
309
+ // A later read that fails keeps what this trigger already did and could not record.
310
+ const kept = [...failures, ...notices.map(noticeFailure)];
311
+ // The read's own failure stays original beside the trigger's earlier refusals.
312
+ const reason = thrown;
313
+ throw kept.length === 0 ? reason : Object.assign(new AggregateError([...kept, reason], `${reason.message}, after ${kept.length} earlier failure${kept.length === 1 ? '' : 's'} of this trigger`), { cause: reason });
314
+ } finally {
315
+ if (read !== undefined) setAsides.done(read);
316
+ }
317
+ },
318
+
319
+ /**
320
+ * Records a claim's pull event, then hands the claim to L2 with L2's answer for it, unread, and
321
+ * L2 moves the card as its column and that answer ask (the architect's ruling 2, AQ3, on #467). The event follows the claim and comes before
322
+ * the move, as `ARCHITECTURE.md`, "Failure model", orders a start. A pull event the sink
323
+ * refuses is the halt: the start is not made, the claim is released, nothing is recorded for
324
+ * it, since no pull holds a slot in the record, and the failure names the card not started and
325
+ * the sink's error.
326
+ */
327
+ start: async ({ card, kind, next, queueDepth, inFlight }) => {
328
+ try {
329
+ record('pull', { kind, queueDepth, inFlight }, card.number);
330
+ } catch (refusal) {
331
+ claims.delete(card.number);
332
+ slots.delete(card.number);
333
+ throw refused(`card #${card.number} was not started, because the event sink refused to record its pull`, refusal);
334
+ }
335
+ // L2's claim move answers the column it left the card in, which the run's memory takes.
336
+ return ['dispatch', 'judge', 'continue'].includes(next.action) ? l2.claimed(card, next) : undefined;
337
+ },
338
+
339
+ /**
340
+ * Releases `card`'s slot, which ends its claim, and records the release. A claim already
341
+ * released, as a refused pull event releases one, holds no slot in the record, so nothing is
342
+ * recorded for it. A release event the sink refuses is reported naming the card.
343
+ */
344
+ release: (card) => {
345
+ if (!claims.delete(card.number)) return;
346
+ if (!slots.delete(card.number)) return;
347
+ try {
348
+ record('slot.release', {}, card.number);
349
+ } catch (refusal) {
350
+ throw refused(`card #${card.number}'s slot was released, and the event sink refused to record it`, refusal);
351
+ }
352
+ },
353
+ };
354
+ }
355
+
356
+ /** Refuses a claim limit that is given and is not a positive whole number, naming it. */
357
+ function refuseLimit(limit) {
358
+ if (limit !== undefined && !(Number.isInteger(limit) && limit > 0)) {
359
+ const shown = typeof limit === 'string' ? `'${limit}'` : String(limit);
360
+ throw new Error(`the claim limit must be a positive whole number, and ${shown} is not one`);
361
+ }
362
+ }
363
+
364
+ /**
365
+ * Releases `claim`'s slot through `release` once `failure`, or nothing, ended its work, and
366
+ * answers what its caller reports: `failure` as it is, the release's own refusal where there
367
+ * was no failure, or the two in one AggregateError, since neither may hide the other.
368
+ */
369
+ function released(release, claim, failure) {
370
+ try {
371
+ release(claim.card);
372
+ return failure;
373
+ } catch (refusal) {
374
+ return failure === null ? refusal : new AggregateError([failure, refusal], `card #${claim.card.number} failed, and its release went unrecorded`);
375
+ }
376
+ }
377
+
378
+ /**
379
+ * An instant as the sink writes one: ISO 8601 in UTC, exactly as `toISOString` spells it, the
380
+ * six-digit years past 9999 included ("The envelope").
381
+ */
382
+ const instant = (value) => typeof value === 'string' && Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
383
+ const named = (value) => typeof value === 'string' && value !== '';
384
+ const whole = (least) => (value) => Number.isSafeInteger(value) && value >= least;
385
+ /** Whether the arming `event` holds a schedule whose `key` the config's validator admits, as L3 records it from that config. */
386
+ const admits = (key) => (value, event) => !schedule(event, 0).refusals.some((refusal) => refusal.key === key);
387
+
388
+ /**
389
+ * The fields each kind of clock event the start reads must hold, each with its check, given the
390
+ * field and the event: exactly what L3 records from any config the validator admits. A trigger's
391
+ * name is any key of the config, the empty string included; an arming's schedule is one `schedule`
392
+ * admits; a firing's start, whose `after` only a card's carries, and an outcome name an occurrence
393
+ * ("How a clock trigger fires").
394
+ */
395
+ const CLOCK_EVENTS = {
396
+ 'trigger.armed': { name: (value) => typeof value === 'string', interval: admits('interval'), anchor: admits('anchor') },
397
+ clock: { name: (value) => typeof value === 'string', occurrence: instant, after: (value) => value === undefined || whole(0)(value) },
398
+ 'trigger.outcome': { name: (value) => typeof value === 'string', occurrence: instant, outcome: (value) => ['job', 'failed', 'abandoned', 'card'].includes(value) },
399
+ };
400
+
401
+ /**
402
+ * Why `event`, read from the record, is not one event as this start reads it, or undefined where
403
+ * it is one. Every event holds the envelope: an instant as `ts`, a `run`, a layer and an `event`,
404
+ * and a `trigger` names its trigger. A clock event is L3's, and holds its kind's fields, a card
405
+ * outcome naming its issue. This is the one place the start decides what a recorded event is.
406
+ */
407
+ function unlikeEvent(event) {
408
+ if (event.event === 'trigger' && !named(event.trigger)) return 'it is a trigger naming no trigger';
409
+ const kind = event.event === 'trigger' ? (event.trigger === 'clock' ? 'clock' : undefined)
410
+ : (event.event === 'trigger.armed' || event.event === 'trigger.outcome' ? event.event : undefined);
411
+ if (kind === undefined) return undefined;
412
+ const fields = CLOCK_EVENTS[kind];
413
+ if (event.layer !== 'L3') return `it is a clock event, which only L3 records, from ${event.layer}`;
414
+ for (const [field, holds] of Object.entries(fields)) if (!holds(event[field], event)) return `its \`${field}\` is ${JSON.stringify(event[field]) ?? 'missing'}`;
415
+ if (event.outcome === 'card' && !whole(1)(event.issue)) return 'it is a card outcome naming no issue';
416
+ return undefined;
417
+ }
418
+
419
+ /**
420
+ * What the event record holds of each clock trigger, by name ("How a clock trigger fires"), read
421
+ * through `readRecord`, the verb's read of it: the instant of its newest arming, its event's `ts`,
422
+ * with that arming's `interval` and `anchor`; as `fired`, its last firing's occurrence, the newest by
423
+ * occurrence of any outcome or firing found pending; and that pending start as `pending`, keeping
424
+ * a card's `after` and whether an arming followed it. A record
425
+ * holding a line that is not one event throws, naming the stream `readRecord.stream`, the line and why.
426
+ */
427
+ function triggerRecord(readRecord) {
428
+ const events = readRecord();
429
+ const held = new Map();
430
+ const of = (name) => held.get(name) ?? held.set(name, { fired: -Infinity, starts: new Map() }).get(name);
431
+ for (const [index, event] of events.entries()) {
432
+ const why = unlikeEvent(event);
433
+ if (why !== undefined) throw new Error(`${readRecord.stream ?? 'the event record'} line ${index + 1} is not a recorded event`, { cause: new Error(why) });
434
+ if (event.event === 'trigger.armed') {
435
+ for (const firing of of(event.name).starts.values()) firing.rearmed = true;
436
+ Object.assign(of(event.name), { armed: Date.parse(event.ts), interval: event.interval, anchor: event.anchor });
437
+ }
438
+ if (event.event === 'trigger' && event.trigger === 'clock') of(event.name).starts.set(event.occurrence,
439
+ { occurrence: event.occurrence, ...(event.after === undefined ? {} : { after: event.after }) });
440
+ if (event.event !== 'trigger.outcome') continue;
441
+ const trigger = of(event.name);
442
+ trigger.fired = Math.max(trigger.fired, Date.parse(event.occurrence));
443
+ trigger.starts.delete(event.occurrence);
444
+ }
445
+ for (const trigger of held.values()) {
446
+ for (const [occurrence, firing] of trigger.starts) {
447
+ trigger.pending = firing;
448
+ trigger.fired = Math.max(trigger.fired, Date.parse(occurrence));
449
+ }
450
+ }
451
+ return held;
452
+ }
453
+
454
+ /**
455
+ * L3's dispatching entry point, over the board `config` names.
456
+ *
457
+ * `board` is L0's handle on it, the forge adapter's read side: `readColumns()` answers the
458
+ * declared columns by key, and `readPriority()` answers the cards with their priority and the
459
+ * declared order, which is what L0 hands L3 for the pull order. `readIssueState(number)` answers
460
+ * one issue's state, which L3 reads for each issue a hold's closer names, as `follow` says.
461
+ * `readItems()` answers the cards, which the repo lane reads again as it reaches a merge, as `lane` says. `facts` is L2's facts call, which
462
+ * L3 awaits over the cards it read, between its board read and its claims, and which answers the
463
+ * next action L3 asks once for each card at the pull, as `take` says. `decide` is L2's next action
464
+ * for a card, which L3 asks within each attempt as `decide(card, outcomes, options)`: with the
465
+ * attempt's outcomes after each step, with none once a later attempt's workspace is made, and
466
+ * with L1's failure as `workspace` where it could not be made. After each maker dispatch,
467
+ * L3 hands its outcome back unread as `maker`; `attempt` numbers each attempt from 1. L2 alone
468
+ * names the steps L3 dispatches, and whether the
469
+ * card is attempted again (the architect's ruling 6, Q-A and Q-D, and ruling 1, A1, on #423). After
470
+ * the maker's settle, L3 asks it again with the facts the settle answered as `forge`, and, while
471
+ * the judges it names are made and run, with `directories` and `judged`, as `attempt` and `judged`
472
+ * say. `l2` is L2's column changes, whose `claimed` takes each claim and whose `settled` takes the
473
+ * maker's outcome and, for a maker that exited 0, L1's workspace tip, and for a continuing one the
474
+ * head and rulings L2 handed that maker, unread, and the read measure, or for a fresh one the
475
+ * workspace's path. It answers what it read of the forge, which L3 reads nothing of. The
476
+ * maker is always the role L2's maker answer names, dispatched through L1, as `dispatchRole` says
477
+ * (the architect's ruling 1, Q1, on #467). `environment` is the environment L3 hands
478
+ * every dispatch it makes, each step's, the maker's and each judge's (ruling 2, AQ1). `ps` and
479
+ * `readTimeout` stand in for L0's own process-table reader and read bound, and L3 hands both to L1
480
+ * unread for every dispatch it makes, where neither is given L0 using its own
481
+ * (ruling 3, AQ7). `workspace(card)` is L1's
482
+ * workspace handle, injected, and
483
+ * answers the attempt's workspace as `{ path, branch }`, with the card's scratch base as `scratch`
484
+ * and the repository it made from as `repository` (ruling 5, P4; the architect's rulings 19 and
485
+ * 21 on #467). `workspaceTip` is L1's read of the branch's tip in that workspace after a maker
486
+ * exits 0. `clock` supplies the time and pause for a repeated forge read.
487
+ * `escalationDirectory(card, role, head)` makes an escalation role's detached directory before
488
+ * dispatch, and its retry makes both directories fresh under the same routing comment.
489
+ * `judgeDirectory(card, role, head)` is L1's make of a judge's directory, injected, as
490
+ * `judged` says (the architect's ruling 4's addendum on #467). `removeDirectories(card)` is L1's
491
+ * shared guarded directory removal, injected. `state` is the state directory L1 records each dispatch's process
492
+ * group in, which L3 hands L1's `dispatch` unread (ruling 10).
493
+ * `kill()` is L1's kill of recorded process groups, injected, and the first call on the handle
494
+ * awaits it before L3 records or reads anything, as `claiming` says. A handle is refused when it
495
+ * is built where `kill` or the facts call is not a function, checked in that order, and then, each
496
+ * after those, where the workspace handle, `judgeDirectory` or `removeDirectories` is not a
497
+ * function, `state` not a non-empty string, `environment` not an object, or `run` not a non-empty
498
+ * string. `run` is the invocation's run id, which `recording` drew, and L3 builds its one admission
499
+ * handle over `state` with it and the clock's `now`, so a hold's closer names the run that linked it.
500
+ * `readRecord` is the verb's read of the event record, handed down as the sink is: it answers the
501
+ * record's events in order, and its `stream` names the stream. A start under `run` reads it once;
502
+ * a loop handed none reads the record as holding no event.
503
+ * `drained`, where supplied, is L5's injected push step. A clock-held run calls it after a drain's
504
+ * event is recorded, without waiting, handing it the verb's `handOver` unread.
505
+ * `sink` is L5's, and L3 writes its own events through it under layer `L3`:
506
+ *
507
+ * - `run.start`, with `concurrency`, the run's N, as a run starts.
508
+ * - `trigger`, with `trigger` naming which fired: `pull` each time the pull trigger fires, before
509
+ * it reads the board, and `drain` when a pull finds nothing in flight and nothing to pull, once
510
+ * per idle period.
511
+ * - `pull`, under the card, with its `kind`, `queueDepth`, the pullable cards the pull left
512
+ * unclaimed, and `inFlight`, the slots held, a merge claim holding none. It follows the card's
513
+ * claim and comes before L2 moves the card or the lane merges it, as `ARCHITECTURE.md`,
514
+ * "Failure model", orders a start.
515
+ * - `slot.release`, under the card, as its slot is released, however its work ended. A merge claim
516
+ * holds no slot, and records none.
517
+ * - `merge.start` and `merge.end`, under the card, around its merge in the repo lane, as `lane` says.
518
+ * - `dispatch`, under its own dispatch id and the card, before anything acts on what it starts, in
519
+ * one of three kinds:
520
+ * - a step's, with the `step`'s name and either the `attempt` number, for a step in an attempt's
521
+ * workspace, or the judge's `role`, for a step in a judge's `head`, before L1 acts on the step
522
+ * (ruling 1, A8);
523
+ * - the maker's, with its `role`, its `tier` and the `attempt` number, and no `step`, before the
524
+ * provider adapter or L1 acts on it (ruling 1, Q10, and ruling 5, on #467);
525
+ * - a judge's, with its `role` and its `tier`, and neither a `step` nor an `attempt`, before the
526
+ * provider adapter or L1 acts on it.
527
+ *
528
+ * One the sink refuses starts nothing, and the failure names the card and the step or the role.
529
+ *
530
+ * A claim and its slot are held in memory from the moment L3 pulls a card until its work settles.
531
+ * A card L2 answers `merge` takes a claim and no slot, and is handed to the repo lane, which merges
532
+ * one card at a time in the order L3 pulled them (`R-SCHED-15`), as `lane` says. Its claim is
533
+ * released once its merge ends, and the card is set aside.
534
+ * One run also sets aside stopped cards, though not at a first stop for a line of work moved or
535
+ * deleted, and cards whose judges L2 withheld, leaving each out of its later pulls until its skip
536
+ * ends, as `setAside` says; a later invocation starts empty. A held
537
+ * card needs no memory, because its hold closes admission ("Failure model"): L3 follows L2's `hold`
538
+ * at every point it asks L2 within a claim, as `attempt` and `judged` say, and links one closer for
539
+ * the card through that handle on its first `hold` answer, as `holding` says. Where a hold's close
540
+ * rejects, no pull of this loop claims a card after it, and claims already held finish.
541
+ */
542
+ export function loop({ config, board, decide, facts, l2, sink, kill, workspace, workspaceTip, judgeDirectory, escalationDirectory, removeDirectories, state, readRecord = () => [], environment, run, host, readTimeout, clock, drained }) {
543
+ let admissionRecord;
544
+ let stoppedSigns = [];
545
+ let signStop;
546
+ const observeSigns = (signs = []) => { stoppedSigns = [...new Map([...stoppedSigns, ...signs].map((sign) => [JSON.stringify(sign), sign])).values()]; };
547
+ const stopped = () => {
548
+ if (signStop !== undefined) return signStop;
549
+ signStop = signFailure(stoppedSigns);
550
+ try { sink.emitter({ layer: 'L3' }).emit('sign.stopped', { signs: stoppedSigns }); }
551
+ catch (cause) { signStop.message += `; the sink refused sign.stopped: ${cause.message}`; }
552
+ return signStop;
553
+ };
554
+ const reap = typeof kill !== 'function' ? kill : async () => {
555
+ try { await kill(); } catch (failure) {
556
+ if (failure.signs === undefined) throw failure;
557
+ observeSigns(failure.signs);
558
+ throw stopped();
559
+ }
560
+ };
561
+ const { concurrency, claims, killed, record, refused, take, start, release } = claiming({ config, board, facts, l2, sink, kill: reap, hasSigns: () => stoppedSigns.length > 0, readAdmission: () => admissionRecord.read(), follow: () => follow(), halted: () => { observeSigns(signsStanding(state, { host, readTimeout })); return unsaved !== undefined || stoppedSigns.length > 0; } });
562
+ // The column each merge's end left its card in, by card, which `merged` takes for the run's memory.
563
+ const mergeEnds = new Map();
564
+ const endedAt = (card, column) => {
565
+ if (typeof column === 'string') mergeEnds.set(card.number, column);
566
+ return column;
567
+ };
568
+ const laneL2 = Object.create(l2, { mergeEnded: { value: async (card, ...rest) => {
569
+ try {
570
+ return endedAt(card, await l2.mergeEnded(card, ...rest));
571
+ } catch (failure) {
572
+ endedAt(card, failure?.column);
573
+ throw failure;
574
+ }
575
+ } } });
576
+ const { merge } = lane({ board, facts, l2: laneL2, record, refused, removeDirectories, clock });
577
+ const now = clock?.now ?? Date.now;
578
+ const pause = clock?.pause ?? ((delay) => new Promise((resolve) => { whenElapsed(delay, resolve, { hold: true }); }));
579
+ if (typeof workspace !== 'function') throw new Error(`L3 was handed no workspace handle of L1's, so it cannot make an attempt's workspace: the workspace handle is ${typeof workspace}`);
580
+ if (typeof judgeDirectory !== 'function') throw new Error(`L3 was handed no judgeDirectory of L1's, so it cannot make a judge's directory: judgeDirectory is ${typeof judgeDirectory}`);
581
+ if (typeof removeDirectories !== 'function') throw new Error(`L3 was handed no removeDirectories handle of L1's, so it cannot remove a merged card's directories: removeDirectories is ${typeof removeDirectories}`);
582
+ if (typeof state !== 'string' || state === '') throw new Error(`L3 was handed no state directory for L1's record of process groups, so it cannot dispatch: the state directory is ${JSON.stringify(state)}`);
583
+ if (environment === null || typeof environment !== 'object') throw new Error(`L3 was handed no environment for the dispatches it makes, so it cannot dispatch: the environment is ${environment === null ? 'null' : typeof environment}`);
584
+ if (typeof run !== 'string' || run === '') throw new Error(`L3 was handed no run id, so it cannot record a hold's closer: the run id is ${JSON.stringify(run) ?? 'undefined'}`);
585
+ admissionRecord = admission({ directory: state, run, now, sink });
586
+
587
+ /**
588
+ * Whether the drain trigger has fired in this idle period. Drain fires once per idle period, by
589
+ * the owner's U21 ruling, and several pulls can find the board empty in one. A claim ends an
590
+ * idle period, and so does a run's start, since drain fires at a start that finds nothing.
591
+ */
592
+ let idle = false;
593
+
594
+ /** How many drain triggers this loop has fired, so a kept-up `run` knows a drain fell in a pull. */
595
+ let drains = 0;
596
+
597
+ // Reached objects keep their producer fields; claim order lives beside them for a no-clock run.
598
+ const reachedOrder = new WeakMap();
599
+
600
+ // Owned start refusals, L2 recording halts and L1 provenance defer an unstarted identity.
601
+ const refusedStarts = new WeakSet();
602
+ const refusedAnswers = new WeakSet();
603
+ const answerFrom = (answer, ...args) => {
604
+ try { return answer(...args); }
605
+ catch (failure) {
606
+ if (failure?.halt === true) refusedAnswers.add(failure);
607
+ throw failure;
608
+ }
609
+ };
610
+ const refusedStart = (message, cause) => {
611
+ const failure = Object.assign(refused(message, cause), { halt: true });
612
+ refusedStarts.add(failure);
613
+ return failure;
614
+ };
615
+ const recordingRefusal = (failure) => failure != null && (refusedStarts.has(failure) || refusedAnswers.has(failure)
616
+ || failure.code === EVENT_REFUSED || failure.startCause?.kind === 'event-unrecorded'
617
+ || recordingRefusal(failure.cause));
618
+ const defer = (scope, card, identity) => scope?.memory.deferred.add(`${card.number}:${identity}`);
619
+
620
+
621
+ /**
622
+ * Dispatches `step`, as L2's next action names it, for `card`, in the directory at `path`, and
623
+ * settles on its outcome as `Promise.allSettled` records it. L3 allocates the dispatch's id and
624
+ * appends its start, under the id and the card, naming the step and `fields`, the attempt
625
+ * numbered `attempt` for a step in an attempt's workspace, or the judge `role` for one in a
626
+ * judge's `head`, before L1 acts (`ARCHITECTURE.md`, "Failure model" and "Telemetry"). A start
627
+ * the sink refuses starts nothing, and rejects naming the card and the step. The outcome carries
628
+ * the id as `dispatch`, from which L2 composes a hold's dispatch ids.
629
+ */
630
+ const dispatchStep = async (card, step, path, fields) => {
631
+ if (stoppedSigns.length > 0) throw signFailure(stoppedSigns);
632
+ const id = `d-${randomUUID()}`;
633
+ try {
634
+ sink.emitter({ layer: 'L3', card: card.number, dispatch: id }).emit('dispatch', { step: step.name, ...fields });
635
+ } catch (refusal) {
636
+ throw refusedStart(`card #${card.number}'s step \`${step.name}\` was not started, because the event sink refused to record its start`, refusal);
637
+ }
638
+ const [outcome] = await Promise.allSettled([dispatchOnL1({ id, card: card.number, directory: state, sink, host, readTimeout, ...stepDispatch(step, path, environment) })]);
639
+ observeSigns(outcome.value?.signs ?? outcome.reason?.signs);
640
+ if (outcome.reason?.code === SIGN_STOPPED) throw signFailure(stoppedSigns);
641
+ return { ...outcome, dispatch: id };
642
+ };
643
+
644
+ /**
645
+ * Dispatches the role L2's role answer `answer` names, for `card`, with `cwd` as its working
646
+ * directory, `directory` as the dispatch's directory, `reach` the directories it may reach, and
647
+ * the card's scratch base `scratch` and the `repository` L1 made from, each as L1's make answered
648
+ * it, and settles on its outcome as `Promise.allSettled` records it. L3 allocates the dispatch's
649
+ * id and appends its start, under the id and the card, naming the role, its tier and `fields`,
650
+ * the attempt number for a maker, then awaits `roleDispatch` and L1's `dispatch` as one settled
651
+ * unit, so anything the provider adapter runs runs after that start (the architect's ruling 5 on
652
+ * #467). `roleDispatch` is handed the answer unread, the directories, the scratch base and the
653
+ * repository unread (the architect's rulings 19 and 21, and ruling 3, P8), and `environment`. A
654
+ * start the sink refuses starts nothing, and rejects naming the card and the role. `stamp`, handed
655
+ * the answer and the id, answers the answer `roleDispatch` is handed, so that L2's `dispatched`
656
+ * writes a judge's id into its instruction (the architect's r2 ruling 6 on #642). The outcome
657
+ * carries the id as `dispatch`, as `dispatchStep`'s does.
658
+ */
659
+ const dispatchRole = async (card, answer, { cwd, directory, reach, scratch, repository, maker }, fields, stamp = (given) => given, id = `d-${randomUUID()}`) => {
660
+ if (stoppedSigns.length > 0) throw signFailure(stoppedSigns);
661
+ try {
662
+ sink.emitter({ layer: 'L3', card: card.number, dispatch: id }).emit('dispatch', { role: answer.role, tier: answer.tier, ...fields });
663
+ } catch (refusal) {
664
+ throw refusedStart(`card #${card.number}'s role \`${answer.role}\` was not started, because the event sink refused to record its start`, refusal);
665
+ }
666
+ const run = async () => {
667
+ const handed = await roleDispatch({ answer: stamp(answer, id), cwd, directory, scratch, repository, reach, maker, env: environment, sink, id, card: card.number });
668
+ return dispatchOnL1({ id, card: card.number, directory: state, sink, host, readTimeout, ...handed });
669
+ };
670
+ const [outcome] = await Promise.allSettled([run()]);
671
+ observeSigns(outcome.value?.signs ?? outcome.reason?.signs);
672
+ if (outcome.reason?.code === SIGN_STOPPED) throw signFailure(stoppedSigns);
673
+ const result = outcome.status === 'fulfilled' ? outcome.value : outcome.reason?.result;
674
+ if (result !== undefined) keepOutput({ directory: state, id, card: card.number, sink, result });
675
+ return { ...outcome, dispatch: id };
676
+ };
677
+
678
+ /** Each claimed card's close for its first `hold` answer under its claim, by card, until the claim is released. */
679
+ const holds = new Map();
680
+
681
+ /**
682
+ * The failure of a hold's close, once one has rejected: from then on no pull of this loop claims
683
+ * a card ("Failure model", "Where a hold's closer could not be saved").
684
+ */
685
+ let unsaved;
686
+
687
+ /**
688
+ * Closes admission for L2's `hold` answer `answer`, linking the hold's closer through this loop's
689
+ * one admission handle, and answers `{ closer }`, or `{ failure }` where the close rejected,
690
+ * keeping that failure as `unsaved`. Its reason names the card, and each of L2's two failures as
691
+ * `JSON.stringify` writes it. Only a card's first `hold` under its claim links a closer; a later
692
+ * one answers that close.
693
+ */
694
+ const holding = (answer) => {
695
+ if (!holds.has(answer.card)) holds.set(answer.card, closing(answer));
696
+ return holds.get(answer.card);
697
+ };
698
+
699
+ /**
700
+ * Links the closer for `holding`'s first `hold` answer of a card, then, under the card's claim,
701
+ * awaits L2's notice call for it, as `notify` says. A notice that failed is carried on the closer
702
+ * as `notice`, naming the step and its cause.
703
+ */
704
+ const closing = async ({ card, role, firstFailure, failure }) => {
705
+ const whose = role === undefined ? `card #${card}` : `card #${card}'s judge \`${role}\``;
706
+ const reason = `${whose} was held after two failures the same way: ${JSON.stringify(firstFailure)}, then ${JSON.stringify(failure)}`;
707
+ let closer;
708
+ try {
709
+ closer = await admissionRecord.close({ kind: 'hold', reason });
710
+ } catch (thrown) {
711
+ unsaved ??= thrown;
712
+ return { failure: thrown };
713
+ }
714
+ const notice = await notify(closer.id, { card, firstFailure, failure });
715
+ return { closer: notice?.failed === undefined ? closer : { ...closer, notice: notice.failed }, unrecorded: notice?.unrecorded ?? [] };
716
+ };
717
+
718
+ /** The tail of L3's calls to L2's notice function, which run one at a time ("Failure model"). */
719
+ let noticing = Promise.resolve();
720
+
721
+ /**
722
+ * Queues a call to L2's notice function for hold `id`, handed `hold`, L2's `hold` answer, where
723
+ * the call is the hold's own, and answers how it ended: undefined where, as it starts, no closer
724
+ * carries the id or the closer names an issue; `{ gone }` where a rename found the closer gone and
725
+ * L3 ended the call; otherwise what L2 answered, a call that threw answering as `failed`.
726
+ */
727
+ const notify = (id, hold, issueState) => {
728
+ noticing = noticing.then(() => noticed(id, hold, issueState)).catch((thrown) => ({ failed: { step: 'notice', cause: causeOf(thrown) } }));
729
+ return noticing;
730
+ };
731
+
732
+ /**
733
+ * One notice call for hold `id`, on its closer as L3 lists it as the call starts, handing L2 the
734
+ * issue numbers the other hold closers name. L3 makes each rename L2 answers through `admission.mjs`
735
+ * and hands L2 the outcome unread, as `Promise.allSettled` records it, before L2 writes again.
736
+ * A closer naming an issue is followed only where L3 read that issue's state, `issueState`, as `{
737
+ * issue, state }`, and only while the closer still names the issue that state was read for: a
738
+ * call queued behind another that renamed the closer hands L2 nothing, and the next trigger reads
739
+ * the issue it now names. L3 hands L2 that state; where L2 answers that the notice closed for that
740
+ * hold, L3 removes its closer through `admission.mjs`, the event naming the issue's close as what
741
+ * reopened admission. A removal whose event the sink refused answers as `unrecorded`, the refusal.
742
+ */
743
+ const noticed = async (id, hold, issueState) => {
744
+ const closers = admissionRecord.read().closers ?? [];
745
+ const closer = closers.find((each) => each.id === id);
746
+ if (closer === undefined || closer.issue !== issueState?.issue) return undefined;
747
+ const others = closers.filter((each) => each.issue !== undefined && each.id !== id).map((each) => Number(each.issue));
748
+ let { name } = closer;
749
+ // Each action L3 makes whose record the sink refused, kept by L3 whatever L2 does next.
750
+ const unrecorded = [];
751
+ try {
752
+ const steps = l2.notice({ closer, others, hold, admission: admissionPath(state), ...(issueState === undefined ? {} : { state: issueState.state }) });
753
+ let { done, value } = await steps.next();
754
+ while (!done) {
755
+ const asked = value;
756
+ const [outcome] = await Promise.allSettled([(async () => admissionRecord.rename(name, asked))()]);
757
+ if (outcome.value?.gone) {
758
+ await steps.return();
759
+ return { gone: true, unrecorded };
760
+ }
761
+ if (outcome.status === 'fulfilled') ({ name } = outcome.value);
762
+ // A rename made whose record the sink refused: the closer is at its new name, and the refusal is L3's to report.
763
+ else if (admissions(outcome.reason) && outcome.reason.renamed !== undefined) {
764
+ name = outcome.reason.renamed;
765
+ unrecorded.push(outcome.reason);
766
+ }
767
+ ({ done, value } = await steps.next(outcome));
768
+ }
769
+ const answer = noticeAnswer(value);
770
+ if (answer.closed) {
771
+ const [opened] = await Promise.allSettled([admissionRecord.open(name, answer.issue === undefined ? {} : { issue: answer.issue })]);
772
+ if (opened.status === 'rejected') unrecorded.push(opened.reason);
773
+ }
774
+ return { ...answer, unrecorded };
775
+ } catch (thrown) {
776
+ return { failed: { step: 'notice', cause: causeOf(thrown) }, unrecorded };
777
+ }
778
+ };
779
+
780
+ /**
781
+ * Issue `number`'s state as `board.readIssueState` answers it, tagged `ok` with the state where the
782
+ * read fulfilled with a state it names, and otherwise not `ok`, with a printable `failure`: the
783
+ * tag, never the rejected value, tells the two apart, since a read can reject with anything,
784
+ * undefined among it.
785
+ */
786
+ const stateOf = async (number) => {
787
+ let answer;
788
+ try {
789
+ answer = await board.readIssueState(number);
790
+ } catch (thrown) {
791
+ return { ok: false, failure: causeOf(thrown) };
792
+ }
793
+ const { state } = answer;
794
+ if (!ISSUE_STATES.includes(state)) return { ok: false, failure: `board.readIssueState answered no state: ${causeOf(answer)}` };
795
+ return { ok: true, read: state };
796
+ };
797
+
798
+ /**
799
+ * L3's act at a trigger on each hold's closer naming an issue, after it lists admission: it reads
800
+ * each issue those closers name by its number, once whatever number of closers name it, through
801
+ * `board.readIssueState`, and hands L2's notice function each closer's hold and that state, as
802
+ * `noticed` says. A read that fails or times out counts as unreadable: L3 hands L2 nothing for that
803
+ * closer, records `notice.failed` naming the issue, and the next trigger reads again. Answers
804
+ * `notices`, each failed notice as `{ id, step, cause }`, and `unrecorded`, the failure of each
805
+ * opening whose event the sink refused, which the trigger reports whether or not admission opened.
806
+ */
807
+ const follow = async () => {
808
+ const listed = admissionRecord.read();
809
+ const notices = [];
810
+ const unrecorded = [];
811
+ if (listed.state !== 'closed') return { notices, unrecorded };
812
+ const states = new Map();
813
+ for (const { kind, id, issue } of listed.closers) {
814
+ if (kind !== 'hold' || issue === undefined) continue;
815
+ if (!states.has(issue)) states.set(issue, stateOf(Number(issue)));
816
+ const { ok, read, failure } = await states.get(issue);
817
+ if (!ok) {
818
+ const failed = { step: `read issue #${issue}'s state`, cause: failure };
819
+ try {
820
+ record('notice.failed', { hold: id, issue: Number(issue), ...failed });
821
+ notices.push({ id, ...failed });
822
+ } catch (refusal) {
823
+ notices.push({ id, ...failed, cause: `${failed.cause}; and the sink refused its notice.failed event: ${causeOf(refusal)}` });
824
+ }
825
+ continue;
826
+ }
827
+ const ended = await notify(id, undefined, { issue, state: read });
828
+ if (ended?.failed !== undefined) notices.push({ id, ...ended.failed });
829
+ unrecorded.push(...(ended?.unrecorded ?? []));
830
+ }
831
+ return { notices, unrecorded };
832
+ };
833
+
834
+ /**
835
+ * Closes admission for L2's `hold` answer `answer` for `card`'s judge `role`, as `holding` says,
836
+ * and answers the failure the card ends held with: it names the card, the judge, that it was held
837
+ * and both of L2's failures, carrying them, the decision and the closer as fields, or as
838
+ * `unsaved` the close's failure where it rejected.
839
+ */
840
+ const heldJudge = async (card, role, answer) => {
841
+ const { closer, failure: unsavedBy, unrecorded = [] } = await holding({ ...answer, role });
842
+ const { firstFailure, failure } = answer;
843
+ return Object.assign(new Error(`card #${card.number}'s judge \`${role}\` was held after two dispatches that failed the same way:\nfirst: ${JSON.stringify(firstFailure)}\nsecond: ${JSON.stringify(failure)}`), {
844
+ card: card.number, role, decision: 'hold', firstFailure, failure, unrecorded, ...(unsavedBy === undefined ? { closer } : { unsaved: unsavedBy }),
845
+ });
846
+ };
847
+
848
+ /**
849
+ * Has L1 make `card`'s workspace for the attempt numbered `number`, and answers it as `{ path,
850
+ * scratch, repository }`, the card's scratch base and repository beside it as L1 answered them,
851
+ * or, where L1 could not make it, L2's answer for that attempt, handed the failure unread.
852
+ */
853
+ const made = async (card, number, continuing, firstFailure) => {
854
+ const [outcome] = await Promise.allSettled([new Promise((resolve) => resolve(workspace(card.number, continuing?.head)))]);
855
+ if (outcome.status === 'fulfilled') return { path: outcome.value.path, branch: outcome.value.branch, scratch: outcome.value.scratch, repository: outcome.value.repository };
856
+ return { answer: answerFrom(decide, card, [], { attempt: number, firstFailure, workspace: outcome, continuing }) };
857
+ };
858
+
859
+ /**
860
+ * The attempts at `card`, from `next`, L2's answer for it at the pull, under its
861
+ * one claim. Each attempt has L1 make the workspace, then dispatches each step L2 names, one at a
862
+ * time, handing L2 each outcome unread with the attempt's number and asking it again, until L2
863
+ * names no step. A later attempt asks L2 for its first step once its workspace is made.
864
+ *
865
+ * An answer that dispatches no step is the maker: the role the answer's `maker` names,
866
+ * dispatched through L1 as `dispatchRole` says. After a continuing maker exits 0, L3 reads its
867
+ * workspace tip through L1. L3 hands L2 each maker outcome unread, with that tip where read.
868
+ * A stale forge head has L3 pause and ask L2 to settle again under the same claim and slot.
869
+ * Where the settle succeeded, L3 hands its facts to `decide` with the attempt number. L3 follows
870
+ * L2's `again`, `hold`, `stop` or `escalate` answer; a retry makes a fresh workspace. Otherwise the attempt
871
+ * answers the card, its
872
+ * workspace, the maker's `outcome` and L2's `settled`, each as `Promise.allSettled` records it.
873
+ * Where the settle
874
+ * answered facts and L2, asked again with them, names judges, they are dispatched under the same
875
+ * claim, as `judges` says, and the answer also carries them as `judges`. The maker's result is
876
+ * handed to `kept` as soon as the settle answers, before L2 is asked about judges, so a judge's
877
+ * failure, or L2's judge answer throwing, still leaves its caller the maker's result while the
878
+ * attempt rejects with that failure. Where a judge failed to hand back, the maker's result is
879
+ * handed to `kept` again with every judge L2 named beside it as `judges`, as `judges` hands them
880
+ * to its `keep`. An answer naming the
881
+ * next attempt has L3 make it; one holding or stopping the card fails, naming the card and each
882
+ * attempt's failure, in order, both in the message and as fields `card` and `attemptFailures`.
883
+ * A hold first closes admission, and its failure carries the closer as `closer`, or, where the
884
+ * close rejected, fails as an AggregateError holding it beside the close's failure.
885
+ * A held or stopped card is absent from `reached`. Any other answer stops the attempts, naming the card
886
+ * and what L2 answered. `remember` marks a card whose judges L2 withheld, or whose failed maker
887
+ * L2 answered `set-aside`, for this run. A set-aside settle answers `reached` without asking judges.
888
+ * `placed` takes each column an L2 column change answered, as `work` says.
889
+ */
890
+ const attempt = async (card, next, kept, remember, placed, scope) => {
891
+ const continuing = next.action === 'continue' ? next : undefined;
892
+ const failures = [];
893
+ const askAttempt = (outcomes, options) => answerFrom(decide, card, outcomes, { ...options, firstFailure: failures[0], continuing });
894
+ const escalated = async (answer) => {
895
+ remember(answer);
896
+ placed(await l2.escalated(card, answer));
897
+ return { card: card.number, ...answer };
898
+ };
899
+ /** The failure naming the card as held or stopped after its attempts, each attempt's failure in order. */
900
+ const ended = (answer, held) => {
901
+ const attemptFailures = [...failures, answer.failure];
902
+ const each = attemptFailures.map((failure, at) => `attempt ${at + 1}: ${JSON.stringify(failure)}`);
903
+ return Object.assign(new Error(`card #${card.number} was ${held ? 'held' : 'stopped'} after ${each.length} attempts, each failing before the maker:\n${each.join('\n')}`), { card: card.number, attemptFailures, ...(held ? { decision: 'hold' } : {}) });
904
+ };
905
+ /**
906
+ * Follows L2's retry, hold or stop answer, retaining each failure for the final report. A hold
907
+ * closes admission first, through `holding`, and the card then ends held.
908
+ */
909
+ const advance = async (answer, number) => {
910
+ if (answer.action === 'again' && answer.attempt === number + 1) {
911
+ failures.push(answer.failure);
912
+ return true;
913
+ }
914
+ if (answer.action === 'hold') {
915
+ const { closer, failure: unsavedBy, unrecorded = [] } = await holding(answer);
916
+ if (unsavedBy !== undefined) throw new AggregateError([ended(answer, true), unsavedBy], `card #${card.number} was held, and its closer was not saved`);
917
+ // A notice step L3 made for the closer whose record the sink refused stays beside the held card.
918
+ if (unrecorded.length > 0) throw new AggregateError([Object.assign(ended(answer, true), { closer }), ...unrecorded], `card #${card.number} was held, and a step of its notice went unrecorded`);
919
+ throw Object.assign(ended(answer, true), { closer });
920
+ }
921
+ if (answer.action === 'stop') throw ended(answer, false);
922
+ return false;
923
+ };
924
+ let answer = next;
925
+ for (let number = 1; ; number += 1) {
926
+ const { path, branch, scratch, repository, answer: unmade } = await made(card, number, continuing, failures[0]);
927
+ if (unmade !== undefined) {
928
+ answer = unmade;
929
+ } else {
930
+ if (number > 1 || continuing !== undefined) answer = askAttempt([], { attempt: number });
931
+ const outcomes = [];
932
+ while (answer.action === 'dispatch' && answer.step !== undefined) {
933
+ outcomes.push(await dispatchStep(card, answer.step, path, { attempt: number }));
934
+ answer = askAttempt([...outcomes], { attempt: number });
935
+ }
936
+ }
937
+ if (await advance(answer, number)) continue;
938
+ if (answer.action === 'escalate') return escalated(answer);
939
+ if (answer.action !== 'dispatch') {
940
+ throw new Error(`card #${card.number}'s attempt stopped, as L2 answered: ${JSON.stringify(answer)}`);
941
+ }
942
+ let dispatch;
943
+ const outcome = await dispatchRole(card, answer.maker, { cwd: path, directory: path, reach: [], scratch, repository, maker: true }, { attempt: number }, (given, id) => {
944
+ dispatch = id;
945
+ return dispatchedEscalation(given, id);
946
+ });
947
+ if (scope !== undefined && (outcome.status === 'fulfilled' || outcome.reason?.result !== undefined)) {
948
+ scope.memory.actions.add(`${card.number}:${actionIdentity(next)}`);
949
+ }
950
+ const terminal = scope !== undefined && outcome.status === 'rejected' && recordingRefusal(outcome.reason);
951
+ if (terminal) defer(scope, card, actionIdentity(next));
952
+ let settled;
953
+ // Every settle of this maker hands L2 `placed`, so the column its move left the card in reaches the memory.
954
+ const settling = (options) => Promise.allSettled([l2.settled(card, outcome, { dispatch, placed, ...options })]);
955
+ const exitedZero = outcome.status === 'fulfilled' && outcome.value.exit === 0;
956
+ let expectedHead;
957
+ let tipFailure;
958
+ // Every maker that exits 0 has L1 read its workspace's tip, which L2 compares for a continuing one and names in a fresh one's escalation.
959
+ if (exitedZero) {
960
+ try {
961
+ if (typeof workspaceTip !== 'function') throw new Error('L3 was handed no L1 workspace-tip reader');
962
+ expectedHead = await workspaceTip({ card: card.number, dispatch, path, branch, repository });
963
+ if (typeof expectedHead !== 'string' || expectedHead === '') throw new Error(`L1 found no tip for card #${card.number}'s line of work`);
964
+ } catch (failure) {
965
+ if (failure.code === EVENT_REFUSED) throw failure;
966
+ tipFailure = failure;
967
+ }
968
+ }
969
+ if (continuing !== undefined && exitedZero) {
970
+ const first = now();
971
+ let reads = 0;
972
+ let lastForgeHead;
973
+ for (;;) {
974
+ const elapsedMs = now() - first;
975
+ reads += 1;
976
+ [settled] = await settling({ continuing: true, startHead: continuing.head, rulings: continuing.markers, expectedHead, tipFailure, lastForgeHead, last: elapsedMs >= 60_000, reads, elapsedMs });
977
+ if (settled.status !== 'fulfilled' || !settled.value?.waiting) break;
978
+ lastForgeHead = settled.value.forgeHead;
979
+ // D16 rule 3: the forge can still show the old head after a push. #664's journal/P58
980
+ // saw old facts at about 2, 2.4, 6 and 7 seconds. #664's stream saw new facts on later
981
+ // invocations by 103.5 and 91.7 seconds (#758); no forge lag was measured.
982
+ await pause(5_000);
983
+ }
984
+ } else {
985
+ [settled] = await settling({ continuing: continuing !== undefined, ...(scope === undefined ? {} : { noClock: true }),
986
+ ...(exitedZero ? { tip: expectedHead, tipUnread: tipFailure, workspace: path } : {}) });
987
+ }
988
+ // Only L2's settlement answer supplies this halt; a generic L1 failure is not terminal.
989
+ if (scope !== undefined && settled.status === 'rejected' && settled.reason?.halt === true) defer(scope, card, actionIdentity(next));
990
+ const makerWork = settled.status === 'fulfilled' ? settled.value?.makerWork : settled.reason?.makerWork;
991
+ if (makerWork !== undefined && makerWork !== 'present') {
992
+ if (scope === undefined) remember({ action: 'set-aside' });
993
+ else scope.memory.barred.add(card.number);
994
+ }
995
+ if (settled.status === 'fulfilled' && settled.value?.action === 'escalate') {
996
+ const escalation = settled.value;
997
+ remember(escalation);
998
+ const reached = { card: card.number, workspace: path, outcome, settled };
999
+ kept(reached);
1000
+ if (escalation.destination !== 'owner') {
1001
+ let routed;
1002
+ // A refused routing write leaves the card set aside, as `remember` marked the escalation.
1003
+ routed = await l2.routed(card, escalation);
1004
+ if (routed.action === 'escalate') return { ...reached, ...await escalated(routed) };
1005
+ let firstFailure;
1006
+ for (;;) {
1007
+ const [made] = await Promise.allSettled([new Promise((resolve) => resolve(escalationDirectory(card.number, routed.role.role, escalation.head)))]);
1008
+ let roleId;
1009
+ let roleOutcome = made;
1010
+ if (made.status === 'fulfilled') {
1011
+ const directory = made.value;
1012
+ roleOutcome = await dispatchRole(card, routed.role, {
1013
+ cwd: directory.main, directory: directory.path, reach: directory.head === undefined ? [] : [directory.head], scratch: directory.scratch, repository: directory.repository,
1014
+ }, {}, (given, id) => { roleId = id; return dispatchedEscalation(given, id); });
1015
+ }
1016
+ const ended = await l2.roleSettled(card, escalation, roleOutcome, { dispatch: roleId, firstFailure });
1017
+ placed(ended?.column);
1018
+ if (ended?.action === 'again') {
1019
+ firstFailure = roleOutcome;
1020
+ continue;
1021
+ }
1022
+ const handled = { ...reached, action: 'handled', escalationRole: { role: routed.role.role, outcome: roleOutcome, settled: ended } };
1023
+ kept(handled);
1024
+ if (ended?.action === 'escalate') return { ...handled, ...await escalated(ended) };
1025
+ return handled;
1026
+ }
1027
+ }
1028
+ const ended = { ...reached, ...await escalated(escalation) };
1029
+ kept(ended);
1030
+ return ended;
1031
+ }
1032
+ // A settle that rejects after the board accepted its move carries that column (`change` in transitions.mjs).
1033
+ if (settled.status === 'rejected') placed(settled.reason?.column);
1034
+ if (settled.status === 'fulfilled' && !terminal) {
1035
+ answer = askAttempt([], { attempt: number, maker: outcome });
1036
+ if (await advance(answer, number)) continue;
1037
+ if (answer.action === 'escalate') return escalated(answer);
1038
+ }
1039
+ const reached = { card: card.number, workspace: path, outcome, settled, ...(continuing === undefined ? {} : { action: 'continue', pull: continuing.pull, head: continuing.head }) };
1040
+ kept(reached);
1041
+ if (scope !== undefined && makerWork !== undefined) {
1042
+ if (continuing !== undefined) remember({ action: 'set-aside' });
1043
+ return reached;
1044
+ }
1045
+ if (settled.status === 'fulfilled' && settled.value?.action === 'set-aside') {
1046
+ remember(settled.value);
1047
+ return reached;
1048
+ }
1049
+ if (settled.status !== 'fulfilled' || settled.value === undefined) return reached;
1050
+ // The facts L2's settle answered go back to L2 unread, so one read decides both the move and
1051
+ // the judges (the architect's ruling 3, AQ4, on #467).
1052
+ const ask = (options) => answerFrom(decide, card, [], { ...options, forge: settled.value });
1053
+ const judging = eligible(card, ask({}), scope?.memory);
1054
+ if (judging.action !== 'judge') return reached;
1055
+ return { ...reached, judges: await judges(card, judging, ask, (ended) => kept({ ...reached, judges: ended }), remember, placed, scope) };
1056
+ }
1057
+ };
1058
+
1059
+ /**
1060
+ * The judge L2's answer `answer` names as `role`, or nothing where it names none, being no judge
1061
+ * answer or one that withholds that judge.
1062
+ */
1063
+ const named = (answer, role) => (answer.action === 'judge' ? answer.judges.find((judge) => judge.role === role) : undefined);
1064
+
1065
+ /**
1066
+ * The judge `judge`, as L2's judge answer names it, of `card`, under the card's one claim, asking
1067
+ * L2 again through `ask`. L3 has L1 make the judge's directory through `judgeDirectory`, handed the
1068
+ * card, the role and the head SHA L2 named, before any of the judge's dispatches start. Where L1
1069
+ * could not make it, L3 hands the failure unread to L2 as the role's in `directories`, and the
1070
+ * judge is not dispatched. Otherwise L3 dispatches each step L2 named in the directory's `head`,
1071
+ * one at a time, handing L2 the role's outcomes so far unread in `judged` after each, and the judge
1072
+ * is not dispatched once L2's answer no longer names it. Then the judge, as L2 last named it, is
1073
+ * dispatched with `main` as its working directory, its judge directory as the dispatch's, and
1074
+ * `head` as the directory it may reach, each as L1's make answered it, never from L2's answer (the
1075
+ * architect's ruling 3, P8, and ruling 4's addendum), its instruction carrying its dispatch id as
1076
+ * L2's `dispatched` writes it. Where L1 reports that the judge's dispatch did not start, L3 hands
1077
+ * that report unread to L2 as the role's in `directories`, and L2 withholds the judge where the
1078
+ * report names its scratch directory as missing ("Failure model", step 4). Where L2 answers either
1079
+ * of those two asks `hold`, L3 closes admission at once, without waiting for the card's other
1080
+ * judges, and answers `{ role, held }`, `held` the failure `heldJudge` names. Answers `{ role,
1081
+ * outcome }`, the judge's
1082
+ * outcome as `Promise.allSettled` records it, or, for a judge L2 withheld, `{ role, withheld }`,
1083
+ * `withheld` holding what L3 handed L2 that L2 withheld it for: `{ directory }`, L1's failure to
1084
+ * make its directory, `{ scratch }`, L1's report that its dispatch did not start, or `{ step,
1085
+ * outcome }`, the step in its `head` whose outcome L2 was handed
1086
+ * last, by name, and that outcome, since L3 asks after each step.
1087
+ */
1088
+ const judgeWork = async (card, judge, ask, scope) => {
1089
+ const { role } = judge;
1090
+ const [made] = await Promise.allSettled([new Promise((resolve) => resolve(judgeDirectory(card.number, role, judge.facts.head)))]);
1091
+ if (made.status === 'rejected') {
1092
+ const answer = ask({ directories: { [role]: made } });
1093
+ if (answer.halt) {
1094
+ defer(scope, card, judgeIdentity(judge));
1095
+ throw made.reason;
1096
+ }
1097
+ if (answer.action === 'hold') return { role, held: await heldJudge(card, role, answer), decision: answer };
1098
+ if (answer.action === 'escalate') return { role, outcome: made, escalation: answer, decision: answer };
1099
+ return { role, withheld: { directory: made }, decision: answer };
1100
+ }
1101
+ const { path, main, head, scratch, repository } = made.value;
1102
+ const outcomes = [];
1103
+ let current = judge;
1104
+ while (outcomes.length < current.steps.length) {
1105
+ const step = current.steps[outcomes.length];
1106
+ outcomes.push(await dispatchStep(card, step, head, { role }));
1107
+ const answer = ask({ judged: { [role]: [...outcomes] } });
1108
+ current = named(answer, role);
1109
+ if (current === undefined) return { role, withheld: { step: step.name, outcome: outcomes.at(-1) }, decision: answer };
1110
+ }
1111
+ const id = `d-${randomUUID()}`;
1112
+ const ready = ask({ judgeDispatch: { judge: current, id } });
1113
+ if (ready.action === 'escalate') return { role, escalation: ready, decision: ready };
1114
+ current = named(ready, role);
1115
+ if (current === undefined) return { role, decision: ready };
1116
+ const outcome = await dispatchRole(card, current, { cwd: main, directory: path, reach: [head], scratch, repository }, {}, (given) => given, id);
1117
+ if (scope !== undefined && (outcome.status === 'fulfilled' || outcome.reason?.result !== undefined)) {
1118
+ scope.memory.actions.add(`${card.number}:${judgeIdentity(current)}`);
1119
+ }
1120
+ if (outcome.status === 'rejected' && [NOT_STARTED, SCRATCH_REFUSED, EVENT_REFUSED].includes(outcome.reason?.code)) {
1121
+ const answer = ask({ directories: { [role]: outcome } });
1122
+ if (answer.halt) {
1123
+ defer(scope, card, judgeIdentity(judge));
1124
+ return { role, outcome, halt: true, decision: answer };
1125
+ }
1126
+ if (answer.action === 'hold') return { role, held: await heldJudge(card, role, answer), decision: answer };
1127
+ if (answer.action === 'escalate') return { role, outcome, escalation: answer, decision: answer };
1128
+ if (answer.action === 'again') return { role, retry: { judge: current, failure: outcome } };
1129
+ if (answer.action === 'stop') return { role, decision: answer, failure: Object.assign(new Error(`card #${card.number}'s judge \`${role}\` was stopped after two dispatches:\nfirst: ${JSON.stringify(answer.firstFailure)}\nsecond: ${JSON.stringify(answer.failure)}`), { card: card.number, role, decision: 'stop', firstFailure: answer.firstFailure, failure: answer.failure }) };
1130
+ if (named(answer, role) === undefined) return { role, withheld: { scratch: outcome }, decision: answer };
1131
+ }
1132
+ const comments = await facts([], { judge: current });
1133
+ const [history] = await Promise.allSettled([Promise.resolve().then(() => readRecord().filter((event) => event.card === card.number))]);
1134
+ const decision = ask({ judgeSettled: { judge: current, outcome, comments, record: history } });
1135
+ if (history.status === 'rejected') return { role, outcome, decision,
1136
+ failure: new Error(`the event record ${readRecord.stream ?? ''} could not be read: ${history.reason.message}`, { cause: history.reason }) };
1137
+ return { role, outcome, decision, ...(decision.action === 'escalate' ? { escalation: decision } : {}) };
1138
+ };
1139
+
1140
+ const judged = async (card, judge, ask, scope) => {
1141
+ try {
1142
+ return await judgeWork(card, judge, ask, scope);
1143
+ } catch (failure) {
1144
+ if (recordingRefusal(failure)) defer(scope, card, judgeIdentity(judge));
1145
+ throw failure;
1146
+ }
1147
+ };
1148
+
1149
+ /**
1150
+ * Dispatches every judge L2's judge answer `answer` names for `card`, at once, under the card's
1151
+ * one claim, as `judged` says, asking L2 again through `ask`, and settles once every one of them
1152
+ * has handed back its outcome. Answers the judges dispatched, each `{ role, outcome }`, in the
1153
+ * order L2 named them, a judge L2 withheld among none of them.
1154
+ *
1155
+ * Where one failed to hand back an outcome, its start refused or L2 answering no action for it,
1156
+ * it waits for every other, then hands `keep` every judge L2 named, in the order it named them,
1157
+ * each in one of three shapes:
1158
+ *
1159
+ * - `{ role, outcome }`, for a judge that handed back;
1160
+ * - `{ role, failure }`, for one that failed to, `failure` being the error that names it in the
1161
+ * rejection;
1162
+ * - `{ role, withheld }`, for one L2 withheld, as `judged` answers it.
1163
+ *
1164
+ * A judge L2 held is one that failed to hand back, its failure the held one, beside the close's
1165
+ * own where that rejected, so the card ends held once every judge it dispatched has handed back.
1166
+ *
1167
+ * Where L2 answered an escalation, every outcome is kept before one write through L2, after
1168
+ * all the named judges finish, and so after any hold's close. L2 is handed every refusal report together for that answer.
1169
+ * Then it rejects with an AggregateError naming the card and each judge that failed, and why, in
1170
+ * its `errors`, so no judge's outcome is dropped for another's failure.
1171
+ */
1172
+ const judges = async (card, answer, ask, keep, remember, placed, scope) => {
1173
+ const settled = await Promise.allSettled(answer.judges.map((judge) => judged(card, judge, ask, scope)));
1174
+ let interrupted = settled.some((each) => each.status === 'rejected' || each.value.escalation !== undefined || each.value.halt);
1175
+ for (const [at, each] of settled.entries()) {
1176
+ if (each.status !== 'fulfilled' || each.value.retry === undefined) continue;
1177
+ const { judge, failure } = each.value.retry;
1178
+ if (interrupted) {
1179
+ settled[at] = { status: 'fulfilled', value: { role: judge.role, outcome: failure } };
1180
+ continue;
1181
+ }
1182
+ const repeat = (options) => ask({ ...options, ...(options.directories === undefined ? {} : {
1183
+ directories: Object.fromEntries(Object.entries(options.directories).map(([role, outcome]) => [role, { ...outcome, firstFailure: failure }])),
1184
+ }) });
1185
+ [settled[at]] = await Promise.allSettled([judged(card, judge, repeat, scope)]);
1186
+ interrupted ||= settled[at].status === 'rejected' || settled[at].value.halt;
1187
+ }
1188
+ const decision = ask({ judged: Object.fromEntries(settled.map((each, at) => [answer.judges[at].role, { decision: each.status === 'fulfilled' ? each.value.decision : undefined }])) });
1189
+ remember(decision);
1190
+ // A judge L2 held fails the card held, as one that handed back no outcome fails it.
1191
+ const ended = settled.map((each, at) => (each.status === 'fulfilled'
1192
+ ? (each.value.held === undefined ? each.value : { role: each.value.role, failure: each.value.held })
1193
+ : { role: answer.judges[at].role, failure: noOutcome(`card #${card.number}'s judge \`${answer.judges[at].role}\` handed back no outcome`, each.reason) }));
1194
+ const failed = ended.filter((each) => each.failure !== undefined).flatMap((each) => [each.failure, ...(each.failure.unsaved === undefined ? [] : [each.failure.unsaved]), ...(each.failure.unrecorded ?? [])]);
1195
+ const escalating = ended.filter((each) => each.escalation !== undefined);
1196
+ const carried = ended.map(({ escalation, decision, ...each }) => each);
1197
+ if (escalating.length > 0) {
1198
+ keep(carried);
1199
+ const escalation = ask({ directories: Object.fromEntries(escalating.map(({ role, outcome }) => [role, outcome])), judged: Object.fromEntries(settled.map((each, at) => [answer.judges[at].role, { decision: each.status === 'fulfilled' ? each.value.decision : undefined }])) });
1200
+ try {
1201
+ placed(await l2.escalated(card, escalation));
1202
+ } catch (failure) {
1203
+ placed(failure?.column);
1204
+ failed.push(failure);
1205
+ }
1206
+ if (failed.length === 0) return carried;
1207
+ }
1208
+ if (failed.length === 0) return carried.filter((each) => each.outcome !== undefined);
1209
+ keep(carried);
1210
+ throw new AggregateError(failed, `card #${card.number}'s judges did not all hand back an outcome`);
1211
+ };
1212
+
1213
+ /**
1214
+ * One claimed card's work: its start, then its attempt and L2's handling of the maker's outcome,
1215
+ * handed over unread, or, for a card L2 answered with its judges at the pull, those judges alone,
1216
+ * with no workspace made and no maker dispatched, asking L2 again through the `decide` the facts
1217
+ * call answered. The slot is released however it ends, and then `freed` runs, unless the start
1218
+ * was not made: a claim the board refused to move, or whose pull event the sink refused, waits
1219
+ * for the next trigger rather than starting another pull at once, by the owner's ruling on
1220
+ * #228, so a board refusing every claim, or a sink refusing every event, cannot keep a run
1221
+ * pulling. Settles on `{ reached, failure }`: `reached`, what the card answers as `trigger` says,
1222
+ * or nothing for a card whose maker never ran and whose work failed; and `failure`, the work's
1223
+ * failure and a refused release event, both reported as `released` says, or null where there was
1224
+ * neither. A card whose maker ran keeps its maker's result in `reached` though its judges then
1225
+ * failed, as `attempt` says. A card one of whose judges failed to hand back carries in `reached`
1226
+ * every judge L2 named beside its number, as `judges` hands them to its `keep`, whichever way it
1227
+ * was claimed, and whether or not its release event was refused. L2's report of a refused
1228
+ * transition event passes through unchanged as the work's failure where it comes from the claim;
1229
+ * from the maker's settle it comes back in the card's `settled`, as `attempt` says. `setAsides`,
1230
+ * the run's memory as `setAside` says, sets aside a stopped card, a card whose judges L2
1231
+ * withheld, or a removal's following refusal or ignore before `freed` fires another trigger,
1232
+ * against its compared columns, which each of L2's column changes under the claim sets to the
1233
+ * column it answered. A stop for a line of work moved or deleted sets the card aside only at its second.
1234
+ * A removal keeps this claim through guarded cleanup and its following ordinary action.
1235
+ * Cleanup failure is retained beside that action's failure and never replaces the action;
1236
+ * a following Coding move is attempted only after cleanup.
1237
+ */
1238
+ const work = async (claim, freed, setAsides) => {
1239
+ const { card, decide: atPull, scope } = claim;
1240
+ let next = claim.next;
1241
+ // Whether the run sets the card aside once its work ends, and whether its claim ended at a stop
1242
+ // for its line of work, which counts in place of every other rule.
1243
+ let aside = false;
1244
+ let lineStop = false;
1245
+ /** Takes `answered`, where it names a column, as the target of a change of the card the board accepted. */
1246
+ const placed = (answered) => setAsides?.placed(card.number, answered);
1247
+ /** Keeps L2's withheld, set-aside or escalating card out of later pulls, including a refused escalation write. */
1248
+ const remember = (answer) => {
1249
+ if (answer.action === 'escalate' || answer.action === 'stop' || answer.action === 'set-aside' || answer.withheld?.length > 0) aside = true;
1250
+ return answer;
1251
+ };
1252
+ // Whether the start was made: for a redo as for a Ready card, only once `start` returns.
1253
+ let claimed = false;
1254
+ let failure = null;
1255
+ let removalFailure = null;
1256
+ let reached;
1257
+ // Whether L2 held the card under this claim. A held card needs no memory, because its hold
1258
+ // closed admission; removing the closer is what lets a later pull claim it again.
1259
+ let held = false;
1260
+ try {
1261
+ placed(await start(claim));
1262
+ claimed = true;
1263
+ if (next.action === 'remove') {
1264
+ if (scope !== undefined && makerAction(next)) scope.memory.actions.add(`${card.number}:${actionIdentity(next)}`);
1265
+ try {
1266
+ await removeDirectories(card.number);
1267
+ } catch (failure) {
1268
+ removalFailure = failure;
1269
+ }
1270
+ next = next.following;
1271
+ if (['dispatch', 'judge', 'continue'].includes(next.action)) {
1272
+ claimed = false;
1273
+ placed(await l2.claimed(card, next));
1274
+ claimed = true;
1275
+ }
1276
+ }
1277
+ const kept = (made) => { reached = made; };
1278
+ if (next.action === 'move') {
1279
+ if (next.to === 'done') await removeDirectories(card.number);
1280
+ placed(await l2.moved(card, next));
1281
+ reached = { card: card.number, ...next };
1282
+ } else if (next.action === 'return') {
1283
+ await l2.returned(card, next);
1284
+ reached = { card: card.number, action: 'return', pull: next.pull };
1285
+ } else if (next.action === 'escalate') {
1286
+ placed(await l2.escalated(card, next));
1287
+ aside = true;
1288
+ reached = { card: card.number, ...next };
1289
+ } else if (['refuse', 'ignore'].includes(next.action)) {
1290
+ aside = true;
1291
+ reached = { card: card.number, ...next };
1292
+ } else {
1293
+ reached = next.action === 'judge'
1294
+ ? { card: card.number, judges: await judges(card, next, (options) => answerFrom(atPull, card, [], options), (ended) => kept({ card: card.number, judges: ended }), remember, placed, scope) }
1295
+ : await attempt(card, next, kept, remember, placed, scope);
1296
+ }
1297
+ } catch (thrown) {
1298
+ failure = thrown;
1299
+ if (makerAction(next) && recordingRefusal(thrown)) defer(scope, card, actionIdentity(next));
1300
+ held = thrown.card === card.number && thrown.decision === 'hold';
1301
+ // A change the board accepted before a later write failed still moved the card.
1302
+ placed(thrown?.column);
1303
+ if (['move', 'return', 'escalate'].includes(next.action)) aside = true;
1304
+ // A stopped card is remembered, a line moved or deleted only at its second stop; a held one is not.
1305
+ if (thrown.card === card.number && Array.isArray(thrown.attemptFailures) && !held) {
1306
+ lineStop = [LINE_MOVED, LINE_DELETED].includes(thrown.attemptFailures.at(-1)?.code);
1307
+ if (!lineStop || setAsides?.lineStopped(card.number)) aside = true;
1308
+ }
1309
+ }
1310
+ if (removalFailure !== null) {
1311
+ failure = failure === null ? removalFailure : new AggregateError([removalFailure, failure], `card #${card.number}'s directory removal and following action failed`);
1312
+ }
1313
+ if (next.action === 'continue' && !held && !lineStop && !(reached?.settled?.status === 'fulfilled' && reached.settled.value !== undefined)) {
1314
+ aside = true;
1315
+ }
1316
+ if (aside) setAsides?.add(card.number);
1317
+ failure = released(release, claim, failure);
1318
+ holds.delete(card.number);
1319
+ if (claimed) await freed();
1320
+ return { reached, failure };
1321
+ };
1322
+
1323
+ /**
1324
+ * One merge claim's work: its start, which records its pull, then its merge in the lane, as the
1325
+ * lane's `merge` says. Its claim is released however it ends, with no `slot.release`, since it
1326
+ * holds no slot, and fires no trigger, since it frees none. Settles on `{ reached, failure }` as
1327
+ * `work` does. The run's `setAsides` sets the card aside, against the compared columns its claim took
1328
+ * or the one the merge's end answered.
1329
+ */
1330
+ const merged = async (claim, setAsides) => {
1331
+ let ended;
1332
+ try {
1333
+ await start(claim);
1334
+ ended = await merge(claim);
1335
+ } catch (failure) {
1336
+ ended = { failure };
1337
+ }
1338
+ // Whatever its merge answered, the card is set aside, so this run's next pull leaves it out.
1339
+ const { number } = claim.card;
1340
+ setAsides?.placed(number, mergeEnds.get(number));
1341
+ setAsides?.add(number);
1342
+ mergeEnds.delete(number);
1343
+ claims.delete(number);
1344
+ return { reached: ended.reached, failure: ended.failure };
1345
+ };
1346
+
1347
+ /**
1348
+ * Fires the pull trigger once: claims as many cards as there are free slots, as `take` says, and
1349
+ * works each. `freed` runs as each claimed card's slot is released, as `work` says, and that
1350
+ * card's work is not over until it settles. `setAsides` is this run's memory of the cards it set
1351
+ * aside, as `setAside` says; without it, a single pull keeps no admission memory.
1352
+ *
1353
+ * It claims no more than `limit` cards where one is given, merges among them, and otherwise as
1354
+ * many as there are free slots, beside every card L2 answered `merge`. Settles once every card it
1355
+ * claimed has been worked, on what each card it claimed answers, in one of these shapes:
1356
+ *
1357
+ * - a card whose maker ran: `{ card, workspace, outcome, settled }`, naming its number, its
1358
+ * workspace's path, the maker's outcome and L2's settle of it, as `attempt` answers them, and
1359
+ * `judges` beside them, each `{ role, outcome }`, where L2 named judges after the settle and
1360
+ * every one dispatched handed back;
1361
+ * - a card pulled for its judges alone: `{ card, judges }`, the judges as `judges` answers them,
1362
+ * with no workspace made and no maker dispatched.
1363
+ * - a card pulled for its merge: `{ card, action: 'merge', pull, head, merge }`, as the lane
1364
+ * answers it, `merge` being what its `merge.end` named.
1365
+ *
1366
+ * A closed admission answers `{ admission, reached: [] }`, with the closers `take` read. A card
1367
+ * that failed before its maker ran answers nothing. A read that fails
1368
+ * rejects with the read's own error, and no card is claimed. A card whose work fails, and a trigger event the
1369
+ * sink refused, are reported in one AggregateError naming how many failed, each failure
1370
+ * unchanged in its `errors`, and carrying as `reached` what every card answered, as the pull
1371
+ * would have settled on them, so no card's outcome is dropped for another's failure. A card for
1372
+ * which L2's judge answer threw is in `reached` with its maker's result and no `judges`. A card
1373
+ * one of whose judges failed to hand back is in `reached` under its number, in the shape its
1374
+ * claim gives it above, its `judges` holding every judge L2 named, in the order L2 named them,
1375
+ * each `{ role, outcome }`, `{ role, failure }` or `{ role, withheld }`, as `judges` hands them to
1376
+ * its `keep`. Its failure, naming the card and each judge that failed to hand back, and why, is
1377
+ * in `errors`, inside an AggregateError beside the refusal where its release event was refused,
1378
+ * as `released` says.
1379
+ */
1380
+ const trigger = async (freed = () => {}, limit = undefined, setAsides, settlePending = () => {}, { taken = () => {}, poll = false, carry = false, memory, drained } = {}) => {
1381
+ await settlePending();
1382
+ const { claims: claimed, failures, admission: closed, notices = [] } = await take(limit, setAsides, poll, memory);
1383
+ taken(claimed.length);
1384
+ // Where admission is open, as after a concurrent `resume`, no closed admission carries the
1385
+ // notices, so each is a failure of this pull and reaches the caller there.
1386
+ if (closed === undefined) failures.push(...notices.map(noticeFailure));
1387
+ for (const { kind, id, issue } of closed?.closers ?? []) {
1388
+ const ended = kind === 'hold' && issue === undefined ? await notify(id) : undefined;
1389
+ if (ended?.failed !== undefined) notices.push({ id, ...ended.failed });
1390
+ failures.push(...(ended?.unrecorded ?? []));
1391
+ }
1392
+ if (claimed.length > 0) idle = false;
1393
+ if (claims.size === 0 && !idle) {
1394
+ idle = true;
1395
+ let recorded = false;
1396
+ try {
1397
+ await settlePending();
1398
+ drains += 1;
1399
+ record('trigger', { trigger: 'drain' });
1400
+ recorded = true;
1401
+ } catch (refusal) {
1402
+ failures.push(refused('the event sink refused to record the drain trigger', refusal));
1403
+ }
1404
+ if (recorded) drained?.();
1405
+ }
1406
+ const worked = await Promise.allSettled(claimed.map((claim) => (claim.next.action === 'merge' ? merged(claim, setAsides) : work(claim, freed, setAsides))));
1407
+ const ended = worked.map((result) => (result.status === 'fulfilled' ? result.value : { failure: result.reason }));
1408
+ failures.push(...ended.filter((each) => each.failure !== null).map((each) => each.failure));
1409
+ const reached = ended.map((each) => each.reached).filter((each) => each !== undefined);
1410
+ for (const [at, each] of ended.entries()) if (each.reached !== undefined) reachedOrder.set(each.reached, claimed[at].order);
1411
+ if (stoppedSigns.length > 0 && claims.size === 0) failures.push(stopped());
1412
+ if (failures.length > 0) {
1413
+ // A closed admission's notices would otherwise go only with the answer this throw replaces.
1414
+ if (closed !== undefined) failures.push(...notices.map(noticeFailure));
1415
+ // A run hands its closers over beside the failures, so `carry` keeps them here.
1416
+ throw Object.assign(new AggregateError(failures, `${failures.length} failures across the ${claimed.length} cards this pull claimed`), { reached, ...(carry && closed !== undefined && { admission: closed }) });
1417
+ }
1418
+ return closed === undefined ? reached : { admission: closed, reached, notices };
1419
+ };
1420
+
1421
+ return {
1422
+ /**
1423
+ * Fires the pull trigger once, as `trigger` says, claiming no more than `limit` cards where one
1424
+ * is given, merges among them, and never more slots than N. A limit that is not a positive whole number is refused,
1425
+ * naming it, before the board is read.
1426
+ */
1427
+ pull: async (limit) => {
1428
+ refuseLimit(limit);
1429
+ return trigger(() => {}, limit);
1430
+ },
1431
+
1432
+ /**
1433
+ * Fires the pull trigger, and fires it again each time a slot this run filled is released, so
1434
+ * a card freeing its slot lets the next pullable card start while the others still run. A slot
1435
+ * freed by a claim move the board refused fires nothing, as `work` says. A stopped card, though
1436
+ * not at a first stop for a line of work moved or deleted, or one whose judges L2 withheld, stays
1437
+ * out of later pulls in this run until its skip ends, as `setAside` says; the next invocation
1438
+ * starts without that memory.
1439
+ *
1440
+ * With no clock trigger declared it ends once every pull it fired has settled, which is once a
1441
+ * pull fired on a freed slot claims nothing and no card it claimed is still being worked. It settles on
1442
+ * what every card its pulls answered, in the shapes `trigger` says. A pull that fails stops no
1443
+ * other, and its cards are carried in its own failure's `reached`. Once the run has ended,
1444
+ * every failed pull is reported in one AggregateError naming how many failed, each pull's own
1445
+ * failure unchanged in its `errors`, and carrying as `reached` what every pull that settled
1446
+ * answered, so no card's outcome is dropped for another pull's failure, and, where a pull read
1447
+ * admission closed, as `admission` what that read answered, so a run that ended on a hold
1448
+ * answers its closer. A closed pull's notices are failures of the run.
1449
+ *
1450
+ * While a clock trigger is declared, whatever its shape, it does not end at the drain, and
1451
+ * as "While a clock trigger keeps `run` up" specifies. It arms the clock
1452
+ * after `run.start`, fires each occurrence as `fireOccurrence` says, and, while it holds
1453
+ * no claim, polls the board every `clock.poll` milliseconds: each poll fires the pull trigger,
1454
+ * and the next fires that long after it settles, unless it claimed a card, which ends the idle
1455
+ * period. Each settled hand-over goes to `handOver` as it settles: a report as `{ report }`, a
1456
+ * firing's failure as `{ failure }`, and, once its pulls have settled, at each drain or where
1457
+ * a pull failed or read admission closed, what settled since the previous hand-over as
1458
+ * `{ settled }`, `{ status, value }` or `{ status, reason }` in the shapes this run ends on
1459
+ * with no clock trigger, a closed admission's value as `pull` answers it; a failure carries as
1460
+ * `reached` every card that settled, its failed pulls' cards among them, and as `admission`
1461
+ * the closers a pull read. It ends only where a
1462
+ * hold's closer could not be saved, or once `stop`, an `AbortSignal`, fires: it then polls and
1463
+ * fires no more, cancels its timer, pulls at no further slot release, and ends once its claims
1464
+ * finish, on what settled since the previous hand-over, in those shapes.
1465
+ *
1466
+ * A start's kill that failed rejects the run with its failure, before `run.start`.
1467
+ */
1468
+ run: async ({ handOver = () => {}, stop } = {}) => {
1469
+ // A trigger of any shape keeps `run` up; this is the one place that decides it.
1470
+ const kept = Object.keys(config.clock?.triggers ?? {}).length > 0;
1471
+ // The run's memory of the cards it set aside, which a firing's recovery moves update too.
1472
+ const setAsides = setAside(kept);
1473
+ await killed();
1474
+ if (stop?.aborted) return [];
1475
+ let clockStopped = false;
1476
+ const ending = () => clockStopped || unsaved !== undefined || stoppedSigns.length > 0 || stop?.aborted === true;
1477
+ const active = () => !ending();
1478
+ const pending = new Map();
1479
+ const clockFailed = (failure) => handOver({ failure });
1480
+ const drain = () => {
1481
+ try { Promise.resolve(drained(handOver)).catch(clockFailed); }
1482
+ catch (failure) { clockFailed(failure); }
1483
+ };
1484
+ const rememberIssue = (firing, issue) => {
1485
+ if (issue !== undefined) firing.issue = Math.max(firing.issue ?? 0, issue);
1486
+ };
1487
+ const clockOutcome = (name, firing, outcome, issue) => {
1488
+ record('trigger.outcome', { name, occurrence: firing.occurrence, outcome, ...(issue === undefined ? {} : { issue }) });
1489
+ pending.delete(name);
1490
+ };
1491
+ const settleReports = () => {
1492
+ for (const [name, firing] of pending) {
1493
+ if (firing.after !== undefined) continue;
1494
+ try { clockOutcome(name, firing, 'abandoned'); }
1495
+ catch (refusal) {
1496
+ clockFailed(refused(`clock trigger ${name} at ${firing.occurrence} stayed pending, because the event sink refused its abandoned outcome`, refusal));
1497
+ }
1498
+ }
1499
+ };
1500
+ const settleFirings = async () => {
1501
+ for (const [name, firing] of pending) {
1502
+ if (ending()) return;
1503
+ try {
1504
+ const template = firing.rearmed ? undefined : config.clock?.triggers?.[name]?.card;
1505
+ const issue = firing.after === undefined ? undefined
1506
+ : await l2.clockCardAfter(name, Date.parse(firing.occurrence), firing.after, template, firing.issue, active, setAsides.placed);
1507
+ rememberIssue(firing, issue);
1508
+ if (ending()) return;
1509
+ clockOutcome(name, firing, issue === undefined ? 'abandoned' : 'card', issue);
1510
+ } catch (failure) {
1511
+ rememberIssue(firing, failure.issue);
1512
+ // A move the board accepted before its record failed still placed the card.
1513
+ setAsides.placed(failure.issue, failure.column);
1514
+ clockFailed(new Error(`clock trigger ${name} at ${firing.occurrence} stayed pending: ${failure.message}`, { cause: failure }));
1515
+ }
1516
+ }
1517
+ };
1518
+ // Pulls can arrive while a firing awaits the forge. Neither scans nor firings may overlap it.
1519
+ let clockWork;
1520
+ const serialized = (act) => {
1521
+ const guarded = () => ending() ? undefined : act();
1522
+ const next = clockWork === undefined ? Promise.resolve(guarded()) : clockWork.then(guarded);
1523
+ const done = next.catch(() => {});
1524
+ clockWork = done;
1525
+ done.then(() => { if (clockWork === done) clockWork = undefined; });
1526
+ return next;
1527
+ };
1528
+ let settlementQueued = false;
1529
+ let settlement;
1530
+ const settlePending = () => {
1531
+ if (ending() || pending.size === 0) return;
1532
+ if (!settlementQueued) {
1533
+ settlementQueued = true;
1534
+ settlement = serialized(async () => {
1535
+ settlementQueued = false;
1536
+ await settleFirings();
1537
+ });
1538
+ }
1539
+ return kept ? undefined : settlement;
1540
+ };
1541
+ /**
1542
+ * The start's read of the record, whatever the clock declares: it arms each declared trigger
1543
+ * and settles each `report` firing found pending, answering each armed trigger's `{ armed,
1544
+ * fired }` for the clock, and the instant the start read the record as `started`.
1545
+ */
1546
+ const starting = () => {
1547
+ const armings = new Map();
1548
+ const started = now();
1549
+ let held;
1550
+ try { held = triggerRecord(readRecord); }
1551
+ catch (failure) {
1552
+ clockFailed(new Error(`no clock trigger arms or fires in this run, because the event record could not be read: ${failure.message}${failure.cause ? `: ${failure.cause.message}` : ''}`, { cause: failure }));
1553
+ return { armings, started };
1554
+ }
1555
+ const fresh = [];
1556
+ for (const [name, { interval, anchor }] of Object.entries(config.clock?.triggers ?? {})) {
1557
+ const was = held.get(name) ?? { fired: -Infinity };
1558
+ if (was.armed === undefined || was.interval !== interval || was.anchor !== anchor) {
1559
+ try { record('trigger.armed', { name, interval, anchor }); }
1560
+ catch (refusal) {
1561
+ clockFailed(refused(`clock trigger ${name} fires nothing in this run, because the event sink refused its arming`, refusal));
1562
+ continue;
1563
+ }
1564
+ fresh.push(name);
1565
+ }
1566
+ armings.set(name, { armed: was.armed, fired: was.fired });
1567
+ }
1568
+ // An arming's instant is its event's `ts`, which the record holds once the sink has written it.
1569
+ if (fresh.length > 0) {
1570
+ let armed;
1571
+ try { armed = triggerRecord(readRecord); } catch { armed = new Map(); }
1572
+ const fallback = now();
1573
+ for (const name of fresh) armings.get(name).armed = armed.get(name)?.armed ?? fallback;
1574
+ }
1575
+ for (const [name, { pending: firing }] of held) if (firing !== undefined) pending.set(name, { ...firing, rearmed: firing.rearmed || fresh.includes(name) });
1576
+ settleReports();
1577
+ return { armings, started };
1578
+ };
1579
+ record('run.start', { concurrency });
1580
+ idle = false;
1581
+ const failures = [];
1582
+ const reached = [];
1583
+ const notices = [];
1584
+ const memory = kept ? undefined : { actions: new Set(), deferred: new Set(), barred: new Set() };
1585
+ let closed;
1586
+ const atStart = starting();
1587
+ // Report catch-ups precede the first pull; a card's I/O releases it to proceed independently.
1588
+ let releasePull;
1589
+ const cardWork = new Promise((resolve) => { releasePull = resolve; });
1590
+ /** One occurrence's firing, answering whether it settled the occurrence. */
1591
+ const fireOccurrence = ({ name, occurrence }) => serialized(async () => {
1592
+ const at = new Date(occurrence).toISOString();
1593
+ const template = config.clock.triggers[name].card;
1594
+ if (template !== undefined || pending.has(name)) {
1595
+ releasePull();
1596
+ if (pending.size > 0) await settleFirings();
1597
+ }
1598
+ if (ending() || pending.has(name)) return false;
1599
+ let after;
1600
+ try { if (template !== undefined) after = await l2.clockCardNumber(); }
1601
+ catch (failure) {
1602
+ clockFailed(new Error(`clock trigger ${name} at ${at} could not read its newest number: ${failure.message}`, { cause: failure }));
1603
+ return false;
1604
+ }
1605
+ if (ending()) return false;
1606
+ try { record('trigger', { trigger: 'clock', name, occurrence: at, ...(after === undefined ? {} : { after }) }); }
1607
+ catch (refusal) {
1608
+ clockFailed(refused(`clock trigger ${name} at ${at} did not start, because the event sink refused its firing start`, refusal));
1609
+ return false;
1610
+ }
1611
+ if (ending()) return false;
1612
+ if (template !== undefined) {
1613
+ const firing = { occurrence: at, after };
1614
+ pending.set(name, firing);
1615
+ try {
1616
+ const issue = await l2.openClockCard(name, occurrence, template, active, setAsides.placed);
1617
+ rememberIssue(firing, issue);
1618
+ if (ending()) return;
1619
+ clockOutcome(name, firing, 'card', issue);
1620
+ } catch (failure) {
1621
+ rememberIssue(firing, failure.issue);
1622
+ // A move the board accepted before its record failed still placed the card.
1623
+ setAsides.placed(failure.issue, failure.column);
1624
+ clockFailed(new Error(`clock trigger ${name} at ${at} stayed pending: ${failure.message}`, { cause: failure }));
1625
+ }
1626
+ return true;
1627
+ }
1628
+ let report;
1629
+ let failure;
1630
+ try { report = deriveReport(state); }
1631
+ catch (thrown) { failure = thrown; }
1632
+ try { record('trigger.outcome', { name, occurrence: at, outcome: failure ? 'failed' : 'job' }); }
1633
+ catch (refusal) {
1634
+ pending.set(name, { occurrence: at });
1635
+ clockFailed(refused(`clock trigger ${name} at ${at} stayed pending, because the event sink refused its outcome`, refusal));
1636
+ return true;
1637
+ }
1638
+ if (failure) clockFailed(new Error(`clock trigger ${name} at ${at}: ${failure.message}`, { cause: failure }));
1639
+ else handOver({ report });
1640
+ return true;
1641
+ });
1642
+ const fire = (polling) => trigger(() => (kept && ending() ? undefined : fire()), undefined, setAsides, settlePending, { ...polling, carry: true, memory, ...(kept && drained !== undefined && { drained: drain }) }).then((each) => {
1643
+ reached.push(...(Array.isArray(each) ? each : each.reached));
1644
+ if (Array.isArray(each)) return;
1645
+ closed = each.admission;
1646
+ // A closed pull's notices are its failures to report, a made write's refused record among
1647
+ // them, so the run passes each on to its caller rather than ending with `reached` alone.
1648
+ if (kept) notices.push(...(each.notices ?? []));
1649
+ else failures.push(...(each.notices ?? []).map(noticeFailure));
1650
+ }, (failure) => {
1651
+ failures.push(failure);
1652
+ // Every failed pull retains the cards it settled beside its failure.
1653
+ reached.push(...(failure.reached ?? []));
1654
+ if (failure.admission !== undefined) closed = failure.admission;
1655
+ });
1656
+ /** What settled since the previous hand-over, which it takes, in the shapes the run ends on. */
1657
+ // Every accumulator is taken whatever the answer, so nothing waits for a later hand-over.
1658
+ const since = () => {
1659
+ const failed = failures.splice(0);
1660
+ const cards = reached.splice(0);
1661
+ if (!kept) cards.sort((one, other) => reachedOrder.get(one) - reachedOrder.get(other));
1662
+ const told = notices.splice(0);
1663
+ const admitted = closed;
1664
+ closed = undefined;
1665
+ if (failed.length > 0) {
1666
+ return { status: 'rejected', reason: Object.assign(new AggregateError(failed, `${failed.length} of the pulls this run fired failed`), { reached: cards, ...(admitted && { admission: admitted }), ...(told.length > 0 && { notices: told }) }) };
1667
+ }
1668
+ return { status: 'fulfilled', value: admitted ? { admission: admitted, reached: cards, notices: told } : cards };
1669
+ };
1670
+ const ended = () => {
1671
+ const { status, value, reason } = since();
1672
+ // With no clock trigger, the failure keeps the empty `reports` and `handoffs` the run has
1673
+ // always answered beside `reached`.
1674
+ if (status === 'rejected') throw kept ? reason : Object.assign(reason, { reports: [], handoffs: [] });
1675
+ return value;
1676
+ };
1677
+ if (!kept) {
1678
+ await fire();
1679
+ return ended();
1680
+ }
1681
+ let finish;
1682
+ const finished = new Promise((resolve) => { finish = resolve; });
1683
+ // The pulls in flight that no slot release fired: the first, and each poll's.
1684
+ let flying = 0;
1685
+ let handed = drains;
1686
+ /** A first or polled pull's end, with all it claimed: hands over, or ends the run. Answers whether `run` goes on. */
1687
+ const settled = () => {
1688
+ flying -= 1;
1689
+ if (ending()) {
1690
+ finish();
1691
+ return false;
1692
+ }
1693
+ if (drains > handed || failures.length > 0 || closed !== undefined || notices.length > 0) {
1694
+ handed = drains;
1695
+ handOver({ settled: since() });
1696
+ }
1697
+ return true;
1698
+ };
1699
+ const pulled = (polling) => {
1700
+ flying += 1;
1701
+ return fire(polling).then(settled);
1702
+ };
1703
+ /** One poll: settles once it has claimed a card, or once it has settled claiming none, answering whether to poll again. */
1704
+ const polled = () => new Promise((resolve) => {
1705
+ let claimed = false;
1706
+ pulled({ poll: true, taken: (count) => {
1707
+ if (count === 0) return;
1708
+ claimed = true;
1709
+ resolve(false);
1710
+ } }).then((going) => {
1711
+ if (!claimed) resolve(going);
1712
+ else if (going) wakes.poll();
1713
+ });
1714
+ });
1715
+ const wakes = clockWakes(config.clock, clock, { fire: fireOccurrence, polled }, atStart);
1716
+ const stopped = () => {
1717
+ clockStopped = true;
1718
+ wakes.stop();
1719
+ if (flying === 0) finish();
1720
+ };
1721
+ try {
1722
+ stop?.addEventListener('abort', stopped, { once: true });
1723
+ if (stop?.aborted) stopped();
1724
+ await Promise.race([wakes.started, cardWork]);
1725
+ if (!ending()) pulled().then((going) => { if (going) wakes.poll(); });
1726
+ await wakes.started;
1727
+ await finished;
1728
+ } finally {
1729
+ clockStopped = true;
1730
+ stop?.removeEventListener('abort', stopped);
1731
+ const stopping = wakes.stop();
1732
+ await clockWork;
1733
+ await stopping;
1734
+ }
1735
+ return ended();
1736
+ },
1737
+ };
1738
+ }