impeccable 3.3.0 → 3.4.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.
@@ -1,7 +1,8 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
3
4
 
4
- import { loadDesignSystemForCwd } from '../design-system.mjs';
5
+ import { loadDesignSystemForTarget } from '../design-system.mjs';
5
6
  import { RULE_SCOPES, filterByScopes } from '../registry/antipatterns.mjs';
6
7
  import { createBrowserDetector, detectUrl } from '../engines/browser/detect-url.mjs';
7
8
  import { detectHtml } from '../engines/static-html/detect-html.mjs';
@@ -27,9 +28,37 @@ function formatFindingSummary(count) {
27
28
  return `${count} anti-pattern${count === 1 ? '' : 's'} found.`;
28
29
  }
29
30
 
30
- function formatFindings(findings, jsonMode) {
31
- if (jsonMode) return JSON.stringify(findings, null, 2);
31
+ // Local filesystem path behind a file:// URL, or null when it can't be mapped.
32
+ function fileUrlToLocalPath(url) {
33
+ try {
34
+ return fileURLToPath(url);
35
+ } catch {
36
+ return null;
37
+ }
38
+ }
39
+
40
+ // Advisory findings are detected but never treated as failures: they list in a
41
+ // separate, visually dimmed section, are excluded from the failure count that
42
+ // drives the exit code, and carry `"advisory": true` in JSON so consumers can
43
+ // filter. Every advisory finding carries the flag (stamped by the registry via
44
+ // findings.mjs).
45
+ function isAdvisory(finding) {
46
+ return finding && finding.advisory === true;
47
+ }
48
+
49
+ function partitionAdvisory(findings) {
50
+ const primary = [];
51
+ const advisory = [];
52
+ for (const f of findings) (isAdvisory(f) ? advisory : primary).push(f);
53
+ return { primary, advisory };
54
+ }
55
+
56
+ // ANSI dim, when stderr is a TTY. Advisory output is chrome, so keep it quiet.
57
+ function dim(text) {
58
+ return process.stderr.isTTY ? `\x1b[2m${text}\x1b[0m` : text;
59
+ }
32
60
 
61
+ function formatFindingsBody(findings) {
33
62
  const grouped = {};
34
63
  for (const f of findings) {
35
64
  if (!grouped[f.file]) grouped[f.file] = [];
@@ -44,7 +73,28 @@ function formatFindings(findings, jsonMode) {
44
73
  out.push(` → ${item.description}`);
45
74
  }
46
75
  }
47
- out.push(`\n${formatFindingSummary(findings.length)}`);
76
+ return out;
77
+ }
78
+
79
+ function formatAdvisorySection(advisory) {
80
+ if (!advisory || advisory.length === 0) return '';
81
+ const lines = [`\n${dim('── Advisory (not counted as failures) ──')}`];
82
+ for (const line of formatFindingsBody(advisory)) lines.push(dim(line));
83
+ lines.push(dim(`\n${advisory.length} advisory note${advisory.length === 1 ? '' : 's'}. Suppress with --no-advisory.`));
84
+ return lines.join('\n');
85
+ }
86
+
87
+ // Text/JSON formatter. `findings` is the full set; advisory items are separated
88
+ // out into their own section and excluded from the failure summary count. JSON
89
+ // output keeps every finding (each advisory one flagged) in a single array.
90
+ function formatFindings(findings, jsonMode) {
91
+ if (jsonMode) return JSON.stringify(findings, null, 2);
92
+
93
+ const { primary, advisory } = partitionAdvisory(findings);
94
+ const out = [...formatFindingsBody(primary)];
95
+ out.push(`\n${formatFindingSummary(primary.length)}`);
96
+ const advisorySection = formatAdvisorySection(advisory);
97
+ if (advisorySection) out.push(advisorySection);
48
98
  return out.join('\n');
49
99
  }
50
100
 
@@ -52,7 +102,11 @@ function formatFindings(findings, jsonMode) {
52
102
  // Stdin handling
53
103
  // ---------------------------------------------------------------------------
54
104
 
55
- async function handleStdin(options = {}) {
105
+ // `optionsFor` maps a local path to scan options carrying that path's own
106
+ // project design system (or base options when null). Falls back to a plain
107
+ // object so direct/legacy callers still work.
108
+ async function handleStdin(optionsFor = () => ({})) {
109
+ const resolve = typeof optionsFor === 'function' ? optionsFor : () => optionsFor;
56
110
  const chunks = [];
57
111
  for await (const chunk of process.stdin) chunks.push(chunk);
58
112
  const input = Buffer.concat(chunks).toString('utf-8');
@@ -60,11 +114,12 @@ async function handleStdin(options = {}) {
60
114
  const parsed = JSON.parse(input);
61
115
  const fp = parsed?.tool_input?.file_path;
62
116
  if (fp && fs.existsSync(fp)) {
117
+ const options = resolve(fp);
63
118
  return HTML_EXTENSIONS.has(path.extname(fp).toLowerCase())
64
119
  ? detectHtml(fp, options) : detectText(fs.readFileSync(fp, 'utf-8'), fp, options);
65
120
  }
66
121
  } catch { /* not JSON */ }
67
- return detectText(input, '<stdin>', options);
122
+ return detectText(input, '<stdin>', resolve(null));
68
123
  }
69
124
 
70
125
 
@@ -100,8 +155,14 @@ Options:
100
155
  ignore comments, or DESIGN.md
101
156
  --no-inline-ignores Do not honor in-file impeccable-disable* ignore comments
102
157
  --no-design-system Do not load local DESIGN.md / .impeccable/design.json context
158
+ --no-advisory Suppress advisory findings entirely (e.g. em-dash overuse)
103
159
  --help Show this help message
104
160
 
161
+ Advisory findings:
162
+ Some rules are advisory: detected and listed in a separate section, but never
163
+ counted as failures and never changing the exit code. They stay out of the
164
+ failure count so they never block automation. --no-advisory hides them.
165
+
105
166
  Project config:
106
167
  Respects .impeccable/config.json and .impeccable/config.local.json detector
107
168
  settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
@@ -139,6 +200,7 @@ async function detectCli() {
139
200
  const jsonMode = args.includes('--json');
140
201
  const quietMode = args.includes('--quiet');
141
202
  const helpMode = args.includes('--help');
203
+ const noAdvisory = args.includes('--no-advisory');
142
204
  // --fast (regex-only) is deprecated: since the jsdom removal, the static
143
205
  // HTML/CSS analysis is fast and covers every rule, so the regex-only path
144
206
  // only loses coverage for no real speed win. Accept the flag for back-compat
@@ -199,14 +261,23 @@ async function detectCli() {
199
261
  process.exit(1);
200
262
  }
201
263
  const designSystemEnabled = configEnabled && !args.includes('--no-design-system') && detectionConfig.designSystem?.enabled !== false;
202
- const designSystem = designSystemEnabled ? loadDesignSystemForCwd(process.cwd()) : null;
203
264
  // Inline `impeccable-disable*` waivers are part of the scanned file, so they
204
265
  // apply by default. `--no-config` (raw scan) and the dedicated
205
266
  // `--no-inline-ignores` both turn them off.
206
267
  const inlineIgnoresEnabled = configEnabled && !args.includes('--no-inline-ignores');
207
- const scanOptions = { inlineIgnores: inlineIgnoresEnabled };
208
- if (designSystem) scanOptions.designSystem = designSystem;
209
- if (viewport) scanOptions.viewport = viewport;
268
+ const baseScanOptions = { inlineIgnores: inlineIgnoresEnabled };
269
+ if (viewport) baseScanOptions.viewport = viewport;
270
+ // DESIGN.md must resolve from EACH scan target's own project root, not from
271
+ // process.cwd(): scanning project B's files from inside project A applied A's
272
+ // design rules (cross-project contamination). Resolve per target, memoized by
273
+ // resolved project root so a multi-file scan pays the read once per project.
274
+ // A target with no project marker above it gets no design system (never cwd's).
275
+ const designSystemCache = new Map();
276
+ const scanOptionsFor = (localPath) => {
277
+ if (!designSystemEnabled || !localPath) return baseScanOptions;
278
+ const designSystem = loadDesignSystemForTarget(localPath, { cache: designSystemCache });
279
+ return designSystem ? { ...baseScanOptions, designSystem } : baseScanOptions;
280
+ };
210
281
  const targets = args.filter(a => !a.startsWith('--'));
211
282
 
212
283
  if (helpMode) { printUsage(); process.exit(0); }
@@ -214,7 +285,7 @@ async function detectCli() {
214
285
  let allFindings = [];
215
286
 
216
287
  if (!process.stdin.isTTY && targets.length === 0) {
217
- allFindings = await handleStdin(scanOptions);
288
+ allFindings = await handleStdin(scanOptionsFor);
218
289
  } else {
219
290
  const paths = targets.length > 0 ? targets : [process.cwd()];
220
291
  // file:// URLs get the same Puppeteer-rendered pass as http(s) — the
@@ -228,10 +299,17 @@ async function detectCli() {
228
299
  try {
229
300
  for (const target of paths) {
230
301
  if (urlRe.test(target)) {
302
+ // A file:// URL points at a local artifact, so its design system
303
+ // resolves from that file's project. A remote http(s) URL has no
304
+ // local project — it gets base options (no design system), never
305
+ // process.cwd()'s.
306
+ const urlOptions = /^file:/i.test(target)
307
+ ? scanOptionsFor(fileUrlToLocalPath(target))
308
+ : baseScanOptions;
231
309
  try {
232
310
  const scanner = browserDetector
233
- ? (url) => browserDetector.detectUrl(url, scanOptions)
234
- : (url) => detectUrl(url, scanOptions);
311
+ ? (url) => browserDetector.detectUrl(url, urlOptions)
312
+ : (url) => detectUrl(url, urlOptions);
235
313
  allFindings.push(...await scanner(target));
236
314
  } catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
237
315
  continue;
@@ -297,11 +375,14 @@ async function detectCli() {
297
375
 
298
376
  for (const file of files) {
299
377
  const ext = path.extname(file).toLowerCase();
378
+ // Each file resolves its own project design system (cached by root),
379
+ // so a scan spanning sibling projects applies the right rules per file.
380
+ const fileOptions = scanOptionsFor(file);
300
381
  let fileFindings;
301
382
  if (HTML_EXTENSIONS.has(ext)) {
302
- fileFindings = await detectHtml(file, scanOptions);
383
+ fileFindings = await detectHtml(file, fileOptions);
303
384
  } else {
304
- fileFindings = detectText(fs.readFileSync(file, 'utf-8'), file, scanOptions);
385
+ fileFindings = detectText(fs.readFileSync(file, 'utf-8'), file, fileOptions);
305
386
  }
306
387
  // Annotate findings with import context
307
388
  const importers = importedByMap.get(file);
@@ -316,10 +397,11 @@ async function detectCli() {
316
397
  } else if (stat.isFile()) {
317
398
  if (shouldIgnoreDetectionFile(resolved, process.cwd(), detectionConfig)) continue;
318
399
  const ext = path.extname(resolved).toLowerCase();
400
+ const fileOptions = scanOptionsFor(resolved);
319
401
  if (HTML_EXTENSIONS.has(ext)) {
320
- allFindings.push(...await detectHtml(resolved, scanOptions));
402
+ allFindings.push(...await detectHtml(resolved, fileOptions));
321
403
  } else {
322
- allFindings.push(...detectText(fs.readFileSync(resolved, 'utf-8'), resolved, scanOptions));
404
+ allFindings.push(...detectText(fs.readFileSync(resolved, 'utf-8'), resolved, fileOptions));
323
405
  }
324
406
  }
325
407
  }
@@ -330,12 +412,24 @@ async function detectCli() {
330
412
 
331
413
  allFindings = filterDetectionFindings(allFindings, detectionConfig);
332
414
  allFindings = filterByScopes(allFindings, scopes);
415
+ // --no-advisory drops advisory findings before any output or exit-code math.
416
+ if (noAdvisory) allFindings = allFindings.filter((f) => !isAdvisory(f));
417
+
418
+ // The exit code and failure count reflect non-advisory findings only. An
419
+ // advisory-only scan still prints its notes but exits 0 (a clean pass), so
420
+ // advisory rules never break CI or block automation.
421
+ const { primary, advisory } = partitionAdvisory(allFindings);
333
422
 
334
423
  if (allFindings.length > 0) {
335
424
  if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
336
- else if (quietMode) process.stderr.write(formatFindingSummary(allFindings.length) + '\n');
425
+ else if (quietMode) {
426
+ process.stderr.write(formatFindingSummary(primary.length) + '\n');
427
+ if (advisory.length > 0) {
428
+ process.stderr.write(dim(`${advisory.length} advisory note${advisory.length === 1 ? '' : 's'} (not counted).`) + '\n');
429
+ }
430
+ }
337
431
  else process.stderr.write(formatFindings(allFindings, false) + '\n');
338
- process.exit(2);
432
+ process.exit(primary.length > 0 ? 2 : 0);
339
433
  }
340
434
  if (jsonMode) process.stdout.write('[]\n');
341
435
  process.exit(0);
@@ -1,4 +1,5 @@
1
1
  import fs from 'node:fs';
2
+ import os from 'node:os';
2
3
  import path from 'node:path';
3
4
 
4
5
  import { finding } from './findings.mjs';
@@ -7,6 +8,11 @@ import { parseAnyColor, resolveLengthPx } from './rules/checks.mjs';
7
8
 
8
9
  const DESIGN_NAMES = ['DESIGN.md', 'Design.md', 'design.md'];
9
10
  const FALLBACK_DIRS = ['.agents/context', 'docs'];
11
+ // Files/dirs whose presence marks a directory as a project root. Mirrors the
12
+ // walk-up semantics of skill/scripts/context.mjs (`resolveProject`), which the
13
+ // CLI can't import (separate tree). `.git` and `package.json` are the common
14
+ // boundaries; `.impeccable` is our own project marker.
15
+ const PROJECT_ROOT_MARKERS = ['.git', 'package.json', '.impeccable'];
10
16
  const COLOR_CHANNEL_TOLERANCE = 6;
11
17
  const RADIUS_TOLERANCE_PX = 0.5;
12
18
  const FONT_SIZE_TOLERANCE_PX = 0.5;
@@ -469,6 +475,62 @@ function loadDesignSystemForCwd(cwd = process.cwd()) {
469
475
  });
470
476
  }
471
477
 
478
+ // Directory to begin the project-root walk from, given a scan target that may
479
+ // be a file or a directory (and may not exist yet).
480
+ function designSystemStartDir(targetPath, cwd = process.cwd()) {
481
+ const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
482
+ try {
483
+ return fs.statSync(abs).isDirectory() ? abs : path.dirname(abs);
484
+ } catch {
485
+ // Nonexistent path: treat an extension-bearing leaf as a file.
486
+ return path.extname(abs) ? path.dirname(abs) : abs;
487
+ }
488
+ }
489
+
490
+ // Walk up from `startDir` to the directory that governs the target's design
491
+ // system, mirroring skill/scripts/context.mjs's project-boundary semantics:
492
+ //
493
+ // - A directory carrying a DESIGN.md (directly or in a fallback dir) IS the
494
+ // design root — that's where the rules live.
495
+ // - A directory carrying a project marker (.git / package.json / .impeccable)
496
+ // but no DESIGN.md is a project BOUNDARY: the walk stops with no design
497
+ // system, so a sibling project never inherits a parent's or cwd's rules.
498
+ // - Reaching the home directory / filesystem root with neither means no
499
+ // design system at all — never process.cwd()'s.
500
+ //
501
+ // Returns { dir, hasDesign } for the stopping directory, or null when the walk
502
+ // runs out. This is the fix for cross-project contamination.
503
+ export function findDesignRoot(startDir) {
504
+ let dir = path.resolve(startDir);
505
+ const homeDir = path.resolve(os.homedir());
506
+ while (true) {
507
+ if (resolveDesignMdPath(dir)) return { dir, hasDesign: true };
508
+ if (PROJECT_ROOT_MARKERS.some((marker) => fs.existsSync(path.join(dir, marker)))) {
509
+ return { dir, hasDesign: false };
510
+ }
511
+ if (dir === homeDir) return null;
512
+ const parent = path.dirname(dir);
513
+ if (parent === dir) return null;
514
+ dir = parent;
515
+ }
516
+ }
517
+
518
+ // Resolve the design system that governs a specific scan target, by walking up
519
+ // from the target's own location — never process.cwd(). Scanning project B's
520
+ // files from inside project A applies B's DESIGN.md (or none), not A's.
521
+ //
522
+ // Pass a `cache` Map to memoize by resolved design root across a multi-file
523
+ // scan; a target with no design root above it resolves to null.
524
+ export function loadDesignSystemForTarget(targetPath, { cache, cwd = process.cwd() } = {}) {
525
+ const startDir = designSystemStartDir(targetPath, cwd);
526
+ const found = findDesignRoot(startDir);
527
+ const key = found ? `root:${found.dir}` : '\0none';
528
+ if (cache && cache.has(key)) return cache.get(key);
529
+ const loaded = found?.hasDesign ? loadDesignSystemForCwd(found.dir) : null;
530
+ if (cache) cache.set(key, loaded);
531
+ return loaded;
532
+ }
533
+
472
534
  function isAllowedFont(font, designSystem) {
473
535
  if (!font || GENERIC_FONTS.has(font)) return true;
474
536
  if (!designSystem?.hasFonts) return true;