rachnasutra 0.4.0 → 0.5.1

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 (39) hide show
  1. package/CHANGELOG.md +22 -2
  2. package/CITATION.cff +2 -2
  3. package/Dockerfile +9 -0
  4. package/README.gu.md +35 -0
  5. package/README.md +14 -12
  6. package/ROADMAP.md +8 -1
  7. package/case-studies/clean-blog/fixes.diff +152 -152
  8. package/dist/audit.js +24 -6
  9. package/dist/browser.js +147 -0
  10. package/dist/cli.js +117 -17
  11. package/dist/report.js +23 -0
  12. package/dist/rules.js +176 -0
  13. package/dist/tw-color.js +36 -0
  14. package/docs/cli-reference.md +1 -1
  15. package/docs/compatibility.md +1 -1
  16. package/docs/status.md +13 -6
  17. package/documents/rachnasutra/00-overview.md +4 -4
  18. package/documents/rachnasutra/02-functional-specification.md +6 -6
  19. package/documents/rachnasutra/03-architecture.md +1 -1
  20. package/documents/rachnasutra/04-technical-reference.md +2 -2
  21. package/documents/rachnasutra/05-user-guide.md +1 -1
  22. package/documents/rachnasutra/06-audit-rules-reference.md +46 -1
  23. package/documents/rachnasutra/10-testing-and-evidence.md +22 -21
  24. package/documents/rachnasutra/11-deployment-and-ci.md +26 -6
  25. package/documents/rachnasutra/12-roadmap-and-status.md +13 -11
  26. package/documents/rachnasutra/13-maintainer-handbook.md +1 -1
  27. package/documents/rachnasutra/15-rule-examples.md +456 -0
  28. package/documents/rachnasutra/16-validation-and-benchmarks.md +3 -3
  29. package/examples/prime-session-example.md +2 -2
  30. package/fixtures/rule-cases.mjs +85 -70
  31. package/llms.txt +4 -3
  32. package/package.json +7 -2
  33. package/samples/broken-ui/latest.html +42 -30
  34. package/samples/broken-ui/latest.json +39 -14
  35. package/samples/broken-ui/latest.md +24 -13
  36. package/samples/broken-ui/latest.sarif +48 -10
  37. package/samples/good-ui/latest.html +1 -1
  38. package/samples/good-ui/latest.json +3 -3
  39. package/samples/good-ui/latest.md +2 -2
