@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,8 @@
1
+ // ABOUTME: L0's adapter map: each provider name a role can declare, mapped to the module that
2
+ // holds every fact Rigger knows about that provider's agent CLI.
3
+
4
+ import * as claude from './claude.mjs';
5
+ import * as codex from './codex.mjs';
6
+
7
+ /** Every provider adapter, by the provider name a role's `provider` key gives (ruling 1 Q1 on #467). */
8
+ export const ADAPTERS = Object.freeze({ claude, codex });
@@ -0,0 +1,427 @@
1
+ // ABOUTME: L0's provider adapter for Claude Code: every fact Rigger holds about the `claude` CLI,
2
+ // and the command line and standard input that run one role's agent file in one directory.
3
+
4
+ import { existsSync, lstatSync, readFileSync, realpathSync } from 'node:fs';
5
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
6
+ import { startFailure } from '../process.mjs';
7
+ import { atStart } from '../process.mjs';
8
+
9
+ /** No Claude Code prompt limit has been measured. */
10
+ export const promptLimit = undefined;
11
+
12
+ /*
13
+ * Every flag and setting here is grounded in #473's report, `docs/spikes/what-headless-sessions-
14
+ * load.md`, measured with Claude Code 2.1.286, and cited below by its run labels. Where `claude`'s
15
+ * answer can differ from what this module expects (`D16` rule 3), measured on this host with
16
+ * Claude Code 2.1.287 by #480's gated live runs (`test/provider-claude-live.test.mjs`):
17
+ *
18
+ * - `--append-system-prompt-file` is absent from `claude --help`'s list of options, which names
19
+ * it only inside the text for `--bare`. The live runs carried the agent file's last sentence
20
+ * through it, as #473's c30 did. What a version that drops it does with it is not measured.
21
+ * - `--strict-mcp-config` drops the directory's own `.mcp.json` with every other MCP source, so
22
+ * the file is named again with `--mcp-config` (c2, c6). A version in which the strict flag
23
+ * stops dropping the claude.ai connectors would let them back in; the live run reads that from
24
+ * the session's own `init` record.
25
+ * - `claudeMdExcludes` is matched against absolute paths as globs. The live run measured that an
26
+ * absolute path, with no glob character in it, withheld a parent's `CLAUDE.md`, which reaches a
27
+ * session without it (c10).
28
+ * - An MCP tool the directory's own settings allow is called; one they do not is refused with
29
+ * "Claude requested permissions to use mcp__…, but you haven't granted it yet", and the session
30
+ * still exits 0. A version that honours an untrusted directory's own `permissions.allow` makes
31
+ * `rulesOf` redundant, never wrong.
32
+ * - The tools a session is offered, and which act through the owner's account, are `OWNERS`'s
33
+ * measurement on 2.1.287, and the built-in plugins `BUILTINS`'s. Each moves on a patch release.
34
+ *
35
+ * How a judge reaches its `head` (`reach`): route B of #519's report, `docs/spikes/how-a-judge-
36
+ * reaches-head.md`, measured with Claude Code 2.1.287. No `--add-dir`, which lists the reached
37
+ * directory's agents even with slash commands disabled and the agent tool withheld (route A, c2,
38
+ * c12), and no `permissions.additionalDirectories`; only path-scoped `Read` and `Edit` rules in
39
+ * `--settings`, so nothing of `head`'s loads (c6 to c8, c13 to c19). The fallback is route C,
40
+ * `permissions.additionalDirectories: [<head>]` in the same `--settings` JSON, which the report
41
+ * found passing too, loading nothing from `head` and running `npm test` there with no reset of the
42
+ * shell's directory (c9 to c11). It is used only where a live run shows route B failing. Route B
43
+ * stops passing in a version that loads `head`'s `CLAUDE.md` or `.claude/` once a session reads
44
+ * there or enters it with `cd`, or in one where the `//` rules stop admitting the read, the write or
45
+ * the `cd` (report, "What would reverse the recommendation"); the gated live run
46
+ * `test/provider-claude-reach-live.test.mjs` reads both.
47
+ *
48
+ * One source the reports found is not withheld here: the owner's account email, which #473's
49
+ * report found in every session's context (c47), and for which it found no withholder.
50
+ */
51
+
52
+ /** The provider name a role's `provider` key names this adapter by. */
53
+ export const name = 'claude';
54
+
55
+ /**
56
+ * How Claude Code is asked whether it is signed in. `D16` rule 1: Claude Code owns that fact, and
57
+ * `claude auth status --json` states it as `loggedIn`, which `signedIn` reads for `doctor`.
58
+ */
59
+ export const auth = ['claude', 'auth', 'status', '--json'];
60
+
61
+ /**
62
+ * Whether `said`, what `claude auth status --json` answered, says Claude Code is signed in: the
63
+ * `loggedIn` its standard output states, read rather than its exit status, because the statement
64
+ * is the fact and the status a second telling of it that could drift from the first. Undefined
65
+ * where it states no boolean `loggedIn` this can read, which is not a measured answer but the shape
66
+ * a later version could take, and reading a missing key as `false` would tell a signed-in consumer
67
+ * they are signed out on a day the CLI merely reworded itself.
68
+ *
69
+ * Where its answer can differ (`D16` rule 3), measured with Claude Code 2.1.281 on this host:
70
+ * signed in it states `loggedIn: true` and exits 0; pointed at an empty `CLAUDE_CONFIG_DIR` it
71
+ * states `loggedIn: false` and exits 1. `--json` is the default the command documents, and it is
72
+ * passed anyway, because a default is the one part of a tool's answer that changes without notice.
73
+ */
74
+ export function signedIn(said) {
75
+ try {
76
+ const { loggedIn } = JSON.parse(said.stdout);
77
+ return typeof loggedIn === 'boolean' ? loggedIn : undefined;
78
+ } catch {
79
+ return undefined;
80
+ }
81
+ }
82
+
83
+ /** The directory, under a consumer's repository, Claude Code reads its assets from. */
84
+ export const assets = '.claude';
85
+
86
+ /**
87
+ * The model each tier Rigger fixes selects (`O4`), as #473's report recommends (item 7): `sonnet`
88
+ * resolved to `claude-sonnet-5-5` and `opus` to `claude-opus-5-5` (c32).
89
+ */
90
+ export const tiers = { standard: 'sonnet', high: 'opus' };
91
+
92
+ /**
93
+ * The variables `claude` must not inherit from the engine's environment (ruling 3 AQ5 on #467).
94
+ * Empty, as measured: #473's report removed the eleven `CLAUDE*` variables a calling Claude Code
95
+ * session carries and found no difference in the `init` record, the transcript, the debug log or
96
+ * the request sent (c1, c2, c23 to c26). None of them carries the owner's authentication, since
97
+ * every run without them signed in ("Inherited environment variables").
98
+ */
99
+ const UNSET = [];
100
+
101
+ /**
102
+ * The variable that keeps background-task output under the session's directory, and the fixed,
103
+ * dot-named directory under it that the invocation sets it to (ruling 9 on #467). #473's report
104
+ * found that output written under `/tmp/claude-<uid>/<encoded working directory>/<session>/tasks/`,
105
+ * outside the directory, whatever `TMPDIR` said (c33, c34), and moved under the directory by
106
+ * `CLAUDE_CODE_TMPDIR` (c35). #480's live run measured it on Claude Code 2.1.287: a background
107
+ * task's output landed under `<directory>/.claude-tmp/`. For a maker those files lie in its
108
+ * worktree, untracked, under the one name.
109
+ */
110
+ const TMPDIR_KEY = 'CLAUDE_CODE_TMPDIR';
111
+ const TMPDIR_NAME = '.claude-tmp';
112
+
113
+ /**
114
+ * The one folder Claude Code keeps for `directory` outside the dispatch. #629 measured on Claude
115
+ * Code 2.1.303, 2.1.304 and 2.1.306 that every character outside ASCII letters and digits becomes `-`. A name longer
116
+ * than 200 characters keeps its first 200, then `-` and the absolute value of the real path's
117
+ * signed 32-bit Java string hash in base 36. The live relation test measured this with `_`, a
118
+ * space and a real path longer than 200 characters. A later version may name them differently.
119
+ * The home is the one the session's environment selects (U8.2), left as given so L1
120
+ * can refuse an invalid value without choosing another home.
121
+ */
122
+ export function cliFolder(directory, environment) {
123
+ const home = Object.hasOwn(environment, 'CLAUDE_CONFIG_DIR')
124
+ ? environment.CLAUDE_CONFIG_DIR
125
+ : (typeof environment.HOME === 'string' ? join(environment.HOME, '.claude') : undefined);
126
+ const plain = directory.replace(/[^A-Za-z0-9]/g, '-');
127
+ if (plain.length <= 200) return { home, name: plain };
128
+ let hash = 0;
129
+ for (let index = 0; index < directory.length; index += 1) hash = ((hash << 5) - hash + directory.charCodeAt(index)) | 0;
130
+ return { home, name: `${plain.slice(0, 200)}-${Math.abs(hash).toString(36)}` };
131
+ }
132
+
133
+ /**
134
+ * The worktree tools, which #473's report found offered under both flags and withheld by
135
+ * `--disallowedTools` (c36). They are withheld from every session.
136
+ */
137
+ const WORKTREE = ['EnterWorktree', 'ExitWorktree'];
138
+
139
+ /**
140
+ * Every tool Claude Code offers a session that acts through the owner's own sessions or login,
141
+ * which `R-SAFE-9` withholds unless the repository declares it. Measured on Claude Code 2.1.287,
142
+ * by the definitions a session's request carried and the tools its `init` record listed:
143
+ *
144
+ * - `ListAgents` lists "other local Claude sessions on this machine" and the account's cloud
145
+ * sessions; #519's report found it listing four of the owner's interactive sessions;
146
+ * - `SendMessage` sends a message to any session `ListAgents` names;
147
+ * - `PushNotification` "sends a desktop notification in the user's terminal", and to their phone;
148
+ * - `RemoteTrigger` creates and manages "routines: cloud agents on a schedule" on the account;
149
+ * - `DesignSync` reads and updates claude.ai designs "through their claude.ai login".
150
+ *
151
+ * The agent tool, `Task` (sent as `Agent`), also acts through the account in one form: its
152
+ * `isolation: "remote"` "launches the agent in a remote cloud environment". The CLI runs it so only
153
+ * where the owner is signed in to claude.ai, the directory has a git remote, `~/.claude.json` holds
154
+ * `hasUsedRemoteSession` and `hasRemoteEnvironment`, and the flag `tengu_neapolitan` is on (its
155
+ * gate, read from the 2.1.287 binary). No flag, setting or path the invocation may pass withholds
156
+ * that form alone, so the whole tool is withheld, and a dispatched agent gets no subagents (O45).
157
+ * A rule may name it `Task` or `Agent` (#519's report, c2, c3), so either declares it.
158
+ *
159
+ * `Workflow`, whose definition reads "Execute a workflow script that orchestrates multiple
160
+ * subagents", is withheld for the agent tool's reason: no flag limits what a workflow's agents may
161
+ * do, so a session offered it would have subagents after all (O52).
162
+ *
163
+ * Every other tool in that record acts within the session or on its host as the session's own
164
+ * user. `Monitor`, `TaskStop`, `CronCreate`, `CronDelete`, `CronList` and `ScheduleWakeup` act
165
+ * within the session; `Bash`, `Read`, `Edit`, `Write` and `NotebookEdit` on the host;
166
+ * `ToolSearch` loads a deferred tool's definition; `ReportFindings` renders findings in the host's
167
+ * own interface; `WebFetch` and `WebSearch` reach the public web.
168
+ * Claude in Chrome, which drives the owner's browser, is kept out by `--no-chrome`. A version adding
169
+ * a tool that acts through the account offers it until this list names it.
170
+ *
171
+ * A repository declares one by naming it in its own `permissions.allow`.
172
+ */
173
+ const OWNERS = ['Task', 'Workflow', 'ListAgents', 'SendMessage', 'PushNotification', 'RemoteTrigger', 'DesignSync'];
174
+
175
+ /** The other names a rule may give a tool in `OWNERS`, each of which declares it. */
176
+ const ALIASES = { Task: ['Agent'] };
177
+
178
+ /**
179
+ * The built-in plugins Claude Code loads under `--setting-sources project`, each withheld by
180
+ * `enabledPlugins` unless the directory's own settings enable it. The first two are #473's (c36);
181
+ * the third is the one #519's report found under 2.1.287.
182
+ */
183
+ const BUILTINS = ['cc-plugin-agents-md@builtin', 'cc-plugin-telemetry@builtin', 'cc-plugin-plugin-authoring@builtin'];
184
+
185
+ /** The permission lists carried across from the directory's own settings, and nothing else. */
186
+ const RULES = ['allow', 'deny', 'ask'];
187
+
188
+ /** What a `claudeMdExcludes` glob reads as other than itself. */
189
+ const GLOB = /[*?[\]{}\\]|[!@+]\(/;
190
+
191
+ /**
192
+ * The real path of `path`, a file that need not exist: the real path of its nearest ancestor that
193
+ * does, with the rest of `path` after it. A link that exists and cannot be resolved throws, so it
194
+ * is refused rather than taken for absent.
195
+ */
196
+ function realOf(path) {
197
+ try {
198
+ lstatSync(path);
199
+ } catch {
200
+ const parent = dirname(path);
201
+ return parent === path ? path : join(realOf(parent), basename(path));
202
+ }
203
+ return realpathSync.native(path);
204
+ }
205
+
206
+ /** Whether the real path `path` lies under the real path `directory`. */
207
+ function under(path, directory) {
208
+ const between = relative(directory, path);
209
+ return between !== '' && !isAbsolute(between) && between.split(sep)[0] !== '..';
210
+ }
211
+
212
+ /**
213
+ * What `directory`'s own `.claude/settings.json` declares, as a JSON object, or an empty one where
214
+ * there is no such file. A file that is no JSON object is refused, because the CLI would ignore it
215
+ * in silence and its hooks with it.
216
+ */
217
+ function declaredIn(directory) {
218
+ const file = join(directory, '.claude', 'settings.json');
219
+ if (!existsSync(file)) return {};
220
+ let declared;
221
+ try {
222
+ declared = JSON.parse(readFileSync(file, 'utf8'));
223
+ } catch (failure) {
224
+ throw startFailure(new Error(`${file} is no JSON the Claude Code adapter can read, so it started nothing: ${failure.message}`), 'claude-settings-unreadable');
225
+ }
226
+ if (declared === null || typeof declared !== 'object' || Array.isArray(declared)) {
227
+ throw startFailure(new Error(`${file} holds no JSON object, so the Claude Code adapter started nothing`), 'claude-settings-unreadable');
228
+ }
229
+ return declared;
230
+ }
231
+
232
+ /**
233
+ * The permission rules `declared` holds, as `{ allow, deny, ask }` holding each it declares, or
234
+ * undefined where it declares none.
235
+ *
236
+ * A `-p` session ignores an untrusted directory's own `permissions.allow` and honours the same
237
+ * rule passed in `--settings` (#473's report, "A command the directory's settings do not allow";
238
+ * c38, c42). So the consumer's own rules decide, as ruling 1 Q1 has them decide, only once they are
239
+ * carried across. A mode or a directory in the same block is not, since either would skip or
240
+ * widen the checks.
241
+ */
242
+ function rulesOf(declared) {
243
+ const rules = Object.fromEntries(RULES.filter((list) => Array.isArray(declared.permissions?.[list])).map((list) => [list, declared.permissions[list]]));
244
+ return Object.keys(rules).length === 0 ? undefined : rules;
245
+ }
246
+
247
+ /**
248
+ * What makes a Bash rule name a compound command line rather than one command: any shell list or
249
+ * pipeline operator, `;`, `&`, `&&`, `|`, `||` or a line break. It is read as characters, so a rule
250
+ * holding one only inside quotes, such as `Bash(grep -E 'a|b' x)`, is refused too.
251
+ */
252
+ const COMPOUND = /[;&|\n\r]/;
253
+
254
+ /**
255
+ * The characters an anchored directory's real path may hold, so that no rule reads part of the path
256
+ * as a separator, a glob or `:*`: a glob character would let `Read(/<head>/**)` and
257
+ * `Edit(/<head>/**)` match directories beside it. A space is admitted (ruling 12 on #520), since the
258
+ * default worktree root sits beside the consumer's checkout, under a home that may hold one; #531's
259
+ * live run read, wrote and ran a command in a `head` whose path held one, with no denial. Should
260
+ * Claude Code stop matching `Read(//<path with a space>/**)`, refusing the space is the fallback,
261
+ * and that carries a README line, which is the owner's.
262
+ */
263
+ const PLAIN = /^[A-Za-z0-9/._+ -]+$/;
264
+
265
+ /**
266
+ * `rules` with the grant on each directory `reach` names, by route B of #519's report
267
+ * ("Recommendation"): a `Read` and an `Edit` rule on the directory's real path, which begins with
268
+ * `/`, so each rule begins `//`, Claude Code's form for an absolute path. Without them a session can
269
+ * neither read, write nor `cd` there (c14, c18).
270
+ *
271
+ * No `cd` rule is written (ruling 12 on #520). #531 measured on Claude Code 2.1.287 that with the
272
+ * two path rules and no `Bash(cd <head>)`, `cd <head> && npm test` ran with no permission denied. A
273
+ * version that denies a `cd` into `head` with no rule brings the rule back, written only for a path
274
+ * whose characters a Bash rule takes plainly.
275
+ *
276
+ * The commands a role runs in `head` are those the directory's own settings allow, each already a
277
+ * rule of its own. Claude Code matches a Bash rule against each part of a compound command, so
278
+ * `cd <head> && npm test` runs under `Bash(npm test)`, and a rule naming a compound line admits
279
+ * nothing, not even that line (c16, c17, c19). Such a declared rule is refused, naming it, rather
280
+ * than handed on as a grant it is not. A reached directory whose real path cannot be read is
281
+ * refused, since a rule on a path it does not resolve to was not measured to match; so is one whose
282
+ * real path holds a character outside `PLAIN`.
283
+ *
284
+ * Each relative Read or Edit allow and deny rule is anchored at `real`, the dispatch directory's
285
+ * real path, so it still holds after the session changes directory (M8-29). Each relative deny
286
+ * rule is also copied to each reached directory (O61 on #520; ruling 12).
287
+ */
288
+ function granting(rules, reach, real) {
289
+ const copied = (list, at) => atStart('claude-rule-unreadable', () => (rules?.[list] ?? []).map((rule) => anchoredAt(rule, at)).filter((copy) => copy !== undefined));
290
+ // Reached-path refusals must name the reached directory before dispatch copies are checked.
291
+ if (reach.length > 0) {
292
+ const compound = atStart('claude-rule-unreadable', () => Object.values(rules ?? {}).flat().find((rule) => /^Bash\(/.test(rule) && COMPOUND.test(rule)));
293
+ if (compound !== undefined) {
294
+ throw startFailure(new Error(`the directory's settings declare ${compound}, a rule for a compound command line, which admits nothing (#519's report, c17), so the Claude Code adapter started nothing`), 'claude-compound-rule');
295
+ }
296
+ }
297
+ const heads = reach.map((each) => atStart('directory-unusable', () => realpathSync.native(each)));
298
+ const unplain = heads.find((head) => !PLAIN.test(head));
299
+ if (unplain !== undefined) {
300
+ throw startFailure(new Error(`the reached directory ${unplain} holds a character outside letters, digits, a space and \`/._+-\`, which its rules would read as more than a path, so the Claude Code adapter started nothing`), 'claude-reached-path', { path: unplain });
301
+ }
302
+ let permissions = rules;
303
+ for (const list of ['allow', 'deny']) {
304
+ const copies = copied(list, real);
305
+ if (copies.length === 0) continue;
306
+ if (!PLAIN.test(real)) {
307
+ throw startFailure(new Error(`the dispatch directory ${real} holds a character outside letters, digits, a space and \`/._+-\`, which its rules would read as more than a path, so the Claude Code adapter started nothing`), 'claude-dispatch-path', { path: real });
308
+ }
309
+ permissions = { ...permissions, [list]: [...rules[list], ...copies] };
310
+ }
311
+ if (reach.length === 0) return permissions;
312
+ const grants = heads.flatMap((head) => [`Read(/${head}/**)`, `Edit(/${head}/**)`]);
313
+ const copies = heads.flatMap((head) => copied('deny', head));
314
+ return { ...permissions, allow: [...(permissions?.allow ?? []), ...grants], ...(copies.length > 0 ? { deny: [...(permissions?.deny ?? []), ...copies] } : {}) };
315
+ }
316
+
317
+ /** A Read or Edit rule naming a path, as its tool and its path. */
318
+ const PATH_RULE = /^(Read|Edit)\((.+)\)$/s;
319
+
320
+ /**
321
+ * The path rule `rule` anchored at the directory `at`, or undefined where it is not copied there.
322
+ * Claude Code reads a Read or Edit path as a gitignore pattern ("Read and Edit",
323
+ * code.claude.com/docs/en/permissions), and the copy matches under `at` what the rule matches under the
324
+ * working directory, depth for depth:
325
+ *
326
+ * - `path` and `./path` alike: one segment, alone or before `/**` or a trailing `/`, at any depth, as
327
+ * `**\/path`; more than one segment, at its own place under the current directory only.
328
+ * Measured, each rule in a working directory's own settings: `Read(./.env)` denied `.env` and
329
+ * `sub/.env` (Claude Code 2.1.287, #531's engineer judge; 2.1.288, the maker's probe);
330
+ * `Read(secrets/**)`, `Read(secrets/)` and `Read(./secrets/**)` each denied `secrets/token` and
331
+ * `sub/secrets/token`, and `Read(./a/b.txt)` and `Read(a/b.txt)` denied `a/b.txt` and not
332
+ * `x/a/b.txt` (2.1.288, the maker's probes). The dispatch and reached directories use that same
333
+ * mapping. A version that reads `./` as the top only, as the docs' "relative to current
334
+ * directory" suggests, would require changing this mapping to retain the declared root behavior.
335
+ * - `/path` is "relative to the settings source", which for the consumer's project settings is the
336
+ * repository's root. Passed inline in `--settings` it does not hold there: #531 measured on Claude
337
+ * Code 2.1.287 that `Read(/secret.txt)` passed inline let a session read the working directory's
338
+ * `secret.txt`, while the same rule in the project's own `.claude/settings.json` denied it. Where
339
+ * the inline rule does resolve was not measured. So it is copied to each reached directory and,
340
+ * to the working directory too (ruling 12 on #520).
341
+ * - `//path` and `~/path` name one place already and are not copied.
342
+ * - A `!` pattern is read relative to the current directory and cannot carve anything out of an
343
+ * anchored rule, so it is not copied, and a reached directory's copies may block what the working
344
+ * directory spares. That errs toward the consumer's deny intent and never widens (ruling 12). A
345
+ * judge measured unable to do its card's work for a negation its copies could not carry reverses
346
+ * it, as a placement question for the architect.
347
+ */
348
+ function anchoredAt(rule, at) {
349
+ const match = PATH_RULE.exec(rule);
350
+ if (match === null) return undefined;
351
+ const [, tool, path] = match;
352
+ if (path.startsWith('//') || path.startsWith('~/') || path.startsWith('!')) return undefined;
353
+ if (path.startsWith('/')) return `${tool}(/${at}${path})`;
354
+ const bare = path.startsWith('./') ? path.slice(2) : path;
355
+ const relative = bare === '**' || bare.replace(/\/(\*\*)?$/, '').includes('/') ? bare : `**/${bare}`;
356
+ return `${tool}(/${at}/${relative})`;
357
+ }
358
+
359
+ /** Every `CLAUDE.md` above `directory`, up to the root, as absolute paths. */
360
+ function above(directory) {
361
+ const files = [];
362
+ for (let at = dirname(directory); ; at = dirname(at)) {
363
+ files.push(join(at, 'CLAUDE.md'));
364
+ if (dirname(at) === at) return files;
365
+ }
366
+ }
367
+
368
+ /**
369
+ * The command line that runs the agent file `agent`, at `tier`, on `prompt`, in `directory`: the
370
+ * CLI by its command name, its arguments, the prompt's bytes for its standard input, the variables
371
+ * it must not inherit, and the variables it sets, each a path under `directory` (ruling 9 on
372
+ * #467). Each directory `reach` names is granted by `granting`; the prompt is handed over as given,
373
+ * so whoever composes it names the directory there. It runs nothing, so it leaves `emitter` unused
374
+ * (ruling 5 on #467).
375
+ *
376
+ * Refused, each naming what it refused: a tier Rigger does not fix; an agent file whose real path is not under `directory`
377
+ * (`R-SAFE-6`), though the file is not read and need not exist; a directory under a path holding a
378
+ * glob character, which its `CLAUDE.md` exclusions would read as a pattern; a settings file in
379
+ * `directory` that is no JSON object; a dispatch real path outside `PLAIN` needing an anchored
380
+ * rule; and, given `reach`, a reached directory with no real path, one
381
+ * whose real path holds a character outside `PLAIN`, or a declared Bash rule for a compound line.
382
+ */
383
+ export async function invocation({ agent, tier, prompt, directory, card, reach = [], emitter, environment = process.env }) {
384
+ if (!Object.hasOwn(tiers, tier)) {
385
+ throw new Error(`the Claude Code adapter maps no model to the tier \`${tier}\`, only to \`standard\` and \`high\``);
386
+ }
387
+ const real = atStart('directory-unusable', () => realpathSync.native(directory));
388
+ const file = resolve(directory, agent);
389
+ const fileReal = atStart('agent-unresolved', () => realOf(file), { file: agent });
390
+ if (!under(fileReal, real)) {
391
+ throw startFailure(new Error(`the agent file ${agent} lies at ${fileReal}, outside the consumer's repository ${real}, so the Claude Code adapter refused it (R-SAFE-6)`), 'agent-outside', { file: agent });
392
+ }
393
+ const excludes = [...new Set([...above(resolve(directory)), ...above(real)])];
394
+ const globbed = excludes.find((each) => GLOB.test(each));
395
+ if (globbed !== undefined) {
396
+ const path = atStart('directory-unusable', () => realpathSync.native(dirname(globbed)));
397
+ throw startFailure(new Error(`the directory ${directory} lies under a path holding a glob character, as ${globbed} does, so its \`claudeMdExcludes\` entries would match other files`), 'claude-exclusion-path', { path });
398
+ }
399
+ const mcp = join(directory, '.mcp.json');
400
+ const declared = declaredIn(directory);
401
+ const allowed = rulesOf(declared)?.allow ?? [];
402
+ const declares = (tool) => [tool, ...(ALIASES[tool] ?? [])].some((each) => allowed.includes(each));
403
+ const withheld = [...WORKTREE, ...OWNERS.filter((tool) => !declares(tool))];
404
+ const enabledPlugins = Object.fromEntries(BUILTINS.filter((id) => declared.enabledPlugins?.[id] !== true).map((id) => [id, false]));
405
+ let permissions = granting(rulesOf(declared), reach, real);
406
+ if (card !== undefined) permissions = { ...permissions, allow: [...(permissions?.allow ?? []), `Bash(gh issue comment ${card} --body-file .rigger-escalation.md)`] };
407
+ const settings = { autoMemoryEnabled: false, claudeMdExcludes: excludes, enabledPlugins, permissions };
408
+ return {
409
+ command: 'claude',
410
+ args: [
411
+ '-p', '--output-format', 'stream-json', '--verbose', '--include-hook-events',
412
+ '--model', tiers[tier],
413
+ '--strict-mcp-config', ...(existsSync(mcp) ? ['--mcp-config', mcp] : []),
414
+ '--setting-sources', 'project',
415
+ '--settings', JSON.stringify(settings),
416
+ '--disallowedTools', withheld.join(','),
417
+ '--no-session-persistence',
418
+ '--disable-slash-commands',
419
+ '--no-chrome',
420
+ '--append-system-prompt-file', file,
421
+ ],
422
+ input: Buffer.from(prompt, 'utf8'),
423
+ unset: [...UNSET],
424
+ env: { [TMPDIR_KEY]: join(real, TMPDIR_NAME) },
425
+ folder: cliFolder(real, environment),
426
+ };
427
+ }