yadflow 4.10.0 → 4.12.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 (120) hide show
  1. package/CHANGELOG.md +152 -0
  2. package/README.md +14 -3
  3. package/bin/commands.mjs +7 -1
  4. package/bin/yad.mjs +163 -16
  5. package/cli/agent-guard-worker.mjs +13 -0
  6. package/cli/agent-guard.mjs +1053 -57
  7. package/cli/agent-rules.mjs +59 -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 +345 -0
  26. package/cli/brain.mjs +810 -0
  27. package/cli/brand-cmd.mjs +326 -0
  28. package/cli/brand.mjs +327 -0
  29. package/cli/ci-check.mjs +3 -3
  30. package/cli/doctor.mjs +145 -14
  31. package/cli/epic-state.mjs +93 -1
  32. package/cli/epic.mjs +15 -3
  33. package/cli/errors.mjs +2 -1
  34. package/cli/find-product.mjs +69 -15
  35. package/cli/foundation-publish.mjs +256 -0
  36. package/cli/gate.mjs +29 -3
  37. package/cli/git-read.mjs +38 -0
  38. package/cli/guard-stream.mjs +409 -0
  39. package/cli/guide.mjs +26 -3
  40. package/cli/hook.mjs +59 -9
  41. package/cli/issues-act.mjs +57 -13
  42. package/cli/issues-write.mjs +19 -6
  43. package/cli/issues.mjs +69 -24
  44. package/cli/lib.mjs +37 -2
  45. package/cli/local-page.mjs +138 -0
  46. package/cli/local-setup-record.mjs +71 -0
  47. package/cli/local-setup-steps.mjs +186 -0
  48. package/cli/local-setup.mjs +611 -0
  49. package/cli/machine.mjs +1 -1
  50. package/cli/manifest.mjs +55 -0
  51. package/cli/map/view/app.js +712 -0
  52. package/cli/map/view/index.html +50 -0
  53. package/cli/map/view/style.css +142 -0
  54. package/cli/map-view.mjs +190 -0
  55. package/cli/map.mjs +637 -0
  56. package/cli/members.mjs +9 -15
  57. package/cli/next.mjs +1 -1
  58. package/cli/openpr.mjs +2 -2
  59. package/cli/plain-text.mjs +22 -0
  60. package/cli/plan.mjs +310 -36
  61. package/cli/platform.mjs +5 -5
  62. package/cli/product-index.mjs +1 -1
  63. package/cli/protection.mjs +32 -0
  64. package/cli/reconcile.mjs +61 -13
  65. package/cli/report.mjs +9 -3
  66. package/cli/reports-dir.mjs +393 -0
  67. package/cli/reports.mjs +65 -0
  68. package/cli/run-checks.mjs +5 -2
  69. package/cli/scan.mjs +4 -6
  70. package/cli/secret-text.mjs +66 -0
  71. package/cli/setup.mjs +54 -8
  72. package/cli/standup.mjs +94 -72
  73. package/cli/status.mjs +6 -5
  74. package/cli/test-agents-file.mjs +614 -8
  75. package/cli/test-brain-activity.mjs +753 -0
  76. package/cli/test-brain-view.mjs +381 -0
  77. package/cli/test-brain.mjs +795 -0
  78. package/cli/test-brand.mjs +558 -0
  79. package/cli/test-guide.mjs +438 -0
  80. package/cli/test-local-setup.mjs +1188 -0
  81. package/cli/test-machine.mjs +59 -0
  82. package/cli/test-map.mjs +615 -0
  83. package/cli/test-reports.mjs +382 -0
  84. package/cli/test-run-checks.mjs +4 -0
  85. package/cli/test-worktree.mjs +24 -3
  86. package/cli/toolbox-connect.mjs +21 -6
  87. package/cli/toolbox.mjs +74 -5
  88. package/cli/update-commit.mjs +118 -9
  89. package/cli/usage.mjs +17 -7
  90. package/cli/workspace.mjs +11 -2
  91. package/package.json +8 -4
  92. package/skills/sdlc/module-help.csv +1 -0
  93. package/skills/yad-architecture/SKILL.md +22 -4
  94. package/skills/yad-brand/SKILL.md +69 -0
  95. package/skills/yad-change/SKILL.md +3 -1
  96. package/skills/yad-change/references/triage.md +2 -0
  97. package/skills/yad-checks/SKILL.md +2 -0
  98. package/skills/yad-checks/references/check-gates.md +8 -5
  99. package/skills/yad-checks/templates/checks/build-test-lint.sh +7 -0
  100. package/skills/yad-checks/templates/checks/install-deps.sh +6 -0
  101. package/skills/yad-checks/templates/checks/package-manager.sh +42 -0
  102. package/skills/yad-checks/templates/github/yad-checks.yml +3 -2
  103. package/skills/yad-checks/templates/gitlab/yad-checks.gitlab-ci.yml +3 -2
  104. package/skills/yad-checks/templates/hooks/local-setup-notice.mjs +96 -0
  105. package/skills/yad-checks/templates/hooks/yad-activity.mjs +238 -0
  106. package/skills/yad-connect-repos/SKILL.md +14 -0
  107. package/skills/yad-discovery/SKILL.md +11 -0
  108. package/skills/yad-discovery/references/foundation-schema.md +11 -0
  109. package/skills/yad-docs/templates/app/package-lock.json +18 -10
  110. package/skills/yad-docs/templates/app/package.json +6 -1
  111. package/skills/yad-epic/SKILL.md +3 -0
  112. package/skills/yad-epic/references/state-schema.md +35 -1
  113. package/skills/yad-guide/SKILL.md +10 -7
  114. package/skills/yad-implement/SKILL.md +76 -15
  115. package/skills/yad-issues/SKILL.md +2 -1
  116. package/skills/yad-pr-template/templates/checks/pr-template.sh +8 -4
  117. package/skills/yad-pr-template/templates/checks/pr-title.sh +8 -4
  118. package/skills/yad-spec/SKILL.md +19 -0
  119. package/skills/yad-stories/SKILL.md +22 -4
  120. package/skills/yad-stories/references/story-schema.md +1 -1
