rachnasutra 0.5.2 → 0.6.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 (38) hide show
  1. package/CHANGELOG.md +32 -1
  2. package/CITATION.cff +2 -2
  3. package/README.md +4 -4
  4. package/dist/audit.js +117 -18
  5. package/dist/baseline.js +52 -0
  6. package/dist/browser.js +35 -5
  7. package/dist/cli.js +140 -27
  8. package/dist/fsutil.js +11 -4
  9. package/dist/redact.js +17 -7
  10. package/dist/report.js +51 -17
  11. package/dist/rules.js +70 -19
  12. package/dist/verify.js +35 -7
  13. package/docs/cli-reference.md +16 -3
  14. package/docs/status.md +2 -2
  15. package/documents/rachnasutra/00-overview.md +13 -2
  16. package/documents/rachnasutra/01-executive-summary.md +3 -1
  17. package/documents/rachnasutra/02-functional-specification.md +1 -1
  18. package/documents/rachnasutra/03-architecture.md +4 -0
  19. package/documents/rachnasutra/04-technical-reference.md +12 -7
  20. package/documents/rachnasutra/05-user-guide.md +53 -3
  21. package/documents/rachnasutra/07-skills-and-agents.md +2 -0
  22. package/documents/rachnasutra/08-security-and-privacy.md +2 -1
  23. package/documents/rachnasutra/10-testing-and-evidence.md +9 -5
  24. package/documents/rachnasutra/11-deployment-and-ci.md +2 -0
  25. package/documents/rachnasutra/12-roadmap-and-status.md +2 -2
  26. package/documents/rachnasutra/13-maintainer-handbook.md +4 -0
  27. package/documents/rachnasutra/16-validation-and-benchmarks.md +12 -2
  28. package/documents/rachnasutra/18-quick-tour.md +120 -0
  29. package/documents/rachnasutra/19-real-world-scenarios.md +251 -0
  30. package/llms.txt +2 -0
  31. package/package.json +4 -2
  32. package/samples/broken-ui/latest.html +96 -73
  33. package/samples/broken-ui/latest.json +236 -25
  34. package/samples/broken-ui/latest.md +2 -2
  35. package/samples/broken-ui/latest.sarif +1 -1
  36. package/samples/good-ui/latest.html +27 -7
  37. package/samples/good-ui/latest.json +4 -3
  38. package/samples/good-ui/latest.md +2 -2
package/dist/cli.js CHANGED
@@ -2,14 +2,18 @@
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 { BASELINE_FILE, applyBaseline, nextBaseline, readBaseline } from './baseline.js';
5
6
  import { BrowserMissing, runBrowserAudit, saveScreenshot } from './browser.js';
6
- import { CONFIG_FILE, SEVERITY_ORDER, loadConfig, runAudit, validateConfig } from './audit.js';
7
+ import { CONFIG_FILE, SEVERITY_ORDER, UsageError, loadConfig, runAudit, toolVersion, validateConfig } from './audit.js';
7
8
  import { exists } from './fsutil.js';
8
9
  import { renderFixPlanHtml, renderFixPlanMarkdown, renderHistoryHtml, renderHistoryMarkdown, renderHtml, renderJson, renderMarkdown, renderSarif, renderTokensHtml, renderTokensMarkdown, renderVerifyHtml, renderVerifyMarkdown } from './report.js';
9
10
  import { compareToReport, verifyPackage } from './verify.js';
10
11
  const EXIT = { ok: 0, findings: 1, usage: 2, notAvailable: 3, verifyFailed: 4, error: 5 };
11
12
  const NOT_AVAILABLE = ['visual', 'browser'];
12
13
  const DEFAULT_REPORT_DIR = 'rachnasutra-reports';
14
+ const VALUE_FLAGS = new Set(['host', 'target', 'out', 'format', 'fail-on', 'report', 'mode', 'baseline']);
15
+ const BOOL_FLAGS = new Set(['json', 'no-report', 'dry-run', 'force', 'verbose', 'version', 'help', 'allow-empty', 'no-excerpts']);
16
+ const FORMATS = ['json', 'md', 'html', 'sarif'];
13
17
  const HELP = `RachnaSutra AI - Design Beautifully. Audit Precisely. Deliver Delight.
14
18
 
15
19
  Usage: rachnasutra <command> [path] [options]
@@ -30,6 +34,8 @@ Deterministic commands (no AI, no network, read-only unless noted):
30
34
  verify --report <file> [path] re-audit; writes verify.md and verify.html next to the JSON report
31
35
  export --format sarif [path] print SARIF 2.1.0
32
36
  ci [path] audit with CI exit codes (--fail-on confirmed-critical|<severity>)
37
+ baseline [path] accept today's findings in rachnasutra.baseline.json; running it again only
38
+ removes fixed ones (--force accepts new ones, --baseline <file> to choose)
33
39
  history [dir] compare saved JSON reports; writes history.md and history.html
34
40
  config validate [path] validate ${CONFIG_FILE}
35
41
  install | uninstall aliases of skills install | uninstall
@@ -41,56 +47,121 @@ Browser mode (real browser, exit 3 only when Playwright is not installed):
41
47
 
42
48
  Options:
43
49
  --json --no-report --dry-run --force --host <id> --target <dir> --out <dir> --format <list>
44
- --fail-on <sev|confirmed-critical> --verbose --version --help
50
+ --fail-on <sev|confirmed-critical> --allow-empty --no-excerpts --report <file> --mode static|browser
51
+ --baseline <file> --verbose --version --help
52
+ Values may be written as --key value or --key=value. Unknown flags are an error.
45
53
 
46
- Exit codes: 0 ok | 1 findings at/above threshold | 2 usage | 3 not available | 4 verify failed | 5 error
54
+ --baseline gate only on findings that are not in this file (config key "baseline" also works)
55
+ --allow-empty let a gate pass when no supported file was found
56
+ --no-excerpts leave source excerpts and the absolute project path out of reports
57
+
58
+ Exit codes: 0 ok | 1 findings at/above threshold | 2 usage | 3 not available | 4 verify failed
59
+ 5 error, or a gate that could not see the whole project
47
60
  `;
