@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,489 @@
1
+ // ABOUTME: The `once` verb: fires one pull through L3's dispatching entry point, which claims one card,
2
+ // has L1 make and provision its workspace and dispatches its maker and then the judges L2 names, and says
3
+ // what the maker and each judge did. It reads the
4
+ // board through L0, moves the card through L2, and records through L5. `run` shares the setup and
5
+ // presenter, handing L3 its run instead of one pull.
6
+
7
+ import { existsSync, lstatSync, realpathSync, writeSync } from 'node:fs';
8
+ import { basename, dirname, join, resolve } from 'node:path';
9
+
10
+ import { OWNER, validate, worktreeTopic } from '../config/validate.mjs';
11
+ import { killRecordedGroups } from '../execution/run.mjs';
12
+ import { escalationDirectoryHandle, judgeDirectoryHandle, removeCardDirectories, workspaceHandle } from '../execution/workspace.mjs';
13
+ import { loop } from '../scheduling/loop.mjs';
14
+ import { readEvents, streamPath } from '../observation/sink.mjs';
15
+ import { failedPushLine } from '../observation/push.mjs';
16
+ import { readSide, repositoryReads } from '../substrate/forge/read.mjs';
17
+ import { NOT_STARTED } from '../substrate/process.mjs';
18
+ import { factsCall } from '../workflow/facts.mjs';
19
+ import { failed, nextAction } from '../workflow/next-action.mjs';
20
+ import { REVIEW_WITHHELD, columnChanges } from '../workflow/transitions.mjs';
21
+ import { CONFIG } from './init.mjs';
22
+ import { PACKAGE, closerLine, outsideText, consumerConfig, gitAnswer, real, sameTree, settled, unreadableAdmission, within } from './doctor.mjs';
23
+ import { refusalLine } from './plan.mjs';
24
+ import { STATE, recording } from './recording.mjs';
25
+ import { reportText } from './report.mjs';
26
+
27
+ /**
28
+ * Writes `text` and a newline to standard output, whole, before it returns, so a signal that ends
29
+ * the process after it never cuts what it wrote (the architect's placement P3 on #1175).
30
+ */
31
+ function standardOutput(text) {
32
+ let rest = Buffer.from(`${text}\n`);
33
+ while (rest.length > 0) rest = rest.subarray(writeSync(1, rest));
34
+ }
35
+
36
+ /**
37
+ * Every failure `failure` holds, an AggregateError opened to the failures inside it, however
38
+ * deep: L3 reports a pull's failures in one, and a card's own in another inside it.
39
+ */
40
+ const failuresIn = (failure) => (failure instanceof AggregateError ? failure.errors.flatMap(failuresIn) : [failure]);
41
+
42
+ /**
43
+ * The reason of a loop-raised escalation L2 answered at a maker's settle, `answer`, on one line:
44
+ * Rigger raised it, so it names no acceptance item (`R-LOOP-20`, `R-LOOP-21`).
45
+ */
46
+ const loopReason = (answer) => answer.reason.replaceAll('\n', ' ');
47
+
48
+ /**
49
+ * What a card's maker did, as the pull answered it for a card that reached its maker: `outcome`,
50
+ * L1's, and `settled`, L2's settle of it, each as `Promise.allSettled` records it. Answers `said`,
51
+ * the outcome as the card's line reads it, `review`, whether L2 moved the card to review, and
52
+ * `failure`, L2's own failure where it was neither a move nor a card left in coding for what the
53
+ * forge holds, such as an event the record refused, which is said whole on a line of its own.
54
+ */
55
+ function makerOutcome({ outcome, settled: settle }) {
56
+ const failure = settle.status === 'rejected' && settle.reason?.code !== REVIEW_WITHHELD ? settle.reason : undefined;
57
+ if (outcome.status === 'rejected') {
58
+ const said = outcome.reason?.code === NOT_STARTED ? 'its maker did not start' : 'its maker\'s dispatch failed';
59
+ return { said: `${said}: ${outcome.reason?.message}`, review: false, failure };
60
+ }
61
+ const { exit } = outcome.value;
62
+ if (exit !== 0 || failure !== undefined) return { said: `its maker exited ${exit}`, review: false, failure };
63
+ if (settle.status === 'fulfilled' && settle.value?.action === 'escalate' && settle.value.raiser === 'loop') return { said: `Rigger escalated it as ${settle.value.category}: ${loopReason(settle.value)}`, review: false };
64
+ if (settle.status === 'fulfilled' && settle.value?.action === 'escalate') return { said: `its maker raised ${settle.value.category} for acceptance item ${settle.value.item}`, review: false };
65
+ if (settle.status === 'fulfilled') {
66
+ const { line, open: [pull] } = settle.value;
67
+ return { said: `its maker exited 0 and pull request #${pull.number} is open from ${line}, so the card is in review`, review: true };
68
+ }
69
+ if (settle.reason.facts === undefined || settle.reason.facts.open.length === 1) {
70
+ return { said: settle.reason.message, review: false };
71
+ }
72
+ const { line, open } = settle.reason.facts;
73
+ if (open.length === 0) return { said: `its maker exited 0 and opened no pull request from ${line}`, review: false };
74
+ return { said: `its maker exited 0, and the forge holds more than one open pull request from ${line}: ${open.map((pull) => `#${pull.number}`).join(', ')}`, review: false };
75
+ }
76
+
77
+ /**
78
+ * What a card's merge of pull request `pull` did, as the lane's `merge.end` named it in
79
+ * `merge`: `said`, the line's words, and `review`, whether the pull request is merged, the one
80
+ * outcome this verb meets in full. Any other leaves the card for a later invocation, short of it.
81
+ */
82
+ function mergeOutcome({ pull, merge }) {
83
+ if (['merged', 'already merged'].includes(merge.outcome)) return { said: `${merge.outcome} pull request #${pull}`, review: true };
84
+ const why = [merge.outcome, merge.reason, merge.context, merge.action].filter((each) => each !== undefined).join(', ');
85
+ return { said: `did not merge pull request #${pull}: ${why}`, review: false };
86
+ }
87
+
88
+ /**
89
+ * What a judge's `outcome`, L1's as `Promise.allSettled` records it, says on the judge's line, for
90
+ * a judge whose time is `timeout` milliseconds, and `passed`, whether the judge exited 0 in its time.
91
+ */
92
+ function judgeOutcome(outcome, timeout) {
93
+ if (outcome.status === 'rejected') {
94
+ const said = outcome.reason?.code === NOT_STARTED ? 'did not start' : 'was dispatched, and its dispatch failed';
95
+ return { said: `${said}: ${outcome.reason?.message}`, passed: false };
96
+ }
97
+ const { exit, timedOut } = outcome.value;
98
+ if (timedOut) return { said: `ran past its time, ${timeout} ms, and was ended`, passed: false };
99
+ return { said: `exited ${exit}`, passed: exit === 0 };
100
+ }
101
+
102
+ /** How a step failed, as L2's `failed` answers it, in the words a judge's line says it in. */
103
+ const stepFailure = ({ reason, timeout, exit }) => {
104
+ if (reason !== undefined) return `it did not start: ${reason}`;
105
+ if (timeout !== undefined) return `it ran past its time, ${timeout} ms`;
106
+ return `it exited ${exit}`;
107
+ };
108
+
109
+ /**
110
+ * The absolute worktree root for the config `config` in the repository whose top level is `top`:
111
+ * `worktrees.root` where the config declares one, and otherwise `../<name>-worktrees`, `<name>`
112
+ * being the part of `repo` after the slash, a relative one resolved against `top` (the
113
+ * architect's ruling 3, P3, on #423).
114
+ */
115
+ const worktreeRoot = (config, top) => resolve(top, config.worktrees?.root ?? `../${config.repo.split('/')[1]}-worktrees`);
116
+
117
+ /**
118
+ * The real path of `path`, read with `realpathSync.native`. Where `path` is absent, the real path
119
+ * of its nearest existing parent with the rest taken as written. Any other failure throws: a link
120
+ * whose target is not there is present rather than absent, and a path that cannot be read is
121
+ * refused rather than guessed at, which is where this differs from `real`.
122
+ */
123
+ function strictReal(path) {
124
+ try {
125
+ return realpathSync.native(path);
126
+ } catch (failure) {
127
+ if (failure.code !== 'ENOENT') throw failure;
128
+ try {
129
+ lstatSync(path);
130
+ } catch (absent) {
131
+ if (absent.code !== 'ENOENT' || dirname(path) === path) throw absent;
132
+ return join(strictReal(dirname(path)), basename(path));
133
+ }
134
+ throw failure;
135
+ }
136
+ }
137
+
138
+ /**
139
+ * Why a verb named `verb` refuses the worktree root `root` for the repository whose top level is
140
+ * `top`, or undefined where it does not: the root is that working tree, or the main working tree
141
+ * of the repository where `top` is a linked worktree, or lies inside either, read as real paths.
142
+ * A workspace, a judge's directory or a role's scratch directory there would sit in the tree a
143
+ * maker stages from. A root or a tree whose real path cannot be read is refused too. Git names the
144
+ * main working tree, through L0 with `options` (`gitAnswer`).
145
+ */
146
+ async function rootInsideTree(verb, root, top, options) {
147
+ const { stdout, why } = await gitAnswer(['-C', top, 'worktree', 'list', '--porcelain', '-z'], options);
148
+ if (why !== undefined) return `rigger ${verb}: git could not name the main working tree of ${top} (${why}), so Rigger cannot tell whether the worktree root ${root} lies inside it, and refuses it.`;
149
+ // `-z` ends each field with a NUL, so a path holding a line break is read whole.
150
+ const main = stdout.split('\0')[0].replace(/^worktree /, '');
151
+ let paths;
152
+ try {
153
+ paths = [root, top, main].map(strictReal);
154
+ } catch (failure) {
155
+ return `rigger ${verb}: the real path of the worktree root ${root} cannot be read (${failure.message}), so Rigger cannot tell whether it lies inside the working tree ${top}, and refuses it. Declare a \`worktrees.root\` outside it.`;
156
+ }
157
+ const [there, ...trees] = paths;
158
+ const tree = trees.find((each) => within(each, there));
159
+ if (tree === undefined) return undefined;
160
+ return `rigger ${verb}: the worktree root ${root} lies inside the working tree ${tree}, where every workspace Rigger made would sit in the tree a maker stages from. Declare a \`worktrees.root\` outside it.`;
161
+ }
162
+
163
+ /**
164
+ * The claiming verbs' shared setup and presenter. `once` fires one L3 pull with `limit`;
165
+ * `run` hands L3 its run, which refills freed slots. L3 reads N and the clock declaration from
166
+ * the config. Each hand-over L3 makes is written through `write`, rendered as a whole run,
167
+ * and a report as `report` renders one. `stop`, which the `rigger run` command never passes,
168
+ * is handed to L3's `run`; once that run
169
+ * ends, the verb answers what settled since the last hand-over, with the status picked over every
170
+ * outcome it handed.
171
+ *
172
+ * It records through the sink `recording` opens, in the repository the guard names. L3 is handed
173
+ * L1's kill of the process groups a dead engine recorded in that repository's state directory,
174
+ * and runs it before it records or reads anything, and the state directory, where L1 records each
175
+ * step's group (ruling 10). L3 is handed L1's workspace handle, built over the root the verb
176
+ * resolved, the topic, and the guard's top level as the repository, before `loop` is built (ruling
177
+ * 5, P4; ruling 6, Q-B), and L1's make of a judge's directory over the same three, as
178
+ * `judgeDirectory` (the architect's ruling 4's addendum on #467). `ps` and `readTimeout` stand in for L0's own process-table read and its
179
+ * bound where a test gives them.
180
+ */
181
+ /**
182
+ * The line `verb` prints for hold `id`'s notice that did not finish, from the `failed` L2 returned:
183
+ * a step the forge made, which L2 marks `made`, named as made with each event of it that went
184
+ * unrecorded where there are any, and its cause; otherwise the step the notice failed to take.
185
+ * Both of `claiming`'s
186
+ * paths print it, the closer's `notice` and the pull's `notices` (the architect's placement rulings
187
+ * on #1056).
188
+ */
189
+ export const noticeLine = (verb, id, { step, cause, made, unrecorded }) => (made === undefined
190
+ ? `rigger ${verb}: the notice for hold ${id} failed to ${outsideText(step)}: ${outsideText(cause)}`
191
+ : `rigger ${verb}: the notice for hold ${id} made its step to ${outsideText(step)}${unrecorded === undefined ? '' : `, but the sink refused its record, so these events went unrecorded: ${unrecorded.map(({ event }) => outsideText(event)).join(', ')}`}: ${outsideText(cause)}`);
192
+
193
+ export const claimVerb = async (verb, limit, options) => {
194
+ // A drain can hand over a refusal while recording waits for the normal return's push.
195
+ const handed = {};
196
+ const answer = await recording((opened) => claiming(verb, limit, opened, options, handed), options?.push);
197
+ return { ...answer, code: Math.max(answer.code, handed.code ?? 0) };
198
+ };
199
+
200
+ /**
201
+ * `claimVerb`'s work, recording through the sink `opened` holds once `settled` has named its state
202
+ * directory. It presents a held or stopped card from L3's failure, using the last attempt's failure to
203
+ * choose the wording shared by `once` and `run`.
204
+ */
205
+ async function claiming(verb, limit, opened, {
206
+ target = process.cwd(), packageRoot = PACKAGE, ask, send, host, readTimeout, clock, stop, write = standardOutput, push,
207
+ } = {}, handed) {
208
+ const { named, refusal } = await settled(verb, opened, { target, packageRoot, ask });
209
+ if (refusal) return refusal;
210
+ const { sink } = opened;
211
+ const { config, problem } = await consumerConfig(named);
212
+ if (problem) return { text: `rigger ${verb}: ${problem}`, code: 1 };
213
+ const invalid = validate(config);
214
+ if (invalid.length > 0) return { text: `rigger ${verb}: \`${CONFIG}\`: ${invalid.join('; ')}`, code: 1 };
215
+ opened.admitted(config);
216
+
217
+ const root = worktreeRoot(config, named);
218
+ // The guard reads the resolved root before anything is claimed, as it read the target: a
219
+ // workspace made inside the source tree this Rigger runs from is an agent's to delete it from
220
+ // under the run (the architect's ruling 3, P3, on #423).
221
+ if (sameTree(root, packageRoot)) {
222
+ return {
223
+ text: `rigger ${verb}: the worktree root ${root} and ${real(packageRoot)}, the source tree this Rigger is running from, `
224
+ + 'are one tree, and Rigger never makes a workspace there (`R-SAFE-5`). Declare a `worktrees.root` outside it.',
225
+ code: 1,
226
+ };
227
+ }
228
+ const inside = await rootInsideTree(verb, root, named, { ask, emitter: sink.emitter({ layer: 'L0' }) });
229
+ if (inside !== undefined) return { text: inside, code: 1 };
230
+ let workspace;
231
+ try {
232
+ workspace = await workspaceHandle({ root, topic: worktreeTopic(config), repository: named, sink });
233
+ } catch (failure) {
234
+ return { text: `rigger ${verb}: ${failure.message}`, code: 1 };
235
+ }
236
+ const judgeDirectory = judgeDirectoryHandle({ root, topic: worktreeTopic(config), repository: named, sink });
237
+ const escalationDirectory = escalationDirectoryHandle({ root, topic: worktreeTopic(config), repository: named, sink });
238
+ const workspaceTip = workspace.tip;
239
+ const removeDirectories = (card) => removeCardDirectories({ root, topic: worktreeTopic(config), card, repository: named, sink });
240
+
241
+ const forge = { ...config.board, repo: config.repo };
242
+ const board = readSide(forge, { send, emitter: sink.emitter({ layer: 'L0' }) });
243
+ const cardReads = (card, dispatch) => repositoryReads(forge, { send, emitter: sink.emitter({ layer: 'L0', card, dispatch }) });
244
+ const reads = cardReads();
245
+ const l2 = columnChanges({ config, sink, send, cardReads });
246
+ // L3 answers, as `trigger` says, a card whose maker ran, with its maker's outcome, L2's settle
247
+ // and the judges L2 then named; a card pulled for its judges alone, with those judges; and,
248
+ // where any card failed, a failure carrying both kinds of card as `reached`, a card one of whose
249
+ // judges failed to hand back among them with every judge L2 named, the judges' failure in the
250
+ // failure's errors. A held or stopped card is in the failure alone. It answers nothing about a card
251
+ // that failed before its maker, nor
252
+ // about an unclaimed refusal. Those are seen here through the next action this verb hands L3
253
+ // (the reviewer's ruling on #312). A refusal following closed cleanup is already in reached,
254
+ // so it is presented there once rather than added to these unclaimed refusals.
255
+ // Nor does it answer why a judge L2 stopped naming was not dispatched, which is seen here too.
256
+ // Within an attempt L2 answers from the provisioning steps as well (ruling 6, Q-A), and answers
257
+ // the maker as a role. A maker that never started is handed back to L2 for its retry decision.
258
+ const refusals = [];
259
+ // What L2 last answered of each card's judges, by card: its kind, each judge it named, by role,
260
+ // and why each judge it stopped naming was not dispatched, which L3 does not answer.
261
+ const panels = new Map();
262
+ /** L2's next action, recording refusals and judge wording while forwarding each attempt's outcomes. */
263
+ const decide = (card, outcomes, { attempt, firstFailure, workspace: unmade, maker, forge: settledFacts, judged, directories, continuing, judgeSettled, judgeDispatch } = {}) => {
264
+ const next = nextAction(card, config.kinds, config.epicLabel, {
265
+ roles: config.roles, topic: worktreeTopic(config), provisioning: config.provisioning ?? {}, outcomes, sink, attempt, firstFailure, workspace: unmade, maker, forge: settledFacts, judged, directories, continuing, judgeSettled, judgeDispatch,
266
+ });
267
+ if (next.action === 'refuse') refusals.push(next);
268
+ if (next.action === 'judge') judging(card.number, next, judged ?? {}, directories ?? {});
269
+ if (next.action === 'escalate' && judgeDispatch !== undefined) panels.get(card.number).withheld.set(judgeDispatch.judge.role, `was not dispatched: ${next.reason}`);
270
+ return next;
271
+ };
272
+ /**
273
+ * Keeps L2's judge answer `next` for card `number`, and, for each judge L3 handed outcomes of in
274
+ * `judged` or a directory outcome of in `directories` that the answer no longer names, why it was
275
+ * not dispatched: the required step in its `head` that failed and how, its newest outcome, since
276
+ * L3 asks after each step; or why L1 could not make its directory or its scratch directory.
277
+ */
278
+ const judging = (number, next, judged, directories) => {
279
+ const panel = panels.get(number) ?? { kind: next.kind, named: new Map(), withheld: new Map() };
280
+ panels.set(number, panel);
281
+ for (const judge of next.judges) panel.named.set(judge.role, judge);
282
+ const absent = (role) => !next.judges.some((judge) => judge.role === role);
283
+ for (const [role, outcomes] of Object.entries(judged).filter(([role]) => absent(role))) {
284
+ const { name } = panel.named.get(role).steps[outcomes.length - 1];
285
+ const how = failed(outcomes.at(-1), config.provisioning[name], { number }, name);
286
+ panel.withheld.set(role, `was not dispatched, because its required step \`${name}\` failed in its head: ${stepFailure(how)}`);
287
+ }
288
+ // L2 withholds a judge for a directory outcome that is L1's failure to make its directory, or
289
+ // L1's report that its dispatch did not start for a scratch directory not made (`unmade`).
290
+ for (const [role, outcome] of Object.entries(directories).filter(([role]) => absent(role))) {
291
+ const which = outcome.reason?.code === NOT_STARTED ? 'its scratch directory' : 'its directory';
292
+ panel.withheld.set(role, `was not dispatched, because ${which} could not be made: ${outcome.reason?.message}`);
293
+ }
294
+ };
295
+ const facts = (cards, options) => factsCall({ config, reads: cards.length === 1 ? cardReads(cards[0].number) : reads, decide })(cards, options);
296
+ const state = join(named, STATE);
297
+ const kill = () => killRecordedGroups({ directory: state, sink, host, readTimeout });
298
+ // L3's read of the event record, handed down as the sink is: its events in order, none where no
299
+ // stream exists yet, as `report` reads it, and otherwise what `readEvents` throws. `stream`
300
+ // names the stream, so L3 can name the line it refuses.
301
+ const readRecord = Object.assign(() => (existsSync(streamPath(state)) ? readEvents(state) : []), { stream: streamPath(state) });
302
+ const { project } = config.board;
303
+ // One line for each card that reached its maker, or that was pulled for its judges alone, each
304
+ // followed by a line for each of its judges, then one for each failure of L2's settle that was
305
+ // not the card left in coding for what the forge holds.
306
+ const outcomes = (reached) => reached.map((each) => {
307
+ if (each.action === 'handled') {
308
+ const role = each.escalationRole;
309
+ const review = role.settled?.facts?.open.length === 1;
310
+ const failure = role.outcome.status === 'rejected' ? role.outcome.reason : undefined;
311
+ return { ...each, said: `role \`${role.role}\` handled its escalation; card is in ${review ? 'Review' : 'Coding'}`,
312
+ review, failure, judgesPassed: true, judgeLines: [] };
313
+ }
314
+ if (each.action !== undefined && each.action !== 'continue') {
315
+ const words = {
316
+ move: `moved to ${each.to}`,
317
+ return: `returned acceptance on pull request #${each.pull}`,
318
+ escalate: each.settled?.status === 'fulfilled' && each.settled.value?.action === 'escalate' && each.settled.value.raiser === 'loop'
319
+ ? `escalated ${each.category} by Rigger: ${loopReason(each.settled.value)}`
320
+ : `escalated ${each.category}${each.item === undefined ? '' : ` for acceptance item ${each.item}`}`,
321
+ refuse: `refused: ${each.reason}`,
322
+ };
323
+ if (each.action === 'merge') return { ...each, ...mergeOutcome(each), judgesPassed: true, judgeLines: [] };
324
+ return { ...each, said: words[each.action], review: true, judgesPassed: true, judgeLines: [] };
325
+ }
326
+ return { ...each, ...(each.outcome === undefined ? { said: undefined, review: true } : makerOutcome(each)), ...judgesOf(each) };
327
+ });
328
+ /**
329
+ * What card `reached`'s judges did, as the verb says it: `judgeLines`, a line for each judge L3
330
+ * carried, in the order L3 carried them, then each other judge L2 stopped naming, then, where the
331
+ * card's kind names the owner beside them, that the owner judges last; and `judgesPassed`, whether
332
+ * every judge dispatched exited 0 in its time and none failed to hand back or was withheld. L3
333
+ * carries the judges it dispatched where every one handed back, and every judge L2 named, in the
334
+ * order L2 named them, where one failed to: one that failed is said as L3's failure names it, and
335
+ * one L2 withheld as this verb kept why.
336
+ */
337
+ const judgesOf = ({ card, judges = [] }) => {
338
+ const panel = panels.get(card);
339
+ if (panel === undefined) return { judgeLines: [], judgesPassed: true };
340
+ const line = (role, what) => `rigger ${verb}: card #${card}'s judge \`${role}\` ${what}`;
341
+ const carried = judges.map(({ role, outcome, failure }) => {
342
+ if (outcome !== undefined) {
343
+ const { said: what, passed } = judgeOutcome(outcome, panel.named.get(role)?.timeout);
344
+ return { text: line(role, `${what}${failure === undefined ? '' : `; ${failure.message}`}`), passed: passed && failure === undefined };
345
+ }
346
+ if (failure !== undefined) return { text: `rigger ${verb}: ${failure.message}`, passed: false };
347
+ return { text: line(role, panel.withheld.get(role)), passed: false };
348
+ });
349
+ const withheld = [...panel.withheld].filter(([role]) => !judges.some((judge) => judge.role === role));
350
+ const owner = config.kinds[panel.kind].judges.includes(OWNER) && panel.named.size > 0;
351
+ const judgeLines = [
352
+ ...carried.map(({ text }) => text),
353
+ ...withheld.map(([role, why]) => line(role, why)),
354
+ ...(owner ? [`rigger ${verb}: card #${card}'s judge \`${OWNER}\` judges last, once every agent judge is satisfied, and Rigger never dispatches it`] : []),
355
+ ];
356
+ return { judgeLines, judgesPassed: carried.every(({ passed }) => passed) && withheld.length === 0 };
357
+ };
358
+ const said = (worked) => [
359
+ ...worked.flatMap(({ card, workspace: path, said: what, judgeLines, action, pull, head }) => [
360
+ action !== undefined && action !== 'continue'
361
+ ? `rigger ${verb}: card #${card} ${what}`
362
+ : action === 'continue'
363
+ ? `rigger ${verb}: continued #${card} on pull request #${pull} at ${head}; ${what}, in its workspace, ${path}`
364
+ : what === undefined
365
+ ? `rigger ${verb}: claimed #${card} from board ${project} for its judges alone`
366
+ : `rigger ${verb}: claimed #${card} from board ${project}; ${what}, in its workspace, ${path}`,
367
+ ...judgeLines,
368
+ ]),
369
+ ...worked.filter(({ failure }) => failure !== undefined).map(({ failure }) => `rigger ${verb}: ${failure.message}`),
370
+ ];
371
+ /**
372
+ * Presents L3's failure: an unreadable admission's entries, which L3 carries as `unreadable`, in
373
+ * `unreadableAdmission`'s words, and otherwise the held or stopped wording from its last attempt
374
+ * failure.
375
+ */
376
+ const failureLine = (held) => {
377
+ if (held.notice !== undefined) return noticeLine(verb, held.notice.id, held.notice);
378
+ if (Array.isArray(held.unreadable)) return `rigger ${verb}: ${unreadableAdmission(held.unreadable)}`;
379
+ const attempts = held.attemptFailures;
380
+ if (!Array.isArray(attempts) || attempts.at(-1)?.maker === undefined) return `rigger ${verb}: ${held.message}`;
381
+ const heading = `rigger ${verb}: claimed #${held.card} from board ${project}; its maker did not start: ${attempts.at(-1).reason}, and the card was ${held.decision === 'hold' ? 'held' : 'stopped'} after ${attempts.length} attempts:`;
382
+ return [heading, ...attempts.map((each, at) => `attempt ${at + 1}: ${JSON.stringify(each)}`)].join('\n');
383
+ };
384
+ /**
385
+ * The lines naming each closer a held card's failure among `held` carries, once each however many
386
+ * of its judges held: admission closed by it, in `closerLine`'s words, its notice where that
387
+ * failed, and, where its close left a temporary file, that file, as `pause` says it.
388
+ */
389
+ const holdLines = (held) => [...new Map(held.filter(({ closer }) => closer !== undefined).map(({ closer }) => [closer.name, closer])).values()]
390
+ .flatMap((closer) => [
391
+ `rigger ${verb}: ${closerLine(closer)}`,
392
+ ...(closer.notice ? [noticeLine(verb, closer.id, closer.notice)] : []),
393
+ ...(closer.leftover ? [`rigger ${verb}: the temporary file ${closer.leftover} could not be removed, and the close stands`] : []),
394
+ ]);
395
+ /**
396
+ * The text and status of a whole run whose settle `settled` records, as `Promise.allSettled`
397
+ * records it, naming the refusals met since the last one rendered.
398
+ */
399
+ // Each refusal line a hand-over has written: a clock-held run's idle polls ask L2 again about a
400
+ // card it refuses, and a refusal already written is no news.
401
+ const handedRefusals = new Set();
402
+ /**
403
+ * The refusal lines met since the last render that no hand-over has written, once each. A pull
404
+ * can ask L2 about an unchanged refusal on several pulls, and renders each distinct line once.
405
+ */
406
+ const freshRefusals = () => {
407
+ const lines = refusals.splice(0).map(refusalLine);
408
+ const fresh = [...new Set(lines)].filter((line) => !handedRefusals.has(line));
409
+ for (const line of fresh) handedRefusals.add(line);
410
+ return fresh;
411
+ };
412
+ const rendered = (settled, refused = freshRefusals()) => {
413
+ // Zero only where every card's maker delivered, its card in review; any other outcome is short
414
+ // of what the README promises of this verb, and a zero exit would read to whoever called it as
415
+ // work that was done (the owner's O8 on #423).
416
+ const delivered = (worked) => worked.every(({ review, failure, judgesPassed }) => review && failure === undefined && judgesPassed);
417
+ if (settled.status === 'rejected') {
418
+ const failure = settled.reason;
419
+ // What L3 reports is said whole, one line per failure it holds, and the exit is non-zero:
420
+ // an event the record refused names an action Rigger took and could not record, or a start
421
+ // it did not make, and so does a start's kill that failed, naming each unrecorded kill,
422
+ // unconfirmed group or unreadable record. A card held or stopped after its second attempt names each
423
+ // attempt's failure. Each is loud by the owner's ruling (#277; `ARCHITECTURE.md`, "Failure
424
+ // model"). The record is not used to say so, because the record is what failed. A held or stopped
425
+ // card is named only from its failure, and a held card's closer after the failures, once, in
426
+ // `closerLine`'s words, as `holdLines` says. When its last failure was a maker that never started,
427
+ // the shared presenter puts that reason first; other stops keep L3's wording. The cards the
428
+ // same pull left at their workspaces are named first, as they would be had none failed, a card
429
+ // whose maker ran and whose judges then failed among them. A judge that failed to hand back is
430
+ // said among its card's judge lines, where L3 carried it, and not again after them.
431
+ const reachedCards = failure.reached ?? [];
432
+ const carried = new Set(reachedCards.flatMap(({ judges = [] }) => judges.flatMap(({ failure: held }) => (held === undefined ? [] : [held]))));
433
+ // A clock-held run's hand-over can carry a closed admission beside its failures; each closer
434
+ // the held cards' lines have not already named is said after them.
435
+ const holding = [...failuresIn(failure), ...carried];
436
+ const named = new Set(holding.flatMap(({ closer }) => (closer === undefined ? [] : [closer.id])));
437
+ const closers = failure.admission?.state === 'closed' ? failure.admission.closers.filter(({ id }) => !named.has(id)) : [];
438
+ return {
439
+ text: [...said(outcomes(reachedCards)), ...failuresIn(failure).filter((held) => !carried.has(held)).map(failureLine), ...holdLines(holding), ...closers.map((closer) => `rigger ${verb}: ${closerLine(closer)}`), ...(failure.notices ?? []).map((failed) => noticeLine(verb, failed.id, failed)), ...refused].join('\n'),
440
+ code: 1,
441
+ };
442
+ }
443
+ const reached = settled.value;
444
+ if (reached.admission?.state === 'closed') {
445
+ const notices = (reached.notices ?? []).map((failed) => noticeLine(verb, failed.id, failed));
446
+ // A clock-held run's drain can read admission closed after cards settled; each is said, and
447
+ // counts toward the status, as it would without the closer.
448
+ const worked = outcomes(reached.reached ?? []);
449
+ return {
450
+ text: [...reached.admission.closers.map((closer) => `rigger ${verb}: ${closerLine(closer)}`), ...notices, ...said(worked), ...refused].join('\n'),
451
+ code: notices.length === 0 && delivered(worked) ? 0 : 1,
452
+ };
453
+ }
454
+ // Nothing to pull is the one outcome this verb meets in full, so it alone exits zero (U29).
455
+ if (reached.length === 0) return { text: [`rigger ${verb}: from board ${project}, no card was pullable`, ...refused].join('\n'), code: 0 };
456
+ const worked = outcomes(reached);
457
+ return { text: [...said(worked), ...refused].join('\n'), code: delivered(worked) ? 0 : 1 };
458
+ };
459
+ /** Writes one hand-over of a kept-up `run` as it settles: a report, a firing's failure, or what settled since the last. */
460
+ const handOver = ({ report, failure, push, settled: each }) => {
461
+ if (push !== undefined) {
462
+ write(failedPushLine(push).slice(0, -1));
463
+ return;
464
+ }
465
+ const { text, code } = report !== undefined ? { text: reportText(report), code: 0 }
466
+ : failure !== undefined ? { text: failureLine(failure), code: 1 } : rendered(each);
467
+ handed.code = Math.max(handed.code ?? 0, code);
468
+ write(text);
469
+ };
470
+ // The verb hands L3 the process's own environment, which L3 hands every dispatch it makes
471
+ // (the architect's ruling 2, P7, on #467), and no maker: L3 dispatches it through L1.
472
+ const [settledRun] = await Promise.allSettled([(async () => {
473
+ const drained = push === undefined ? undefined : (handOver) => push({ sink, run: opened.run, config, repository: named, directory: state, handOver });
474
+ const l3 = loop({ config, board, decide, facts, l2, sink, kill, workspace, workspaceTip, judgeDirectory, escalationDirectory, removeDirectories, state, readRecord, environment: process.env, run: opened.run, clock, drained });
475
+ return verb === 'run' ? l3.run({ handOver, stop }) : l3.pull(limit);
476
+ })()]);
477
+ if (handed.code === undefined) return rendered(settledRun);
478
+ // A kept-up run that ended answers only what it had not yet handed over (the architect's ruling 1175#6560236393, (b)).
479
+ const refused = freshRefusals();
480
+ const nothing = settledRun.status === 'fulfilled' && Array.isArray(settledRun.value) && settledRun.value.length === 0 && refused.length === 0;
481
+ const { text, code } = nothing ? { text: '', code: 0 } : rendered(settledRun, refused);
482
+ return { text, code: Math.max(code, handed.code) };
483
+ }
484
+
485
+ /**
486
+ * What the command prints for a `once` run, and the status it exits with. The limit is this
487
+ * verb's own literal: `once` claims one card, whatever N the config declares.
488
+ */
489
+ export const once = (options) => claimVerb('once', 1, options);
@@ -0,0 +1,56 @@
1
+ // ABOUTME: The `pause` verb: a thin caller of L3's admission module, which closes admission as the
2
+ // owner and records it, and then says the closer it added and every closer then present.
3
+
4
+ import { join } from 'node:path';
5
+
6
+ import { admission } from '../scheduling/admission.mjs';
7
+ import { PACKAGE, closerLine, settled } from './doctor.mjs';
8
+ import { STATE, recording } from './recording.mjs';
9
+
10
+ /** The reason every closer `pause` adds names. */
11
+ const OWNER_PAUSE = "the owner's pause";
12
+
13
+ /**
14
+ * The line `pause` prints for closer `closer`: the words `once`, `plan` and `doctor` name a closer
15
+ * in (`closerLine`), then the closer's path (K100 on #740).
16
+ */
17
+ const presentLine = (closer) => `rigger pause: ${closerLine(closer)}; at ${closer.path}`;
18
+
19
+ /** The line verb `verb` prints for an entry it could not read: its path and the cause. */
20
+ const unreadableLine = (verb) => ({ path, cause }) => `rigger ${verb}: unreadable closer ${path} (${cause})`;
21
+
22
+ /**
23
+ * What `rigger pause` prints, and the status it exits with. It resolves the repository and its
24
+ * state directory as `once` does, and reads no `rigger.config.mjs`. `now` is the clock the closer's
25
+ * time is read from, and `fs` the `node:fs` calls the module makes, each a test's to replace.
26
+ */
27
+ export const pause = (options) => recording((opened) => pausing(opened, options));
28
+
29
+ /** `pause`'s work, recording through the sink `opened` holds once `settled` has named its state directory. */
30
+ async function pausing(opened, {
31
+ target = process.cwd(), packageRoot = PACKAGE, ask, now = Date.now, fs,
32
+ } = {}) {
33
+ const { named, refusal } = await settled('pause', opened, { target, packageRoot, ask });
34
+ if (refusal) return refusal;
35
+ const admissionRecord = admission({ directory: join(named, STATE), run: opened.run, now, sink: opened.sink, ...(fs && { fs }) });
36
+ /** Every closer present, and every entry that cannot be read, a line each. */
37
+ const present = () => {
38
+ const state = admissionRecord.read();
39
+ return [...(state.closers ?? []).map(presentLine), ...(state.unreadable ?? []).map(unreadableLine('pause'))];
40
+ };
41
+ let closer;
42
+ try {
43
+ closer = await admissionRecord.close({ kind: 'owner', reason: OWNER_PAUSE });
44
+ } catch (failure) {
45
+ // A refusal after the link leaves the closer standing, so what is present is said either way.
46
+ return { text: [`rigger pause: ${failure.message}`, ...present()].join('\n'), code: 1 };
47
+ }
48
+ return {
49
+ text: [
50
+ `rigger pause: closed admission as the owner at ${closer.path}: ${closer.reason}; time ${closer.time}`,
51
+ ...(closer.leftover ? [`rigger pause: the temporary file ${closer.leftover} could not be removed, and the close stands`] : []),
52
+ ...present(),
53
+ ].join('\n'),
54
+ code: 0,
55
+ };
56
+ }
@@ -0,0 +1,106 @@
1
+ // ABOUTME: The `plan` verb: what the next run would pull from the board, first pulled first, and
2
+ // the cards it refuses, read through L0 and ordered by L2 and L3's own functions. It writes nothing.
3
+
4
+ import { validate } from '../config/validate.mjs';
5
+ import { pullOrder } from '../scheduling/pull-order.mjs';
6
+ import { readSide, repositoryReads } from '../substrate/forge/read.mjs';
7
+ import { factsCall } from '../workflow/facts.mjs';
8
+ import { escalationStatus, nextAction } from '../workflow/next-action.mjs';
9
+ import { CONFIG } from './init.mjs';
10
+ import { PACKAGE, admissionIn, closerLine, consumerConfig, settled, unreadableAdmission } from './doctor.mjs';
11
+ import { recording } from './recording.mjs';
12
+
13
+ /**
14
+ * One line per card: what the run does with it, its number, and the kind or the reason, and for a
15
+ * card pulled for its judges, the judges it would dispatch.
16
+ */
17
+ const pullLine = ({ card, kind, redo, judges, action, to, pull, head, category, reason, following }) => {
18
+ const prefix = ` pull #${card} `;
19
+ const suffix = redo ? ' (redo)' : '';
20
+ if (action === 'remove') return `${prefix}remove directories, then ${pullLine({ card, redo, ...following }).slice(prefix.length)}`;
21
+ if (action === 'refuse') return `${prefix}refuse: ${reason}${suffix}`;
22
+ if (action === 'move') return `${prefix}move to ${to}${suffix}`;
23
+ if (action === 'continue') return `${prefix}continue pull request #${pull} at ${head}${suffix}`;
24
+ if (action === 'return') return `${prefix}return pull request #${pull}${suffix}`;
25
+ if (action === 'escalate') return `${prefix}escalate ${category}${suffix}`;
26
+ if (action === 'merge') return `${prefix}merge pull request #${pull} at ${head}${suffix}`;
27
+ if (judges !== undefined) return ` pull #${card} ${kind} judges ${judges.join(', ')}`;
28
+ return `${prefix}${kind}${suffix}`;
29
+ };
30
+
31
+ /**
32
+ * The sink `plan` hands L2's next action, which records nothing: a judge answer records a diff the
33
+ * forge would not serve, and `plan` writes nothing but what L0 records of a process it kills.
34
+ */
35
+ const UNRECORDED = { emitter: () => ({ emit: () => {} }) };
36
+ /** Exported because `once` names the cards it refuses in this verb's words. */
37
+ export const refusalLine = ({ card, reason }) => ` refuse #${card} ${reason}`;
38
+
39
+ /**
40
+ * What the command prints for a `plan` run, and the status it exits with. It writes nothing but
41
+ * what L0 records of a process it kills, through the sink `recording` opens.
42
+ */
43
+ export const plan = (options) => recording((opened) => planning(opened, options));
44
+
45
+ /** `plan`'s work, recording through the sink `opened` holds once `settled` has named its state directory. */
46
+ async function planning(opened, { target = process.cwd(), packageRoot = PACKAGE, ask, send } = {}) {
47
+ const { named, refusal } = await settled('plan', opened, { target, packageRoot, ask });
48
+ if (refusal) return refusal;
49
+ const { sink } = opened;
50
+ // Admission is read first, so `plan` names its state whatever else it fails to read
51
+ // (`R-SCHED-18`). A closed admission is no failure of the pull and an unreadable one is
52
+ // ("Failure model"), so only the second fails the verb.
53
+ const admission = admissionIn(named, sink);
54
+ let admissionLines = [];
55
+ if (admission.state === 'closed') admissionLines = admission.closers.map((closer) => `rigger plan: ${closerLine(closer)}`);
56
+ if (admission.state === 'unreadable') admissionLines = [`rigger plan: ${unreadableAdmission(admission.unreadable)}`];
57
+ const failed = (said) => ({ text: [said, ...admissionLines].join('\n'), code: 1 });
58
+ const { config, problem } = await consumerConfig(named);
59
+ if (problem) return failed(`rigger plan: ${problem}`);
60
+ const refusals = validate(config);
61
+ if (refusals.length > 0) return failed(`rigger plan: \`${CONFIG}\`: ${refusals.join('; ')}`);
62
+
63
+ const { project } = config.board;
64
+ const forge = { ...config.board, repo: config.repo };
65
+ const side = readSide(forge, { send, emitter: sink.emitter({ layer: 'L0' }) });
66
+ let read;
67
+ try {
68
+ read = { columns: await side.readColumns(), ...(await side.readPriority()) };
69
+ } catch (threw) {
70
+ return failed(`rigger plan: board ${project} could not be read: ${threw.message}`);
71
+ }
72
+ // The same facts call and next action the claiming verbs hand L3, so `plan` refuses each card
73
+ // they would: for what the forge holds of its line of work, and for its maker's or a judge's
74
+ // tier; and names the judges they would dispatch for a Review card.
75
+ const answers = new Map();
76
+ const decide = (card) => {
77
+ const answer = nextAction(card, config.kinds, config.epicLabel, { roles: config.roles, provisioning: config.provisioning ?? {}, sink: UNRECORDED });
78
+ answers.set(card.number, answer);
79
+ return answer;
80
+ };
81
+ let decided;
82
+ try {
83
+ decided = await factsCall({ config, reads: repositoryReads(forge, { send, emitter: sink.emitter({ layer: 'L0' }) }), decide })(read.items);
84
+ } catch (threw) {
85
+ return failed(`rigger plan: ${threw.message}`);
86
+ }
87
+ const order = pullOrder(read, decided);
88
+ // A closed or unreadable admission changes only what the next run would pull: the refusals and
89
+ // the escalated cards are reported in every state, so the owner sees in one run all to fix.
90
+ const pulls = admission.state === 'open' ? order.pulls : [];
91
+ const escalated = read.items.map((card) => [card.number,
92
+ answers.has(card.number) ? answers.get(card.number) : escalationStatus(card)])
93
+ .filter(([, answer]) => answer?.escalated);
94
+ const namedRefusals = order.refusals.filter(({ card }) => !answers.get(card)?.escalated);
95
+
96
+ const counted = (n, what) => `${n} ${what}${n === 1 ? '' : 's'}`;
97
+ const heading = pulls.length === 0
98
+ ? `rigger plan: from board ${project}, nothing would be pulled`
99
+ : `rigger plan: from board ${project}, the next run would pull ${counted(pulls.length, 'card')}, first pulled first`;
100
+ const refused = namedRefusals.length === 0 ? '' : `, and refuses ${counted(namedRefusals.length, 'card')}`;
101
+ return {
102
+ text: [`${heading}${refused}`, ...admissionLines, ...pulls.map(pullLine), ...namedRefusals.map(refusalLine),
103
+ ...escalated.map(([card, answer]) => ` escalated #${card}${answer.reason ? ` ${answer.reason}` : ''}`)].join('\n'),
104
+ code: admission.state === 'unreadable' ? 1 : 0,
105
+ };
106
+ }