@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,510 @@
1
+ // ABOUTME: The forge adapter's four runners, read, schema-write, item-write and repository-write. Each admits one
2
+ // operation of its own side and refuses everything else by name before anything is sent.
3
+
4
+ import { gitEnvironment } from '../git-environment.mjs';
5
+ import { EVENT_REFUSED, NOT_STARTED, runCommand } from '../process.mjs';
6
+ import { literal, parseDocument } from './graphql.mjs';
7
+
8
+ /**
9
+ * How long L0 lets one forge call run before it kills the call's group, where the caller passes no
10
+ * other value (the architect's ruling 2, (g), on #332). A judgment, not a measurement. Its premise
11
+ * is GitHub's own limit: "If GitHub takes more than 10 seconds to process an API request, GitHub
12
+ * will terminate the request" (GitHub's GraphQL documentation, "Rate limits and query limits",
13
+ * "Timeouts", read on 2026-09-28). One call is one request, so a minute is six times that, room
14
+ * for a slow network and for `gh`'s own start, while a call that hangs holds its verb back by no
15
+ * more than a minute.
16
+ */
17
+ export const FORGE_TIMEOUT = 60_000;
18
+
19
+ /**
20
+ * The one spawn every runner makes, through L0's process adapter: `gh` runs in a process group of
21
+ * its own, the group is ended at `timeout`, and every process it leaves behind is killed and
22
+ * recorded through `emitter`. It hands back `gh`'s exit code as `status`, its output as text, and
23
+ * whether the timeout ended it. A command that never started, and a kill the sink refused, reject
24
+ * as the adapter rejects, each failure's `code` naming which.
25
+ * Each settled call records call.end with its runner's side and duration. A refused end carries
26
+ * the adapter's raw result, so the caller can still tell whether its action was made.
27
+ *
28
+ * The environment is the one a git child is given, as `doctor` gave `gh auth status` before this
29
+ * runner existed: `gh` reads the repository it runs in, and an inherited `GIT_DIR` would point it
30
+ * at a repository nobody named.
31
+ */
32
+ async function throughL0(command, args, { emitter, timeout, side }) {
33
+ const began = performance.now();
34
+ let result, failure;
35
+ try {
36
+ result = await runCommand({ command, args, cwd: process.cwd(), env: gitEnvironment(), timeout, emitter });
37
+ } catch (error) {
38
+ if (![NOT_STARTED, EVENT_REFUSED].includes(error.code) || typeof emitter?.emit !== 'function' || error.startCause?.kind === 'dispatch-timeout') throw error;
39
+ failure = error;
40
+ result = error.result;
41
+ }
42
+ const { exit, timedOut, stdout, stderr } = result ?? {};
43
+ const fields = { system: 'forge', side, ms: performance.now() - began, outcome: timedOut ? 'timed-out' : exit === 0 ? 'ok' : 'failed' };
44
+ try {
45
+ emitter.emit('call.end', fields);
46
+ } catch (cause) {
47
+ if (failure?.code === EVENT_REFUSED) {
48
+ failure.unrecorded.push({ event: 'call.end', ...fields, cause });
49
+ failure.message += `\ncall.end ${JSON.stringify(fields)} went unrecorded: ${cause.message}`;
50
+ throw failure;
51
+ }
52
+ throw Object.assign(new Error(`the sink refused L0's call.end ${JSON.stringify(fields)}, so it went unrecorded: ${cause.message}`, { cause: failure ?? cause }), {
53
+ code: EVENT_REFUSED, result, unrecorded: [{ event: 'call.end', ...fields, cause }],
54
+ });
55
+ }
56
+ if (failure) throw failure;
57
+ return { status: exit, timedOut, timeout, stdout: stdout.toString('utf8'), stderr: stderr.toString('utf8') };
58
+ }
59
+
60
+ /** Every command a runner sends is this one (`R-SAFE-2`). */
61
+ const FORGE = 'gh';
62
+
63
+ /** Throws the refusal every runner gives: which runner, what it refused, and that nothing went. */
64
+ function refuse(runner, what) {
65
+ throw new Error(`the ${runner} runner refuses ${what}, and did not send it`);
66
+ }
67
+
68
+ /** How a request is named in a refusal: as the command it would have run. */
69
+ const spelled = (args) => `\`${[FORGE, ...args].join(' ')}\``;
70
+
71
+ /**
72
+ * The `gh` subcommands the read runner admits other than `gh api`, each as its whole argument
73
+ * list. A whole list rather than a subcommand name, so that `gh auth status --show-token`, which
74
+ * would put a credential into whatever captured the output, is refused with everything else.
75
+ * `gh --version` is the one form with no subcommand: it names the installed release.
76
+ */
77
+ const READ_SUBCOMMANDS = [['auth', 'status'], ['--version']];
78
+
79
+ /** Whether `args` is exactly one of `lists`. */
80
+ const oneOf = (args, lists) => lists.some((list) => list.length === args.length && list.every((word, i) => word === args[i]));
81
+
82
+ /**
83
+ * The header asking GitHub to serve a pull request as its diff: one of the two headers a read
84
+ * sends, each of which the read runner admits after `-X GET` alone.
85
+ */
86
+ export const DIFF_HEADER = 'Accept: application/vnd.github.diff';
87
+
88
+ /**
89
+ * The header asking for the API version GitHub serves the Actions policy endpoints at: the other
90
+ * header a read sends, admitted as `DIFF_HEADER` is.
91
+ */
92
+ export const API_VERSION_HEADER = 'X-GitHub-Api-Version: 2026-03-10';
93
+
94
+ /**
95
+ * The whole of what may follow `gh api <path>` for the read runner to send it: an explicit GET,
96
+ * and, after `-X GET` only, the header asking for a diff or the one naming the policy endpoints'
97
+ * API version. Only the diff form also admits `--allow-escape-sequences`, after its header:
98
+ * gh 2.103.3 refuses a raw diff holding ESC without it (#1441, measured on 2026-11-20).
99
+ *
100
+ * `gh` chooses the method itself when none is named, and where it can disagree with a reading of
101
+ * the request (`D16` rule 3), measured with gh 2.99.0 on macOS on 2026-09-25 through a local
102
+ * proxy: with no flag it sends GET; with `-f`, `-F` or `--input` it sends POST; with `-X GET` or
103
+ * `--method GET` it sends GET, and `-X GET -f` puts the field in the query string. So only a
104
+ * named GET is admitted, and with no field at all, after a path that is not itself a flag. A
105
+ * header can override the method, so no header is admitted but the diff's and the policy endpoints'
106
+ * API version, each as a fixed literal.
107
+ * `test/forge-runners.test.mjs` asks `gh` the same question each run, of each header's form too.
108
+ */
109
+ const EXPLICIT_GET = [['-X', 'GET'], ['--method', 'GET'], ['-X', 'GET', '-H', DIFF_HEADER], ['-X', 'GET', '-H', API_VERSION_HEADER], ['-X', 'GET', '-H', DIFF_HEADER, '--allow-escape-sequences']];
110
+
111
+ /** How an operation is named in a refusal: its type, its name if it has one, and its root fields. */
112
+ function named(operation) {
113
+ const fields = operation.selections.map((selection) => selection.name ?? '...').join(', ');
114
+ return `${operation.type}${operation.name ? ` ${operation.name}` : ''} (${fields})`;
115
+ }
116
+
117
+ /** A `gh api graphql` request carrying `document`: the one form a write runner admits. */
118
+ export const graphqlRequest = (document) => ['api', 'graphql', '-f', `query=${document}`];
119
+
120
+ /**
121
+ * The operations of the GraphQL document `query` carries, read for `runner`, which refuses a
122
+ * document it cannot read or one carrying more than one operation.
123
+ */
124
+ function operationsOf(runner, query) {
125
+ let document;
126
+ try {
127
+ document = parseDocument(query);
128
+ } catch (error) {
129
+ refuse(runner, `a GraphQL document it cannot read, ${error.message}: ${query}`);
130
+ }
131
+ const { operations } = document;
132
+ if (operations.length > 1) {
133
+ refuse(runner, `a request carrying more than one operation: ${operations.map(named).join('; ')}`);
134
+ }
135
+ return operations[0];
136
+ }
137
+
138
+ /**
139
+ * The GraphQL document a `gh api graphql` request sends, given what follows `graphql`: exactly
140
+ * one `-f query=`, and otherwise only `-f` or `-F` fields, which `gh` sends as its variables.
141
+ * `-F query=` is refused because `-F` reads a value beginning with `@` from a file, which is a
142
+ * document this runner would never see.
143
+ */
144
+ function queryOf(runner, args, rest) {
145
+ const queries = [];
146
+ for (let i = 0; i < rest.length; i += 2) {
147
+ const [flag, field] = [rest[i], rest[i + 1] ?? ''];
148
+ if (flag !== '-f' && flag !== '-F') refuse(runner, `${spelled(args)}, which carries \`${flag}\``);
149
+ if (field.startsWith('query=')) queries.push([flag, field]);
150
+ }
151
+ if (queries.length !== 1 || queries[0][0] !== '-f') {
152
+ refuse(runner, `${spelled(args)}, which does not carry its document as exactly one \`-f query=\``);
153
+ }
154
+ return queries[0][1].slice('query='.length);
155
+ }
156
+
157
+ /**
158
+ * Sends a request that changes nothing on the forge, and refuses any other.
159
+ *
160
+ * `emitter` is the `L0` emitter the call's kills are recorded through, and `timeout` how long the
161
+ * call may run, `FORGE_TIMEOUT` where it is not given. `send` stands in for the spawn in tests, and
162
+ * is handed what the runner admitted, with the emitter and the timeout. Every runner takes these
163
+ * three, and hands them on to any read it makes itself.
164
+ */
165
+ export async function readRunner(args, { send = throughL0, emitter, timeout = FORGE_TIMEOUT } = {}) {
166
+ const [subcommand, endpoint, ...rest] = args;
167
+ if (subcommand === 'api' && endpoint === 'graphql') {
168
+ const operation = operationsOf('read', queryOf('read', args, rest));
169
+ if (operation.type !== 'query') refuse('read', `${named(operation)}, which is not a query`);
170
+ } else if (subcommand === 'api' && endpoint !== undefined) {
171
+ // A path slot holding a flag makes that flag take the next word, so the `-X GET` after it
172
+ // would name no method: `gh api --input -X GET` sends `POST /GET` with a file as its body.
173
+ if (endpoint.startsWith('-') || !oneOf(rest, EXPLICIT_GET)) {
174
+ refuse('read', `${spelled(args)}, which is not \`gh api <path>\` with an explicit GET and nothing else but the diff's or the API version's header`);
175
+ }
176
+ } else if (!oneOf(args, READ_SUBCOMMANDS)) {
177
+ refuse('read', `${spelled(args)}, which its read allowlist does not name`);
178
+ }
179
+ return send(FORGE, args, { emitter, timeout, side: 'read' });
180
+ }
181
+
182
+ /**
183
+ * The argument names that name a board item. GitHub owns which they are (`D16`), and its IDs are
184
+ * opaque, so an item is recognised by the name of the argument carrying it and never by what its
185
+ * value looks like. Measured by introspecting the input of every `ProjectV2` mutation with gh
186
+ * 2.99.0 on 2026-09-25: `itemId` names the item in six of them, and `afterId` names a second one
187
+ * in `updateProjectV2ItemPosition`'s. `draftIssueId` and `contentId` name what an item holds, not
188
+ * the item.
189
+ */
190
+ const ITEM_ARGUMENTS = new Set(['itemId', 'afterId']);
191
+
192
+ /** Every argument and input-object field name in `args`, at any depth. */
193
+ function argumentNames(args) {
194
+ const names = [];
195
+ const visit = ({ name, value }) => {
196
+ names.push(name);
197
+ if (value.kind === 'object') value.fields.forEach(visit);
198
+ if (value.kind === 'list') value.values.forEach((held) => visit({ name: null, value: held }));
199
+ };
200
+ args.forEach(visit);
201
+ return names.filter(Boolean);
202
+ }
203
+
204
+ /** Every variable `args` reads, at any depth. */
205
+ function variablesIn(args) {
206
+ const found = [];
207
+ const visit = (value) => {
208
+ if (value.kind === 'variable') found.push(`$${value.name}`);
209
+ if (value.kind === 'object') value.fields.forEach((field) => visit(field.value));
210
+ if (value.kind === 'list') value.values.forEach(visit);
211
+ };
212
+ args.forEach((arg) => visit(arg.value));
213
+ return found;
214
+ }
215
+
216
+ /**
217
+ * The one mutation a write request sends, read for `runner`: its root field, which is the
218
+ * operation a write runner names and admits.
219
+ *
220
+ * A write is admitted only as `gh api graphql -f query=<document>` and nothing else, with every
221
+ * argument written in the document. A variable, a fragment at the root, a directive or a second
222
+ * root field each put what the request does somewhere the runner cannot name, so each is refused.
223
+ */
224
+ function mutationOf(runner, args) {
225
+ const [subcommand, endpoint, flag, query, ...rest] = args;
226
+ if (subcommand !== 'api' || endpoint !== 'graphql' || flag !== '-f' || !query?.startsWith('query=') || rest.length > 0) {
227
+ refuse(runner, `${spelled(args)}, which is not a GraphQL document sent as \`gh api graphql -f query=\` and nothing else`);
228
+ }
229
+ const operation = operationsOf(runner, query.slice('query='.length));
230
+ if (operation.type !== 'mutation') refuse(runner, `${named(operation)}, which is not a mutation`);
231
+ if (operation.selections.some((selection) => selection.kind === 'fragment')) {
232
+ refuse(runner, `${named(operation)}, which puts a fragment at its root`);
233
+ }
234
+ if (operation.selections.length > 1) {
235
+ refuse(runner, `a request carrying more than one operation: ${operation.selections.map((field) => field.name).join(', ')}`);
236
+ }
237
+ const [field] = operation.selections;
238
+ const directives = [...operation.directives, ...field.directives].map((directive) => `@${directive.name}`);
239
+ if (directives.length > 0) refuse(runner, `${field.name}, which carries ${directives.join(', ')}`);
240
+ const variables = variablesIn(field.arguments);
241
+ if (variables.length > 0 || operation.variables) {
242
+ refuse(runner, `${field.name}, whose arguments carry ${variables.join(', ') || 'declared variables'}, which the document does not show`);
243
+ }
244
+ return field;
245
+ }
246
+
247
+ /**
248
+ * The write that adds an option to the field holding the columns, which the schema-write runner
249
+ * admits only in the shape #212's spike found keeps every item's column
250
+ * (`docs/spikes/status-option-through-gh.md`, "Conclusion").
251
+ */
252
+ const OPTIONS_WRITE = 'updateProjectV2Field';
253
+
254
+ /** The operations the schema-write runner admits: creating a field and a label, and the options write. */
255
+ const SCHEMA_WRITES = new Set(['createProjectV2Field', 'createLabel', OPTIONS_WRITE]);
256
+
257
+ /**
258
+ * What an option of a single-select field is, and what way B sends back of every held option.
259
+ * GitHub requires a `color` and a `description` on every option sent (`ProjectV2SingleSelect-
260
+ * FieldOptionInput`, introspected with gh 2.99.0 on 2026-09-25), so a held option sent without
261
+ * its own is changed.
262
+ */
263
+ const OPTION_FIELDS = ['id', 'name', 'color', 'description'];
264
+
265
+ /**
266
+ * How way B writes each field of an option, as the parser reads it: the colour as an unquoted
267
+ * scalar, the rest as strings. A held option carries all four; a new one carries all but its `id`.
268
+ * An unquoted scalar is any bare name, number or `null`, so which colour it names is checked
269
+ * against `OPTION_COLOURS` separately.
270
+ */
271
+ const OPTION_KINDS = { id: 'string', name: 'string', color: 'scalar', description: 'string' };
272
+
273
+ /**
274
+ * The values of GitHub's `ProjectV2SingleSelectFieldOptionColor`, the type GitHub gives `color`
275
+ * on `ProjectV2SingleSelectFieldOptionInput`. GitHub owns them (`D16`); this copy is what gh
276
+ * 2.99.0 answered to `__type(name: "ProjectV2SingleSelectFieldOptionColor") { enumValues { name } }`
277
+ * on 2026-09-25.
278
+ */
279
+ const OPTION_COLOURS = new Set(['GRAY', 'BLUE', 'GREEN', 'YELLOW', 'ORANGE', 'RED', 'PINK', 'PURPLE']);
280
+
281
+ /**
282
+ * Refuses the schema write `field` unless its options are written one way: its arguments each
283
+ * given once, an `input` object giving each of its fields once, and, where that input gives
284
+ * `singleSelectOptions`, a list of objects each giving each of its fields once and a `color`
285
+ * written as an unquoted value of `OPTION_COLOURS`. So a quoted colour, `null`, a number, a
286
+ * boolean, another name, no colour, a lone option given where the list belongs, and any field or
287
+ * argument given twice are each refused, naming the write. A write carrying no options, as
288
+ * creating a label does, has nothing here to refuse.
289
+ */
290
+ function checkColours(field) {
291
+ const args = fieldsOf('schema-write', field, field.arguments);
292
+ const input = args.input?.kind === 'object' ? fieldsOf('schema-write', field, args.input.fields) : {};
293
+ const options = input.singleSelectOptions;
294
+ if (options === undefined) return;
295
+ if (options.kind !== 'list') refuse('schema-write', `${field.name}, whose singleSelectOptions is not a list`);
296
+ for (const option of options.values) {
297
+ if (option.kind !== 'object') refuse('schema-write', `${field.name}, which sends an option that is not an object`);
298
+ const { name, color } = fieldsOf('schema-write', field, option.fields);
299
+ if (color?.kind !== 'scalar' || !OPTION_COLOURS.has(color.value)) {
300
+ refuse('schema-write', `${field.name}, which sends the option ${name?.value ?? 'with no name'} with a color that is no value of ProjectV2SingleSelectFieldOptionColor`);
301
+ }
302
+ }
303
+ }
304
+
305
+ /**
306
+ * The options a field holds, each `{ id, name, color, description }`, and the field's name, read
307
+ * through the read runner, sent as `via` says. A read that fails throws, naming what `gh` said, so
308
+ * no write follows.
309
+ */
310
+ async function heldOptions(fieldId, via) {
311
+ const query = `query { field: node(id: ${literal(fieldId)}) { ... on ProjectV2SingleSelectField { name options { id name color description } } } }`;
312
+ const said = await readRunner(graphqlRequest(query), via);
313
+ if (said.status !== 0) {
314
+ throw new Error(`the schema-write runner could not read the options of ${fieldId}, and sent no write: ${firstLine(said)}`);
315
+ }
316
+ const { data } = JSON.parse(said.stdout);
317
+ return { name: data?.field?.name, options: data?.field?.options ?? [] };
318
+ }
319
+
320
+ /** The fields of an input object `field` carries, by name, or `runner`'s refusal naming one given twice. */
321
+ function fieldsOf(runner, field, fields) {
322
+ const read = {};
323
+ for (const { name, value } of fields) {
324
+ if (Object.hasOwn(read, name)) refuse(runner, `${field.name}, whose input gives ${name} twice`);
325
+ read[name] = value;
326
+ }
327
+ return read;
328
+ }
329
+
330
+ /**
331
+ * The field ID and the options an options write sends, each option as its fields' values by
332
+ * name, or a refusal naming what is not way B's: one `input` of a `fieldId` string and a
333
+ * `singleSelectOptions` list, each option a name, colour and description written as
334
+ * `OPTION_KINDS` says and an `id` or none, no `id` twice, and at least one option with no `id`,
335
+ * which is the option the write adds.
336
+ */
337
+ function optionsInput(field) {
338
+ const [input, ...others] = field.arguments;
339
+ const read = input?.name === 'input' && input.value.kind === 'object' && others.length === 0 ? fieldsOf('schema-write', field, input.value.fields) : null;
340
+ const extra = read ? Object.keys(read).filter((name) => name !== 'fieldId' && name !== 'singleSelectOptions') : [];
341
+ if (!read || extra.length > 0 || read.fieldId?.kind !== 'string' || read.singleSelectOptions?.kind !== 'list') {
342
+ refuse('schema-write', `${field.name}, whose input is not a fieldId and singleSelectOptions alone${extra.length > 0 ? `: it carries ${extra.join(', ')}` : ''}`);
343
+ }
344
+ const sent = read.singleSelectOptions.values.map((option) => {
345
+ if (option.kind !== 'object') refuse('schema-write', `${field.name}, which sends an option that is not an object`);
346
+ const entry = fieldsOf('schema-write', field, option.fields);
347
+ const foreign = Object.keys(entry).filter((name) => !Object.hasOwn(OPTION_KINDS, name));
348
+ if (foreign.length > 0) refuse('schema-write', `${field.name}, which sends an option carrying ${foreign.join(', ')}`);
349
+ const wrong = Object.keys(OPTION_KINDS).filter((name) => (name !== 'id' || entry.id) && entry[name]?.kind !== OPTION_KINDS[name]);
350
+ if (wrong.length > 0) {
351
+ refuse('schema-write', `${field.name}, which sends an option whose ${wrong.join(', ')} is not given as way B gives it`);
352
+ }
353
+ return Object.fromEntries(Object.entries(entry).map(([name, value]) => [name, value.value]));
354
+ });
355
+ const twice = sent.filter((entry, i) => entry.id !== undefined && sent.findIndex((other) => other.id === entry.id) !== i);
356
+ if (twice.length > 0) refuse('schema-write', `${field.name}, which sends ${twice.map((entry) => `${entry.name} (${entry.id})`).join(', ')} twice`);
357
+ if (!sent.some((entry) => entry.id === undefined)) refuse('schema-write', `${field.name}, which adds no option`);
358
+ return { fieldId: read.fieldId.value, sent };
359
+ }
360
+
361
+ /**
362
+ * Refuses the options write `field` unless it is #212's way B on the field holding the columns:
363
+ * its input is the field's ID and its options, and every option the field holds, as read now,
364
+ * is sent with its `id`, name, colour and description. Way C, the same options with no `id`, gave
365
+ * every option a new ID and cleared every item's column, so a held option sent without its `id`
366
+ * is refused like one left out. The options are read as `via` says.
367
+ */
368
+ async function checkOptionsWrite(field, via) {
369
+ const { fieldId, sent } = optionsInput(field);
370
+ checkColours(field);
371
+ const held = await heldOptions(fieldId, via);
372
+ if (held.name !== COLUMNS) {
373
+ refuse('schema-write', `${field.name} on ${held.name ?? 'a field'} (${fieldId}), which is not the field holding the columns`);
374
+ }
375
+ const request = `${field.name} on ${COLUMNS} (${fieldId})`;
376
+ const dropped = held.options.filter((option) => !sent.some((entry) => entry.id === option.id));
377
+ if (dropped.length > 0) {
378
+ const named = dropped.map((option) => `${option.name} (${option.id})`).join(', ');
379
+ refuse('schema-write', `${request}, which does not send the held option${dropped.length > 1 ? 's' : ''} ${named} with its id`);
380
+ }
381
+ for (const option of held.options) {
382
+ const entry = sent.find((candidate) => candidate.id === option.id);
383
+ const differs = OPTION_FIELDS.filter((name) => entry[name] !== option[name]);
384
+ if (differs.length > 0) {
385
+ refuse('schema-write', `${request}, which sends the held option ${option.name} (${option.id}) without its own ${differs.join(', ')}`);
386
+ }
387
+ }
388
+ const unheld = sent.filter((entry) => entry.id !== undefined && !held.options.some((option) => option.id === entry.id));
389
+ if (unheld.length > 0) {
390
+ const named = unheld.map((entry) => `${entry.name} (${entry.id})`).join(', ');
391
+ refuse('schema-write', `${request}, which sends ${named} with an id the field does not hold`);
392
+ }
393
+ return fieldId;
394
+ }
395
+
396
+ /**
397
+ * Sends one write to the board's fields or the repository's labels, and refuses any other
398
+ * request, including one on its allowlist whose arguments name a board item.
399
+ */
400
+ export async function schemaWriteRunner(args, { send = throughL0, emitter, timeout = FORGE_TIMEOUT } = {}) {
401
+ const field = mutationOf('schema-write', args);
402
+ const items = argumentNames(field.arguments).filter((name) => ITEM_ARGUMENTS.has(name));
403
+ if (items.length > 0) refuse('schema-write', `${field.name}, whose ${items.join(', ')} names a board item`);
404
+ if (!SCHEMA_WRITES.has(field.name)) refuse('schema-write', `${field.name}, which its allowlist does not hold`);
405
+ if (field.name === OPTIONS_WRITE) await checkOptionsWrite(field, { send, emitter, timeout });
406
+ else checkColours(field);
407
+ return send(FORGE, args, { emitter, timeout, side: 'schema-write' });
408
+ }
409
+
410
+ /** The operations the item-write runner admits: a column move and an issue added to the board. */
411
+ const ITEM_WRITES = new Set(['updateProjectV2ItemFieldValue', 'addProjectV2ItemById']);
412
+
413
+ /** The field holding the columns, whose options are the column display names (`ARCHITECTURE.md`). */
414
+ export const COLUMNS = 'Status';
415
+
416
+ /**
417
+ * The first line of what `gh` said, from its error stream first: a failed `gh api graphql` prints
418
+ * the whole response as one line on stdout and its message on stderr. A call the timeout ended is
419
+ * said to be that, whatever `gh` had printed by then.
420
+ */
421
+ export function firstLine(said) {
422
+ if (said.timedOut) return `${FORGE} ran past its timeout of ${said.timeout} ms, and L0 ended it`;
423
+ const lines = `${said.stderr ?? ''}\n${said.stdout ?? ''}`.split('\n').map((line) => line.trim());
424
+ return lines.find(Boolean) ?? `${FORGE} exited ${said.status} and said nothing`;
425
+ }
426
+
427
+ /**
428
+ * The fields of the one `input` a column move carries, each written as a string in the document,
429
+ * or a refusal naming what is not: a column move names its board, its item, its field and the
430
+ * option it sets, and nothing else.
431
+ */
432
+ function moveInput(field) {
433
+ const [input, ...others] = field.arguments;
434
+ const fields = input?.name === 'input' && input.value.kind === 'object' && others.length === 0 ? input.value.fields : null;
435
+ const read = fieldsOf('item-write', field, fields ?? []);
436
+ const option = read.value?.kind === 'object' && read.value.fields.length === 1 ? read.value.fields[0] : null;
437
+ const strings = ['projectId', 'itemId', 'fieldId'].every((name) => read[name]?.kind === 'string');
438
+ if (!fields || Object.keys(read).length !== 4 || !strings || option?.name !== 'singleSelectOptionId' || option.value.kind !== 'string') {
439
+ refuse('item-write', `${field.name}, whose input is not a projectId, itemId, fieldId and a value setting one singleSelectOptionId`);
440
+ }
441
+ return { projectId: read.projectId.value, fieldId: read.fieldId.value };
442
+ }
443
+
444
+ /** One board and one issue content ID, both written as strings and with no other input. */
445
+ function addInput(field) {
446
+ const [input, ...others] = field.arguments;
447
+ const fields = input?.name === 'input' && input.value.kind === 'object' && others.length === 0 ? input.value.fields : null;
448
+ const read = fieldsOf('item-write', field, fields ?? []);
449
+ if (!fields || Object.keys(read).length !== 2 || read.projectId?.kind !== 'string' || read.contentId?.kind !== 'string') {
450
+ refuse('item-write', `${field.name}, whose input is not a projectId and contentId alone`);
451
+ }
452
+ }
453
+
454
+ /**
455
+ * Which field of `projectId` holds the columns, and what the field `fieldId` is called, read
456
+ * through the read runner, sent as `via` says. A read that fails throws, naming what `gh` said, so
457
+ * no write follows.
458
+ */
459
+ async function columnsField(projectId, fieldId, via) {
460
+ const query = `query { project: node(id: ${literal(projectId)}) { ... on ProjectV2 { field(name: ${literal(COLUMNS)}) { ... on ProjectV2SingleSelectField { id } } } } target: node(id: ${literal(fieldId)}) { ... on ProjectV2FieldCommon { name } } }`;
461
+ const said = await readRunner(graphqlRequest(query), via);
462
+ if (said.status !== 0) {
463
+ throw new Error(`the item-write runner could not read which field holds the columns, and sent no write: ${firstLine(said)}`);
464
+ }
465
+ const { data } = JSON.parse(said.stdout);
466
+ return { id: data?.project?.field?.id, target: data?.target?.name };
467
+ }
468
+
469
+ /**
470
+ * Sends an issue addition or a column move, and refuses any other item write. For a column move,
471
+ * the runner reads which field holds the columns rather than taking the field from the caller.
472
+ */
473
+ export async function itemWriteRunner(args, { send = throughL0, emitter, timeout = FORGE_TIMEOUT } = {}) {
474
+ const field = mutationOf('item-write', args);
475
+ if (!ITEM_WRITES.has(field.name)) refuse('item-write', `${field.name}, which its allowlist does not hold`);
476
+ if (field.name === 'addProjectV2ItemById') {
477
+ addInput(field);
478
+ return send(FORGE, args, { emitter, timeout, side: 'item-write' });
479
+ }
480
+ const { projectId, fieldId } = moveInput(field);
481
+ const columns = await columnsField(projectId, fieldId, { send, emitter, timeout });
482
+ if (columns.id !== fieldId) {
483
+ refuse('item-write', `a field-value write on ${columns.target ?? 'a field'} (${fieldId}), which is not the field holding the columns`);
484
+ }
485
+ return send(FORGE, args, { emitter, timeout, side: 'item-write' });
486
+ }
487
+
488
+ /** Sends only a head-guarded merge, a comment, a label addition or removal, or an issue opening or closing. */
489
+ export async function repositoryWriteRunner(args, { send = throughL0, emitter, timeout = FORGE_TIMEOUT } = {}) {
490
+ const [api, path, method, verb, field, value, option, mergeMethod, ...extra] = args;
491
+ const merge = api === 'api' && /^repos\/[^/]+\/[^/]+\/pulls\/[1-9]\d*\/merge$/.test(path ?? '')
492
+ && method === '-X' && verb === 'PUT' && field === '-f' && /^sha=[0-9a-f]{40}$/.test(value ?? '')
493
+ && option === '-f' && mergeMethod === 'merge_method=merge' && extra.length === 0;
494
+ const post = api === 'api' && method === '-X' && verb === 'POST' && field === '-f' && args.length === 6;
495
+ const comment = post && /^repos\/[^/]+\/[^/]+\/issues\/[1-9]\d*\/comments$/.test(path ?? '')
496
+ && typeof value === 'string' && value.startsWith('body=');
497
+ const label = post && /^repos\/[^/]+\/[^/]+\/issues\/[1-9]\d*\/labels$/.test(path ?? '')
498
+ && typeof value === 'string' && value.startsWith('labels[]=');
499
+ const open = api === 'api' && /^repos\/[^/]+\/[^/]+\/issues$/.test(path ?? '')
500
+ && method === '-X' && verb === 'POST' && field === '-f' && typeof value === 'string' && value.startsWith('title=') && value.length > 'title='.length
501
+ && option === '-f' && typeof mergeMethod === 'string' && mergeMethod.startsWith('body=') && mergeMethod.length > 'body='.length
502
+ && extra.length >= 2 && extra.length % 2 === 0 && extra.every((word, index) => index % 2 === 0 ? word === '-f'
503
+ : typeof word === 'string' && word.startsWith('labels[]=') && word.length > 'labels[]='.length);
504
+ const close = api === 'api' && /^repos\/[^/]+\/[^/]+\/issues\/[1-9]\d*$/.test(path ?? '')
505
+ && method === '-X' && verb === 'PATCH' && field === '-f' && value === 'state=closed' && args.length === 6;
506
+ const removeLabel = api === 'api' && /^repos\/[^/]+\/[^/]+\/issues\/[1-9]\d*\/labels\/[^/]+$/.test(path ?? '')
507
+ && method === '-X' && verb === 'DELETE' && args.length === 4;
508
+ if (!merge && !comment && !label && !open && !close && !removeLabel) refuse('repository-write', spelled(args));
509
+ return send(FORGE, args, { emitter, timeout, side: 'repository-write' });
510
+ }
@@ -0,0 +1,70 @@
1
+ // ABOUTME: The forge adapter's schema-write side: creating a board field, adding a column and
2
+ // creating a repository label, each sent through the schema-write runner. Only the CLI's verbs
3
+ // reach it.
4
+
5
+ import { literal } from './graphql.mjs';
6
+ import { answerOf, boardOf, repositoryOf } from './read.mjs';
7
+ import { firstLine, graphqlRequest, schemaWriteRunner } from './runners.mjs';
8
+ import { written } from './write-made.mjs';
9
+
10
+ /**
11
+ * The colours a new field option and a new label are given. GitHub requires one for each (the
12
+ * `color` of `ProjectV2SingleSelectFieldOptionInput` and of `CreateLabelInput` are both non-null,
13
+ * introspected on 2026-09-25), and nothing in the config declares one, so these are a choice: the
14
+ * neutral grey each palette offers.
15
+ */
16
+ const OPTION_COLOUR = 'GRAY';
17
+ const LABEL_COLOUR = 'ededed';
18
+
19
+ /**
20
+ * The schema writes on `board`, which names its `repo`, its `project` number and, where the config
21
+ * declares one, its `owner`, each read and write sent with `emitter` and `timeout` as the read side
22
+ * sends its reads. `send` stands in for the runners' spawn in tests. No write here is
23
+ * read back to confirm it, for the reason the column move gives (`item-write.mjs`): `gh` exiting
24
+ * 0 is the write.
25
+ */
26
+ export function schemaWriteSide(board, { send, emitter, timeout } = {}) {
27
+ const via = { send, emitter, timeout };
28
+ /**
29
+ * Sends the mutation `document` for `operation`, whose root field is `root`, and reads its answer.
30
+ * A refused event on the call is marked made where the call exited 0 within its timeout and its
31
+ * answer's `data` holds `root`, non-null. The root tells the write's answer from that of the
32
+ * runner's own read inside the same call (`heldOptions`), whose `data` holds no such field.
33
+ */
34
+ const write = async (operation, root, document) => {
35
+ const made = (said) => {
36
+ if (said.timedOut) throw new Error(firstLine(said));
37
+ if (answerOf(operation, board, said)?.[root] == null) throw new Error(`${operation} on board ${board.project} answered no ${root}`);
38
+ };
39
+ answerOf(operation, board, await written(schemaWriteRunner(graphqlRequest(document), via), made));
40
+ };
41
+ return {
42
+ /** Creates the single-select field `name` holding `options`, in the order given. */
43
+ createField: async (name, options) => {
44
+ const { id } = await boardOf('createField', board, via);
45
+ const held = options.map((option) => `{name: ${literal(option)}, color: ${OPTION_COLOUR}, description: ""}`);
46
+ const create = `mutation { createProjectV2Field(input: {projectId: ${literal(id)}, dataType: SINGLE_SELECT, name: ${literal(name)}, singleSelectOptions: [${held.join(', ')}]}) { projectV2Field { ... on ProjectV2SingleSelectField { id } } } }`;
47
+ await write('createField', 'createProjectV2Field', create);
48
+ },
49
+ /**
50
+ * Adds the column `name`, an option of the field holding the columns, after the options the
51
+ * field holds. It sends every held option back with its `id`, name, colour and description,
52
+ * and the new one without an `id`: #212's way B, which kept every item's column where way C,
53
+ * the same options without their `id`, cleared them all
54
+ * (`docs/spikes/status-option-through-gh.md`, "Conclusion").
55
+ */
56
+ createColumn: async (name) => {
57
+ const { columns } = await boardOf('createColumn', board, via);
58
+ const held = columns.options.map((option) => `{id: ${literal(option.id)}, name: ${literal(option.name)}, color: ${option.color}, description: ${literal(option.description)}}`);
59
+ const added = `{name: ${literal(name)}, color: ${OPTION_COLOUR}, description: ""}`;
60
+ const update = `mutation { updateProjectV2Field(input: {fieldId: ${literal(columns.id)}, singleSelectOptions: [${[...held, added].join(', ')}]}) { projectV2Field { ... on ProjectV2SingleSelectField { id } } } }`;
61
+ await write('createColumn', 'updateProjectV2Field', update);
62
+ },
63
+ /** Creates the label `name` in the board's repository. */
64
+ createLabel: async (name) => {
65
+ const repositoryId = await repositoryOf('createLabel', board, via);
66
+ const create = `mutation { createLabel(input: {repositoryId: ${literal(repositoryId)}, name: ${literal(name)}, color: ${literal(LABEL_COLOUR)}}) { label { id } } }`;
67
+ await write('createLabel', 'createLabel', create);
68
+ },
69
+ };
70
+ }
@@ -0,0 +1,40 @@
1
+ // ABOUTME: The forge write sides' shared mark for a write the forge made, including a side's own
2
+ // refusal of its answer, and the mark's carry through a side's rewrap of a failure.
3
+
4
+ import { EVENT_REFUSED } from '../process.mjs';
5
+
6
+ /**
7
+ * Awaits `call`, a write side's one write call, and answers what it resolves with, unread. A
8
+ * rejection with `EVENT_REFUSED` carrying the call's result means the call ran and only an event
9
+ * of it went unrecorded. Where `check`, the side's own success check, passes on that result, the
10
+ * forge made the write: the failure is marked `made`, holding `check`'s parsed answer as `answer`,
11
+ * and rethrown. `check` is handed the result as the runners hand a resolved call's, its output as
12
+ * text. A check's own refusal marked made retains that mark and its reason alongside the refused
13
+ * event. Any other rejection passes on unmarked.
14
+ */
15
+ export async function written(call, check) {
16
+ try {
17
+ return await call;
18
+ } catch (failure) {
19
+ if (failure?.code === EVENT_REFUSED && failure.result !== undefined) {
20
+ const { exit, timedOut, stdout, stderr } = failure.result;
21
+ try {
22
+ failure.made = { answer: check({ status: exit, timedOut, stdout: String(stdout), stderr: String(stderr) }) };
23
+ } catch (refusal) {
24
+ if (refusal.made !== undefined) {
25
+ failure.made = refusal.made;
26
+ failure.message = `${refusal.message}; ${failure.message}`;
27
+ }
28
+ }
29
+ }
30
+ throw failure;
31
+ }
32
+ }
33
+
34
+ /** `failure`, a side's rewrap of `original`, given the original's code, result, unrecorded events and mark. */
35
+ export function carried(failure, original) {
36
+ for (const key of ['code', 'result', 'unrecorded', 'made']) {
37
+ if (original?.[key] !== undefined) failure[key] = original[key];
38
+ }
39
+ return failure;
40
+ }