rungate 0.8.0 → 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.
Files changed (73) hide show
  1. package/gates/.gate-salt +1 -0
  2. package/gates/SCHEMA-GUIDE.md +485 -0
  3. package/gates/ac-quality.test.ts +106 -0
  4. package/gates/adversarial.test.ts +283 -0
  5. package/gates/brief-assembler.test.ts +487 -0
  6. package/gates/brief-assembler.ts +448 -0
  7. package/gates/bunfig.toml +2 -0
  8. package/gates/chain.test.ts +91 -0
  9. package/gates/e2e-smoke.test.ts +234 -0
  10. package/gates/error-classifier.test.ts +250 -0
  11. package/gates/error-classifier.ts +99 -0
  12. package/gates/gate-executor.ts +3071 -0
  13. package/gates/orchestrator.test.ts +968 -0
  14. package/gates/orchestrator.ts +827 -0
  15. package/gates/preload.ts +89 -0
  16. package/gates/prompts/ac-adversary.md +20 -0
  17. package/gates/prompts/evidence-validator.md +22 -0
  18. package/gates/prompts/prove-reproducer.md +53 -0
  19. package/gates/prompts.sha256 +3 -0
  20. package/gates/prove.test.ts +164 -0
  21. package/gates/rook-state.test.ts +108 -0
  22. package/gates/run-attribution.ts +290 -0
  23. package/gates/run-gate.ts +163 -0
  24. package/gates/schema-parity.test.ts +378 -0
  25. package/gates/schema.ts +1209 -0
  26. package/gates/self-heal.test.ts +511 -0
  27. package/gates/self-heal.ts +125 -0
  28. package/gates/ship-orchestrator.test.ts +399 -0
  29. package/gates/ship-orchestrator.ts +384 -0
  30. package/gates/spec-compliance-probe.ts +159 -0
  31. package/gates/test-fixtures/broken-no-environments.json +110 -0
  32. package/gates/test-fixtures/consumer-directory-layout.json +90 -0
  33. package/gates/test-fixtures/valid-standard.json +91 -0
  34. package/gates/test-utils.ts +43 -0
  35. package/gates/typecheck-gate.ts +111 -0
  36. package/gates/witness.ts +349 -0
  37. package/gates/workflow.test.ts +2018 -0
  38. package/hooks/BashWriteGuard.hook.ts +19 -0
  39. package/hooks/GateResultProtection.hook.ts +27 -1
  40. package/hooks/VerifyPhaseLock.hook.ts +51 -11
  41. package/hooks/WorkflowStateGuard.hook.ts +24 -0
  42. package/lib/ai-review-rounds.ts +462 -0
  43. package/lib/bash-file-read.ts +17 -3
  44. package/lib/bash-write-guard.ts +1285 -50
  45. package/lib/distribution-standing.ts +75 -4
  46. package/lib/failure-intake.ts +12 -4
  47. package/lib/file-extensions.ts +81 -0
  48. package/lib/finding-arbiter.ts +1015 -0
  49. package/lib/finding-jury.ts +537 -0
  50. package/lib/gate-enforcement.ts +171 -43
  51. package/lib/gate-result-protection.ts +12 -2
  52. package/lib/generators/code-map.ts +55 -4
  53. package/lib/generators/types.ts +27 -1
  54. package/lib/github.ts +55 -0
  55. package/lib/interpreters.ts +64 -0
  56. package/lib/issue-create-override.ts +69 -8
  57. package/lib/issue-filing-gate.ts +605 -0
  58. package/lib/js-top-level-code.ts +20 -2
  59. package/lib/junit-checks.ts +239 -1
  60. package/lib/package-closure.ts +114 -0
  61. package/lib/publish-window.ts +287 -0
  62. package/lib/scaffold/ai-review-findings.ts +142 -3
  63. package/lib/scaffold/ai-review-step.ts +1012 -18
  64. package/lib/scaffold/managed-workflow.ts +163 -4
  65. package/lib/scaffold/steps.ts +498 -22
  66. package/lib/scanner.ts +13 -4
  67. package/lib/ticked-sc-symbols.ts +361 -0
  68. package/lib/transcript-checker.ts +6 -0
  69. package/lib/workflow-actions.ts +18 -0
  70. package/package.json +3 -1
  71. package/scripts/arbitrate-finding.ts +224 -0
  72. package/scripts/generate-code-map.ts +18 -10
  73. package/scripts/sync-sc-status.ts +82 -8
