yadflow 4.8.0 → 4.9.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.
@@ -0,0 +1,511 @@
1
+ // #359: a preview address for each PR/MR. A repo records a pattern (`preview_url` in repos.json, set
2
+ // with `yad repo preview`); else the platform's deployment for the PR; else "locally only". The PR/MR
3
+ // body carries a Preview line, and `yad review context` hands the address to the review skills.
4
+ import { test } from 'node:test';
5
+ import assert from 'node:assert/strict';
6
+ import { spawnSync } from 'node:child_process';
7
+ import fs from 'node:fs';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+
12
+ if (process.env.NODE_TEST_CONTEXT) {
13
+ const write = process.stdout.write;
14
+ for (const k of ['log', 'info']) {
15
+ const orig = console[k];
16
+ console[k] = (...a) => (process.stdout.write === write ? console.error(...a) : orig(...a));
17
+ }
18
+ }
19
+ process.env.YAD_NO_UPDATE_NOTIFIER = '1';
20
+
21
+ const { patternProblems, fillPattern, previewPattern, platformPreview, resolvePreview, prHead, previewLine, urlProblem, budget, PREVIEW_NONE, PREVIEW_UNFILLED, PREVIEW_UNUSABLE, slug } = await import('./preview.mjs');
22
+ const { templateBody, withPreviewLine, runOpenPr } = await import('./openpr.mjs');
23
+ const { reviewContext } = await import('./review.mjs');
24
+ const { previewChecks } = await import('./doctor.mjs');
25
+
26
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
27
+ const YAD = path.join(HERE, '..', 'bin', 'yad.mjs');
28
+ const REPO = path.join(HERE, '..');
29
+
30
+ const tmp = () => fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'yad-preview-')));
31
+ const put = (file, data) => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, typeof data === 'string' ? data : JSON.stringify(data)); };
32
+ const done = (...dirs) => dirs.forEach((d) => fs.rmSync(d, { recursive: true, force: true }));
33
+ const git = (cwd, ...a) => spawnSync('git', a, { cwd, encoding: 'utf8' });
34
+ const yad = (cwd, ...a) => spawnSync(process.execPath, [YAD, ...a], { cwd, encoding: 'utf8', env: { ...process.env, NO_COLOR: '1', SDLC_NONINTERACTIVE: '1', YAD_NO_REPORT: '1' } });
35
+
36
+ // A scripted runner: the first prefix that matches answers; anything else fails, as an unknown host would.
37
+ function fakeRunner(answers = {}) {
38
+ const calls = [];
39
+ const runner = (cmd, args = []) => {
40
+ const line = [cmd, ...args].join(' ');
41
+ calls.push(line);
42
+ for (const [prefix, out] of Object.entries(answers)) {
43
+ if (line.startsWith(prefix)) return typeof out === 'string' ? { ok: true, code: 0, stdout: out, stderr: '' } : out;
44
+ }
45
+ return { ok: false, code: 1, stdout: '', stderr: 'not scripted' };
46
+ };
47
+ runner.calls = calls;
48
+ return runner;
49
+ }
50
+
51
+ test('patternProblems: one rule for a usable pattern', () => {
52
+ for (const good of ['https://pr-{pr}.myapp.dev', 'https://{branch}--{repo}.netlify.app/', 'https://staging.example.com', 'http://localhost:3000/pr/{pr}', 'https://x.dev/?b={branch}&r={repo}'])
53
+ assert.deepEqual(patternProblems(good), [], good);
54
+ const bad = (p, re) => assert.match(patternProblems(p).join(' | '), re, String(p));
55
+ bad('http://pr-{pr}.myapp.dev', /https:\/\//);
56
+ bad('ftp://x.dev', /https:\/\//);
57
+ bad('javascript:alert(1)', /https:\/\//);
58
+ bad('https://pr-{id}.myapp.dev', /unknown placeholder \{id\}/);
59
+ bad('https://pr-{pr.myapp.dev', /lone \{/);
60
+ bad('https://pr {pr}.dev', /space/);
61
+ bad('https://x.dev/<b>', /not allowed/);
62
+ bad('https://user:pw@x.dev', /user name or password/);
63
+ bad(`https://x.dev/${'a'.repeat(2100)}`, /longer than/);
64
+ bad(42, /not text/);
65
+ bad(null, /not text/);
66
+ });
67
+
68
+ test('fillPattern: fills, slugs the branch and repo, and refuses what it cannot fill', () => {
69
+ assert.equal(fillPattern('https://pr-{pr}.myapp.dev', { pr: 12 }), 'https://pr-12.myapp.dev');
70
+ assert.equal(fillPattern('https://{branch}.{repo}.dev', { branch: 'feat/EP-x-S01-T01_Cart', repo: 'Web App' }), 'https://feat-ep-x-s01-t01-cart.web-app.dev');
71
+ assert.equal(fillPattern('https://pr-{pr}.myapp.dev', {}), null, '{pr} before the PR exists');
72
+ assert.equal(fillPattern('https://pr-{pr}.myapp.dev', { pr: '1; rm' }), null, 'a PR number is digits only');
73
+ assert.equal(fillPattern('https://{branch}.dev', { branch: '///' }), null, 'a branch that slugs to nothing');
74
+ assert.equal(fillPattern('http://x.dev/{pr}', { pr: 1 }), null, 'an unusable pattern fills to nothing');
75
+ assert.equal(fillPattern('https://x.dev/$&-{pr}', { pr: 3 }), 'https://x.dev/$&-3', 'a $ is kept as written');
76
+ assert.equal(slug(' A__b//C '), 'a-b-c');
77
+ });
78
+
79
+ test('previewPattern: none, usable, or recorded but unusable', () => {
80
+ assert.deepEqual(previewPattern({ name: 'web' }), {});
81
+ assert.deepEqual(previewPattern({ name: 'web', preview_url: null }), {});
82
+ assert.deepEqual(previewPattern(null), {});
83
+ assert.deepEqual(previewPattern({ preview_url: 'https://pr-{pr}.x.dev' }), { pattern: 'https://pr-{pr}.x.dev' });
84
+ assert.ok(previewPattern({ preview_url: 'http://x.dev' }).problems.length);
85
+ assert.ok(previewPattern({ preview_url: 5 }).problems.length);
86
+ });
87
+
88
+ test('urlProblem: an address from a deployment service must be https and plain', () => {
89
+ assert.equal(urlProblem('https://pr-1.x.vercel.app'), null);
90
+ assert.equal(urlProblem('http://127.0.0.1:8080'), null);
91
+ assert.match(urlProblem('http://pr-1.x.dev'), /https/);
92
+ assert.match(urlProblem('javascript:alert(1)'), /https/);
93
+ assert.match(urlProblem('https://x.dev/‮'), /non-ASCII/);
94
+ });
95
+
96
+ const SHA = 'a'.repeat(40);
97
+ const deployments = (list) => JSON.stringify(list);
98
+
99
+ test('platformPreview (GitHub): the newest successful non-production deployment of the head commit', () => {
100
+ const runner = fakeRunner({
101
+ [`gh api repos/{owner}/{repo}/deployments?sha=${SHA}`]: deployments([
102
+ { id: 3, production_environment: true },
103
+ { id: 2, production_environment: false },
104
+ { id: 1 },
105
+ ]),
106
+ 'gh api repos/{owner}/{repo}/deployments/2/statuses': deployments([{ state: 'in_progress', environment_url: '' }, { state: 'success', environment_url: 'https://old.x.dev' }]),
107
+ 'gh api repos/{owner}/{repo}/deployments/1/statuses': deployments([{ state: 'success', environment_url: 'https://pr-7.x.vercel.app' }]),
108
+ });
109
+ assert.deepEqual(platformPreview('github', { sha: SHA, runner }), { url: 'https://pr-7.x.vercel.app' });
110
+ assert.ok(!runner.calls.some((c) => c.includes('deployments/3/')), 'a production deployment is the live site, never asked');
111
+ const named = fakeRunner({
112
+ [`gh api repos/{owner}/{repo}/deployments?sha=${SHA}`]: deployments([{ id: 5, environment: 'Production' }, { id: 6, environment: 'prod' }, { id: 7, environment: 'Production – myapp' }, { id: 8, environment: 'production-eu' }, { id: 10, environment: 'prod_us' }]),
113
+ 'gh api repos/{owner}/{repo}/deployments/': deployments([{ state: 'success', environment_url: 'https://live.x.dev' }]),
114
+ });
115
+ assert.match(platformPreview('github', { sha: SHA, runner: named }).why, /no preview deployment/, 'an environment named production is production, flag or not');
116
+ const failing = fakeRunner({ [`gh api repos/{owner}/{repo}/deployments?sha=${SHA}`]: deployments([{ id: 1 }, { id: 2 }]) });
117
+ assert.match(platformPreview('github', { sha: SHA, runner: failing }).why, /could not be asked for the deployments' status/, 'failed status calls are not "no deployment"');
118
+ });
119
+
120
+ test('platformPreview (GitHub): no deployment, a failed gh, an odd address, an unreadable answer', () => {
121
+ assert.match(platformPreview('github', { sha: SHA, runner: fakeRunner({ 'gh api': '[]' }) }).why, /no preview deployment/);
122
+ assert.match(platformPreview('github', { sha: SHA, runner: fakeRunner({}) }).why, /could not be asked/);
123
+ assert.match(platformPreview('github', { sha: SHA, runner: fakeRunner({ 'gh api': '{' }) }).why, /cannot read/);
124
+ assert.match(platformPreview('github', { sha: null, runner: fakeRunner({}) }).why, /head commit is not known/);
125
+ assert.match(platformPreview('github', { sha: 'x&y', runner: fakeRunner({}) }).why, /head commit is not known/, 'a sha is hex only before it goes into the API path');
126
+ const odd = fakeRunner({
127
+ [`gh api repos/{owner}/{repo}/deployments?sha=${SHA}`]: deployments([{ id: 1 }]),
128
+ 'gh api repos/{owner}/{repo}/deployments/1/statuses': deployments([{ state: 'success', environment_url: 'javascript:alert(1)' }]),
129
+ });
130
+ const r = platformPreview('github', { sha: SHA, runner: odd });
131
+ assert.equal(r.url, null);
132
+ assert.match(r.why, /will not use/);
133
+ });
134
+
135
+ test('platformPreview (GitHub): stops asking once its time budget is spent', () => {
136
+ let t = 0;
137
+ const now = () => t;
138
+ const runner = (cmd, args) => {
139
+ t += 10000; // every call takes 10 s
140
+ const line = [cmd, ...args].join(' ');
141
+ if (line.includes('/statuses')) return { ok: true, stdout: '[{"state":"failure"}]' };
142
+ return { ok: true, stdout: deployments([{ id: 1 }, { id: 2 }, { id: 3 }]) };
143
+ };
144
+ assert.match(platformPreview('github', { sha: SHA, runner, clock: budget(now) }).why, /too slow/);
145
+ // Each call is handed only the time that is left, never a fresh 8 s.
146
+ const seen = [];
147
+ let t2 = 0;
148
+ const clock = budget(() => t2);
149
+ const timed = (cmd, args, o) => { seen.push(o.timeout); t2 += 6000; return { ok: true, stdout: deployments([{ id: 1 }, { id: 2 }]) }; };
150
+ platformPreview('github', { sha: SHA, runner: timed, clock });
151
+ assert.deepEqual(seen, [8000, 8000, 3000], 'a hard total of 15 s');
152
+ });
153
+
154
+ test('platformPreview (GitLab): this branch\'s deployment whose environment is running and not production', () => {
155
+ const list = deployments([
156
+ { ref: 'main', sha: SHA, environment: { id: 1, name: 'review/main' } },
157
+ { ref: 'feat/x', sha: SHA, environment: { id: 2, name: 'Production' } },
158
+ { ref: 'feat/x', sha: SHA, environment: { id: 3, name: 'review/old' } },
159
+ { ref: 'feat/x', sha: 'c'.repeat(40), environment: { id: 9, name: 'review/older-commit' } },
160
+ { ref: 'feat/x', sha: SHA, environment: { id: 4, name: 'review/feat-x' } },
161
+ ]);
162
+ const runner = fakeRunner({
163
+ 'glab api projects/:id/deployments?': list,
164
+ 'glab api projects/:id/environments/3': JSON.stringify({ id: 3, name: 'review/old', state: 'stopped', external_url: 'https://dead.review.x.dev' }),
165
+ 'glab api projects/:id/environments/4': JSON.stringify({ id: 4, name: 'review/feat-x', state: 'available', tier: 'development', external_url: 'https://feat-x.review.x.dev' }),
166
+ });
167
+ assert.deepEqual(platformPreview('gitlab', { sha: SHA, branch: 'feat/x', runner }), { url: 'https://feat-x.review.x.dev' });
168
+ assert.ok(!runner.calls.some((c) => /environments\/(1|2|9)$/.test(c)), 'another branch, production and another commit are never asked');
169
+ assert.ok(!runner.calls[0].includes('ref='), 'the list has no branch filter: yad filters it');
170
+ const prodTier = fakeRunner({ 'glab api projects/:id/deployments?': deployments([{ ref: 'feat/x', environment: { id: 5, name: 'live' } }]),
171
+ 'glab api projects/:id/environments/5': JSON.stringify({ state: 'available', tier: 'production', external_url: 'https://x.dev' }) });
172
+ assert.match(platformPreview('gitlab', { branch: 'feat/x', runner: prodTier }).why, /no successful, running review deployment/);
173
+ const envFails = fakeRunner({ 'glab api projects/:id/deployments?': deployments([{ ref: 'feat/x', environment: { id: 5, name: 'r' } }]) });
174
+ const envDown = platformPreview('gitlab', { branch: 'feat/x', runner: envFails });
175
+ assert.match(envDown.why, /could not be asked about the review environments/);
176
+ assert.equal(envDown.listedNone, undefined, 'environments it could not ask are not "none listed"');
177
+ assert.match(platformPreview('gitlab', { branch: 'feat/x', runner: fakeRunner({}) }).why, /could not be asked/);
178
+ const empty = platformPreview('gitlab', { branch: 'feat/x', runner: fakeRunner({ 'glab api': '[]' }) });
179
+ assert.match(empty.why, /no successful, running review deployment/);
180
+ assert.equal(empty.listedNone, true, 'resolvePreview reads this flag, never the wording');
181
+ assert.equal(platformPreview('gitlab', { branch: 'feat/x', runner: fakeRunner({}) }).listedNone, undefined, 'a GitLab it could not ask listed nothing only in the sense that it was not asked');
182
+ assert.match(platformPreview('gitlab', { branch: null, runner: fakeRunner({}) }).why, /branch is not known/);
183
+ assert.match(platformPreview('bitbucket', {}).why, /not GitHub or GitLab/);
184
+ });
185
+
186
+ test('prHead: with a PR number only the platform answers; without one, this checkout', () => {
187
+ const gh = fakeRunner({ 'gh pr view 9': JSON.stringify({ headRefOid: SHA, headRefName: 'feat/x' }) });
188
+ assert.deepEqual(prHead('github', 9, { runner: gh }), { sha: SHA, branch: 'feat/x' });
189
+ const gl = fakeRunner({ 'glab mr view 9': JSON.stringify({ sha: SHA, source_branch: 'feat/y' }) });
190
+ assert.deepEqual(prHead('gitlab', 9, { runner: gl }), { sha: SHA, branch: 'feat/y' });
191
+ const local = fakeRunner({ 'git rev-parse HEAD': 'b'.repeat(40), 'git rev-parse --abbrev-ref HEAD': 'main' });
192
+ const failed = prHead('github', 9, { runner: local });
193
+ assert.equal(failed.branch, null, 'a gh failure never falls back to this checkout: main is not the PR');
194
+ assert.equal(failed.sha, null);
195
+ assert.match(failed.why, /PR #9's head branch/);
196
+ assert.ok(!local.calls.some((c) => c.startsWith('git')), 'git is not asked when a PR is named');
197
+ assert.deepEqual(prHead('github', null, { runner: local }), { sha: 'b'.repeat(40), branch: 'main' });
198
+ const detached = prHead('github', null, { runner: fakeRunner({ 'git rev-parse HEAD': 'b'.repeat(40), 'git rev-parse --abbrev-ref HEAD': 'HEAD' }) });
199
+ assert.equal(detached.branch, null, 'a detached checkout has no branch, never "HEAD"');
200
+ assert.match(detached.why, /detached/);
201
+ const onMain = prHead('github', null, { runner: local, base: 'main' });
202
+ assert.equal(onMain.branch, null, 'the default branch is no PR\'s branch');
203
+ assert.match(onMain.why, /default branch \(main\), not the PR's$/, 'a fact; resolvePreview chooses the step');
204
+ });
205
+
206
+ test('resolvePreview: the pattern wins, the platform is the fallback, else local-only with why and the fix', () => {
207
+ const head = { sha: SHA, branch: 'b' };
208
+ const never = () => { throw new Error('the platform is not asked when the pattern answers'); };
209
+ const noNet = fakeRunner({});
210
+ assert.deepEqual(resolvePreview({ meta: { name: 'web', preview_url: 'https://pr-{pr}.x.dev' }, platform: 'github', pr: 4, runner: noNet, lookup: never }), { url: 'https://pr-4.x.dev', source: 'pattern' });
211
+ assert.deepEqual(noNet.calls, [], 'a {pr} pattern answers with no call at all');
212
+ const plat = () => ({ url: 'https://dep.x.dev' });
213
+ assert.deepEqual(resolvePreview({ meta: { name: 'web' }, platform: 'github', pr: 4, head, lookup: plat }), { url: 'https://dep.x.dev', source: 'platform' });
214
+ const none = () => ({ url: null, why: 'GitHub lists no preview deployment for this commit' });
215
+ const r = resolvePreview({ meta: { name: 'web' }, platform: 'github', pr: 4, head, lookup: none });
216
+ assert.equal(r.url, null);
217
+ assert.equal(r.source, 'local-only');
218
+ assert.match(r.why, /no preview_url pattern is recorded for this repo; GitHub lists no preview deployment/);
219
+ assert.match(r.why, /set one with `yad repo preview <repo> <pattern>`/);
220
+ const noPr = resolvePreview({ meta: { name: 'web', preview_url: 'https://pr-{pr}.x.dev' }, platform: 'github', pr: null, head, lookup: none });
221
+ assert.match(noPr.why, /needs the PR number \(\{pr\}\), and none was given \(--pr\).* — pass --pr <n>$/);
222
+ const badPat = resolvePreview({ meta: { name: 'web', preview_url: 'http://x.dev' }, platform: 'github', pr: 1, head, lookup: none });
223
+ assert.match(badPat.why, /cannot be used: it must start with https.*set it again/);
224
+ const outside = resolvePreview({ meta: null, platform: 'github', pr: 1, head, lookup: none });
225
+ assert.match(outside.why, /register the repo/);
226
+ });
227
+
228
+ test('resolvePreview: on the default branch without --pr, one next step — pass --pr', () => {
229
+ const onMain = fakeRunner({ 'git rev-parse HEAD': 'b'.repeat(40), 'git rev-parse --abbrev-ref HEAD': 'main' });
230
+ const lookup = () => { throw new Error('no head, nothing to ask'); };
231
+ for (const meta of [{ name: 'web', preview_url: 'https://pr-{pr}.x.dev' }, { name: 'web', preview_url: 'https://{branch}.x.dev' }, { name: 'web' }, { name: 'web', preview_url: 'http://x.dev' }]) {
232
+ const r = resolvePreview({ meta, platform: 'github', pr: null, base: 'main', runner: onMain, lookup });
233
+ assert.equal(r.source, 'local-only', JSON.stringify(meta));
234
+ assert.equal(r.why.split(' — ').length, 2, `one next step: ${r.why}`);
235
+ assert.match(r.why, / — pass --pr <n>$/, r.why);
236
+ }
237
+ });
238
+
239
+ test('platformPreview (GitLab): a merge-request pipeline\'s deployment counts, whatever its commit', () => {
240
+ const runner = fakeRunner({
241
+ 'glab api projects/:id/deployments?': deployments([
242
+ { ref: 'feat/x', sha: 'c'.repeat(40), environment: { id: 3, name: 'review/feat-x' } },
243
+ { ref: 'refs/merge-requests/7/head', sha: 'd'.repeat(40), environment: { id: 4, name: 'review/mr-7' } },
244
+ ]),
245
+ 'glab api projects/:id/environments/4': JSON.stringify({ state: 'available', external_url: 'https://mr-7.review.x.dev' }),
246
+ });
247
+ assert.deepEqual(platformPreview('gitlab', { sha: SHA, branch: 'feat/x', pr: 7, runner }), { url: 'https://mr-7.review.x.dev' });
248
+ assert.ok(!runner.calls.some((c) => c.endsWith('environments/3')), 'the branch deployment at another commit is still skipped');
249
+ assert.match(platformPreview('gitlab', { sha: SHA, branch: 'feat/x', pr: 8, runner }).why, /no successful/, 'another MR\'s ref is not this one');
250
+ assert.deepEqual(platformPreview('gitlab', { sha: SHA, branch: null, pr: 7, runner }), { url: 'https://mr-7.review.x.dev' }, 'no source branch: the MR ref still counts');
251
+ });
252
+
253
+ test('resolvePreview: GitLab without --pr, and a --pr that is not a number, both say pass --pr', () => {
254
+ const head = { sha: SHA, branch: 'feat/x' };
255
+ const none = () => ({ url: null, listedNone: true, why: 'GitLab lists no successful, running review deployment' });
256
+ const gl = resolvePreview({ meta: { name: 'web' }, platform: 'gitlab', pr: null, head, lookup: none });
257
+ assert.match(gl.why, /found only with --pr — pass --pr <n>$/);
258
+ const glBroken = resolvePreview({ meta: { name: 'web', preview_url: 'http://x' }, platform: 'gitlab', pr: null, head, lookup: () => ({ url: null, listedNone: true, why: 'GitLab lists no successful, running review deployment' }) });
259
+ assert.match(glBroken.why, /found only with --pr — set it again with `yad repo preview <repo> <pattern>`$/, 'a broken pattern is the fix to name first');
260
+ const glDown = resolvePreview({ meta: { name: 'web' }, platform: 'gitlab', pr: null, head, lookup: () => ({ url: null, why: 'GitLab could not be asked for deployments (glab not signed in, offline, or no GitLab remote)' }) });
261
+ assert.doesNotMatch(glDown.why, /found only with --pr/, '--pr would not help a GitLab that cannot be asked');
262
+ assert.match(glDown.why, / — set one with `yad repo preview <repo> <pattern>`$/);
263
+ const bad = resolvePreview({ meta: { name: 'web', preview_url: 'https://pr-{pr}.x.dev' }, platform: 'github', pr: 'abc', head, lookup: none });
264
+ assert.match(bad.why, /--pr\) is not a number.* — pass --pr <n>$/);
265
+ assert.equal(urlProblem(''), 'is not a URL');
266
+ });
267
+
268
+ test('resolvePreview: a {branch} pattern never fills from the wrong branch', () => {
269
+ // gh offline, the reviewer on main: the old fallback answered https://main--web… as "the PR's preview".
270
+ const runner = fakeRunner({ 'git rev-parse HEAD': 'b'.repeat(40), 'git rev-parse --abbrev-ref HEAD': 'main' });
271
+ const lookup = () => { throw new Error('nothing to ask the platform about'); };
272
+ const r = resolvePreview({ meta: { name: 'web', preview_url: 'https://{branch}--web.netlify.app' }, platform: 'github', pr: 12, runner, lookup });
273
+ assert.equal(r.url, null);
274
+ assert.equal(r.source, 'local-only');
275
+ assert.match(r.why, /needs the PR's branch \(\{branch\}\), and it is not known: GitHub could not be asked for PR #12's head branch/);
276
+ assert.equal((r.why.match(/head branch/g) || []).length, 1, 'the reason is said once');
277
+ const ok = resolvePreview({ meta: { name: 'web', preview_url: 'https://{branch}--web.netlify.app' }, platform: 'github', pr: 12,
278
+ runner: fakeRunner({ 'gh pr view 12': JSON.stringify({ headRefOid: SHA, headRefName: 'feat/cart' }) }), lookup });
279
+ assert.deepEqual(ok, { url: 'https://feat-cart--web.netlify.app', source: 'pattern' });
280
+ });
281
+
282
+ test('previewLine: the filled pattern in angle brackets, else the note', () => {
283
+ assert.equal(previewLine({ name: 'web', preview_url: 'https://{branch}.x.dev' }, { branch: 'feat/a' }), '<https://feat-a.x.dev>');
284
+ assert.equal(previewLine({ name: 'web', preview_url: 'https://pr-{pr}.x.dev' }, { branch: 'feat/a' }), PREVIEW_UNFILLED, '{pr} is filled after the PR exists, never "none recorded"');
285
+ assert.equal(previewLine({ name: 'web', preview_url: 'http://x.dev' }, {}), PREVIEW_UNUSABLE, 'an unusable pattern says so, never "none recorded"');
286
+ assert.match(PREVIEW_UNUSABLE, /yad repo preview <repo> <pattern>/);
287
+ assert.equal(previewLine({ name: 'web', preview_url: 'https://{branch}.x.dev' }, { branch: '///' }), PREVIEW_UNFILLED);
288
+ assert.equal(previewLine({ name: 'web' }, {}), PREVIEW_NONE);
289
+ assert.match(PREVIEW_NONE, /locally only/);
290
+ });
291
+
292
+ test('templateBody: the shipped templates carry the Preview line, and it is filled', () => {
293
+ const T = tmp();
294
+ try {
295
+ for (const platform of ['github', 'gitlab']) {
296
+ const body = templateBody(T, platform, { task: 'EP-a-S01-T01', risk: 'low', preview: '<https://pr.x.dev>' });
297
+ assert.match(body, /## Testing\n<!--[^\n]*-->\n- \*\*Preview:\*\* <https:\/\/pr\.x\.dev>\n/, platform);
298
+ assert.doesNotMatch(body, /\*\*Preview:\*\* none\n/);
299
+ assert.match(templateBody(T, platform, { task: 'EP-a-S01-T01', risk: 'low' }), /\*\*Preview:\*\* none\n/, 'no preview given: the template is left as it is');
300
+ }
301
+ } finally { done(T); }
302
+ });
303
+
304
+ test('withPreviewLine: only the Testing section; an older template gets the line there; no Testing is left alone', () => {
305
+ assert.equal(withPreviewLine('## Summary\nx\n\n## Testing\n<!-- how -->\nran it\n', 'P'), '## Summary\nx\n\n## Testing\n<!-- how -->\n- **Preview:** P\nran it\n');
306
+ assert.equal(withPreviewLine('## Testing\r\nran it\r\n', 'P'), '## Testing\r\n- **Preview:** P\r\nran it\r\n', 'a CRLF template keeps CRLF');
307
+ assert.equal(withPreviewLine('## Summary\nx\n', 'P'), '## Summary\nx\n');
308
+ assert.equal(withPreviewLine('**Preview:** mine\n', 'P'), '**Preview:** mine\n', 'no Testing section: nothing is touched');
309
+ assert.equal(withPreviewLine('## Testing\n- **Preview:** old\n', '$&'), '## Testing\n- **Preview:** $&\n', 'replaced in place, a $ kept');
310
+ // The Summary comes from the commit and may hold a line of its own that reads the same.
311
+ assert.equal(withPreviewLine('## Summary\n**Preview:** my notes\n\n## Testing\n- **Preview:** none\n\n## Checklist\n', 'P'),
312
+ '## Summary\n**Preview:** my notes\n\n## Testing\n- **Preview:** P\n\n## Checklist\n');
313
+ assert.equal(withPreviewLine('## Testing\nran it\n\n## Checklist\n- **Preview:** x\n', 'P'), '## Testing\n- **Preview:** P\nran it\n\n## Checklist\n- **Preview:** x\n', 'never past the next heading');
314
+ });
315
+
316
+ // A Product with one registered code repo on a task branch, pushable to a bare remote.
317
+ function productWithRepo(entry = {}) {
318
+ const P = tmp();
319
+ const bare = tmp();
320
+ const R = path.join(P, 'web');
321
+ git(bare, 'init', '-q', '--bare');
322
+ fs.mkdirSync(R);
323
+ git(R, 'init', '-q'); git(R, 'config', 'user.email', 'a@b.c'); git(R, 'config', 'user.name', 'x');
324
+ git(R, 'config', 'commit.gpgsign', 'false');
325
+ put(path.join(R, 'seed.txt'), '0'); git(R, 'add', '-A'); git(R, 'commit', '-q', '-m', 'feat: seed');
326
+ git(R, 'branch', '-q', '-M', 'main'); git(R, 'remote', 'add', 'origin', bare);
327
+ git(R, 'checkout', '-q', '-b', 'feat/EP-demo-S01-T01-cart');
328
+ put(path.join(P, '.sdlc/repos.json'), { repos: [{ name: 'web', path: 'web', platform: 'github', default_branch: 'main', ...entry }] });
329
+ return { P, R, bare };
330
+ }
331
+
332
+ test('runOpenPr: a {branch} pattern is in the body as the PR is opened', async () => {
333
+ const { P, bare } = productWithRepo({ preview_url: 'https://{branch}.x.dev' });
334
+ const prev = process.exitCode;
335
+ try {
336
+ let seen; let edited = false;
337
+ const creator = (_p, o) => { seen = o; return { ok: true, url: 'https://github.com/o/r/pull/41' }; };
338
+ await runOpenPr(P, { repo: 'web', platform: 'github', creator, editBody: () => { edited = true; return { ok: true }; }, runner: fakeRunner({}) });
339
+ assert.match(seen.body, /\*\*Preview:\*\* <https:\/\/feat-ep-demo-s01-t01-cart\.x\.dev>/);
340
+ assert.equal(edited, false, 'nothing to fill afterwards');
341
+ } finally { process.exitCode = prev; done(P, bare); }
342
+ });
343
+
344
+ test('templateBody: a summary with a ## Testing of its own never takes the Preview line', () => {
345
+ const T = tmp();
346
+ try {
347
+ const body = templateBody(T, 'github', { task: 'EP-a-S01-T01', risk: 'low', summary: 'fix x\n\n## Testing\nran it by hand', preview: '<https://p.x.dev>' });
348
+ const summaryPart = body.slice(0, body.indexOf('## Impact'));
349
+ assert.doesNotMatch(summaryPart, /Preview/, 'the summary is left as the commit wrote it');
350
+ assert.match(body.slice(body.indexOf('## Impact')), /\*\*Preview:\*\* <https:\/\/p\.x\.dev>/);
351
+ } finally { done(T); }
352
+ });
353
+
354
+ test('runOpenPr: a {pr} pattern is filled once the PR has its number', async () => {
355
+ const { P, bare } = productWithRepo({ preview_url: 'https://pr-{pr}.x.dev' });
356
+ const prev = process.exitCode;
357
+ try {
358
+ let seen; let edit;
359
+ const creator = (_p, o) => { seen = o; return { ok: true, url: 'https://github.com/o/r/pull/41' }; };
360
+ const editBody = (platform, n, body) => { edit = { platform, n, body }; return { ok: true }; };
361
+ await runOpenPr(P, { repo: 'web', platform: 'github', creator, editBody, runner: fakeRunner({}) });
362
+ assert.match(seen.body, /\*\*Preview:\*\* a preview_url pattern is recorded but could not be filled/, 'at open time the number is not known');
363
+ assert.equal(edit.n, 41);
364
+ assert.match(edit.body, /\*\*Preview:\*\* <https:\/\/pr-41\.x\.dev>/);
365
+ assert.equal(edit.body.replace(/\*\*Preview:\*\*[^\n]*/, ''), seen.body.replace(/\*\*Preview:\*\*[^\n]*/, ''), 'only the Preview line changes');
366
+ } finally { process.exitCode = prev; done(P, bare); }
367
+ });
368
+
369
+ test('runOpenPr: a failed edit is said, and the PR stays open; no pattern writes the note', async () => {
370
+ const prev = process.exitCode;
371
+ let { P, bare } = productWithRepo({ preview_url: 'https://pr-{pr}.x.dev' });
372
+ try {
373
+ process.exitCode = 0;
374
+ const creator = () => ({ ok: true, url: 'https://github.com/o/r/pull/41' });
375
+ const warned = [];
376
+ const orig = console.log;
377
+ console.log = (...a) => warned.push(a.join(' '));
378
+ try { await runOpenPr(P, { repo: 'web', platform: 'github', creator, editBody: () => ({ ok: false, reason: 'boom' }), runner: fakeRunner({}) }); }
379
+ finally { console.log = orig; }
380
+ assert.ok(warned.some((l) => /Preview line could not be filled \(boom\).*pr-41\.x\.dev/.test(l)), warned.join('\n'));
381
+ assert.ok(!process.exitCode, 'not a failure');
382
+ } finally { process.exitCode = prev; done(P, bare); }
383
+ ({ P, bare } = productWithRepo());
384
+ try {
385
+ let seen;
386
+ await runOpenPr(P, { repo: 'web', platform: 'github', creator: (_p, o) => { seen = o; return { ok: true, url: 'https://github.com/o/r/pull/2' }; }, runner: fakeRunner({}) });
387
+ assert.match(seen.body, /\*\*Preview:\*\* none recorded — a live design check runs locally only/);
388
+ } finally { process.exitCode = prev; done(P, bare); }
389
+ });
390
+
391
+ test('runOpenPr: an unusable pattern warns and the body says a pattern is recorded; a template with no place skips the edit', async () => {
392
+ const prev = process.exitCode;
393
+ let { P, bare } = productWithRepo({ preview_url: 'http://x.dev' });
394
+ let R;
395
+ const quiet = async (fn) => { const out = []; const orig = console.log; console.log = (...a) => out.push(a.join(' ')); try { await fn(); } finally { console.log = orig; } return out.join('\n'); };
396
+ try {
397
+ let seen;
398
+ const out = await quiet(() => runOpenPr(P, { repo: 'web', platform: 'github', creator: (_p, o) => { seen = o; return { ok: true, url: 'https://github.com/o/r/pull/3' }; }, runner: fakeRunner({}) }));
399
+ assert.match(out, /preview_url pattern cannot be used: it must start with https/);
400
+ assert.match(seen.body, /\*\*Preview:\*\* the recorded preview_url pattern cannot be used/);
401
+ } finally { process.exitCode = prev; done(P, bare); }
402
+ ({ P, R, bare } = productWithRepo({ preview_url: 'https://pr-{pr}.x.dev' }));
403
+ try {
404
+ put(path.join(R, '.github/pull_request_template.md'), '## Summary\n\n## Impact & Risk\n- **Risk level:** low\n\n## Checklist\n');
405
+ let edited = false;
406
+ const out = await quiet(() => runOpenPr(P, { repo: 'web', platform: 'github', creator: () => ({ ok: true, url: 'https://github.com/o/r/pull/8' }), editBody: () => { edited = true; return { ok: true }; }, runner: fakeRunner({}) }));
407
+ assert.equal(edited, false, 'nothing to change: no edit is sent');
408
+ assert.match(out, /no ## Testing section.*https:\/\/pr-8\.x\.dev/);
409
+ assert.doesNotMatch(out, /✓ preview/);
410
+ } finally { process.exitCode = prev; done(P, bare); }
411
+ });
412
+
413
+ test('runOpenPr: a PR URL with no readable number leaves the line unfilled and says so', async () => {
414
+ const { P, bare } = productWithRepo({ preview_url: 'https://pr-{pr}.x.dev' });
415
+ const prev = process.exitCode;
416
+ try {
417
+ let seen; let edited = false;
418
+ const out = []; const orig = console.log; console.log = (...a) => out.push(a.join(' '));
419
+ try { await runOpenPr(P, { repo: 'web', platform: 'github', creator: (_p, o) => { seen = o; return { ok: true, url: 'https://example.com/x' }; }, editBody: () => { edited = true; return { ok: true }; }, runner: fakeRunner({}) }); }
420
+ finally { console.log = orig; }
421
+ assert.equal(edited, false);
422
+ assert.match(out.join('\n'), /left unfilled \(`yad review context --pr <n>` gives the address\)/);
423
+ assert.ok(seen.body.includes(PREVIEW_UNFILLED));
424
+ } finally { process.exitCode = prev; done(P, bare); }
425
+ });
426
+
427
+ test('review context: carries the preview — the pattern, or local-only with why', async () => {
428
+ const { P, bare } = productWithRepo({ preview_url: 'https://pr-{pr}.x.dev' });
429
+ try {
430
+ const runner = fakeRunner({});
431
+ const b = await reviewContext(P, { repo: 'web', pr: 12, runner });
432
+ assert.deepEqual(b.preview, { url: 'https://pr-12.x.dev', source: 'pattern' });
433
+ assert.ok(!runner.calls.some((c) => c.includes('deployments')), 'the pattern answers without asking the host');
434
+ } finally { done(P, bare); }
435
+ const other = productWithRepo();
436
+ try {
437
+ const runner = fakeRunner({ 'gh api': '[]' });
438
+ const b = await reviewContext(other.P, { repo: 'web', pr: 12, runner });
439
+ assert.equal(b.preview.source, 'local-only');
440
+ assert.match(b.preview.why, /no preview_url pattern/);
441
+ } finally { done(other.P, other.bare); }
442
+ });
443
+
444
+ test('yad repo preview: show, set, refuse a bad pattern, clear', () => {
445
+ const { P, bare } = productWithRepo();
446
+ try {
447
+ const reg = () => JSON.parse(fs.readFileSync(path.join(P, '.sdlc/repos.json'), 'utf8')).repos[0];
448
+ let r = yad(P, 'repo', 'preview', 'web', '--json');
449
+ assert.equal(r.status, 0, r.stderr);
450
+ assert.equal(JSON.parse(r.stdout).preview_url, null);
451
+ r = yad(P, 'repo', 'preview', 'web', 'https://pr-{pr}.x.dev');
452
+ assert.equal(r.status, 0, r.stderr + r.stdout);
453
+ assert.equal(reg().preview_url, 'https://pr-{pr}.x.dev');
454
+ assert.match(r.stdout + r.stderr, /commit \.sdlc\/repos\.json/);
455
+ const before = fs.readFileSync(path.join(P, '.sdlc/repos.json'), 'utf8');
456
+ r = yad(P, 'repo', 'preview', 'web', 'http://pr-{pr}.x.dev');
457
+ assert.equal(r.status, 1);
458
+ assert.match(r.stdout + r.stderr, /must start with https:\/\/ .*nothing written/);
459
+ assert.equal(fs.readFileSync(path.join(P, '.sdlc/repos.json'), 'utf8'), before, 'nothing written');
460
+ r = yad(P, 'repo', 'preview', 'nope', 'https://x.dev');
461
+ assert.equal(r.status, 1);
462
+ assert.match(r.stdout + r.stderr, /unknown repo: nope/);
463
+ r = yad(P, 'repo', 'preview', 'web', 'https://x.dev', '--clear');
464
+ assert.equal(r.status, 1, 'a pattern and --clear together');
465
+ r = yad(P, 'repo', 'preview', 'web', 'https://a', '--push');
466
+ assert.equal(r.status, 1, '--push is refused, not ignored');
467
+ assert.match(r.stdout + r.stderr, /--push does not apply/);
468
+ r = yad(P, 'repo', 'preview', 'web', 'https://a', 'extra');
469
+ assert.notEqual(r.status, 0, 'an extra word is refused');
470
+ r = yad(P, 'repo', 'list', '--json');
471
+ assert.equal(JSON.parse(r.stdout).repos[0].preview_url, 'https://pr-{pr}.x.dev');
472
+ r = yad(P, 'repo', 'preview', 'web', '--clear');
473
+ assert.equal(r.status, 0, r.stderr);
474
+ assert.ok(!('preview_url' in reg()));
475
+ } finally { done(P, bare); }
476
+ });
477
+
478
+ test('yad repo preview: a registry that does not parse is refused, never overwritten', () => {
479
+ const P = tmp();
480
+ try {
481
+ put(path.join(P, '.sdlc/repos.json'), '{ broken');
482
+ const r = yad(P, 'repo', 'preview', 'web', 'https://x.dev');
483
+ assert.equal(r.status, 1);
484
+ assert.equal(fs.readFileSync(path.join(P, '.sdlc/repos.json'), 'utf8'), '{ broken');
485
+ } finally { done(P); }
486
+ });
487
+
488
+ test('doctor: repos:preview warns on an unusable pattern and is silent when none is recorded', () => {
489
+ const rows = (entries) => { const checks = []; previewChecks(checks, entries); return checks; };
490
+ assert.deepEqual(rows([{ name: 'web' }]), [], 'no pattern: nothing said');
491
+ const okRow = rows([{ name: 'web', preview_url: 'https://pr-{pr}.x.dev' }]);
492
+ assert.equal(okRow.length, 1);
493
+ assert.equal(okRow[0].status, 'ok');
494
+ const bad = rows([{ name: 'web', preview_url: 'http://x.dev' }, { name: 'api', preview_url: 'https://ok.dev' }]);
495
+ assert.equal(bad[0].status, 'warn');
496
+ assert.equal(bad[0].id, 'repos:preview');
497
+ assert.match(bad[0].message, /web: it must start with https/);
498
+ assert.match(bad[0].hint, /yad repo preview web <pattern>/);
499
+ });
500
+
501
+ test('skills: the review skills use review context\'s preview and say when the check ran locally only', () => {
502
+ for (const s of ['yad-engineer-review', 'yad-review-companion', 'yad-pair-review']) {
503
+ const text = fs.readFileSync(path.join(REPO, 'skills', s, 'SKILL.md'), 'utf8');
504
+ assert.match(text, /`preview`/, s);
505
+ assert.match(text, /locally only/, s);
506
+ assert.match(text, /preview\.url/, s);
507
+ }
508
+ const connect = fs.readFileSync(path.join(REPO, 'skills/yad-connect-repos/SKILL.md'), 'utf8');
509
+ assert.match(connect, /preview_url/);
510
+ assert.match(connect, /yad repo preview/);
511
+ });