@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,517 @@
1
+ // ABOUTME: L0's workspace adapter: makes a branch worktree from main or a verified card head, or
2
+ // a detached worktree, removes one, and answers git questions about paths, branches and commits.
3
+ // Every git call it makes runs one at a time.
4
+
5
+ import { lstatSync, readFileSync, realpathSync, statSync } from 'node:fs';
6
+ import { basename, dirname, join, resolve } from 'node:path';
7
+
8
+ import { gitEnvironment } from './git-environment.mjs';
9
+ import { EVENT_REFUSED, NOT_STARTED, runCommand } from './process.mjs';
10
+
11
+ /**
12
+ * How long L0 lets one git call run before it kills the call's group, where the caller passes no
13
+ * other value. A judgment, not a measurement. Its premise is #426 (M3-S1)'s report, which timed a
14
+ * worktree's making at 57 ms and its removal at 51 ms on a clone of this repository, and a fetch
15
+ * against a held commit at 57 ms (`docs/spikes/git-operations-at-once.md`). A fetch across a
16
+ * network and a checkout of a large repository are unmeasured, so five minutes leaves them room,
17
+ * while a git that hangs holds an attempt back by no more than five minutes.
18
+ */
19
+ export const GIT_TIMEOUT = 300_000;
20
+
21
+ /**
22
+ * How many times L0 tries a fetch that another process's fetch beats to the remote-tracking ref,
23
+ * before it gives up (architect ruling 7, section 5). A judgment, not a measurement. Its premise is
24
+ * #426 (M3-S1)'s report: in every round of fetches at once, at least one succeeded, and the loser
25
+ * failed because the winner had already moved the ref, so a second try finds nothing left to race
26
+ * unless a third fetch starts meanwhile. Three tries allow for that third.
27
+ */
28
+ export const FETCH_TRIES = 3;
29
+
30
+ /** Causes L0 can distinguish while verifying a continuing line of work. */
31
+ export const LINE_MOVED = 'FORGE_LINE_MOVED';
32
+ export const LINE_DELETED = 'FORGE_LINE_DELETED';
33
+ export const FETCH_FAILED = 'FORGE_FETCH_FAILED';
34
+
35
+ /**
36
+ * Git's words for a fetch another process's fetch beat to a remote-tracking ref, and the ref.
37
+ *
38
+ * A copy of git's answer (`D16` rule 2), tied to git by `test/worktrees.test.mjs`, which has the
39
+ * real git print the refusal. Measured with git 2.54.0 and the `files` ref backend: a fetch that
40
+ * lost the race exits 1 with `error: cannot lock ref 'refs/remotes/origin/main': is at <sha> but
41
+ * expected <sha>` (#426 (M3-S1)'s report, "Failures, quoted"), and `git update-ref` moving a ref
42
+ * from a value it does not hold prints the same clause after `fatal: update_ref failed for ref
43
+ * '<ref>': `. Where git words it otherwise, such as under the `reftable` backend, which was not
44
+ * measured, the race is not retried and the fetch rejects with git's own words.
45
+ */
46
+ const RACED = /cannot lock ref '(refs\/remotes\/[^']+)': is at \S+ but expected \S+/;
47
+
48
+ /**
49
+ * The lock reason `git worktree add` writes while it makes a worktree, and takes away once it has.
50
+ *
51
+ * A copy of git's answer (`D16` rule 2), tied to git by `test/worktrees.test.mjs`, which has git
52
+ * list a worktree while `git worktree add` is making it. Measured with git 2.54.0 (Apple Git-157)
53
+ * on 2026-09-30, by a smudge filter reading the worktree's administrative files mid-add: the file
54
+ * `.git/worktrees/<name>/locked` held the 13 bytes `initializing\n`, under `LANG` `en_US.UTF-8` and
55
+ * again under `de_DE.UTF-8`, and `git worktree list --porcelain` printed `locked initializing`. That
56
+ * build printed its own messages in English under `de_DE.UTF-8` too, so whether a git that
57
+ * translates its messages writes other words is unmeasured. Where it does, the lock reads as a
58
+ * person's, and the attempt fails naming it rather than unlocking it.
59
+ */
60
+ export const ADDING = 'initializing';
61
+
62
+ /** The remote whose default branch is the main line. */
63
+ const ORIGIN = 'origin';
64
+
65
+ /**
66
+ * The tail of the one queue every git call this module makes waits in, whatever repository it is
67
+ * on. A call waits for the one before it to settle, however it settled.
68
+ *
69
+ * One queue for the process, rather than one per repository, because a repository has as many
70
+ * paths as it has working trees, and asking git which repository a path belongs to, by its common
71
+ * directory, is itself a git call no queue would yet hold. One engine runs per repository (`D11`),
72
+ * so the one queue holds that repository's calls alone. It reverses on a process serving several
73
+ * repositories, whose calls would then wait on one another's.
74
+ */
75
+ let tail = Promise.resolve();
76
+
77
+ /** Runs `step` once every call queued before it has settled, and settles as it does. */
78
+ function queued(step) {
79
+ const ran = tail.then(step);
80
+ tail = ran.then(() => {}, () => {});
81
+ return ran;
82
+ }
83
+
84
+ /**
85
+ * The adapter over the repository whose working tree is at `repository`. Every git call it makes
86
+ * runs through L0's process adapter under `gitEnvironment()`, in `repository`, as `git`, for at
87
+ * most `timeout` milliseconds, with its kills recorded through `emitter`.
88
+ * Removal sets `rejectFailedChecks`: a check that gives no answer then rejects, while a missing
89
+ * .git entry or administrative directory still reads as no linked worktree.
90
+ */
91
+ export function workspaces({ repository, emitter, git = 'git', timeout = GIT_TIMEOUT, rejectFailedChecks = false }) {
92
+ /** Runs git one call at a time, records its end, and hands back its result or recording refusal. */
93
+ const call = (args) => queued(async () => {
94
+ const began = performance.now();
95
+ let result, failure;
96
+ try {
97
+ result = await runCommand({ command: git, args, cwd: repository, env: gitEnvironment(), timeout, emitter });
98
+ } catch (error) {
99
+ if (![NOT_STARTED, EVENT_REFUSED].includes(error.code) || typeof emitter?.emit !== 'function' || error.startCause?.kind === 'dispatch-timeout') throw error;
100
+ failure = error;
101
+ result = error.result;
102
+ }
103
+ const { exit, timedOut, stdout, stderr } = result ?? {};
104
+ const operation = args[0] === '-C' ? args[2] : args[0];
105
+ const fields = { system: 'git', operation, ms: performance.now() - began, outcome: timedOut ? 'timed-out' : exit === 0 ? 'ok' : 'failed' };
106
+ try {
107
+ emitter.emit('call.end', fields);
108
+ } catch (cause) {
109
+ if (failure?.code === EVENT_REFUSED) {
110
+ failure.unrecorded.push({ event: 'call.end', ...fields, cause });
111
+ failure.message += `\ncall.end ${JSON.stringify(fields)} went unrecorded: ${cause.message}`;
112
+ throw failure;
113
+ }
114
+ throw Object.assign(new Error(`the sink refused L0's call.end ${JSON.stringify(fields)}, so it went unrecorded: ${cause.message}`, { cause: failure ?? cause }), {
115
+ code: EVENT_REFUSED, result, unrecorded: [{ event: 'call.end', ...fields, cause }],
116
+ });
117
+ }
118
+ if (failure) throw failure;
119
+ return { args, exit, timedOut, stdout: stdout.toString('utf8'), stderr: stderr.toString('utf8') };
120
+ });
121
+
122
+ /** Runs git with `args` and hands back what it printed, rejecting where it did not exit 0. */
123
+ const answer = async (args) => {
124
+ const result = await call(args);
125
+ if (result.exit !== 0) throw failed(git, result, timeout);
126
+ return result.stdout;
127
+ };
128
+
129
+ /**
130
+ * Fetches `branch` from `origin`, trying again, up to `FETCH_TRIES` tries in all, where another
131
+ * process's fetch beat this one to the remote-tracking ref, and recording each retry. A sink that
132
+ * refuses that record rejects the call with an `EVENT_REFUSED` failure naming it as unrecorded,
133
+ * and the fetch is not tried again.
134
+ *
135
+ * Naming the branch still updates its remote-tracking ref where the remote's fetch refspec
136
+ * covers it, measured with git 2.54.0, so an agent's own fetch in its worktree races this one on
137
+ * that ref, which no queue here can hold. `--no-write-fetch-head` leaves `FETCH_HEAD` alone.
138
+ */
139
+ const fetched = async (branch) => {
140
+ const args = ['fetch', '--no-write-fetch-head', ORIGIN, `refs/heads/${branch}`];
141
+ for (let tries = 1; ; tries += 1) {
142
+ const result = await call(args);
143
+ if (result.exit === 0 && !result.timedOut) return;
144
+ const ref = result.timedOut ? undefined : RACED.exec(result.stderr)?.[1];
145
+ if (ref === undefined) throw failed(git, result, timeout);
146
+ if (tries === FETCH_TRIES) {
147
+ throw new Error(`\`${[git, ...args].join(' ')}\` lost the race for ${ref} to another process's fetch on all ${FETCH_TRIES} tries: ${firstLine(result.stderr)}`);
148
+ }
149
+ try {
150
+ emitter.emit('fetch.retried', { ref, tries });
151
+ } catch (cause) {
152
+ const failure = new Error(`the sink refused L0's fetch.retried ${JSON.stringify({ ref, tries })}, so it went unrecorded, and L0 tried the fetch no more: ${cause.message}`, { cause });
153
+ throw Object.assign(failure, { code: EVENT_REFUSED, unrecorded: [{ event: 'fetch.retried', ref, tries, cause }] });
154
+ }
155
+ }
156
+ };
157
+
158
+ /**
159
+ * The main line: the branch `origin`'s `HEAD` names as the call begins, and the commit it holds,
160
+ * fetched into this repository.
161
+ *
162
+ * Asked of `origin` rather than read off `refs/remotes/origin/HEAD`, which a clone writes once
163
+ * and never moves, and which a repository need not hold at all.
164
+ *
165
+ * Measured with git 2.54.0: `git ls-remote --symref origin HEAD` prints `ref: refs/heads/<branch>`
166
+ * and `<sha>`, each followed by a tab and `HEAD`, and where `origin`'s `HEAD` is detached it
167
+ * prints the second line alone, which this rejects as naming no main line. The commit is the one
168
+ * `origin` answered with, which the fetch after it brings.
169
+ */
170
+ /**
171
+ * Each worktree `git worktree list --porcelain -z` lists: its path, `at`, as git holds it, the
172
+ * branch it has checked out, whether its `HEAD` is detached, and the reason it is locked, an
173
+ * empty one for a lock given none, or nothing where it is not locked. Measured with git 2.54.0:
174
+ * each worktree is a run of NUL-ended fields, `worktree <path>`, `HEAD <sha>`, then `branch
175
+ * refs/heads/<name>` or `detached`, then `locked` or `locked <reason>` where it is locked and
176
+ * `prunable <reason>` where its directory is gone, the run ended by a second NUL.
177
+ */
178
+ const listed = async () => {
179
+ const records = [];
180
+ for (const record of (await answer(['worktree', 'list', '--porcelain', '-z'])).split('\0\0')) {
181
+ const fields = record.split('\0').filter((field) => field !== '');
182
+ const at = fields.find((field) => field.startsWith('worktree '))?.slice('worktree '.length);
183
+ if (at === undefined) continue;
184
+ const branch = fields.find((field) => field.startsWith('branch refs/heads/'))?.slice('branch refs/heads/'.length);
185
+ const lock = fields.find((field) => field === 'locked' || field.startsWith('locked '));
186
+ records.push({ at, branch, detached: fields.includes('detached'), locked: lock === undefined ? undefined : lock.slice('locked '.length) });
187
+ }
188
+ return records;
189
+ };
190
+
191
+ const fetchMainLine = async () => {
192
+ const printed = await answer(['ls-remote', '--symref', ORIGIN, 'HEAD']);
193
+ const named = /^ref: refs\/heads\/(\S+)\tHEAD$/m.exec(printed);
194
+ const held = /^([0-9a-f]+)\tHEAD$/m.exec(printed);
195
+ if (!named || !held) throw new Error(`\`${git} ls-remote --symref ${ORIGIN} HEAD\` named no branch for ${ORIGIN}'s HEAD, so there is no main line: ${JSON.stringify(printed)}`);
196
+ const branch = named[1];
197
+ await fetched(branch);
198
+ return { branch, commit: held[1] };
199
+ };
200
+
201
+ /** The commit the forge holds for `branch`, or a refusal naming a deleted branch. */
202
+ const lineHead = async (branch) => {
203
+ const ref = `refs/heads/${branch}`;
204
+ const result = await call(['ls-remote', '--exit-code', ORIGIN, ref]);
205
+ if (result.exit === 2 && !result.timedOut) throw Object.assign(new Error(`${ORIGIN}'s ${ref} was deleted`), { code: LINE_DELETED });
206
+ if (result.exit !== 0 || result.timedOut) throw Object.assign(failed(git, result, timeout), { code: FETCH_FAILED });
207
+ const line = result.stdout.split('\n').find((each) => each.endsWith(`\t${ref}`));
208
+ if (line === undefined) throw Object.assign(new Error(`${ORIGIN} named no head for ${ref}: ${JSON.stringify(result.stdout)}`), { code: FETCH_FAILED });
209
+ return line.split('\t')[0];
210
+ };
211
+
212
+ /**
213
+ * Adds a worktree on `branch` at `commit`, resetting a local branch left by an attempt. A
214
+ * registration whose directory was deleted must be pruned first. `-B` resets the branch where
215
+ * it exists, and `--no-track` leaves the repository's shared config untouched. An add that
216
+ * fails may already have moved the branch, and is not retried (#426, M3-S1).
217
+ */
218
+ const addAt = async (path, branch, commit) => {
219
+ await answer(['worktree', 'prune']);
220
+ await answer(['worktree', 'add', '--quiet', '--no-track', '-B', branch, path, commit]);
221
+ };
222
+
223
+ return {
224
+ fetchMainLine,
225
+
226
+ /**
227
+ * A linked maker's own git directory and common objects, refs and logs, by real path.
228
+ * An absent common logs directory is named under its real parent without being made.
229
+ * An unresolved existing path or a main working tree is refused, never granted.
230
+ */
231
+ async gitDirectories(path) {
232
+ const [own, common] = (await answer(['-C', path, 'rev-parse', '--path-format=absolute', '--git-dir', '--git-common-dir'])).replace(/\n$/, '').split('\n');
233
+ if (realpathSync.native(own) === realpathSync.native(common)) throw new Error(`${path} is no linked worktree, so its common git directory cannot be granted`);
234
+ const directories = [own, ...['objects', 'refs'].map((name) => join(common, name))].map((directory) => realpathSync.native(directory));
235
+ const logs = join(realpathSync.native(common), 'logs');
236
+ try {
237
+ lstatSync(logs);
238
+ } catch (failure) {
239
+ if (failure.code !== 'ENOENT') throw failure;
240
+ return [...directories, logs];
241
+ }
242
+ return [...directories, realpathSync.native(logs)];
243
+ },
244
+
245
+ /** Reads the checked-out `branch`'s commit at the tip of its own linked workspace `path`. */
246
+ async tip(path, branch) {
247
+ if (!(await this.isWorktree(path))) throw new Error(`${path} is not a linked worktree of this repository`);
248
+ const checkedOut = (await answer(['-C', path, 'symbolic-ref', '--quiet', '--short', 'HEAD'])).trim();
249
+ if (checkedOut !== branch) throw new Error(`${path} holds branch ${checkedOut}, not ${branch}`);
250
+ return (await answer(['-C', path, 'rev-parse', '--verify', 'HEAD^{commit}'])).trim();
251
+ },
252
+
253
+ /** Makes a workspace at `path` with `branch` checked out at the main line's commit. */
254
+ async make(path, branch) {
255
+ const { commit } = await fetchMainLine();
256
+ await addAt(path, branch, commit);
257
+ },
258
+
259
+ /** Fetches the card's forge line only while its head is the one L2 read. */
260
+ async fetchLineAt(branch, expected) {
261
+ const compare = async () => {
262
+ const actual = await lineHead(branch);
263
+ if (actual !== expected) throw Object.assign(new Error(`${ORIGIN}'s ${branch} moved from ${expected} to ${actual}`), { code: LINE_MOVED });
264
+ };
265
+ await compare();
266
+ try {
267
+ await fetched(branch);
268
+ } catch (cause) {
269
+ if (cause.code === EVENT_REFUSED) throw cause;
270
+ throw Object.assign(cause, { code: FETCH_FAILED });
271
+ }
272
+ await compare();
273
+ let kind;
274
+ try {
275
+ kind = (await answer(['cat-file', '-t', expected])).trim();
276
+ } catch (cause) {
277
+ if (cause.code === EVENT_REFUSED) throw cause;
278
+ throw Object.assign(cause, { code: FETCH_FAILED });
279
+ }
280
+ if (kind !== 'commit') throw Object.assign(new Error(`${ORIGIN}'s ${branch} at ${expected} names a ${kind}, not a commit`), { code: FETCH_FAILED });
281
+ },
282
+
283
+ /** Makes the card's worktree at the already fetched forge head. */
284
+ async makeAt(path, branch, commit) {
285
+ await addAt(path, branch, commit);
286
+ },
287
+
288
+ /**
289
+ * Makes a worktree at `path` with its `HEAD` detached at `commit`, making no branch.
290
+ *
291
+ * Measured with git 2.54.0 (Apple Git-157) on 2026-10-01, where git's answer can differ from
292
+ * what L1 expects (`D16` rule 3). `--detach` makes no branch, and neither does a commit named by
293
+ * its object name, so `git for-each-ref refs/heads` prints the same before and after. Git makes
294
+ * every missing directory leading to `path`. Onto a directory that is there and not empty, it
295
+ * exits 128 with `fatal: '<path>' already exists`; with a commit the repository does not hold,
296
+ * it exits 128 with `fatal: invalid reference: <commit>` and makes no directory, not even the
297
+ * leading ones. It names the worktree's administrative directory after `path`'s last name,
298
+ * adding a number where one of that name is already registered, so two judges' `main` trees
299
+ * never share one. Like `make`, it prunes first, since a registration whose directory was
300
+ * deleted without git refuses an add at its path, exiting 128 with `fatal: '<path>' is a missing
301
+ * but already registered worktree`. A registration locked with `initializing`, as a killed `git
302
+ * worktree add` leaves it, is not pruned, and the add exits 128 with `fatal: '<path>' is a
303
+ * missing but locked worktree`.
304
+ */
305
+ async makeDetached(path, commit) {
306
+ await answer(['worktree', 'prune']);
307
+ await answer(['worktree', 'add', '--quiet', '--detach', path, commit]);
308
+ },
309
+
310
+ /**
311
+ * Whether the repository holds `commit` as a commit once it has fetched it from `origin`, and
312
+ * where it does not, why. Git decides what names a commit (`D16` rule 1): `commit` is taken
313
+ * only where git, asked to verify it, prints it back unchanged, so it is a full object name and
314
+ * never a branch, an abbreviation or a refspec that a fetch could write a ref from.
315
+ *
316
+ * Measured with git 2.54.0 on 2026-10-01: `git rev-parse --verify` prints back any full-length
317
+ * hexadecimal name in lower case whether or not the object is there, prints a branch's commit for
318
+ * its name, and exits 1 for an abbreviation and for `main:refs/heads/x`. A fetch of a commit the
319
+ * repository already holds exits 0 without asking `origin`; one `origin` holds, reachable from
320
+ * any of its branches, is fetched under protocol version 2; one it does not hold exits 128 with
321
+ * `fatal: remote error: upload-pack: not our ref <commit>`. A fetch that fails is read through
322
+ * the check after it, so a commit held already is held whatever the fetch answered. That check is
323
+ * `git cat-file -t`, which prints `commit` for a commit, `tag` for an annotated tag's own object,
324
+ * which a peeling check such as `<name>^{commit}` would take for the commit it tags, and exits
325
+ * 128 with `fatal: git cat-file: could not get object info` for an object the repository does not
326
+ * hold. A timeout rejects.
327
+ */
328
+ async holdsAfterFetch(commit) {
329
+ const named = await call(['rev-parse', '--verify', '--quiet', '--end-of-options', commit]);
330
+ if (named.timedOut) throw failed(git, named, timeout);
331
+ if (named.exit !== 0 || named.stdout.trim() !== commit) return { held: false, why: `git does not read ${commit} as a full object name` };
332
+ const fetch = await call(['fetch', '--no-write-fetch-head', '--end-of-options', ORIGIN, commit]);
333
+ if (fetch.timedOut) throw failed(git, fetch, timeout);
334
+ const held = await call(['cat-file', '-t', '--end-of-options', commit]);
335
+ if (held.timedOut) throw failed(git, held, timeout);
336
+ if (held.exit === 0 && held.stdout.trim() === 'commit') return { held: true };
337
+ if (held.exit === 0) return { held: false, why: `${commit} names a ${held.stdout.trim()}, not a commit` };
338
+ return { held: false, why: fetch.exit === 0 ? `the repository does not hold ${commit}` : firstLine(fetch.stderr) };
339
+ },
340
+
341
+ /**
342
+ * Removes the workspace at `path`, its directory and its registration, whatever an attempt
343
+ * left in it. `--force` removes a worktree holding changes or untracked files, which git
344
+ * otherwise refuses. Git itself refuses the repository's main working tree, exiting 128 with
345
+ * `fatal: '<path>' is a main working tree`, and forgets a registered worktree whose directory
346
+ * is already gone, exiting 0.
347
+ */
348
+ async remove(path) {
349
+ await answer(['worktree', 'remove', '--force', path]);
350
+ },
351
+
352
+ /**
353
+ * Whether `path` is a linked worktree of this repository: whether git, asked in `path`, finds
354
+ * `path` the top of a working tree whose common directory is this repository's, and whose own
355
+ * git directory is not that common directory, which is how the main working tree answers.
356
+ *
357
+ * Asked of what is at the path now, never read off `git worktree list`: git keeps listing a
358
+ * worktree whose directory was deleted, and a locked one is never marked `prunable`, so a
359
+ * plain directory, or another repository's worktree, made at a listed path would read as one.
360
+ *
361
+ * Measured with git 2.54.0, `git rev-parse --path-format=absolute --show-toplevel --git-dir
362
+ * --git-common-dir` prints the three paths a line each. In the main working tree the git
363
+ * directory and the common directory are one; in a linked worktree the git directory is
364
+ * `<common>/worktrees/<name>`; in a directory below either, the top level is the worktree's,
365
+ * not the directory's. Non-zero exits read as no unless `rejectFailedChecks` is set, when a
366
+ * git or filesystem check giving no answer rejects. A missing .git entry still answers no.
367
+ * After a non-zero exit, only ENOENT from lstat of the `gitdir:` target in the .git file
368
+ * answers no: an existing but unreadable administrative directory must leave the check failed.
369
+ * This distinguishes a dropped registration without interpreting git's diagnostic text.
370
+ * A timeout rejects in either mode. A path holding a newline would split the answer, and so
371
+ * is read as no.
372
+ */
373
+ async isWorktree(path) {
374
+ const real = realOrNothing(path, rejectFailedChecks);
375
+ if (real === undefined || !statSync(real).isDirectory()) return false;
376
+ if (rejectFailedChecks) {
377
+ // A linked worktree has its .git entry at its root. Absence proves this path is not one;
378
+ // an unreadable entry or a failed git question proves nothing and must reject.
379
+ try {
380
+ lstatSync(join(real, '.git'));
381
+ } catch (error) {
382
+ if (error.code === 'ENOENT') return false;
383
+ throw error;
384
+ }
385
+ }
386
+ const own = (await answer(['rev-parse', '--path-format=absolute', '--git-common-dir'])).trim();
387
+ const there = await call(['-C', real, 'rev-parse', '--path-format=absolute', '--show-toplevel', '--git-dir', '--git-common-dir']);
388
+ if (there.timedOut) throw failed(git, there, timeout);
389
+ if (there.exit !== 0) {
390
+ if (rejectFailedChecks) {
391
+ const target = /^gitdir: (.+)$/.exec(readFileSync(join(real, '.git'), 'utf8').split('\n')[0])?.[1];
392
+ if (target !== undefined) {
393
+ try {
394
+ lstatSync(resolve(real, target));
395
+ } catch (error) {
396
+ if (error.code === 'ENOENT') return false;
397
+ throw error;
398
+ }
399
+ }
400
+ throw failed(git, there, timeout);
401
+ }
402
+ return false;
403
+ }
404
+ const [top, gitDirectory, common] = there.stdout.split('\n').map((each) => realOrNothing(each, rejectFailedChecks));
405
+ return top === real && common === realOrNothing(own, rejectFailedChecks) && common !== undefined && gitDirectory !== common;
406
+ },
407
+
408
+ /**
409
+ * What git lists for the worktree registered at `path`, compared by real path, or nothing
410
+ * where it lists none: the branch it has checked out, whether its `HEAD` is detached, and the
411
+ * reason it is locked, an empty one for a lock given none, or nothing where it is not locked.
412
+ *
413
+ * Read from `git worktree list --porcelain -z`, as `listed` says, which git lists whether or
414
+ * not the directory is still there. The path is git's absolute one, which a registration whose
415
+ * directory is gone keeps, so both are compared by the real path of what is left of them.
416
+ */
417
+ async registration(path) {
418
+ const wanted = realOrLeft(path);
419
+ const held = (await listed()).find(({ at }) => realOrLeft(at) === wanted);
420
+ return held === undefined ? undefined : { branch: held.branch, detached: held.detached, locked: held.locked };
421
+ },
422
+
423
+ /**
424
+ * Every worktree of the repository git lists, its main worktree included, as `listed` reads
425
+ * them: its path `at` as git holds it, its branch, whether its `HEAD` is detached, and the
426
+ * reason it is locked.
427
+ */
428
+ async listing() {
429
+ return listed();
430
+ },
431
+
432
+ /**
433
+ * The path of every worktree of the repository git lists, its main worktree included, as git
434
+ * lists it, whether or not its directory is still there. Read as `registration` reads them.
435
+ */
436
+ async registered() {
437
+ return (await listed()).map(({ at }) => at);
438
+ },
439
+
440
+ /** Forgets registrations whose directories are gone, leaving person-locked registrations intact. */
441
+ async prune() {
442
+ await answer(['worktree', 'prune']);
443
+ },
444
+
445
+ /** Takes away the lock on the worktree registered at `path`, whether or not its directory is there. */
446
+ async unlock(path) {
447
+ await answer(['worktree', 'unlock', path]);
448
+ },
449
+
450
+ /**
451
+ * The real path, by `realpath(3)`, of the top of the working tree git finds for the path this
452
+ * adapter was handed, which, for a directory below a worktree, is the worktree's, not the
453
+ * directory's.
454
+ */
455
+ async topLevel() {
456
+ return realpathSync.native((await answer(['rev-parse', '--path-format=absolute', '--show-toplevel'])).replace(/\n$/, ''));
457
+ },
458
+
459
+ /**
460
+ * Whether git accepts `name` as a literal branch name, and where it does not, why (`D16` rule
461
+ * 1: git owns what a valid branch name is). A literal name is one git accepts and prints back
462
+ * unchanged: this compares git's printed name with the name asked, and copies no rule of git's
463
+ * (the architect's ruling 9 on #423).
464
+ *
465
+ * Measured with git 2.54.0, run in the repository: `rigger-1` exits 0 printing `rigger-1`, and
466
+ * `rigger-1.lock` exits 128 with `fatal: 'rigger-1.lock' is not a valid branch name`. Git's
467
+ * answer differs from the name asked where it expands previous-checkout syntax: `@{-1}`, with
468
+ * `owner-feature` the previous checkout, exits 0 printing `owner-feature`, and `@{-3}`, with
469
+ * fewer previous checkouts, exits 128. `@` exits 0 printing `@`, so it is a literal name there,
470
+ * which `git worktree add -B @` makes as `refs/heads/@`. Any non-zero exit is read as a refusal,
471
+ * so a git that fails for another reason answers no with its own words; one the timeout ended
472
+ * rejects.
473
+ */
474
+ async acceptsBranch(name) {
475
+ const result = await call(['check-ref-format', '--branch', name]);
476
+ if (result.timedOut) throw failed(git, result, timeout);
477
+ if (result.exit !== 0) return { accepted: false, why: firstLine(result.stderr) };
478
+ const printed = result.stdout.replace(/\n$/, '');
479
+ if (printed !== name) return { accepted: false, why: `git expands ${name} to ${printed}, so it is not a literal branch name` };
480
+ return { accepted: true };
481
+ },
482
+ };
483
+ }
484
+
485
+ /**
486
+ * `path`'s real path, or nothing where no file is there to resolve. The real path is the file
487
+ * system's own, `realpath(3)`, in the case the disk holds: git prints paths in that case, while
488
+ * Node's JavaScript `realpathSync` keeps the case it was handed, so on a volume that folds case
489
+ * two spellings of one directory would compare as two.
490
+ */
491
+ function realOrNothing(path, rejectFailed = false) {
492
+ try {
493
+ return realpathSync.native(path);
494
+ } catch (error) {
495
+ if (rejectFailed && error.code !== 'ENOENT') throw error;
496
+ return undefined;
497
+ }
498
+ }
499
+
500
+ /**
501
+ * `path`'s real path, or, where nothing is there, the real path of its parent joined to its name,
502
+ * or `path` itself where neither resolves: so a path whose directory is gone still compares by the
503
+ * real path of what is left of it.
504
+ */
505
+ function realOrLeft(path) {
506
+ return realOrNothing(path) ?? (realOrNothing(dirname(path)) === undefined ? path : join(realOrNothing(dirname(path)), basename(path)));
507
+ }
508
+
509
+ /** The failure for a git call that exited non-zero or that its timeout ended. */
510
+ function failed(git, { args, exit, timedOut, stderr }, timeout) {
511
+ const command = `\`${[git, ...args].join(' ')}\``;
512
+ if (timedOut) return new Error(`${command} ran past its timeout of ${timeout} ms, and L0 ended it`);
513
+ return new Error(`${command} exited ${exit}: ${firstLine(stderr)}`);
514
+ }
515
+
516
+ /** The first line of `text` holding anything but blanks. */
517
+ const firstLine = (text) => text.split('\n').find((line) => line.trim() !== '') ?? '';
@@ -0,0 +1,40 @@
1
+ // ABOUTME: Composes and reads a clock firing's mark and author in a card body.
2
+
3
+ const PREFIX = 'Rigger clock: ';
4
+
5
+ /** One inert line encoding the exact name and the occurrence's millisecond time value. */
6
+ export function composeClockMark(name, occurrence) {
7
+ if (typeof name !== 'string') throw new TypeError(`Invalid clock name: ${name}`);
8
+ if (!Number.isInteger(occurrence) || Math.abs(occurrence) > 8640000000000000) {
9
+ throw new RangeError(`Invalid clock occurrence: ${occurrence}`);
10
+ }
11
+ return PREFIX + JSON.stringify([name, occurrence]);
12
+ }
13
+
14
+ /** The pair named by a composed line, or null where the line is not a mark. */
15
+ export function parseClockMark(line) {
16
+ if (!line.startsWith(PREFIX)) return null;
17
+ try {
18
+ const pair = JSON.parse(line.slice(PREFIX.length));
19
+ if (!Array.isArray(pair) || pair.length !== 2) return null;
20
+ const [name, occurrence] = pair;
21
+ return composeClockMark(name, occurrence) === line ? { name, occurrence } : null;
22
+ } catch {
23
+ return null;
24
+ }
25
+ }
26
+
27
+ /** Whether any LF/CRLF-delimited body line is exactly this pair's composed mark. */
28
+ export function carriesClockMark(body, name, occurrence) {
29
+ return body.split(/\r?\n/).includes(composeClockMark(name, occurrence));
30
+ }
31
+
32
+ /** The author on the next nonempty line after a valid mark, preserved exactly as written. */
33
+ export function clockAuthor(body) {
34
+ const lines = body.split(/\r?\n/);
35
+ const mark = lines.findIndex((line) => parseClockMark(line) !== null);
36
+ if (mark < 0) return undefined;
37
+ const author = lines.slice(mark + 1).find((line) => line !== '');
38
+ const prefix = '**Author:** ';
39
+ return author?.startsWith(prefix) ? author.slice(prefix.length) : undefined;
40
+ }
@@ -0,0 +1,110 @@
1
+ // ABOUTME: The maker escalation note's syntax, its selection from issue comments, the escalation
2
+ // answer L2 gives for the selected note, and L2's one function answering each escalation's
3
+ // destination, the routing post and the escalation role's instruction.
4
+
5
+ import { CATEGORIES, OWNER, judgeRole } from '../config/validate.mjs';
6
+
7
+ import { acceptanceItems } from './form-check.mjs';
8
+ import { evidenceDigest, WRITERS } from './marker.mjs';
9
+
10
+ const DISPATCH = /^d-[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;
11
+ const POSITIVE = /^[1-9][0-9]*$/;
12
+ const FIELDS = ['category', 'item', 'reason', 'dispatch'];
13
+ const DISPATCH_SLOT = '<the dispatch id>';
14
+
15
+ /** The one block a maker writes, in the order the parser reads its fields. */
16
+ const blockLines = (fields) => ['```rigger-escalation', ...FIELDS.map((key) => `${key}: ${fields[key]}`), '```'];
17
+
18
+ /** The instruction's note form and its one-comment stop rule for a maker of `card`. */
19
+ export function escalationInstruction(card) {
20
+ return [
21
+ 'Where you cannot meet an acceptance item, write this block to `.rigger-escalation.md` in the directory this session started in, filling each field:',
22
+ ...blockLines({ category: '<recorded-decision, critical, or ambiguous>', item: '<the item ordinal>', reason: '<one line naming why>', dispatch: DISPATCH_SLOT }),
23
+ 'Count the item ordinal from 1 over the acceptance items in the evidence below, in order.',
24
+ `Write the note once, never edit it, then run exactly \`gh issue comment ${card.number} --body-file .rigger-escalation.md\` from the directory this session started in and end your session after posting it.`,
25
+ ].join('\n');
26
+ }
27
+
28
+ /** Puts L3's maker or escalation-role dispatch id in the answer the provider sees. */
29
+ export function dispatchedEscalation(answer, dispatch) {
30
+ return { ...answer, instruction: answer.instruction.replace(`dispatch: ${DISPATCH_SLOT}`, `dispatch: ${dispatch}`) };
31
+ }
32
+
33
+ /** A note under one fence, with the fields the maker's instruction names. */
34
+ export function parseEscalationNote(body, count) {
35
+ const lines = String(body).split(/\r?\n/);
36
+ const start = lines[0] === '```rigger-escalation' ? 0 : 1;
37
+ if (lines[start] !== '```rigger-escalation' || lines[start + 5] !== '```' || lines.slice(start + 6).some((line) => line !== '')) return null;
38
+ const fields = {};
39
+ for (const [at, key] of FIELDS.entries()) {
40
+ const line = lines[start + at + 1];
41
+ if (!line?.startsWith(`${key}: `)) return null;
42
+ fields[key] = line.slice(key.length + 2);
43
+ }
44
+ const item = Number(fields.item);
45
+ if (!CATEGORIES.includes(fields.category) || !POSITIVE.test(fields.item) || !Number.isSafeInteger(item) || item > count || !fields.reason || !DISPATCH.test(fields.dispatch)) return null;
46
+ return { category: fields.category, item, reason: fields.reason, dispatch: fields.dispatch };
47
+ }
48
+
49
+ /** The first unedited writer's note under `dispatch`, from comments in the forge's oldest-first order. */
50
+ export function makerNote(comments, dispatch, count) {
51
+ for (const comment of comments) {
52
+ if (!WRITERS.includes(comment.permission) || comment.edited) continue;
53
+ const note = parseEscalationNote(comment.body, count);
54
+ if (note?.dispatch === dispatch) return note;
55
+ }
56
+ return null;
57
+ }
58
+
59
+ /** L2's escalation answer, naming one open pull request and its head where the line holds one. */
60
+ export function makerEscalation(note, { line, open }) {
61
+ return {
62
+ action: 'escalate', raiser: 'maker', ...note, line,
63
+ ...(open.length === 1 ? { pull: open[0].number, head: open[0].head } : {}),
64
+ };
65
+ }
66
+
67
+ /** The routing comment's first line, by which L2 finds the comment on a card's issue, whoever wrote it. */
68
+ export const ROUTING_LINE = 'Rigger sends this card\'s ambiguous escalation to a role.';
69
+
70
+ /** Whether a comment in `comments`, the card's issue comments, opens with the routing comment's line. */
71
+ const routed = (comments) => comments.some((comment) => String(comment.body).split(/\r?\n/)[0] === ROUTING_LINE);
72
+
73
+ /**
74
+ * The one destination of an escalation (`ARCHITECTURE.md`, "Escalation"): the owner, or the role
75
+ * `escalate`, the configuration's destinations, names for its category. Only a maker's ambiguity
76
+ * goes to a role (`R-ESCALATE-15`), and a category given none goes to the owner (`R-ESCALATE-22`).
77
+ * It goes to the owner where `maker`, the card's kind's maker, or one of `judges`, its kind's
78
+ * judges, is that role (`R-ESCALATE-17`), and where `comments`, the card's issue comments, carry
79
+ * the routing comment (`R-ESCALATE-16`). A loop-raised escalation reads no comment.
80
+ */
81
+ export function escalationDestination({ category, raiser, escalate, maker, judges = [], comments = [] }) {
82
+ if (raiser !== 'maker' || category !== 'ambiguous') return OWNER;
83
+ const configured = escalate !== undefined && Object.hasOwn(escalate, category) ? escalate[category] : OWNER;
84
+ if (configured === OWNER || configured === maker || judges.map(judgeRole).includes(configured)) return OWNER;
85
+ return routed(comments) ? OWNER : configured;
86
+ }
87
+
88
+ /** The routing post's data, below its fixed first line. */
89
+ export function routingComment({ destination, category, item, reason, pull, head }) {
90
+ return [ROUTING_LINE, '', `Role: ${destination}`, `Category: ${category}`, `Acceptance item: ${item}`, reason,
91
+ ...(pull === undefined ? [] : [`Pull request: #${pull}`, `Head: ${head}`]), ''].join('\n');
92
+ }
93
+
94
+ /** The role receives the acceptance and maker's reason, with no judge evidence. */
95
+ export function escalationRoleInstruction(card, next) {
96
+ const acceptance = acceptanceItems(card.body ?? '');
97
+ const facts = { card: card.number, title: card.title, acceptance, category: next.category, item: next.item, reason: next.reason,
98
+ ...(next.pull === undefined ? {} : { pull: next.pull, head: next.head }) };
99
+ const instruction = [
100
+ `Rigger dispatched this session to handle an escalation for card #${card.number}.`,
101
+ "Only the card's author changes an acceptance.",
102
+ escalationInstruction(card), '',
103
+ `Card #${card.number}: ${card.title}`,
104
+ 'Acceptance:', ...acceptance.map((item) => `- ${item}`), '',
105
+ `Maker's ${next.category} note, acceptance item ${next.item}:`, next.reason,
106
+ ...(next.pull === undefined ? [] : [`Pull request: #${next.pull}`, `Head: ${next.head}`]), '',
107
+ ].join('\n');
108
+ const evidence = '';
109
+ return { instruction, evidence, digest: evidenceDigest(evidence), facts };
110
+ }