48
61
  function parse(argv) {
49
62
  const flags = {};
50
63
  const pos = [];
51
- const withValue = new Set(['host', 'target', 'out', 'format', 'fail-on', 'report', 'mode', 'base-url', 'viewport', 'profile', 'level', 'url']);
52
64
  for (let i = 0; i < argv.length; i++) {
53
65
  const a = argv[i];
54
- if (a.startsWith('--')) {
55
- const key = a.slice(2);
56
- if (withValue.has(key))
57
- flags[key] = argv[++i] ?? '';
58
- else
59
- flags[key] = true;
66
+ if (!a.startsWith('--')) {
67
+ pos.push(a);
68
+ continue;
69
+ }
70
+ const eq = a.indexOf('=');
71
+ const key = a.slice(2, eq < 0 ? undefined : eq);
72
+ if (VALUE_FLAGS.has(key)) {
73
+ const value = eq < 0 ? argv[++i] : a.slice(eq + 1);
74
+ if (!value || value.startsWith('--'))
75
+ throw new UsageError(`--${key} needs a value.`);
76
+ flags[key] = value;
77
+ }
78
+ else if (BOOL_FLAGS.has(key)) {
79
+ if (eq >= 0)
80
+ throw new UsageError(`--${key} takes no value.`);
81
+ flags[key] = true;
60
82
  }
61
83
  else
62
- pos.push(a);
84
+ throw new UsageError(`Unknown flag --${key}. See: rachnasutra --help`);
63
85
  }
64
86
  return { cmd: pos.shift(), pos, flags };
65
87
  }
88
+ /** Reject bad option values before any work is done. */
89
+ function checkValues(flags) {
90
+ const th = flags['fail-on'];
91
+ if (th && th !== 'confirmed-critical' && !SEVERITY_ORDER.includes(th)) {
92
+ throw new UsageError(`--fail-on must be confirmed-critical|${SEVERITY_ORDER.join('|')}, not "${th}".`);
93
+ }
94
+ const bad = formatList(flags).filter((f) => !FORMATS.includes(f));
95
+ if (bad.length)
96
+ throw new UsageError(`Unknown format "${bad[0]}". Use ${FORMATS.join(',')}.`);
97
+ if (formatList(flags).length > 1 && !flags.out)
98
+ throw new UsageError('Several formats need --out <dir>.');
99
+ if (flags.mode && flags.mode !== 'static' && flags.mode !== 'browser')
100
+ throw new UsageError(`--mode must be static or browser, not "${String(flags.mode)}".`);
101
+ }
102
+ const formatList = (flags) => String(flags.format ?? '').split(',').map((s) => s.trim()).filter(Boolean);
103
+ async function requireDir(dir) {
104
+ const stat = await fs.stat(dir).catch(() => null);
105
+ if (!stat?.isDirectory())
106
+ throw new UsageError(stat ? `Not a directory: ${dir}` : `No such directory: ${dir}`);
107
+ }
66
108
  const write = (s) => void process.stdout.write(s.endsWith('\n') ? s : `${s}\n`);
67
109
  function failCode(res, th) {
68
110
  if (!th)
69
111
  return EXIT.ok;
112
+ const counted = res.findings.filter((f) => f.baselineState !== 'unchanged');
70
113
  if (th === 'confirmed-critical')
71
- return res.findings.some((f) => f.status === 'confirmed' && (f.severity === 'critical' || f.severity === 'high')) ? EXIT.findings : EXIT.ok;
114
+ return counted.some((f) => f.status === 'confirmed' && (f.severity === 'critical' || f.severity === 'high')) ? EXIT.findings : EXIT.ok;
72
115
  const i = SEVERITY_ORDER.indexOf(th);
73
116
  if (i < 0)
74
117
  return EXIT.usage;
75
- return res.findings.some((f) => SEVERITY_ORDER.indexOf(f.severity) <= i) ? EXIT.findings : EXIT.ok;
118
+ return counted.some((f) => SEVERITY_ORDER.indexOf(f.severity) <= i) ? EXIT.findings : EXIT.ok;
119
+ }
120
+ /** Why a clean result cannot be trusted as a pass, if it cannot. */
121
+ function gateGap(r, allowEmpty) {
122
+ if (r.truncated)
123
+ return 'The scan stopped at a file or time limit. Raise maxFiles or add exclude entries.';
124
+ if (r.skipped.unreadable)
125
+ return `${r.skipped.unreadable} file(s) or folder(s) could not be read.`;
126
+ if (!r.filesScanned && !allowEmpty)
127
+ return 'No supported file was scanned. Check the path, or pass --allow-empty.';
128
+ return undefined;
129
+ }
130
+ /** Privacy mode: keep file and line, drop source text and the absolute path. */
131
+ function stripSource(r) {
132
+ // browser mode also writes screenshot paths into limitations and coverage details
133
+ const local = (s) => s.replaceAll(r.root + path.sep, '').replaceAll(process.cwd() + path.sep, '');
134
+ r.limitations = r.limitations.map(local);
135
+ for (const c of r.coverage)
136
+ c.detail = local(c.detail);
137
+ r.root = path.basename(r.root);
138
+ for (const f of [...r.findings, ...(r.suppressed ?? [])])
139
+ for (const e of f.evidence) {
140
+ e.excerpt = '[omitted]';
141
+ delete e.context;
142
+ }
76
143
  }
77
144
  function textSummary(r) {
78
145
  const by = SEVERITY_ORDER.map((s) => `${r.findings.filter((f) => f.severity === s).length} ${s}`).join(', ');
79
146
  const lines = [
80
147
  `RachnaSutra static audit of ${r.root}`,
81
148
  `Scanned ${r.filesScanned} file(s). ${r.findings.length} finding(s): ${by}.`,
82
- ...r.findings.slice(0, 40).map((f) => ` ${f.id} [${f.severity}/${f.status}] ${f.rule} ${f.file}${f.line ? `:${f.line}` : ''} - ${f.title}`),
149
+ ...(r.findings.some((f) => f.baselineState) ? [r.limitations.find((l) => l.startsWith('Baseline:')) ?? ''] : []),
150
+ ...r.findings.filter((f) => f.baselineState !== 'unchanged').slice(0, 40).map((f) => ` ${f.id} [${f.severity}/${f.status}] ${f.rule} ${f.file}${f.line ? `:${f.line}` : ''} - ${f.title}`),
83
151
  ];
84
- if (r.findings.length > 40)
85
- lines.push(` ... ${r.findings.length - 40} more (use --format or --json)`);
152
+ const shown = r.findings.filter((f) => f.baselineState !== 'unchanged').length;
153
+ if (shown > 40)
154
+ lines.push(` ... ${shown - 40} more (use --format or --json)`);
86
155
  const notRun = r.coverage.filter((c) => c.state === 'not-run').map((c) => c.category);
87
156
  lines.push(notRun.length ? `Not evaluated: ${notRun.join(', ')}.` : 'Every listed coverage category ran.', 'This is not a WCAG conformance statement.');
88
157
  return lines.join('\n');
89
158
  }
90
159
  async function emitAudit(res, args) {
91
- const formats = String(args.flags.format ?? '').split(',').map((s) => s.trim()).filter(Boolean);
160
+ let formats = formatList(args.flags);
92
161
  const outDir = args.flags.out ? path.resolve(String(args.flags.out)) : undefined;
93
- if (!formats.length || !outDir) {
162
+ if (outDir && !formats.length)
163
+ formats = args.flags.json ? ['json'] : ['md', 'html', 'json'];
164
+ if (!outDir) {
94
165
  if (args.flags.json || formats.includes('json'))
95
166
  write(renderJson(res));
96
167
  else if (formats.includes('md'))
@@ -111,8 +182,6 @@ async function emitAudit(res, args) {
111
182
  if (!args.flags['dry-run'])
112
183
  await fs.mkdir(outDir, { recursive: true });
113
184
  for (const f of formats) {
114
- if (!files[f])
115
- throw new Error(`Unknown format "${f}". Use json,md,html,sarif.`);
116
185
  if (!args.flags['dry-run'])
117
186
  await fs.writeFile(path.join(outDir, names[f]), files[f], 'utf8');
118
187
  written.push(path.join(outDir, names[f]));
@@ -136,17 +205,22 @@ async function main() {
136
205
  const json = Boolean(args.flags.json);
137
206
  const dry = Boolean(args.flags['dry-run']);
138
207
  if (args.flags.version || args.cmd === 'version') {
139
- const pkg = JSON.parse(await fs.readFile(path.join(packageRoot(), 'package.json'), 'utf8'));
140
- write(json ? JSON.stringify({ version: pkg.version }) : pkg.version);
208
+ write(json ? JSON.stringify({ version: toolVersion() }) : toolVersion());
141
209
  return EXIT.ok;
142
210
  }
143
211
  if (!args.cmd || args.flags.help || args.cmd === 'help') {
144
212
  process.stdout.write(HELP);
145
213
  return args.cmd || args.flags.help ? EXIT.ok : EXIT.usage;
146
214
  }
215
+ checkValues(args.flags);
147
216
  const cmd = args.cmd;
148
217
  const sub = ['skills', 'design-system', 'config', 'visual'].includes(cmd) ? args.pos.shift() : undefined;
149
218
  const target = path.resolve(args.pos[0] ?? '.');
219
+ if (args.flags.baseline && !['audit', 'accessibility', 'ci', 'baseline'].includes(cmd))
220
+ throw new UsageError(`--baseline does not apply to ${cmd}.`);
221
+ const readsProject = ['audit', 'accessibility', 'ci', 'export', 'design-system', 'init', 'config', 'visual', 'baseline'].includes(cmd) || (cmd === 'verify' && args.flags.report);
222
+ if (readsProject)
223
+ await requireDir(target);
150
224
  if (cmd === 'visual' || (cmd === 'audit' && args.flags.mode === 'browser')) {
151
225
  try {
152
226
  if (cmd === 'visual') {
@@ -245,7 +319,12 @@ async function main() {
245
319
  case 'audit':
246
320
  case 'accessibility':
247
321
  case 'ci': {
248
- const res = await runAudit(target, cmd === 'accessibility' ? { categories: ['accessibility'] } : {});
322
+ const config = await loadConfig(target);
323
+ const baselinePath = args.flags.baseline ? path.resolve(String(args.flags.baseline)) : config.baseline ? path.resolve(target, config.baseline) : undefined;
324
+ const accepted = baselinePath ? await readBaseline(baselinePath) : null;
325
+ if (baselinePath && !accepted)
326
+ throw new UsageError(`No baseline at ${baselinePath}. Create it with: rachnasutra baseline`);
327
+ const res = await runAudit(target, { config, uncapped: Boolean(accepted), ...(cmd === 'accessibility' ? { categories: ['accessibility'] } : {}) });
249
328
  if (cmd === 'audit' && args.flags.mode === 'browser') {
250
329
  try {
251
330
  const out = path.resolve(String(args.flags.out ?? DEFAULT_REPORT_DIR));
@@ -280,8 +359,12 @@ async function main() {
280
359
  throw e;
281
360
  }
282
361
  }
362
+ if (accepted)
363
+ applyBaseline(res, accepted);
364
+ if (args.flags['no-excerpts'])
365
+ stripSource(res);
283
366
  if (cmd === 'ci') {
284
- if (!args.flags.format)
367
+ if (!args.flags.format && !args.flags.out)
285
368
  args.flags.json = true;
286
369
  }
287
370
  else if (!args.flags.json && !args.flags.format && !args.flags.out && !args.flags['no-report']) {
@@ -290,11 +373,40 @@ async function main() {
290
373
  args.flags.out = DEFAULT_REPORT_DIR;
291
374
  }
292
375
  await emitAudit(res, args);
293
- const cfgFail = (await loadConfig(target)).failOn;
294
- return failCode(res, args.flags['fail-on'] ?? cfgFail ?? (cmd === 'ci' ? 'confirmed-critical' : undefined));
376
+ const threshold = args.flags['fail-on'] ?? config.failOn ?? (cmd === 'ci' ? 'confirmed-critical' : undefined);
377
+ const code = failCode(res, threshold);
378
+ if (code !== EXIT.ok || !threshold)
379
+ return code;
380
+ const gap = gateGap(res, Boolean(args.flags['allow-empty']));
381
+ if (!gap)
382
+ return EXIT.ok;
383
+ process.stderr.write(`rachnasutra: gate not passed. ${gap}\n`);
384
+ return EXIT.error;
385
+ }
386
+ case 'baseline': {
387
+ const config = await loadConfig(target);
388
+ const file = args.flags.baseline ? path.resolve(String(args.flags.baseline)) : path.resolve(target, config.baseline ?? BASELINE_FILE);
389
+ const previous = args.flags.force ? null : await readBaseline(file);
390
+ const res = await runAudit(target, { config, uncapped: true });
391
+ const gap = gateGap(res, Boolean(args.flags['allow-empty']));
392
+ if (gap) {
393
+ process.stderr.write(`rachnasutra: baseline not written. ${gap}\n`);
394
+ return EXIT.error;
395
+ }
396
+ const next = nextBaseline(res, previous);
397
+ if (!dry)
398
+ await fs.writeFile(file, `${JSON.stringify(next, null, 2)}\n`, 'utf8');
399
+ const added = res.findings.length - next.entries.length;
400
+ write([
401
+ `${dry ? 'Would write' : 'Wrote'} ${file}: ${next.entries.length} accepted finding(s).`,
402
+ ...(previous ? [`Removed ${previous.entries.length - next.entries.length} fixed. ${added} new finding(s) were not added${added ? '; fix them, or use --force to accept them' : ''}.`] : []),
403
+ ].join('\n'));
404
+ return EXIT.ok;
295
405
  }
296
406
  case 'export': {
297
407
  const res = await runAudit(target);
408
+ if (args.flags['no-excerpts'])
409
+ stripSource(res);
298
410
  if (String(args.flags.format ?? 'sarif') !== 'sarif') {
299
411
  process.stderr.write('export supports --format sarif\n');
300
412
  return EXIT.usage;
@@ -360,6 +472,7 @@ async function main() {
360
472
  `Resolved: ${c.resolved.length} Remaining: ${c.remaining.length} Introduced: ${c.introduced.length}`,
361
473
  ...c.resolved.map((f) => ` resolved ${f.rule} ${f.file}${f.line ? `:${f.line}` : ''}`),
362
474
  ...c.introduced.map((f) => ` introduced ${f.rule} ${f.file}${f.line ? `:${f.line}` : ''} - ${f.title}`),
475
+ ...(c.notRechecked ? [`Not re-checked: ${c.notRechecked} browser finding(s). Run audit --mode browser again.`] : []),
363
476
  'Static re-check only; manual accessibility and visual verification are still needed.',
364
477
  ].join('\n'));
365
478
  return c.introduced.length ? EXIT.verifyFailed : EXIT.ok;
@@ -435,5 +548,5 @@ main().then((code) => process.exit(code), (e) => {
435
548
  process.stderr.write(`rachnasutra: ${e.message}\n`);
436
549
  if (process.argv.includes('--verbose'))
437
550
  process.stderr.write(`${e.stack}\n`);
438
- process.exit(EXIT.error);
551
+ process.exit(e instanceof UsageError ? EXIT.usage : EXIT.error);
439
552
  });
package/dist/fsutil.js CHANGED
@@ -1,9 +1,13 @@
1
1
  import { promises as fs } from 'node:fs';
2
2
  import path from 'node:path';
3
3
  const IGNORED_DIRS = new Set([
4
- 'node_modules', '.git', 'dist', 'build', 'out', 'target', 'vendor', '.venv', 'venv', '__pycache__',
5
- '.next', '.nuxt', '.svelte-kit', 'coverage', '.idea', '.vscode', '.rachnasutra', 'reports', 'rachnasutra-reports', 'graphify-out',
4
+ 'node_modules', '.git', '.venv', 'venv', '__pycache__',
5
+ '.next', '.nuxt', '.svelte-kit', '.idea', '.vscode', '.rachnasutra', 'rachnasutra-reports', 'graphify-out',
6
6
  ]);
7
+ /** Often generated, but also ordinary source folder names (src/reports, app/build). */
8
+ const OUTPUT_DIRS = new Set(['dist', 'build', 'out', 'target', 'vendor', 'coverage', 'reports']);
9
+ /** A folder holding one of these is a project root, so its output folders are generated ones. */
10
+ const PROJECT_MARKERS = new Set(['package.json', 'pom.xml', 'Cargo.toml', 'composer.json', 'go.mod', 'build.gradle', 'build.gradle.kts']);
7
11
  const IMAGE_EXT = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.avif', '.svg']);
8
12
  const BINARY_EXT = new Set([
9
13
  '.ico', '.pdf', '.zip', '.gz', '.tgz', '.tar', '.7z', '.woff', '.woff2', '.ttf', '.eot', '.otf',
@@ -33,7 +37,7 @@ export async function walk(root, opts = {}) {
33
37
  const start = Date.now();
34
38
  const files = [];
35
39
  const assets = [];
36
- const skipped = { ignoredDirs: 0, tooLarge: 0, binary: 0, symlinks: 0, overBudget: 0, excluded: 0 };
40
+ const skipped = { ignoredDirs: 0, tooLarge: 0, binary: 0, symlinks: 0, overBudget: 0, excluded: 0, unreadable: 0 };
37
41
  let truncated = false;
38
42
  const absRoot = path.resolve(root);
39
43
  async function visit(dir) {
@@ -44,8 +48,10 @@ export async function walk(root, opts = {}) {
44
48
  entries = await fs.readdir(dir, { withFileTypes: true });
45
49
  }
46
50
  catch {
51
+ skipped.unreadable++;
47
52
  return;
48
53
  }
54
+ const projectRoot = dir === absRoot || entries.some((e) => PROJECT_MARKERS.has(e.name));
49
55
  entries.sort((a, b) => a.name.localeCompare(b.name));
50
56
  for (const e of entries) {
51
57
  if (Date.now() - start > timeBudgetMs || files.length >= maxFiles) {
@@ -64,7 +70,7 @@ export async function walk(root, opts = {}) {
64
70
  continue;
65
71
  }
66
72
  if (e.isDirectory()) {
67
- if (IGNORED_DIRS.has(e.name)) {
73
+ if (IGNORED_DIRS.has(e.name) || (projectRoot && OUTPUT_DIRS.has(e.name))) {
68
74
  skipped.ignoredDirs++;
69
75
  continue;
70
76
  }
@@ -79,6 +85,7 @@ export async function walk(root, opts = {}) {
79
85
  size = (await fs.stat(abs)).size;
80
86
  }
81
87
  catch {
88
+ skipped.unreadable++;
82
89
  continue;
83
90
  }
84
91
  if (IMAGE_EXT.has(ext))
package/dist/redact.js CHANGED
@@ -6,9 +6,24 @@ const PATTERNS = [
6
6
  { name: 'slack-token', re: /\bxox[abprs]-[A-Za-z0-9-]{10,}\b/g },
7
7
  { name: 'google-api-key', re: /\bAIza[0-9A-Za-z_-]{35}\b/g },
8
8
  { name: 'private-key', re: /-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP )?PRIVATE KEY-----/g },
9
+ { name: 'stripe-key', re: /\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}\b/g },
10
+ { name: 'npm-token', re: /\bnpm_[A-Za-z0-9]{30,}\b/g },
11
+ { name: 'jwt', re: /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g },
12
+ { name: 'bearer-token', re: /\bBearer\s+(?=[A-Za-z._~+/-]*\d)[A-Za-z0-9._~+/-]{16,}=*/g },
13
+ // The patterns below keep the surrounding text and mask only the value.
14
+ { name: 'url-credential', re: /\b([a-z][a-z0-9+.-]*:\/\/[^\s/:@"']*:)[^\s/@"']+(?=@)/gi, keep: '$1[REDACTED]' },
15
+ { name: 'query-credential', re: /([?&](?:access_token|auth_token|token|api[_-]?key|key|secret|password)=)(?!\[)[^&\s"'<>]{8,}/gi, keep: '$1[REDACTED]' },
9
16
  {
17
+ // password = "x", "client_secret": "x", apiKeyProd: 'x'
10
18
  name: 'credential-assignment',
11
- re: /\b(password|passwd|secret|api[_-]?key|token|access[_-]?key)\b(\s*[:=]\s*)(["'])[^"'\s]{8,}\3/gi,
19
+ re: /((?:password|passwd|secret|api[_-]?key|token|access[_-]?key|private[_-]?key)[\w-]{0,40}["']?\s*[:=]\s*)(["'])(?!\[REDACTED)[^"'\s]{8,}\2/gi,
20
+ keep: '$1$2[REDACTED]$2',
21
+ },
22
+ {
23
+ // API_KEY=abc123 (upper-case environment style, no quotes)
24
+ name: 'env-assignment',
25
+ re: /\b([A-Z0-9_]{0,40}(?:PASSWORD|PASSWD|SECRET|API_?KEY|TOKEN|ACCESS_?KEY|PRIVATE_KEY)[A-Z0-9_]{0,40}=)(?!\[)[^\s"'<>;&{}$()]{8,}/g,
26
+ keep: '$1[REDACTED]',
12
27
  },
13
28
  ];
14
29
  /** Return the kinds of secret found in a line (never the value). */
@@ -26,12 +41,7 @@ export function redact(text) {
26
41
  let out = text;
27
42
  for (const p of PATTERNS) {
28
43
  p.re.lastIndex = 0;
29
- if (p.name === 'credential-assignment') {
30
- out = out.replace(p.re, (_m, k, sep, q) => `${k}${sep}${q}[REDACTED]${q}`);
31
- }
32
- else {
33
- out = out.replace(p.re, `[REDACTED:${p.name}]`);
34
- }
44
+ out = out.replace(p.re, p.keep ?? `[REDACTED:${p.name}]`);
35
45
  }
36
46
  return out;
37
47
  }
package/dist/report.js CHANGED
@@ -4,20 +4,37 @@ import { RULE_CATALOG } from './rules.js';
4
4
  export const escHtml = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
5
5
  /** Escape text for a Markdown table cell or inline span. */
6
6
  const escMd = (s) => s.replace(/\|/g, '\\|').replace(/[\r\n]+/g, ' ').replace(/`/g, "'");
7
- const PAGE_CSS = `:root{--bg:#fbfaf8;--fg:#1d1b19;--muted:#5b564f;--card:#fff;--line:#d9d4cc;--accent:#8a3b12;--crit:#8f1d1d;--high:#a1400b;--med:#7a5a00;--low:#245c3a;--info:#33506b}
8
- @media (prefers-color-scheme:dark){:root{--bg:#141210;--fg:#f2eee8;--muted:#b8b0a5;--card:#1d1a17;--line:#3a352f;--accent:#f0a070;--crit:#ff9a9a;--high:#ffb27a;--med:#f0d070;--low:#8fd6a8;--info:#9cc4e8}}
7
+ const LIGHT = 'color-scheme:light;--bg:#fbfaf8;--fg:#1d1b19;--muted:#5b564f;--card:#fff;--line:#d9d4cc;--accent:#8a3b12;--hit:#fbeee4;--crit:#8f1d1d;--high:#a1400b;--med:#7a5a00;--low:#245c3a;--info:#33506b';
8
+ const DARK = 'color-scheme:dark;--bg:#141210;--fg:#f2eee8;--muted:#b8b0a5;--card:#1d1a17;--line:#3a352f;--accent:#f0a070;--hit:#3a2a1f;--crit:#ff9a9a;--high:#ffb27a;--med:#f0d070;--low:#8fd6a8;--info:#9cc4e8';
9
+ const STATUSES = ['confirmed', 'review-required'];
10
+ const THEMES = [['auto', 'Auto'], ['light', 'Light'], ['dark', 'Dark'], ['mix', 'Mix']];
11
+ // Themes and filters are CSS only (:has), so reports stay script-free. The choice is not remembered after a reload.
12
+ const PAGE_CSS = `:root{${LIGHT}}
13
+ @media (prefers-color-scheme:dark){:root{${DARK}}}
14
+ :root:has(#t-light:checked),:root:has(#t-mix:checked){${LIGHT}}
15
+ :root:has(#t-dark:checked),:root:has(#t-mix:checked) .top{${DARK}}
9
16
  body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.55 system-ui,-apple-system,"Segoe UI",sans-serif}
10
- main{max-width:70rem;margin:0 auto;padding:1.5rem 1rem 4rem}
17
+ main,.top>div{max-width:70rem;margin:0 auto;padding:0 1rem}main{padding-bottom:4rem}
18
+ .top{background:var(--bg);color:var(--fg);border-bottom:1px solid var(--line);padding:1.2rem 0 .8rem}
11
19
  h1{font-size:1.75rem;margin:.2rem 0}h2{margin-top:2.2rem;font-size:1.25rem;border-bottom:1px solid var(--line);padding-bottom:.3rem}
20
+ fieldset{border:0;padding:0;margin:.6rem 0 0;display:flex;flex-wrap:wrap;gap:.4rem;align-items:center}legend{float:left;font-weight:600;margin-right:.4rem}
21
+ fieldset label{display:inline-flex;align-items:center;gap:.35rem;border:1px solid var(--line);background:var(--card);border-radius:2rem;padding:.25rem .75rem;cursor:pointer}
22
+ fieldset label:has(:checked){border-color:var(--accent)}input{accent-color:var(--accent)}
12
23
  .muted{color:var(--muted)}.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(8rem,1fr));gap:.75rem}
13
24
  .stat{background:var(--card);border:1px solid var(--line);border-radius:.6rem;padding:.7rem}.stat b{display:block;font-size:1.5rem}
14
25
  .tablewrap{overflow-x:auto}table{border-collapse:collapse;width:100%;background:var(--card)}th,td{border:1px solid var(--line);padding:.45rem .6rem;text-align:left;vertical-align:top}
15
- .sev{font-weight:600}.sev-critical{color:var(--crit)}.sev-high{color:var(--high)}.sev-medium{color:var(--med)}.sev-low{color:var(--low)}.sev-info{color:var(--info)}
26
+ .f th{white-space:nowrap}.sev{font-weight:600}.sev-critical{color:var(--crit)}.sev-high{color:var(--high)}.sev-medium{color:var(--med)}.sev-low{color:var(--low)}.sev-info{color:var(--info)}
16
27
  .card{background:var(--card);border:1px solid var(--line);border-radius:.6rem;padding:.8rem 1rem;margin:.8rem 0}.card h3{margin:.1rem 0 .4rem;font-size:1.05rem}
17
28
  .note{background:var(--card);border:1px solid var(--line);border-radius:.6rem;padding:.8rem 1rem}
29
+ .ctx{border:1px solid var(--line);border-radius:.4rem;padding:.3rem 0;white-space:normal}.ctx>span{display:flex;gap:.8rem;padding:0 .6rem;white-space:pre-wrap}.ctx i{font-style:normal;color:var(--muted);min-width:3ch;text-align:right}.ctx>.hit{background:var(--hit);font-weight:600}
18
30
  dt{font-weight:600;margin-top:.5rem}dd{margin:0}code,pre{font-family:ui-monospace,Consolas,monospace;font-size:.88em;white-space:pre-wrap;overflow-wrap:anywhere}pre{margin:.2rem 0}
19
- a:focus-visible,summary:focus-visible{outline:3px solid var(--accent);outline-offset:2px}`;
31
+ a{color:var(--accent)}a:focus-visible,input:focus-visible{outline:3px solid var(--accent);outline-offset:2px}
32
+ ${[...SEVERITY_ORDER.map((s) => `s-${s}`), ...STATUSES.map((s) => `st-${s}`)].map((c) => `body:has(#f-${c}:not(:checked)) .f.${c}{display:none}`).join('\n')}
33
+ @media print{:root,:root .top{${LIGHT.replace(/;|$/g, '!important$&')}}
34
+ fieldset,.filter-note{display:none}tr.f.f{display:table-row!important}article.f.f{display:block!important}
35
+ body{font-size:11pt}main,.top>div{max-width:none}.card,tr,.ctx{break-inside:avoid}h2,h3{break-after:avoid}.ctx>.hit{print-color-adjust:exact}}`;
20
36
  function page(title, body) {
37
+ const themes = THEMES.map(([id, label]) => `<label><input type="radio" name="theme" id="t-${id}"${id === 'auto' ? ' checked' : ''}> ${label}</label>`).join('');
21
38
  return `<!doctype html>
22
39
  <html lang="en">
23
40
  <head>
@@ -29,6 +46,10 @@ ${PAGE_CSS}
29
46
  </style>
30
47
  </head>
31
48
  <body>
49
+ <header class="top"><div>
50
+ <h1>${escHtml(title)}</h1>
51
+ <fieldset><legend>Theme</legend>${themes}</fieldset>
52
+ </div></header>
32
53
  <main>
33
54
  ${body}
34
55
  </main>
@@ -36,6 +57,19 @@ ${body}
36
57
  </html>
37
58
  `;
38
59
  }
60
+ function contextBlock(e) {
61
+ if (!e.context)
62
+ return e.excerpt ? ` <pre>${escHtml(e.excerpt)}</pre>` : '';
63
+ const { start, lines } = e.context;
64
+ return ` <code class="ctx" style="display:block">${lines.map((l, i) => `<span${start + i === e.line ? ' class="hit"' : ''}><i>${start + i}</i>${escHtml(l) || ' '}</span>`).join('')}</code>`;
65
+ }
66
+ /** Checkboxes that hide rows and cards. Only values present in this report get one. */
67
+ function filterBar(findings) {
68
+ const group = (legend, prefix, values) => `<fieldset><legend>${legend}</legend>${values.map((v) => `<label><input type="checkbox" id="f-${prefix}-${v}" checked> ${v} (${findings.filter((f) => (prefix === 's' ? f.severity : f.status) === v).length})</label>`).join('')}</fieldset>`;
69
+ return `${group('Severity', 's', SEVERITY_ORDER.filter((s) => findings.some((f) => f.severity === s)))}
70
+ ${group('Status', 'st', STATUSES.filter((s) => findings.some((f) => f.status === s)))}
71
+ <p class="muted filter-note">Filters hide findings in the table and details on this page. Counts and printouts include everything.</p>`;
72
+ }
39
73
  const HOW_TO_READ_MD = [
40
74
  '## How to read this',
41
75
  '',
@@ -122,15 +156,15 @@ export function renderMarkdown(r) {
122
156
  export function renderHtml(r) {
123
157
  const s = summarize(r);
124
158
  const rows = r.findings
125
- .map((f) => `<tr id="${escHtml(f.id)}"><th scope="row"><a href="#h-${escHtml(f.id)}">${escHtml(f.id)}</a></th><td><span class="sev sev-${f.severity}">${f.severity}</span></td><td>${escHtml(f.rule)}</td><td>${escHtml(f.title)}</td><td><code>${escHtml(loc(f))}</code></td><td>${f.status}</td></tr>`)
159
+ .map((f) => `<tr id="${escHtml(f.id)}" class="f s-${f.severity} st-${f.status}"><th scope="row"><a href="#h-${escHtml(f.id)}">${escHtml(f.id)}</a></th><td><span class="sev sev-${f.severity}">${f.severity}</span></td><td>${escHtml(f.rule)}</td><td>${escHtml(f.title)}</td><td><code>${escHtml(loc(f))}</code></td><td>${f.status}</td></tr>`)
126
160
  .join('\n');
127
161
  const details = r.findings
128
- .map((f) => `<article class="card" aria-labelledby="h-${escHtml(f.id)}">
162
+ .map((f) => `<article class="card f s-${f.severity} st-${f.status}" aria-labelledby="h-${escHtml(f.id)}">
129
163
  <h3 id="h-${escHtml(f.id)}">${escHtml(f.id)} &mdash; ${escHtml(f.title)}</h3>
130
164
  <dl>
131
165
  <dt>Severity / confidence / status</dt><dd>${f.severity} / ${f.confidence} / ${f.status}</dd>
132
166
  ${f.criterion ? `<dt>Criterion</dt><dd>${escHtml(f.criterion)}</dd>` : ''}
133
- <dt>Evidence</dt><dd>${f.evidence.map((e) => `<code>${escHtml(e.path)}${e.line ? `:${e.line}` : ''}</code>${e.excerpt ? ` <pre>${escHtml(e.excerpt)}</pre>` : ''}`).join('')}</dd>
167
+ <dt>Evidence</dt><dd>${f.evidence.map((e) => `<code>${escHtml(e.path)}${e.line ? `:${e.line}` : ''}</code>${contextBlock(e)}`).join('')}</dd>
134
168
  <dt>User impact</dt><dd>${escHtml(f.user_impact)}</dd>
135
169
  <dt>Recommended fix</dt><dd>${escHtml(f.recommended_fix)}</dd>
136
170
  <dt>Verification</dt><dd>${escHtml(f.verification)}</dd>
@@ -138,8 +172,7 @@ ${f.criterion ? `<dt>Criterion</dt><dd>${escHtml(f.criterion)}</dd>` : ''}
138
172
  </dl></article>`)
139
173
  .join('\n');
140
174
  const cov = r.coverage.map((c) => `<tr><th scope="row">${escHtml(c.category)}</th><td>${c.state}</td><td>${escHtml(c.detail)}</td></tr>`).join('\n');
141
- return redact(page('RachnaSutra AI audit report', `<h1>RachnaSutra AI audit report</h1>
142
- <p class="muted">Static mode &middot; read-only &middot; ${escHtml(r.generatedAt)} &middot; ${escHtml(r.tool.name)} ${escHtml(r.tool.version)}</p>
175
+ return redact(page('RachnaSutra AI audit report', `<p class="muted">Static mode &middot; read-only &middot; ${escHtml(r.generatedAt)} &middot; ${escHtml(r.tool.name)} ${escHtml(r.tool.version)}</p>
143
176
  ${HOW_TO_READ_HTML}
144
177
  <h2>Summary</h2>
145
178
  <div class="grid" role="list">
@@ -155,7 +188,8 @@ ${topFixes(r).length ? `<ol>${topFixes(r).map((f) => `<li><strong>${escHtml(f.ti
155
188
  ${cov}
156
189
  </tbody></table></div>
157
190
  <h2>Findings</h2>
158
- ${r.findings.length ? `<div class="tablewrap"><table><caption class="muted">All findings, most severe first</caption><thead><tr><th scope="col">ID</th><th scope="col">Severity</th><th scope="col">Rule</th><th scope="col">Title</th><th scope="col">Location</th><th scope="col">Status</th></tr></thead><tbody>
191
+ ${r.findings.length ? `${filterBar(r.findings)}
192
+ <div class="tablewrap"><table><caption class="muted">All findings, most severe first</caption><thead><tr><th scope="col">ID</th><th scope="col">Severity</th><th scope="col">Rule</th><th scope="col">Title</th><th scope="col">Location</th><th scope="col">Status</th></tr></thead><tbody>
159
193
  ${rows}
160
194
  </tbody></table></div>
161
195
  <h2>Details</h2>
@@ -202,8 +236,7 @@ export function renderFixPlanHtml(findings) {
202
236
  <p><strong>Fix.</strong> ${escHtml(f.recommended_fix)}</p>
203
237
  <p><strong>Check.</strong> ${escHtml(f.verification)}</p>
204
238
  </article>`).join('\n');
205
- return redact(page('RachnaSutra AI fix plan', `<h1>RachnaSutra AI fix plan</h1>
206
- <p class="note">Proposal only. No source files were changed. Work top to bottom. <strong>Confirmed</strong> items are safe to act on. <strong>Review required</strong> items need a person to look first.</p>
239
+ return redact(page('RachnaSutra AI fix plan', `<p class="note">Proposal only. No source files were changed. Work top to bottom. <strong>Confirmed</strong> items are safe to act on. <strong>Review required</strong> items need a person to look first.</p>
207
240
  <h2>Steps</h2>
208
241
  ${order.length ? cards : '<p>No findings in the baseline report.</p>'}
209
242
  <p class="muted">Effort labels are rough assumptions, not estimates from your codebase. After the edits, run <code>rachnasutra verify --report &lt;baseline.json&gt;</code>.</p>`));
@@ -218,6 +251,7 @@ export function renderVerifyMarkdown(c) {
218
251
  `- Resolved: ${c.resolved.length}`,
219
252
  `- Still open: ${c.remaining.length}`,
220
253
  `- New findings: ${c.introduced.length}`,
254
+ ...(c.notRechecked ? [`- Browser findings not re-checked: ${c.notRechecked}`] : []),
221
255
  '',
222
256
  c.introduced.length
223
257
  ? 'New findings appeared. Treat this as a regression and review them before shipping.'
@@ -232,14 +266,14 @@ export function renderVerifyMarkdown(c) {
232
266
  }
233
267
  export function renderVerifyHtml(c) {
234
268
  const section = (title, items) => `<h2>${title}</h2>${items.length ? `<ul>${items.map(findingItem).join('')}</ul>` : '<p>None.</p>'}`;
235
- return redact(page('RachnaSutra AI fix verification', `<h1>RachnaSutra AI fix verification</h1>
236
- <div class="grid" role="list">
269
+ return redact(page('RachnaSutra AI fix verification', `<div class="grid" role="list">
237
270
  <div class="stat" role="listitem"><b>${c.baselineTotal}</b>baseline</div>
238
271
  <div class="stat" role="listitem"><b>${c.currentTotal}</b>now</div>
239
272
  <div class="stat" role="listitem"><b>${c.resolved.length}</b>resolved</div>
240
273
  <div class="stat" role="listitem"><b>${c.remaining.length}</b>still open</div>
241
274
  <div class="stat" role="listitem"><b>${c.introduced.length}</b>new</div>
242
275
  </div>
276
+ ${c.notRechecked ? `<p class="muted">Browser findings not re-checked: ${c.notRechecked}.</p>` : ''}
243
277
  <p class="note">${c.introduced.length ? 'New findings appeared. Treat this as a regression and review them before shipping.' : 'No new findings. Static rules did not see a regression.'}</p>
244
278
  ${section('Resolved', c.resolved)}
245
279
  ${section('Still open', c.remaining)}
@@ -274,8 +308,7 @@ export function renderTokensHtml(t) {
274
308
  return `<h2>${escHtml(title)}</h2><p>None found.</p>`;
275
309
  return `<h2>${escHtml(title)}</h2><div class="tablewrap"><table><thead><tr><th scope="col">Value</th><th scope="col">Count</th></tr></thead><tbody>${rows.map((row) => `<tr><td><code>${escHtml(row.value)}</code></td><td>${row.count}</td></tr>`).join('')}</tbody></table></div>`;
276
310
  };
277
- return redact(page('RachnaSutra AI design token inventory', `<h1>RachnaSutra AI design token inventory</h1>
278
- <p>What the styles use most often. Use this to decide what to turn into shared tokens.</p>
311
+ return redact(page('RachnaSutra AI design token inventory', `<p>What the styles use most often. Use this to decide what to turn into shared tokens.</p>
279
312
  <div class="grid" role="list">
280
313
  <div class="stat" role="listitem"><b>${t.cssVariables}</b>CSS custom properties</div>
281
314
  <div class="stat" role="listitem"><b>${Math.round(t.hardcodedColorRatio * 100)}%</b>literal colours</div>
@@ -311,6 +344,7 @@ export function renderSarif(r) {
311
344
  level: level(f.severity),
312
345
  message: { text: `${f.title}. Fix: ${f.recommended_fix}` },
313
346
  partialFingerprints: { rachnasutra: f.fingerprint },
347
+ ...(f.baselineState ? { baselineState: f.baselineState } : {}),
314
348
  locations: [{ physicalLocation: { artifactLocation: { uri: f.file }, region: { startLine: f.line ?? 1 } } }],
315
349
  properties: { confidence: f.confidence, status: f.status, id: f.id },
316
350
  })),