@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,695 @@
1
+ // ABOUTME: L2's review loop for a card with one open pull request: its answer from the verdict
2
+ // markers at the pull request's head and acceptance digest, its rounds, the forge's mergeability
3
+ // and the gate rule; and its judge answer, naming the agent judges owed a marker, each with its
4
+ // steps, the evidence they all share, and the instruction asking each for its marker.
5
+
6
+ import { OWNER, judgeRole, roleTimeout, workRequires } from '../config/validate.mjs';
7
+ import { SCRATCH_REFUSED, WORKSPACE_NOT_MADE, WORKSPACE_REFUSED } from '../execution/workspace.mjs';
8
+ import { EFFECTIVE_RULES_UNAVAILABLE } from '../substrate/forge/read.mjs';
9
+ import { NOT_STARTED } from '../substrate/process.mjs';
10
+ import { EVENT_REFUSED } from '../substrate/process.mjs';
11
+ import { acceptanceItems, checkAcceptanceForm } from './form-check.mjs';
12
+ import { GATE_CONTEXT, gateAnswer } from './gate.mjs';
13
+ import { acceptanceDigest, evidenceDigest, markerInstruction, readMarkers, WRITERS } from './marker.mjs';
14
+ import { failed, kindOf, panelOf, selectedSteps, stepAnswer, tierOf } from './next-action.mjs';
15
+ import { failedAttempt, recordingHalt } from './next-action.mjs';
16
+ import { dispatched } from './marker.mjs';
17
+ import { ADAPTERS } from '../substrate/providers/adapters.mjs';
18
+
19
+ /** L2 fills the minted id before preparing the prompt the provider's adapter will receive. */
20
+ export function preparedJudge(card, kinds, epicLabel, { judge, id }, options) {
21
+ const full = dispatched(judge, id);
22
+ const limit = ADAPTERS[judge.provider]?.promptLimit;
23
+ if (limit === undefined || Buffer.byteLength(full.instruction + full.evidence, 'utf8') <= limit) return { action: 'judge', judges: [full] };
24
+ const paths = changedPaths(card.forge.diff.value);
25
+ const diff = `Changed lines were omitted because the prompt exceeded the provider's limit of ${limit} UTF-8 bytes.\nChanged paths:\n${paths.map((path) => JSON.stringify(path)).join('\n')}`;
26
+ const { judges, ...next } = judgeAnswer({ ...card, forge: { ...card.forge, diff: { status: 'fulfilled', value: diff } } }, kinds, epicLabel, options);
27
+ const bounded = dispatched(judges.find((each) => each.role === judge.role), id);
28
+ if (Buffer.byteLength(bounded.instruction + bounded.evidence, 'utf8') > limit) return {
29
+ action: 'escalate', category: 'ambiguous', raiser: 'loop', pull: judge.facts.pull, head: judge.facts.head, from: card.forge.stage,
30
+ reason: `Judge ${judge.role}'s prompt still exceeds its provider's limit of ${limit} UTF-8 bytes with changed paths in place of changed lines.`,
31
+ };
32
+ return { ...next, judges: [bounded] };
33
+ }
34
+
35
+ /** Git quotes control characters and UTF-8 bytes with C escapes; JSON does not read its octal escapes. */
36
+ function gitPath(text) {
37
+ if (!text.startsWith('"')) return text;
38
+ const escaped = { a: 7, b: 8, f: 12, n: 10, r: 13, t: 9, v: 11, '"': 34, '\\': 92 };
39
+ const bytes = [...text.slice(1, -1).matchAll(/\\([0-7]{1,3}|.)|([^\\]+)/g)].map(([, escape, plain]) => plain !== undefined
40
+ ? Buffer.from(plain, 'utf8') : Buffer.from([/^[0-7]/.test(escape) ? parseInt(escape, 8) : escaped[escape]]));
41
+ return Buffer.concat(bytes).toString('utf8');
42
+ }
43
+
44
+ /** Diff metadata names both rename paths and deleted files; binary/mode-only changes need the header. */
45
+ function changedPaths(diff) {
46
+ const paths = new Set();
47
+ for (const block of diff.split(/^diff --git /m).slice(1)) {
48
+ const [header, ...lines] = block.split('\n');
49
+ const metadata = [];
50
+ for (const line of lines) {
51
+ if (/^@@|^GIT binary patch/.test(line)) break;
52
+ const renamed = /^(?:rename|copy) (?:from|to) (.*)$/.exec(line);
53
+ const file = /^(?:---|\+\+\+) (.*?)(?:\t.*)?$/.exec(line);
54
+ if (renamed) metadata.push(gitPath(renamed[1]));
55
+ if (file && file[1] !== '/dev/null') metadata.push(gitPath(file[1]).slice(2));
56
+ }
57
+ if (metadata.length > 0) { for (const path of metadata) paths.add(path); continue; }
58
+ // Unquoted equal paths can themselves contain " b/"; split at the equal halves first.
59
+ const length = (header.length - 5) / 2;
60
+ const same = header.slice(2, 2 + length);
61
+ if (header === `a/${same} b/${same}`) { paths.add(same); continue; }
62
+ const pair = /^("(?:\\.|[^"\\])*"|a\/.*?) ("(?:\\.|[^"\\])*"|b\/.*)$/.exec(header);
63
+ if (pair) for (const path of pair.slice(1)) paths.add(gitPath(path).slice(2));
64
+ }
65
+ return [...paths];
66
+ }
67
+
68
+ /** What each read of a Review card's facts the judge answer uses reads, as its failure names it. */
69
+ const READS = {
70
+ pull: 'the pull request',
71
+ comments: 'the pull request\'s comments',
72
+ mergeable: 'the pull request\'s mergeability',
73
+ rules: 'the base branch\'s effective rules',
74
+ checks: 'the pull request\'s check states',
75
+ };
76
+
77
+ /** The selected judge dispatch, identified by L2's evidence and role selection. */
78
+ export function judgeIdentity({ role, provider, tier, facts, comment }) {
79
+ return JSON.stringify(['judge', facts.pull, facts.head, facts.revision, role, provider, tier, comment]);
80
+ }
81
+
82
+ /**
83
+ * What the read named `read` answered for `card`, from its `forge` facts, each a read's outcome as
84
+ * `Promise.allSettled` records it. A read that failed has L2 name no judge: it answers no action,
85
+ * naming the card, the read and why it failed (reviewer 12 on #467).
86
+ */
87
+ function held(card, read) {
88
+ const outcome = card.forge?.[read];
89
+ if (outcome?.status === 'fulfilled') return outcome.value;
90
+ const why = outcome?.status === 'rejected' ? outcome.reason?.message : `no outcome: ${JSON.stringify(outcome)}`;
91
+ throw new Error(`card #${card.number}'s read of ${READS[read]} failed, so L2 names no judge for it: ${why}`, { cause: outcome?.reason });
92
+ }
93
+
94
+ /**
95
+ * Records the L2 event `name` with `fields` under `card`, and under `dispatch` where one is given,
96
+ * through `sink`. A sink that refuses it has L2 answer no action, naming the card, `what` it was
97
+ * recording and the refusal.
98
+ */
99
+ function record(sink, card, name, fields, what, dispatch) {
100
+ try {
101
+ sink.emitter({ layer: 'L2', card: card.number, ...(dispatch === undefined ? {} : { dispatch }) }).emit(name, fields);
102
+ } catch (refusal) {
103
+ throw recordingHalt(`card #${card.number}'s ${what}, and the event sink refused to record it, so L2 answers no action: ${refusal.message}`, refusal);
104
+ }
105
+ }
106
+
107
+ /** L2 records a started judge's failure after L3 obtains the settle read under its claim. */
108
+ export function settledJudge(card, { judge, outcome, comments, record: history }, sink) {
109
+ if (comments.status !== 'fulfilled') return { action: 'ignore' };
110
+ const { role, facts: { pull, head, revision: digest } } = judge;
111
+ const round = { card: card.number, pull, head, digest, count: acceptanceItems(card.body).length };
112
+ const { governing } = readMarkers(comments.value, round);
113
+ const verdict = governing.get(role);
114
+ const readable = stateOf(verdict, judge.provider) !== 'owed';
115
+ const result = outcome.status === 'fulfilled' ? outcome.value : outcome.reason?.result;
116
+ const failed = result !== undefined && (result.timedOut || !readable);
117
+ if (failed) {
118
+ record(sink, card, 'judge.failed', { role, pull, head, digest,
119
+ outcome: { exit: result.exit, timedOut: result.timedOut ?? false } },
120
+ `judge ${role}'s dispatch failed`, outcome.dispatch);
121
+ }
122
+ if (verdict !== undefined) markerRead(sink, card, { number: pull }, round, role, verdict);
123
+ if (failed && !readable && history?.status === 'fulfilled') {
124
+ const reset = history.value.findLastIndex((event) => event.event === 'review.escalate' || (event.event === 'marker.read' && event.role === role && event.head === head && event.digest === digest
125
+ && event.provider === judge.provider && !event.edited && event.verdict !== null && event.reason === undefined));
126
+ const failures = history.value.slice(reset + 1).filter((event) => event.event === 'judge.failed' && event.role === role && event.head === head && event.digest === digest);
127
+ if (failures.length > 0) return { action: 'escalate', category: 'ambiguous', raiser: 'loop', pull, head,
128
+ reason: `Judge ${role} failed twice at head ${head}, acceptance ${digest}: dispatches ${failures.at(-1).dispatch} and ${outcome.dispatch}.` };
129
+ }
130
+ return { action: 'ignore' };
131
+ }
132
+
133
+ /**
134
+ * L2's judge answer for `card`, a Review card with one open pull request from its line of work,
135
+ * under a config's `kinds` and `epicLabel`, `roles` and `provisioning`, from the `forge` facts L2's
136
+ * facts call holds for it: `pull`, the pull request's `{ number, base, head }`, `base` and `head`
137
+ * its SHAs; `diff`; and `comments`, each in the shape the forge's read answers, `{ body, createdAt,
138
+ * id, author, permission, edited }`. Each is a read's outcome as `Promise.allSettled` records it.
139
+ *
140
+ * A card no kind selects, or more than one does, is answered as `nextAction` answers it. A card
141
+ * whose labels select two tiers for one of its agent judges (`R-LOOP-13`), or two providers for
142
+ * its maker or one of its judges (`R-LOOP-16`), is refused naming the role and each label, and one
143
+ * whose acceptance the form check refuses is refused with its reason, the one refusal naming each
144
+ * that applies. A failed read of the pull request or its comments
145
+ * answers no action, naming the card and the read.
146
+ *
147
+ * It names every agent judge of the card's kind, in the kind's order, that is owed a marker: one
148
+ * whose governing marker at the pull request's head and the card's acceptance digest, as
149
+ * `readMarkers` reads it, is absent, unreadable or edited (the architect's ruling R2 on #642), or
150
+ * names no provider or another than the one the panel function requires of it (`D24` rule 2). The
151
+ * owner is never named (`R-LOOP-11`), and a marker naming a role the kind does not name as a judge
152
+ * counts for none. With none to name it is `{ action:
153
+ * 'ignore' }`. Otherwise it is `{ action: 'judge', kind, judges }`, each judge a role answer, as
154
+ * `judgeOf` composes it, with `steps`, the card's selected steps for the judge's `head`, in the
155
+ * order the kind lists them, as `nextAction` answers each.
156
+ *
157
+ * Where the forge would not serve the diff, it names no judge, since two SHAs do not tell a judge
158
+ * what changed (Codex 5 on #467). It records a `diff.refused` event under the card through `sink`,
159
+ * naming the pull request and the forge's reason, and answers `ignore`.
160
+ *
161
+ * `directories` holds, by role, the outcome of L1's make of a judge's directory where L1 could not
162
+ * make it, or L1's report that a judge's dispatch did not start, which L3 hands L2 unread. A refused
163
+ * directory or scratch directory answers one loop-raised ambiguous escalation naming every
164
+ * refusal, with `from` naming the stage the facts hold. A judge
165
+ * whose directory or scratch directory was not made is not named, as `unmade` says (the architect's
166
+ * ruling 4's addendum; "Failure model", step 4).
167
+ *
168
+ * `outcomes` holds, by role, the outcomes L3 has handed L2 of a judge's steps in its `head`. A judge
169
+ * whose required step failed is not named, and L2 records a `judge.withheld` event under the card
170
+ * naming the role, the step and the failure, classed as the environment's. The answer also names
171
+ * each withheld role so L3 can leave the card out of later pulls in this invocation. Nothing retries it
172
+ * within the claim: the next invocation names it again, since it still has no marker at the head
173
+ * (the architect's ruling 2, P3). L2 keeps no memory, so it records the failure each time it is
174
+ * handed it, and L3 hands a judge's outcomes to it once.
175
+ */
176
+ export function judgeAnswer(card, kinds, epicLabel, { roles = {}, provisioning = {}, sink, outcomes = {}, directories: reports = {} } = {}) {
177
+ const { kind, answer } = kindOf(card, kinds, epicLabel);
178
+ if (answer !== undefined) return answer;
179
+ const declared = kinds[kind];
180
+ const decisions = panelDecisions(outcomes);
181
+ if (decisions !== undefined) {
182
+ const escalations = decisions.filter((answer) => answer.action === 'escalate');
183
+ if (escalations.length > 0) return { ...escalations[0], reason: escalations.map((answer) => answer.reason).join('\n') };
184
+ const ended = decisions.find((answer) => answer.action === 'hold') ?? decisions.find((answer) => answer.action === 'stop');
185
+ if (ended !== undefined) return ended;
186
+ const withheld = [...new Set(decisions.flatMap((answer) => answer.withheld ?? []))];
187
+ return { action: 'ignore', ...(withheld.length === 0 ? {} : { withheld }) };
188
+ }
189
+ const directories = reports;
190
+ const firstFailures = Object.fromEntries(Object.entries(reports).filter(([, report]) => report?.firstFailure !== undefined).map(([role, report]) => [role, report.firstFailure]));
191
+ const agents = declared.judges.map(judgeRole).filter((role) => role !== OWNER);
192
+ if (agents.length === 0) return { action: 'ignore' };
193
+ const tiers = new Map(agents.map((role) => [role, tierOf(card, role, roles[role] ?? {}, 'judge')]));
194
+ const panel = panelOf(card, declared, roles);
195
+ const form = checkAcceptanceForm(card);
196
+ const reasons = [...[...tiers.values()].map((tier) => tier.conflict), panel[0]?.conflict, form.admitted ? undefined : form.reason].filter((reason) => reason !== undefined);
197
+ if (reasons.length > 0) return { action: 'refuse', card: card.number, reason: reasons.join('; and ') };
198
+ const pull = held(card, 'pull');
199
+ const comments = held(card, 'comments');
200
+ const items = acceptanceItems(card.body);
201
+ const digest = acceptanceDigest(card.body);
202
+ const { governing, markers } = readMarkers(comments, { card: card.number, pull: pull.number, head: pull.head, digest, count: items.length });
203
+ const required = requiredOf(panel);
204
+ const owed = agents.filter((role) => stateOf(governing.get(role), required.get(role)) === 'owed');
205
+ if (owed.length === 0) return { action: 'ignore' };
206
+ if (card.forge.diff?.status !== 'fulfilled') {
207
+ const reason = card.forge.diff?.reason?.message ?? `no outcome: ${JSON.stringify(card.forge.diff)}`;
208
+ record(sink, card, 'diff.refused', { pull: pull.number, reason }, `pull request #${pull.number}'s diff was not served`);
209
+ return { action: 'ignore' };
210
+ }
211
+ const earlier = markers.filter((marker) => agents.includes(marker.role) && marker.head !== pull.head).at(-1)?.head;
212
+ const evidence = evidenceOf(card, pull, digest, card.forge.diff.value, earlier);
213
+ const facts = { card: card.number, revision: digest, pull: pull.number, base: pull.base, head: pull.head };
214
+ const steps = selectedSteps(card, declared, provisioning);
215
+ const withheldRoles = [];
216
+ const refusals = [];
217
+ const judges = owed
218
+ .filter((role) => {
219
+ const directory = directories[role];
220
+ if (directory?.status === 'rejected' && [WORKSPACE_REFUSED, SCRATCH_REFUSED].includes(directory.reason?.code)) {
221
+ refusals.push(`${role}: ${directory.reason.message}`);
222
+ return false;
223
+ }
224
+ const missing = (directories[role] !== undefined && unmade(card, role, directories[role], sink))
225
+ || withheld(card, role, steps, outcomes[role] ?? [], provisioning, sink);
226
+ if (missing) withheldRoles.push(role);
227
+ return !missing;
228
+ })
229
+ .map((role) => ({ ...judgeOf(role, roles[role] ?? {}, tiers.get(role).tier, required.get(role), pull, evidence, facts, items),
230
+ ...(governing.has(role) ? { comment: governing.get(role).comment } : {}), steps: steps.map((name) => stepAnswer(name, provisioning)) }));
231
+ const withholding = withheldRoles.length > 0 ? { withheld: withheldRoles } : {};
232
+ if (refusals.length > 0) return { action: 'escalate', class: 'card-local', category: 'ambiguous', raiser: 'loop', reason: refusals.join('\n'), pull: pull.number, head: pull.head, from: card.forge.stage, ...withholding };
233
+ if (Object.values(directories).some(({ reason }) => reason?.code === EVENT_REFUSED || reason?.startCause?.kind === 'event-unrecorded')) return { action: 'judge', kind, judges, halt: true, ...withholding };
234
+ const retry = owed.find((role) => judgeFailure(role, directories[role]) !== undefined);
235
+ if (retry !== undefined) {
236
+ const classified = (report) => ({ class: 'environment', ...judgeFailure(retry, report), ...(report?.dispatch === undefined ? {} : { dispatch: report.dispatch }) });
237
+ const firstFailure = firstFailures[retry] === undefined ? undefined : classified(firstFailures[retry]);
238
+ return { ...failedAttempt(card, firstFailure === undefined ? 1 : 2, firstFailure, classified(directories[retry]), sink), role: retry, ...(firstFailure === undefined ? {} : { firstFailure }) };
239
+ }
240
+ return { action: 'judge', kind, judges, ...withholding };
241
+ }
242
+
243
+ /** The completed panel's L2 decisions, carried beside its per-role step outcomes. */
244
+ function panelDecisions(reports = {}) {
245
+ const entries = Object.values(reports);
246
+ return entries.length > 0 && entries.every((report) => Object.hasOwn(report, 'decision'))
247
+ ? entries.map((report) => report.decision).filter((decision) => decision !== undefined) : undefined;
248
+ }
249
+
250
+ /** The host causes L1 names, in its vocabulary, and L2's row and counted identity for each. */
251
+ const START_FAILURES = {
252
+ 'codex-probe-timeout': ['R19'],
253
+ 'codex-skill-unresolved': ['R18'],
254
+ 'codex-probe-answer': ['R17'],
255
+ 'codex-probe-exit': ['R16'],
256
+ 'dispatch-location': ['R21'],
257
+ 'adapter-variable': ['R20', 'variable'],
258
+ 'agent-name-invalid': ['R35'],
259
+ 'owner-home-missing': ['R34'],
260
+ 'codex-home-file-unwritten': ['R27'],
261
+ 'codex-config-unreadable': ['R11'],
262
+ 'codex-directory-unmade': ['R26'],
263
+ 'claude-reached-path': ['R13', 'path'],
264
+ 'claude-exclusion-path': ['R12', 'path'],
265
+ 'claude-rule-unreadable': ['R33'],
266
+ 'claude-compound-rule': ['R10'],
267
+ 'claude-settings-unreadable': ['R9'],
268
+ 'agent-unreadable': ['R8', 'file'],
269
+ 'agent-unresolved': ['R7', 'file'],
270
+ 'agent-outside': ['R6', 'file'],
271
+ 'directory-occupied': ['R31'],
272
+ 'working-directory-outside': ['R30'],
273
+ 'groups-unwritable': ['R25'],
274
+ 'event-emitter-missing': ['R24'],
275
+ 'dispatch-timeout': ['R23'],
276
+ 'dispatch-identity': ['R22'],
277
+ 'directory-illegible': ['R14', 'path'],
278
+ 'scratch-illegible': ['R15', 'path'],
279
+ 'command-character': ['R5'],
280
+ 'command-missing': ['R2', 'provider'],
281
+ 'host-error': ['R37'],
282
+ 'file-descriptors': ['R36'],
283
+ 'process-resources': ['R28'],
284
+ 'command-too-long': ['R4'],
285
+ 'command-not-executable': ['R3', 'provider'],
286
+ 'directory-unusable': ['R29'],
287
+ };
288
+
289
+ /** L2's classification of a judge's never-started report, apart from a scratch directory not made. */
290
+ function judgeFailure(judge, outcome) {
291
+ const reason = outcome?.reason;
292
+ if (outcome?.status !== 'rejected' || reason?.code !== NOT_STARTED || reason.missing !== undefined) return undefined;
293
+ const cause = reason.startCause;
294
+ const classified = START_FAILURES[cause?.kind];
295
+ if (classified === undefined) return undefined;
296
+ const [row, identity] = classified;
297
+ return { judge, row, reason: reason.message, ...(identity === undefined ? {} : { [identity]: cause[identity] }) };
298
+ }
299
+
300
+ /**
301
+ * Whether judge `role` of `card` is withheld for its directory: whether `outcome`, of L1's make of
302
+ * it, is L1's failure to make it, which L2 records through `sink` as a `judge.withheld` event naming
303
+ * the role, the directory and why, classed as the environment's.
304
+ *
305
+ * `outcome` may instead be L1's report that the judge's dispatch did not start. Where that report
306
+ * names the judge's scratch directory as `missing`, L1 could not make it for a host cause, and L2
307
+ * withholds the judge as for its directory, its event naming the scratch directory as `scratch`
308
+ * (`R-FAIL-8`; U43). A dispatch that never started for another cause withholds nothing, and its
309
+ * outcome stands. `judgeAnswer` handles directory refusals before reaching this host-failure rule.
310
+ * Any other outcome is no such failure, so L2 answers no action for it, naming the card and the role.
311
+ */
312
+ function unmade(card, role, outcome, sink) {
313
+ if (outcome?.status === 'rejected' && outcome.reason?.code === EVENT_REFUSED) return false;
314
+ if (outcome?.status === 'rejected' && outcome.reason?.code === NOT_STARTED) {
315
+ const { missing, message } = outcome.reason;
316
+ if (missing === undefined) return false;
317
+ record(sink, card, 'judge.withheld', { role, scratch: missing, reason: message, class: 'environment' }, `judge ${role}'s scratch directory was not made`);
318
+ return true;
319
+ }
320
+ if (outcome?.status !== 'rejected' || outcome.reason?.code !== WORKSPACE_NOT_MADE) {
321
+ const read = outcome?.status === 'rejected' ? outcome.reason?.message : JSON.stringify(outcome);
322
+ throw new Error(`card #${card.number}'s judge ${role} has a directory outcome that is not L1's failure to make it, so L2 answers no action for it: ${read}`, { cause: outcome?.reason });
323
+ }
324
+ record(sink, card, 'judge.withheld', { role, directory: outcome.reason.path, reason: outcome.reason.message, class: 'environment' }, `judge ${role}'s directory was not made`);
325
+ return true;
326
+ }
327
+
328
+ /**
329
+ * Whether judge `role` of `card` is withheld: whether one of `outcomes`, the outcomes of its
330
+ * `steps` so far, in order, is a required step's failure, which L2 records through `sink`.
331
+ */
332
+ function withheld(card, role, steps, outcomes, provisioning, sink) {
333
+ for (const [at, outcome] of outcomes.entries()) {
334
+ const name = steps[at];
335
+ const failure = failed(outcome, provisioning[name], card, name);
336
+ if (failure === undefined || !workRequires(provisioning[name])) continue;
337
+ record(sink, card, 'judge.withheld', { role, step: name, ...failure, class: 'environment' }, `judge ${role}'s required step \`${name}\` failed`);
338
+ return true;
339
+ }
340
+ return false;
341
+ }
342
+
343
+ /**
344
+ * The evidence every judge of `card` at `pull`'s head is handed, the same bytes for each: the
345
+ * card's number and title, its acceptance as `R-CARD-12` reads it and that acceptance's `digest`,
346
+ * which the marker carries, the pull request's number and its base and head SHAs, the `earlier`
347
+ * head the newest marker at another head named where there is one, and the `diff` (`R-EVIDENCE-1`,
348
+ * `R-EVIDENCE-3`). It carries no comment's text and nothing of the maker's session (`R-EVIDENCE-4`).
349
+ */
350
+ function evidenceOf(card, pull, digest, diff, earlier) {
351
+ return [
352
+ `Card #${card.number}: ${card.title}`,
353
+ '',
354
+ `Acceptance, whose digest your marker carries, ${digest}:`,
355
+ ...acceptanceItems(card.body).map((item) => `- ${item}`),
356
+ '',
357
+ `Pull request #${pull.number}, from base ${pull.base} to head ${pull.head}.`,
358
+ ...(earlier === undefined ? [] : [`Earlier head, which the previous marker named: ${earlier}`]),
359
+ '',
360
+ 'Diff:',
361
+ diff,
362
+ ].join('\n');
363
+ }
364
+
365
+ /**
366
+ * The provider the panel function `panel` requires of each agent judge, by role. A panel holding a
367
+ * conflict requires none, and its card is refused before any judge is read.
368
+ */
369
+ const requiredOf = (panel) => new Map(panel.filter((entry) => entry.provider !== undefined).map(({ role, provider }) => [role, provider]));
370
+
371
+ /**
372
+ * L2's answer for judge `role`, declared as `declared`, running at `tier` on `provider`, the one the
373
+ * panel function requires of it, on `pull`: its name and agent file as declared, its provider, its
374
+ * time as `roleTimeout` answers it, `evidence` and `facts` as
375
+ * given, `digest`, the evidence digest L1 records at `dispatch.start`, and the instruction Rigger's
376
+ * contract with every judge composes, which asks for a marker ruling on each of `items` and
377
+ * carrying its provider and the evidence digest, and holds the slot L3 fills with the dispatch id (`dispatched`). No
378
+ * directory is a field of it: L1 makes the judge's directory once L2 has answered (the architect's
379
+ * ruling 3, P8).
380
+ */
381
+ function judgeOf(role, declared, tier, provider, pull, evidence, facts, items) {
382
+ const digest = evidenceDigest(evidence);
383
+ const instruction = [
384
+ `Rigger dispatched this session, unattended, as the judge \`${role}\` of pull request #${pull.number}, at head \`${pull.head}\`.`,
385
+ 'What follows is a floor, never a limit: you may read beyond what you were given.',
386
+ 'The pull request\'s head, with the card\'s provisioning steps run in it, is in the `head` directory beside your working directory. Build and test in the `head` directory, and never edit it.',
387
+ `Before ruling, run \`git diff ${pull.base} ${pull.head}\` in your working directory as its own tool call, even when the evidence below includes the diff.`,
388
+ 'Run any command in `head` as one line: `cd ../head && <command>`.',
389
+ 'Never run git in `head`; run git commands in your working directory.',
390
+ 'Your working directory is not provisioned; never build or test there. Read a command\'s exit status from the tool\'s result.',
391
+ 'Use a separate tool call for each command, with no extra shell operations, pipes, groups, variables, or status probes such as `$?`, `${...}` or `$(...)`. Keep the `cd ../head && <command>` line by itself.',
392
+ markerInstruction({ card: facts.card, pull: pull.number, head: pull.head, digest: facts.revision, role, provider, items, evidence: digest }),
393
+ '',
394
+ '',
395
+ ].join('\n');
396
+ return { role, agent: declared.agent, provider, tier, timeout: roleTimeout(declared), instruction, evidence, digest, facts };
397
+ }
398
+
399
+ /**
400
+ * L2's review loop: its answer for `card`, a Review, Owner or Coding card whose one open pull
401
+ * request L2's facts call read, under a config's `kinds` and `epicLabel`, from the markers at that
402
+ * pull request's head and the card's acceptance digest, as `readMarkers` governs them. `options` are
403
+ * `judgeAnswer`'s, and its `sink` records one `marker.read` event per governing marker read, as
404
+ * `markerRead` says: every agent judge's, and in Owner the owner's too. In Review the owner's marker
405
+ * is never read.
406
+ *
407
+ * First, in every column, a card whose labels select two providers for its maker or one of its
408
+ * judges is refused, naming the role and each label, as the panel function answers it (`R-LOOP-16`).
409
+ * A Coding card is answered as `codingAnswer` says, and an Owner card whose agent judges are all
410
+ * sound as `ownerAnswer` says. Otherwise L2 takes the first rule that applies (architect review B's
411
+ * R3 on #642):
412
+ * 1. a governing critical marker escalates the card as `critical`, spending no round (`R-ESCALATE-6`);
413
+ * 2. an Owner card any of whose agent markers no longer governs, or is not sound, moves to Review;
414
+ * 3. agent judges owed a marker, absent, unreadable, edited or on another provider than the one
415
+ * the panel function requires, are dispatched, and only they, as
416
+ * `judgeAnswer` answers them, spending no round (the architect's r2 ruling 7);
417
+ * 4. coverage ruled insufficient returns the acceptance to its author, as `returned` says (`R-LOOP-6`);
418
+ * 5. needs revision, or sound with an item unmet, is a continuing attempt, as `continued` says,
419
+ * unless the kind's rounds, three where it declares none, are spent: then the card escalates as
420
+ * `ambiguous` (`R-LOOP-9`), its rounds counted as `roundsOf` counts them;
421
+ * 6. every agent judge sound under a kind naming the owner moves the card to Owner, and nothing is
422
+ * dispatched for the owner (`R-LOOP-11`);
423
+ * 7. every judge sound goes to the merge decision, as `mergeAnswer` says.
424
+ *
425
+ * Each answer is one of `{ action: 'judge', kind, judges }`, `{ action: 'refuse', card, reason }`,
426
+ * `{ action: 'move', to }`, `{ action: 'continue', pull, head, markers }`, `{ action: 'return',
427
+ * pull, comment }`, `{ action: 'escalate', category, raiser, reason, pull, head }`, `{ action: 'merge', pull, head, digest, verdicts }` and
428
+ * `{ action: 'ignore', reason }`, which L3 carries out.
429
+ */
430
+ export function reviewAnswer(card, kinds, epicLabel, options = {}) {
431
+ if (panelDecisions(options.outcomes) !== undefined) return judgeAnswer(card, kinds, epicLabel, options);
432
+ const { kind, answer } = kindOf(card, kinds, epicLabel);
433
+ if (answer !== undefined) return answer;
434
+ const declared = kinds[kind];
435
+ const panel = panelOf(card, declared, options.roles);
436
+ if (panel[0]?.conflict !== undefined) return { action: 'refuse', card: card.number, reason: panel[0].conflict };
437
+ const required = requiredOf(panel);
438
+ const agents = declared.judges.map(judgeRole).filter((role) => role !== OWNER);
439
+ // In Review the owner's marker is never read, so a kind naming the owner alone reads no marker,
440
+ // and moves to Owner once the forge facts every advance rests on are served.
441
+ if (agents.length === 0 && card.forge.stage === 'review') return advanced(card, { action: 'move', to: 'owner' });
442
+ // The pull request's number and head as L2's facts call read them from its line of work: only
443
+ // a judge's evidence needs the merge base, which `judgeAnswer` reads.
444
+ const [pull] = card.forge.open;
445
+ const comments = held(card, 'comments');
446
+ const items = acceptanceItems(card.body);
447
+ const digest = acceptanceDigest(card.body);
448
+ const round = { card: card.number, pull: pull.number, head: pull.head, digest, count: items.length };
449
+ const { governing } = readMarkers(comments, round);
450
+ const read = card.forge.stage === 'owner' ? [...agents, OWNER] : agents;
451
+ for (const role of read.filter((each) => governing.has(each))) markerRead(options.sink, card, pull, round, role, governing.get(role));
452
+ const states = agents.map((role) => stateOf(governing.get(role), required.get(role)));
453
+ if (card.forge.stage === 'coding') return codingAnswer(card, pull, states, agents.map((role) => governing.get(role)), items);
454
+ if (states.includes('critical')) return {
455
+ action: 'escalate', category: 'critical', raiser: 'loop', pull: pull.number, head: pull.head,
456
+ reason: agents.filter((role, at) => states[at] === 'critical')
457
+ .map((role) => markerReason(governing.get(role).marker, items)).join('\n'),
458
+ };
459
+ if (card.forge.stage === 'owner') {
460
+ if (!states.every((state) => state === 'sound')) return { action: 'move', to: 'review' };
461
+ return ownerAnswer(card, panel, pull, comments, round, governing.get(OWNER), items);
462
+ }
463
+ if (states.includes('owed')) return judgeAnswer(card, kinds, epicLabel, options);
464
+ const insufficient = agents.find((role, at) => states[at] === 'insufficient');
465
+ if (insufficient !== undefined) return returned(card, pull, comments, governing.get(insufficient).marker);
466
+ const revising = agents.filter((role, at) => states[at] === 'revision');
467
+ const spent = revising.length > 0 ? roundsOf(comments, round, required) : 0;
468
+ const bound = declared.rounds ?? ROUNDS;
469
+ if (revising.length > 0 && spent >= bound) return {
470
+ action: 'escalate', category: 'ambiguous', raiser: 'loop', pull: pull.number, head: pull.head,
471
+ reason: [`${spent} of ${bound} rounds spent.`, ...revising.map((role) => markerReason(governing.get(role).marker, items))].join('\n'),
472
+ };
473
+ if (revising.length > 0) return continued(pull, revising.map((role) => governing.get(role)), items);
474
+ if (declared.judges.map(judgeRole).includes(OWNER)) return advanced(card, { action: 'move', to: 'owner' });
475
+ return mergeAnswer(card, panel, pull, comments, round);
476
+ }
477
+
478
+ /**
479
+ * Records, through `sink`, the L2 `marker.read` event for `role`'s marker `governing`, governing at
480
+ * `round` on `card`'s pull request `pull`: its role, head, digest, provider, verdict, dispatch id
481
+ * and evidence digest, a field it lacks as null (`R-VERDICT-7`), and whether its comment was edited. An unreadable
482
+ * marker is recorded with verdict null and its parse reason. The dispatch id is the event's own
483
+ * `dispatch`, which the sink stamps.
484
+ */
485
+ function markerRead(sink, card, pull, round, role, governing) {
486
+ const fields = governing.marker ?? {};
487
+ const unreadable = governing.state === 'marker' ? {} : { reason: governing.reason };
488
+ const event = { pull: pull.number, role, head: round.head, digest: round.digest, provider: fields.provider ?? null, verdict: fields.verdict ?? null, evidence: fields.evidence ?? null, edited: governing.edited, ...unreadable };
489
+ // The sink stamps the dispatch id, as the dispatch the marker arose under.
490
+ record(sink, card, 'marker.read', event, `${role}'s marker at head ${round.head} was read`, fields.dispatch ?? null);
491
+ }
492
+
493
+ /**
494
+ * L2's answer for `card` in the Coding column with one open pull request, from `states`, its agent
495
+ * judges' states, and `governing`, their governing markers: a continuing attempt where one needs
496
+ * revision, or where every one is sound and the forge reads the pull request as conflicting
497
+ * (`R-CONFLICT-1`); `ignore` where every one is sound and the forge cannot yet say whether it
498
+ * conflicts; and otherwise refused as at the base, since its work would start again from the
499
+ * beginning over what was pushed (`R-WORK-19`).
500
+ */
501
+ function codingAnswer(card, pull, states, governing, items) {
502
+ const revising = governing.filter((held, at) => states[at] === 'revision');
503
+ if (revising.length > 0) return continued(pull, revising, items);
504
+ if (states.every((state) => state === 'sound')) {
505
+ const mergeable = held(card, 'mergeable');
506
+ if (mergeable === 'conflicting') return continued(pull, [], items, governing.map(({ comment }) => comment));
507
+ if (mergeable === 'unknown') return { action: 'ignore', reason: `the forge reads pull request #${pull.number}'s mergeability as unknown` };
508
+ }
509
+ return { action: 'refuse', card: card.number, reason: `the forge holds its line of work, ${card.forge.line}, so its work would not start from the beginning` };
510
+ }
511
+
512
+ /**
513
+ * L2's answer for `card` in the Owner column, every agent judge sound, from `owner`, the owner's
514
+ * governing marker at the head and digest: with none, the card stays in Owner and nothing is
515
+ * dispatched, since the owner is never dispatched (`R-LOOP-11`); an unreadable or edited one, or
516
+ * one naming a provider, which the owner's never does (`D24` rule 2), is named and left for the
517
+ * owner; otherwise the marker is answered as an agent judge's would be, with no bound on rounds,
518
+ * and a sound one goes to the merge decision under `panel`, the panel function's entries.
519
+ */
520
+ function ownerAnswer(card, panel, pull, comments, round, owner, items) {
521
+ const at = `at head ${pull.head}, acceptance digest ${round.digest}`;
522
+ if (owner === undefined) return { action: 'ignore', reason: `every agent judge is sound, and the owner has written no marker ${at}` };
523
+ if (owner.state === 'marker' && !owner.edited && owner.marker.provider !== undefined) {
524
+ return { action: 'ignore', reason: `the owner's marker ${at} names a provider, ${owner.marker.provider}, and the owner's names none` };
525
+ }
526
+ const state = stateOf(owner);
527
+ if (state === 'owed') {
528
+ const why = owner.state === 'marker' ? 'edited' : `unreadable: ${owner.reason}`;
529
+ return { action: 'ignore', reason: `the owner's marker ${at} is ${why}` };
530
+ }
531
+ if (state === 'critical') return {
532
+ action: 'escalate', category: 'critical', raiser: 'loop', pull: pull.number, head: pull.head,
533
+ reason: markerReason(owner.marker, items),
534
+ };
535
+ if (state === 'insufficient') return returned(card, pull, comments, owner.marker);
536
+ if (state === 'revision') return continued(pull, [owner], items);
537
+ return mergeAnswer(card, panel, pull, comments, round);
538
+ }
539
+
540
+ /**
541
+ * L2's answer returning `card`'s acceptance to its author for `marker`, which rules its coverage
542
+ * insufficient: one comment on `pull`, the card's open pull request, quoting the marker's role and
543
+ * its `coverageReason` (`R-LOOP-6`). Its first line names the marker's role, head and digest, so
544
+ * the comment is the one return for that marker: where `comments` already hold it, written by an
545
+ * account with write access and its text the same but for line endings and trailing whitespace,
546
+ * L2 answers `ignore` and no second comment. A copy by any other account, or another comment
547
+ * opening on that line, is no return and stops none. Its second line opens no marker block, so it
548
+ * parses as no marker and never governs.
549
+ */
550
+ function returned(card, pull, comments, { role, head, digest, coverageReason }) {
551
+ const first = `Rigger returns card #${card.number}'s acceptance to its author: the judge ${role} ruled its coverage insufficient at head ${head}, acceptance digest ${digest}.`;
552
+ const comment = [first, '', `${role}'s reason: ${coverageReason}`, '', 'The acceptance returns to its author, who revises it. No judge rewrites it.', ''].join('\n');
553
+ const same = (body) => String(body).replace(/\r\n/g, '\n').trimEnd() === comment.trimEnd();
554
+ if (comments.some((each) => each.author !== null && WRITERS.includes(each.permission) && same(each.body))) {
555
+ return { action: 'ignore', reason: `pull request #${pull.number} already holds the comment returning the acceptance for ${role}'s marker at head ${head}, acceptance digest ${digest}` };
556
+ }
557
+ return { action: 'return', pull: pull.number, comment };
558
+ }
559
+
560
+ /** The rounds a kind gets where it declares none (`R-LOOP-9`). */
561
+ const ROUNDS = 3;
562
+
563
+ /** The lines of a comment's text that look like a marker's item line, `item <n>: …`, inside its block or not. */
564
+ const ITEM_LINE = /^item \d+:/gm;
565
+
566
+ /**
567
+ * The readable markers `comment` holds for `round`, read against the item count its own block
568
+ * rules on, whatever acceptance it ruled against. A block parses against exactly the count of the
569
+ * items it rules on, so it is read against each count up to the item-like lines the comment holds,
570
+ * prose after the block included, and the count it parses against is its own.
571
+ */
572
+ function readableAtAnyCount(comment, round) {
573
+ for (let count = (String(comment.body).match(ITEM_LINE) ?? []).length; count >= 0; count -= 1) {
574
+ const { markers } = readMarkers([comment], { ...round, count });
575
+ if (markers.length > 0) return markers;
576
+ }
577
+ return [];
578
+ }
579
+
580
+ /**
581
+ * The rounds a card's pull request has spent, from its `comments` read for `round`: the distinct
582
+ * (head, digest) pairs at which a readable, unedited marker of one of the agent judges in
583
+ * `required` stands, on the provider `required` names for it (`D24`), a pair at a
584
+ * head the pull request no longer holds included (the architect's r2 ruling 7 on #642). A marker
585
+ * from an earlier acceptance ruled on that acceptance's items, however many it held, so each is
586
+ * read as `readableAtAnyCount` reads it: a marker valid against its own acceptance spends its round
587
+ * after an item is added or removed, and whatever prose its comment holds.
588
+ */
589
+ function roundsOf(comments, round, required) {
590
+ const pairs = comments.filter((comment) => !comment.edited).flatMap((comment) => readableAtAnyCount(comment, round));
591
+ return new Set(pairs.filter((marker) => required.has(marker.role) && marker.provider === required.get(marker.role)).map((marker) => `${marker.head} ${marker.digest}`)).size;
592
+ }
593
+
594
+ /**
595
+ * L2's continuing attempt on `pull`, the card's open pull request, at the head L2 read: the maker
596
+ * is handed each of `markers`, the governing markers that are not sound, as its role, its verdict,
597
+ * each unmet item by its ordinal and its text among `items`, and its `toSound` where it gives one.
598
+ */
599
+ function continued(pull, markers, items, comments) {
600
+ const handedOf = ({ comment, marker: { role, verdict, items: ruled, toSound } }) => ({
601
+ comment,
602
+ role,
603
+ verdict,
604
+ unmet: ruled.flatMap((ruling, at) => (ruling === 'unmet' ? [{ item: at + 1, text: items[at] }] : [])),
605
+ ...(toSound === undefined ? {} : { toSound }),
606
+ });
607
+ return { action: 'continue', pull: pull.number, head: pull.head, markers: markers.map(handedOf), ...(comments === undefined ? {} : { comments }) };
608
+ }
609
+
610
+ /** The actual reason and unmet acceptance text a governing marker contributes to an escalation. */
611
+ function markerReason({ role, verdict, toSound, items: ruled }, items) {
612
+ const unmet = ruled.flatMap((ruling, at) => ruling === 'unmet' ? [`unmet item ${at + 1}: ${items[at]}`] : []);
613
+ return `${role} (${verdict}): ${[...(toSound === undefined ? [] : [toSound]), ...unmet].join('; ')}`;
614
+ }
615
+
616
+ /**
617
+ * What a judge's governing marker `governing`, as `readMarkers` answers it, rules: `owed` where it
618
+ * is absent, unreadable or edited, or, for an agent judge required to run on `provider`, where it
619
+ * names no provider or another (`D24` rule 2); `critical`; `insufficient`, coverage ruled
620
+ * insufficient; `revision`, needs revision or sound with an item unmet; or `sound`. The owner is
621
+ * handed no provider, and `ownerAnswer` reads the owner's own.
622
+ */
623
+ function stateOf(governing, provider) {
624
+ if (governing?.state !== 'marker' || governing.edited) return 'owed';
625
+ if (provider !== undefined && governing.marker.provider !== provider) return 'owed';
626
+ const { verdict, coverage, items } = governing.marker;
627
+ if (verdict === 'critical') return 'critical';
628
+ if (coverage === 'insufficient') return 'insufficient';
629
+ if (verdict !== 'sound' || items.includes('unmet')) return 'revision';
630
+ return 'sound';
631
+ }
632
+
633
+ /**
634
+ * What the read named `read`, the rules or the check states they leave unread, answered for `card`,
635
+ * or null where it failed because L0 read the forge's refusal as the feature being unavailable.
636
+ * Any other failure is held.
637
+ */
638
+ function policyFact(card, read) {
639
+ const outcome = card.forge?.[read];
640
+ return outcome?.status === 'rejected' && outcome.reason?.code === EFFECTIVE_RULES_UNAVAILABLE ? null : held(card, read);
641
+ }
642
+
643
+ /**
644
+ * The forge facts every advance of a Review or Owner card rests on, `card`'s mergeability, its base
645
+ * branch's effective rules and its check states, so a failed read of any one answers no action
646
+ * naming it, whatever the others answered (the answers table's failed-read row). Rules the forge
647
+ * offers this repository no feature for are null, as `policyFact` says, and `mergeAnswer` alone
648
+ * reads what that means.
649
+ */
650
+ function forgeFacts(card) {
651
+ return { mergeable: held(card, 'mergeable'), rules: policyFact(card, 'rules'), states: policyFact(card, 'checks') };
652
+ }
653
+
654
+ /** `answer`, L2's advance of `card`, once every read `forgeFacts` holds was served. */
655
+ function advanced(card, answer) {
656
+ forgeFacts(card);
657
+ return answer;
658
+ }
659
+
660
+ /**
661
+ * L2's merge decision for `card` once every one of `panel`, the panel function's entries, is sound
662
+ * at `pull`'s head. Where the
663
+ * forge reads the pull request as conflicting, the card's maker continues on it (`R-CONFLICT-1`);
664
+ * where its mergeability is unknown, L2 answers `ignore`, naming it and setting
665
+ * `unknownMergeability` beside the reason. L3 uses that field to read the whole card and run L2's
666
+ * rule again (`R-SCHED-26`); L2 never decides when to wait (the architect's r2 ruling 5).
667
+ * Otherwise the gate rule is handed the checks the base branch's effective rules require, less the
668
+ * gate's own context, each in the state the facts hold, `absent` where they hold none (`ARCHITECTURE.md`,
669
+ * "The engine's merge decision"): it answers `merge` where the gate admits, and `ignore` naming each
670
+ * refusal where it does not. L2 judges no status's creator; the forge enforces the pin at the merge.
671
+ * A failed read of the mergeability, the rules or the check states answers no action, naming it,
672
+ * whatever the other reads answered. Rules the forge offers this repository no feature for leave
673
+ * nothing for the gate rule to take, so L2 refuses the merge, naming them, and never answers `merge`.
674
+ */
675
+ function mergeAnswer(card, panel, pull, comments, round) {
676
+ const { mergeable, rules, states } = forgeFacts(card);
677
+ if (mergeable === 'conflicting') {
678
+ const { governing } = readMarkers(comments, round);
679
+ return continued(pull, [], [], panel.map(({ role }) => governing.get(role)?.comment).filter((id) => id !== undefined));
680
+ }
681
+ if (mergeable !== 'mergeable') return { action: 'ignore', reason: `the forge reads pull request #${pull.number}'s mergeability as ${mergeable}`, ...(mergeable === 'unknown' ? { unknownMergeability: true } : {}) };
682
+ if (rules === null || states === null) {
683
+ const { reason } = [card.forge.rules, card.forge.checks].find(({ status }) => status === 'rejected');
684
+ return { action: 'refuse', card: card.number, reason: `pull request #${pull.number} is not merged, because the forge offers this repository no effective rules for its base branch, so the checks they require are unavailable evidence: ${reason.message}` };
685
+ }
686
+ const required = new Set(rules.map((rule) => rule.context).filter((context) => context !== GATE_CONTEXT));
687
+ const checks = Object.fromEntries([...required].map((context) => [context, states[context] ?? { state: 'absent', creator: null }]));
688
+ const gate = gateAnswer({ comments, ...round, judges: panel, checks });
689
+ if (gate.admit) {
690
+ const { governing } = readMarkers(comments, round);
691
+ return { action: 'merge', pull: pull.number, head: pull.head, digest: round.digest,
692
+ verdicts: panel.map(({ role }) => ({ role, verdict: governing.get(role).marker.verdict })) };
693
+ }
694
+ return { action: 'ignore', reason: gate.refusals.map((refusal) => `${refusal.judge ?? refusal.check}: ${refusal.reason}`).join('; ') };
695
+ }