yadflow 4.8.0 → 4.10.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 (107) hide show
  1. package/CHANGELOG.md +114 -0
  2. package/README.md +4 -3
  3. package/bin/commands.mjs +7 -0
  4. package/bin/yad.mjs +123 -8
  5. package/cli/agent-guard.mjs +793 -65
  6. package/cli/agent-rules.mjs +40 -5
  7. package/cli/argv-flags.mjs +1 -1
  8. package/cli/build.mjs +1 -1
  9. package/cli/ci-check.mjs +45 -1
  10. package/cli/codeowners-command.mjs +72 -6
  11. package/cli/commit.mjs +17 -3
  12. package/cli/docs.mjs +2 -0
  13. package/cli/doctor.mjs +176 -12
  14. package/cli/epic-state.mjs +94 -4
  15. package/cli/epic.mjs +11 -7
  16. package/cli/fold.mjs +31 -6
  17. package/cli/guide.mjs +3 -1
  18. package/cli/hook.mjs +50 -7
  19. package/cli/issue-links.mjs +61 -0
  20. package/cli/issues-act.mjs +327 -0
  21. package/cli/issues-write.mjs +428 -0
  22. package/cli/issues.mjs +474 -0
  23. package/cli/lifecycle.mjs +7 -0
  24. package/cli/machine.mjs +141 -0
  25. package/cli/manifest.mjs +9 -3
  26. package/cli/openpr.mjs +69 -9
  27. package/cli/plan.mjs +2 -0
  28. package/cli/platform.mjs +157 -2
  29. package/cli/preview.mjs +253 -0
  30. package/cli/protection.mjs +21 -3
  31. package/cli/reconcile.mjs +1 -1
  32. package/cli/repo.mjs +64 -3
  33. package/cli/review.mjs +4 -0
  34. package/cli/run-checks.mjs +10 -2
  35. package/cli/scan.mjs +314 -0
  36. package/cli/setup.mjs +12 -3
  37. package/cli/standup.mjs +33 -7
  38. package/cli/story-frames.mjs +307 -0
  39. package/cli/test-agents-file.mjs +378 -11
  40. package/cli/test-build.mjs +25 -0
  41. package/cli/test-ci-check.mjs +469 -10
  42. package/cli/test-guide.mjs +7 -0
  43. package/cli/test-machine.mjs +140 -0
  44. package/cli/test-node.mjs +15 -0
  45. package/cli/test-preview.mjs +511 -0
  46. package/cli/test-run-checks.mjs +17 -0
  47. package/cli/test-setup-agent.mjs +14 -0
  48. package/cli/test-story-frames.mjs +409 -0
  49. package/cli/toolbox-connect.mjs +244 -0
  50. package/cli/toolbox.mjs +159 -5
  51. package/package.json +7 -3
  52. package/skills/sdlc/config.yaml +1 -1
  53. package/skills/sdlc/module-help.csv +3 -1
  54. package/skills/yad-analysis/SKILL.md +4 -0
  55. package/skills/yad-backfill/SKILL.md +4 -0
  56. package/skills/yad-change/SKILL.md +4 -0
  57. package/skills/yad-checks/SKILL.md +13 -7
  58. package/skills/yad-checks/references/check-gates.md +62 -30
  59. package/skills/yad-checks/templates/checks/member-check.mjs +3 -2
  60. package/skills/yad-checks/templates/checks/risk-map-check.sh +2 -2
  61. package/skills/yad-checks/templates/checks/verified-commits.sh +3 -3
  62. package/skills/yad-checks/templates/github/yad-checks.yml +357 -69
  63. package/skills/yad-checks/templates/github/yad-pr-text.yml +118 -0
  64. package/skills/yad-checks/templates/github/yad-product-checks.yml +130 -54
  65. package/skills/yad-checks/templates/github/yad-product-pr-text.yml +131 -0
  66. package/skills/yad-checks/templates/github/yad-update-guard.yml +2 -1
  67. package/skills/yad-checks/templates/github/yad-verified-commits.yml +49 -3
  68. package/skills/yad-checks/templates/gitlab/yad-checks.gitlab-ci.yml +79 -20
  69. package/skills/yad-checks/templates/gitlab/yad-product-checks.gitlab-ci.yml +59 -9
  70. package/skills/yad-checks/templates/gitlab/yad-update-guard.gitlab-ci.yml +1 -0
  71. package/skills/yad-checks/templates/gitlab/yad-verified-commits.gitlab-ci.yml +49 -1
  72. package/skills/yad-checks/templates/hooks/agent-guard.mjs +44 -10
  73. package/skills/yad-checks/templates/hooks/ledger-guard-cursor.mjs +12 -6
  74. package/skills/yad-commit/SKILL.md +3 -1
  75. package/skills/yad-connect-design/SKILL.md +48 -13
  76. package/skills/yad-connect-design/references/design-context.md +56 -3
  77. package/skills/yad-connect-design/references/design-registry.md +4 -4
  78. package/skills/yad-connect-learning/SKILL.md +12 -2
  79. package/skills/yad-connect-repos/SKILL.md +12 -0
  80. package/skills/yad-connect-testing/SKILL.md +22 -5
  81. package/skills/yad-connect-testing/references/testing-context.md +1 -1
  82. package/skills/yad-engineer-review/SKILL.md +13 -0
  83. package/skills/yad-epic/SKILL.md +4 -0
  84. package/skills/yad-epic/references/state-schema.md +21 -0
  85. package/skills/yad-guide/SKILL.md +8 -4
  86. package/skills/yad-implement/SKILL.md +69 -3
  87. package/skills/yad-implement/references/implement-conventions.md +2 -1
  88. package/skills/yad-issues/SKILL.md +53 -0
  89. package/skills/yad-learn/SKILL.md +4 -0
  90. package/skills/yad-open-pr/SKILL.md +10 -1
  91. package/skills/yad-pair-review/SKILL.md +5 -0
  92. package/skills/yad-pr-template/SKILL.md +2 -1
  93. package/skills/yad-pr-template/templates/checks/pr-title.sh +34 -2
  94. package/skills/yad-pr-template/templates/github/pull_request_template.md +1 -0
  95. package/skills/yad-pr-template/templates/gitlab/merge_request_templates/Default.md +1 -0
  96. package/skills/yad-product-bridge/references/bridge.md +28 -0
  97. package/skills/yad-product-bridge/templates/github/yad-gate-sync.yml +25 -11
  98. package/skills/yad-product-bridge/templates/gitlab/yad-gate-sync.gitlab-ci.yml +38 -14
  99. package/skills/yad-review-companion/SKILL.md +4 -1
  100. package/skills/yad-run/SKILL.md +5 -0
  101. package/skills/yad-scan/SKILL.md +51 -0
  102. package/skills/yad-spec/SKILL.md +32 -0
  103. package/skills/yad-stories/SKILL.md +22 -0
  104. package/skills/yad-stories/references/story-schema.md +1 -0
  105. package/skills/yad-test-cases/SKILL.md +18 -2
  106. package/skills/yad-ui/SKILL.md +48 -8
  107. package/skills/yad-checks/templates/gitlab/.gitlab-ci.yml +0 -49
@@ -16,12 +16,64 @@
16
16
  // ledger guard). The rules in AGENTS.md are what the agent follows; this catches the plain mistake.
17
17
  //
18
18
  // FAIL-OPEN, like the ledger guard: a payload it cannot read, or no command in it, is allowed.
19
- import { classify } from './agent-rules.mjs';
19
+ import fs from 'node:fs';
20
+ import path from 'node:path';
21
+ import { fileURLToPath } from 'node:url';
22
+ import { classify, readAllowList } from './agent-rules.mjs';
20
23
  import { VALUE_FLAGS, LIST_FLAGS } from './argv-flags.mjs';
21
24
 
22
25
  // A heredoc's `<<` and its end word: bare (`EOF`), quoted (`'EOF'`, `"EOF"`, `E"OF"`) or escaped (`\EOF`). Any
