yadflow 4.10.0 → 4.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +97 -0
- package/README.md +12 -3
- package/bin/commands.mjs +5 -1
- package/bin/yad.mjs +109 -15
- package/cli/agent-guard-worker.mjs +13 -0
- package/cli/agent-guard.mjs +1053 -57
- package/cli/agent-rules.mjs +34 -3
- package/cli/argv-flags.mjs +2 -2
- package/cli/brain/vendor/LICENSE-graphology-library.txt +21 -0
- package/cli/brain/vendor/LICENSE-graphology.txt +21 -0
- package/cli/brain/vendor/LICENSE-sigma.txt +12 -0
- package/cli/brain/vendor/graphology-library.min.js +2 -0
- package/cli/brain/vendor/graphology.umd.min.js +2 -0
- package/cli/brain/vendor/sigma.min.js +1369 -0
- package/cli/brain/view/app.js +382 -0
- package/cli/brain/view/index.html +63 -0
- package/cli/brain/view/live.css +228 -0
- package/cli/brain/view/live.html +110 -0
- package/cli/brain/view/live.js +884 -0
- package/cli/brain/view/style.css +141 -0
- package/cli/brain-about.mjs +206 -0
- package/cli/brain-activity.mjs +285 -0
- package/cli/brain-skills.mjs +118 -0
- package/cli/brain-vendor.mjs +71 -0
- package/cli/brain-view.mjs +344 -0
- package/cli/brain.mjs +810 -0
- package/cli/ci-check.mjs +3 -3
- package/cli/doctor.mjs +80 -13
- package/cli/epic-state.mjs +93 -1
- package/cli/epic.mjs +15 -3
- package/cli/errors.mjs +2 -1
- package/cli/find-product.mjs +69 -15
- package/cli/foundation-publish.mjs +256 -0
- package/cli/gate.mjs +29 -3
- package/cli/git-read.mjs +38 -0
- package/cli/guard-stream.mjs +409 -0
- package/cli/hook.mjs +59 -9
- package/cli/issues-act.mjs +57 -13
- package/cli/issues-write.mjs +19 -6
- package/cli/issues.mjs +62 -23
- package/cli/lib.mjs +37 -2
- package/cli/local-page.mjs +138 -0
- package/cli/machine.mjs +1 -1
- package/cli/manifest.mjs +50 -0
- package/cli/map/view/app.js +712 -0
- package/cli/map/view/index.html +50 -0
- package/cli/map/view/style.css +142 -0
- package/cli/map-view.mjs +186 -0
- package/cli/map.mjs +637 -0
- package/cli/members.mjs +9 -15
- package/cli/next.mjs +1 -1
- package/cli/openpr.mjs +2 -2
- package/cli/plan.mjs +125 -0
- package/cli/platform.mjs +5 -5
- package/cli/product-index.mjs +1 -1
- package/cli/protection.mjs +32 -0
- package/cli/reconcile.mjs +8 -2
- package/cli/report.mjs +9 -3
- package/cli/reports-dir.mjs +391 -0
- package/cli/reports.mjs +65 -0
- package/cli/run-checks.mjs +5 -2
- package/cli/scan.mjs +1 -1
- package/cli/setup.mjs +30 -5
- package/cli/standup.mjs +87 -71
- package/cli/status.mjs +6 -5
- package/cli/test-agents-file.mjs +614 -8
- package/cli/test-brain-activity.mjs +753 -0
- package/cli/test-brain-view.mjs +381 -0
- package/cli/test-brain.mjs +795 -0
- package/cli/test-guide.mjs +211 -0
- package/cli/test-machine.mjs +59 -0
- package/cli/test-map.mjs +615 -0
- package/cli/test-reports.mjs +382 -0
- package/cli/test-run-checks.mjs +4 -0
- package/cli/test-worktree.mjs +24 -3
- package/cli/toolbox-connect.mjs +21 -6
- package/cli/toolbox.mjs +59 -4
- package/cli/update-commit.mjs +101 -9
- package/cli/usage.mjs +8 -4
- package/package.json +8 -4
- package/skills/yad-architecture/SKILL.md +22 -4
- package/skills/yad-change/SKILL.md +3 -1
- package/skills/yad-change/references/triage.md +2 -0
- package/skills/yad-checks/SKILL.md +2 -0
- package/skills/yad-checks/references/check-gates.md +8 -5
- package/skills/yad-checks/templates/checks/build-test-lint.sh +7 -0
- package/skills/yad-checks/templates/checks/install-deps.sh +6 -0
- package/skills/yad-checks/templates/checks/package-manager.sh +42 -0
- package/skills/yad-checks/templates/github/yad-checks.yml +3 -2
- package/skills/yad-checks/templates/gitlab/yad-checks.gitlab-ci.yml +3 -2
- package/skills/yad-checks/templates/hooks/yad-activity.mjs +238 -0
- package/skills/yad-connect-repos/SKILL.md +14 -0
- package/skills/yad-discovery/SKILL.md +11 -0
- package/skills/yad-discovery/references/foundation-schema.md +11 -0
- package/skills/yad-docs/templates/app/package-lock.json +18 -10
- package/skills/yad-docs/templates/app/package.json +6 -1
- package/skills/yad-epic/SKILL.md +3 -0
- package/skills/yad-epic/references/state-schema.md +35 -1
- package/skills/yad-guide/SKILL.md +4 -4
- package/skills/yad-implement/SKILL.md +76 -15
- package/skills/yad-issues/SKILL.md +2 -1
- package/skills/yad-pr-template/templates/checks/pr-template.sh +8 -4
- package/skills/yad-pr-template/templates/checks/pr-title.sh +8 -4
- package/skills/yad-spec/SKILL.md +19 -0
- package/skills/yad-stories/SKILL.md +22 -4
- 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/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 {
|
|
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
|
-
|
|
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
|
-
|
|
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 (
|
|
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)` } });
|
package/cli/issues-act.mjs
CHANGED
|
@@ -11,7 +11,7 @@ import fs from 'node:fs';
|
|
|
11
11
|
import { run, forTerminal, c, log, fail, hand, info, warn, emitJSON } from './lib.mjs';
|
|
12
12
|
import { addItemLabels, removeItemLabels, commentOnItem, closeItem, newItem, editItem, reopenItem, setAssignee, makeConfidential, platformLogin } from './platform.mjs';
|
|
13
13
|
import { api, httpStatus } from './protection.mjs';
|
|
14
|
-
import { labelRules, ITEM_TYPES, PRIORITIES } from './issues.mjs';
|
|
14
|
+
import { labelRules, labelOwner, labelKey, readLabels, ITEM_TYPES, PRIORITIES } from './issues.mjs';
|
|
15
15
|
import { readItem, resolveTarget } from './issues-write.mjs';
|
|
16
16
|
import { allLinks, itemKey } from './issue-links.mjs';
|
|
17
17
|
import { redactTokens, repoFacts, routeFor } from './scan.mjs';
|
|
@@ -70,7 +70,7 @@ function bodyOf({ body, bodyFile }) {
|
|
|
70
70
|
}
|
|
71
71
|
|
|
72
72
|
// The repo: the Product unless a registered one is named. `ref` resolution does the registry and login checks.
|
|
73
|
-
function targetOf(root, repo, { env, runner }) {
|
|
73
|
+
export function targetOf(root, repo, { env, runner }) {
|
|
74
74
|
const r = resolveTarget(root, repo && repo !== 'Product' ? `${repo}#1` : '1', { env, runner });
|
|
75
75
|
if (!r.ok) throw new Refused(r.why, r.hint);
|
|
76
76
|
if (!r.t.ok) throw new Refused(`${forTerminal(r.label)}: ${r.t.why}`);
|
|
@@ -197,11 +197,27 @@ export async function runIssuesAssign(root, { ref, assignee = null, me = false,
|
|
|
197
197
|
});
|
|
198
198
|
}
|
|
199
199
|
|
|
200
|
-
|
|
200
|
+
// `--add` / `--remove` (#514) take any label but yad's own: those have a flag of their own, or yad writes them.
|
|
201
|
+
const OWNER_HINT = {
|
|
202
|
+
priority: 'set the priority with --priority',
|
|
203
|
+
type: 'set the type with --type',
|
|
204
|
+
status: 'yad writes the status label itself, from what the item and its epic say (`yad issues sync`)',
|
|
205
|
+
epic: 'yad writes an epic label itself: link the item with `yad issues link <ref> <EP-id>`',
|
|
206
|
+
};
|
|
207
|
+
const names = (v) => (v == null ? [] : Array.isArray(v) ? v : [v]).map((n) => String(n).trim());
|
|
208
|
+
// Every comparison of two label names is `labelKey` (cli/issues.mjs), never a spelling of its own (#514 reviews 1-2).
|
|
209
|
+
const fold = labelKey;
|
|
210
|
+
|
|
211
|
+
export async function runIssuesLabel(root, { ref, priority: rawPriority = null, type: rawType = null, add: rawAdd = [], remove: rawRemove = [], json = false, env = process.env, runner = run } = {}) {
|
|
201
212
|
const priority = normPriority(rawPriority);
|
|
202
213
|
const type = normType(rawType);
|
|
214
|
+
const plus = names(rawAdd);
|
|
215
|
+
const minus = names(rawRemove);
|
|
203
216
|
return act(root, ref, { json, env, runner }, async (got, out) => {
|
|
204
|
-
if (priority === null && type === null) throw new Refused('pass --priority, --type or
|
|
217
|
+
if (priority === null && type === null && !plus.length && !minus.length) throw new Refused('pass --priority, --type, --add or --remove');
|
|
218
|
+
if ([...plus, ...minus].some((n) => !n)) throw new Refused('--add and --remove need a label name');
|
|
219
|
+
const both = plus.filter((n) => minus.some((m) => fold(m) === fold(n)));
|
|
220
|
+
if (both.length) throw new Refused(`${forTerminal(both.join(', '))} is in both --add and --remove`, 'name each label once');
|
|
205
221
|
if (priority !== null && !PRIORITIES.includes(priority)) throw new Refused(`unknown --priority ${forTerminal(String(priority))}`, `use one of ${PRIORITIES.join(', ')}`);
|
|
206
222
|
if (type !== null && !ITEM_TYPES.includes(type)) throw new Refused(`unknown --type ${forTerminal(String(type))}`, `use one of ${ITEM_TYPES.join(', ')}`);
|
|
207
223
|
if (type === 'security' && got.t.platform === 'github' && !got.item.confidential && routeFor('security', 'github', repoFacts(got.t, runner).vis) !== 'issue') {
|
|
@@ -210,17 +226,44 @@ export async function runIssuesLabel(root, { ref, priority: rawPriority = null,
|
|
|
210
226
|
// A confidential item's labels are not read, so the old ones could not be removed.
|
|
211
227
|
if (got.item.confidential) throw new Refused('a confidential item\'s labels are not read, so they cannot be replaced here', 'change them on GitLab');
|
|
212
228
|
const rules = labelRules(got.productConfig);
|
|
213
|
-
const
|
|
229
|
+
for (const n of [...plus, ...minus]) {
|
|
230
|
+
const owner = labelOwner(n, rules);
|
|
231
|
+
if (owner) throw new Refused(`${forTerminal(n)} is a${owner === 'epic' ? 'n epic' : ` ${owner}`} label, which --add and --remove do not change`, OWNER_HINT[owner]);
|
|
232
|
+
}
|
|
233
|
+
const have = new Set(got.item.labels.map(fold));
|
|
214
234
|
const add = [];
|
|
215
235
|
const remove = [];
|
|
236
|
+
// The repo's labels, read once and only when needed.
|
|
237
|
+
let known = null;
|
|
238
|
+
const repoLabels = () => (known ??= readLabels(got.t, runner));
|
|
239
|
+
// A label is added only as the repo already spells it: a missing one is refused, never made by the platform.
|
|
240
|
+
if (plus.length) {
|
|
241
|
+
repoLabels();
|
|
242
|
+
if (!known.ok) throw new Refused(`the repo's labels could not be read, so --add was not checked: ${known.why}`, 'try again, or set the label on the platform');
|
|
243
|
+
const missing = plus.filter((n) => !known.keys.has(fold(n)));
|
|
244
|
+
if (missing.length) throw new Refused(`the repo has no label ${forTerminal(missing.join(', '))}`, 'create it on the platform first, then run this again; nothing was changed');
|
|
245
|
+
for (const n of plus) if (!have.has(fold(n)) && !add.some((a) => fold(a) === fold(n))) add.push(known.real.get(fold(n)) ?? n);
|
|
246
|
+
const already = [...new Map(plus.filter((n) => have.has(fold(n))).map((n) => [fold(n), n])).values()];
|
|
247
|
+
if (already.length) out.notes.push(`it already has ${already.map(forTerminal).join(', ')}`);
|
|
248
|
+
}
|
|
249
|
+
for (const n of minus) {
|
|
250
|
+
if (remove.some((r) => fold(r) === fold(n))) continue; // named twice: one removal, never a second that fails
|
|
251
|
+
if (have.has(fold(n))) remove.push(n);
|
|
252
|
+
else out.notes.push(`it has no label ${forTerminal(n)}, so there was nothing to remove`);
|
|
253
|
+
}
|
|
216
254
|
for (const [kind, value] of [['priority', priority], ['type', type]]) {
|
|
217
255
|
if (value === null) continue;
|
|
218
256
|
const want = rules[kind][value][0];
|
|
219
|
-
if (!rules[kind][value].some((l) => have.has(l
|
|
220
|
-
for (const [other, names] of Object.entries(rules[kind])) if (other !== value) remove.push(...names.filter((l) => have.has(l
|
|
257
|
+
if (!rules[kind][value].some((l) => have.has(fold(l)))) add.push(want);
|
|
258
|
+
for (const [other, names] of Object.entries(rules[kind])) if (other !== value) remove.push(...names.filter((l) => have.has(fold(l))));
|
|
221
259
|
}
|
|
222
|
-
|
|
223
|
-
|
|
260
|
+
// Removed as the repo spells it: an item's labels are read cleaned (spaces folded), and a DELETE or a GitLab
|
|
261
|
+
// remove_labels of the cleaned spelling misses a label like `needs design`. If the repo's labels cannot be
|
|
262
|
+
// read, the item's own spelling is sent, and the read-back says if it stayed.
|
|
263
|
+
const realNames = new Map(got.item.labels.map((l) => [fold(l), l]));
|
|
264
|
+
if (remove.length) repoLabels();
|
|
265
|
+
const spelled = (l) => (known?.ok ? known.real.get(fold(l)) : null) ?? realNames.get(fold(l)) ?? l;
|
|
266
|
+
const stale = [...new Map(remove.map((l) => [fold(l), spelled(l)])).values()];
|
|
224
267
|
if (got.t.platform === 'gitlab' && [...add, ...stale].some((l) => l.includes(','))) throw new Refused('a GitLab label name with a comma cannot be sent', 'rename that label in the issues settings of .sdlc/product.json');
|
|
225
268
|
// On GitLab a vulnerability is confidential first, so the label is never on a public item. This runs even when
|
|
226
269
|
// the label is already there: a public item that carries it is exactly what must not stay.
|
|
@@ -233,7 +276,7 @@ export async function runIssuesLabel(root, { ref, priority: rawPriority = null,
|
|
|
233
276
|
out.changed.push('made confidential');
|
|
234
277
|
madeConfidential = true;
|
|
235
278
|
}
|
|
236
|
-
if (!add.length && !stale.length) { out.notes.push('it already has those labels'); return null; }
|
|
279
|
+
if (!add.length && !stale.length) { if (priority !== null || type !== null || !out.notes.length) out.notes.push('it already has those labels'); return null; }
|
|
237
280
|
if (add.length) {
|
|
238
281
|
const r = addItemLabels(got.t, got.number, add, { runner });
|
|
239
282
|
if (!r.ok && !madeConfidential) return r;
|
|
@@ -245,8 +288,9 @@ export async function runIssuesLabel(root, { ref, priority: rawPriority = null,
|
|
|
245
288
|
if (madeConfidential) out.notes.push('it is confidential now, so its labels could not be read back to check');
|
|
246
289
|
else if (!after) out.notes.push('the item could not be read again to check the change');
|
|
247
290
|
else {
|
|
248
|
-
const now = new Set(after.labels.map(
|
|
249
|
-
for (const l of add) if (!now.has(l
|
|
291
|
+
const now = new Set(after.labels.map(fold));
|
|
292
|
+
for (const l of add) if (!now.has(fold(l))) out.dropped.push(`the label ${l} was not set`);
|
|
293
|
+
for (const l of stale) if (now.has(fold(l))) out.dropped.push(`the label ${l} is still there`);
|
|
250
294
|
}
|
|
251
295
|
return null;
|
|
252
296
|
});
|
|
@@ -318,7 +362,7 @@ export async function runIssuesReopen(root, { ref, json = false, env = process.e
|
|
|
318
362
|
const ACT_FLAGS = {
|
|
319
363
|
new: ['--title', '--body', '--body-file', '--type', '--priority', '--assignee', '--me', '--repo'],
|
|
320
364
|
assign: ['--me', '--none'],
|
|
321
|
-
label: ['--priority', '--type'],
|
|
365
|
+
label: ['--priority', '--type', '--add', '--remove'],
|
|
322
366
|
edit: ['--title', '--body', '--body-file'],
|
|
323
367
|
comment: ['--body', '--body-file'],
|
|
324
368
|
close: [], reopen: [],
|