@@ -0,0 +1,147 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { createServer } from 'node:http';
3
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ export class BrowserMissing extends Error {
6
+ constructor(message) {
7
+ super(message);
8
+ this.name = 'BrowserMissing';
9
+ }
10
+ }
11
+ const INSTALL = 'npm install --save-dev playwright @axe-core/playwright lighthouse && npx playwright install chromium';
12
+ const dyn = new Function('s', 'return import(s)');
13
+ async function loadPlaywright() {
14
+ try {
15
+ return await dyn('playwright');
16
+ }
17
+ catch {
18
+ throw new BrowserMissing(`Playwright is not installed. No browser was launched. Install it with: ${INSTALL}`);
19
+ }
20
+ }
21
+ async function launchBrowser(port) {
22
+ const { chromium } = await loadPlaywright();
23
+ const args = [`--remote-debugging-port=${port}`];
24
+ try {
25
+ return { browser: await chromium.launch({ channel: 'msedge', headless: true, args }), channel: 'msedge' };
26
+ }
27
+ catch {
28
+ try {
29
+ return { browser: await chromium.launch({ headless: true, args }), channel: 'chromium' };
30
+ }
31
+ catch (e) {
32
+ throw new BrowserMissing(`Playwright is installed but no browser binary launched (${e.message}). Run: npx playwright install chromium`);
33
+ }
34
+ }
35
+ }
36
+ function serve(dir) {
37
+ const root = path.resolve(dir);
38
+ const server = createServer(async (req, res) => {
39
+ const pathname = decodeURIComponent(new URL(req.url ?? '/', 'http://127.0.0.1').pathname);
40
+ const rel = pathname === '/' ? 'index.html' : pathname.replace(/^\/+/, '');
41
+ const abs = path.resolve(root, rel);
42
+ if (abs !== root && !abs.startsWith(root + path.sep)) {
43
+ res.statusCode = 403;
44
+ res.end();
45
+ return;
46
+ }
47
+ try {
48
+ const buf = await readFile(abs);
49
+ res.end(buf);
50
+ }
51
+ catch {
52
+ res.statusCode = 404;
53
+ res.end();
54
+ }
55
+ });
56
+ return new Promise((resolve) => {
57
+ server.listen(0, '127.0.0.1', () => {
58
+ const addr = server.address();
59
+ const port = typeof addr === 'object' && addr ? addr.port : 0;
60
+ resolve({ url: `http://127.0.0.1:${port}/`, close: () => new Promise((done) => server.close(() => done())) });
61
+ });
62
+ });
63
+ }
64
+ function finding(n, rule, title, severity, file, excerpt) {
65
+ const fingerprint = createHash('sha256').update(`${rule}|${file}|${excerpt}`).digest('hex').slice(0, 12);
66
+ return {
67
+ id: `RS-${String(n).padStart(4, '0')}`,
68
+ rule,
69
+ category: 'accessibility',
70
+ title,
71
+ severity,
72
+ confidence: 'high',
73
+ status: 'confirmed',
74
+ platform: 'web',
75
+ file,
76
+ line: 1,
77
+ evidence: [{ path: file, line: 1, excerpt: excerpt.slice(0, 240) }],
78
+ user_impact: 'A rendered-page check reported this. Static source rules cannot see it.',
79
+ recommended_fix: 'Open the page in a browser and fix the cited element. Re-run with --mode browser.',
80
+ verification: 'Re-run `rachnasutra audit --mode browser`.',
81
+ limitations: 'Line number is the page, not the source line. axe-core owns the rule id.',
82
+ fingerprint,
83
+ };
84
+ }
85
+ const AXE_SEV = { critical: 'critical', serious: 'high', moderate: 'medium', minor: 'low' };
86
+ /** Launch a real browser, save a screenshot, run axe-core, and try Lighthouse. */
87
+ export async function runBrowserAudit(root, outDir, startId) {
88
+ const html = path.join(root, 'index.html');
89
+ try {
90
+ await readFile(html);
91
+ }
92
+ catch {
93
+ throw new BrowserMissing(`No index.html in ${root}. Nothing was rendered.`);
94
+ }
95
+ const debugPort = 9400 + Math.floor(Math.random() * 100);
96
+ const { browser, channel } = await launchBrowser(debugPort);
97
+ const site = await serve(root);
98
+ await mkdir(outDir, { recursive: true });
99
+ const screenshot = path.join(outDir, 'screenshot.png');
100
+ const findings = [];
101
+ let lighthouse = 'Lighthouse did not run.';
102
+ try {
103
+ const context = await browser.newContext();
104
+ const page = await context.newPage();
105
+ await page.goto(site.url, { waitUntil: 'load' });
106
+ await page.screenshot({ path: screenshot, fullPage: true });
107
+ try {
108
+ const axeMod = await dyn('@axe-core/playwright');
109
+ const result = await new axeMod.AxeBuilder({ page }).analyze();
110
+ let n = startId;
111
+ for (const v of result.violations) {
112
+ const excerpt = v.nodes[0]?.html || v.help;
113
+ findings.push(finding(n++, `axe/${v.id}`, `${v.help} (${v.nodes.length} node${v.nodes.length === 1 ? '' : 's'})`, AXE_SEV[v.impact ?? ''] ?? 'medium', 'index.html', excerpt));
114
+ }
115
+ }
116
+ catch (e) {
117
+ findings.push(finding(startId, 'axe/missing', `axe did not finish: ${e.message}`, 'info', 'index.html', 'axe did not finish'));
118
+ }
119
+ try {
120
+ const lhMod = await dyn('lighthouse');
121
+ const lh = await Promise.race([
122
+ lhMod.default(site.url, { logLevel: 'error', output: 'json', port: debugPort, onlyCategories: ['performance', 'accessibility'] }),
123
+ new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), 60_000)),
124
+ ]);
125
+ const perf = lh.lhr?.categories?.performance?.score;
126
+ const a11y = lh.lhr?.categories?.accessibility?.score;
127
+ lighthouse = `Lighthouse performance ${perf == null ? 'n/a' : Math.round(perf * 100)}, accessibility ${a11y == null ? 'n/a' : Math.round(a11y * 100)}. Lab only. Not a field measurement.`;
128
+ }
129
+ catch {
130
+ lighthouse = 'Lighthouse package is not installed or did not finish. Screenshot and axe still ran.';
131
+ }
132
+ await page.close();
133
+ await context.close();
134
+ }
135
+ finally {
136
+ await browser.close();
137
+ await site.close();
138
+ }
139
+ return { channel, screenshot, findings, lighthouse };
140
+ }
141
+ export async function saveScreenshot(root, dest) {
142
+ const run = await runBrowserAudit(root, path.dirname(dest), 1);
143
+ await mkdir(path.dirname(dest), { recursive: true });
144
+ const buf = await readFile(run.screenshot);
145
+ await writeFile(dest, buf);
146
+ return { channel: run.channel, file: dest };
147
+ }
package/dist/cli.js CHANGED
@@ -2,9 +2,10 @@
2
2
  import { promises as fs } from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { HOSTS, detectHosts, doctor, install, packageRoot, planInstall, uninstall } from './adapters.js';
5
+ import { BrowserMissing, runBrowserAudit, saveScreenshot } from './browser.js';
5
6
  import { CONFIG_FILE, SEVERITY_ORDER, loadConfig, runAudit, validateConfig } from './audit.js';
6
7
  import { exists } from './fsutil.js';
7
- import { renderFixPlanHtml, renderFixPlanMarkdown, renderHtml, renderJson, renderMarkdown, renderSarif, renderTokensHtml, renderTokensMarkdown, renderVerifyHtml, renderVerifyMarkdown } from './report.js';
8
+ import { renderFixPlanHtml, renderFixPlanMarkdown, renderHistoryHtml, renderHistoryMarkdown, renderHtml, renderJson, renderMarkdown, renderSarif, renderTokensHtml, renderTokensMarkdown, renderVerifyHtml, renderVerifyMarkdown } from './report.js';
8
9
  import { compareToReport, verifyPackage } from './verify.js';
9
10
  const EXIT = { ok: 0, findings: 1, usage: 2, notAvailable: 3, verifyFailed: 4, error: 5 };
10
11
  const NOT_AVAILABLE = ['visual', 'browser'];
@@ -29,11 +30,14 @@ Deterministic commands (no AI, no network, read-only unless noted):
29
30
  verify --report <file> [path] re-audit; writes verify.md and verify.html next to the JSON report
