@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,456 @@
1
+ // ABOUTME: L2's next action for a ready card, or an unclaimed Coding, Review or Owner card: ignore
2
+ // it, refuse it with a reason, dispatch it under the one kind that selects it, or answer it from
3
+ // its pull request's markers, from what the forge holds of its line of work where L2's facts call
4
+ // read it. Within an attempt at it: the next provisioning step it selected, the maker as a role,
5
+ // the card attempted again, held, stopped, or escalated.
6
+
7
+ import { FIXED_LABELS, OWNER, judgeRole, roleTimeout, sameLabel, stepTimeout, workRequires, worktreeTopic } from '../config/validate.mjs';
8
+ import { BRANCH_ELSEWHERE, BRANCH_REFUSED, FETCH_FAILED, LINE_DELETED, LINE_MOVED, ROOT_NOT_ABSOLUTE, SCRATCH_REFUSED, WORKSPACE_NOT_MADE, WORKSPACE_REFUSED, topicFor } from '../execution/workspace.mjs';
9
+ import { NOT_STARTED } from '../substrate/process.mjs';
10
+ import { escalationDestination, escalationInstruction } from './escalation.mjs';
11
+ import { acceptanceItems, checkAcceptanceForm } from './form-check.mjs';
12
+ import { reviewAnswer, settledJudge } from './judges.mjs';
13
+ import { evidenceDigest } from './marker.mjs';
14
+ import { preparedJudge } from './judges.mjs';
15
+
16
+ /** Whether a card carries `label`, reading label names as GitHub does, whatever their letter case. */
17
+ const carries = (card, label) => card.labels.some((held) => sameLabel(held, label));
18
+
19
+ /** A loop-raised escalate answer with the destination L2's one function answers, reading no comment. */
20
+ const routed = (answer) => answer.action === 'escalate'
21
+ ? { ...answer, destination: escalationDestination({ category: answer.category, raiser: answer.raiser }) }
22
+ : answer;
23
+
24
+ /** The escalation status of an already-read board item, without reading its workflow facts. */
25
+ export const escalationStatus = (card) => carries(card, FIXED_LABELS.escalated) ? { escalated: true } : undefined;
26
+
27
+ /** The maker action selected by L2, before L3 allocates any dispatch id. */
28
+ export const actionIdentity = (answer) => JSON.stringify(answer);
29
+
30
+ /** Whether the selected action, including removal's following action, starts a maker. */
31
+ export const makerAction = (answer) => ['dispatch', 'continue'].includes((answer.action === 'remove' ? answer.following : answer).action);
32
+
33
+ /** L2's recording refusal halts the selected action, retaining the sink's original failure. */
34
+ export const recordingHalt = (message, cause) => Object.assign(new Error(message, { cause }), { halt: true });
35
+
36
+ /**
37
+ * The names of the kinds that select a card, in the config's order: each kind any one of whose
38
+ * `select.labels` the card carries (the owner's 1-A ruling). A kind whose labels are not a list of
39
+ * one or more label names is refused by the config validator, so every kind read here holds one.
40
+ */
41
+ const selecting = (card, kinds) =>
42
+ Object.entries(kinds)
43
+ .filter(([, kind]) => kind.select.labels.some((label) => carries(card, label)))
44
+ .map(([name]) => name);
45
+
46
+ /**
47
+ * The next action for a card, which is `{ number, title, body, labels }` as the forge holds
48
+ * it, under a config's `kinds` and its `epicLabel`. A card carrying the epic label is selected by
49
+ * no kind, whatever else it carries, and an absent `epicLabel` marks no card an epic. A card no
50
+ * kind selects is `{ action: 'ignore' }`, and never a refusal (`R-SCHED-11`). A card more than
51
+ * one kind selects is refused naming every one of them, in the config's order (the owner's U15
52
+ * ruling). A card the form check refuses is refused with the form check's reason. Otherwise it is
53
+ * `{ action: 'dispatch', kind }`. A refusal is `{ action: 'refuse', card, reason }`, naming the
54
+ * card's number.
55
+ *
56
+ * A card L2's facts call handed on with its `forge` facts is answered from them, as `fromTheForge`
57
+ * says, once a kind selects it and before the form check: refused for what the forge holds of its
58
+ * line of work, moved to Done, left to be dispatched, or, for a Review or Owner card with one open
59
+ * pull request from its line of work, and a Coding card with one, answered by L2's review loop, as
60
+ * `reviewAnswer` answers it under `roles`, `provisioning` and `sink`, handed `judged`, the outcomes
61
+ * of each judge's steps by role, and `directories`, the outcome of L1's make of each judge's
62
+ * directory by role, where L1 could not make it. `forge`, where given, is the facts L2's settle answered for a card it moved to review,
63
+ * which L3 hands back unread, and L2 answers the card from them as from the facts call's (the
64
+ * architect's ruling 3, AQ4, on #467). A card handed on with none is answered as if the forge held
65
+ * nothing L2 reads. Handed `roles`, a config's roles by name, L2 refuses a card whose
66
+ * labels select two tiers (`R-LOOP-13`) or two providers (`R-LOOP-16`) for its kind's maker,
67
+ * naming the role and each label, and
68
+ * where it would also refuse the card for what the forge holds, for its acceptance's form, or for
69
+ * both, the one refusal names each of those reasons too.
70
+ *
71
+ * An actually selected forge refusal becomes an ambiguous escalation; composed
72
+ * tier/provider conflicts and form or kind refusals remain refusals. An eligible closed card is
73
+ * answered `{ action: 'remove', following }`, carrying that answer. Removal is selected between
74
+ * attempts, never while L3 is handing back the current attempt's outcomes.
75
+ * An item carrying the fixed status label has no card action, regardless of its other facts.
76
+ *
77
+ * Whether a verdict covers a Coding or Review card is read from its pull request's markers, never
78
+ * injected: L2 takes no `fresh` input.
79
+ *
80
+ * `continuing` is L2's continuing-attempt answer for the card, `{ action: 'continue', pull, head,
81
+ * markers }`, which L3 hands back unread within that attempt. With it, L2 answers within the attempt
82
+ * as below, and its maker answer is the continuing one `makerAnswer` composes.
83
+ *
84
+ * Handed `provisioning`, a config's provisioning steps by name, L2 answers within an attempt at the
85
+ * card, from `outcomes`, the outcomes L3 has handed it of the attempt's steps so far, none by
86
+ * default, as `within` says. `sink` is L5's, through which L2 records an optional step's failure,
87
+ * and an attempt's failure with what follows it. `attempt` is the attempt's number, 1 by default,
88
+ * which L3 hands L2 with each outcome, so L2 keeps no count of its own (the architect's ruling 1,
89
+ * A1). `workspace` is the outcome of L1's making the attempt's workspace, where L1 could not make it.
90
+ * `maker` is L1's maker outcome, handed unread by L3 after L2's settle. Where its dispatch never
91
+ * started, L2 records an environment attempt failure and answers another attempt, hold or stop. For
92
+ * any other outcome, L2 answers `settled`, ending the attempt as L2's column changes settled it.
93
+ * Without `provisioning`, a maker outcome or `continuing`, L2 answers as above, whatever `outcomes`,
94
+ * `sink`, `attempt` and `workspace` are (the architect's ruling 6, Q-D, on #423). A maker outcome
95
+ * is classified even without `provisioning`. Its maker answer is the role
96
+ * `makerAnswer` composes from `roles`, under `topic`, the rule naming the card's line of work, the
97
+ * default rule where none is given.
98
+ */
99
+ export function nextAction(given, kinds, epicLabel, { roles, topic = worktreeTopic(), provisioning, outcomes = [], sink, attempt = 1, firstFailure, workspace, maker, forge, judged, directories, continuing, judgeSettled, judgeDispatch } = {}) {
100
+ if (judgeSettled !== undefined) return routed(settledJudge(given, judgeSettled, sink));
101
+ // The facts L2's settle answered are of a card it moved to review.
102
+ const card = forge === undefined ? given : { ...given, forge: { stage: 'review', ...forge } };
103
+ if (carries(card, FIXED_LABELS.status)) return { action: 'ignore' };
104
+ const escalation = escalationStatus(card);
105
+ if (escalation !== undefined && !(card.forge?.merged?.length > 0)) return { action: 'ignore', ...escalation };
106
+ if (judgeDispatch !== undefined) return routed(preparedJudge(card, kinds, epicLabel, judgeDispatch, { roles, provisioning, sink }));
107
+ const betweenAttempts = continuing === undefined && forge === undefined && maker === undefined
108
+ && !(provisioning !== undefined && (attempt !== 1 || workspace !== undefined || outcomes.length > 0));
109
+ /** Carries the ordinary answer through an eligible closed-card removal, preserving its origin. */
110
+ const removing = (ordinary, forgeRefusal = false) => {
111
+ const facts = card.forge;
112
+ const following = forgeRefusal && escalation === undefined
113
+ ? routed({ action: 'escalate', class: 'card-local', category: 'ambiguous', raiser: 'loop', reason: ordinary.reason, line: facts.line })
114
+ : ordinary;
115
+ if (!betweenAttempts || ordinary.action === 'ignore' || escalation !== undefined
116
+ || !['review', 'owner'].includes(facts?.stage) || facts.closed.length === 0
117
+ || facts.open.length > 0 || facts.merged.length > 0) return following;
118
+ if (makerAction(following)) {
119
+ const closed = facts.closed.map(({ number, head }) => ({ number, head })).sort((one, other) => one.number - other.number || one.head.localeCompare(other.head));
120
+ return { action: 'remove', closed, following };
121
+ }
122
+ return { action: 'remove', following };
123
+ };
124
+ const { kind, answer } = kindOf(card, kinds, epicLabel);
125
+ if (answer !== undefined) return removing(escalation === undefined ? answer : { ...answer, ...escalation });
126
+ if (continuing !== undefined) {
127
+ const tier = roles === undefined ? undefined : tierOf(card, kinds[kind].maker, roles[kinds[kind].maker]);
128
+ return within(card, kind, kinds[kind], { roles, tier: tier?.tier, topic, provisioning: provisioning ?? {}, outcomes, sink, attempt, firstFailure, workspace, maker, continuing });
129
+ }
130
+ const held = card.forge === undefined ? undefined : fromTheForge(card);
131
+ if (held?.action === 'ignore' || held?.action === 'move') return escalation === undefined ? held : { ...held, ...escalation };
132
+ if (held?.action === 'judge') return routed(reviewAnswer(card, kinds, epicLabel, { roles, provisioning, sink, outcomes: judged, directories }));
133
+ const form = checkAcceptanceForm(card);
134
+ const makerRole = kinds[kind].maker;
135
+ const tier = roles === undefined ? undefined : tierOf(card, makerRole, roles[makerRole]);
136
+ const provider = roles === undefined ? undefined : providerOf(card, makerRole, roles[makerRole]);
137
+ const conflicts = [tier?.conflict, provider?.conflict].filter((conflict) => conflict !== undefined);
138
+ // Without a tier or provider conflict, what the forge holds is refused before the acceptance's
139
+ // form, as at the base. With one, no reason replaces another, so the one refusal names every
140
+ // reason that applies (`R-LOOP-13`, `R-LOOP-16`, `R-WORK-19`; the amended acceptance of #484).
141
+ const reasons = conflicts.length === 0
142
+ ? [held?.reason ?? (form.admitted ? undefined : form.reason)]
143
+ : [...conflicts, held?.reason, form.admitted ? undefined : form.reason];
144
+ const named = reasons.filter((reason) => reason !== undefined);
145
+ if (named.length > 0) return removing({ action: 'refuse', card: card.number, reason: named.join('; and '), ...escalation }, conflicts.length === 0 && held?.action === 'refuse');
146
+ if (provisioning === undefined && maker === undefined) return removing({ action: 'dispatch', kind });
147
+ return removing(within(card, kind, kinds[kind], { roles, tier: tier?.tier, topic, provisioning: provisioning ?? {}, outcomes, sink, attempt, firstFailure, workspace, maker }));
148
+ }
149
+
150
+ /**
151
+ * The kind that selects `card` under `kinds` and `epicLabel`, as `{ kind }`, its name, or as
152
+ * `{ answer }`, what L2 answers for a card no kind selects or more than one does, as `nextAction`
153
+ * says.
154
+ */
155
+ export function kindOf(card, kinds, epicLabel) {
156
+ const names = carries(card, epicLabel) ? [] : selecting(card, kinds);
157
+ if (names.length === 0) return { answer: { action: 'ignore' } };
158
+ if (names.length > 1) return { answer: { action: 'refuse', card: card.number, reason: `selected by more than one kind: ${names.join(', ')}` } };
159
+ return { kind: names[0] };
160
+ }
161
+
162
+ /** Pull requests by number, as a refusal names them. */
163
+ const numbered = (pulls) => pulls.map((pull) => `#${pull.number}`).join(', ');
164
+
165
+ /**
166
+ * What L2 answers for `card` from what the forge holds of its line of work, its `forge` facts as
167
+ * L2's facts call read them, or nothing where those facts leave the card to be dispatched.
168
+ *
169
+ * A merged pull request from the line of work moves a Review or Owner card to Done, whoever merged
170
+ * it (the architect's r2 ruling 5 on #642), and refuses a Ready or Coding card, naming the pull
171
+ * request. The line of work itself refuses a Ready or Coding card, naming it: its work would start
172
+ * again from the beginning over what was pushed (`R-WORK-19`; the owner's O6 on #467). A Review or
173
+ * Owner card with one open pull request, and a Coding card with one, is answered `{ action:
174
+ * 'judge' }`, which `nextAction` answers by L2's review loop, and a Review or Owner card with more
175
+ * is refused, naming each. A Review card whose line of work is on the forge with no pull request
176
+ * from it is refused, naming the line of work, and a Review card the forge holds nothing for is
177
+ * done again from the beginning (`R-WORK-24`). An Owner card with no pull request is refused,
178
+ * naming its line of work where the forge holds it and saying it holds none otherwise.
179
+ */
180
+ function fromTheForge(card) {
181
+ const { stage, line, branch, open, merged } = card.forge;
182
+ const refuse = (reason) => ({ action: 'refuse', card: card.number, reason });
183
+ if (merged.length > 0 && ['review', 'owner'].includes(stage)) return { action: 'move', to: 'done' };
184
+ if (merged.length > 0) return refuse(`the forge holds pull request ${numbered(merged)}, merged from its line of work ${line}`);
185
+ if (['review', 'owner'].includes(stage) || (stage === 'coding' && open.length === 1)) {
186
+ if (open.length === 1) return { action: 'judge' };
187
+ if (open.length > 1) return refuse(`the forge holds more than one open pull request from its line of work ${line}: ${numbered(open)}`);
188
+ }
189
+ if (stage === 'owner') return refuse(branch ? `the forge holds its line of work ${line} with no pull request from it` : `the forge holds no pull request from its line of work ${line}, open or merged`);
190
+ if (branch || open.length > 0) return refuse(`the forge holds its line of work, ${line}, so its work would not start from the beginning`);
191
+ return undefined;
192
+ }
193
+
194
+ /**
195
+ * What L2 answers within an attempt at `card` under the kind named `kind`, declared as `declared`, once L3 has handed it `outcomes`, the
196
+ * outcomes of the attempt's steps so far, in order: `{ step }`, the next step it selected, with
197
+ * its name and what L1 runs; `{ maker }`, the kind's maker as a role answer, running at `tier`,
198
+ * once every selected step has an outcome and no required one failed; or, for a required step that failed, or a `workspace` L1
199
+ * could not make, or a maker outcome rejected with `NOT_STARTED`, the card attempted again, held
200
+ * or stopped, as `failedAttempt` says. Any other maker outcome is answered `settled` to end the attempt.
201
+ *
202
+ * An optional step's failure is recorded through `sink` as an L2 `step.failed` event under the card,
203
+ * and the attempt goes on (`R-PROV-2`). L3 asks again after each outcome, so only the newest
204
+ * outcome's failure is recorded, and each is recorded once. A sink that refuses it has L2 answer
205
+ * no action, naming the card, the step and the refusal.
206
+ */
207
+ function within(card, kind, declared, { roles, tier, topic, provisioning, outcomes, sink, attempt, firstFailure, workspace, maker, continuing }) {
208
+ if (workspace !== undefined) return failedAttempt(card, attempt, firstFailure, unmade(workspace, card), sink);
209
+ if (maker !== undefined) {
210
+ if (maker?.status === 'rejected' && [NOT_STARTED, SCRATCH_REFUSED].includes(maker.reason?.code)) {
211
+ return failedAttempt(card, attempt, firstFailure, { maker: declared.maker, status: maker.status, code: maker.reason.code, reason: maker.reason.message, ...dispatchOf(maker) }, sink);
212
+ }
213
+ return { action: 'settled' };
214
+ }
215
+ const steps = selectedSteps(card, declared, provisioning);
216
+ if (outcomes.length > steps.length) {
217
+ throw new Error(`card #${card.number} has ${outcomes.length} outcome(s) and L2 selected ${steps.length} step(s) for it, so L2 answers no action`);
218
+ }
219
+ for (const [at, outcome] of outcomes.entries()) {
220
+ const name = steps[at];
221
+ const failure = failed(outcome, provisioning[name], card, name);
222
+ if (failure === undefined) continue;
223
+ if (workRequires(provisioning[name])) return failedAttempt(card, attempt, firstFailure, { step: name, ...failure, ...dispatchOf(outcome) }, sink);
224
+ if (at === outcomes.length - 1) {
225
+ try {
226
+ sink.emitter({ layer: 'L2', card: card.number }).emit('step.failed', { step: name, ...failure, optional: true });
227
+ } catch (refusal) {
228
+ throw recordingHalt(`card #${card.number}'s optional step \`${name}\` failed, and the event sink refused to record it, so L2 answers no action: ${refusal.message}`, refusal);
229
+ }
230
+ }
231
+ }
232
+ if (outcomes.length === steps.length) return { action: 'dispatch', kind, maker: makerAnswer(card, declared.maker, roles?.[declared.maker] ?? {}, tier, topicFor(topic, card.number), continuing) };
233
+ return { action: 'dispatch', kind, step: stepAnswer(steps[outcomes.length], provisioning) };
234
+ }
235
+
236
+ /** The dispatch id L3 tagged `outcome` with, as a failure carries it, so a hold's notice names it; none where it carries none. */
237
+ const dispatchOf = (outcome) => (outcome?.dispatch === undefined ? {} : { dispatch: outcome.dispatch });
238
+
239
+ /** L2's answer for the provisioning step named `name`: its name, and what L1 runs, as `provisioning` declares it. */
240
+ export function stepAnswer(name, provisioning) {
241
+ const { run, cwd, timeout } = provisioning[name];
242
+ return { name, run, ...(cwd === undefined ? {} : { cwd }), ...(timeout === undefined ? {} : { timeout }) };
243
+ }
244
+
245
+ /** How many times L2 has a card attempted before it stops it: the first attempt and one more (`R-FAIL-2`). */
246
+ const ATTEMPTS = 2;
247
+
248
+ /** Whether two failures L1 reported as environment failures are the same R-FAIL-6 host way. */
249
+ function sameWay(first, second) {
250
+ if (first?.class !== 'environment' || second.class !== 'environment') return false;
251
+ if (first.judge !== undefined || second.judge !== undefined) return first.judge === second.judge && first.row === second.row && ['provider', 'file', 'path', 'variable'].every((key) => first[key] === second[key]);
252
+ if (first.workspace !== undefined || second.workspace !== undefined) return first.workspace !== undefined && second.workspace !== undefined && first.code === second.code;
253
+ if (first.maker !== undefined || second.maker !== undefined) return first.maker !== undefined && second.maker !== undefined;
254
+ if (first.step === undefined || second.step === undefined || first.step !== second.step) return false;
255
+ const neverStarted = (failure) => failure.reason !== undefined;
256
+ return neverStarted(first) === neverStarted(second);
257
+ }
258
+
259
+ /**
260
+ * What L2 answers for `card`'s attempt numbered `attempt`, which failed before its maker ran as `what`
261
+ * says, once it has recorded the failure and its decision through `sink`. A card-local refusal
262
+ * answers `escalate`, as ambiguous with raiser `loop`, naming every refusal in the attempt pair.
263
+ * Its `from` names Coding, where the claimed attempt runs. An environment attempt before the last is followed
264
+ * by `{ action: 'again', card, attempt, failure }`, naming the attempt to make next. The last is
265
+ * `{ action: 'hold', card, firstFailure, failure }` when both failures are the same R-FAIL-6 host
266
+ * way; otherwise it is `{ action: 'stop', card, failure }`.
267
+ *
268
+ * L2 records an `attempt.failed` event under the card, naming the attempt, what failed and why,
269
+ * and the failure's class, then an `attempt.decided` event naming the attempt and whether the card
270
+ * is attempted `again`, held, stopped or escalated. A sink that refuses either has L2 answer no action, naming the
271
+ * card, the attempt and the refusal: the refusal is the halt, and spends no attempt.
272
+ */
273
+ export function failedAttempt(card, attempt, firstFailure, what, sink) {
274
+ const cardLocal = [WORKSPACE_REFUSED, BRANCH_ELSEWHERE, SCRATCH_REFUSED].includes(what.code);
275
+ const out = [LINE_MOVED, LINE_DELETED, BRANCH_REFUSED, ROOT_NOT_ABSOLUTE].includes(what.code);
276
+ const failure = { class: cardLocal ? 'card-local' : out ? 'out' : 'environment', ...what };
277
+ const refusals = [firstFailure, failure].filter((each) => each?.class === 'card-local');
278
+ const again = refusals.length === 0 && failure.class === 'environment' && attempt < ATTEMPTS;
279
+ if (attempt === ATTEMPTS && firstFailure === undefined) throw new Error(`card #${card.number}'s second attempt failed without its first attempt's failure, so L2 answers no action`);
280
+ const hold = refusals.length === 0 && !again && sameWay(firstFailure, failure);
281
+ const { dispatch, ...recorded } = failure;
282
+ // The sink stamps a dispatch's id itself, so both events use the failure's context.
283
+ const events = sink.emitter({ layer: 'L2', card: card.number, ...(dispatch === undefined ? {} : { dispatch }) });
284
+ try {
285
+ events.emit('attempt.failed', { attempt, ...recorded });
286
+ events.emit('attempt.decided', { attempt, decision: refusals.length > 0 ? 'escalate' : again ? 'again' : hold ? 'hold' : 'stop', ...(hold ? { failures: [firstFailure, failure] } : {}) });
287
+ } catch (refusal) {
288
+ throw recordingHalt(`card #${card.number}'s attempt ${attempt} failed, and the event sink refused to record it, so L2 answers no action: ${refusal.message}`, refusal);
289
+ }
290
+ if (refusals.length > 0) return routed({ action: 'escalate', class: 'card-local', category: 'ambiguous', raiser: 'loop', reason: refusals.map((each) => each.reason).join('\n'), card: card.number, failure, from: 'coding' });
291
+ return again ? { action: 'again', card: card.number, attempt: attempt + 1, failure }
292
+ : hold ? { action: 'hold', card: card.number, firstFailure, failure } : { action: 'stop', card: card.number, failure };
293
+ }
294
+
295
+ /**
296
+ * How L1 failed to make `card`'s workspace, as `outcome`, its rejection, says: the path and why.
297
+ * Any other outcome is no workspace's failure, so L2 answers no action for it, naming the card.
298
+ */
299
+ function unmade(outcome, card) {
300
+ const code = outcome?.reason?.code;
301
+ if (outcome?.status !== 'rejected' || ![WORKSPACE_NOT_MADE, WORKSPACE_REFUSED, BRANCH_ELSEWHERE, LINE_MOVED, LINE_DELETED, FETCH_FAILED, BRANCH_REFUSED, ROOT_NOT_ABSOLUTE].includes(code)) {
302
+ const read = outcome?.status === 'rejected' ? outcome.reason?.message : JSON.stringify(outcome);
303
+ throw new Error(`card #${card.number}'s workspace has an outcome that is not L1's failure to make it, so L2 answers no action for it: ${read}`, { cause: outcome?.reason });
304
+ }
305
+ return { workspace: outcome.reason.path, ...(code === WORKSPACE_NOT_MADE ? {} : { code }), reason: outcome.reason.message };
306
+ }
307
+
308
+ /**
309
+ * How `step`'s `outcome` failed, or nothing where it did not: why a command that never started did
310
+ * not, the time of one its timeout ended, or the exit code of one that exited non-zero.
311
+ *
312
+ * Any other outcome, such as an event the sink refused, is no step's failure. It is the halt,
313
+ * which L3 passes on to its caller, so L2 answers no action for it and names the card and step.
314
+ */
315
+ export function failed(outcome, step, card, name) {
316
+ if (outcome?.status === 'rejected' && outcome.reason?.code === NOT_STARTED) return { reason: outcome.reason.message };
317
+ if (outcome?.status !== 'fulfilled' || !Number.isInteger(outcome.value?.exit)) {
318
+ const read = outcome?.status === 'rejected' ? outcome.reason?.message : JSON.stringify(outcome);
319
+ throw new Error(`card #${card.number}'s step \`${name}\` has an outcome that is neither L1's result nor a command that never started, so L2 answers no action for it: ${read}`, { cause: outcome?.reason });
320
+ }
321
+ const { exit, timedOut } = outcome.value;
322
+ if (timedOut) return { timeout: stepTimeout(step) };
323
+ if (exit !== 0) return { exit };
324
+ return undefined;
325
+ }
326
+
327
+ /**
328
+ * The names of the steps `kind` runs for `card`, in the order the kind lists them: each step the
329
+ * kind lists that selects nothing, or one of whose `select.labels` the card carries.
330
+ */
331
+ export const selectedSteps = (card, kind, provisioning) => (kind.provisioning ?? [])
332
+ .filter((name) => provisioning[name].select?.labels.some((label) => carries(card, label)) ?? true);
333
+
334
+ /**
335
+ * The tier the role named `name`, declared as `role`, runs at for `card`, as `{ tier }`: the tier
336
+ * the labels its `labels` names that the card carries select, or its own `tier` where the card
337
+ * carries none of them (`R-LOOP-12`). Where those labels select more than one tier, it is
338
+ * `{ conflict }`, the refusal's reason, naming the role, as the card's `part`, `maker` or `judge`,
339
+ * and each such label (`R-LOOP-13`).
340
+ */
341
+ export function tierOf(card, name, role, part = 'maker') {
342
+ const { value, conflict } = selected(card, name, role.labels, role.tier, part, 'tiers');
343
+ return conflict === undefined ? { tier: value } : { conflict };
344
+ }
345
+
346
+ /**
347
+ * The provider the role named `name`, declared as `role`, runs on for `card`, as `{ provider }`:
348
+ * the provider the labels its `providerLabels` names that the card carries select, or its own
349
+ * `provider` where the card carries none of them (`R-LOOP-16`). Where those labels select more than
350
+ * one provider, it is `{ conflict }`, the refusal's reason, naming the role, as the card's `part`,
351
+ * and each such label.
352
+ */
353
+ export function providerOf(card, name, role = {}, part = 'maker') {
354
+ const { value, conflict } = selected(card, name, role.providerLabels, role.provider, part, 'providers');
355
+ return conflict === undefined ? { provider: value } : { conflict };
356
+ }
357
+
358
+ /**
359
+ * What the labels `labels` maps that `card` carries select for the role named `name`, or `fallback`
360
+ * where it carries none, as `{ value }`; or, where they select more than one value, `{ conflict }`,
361
+ * naming the role as the card's `part` and each label with the value it selects, `what` naming the
362
+ * values.
363
+ */
364
+ function selected(card, name, labels, fallback, part, what) {
365
+ const selecting = Object.entries(labels ?? {}).filter(([label]) => carries(card, label));
366
+ const values = [...new Set(selecting.map(([, value]) => value))];
367
+ if (values.length > 1) {
368
+ const named = selecting.map(([label, value]) => `${label} (${value})`).join(', ');
369
+ return { conflict: `carries labels selecting different ${what} for its ${part} role \`${name}\`: ${named}` };
370
+ }
371
+ return { value: values[0] ?? fallback };
372
+ }
373
+
374
+ /**
375
+ * The panel function: the judges of `kind`, declared as a config's kind is, that `card` needs, in
376
+ * the kind's order, each with the provider it must run on, from `roles`, a config's roles by name.
377
+ * The owner is `{ role: 'owner' }`, with no provider. An agent judge is `{ role, provider }`: a
378
+ * plain role name runs on its role's provider as `providerOf` answers it, a fixed rule on its
379
+ * provider, and a map on the provider it names for the maker's, as `providerOf` answers that.
380
+ * Where an entry carries a rule, its role's `provider` and `providerLabels` are unread. Where the
381
+ * card's labels select two providers for the maker or for a plain-named judge, it answers one `{
382
+ * conflict }` in place of every entry, naming each role and label (`D24`; `R-LOOP-16`, `R-LOOP-17`).
383
+ * The dispatch, the marker's instruction and the gate all take a judge's provider from it.
384
+ */
385
+ export function panelOf(card, kind, roles = {}) {
386
+ const maker = providerOf(card, kind.maker, roles[kind.maker]);
387
+ const entries = kind.judges.map((entry) => {
388
+ const role = judgeRole(entry);
389
+ if (role === OWNER) return { role };
390
+ if (typeof entry === 'string') {
391
+ const { provider, conflict } = providerOf(card, role, roles[role], 'judge');
392
+ return conflict === undefined ? { role, provider } : { conflict };
393
+ }
394
+ return { role, provider: typeof entry.provider === 'string' ? entry.provider : entry.provider[maker.provider] };
395
+ });
396
+ const conflicts = [maker, ...entries].map((each) => each.conflict).filter((conflict) => conflict !== undefined);
397
+ return conflicts.length > 0 ? [{ conflict: conflicts.join('; and ') }] : entries;
398
+ }
399
+
400
+ /**
401
+ * L2's answer for `card`'s maker, the role named `name` and declared as `role`, running at `tier`
402
+ * on the line of work `line`: its name and agent file as declared, its provider as `providerOf`
403
+ * answers it, its time as
404
+ * `roleTimeout` answers it, the prompt L2 composes, `instruction` and then `evidence`, and
405
+ * `digest`, the evidence digest L1 records at `dispatch.start`.
406
+ *
407
+ * The evidence is the card's number, title and acceptance, read as `R-CARD-12` reads it. The
408
+ * instruction is Rigger's contract with every maker, so no role prompt spends words on it (the M4
409
+ * decomposition's §2.5, on #467). It says Rigger dispatched
410
+ * the session, which a role prompt can condition on. A maker that cannot meet an item receives
411
+ * the escalation note instruction.
412
+ *
413
+ * Handed `continuing`, L2's continuing-attempt answer, the instruction names the open pull request
414
+ * and the head L2 read, and asks for commits pushed to the line of work rather than a pull request
415
+ * opened, and the evidence also holds each marker the answer hands the maker, as `rulings` says.
416
+ */
417
+ function makerAnswer(card, name, role, tier, line, continuing) {
418
+ const { agent } = role;
419
+ const { provider } = providerOf(card, name, role);
420
+ const instruction = [
421
+ `Rigger dispatched this session, unattended, as the maker for card #${card.number}.`,
422
+ `This workspace is on the card's line of work, the branch \`${line}\`.`,
423
+ ...(continuing === undefined
424
+ ? [`Once your work meets every acceptance item below, open a pull request from \`${line}\`.`]
425
+ : [
426
+ `This is a continuing attempt on its open pull request #${continuing.pull}, at head \`${continuing.head}\`.`,
427
+ `Once your work meets every acceptance item and answers every ruling below, push your commits to \`${line}\`, so they reach pull request #${continuing.pull}. Open no other pull request.`,
428
+ ]),
429
+ `Never switch this workspace off \`${line}\`, never detach \`HEAD\`, and never add a worktree inside this workspace.`,
430
+ escalationInstruction(card),
431
+ '',
432
+ '',
433
+ ].join('\n');
434
+ const evidence = [
435
+ `Card #${card.number}: ${card.title}`, '', 'Acceptance:', ...acceptanceItems(card.body).map((item) => `- ${item}`), '',
436
+ ...(continuing === undefined ? [] : [...rulings(continuing), '']),
437
+ ].join('\n');
438
+ return { role: name, agent, provider, tier, timeout: roleTimeout(role), instruction, evidence, digest: evidenceDigest(evidence) };
439
+ }
440
+
441
+ /**
442
+ * The lines of a continuing maker's evidence naming what it answers: each marker `continuing`
443
+ * hands it, by its role and verdict, each unmet item by its ordinal and text, and its `toSound`
444
+ * where it gives one, or, with no marker, the forge's reading of the pull request as conflicting.
445
+ */
446
+ function rulings({ pull, head, markers }) {
447
+ if (markers.length === 0) return [`The forge reads pull request #${pull} as conflicting with its base at head ${head}.`];
448
+ return [
449
+ `Rulings at head ${head}:`,
450
+ ...markers.flatMap(({ role, verdict, unmet, toSound }) => [
451
+ `- ${role}: ${verdict}`,
452
+ ...unmet.map(({ item, text }) => ` - item ${item} unmet: ${text}`),
453
+ ...(toSound === undefined ? [] : [` - to make it sound: ${toSound}`]),
454
+ ]),
455
+ ];
456
+ }