23
- // quote or `\` in the word makes the text plain text, as bash reads it: nothing in it runs.
24
- const HEREDOC = /^<<(-?)[ \t]*((?:\\.|'[^'\n]*'|"[^"\n]*"|[A-Za-z0-9_.-])+)/;
26
+ // quote or `\` in the word makes the text plain text, as bash reads it: nothing in it runs. The word is every
27
+ // character the shell reads as one word (#492): anything but a space, a tab, a newline or `; & | ( ) < >` — so
28
+ // `EOF#`, `EOF+` and a CR (`EOF\r`, from a line written with CRLF) are part of it. Sticky, matched in place
29
+ // (`heredocAt`): slicing the rest of the line for each `<<` made a long line take quadratic time.
30
+ const HEREDOC = /<<(-?)[ \t]*((?:\\.|'[^'\n]*'|"[^"\n]*"|[^ \t\n;&|()<>'"\\])+)/y;
31
+ // An end word holding `$` or a backtick is read as no heredoc (#492 review): inside `bash -c "…"` the outer shell
32
+ // expands it first (`EOF$x` becomes `EOF`), so where it ends cannot be known here, and the lines after it are
33
+ // judged as commands instead.
34
+ // It is still a redirect (`<<"E$x" gh pr merge 1` runs gh), so the `<<word` is read past either way: only no
35
+ // heredoc is recorded for it (`expands`).
36
+ const heredocAt = (line, i) => { HEREDOC.lastIndex = i; const m = HEREDOC.exec(line); if (m) m.expands = /[$`]/.test(m[2]); return m; };
37
+
38
+ // A `$'…'` string from `from` (just past `$'`): its text with the escapes bash applies, and the index of its closing
39
+ // quote (or the end). `\'` is a quote in it, so it does not end the string.
40
+ const ANSI = { n: '\n', t: '\t', r: '\r', a: '\x07', b: '\b', e: '\x1b', E: '\x1b', f: '\f', v: '\v', '\\': '\\', "'": "'", '"': '"', '?': '?' };
41
+ function ansiC(line, from) {
42
+ let text = '';
43
+ let i = from;
44
+ for (; i < line.length && line[i] !== "'"; i++) {
45
+ if (line[i] !== '\\' || i + 1 >= line.length) { text += line[i]; continue; }
46
+ const c = line[i + 1];
47
+ let m;
48
+ if (c in ANSI) { text += ANSI[c]; i++; } else if ((m = /^x([0-9A-Fa-f]{1,2})/.exec(line.slice(i + 1, i + 4)))) { text += String.fromCharCode(parseInt(m[1], 16)); i += m[0].length; } else if ((m = /^[0-7]{1,3}/.exec(line.slice(i + 1, i + 4)))) { text += String.fromCharCode(parseInt(m[0], 8)); i += m[0].length; } else if ((m = /^u([0-9A-Fa-f]{1,4})/.exec(line.slice(i + 1, i + 6)))) { text += String.fromCharCode(parseInt(m[1], 16)); i += m[0].length; } else { text += `\\${c}`; i++; }
49
+ }
50
+ return { text, end: i };
51
+ }
52
+
53
+ // Where each line of `text` starts, by its exact text and by its text with leading tabs removed (`<<-`), so a
54
+ // heredoc's end line is found by a binary search, not by scanning on: a line of many heredocs with different
55
+ // end words is read in near-linear time (#492). `endAfter` gives the index just past the first line at or
56
+ // after `at` that reads `word`, or -1.
57
+ function lineIndex(text) {
58
+ const exact = new Map(), stripped = new Map();
59
+ for (let at = 0; at <= text.length;) {
60
+ const eol = text.indexOf('\n', at);
61
+ const t = text.slice(at, eol < 0 ? text.length : eol);
62
+ for (const [map, k] of [[exact, t], [stripped, t.replace(/^\t+/, '')]]) { const list = map.get(k); if (list) list.push(at); else map.set(k, [at]); }
63
+ at = eol < 0 ? text.length + 1 : eol + 1;
64
+ }
65
+ return {
66
+ endAfter(word, tabs, at) {
67
+ const list = (tabs ? stripped : exact).get(word);
68
+ if (!list) return -1;
69
+ let lo = 0, hi = list.length;
70
+ while (lo < hi) { const mid = (lo + hi) >> 1; if (list[mid] < at) lo = mid + 1; else hi = mid; }
71
+ if (lo === list.length) return -1;
72
+ const eol = text.indexOf('\n', list[lo]);
73
+ return eol < 0 ? text.length + 1 : eol + 1;
74
+ },
75
+ };
76
+ }
25
77
  const heredocOf = (m) => ({ word: m[2].replace(/\\(.)|['"]/g, '$1'), tabs: m[1] === '-', quoted: /['"\\]/.test(m[2]) });
26
78
 
27
79
  // One command line split into its simple commands: on `;`, `&`, `&&`, `||`, `|` and newlines, outside
@@ -33,43 +85,89 @@ const heredocOf = (m) => ({ word: m[2].replace(/\\(.)|['"]/g, '$1'), tabs: m[1]
33
85
  // (`$(…)` or backticks, outside single quotes) stays inside its word, and its text is also kept in
34
86
  // `parts.subs`, so the caller judges the command it runs: `r=$(yad gate approve …)` runs an approval. Quotes
35
87
  // inside it are its own (`"$(cat <<'EOF' … EOF)"` holds any `"` in the heredoc's text).
36
- export function shellParts(line) {
88
+ // `mode` picks the reading where bash and zsh decide by context the reader does not track (#492): `literalExpanding`
89
+ // reads an end word holding `$` or a backtick as a heredoc ending at that literal word (else: no heredoc), and
90
+ // `hashAfterParen` reads a `#` right after `(` or `)` as a comment (else: text). agentGuardDecision judges both.
91
+ export function shellParts(rawLine, mode = {}) {
92
+ // The private-use characters that shield quoted braces (below) cannot come from the line itself: a typed one
93
+ // would turn into a real `{` when a carried command is re-read (`bash -c "gh pr {merge,\uE000} 5"`).
94
+ const line = rawLine.replace(/[\uE000-\uE002]/g, '\uFFFD');
37
95
  const parts = [];
38
- // Not enumerable: `parts` reads as the plain list of parts it always was.
96
+ // Not enumerable: `parts` reads as the plain list of parts it always was. `bodies` and `herestrings` (#495) are
97
+ // the text a part's heredocs and here-strings feed it, by part index: a shell reading them runs them.
39
98
  Object.defineProperty(parts, 'subs', { value: [] });
99
+ Object.defineProperty(parts, 'bodies', { value: [] });
100
+ Object.defineProperty(parts, 'herestrings', { value: [] });
40
101
  let words = [];
41
102
  let word = '';
42
103
  let inWord = false;
43
104
  let quote = null;
44
105
  const heredocs = [];
45
- const endWord = () => { if (inWord) words.push(word); word = ''; inWord = false; };
46
- const endPart = () => { endWord(); if (words.length) parts.push(words); words = []; };
106
+ // A redirect's target is not a word of the command (#495): `gh >x pr merge 5` runs `gh pr merge 5`.
107
+ let dropWord = false;
108
+ let hereString = false;
109
+ // Which words hold an unquoted `{` (#495): only those are brace-expanded, as the shell does — quoted JSON is not.
110
+ Object.defineProperty(parts, 'braced', { value: [] });
111
+ // Which parts read the previous part's output through a pipe (`|`, `|&`), by index.
112
+ Object.defineProperty(parts, 'piped', { value: new Set() });
113
+ let orAt = -1;
114
+ let wordBraced = false;
115
+ let partBraced = null;
116
+ const endWord = () => {
117
+ if (inWord) {
118
+ // A here-string is the command's input, not one of its words (`x=<<<1 git commit …` runs git).
119
+ if (hereString) parts.herestrings.push({ part: parts.length, text: unshieldBraces(word) });
120
+ else if (!dropWord) { words.push(unshieldBraces(word)); if (wordBraced) (partBraced ??= new Map()).set(words.length - 1, word); }
121
+ }
122
+ wordBraced = false;
123
+ // Reset only once the target (or the here-string) was read: a space before it ends no word.
124
+ if (inWord) { dropWord = false; hereString = false; }
125
+ word = ''; inWord = false;
126
+ };
127
+ const endPart = () => { endWord(); dropWord = false; hereString = false; if (words.length) { parts.braced.push(partBraced); parts.push(words); } words = []; partBraced = null; };
47
128
  // Where the heredocs opened on this line end: the index just past the last one's end line, or -1 when an end
48
129
  // line never comes. The text of one whose end word is not quoted (`<<EOF`, not `<<'EOF'`) still runs its
49
130
  // `$(…)` and backticks, so those go to `parts.subs`.
131
+ // The end line must match exactly: `EOF\r` ends only a heredoc whose word is `EOF\r`, as in bash and zsh (a
132
+ // shell that drops CRs is the other reading, judged by agentGuardDecision). A heredoc whose end line never
133
+ // comes is ended by the shell at the end of the input, and an unquoted one still runs its `$(…)` there: those
134
+ // are judged too, as the rest of the line is also read as commands.
135
+ let index = null;
136
+ let restFrom = -1;
50
137
  const heredocsEnd = (from) => {
138
+ index ??= lineIndex(line);
51
139
  let at = from;
52
140
  const bodies = [];
53
141
  for (const h of heredocs) {
54
142
  const start = at;
55
- for (;;) {
56
- if (at > line.length) return -1;
57
- const eol = line.indexOf('\n', at);
58
- const text = line.slice(at, eol < 0 ? line.length : eol).replace(/\r$/, '');
59
- const lineStart = at;
60
- at = eol < 0 ? line.length + 1 : eol + 1;
61
- if ((h.tabs ? text.replace(/^\t+/, '') : text) === h.word) { if (!h.quoted) bodies.push(line.slice(start, lineStart)); break; }
143
+ const next = index.endAfter(h.word, h.tabs, at);
144
+ if (next >= 0) parts.bodies.push({ part: h.part, text: line.slice(start, line.lastIndexOf('\n', next - 2) + 1 || start) });
145
+ if (next < 0) {
146
+ // Once is enough: a later heredoc that never ends starts further on, inside text already judged.
147
+ if (restFrom < 0 && heredocs.some((x) => !x.quoted)) { restFrom = from; for (const x of substitutionsIn(line.slice(from))) parts.subs.push(x); }
148
+ return -1;
62
149
  }
150
+ if (!h.quoted) bodies.push(line.slice(start, line.lastIndexOf('\n', next - 2) + 1 || start));
151
+ at = next;
63
152
  }
64
- for (const body of bodies) parts.subs.push(...substitutionsIn(body));
153
+ // A loop, not a spread: a body of 124,000 `$(` overflowed the stack with `push(...)` (#492 review).
154
+ for (const body of bodies) for (const x of substitutionsIn(body)) parts.subs.push(x);
65
155
  return at;
66
156
  };
67
157
  for (let i = 0; i < line.length; i++) {
68
158
  const ch = line[i];
69
159
  // A command substitution, unquoted or in double quotes (single quotes keep it as text).
70
160
  if (quote !== '\'' && ((ch === '$' && line[i + 1] === '(') || ch === '`')) {
71
- const end = ch === '`' ? backtickEnd(line, i + 1) : substitutionEnd(line, i + 2);
161
+ const end = ch === '`' ? backtickEnd(line, i + 1) : substitutionEnd(line, i + 2, () => (index ??= lineIndex(line)), mode);
72
162
  parts.subs.push(ch === '`' ? line.slice(i + 1, end).replace(/\\`/g, '`') : line.slice(i + 2, end));
163
+ // A `case` in it: its `x)` closes no `$(` to the shell (#495), so the text up to the line's last `)` is
164
+ // judged too. Only refuses more.
165
+ if (ch === '$' && /\bcase\b/.test(line.slice(i + 2, end))) {
166
+ const eol = line.indexOf('\n', i);
167
+ const stop = eol < 0 ? line.length : eol;
168
+ const last = line.lastIndexOf(')', stop - 1);
169
+ if (last > end && /\bcase\b/.test(line.slice(i + 2, last))) parts.subs.push(line.slice(i + 2, last));
170
+ }
73
171
  word += line.slice(i, end + 1); inWord = true;
74
172
  i = end;
75
173
  continue;
@@ -77,20 +175,26 @@ export function shellParts(line) {
77
175
  if (quote) {
78
176
  if (ch === quote) quote = null;
79
177
  else if (ch === '\\' && quote === '"' && line[i + 1] === '\n') i++;
80
- else if (ch === '\\' && quote === '"' && i + 1 < line.length) word += line[++i];
81
- else word += ch;
178
+ else if (ch === '\\' && quote === '"' && i + 1 < line.length) word += shieldBrace(line[++i]);
179
+ else word += shieldBrace(ch);
82
180
  continue;
83
181
  }
182
+ // `$'…'` is read with its escapes (`\'` is a quote in it, #495); `$"…"` is a double-quoted string.
183
+ if (ch === '$' && line[i + 1] === '\'') { const r = ansiC(line, i + 2); word += [...r.text].map(shieldBrace).join(''); inWord = true; i = r.end; continue; }
184
+ if (ch === '$' && line[i + 1] === '"') { continue; }
84
185
  if (ch === '\'' || ch === '"') { quote = ch; inWord = true; continue; }
85
186
  if (ch === '\\' && line[i + 1] === '\n') { i++; continue; }
86
- if (ch === '\\' && line[i + 1] === '\r' && line[i + 2] === '\n') { i += 2; continue; }
87
- if (ch === '\\' && i + 1 < line.length) { word += line[++i]; inWord = true; continue; }
88
- if (ch === '#' && !inWord) { while (i + 1 < line.length && line[i + 1] !== '\n') i++; continue; }
89
- if (ch === '<' && line[i + 1] === '<' && line[i + 2] === '<') { endWord(); i += 2; continue; }
187
+ // `\` + CR + LF is NOT a line join: bash and zsh read an escaped CR, then run the next line as its own
188
+ // command. So it falls through to the escape below (the CR is a character of the word), and the LF ends the part.
189
+ if (ch === '\\' && i + 1 < line.length) { word += shieldBrace(line[++i]); inWord = true; continue; }
190
+ // A `#` starts a comment only where a word starts after a space, a tab, a newline, `;`, `&` or `|` (or at the
191
+ // start): right after `(` or `)` it is text to zsh's globs and to bash's `[[ =~ ]]` (#492 review).
192
+ if (ch === '#' && !inWord && (i === 0 || (mode.hashAfterParen ? /[ \t\n;&|()]/ : /[ \t\n;&|]/).test(line[i - 1])) && !(mode.hashAfterBar && line[i - 1] === '|')) { while (i + 1 < line.length && line[i + 1] !== '\n') i++; continue; }
193
+ if (ch === '<' && line[i + 1] === '<' && line[i + 2] === '<') { endWord(); hereString = true; i += 2; continue; }
90
194
  if (ch === '<' && line[i + 1] === '<') {
91
195
  // A heredoc: its delimiter, bare or quoted, with `<<-` stripping leading tabs from the lines.
92
- const m = HEREDOC.exec(line.slice(i));
93
- if (m) { heredocs.push(heredocOf(m)); endWord(); i += m[0].length - 1; continue; }
196
+ const m = heredocAt(line, i);
197
+ if (m) { if (!m.expands || mode.literalExpanding) heredocs.push({ ...heredocOf(m), part: parts.length }); endWord(); i += m[0].length - 1; continue; }
94
198
  }
95
199
  if (ch === '\n' && heredocs.length) {
96
200
  endPart();
@@ -100,8 +204,37 @@ export function shellParts(line) {
100
204
  if (at >= 0) i = at - 1 - 1;
101
205
  continue;
102
206
  }
103
- if (ch === '\n' || ch === ';' || ch === '&' || ch === '|') { endPart(); continue; }
104
- if (ch === ' ' || ch === '\t' || ch === '\r') { endWord(); continue; }
207
+ // A redirect (#495): `[n]>`, `>>`, `>|`, `&>`, `&>>`, `<`, `<>`, `[n]>&n`, `[n]<&n`, `>&-`. Its operator and its
208
+ // target are not words of the command, and the `&` in it splits nothing (`git push origin main 2>&1 --force`
209
+ // pushes with --force). A `(` right after it is a process substitution: the part break below reads it.
210
+ // zsh's numeric glob (`<->`, `<1-9>`) is one word, not two redirects (#495 review): judged both ways.
211
+ if (mode.numericGlob && ch === '<') {
212
+ const g = /^<[0-9]*-[0-9]*>/.exec(line.slice(i, i + 24));
213
+ if (g) { word += g[0]; inWord = true; i += g[0].length - 1; continue; }
214
+ }
215
+ if ((ch === '>' || ch === '<') || (ch === '&' && line[i + 1] === '>')) {
216
+ if (inWord && /^[0-9]+$/.test(word)) { word = ''; inWord = false; } else endWord();
217
+ let j = i + (ch === '&' ? 2 : 1);
218
+ if (line[j] === '>' || line[j] === '|' || (ch === '<' && line[j] === '>')) j++;
219
+ if (line[j] === '&') { j++; while (j < line.length && /[0-9-]/.test(line[j])) j++; i = j - 1; continue; }
220
+ dropWord = true;
221
+ i = j - 1;
222
+ continue;
223
+ }
224
+ // `(` and `)` end a part too (#492): `<(cmd)`, `>(cmd)`, `f(){ cmd; }` and `case x in x) cmd;;` run `cmd`.
225
+ if (ch === '\n' || ch === ';' || ch === '&' || ch === '|' || ch === '(' || ch === ')') {
226
+ endPart();
227
+ if (ch === '|') {
228
+ // The second `|` of `||` is known by where the first one was, not by the raw text before it (`\||bash`).
229
+ if (line[i + 1] === '|' && orAt !== i) orAt = i + 1;
230
+ else if (orAt !== i) parts.piped.add(parts.length);
231
+ }
232
+ continue;
233
+ }
234
+ // A CR is a character of the word, as bash and zsh read it (#492): `x\r#` is one word, so its `#` starts no
235
+ // comment. A shell that drops CRs is the other reading, judged by agentGuardDecision.
236
+ if (ch === ' ' || ch === '\t') { endWord(); continue; }
237
+ if (ch === '{') wordBraced = true;
105
238
  word += ch; inWord = true;
106
239
  }
107
240
  endPart();
@@ -110,7 +243,9 @@ export function shellParts(line) {
110
243
 
111
244
  // Where the `$(` whose text starts at `from` closes: the index of its `)`, or the end of the line when it never
112
245
  // closes. Quotes, nested `(…)` and a heredoc's text inside it are its own, so a `)` in them does not close it.
113
- function substitutionEnd(line, from) {
246
+ // `getIndex` gives the line index of `line`, built once per text and shared by every `$(` in it (#492 review: one
247
+ // per call made many `$(…)` holding heredocs take quadratic time).
248
+ function substitutionEnd(line, from, getIndex, mode = {}) {
114
249
  let depth = 1;
115
250
  let quote = null;
116
251
  const heredocs = [];
@@ -124,22 +259,18 @@ function substitutionEnd(line, from) {
124
259
  if (ch === '\\') { i++; continue; }
125
260
  if (ch === '\'' || ch === '"') { quote = ch; continue; }
126
261
  if (ch === '<' && line[i + 1] === '<' && line[i + 2] !== '<') {
127
- const m = HEREDOC.exec(line.slice(i));
128
- if (m) { heredocs.push(heredocOf(m)); i += m[0].length - 1; continue; }
262
+ const m = heredocAt(line, i);
263
+ if (m) { if (!m.expands || mode.literalExpanding) heredocs.push(heredocOf(m)); i += m[0].length - 1; continue; }
129
264
  }
130
265
  if (ch === '\n' && heredocs.length) {
131
266
  // Skip each heredoc's text to its end line; one that never ends is not a heredoc.
267
+ const index = getIndex();
132
268
  let at = i + 1;
133
269
  let found = true;
134
270
  for (const h of heredocs) {
135
- for (;;) {
136
- if (at > line.length) { found = false; break; }
137
- const eol = line.indexOf('\n', at);
138
- const text = line.slice(at, eol < 0 ? line.length : eol).replace(/\r$/, '');
139
- at = eol < 0 ? line.length + 1 : eol + 1;
140
- if ((h.tabs ? text.replace(/^\t+/, '') : text) === h.word) break;
141
- }
142
- if (!found) break;
271
+ const next = index.endAfter(h.word, h.tabs, at);
272
+ if (next < 0) { found = false; break; }
273
+ at = next;
143
274
  }
144
275
  heredocs.length = 0;
145
276
  if (found) i = at - 2;
@@ -155,11 +286,13 @@ function substitutionEnd(line, from) {
155
286
  // keeps the next one as text.
156
287
  function substitutionsIn(text) {
157
288
  const out = [];
289
+ let index = null;
290
+ const getIndex = () => (index ??= lineIndex(text));
158
291
  for (let i = 0; i < text.length; i++) {
159
292
  const ch = text[i];
160
293
  if (ch === '\\') { i++; continue; }
161
294
  if ((ch === '$' && text[i + 1] === '(') || ch === '`') {
162
- const end = ch === '`' ? backtickEnd(text, i + 1) : substitutionEnd(text, i + 2);
295
+ const end = ch === '`' ? backtickEnd(text, i + 1) : substitutionEnd(text, i + 2, getIndex);
163
296
  out.push(ch === '`' ? text.slice(i + 1, end).replace(/\\`/g, '`') : text.slice(i + 2, end));
164
297
  i = end;
165
298
  }
@@ -180,7 +313,9 @@ function backtickEnd(line, from) {
180
313
  // `command`, `exec`, `time`, `nohup`, `nice`, `timeout` with its duration, the shell's own words (`then`, `do`,
181
314
  // `else`, `{`, `!`), `xargs`, `stdbuf`, `watch`, and a `(` stuck to the front of the first word. The options of a prefix are skipped with
182
315
  // it, and the value of one that takes a value (`sudo -u <user>`, `nice -n <n>`, `env -u <name>`).
183
- const PREFIXES = new Set(['env', 'sudo', 'command', 'exec', 'time', 'nohup', 'nice', 'xargs', 'stdbuf', 'watch', 'then', 'do', 'else', 'elif', 'if', 'while', 'until', '{', '!']);
316
+ // #495 adds `builtin`, zsh's `noglob` and `nocorrect`, `coproc [NAME]`, `function NAME` and `exec -a NAME`.
317
+ const PREFIXES = new Set(['env', 'sudo', 'command', 'exec', 'time', 'nohup', 'nice', 'xargs', 'stdbuf', 'watch', 'then', 'do', 'else', 'elif', 'if', 'while', 'until', '{', '!',
318
+ 'builtin', 'noglob', 'nocorrect', 'coproc', 'function']);
184
319
  const PREFIX_VALUE_OPTIONS = new Set(['-u', '-g', '-n', '-C', '-h', '-U', '-r', '-t', '-s', '-k', '-o', '--user', '--group', '--signal',
185
320
  '--kill-after', '--unset', '--chdir', '--adjustment', '--output']);
186
321
  // A prefix whose letters mean something else (`xargs -r` and `-t` take no value, `sudo -E` none either) reads
@@ -191,14 +326,19 @@ const PREFIX_OWN_VALUE_OPTIONS = {
191
326
  '--max-procs', '--delimiter', '--arg-file', '--eof']),
192
327
  stdbuf: new Set(['-i', '-o', '-e', '--input', '--output', '--error']),
193
328
  watch: new Set(['-n', '--interval']),
329
+ exec: new Set(['-a']),
194
330
  };
195
331
  const stripPrefix = (words) => {
196
332
  const w = words.slice();
197
- if (w.length && w[0].startsWith('(')) w[0] = w[0].replace(/^\(+/, '');
333
+ // A `(` or a `{` stuck to the first word (zsh reads `{gh pr merge 5;}` as a group).
334
+ if (w.length && /^[({]/.test(w[0])) w[0] = w[0].replace(/^[({]+/, '');
198
335
  let i = 0;
199
336
  for (;;) {
200
337
  while (i < w.length && w[i] === '') i++;
201
338
  if (i < w.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(w[i])) { i++; continue; }
339
+ // `function NAME`, and `coproc NAME {` (a name only before a `{`): the name is not the command.
340
+ if (i < w.length && w[i] === 'function') { i += 2; continue; }
341
+ if (i < w.length && w[i] === 'coproc' && w[i + 2] === '{') { i += 2; continue; }
202
342
  if (i < w.length && (PREFIXES.has(w[i]) || w[i] === 'timeout')) {
203
343
  const isTimeout = w[i] === 'timeout';
204
344
  const own = PREFIX_OWN_VALUE_OPTIONS[w[i]];
@@ -268,13 +408,103 @@ function runnerOf(w) {
268
408
  // The command line a shell runs from its `-c` argument (`bash -c "yad gate approve …"`), or null. A package
269
409
  // runner's `-c`/`--call` before its program is one too (`npx -c '<line>'`, `npm exec -c '<line>'`), and
270
410
  // `pnpm exec|dlx -c` runs the rest of its words as a shell line. A program's own `-c` (`vitest -c x`) is not.
411
+ const SHELLS = ['bash', 'sh', 'zsh', 'dash', 'ksh'];
412
+ // A shell reading its script from its input, not from a file: no `-c`, and either no plain word, or `-s` among its
413
+ // options (the words after are `$1…`), or the first plain word is the input itself (`-`, `/dev/stdin`,
414
+ // `/dev/fd/0`, `/proc/self/fd/0`); `source` / `.` of the input too. `--rcfile` / `--init-file` take a value.
415
+ const STDIN_FILES = /^(-|\/dev\/stdin|\/dev\/fd\/0|\/proc\/self\/fd\/0)$/;
416
+ function bareShell(w) {
417
+ if (!w.length) return false;
418
+ const prog = programOf(w[0]);
419
+ if ((prog === 'source' || prog === '.') && STDIN_FILES.test(w[1] ?? '')) return true;
420
+ if (!SHELLS.includes(prog) || shellC(w) !== null) return false;
421
+ for (let k = 1; k < w.length; k++) {
422
+ if (w[k] === '--') return k + 1 >= w.length || STDIN_FILES.test(w[k + 1]);
423
+ if (/^--(rcfile|init-file|emulate)$/.test(w[k])) { k++; continue; }
424
+ if (/^-[A-Za-z]*s[A-Za-z]*$/.test(w[k])) return true;
425
+ // A cluster holding `o` or `O` takes the next word as its value (`-euo pipefail`).
426
+ if (/^[-+][A-Za-z]*[oO][A-Za-z]*$/.test(w[k])) { k++; continue; }
427
+ if (/^[-+]/.test(w[k]) && w[k] !== '-') continue;
428
+ // A word that may expand to nothing (`bash $NOPE`, `"$@"`): the next one decides.
429
+ if (/[$`]/.test(w[k])) continue;
430
+ return STDIN_FILES.test(w[k]);
431
+ }
432
+ return true;
433
+ }
434
+ // A quoted or escaped `{`, `}` or `,` is text to the shell, not brace syntax: the reader carries it as a private-use
435
+ // character until the word's expansion is done (`git commit -m {'}',-n}` is a list of `}` and `-n`).
436
+ const QUOTED_BRACE = { '{': '\uE000', '}': '\uE001', ',': '\uE002' };
437
+ const shieldBrace = (c) => QUOTED_BRACE[c] ?? c;
438
+ const unshieldBraces = (x) => (/[\uE000-\uE002]/.test(x) ? x.replace(/\uE000/g, '{').replace(/\uE001/g, '}').replace(/\uE002/g, ',') : x);
439
+ // A word's brace expansion, as the shell makes it: every alternative of each list, lists side by side multiplied,
440
+ // lists inside lists expanded, `{x..y}` sequences (any one character, as zsh allows: `{-..-}` is `-`). A number
441
+ // sequence stands for one word, since digits spell no flag. Null when the word is too long to expand (over
442
+ // BRACE_WORD characters with a `{`) or would make more than BRACE_CAP words: the line is refused. The length bound
443
+ // keeps every scan here small, so nesting and long lists cannot make it slow (#495 review).
444
+ const BRACE_CAP = 64;
445
+ const BRACE_WORD = 4096;
446
+ function braceExpand(x, budget = { left: BRACE_CAP }) {
447
+ if (x.length > BRACE_WORD || Date.now() > deadline) return null;
448
+ // Nothing to expand: no scan of its braces, whatever their nesting.
449
+ if (!x.includes(',') && !x.includes('..')) return --budget.left < 0 ? null : [x];
450
+ for (let i = x.indexOf('{'); i >= 0; i = x.indexOf('{', i + 1)) {
451
+ let depth = 0, close = -1;
452
+ const commas = [];
453
+ for (let j = i; j < x.length; j++) {
454
+ if (x[j] === '{') depth++;
455
+ else if (x[j] === '}') { depth--; if (depth === 0) { close = j; break; } } else if (x[j] === ',' && depth === 1) commas.push(j);
456
+ }
457
+ if (close < 0) break;
458
+ const body = x.slice(i + 1, close), pre = x.slice(0, i), post = x.slice(close + 1);
459
+ let alts = null;
460
+ if (commas.length) {
461
+ alts = [];
462
+ let from = i + 1;
463
+ for (const c of [...commas, close]) { alts.push(x.slice(from, c)); from = c + 1; }
464
+ } else {
465
+ const m = /^(-?\d+|.)\.\.(-?\d+|.)(?:\.\.-?\d+)?$/s.exec(body);
466
+ if (m) {
467
+ const num = /^-?\d+$/.test(m[1]) && /^-?\d+$/.test(m[2]);
468
+ if (num) alts = [m[1]];
469
+ else if (m[1].length === 1 && m[2].length === 1) {
470
+ const a = m[1].charCodeAt(0), b = m[2].charCodeAt(0);
471
+ if (Math.abs(b - a) + 1 > BRACE_CAP) return null;
472
+ alts = [];
473
+ for (let k = a; a <= b ? k <= b : k >= b; k += a <= b ? 1 : -1) alts.push(String.fromCharCode(k));
474
+ }
475
+ }
476
+ }
477
+ if (!alts) continue;
478
+ const out = [];
479
+ for (const alt of alts) {
480
+ const more = braceExpand(pre + alt + post, budget);
481
+ if (!more) return null;
482
+ for (const y of more) out.push(y);
483
+ }
484
+ return out;
485
+ }
486
+ // A finished word: only these count against the cap.
487
+ return --budget.left < 0 ? null : [x];
488
+ }
489
+ // A word quoted for a shell line, so a carried command re-read as a line keeps its words (`find -exec sh -c '…'`).
490
+ const shq = (x) => (/^[A-Za-z0-9_@%+=:,./-]+$/.test(x) ? x : `'${x.replace(/'/g, "'\\''")}'`);
271
491
  function shellC(words) {
272
492
  const w = stripPrefix(words);
273
493
  if (!w.length) return null;
274
494
  const prog = programOf(w[0]);
275
- if (['bash', 'sh', 'zsh', 'dash', 'ksh'].includes(prog)) {
495
+ if (SHELLS.includes(prog)) {
276
496
  const c = w.findIndex((x, n) => n > 0 && /^-[A-Za-z]*c[A-Za-z]*$/.test(x));
277
- return c > 0 && c + 1 < w.length ? w[c + 1] : null;
497
+ if (c < 0) return null;
498
+ // The line is the first word after the options that follow `-c` (#495): `bash -c -- "…"`, `bash -c -x "…"`,
499
+ // and `-o NAME` / `-O NAME`, which take a value.
500
+ let k = c + 1;
501
+ while (k < w.length) {
502
+ if (w[k] === '--' || w[k] === '-') { k++; break; }
503
+ if (/^[-+][oO]$/.test(w[k])) { k += 2; continue; }
504
+ if (/^[-+][A-Za-z]+$/.test(w[k])) { k++; continue; }
505
+ break;
506
+ }
507
+ return k < w.length ? w[k] : null;
278
508
  }
279
509
  const r = runnerOf(w);
280
510
  if (!r) return null;
@@ -298,6 +528,59 @@ function shellC(words) {
298
528
  return null;
299
529
  }
300
530
 
531
+ // Every command line a part carries and runs (#495): a shell's `-c` line (`shellC`); `env -S "<line>"`; each
532
+ // `find … -exec|-execdir|-ok|-okdir <cmd…> ;|+`; a `git -c alias.NAME=VALUE … NAME …` (a `!VALUE` is a shell
533
+ // line, any other VALUE runs as `git VALUE …`); and `eval <args>`, joined.
534
+ function innerLines(part) {
535
+ const out = [];
536
+ const c = shellC(part);
537
+ if (c !== null) out.push(c);
538
+ const lead = part.slice(0, part.length - stripPrefix(part).length);
539
+ const envAt = lead.lastIndexOf('env') >= 0 ? lead.indexOf('env') : (part[0] === 'env' ? 0 : -1);
540
+ if (envAt >= 0) {
541
+ for (let i = envAt + 1; i < part.length; i++) {
542
+ const a = part[i];
543
+ if (a === '-S' || a === '--split-string') { out.push([part[i + 1] ?? '', ...part.slice(i + 2)].join(' ')); break; }
544
+ const m = /^(?:-S|--split-string=)(.+)$/.exec(a);
545
+ if (m) { out.push([m[1], ...part.slice(i + 1)].join(' ')); break; }
546
+ // `env`'s options that take a value come before `-S` too (`env -u X -S "…"`).
547
+ if (['-u', '--unset', '-C', '--chdir', '-a', '--argv0'].includes(a)) { i++; continue; }
548
+ if (!a.startsWith('-') && !/^[A-Za-z_][A-Za-z0-9_]*=/.test(a)) break;
549
+ }
550
+ }
551
+ const w = stripPrefix(part);
552
+ const prog = w.length ? programOf(w[0]) : '';
553
+ if (prog === 'find') {
554
+ for (let i = 1; i < w.length; i++) {
555
+ if (!/^-(exec|execdir|ok|okdir)$/.test(w[i])) continue;
556
+ let j = i + 1;
557
+ while (j < w.length && w[j] !== ';' && w[j] !== '+') j++;
558
+ out.push(w.slice(i + 1, j).map(shq).join(' '));
559
+ i = j;
560
+ }
561
+ }
562
+ if (prog === 'git') {
563
+ const alias = new Map();
564
+ let i = 1;
565
+ while (i < w.length && w[i].startsWith('-')) {
566
+ const m = w[i] === '-c' ? /^alias\.([^=]+)=(.*)$/s.exec(w[i + 1] ?? '') : null;
567
+ if (m) alias.set(m[1].toLowerCase(), m[2]);
568
+ i += GIT_VALUE_OPTIONS.has(w[i]) ? 2 : 1;
569
+ }
570
+ // Aliases may name aliases (`-c alias.a=b -c alias.b='push --force' a`): followed a few steps.
571
+ let rest = w.slice(i);
572
+ for (let step = 0; step < 5 && rest.length; step++) {
573
+ const value = alias.get(rest[0].toLowerCase());
574
+ if (value === undefined) break;
575
+ if (value.startsWith('!')) { out.push([value.slice(1), ...rest.slice(1).map(shq)].join(' ')); break; }
576
+ out.push(['git', value, ...rest.slice(1).map(shq)].join(' '));
577
+ rest = [...value.split(/\s+/).filter(Boolean), ...rest.slice(1)];
578
+ }
579
+ }
580
+ if (prog === 'eval') out.push(w.slice(1).join(' '));
581
+ return out;
582
+ }
583
+
301
584
  // The yad argv after the program, or null when the part does not run yad: `yad …` (any path, `yad.mjs` too),
302
585
  // yadflow's `yad` through a package runner (`runnerOf`), or `node [options] …/yad.mjs …`.
303
586
  function yadArgs(words) {
@@ -461,39 +744,174 @@ function platformApproval(words) {
461
744
  }
462
745
 
463
746
  // The verdict for one shell command line: `{allow: true}` or `{allow: false, message}`.
747
+ // Bash and zsh read a CR as a character of a word; a shell that drops CRs (Git Bash with `igncr`) does not, and
748
+ // reads `\` + CR + LF as a line join. Refuse under either reading (#353, #492): a line holding a CR is judged
749
+ // again with every CR removed, at every depth, since a `bash -c` string built from quoted pieces holds one only
750
+ // once its quotes are gone. A line too long to judge in a hook's time is refused, never let through.
751
+ export const MAX_JUDGED = 1_000_000;
752
+ // Every reading costs time, so the whole judgement has a budget: past it the line is refused, as a line too long
753
+ // is — a hook that runs out its harness's time lets the command through (#492).
754
+ // (agentGuardPreapproval asks again for an allowed line, so a hook can spend it twice: about 10 s at worst, well
755
+ // under a harness's hook timeout. Each reading is linear, so a 1 MB line costs well under a second per reading.)
756
+ export const JUDGE_BUDGET_MS = 5000;
757
+ let deadline = Infinity;
758
+ const OUT_OF_TIME = { allow: false, message: 'yad agent guard: this command took too long to judge. Run it as separate commands.' };
464
759
  export function agentGuardDecision(line, depth = 0) {
465
- if (typeof line !== 'string' || !line.trim()) return { allow: true };
466
- const parts = shellParts(line);
467
- // The commands a `$(…)` or backticks run are judged too (a few levels deep at most).
468
- if (depth < 3) {
469
- for (const sub of parts.subs) {
470
- const v = agentGuardDecision(sub, depth + 1);
760
+ if (typeof line === 'string' && line.length > MAX_JUDGED) {
761
+ return { allow: false, message: `yad agent guard: this command is too long to judge (${line.length} characters, more than ${MAX_JUDGED}). Write what it carries to a file with your editor, or run it as separate commands.` };
762
+ }
763
+ if (depth > 0) return judgeReadings(line, depth);
764
+ deadline = Date.now() + JUDGE_BUDGET_MS;
765
+ try {
766
+ return judgeReadings(line, depth);
767
+ } catch (e) {
768
+ // A line the reader cannot judge is refused, never let through: the payload was read, so this is a bug here.
769
+ return { allow: false, message: `yad agent guard: this command could not be judged (${e?.message ?? e}). Run it as separate commands, and report it with \`yad report\`.` };
770
+ } finally {
771
+ deadline = Infinity;
772
+ }
773
+ }
774
+ // Where the first heredoc whose end word expands (`<<E$x`, `<<"E\`x\`"`) opens, or -1: read from the actual matches,
775
+ // one `<<` at a time, so it is linear (a regex over the line backtracked: quadratic on a run of `<<`).
776
+ function firstExpandingHeredoc(text) {
777
+ for (let i = text.indexOf('<<'); i >= 0; i = text.indexOf('<<', i + 2)) {
778
+ const m = heredocAt(text, i);
779
+ if (m?.expands) return i;
780
+ }
781
+ return -1;
782
+ }
783
+ // Every reading the shells may make of the line: as written; with CRs dropped (a CR-dropping shell); with every
784
+ // `\` + newline join made, CRs dropped first (a `$\<LF>(`, an end word split by a join: `EO\<LF>F`); and, where
785
+ // the line has the context the reader does not track, each mode of shellParts. Refused if any reading refuses.
786
+ function judgeReadings(line, depth) {
787
+ if (typeof line !== 'string') return { allow: true };
788
+ const texts = [line];
789
+ if (line.includes('\r')) texts.push(line.replace(/\r/g, ''));
790
+ if (/\\\r?\n/.test(line)) texts.push(line.replace(/\r/g, '').replace(/\\\n/g, ''));
791
+ const expandsAt = firstExpandingHeredoc(line);
792
+ const flags = [];
793
+ if (expandsAt >= 0) flags.push('literalExpanding');
794
+ if (/[()]#/.test(line)) flags.push('hashAfterParen');
795
+ // A `#` right after `|` is a comment in command position, text in `[[ =~ ]]` (#495).
796
+ if (/\|#/.test(line)) flags.push('hashAfterBar');
797
+ if (/<[0-9]*-[0-9]*>/.test(line)) flags.push('numericGlob');
798
+ // Every combination of the readings that apply (at most 16).
799
+ const modes = [{}];
800
+ for (const f of flags) for (const m of modes.slice()) modes.push({ ...m, [f]: true });
801
+ for (const mode of modes) {
802
+ for (const text of texts) {
803
+ const v = judgeLine(text, depth, mode);
471
804
  if (!v.allow) return v;
472
805
  }
473
806
  }
474
- for (const part of parts) {
475
- // `bash -c "<line>"`: the line it runs is judged too (a few levels deep at most).
476
- const inner = shellC(part);
477
- if (inner !== null && depth < 3) {
478
- const v = agentGuardDecision(inner, depth + 1);
479
- if (!v.allow) return v;
807
+ // An end word that expands can end the heredoc on any line, whatever the variable holds (`bash -c "cat <<E$x …"`
808
+ // with an empty $x ends at `E`): each line is judged on its own too, so the command after it is seen wherever
809
+ // the heredoc ends. Only refuses more.
810
+ if (expandsAt >= 0) {
811
+ for (const text of texts) {
812
+ const from = firstExpandingHeredoc(text);
813
+ for (const one of text.slice(from < 0 ? 0 : from).split('\n')) {
814
+ const v = judgeLine(one, depth, {});
815
+ if (!v.allow) return v;
816
+ }
480
817
  }
481
- const args = yadArgs(part);
482
- if (args) {
483
- const { words, flags, help } = yadWords(args);
484
- if (!help && classify(words, flags) === 'human-only') {
485
- return { allow: false, message: `yad agent guard: \`yad ${words.join(' ')}${flags.includes('manual') ? ' --manual' : ''}\` is the person's to run, never the agent's (an approval, a gate comment or advance or reopen, or a commit past the ledger guard). Ask the person to run it themselves — in Claude Code they type it with \`!\` in front — then confirm by reading (\`yad gate status\` / \`yad guide --json\`).` };
818
+ }
819
+ return { allow: true };
820
+ }
821
+ // The four refusals for one part's words.
822
+ function partVerdict(part) {
823
+ const args = yadArgs(part);
824
+ if (args) {
825
+ const { words, flags, help } = yadWords(args);
826
+ if (!help && classify(words, flags) === 'human-only') {
827
+ return { allow: false, message: `yad agent guard: \`yad ${words.join(' ')}${flags.includes('manual') ? ' --manual' : ''}\` is the person's to run, never the agent's (an approval, a gate comment or advance or reopen, or a commit past the ledger guard). Ask the person to run it themselves — in Claude Code they type it with \`!\` in front — then confirm by reading (\`yad gate status\` / \`yad guide --json\`).` };
828
+ }
829
+ }
830
+ if (platformApproval(part)) {
831
+ return { allow: false, message: 'yad agent guard: approving or merging a PR/MR is the person\'s, never the agent\'s (the yadflow rules), even when your login could. Give the person the link and the exact steps, wait, then confirm by reading (`yad gate status` / `yad guide --json`).' };
832
+ }
833
+ if (hookSkip(part)) {
834
+ return { allow: false, message: 'yad agent guard: skipping the git hooks (`--no-verify`, `-n`, `YAD_HOOK_DISABLE`, `core.hooksPath`) is the person\'s, never the agent\'s (the yadflow rules): it is the door past the ledger guard. When a hook refuses a commit, follow its message; if the commit must go through, the person runs `yad commit --manual --reason "<why>"` themselves (`!` in front in Claude Code).' };
835
+ }
836
+ if (forcePush(part)) {
837
+ return { allow: false, message: 'yad agent guard: a force push is never the agent\'s (the yadflow rules). Tell the person why the push was refused and what a force push would overwrite; if it is needed, they run it themselves.' };
838
+ }
839
+ return { allow: true };
840
+ }
841
+ const TOO_MANY_BRACES = { allow: false, message: 'yad agent guard: this command\'s brace lists expand to too many words, or a word with them is too long, to judge. Write the words out, quote them, or run it as separate commands.' };
842
+ const TOO_DEEP = { allow: false, message: 'yad agent guard: this command nests `$(…)`, backticks or `bash -c` too deep to judge. Run it as separate commands.' };
843
+ function judgeLine(line, depth, mode = {}) {
844
+ if (typeof line !== 'string' || !line.trim()) return { allow: true };
845
+ if (Date.now() > deadline) return OUT_OF_TIME;
846
+ const parts = shellParts(line, mode);
847
+ // The commands a `$(…)` or backticks run are judged too, three levels deep; one deeper is refused (#492).
848
+ if (parts.subs.length && depth >= 3) return TOO_DEEP;
849
+ for (const sub of parts.subs) {
850
+ const v = agentGuardDecision(sub, depth + 1);
851
+ if (!v.allow) return v;
852
+ }
853
+ // The text each part is fed, grouped once by part (a loop over every body for every part was quadratic).
854
+ const fed = new Map();
855
+ const printed = [];
856
+ for (const x of [...parts.bodies, ...parts.herestrings]) { if (!fed.has(x.part)) fed.set(x.part, []); fed.get(x.part).push(x.text); }
857
+ for (let n = 0; n < parts.length; n++) {
858
+ const part = parts[n];
859
+ // Every way the shell may read this part's words (#495): as written; with a command word that expands
860
+ // (`$(echo gh)`, `${x:-gh}`, `=gh`, `$SHELL`) dropped (it may be empty) or as each guarded program or a
861
+ // shell; and with its unquoted brace lists expanded, with the empty words kept (zsh) and dropped (bash).
862
+ if (Date.now() > deadline) return OUT_OF_TIME;
863
+ const w = stripPrefix(part);
864
+ const variants = [part];
865
+ const braced = parts.braced[n];
866
+ if (braced) {
867
+ const expanded = [], noEmpty = [];
868
+ let added = 0;
869
+ for (let k = 0; k < part.length; k++) {
870
+ if (!braced.has(k)) { expanded.push(part[k]); noEmpty.push(part[k]); continue; }
871
+ const e = braceExpand(braced.get(k));
872
+ if (!e || (added += e.length - 1) > 4 * BRACE_CAP) return TOO_MANY_BRACES;
873
+ // Only an expansion's empty words are dropped, as bash does; a quoted `''` is a word.
874
+ for (const y of e) { const real = unshieldBraces(y); expanded.push(real); if (y !== '') noEmpty.push(real); }
486
875
  }
876
+ variants.push(expanded, noEmpty);
487
877
  }
488
- if (platformApproval(part)) {
489
- return { allow: false, message: 'yad agent guard: approving or merging a PR/MR is the person\'s, never the agent\'s (the yadflow rules), even when your login could. Give the person the link and the exact steps, wait, then confirm by reading (`yad gate status` / `yad guide --json`).' };
878
+ for (const base of variants.slice()) {
879
+ const bw = stripPrefix(base);
880
+ const raw = base[base.length - bw.length] ?? '';
881
+ if (bw.length && (/[$`]/.test(raw) || /^=[A-Za-z]/.test(raw))) {
882
+ const bl = base.slice(0, base.length - bw.length);
883
+ variants.push([...bl, ...bw.slice(1)], ...['gh', 'glab', 'git', 'yad', 'bash'].map((prog) => [...bl, prog, ...bw.slice(1)]));
884
+ }
490
885
  }
491
- if (hookSkip(part)) {
492
- return { allow: false, message: 'yad agent guard: skipping the git hooks (`--no-verify`, `-n`, `YAD_HOOK_DISABLE`, `core.hooksPath`) is the person\'s, never the agent\'s (the yadflow rules): it is the door past the ledger guard. When a hook refuses a commit, follow its message; if the commit must go through, the person runs `yad commit --manual --reason "<why>"` themselves (`!` in front in Claude Code).' };
886
+ // The lines each variant carries (`bash -c`, `env -S`, `find -exec`, a git alias, `eval`) are judged too, as deep;
887
+ // one deeper is refused. A shell that reads its input runs what it is fed: its own heredoc or here-string, and
888
+ // any text an earlier part prints (a pipe, `tee`, a `cat <<EOF` body), each judged once, by the first shell.
889
+ const carried = [];
890
+ let readsInput = false;
891
+ for (const vw of variants) for (const t of innerLines(vw)) carried.push(t);
892
+ // A real shell (as written, or brace-expanded) takes all the text printed before it: through a pipe, a group
893
+ // (`{ echo …; } | bash`), or a file it reads back. A command word only guessed to be a shell needs a real pipe:
894
+ // otherwise any `$x` line after a docs heredoc would be judged as running it.
895
+ const real = braced ? 3 : 1;
896
+ let realShell = false;
897
+ variants.forEach((vw, k) => { if (bareShell(stripPrefix(vw))) { readsInput = true; if (k < real) realShell = true; } });
898
+ if (readsInput) {
899
+ for (const t of fed.get(n) ?? []) carried.push(t);
900
+ if (realShell || parts.piped.has(n)) { for (const t of printed) carried.push(t); printed.length = 0; }
493
901
  }
494
- if (forcePush(part)) {
495
- return { allow: false, message: 'yad agent guard: a force push is never the agent\'s (the yadflow rules). Tell the person why the push was refused and what a force push would overwrite; if it is needed, they run it themselves.' };
902
+ if (carried.length && depth >= 3) return TOO_DEEP;
903
+ for (const inner of carried) {
904
+ const v = agentGuardDecision(inner, depth + 1);
905
+ if (!v.allow) return v;
906
+ }
907
+ for (const vw of variants) {
908
+ const v = partVerdict(vw);
909
+ if (!v.allow) return v;
496
910
  }
911
+ // What this part prints or is fed, for a shell later on the line.
912
+ for (const t of fed.get(n) ?? []) printed.push(t);
913
+ if (w.length && programOf(w[0]) === 'echo') printed.push(w.slice(1).filter((x) => !/^-[neE]+$/.test(x)).join(' '));
914
+ if (w.length && programOf(w[0]) === 'printf') printed.push(w.slice(1).join(' '), w.slice(2).join(' '));
497
915
  }
498
916
  return { allow: true };
499
917
  }
@@ -509,3 +927,313 @@ export function payloadCommand(payload) {
509
927
 
510
928
  // Cursor's payload names its event; Claude Code's says `PreToolUse`.
511
929
  export const isCursorPayload = (payload) => payload?.hook_event_name === 'beforeShellExecution' || typeof payload?.cursor_version === 'string';
930
+
931
+ // ---------------------------------------------------------------------------------------------------------------
932
+ // PRE-APPROVAL (E167, issue #353). The other half of the guard: a command line it can SEE only reads runs with no
933
+ // permission prompt. Claude Code's allow rules match the start of a command, so `Bash(gh api:*)` would also pass
934
+ // `gh api -X DELETE …`; this reads each word instead. It answers "allow" only when EVERY part of the line is one of
935
+ // the reads below, written in a form it knows; anything else gets no answer, which is the prompt the person had
936
+ // before. So a mistake here, or a hook that fails, costs a prompt, never a write. A team's own `deny` and `ask`
937
+ // rules still win over a hook's "allow" (Claude Code's rule), and `YAD_NO_PREAPPROVE=1` turns this half off.
938
+ //
939
+ // Never pre-approved, whatever the form: a secret, token, variable, key or webhook (the person's, HUMAN_ONLY_ACTS
940
+ // in cli/agent-rules.mjs), GraphQL (a mutation rides the same call as a query), any API call that is not a GET, a
941
+ // file written or a file read from outside the project, a `$(…)`, a `bash -c`, an env prefix, and any program not
942
+ // named here. What it lists is printed by `yad setup` and given to agents by `yad guide --json`.
943
+ export const PREAPPROVED = Object.freeze({
944
+ api: 'gh api / glab api: a GET (no -X other than GET, no fields, no --input, --hostname or --cache, only an Accept header), not graphql, and no secrets, secure files, variables, tokens, keys, hooks, e-mails, triggers, integrations, services, credentials, Terraform state, schedules, CI logs, traces or artifacts, admin settings (application) or user in the path, with or without a .json-style suffix',
945
+ git: 'git log, status, diff, show, rev-parse, ls-files, blame (no git option before them; no --output, --ext-diff, --textconv, --no-index, --contents, --show-signature or a shortening of one, no %G in a format, git diff paths inside the project; git still runs what its own config names, such as an external diff or fsmonitor)',
946
+ jq: 'jq (a filter on the line, never from a file; no env, $ENV, import or include in it; files inside the project)',
947
+ filters: 'head, tail, wc, grep (not -R), cut, uniq, tr, cat (files inside the project)',
948
+ yad: 'the read-only yad commands of the settings allow list',
949
+ gates: 'the read-only gates in checks/ (spec-link, contract-check, commit-message, lineage-check, epic-open, reconcile-debt-check, risk-map-check, verified-commits, ledger-guard, member-check), only while the file is the copy this yadflow ships',
950
+ never: 'secrets, tokens, variables, keys, webhooks, GraphQL, API writes, file writes, $ (variables) outside single quotes, brace lists, globs, ( ), a word starting with ~ or =, $(…), bash -c, env prefixes',
951
+ });
952
+ export const PREAPPROVED_GATES = Object.freeze(['spec-link.sh', 'contract-check.sh', 'commit-message.sh', 'lineage-check.sh', 'epic-open.sh',
953
+ 'reconcile-debt-check.sh', 'risk-map-check.sh', 'verified-commits.sh', 'ledger-guard.sh', 'member-check.mjs']);
954
+ const SHIPPED_CHECKS = fileURLToPath(new URL('../skills/yad-checks/templates/checks/', import.meta.url));
955
+
956
+ // The line with its harmless redirects blanked out (`2>/dev/null`, `>/dev/null`, `&>/dev/null`, `2>&1`, `>&2`),
957
+ // or null when it has any other: a `>` to a file writes it, a `<` (a file, a heredoc, a here-string) or a
958
+ // process substitution feeds text from somewhere this does not judge. Quotes are respected, so the `>` in
959
+ // `jq '.a > 1'` is text. Null too for anything the shell EXPANDS before the program sees it, because the words
960
+ // judged here would not be the words run: a `$` outside single quotes (`"$GH_TOKEN"`, `${HOME}`, `$((…))`).
961
+ // Unquoted text is held to an ALLOW list of characters — letters, digits, `_ . / : @ % + , ^ ~ = -`, spaces and
962
+ // the separators — because bash and zsh each expand more than any list of bad ones names: a brace list
963
+ // (`{~/.ssh/id_rsa,x}`), a glob (`*`, `?`, `[`, which can reach a link out of the project), zsh's glob
964
+ // qualifiers (`file(e:cmd:)` runs cmd) and `=(cmd)` / `=ls`. So also: no `=` or `~` starting a word. One form is
965
+ // let through because neither shell expands it: a brace around one plain word (`{owner}` in a gh path, `@{u}`).
966
+ // Only a space, a tab and a newline break words: `\r`, `\v`, a no-break space are word characters to the shell,
967
+ // and a guard that read them as breaks would judge different words than the shell runs. No `#` either: where a
968
+ // comment starts depends on that same reading (a `\`-newline joins words), so a `#` gets the prompt.
969
+ // Not `^`: zsh's `extendedglob` (on in setups such as Prezto) makes it a glob.
970
+ const UNQUOTED_SAFE = /[A-Za-z0-9_./:@%+,~=-]/;
971
+ function blankHarmlessRedirects(line) {
972
+ let out = '';
973
+ let quote = null;
974
+ for (let i = 0; i < line.length; i++) {
975
+ const ch = line[i];
976
+ if (quote) {
977
+ if (ch === quote) quote = null;
978
+ else if (quote === '"' && (ch === '$' || ch === '`')) return null;
979
+ else if (ch === '\\' && quote === '"') { out += ch + (line[i + 1] ?? ''); i++; continue; }
980
+ out += ch;
981
+ continue;
982
+ }
983
+ // An escaped character is literal, except a CR, which the guard's reader and the shell do not split alike.
984
+ if (ch === '\\') { if (line[i + 1] === '\r') return null; out += ch + (line[i + 1] ?? ''); i++; continue; }
985
+ if (ch === '\'' || ch === '"') { quote = ch; out += ch; continue; }
986
+ const wordStart = i === 0 || /[ \t\n;|&]/.test(line[i - 1]);
987
+ if ((ch === '~' || ch === '=') && (wordStart || /[=:]/.test(line[i - 1]))) return null;
988
+ if (ch === '{') {
989
+ const m = /^\{[A-Za-z0-9_]*\}/.exec(line.slice(i));
990
+ if (!m) return null;
991
+ out += m[0]; i += m[0].length - 1; continue;
992
+ }
993
+ if (ch === '<') return null;
994
+ if (ch !== '>' && !UNQUOTED_SAFE.test(ch) && !/[ \t\n;|&]/.test(ch)) return null;
995
+ if (ch !== '>') { out += ch; continue; }
996
+ // The fd before it (`2>`) or `&>`: blanked with it.
997
+ let start = out.length;
998
+ while (start > 0 && /[0-9&]/.test(out[start - 1])) start--;
999
+ if (start > 0 && !/[\s;|&]/.test(out[start - 1])) return null;
1000
+ let j = i + 1;
1001
+ if (line[j] === '(') return null;
1002
+ let dup = false;
1003
+ if (line[j] === '>') j++;
1004
+ else if (line[j] === '&') { dup = true; j++; } else if (line[j] === '|') return null;
1005
+ while (line[j] === ' ' || line[j] === '\t') j++;
1006
+ let k = j;
1007
+ while (k < line.length && !/[\s;|&<>()'"`$\\]/.test(line[k])) k++;
1008
+ const target = line.slice(j, k);
1009
+ if (!(dup ? /^[0-9]+$/.test(target) : target === '/dev/null')) return null;
1010
+ // The target ends the word: `2>/dev/null"x"` writes to `/dev/nullx`.
1011
+ if (k < line.length && !/[\s;|&)]/.test(line[k])) return null;
1012
+ out = `${out.slice(0, start)}${' '.repeat(i - start)}${' '.repeat(k - i)}`;
1013
+ i = k - 1;
1014
+ }
1015
+ return quote ? null : out;
1016
+ }
1017
+
1018
+ // A file named on a command line, read inside the project only: no `~`, no `$`, nothing that resolves (through a
1019
+ // link too) outside the project. `at` is `{ cwd, root }`: the word resolves from `cwd` and must land in `root`.
1020
+ // `-` is standard input.
1021
+ function insideProject(word, at) {
1022
+ if (word === '-') return true;
1023
+ if (!word || /^~|\$/.test(word)) return false;
1024
+ let root, cwd;
1025
+ // Both through realpath, so a link in either (macOS's /var is /private/var) does not make a file look outside.
1026
+ try { root = fs.realpathSync(at.root); cwd = fs.realpathSync(at.cwd); } catch { return false; }
1027
+ let full = path.resolve(cwd, word);
1028
+ try { full = fs.realpathSync(full); } catch { /* not there yet (or a glob): judged by its spelling */ }
1029
+ const rel = path.relative(root, full);
1030
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
1031
+ }
1032
+
1033
+ // Read a program's arguments against its options: `bool` takes no value, `value` takes one (`-n 5`, `-n5`,
1034
+ // `--lines=5`, `--lines 5`), `pairs` takes two (`--arg name value`). Short options may be clustered (`-in`) while
1035
+ // they take no value. `numeric` allows `-5` (head, tail). Returns the plain operands, or null for an option it
1036
+ // does not know: an unknown option is never guessed at.
1037
+ function operandsOf(args, { bool = [], value = [], pairs = [], numeric = false } = {}) {
1038
+ const B = new Set(bool), V = new Set(value), P = new Set(pairs);
1039
+ const ops = [];
1040
+ const values = {};
1041
+ for (let i = 0; i < args.length; i++) {
1042
+ const a = args[i];
1043
+ if (a === '--') { ops.push(...args.slice(i + 1)); break; }
1044
+ if (a === '-' || !a.startsWith('-')) { ops.push(a); continue; }
1045
+ if (a.startsWith('--')) {
1046
+ const [name, eq] = [a.split('=')[0], a.includes('=')];
1047
+ if (B.has(name) && !eq) continue;
1048
+ if (V.has(name)) { (values[name] ??= []).push(eq ? a.slice(a.indexOf('=') + 1) : args[++i]); if (!eq && i >= args.length) return null; continue; }
1049
+ if (P.has(name) && !eq) { (values[name] ??= []).push([args[i + 1], args[i + 2]]); i += 2; if (i >= args.length) return null; continue; }
1050
+ return null;
1051
+ }
1052
+ if (numeric && /^-[0-9]+$/.test(a)) continue;
1053
+ // A short option or a cluster of them.
1054
+ for (let c = 1; c < a.length; c++) {
1055
+ const o = `-${a[c]}`;
1056
+ if (B.has(o)) continue;
1057
+ if (V.has(o)) {
1058
+ const rest = a.slice(c + 1);
1059
+ (values[o] ??= []).push(rest || args[++i]);
1060
+ if (!rest && i >= args.length) return null;
1061
+ break;
1062
+ }
1063
+ return null;
1064
+ }
1065
+ }
1066
+ return { ops, values };
1067
+ }
1068
+
1069
+ // The tools a part may run, each judged on its own words (the program name first, bare: `./gh` is a script).
1070
+ const FILTERS = {
1071
+ head: { bool: ['-q', '-v', '--quiet', '--silent', '--verbose'], value: ['-n', '-c', '--lines', '--bytes'], numeric: true },
1072
+ tail: { bool: ['-q', '-v', '-r', '--quiet', '--silent', '--verbose'], value: ['-n', '-c', '--lines', '--bytes'], numeric: true },
1073
+ wc: { bool: ['-l', '-w', '-c', '-m', '-L', '--lines', '--words', '--bytes', '--chars', '--max-line-length'] },
1074
+ cut: { bool: ['-s', '-n', '--only-delimited', '--complement'], value: ['-d', '-f', '-c', '-b', '--delimiter', '--fields', '--characters', '--bytes', '--output-delimiter'] },
1075
+ cat: { bool: ['-n', '-b', '-s', '-v', '-e', '-t', '-A', '-E', '-T', '-u', '--number', '--number-nonblank', '--squeeze-blank', '--show-all'] },
1076
+ grep: { bool: ['-i', '-v', '-c', '-n', '-E', '-F', '-G', '-o', '-q', '-w', '-x', '-l', '-L', '-h', '-H', '-s', '-r', '-z', '-a', '-I',
1077
+ '--ignore-case', '--invert-match', '--count', '--line-number', '--extended-regexp', '--fixed-strings', '--only-matching', '--quiet', '--silent',
1078
+ '--word-regexp', '--line-regexp', '--files-with-matches', '--files-without-match', '--no-filename', '--with-filename', '--recursive', '--color', '--no-messages'],
1079
+ // Not -R / --dereference-recursive: it follows every link under the folder, out of the project too.
1080
+ value: ['-e', '-m', '-A', '-B', '-C', '--regexp', '--max-count', '--after-context', '--before-context', '--context', '--include', '--exclude', '--exclude-dir'] },
1081
+ };
1082
+ function filterPart(prog, args, at) {
1083
+ if (prog === 'uniq') {
1084
+ const r = operandsOf(args, { bool: ['-c', '-d', '-u', '-i', '--count', '--repeated', '--unique', '--ignore-case'] });
1085
+ // A second operand is the file uniq WRITES.
1086
+ return Boolean(r && r.ops.length <= 1 && r.ops.every((f) => insideProject(f, at)));
1087
+ }
1088
+ if (prog === 'tr') {
1089
+ const r = operandsOf(args, { bool: ['-d', '-s', '-c', '-C', '--delete', '--squeeze-repeats', '--complement'] });
1090
+ return Boolean(r && r.ops.length >= 1 && r.ops.length <= 2);
1091
+ }
1092
+ const spec = FILTERS[prog];
1093
+ if (!spec) return false;
1094
+ const r = operandsOf(args, spec);
1095
+ if (!r) return false;
1096
+ // grep's first operand is its pattern, unless one came with -e.
1097
+ const files = prog === 'grep' && !r.values['-e'] && !r.values['--regexp'] ? r.ops.slice(1) : r.ops;
1098
+ if (prog === 'grep' && !r.values['-e'] && !r.values['--regexp'] && !r.ops.length) return false;
1099
+ return files.every((f) => insideProject(f, at));
1100
+ }
1101
+
1102
+ const JQ_SPEC = { bool: ['-r', '-j', '-c', '-n', '-s', '-e', '-a', '-S', '-C', '-M', '--raw-output', '--join-output', '--compact-output', '--null-input',
1103
+ '--slurp', '--exit-status', '--ascii-output', '--sort-keys', '--color-output', '--monochrome-output', '--tab', '--seq', '--stream', '--raw-output0', '--raw-input', '-R'],
1104
+ // Not -f / --from-file: the filter would come from a file this does not read (it could hold `env`); not -L.
1105
+ value: ['--indent'], pairs: ['--arg', '--argjson', '--slurpfile', '--rawfile'] };
1106
+ // `env` and `$ENV` print the environment, where the platform tokens live; `import` and `include` read a file
1107
+ // from any path. A filter that only names a field `.env` is caught too: it gets the prompt, which is safe.
1108
+ const READS_ENV = /\benv\b|\bENV\b|\$__prog_args\b|\bimport\b|\binclude\b/;
1109
+ function jqPart(args, at) {
1110
+ const r = operandsOf(args, JQ_SPEC);
1111
+ if (!r) return false;
1112
+ const filter = r.ops[0];
1113
+ if (filter === undefined || READS_ENV.test(filter)) return false;
1114
+ for (const [, f] of [...(r.values['--slurpfile'] ?? []), ...(r.values['--rawfile'] ?? [])]) if (!insideProject(f, at)) return false;
1115
+ return r.ops.slice(1).every((f) => insideProject(f, at));
1116
+ }
1117
+
1118
+ // `gh api` / `glab api`: a GET of a REST path, with only the options that keep it one.
1119
+ const API_SPEC = { bool: ['--paginate', '--slurp', '-i', '--include', '--silent', '--verbose'], value: ['-X', '--method', '-H', '--header', '-q', '--jq', '-t', '--template', '-p', '--preview'] };
1120
+ // (Not --cache: it writes gh's cache files, outside the project.)
1121
+ // Any path segment that names a secret, token, variable, key or hook (`gpg_keys`, `webhooks`, `access_tokens`),
1122
+ // a person's e-mail addresses, a pipeline trigger (its token), an integration or service (a webhook URL), a
1123
+ // credential, CI logs, traces and artifacts (masking there is best effort, or none), GitLab's secure files,
1124
+ // Terraform state, pipeline schedules (one lists its variables with their values) and admin settings, and
1125
+ // GitLab's `user` (the caller's private e-mail).
1126
+ const NEVER_PATH = /secret|secure|token|variable|key|hook|email|trigger|integration|service|credential|terraform|schedule|artifact|^logs$|^trace$|^application$|^user$/i;
1127
+ function apiPart(prog, args) {
1128
+ const r = operandsOf(args, API_SPEC);
1129
+ if (!r || r.ops.length !== 1) return false;
1130
+ const methods = [...(r.values['-X'] ?? []), ...(r.values['--method'] ?? [])];
1131
+ if (methods.some((m) => String(m).toUpperCase() !== 'GET')) return false;
1132
+ if ([...(r.values['-H'] ?? []), ...(r.values['--header'] ?? [])].some((h) => !/^accept\s*:/i.test(String(h)))) return false;
1133
+ if ([...(r.values['-q'] ?? []), ...(r.values['--jq'] ?? [])].some((q) => READS_ENV.test(String(q)))) return false;
1134
+ const endpoint = r.ops[0];
1135
+ if (/^[a-z][a-z0-9+.-]*:|^\/\//i.test(endpoint) || /\$/.test(endpoint)) return false;
1136
+ // Decoded first, then split, so `user%2F` is two parts; each part is tested as written and without a format
1137
+ // suffix (`user.json`).
1138
+ const bare = decodeURIComponent(endpoint.split(/[?#]/)[0]);
1139
+ if (bare.replace(/^\/+/, '') === 'graphql') return false;
1140
+ if (bare.split('/').some((seg) => NEVER_PATH.test(seg) || NEVER_PATH.test(seg.replace(/\.[A-Za-z0-9]*$/, '')))) return false;
1141
+ return apiMethod([prog, 'api', ...args]) === 'GET';
1142
+ }
1143
+
1144
+ const GIT_READS = new Set(['log', 'status', 'diff', 'show', 'rev-parse', 'ls-files', 'blame']);
1145
+ // The options that write a file, read one from anywhere, or run a program. git accepts any unique shortening of a
1146
+ // long option in some commands (`git blame --conten=/etc/hosts` is `--contents`), so a long option is refused
1147
+ // when it is a prefix of one of these, not only when it equals one. The short ones: blame's `-S <file>`,
1148
+ // ls-files' `-X <file>`, diff's `-O<file>`, in any cluster.
1149
+ const GIT_RISKY = ['--output', '--output-directory', '--ext-diff', '--textconv', '--no-index', '--contents', '--open-files-in-pager', '--ignore-revs-file',
1150
+ '--exclude-from', '--exclude-per-directory', '--pathspec-from-file', '--orderfile', '--show-signature', '--rotate-to', '--skip-to'];
1151
+ // Real options that happen to begin a risky one: allowed as written.
1152
+ const GIT_EXACT_SAFE = new Set(['--text', '--ignore-rev', '--output-indicator-new', '--output-indicator-old', '--output-indicator-context']);
1153
+ // The short options that read a file, by command: blame's `-S <file>`, ls-files' `-X <file>`, `-O<file>` (diff's
1154
+ // order file). `git log -S <text>` is a search, not a file, so it stays.
1155
+ const GIT_RISKY_SHORT = { blame: 'S', 'ls-files': 'X', diff: 'O', log: 'O', show: 'O' };
1156
+ function gitPart(args, at) {
1157
+ if (!GIT_READS.has(args[0])) return false;
1158
+ const shortRisk = GIT_RISKY_SHORT[args[0]] ?? '';
1159
+ let afterDashes = false;
1160
+ for (const a of args.slice(1)) {
1161
+ if (a === '--') { afterDashes = true; continue; }
1162
+ // `%G…` in a format makes git check signatures, which runs gpg.
1163
+ if (/%G/.test(a)) return false;
1164
+ if (!afterDashes && a.startsWith('--')) {
1165
+ const name = a.split('=')[0];
1166
+ if (!GIT_EXACT_SAFE.has(name) && name.length > 2 && GIT_RISKY.some((r) => r.startsWith(name))) return false;
1167
+ } else if (!afterDashes && a.startsWith('-') && shortRisk && new RegExp(`^-[A-Za-z]*[${shortRisk}]`).test(a)) return false;
1168
+ // `git diff` turns to --no-index by itself when a path is outside the repo, and prints both files: every path
1169
+ // it is given must be inside the project. A ref (`main`, `origin/main`, `HEAD~1`) reads as one inside.
1170
+ else if (args[0] === 'diff' && (afterDashes || !a.startsWith('-')) && !insideProject(a, at)) return false;
1171
+ }
1172
+ return true;
1173
+ }
1174
+
1175
+ // A read gate run from checks/, unchanged from the copy this yadflow ships.
1176
+ function gatePart(prog, args, at) {
1177
+ const file = args[0] ?? '';
1178
+ const name = file.replace(/^\.\//, '');
1179
+ const m = /^checks\/([A-Za-z0-9._-]+)$/.exec(name);
1180
+ if (!m || !PREAPPROVED_GATES.includes(m[1])) return false;
1181
+ if (m[1].endsWith('.mjs') ? prog !== 'node' : !(prog === 'bash' || prog === 'sh')) return false;
1182
+ if (!insideProject(name, at)) return false;
1183
+ try {
1184
+ return fs.readFileSync(path.resolve(at.cwd, name)).equals(fs.readFileSync(path.join(SHIPPED_CHECKS, m[1])));
1185
+ } catch { return false; }
1186
+ }
1187
+
1188
+ function yadPart(args) {
1189
+ const { words, flags } = yadWords(args);
1190
+ // yad's own reading of the words and flags must be a read too (`check --fix` is not, whatever the prefix).
1191
+ if (classify(words, flags) !== 'read') return false;
1192
+ const key = words.join(' ');
1193
+ return readAllowList().some((rule) => {
1194
+ const k = rule.slice('Bash(yad '.length, -':*)'.length);
1195
+ return key === k || key.startsWith(`${k} `);
1196
+ });
1197
+ }
1198
+
1199
+ // What one part of the line is, when it is a read this pre-approves; else null.
1200
+ function readKind(words, at) {
1201
+ if (!words.length) return null;
1202
+ const [prog, ...args] = words;
1203
+ // A bare program name: no path (a script that shares a name), no `VAR=value`, no prefix (`env`, `sudo`, …).
1204
+ if (!/^[a-z][a-z0-9_-]*$/.test(prog) || PREFIXES.has(prog)) return null;
1205
+ if ((prog === 'gh' || prog === 'glab') && args[0] === 'api') return apiPart(prog, args.slice(1)) ? `${prog} api GET` : null;
1206
+ if (prog === 'git') return gitPart(args, at) ? `git ${args[0]}` : null;
1207
+ if (prog === 'jq') return jqPart(args, at) ? 'jq' : null;
1208
+ if (prog === 'yad') return yadPart(args) ? 'a read-only yad command' : null;
1209
+ if (prog === 'bash' || prog === 'sh' || prog === 'node') return gatePart(prog, args, at) ? `the ${args[0].replace(/^\.\/|^checks\//g, '')} gate` : null;
1210
+ return filterPart(prog, args, at) ? prog : null;
1211
+ }
1212
+
1213
+ // `{ preapproved: true, reason }` when every part of the line is a read named above, else `{ preapproved: false }`.
1214
+ // It never judges a refusal: the caller asks `agentGuardDecision` first, and a refused line is never pre-approved.
1215
+ // `cwd` is where the line runs (files resolve from it); `root` is the project, and `cwd` must be inside it — an
1216
+ // agent that changed to `/` would otherwise make every file "inside".
1217
+ export function agentGuardPreapproval(line, { cwd = process.cwd(), root = cwd } = {}) {
1218
+ const no = { preapproved: false };
1219
+ try {
1220
+ if (typeof line !== 'string' || !line.trim() || !agentGuardDecision(line).allow) return no;
1221
+ // The reader replaces these (the brace shield), so a file named with one would be judged under another name.
1222
+ if (/[\uE000-\uE002]/.test(line)) return no;
1223
+ const at = { cwd: path.resolve(root, cwd), root };
1224
+ if (!insideProject('.', at)) return no;
1225
+ const clean = blankHarmlessRedirects(line);
1226
+ if (clean === null) return no;
1227
+ const parts = shellParts(clean);
1228
+ if (!parts.length || parts.subs.length || clean.includes('`') || /\$\(/.test(clean)) return no;
1229
+ const kinds = [];
1230
+ for (const words of parts) {
1231
+ const kind = readKind(words, at);
1232
+ if (!kind) return no;
1233
+ if (!kinds.includes(kind)) kinds.push(kind);
1234
+ }
1235
+ return { preapproved: true, reason: kinds.join(', ') };
1236
+ } catch {
1237
+ return no;
1238
+ }
1239
+ }