rungate 0.8.24 → 0.8.26

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.
@@ -86,7 +86,7 @@
86
86
  * Narrowing it over-blocks; it cannot open a hole.
87
87
  */
88
88
 
89
- import { realpathSync, statSync } from 'fs';
89
+ import { lstatSync, realpathSync, statSync, type Stats } from 'fs';
90
90
  import { tmpdir } from 'os';
91
91
  import { basename, dirname, join, resolve } from 'path';
92
92
  import { isInterpreterWord, isShellWord } from './interpreters';
@@ -321,7 +321,7 @@ function scratchRoots(): string[] {
321
321
  * already matched, so the common command pays nothing for it.
322
322
  *
323
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
324
+ * see `chainHolds` (#1367), which is where that is handled, because the answer
325
325
  * is a property of the command and not of the path.
326
326
  *
327
327
  * An UNEXPANDED expansion is refused. `/tmp/$X/workflow-state.json` is not a
@@ -347,7 +347,7 @@ function scratchRoots(): string[] {
347
347
  * into the run store: `/tmp/sym*` does not exist, the walk climbs past it to
348
348
  * `/tmp`, and the path is exempted — then the shell expands the glob and the
349
349
  * write goes through the link. Same escape as the symlink case with no `ln`
350
- * in the command for `exemptionIsVoid` to see.
350
+ * in the command for a reader of the command to see.
351
351
  *
352
352
  * Only the directory part is tested, and that is measured rather than
353
353
  * cautious. A glob in the BASENAME is already safe, because the directory
@@ -408,229 +408,576 @@ function resolveThroughLinks(normalised: string): string | null {
408
408
  }
409
409
 
410
410
  /**
411
- * Does this command do something that makes a resolved path untrustworthy?
411
+ * Can this destination be shown to be what it looks like when the write
412
+ * RUNS, and not only when the decision is taken? (#1367)
412
413
  *
413
414
  * `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:
415
+ * time. A command that plants a link before it writes invalidates that
416
+ * resolution between the decision and the execution, and the whole thing
417
+ * fits in one command:
417
418
  *
418
419
  * ln -s ~/.rungate/victim /tmp/esc && echo '{}' > /tmp/esc/workflow-state.json
419
420
  *
420
421
  * At decision time `/tmp/esc` does not exist, the walk reaches `/tmp`, and
421
422
  * 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
- * `ln` is not the only verb that makes a link (#1411, raised as a CRITICAL
462
- * by the review on #1354).
463
- *
464
- * GNU and BSD `cp` create links on request and spell none of
465
- * `LINK_CREATION`'s four alternatives, so every one of these was ALLOWED —
466
- * the bypass in the docblock above, reachable by a different verb:
467
- *
468
- * cp -s ~/.rungate/victim /tmp/esc && echo '{}' > /tmp/esc/workflow-state.json
469
- *
470
- * Measured before the fix, all allowed: `cp -s`, `cp --symbolic-link`,
471
- * `cp -l`, `cp --link`, `cp -rs`, `cp -as`, `cp -sv`, `/bin/cp -s`,
472
- * `sudo cp -s`, `install -l s`. `-l` belongs with `-s`: a hard link to a
473
- * file inside the run store aims a later write at the victim's inode just
474
- * as a symlink aims it at the victim's path.
475
- *
476
- * ## The FAMILY, not the spelling
477
- *
478
- * A test for the literal `cp -s` is the cheapest wrong fix — seven of the
479
- * ten rows above walk around it. So the reading is token-level: a short
480
- * cluster is any `-…` containing a lower-case `s` or `l`, which is what
481
- * makes `-rs`, `-as` and `-sv` fall out of one rule rather than three; a
482
- * long option is matched by PREFIX, because GNU accepts any unambiguous
483
- * abbreviation and `--sym` is as real as `--symbolic-link`.
484
- *
485
- * Case matters: `cp -L` dereferences links in the SOURCE and creates none,
486
- * so only the lower-case letters count. `cp -r`, `cp -p`, `cp -a` and
487
- * `mkdir -p` are CONTROL rows and must stay exempt.
488
- *
489
- * The scan is position-independent rather than keyed to the resolved verb,
490
- * so `find . -exec cp -s …` is covered — the same position `LINK_CREATION`
491
- * exists to reach for `ln`, where `commandWord` resolves to `find`.
492
- *
493
- * ## And the `ln` boundary, since it was asked
494
- *
495
- * `\bln\s` needs a following character, so it misses an `ln` that ends a
496
- * segment. Measured over five spellings: the regex misses four, and the
497
- * segment-verb net catches three of those four (`ln`, `echo x && ln`,
498
- * `sudo ln`). The one neither catches is `find . -exec ln` with no
499
- * terminator, which `find(1)` refuses — "the expression must be terminated
500
- * by a semicolon" — so it is a syntax error, not a bypass. Count: ONE
501
- * spelling missed by both nets, ZERO executable. No change made.
502
- *
503
- * ## The FOUR transforms a shell applies before `cp` sees a flag
504
- *
505
- * Every bypass found in this family so far has been the same question asked
506
- * about a different transform, and each was rediscovered separately because
507
- * nothing wrote the list down. There are three, and a reading of a token is
508
- * only correct if it survives all of them:
509
- *
510
- * | transform | what the shell does | where this module does it |
511
- * |---|---|---|
512
- * | quote removal | `'-s'`, `"-s"`, `-'s'`, `c""p` all arrive bare | `readWord`, via `scanSegment` (#1429) |
513
- * | escape removal | `-\s`, `-r\s`, `-\-symbolic-link`, `--sy\mbolic-link` arrive as `-s`, `-rs`, `--symbolic-link` | `isLinkFlag`, before EITHER branch |
514
- * | substitution grouping | `` `…` `` and `$(…)` hand their text to ANOTHER shell, and `$(…)` nests | `nestedCommands` |
515
- * | ANSI-C quoting | `$'-s'` is the word `-s`, and `$'-\163'` is too | `readWord`, via `decodeAnsiC` |
516
- *
517
- * Measured against `/bin/bash` rather than assumed: `printf '[%s]' -\s -\l
518
- * -r\s -\-symbolic-link --sy\mbolic-link $'-s' $'-\163' $'cp'` prints
519
- * `[-s][-l][-rs][--symbolic-link][--symbolic-link][-s][-s][cp]`. Every one
520
- * of those was ALLOWED before its transform was read, as were
521
- * `` `cp -s …` ``, ``eval `cp -s …` ``, a `$(…)` containing a second
522
- * `$(…)`, and a `$(…)` wrapping a parenthesised subshell.
523
- *
524
- * The fourth arrived the way the second and third did — a review round
525
- * after the table said three — which is the argument for the table rather
526
- * than against it. If a fifth turns up, add the row. The point is that the
527
- * next reader checks all of them at once instead of finding them one review
528
- * at a time.
529
- *
530
- * ANSI-C is the one that hides a VERB as well as a flag: `$'cp' -s` leaves
531
- * `verbToken` nothing to match, so it is read in `readWord` — the module's
532
- * one quote reader — rather than in `isLinkFlag`, which a hidden verb never
533
- * reaches. Unlike the other substitution syntaxes it is settled at parse
534
- * time, so decoding it makes a word more readable rather than guessing at
535
- * one, and an unexpanded `$(…)` goes on reading as unprovable.
536
- */
537
- const LINK_VERBS = new Set(['cp', 'install']);
538
-
539
- /** A token's verb name: `/bin/cp` and `\cp` are both `cp`. */
540
- function verbToken(token: string): string {
423
+ * in the run store. Both halves were executed in the #1175 review: no second
424
+ * actor is required.
425
+ *
426
+ * ## The verb list this replaces, and why it was deleted
427
+ *
428
+ * Until #1367 the answer was a list of ways to make a link: a raw-text regex
429
+ * (`ln`, `symlinkSync`, `os.symlink`, `symlink(`), an `ln` command-word test,
430
+ * and a `cp`/`install` flag reader (#1411). A list of ways to make a link is
431
+ * wrong the moment somebody uses one that is not on it, and seven were not:
432
+ * `pathlib`'s `symlink_to`, `ruby`'s `File.symlink` without parentheses, and
433
+ * `cp -a`, `cp -r`, `mv`, `rsync -a` or `tar -x` carrying a link planted by
434
+ * an earlier command (#1425). All seven are witness rows in the tests.
435
+ *
436
+ * ## The property: the chain is REAL
437
+ *
438
+ * Every directory between the scratch root and the destination must exist
439
+ * NOW, or be made by a `mkdir` in this same command. A directory that exists
440
+ * cannot become a link without being removed first, and a directory `mkdir`
441
+ * makes is a directory — so a link the command makes cannot be in the chain,
442
+ * whatever verb makes it.
443
+ *
444
+ * A directory that neither exists nor is made is refused. The write into it
445
+ * would fail unless something in the command makes it, and the things that
446
+ * make it without `mkdir` are the ones this exists to catch.
447
+ *
448
+ * ## Why that alone was not enough to delete the list
449
+ *
450
+ * Built and run with only the paragraph above, three bypasses the list
451
+ * caught were re-opened — each with the plain `ln -s` or `cp -l` the list
452
+ * names. Every one is a test row that was red under that paragraph alone:
453
+ *
454
+ * 1. `ln -s V d && mkdir -p d && echo > d/…` — `mkdir -p` succeeds silently
455
+ * on a link to a directory, so the forgiveness clause forgave the link.
456
+ * 2. `rmdir d && ln -s V d && echo > d/…` with `d` real — the chain is real
457
+ * when the decision is taken and is not when the write runs.
458
+ * 3. `cp -l V/f d/f && echo > d/f` — a link at the destination FILE, which
459
+ * a property about directories says nothing about.
460
+ *
461
+ * So the property has three parts, and none of them reads a verb:
462
+ *
463
+ * PART 1 every directory of the chain is real now, or `mkdir` makes it;
464
+ * PART 2 nothing that runs before the write, or alongside it, NAMES a
465
+ * directory of the chain or the destination itself — a `mkdir`'s
466
+ * own arguments excepted. Removing a directory, re-linking it, or
467
+ * planting a link where `mkdir -p` will accept it all need the
468
+ * path spelled, and this asks whether it was — not by what;
469
+ * PART 3 an existing destination has one name and is not a link, and no
470
+ * existing directory of the chain is a symbolic link, so a link
471
+ * planted by an EARLIER command cannot be re-aimed unseen.
472
+ *
473
+ * ## What "names" means, and the direction it errs in
474
+ *
475
+ * A word names a path when, after quotes, ANSI-C, `~`, `$HOME` and the
476
+ * command's own earlier assignments are applied, it resolves to that path
477
+ * under either spelling and either case; when it is relative and its last
478
+ * component is the path's basename (`cd /tmp && ln -s V esc` spells only
479
+ * `esc`); or when an expansion or glob it still carries could produce that
480
+ * basename under that prefix. Interpreter bodies contribute their string
481
+ * literals; text handed to another shell — quoted words, `$( )`, backticks,
482
+ * `bash -c` bodies, heredoc programs — contributes its words. A body this
483
+ * module cannot read names everything. Each approximation errs toward
484
+ * NAMING, which costs an exemption and never opens one.
485
+ *
486
+ * "Before" is by position when the steps are sequential. A background `&`,
487
+ * a `coproc`, a subshell, a brace group or a substitution hides the order,
488
+ * and then every other step counts. A word naming the scratch ROOT counts as
489
+ * naming the chain, because a link put INTO the root takes its source's
490
+ * basename. `~` and `$HOME` read the command's own `HOME` first; any other
491
+ * tilde form could be anything.
492
+ *
493
+ * A plain `D=/tmp/x` sets a shell variable and touches nothing: its uses are
494
+ * substituted and read where they occur, which is what lets `mkdir -p $D`
495
+ * forgive. An EXPORTED value — `export D=…`, a `D=… cmd` prefix, `set -a`,
496
+ * or a name the environment already exports — reaches a process's
497
+ * environment, where a link can be made from it with the path never spelled
498
+ * again, so it names the path where it is set.
499
+ *
500
+ * ## A program that computes the path: `BODY_LINK_CALL`
501
+ *
502
+ * A program that computes a directory's name at run time — decoded,
503
+ * assembled, read from a file — and re-links a directory that ALREADY
504
+ * exists names nothing a reader of the command can see. With the list gone
505
+ * that was a regression for the list's own spellings, so an interpreter body
506
+ * that calls a link function names everything (Jason's option (b), PR #2282).
507
+ * A body that only makes directories — the `mkdirSync` fixtures #1175 exists
508
+ * to allow — calls none and is unaffected. Outside interpreter bodies the
509
+ * shell's own words are read, and an expansion already names what it could
510
+ * produce.
511
+ */
512
+
513
+ /** Decides, for one destination path, whether the scratch exemption holds. */
514
+ type Exemption = (path: string) => boolean;
515
+ const NO_EXEMPTION: Exemption = () => false;
516
+
517
+ /** A word that may name a path, and where in the command it sits. */
518
+ interface Mention {
519
+ /** The word, with the command's earlier assignments substituted. */
520
+ text: string;
521
+ /** Its top-level step; -1 when its position is unknown. */
522
+ at: number;
523
+ /** `seg:i`, `sub:i` (handed to another shell), `body:i`, `prog:k`, `outer`. */
524
+ src: string;
525
+ }
526
+
527
+ /** Which top-level steps run before, or alongside, which. */
528
+ interface StepOrder {
529
+ /** False when a background `&`, a `coproc`, or a bracket hides the order. */
530
+ ordered: boolean;
531
+ /** Pipeline membership per step: equal numbers run concurrently. */
532
+ group: number[];
533
+ }
534
+
535
+ /** What the whole command does that the chain question depends on. */
536
+ interface ChainContext {
537
+ /** Directories some `mkdir` in the command makes, by `chainKey`. */
538
+ made: Set<string>;
539
+ mentions: Mention[];
540
+ order: StepOrder;
541
+ }
542
+
543
+ /** What an enclosing command hands down to a body it runs. */
544
+ interface Outer {
545
+ made: Set<string>;
546
+ mentions: Mention[];
547
+ }
548
+
549
+ /**
550
+ * One spelling per directory, so `/tmp/x`, `/private/tmp/x` and `/TMP/X`
551
+ * compare equal: resolved through the links that exist, then folded the way
552
+ * `names()` folds, because the default macOS volume makes them one inode.
553
+ * On a case-sensitive volume the fold over-matches, which only ever refuses.
554
+ */
555
+ function chainKey(p: string): string {
556
+ const normalised = resolve(p);
557
+ return (resolveThroughLinks(normalised) ?? normalised).normalize('NFC').toLowerCase();
558
+ }
559
+
560
+ /** A token's bare name: `/bin/mkdir` and `\mkdir` are both `mkdir`. */
561
+ function verbName(token: string): string {
541
562
  const bare = token.replace(/^[\\(]+/, '');
542
563
  return bare.slice(bare.lastIndexOf('/') + 1);
543
564
  }
544
565
 
545
- function isLinkFlag(raw: string): boolean {
546
- // ESCAPE REMOVAL, the second of the three transforms in the table above,
547
- // and it governs BOTH branches below rather than only the short one.
548
- // `cp -\s` reaches `cp` as `-s` and `cp --sy\mbolic-link` reaches it as
549
- // `--symbolic-link`; against the raw token the letter run reads `''` and
550
- // the long name fails its prefix test, so all five escaped spellings were
551
- // measured ALLOWED.
552
- //
553
- // A backslash inside a QUOTED word is literal to the shell, and `readWord`
554
- // has already removed the quotes by the time the token arrives, so this
555
- // cannot tell `-\s` from `'-\s'` and treats both as `-s`. That is the
556
- // fail-closed direction and it costs a token that `cp` itself rejects as
557
- // an invalid option. The control that keeps it honest is an ordinary
558
- // quoted filename containing a backslash, which carries no leading `-`
559
- // and so never reaches either branch.
560
- const token = raw.replace(/\\(.)/g, '$1');
561
- if (token.startsWith('--')) {
562
- const name = token.slice(2).split('=')[0];
563
- if (!name) return false;
564
- return 'symbolic-link'.startsWith(name) || 'link'.startsWith(name);
566
+ /**
567
+ * `$NAME`, `${NAME}` and a leading `~`, from what the command assigned
568
+ * EARLIER — its own `HOME` before the environment's, for `~` as well as
569
+ * `$HOME` (#1367 review). Anything else is left as written, so it stays
570
+ * unresolved and forgives nothing.
571
+ *
572
+ * A tilde other than `~` or `~/…` — `~+`, `~-`, `~user` — expands to a
573
+ * directory this module cannot see, so it becomes `$?`, which reads as
574
+ * "could be anything" everywhere downstream and cannot be assigned to.
575
+ */
576
+ const ANYTHING = '$?';
577
+
578
+ function substitute(word: string, vars: Map<string, string | null>): string {
579
+ const home = vars.has('HOME') ? vars.get('HOME') : process.env.HOME || null;
580
+ let w = word;
581
+ const tilde = /^~([^/]*)/.exec(w);
582
+ if (tilde) w = (tilde[1] === '' && typeof home === 'string' && home ? home : ANYTHING) + w.slice(tilde[0].length);
583
+ return w.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g, (m, a, b) => {
584
+ const name = a ?? b;
585
+ const v = vars.has(name) ? vars.get(name) : name === 'HOME' ? home : undefined;
586
+ return typeof v === 'string' && v ? v : m;
587
+ });
588
+ }
589
+
590
+ /** Record `NAME=value`; an unresolvable value is recorded as unresolvable. */
591
+ function assign(word: string, vars: Map<string, string | null>): void {
592
+ const eq = word.indexOf('=');
593
+ const value = substitute(word.slice(eq + 1), vars);
594
+ vars.set(word.slice(0, eq), /[$`]/.test(value) ? null : value);
595
+ }
596
+
597
+ /** Text a resolved path cannot contain: an expansion, a glob, a brace. */
598
+ const UNRESOLVED = /[$`*?[\]{}]/;
599
+
600
+ /** Add `path`, and with `parents` every ancestor of it, to `made`. */
601
+ function addMade(path: string, parents: boolean, made: Set<string>): void {
602
+ if (!path.startsWith('/') || UNRESOLVED.test(path)) return; // unplaceable: forgives nothing
603
+ let d = resolve(path);
604
+ made.add(chainKey(d));
605
+ if (!parents) return;
606
+ for (let up = dirname(d); up !== d; d = up, up = dirname(up)) made.add(chainKey(up));
607
+ }
608
+
609
+ /**
610
+ * The directories a shell `mkdir` segment makes. `-p` makes the ancestors
611
+ * too; without it a missing parent fails the `mkdir`, so only the argument
612
+ * itself is made. `-m` takes a value, which is not a directory.
613
+ */
614
+ function mkdirMakes(words: string[], vars: Map<string, string | null>, made: Set<string>): void {
615
+ const at = words.findIndex(w => verbName(w) === 'mkdir');
616
+ if (at === -1) return;
617
+ let parents = false;
618
+ let value = false;
619
+ let options = true;
620
+ const paths: string[] = [];
621
+ for (const w of words.slice(at + 1)) {
622
+ if (value) {
623
+ value = false;
624
+ continue;
625
+ }
626
+ if (options && w === '--') {
627
+ options = false;
628
+ continue;
629
+ }
630
+ if (options && w.startsWith('--')) {
631
+ if (w === '--parents') parents = true;
632
+ if (w === '--mode') value = true;
633
+ continue;
634
+ }
635
+ if (options && /^-[A-Za-z]/.test(w)) {
636
+ const letters = /^-([A-Za-z]*)/.exec(w)?.[1] ?? '';
637
+ if (letters.includes('p')) parents = true;
638
+ // `-m 755` and `-pm 755` take the NEXT word; `-m755` carries it.
639
+ if (letters.endsWith('m') && letters.length === w.length - 1) value = true;
640
+ continue;
641
+ }
642
+ paths.push(w);
565
643
  }
566
- if (!token.startsWith('-') || token.length < 2) return false;
567
- // A flag whose letters this module cannot read — `-$F`, `-${X}`, `-`+a
568
- // substitution — is one it cannot rule OUT, and the verb is already known
569
- // to make links on request. Same fail-closed shape as an unplaceable
570
- // literal in `placeLiteral`: declining to clear is cheap and visible,
571
- // clearing something unread is neither.
572
- if (/[$`]/.test(token)) return true;
573
- // The LEADING LETTER RUN, not the whole token. `cp -st/tmp/esc` bundles
574
- // `-s` with `-t`'s attached argument and `cp -sS.bak` bundles it with
575
- // `-S`'s, and an anchored `^-[A-Za-z]+$` rejected both on the `/` and the
576
- // `.` without ever reading the `s`. Both were measured ALLOWED. The
577
- // controls are the same bundles without the link letter — `-t/tmp/p` and
578
- // `-S.bak` — which must stay exempt, and do.
579
- //
580
- // Lower case only: `-L` follows links in the SOURCE and creates none.
581
- const letters = /^-([A-Za-z]*)/.exec(token)?.[1] ?? '';
582
- return /[sl]/.test(letters);
644
+ for (const p of paths) addMade(substitute(p, vars), parents, made);
583
645
  }
584
646
 
585
647
  /**
586
- * The tokens come from `scanSegment`, the module's ONE quote-aware pass.
587
- *
588
- * The first spelling of this used `stripQuoted`, which deletes a quoted
589
- * span's content rather than removing the quotes, and the #1429 review was
590
- * right that it defeated the whole check: `cp '-s'`, `cp "-s"`, `"cp" -s`,
591
- * `c""p -s` and `cp --'s'ymbolic-link` were all measured ALLOWED, each one
592
- * a command the shell runs identically to the one that was refused.
593
- *
594
- * The second spelling was a tokeniser of my own, and that was the wrong
595
- * repair even though it worked. `commandWord` already resolves `"cp"`
596
- * correctly, through `scanSegment`, because #1184 and #1196 taught it to
597
- * after `stripQuoted` deleted `"chmod"` outright. A second tokeniser beside
598
- * it is two deciders answering one question — the fourth shape in
599
- * `.claude/rules/checks-must-be-able-to-fail.md` — and a mutation of either
600
- * leaves the other holding every case up. One tokeniser.
648
+ * The directories an interpreter body makes with a `mkdir` call whose first
649
+ * argument is a literal: `mkdirSync`, `fs.promises.mkdir`, `os.mkdir`,
650
+ * `os.makedirs`, and `Path("…").mkdir(…)`. `recursive` / `parents=True` /
651
+ * `makedirs` make the ancestors too. A call whose path is computed forgives
652
+ * nothing — the fail-closed direction.
653
+ */
654
+ const BODY_MKDIR = new Set(['mkdirSync', 'mkdir', 'makedirs']);
655
+ const PATH_CTORS = new Set(['Path', 'PurePath', 'PosixPath']);
656
+
657
+ function bodyMakes(body: string, lits: Array<{ value: string; start: number; end: number }>, made: Set<string>): Set<number> {
658
+ const consumed = new Set<number>();
659
+ for (const { value, start, end } of lits) {
660
+ const open = previousNonSpace(body, start - 1);
661
+ if (body[open] !== '(') continue;
662
+ const callee = calleeBefore(body, open);
663
+ const last = callee.slice(callee.lastIndexOf('.') + 1);
664
+ const rest = body.slice(end + 1);
665
+ if (BODY_MKDIR.has(last)) {
666
+ const args = rest.split(')')[0];
667
+ addMade(value, last === 'makedirs' || /\brecursive\s*:\s*true\b|\bparents\s*=\s*True\b/.test(args), made);
668
+ consumed.add(start);
669
+ continue;
670
+ }
671
+ const chained = /^\s*\)\s*\.mkdir\s*\(([^)]*)\)/.exec(rest);
672
+ if (PATH_CTORS.has(last) && chained) {
673
+ addMade(value, /\bparents\s*=\s*True\b/.test(chained[1]), made);
674
+ consumed.add(start);
675
+ }
676
+ }
677
+ return consumed;
678
+ }
679
+
680
+ /** The index of the last non-whitespace character at or before `i`. */
681
+ function previousNonSpace(text: string, i: number): number {
682
+ while (i >= 0 && WHITESPACE.has(text[i])) i--;
683
+ return i;
684
+ }
685
+
686
+ /** A body this module cannot read names every path (see `mentionNames`). */
687
+ const NAMES_EVERYTHING = '$UNREADABLE';
688
+
689
+ interface Sink {
690
+ made: Set<string>;
691
+ mentions: Mention[];
692
+ /** Plain assignments, whose values count only if the name is exported. */
693
+ plain: Array<{ name: string; mention: Mention }>;
694
+ allexport: boolean;
695
+ }
696
+
697
+ const subSrc = (src: string): string => (src.startsWith('seg:') ? `sub:${src.slice(4)}` : src);
698
+ const bodySrc = (src: string): string => (src.startsWith('seg:') ? `body:${src.slice(4)}` : src);
699
+
700
+ /**
701
+ * Read `text` as shell: what its `mkdir`s make (when `makes`), and every
702
+ * word that may name a path. `tag` places each of its segments in the
703
+ * top-level command. Text handed to another shell is read with `makes`
704
+ * off — a quoted string that LOOKS like a `mkdir` makes nothing.
705
+ */
706
+ function collectShell(text: string, depth: number, tag: (i: number) => { at: number; src: string }, sink: Sink, makes: boolean): void {
707
+ if (depth > 3) {
708
+ sink.mentions.push({ text: NAMES_EVERYTHING, at: -1, src: 'deep' });
709
+ return;
710
+ }
711
+ const vars = new Map<string, string | null>();
712
+ segments(text).forEach((seg, i) => {
713
+ const { at, src } = tag(i);
714
+ const { words, targets } = scanSegment(seg);
715
+ const word = commandWord(seg);
716
+ const add = (w: string) => sink.mentions.push({ text: substitute(w, vars), at, src });
717
+ const nested = () => {
718
+ for (const n of nestedCommands(seg)) collectShell(n, depth + 1, () => ({ at, src: subSrc(src) }), sink, false);
719
+ };
720
+ if (!word && words.length > 0 && words.every(w => ASSIGNMENT.test(w))) {
721
+ for (const w of words) {
722
+ const value = substitute(w.slice(w.indexOf('=') + 1), vars);
723
+ sink.plain.push({ name: w.slice(0, w.indexOf('=')), mention: { text: value, at, src } });
724
+ assign(w, vars);
725
+ }
726
+ nested(); // `x="$(…)"` runs the substitution, whatever it assigns
727
+ return;
728
+ }
729
+ if (word === 'set' && words.some(w => /^-[A-Za-z]*a/.test(w) || w === 'allexport')) sink.allexport = true;
730
+ if (word === 'mkdir') {
731
+ if (makes) mkdirMakes(words, vars, sink.made);
732
+ nested(); // a `mkdir`'s own arguments are not mentions; a substitution in one is
733
+ return;
734
+ }
735
+ if (isInterpreterWord(word) && /\s-[a-z]*[ce]\b/.test(stripQuoted(seg))) {
736
+ const shell = isShellWord(word);
737
+ const body = shell ? shellBody(seg) : programBody(seg);
738
+ for (const w of words) if (w !== body && dequote(w) !== body) add(w);
739
+ if (shell) collectShell(body, depth + 1, () => ({ at, src }), sink, makes);
740
+ else collectBody(body, at, bodySrc(src), sink, makes);
741
+ return;
742
+ }
743
+ for (const w of [...words, ...targets]) add(w);
744
+ nested();
745
+ });
746
+ }
747
+
748
+ /**
749
+ * A call that makes a link, in any interpreter body: `symlink` in every
750
+ * spelling (`os.symlink`, `fs.symlinkSync`, `fs.promises.symlink(`,
751
+ * `symlink_to`, ruby's `File.symlink a, b`, perl's `symlink $a, $b`), the
752
+ * hard-link calls (`os.link`, `linkSync`, `hardlink_to`, `link(`), and `ln`
753
+ * handed to a subprocess.
754
+ *
755
+ * Jason's option (b) on PR #2282, 2026-11-16. A program can compute a path at
756
+ * run time — decoded, assembled, read from a file — and link it, and then no
757
+ * word in the command spells the path. A body that calls one of these
758
+ * therefore NAMES EVERYTHING, like a body this module cannot read. That is
759
+ * the one place a verb list survives #1367: it closes the regression the
760
+ * deleted list's own spellings would otherwise have, and only ever refuses.
761
+ * A body that only makes directories calls none of these.
762
+ */
763
+ export const BODY_LINK_CALL = /\bsymlink(?:Sync|_to|at)?\b|\bhardlink_to\b|\blink(?:Sync|at)?\s*\(|\bos\.link\b|\bFile\.link\b|\bln\b/;
764
+
765
+ /** An interpreter body: its `mkdir` calls make, its other literals are mentions. */
766
+ function collectBody(body: string, at: number, src: string, sink: Sink, makes: boolean): void {
767
+ const lits = readLiterals(body);
768
+ if (!lits || BODY_LINK_CALL.test(body)) sink.mentions.push({ text: NAMES_EVERYTHING, at, src });
769
+ if (!lits) return;
770
+ const consumed = bodyMakes(body, lits, makes ? sink.made : new Set());
771
+ for (const l of lits) if (!consumed.has(l.start)) sink.mentions.push({ text: l.value, at, src });
772
+ }
773
+
774
+ /** Read everything in `cmd` the chain question depends on, once. */
775
+ function chainContext(cmd: string, outer?: Outer): ChainContext {
776
+ const sink: Sink = { made: new Set(outer?.made ?? []), mentions: [...(outer?.mentions ?? [])], plain: [], allexport: false };
777
+ collectShell(cmd, 0, i => ({ at: i, src: `seg:${i}` }), sink, true);
778
+ interpreterPrograms(cmd).forEach(({ shell, program }, k) => {
779
+ if (shell) collectShell(program, 1, () => ({ at: -1, src: `prog:${k}` }), sink, true);
780
+ else collectBody(program, -1, `prog:${k}`, sink, true);
781
+ });
782
+ // An exported value reaches a process's environment, so it names the path
783
+ // where it is set. `export D` and `D=… cmd` both spell the name as a word.
784
+ // A name the environment ALREADY exports stays exported when the command
785
+ // reassigns it (#1367 review): `HOME=…` reaches every child process.
786
+ const exported = (name: string): boolean =>
787
+ sink.allexport ||
788
+ process.env[name] !== undefined ||
789
+ sink.mentions.some(m => m.text === name || m.text.startsWith(`${name}=`));
790
+ for (const { name, mention } of sink.plain) if (exported(name)) sink.mentions.push(mention);
791
+ return { made: sink.made, mentions: sink.mentions, order: stepOrder(cmd) };
792
+ }
793
+
794
+ /**
795
+ * Which steps of `cmd` run before, or alongside, which — read off its
796
+ * separators. Position is order only for plain sequential steps: a
797
+ * background `&`, a `coproc`, a subshell, a brace group, a command or
798
+ * process substitution can each run a step out of its written place, so any
799
+ * of them makes every other step count (#1367 review).
800
+ */
801
+ function stepOrder(cmd: string): StepOrder {
802
+ const parts = splitSegments(cmd);
803
+ const background = parts.some(p => p.sep === '&' || commandWord(p.text) === 'coproc');
804
+ const bracketed = /[()]|(?:^|[\s;&|])\{(?=\s|$)/m.test(stripQuoted(cmd));
805
+ const group: number[] = [];
806
+ let g = 0;
807
+ parts.forEach((p, i) => {
808
+ group[i] = g;
809
+ if (p.sep !== '|' && p.sep !== 'redir') g++;
810
+ });
811
+ return { ordered: !background && !bracketed, group };
812
+ }
813
+
814
+ /** Can the step at `from` run before, or alongside, the write at `at`? */
815
+ function runsBefore(from: number, at: number, order: StepOrder): boolean {
816
+ if (from < 0 || at < 0 || !order.ordered) return true;
817
+ return from < at || order.group[from] === order.group[at];
818
+ }
819
+
820
+ /** The directories strictly between `root` and the destination. */
821
+ function chainBelow(root: string, normalised: string): string[] {
822
+ const out: string[] = [];
823
+ for (let d = dirname(normalised); d.startsWith(root + '/'); d = dirname(d)) out.push(d);
824
+ return out;
825
+ }
826
+
827
+ /** The deepest scratch root this (normalised) path is inside. */
828
+ function scratchRootOf(normalised: string): string | null {
829
+ const roots = scratchRoots().filter(r => inAnyTree(normalised, [r]));
830
+ return roots.sort((a, b) => b.length - a.length)[0] ?? null;
831
+ }
832
+
833
+ const fold = (s: string): string => s.normalize('NFC').toLowerCase();
834
+
835
+ /** `lstat`, or `null` when nothing is there. */
836
+ function lstatOrNull(p: string): Stats | null {
837
+ try {
838
+ return lstatSync(p);
839
+ } catch {
840
+ return null; // not there now — part 1 decides whether that is allowed
841
+ }
842
+ }
843
+
844
+ /** Mentions that come from the write's OWN step and do not count against it. */
845
+ interface Own {
846
+ src: string;
847
+ /** When set, only these texts from `src` are the write's own; the rest count. */
848
+ only?: Set<string>;
849
+ }
850
+
851
+ /**
852
+ * The three parts, for one destination. See the docblock above `Exemption`.
853
+ */
854
+ function chainHolds(path: string, ctx: ChainContext, own: Own, at: number): boolean {
855
+ const normalised = resolve(path);
856
+ const root = scratchRootOf(normalised);
857
+ if (!root) return false;
858
+ const dirs = chainBelow(root, normalised);
859
+ // PART 1, with part 3's directory half: real now and not a link, or made.
860
+ for (const dir of dirs) {
861
+ const st = lstatOrNull(dir);
862
+ if (st === null) {
863
+ if (!ctx.made.has(chainKey(dir))) return false;
864
+ continue;
865
+ }
866
+ if (!st.isDirectory()) return false; // a symbolic link, or a file
867
+ }
868
+ // PART 3: an existing destination has one name and is not a link.
869
+ const dest = lstatOrNull(normalised);
870
+ if (dest && (dest.isSymbolicLink() || (!dest.isDirectory() && dest.nlink > 1))) return false;
871
+ // PART 2: nothing before the write names the chain or the destination.
872
+ // The ROOT is named too (#1367 review): `ln -s V /tmp/` and `ln -s V -t
873
+ // /tmp` call the link after V's basename, so a step that puts anything
874
+ // INTO the root plants a name only its source spells. A chain directory's
875
+ // other parents are chain directories, and are already named.
876
+ const named = [root, ...dirs, normalised].map(p => ({ key: chainKey(p), base: fold(basename(p)) }));
877
+ for (const m of ctx.mentions) {
878
+ // The word being judged is never a mention of itself — a copy's SOURCE
879
+ // literal is judged too, by every path word that carries the name.
880
+ if (m.src === own.src && (!own.only || own.only.has(m.text) || m.text === path)) continue;
881
+ if (!runsBefore(m.at, at, ctx.order)) continue;
882
+ if (mentionNames(m.text, named)) return false;
883
+ }
884
+ return true;
885
+ }
886
+
887
+ /** A word as a path, and — for `--opt=value` or `NAME=value` — its value. */
888
+ function mentionCandidates(text: string): string[] {
889
+ const w = text.replace(/^[(!{]+/, '').replace(/[);,]+$/, '');
890
+ if (!w) return [];
891
+ const eq = w.indexOf('=');
892
+ return eq > 0 && eq < w.length - 1 ? [w, w.slice(eq + 1)] : [w];
893
+ }
894
+
895
+ /** Text not settled until the command runs: an expansion, a substitution, a glob, a brace. */
896
+ const OPEN_TEXT = /[$`*?[{]/;
897
+ const OPEN_PIECE = /(\$\{[^}]*\}?|\$[A-Za-z_0-9?#@*!$-]*|\*|\?|\[[^\]]*\]|\{[^}]*\})/;
898
+
899
+ /** A component carrying open text, as the set of names it could produce. */
900
+ function openPattern(component: string): RegExp {
901
+ const src = component
902
+ .split(OPEN_PIECE)
903
+ .map((p, i) => (i % 2 === 1 ? (p === '?' ? '.' : '.*') : p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')))
904
+ .join('');
905
+ return new RegExp(`^${src}$`, 'i');
906
+ }
907
+
908
+ /** Does this word name any of these paths? See "What names means" above. */
909
+ function mentionNames(text: string, named: Array<{ key: string; base: string }>): boolean {
910
+ for (const w of mentionCandidates(text)) {
911
+ const trimmed = w.replace(/\/+$/, '') || w;
912
+ const last = trimmed.slice(trimmed.lastIndexOf('/') + 1);
913
+ const open = w.search(OPEN_TEXT);
914
+ if (open === -1) {
915
+ if (w.startsWith('/')) {
916
+ const key = chainKey(w);
917
+ if (named.some(n => n.key === key)) return true;
918
+ continue;
919
+ }
920
+ if (last === '.' || last === '..') return true; // relative to a directory nobody can see
921
+ if (named.some(n => n.base === fold(last))) return true;
922
+ continue;
923
+ }
924
+ // A substitution can produce anything, slashes included; a variable or
925
+ // glob produces one component's worth, so the last one is matched.
926
+ const prefix = w.slice(0, open);
927
+ const prefixKey = prefix.startsWith('/') ? chainKey(prefix) : null;
928
+ const pattern = /\$\(|`/.test(w) ? null : openPattern(last);
929
+ for (const n of named) {
930
+ if (prefixKey !== null && n.key !== prefixKey && !n.key.startsWith(prefixKey)) continue;
931
+ if (pattern && !pattern.test(n.base)) continue;
932
+ return true;
933
+ }
934
+ }
935
+ return false;
936
+ }
937
+
938
+ /** The exemption for writes judged at step `at`, excluding the write's own words. */
939
+ function judgeFor(getCtx: () => ChainContext, own: Own, at: number): Exemption {
940
+ return path => isScratchPath(path) && chainHolds(path, getCtx(), own, at);
941
+ }
942
+
943
+ /**
944
+ * What a body run by step `at` inherits: every `mkdir`, and every mention
945
+ * from a step that runs before or alongside it, placed BEFORE everything
946
+ * inside — except the body's own words, which it reads with positions.
601
947
  */
602
- function flagMakesLink(segment: string): boolean {
603
- const words = scanSegment(segment).words;
604
- if (!words.some(w => LINK_VERBS.has(verbToken(w)))) return false;
605
- return words.some(isLinkFlag);
948
+ function outerFor(ctx: ChainContext, src: string, at: number): Outer {
949
+ return {
950
+ made: ctx.made,
951
+ mentions: ctx.mentions
952
+ .filter(m => m.src !== src && runsBefore(m.at, at, ctx.order))
953
+ .map(m => ({ ...m, at: -1, src: 'outer' })),
954
+ };
606
955
  }
607
956
 
608
957
  /**
609
958
  * Text a segment will hand to ANOTHER shell: the contents of its quoted
610
959
  * words and of its command substitutions (#1429).
611
960
  *
612
- * `ln` is caught inside `bash -c '…'`, `$( … )` and `eval '…'` today, but
613
- * only because `LINK_CREATION` is a regex read off the raw text and a regex
614
- * does not care about nesting. A reading built on segments and tokens does,
615
- * and all four spellings of `cp -s` were measured ALLOWED while their `ln`
616
- * twins were refused — so this is not a new hole, it is the old net's reach
617
- * that the new one had to be given too.
961
+ * #1429 built this for the verb list #1367 deleted; it now feeds part 2 of
962
+ * the chain property, which needs the words of `eval '…'`, `$( … )` and
963
+ * backticks for the same reason the list needed their verbs — a reading built
964
+ * on segments does not see inside them. Every quoted span is read, data or
965
+ * not, which over-collects: that is the direction part 2 is allowed to err.
618
966
  *
619
967
  * `interpreterPrograms` was the obvious place and is the wrong one: it
620
- * reaches a heredoc body and returns NOTHING for `bash -c 'cp -s …'`,
621
- * `sh -c "…"`, `$( … )` or `eval '…'` — measured, all four empty, against
622
- * a heredoc control that returns the body. Widening it would change what
623
- * every other arm reads. This is local to the void check.
968
+ * reaches a heredoc body and returns NOTHING for `sh -c "…"`, `$( … )` or
969
+ * `eval '…'` — measured, all four empty, against a heredoc control that
970
+ * returns the body. Widening it would change what every other arm reads.
624
971
  */
625
972
  function nestedCommands(view: string): string[] {
626
973
  const out: string[] = [];
627
- for (const m of view.matchAll(/'([^']*)'|"([^"]*)"/g)) out.push(m[1] ?? m[2] ?? '');
628
- // Backticks are the OTHER substitution syntax and were missing entirely:
629
- // `` `cp -s …` `` and ``eval `cp -s …` `` were measured ALLOWED while
630
- // their `ln` twins were refused, for the same reason the `$(…)` rows were
631
- // — `LINK_CREATION` is a raw-text regex that does not care about nesting
632
- // and this reading is built on segments. They do not nest in bash, so a
633
- // flat match is the whole grammar here.
974
+ // A substitution inside a quoted span is read by the walk below. Left in
975
+ // the span, `segments` cuts it at its own `;` and the fragment `$(date`
976
+ // reads as a word that could be anything (#1367), so it is blanked here.
977
+ for (const m of view.matchAll(/'([^']*)'|"([^"]*)"/g)) out.push(blankSubstitutions(m[1] ?? m[2] ?? ''));
978
+ // Backticks are the OTHER substitution syntax and were missing entirely
979
+ // from #1429's first reading. They do not nest in bash, so a flat match is
980
+ // the whole grammar here.
634
981
  for (const m of view.matchAll(/`([^`]*)`/g)) out.push(m[1]);
635
982
  // `$(…)` DOES nest, so it gets the module's one substitution walk rather
636
983
  // than a second spelling of it. Every `$(` position is examined — the
@@ -645,21 +992,23 @@ function nestedCommands(view: string): string[] {
645
992
  return out.filter(s => /\s/.test(s));
646
993
  }
647
994
 
648
- /**
649
- * #1240: both tests read a view that KEEPS the text an interpreter is going
650
- * to run. `stripHeredocs` deletes a heredoc body, so an `ln` inside
651
- * `bash <<'EOF'` was invisible to the first test; `segments(cmd)` over the
652
- * raw command does not make a body's lines into segments, so it was
653
- * invisible to the second as well. One view, built once, fed to both.
654
- */
655
- function exemptionIsVoid(cmd: string): boolean {
656
- const programs = interpreterPrograms(cmd).map(p => p.program);
657
- const view = [stripHeredocs(cmd), ...programs].join('\n');
658
- if (LINK_CREATION.test(view)) return true;
659
- const all = [...segments(view), ...nestedCommands(view).flatMap(inner => segments(inner))];
660
- return all.some(seg => commandWord(seg) === 'ln' || flagMakesLink(seg));
995
+ /** `text` with every `$( … )` and backtick span replaced by `$?` (#1367). */
996
+ function blankSubstitutions(text: string): string {
997
+ let out = '';
998
+ for (let i = 0; i < text.length; i++) {
999
+ if (text[i] === '$' && text[i + 1] === '(') {
1000
+ out += ANYTHING;
1001
+ i = endOfSubstitution(text, i) - 1;
1002
+ } else if (text[i] === '`') {
1003
+ out += ANYTHING;
1004
+ const close = text.indexOf('`', i + 1);
1005
+ i = close === -1 ? text.length : close;
1006
+ } else out += text[i];
1007
+ }
1008
+ return out;
661
1009
  }
662
1010
 
1011
+
663
1012
  /**
664
1013
  * Path-like words in `text` that contain `needle`.
665
1014
  *
@@ -705,13 +1054,26 @@ function pathWordsContaining(text: string, needle: string): string[] {
705
1054
  * never opens a hole, which is the direction a guard should err in.
706
1055
  */
707
1056
  export function segments(cmd: string): string[] {
1057
+ return splitSegments(cmd).map(p => p.text);
1058
+ }
1059
+
1060
+ /**
1061
+ * `segments`, with the separator that ENDS each one (#1367): `;`, `\n`,
1062
+ * `|`, `||`, `&`, `&&`, or `redir` for the `&` of `2>&1` / `&>`, which
1063
+ * this splitter has always cut at and which is not a background job. One
1064
+ * splitter, so the order the chain property reads cannot disagree with the
1065
+ * segments every arm reads. An empty segment is dropped and its separator
1066
+ * folded into the one before it, strongest first: a `&` hides order, a `|`
1067
+ * joins a pipeline.
1068
+ */
1069
+ function splitSegments(cmd: string): Array<{ text: string; sep: string }> {
708
1070
  // Heredoc bodies go FIRST, before anything looks for a separator. A
709
1071
  // heredoc is not a quote, so a `|` or `;` inside an issue body, a commit
710
1072
  // message or a PR description used to tear the document into fragments
711
1073
  // and each fragment was then read as a command — which is how a sentence
712
1074
  // about `workflow-state.json` came to be refused as a write to it.
713
1075
  cmd = stripHeredocs(cmd);
714
- const out: string[] = [];
1076
+ const raw: Array<{ text: string; sep: string }> = [];
715
1077
  let cur = '';
716
1078
  let quote: string | null = null;
717
1079
  for (let i = 0; i < cmd.length; i++) {
@@ -772,15 +1134,32 @@ export function segments(cmd: string): string[] {
772
1134
  continue;
773
1135
  }
774
1136
  if (c === ';' || c === '\n' || c === '|' || c === '&') {
775
- if (cmd[i + 1] === c) i++; // `&&`, `||` are one separator, not two
776
- out.push(cur);
1137
+ let sep: string = c;
1138
+ if (c === '&' && (cmd[i - 1] === '>' || cmd[i - 1] === '<' || cmd[i + 1] === '>')) sep = 'redir';
1139
+ if (cmd[i + 1] === c) {
1140
+ i++; // `&&`, `||` are one separator, not two
1141
+ sep = c + c;
1142
+ }
1143
+ raw.push({ text: cur, sep });
777
1144
  cur = '';
778
1145
  continue;
779
1146
  }
780
1147
  cur += c;
781
1148
  }
782
- out.push(cur);
783
- return out.map(s => s.trim()).filter(Boolean);
1149
+ raw.push({ text: cur, sep: '' });
1150
+ const out: Array<{ text: string; sep: string }> = [];
1151
+ for (const p of raw) {
1152
+ const text = p.text.trim();
1153
+ if (text) {
1154
+ out.push({ text, sep: p.sep });
1155
+ continue;
1156
+ }
1157
+ const prev = out[out.length - 1];
1158
+ if (!prev) continue;
1159
+ if (p.sep === '&' || prev.sep === '&') prev.sep = '&';
1160
+ else if (p.sep === '|' || prev.sep === '|') prev.sep = '|';
1161
+ }
1162
+ return out;
784
1163
  }
785
1164
 
786
1165
  /**
@@ -1734,12 +2113,11 @@ function readWord(s: string, i: number): [string, number] {
1734
2113
  continue;
1735
2114
  }
1736
2115
  // ANSI-C quoting, the FOURTH transform. `$'-s'` is the word `-s`, and
1737
- // reading the `$` as an ordinary character left the token `$-s`, which
1738
- // fails `isLinkFlag`'s `startsWith('-')` precondition before any flag
1739
- // letter is looked at. Handled here rather than in `isLinkFlag` because
1740
- // it is a QUOTING rule and this is the module's quote reader — and
1741
- // because doing it here also fixes `$'cp'`, where the thing hidden is
1742
- // the VERB and `isLinkFlag` is never consulted at all.
2116
+ // reading the `$` as an ordinary character left the token `$-s`. It is
2117
+ // a QUOTING rule and this is the module's quote reader, so every reader
2118
+ // of a word gets it — `commandWord` for a hidden verb (`$'chmod'`), and
2119
+ // since #1367 the chain property for a hidden path (`rmdir $'\x65sc'`).
2120
+ // It was added for #1411's link-flag reader, which #1367 deleted.
1743
2121
  //
1744
2122
  // A `\'` inside the body is an escaped quote, so the closing quote is
1745
2123
  // found by walking rather than by `indexOf`.
@@ -2228,12 +2606,12 @@ function names(text: string, list: string[]): string | null {
2228
2606
  * the direction a guard should err in and also the common real shape: a
2229
2607
  * command that copies a fixture over a run's state names both.
2230
2608
  */
2231
- function namesOutsideScratch(text: string, list: string[], exempt: boolean): string[] {
2609
+ function namesOutsideScratch(text: string, list: string[], exempt: Exemption): string[] {
2232
2610
  const out: string[] = [];
2233
2611
  for (const p of list) {
2234
2612
  const words = pathWordsContaining(text, p);
2235
2613
  if (words.length === 0) continue;
2236
- if (exempt && words.every(isScratchPath)) continue;
2614
+ if (words.every(exempt)) continue;
2237
2615
  out.push(p);
2238
2616
  }
2239
2617
  return out;
@@ -2259,12 +2637,12 @@ function namesOutsideScratch(text: string, list: string[], exempt: boolean): str
2259
2637
  * keeps its looser reading: that behaviour is pre-existing and measured,
2260
2638
  * and tightening it is not this change's business.
2261
2639
  */
2262
- function absoluteNamesOutsideScratch(text: string, exempt: boolean): string[] {
2640
+ function absoluteNamesOutsideScratch(text: string, exempt: Exemption): string[] {
2263
2641
  const out: string[] = [];
2264
2642
  for (const p of ALL_PROTECTED) {
2265
2643
  const words = pathWordsContaining(text, p).filter(w => w.startsWith('/'));
2266
2644
  if (words.length === 0) continue;
2267
- if (exempt && words.every(isScratchPath)) continue;
2645
+ if (words.every(exempt)) continue;
2268
2646
  out.push(p);
2269
2647
  }
2270
2648
  return out;
@@ -2537,11 +2915,35 @@ export function bodyTargets(body: string): BodyTargets {
2537
2915
  const fragments: string[] = [];
2538
2916
  const protectedLiterals: string[] = [];
2539
2917
  const unplaceable: string[] = [];
2540
- /** Every literal span read so far, so the backward walk can step over one. */
2541
- const spans: [number, number][] = [];
2918
+ const lits = readLiterals(body);
2919
+ // An unterminated literal means every boundary after it is a guess.
2920
+ if (!lits) return { targets: [], fragments: [], protectedLiterals: [], unplaceable: [], unreadable: true };
2921
+ /** Every literal span, so the backward walk can step over one. */
2922
+ const spans: [number, number][] = lits.map(l => [l.start, l.end]);
2542
2923
  // Read once per body rather than once per literal: each call realpaths up
2543
2924
  // to six trees, and a body has as many literals as it likes.
2544
2925
  const live = protectedTrees();
2926
+ for (const { value, start: i, end: j } of lits) {
2927
+ const where = placeLiteral(value, live);
2928
+ if (where === 'protected') protectedLiterals.push(value);
2929
+ if (where === 'unplaceable') unplaceable.push(value);
2930
+ if (ALL_PROTECTED.some(p => value.toLowerCase().includes(p.toLowerCase()))) {
2931
+ const pos = standsAlone(body, i, j) ? inWritePosition(body, i, spans) : UNPROVEN;
2932
+ if (pos === 'destination') targets.push(value);
2933
+ // `argument` is deliberately in neither list — see `inWritePosition`.
2934
+ else if (pos === 'unproven') fragments.push(value);
2935
+ }
2936
+ }
2937
+ return { targets, fragments, protectedLiterals, unplaceable, unreadable: false };
2938
+ }
2939
+
2940
+ /**
2941
+ * The string literals of an interpreter body, with the index of each opening
2942
+ * and closing quote — or `null` when one is never closed (#1367 split this
2943
+ * out of `bodyTargets` so the chain reader uses the same one reader).
2944
+ */
2945
+ function readLiterals(body: string): Array<{ value: string; start: number; end: number }> | null {
2946
+ const out: Array<{ value: string; start: number; end: number }> = [];
2545
2947
  let i = 0;
2546
2948
  while (i < body.length) {
2547
2949
  const q = body[i];
@@ -2570,21 +2972,11 @@ export function bodyTargets(body: string): BodyTargets {
2570
2972
  value += c;
2571
2973
  j++;
2572
2974
  }
2573
- // An unterminated literal means every boundary after it is a guess.
2574
- if (!closed) return { targets: [], fragments: [], protectedLiterals: [], unplaceable: [], unreadable: true };
2575
- spans.push([i, j]);
2576
- const where = placeLiteral(value, live);
2577
- if (where === 'protected') protectedLiterals.push(value);
2578
- if (where === 'unplaceable') unplaceable.push(value);
2579
- if (ALL_PROTECTED.some(p => value.toLowerCase().includes(p.toLowerCase()))) {
2580
- const pos = standsAlone(body, i, j) ? inWritePosition(body, i, spans) : UNPROVEN;
2581
- if (pos === 'destination') targets.push(value);
2582
- // `argument` is deliberately in neither list — see `inWritePosition`.
2583
- else if (pos === 'unproven') fragments.push(value);
2584
- }
2975
+ if (!closed) return null;
2976
+ out.push({ value, start: i, end: j });
2585
2977
  i = j + 1;
2586
2978
  }
2587
- return { targets, fragments, protectedLiterals, unplaceable, unreadable: false };
2979
+ return out;
2588
2980
  }
2589
2981
 
2590
2982
  /**
@@ -2883,12 +3275,12 @@ function standsAlone(body: string, start: number, end: number): boolean {
2883
3275
  * test can tell them apart, and the next reader deletes the live half —
2884
3276
  * `.claude/rules/checks-must-be-able-to-fail.md`, the fourth shape.
2885
3277
  */
2886
- function bodyTargetsAreScratch(body: string): boolean {
3278
+ function bodyTargetsAreScratch(body: string, exempt: Exemption): boolean {
2887
3279
  const { targets, fragments, protectedLiterals, unplaceable, unreadable } = bodyTargets(body);
2888
3280
  if (unreadable || fragments.length > 0) return false;
2889
3281
  if (protectedLiterals.length > 0 || unplaceable.length > 0) return false;
2890
3282
  if (targets.length === 0) return false;
2891
- return targets.every(isScratchPath);
3283
+ return targets.every(exempt);
2892
3284
  }
2893
3285
 
2894
3286
  const ALL_PROTECTED = [...PROTECTED_FILES, ...PROTECTED_HOOKS];
@@ -2902,17 +3294,20 @@ const ALL_PROTECTED = [...PROTECTED_FILES, ...PROTECTED_HOOKS];
2902
3294
  * work around it protects nothing, and four real refusals of read-only work
2903
3295
  * is already a pattern.
2904
3296
  *
2905
- * `exempt` is computed once from the WHOLE command and handed down, rather
2906
- * than recomputed per segment or per recursion. The command that voids the
2907
- * exemption puts the `ln` in one segment and the write in another, so a
2908
- * per-segment answer would never see both.
3297
+ * The scratch exemption is decided per DESTINATION against the WHOLE command
3298
+ * (#1367): the chain context is read once, lazily — most commands name no
3299
+ * protected artifact and never ask — and each step gets a judge that knows
3300
+ * its position and which words are its own. A body this command runs is
3301
+ * decided as a command of its own, inheriting what the enclosing command
3302
+ * made and named before it (`outer`).
2909
3303
  */
2910
- export function decideBashWrite(cmd: string, depth = 0, exemptIn?: boolean): BashWriteDecision {
3304
+ export function decideBashWrite(cmd: string, depth = 0, outer?: () => Outer): BashWriteDecision {
2911
3305
  if (!cmd) return ALLOW;
2912
3306
  // A shell body can contain a shell body. Bounded so a crafted nest costs a
2913
3307
  // fixed amount of work rather than the session.
2914
3308
  if (depth > 3) return ALLOW;
2915
- const exempt = exemptIn ?? !exemptionIsVoid(cmd);
3309
+ let ctx: ChainContext | null = null;
3310
+ const getCtx = (): ChainContext => (ctx ??= chainContext(cmd, outer?.()));
2916
3311
 
2917
3312
  // #1240: a program handed to an interpreter on stdin. `stripHeredocs`
2918
3313
  // deletes the body before every arm below, and arm 3a only reads a body
@@ -2926,17 +3321,18 @@ export function decideBashWrite(cmd: string, depth = 0, exemptIn?: boolean): Bas
2926
3321
  // of a protected artifact. Reading a Python body as shell finds nothing,
2927
3322
  // which is how `python3 <<'PY'` stayed allowed after the shell spellings
2928
3323
  // were closed.
2929
- for (const { shell, program } of interpreterPrograms(cmd)) {
3324
+ for (const [k, { shell, program }] of interpreterPrograms(cmd).entries()) {
2930
3325
  if (shell) {
2931
- const inner = decideBashWrite(program, depth + 1, exempt && !exemptionIsVoid(program));
3326
+ const inner = decideBashWrite(program, depth + 1, () => outerFor(getCtx(), `prog:${k}`, -1));
2932
3327
  if (inner.blocked) return inner;
2933
3328
  continue;
2934
3329
  }
3330
+ const exempt = judgeFor(getCtx, { src: `prog:${k}`, only: new Set(bodyTargets(program).targets) }, -1);
2935
3331
  // #1277: the same target question as arm 3 below. A stdin program is
2936
3332
  // the arm 3 body reached by another route, and it had NO body gate at
2937
3333
  // all — so the `.replace` spelling #1276 closed for `-e` was still open
2938
3334
  // here, in a heredoc, for as long as the stopgap existed.
2939
- const pf = absoluteNamesOutsideScratch(program, exempt && bodyTargetsAreScratch(program)).find(p =>
3335
+ const pf = absoluteNamesOutsideScratch(program, bodyTargetsAreScratch(program, exempt) ? exempt : NO_EXEMPTION).find(p =>
2940
3336
  writesNear(program, p),
2941
3337
  );
2942
3338
  if (pf) {
@@ -2949,7 +3345,12 @@ export function decideBashWrite(cmd: string, depth = 0, exemptIn?: boolean): Bas
2949
3345
  }
2950
3346
  }
2951
3347
 
2952
- for (const seg of segments(cmd)) {
3348
+ const segs = segments(cmd);
3349
+ for (let i = 0; i < segs.length; i++) {
3350
+ const seg = segs[i];
3351
+ // The write's own words are the step's shell words: they are what the
3352
+ // writing verb is handed, not something that runs before it.
3353
+ const exempt = judgeFor(getCtx, { src: `seg:${i}` }, i);
2953
3354
  const bare = dequote(seg); // TARGET view: contents kept
2954
3355
  const code = stripQuoted(seg); // VERB view: quoted spans gone
2955
3356
  const word = commandWord(seg);
@@ -2961,7 +3362,7 @@ export function decideBashWrite(cmd: string, depth = 0, exemptIn?: boolean): Bas
2961
3362
  for (const target of writeTargets(seg, cmd)) {
2962
3363
  // #1175: the target IS a path, so the tree question is asked directly
2963
3364
  // here rather than through `namesOutsideScratch`.
2964
- if (exempt && isScratchPath(target)) continue;
3365
+ if (exempt(target)) continue;
2965
3366
  const pf = names(target, PROTECTED_FILES);
2966
3367
  if (pf) {
2967
3368
  return {
@@ -3007,7 +3408,7 @@ export function decideBashWrite(cmd: string, depth = 0, exemptIn?: boolean): Bas
3007
3408
  if (isInterpreter && isShellWord(word)) {
3008
3409
  const body = shellBody(seg);
3009
3410
  if (body) {
3010
- const inner = decideBashWrite(body, depth + 1, exempt);
3411
+ const inner = decideBashWrite(body, depth + 1, () => outerFor(getCtx(), `seg:${i}`, i));
3011
3412
  if (inner.blocked) return inner;
3012
3413
  }
3013
3414
  }
@@ -3034,8 +3435,17 @@ export function decideBashWrite(cmd: string, depth = 0, exemptIn?: boolean): Bas
3034
3435
  // `find`, whose operands are on the command line, and a shell `-c`
3035
3436
  // body, which arm 3a re-enters as shell. Handing either to a reader of
3036
3437
  // string literals would refuse them for having none.
3438
+ // An interpreter's own words are NOT excused the way a verb's are: the
3439
+ // program can do anything with its arguments and environment before it
3440
+ // writes. Only the body's write targets are the write's own.
3441
+ const body = programBody(seg);
3442
+ const bodyJudge = judgeFor(getCtx, { src: `body:${i}`, only: new Set(bodyTargets(body).targets) }, i);
3037
3443
  const bodyExempt =
3038
- isMutatingFind || isShellWord(word) ? exempt : exempt && bodyTargetsAreScratch(programBody(seg));
3444
+ isMutatingFind || isShellWord(word)
3445
+ ? exempt
3446
+ : bodyTargetsAreScratch(body, bodyJudge)
3447
+ ? bodyJudge
3448
+ : NO_EXEMPTION;
3039
3449
  const candidates = namesOutsideScratch(bare, ALL_PROTECTED, bodyExempt);
3040
3450
  const pf = isMutatingFind
3041
3451
  ? (candidates[0] ?? null)