@@ -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);
@@ -129,7 +616,198 @@ export function stripQuoted(s: string): string {
129
616
  * command writing it.
130
617
  */
131
618
  export function stripHeredocs(s: string): string {
132
- return s.replace(/<<-?\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1[\s\S]*?^\s*\2\s*$/gm, ' ');
619
+ const lines = s.split('\n');
620
+ const out: string[] = [];
621
+ let i = 0;
622
+ while (i < lines.length) {
623
+ const line = lines[i];
624
+ // A whole-line `#` comment is prose, and its APOSTROPHE is not a quote.
625
+ // #1176: `# First, check if there's a test workflow-state.json` opened a
626
+ // quote that stayed open across the newline and swallowed the redirect on
627
+ // a later line, so a real write to a protected file read as quoted text.
628
+ // Two commands in a 5,513-command corpus did exactly this, both of them
629
+ // genuine writes. Dropped here rather than in each caller because every
630
+ // arm reaches this function first.
631
+ const isComment = /^\s*#/.test(line);
632
+ out.push(isComment ? '' : line); // #1176: the OPERATOR's line is kept — see below.
633
+ i++;
634
+ if (isComment) continue; // a comment cannot open a heredoc
635
+ const delim = heredocDelimiter(line);
636
+ if (!delim) continue;
637
+ // #1184: buffer the body rather than consuming to end-of-input. A
638
+ // heredoc whose terminator never arrives is not a heredoc this module can
639
+ // trust, and dropping the rest of the command is a BYPASS — `cat <<EOF`
640
+ // followed by a write on the next line used to read as a bare `cat`. The
641
+ // regex this scanner replaced required the terminator to match, so it
642
+ // failed closed; the first version of the scanner failed open. Keeping
643
+ // the bytes is the direction a guard is allowed to be wrong in.
644
+ const body: string[] = [];
645
+ let j = i;
646
+ while (j < lines.length && lines[j].trim() !== delim) {
647
+ body.push(lines[j]);
648
+ j++;
649
+ }
650
+ if (j < lines.length) {
651
+ i = j + 1; // terminated: the body and the terminator are the document
652
+ } else {
653
+ out.push(...body); // never terminated: emit unchanged
654
+ i = j;
655
+ }
656
+ }
657
+ return out.join('\n');
658
+ }
659
+
660
+ /**
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.
713
+ *
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.
725
+ */
726
+ function heredocDelimiter(line: string): string | null {
727
+ // #1184: `(?<!<)` and `(?!<)` exclude a `<<<` HERESTRING, which has no
728
+ // terminator at all. Matching one invented a delimiter from the quoted text
729
+ // after it and then ran straight into the unterminated case above.
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 !== '');
133
811
  }
134
812
 
135
813
  /** Remove quote characters, keep the contents. Use when looking for a TARGET. */
