rungate 0.8.1 → 0.8.2

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.
@@ -47,8 +47,50 @@
47
47
  * Using `stripQuoted` for both would let an attacker quote the path; using
48
48
  * `dequote` for both reinstates all four false positives. Each test below
49
49
  * names which one it uses and why.
50
+ *
51
+ * ## The names are global; the artifacts are not (#1175)
52
+ *
53
+ * `PROTECTED_FILES` is a list of NAMES, and until #1175 a name matched in any
54
+ * tree. A fixture at `/tmp/rg-abc/workflow-state.json` was refused as readily
55
+ * as a live run's state, which is a true positive against the rule and a false
56
+ * positive against intent — agents on this repo build such fixtures
57
+ * constantly, including fixtures for this module.
58
+ *
59
+ * The scoping is by SCRATCH TREE rather than by project root, and that is a
60
+ * measurement and not a preference. #1175's acceptance asked for "the path
61
+ * relative to the project root". Swept over 5,531 real commands, the gate
62
+ * artifacts named in them resolve like this:
63
+ *
64
+ * 2,620 under the run store (`$RUNGATE_WORK_DIR`, i.e. `~/.rungate`)
65
+ * 521 under a former run store (`~/.pai-work`) or `~/.claude`
66
+ * 1,724 no resolvable path at all — a bare basename, or built by `join`
67
+ * 83 under an OS temp root
68
+ * 65 relative
69
+ * 16 under a repository tree
70
+ *
71
+ * A live `workflow-state.json` is almost never inside the project root: it is
72
+ * in the run store, one level up and sideways. "Protect what is under the
73
+ * root" would therefore have stopped protecting 3,141 of 3,240 absolute
74
+ * references — reopening `pai-config#473` C1, the forge-a-gate-result attack
75
+ * this guard was built for. The root-relative reading is recorded here as
76
+ * MEASURED WRONG rather than merely not chosen.
77
+ *
78
+ * So the question asked is the fail-closed one: can this path be shown to be
79
+ * in a scratch tree? Only then is it a fixture. Every other answer —
80
+ * elsewhere, relative, or not a path at all — keeps the old refusal. An
81
+ * allowlist is normally the wrong shape here and `pai-config#474`'s
82
+ * read-only-prefix list is why: a PREFIX says nothing about what a command
83
+ * writes. A scratch root says something about the DESTINATION, is consulted
84
+ * only after the destination has been extracted, and is not a judgement call
85
+ * — each entry is a value `mktemp -d` returns on a supported platform.
86
+ * Narrowing it over-blocks; it cannot open a hole.
50
87
  */
51
88
 
89
+ import { realpathSync, statSync } from 'fs';
90
+ import { tmpdir } from 'os';
91
+ import { basename, dirname, join, resolve } from 'path';
92
+ import { isInterpreterWord, isShellWord } from './interpreters';
93
+
52
94
  /** Gate artifacts. A write to any of these must come from the gate runner. */
53
95
  export const PROTECTED_FILES = ['workflow-state.json', '.gate-salt', '/witnesses/'];
54
96
 
