@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,1021 @@
1
+ // ABOUTME: The `doctor` verb: what it asks the tool that owns each fact, what it reports one line
2
+ // at a time, and the source tree it refuses to run against.
3
+
4
+ import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
5
+ import { basename, isAbsolute, join, relative, resolve, dirname, sep } from 'node:path';
6
+ import { fileURLToPath, pathToFileURL } from 'node:url';
7
+ import { types } from 'node:util';
8
+
9
+ import { gitEnvironment } from '../substrate/git-environment.mjs';
10
+ import { GH_MINIMUM, boardOf, readGhVersion, readSide } from '../substrate/forge/read.mjs';
11
+ import { COLUMNS, FORGE_TIMEOUT, readRunner } from '../substrate/forge/runners.mjs';
12
+ import { EVENT_REFUSED, NOT_STARTED, runCommand } from '../substrate/process.mjs';
13
+ import { ADAPTERS } from '../substrate/providers/adapters.mjs';
14
+ import { launchdExitTimeout, validate } from '../config/validate.mjs';
15
+ import { CONFIG } from './init.mjs';
16
+ import { STATE, recording } from './recording.mjs';
17
+ import { admission } from '../scheduling/admission.mjs';
18
+ import { repositoryReads } from '../substrate/forge/read.mjs';
19
+ import { GATE_CONTEXT } from '../workflow/gate.mjs';
20
+ import { loadedJob } from '../substrate/launchd.mjs';
21
+
22
+ /**
23
+ * Runs a command through L0's process adapter and hands back what it answered: its exit code as
24
+ * `status`, its output as text, and whether the timeout ended it. This is every authority the
25
+ * guard, `doctor` and `init` ask but the forge, which `ghVersion` and `ghAuth` ask through the
26
+ * forge adapter's read runner. The command runs in a group of its own, ended at `timeout`, and every process it
27
+ * leaves is killed and recorded through `emitter`. A command that never started, and a kill the sink
28
+ * refused, reject as the adapter rejects, each failure's `code` naming which.
29
+ *
30
+ * The environment is the one `gitEnvironment` hands a git child. A `doctor` run from inside a git
31
+ * hook, a `git rebase --exec` or a `git bisect run` inherits variables naming the repository that
32
+ * started it, and git honours those over the directory this verb was pointed at. Every authority
33
+ * here is asked about a named directory, so none may be redirected by the environment.
34
+ */
35
+ export async function asked(command, args, { emitter, timeout }) {
36
+ const { exit, timedOut, stdout, stderr } = await runCommand({ command, args, cwd: process.cwd(), env: gitEnvironment(), timeout, emitter });
37
+ return { status: exit, timedOut, stdout: stdout.toString('utf8'), stderr: stderr.toString('utf8') };
38
+ }
39
+
40
+ /**
41
+ * How long the guard's `git`, `init`'s read of `origin`, and each agent CLI probe may run before
42
+ * L0 kills its group. Every call that is not a dispatch passes the one L0 constant the forge
43
+ * adapter states (the architect's ruling 2, (g), on #332), and a test passes a value of its own.
44
+ */
45
+ export const CALL_TIMEOUT = FORGE_TIMEOUT;
46
+
47
+ /**
48
+ * The package this code is part of, which is the source tree `R-SAFE-5` is about.
49
+ *
50
+ * Taken from this module's own location rather than from `process.argv[1]` or the working
51
+ * directory, because neither answers where the running code lives: an installed bin is reached
52
+ * through a symlink in `node_modules/.bin`, and Node resolves that symlink before it sets
53
+ * `import.meta.url` — which is what makes an `npm link`ed engine resolve back to the checkout it
54
+ * was linked from, as `AGENTS.md`'s "Self-hosting" section says it must.
55
+ */
56
+ export const PACKAGE = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..');
57
+
58
+ /**
59
+ * The same directory, spelled the way the filesystem spells it.
60
+ *
61
+ * Every comparison below is between real paths, because a path is a name and two names for one
62
+ * directory are what a string comparison reads as two directories. Measured rather than reasoned,
63
+ * each on the host it occurs on:
64
+ *
65
+ * - `git rev-parse --show-toplevel` answers `C:/Users/...` on Windows where `process.cwd()`
66
+ * answers `C:\Users\...`, so the two never compare equal unless both are resolved. Measured
67
+ * with git 2.55.0 on Windows 11;
68
+ * - `realpathSync.native` answers the canonical casing on Windows, so a `c:\users\...` spelling
69
+ * of the checkout resolves to the `C:\Users\...` the same directory is listed under. Measured
70
+ * on the same host, where the lowercased path answered with the canonical one;
71
+ * - on macOS `os.tmpdir()` answers `/var/folders/...` while the same directory resolves to
72
+ * `/private/var/folders/...`, `/var` being a symlink. Measured by CI on macOS, which redded on
73
+ * one path resolved and the other not where this host's filesystem had let the pair through.
74
+ *
75
+ * A path that is not there is resolved as far as it can be and the rest carried across. Resolving
76
+ * only what exists whole is the asymmetry that makes two spellings of one tree compare unequal,
77
+ * and on macOS that is the everyday case rather than an edge: `/var/folders/x` and
78
+ * `/private/var/folders/x` are one directory, so a path this could not resolve is a path still
79
+ * spelled the other way. CI found it, on a comparison this host's filesystem let through.
80
+ */
81
+ export const real = (dir) => {
82
+ const full = resolve(dir);
83
+ try {
84
+ return realpathSync.native(full);
85
+ } catch {
86
+ const above = dirname(full);
87
+ // A root resolves to itself, which is what stops this where no segment can be read at all.
88
+ return above === full ? full : join(real(above), basename(full));
89
+ }
90
+ };
91
+
92
+ /**
93
+ * Whether one directory is another or sits beneath it.
94
+ *
95
+ * `relative` rather than a prefix comparison, because a prefix reads a sibling whose name starts
96
+ * with the same characters as a child: this repository's worktrees live in `rigger-worktrees/`
97
+ * beside the `rigger/` checkout, and `'rigger-worktrees/card-34'.startsWith('rigger')` is true.
98
+ * A worktree is where a dispatched maker works, so a check that refused one would refuse every
99
+ * card this engine is built by. Only a first step of `..` itself leaves `outer`: a child whose
100
+ * name begins with two dots, such as `..worktrees`, is inside it.
101
+ */
102
+ export function within(outer, inner) {
103
+ const step = relative(outer, inner);
104
+ return step === '' || (step !== '..' && !step.startsWith(`..${sep}`) && !isAbsolute(step));
105
+ }
106
+
107
+ /**
108
+ * Whether the tree being checked and the package doing the checking are one tree.
109
+ *
110
+ * Containment either way, because the two arrangements `R-SAFE-5` forbids sit either way about.
111
+ * A run from inside the checkout — its root, or `docs/` beneath it — has the target within the
112
+ * package. An engine installed into the target's own `node_modules` has the package within the
113
+ * target, which is the arrangement where an agent clearing that directory deletes the runtime
114
+ * mid-run. Equal paths are the plain case, and `within` reads them as either.
115
+ */
116
+ export function sameTree(target, packageRoot = PACKAGE) {
117
+ const [here, there] = [real(target), real(packageRoot)];
118
+ return within(there, here) || within(here, there);
119
+ }
120
+
121
+ /**
122
+ * The root of the repository a directory sits in, as git names it, as `{ root }`, or `{ root: null,
123
+ * why }` where git names none, `why` saying in one line what git answered instead.
124
+ *
125
+ * Git owns what a repository is, so it is asked (`D16` rule 1). Null rather than the directory
126
+ * handed in, because a fallback is this code answering the same question a weaker way: the whole
127
+ * point of asking is that a run from `<repo>/src` is compared as `<repo>`, and a git that
128
+ * declines must not narrow that back to `<repo>/src`. What to do about a tree git cannot name is
129
+ * the caller's to decide, and `doctor` refuses rather than compares.
130
+ *
131
+ * Where git's answer can differ from the directory handed in, measured by asking rather than
132
+ * reasoned about, with git 2.55.0: it walks up, so a run from `docs/` inside a checkout answers
133
+ * the checkout; and a directory that is no repository answers 128 with nothing on stdout, which
134
+ * is why the status is read before the output. A host with no git at all never starts it, and a
135
+ * git its timeout ended answers nothing that can be read.
136
+ *
137
+ * Git is asked through L0 (`asked`), with `emitter` for L0's kills and `timeout` for the call, and
138
+ * `ask` stands in for that in tests. A kill the sink refused rejects, as the adapter rejects.
139
+ */
140
+ export async function repoRoot(dir, options = {}) {
141
+ const { stdout, why, status } = await gitAnswer(['-C', dir, 'rev-parse', '--show-toplevel'], options);
142
+ return why === undefined ? { root: real(stdout.trim()) } : { root: null, why, status };
143
+ }
144
+
145
+ /**
146
+ * What git printed on standard output for `args`, as `{ stdout }`, where it ran and exited 0, or
147
+ * `{ why }`, one line saying what it answered instead: that it could not be run, that its timeout
148
+ * ended it, or the status it exited with and the first line it said.
149
+ *
150
+ * Git is asked through L0 (`asked`), with `emitter` for L0's kills and `timeout` for the call, and
151
+ * `ask` stands in for that in tests. A kill the sink refused rejects, as the adapter rejects.
152
+ */
153
+ export async function gitAnswer(args, { ask = asked, emitter, timeout = CALL_TIMEOUT } = {}) {
154
+ const spelled = `\`${['git', ...args].join(' ')}\``;
155
+ let said;
156
+ try {
157
+ said = await ask('git', args, { emitter, timeout });
158
+ } catch (failure) {
159
+ if (failure.code !== NOT_STARTED) throw failure;
160
+ return { why: `${spelled} could not be run here: ${oneLine(failure.message)}` };
161
+ }
162
+ if (said.timedOut) return { why: `the timeout of ${timeout} ms ended ${spelled}` };
163
+ if (said.status !== 0) return { why: `${spelled} exited ${said.status}: ${firstLine(said)}`, status: said.status };
164
+ return { stdout: said.stdout };
165
+ }
166
+
167
+ /**
168
+ * The one form of `engines.node` this reads: a single `>=` comparator over a dotted version.
169
+ *
170
+ * npm owns the range language, and this reads one comparator of it rather than restating the
171
+ * whole. Where npm's answer can differ from this one (`D16` rule 3), measured by writing the
172
+ * range and reading what comes back rather than reasoned about:
173
+ *
174
+ * - every other form npm accepts — `^20`, `20.x`, `>=20 <23`, `^20 || ^22` — is unread here, and
175
+ * a check that cannot read its floor says so rather than answering for a comparison it never
176
+ * made. `test/doctor.test.mjs` measures the four above;
177
+ * - npm reads a prerelease as below the release of the same numbers, where the comparison below
178
+ * drops the tag, so a Node built as `25.0.0-pre` satisfies a `>=25` floor here and would not
179
+ * under npm. Unmeasured against npm: no command it ships answers this question on its own, and
180
+ * a guess about how it would answer is what `D16` rule 3 exists to refuse.
181
+ */
182
+ const FLOOR = /^>=\s*(\d+(?:\.\d+)*)$/;
183
+
184
+ /** Whether a dotted version reaches a floor, each segment the floor names compared in turn. */
185
+ function reaches(running, floor) {
186
+ const has = running.split('-')[0].split('.').map(Number);
187
+ const wants = floor.split('.').map(Number);
188
+ for (const [index, want] of wants.entries()) {
189
+ const got = has[index] ?? 0;
190
+ if (got !== want) return got > want;
191
+ }
192
+ return true;
193
+ }
194
+
195
+ /**
196
+ * Whether the running Node reaches the floor this package declares.
197
+ *
198
+ * `package.json` owns the floor: it is what npm refuses an install against, so a number typed
199
+ * here would be a second answer to a question already answered (`D16` rule 1). Nothing is copied
200
+ * — the file is read at the moment the check runs — and the line names both numbers compared, so
201
+ * a consumer reads the floor rather than being told a verdict about it.
202
+ */
203
+ export function nodeVersion({ packageRoot = PACKAGE, running = process.versions.node } = {}) {
204
+ const name = 'Node version';
205
+ let declared;
206
+ try {
207
+ declared = JSON.parse(readFileSync(join(packageRoot, 'package.json'), 'utf8')).engines?.node;
208
+ } catch (threw) {
209
+ // A check that throws takes the whole report with it: the three checks below never run, and
210
+ // a consumer setting Rigger up sees a stack trace where a line per check belongs. Every other
211
+ // check here can say it could not look, and this one is no different.
212
+ return { name, ok: null, detail: `the floor could not be read from \`package.json\`: ${wentWrong(threw)}` };
213
+ }
214
+ const floor = typeof declared === 'string' ? declared.trim().match(FLOOR) : null;
215
+ if (!floor) {
216
+ return {
217
+ name,
218
+ ok: null,
219
+ detail: `\`engines.node\` says \`${declared}\`, which is no \`>=\` floor this reads, so `
220
+ + `Node ${running} was compared against nothing`,
221
+ };
222
+ }
223
+ return {
224
+ name,
225
+ ok: reaches(running, floor[1]),
226
+ detail: `Node ${running} against the \`${declared}\` this package declares`,
227
+ };
228
+ }
229
+
230
+ /**
231
+ * The first thing a piece of text says, and nothing after it.
232
+ *
233
+ * Every detail in the report is one line, because the report is a line per check and a detail
234
+ * that brought its own lines would break that shape wherever it landed — gh's account block and
235
+ * a thrown error's stack are both several lines long.
236
+ */
237
+ const oneLine = (text) => text.split('\n').map((line) => line.trim()).find(Boolean) ?? '';
238
+
239
+ /** What a command said, whichever stream it said it on, reduced to its first line. */
240
+ const firstLine = (said) => oneLine(`${said.stdout ?? ''}\n${said.stderr ?? ''}`);
241
+
242
+ /**
243
+ * One line saying what a thrown value was, whatever kind of value it is.
244
+ *
245
+ * `throw` takes any value, and the consumer's config is the one input here that is arbitrary code
246
+ * (`configValidity` below). Reading `.message` off it works only for the half of that input which
247
+ * happens to be an `Error`: it is `undefined` for a thrown string or plain object and unreadable
248
+ * on a thrown `null`, so reading it is a second throw — and that one escapes the check, `doctor`,
249
+ * the surface and the bin, and costs a consumer every line of the report. A check that says it
250
+ * could not look is the whole point of this file, and it cannot say that by throwing.
251
+ *
252
+ * Quoting the value is itself the consumer's code running: `String` calls a `toString` they
253
+ * supplied and `JSON.stringify` a `toJSON`, either of which can throw in its turn. What is left
254
+ * to say then is that it threw, which is still a line.
255
+ */
256
+ const wentWrong = (threw) => {
257
+ let said;
258
+ try {
259
+ const held = threw instanceof Error ? threw.message : threw;
260
+ said = oneLine(String((typeof held === 'string' ? held : JSON.stringify(held)) || threw));
261
+ } catch {
262
+ said = '';
263
+ }
264
+ return said || 'a value it could say nothing about';
265
+ };
266
+
267
+ /**
268
+ * Whether `gh` is authenticated, which is `gh auth status`'s answer and not this code's.
269
+ *
270
+ * `D16` rule 1: gh owns the fact. Its exit status is the whole of what is read — measured with
271
+ * gh 2.96.0 as 0 authenticated and 1 not — and the line carries gh's own first line so a
272
+ * consumer reads what to do about it. `--show-token` is never passed: it is the one argument
273
+ * that would put a credential into a report (`AGENTS.md`, never log a secret), and the read
274
+ * runner's allowlist admits the request only without it.
275
+ *
276
+ * It is a forge read, so it goes through the forge adapter's read runner, which names the command
277
+ * (the architect's ruling on #214, R214-B4), with `emitter` for L0's kills. A `gh` L0 could not
278
+ * start is reported as unasked, and every other failure of the call is the call's own to report.
279
+ * `ask` stands in for the runner's spawn in tests.
280
+ */
281
+ export async function ghAuth({ ask, emitter } = {}) {
282
+ const name = 'gh authentication';
283
+ let said;
284
+ try {
285
+ said = await readRunner(['auth', 'status'], { send: ask, emitter });
286
+ } catch (failure) {
287
+ if (failure.code !== NOT_STARTED) throw failure;
288
+ return { name, ok: null, detail: `\`gh auth status\` could not be run here: ${oneLine(failure.message)}` };
289
+ }
290
+ return { name, ok: said.status === 0, detail: `\`gh auth status\` exited ${said.status}: ${firstLine(said)}` };
291
+ }
292
+
293
+ /**
294
+ * Whether the installed gh is a release at or above the minimum Rigger requires, which is the
295
+ * forge adapter's reading of `gh --version` reported by `versionLine`.
296
+ *
297
+ * The read goes through the forge adapter's read runner, as `ghAuth`'s does, with `emitter` for
298
+ * L0's kills, and `ask` stands in for the runner's spawn in tests.
299
+ */
300
+ export async function ghVersion({ ask, emitter } = {}) {
301
+ try {
302
+ return versionLine(await readGhVersion({ send: ask, emitter }));
303
+ } catch (failure) {
304
+ if (failure.code !== NOT_STARTED) throw failure;
305
+ return versionLine({ unstarted: oneLine(failure.message) });
306
+ }
307
+ }
308
+
309
+ /**
310
+ * The `gh version` line for a version read, `readGhVersion`'s plain data or `{ unstarted }` naming
311
+ * why gh could not be run, its version compared with the minimum number by number. A gh that
312
+ * could not be run, exited non-zero, ran past its timeout, or named no release is reported as
313
+ * unasked: no comparison was made. Every detail is one line.
314
+ */
315
+ export function versionLine(read) {
316
+ const line = (ok, detail) => ({ name: 'gh version', ok, detail });
317
+ if (read.unstarted !== undefined) return line(null, `\`gh --version\` could not be run here: ${read.unstarted}`);
318
+ if (read.timedOut) return line(null, `\`gh --version\` ran past its timeout of ${read.timeout} ms, and L0 ended it`);
319
+ if (read.status !== 0) return line(null, `\`gh --version\` exited ${read.status}, so no version was read`);
320
+ if (read.version === null) return line(null, `\`gh --version\` began \`${printable(read.line)}\`, which names no release as \`gh version <major>.<minor>.<patch>\`; Rigger requires gh ${GH_MINIMUM} or later`);
321
+ const ok = reaches(read.version, GH_MINIMUM);
322
+ return line(ok, ok ? `gh ${read.version} against the ${GH_MINIMUM} Rigger requires` : `gh ${read.version} is below the ${GH_MINIMUM} Rigger requires; install gh ${GH_MINIMUM} or later`);
323
+ }
324
+
325
+ /** The verdict a set of them folds to: unknown if any is, failed if any is, passed otherwise. */
326
+ const folded = (verdicts) => {
327
+ if (verdicts.length === 0 || verdicts.includes(null)) return null;
328
+ return !verdicts.includes(false);
329
+ };
330
+
331
+ /**
332
+ * The adapters whose CLIs `doctor` asks for the consumer in `target`: those of every provider the
333
+ * config it holds can dispatch, where that config earns no refusals, and every adapter in the map
334
+ * otherwise, as where it is handed no `target` (the architect's ruling 18 on #467). A config can
335
+ * dispatch each role's `provider` and `providerLabels` values, and each judge entry's fixed
336
+ * provider and map values (`D24` rule 1). A consumer that uses no Codex sees no Codex line it
337
+ * cannot act on (`R-OPTION-1`).
338
+ */
339
+ async function adaptersAsked(target) {
340
+ if (target === undefined) return ADAPTERS;
341
+ const { config } = await consumerConfig(target);
342
+ const refusals = config === undefined ? undefined : validate(config);
343
+ if (refusals === undefined || refusals.length > 0) return ADAPTERS;
344
+ const rules = Object.values(config.kinds).flatMap((kind) => kind.judges.flatMap((entry) => {
345
+ if (typeof entry === 'string') return [];
346
+ return typeof entry.provider === 'string' ? [entry.provider] : Object.values(entry.provider);
347
+ }));
348
+ const named = new Set([
349
+ ...Object.values(config.roles).flatMap((role) => [role.provider, ...Object.values(role.providerLabels ?? {})]),
350
+ ...rules,
351
+ ]);
352
+ return Object.fromEntries(Object.entries(ADAPTERS).filter(([provider]) => named.has(provider)));
353
+ }
354
+
355
+ /**
356
+ * Whether each agent CLI is authenticated, which is that CLI's answer and not this code's.
357
+ *
358
+ * `D16` rule 1: each CLI owns whether it is signed in. Each adapter names the question in `auth`
359
+ * and reads the answer with its own `signedIn`, which answers true, false, or unknown (the
360
+ * architect's ruling 18 on #467), so this code holds no reader of any CLI's words. An answer the
361
+ * adapter reads as neither is reported unread, never as a refusal.
362
+ *
363
+ * `adapters` are the adapters asked, where the caller hands them; otherwise those `adaptersAsked`
364
+ * answers for `target`. Each CLI is asked through L0 (`asked`), with `emitter` for L0's kills and
365
+ * `timeout` for the call. A CLI L0 could not start, or whose timeout ended it, is reported unread,
366
+ * and a kill the sink refused rejects, as the adapter rejects. `ask` stands in for that in tests.
367
+ */
368
+ export async function agentAuth({ ask = asked, adapters, target, emitter, timeout = CALL_TIMEOUT } = {}) {
369
+ const name = 'agent CLI authentication';
370
+ const verdicts = [];
371
+ const lines = [];
372
+ for (const adapter of Object.values(adapters ?? await adaptersAsked(target))) {
373
+ const [command, ...args] = adapter.auth;
374
+ const spelled = `\`${[command, ...args].join(' ')}\``;
375
+ let said;
376
+ try {
377
+ said = await ask(command, args, { emitter, timeout });
378
+ } catch (failure) {
379
+ if (failure.code !== NOT_STARTED) throw failure;
380
+ verdicts.push(null);
381
+ lines.push(`${spelled} could not be run here: ${oneLine(failure.message)}`);
382
+ continue;
383
+ }
384
+ const state = said.timedOut ? undefined : adapter.signedIn(said);
385
+ if (said.timedOut) {
386
+ verdicts.push(null);
387
+ lines.push(`the timeout of ${timeout} ms ended ${spelled}, so nothing was read from it`);
388
+ } else if (typeof state !== 'boolean') {
389
+ verdicts.push(null);
390
+ lines.push(`${spelled} exited ${said.status} and said nothing its adapter reads as signed in or out, so nothing was read from it`);
391
+ } else {
392
+ verdicts.push(state);
393
+ lines.push(`${spelled} says it is signed ${state ? 'in' : 'out'}`);
394
+ }
395
+ }
396
+ return { name, ok: folded(verdicts), detail: lines.join('; ') };
397
+ }
398
+
399
+ /**
400
+ * Whether the config the consumer holds is one Rigger accepts, which is the validator's answer.
401
+ *
402
+ * `src/config/validate.mjs` decides what Rigger accepts, and every refusal it gives is carried
403
+ * here word for word: a second reading of the config living in this file would be a second answer
404
+ * to a question already answered, drifting from the first the day the validator gains a rule.
405
+ *
406
+ * The entry point refuses an import failure or a value that is not plain data before validation.
407
+ * What the report carries is the first line of what went wrong, never the error: a
408
+ * stack of Node's own frames tells a consumer nothing about the file they have to fix, and the
409
+ * card asks for a line per check without one.
410
+ */
411
+ export async function configValidity({ target = process.cwd() } = {}) {
412
+ const name = 'config validity';
413
+ const { config, problem } = await consumerConfig(target);
414
+ if (problem) return { name, ok: false, detail: problem };
415
+ const refusals = validate(config);
416
+ return {
417
+ name,
418
+ ok: refusals.length === 0,
419
+ detail: refusals.length === 0
420
+ ? `\`${CONFIG}\` earns no refusals`
421
+ : `\`${CONFIG}\`: ${refusals.map(oneLine).join('; ')}`,
422
+ };
423
+ }
424
+
425
+ /** The answer of each config file read in this process, by the real path of its directory. */
426
+ const held = new Map();
427
+
428
+ /**
429
+ * The config the consumer holds in `target`, as `{ config }`, or `{ problem }` saying in one line
430
+ * why there is none to read: the file is not there, importing it threw, or its default export is
431
+ * not plain data. Every verb that reads the config reads it here, so the one dynamic import of the
432
+ * consumer's code is this one, and it runs once per file and process: each later call answers a
433
+ * fresh copy of the first answer (boundary rule 4).
434
+ */
435
+ export async function consumerConfig(target) {
436
+ const path = join(target, CONFIG);
437
+ const file = join(real(target), CONFIG);
438
+ if (!held.has(file)) {
439
+ let read;
440
+ try {
441
+ read = existsSync(path) ? copied((await import(pathToFileURL(path))).default)
442
+ : { problem: `\`${CONFIG}\` is not in ${target}, and \`rigger init\` is what writes it` };
443
+ } catch (threw) {
444
+ read = { problem: `\`${CONFIG}\` could not be read: ${wentWrong(threw)}` };
445
+ }
446
+ held.set(file, read);
447
+ }
448
+ const { config, problem } = held.get(file);
449
+ return problem ? { problem } : copied(config);
450
+ }
451
+
452
+ /** How deep a config may nest: far past any extension point, and short of where a stack runs out. */
453
+ const DEPTH = 100;
454
+
455
+ /** `value` as `{ config }`, a plain-data copy, or `{ problem }` naming the part of it refused. */
456
+ function copied(value) {
457
+ if (value === undefined) return { config: undefined };
458
+ try {
459
+ return { config: plain(value, 'default', []) };
460
+ } catch (refused) {
461
+ return { problem: refused };
462
+ }
463
+ }
464
+
465
+ /**
466
+ * `value`, found at `path` under the objects `within`, copied as plain data, or a throw of the line
467
+ * naming what is not. Own list indices and enumerable object fields are read only where their
468
+ * descriptors hold values. A Proxy is refused before any read, so no config code runs here.
469
+ */
470
+ function plain(value, path, within) {
471
+ const refuse = (what, at = path) => {
472
+ throw `\`${CONFIG}\` holds ${what} at \`${at}\`, which is not plain data`;
473
+ };
474
+ if (value === null || typeof value === 'string' || typeof value === 'boolean') return value;
475
+ if (typeof value === 'number') return Number.isFinite(value) ? value : refuse(String(value));
476
+ if (typeof value !== 'object') return refuse(value === undefined ? 'undefined' : `a ${typeof value}`);
477
+ if (types.isProxy(value)) refuse('a Proxy');
478
+ if (within.includes(value)) refuse('an object that holds itself');
479
+ if (within.length > DEPTH) refuse(`an object or a list more than ${DEPTH} levels below the default export`);
480
+ const list = Array.isArray(value);
481
+ const prototype = Object.getPrototypeOf(value);
482
+ if (list ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null) refuse('an object neither plain nor a list');
483
+ if (Object.getOwnPropertySymbols(value).length > 0) refuse('a Symbol key');
484
+ const keys = Object.keys(value);
485
+ const index = (key) => /^(0|[1-9][0-9]*)$/.test(key) && Number(key) < value.length;
486
+ const step = (key) => (list && index(key) ? `[${key}]`
487
+ : `.${/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : printable(JSON.stringify(key))}`);
488
+ const copy = (key) => {
489
+ const at = `${path}${step(key)}`;
490
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
491
+ if (descriptor === undefined) refuse('a hole', at);
492
+ if (!('value' in descriptor)) refuse('an accessor', at);
493
+ return plain(descriptor.value, at, [...within, value]);
494
+ };
495
+ if (list) {
496
+ for (const key of keys) if (!index(key)) refuse('a property that is not an index', `${path}${step(key)}`);
497
+ const answer = [];
498
+ for (let key = 0; key < value.length; key += 1) answer.push(copy(String(key)));
499
+ return answer;
500
+ }
501
+ const entries = keys.map((key) => [key, copy(key)]);
502
+ return prototype === null ? Object.setPrototypeOf(Object.fromEntries(entries), null) : Object.fromEntries(entries);
503
+ }
504
+
505
+ /**
506
+ * The failed line for the check `name`, whose forge read threw `threw`, carrying the adapter's
507
+ * message. A kill the sink refused is no failed read, and is thrown on, told apart by its kind:
508
+ * it stops `doctor` before its next call (the architect's ruling 3, §4, on #332).
509
+ */
510
+ function failedRead(name, threw) {
511
+ if (threw?.code === EVENT_REFUSED) throw threw;
512
+ return { name, ok: false, detail: wentWrong(threw) };
513
+ }
514
+
515
+ /**
516
+ * What the forge adapter's report of other repositories says of the board numbered `project`, or
517
+ * null where the board holds nothing from outside the repository. It names the other repositories
518
+ * and the count of items that cannot be read, and never the repository itself. `setup-board`
519
+ * refuses in the same words.
520
+ */
521
+ export function sharedWith(project, { repositories, unreadable }) {
522
+ const said = [];
523
+ if (repositories.length > 0) {
524
+ said.push(`board ${project} holds issues or pull requests of ${repositories.length === 1 ? 'another repository' : 'other repositories'}: ${repositories.join(', ')}`);
525
+ }
526
+ if (unreadable > 0) said.push(`board ${project} holds ${unreadable} ${unreadable === 1 ? 'item it cannot read' : 'items it cannot read'}`);
527
+ return said.length > 0 ? said.join('; ') : null;
528
+ }
529
+
530
+ /**
531
+ * The forge adapter's reads on the board `config` names, or on `board` where it is given, which
532
+ * is that board narrowed to fewer columns, each sent as `via` says: `send`, which stands in for the
533
+ * read runner's spawn in tests, and `emitter`, the `L0` emitter for L0's kills.
534
+ */
535
+ const readsOf = (config, via, board = config.board) => readSide({ repo: config.repo, ...board }, via);
536
+
537
+ /**
538
+ * Whether the board the config names holds anything from outside the repository `repo` names,
539
+ * which is the forge adapter's report and not this code's. An issue or pull request of another
540
+ * repository means two engines share the board, and an item the engine's `gh` cannot read is not
541
+ * the repository's (the architect's ruling on #285, comment 5835129833). A read that fails fails
542
+ * the line, carrying the adapter's message.
543
+ *
544
+ * A config Rigger refuses, cannot read, or throws during validation names no board worth
545
+ * reading, so the check answers null, sends nothing, and `doctor` prints no line for it. `ask`
546
+ * stands in for the read runner's spawn in tests.
547
+ */
548
+ export async function boardSharing({ target = process.cwd(), ask, emitter } = {}) {
549
+ const name = 'board sharing';
550
+ const { config, problem } = await consumerConfig(target);
551
+ if (problem) return null;
552
+ if (validate(config).length > 0) return null;
553
+ let held;
554
+ try {
555
+ held = await readsOf(config, { send: ask, emitter }).readOtherRepositories();
556
+ } catch (threw) {
557
+ return failedRead(name, threw);
558
+ }
559
+ const shared = sharedWith(config.board.project, held);
560
+ return { name, ok: shared === null, detail: shared ?? `board ${config.board.project} holds nothing from outside ${config.repo}` };
561
+ }
562
+
563
+ /**
564
+ * Whether the board the config names can be read, which is the forge adapter's read side's
565
+ * answer: it finds the board by its owner and number, and a read it cannot make fails the line,
566
+ * carrying the adapter's message, which names the board and the owner the request addressed.
567
+ */
568
+ async function reachability(config, via) {
569
+ const name = 'board reachability';
570
+ try {
571
+ await readsOf(config, via).readFieldTypes();
572
+ } catch (threw) {
573
+ return failedRead(name, threw);
574
+ }
575
+ return { name, ok: true, detail: `board ${config.board.project} can be read` };
576
+ }
577
+
578
+ /**
579
+ * A line per column the config declares, each saying whether its display name is an option of
580
+ * the board's field holding the columns. Each is the forge adapter's column read of that one
581
+ * column, so a line that fails carries the adapter's message, which names the column by key and
582
+ * display name.
583
+ */
584
+ async function columns(config, via) {
585
+ const lines = [];
586
+ for (const [key, display] of Object.entries(config.board.columns)) {
587
+ const name = `board column ${key}`;
588
+ try {
589
+ await readsOf(config, via, { ...config.board, columns: { [key]: display } }).readColumns();
590
+ lines.push({ name, ok: true, detail: `${display} is an option of board ${config.board.project}'s columns` });
591
+ } catch (threw) {
592
+ lines.push(failedRead(name, threw));
593
+ }
594
+ }
595
+ return lines;
596
+ }
597
+
598
+ /** The type GitHub names a single-select field by, as the read side's field types carry it. */
599
+ const SINGLE_SELECT = 'SINGLE_SELECT';
600
+
601
+ /**
602
+ * Whether the board holds the priority field the config declares: a single-select field of that
603
+ * name, the field holding the columns among them, whose option names are exactly the declared
604
+ * ones. Order is not compared, because the config's order is the ranking of whatever options the
605
+ * board holds, and the board's own order ranks nothing. A config declaring no priority passes,
606
+ * since no field is asked for.
607
+ *
608
+ * Only fields are read, never cards, so a card the read side refuses cannot decide this line.
609
+ * Every field's name and type comes from the read side's typed field listing. A single-select
610
+ * field's options come from its single-select field read, which leaves out the field holding the
611
+ * columns; that field's options come from the board read `setup-board` takes them from.
612
+ */
613
+ async function priority(config, via) {
614
+ const name = 'board priority';
615
+ const declared = config.board.priority;
616
+ if (!declared) return { name, ok: true, detail: 'no priority field is declared, so every card ranks alike' };
617
+ const field = `board ${config.board.project}'s field ${declared.field}`;
618
+ const reads = readsOf(config, via);
619
+ let held;
620
+ try {
621
+ const typed = (await reads.readFieldTypes()).find((each) => each.name === declared.field);
622
+ if (!typed) return { name, ok: false, detail: `board ${config.board.project} has no field named ${declared.field}` };
623
+ if (typed.type !== SINGLE_SELECT) {
624
+ return { name, ok: false, detail: `${field} is a ${typed.type} field, not a single-select field` };
625
+ }
626
+ held = declared.field === COLUMNS
627
+ ? (await boardOf('doctor', { repo: config.repo, ...config.board }, via)).columns.options.map((option) => option.name)
628
+ : (await reads.readFields()).find((select) => select.name === declared.field).options;
629
+ } catch (threw) {
630
+ return failedRead(name, threw);
631
+ }
632
+ const unasked = held.filter((option) => !declared.options.includes(option));
633
+ const missing = declared.options.filter((option) => !held.includes(option));
634
+ const said = [];
635
+ if (unasked.length > 0) said.push(`on the board and not in the config: ${unasked.join(', ')}`);
636
+ if (missing.length > 0) said.push(`in the config and not on the board: ${missing.join(', ')}`);
637
+ if (said.length > 0) return { name, ok: false, detail: `${field} holds options ${said.join('; ')}` };
638
+ return { name, ok: true, detail: `${field} holds exactly the declared options` };
639
+ }
640
+
641
+ /**
642
+ * The lines about the board the config names: whether it can be read, whether it holds each
643
+ * declared column, and whether it holds the declared priority field. A config Rigger refuses,
644
+ * cannot read or the validator refuses names no board worth reading, so it earns one line
645
+ * saying the board was not checked, and nothing is sent.
646
+ */
647
+ export async function boardChecks({ target = process.cwd(), ask, emitter } = {}) {
648
+ const { config, problem } = await consumerConfig(target);
649
+ let why = problem ? 'the config could not be read' : null;
650
+ if (!why && validate(config).length > 0) why = 'the config was refused';
651
+ if (why) return { name: 'board checks', ok: null, detail: `the board was not checked, because ${why}` };
652
+ const via = { send: ask, emitter };
653
+ return [await reachability(config, via), ...await columns(config, via), await priority(config, via)];
654
+ }
655
+
656
+ /**
657
+ * What a check answered, in the words the report writes it with.
658
+ *
659
+ * Three verdicts and not two. A check that could not reach the tool it asks has not passed, and
660
+ * saying so is the whole difference between a report a consumer can act on and one that claims
661
+ * a green nobody measured.
662
+ */
663
+ const SAYS = { true: 'ok', false: 'failed', null: 'not asked' };
664
+
665
+ /** The owner-provisioned names the gate workflow declares, guarded against the template in tests. */
666
+ const GATE_ENVIRONMENT = 'gate';
667
+ const GATE_APP_ID = 'GATE_APP_ID';
668
+ const GATE_APP_PRIVATE_KEY = 'GATE_APP_PRIVATE_KEY';
669
+
670
+ /** The gate workflow `init` forks, by the path a `workflow_path` condition names it with. */
671
+ const GATE_WORKFLOW = '.github/workflows/rigger-gate.yml';
672
+
673
+ /** The events the gate workflow declares under `on:`, in its order, guarded against the template in tests. */
674
+ const GATE_EVENTS = ['pull_request_target', 'issue_comment', 'issues'];
675
+
676
+ /** Whether a `workflow_path` pattern is one this check does not judge: a glob, or `~ALL`, which only `include` may hold. */
677
+ const unjudgedPattern = (pattern) => /[*?[\]{}!]/.test(pattern) || pattern === '~ALL';
678
+
679
+ /**
680
+ * Whether `policy` covers the gate workflow: true, false, or the patterns coverage turns on that
681
+ * this check does not judge. No `workflow_path` condition targets every workflow, and so does an
682
+ * empty `include` or one holding `~ALL`, less what `exclude` names (GitHub's REST page for Actions
683
+ * policies, read 2026-11-09).
684
+ */
685
+ function covers({ workflowPath }) {
686
+ if (workflowPath === null) return true;
687
+ const { include, exclude } = workflowPath;
688
+ const unjudged = [];
689
+ const every = include.length === 0 || include.includes('~ALL');
690
+ if (!every && !include.includes(GATE_WORKFLOW)) {
691
+ unjudged.push(...include.filter(unjudgedPattern));
692
+ if (unjudged.length === 0) return false;
693
+ }
694
+ if (exclude.includes(GATE_WORKFLOW)) return false;
695
+ unjudged.push(...exclude.filter(unjudgedPattern));
696
+ return unjudged.length === 0 ? true : unjudged;
697
+ }
698
+
699
+ /**
700
+ * The event-policy axis of the gate line (`ARCHITECTURE.md`, "What the owner provisions"), as
701
+ * `{ unjudged, passes }`: what could not be judged, and what the line says where it passes. What
702
+ * fails it is added to `faults`, the line's own. Only the repository's own policies are read. Any
703
+ * covering active event rule that lacks one of the gate's events fails it, whatever another policy
704
+ * allows. `obtain` makes each read, adding a failed one to `faults` and answering undefined.
705
+ */
706
+ async function eventPolicyAxis(repo, obtain, faults) {
707
+ const axis = { unjudged: [], passes: null };
708
+ const held = await obtain('readVisibility');
709
+ if (held === undefined) return axis;
710
+ if (held.visibility !== 'public') return { ...axis, passes: `${repo} is ${held.visibility}, so no Actions event policy is required` };
711
+ const policies = await obtain('readEventPolicies');
712
+ if (policies === undefined) return axis;
713
+ if (policies.length === 0) {
714
+ if (held.owner === 'organization') {
715
+ axis.unjudged.push(`${repo} holds no Actions event policy of its own, and only the repository's own policies were read, so one its organization or enterprise holds was not judged`);
716
+ } else {
717
+ faults.push(`${repo} is public and holds no Actions event policy of its own; add one that covers ${GATE_WORKFLOW} and allows its events (ARCHITECTURE.md, "What the owner provisions")`);
718
+ }
719
+ return axis;
720
+ }
721
+ const named = (policy) => `Actions event policy "${printable(policy.name)}"`;
722
+ const missing = (events) => GATE_EVENTS.filter((event) => !events.includes(event));
723
+ const judged = policies.map((policy) => ({ policy, covering: covers(policy), active: policy.enforcement === 'active' }));
724
+ const lacking = [];
725
+ for (const { policy, covering, active } of judged) {
726
+ if (covering !== true || !active) continue;
727
+ for (const events of policy.events) {
728
+ if (missing(events).length > 0) lacking.push(`${named(policy)} covers ${GATE_WORKFLOW} and does not allow ${missing(events).join(', ')}`);
729
+ }
730
+ }
731
+ if (lacking.length > 0) {
732
+ faults.push(...lacking);
733
+ return axis;
734
+ }
735
+ const notJudged = ({ policy, covering }) => covering.map((pattern) => `${named(policy)} has the workflow_path pattern ${printable(pattern)}, which was not judged against ${GATE_WORKFLOW}`);
736
+ const unknown = judged.filter(({ covering, active }) => Array.isArray(covering) && active);
737
+ const passing = judged.find(({ policy, covering, active }) => covering === true && active && policy.events.some((events) => missing(events).length === 0));
738
+ if (passing) {
739
+ const doubtful = unknown.filter(({ policy }) => policy.events.some((events) => missing(events).length > 0));
740
+ if (doubtful.length > 0) axis.unjudged.push(...doubtful.flatMap(notJudged));
741
+ else axis.passes = `${named(passing.policy)} covers ${GATE_WORKFLOW} and allows its events`;
742
+ return axis;
743
+ }
744
+ if (unknown.length > 0) {
745
+ axis.unjudged.push(...unknown.flatMap(notJudged));
746
+ return axis;
747
+ }
748
+ const covering = judged.filter((each) => each.covering === true);
749
+ const enforced = covering.filter((each) => each.active);
750
+ if (enforced.length > 0) faults.push(...enforced.map(({ policy }) => `${named(policy)} covers ${GATE_WORKFLOW} and has no restrict_action_events rule allowing its events`));
751
+ else if (covering.length > 0) faults.push(...covering.map(({ policy }) => `${named(policy)} covers ${GATE_WORKFLOW} but its enforcement is ${printable(policy.enforcement)}`));
752
+ else faults.push(`no active Actions event policy of ${repo}'s own covers ${GATE_WORKFLOW}`);
753
+ return axis;
754
+ }
755
+
756
+ /**
757
+ * The required gate context, its environment, and the repository's own Actions event policy,
758
+ * read only through L0's repository side. The line fails on any fault, is not asked where only
759
+ * the event policy could not be judged, and passes otherwise.
760
+ */
761
+ export async function gateCheck({ target = process.cwd(), ask, emitter } = {}) {
762
+ const name = 'gate check required';
763
+ const valid = await configValidity({ target });
764
+ if (valid.ok !== true) return { name, ok: null, detail: `the gate was not checked, because ${valid.detail}` };
765
+ const { config } = await consumerConfig(target);
766
+ const reads = repositoryReads({ repo: config.repo, ...config.board }, { send: ask, emitter });
767
+ const faults = [];
768
+ const obtain = async (read, ...args) => {
769
+ try { return await reads[read](...args); }
770
+ catch (error) { faults.push(failedRead(name, error).detail); }
771
+ };
772
+ const branch = await obtain('readDefaultBranch');
773
+ const rules = branch ? await obtain('readEffectiveRules', branch.name) : undefined;
774
+ const required = rules?.filter((rule) => rule.context === GATE_CONTEXT);
775
+ if (required?.length === 0) faults.push(`${GATE_CONTEXT} is not required on ${branch.name}; add an active required-status-check rule`);
776
+ const environment = await obtain('readEnvironment', GATE_ENVIRONMENT);
777
+ if (environment === null) faults.push(`environment ${GATE_ENVIRONMENT} is absent, or not readable with this token`);
778
+ let app;
779
+ let appKnown = false;
780
+ if (environment !== null) {
781
+ app = await obtain('readEnvironmentVariable', GATE_ENVIRONMENT, GATE_APP_ID);
782
+ const secret = await obtain('readEnvironmentSecret', GATE_ENVIRONMENT, GATE_APP_PRIVATE_KEY);
783
+ if (secret === false) faults.push(`${GATE_APP_PRIVATE_KEY} is absent, or not readable with this token`);
784
+ if (environment && environment.canAdminsBypass !== false) faults.push(`environment ${GATE_ENVIRONMENT} requires can_admins_bypass: false`);
785
+ appKnown = typeof app === 'string' && /^[0-9]+$/.test(app);
786
+ if (!appKnown && app !== undefined) faults.push(`${GATE_APP_ID} ${app === null ? 'is absent, or not readable with this token' : 'must hold decimal digits only'}`);
787
+ const policy = environment?.deploymentBranchPolicy;
788
+ if (environment?.policies === null) faults.push(`environment ${GATE_ENVIRONMENT}'s deployment-branch policy list is absent, or not readable with this token`);
789
+ else if (environment && branch && (policy?.protectedBranches !== false || policy?.customBranchPolicies !== true || environment.policies?.length !== 1
790
+ || environment.policies[0].type !== 'branch' || environment.policies[0].name !== branch.name)) {
791
+ faults.push(`environment ${GATE_ENVIRONMENT}'s deployment-branch policy must admit only branch ${branch.name}`);
792
+ }
793
+ }
794
+ for (const rule of required ?? []) {
795
+ if (rule.integration_id === null) faults.push(`${GATE_CONTEXT} has a missing integration pin`);
796
+ else if (environment !== null && !appKnown) faults.push(`${GATE_CONTEXT}'s integration pin was not judged against ${GATE_APP_ID}`);
797
+ else if (environment !== null && BigInt(rule.integration_id) !== BigInt(app)) faults.push(`${GATE_CONTEXT} is pinned to integration ${rule.integration_id}, rather than the gate App`);
798
+ }
799
+ const { unjudged, passes } = await eventPolicyAxis(config.repo, obtain, faults);
800
+ const said = [...faults, ...unjudged];
801
+ return { name, ok: faults.length > 0 ? false : unjudged.length > 0 ? null : true, detail: said.length ? said.join('; ')
802
+ : `${GATE_CONTEXT} is required on ${branch.name}; environment ${GATE_ENVIRONMENT}, ${GATE_APP_ID} and ${GATE_APP_PRIVATE_KEY} pass; ${passes}` };
803
+ }
804
+
805
+ /**
806
+ * What a run of the checks prints, and the status it exits with.
807
+ *
808
+ * One line per check, the verdict first and then the check's own name, as `init` writes one line
809
+ * per file under a heading that counts them. Zero only where every check passed: a check that
810
+ * failed and one that could not be run are both "not passed", and either leaves a consumer with
811
+ * a Rigger that is not ready.
812
+ */
813
+ export function report(where, results) {
814
+ const passed = results.filter((result) => result.ok === true).length;
815
+ const width = Math.max(...Object.values(SAYS).map((said) => said.length));
816
+ return {
817
+ text: [
818
+ `rigger doctor: ${passed} of ${results.length} checks passed in ${where}`,
819
+ ...results.map((result) => ` ${SAYS[result.ok].padEnd(width)} ${result.name}: ${result.detail}`),
820
+ ].join('\n'),
821
+ code: passed === results.length ? 0 : 1,
822
+ };
823
+ }
824
+
825
+ /**
826
+ * The words that name one closer of a closed admission: its kind, its reason and its time. `once`,
827
+ * `run`, `plan` and `doctor` each name a closer in them.
828
+ */
829
+ export const closedBy = ({ kind, reason, time }) => `admission is closed by ${kind}: ${reason}; time ${time}`;
830
+
831
+ /** The escapes `printable` writes for the line breaks a reader most often meets. */
832
+ const ESCAPES = { '\n': '\\n', '\r': '\\r', '\t': '\\t' };
833
+
834
+ /**
835
+ * `text` with every character that ends a line or drives a terminal written as an escape: the C0
836
+ * and C1 controls, DEL, and the line and paragraph separators. A closer's reason and an entry's
837
+ * name are whatever anyone who can write the state directory chose, and `doctor` and `plan` print
838
+ * a line per check and per card, so a break left raw would let either text print a line of its
839
+ * own, such as one reading as a pull. Any other text prints as it is, so an ordinary reason reads
840
+ * in `once`'s words exactly.
841
+ */
842
+ const printable = (text) => String(text).replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g,
843
+ (character) => ESCAPES[character] ?? `\\u${character.charCodeAt(0).toString(16).padStart(4, '0')}`);
844
+
845
+ /** `printable`, as `once`, `run` and `resume` print text from outside the process (U109 rule 4). */
846
+ export { printable as outsideText };
847
+
848
+ /** The words that name one closer in `doctor`'s and `plan`'s output: `closedBy`'s, its reason printable. */
849
+ export const closerLine = (closer) => closedBy({ ...closer, reason: printable(closer.reason) });
850
+
851
+ /** The words that name one closer removed by `resume`, its reason printable. */
852
+ export const removedCloserLine = ({ kind, path, reason, time }) => `removed the ${kind} closer ${path}: ${printable(reason)}; time ${time}`;
853
+
854
+ /** The words that name each entry of an admission that cannot be read, by its path and cause. */
855
+ export const unreadableAdmission = (unreadable) => `admission cannot be read: ${unreadable.map(({ path, cause }) => `${printable(path)} (${printable(cause)})`).join(', ')}`;
856
+
857
+ /**
858
+ * Admission in the repository `named`, as L3's module reads it from the state directory there:
859
+ * open, closed naming each closer, or unreadable naming each entry it could not read. It reads
860
+ * through `sink`, and a read records nothing.
861
+ */
862
+ export const admissionIn = (named, sink) => admission({ directory: join(named, STATE), sink }).read();
863
+
864
+ /**
865
+ * Whether admission is open, closed, or cannot be read (`R-SCHED-17`). It needs only the state
866
+ * directory, so it reports where the config cannot be read. A closed admission passes, so it
867
+ * leaves the exit status as it is; an unreadable one fails.
868
+ */
869
+ export function admissionCheck({ target = process.cwd(), sink }) {
870
+ const name = 'admission';
871
+ const read = admissionIn(target, sink);
872
+ if (read.state === 'unreadable') return { name, ok: false, detail: unreadableAdmission(read.unreadable) };
873
+ return { name, ok: true, detail: read.state === 'open' ? 'admission is open' : read.closers.map(closerLine).join('; ') };
874
+ }
875
+
876
+ /** The label whose shipped template is bound to this value in tests. */
877
+ const LAUNCHD_LABEL = 'com.williacj.rigger';
878
+
879
+ /** The installed package containing a real program path, or null for a checkout or npx cache. */
880
+ function installedPackage(program) {
881
+ for (let root = dirname(program); root !== dirname(root); root = dirname(root)) {
882
+ if (!root.endsWith(`${sep}${join('node_modules', '@williacj', 'rigger')}`)) continue;
883
+ const manifest = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
884
+ return manifest.name === '@williacj/rigger' && !root.split(sep).includes('_npx') ? root : null;
885
+ }
886
+ return null;
887
+ }
888
+
889
+ /** The loaded job's program and timeout, compared with the target's config. */
890
+ export async function launchdCheck({ target = process.cwd(), platform = process.platform, readLaunchdJob = loadedJob, emitter } = {}) {
891
+ if (platform !== 'darwin') return null;
892
+ const name = 'launchd job';
893
+ const answer = (ok, detail) => ({ name, ok, detail: printable(detail) });
894
+ let job;
895
+ try {
896
+ job = await readLaunchdJob(LAUNCHD_LABEL, { emitter });
897
+ } catch (error) {
898
+ if (error?.code === EVENT_REFUSED) throw error;
899
+ return answer(null, `could not read the loaded job: ${wentWrong(error)}`);
900
+ }
901
+ if (job === null) return null;
902
+ const faults = [];
903
+ const sharedTree = 'the program and target share a tree (R-SAFE-5)';
904
+ try {
905
+ const program = realpathSync.native(job.program);
906
+ if (!statSync(program).isFile()) faults.push('not a file');
907
+ const inside = sameTree(target, program);
908
+ if (inside) faults.push(sharedTree);
909
+ const root = installedPackage(program);
910
+ if (!inside && root && sameTree(target, root)) faults.push(sharedTree);
911
+ if (!root) faults.push('the package name or layout does not match node_modules/@williacj/rigger outside npx cache');
912
+ } catch (error) {
913
+ faults.push(wentWrong(error));
914
+ }
915
+ const valid = await configValidity({ target });
916
+ if (valid.ok !== true) return answer(faults.length ? false : null,
917
+ `${job.program}; ${[...faults, `the bound could not be computed: ${valid.detail}`].join('; ')}`);
918
+ const { config } = await consumerConfig(target);
919
+ const bound = launchdExitTimeout(config) / 1_000;
920
+ if (job.exitTimeout < bound) faults.push('exit timeout is below the bound');
921
+ return answer(faults.length === 0,
922
+ `${LAUNCHD_LABEL}; ${job.program}; exit timeout ${job.exitTimeout} s; bound ${bound} s${faults.length ? `; ${faults.join('; ')}` : ''}`);
923
+ }
924
+
925
+ /**
926
+ * The checks `doctor` runs: the Node version and the gh version, then gh authentication, agent
927
+ * CLI authentication and config validity, then the board checks, and then board sharing, the required gate, admission and the launchd job. The forge
928
+ * checks read only once the config earns no refusals.
929
+ *
930
+ * Each takes the same options and reads the ones it needs, so this list is the whole of what
931
+ * decides which checks there are and what order they are reported in. A check answers one line,
932
+ * a list of lines, or null, which has nothing to report and prints no line.
933
+ */
934
+ export const CHECKS = [nodeVersion, ghVersion, ghAuth, agentAuth, configValidity, boardChecks, boardSharing, gateCheck, admissionCheck, launchdCheck];
935
+
936
+ /**
937
+ * What a verb named `verb` prints and exits with where `here` and the source tree this Rigger is
938
+ * running from are one tree, as `sameTree` answers it (`R-SAFE-5`).
939
+ */
940
+ export const sourceTreeRefusal = (verb, here) => ({
941
+ text: `rigger ${verb}: ${here} is the source tree this Rigger is running from, and Rigger `
942
+ + 'never runs against that (`R-SAFE-5`). Install the package outside this tree and run it '
943
+ + 'from there.',
944
+ code: 1,
945
+ });
946
+
947
+ /**
948
+ * The repository a verb named `verb` was pointed at, as `{ named }`, or `{ refusal }`, what the
949
+ * verb prints and exits with where that is the source tree this Rigger is running from, or a tree
950
+ * git cannot name (`R-SAFE-5`). Nothing but git is asked before this answers, through L0 with
951
+ * `emitter` and `timeout` (`repoRoot`), and a kill the sink refused rejects.
952
+ */
953
+ export async function sourceTreeGuard(verb, { target = process.cwd(), packageRoot = PACKAGE, ask, emitter, timeout } = {}) {
954
+ const { root: named, why } = await repoRoot(target, { ask, emitter, timeout });
955
+ // The paths are compared whatever git said, so a tree the comparison can name is named
956
+ // precisely even where git declines — a run from inside the installed package is the case.
957
+ const here = named ?? real(target);
958
+ if (sameTree(here, packageRoot)) return { refusal: sourceTreeRefusal(verb, here) };
959
+ // A tree git cannot name is refused rather than checked, because the comparison above is only
960
+ // as good as the name it was given: asked about `<repo>/src` rather than `<repo>`, it answers
961
+ // that an engine in `<repo>/node_modules` is a different tree, and the run goes ahead with the
962
+ // runtime inside the directory being checked. Refusing one tree too many costs a message;
963
+ // refusing one too few costs the runtime mid-run, which is what `R-SAFE-5` is for.
964
+ if (named === null) {
965
+ return {
966
+ refusal: {
967
+ text: `rigger ${verb}: git names no repository at ${here} (${why}), so Rigger cannot tell it from the `
968
+ + 'source tree this Rigger is running from, and it never runs against that (`R-SAFE-5`). '
969
+ + 'Run it in a git repository, with git on the path.',
970
+ code: 1,
971
+ },
972
+ };
973
+ }
974
+ return { named };
975
+ }
976
+
977
+ /**
978
+ * The repository a verb named `verb` serves, settled for the sink `recording` opened: the guard
979
+ * asks git with an `L0` emitter on `sink`, and where it accepts the target, `name` names the state
980
+ * directory there, which writes every event the sink held. As `{ named }`, or `{ refusal }`, what
981
+ * the verb prints and exits with where the guard refused, or where the state directory refused
982
+ * what the sink held, which names each held event not yet recorded. The sink still holds those,
983
+ * and its next append writes them first (`R-RECORD-9`).
984
+ */
985
+ export async function settled(verb, { sink, name }, options = {}) {
986
+ const guarded = await sourceTreeGuard(verb, { ...options, emitter: sink.emitter({ layer: 'L0' }) });
987
+ if (guarded.refusal) return guarded;
988
+ try {
989
+ name(guarded.named);
990
+ } catch (refused) {
991
+ return { refusal: { text: `rigger ${verb}: ${refused.message}`, code: 1 } };
992
+ }
993
+ return guarded;
994
+ }
995
+
996
+ /**
997
+ * What the command prints for a `doctor` run, and the status it exits with. Each check is handed
998
+ * an `L0` emitter on the sink `recording` opens, for L0's kills in the forge calls it makes.
999
+ */
1000
+ export const doctor = (options) => recording((opened) => checking(opened, options));
1001
+
1002
+ /** `doctor`'s work, recording through the sink `opened` holds once `settled` has named its state directory. */
1003
+ async function checking(opened, {
1004
+ target = process.cwd(), packageRoot = PACKAGE, ask, checks = CHECKS, platform = process.platform, readLaunchdJob,
1005
+ } = {}) {
1006
+ const { named, refusal } = await settled('doctor', opened, { target, packageRoot, ask });
1007
+ if (refusal) return refusal;
1008
+ const emitter = opened.sink.emitter({ layer: 'L0' });
1009
+ const results = [];
1010
+ for (const check of checks) {
1011
+ try {
1012
+ results.push(await check({ target: named, packageRoot, ask, emitter, sink: opened.sink, platform, readLaunchdJob }));
1013
+ } catch (failure) {
1014
+ // A kill the sink refused stops the verb before its next call, and is never a failed check
1015
+ // (the architect's ruling 3, §4, on #332): the failure's kind says so, not its message.
1016
+ if (failure.code !== EVENT_REFUSED) throw failure;
1017
+ return { text: `rigger doctor: ${failure.message}`, code: 1 };
1018
+ }
1019
+ }
1020
+ return report(named, results.flat().filter((result) => result !== null));
1021
+ }