30
31
  export --format sarif [path] print SARIF 2.1.0
31
32
  ci [path] audit with CI exit codes (--fail-on confirmed-critical|<severity>)
33
+ history [dir] compare saved JSON reports; writes history.md and history.html
32
34
  config validate [path] validate ${CONFIG_FILE}
33
35
  install | uninstall aliases of skills install | uninstall
34
36
 
35
- Not available in this version (exit 3, nothing is faked):
36
- visual baseline|compare, audit --mode browser
37
+ Browser mode (real browser, exit 3 only when Playwright is not installed):
38
+ audit --mode browser [path] screenshot + axe-core + Lighthouse, then the static audit
39
+ visual baseline [path] save .rachnasutra/visual/baseline.png
40
+ visual compare [path] screenshot again and compare bytes to the baseline
37
41
 
38
42
  Options:
39
43
  --json --no-report --dry-run --force --host <id> --target <dir> --out <dir> --format <list>
@@ -79,7 +83,8 @@ function textSummary(r) {
79
83
  ];
80
84
  if (r.findings.length > 40)
81
85
  lines.push(` ... ${r.findings.length - 40} more (use --format or --json)`);
82
- lines.push('Not evaluated: browser runtime, visual review, screen-reader/keyboard testing, Core Web Vitals.', 'Static review only; this is not a WCAG conformance statement.');
86
+ const notRun = r.coverage.filter((c) => c.state === 'not-run').map((c) => c.category);
87
+ lines.push(notRun.length ? `Not evaluated: ${notRun.join(', ')}.` : 'Every listed coverage category ran.', 'This is not a WCAG conformance statement.');
83
88
  return lines.join('\n');
84
89
  }
