yadflow 4.10.0 → 4.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/README.md +12 -3
  3. package/bin/commands.mjs +5 -1
  4. package/bin/yad.mjs +109 -15
  5. package/cli/agent-guard-worker.mjs +13 -0
  6. package/cli/agent-guard.mjs +1053 -57
  7. package/cli/agent-rules.mjs +34 -3
  8. package/cli/argv-flags.mjs +2 -2
  9. package/cli/brain/vendor/LICENSE-graphology-library.txt +21 -0
  10. package/cli/brain/vendor/LICENSE-graphology.txt +21 -0
  11. package/cli/brain/vendor/LICENSE-sigma.txt +12 -0
  12. package/cli/brain/vendor/graphology-library.min.js +2 -0
  13. package/cli/brain/vendor/graphology.umd.min.js +2 -0
  14. package/cli/brain/vendor/sigma.min.js +1369 -0
  15. package/cli/brain/view/app.js +382 -0
  16. package/cli/brain/view/index.html +63 -0
  17. package/cli/brain/view/live.css +228 -0
  18. package/cli/brain/view/live.html +110 -0
  19. package/cli/brain/view/live.js +884 -0
  20. package/cli/brain/view/style.css +141 -0
  21. package/cli/brain-about.mjs +206 -0
  22. package/cli/brain-activity.mjs +285 -0
  23. package/cli/brain-skills.mjs +118 -0
  24. package/cli/brain-vendor.mjs +71 -0
  25. package/cli/brain-view.mjs +344 -0
  26. package/cli/brain.mjs +810 -0
  27. package/cli/ci-check.mjs +3 -3
  28. package/cli/doctor.mjs +80 -13
  29. package/cli/epic-state.mjs +93 -1
  30. package/cli/epic.mjs +15 -3
  31. package/cli/errors.mjs +2 -1
  32. package/cli/find-product.mjs +69 -15
  33. package/cli/foundation-publish.mjs +256 -0
  34. package/cli/gate.mjs +29 -3
  35. package/cli/git-read.mjs +38 -0
  36. package/cli/guard-stream.mjs +409 -0
  37. package/cli/hook.mjs +59 -9
  38. package/cli/issues-act.mjs +57 -13
  39. package/cli/issues-write.mjs +19 -6
  40. package/cli/issues.mjs +62 -23
  41. package/cli/lib.mjs +37 -2
  42. package/cli/local-page.mjs +138 -0
  43. package/cli/machine.mjs +1 -1
  44. package/cli/manifest.mjs +50 -0
  45. package/cli/map/view/app.js +712 -0
  46. package/cli/map/view/index.html +50 -0
  47. package/cli/map/view/style.css +142 -0
  48. package/cli/map-view.mjs +186 -0
  49. package/cli/map.mjs +637 -0
  50. package/cli/members.mjs +9 -15
  51. package/cli/next.mjs +1 -1
  52. package/cli/openpr.mjs +2 -2
  53. package/cli/plan.mjs +125 -0
  54. package/cli/platform.mjs +5 -5
  55. package/cli/product-index.mjs +1 -1
  56. package/cli/protection.mjs +32 -0
  57. package/cli/reconcile.mjs +8 -2
  58. package/cli/report.mjs +9 -3
  59. package/cli/reports-dir.mjs +391 -0
  60. package/cli/reports.mjs +65 -0
  61. package/cli/run-checks.mjs +5 -2
  62. package/cli/scan.mjs +1 -1
  63. package/cli/setup.mjs +30 -5
  64. package/cli/standup.mjs +87 -71
  65. package/cli/status.mjs +6 -5
  66. package/cli/test-agents-file.mjs +614 -8
  67. package/cli/test-brain-activity.mjs +753 -0
  68. package/cli/test-brain-view.mjs +381 -0
  69. package/cli/test-brain.mjs +795 -0
  70. package/cli/test-guide.mjs +211 -0
  71. package/cli/test-machine.mjs +59 -0
  72. package/cli/test-map.mjs +615 -0
  73. package/cli/test-reports.mjs +382 -0
  74. package/cli/test-run-checks.mjs +4 -0
  75. package/cli/test-worktree.mjs +24 -3
  76. package/cli/toolbox-connect.mjs +21 -6
  77. package/cli/toolbox.mjs +59 -4
  78. package/cli/update-commit.mjs +101 -9
  79. package/cli/usage.mjs +8 -4
  80. package/package.json +8 -4
  81. package/skills/yad-architecture/SKILL.md +22 -4
  82. package/skills/yad-change/SKILL.md +3 -1
  83. package/skills/yad-change/references/triage.md +2 -0
  84. package/skills/yad-checks/SKILL.md +2 -0
  85. package/skills/yad-checks/references/check-gates.md +8 -5
  86. package/skills/yad-checks/templates/checks/build-test-lint.sh +7 -0
  87. package/skills/yad-checks/templates/checks/install-deps.sh +6 -0
  88. package/skills/yad-checks/templates/checks/package-manager.sh +42 -0
  89. package/skills/yad-checks/templates/github/yad-checks.yml +3 -2
  90. package/skills/yad-checks/templates/gitlab/yad-checks.gitlab-ci.yml +3 -2
  91. package/skills/yad-checks/templates/hooks/yad-activity.mjs +238 -0
  92. package/skills/yad-connect-repos/SKILL.md +14 -0
  93. package/skills/yad-discovery/SKILL.md +11 -0
  94. package/skills/yad-discovery/references/foundation-schema.md +11 -0
  95. package/skills/yad-docs/templates/app/package-lock.json +18 -10
  96. package/skills/yad-docs/templates/app/package.json +6 -1
  97. package/skills/yad-epic/SKILL.md +3 -0
  98. package/skills/yad-epic/references/state-schema.md +35 -1
  99. package/skills/yad-guide/SKILL.md +4 -4
  100. package/skills/yad-implement/SKILL.md +76 -15
  101. package/skills/yad-issues/SKILL.md +2 -1
  102. package/skills/yad-pr-template/templates/checks/pr-template.sh +8 -4
  103. package/skills/yad-pr-template/templates/checks/pr-title.sh +8 -4
  104. package/skills/yad-spec/SKILL.md +19 -0
  105. package/skills/yad-stories/SKILL.md +22 -4
  106. package/skills/yad-stories/references/story-schema.md +1 -1
@@ -12,7 +12,7 @@ import { execFileSync } from 'node:child_process';
12
12
  import fs from 'node:fs';
13
13
  import os from 'node:os';
14
14
  import path from 'node:path';
15
- import { fileURLToPath } from 'node:url';
15
+ import { fileURLToPath, pathToFileURL } from 'node:url';
16
16
 
17
17
  // The #280 guard (cli/test.mjs): printed lines go to stderr while the runner owns stdout.
