@su-sws/synthetic-web-team 0.1.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 (82) hide show
  1. package/AGENTS.md +149 -0
  2. package/README.md +321 -0
  3. package/package.json +58 -0
  4. package/packages/cli/bin/sws.mjs +722 -0
  5. package/packages/cli/src/axe.mjs +164 -0
  6. package/packages/cli/src/browser.mjs +192 -0
  7. package/packages/cli/src/checks.mjs +1254 -0
  8. package/packages/cli/src/github.mjs +131 -0
  9. package/packages/cli/src/history.mjs +137 -0
  10. package/packages/cli/src/perf.mjs +245 -0
  11. package/packages/cli/src/preflight.mjs +185 -0
  12. package/packages/cli/src/report.mjs +315 -0
  13. package/packages/cli/src/states.mjs +556 -0
  14. package/packages/wizard/bin/wizard.mjs +767 -0
  15. package/packages/wizard/src/detect.mjs +135 -0
  16. package/packages/wizard/src/emit.mjs +553 -0
  17. package/skills/role-accessibility-lead/SKILL.md +183 -0
  18. package/skills/role-api-architect/SKILL.md +65 -0
  19. package/skills/role-backend-developer/SKILL.md +66 -0
  20. package/skills/role-compliance-officer/SKILL.md +73 -0
  21. package/skills/role-content-designer/SKILL.md +145 -0
  22. package/skills/role-devops/SKILL.md +200 -0
  23. package/skills/role-discoverability/SKILL.md +164 -0
  24. package/skills/role-frontend-developer/SKILL.md +167 -0
  25. package/skills/role-fullstack-developer/SKILL.md +56 -0
  26. package/skills/role-identity-engineer/SKILL.md +77 -0
  27. package/skills/role-information-architect/SKILL.md +136 -0
  28. package/skills/role-infrastructure-architect/SKILL.md +60 -0
  29. package/skills/role-qa-engineer/SKILL.md +81 -0
  30. package/skills/role-security-operations/SKILL.md +56 -0
  31. package/skills/role-software-architect/SKILL.md +75 -0
  32. package/skills/role-staff-technical-architect/SKILL.md +73 -0
  33. package/skills/role-strategist/SKILL.md +122 -0
  34. package/skills/role-user-researcher/SKILL.md +66 -0
  35. package/skills/role-ux-designer/SKILL.md +159 -0
  36. package/skills/sws-compliance-check/SKILL.md +153 -0
  37. package/skills/sws-decanter/SKILL.md +191 -0
  38. package/skills/sws-deploy/SKILL.md +162 -0
  39. package/skills/sws-diverge/SKILL.md +131 -0
  40. package/skills/sws-github/SKILL.md +171 -0
  41. package/skills/sws-install/SKILL.md +97 -0
  42. package/skills/sws-netlify/SKILL.md +110 -0
  43. package/skills/sws-onboard/SKILL.md +85 -0
  44. package/skills/sws-preflight/SKILL.md +87 -0
  45. package/skills/sws-prior-art/SKILL.md +137 -0
  46. package/skills/sws-vercel/SKILL.md +117 -0
  47. package/standards/fragments/global-footer.yml +137 -0
  48. package/standards/fragments/identity-bar.yml +180 -0
  49. package/standards/hosting/capabilities.yml +215 -0
  50. package/standards/hosting/github-pages.yml +306 -0
  51. package/standards/hosting/netlify.yml +234 -0
  52. package/standards/hosting/vercel.yml +284 -0
  53. package/standards/patterns/components.md +162 -0
  54. package/standards/patterns/content.md +130 -0
  55. package/standards/patterns/decanter.md +352 -0
  56. package/standards/patterns/discoverability.md +121 -0
  57. package/standards/patterns/forms.md +116 -0
  58. package/standards/patterns/ia.md +126 -0
  59. package/standards/patterns/motion.md +267 -0
  60. package/standards/patterns/sws-conventions.md +225 -0
  61. package/standards/policy/accessibility.md +241 -0
  62. package/standards/policy/brand.md +213 -0
  63. package/standards/policy/escalation.md +53 -0
  64. package/standards/policy/identity.md +96 -0
  65. package/standards/policy/minsec.md +119 -0
  66. package/standards/policy/minweb.md +87 -0
  67. package/standards/policy/privacy.md +114 -0
  68. package/standards/policy/procurement.md +79 -0
  69. package/standards/prior-art/README.md +205 -0
  70. package/standards/prior-art/catalog.yml +409 -0
  71. package/standards/prior-art/patterns/INDEX.md +53 -0
  72. package/standards/prior-art/repos.yml +734 -0
  73. package/standards/recipes/astro-ssr/RECIPE.md +274 -0
  74. package/standards/recipes/astro-ssr/acceptance.yml +168 -0
  75. package/standards/recipes/astro-static/RECIPE.md +468 -0
  76. package/standards/recipes/astro-static/acceptance.yml +800 -0
  77. package/standards/recipes/next-ssr/RECIPE.md +407 -0
  78. package/standards/recipes/next-ssr/acceptance.yml +187 -0
  79. package/standards/scope.md +111 -0
  80. package/standards/stack/performance-budget.yml +95 -0
  81. package/standards/stack/reference-versions.yml +168 -0
  82. package/standards/stack/requirements.yml +154 -0