@@ -0,0 +1,409 @@
1
+ // Output reading (#532): a pass beside the guard's own readings. It follows what each command prints, byte by
2
+ // byte, so a print with no newline runs on into the next one as in a real shell, and it judges any text that
3
+ // reaches a shell (a pipe into `bash`, a file then run, `bash <(…)`). It never adds an entry to the guard's lists
4
+ // paired by place (zipJoin, printedOf, …), and it runs only after the guard's own reading allowed the line, so it
5
+ // can only add refusals.
6
+ //
7
+ // bash and zsh print some things differently (zsh's `echo` always makes escapes, `%b` and `\c` differ), so the
8
+ // pass runs once as bash reads the line and, when they may differ (`zshDiffers`), once more as zsh reads it.
9
+ import path from 'node:path';
10
+
11
+ const SHELL_PROG = /^(?:bash|sh|zsh|dash|ksh|source|\.)$/;
12
+ // A compound command's last part: its output, and its redirects, are the whole command's.
13
+ const CLOSERS = new Set(['}', 'fi', 'done', 'esac']);
14
+ // Each opener with the word that closes it.
15
+ const OPENERS = new Map([['if', 'fi'], ['for', 'done'], ['while', 'done'], ['until', 'done'], ['select', 'done'], ['case', 'esac']]);
16
+ // Reserved words that may stand before a compound command in the same part (`then while …`, `{ if …`, `! for …`).
17
+ const LEAD = new Set(['{', '(', 'then', 'do', 'else', 'elif', '!', 'time']);
18
+ // The part's first word that is not one of those (`time -p for …` too).
19
+ const headOf = (ws) => { let i = 0; while (i < ws.length && (LEAD.has(ws[i]) || (ws[i - 1] === 'time' && ws[i] === '-p'))) i++; return ws[i]; };
20
+ // Every text a file may hold is kept (a write that may not run hides none before it, as in the guard's own
21
+ // file reading); past this many for one file the line is refused.
22
+ const MAX_TEXTS = 64;
23
+ // A `printf` width past this is refused, not built (`%999999999s`).
24
+ const MAX_WIDTH = 65536;
25
+ // Process substitutions nested past this many are refused as too deep.
26
+ const PROC_LEVELS = 16;
27
+ const LIMIT = 'YAD_GUARD_OUTPUT_LIMIT';
28
+ const fail = (message, code = LIMIT) => Object.assign(new Error(message), { code });
29
+
30
+ // True when zsh may print the line differently from bash: an escape (a backslash), or zsh's `echo -`.
31
+ export const zshDiffers = (line) => line.includes('\\') || /(?:^|[\s;&|({])echo\s+-(?:\s|$)/.test(line);
32
+
33
+ // The characters a `tr` set names: escapes, ranges and the common classes. null for what is not read
34
+ // (`[=c=]`, `[c*n]`, an unknown class): its output is then unknown, as before.
35
+ const CLASSES = { space: /\s/, blank: /[ \t]/, cntrl: { test: (c) => c < ' ' || c === '\x7f' }, digit: /\d/, lower: /[a-z]/, upper: /[A-Z]/,
36
+ alpha: /[A-Za-z]/, alnum: /[A-Za-z0-9]/, punct: /[!-/:-@[-`{-~]/, print: /[ -~]/, graph: /[!-~]/ };
37
+ function trSet(s) {
38
+ if (s === undefined) return null;
39
+ const chars = [];
40
+ let i = 0;
41
+ const one = () => {
42
+ if (s[i] === '\\' && i + 1 < s.length) {
43
+ const oct = /^[0-7]{1,3}/.exec(s.slice(i + 1));
44
+ if (oct) { i += 1 + oct[0].length; return String.fromCharCode(parseInt(oct[0], 8) & 255); }
45
+ const c = s[i + 1];
46
+ i += 2;
47
+ return ({ n: '\n', t: '\t', r: '\r', a: '\x07', b: '\b', f: '\f', v: '\v' })[c] ?? c;
48
+ }
49
+ return s[i++];
50
+ };
51
+ while (i < s.length) {
52
+ const cls = /^\[:(\w+):\]/.exec(s.slice(i));
53
+ if (cls) {
54
+ const re = CLASSES[cls[1]];
55
+ if (!re) return null;
56
+ for (let c = 0; c < 128; c++) if (re.test(String.fromCharCode(c))) chars.push(String.fromCharCode(c));
57
+ i += cls[0].length;
58
+ continue;
59
+ }
60
+ if (/^\[(?:=.=\]|.\*)/.test(s.slice(i))) return null;
61
+ const a = one();
62
+ if (s[i] === '-' && i + 1 < s.length) {
63
+ i++;
64
+ const b = one();
65
+ const from = a.charCodeAt(0), to = b.charCodeAt(0);
66
+ if (to < from || to - from > 512) return null;
67
+ for (let c = from; c <= to; c++) chars.push(String.fromCharCode(c));
68
+ } else chars.push(a);
69
+ }
70
+ return chars;
71
+ }
72
+
73
+ export function streamGuard(line, mode, api, zsh = false) {
74
+ const files = new Map();
75
+ let verdict = { allow: true };
76
+ const charge = api.charge;
77
+ const copy = (s) => { charge(s.length + 1); return s; };
78
+ const join = (xs) => { for (const x of xs) charge(x.length + 1); return xs.join(''); };
79
+ // A file's name as the reader records a redirect's target, with no backslash (the run's word keeps the one the
80
+ // shell keeps in double quotes): `> "a\b"; bash "a\b"` is one file (#532 review 2). Two names may share one.
81
+ const key = (s) => path.posix.normalize(s.replace(/\\/g, ''));
82
+ // Every text the file may hold, one after another on lines of their own: no two are read as one line.
83
+ // Each text on its own, for a shell that runs the file: joined, an open quote in one would hide the next
84
+ // (#532 review 2). Past MAX_TEXTS a file is refused only when read, not when written.
85
+ const textsOf = (s) => {
86
+ const texts = files.get(key(s));
87
+ if (!texts) return [];
88
+ if (texts.over) throw fail('too many writes to one file');
89
+ for (const t of texts) charge(t.length + 1);
90
+ return texts.slice();
91
+ };
92
+ const read = (s) => join(textsOf(s).flatMap((t, i) => i ? ['\n', t] : [t]));
93
+ // A `>` adds a text (the same text again only moves to the end, as the guard's own set of a file's texts
94
+ // keeps it once); a `>>` adds to each one.
95
+ const write = (wr, text) => {
96
+ const k = key(wr.target);
97
+ const t = copy(text);
98
+ const texts = files.get(k);
99
+ if (!texts) { files.set(k, [t]); return; }
100
+ // Texts that differ still differ with the same text added, so a `>>` makes no two the same.
101
+ if (wr.append) { for (let i = 0; i < texts.length; i++) { charge(t.length + 1); texts[i] += t; } return; }
102
+ const at = texts.indexOf(t);
103
+ if (at >= 0) texts.splice(at, 1);
104
+ else if (texts.length >= MAX_TEXTS) { texts.over = true; return; }
105
+ texts.push(t);
106
+ };
107
+ const check = (s) => { if (s && verdict.allow) verdict = api.judge(s); };
108
+
109
+ // The octal escapes each reader makes (checked in a real bash 3.2 and zsh 5.9): `echo` (bash's with -e) and
110
+ // zsh's `%b` read `\0NNN` only; bash's `%b` also reads `\NNN`; a `printf` format and zsh's `print` read `\NNN`,
111
+ // so `\0405` there is `\040` and `5`.
112
+ const OCTAL = { echo: '0[0-7]{0,3}', b: zsh ? '0[0-7]{0,3}' : '0[0-7]{0,3}|[1-7][0-7]{0,2}', fmt: '[0-7]{1,3}' };
113
+ const ESC = Object.fromEntries(Object.entries(OCTAL).map(([k, o]) => [k, {
114
+ any: new RegExp(`\\\\(x[\\da-fA-F]{1,2}|${o}|[\\s\\S])`, 'g'), octal: new RegExp(`^(?:${o})$`) }]));
115
+ const LETTERS = { n: '\n', t: '\t', r: '\r', a: '\x07', b: '\b', e: '\x1b', E: '\x1b', f: '\f', v: '\v', '\\': '\\' };
116
+ // `\c` ends all output; in a format bash 3.2 prints it as it is, zsh stops.
117
+ function escapes(s, kind, stopAtC = kind !== 'fmt' || zsh) {
118
+ const { any, octal } = ESC[kind];
119
+ any.lastIndex = 0;
120
+ let text = '', from = 0, m;
121
+ while ((m = any.exec(s))) {
122
+ text += s.slice(from, m.index);
123
+ from = any.lastIndex;
124
+ const c = m[1];
125
+ if (c === 'c' && stopAtC) return { text, stopped: true };
126
+ if (c.length > 1 && c[0] === 'x') text += String.fromCharCode(parseInt(c.slice(1), 16));
127
+ else if (octal.test(c)) text += String.fromCharCode(parseInt(c, 8) & 255);
128
+ else text += LETTERS[c] ?? `\\${c}`;
129
+ }
130
+ return { text: text + s.slice(from), stopped: false };
131
+ }
132
+ // What `printf` (or `print -f`) prints: its format, used again while words are left, with `%s`, `%b`, `%c`,
133
+ // the numbers, widths and precisions filled from its words.
134
+ const CONV = /%([-+ #0]*)(\*|\d+)?(?:\.(\*|\d*))?([a-zA-Z%])/g;
135
+ function formatted(args) {
136
+ const fmt = args[0] ?? '', rest = args.slice(1);
137
+ const out = [];
138
+ let at = 0, stop = false;
139
+ for (;;) {
140
+ let from = 0, used = false;
141
+ for (const m of fmt.matchAll(CONV)) {
142
+ const lit = escapes(fmt.slice(from, m.index), 'fmt');
143
+ out.push(copy(lit.text));
144
+ if (lit.stopped) { stop = true; break; }
145
+ from = m.index + m[0].length;
146
+ const [, flags, w, p, conv] = m;
147
+ if (conv === '%') { out.push('%'); continue; }
148
+ used = true;
149
+ const width = w === '*' ? Number.parseInt(rest[at++] ?? '0', 10) || 0 : Number(w ?? 0);
150
+ const prec = p === undefined ? undefined : p === '*' ? Number.parseInt(rest[at++] ?? '0', 10) || 0 : Number(p || 0);
151
+ const arg = rest[at++] ?? '';
152
+ let text = arg;
153
+ if (conv === 'b') { const r = escapes(arg, 'b'); text = r.text; if (r.stopped) stop = true; }
154
+ else if (conv === 'c') text = arg.slice(0, 1);
155
+ else if ('diu'.includes(conv)) text = String(Number.parseInt(arg, 10) || 0);
156
+ if (prec !== undefined && 'sb'.includes(conv)) text = text.slice(0, prec);
157
+ if (Math.abs(width) > MAX_WIDTH) throw fail('printf width too large');
158
+ if (Math.abs(width) > text.length) text = flags.includes('-') || width < 0 ? text.padEnd(Math.abs(width)) : text.padStart(width);
159
+ out.push(copy(text));
160
+ if (stop) break;
161
+ }
162
+ if (stop) break;
163
+ const tail = escapes(fmt.slice(from), 'fmt');
164
+ out.push(copy(tail.text));
165
+ if (tail.stopped || !used || at >= rest.length) break;
166
+ }
167
+ return join(out);
168
+ }
169
+ function run(text, level = 0, stdin = '', procLevel = 0) {
170
+ // `$(…)` and shells nest as the guard counts them (its TOO_DEEP). Process substitutions count on their own,
171
+ // deeper (#532 review 10): each level parses its text again, so 1,500 of them overflowed the stack (review 2).
172
+ if (level > 3) throw fail('output nesting limit exceeded', 'YAD_GUARD_TOO_DEEP');
173
+ if (procLevel > PROC_LEVELS) throw fail('process substitutions nested too deep', 'YAD_GUARD_TOO_MANY_PROCSUBS');
174
+ const fileSub = /^\s*<\s*([^\s;&|<>()$`'"\\]+)\s*$/.exec(text);
175
+ if (fileSub) return read(fileSub[1]);
176
+ if (/^[A-Za-z0-9_]*$/.test(text) && !/^(echo|printf|print|cat|tee|eval|bash|zsh|sh|dash|ksh)$/.test(text)) return '';
177
+ const parts = api.shellParts(text, mode);
178
+ if (parts.tooComplex) throw fail('output parse budget exceeded');
179
+ const stdout = [];
180
+ const indexed = (xs, at) => { const m = new Map(); for (const x of xs) { const k = at(x); if (!m.has(k)) m.set(k, []); m.get(k).push(x); } return m; };
181
+ const bodies = indexed(parts.bodies, (x) => x.part);
182
+ const heres = indexed(parts.herestrings, (x) => x.part);
183
+ const procs = indexed(parts.procsubs, (x) => x.from - 1);
184
+ const pipedWrites = indexed(parts.pipedWrites, (x) => x.after);
185
+ let before = '';
186
+ // Groups by the part they close at: `{ … }` and `( … )` from the reader, and the compound commands
187
+ // (`if … fi`, `for … done`, `case … esac`) found here, so the reader's own records stay as they are.
188
+ const groups = new Map();
189
+ const addGroup = (g) => { if (!groups.has(g.to)) groups.set(g.to, []); groups.get(g.to).push(g); };
190
+ for (const g of parts.groups) addGroup(g);
191
+ // A closer closes only its own opener: inside a `case`, a pattern spelled `done` or `fi` closes nothing
192
+ // (#532 review 2), and a mismatched one is left alone rather than pairing with the wrong opener.
193
+ const opened = [];
194
+ const patterns = new Set();
195
+ // The real (not `maybe`) openers, kept beside `opened` so the innermost one is read in one step, not a scan
196
+ // (a scan made deep nests quadratic). A pattern stands only straight inside a `case` (review 5).
197
+ const real = [];
198
+ const push = (o) => { opened.push(o); if (!o.maybe) real.push(o); };
199
+ const pop = () => { const o = opened.pop(); if (!o.maybe) real.pop(); return o; };
200
+ for (let n = 0; n < parts.length; n++) {
201
+ const w = headOf(parts[n]);
202
+ // Inside an open `case`, a part that is one reserved word may be a pattern (`while)`, `done)`), which opens
203
+ // and closes nothing and prints nothing (#532 review 3). One-word `if`, `while` and `until` may also start a
204
+ // real block (bash and zsh allow a newline after them, review 4), so they are kept as openers that may be
205
+ // patterns: a closer that does not match one drops it, and it was a pattern after all.
206
+ const inCase = real.at(-1)?.end === 'esac';
207
+ const alone = parts[n].length === 1;
208
+ if (OPENERS.has(w)) {
209
+ if (inCase && alone && !['if', 'while', 'until'].includes(w)) patterns.add(n);
210
+ else push({ n, end: OPENERS.get(w), maybe: inCase && alone });
211
+ } else if (w === '}') {
212
+ // A lone `}` that closes no `{ … }` is a pattern inside a `case` too (`'}')`, review 4).
213
+ if (inCase && alone && !(groups.get(n) ?? []).some((g) => g.brace)) patterns.add(n);
214
+ } else if (CLOSERS.has(w)) {
215
+ while (opened.at(-1)?.maybe && opened.at(-1).end !== w) patterns.add(pop().n);
216
+ if (opened.at(-1)?.end === w) addGroup({ from: pop().n, to: n, writes: [], closer: true });
217
+ else if (inCase && alone && w !== 'esac') patterns.add(n);
218
+ }
219
+ }
220
+ // A closed group is folded into its first slot (`jump[from] = to`, its output, if it prints any, in
221
+ // `stdout[from]`), so an outer group reads each inner one once: nests cost their size, not the square of their
222
+ // depth (`if …; then` × 10,000 took 3 s, reviews 3 and 4). The step count stays as a backstop.
223
+ const jump = [];
224
+ const foldedAt = new Map();
225
+ let steps = 0;
226
+ const STEPS = 64 * parts.length + 100000;
227
+ let left;
228
+ const collect = (from, to) => {
229
+ const xs = [];
230
+ left = undefined;
231
+ for (let i = from; i < to;) {
232
+ if (++steps > STEPS) throw fail('blocks nested too deep to read', 'YAD_GUARD_BLOCKS_DEEP');
233
+ if (i > from && foldedAt.get(i) < from) left = Math.min(left ?? from, foldedAt.get(i));
234
+ if (stdout[i] !== undefined) xs.push(stdout[i]);
235
+ const j = jump[i];
236
+ i = j !== undefined && j > i && j <= to ? j : i + 1;
237
+ }
238
+ if (foldedAt.get(to) < from) left = Math.min(left ?? from, foldedAt.get(to));
239
+ return xs;
240
+ };
241
+ const close = (n) => {
242
+ for (const g of groups.get(n) ?? []) {
243
+ // What reaches the group's own output: not what its parts wrote to files (#532 review 9).
244
+ let from = g.from, xs = collect(from, g.to);
245
+ while (left !== undefined) { from = left; xs = collect(from, g.to); }
246
+ const output = join(xs);
247
+ before = output;
248
+ jump[from] = g.to;
249
+ // A walk that starts inside the group skips it too, and is sent back to `from` at its end.
250
+ if (from !== g.from) jump[g.from] = g.to;
251
+ foldedAt.set(g.to, Math.min(foldedAt.get(g.to) ?? from, from));
252
+ stdout[from] = '';
253
+ // A group that ends in a part of its own (`}`, `fi`, `done`, `esac`): that part prints and writes it.
254
+ if (g.brace || g.closer) continue;
255
+ if (g.writes.length) for (const wr of g.writes) write(wr, output);
256
+ else stdout[from] = output;
257
+ }
258
+ };
259
+ for (let n = 0; n < parts.length; n++) {
260
+ charge(1); close(n);
261
+ let words = [];
262
+ for (let i = 0; i < parts[n].length; i++) {
263
+ const entry = parts.subst[n]?.get(i);
264
+ // The word as the shell spells it: in double quotes bash and zsh keep a backslash before an ordinary
265
+ // character (`tr -d "\n"`, `echo "\x67h …"`), which the reader keeps as the word's posix spelling.
266
+ if (!entry) { words.push(parts.posix[n]?.get(i) ?? parts[n][i]); continue; }
267
+ const pieces = []; let from = 0;
268
+ for (const sub of entry.subs) {
269
+ pieces.push(entry.word.slice(from, sub.at), run(sub.text, level + 1, '', procLevel).replace(/\n+$/, ''));
270
+ from = sub.at + sub.len;
271
+ }
272
+ pieces.push(entry.word.slice(from));
273
+ const value = join(pieces);
274
+ if (entry.subs.every((s) => s.quoted)) words.push(value);
275
+ else for (const w of value.split(/[ \t\n]+/)) if (w) words.push(w);
276
+ }
277
+ words = api.stripPrefix(words);
278
+ const prog = api.programOf(words[0] ?? '');
279
+ const input = parts.piped.has(n) ? before : stdin;
280
+ // Piped on: the part before (or the group folded up to here) prints nothing of its own.
281
+ if (parts.piped.has(n) && n > 0) { stdout[n - 1] = ''; if (foldedAt.has(n)) stdout[foldedAt.get(n)] = ''; }
282
+ const fed = join([...((bodies.get(n) ?? []).map((b) => b.text)),
283
+ ...((heres.get(n) ?? []).map((b) => b.text + '\n'))]);
284
+ const redirected = join((parts.reads[n] ?? []).map(read));
285
+ const stdinText = () => input || fed || redirected;
286
+ let out = '';
287
+ const proc = procs.get(n) ?? [];
288
+ const procOutputs = proc.map((p) => run(p.text ?? '', level, '', procLevel + 1));
289
+ // A closing part prints its group's output. One that closes none prints what came before, as a group the
290
+ // finder missed would (`do { …; } done`, a quoted `'fi'`, review 3); only a `case` pattern prints nothing.
291
+ if (CLOSERS.has(parts[n][0])) out = patterns.has(n) && !(groups.get(n) ?? []).some((g) => g.brace || g.closer) ? '' : before;
292
+ else if (prog === 'echo') {
293
+ // zsh's `echo` always makes escapes, and its `-` ends the options; bash's makes them with -e.
294
+ let k = 1, newline = true, decode = zsh;
295
+ while (k < words.length) {
296
+ if (zsh && words[k] === '-') { k++; break; }
297
+ if (!/^-[neE]+$/.test(words[k])) break;
298
+ for (const c of words[k].slice(1)) { if (c === 'n') newline = false; else decode = c === 'e'; }
299
+ k++;
300
+ }
301
+ const t = words.slice(k).join(' '), r = decode ? escapes(t, 'echo') : { text: t, stopped: false };
302
+ out = join([r.text, newline && !r.stopped ? '\n' : '']);
303
+ } else if (prog === 'print') {
304
+ // zsh's `print`: escapes as a format makes them, unless -r or -R; -l and -N part the words; -f formats.
305
+ let k = 1, newline = true, decode = true, sep = ' ', end = '\n', fmt = null, silent = false;
306
+ while (k < words.length) {
307
+ const w = words[k];
308
+ if (w === '-' || w === '--') { k++; break; }
309
+ if (!/^-[A-Za-z]/.test(w)) break;
310
+ k++;
311
+ for (const c of w.slice(1)) {
312
+ if (c === 'n') newline = false;
313
+ else if (c === 'r' || c === 'R') decode = false;
314
+ else if (c === 'e') decode = true;
315
+ else if (c === 'l') sep = '\n';
316
+ else if (c === 'N') { sep = '\0'; end = '\0'; }
317
+ else if ('sSz'.includes(c)) silent = true;
318
+ else if ('fvuCxX'.includes(c)) {
319
+ // An option that takes a value takes the rest of the word (`-u1`, `-f'%s '`), or else the next word.
320
+ const rest = w.slice(w.indexOf(c) + 1);
321
+ const value = rest || (words[k++] ?? '');
322
+ if (c === 'f') fmt = value;
323
+ else if (c === 'v' || (c === 'u' && value !== '1')) silent = true;
324
+ break;
325
+ }
326
+ }
327
+ }
328
+ if (silent) out = '';
329
+ else if (fmt !== null) out = formatted([fmt, ...words.slice(k)]);
330
+ else {
331
+ const t = words.slice(k).join(sep), r = decode ? escapes(t, 'fmt', true) : { text: t, stopped: false };
332
+ out = join([r.text, newline && !r.stopped ? end : '']);
333
+ }
334
+ } else if (prog === 'printf') {
335
+ const args = words.slice(1);
336
+ if (args[0] === '--') args.shift();
337
+ // bash's `printf -v name` sets a variable and prints nothing.
338
+ out = args[0] === '-v' ? '' : formatted(args);
339
+ } else if (prog === 'cat') {
340
+ const args = words.slice(1).filter((w) => !w.startsWith('-') || w === '-');
341
+ const operands = args.map((a) => a === '-' ? stdinText() : read(a));
342
+ for (let i = 0; i < proc.length; i++) operands.splice(Math.max(0, proc[i].position - 1), 0, procOutputs[i]);
343
+ out = join(operands.length ? operands : [stdinText()]);
344
+ } else if (prog === 'tee') out = copy(stdinText());
345
+ else if (prog === 'tr') {
346
+ const opts = [];
347
+ let k = 1;
348
+ while (/^-[A-Za-z]+$/.test(words[k] ?? '')) opts.push(...words[k++].slice(1));
349
+ const s1 = trSet(words[k]), s2 = trSet(words[k + 1]);
350
+ const src = stdinText();
351
+ if (s1 && !opts.includes('c') && !opts.includes('C')) {
352
+ if (opts.includes('d')) { const del = new Set(s1); out = copy([...src].filter((ch) => !del.has(ch)).join('')); }
353
+ else if (s2?.length) {
354
+ const map = new Map();
355
+ s1.forEach((ch, i) => map.set(ch, s2[Math.min(i, s2.length - 1)]));
356
+ out = copy([...src].map((ch) => map.get(ch) ?? ch).join(''));
357
+ }
358
+ }
359
+ } else if (prog === 'head') {
360
+ let count = null;
361
+ const a = words.slice(1);
362
+ for (let j = 0; j < a.length; j++) {
363
+ const m = /^-c(\d*)$/.exec(a[j]) ?? /^--bytes=(\d+)$/.exec(a[j]);
364
+ if (m) count = m[1] || a[++j];
365
+ else if (a[j] === '--bytes') count = a[++j];
366
+ }
367
+ const c = Number(count);
368
+ if (count !== null && Number.isSafeInteger(c) && c >= 0) out = copy(Buffer.from(stdinText()).subarray(0, c).toString());
369
+ } else {
370
+ const script = api.scriptAt(words);
371
+ const body = api.innerLines(words);
372
+ // A file a shell runs is run text by text (see textsOf).
373
+ if (api.bareShell(words)) {
374
+ if (!input && !fed && parts.reads[n]?.length) for (const r of parts.reads[n]) body.push(...textsOf(r));
375
+ else body.push(stdinText());
376
+ }
377
+ if (script >= 0) body.push(...textsOf(words[script]));
378
+ if (words[0]?.includes('/')) body.push(...textsOf(words[0]));
379
+ // A process substitution the command's shell runs (#532 review 6): its stdin when it has no script
380
+ // (`bash < <(…)`, not `bash x < <(…)`), or its script, the first word after the shell's options
381
+ // (`bash <(…)`, `source <(…)`, zsh's `zsh =(…)`), never with -c or -s. Only the command word counts as the
382
+ // shell: `ls . <(…)` and `grep sh <(…)` run nothing (review 2).
383
+ const cmdAt = SHELL_PROG.test(prog) ? parts[n].indexOf(words[0]) : -1;
384
+ const opts = (ws) => ws.every((w) => w.startsWith('-') && w !== '-c' && w !== '-s');
385
+ for (let i = 0; cmdAt >= 0 && i < proc.length; i++) {
386
+ const p = proc[i];
387
+ const runs = p.viaStdin ? opts(words.slice(1)) : p.position > cmdAt && opts(parts[n].slice(cmdAt + 1, p.position));
388
+ if (runs) body.push(procOutputs[i]);
389
+ }
390
+ // The shell's stdin is the stdin of the text it runs (`bash -c bash < <(…)`, `echo … | bash -c bash`,
391
+ // review 3); a shell that reads its stdin as the script has it in `body` already.
392
+ const childIn = api.bareShell(words) ? '' : join([...proc.flatMap((p, i) => p.viaStdin ? [procOutputs[i]] : []), stdinText()]);
393
+ for (const t of body) { check(t); out = join([out, run(t, level + 1, childIn, procLevel)]); }
394
+ }
395
+ // Judge substituted commands too, but quote words so data arguments stay data.
396
+ if (parts.subst[n]) check(words.map((w) => "'" + w.replace(/'/g, "'\\''") + "'").join(' '));
397
+ const after = proc.flatMap((p) => p.after ?? []);
398
+ for (const wr of [...(parts.writes[n] ?? []), ...after]) write(wr, out);
399
+ for (const p of pipedWrites.get(n) ?? []) for (const wr of p.writes) write(wr, out);
400
+ if (prog === 'tee') for (const a of words.slice(1)) if (!a.startsWith('-')) write({ target: a, append: words.includes('-a') || words.includes('--append') }, out);
401
+ stdout[n] = parts.writes[n]?.length || after.length ? '' : out; before = out;
402
+ if (proc.length) n = Math.max(...proc.map((p) => p.to)) - 1;
403
+ }
404
+ close(parts.length);
405
+ return join(collect(0, parts.length));
406
+ }
407
+ run(line);
408
+ return verdict;
409
+ }
package/cli/guide.mjs CHANGED
@@ -33,6 +33,7 @@ import { seededSlugs } from './hook.mjs';
33
33
  import { setupQuestions } from './setup.mjs';
34
34
  import { reposBeside, insideGitRepo, PRODUCT_DIR } from './workspace.mjs';
35
35
  import { PREAPPROVED } from './agent-guard.mjs';
36
+ import { localSetupWaiting } from './local-setup.mjs';
36
37
 
37
38
  export const GUIDE_VERSION = 1;
38
39
 
@@ -392,7 +393,23 @@ export function installState(root, running = VERSION) {
392
393
  return { project: product?.version ?? null, yadflow: running, behind: rows.some((r) => r.behind) ? true : product?.behind ?? null, repos: rows.filter((r) => r.behind) };
393
394
  }
394
395
 
395
- function upkeepFor(install, { platform }) {
396
+ // The update first (an older yad misreads the files), then this machine's local setup steps (E185).
397
+ function upkeepFor(install, { platform, root }) {
398
+ const update = updateUpkeep(install, { platform });
399
+ const waiting = root ? localSetupWaiting(root) : null;
400
+ if (!waiting) return update;
401
+ const ids = [...waiting.pending, ...waiting.ask];
402
+ const why = waiting.error ? `the local setup script cannot be read (${forTerminal(waiting.error)}): read what it says, and tell the person`
403
+ : ids.length ? `steps for this machine are waiting (${ids.join(', ')}): follow the local-setup rule — show the person each step's \`purpose\`, \`impact\` and \`commands\`, run one only after their yes, then record it with \`yad local-setup done\` or \`skip\``
404
+ : 'this machine\'s local setup record cannot be read: show the person the warning it prints';
405
+ return {
406
+ agent: [...(update?.agent ?? []), agentRun('yad local-setup list --json', why)],
407
+ person: update?.person ?? [],
408
+ localSetup: waiting,
409
+ };
410
+ }
411
+
412
+ function updateUpkeep(install, { platform }) {
396
413
  if (!install.behind) return null;
397
414
  const which = install.repos.map((r) => (r.repo === 'product' ? 'the Product' : r.repo)).join(', ');
398
415
  if (!platform) {
@@ -443,7 +460,7 @@ export function buildGuide(root, { epic = null, cwd = root ?? process.cwd(), run
443
460
  const situation = { stage: 'ready', product: rel, platform, ledger: platform && verified ? 'verified' : 'local', solo, here: m.here ?? null, install };
444
461
  if (!m.setUp) return { ...base, situation: { ...situation, stage: 'no-product' }, ...noProduct(cwd, root) };
445
462
  // Upkeep rides every answer about this Product until it is done.
446
- base.upkeep = upkeepFor(install, { platform });
463
+ base.upkeep = upkeepFor(install, { platform, root });
447
464
 
448
465
  const ctx = { verified, platform, solo };
449
466
  const chosen = epic ?? m.here?.epic ?? null;
@@ -504,7 +521,13 @@ export function buildGuide(root, { epic = null, cwd = root ?? process.cwd(), run
504
521
  export function printGuide(g) {
505
522
  const s = g.step;
506
523
  if (g.upkeep) {
507
- log(`\n ${c.bold(`Upkeep first: yadflow is v${g.situation.install.yadflow}, and ${g.situation.install.repos.map((r) => `${r.repo} is on v${r.version ?? '?'}`).join(', ')}.`)}`);
524
+ const install = g.situation.install;
525
+ if (install?.behind) log(`\n ${c.bold(`Upkeep first: yadflow is v${install.yadflow}, and ${install.repos.map((r) => `${r.repo} is on v${r.version ?? '?'}`).join(', ')}.`)}`);
526
+ const ls = g.upkeep.localSetup;
527
+ if (ls) {
528
+ const n = ls.pending.length + ls.ask.length;
529
+ log(`\n ${c.bold(n ? `Local setup: ${n} step(s) for this machine are waiting for your answer.` : 'Local setup: something could not be read.')}`);
530
+ }
508
531
  for (const a of g.upkeep.agent) hand(`${c.bold(a.run)} ${c.dim(`— ${a.why}`)}`);
509
532
  for (const p of g.upkeep.person) for (const st of p.steps) info(st);
510
533
  }
package/cli/hook.mjs CHANGED
@@ -23,13 +23,15 @@
23
23
  // brick an agent's ability to edit anything the moment a config went sideways. The asymmetry is the
24
24
  // design: `ledger-guard` in CI fails closed and is what actually protects the ledger.
25
25
  import { spawnSync } from 'node:child_process';
26
+ import { setTimeout, clearTimeout } from 'node:timers';
27
+ import { Worker } from 'node:worker_threads';
26
28
  import fs from 'node:fs';
27
29
  import path from 'node:path';
28
30
  import { fileURLToPath } from 'node:url';
29
31
  import { note, readJSON, run } from './lib.mjs';
30
32
  import { isVerifiedLedger, mirrorDrift, productConfigPath, HOOK_PROJECT_DIR_ENVS, PROJECT_FILES } from './manifest.mjs';
31
33
  import { DISCOVERY_EPIC, FOUNDATION_DIR, FOUNDATION_EPIC } from './epic-state.mjs';
32
- import { agentGuardDecision, agentGuardPreapproval, payloadCommand, isCursorPayload } from './agent-guard.mjs';
34
+ import { payloadCommand, isCursorPayload, JUDGE_BUDGET_MS } from './agent-guard.mjs';
33
35
 
34
36
  // The CI-owned files, exactly as `templates/checks/ledger-guard.sh` lists them. NOT `contract-lock.json`
35
37
  // (artifact-side: the architect commits it with the architecture) and NOT `change.json` — both are a
@@ -649,25 +651,30 @@ export function runLedgerGuardHook({ paths = [], format = 'exit' } = {}) {
649
651
  // a PreToolUse "allow" on stdout, so it runs with no permission prompt; any other allowed line gets no answer
650
652
  // (exit 0, nothing printed), which leaves the prompt to Claude Code as before. `YAD_NO_PREAPPROVE=1` keeps the
651
653
  // refusals and drops this half. Cursor's answer is unchanged.
652
- export function runAgentGuardHook({ format = null } = {}) {
654
+ //
655
+ // Fail-closed when judging fails (#498): the decision runs in a worker with a memory cap and a time limit
656
+ // (cli/agent-guard-worker.mjs). A line that runs it out of memory, past the limit, or into an error is refused:
657
+ // a hook that crashed would exit with a code the harness reads as no answer, and the command would run.
658
+ export async function runAgentGuardHook({ format = null } = {}) {
653
659
  const payload = readPayload();
654
660
  const cursor = format ? format === 'cursor' : isCursorPayload(payload);
655
661
  if (format && !HOOK_FORMATS.includes(format)) {
656
662
  note(`yad hook: unknown --format '${format}' — using '${HOOK_FORMATS[0]}' (known: ${HOOK_FORMATS.join(', ')})`);
657
663
  }
658
- const verdict = process.env.YAD_HOOK_DISABLE ? { allow: true } : agentGuardDecision(payloadCommand(payload));
664
+ // Claude Code names the project in CLAUDE_PROJECT_DIR and where the command runs in the payload's `cwd`.
665
+ const root = process.env.CLAUDE_PROJECT_DIR || process.cwd();
666
+ const preapproval = !cursor && !process.env.YAD_NO_PREAPPROVE ? { root, cwd: typeof payload?.cwd === 'string' && payload.cwd ? payload.cwd : root } : null;
667
+ // No command to judge (no payload, or none in it) fails open without a worker, as before.
668
+ const command = payloadCommand(payload);
669
+ const skip = process.env.YAD_HOOK_DISABLE || typeof command !== 'string' || !command.trim();
670
+ const { verdict, pre } = skip ? { verdict: { allow: true }, pre: null } : await judgeInWorker(command, preapproval);
659
671
  if (cursor) {
660
672
  process.stdout.write(`${verdict.allow ? CURSOR_ALLOW : cursorDeny(verdict.message)}\n`);
661
673
  if (!verdict.allow) console.error(verdict.message);
662
674
  return 0;
663
675
  }
664
676
  if (verdict.allow) {
665
- if (!process.env.YAD_HOOK_DISABLE && !process.env.YAD_NO_PREAPPROVE) {
666
- // Claude Code names the project in CLAUDE_PROJECT_DIR and where the command runs in the payload's `cwd`.
667
- const root = process.env.CLAUDE_PROJECT_DIR || process.cwd();
668
- const pre = agentGuardPreapproval(payloadCommand(payload), { root, cwd: typeof payload?.cwd === 'string' && payload.cwd ? payload.cwd : root });
669
- if (pre.preapproved) process.stdout.write(`${claudePreapproval(pre.reason)}\n`);
670
- }
677
+ if (pre?.preapproved) process.stdout.write(`${claudePreapproval(pre.reason)}\n`);
671
678
  return 0;
672
679
  }
673
680
  console.error(verdict.message);
@@ -675,6 +682,49 @@ export function runAgentGuardHook({ format = null } = {}) {
675
682
  return 2;
676
683
  }
677
684
 
685
+ // The worker's limits: well above what the longest ordinary line takes (about 400 MB, under a second), and a
686
+ // wall clock past two of the guard's own 5 s budgets (pre-approval judges the line again), with slack. Past it
687
+ // with a verdict given, the verdict stands, not pre-approved; with none, the line is refused.
688
+ export const GUARD_HEAP_MB = 1024;
689
+ export const GUARD_WALL_MS = 2 * JUDGE_BUDGET_MS + 2000;
690
+ const NOT_JUDGED = (why) => ({ allow: false, message: `yad agent guard: this command could not be judged (${why}). Run it as separate commands, shorter, or ask the person to run it.` });
691
+ // The verdict (and pre-approval) for `command`, judged in a worker; a refusal when the worker does not answer.
692
+ export function judgeInWorker(command, preapproval, { heapMb = GUARD_HEAP_MB, wallMs = GUARD_WALL_MS } = {}) {
693
+ return new Promise((resolve) => {
694
+ let done = false;
695
+ let worker = null;
696
+ let timer = null;
697
+ // The verdict, once the worker has given it: after it, only pre-approval can be lost (it is then not given).
698
+ let verdict = null;
699
+ const lost = (why) => (verdict ? { verdict, pre: null } : { verdict: NOT_JUDGED(why), pre: null });
700
+ const finish = (answer) => {
701
+ if (done) return;
702
+ done = true;
703
+ clearTimeout(timer);
704
+ if (worker) worker.terminate().catch(() => {});
705
+ resolve(answer);
706
+ };
707
+ try {
708
+ worker = new Worker(new URL('./agent-guard-worker.mjs', import.meta.url), { workerData: { command, preapproval }, resourceLimits: { maxOldGenerationSizeMb: heapMb } });
709
+ } catch (e) {
710
+ finish({ verdict: NOT_JUDGED(e?.message ?? String(e)), pre: null });
711
+ return;
712
+ }
713
+ timer = setTimeout(() => finish(lost(`no answer in ${wallMs / 1000} s`)), wallMs);
714
+ worker.on('message', (m) => {
715
+ if (!verdict) {
716
+ if (!m || typeof m.verdict?.allow !== 'boolean') { finish({ verdict: NOT_JUDGED('no verdict'), pre: null }); return; }
717
+ verdict = m.verdict;
718
+ if (!verdict.allow || !preapproval) finish({ verdict, pre: null });
719
+ return;
720
+ }
721
+ finish({ verdict, pre: m?.pre ?? null });
722
+ });
723
+ worker.once('error', (e) => finish(lost(e?.code === 'ERR_WORKER_OUT_OF_MEMORY' ? 'it ran out of memory' : (e?.message ?? String(e)))));
724
+ worker.once('exit', (code) => finish(lost(`the judge stopped (${code})`)));
725
+ });
726
+ }
727
+
678
728
  // Claude Code's PreToolUse answer that skips the permission prompt. A team's own `deny` or `ask` rule still wins.
679
729
  export const claudePreapproval = (reason) => JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'allow',
680
730
  permissionDecisionReason: `yad agent guard: a read-only command (${reason}), pre-approved (E167; YAD_NO_PREAPPROVE=1 turns this off)` } });