@@ -140,14 +818,65 @@ export function dequote(s: string): string {
140
818
  /** Wrappers that delegate to the real command word rather than being one. */
141
819
  const WRAPPERS = /^(?:sudo|env|nohup|time|command|xargs)$/;
142
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
+
143
828
  /**
144
829
  * The command word of a segment — the first token that is not a wrapper, an
145
830
  * assignment or an option. Read off `stripQuoted`, because a quoted token is
146
831
  * an argument.
147
832
  */
148
833
  export function commandWord(segment: string): string {
149
- for (const raw of stripQuoted(segment).trim().split(/\s+/)) {
150
- const tok = raw.replace(/^.*\//, ''); // `/usr/bin/python3` -> `python3`
834
+ // #1184: read the DEQUOTED token stream, not the quote-stripped one. This
835
+ // is the mirror of #1176's F2 — there the TARGET was read off a view the
836
+ // writer controls, here the VERB was: `stripQuoted` deleted `"chmod"`
837
+ // outright, so `"chmod" 777 x.hook.ts` resolved its command word to `777`
838
+ // and the shell ran chmod anyway. Quoting a verb changes nothing about
839
+ // what executes, so it must change nothing about what the guard reads.
840
+ //
841
+ // The grep-PATTERN false positive this function was protecting against is
842
+ // unaffected: `grep -nE "chmod" f` still resolves to `grep`, because the
843
+ // real verb comes FIRST and a pattern is never in first position.
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;
877
+ const tok = raw
878
+ .replace(/^[({\\]+/, '') // `(cmd …`, `{ cmd …`, `\cmd` — alias bypass
879
+ .replace(/^.*\//, ''); // `/usr/bin/python3` -> `python3`
151
880
  if (!tok || tok.includes('=') || tok.startsWith('-')) continue;
152
881
  if (WRAPPERS.test(tok)) continue;
153
882
  return tok;
@@ -163,38 +892,252 @@ export function commandWord(segment: string): string {
163
892
  * then dequoted, because `> "x/.gate-salt"` writes the same file as `>
164
893
  * x/.gate-salt`.
165
894
  */
166
- export function writeTargets(segment: string): string[] {
895
+ /**
896
+ * Read one word starting at `i`, honouring quotes. Returns the word's
897
+ * CONTENTS — quote characters removed, contents kept — and the index after
898
+ * it, so `dir/"workflow-state.json"` reads as one word and not as two halves
899
+ * either side of a span that was deleted.
900
+ */
901
+ function readWord(s: string, i: number): [string, number] {
902
+ let w = '';
903
+ while (i < s.length) {
904
+ const c = s[i];
905
+ if (c === ' ' || c === '\t' || c === '\n') break;
906
+ if (c === '>' || c === '<') break; // an operator ends a word
907
+ if (c === "'" || c === '"') {
908
+ const close = s.indexOf(c, i + 1);
909
+ const end = close === -1 ? s.length : close;
910
+ w += s.slice(i + 1, end);
911
+ i = end + 1;
912
+ continue;
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
+ }
966
+ w += c;
967
+ i++;
968
+ }
969
+ return [w, i];
970
+ }
971
+
972
+ /**
973
+ * Is this redirect operand a PATH being written, or plumbing?
974
+ *
975
+ * `2>&1` and `>&2` name a descriptor, not a file. Keeping that distinction is
976
+ * what lets `2>` count as a write at all (#1176): without it, dropping `2`
977
+ * from the old lookbehind would have turned every `2>&1` in the corpus into
978
+ * a write to a file called `&1`.
979
+ */
980
+ function isWriteOperand(op: string): boolean {
981
+ if (!op) return false;
982
+ if (/^&?\d+$/.test(op) || op === '-') return false;
983
+ return op !== '/dev/null' && op !== '/dev/stderr' && op !== '/dev/stdout';
984
+ }
985
+
986
+ /**
987
+ * Paths a segment writes through shell redirection or a copying verb.
988
+ *
989
+ * #1176 replaced three substring matches with one left-to-right scan. The
990
+ * substring version read redirects off `stripQuoted`, which deletes quoted
991
+ * spans AND their contents, then tried to recover a wholly-quoted target in a
992
+ * second pass — so a target quoted in the MIDDLE of the word (`> dir/"x"`)
993
+ * was seen by neither pass. Scanning finds the operator at a position and
994
+ * then reads the operand as a word, which is the same rule the shell uses.
995
+ */
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[] } {
167
1008
  const targets: string[] = [];
168
- const code = stripQuoted(segment);
169
- // `> file` and `>> file`, but not `2>` or `&>` — those are stderr plumbing.
170
- for (const m of code.matchAll(/(?<![2&])\s*>{1,2}\s*(\S+)/g)) {
171
- if (m[1] && m[1] !== '/dev/null') targets.push(dequote(m[1]));
1009
+ const words: string[] = [];
1010
+ const s = stripHeredocs(segment);
1011
+ let i = 0;
1012
+ while (i < s.length) {
1013
+ const c = s[i];
1014
+ if (c === ' ' || c === '\t' || c === '\n') {
1015
+ i++;
1016
+ continue;
1017
+ }
1018
+ if (c === '>') {
1019
+ i++;
1020
+ if (s[i] === '>') i++;
1021
+ while (s[i] === ' ' || s[i] === '\t') i++;
1022
+ // `>&1` — the `&` belongs to the operand, so readWord keeps it and
1023
+ // isWriteOperand rejects it.
1024
+ const [operand, next] = readWord(s, i);
1025
+ i = next;
1026
+ if (isWriteOperand(operand)) targets.push(operand);
1027
+ continue;
1028
+ }
1029
+ if (c === '<') {
1030
+ // An input redirect reads; skip it and its operand so the operand is
1031
+ // never mistaken for a command word.
1032
+ i++;
1033
+ if (s[i] === '<') i++;
1034
+ while (s[i] === ' ' || s[i] === '\t') i++;
1035
+ i = readWord(s, i)[1];
1036
+ continue;
1037
+ }
1038
+ const [w, next] = readWord(s, i);
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;
1050
+ if (w) words.push(w);
172
1051
  }
173
- // A quoted redirect target survives quote-stripping as nothing at all, so
174
- // it is recovered separately rather than lost.
175
- for (const m of segment.matchAll(/(?<![2&])\s*>{1,2}\s*(['"])([^'"]+)\1/g)) targets.push(m[2]);
176
- const tee = code.match(/\btee\s+(?:-a\s+)?(\S+)/);
177
- if (tee) targets.push(dequote(tee[1]));
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);
1060
+
1061
+ // `tee` takes MANY files. Reading only the first operand let
1062
+ // `tee /tmp/a <protected>` through (#1176).
1063
+ const teeAt = words.findIndex(w => w.replace(/^.*\//, '') === 'tee');
1064
+ if (teeAt !== -1) {
1065
+ for (const w of words.slice(teeAt + 1)) if (!w.startsWith('-')) targets.push(w);
1066
+ }
1067
+
178
1068
  // `cp`/`mv` take the LAST non-option argument as the destination. Reading
179
1069
  // the second token instead — which this did until #1120 — mis-parses every
180
1070
  // invocation carrying a flag: `cp -p src /x/workflow-state.json` read the
181
1071
  // destination as `src` and never examined the real one.
182
- //
183
- // Arguments are DEQUOTED rather than stripped. Stripping them was measured
184
- // to lose the destination entirely for `cp "a/X.hook.ts" "b/X.hook.ts"`,
185
- // which is a real hook write that then read as having no target.
186
1072
  const word = commandWord(segment);
187
1073
  if (word === 'cp' || word === 'mv' || word === 'install' || word === 'rsync') {
188
- const args = dequote(segment)
189
- .trim()
190
- .split(/\s+/)
191
- .slice(1)
192
- .filter(a => !a.startsWith('-'));
193
- if (args.length >= 2) targets.push(args[args.length - 1]);
1074
+ const args = words.slice(1).filter(a => !a.startsWith('-'));
1075
+ if (args.length >= 2) {
1076
+ const dest = args[args.length - 1];
1077
+ targets.push(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)) {
1081
+ for (const src of args.slice(0, -1)) {
1082
+ targets.push(`${dest.replace(/\/+$/, '')}/${src.replace(/^.*\//, '')}`);
1083
+ }
1084
+ }
1085
+ }
194
1086
  }
195
1087
  return targets;
196
1088
  }
197
1089
 
1090
+ /**
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.
1110
+ */
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`
1118
+ try {
1119
+ return statSync(dest).isDirectory();
1120
+ } catch {
1121
+ return false; // unreadable reads as a plain file; that is the last-arg case
1122
+ }
1123
+ }
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
+
198
1141
  /**
199
1142
  * Non-option arguments of a segment, dequoted. This is what an in-place verb
200
1143
  * actually operates on — as opposed to its script, which is an argument too
@@ -244,10 +1187,52 @@ const IN_PLACE = [
244
1187
  /\brm\b/,
245
1188
  /\bln\b/,
246
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/,
247
1213
  ];
248
1214
 
249
- /** Interpreters whose argument is a program this module cannot read. */
250
- const INTERPRETERS = /^(?:python[23]?|perl|ruby|node|bun|deno|osascript|sh|bash|zsh|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.
1219
+
1220
+ /**
1221
+ * Interpreters whose `-c` argument is SHELL — which this module can read.
1222
+ *
1223
+ * #1176: these were being handed to `WRITE_INTENT`, which enumerates Node and
1224
+ * Python idioms, so `bash -c 'echo x > <protected>'` matched nothing and was
1225
+ * allowed. Arm 1 could not see it either, because the body is quoted. The
1226
+ * body is shell, the module parses shell, so it recurses instead of guessing.
1227
+ *
1228
+ * #1240: also in `lib/interpreters.ts` as `isShellWord`.
1229
+ */
1230
+
1231
+ /** The `-c` body of a shell invocation, dequoted. */
1232
+ function shellBody(segment: string): string {
1233
+ const m = /\s-[a-z]*c\s+([\s\S]+)$/.exec(segment);
1234
+ return m ? dequote(m[1]).trim() : '';
1235
+ }
251
1236
 
252
1237
  /**
253
1238
  * Declared write intent inside an interpreter body.
@@ -272,15 +1257,158 @@ const INTERPRETERS = /^(?:python[23]?|perl|ruby|node|bun|deno|osascript|sh|bash|
272
1257
  const WRITE_INTENT =
273
1258
  /\b(?:writeFileSync|appendFileSync|createWriteStream|copyFileSync|renameSync|unlinkSync|rmSync|truncateSync|write_text|json\.dump|os\.remove|os\.rename|os\.replace|os\.unlink|shutil\.(?:copy|move|rmtree))\b|(?<!stdout)(?<!stderr)\.write\s*\(|\bopen\s*\([^)]*['"][wax]\+?['"]/;
274
1259
 
1260
+ /**
1261
+ * #1176 measured the suggested widening of WRITE_INTENT to shell idioms —
1262
+ * `>`, `>>`, `tee`, `rm`, `mv`, `cp`, `dd of=`, `truncate` — so that a
1263
+ * NON-shell interpreter shelling out would also fire. It is not implemented.
1264
+ *
1265
+ * Measured: 100 newly blocked against 4 without it, on 5,513 real commands.
1266
+ * Sampling the extra 96 found them to be reads, and the mechanism is
1267
+ * specific: `>{1,2}\s*\S` matches `=>`, so every arrow function in a
1268
+ * `bun -e` body became a declared write. `x=>x.id==="AC-4"` is not a write.
1269
+ *
1270
+ * The same lesson as the interpreter widening this module already records:
1271
+ * matching SHELL idioms inside a body that is not shell matches the host
1272
+ * language instead. A shell body is handled properly by recursion (see
1273
+ * SHELLS); a Python or Node body that shells out would need its
1274
+ * `os.system`/`subprocess`/`execSync` argument extracted and recursed, which
1275
+ * is a real fix and a different issue from this one.
1276
+ */
1277
+
275
1278
  /** `find` actions that run or delete rather than print. */
276
1279
  const FIND_MUTATING = /\s-(?:delete|exec|execdir|ok|okdir)\b/;
277
1280
 
278
- /** Does this text name a protected artifact? Pass a DEQUOTED segment. */
1281
+ /**
1282
+ * Does this text name a protected artifact? Pass a DEQUOTED segment.
1283
+ *
1284
+ * #1184: folded to lower case. Measured on this machine, `WORKFLOW-STATE.JSON`
1285
+ * and `workflow-state.json` resolve to the SAME INODE — the default macOS
1286
+ * filesystem is case-insensitive — so a case-sensitive match let the
1287
+ * uppercase spelling of every protected artifact through. On a case-sensitive
1288
+ * filesystem the two are different files, so folding costs only a refusal of
1289
+ * a file that cannot coexist with the real one where it matters.
1290
+ */
279
1291
  function names(text: string, list: string[]): string | null {
280
- for (const p of list) if (text.includes(p)) return p;
1292
+ const hay = text.toLowerCase();
1293
+ for (const p of list) if (hay.includes(p.toLowerCase())) return p;
281
1294
  return null;
282
1295
  }
283
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
+
284
1412
  const ALL_PROTECTED = [...PROTECTED_FILES, ...PROTECTED_HOOKS];
285
1413
 
286
1414
  /**
@@ -291,9 +1419,47 @@ const ALL_PROTECTED = [...PROTECTED_FILES, ...PROTECTED_HOOKS];
291
1419
  * reason the checks above are structural: a guard tuned so wide that people
292
1420
  * work around it protects nothing, and four real refusals of read-only work
293
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.
294
1427
  */
295
- export function decideBashWrite(cmd: string): BashWriteDecision {
1428
+ export function decideBashWrite(cmd: string, depth = 0, exemptIn?: boolean): BashWriteDecision {
296
1429
  if (!cmd) return ALLOW;
1430
+ // A shell body can contain a shell body. Bounded so a crafted nest costs a
1431
+ // fixed amount of work rather than the session.
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
+ }
297
1463
 
298
1464
  for (const seg of segments(cmd)) {
299
1465
  const bare = dequote(seg); // TARGET view: contents kept
@@ -302,7 +1468,12 @@ export function decideBashWrite(cmd: string): BashWriteDecision {
302
1468
 
303
1469
  // 1. Shell redirection and copying verbs. Never exempted by anything:
304
1470
  // this is the arm the old allowlist sat above, which is #1120.
305
- 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;
306
1477
  const pf = names(target, PROTECTED_FILES);
307
1478
  if (pf) {
308
1479
  return {
@@ -319,8 +1490,14 @@ export function decideBashWrite(cmd: string): BashWriteDecision {
319
1490
  // be an ARGUMENT — not any text in the segment. `sed -i '' "s/|
320
1491
  // X.hook.ts |/…/" NOTES.md` edits a markdown file and merely mentions
321
1492
  // a hook in its script; matching the whole segment refused it.
322
- if (IN_PLACE.some(p => p.test(code))) {
323
- const pf = names(argumentsOf(seg).join(' '), ALL_PROTECTED);
1493
+ // #1184: the resolved command word is prepended, so a QUOTED in-place
1494
+ // verb is still seen. Prepending rather than testing the dequoted
1495
+ // segment keeps the measured false positive out: `sed -i '' "s/|
1496
+ // X.hook.ts |/…/" NOTES.md` must not match `rm` because some quoted
1497
+ // text contains it, and `grep "rm -rf …"` must stay a grep.
1498
+ const verbView = `${word} ${code}`;
1499
+ if (IN_PLACE.some(p => p.test(verbView))) {
1500
+ const pf = namesOutsideScratch(argumentsOf(seg).join(' '), ALL_PROTECTED, exempt)[0];
324
1501
  if (pf) {
325
1502
  return {
326
1503
  blocked: true,
@@ -334,12 +1511,28 @@ export function decideBashWrite(cmd: string): BashWriteDecision {
334
1511
  // this asks for a declared write verb rather than refusing every
335
1512
  // interpreter that names a protected artifact, and for what that
336
1513
  // concession costs.
337
- const isInterpreter = INTERPRETERS.test(word) && /\s-[a-z]*[ce]\b/.test(code);
1514
+ const isInterpreter = isInterpreterWord(word) && /\s-[a-z]*[ce]\b/.test(code);
338
1515
  const isMutatingFind = word === 'find' && FIND_MUTATING.test(code);
1516
+
1517
+ // 3a. A shell `-c` body is shell. Read it as shell rather than scanning
1518
+ // it for Node and Python idioms it will never contain (#1176).
1519
+ if (isInterpreter && isShellWord(word)) {
1520
+ const body = shellBody(seg);
1521
+ if (body) {
1522
+ const inner = decideBashWrite(body, depth + 1, exempt);
1523
+ if (inner.blocked) return inner;
1524
+ }
1525
+ }
1526
+
339
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));
340
1533
  const pf = isMutatingFind
341
- ? names(bare, ALL_PROTECTED)
342
- : (ALL_PROTECTED.find(p => bare.includes(p) && writesNear(bare, p)) ?? null);
1534
+ ? (candidates[0] ?? null)
1535
+ : (candidates.find(p => writesNear(bare, p)) ?? null);
343
1536
  if (pf) {
344
1537
  return {
345
1538
  blocked: true,
@@ -350,23 +1543,65 @@ export function decideBashWrite(cmd: string): BashWriteDecision {
350
1543
  }
351
1544
  }
352
1545
 
353
- // 4. Permission changes on a hook file. The COMMAND WORD must be the
354
- // verb — not merely a `chmod` somewhere in the string, which is what
355
- // refused four read-only commands. The target is read off `bare`, so
356
- // quoting the path does not hide it.
357
- if ((word === 'chmod' || word === 'chflags') && names(bare, PROTECTED_HOOKS)) {
358
- 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
+ };
359
1577
  }
360
- }
361
1578
 
362
- // 5. The gate salt in the Keychain. Exempted by nothing — unlike `chmod`,
363
- // which turns up innocently in docs and greps, `pai-gate-salt` beside
364
- // `security` has no benign INVOCATION. It has a benign MENTION though,
365
- // and two real commands hit it: issue comments quoting the very command
366
- // they were proposing to guard. So it reads the code, not the prose.
367
- const codeOnly = stripQuoted(cmd);
368
- if (codeOnly.includes('pai-gate-salt') && codeOnly.includes('security')) {
369
- return { blocked: true, reason: 'Access to gate salt Keychain entry blocked.' };
1579
+ // 5. The gate salt in the Keychain. Exempted by nothing — unlike `chmod`,
1580
+ // which turns up innocently in docs and greps, `security` INVOKED on
1581
+ // the gate-salt entry has no benign form. It has a benign MENTION
1582
+ // though, and two real commands hit it: issue comments quoting the
1583
+ // very command they proposed to guard.
1584
+ //
1585
+ // #1176: this used to read `stripQuoted(cmd)` over the whole command,
1586
+ // which deleted the quoted key name outright — so the real invocation,
1587
+ // `security find-generic-password -s 'pai-gate-salt'`, could not fire
1588
+ // it. The prose case is now separated by POSITION instead: the command
1589
+ // word must BE `security`, which an issue comment's `gh` never is.
1590
+ // #1184: the key is matched across the WHOLE command, not just this
1591
+ // segment, so `KEY=pai-gate-salt; security … -s "$KEY"` cannot hide it
1592
+ // behind a variable. Measured cost: 0 commands in an unfiltered corpus
1593
+ // of 125,644. The command word must still BE `security`, which is what
1594
+ // keeps the `gh issue comment` prose case allowed.
1595
+ //
1596
+ // The other half of that suggestion — firing on any keychain
1597
+ // SUBCOMMAND whether or not the key is named — is refused. In the same
1598
+ // corpus only TWO commands have `security` as their command word, and
1599
+ // widening to subcommands newly blocks exactly one: `security
1600
+ // find-generic-password -h`, a help invocation. One false positive,
1601
+ // zero true positives, no evidence of the risk it was meant to cover.
1602
+ if (word === 'security' && dequote(cmd).toLowerCase().includes('pai-gate-salt')) {
1603
+ return { blocked: true, reason: 'Access to gate salt Keychain entry blocked.' };
1604
+ }
370
1605
  }
371
1606
 
372
1607
  return ALLOW;