@@ -0,0 +1,722 @@
1
+ #!/usr/bin/env node
2
+ // sws: advisory compliance checks for Stanford websites.
3
+ //
4
+ // Design commitments, enforced here rather than documented elsewhere:
5
+ // - `doctor` ALWAYS exits 0. It is a conversation, not a gate.
6
+ // - `check` exits non-zero ONLY for a blocking finding. Today that is exactly
7
+ // one thing: committed secrets.
8
+ // - A check that cannot run reports `unknown`, never `pass`.
9
+
10
+ import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
11
+ import { join, resolve, dirname, relative } from 'node:path';
12
+ import { fileURLToPath } from 'node:url';
13
+ import { parseArgs } from 'node:util';
14
+ import YAML from 'yaml';
15
+ import { ALL, findHtml } from '../src/checks.mjs';
16
+ import { runAxe, RESULTS_PATH as AXE_RESULTS_PATH } from '../src/axe.mjs';
17
+ import { runPerf, RESULTS_PATH as PERF_RESULTS_PATH } from '../src/perf.mjs';
18
+ import { runStates, RESULTS_PATH as STATE_RESULTS_PATH } from '../src/states.mjs';
19
+ import {
20
+ score, renderTerminal, renderMarkdown, renderJson, group,
21
+ renderPrComment, renderIssueBody, renderHtml, renderBadge,
22
+ } from '../src/report.mjs';
23
+ import * as history from '../src/history.mjs';
24
+ import * as gh from '../src/github.mjs';
25
+ import { preflight, summarise } from '../src/preflight.mjs';
26
+ // Sibling directory inside the same published package (@su-sws/synthetic-web-team), so this
27
+ // relative path resolves in the repository and in a tarball alike. One reader
28
+ // of the install record means the CLI and the wizard cannot disagree about what
29
+ // "installed" means.
30
+ import { readInstalled } from '../../wizard/src/emit.mjs';
31
+
32
+ const HERE = dirname(fileURLToPath(import.meta.url));
33
+
34
+ // `standards/` ships in the same package as this file (@su-sws/synthetic-web-team), so the
35
+ // relative walk below finds it in both the published layout and this
36
+ // repository. There used to be an `import('@su-sws/standards')` fallback here;
37
+ // consolidating content and tools into one package removed the need for it,
38
+ // along with the cross-package version skew it could produce.
39
+
40
+ const { values: flags, positionals } = parseArgs({
41
+ allowPositionals: true,
42
+ options: {
43
+ dist: { type: 'string' },
44
+ standards: { type: 'string' },
45
+ recipe: { type: 'string' },
46
+ format: { type: 'string', default: 'terminal' },
47
+ out: { type: 'string' },
48
+ strict: { type: 'boolean', default: false },
49
+ 'no-summary': { type: 'boolean', default: false },
50
+ 'no-publish': { type: 'boolean', default: false },
51
+ 'html': { type: 'string' },
52
+ 'badge': { type: 'string' },
53
+ help: { type: 'boolean', short: 'h', default: false },
54
+ },
55
+ });
56
+
57
+ const cmd = positionals[0] ?? 'doctor';
58
+ const root = resolve(process.cwd());
59
+
60
+ // With --format json, stdout is exactly one JSON document. Every other line --
61
+ // the trend, publish confirmations, warnings -- goes to stderr.
62
+ //
63
+ // This was a real bug: the trend line was appended to stdout after the JSON, so
64
+ // `sws doctor --format json | jq` failed, and the MCP server's sws_check tool
65
+ // reported "output that is not JSON" while looking at valid JSON with a
66
+ // sentence stuck to the end of it. Machine-readable means machine-readable.
67
+ const note = (...a) => (flags.format === 'json' ? console.error(...a) : console.log(...a));
68
+
69
+ const USAGE = `
70
+ sws <command>
71
+
72
+ preflight Is this machine equipped to build and deploy? Checks the
73
+ tools in standards/stack/requirements.yml and reports what
74
+ is missing. It does NOT install anything and does not say
75
+ how to: install what it names, your own way, then run it
76
+ again to confirm. Exits 0 unless --strict.
77
+ doctor Friendly local report. Always exits 0.
78
+ check Full run for CI. Exits non-zero only on a blocking finding.
79
+ a11y Run axe over every built route, then measure hover and
80
+ focus states with a real mouse and a real Tab key. Writes
81
+ .sws/axe-results.json and .sws/state-results.json, which
82
+ check and doctor then read. Always exits 0.
83
+ Needs @playwright/test and @axe-core/playwright in THIS
84
+ project, plus: npx playwright install chromium
85
+ perf Measure the performance budget in a real browser. Writes
86
+ .sws/perf-results.json. Needs @playwright/test. Exits 0.
87
+ prior-art scan Index Stanford projects on this machine. Never transmitted.
88
+ version
89
+
90
+ --dist <dir> Build output (default: auto-detect dist, _site, build, out)
91
+ --standards <dir> Standards directory (default: auto-detect)
92
+ --recipe <id> Recipe id (default: from .sws/manifest.yml, else astro-static)
93
+ --format terminal | json | markdown
94
+ --out <file> Write the report to a file as well as stdout
95
+ --strict Treat every failure as blocking. Opt-in, off by default.
96
+ --no-summary Do not append to \$GITHUB_STEP_SUMMARY.
97
+ --no-publish Do not write the PR comment or the Site health issue.
98
+ --html <file> Also write a standalone HTML report.
99
+ --badge <file> Write a shields.io endpoint JSON for a README badge.
100
+
101
+ In CI, check upserts ONE PR comment on a pull request, or ONE persistent
102
+ "Site health" issue on a push to the default branch. Both are updated in
103
+ place, never duplicated. Needs issues:write and pull-requests:write.
104
+ Publishing never fails the build: a network or permission error is reported
105
+ and the exit code is unaffected.
106
+
107
+ In GitHub Actions the report is appended to the job summary automatically,
108
+ unless --format markdown (you are handling output) or --no-summary. One
109
+ invocation is enough; do not also redirect into the summary file.
110
+ `;
111
+
112
+ if (flags.help) { console.log(USAGE); process.exit(0); }
113
+
114
+ // Does this project look like it was installed by the wizard?
115
+ //
116
+ // A `.sws/manifest.yml` alone is NOT enough evidence, and assuming it was cost a
117
+ // false nag on this project's own docs site: `site/` is hand-built inside this
118
+ // repository and carries a manifest, but nothing was ever vendored into it. The
119
+ // advice "re-run the installer" would have written 46 files of standards and
120
+ // page furniture into a directory that wants none of them.
121
+ //
122
+ // The real signature of a wizard install is vendored content, so look for that.
123
+ //
124
+ // THE SIGNATURE MOVED when the install split in two. This used to look for
125
+ // `.agents/skills` or `.claude/skills`, which a project install no longer
126
+ // writes -- skills are installed once into the person's tool instead. So it
127
+ // returned false for every correctly installed project, and the caller's "no
128
+ // install record" nag silently stopped firing. Verified: a fresh project with
129
+ // its record deleted reported nothing.
130
+ //
131
+ // `standards/` is the right test now. It is what a project install actually
132
+ // vendors, and `site/` has neither it nor an AGENTS.md, so the original false
133
+ // nag stays fixed.
134
+ function wizardInstalled(dir) {
135
+ return existsSync(join(dir, 'AGENTS.md')) && existsSync(join(dir, 'standards'));
136
+ }
137
+
138
+ // --- locate things ----------------------------------------------------------
139
+
140
+ // A project normally vendors `standards/` (the wizard copies it in), so the
141
+ // local lookups come first and win. The last entry is the copy that ships
142
+ // alongside this CLI, which covers `npx -p @su-sws/synthetic-web-team sws doctor` in a project
143
+ // that never vendored them.
144
+ function findStandards() {
145
+ if (flags.standards) return resolve(flags.standards);
146
+ for (const c of [
147
+ join(root, 'standards'),
148
+ join(root, '.sws', 'standards'),
149
+ resolve(HERE, '..', '..', '..', 'standards'),
150
+ ]) if (existsSync(c)) return c;
151
+ return null;
152
+ }
153
+
154
+ function findDist() {
155
+ if (flags.dist) return resolve(flags.dist);
156
+ for (const c of ['dist', '_site', 'build', 'out']) {
157
+ if (existsSync(join(root, c))) return join(root, c);
158
+ }
159
+ return join(root, 'dist');
160
+ }
161
+
162
+ function loadManifest() {
163
+ const p = join(root, '.sws', 'manifest.yml');
164
+ if (!existsSync(p)) return {};
165
+ try { return YAML.parse(readFileSync(p, 'utf8')) || {}; } catch { return {}; }
166
+ }
167
+
168
+ function loadAcknowledged() {
169
+ const p = join(root, '.sws', 'acknowledged.yml');
170
+ if (!existsSync(p)) return [];
171
+ try {
172
+ const y = YAML.parse(readFileSync(p, 'utf8'));
173
+ return Array.isArray(y) ? y : (y?.accepted ?? []);
174
+ } catch { return []; }
175
+ }
176
+
177
+ // Recipes may `extends: <recipeId>`. Only differences live in the child, so the
178
+ // shared criteria cannot drift between recipes, which is the failure this whole
179
+ // project is organised against.
180
+ //
181
+ // Merge rules:
182
+ // - parent criteria are inherited
183
+ // - `overrides:` with `applies: false` REMOVES an inherited criterion
184
+ // - any other `overrides:` entry patches the inherited one field by field
185
+ // - `criteria:` in the child adds new ones, or replaces by id
186
+ function loadAcceptance(standards, recipeId, seen = new Set()) {
187
+ const p = join(standards, 'recipes', recipeId, 'acceptance.yml');
188
+ if (!existsSync(p)) return null;
189
+ if (seen.has(recipeId)) {
190
+ console.error(`Circular recipe extends chain at "${recipeId}".`);
191
+ process.exit(2);
192
+ }
193
+ seen.add(recipeId);
194
+
195
+ const own = YAML.parse(readFileSync(p, 'utf8')) || {};
196
+ if (!own.extends) return { ...own, criteria: own.criteria ?? [] };
197
+
198
+ const parent = loadAcceptance(standards, own.extends, seen);
199
+ if (!parent) {
200
+ console.error(`Recipe "${recipeId}" extends "${own.extends}", which was not found.`);
201
+ process.exit(2);
202
+ }
203
+
204
+ const merged = new Map((parent.criteria ?? []).map((c) => [c.id, c]));
205
+ for (const o of own.overrides ?? []) {
206
+ if (!merged.has(o.id)) {
207
+ console.error(`Warning: ${recipeId} overrides "${o.id}", which the parent does not define.`);
208
+ continue;
209
+ }
210
+ if (o.applies === false) merged.delete(o.id);
211
+ else merged.set(o.id, { ...merged.get(o.id), ...o });
212
+ }
213
+ for (const c of own.criteria ?? []) merged.set(c.id, c);
214
+
215
+ return {
216
+ ...parent, ...own,
217
+ extends: own.extends,
218
+ inherited_from: [own.extends, ...(parent.inherited_from ?? [])],
219
+ criteria: [...merged.values()],
220
+ };
221
+ }
222
+
223
+ // --- run --------------------------------------------------------------------
224
+
225
+ async function run() {
226
+ const standards = findStandards();
227
+ if (!standards) {
228
+ console.error('Could not find a standards/ directory. Pass --standards <dir>.');
229
+ process.exit(2);
230
+ }
231
+
232
+ const manifest = loadManifest();
233
+ const recipeId = flags.recipe || manifest.recipe || 'astro-static';
234
+ const acceptance = loadAcceptance(standards, recipeId);
235
+ if (!acceptance) {
236
+ console.error(`No acceptance.yml for recipe "${recipeId}" under ${standards}/recipes/.`);
237
+ process.exit(2);
238
+ }
239
+
240
+ const dist = findDist();
241
+ const html = findHtml(dist);
242
+ const ctx = { root, dist, html, standards, manifest };
243
+
244
+ // Run every check module once; they each return several findings.
245
+ const raw = [];
246
+ for (const [name, fn] of Object.entries(ALL)) {
247
+ try {
248
+ raw.push(...fn(ctx));
249
+ } catch (err) {
250
+ raw.push({ id: `${name}.internal-error`, state: 'unknown',
251
+ detail: `check crashed: ${err.message}` });
252
+ }
253
+ }
254
+
255
+ // Attach weights and severities from the criteria. A finding with no matching
256
+ // criterion still reports, at weight 0, so a check is never silently dropped.
257
+ const byId = new Map((acceptance.criteria || []).map((c) => [c.id, c]));
258
+ const ack = loadAcknowledged();
259
+ const now = new Date();
260
+
261
+ const findings = raw.map((f) => {
262
+ const c = byId.get(f.id) || {};
263
+ const a = ack.find((x) => x.check === f.id);
264
+ let state = f.state;
265
+ let note;
266
+ if (a && state === 'fail') {
267
+ state = 'acknowledged';
268
+ note = `accepted by ${a.accepted_by ?? 'unknown'}${a.reason ? `: ${a.reason}` : ''}`;
269
+ if (a.review_by && new Date(a.review_by) < now) note += ` [review overdue since ${a.review_by}]`;
270
+ }
271
+ return {
272
+ ...f, state,
273
+ detail: note ? `${f.detail} (${note})` : f.detail,
274
+ weight: c.weight ?? 0,
275
+ severity: c.severity ?? 'warn',
276
+ blocking: f.blocking || c.severity === 'block',
277
+ policy: c.policy ?? null,
278
+ };
279
+ });
280
+
281
+ // Any criterion that produced NO finding is reported as `unknown`, never
282
+ // silently dropped. A criterion absent from the report is invisible: the
283
+ // reader cannot tell it passed, failed, or never ran. This bit us on a Next
284
+ // project with no build output, where five inherited criteria vanished.
285
+ for (const c of acceptance.criteria || []) {
286
+ if (findings.some((f) => f.id === c.id)) continue;
287
+ findings.push({
288
+ id: c.id,
289
+ state: 'unknown',
290
+ detail: c.manual
291
+ ? 'manual step, not automatable'
292
+ // Declared debt reads differently from a missing prerequisite, and
293
+ // conflating them was how `perf.budget` looked like a build problem for
294
+ // weeks. Say "not built yet" plainly; the points stay withheld either way.
295
+ : c.unimplemented
296
+ ? `no check implemented yet, so its ${c.weight ?? 0} point(s) are withheld. ${
297
+ String(c.unimplemented).trim().replace(/\s+/g, ' ')}`
298
+ : `no check produced a result. Usually means a prerequisite is missing: ${
299
+ c.check === 'footer' || c.check === 'identity' || c.check === 'a11y' || c.check === 'seo'
300
+ ? 'no build output, so run the build first'
301
+ : c.check === 'decanter'
302
+ ? 'dependencies are not installed'
303
+ : 'see the recipe'}`,
304
+ weight: c.weight ?? 0,
305
+ severity: c.severity ?? 'info',
306
+ blocking: false,
307
+ policy: c.policy ?? null,
308
+ });
309
+ }
310
+
311
+ // A criterion the recipe removed via `applies: false` should not appear at
312
+ // all, even if its check still emits a finding.
313
+ const declared = new Set((acceptance.criteria || []).map((c) => c.id));
314
+ for (let i = findings.length - 1; i >= 0; i--) {
315
+ const f = findings[i];
316
+ if (!declared.has(f.id) && f.state === 'not_applicable') findings.splice(i, 1);
317
+ }
318
+
319
+ findings.sort((a, b) => a.id.localeCompare(b.id));
320
+ const sc = score(findings);
321
+ const blocking = findings.filter((f) => f.blocking && f.state === 'fail');
322
+
323
+ const payload = { findings, sc, recipe: recipeId, blocking };
324
+ const render = { json: renderJson, markdown: renderMarkdown, terminal: renderTerminal };
325
+ const text = (render[flags.format] ?? renderTerminal)(payload);
326
+ console.log(text);
327
+
328
+ if (flags.out) {
329
+ mkdirSync(dirname(resolve(flags.out)), { recursive: true });
330
+ writeFileSync(resolve(flags.out), text);
331
+ }
332
+
333
+ // GitHub job summary, so a trunk push reports somewhere a human will look.
334
+ //
335
+ // Only when the caller did NOT ask for markdown on stdout. Otherwise a
336
+ // workflow doing `sws check --format markdown >> $GITHUB_STEP_SUMMARY` gets
337
+ // the report twice from one invocation, and a workflow that also runs the
338
+ // terminal format gets it three times. That happened on the first real run of
339
+ // this project's own Pages workflow.
340
+ //
341
+ // `--no-summary` opts out entirely, for a caller that wants full control.
342
+ const wantsSummary =
343
+ process.env.GITHUB_STEP_SUMMARY && flags.format !== 'markdown' && !flags['no-summary'];
344
+ if (wantsSummary) {
345
+ writeFileSync(process.env.GITHUB_STEP_SUMMARY, renderMarkdown(payload) + '\n', { flag: 'a' });
346
+ }
347
+
348
+ // --- trend, artifacts, publishing ----------------------------------------
349
+ //
350
+ // Two histories, deliberately not reconciled. The LOCAL one is a
351
+ // per-developer convenience for `doctor`'s "since your last run"; the SHARED
352
+ // one lives in the Site health issue body so the project trend is not
353
+ // polluted by one person's local runs. See src/history.mjs.
354
+
355
+ const ghCtx = gh.context();
356
+ const entry = history.entryFor({
357
+ score: sc.value, findings, sha: ghCtx?.sha, ref: ghCtx?.ref, runId: ghCtx?.runId,
358
+ });
359
+
360
+ // Local delta. Recorded for both commands, shown only by doctor: in CI the
361
+ // shared trend is the meaningful one and two numbers would confuse.
362
+ const localBefore = history.readLocal(root);
363
+ history.appendLocal(root, entry);
364
+ if (cmd === 'doctor') {
365
+ const t = history.trend(sc.value, localBefore);
366
+ if (t) {
367
+ note(t.delta === 0
368
+ ? ` Unchanged since your last local run.\n`
369
+ : ` Score ${sc.value}, ${t.text} since your last local run.\n`);
370
+ }
371
+ }
372
+
373
+ // Read the shared history BEFORE composing anything, because the trend line
374
+ // has to compare against the previous run rather than this one.
375
+ let existingIssue = null;
376
+ let sharedHistory = [];
377
+ const wantsPublish = ghCtx && ghCtx.token && !flags['no-publish'] && cmd === 'check';
378
+ if (wantsPublish) {
379
+ const found = await gh.findHealthIssue(ghCtx);
380
+ if (found.error) console.error(` note: could not read the Site health issue (${found.error})`);
381
+ existingIssue = found.issue ?? null;
382
+ sharedHistory = history.parseFromBody(existingIssue?.body);
383
+ }
384
+
385
+ const trend = history.trend(sc.value, sharedHistory.length ? sharedHistory : localBefore);
386
+ const spark = history.sparkline([...sharedHistory, entry]);
387
+
388
+ if (flags.html) {
389
+ mkdirSync(dirname(resolve(flags.html)), { recursive: true });
390
+ writeFileSync(resolve(flags.html), renderHtml(payload, { trend, spark, sha: ghCtx?.sha, runUrl: ghCtx?.runUrl }));
391
+ }
392
+ if (flags.badge) {
393
+ mkdirSync(dirname(resolve(flags.badge)), { recursive: true });
394
+ writeFileSync(resolve(flags.badge), renderBadge(sc) + '\n');
395
+ }
396
+
397
+ if (wantsPublish) {
398
+ const isPr = Boolean(ghCtx.pr);
399
+ if (isPr) {
400
+ const r = await gh.upsertPrComment(ghCtx, renderPrComment(payload, { trend, runUrl: ghCtx.runUrl }));
401
+ if (r.error) console.error(` note: PR comment failed (${r.error})`);
402
+ else if (r.action) note(` PR comment ${r.action}: ${r.url}`);
403
+ } else {
404
+ const body = renderIssueBody(payload, {
405
+ trend, spark, runUrl: ghCtx.runUrl, sha: ghCtx.sha,
406
+ }) + '\n\n' + history.embedInBody([...sharedHistory, entry]);
407
+ const r = await gh.upsertHealthIssue(ghCtx, body, existingIssue);
408
+ if (r.error) console.error(` note: Site health issue failed (${r.error})`);
409
+ else if (r.action) note(` Site health issue ${r.action}: ${r.url}`);
410
+ }
411
+ } else if (ghCtx && !ghCtx.token && cmd === 'check' && !flags['no-publish']) {
412
+ console.error(' note: in CI without GITHUB_TOKEN, so no PR comment or issue was written.');
413
+ }
414
+
415
+ // --- is this project on stale standards? ---------------------------------
416
+ //
417
+ // A doctor NOTE, deliberately not a finding. Being behind is a maintenance
418
+ // fact about the toolchain, not a compliance fact about the site, and scoring
419
+ // it would mean a project loses points for something that has nothing to do
420
+ // with whether it meets Stanford's requirements.
421
+ //
422
+ // The comparison is free because content and tools ship in ONE package
423
+ // (@su-sws/synthetic-web-team), so the version of this CLI *is* the version of the standards
424
+ // it carries. No network call, no registry lookup.
425
+ if (cmd === 'doctor') {
426
+ const installed = readInstalled(root);
427
+ const mine = (() => {
428
+ try { return JSON.parse(readFileSync(resolve(HERE, '..', '..', '..', 'package.json'), 'utf8')).version; }
429
+ catch { return null; }
430
+ })();
431
+ if (installed?.version && mine && installed.version !== mine) {
432
+ note(` Standards in this project are v${installed.version}; this tool carries v${mine}.`);
433
+ note(` To update: npx @su-sws/synthetic-web-team add .`);
434
+ note(` ${'Content is rewritten, your .sws state is preserved, and files you edited'}`);
435
+ note(` are reported rather than overwritten.\n`);
436
+ } else if (!installed && wizardInstalled(root)) {
437
+ note(` No .sws/installed.json, so an update cannot tell your edits from an old`);
438
+ note(` version. Re-run the installer once to create it.\n`);
439
+ }
440
+ return 0; // never gates
441
+ }
442
+ if (blocking.length) return 1;
443
+ if (flags.strict && findings.some((f) => f.state === 'fail')) return 1;
444
+ return 0;
445
+ }
446
+
447
+ // --- a11y -------------------------------------------------------------------
448
+ // Separate command, not folded into `check`, for two reasons: `check` must stay
449
+ // fast and runnable without a browser, and CI wants axe as its own step so a
450
+ // browser download failure is legible instead of buried in a compliance report.
451
+ //
452
+ // Two measurements, one command and one browser launch: axe over every route,
453
+ // then the interactive-state audit. They belong together -- both need Chromium,
454
+ // both are accessibility, and a second command would be a second thing for CI
455
+ // and for people to forget. The state audit is what catches a hover or focus
456
+ // state that is only a colour change, which axe cannot see because it audits a
457
+ // static snapshot.
458
+ //
459
+ // Always exits 0. These are measurements, not gates: the resulting findings are
460
+ // scored by `check` like everything else.
461
+
462
+ async function a11y() {
463
+ const dist = findDist();
464
+ const html = dist ? findHtml(dist) : [];
465
+ console.log(` axe: ${html.length} route(s) from ${dist ? relative(root, dist) || '.' : 'no build output'}`);
466
+
467
+ const r = await runAxe({ root, dist, html });
468
+
469
+ if (r.status !== 'ok') {
470
+ console.log(`\n Did not complete: ${r.status}`);
471
+ console.log(` ${r.detail}`);
472
+ console.log(`\n Recorded in ${AXE_RESULTS_PATH}. This reports as \`unknown\`, never as a pass,`);
473
+ console.log(' so the criterion withholds its points rather than flattering the score.');
474
+ // Still attempt the state audit. It needs Playwright but NOT
475
+ // @axe-core/playwright, so the commonest reason axe bails -- that one
476
+ // package missing -- says nothing about whether states can be measured.
477
+ // Returning here would have turned one missing dependency into four
478
+ // unknowns instead of one.
479
+ await states();
480
+ return 0;
481
+ }
482
+
483
+ const v = r.totals.violations;
484
+ console.log(` axe ${r.versions.axe} on ${r.versions.browser}, tags: ${r.tags.join(', ')}`);
485
+ if (!v) {
486
+ console.log(`\n 0 violations across ${r.totals.routes} route(s).`);
487
+ console.log(' That is a floor, not a conformance claim: automation covers roughly 30%');
488
+ console.log(' of accessibility issues per ODA guidance. The manual checklist covers the rest.');
489
+ } else {
490
+ console.log(`\n ${v} violation(s):\n`);
491
+ for (const route of r.routes.filter((x) => x.counts?.violations)) {
492
+ console.log(` ${route.route}`);
493
+ for (const x of route.violations) {
494
+ console.log(` ${x.impact ?? 'unknown'} ${x.id}${x.nodeCount > 1 ? ` (${x.nodeCount} nodes)` : ''} ${x.help}`);
495
+ if (x.nodes[0]?.target) console.log(` ${x.nodes[0].target}`);
496
+ console.log(` ${x.helpUrl}`);
497
+ }
498
+ console.log('');
499
+ }
500
+ }
501
+ if (r.totals.incomplete) {
502
+ console.log(` ${r.totals.incomplete} incomplete result(s) need human review. axe could not decide;`);
503
+ console.log(' these are not failures and are not scored. See the results file.');
504
+ }
505
+ console.log(` Full detail: ${AXE_RESULTS_PATH}`);
506
+
507
+ await states();
508
+ return 0;
509
+ }
510
+
511
+ // --- interactive states -----------------------------------------------------
512
+ // Hover and focus, measured rather than inferred: real mouse, real Tab key,
513
+ // computed style diffed property by property. A change that is only a colour
514
+ // is a finding (SC 1.4.1 via G183); no change at all on focus is a finding
515
+ // (SC 2.4.7). Never gates, and reports `unknown` rather than `pass` when it
516
+ // could not measure.
517
+
518
+ async function states() {
519
+ const dist = findDist();
520
+ const html = dist ? findHtml(dist) : [];
521
+
522
+ console.log('');
523
+ console.log(` states: hover and focus on ${html.length} route(s)`);
524
+
525
+ const r = await runStates({ root, dist, html });
526
+
527
+ if (r.status !== 'ok') {
528
+ console.log(`\n Did not complete: ${r.status}`);
529
+ console.log(` ${r.detail}`);
530
+ console.log(`\n Recorded in ${STATE_RESULTS_PATH}. Reports as \`unknown\`, never as a pass.`);
531
+ return 0;
532
+ }
533
+
534
+ const t = r.totals;
535
+ console.log(` ${t.controls} distinct control shape(s), ${t.instances} instance(s)`);
536
+
537
+ const flagged = r.routes.flatMap((x) => (x.findings ?? []).map((f) => ({ ...f, route: x.route })));
538
+ if (!flagged.length) {
539
+ console.log('\n Every hover and focus state carries a cue that does not depend on colour.');
540
+ } else {
541
+ console.log(`\n ${flagged.length} control shape(s) to fix:\n`);
542
+ for (const f of flagged) {
543
+ const what = f.verdict === 'no-change' ? 'no visible focus state' : `${f.state}: colour only`;
544
+ console.log(` ${what} ${f.label ? `"${f.label}"` : f.target}${f.occurrences > 1 ? ` (${f.occurrences} instances)` : ''}`);
545
+ console.log(` ${f.route} ${f.target}`);
546
+ if (f.classes?.length) console.log(` classes: ${f.classes.join(' ')}`);
547
+ if (f.changed?.length) console.log(` changed: ${f.changed.join(', ')}`);
548
+ console.log(` fix: ${f.graphic
549
+ ? 'no text on this control, so an underline is not the fix -- add an outline, a border, or a shape change'
550
+ : 'add or remove an underline (`hover:underline`, `focus-visible:underline`, or `hocus:underline`)'}`);
551
+ }
552
+ console.log('');
553
+ console.log(' WCAG 2.1 SC 1.4.1 via technique G183: where colour identifies a control,');
554
+ console.log(' hover AND focus each need a cue that does not depend on colour vision.');
555
+ }
556
+
557
+ if (t.inconclusive) {
558
+ console.log(`\n ${t.inconclusive} control(s) could not be hovered by a real mouse: covered by another`);
559
+ console.log(' element, moving under the pointer, or not pointer-reachable at all, which is');
560
+ console.log(' normal for a visually hidden skip link. Not counted either way -- the');
561
+ console.log(` inventory in ${STATE_RESULTS_PATH} says which, and why.`);
562
+ }
563
+ console.log(`\n Full detail: ${STATE_RESULTS_PATH}`);
564
+ return 0;
565
+ }
566
+
567
+ // --- perf -------------------------------------------------------------------
568
+ // Budgets first-party uncompressed bytes and request counts, not Lighthouse
569
+ // scores. See standards/stack/performance-budget.yml for why. Always exits 0.
570
+
571
+ async function perf() {
572
+ const standards = findStandards();
573
+ const dist = findDist();
574
+ const html = dist ? findHtml(dist) : [];
575
+ console.log(` perf: ${html.length} route(s) from ${dist ? relative(root, dist) || '.' : 'no build output'}`);
576
+
577
+ const r = await runPerf({ root, dist, html, standards, manifest: loadManifest() });
578
+
579
+ if (r.status !== 'ok') {
580
+ console.log(`\n Did not complete: ${r.status}`);
581
+ console.log(` ${r.detail}`);
582
+ console.log(`\n Recorded in ${PERF_RESULTS_PATH}. Reports as \`unknown\`, never as a pass.`);
583
+ return 0;
584
+ }
585
+
586
+ const L = r.budget.limits;
587
+ console.log(` budget v${r.budget.version}, measuring ${r.budget.measures}`);
588
+ if (Object.keys(r.budget.overrides).length) {
589
+ console.log(` project override: ${JSON.stringify(r.budget.overrides)}`);
590
+ if (r.budget.overrideReason) console.log(` reason: ${r.budget.overrideReason.trim().split('\n')[0]}`);
591
+ }
592
+ console.log('');
593
+
594
+ for (const route of r.routes) {
595
+ const f = route.firstParty;
596
+ const flag = r.breaches.some((b) => b.route === route.route) ? '!' : ' ';
597
+ console.log(` ${flag} ${route.route} ${f.total_kb} KB / ${L.total_kb} KB, ${f.requests} req`);
598
+ const parts = Object.entries(f.by_type_kb).filter(([, v]) => v > 0)
599
+ .sort((a, b) => b[1] - a[1]).map(([k, v]) => `${k} ${v}`);
600
+ if (parts.length) console.log(` ${parts.join(' ')}`);
601
+ if (route.timings_ms_unscored) {
602
+ console.log(` unscored: DCL ${route.timings_ms_unscored.domContentLoaded}ms, load ${route.timings_ms_unscored.load}ms`);
603
+ }
604
+ }
605
+
606
+ if (r.breaches.length) {
607
+ console.log(`\n ${r.breaches.length} breach(es):`);
608
+ for (const b of r.breaches) {
609
+ console.log(` ${b.route} ${b.key.replace(/_kb$/, '')} ${b.actual} > ${b.limit}${b.overridden ? ' (overridden limit)' : ''}`);
610
+ }
611
+ console.log('\n Usual wins: fewer and correctly sized images, fewer islands, no');
612
+ console.log(' client-side framework for static content.');
613
+ } else {
614
+ console.log(`\n Within budget on all ${r.totals.routes} route(s).`);
615
+ }
616
+
617
+ // Third party is reported, never scored. It is also a privacy signal.
618
+ if (r.totals.third_party_origins) {
619
+ console.log(`\n ${r.totals.third_party_origins} third-party origin(s), ${r.totals.third_party_kb} KB, not counted against the budget:`);
620
+ for (const o of r.thirdPartyOrigins) console.log(` ${o}`);
621
+ console.log(' These are a privacy surface as well as a performance cost: MinPriv treats');
622
+ console.log(' a new third-party service as disclosable, and it can trigger a DRA.');
623
+ console.log(' See standards/policy/privacy.md.');
624
+ }
625
+ console.log(`\n Full measurement: ${PERF_RESULTS_PATH}`);
626
+ return 0;
627
+ }
628
+
629
+ // --- preflight --------------------------------------------------------------
630
+
631
+ function runPreflight() {
632
+ const standards = findStandards();
633
+ if (!standards) {
634
+ console.error('Could not find a standards/ directory. Pass --standards <dir>.');
635
+ return 2;
636
+ }
637
+
638
+ const { results, error, packageManager, provider, notRequired } =
639
+ preflight({ standardsDir: standards, root, manifest: loadManifest() });
640
+
641
+ if (error) { console.error(error); return 2; }
642
+
643
+ const { blocking, unknown, optional, ready } = summarise(results);
644
+
645
+ if (flags.format === 'json') {
646
+ console.log(JSON.stringify({
647
+ ready, packageManager, provider,
648
+ results, blocking: blocking.map((b) => b.id), notRequired,
649
+ }, null, 2));
650
+ return ready || !flags.strict ? 0 : 1;
651
+ }
652
+
653
+ const MARK = {
654
+ pass: 'ok', missing: 'MISSING', too_old: 'TOO OLD',
655
+ unknown: 'unknown', not_applicable: '-', skip: '-',
656
+ };
657
+
658
+ console.log('\nSystem preflight\n');
659
+ for (const r of results) {
660
+ const tag = MARK[r.state] ?? r.state;
661
+ console.log(` ${tag.padEnd(9)} ${String(r.name || r.id).padEnd(34)} ${r.detail || ''}`);
662
+ }
663
+
664
+ // The actionable part. Say WHAT to install and WHY it matters, never how.
665
+ if (blocking.length) {
666
+ console.log('\nInstall these, however you normally would on this machine:\n');
667
+ for (const b of blocking) {
668
+ console.log(` - ${b.name || b.id}`);
669
+ if (b.why) console.log(` why: ${b.why.trim().split('\n').join(' ')}`);
670
+ if (b.blocks) console.log(` blocks: ${b.blocks.trim().split('\n').join(' ')}`);
671
+ }
672
+ console.log('\n Then run `sws preflight` again. Verifying the install is the point:');
673
+ console.log(' an install that reported success and did not put the binary on PATH is');
674
+ console.log(' the common failure, and it is invisible until something else breaks.');
675
+ }
676
+
677
+ if (unknown.length) {
678
+ console.log('\nCould not determine (present but the probe failed). Not a pass:');
679
+ for (const u of unknown) console.log(` - ${u.name || u.id}: ${u.detail}`);
680
+ }
681
+
682
+ if (optional.length) {
683
+ console.log('\nOptional, missing, nothing is blocked:');
684
+ for (const o of optional) console.log(` - ${o.name || o.id}`);
685
+ }
686
+
687
+ if (ready) console.log('\nReady. Everything required for this project is present.\n');
688
+ else console.log('');
689
+
690
+ return ready || !flags.strict ? 0 : 1;
691
+ }
692
+
693
+ // --- dispatch ---------------------------------------------------------------
694
+
695
+ switch (cmd) {
696
+ case 'preflight':
697
+ process.exit(runPreflight());
698
+ break;
699
+ case 'doctor':
700
+ case 'check':
701
+ process.exit(await run());
702
+ break;
703
+ case 'a11y':
704
+ process.exit(await a11y());
705
+ break;
706
+ case 'perf':
707
+ process.exit(await perf());
708
+ break;
709
+ case 'prior-art':
710
+ console.log('prior-art scan is not implemented yet. It will index Stanford');
711
+ console.log('projects on this machine (metadata only) to .sws/prior-art.local.yml,');
712
+ console.log('which is gitignored and never transmitted.');
713
+ process.exit(0);
714
+ break;
715
+ case 'version':
716
+ console.log(JSON.parse(readFileSync(join(HERE, '..', 'package.json'), 'utf8')).version);
717
+ process.exit(0);
718
+ break;
719
+ default:
720
+ console.log(USAGE);
721
+ process.exit(cmd ? 2 : 0);
722
+ }