@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,46 @@
1
+ // ABOUTME: L3's pull order: redos ahead of Ready cards, each group by declared priority and then
2
+ // oldest first, with the cards L2 refuses reported beside it.
3
+
4
+ /**
5
+ * A card's rank under the declared order, lower pulled first: its option's place in it. A card with
6
+ * no value and a card whose value the declaration does not name share the rank below every option.
7
+ * With no declared order, every card holds the one rank.
8
+ */
9
+ const rankOf = (card, declared) => {
10
+ if (!declared) return 0;
11
+ return card.priority.declared ? declared.indexOf(card.priority.value) : declared.length;
12
+ };
13
+
14
+ /**
15
+ * The pull order over `items`, the board's cards as L0 hands them, each carrying its `column` and
16
+ * its `priority` as `{ value, declared }`, or null where no order is declared, with `columns`,
17
+ * the declared columns by key, and `declared`, the declared priority options highest rank first,
18
+ * or null where none is declared.
19
+ * `decide` is L2's next action for a card.
20
+ *
21
+ * A card in the `ready` column is a Ready card. A card in `coding`, `review` or `owner` is a
22
+ * redo. No card in any other column is offered to L2. An answer to dispatch or judge, move,
23
+ * continue, return, escalate, merge or remove enters the pull order; an ignore does not. Returns `pulls`,
24
+ * each with `card` and `redo`, and the fields of L2's answer; for a judge answer, `judges` names
25
+ * the roles L2 named, first
26
+ * pulled first, and `refusals`,
27
+ * each `{ card, reason }` as L2 gave it. A card L2 ignores is in neither.
28
+ */
29
+ export function pullOrder({ items, columns, declared }, decide) {
30
+ const redoColumns = [columns.coding, columns.review, columns.owner];
31
+ const pulls = [];
32
+ const refusals = [];
33
+ for (const card of items) {
34
+ const redo = redoColumns.includes(card.column);
35
+ if (!redo && card.column !== columns.ready) continue;
36
+ const next = decide(card);
37
+ if (next.action === 'dispatch') pulls.push({ card, kind: next.kind, redo });
38
+ if (next.action === 'judge') pulls.push({ card, kind: next.kind, redo, judges: next.judges.map((judge) => judge.role) });
39
+ if (['move', 'continue', 'return', 'escalate', 'merge', 'remove'].includes(next.action)) pulls.push({ card, redo, ...next });
40
+ if (next.action === 'refuse') refusals.push({ card: next.card, reason: next.reason });
41
+ }
42
+ pulls.sort((a, b) => Number(b.redo) - Number(a.redo)
43
+ || rankOf(a.card, declared) - rankOf(b.card, declared)
44
+ || a.card.number - b.card.number);
45
+ return { pulls: pulls.map(({ card, ...pull }) => ({ card: card.number, ...pull })), refusals };
46
+ }
@@ -0,0 +1,147 @@
1
+ // ABOUTME: L0's push side: the one write that sets the data ref, refs/rigger/events on origin, to
2
+ // a commit holding the whole event stream, never forced ("Pushing the stream").
3
+
4
+ import { gitEnvironment } from './git-environment.mjs';
5
+ import { EVENT_REFUSED, runCommand } from './process.mjs';
6
+
7
+ /** Every push's time limit, in milliseconds, over the whole push (`R-RECORD-17`). */
8
+ export const PUSH_TIMEOUT = 30_000;
9
+
10
+ /** The data ref on `origin`, the one ref the push side writes (boundary rule 2). */
11
+ export const DATA_REF = 'refs/rigger/events';
12
+
13
+ /** The remote the push names, which exists only on the push's own command line. */
14
+ const PUSH_REMOTE = 'rigger-data-push';
15
+
16
+ /**
17
+ * The exit code of a `git` that died, as `commit-tree` does on a parent the store lacks, measured
18
+ * with git 2.54.0. A refused object write exits 1 instead.
19
+ */
20
+ const MISSING_PARENT = 128;
21
+
22
+ /** The message every stream commit carries. */
23
+ const MESSAGE = 'rigger: the event stream';
24
+
25
+ /**
26
+ * Pushes `stream`, the stream's bytes as L5 read them, to the data ref on `origin` of the
27
+ * repository at `repository`, by origin's one push URL, and answers how the push went: `{ outcome,
28
+ * bytes, parent, commit, reason }`, each field present where "The outcome" says a `push.end` line
29
+ * holds it.
30
+ *
31
+ * Every `git` call goes through `spawn`, which has `runCommand`'s contract and is `runCommand`
32
+ * unless the caller hands another, with `emitter` for the process adapter's kill events and the
33
+ * environment `gitEnvironment` gives of `environment`, with prompts off. The whole push has
34
+ * `limit` milliseconds on the clock `now` reads, `PUSH_TIMEOUT` unless the caller hands a shorter
35
+ * one, and each call is handed what is left of it.
36
+ */
37
+ export async function pushStream({ repository, stream, emitter, limit = PUSH_TIMEOUT, spawn: run = runCommand, now = Date.now, environment = process.env }) {
38
+ const start = now();
39
+ const env = { ...gitEnvironment(environment), GIT_TERMINAL_PROMPT: '0' };
40
+ // "The commit": the stream up to and including its last newline, so a line still being appended
41
+ // waits for the next push.
42
+ const held = stream.subarray(0, stream.lastIndexOf(0x0a) + 1);
43
+ // The fields every answer carries, `parent` joining them once the tip is read.
44
+ const known = { bytes: held.length };
45
+ /**
46
+ * Runs git with `args`, handing it `input`, and hands back what it printed, as text. A call its
47
+ * timeout ended ends the push as timed out, in the process adapter's own phrase for that.
48
+ */
49
+ const git = async (args, input) => {
50
+ const timeout = limit - (now() - start);
51
+ // `runCommand` starts nothing given no positive timeout, and the push has then run out of time.
52
+ if (timeout <= 0) throw new Ended('timed-out', `the push's limit of ${limit} ms was spent before git ${subcommandIn(args)} started`);
53
+ const result = await run({ command: 'git', args, cwd: repository, env, input, timeout, emitter });
54
+ if (result.timedOut) throw new Ended('timed-out', `the timeout of ${timeout} ms ended git ${subcommandIn(args)}`);
55
+ return { ...result, stdout: result.stdout.toString('utf8'), stderr: result.stderr.toString('utf8') };
56
+ };
57
+ /** Runs git as `git` does, ending the push as failed, in git's words, where it exits non-zero. */
58
+ const needed = async (args, input) => {
59
+ const result = await git(args, input);
60
+ if (result.exit !== 0) throw new Ended('failed', printed(result));
61
+ return result.stdout;
62
+ };
63
+ const steps = async () => {
64
+ // A tip holding an empty copy would read as an empty record over a full stream.
65
+ if (held.length === 0) throw new Ended('failed', 'the stream\'s bytes hold no complete line, so the push wrote nothing');
66
+ // Every step addresses the one URL a push to `origin` goes to, so the guard, the parent and
67
+ // the write name one repository, and a fetch mapping of origin's gets no ref to update.
68
+ const urls = (await needed(['remote', 'get-url', '--push', '--all', 'origin'])).split('\n').filter(Boolean);
69
+ // One URL only: a push to one of several would reach that one alone.
70
+ if (urls.length !== 1) throw new Ended('failed', `origin has ${urls.length} push URLs, ${urls.join(', ') || 'none'}, where the push needs exactly one, so the push wrote nothing`);
71
+ const [url] = urls;
72
+ // The push names a remote that exists only on its own command line; one the consumer's
73
+ // configuration also names would lend it that remote's settings, so the push stops there.
74
+ const named = await git(['config', '--get-regexp', '^remote\\.rigger-data-push\\.']);
75
+ if (named.exit === 0 || named.stdout.trim() !== '') throw new Ended('failed', `the consumer's configuration names a remote ${PUSH_REMOTE}, which the push uses for itself, so the push wrote nothing`);
76
+ if (named.exit !== 1) throw new Ended('failed', printed(named));
77
+ const { parent, other } = tipIn(await needed(['ls-remote', url, DATA_REF, 'refs/remotes/refs/rigger/events/HEAD']));
78
+ if (parent !== undefined) known.parent = parent;
79
+ if (other !== undefined) throw new Ended('failed', `${url} holds ${other}, to which git push would resolve ${DATA_REF}, so the push wrote nothing`);
80
+ const blob = (await needed(['hash-object', '-w', '--stdin'], held)).trim();
81
+ const tree = (await needed(['mktree'], `100644 blob ${blob}\tevents.jsonl\n`)).trim();
82
+ const committed = (onto) => git(['commit-tree', tree, ...(onto === undefined ? [] : ['-p', onto]), '-m', MESSAGE]);
83
+ let built = await committed(parent);
84
+ if (built.exit === MISSING_PARENT && parent !== undefined) {
85
+ // None of the allowed calls asks whether the store holds an object in words that do not
86
+ // depend on the locale. `commit-tree` checks its parent before it writes anything and dies,
87
+ // exiting 128, where the store lacks it; a refused object write is an error, exiting 1. So
88
+ // the tip is taken as lacking only where the commit onto it died and a commit with no parent
89
+ // can then be built. Only then is it fetched.
90
+ if ((await committed(undefined)).exit !== 0) throw new Ended('failed', printed(built));
91
+ await needed(['fetch', '--no-write-fetch-head', url, parent]);
92
+ built = await committed(parent);
93
+ }
94
+ if (built.exit !== 0) throw new Ended('failed', printed(built));
95
+ const commit = built.stdout.trim();
96
+ // A push to a bare URL still updates the tracking ref of a configured remote with that URL
97
+ // under git 2.56, so the push names a remote whose one URL is <url> and which has no fetch
98
+ // mapping: it exists only here, and git matches no other remote to a configured one.
99
+ const sent = await git(['-c', `remote.${PUSH_REMOTE}.url=${url}`, 'push', '--porcelain', '--no-signed', '--no-verify', PUSH_REMOTE, `${commit}:${DATA_REF}`]);
100
+ if (sent.exit !== 0) throw new Ended(rejected(sent.stdout) ? 'refused' : 'failed', printed(sent));
101
+ return { outcome: 'pushed', ...known, commit };
102
+ };
103
+ try {
104
+ return await steps();
105
+ } catch (failure) {
106
+ if (failure instanceof Ended) return { outcome: failure.outcome, ...known, reason: failure.reason };
107
+ // A refused event here is one of the process adapter's kill events, which goes to L3's halt
108
+ // and never into an outcome ("Failure model").
109
+ if (failure?.code === EVENT_REFUSED) throw failure;
110
+ return { outcome: 'failed', ...known, reason: failure.message };
111
+ }
112
+ }
113
+
114
+ /** How a push that did not succeed ended, thrown from the step that ended it. */
115
+ class Ended {
116
+ constructor(outcome, reason) {
117
+ this.outcome = outcome;
118
+ this.reason = reason;
119
+ }
120
+ }
121
+
122
+ /**
123
+ * Whether `git push --porcelain` printed a rejected status for the data ref: a line `!`, a tab,
124
+ * `<commit>:refs/rigger/events`, a tab and the reason, as git's documentation for `--porcelain`
125
+ * gives it.
126
+ */
127
+ const rejected = (porcelain) => porcelain.split('\n').some((line) => line.startsWith('!\t') && line.split('\t')[1]?.endsWith(`:${DATA_REF}`));
128
+
129
+ /** The `git` subcommand in `args`, the first argument after any `-c` option and its value. */
130
+ const subcommandIn = (args) => (args[0] === '-c' ? args[2] : args[0]);
131
+
132
+ /** What a `git` call printed, its standard error and then its standard output, trimmed. */
133
+ const printed = ({ stdout, stderr }) => `${stderr}${stdout}`.trim();
134
+
135
+ /**
136
+ * What `git ls-remote` printed, one `<object>\t<ref>` line a ref, read as the data ref's tip,
137
+ * `parent`, and the first other ref it printed, `other`, each undefined where there is none.
138
+ */
139
+ function tipIn(listing) {
140
+ const read = {};
141
+ for (const line of listing.split('\n').filter(Boolean)) {
142
+ const [object, ref] = line.split('\t');
143
+ if (ref === DATA_REF) read.parent = object;
144
+ else read.other ??= ref;
145
+ }
146
+ return read;
147
+ }
@@ -0,0 +1,5 @@
1
+ // ABOUTME: Where the forge adapter's assets land in a consumer's repository: GitHub reads its
2
+ // workflows from `.github/`, so the gate workflow `init` forks lands there.
3
+
4
+ /** The directory, under a consumer's repository, GitHub reads its workflows from. */
5
+ export const assets = '.github';
@@ -0,0 +1,258 @@
1
+ // ABOUTME: Reads a GraphQL document into its operations, each with its type, name and root
2
+ // fields, so the forge runners judge a request by what it asks rather than by its text.
3
+
4
+ /**
5
+ * The executable part of the GraphQL grammar (the October 2021 specification, section 2), which
6
+ * is every document `gh api graphql` sends. Type-system definitions are not read: a document
7
+ * holding one is not a request, and is refused as unreadable. A document this cannot read
8
+ * throws, and the runners treat that as a refusal, so a gap here fails closed.
9
+ */
10
+
11
+ const PUNCTUATORS = new Set(['!', '$', '&', '(', ')', ':', '=', '@', '[', ']', '{', '|', '}']);
12
+ const NAME = /[_A-Za-z][_0-9A-Za-z]*/y;
13
+ const NUMBER = /-?(?:0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/y;
14
+ const IGNORED = /(?:[\s,]|#[^\n\r]*)+/y;
15
+
16
+ /** The escapes a quoted string may carry, other than `\u`. */
17
+ const ESCAPES = { '"': '"', '\\': '\\', '/': '/', b: '\b', f: '\f', n: '\n', r: '\r', t: '\t' };
18
+
19
+ /** Reads the quoted string opening at `at`, and returns its value and where it ends. */
20
+ function quoted(source, at) {
21
+ let value = '';
22
+ let i = at + 1;
23
+ while (i < source.length) {
24
+ const char = source[i];
25
+ if (char === '"') return { value, end: i + 1 };
26
+ if (char === '\n' || char === '\r') break;
27
+ if (char !== '\\') {
28
+ value += char;
29
+ i += 1;
30
+ continue;
31
+ }
32
+ const escaped = source[i + 1];
33
+ if (Object.hasOwn(ESCAPES, escaped)) {
34
+ value += ESCAPES[escaped];
35
+ i += 2;
36
+ } else if (escaped === 'u') {
37
+ const code = source.slice(i + 2).match(/^(?:\{([0-9A-Fa-f]+)\}|([0-9A-Fa-f]{4}))/);
38
+ if (!code) break;
39
+ value += String.fromCodePoint(parseInt(code[1] ?? code[2], 16));
40
+ i += 2 + code[0].length;
41
+ } else {
42
+ break;
43
+ }
44
+ }
45
+ throw new Error(`a string opening at offset ${at} does not close`);
46
+ }
47
+
48
+ /** Reads the block string opening at `at`, returning its raw text: nothing here reads its value. */
49
+ function block(source, at) {
50
+ let i = at + 3;
51
+ while (i < source.length) {
52
+ if (source.startsWith('\\"""', i)) i += 4;
53
+ else if (source.startsWith('"""', i)) return { value: source.slice(at + 3, i), end: i + 3 };
54
+ else i += 1;
55
+ }
56
+ throw new Error(`a block string opening at offset ${at} does not close`);
57
+ }
58
+
59
+ /** The document's tokens, each `{ kind, value }`, where kind is punct, name, number or string. */
60
+ function tokens(source) {
61
+ const found = [];
62
+ let i = 0;
63
+ while (i < source.length) {
64
+ IGNORED.lastIndex = i;
65
+ if (IGNORED.test(source)) {
66
+ i = IGNORED.lastIndex;
67
+ continue;
68
+ }
69
+ const char = source[i];
70
+ if (source.startsWith('...', i)) {
71
+ found.push({ kind: 'punct', value: '...' });
72
+ i += 3;
73
+ } else if (PUNCTUATORS.has(char)) {
74
+ found.push({ kind: 'punct', value: char });
75
+ i += 1;
76
+ } else if (char === '"') {
77
+ const string = source.startsWith('"""', i) ? block(source, i) : quoted(source, i);
78
+ found.push({ kind: 'string', value: string.value });
79
+ i = string.end;
80
+ } else {
81
+ NAME.lastIndex = i;
82
+ NUMBER.lastIndex = i;
83
+ const match = NAME.exec(source) ?? NUMBER.exec(source);
84
+ if (!match) throw new Error(`\`${char}\` at offset ${i} is not GraphQL`);
85
+ found.push({ kind: match[0].match(/^[_A-Za-z]/) ? 'name' : 'number', value: match[0] });
86
+ i += match[0].length;
87
+ }
88
+ }
89
+ return found;
90
+ }
91
+
92
+ /**
93
+ * Reads `source` as an executable GraphQL document.
94
+ *
95
+ * Returns its `operations`, each `{ type, name, variables, directives, selections }`: `variables`
96
+ * is whether it declares any, and a selection is a `field` with its `name`, `arguments`,
97
+ * `directives` and `selections`, or a `fragment`, spread or inline. An argument's value is a
98
+ * `variable`, a `string`, a `list` of `values`, an `object` of `fields`, or a `scalar` for every
99
+ * other literal.
100
+ */
101
+ export function parseDocument(source) {
102
+ const list = tokens(source);
103
+ let at = 0;
104
+ const peek = (value) => list[at]?.value === value && list[at].kind !== 'string';
105
+ const take = (value) => {
106
+ if (!peek(value)) throw new Error(`expected \`${value}\` where the document has \`${list[at]?.value ?? 'its end'}\``);
107
+ at += 1;
108
+ };
109
+ const name = () => {
110
+ if (list[at]?.kind !== 'name') throw new Error(`expected a name where the document has \`${list[at]?.value ?? 'its end'}\``);
111
+ return list[at++].value;
112
+ };
113
+
114
+ function value() {
115
+ const token = list[at];
116
+ if (peek('$')) {
117
+ at += 1;
118
+ return { kind: 'variable', name: name() };
119
+ }
120
+ if (peek('[')) {
121
+ at += 1;
122
+ const values = [];
123
+ while (!peek(']')) values.push(value());
124
+ at += 1;
125
+ return { kind: 'list', values };
126
+ }
127
+ if (peek('{')) {
128
+ at += 1;
129
+ const fields = [];
130
+ while (!peek('}')) {
131
+ const key = name();
132
+ take(':');
133
+ fields.push({ name: key, value: value() });
134
+ }
135
+ at += 1;
136
+ return { kind: 'object', fields };
137
+ }
138
+ if (token?.kind === 'string') {
139
+ at += 1;
140
+ return { kind: 'string', value: token.value };
141
+ }
142
+ if (token?.kind === 'name' || token?.kind === 'number') {
143
+ at += 1;
144
+ return { kind: 'scalar', value: token.value };
145
+ }
146
+ throw new Error(`expected a value where the document has \`${token?.value ?? 'its end'}\``);
147
+ }
148
+
149
+ function args() {
150
+ const found = [];
151
+ if (!peek('(')) return found;
152
+ at += 1;
153
+ do {
154
+ const key = name();
155
+ take(':');
156
+ found.push({ name: key, value: value() });
157
+ } while (!peek(')'));
158
+ at += 1;
159
+ return found;
160
+ }
161
+
162
+ function directives() {
163
+ const found = [];
164
+ while (peek('@')) {
165
+ at += 1;
166
+ found.push({ name: name(), arguments: args() });
167
+ }
168
+ return found;
169
+ }
170
+
171
+ function type() {
172
+ if (peek('[')) {
173
+ at += 1;
174
+ type();
175
+ take(']');
176
+ } else {
177
+ name();
178
+ }
179
+ if (peek('!')) at += 1;
180
+ }
181
+
182
+ function selections() {
183
+ take('{');
184
+ const found = [];
185
+ do {
186
+ if (peek('...')) {
187
+ at += 1;
188
+ if (list[at]?.kind === 'name' && list[at].value !== 'on') {
189
+ found.push({ kind: 'fragment', name: name(), directives: directives() });
190
+ } else {
191
+ if (peek('on')) {
192
+ at += 1;
193
+ name();
194
+ }
195
+ found.push({ kind: 'fragment', name: null, directives: directives(), selections: selections() });
196
+ }
197
+ continue;
198
+ }
199
+ let field = name();
200
+ if (peek(':')) {
201
+ at += 1;
202
+ field = name();
203
+ }
204
+ const inner = { kind: 'field', name: field, arguments: args(), directives: directives(), selections: [] };
205
+ if (peek('{')) inner.selections = selections();
206
+ found.push(inner);
207
+ } while (!peek('}'));
208
+ at += 1;
209
+ return found;
210
+ }
211
+
212
+ const operations = [];
213
+ while (at < list.length) {
214
+ if (peek('{')) {
215
+ operations.push({ type: 'query', name: null, variables: false, directives: [], selections: selections() });
216
+ } else if (peek('fragment')) {
217
+ at += 1;
218
+ name();
219
+ take('on');
220
+ name();
221
+ directives();
222
+ selections();
223
+ } else if (peek('query') || peek('mutation') || peek('subscription')) {
224
+ const operation = { type: list[at++].value, name: null, variables: false };
225
+ if (list[at]?.kind === 'name') operation.name = name();
226
+ if (peek('(')) {
227
+ at += 1;
228
+ do {
229
+ take('$');
230
+ name();
231
+ take(':');
232
+ type();
233
+ if (peek('=')) {
234
+ at += 1;
235
+ value();
236
+ }
237
+ directives();
238
+ } while (!peek(')'));
239
+ at += 1;
240
+ operation.variables = true;
241
+ }
242
+ operation.directives = directives();
243
+ operation.selections = selections();
244
+ operations.push(operation);
245
+ } else {
246
+ throw new Error(`\`${list[at].value}\` begins no operation or fragment`);
247
+ }
248
+ }
249
+ if (operations.length === 0) throw new Error('the document holds no operation');
250
+ return { operations };
251
+ }
252
+
253
+ /**
254
+ * A GraphQL string literal holding `value`. JSON's string syntax is a subset of GraphQL's, and
255
+ * `JSON.stringify` escapes every quote, backslash and control character, so a value can never
256
+ * close the literal and write GraphQL of its own.
257
+ */
258
+ export const literal = (value) => JSON.stringify(String(value));
@@ -0,0 +1,74 @@
1
+ // ABOUTME: The forge adapter's item-write side: adding an issue and moving an item on the board,
2
+ // sent through the item-write runner. Only L2 reaches it.
3
+
4
+ import { literal } from './graphql.mjs';
5
+ import { answerOf, boardOf } from './read.mjs';
6
+ import { COLUMNS, firstLine, graphqlRequest, itemWriteRunner, readRunner } from './runners.mjs';
7
+ import { carried, written } from './write-made.mjs';
8
+
9
+ /**
10
+ * The check a refused event on an item write's call is marked made by: the call `said` exited 0
11
+ * within its timeout, and its answer's `data` holds the mutation's `root` field, non-null. The
12
+ * root tells the write's answer from that of the runner's own read inside the same call
13
+ * (`columnsField`), whose `data` holds no such field. Answers that field.
14
+ */
15
+ function mutated(operation, board, root) {
16
+ return (said) => {
17
+ if (said.timedOut) throw new Error(firstLine(said));
18
+ const answer = answerOf(operation, board, said)?.[root];
19
+ if (answer == null) throw new Error(`${operation} on board ${board.project} answered no ${root}`);
20
+ return answer;
21
+ };
22
+ }
23
+
24
+ /**
25
+ * The item writes on `board`, which names its `repo`, its `project` number and, where the config
26
+ * declares one, its `owner`, each read and write sent with `timeout` as the read side sends its
27
+ * reads. `send` stands in for the runners' spawn in tests.
28
+ */
29
+ export function itemWriteSide(board, { send, timeout } = {}) {
30
+ return {
31
+ /** Add one issue to the board by number, reading its node ID before the mutation. */
32
+ addIssue: async (number, emitter) => {
33
+ if (!Number.isSafeInteger(number) || number < 1) throw new Error(`addIssue on issue #${number} failed: not an issue number`);
34
+ const via = { send, emitter, timeout };
35
+ try {
36
+ const issue = await readRunner(['api', `repos/${board.repo}/issues/${number}`, '-X', 'GET'], via);
37
+ if (issue.status !== 0 || issue.timedOut) throw new Error(firstLine(issue));
38
+ const contentId = JSON.parse(issue.stdout).node_id;
39
+ if (typeof contentId !== 'string' || !contentId) throw new Error('the read answered no node id');
40
+ const { id } = await boardOf('addIssue', board, via);
41
+ const add = `mutation { addProjectV2ItemById(input: {projectId: ${literal(id)}, contentId: ${literal(contentId)}}) { item { id } } }`;
42
+ const added = mutated('addIssue', board, 'addProjectV2ItemById');
43
+ const said = await written(itemWriteRunner(graphqlRequest(add), via), (answer) => added(answer).item.id);
44
+ if (said.timedOut) throw new Error(firstLine(said));
45
+ return answerOf('addIssue', board, said).addProjectV2ItemById.item.id;
46
+ } catch (error) {
47
+ throw carried(new Error(`addIssue on issue #${number} failed: ${error.message}`, { cause: error }), error);
48
+ }
49
+ },
50
+ /**
51
+ * Moves board item `itemId` to the column the board displays as `column`: one write, setting
52
+ * that column's option of the field holding the columns.
53
+ *
54
+ * Nothing reads the board back to confirm it. #212's spike saw a read straight after a write
55
+ * miss that write, twice (`docs/spikes/status-option-through-gh.md`, "Incidental finding"), so
56
+ * a read-back could report a move that landed as one that did not. The write's own answer is
57
+ * what is read: `gh` exiting 0 is the move, and anything else fails the call.
58
+ *
59
+ * `emitter` is the `L0` emitter every kill in the move's reads and write is recorded through.
60
+ * Its caller opens it for the moved card, so a kill carries the card L0 never knows.
61
+ */
62
+ moveItem: async (itemId, column, emitter) => {
63
+ const via = { send, emitter, timeout };
64
+ const { id, columns } = await boardOf('moveItem', board, via);
65
+ const option = columns.options.find((held) => held.name === column);
66
+ if (!option) {
67
+ throw new Error(`moveItem on board ${board.project} failed: its ${COLUMNS} field has no option named ${column}`);
68
+ }
69
+ const move = `mutation { updateProjectV2ItemFieldValue(input: {projectId: ${literal(id)}, itemId: ${literal(itemId)}, fieldId: ${literal(columns.id)}, value: {singleSelectOptionId: ${literal(option.id)}}}) { projectV2Item { id } } }`;
70
+ const moved = mutated('moveItem', board, 'updateProjectV2ItemFieldValue');
71
+ answerOf('moveItem', board, await written(itemWriteRunner(graphqlRequest(move), via), (said) => { moved(said); }));
72
+ },
73
+ };
74
+ }