18
18
  if (process.env.NODE_TEST_CONTEXT) {
@@ -470,7 +470,169 @@ test('the agent guard refuses every human-only yad command and every force push,
470
470
  'sudo -E yad gate approve EP-x analysis',
471
471
  'yarn workspaces foreach -A run yad gate approve EP-x analysis',
472
472
  'yarn workspaces foreach --include web exec yad gate approve EP-x analysis',
473
- ]) assert.equal(agentGuardDecision(cmd).allow, false, cmd);
473
+ // #498, rows 3–7, each run by a real shell (bash 3.2 and zsh 5.9 unless named). Row 3: `$'…'` inside `$(…)`.
474
+ "echo $(echo $'a\\')'; gh pr merge 5\n)", "echo \"$(echo $'a\\')'; gh pr merge 5\n)\"", "x=$(echo $'a\\')'; git push --force\n)",
475
+ // Row 4: a `case` in `"$(…)"` across a newline (zsh runs it).
476
+ 'echo "$(case x in x)\ngh pr merge 5;; esac)"', 'x="$(case x in\nx) gh pr merge 5;; esac)"',
477
+ // Row 5: bash closes a list only after a comma (`{x},-n}` is `x}` and `-n`).
478
+ 'git commit -m {x},-n}', 'git push origin {a},+main}', 'git commit -m {a}{b},-n}',
479
+ // Row 6: a backslash kept in double quotes, re-read by the shell `bash -c` and `eval` start.
480
+ "bash -c \"echo \\'; gh pr merge 5; echo \\'\"", "eval \"echo \\'; gh pr merge 5; echo \\'\"", 'bash -c "gh pr {merge,\\}} 5"',
481
+ "sh -c \"echo \\'; git push --force; echo \\'\"",
482
+ // Row 7: a brace list does not see into `$(…)`, backticks or `${…}`.
483
+ "git commit -m {$(echo '}'),-n}", "git push origin {$(echo '}'),+main}", "git commit -m {`echo '}'`,-n}", 'git commit -m {$(echo \\}),-n}',
484
+ // Rows 3 and 7 together, and row 4's `case` inside a list (zsh).
485
+ "git commit -m {$(echo $'\\')'),-n}", 'git commit -m {$(case x in x) echo a;; esac),-n}',
486
+ // Row 4 with the `case` word quoted, escaped, a `$(…)`, longer than 256 characters, or an `esac` that is only a word (zsh).
487
+ 'echo "$(case "a b" in\n"a b") gh pr merge 5;; esac)"', "echo \"$(case 'a b' in\n*) gh pr merge 5;; esac)\"", 'echo "$(case a\\ b in\n*) gh pr merge 5;; esac)"',
488
+ 'echo "$(case $(echo y) in\n*) gh pr merge 5;; esac)"', `echo "$(case \${y:-${'x'.repeat(300)}} in\n*) gh pr merge 5;; esac)"`,
489
+ 'echo "$(case y in x) echo esac;;\n*) gh pr merge 5;; esac)"',
490
+ // Rows 3 and 4 in an unquoted heredoc's text (zsh).
491
+ "cat <<EOF\n$(echo $'a\\')'; gh pr merge 5\n)\nEOF", 'cat <<EOF\n$(case x in\nx) gh pr merge 5;; esac)\nEOF',
492
+ // Row 6 through a here-string and a piped echo or printf.
493
+ "bash <<< \"echo \\'; gh pr merge 5; echo \\'\"", "echo \"echo \\'; gh pr merge 5; echo \\'\" | bash", "printf '%s\\n' \"echo \\'; gh pr merge 5; echo \\'\" | sh",
494
+ // Review round 2: a `$(…)` in a heredoc's text that the shells end sooner hides nothing after it (zsh), and
495
+ // a chain of `case $(` that once took exponential time is refused at once (bash runs line 1 first).
496
+ "cat <<E\n$(echo $'\\''x) it's $(gh pr merge 5)\nE", `gh pr merge 5\necho $(${' case $('.repeat(40)}`,
497
+ // Each `$(…)` on the line is read to that reading's own end.
498
+ "echo $(echo $'\\')'; gh pr merge 5\n) $(echo $'\\')' x\n)",
499
+ // Review round 5: bash 3.2 honours `$'…'` but reads a `case` as text; zsh honours both. A reading per shell,
500
+ // never one mixed reading (bash runs the first, zsh the heredoc one).
501
+ "echo \"$(case x in x) echo ' ;; esac)\" $(echo $'\\')' ; git push -f) ' ;; esac)\"'", "echo $($'\\'' $(case x in x) esac) $(echo ')') ; git push -f ; ",
502
+ "cat <<E\n$(echo $'\\')' ' $(echo ' ) $(git push -f) ' )\nE\n",
503
+ // Round 6: a `#` comment inside `$(…)` (both shells; zsh only in double quotes), and backticks inside it (bash).
504
+ "echo $( # )'\ngit push -f\n)''", "echo \"$( # )\"'\ngit push -f\n)\"''", "echo $( echo hi # )'\ngit push -f\n)''", "echo $(echo $((1)) # )'\ngit push -f\n)''",
505
+ "echo $(echo `echo )'`\ngit push -f\n)''",
506
+ // Round 7: bash starts a comment only after a blank (`;#` is none to it); the brace shield; `${…}` as a `case` word.
507
+ "echo $(echo $'\\'' ;#) ; git push -f ; echo '\n)'", "echo $(echo $'\\''&#) ; git push -f ; echo '\n)'", "echo $(echo $'\\''&&#) ; gh pr merge 5 ; echo '\n)'",
508
+ "git commit -m {$(echo '{'),-n}", 'git commit -m {$(echo {),-n}', 'git commit -m {`echo {`,-n}', 'echo "$(case ${x:-a b} in\n*) git push -f ;; esac)"',
509
+ // Round 4: a reading that trusts the first reading's quotes past a `$(…)` the shells end elsewhere misses these.
510
+ "echo $(echo $'\\')\"') ' $(echo ' ; git push -f ; echo \"' $'\\')\"') '", "echo $(echo $'\\')\"') ' $(echo ' ; gh pr merge 1 ; echo \"' $'\\')\"') '",
511
+ "echo $(echo $'\\')\"') $(echo $'\\')\"') ' $(echo ' ; git push -f ; echo \"' $'\\')\"') '",
512
+ // #516, each run by a real shell. B2 (bash 3.2): a heredoc's text inside `$(…)` is read as code.
513
+ "x=$(cat <<'E'\n) ; git push -f ; echo '\nE\n)'", "echo \"$(cat <<'E'\n)\" ; git push -f ; echo \"\nE\n)\"", "x=$(cat <<E\n) ; gh pr merge 5 ; echo '\nE\n)'",
514
+ // B2's printed text: bash 3.2 ends the `$(…)` at the heredoc's `)`, so `cat` prints the text before it (the heredoc
515
+ // never ends there), joined to the text after it.
516
+ "eval \"$(cat <<'EOF'\ngit p)ush --force\nEOF\n)\"", "bash -c \"$(cat <<'EOF'\ngit commit -)n -m x\n)EOF\n)\"",
517
+ "bash -c \"$(echo 'eval \"$(cat <<'EOF'\nyad gate )approve EP-x epic\n\nEOF\n)\"')\"",
518
+ // B3, B4 (zsh): a `case` word in backticks; a comment, a newline or a `;` before `in`.
519
+ 'echo "$(case `echo x` in\nx) gh pr merge 5 ;; esac)"', 'echo "$(case x #c\nin\nx) gh pr merge 5 ;; esac)"', 'echo "$(case x #c\n#d\n\nin\nx) gh pr merge 5 ;; esac)"',
520
+ 'echo "$(case x ;in\nx) gh pr merge 5 ;; esac)"',
521
+ // B5 (zsh): `esac` right after `}` or `]]` (and `esac`, `!`, `in`: no line found that main lets through and zsh runs).
522
+ `echo "$(case x in x) { echo '"' ; } esac)" ; git push -f ; echo '"'`, `echo "$(case x in x) [[ '"' ]] esac)" ; git push -f ; echo '"'`,
523
+ // B6 (zsh): `case x { … }`, closed by `}` (anywhere, `echo }` too) or `esac`; a group's `}` inside it closes the group.
524
+ 'echo "$(case x {\nx) git push -f ;; })"', `echo "$(case x { x) echo '"' } )" ; git push -f ; echo '"'`, `echo "$(case x { x) echo '"' ;; esac)" ; git push -f ; echo '"'`,
525
+ // Review round 1: an `in` right at the 4,096-character bound on a `case` word still counts, as on main (zsh runs it).
526
+ `echo "$(case x${' '.repeat(4090)}in x) echo '"' ;; esac)" ; git push -f ; echo '"'`,
527
+ // Review round 2: a `#'` right after a `)` on an earlier line (the `)#` reading) with B2, B3 and B6 after it.
528
+ // Round 3: the same after a `|#'` (the `|#` reading), alone or with `)#'`.
529
+ "[[ a =~ x|#'\n' ]] ; x=$(cat <<'E'\n) ; git push -f ; echo '\nE\n)'", "case a in (x|#'\n') ;; esac ; echo \"$(case x {\nx) git push -f ;; })\"",
530
+ "(echo a)#'\ncase a in (x|#'\n') ;; esac ; echo \"$(case x {\nx) git push -f ;; })\"",
531
+ "(echo a)#'\nx=$(cat <<'E'\n) ; git push -f ; echo '\nE\n)'", "(echo a)#'\necho \"$(case `echo x` in\nx) gh pr merge 5 ;; esac)\"", "(echo a)#'\necho \"$(case x {\nx) git push -f ;; })\"",
532
+ // #498, rows 1, 2, 8: text that reaches a shell (bash 3.2 and zsh 5.9 run each). Row 1: a process substitution
533
+ // as a shell's script or input.
534
+ 'bash <(echo "gh pr merge 5")', 'bash < <(echo "gh pr merge 5")', 'source <(echo "git push --force")', ". <(echo 'gh pr merge 5')",
535
+ 'zsh =(echo "gh pr merge 5")', "bash -s < <(echo 'gh pr merge 5')", "bash -x <(echo 'git commit -n -m x')", "bash <(cat <<'EOF'\ngh pr merge 5\nEOF\n)",
536
+ // Row 2: a `$(…)` whose printed text is known becomes code.
537
+ "bash -c \"$(cat <<'EOF'\ngh pr merge 5\nEOF\n)\"", 'eval "$(echo gh pr merge 5)"', "$(cat <<'EOF'\ngh pr merge 5\nEOF\n)", "bash -c \"$(echo 'true; gh pr merge 5')\"",
538
+ "bash <<< \"$(echo 'true; gh pr merge 5')\"", "bash -c '$(cat <<EOF\ngh pr merge 5\nEOF\n)'", 'bash -c "gh pr $(echo merge) 5"', 'eval "$(printf \'%s\\n\' \'git push --force\')"',
539
+ // Row 8: a file written, then run, by every path a shell finds it by.
540
+ 'echo "gh pr merge 5" > f; bash f', "cat > f.sh <<'EOF'\ngh pr merge 5\nEOF\nbash f.sh", "echo 'gh pr merge 5' > f; cat f | bash", "echo 'gh pr merge 5' > f; bash < f",
541
+ "echo 'gh pr merge 5' > f; chmod +x f; ./f", "echo 'gh pr merge 5' > f; bash -- f", "echo 'gh pr merge 5' > ./f; bash f", "echo 'gh pr merge 5' > f; bash ./f",
542
+ "printf '%s\\n' 'gh pr merge 5' > f; source f", "echo 'git push --force' > f; . ./f", "echo 'gh pr merge 5' &> f; bash f",
543
+ // Appended, through `tee`, and a write that may not run (it must not hide the one before).
544
+ "echo 'true' > f; echo 'gh pr merge 5' >> f; bash f", "echo 'gh pr merge 5' | tee f; bash f", "echo 'gh pr merge 5' > f; false && echo ok > f; bash f",
545
+ // Across rows and across the lines a command carries.
546
+ "echo 'gh pr merge 5' > f; bash <(cat f)", "echo 'gh pr merge 5' > f; bash -c \"$(cat f)\"", "echo 'gh pr merge 5' > f; eval \"$(<f)\"",
547
+ "echo 'gh pr merge 5' > f; bash -c 'bash f'", "echo 'gh pr merge 5' > f; eval bash f", "echo \"echo '\" > f; echo 'gh pr merge 5' > f; bash -c \"$(cat f)\"",
548
+ // The differential test: only `echo`'s leading options are options; zsh writes a pipe to a bare `> f`; a
549
+ // backslash in a printer's name; zsh's `print`.
550
+ 'echo git commit -n -m x > f; bash f', "echo 'gh pr merge 5' | > f; bash f", "bash <<< \"$(ech\\o 'gh pr merge 5')\"", "print 'gh pr merge 5' > f; source f",
551
+ // Review round 1: a file run by a `$(…)`, a loop or a function after the write; `source --`; a `case` in a
552
+ // process substitution; a second one on the same command; `tee` and filters fed by a here-string, a pipe or `<`.
553
+ "echo 'gh pr merge 5' > f; x=$(bash f)", "echo 'gh pr merge 5' > f; echo `bash f`", "for i in 1 2; do bash f; echo 'gh pr merge 5' > f; done",
554
+ "g(){ bash f; }; echo 'gh pr merge 5' > f; g", "echo 'gh pr merge 5' > f; source -- f", "source -- <(echo 'gh pr merge 5')",
555
+ "bash <(case x in x) echo 'gh pr merge 5';; esac)", "bash <( (case x in x) ;; esac); echo 'gh pr merge 5')", "bash < <(echo x) < <(echo 'gh pr merge 5')",
556
+ "tee f <<< 'gh pr merge 5'; bash f", "tee f <<'E'\ngh pr merge 5\nE\nbash f", "echo 'gh pr merge 5' | cat > f; bash f", "echo 'gh pr merge 5' | sort > f; bash f",
557
+ "echo 'gh pr merge 5' > f; cat < f > g; bash g", "echo 'gh pr merge 5' > f; tee g < f; bash g",
558
+ // Texts joined as the shell joins them: a `>>` after a `$(…)` reading, `cat a b`; a guessed shell; `>&f`; a path
559
+ // spelled another way.
560
+ "echo \"$(echo 'gh pr \\')\" > f; echo 'merge 5' >> f; bash f", "echo 'gh pr \\' > a; echo 'merge 5' > b; cat a b | bash",
561
+ "$SHELL <(echo 'gh pr merge 5')", "echo 'gh pr merge 5' >& f; bash f", "echo 'gh pr merge 5' >&f; bash f", "echo 'gh pr merge 5' > d/../f; bash f",
562
+ // Review round 2: a quoted `case` is no reserved word, and one after `then`, `do` or `{` is; a command read
563
+ // from a file past its limits; zsh's `-`, `--` and `print -f`.
564
+ 'bash <(echo gh pr merge 1; "case")', 'bash <(echo gh pr merge 1; \\case)', 'bash <(if :; then case x in x) echo gh pr merge 1;; esac; fi)',
565
+ 'bash <({ case x in x) echo gh pr merge 1;; esac; })', `${Array.from({ length: 70 }, (_, i) => `echo a${i} > f`).join('; ')}; echo gh pr merge 1 > f; $(<f)`,
566
+ 'print -r -- gh pr merge 1 > f; bash f', 'echo - gh pr merge 1 > f; bash f', "print -f '%s %s %s %s\\n' gh pr merge 1 > f; bash f",
567
+ `bash < <(true) ${'-e '.repeat(70)}<(echo gh pr merge 1)`, 'git push origin >&+main', 'git push origin >& --force',
568
+ // Review round 3: an `esac` that is an argument; a file past its limits in an argument.
569
+ 'bash <(case x in y) echo then esac;; x) echo gh pr merge 5;; esac)', "bash <(printf '%b' 'echo hi\\n'; echo gh pr merge 5)",
570
+ "bash <(printf 'echo hi\\012'; printf 'gh pr merge 5')", "bash <(echo -en 'echo hi\\n'; echo gh pr merge 5)",
571
+ `${Array.from({ length: 70 }, (_, i) => `echo t${i} > f`).join('; ')}; echo 'pr merge 5' > f; gh $(<f)`,
572
+ // Review round 4: a held `)` record runs on to the real close; `1>&f` writes f.
573
+ 'bash <(: { case; case y in y) echo gh pr merge 5;; esac)', 'bash <(: { case; case y in y) :;; esac; echo gh pr merge 5)',
574
+ 'bash <(case y in y) { :; } esac; echo gh pr merge 5)', 'echo gh pr merge 5 1>& f; bash f',
575
+ // Review round 5: `printf --` keeps its format; a quote one printed text opens and the next closes; `>& -n`
576
+ // writes the file `-n`.
577
+ "printf -- 'gh pr merge 1\\n' | bash", "bash <(printf -- 'gh pr merge 1')", `{ echo "x='"; echo "'; gh pr merge 1"; } | bash`,
578
+ "echo gh pr merge 1 >& -'n'; bash ./-n", 'echo gh pr merge 1 >& -n; bash ./-n',
579
+ // Review round 6: main's reading of `echo` (every `-n`/`-e` word dropped) is kept beside the shells'.
580
+ 'echo git -c -n core.hooksPath=x commit | bash', 'echo git -c -e core.hooksPath=x commit | zsh',
581
+ // Review round 7: main's reading is judged alone, so the joins still pair the shells' readings.
582
+ `bash -c "$(printf -- 'git commit '; echo - -n)"`,
583
+ // CI review: a `cat` whose file names come from a file read past its limits prints what is not known.
584
+ // A file empty when it is read: the next text stands alone (`printf '' > a` after an open quote).
585
+ `printf '"' > a; printf '' > a; bash <(cat a; printf 'gh pr merge 5')`, `printf '"' > a; printf '' > a; bash -c "$(cat a; printf 'gh pr merge 5')"`,
586
+ `false && printf '"' > a; source <(cat a; printf 'gh pr merge 5')`, `printf 'echo "' "'" > b; source <(cat nofile b; printf 'gh pr merge 5')`,
587
+ // Readings are paired by their place: empty ones from files never written keep theirs.
588
+ ...['bash -c "$(cat e1 e2 a; cat q)"', 'eval "$(cat e1 e2 a; cat q)"', 'source <(cat e1 e2 a; cat q)'].map((t) => `printf '"' > a; printf '' > a; printf 'echo hi\\n' > q; printf 'gh pr merge 5\\n' > q; false && printf 'echo z\\n' > q; ${t}`),
589
+ ...['cat $(cat f) | bash', 'cat $(<f) | bash', 'cat $(cat f) > g; bash g'].map((t) => `bash -c "printf '%s' 'gh pr merge 5' > h"; cat > f <<'E'\nh${' '.repeat(300000)}\nE\n${t}`),
590
+ // #518, PR 1: the word after `>&` / `<&` as bash 3.2 reads it — an unquoted `-` closes the descriptor and the
591
+ // rest is a word of the command — and as zsh reads it — any word but digits, `-` or `p` is a file written.
592
+ 'git commit -m x >&--n', 'git commit -m x >& --n', 'git commit -m x <&--n', 'git commit -m x <& --n', 'git commit -m x 2>&--n', 'git commit -m x 1>&--n',
593
+ 'git commit -m x >&\t--n', 'git commit -m x >&-"-n"', 'git commit -m x >& -"-n"', 'git commit -m x >&-\\-n', 'git push origin >& -+main', 'git push origin >&-+main',
594
+ // Crossed with a brace and a `$(…)` word: bash expands the word that follows the `-`.
595
+ 'git commit -m x >&--{n,x}', 'git commit -m x >&--$(echo n)', 'git commit -m x >& --$(echo n)', 'git push origin >&-{+main,x}',
596
+ 'echo gh pr merge 1 >&--n; bash ./--n', 'echo gh pr merge 1 >&-n; bash ./-n', 'echo gh pr merge 1 >&1--n; bash ./1--n', 'echo gh pr merge 1 >&1-; bash ./1-',
597
+ 'echo gh pr merge 1 >&p; bash ./p', 'echo gh pr merge 1 >&--n; source ./--n',
598
+ // zsh's `>!`, `>>!`, `&>!`, `&>>!`, `>>|`, `>&|` and `>&!` write a file, as `>|` does.
599
+ 'echo gh pr merge 1 >! f; bash f', 'echo gh pr merge 1 >!f; bash f', 'echo gh pr merge 1 >>! f; bash f', 'echo gh pr merge 1 >>| f; bash f',
600
+ 'echo gh pr merge 1 >&| f; bash f', 'echo gh pr merge 1 >&|f; bash f', 'echo gh pr merge 1 >&! f; bash f', 'echo gh pr merge 1 &>! f; bash f',
601
+ 'echo gh pr merge 1 &>>! f; bash f', 'echo gh pr merge 1 1>! f; bash f', 'echo gh pr merge 1 >! "f"; bash f', 'bash -c "echo gh pr merge 1 >! f; bash f"',
602
+ // #518 review 1: main's redirect reading still runs under bash's and zsh's `$(…)` end rules — zsh reads `>|!` as
603
+ // `>|` writing the file `!` — and a blank before a descriptor number, a `\`-newline join, and a `#` right after
604
+ // bash's closing `-` are read too.
605
+ 'echo "$(case x in x)\ngh pr >|! merge 5;; esac)"', 'echo "$(case x in x)\ngh pr &>|! merge 5;; esac)"', 'echo "$(case x in x)\ngit commit -m x >|! -n;; esac)"',
606
+ 'echo gh pr >|! merge 5 >! f; bash f', 'gh pr >& 1 merge 5', 'gh pr 2>& 1 merge 5', 'gh pr >&\t2 merge 5', 'gh pr <& 0 merge 5',
607
+ 'git commit -m x >\\\n&--n', 'git commit -m x >&\\\n--n', "echo x >&-#'\ngh pr merge 5\n#'", "echo x 2>&-#'\ngh pr merge 5\n#'", "echo x >& -#'\ngh pr merge 5\n#'",
608
+ `bash -c "echo x >&-#'\ngh pr merge 5\n#'"`,
609
+ // #518 review 2: what a `$(…)` prints is read by each shell's redirect reading too.
610
+ '$(echo gh >& 1 pr merge 5)', '$(echo gh <& 0 pr merge 5)', '$(echo gh 2>& 1 pr merge 5)', "bash -c '$(echo gh >& 1 pr merge 5)'", 'eval "$(echo gh >& 1 pr merge 5)"',
611
+ "bash <<'E'\n$(echo gh >& 1 pr merge 5)\nE", '$(echo gh pr >& 1- merge 5)', 'echo "$(case x in x)\n$(echo gh >& 1 pr merge 5);; esac)"',
612
+ // #518, PR 2: text printed with no newline runs on into what is printed next — through `>>`, a pipe, a group, a
613
+ // process substitution, `cat` of two files and a `$(…)`; `echo -n`, `print -n` and a `printf` format with no
614
+ // newline at its end.
615
+ "printf 'gh pr ' > f; printf 'merge 1' >> f; bash f", "{ printf 'gh pr '; echo merge 5; } | bash", "bash <(printf 'gh pr '; echo merge 1)", "echo -n 'gh pr ' > f; echo merge 1 >> f; bash f",
616
+ "printf '%s' 'gh pr ' > f; echo merge 1 >> f; bash f", "print -n 'gh pr ' > f; echo merge 1 >> f; zsh f", "printf 'gh pr ' > a; echo merge 5 > b; cat a b | bash", "printf 'gh pr ' > a; echo merge 5 > b; cat a b > c; bash c",
617
+ "{ echo -n gh pr; echo ' merge 5'; } | bash", "{ printf 'git com'; printf 'mit -n -m x'; } | bash", "echo -ne 'gh pr ' > f; echo merge 1 >> f; bash f", "printf -- 'gh pr ' > f; echo merge 1 >> f; bash f",
618
+ "printf 'gh pr ' > f; printf 'mer' >> f; echo 'ge 5' >> f; bash f", "source <(printf 'gh pr '; echo merge 1)", "echo x | { printf 'gh pr '; echo merge 5; } | bash",
619
+ // PR 2 review 1: the readings with no newline are kept apart, never among those paired by place — these two main
620
+ // refused only by its pairs, which readings put among them had moved — and the mark passes through `tee`, `cat`,
621
+ // `< f` and a filter; `printf`'s and `echo`'s escapes are made; an escaped backslash before `n` is no newline.
622
+ "printf x > a; echo y >> a; echo 'gh pr \\' > g; echo q0 > b; echo q1 > b; echo q2 > b; echo q3 > b; echo 'merge 5' > b; echo r0 > b; echo r1 > b; echo r2 > b; echo r3 > b; echo 'merge 5' > b; { cat a g; cat b; } | bash",
623
+ "echo x0 > x; echo x1 > x; echo x2 > x; echo x3 > x; echo x4 > x; echo 'gh pr \\' > g; : > a; printf p > b; echo y >> b; echo z > b; echo 'merge 5' > b; echo r0 > b; echo r1 > b; echo r2 > b; echo 'merge 5' > b; { cat x g a; cat b; } | bash",
624
+ "printf 'gh pr ' | tee f; echo merge 1 >> f; bash f", "printf 'gh pr ' | tee -a f; echo merge 1 >> f; bash f", "printf 'gh pr ' | cat > f; echo merge 1 >> f; bash f",
625
+ "{ printf 'gh pr ' | cat; echo merge 5; } | bash", "printf 'gh pr ' > f; { cat < f; echo merge 5; } | bash", "printf 'gh pr ' > f; cat < f > g; echo merge 5 >> g; bash g",
626
+ "bash <(printf 'gh pr ' | cat; echo merge 1)", "printf 'gh pr ' | tr a a > f; echo merge 5 >> f; bash f", "printf 'gh pr ' | sed s/x/x/ > f; echo merge 5 >> f; bash f",
627
+ "printf 'git push --force\\n' | bash", "{ printf 'git push'; printf ' --force\\n'; } | bash", "source <(printf -- 'git push'; printf ' --force\\n')",
628
+ "printf 'git push' > f; printf ' --force\\n' >> f; printf 'x' >> f; bash f", "{ printf 'git -c a=\\\\n'; echo 'b push --force'; } | bash", "{ echo -e 'gh pr \\c'; echo merge 5; } | bash",
629
+ "{ print -f 'gh pr '; echo merge 5; } | zsh",
630
+ // PR 2 review 2: a word's spellings kept apart stay apart too — main refuses this only by pairing `gh` with the
631
+ // last spelling of the next word — and `\c` before a final `\n` still prints no newline (zsh).
632
+ "printf '%s\\n' 'pr merge 5' > c; printf z0 > a; printf '%s\\n' gh > a; eval $(<a) $(<c)",
633
+ "printf '%s\\n' --force >> c; printf '%s\\n' 'pr merge 5' > a; printf '%s' gh > c; echo $(<c) \"$(cat a)\" | bash",
634
+ "{ printf 'gh pr \\c\\n'; echo merge 5; } | zsh",
635
+ ]) assert.equal(agentGuardDecision(cmd).allow, false, cmd.slice(-40));
474
636
  });