85
90
  async function emitAudit(res, args) {
@@ -143,9 +148,33 @@ async function main() {
143
148
  const sub = ['skills', 'design-system', 'config', 'visual'].includes(cmd) ? args.pos.shift() : undefined;
144
149
  const target = path.resolve(args.pos[0] ?? '.');
145
150
  if (cmd === 'visual' || (cmd === 'audit' && args.flags.mode === 'browser')) {
146
- const msg = 'Browser and visual audits are not available in this version (planned: see docs/status.md). No browser was launched and no screenshot was taken. Use `audit --mode static`.';
147
- write(json ? JSON.stringify({ available: false, message: msg }) : msg);
148
- return EXIT.notAvailable;
151
+ try {
152
+ if (cmd === 'visual') {
153
+ const destDir = path.join(target, '.rachnasutra', 'visual');
154
+ const dest = path.join(destDir, sub === 'compare' ? 'current.png' : 'baseline.png');
155
+ const shot = await saveScreenshot(target, dest);
156
+ if (sub === 'compare') {
157
+ const baseline = path.join(destDir, 'baseline.png');
158
+ const [a, b] = await Promise.all([fs.readFile(baseline).catch(() => null), fs.readFile(dest)]);
159
+ if (!a) {
160
+ process.stderr.write('No baseline. Run: rachnasutra visual baseline\n');
161
+ return EXIT.usage;
162
+ }
163
+ const same = a.equals(b);
164
+ write(`${shot.channel} screenshot ${dest}\n${same ? 'Matches the baseline byte for byte.' : 'Differs from the baseline. Open both PNG files.'}`);
165
+ return same ? EXIT.ok : EXIT.findings;
166
+ }
167
+ write(`${shot.channel} screenshot written: ${shot.file}`);
168
+ return EXIT.ok;
169
+ }
170
+ }
171
+ catch (e) {
172
+ if (e instanceof BrowserMissing) {
173
+ write(json ? JSON.stringify({ available: false, message: e.message }) : e.message);
174
+ return EXIT.notAvailable;
175
+ }
176
+ throw e;
177
+ }
149
178
  }
150
179
  switch (cmd) {
151
180
  case 'hosts':
@@ -167,12 +196,15 @@ async function main() {
167
196
  }
168
197
  case 'doctor': {
169
198
  const res = await doctor(target);
170
- res.push({ id: 'capability:static-audit', ok: true, message: 'available' });
171
- res.push({ id: 'capability:browser-audit', ok: true, message: 'not-available (planned); not counted as failure' });
172
- res.push({ id: 'capability:visual-review', ok: true, message: 'not-available (planned); not counted as failure' });
173
- res.push({ id: 'model-requirement', ok: true, message: 'none for the CLI; skills use your IDE model' });
174
- write(json ? JSON.stringify(res, null, 2) : res.map((r) => `${r.ok ? 'OK ' : 'FAIL'} ${r.id}: ${r.message}${r.fix ? `\n fix: ${r.fix}` : ''}`).join('\n'));
175
- return res.every((r) => r.ok) ? EXIT.ok : EXIT.findings;
199
+ const rows = [
200
+ ...res.map((r) => ({ ...r, level: 'check' })),
201
+ { id: 'capability:static-audit', ok: true, level: 'check', message: 'available' },
202
+ { id: 'capability:browser-audit', ok: true, level: 'note', message: 'runs when Playwright is installed (`audit --mode browser`). Otherwise no browser is launched. Not a pass by itself.' },
203
+ { id: 'capability:visual-review', ok: true, level: 'note', message: 'screenshot baseline and compare run when Playwright is installed. Otherwise no screenshot is taken. Not a pass by itself.' },
204
+ { id: 'model-requirement', ok: true, level: 'note', message: 'none for the CLI. Skills use the IDE model. No host has been smoke-tested.' },
205
+ ];
206
+ write(json ? JSON.stringify(rows, null, 2) : rows.map((r) => `${r.level === 'note' ? 'NOTE' : r.ok ? 'OK ' : 'FAIL'} ${r.id}: ${r.message}${r.fix ? `\n fix: ${r.fix}` : ''}`).join('\n'));
207
+ return rows.every((r) => r.ok) ? EXIT.ok : EXIT.findings;
176
208
  }
177
209
  case 'skills':
178
210
  case 'install':
@@ -214,6 +246,40 @@ async function main() {
214
246
  case 'accessibility':
215
247
  case 'ci': {
216
248
  const res = await runAudit(target, cmd === 'accessibility' ? { categories: ['accessibility'] } : {});
249
+ if (cmd === 'audit' && args.flags.mode === 'browser') {
250
+ try {
251
+ const out = path.resolve(String(args.flags.out ?? DEFAULT_REPORT_DIR));
252
+ const browser = await runBrowserAudit(target, out, res.findings.length + 1);
253
+ res.findings.push(...browser.findings);
254
+ res.limitations.push(`Browser ${browser.channel}. Screenshot: ${browser.screenshot}. ${browser.lighthouse}`);
255
+ const runtime = res.coverage.find((c) => c.category === 'browser runtime');
256
+ if (runtime) {
257
+ runtime.state = 'partial';
258
+ runtime.checks = browser.findings.length;
259
+ runtime.detail = `axe-core ran in ${browser.channel}. Screenshot saved. This is not a full manual test.`;
260
+ }
261
+ const visual = res.coverage.find((c) => c.category === 'visual review');
262
+ if (visual) {
263
+ visual.state = 'partial';
264
+ visual.checks = 1;
265
+ visual.detail = `Screenshot saved at ${browser.screenshot}. Compare is byte-for-byte, not a perceptual diff.`;
266
+ }
267
+ const cwv = res.coverage.find((c) => c.category === 'Core Web Vitals (lab and field)');
268
+ if (cwv && browser.lighthouse.startsWith('Lighthouse')) {
269
+ cwv.state = 'partial';
270
+ cwv.checks = 1;
271
+ cwv.detail = `${browser.lighthouse} Field data was not collected.`;
272
+ }
273
+ write(`Browser ${browser.channel}. Screenshot: ${browser.screenshot}\n${browser.lighthouse}`);
274
+ }
275
+ catch (e) {
276
+ if (e instanceof BrowserMissing) {
277
+ write(json ? JSON.stringify({ available: false, message: e.message }) : e.message);
278
+ return EXIT.notAvailable;
279
+ }
280
+ throw e;
281
+ }
282
+ }
217
283
  if (cmd === 'ci') {
218
284
  if (!args.flags.format)
219
285
  args.flags.json = true;
@@ -302,6 +368,42 @@ async function main() {
302
368
  write(json ? JSON.stringify(checks, null, 2) : checks.map((c) => `${c.ok ? 'PASS' : 'FAIL'} ${c.id}: ${c.message}`).join('\n'));
303
369
  return checks.every((c) => c.ok) ? EXIT.ok : EXIT.verifyFailed;
304
370
  }
371
+ case 'history': {
372
+ const dir = target;
373
+ let names = [];
374
+ try {
375
+ names = (await fs.readdir(dir)).filter((n) => n.endsWith('.json')).sort();
376
+ }
377
+ catch {
378
+ process.stderr.write(`No directory ${dir}\n`);
379
+ return EXIT.usage;
380
+ }
381
+ const rows = [];
382
+ for (const name of names) {
383
+ try {
384
+ const data = JSON.parse(await fs.readFile(path.join(dir, name), 'utf8'));
385
+ if (!Array.isArray(data.findings))
386
+ continue;
387
+ rows.push({
388
+ file: name,
389
+ generatedAt: data.generatedAt ?? '',
390
+ total: data.findings.length,
391
+ high: data.findings.filter((f) => f.severity === 'high' || f.severity === 'critical').length,
392
+ });
393
+ }
394
+ catch {
395
+ // skip JSON that is not an audit report
396
+ }
397
+ }
398
+ rows.sort((a, b) => a.generatedAt.localeCompare(b.generatedAt) || a.file.localeCompare(b.file));
399
+ if (!rows.length) {
400
+ process.stderr.write(`No audit JSON in ${dir}\n`);
401
+ return EXIT.usage;
402
+ }
403
+ const out = args.flags.out ? path.resolve(String(args.flags.out)) : dir;
404
+ await writeReadable(out, 'history', renderHistoryMarkdown(rows), renderHistoryHtml(rows), dry);
405
+ return EXIT.ok;
406
+ }
305
407
  case 'config': {
306
408
  if (sub !== 'validate') {
307
409
  process.stderr.write('Usage: rachnasutra config validate [path]\n');
@@ -329,11 +431,9 @@ async function main() {
329
431
  return EXIT.usage;
330
432
  }
331
433
  }
332
- main().then((code) => {
333
- process.exitCode = code;
334
- }, (e) => {
434
+ main().then((code) => process.exit(code), (e) => {
335
435
  process.stderr.write(`rachnasutra: ${e.message}\n`);
336
436
  if (process.argv.includes('--verbose'))
337
437
  process.stderr.write(`${e.stack}\n`);
338
- process.exitCode = EXIT.error;
438
+ process.exit(EXIT.error);
339
439
  });
package/dist/report.js CHANGED
@@ -317,3 +317,26 @@ export function renderSarif(r) {
317
317
  }],
318
318
  };
319
319
  }
320
+ /** Counts only. This is not a rendered visual diff. */
321
+ export function renderHistoryMarkdown(rows) {
322
+ const lines = [
323
+ '# Audit history',
324
+ '',
325
+ 'Each row is one saved JSON report. Counts are findings in that file. This is not a browser or screenshot comparison.',
326
+ '',
327
+ '| Report | Generated | Findings | High or critical |',
328
+ '|---|---|---|---|',
329
+ ...rows.map((r) => `| ${r.file} | ${r.generatedAt} | ${r.total} | ${r.high} |`),
330
+ '',
331
+ ];
332
+ if (rows.length >= 2) {
333
+ const a = rows[rows.length - 2];
334
+ const b = rows[rows.length - 1];
335
+ lines.push(`Latest change: ${a.file} had ${a.total} findings, ${b.file} has ${b.total}.`, '');
336
+ }
337
+ return lines.join('\n');
338
+ }
339
+ export function renderHistoryHtml(rows) {
340
+ const body = rows.map((r) => `<tr><td>${escHtml(r.file)}</td><td>${escHtml(r.generatedAt)}</td><td>${r.total}</td><td>${r.high}</td></tr>`).join('');
341
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Audit history</title></head><body><main><h1>Audit history</h1><p>Saved JSON reports only. No browser and no screenshot.</p><table><thead><tr><th>Report</th><th>Generated</th><th>Findings</th><th>High or critical</th></tr></thead><tbody>${body}</tbody></table></main></body></html>\n`;
342
+ }
package/dist/rules.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { contrastRatio, parseColor } from './color.js';
2
+ import { TW_COLOR } from './tw-color.js';
2
3
  import { excerpt } from './redact.js';
3
4
  export const MARKUP_EXT = new Set(['.html', '.htm', '.jsx', '.tsx', '.vue', '.svelte', '.astro']);
4
5
  export const STYLE_EXT = new Set(['.css', '.scss', '.less']);
@@ -66,6 +67,48 @@ function mk(doc, index, base) {
66
67
  const line = lineAt(doc.text, index);
67
68
  return { ...base, file: doc.file.rel, line, evidence: [{ path: doc.file.rel, line, excerpt: excerpt(lineText(doc.text, line)) }] };
68
69
  }
70
+ /** Tailwind arbitrary hex utilities and JSX style objects. Named palettes and the cascade are not resolved. */
71
+ function reportUtilityContrast(d, t, push) {
72
+ const judge = (index, fgRaw, bgRaw, where) => {
73
+ const f = parseColor(fgRaw);
74
+ const g = parseColor(bgRaw);
75
+ if (!f || !g)
76
+ return;
77
+ const ratio = contrastRatio(f, g);
78
+ if (ratio >= 4.5)
79
+ return;
80
+ push(mk(d, index, {
81
+ rule: 'RS-A11Y-013', category: 'accessibility',
82
+ title: `Text contrast ${ratio.toFixed(2)}:1 is below 4.5:1 (${fgRaw} on ${bgRaw})`,
83
+ severity: ratio < 3 ? 'high' : 'medium', confidence: 'medium',
84
+ criterion: 'WCAG 2.2: 1.4.3 Contrast (Minimum)',
85
+ user_impact: 'Low-vision users and anyone in bright light may be unable to read this text.',
86
+ recommended_fix: 'Darken the text or lighten the background until the ratio is at least 4.5:1.',
87
+ verification: 'Re-run the audit and check the rendered pair.',
88
+ limitations: where,
89
+ }));
90
+ };
91
+ for (const m of t.matchAll(/\b(?:class|className)\s*=\s*(?:"([^"]*)"|'([^']*)'|\{`([^`]*)`\})/g)) {
92
+ const cls = m[1] ?? m[2] ?? m[3] ?? '';
93
+ const fgHex = /(?:^|\s)text-\[(#[0-9a-fA-F]{3,6})\]/.exec(cls);
94
+ const bgHex = /(?:^|\s)bg-\[(#[0-9a-fA-F]{3,6})\]/.exec(cls);
95
+ const fgName = /(?:^|\s)text-([a-z]+(?:-\d{2,3})?)(?=\s|$)/.exec(cls);
96
+ const bgName = /(?:^|\s)bg-([a-z]+(?:-\d{2,3})?)(?=\s|$)/.exec(cls);
97
+ const fg = fgHex?.[1] ?? (fgName && !fgName[1].includes('/') ? TW_COLOR[fgName[1]] : undefined);
98
+ const bg = bgHex?.[1] ?? (bgName && !bgName[1].includes('/') ? TW_COLOR[bgName[1]] : undefined);
99
+ if (fg && bg)
100
+ judge(m.index, fg, bg, 'Tailwind utilities on one class string. Opacity modifiers, CSS variables and the cascade are not resolved.');
101
+ }
102
+ for (const m of t.matchAll(/\bstyle=\{\{([\s\S]*?)\}\}/g)) {
103
+ if (/\.\.\./.test(m[1]))
104
+ continue;
105
+ const fg = /(?:^|[,{])\s*color\s*:\s*['"]([^'"]+)['"]/.exec(m[1]);
106
+ const bg = /(?:^|[,{])\s*background(?:Color)?\s*:\s*['"]([^'"]+)['"]/.exec(m[1]);
107
+ if (fg && bg && !/textShadow|opacity|gradient/i.test(m[1])) {
108
+ judge(m.index, fg[1], bg[1], 'JSX style object with two literal colours. Theme variables and spreads are not resolved.');
109
+ }
110
+ }
111
+ }
69
112
  /** Run all deterministic rules. Output order is stable: caller sorts. */
70
113
  export function runRules(ctx) {
71
114
  const hits = [];
@@ -116,6 +159,112 @@ export function runRules(ctx) {
116
159
  }));
117
160
  }
118
161
  }
162
+ for (const m of t.matchAll(tagRe('div|span|svg|i|figure'))) {
163
+ if (!/\brole\s*=\s*["']img["']/i.test(m[2]) || hasSpread(m[2]) || isHidden(m[2]))
164
+ continue;
165
+ const named = nonEmptyAttr(m[2], 'aria-label') || nonEmptyAttr(m[2], 'aria-labelledby') || nonEmptyAttr(m[2], 'title') || nonEmptyAttr(m[2], 'alt');
166
+ const after = t.slice(m.index, m.index + 600);
167
+ const close = after.search(new RegExp(`</${m[1]}>`, 'i'));
168
+ const chunk = close > 0 ? after.slice(0, close) : after.slice(0, 200);
169
+ const inner = contentName(chunk);
170
+ if (!named && inner !== 'named' && inner !== 'unknown') {
171
+ push(mk(d, m.index, {
172
+ rule: 'RS-A11Y-001', category: 'accessibility', title: 'Element with role="img" has no accessible name', severity: 'high', confidence: 'high',
173
+ criterion: 'WCAG 2.2: 1.1.1 Non-text Content',
174
+ user_impact: 'A graphic exposed as an image is announced with no description.',
175
+ recommended_fix: 'Add aria-label, or aria-hidden="true" when the graphic is decorative.',
176
+ verification: 'Re-run the audit and check the accessibility tree.',
177
+ limitations: 'A name computed from a distant aria-labelledby target is not resolved.',
178
+ }));
179
+ }
180
+ }
181
+ const ids = [...t.matchAll(/\bid\s*=\s*["']([^"']+)["']/gi)].filter((m) => !insideCode(t, m.index) && !TEMPLATED.test(m[1]));
182
+ const seenIds = new Map();
183
+ for (const m of ids) {
184
+ const id = m[1];
185
+ const prev = seenIds.get(id);
186
+ if (prev !== undefined) {
187
+ push(mk(d, m.index, {
188
+ rule: 'RS-A11Y-016', category: 'accessibility', title: `Duplicate id "${id}"`, severity: 'high', confidence: 'high',
189
+ criterion: 'WCAG 2.2: 4.1.1 Parsing (obsolete) and 1.3.1, 4.1.2',
190
+ user_impact: 'Labels, skip links and aria-labelledby can point at the wrong element.',
191
+ recommended_fix: 'Give every id in the file a unique value.',
192
+ verification: 'Re-run the audit. In the browser, document.querySelectorAll("[id]") should not repeat a value in this file.',
193
+ limitations: 'The same id in two files can still collide after a template include. Only this file is checked.',
194
+ }));
195
+ }
196
+ else
197
+ seenIds.set(id, m.index);
198
+ }
199
+ for (const m of t.matchAll(tagRe('iframe'))) {
200
+ if (hasSpread(m[2]) || isHidden(m[2]))
201
+ continue;
202
+ if (!nonEmptyAttr(m[2], 'title') && !nonEmptyAttr(m[2], 'aria-label') && !nonEmptyAttr(m[2], 'aria-labelledby')) {
203
+ push(mk(d, m.index, {
204
+ rule: 'RS-A11Y-017', category: 'accessibility', title: 'Frame has no title', severity: 'high', confidence: 'high',
205
+ criterion: 'WCAG 2.2: 2.4.1 Bypass Blocks, 4.1.2 Name, Role, Value',
206
+ user_impact: 'Screen-reader users hear an unnamed frame and cannot tell whether to enter it.',
207
+ recommended_fix: 'Add a title that says what the frame contains, for example title="Payment form".',
208
+ verification: 'Re-run the audit and listen to the frame in a screen reader.',
209
+ limitations: 'A title set by script after load is not visible here.',
210
+ }));
211
+ }
212
+ }
213
+ if (d.isHtmlDoc && /<nav\b/i.test(t) && !insideCode(t, t.search(/<nav\b/i)) && !/href\s*=\s*["']#[^"']+["']/.test(t)) {
214
+ push(mk(d, Math.max(0, t.search(/<nav\b/i)), {
215
+ rule: 'RS-A11Y-018', category: 'accessibility', title: 'Navigation with no skip link', severity: 'medium', confidence: 'medium',
216
+ criterion: 'WCAG 2.2: 2.4.1 Bypass Blocks',
217
+ user_impact: 'Keyboard users must tab through the whole navigation on every page.',
218
+ recommended_fix: 'Add a skip link as the first focusable control, for example <a href="#main">Skip to content</a>, and a matching id on <main>.',
219
+ verification: 'Tab once from the top of the page. The skip link should appear and move focus to the main content.',
220
+ limitations: 'A skip link in a shared layout file is not visible in this file. Any in-page href counts as a possible skip target.',
221
+ }));
222
+ }
223
+ for (const m of t.matchAll(tagRe('input'))) {
224
+ if (hasSpread(m[2]) || isHidden(m[2]))
225
+ continue;
226
+ const type = (attrVal(m[2], 'type') ?? 'text').toLowerCase();
227
+ if (!['email', 'tel'].includes(type))
228
+ continue;
229
+ if (hasAttr(m[2], 'autocomplete'))
230
+ continue;
231
+ push(mk(d, m.index, {
232
+ rule: 'RS-A11Y-019', category: 'accessibility', title: `${type} field has no autocomplete attribute`, severity: 'medium', confidence: 'medium',
233
+ criterion: 'WCAG 2.2: 1.3.5 Identify Input Purpose',
234
+ user_impact: 'Browsers and password managers cannot fill the field, and users retype personal data.',
235
+ recommended_fix: type === 'email' ? 'Add autocomplete="email".' : 'Add autocomplete="tel".',
236
+ verification: 'Re-run the audit, then use the browser autofill menu on the field.',
237
+ limitations: 'Only type=email and type=tel are checked. Other personal fields need a human look.',
238
+ }));
239
+ }
240
+ for (const m of t.matchAll(/<h([1-6])\b([^>]*)>([\s\S]*?)<\/h\1>/gi)) {
241
+ if (insideCode(t, m.index) || hasSpread(m[2]))
242
+ continue;
243
+ const name = contentName(m[3]);
244
+ if (name === 'empty' || name === 'no-text') {
245
+ push(mk(d, m.index, {
246
+ rule: 'RS-A11Y-020', category: 'accessibility', title: `Heading h${m[1]} has no text`, severity: 'medium', confidence: 'medium',
247
+ criterion: 'WCAG 2.2: 1.3.1 Info and Relationships, 2.4.6 Headings and Labels',
248
+ user_impact: 'The heading outline contains an empty entry, so navigation by heading fails.',
249
+ recommended_fix: 'Put the visible heading text inside the element, or remove the heading.',
250
+ verification: 'Re-run the audit and open the browser heading outline.',
251
+ limitations: 'Text injected by script or a child component is not visible.',
252
+ }));
253
+ }
254
+ }
255
+ for (const m of t.matchAll(/<(?!html\b)([a-zA-Z][\w:-]*)\b([^>]*?)\slang\s*=\s*(["'])\s*\3/gi)) {
256
+ if (insideCode(t, m.index))
257
+ continue;
258
+ push(mk(d, m.index, {
259
+ rule: 'RS-A11Y-022', category: 'accessibility', title: `<${m[1]}> has an empty lang attribute`, severity: 'medium', confidence: 'high',
260
+ criterion: 'WCAG 2.2: 3.1.2 Language of Parts',
261
+ user_impact: 'Assistive technology may pronounce that passage with the wrong language.',
262
+ recommended_fix: 'Set lang to a real language tag, such as lang="fr", or remove the attribute.',
263
+ verification: 'Re-run the audit.',
264
+ limitations: 'The page language (the html element) is rule RS-A11Y-002. This rule only flags an empty lang on other elements.',
265
+ }));
266
+ }
267
+ reportUtilityContrast(d, t, push);
119
268
  if (d.isHtmlDoc) {
120
269
  for (const m of t.matchAll(/<html\b([^>]*)>/gi)) {
121
270
  if (insideCode(t, m.index))
@@ -404,6 +553,26 @@ export function runRules(ctx) {
404
553
  }
405
554
  }
406
555
  }
556
+ const borderPaint = /(?:^|[;\s])border-color\s*:\s*(#[0-9a-fA-F]{3,6}\b|white|black|red|gray|grey|silver)\b|border\s*:\s*[^;{}]*?\s(#[0-9a-fA-F]{3,6}\b|white|black|red|gray|grey|silver)\b/.exec(body);
557
+ if (bg && borderPaint && /button|input|select|textarea|(^|[\s.#])a($|[\s:.,])|btn/i.test(selector) && !/text-shadow|opacity|gradient|filter|mix-blend/i.test(body)) {
558
+ const edge = parseColor(borderPaint[1] ?? borderPaint[2]);
559
+ const fill = parseColor(bg[1]);
560
+ if (edge && fill) {
561
+ const ratio = contrastRatio(edge, fill);
562
+ if (ratio < 3) {
563
+ hit(bodyAt + body.search(/border/), {
564
+ rule: 'RS-A11Y-021', category: 'accessibility',
565
+ title: `Control border contrast ${ratio.toFixed(2)}:1 is below 3:1`,
566
+ severity: 'medium', confidence: 'medium',
567
+ criterion: 'WCAG 2.2: 1.4.11 Non-text Contrast',
568
+ user_impact: 'The edge of the control can disappear against the background for low-vision users.',
569
+ recommended_fix: 'Darken the border or change the background until the ratio is at least 3:1.',
570
+ verification: 'Re-run the audit and check the rendered control with a contrast tool.',
571
+ limitations: 'Only a literal border and background in the same rule are measured. Focus rings and icons are not.',
572
+ });
573
+ }
574
+ }
575
+ }
407
576
  // focus outline removal
408
577
  if (/outline\s*:\s*(none|0)\b|outline-width\s*:\s*0/.test(body) && !/:focus-visible/.test(selector) && !/:not\(:focus/.test(selector)
409
578
  && (/:focus/.test(selector) || !/:active|:hover|:disabled|::|:before|:after/.test(selector))) {
@@ -561,6 +730,13 @@ export const RULE_CATALOG = [
561
730
  { id: 'RS-A11Y-013', title: 'Text contrast below minimum (measured)', category: 'accessibility', severity: 'high', criterion: 'WCAG 1.4.3' },
562
731
  { id: 'RS-A11Y-014', title: 'Interactive target below 24x24 CSS px', category: 'accessibility', severity: 'medium', criterion: 'WCAG 2.5.8' },
563
732
  { id: 'RS-A11Y-015', title: 'No main landmark', category: 'accessibility', severity: 'low', criterion: 'WCAG 1.3.1, 2.4.1' },
733
+ { id: 'RS-A11Y-016', title: 'Duplicate id', category: 'accessibility', severity: 'high', criterion: 'WCAG 4.1.2, 1.3.1' },
734
+ { id: 'RS-A11Y-017', title: 'Frame has no title', category: 'accessibility', severity: 'high', criterion: 'WCAG 4.1.2, 2.4.1' },
735
+ { id: 'RS-A11Y-018', title: 'Navigation with no skip link', category: 'accessibility', severity: 'medium', criterion: 'WCAG 2.4.1' },
736
+ { id: 'RS-A11Y-019', title: 'Email or telephone field has no autocomplete', category: 'accessibility', severity: 'medium', criterion: 'WCAG 1.3.5' },
737
+ { id: 'RS-A11Y-020', title: 'Heading has no text', category: 'accessibility', severity: 'medium', criterion: 'WCAG 2.4.6, 1.3.1' },
738
+ { id: 'RS-A11Y-021', title: 'Control border contrast below 3:1', category: 'accessibility', severity: 'medium', criterion: 'WCAG 1.4.11' },
739
+ { id: 'RS-A11Y-022', title: 'Empty lang on a part of the page', category: 'accessibility', severity: 'medium', criterion: 'WCAG 3.1.2' },
564
740
  { id: 'RS-RESP-001', title: 'No viewport meta tag', category: 'responsive', severity: 'medium', criterion: 'WCAG 1.4.10' },
565
741
  { id: 'RS-RESP-002', title: 'Fixed width can overflow narrow viewports', category: 'responsive', severity: 'medium', criterion: 'WCAG 1.4.10' },
566
742
  { id: 'RS-RESP-003', title: 'No responsive CSS found', category: 'responsive', severity: 'medium' },
@@ -0,0 +1,36 @@
1
+ /** Tailwind CSS default palette, v3. Official hex values. Unknown utilities are ignored. */
2
+ export const TW_COLOR = {
3
+ white: '#ffffff',
4
+ black: '#000000',
5
+ 'gray-50': '#f9fafb',
6
+ 'gray-100': '#f3f4f6',
7
+ 'gray-200': '#e5e7eb',
8
+ 'gray-300': '#d1d5db',
9
+ 'gray-400': '#9ca3af',
10
+ 'gray-500': '#6b7280',
11
+ 'gray-600': '#4b5563',
12
+ 'gray-700': '#374151',
13
+ 'gray-800': '#1f2937',
14
+ 'gray-900': '#111827',
15
+ 'gray-950': '#030712',
16
+ 'slate-50': '#f8fafc',
17
+ 'slate-100': '#f1f5f9',
18
+ 'slate-200': '#e2e8f0',
19
+ 'slate-300': '#cbd5e1',
20
+ 'slate-400': '#94a3b8',
21
+ 'slate-500': '#64748b',
22
+ 'slate-600': '#475569',
23
+ 'slate-700': '#334155',
24
+ 'slate-800': '#1e293b',
25
+ 'slate-900': '#0f172a',
26
+ 'slate-950': '#020617',
27
+ 'red-500': '#ef4444',
28
+ 'red-600': '#dc2626',
29
+ 'red-700': '#b91c1c',
30
+ 'blue-500': '#3b82f6',
31
+ 'blue-600': '#2563eb',
32
+ 'blue-700': '#1d4ed8',
33
+ 'green-500': '#22c55e',
34
+ 'green-600': '#16a34a',
35
+ 'green-700': '#15803d',
36
+ };
@@ -20,7 +20,7 @@
20
20
  | `ci` | audit with JSON default, default gate `confirmed-critical` | no |
21
21
  | `config validate` | validate `rachnasutra.config.json` | no |
22
22
 
23
- Not available: `visual ...` and `audit --mode browser` (exit 3).
23
+ `audit --mode browser` and `visual baseline` / `visual compare` launch Playwright when it is installed. Exit 3 when Playwright or a browser binary is missing, or when the folder has no `index.html`. No result is invented.
24
24
 
25
25
  ## Exit codes
26
26
 
@@ -10,7 +10,7 @@
10
10
  | Windsurf, Kiro, others | unsupported | copy `skills/` manually | - | - |
11
11
  | Headless Linux / CI | CLI works | - | JSON output, exit codes | - |
12
12
  | Windows / Linux | CLI works (Node 20+), tested in blocking CI | - | `.github/workflows/ci.yml` | - |
13
- | macOS | CLI works (Node 20+) | - | weekly and on-demand, `macos-15`, Node 22 and 26, not a required check | - |
13
+ | macOS | CLI should work (Node 20+). Not run in CI | - | GitHub cancels queued macOS jobs before any step. No result is claimed | - |
14
14
 
15
15
  Support labels: `adapter` = files follow the vendor's documented layout; `experimental` = layout unconfirmed; `unsupported` = no adapter. Nothing is marked "verified" because live-host smoke tests have not been done yet.
16
16