@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,349 @@
1
+ // ABOUTME: L0's provider adapter for Codex: every fact Rigger holds about the `codex` CLI, the skill
2
+ // probe it runs, and the command line, standard input and environment that run one role's agent
3
+ // file in one directory under a Codex home of the dispatch's own.
4
+
5
+ import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, symlinkSync, writeFileSync } from 'node:fs';
6
+ import { homedir } from 'node:os';
7
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
8
+ import { atStart } from '../process.mjs';
9
+ import { startFailure } from '../process.mjs';
10
+
11
+ import { gitEnvironment } from '../git-environment.mjs';
12
+ import { runCommand } from '../process.mjs';
13
+
14
+ // Measured from dispatch d-796876a3's stderr (#1433): max_chars=1048576.
15
+ // Codex counts characters; Rigger counts UTF-8 bytes, conservatively for non-ASCII text.
16
+ // provider-codex-live.test.mjs proves refusal above this limit only, never acceptance below it.
17
+ export const promptLimit = 1048576;
18
+
19
+ /*
20
+ * Every flag and setting here is grounded in #473's report, `docs/spikes/what-headless-sessions-
21
+ * load.md`, measured with codex-cli 0.159.2 and cited below by its run labels, in #519's report,
22
+ * `docs/spikes/how-a-judge-reaches-head.md`, and in the architect's rulings 4, 5 and 18 on #467.
23
+ * The flags this module passes, read beside `codex exec --help` at codex-cli 0.159.2 (engineer 17):
24
+ * `exec`, `--json`, `-C`, `--add-dir`, `-m`, `-c` and `--disable`. None of them is one of the
25
+ * flags that widen what the directory's own declaration says of the sandbox, approval or network:
26
+ * `-s`, `--approve-for-me`, `--dangerously-bypass-approvals-and-sandbox`,
27
+ * `--dangerously-bypass-hook-trust`, `--enable` and `--ignore-rules`. The `-c` keys it sets are
28
+ * the model's effort, the agent file and the skill toggles, none of them a sandbox, approval or
29
+ * network key. `--add-dir` names a writable root, which only a `workspace-write` sandbox the
30
+ * declaration chose honours (#519's x3 to x5).
31
+ *
32
+ * Where `codex`'s answer can differ from what this module expects (`D16` rule 3), measured with
33
+ * codex-cli 0.159.2 by #473's report and #519's report. The gated live run,
34
+ * `test/provider-codex-live.test.mjs`, re-measures them with the owner's credentials; its run at
35
+ * `c63a27a` on 2026-10-04 is the one cited below (#489).
36
+ *
37
+ * - **The home.** `CODEX_HOME` names the directory Codex reads its `config.toml`, its
38
+ * credentials and its bundled skills from, and writes its rollouts under (r1-x16). A version
39
+ * that ignores it reads the owner's own home, plugins and computer-use server included.
40
+ * - **The declaration.** A directory's `.codex/config.toml` is read only where the directory is
41
+ * trusted, and the trust entry lives in the user's configuration (r1-x5, r1-x13). The home's
42
+ * `config.toml` is read with no trust (r1-x16), so the declaration is copied there. A version
43
+ * that stops loading MCP servers or instructions from it breaks the route (ruling 18).
44
+ * - **The credentials.** The home's `auth.json` is a symbolic link to the owner's. Codex's own
45
+ * credential write went through such a link (r1-login-through-link). The live run at `c63a27a`
46
+ * kept the link, with no regular `auth.json` and no token value in any file of the home, but no
47
+ * token refresh happened during it, so whether a refresh writes through the link is still
48
+ * unobserved. A version whose refresh replaces the link with a file leaves a copy of the
49
+ * credentials in the scratch directory (`R-SAFE-1`).
50
+ * - **Plugins, apps and the host's browser and desktop.** `--disable plugins` withheld every
51
+ * plugin, the owner's computer-use server among them (r1-x44); `--disable apps` withheld
52
+ * `request_plugin_install` (x41). `HOST_FEATURES` is the list of features #473 found reaching the
53
+ * owner's browser or desktop; disabling them removed nothing measurable (r1-x45, r1-x42), and they
54
+ * are disabled under `D16` rule 3 so that a version in which one acts alone is held off too.
55
+ * - **The agent file.** `-c developer_instructions=<the file>` carried a 4,057-word file whole,
56
+ * frontmatter included, as one developer message (r1-x30). The frontmatter never needed
57
+ * stripping for the end marker to arrive (x28 to x30), so it is not stripped (O16).
58
+ * - **The prompt.** With no prompt argument, `codex exec` reads the prompt from standard input
59
+ * (x34), and exits 1 on an empty one (r1-x35).
60
+ * - **A maker's git directories.** Exact writable roots for the linked worktree's git directory
61
+ * and common `objects`, `refs` and `logs` override the git-metadata write refusal without
62
+ * granting common `hooks` or `config`. The architect measured this with `codex sandbox` and
63
+ * `writable_roots`, at codex-cli 0.164.0 on the Mini and 0.166.0 on the laptop, on 2026-11-05
64
+ * (#1230, at `40ecb3f8`). The gated maker run checks the same behaviour through `--add-dir`.
65
+ * A release dropping that exact-root override reverses the choice to a separate git directory;
66
+ * a documented Codex setting for git writes replaces these explicit roots.
67
+ * - **The process table and setuid programs.** The sandbox refuses `/bin/ps`, `pgrep`, `sysctl`
68
+ * and `sudo` to processes inside a session on macOS, measured with codex-cli 0.164.0 on the
69
+ * Mini and 0.166.0 on the laptop (#1230, row M17, 2026-11-05). A consumer's hook, test or build
70
+ * needing them cannot pass there; this repository's pre-commit suite meets that limit (M5a).
71
+ * A release permitting those operations would require re-measuring the limit.
72
+ * - **The tiers.** `-m gpt-6.1-sol` with `model_reasoning_effort` `medium` resolved to that model
73
+ * and effort in the rollout, and `high` to `high` (r1-x37, r1-x38).
74
+ * - **The bundled `.system` skills.** They are written into every fresh home (ruling 4) and
75
+ * reported by the probe from outside the directory, so they are withheld with every other such
76
+ * skill. Withholding them is optional (O18).
77
+ * - **A `skills.config` the declaration holds.** The `-c skills.config` override replaces the
78
+ * declaration's own list rather than adding to it, so a consumer's own skill toggles do not
79
+ * reach the session. Not measured; a judgment from how `-c` replaces a key.
80
+ */
81
+
82
+ /** The provider name a role's `provider` key names this adapter by. */
83
+ export const name = 'codex';
84
+
85
+ /**
86
+ * How Codex is asked whether it is signed in (`D16` rule 1): `codex login status`, whose words
87
+ * `signedIn` reads.
88
+ */
89
+ export const auth = ['codex', 'login', 'status'];
90
+
91
+ /** The directory, under a consumer's repository, Codex reads its project configuration from (#473's report, r1-x10). */
92
+ export const assets = '.codex';
93
+
94
+ /**
95
+ * The model each tier Rigger fixes selects (`O4`), with the effort `EFFORT` gives it, as #473's
96
+ * report recommends (r1-x37, r1-x38).
97
+ */
98
+ export const tiers = { standard: 'gpt-6.1-sol', high: 'gpt-6.1-sol' };
99
+
100
+ /** The `model_reasoning_effort` each tier selects beside its model. */
101
+ const EFFORT = { standard: 'medium', high: 'high' };
102
+
103
+ /**
104
+ * Codex's words for a signed-in and a signed-out account, as `codex login status` writes them to
105
+ * standard error: a copy of that CLI's answer (`D16` rule 2), tied to it by the gated live test
106
+ * `test/provider-codex-live.test.mjs`. Measured with codex-cli 0.159.2 on 2026-10-03: signed in
107
+ * with ChatGPT it wrote `Logged in using ChatGPT` and exited 0, and with an empty `CODEX_HOME`
108
+ * `Not logged in` and exited 1, with nothing on standard output either time. The same binary holds
109
+ * `Logged in using ` before each other way of signing in, an API key among them, whose line carries
110
+ * part of the key, so the line is read and never repeated.
111
+ */
112
+ const SIGNED_IN = /^Logged in using /m;
113
+ const SIGNED_OUT = /^Not logged in$/m;
114
+
115
+ /**
116
+ * Whether `said`, what `codex login status` answered, says Codex is signed in: true, false, or
117
+ * undefined where it says neither in words this reads.
118
+ */
119
+ export function signedIn(said) {
120
+ const text = `${said.stderr ?? ''}${said.stdout ?? ''}`;
121
+ if (SIGNED_IN.test(text)) return true;
122
+ if (SIGNED_OUT.test(text)) return false;
123
+ return undefined;
124
+ }
125
+
126
+ /**
127
+ * The features `codex features list` showed reaching the owner's browser or desktop, all stable and
128
+ * on at codex-cli 0.159.2 (#473's report, "Apps, .system skills, plugin caches and the browser and
129
+ * computer-use features"), each disabled under `D16` rule 3.
130
+ */
131
+ const HOST_FEATURES = ['browser_use', 'browser_use_external', 'browser_use_full_cdp_access', 'computer_use', 'in_app_browser'];
132
+
133
+ /** The flags both the probe and the session pass, so each reads the same configuration (ruling 18). */
134
+ const WITHHELD = ['--disable', 'plugins', '--disable', 'apps', ...HOST_FEATURES.flatMap((feature) => ['--disable', feature])];
135
+
136
+ /** The name of the Codex home a dispatch's scratch directory holds. */
137
+ const HOME = 'codex-home';
138
+
139
+ /**
140
+ * The name of the temporary directory a dispatch's scratch directory holds, the one directory
141
+ * outside the declaration's roots for temporary files (O93). The declaration leaves `/tmp` and
142
+ * `$TMPDIR` out of the sandbox, so without it a session has nowhere to put a temporary file: zsh
143
+ * writes a here-document under `$TMPPREFIX`, `/tmp/zsh` unless set, and fails (#489).
144
+ */
145
+ const TEMPORARY = 'tmp';
146
+
147
+ /**
148
+ * How long L0 lets the skill probe run before it kills the probe's group. A judgment, not a
149
+ * measurement, recorded as `GIT_TIMEOUT` is. Its premise is a measurement: ten runs of the probe
150
+ * as this module runs it, in a probe repository under a fresh home, took 0.45 to 1.07 s each with
151
+ * codex-cli 0.159.2 on 2026-10-03, at a one-minute load near 16. A minute is over fifty times the
152
+ * slowest, room for a loaded host, while a probe that hangs holds a dispatch back by a minute.
153
+ *
154
+ * The probe runs outside any dispatch's record: it is part of answering the invocation, before L1
155
+ * records `dispatch.start`, so no entry names its group. An engine killed outright while it runs
156
+ * leaves it to end by itself, as any `git` or `gh` call under `GIT_TIMEOUT` is left.
157
+ */
158
+ export const PROBE_TIMEOUT = 60_000;
159
+
160
+ /**
161
+ * The real path of `path`, a file that need not exist: the real path of its nearest ancestor that
162
+ * does, with the rest of `path` after it. A link that exists and cannot be resolved throws, so it
163
+ * is refused rather than taken for absent.
164
+ */
165
+ function realOf(path) {
166
+ try {
167
+ lstatSync(path);
168
+ } catch {
169
+ const parent = dirname(path);
170
+ return parent === path ? path : join(realOf(parent), basename(path));
171
+ }
172
+ return realpathSync.native(path);
173
+ }
174
+
175
+ /** Whether the real path `path` lies under the real path `directory`. */
176
+ function under(path, directory) {
177
+ const between = relative(directory, path);
178
+ return between !== '' && !isAbsolute(between) && between.split(sep)[0] !== '..';
179
+ }
180
+
181
+ /**
182
+ * `text` as a TOML basic string, which is how `-c` reads a value: JSON's escapes are TOML's, but
183
+ * for DEL, which TOML admits only escaped.
184
+ */
185
+ const toml = (text) => JSON.stringify(text).replaceAll('\u007f', '\\u007f');
186
+
187
+ /** The line that opens the probe's list of skills. */
188
+ const AVAILABLE = '### Available skills';
189
+
190
+ /** One skill in that list, as codex-cli 0.159.2 printed it, capturing its `SKILL.md` file. */
191
+ const SKILL_LINE = /^- .*\(file: (.+)\)$/;
192
+
193
+ /**
194
+ * The skill list in `answer`, what `codex debug prompt-input` printed, as absolute `SKILL.md`
195
+ * paths, or a thrown error saying why it holds none this can read.
196
+ *
197
+ * The format, measured with codex-cli 0.159.2 on 2026-10-03 and recorded at
198
+ * `test/fixtures/codex-prompt-input-0.159.2.json` (`D16` rule 3): a JSON array of model-visible
199
+ * messages, one of which holds a `<skills_instructions>` block. In it, a `### Skill roots` table
200
+ * gives each root as a line `` - `rN` = `<absolute path>` ``. A line `### Available skills`
201
+ * follows, and every line after it, up to `</skills_instructions>`, is one skill: a line starting
202
+ * `- ` and ending `(file: rN/<name>/SKILL.md)`. Each `rN` is expanded to its root's path. A file
203
+ * given as an absolute path is taken as it is. A blank line is passed over.
204
+ *
205
+ * Anything else is refused, naming what was refused: no block, no `### Available skills` line, a
206
+ * line after it in any other shape, and a root the table does not hold. A list read short would
207
+ * leave a skill from outside the directory loaded (`R-SAFE-6`), so a line this cannot read is
208
+ * never passed over. An `### Available skills` line with no skill after it is read as no skill.
209
+ * Codex was not measured giving that answer, since every home holds the bundled skills, and it
210
+ * leaves nothing loaded that a refusal would have withheld.
211
+ */
212
+ function skillsIn(answer) {
213
+ let messages;
214
+ try {
215
+ messages = JSON.parse(answer);
216
+ } catch (failure) {
217
+ throw new Error(`it printed no JSON: ${failure.message}`);
218
+ }
219
+ const texts = (Array.isArray(messages) ? messages : []).flatMap((message) => (Array.isArray(message?.content) ? message.content : [])).map((part) => part?.text).filter((text) => typeof text === 'string');
220
+ const block = texts.find((text) => text.includes('<skills_instructions>'));
221
+ if (block === undefined) throw new Error('its answer holds no skill list');
222
+ const roots = new Map([...block.matchAll(/^- `(r\d+)` = `(.+)`$/gm)].map(([, key, path]) => [key, path]));
223
+ const lines = block.split('\n');
224
+ const heading = lines.indexOf(AVAILABLE);
225
+ if (heading === -1) throw new Error(`its skill list holds no line \`${AVAILABLE}\``);
226
+ const end = lines.findIndex((line, at) => at > heading && line.startsWith('</skills_instructions>'));
227
+ const files = lines.slice(heading + 1, end === -1 ? undefined : end).filter((line) => line !== '').map((line) => {
228
+ const file = line.match(SKILL_LINE)?.[1];
229
+ if (file === undefined) throw new Error(`its skill list holds the line ${JSON.stringify(line)}, which is in no shape this adapter reads`);
230
+ return file;
231
+ });
232
+ return files.map((file) => {
233
+ if (isAbsolute(file)) return file;
234
+ const [key, ...rest] = file.split('/');
235
+ if (!roots.has(key) || rest.length === 0) throw new Error(`it names the skill file ${file}, under no root its table holds`);
236
+ return join(roots.get(key), ...rest);
237
+ });
238
+ }
239
+
240
+ /**
241
+ * The skills Codex reports from outside `directory` for a session under `home`, as absolute
242
+ * `SKILL.md` paths: the skill probe (ruling 4 Q2; ruling 5; ruling 18).
243
+ *
244
+ * It asks Codex itself (`D16` rule 1): `codex -C <directory> debug prompt-input`, under the same
245
+ * `CODEX_HOME` and the same withholding flags as the session, since `prompt-input` takes neither
246
+ * `--ignore-user-config` nor `--add-dir` (engineer r3-4). It runs through L0's process adapter, in
247
+ * a process group of its own, in `directory`, under the engine's own environment less git's
248
+ * redirecting variables, for at most `timeout` milliseconds, with every kill recorded through
249
+ * `emitter`.
250
+ *
251
+ * `prompt-input` is an undocumented debugging command. Its list agreed with the `host_skills` a
252
+ * session's rollout recorded under the same home, with skill toggles off, in the live run at
253
+ * `c63a27a` with codex-cli 0.159.2 on 2026-10-04 (#489); the gated live run re-checks it on each
254
+ * run. A Codex release that drops the command or changes its answer, or a documented switch that
255
+ * turns off the user's and the bundled skill roots, replaces the probe.
256
+ */
257
+ async function probed({ directory, home, emitter, timeout, host }) {
258
+ const args = ['-C', directory, ...WITHHELD, 'debug', 'prompt-input'];
259
+ const spelled = `\`codex ${args.join(' ')}\``;
260
+ const { exit, timedOut, stdout, stderr } = await runCommand({ command: 'codex', args, cwd: directory, env: { ...gitEnvironment(), CODEX_HOME: home }, timeout, emitter, host });
261
+ if (timedOut) throw startFailure(new Error(`the skill probe ${spelled} outlived its bound of ${timeout} ms, and L0 killed it`), 'codex-probe-timeout');
262
+ if (exit !== 0) throw startFailure(new Error(`the skill probe ${spelled} exited ${exit}: ${stderr.toString('utf8').trim().split('\n')[0] || stdout.toString('utf8').trim().split('\n')[0] || 'it said nothing'}`), 'codex-probe-exit');
263
+ let skills;
264
+ try {
265
+ skills = skillsIn(stdout.toString('utf8'));
266
+ } catch (failure) {
267
+ throw startFailure(new Error(`the skill probe ${spelled} answered nothing this adapter can read: ${failure.message}`), 'codex-probe-answer');
268
+ }
269
+ const real = atStart('directory-unusable', () => realpathSync.native(directory));
270
+ return skills.filter((skill) => !under(atStart('codex-skill-unresolved', () => realOf(skill)), real));
271
+ }
272
+
273
+ /**
274
+ * The owner's own Codex home, whose `auth.json` a dispatch's home links to: the `CODEX_HOME` the
275
+ * engine runs under, or `~/.codex`, Codex's default.
276
+ */
277
+ const ownerHome = () => process.env.CODEX_HOME || join(homedir(), '.codex');
278
+
279
+ /**
280
+ * Makes the Codex home for a dispatch in `directory` under its scratch directory `scratch`, and
281
+ * answers its path (ruling 18): `config.toml`, a copy of the directory's own declaration at
282
+ * `.codex/config.toml`, or empty where the directory declares nothing, and `auth.json`, a symbolic
283
+ * link to the owner's, never a copy (`R-SAFE-1`). The link is made whether or not the owner's file
284
+ * exists, so a signed-out owner's session fails as Codex fails it. A home already there is
285
+ * refused, since L1 makes the scratch directory fresh.
286
+ */
287
+ function homeFor(directory, scratch) {
288
+ const home = join(atStart('directory-unusable', () => realpathSync.native(scratch)), HOME);
289
+ atStart('codex-directory-unmade', () => mkdirSync(home));
290
+ const declared = join(directory, assets, 'config.toml');
291
+ const content = existsSync(declared) ? atStart('codex-config-unreadable', () => readFileSync(declared)) : '';
292
+ atStart('codex-home-file-unwritten', () => writeFileSync(join(home, 'config.toml'), content));
293
+ const authentication = join(atStart('owner-home-missing', ownerHome), 'auth.json');
294
+ atStart('codex-home-file-unwritten', () => symlinkSync(authentication, join(home, 'auth.json')));
295
+ return home;
296
+ }
297
+
298
+ /**
299
+ * The command line that runs the agent file `agent`, at `tier`, on `prompt`, in `directory`, with
300
+ * each directory `reach` names writable beside it, and the dispatch's temporary directory in
301
+ * `scratch` writable too (O93): the CLI by its command name, its arguments, the prompt's bytes for
302
+ * its standard input, no variable to unset, `CODEX_HOME`, the dispatch's own home in `scratch`
303
+ * (ruling 18), and `TMPDIR` and `TMPPREFIX`, the temporary directory and a prefix inside it. It runs the skill probe first, through `emitter`, bounded by
304
+ * `probeTimeout`, using the optional `host`'s processes and clock. It disables each outside
305
+ * `SKILL.md` path the probe reports, with one `skills.config` entry per skill.
306
+ * A maker's optional `gitDirectories` thunk supplies its git metadata roots, read before the home
307
+ * or probe is made; an unreadable answer refuses the invocation under its own preparation kind.
308
+ *
309
+ * Refused, each naming what it refused: a tier Rigger does not fix, before anything is made or
310
+ * run; an agent file whose real path is not under `directory` (`R-SAFE-6`); an agent file that
311
+ * cannot be read; a home or temporary directory that cannot be made; and a probe that fails,
312
+ * outlives its bound, or answers nothing it can read.
313
+ */
314
+ export async function invocation({ agent, tier, prompt, directory, scratch, reach = [], gitDirectories, emitter, host, probeTimeout = PROBE_TIMEOUT }) {
315
+ if (!Object.hasOwn(tiers, tier)) {
316
+ throw new Error(`the Codex adapter maps no model to the tier \`${tier}\`, only to \`standard\` and \`high\``);
317
+ }
318
+ const real = atStart('directory-unusable', () => realpathSync.native(directory));
319
+ const file = resolve(directory, agent);
320
+ const fileReal = atStart('agent-unresolved', () => realOf(file), { file: agent });
321
+ if (!under(fileReal, real)) {
322
+ throw startFailure(new Error(`the agent file ${agent} lies at ${fileReal}, outside the consumer's repository ${real}, so the Codex adapter refused it (R-SAFE-6)`), 'agent-outside', { file: agent });
323
+ }
324
+ const instructions = atStart('agent-unreadable', () => readFileSync(file, 'utf8'), { file: agent });
325
+ const gitRoots = gitDirectories === undefined ? [] : await atStart('codex-git-directories-unreadable', gitDirectories)
326
+ .catch((failure) => { throw startFailure(failure, 'codex-git-directories-unreadable'); });
327
+ const home = homeFor(directory, scratch);
328
+ const temporary = join(atStart('directory-unusable', () => realpathSync.native(scratch)), TEMPORARY);
329
+ atStart('codex-directory-unmade', () => mkdirSync(temporary));
330
+ const outside = await probed({ directory, home, emitter, timeout: probeTimeout, host });
331
+ const toggles = `[${outside.map((path) => `{path = ${toml(path)}, enabled = false}`).join(', ')}]`;
332
+ return {
333
+ command: 'codex',
334
+ args: [
335
+ 'exec', '--json',
336
+ '-C', directory,
337
+ ...[...reach, ...gitRoots, temporary].flatMap((each) => ['--add-dir', each]),
338
+ '-m', tiers[tier],
339
+ '-c', `model_reasoning_effort=${toml(EFFORT[tier])}`,
340
+ ...WITHHELD,
341
+ '-c', `skills.config=${toggles}`,
342
+ '-c', `developer_instructions=${toml(instructions)}`,
343
+ ],
344
+ input: Buffer.from(prompt, 'utf8'),
345
+ unset: [],
346
+ env: { CODEX_HOME: home, TMPDIR: temporary, TMPPREFIX: join(temporary, 'zsh') },
347
+ folder: undefined,
348
+ };
349
+ }
@@ -0,0 +1,134 @@
1
+ // ABOUTME: A write to standard error that returns only once all of it is written, or once its
2
+ // reader has left it undrained too long, for the writes L5's sink and L0's exit cleanup make as the
3
+ // process exits.
4
+
5
+ import { writeSync } from 'node:fs';
6
+
7
+ /**
8
+ * The longest a write to standard error waits on a reader that takes nothing, before it gives up
9
+ * and drops what it has not written. It gives up sooner, once the reader has taken nothing for
10
+ * `WAIT` of a pipe found full, or for this less `SPARE` and a `PAUSE`, 899 ms, whichever comes
11
+ * first, so that it has returned by this even where a pause ends late. A judgment, not a
12
+ * measurement. Its premise is a measurement: over 20 writes of 2,000,000 bytes, each by a loop that
13
+ * tried a full pipe again at once, to a reader draining the pipe (`spawnSync`'s), the longest the
14
+ * reader left the pipe full was 1.04 ms, with Node 26.5.0 on macOS 27.0 on 2026-09-28, at a load
15
+ * average of about 42. `WAIT` is over 500 times that, room for a loaded host, and a process whose
16
+ * reader never drains ends within one second.
17
+ */
18
+ export const UNDRAINED_BOUND = 1_000;
19
+
20
+ /**
21
+ * How long a write pauses before it tries a full pipe again, so a wait on the reader uses next to
22
+ * no processor time. A judgment, not a measurement. A pause ends late: over five writes of
23
+ * 2,000,000 bytes to `spawnSync`'s reader with Node 20.20.2 on macOS 27.0 on 2026-09-28, each 1 ms
24
+ * pause took 2.3 ms on average, and a write met the full pipe up to 186 times. So a draining
25
+ * reader is kept waiting some milliseconds a write, and never charged the bound.
26
+ */
27
+ const PAUSE = 1;
28
+
29
+ /**
30
+ * How much of `UNDRAINED_BOUND` a write keeps in hand for a host that ends a pause late, and for
31
+ * what its caller does next. A judgment, not a measurement. Its premise is a measurement: in CI's
32
+ * Node 20 job on 2026-09-28 (run 36478413721), a write that paused 10 ms at a time and kept one
33
+ * pause in hand still returned 30.7 ms past the bound. A tenth of the bound is three times that
34
+ * overrun.
35
+ */
36
+ const SPARE = UNDRAINED_BOUND / 10;
37
+
38
+ /**
39
+ * The longest a write waits on a pipe it found full, from when it found it full, before it gives
40
+ * up. A judgment, not a measurement. It leaves four tenths of the bound in hand, four times
41
+ * `SPARE`, for a final pause that a host ends late when no pause before it ran late, so the write
42
+ * had nothing to see it coming by. Under #440's forcing, a final pause ending 250 ms late took a
43
+ * write that waited until 899 ms to 1,103.7 ms.
44
+ */
45
+ const WAIT = UNDRAINED_BOUND * 0.6;
46
+
47
+ /** What a write pauses on: a cell nothing ever wakes, so each wait lasts its whole timeout. */
48
+ const idle = new Int32Array(new SharedArrayBuffer(4));
49
+
50
+ /**
51
+ * Whether the last write gave up on the reader. A write then gives up at the first full pipe, so a
52
+ * reader that never drains holds the process once, however many writes it makes. A write the
53
+ * reader takes bytes of clears it, so a reader that drains again is waited on again. That is seen
54
+ * only where the pipe has room when a write starts: a reader that has begun draining, and has not
55
+ * yet made room, loses that write.
56
+ */
57
+ let abandoned = false;
58
+
59
+ /**
60
+ * Write all of `text` to standard error before returning, even as the process exits, or until its
61
+ * reader has taken nothing for most of `UNDRAINED_BOUND`. What it could not write is dropped:
62
+ * standard error is the last place left to report to.
63
+ *
64
+ * A standard error Node has not opened is the descriptor the process inherited, and on a pipe that
65
+ * is blocking: a write to a full pipe waits in the kernel for as long as the reader does, and no
66
+ * bound here reaches it. Opening `process.stderr` leaves a pipe non-blocking, so the write first
67
+ * opens it. Measured with Node 20.20.2 and 26.5.0 on macOS 27.0 on 2026-09-28, standard error a
68
+ * FIFO nothing read: a `writeSync` of 200,000 bytes with `process.stderr` untouched was still
69
+ * blocked after 3 s, and with it opened, each was refused with EAGAIN once the pipe was full.
70
+ * Reopening `/dev/fd/2` non-blocking does not do it: it shares the inherited, blocking file.
71
+ *
72
+ * A standard error that is a terminal is the one limit: Node opens it blocking, so a terminal that
73
+ * stops reading holds the write in the kernel, and neither bound here holds. Measured with Node
74
+ * 20.20.2 and 26.5.0 on macOS 27.0 on 2026-09-28, standard error a pty whose other end nothing
75
+ * read: `writeWhole` of 200,000 bytes, `process.stderr` opened, was still blocked after 3 s, three
76
+ * runs of 26.5.0 and one of 20.20.2, where with that end read it returned in 1 to 2 ms. The limit
77
+ * stands because a terminal that stops reading holds any program writing to it, and bounding the
78
+ * write would need a second writer, in a thread or a process, for the exit alone (the card's
79
+ * author on #376).
80
+ *
81
+ * A write to a full non-blocking pipe comes back short or refused with EAGAIN.
82
+ * `process.stderr.write` queues the rest, which an exit drops. Measured on macOS 27.0 with Node
83
+ * 20.20.2, 24.21.0 and 26.5.0, one `writeSync` of 200,000 bytes after `process.stderr` was touched
84
+ * delivered 8,192 bytes on Node 20 and 65,536 on 24 and 26. A loop that wrote again until every
85
+ * byte was taken delivered 2,000,000 bytes whole on all three, from an `exit` listener and from a
86
+ * re-raised `SIGTERM`. `test/event-sink.test.mjs` and `test/exit-cleanup.test.mjs` each write
87
+ * past 65,536 bytes at exit.
88
+ *
89
+ * There is nothing to wait on at exit, so a full pipe is waited on synchronously, a `PAUSE` at a
90
+ * time. The wait runs from the call, or from the last time the reader took anything, so a slow
91
+ * reader that keeps draining gets every byte. Only a write into a pipe found full shows the reader
92
+ * took something: a write into room it had from the start shows nothing, so it leaves the wait
93
+ * running from the call, and what the call spent before it, opening `process.stderr` included,
94
+ * counts against the bound. A pause is begun only where it would end `SPARE` before the bound, so
95
+ * the write gives up within the bound even where the host ends its last pause late by up to that.
96
+ * Where an earlier pause of the same write ended later than that, the write keeps that much in hand
97
+ * instead: a host loaded for the whole of the wait ends every pause late, so the last is taken to
98
+ * end as late as the latest before it. A host can also hold only the last pause, when none before it
99
+ * ran late, so the write gives up once it has waited `WAIT` on a pipe it found full, with the rest
100
+ * of the bound in hand. A pause the host holds longer than that rest still holds the write past the
101
+ * bound: the call cannot return while its wait is blocked (#440).
102
+ */
103
+ export function writeWhole(text) {
104
+ let deadline = performance.now() + UNDRAINED_BOUND;
105
+ let full = false;
106
+ // The latest any pause of this write has ended, past its `PAUSE`.
107
+ let late = 0;
108
+ // When this write found the pipe full, since the reader last took anything.
109
+ let found;
110
+ // Opened for what it leaves the descriptor, not to write through.
111
+ void process.stderr;
112
+ let rest = Buffer.from(text);
113
+ while (rest.length > 0) {
114
+ try {
115
+ rest = rest.subarray(writeSync(2, rest));
116
+ abandoned = false;
117
+ if (full) deadline = performance.now() + UNDRAINED_BOUND;
118
+ full = false;
119
+ found = undefined;
120
+ } catch (error) {
121
+ if (error.code !== 'EAGAIN') throw error;
122
+ const now = performance.now();
123
+ found ??= now;
124
+ if (abandoned || now + PAUSE + Math.max(SPARE, late) > deadline || now - found >= WAIT) {
125
+ abandoned = true;
126
+ return;
127
+ }
128
+ full = true;
129
+ const paused = performance.now();
130
+ Atomics.wait(idle, 0, 0, PAUSE);
131
+ late = Math.max(late, performance.now() - paused - PAUSE);
132
+ }
133
+ }
134
+ }