475
637
 
476
638
  test('the agent guard lets the rest through: reads, the agent\'s own pushes, text that only mentions a command', () => {
@@ -578,19 +740,120 @@ test('the agent guard lets the rest through: reads, the agent\'s own pushes, tex
578
740
  'echo x || bash', 'docker ps --format {{.Names}}', 'gh pr view {1,2,3}', 'gh pr {merge\\,x,} 5',
579
741
  `gh api repos/x -f body='[${'{"a":1,"b":2},'.repeat(10)}{}]'`, "echo '{a,b}{a,b}{a,b}{a,b}{a,b}'", 'echo {a,b}{a,b}{a,b}{a,b}{a,b}', 'bash -euo pipefail ./x.sh', 'echo {a..z}',
580
742
  `curl -d '[${'{"a":1,"b":2},'.repeat(66000)}{}]' https://x`,
581
- `git add ${'f.js '.repeat(2000)}src/{a,b}.js`]) {
743
+ `git add ${'f.js '.repeat(2000)}src/{a,b}.js`,
744
+ // #498: the ordinary forms around the new readings stay allowed.
745
+ "echo $(echo $'it\\'s')", "x=$(printf $'a\\tb')", 'echo "$(echo $\'\\\'\')"', 'echo "$(case $x in a) echo a;; esac)"', 'echo "$(echo case)"',
746
+ 'echo {x}', 'gh pr view {x},5}', 'git log {x},y}', "echo {$(echo '}'),x}", 'git log {$(echo a),b}', 'gh api repos/{owner}/{repo}/pulls',
747
+ 'bash -c "echo \\"hi\\""', 'bash -c "echo \\$HOME"', "bash -c \"grep '\\d' f\"", "bash -c \"printf 'a\\nb'\"", "eval \"echo \\'quoted\\'\"", 'grep "\\d+" f',
748
+ 'echo "$(echo test case)"', "echo \"it\\'s\" | cat", 'echo "$(case y in x) echo esac;; esac)"', "cat <<EOF\n$(echo $'it\\'s')\nEOF",
749
+ // The budget counts only a `$(…)` the shells end elsewhere, once per reading: 40 ordinary ones, with a CR too.
750
+ Array(40).fill("x=$(printf $'a\\tb')").join('; '), `${Array(40).fill("x=$(printf $'a\\tb')").join('; ')}\r`,
751
+ // Review round 2: a line read again with `$(:)` is judged at its own depth, and `a|esac)` is a pattern.
752
+ `echo "$(printf $'it\\'s')" "$(printf $'a\\'b')" "$(printf $'c\\'d')"`, 'echo "$(case x in a|esac) echo a;; esac)"',
753
+ // Any number of `$(…)` that a shell ends elsewhere: each reading reads them all in one pass.
754
+ Array.from({ length: 100 }, (_, n) => `echo "$(case x${n} in x${n}) echo esac;; esac)"`).join('\n'), Array(4).fill('echo $(case a in a) echo hi;; esac)').join(' '), Array(100).fill("$(echo $'\\')')").join(' '),
755
+ // #516: a heredoc in `$(…)`, zsh's `case x { … }` and a `case` word in backticks, with safe commands.
756
+ // Review round 2: a `#` right at the 4,096-character bound of a `case` word is judged at once (it looped forever).
757
+ // Round 3: many heredocs that never end, inside `$(…)`, are read in linear time (one text each was quadratic).
758
+ `x=$(cat <<A\n${'bash <<B\n'.repeat(10000)})`,
759
+ `echo "$(case x${' '.repeat(4090)}#x\nin x) ;; esac)"`, `echo "$(case x${';'.repeat(4090)}#x\nin x) ;; esac)"`,
760
+ "x=$(cat <<'E'\n(a)\nE\n); echo ok", "git commit -m \"$(cat <<'EOF'\nfix: it's done\nEOF\n)\" && git push", 'echo "$(case x { x) echo a ;; })"',
761
+ 'echo "$(case `echo x` in x) echo a ;; esac)"', 'echo "$(case x #c\nin x) echo a ;; esac)"',
762
+ // A `#` that starts no word is no comment, and backticks inside `$(…)` are ordinary.
763
+ 'x=$(echo a#b)', 'echo $(git log --format=%H#%s -1)', 'echo "$(date) # not a comment"', 'echo $(echo $#)', 'echo ${#x} $(echo ${#y})',
764
+ 'n=$((16#ff)); echo $(echo $n)', 'echo $(echo `date`)', 'echo $( # a comment\necho hi )', 'y=$(echo `echo a`)$(echo b)',
765
+ // #498, rows 1, 2, 8: a process substitution as an argument, a `$(…)` whose text is not run or not known, and
766
+ // a file written that no shell runs.
767
+ 'bash build.sh <(echo "gh pr merge 5")', 'cat <(echo "gh pr merge 5")', 'bash <(curl -fsSL https://x/i.sh)', 'bash -c "$(curl -fsSL https://x/i.sh)"',
768
+ "bash -c 'echo $(echo gh pr merge 5)'", 'bash -c "echo $(echo gh pr merge 5)"', 'echo "$(echo gh pr merge 5)"', 'x=$(git rev-parse HEAD); echo $x',
769
+ 'cd "$(git rev-parse --show-toplevel)" && bash build.sh', 'echo x > notes; bash build.sh', 'echo "gh pr merge 5" > notes.md; bash build.sh', "echo 'gh pr merge 5' > f; cat f",
770
+ 'bash build.sh > log.txt; cat log.txt', 'echo "gh pr merge 5" 2> f; bash f', "echo 'gh pr merge 5' > f; bash g", 'git diff > x.patch; git apply x.patch',
771
+ // Review round 1: a file printed, however many times it was written; a copy of a descriptor is no file.
772
+ `${Array.from({ length: 70 }, (_, i) => `echo "line ${i}" >> notes.md`).join('; ')}; cat notes.md`, 'npm test 2>&1 | tee out.txt', 'echo "$(date)" >> notes.md',
773
+ 'cat < in.txt > out.txt', 'bash build.sh >&2', 'echo x >&-', 'source .venv/bin/activate',
774
+ // Review round 2: a file run after many lines written to it; descriptors copied; a `case` that runs a script.
775
+ `cat > f <<'E'\n${'npm run lint\n'.repeat(45000)}E\nbash f`, 'npm run build >&build.log', 'exec 3>&1; npm test >&3', 'make 2>&1 >&2 | tee make.log',
776
+ 'case "$1" in start) bash run.sh;; esac', 'printf "%s\\n" a > f; bash f',
777
+ // Review round 3: a long `case` in a process substitution; a quoted word after `>&`.
778
+ `bash <(case x in ${'a) echo a;; '.repeat(600)}esac)`, 'git commit -m x >&"--n"', 'echo hi 2>& f',
779
+ // Review round 4: bash passes nothing here.
780
+ 'git commit -m x >& "-"-n', 'git commit -m x >&1--n', `bash <(${'case y in y) :;; esac; '.repeat(40000)})`,
781
+ // #518, PR 1: the forms around the new readings stay allowed — a descriptor copied, moved or closed, a file
782
+ // written that nothing runs, and words that run nothing in bash or zsh.
783
+ 'npm run build 2>&1 | tee build.log', 'git log >& log.txt', 'git diff >& d.txt; cat d.txt', 'echo x >&2', 'cmd 2>&1 >/dev/null', 'git fetch 2>&- ; git status',
784
+ 'git commit -m x >&-n', 'git commit -m x >&1-', 'git commit -m x 2>&1--n', 'git commit -m x >&p', 'npm test >! out', 'git status >| s.txt', 'npm test >>! out.log',
785
+ 'echo gh pr merge 1 2>&--n; bash ./--n', 'echo gh pr merge 1 2>! f; bash f', 'echo gh pr merge 1 > !f; bash f', 'echo gh pr merge 1 <&--n; bash ./--n',
786
+ 'git commit -m x >&| -n', 'git push origin main >&2',
787
+ // #518 review 1: a blank before the number copies a descriptor as before; a `#` after `>&-` with a blank is text.
788
+ 'make >& 1 | head', 'echo x >& 2', 'npm test 2>& 1 | tail', 'echo x >&- # done', 'echo "$(case x in x) echo a >&2;; esac)"',
789
+ 'x=$(git status >& 1)', 'echo "$(make 2>& 1 | tail)"', 'out=$(npm test >&- 2>&1)',
790
+ // #518, PR 2: a newline printed between them keeps the texts apart; ordinary prompts and files stay allowed.
791
+ "printf 'gh pr \\n' > f; echo merge 1 >> f; bash f", "printf '%s\\n' 'gh pr ' > f; echo merge 1 >> f; bash f", "echo 'gh pr' > f; echo merge 1 >> f; bash f",
792
+ "printf 'building ' ; npm run build", "echo -n 'Password: '; read -s p", "printf 'npm ' > f; echo test >> f; bash f", "{ printf 'a'; echo b; } | cat",
793
+ `${Array.from({ length: 60 }, (_, i) => `printf 'line ${i} ' >> notes.md`).join('; ')}; cat notes.md`,
794
+ // PR 2 review 1: what a `grep -q` is piped is not printed; a script built line by line with `printf` runs.
795
+ "{ printf 'gh pr ' | grep -q x; echo merge 5; } | bash", `printf '#!/bin/sh\\n' > run.sh; ${Array.from({ length: 30 }, (_, i) => `printf 'npm run step${i}\\n' >> run.sh`).join('; ')}; bash run.sh`,
796
+ "printf 'x=1\\n' > env.sh; echo 'echo $x' >> env.sh; bash env.sh"]) {
582
797
  assert.equal(agentGuardDecision(ok).allow, true, ok);
583
798
  }