@@ -62,6 +104,406 @@ export interface BashWriteDecision {
62
104
 
63
105
  const ALLOW: BashWriteDecision = { blocked: false };
64
106
 
107
+ /**
108
+ * The trees an OS temporary directory can be in.
109
+ *
110
+ * `/tmp` and `/private/tmp` are both listed because on macOS they are the
111
+ * same directory under two names and a command may spell either; `resolve()`
112
+ * normalises `..` but does not follow links, and the link cannot be followed
113
+ * here because the path being judged usually does not exist yet — it is about
114
+ * to be created. `/var/folders` is where macOS puts a per-user `$TMPDIR`, and
115
+ * `tmpdir()` covers whatever the platform or the environment says, which is
116
+ * what `mkdtemp`, `mkstemp` and `mktemp -d` all build on.
117
+ *
118
+ * Each root is also recorded in its REALPATH form. On macOS `/var` is a
119
+ * symlink to `/private/var`, so `tmpdir()` hands back `/var/folders/…/T`
120
+ * while the resolution below hands back `/private/var/folders/…/T`, and a
121
+ * list holding only the first form answers `false` for every path spelled
122
+ * the way `mkdtemp` hands it to a program.
123
+ *
124
+ * The corpus does NOT show this, and saying so is the point: real commands
125
+ * spell `/tmp` literally, so all 37 fixture commands clear either way. It
126
+ * was found by `isScratchPath, asserted directly` calling `tmpdir()`, which
127
+ * is what a program does and what a person does not. A sweep over what
128
+ * people typed cannot see a defect in what their programs compute.
129
+ *
130
+ * Read at call time rather than frozen at import, because `TMPDIR` is what a
131
+ * test harness moves when it wants its own scratch space, and a guard that
132
+ * cached the old value would refuse the new one.
133
+ *
134
+ * ## `TMPDIR` is the writer's variable, so it is not trusted
135
+ *
136
+ * The first version of this took `process.env.TMPDIR` as given. Measured:
137
+ *
138
+ * TMPDIR unset isScratchPath(…/.rungate/x/…) = false
139
+ * TMPDIR=$HOME/.rungate = true
140
+ *
141
+ * The agent whose write is being judged sets the variable that decides
142
+ * whether the write is exempt, and pointing it at the run store switches the
143
+ * guard off for the one directory it exists to protect. `tmpdir()` is the
144
+ * same hole wearing a function call — on POSIX it READS `TMPDIR`.
145
+ *
146
+ * So `FIXED` is the whole of the trust, and the environment can only ever
147
+ * SELECT within it: a `TMPDIR` that does not already resolve inside a fixed
148
+ * root is dropped. A platform whose temp directory is somewhere else
149
+ * over-blocks, which is the direction this module is allowed to be wrong in.
150
+ */
151
+ const FIXED_SCRATCH_ROOTS = ['/tmp', '/private/tmp', '/var/folders'];
152
+
153
+ /**
154
+ * Trees that hold LIVE artifacts, wherever on the disk they are.
155
+ *
156
+ * This is SUBTRACTED from the exemption in `isScratchPath`, not merely used
157
+ * to vet the root list. The difference matters: vetting roots is a proxy for
158
+ * the property, and it only holds for roots somebody thought of. Subtracting
159
+ * the trees themselves IS the property — "a live artifact is never exempt" —
160
+ * and it keeps holding when a root is added later by someone who has not
161
+ * read this comment.
162
+ *
163
+ * The two mechanisms are also not interchangeable, and conflating them was
164
+ * measured. Dropping a ROOT because it contains a protected tree removes
165
+ * `/tmp` wholesale the moment `RUNGATE_WORK_DIR` points inside it — which a
166
+ * real corpus command does — and refuses every fixture on the machine.
167
+ * Subtracting the TREE removes only that subtree and leaves the rest of
168
+ * `/tmp` exempt. So the root list is vetted only against trees that are not
169
+ * themselves scratch, and the subtraction below applies unconditionally.
170
+ *
171
+ * ## The hook directories are here because a checkout CAN be the live hook
172
+ *
173
+ * A review argued that `PROTECTED_HOOKS` should lose the scratch exemption
174
+ * entirely, on the grounds that a `.hook.ts` under `/tmp` is as likely to be
175
+ * a real checkout as a fixture — worktrees under `/tmp` are routine here.
176
+ * The counter-argument offered was that a hook source in a checkout is not
177
+ * the live hook, so compromising one does nothing until it is deployed.
178
+ *
179
+ * That counter-argument is FALSE on this machine, and `lib/hook-target-tree.ts`
180
+ * is where it was measured: every registration in `~/.claude/settings.json`
181
+ * is spelled `${PAI_HOOKS_DIR}/…` or `${RUNGATE_HOOKS_DIR}/…`, and
182
+ * `RUNGATE_HOOKS_DIR` resolved to *a checkout that is not this one*, with
183
+ * fourteen hooks executing from it. #999's shell-injection fix never reached
184
+ * the bytes that run. A checkout is the live hook exactly when a variable
185
+ * says it is.
186
+ *
187
+ * So the answer is neither "refuse the exemption for hooks" nor "trust the
188
+ * checkout": resolve where the registrations actually point and subtract
189
+ * THAT, wherever it is — including when it is under `/tmp`. A hook in a
190
+ * worktree nothing registers stays a fixture, which is the case #1175 exists
191
+ * for; a hook in the tree that is actually wired stays protected, which is
192
+ * the case the review was worried about.
193
+ *
194
+ * `process.cwd()` is deliberately NOT here, and the reason is measured. A
195
+ * checkout under `/tmp` is ordinary on this machine — the worktree this was
196
+ * written in is `/private/tmp/rg-1175-wt` — so treating the working
197
+ * directory as protected drops `/private/tmp` from the roots, and because
198
+ * `/tmp` realpaths to it the walk then refuses every `/tmp` path as well.
199
+ * 12 of 145 tests red, measured.
200
+ *
201
+ * ## BOTH spellings, which #1175 got wrong
202
+ *
203
+ * `resolve()` normalises `.` and `..`; it does not follow a symlink. So a
204
+ * tree named `/tmp/e2e` stayed in this list as `/tmp/e2e` while a path
205
+ * through the same inode reads `/private/tmp/e2e/…`, and `inAnyTree`
206
+ * matches neither spelling against the other. Executed against the module
207
+ * as merged, with `RUNGATE_WORK_DIR=/tmp/e2e`:
208
+ *
209
+ * /tmp/e2e/s/workflow-state.json blocked
210
+ * /private/tmp/e2e/s/workflow-state.json ALLOWED ← the run store
211
+ *
212
+ * The same for `RUNGATE_HOOKS_DIR`, and `/tmp` is a symlink to
213
+ * `/private/tmp` on every macOS install, so the second spelling is not
214
+ * exotic — it is what `realpath` prints.
215
+ *
216
+ * `scratchRoots()` below already recorded both spellings for the fixed
217
+ * roots, so the asymmetry was inside one file: the roots a write may land
218
+ * in were realpathed and the trees it may not were not. A `catch` here
219
+ * means the tree is not on disk, which is ordinary for a variable pointing
220
+ * at a directory the command is about to create, and the resolved spelling
221
+ * stands on its own.
222
+ */
223
+ function protectedTrees(): string[] {
224
+ const home = process.env.HOME || '';
225
+ const spellings: string[] = [];
226
+ for (const p of [
227
+ // The run store — where 2,620 of 3,240 absolute artifact references live.
228
+ process.env.RUNGATE_WORK_DIR || '',
229
+ home ? join(home, '.rungate') : '',
230
+ home ? join(home, '.claude') : '',
231
+ // The trees a hook registration resolves to. Read from the environment
232
+ // because that is what the registrations are spelled with.
233
+ process.env.PAI_HOOKS_DIR || '',
234
+ process.env.RUNGATE_HOOKS_DIR || '',
235
+ home ? join(home, '.pai', 'hooks') : '',
236
+ ].filter(Boolean)) {
237
+ const normalised = resolve(p);
238
+ spellings.push(normalised);
239
+ try {
240
+ const real = realpathSync(normalised);
241
+ if (real !== normalised) spellings.push(real);
242
+ } catch {
243
+ // Not on disk. The resolved spelling above still stands.
244
+ }
245
+ }
246
+ return spellings;
247
+ }
248
+
249
+ /** Is `p` inside, or equal to, any of `trees`? */
250
+ function inAnyTree(p: string, trees: string[]): boolean {
251
+ return trees.some(t => p === t || p.startsWith(t + '/'));
252
+ }
253
+
254
+ function scratchRoots(): string[] {
255
+ const out: string[] = [];
256
+ const contains = (root: string, p: string) => p === root || p.startsWith(root + '/');
257
+
258
+ const fixed: string[] = [];
259
+ for (const r of FIXED_SCRATCH_ROOTS) {
260
+ const n = resolve(r);
261
+ fixed.push(n);
262
+ try {
263
+ fixed.push(realpathSync(n));
264
+ } catch {
265
+ // A root that is not on this disk is still a name a command can spell.
266
+ }
267
+ }
268
+
269
+ // A protected tree that is ITSELF inside a fixed scratch root is not a
270
+ // reason to drop that root. `RUNGATE_WORK_DIR=/tmp/e2e-gate-test` is a real
271
+ // corpus command — a harness deliberately putting the run store in scratch
272
+ // for a test — and without this clause it drops `/tmp` and refuses every
273
+ // fixture on the machine, which is the same self-defeat `process.cwd()`
274
+ // caused. Measured: `isScratchPath('/tmp/p/x')` goes false under that one
275
+ // environment variable.
276
+ const guarded = protectedTrees().filter(t => !fixed.some(f => contains(f, t)));
277
+ const add = (p: string) => {
278
+ if (p === '/' || out.includes(p)) return;
279
+ // The invariant, enforced rather than documented: an exemption root that
280
+ // contains a protected tree is not an exemption root.
281
+ if (guarded.some(t => contains(p, t))) return;
282
+ out.push(p);
283
+ };
284
+
285
+ for (const f of fixed) add(f);
286
+
287
+ // The environment SELECTS within the fixed set; it cannot extend it.
288
+ for (const r of [tmpdir(), process.env.TMPDIR ?? '']) {
289
+ if (!r || !r.startsWith('/')) continue;
290
+ const n = resolve(r);
291
+ let real = n;
292
+ try {
293
+ real = realpathSync(n);
294
+ } catch {
295
+ /* not on this disk; judge the spelling */
296
+ }
297
+ if (!fixed.some(f => contains(f, n) || contains(f, real))) continue;
298
+ add(n);
299
+ add(real);
300
+ }
301
+ return out;
302
+ }
303
+
304
+ /**
305
+ * Is this path demonstrably inside a scratch tree?
306
+ *
307
+ * Only an ABSOLUTE path can be placed in a tree, so everything else — a bare
308
+ * basename, a relative path, a `join(dir, "workflow-state.json")` whose `dir`
309
+ * lives in a variable — answers `false` and stays refused. That is the whole
310
+ * fail-closed property: this function's job is to say YES, and silence means
311
+ * the old behaviour.
312
+ *
313
+ * `resolve()` first, per #1129: a destination spelled `/tmp/../Users/me/
314
+ * .rungate/x/workflow-state.json` is not in `/tmp`, and comparing the
315
+ * unnormalised string would say it is.
316
+ *
317
+ * The deepest EXISTING ancestor is then realpath'd, which is the half
318
+ * `resolve()` cannot do. Without it, `ln -s ~/.rungate/slug /tmp/esc` followed
319
+ * by a write to `/tmp/esc/workflow-state.json` is a two-command bypass of the
320
+ * thing this guard protects. The stat happens only after a protected NAME has
321
+ * already matched, so the common command pays nothing for it.
322
+ *
323
+ * It does NOT close the case where the link is made by the SAME command —
324
+ * see `exemptionIsVoid`, which is where that is handled, because the answer
325
+ * is a property of the command and not of the path.
326
+ *
327
+ * An UNEXPANDED expansion is refused. `/tmp/$X/workflow-state.json` is not a
328
+ * path, it is a path the shell will build, and `$X` may be `../../Users/me/
329
+ * .rungate/slug`. Five of the six spellings a review raised were already
330
+ * refused by `resolve()` and the `startsWith('/')` precondition — `${X}`, the
331
+ * backtick form, `/tmp/../…`, `$HOME/…` and `~/…` — and this is the sixth.
332
+ * Measured cost of refusing it: 0 of the 37 commands this branch clears, with
333
+ * 209 corpus-wide carrying a `$` in an artifact path, none of them in the
334
+ * population at stake.
335
+ *
336
+ * Both exits below return `false`. They are all but unreachable — the
337
+ * deepest artifact path in the corpus is 6 components against a cap of 64,
338
+ * and the walk only runs out of parents if `realpathSync('/')` throws — but
339
+ * an unreachable fail-OPEN in a fail-closed module is a line that reads as
340
+ * permission, and the next person to make the walk reachable inherits it.
341
+ */
342
+
343
+ /**
344
+ * Glob and brace metacharacters, tested against the DIRECTORY part only.
345
+ *
346
+ * `echo '{}' > /tmp/sym*​/workflow-state.json`, with `/tmp/syma` a symlink
347
+ * into the run store: `/tmp/sym*` does not exist, the walk climbs past it to
348
+ * `/tmp`, and the path is exempted — then the shell expands the glob and the
349
+ * write goes through the link. Same escape as the symlink case with no `ln`
350
+ * in the command for `exemptionIsVoid` to see.
351
+ *
352
+ * Only the directory part is tested, and that is measured rather than
353
+ * cautious. A glob in the BASENAME is already safe, because the directory
354
+ * above it is the thing `resolveThroughLinks` resolves — built and executed:
355
+ * with `SRC/syma` linked out of scratch, `SRC/syma/*.json` answers false and
356
+ * `SRC/sym*​/x` answered true. So the basename case needs no refusal, and
357
+ * refusing it anyway costs a real command: `rm -f /tmp/713-battery/
358
+ * pai-wrongfix/*.hook.ts` is 1 of the 37 this branch clears, and a blanket
359
+ * metacharacter class takes it back. Restricting the test to the directory
360
+ * part closes the escape at a measured cost of 0.
361
+ *
362
+ * The exact class a review proposed, `[$`*?[]{}~]` tested against the whole
363
+ * path, was swept over the same 5,573-command corpus: it takes back 1 of the
364
+ * 37, that `rm -f`. It does not ship on caution either way — it ships on the
365
+ * reading, and the reading is 1 against 0.
366
+ */
367
+ const UNRESOLVED_DIR = /[*?[\]{}]/;
368
+ export function isScratchPath(path: string): boolean {
369
+ if (!path || !path.startsWith('/')) return false;
370
+ if (/[$`]/.test(path)) return false;
371
+ // A glob in a DIRECTORY component is unresolvable and escapes; one in the
372
+ // basename does not. See `UNRESOLVED_DIR` for the measurement.
373
+ if (UNRESOLVED_DIR.test(dirname(path))) return false;
374
+
375
+ const normalised = resolve(path);
376
+ const real = resolveThroughLinks(normalised);
377
+ if (real === null) return false;
378
+
379
+ // The subtraction, applied to BOTH the spelling and the resolved path. A
380
+ // live artifact is never exempt, whichever of the two names it.
381
+ const live = protectedTrees();
382
+ if (inAnyTree(normalised, live) || inAnyTree(real, live)) return false;
383
+
384
+ const roots = scratchRoots();
385
+ return inAnyTree(normalised, roots) && inAnyTree(real, roots);
386
+ }
387
+
388
+ /**
389
+ * The path with its deepest EXISTING ancestor resolved through symlinks, and
390
+ * the not-yet-created tail re-attached. `null` when nothing in the chain can
391
+ * be resolved — which is the fail-closed answer, not a missing one.
392
+ */
393
+ function resolveThroughLinks(normalised: string): string | null {
394
+ let dir = normalised;
395
+ let suffix = '';
396
+ for (let i = 0; i < 64; i++) {
397
+ try {
398
+ const real = realpathSync(dir);
399
+ return suffix ? resolve(real, suffix) : real;
400
+ } catch {
401
+ const parent = dirname(dir);
402
+ if (parent === dir) return null;
403
+ suffix = suffix ? join(basename(dir), suffix) : basename(dir);
404
+ dir = parent;
405
+ }
406
+ }
407
+ return null;
408
+ }
409
+
410
+ /**
411
+ * Does this command do something that makes a resolved path untrustworthy?
412
+ *
413
+ * `isScratchPath` resolves the destination's existing ancestors at DECISION
414
+ * time. A command that creates a symbolic link before it writes invalidates
415
+ * that resolution between the decision and the execution, and the whole
416
+ * thing fits in one command:
417
+ *
418
+ * ln -s ~/.rungate/victim /tmp/esc && echo '{}' > /tmp/esc/workflow-state.json
419
+ *
420
+ * At decision time `/tmp/esc` does not exist, the walk reaches `/tmp`, and
421
+ * the write is exempted. Then the shell creates the link and the write lands
422
+ * in the run store. Both halves were executed: the module allowed the
423
+ * command, and a real shell put the bytes through the link. This is a
424
+ * bypass, not a race — no second actor is required.
425
+ *
426
+ * `mkdir -p` is the overwhelmingly common thing a fixture does to a path that
427
+ * does not exist yet, and a directory cannot point out of its tree. Only a
428
+ * LINK can, so only link creation voids the exemption. Measured: 0 of the 37
429
+ * commands this branch clears create one, and 9 commands in the whole 5,550
430
+ * corpus match at all.
431
+ *
432
+ * ## The verb is resolved, not pattern-matched
433
+ *
434
+ * The first version tested `/(?:^|[\s;&|(])ln\s/` against the raw command,
435
+ * which requires whitespace or a separator immediately before `ln`. Measured:
436
+ * `ln -s`, `sudo ln` and `find -exec ln` voided, but **`/bin/ln -s … /tmp/x`
437
+ * and `\ln -s … /tmp/x` did not** — two spellings the shell resolves
438
+ * identically to the one that did, walking past the control the whole
439
+ * exemption rests on.
440
+ *
441
+ * `commandWord` already strips a leading path and a leading `\` or `(`, and
442
+ * already skips `sudo`, `env`, `xargs` and the other wrappers, because
443
+ * #1120 and #1184 taught it to. Running it per segment is one tokeniser
444
+ * instead of two and gets all of that for free, so the segment's resolved
445
+ * VERB is the primary test.
446
+ *
447
+ * `LINK_CREATION` stays as a second, broader net for the positions a command
448
+ * word cannot reach: `find . -exec ln …` resolves to `find`, and
449
+ * `symlinkSync` lives inside an interpreter body this module does not parse.
450
+ * It is read off the raw command for that reason — the link and the write
451
+ * are in different segments by construction.
452
+ *
453
+ * `mkdir -p` is the overwhelmingly common thing a fixture does to a path that
454
+ * does not exist yet, and a directory cannot point out of its tree. Only a
455
+ * LINK can, so only link creation voids the exemption. Measured: 0 of the 37
456
+ * commands this branch clears create one.
457
+ */
458
+ const LINK_CREATION = /\bln\s|\bsymlinkSync\b|\bos\.symlink\b|\bsymlink\s*\(/;
459
+
460
+ /**
461
+ * #1240: both tests read a view that KEEPS the text an interpreter is going
462
+ * to run. `stripHeredocs` deletes a heredoc body, so an `ln` inside
463
+ * `bash <<'EOF'` was invisible to the first test; `segments(cmd)` over the
464
+ * raw command does not make a body's lines into segments, so it was
465
+ * invisible to the second as well. One view, built once, fed to both.
466
+ */
467
+ function exemptionIsVoid(cmd: string): boolean {
468
+ const programs = interpreterPrograms(cmd).map(p => p.program);
469
+ const view = [stripHeredocs(cmd), ...programs].join('\n');
470
+ if (LINK_CREATION.test(view)) return true;
471
+ return segments(view).some(seg => commandWord(seg) === 'ln');
472
+ }
473
+
474
+ /**
475
+ * Path-like words in `text` that contain `needle`.
476
+ *
477
+ * A word here ends at whitespace or at a character that cannot be inside a
478
+ * shell or source-literal path — a quote, a comma, a bracket, a semicolon.
479
+ * That is deliberately crude and deliberately in the refusing direction: when
480
+ * a path is assembled rather than written out, the word this returns is the
481
+ * fragment that WAS written, which is relative, which `isScratchPath` refuses
482
+ * to exempt.
483
+ *
484
+ * Case-folded for the same reason `names()` is (#1184): the default macOS
485
+ * filesystem resolves `WORKFLOW-STATE.JSON` and `workflow-state.json` to one
486
+ * inode, so a case-sensitive search here would find no path word for the
487
+ * uppercase spelling, and a name with no path words is not exempted — it
488
+ * would refuse rather than leak. Folding keeps the two readings agreeing
489
+ * instead of agreeing by accident.
490
+ */
491
+ function pathWordsContaining(text: string, needle: string): string[] {
492
+ const out: string[] = [];
493
+ const hay = text.toLowerCase();
494
+ const pin = needle.toLowerCase();
495
+ let i = 0;
496
+ while ((i = hay.indexOf(pin, i)) !== -1) {
497
+ let s = i;
498
+ while (s > 0 && !/[\s'"`,;(){}[\]]/.test(hay[s - 1])) s--;
499
+ let e = i + pin.length;
500
+ while (e < hay.length && !/[\s'"`,;(){}[\]]/.test(hay[e])) e++;
501
+ out.push(text.slice(s, e)); // the ORIGINAL case: this is a path to resolve
502
+ i = e;
503
+ }
504
+ return out;
505
+ }
506
+
65
507
  /**
66
508
  * Split a command at top-level `;`, `&&`, `||`, `|` and newline, leaving
67
509
  * separators inside quotes alone.
@@ -87,7 +529,27 @@ export function segments(cmd: string): string[] {
87
529
  const c = cmd[i];
88
530
  if (quote) {
89
531
  cur += c;
90
- if (c === quote && cmd[i - 1] !== '\\') quote = null;
532
+ // #1203: inside SINGLE quotes nothing is escaped, not even a backslash,
533
+ // so the first `'` always closes. Treating `\'` as an escape there kept
534
+ // the span open past its real end, and everything after it — the
535
+ // separator AND the write verb — was swallowed into one segment where
536
+ // `commandWord` could never reach the verb. Inside DOUBLE quotes `\"`
537
+ // IS an escape, which is why the two cases are told apart rather than
538
+ // handled by one rule.
539
+ //
540
+ // #1249: inside DOUBLE quotes, consume the escape PAIR rather than
541
+ // looking one character back. `\\` is an escaped BACKSLASH — a
542
+ // complete pair — and the `"` after it closes the span. A lookbehind
543
+ // cannot tell that `"` from the escaped one in `\"`, so `"x\\"` was
544
+ // read as still open and the rest of the command, separator and write
545
+ // verb together, became one segment whose command word is `echo`. The
546
+ // outside-quote branch below already consumes the pair, for this same
547
+ // reason; this is that rule applied inside the span.
548
+ if (quote === '"' && c === '\\' && i + 1 < cmd.length) {
549
+ cur += cmd[++i];
550
+ continue;
551
+ }
552
+ if (c === quote) quote = null;
91
553
  continue;
92
554
  }
93
555
  if (c === '"' || c === "'") {
@@ -95,6 +557,31 @@ export function segments(cmd: string): string[] {
95
557
  cur += c;
96
558
  continue;
97
559
  }
560
+ // #1203: a backslash-newline is a LINE CONTINUATION. The shell joins the
561
+ // two lines into one command before it looks for anything else, so
562
+ // splitting on that newline put the verb in one segment and its target in
563
+ // the next, and `cp x \<nl> /r/workflow-state.json` reached the `cp` arm
564
+ // with a single operand. Same class as #1176 and #1184 — a check reading a
565
+ // transformed view whose transformation relocated the token — except this
566
+ // one relocates it across a SEGMENT boundary rather than into a quote.
567
+ //
568
+ // Joining with NOTHING, not with a space, because that is what the shell
569
+ // does: `ch\<nl>mod 777 x.hook.ts` runs chmod, so `commandWord` has to
570
+ // resolve `chmod` too. Inserting a space would read the verb as `ch`.
571
+ //
572
+ // Only outside a quote. Inside single quotes the backslash is literal and
573
+ // the newline is data, which is the negative control this must not break.
574
+ if (c === '\\') {
575
+ if (cmd[i + 1] === '\n') {
576
+ i++;
577
+ continue;
578
+ }
579
+ // An ESCAPED backslash. Consume the pair, so `\\` at end of line leaves
580
+ // no dangling `\` to swallow the newline that genuinely separates.
581
+ cur += c;
582
+ if (i + 1 < cmd.length) cur += cmd[++i];
583
+ continue;
584
+ }
98
585
  if (c === ';' || c === '\n' || c === '|' || c === '&') {
99
586
  if (cmd[i + 1] === c) i++; // `&&`, `||` are one separator, not two
100
587
  out.push(cur);
@@ -171,24 +658,156 @@ export function stripHeredocs(s: string): string {
171
658
  }
172
659
 
173
660
  /**
174
- * The delimiter word of a `<<WORD` on this line, if any.
661
+ * Which character positions on this line are OUTSIDE every quoted span.
662
+ *
663
+ * A `$(` opens a COMMAND SUBSTITUTION, and the shell parses its contents as a
664
+ * fresh command with fresh quoting — so text inside `"$( … )"` is unquoted
665
+ * even though it sits between double quotes. That one rule is the whole
666
+ * difference between the two cases in #1196's H6, and it is why this is a
667
+ * small stack rather than a boolean. Single quotes do not substitute, so a
668
+ * `$(` inside them is literal and opens nothing.
669
+ *
670
+ * Deliberately per-line, matching its only caller: a quote opened on an
671
+ * earlier line reads as unquoted here. That is the behaviour this function
672
+ * replaced — which was not quote-aware at all — so no case gets worse, and
673
+ * the direction it is wrong in deletes text rather than admitting it.
674
+ */
675
+ function unquotedPositions(line: string): boolean[] {
676
+ const open = new Array<boolean>(line.length).fill(false);
677
+ const stack: string[] = ['']; // quote state per substitution depth
678
+ let i = 0;
679
+ while (i < line.length) {
680
+ const q = stack[stack.length - 1];
681
+ const c = line[i];
682
+ if (q === "'") {
683
+ if (c === "'") stack[stack.length - 1] = '';
684
+ i++;
685
+ } else if (q === '"') {
686
+ if (c === '\\') i += 2;
687
+ else if (c === '$' && line[i + 1] === '(') (stack.push(''), (i += 2));
688
+ else if (c === '"') (stack[stack.length - 1] = ''), i++;
689
+ else i++;
690
+ } else if (c === '\\') {
691
+ i += 2;
692
+ } else if (c === '$' && line[i + 1] === '(') {
693
+ open[i] = open[i + 1] = true;
694
+ stack.push('');
695
+ i += 2;
696
+ } else if (c === ')' && stack.length > 1) {
697
+ stack.pop();
698
+ i++;
699
+ } else if (c === '"' || c === "'") {
700
+ stack[stack.length - 1] = c;
701
+ i++;
702
+ } else {
703
+ open[i] = true;
704
+ i++;
705
+ }
706
+ }
707
+ return open;
708
+ }
709
+
710
+ /**
711
+ * The delimiter word of a `<<WORD` on this line, if any — at a position the
712
+ * shell would read as an operator rather than as text.
175
713
  *
176
- * #1176: deliberately NOT quote-aware, and that is load-bearing. Restricting
177
- * this to a top-level `<<` — the obvious hardening — was tried and REDDENS
178
- * the recorded `pai-config#474` false positive, whose heredoc is legitimately
179
- * nested inside `"$(cat <<'EOF' … )"`. A heredoc inside a command
180
- * substitution inside double quotes is a real heredoc; telling it apart from
181
- * `echo "<<EOF"` needs command-substitution nesting, which is a shell parser.
182
- * So `echo "<<EOF"` followed by a later bare `EOF` line still over-strips.
183
- * That direction over-blocks nothing — it deletes text the checks would
184
- * otherwise read — and is recorded rather than half-fixed.
714
+ * #1176 left this NOT quote-aware on purpose, because the obvious hardening
715
+ * ("must be top-level") REDDENS the recorded `pai-config#474` false positive,
716
+ * whose heredoc is legitimately nested inside `"$(cat <<'EOF' … )"`. That
717
+ * reasoning was right about the fix it tried and wrong about the conclusion:
718
+ * the distinction is not depth, it is whether a command substitution has
719
+ * reset the quoting. #1196 pays for the small stack that tells them apart.
720
+ *
721
+ * What it buys: `bun -e 'x = "<<EOF"'` opened a heredoc, so every following
722
+ * line up to a bare `EOF` was deleted as a document — a quoted STRING chose
723
+ * what the guard could see. H5 was this same body-drop reached through the
724
+ * wrong character position (`<<<`); this is the wrong quoting position.
185
725
  */
186
726
  function heredocDelimiter(line: string): string | null {
187
727
  // #1184: `(?<!<)` and `(?!<)` exclude a `<<<` HERESTRING, which has no
188
728
  // terminator at all. Matching one invented a delimiter from the quoted text
189
729
  // after it and then ran straight into the unterminated case above.
190
- const m = /(?<!<)<<(?!<)-?\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1/.exec(line);
191
- return m ? m[2] : null;
730
+ const re = /(?<!<)<<(?!<)-?\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1/g;
731
+ const open = unquotedPositions(line);
732
+ for (let m = re.exec(line); m; m = re.exec(line)) {
733
+ if (open[m.index]) return m[2];
734
+ }
735
+ return null;
736
+ }
737
+
738
+ /**
739
+ * Does the heredoc opened on this line hand its body to an interpreter?
740
+ *
741
+ * Two ways it can. The segment carrying the operator IS an interpreter
742
+ * (`bash <<'EOF'`), or the operator's segment is piped into one
743
+ * (`cat <<'EOF' | bash`). Everything else — `cat > doc.md <<'EOF'`,
744
+ * `gh issue comment --body-file - <<'EOF'` — is a DOCUMENT, and stripping
745
+ * those bodies is what stopped 1,860 real commands from being refused for
746
+ * quoting the words this guard looks for. That distinction is the whole
747
+ * reason this is a predicate rather than "stop stripping heredocs".
748
+ */
749
+ function heredocInterpreter(line: string): string | null {
750
+ const segs = segments(line);
751
+ const ownerIdx = segs.findIndex(s => heredocDelimiter(s) !== null);
752
+ if (ownerIdx === -1) return null;
753
+ const owner = commandWord(segs[ownerIdx]);
754
+ if (isInterpreterWord(owner)) return owner;
755
+ const opAt = line.search(/(?<!<)<<(?!<)/);
756
+ if (opAt === -1 || !line.slice(opAt).includes('|')) return null;
757
+ return segs.slice(ownerIdx + 1).map(commandWord).find(isInterpreterWord) ?? null;
758
+ }
759
+
760
+ /**
761
+ * The program text this command hands to an interpreter on stdin (#1240).
762
+ *
763
+ * A heredoc body fed to an interpreter, and a herestring operand of one.
764
+ * Deliberately NOT the `-c`/`-e` form: arm 3a already reads that, and
765
+ * returning it here would decide it twice.
766
+ *
767
+ * An UNTERMINATED heredoc is not returned. `stripHeredocs` already emits
768
+ * those lines unchanged — the #1184 fail-closed direction — so every arm
769
+ * can already see them, and returning them again would double-count a body
770
+ * that is not hidden in the first place.
771
+ */
772
+ export function interpreterPrograms(cmd: string): Array<{ shell: boolean; program: string }> {
773
+ const out: Array<{ shell: boolean; program: string }> = [];
774
+ const lines = cmd.split('\n');
775
+ let i = 0;
776
+ while (i < lines.length) {
777
+ const line = lines[i];
778
+ i++;
779
+ if (/^\s*#/.test(line)) continue; // a comment cannot open either form
780
+
781
+ // A HERESTRING has no body and no terminator, which is why
782
+ // `heredocDelimiter` excludes it (#1184). It is still a program, and it
783
+ // is invisible for the other half of the mechanism: the `>` inside it
784
+ // sits in a quoted span that the VERB view removes.
785
+ const hs = /(?<!<)<<<(?!<)([\s\S]*)$/.exec(line);
786
+ if (hs) {
787
+ const owner = segments(line).find(s => /(?<!<)<<<(?!<)/.test(s));
788
+ const word = owner ? commandWord(owner) : '';
789
+ if (isInterpreterWord(word)) {
790
+ out.push({ shell: isShellWord(word), program: dequote(hs[1]).trim() });
791
+ }
792
+ }
793
+
794
+ const delim = heredocDelimiter(line);
795
+ if (!delim) continue;
796
+ const body: string[] = [];
797
+ let j = i;
798
+ while (j < lines.length && lines[j].trim() !== delim) {
799
+ body.push(lines[j]);
800
+ j++;
801
+ }
802
+ if (j < lines.length) {
803
+ const word = heredocInterpreter(line);
804
+ if (word) out.push({ shell: isShellWord(word), program: body.join('\n') });
805
+ i = j + 1;
806
+ } else {
807
+ i = j; // unterminated: already visible, see the docblock
808
+ }
809
+ }
810
+ return out.filter(p => p.program !== '');
192
811
  }
193
812
 
194
813
  /** Remove quote characters, keep the contents. Use when looking for a TARGET. */
@@ -199,6 +818,13 @@ export function dequote(s: string): string {
199
818
  /** Wrappers that delegate to the real command word rather than being one. */
200
819
  const WRAPPERS = /^(?:sudo|env|nohup|time|command|xargs)$/;
201
820
 
821
+ /**
822
+ * A variable assignment prefix, by the POSIX shape: an identifier, an
823
+ * optional array subscript, then `=`. Read on the raw token — see
824
+ * `commandWord`, where recognising it only after the path strip was a bypass.
825
+ */
826
+ const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*(?:\[[^\]]*\])?=/;
827
+
202
828
  /**
203
829
  * The command word of a segment — the first token that is not a wrapper, an
204
830
  * assignment or an option. Read off `stripQuoted`, because a quoted token is
@@ -215,7 +841,39 @@ export function commandWord(segment: string): string {
215
841
  // The grep-PATTERN false positive this function was protecting against is
216
842
  // unaffected: `grep -nE "chmod" f` still resolves to `grep`, because the
217
843
  // real verb comes FIRST and a pattern is never in first position.
218
- for (const raw of dequote(stripHeredocs(segment)).trim().split(/\s+/)) {
844
+ //
845
+ // #1196: the TOKENS come from `scanSegment`, the same quote-aware pass the
846
+ // redirect scan uses. The #1184 spelling was `dequote(...).split(/\s+/)`,
847
+ // which removes the quote characters and THEN splits on whitespace — so a
848
+ // quoted value's internal spaces become token boundaries. `A="1 grep" cp
849
+ // <protected> /tmp/x` split to `A=1`, `grep`, `cp`, …: the `=` skip
850
+ // consumed only `A=1` and the verb resolved to `grep`, which is on the
851
+ // read-only side, so the `cp` was allowed. A quoted span must stay inside
852
+ // its word; `readWord` already does that, and now there is one tokeniser
853
+ // rather than two spellings of the idea.
854
+ for (const raw of scanSegment(segment).words) {
855
+ // A token carrying WHITESPACE is not a verb. It is what the quote-aware
856
+ // tokeniser above is for — `A="1 grep"` is one word — and the same
857
+ // property makes `--body "## Goal … chflags uchg …"` one word too. The
858
+ // first spelling of this fix returned that whole document as the command
859
+ // word, and `decideBashWrite` tests `IN_PLACE` against `${word} ${code}`:
860
+ // a `gh issue create` whose body described chflags on a hook was refused,
861
+ // which is the recorded `pai-config#474` family. The shell cannot run a
862
+ // verb named `chmod 777` either, so nothing executable is lost.
863
+ if (/\s/.test(raw)) continue;
864
+ // An assignment prefix is recognised on the RAW token, before the path
865
+ // strip. #1196: the strip runs `^.*\/` and takes the `=` away with the
866
+ // directory part, so `FOO=/x/grep` arrived at the `includes('=')` test
867
+ // spelled `grep` and was returned as the command word — a fake verb in
868
+ // front of the real one. `FOO=/x/grep chmod 777 <hook>` was ALLOW on
869
+ // main and ALLOW behind the first #1196 fix; `chmod 777 <hook>` BLOCKs.
870
+ // Four arms were reachable this way. Same defect this issue names, a
871
+ // different assignment shape: the prefix hides the verb either way.
872
+ //
873
+ // Matched by the POSIX shape rather than by `includes('=')` so a real
874
+ // path is not mistaken for one — `/opt/a=b/bin/tool` does not start
875
+ // with an identifier, and the test below still catches the rest.
876
+ if (ASSIGNMENT.test(raw)) continue;
219
877
  const tok = raw
220
878
  .replace(/^[({\\]+/, '') // `(cmd …`, `{ cmd …`, `\cmd` — alias bypass
221
879
  .replace(/^.*\//, ''); // `/usr/bin/python3` -> `python3`
@@ -253,6 +911,58 @@ function readWord(s: string, i: number): [string, number] {
253
911
  i = end + 1;
254
912
  continue;
255
913
  }
914
+ // #1205: a command substitution is part of the word it sits in, however
915
+ // much whitespace is inside it. Ending the word at the first space split
916
+ // `> /tmp/`id -un`/workflow-state.json` into the target `/tmp/`id` — which
917
+ // names no protected artifact, so arm 1 never fired at all and a write to
918
+ // a live run-store path was allowed. The space-free spelling was caught,
919
+ // which is why this survived: the bug is the SPACE, not the substitution.
920
+ //
921
+ // The text is kept verbatim rather than expanded. This module does not
922
+ // expand anything, and keeping the `$`/backtick is what lets #1175's
923
+ // `isScratchPath` go on reading an unexpanded path as unprovable.
924
+ if (c === '`') {
925
+ const close = s.indexOf('`', i + 1);
926
+ // Unterminated: consume to the end. A substitution this module cannot
927
+ // see the end of is not one it can read a word boundary out of, so it
928
+ // takes the rest — the fail-closed direction.
929
+ const end = close === -1 ? s.length : close + 1;
930
+ w += s.slice(i, end);
931
+ i = end;
932
+ continue;
933
+ }
934
+ if (c === '$' && s[i + 1] === '(') {
935
+ let depth = 0;
936
+ let j = i;
937
+ for (; j < s.length; j++) {
938
+ // A parenthesis inside a STRING LITERAL is data, not grammar.
939
+ // Counting it dropped the depth to zero early, ended the word in the
940
+ // middle of the substitution, and left a `"` whose partner had
941
+ // already been consumed — so the quote branch above then took
942
+ // `close === -1` and swallowed the rest of the line INCLUDING the
943
+ // `>` operator. No operator, no target, allow:
944
+ //
945
+ // echo $(echo "x)") > <protected> ran, and wrote
946
+ //
947
+ // This is #1205's own sentence a second time — the bug is what the
948
+ // scanner cannot see, not the substitution — so it is fixed the same
949
+ // way rather than by special-casing the literal that exposed it.
950
+ const q = s[j];
951
+ if (q === "'" || q === '"') {
952
+ const close = s.indexOf(q, j + 1);
953
+ j = close === -1 ? s.length : close; // the loop's j++ steps past it
954
+ continue;
955
+ }
956
+ if (s[j] === '(') depth++;
957
+ else if (s[j] === ')' && --depth === 0) {
958
+ j++;
959
+ break;
960
+ }
961
+ }
962
+ w += s.slice(i, j); // unterminated falls out here with j === s.length
963
+ i = j;
964
+ continue;
965
+ }
256
966
  w += c;
257
967
  i++;
258
968
  }
@@ -283,7 +993,18 @@ function isWriteOperand(op: string): boolean {
283
993
  * was seen by neither pass. Scanning finds the operator at a position and
284
994
  * then reads the operand as a word, which is the same rule the shell uses.
285
995
  */
286
- export function writeTargets(segment: string): string[] {
996
+ /**
997
+ * One left-to-right pass over a segment, returning its WORDS and its
998
+ * redirect TARGETS.
999
+ *
1000
+ * #1196 made this the single tokeniser. `commandWord` previously did its own
1001
+ * `dequote(...).split(/\s+/)`, which is not tokenisation: it let a quoted
1002
+ * multi-word assignment VALUE break into separate tokens, so
1003
+ * `A="1 grep" cp …` dropped only `A=1` on the `includes('=')` skip and
1004
+ * resolved the verb to `grep`. Here a quoted span stays INSIDE its word, so
1005
+ * the same input yields the single token `A=1 grep`, which is skipped whole.
1006
+ */
1007
+ function scanSegment(segment: string): { words: string[]; targets: string[] } {
287
1008
  const targets: string[] = [];
288
1009
  const words: string[] = [];
289
1010
  const s = stripHeredocs(segment);
@@ -316,8 +1037,26 @@ export function writeTargets(segment: string): string[] {
316
1037
  }
317
1038
  const [w, next] = readWord(s, i);
318
1039
  i = next === i ? i + 1 : next;
1040
+ // #1196 R3: an IO NUMBER is not a word. POSIX: an unquoted digit string
1041
+ // immediately preceding `<` or `>` names a file descriptor, so the `2`
1042
+ // in `2>/dev/null` belongs to the redirect. Emitting it as a word put it
1043
+ // in LAST position among a `cp`'s arguments, which is where this module
1044
+ // looks for the destination — so `cp /tmp/x.json /r/<protected>
1045
+ // 2>/dev/null` read its destination as `2` and the real one was demoted
1046
+ // to a source. Measured on the corpus: four genuine writes to a gate
1047
+ // artifact or a hook, allowed by #1188, and found only because a
1048
+ // classifier written for a different question made the same mistake.
1049
+ if (w && /^\d+$/.test(w) && (s[i] === '>' || s[i] === '<')) continue;
319
1050
  if (w) words.push(w);
320
1051
  }
1052
+ return { words, targets };
1053
+ }
1054
+
1055
+ /**
1056
+ * Paths a segment writes through shell redirection or a copying verb.
1057
+ */
1058
+ export function writeTargets(segment: string, whole: string = segment): string[] {
1059
+ const { words, targets } = scanSegment(segment);
321
1060
 
322
1061
  // `tee` takes MANY files. Reading only the first operand let
323
1062
  // `tee /tmp/a <protected>` through (#1176).
@@ -336,11 +1075,9 @@ export function writeTargets(segment: string): string[] {
336
1075
  if (args.length >= 2) {
337
1076
  const dest = args[args.length - 1];
338
1077
  targets.push(dest);
339
- // #1184: when the destination is a DIRECTORY the real sink is
340
- // `dest/basename(src)`, for every source. `cp /tmp/forged/
341
- // workflow-state.json /Users/jhorn/.rungate/x/` names no protected
342
- // artifact in its last argument and writes one.
343
- if (isDirDestination(dest)) {
1078
+ // When the destination is a DIRECTORY the real sink is
1079
+ // `dest/basename(src)`, for every source (#1184).
1080
+ if (isDirDestination(dest, args, whole)) {
344
1081
  for (const src of args.slice(0, -1)) {
345
1082
  targets.push(`${dest.replace(/\/+$/, '')}/${src.replace(/^.*\//, '')}`);
346
1083
  }
@@ -351,23 +1088,56 @@ export function writeTargets(segment: string): string[] {
351
1088
  }
352
1089
 
353
1090
  /**
354
- * Does this destination name a directory? A trailing slash settles it without
355
- * touching the disk; otherwise one `stat`, which is allowed to fail — a path
356
- * that cannot be examined is treated as a plain file, because the plain-file
357
- * reading is what the last-argument test already covers.
1091
+ * Does this destination name a DIRECTORY? Four oracles, three of them
1092
+ * syntactic, in the order they settle the question cheaply.
1093
+ *
1094
+ * #1184 asked only the fourth, `statSync`, and that is #1196's R2: a
1095
+ * PreToolUse hook decides before ANY of the command has run, so in
1096
+ * `mkdir -p d && cp <protected> d` the directory never exists at decision
1097
+ * time. Measured both ways on the same command — directory absent ALLOW,
1098
+ * directory present BLOCK. A guard whose answer depends on a directory the
1099
+ * same command is about to create is not a guard.
1100
+ *
1101
+ * The reviewer's simpler repair was to delete the test and push
1102
+ * `dest/basename(src)` unconditionally. Measured on 5,543 corpus commands
1103
+ * naming a protected artifact, that refuses 19 real commands and catches no
1104
+ * real write that the oracles below miss — every one of the 19 is a
1105
+ * protected file copied OUT to a plain destination, and 11 of those are the
1106
+ * `cp hooks/X.hook.ts /tmp/x.bak` backup that
1107
+ * `.claude/rules/checks-must-be-able-to-fail.md` requires before a mutation
1108
+ * battery. A guard that refuses the repository's own mandated practice gets
1109
+ * switched off. So the test stays and gains the readings it was missing.
358
1110
  */
359
- // Declared beside its only reader, matching `lib/gate-result-protection.ts`.
360
- import { statSync } from 'fs';
361
-
362
- function isDirDestination(dest: string): boolean {
363
- if (dest.endsWith('/')) return true;
1111
+ // #1175 moved `statSync` to the import block at the top, which `isScratchPath`
1112
+ // also reads from. Two `from 'fs'` statements in one module is legal and is
1113
+ // still one import of one module; one of them is what a reader greps for.
1114
+ function isDirDestination(dest: string, args: string[], whole: string): boolean {
1115
+ if (dest.endsWith('/')) return true; // `cp x d/` — the shell requires a dir
1116
+ if (args.length > 2) return true; // `cp a b c d` — d MUST be a directory
1117
+ if (createdAsDirectory(dest, whole)) return true; // `mkdir -p d && cp x d`
364
1118
  try {
365
1119
  return statSync(dest).isDirectory();
366
1120
  } catch {
367
- return false;
1121
+ return false; // unreadable reads as a plain file; that is the last-arg case
368
1122
  }
369
1123
  }
370
1124
 
1125
+ /** Does some earlier segment of this same command `mkdir` the destination? */
1126
+ function createdAsDirectory(dest: string, whole: string): boolean {
1127
+ const want = dest.replace(/\/+$/, '');
1128
+ for (const seg of segments(whole)) {
1129
+ if (commandWord(seg) !== 'mkdir') continue;
1130
+ for (const a of scanSegment(seg).words.slice(1)) {
1131
+ if (!a.startsWith('-') && a.replace(/\/+$/, '') === want) return true;
1132
+ }
1133
+ }
1134
+ return false;
1135
+ }
1136
+
1137
+ // `statSync` used to be declared here, beside its only reader. #1175 gave it
1138
+ // a second reader in `isScratchPath` at the top of the module, so the import
1139
+ // moved to the import block rather than being written twice.
1140
+
371
1141
  /**
372
1142
  * Non-option arguments of a segment, dequoted. This is what an in-place verb
373
1143
  * actually operates on — as opposed to its script, which is an argument too
@@ -417,10 +1187,35 @@ const IN_PLACE = [
417
1187
  /\brm\b/,
418
1188
  /\bln\b/,
419
1189
  /\bgit\s+(?:checkout|restore)\b/,
1190
+ // #1146: extended attributes are file metadata, and `com.apple.provenance`
1191
+ // is what was blocking writes to the hooks on this machine — so removing it
1192
+ // is a mutation of hook integrity by any reading.
1193
+ //
1194
+ // The mutating forms are read off `xattr --help`, not guessed:
1195
+ //
1196
+ // xattr [-lrsvx] file … list READ
1197
+ // xattr -p [-lrsvx] attr file … print READ
1198
+ // xattr -w [-rsx] attr value file set MUTATES
1199
+ // xattr -d [-rsv] attr file … delete MUTATES
1200
+ // xattr -c [-rsv] file … clear ALL MUTATES
1201
+ //
1202
+ // So the letters are `c`, `d`, `w` — and they may sit ANYWHERE in a flag
1203
+ // cluster, which is why this does not read a single letter. The first
1204
+ // revision of this PR shipped `-[dws]`, wrong in both directions against
1205
+ // that table: it missed `-c`, which deletes every attribute on the file,
1206
+ // and it refused `-s`, which only says "act on the symbolic link itself".
1207
+ // Seven of fifteen spellings were decided wrongly.
1208
+ //
1209
+ // A bare invocation carries no leading dash, so the READ that this arm
1210
+ // must not refuse — two real corpus commands run `xattr <hook>` to inspect
1211
+ // the attribute list — is excluded by construction rather than by a list.
1212
+ /\bxattr\b[^\n]*\s-[A-Za-z]*[cdw][A-Za-z]*\b/,
420
1213
  ];
421
1214
 
422
- /** Interpreters whose argument is a program this module cannot read. */
423
- const INTERPRETERS = /^(?:python[23]?|perl|ruby|node|bun|deno|osascript|sh|bash|zsh|dash|ksh|php)$/;
1215
+ // #1240: the list moved to `lib/interpreters.ts`, which `lib/bash-file-read.ts`
1216
+ // now reads too. Two modules were answering "is this an interpreter" with two
1217
+ // different lists, and the narrower one was why a `python3` heredoc read as a
1218
+ // document.
424
1219
 
425
1220
  /**
426
1221
  * Interpreters whose `-c` argument is SHELL — which this module can read.
@@ -429,8 +1224,9 @@ const INTERPRETERS = /^(?:python[23]?|perl|ruby|node|bun|deno|osascript|sh|bash|
429
1224
  * Python idioms, so `bash -c 'echo x > <protected>'` matched nothing and was
430
1225
  * allowed. Arm 1 could not see it either, because the body is quoted. The
431
1226
  * body is shell, the module parses shell, so it recurses instead of guessing.
1227
+ *
1228
+ * #1240: also in `lib/interpreters.ts` as `isShellWord`.
432
1229
  */
433
- const SHELLS = /^(?:sh|bash|zsh|dash|ksh)$/;
434
1230
 
435
1231
  /** The `-c` body of a shell invocation, dequoted. */
436
1232
  function shellBody(segment: string): string {
@@ -498,6 +1294,121 @@ function names(text: string, list: string[]): string | null {
498
1294
  return null;
499
1295
  }
500
1296
 
1297
+ /**
1298
+ * Protected artifacts this text names somewhere OTHER than a scratch tree
1299
+ * (#1175).
1300
+ *
1301
+ * A name is exempted only when EVERY path word carrying it is scratch. One
1302
+ * mention of the live artifact alongside ten fixtures still refuses, which is
1303
+ * the direction a guard should err in and also the common real shape: a
1304
+ * command that copies a fixture over a run's state names both.
1305
+ */
1306
+ function namesOutsideScratch(text: string, list: string[], exempt: boolean): string[] {
1307
+ const out: string[] = [];
1308
+ for (const p of list) {
1309
+ const words = pathWordsContaining(text, p);
1310
+ if (words.length === 0) continue;
1311
+ if (exempt && words.every(isScratchPath)) continue;
1312
+ out.push(p);
1313
+ }
1314
+ return out;
1315
+ }
1316
+
1317
+ /**
1318
+ * Protected names in a program body, counting only ABSOLUTE spellings
1319
+ * outside a scratch tree (#1240).
1320
+ *
1321
+ * The stricter reading exists because of what it costs otherwise, measured
1322
+ * rather than reasoned: scanning an interpreter body for a protected NAME
1323
+ * newly refused **23** real commands, and every one of them was an agent
1324
+ * building hook FIXTURES in a `/tmp` tree with an assembled path —
1325
+ * `open(os.path.join(dst, n), "w")`, where the only word carrying
1326
+ * `.hook.ts` is the relative suffix itself. A relative fragment cannot be
1327
+ * shown to be scratch, so the fail-closed reading in `isScratchPath`
1328
+ * correctly refuses to exempt it, and the result is that the fixture work
1329
+ * #1175 exists to unblock gets refused by the arm added beside it.
1330
+ *
1331
+ * So this arm asks for an absolute path. The spelling it is there to catch
1332
+ * — `open("<run store>/workflow-state.json", "w")` inside a heredoc — is
1333
+ * absolute, and the 23 are not. The arm it mirrors (arm 3, the `-c` form)
1334
+ * keeps its looser reading: that behaviour is pre-existing and measured,
1335
+ * and tightening it is not this change's business.
1336
+ */
1337
+ function absoluteNamesOutsideScratch(text: string, exempt: boolean): string[] {
1338
+ const out: string[] = [];
1339
+ for (const p of ALL_PROTECTED) {
1340
+ const words = pathWordsContaining(text, p).filter(w => w.startsWith('/'));
1341
+ if (words.length === 0) continue;
1342
+ if (exempt && words.every(isScratchPath)) continue;
1343
+ out.push(p);
1344
+ }
1345
+ return out;
1346
+ }
1347
+
1348
+ /**
1349
+ * Does every absolute path literal in an interpreter body sit in a scratch
1350
+ * tree? A STOPGAP, and labelled one — see #1269.
1351
+ *
1352
+ * Arm 3 refuses because an interpreter's program is opaque: what it writes
1353
+ * cannot be read off the command line. The scratch exemption contradicted
1354
+ * that premise by deciding the destination from one path word, and a
1355
+ * destination can be computed. Executed against the module as merged:
1356
+ *
1357
+ * bun -e 'writeFileSync("/tmp/x/workflow-state.json"
1358
+ * .replace("/tmp/x", "<run store>"), "{}")' EXEMPT
1359
+ *
1360
+ * The word carrying the name is the `/tmp` literal that is thrown away. Two
1361
+ * other computed spellings — a `..` chain and an `os.path.join` with `..`
1362
+ * components — happened to normalise back into the store and were already
1363
+ * refused, which is luck rather than coverage.
1364
+ *
1365
+ * This asks a question about the WHOLE body instead of one word: if the
1366
+ * program also names an absolute path that is NOT scratch, the exemption
1367
+ * does not apply. The escaping spelling above names the run store in its
1368
+ * second argument, so it is refused.
1369
+ *
1370
+ * ## What this does NOT cover, stated so nobody reads it as the repair
1371
+ *
1372
+ * It still reads literals, so a spelling that leaves no non-scratch
1373
+ * literal behind would still pass. Three candidates were tried rather than
1374
+ * assumed, and all three were ALREADY refused on `origin/main` — a `$HOME`
1375
+ * concatenation, an env-var concatenation and a command substitution — in
1376
+ * each case because the carrying word is an absolute non-scratch suffix
1377
+ * like `/.rungate/run/workflow-state.json`. Only the `.replace` of a
1378
+ * scratch literal ever escaped, and that is what this closes.
1379
+ *
1380
+ * The durable repair is to resolve the write TARGET and ask whether the
1381
+ * resolved path is under a scratch root, at which point a computed
1382
+ * destination stops being a special case — the same primitive #1269's
1383
+ * first fix introduced for protected trees. Filed; this is the stopgap.
1384
+ *
1385
+ * Neither reading closes an assembled NAME: `'workflow' + '-state.json'`
1386
+ * leaves no word carrying the artifact, so arm 3 never receives a
1387
+ * candidate at all. That is a limit of the candidate search rather than of
1388
+ * the exemption, it is pre-existing, and it has its own row in the tests.
1389
+ *
1390
+ * ## Why not drop the exemption from arm 3 altogether
1391
+ *
1392
+ * It was built and swept. It costs **12** corpus commands against this
1393
+ * one's **4**, and it reverses two of #1175's ten witnesses — the
1394
+ * `python3 -I -c` and `bun -e` rows, which assert that an interpreter
1395
+ * writing under a scratch root is a fixture. It also still reads literals,
1396
+ * so it buys a stricter version of the same weakness rather than the
1397
+ * property. Paying 12 and two witnesses for a different patch is the wrong
1398
+ * trade; paying 6 for today's escape is not.
1399
+ */
1400
+ function bodyIsAllScratch(bare: string): boolean {
1401
+ // `/^\/[^/]/` and not `startsWith('/')`: the looser test counted a bare
1402
+ // `/` and the `//` of a comment as absolute paths that are not scratch,
1403
+ // which ended the exemption for two real fixture commands on the strength
1404
+ // of a comment marker. Measured, not reasoned: the loose version newly
1405
+ // refuses 6 corpus commands and this one refuses 4, and the two it drops
1406
+ // had no non-scratch path in them at all — only punctuation that looked
1407
+ // like one.
1408
+ const words = bare.split(/[\s'"`,;(){}[\]]+/).filter(w => /^\/[^/]/.test(w));
1409
+ return words.length > 0 && words.every(isScratchPath);
1410
+ }
1411
+
501
1412
  const ALL_PROTECTED = [...PROTECTED_FILES, ...PROTECTED_HOOKS];
502
1413
 
503
1414
  /**
@@ -508,12 +1419,47 @@ const ALL_PROTECTED = [...PROTECTED_FILES, ...PROTECTED_HOOKS];
508
1419
  * reason the checks above are structural: a guard tuned so wide that people
509
1420
  * work around it protects nothing, and four real refusals of read-only work
510
1421
  * is already a pattern.
1422
+ *
1423
+ * `exempt` is computed once from the WHOLE command and handed down, rather
1424
+ * than recomputed per segment or per recursion. The command that voids the
1425
+ * exemption puts the `ln` in one segment and the write in another, so a
1426
+ * per-segment answer would never see both.
511
1427
  */
512
- export function decideBashWrite(cmd: string, depth = 0): BashWriteDecision {
1428
+ export function decideBashWrite(cmd: string, depth = 0, exemptIn?: boolean): BashWriteDecision {
513
1429
  if (!cmd) return ALLOW;
514
1430
  // A shell body can contain a shell body. Bounded so a crafted nest costs a
515
1431
  // fixed amount of work rather than the session.
516
1432
  if (depth > 3) return ALLOW;
1433
+ const exempt = exemptIn ?? !exemptionIsVoid(cmd);
1434
+
1435
+ // #1240: a program handed to an interpreter on stdin. `stripHeredocs`
1436
+ // deletes the body before every arm below, and arm 3a only reads a body
1437
+ // back when the segment also carries `-c`/`-e` — which `bash <<'EOF'` does
1438
+ // not. The result was that the guard decided on the single word `bash`
1439
+ // while the program underneath wrote whatever it liked. Each program is
1440
+ // re-entered as a command in its own right, and recomputes its own
1441
+ // exemption: an `ln` in the body is the body's business.
1442
+ // A SHELL body is read as shell; anything else gets the treatment arm 3
1443
+ // gives a `-c` body it cannot parse — a declared write verb near the name
1444
+ // of a protected artifact. Reading a Python body as shell finds nothing,
1445
+ // which is how `python3 <<'PY'` stayed allowed after the shell spellings
1446
+ // were closed.
1447
+ for (const { shell, program } of interpreterPrograms(cmd)) {
1448
+ if (shell) {
1449
+ const inner = decideBashWrite(program, depth + 1, exempt && !exemptionIsVoid(program));
1450
+ if (inner.blocked) return inner;
1451
+ continue;
1452
+ }
1453
+ const pf = absoluteNamesOutsideScratch(program, exempt).find(p => writesNear(program, p));
1454
+ if (pf) {
1455
+ return {
1456
+ blocked: true,
1457
+ reason:
1458
+ `Bash command runs an interpreter or a mutating \`find\` naming "${pf}". ` +
1459
+ `What it writes cannot be read off the command line, so it is refused.`,
1460
+ };
1461
+ }
1462
+ }
517
1463
 
518
1464
  for (const seg of segments(cmd)) {
519
1465
  const bare = dequote(seg); // TARGET view: contents kept
@@ -522,7 +1468,12 @@ export function decideBashWrite(cmd: string, depth = 0): BashWriteDecision {
522
1468
 
523
1469
  // 1. Shell redirection and copying verbs. Never exempted by anything:
524
1470
  // this is the arm the old allowlist sat above, which is #1120.
525
- for (const target of writeTargets(seg)) {
1471
+ // The whole command is passed so the directory test can see a `mkdir`
1472
+ // in an EARLIER segment (#1196 R2). Everything else is per-segment.
1473
+ for (const target of writeTargets(seg, cmd)) {
1474
+ // #1175: the target IS a path, so the tree question is asked directly
1475
+ // here rather than through `namesOutsideScratch`.
1476
+ if (exempt && isScratchPath(target)) continue;
526
1477
  const pf = names(target, PROTECTED_FILES);
527
1478
  if (pf) {
528
1479
  return {
@@ -546,7 +1497,7 @@ export function decideBashWrite(cmd: string, depth = 0): BashWriteDecision {
546
1497
  // text contains it, and `grep "rm -rf …"` must stay a grep.
547
1498
  const verbView = `${word} ${code}`;
548
1499
  if (IN_PLACE.some(p => p.test(verbView))) {
549
- const pf = names(argumentsOf(seg).join(' '), ALL_PROTECTED);
1500
+ const pf = namesOutsideScratch(argumentsOf(seg).join(' '), ALL_PROTECTED, exempt)[0];
550
1501
  if (pf) {
551
1502
  return {
552
1503
  blocked: true,
@@ -560,23 +1511,28 @@ export function decideBashWrite(cmd: string, depth = 0): BashWriteDecision {
560
1511
  // this asks for a declared write verb rather than refusing every
561
1512
  // interpreter that names a protected artifact, and for what that
562
1513
  // concession costs.
563
- const isInterpreter = INTERPRETERS.test(word) && /\s-[a-z]*[ce]\b/.test(code);
1514
+ const isInterpreter = isInterpreterWord(word) && /\s-[a-z]*[ce]\b/.test(code);
564
1515
  const isMutatingFind = word === 'find' && FIND_MUTATING.test(code);
565
1516
 
566
1517
  // 3a. A shell `-c` body is shell. Read it as shell rather than scanning
567
1518
  // it for Node and Python idioms it will never contain (#1176).
568
- if (isInterpreter && SHELLS.test(word)) {
1519
+ if (isInterpreter && isShellWord(word)) {
569
1520
  const body = shellBody(seg);
570
1521
  if (body) {
571
- const inner = decideBashWrite(body, depth + 1);
1522
+ const inner = decideBashWrite(body, depth + 1, exempt);
572
1523
  if (inner.blocked) return inner;
573
1524
  }
574
1525
  }
575
1526
 
576
1527
  if (isInterpreter || isMutatingFind) {
1528
+ // #1269: the exemption asks about the whole body, not one word. See
1529
+ // `bodyIsAllScratch` for what it closes, what it does not, and the
1530
+ // 6-against-12 measurement behind choosing it over dropping the
1531
+ // exemption from this arm entirely.
1532
+ const candidates = namesOutsideScratch(bare, ALL_PROTECTED, exempt && bodyIsAllScratch(bare));
577
1533
  const pf = isMutatingFind
578
- ? names(bare, ALL_PROTECTED)
579
- : (ALL_PROTECTED.find(p => bare.includes(p) && writesNear(bare, p)) ?? null);
1534
+ ? (candidates[0] ?? null)
1535
+ : (candidates.find(p => writesNear(bare, p)) ?? null);
580
1536
  if (pf) {
581
1537
  return {
582
1538
  blocked: true,
@@ -587,12 +1543,37 @@ export function decideBashWrite(cmd: string, depth = 0): BashWriteDecision {
587
1543
  }
588
1544
  }
589
1545
 
590
- // 4. Permission changes on a hook file. The COMMAND WORD must be the
591
- // verb — not merely a `chmod` somewhere in the string, which is what
592
- // refused four read-only commands. The target is read off `bare`, so
593
- // quoting the path does not hide it.
594
- if ((word === 'chmod' || word === 'chflags') && names(bare, PROTECTED_HOOKS)) {
595
- return { blocked: true, reason: 'Permission change on hook file blocked. Hook integrity is protected.' };
1546
+ // 4. Permission changes on a protected artifact. The COMMAND WORD must be
1547
+ // the verb — not merely a `chmod` somewhere in the string, which is
1548
+ // what refused four read-only commands. The target is read off `bare`,
1549
+ // so quoting the path does not hide it.
1550
+ //
1551
+ // #1146: the TARGET list widened from PROTECTED_HOOKS to every
1552
+ // protected artifact; the VERB test is untouched, and that asymmetry is
1553
+ // the point. There was no reason for a `chmod` on `.gate-salt` to be
1554
+ // allowed while a `chmod` on a `.hook.ts` was refused — mode bits are
1555
+ // how a file stops being writable, so a permission change on the gate
1556
+ // salt is a step toward writing it. Measured on the 5,059 allowed
1557
+ // commands naming a protected artifact, the widening newly blocks
1558
+ // exactly one, and that one is real:
1559
+ // `chmod 600 …/worktrees/agent-abbce…/hooks/lib/.gate-salt`
1560
+ //
1561
+ // #1175 composes with that widening rather than replacing it: the
1562
+ // target list stays `ALL_PROTECTED` and the lookup moves to
1563
+ // `namesOutsideScratch`, so a `chmod` on a FIXTURE in a scratch tree
1564
+ // is not a permission change on a protected artifact. The widened
1565
+ // list and the tree scoping are independent and both are kept — a
1566
+ // textual merge that took either side alone would have silently
1567
+ // dropped one of them.
1568
+ const permTarget =
1569
+ word === 'chmod' || word === 'chflags'
1570
+ ? (namesOutsideScratch(bare, ALL_PROTECTED, exempt)[0] ?? null)
1571
+ : null;
1572
+ if (permTarget) {
1573
+ return {
1574
+ blocked: true,
1575
+ reason: `Permission change on protected artifact "${permTarget}" blocked. Integrity is protected.`,
1576
+ };
596
1577
  }
597
1578
 
598
1579
  // 5. The gate salt in the Keychain. Exempted by nothing — unlike `chmod`,