584
799
  });
585
800
 
586
- test('#492: a line of many heredocs that never end is judged in bounded time; one too long to judge is refused', async () => {
801
+ // A copy of the guard whose deadline a test sets per call (`globalThis.YAD_TEST_BUDGET`, cleared after), with its
802
+ // imports pointing back here (its SHIPPED_CHECKS path points nowhere, which agentGuardDecision never reads).
803
+ async function guardCopy() {
804
+ const dir = path.dirname(fileURLToPath(import.meta.url));
805
+ const src = fs.readFileSync(path.join(dir, 'agent-guard.mjs'), 'utf8')
806
+ .replace('deadline = Date.now() + JUDGE_BUDGET_MS;', 'deadline = Date.now() + (globalThis.YAD_TEST_BUDGET ?? JUDGE_BUDGET_MS);')
807
+ .replace(/from '\.\/([\w-]+\.mjs)'/g, (_, f) => `from ${JSON.stringify(new URL(f, import.meta.url).href)}`);
808
+ assert.ok(src.includes('globalThis.YAD_TEST_BUDGET ?? JUDGE_BUDGET_MS'), 'the budget is set per call in the copy');
809
+ const T = fs.mkdtempSync(path.join(os.tmpdir(), 'yad-guard-copy-'));
810
+ const copy = path.join(T, 'agent-guard.mjs');
811
+ fs.writeFileSync(copy, src);
812
+ const mod = await import(pathToFileURL(copy).href);
813
+ const done = () => { delete globalThis.YAD_TEST_BUDGET; fs.rmSync(T, { recursive: true, force: true }); };
814
+ // A judgement with no deadline: a slow runner takes the real time, and the verdict never depends on it.
815
+ const uncut = (l) => { globalThis.YAD_TEST_BUDGET = Infinity; try { return mod.agentGuardDecision(l); } finally { delete globalThis.YAD_TEST_BUDGET; } };
816
+ return { mod, uncut, done };
817
+ }
818
+
819
+ test('#535 CI: a reading of what a command writes, stopped by the deadline, is refused as out of time, not as too much written', async () => {
820
+ // A slow runner, made on purpose, from the copy whose budget is set per call. Where the deadline lands depends
821
+ // on the machine's speed, so each line is timed with no deadline, then judged again at budgets from a tenth of
822
+ // that time to nearly all of it: every phase the deadline can stop is reached.
823
+ const { mod: slow, done } = await guardCopy();
824
+ try {
825
+ const half = (unit) => unit.repeat(Math.floor(slow.MAX_JUDGED / 2 / unit.length));
826
+ const steps = process.env.NODE_V8_COVERAGE ? [0.1, 0.3, 0.5, 0.7, 0.9] : [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9];
827
+ for (const unit of ['bash -c "$(echo x)";', 'echo x > f; bash f;', 'x=$(echo a > f; bash f);', 'echo $(echo x)', 'bash <(cat <<E\nx\nE\n) ']) {
828
+ const line = half(unit);
829
+ globalThis.YAD_TEST_BUDGET = Infinity;
830
+ const t0 = Date.now();
831
+ assert.equal(slow.agentGuardDecision(line).allow, true, `${unit}: allowed in full time`);
832
+ const full = Date.now() - t0;
833
+ for (const f of steps) {
834
+ globalThis.YAD_TEST_BUDGET = Math.max(1, Math.round(full * f));
835
+ const d = slow.agentGuardDecision(line);
836
+ assert.ok(d.allow || /took too long to judge/.test(d.message), `${unit} at ${globalThis.YAD_TEST_BUDGET} of ${full} ms: ${d.message}`);
837
+ }
838
+ delete globalThis.YAD_TEST_BUDGET;
839
+ }
840
+ } finally { done(); }
841
+ });
842
+
843
+ test('#492: a line of many heredocs that never end is judged in bounded time; one too long to judge is refused', async (t) => {
587
844
  // A coverage run makes this work about seven times slower, which says nothing about the guard, so it is not
588
845
  // timed. The other runs are timed, but a shared CI machine has passed 3 s on work that takes 0.5 s here, so
589
846
  // every limit is 4.5 s: still under the guard's own 5 s cut-off, because a line refused at the cut-off would
590
847
  // otherwise pass this test and hide a slowdown. Nested tails keep 6 s; that case runs into the cut-off inside
591
- // the brace expansion by design.
848
+ // the brace expansion by design. The lines read in full, with their output read too (#535), take about 1.2 s
849
+ // here, and a CI runner has been about four times slower: near the cut-off, which would refuse them. They are
850
+ // judged with no deadline (`uncut`), so the verdict is exact and the time is real, and get `SLOW`: a reading
851
+ // that has turned quadratic takes minutes on such a line, so it still shows.
592
852
  const within = (ms) => (process.env.NODE_V8_COVERAGE ? Infinity : ms);
593
- const { MAX_JUDGED } = await import('./agent-guard.mjs');
853
+ const { MAX_JUDGED, JUDGE_BUDGET_MS } = await import('./agent-guard.mjs');
854
+ const SLOW = JUDGE_BUDGET_MS + 1500;
855
+ const { uncut, done } = await guardCopy();
856
+ t.after(done);
594
857
  const line = `${'cat <<X\n'.repeat(60000)}gh pr merge 5`;
595
858
  const t0 = Date.now();
596
859
  assert.equal(agentGuardDecision(line).allow, false);
@@ -627,19 +890,120 @@ test('#492: a line of many heredocs that never end is judged in bounded time; on
627
890
  for (const [unit, tail] of [['$()', '$()'], ['$(a) ', '$(a) '], [':<<<x;', 'sh;'], [':<<E\nE\n', 'sh;']]) {
628
891
  const l = unit.repeat(Math.floor(495000 / unit.length)) + tail.repeat(Math.floor(495000 / tail.length));
629
892
  const t5 = Date.now();
630
- agentGuardDecision(l);
631
- assert.ok(Date.now() - t5 < within(4500), `${JSON.stringify(unit)} took ${Date.now() - t5} ms`);
893
+ uncut(l);
894
+ assert.ok(Date.now() - t5 < within(SLOW), `${JSON.stringify(unit)} took ${Date.now() - t5} ms`);
632
895
  }
633
896
  let inSub = 'echo $(';
634
897
  for (let i = 0; i < 10000; i++) inSub += `<<B${i}\n`;
635
898
  const t2 = Date.now();
636
899
  agentGuardDecision(`${inSub})`);
637
900
  assert.ok(Date.now() - t2 < within(4500), `inside $( took ${Date.now() - t2} ms`);
901
+ // #498: each shell's reading of `$(…)` is one pass, and bash's brace rule is bounded per word.
902
+ for (const unit of ["$(echo $'a\\'", '$(case x in x) ', "\"$(case x in x)\n", `{x}${'{x}'.repeat(50)},y `, 'echo "$(case $(', ' case $(', ' case ${', '(case ${', " case '"]) {
903
+ const l = unit.repeat(Math.floor((MAX_JUDGED - 100) / unit.length)) + ' gh pr merge 5';
904
+ const t8 = Date.now();
905
+ agentGuardDecision(l);
906
+ assert.ok(Date.now() - t8 < within(4500), `#498 ${JSON.stringify(unit.slice(0, 12))} took ${Date.now() - t8} ms`);
907
+ }
908
+ // #498, rows 1, 2, 8: each new path is linear; a file run again after each of many appends is refused at its bound.
909
+ // Half the cap (#498 CI): a shared runner has run two to four times slower than a laptop. The trade-off: a path
910
+ // that scans every earlier part costs a quarter as much at half the length, so a mild one may only show near
911
+ // the limit. Judged with no deadline, so every run checks each verdict.
912
+ const half = (unit) => unit.repeat(Math.floor(MAX_JUDGED / 2 / unit.length));
913
+ for (const unit of ['bash <(echo x) ', 'bash <(', 'echo x > f; bash f;', 'echo x >> f; ', 'printf x >> f; ', 'x=$(echo a > f; bash f);', 'bash -c "$(echo x)";', 'echo $(echo x)', 'bash <(cat <<E\nx\nE\n) ', 'x <<< "$(echo a b)" ', '$(<f)']) {
914
+ const l = half(unit);
915
+ const t10 = Date.now();
916
+ const d = uncut(l);
917
+ assert.ok(d.allow, `${unit}: ${d.message}`);
918
+ assert.ok(Date.now() - t10 < within(SLOW), `#498 ${JSON.stringify(unit)} took ${Date.now() - t10} ms`);
919
+ }
920
+ for (const unit of ['echo x >> f; bash f;', 'echo x | tee -a f; cat f | bash;', 'echo x > f; echo "$(cat f)$(cat f)" > f; cat f | bash;']) {
921
+ const l = half(unit);
922
+ const t11 = Date.now();
923
+ // Refused at its bound, or on a runner slow enough to need it at the 5 s cut-off (CI's Node 20 reached the
924
+ // bound in 4.7 s). Either way within the guard's own budget, with slack: a missing deadline check still shows.
925
+ const m = agentGuardDecision(l).message;
926
+ const ms = Date.now() - t11;
927
+ assert.ok(/runs files it writes too many times|took too long/.test(m ?? ''), `${unit}: ${m}`);
928
+ assert.ok(ms < within(JUDGE_BUDGET_MS + 1500), `#498 ${JSON.stringify(unit)} took ${ms} ms`);
929
+ }
930
+ const echoes = uncut(`echo ${'$(echo x)'.repeat(100000)}`);
931
+ assert.ok(echoes.allow, echoes.message);
932
+ // CI review: many file names from a `$(…)`, each read joined to a long text, ran out of memory before the cut-off.
933
+ for (const n of [60000, 150000]) {
934
+ const t14 = Date.now();
935
+ agentGuardDecision(`cat > f <<'E'\nh ${'a '.repeat(n)}\nE\ncat $(cat f) | bash`);
936
+ assert.ok(Date.now() - t14 < within(4500), `#498 cat $(cat f) with ${n} names took ${Date.now() - t14} ms`);
937
+ }
938
+ // Review round 3: many files to one `cat`, many `>&f`, many parts in one process substitution stay linear.
939
+ for (const l of [`echo -n a>f;cat ${'f '.repeat(490000)};gh pr merge 5`, `cat ${'x '.repeat(490000)};gh pr merge 5`, `echo hi ${'>&f '.repeat(245000)}`, `bash <(${'echo a;'.repeat(140000)})`]) {
940
+ const t13 = Date.now();
941
+ uncut(l);
942
+ assert.ok(Date.now() - t13 < within(SLOW), `#498 ${JSON.stringify(l.slice(0, 20))} took ${Date.now() - t13} ms`);
943
+ }
944
+ // From here on, each check expects one exact verdict: an allow, or a refusal for a named reason. The guard's own
945
+ // 5 s cut-off would turn any of them into "took too long" on a slow enough runner: the coverage leg runs the
946
+ // near-limit `case` line in about 1.8 s on a laptop, and a CI runner has been about four times slower. So
947
+ // `exact` always runs the real guard, and on every run but coverage its verdict is the one checked, and the long
948
+ // lines are timed against the real budget (4.5 s, under the 5 s cut-off). Under coverage (not timed) the real guard still runs, so
949
+ // its lines are counted, and the verdict checked is the copy's with no deadline (`uncut`), which never depends
950
+ // on the runner's speed.
951
+ const exact = (l) => { const real = agentGuardDecision(l); return process.env.NODE_V8_COVERAGE ? uncut(l) : real; };
952
+ // Review round 1: nested process substitutions are refused past their bound, not read in quadratic time.
953
+ for (const d of [4000, 16000]) {
954
+ const t12 = Date.now();
955
+ assert.match(exact(`${'bash <('.repeat(d)}echo hi${')'.repeat(d)}`).message, /too many process substitutions/);
956
+ assert.ok(Date.now() - t12 < within(4500), `#498 nested <( took ${Date.now() - t12} ms`);
957
+ }
958
+ assert.equal(exact(Array(60).fill("echo 'echo hi' >> f").join('; ') + '; bash f').allow, true);
959
+ // #498 review round 7: each budget refuses past its limit, and a line well under it stays allowed.
960
+ const t15 = Date.now();
961
+ assert.match(exact(`echo $(${' case ${'.repeat(120000)})`).message, /too many `case` words/);
962
+ assert.ok(Date.now() - t15 < within(4500), `#498 many case words took ${Date.now() - t15} ms`);
963
+ // Near the limit: 240 `case` words of 4,000 characters read about 960,000 of the 1,048,576 allowed. The line
964
+ // must also stay under MAX_JUDGED, or it is refused as too long rather than for its words.
965
+ const nearCase = `echo $(${` case ${'x'.repeat(4000)} in x) :;; esac;`.repeat(240)})`;
966
+ assert.ok(nearCase.length < MAX_JUDGED, `the near-limit line is ${nearCase.length} characters`);
967
+ const t16 = Date.now();
968
+ const near = exact(nearCase);
969
+ assert.equal(near.allow, true, near.message);
970
+ assert.ok(Date.now() - t16 < within(4500), `#498 near-limit case words took ${Date.now() - t16} ms`);
971
+ assert.match(exact(`echo ${'{x}'.repeat(1300)},y`).message, /brace lists expand to too many words/);
972
+ assert.equal(exact(`echo ${'{x}'.repeat(150)},y`).allow, true);
973
+ // #498 review: the kept spelling of a long double-quoted word with many backslashes is built in one pass.
974
+ const n = Math.floor((MAX_JUDGED - 100) / 2);
975
+ for (const [l, allow] of [[`bash -c "${'\\x'.repeat(n)}; gh pr merge 5"`, false], [`echo "${'\\x'.repeat(n)}"`, true]]) {
976
+ const t9 = Date.now();
977
+ assert.equal(exact(l).allow, allow, l.slice(0, 20));
978
+ assert.ok(Date.now() - t9 < within(4500), `#498 kept backslashes took ${Date.now() - t9} ms`);
979
+ }
638
980
  const long = agentGuardDecision(`echo ${'x'.repeat(MAX_JUDGED)}`);
639
981
  assert.equal(long.allow, false);
640
982
  assert.match(long.message, /too long to judge/);
641
983
  });
642
984
 
985
+ test('#518: a long line the bash and zsh readings are added for is judged in bounded time', () => {
986
+ const within = (ms) => (process.env.NODE_V8_COVERAGE ? Infinity : ms);
987
+ for (const line of [`${'npm run lint >&- ; '.repeat(40000)}gh pr view 1`, `${'echo x >! f; '.repeat(40000)}bash f`, `cat > f <<'E'\n${'npm run lint\n'.repeat(45000)}E\nbash f >&-`]) {
988
+ const t0 = Date.now();
989
+ agentGuardDecision(line);
990
+ assert.ok(Date.now() - t0 < within(4500), `took ${Date.now() - t0} ms: ${line.slice(0, 30)}`);
991
+ }
992
+ assert.equal(agentGuardDecision(`${'npm run lint >&- ; '.repeat(40000)}git commit -m x >&--n`).allow, false);
993
+ // PR 2: joins with no newline stay linear — a long run of `>>` after `printf`, and `cat` of many files.
994
+ for (const line of [`${Array.from({ length: 3000 }, (_, i) => `printf 'a${i} ' >> f`).join('; ')}; bash f`, `printf 'x ' > a; ${'cat a a a a a a a a a a | '.repeat(1)}cat ${'a '.repeat(20000)}| bash`]) {
995
+ const t2 = Date.now();
996
+ agentGuardDecision(line);
997
+ assert.ok(Date.now() - t2 < within(4500), `took ${Date.now() - t2} ms: ${line.slice(0, 30)}`);
998
+ }
999
+ // Review 2: a `$(…)` inside a `$(…)` keeps its reading's shell, so nesting does not multiply the readings.
1000
+ const nest = (n) => (n ? `$(echo a >&p >& 1 >&|q ${nest(n - 1)})` : 'x');
1001
+ const nested = Array(20).fill(`echo ${nest(3)}`).join('; ');
1002
+ const t1 = Date.now();
1003
+ assert.equal(agentGuardDecision(nested).allow, true);
1004
+ assert.ok(Date.now() - t1 < within(4500), `nested took ${Date.now() - t1} ms`);
1005
+ });
1006
+
643
1007
  test('the refusal says what to do instead: the person runs it', () => {
644
1008
  const v = agentGuardDecision('yad gate approve EP-a epic');
645
1009
  assert.match(v.message, /`yad gate approve`/);
@@ -694,6 +1058,45 @@ test('hooks/agent-guard.mjs: Claude Code reads the exit code, Cursor a JSON verd
694
1058
  } finally { fs.rmSync(T, { recursive: true, force: true }); }
695
1059
  });
696
1060
 
1061
+ test('#498: yad hook agent-guard judges in a worker; one that runs out of memory, out of time, or into an error refuses', async () => {
1062
+ const { judgeInWorker } = await import('./hook.mjs');
1063
+ const yadBin = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'bin', 'yad.mjs');
1064
+ const ok = await judgeInWorker('npm test', null);
1065
+ assert.equal(ok.verdict.allow, true, JSON.stringify(ok));
1066
+ const no = await judgeInWorker('gh pr merge 5', null);
1067
+ assert.match(no.verdict.message, /approving or merging/);
1068
+ // A worker with almost no memory, or no time, does not answer: the line is refused, never allowed.
1069
+ const big = `echo ${'$(echo x) '.repeat(60000)}`;
1070
+ const oom = await judgeInWorker(big, null, { heapMb: 16 }); // 1-2 MB aborts Node itself, before the worker starts
1071
+ assert.equal(oom.verdict.allow, false, JSON.stringify(oom.verdict));
1072
+ assert.match(oom.verdict.message, /could not be judged/);
1073
+ const slow = await judgeInWorker(big, null, { wallMs: 1 });
1074
+ assert.equal(slow.verdict.allow, false, JSON.stringify(slow.verdict));
1075
+ assert.match(slow.verdict.message, /could not be judged \(no answer/);
1076
+ // The real hook: a refusal is exit 2, and a read-only line is still pre-approved from the worker.
1077
+ const hook = (command) => spawnSync(process.execPath, [yadBin, 'hook', 'agent-guard'], { input: JSON.stringify({ hook_event_name: 'PreToolUse', tool_name: 'Bash', tool_input: { command } }), encoding: 'utf8', env: { ...process.env, CLAUDE_PROJECT_DIR: os.tmpdir(), YAD_HOOK_DISABLE: '' }, cwd: os.tmpdir() });
1078
+ assert.equal(hook('gh pr merge 5').status, 2);
1079
+ assert.match(hook('git status').stdout, /pre-approved/);
1080
+ // Out of time after the verdict: an allowed line stays allowed, only not pre-approved. This line's verdict
1081
+ // takes about 0.2 s on a laptop, its pre-approval about 6.5 s. Under coverage the verdict may be late too.
1082
+ const longRead = 'git status 2>&1; '.repeat(Math.floor(990_000 / 17));
1083
+ const late = await judgeInWorker(longRead, { root: os.tmpdir(), cwd: os.tmpdir() }, { wallMs: 3000 });
1084
+ assert.equal(late.pre, null, JSON.stringify(late.pre));
1085
+ if (!process.env.NODE_V8_COVERAGE) assert.equal(late.verdict.allow, true, late.verdict.message);
1086
+ });
1087
+
1088
+ test('#498: a named pipe where a shipped check should be is not read, so pre-approval never blocks the hook', { skip: process.platform === 'win32', timeout: 20_000 }, async () => {
1089
+ const { agentGuardPreapproval } = await import('./agent-guard.mjs');
1090
+ const T = fs.mkdtempSync(path.join(os.tmpdir(), 'yad-fifo-'));
1091
+ try {
1092
+ fs.mkdirSync(path.join(T, 'checks'));
1093
+ execFileSync('mkfifo', [path.join(T, 'checks', 'spec-link.sh')]);
1094
+ const t = Date.now();
1095
+ assert.equal(agentGuardPreapproval('bash checks/spec-link.sh', { cwd: T, root: T }).preapproved, false);
1096
+ assert.ok(Date.now() - t < 2000);
1097
+ } finally { fs.rmSync(T, { recursive: true, force: true }); }
1098
+ });
1099
+
697
1100
  test('the hooks read a payload that arrives late or in pieces, retry a pipe that is not ready (EAGAIN), and never lose a verdict at exit', async () => {
698
1101
  const { readStdin } = await import('./hook.mjs');
699
1102
  // EAGAIN twice, then data in two pieces, then the end: all of it, once.
@@ -1358,3 +1761,206 @@ test('E167: nothing that creates, prints or changes a secret, token or variable
1358
1761
  assert.match(PREAPPROVED.never, /secrets, tokens, variables/);
1359
1762
  } finally { fs.rmSync(T, { recursive: true, force: true }); }
1360
1763
  });
1764
+
1765
+ // #532: output readings stay separate from the historical positional readings.
1766
+ const outputGaps = [
1767
+ '{ echo gh pr merge 5; } > f; bash f',
1768
+ '( echo gh pr merge 5 ) > f; bash f',
1769
+ '{ echo gh pr merge 5; } >! f; zsh f',
1770
+ '{ echo gh pr merge 5; } | tee f; bash f',
1771
+ "echo echo 'gh pr merge 5' | bash > g; bash g",
1772
+ "echo 'echo gh pr merge 5' > f; eval \"$(<f)\" > g; bash g",
1773
+ '$(echo $(echo gh >& 1 pr merge 5))',
1774
+ "printf 'gh pr ' | cat - <(echo merge 5) | bash",
1775
+ "{ printf '%s ' gh pr; echo merge 5; } | bash",
1776
+ "printf 'gh pr ' > a; printf '%s\\n' 'merge 5' >> a; bash a",
1777
+ "{ printf '%b\\n' 'gh pr \\c'; echo merge 5; } | bash",
1778
+ "printf '\\x67h pr merge 5\\n' | bash",
1779
+ "printf 'git push \\055-force\\n' | bash",
1780
+ "{ printf 'gh pr\\n' | tr -d '\\n'; echo ' merge 5'; } | bash",
1781
+ "{ printf 'gh prX' | head -c 5; echo ' merge 5'; } | bash",
1782
+ ];
1783
+ test('#532: every reported output gap is refused, while text only printed stays allowed', () => {
1784
+ for (const line of outputGaps) assert.equal(agentGuardDecision(line).allow, false, line);
1785
+ for (const line of ["printf '%s ' gh pr merge 5", '{ echo gh pr merge 5; } > f',
1786
+ "printf '\\x67h pr merge 5\\n'", "{ printf '%s ' echo; echo hello; } | bash",
1787
+ "printf 'echo ' > a; printf '%s\\n' hello >> a; bash a"]) {
1788
+ assert.equal(agentGuardDecision(line).allow, true, line);
1789
+ }
1790
+ });
1791
+
1792
+ test('#532 review 1: a group record never changes what main reads a part writes', () => {
1793
+ // The `}` part's write list was shared with the group record, so a later redirect-only part (`> g`) was added
1794
+ // to main's own reading of `{ :; } > f`, and `g` read as emptied by it: a refusal main makes was lost.
1795
+ assert.deepEqual(shellParts('{ :; } > f; > g').writes.map((w) => w && w.map((x) => x.target)), [null, ['f']]);
1796
+ assert.equal(agentGuardDecision("printf 'gh pr ' > g; { :; } > f; false && > g; echo merge 5 >> g; bash g").allow, false);
1797
+ // A redirect-only part writes a subshell's output only straight after its `)`; later ones are other commands.
1798
+ for (const line of ['( echo gh pr merge 5 ); > f; bash f', '{ echo gh pr merge 5; }; > f; bash f',
1799
+ '( echo gh pr merge 5 ) && > f; bash f']) assert.equal(agentGuardDecision(line).allow, true, line);
1800
+ for (const line of ['( echo gh pr merge 5 ) > f; bash f', '( ( echo gh pr merge 5 ) > f ); bash f'])
1801
+ assert.equal(agentGuardDecision(line).allow, false, line);
1802
+ });
1803
+
1804
+ test('#532 review: lines main allows stay allowed (group writes, process substitutions, long text)', () => {
1805
+ // A part that writes to a file adds nothing to its group's output (review 9).
1806
+ for (const line of ['{ echo gh pr merge 5 > g; echo hi; } > f; bash f', '( echo gh pr merge 5 > g ) > f; bash f'])
1807
+ assert.equal(agentGuardDecision(line).allow, true, line);
1808
+ // Process substitutions are not nesting levels; main bounds them with its own walk (review 10).
1809
+ assert.equal(agentGuardDecision('cat <(cat <(cat <(cat <(echo hi))))').allow, true);
1810
+ assert.equal(agentGuardDecision('cat <(cat <(cat <(cat <(echo gh pr merge 5)))) | bash').allow, false);
1811
+ // The output pass has its own text budget: a long message through a few `tee` stages (review 11).
1812
+ const msg = 'fix: a line of text for the body\n'.repeat(27000);
1813
+ assert.equal(agentGuardDecision(`printf '%s' '${msg}' | ${'tee -a log | '.repeat(8)}git commit -F -`).allow, true);
1814
+ });
1815
+
1816
+ // Lines review 1 found that a real bash 3.2 or zsh 5.9 runs and the output pass let through (main did too).
1817
+ const outputGapsReview = [
1818
+ // zsh's `echo` always makes escapes; double quotes keep the backslash (review 2).
1819
+ "echo '\\x67h pr merge 5' | bash", "{ echo '\\0147h pr merge 5'; } | zsh", 'echo "\\x67h pr merge 5" | zsh',
1820
+ // zsh's `print` options (review 3).
1821
+ "{ print -r -- 'gh pr merge 5'; } > f; zsh f", "{ print -f '%s ' gh pr; print merge 5; } | zsh",
1822
+ "print -l 'gh pr merge 5' | bash",
1823
+ // A write that may not run hides no text before it (review 4).
1824
+ '{ echo gh pr merge 5; } > f; false && echo hi > f; bash f', '( echo gh pr merge 5 ) > f; [ -e g ] && : > f; bash f',
1825
+ // A format reads `\NNN` (review 5), and its other conversions.
1826
+ "printf 'gh pr merge\\0405\\n' | bash", "printf '%c%c pr merge 5\\n' gx hx | bash", "printf '%.2s pr merge 5\\n' ghx | bash",
1827
+ // A process substitution a shell runs (review 6).
1828
+ "bash <(printf '\\x67h pr merge 5\\n')", "source <(printf '\\x67h pr merge 5\\n')", "bash < <(printf '\\x67h pr merge 5\\n')",
1829
+ "zsh =(printf '\\x67h pr merge 5\\n')", "bash <(echo '{ echo gh pr merge 5; } > f; bash f')",
1830
+ // Compound commands' output (review 7).
1831
+ 'if true; then echo gh pr merge 5; fi > f; bash f', 'for x in 1; do echo gh pr merge 5; done > f; bash f',
1832
+ 'while false; do :; done; { if true; then echo gh pr merge 5; fi; } | bash',
1833
+ // Filters, as the shell spells their words (review 8).
1834
+ "{ printf 'gh pr\\n' | tr -d \"\\n\"; echo ' merge 5'; } | bash", "{ printf 'gh pr\\r\\n' | tr -d '\\r\\n'; echo ' merge 5'; } | bash",
1835
+ "{ printf 'gh pr\\n' | tr '\\n' ' '; echo merge 5; } | bash", "{ printf 'gh pr\\n' | head --bytes=5; echo ' merge 5'; } | bash",
1836
+ ];
1837
+
1838
+ test('#532 review: the twins of the output gaps are refused, and text only printed stays allowed', () => {
1839
+ for (const line of outputGapsReview) assert.equal(agentGuardDecision(line).allow, false, line);
1840
+ // bash reads `\0053` in a format as `\005` and `3`: a plain push, not `+main` (a wrong refusal before).
1841
+ for (const line of ["printf 'git push origin \\0053main\\n' | bash", "echo '\\x67h pr merge 5'",
1842
+ "print -r 'gh pr merge 5'", "printf -v x '%s' 'gh pr merge 5'; echo done | bash", 'if true; then echo gh pr merge 5; fi',
1843
+ "bash script.sh <(echo gh pr merge 5)", "{ printf 'gh pr\\n' | tr a-z A-Z; } | bash"]) {
1844
+ assert.equal(agentGuardDecision(line).allow, true, line);
1845
+ }
1846
+ });
1847
+
1848
+ // No time limit under coverage, as in the other timing tests.
1849
+ const withinTime = (ms) => (process.env.NODE_V8_COVERAGE ? Infinity : ms);
1850
+
1851
+ // Lines review 2 found that a real bash 3.2 or zsh 5.9 runs, and the output pass let through.
1852
+ const outputGapsReview2 = [
1853
+ // A file name with a backslash the shell keeps in double quotes is the file its redirect wrote (R1).
1854
+ `{ printf 'gh pr '; echo merge 5; } > "a\\b"; bash "a\\b"`, `{ printf 'gh pr '; echo merge 5; } > "a\\b"; source "a\\b"`,
1855
+ // Each text a file may hold is run on its own: an open quote in one hides no other (R2).
1856
+ `echo "echo '" > f; test -n "$X" || { printf 'gh pr '; echo merge 5; } > f; bash f`,
1857
+ // Compound commands after a reserved word, nested, and a `case` pattern spelled like a closer (R3).
1858
+ "{ if true; then printf 'gh '; fi; printf 'pr '; } > f; echo merge 5 >> f; bash f",
1859
+ "if true; then while false; do :; done; printf 'gh '; printf 'pr '; fi > f; echo merge 5 >> f; bash f",
1860
+ "for i in 1; do for j in 1; do :; done; printf 'gh '; printf 'pr '; done > f; echo merge 5 >> f; bash f",
1861
+ "time for i in 1; do printf 'gh '; printf 'pr '; done > f; echo merge 5 >> f; bash f",
1862
+ "! for i in 1; do printf 'gh '; printf 'pr '; done > f; echo merge 5 >> f; bash f",
1863
+ "case x in x) printf 'gh pr ' ;; done) : ;; esac > f; echo merge 5 >> f; bash f",
1864
+ // A redirect after a process substitution, and `print` options with their value attached.
1865
+ "cat <(printf 'gh pr ') > f; echo merge 5 >> f; bash f", 'print -u1 gh pr merge 5 | zsh', `print -f"%s " gh pr merge 5 | zsh`,
1866
+ ];
1867
+
1868
+ test('#532 review 2: holes the round-1 fixes opened are closed, and lines that run nothing stay allowed', () => {
1869
+ for (const line of outputGapsReview2) assert.equal(agentGuardDecision(line).allow, false, line);
1870
+ // A file written past 64 texts is refused only when it is read (B1); only the command word is the shell that
1871
+ // runs a process substitution, and `bash x < <(…)` runs `x` (B2).
1872
+ for (const line of [Array.from({ length: 65 }, (_, i) => `echo ${i} > out.txt`).join('; '),
1873
+ "ls . <(printf 'gh pr '; echo merge 5)", "grep -n sh <(printf 'gh pr '; echo merge 5)",
1874
+ "bash x < <(printf 'gh pr '; echo merge 5)", 'print -u2 gh pr merge 5 | zsh']) {
1875
+ assert.equal(agentGuardDecision(line).allow, true, line);
1876
+ }
1877
+ assert.equal(agentGuardDecision(`${Array.from({ length: 65 }, (_, i) => `echo ${i} > f`).join('; ')}; bash f`).allow, false);
1878
+ // A deep nest of process substitutions is refused at once, with the process substitution message (B3).
1879
+ const t = Date.now();
1880
+ const deep = agentGuardDecision(`${'cat <('.repeat(1500)}echo hi${')'.repeat(1500)}`);
1881
+ assert.equal(deep.allow, false);
1882
+ assert.match(deep.message, /process substitutions/);
1883
+ assert.ok(Date.now() - t < withinTime(2000), `took ${Date.now() - t} ms`);
1884
+ });
1885
+
1886
+ test('#532 review 3: a shell passes its stdin to the text it runs, and an unclosed or missed group keeps its output', () => {
1887
+ for (const line of ["bash -c bash < <(echo 'gh pr merge 5')", "zsh -c zsh < <(echo 'gh pr merge 5')",
1888
+ "bash -c 'cat | bash' < <(echo 'gh pr merge 5')", "echo bash > x; bash x < <(echo 'gh pr merge 5')",
1889
+ "for i in 1; do { printf 'gh pr '; } done > f; echo merge 5 >> f; bash f",
1890
+ "if true; then 'fi'; printf 'gh pr '; fi > f; echo merge 5 >> f; bash f",
1891
+ "case x in x) printf 'gh pr ' ;; while) : ;; esac > f; echo merge 5 >> f; bash f"]) {
1892
+ assert.equal(agentGuardDecision(line).allow, false, line);
1893
+ }
1894
+ for (const line of ["bash x < <(echo 'gh pr merge 5')", "bash -c 'echo hi' < <(echo 'gh pr merge 5')",
1895
+ "bash -c cat < <(echo 'gh pr merge 5')", 'if true; then '.repeat(100) + 'echo hi' + '; fi'.repeat(100)]) {
1896
+ assert.equal(agentGuardDecision(line).allow, true, line.slice(0, 80));
1897
+ }
1898
+ // A closed group is read once by the groups around it: deep nests cost their size (review 4).
1899
+ for (const open of ['if true; then ', 'for i in 1; do ']) {
1900
+ const t = Date.now();
1901
+ const v = agentGuardDecision(open.repeat(10000) + 'echo hi' + (open.startsWith('if') ? '; fi' : '; done').repeat(10000));
1902
+ assert.equal(v.allow, true, open);
1903
+ assert.ok(Date.now() - t < withinTime(1500), `${open} took ${Date.now() - t} ms`);
1904
+ }
1905
+ const t = Date.now();
1906
+ assert.equal(agentGuardDecision('if true; then '.repeat(80) + 'echo a;'.repeat(10000) + '; fi'.repeat(80)).allow, true);
1907
+ assert.ok(Date.now() - t < withinTime(1500), `took ${Date.now() - t} ms`);
1908
+ });
1909
+
1910
+ test('#532 review 4: inside a case, a one-word `if` may start a real block, and a lone pattern prints nothing', () => {
1911
+ for (const line of ["case x in x)\nif\ntrue; then printf 'gh pr '; fi > f;; esac; echo merge 5 >> f; bash f",
1912
+ "case x in x) if\ntrue; then printf 'gh pr '; fi > f;; esac; echo merge 5 >> f; bash f",
1913
+ "case x in x)\nif\ntrue\nthen\nprintf 'gh pr '\nfi > f\n;;\nesac\necho merge 5 >> f\nbash f",
1914
+ "case x in x) printf 'gh pr ' ;; if) : ;; esac > f; echo merge 5 >> f; bash f",
1915
+ "case x in x) printf 'gh pr ' ;; '}') : ;; esac > f; echo merge 5 >> f; bash f",
1916
+ "( ( echo gh pr ) ; echo merge 5 ) | tr '\\n' ' ' | bash"]) {
1917
+ assert.equal(agentGuardDecision(line).allow, false, line);
1918
+ }
1919
+ });
1920
+
1921
+ test('#532 review 5: a block the finder pairs across a folded group, and a case under an open loop, keep their output', () => {
1922
+ for (const line of ["for i in 1; do ( printf 'gh pr '; for j in 1; { echo merge 5; } ); done > f; bash f",
1923
+ "for i in 1; do ( echo gh pr; for j in 1; { echo merge 5; } ); done | tr '\\n' ' ' | bash",
1924
+ "case x in x) for j in 1; { :; }; printf 'gh pr merge 5';; esac > f; bash f",
1925
+ "case x in x) for j in 1; { :; }; printf 'gh pr ';; esac > f; echo merge 5 >> f; bash f",
1926
+ "case x in x) if true; then for j in 1; { :; }; printf 'gh pr merge 5'; fi > f;; esac; bash f"]) {
1927
+ assert.equal(agentGuardDecision(line).allow, false, line);
1928
+ }
1929
+ });
1930
+
1931
+ test('#532: differential output corpus against bash and zsh with harmless executable stubs', () => {
1932
+ const T = tmp();
1933
+ const log = path.join(T, 'executed');
1934
+ const bin = path.join(T, 'bin'); fs.mkdirSync(bin);
1935
+ for (const name of ['gh', 'git']) {
1936
+ fs.writeFileSync(path.join(bin, name), '#!/bin/sh\nprintf reached >> "$GUARD_STREAM_LOG"\n', { mode: 0o755 });
1937
+ }
1938
+ const corpus = [...outputGaps, ...outputGapsReview, ...outputGapsReview2,
1939
+ "bash -c bash < <(echo 'gh pr merge 5')", "for i in 1; do { printf 'gh pr '; } done > f; echo merge 5 >> f; bash f",
1940
+ "case x in x) printf 'gh pr ' ;; while) : ;; esac > f; echo merge 5 >> f; bash f"];
1941
+ for (const printer of ["echo gh pr merge 5", "printf '%s ' gh pr merge 5", "printf '%b' '\\x67h pr merge 5\\n'"]) {
1942
+ for (const group of [`{ ${printer}; }`, `( ${printer} )`]) {
1943
+ for (const sink of ['| bash', '> f; bash f', '| tee f; bash f']) corpus.push(`${group} ${sink}`);
1944
+ }
1945
+ }
1946
+ // Each shell that is installed: macOS has bash 3.2 and zsh; a Linux runner has bash 5 and may have no zsh, so
1947
+ // there this checks bash 5 only. The zsh-only lines are checked by the asserts above on every runner.
1948
+ for (const shell of ['/bin/bash', '/bin/zsh']) {
1949
+ if (!fs.existsSync(shell)) continue;
1950
+ for (const line of corpus) {
1951
+ fs.rmSync(log, { force: true });
1952
+ try {
1953
+ execFileSync(shell, ['-c', line], { cwd: T, timeout: 2000, stdio: 'ignore',
1954
+ env: { PATH: `${bin}:/bin:/usr/bin`, HOME: T, GUARD_STREAM_LOG: log } });
1955
+ } catch { /* A shell-specific syntax error is not an execution witness. */ }
1956
+ if (fs.existsSync(log)) assert.equal(agentGuardDecision(line).allow, false, `${shell}: ${line}`);
1957
+ }
1958
+ }
1959
+ });
1960
+
1961
+ test('#532: repeated cat stdin copies are charged before they exhaust the deadline', () => {
1962
+ const line = `printf x > a; echo go | ${'cat - $(<a) | '.repeat(25)}bash`;
1963
+ const v = agentGuardDecision(line);
1964
+ assert.equal(v.allow, false);
1965
+ assert.doesNotMatch(v.message, /took too long/);
1966
+ });