Skip to content

The design language that makes your AI harness better at design.

JavaScript

Sync generated provider output

github-actions[bot]0330f61cef1c
diff --git a/.agents/skills/impeccable/scripts/detector/browser/injected/index.mjs b/.agents/skills/impeccable/scripts/detector/browser/injected/index.mjs
index febf7f297..76fc558e5 100644
--- a/.agents/skills/impeccable/scripts/detector/browser/injected/index.mjs
+++ b/.agents/skills/impeccable/scripts/detector/browser/injected/index.mjs
@@ -1228,14 +1228,17 @@ if (IS_BROWSER) {
isHidden: isElementHidden(el),
findings: findings.map(f => {
const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
+ const severity = f.severity || ap?.severity || 'warning';
return {
type: f.type || f.id,
category: ap ? ap.category : 'quality',
- severity: f.severity || ap?.severity || 'warning',
+ severity,
// Advisory findings (em-dash overuse, etc.) are surfaced but never
// treated as failures; carry the flag so the overlay/extension can
// render them with the mildest affordance and consumers can filter.
- advisory: (ap && ap.advisory === true) || f.advisory === true,
+ // Per-finding promotions override the registry default, so derive
+ // this strictly from the effective severity.
+ advisory: severity === 'advisory',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
@@ -1277,6 +1280,381 @@ if (IS_BROWSER) {
else groupMap.set(el, [...kept]);
}
+ function pseudoElementHostSelector(selector) {
+ const raw = String(selector || '');
+ const legacyNames = new Set(['before', 'after', 'first-letter', 'first-line']);
+ const isNameChar = char => /[a-zA-Z0-9_-]/.test(char || '');
+ const consumeFunction = (start) => {
+ let depth = 0;
+ let quote = '';
+ for (let i = start; i < raw.length; i += 1) {
+ const char = raw[i];
+ if (char === '\\') {
+ i += 1;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '(') depth += 1;
+ if (char === ')' && --depth === 0) return i + 1;
+ }
+ return raw.length;
+ };
+
+ let output = '';
+ let found = false;
+ for (let i = 0; i < raw.length;) {
+ const char = raw[i];
+ if (char === '\\') {
+ output += raw.slice(i, Math.min(raw.length, i + 2));
+ i += 2;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ const quote = char;
+ const start = i;
+ i += 1;
+ while (i < raw.length) {
+ if (raw[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ const value = raw[i];
+ i += 1;
+ if (value === quote) break;
+ }
+ output += raw.slice(start, i);
+ continue;
+ }
+ if (char !== ':') {
+ output += char;
+ i += 1;
+ continue;
+ }
+
+ let end = i + 1;
+ let isPseudoElement = false;
+ if (raw[end] === ':') {
+ end += 1;
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = end > nameStart;
+ } else {
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = legacyNames.has(raw.slice(nameStart, end).toLowerCase());
+ }
+ if (!isPseudoElement) {
+ output += char;
+ i += 1;
+ continue;
+ }
+ if (raw[end] === '(') end = consumeFunction(end);
+ found = true;
+ if (!output || /[\s>+~,]/.test(output[output.length - 1])) output += '*';
+ i = end;
+ }
+ if (!found) return null;
+ return output.trim().replace(/,\s*(?=,|$)/g, '');
+ }
+
+ function selectorNodesForLiveDom(root, selector) {
+ const raw = String(selector || '').trim();
+ if (!raw) return null;
+ const fallback = pseudoElementHostSelector(raw);
+ if (fallback == null) {
+ // An empty result from a valid full selector is authoritative. In
+ // particular, do not broaden inactive :hover/:focus/:not() rules to
+ // their host element by stripping pseudo-classes.
+ try { return Array.from(root.querySelectorAll(raw)); }
+ catch { return null; }
+ }
+
+ // Resolve pseudo-elements to their originating live elements. An attached
+ // pseudo-element (`.card::before`) belongs to the element before it, while
+ // a hostless pseudo-element after a combinator (`main > ::before`) belongs
+ // to a matching element at that position (`main > *`). Replacing every
+ // pseudo indiscriminately with an empty string leaves the latter as the
+ // invalid selector `main >` and makes absent hosts indistinguishable from
+ // selectors the DOM API cannot parse.
+ if (!fallback || /^[,\s]*$/.test(fallback)) return null;
+ try { return Array.from(root.querySelectorAll(fallback)); }
+ catch { return null; }
+ }
+
+ let containerProbeSequence = 0;
+
+ function isContainerCssRule(rule) {
+ return rule?.constructor?.name === 'CSSContainerRule'
+ || /^\s*@container\b/i.test(rule?.cssText || '');
+ }
+
+ function styleRuleAppliesToLiveMatches(rule, matches) {
+ const style = rule?.style;
+ if (!style || !matches?.length || typeof getComputedStyle !== 'function') return false;
+ const sequence = ++containerProbeSequence;
+ const property = `--impeccable-container-probe-${sequence}-${Math.random().toString(36).slice(2)}`;
+ const value = `impeccable-container-active-${sequence}`;
+ const previousValue = style.getPropertyValue(property);
+ const previousPriority = style.getPropertyPriority(property);
+ try {
+ style.setProperty(property, value, 'important');
+ } catch {
+ return false;
+ }
+
+ const pseudoElements = [...new Set(
+ String(rule.selectorText || '').match(/::[a-zA-Z-]+(?:\([^)]*\))?/g) || [],
+ )];
+ try {
+ return matches.some(el => [null, ...pseudoElements].some(pseudo => {
+ try {
+ const computed = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el);
+ return computed.getPropertyValue(property).trim() === value;
+ } catch {
+ return false;
+ }
+ }));
+ } finally {
+ if (previousValue) style.setProperty(property, previousValue, previousPriority);
+ else style.removeProperty(property);
+ }
+ }
+
+ function conditionalCssRuleIsActive(rule) {
+ const type = Number(rule?.type);
+ const constructorName = rule?.constructor?.name || '';
+ if (constructorName === 'CSSMediaRule' || type === 4) {
+ const condition = rule.conditionText || rule.media?.mediaText || '';
+ if (!condition || typeof window.matchMedia !== 'function') return true;
+ try { return window.matchMedia(condition).matches; }
+ catch { return true; }
+ }
+ if (constructorName === 'CSSSupportsRule' || type === 12) {
+ const condition = rule.conditionText || '';
+ if (!condition || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return true;
+ try { return CSS.supports(condition); }
+ catch { return true; }
+ }
+ return true;
+ }
+
+ function splitCssCommaList(value) {
+ const parts = [];
+ let current = '';
+ let quote = '';
+ let escaped = false;
+ for (const char of String(value || '')) {
+ if (escaped) {
+ current += char;
+ escaped = false;
+ continue;
+ }
+ if (char === '\\') {
+ current += char;
+ escaped = true;
+ continue;
+ }
+ if (quote) {
+ current += char;
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ current += char;
+ continue;
+ }
+ if (char === ',') {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+ return parts;
+ }
+
+ function normalizeAnimationName(value) {
+ const name = String(value || '').trim();
+ if (name.length >= 2 && name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) {
+ return name.slice(1, -1);
+ }
+ return name;
+ }
+
+ function animationNamesDeclaredByRule(rule) {
+ const style = rule?.style;
+ if (!style) return [];
+ let value = '';
+ try {
+ value = style.animationName
+ || style.getPropertyValue?.('animation-name')
+ || style.webkitAnimationName
+ || style.getPropertyValue?.('-webkit-animation-name')
+ || '';
+ } catch {
+ return [];
+ }
+ return splitCssCommaList(value)
+ .map(normalizeAnimationName)
+ .filter(name => name && name.toLowerCase() !== 'none');
+ }
+
+ function keyframesRuleName(rule, cssText) {
+ const constructorName = rule?.constructor?.name || '';
+ const type = Number(rule?.type);
+ const isKeyframes = constructorName === 'CSSKeyframesRule'
+ || constructorName === 'WebKitCSSKeyframesRule'
+ || type === 7
+ || /^\s*@(?:-webkit-)?keyframes\b/i.test(cssText);
+ if (!isKeyframes) return '';
+ const match = String(cssText || '').match(/^\s*@(?:-webkit-)?keyframes\s+([^\s{]+)/i);
+ return normalizeAnimationName(rule?.name || match?.[1] || '');
+ }
+
+ function cssPropertyName(property) {
+ if (property.startsWith('--')) return property;
+ return property.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
+ }
+
+ function resolvedAnimationKeyframes(candidateNames) {
+ if (typeof document.getAnimations !== 'function') return null;
+ let animations;
+ try { animations = document.getAnimations(); }
+ catch { return null; }
+
+ const resolved = new Map();
+ const metadata = new Set(['offset', 'computedOffset', 'easing', 'composite']);
+ for (const animation of animations) {
+ const name = normalizeAnimationName(animation?.animationName || '');
+ if (!name || !candidateNames.has(name) || resolved.has(name)) continue;
+ let frames;
+ try { frames = animation.effect?.getKeyframes?.() || []; }
+ catch { continue; }
+ const blocks = [];
+ for (const frame of frames) {
+ const rawOffset = Number.isFinite(frame.computedOffset) ? frame.computedOffset : frame.offset;
+ if (!Number.isFinite(rawOffset)) continue;
+ const offset = Math.round(rawOffset * 1000000) / 10000;
+ const declarations = Object.entries(frame)
+ .filter(([property, value]) => !metadata.has(property) && value != null && value !== '')
+ .map(([property, value]) => `${cssPropertyName(property)}: ${value};`);
+ const easing = String(frame.easing || '').trim();
+ if (easing && easing.toLowerCase() !== 'linear') {
+ declarations.push(`animation-timing-function: ${easing};`);
+ }
+ if (declarations.length === 0) continue;
+ blocks.push(`${offset}% { ${declarations.join(' ')} }`);
+ }
+ if (blocks.length > 0) resolved.set(name, `@keyframes ${name} { ${blocks.join(' ')} }`);
+ }
+ return resolved;
+ }
+
+ // Read CSS that is absent from document.outerHTML. Inline <style> blocks are
+ // already present in the HTML pattern corpus, so limit this walk to linked
+ // stylesheets. Flatten grouping rules so each declaration keeps its selector,
+ // and admit only selector rules that target the live DOM. That prevents
+ // unused utilities from feeding both selector-scoped and page-level checks.
+ // Same-origin CSS and readable CORS sheets participate; browser security
+ // exceptions for cross-origin sheets are expected and skipped.
+ function linkedStylesheetText() {
+ const parts = [];
+ const seen = new Set();
+ const animationNames = new Set();
+ const keyframeCandidates = new Map();
+ const appendRules = (rules, requiresAppliedMatch = false) => {
+ for (const rule of rules) {
+ if (rule.styleSheet) {
+ appendSheet(rule.styleSheet);
+ continue;
+ }
+ const cssText = rule.cssText || '';
+ if (rule.selectorText) {
+ const matches = selectorNodesForLiveDom(document, rule.selectorText);
+ // Only declarations with a resolvable live host enter the corpus.
+ // Unresolvable selectors are uncertain, not evidence that a pattern
+ // rendered, and retaining them would leak unused CSS into findings.
+ if (
+ matches?.length > 0
+ && (!requiresAppliedMatch || styleRuleAppliesToLiveMatches(rule, matches))
+ ) {
+ parts.push(cssText);
+ for (const name of animationNamesDeclaredByRule(rule)) animationNames.add(name);
+ }
+ continue;
+ }
+ let nested = [];
+ let hasNestedRules = false;
+ try {
+ const ruleList = rule.cssRules;
+ hasNestedRules = ruleList != null;
+ nested = Array.from(ruleList || []);
+ } catch {
+ continue;
+ }
+ const keyframesName = keyframesRuleName(rule, cssText);
+ if (keyframesName) {
+ // Keyframes do not merge: when a name is defined more than once, the
+ // later effective definition replaces the earlier one.
+ keyframeCandidates.set(keyframesName, {
+ name: keyframesName,
+ cssText,
+ });
+ continue;
+ }
+ if (hasNestedRules) {
+ if (!conditionalCssRuleIsActive(rule)) continue;
+ appendRules(nested, requiresAppliedMatch || isContainerCssRule(rule));
+ continue;
+ }
+ // Other selector-less leaf at-rules cannot be tied to a rendered node.
+ }
+ };
+ const appendSheet = (sheet) => {
+ if (!sheet || seen.has(sheet)) return;
+ seen.add(sheet);
+ let rules;
+ try { rules = Array.from(sheet.cssRules || sheet.rules || []); }
+ catch { return; }
+ appendRules(rules);
+ };
+ let sheets;
+ try { sheets = Array.from(document.styleSheets || []); }
+ catch { return ''; }
+ for (const sheet of sheets) {
+ const owner = sheet.ownerNode;
+ if (owner?.tagName?.toLowerCase() !== 'link') continue;
+ if (!/\bstylesheet\b/i.test(owner.getAttribute?.('rel') || '')) continue;
+ appendSheet(sheet);
+ }
+ // Motion checks need the effective body of a live animation's keyframes.
+ // Let the browser resolve duplicate names across source order, imports,
+ // conditional groups, and cascade layers, then serialize those computed
+ // frames back into the pattern corpus. Browsers also make container-nested
+ // keyframes globally available, so lexical grouping is not a reliable
+ // activity signal. When the Web Animations API is unavailable, fall back to
+ // the last source-order definition referenced by a retained linked rule.
+ const resolvedKeyframes = resolvedAnimationKeyframes(new Set(keyframeCandidates.keys()));
+ if (resolvedKeyframes) {
+ parts.push(...resolvedKeyframes.values());
+ } else {
+ for (const candidate of keyframeCandidates.values()) {
+ if (!animationNames.has(candidate.name)) continue;
+ parts.push(candidate.cssText);
+ }
+ }
+ return parts.join('\n');
+ }
+
function browserFindingsFromMap(groupMap) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
@@ -1650,18 +2028,16 @@ if (IS_BROWSER) {
// (the CSS ships here, but the pattern never renders — the live DOM is
// ground truth in the browser), and a match under a data-impeccable-ignore
// ancestor is waived. Selector-less findings stay page-level.
- const scopedHtmlFindings = checkHtmlPatterns(docClone.outerHTML).filter(f => {
+ const html = docClone.outerHTML;
+ const corpora = buildHtmlPatternCorpora(html);
+ const linkedCss = linkedStylesheetText();
+ if (linkedCss) corpora.styleText += `\n${linkedCss}`;
+ const scopedHtmlFindings = checkHtmlPatterns(html, corpora).filter(f => {
if (!f.selector) return true;
- const query = String(f.selector).replace(/::?[a-zA-Z-]+(\([^)]*\))?/g, '').trim().replace(/,\s*(?=,|$)/g, '');
- if (!query || /^[,\s]*$/.test(query)) return true;
- let matches;
- try {
- matches = document.querySelectorAll(query);
- } catch {
- return true;
- }
+ const matches = selectorNodesForLiveDom(document, f.selector);
+ if (!matches) return false;
if (matches.length === 0) return false;
- return [...matches].some(el => !scopedIgnoreActive(el, f.id));
+ return matches.some(el => !scopedIgnoreActive(el, f.id));
});
if (scopedHtmlFindings.length > 0) {
const mapped = scopedHtmlFindings.map(f => {
diff --git a/.agents/skills/impeccable/scripts/detector/cli/main.mjs b/.agents/skills/impeccable/scripts/detector/cli/main.mjs
index 4476d04f1..3451d6c6b 100644
--- a/.agents/skills/impeccable/scripts/detector/cli/main.mjs
+++ b/.agents/skills/impeccable/scripts/detector/cli/main.mjs
@@ -37,13 +37,30 @@ function fileUrlToLocalPath(url) {
}
}
+const URL_TARGET_RE = /^(?:https?|file):\/\//i;
+
+// Some agent runners hand a shell-ready URL list to Node as one argv value.
+// A browser accepts the spaces as part of one encoded URL, producing a
+// plausible scan attributed to a bogus joined path. Expand only when every
+// whitespace-delimited token is independently a URL, preserving ordinary
+// filesystem paths that contain spaces.
+function expandJoinedUrlTargets(targets) {
+ return targets.flatMap((target) => {
+ if (!/\s/.test(target)) return [target];
+ const parts = target.trim().split(/\s+/).filter(Boolean);
+ return parts.length > 1 && parts.every(part => URL_TARGET_RE.test(part))
+ ? parts
+ : [target];
+ });
+}
+
// Advisory findings are detected but never treated as failures: they list in a
// separate, visually dimmed section, are excluded from the failure count that
// drives the exit code, and carry `"advisory": true` in JSON so consumers can
// filter. Every advisory finding carries the flag (stamped by the registry via
// findings.mjs).
function isAdvisory(finding) {
- return finding && finding.advisory === true;
+ return Boolean(finding && (finding.advisory === true || finding.severity === 'advisory'));
}
function partitionAdvisory(findings) {
@@ -168,6 +185,10 @@ Advisory findings:
counted as failures and never changing the exit code. They stay out of the
failure count so they never block automation. --no-advisory hides them.
+Output streams:
+ Human-readable findings go to stderr so stdout stays available for structured
+ output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.
+
Project config:
Respects .impeccable/config.json and .impeccable/config.local.json detector
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
@@ -185,7 +206,7 @@ Detection modes:
HTML files Static HTML/CSS analysis (default, catches linked CSS)
Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)
URLs Puppeteer full browser rendering (auto-detected;
- http(s):// and file:// URLs)
+ http(s):// and file:// URLs; accessible linked CSS included)
Examples:
impeccable detect src/
@@ -283,7 +304,7 @@ async function detectCli() {
const designSystem = loadDesignSystemForTarget(localPath, { cache: designSystemCache });
return designSystem ? { ...baseScanOptions, designSystem } : baseScanOptions;
};
- const targets = args.filter(a => !a.startsWith('--'));
+ const targets = expandJoinedUrlTargets(args.filter(a => !a.startsWith('--')));
if (helpMode) { printUsage(); process.exit(0); }
@@ -297,13 +318,12 @@ async function detectCli() {
// real cascade, real computed styles, real layout. Callers that want a
// browser-grade scan of a local artifact can pass file:///abs/path.html
// instead of the bare path (which stays on the static engine).
- const urlRe = /^(?:https?|file):\/\//i;
- const urlTargetCount = paths.filter(target => urlRe.test(target)).length;
+ const urlTargetCount = paths.filter(target => URL_TARGET_RE.test(target)).length;
const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
try {
for (const target of paths) {
- if (urlRe.test(target)) {
+ if (URL_TARGET_RE.test(target)) {
// A file:// URL points at a local artifact, so its design system
// resolves from that file's project. A remote http(s) URL has no
// local project — it gets base options (no design system), never
diff --git a/.agents/skills/impeccable/scripts/detector/detect-antipatterns-browser.js b/.agents/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
index e6899f569..460ffb45b 100644
--- a/.agents/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
+++ b/.agents/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
@@ -358,7 +358,7 @@ const ANTIPATTERNS = [
// rather than a failure. It fires only on the AI saturation pattern, not on
// ordinary prose. Advisory findings are surfaced separately, never counted
// as failures, and skipped by the design hook unless a project opts in.
- advisory: true,
+ severity: 'advisory',
name: 'Em-dash overuse',
description:
'Em-dash saturation in body copy is an AI cadence tell. Advisory only: humans use em-dashes legitimately, so this fires only on saturation — at least 8 em-dashes (— or --) at a density near one per 500 characters of body text — never on a long article that uses a few. Prefer commas, colons, periods, or parentheses.',
@@ -1961,7 +1961,10 @@ function enclosingCssSelector(cssText, index) {
// `{` belongs to some other selector.
const closeBeforeIndex = cssText.lastIndexOf('}', index);
if (closeBeforeIndex > open) return null;
- const prevClose = Math.max(cssText.lastIndexOf('}', open - 1), cssText.lastIndexOf(';', open - 1));
+ // Ignore delimiters inside comments when locating the previous declaration.
+ // Keeping comment length intact preserves indices into the original source.
+ const beforeOpen = cssText.slice(0, open).replace(/\/\*[\s\S]*?\*\//g, comment => ' '.repeat(comment.length));
+ const prevClose = Math.max(beforeOpen.lastIndexOf('}'), beforeOpen.lastIndexOf(';'));
const raw = cssText.slice(prevClose + 1, open).replace(/\/\*[\s\S]*?\*\//g, '').trim().replace(/\s+/g, ' ');
if (!raw || raw.startsWith('@') || /^\d/.test(raw) || /[{}<]/.test(raw)) return null;
// Keyframe steps: percentage steps fail the digit test above, but `from`
@@ -5293,14 +5296,17 @@ function checkTypography() {
}
if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
+ // Report the actual primary face: the uniquely most-used family. The old
+ // 15% threshold labeled secondary faces as primary (e.g. an 82/18 split).
+ const ranked = [...fontUsage.entries()].sort((a, b) => b[1] - a[1]);
+ const [primary] = ranked;
+ const tied = ranked[1]?.[1] === primary?.[1];
+ if (primary && !tied) {
+ const [font, count] = primary;
const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ if (OVERUSED_FONTS.has(font) && !isBrandFontOnOwnDomain(font)) {
+ findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ }
}
}
@@ -8126,14 +8132,17 @@ if (IS_BROWSER) {
isHidden: isElementHidden(el),
findings: findings.map(f => {
const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
+ const severity = f.severity || ap?.severity || 'warning';
return {
type: f.type || f.id,
category: ap ? ap.category : 'quality',
- severity: f.severity || ap?.severity || 'warning',
+ severity,
// Advisory findings (em-dash overuse, etc.) are surfaced but never
// treated as failures; carry the flag so the overlay/extension can
// render them with the mildest affordance and consumers can filter.
- advisory: (ap && ap.advisory === true) || f.advisory === true,
+ // Per-finding promotions override the registry default, so derive
+ // this strictly from the effective severity.
+ advisory: severity === 'advisory',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
@@ -8175,6 +8184,381 @@ if (IS_BROWSER) {
else groupMap.set(el, [...kept]);
}
+ function pseudoElementHostSelector(selector) {
+ const raw = String(selector || '');
+ const legacyNames = new Set(['before', 'after', 'first-letter', 'first-line']);
+ const isNameChar = char => /[a-zA-Z0-9_-]/.test(char || '');
+ const consumeFunction = (start) => {
+ let depth = 0;
+ let quote = '';
+ for (let i = start; i < raw.length; i += 1) {
+ const char = raw[i];
+ if (char === '\\') {
+ i += 1;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '(') depth += 1;
+ if (char === ')' && --depth === 0) return i + 1;
+ }
+ return raw.length;
+ };
+
+ let output = '';
+ let found = false;
+ for (let i = 0; i < raw.length;) {
+ const char = raw[i];
+ if (char === '\\') {
+ output += raw.slice(i, Math.min(raw.length, i + 2));
+ i += 2;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ const quote = char;
+ const start = i;
+ i += 1;
+ while (i < raw.length) {
+ if (raw[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ const value = raw[i];
+ i += 1;
+ if (value === quote) break;
+ }
+ output += raw.slice(start, i);
+ continue;
+ }
+ if (char !== ':') {
+ output += char;
+ i += 1;
+ continue;
+ }
+
+ let end = i + 1;
+ let isPseudoElement = false;
+ if (raw[end] === ':') {
+ end += 1;
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = end > nameStart;
+ } else {
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = legacyNames.has(raw.slice(nameStart, end).toLowerCase());
+ }
+ if (!isPseudoElement) {
+ output += char;
+ i += 1;
+ continue;
+ }
+ if (raw[end] === '(') end = consumeFunction(end);
+ found = true;
+ if (!output || /[\s>+~,]/.test(output[output.length - 1])) output += '*';
+ i = end;
+ }
+ if (!found) return null;
+ return output.trim().replace(/,\s*(?=,|$)/g, '');
+ }
+
+ function selectorNodesForLiveDom(root, selector) {
+ const raw = String(selector || '').trim();
+ if (!raw) return null;
+ const fallback = pseudoElementHostSelector(raw);
+ if (fallback == null) {
+ // An empty result from a valid full selector is authoritative. In
+ // particular, do not broaden inactive :hover/:focus/:not() rules to
+ // their host element by stripping pseudo-classes.
+ try { return Array.from(root.querySelectorAll(raw)); }
+ catch { return null; }
+ }
+
+ // Resolve pseudo-elements to their originating live elements. An attached
+ // pseudo-element (`.card::before`) belongs to the element before it, while
+ // a hostless pseudo-element after a combinator (`main > ::before`) belongs
+ // to a matching element at that position (`main > *`). Replacing every
+ // pseudo indiscriminately with an empty string leaves the latter as the
+ // invalid selector `main >` and makes absent hosts indistinguishable from
+ // selectors the DOM API cannot parse.
+ if (!fallback || /^[,\s]*$/.test(fallback)) return null;
+ try { return Array.from(root.querySelectorAll(fallback)); }
+ catch { return null; }
+ }
+
+ let containerProbeSequence = 0;
+
+ function isContainerCssRule(rule) {
+ return rule?.constructor?.name === 'CSSContainerRule'
+ || /^\s*@container\b/i.test(rule?.cssText || '');
+ }
+
+ function styleRuleAppliesToLiveMatches(rule, matches) {
+ const style = rule?.style;
+ if (!style || !matches?.length || typeof getComputedStyle !== 'function') return false;
+ const sequence = ++containerProbeSequence;
+ const property = `--impeccable-container-probe-${sequence}-${Math.random().toString(36).slice(2)}`;
+ const value = `impeccable-container-active-${sequence}`;
+ const previousValue = style.getPropertyValue(property);
+ const previousPriority = style.getPropertyPriority(property);
+ try {
+ style.setProperty(property, value, 'important');
+ } catch {
+ return false;
+ }
+
+ const pseudoElements = [...new Set(
+ String(rule.selectorText || '').match(/::[a-zA-Z-]+(?:\([^)]*\))?/g) || [],
+ )];
+ try {
+ return matches.some(el => [null, ...pseudoElements].some(pseudo => {
+ try {
+ const computed = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el);
+ return computed.getPropertyValue(property).trim() === value;
+ } catch {
+ return false;
+ }
+ }));
+ } finally {
+ if (previousValue) style.setProperty(property, previousValue, previousPriority);
+ else style.removeProperty(property);
+ }
+ }
+
+ function conditionalCssRuleIsActive(rule) {
+ const type = Number(rule?.type);
+ const constructorName = rule?.constructor?.name || '';
+ if (constructorName === 'CSSMediaRule' || type === 4) {
+ const condition = rule.conditionText || rule.media?.mediaText || '';
+ if (!condition || typeof window.matchMedia !== 'function') return true;
+ try { return window.matchMedia(condition).matches; }
+ catch { return true; }
+ }
+ if (constructorName === 'CSSSupportsRule' || type === 12) {
+ const condition = rule.conditionText || '';
+ if (!condition || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return true;
+ try { return CSS.supports(condition); }
+ catch { return true; }
+ }
+ return true;
+ }
+
+ function splitCssCommaList(value) {
+ const parts = [];
+ let current = '';
+ let quote = '';
+ let escaped = false;
+ for (const char of String(value || '')) {
+ if (escaped) {
+ current += char;
+ escaped = false;
+ continue;
+ }
+ if (char === '\\') {
+ current += char;
+ escaped = true;
+ continue;
+ }
+ if (quote) {
+ current += char;
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ current += char;
+ continue;
+ }
+ if (char === ',') {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+ return parts;
+ }
+
+ function normalizeAnimationName(value) {
+ const name = String(value || '').trim();
+ if (name.length >= 2 && name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) {
+ return name.slice(1, -1);
+ }
+ return name;
+ }
+
+ function animationNamesDeclaredByRule(rule) {
+ const style = rule?.style;
+ if (!style) return [];
+ let value = '';
+ try {
+ value = style.animationName
+ || style.getPropertyValue?.('animation-name')
+ || style.webkitAnimationName
+ || style.getPropertyValue?.('-webkit-animation-name')
+ || '';
+ } catch {
+ return [];
+ }
+ return splitCssCommaList(value)
+ .map(normalizeAnimationName)
+ .filter(name => name && name.toLowerCase() !== 'none');
+ }
+
+ function keyframesRuleName(rule, cssText) {
+ const constructorName = rule?.constructor?.name || '';
+ const type = Number(rule?.type);
+ const isKeyframes = constructorName === 'CSSKeyframesRule'
+ || constructorName === 'WebKitCSSKeyframesRule'
+ || type === 7
+ || /^\s*@(?:-webkit-)?keyframes\b/i.test(cssText);
+ if (!isKeyframes) return '';
+ const match = String(cssText || '').match(/^\s*@(?:-webkit-)?keyframes\s+([^\s{]+)/i);
+ return normalizeAnimationName(rule?.name || match?.[1] || '');
+ }
+
+ function cssPropertyName(property) {
+ if (property.startsWith('--')) return property;
+ return property.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
+ }
+
+ function resolvedAnimationKeyframes(candidateNames) {
+ if (typeof document.getAnimations !== 'function') return null;
+ let animations;
+ try { animations = document.getAnimations(); }
+ catch { return null; }
+
+ const resolved = new Map();
+ const metadata = new Set(['offset', 'computedOffset', 'easing', 'composite']);
+ for (const animation of animations) {
+ const name = normalizeAnimationName(animation?.animationName || '');
+ if (!name || !candidateNames.has(name) || resolved.has(name)) continue;
+ let frames;
+ try { frames = animation.effect?.getKeyframes?.() || []; }
+ catch { continue; }
+ const blocks = [];
+ for (const frame of frames) {
+ const rawOffset = Number.isFinite(frame.computedOffset) ? frame.computedOffset : frame.offset;
+ if (!Number.isFinite(rawOffset)) continue;
+ const offset = Math.round(rawOffset * 1000000) / 10000;
+ const declarations = Object.entries(frame)
+ .filter(([property, value]) => !metadata.has(property) && value != null && value !== '')
+ .map(([property, value]) => `${cssPropertyName(property)}: ${value};`);
+ const easing = String(frame.easing || '').trim();
+ if (easing && easing.toLowerCase() !== 'linear') {
+ declarations.push(`animation-timing-function: ${easing};`);
+ }
+ if (declarations.length === 0) continue;
+ blocks.push(`${offset}% { ${declarations.join(' ')} }`);
+ }
+ if (blocks.length > 0) resolved.set(name, `@keyframes ${name} { ${blocks.join(' ')} }`);
+ }
+ return resolved;
+ }
+
+ // Read CSS that is absent from document.outerHTML. Inline <style> blocks are
+ // already present in the HTML pattern corpus, so limit this walk to linked
+ // stylesheets. Flatten grouping rules so each declaration keeps its selector,
+ // and admit only selector rules that target the live DOM. That prevents
+ // unused utilities from feeding both selector-scoped and page-level checks.
+ // Same-origin CSS and readable CORS sheets participate; browser security
+ // exceptions for cross-origin sheets are expected and skipped.
+ function linkedStylesheetText() {
+ const parts = [];
+ const seen = new Set();
+ const animationNames = new Set();
+ const keyframeCandidates = new Map();
+ const appendRules = (rules, requiresAppliedMatch = false) => {
+ for (const rule of rules) {
+ if (rule.styleSheet) {
+ appendSheet(rule.styleSheet);
+ continue;
+ }
+ const cssText = rule.cssText || '';
+ if (rule.selectorText) {
+ const matches = selectorNodesForLiveDom(document, rule.selectorText);
+ // Only declarations with a resolvable live host enter the corpus.
+ // Unresolvable selectors are uncertain, not evidence that a pattern
+ // rendered, and retaining them would leak unused CSS into findings.
+ if (
+ matches?.length > 0
+ && (!requiresAppliedMatch || styleRuleAppliesToLiveMatches(rule, matches))
+ ) {
+ parts.push(cssText);
+ for (const name of animationNamesDeclaredByRule(rule)) animationNames.add(name);
+ }
+ continue;
+ }
+ let nested = [];
+ let hasNestedRules = false;
+ try {
+ const ruleList = rule.cssRules;
+ hasNestedRules = ruleList != null;
+ nested = Array.from(ruleList || []);
+ } catch {
+ continue;
+ }
+ const keyframesName = keyframesRuleName(rule, cssText);
+ if (keyframesName) {
+ // Keyframes do not merge: when a name is defined more than once, the
+ // later effective definition replaces the earlier one.
+ keyframeCandidates.set(keyframesName, {
+ name: keyframesName,
+ cssText,
+ });
+ continue;
+ }
+ if (hasNestedRules) {
+ if (!conditionalCssRuleIsActive(rule)) continue;
+ appendRules(nested, requiresAppliedMatch || isContainerCssRule(rule));
+ continue;
+ }
+ // Other selector-less leaf at-rules cannot be tied to a rendered node.
+ }
+ };
+ const appendSheet = (sheet) => {
+ if (!sheet || seen.has(sheet)) return;
+ seen.add(sheet);
+ let rules;
+ try { rules = Array.from(sheet.cssRules || sheet.rules || []); }
+ catch { return; }
+ appendRules(rules);
+ };
+ let sheets;
+ try { sheets = Array.from(document.styleSheets || []); }
+ catch { return ''; }
+ for (const sheet of sheets) {
+ const owner = sheet.ownerNode;
+ if (owner?.tagName?.toLowerCase() !== 'link') continue;
+ if (!/\bstylesheet\b/i.test(owner.getAttribute?.('rel') || '')) continue;
+ appendSheet(sheet);
+ }
+ // Motion checks need the effective body of a live animation's keyframes.
+ // Let the browser resolve duplicate names across source order, imports,
+ // conditional groups, and cascade layers, then serialize those computed
+ // frames back into the pattern corpus. Browsers also make container-nested
+ // keyframes globally available, so lexical grouping is not a reliable
+ // activity signal. When the Web Animations API is unavailable, fall back to
+ // the last source-order definition referenced by a retained linked rule.
+ const resolvedKeyframes = resolvedAnimationKeyframes(new Set(keyframeCandidates.keys()));
+ if (resolvedKeyframes) {
+ parts.push(...resolvedKeyframes.values());
+ } else {
+ for (const candidate of keyframeCandidates.values()) {
+ if (!animationNames.has(candidate.name)) continue;
+ parts.push(candidate.cssText);
+ }
+ }
+ return parts.join('\n');
+ }
+
function browserFindingsFromMap(groupMap) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
@@ -8548,18 +8932,16 @@ if (IS_BROWSER) {
// (the CSS ships here, but the pattern never renders — the live DOM is
// ground truth in the browser), and a match under a data-impeccable-ignore
// ancestor is waived. Selector-less findings stay page-level.
- const scopedHtmlFindings = checkHtmlPatterns(docClone.outerHTML).filter(f => {
+ const html = docClone.outerHTML;
+ const corpora = buildHtmlPatternCorpora(html);
+ const linkedCss = linkedStylesheetText();
+ if (linkedCss) corpora.styleText += `\n${linkedCss}`;
+ const scopedHtmlFindings = checkHtmlPatterns(html, corpora).filter(f => {
if (!f.selector) return true;
- const query = String(f.selector).replace(/::?[a-zA-Z-]+(\([^)]*\))?/g, '').trim().replace(/,\s*(?=,|$)/g, '');
- if (!query || /^[,\s]*$/.test(query)) return true;
- let matches;
- try {
- matches = document.querySelectorAll(query);
- } catch {
- return true;
- }
+ const matches = selectorNodesForLiveDom(document, f.selector);
+ if (!matches) return false;
if (matches.length === 0) return false;
- return [...matches].some(el => !scopedIgnoreActive(el, f.id));
+ return matches.some(el => !scopedIgnoreActive(el, f.id));
});
if (scopedHtmlFindings.length > 0) {
const mapped = scopedHtmlFindings.map(f => {
diff --git a/.agents/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs b/.agents/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
index f3ff43c84..ac4bd0a7c 100644
--- a/.agents/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
+++ b/.agents/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
@@ -2,7 +2,7 @@ import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { finding } from '../../findings.mjs';
+import { deriveAdvisoryFlag, finding } from '../../findings.mjs';
import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
import { checkContentHiddenAtRest } from '../../rules/checks.mjs';
@@ -394,7 +394,7 @@ async function detectUrl(rawUrl, options = {}) {
// Per-finding severity promotion (e.g. hero-region pulsing dot)
// overrides the registry default carried by finding().
if (f.severity && f.severity !== item.severity) item.severity = f.severity;
- return item;
+ return deriveAdvisoryFlag(item);
});
}
diff --git a/.agents/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs b/.agents/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
index 84e6ab1f5..dac6939b0 100644
--- a/.agents/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
+++ b/.agents/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
@@ -9,7 +9,7 @@ import {
} from '../../design-system.mjs';
import { isFullPage } from '../../shared/page.mjs';
import { applyInlineIgnores } from '../../shared/inline-ignores.mjs';
-import { finding } from '../../findings.mjs';
+import { deriveAdvisoryFlag, finding } from '../../findings.mjs';
import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import {
checkElementBorders,
@@ -257,7 +257,7 @@ async function detectHtml(filePath, options = {}) {
// severity (e.g. a pulsing dot inside a header/nav landmark) that
// overrides the registry default.
if (f.severity) item.severity = f.severity;
- findings.push(item);
+ findings.push(deriveAdvisoryFlag(item));
}
// Text-content analyzers (em-dash overuse, marketing buzzwords,
// numbered section markers, aphoristic cadence) live in the regex
diff --git a/.agents/skills/impeccable/scripts/detector/findings.mjs b/.agents/skills/impeccable/scripts/detector/findings.mjs
index fa98dd935..ae7e134f9 100644
--- a/.agents/skills/impeccable/scripts/detector/findings.mjs
+++ b/.agents/skills/impeccable/scripts/detector/findings.mjs
@@ -4,6 +4,12 @@ function getAP(id) {
return getAntipattern(id);
}
+function deriveAdvisoryFlag(item) {
+ if (item.severity === 'advisory') item.advisory = true;
+ else delete item.advisory;
+ return item;
+}
+
function finding(id, filePath, snippet, line = 0) {
const ap = getAP(id);
const base = { antipattern: id, name: ap.name, description: ap.description, severity: ap.severity || 'warning', category: ap.category || null, file: filePath, line, snippet };
@@ -11,8 +17,7 @@ function finding(id, filePath, snippet, line = 0) {
// failures. Carry the flag on the finding so every consumer (CLI, JSON, hook)
// can partition without a registry lookup. Only stamped when true to keep the
// finding shape stable for the vast majority of rules.
- if (ap.advisory === true) base.advisory = true;
- return base;
+ return deriveAdvisoryFlag(base);
}
-export { getAP, finding };
+export { getAP, finding, deriveAdvisoryFlag };
diff --git a/.agents/skills/impeccable/scripts/detector/registry/antipatterns.mjs b/.agents/skills/impeccable/scripts/detector/registry/antipatterns.mjs
index 945307783..7c692c79a 100644
--- a/.agents/skills/impeccable/scripts/detector/registry/antipatterns.mjs
+++ b/.agents/skills/impeccable/scripts/detector/registry/antipatterns.mjs
@@ -233,7 +233,7 @@ const ANTIPATTERNS = [
// rather than a failure. It fires only on the AI saturation pattern, not on
// ordinary prose. Advisory findings are surfaced separately, never counted
// as failures, and skipped by the design hook unless a project opts in.
- advisory: true,
+ severity: 'advisory',
name: 'Em-dash overuse',
description:
'Em-dash saturation in body copy is an AI cadence tell. Advisory only: humans use em-dashes legitimately, so this fires only on saturation — at least 8 em-dashes (— or --) at a density near one per 500 characters of body text — never on a long article that uses a few. Prefer commas, colons, periods, or parentheses.',
@@ -588,9 +588,10 @@ function getAntipattern(id) {
// Advisory rules are detected and reported, but never treated as failures:
// the CLI lists them under a separate "Advisory" section, they do not affect
// exit codes or the failure count, and the design hook skips them by default.
-// The set is derived from the registry so a rule only needs `advisory: true`.
+// `severity` is the canonical registry field. The runtime finding serializer
+// derives its `advisory: true` compatibility/output flag from this set.
const ADVISORY_RULE_IDS = new Set(
- ANTIPATTERNS.filter(rule => rule.advisory === true).map(rule => rule.id),
+ ANTIPATTERNS.filter(rule => rule.severity === 'advisory').map(rule => rule.id),
);
function isAdvisoryRule(id) {
diff --git a/.agents/skills/impeccable/scripts/detector/rules/checks.mjs b/.agents/skills/impeccable/scripts/detector/rules/checks.mjs
index 579e1c12e..a24631ce9 100644
--- a/.agents/skills/impeccable/scripts/detector/rules/checks.mjs
+++ b/.agents/skills/impeccable/scripts/detector/rules/checks.mjs
@@ -688,7 +688,10 @@ function enclosingCssSelector(cssText, index) {
// `{` belongs to some other selector.
const closeBeforeIndex = cssText.lastIndexOf('}', index);
if (closeBeforeIndex > open) return null;
- const prevClose = Math.max(cssText.lastIndexOf('}', open - 1), cssText.lastIndexOf(';', open - 1));
+ // Ignore delimiters inside comments when locating the previous declaration.
+ // Keeping comment length intact preserves indices into the original source.
+ const beforeOpen = cssText.slice(0, open).replace(/\/\*[\s\S]*?\*\//g, comment => ' '.repeat(comment.length));
+ const prevClose = Math.max(beforeOpen.lastIndexOf('}'), beforeOpen.lastIndexOf(';'));
const raw = cssText.slice(prevClose + 1, open).replace(/\/\*[\s\S]*?\*\//g, '').trim().replace(/\s+/g, ' ');
if (!raw || raw.startsWith('@') || /^\d/.test(raw) || /[{}<]/.test(raw)) return null;
// Keyframe steps: percentage steps fail the digit test above, but `from`
@@ -4020,14 +4023,17 @@ function checkTypography() {
}
if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
+ // Report the actual primary face: the uniquely most-used family. The old
+ // 15% threshold labeled secondary faces as primary (e.g. an 82/18 split).
+ const ranked = [...fontUsage.entries()].sort((a, b) => b[1] - a[1]);
+ const [primary] = ranked;
+ const tied = ranked[1]?.[1] === primary?.[1];
+ if (primary && !tied) {
+ const [font, count] = primary;
const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ if (OVERUSED_FONTS.has(font) && !isBrandFontOnOwnDomain(font)) {
+ findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ }
}
}
diff --git a/.agents/skills/impeccable/scripts/hook-lib.mjs b/.agents/skills/impeccable/scripts/hook-lib.mjs
index 767fe65a6..6d8c3db81 100644
--- a/.agents/skills/impeccable/scripts/hook-lib.mjs
+++ b/.agents/skills/impeccable/scripts/hook-lib.mjs
@@ -138,17 +138,20 @@ export const IMMEDIATE_TIER_RULES = new Set([
// the agent is never nagged about a taste call a human might make on purpose.
// A project opts back in with `.impeccable/config.json`:
// { "detector": { "advisoryRules": "include" } }
-// This set is the hook's own copy of the registry's `advisory: true` rules,
-// mirroring how IMMEDIATE_TIER_RULES lists rule ids inline so the hook stays
-// self-contained and testable without loading the detector. Keep it in sync
-// with the registry (cli/engine/registry/antipatterns.mjs).
+// This legacy id fallback keeps older detector findings recognizable when they
+// carry neither the current runtime flag nor the canonical advisory severity.
+// Current findings are classified by their serialized metadata below.
export const ADVISORY_RULES = new Set([
'em-dash-overuse',
]);
export function isAdvisoryFinding(finding) {
const id = finding && normalizeIgnoreRule(finding.antipattern);
- return Boolean(id && (ADVISORY_RULES.has(id) || finding.advisory === true));
+ return Boolean(id && (
+ ADVISORY_RULES.has(id)
+ || finding.advisory === true
+ || finding.severity === 'advisory'
+ ));
}
export const DEFAULT_CONFIG = Object.freeze({
diff --git a/.claude/skills/impeccable/scripts/detector/browser/injected/index.mjs b/.claude/skills/impeccable/scripts/detector/browser/injected/index.mjs
index febf7f297..76fc558e5 100644
--- a/.claude/skills/impeccable/scripts/detector/browser/injected/index.mjs
+++ b/.claude/skills/impeccable/scripts/detector/browser/injected/index.mjs
@@ -1228,14 +1228,17 @@ if (IS_BROWSER) {
isHidden: isElementHidden(el),
findings: findings.map(f => {
const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
+ const severity = f.severity || ap?.severity || 'warning';
return {
type: f.type || f.id,
category: ap ? ap.category : 'quality',
- severity: f.severity || ap?.severity || 'warning',
+ severity,
// Advisory findings (em-dash overuse, etc.) are surfaced but never
// treated as failures; carry the flag so the overlay/extension can
// render them with the mildest affordance and consumers can filter.
- advisory: (ap && ap.advisory === true) || f.advisory === true,
+ // Per-finding promotions override the registry default, so derive
+ // this strictly from the effective severity.
+ advisory: severity === 'advisory',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
@@ -1277,6 +1280,381 @@ if (IS_BROWSER) {
else groupMap.set(el, [...kept]);
}
+ function pseudoElementHostSelector(selector) {
+ const raw = String(selector || '');
+ const legacyNames = new Set(['before', 'after', 'first-letter', 'first-line']);
+ const isNameChar = char => /[a-zA-Z0-9_-]/.test(char || '');
+ const consumeFunction = (start) => {
+ let depth = 0;
+ let quote = '';
+ for (let i = start; i < raw.length; i += 1) {
+ const char = raw[i];
+ if (char === '\\') {
+ i += 1;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '(') depth += 1;
+ if (char === ')' && --depth === 0) return i + 1;
+ }
+ return raw.length;
+ };
+
+ let output = '';
+ let found = false;
+ for (let i = 0; i < raw.length;) {
+ const char = raw[i];
+ if (char === '\\') {
+ output += raw.slice(i, Math.min(raw.length, i + 2));
+ i += 2;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ const quote = char;
+ const start = i;
+ i += 1;
+ while (i < raw.length) {
+ if (raw[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ const value = raw[i];
+ i += 1;
+ if (value === quote) break;
+ }
+ output += raw.slice(start, i);
+ continue;
+ }
+ if (char !== ':') {
+ output += char;
+ i += 1;
+ continue;
+ }
+
+ let end = i + 1;
+ let isPseudoElement = false;
+ if (raw[end] === ':') {
+ end += 1;
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = end > nameStart;
+ } else {
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = legacyNames.has(raw.slice(nameStart, end).toLowerCase());
+ }
+ if (!isPseudoElement) {
+ output += char;
+ i += 1;
+ continue;
+ }
+ if (raw[end] === '(') end = consumeFunction(end);
+ found = true;
+ if (!output || /[\s>+~,]/.test(output[output.length - 1])) output += '*';
+ i = end;
+ }
+ if (!found) return null;
+ return output.trim().replace(/,\s*(?=,|$)/g, '');
+ }
+
+ function selectorNodesForLiveDom(root, selector) {
+ const raw = String(selector || '').trim();
+ if (!raw) return null;
+ const fallback = pseudoElementHostSelector(raw);
+ if (fallback == null) {
+ // An empty result from a valid full selector is authoritative. In
+ // particular, do not broaden inactive :hover/:focus/:not() rules to
+ // their host element by stripping pseudo-classes.
+ try { return Array.from(root.querySelectorAll(raw)); }
+ catch { return null; }
+ }
+
+ // Resolve pseudo-elements to their originating live elements. An attached
+ // pseudo-element (`.card::before`) belongs to the element before it, while
+ // a hostless pseudo-element after a combinator (`main > ::before`) belongs
+ // to a matching element at that position (`main > *`). Replacing every
+ // pseudo indiscriminately with an empty string leaves the latter as the
+ // invalid selector `main >` and makes absent hosts indistinguishable from
+ // selectors the DOM API cannot parse.
+ if (!fallback || /^[,\s]*$/.test(fallback)) return null;
+ try { return Array.from(root.querySelectorAll(fallback)); }
+ catch { return null; }
+ }
+
+ let containerProbeSequence = 0;
+
+ function isContainerCssRule(rule) {
+ return rule?.constructor?.name === 'CSSContainerRule'
+ || /^\s*@container\b/i.test(rule?.cssText || '');
+ }
+
+ function styleRuleAppliesToLiveMatches(rule, matches) {
+ const style = rule?.style;
+ if (!style || !matches?.length || typeof getComputedStyle !== 'function') return false;
+ const sequence = ++containerProbeSequence;
+ const property = `--impeccable-container-probe-${sequence}-${Math.random().toString(36).slice(2)}`;
+ const value = `impeccable-container-active-${sequence}`;
+ const previousValue = style.getPropertyValue(property);
+ const previousPriority = style.getPropertyPriority(property);
+ try {
+ style.setProperty(property, value, 'important');
+ } catch {
+ return false;
+ }
+
+ const pseudoElements = [...new Set(
+ String(rule.selectorText || '').match(/::[a-zA-Z-]+(?:\([^)]*\))?/g) || [],
+ )];
+ try {
+ return matches.some(el => [null, ...pseudoElements].some(pseudo => {
+ try {
+ const computed = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el);
+ return computed.getPropertyValue(property).trim() === value;
+ } catch {
+ return false;
+ }
+ }));
+ } finally {
+ if (previousValue) style.setProperty(property, previousValue, previousPriority);
+ else style.removeProperty(property);
+ }
+ }
+
+ function conditionalCssRuleIsActive(rule) {
+ const type = Number(rule?.type);
+ const constructorName = rule?.constructor?.name || '';
+ if (constructorName === 'CSSMediaRule' || type === 4) {
+ const condition = rule.conditionText || rule.media?.mediaText || '';
+ if (!condition || typeof window.matchMedia !== 'function') return true;
+ try { return window.matchMedia(condition).matches; }
+ catch { return true; }
+ }
+ if (constructorName === 'CSSSupportsRule' || type === 12) {
+ const condition = rule.conditionText || '';
+ if (!condition || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return true;
+ try { return CSS.supports(condition); }
+ catch { return true; }
+ }
+ return true;
+ }
+
+ function splitCssCommaList(value) {
+ const parts = [];
+ let current = '';
+ let quote = '';
+ let escaped = false;
+ for (const char of String(value || '')) {
+ if (escaped) {
+ current += char;
+ escaped = false;
+ continue;
+ }
+ if (char === '\\') {
+ current += char;
+ escaped = true;
+ continue;
+ }
+ if (quote) {
+ current += char;
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ current += char;
+ continue;
+ }
+ if (char === ',') {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+ return parts;
+ }
+
+ function normalizeAnimationName(value) {
+ const name = String(value || '').trim();
+ if (name.length >= 2 && name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) {
+ return name.slice(1, -1);
+ }
+ return name;
+ }
+
+ function animationNamesDeclaredByRule(rule) {
+ const style = rule?.style;
+ if (!style) return [];
+ let value = '';
+ try {
+ value = style.animationName
+ || style.getPropertyValue?.('animation-name')
+ || style.webkitAnimationName
+ || style.getPropertyValue?.('-webkit-animation-name')
+ || '';
+ } catch {
+ return [];
+ }
+ return splitCssCommaList(value)
+ .map(normalizeAnimationName)
+ .filter(name => name && name.toLowerCase() !== 'none');
+ }
+
+ function keyframesRuleName(rule, cssText) {
+ const constructorName = rule?.constructor?.name || '';
+ const type = Number(rule?.type);
+ const isKeyframes = constructorName === 'CSSKeyframesRule'
+ || constructorName === 'WebKitCSSKeyframesRule'
+ || type === 7
+ || /^\s*@(?:-webkit-)?keyframes\b/i.test(cssText);
+ if (!isKeyframes) return '';
+ const match = String(cssText || '').match(/^\s*@(?:-webkit-)?keyframes\s+([^\s{]+)/i);
+ return normalizeAnimationName(rule?.name || match?.[1] || '');
+ }
+
+ function cssPropertyName(property) {
+ if (property.startsWith('--')) return property;
+ return property.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
+ }
+
+ function resolvedAnimationKeyframes(candidateNames) {
+ if (typeof document.getAnimations !== 'function') return null;
+ let animations;
+ try { animations = document.getAnimations(); }
+ catch { return null; }
+
+ const resolved = new Map();
+ const metadata = new Set(['offset', 'computedOffset', 'easing', 'composite']);
+ for (const animation of animations) {
+ const name = normalizeAnimationName(animation?.animationName || '');
+ if (!name || !candidateNames.has(name) || resolved.has(name)) continue;
+ let frames;
+ try { frames = animation.effect?.getKeyframes?.() || []; }
+ catch { continue; }
+ const blocks = [];
+ for (const frame of frames) {
+ const rawOffset = Number.isFinite(frame.computedOffset) ? frame.computedOffset : frame.offset;
+ if (!Number.isFinite(rawOffset)) continue;
+ const offset = Math.round(rawOffset * 1000000) / 10000;
+ const declarations = Object.entries(frame)
+ .filter(([property, value]) => !metadata.has(property) && value != null && value !== '')
+ .map(([property, value]) => `${cssPropertyName(property)}: ${value};`);
+ const easing = String(frame.easing || '').trim();
+ if (easing && easing.toLowerCase() !== 'linear') {
+ declarations.push(`animation-timing-function: ${easing};`);
+ }
+ if (declarations.length === 0) continue;
+ blocks.push(`${offset}% { ${declarations.join(' ')} }`);
+ }
+ if (blocks.length > 0) resolved.set(name, `@keyframes ${name} { ${blocks.join(' ')} }`);
+ }
+ return resolved;
+ }
+
+ // Read CSS that is absent from document.outerHTML. Inline <style> blocks are
+ // already present in the HTML pattern corpus, so limit this walk to linked
+ // stylesheets. Flatten grouping rules so each declaration keeps its selector,
+ // and admit only selector rules that target the live DOM. That prevents
+ // unused utilities from feeding both selector-scoped and page-level checks.
+ // Same-origin CSS and readable CORS sheets participate; browser security
+ // exceptions for cross-origin sheets are expected and skipped.
+ function linkedStylesheetText() {
+ const parts = [];
+ const seen = new Set();
+ const animationNames = new Set();
+ const keyframeCandidates = new Map();
+ const appendRules = (rules, requiresAppliedMatch = false) => {
+ for (const rule of rules) {
+ if (rule.styleSheet) {
+ appendSheet(rule.styleSheet);
+ continue;
+ }
+ const cssText = rule.cssText || '';
+ if (rule.selectorText) {
+ const matches = selectorNodesForLiveDom(document, rule.selectorText);
+ // Only declarations with a resolvable live host enter the corpus.
+ // Unresolvable selectors are uncertain, not evidence that a pattern
+ // rendered, and retaining them would leak unused CSS into findings.
+ if (
+ matches?.length > 0
+ && (!requiresAppliedMatch || styleRuleAppliesToLiveMatches(rule, matches))
+ ) {
+ parts.push(cssText);
+ for (const name of animationNamesDeclaredByRule(rule)) animationNames.add(name);
+ }
+ continue;
+ }
+ let nested = [];
+ let hasNestedRules = false;
+ try {
+ const ruleList = rule.cssRules;
+ hasNestedRules = ruleList != null;
+ nested = Array.from(ruleList || []);
+ } catch {
+ continue;
+ }
+ const keyframesName = keyframesRuleName(rule, cssText);
+ if (keyframesName) {
+ // Keyframes do not merge: when a name is defined more than once, the
+ // later effective definition replaces the earlier one.
+ keyframeCandidates.set(keyframesName, {
+ name: keyframesName,
+ cssText,
+ });
+ continue;
+ }
+ if (hasNestedRules) {
+ if (!conditionalCssRuleIsActive(rule)) continue;
+ appendRules(nested, requiresAppliedMatch || isContainerCssRule(rule));
+ continue;
+ }
+ // Other selector-less leaf at-rules cannot be tied to a rendered node.
+ }
+ };
+ const appendSheet = (sheet) => {
+ if (!sheet || seen.has(sheet)) return;
+ seen.add(sheet);
+ let rules;
+ try { rules = Array.from(sheet.cssRules || sheet.rules || []); }
+ catch { return; }
+ appendRules(rules);
+ };
+ let sheets;
+ try { sheets = Array.from(document.styleSheets || []); }
+ catch { return ''; }
+ for (const sheet of sheets) {
+ const owner = sheet.ownerNode;
+ if (owner?.tagName?.toLowerCase() !== 'link') continue;
+ if (!/\bstylesheet\b/i.test(owner.getAttribute?.('rel') || '')) continue;
+ appendSheet(sheet);
+ }
+ // Motion checks need the effective body of a live animation's keyframes.
+ // Let the browser resolve duplicate names across source order, imports,
+ // conditional groups, and cascade layers, then serialize those computed
+ // frames back into the pattern corpus. Browsers also make container-nested
+ // keyframes globally available, so lexical grouping is not a reliable
+ // activity signal. When the Web Animations API is unavailable, fall back to
+ // the last source-order definition referenced by a retained linked rule.
+ const resolvedKeyframes = resolvedAnimationKeyframes(new Set(keyframeCandidates.keys()));
+ if (resolvedKeyframes) {
+ parts.push(...resolvedKeyframes.values());
+ } else {
+ for (const candidate of keyframeCandidates.values()) {
+ if (!animationNames.has(candidate.name)) continue;
+ parts.push(candidate.cssText);
+ }
+ }
+ return parts.join('\n');
+ }
+
function browserFindingsFromMap(groupMap) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
@@ -1650,18 +2028,16 @@ if (IS_BROWSER) {
// (the CSS ships here, but the pattern never renders — the live DOM is
// ground truth in the browser), and a match under a data-impeccable-ignore
// ancestor is waived. Selector-less findings stay page-level.
- const scopedHtmlFindings = checkHtmlPatterns(docClone.outerHTML).filter(f => {
+ const html = docClone.outerHTML;
+ const corpora = buildHtmlPatternCorpora(html);
+ const linkedCss = linkedStylesheetText();
+ if (linkedCss) corpora.styleText += `\n${linkedCss}`;
+ const scopedHtmlFindings = checkHtmlPatterns(html, corpora).filter(f => {
if (!f.selector) return true;
- const query = String(f.selector).replace(/::?[a-zA-Z-]+(\([^)]*\))?/g, '').trim().replace(/,\s*(?=,|$)/g, '');
- if (!query || /^[,\s]*$/.test(query)) return true;
- let matches;
- try {
- matches = document.querySelectorAll(query);
- } catch {
- return true;
- }
+ const matches = selectorNodesForLiveDom(document, f.selector);
+ if (!matches) return false;
if (matches.length === 0) return false;
- return [...matches].some(el => !scopedIgnoreActive(el, f.id));
+ return matches.some(el => !scopedIgnoreActive(el, f.id));
});
if (scopedHtmlFindings.length > 0) {
const mapped = scopedHtmlFindings.map(f => {
diff --git a/.claude/skills/impeccable/scripts/detector/cli/main.mjs b/.claude/skills/impeccable/scripts/detector/cli/main.mjs
index 4476d04f1..3451d6c6b 100644
--- a/.claude/skills/impeccable/scripts/detector/cli/main.mjs
+++ b/.claude/skills/impeccable/scripts/detector/cli/main.mjs
@@ -37,13 +37,30 @@ function fileUrlToLocalPath(url) {
}
}
+const URL_TARGET_RE = /^(?:https?|file):\/\//i;
+
+// Some agent runners hand a shell-ready URL list to Node as one argv value.
+// A browser accepts the spaces as part of one encoded URL, producing a
+// plausible scan attributed to a bogus joined path. Expand only when every
+// whitespace-delimited token is independently a URL, preserving ordinary
+// filesystem paths that contain spaces.
+function expandJoinedUrlTargets(targets) {
+ return targets.flatMap((target) => {
+ if (!/\s/.test(target)) return [target];
+ const parts = target.trim().split(/\s+/).filter(Boolean);
+ return parts.length > 1 && parts.every(part => URL_TARGET_RE.test(part))
+ ? parts
+ : [target];
+ });
+}
+
// Advisory findings are detected but never treated as failures: they list in a
// separate, visually dimmed section, are excluded from the failure count that
// drives the exit code, and carry `"advisory": true` in JSON so consumers can
// filter. Every advisory finding carries the flag (stamped by the registry via
// findings.mjs).
function isAdvisory(finding) {
- return finding && finding.advisory === true;
+ return Boolean(finding && (finding.advisory === true || finding.severity === 'advisory'));
}
function partitionAdvisory(findings) {
@@ -168,6 +185,10 @@ Advisory findings:
counted as failures and never changing the exit code. They stay out of the
failure count so they never block automation. --no-advisory hides them.
+Output streams:
+ Human-readable findings go to stderr so stdout stays available for structured
+ output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.
+
Project config:
Respects .impeccable/config.json and .impeccable/config.local.json detector
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
@@ -185,7 +206,7 @@ Detection modes:
HTML files Static HTML/CSS analysis (default, catches linked CSS)
Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)
URLs Puppeteer full browser rendering (auto-detected;
- http(s):// and file:// URLs)
+ http(s):// and file:// URLs; accessible linked CSS included)
Examples:
impeccable detect src/
@@ -283,7 +304,7 @@ async function detectCli() {
const designSystem = loadDesignSystemForTarget(localPath, { cache: designSystemCache });
return designSystem ? { ...baseScanOptions, designSystem } : baseScanOptions;
};
- const targets = args.filter(a => !a.startsWith('--'));
+ const targets = expandJoinedUrlTargets(args.filter(a => !a.startsWith('--')));
if (helpMode) { printUsage(); process.exit(0); }
@@ -297,13 +318,12 @@ async function detectCli() {
// real cascade, real computed styles, real layout. Callers that want a
// browser-grade scan of a local artifact can pass file:///abs/path.html
// instead of the bare path (which stays on the static engine).
- const urlRe = /^(?:https?|file):\/\//i;
- const urlTargetCount = paths.filter(target => urlRe.test(target)).length;
+ const urlTargetCount = paths.filter(target => URL_TARGET_RE.test(target)).length;
const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
try {
for (const target of paths) {
- if (urlRe.test(target)) {
+ if (URL_TARGET_RE.test(target)) {
// A file:// URL points at a local artifact, so its design system
// resolves from that file's project. A remote http(s) URL has no
// local project — it gets base options (no design system), never
diff --git a/.claude/skills/impeccable/scripts/detector/detect-antipatterns-browser.js b/.claude/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
index e6899f569..460ffb45b 100644
--- a/.claude/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
+++ b/.claude/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
@@ -358,7 +358,7 @@ const ANTIPATTERNS = [
// rather than a failure. It fires only on the AI saturation pattern, not on
// ordinary prose. Advisory findings are surfaced separately, never counted
// as failures, and skipped by the design hook unless a project opts in.
- advisory: true,
+ severity: 'advisory',
name: 'Em-dash overuse',
description:
'Em-dash saturation in body copy is an AI cadence tell. Advisory only: humans use em-dashes legitimately, so this fires only on saturation — at least 8 em-dashes (— or --) at a density near one per 500 characters of body text — never on a long article that uses a few. Prefer commas, colons, periods, or parentheses.',
@@ -1961,7 +1961,10 @@ function enclosingCssSelector(cssText, index) {
// `{` belongs to some other selector.
const closeBeforeIndex = cssText.lastIndexOf('}', index);
if (closeBeforeIndex > open) return null;
- const prevClose = Math.max(cssText.lastIndexOf('}', open - 1), cssText.lastIndexOf(';', open - 1));
+ // Ignore delimiters inside comments when locating the previous declaration.
+ // Keeping comment length intact preserves indices into the original source.
+ const beforeOpen = cssText.slice(0, open).replace(/\/\*[\s\S]*?\*\//g, comment => ' '.repeat(comment.length));
+ const prevClose = Math.max(beforeOpen.lastIndexOf('}'), beforeOpen.lastIndexOf(';'));
const raw = cssText.slice(prevClose + 1, open).replace(/\/\*[\s\S]*?\*\//g, '').trim().replace(/\s+/g, ' ');
if (!raw || raw.startsWith('@') || /^\d/.test(raw) || /[{}<]/.test(raw)) return null;
// Keyframe steps: percentage steps fail the digit test above, but `from`
@@ -5293,14 +5296,17 @@ function checkTypography() {
}
if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
+ // Report the actual primary face: the uniquely most-used family. The old
+ // 15% threshold labeled secondary faces as primary (e.g. an 82/18 split).
+ const ranked = [...fontUsage.entries()].sort((a, b) => b[1] - a[1]);
+ const [primary] = ranked;
+ const tied = ranked[1]?.[1] === primary?.[1];
+ if (primary && !tied) {
+ const [font, count] = primary;
const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ if (OVERUSED_FONTS.has(font) && !isBrandFontOnOwnDomain(font)) {
+ findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ }
}
}
@@ -8126,14 +8132,17 @@ if (IS_BROWSER) {
isHidden: isElementHidden(el),
findings: findings.map(f => {
const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
+ const severity = f.severity || ap?.severity || 'warning';
return {
type: f.type || f.id,
category: ap ? ap.category : 'quality',
- severity: f.severity || ap?.severity || 'warning',
+ severity,
// Advisory findings (em-dash overuse, etc.) are surfaced but never
// treated as failures; carry the flag so the overlay/extension can
// render them with the mildest affordance and consumers can filter.
- advisory: (ap && ap.advisory === true) || f.advisory === true,
+ // Per-finding promotions override the registry default, so derive
+ // this strictly from the effective severity.
+ advisory: severity === 'advisory',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
@@ -8175,6 +8184,381 @@ if (IS_BROWSER) {
else groupMap.set(el, [...kept]);
}
+ function pseudoElementHostSelector(selector) {
+ const raw = String(selector || '');
+ const legacyNames = new Set(['before', 'after', 'first-letter', 'first-line']);
+ const isNameChar = char => /[a-zA-Z0-9_-]/.test(char || '');
+ const consumeFunction = (start) => {
+ let depth = 0;
+ let quote = '';
+ for (let i = start; i < raw.length; i += 1) {
+ const char = raw[i];
+ if (char === '\\') {
+ i += 1;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '(') depth += 1;
+ if (char === ')' && --depth === 0) return i + 1;
+ }
+ return raw.length;
+ };
+
+ let output = '';
+ let found = false;
+ for (let i = 0; i < raw.length;) {
+ const char = raw[i];
+ if (char === '\\') {
+ output += raw.slice(i, Math.min(raw.length, i + 2));
+ i += 2;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ const quote = char;
+ const start = i;
+ i += 1;
+ while (i < raw.length) {
+ if (raw[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ const value = raw[i];
+ i += 1;
+ if (value === quote) break;
+ }
+ output += raw.slice(start, i);
+ continue;
+ }
+ if (char !== ':') {
+ output += char;
+ i += 1;
+ continue;
+ }
+
+ let end = i + 1;
+ let isPseudoElement = false;
+ if (raw[end] === ':') {
+ end += 1;
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = end > nameStart;
+ } else {
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = legacyNames.has(raw.slice(nameStart, end).toLowerCase());
+ }
+ if (!isPseudoElement) {
+ output += char;
+ i += 1;
+ continue;
+ }
+ if (raw[end] === '(') end = consumeFunction(end);
+ found = true;
+ if (!output || /[\s>+~,]/.test(output[output.length - 1])) output += '*';
+ i = end;
+ }
+ if (!found) return null;
+ return output.trim().replace(/,\s*(?=,|$)/g, '');
+ }
+
+ function selectorNodesForLiveDom(root, selector) {
+ const raw = String(selector || '').trim();
+ if (!raw) return null;
+ const fallback = pseudoElementHostSelector(raw);
+ if (fallback == null) {
+ // An empty result from a valid full selector is authoritative. In
+ // particular, do not broaden inactive :hover/:focus/:not() rules to
+ // their host element by stripping pseudo-classes.
+ try { return Array.from(root.querySelectorAll(raw)); }
+ catch { return null; }
+ }
+
+ // Resolve pseudo-elements to their originating live elements. An attached
+ // pseudo-element (`.card::before`) belongs to the element before it, while
+ // a hostless pseudo-element after a combinator (`main > ::before`) belongs
+ // to a matching element at that position (`main > *`). Replacing every
+ // pseudo indiscriminately with an empty string leaves the latter as the
+ // invalid selector `main >` and makes absent hosts indistinguishable from
+ // selectors the DOM API cannot parse.
+ if (!fallback || /^[,\s]*$/.test(fallback)) return null;
+ try { return Array.from(root.querySelectorAll(fallback)); }
+ catch { return null; }
+ }
+
+ let containerProbeSequence = 0;
+
+ function isContainerCssRule(rule) {
+ return rule?.constructor?.name === 'CSSContainerRule'
+ || /^\s*@container\b/i.test(rule?.cssText || '');
+ }
+
+ function styleRuleAppliesToLiveMatches(rule, matches) {
+ const style = rule?.style;
+ if (!style || !matches?.length || typeof getComputedStyle !== 'function') return false;
+ const sequence = ++containerProbeSequence;
+ const property = `--impeccable-container-probe-${sequence}-${Math.random().toString(36).slice(2)}`;
+ const value = `impeccable-container-active-${sequence}`;
+ const previousValue = style.getPropertyValue(property);
+ const previousPriority = style.getPropertyPriority(property);
+ try {
+ style.setProperty(property, value, 'important');
+ } catch {
+ return false;
+ }
+
+ const pseudoElements = [...new Set(
+ String(rule.selectorText || '').match(/::[a-zA-Z-]+(?:\([^)]*\))?/g) || [],
+ )];
+ try {
+ return matches.some(el => [null, ...pseudoElements].some(pseudo => {
+ try {
+ const computed = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el);
+ return computed.getPropertyValue(property).trim() === value;
+ } catch {
+ return false;
+ }
+ }));
+ } finally {
+ if (previousValue) style.setProperty(property, previousValue, previousPriority);
+ else style.removeProperty(property);
+ }
+ }
+
+ function conditionalCssRuleIsActive(rule) {
+ const type = Number(rule?.type);
+ const constructorName = rule?.constructor?.name || '';
+ if (constructorName === 'CSSMediaRule' || type === 4) {
+ const condition = rule.conditionText || rule.media?.mediaText || '';
+ if (!condition || typeof window.matchMedia !== 'function') return true;
+ try { return window.matchMedia(condition).matches; }
+ catch { return true; }
+ }
+ if (constructorName === 'CSSSupportsRule' || type === 12) {
+ const condition = rule.conditionText || '';
+ if (!condition || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return true;
+ try { return CSS.supports(condition); }
+ catch { return true; }
+ }
+ return true;
+ }
+
+ function splitCssCommaList(value) {
+ const parts = [];
+ let current = '';
+ let quote = '';
+ let escaped = false;
+ for (const char of String(value || '')) {
+ if (escaped) {
+ current += char;
+ escaped = false;
+ continue;
+ }
+ if (char === '\\') {
+ current += char;
+ escaped = true;
+ continue;
+ }
+ if (quote) {
+ current += char;
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ current += char;
+ continue;
+ }
+ if (char === ',') {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+ return parts;
+ }
+
+ function normalizeAnimationName(value) {
+ const name = String(value || '').trim();
+ if (name.length >= 2 && name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) {
+ return name.slice(1, -1);
+ }
+ return name;
+ }
+
+ function animationNamesDeclaredByRule(rule) {
+ const style = rule?.style;
+ if (!style) return [];
+ let value = '';
+ try {
+ value = style.animationName
+ || style.getPropertyValue?.('animation-name')
+ || style.webkitAnimationName
+ || style.getPropertyValue?.('-webkit-animation-name')
+ || '';
+ } catch {
+ return [];
+ }
+ return splitCssCommaList(value)
+ .map(normalizeAnimationName)
+ .filter(name => name && name.toLowerCase() !== 'none');
+ }
+
+ function keyframesRuleName(rule, cssText) {
+ const constructorName = rule?.constructor?.name || '';
+ const type = Number(rule?.type);
+ const isKeyframes = constructorName === 'CSSKeyframesRule'
+ || constructorName === 'WebKitCSSKeyframesRule'
+ || type === 7
+ || /^\s*@(?:-webkit-)?keyframes\b/i.test(cssText);
+ if (!isKeyframes) return '';
+ const match = String(cssText || '').match(/^\s*@(?:-webkit-)?keyframes\s+([^\s{]+)/i);
+ return normalizeAnimationName(rule?.name || match?.[1] || '');
+ }
+
+ function cssPropertyName(property) {
+ if (property.startsWith('--')) return property;
+ return property.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
+ }
+
+ function resolvedAnimationKeyframes(candidateNames) {
+ if (typeof document.getAnimations !== 'function') return null;
+ let animations;
+ try { animations = document.getAnimations(); }
+ catch { return null; }
+
+ const resolved = new Map();
+ const metadata = new Set(['offset', 'computedOffset', 'easing', 'composite']);
+ for (const animation of animations) {
+ const name = normalizeAnimationName(animation?.animationName || '');
+ if (!name || !candidateNames.has(name) || resolved.has(name)) continue;
+ let frames;
+ try { frames = animation.effect?.getKeyframes?.() || []; }
+ catch { continue; }
+ const blocks = [];
+ for (const frame of frames) {
+ const rawOffset = Number.isFinite(frame.computedOffset) ? frame.computedOffset : frame.offset;
+ if (!Number.isFinite(rawOffset)) continue;
+ const offset = Math.round(rawOffset * 1000000) / 10000;
+ const declarations = Object.entries(frame)
+ .filter(([property, value]) => !metadata.has(property) && value != null && value !== '')
+ .map(([property, value]) => `${cssPropertyName(property)}: ${value};`);
+ const easing = String(frame.easing || '').trim();
+ if (easing && easing.toLowerCase() !== 'linear') {
+ declarations.push(`animation-timing-function: ${easing};`);
+ }
+ if (declarations.length === 0) continue;
+ blocks.push(`${offset}% { ${declarations.join(' ')} }`);
+ }
+ if (blocks.length > 0) resolved.set(name, `@keyframes ${name} { ${blocks.join(' ')} }`);
+ }
+ return resolved;
+ }
+
+ // Read CSS that is absent from document.outerHTML. Inline <style> blocks are
+ // already present in the HTML pattern corpus, so limit this walk to linked
+ // stylesheets. Flatten grouping rules so each declaration keeps its selector,
+ // and admit only selector rules that target the live DOM. That prevents
+ // unused utilities from feeding both selector-scoped and page-level checks.
+ // Same-origin CSS and readable CORS sheets participate; browser security
+ // exceptions for cross-origin sheets are expected and skipped.
+ function linkedStylesheetText() {
+ const parts = [];
+ const seen = new Set();
+ const animationNames = new Set();
+ const keyframeCandidates = new Map();
+ const appendRules = (rules, requiresAppliedMatch = false) => {
+ for (const rule of rules) {
+ if (rule.styleSheet) {
+ appendSheet(rule.styleSheet);
+ continue;
+ }
+ const cssText = rule.cssText || '';
+ if (rule.selectorText) {
+ const matches = selectorNodesForLiveDom(document, rule.selectorText);
+ // Only declarations with a resolvable live host enter the corpus.
+ // Unresolvable selectors are uncertain, not evidence that a pattern
+ // rendered, and retaining them would leak unused CSS into findings.
+ if (
+ matches?.length > 0
+ && (!requiresAppliedMatch || styleRuleAppliesToLiveMatches(rule, matches))
+ ) {
+ parts.push(cssText);
+ for (const name of animationNamesDeclaredByRule(rule)) animationNames.add(name);
+ }
+ continue;
+ }
+ let nested = [];
+ let hasNestedRules = false;
+ try {
+ const ruleList = rule.cssRules;
+ hasNestedRules = ruleList != null;
+ nested = Array.from(ruleList || []);
+ } catch {
+ continue;
+ }
+ const keyframesName = keyframesRuleName(rule, cssText);
+ if (keyframesName) {
+ // Keyframes do not merge: when a name is defined more than once, the
+ // later effective definition replaces the earlier one.
+ keyframeCandidates.set(keyframesName, {
+ name: keyframesName,
+ cssText,
+ });
+ continue;
+ }
+ if (hasNestedRules) {
+ if (!conditionalCssRuleIsActive(rule)) continue;
+ appendRules(nested, requiresAppliedMatch || isContainerCssRule(rule));
+ continue;
+ }
+ // Other selector-less leaf at-rules cannot be tied to a rendered node.
+ }
+ };
+ const appendSheet = (sheet) => {
+ if (!sheet || seen.has(sheet)) return;
+ seen.add(sheet);
+ let rules;
+ try { rules = Array.from(sheet.cssRules || sheet.rules || []); }
+ catch { return; }
+ appendRules(rules);
+ };
+ let sheets;
+ try { sheets = Array.from(document.styleSheets || []); }
+ catch { return ''; }
+ for (const sheet of sheets) {
+ const owner = sheet.ownerNode;
+ if (owner?.tagName?.toLowerCase() !== 'link') continue;
+ if (!/\bstylesheet\b/i.test(owner.getAttribute?.('rel') || '')) continue;
+ appendSheet(sheet);
+ }
+ // Motion checks need the effective body of a live animation's keyframes.
+ // Let the browser resolve duplicate names across source order, imports,
+ // conditional groups, and cascade layers, then serialize those computed
+ // frames back into the pattern corpus. Browsers also make container-nested
+ // keyframes globally available, so lexical grouping is not a reliable
+ // activity signal. When the Web Animations API is unavailable, fall back to
+ // the last source-order definition referenced by a retained linked rule.
+ const resolvedKeyframes = resolvedAnimationKeyframes(new Set(keyframeCandidates.keys()));
+ if (resolvedKeyframes) {
+ parts.push(...resolvedKeyframes.values());
+ } else {
+ for (const candidate of keyframeCandidates.values()) {
+ if (!animationNames.has(candidate.name)) continue;
+ parts.push(candidate.cssText);
+ }
+ }
+ return parts.join('\n');
+ }
+
function browserFindingsFromMap(groupMap) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
@@ -8548,18 +8932,16 @@ if (IS_BROWSER) {
// (the CSS ships here, but the pattern never renders — the live DOM is
// ground truth in the browser), and a match under a data-impeccable-ignore
// ancestor is waived. Selector-less findings stay page-level.
- const scopedHtmlFindings = checkHtmlPatterns(docClone.outerHTML).filter(f => {
+ const html = docClone.outerHTML;
+ const corpora = buildHtmlPatternCorpora(html);
+ const linkedCss = linkedStylesheetText();
+ if (linkedCss) corpora.styleText += `\n${linkedCss}`;
+ const scopedHtmlFindings = checkHtmlPatterns(html, corpora).filter(f => {
if (!f.selector) return true;
- const query = String(f.selector).replace(/::?[a-zA-Z-]+(\([^)]*\))?/g, '').trim().replace(/,\s*(?=,|$)/g, '');
- if (!query || /^[,\s]*$/.test(query)) return true;
- let matches;
- try {
- matches = document.querySelectorAll(query);
- } catch {
- return true;
- }
+ const matches = selectorNodesForLiveDom(document, f.selector);
+ if (!matches) return false;
if (matches.length === 0) return false;
- return [...matches].some(el => !scopedIgnoreActive(el, f.id));
+ return matches.some(el => !scopedIgnoreActive(el, f.id));
});
if (scopedHtmlFindings.length > 0) {
const mapped = scopedHtmlFindings.map(f => {
diff --git a/.claude/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs b/.claude/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
index f3ff43c84..ac4bd0a7c 100644
--- a/.claude/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
+++ b/.claude/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
@@ -2,7 +2,7 @@ import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { finding } from '../../findings.mjs';
+import { deriveAdvisoryFlag, finding } from '../../findings.mjs';
import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
import { checkContentHiddenAtRest } from '../../rules/checks.mjs';
@@ -394,7 +394,7 @@ async function detectUrl(rawUrl, options = {}) {
// Per-finding severity promotion (e.g. hero-region pulsing dot)
// overrides the registry default carried by finding().
if (f.severity && f.severity !== item.severity) item.severity = f.severity;
- return item;
+ return deriveAdvisoryFlag(item);
});
}
diff --git a/.claude/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs b/.claude/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
index 84e6ab1f5..dac6939b0 100644
--- a/.claude/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
+++ b/.claude/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
@@ -9,7 +9,7 @@ import {
} from '../../design-system.mjs';
import { isFullPage } from '../../shared/page.mjs';
import { applyInlineIgnores } from '../../shared/inline-ignores.mjs';
-import { finding } from '../../findings.mjs';
+import { deriveAdvisoryFlag, finding } from '../../findings.mjs';
import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import {
checkElementBorders,
@@ -257,7 +257,7 @@ async function detectHtml(filePath, options = {}) {
// severity (e.g. a pulsing dot inside a header/nav landmark) that
// overrides the registry default.
if (f.severity) item.severity = f.severity;
- findings.push(item);
+ findings.push(deriveAdvisoryFlag(item));
}
// Text-content analyzers (em-dash overuse, marketing buzzwords,
// numbered section markers, aphoristic cadence) live in the regex
diff --git a/.claude/skills/impeccable/scripts/detector/findings.mjs b/.claude/skills/impeccable/scripts/detector/findings.mjs
index fa98dd935..ae7e134f9 100644
--- a/.claude/skills/impeccable/scripts/detector/findings.mjs
+++ b/.claude/skills/impeccable/scripts/detector/findings.mjs
@@ -4,6 +4,12 @@ function getAP(id) {
return getAntipattern(id);
}
+function deriveAdvisoryFlag(item) {
+ if (item.severity === 'advisory') item.advisory = true;
+ else delete item.advisory;
+ return item;
+}
+
function finding(id, filePath, snippet, line = 0) {
const ap = getAP(id);
const base = { antipattern: id, name: ap.name, description: ap.description, severity: ap.severity || 'warning', category: ap.category || null, file: filePath, line, snippet };
@@ -11,8 +17,7 @@ function finding(id, filePath, snippet, line = 0) {
// failures. Carry the flag on the finding so every consumer (CLI, JSON, hook)
// can partition without a registry lookup. Only stamped when true to keep the
// finding shape stable for the vast majority of rules.
- if (ap.advisory === true) base.advisory = true;
- return base;
+ return deriveAdvisoryFlag(base);
}
-export { getAP, finding };
+export { getAP, finding, deriveAdvisoryFlag };
diff --git a/.claude/skills/impeccable/scripts/detector/registry/antipatterns.mjs b/.claude/skills/impeccable/scripts/detector/registry/antipatterns.mjs
index 945307783..7c692c79a 100644
--- a/.claude/skills/impeccable/scripts/detector/registry/antipatterns.mjs
+++ b/.claude/skills/impeccable/scripts/detector/registry/antipatterns.mjs
@@ -233,7 +233,7 @@ const ANTIPATTERNS = [
// rather than a failure. It fires only on the AI saturation pattern, not on
// ordinary prose. Advisory findings are surfaced separately, never counted
// as failures, and skipped by the design hook unless a project opts in.
- advisory: true,
+ severity: 'advisory',
name: 'Em-dash overuse',
description:
'Em-dash saturation in body copy is an AI cadence tell. Advisory only: humans use em-dashes legitimately, so this fires only on saturation — at least 8 em-dashes (— or --) at a density near one per 500 characters of body text — never on a long article that uses a few. Prefer commas, colons, periods, or parentheses.',
@@ -588,9 +588,10 @@ function getAntipattern(id) {
// Advisory rules are detected and reported, but never treated as failures:
// the CLI lists them under a separate "Advisory" section, they do not affect
// exit codes or the failure count, and the design hook skips them by default.
-// The set is derived from the registry so a rule only needs `advisory: true`.
+// `severity` is the canonical registry field. The runtime finding serializer
+// derives its `advisory: true` compatibility/output flag from this set.
const ADVISORY_RULE_IDS = new Set(
- ANTIPATTERNS.filter(rule => rule.advisory === true).map(rule => rule.id),
+ ANTIPATTERNS.filter(rule => rule.severity === 'advisory').map(rule => rule.id),
);
function isAdvisoryRule(id) {
diff --git a/.claude/skills/impeccable/scripts/detector/rules/checks.mjs b/.claude/skills/impeccable/scripts/detector/rules/checks.mjs
index 579e1c12e..a24631ce9 100644
--- a/.claude/skills/impeccable/scripts/detector/rules/checks.mjs
+++ b/.claude/skills/impeccable/scripts/detector/rules/checks.mjs
@@ -688,7 +688,10 @@ function enclosingCssSelector(cssText, index) {
// `{` belongs to some other selector.
const closeBeforeIndex = cssText.lastIndexOf('}', index);
if (closeBeforeIndex > open) return null;
- const prevClose = Math.max(cssText.lastIndexOf('}', open - 1), cssText.lastIndexOf(';', open - 1));
+ // Ignore delimiters inside comments when locating the previous declaration.
+ // Keeping comment length intact preserves indices into the original source.
+ const beforeOpen = cssText.slice(0, open).replace(/\/\*[\s\S]*?\*\//g, comment => ' '.repeat(comment.length));
+ const prevClose = Math.max(beforeOpen.lastIndexOf('}'), beforeOpen.lastIndexOf(';'));
const raw = cssText.slice(prevClose + 1, open).replace(/\/\*[\s\S]*?\*\//g, '').trim().replace(/\s+/g, ' ');
if (!raw || raw.startsWith('@') || /^\d/.test(raw) || /[{}<]/.test(raw)) return null;
// Keyframe steps: percentage steps fail the digit test above, but `from`
@@ -4020,14 +4023,17 @@ function checkTypography() {
}
if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
+ // Report the actual primary face: the uniquely most-used family. The old
+ // 15% threshold labeled secondary faces as primary (e.g. an 82/18 split).
+ const ranked = [...fontUsage.entries()].sort((a, b) => b[1] - a[1]);
+ const [primary] = ranked;
+ const tied = ranked[1]?.[1] === primary?.[1];
+ if (primary && !tied) {
+ const [font, count] = primary;
const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ if (OVERUSED_FONTS.has(font) && !isBrandFontOnOwnDomain(font)) {
+ findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ }
}
}
diff --git a/.claude/skills/impeccable/scripts/hook-lib.mjs b/.claude/skills/impeccable/scripts/hook-lib.mjs
index 767fe65a6..6d8c3db81 100644
--- a/.claude/skills/impeccable/scripts/hook-lib.mjs
+++ b/.claude/skills/impeccable/scripts/hook-lib.mjs
@@ -138,17 +138,20 @@ export const IMMEDIATE_TIER_RULES = new Set([
// the agent is never nagged about a taste call a human might make on purpose.
// A project opts back in with `.impeccable/config.json`:
// { "detector": { "advisoryRules": "include" } }
-// This set is the hook's own copy of the registry's `advisory: true` rules,
-// mirroring how IMMEDIATE_TIER_RULES lists rule ids inline so the hook stays
-// self-contained and testable without loading the detector. Keep it in sync
-// with the registry (cli/engine/registry/antipatterns.mjs).
+// This legacy id fallback keeps older detector findings recognizable when they
+// carry neither the current runtime flag nor the canonical advisory severity.
+// Current findings are classified by their serialized metadata below.
export const ADVISORY_RULES = new Set([
'em-dash-overuse',
]);
export function isAdvisoryFinding(finding) {
const id = finding && normalizeIgnoreRule(finding.antipattern);
- return Boolean(id && (ADVISORY_RULES.has(id) || finding.advisory === true));
+ return Boolean(id && (
+ ADVISORY_RULES.has(id)
+ || finding.advisory === true
+ || finding.severity === 'advisory'
+ ));
}
export const DEFAULT_CONFIG = Object.freeze({
diff --git a/.cursor/skills/impeccable/scripts/detector/browser/injected/index.mjs b/.cursor/skills/impeccable/scripts/detector/browser/injected/index.mjs
index febf7f297..76fc558e5 100644
--- a/.cursor/skills/impeccable/scripts/detector/browser/injected/index.mjs
+++ b/.cursor/skills/impeccable/scripts/detector/browser/injected/index.mjs
@@ -1228,14 +1228,17 @@ if (IS_BROWSER) {
isHidden: isElementHidden(el),
findings: findings.map(f => {
const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
+ const severity = f.severity || ap?.severity || 'warning';
return {
type: f.type || f.id,
category: ap ? ap.category : 'quality',
- severity: f.severity || ap?.severity || 'warning',
+ severity,
// Advisory findings (em-dash overuse, etc.) are surfaced but never
// treated as failures; carry the flag so the overlay/extension can
// render them with the mildest affordance and consumers can filter.
- advisory: (ap && ap.advisory === true) || f.advisory === true,
+ // Per-finding promotions override the registry default, so derive
+ // this strictly from the effective severity.
+ advisory: severity === 'advisory',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
@@ -1277,6 +1280,381 @@ if (IS_BROWSER) {
else groupMap.set(el, [...kept]);
}
+ function pseudoElementHostSelector(selector) {
+ const raw = String(selector || '');
+ const legacyNames = new Set(['before', 'after', 'first-letter', 'first-line']);
+ const isNameChar = char => /[a-zA-Z0-9_-]/.test(char || '');
+ const consumeFunction = (start) => {
+ let depth = 0;
+ let quote = '';
+ for (let i = start; i < raw.length; i += 1) {
+ const char = raw[i];
+ if (char === '\\') {
+ i += 1;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '(') depth += 1;
+ if (char === ')' && --depth === 0) return i + 1;
+ }
+ return raw.length;
+ };
+
+ let output = '';
+ let found = false;
+ for (let i = 0; i < raw.length;) {
+ const char = raw[i];
+ if (char === '\\') {
+ output += raw.slice(i, Math.min(raw.length, i + 2));
+ i += 2;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ const quote = char;
+ const start = i;
+ i += 1;
+ while (i < raw.length) {
+ if (raw[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ const value = raw[i];
+ i += 1;
+ if (value === quote) break;
+ }
+ output += raw.slice(start, i);
+ continue;
+ }
+ if (char !== ':') {
+ output += char;
+ i += 1;
+ continue;
+ }
+
+ let end = i + 1;
+ let isPseudoElement = false;
+ if (raw[end] === ':') {
+ end += 1;
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = end > nameStart;
+ } else {
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = legacyNames.has(raw.slice(nameStart, end).toLowerCase());
+ }
+ if (!isPseudoElement) {
+ output += char;
+ i += 1;
+ continue;
+ }
+ if (raw[end] === '(') end = consumeFunction(end);
+ found = true;
+ if (!output || /[\s>+~,]/.test(output[output.length - 1])) output += '*';
+ i = end;
+ }
+ if (!found) return null;
+ return output.trim().replace(/,\s*(?=,|$)/g, '');
+ }
+
+ function selectorNodesForLiveDom(root, selector) {
+ const raw = String(selector || '').trim();
+ if (!raw) return null;
+ const fallback = pseudoElementHostSelector(raw);
+ if (fallback == null) {
+ // An empty result from a valid full selector is authoritative. In
+ // particular, do not broaden inactive :hover/:focus/:not() rules to
+ // their host element by stripping pseudo-classes.
+ try { return Array.from(root.querySelectorAll(raw)); }
+ catch { return null; }
+ }
+
+ // Resolve pseudo-elements to their originating live elements. An attached
+ // pseudo-element (`.card::before`) belongs to the element before it, while
+ // a hostless pseudo-element after a combinator (`main > ::before`) belongs
+ // to a matching element at that position (`main > *`). Replacing every
+ // pseudo indiscriminately with an empty string leaves the latter as the
+ // invalid selector `main >` and makes absent hosts indistinguishable from
+ // selectors the DOM API cannot parse.
+ if (!fallback || /^[,\s]*$/.test(fallback)) return null;
+ try { return Array.from(root.querySelectorAll(fallback)); }
+ catch { return null; }
+ }
+
+ let containerProbeSequence = 0;
+
+ function isContainerCssRule(rule) {
+ return rule?.constructor?.name === 'CSSContainerRule'
+ || /^\s*@container\b/i.test(rule?.cssText || '');
+ }
+
+ function styleRuleAppliesToLiveMatches(rule, matches) {
+ const style = rule?.style;
+ if (!style || !matches?.length || typeof getComputedStyle !== 'function') return false;
+ const sequence = ++containerProbeSequence;
+ const property = `--impeccable-container-probe-${sequence}-${Math.random().toString(36).slice(2)}`;
+ const value = `impeccable-container-active-${sequence}`;
+ const previousValue = style.getPropertyValue(property);
+ const previousPriority = style.getPropertyPriority(property);
+ try {
+ style.setProperty(property, value, 'important');
+ } catch {
+ return false;
+ }
+
+ const pseudoElements = [...new Set(
+ String(rule.selectorText || '').match(/::[a-zA-Z-]+(?:\([^)]*\))?/g) || [],
+ )];
+ try {
+ return matches.some(el => [null, ...pseudoElements].some(pseudo => {
+ try {
+ const computed = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el);
+ return computed.getPropertyValue(property).trim() === value;
+ } catch {
+ return false;
+ }
+ }));
+ } finally {
+ if (previousValue) style.setProperty(property, previousValue, previousPriority);
+ else style.removeProperty(property);
+ }
+ }
+
+ function conditionalCssRuleIsActive(rule) {
+ const type = Number(rule?.type);
+ const constructorName = rule?.constructor?.name || '';
+ if (constructorName === 'CSSMediaRule' || type === 4) {
+ const condition = rule.conditionText || rule.media?.mediaText || '';
+ if (!condition || typeof window.matchMedia !== 'function') return true;
+ try { return window.matchMedia(condition).matches; }
+ catch { return true; }
+ }
+ if (constructorName === 'CSSSupportsRule' || type === 12) {
+ const condition = rule.conditionText || '';
+ if (!condition || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return true;
+ try { return CSS.supports(condition); }
+ catch { return true; }
+ }
+ return true;
+ }
+
+ function splitCssCommaList(value) {
+ const parts = [];
+ let current = '';
+ let quote = '';
+ let escaped = false;
+ for (const char of String(value || '')) {
+ if (escaped) {
+ current += char;
+ escaped = false;
+ continue;
+ }
+ if (char === '\\') {
+ current += char;
+ escaped = true;
+ continue;
+ }
+ if (quote) {
+ current += char;
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ current += char;
+ continue;
+ }
+ if (char === ',') {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+ return parts;
+ }
+
+ function normalizeAnimationName(value) {
+ const name = String(value || '').trim();
+ if (name.length >= 2 && name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) {
+ return name.slice(1, -1);
+ }
+ return name;
+ }
+
+ function animationNamesDeclaredByRule(rule) {
+ const style = rule?.style;
+ if (!style) return [];
+ let value = '';
+ try {
+ value = style.animationName
+ || style.getPropertyValue?.('animation-name')
+ || style.webkitAnimationName
+ || style.getPropertyValue?.('-webkit-animation-name')
+ || '';
+ } catch {
+ return [];
+ }
+ return splitCssCommaList(value)
+ .map(normalizeAnimationName)
+ .filter(name => name && name.toLowerCase() !== 'none');
+ }
+
+ function keyframesRuleName(rule, cssText) {
+ const constructorName = rule?.constructor?.name || '';
+ const type = Number(rule?.type);
+ const isKeyframes = constructorName === 'CSSKeyframesRule'
+ || constructorName === 'WebKitCSSKeyframesRule'
+ || type === 7
+ || /^\s*@(?:-webkit-)?keyframes\b/i.test(cssText);
+ if (!isKeyframes) return '';
+ const match = String(cssText || '').match(/^\s*@(?:-webkit-)?keyframes\s+([^\s{]+)/i);
+ return normalizeAnimationName(rule?.name || match?.[1] || '');
+ }
+
+ function cssPropertyName(property) {
+ if (property.startsWith('--')) return property;
+ return property.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
+ }
+
+ function resolvedAnimationKeyframes(candidateNames) {
+ if (typeof document.getAnimations !== 'function') return null;
+ let animations;
+ try { animations = document.getAnimations(); }
+ catch { return null; }
+
+ const resolved = new Map();
+ const metadata = new Set(['offset', 'computedOffset', 'easing', 'composite']);
+ for (const animation of animations) {
+ const name = normalizeAnimationName(animation?.animationName || '');
+ if (!name || !candidateNames.has(name) || resolved.has(name)) continue;
+ let frames;
+ try { frames = animation.effect?.getKeyframes?.() || []; }
+ catch { continue; }
+ const blocks = [];
+ for (const frame of frames) {
+ const rawOffset = Number.isFinite(frame.computedOffset) ? frame.computedOffset : frame.offset;
+ if (!Number.isFinite(rawOffset)) continue;
+ const offset = Math.round(rawOffset * 1000000) / 10000;
+ const declarations = Object.entries(frame)
+ .filter(([property, value]) => !metadata.has(property) && value != null && value !== '')
+ .map(([property, value]) => `${cssPropertyName(property)}: ${value};`);
+ const easing = String(frame.easing || '').trim();
+ if (easing && easing.toLowerCase() !== 'linear') {
+ declarations.push(`animation-timing-function: ${easing};`);
+ }
+ if (declarations.length === 0) continue;
+ blocks.push(`${offset}% { ${declarations.join(' ')} }`);
+ }
+ if (blocks.length > 0) resolved.set(name, `@keyframes ${name} { ${blocks.join(' ')} }`);
+ }
+ return resolved;
+ }
+
+ // Read CSS that is absent from document.outerHTML. Inline <style> blocks are
+ // already present in the HTML pattern corpus, so limit this walk to linked
+ // stylesheets. Flatten grouping rules so each declaration keeps its selector,
+ // and admit only selector rules that target the live DOM. That prevents
+ // unused utilities from feeding both selector-scoped and page-level checks.
+ // Same-origin CSS and readable CORS sheets participate; browser security
+ // exceptions for cross-origin sheets are expected and skipped.
+ function linkedStylesheetText() {
+ const parts = [];
+ const seen = new Set();
+ const animationNames = new Set();
+ const keyframeCandidates = new Map();
+ const appendRules = (rules, requiresAppliedMatch = false) => {
+ for (const rule of rules) {
+ if (rule.styleSheet) {
+ appendSheet(rule.styleSheet);
+ continue;
+ }
+ const cssText = rule.cssText || '';
+ if (rule.selectorText) {
+ const matches = selectorNodesForLiveDom(document, rule.selectorText);
+ // Only declarations with a resolvable live host enter the corpus.
+ // Unresolvable selectors are uncertain, not evidence that a pattern
+ // rendered, and retaining them would leak unused CSS into findings.
+ if (
+ matches?.length > 0
+ && (!requiresAppliedMatch || styleRuleAppliesToLiveMatches(rule, matches))
+ ) {
+ parts.push(cssText);
+ for (const name of animationNamesDeclaredByRule(rule)) animationNames.add(name);
+ }
+ continue;
+ }
+ let nested = [];
+ let hasNestedRules = false;
+ try {
+ const ruleList = rule.cssRules;
+ hasNestedRules = ruleList != null;
+ nested = Array.from(ruleList || []);
+ } catch {
+ continue;
+ }
+ const keyframesName = keyframesRuleName(rule, cssText);
+ if (keyframesName) {
+ // Keyframes do not merge: when a name is defined more than once, the
+ // later effective definition replaces the earlier one.
+ keyframeCandidates.set(keyframesName, {
+ name: keyframesName,
+ cssText,
+ });
+ continue;
+ }
+ if (hasNestedRules) {
+ if (!conditionalCssRuleIsActive(rule)) continue;
+ appendRules(nested, requiresAppliedMatch || isContainerCssRule(rule));
+ continue;
+ }
+ // Other selector-less leaf at-rules cannot be tied to a rendered node.
+ }
+ };
+ const appendSheet = (sheet) => {
+ if (!sheet || seen.has(sheet)) return;
+ seen.add(sheet);
+ let rules;
+ try { rules = Array.from(sheet.cssRules || sheet.rules || []); }
+ catch { return; }
+ appendRules(rules);
+ };
+ let sheets;
+ try { sheets = Array.from(document.styleSheets || []); }
+ catch { return ''; }
+ for (const sheet of sheets) {
+ const owner = sheet.ownerNode;
+ if (owner?.tagName?.toLowerCase() !== 'link') continue;
+ if (!/\bstylesheet\b/i.test(owner.getAttribute?.('rel') || '')) continue;
+ appendSheet(sheet);
+ }
+ // Motion checks need the effective body of a live animation's keyframes.
+ // Let the browser resolve duplicate names across source order, imports,
+ // conditional groups, and cascade layers, then serialize those computed
+ // frames back into the pattern corpus. Browsers also make container-nested
+ // keyframes globally available, so lexical grouping is not a reliable
+ // activity signal. When the Web Animations API is unavailable, fall back to
+ // the last source-order definition referenced by a retained linked rule.
+ const resolvedKeyframes = resolvedAnimationKeyframes(new Set(keyframeCandidates.keys()));
+ if (resolvedKeyframes) {
+ parts.push(...resolvedKeyframes.values());
+ } else {
+ for (const candidate of keyframeCandidates.values()) {
+ if (!animationNames.has(candidate.name)) continue;
+ parts.push(candidate.cssText);
+ }
+ }
+ return parts.join('\n');
+ }
+
function browserFindingsFromMap(groupMap) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
@@ -1650,18 +2028,16 @@ if (IS_BROWSER) {
// (the CSS ships here, but the pattern never renders — the live DOM is
// ground truth in the browser), and a match under a data-impeccable-ignore
// ancestor is waived. Selector-less findings stay page-level.
- const scopedHtmlFindings = checkHtmlPatterns(docClone.outerHTML).filter(f => {
+ const html = docClone.outerHTML;
+ const corpora = buildHtmlPatternCorpora(html);
+ const linkedCss = linkedStylesheetText();
+ if (linkedCss) corpora.styleText += `\n${linkedCss}`;
+ const scopedHtmlFindings = checkHtmlPatterns(html, corpora).filter(f => {
if (!f.selector) return true;
- const query = String(f.selector).replace(/::?[a-zA-Z-]+(\([^)]*\))?/g, '').trim().replace(/,\s*(?=,|$)/g, '');
- if (!query || /^[,\s]*$/.test(query)) return true;
- let matches;
- try {
- matches = document.querySelectorAll(query);
- } catch {
- return true;
- }
+ const matches = selectorNodesForLiveDom(document, f.selector);
+ if (!matches) return false;
if (matches.length === 0) return false;
- return [...matches].some(el => !scopedIgnoreActive(el, f.id));
+ return matches.some(el => !scopedIgnoreActive(el, f.id));
});
if (scopedHtmlFindings.length > 0) {
const mapped = scopedHtmlFindings.map(f => {
diff --git a/.cursor/skills/impeccable/scripts/detector/cli/main.mjs b/.cursor/skills/impeccable/scripts/detector/cli/main.mjs
index 4476d04f1..3451d6c6b 100644
--- a/.cursor/skills/impeccable/scripts/detector/cli/main.mjs
+++ b/.cursor/skills/impeccable/scripts/detector/cli/main.mjs
@@ -37,13 +37,30 @@ function fileUrlToLocalPath(url) {
}
}
+const URL_TARGET_RE = /^(?:https?|file):\/\//i;
+
+// Some agent runners hand a shell-ready URL list to Node as one argv value.
+// A browser accepts the spaces as part of one encoded URL, producing a
+// plausible scan attributed to a bogus joined path. Expand only when every
+// whitespace-delimited token is independently a URL, preserving ordinary
+// filesystem paths that contain spaces.
+function expandJoinedUrlTargets(targets) {
+ return targets.flatMap((target) => {
+ if (!/\s/.test(target)) return [target];
+ const parts = target.trim().split(/\s+/).filter(Boolean);
+ return parts.length > 1 && parts.every(part => URL_TARGET_RE.test(part))
+ ? parts
+ : [target];
+ });
+}
+
// Advisory findings are detected but never treated as failures: they list in a
// separate, visually dimmed section, are excluded from the failure count that
// drives the exit code, and carry `"advisory": true` in JSON so consumers can
// filter. Every advisory finding carries the flag (stamped by the registry via
// findings.mjs).
function isAdvisory(finding) {
- return finding && finding.advisory === true;
+ return Boolean(finding && (finding.advisory === true || finding.severity === 'advisory'));
}
function partitionAdvisory(findings) {
@@ -168,6 +185,10 @@ Advisory findings:
counted as failures and never changing the exit code. They stay out of the
failure count so they never block automation. --no-advisory hides them.
+Output streams:
+ Human-readable findings go to stderr so stdout stays available for structured
+ output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.
+
Project config:
Respects .impeccable/config.json and .impeccable/config.local.json detector
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
@@ -185,7 +206,7 @@ Detection modes:
HTML files Static HTML/CSS analysis (default, catches linked CSS)
Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)
URLs Puppeteer full browser rendering (auto-detected;
- http(s):// and file:// URLs)
+ http(s):// and file:// URLs; accessible linked CSS included)
Examples:
impeccable detect src/
@@ -283,7 +304,7 @@ async function detectCli() {
const designSystem = loadDesignSystemForTarget(localPath, { cache: designSystemCache });
return designSystem ? { ...baseScanOptions, designSystem } : baseScanOptions;
};
- const targets = args.filter(a => !a.startsWith('--'));
+ const targets = expandJoinedUrlTargets(args.filter(a => !a.startsWith('--')));
if (helpMode) { printUsage(); process.exit(0); }
@@ -297,13 +318,12 @@ async function detectCli() {
// real cascade, real computed styles, real layout. Callers that want a
// browser-grade scan of a local artifact can pass file:///abs/path.html
// instead of the bare path (which stays on the static engine).
- const urlRe = /^(?:https?|file):\/\//i;
- const urlTargetCount = paths.filter(target => urlRe.test(target)).length;
+ const urlTargetCount = paths.filter(target => URL_TARGET_RE.test(target)).length;
const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
try {
for (const target of paths) {
- if (urlRe.test(target)) {
+ if (URL_TARGET_RE.test(target)) {
// A file:// URL points at a local artifact, so its design system
// resolves from that file's project. A remote http(s) URL has no
// local project — it gets base options (no design system), never
diff --git a/.cursor/skills/impeccable/scripts/detector/detect-antipatterns-browser.js b/.cursor/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
index e6899f569..460ffb45b 100644
--- a/.cursor/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
+++ b/.cursor/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
@@ -358,7 +358,7 @@ const ANTIPATTERNS = [
// rather than a failure. It fires only on the AI saturation pattern, not on
// ordinary prose. Advisory findings are surfaced separately, never counted
// as failures, and skipped by the design hook unless a project opts in.
- advisory: true,
+ severity: 'advisory',
name: 'Em-dash overuse',
description:
'Em-dash saturation in body copy is an AI cadence tell. Advisory only: humans use em-dashes legitimately, so this fires only on saturation — at least 8 em-dashes (— or --) at a density near one per 500 characters of body text — never on a long article that uses a few. Prefer commas, colons, periods, or parentheses.',
@@ -1961,7 +1961,10 @@ function enclosingCssSelector(cssText, index) {
// `{` belongs to some other selector.
const closeBeforeIndex = cssText.lastIndexOf('}', index);
if (closeBeforeIndex > open) return null;
- const prevClose = Math.max(cssText.lastIndexOf('}', open - 1), cssText.lastIndexOf(';', open - 1));
+ // Ignore delimiters inside comments when locating the previous declaration.
+ // Keeping comment length intact preserves indices into the original source.
+ const beforeOpen = cssText.slice(0, open).replace(/\/\*[\s\S]*?\*\//g, comment => ' '.repeat(comment.length));
+ const prevClose = Math.max(beforeOpen.lastIndexOf('}'), beforeOpen.lastIndexOf(';'));
const raw = cssText.slice(prevClose + 1, open).replace(/\/\*[\s\S]*?\*\//g, '').trim().replace(/\s+/g, ' ');
if (!raw || raw.startsWith('@') || /^\d/.test(raw) || /[{}<]/.test(raw)) return null;
// Keyframe steps: percentage steps fail the digit test above, but `from`
@@ -5293,14 +5296,17 @@ function checkTypography() {
}
if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
+ // Report the actual primary face: the uniquely most-used family. The old
+ // 15% threshold labeled secondary faces as primary (e.g. an 82/18 split).
+ const ranked = [...fontUsage.entries()].sort((a, b) => b[1] - a[1]);
+ const [primary] = ranked;
+ const tied = ranked[1]?.[1] === primary?.[1];
+ if (primary && !tied) {
+ const [font, count] = primary;
const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ if (OVERUSED_FONTS.has(font) && !isBrandFontOnOwnDomain(font)) {
+ findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ }
}
}
@@ -8126,14 +8132,17 @@ if (IS_BROWSER) {
isHidden: isElementHidden(el),
findings: findings.map(f => {
const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
+ const severity = f.severity || ap?.severity || 'warning';
return {
type: f.type || f.id,
category: ap ? ap.category : 'quality',
- severity: f.severity || ap?.severity || 'warning',
+ severity,
// Advisory findings (em-dash overuse, etc.) are surfaced but never
// treated as failures; carry the flag so the overlay/extension can
// render them with the mildest affordance and consumers can filter.
- advisory: (ap && ap.advisory === true) || f.advisory === true,
+ // Per-finding promotions override the registry default, so derive
+ // this strictly from the effective severity.
+ advisory: severity === 'advisory',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
@@ -8175,6 +8184,381 @@ if (IS_BROWSER) {
else groupMap.set(el, [...kept]);
}
+ function pseudoElementHostSelector(selector) {
+ const raw = String(selector || '');
+ const legacyNames = new Set(['before', 'after', 'first-letter', 'first-line']);
+ const isNameChar = char => /[a-zA-Z0-9_-]/.test(char || '');
+ const consumeFunction = (start) => {
+ let depth = 0;
+ let quote = '';
+ for (let i = start; i < raw.length; i += 1) {
+ const char = raw[i];
+ if (char === '\\') {
+ i += 1;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '(') depth += 1;
+ if (char === ')' && --depth === 0) return i + 1;
+ }
+ return raw.length;
+ };
+
+ let output = '';
+ let found = false;
+ for (let i = 0; i < raw.length;) {
+ const char = raw[i];
+ if (char === '\\') {
+ output += raw.slice(i, Math.min(raw.length, i + 2));
+ i += 2;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ const quote = char;
+ const start = i;
+ i += 1;
+ while (i < raw.length) {
+ if (raw[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ const value = raw[i];
+ i += 1;
+ if (value === quote) break;
+ }
+ output += raw.slice(start, i);
+ continue;
+ }
+ if (char !== ':') {
+ output += char;
+ i += 1;
+ continue;
+ }
+
+ let end = i + 1;
+ let isPseudoElement = false;
+ if (raw[end] === ':') {
+ end += 1;
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = end > nameStart;
+ } else {
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = legacyNames.has(raw.slice(nameStart, end).toLowerCase());
+ }
+ if (!isPseudoElement) {
+ output += char;
+ i += 1;
+ continue;
+ }
+ if (raw[end] === '(') end = consumeFunction(end);
+ found = true;
+ if (!output || /[\s>+~,]/.test(output[output.length - 1])) output += '*';
+ i = end;
+ }
+ if (!found) return null;
+ return output.trim().replace(/,\s*(?=,|$)/g, '');
+ }
+
+ function selectorNodesForLiveDom(root, selector) {
+ const raw = String(selector || '').trim();
+ if (!raw) return null;
+ const fallback = pseudoElementHostSelector(raw);
+ if (fallback == null) {
+ // An empty result from a valid full selector is authoritative. In
+ // particular, do not broaden inactive :hover/:focus/:not() rules to
+ // their host element by stripping pseudo-classes.
+ try { return Array.from(root.querySelectorAll(raw)); }
+ catch { return null; }
+ }
+
+ // Resolve pseudo-elements to their originating live elements. An attached
+ // pseudo-element (`.card::before`) belongs to the element before it, while
+ // a hostless pseudo-element after a combinator (`main > ::before`) belongs
+ // to a matching element at that position (`main > *`). Replacing every
+ // pseudo indiscriminately with an empty string leaves the latter as the
+ // invalid selector `main >` and makes absent hosts indistinguishable from
+ // selectors the DOM API cannot parse.
+ if (!fallback || /^[,\s]*$/.test(fallback)) return null;
+ try { return Array.from(root.querySelectorAll(fallback)); }
+ catch { return null; }
+ }
+
+ let containerProbeSequence = 0;
+
+ function isContainerCssRule(rule) {
+ return rule?.constructor?.name === 'CSSContainerRule'
+ || /^\s*@container\b/i.test(rule?.cssText || '');
+ }
+
+ function styleRuleAppliesToLiveMatches(rule, matches) {
+ const style = rule?.style;
+ if (!style || !matches?.length || typeof getComputedStyle !== 'function') return false;
+ const sequence = ++containerProbeSequence;
+ const property = `--impeccable-container-probe-${sequence}-${Math.random().toString(36).slice(2)}`;
+ const value = `impeccable-container-active-${sequence}`;
+ const previousValue = style.getPropertyValue(property);
+ const previousPriority = style.getPropertyPriority(property);
+ try {
+ style.setProperty(property, value, 'important');
+ } catch {
+ return false;
+ }
+
+ const pseudoElements = [...new Set(
+ String(rule.selectorText || '').match(/::[a-zA-Z-]+(?:\([^)]*\))?/g) || [],
+ )];
+ try {
+ return matches.some(el => [null, ...pseudoElements].some(pseudo => {
+ try {
+ const computed = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el);
+ return computed.getPropertyValue(property).trim() === value;
+ } catch {
+ return false;
+ }
+ }));
+ } finally {
+ if (previousValue) style.setProperty(property, previousValue, previousPriority);
+ else style.removeProperty(property);
+ }
+ }
+
+ function conditionalCssRuleIsActive(rule) {
+ const type = Number(rule?.type);
+ const constructorName = rule?.constructor?.name || '';
+ if (constructorName === 'CSSMediaRule' || type === 4) {
+ const condition = rule.conditionText || rule.media?.mediaText || '';
+ if (!condition || typeof window.matchMedia !== 'function') return true;
+ try { return window.matchMedia(condition).matches; }
+ catch { return true; }
+ }
+ if (constructorName === 'CSSSupportsRule' || type === 12) {
+ const condition = rule.conditionText || '';
+ if (!condition || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return true;
+ try { return CSS.supports(condition); }
+ catch { return true; }
+ }
+ return true;
+ }
+
+ function splitCssCommaList(value) {
+ const parts = [];
+ let current = '';
+ let quote = '';
+ let escaped = false;
+ for (const char of String(value || '')) {
+ if (escaped) {
+ current += char;
+ escaped = false;
+ continue;
+ }
+ if (char === '\\') {
+ current += char;
+ escaped = true;
+ continue;
+ }
+ if (quote) {
+ current += char;
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ current += char;
+ continue;
+ }
+ if (char === ',') {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+ return parts;
+ }
+
+ function normalizeAnimationName(value) {
+ const name = String(value || '').trim();
+ if (name.length >= 2 && name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) {
+ return name.slice(1, -1);
+ }
+ return name;
+ }
+
+ function animationNamesDeclaredByRule(rule) {
+ const style = rule?.style;
+ if (!style) return [];
+ let value = '';
+ try {
+ value = style.animationName
+ || style.getPropertyValue?.('animation-name')
+ || style.webkitAnimationName
+ || style.getPropertyValue?.('-webkit-animation-name')
+ || '';
+ } catch {
+ return [];
+ }
+ return splitCssCommaList(value)
+ .map(normalizeAnimationName)
+ .filter(name => name && name.toLowerCase() !== 'none');
+ }
+
+ function keyframesRuleName(rule, cssText) {
+ const constructorName = rule?.constructor?.name || '';
+ const type = Number(rule?.type);
+ const isKeyframes = constructorName === 'CSSKeyframesRule'
+ || constructorName === 'WebKitCSSKeyframesRule'
+ || type === 7
+ || /^\s*@(?:-webkit-)?keyframes\b/i.test(cssText);
+ if (!isKeyframes) return '';
+ const match = String(cssText || '').match(/^\s*@(?:-webkit-)?keyframes\s+([^\s{]+)/i);
+ return normalizeAnimationName(rule?.name || match?.[1] || '');
+ }
+
+ function cssPropertyName(property) {
+ if (property.startsWith('--')) return property;
+ return property.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
+ }
+
+ function resolvedAnimationKeyframes(candidateNames) {
+ if (typeof document.getAnimations !== 'function') return null;
+ let animations;
+ try { animations = document.getAnimations(); }
+ catch { return null; }
+
+ const resolved = new Map();
+ const metadata = new Set(['offset', 'computedOffset', 'easing', 'composite']);
+ for (const animation of animations) {
+ const name = normalizeAnimationName(animation?.animationName || '');
+ if (!name || !candidateNames.has(name) || resolved.has(name)) continue;
+ let frames;
+ try { frames = animation.effect?.getKeyframes?.() || []; }
+ catch { continue; }
+ const blocks = [];
+ for (const frame of frames) {
+ const rawOffset = Number.isFinite(frame.computedOffset) ? frame.computedOffset : frame.offset;
+ if (!Number.isFinite(rawOffset)) continue;
+ const offset = Math.round(rawOffset * 1000000) / 10000;
+ const declarations = Object.entries(frame)
+ .filter(([property, value]) => !metadata.has(property) && value != null && value !== '')
+ .map(([property, value]) => `${cssPropertyName(property)}: ${value};`);
+ const easing = String(frame.easing || '').trim();
+ if (easing && easing.toLowerCase() !== 'linear') {
+ declarations.push(`animation-timing-function: ${easing};`);
+ }
+ if (declarations.length === 0) continue;
+ blocks.push(`${offset}% { ${declarations.join(' ')} }`);
+ }
+ if (blocks.length > 0) resolved.set(name, `@keyframes ${name} { ${blocks.join(' ')} }`);
+ }
+ return resolved;
+ }
+
+ // Read CSS that is absent from document.outerHTML. Inline <style> blocks are
+ // already present in the HTML pattern corpus, so limit this walk to linked
+ // stylesheets. Flatten grouping rules so each declaration keeps its selector,
+ // and admit only selector rules that target the live DOM. That prevents
+ // unused utilities from feeding both selector-scoped and page-level checks.
+ // Same-origin CSS and readable CORS sheets participate; browser security
+ // exceptions for cross-origin sheets are expected and skipped.
+ function linkedStylesheetText() {
+ const parts = [];
+ const seen = new Set();
+ const animationNames = new Set();
+ const keyframeCandidates = new Map();
+ const appendRules = (rules, requiresAppliedMatch = false) => {
+ for (const rule of rules) {
+ if (rule.styleSheet) {
+ appendSheet(rule.styleSheet);
+ continue;
+ }
+ const cssText = rule.cssText || '';
+ if (rule.selectorText) {
+ const matches = selectorNodesForLiveDom(document, rule.selectorText);
+ // Only declarations with a resolvable live host enter the corpus.
+ // Unresolvable selectors are uncertain, not evidence that a pattern
+ // rendered, and retaining them would leak unused CSS into findings.
+ if (
+ matches?.length > 0
+ && (!requiresAppliedMatch || styleRuleAppliesToLiveMatches(rule, matches))
+ ) {
+ parts.push(cssText);
+ for (const name of animationNamesDeclaredByRule(rule)) animationNames.add(name);
+ }
+ continue;
+ }
+ let nested = [];
+ let hasNestedRules = false;
+ try {
+ const ruleList = rule.cssRules;
+ hasNestedRules = ruleList != null;
+ nested = Array.from(ruleList || []);
+ } catch {
+ continue;
+ }
+ const keyframesName = keyframesRuleName(rule, cssText);
+ if (keyframesName) {
+ // Keyframes do not merge: when a name is defined more than once, the
+ // later effective definition replaces the earlier one.
+ keyframeCandidates.set(keyframesName, {
+ name: keyframesName,
+ cssText,
+ });
+ continue;
+ }
+ if (hasNestedRules) {
+ if (!conditionalCssRuleIsActive(rule)) continue;
+ appendRules(nested, requiresAppliedMatch || isContainerCssRule(rule));
+ continue;
+ }
+ // Other selector-less leaf at-rules cannot be tied to a rendered node.
+ }
+ };
+ const appendSheet = (sheet) => {
+ if (!sheet || seen.has(sheet)) return;
+ seen.add(sheet);
+ let rules;
+ try { rules = Array.from(sheet.cssRules || sheet.rules || []); }
+ catch { return; }
+ appendRules(rules);
+ };
+ let sheets;
+ try { sheets = Array.from(document.styleSheets || []); }
+ catch { return ''; }
+ for (const sheet of sheets) {
+ const owner = sheet.ownerNode;
+ if (owner?.tagName?.toLowerCase() !== 'link') continue;
+ if (!/\bstylesheet\b/i.test(owner.getAttribute?.('rel') || '')) continue;
+ appendSheet(sheet);
+ }
+ // Motion checks need the effective body of a live animation's keyframes.
+ // Let the browser resolve duplicate names across source order, imports,
+ // conditional groups, and cascade layers, then serialize those computed
+ // frames back into the pattern corpus. Browsers also make container-nested
+ // keyframes globally available, so lexical grouping is not a reliable
+ // activity signal. When the Web Animations API is unavailable, fall back to
+ // the last source-order definition referenced by a retained linked rule.
+ const resolvedKeyframes = resolvedAnimationKeyframes(new Set(keyframeCandidates.keys()));
+ if (resolvedKeyframes) {
+ parts.push(...resolvedKeyframes.values());
+ } else {
+ for (const candidate of keyframeCandidates.values()) {
+ if (!animationNames.has(candidate.name)) continue;
+ parts.push(candidate.cssText);
+ }
+ }
+ return parts.join('\n');
+ }
+
function browserFindingsFromMap(groupMap) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
@@ -8548,18 +8932,16 @@ if (IS_BROWSER) {
// (the CSS ships here, but the pattern never renders — the live DOM is
// ground truth in the browser), and a match under a data-impeccable-ignore
// ancestor is waived. Selector-less findings stay page-level.
- const scopedHtmlFindings = checkHtmlPatterns(docClone.outerHTML).filter(f => {
+ const html = docClone.outerHTML;
+ const corpora = buildHtmlPatternCorpora(html);
+ const linkedCss = linkedStylesheetText();
+ if (linkedCss) corpora.styleText += `\n${linkedCss}`;
+ const scopedHtmlFindings = checkHtmlPatterns(html, corpora).filter(f => {
if (!f.selector) return true;
- const query = String(f.selector).replace(/::?[a-zA-Z-]+(\([^)]*\))?/g, '').trim().replace(/,\s*(?=,|$)/g, '');
- if (!query || /^[,\s]*$/.test(query)) return true;
- let matches;
- try {
- matches = document.querySelectorAll(query);
- } catch {
- return true;
- }
+ const matches = selectorNodesForLiveDom(document, f.selector);
+ if (!matches) return false;
if (matches.length === 0) return false;
- return [...matches].some(el => !scopedIgnoreActive(el, f.id));
+ return matches.some(el => !scopedIgnoreActive(el, f.id));
});
if (scopedHtmlFindings.length > 0) {
const mapped = scopedHtmlFindings.map(f => {
diff --git a/.cursor/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs b/.cursor/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
index f3ff43c84..ac4bd0a7c 100644
--- a/.cursor/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
+++ b/.cursor/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
@@ -2,7 +2,7 @@ import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { finding } from '../../findings.mjs';
+import { deriveAdvisoryFlag, finding } from '../../findings.mjs';
import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
import { checkContentHiddenAtRest } from '../../rules/checks.mjs';
@@ -394,7 +394,7 @@ async function detectUrl(rawUrl, options = {}) {
// Per-finding severity promotion (e.g. hero-region pulsing dot)
// overrides the registry default carried by finding().
if (f.severity && f.severity !== item.severity) item.severity = f.severity;
- return item;
+ return deriveAdvisoryFlag(item);
});
}
diff --git a/.cursor/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs b/.cursor/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
index 84e6ab1f5..dac6939b0 100644
--- a/.cursor/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
+++ b/.cursor/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
@@ -9,7 +9,7 @@ import {
} from '../../design-system.mjs';
import { isFullPage } from '../../shared/page.mjs';
import { applyInlineIgnores } from '../../shared/inline-ignores.mjs';
-import { finding } from '../../findings.mjs';
+import { deriveAdvisoryFlag, finding } from '../../findings.mjs';
import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import {
checkElementBorders,
@@ -257,7 +257,7 @@ async function detectHtml(filePath, options = {}) {
// severity (e.g. a pulsing dot inside a header/nav landmark) that
// overrides the registry default.
if (f.severity) item.severity = f.severity;
- findings.push(item);
+ findings.push(deriveAdvisoryFlag(item));
}
// Text-content analyzers (em-dash overuse, marketing buzzwords,
// numbered section markers, aphoristic cadence) live in the regex
diff --git a/.cursor/skills/impeccable/scripts/detector/findings.mjs b/.cursor/skills/impeccable/scripts/detector/findings.mjs
index fa98dd935..ae7e134f9 100644
--- a/.cursor/skills/impeccable/scripts/detector/findings.mjs
+++ b/.cursor/skills/impeccable/scripts/detector/findings.mjs
@@ -4,6 +4,12 @@ function getAP(id) {
return getAntipattern(id);
}
+function deriveAdvisoryFlag(item) {
+ if (item.severity === 'advisory') item.advisory = true;
+ else delete item.advisory;
+ return item;
+}
+
function finding(id, filePath, snippet, line = 0) {
const ap = getAP(id);
const base = { antipattern: id, name: ap.name, description: ap.description, severity: ap.severity || 'warning', category: ap.category || null, file: filePath, line, snippet };
@@ -11,8 +17,7 @@ function finding(id, filePath, snippet, line = 0) {
// failures. Carry the flag on the finding so every consumer (CLI, JSON, hook)
// can partition without a registry lookup. Only stamped when true to keep the
// finding shape stable for the vast majority of rules.
- if (ap.advisory === true) base.advisory = true;
- return base;
+ return deriveAdvisoryFlag(base);
}
-export { getAP, finding };
+export { getAP, finding, deriveAdvisoryFlag };
diff --git a/.cursor/skills/impeccable/scripts/detector/registry/antipatterns.mjs b/.cursor/skills/impeccable/scripts/detector/registry/antipatterns.mjs
index 945307783..7c692c79a 100644
--- a/.cursor/skills/impeccable/scripts/detector/registry/antipatterns.mjs
+++ b/.cursor/skills/impeccable/scripts/detector/registry/antipatterns.mjs
@@ -233,7 +233,7 @@ const ANTIPATTERNS = [
// rather than a failure. It fires only on the AI saturation pattern, not on
// ordinary prose. Advisory findings are surfaced separately, never counted
// as failures, and skipped by the design hook unless a project opts in.
- advisory: true,
+ severity: 'advisory',
name: 'Em-dash overuse',
description:
'Em-dash saturation in body copy is an AI cadence tell. Advisory only: humans use em-dashes legitimately, so this fires only on saturation — at least 8 em-dashes (— or --) at a density near one per 500 characters of body text — never on a long article that uses a few. Prefer commas, colons, periods, or parentheses.',
@@ -588,9 +588,10 @@ function getAntipattern(id) {
// Advisory rules are detected and reported, but never treated as failures:
// the CLI lists them under a separate "Advisory" section, they do not affect
// exit codes or the failure count, and the design hook skips them by default.
-// The set is derived from the registry so a rule only needs `advisory: true`.
+// `severity` is the canonical registry field. The runtime finding serializer
+// derives its `advisory: true` compatibility/output flag from this set.
const ADVISORY_RULE_IDS = new Set(
- ANTIPATTERNS.filter(rule => rule.advisory === true).map(rule => rule.id),
+ ANTIPATTERNS.filter(rule => rule.severity === 'advisory').map(rule => rule.id),
);
function isAdvisoryRule(id) {
diff --git a/.cursor/skills/impeccable/scripts/detector/rules/checks.mjs b/.cursor/skills/impeccable/scripts/detector/rules/checks.mjs
index 579e1c12e..a24631ce9 100644
--- a/.cursor/skills/impeccable/scripts/detector/rules/checks.mjs
+++ b/.cursor/skills/impeccable/scripts/detector/rules/checks.mjs
@@ -688,7 +688,10 @@ function enclosingCssSelector(cssText, index) {
// `{` belongs to some other selector.
const closeBeforeIndex = cssText.lastIndexOf('}', index);
if (closeBeforeIndex > open) return null;
- const prevClose = Math.max(cssText.lastIndexOf('}', open - 1), cssText.lastIndexOf(';', open - 1));
+ // Ignore delimiters inside comments when locating the previous declaration.
+ // Keeping comment length intact preserves indices into the original source.
+ const beforeOpen = cssText.slice(0, open).replace(/\/\*[\s\S]*?\*\//g, comment => ' '.repeat(comment.length));
+ const prevClose = Math.max(beforeOpen.lastIndexOf('}'), beforeOpen.lastIndexOf(';'));
const raw = cssText.slice(prevClose + 1, open).replace(/\/\*[\s\S]*?\*\//g, '').trim().replace(/\s+/g, ' ');
if (!raw || raw.startsWith('@') || /^\d/.test(raw) || /[{}<]/.test(raw)) return null;
// Keyframe steps: percentage steps fail the digit test above, but `from`
@@ -4020,14 +4023,17 @@ function checkTypography() {
}
if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
+ // Report the actual primary face: the uniquely most-used family. The old
+ // 15% threshold labeled secondary faces as primary (e.g. an 82/18 split).
+ const ranked = [...fontUsage.entries()].sort((a, b) => b[1] - a[1]);
+ const [primary] = ranked;
+ const tied = ranked[1]?.[1] === primary?.[1];
+ if (primary && !tied) {
+ const [font, count] = primary;
const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ if (OVERUSED_FONTS.has(font) && !isBrandFontOnOwnDomain(font)) {
+ findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ }
}
}
diff --git a/.cursor/skills/impeccable/scripts/hook-lib.mjs b/.cursor/skills/impeccable/scripts/hook-lib.mjs
index 767fe65a6..6d8c3db81 100644
--- a/.cursor/skills/impeccable/scripts/hook-lib.mjs
+++ b/.cursor/skills/impeccable/scripts/hook-lib.mjs
@@ -138,17 +138,20 @@ export const IMMEDIATE_TIER_RULES = new Set([
// the agent is never nagged about a taste call a human might make on purpose.
// A project opts back in with `.impeccable/config.json`:
// { "detector": { "advisoryRules": "include" } }
-// This set is the hook's own copy of the registry's `advisory: true` rules,
-// mirroring how IMMEDIATE_TIER_RULES lists rule ids inline so the hook stays
-// self-contained and testable without loading the detector. Keep it in sync
-// with the registry (cli/engine/registry/antipatterns.mjs).
+// This legacy id fallback keeps older detector findings recognizable when they
+// carry neither the current runtime flag nor the canonical advisory severity.
+// Current findings are classified by their serialized metadata below.
export const ADVISORY_RULES = new Set([
'em-dash-overuse',
]);
export function isAdvisoryFinding(finding) {
const id = finding && normalizeIgnoreRule(finding.antipattern);
- return Boolean(id && (ADVISORY_RULES.has(id) || finding.advisory === true));
+ return Boolean(id && (
+ ADVISORY_RULES.has(id)
+ || finding.advisory === true
+ || finding.severity === 'advisory'
+ ));
}
export const DEFAULT_CONFIG = Object.freeze({
diff --git a/.gemini/skills/impeccable/scripts/detector/browser/injected/index.mjs b/.gemini/skills/impeccable/scripts/detector/browser/injected/index.mjs
index febf7f297..76fc558e5 100644
--- a/.gemini/skills/impeccable/scripts/detector/browser/injected/index.mjs
+++ b/.gemini/skills/impeccable/scripts/detector/browser/injected/index.mjs
@@ -1228,14 +1228,17 @@ if (IS_BROWSER) {
isHidden: isElementHidden(el),
findings: findings.map(f => {
const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
+ const severity = f.severity || ap?.severity || 'warning';
return {
type: f.type || f.id,
category: ap ? ap.category : 'quality',
- severity: f.severity || ap?.severity || 'warning',
+ severity,
// Advisory findings (em-dash overuse, etc.) are surfaced but never
// treated as failures; carry the flag so the overlay/extension can
// render them with the mildest affordance and consumers can filter.
- advisory: (ap && ap.advisory === true) || f.advisory === true,
+ // Per-finding promotions override the registry default, so derive
+ // this strictly from the effective severity.
+ advisory: severity === 'advisory',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
@@ -1277,6 +1280,381 @@ if (IS_BROWSER) {
else groupMap.set(el, [...kept]);
}
+ function pseudoElementHostSelector(selector) {
+ const raw = String(selector || '');
+ const legacyNames = new Set(['before', 'after', 'first-letter', 'first-line']);
+ const isNameChar = char => /[a-zA-Z0-9_-]/.test(char || '');
+ const consumeFunction = (start) => {
+ let depth = 0;
+ let quote = '';
+ for (let i = start; i < raw.length; i += 1) {
+ const char = raw[i];
+ if (char === '\\') {
+ i += 1;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '(') depth += 1;
+ if (char === ')' && --depth === 0) return i + 1;
+ }
+ return raw.length;
+ };
+
+ let output = '';
+ let found = false;
+ for (let i = 0; i < raw.length;) {
+ const char = raw[i];
+ if (char === '\\') {
+ output += raw.slice(i, Math.min(raw.length, i + 2));
+ i += 2;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ const quote = char;
+ const start = i;
+ i += 1;
+ while (i < raw.length) {
+ if (raw[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ const value = raw[i];
+ i += 1;
+ if (value === quote) break;
+ }
+ output += raw.slice(start, i);
+ continue;
+ }
+ if (char !== ':') {
+ output += char;
+ i += 1;
+ continue;
+ }
+
+ let end = i + 1;
+ let isPseudoElement = false;
+ if (raw[end] === ':') {
+ end += 1;
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = end > nameStart;
+ } else {
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = legacyNames.has(raw.slice(nameStart, end).toLowerCase());
+ }
+ if (!isPseudoElement) {
+ output += char;
+ i += 1;
+ continue;
+ }
+ if (raw[end] === '(') end = consumeFunction(end);
+ found = true;
+ if (!output || /[\s>+~,]/.test(output[output.length - 1])) output += '*';
+ i = end;
+ }
+ if (!found) return null;
+ return output.trim().replace(/,\s*(?=,|$)/g, '');
+ }
+
+ function selectorNodesForLiveDom(root, selector) {
+ const raw = String(selector || '').trim();
+ if (!raw) return null;
+ const fallback = pseudoElementHostSelector(raw);
+ if (fallback == null) {
+ // An empty result from a valid full selector is authoritative. In
+ // particular, do not broaden inactive :hover/:focus/:not() rules to
+ // their host element by stripping pseudo-classes.
+ try { return Array.from(root.querySelectorAll(raw)); }
+ catch { return null; }
+ }
+
+ // Resolve pseudo-elements to their originating live elements. An attached
+ // pseudo-element (`.card::before`) belongs to the element before it, while
+ // a hostless pseudo-element after a combinator (`main > ::before`) belongs
+ // to a matching element at that position (`main > *`). Replacing every
+ // pseudo indiscriminately with an empty string leaves the latter as the
+ // invalid selector `main >` and makes absent hosts indistinguishable from
+ // selectors the DOM API cannot parse.
+ if (!fallback || /^[,\s]*$/.test(fallback)) return null;
+ try { return Array.from(root.querySelectorAll(fallback)); }
+ catch { return null; }
+ }
+
+ let containerProbeSequence = 0;
+
+ function isContainerCssRule(rule) {
+ return rule?.constructor?.name === 'CSSContainerRule'
+ || /^\s*@container\b/i.test(rule?.cssText || '');
+ }
+
+ function styleRuleAppliesToLiveMatches(rule, matches) {
+ const style = rule?.style;
+ if (!style || !matches?.length || typeof getComputedStyle !== 'function') return false;
+ const sequence = ++containerProbeSequence;
+ const property = `--impeccable-container-probe-${sequence}-${Math.random().toString(36).slice(2)}`;
+ const value = `impeccable-container-active-${sequence}`;
+ const previousValue = style.getPropertyValue(property);
+ const previousPriority = style.getPropertyPriority(property);
+ try {
+ style.setProperty(property, value, 'important');
+ } catch {
+ return false;
+ }
+
+ const pseudoElements = [...new Set(
+ String(rule.selectorText || '').match(/::[a-zA-Z-]+(?:\([^)]*\))?/g) || [],
+ )];
+ try {
+ return matches.some(el => [null, ...pseudoElements].some(pseudo => {
+ try {
+ const computed = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el);
+ return computed.getPropertyValue(property).trim() === value;
+ } catch {
+ return false;
+ }
+ }));
+ } finally {
+ if (previousValue) style.setProperty(property, previousValue, previousPriority);
+ else style.removeProperty(property);
+ }
+ }
+
+ function conditionalCssRuleIsActive(rule) {
+ const type = Number(rule?.type);
+ const constructorName = rule?.constructor?.name || '';
+ if (constructorName === 'CSSMediaRule' || type === 4) {
+ const condition = rule.conditionText || rule.media?.mediaText || '';
+ if (!condition || typeof window.matchMedia !== 'function') return true;
+ try { return window.matchMedia(condition).matches; }
+ catch { return true; }
+ }
+ if (constructorName === 'CSSSupportsRule' || type === 12) {
+ const condition = rule.conditionText || '';
+ if (!condition || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return true;
+ try { return CSS.supports(condition); }
+ catch { return true; }
+ }
+ return true;
+ }
+
+ function splitCssCommaList(value) {
+ const parts = [];
+ let current = '';
+ let quote = '';
+ let escaped = false;
+ for (const char of String(value || '')) {
+ if (escaped) {
+ current += char;
+ escaped = false;
+ continue;
+ }
+ if (char === '\\') {
+ current += char;
+ escaped = true;
+ continue;
+ }
+ if (quote) {
+ current += char;
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ current += char;
+ continue;
+ }
+ if (char === ',') {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+ return parts;
+ }
+
+ function normalizeAnimationName(value) {
+ const name = String(value || '').trim();
+ if (name.length >= 2 && name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) {
+ return name.slice(1, -1);
+ }
+ return name;
+ }
+
+ function animationNamesDeclaredByRule(rule) {
+ const style = rule?.style;
+ if (!style) return [];
+ let value = '';
+ try {
+ value = style.animationName
+ || style.getPropertyValue?.('animation-name')
+ || style.webkitAnimationName
+ || style.getPropertyValue?.('-webkit-animation-name')
+ || '';
+ } catch {
+ return [];
+ }
+ return splitCssCommaList(value)
+ .map(normalizeAnimationName)
+ .filter(name => name && name.toLowerCase() !== 'none');
+ }
+
+ function keyframesRuleName(rule, cssText) {
+ const constructorName = rule?.constructor?.name || '';
+ const type = Number(rule?.type);
+ const isKeyframes = constructorName === 'CSSKeyframesRule'
+ || constructorName === 'WebKitCSSKeyframesRule'
+ || type === 7
+ || /^\s*@(?:-webkit-)?keyframes\b/i.test(cssText);
+ if (!isKeyframes) return '';
+ const match = String(cssText || '').match(/^\s*@(?:-webkit-)?keyframes\s+([^\s{]+)/i);
+ return normalizeAnimationName(rule?.name || match?.[1] || '');
+ }
+
+ function cssPropertyName(property) {
+ if (property.startsWith('--')) return property;
+ return property.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
+ }
+
+ function resolvedAnimationKeyframes(candidateNames) {
+ if (typeof document.getAnimations !== 'function') return null;
+ let animations;
+ try { animations = document.getAnimations(); }
+ catch { return null; }
+
+ const resolved = new Map();
+ const metadata = new Set(['offset', 'computedOffset', 'easing', 'composite']);
+ for (const animation of animations) {
+ const name = normalizeAnimationName(animation?.animationName || '');
+ if (!name || !candidateNames.has(name) || resolved.has(name)) continue;
+ let frames;
+ try { frames = animation.effect?.getKeyframes?.() || []; }
+ catch { continue; }
+ const blocks = [];
+ for (const frame of frames) {
+ const rawOffset = Number.isFinite(frame.computedOffset) ? frame.computedOffset : frame.offset;
+ if (!Number.isFinite(rawOffset)) continue;
+ const offset = Math.round(rawOffset * 1000000) / 10000;
+ const declarations = Object.entries(frame)
+ .filter(([property, value]) => !metadata.has(property) && value != null && value !== '')
+ .map(([property, value]) => `${cssPropertyName(property)}: ${value};`);
+ const easing = String(frame.easing || '').trim();
+ if (easing && easing.toLowerCase() !== 'linear') {
+ declarations.push(`animation-timing-function: ${easing};`);
+ }
+ if (declarations.length === 0) continue;
+ blocks.push(`${offset}% { ${declarations.join(' ')} }`);
+ }
+ if (blocks.length > 0) resolved.set(name, `@keyframes ${name} { ${blocks.join(' ')} }`);
+ }
+ return resolved;
+ }
+
+ // Read CSS that is absent from document.outerHTML. Inline <style> blocks are
+ // already present in the HTML pattern corpus, so limit this walk to linked
+ // stylesheets. Flatten grouping rules so each declaration keeps its selector,
+ // and admit only selector rules that target the live DOM. That prevents
+ // unused utilities from feeding both selector-scoped and page-level checks.
+ // Same-origin CSS and readable CORS sheets participate; browser security
+ // exceptions for cross-origin sheets are expected and skipped.
+ function linkedStylesheetText() {
+ const parts = [];
+ const seen = new Set();
+ const animationNames = new Set();
+ const keyframeCandidates = new Map();
+ const appendRules = (rules, requiresAppliedMatch = false) => {
+ for (const rule of rules) {
+ if (rule.styleSheet) {
+ appendSheet(rule.styleSheet);
+ continue;
+ }
+ const cssText = rule.cssText || '';
+ if (rule.selectorText) {
+ const matches = selectorNodesForLiveDom(document, rule.selectorText);
+ // Only declarations with a resolvable live host enter the corpus.
+ // Unresolvable selectors are uncertain, not evidence that a pattern
+ // rendered, and retaining them would leak unused CSS into findings.
+ if (
+ matches?.length > 0
+ && (!requiresAppliedMatch || styleRuleAppliesToLiveMatches(rule, matches))
+ ) {
+ parts.push(cssText);
+ for (const name of animationNamesDeclaredByRule(rule)) animationNames.add(name);
+ }
+ continue;
+ }
+ let nested = [];
+ let hasNestedRules = false;
+ try {
+ const ruleList = rule.cssRules;
+ hasNestedRules = ruleList != null;
+ nested = Array.from(ruleList || []);
+ } catch {
+ continue;
+ }
+ const keyframesName = keyframesRuleName(rule, cssText);
+ if (keyframesName) {
+ // Keyframes do not merge: when a name is defined more than once, the
+ // later effective definition replaces the earlier one.
+ keyframeCandidates.set(keyframesName, {
+ name: keyframesName,
+ cssText,
+ });
+ continue;
+ }
+ if (hasNestedRules) {
+ if (!conditionalCssRuleIsActive(rule)) continue;
+ appendRules(nested, requiresAppliedMatch || isContainerCssRule(rule));
+ continue;
+ }
+ // Other selector-less leaf at-rules cannot be tied to a rendered node.
+ }
+ };
+ const appendSheet = (sheet) => {
+ if (!sheet || seen.has(sheet)) return;
+ seen.add(sheet);
+ let rules;
+ try { rules = Array.from(sheet.cssRules || sheet.rules || []); }
+ catch { return; }
+ appendRules(rules);
+ };
+ let sheets;
+ try { sheets = Array.from(document.styleSheets || []); }
+ catch { return ''; }
+ for (const sheet of sheets) {
+ const owner = sheet.ownerNode;
+ if (owner?.tagName?.toLowerCase() !== 'link') continue;
+ if (!/\bstylesheet\b/i.test(owner.getAttribute?.('rel') || '')) continue;
+ appendSheet(sheet);
+ }
+ // Motion checks need the effective body of a live animation's keyframes.
+ // Let the browser resolve duplicate names across source order, imports,
+ // conditional groups, and cascade layers, then serialize those computed
+ // frames back into the pattern corpus. Browsers also make container-nested
+ // keyframes globally available, so lexical grouping is not a reliable
+ // activity signal. When the Web Animations API is unavailable, fall back to
+ // the last source-order definition referenced by a retained linked rule.
+ const resolvedKeyframes = resolvedAnimationKeyframes(new Set(keyframeCandidates.keys()));
+ if (resolvedKeyframes) {
+ parts.push(...resolvedKeyframes.values());
+ } else {
+ for (const candidate of keyframeCandidates.values()) {
+ if (!animationNames.has(candidate.name)) continue;
+ parts.push(candidate.cssText);
+ }
+ }
+ return parts.join('\n');
+ }
+
function browserFindingsFromMap(groupMap) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
@@ -1650,18 +2028,16 @@ if (IS_BROWSER) {
// (the CSS ships here, but the pattern never renders — the live DOM is
// ground truth in the browser), and a match under a data-impeccable-ignore
// ancestor is waived. Selector-less findings stay page-level.
- const scopedHtmlFindings = checkHtmlPatterns(docClone.outerHTML).filter(f => {
+ const html = docClone.outerHTML;
+ const corpora = buildHtmlPatternCorpora(html);
+ const linkedCss = linkedStylesheetText();
+ if (linkedCss) corpora.styleText += `\n${linkedCss}`;
+ const scopedHtmlFindings = checkHtmlPatterns(html, corpora).filter(f => {
if (!f.selector) return true;
- const query = String(f.selector).replace(/::?[a-zA-Z-]+(\([^)]*\))?/g, '').trim().replace(/,\s*(?=,|$)/g, '');
- if (!query || /^[,\s]*$/.test(query)) return true;
- let matches;
- try {
- matches = document.querySelectorAll(query);
- } catch {
- return true;
- }
+ const matches = selectorNodesForLiveDom(document, f.selector);
+ if (!matches) return false;
if (matches.length === 0) return false;
- return [...matches].some(el => !scopedIgnoreActive(el, f.id));
+ return matches.some(el => !scopedIgnoreActive(el, f.id));
});
if (scopedHtmlFindings.length > 0) {
const mapped = scopedHtmlFindings.map(f => {
diff --git a/.gemini/skills/impeccable/scripts/detector/cli/main.mjs b/.gemini/skills/impeccable/scripts/detector/cli/main.mjs
index 4476d04f1..3451d6c6b 100644
--- a/.gemini/skills/impeccable/scripts/detector/cli/main.mjs
+++ b/.gemini/skills/impeccable/scripts/detector/cli/main.mjs
@@ -37,13 +37,30 @@ function fileUrlToLocalPath(url) {
}
}
+const URL_TARGET_RE = /^(?:https?|file):\/\//i;
+
+// Some agent runners hand a shell-ready URL list to Node as one argv value.
+// A browser accepts the spaces as part of one encoded URL, producing a
+// plausible scan attributed to a bogus joined path. Expand only when every
+// whitespace-delimited token is independently a URL, preserving ordinary
+// filesystem paths that contain spaces.
+function expandJoinedUrlTargets(targets) {
+ return targets.flatMap((target) => {
+ if (!/\s/.test(target)) return [target];
+ const parts = target.trim().split(/\s+/).filter(Boolean);
+ return parts.length > 1 && parts.every(part => URL_TARGET_RE.test(part))
+ ? parts
+ : [target];
+ });
+}
+
// Advisory findings are detected but never treated as failures: they list in a
// separate, visually dimmed section, are excluded from the failure count that
// drives the exit code, and carry `"advisory": true` in JSON so consumers can
// filter. Every advisory finding carries the flag (stamped by the registry via
// findings.mjs).
function isAdvisory(finding) {
- return finding && finding.advisory === true;
+ return Boolean(finding && (finding.advisory === true || finding.severity === 'advisory'));
}
function partitionAdvisory(findings) {
@@ -168,6 +185,10 @@ Advisory findings:
counted as failures and never changing the exit code. They stay out of the
failure count so they never block automation. --no-advisory hides them.
+Output streams:
+ Human-readable findings go to stderr so stdout stays available for structured
+ output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.
+
Project config:
Respects .impeccable/config.json and .impeccable/config.local.json detector
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
@@ -185,7 +206,7 @@ Detection modes:
HTML files Static HTML/CSS analysis (default, catches linked CSS)
Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)
URLs Puppeteer full browser rendering (auto-detected;
- http(s):// and file:// URLs)
+ http(s):// and file:// URLs; accessible linked CSS included)
Examples:
impeccable detect src/
@@ -283,7 +304,7 @@ async function detectCli() {
const designSystem = loadDesignSystemForTarget(localPath, { cache: designSystemCache });
return designSystem ? { ...baseScanOptions, designSystem } : baseScanOptions;
};
- const targets = args.filter(a => !a.startsWith('--'));
+ const targets = expandJoinedUrlTargets(args.filter(a => !a.startsWith('--')));
if (helpMode) { printUsage(); process.exit(0); }
@@ -297,13 +318,12 @@ async function detectCli() {
// real cascade, real computed styles, real layout. Callers that want a
// browser-grade scan of a local artifact can pass file:///abs/path.html
// instead of the bare path (which stays on the static engine).
- const urlRe = /^(?:https?|file):\/\//i;
- const urlTargetCount = paths.filter(target => urlRe.test(target)).length;
+ const urlTargetCount = paths.filter(target => URL_TARGET_RE.test(target)).length;
const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
try {
for (const target of paths) {
- if (urlRe.test(target)) {
+ if (URL_TARGET_RE.test(target)) {
// A file:// URL points at a local artifact, so its design system
// resolves from that file's project. A remote http(s) URL has no
// local project — it gets base options (no design system), never
diff --git a/.gemini/skills/impeccable/scripts/detector/detect-antipatterns-browser.js b/.gemini/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
index e6899f569..460ffb45b 100644
--- a/.gemini/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
+++ b/.gemini/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
@@ -358,7 +358,7 @@ const ANTIPATTERNS = [
// rather than a failure. It fires only on the AI saturation pattern, not on
// ordinary prose. Advisory findings are surfaced separately, never counted
// as failures, and skipped by the design hook unless a project opts in.
- advisory: true,
+ severity: 'advisory',
name: 'Em-dash overuse',
description:
'Em-dash saturation in body copy is an AI cadence tell. Advisory only: humans use em-dashes legitimately, so this fires only on saturation — at least 8 em-dashes (— or --) at a density near one per 500 characters of body text — never on a long article that uses a few. Prefer commas, colons, periods, or parentheses.',
@@ -1961,7 +1961,10 @@ function enclosingCssSelector(cssText, index) {
// `{` belongs to some other selector.
const closeBeforeIndex = cssText.lastIndexOf('}', index);
if (closeBeforeIndex > open) return null;
- const prevClose = Math.max(cssText.lastIndexOf('}', open - 1), cssText.lastIndexOf(';', open - 1));
+ // Ignore delimiters inside comments when locating the previous declaration.
+ // Keeping comment length intact preserves indices into the original source.
+ const beforeOpen = cssText.slice(0, open).replace(/\/\*[\s\S]*?\*\//g, comment => ' '.repeat(comment.length));
+ const prevClose = Math.max(beforeOpen.lastIndexOf('}'), beforeOpen.lastIndexOf(';'));
const raw = cssText.slice(prevClose + 1, open).replace(/\/\*[\s\S]*?\*\//g, '').trim().replace(/\s+/g, ' ');
if (!raw || raw.startsWith('@') || /^\d/.test(raw) || /[{}<]/.test(raw)) return null;
// Keyframe steps: percentage steps fail the digit test above, but `from`
@@ -5293,14 +5296,17 @@ function checkTypography() {
}
if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
+ // Report the actual primary face: the uniquely most-used family. The old
+ // 15% threshold labeled secondary faces as primary (e.g. an 82/18 split).
+ const ranked = [...fontUsage.entries()].sort((a, b) => b[1] - a[1]);
+ const [primary] = ranked;
+ const tied = ranked[1]?.[1] === primary?.[1];
+ if (primary && !tied) {
+ const [font, count] = primary;
const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ if (OVERUSED_FONTS.has(font) && !isBrandFontOnOwnDomain(font)) {
+ findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ }
}
}
@@ -8126,14 +8132,17 @@ if (IS_BROWSER) {
isHidden: isElementHidden(el),
findings: findings.map(f => {
const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
+ const severity = f.severity || ap?.severity || 'warning';
return {
type: f.type || f.id,
category: ap ? ap.category : 'quality',
- severity: f.severity || ap?.severity || 'warning',
+ severity,
// Advisory findings (em-dash overuse, etc.) are surfaced but never
// treated as failures; carry the flag so the overlay/extension can
// render them with the mildest affordance and consumers can filter.
- advisory: (ap && ap.advisory === true) || f.advisory === true,
+ // Per-finding promotions override the registry default, so derive
+ // this strictly from the effective severity.
+ advisory: severity === 'advisory',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
@@ -8175,6 +8184,381 @@ if (IS_BROWSER) {
else groupMap.set(el, [...kept]);
}
+ function pseudoElementHostSelector(selector) {
+ const raw = String(selector || '');
+ const legacyNames = new Set(['before', 'after', 'first-letter', 'first-line']);
+ const isNameChar = char => /[a-zA-Z0-9_-]/.test(char || '');
+ const consumeFunction = (start) => {
+ let depth = 0;
+ let quote = '';
+ for (let i = start; i < raw.length; i += 1) {
+ const char = raw[i];
+ if (char === '\\') {
+ i += 1;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '(') depth += 1;
+ if (char === ')' && --depth === 0) return i + 1;
+ }
+ return raw.length;
+ };
+
+ let output = '';
+ let found = false;
+ for (let i = 0; i < raw.length;) {
+ const char = raw[i];
+ if (char === '\\') {
+ output += raw.slice(i, Math.min(raw.length, i + 2));
+ i += 2;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ const quote = char;
+ const start = i;
+ i += 1;
+ while (i < raw.length) {
+ if (raw[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ const value = raw[i];
+ i += 1;
+ if (value === quote) break;
+ }
+ output += raw.slice(start, i);
+ continue;
+ }
+ if (char !== ':') {
+ output += char;
+ i += 1;
+ continue;
+ }
+
+ let end = i + 1;
+ let isPseudoElement = false;
+ if (raw[end] === ':') {
+ end += 1;
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = end > nameStart;
+ } else {
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = legacyNames.has(raw.slice(nameStart, end).toLowerCase());
+ }
+ if (!isPseudoElement) {
+ output += char;
+ i += 1;
+ continue;
+ }
+ if (raw[end] === '(') end = consumeFunction(end);
+ found = true;
+ if (!output || /[\s>+~,]/.test(output[output.length - 1])) output += '*';
+ i = end;
+ }
+ if (!found) return null;
+ return output.trim().replace(/,\s*(?=,|$)/g, '');
+ }
+
+ function selectorNodesForLiveDom(root, selector) {
+ const raw = String(selector || '').trim();
+ if (!raw) return null;
+ const fallback = pseudoElementHostSelector(raw);
+ if (fallback == null) {
+ // An empty result from a valid full selector is authoritative. In
+ // particular, do not broaden inactive :hover/:focus/:not() rules to
+ // their host element by stripping pseudo-classes.
+ try { return Array.from(root.querySelectorAll(raw)); }
+ catch { return null; }
+ }
+
+ // Resolve pseudo-elements to their originating live elements. An attached
+ // pseudo-element (`.card::before`) belongs to the element before it, while
+ // a hostless pseudo-element after a combinator (`main > ::before`) belongs
+ // to a matching element at that position (`main > *`). Replacing every
+ // pseudo indiscriminately with an empty string leaves the latter as the
+ // invalid selector `main >` and makes absent hosts indistinguishable from
+ // selectors the DOM API cannot parse.
+ if (!fallback || /^[,\s]*$/.test(fallback)) return null;
+ try { return Array.from(root.querySelectorAll(fallback)); }
+ catch { return null; }
+ }
+
+ let containerProbeSequence = 0;
+
+ function isContainerCssRule(rule) {
+ return rule?.constructor?.name === 'CSSContainerRule'
+ || /^\s*@container\b/i.test(rule?.cssText || '');
+ }
+
+ function styleRuleAppliesToLiveMatches(rule, matches) {
+ const style = rule?.style;
+ if (!style || !matches?.length || typeof getComputedStyle !== 'function') return false;
+ const sequence = ++containerProbeSequence;
+ const property = `--impeccable-container-probe-${sequence}-${Math.random().toString(36).slice(2)}`;
+ const value = `impeccable-container-active-${sequence}`;
+ const previousValue = style.getPropertyValue(property);
+ const previousPriority = style.getPropertyPriority(property);
+ try {
+ style.setProperty(property, value, 'important');
+ } catch {
+ return false;
+ }
+
+ const pseudoElements = [...new Set(
+ String(rule.selectorText || '').match(/::[a-zA-Z-]+(?:\([^)]*\))?/g) || [],
+ )];
+ try {
+ return matches.some(el => [null, ...pseudoElements].some(pseudo => {
+ try {
+ const computed = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el);
+ return computed.getPropertyValue(property).trim() === value;
+ } catch {
+ return false;
+ }
+ }));
+ } finally {
+ if (previousValue) style.setProperty(property, previousValue, previousPriority);
+ else style.removeProperty(property);
+ }
+ }
+
+ function conditionalCssRuleIsActive(rule) {
+ const type = Number(rule?.type);
+ const constructorName = rule?.constructor?.name || '';
+ if (constructorName === 'CSSMediaRule' || type === 4) {
+ const condition = rule.conditionText || rule.media?.mediaText || '';
+ if (!condition || typeof window.matchMedia !== 'function') return true;
+ try { return window.matchMedia(condition).matches; }
+ catch { return true; }
+ }
+ if (constructorName === 'CSSSupportsRule' || type === 12) {
+ const condition = rule.conditionText || '';
+ if (!condition || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return true;
+ try { return CSS.supports(condition); }
+ catch { return true; }
+ }
+ return true;
+ }
+
+ function splitCssCommaList(value) {
+ const parts = [];
+ let current = '';
+ let quote = '';
+ let escaped = false;
+ for (const char of String(value || '')) {
+ if (escaped) {
+ current += char;
+ escaped = false;
+ continue;
+ }
+ if (char === '\\') {
+ current += char;
+ escaped = true;
+ continue;
+ }
+ if (quote) {
+ current += char;
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ current += char;
+ continue;
+ }
+ if (char === ',') {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+ return parts;
+ }
+
+ function normalizeAnimationName(value) {
+ const name = String(value || '').trim();
+ if (name.length >= 2 && name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) {
+ return name.slice(1, -1);
+ }
+ return name;
+ }
+
+ function animationNamesDeclaredByRule(rule) {
+ const style = rule?.style;
+ if (!style) return [];
+ let value = '';
+ try {
+ value = style.animationName
+ || style.getPropertyValue?.('animation-name')
+ || style.webkitAnimationName
+ || style.getPropertyValue?.('-webkit-animation-name')
+ || '';
+ } catch {
+ return [];
+ }
+ return splitCssCommaList(value)
+ .map(normalizeAnimationName)
+ .filter(name => name && name.toLowerCase() !== 'none');
+ }
+
+ function keyframesRuleName(rule, cssText) {
+ const constructorName = rule?.constructor?.name || '';
+ const type = Number(rule?.type);
+ const isKeyframes = constructorName === 'CSSKeyframesRule'
+ || constructorName === 'WebKitCSSKeyframesRule'
+ || type === 7
+ || /^\s*@(?:-webkit-)?keyframes\b/i.test(cssText);
+ if (!isKeyframes) return '';
+ const match = String(cssText || '').match(/^\s*@(?:-webkit-)?keyframes\s+([^\s{]+)/i);
+ return normalizeAnimationName(rule?.name || match?.[1] || '');
+ }
+
+ function cssPropertyName(property) {
+ if (property.startsWith('--')) return property;
+ return property.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
+ }
+
+ function resolvedAnimationKeyframes(candidateNames) {
+ if (typeof document.getAnimations !== 'function') return null;
+ let animations;
+ try { animations = document.getAnimations(); }
+ catch { return null; }
+
+ const resolved = new Map();
+ const metadata = new Set(['offset', 'computedOffset', 'easing', 'composite']);
+ for (const animation of animations) {
+ const name = normalizeAnimationName(animation?.animationName || '');
+ if (!name || !candidateNames.has(name) || resolved.has(name)) continue;
+ let frames;
+ try { frames = animation.effect?.getKeyframes?.() || []; }
+ catch { continue; }
+ const blocks = [];
+ for (const frame of frames) {
+ const rawOffset = Number.isFinite(frame.computedOffset) ? frame.computedOffset : frame.offset;
+ if (!Number.isFinite(rawOffset)) continue;
+ const offset = Math.round(rawOffset * 1000000) / 10000;
+ const declarations = Object.entries(frame)
+ .filter(([property, value]) => !metadata.has(property) && value != null && value !== '')
+ .map(([property, value]) => `${cssPropertyName(property)}: ${value};`);
+ const easing = String(frame.easing || '').trim();
+ if (easing && easing.toLowerCase() !== 'linear') {
+ declarations.push(`animation-timing-function: ${easing};`);
+ }
+ if (declarations.length === 0) continue;
+ blocks.push(`${offset}% { ${declarations.join(' ')} }`);
+ }
+ if (blocks.length > 0) resolved.set(name, `@keyframes ${name} { ${blocks.join(' ')} }`);
+ }
+ return resolved;
+ }
+
+ // Read CSS that is absent from document.outerHTML. Inline <style> blocks are
+ // already present in the HTML pattern corpus, so limit this walk to linked
+ // stylesheets. Flatten grouping rules so each declaration keeps its selector,
+ // and admit only selector rules that target the live DOM. That prevents
+ // unused utilities from feeding both selector-scoped and page-level checks.
+ // Same-origin CSS and readable CORS sheets participate; browser security
+ // exceptions for cross-origin sheets are expected and skipped.
+ function linkedStylesheetText() {
+ const parts = [];
+ const seen = new Set();
+ const animationNames = new Set();
+ const keyframeCandidates = new Map();
+ const appendRules = (rules, requiresAppliedMatch = false) => {
+ for (const rule of rules) {
+ if (rule.styleSheet) {
+ appendSheet(rule.styleSheet);
+ continue;
+ }
+ const cssText = rule.cssText || '';
+ if (rule.selectorText) {
+ const matches = selectorNodesForLiveDom(document, rule.selectorText);
+ // Only declarations with a resolvable live host enter the corpus.
+ // Unresolvable selectors are uncertain, not evidence that a pattern
+ // rendered, and retaining them would leak unused CSS into findings.
+ if (
+ matches?.length > 0
+ && (!requiresAppliedMatch || styleRuleAppliesToLiveMatches(rule, matches))
+ ) {
+ parts.push(cssText);
+ for (const name of animationNamesDeclaredByRule(rule)) animationNames.add(name);
+ }
+ continue;
+ }
+ let nested = [];
+ let hasNestedRules = false;
+ try {
+ const ruleList = rule.cssRules;
+ hasNestedRules = ruleList != null;
+ nested = Array.from(ruleList || []);
+ } catch {
+ continue;
+ }
+ const keyframesName = keyframesRuleName(rule, cssText);
+ if (keyframesName) {
+ // Keyframes do not merge: when a name is defined more than once, the
+ // later effective definition replaces the earlier one.
+ keyframeCandidates.set(keyframesName, {
+ name: keyframesName,
+ cssText,
+ });
+ continue;
+ }
+ if (hasNestedRules) {
+ if (!conditionalCssRuleIsActive(rule)) continue;
+ appendRules(nested, requiresAppliedMatch || isContainerCssRule(rule));
+ continue;
+ }
+ // Other selector-less leaf at-rules cannot be tied to a rendered node.
+ }
+ };
+ const appendSheet = (sheet) => {
+ if (!sheet || seen.has(sheet)) return;
+ seen.add(sheet);
+ let rules;
+ try { rules = Array.from(sheet.cssRules || sheet.rules || []); }
+ catch { return; }
+ appendRules(rules);
+ };
+ let sheets;
+ try { sheets = Array.from(document.styleSheets || []); }
+ catch { return ''; }
+ for (const sheet of sheets) {
+ const owner = sheet.ownerNode;
+ if (owner?.tagName?.toLowerCase() !== 'link') continue;
+ if (!/\bstylesheet\b/i.test(owner.getAttribute?.('rel') || '')) continue;
+ appendSheet(sheet);
+ }
+ // Motion checks need the effective body of a live animation's keyframes.
+ // Let the browser resolve duplicate names across source order, imports,
+ // conditional groups, and cascade layers, then serialize those computed
+ // frames back into the pattern corpus. Browsers also make container-nested
+ // keyframes globally available, so lexical grouping is not a reliable
+ // activity signal. When the Web Animations API is unavailable, fall back to
+ // the last source-order definition referenced by a retained linked rule.
+ const resolvedKeyframes = resolvedAnimationKeyframes(new Set(keyframeCandidates.keys()));
+ if (resolvedKeyframes) {
+ parts.push(...resolvedKeyframes.values());
+ } else {
+ for (const candidate of keyframeCandidates.values()) {
+ if (!animationNames.has(candidate.name)) continue;
+ parts.push(candidate.cssText);
+ }
+ }
+ return parts.join('\n');
+ }
+
function browserFindingsFromMap(groupMap) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
@@ -8548,18 +8932,16 @@ if (IS_BROWSER) {
// (the CSS ships here, but the pattern never renders — the live DOM is
// ground truth in the browser), and a match under a data-impeccable-ignore
// ancestor is waived. Selector-less findings stay page-level.
- const scopedHtmlFindings = checkHtmlPatterns(docClone.outerHTML).filter(f => {
+ const html = docClone.outerHTML;
+ const corpora = buildHtmlPatternCorpora(html);
+ const linkedCss = linkedStylesheetText();
+ if (linkedCss) corpora.styleText += `\n${linkedCss}`;
+ const scopedHtmlFindings = checkHtmlPatterns(html, corpora).filter(f => {
if (!f.selector) return true;
- const query = String(f.selector).replace(/::?[a-zA-Z-]+(\([^)]*\))?/g, '').trim().replace(/,\s*(?=,|$)/g, '');
- if (!query || /^[,\s]*$/.test(query)) return true;
- let matches;
- try {
- matches = document.querySelectorAll(query);
- } catch {
- return true;
- }
+ const matches = selectorNodesForLiveDom(document, f.selector);
+ if (!matches) return false;
if (matches.length === 0) return false;
- return [...matches].some(el => !scopedIgnoreActive(el, f.id));
+ return matches.some(el => !scopedIgnoreActive(el, f.id));
});
if (scopedHtmlFindings.length > 0) {
const mapped = scopedHtmlFindings.map(f => {
diff --git a/.gemini/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs b/.gemini/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
index f3ff43c84..ac4bd0a7c 100644
--- a/.gemini/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
+++ b/.gemini/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
@@ -2,7 +2,7 @@ import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { finding } from '../../findings.mjs';
+import { deriveAdvisoryFlag, finding } from '../../findings.mjs';
import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
import { checkContentHiddenAtRest } from '../../rules/checks.mjs';
@@ -394,7 +394,7 @@ async function detectUrl(rawUrl, options = {}) {
// Per-finding severity promotion (e.g. hero-region pulsing dot)
// overrides the registry default carried by finding().
if (f.severity && f.severity !== item.severity) item.severity = f.severity;
- return item;
+ return deriveAdvisoryFlag(item);
});
}
diff --git a/.gemini/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs b/.gemini/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
index 84e6ab1f5..dac6939b0 100644
--- a/.gemini/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
+++ b/.gemini/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
@@ -9,7 +9,7 @@ import {
} from '../../design-system.mjs';
import { isFullPage } from '../../shared/page.mjs';
import { applyInlineIgnores } from '../../shared/inline-ignores.mjs';
-import { finding } from '../../findings.mjs';
+import { deriveAdvisoryFlag, finding } from '../../findings.mjs';
import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import {
checkElementBorders,
@@ -257,7 +257,7 @@ async function detectHtml(filePath, options = {}) {
// severity (e.g. a pulsing dot inside a header/nav landmark) that
// overrides the registry default.
if (f.severity) item.severity = f.severity;
- findings.push(item);
+ findings.push(deriveAdvisoryFlag(item));
}
// Text-content analyzers (em-dash overuse, marketing buzzwords,
// numbered section markers, aphoristic cadence) live in the regex
diff --git a/.gemini/skills/impeccable/scripts/detector/findings.mjs b/.gemini/skills/impeccable/scripts/detector/findings.mjs
index fa98dd935..ae7e134f9 100644
--- a/.gemini/skills/impeccable/scripts/detector/findings.mjs
+++ b/.gemini/skills/impeccable/scripts/detector/findings.mjs
@@ -4,6 +4,12 @@ function getAP(id) {
return getAntipattern(id);
}
+function deriveAdvisoryFlag(item) {
+ if (item.severity === 'advisory') item.advisory = true;
+ else delete item.advisory;
+ return item;
+}
+
function finding(id, filePath, snippet, line = 0) {
const ap = getAP(id);
const base = { antipattern: id, name: ap.name, description: ap.description, severity: ap.severity || 'warning', category: ap.category || null, file: filePath, line, snippet };
@@ -11,8 +17,7 @@ function finding(id, filePath, snippet, line = 0) {
// failures. Carry the flag on the finding so every consumer (CLI, JSON, hook)
// can partition without a registry lookup. Only stamped when true to keep the
// finding shape stable for the vast majority of rules.
- if (ap.advisory === true) base.advisory = true;
- return base;
+ return deriveAdvisoryFlag(base);
}
-export { getAP, finding };
+export { getAP, finding, deriveAdvisoryFlag };
diff --git a/.gemini/skills/impeccable/scripts/detector/registry/antipatterns.mjs b/.gemini/skills/impeccable/scripts/detector/registry/antipatterns.mjs
index 945307783..7c692c79a 100644
--- a/.gemini/skills/impeccable/scripts/detector/registry/antipatterns.mjs
+++ b/.gemini/skills/impeccable/scripts/detector/registry/antipatterns.mjs
@@ -233,7 +233,7 @@ const ANTIPATTERNS = [
// rather than a failure. It fires only on the AI saturation pattern, not on
// ordinary prose. Advisory findings are surfaced separately, never counted
// as failures, and skipped by the design hook unless a project opts in.
- advisory: true,
+ severity: 'advisory',
name: 'Em-dash overuse',
description:
'Em-dash saturation in body copy is an AI cadence tell. Advisory only: humans use em-dashes legitimately, so this fires only on saturation — at least 8 em-dashes (— or --) at a density near one per 500 characters of body text — never on a long article that uses a few. Prefer commas, colons, periods, or parentheses.',
@@ -588,9 +588,10 @@ function getAntipattern(id) {
// Advisory rules are detected and reported, but never treated as failures:
// the CLI lists them under a separate "Advisory" section, they do not affect
// exit codes or the failure count, and the design hook skips them by default.
-// The set is derived from the registry so a rule only needs `advisory: true`.
+// `severity` is the canonical registry field. The runtime finding serializer
+// derives its `advisory: true` compatibility/output flag from this set.
const ADVISORY_RULE_IDS = new Set(
- ANTIPATTERNS.filter(rule => rule.advisory === true).map(rule => rule.id),
+ ANTIPATTERNS.filter(rule => rule.severity === 'advisory').map(rule => rule.id),
);
function isAdvisoryRule(id) {
diff --git a/.gemini/skills/impeccable/scripts/detector/rules/checks.mjs b/.gemini/skills/impeccable/scripts/detector/rules/checks.mjs
index 579e1c12e..a24631ce9 100644
--- a/.gemini/skills/impeccable/scripts/detector/rules/checks.mjs
+++ b/.gemini/skills/impeccable/scripts/detector/rules/checks.mjs
@@ -688,7 +688,10 @@ function enclosingCssSelector(cssText, index) {
// `{` belongs to some other selector.
const closeBeforeIndex = cssText.lastIndexOf('}', index);
if (closeBeforeIndex > open) return null;
- const prevClose = Math.max(cssText.lastIndexOf('}', open - 1), cssText.lastIndexOf(';', open - 1));
+ // Ignore delimiters inside comments when locating the previous declaration.
+ // Keeping comment length intact preserves indices into the original source.
+ const beforeOpen = cssText.slice(0, open).replace(/\/\*[\s\S]*?\*\//g, comment => ' '.repeat(comment.length));
+ const prevClose = Math.max(beforeOpen.lastIndexOf('}'), beforeOpen.lastIndexOf(';'));
const raw = cssText.slice(prevClose + 1, open).replace(/\/\*[\s\S]*?\*\//g, '').trim().replace(/\s+/g, ' ');
if (!raw || raw.startsWith('@') || /^\d/.test(raw) || /[{}<]/.test(raw)) return null;
// Keyframe steps: percentage steps fail the digit test above, but `from`
@@ -4020,14 +4023,17 @@ function checkTypography() {
}
if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
+ // Report the actual primary face: the uniquely most-used family. The old
+ // 15% threshold labeled secondary faces as primary (e.g. an 82/18 split).
+ const ranked = [...fontUsage.entries()].sort((a, b) => b[1] - a[1]);
+ const [primary] = ranked;
+ const tied = ranked[1]?.[1] === primary?.[1];
+ if (primary && !tied) {
+ const [font, count] = primary;
const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ if (OVERUSED_FONTS.has(font) && !isBrandFontOnOwnDomain(font)) {
+ findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ }
}
}
diff --git a/.gemini/skills/impeccable/scripts/hook-lib.mjs b/.gemini/skills/impeccable/scripts/hook-lib.mjs
index 767fe65a6..6d8c3db81 100644
--- a/.gemini/skills/impeccable/scripts/hook-lib.mjs
+++ b/.gemini/skills/impeccable/scripts/hook-lib.mjs
@@ -138,17 +138,20 @@ export const IMMEDIATE_TIER_RULES = new Set([
// the agent is never nagged about a taste call a human might make on purpose.
// A project opts back in with `.impeccable/config.json`:
// { "detector": { "advisoryRules": "include" } }
-// This set is the hook's own copy of the registry's `advisory: true` rules,
-// mirroring how IMMEDIATE_TIER_RULES lists rule ids inline so the hook stays
-// self-contained and testable without loading the detector. Keep it in sync
-// with the registry (cli/engine/registry/antipatterns.mjs).
+// This legacy id fallback keeps older detector findings recognizable when they
+// carry neither the current runtime flag nor the canonical advisory severity.
+// Current findings are classified by their serialized metadata below.
export const ADVISORY_RULES = new Set([
'em-dash-overuse',
]);
export function isAdvisoryFinding(finding) {
const id = finding && normalizeIgnoreRule(finding.antipattern);
- return Boolean(id && (ADVISORY_RULES.has(id) || finding.advisory === true));
+ return Boolean(id && (
+ ADVISORY_RULES.has(id)
+ || finding.advisory === true
+ || finding.severity === 'advisory'
+ ));
}
export const DEFAULT_CONFIG = Object.freeze({
diff --git a/.github/skills/impeccable/scripts/detector/browser/injected/index.mjs b/.github/skills/impeccable/scripts/detector/browser/injected/index.mjs
index febf7f297..76fc558e5 100644
--- a/.github/skills/impeccable/scripts/detector/browser/injected/index.mjs
+++ b/.github/skills/impeccable/scripts/detector/browser/injected/index.mjs
@@ -1228,14 +1228,17 @@ if (IS_BROWSER) {
isHidden: isElementHidden(el),
findings: findings.map(f => {
const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
+ const severity = f.severity || ap?.severity || 'warning';
return {
type: f.type || f.id,
category: ap ? ap.category : 'quality',
- severity: f.severity || ap?.severity || 'warning',
+ severity,
// Advisory findings (em-dash overuse, etc.) are surfaced but never
// treated as failures; carry the flag so the overlay/extension can
// render them with the mildest affordance and consumers can filter.
- advisory: (ap && ap.advisory === true) || f.advisory === true,
+ // Per-finding promotions override the registry default, so derive
+ // this strictly from the effective severity.
+ advisory: severity === 'advisory',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
@@ -1277,6 +1280,381 @@ if (IS_BROWSER) {
else groupMap.set(el, [...kept]);
}
+ function pseudoElementHostSelector(selector) {
+ const raw = String(selector || '');
+ const legacyNames = new Set(['before', 'after', 'first-letter', 'first-line']);
+ const isNameChar = char => /[a-zA-Z0-9_-]/.test(char || '');
+ const consumeFunction = (start) => {
+ let depth = 0;
+ let quote = '';
+ for (let i = start; i < raw.length; i += 1) {
+ const char = raw[i];
+ if (char === '\\') {
+ i += 1;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '(') depth += 1;
+ if (char === ')' && --depth === 0) return i + 1;
+ }
+ return raw.length;
+ };
+
+ let output = '';
+ let found = false;
+ for (let i = 0; i < raw.length;) {
+ const char = raw[i];
+ if (char === '\\') {
+ output += raw.slice(i, Math.min(raw.length, i + 2));
+ i += 2;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ const quote = char;
+ const start = i;
+ i += 1;
+ while (i < raw.length) {
+ if (raw[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ const value = raw[i];
+ i += 1;
+ if (value === quote) break;
+ }
+ output += raw.slice(start, i);
+ continue;
+ }
+ if (char !== ':') {
+ output += char;
+ i += 1;
+ continue;
+ }
+
+ let end = i + 1;
+ let isPseudoElement = false;
+ if (raw[end] === ':') {
+ end += 1;
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = end > nameStart;
+ } else {
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = legacyNames.has(raw.slice(nameStart, end).toLowerCase());
+ }
+ if (!isPseudoElement) {
+ output += char;
+ i += 1;
+ continue;
+ }
+ if (raw[end] === '(') end = consumeFunction(end);
+ found = true;
+ if (!output || /[\s>+~,]/.test(output[output.length - 1])) output += '*';
+ i = end;
+ }
+ if (!found) return null;
+ return output.trim().replace(/,\s*(?=,|$)/g, '');
+ }
+
+ function selectorNodesForLiveDom(root, selector) {
+ const raw = String(selector || '').trim();
+ if (!raw) return null;
+ const fallback = pseudoElementHostSelector(raw);
+ if (fallback == null) {
+ // An empty result from a valid full selector is authoritative. In
+ // particular, do not broaden inactive :hover/:focus/:not() rules to
+ // their host element by stripping pseudo-classes.
+ try { return Array.from(root.querySelectorAll(raw)); }
+ catch { return null; }
+ }
+
+ // Resolve pseudo-elements to their originating live elements. An attached
+ // pseudo-element (`.card::before`) belongs to the element before it, while
+ // a hostless pseudo-element after a combinator (`main > ::before`) belongs
+ // to a matching element at that position (`main > *`). Replacing every
+ // pseudo indiscriminately with an empty string leaves the latter as the
+ // invalid selector `main >` and makes absent hosts indistinguishable from
+ // selectors the DOM API cannot parse.
+ if (!fallback || /^[,\s]*$/.test(fallback)) return null;
+ try { return Array.from(root.querySelectorAll(fallback)); }
+ catch { return null; }
+ }
+
+ let containerProbeSequence = 0;
+
+ function isContainerCssRule(rule) {
+ return rule?.constructor?.name === 'CSSContainerRule'
+ || /^\s*@container\b/i.test(rule?.cssText || '');
+ }
+
+ function styleRuleAppliesToLiveMatches(rule, matches) {
+ const style = rule?.style;
+ if (!style || !matches?.length || typeof getComputedStyle !== 'function') return false;
+ const sequence = ++containerProbeSequence;
+ const property = `--impeccable-container-probe-${sequence}-${Math.random().toString(36).slice(2)}`;
+ const value = `impeccable-container-active-${sequence}`;
+ const previousValue = style.getPropertyValue(property);
+ const previousPriority = style.getPropertyPriority(property);
+ try {
+ style.setProperty(property, value, 'important');
+ } catch {
+ return false;
+ }
+
+ const pseudoElements = [...new Set(
+ String(rule.selectorText || '').match(/::[a-zA-Z-]+(?:\([^)]*\))?/g) || [],
+ )];
+ try {
+ return matches.some(el => [null, ...pseudoElements].some(pseudo => {
+ try {
+ const computed = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el);
+ return computed.getPropertyValue(property).trim() === value;
+ } catch {
+ return false;
+ }
+ }));
+ } finally {
+ if (previousValue) style.setProperty(property, previousValue, previousPriority);
+ else style.removeProperty(property);
+ }
+ }
+
+ function conditionalCssRuleIsActive(rule) {
+ const type = Number(rule?.type);
+ const constructorName = rule?.constructor?.name || '';
+ if (constructorName === 'CSSMediaRule' || type === 4) {
+ const condition = rule.conditionText || rule.media?.mediaText || '';
+ if (!condition || typeof window.matchMedia !== 'function') return true;
+ try { return window.matchMedia(condition).matches; }
+ catch { return true; }
+ }
+ if (constructorName === 'CSSSupportsRule' || type === 12) {
+ const condition = rule.conditionText || '';
+ if (!condition || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return true;
+ try { return CSS.supports(condition); }
+ catch { return true; }
+ }
+ return true;
+ }
+
+ function splitCssCommaList(value) {
+ const parts = [];
+ let current = '';
+ let quote = '';
+ let escaped = false;
+ for (const char of String(value || '')) {
+ if (escaped) {
+ current += char;
+ escaped = false;
+ continue;
+ }
+ if (char === '\\') {
+ current += char;
+ escaped = true;
+ continue;
+ }
+ if (quote) {
+ current += char;
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ current += char;
+ continue;
+ }
+ if (char === ',') {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+ return parts;
+ }
+
+ function normalizeAnimationName(value) {
+ const name = String(value || '').trim();
+ if (name.length >= 2 && name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) {
+ return name.slice(1, -1);
+ }
+ return name;
+ }
+
+ function animationNamesDeclaredByRule(rule) {
+ const style = rule?.style;
+ if (!style) return [];
+ let value = '';
+ try {
+ value = style.animationName
+ || style.getPropertyValue?.('animation-name')
+ || style.webkitAnimationName
+ || style.getPropertyValue?.('-webkit-animation-name')
+ || '';
+ } catch {
+ return [];
+ }
+ return splitCssCommaList(value)
+ .map(normalizeAnimationName)
+ .filter(name => name && name.toLowerCase() !== 'none');
+ }
+
+ function keyframesRuleName(rule, cssText) {
+ const constructorName = rule?.constructor?.name || '';
+ const type = Number(rule?.type);
+ const isKeyframes = constructorName === 'CSSKeyframesRule'
+ || constructorName === 'WebKitCSSKeyframesRule'
+ || type === 7
+ || /^\s*@(?:-webkit-)?keyframes\b/i.test(cssText);
+ if (!isKeyframes) return '';
+ const match = String(cssText || '').match(/^\s*@(?:-webkit-)?keyframes\s+([^\s{]+)/i);
+ return normalizeAnimationName(rule?.name || match?.[1] || '');
+ }
+
+ function cssPropertyName(property) {
+ if (property.startsWith('--')) return property;
+ return property.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
+ }
+
+ function resolvedAnimationKeyframes(candidateNames) {
+ if (typeof document.getAnimations !== 'function') return null;
+ let animations;
+ try { animations = document.getAnimations(); }
+ catch { return null; }
+
+ const resolved = new Map();
+ const metadata = new Set(['offset', 'computedOffset', 'easing', 'composite']);
+ for (const animation of animations) {
+ const name = normalizeAnimationName(animation?.animationName || '');
+ if (!name || !candidateNames.has(name) || resolved.has(name)) continue;
+ let frames;
+ try { frames = animation.effect?.getKeyframes?.() || []; }
+ catch { continue; }
+ const blocks = [];
+ for (const frame of frames) {
+ const rawOffset = Number.isFinite(frame.computedOffset) ? frame.computedOffset : frame.offset;
+ if (!Number.isFinite(rawOffset)) continue;
+ const offset = Math.round(rawOffset * 1000000) / 10000;
+ const declarations = Object.entries(frame)
+ .filter(([property, value]) => !metadata.has(property) && value != null && value !== '')
+ .map(([property, value]) => `${cssPropertyName(property)}: ${value};`);
+ const easing = String(frame.easing || '').trim();
+ if (easing && easing.toLowerCase() !== 'linear') {
+ declarations.push(`animation-timing-function: ${easing};`);
+ }
+ if (declarations.length === 0) continue;
+ blocks.push(`${offset}% { ${declarations.join(' ')} }`);
+ }
+ if (blocks.length > 0) resolved.set(name, `@keyframes ${name} { ${blocks.join(' ')} }`);
+ }
+ return resolved;
+ }
+
+ // Read CSS that is absent from document.outerHTML. Inline <style> blocks are
+ // already present in the HTML pattern corpus, so limit this walk to linked
+ // stylesheets. Flatten grouping rules so each declaration keeps its selector,
+ // and admit only selector rules that target the live DOM. That prevents
+ // unused utilities from feeding both selector-scoped and page-level checks.
+ // Same-origin CSS and readable CORS sheets participate; browser security
+ // exceptions for cross-origin sheets are expected and skipped.
+ function linkedStylesheetText() {
+ const parts = [];
+ const seen = new Set();
+ const animationNames = new Set();
+ const keyframeCandidates = new Map();
+ const appendRules = (rules, requiresAppliedMatch = false) => {
+ for (const rule of rules) {
+ if (rule.styleSheet) {
+ appendSheet(rule.styleSheet);
+ continue;
+ }
+ const cssText = rule.cssText || '';
+ if (rule.selectorText) {
+ const matches = selectorNodesForLiveDom(document, rule.selectorText);
+ // Only declarations with a resolvable live host enter the corpus.
+ // Unresolvable selectors are uncertain, not evidence that a pattern
+ // rendered, and retaining them would leak unused CSS into findings.
+ if (
+ matches?.length > 0
+ && (!requiresAppliedMatch || styleRuleAppliesToLiveMatches(rule, matches))
+ ) {
+ parts.push(cssText);
+ for (const name of animationNamesDeclaredByRule(rule)) animationNames.add(name);
+ }
+ continue;
+ }
+ let nested = [];
+ let hasNestedRules = false;
+ try {
+ const ruleList = rule.cssRules;
+ hasNestedRules = ruleList != null;
+ nested = Array.from(ruleList || []);
+ } catch {
+ continue;
+ }
+ const keyframesName = keyframesRuleName(rule, cssText);
+ if (keyframesName) {
+ // Keyframes do not merge: when a name is defined more than once, the
+ // later effective definition replaces the earlier one.
+ keyframeCandidates.set(keyframesName, {
+ name: keyframesName,
+ cssText,
+ });
+ continue;
+ }
+ if (hasNestedRules) {
+ if (!conditionalCssRuleIsActive(rule)) continue;
+ appendRules(nested, requiresAppliedMatch || isContainerCssRule(rule));
+ continue;
+ }
+ // Other selector-less leaf at-rules cannot be tied to a rendered node.
+ }
+ };
+ const appendSheet = (sheet) => {
+ if (!sheet || seen.has(sheet)) return;
+ seen.add(sheet);
+ let rules;
+ try { rules = Array.from(sheet.cssRules || sheet.rules || []); }
+ catch { return; }
+ appendRules(rules);
+ };
+ let sheets;
+ try { sheets = Array.from(document.styleSheets || []); }
+ catch { return ''; }
+ for (const sheet of sheets) {
+ const owner = sheet.ownerNode;
+ if (owner?.tagName?.toLowerCase() !== 'link') continue;
+ if (!/\bstylesheet\b/i.test(owner.getAttribute?.('rel') || '')) continue;
+ appendSheet(sheet);
+ }
+ // Motion checks need the effective body of a live animation's keyframes.
+ // Let the browser resolve duplicate names across source order, imports,
+ // conditional groups, and cascade layers, then serialize those computed
+ // frames back into the pattern corpus. Browsers also make container-nested
+ // keyframes globally available, so lexical grouping is not a reliable
+ // activity signal. When the Web Animations API is unavailable, fall back to
+ // the last source-order definition referenced by a retained linked rule.
+ const resolvedKeyframes = resolvedAnimationKeyframes(new Set(keyframeCandidates.keys()));
+ if (resolvedKeyframes) {
+ parts.push(...resolvedKeyframes.values());
+ } else {
+ for (const candidate of keyframeCandidates.values()) {
+ if (!animationNames.has(candidate.name)) continue;
+ parts.push(candidate.cssText);
+ }
+ }
+ return parts.join('\n');
+ }
+
function browserFindingsFromMap(groupMap) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
@@ -1650,18 +2028,16 @@ if (IS_BROWSER) {
// (the CSS ships here, but the pattern never renders — the live DOM is
// ground truth in the browser), and a match under a data-impeccable-ignore
// ancestor is waived. Selector-less findings stay page-level.
- const scopedHtmlFindings = checkHtmlPatterns(docClone.outerHTML).filter(f => {
+ const html = docClone.outerHTML;
+ const corpora = buildHtmlPatternCorpora(html);
+ const linkedCss = linkedStylesheetText();
+ if (linkedCss) corpora.styleText += `\n${linkedCss}`;
+ const scopedHtmlFindings = checkHtmlPatterns(html, corpora).filter(f => {
if (!f.selector) return true;
- const query = String(f.selector).replace(/::?[a-zA-Z-]+(\([^)]*\))?/g, '').trim().replace(/,\s*(?=,|$)/g, '');
- if (!query || /^[,\s]*$/.test(query)) return true;
- let matches;
- try {
- matches = document.querySelectorAll(query);
- } catch {
- return true;
- }
+ const matches = selectorNodesForLiveDom(document, f.selector);
+ if (!matches) return false;
if (matches.length === 0) return false;
- return [...matches].some(el => !scopedIgnoreActive(el, f.id));
+ return matches.some(el => !scopedIgnoreActive(el, f.id));
});
if (scopedHtmlFindings.length > 0) {
const mapped = scopedHtmlFindings.map(f => {
diff --git a/.github/skills/impeccable/scripts/detector/cli/main.mjs b/.github/skills/impeccable/scripts/detector/cli/main.mjs
index 4476d04f1..3451d6c6b 100644
--- a/.github/skills/impeccable/scripts/detector/cli/main.mjs
+++ b/.github/skills/impeccable/scripts/detector/cli/main.mjs
@@ -37,13 +37,30 @@ function fileUrlToLocalPath(url) {
}
}
+const URL_TARGET_RE = /^(?:https?|file):\/\//i;
+
+// Some agent runners hand a shell-ready URL list to Node as one argv value.
+// A browser accepts the spaces as part of one encoded URL, producing a
+// plausible scan attributed to a bogus joined path. Expand only when every
+// whitespace-delimited token is independently a URL, preserving ordinary
+// filesystem paths that contain spaces.
+function expandJoinedUrlTargets(targets) {
+ return targets.flatMap((target) => {
+ if (!/\s/.test(target)) return [target];
+ const parts = target.trim().split(/\s+/).filter(Boolean);
+ return parts.length > 1 && parts.every(part => URL_TARGET_RE.test(part))
+ ? parts
+ : [target];
+ });
+}
+
// Advisory findings are detected but never treated as failures: they list in a
// separate, visually dimmed section, are excluded from the failure count that
// drives the exit code, and carry `"advisory": true` in JSON so consumers can
// filter. Every advisory finding carries the flag (stamped by the registry via
// findings.mjs).
function isAdvisory(finding) {
- return finding && finding.advisory === true;
+ return Boolean(finding && (finding.advisory === true || finding.severity === 'advisory'));
}
function partitionAdvisory(findings) {
@@ -168,6 +185,10 @@ Advisory findings:
counted as failures and never changing the exit code. They stay out of the
failure count so they never block automation. --no-advisory hides them.
+Output streams:
+ Human-readable findings go to stderr so stdout stays available for structured
+ output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.
+
Project config:
Respects .impeccable/config.json and .impeccable/config.local.json detector
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
@@ -185,7 +206,7 @@ Detection modes:
HTML files Static HTML/CSS analysis (default, catches linked CSS)
Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)
URLs Puppeteer full browser rendering (auto-detected;
- http(s):// and file:// URLs)
+ http(s):// and file:// URLs; accessible linked CSS included)
Examples:
impeccable detect src/
@@ -283,7 +304,7 @@ async function detectCli() {
const designSystem = loadDesignSystemForTarget(localPath, { cache: designSystemCache });
return designSystem ? { ...baseScanOptions, designSystem } : baseScanOptions;
};
- const targets = args.filter(a => !a.startsWith('--'));
+ const targets = expandJoinedUrlTargets(args.filter(a => !a.startsWith('--')));
if (helpMode) { printUsage(); process.exit(0); }
@@ -297,13 +318,12 @@ async function detectCli() {
// real cascade, real computed styles, real layout. Callers that want a
// browser-grade scan of a local artifact can pass file:///abs/path.html
// instead of the bare path (which stays on the static engine).
- const urlRe = /^(?:https?|file):\/\//i;
- const urlTargetCount = paths.filter(target => urlRe.test(target)).length;
+ const urlTargetCount = paths.filter(target => URL_TARGET_RE.test(target)).length;
const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
try {
for (const target of paths) {
- if (urlRe.test(target)) {
+ if (URL_TARGET_RE.test(target)) {
// A file:// URL points at a local artifact, so its design system
// resolves from that file's project. A remote http(s) URL has no
// local project — it gets base options (no design system), never
diff --git a/.github/skills/impeccable/scripts/detector/detect-antipatterns-browser.js b/.github/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
index e6899f569..460ffb45b 100644
--- a/.github/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
+++ b/.github/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
@@ -358,7 +358,7 @@ const ANTIPATTERNS = [
// rather than a failure. It fires only on the AI saturation pattern, not on
// ordinary prose. Advisory findings are surfaced separately, never counted
// as failures, and skipped by the design hook unless a project opts in.
- advisory: true,
+ severity: 'advisory',
name: 'Em-dash overuse',
description:
'Em-dash saturation in body copy is an AI cadence tell. Advisory only: humans use em-dashes legitimately, so this fires only on saturation — at least 8 em-dashes (— or --) at a density near one per 500 characters of body text — never on a long article that uses a few. Prefer commas, colons, periods, or parentheses.',
@@ -1961,7 +1961,10 @@ function enclosingCssSelector(cssText, index) {
// `{` belongs to some other selector.
const closeBeforeIndex = cssText.lastIndexOf('}', index);
if (closeBeforeIndex > open) return null;
- const prevClose = Math.max(cssText.lastIndexOf('}', open - 1), cssText.lastIndexOf(';', open - 1));
+ // Ignore delimiters inside comments when locating the previous declaration.
+ // Keeping comment length intact preserves indices into the original source.
+ const beforeOpen = cssText.slice(0, open).replace(/\/\*[\s\S]*?\*\//g, comment => ' '.repeat(comment.length));
+ const prevClose = Math.max(beforeOpen.lastIndexOf('}'), beforeOpen.lastIndexOf(';'));
const raw = cssText.slice(prevClose + 1, open).replace(/\/\*[\s\S]*?\*\//g, '').trim().replace(/\s+/g, ' ');
if (!raw || raw.startsWith('@') || /^\d/.test(raw) || /[{}<]/.test(raw)) return null;
// Keyframe steps: percentage steps fail the digit test above, but `from`
@@ -5293,14 +5296,17 @@ function checkTypography() {
}
if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
+ // Report the actual primary face: the uniquely most-used family. The old
+ // 15% threshold labeled secondary faces as primary (e.g. an 82/18 split).
+ const ranked = [...fontUsage.entries()].sort((a, b) => b[1] - a[1]);
+ const [primary] = ranked;
+ const tied = ranked[1]?.[1] === primary?.[1];
+ if (primary && !tied) {
+ const [font, count] = primary;
const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ if (OVERUSED_FONTS.has(font) && !isBrandFontOnOwnDomain(font)) {
+ findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ }
}
}
@@ -8126,14 +8132,17 @@ if (IS_BROWSER) {
isHidden: isElementHidden(el),
findings: findings.map(f => {
const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
+ const severity = f.severity || ap?.severity || 'warning';
return {
type: f.type || f.id,
category: ap ? ap.category : 'quality',
- severity: f.severity || ap?.severity || 'warning',
+ severity,
// Advisory findings (em-dash overuse, etc.) are surfaced but never
// treated as failures; carry the flag so the overlay/extension can
// render them with the mildest affordance and consumers can filter.
- advisory: (ap && ap.advisory === true) || f.advisory === true,
+ // Per-finding promotions override the registry default, so derive
+ // this strictly from the effective severity.
+ advisory: severity === 'advisory',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
@@ -8175,6 +8184,381 @@ if (IS_BROWSER) {
else groupMap.set(el, [...kept]);
}
+ function pseudoElementHostSelector(selector) {
+ const raw = String(selector || '');
+ const legacyNames = new Set(['before', 'after', 'first-letter', 'first-line']);
+ const isNameChar = char => /[a-zA-Z0-9_-]/.test(char || '');
+ const consumeFunction = (start) => {
+ let depth = 0;
+ let quote = '';
+ for (let i = start; i < raw.length; i += 1) {
+ const char = raw[i];
+ if (char === '\\') {
+ i += 1;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '(') depth += 1;
+ if (char === ')' && --depth === 0) return i + 1;
+ }
+ return raw.length;
+ };
+
+ let output = '';
+ let found = false;
+ for (let i = 0; i < raw.length;) {
+ const char = raw[i];
+ if (char === '\\') {
+ output += raw.slice(i, Math.min(raw.length, i + 2));
+ i += 2;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ const quote = char;
+ const start = i;
+ i += 1;
+ while (i < raw.length) {
+ if (raw[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ const value = raw[i];
+ i += 1;
+ if (value === quote) break;
+ }
+ output += raw.slice(start, i);
+ continue;
+ }
+ if (char !== ':') {
+ output += char;
+ i += 1;
+ continue;
+ }
+
+ let end = i + 1;
+ let isPseudoElement = false;
+ if (raw[end] === ':') {
+ end += 1;
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = end > nameStart;
+ } else {
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = legacyNames.has(raw.slice(nameStart, end).toLowerCase());
+ }
+ if (!isPseudoElement) {
+ output += char;
+ i += 1;
+ continue;
+ }
+ if (raw[end] === '(') end = consumeFunction(end);
+ found = true;
+ if (!output || /[\s>+~,]/.test(output[output.length - 1])) output += '*';
+ i = end;
+ }
+ if (!found) return null;
+ return output.trim().replace(/,\s*(?=,|$)/g, '');
+ }
+
+ function selectorNodesForLiveDom(root, selector) {
+ const raw = String(selector || '').trim();
+ if (!raw) return null;
+ const fallback = pseudoElementHostSelector(raw);
+ if (fallback == null) {
+ // An empty result from a valid full selector is authoritative. In
+ // particular, do not broaden inactive :hover/:focus/:not() rules to
+ // their host element by stripping pseudo-classes.
+ try { return Array.from(root.querySelectorAll(raw)); }
+ catch { return null; }
+ }
+
+ // Resolve pseudo-elements to their originating live elements. An attached
+ // pseudo-element (`.card::before`) belongs to the element before it, while
+ // a hostless pseudo-element after a combinator (`main > ::before`) belongs
+ // to a matching element at that position (`main > *`). Replacing every
+ // pseudo indiscriminately with an empty string leaves the latter as the
+ // invalid selector `main >` and makes absent hosts indistinguishable from
+ // selectors the DOM API cannot parse.
+ if (!fallback || /^[,\s]*$/.test(fallback)) return null;
+ try { return Array.from(root.querySelectorAll(fallback)); }
+ catch { return null; }
+ }
+
+ let containerProbeSequence = 0;
+
+ function isContainerCssRule(rule) {
+ return rule?.constructor?.name === 'CSSContainerRule'
+ || /^\s*@container\b/i.test(rule?.cssText || '');
+ }
+
+ function styleRuleAppliesToLiveMatches(rule, matches) {
+ const style = rule?.style;
+ if (!style || !matches?.length || typeof getComputedStyle !== 'function') return false;
+ const sequence = ++containerProbeSequence;
+ const property = `--impeccable-container-probe-${sequence}-${Math.random().toString(36).slice(2)}`;
+ const value = `impeccable-container-active-${sequence}`;
+ const previousValue = style.getPropertyValue(property);
+ const previousPriority = style.getPropertyPriority(property);
+ try {
+ style.setProperty(property, value, 'important');
+ } catch {
+ return false;
+ }
+
+ const pseudoElements = [...new Set(
+ String(rule.selectorText || '').match(/::[a-zA-Z-]+(?:\([^)]*\))?/g) || [],
+ )];
+ try {
+ return matches.some(el => [null, ...pseudoElements].some(pseudo => {
+ try {
+ const computed = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el);
+ return computed.getPropertyValue(property).trim() === value;
+ } catch {
+ return false;
+ }
+ }));
+ } finally {
+ if (previousValue) style.setProperty(property, previousValue, previousPriority);
+ else style.removeProperty(property);
+ }
+ }
+
+ function conditionalCssRuleIsActive(rule) {
+ const type = Number(rule?.type);
+ const constructorName = rule?.constructor?.name || '';
+ if (constructorName === 'CSSMediaRule' || type === 4) {
+ const condition = rule.conditionText || rule.media?.mediaText || '';
+ if (!condition || typeof window.matchMedia !== 'function') return true;
+ try { return window.matchMedia(condition).matches; }
+ catch { return true; }
+ }
+ if (constructorName === 'CSSSupportsRule' || type === 12) {
+ const condition = rule.conditionText || '';
+ if (!condition || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return true;
+ try { return CSS.supports(condition); }
+ catch { return true; }
+ }
+ return true;
+ }
+
+ function splitCssCommaList(value) {
+ const parts = [];
+ let current = '';
+ let quote = '';
+ let escaped = false;
+ for (const char of String(value || '')) {
+ if (escaped) {
+ current += char;
+ escaped = false;
+ continue;
+ }
+ if (char === '\\') {
+ current += char;
+ escaped = true;
+ continue;
+ }
+ if (quote) {
+ current += char;
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ current += char;
+ continue;
+ }
+ if (char === ',') {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+ return parts;
+ }
+
+ function normalizeAnimationName(value) {
+ const name = String(value || '').trim();
+ if (name.length >= 2 && name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) {
+ return name.slice(1, -1);
+ }
+ return name;
+ }
+
+ function animationNamesDeclaredByRule(rule) {
+ const style = rule?.style;
+ if (!style) return [];
+ let value = '';
+ try {
+ value = style.animationName
+ || style.getPropertyValue?.('animation-name')
+ || style.webkitAnimationName
+ || style.getPropertyValue?.('-webkit-animation-name')
+ || '';
+ } catch {
+ return [];
+ }
+ return splitCssCommaList(value)
+ .map(normalizeAnimationName)
+ .filter(name => name && name.toLowerCase() !== 'none');
+ }
+
+ function keyframesRuleName(rule, cssText) {
+ const constructorName = rule?.constructor?.name || '';
+ const type = Number(rule?.type);
+ const isKeyframes = constructorName === 'CSSKeyframesRule'
+ || constructorName === 'WebKitCSSKeyframesRule'
+ || type === 7
+ || /^\s*@(?:-webkit-)?keyframes\b/i.test(cssText);
+ if (!isKeyframes) return '';
+ const match = String(cssText || '').match(/^\s*@(?:-webkit-)?keyframes\s+([^\s{]+)/i);
+ return normalizeAnimationName(rule?.name || match?.[1] || '');
+ }
+
+ function cssPropertyName(property) {
+ if (property.startsWith('--')) return property;
+ return property.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
+ }
+
+ function resolvedAnimationKeyframes(candidateNames) {
+ if (typeof document.getAnimations !== 'function') return null;
+ let animations;
+ try { animations = document.getAnimations(); }
+ catch { return null; }
+
+ const resolved = new Map();
+ const metadata = new Set(['offset', 'computedOffset', 'easing', 'composite']);
+ for (const animation of animations) {
+ const name = normalizeAnimationName(animation?.animationName || '');
+ if (!name || !candidateNames.has(name) || resolved.has(name)) continue;
+ let frames;
+ try { frames = animation.effect?.getKeyframes?.() || []; }
+ catch { continue; }
+ const blocks = [];
+ for (const frame of frames) {
+ const rawOffset = Number.isFinite(frame.computedOffset) ? frame.computedOffset : frame.offset;
+ if (!Number.isFinite(rawOffset)) continue;
+ const offset = Math.round(rawOffset * 1000000) / 10000;
+ const declarations = Object.entries(frame)
+ .filter(([property, value]) => !metadata.has(property) && value != null && value !== '')
+ .map(([property, value]) => `${cssPropertyName(property)}: ${value};`);
+ const easing = String(frame.easing || '').trim();
+ if (easing && easing.toLowerCase() !== 'linear') {
+ declarations.push(`animation-timing-function: ${easing};`);
+ }
+ if (declarations.length === 0) continue;
+ blocks.push(`${offset}% { ${declarations.join(' ')} }`);
+ }
+ if (blocks.length > 0) resolved.set(name, `@keyframes ${name} { ${blocks.join(' ')} }`);
+ }
+ return resolved;
+ }
+
+ // Read CSS that is absent from document.outerHTML. Inline <style> blocks are
+ // already present in the HTML pattern corpus, so limit this walk to linked
+ // stylesheets. Flatten grouping rules so each declaration keeps its selector,
+ // and admit only selector rules that target the live DOM. That prevents
+ // unused utilities from feeding both selector-scoped and page-level checks.
+ // Same-origin CSS and readable CORS sheets participate; browser security
+ // exceptions for cross-origin sheets are expected and skipped.
+ function linkedStylesheetText() {
+ const parts = [];
+ const seen = new Set();
+ const animationNames = new Set();
+ const keyframeCandidates = new Map();
+ const appendRules = (rules, requiresAppliedMatch = false) => {
+ for (const rule of rules) {
+ if (rule.styleSheet) {
+ appendSheet(rule.styleSheet);
+ continue;
+ }
+ const cssText = rule.cssText || '';
+ if (rule.selectorText) {
+ const matches = selectorNodesForLiveDom(document, rule.selectorText);
+ // Only declarations with a resolvable live host enter the corpus.
+ // Unresolvable selectors are uncertain, not evidence that a pattern
+ // rendered, and retaining them would leak unused CSS into findings.
+ if (
+ matches?.length > 0
+ && (!requiresAppliedMatch || styleRuleAppliesToLiveMatches(rule, matches))
+ ) {
+ parts.push(cssText);
+ for (const name of animationNamesDeclaredByRule(rule)) animationNames.add(name);
+ }
+ continue;
+ }
+ let nested = [];
+ let hasNestedRules = false;
+ try {
+ const ruleList = rule.cssRules;
+ hasNestedRules = ruleList != null;
+ nested = Array.from(ruleList || []);
+ } catch {
+ continue;
+ }
+ const keyframesName = keyframesRuleName(rule, cssText);
+ if (keyframesName) {
+ // Keyframes do not merge: when a name is defined more than once, the
+ // later effective definition replaces the earlier one.
+ keyframeCandidates.set(keyframesName, {
+ name: keyframesName,
+ cssText,
+ });
+ continue;
+ }
+ if (hasNestedRules) {
+ if (!conditionalCssRuleIsActive(rule)) continue;
+ appendRules(nested, requiresAppliedMatch || isContainerCssRule(rule));
+ continue;
+ }
+ // Other selector-less leaf at-rules cannot be tied to a rendered node.
+ }
+ };
+ const appendSheet = (sheet) => {
+ if (!sheet || seen.has(sheet)) return;
+ seen.add(sheet);
+ let rules;
+ try { rules = Array.from(sheet.cssRules || sheet.rules || []); }
+ catch { return; }
+ appendRules(rules);
+ };
+ let sheets;
+ try { sheets = Array.from(document.styleSheets || []); }
+ catch { return ''; }
+ for (const sheet of sheets) {
+ const owner = sheet.ownerNode;
+ if (owner?.tagName?.toLowerCase() !== 'link') continue;
+ if (!/\bstylesheet\b/i.test(owner.getAttribute?.('rel') || '')) continue;
+ appendSheet(sheet);
+ }
+ // Motion checks need the effective body of a live animation's keyframes.
+ // Let the browser resolve duplicate names across source order, imports,
+ // conditional groups, and cascade layers, then serialize those computed
+ // frames back into the pattern corpus. Browsers also make container-nested
+ // keyframes globally available, so lexical grouping is not a reliable
+ // activity signal. When the Web Animations API is unavailable, fall back to
+ // the last source-order definition referenced by a retained linked rule.
+ const resolvedKeyframes = resolvedAnimationKeyframes(new Set(keyframeCandidates.keys()));
+ if (resolvedKeyframes) {
+ parts.push(...resolvedKeyframes.values());
+ } else {
+ for (const candidate of keyframeCandidates.values()) {
+ if (!animationNames.has(candidate.name)) continue;
+ parts.push(candidate.cssText);
+ }
+ }
+ return parts.join('\n');
+ }
+
function browserFindingsFromMap(groupMap) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
@@ -8548,18 +8932,16 @@ if (IS_BROWSER) {
// (the CSS ships here, but the pattern never renders — the live DOM is
// ground truth in the browser), and a match under a data-impeccable-ignore
// ancestor is waived. Selector-less findings stay page-level.
- const scopedHtmlFindings = checkHtmlPatterns(docClone.outerHTML).filter(f => {
+ const html = docClone.outerHTML;
+ const corpora = buildHtmlPatternCorpora(html);
+ const linkedCss = linkedStylesheetText();
+ if (linkedCss) corpora.styleText += `\n${linkedCss}`;
+ const scopedHtmlFindings = checkHtmlPatterns(html, corpora).filter(f => {
if (!f.selector) return true;
- const query = String(f.selector).replace(/::?[a-zA-Z-]+(\([^)]*\))?/g, '').trim().replace(/,\s*(?=,|$)/g, '');
- if (!query || /^[,\s]*$/.test(query)) return true;
- let matches;
- try {
- matches = document.querySelectorAll(query);
- } catch {
- return true;
- }
+ const matches = selectorNodesForLiveDom(document, f.selector);
+ if (!matches) return false;
if (matches.length === 0) return false;
- return [...matches].some(el => !scopedIgnoreActive(el, f.id));
+ return matches.some(el => !scopedIgnoreActive(el, f.id));
});
if (scopedHtmlFindings.length > 0) {
const mapped = scopedHtmlFindings.map(f => {
diff --git a/.github/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs b/.github/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
index f3ff43c84..ac4bd0a7c 100644
--- a/.github/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
+++ b/.github/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
@@ -2,7 +2,7 @@ import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { finding } from '../../findings.mjs';
+import { deriveAdvisoryFlag, finding } from '../../findings.mjs';
import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
import { checkContentHiddenAtRest } from '../../rules/checks.mjs';
@@ -394,7 +394,7 @@ async function detectUrl(rawUrl, options = {}) {
// Per-finding severity promotion (e.g. hero-region pulsing dot)
// overrides the registry default carried by finding().
if (f.severity && f.severity !== item.severity) item.severity = f.severity;
- return item;
+ return deriveAdvisoryFlag(item);
});
}
diff --git a/.github/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs b/.github/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
index 84e6ab1f5..dac6939b0 100644
--- a/.github/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
+++ b/.github/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
@@ -9,7 +9,7 @@ import {
} from '../../design-system.mjs';
import { isFullPage } from '../../shared/page.mjs';
import { applyInlineIgnores } from '../../shared/inline-ignores.mjs';
-import { finding } from '../../findings.mjs';
+import { deriveAdvisoryFlag, finding } from '../../findings.mjs';
import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import {
checkElementBorders,
@@ -257,7 +257,7 @@ async function detectHtml(filePath, options = {}) {
// severity (e.g. a pulsing dot inside a header/nav landmark) that
// overrides the registry default.
if (f.severity) item.severity = f.severity;
- findings.push(item);
+ findings.push(deriveAdvisoryFlag(item));
}
// Text-content analyzers (em-dash overuse, marketing buzzwords,
// numbered section markers, aphoristic cadence) live in the regex
diff --git a/.github/skills/impeccable/scripts/detector/findings.mjs b/.github/skills/impeccable/scripts/detector/findings.mjs
index fa98dd935..ae7e134f9 100644
--- a/.github/skills/impeccable/scripts/detector/findings.mjs
+++ b/.github/skills/impeccable/scripts/detector/findings.mjs
@@ -4,6 +4,12 @@ function getAP(id) {
return getAntipattern(id);
}
+function deriveAdvisoryFlag(item) {
+ if (item.severity === 'advisory') item.advisory = true;
+ else delete item.advisory;
+ return item;
+}
+
function finding(id, filePath, snippet, line = 0) {
const ap = getAP(id);
const base = { antipattern: id, name: ap.name, description: ap.description, severity: ap.severity || 'warning', category: ap.category || null, file: filePath, line, snippet };
@@ -11,8 +17,7 @@ function finding(id, filePath, snippet, line = 0) {
// failures. Carry the flag on the finding so every consumer (CLI, JSON, hook)
// can partition without a registry lookup. Only stamped when true to keep the
// finding shape stable for the vast majority of rules.
- if (ap.advisory === true) base.advisory = true;
- return base;
+ return deriveAdvisoryFlag(base);
}
-export { getAP, finding };
+export { getAP, finding, deriveAdvisoryFlag };
diff --git a/.github/skills/impeccable/scripts/detector/registry/antipatterns.mjs b/.github/skills/impeccable/scripts/detector/registry/antipatterns.mjs
index 945307783..7c692c79a 100644
--- a/.github/skills/impeccable/scripts/detector/registry/antipatterns.mjs
+++ b/.github/skills/impeccable/scripts/detector/registry/antipatterns.mjs
@@ -233,7 +233,7 @@ const ANTIPATTERNS = [
// rather than a failure. It fires only on the AI saturation pattern, not on
// ordinary prose. Advisory findings are surfaced separately, never counted
// as failures, and skipped by the design hook unless a project opts in.
- advisory: true,
+ severity: 'advisory',
name: 'Em-dash overuse',
description:
'Em-dash saturation in body copy is an AI cadence tell. Advisory only: humans use em-dashes legitimately, so this fires only on saturation — at least 8 em-dashes (— or --) at a density near one per 500 characters of body text — never on a long article that uses a few. Prefer commas, colons, periods, or parentheses.',
@@ -588,9 +588,10 @@ function getAntipattern(id) {
// Advisory rules are detected and reported, but never treated as failures:
// the CLI lists them under a separate "Advisory" section, they do not affect
// exit codes or the failure count, and the design hook skips them by default.
-// The set is derived from the registry so a rule only needs `advisory: true`.
+// `severity` is the canonical registry field. The runtime finding serializer
+// derives its `advisory: true` compatibility/output flag from this set.
const ADVISORY_RULE_IDS = new Set(
- ANTIPATTERNS.filter(rule => rule.advisory === true).map(rule => rule.id),
+ ANTIPATTERNS.filter(rule => rule.severity === 'advisory').map(rule => rule.id),
);
function isAdvisoryRule(id) {
diff --git a/.github/skills/impeccable/scripts/detector/rules/checks.mjs b/.github/skills/impeccable/scripts/detector/rules/checks.mjs
index 579e1c12e..a24631ce9 100644
--- a/.github/skills/impeccable/scripts/detector/rules/checks.mjs
+++ b/.github/skills/impeccable/scripts/detector/rules/checks.mjs
@@ -688,7 +688,10 @@ function enclosingCssSelector(cssText, index) {
// `{` belongs to some other selector.
const closeBeforeIndex = cssText.lastIndexOf('}', index);
if (closeBeforeIndex > open) return null;
- const prevClose = Math.max(cssText.lastIndexOf('}', open - 1), cssText.lastIndexOf(';', open - 1));
+ // Ignore delimiters inside comments when locating the previous declaration.
+ // Keeping comment length intact preserves indices into the original source.
+ const beforeOpen = cssText.slice(0, open).replace(/\/\*[\s\S]*?\*\//g, comment => ' '.repeat(comment.length));
+ const prevClose = Math.max(beforeOpen.lastIndexOf('}'), beforeOpen.lastIndexOf(';'));
const raw = cssText.slice(prevClose + 1, open).replace(/\/\*[\s\S]*?\*\//g, '').trim().replace(/\s+/g, ' ');
if (!raw || raw.startsWith('@') || /^\d/.test(raw) || /[{}<]/.test(raw)) return null;
// Keyframe steps: percentage steps fail the digit test above, but `from`
@@ -4020,14 +4023,17 @@ function checkTypography() {
}
if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
+ // Report the actual primary face: the uniquely most-used family. The old
+ // 15% threshold labeled secondary faces as primary (e.g. an 82/18 split).
+ const ranked = [...fontUsage.entries()].sort((a, b) => b[1] - a[1]);
+ const [primary] = ranked;
+ const tied = ranked[1]?.[1] === primary?.[1];
+ if (primary && !tied) {
+ const [font, count] = primary;
const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ if (OVERUSED_FONTS.has(font) && !isBrandFontOnOwnDomain(font)) {
+ findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ }
}
}
diff --git a/.github/skills/impeccable/scripts/hook-lib.mjs b/.github/skills/impeccable/scripts/hook-lib.mjs
index 767fe65a6..6d8c3db81 100644
--- a/.github/skills/impeccable/scripts/hook-lib.mjs
+++ b/.github/skills/impeccable/scripts/hook-lib.mjs
@@ -138,17 +138,20 @@ export const IMMEDIATE_TIER_RULES = new Set([
// the agent is never nagged about a taste call a human might make on purpose.
// A project opts back in with `.impeccable/config.json`:
// { "detector": { "advisoryRules": "include" } }
-// This set is the hook's own copy of the registry's `advisory: true` rules,
-// mirroring how IMMEDIATE_TIER_RULES lists rule ids inline so the hook stays
-// self-contained and testable without loading the detector. Keep it in sync
-// with the registry (cli/engine/registry/antipatterns.mjs).
+// This legacy id fallback keeps older detector findings recognizable when they
+// carry neither the current runtime flag nor the canonical advisory severity.
+// Current findings are classified by their serialized metadata below.
export const ADVISORY_RULES = new Set([
'em-dash-overuse',
]);
export function isAdvisoryFinding(finding) {
const id = finding && normalizeIgnoreRule(finding.antipattern);
- return Boolean(id && (ADVISORY_RULES.has(id) || finding.advisory === true));
+ return Boolean(id && (
+ ADVISORY_RULES.has(id)
+ || finding.advisory === true
+ || finding.severity === 'advisory'
+ ));
}
export const DEFAULT_CONFIG = Object.freeze({
diff --git a/.grok/skills/impeccable/scripts/detector/browser/injected/index.mjs b/.grok/skills/impeccable/scripts/detector/browser/injected/index.mjs
index febf7f297..76fc558e5 100644
--- a/.grok/skills/impeccable/scripts/detector/browser/injected/index.mjs
+++ b/.grok/skills/impeccable/scripts/detector/browser/injected/index.mjs
@@ -1228,14 +1228,17 @@ if (IS_BROWSER) {
isHidden: isElementHidden(el),
findings: findings.map(f => {
const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
+ const severity = f.severity || ap?.severity || 'warning';
return {
type: f.type || f.id,
category: ap ? ap.category : 'quality',
- severity: f.severity || ap?.severity || 'warning',
+ severity,
// Advisory findings (em-dash overuse, etc.) are surfaced but never
// treated as failures; carry the flag so the overlay/extension can
// render them with the mildest affordance and consumers can filter.
- advisory: (ap && ap.advisory === true) || f.advisory === true,
+ // Per-finding promotions override the registry default, so derive
+ // this strictly from the effective severity.
+ advisory: severity === 'advisory',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
@@ -1277,6 +1280,381 @@ if (IS_BROWSER) {
else groupMap.set(el, [...kept]);
}
+ function pseudoElementHostSelector(selector) {
+ const raw = String(selector || '');
+ const legacyNames = new Set(['before', 'after', 'first-letter', 'first-line']);
+ const isNameChar = char => /[a-zA-Z0-9_-]/.test(char || '');
+ const consumeFunction = (start) => {
+ let depth = 0;
+ let quote = '';
+ for (let i = start; i < raw.length; i += 1) {
+ const char = raw[i];
+ if (char === '\\') {
+ i += 1;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '(') depth += 1;
+ if (char === ')' && --depth === 0) return i + 1;
+ }
+ return raw.length;
+ };
+
+ let output = '';
+ let found = false;
+ for (let i = 0; i < raw.length;) {
+ const char = raw[i];
+ if (char === '\\') {
+ output += raw.slice(i, Math.min(raw.length, i + 2));
+ i += 2;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ const quote = char;
+ const start = i;
+ i += 1;
+ while (i < raw.length) {
+ if (raw[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ const value = raw[i];
+ i += 1;
+ if (value === quote) break;
+ }
+ output += raw.slice(start, i);
+ continue;
+ }
+ if (char !== ':') {
+ output += char;
+ i += 1;
+ continue;
+ }
+
+ let end = i + 1;
+ let isPseudoElement = false;
+ if (raw[end] === ':') {
+ end += 1;
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = end > nameStart;
+ } else {
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = legacyNames.has(raw.slice(nameStart, end).toLowerCase());
+ }
+ if (!isPseudoElement) {
+ output += char;
+ i += 1;
+ continue;
+ }
+ if (raw[end] === '(') end = consumeFunction(end);
+ found = true;
+ if (!output || /[\s>+~,]/.test(output[output.length - 1])) output += '*';
+ i = end;
+ }
+ if (!found) return null;
+ return output.trim().replace(/,\s*(?=,|$)/g, '');
+ }
+
+ function selectorNodesForLiveDom(root, selector) {
+ const raw = String(selector || '').trim();
+ if (!raw) return null;
+ const fallback = pseudoElementHostSelector(raw);
+ if (fallback == null) {
+ // An empty result from a valid full selector is authoritative. In
+ // particular, do not broaden inactive :hover/:focus/:not() rules to
+ // their host element by stripping pseudo-classes.
+ try { return Array.from(root.querySelectorAll(raw)); }
+ catch { return null; }
+ }
+
+ // Resolve pseudo-elements to their originating live elements. An attached
+ // pseudo-element (`.card::before`) belongs to the element before it, while
+ // a hostless pseudo-element after a combinator (`main > ::before`) belongs
+ // to a matching element at that position (`main > *`). Replacing every
+ // pseudo indiscriminately with an empty string leaves the latter as the
+ // invalid selector `main >` and makes absent hosts indistinguishable from
+ // selectors the DOM API cannot parse.
+ if (!fallback || /^[,\s]*$/.test(fallback)) return null;
+ try { return Array.from(root.querySelectorAll(fallback)); }
+ catch { return null; }
+ }
+
+ let containerProbeSequence = 0;
+
+ function isContainerCssRule(rule) {
+ return rule?.constructor?.name === 'CSSContainerRule'
+ || /^\s*@container\b/i.test(rule?.cssText || '');
+ }
+
+ function styleRuleAppliesToLiveMatches(rule, matches) {
+ const style = rule?.style;
+ if (!style || !matches?.length || typeof getComputedStyle !== 'function') return false;
+ const sequence = ++containerProbeSequence;
+ const property = `--impeccable-container-probe-${sequence}-${Math.random().toString(36).slice(2)}`;
+ const value = `impeccable-container-active-${sequence}`;
+ const previousValue = style.getPropertyValue(property);
+ const previousPriority = style.getPropertyPriority(property);
+ try {
+ style.setProperty(property, value, 'important');
+ } catch {
+ return false;
+ }
+
+ const pseudoElements = [...new Set(
+ String(rule.selectorText || '').match(/::[a-zA-Z-]+(?:\([^)]*\))?/g) || [],
+ )];
+ try {
+ return matches.some(el => [null, ...pseudoElements].some(pseudo => {
+ try {
+ const computed = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el);
+ return computed.getPropertyValue(property).trim() === value;
+ } catch {
+ return false;
+ }
+ }));
+ } finally {
+ if (previousValue) style.setProperty(property, previousValue, previousPriority);
+ else style.removeProperty(property);
+ }
+ }
+
+ function conditionalCssRuleIsActive(rule) {
+ const type = Number(rule?.type);
+ const constructorName = rule?.constructor?.name || '';
+ if (constructorName === 'CSSMediaRule' || type === 4) {
+ const condition = rule.conditionText || rule.media?.mediaText || '';
+ if (!condition || typeof window.matchMedia !== 'function') return true;
+ try { return window.matchMedia(condition).matches; }
+ catch { return true; }
+ }
+ if (constructorName === 'CSSSupportsRule' || type === 12) {
+ const condition = rule.conditionText || '';
+ if (!condition || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return true;
+ try { return CSS.supports(condition); }
+ catch { return true; }
+ }
+ return true;
+ }
+
+ function splitCssCommaList(value) {
+ const parts = [];
+ let current = '';
+ let quote = '';
+ let escaped = false;
+ for (const char of String(value || '')) {
+ if (escaped) {
+ current += char;
+ escaped = false;
+ continue;
+ }
+ if (char === '\\') {
+ current += char;
+ escaped = true;
+ continue;
+ }
+ if (quote) {
+ current += char;
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ current += char;
+ continue;
+ }
+ if (char === ',') {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+ return parts;
+ }
+
+ function normalizeAnimationName(value) {
+ const name = String(value || '').trim();
+ if (name.length >= 2 && name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) {
+ return name.slice(1, -1);
+ }
+ return name;
+ }
+
+ function animationNamesDeclaredByRule(rule) {
+ const style = rule?.style;
+ if (!style) return [];
+ let value = '';
+ try {
+ value = style.animationName
+ || style.getPropertyValue?.('animation-name')
+ || style.webkitAnimationName
+ || style.getPropertyValue?.('-webkit-animation-name')
+ || '';
+ } catch {
+ return [];
+ }
+ return splitCssCommaList(value)
+ .map(normalizeAnimationName)
+ .filter(name => name && name.toLowerCase() !== 'none');
+ }
+
+ function keyframesRuleName(rule, cssText) {
+ const constructorName = rule?.constructor?.name || '';
+ const type = Number(rule?.type);
+ const isKeyframes = constructorName === 'CSSKeyframesRule'
+ || constructorName === 'WebKitCSSKeyframesRule'
+ || type === 7
+ || /^\s*@(?:-webkit-)?keyframes\b/i.test(cssText);
+ if (!isKeyframes) return '';
+ const match = String(cssText || '').match(/^\s*@(?:-webkit-)?keyframes\s+([^\s{]+)/i);
+ return normalizeAnimationName(rule?.name || match?.[1] || '');
+ }
+
+ function cssPropertyName(property) {
+ if (property.startsWith('--')) return property;
+ return property.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
+ }
+
+ function resolvedAnimationKeyframes(candidateNames) {
+ if (typeof document.getAnimations !== 'function') return null;
+ let animations;
+ try { animations = document.getAnimations(); }
+ catch { return null; }
+
+ const resolved = new Map();
+ const metadata = new Set(['offset', 'computedOffset', 'easing', 'composite']);
+ for (const animation of animations) {
+ const name = normalizeAnimationName(animation?.animationName || '');
+ if (!name || !candidateNames.has(name) || resolved.has(name)) continue;
+ let frames;
+ try { frames = animation.effect?.getKeyframes?.() || []; }
+ catch { continue; }
+ const blocks = [];
+ for (const frame of frames) {
+ const rawOffset = Number.isFinite(frame.computedOffset) ? frame.computedOffset : frame.offset;
+ if (!Number.isFinite(rawOffset)) continue;
+ const offset = Math.round(rawOffset * 1000000) / 10000;
+ const declarations = Object.entries(frame)
+ .filter(([property, value]) => !metadata.has(property) && value != null && value !== '')
+ .map(([property, value]) => `${cssPropertyName(property)}: ${value};`);
+ const easing = String(frame.easing || '').trim();
+ if (easing && easing.toLowerCase() !== 'linear') {
+ declarations.push(`animation-timing-function: ${easing};`);
+ }
+ if (declarations.length === 0) continue;
+ blocks.push(`${offset}% { ${declarations.join(' ')} }`);
+ }
+ if (blocks.length > 0) resolved.set(name, `@keyframes ${name} { ${blocks.join(' ')} }`);
+ }
+ return resolved;
+ }
+
+ // Read CSS that is absent from document.outerHTML. Inline <style> blocks are
+ // already present in the HTML pattern corpus, so limit this walk to linked
+ // stylesheets. Flatten grouping rules so each declaration keeps its selector,
+ // and admit only selector rules that target the live DOM. That prevents
+ // unused utilities from feeding both selector-scoped and page-level checks.
+ // Same-origin CSS and readable CORS sheets participate; browser security
+ // exceptions for cross-origin sheets are expected and skipped.
+ function linkedStylesheetText() {
+ const parts = [];
+ const seen = new Set();
+ const animationNames = new Set();
+ const keyframeCandidates = new Map();
+ const appendRules = (rules, requiresAppliedMatch = false) => {
+ for (const rule of rules) {
+ if (rule.styleSheet) {
+ appendSheet(rule.styleSheet);
+ continue;
+ }
+ const cssText = rule.cssText || '';
+ if (rule.selectorText) {
+ const matches = selectorNodesForLiveDom(document, rule.selectorText);
+ // Only declarations with a resolvable live host enter the corpus.
+ // Unresolvable selectors are uncertain, not evidence that a pattern
+ // rendered, and retaining them would leak unused CSS into findings.
+ if (
+ matches?.length > 0
+ && (!requiresAppliedMatch || styleRuleAppliesToLiveMatches(rule, matches))
+ ) {
+ parts.push(cssText);
+ for (const name of animationNamesDeclaredByRule(rule)) animationNames.add(name);
+ }
+ continue;
+ }
+ let nested = [];
+ let hasNestedRules = false;
+ try {
+ const ruleList = rule.cssRules;
+ hasNestedRules = ruleList != null;
+ nested = Array.from(ruleList || []);
+ } catch {
+ continue;
+ }
+ const keyframesName = keyframesRuleName(rule, cssText);
+ if (keyframesName) {
+ // Keyframes do not merge: when a name is defined more than once, the
+ // later effective definition replaces the earlier one.
+ keyframeCandidates.set(keyframesName, {
+ name: keyframesName,
+ cssText,
+ });
+ continue;
+ }
+ if (hasNestedRules) {
+ if (!conditionalCssRuleIsActive(rule)) continue;
+ appendRules(nested, requiresAppliedMatch || isContainerCssRule(rule));
+ continue;
+ }
+ // Other selector-less leaf at-rules cannot be tied to a rendered node.
+ }
+ };
+ const appendSheet = (sheet) => {
+ if (!sheet || seen.has(sheet)) return;
+ seen.add(sheet);
+ let rules;
+ try { rules = Array.from(sheet.cssRules || sheet.rules || []); }
+ catch { return; }
+ appendRules(rules);
+ };
+ let sheets;
+ try { sheets = Array.from(document.styleSheets || []); }
+ catch { return ''; }
+ for (const sheet of sheets) {
+ const owner = sheet.ownerNode;
+ if (owner?.tagName?.toLowerCase() !== 'link') continue;
+ if (!/\bstylesheet\b/i.test(owner.getAttribute?.('rel') || '')) continue;
+ appendSheet(sheet);
+ }
+ // Motion checks need the effective body of a live animation's keyframes.
+ // Let the browser resolve duplicate names across source order, imports,
+ // conditional groups, and cascade layers, then serialize those computed
+ // frames back into the pattern corpus. Browsers also make container-nested
+ // keyframes globally available, so lexical grouping is not a reliable
+ // activity signal. When the Web Animations API is unavailable, fall back to
+ // the last source-order definition referenced by a retained linked rule.
+ const resolvedKeyframes = resolvedAnimationKeyframes(new Set(keyframeCandidates.keys()));
+ if (resolvedKeyframes) {
+ parts.push(...resolvedKeyframes.values());
+ } else {
+ for (const candidate of keyframeCandidates.values()) {
+ if (!animationNames.has(candidate.name)) continue;
+ parts.push(candidate.cssText);
+ }
+ }
+ return parts.join('\n');
+ }
+
function browserFindingsFromMap(groupMap) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
@@ -1650,18 +2028,16 @@ if (IS_BROWSER) {
// (the CSS ships here, but the pattern never renders — the live DOM is
// ground truth in the browser), and a match under a data-impeccable-ignore
// ancestor is waived. Selector-less findings stay page-level.
- const scopedHtmlFindings = checkHtmlPatterns(docClone.outerHTML).filter(f => {
+ const html = docClone.outerHTML;
+ const corpora = buildHtmlPatternCorpora(html);
+ const linkedCss = linkedStylesheetText();
+ if (linkedCss) corpora.styleText += `\n${linkedCss}`;
+ const scopedHtmlFindings = checkHtmlPatterns(html, corpora).filter(f => {
if (!f.selector) return true;
- const query = String(f.selector).replace(/::?[a-zA-Z-]+(\([^)]*\))?/g, '').trim().replace(/,\s*(?=,|$)/g, '');
- if (!query || /^[,\s]*$/.test(query)) return true;
- let matches;
- try {
- matches = document.querySelectorAll(query);
- } catch {
- return true;
- }
+ const matches = selectorNodesForLiveDom(document, f.selector);
+ if (!matches) return false;
if (matches.length === 0) return false;
- return [...matches].some(el => !scopedIgnoreActive(el, f.id));
+ return matches.some(el => !scopedIgnoreActive(el, f.id));
});
if (scopedHtmlFindings.length > 0) {
const mapped = scopedHtmlFindings.map(f => {
diff --git a/.grok/skills/impeccable/scripts/detector/cli/main.mjs b/.grok/skills/impeccable/scripts/detector/cli/main.mjs
index 4476d04f1..3451d6c6b 100644
--- a/.grok/skills/impeccable/scripts/detector/cli/main.mjs
+++ b/.grok/skills/impeccable/scripts/detector/cli/main.mjs
@@ -37,13 +37,30 @@ function fileUrlToLocalPath(url) {
}
}
+const URL_TARGET_RE = /^(?:https?|file):\/\//i;
+
+// Some agent runners hand a shell-ready URL list to Node as one argv value.
+// A browser accepts the spaces as part of one encoded URL, producing a
+// plausible scan attributed to a bogus joined path. Expand only when every
+// whitespace-delimited token is independently a URL, preserving ordinary
+// filesystem paths that contain spaces.
+function expandJoinedUrlTargets(targets) {
+ return targets.flatMap((target) => {
+ if (!/\s/.test(target)) return [target];
+ const parts = target.trim().split(/\s+/).filter(Boolean);
+ return parts.length > 1 && parts.every(part => URL_TARGET_RE.test(part))
+ ? parts
+ : [target];
+ });
+}
+
// Advisory findings are detected but never treated as failures: they list in a
// separate, visually dimmed section, are excluded from the failure count that
// drives the exit code, and carry `"advisory": true` in JSON so consumers can
// filter. Every advisory finding carries the flag (stamped by the registry via
// findings.mjs).
function isAdvisory(finding) {
- return finding && finding.advisory === true;
+ return Boolean(finding && (finding.advisory === true || finding.severity === 'advisory'));
}
function partitionAdvisory(findings) {
@@ -168,6 +185,10 @@ Advisory findings:
counted as failures and never changing the exit code. They stay out of the
failure count so they never block automation. --no-advisory hides them.
+Output streams:
+ Human-readable findings go to stderr so stdout stays available for structured
+ output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.
+
Project config:
Respects .impeccable/config.json and .impeccable/config.local.json detector
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
@@ -185,7 +206,7 @@ Detection modes:
HTML files Static HTML/CSS analysis (default, catches linked CSS)
Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)
URLs Puppeteer full browser rendering (auto-detected;
- http(s):// and file:// URLs)
+ http(s):// and file:// URLs; accessible linked CSS included)
Examples:
impeccable detect src/
@@ -283,7 +304,7 @@ async function detectCli() {
const designSystem = loadDesignSystemForTarget(localPath, { cache: designSystemCache });
return designSystem ? { ...baseScanOptions, designSystem } : baseScanOptions;
};
- const targets = args.filter(a => !a.startsWith('--'));
+ const targets = expandJoinedUrlTargets(args.filter(a => !a.startsWith('--')));
if (helpMode) { printUsage(); process.exit(0); }
@@ -297,13 +318,12 @@ async function detectCli() {
// real cascade, real computed styles, real layout. Callers that want a
// browser-grade scan of a local artifact can pass file:///abs/path.html
// instead of the bare path (which stays on the static engine).
- const urlRe = /^(?:https?|file):\/\//i;
- const urlTargetCount = paths.filter(target => urlRe.test(target)).length;
+ const urlTargetCount = paths.filter(target => URL_TARGET_RE.test(target)).length;
const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
try {
for (const target of paths) {
- if (urlRe.test(target)) {
+ if (URL_TARGET_RE.test(target)) {
// A file:// URL points at a local artifact, so its design system
// resolves from that file's project. A remote http(s) URL has no
// local project — it gets base options (no design system), never
diff --git a/.grok/skills/impeccable/scripts/detector/detect-antipatterns-browser.js b/.grok/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
index e6899f569..460ffb45b 100644
--- a/.grok/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
+++ b/.grok/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
@@ -358,7 +358,7 @@ const ANTIPATTERNS = [
// rather than a failure. It fires only on the AI saturation pattern, not on
// ordinary prose. Advisory findings are surfaced separately, never counted
// as failures, and skipped by the design hook unless a project opts in.
- advisory: true,
+ severity: 'advisory',
name: 'Em-dash overuse',
description:
'Em-dash saturation in body copy is an AI cadence tell. Advisory only: humans use em-dashes legitimately, so this fires only on saturation — at least 8 em-dashes (— or --) at a density near one per 500 characters of body text — never on a long article that uses a few. Prefer commas, colons, periods, or parentheses.',
@@ -1961,7 +1961,10 @@ function enclosingCssSelector(cssText, index) {
// `{` belongs to some other selector.
const closeBeforeIndex = cssText.lastIndexOf('}', index);
if (closeBeforeIndex > open) return null;
- const prevClose = Math.max(cssText.lastIndexOf('}', open - 1), cssText.lastIndexOf(';', open - 1));
+ // Ignore delimiters inside comments when locating the previous declaration.
+ // Keeping comment length intact preserves indices into the original source.
+ const beforeOpen = cssText.slice(0, open).replace(/\/\*[\s\S]*?\*\//g, comment => ' '.repeat(comment.length));
+ const prevClose = Math.max(beforeOpen.lastIndexOf('}'), beforeOpen.lastIndexOf(';'));
const raw = cssText.slice(prevClose + 1, open).replace(/\/\*[\s\S]*?\*\//g, '').trim().replace(/\s+/g, ' ');
if (!raw || raw.startsWith('@') || /^\d/.test(raw) || /[{}<]/.test(raw)) return null;
// Keyframe steps: percentage steps fail the digit test above, but `from`
@@ -5293,14 +5296,17 @@ function checkTypography() {
}
if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
+ // Report the actual primary face: the uniquely most-used family. The old
+ // 15% threshold labeled secondary faces as primary (e.g. an 82/18 split).
+ const ranked = [...fontUsage.entries()].sort((a, b) => b[1] - a[1]);
+ const [primary] = ranked;
+ const tied = ranked[1]?.[1] === primary?.[1];
+ if (primary && !tied) {
+ const [font, count] = primary;
const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ if (OVERUSED_FONTS.has(font) && !isBrandFontOnOwnDomain(font)) {
+ findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ }
}
}
@@ -8126,14 +8132,17 @@ if (IS_BROWSER) {
isHidden: isElementHidden(el),
findings: findings.map(f => {
const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
+ const severity = f.severity || ap?.severity || 'warning';
return {
type: f.type || f.id,
category: ap ? ap.category : 'quality',
- severity: f.severity || ap?.severity || 'warning',
+ severity,
// Advisory findings (em-dash overuse, etc.) are surfaced but never
// treated as failures; carry the flag so the overlay/extension can
// render them with the mildest affordance and consumers can filter.
- advisory: (ap && ap.advisory === true) || f.advisory === true,
+ // Per-finding promotions override the registry default, so derive
+ // this strictly from the effective severity.
+ advisory: severity === 'advisory',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
@@ -8175,6 +8184,381 @@ if (IS_BROWSER) {
else groupMap.set(el, [...kept]);
}
+ function pseudoElementHostSelector(selector) {
+ const raw = String(selector || '');
+ const legacyNames = new Set(['before', 'after', 'first-letter', 'first-line']);
+ const isNameChar = char => /[a-zA-Z0-9_-]/.test(char || '');
+ const consumeFunction = (start) => {
+ let depth = 0;
+ let quote = '';
+ for (let i = start; i < raw.length; i += 1) {
+ const char = raw[i];
+ if (char === '\\') {
+ i += 1;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '(') depth += 1;
+ if (char === ')' && --depth === 0) return i + 1;
+ }
+ return raw.length;
+ };
+
+ let output = '';
+ let found = false;
+ for (let i = 0; i < raw.length;) {
+ const char = raw[i];
+ if (char === '\\') {
+ output += raw.slice(i, Math.min(raw.length, i + 2));
+ i += 2;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ const quote = char;
+ const start = i;
+ i += 1;
+ while (i < raw.length) {
+ if (raw[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ const value = raw[i];
+ i += 1;
+ if (value === quote) break;
+ }
+ output += raw.slice(start, i);
+ continue;
+ }
+ if (char !== ':') {
+ output += char;
+ i += 1;
+ continue;
+ }
+
+ let end = i + 1;
+ let isPseudoElement = false;
+ if (raw[end] === ':') {
+ end += 1;
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = end > nameStart;
+ } else {
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = legacyNames.has(raw.slice(nameStart, end).toLowerCase());
+ }
+ if (!isPseudoElement) {
+ output += char;
+ i += 1;
+ continue;
+ }
+ if (raw[end] === '(') end = consumeFunction(end);
+ found = true;
+ if (!output || /[\s>+~,]/.test(output[output.length - 1])) output += '*';
+ i = end;
+ }
+ if (!found) return null;
+ return output.trim().replace(/,\s*(?=,|$)/g, '');
+ }
+
+ function selectorNodesForLiveDom(root, selector) {
+ const raw = String(selector || '').trim();
+ if (!raw) return null;
+ const fallback = pseudoElementHostSelector(raw);
+ if (fallback == null) {
+ // An empty result from a valid full selector is authoritative. In
+ // particular, do not broaden inactive :hover/:focus/:not() rules to
+ // their host element by stripping pseudo-classes.
+ try { return Array.from(root.querySelectorAll(raw)); }
+ catch { return null; }
+ }
+
+ // Resolve pseudo-elements to their originating live elements. An attached
+ // pseudo-element (`.card::before`) belongs to the element before it, while
+ // a hostless pseudo-element after a combinator (`main > ::before`) belongs
+ // to a matching element at that position (`main > *`). Replacing every
+ // pseudo indiscriminately with an empty string leaves the latter as the
+ // invalid selector `main >` and makes absent hosts indistinguishable from
+ // selectors the DOM API cannot parse.
+ if (!fallback || /^[,\s]*$/.test(fallback)) return null;
+ try { return Array.from(root.querySelectorAll(fallback)); }
+ catch { return null; }
+ }
+
+ let containerProbeSequence = 0;
+
+ function isContainerCssRule(rule) {
+ return rule?.constructor?.name === 'CSSContainerRule'
+ || /^\s*@container\b/i.test(rule?.cssText || '');
+ }
+
+ function styleRuleAppliesToLiveMatches(rule, matches) {
+ const style = rule?.style;
+ if (!style || !matches?.length || typeof getComputedStyle !== 'function') return false;
+ const sequence = ++containerProbeSequence;
+ const property = `--impeccable-container-probe-${sequence}-${Math.random().toString(36).slice(2)}`;
+ const value = `impeccable-container-active-${sequence}`;
+ const previousValue = style.getPropertyValue(property);
+ const previousPriority = style.getPropertyPriority(property);
+ try {
+ style.setProperty(property, value, 'important');
+ } catch {
+ return false;
+ }
+
+ const pseudoElements = [...new Set(
+ String(rule.selectorText || '').match(/::[a-zA-Z-]+(?:\([^)]*\))?/g) || [],
+ )];
+ try {
+ return matches.some(el => [null, ...pseudoElements].some(pseudo => {
+ try {
+ const computed = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el);
+ return computed.getPropertyValue(property).trim() === value;
+ } catch {
+ return false;
+ }
+ }));
+ } finally {
+ if (previousValue) style.setProperty(property, previousValue, previousPriority);
+ else style.removeProperty(property);
+ }
+ }
+
+ function conditionalCssRuleIsActive(rule) {
+ const type = Number(rule?.type);
+ const constructorName = rule?.constructor?.name || '';
+ if (constructorName === 'CSSMediaRule' || type === 4) {
+ const condition = rule.conditionText || rule.media?.mediaText || '';
+ if (!condition || typeof window.matchMedia !== 'function') return true;
+ try { return window.matchMedia(condition).matches; }
+ catch { return true; }
+ }
+ if (constructorName === 'CSSSupportsRule' || type === 12) {
+ const condition = rule.conditionText || '';
+ if (!condition || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return true;
+ try { return CSS.supports(condition); }
+ catch { return true; }
+ }
+ return true;
+ }
+
+ function splitCssCommaList(value) {
+ const parts = [];
+ let current = '';
+ let quote = '';
+ let escaped = false;
+ for (const char of String(value || '')) {
+ if (escaped) {
+ current += char;
+ escaped = false;
+ continue;
+ }
+ if (char === '\\') {
+ current += char;
+ escaped = true;
+ continue;
+ }
+ if (quote) {
+ current += char;
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ current += char;
+ continue;
+ }
+ if (char === ',') {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+ return parts;
+ }
+
+ function normalizeAnimationName(value) {
+ const name = String(value || '').trim();
+ if (name.length >= 2 && name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) {
+ return name.slice(1, -1);
+ }
+ return name;
+ }
+
+ function animationNamesDeclaredByRule(rule) {
+ const style = rule?.style;
+ if (!style) return [];
+ let value = '';
+ try {
+ value = style.animationName
+ || style.getPropertyValue?.('animation-name')
+ || style.webkitAnimationName
+ || style.getPropertyValue?.('-webkit-animation-name')
+ || '';
+ } catch {
+ return [];
+ }
+ return splitCssCommaList(value)
+ .map(normalizeAnimationName)
+ .filter(name => name && name.toLowerCase() !== 'none');
+ }
+
+ function keyframesRuleName(rule, cssText) {
+ const constructorName = rule?.constructor?.name || '';
+ const type = Number(rule?.type);
+ const isKeyframes = constructorName === 'CSSKeyframesRule'
+ || constructorName === 'WebKitCSSKeyframesRule'
+ || type === 7
+ || /^\s*@(?:-webkit-)?keyframes\b/i.test(cssText);
+ if (!isKeyframes) return '';
+ const match = String(cssText || '').match(/^\s*@(?:-webkit-)?keyframes\s+([^\s{]+)/i);
+ return normalizeAnimationName(rule?.name || match?.[1] || '');
+ }
+
+ function cssPropertyName(property) {
+ if (property.startsWith('--')) return property;
+ return property.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
+ }
+
+ function resolvedAnimationKeyframes(candidateNames) {
+ if (typeof document.getAnimations !== 'function') return null;
+ let animations;
+ try { animations = document.getAnimations(); }
+ catch { return null; }
+
+ const resolved = new Map();
+ const metadata = new Set(['offset', 'computedOffset', 'easing', 'composite']);
+ for (const animation of animations) {
+ const name = normalizeAnimationName(animation?.animationName || '');
+ if (!name || !candidateNames.has(name) || resolved.has(name)) continue;
+ let frames;
+ try { frames = animation.effect?.getKeyframes?.() || []; }
+ catch { continue; }
+ const blocks = [];
+ for (const frame of frames) {
+ const rawOffset = Number.isFinite(frame.computedOffset) ? frame.computedOffset : frame.offset;
+ if (!Number.isFinite(rawOffset)) continue;
+ const offset = Math.round(rawOffset * 1000000) / 10000;
+ const declarations = Object.entries(frame)
+ .filter(([property, value]) => !metadata.has(property) && value != null && value !== '')
+ .map(([property, value]) => `${cssPropertyName(property)}: ${value};`);
+ const easing = String(frame.easing || '').trim();
+ if (easing && easing.toLowerCase() !== 'linear') {
+ declarations.push(`animation-timing-function: ${easing};`);
+ }
+ if (declarations.length === 0) continue;
+ blocks.push(`${offset}% { ${declarations.join(' ')} }`);
+ }
+ if (blocks.length > 0) resolved.set(name, `@keyframes ${name} { ${blocks.join(' ')} }`);
+ }
+ return resolved;
+ }
+
+ // Read CSS that is absent from document.outerHTML. Inline <style> blocks are
+ // already present in the HTML pattern corpus, so limit this walk to linked
+ // stylesheets. Flatten grouping rules so each declaration keeps its selector,
+ // and admit only selector rules that target the live DOM. That prevents
+ // unused utilities from feeding both selector-scoped and page-level checks.
+ // Same-origin CSS and readable CORS sheets participate; browser security
+ // exceptions for cross-origin sheets are expected and skipped.
+ function linkedStylesheetText() {
+ const parts = [];
+ const seen = new Set();
+ const animationNames = new Set();
+ const keyframeCandidates = new Map();
+ const appendRules = (rules, requiresAppliedMatch = false) => {
+ for (const rule of rules) {
+ if (rule.styleSheet) {
+ appendSheet(rule.styleSheet);
+ continue;
+ }
+ const cssText = rule.cssText || '';
+ if (rule.selectorText) {
+ const matches = selectorNodesForLiveDom(document, rule.selectorText);
+ // Only declarations with a resolvable live host enter the corpus.
+ // Unresolvable selectors are uncertain, not evidence that a pattern
+ // rendered, and retaining them would leak unused CSS into findings.
+ if (
+ matches?.length > 0
+ && (!requiresAppliedMatch || styleRuleAppliesToLiveMatches(rule, matches))
+ ) {
+ parts.push(cssText);
+ for (const name of animationNamesDeclaredByRule(rule)) animationNames.add(name);
+ }
+ continue;
+ }
+ let nested = [];
+ let hasNestedRules = false;
+ try {
+ const ruleList = rule.cssRules;
+ hasNestedRules = ruleList != null;
+ nested = Array.from(ruleList || []);
+ } catch {
+ continue;
+ }
+ const keyframesName = keyframesRuleName(rule, cssText);
+ if (keyframesName) {
+ // Keyframes do not merge: when a name is defined more than once, the
+ // later effective definition replaces the earlier one.
+ keyframeCandidates.set(keyframesName, {
+ name: keyframesName,
+ cssText,
+ });
+ continue;
+ }
+ if (hasNestedRules) {
+ if (!conditionalCssRuleIsActive(rule)) continue;
+ appendRules(nested, requiresAppliedMatch || isContainerCssRule(rule));
+ continue;
+ }
+ // Other selector-less leaf at-rules cannot be tied to a rendered node.
+ }
+ };
+ const appendSheet = (sheet) => {
+ if (!sheet || seen.has(sheet)) return;
+ seen.add(sheet);
+ let rules;
+ try { rules = Array.from(sheet.cssRules || sheet.rules || []); }
+ catch { return; }
+ appendRules(rules);
+ };
+ let sheets;
+ try { sheets = Array.from(document.styleSheets || []); }
+ catch { return ''; }
+ for (const sheet of sheets) {
+ const owner = sheet.ownerNode;
+ if (owner?.tagName?.toLowerCase() !== 'link') continue;
+ if (!/\bstylesheet\b/i.test(owner.getAttribute?.('rel') || '')) continue;
+ appendSheet(sheet);
+ }
+ // Motion checks need the effective body of a live animation's keyframes.
+ // Let the browser resolve duplicate names across source order, imports,
+ // conditional groups, and cascade layers, then serialize those computed
+ // frames back into the pattern corpus. Browsers also make container-nested
+ // keyframes globally available, so lexical grouping is not a reliable
+ // activity signal. When the Web Animations API is unavailable, fall back to
+ // the last source-order definition referenced by a retained linked rule.
+ const resolvedKeyframes = resolvedAnimationKeyframes(new Set(keyframeCandidates.keys()));
+ if (resolvedKeyframes) {
+ parts.push(...resolvedKeyframes.values());
+ } else {
+ for (const candidate of keyframeCandidates.values()) {
+ if (!animationNames.has(candidate.name)) continue;
+ parts.push(candidate.cssText);
+ }
+ }
+ return parts.join('\n');
+ }
+
function browserFindingsFromMap(groupMap) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
@@ -8548,18 +8932,16 @@ if (IS_BROWSER) {
// (the CSS ships here, but the pattern never renders — the live DOM is
// ground truth in the browser), and a match under a data-impeccable-ignore
// ancestor is waived. Selector-less findings stay page-level.
- const scopedHtmlFindings = checkHtmlPatterns(docClone.outerHTML).filter(f => {
+ const html = docClone.outerHTML;
+ const corpora = buildHtmlPatternCorpora(html);
+ const linkedCss = linkedStylesheetText();
+ if (linkedCss) corpora.styleText += `\n${linkedCss}`;
+ const scopedHtmlFindings = checkHtmlPatterns(html, corpora).filter(f => {
if (!f.selector) return true;
- const query = String(f.selector).replace(/::?[a-zA-Z-]+(\([^)]*\))?/g, '').trim().replace(/,\s*(?=,|$)/g, '');
- if (!query || /^[,\s]*$/.test(query)) return true;
- let matches;
- try {
- matches = document.querySelectorAll(query);
- } catch {
- return true;
- }
+ const matches = selectorNodesForLiveDom(document, f.selector);
+ if (!matches) return false;
if (matches.length === 0) return false;
- return [...matches].some(el => !scopedIgnoreActive(el, f.id));
+ return matches.some(el => !scopedIgnoreActive(el, f.id));
});
if (scopedHtmlFindings.length > 0) {
const mapped = scopedHtmlFindings.map(f => {
diff --git a/.grok/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs b/.grok/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
index f3ff43c84..ac4bd0a7c 100644
--- a/.grok/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
+++ b/.grok/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
@@ -2,7 +2,7 @@ import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { finding } from '../../findings.mjs';
+import { deriveAdvisoryFlag, finding } from '../../findings.mjs';
import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
import { checkContentHiddenAtRest } from '../../rules/checks.mjs';
@@ -394,7 +394,7 @@ async function detectUrl(rawUrl, options = {}) {
// Per-finding severity promotion (e.g. hero-region pulsing dot)
// overrides the registry default carried by finding().
if (f.severity && f.severity !== item.severity) item.severity = f.severity;
- return item;
+ return deriveAdvisoryFlag(item);
});
}
diff --git a/.grok/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs b/.grok/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
index 84e6ab1f5..dac6939b0 100644
--- a/.grok/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
+++ b/.grok/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
@@ -9,7 +9,7 @@ import {
} from '../../design-system.mjs';
import { isFullPage } from '../../shared/page.mjs';
import { applyInlineIgnores } from '../../shared/inline-ignores.mjs';
-import { finding } from '../../findings.mjs';
+import { deriveAdvisoryFlag, finding } from '../../findings.mjs';
import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import {
checkElementBorders,
@@ -257,7 +257,7 @@ async function detectHtml(filePath, options = {}) {
// severity (e.g. a pulsing dot inside a header/nav landmark) that
// overrides the registry default.
if (f.severity) item.severity = f.severity;
- findings.push(item);
+ findings.push(deriveAdvisoryFlag(item));
}
// Text-content analyzers (em-dash overuse, marketing buzzwords,
// numbered section markers, aphoristic cadence) live in the regex
diff --git a/.grok/skills/impeccable/scripts/detector/findings.mjs b/.grok/skills/impeccable/scripts/detector/findings.mjs
index fa98dd935..ae7e134f9 100644
--- a/.grok/skills/impeccable/scripts/detector/findings.mjs
+++ b/.grok/skills/impeccable/scripts/detector/findings.mjs
@@ -4,6 +4,12 @@ function getAP(id) {
return getAntipattern(id);
}
+function deriveAdvisoryFlag(item) {
+ if (item.severity === 'advisory') item.advisory = true;
+ else delete item.advisory;
+ return item;
+}
+
function finding(id, filePath, snippet, line = 0) {
const ap = getAP(id);
const base = { antipattern: id, name: ap.name, description: ap.description, severity: ap.severity || 'warning', category: ap.category || null, file: filePath, line, snippet };
@@ -11,8 +17,7 @@ function finding(id, filePath, snippet, line = 0) {
// failures. Carry the flag on the finding so every consumer (CLI, JSON, hook)
// can partition without a registry lookup. Only stamped when true to keep the
// finding shape stable for the vast majority of rules.
- if (ap.advisory === true) base.advisory = true;
- return base;
+ return deriveAdvisoryFlag(base);
}
-export { getAP, finding };
+export { getAP, finding, deriveAdvisoryFlag };
diff --git a/.grok/skills/impeccable/scripts/detector/registry/antipatterns.mjs b/.grok/skills/impeccable/scripts/detector/registry/antipatterns.mjs
index 945307783..7c692c79a 100644
--- a/.grok/skills/impeccable/scripts/detector/registry/antipatterns.mjs
+++ b/.grok/skills/impeccable/scripts/detector/registry/antipatterns.mjs
@@ -233,7 +233,7 @@ const ANTIPATTERNS = [
// rather than a failure. It fires only on the AI saturation pattern, not on
// ordinary prose. Advisory findings are surfaced separately, never counted
// as failures, and skipped by the design hook unless a project opts in.
- advisory: true,
+ severity: 'advisory',
name: 'Em-dash overuse',
description:
'Em-dash saturation in body copy is an AI cadence tell. Advisory only: humans use em-dashes legitimately, so this fires only on saturation — at least 8 em-dashes (— or --) at a density near one per 500 characters of body text — never on a long article that uses a few. Prefer commas, colons, periods, or parentheses.',
@@ -588,9 +588,10 @@ function getAntipattern(id) {
// Advisory rules are detected and reported, but never treated as failures:
// the CLI lists them under a separate "Advisory" section, they do not affect
// exit codes or the failure count, and the design hook skips them by default.
-// The set is derived from the registry so a rule only needs `advisory: true`.
+// `severity` is the canonical registry field. The runtime finding serializer
+// derives its `advisory: true` compatibility/output flag from this set.
const ADVISORY_RULE_IDS = new Set(
- ANTIPATTERNS.filter(rule => rule.advisory === true).map(rule => rule.id),
+ ANTIPATTERNS.filter(rule => rule.severity === 'advisory').map(rule => rule.id),
);
function isAdvisoryRule(id) {
diff --git a/.grok/skills/impeccable/scripts/detector/rules/checks.mjs b/.grok/skills/impeccable/scripts/detector/rules/checks.mjs
index 579e1c12e..a24631ce9 100644
--- a/.grok/skills/impeccable/scripts/detector/rules/checks.mjs
+++ b/.grok/skills/impeccable/scripts/detector/rules/checks.mjs
@@ -688,7 +688,10 @@ function enclosingCssSelector(cssText, index) {
// `{` belongs to some other selector.
const closeBeforeIndex = cssText.lastIndexOf('}', index);
if (closeBeforeIndex > open) return null;
- const prevClose = Math.max(cssText.lastIndexOf('}', open - 1), cssText.lastIndexOf(';', open - 1));
+ // Ignore delimiters inside comments when locating the previous declaration.
+ // Keeping comment length intact preserves indices into the original source.
+ const beforeOpen = cssText.slice(0, open).replace(/\/\*[\s\S]*?\*\//g, comment => ' '.repeat(comment.length));
+ const prevClose = Math.max(beforeOpen.lastIndexOf('}'), beforeOpen.lastIndexOf(';'));
const raw = cssText.slice(prevClose + 1, open).replace(/\/\*[\s\S]*?\*\//g, '').trim().replace(/\s+/g, ' ');
if (!raw || raw.startsWith('@') || /^\d/.test(raw) || /[{}<]/.test(raw)) return null;
// Keyframe steps: percentage steps fail the digit test above, but `from`
@@ -4020,14 +4023,17 @@ function checkTypography() {
}
if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
+ // Report the actual primary face: the uniquely most-used family. The old
+ // 15% threshold labeled secondary faces as primary (e.g. an 82/18 split).
+ const ranked = [...fontUsage.entries()].sort((a, b) => b[1] - a[1]);
+ const [primary] = ranked;
+ const tied = ranked[1]?.[1] === primary?.[1];
+ if (primary && !tied) {
+ const [font, count] = primary;
const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ if (OVERUSED_FONTS.has(font) && !isBrandFontOnOwnDomain(font)) {
+ findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ }
}
}
diff --git a/.grok/skills/impeccable/scripts/hook-lib.mjs b/.grok/skills/impeccable/scripts/hook-lib.mjs
index 767fe65a6..6d8c3db81 100644
--- a/.grok/skills/impeccable/scripts/hook-lib.mjs
+++ b/.grok/skills/impeccable/scripts/hook-lib.mjs
@@ -138,17 +138,20 @@ export const IMMEDIATE_TIER_RULES = new Set([
// the agent is never nagged about a taste call a human might make on purpose.
// A project opts back in with `.impeccable/config.json`:
// { "detector": { "advisoryRules": "include" } }
-// This set is the hook's own copy of the registry's `advisory: true` rules,
-// mirroring how IMMEDIATE_TIER_RULES lists rule ids inline so the hook stays
-// self-contained and testable without loading the detector. Keep it in sync
-// with the registry (cli/engine/registry/antipatterns.mjs).
+// This legacy id fallback keeps older detector findings recognizable when they
+// carry neither the current runtime flag nor the canonical advisory severity.
+// Current findings are classified by their serialized metadata below.
export const ADVISORY_RULES = new Set([
'em-dash-overuse',
]);
export function isAdvisoryFinding(finding) {
const id = finding && normalizeIgnoreRule(finding.antipattern);
- return Boolean(id && (ADVISORY_RULES.has(id) || finding.advisory === true));
+ return Boolean(id && (
+ ADVISORY_RULES.has(id)
+ || finding.advisory === true
+ || finding.severity === 'advisory'
+ ));
}
export const DEFAULT_CONFIG = Object.freeze({
diff --git a/.hermes/skills/impeccable/scripts/detector/browser/injected/index.mjs b/.hermes/skills/impeccable/scripts/detector/browser/injected/index.mjs
index febf7f297..76fc558e5 100644
--- a/.hermes/skills/impeccable/scripts/detector/browser/injected/index.mjs
+++ b/.hermes/skills/impeccable/scripts/detector/browser/injected/index.mjs
@@ -1228,14 +1228,17 @@ if (IS_BROWSER) {
isHidden: isElementHidden(el),
findings: findings.map(f => {
const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
+ const severity = f.severity || ap?.severity || 'warning';
return {
type: f.type || f.id,
category: ap ? ap.category : 'quality',
- severity: f.severity || ap?.severity || 'warning',
+ severity,
// Advisory findings (em-dash overuse, etc.) are surfaced but never
// treated as failures; carry the flag so the overlay/extension can
// render them with the mildest affordance and consumers can filter.
- advisory: (ap && ap.advisory === true) || f.advisory === true,
+ // Per-finding promotions override the registry default, so derive
+ // this strictly from the effective severity.
+ advisory: severity === 'advisory',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
@@ -1277,6 +1280,381 @@ if (IS_BROWSER) {
else groupMap.set(el, [...kept]);
}
+ function pseudoElementHostSelector(selector) {
+ const raw = String(selector || '');
+ const legacyNames = new Set(['before', 'after', 'first-letter', 'first-line']);
+ const isNameChar = char => /[a-zA-Z0-9_-]/.test(char || '');
+ const consumeFunction = (start) => {
+ let depth = 0;
+ let quote = '';
+ for (let i = start; i < raw.length; i += 1) {
+ const char = raw[i];
+ if (char === '\\') {
+ i += 1;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '(') depth += 1;
+ if (char === ')' && --depth === 0) return i + 1;
+ }
+ return raw.length;
+ };
+
+ let output = '';
+ let found = false;
+ for (let i = 0; i < raw.length;) {
+ const char = raw[i];
+ if (char === '\\') {
+ output += raw.slice(i, Math.min(raw.length, i + 2));
+ i += 2;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ const quote = char;
+ const start = i;
+ i += 1;
+ while (i < raw.length) {
+ if (raw[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ const value = raw[i];
+ i += 1;
+ if (value === quote) break;
+ }
+ output += raw.slice(start, i);
+ continue;
+ }
+ if (char !== ':') {
+ output += char;
+ i += 1;
+ continue;
+ }
+
+ let end = i + 1;
+ let isPseudoElement = false;
+ if (raw[end] === ':') {
+ end += 1;
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = end > nameStart;
+ } else {
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = legacyNames.has(raw.slice(nameStart, end).toLowerCase());
+ }
+ if (!isPseudoElement) {
+ output += char;
+ i += 1;
+ continue;
+ }
+ if (raw[end] === '(') end = consumeFunction(end);
+ found = true;
+ if (!output || /[\s>+~,]/.test(output[output.length - 1])) output += '*';
+ i = end;
+ }
+ if (!found) return null;
+ return output.trim().replace(/,\s*(?=,|$)/g, '');
+ }
+
+ function selectorNodesForLiveDom(root, selector) {
+ const raw = String(selector || '').trim();
+ if (!raw) return null;
+ const fallback = pseudoElementHostSelector(raw);
+ if (fallback == null) {
+ // An empty result from a valid full selector is authoritative. In
+ // particular, do not broaden inactive :hover/:focus/:not() rules to
+ // their host element by stripping pseudo-classes.
+ try { return Array.from(root.querySelectorAll(raw)); }
+ catch { return null; }
+ }
+
+ // Resolve pseudo-elements to their originating live elements. An attached
+ // pseudo-element (`.card::before`) belongs to the element before it, while
+ // a hostless pseudo-element after a combinator (`main > ::before`) belongs
+ // to a matching element at that position (`main > *`). Replacing every
+ // pseudo indiscriminately with an empty string leaves the latter as the
+ // invalid selector `main >` and makes absent hosts indistinguishable from
+ // selectors the DOM API cannot parse.
+ if (!fallback || /^[,\s]*$/.test(fallback)) return null;
+ try { return Array.from(root.querySelectorAll(fallback)); }
+ catch { return null; }
+ }
+
+ let containerProbeSequence = 0;
+
+ function isContainerCssRule(rule) {
+ return rule?.constructor?.name === 'CSSContainerRule'
+ || /^\s*@container\b/i.test(rule?.cssText || '');
+ }
+
+ function styleRuleAppliesToLiveMatches(rule, matches) {
+ const style = rule?.style;
+ if (!style || !matches?.length || typeof getComputedStyle !== 'function') return false;
+ const sequence = ++containerProbeSequence;
+ const property = `--impeccable-container-probe-${sequence}-${Math.random().toString(36).slice(2)}`;
+ const value = `impeccable-container-active-${sequence}`;
+ const previousValue = style.getPropertyValue(property);
+ const previousPriority = style.getPropertyPriority(property);
+ try {
+ style.setProperty(property, value, 'important');
+ } catch {
+ return false;
+ }
+
+ const pseudoElements = [...new Set(
+ String(rule.selectorText || '').match(/::[a-zA-Z-]+(?:\([^)]*\))?/g) || [],
+ )];
+ try {
+ return matches.some(el => [null, ...pseudoElements].some(pseudo => {
+ try {
+ const computed = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el);
+ return computed.getPropertyValue(property).trim() === value;
+ } catch {
+ return false;
+ }
+ }));
+ } finally {
+ if (previousValue) style.setProperty(property, previousValue, previousPriority);
+ else style.removeProperty(property);
+ }
+ }
+
+ function conditionalCssRuleIsActive(rule) {
+ const type = Number(rule?.type);
+ const constructorName = rule?.constructor?.name || '';
+ if (constructorName === 'CSSMediaRule' || type === 4) {
+ const condition = rule.conditionText || rule.media?.mediaText || '';
+ if (!condition || typeof window.matchMedia !== 'function') return true;
+ try { return window.matchMedia(condition).matches; }
+ catch { return true; }
+ }
+ if (constructorName === 'CSSSupportsRule' || type === 12) {
+ const condition = rule.conditionText || '';
+ if (!condition || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return true;
+ try { return CSS.supports(condition); }
+ catch { return true; }
+ }
+ return true;
+ }
+
+ function splitCssCommaList(value) {
+ const parts = [];
+ let current = '';
+ let quote = '';
+ let escaped = false;
+ for (const char of String(value || '')) {
+ if (escaped) {
+ current += char;
+ escaped = false;
+ continue;
+ }
+ if (char === '\\') {
+ current += char;
+ escaped = true;
+ continue;
+ }
+ if (quote) {
+ current += char;
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ current += char;
+ continue;
+ }
+ if (char === ',') {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+ return parts;
+ }
+
+ function normalizeAnimationName(value) {
+ const name = String(value || '').trim();
+ if (name.length >= 2 && name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) {
+ return name.slice(1, -1);
+ }
+ return name;
+ }
+
+ function animationNamesDeclaredByRule(rule) {
+ const style = rule?.style;
+ if (!style) return [];
+ let value = '';
+ try {
+ value = style.animationName
+ || style.getPropertyValue?.('animation-name')
+ || style.webkitAnimationName
+ || style.getPropertyValue?.('-webkit-animation-name')
+ || '';
+ } catch {
+ return [];
+ }
+ return splitCssCommaList(value)
+ .map(normalizeAnimationName)
+ .filter(name => name && name.toLowerCase() !== 'none');
+ }
+
+ function keyframesRuleName(rule, cssText) {
+ const constructorName = rule?.constructor?.name || '';
+ const type = Number(rule?.type);
+ const isKeyframes = constructorName === 'CSSKeyframesRule'
+ || constructorName === 'WebKitCSSKeyframesRule'
+ || type === 7
+ || /^\s*@(?:-webkit-)?keyframes\b/i.test(cssText);
+ if (!isKeyframes) return '';
+ const match = String(cssText || '').match(/^\s*@(?:-webkit-)?keyframes\s+([^\s{]+)/i);
+ return normalizeAnimationName(rule?.name || match?.[1] || '');
+ }
+
+ function cssPropertyName(property) {
+ if (property.startsWith('--')) return property;
+ return property.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
+ }
+
+ function resolvedAnimationKeyframes(candidateNames) {
+ if (typeof document.getAnimations !== 'function') return null;
+ let animations;
+ try { animations = document.getAnimations(); }
+ catch { return null; }
+
+ const resolved = new Map();
+ const metadata = new Set(['offset', 'computedOffset', 'easing', 'composite']);
+ for (const animation of animations) {
+ const name = normalizeAnimationName(animation?.animationName || '');
+ if (!name || !candidateNames.has(name) || resolved.has(name)) continue;
+ let frames;
+ try { frames = animation.effect?.getKeyframes?.() || []; }
+ catch { continue; }
+ const blocks = [];
+ for (const frame of frames) {
+ const rawOffset = Number.isFinite(frame.computedOffset) ? frame.computedOffset : frame.offset;
+ if (!Number.isFinite(rawOffset)) continue;
+ const offset = Math.round(rawOffset * 1000000) / 10000;
+ const declarations = Object.entries(frame)
+ .filter(([property, value]) => !metadata.has(property) && value != null && value !== '')
+ .map(([property, value]) => `${cssPropertyName(property)}: ${value};`);
+ const easing = String(frame.easing || '').trim();
+ if (easing && easing.toLowerCase() !== 'linear') {
+ declarations.push(`animation-timing-function: ${easing};`);
+ }
+ if (declarations.length === 0) continue;
+ blocks.push(`${offset}% { ${declarations.join(' ')} }`);
+ }
+ if (blocks.length > 0) resolved.set(name, `@keyframes ${name} { ${blocks.join(' ')} }`);
+ }
+ return resolved;
+ }
+
+ // Read CSS that is absent from document.outerHTML. Inline <style> blocks are
+ // already present in the HTML pattern corpus, so limit this walk to linked
+ // stylesheets. Flatten grouping rules so each declaration keeps its selector,
+ // and admit only selector rules that target the live DOM. That prevents
+ // unused utilities from feeding both selector-scoped and page-level checks.
+ // Same-origin CSS and readable CORS sheets participate; browser security
+ // exceptions for cross-origin sheets are expected and skipped.
+ function linkedStylesheetText() {
+ const parts = [];
+ const seen = new Set();
+ const animationNames = new Set();
+ const keyframeCandidates = new Map();
+ const appendRules = (rules, requiresAppliedMatch = false) => {
+ for (const rule of rules) {
+ if (rule.styleSheet) {
+ appendSheet(rule.styleSheet);
+ continue;
+ }
+ const cssText = rule.cssText || '';
+ if (rule.selectorText) {
+ const matches = selectorNodesForLiveDom(document, rule.selectorText);
+ // Only declarations with a resolvable live host enter the corpus.
+ // Unresolvable selectors are uncertain, not evidence that a pattern
+ // rendered, and retaining them would leak unused CSS into findings.
+ if (
+ matches?.length > 0
+ && (!requiresAppliedMatch || styleRuleAppliesToLiveMatches(rule, matches))
+ ) {
+ parts.push(cssText);
+ for (const name of animationNamesDeclaredByRule(rule)) animationNames.add(name);
+ }
+ continue;
+ }
+ let nested = [];
+ let hasNestedRules = false;
+ try {
+ const ruleList = rule.cssRules;
+ hasNestedRules = ruleList != null;
+ nested = Array.from(ruleList || []);
+ } catch {
+ continue;
+ }
+ const keyframesName = keyframesRuleName(rule, cssText);
+ if (keyframesName) {
+ // Keyframes do not merge: when a name is defined more than once, the
+ // later effective definition replaces the earlier one.
+ keyframeCandidates.set(keyframesName, {
+ name: keyframesName,
+ cssText,
+ });
+ continue;
+ }
+ if (hasNestedRules) {
+ if (!conditionalCssRuleIsActive(rule)) continue;
+ appendRules(nested, requiresAppliedMatch || isContainerCssRule(rule));
+ continue;
+ }
+ // Other selector-less leaf at-rules cannot be tied to a rendered node.
+ }
+ };
+ const appendSheet = (sheet) => {
+ if (!sheet || seen.has(sheet)) return;
+ seen.add(sheet);
+ let rules;
+ try { rules = Array.from(sheet.cssRules || sheet.rules || []); }
+ catch { return; }
+ appendRules(rules);
+ };
+ let sheets;
+ try { sheets = Array.from(document.styleSheets || []); }
+ catch { return ''; }
+ for (const sheet of sheets) {
+ const owner = sheet.ownerNode;
+ if (owner?.tagName?.toLowerCase() !== 'link') continue;
+ if (!/\bstylesheet\b/i.test(owner.getAttribute?.('rel') || '')) continue;
+ appendSheet(sheet);
+ }
+ // Motion checks need the effective body of a live animation's keyframes.
+ // Let the browser resolve duplicate names across source order, imports,
+ // conditional groups, and cascade layers, then serialize those computed
+ // frames back into the pattern corpus. Browsers also make container-nested
+ // keyframes globally available, so lexical grouping is not a reliable
+ // activity signal. When the Web Animations API is unavailable, fall back to
+ // the last source-order definition referenced by a retained linked rule.
+ const resolvedKeyframes = resolvedAnimationKeyframes(new Set(keyframeCandidates.keys()));
+ if (resolvedKeyframes) {
+ parts.push(...resolvedKeyframes.values());
+ } else {
+ for (const candidate of keyframeCandidates.values()) {
+ if (!animationNames.has(candidate.name)) continue;
+ parts.push(candidate.cssText);
+ }
+ }
+ return parts.join('\n');
+ }
+
function browserFindingsFromMap(groupMap) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
@@ -1650,18 +2028,16 @@ if (IS_BROWSER) {
// (the CSS ships here, but the pattern never renders — the live DOM is
// ground truth in the browser), and a match under a data-impeccable-ignore
// ancestor is waived. Selector-less findings stay page-level.
- const scopedHtmlFindings = checkHtmlPatterns(docClone.outerHTML).filter(f => {
+ const html = docClone.outerHTML;
+ const corpora = buildHtmlPatternCorpora(html);
+ const linkedCss = linkedStylesheetText();
+ if (linkedCss) corpora.styleText += `\n${linkedCss}`;
+ const scopedHtmlFindings = checkHtmlPatterns(html, corpora).filter(f => {
if (!f.selector) return true;
- const query = String(f.selector).replace(/::?[a-zA-Z-]+(\([^)]*\))?/g, '').trim().replace(/,\s*(?=,|$)/g, '');
- if (!query || /^[,\s]*$/.test(query)) return true;
- let matches;
- try {
- matches = document.querySelectorAll(query);
- } catch {
- return true;
- }
+ const matches = selectorNodesForLiveDom(document, f.selector);
+ if (!matches) return false;
if (matches.length === 0) return false;
- return [...matches].some(el => !scopedIgnoreActive(el, f.id));
+ return matches.some(el => !scopedIgnoreActive(el, f.id));
});
if (scopedHtmlFindings.length > 0) {
const mapped = scopedHtmlFindings.map(f => {
diff --git a/.hermes/skills/impeccable/scripts/detector/cli/main.mjs b/.hermes/skills/impeccable/scripts/detector/cli/main.mjs
index 4476d04f1..3451d6c6b 100644
--- a/.hermes/skills/impeccable/scripts/detector/cli/main.mjs
+++ b/.hermes/skills/impeccable/scripts/detector/cli/main.mjs
@@ -37,13 +37,30 @@ function fileUrlToLocalPath(url) {
}
}
+const URL_TARGET_RE = /^(?:https?|file):\/\//i;
+
+// Some agent runners hand a shell-ready URL list to Node as one argv value.
+// A browser accepts the spaces as part of one encoded URL, producing a
+// plausible scan attributed to a bogus joined path. Expand only when every
+// whitespace-delimited token is independently a URL, preserving ordinary
+// filesystem paths that contain spaces.
+function expandJoinedUrlTargets(targets) {
+ return targets.flatMap((target) => {
+ if (!/\s/.test(target)) return [target];
+ const parts = target.trim().split(/\s+/).filter(Boolean);
+ return parts.length > 1 && parts.every(part => URL_TARGET_RE.test(part))
+ ? parts
+ : [target];
+ });
+}
+
// Advisory findings are detected but never treated as failures: they list in a
// separate, visually dimmed section, are excluded from the failure count that
// drives the exit code, and carry `"advisory": true` in JSON so consumers can
// filter. Every advisory finding carries the flag (stamped by the registry via
// findings.mjs).
function isAdvisory(finding) {
- return finding && finding.advisory === true;
+ return Boolean(finding && (finding.advisory === true || finding.severity === 'advisory'));
}
function partitionAdvisory(findings) {
@@ -168,6 +185,10 @@ Advisory findings:
counted as failures and never changing the exit code. They stay out of the
failure count so they never block automation. --no-advisory hides them.
+Output streams:
+ Human-readable findings go to stderr so stdout stays available for structured
+ output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.
+
Project config:
Respects .impeccable/config.json and .impeccable/config.local.json detector
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
@@ -185,7 +206,7 @@ Detection modes:
HTML files Static HTML/CSS analysis (default, catches linked CSS)
Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)
URLs Puppeteer full browser rendering (auto-detected;
- http(s):// and file:// URLs)
+ http(s):// and file:// URLs; accessible linked CSS included)
Examples:
impeccable detect src/
@@ -283,7 +304,7 @@ async function detectCli() {
const designSystem = loadDesignSystemForTarget(localPath, { cache: designSystemCache });
return designSystem ? { ...baseScanOptions, designSystem } : baseScanOptions;
};
- const targets = args.filter(a => !a.startsWith('--'));
+ const targets = expandJoinedUrlTargets(args.filter(a => !a.startsWith('--')));
if (helpMode) { printUsage(); process.exit(0); }
@@ -297,13 +318,12 @@ async function detectCli() {
// real cascade, real computed styles, real layout. Callers that want a
// browser-grade scan of a local artifact can pass file:///abs/path.html
// instead of the bare path (which stays on the static engine).
- const urlRe = /^(?:https?|file):\/\//i;
- const urlTargetCount = paths.filter(target => urlRe.test(target)).length;
+ const urlTargetCount = paths.filter(target => URL_TARGET_RE.test(target)).length;
const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
try {
for (const target of paths) {
- if (urlRe.test(target)) {
+ if (URL_TARGET_RE.test(target)) {
// A file:// URL points at a local artifact, so its design system
// resolves from that file's project. A remote http(s) URL has no
// local project — it gets base options (no design system), never
diff --git a/.hermes/skills/impeccable/scripts/detector/detect-antipatterns-browser.js b/.hermes/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
index e6899f569..460ffb45b 100644
--- a/.hermes/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
+++ b/.hermes/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
@@ -358,7 +358,7 @@ const ANTIPATTERNS = [
// rather than a failure. It fires only on the AI saturation pattern, not on
// ordinary prose. Advisory findings are surfaced separately, never counted
// as failures, and skipped by the design hook unless a project opts in.
- advisory: true,
+ severity: 'advisory',
name: 'Em-dash overuse',
description:
'Em-dash saturation in body copy is an AI cadence tell. Advisory only: humans use em-dashes legitimately, so this fires only on saturation — at least 8 em-dashes (— or --) at a density near one per 500 characters of body text — never on a long article that uses a few. Prefer commas, colons, periods, or parentheses.',
@@ -1961,7 +1961,10 @@ function enclosingCssSelector(cssText, index) {
// `{` belongs to some other selector.
const closeBeforeIndex = cssText.lastIndexOf('}', index);
if (closeBeforeIndex > open) return null;
- const prevClose = Math.max(cssText.lastIndexOf('}', open - 1), cssText.lastIndexOf(';', open - 1));
+ // Ignore delimiters inside comments when locating the previous declaration.
+ // Keeping comment length intact preserves indices into the original source.
+ const beforeOpen = cssText.slice(0, open).replace(/\/\*[\s\S]*?\*\//g, comment => ' '.repeat(comment.length));
+ const prevClose = Math.max(beforeOpen.lastIndexOf('}'), beforeOpen.lastIndexOf(';'));
const raw = cssText.slice(prevClose + 1, open).replace(/\/\*[\s\S]*?\*\//g, '').trim().replace(/\s+/g, ' ');
if (!raw || raw.startsWith('@') || /^\d/.test(raw) || /[{}<]/.test(raw)) return null;
// Keyframe steps: percentage steps fail the digit test above, but `from`
@@ -5293,14 +5296,17 @@ function checkTypography() {
}
if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
+ // Report the actual primary face: the uniquely most-used family. The old
+ // 15% threshold labeled secondary faces as primary (e.g. an 82/18 split).
+ const ranked = [...fontUsage.entries()].sort((a, b) => b[1] - a[1]);
+ const [primary] = ranked;
+ const tied = ranked[1]?.[1] === primary?.[1];
+ if (primary && !tied) {
+ const [font, count] = primary;
const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ if (OVERUSED_FONTS.has(font) && !isBrandFontOnOwnDomain(font)) {
+ findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ }
}
}
@@ -8126,14 +8132,17 @@ if (IS_BROWSER) {
isHidden: isElementHidden(el),
findings: findings.map(f => {
const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
+ const severity = f.severity || ap?.severity || 'warning';
return {
type: f.type || f.id,
category: ap ? ap.category : 'quality',
- severity: f.severity || ap?.severity || 'warning',
+ severity,
// Advisory findings (em-dash overuse, etc.) are surfaced but never
// treated as failures; carry the flag so the overlay/extension can
// render them with the mildest affordance and consumers can filter.
- advisory: (ap && ap.advisory === true) || f.advisory === true,
+ // Per-finding promotions override the registry default, so derive
+ // this strictly from the effective severity.
+ advisory: severity === 'advisory',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
@@ -8175,6 +8184,381 @@ if (IS_BROWSER) {
else groupMap.set(el, [...kept]);
}
+ function pseudoElementHostSelector(selector) {
+ const raw = String(selector || '');
+ const legacyNames = new Set(['before', 'after', 'first-letter', 'first-line']);
+ const isNameChar = char => /[a-zA-Z0-9_-]/.test(char || '');
+ const consumeFunction = (start) => {
+ let depth = 0;
+ let quote = '';
+ for (let i = start; i < raw.length; i += 1) {
+ const char = raw[i];
+ if (char === '\\') {
+ i += 1;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '(') depth += 1;
+ if (char === ')' && --depth === 0) return i + 1;
+ }
+ return raw.length;
+ };
+
+ let output = '';
+ let found = false;
+ for (let i = 0; i < raw.length;) {
+ const char = raw[i];
+ if (char === '\\') {
+ output += raw.slice(i, Math.min(raw.length, i + 2));
+ i += 2;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ const quote = char;
+ const start = i;
+ i += 1;
+ while (i < raw.length) {
+ if (raw[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ const value = raw[i];
+ i += 1;
+ if (value === quote) break;
+ }
+ output += raw.slice(start, i);
+ continue;
+ }
+ if (char !== ':') {
+ output += char;
+ i += 1;
+ continue;
+ }
+
+ let end = i + 1;
+ let isPseudoElement = false;
+ if (raw[end] === ':') {
+ end += 1;
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = end > nameStart;
+ } else {
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = legacyNames.has(raw.slice(nameStart, end).toLowerCase());
+ }
+ if (!isPseudoElement) {
+ output += char;
+ i += 1;
+ continue;
+ }
+ if (raw[end] === '(') end = consumeFunction(end);
+ found = true;
+ if (!output || /[\s>+~,]/.test(output[output.length - 1])) output += '*';
+ i = end;
+ }
+ if (!found) return null;
+ return output.trim().replace(/,\s*(?=,|$)/g, '');
+ }
+
+ function selectorNodesForLiveDom(root, selector) {
+ const raw = String(selector || '').trim();
+ if (!raw) return null;
+ const fallback = pseudoElementHostSelector(raw);
+ if (fallback == null) {
+ // An empty result from a valid full selector is authoritative. In
+ // particular, do not broaden inactive :hover/:focus/:not() rules to
+ // their host element by stripping pseudo-classes.
+ try { return Array.from(root.querySelectorAll(raw)); }
+ catch { return null; }
+ }
+
+ // Resolve pseudo-elements to their originating live elements. An attached
+ // pseudo-element (`.card::before`) belongs to the element before it, while
+ // a hostless pseudo-element after a combinator (`main > ::before`) belongs
+ // to a matching element at that position (`main > *`). Replacing every
+ // pseudo indiscriminately with an empty string leaves the latter as the
+ // invalid selector `main >` and makes absent hosts indistinguishable from
+ // selectors the DOM API cannot parse.
+ if (!fallback || /^[,\s]*$/.test(fallback)) return null;
+ try { return Array.from(root.querySelectorAll(fallback)); }
+ catch { return null; }
+ }
+
+ let containerProbeSequence = 0;
+
+ function isContainerCssRule(rule) {
+ return rule?.constructor?.name === 'CSSContainerRule'
+ || /^\s*@container\b/i.test(rule?.cssText || '');
+ }
+
+ function styleRuleAppliesToLiveMatches(rule, matches) {
+ const style = rule?.style;
+ if (!style || !matches?.length || typeof getComputedStyle !== 'function') return false;
+ const sequence = ++containerProbeSequence;
+ const property = `--impeccable-container-probe-${sequence}-${Math.random().toString(36).slice(2)}`;
+ const value = `impeccable-container-active-${sequence}`;
+ const previousValue = style.getPropertyValue(property);
+ const previousPriority = style.getPropertyPriority(property);
+ try {
+ style.setProperty(property, value, 'important');
+ } catch {
+ return false;
+ }
+
+ const pseudoElements = [...new Set(
+ String(rule.selectorText || '').match(/::[a-zA-Z-]+(?:\([^)]*\))?/g) || [],
+ )];
+ try {
+ return matches.some(el => [null, ...pseudoElements].some(pseudo => {
+ try {
+ const computed = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el);
+ return computed.getPropertyValue(property).trim() === value;
+ } catch {
+ return false;
+ }
+ }));
+ } finally {
+ if (previousValue) style.setProperty(property, previousValue, previousPriority);
+ else style.removeProperty(property);
+ }
+ }
+
+ function conditionalCssRuleIsActive(rule) {
+ const type = Number(rule?.type);
+ const constructorName = rule?.constructor?.name || '';
+ if (constructorName === 'CSSMediaRule' || type === 4) {
+ const condition = rule.conditionText || rule.media?.mediaText || '';
+ if (!condition || typeof window.matchMedia !== 'function') return true;
+ try { return window.matchMedia(condition).matches; }
+ catch { return true; }
+ }
+ if (constructorName === 'CSSSupportsRule' || type === 12) {
+ const condition = rule.conditionText || '';
+ if (!condition || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return true;
+ try { return CSS.supports(condition); }
+ catch { return true; }
+ }
+ return true;
+ }
+
+ function splitCssCommaList(value) {
+ const parts = [];
+ let current = '';
+ let quote = '';
+ let escaped = false;
+ for (const char of String(value || '')) {
+ if (escaped) {
+ current += char;
+ escaped = false;
+ continue;
+ }
+ if (char === '\\') {
+ current += char;
+ escaped = true;
+ continue;
+ }
+ if (quote) {
+ current += char;
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ current += char;
+ continue;
+ }
+ if (char === ',') {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+ return parts;
+ }
+
+ function normalizeAnimationName(value) {
+ const name = String(value || '').trim();
+ if (name.length >= 2 && name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) {
+ return name.slice(1, -1);
+ }
+ return name;
+ }
+
+ function animationNamesDeclaredByRule(rule) {
+ const style = rule?.style;
+ if (!style) return [];
+ let value = '';
+ try {
+ value = style.animationName
+ || style.getPropertyValue?.('animation-name')
+ || style.webkitAnimationName
+ || style.getPropertyValue?.('-webkit-animation-name')
+ || '';
+ } catch {
+ return [];
+ }
+ return splitCssCommaList(value)
+ .map(normalizeAnimationName)
+ .filter(name => name && name.toLowerCase() !== 'none');
+ }
+
+ function keyframesRuleName(rule, cssText) {
+ const constructorName = rule?.constructor?.name || '';
+ const type = Number(rule?.type);
+ const isKeyframes = constructorName === 'CSSKeyframesRule'
+ || constructorName === 'WebKitCSSKeyframesRule'
+ || type === 7
+ || /^\s*@(?:-webkit-)?keyframes\b/i.test(cssText);
+ if (!isKeyframes) return '';
+ const match = String(cssText || '').match(/^\s*@(?:-webkit-)?keyframes\s+([^\s{]+)/i);
+ return normalizeAnimationName(rule?.name || match?.[1] || '');
+ }
+
+ function cssPropertyName(property) {
+ if (property.startsWith('--')) return property;
+ return property.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
+ }
+
+ function resolvedAnimationKeyframes(candidateNames) {
+ if (typeof document.getAnimations !== 'function') return null;
+ let animations;
+ try { animations = document.getAnimations(); }
+ catch { return null; }
+
+ const resolved = new Map();
+ const metadata = new Set(['offset', 'computedOffset', 'easing', 'composite']);
+ for (const animation of animations) {
+ const name = normalizeAnimationName(animation?.animationName || '');
+ if (!name || !candidateNames.has(name) || resolved.has(name)) continue;
+ let frames;
+ try { frames = animation.effect?.getKeyframes?.() || []; }
+ catch { continue; }
+ const blocks = [];
+ for (const frame of frames) {
+ const rawOffset = Number.isFinite(frame.computedOffset) ? frame.computedOffset : frame.offset;
+ if (!Number.isFinite(rawOffset)) continue;
+ const offset = Math.round(rawOffset * 1000000) / 10000;
+ const declarations = Object.entries(frame)
+ .filter(([property, value]) => !metadata.has(property) && value != null && value !== '')
+ .map(([property, value]) => `${cssPropertyName(property)}: ${value};`);
+ const easing = String(frame.easing || '').trim();
+ if (easing && easing.toLowerCase() !== 'linear') {
+ declarations.push(`animation-timing-function: ${easing};`);
+ }
+ if (declarations.length === 0) continue;
+ blocks.push(`${offset}% { ${declarations.join(' ')} }`);
+ }
+ if (blocks.length > 0) resolved.set(name, `@keyframes ${name} { ${blocks.join(' ')} }`);
+ }
+ return resolved;
+ }
+
+ // Read CSS that is absent from document.outerHTML. Inline <style> blocks are
+ // already present in the HTML pattern corpus, so limit this walk to linked
+ // stylesheets. Flatten grouping rules so each declaration keeps its selector,
+ // and admit only selector rules that target the live DOM. That prevents
+ // unused utilities from feeding both selector-scoped and page-level checks.
+ // Same-origin CSS and readable CORS sheets participate; browser security
+ // exceptions for cross-origin sheets are expected and skipped.
+ function linkedStylesheetText() {
+ const parts = [];
+ const seen = new Set();
+ const animationNames = new Set();
+ const keyframeCandidates = new Map();
+ const appendRules = (rules, requiresAppliedMatch = false) => {
+ for (const rule of rules) {
+ if (rule.styleSheet) {
+ appendSheet(rule.styleSheet);
+ continue;
+ }
+ const cssText = rule.cssText || '';
+ if (rule.selectorText) {
+ const matches = selectorNodesForLiveDom(document, rule.selectorText);
+ // Only declarations with a resolvable live host enter the corpus.
+ // Unresolvable selectors are uncertain, not evidence that a pattern
+ // rendered, and retaining them would leak unused CSS into findings.
+ if (
+ matches?.length > 0
+ && (!requiresAppliedMatch || styleRuleAppliesToLiveMatches(rule, matches))
+ ) {
+ parts.push(cssText);
+ for (const name of animationNamesDeclaredByRule(rule)) animationNames.add(name);
+ }
+ continue;
+ }
+ let nested = [];
+ let hasNestedRules = false;
+ try {
+ const ruleList = rule.cssRules;
+ hasNestedRules = ruleList != null;
+ nested = Array.from(ruleList || []);
+ } catch {
+ continue;
+ }
+ const keyframesName = keyframesRuleName(rule, cssText);
+ if (keyframesName) {
+ // Keyframes do not merge: when a name is defined more than once, the
+ // later effective definition replaces the earlier one.
+ keyframeCandidates.set(keyframesName, {
+ name: keyframesName,
+ cssText,
+ });
+ continue;
+ }
+ if (hasNestedRules) {
+ if (!conditionalCssRuleIsActive(rule)) continue;
+ appendRules(nested, requiresAppliedMatch || isContainerCssRule(rule));
+ continue;
+ }
+ // Other selector-less leaf at-rules cannot be tied to a rendered node.
+ }
+ };
+ const appendSheet = (sheet) => {
+ if (!sheet || seen.has(sheet)) return;
+ seen.add(sheet);
+ let rules;
+ try { rules = Array.from(sheet.cssRules || sheet.rules || []); }
+ catch { return; }
+ appendRules(rules);
+ };
+ let sheets;
+ try { sheets = Array.from(document.styleSheets || []); }
+ catch { return ''; }
+ for (const sheet of sheets) {
+ const owner = sheet.ownerNode;
+ if (owner?.tagName?.toLowerCase() !== 'link') continue;
+ if (!/\bstylesheet\b/i.test(owner.getAttribute?.('rel') || '')) continue;
+ appendSheet(sheet);
+ }
+ // Motion checks need the effective body of a live animation's keyframes.
+ // Let the browser resolve duplicate names across source order, imports,
+ // conditional groups, and cascade layers, then serialize those computed
+ // frames back into the pattern corpus. Browsers also make container-nested
+ // keyframes globally available, so lexical grouping is not a reliable
+ // activity signal. When the Web Animations API is unavailable, fall back to
+ // the last source-order definition referenced by a retained linked rule.
+ const resolvedKeyframes = resolvedAnimationKeyframes(new Set(keyframeCandidates.keys()));
+ if (resolvedKeyframes) {
+ parts.push(...resolvedKeyframes.values());
+ } else {
+ for (const candidate of keyframeCandidates.values()) {
+ if (!animationNames.has(candidate.name)) continue;
+ parts.push(candidate.cssText);
+ }
+ }
+ return parts.join('\n');
+ }
+
function browserFindingsFromMap(groupMap) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
@@ -8548,18 +8932,16 @@ if (IS_BROWSER) {
// (the CSS ships here, but the pattern never renders — the live DOM is
// ground truth in the browser), and a match under a data-impeccable-ignore
// ancestor is waived. Selector-less findings stay page-level.
- const scopedHtmlFindings = checkHtmlPatterns(docClone.outerHTML).filter(f => {
+ const html = docClone.outerHTML;
+ const corpora = buildHtmlPatternCorpora(html);
+ const linkedCss = linkedStylesheetText();
+ if (linkedCss) corpora.styleText += `\n${linkedCss}`;
+ const scopedHtmlFindings = checkHtmlPatterns(html, corpora).filter(f => {
if (!f.selector) return true;
- const query = String(f.selector).replace(/::?[a-zA-Z-]+(\([^)]*\))?/g, '').trim().replace(/,\s*(?=,|$)/g, '');
- if (!query || /^[,\s]*$/.test(query)) return true;
- let matches;
- try {
- matches = document.querySelectorAll(query);
- } catch {
- return true;
- }
+ const matches = selectorNodesForLiveDom(document, f.selector);
+ if (!matches) return false;
if (matches.length === 0) return false;
- return [...matches].some(el => !scopedIgnoreActive(el, f.id));
+ return matches.some(el => !scopedIgnoreActive(el, f.id));
});
if (scopedHtmlFindings.length > 0) {
const mapped = scopedHtmlFindings.map(f => {
diff --git a/.hermes/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs b/.hermes/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
index f3ff43c84..ac4bd0a7c 100644
--- a/.hermes/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
+++ b/.hermes/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
@@ -2,7 +2,7 @@ import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { finding } from '../../findings.mjs';
+import { deriveAdvisoryFlag, finding } from '../../findings.mjs';
import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
import { checkContentHiddenAtRest } from '../../rules/checks.mjs';
@@ -394,7 +394,7 @@ async function detectUrl(rawUrl, options = {}) {
// Per-finding severity promotion (e.g. hero-region pulsing dot)
// overrides the registry default carried by finding().
if (f.severity && f.severity !== item.severity) item.severity = f.severity;
- return item;
+ return deriveAdvisoryFlag(item);
});
}
diff --git a/.hermes/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs b/.hermes/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
index 84e6ab1f5..dac6939b0 100644
--- a/.hermes/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
+++ b/.hermes/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
@@ -9,7 +9,7 @@ import {
} from '../../design-system.mjs';
import { isFullPage } from '../../shared/page.mjs';
import { applyInlineIgnores } from '../../shared/inline-ignores.mjs';
-import { finding } from '../../findings.mjs';
+import { deriveAdvisoryFlag, finding } from '../../findings.mjs';
import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import {
checkElementBorders,
@@ -257,7 +257,7 @@ async function detectHtml(filePath, options = {}) {
// severity (e.g. a pulsing dot inside a header/nav landmark) that
// overrides the registry default.
if (f.severity) item.severity = f.severity;
- findings.push(item);
+ findings.push(deriveAdvisoryFlag(item));
}
// Text-content analyzers (em-dash overuse, marketing buzzwords,
// numbered section markers, aphoristic cadence) live in the regex
diff --git a/.hermes/skills/impeccable/scripts/detector/findings.mjs b/.hermes/skills/impeccable/scripts/detector/findings.mjs
index fa98dd935..ae7e134f9 100644
--- a/.hermes/skills/impeccable/scripts/detector/findings.mjs
+++ b/.hermes/skills/impeccable/scripts/detector/findings.mjs
@@ -4,6 +4,12 @@ function getAP(id) {
return getAntipattern(id);
}
+function deriveAdvisoryFlag(item) {
+ if (item.severity === 'advisory') item.advisory = true;
+ else delete item.advisory;
+ return item;
+}
+
function finding(id, filePath, snippet, line = 0) {
const ap = getAP(id);
const base = { antipattern: id, name: ap.name, description: ap.description, severity: ap.severity || 'warning', category: ap.category || null, file: filePath, line, snippet };
@@ -11,8 +17,7 @@ function finding(id, filePath, snippet, line = 0) {
// failures. Carry the flag on the finding so every consumer (CLI, JSON, hook)
// can partition without a registry lookup. Only stamped when true to keep the
// finding shape stable for the vast majority of rules.
- if (ap.advisory === true) base.advisory = true;
- return base;
+ return deriveAdvisoryFlag(base);
}
-export { getAP, finding };
+export { getAP, finding, deriveAdvisoryFlag };
diff --git a/.hermes/skills/impeccable/scripts/detector/registry/antipatterns.mjs b/.hermes/skills/impeccable/scripts/detector/registry/antipatterns.mjs
index 945307783..7c692c79a 100644
--- a/.hermes/skills/impeccable/scripts/detector/registry/antipatterns.mjs
+++ b/.hermes/skills/impeccable/scripts/detector/registry/antipatterns.mjs
@@ -233,7 +233,7 @@ const ANTIPATTERNS = [
// rather than a failure. It fires only on the AI saturation pattern, not on
// ordinary prose. Advisory findings are surfaced separately, never counted
// as failures, and skipped by the design hook unless a project opts in.
- advisory: true,
+ severity: 'advisory',
name: 'Em-dash overuse',
description:
'Em-dash saturation in body copy is an AI cadence tell. Advisory only: humans use em-dashes legitimately, so this fires only on saturation — at least 8 em-dashes (— or --) at a density near one per 500 characters of body text — never on a long article that uses a few. Prefer commas, colons, periods, or parentheses.',
@@ -588,9 +588,10 @@ function getAntipattern(id) {
// Advisory rules are detected and reported, but never treated as failures:
// the CLI lists them under a separate "Advisory" section, they do not affect
// exit codes or the failure count, and the design hook skips them by default.
-// The set is derived from the registry so a rule only needs `advisory: true`.
+// `severity` is the canonical registry field. The runtime finding serializer
+// derives its `advisory: true` compatibility/output flag from this set.
const ADVISORY_RULE_IDS = new Set(
- ANTIPATTERNS.filter(rule => rule.advisory === true).map(rule => rule.id),
+ ANTIPATTERNS.filter(rule => rule.severity === 'advisory').map(rule => rule.id),
);
function isAdvisoryRule(id) {
diff --git a/.hermes/skills/impeccable/scripts/detector/rules/checks.mjs b/.hermes/skills/impeccable/scripts/detector/rules/checks.mjs
index 579e1c12e..a24631ce9 100644
--- a/.hermes/skills/impeccable/scripts/detector/rules/checks.mjs
+++ b/.hermes/skills/impeccable/scripts/detector/rules/checks.mjs
@@ -688,7 +688,10 @@ function enclosingCssSelector(cssText, index) {
// `{` belongs to some other selector.
const closeBeforeIndex = cssText.lastIndexOf('}', index);
if (closeBeforeIndex > open) return null;
- const prevClose = Math.max(cssText.lastIndexOf('}', open - 1), cssText.lastIndexOf(';', open - 1));
+ // Ignore delimiters inside comments when locating the previous declaration.
+ // Keeping comment length intact preserves indices into the original source.
+ const beforeOpen = cssText.slice(0, open).replace(/\/\*[\s\S]*?\*\//g, comment => ' '.repeat(comment.length));
+ const prevClose = Math.max(beforeOpen.lastIndexOf('}'), beforeOpen.lastIndexOf(';'));
const raw = cssText.slice(prevClose + 1, open).replace(/\/\*[\s\S]*?\*\//g, '').trim().replace(/\s+/g, ' ');
if (!raw || raw.startsWith('@') || /^\d/.test(raw) || /[{}<]/.test(raw)) return null;
// Keyframe steps: percentage steps fail the digit test above, but `from`
@@ -4020,14 +4023,17 @@ function checkTypography() {
}
if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
+ // Report the actual primary face: the uniquely most-used family. The old
+ // 15% threshold labeled secondary faces as primary (e.g. an 82/18 split).
+ const ranked = [...fontUsage.entries()].sort((a, b) => b[1] - a[1]);
+ const [primary] = ranked;
+ const tied = ranked[1]?.[1] === primary?.[1];
+ if (primary && !tied) {
+ const [font, count] = primary;
const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ if (OVERUSED_FONTS.has(font) && !isBrandFontOnOwnDomain(font)) {
+ findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ }
}
}
diff --git a/.hermes/skills/impeccable/scripts/hook-lib.mjs b/.hermes/skills/impeccable/scripts/hook-lib.mjs
index 767fe65a6..6d8c3db81 100644
--- a/.hermes/skills/impeccable/scripts/hook-lib.mjs
+++ b/.hermes/skills/impeccable/scripts/hook-lib.mjs
@@ -138,17 +138,20 @@ export const IMMEDIATE_TIER_RULES = new Set([
// the agent is never nagged about a taste call a human might make on purpose.
// A project opts back in with `.impeccable/config.json`:
// { "detector": { "advisoryRules": "include" } }
-// This set is the hook's own copy of the registry's `advisory: true` rules,
-// mirroring how IMMEDIATE_TIER_RULES lists rule ids inline so the hook stays
-// self-contained and testable without loading the detector. Keep it in sync
-// with the registry (cli/engine/registry/antipatterns.mjs).
+// This legacy id fallback keeps older detector findings recognizable when they
+// carry neither the current runtime flag nor the canonical advisory severity.
+// Current findings are classified by their serialized metadata below.
export const ADVISORY_RULES = new Set([
'em-dash-overuse',
]);
export function isAdvisoryFinding(finding) {
const id = finding && normalizeIgnoreRule(finding.antipattern);
- return Boolean(id && (ADVISORY_RULES.has(id) || finding.advisory === true));
+ return Boolean(id && (
+ ADVISORY_RULES.has(id)
+ || finding.advisory === true
+ || finding.severity === 'advisory'
+ ));
}
export const DEFAULT_CONFIG = Object.freeze({
diff --git a/.kiro/skills/impeccable/scripts/detector/browser/injected/index.mjs b/.kiro/skills/impeccable/scripts/detector/browser/injected/index.mjs
index febf7f297..76fc558e5 100644
--- a/.kiro/skills/impeccable/scripts/detector/browser/injected/index.mjs
+++ b/.kiro/skills/impeccable/scripts/detector/browser/injected/index.mjs
@@ -1228,14 +1228,17 @@ if (IS_BROWSER) {
isHidden: isElementHidden(el),
findings: findings.map(f => {
const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
+ const severity = f.severity || ap?.severity || 'warning';
return {
type: f.type || f.id,
category: ap ? ap.category : 'quality',
- severity: f.severity || ap?.severity || 'warning',
+ severity,
// Advisory findings (em-dash overuse, etc.) are surfaced but never
// treated as failures; carry the flag so the overlay/extension can
// render them with the mildest affordance and consumers can filter.
- advisory: (ap && ap.advisory === true) || f.advisory === true,
+ // Per-finding promotions override the registry default, so derive
+ // this strictly from the effective severity.
+ advisory: severity === 'advisory',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
@@ -1277,6 +1280,381 @@ if (IS_BROWSER) {
else groupMap.set(el, [...kept]);
}
+ function pseudoElementHostSelector(selector) {
+ const raw = String(selector || '');
+ const legacyNames = new Set(['before', 'after', 'first-letter', 'first-line']);
+ const isNameChar = char => /[a-zA-Z0-9_-]/.test(char || '');
+ const consumeFunction = (start) => {
+ let depth = 0;
+ let quote = '';
+ for (let i = start; i < raw.length; i += 1) {
+ const char = raw[i];
+ if (char === '\\') {
+ i += 1;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '(') depth += 1;
+ if (char === ')' && --depth === 0) return i + 1;
+ }
+ return raw.length;
+ };
+
+ let output = '';
+ let found = false;
+ for (let i = 0; i < raw.length;) {
+ const char = raw[i];
+ if (char === '\\') {
+ output += raw.slice(i, Math.min(raw.length, i + 2));
+ i += 2;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ const quote = char;
+ const start = i;
+ i += 1;
+ while (i < raw.length) {
+ if (raw[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ const value = raw[i];
+ i += 1;
+ if (value === quote) break;
+ }
+ output += raw.slice(start, i);
+ continue;
+ }
+ if (char !== ':') {
+ output += char;
+ i += 1;
+ continue;
+ }
+
+ let end = i + 1;
+ let isPseudoElement = false;
+ if (raw[end] === ':') {
+ end += 1;
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = end > nameStart;
+ } else {
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = legacyNames.has(raw.slice(nameStart, end).toLowerCase());
+ }
+ if (!isPseudoElement) {
+ output += char;
+ i += 1;
+ continue;
+ }
+ if (raw[end] === '(') end = consumeFunction(end);
+ found = true;
+ if (!output || /[\s>+~,]/.test(output[output.length - 1])) output += '*';
+ i = end;
+ }
+ if (!found) return null;
+ return output.trim().replace(/,\s*(?=,|$)/g, '');
+ }
+
+ function selectorNodesForLiveDom(root, selector) {
+ const raw = String(selector || '').trim();
+ if (!raw) return null;
+ const fallback = pseudoElementHostSelector(raw);
+ if (fallback == null) {
+ // An empty result from a valid full selector is authoritative. In
+ // particular, do not broaden inactive :hover/:focus/:not() rules to
+ // their host element by stripping pseudo-classes.
+ try { return Array.from(root.querySelectorAll(raw)); }
+ catch { return null; }
+ }
+
+ // Resolve pseudo-elements to their originating live elements. An attached
+ // pseudo-element (`.card::before`) belongs to the element before it, while
+ // a hostless pseudo-element after a combinator (`main > ::before`) belongs
+ // to a matching element at that position (`main > *`). Replacing every
+ // pseudo indiscriminately with an empty string leaves the latter as the
+ // invalid selector `main >` and makes absent hosts indistinguishable from
+ // selectors the DOM API cannot parse.
+ if (!fallback || /^[,\s]*$/.test(fallback)) return null;
+ try { return Array.from(root.querySelectorAll(fallback)); }
+ catch { return null; }
+ }
+
+ let containerProbeSequence = 0;
+
+ function isContainerCssRule(rule) {
+ return rule?.constructor?.name === 'CSSContainerRule'
+ || /^\s*@container\b/i.test(rule?.cssText || '');
+ }
+
+ function styleRuleAppliesToLiveMatches(rule, matches) {
+ const style = rule?.style;
+ if (!style || !matches?.length || typeof getComputedStyle !== 'function') return false;
+ const sequence = ++containerProbeSequence;
+ const property = `--impeccable-container-probe-${sequence}-${Math.random().toString(36).slice(2)}`;
+ const value = `impeccable-container-active-${sequence}`;
+ const previousValue = style.getPropertyValue(property);
+ const previousPriority = style.getPropertyPriority(property);
+ try {
+ style.setProperty(property, value, 'important');
+ } catch {
+ return false;
+ }
+
+ const pseudoElements = [...new Set(
+ String(rule.selectorText || '').match(/::[a-zA-Z-]+(?:\([^)]*\))?/g) || [],
+ )];
+ try {
+ return matches.some(el => [null, ...pseudoElements].some(pseudo => {
+ try {
+ const computed = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el);
+ return computed.getPropertyValue(property).trim() === value;
+ } catch {
+ return false;
+ }
+ }));
+ } finally {
+ if (previousValue) style.setProperty(property, previousValue, previousPriority);
+ else style.removeProperty(property);
+ }
+ }
+
+ function conditionalCssRuleIsActive(rule) {
+ const type = Number(rule?.type);
+ const constructorName = rule?.constructor?.name || '';
+ if (constructorName === 'CSSMediaRule' || type === 4) {
+ const condition = rule.conditionText || rule.media?.mediaText || '';
+ if (!condition || typeof window.matchMedia !== 'function') return true;
+ try { return window.matchMedia(condition).matches; }
+ catch { return true; }
+ }
+ if (constructorName === 'CSSSupportsRule' || type === 12) {
+ const condition = rule.conditionText || '';
+ if (!condition || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return true;
+ try { return CSS.supports(condition); }
+ catch { return true; }
+ }
+ return true;
+ }
+
+ function splitCssCommaList(value) {
+ const parts = [];
+ let current = '';
+ let quote = '';
+ let escaped = false;
+ for (const char of String(value || '')) {
+ if (escaped) {
+ current += char;
+ escaped = false;
+ continue;
+ }
+ if (char === '\\') {
+ current += char;
+ escaped = true;
+ continue;
+ }
+ if (quote) {
+ current += char;
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ current += char;
+ continue;
+ }
+ if (char === ',') {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+ return parts;
+ }
+
+ function normalizeAnimationName(value) {
+ const name = String(value || '').trim();
+ if (name.length >= 2 && name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) {
+ return name.slice(1, -1);
+ }
+ return name;
+ }
+
+ function animationNamesDeclaredByRule(rule) {
+ const style = rule?.style;
+ if (!style) return [];
+ let value = '';
+ try {
+ value = style.animationName
+ || style.getPropertyValue?.('animation-name')
+ || style.webkitAnimationName
+ || style.getPropertyValue?.('-webkit-animation-name')
+ || '';
+ } catch {
+ return [];
+ }
+ return splitCssCommaList(value)
+ .map(normalizeAnimationName)
+ .filter(name => name && name.toLowerCase() !== 'none');
+ }
+
+ function keyframesRuleName(rule, cssText) {
+ const constructorName = rule?.constructor?.name || '';
+ const type = Number(rule?.type);
+ const isKeyframes = constructorName === 'CSSKeyframesRule'
+ || constructorName === 'WebKitCSSKeyframesRule'
+ || type === 7
+ || /^\s*@(?:-webkit-)?keyframes\b/i.test(cssText);
+ if (!isKeyframes) return '';
+ const match = String(cssText || '').match(/^\s*@(?:-webkit-)?keyframes\s+([^\s{]+)/i);
+ return normalizeAnimationName(rule?.name || match?.[1] || '');
+ }
+
+ function cssPropertyName(property) {
+ if (property.startsWith('--')) return property;
+ return property.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
+ }
+
+ function resolvedAnimationKeyframes(candidateNames) {
+ if (typeof document.getAnimations !== 'function') return null;
+ let animations;
+ try { animations = document.getAnimations(); }
+ catch { return null; }
+
+ const resolved = new Map();
+ const metadata = new Set(['offset', 'computedOffset', 'easing', 'composite']);
+ for (const animation of animations) {
+ const name = normalizeAnimationName(animation?.animationName || '');
+ if (!name || !candidateNames.has(name) || resolved.has(name)) continue;
+ let frames;
+ try { frames = animation.effect?.getKeyframes?.() || []; }
+ catch { continue; }
+ const blocks = [];
+ for (const frame of frames) {
+ const rawOffset = Number.isFinite(frame.computedOffset) ? frame.computedOffset : frame.offset;
+ if (!Number.isFinite(rawOffset)) continue;
+ const offset = Math.round(rawOffset * 1000000) / 10000;
+ const declarations = Object.entries(frame)
+ .filter(([property, value]) => !metadata.has(property) && value != null && value !== '')
+ .map(([property, value]) => `${cssPropertyName(property)}: ${value};`);
+ const easing = String(frame.easing || '').trim();
+ if (easing && easing.toLowerCase() !== 'linear') {
+ declarations.push(`animation-timing-function: ${easing};`);
+ }
+ if (declarations.length === 0) continue;
+ blocks.push(`${offset}% { ${declarations.join(' ')} }`);
+ }
+ if (blocks.length > 0) resolved.set(name, `@keyframes ${name} { ${blocks.join(' ')} }`);
+ }
+ return resolved;
+ }
+
+ // Read CSS that is absent from document.outerHTML. Inline <style> blocks are
+ // already present in the HTML pattern corpus, so limit this walk to linked
+ // stylesheets. Flatten grouping rules so each declaration keeps its selector,
+ // and admit only selector rules that target the live DOM. That prevents
+ // unused utilities from feeding both selector-scoped and page-level checks.
+ // Same-origin CSS and readable CORS sheets participate; browser security
+ // exceptions for cross-origin sheets are expected and skipped.
+ function linkedStylesheetText() {
+ const parts = [];
+ const seen = new Set();
+ const animationNames = new Set();
+ const keyframeCandidates = new Map();
+ const appendRules = (rules, requiresAppliedMatch = false) => {
+ for (const rule of rules) {
+ if (rule.styleSheet) {
+ appendSheet(rule.styleSheet);
+ continue;
+ }
+ const cssText = rule.cssText || '';
+ if (rule.selectorText) {
+ const matches = selectorNodesForLiveDom(document, rule.selectorText);
+ // Only declarations with a resolvable live host enter the corpus.
+ // Unresolvable selectors are uncertain, not evidence that a pattern
+ // rendered, and retaining them would leak unused CSS into findings.
+ if (
+ matches?.length > 0
+ && (!requiresAppliedMatch || styleRuleAppliesToLiveMatches(rule, matches))
+ ) {
+ parts.push(cssText);
+ for (const name of animationNamesDeclaredByRule(rule)) animationNames.add(name);
+ }
+ continue;
+ }
+ let nested = [];
+ let hasNestedRules = false;
+ try {
+ const ruleList = rule.cssRules;
+ hasNestedRules = ruleList != null;
+ nested = Array.from(ruleList || []);
+ } catch {
+ continue;
+ }
+ const keyframesName = keyframesRuleName(rule, cssText);
+ if (keyframesName) {
+ // Keyframes do not merge: when a name is defined more than once, the
+ // later effective definition replaces the earlier one.
+ keyframeCandidates.set(keyframesName, {
+ name: keyframesName,
+ cssText,
+ });
+ continue;
+ }
+ if (hasNestedRules) {
+ if (!conditionalCssRuleIsActive(rule)) continue;
+ appendRules(nested, requiresAppliedMatch || isContainerCssRule(rule));
+ continue;
+ }
+ // Other selector-less leaf at-rules cannot be tied to a rendered node.
+ }
+ };
+ const appendSheet = (sheet) => {
+ if (!sheet || seen.has(sheet)) return;
+ seen.add(sheet);
+ let rules;
+ try { rules = Array.from(sheet.cssRules || sheet.rules || []); }
+ catch { return; }
+ appendRules(rules);
+ };
+ let sheets;
+ try { sheets = Array.from(document.styleSheets || []); }
+ catch { return ''; }
+ for (const sheet of sheets) {
+ const owner = sheet.ownerNode;
+ if (owner?.tagName?.toLowerCase() !== 'link') continue;
+ if (!/\bstylesheet\b/i.test(owner.getAttribute?.('rel') || '')) continue;
+ appendSheet(sheet);
+ }
+ // Motion checks need the effective body of a live animation's keyframes.
+ // Let the browser resolve duplicate names across source order, imports,
+ // conditional groups, and cascade layers, then serialize those computed
+ // frames back into the pattern corpus. Browsers also make container-nested
+ // keyframes globally available, so lexical grouping is not a reliable
+ // activity signal. When the Web Animations API is unavailable, fall back to
+ // the last source-order definition referenced by a retained linked rule.
+ const resolvedKeyframes = resolvedAnimationKeyframes(new Set(keyframeCandidates.keys()));
+ if (resolvedKeyframes) {
+ parts.push(...resolvedKeyframes.values());
+ } else {
+ for (const candidate of keyframeCandidates.values()) {
+ if (!animationNames.has(candidate.name)) continue;
+ parts.push(candidate.cssText);
+ }
+ }
+ return parts.join('\n');
+ }
+
function browserFindingsFromMap(groupMap) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
@@ -1650,18 +2028,16 @@ if (IS_BROWSER) {
// (the CSS ships here, but the pattern never renders — the live DOM is
// ground truth in the browser), and a match under a data-impeccable-ignore
// ancestor is waived. Selector-less findings stay page-level.
- const scopedHtmlFindings = checkHtmlPatterns(docClone.outerHTML).filter(f => {
+ const html = docClone.outerHTML;
+ const corpora = buildHtmlPatternCorpora(html);
+ const linkedCss = linkedStylesheetText();
+ if (linkedCss) corpora.styleText += `\n${linkedCss}`;
+ const scopedHtmlFindings = checkHtmlPatterns(html, corpora).filter(f => {
if (!f.selector) return true;
- const query = String(f.selector).replace(/::?[a-zA-Z-]+(\([^)]*\))?/g, '').trim().replace(/,\s*(?=,|$)/g, '');
- if (!query || /^[,\s]*$/.test(query)) return true;
- let matches;
- try {
- matches = document.querySelectorAll(query);
- } catch {
- return true;
- }
+ const matches = selectorNodesForLiveDom(document, f.selector);
+ if (!matches) return false;
if (matches.length === 0) return false;
- return [...matches].some(el => !scopedIgnoreActive(el, f.id));
+ return matches.some(el => !scopedIgnoreActive(el, f.id));
});
if (scopedHtmlFindings.length > 0) {
const mapped = scopedHtmlFindings.map(f => {
diff --git a/.kiro/skills/impeccable/scripts/detector/cli/main.mjs b/.kiro/skills/impeccable/scripts/detector/cli/main.mjs
index 4476d04f1..3451d6c6b 100644
--- a/.kiro/skills/impeccable/scripts/detector/cli/main.mjs
+++ b/.kiro/skills/impeccable/scripts/detector/cli/main.mjs
@@ -37,13 +37,30 @@ function fileUrlToLocalPath(url) {
}
}
+const URL_TARGET_RE = /^(?:https?|file):\/\//i;
+
+// Some agent runners hand a shell-ready URL list to Node as one argv value.
+// A browser accepts the spaces as part of one encoded URL, producing a
+// plausible scan attributed to a bogus joined path. Expand only when every
+// whitespace-delimited token is independently a URL, preserving ordinary
+// filesystem paths that contain spaces.
+function expandJoinedUrlTargets(targets) {
+ return targets.flatMap((target) => {
+ if (!/\s/.test(target)) return [target];
+ const parts = target.trim().split(/\s+/).filter(Boolean);
+ return parts.length > 1 && parts.every(part => URL_TARGET_RE.test(part))
+ ? parts
+ : [target];
+ });
+}
+
// Advisory findings are detected but never treated as failures: they list in a
// separate, visually dimmed section, are excluded from the failure count that
// drives the exit code, and carry `"advisory": true` in JSON so consumers can
// filter. Every advisory finding carries the flag (stamped by the registry via
// findings.mjs).
function isAdvisory(finding) {
- return finding && finding.advisory === true;
+ return Boolean(finding && (finding.advisory === true || finding.severity === 'advisory'));
}
function partitionAdvisory(findings) {
@@ -168,6 +185,10 @@ Advisory findings:
counted as failures and never changing the exit code. They stay out of the
failure count so they never block automation. --no-advisory hides them.
+Output streams:
+ Human-readable findings go to stderr so stdout stays available for structured
+ output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.
+
Project config:
Respects .impeccable/config.json and .impeccable/config.local.json detector
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
@@ -185,7 +206,7 @@ Detection modes:
HTML files Static HTML/CSS analysis (default, catches linked CSS)
Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)
URLs Puppeteer full browser rendering (auto-detected;
- http(s):// and file:// URLs)
+ http(s):// and file:// URLs; accessible linked CSS included)
Examples:
impeccable detect src/
@@ -283,7 +304,7 @@ async function detectCli() {
const designSystem = loadDesignSystemForTarget(localPath, { cache: designSystemCache });
return designSystem ? { ...baseScanOptions, designSystem } : baseScanOptions;
};
- const targets = args.filter(a => !a.startsWith('--'));
+ const targets = expandJoinedUrlTargets(args.filter(a => !a.startsWith('--')));
if (helpMode) { printUsage(); process.exit(0); }
@@ -297,13 +318,12 @@ async function detectCli() {
// real cascade, real computed styles, real layout. Callers that want a
// browser-grade scan of a local artifact can pass file:///abs/path.html
// instead of the bare path (which stays on the static engine).
- const urlRe = /^(?:https?|file):\/\//i;
- const urlTargetCount = paths.filter(target => urlRe.test(target)).length;
+ const urlTargetCount = paths.filter(target => URL_TARGET_RE.test(target)).length;
const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
try {
for (const target of paths) {
- if (urlRe.test(target)) {
+ if (URL_TARGET_RE.test(target)) {
// A file:// URL points at a local artifact, so its design system
// resolves from that file's project. A remote http(s) URL has no
// local project — it gets base options (no design system), never
diff --git a/.kiro/skills/impeccable/scripts/detector/detect-antipatterns-browser.js b/.kiro/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
index e6899f569..460ffb45b 100644
--- a/.kiro/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
+++ b/.kiro/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
@@ -358,7 +358,7 @@ const ANTIPATTERNS = [
// rather than a failure. It fires only on the AI saturation pattern, not on
// ordinary prose. Advisory findings are surfaced separately, never counted
// as failures, and skipped by the design hook unless a project opts in.
- advisory: true,
+ severity: 'advisory',
name: 'Em-dash overuse',
description:
'Em-dash saturation in body copy is an AI cadence tell. Advisory only: humans use em-dashes legitimately, so this fires only on saturation — at least 8 em-dashes (— or --) at a density near one per 500 characters of body text — never on a long article that uses a few. Prefer commas, colons, periods, or parentheses.',
@@ -1961,7 +1961,10 @@ function enclosingCssSelector(cssText, index) {
// `{` belongs to some other selector.
const closeBeforeIndex = cssText.lastIndexOf('}', index);
if (closeBeforeIndex > open) return null;
- const prevClose = Math.max(cssText.lastIndexOf('}', open - 1), cssText.lastIndexOf(';', open - 1));
+ // Ignore delimiters inside comments when locating the previous declaration.
+ // Keeping comment length intact preserves indices into the original source.
+ const beforeOpen = cssText.slice(0, open).replace(/\/\*[\s\S]*?\*\//g, comment => ' '.repeat(comment.length));
+ const prevClose = Math.max(beforeOpen.lastIndexOf('}'), beforeOpen.lastIndexOf(';'));
const raw = cssText.slice(prevClose + 1, open).replace(/\/\*[\s\S]*?\*\//g, '').trim().replace(/\s+/g, ' ');
if (!raw || raw.startsWith('@') || /^\d/.test(raw) || /[{}<]/.test(raw)) return null;
// Keyframe steps: percentage steps fail the digit test above, but `from`
@@ -5293,14 +5296,17 @@ function checkTypography() {
}
if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
+ // Report the actual primary face: the uniquely most-used family. The old
+ // 15% threshold labeled secondary faces as primary (e.g. an 82/18 split).
+ const ranked = [...fontUsage.entries()].sort((a, b) => b[1] - a[1]);
+ const [primary] = ranked;
+ const tied = ranked[1]?.[1] === primary?.[1];
+ if (primary && !tied) {
+ const [font, count] = primary;
const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ if (OVERUSED_FONTS.has(font) && !isBrandFontOnOwnDomain(font)) {
+ findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ }
}
}
@@ -8126,14 +8132,17 @@ if (IS_BROWSER) {
isHidden: isElementHidden(el),
findings: findings.map(f => {
const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
+ const severity = f.severity || ap?.severity || 'warning';
return {
type: f.type || f.id,
category: ap ? ap.category : 'quality',
- severity: f.severity || ap?.severity || 'warning',
+ severity,
// Advisory findings (em-dash overuse, etc.) are surfaced but never
// treated as failures; carry the flag so the overlay/extension can
// render them with the mildest affordance and consumers can filter.
- advisory: (ap && ap.advisory === true) || f.advisory === true,
+ // Per-finding promotions override the registry default, so derive
+ // this strictly from the effective severity.
+ advisory: severity === 'advisory',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
@@ -8175,6 +8184,381 @@ if (IS_BROWSER) {
else groupMap.set(el, [...kept]);
}
+ function pseudoElementHostSelector(selector) {
+ const raw = String(selector || '');
+ const legacyNames = new Set(['before', 'after', 'first-letter', 'first-line']);
+ const isNameChar = char => /[a-zA-Z0-9_-]/.test(char || '');
+ const consumeFunction = (start) => {
+ let depth = 0;
+ let quote = '';
+ for (let i = start; i < raw.length; i += 1) {
+ const char = raw[i];
+ if (char === '\\') {
+ i += 1;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '(') depth += 1;
+ if (char === ')' && --depth === 0) return i + 1;
+ }
+ return raw.length;
+ };
+
+ let output = '';
+ let found = false;
+ for (let i = 0; i < raw.length;) {
+ const char = raw[i];
+ if (char === '\\') {
+ output += raw.slice(i, Math.min(raw.length, i + 2));
+ i += 2;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ const quote = char;
+ const start = i;
+ i += 1;
+ while (i < raw.length) {
+ if (raw[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ const value = raw[i];
+ i += 1;
+ if (value === quote) break;
+ }
+ output += raw.slice(start, i);
+ continue;
+ }
+ if (char !== ':') {
+ output += char;
+ i += 1;
+ continue;
+ }
+
+ let end = i + 1;
+ let isPseudoElement = false;
+ if (raw[end] === ':') {
+ end += 1;
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = end > nameStart;
+ } else {
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = legacyNames.has(raw.slice(nameStart, end).toLowerCase());
+ }
+ if (!isPseudoElement) {
+ output += char;
+ i += 1;
+ continue;
+ }
+ if (raw[end] === '(') end = consumeFunction(end);
+ found = true;
+ if (!output || /[\s>+~,]/.test(output[output.length - 1])) output += '*';
+ i = end;
+ }
+ if (!found) return null;
+ return output.trim().replace(/,\s*(?=,|$)/g, '');
+ }
+
+ function selectorNodesForLiveDom(root, selector) {
+ const raw = String(selector || '').trim();
+ if (!raw) return null;
+ const fallback = pseudoElementHostSelector(raw);
+ if (fallback == null) {
+ // An empty result from a valid full selector is authoritative. In
+ // particular, do not broaden inactive :hover/:focus/:not() rules to
+ // their host element by stripping pseudo-classes.
+ try { return Array.from(root.querySelectorAll(raw)); }
+ catch { return null; }
+ }
+
+ // Resolve pseudo-elements to their originating live elements. An attached
+ // pseudo-element (`.card::before`) belongs to the element before it, while
+ // a hostless pseudo-element after a combinator (`main > ::before`) belongs
+ // to a matching element at that position (`main > *`). Replacing every
+ // pseudo indiscriminately with an empty string leaves the latter as the
+ // invalid selector `main >` and makes absent hosts indistinguishable from
+ // selectors the DOM API cannot parse.
+ if (!fallback || /^[,\s]*$/.test(fallback)) return null;
+ try { return Array.from(root.querySelectorAll(fallback)); }
+ catch { return null; }
+ }
+
+ let containerProbeSequence = 0;
+
+ function isContainerCssRule(rule) {
+ return rule?.constructor?.name === 'CSSContainerRule'
+ || /^\s*@container\b/i.test(rule?.cssText || '');
+ }
+
+ function styleRuleAppliesToLiveMatches(rule, matches) {
+ const style = rule?.style;
+ if (!style || !matches?.length || typeof getComputedStyle !== 'function') return false;
+ const sequence = ++containerProbeSequence;
+ const property = `--impeccable-container-probe-${sequence}-${Math.random().toString(36).slice(2)}`;
+ const value = `impeccable-container-active-${sequence}`;
+ const previousValue = style.getPropertyValue(property);
+ const previousPriority = style.getPropertyPriority(property);
+ try {
+ style.setProperty(property, value, 'important');
+ } catch {
+ return false;
+ }
+
+ const pseudoElements = [...new Set(
+ String(rule.selectorText || '').match(/::[a-zA-Z-]+(?:\([^)]*\))?/g) || [],
+ )];
+ try {
+ return matches.some(el => [null, ...pseudoElements].some(pseudo => {
+ try {
+ const computed = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el);
+ return computed.getPropertyValue(property).trim() === value;
+ } catch {
+ return false;
+ }
+ }));
+ } finally {
+ if (previousValue) style.setProperty(property, previousValue, previousPriority);
+ else style.removeProperty(property);
+ }
+ }
+
+ function conditionalCssRuleIsActive(rule) {
+ const type = Number(rule?.type);
+ const constructorName = rule?.constructor?.name || '';
+ if (constructorName === 'CSSMediaRule' || type === 4) {
+ const condition = rule.conditionText || rule.media?.mediaText || '';
+ if (!condition || typeof window.matchMedia !== 'function') return true;
+ try { return window.matchMedia(condition).matches; }
+ catch { return true; }
+ }
+ if (constructorName === 'CSSSupportsRule' || type === 12) {
+ const condition = rule.conditionText || '';
+ if (!condition || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return true;
+ try { return CSS.supports(condition); }
+ catch { return true; }
+ }
+ return true;
+ }
+
+ function splitCssCommaList(value) {
+ const parts = [];
+ let current = '';
+ let quote = '';
+ let escaped = false;
+ for (const char of String(value || '')) {
+ if (escaped) {
+ current += char;
+ escaped = false;
+ continue;
+ }
+ if (char === '\\') {
+ current += char;
+ escaped = true;
+ continue;
+ }
+ if (quote) {
+ current += char;
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ current += char;
+ continue;
+ }
+ if (char === ',') {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+ return parts;
+ }
+
+ function normalizeAnimationName(value) {
+ const name = String(value || '').trim();
+ if (name.length >= 2 && name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) {
+ return name.slice(1, -1);
+ }
+ return name;
+ }
+
+ function animationNamesDeclaredByRule(rule) {
+ const style = rule?.style;
+ if (!style) return [];
+ let value = '';
+ try {
+ value = style.animationName
+ || style.getPropertyValue?.('animation-name')
+ || style.webkitAnimationName
+ || style.getPropertyValue?.('-webkit-animation-name')
+ || '';
+ } catch {
+ return [];
+ }
+ return splitCssCommaList(value)
+ .map(normalizeAnimationName)
+ .filter(name => name && name.toLowerCase() !== 'none');
+ }
+
+ function keyframesRuleName(rule, cssText) {
+ const constructorName = rule?.constructor?.name || '';
+ const type = Number(rule?.type);
+ const isKeyframes = constructorName === 'CSSKeyframesRule'
+ || constructorName === 'WebKitCSSKeyframesRule'
+ || type === 7
+ || /^\s*@(?:-webkit-)?keyframes\b/i.test(cssText);
+ if (!isKeyframes) return '';
+ const match = String(cssText || '').match(/^\s*@(?:-webkit-)?keyframes\s+([^\s{]+)/i);
+ return normalizeAnimationName(rule?.name || match?.[1] || '');
+ }
+
+ function cssPropertyName(property) {
+ if (property.startsWith('--')) return property;
+ return property.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
+ }
+
+ function resolvedAnimationKeyframes(candidateNames) {
+ if (typeof document.getAnimations !== 'function') return null;
+ let animations;
+ try { animations = document.getAnimations(); }
+ catch { return null; }
+
+ const resolved = new Map();
+ const metadata = new Set(['offset', 'computedOffset', 'easing', 'composite']);
+ for (const animation of animations) {
+ const name = normalizeAnimationName(animation?.animationName || '');
+ if (!name || !candidateNames.has(name) || resolved.has(name)) continue;
+ let frames;
+ try { frames = animation.effect?.getKeyframes?.() || []; }
+ catch { continue; }
+ const blocks = [];
+ for (const frame of frames) {
+ const rawOffset = Number.isFinite(frame.computedOffset) ? frame.computedOffset : frame.offset;
+ if (!Number.isFinite(rawOffset)) continue;
+ const offset = Math.round(rawOffset * 1000000) / 10000;
+ const declarations = Object.entries(frame)
+ .filter(([property, value]) => !metadata.has(property) && value != null && value !== '')
+ .map(([property, value]) => `${cssPropertyName(property)}: ${value};`);
+ const easing = String(frame.easing || '').trim();
+ if (easing && easing.toLowerCase() !== 'linear') {
+ declarations.push(`animation-timing-function: ${easing};`);
+ }
+ if (declarations.length === 0) continue;
+ blocks.push(`${offset}% { ${declarations.join(' ')} }`);
+ }
+ if (blocks.length > 0) resolved.set(name, `@keyframes ${name} { ${blocks.join(' ')} }`);
+ }
+ return resolved;
+ }
+
+ // Read CSS that is absent from document.outerHTML. Inline <style> blocks are
+ // already present in the HTML pattern corpus, so limit this walk to linked
+ // stylesheets. Flatten grouping rules so each declaration keeps its selector,
+ // and admit only selector rules that target the live DOM. That prevents
+ // unused utilities from feeding both selector-scoped and page-level checks.
+ // Same-origin CSS and readable CORS sheets participate; browser security
+ // exceptions for cross-origin sheets are expected and skipped.
+ function linkedStylesheetText() {
+ const parts = [];
+ const seen = new Set();
+ const animationNames = new Set();
+ const keyframeCandidates = new Map();
+ const appendRules = (rules, requiresAppliedMatch = false) => {
+ for (const rule of rules) {
+ if (rule.styleSheet) {
+ appendSheet(rule.styleSheet);
+ continue;
+ }
+ const cssText = rule.cssText || '';
+ if (rule.selectorText) {
+ const matches = selectorNodesForLiveDom(document, rule.selectorText);
+ // Only declarations with a resolvable live host enter the corpus.
+ // Unresolvable selectors are uncertain, not evidence that a pattern
+ // rendered, and retaining them would leak unused CSS into findings.
+ if (
+ matches?.length > 0
+ && (!requiresAppliedMatch || styleRuleAppliesToLiveMatches(rule, matches))
+ ) {
+ parts.push(cssText);
+ for (const name of animationNamesDeclaredByRule(rule)) animationNames.add(name);
+ }
+ continue;
+ }
+ let nested = [];
+ let hasNestedRules = false;
+ try {
+ const ruleList = rule.cssRules;
+ hasNestedRules = ruleList != null;
+ nested = Array.from(ruleList || []);
+ } catch {
+ continue;
+ }
+ const keyframesName = keyframesRuleName(rule, cssText);
+ if (keyframesName) {
+ // Keyframes do not merge: when a name is defined more than once, the
+ // later effective definition replaces the earlier one.
+ keyframeCandidates.set(keyframesName, {
+ name: keyframesName,
+ cssText,
+ });
+ continue;
+ }
+ if (hasNestedRules) {
+ if (!conditionalCssRuleIsActive(rule)) continue;
+ appendRules(nested, requiresAppliedMatch || isContainerCssRule(rule));
+ continue;
+ }
+ // Other selector-less leaf at-rules cannot be tied to a rendered node.
+ }
+ };
+ const appendSheet = (sheet) => {
+ if (!sheet || seen.has(sheet)) return;
+ seen.add(sheet);
+ let rules;
+ try { rules = Array.from(sheet.cssRules || sheet.rules || []); }
+ catch { return; }
+ appendRules(rules);
+ };
+ let sheets;
+ try { sheets = Array.from(document.styleSheets || []); }
+ catch { return ''; }
+ for (const sheet of sheets) {
+ const owner = sheet.ownerNode;
+ if (owner?.tagName?.toLowerCase() !== 'link') continue;
+ if (!/\bstylesheet\b/i.test(owner.getAttribute?.('rel') || '')) continue;
+ appendSheet(sheet);
+ }
+ // Motion checks need the effective body of a live animation's keyframes.
+ // Let the browser resolve duplicate names across source order, imports,
+ // conditional groups, and cascade layers, then serialize those computed
+ // frames back into the pattern corpus. Browsers also make container-nested
+ // keyframes globally available, so lexical grouping is not a reliable
+ // activity signal. When the Web Animations API is unavailable, fall back to
+ // the last source-order definition referenced by a retained linked rule.
+ const resolvedKeyframes = resolvedAnimationKeyframes(new Set(keyframeCandidates.keys()));
+ if (resolvedKeyframes) {
+ parts.push(...resolvedKeyframes.values());
+ } else {
+ for (const candidate of keyframeCandidates.values()) {
+ if (!animationNames.has(candidate.name)) continue;
+ parts.push(candidate.cssText);
+ }
+ }
+ return parts.join('\n');
+ }
+
function browserFindingsFromMap(groupMap) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
@@ -8548,18 +8932,16 @@ if (IS_BROWSER) {
// (the CSS ships here, but the pattern never renders — the live DOM is
// ground truth in the browser), and a match under a data-impeccable-ignore
// ancestor is waived. Selector-less findings stay page-level.
- const scopedHtmlFindings = checkHtmlPatterns(docClone.outerHTML).filter(f => {
+ const html = docClone.outerHTML;
+ const corpora = buildHtmlPatternCorpora(html);
+ const linkedCss = linkedStylesheetText();
+ if (linkedCss) corpora.styleText += `\n${linkedCss}`;
+ const scopedHtmlFindings = checkHtmlPatterns(html, corpora).filter(f => {
if (!f.selector) return true;
- const query = String(f.selector).replace(/::?[a-zA-Z-]+(\([^)]*\))?/g, '').trim().replace(/,\s*(?=,|$)/g, '');
- if (!query || /^[,\s]*$/.test(query)) return true;
- let matches;
- try {
- matches = document.querySelectorAll(query);
- } catch {
- return true;
- }
+ const matches = selectorNodesForLiveDom(document, f.selector);
+ if (!matches) return false;
if (matches.length === 0) return false;
- return [...matches].some(el => !scopedIgnoreActive(el, f.id));
+ return matches.some(el => !scopedIgnoreActive(el, f.id));
});
if (scopedHtmlFindings.length > 0) {
const mapped = scopedHtmlFindings.map(f => {
diff --git a/.kiro/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs b/.kiro/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
index f3ff43c84..ac4bd0a7c 100644
--- a/.kiro/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
+++ b/.kiro/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
@@ -2,7 +2,7 @@ import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { finding } from '../../findings.mjs';
+import { deriveAdvisoryFlag, finding } from '../../findings.mjs';
import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
import { checkContentHiddenAtRest } from '../../rules/checks.mjs';
@@ -394,7 +394,7 @@ async function detectUrl(rawUrl, options = {}) {
// Per-finding severity promotion (e.g. hero-region pulsing dot)
// overrides the registry default carried by finding().
if (f.severity && f.severity !== item.severity) item.severity = f.severity;
- return item;
+ return deriveAdvisoryFlag(item);
});
}
diff --git a/.kiro/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs b/.kiro/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
index 84e6ab1f5..dac6939b0 100644
--- a/.kiro/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
+++ b/.kiro/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
@@ -9,7 +9,7 @@ import {
} from '../../design-system.mjs';
import { isFullPage } from '../../shared/page.mjs';
import { applyInlineIgnores } from '../../shared/inline-ignores.mjs';
-import { finding } from '../../findings.mjs';
+import { deriveAdvisoryFlag, finding } from '../../findings.mjs';
import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import {
checkElementBorders,
@@ -257,7 +257,7 @@ async function detectHtml(filePath, options = {}) {
// severity (e.g. a pulsing dot inside a header/nav landmark) that
// overrides the registry default.
if (f.severity) item.severity = f.severity;
- findings.push(item);
+ findings.push(deriveAdvisoryFlag(item));
}
// Text-content analyzers (em-dash overuse, marketing buzzwords,
// numbered section markers, aphoristic cadence) live in the regex
diff --git a/.kiro/skills/impeccable/scripts/detector/findings.mjs b/.kiro/skills/impeccable/scripts/detector/findings.mjs
index fa98dd935..ae7e134f9 100644
--- a/.kiro/skills/impeccable/scripts/detector/findings.mjs
+++ b/.kiro/skills/impeccable/scripts/detector/findings.mjs
@@ -4,6 +4,12 @@ function getAP(id) {
return getAntipattern(id);
}
+function deriveAdvisoryFlag(item) {
+ if (item.severity === 'advisory') item.advisory = true;
+ else delete item.advisory;
+ return item;
+}
+
function finding(id, filePath, snippet, line = 0) {
const ap = getAP(id);
const base = { antipattern: id, name: ap.name, description: ap.description, severity: ap.severity || 'warning', category: ap.category || null, file: filePath, line, snippet };
@@ -11,8 +17,7 @@ function finding(id, filePath, snippet, line = 0) {
// failures. Carry the flag on the finding so every consumer (CLI, JSON, hook)
// can partition without a registry lookup. Only stamped when true to keep the
// finding shape stable for the vast majority of rules.
- if (ap.advisory === true) base.advisory = true;
- return base;
+ return deriveAdvisoryFlag(base);
}
-export { getAP, finding };
+export { getAP, finding, deriveAdvisoryFlag };
diff --git a/.kiro/skills/impeccable/scripts/detector/registry/antipatterns.mjs b/.kiro/skills/impeccable/scripts/detector/registry/antipatterns.mjs
index 945307783..7c692c79a 100644
--- a/.kiro/skills/impeccable/scripts/detector/registry/antipatterns.mjs
+++ b/.kiro/skills/impeccable/scripts/detector/registry/antipatterns.mjs
@@ -233,7 +233,7 @@ const ANTIPATTERNS = [
// rather than a failure. It fires only on the AI saturation pattern, not on
// ordinary prose. Advisory findings are surfaced separately, never counted
// as failures, and skipped by the design hook unless a project opts in.
- advisory: true,
+ severity: 'advisory',
name: 'Em-dash overuse',
description:
'Em-dash saturation in body copy is an AI cadence tell. Advisory only: humans use em-dashes legitimately, so this fires only on saturation — at least 8 em-dashes (— or --) at a density near one per 500 characters of body text — never on a long article that uses a few. Prefer commas, colons, periods, or parentheses.',
@@ -588,9 +588,10 @@ function getAntipattern(id) {
// Advisory rules are detected and reported, but never treated as failures:
// the CLI lists them under a separate "Advisory" section, they do not affect
// exit codes or the failure count, and the design hook skips them by default.
-// The set is derived from the registry so a rule only needs `advisory: true`.
+// `severity` is the canonical registry field. The runtime finding serializer
+// derives its `advisory: true` compatibility/output flag from this set.
const ADVISORY_RULE_IDS = new Set(
- ANTIPATTERNS.filter(rule => rule.advisory === true).map(rule => rule.id),
+ ANTIPATTERNS.filter(rule => rule.severity === 'advisory').map(rule => rule.id),
);
function isAdvisoryRule(id) {
diff --git a/.kiro/skills/impeccable/scripts/detector/rules/checks.mjs b/.kiro/skills/impeccable/scripts/detector/rules/checks.mjs
index 579e1c12e..a24631ce9 100644
--- a/.kiro/skills/impeccable/scripts/detector/rules/checks.mjs
+++ b/.kiro/skills/impeccable/scripts/detector/rules/checks.mjs
@@ -688,7 +688,10 @@ function enclosingCssSelector(cssText, index) {
// `{` belongs to some other selector.
const closeBeforeIndex = cssText.lastIndexOf('}', index);
if (closeBeforeIndex > open) return null;
- const prevClose = Math.max(cssText.lastIndexOf('}', open - 1), cssText.lastIndexOf(';', open - 1));
+ // Ignore delimiters inside comments when locating the previous declaration.
+ // Keeping comment length intact preserves indices into the original source.
+ const beforeOpen = cssText.slice(0, open).replace(/\/\*[\s\S]*?\*\//g, comment => ' '.repeat(comment.length));
+ const prevClose = Math.max(beforeOpen.lastIndexOf('}'), beforeOpen.lastIndexOf(';'));
const raw = cssText.slice(prevClose + 1, open).replace(/\/\*[\s\S]*?\*\//g, '').trim().replace(/\s+/g, ' ');
if (!raw || raw.startsWith('@') || /^\d/.test(raw) || /[{}<]/.test(raw)) return null;
// Keyframe steps: percentage steps fail the digit test above, but `from`
@@ -4020,14 +4023,17 @@ function checkTypography() {
}
if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
+ // Report the actual primary face: the uniquely most-used family. The old
+ // 15% threshold labeled secondary faces as primary (e.g. an 82/18 split).
+ const ranked = [...fontUsage.entries()].sort((a, b) => b[1] - a[1]);
+ const [primary] = ranked;
+ const tied = ranked[1]?.[1] === primary?.[1];
+ if (primary && !tied) {
+ const [font, count] = primary;
const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ if (OVERUSED_FONTS.has(font) && !isBrandFontOnOwnDomain(font)) {
+ findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ }
}
}
diff --git a/.kiro/skills/impeccable/scripts/hook-lib.mjs b/.kiro/skills/impeccable/scripts/hook-lib.mjs
index 767fe65a6..6d8c3db81 100644
--- a/.kiro/skills/impeccable/scripts/hook-lib.mjs
+++ b/.kiro/skills/impeccable/scripts/hook-lib.mjs
@@ -138,17 +138,20 @@ export const IMMEDIATE_TIER_RULES = new Set([
// the agent is never nagged about a taste call a human might make on purpose.
// A project opts back in with `.impeccable/config.json`:
// { "detector": { "advisoryRules": "include" } }
-// This set is the hook's own copy of the registry's `advisory: true` rules,
-// mirroring how IMMEDIATE_TIER_RULES lists rule ids inline so the hook stays
-// self-contained and testable without loading the detector. Keep it in sync
-// with the registry (cli/engine/registry/antipatterns.mjs).
+// This legacy id fallback keeps older detector findings recognizable when they
+// carry neither the current runtime flag nor the canonical advisory severity.
+// Current findings are classified by their serialized metadata below.
export const ADVISORY_RULES = new Set([
'em-dash-overuse',
]);
export function isAdvisoryFinding(finding) {
const id = finding && normalizeIgnoreRule(finding.antipattern);
- return Boolean(id && (ADVISORY_RULES.has(id) || finding.advisory === true));
+ return Boolean(id && (
+ ADVISORY_RULES.has(id)
+ || finding.advisory === true
+ || finding.severity === 'advisory'
+ ));
}
export const DEFAULT_CONFIG = Object.freeze({
diff --git a/.opencode/skills/impeccable/scripts/detector/browser/injected/index.mjs b/.opencode/skills/impeccable/scripts/detector/browser/injected/index.mjs
index febf7f297..76fc558e5 100644
--- a/.opencode/skills/impeccable/scripts/detector/browser/injected/index.mjs
+++ b/.opencode/skills/impeccable/scripts/detector/browser/injected/index.mjs
@@ -1228,14 +1228,17 @@ if (IS_BROWSER) {
isHidden: isElementHidden(el),
findings: findings.map(f => {
const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
+ const severity = f.severity || ap?.severity || 'warning';
return {
type: f.type || f.id,
category: ap ? ap.category : 'quality',
- severity: f.severity || ap?.severity || 'warning',
+ severity,
// Advisory findings (em-dash overuse, etc.) are surfaced but never
// treated as failures; carry the flag so the overlay/extension can
// render them with the mildest affordance and consumers can filter.
- advisory: (ap && ap.advisory === true) || f.advisory === true,
+ // Per-finding promotions override the registry default, so derive
+ // this strictly from the effective severity.
+ advisory: severity === 'advisory',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
@@ -1277,6 +1280,381 @@ if (IS_BROWSER) {
else groupMap.set(el, [...kept]);
}
+ function pseudoElementHostSelector(selector) {
+ const raw = String(selector || '');
+ const legacyNames = new Set(['before', 'after', 'first-letter', 'first-line']);
+ const isNameChar = char => /[a-zA-Z0-9_-]/.test(char || '');
+ const consumeFunction = (start) => {
+ let depth = 0;
+ let quote = '';
+ for (let i = start; i < raw.length; i += 1) {
+ const char = raw[i];
+ if (char === '\\') {
+ i += 1;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '(') depth += 1;
+ if (char === ')' && --depth === 0) return i + 1;
+ }
+ return raw.length;
+ };
+
+ let output = '';
+ let found = false;
+ for (let i = 0; i < raw.length;) {
+ const char = raw[i];
+ if (char === '\\') {
+ output += raw.slice(i, Math.min(raw.length, i + 2));
+ i += 2;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ const quote = char;
+ const start = i;
+ i += 1;
+ while (i < raw.length) {
+ if (raw[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ const value = raw[i];
+ i += 1;
+ if (value === quote) break;
+ }
+ output += raw.slice(start, i);
+ continue;
+ }
+ if (char !== ':') {
+ output += char;
+ i += 1;
+ continue;
+ }
+
+ let end = i + 1;
+ let isPseudoElement = false;
+ if (raw[end] === ':') {
+ end += 1;
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = end > nameStart;
+ } else {
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = legacyNames.has(raw.slice(nameStart, end).toLowerCase());
+ }
+ if (!isPseudoElement) {
+ output += char;
+ i += 1;
+ continue;
+ }
+ if (raw[end] === '(') end = consumeFunction(end);
+ found = true;
+ if (!output || /[\s>+~,]/.test(output[output.length - 1])) output += '*';
+ i = end;
+ }
+ if (!found) return null;
+ return output.trim().replace(/,\s*(?=,|$)/g, '');
+ }
+
+ function selectorNodesForLiveDom(root, selector) {
+ const raw = String(selector || '').trim();
+ if (!raw) return null;
+ const fallback = pseudoElementHostSelector(raw);
+ if (fallback == null) {
+ // An empty result from a valid full selector is authoritative. In
+ // particular, do not broaden inactive :hover/:focus/:not() rules to
+ // their host element by stripping pseudo-classes.
+ try { return Array.from(root.querySelectorAll(raw)); }
+ catch { return null; }
+ }
+
+ // Resolve pseudo-elements to their originating live elements. An attached
+ // pseudo-element (`.card::before`) belongs to the element before it, while
+ // a hostless pseudo-element after a combinator (`main > ::before`) belongs
+ // to a matching element at that position (`main > *`). Replacing every
+ // pseudo indiscriminately with an empty string leaves the latter as the
+ // invalid selector `main >` and makes absent hosts indistinguishable from
+ // selectors the DOM API cannot parse.
+ if (!fallback || /^[,\s]*$/.test(fallback)) return null;
+ try { return Array.from(root.querySelectorAll(fallback)); }
+ catch { return null; }
+ }
+
+ let containerProbeSequence = 0;
+
+ function isContainerCssRule(rule) {
+ return rule?.constructor?.name === 'CSSContainerRule'
+ || /^\s*@container\b/i.test(rule?.cssText || '');
+ }
+
+ function styleRuleAppliesToLiveMatches(rule, matches) {
+ const style = rule?.style;
+ if (!style || !matches?.length || typeof getComputedStyle !== 'function') return false;
+ const sequence = ++containerProbeSequence;
+ const property = `--impeccable-container-probe-${sequence}-${Math.random().toString(36).slice(2)}`;
+ const value = `impeccable-container-active-${sequence}`;
+ const previousValue = style.getPropertyValue(property);
+ const previousPriority = style.getPropertyPriority(property);
+ try {
+ style.setProperty(property, value, 'important');
+ } catch {
+ return false;
+ }
+
+ const pseudoElements = [...new Set(
+ String(rule.selectorText || '').match(/::[a-zA-Z-]+(?:\([^)]*\))?/g) || [],
+ )];
+ try {
+ return matches.some(el => [null, ...pseudoElements].some(pseudo => {
+ try {
+ const computed = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el);
+ return computed.getPropertyValue(property).trim() === value;
+ } catch {
+ return false;
+ }
+ }));
+ } finally {
+ if (previousValue) style.setProperty(property, previousValue, previousPriority);
+ else style.removeProperty(property);
+ }
+ }
+
+ function conditionalCssRuleIsActive(rule) {
+ const type = Number(rule?.type);
+ const constructorName = rule?.constructor?.name || '';
+ if (constructorName === 'CSSMediaRule' || type === 4) {
+ const condition = rule.conditionText || rule.media?.mediaText || '';
+ if (!condition || typeof window.matchMedia !== 'function') return true;
+ try { return window.matchMedia(condition).matches; }
+ catch { return true; }
+ }
+ if (constructorName === 'CSSSupportsRule' || type === 12) {
+ const condition = rule.conditionText || '';
+ if (!condition || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return true;
+ try { return CSS.supports(condition); }
+ catch { return true; }
+ }
+ return true;
+ }
+
+ function splitCssCommaList(value) {
+ const parts = [];
+ let current = '';
+ let quote = '';
+ let escaped = false;
+ for (const char of String(value || '')) {
+ if (escaped) {
+ current += char;
+ escaped = false;
+ continue;
+ }
+ if (char === '\\') {
+ current += char;
+ escaped = true;
+ continue;
+ }
+ if (quote) {
+ current += char;
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ current += char;
+ continue;
+ }
+ if (char === ',') {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+ return parts;
+ }
+
+ function normalizeAnimationName(value) {
+ const name = String(value || '').trim();
+ if (name.length >= 2 && name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) {
+ return name.slice(1, -1);
+ }
+ return name;
+ }
+
+ function animationNamesDeclaredByRule(rule) {
+ const style = rule?.style;
+ if (!style) return [];
+ let value = '';
+ try {
+ value = style.animationName
+ || style.getPropertyValue?.('animation-name')
+ || style.webkitAnimationName
+ || style.getPropertyValue?.('-webkit-animation-name')
+ || '';
+ } catch {
+ return [];
+ }
+ return splitCssCommaList(value)
+ .map(normalizeAnimationName)
+ .filter(name => name && name.toLowerCase() !== 'none');
+ }
+
+ function keyframesRuleName(rule, cssText) {
+ const constructorName = rule?.constructor?.name || '';
+ const type = Number(rule?.type);
+ const isKeyframes = constructorName === 'CSSKeyframesRule'
+ || constructorName === 'WebKitCSSKeyframesRule'
+ || type === 7
+ || /^\s*@(?:-webkit-)?keyframes\b/i.test(cssText);
+ if (!isKeyframes) return '';
+ const match = String(cssText || '').match(/^\s*@(?:-webkit-)?keyframes\s+([^\s{]+)/i);
+ return normalizeAnimationName(rule?.name || match?.[1] || '');
+ }
+
+ function cssPropertyName(property) {
+ if (property.startsWith('--')) return property;
+ return property.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
+ }
+
+ function resolvedAnimationKeyframes(candidateNames) {
+ if (typeof document.getAnimations !== 'function') return null;
+ let animations;
+ try { animations = document.getAnimations(); }
+ catch { return null; }
+
+ const resolved = new Map();
+ const metadata = new Set(['offset', 'computedOffset', 'easing', 'composite']);
+ for (const animation of animations) {
+ const name = normalizeAnimationName(animation?.animationName || '');
+ if (!name || !candidateNames.has(name) || resolved.has(name)) continue;
+ let frames;
+ try { frames = animation.effect?.getKeyframes?.() || []; }
+ catch { continue; }
+ const blocks = [];
+ for (const frame of frames) {
+ const rawOffset = Number.isFinite(frame.computedOffset) ? frame.computedOffset : frame.offset;
+ if (!Number.isFinite(rawOffset)) continue;
+ const offset = Math.round(rawOffset * 1000000) / 10000;
+ const declarations = Object.entries(frame)
+ .filter(([property, value]) => !metadata.has(property) && value != null && value !== '')
+ .map(([property, value]) => `${cssPropertyName(property)}: ${value};`);
+ const easing = String(frame.easing || '').trim();
+ if (easing && easing.toLowerCase() !== 'linear') {
+ declarations.push(`animation-timing-function: ${easing};`);
+ }
+ if (declarations.length === 0) continue;
+ blocks.push(`${offset}% { ${declarations.join(' ')} }`);
+ }
+ if (blocks.length > 0) resolved.set(name, `@keyframes ${name} { ${blocks.join(' ')} }`);
+ }
+ return resolved;
+ }
+
+ // Read CSS that is absent from document.outerHTML. Inline <style> blocks are
+ // already present in the HTML pattern corpus, so limit this walk to linked
+ // stylesheets. Flatten grouping rules so each declaration keeps its selector,
+ // and admit only selector rules that target the live DOM. That prevents
+ // unused utilities from feeding both selector-scoped and page-level checks.
+ // Same-origin CSS and readable CORS sheets participate; browser security
+ // exceptions for cross-origin sheets are expected and skipped.
+ function linkedStylesheetText() {
+ const parts = [];
+ const seen = new Set();
+ const animationNames = new Set();
+ const keyframeCandidates = new Map();
+ const appendRules = (rules, requiresAppliedMatch = false) => {
+ for (const rule of rules) {
+ if (rule.styleSheet) {
+ appendSheet(rule.styleSheet);
+ continue;
+ }
+ const cssText = rule.cssText || '';
+ if (rule.selectorText) {
+ const matches = selectorNodesForLiveDom(document, rule.selectorText);
+ // Only declarations with a resolvable live host enter the corpus.
+ // Unresolvable selectors are uncertain, not evidence that a pattern
+ // rendered, and retaining them would leak unused CSS into findings.
+ if (
+ matches?.length > 0
+ && (!requiresAppliedMatch || styleRuleAppliesToLiveMatches(rule, matches))
+ ) {
+ parts.push(cssText);
+ for (const name of animationNamesDeclaredByRule(rule)) animationNames.add(name);
+ }
+ continue;
+ }
+ let nested = [];
+ let hasNestedRules = false;
+ try {
+ const ruleList = rule.cssRules;
+ hasNestedRules = ruleList != null;
+ nested = Array.from(ruleList || []);
+ } catch {
+ continue;
+ }
+ const keyframesName = keyframesRuleName(rule, cssText);
+ if (keyframesName) {
+ // Keyframes do not merge: when a name is defined more than once, the
+ // later effective definition replaces the earlier one.
+ keyframeCandidates.set(keyframesName, {
+ name: keyframesName,
+ cssText,
+ });
+ continue;
+ }
+ if (hasNestedRules) {
+ if (!conditionalCssRuleIsActive(rule)) continue;
+ appendRules(nested, requiresAppliedMatch || isContainerCssRule(rule));
+ continue;
+ }
+ // Other selector-less leaf at-rules cannot be tied to a rendered node.
+ }
+ };
+ const appendSheet = (sheet) => {
+ if (!sheet || seen.has(sheet)) return;
+ seen.add(sheet);
+ let rules;
+ try { rules = Array.from(sheet.cssRules || sheet.rules || []); }
+ catch { return; }
+ appendRules(rules);
+ };
+ let sheets;
+ try { sheets = Array.from(document.styleSheets || []); }
+ catch { return ''; }
+ for (const sheet of sheets) {
+ const owner = sheet.ownerNode;
+ if (owner?.tagName?.toLowerCase() !== 'link') continue;
+ if (!/\bstylesheet\b/i.test(owner.getAttribute?.('rel') || '')) continue;
+ appendSheet(sheet);
+ }
+ // Motion checks need the effective body of a live animation's keyframes.
+ // Let the browser resolve duplicate names across source order, imports,
+ // conditional groups, and cascade layers, then serialize those computed
+ // frames back into the pattern corpus. Browsers also make container-nested
+ // keyframes globally available, so lexical grouping is not a reliable
+ // activity signal. When the Web Animations API is unavailable, fall back to
+ // the last source-order definition referenced by a retained linked rule.
+ const resolvedKeyframes = resolvedAnimationKeyframes(new Set(keyframeCandidates.keys()));
+ if (resolvedKeyframes) {
+ parts.push(...resolvedKeyframes.values());
+ } else {
+ for (const candidate of keyframeCandidates.values()) {
+ if (!animationNames.has(candidate.name)) continue;
+ parts.push(candidate.cssText);
+ }
+ }
+ return parts.join('\n');
+ }
+
function browserFindingsFromMap(groupMap) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
@@ -1650,18 +2028,16 @@ if (IS_BROWSER) {
// (the CSS ships here, but the pattern never renders — the live DOM is
// ground truth in the browser), and a match under a data-impeccable-ignore
// ancestor is waived. Selector-less findings stay page-level.
- const scopedHtmlFindings = checkHtmlPatterns(docClone.outerHTML).filter(f => {
+ const html = docClone.outerHTML;
+ const corpora = buildHtmlPatternCorpora(html);
+ const linkedCss = linkedStylesheetText();
+ if (linkedCss) corpora.styleText += `\n${linkedCss}`;
+ const scopedHtmlFindings = checkHtmlPatterns(html, corpora).filter(f => {
if (!f.selector) return true;
- const query = String(f.selector).replace(/::?[a-zA-Z-]+(\([^)]*\))?/g, '').trim().replace(/,\s*(?=,|$)/g, '');
- if (!query || /^[,\s]*$/.test(query)) return true;
- let matches;
- try {
- matches = document.querySelectorAll(query);
- } catch {
- return true;
- }
+ const matches = selectorNodesForLiveDom(document, f.selector);
+ if (!matches) return false;
if (matches.length === 0) return false;
- return [...matches].some(el => !scopedIgnoreActive(el, f.id));
+ return matches.some(el => !scopedIgnoreActive(el, f.id));
});
if (scopedHtmlFindings.length > 0) {
const mapped = scopedHtmlFindings.map(f => {
diff --git a/.opencode/skills/impeccable/scripts/detector/cli/main.mjs b/.opencode/skills/impeccable/scripts/detector/cli/main.mjs
index 4476d04f1..3451d6c6b 100644
--- a/.opencode/skills/impeccable/scripts/detector/cli/main.mjs
+++ b/.opencode/skills/impeccable/scripts/detector/cli/main.mjs
@@ -37,13 +37,30 @@ function fileUrlToLocalPath(url) {
}
}
+const URL_TARGET_RE = /^(?:https?|file):\/\//i;
+
+// Some agent runners hand a shell-ready URL list to Node as one argv value.
+// A browser accepts the spaces as part of one encoded URL, producing a
+// plausible scan attributed to a bogus joined path. Expand only when every
+// whitespace-delimited token is independently a URL, preserving ordinary
+// filesystem paths that contain spaces.
+function expandJoinedUrlTargets(targets) {
+ return targets.flatMap((target) => {
+ if (!/\s/.test(target)) return [target];
+ const parts = target.trim().split(/\s+/).filter(Boolean);
+ return parts.length > 1 && parts.every(part => URL_TARGET_RE.test(part))
+ ? parts
+ : [target];
+ });
+}
+
// Advisory findings are detected but never treated as failures: they list in a
// separate, visually dimmed section, are excluded from the failure count that
// drives the exit code, and carry `"advisory": true` in JSON so consumers can
// filter. Every advisory finding carries the flag (stamped by the registry via
// findings.mjs).
function isAdvisory(finding) {
- return finding && finding.advisory === true;
+ return Boolean(finding && (finding.advisory === true || finding.severity === 'advisory'));
}
function partitionAdvisory(findings) {
@@ -168,6 +185,10 @@ Advisory findings:
counted as failures and never changing the exit code. They stay out of the
failure count so they never block automation. --no-advisory hides them.
+Output streams:
+ Human-readable findings go to stderr so stdout stays available for structured
+ output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.
+
Project config:
Respects .impeccable/config.json and .impeccable/config.local.json detector
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
@@ -185,7 +206,7 @@ Detection modes:
HTML files Static HTML/CSS analysis (default, catches linked CSS)
Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)
URLs Puppeteer full browser rendering (auto-detected;
- http(s):// and file:// URLs)
+ http(s):// and file:// URLs; accessible linked CSS included)
Examples:
impeccable detect src/
@@ -283,7 +304,7 @@ async function detectCli() {
const designSystem = loadDesignSystemForTarget(localPath, { cache: designSystemCache });
return designSystem ? { ...baseScanOptions, designSystem } : baseScanOptions;
};
- const targets = args.filter(a => !a.startsWith('--'));
+ const targets = expandJoinedUrlTargets(args.filter(a => !a.startsWith('--')));
if (helpMode) { printUsage(); process.exit(0); }
@@ -297,13 +318,12 @@ async function detectCli() {
// real cascade, real computed styles, real layout. Callers that want a
// browser-grade scan of a local artifact can pass file:///abs/path.html
// instead of the bare path (which stays on the static engine).
- const urlRe = /^(?:https?|file):\/\//i;
- const urlTargetCount = paths.filter(target => urlRe.test(target)).length;
+ const urlTargetCount = paths.filter(target => URL_TARGET_RE.test(target)).length;
const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
try {
for (const target of paths) {
- if (urlRe.test(target)) {
+ if (URL_TARGET_RE.test(target)) {
// A file:// URL points at a local artifact, so its design system
// resolves from that file's project. A remote http(s) URL has no
// local project — it gets base options (no design system), never
diff --git a/.opencode/skills/impeccable/scripts/detector/detect-antipatterns-browser.js b/.opencode/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
index e6899f569..460ffb45b 100644
--- a/.opencode/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
+++ b/.opencode/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
@@ -358,7 +358,7 @@ const ANTIPATTERNS = [
// rather than a failure. It fires only on the AI saturation pattern, not on
// ordinary prose. Advisory findings are surfaced separately, never counted
// as failures, and skipped by the design hook unless a project opts in.
- advisory: true,
+ severity: 'advisory',
name: 'Em-dash overuse',
description:
'Em-dash saturation in body copy is an AI cadence tell. Advisory only: humans use em-dashes legitimately, so this fires only on saturation — at least 8 em-dashes (— or --) at a density near one per 500 characters of body text — never on a long article that uses a few. Prefer commas, colons, periods, or parentheses.',
@@ -1961,7 +1961,10 @@ function enclosingCssSelector(cssText, index) {
// `{` belongs to some other selector.
const closeBeforeIndex = cssText.lastIndexOf('}', index);
if (closeBeforeIndex > open) return null;
- const prevClose = Math.max(cssText.lastIndexOf('}', open - 1), cssText.lastIndexOf(';', open - 1));
+ // Ignore delimiters inside comments when locating the previous declaration.
+ // Keeping comment length intact preserves indices into the original source.
+ const beforeOpen = cssText.slice(0, open).replace(/\/\*[\s\S]*?\*\//g, comment => ' '.repeat(comment.length));
+ const prevClose = Math.max(beforeOpen.lastIndexOf('}'), beforeOpen.lastIndexOf(';'));
const raw = cssText.slice(prevClose + 1, open).replace(/\/\*[\s\S]*?\*\//g, '').trim().replace(/\s+/g, ' ');
if (!raw || raw.startsWith('@') || /^\d/.test(raw) || /[{}<]/.test(raw)) return null;
// Keyframe steps: percentage steps fail the digit test above, but `from`
@@ -5293,14 +5296,17 @@ function checkTypography() {
}
if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
+ // Report the actual primary face: the uniquely most-used family. The old
+ // 15% threshold labeled secondary faces as primary (e.g. an 82/18 split).
+ const ranked = [...fontUsage.entries()].sort((a, b) => b[1] - a[1]);
+ const [primary] = ranked;
+ const tied = ranked[1]?.[1] === primary?.[1];
+ if (primary && !tied) {
+ const [font, count] = primary;
const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ if (OVERUSED_FONTS.has(font) && !isBrandFontOnOwnDomain(font)) {
+ findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ }
}
}
@@ -8126,14 +8132,17 @@ if (IS_BROWSER) {
isHidden: isElementHidden(el),
findings: findings.map(f => {
const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
+ const severity = f.severity || ap?.severity || 'warning';
return {
type: f.type || f.id,
category: ap ? ap.category : 'quality',
- severity: f.severity || ap?.severity || 'warning',
+ severity,
// Advisory findings (em-dash overuse, etc.) are surfaced but never
// treated as failures; carry the flag so the overlay/extension can
// render them with the mildest affordance and consumers can filter.
- advisory: (ap && ap.advisory === true) || f.advisory === true,
+ // Per-finding promotions override the registry default, so derive
+ // this strictly from the effective severity.
+ advisory: severity === 'advisory',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
@@ -8175,6 +8184,381 @@ if (IS_BROWSER) {
else groupMap.set(el, [...kept]);
}
+ function pseudoElementHostSelector(selector) {
+ const raw = String(selector || '');
+ const legacyNames = new Set(['before', 'after', 'first-letter', 'first-line']);
+ const isNameChar = char => /[a-zA-Z0-9_-]/.test(char || '');
+ const consumeFunction = (start) => {
+ let depth = 0;
+ let quote = '';
+ for (let i = start; i < raw.length; i += 1) {
+ const char = raw[i];
+ if (char === '\\') {
+ i += 1;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '(') depth += 1;
+ if (char === ')' && --depth === 0) return i + 1;
+ }
+ return raw.length;
+ };
+
+ let output = '';
+ let found = false;
+ for (let i = 0; i < raw.length;) {
+ const char = raw[i];
+ if (char === '\\') {
+ output += raw.slice(i, Math.min(raw.length, i + 2));
+ i += 2;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ const quote = char;
+ const start = i;
+ i += 1;
+ while (i < raw.length) {
+ if (raw[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ const value = raw[i];
+ i += 1;
+ if (value === quote) break;
+ }
+ output += raw.slice(start, i);
+ continue;
+ }
+ if (char !== ':') {
+ output += char;
+ i += 1;
+ continue;
+ }
+
+ let end = i + 1;
+ let isPseudoElement = false;
+ if (raw[end] === ':') {
+ end += 1;
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = end > nameStart;
+ } else {
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = legacyNames.has(raw.slice(nameStart, end).toLowerCase());
+ }
+ if (!isPseudoElement) {
+ output += char;
+ i += 1;
+ continue;
+ }
+ if (raw[end] === '(') end = consumeFunction(end);
+ found = true;
+ if (!output || /[\s>+~,]/.test(output[output.length - 1])) output += '*';
+ i = end;
+ }
+ if (!found) return null;
+ return output.trim().replace(/,\s*(?=,|$)/g, '');
+ }
+
+ function selectorNodesForLiveDom(root, selector) {
+ const raw = String(selector || '').trim();
+ if (!raw) return null;
+ const fallback = pseudoElementHostSelector(raw);
+ if (fallback == null) {
+ // An empty result from a valid full selector is authoritative. In
+ // particular, do not broaden inactive :hover/:focus/:not() rules to
+ // their host element by stripping pseudo-classes.
+ try { return Array.from(root.querySelectorAll(raw)); }
+ catch { return null; }
+ }
+
+ // Resolve pseudo-elements to their originating live elements. An attached
+ // pseudo-element (`.card::before`) belongs to the element before it, while
+ // a hostless pseudo-element after a combinator (`main > ::before`) belongs
+ // to a matching element at that position (`main > *`). Replacing every
+ // pseudo indiscriminately with an empty string leaves the latter as the
+ // invalid selector `main >` and makes absent hosts indistinguishable from
+ // selectors the DOM API cannot parse.
+ if (!fallback || /^[,\s]*$/.test(fallback)) return null;
+ try { return Array.from(root.querySelectorAll(fallback)); }
+ catch { return null; }
+ }
+
+ let containerProbeSequence = 0;
+
+ function isContainerCssRule(rule) {
+ return rule?.constructor?.name === 'CSSContainerRule'
+ || /^\s*@container\b/i.test(rule?.cssText || '');
+ }
+
+ function styleRuleAppliesToLiveMatches(rule, matches) {
+ const style = rule?.style;
+ if (!style || !matches?.length || typeof getComputedStyle !== 'function') return false;
+ const sequence = ++containerProbeSequence;
+ const property = `--impeccable-container-probe-${sequence}-${Math.random().toString(36).slice(2)}`;
+ const value = `impeccable-container-active-${sequence}`;
+ const previousValue = style.getPropertyValue(property);
+ const previousPriority = style.getPropertyPriority(property);
+ try {
+ style.setProperty(property, value, 'important');
+ } catch {
+ return false;
+ }
+
+ const pseudoElements = [...new Set(
+ String(rule.selectorText || '').match(/::[a-zA-Z-]+(?:\([^)]*\))?/g) || [],
+ )];
+ try {
+ return matches.some(el => [null, ...pseudoElements].some(pseudo => {
+ try {
+ const computed = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el);
+ return computed.getPropertyValue(property).trim() === value;
+ } catch {
+ return false;
+ }
+ }));
+ } finally {
+ if (previousValue) style.setProperty(property, previousValue, previousPriority);
+ else style.removeProperty(property);
+ }
+ }
+
+ function conditionalCssRuleIsActive(rule) {
+ const type = Number(rule?.type);
+ const constructorName = rule?.constructor?.name || '';
+ if (constructorName === 'CSSMediaRule' || type === 4) {
+ const condition = rule.conditionText || rule.media?.mediaText || '';
+ if (!condition || typeof window.matchMedia !== 'function') return true;
+ try { return window.matchMedia(condition).matches; }
+ catch { return true; }
+ }
+ if (constructorName === 'CSSSupportsRule' || type === 12) {
+ const condition = rule.conditionText || '';
+ if (!condition || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return true;
+ try { return CSS.supports(condition); }
+ catch { return true; }
+ }
+ return true;
+ }
+
+ function splitCssCommaList(value) {
+ const parts = [];
+ let current = '';
+ let quote = '';
+ let escaped = false;
+ for (const char of String(value || '')) {
+ if (escaped) {
+ current += char;
+ escaped = false;
+ continue;
+ }
+ if (char === '\\') {
+ current += char;
+ escaped = true;
+ continue;
+ }
+ if (quote) {
+ current += char;
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ current += char;
+ continue;
+ }
+ if (char === ',') {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+ return parts;
+ }
+
+ function normalizeAnimationName(value) {
+ const name = String(value || '').trim();
+ if (name.length >= 2 && name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) {
+ return name.slice(1, -1);
+ }
+ return name;
+ }
+
+ function animationNamesDeclaredByRule(rule) {
+ const style = rule?.style;
+ if (!style) return [];
+ let value = '';
+ try {
+ value = style.animationName
+ || style.getPropertyValue?.('animation-name')
+ || style.webkitAnimationName
+ || style.getPropertyValue?.('-webkit-animation-name')
+ || '';
+ } catch {
+ return [];
+ }
+ return splitCssCommaList(value)
+ .map(normalizeAnimationName)
+ .filter(name => name && name.toLowerCase() !== 'none');
+ }
+
+ function keyframesRuleName(rule, cssText) {
+ const constructorName = rule?.constructor?.name || '';
+ const type = Number(rule?.type);
+ const isKeyframes = constructorName === 'CSSKeyframesRule'
+ || constructorName === 'WebKitCSSKeyframesRule'
+ || type === 7
+ || /^\s*@(?:-webkit-)?keyframes\b/i.test(cssText);
+ if (!isKeyframes) return '';
+ const match = String(cssText || '').match(/^\s*@(?:-webkit-)?keyframes\s+([^\s{]+)/i);
+ return normalizeAnimationName(rule?.name || match?.[1] || '');
+ }
+
+ function cssPropertyName(property) {
+ if (property.startsWith('--')) return property;
+ return property.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
+ }
+
+ function resolvedAnimationKeyframes(candidateNames) {
+ if (typeof document.getAnimations !== 'function') return null;
+ let animations;
+ try { animations = document.getAnimations(); }
+ catch { return null; }
+
+ const resolved = new Map();
+ const metadata = new Set(['offset', 'computedOffset', 'easing', 'composite']);
+ for (const animation of animations) {
+ const name = normalizeAnimationName(animation?.animationName || '');
+ if (!name || !candidateNames.has(name) || resolved.has(name)) continue;
+ let frames;
+ try { frames = animation.effect?.getKeyframes?.() || []; }
+ catch { continue; }
+ const blocks = [];
+ for (const frame of frames) {
+ const rawOffset = Number.isFinite(frame.computedOffset) ? frame.computedOffset : frame.offset;
+ if (!Number.isFinite(rawOffset)) continue;
+ const offset = Math.round(rawOffset * 1000000) / 10000;
+ const declarations = Object.entries(frame)
+ .filter(([property, value]) => !metadata.has(property) && value != null && value !== '')
+ .map(([property, value]) => `${cssPropertyName(property)}: ${value};`);
+ const easing = String(frame.easing || '').trim();
+ if (easing && easing.toLowerCase() !== 'linear') {
+ declarations.push(`animation-timing-function: ${easing};`);
+ }
+ if (declarations.length === 0) continue;
+ blocks.push(`${offset}% { ${declarations.join(' ')} }`);
+ }
+ if (blocks.length > 0) resolved.set(name, `@keyframes ${name} { ${blocks.join(' ')} }`);
+ }
+ return resolved;
+ }
+
+ // Read CSS that is absent from document.outerHTML. Inline <style> blocks are
+ // already present in the HTML pattern corpus, so limit this walk to linked
+ // stylesheets. Flatten grouping rules so each declaration keeps its selector,
+ // and admit only selector rules that target the live DOM. That prevents
+ // unused utilities from feeding both selector-scoped and page-level checks.
+ // Same-origin CSS and readable CORS sheets participate; browser security
+ // exceptions for cross-origin sheets are expected and skipped.
+ function linkedStylesheetText() {
+ const parts = [];
+ const seen = new Set();
+ const animationNames = new Set();
+ const keyframeCandidates = new Map();
+ const appendRules = (rules, requiresAppliedMatch = false) => {
+ for (const rule of rules) {
+ if (rule.styleSheet) {
+ appendSheet(rule.styleSheet);
+ continue;
+ }
+ const cssText = rule.cssText || '';
+ if (rule.selectorText) {
+ const matches = selectorNodesForLiveDom(document, rule.selectorText);
+ // Only declarations with a resolvable live host enter the corpus.
+ // Unresolvable selectors are uncertain, not evidence that a pattern
+ // rendered, and retaining them would leak unused CSS into findings.
+ if (
+ matches?.length > 0
+ && (!requiresAppliedMatch || styleRuleAppliesToLiveMatches(rule, matches))
+ ) {
+ parts.push(cssText);
+ for (const name of animationNamesDeclaredByRule(rule)) animationNames.add(name);
+ }
+ continue;
+ }
+ let nested = [];
+ let hasNestedRules = false;
+ try {
+ const ruleList = rule.cssRules;
+ hasNestedRules = ruleList != null;
+ nested = Array.from(ruleList || []);
+ } catch {
+ continue;
+ }
+ const keyframesName = keyframesRuleName(rule, cssText);
+ if (keyframesName) {
+ // Keyframes do not merge: when a name is defined more than once, the
+ // later effective definition replaces the earlier one.
+ keyframeCandidates.set(keyframesName, {
+ name: keyframesName,
+ cssText,
+ });
+ continue;
+ }
+ if (hasNestedRules) {
+ if (!conditionalCssRuleIsActive(rule)) continue;
+ appendRules(nested, requiresAppliedMatch || isContainerCssRule(rule));
+ continue;
+ }
+ // Other selector-less leaf at-rules cannot be tied to a rendered node.
+ }
+ };
+ const appendSheet = (sheet) => {
+ if (!sheet || seen.has(sheet)) return;
+ seen.add(sheet);
+ let rules;
+ try { rules = Array.from(sheet.cssRules || sheet.rules || []); }
+ catch { return; }
+ appendRules(rules);
+ };
+ let sheets;
+ try { sheets = Array.from(document.styleSheets || []); }
+ catch { return ''; }
+ for (const sheet of sheets) {
+ const owner = sheet.ownerNode;
+ if (owner?.tagName?.toLowerCase() !== 'link') continue;
+ if (!/\bstylesheet\b/i.test(owner.getAttribute?.('rel') || '')) continue;
+ appendSheet(sheet);
+ }
+ // Motion checks need the effective body of a live animation's keyframes.
+ // Let the browser resolve duplicate names across source order, imports,
+ // conditional groups, and cascade layers, then serialize those computed
+ // frames back into the pattern corpus. Browsers also make container-nested
+ // keyframes globally available, so lexical grouping is not a reliable
+ // activity signal. When the Web Animations API is unavailable, fall back to
+ // the last source-order definition referenced by a retained linked rule.
+ const resolvedKeyframes = resolvedAnimationKeyframes(new Set(keyframeCandidates.keys()));
+ if (resolvedKeyframes) {
+ parts.push(...resolvedKeyframes.values());
+ } else {
+ for (const candidate of keyframeCandidates.values()) {
+ if (!animationNames.has(candidate.name)) continue;
+ parts.push(candidate.cssText);
+ }
+ }
+ return parts.join('\n');
+ }
+
function browserFindingsFromMap(groupMap) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
@@ -8548,18 +8932,16 @@ if (IS_BROWSER) {
// (the CSS ships here, but the pattern never renders — the live DOM is
// ground truth in the browser), and a match under a data-impeccable-ignore
// ancestor is waived. Selector-less findings stay page-level.
- const scopedHtmlFindings = checkHtmlPatterns(docClone.outerHTML).filter(f => {
+ const html = docClone.outerHTML;
+ const corpora = buildHtmlPatternCorpora(html);
+ const linkedCss = linkedStylesheetText();
+ if (linkedCss) corpora.styleText += `\n${linkedCss}`;
+ const scopedHtmlFindings = checkHtmlPatterns(html, corpora).filter(f => {
if (!f.selector) return true;
- const query = String(f.selector).replace(/::?[a-zA-Z-]+(\([^)]*\))?/g, '').trim().replace(/,\s*(?=,|$)/g, '');
- if (!query || /^[,\s]*$/.test(query)) return true;
- let matches;
- try {
- matches = document.querySelectorAll(query);
- } catch {
- return true;
- }
+ const matches = selectorNodesForLiveDom(document, f.selector);
+ if (!matches) return false;
if (matches.length === 0) return false;
- return [...matches].some(el => !scopedIgnoreActive(el, f.id));
+ return matches.some(el => !scopedIgnoreActive(el, f.id));
});
if (scopedHtmlFindings.length > 0) {
const mapped = scopedHtmlFindings.map(f => {
diff --git a/.opencode/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs b/.opencode/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
index f3ff43c84..ac4bd0a7c 100644
--- a/.opencode/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
+++ b/.opencode/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
@@ -2,7 +2,7 @@ import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { finding } from '../../findings.mjs';
+import { deriveAdvisoryFlag, finding } from '../../findings.mjs';
import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
import { checkContentHiddenAtRest } from '../../rules/checks.mjs';
@@ -394,7 +394,7 @@ async function detectUrl(rawUrl, options = {}) {
// Per-finding severity promotion (e.g. hero-region pulsing dot)
// overrides the registry default carried by finding().
if (f.severity && f.severity !== item.severity) item.severity = f.severity;
- return item;
+ return deriveAdvisoryFlag(item);
});
}
diff --git a/.opencode/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs b/.opencode/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
index 84e6ab1f5..dac6939b0 100644
--- a/.opencode/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
+++ b/.opencode/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
@@ -9,7 +9,7 @@ import {
} from '../../design-system.mjs';
import { isFullPage } from '../../shared/page.mjs';
import { applyInlineIgnores } from '../../shared/inline-ignores.mjs';
-import { finding } from '../../findings.mjs';
+import { deriveAdvisoryFlag, finding } from '../../findings.mjs';
import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import {
checkElementBorders,
@@ -257,7 +257,7 @@ async function detectHtml(filePath, options = {}) {
// severity (e.g. a pulsing dot inside a header/nav landmark) that
// overrides the registry default.
if (f.severity) item.severity = f.severity;
- findings.push(item);
+ findings.push(deriveAdvisoryFlag(item));
}
// Text-content analyzers (em-dash overuse, marketing buzzwords,
// numbered section markers, aphoristic cadence) live in the regex
diff --git a/.opencode/skills/impeccable/scripts/detector/findings.mjs b/.opencode/skills/impeccable/scripts/detector/findings.mjs
index fa98dd935..ae7e134f9 100644
--- a/.opencode/skills/impeccable/scripts/detector/findings.mjs
+++ b/.opencode/skills/impeccable/scripts/detector/findings.mjs
@@ -4,6 +4,12 @@ function getAP(id) {
return getAntipattern(id);
}
+function deriveAdvisoryFlag(item) {
+ if (item.severity === 'advisory') item.advisory = true;
+ else delete item.advisory;
+ return item;
+}
+
function finding(id, filePath, snippet, line = 0) {
const ap = getAP(id);
const base = { antipattern: id, name: ap.name, description: ap.description, severity: ap.severity || 'warning', category: ap.category || null, file: filePath, line, snippet };
@@ -11,8 +17,7 @@ function finding(id, filePath, snippet, line = 0) {
// failures. Carry the flag on the finding so every consumer (CLI, JSON, hook)
// can partition without a registry lookup. Only stamped when true to keep the
// finding shape stable for the vast majority of rules.
- if (ap.advisory === true) base.advisory = true;
- return base;
+ return deriveAdvisoryFlag(base);
}
-export { getAP, finding };
+export { getAP, finding, deriveAdvisoryFlag };
diff --git a/.opencode/skills/impeccable/scripts/detector/registry/antipatterns.mjs b/.opencode/skills/impeccable/scripts/detector/registry/antipatterns.mjs
index 945307783..7c692c79a 100644
--- a/.opencode/skills/impeccable/scripts/detector/registry/antipatterns.mjs
+++ b/.opencode/skills/impeccable/scripts/detector/registry/antipatterns.mjs
@@ -233,7 +233,7 @@ const ANTIPATTERNS = [
// rather than a failure. It fires only on the AI saturation pattern, not on
// ordinary prose. Advisory findings are surfaced separately, never counted
// as failures, and skipped by the design hook unless a project opts in.
- advisory: true,
+ severity: 'advisory',
name: 'Em-dash overuse',
description:
'Em-dash saturation in body copy is an AI cadence tell. Advisory only: humans use em-dashes legitimately, so this fires only on saturation — at least 8 em-dashes (— or --) at a density near one per 500 characters of body text — never on a long article that uses a few. Prefer commas, colons, periods, or parentheses.',
@@ -588,9 +588,10 @@ function getAntipattern(id) {
// Advisory rules are detected and reported, but never treated as failures:
// the CLI lists them under a separate "Advisory" section, they do not affect
// exit codes or the failure count, and the design hook skips them by default.
-// The set is derived from the registry so a rule only needs `advisory: true`.
+// `severity` is the canonical registry field. The runtime finding serializer
+// derives its `advisory: true` compatibility/output flag from this set.
const ADVISORY_RULE_IDS = new Set(
- ANTIPATTERNS.filter(rule => rule.advisory === true).map(rule => rule.id),
+ ANTIPATTERNS.filter(rule => rule.severity === 'advisory').map(rule => rule.id),
);
function isAdvisoryRule(id) {
diff --git a/.opencode/skills/impeccable/scripts/detector/rules/checks.mjs b/.opencode/skills/impeccable/scripts/detector/rules/checks.mjs
index 579e1c12e..a24631ce9 100644
--- a/.opencode/skills/impeccable/scripts/detector/rules/checks.mjs
+++ b/.opencode/skills/impeccable/scripts/detector/rules/checks.mjs
@@ -688,7 +688,10 @@ function enclosingCssSelector(cssText, index) {
// `{` belongs to some other selector.
const closeBeforeIndex = cssText.lastIndexOf('}', index);
if (closeBeforeIndex > open) return null;
- const prevClose = Math.max(cssText.lastIndexOf('}', open - 1), cssText.lastIndexOf(';', open - 1));
+ // Ignore delimiters inside comments when locating the previous declaration.
+ // Keeping comment length intact preserves indices into the original source.
+ const beforeOpen = cssText.slice(0, open).replace(/\/\*[\s\S]*?\*\//g, comment => ' '.repeat(comment.length));
+ const prevClose = Math.max(beforeOpen.lastIndexOf('}'), beforeOpen.lastIndexOf(';'));
const raw = cssText.slice(prevClose + 1, open).replace(/\/\*[\s\S]*?\*\//g, '').trim().replace(/\s+/g, ' ');
if (!raw || raw.startsWith('@') || /^\d/.test(raw) || /[{}<]/.test(raw)) return null;
// Keyframe steps: percentage steps fail the digit test above, but `from`
@@ -4020,14 +4023,17 @@ function checkTypography() {
}
if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
+ // Report the actual primary face: the uniquely most-used family. The old
+ // 15% threshold labeled secondary faces as primary (e.g. an 82/18 split).
+ const ranked = [...fontUsage.entries()].sort((a, b) => b[1] - a[1]);
+ const [primary] = ranked;
+ const tied = ranked[1]?.[1] === primary?.[1];
+ if (primary && !tied) {
+ const [font, count] = primary;
const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ if (OVERUSED_FONTS.has(font) && !isBrandFontOnOwnDomain(font)) {
+ findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ }
}
}
diff --git a/.opencode/skills/impeccable/scripts/hook-lib.mjs b/.opencode/skills/impeccable/scripts/hook-lib.mjs
index 767fe65a6..6d8c3db81 100644
--- a/.opencode/skills/impeccable/scripts/hook-lib.mjs
+++ b/.opencode/skills/impeccable/scripts/hook-lib.mjs
@@ -138,17 +138,20 @@ export const IMMEDIATE_TIER_RULES = new Set([
// the agent is never nagged about a taste call a human might make on purpose.
// A project opts back in with `.impeccable/config.json`:
// { "detector": { "advisoryRules": "include" } }
-// This set is the hook's own copy of the registry's `advisory: true` rules,
-// mirroring how IMMEDIATE_TIER_RULES lists rule ids inline so the hook stays
-// self-contained and testable without loading the detector. Keep it in sync
-// with the registry (cli/engine/registry/antipatterns.mjs).
+// This legacy id fallback keeps older detector findings recognizable when they
+// carry neither the current runtime flag nor the canonical advisory severity.
+// Current findings are classified by their serialized metadata below.
export const ADVISORY_RULES = new Set([
'em-dash-overuse',
]);
export function isAdvisoryFinding(finding) {
const id = finding && normalizeIgnoreRule(finding.antipattern);
- return Boolean(id && (ADVISORY_RULES.has(id) || finding.advisory === true));
+ return Boolean(id && (
+ ADVISORY_RULES.has(id)
+ || finding.advisory === true
+ || finding.severity === 'advisory'
+ ));
}
export const DEFAULT_CONFIG = Object.freeze({
diff --git a/.pi/skills/impeccable/scripts/detector/browser/injected/index.mjs b/.pi/skills/impeccable/scripts/detector/browser/injected/index.mjs
index febf7f297..76fc558e5 100644
--- a/.pi/skills/impeccable/scripts/detector/browser/injected/index.mjs
+++ b/.pi/skills/impeccable/scripts/detector/browser/injected/index.mjs
@@ -1228,14 +1228,17 @@ if (IS_BROWSER) {
isHidden: isElementHidden(el),
findings: findings.map(f => {
const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
+ const severity = f.severity || ap?.severity || 'warning';
return {
type: f.type || f.id,
category: ap ? ap.category : 'quality',
- severity: f.severity || ap?.severity || 'warning',
+ severity,
// Advisory findings (em-dash overuse, etc.) are surfaced but never
// treated as failures; carry the flag so the overlay/extension can
// render them with the mildest affordance and consumers can filter.
- advisory: (ap && ap.advisory === true) || f.advisory === true,
+ // Per-finding promotions override the registry default, so derive
+ // this strictly from the effective severity.
+ advisory: severity === 'advisory',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
@@ -1277,6 +1280,381 @@ if (IS_BROWSER) {
else groupMap.set(el, [...kept]);
}
+ function pseudoElementHostSelector(selector) {
+ const raw = String(selector || '');
+ const legacyNames = new Set(['before', 'after', 'first-letter', 'first-line']);
+ const isNameChar = char => /[a-zA-Z0-9_-]/.test(char || '');
+ const consumeFunction = (start) => {
+ let depth = 0;
+ let quote = '';
+ for (let i = start; i < raw.length; i += 1) {
+ const char = raw[i];
+ if (char === '\\') {
+ i += 1;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '(') depth += 1;
+ if (char === ')' && --depth === 0) return i + 1;
+ }
+ return raw.length;
+ };
+
+ let output = '';
+ let found = false;
+ for (let i = 0; i < raw.length;) {
+ const char = raw[i];
+ if (char === '\\') {
+ output += raw.slice(i, Math.min(raw.length, i + 2));
+ i += 2;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ const quote = char;
+ const start = i;
+ i += 1;
+ while (i < raw.length) {
+ if (raw[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ const value = raw[i];
+ i += 1;
+ if (value === quote) break;
+ }
+ output += raw.slice(start, i);
+ continue;
+ }
+ if (char !== ':') {
+ output += char;
+ i += 1;
+ continue;
+ }
+
+ let end = i + 1;
+ let isPseudoElement = false;
+ if (raw[end] === ':') {
+ end += 1;
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = end > nameStart;
+ } else {
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = legacyNames.has(raw.slice(nameStart, end).toLowerCase());
+ }
+ if (!isPseudoElement) {
+ output += char;
+ i += 1;
+ continue;
+ }
+ if (raw[end] === '(') end = consumeFunction(end);
+ found = true;
+ if (!output || /[\s>+~,]/.test(output[output.length - 1])) output += '*';
+ i = end;
+ }
+ if (!found) return null;
+ return output.trim().replace(/,\s*(?=,|$)/g, '');
+ }
+
+ function selectorNodesForLiveDom(root, selector) {
+ const raw = String(selector || '').trim();
+ if (!raw) return null;
+ const fallback = pseudoElementHostSelector(raw);
+ if (fallback == null) {
+ // An empty result from a valid full selector is authoritative. In
+ // particular, do not broaden inactive :hover/:focus/:not() rules to
+ // their host element by stripping pseudo-classes.
+ try { return Array.from(root.querySelectorAll(raw)); }
+ catch { return null; }
+ }
+
+ // Resolve pseudo-elements to their originating live elements. An attached
+ // pseudo-element (`.card::before`) belongs to the element before it, while
+ // a hostless pseudo-element after a combinator (`main > ::before`) belongs
+ // to a matching element at that position (`main > *`). Replacing every
+ // pseudo indiscriminately with an empty string leaves the latter as the
+ // invalid selector `main >` and makes absent hosts indistinguishable from
+ // selectors the DOM API cannot parse.
+ if (!fallback || /^[,\s]*$/.test(fallback)) return null;
+ try { return Array.from(root.querySelectorAll(fallback)); }
+ catch { return null; }
+ }
+
+ let containerProbeSequence = 0;
+
+ function isContainerCssRule(rule) {
+ return rule?.constructor?.name === 'CSSContainerRule'
+ || /^\s*@container\b/i.test(rule?.cssText || '');
+ }
+
+ function styleRuleAppliesToLiveMatches(rule, matches) {
+ const style = rule?.style;
+ if (!style || !matches?.length || typeof getComputedStyle !== 'function') return false;
+ const sequence = ++containerProbeSequence;
+ const property = `--impeccable-container-probe-${sequence}-${Math.random().toString(36).slice(2)}`;
+ const value = `impeccable-container-active-${sequence}`;
+ const previousValue = style.getPropertyValue(property);
+ const previousPriority = style.getPropertyPriority(property);
+ try {
+ style.setProperty(property, value, 'important');
+ } catch {
+ return false;
+ }
+
+ const pseudoElements = [...new Set(
+ String(rule.selectorText || '').match(/::[a-zA-Z-]+(?:\([^)]*\))?/g) || [],
+ )];
+ try {
+ return matches.some(el => [null, ...pseudoElements].some(pseudo => {
+ try {
+ const computed = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el);
+ return computed.getPropertyValue(property).trim() === value;
+ } catch {
+ return false;
+ }
+ }));
+ } finally {
+ if (previousValue) style.setProperty(property, previousValue, previousPriority);
+ else style.removeProperty(property);
+ }
+ }
+
+ function conditionalCssRuleIsActive(rule) {
+ const type = Number(rule?.type);
+ const constructorName = rule?.constructor?.name || '';
+ if (constructorName === 'CSSMediaRule' || type === 4) {
+ const condition = rule.conditionText || rule.media?.mediaText || '';
+ if (!condition || typeof window.matchMedia !== 'function') return true;
+ try { return window.matchMedia(condition).matches; }
+ catch { return true; }
+ }
+ if (constructorName === 'CSSSupportsRule' || type === 12) {
+ const condition = rule.conditionText || '';
+ if (!condition || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return true;
+ try { return CSS.supports(condition); }
+ catch { return true; }
+ }
+ return true;
+ }
+
+ function splitCssCommaList(value) {
+ const parts = [];
+ let current = '';
+ let quote = '';
+ let escaped = false;
+ for (const char of String(value || '')) {
+ if (escaped) {
+ current += char;
+ escaped = false;
+ continue;
+ }
+ if (char === '\\') {
+ current += char;
+ escaped = true;
+ continue;
+ }
+ if (quote) {
+ current += char;
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ current += char;
+ continue;
+ }
+ if (char === ',') {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+ return parts;
+ }
+
+ function normalizeAnimationName(value) {
+ const name = String(value || '').trim();
+ if (name.length >= 2 && name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) {
+ return name.slice(1, -1);
+ }
+ return name;
+ }
+
+ function animationNamesDeclaredByRule(rule) {
+ const style = rule?.style;
+ if (!style) return [];
+ let value = '';
+ try {
+ value = style.animationName
+ || style.getPropertyValue?.('animation-name')
+ || style.webkitAnimationName
+ || style.getPropertyValue?.('-webkit-animation-name')
+ || '';
+ } catch {
+ return [];
+ }
+ return splitCssCommaList(value)
+ .map(normalizeAnimationName)
+ .filter(name => name && name.toLowerCase() !== 'none');
+ }
+
+ function keyframesRuleName(rule, cssText) {
+ const constructorName = rule?.constructor?.name || '';
+ const type = Number(rule?.type);
+ const isKeyframes = constructorName === 'CSSKeyframesRule'
+ || constructorName === 'WebKitCSSKeyframesRule'
+ || type === 7
+ || /^\s*@(?:-webkit-)?keyframes\b/i.test(cssText);
+ if (!isKeyframes) return '';
+ const match = String(cssText || '').match(/^\s*@(?:-webkit-)?keyframes\s+([^\s{]+)/i);
+ return normalizeAnimationName(rule?.name || match?.[1] || '');
+ }
+
+ function cssPropertyName(property) {
+ if (property.startsWith('--')) return property;
+ return property.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
+ }
+
+ function resolvedAnimationKeyframes(candidateNames) {
+ if (typeof document.getAnimations !== 'function') return null;
+ let animations;
+ try { animations = document.getAnimations(); }
+ catch { return null; }
+
+ const resolved = new Map();
+ const metadata = new Set(['offset', 'computedOffset', 'easing', 'composite']);
+ for (const animation of animations) {
+ const name = normalizeAnimationName(animation?.animationName || '');
+ if (!name || !candidateNames.has(name) || resolved.has(name)) continue;
+ let frames;
+ try { frames = animation.effect?.getKeyframes?.() || []; }
+ catch { continue; }
+ const blocks = [];
+ for (const frame of frames) {
+ const rawOffset = Number.isFinite(frame.computedOffset) ? frame.computedOffset : frame.offset;
+ if (!Number.isFinite(rawOffset)) continue;
+ const offset = Math.round(rawOffset * 1000000) / 10000;
+ const declarations = Object.entries(frame)
+ .filter(([property, value]) => !metadata.has(property) && value != null && value !== '')
+ .map(([property, value]) => `${cssPropertyName(property)}: ${value};`);
+ const easing = String(frame.easing || '').trim();
+ if (easing && easing.toLowerCase() !== 'linear') {
+ declarations.push(`animation-timing-function: ${easing};`);
+ }
+ if (declarations.length === 0) continue;
+ blocks.push(`${offset}% { ${declarations.join(' ')} }`);
+ }
+ if (blocks.length > 0) resolved.set(name, `@keyframes ${name} { ${blocks.join(' ')} }`);
+ }
+ return resolved;
+ }
+
+ // Read CSS that is absent from document.outerHTML. Inline <style> blocks are
+ // already present in the HTML pattern corpus, so limit this walk to linked
+ // stylesheets. Flatten grouping rules so each declaration keeps its selector,
+ // and admit only selector rules that target the live DOM. That prevents
+ // unused utilities from feeding both selector-scoped and page-level checks.
+ // Same-origin CSS and readable CORS sheets participate; browser security
+ // exceptions for cross-origin sheets are expected and skipped.
+ function linkedStylesheetText() {
+ const parts = [];
+ const seen = new Set();
+ const animationNames = new Set();
+ const keyframeCandidates = new Map();
+ const appendRules = (rules, requiresAppliedMatch = false) => {
+ for (const rule of rules) {
+ if (rule.styleSheet) {
+ appendSheet(rule.styleSheet);
+ continue;
+ }
+ const cssText = rule.cssText || '';
+ if (rule.selectorText) {
+ const matches = selectorNodesForLiveDom(document, rule.selectorText);
+ // Only declarations with a resolvable live host enter the corpus.
+ // Unresolvable selectors are uncertain, not evidence that a pattern
+ // rendered, and retaining them would leak unused CSS into findings.
+ if (
+ matches?.length > 0
+ && (!requiresAppliedMatch || styleRuleAppliesToLiveMatches(rule, matches))
+ ) {
+ parts.push(cssText);
+ for (const name of animationNamesDeclaredByRule(rule)) animationNames.add(name);
+ }
+ continue;
+ }
+ let nested = [];
+ let hasNestedRules = false;
+ try {
+ const ruleList = rule.cssRules;
+ hasNestedRules = ruleList != null;
+ nested = Array.from(ruleList || []);
+ } catch {
+ continue;
+ }
+ const keyframesName = keyframesRuleName(rule, cssText);
+ if (keyframesName) {
+ // Keyframes do not merge: when a name is defined more than once, the
+ // later effective definition replaces the earlier one.
+ keyframeCandidates.set(keyframesName, {
+ name: keyframesName,
+ cssText,
+ });
+ continue;
+ }
+ if (hasNestedRules) {
+ if (!conditionalCssRuleIsActive(rule)) continue;
+ appendRules(nested, requiresAppliedMatch || isContainerCssRule(rule));
+ continue;
+ }
+ // Other selector-less leaf at-rules cannot be tied to a rendered node.
+ }
+ };
+ const appendSheet = (sheet) => {
+ if (!sheet || seen.has(sheet)) return;
+ seen.add(sheet);
+ let rules;
+ try { rules = Array.from(sheet.cssRules || sheet.rules || []); }
+ catch { return; }
+ appendRules(rules);
+ };
+ let sheets;
+ try { sheets = Array.from(document.styleSheets || []); }
+ catch { return ''; }
+ for (const sheet of sheets) {
+ const owner = sheet.ownerNode;
+ if (owner?.tagName?.toLowerCase() !== 'link') continue;
+ if (!/\bstylesheet\b/i.test(owner.getAttribute?.('rel') || '')) continue;
+ appendSheet(sheet);
+ }
+ // Motion checks need the effective body of a live animation's keyframes.
+ // Let the browser resolve duplicate names across source order, imports,
+ // conditional groups, and cascade layers, then serialize those computed
+ // frames back into the pattern corpus. Browsers also make container-nested
+ // keyframes globally available, so lexical grouping is not a reliable
+ // activity signal. When the Web Animations API is unavailable, fall back to
+ // the last source-order definition referenced by a retained linked rule.
+ const resolvedKeyframes = resolvedAnimationKeyframes(new Set(keyframeCandidates.keys()));
+ if (resolvedKeyframes) {
+ parts.push(...resolvedKeyframes.values());
+ } else {
+ for (const candidate of keyframeCandidates.values()) {
+ if (!animationNames.has(candidate.name)) continue;
+ parts.push(candidate.cssText);
+ }
+ }
+ return parts.join('\n');
+ }
+
function browserFindingsFromMap(groupMap) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
@@ -1650,18 +2028,16 @@ if (IS_BROWSER) {
// (the CSS ships here, but the pattern never renders — the live DOM is
// ground truth in the browser), and a match under a data-impeccable-ignore
// ancestor is waived. Selector-less findings stay page-level.
- const scopedHtmlFindings = checkHtmlPatterns(docClone.outerHTML).filter(f => {
+ const html = docClone.outerHTML;
+ const corpora = buildHtmlPatternCorpora(html);
+ const linkedCss = linkedStylesheetText();
+ if (linkedCss) corpora.styleText += `\n${linkedCss}`;
+ const scopedHtmlFindings = checkHtmlPatterns(html, corpora).filter(f => {
if (!f.selector) return true;
- const query = String(f.selector).replace(/::?[a-zA-Z-]+(\([^)]*\))?/g, '').trim().replace(/,\s*(?=,|$)/g, '');
- if (!query || /^[,\s]*$/.test(query)) return true;
- let matches;
- try {
- matches = document.querySelectorAll(query);
- } catch {
- return true;
- }
+ const matches = selectorNodesForLiveDom(document, f.selector);
+ if (!matches) return false;
if (matches.length === 0) return false;
- return [...matches].some(el => !scopedIgnoreActive(el, f.id));
+ return matches.some(el => !scopedIgnoreActive(el, f.id));
});
if (scopedHtmlFindings.length > 0) {
const mapped = scopedHtmlFindings.map(f => {
diff --git a/.pi/skills/impeccable/scripts/detector/cli/main.mjs b/.pi/skills/impeccable/scripts/detector/cli/main.mjs
index 4476d04f1..3451d6c6b 100644
--- a/.pi/skills/impeccable/scripts/detector/cli/main.mjs
+++ b/.pi/skills/impeccable/scripts/detector/cli/main.mjs
@@ -37,13 +37,30 @@ function fileUrlToLocalPath(url) {
}
}
+const URL_TARGET_RE = /^(?:https?|file):\/\//i;
+
+// Some agent runners hand a shell-ready URL list to Node as one argv value.
+// A browser accepts the spaces as part of one encoded URL, producing a
+// plausible scan attributed to a bogus joined path. Expand only when every
+// whitespace-delimited token is independently a URL, preserving ordinary
+// filesystem paths that contain spaces.
+function expandJoinedUrlTargets(targets) {
+ return targets.flatMap((target) => {
+ if (!/\s/.test(target)) return [target];
+ const parts = target.trim().split(/\s+/).filter(Boolean);
+ return parts.length > 1 && parts.every(part => URL_TARGET_RE.test(part))
+ ? parts
+ : [target];
+ });
+}
+
// Advisory findings are detected but never treated as failures: they list in a
// separate, visually dimmed section, are excluded from the failure count that
// drives the exit code, and carry `"advisory": true` in JSON so consumers can
// filter. Every advisory finding carries the flag (stamped by the registry via
// findings.mjs).
function isAdvisory(finding) {
- return finding && finding.advisory === true;
+ return Boolean(finding && (finding.advisory === true || finding.severity === 'advisory'));
}
function partitionAdvisory(findings) {
@@ -168,6 +185,10 @@ Advisory findings:
counted as failures and never changing the exit code. They stay out of the
failure count so they never block automation. --no-advisory hides them.
+Output streams:
+ Human-readable findings go to stderr so stdout stays available for structured
+ output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.
+
Project config:
Respects .impeccable/config.json and .impeccable/config.local.json detector
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
@@ -185,7 +206,7 @@ Detection modes:
HTML files Static HTML/CSS analysis (default, catches linked CSS)
Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)
URLs Puppeteer full browser rendering (auto-detected;
- http(s):// and file:// URLs)
+ http(s):// and file:// URLs; accessible linked CSS included)
Examples:
impeccable detect src/
@@ -283,7 +304,7 @@ async function detectCli() {
const designSystem = loadDesignSystemForTarget(localPath, { cache: designSystemCache });
return designSystem ? { ...baseScanOptions, designSystem } : baseScanOptions;
};
- const targets = args.filter(a => !a.startsWith('--'));
+ const targets = expandJoinedUrlTargets(args.filter(a => !a.startsWith('--')));
if (helpMode) { printUsage(); process.exit(0); }
@@ -297,13 +318,12 @@ async function detectCli() {
// real cascade, real computed styles, real layout. Callers that want a
// browser-grade scan of a local artifact can pass file:///abs/path.html
// instead of the bare path (which stays on the static engine).
- const urlRe = /^(?:https?|file):\/\//i;
- const urlTargetCount = paths.filter(target => urlRe.test(target)).length;
+ const urlTargetCount = paths.filter(target => URL_TARGET_RE.test(target)).length;
const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
try {
for (const target of paths) {
- if (urlRe.test(target)) {
+ if (URL_TARGET_RE.test(target)) {
// A file:// URL points at a local artifact, so its design system
// resolves from that file's project. A remote http(s) URL has no
// local project — it gets base options (no design system), never
diff --git a/.pi/skills/impeccable/scripts/detector/detect-antipatterns-browser.js b/.pi/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
index e6899f569..460ffb45b 100644
--- a/.pi/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
+++ b/.pi/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
@@ -358,7 +358,7 @@ const ANTIPATTERNS = [
// rather than a failure. It fires only on the AI saturation pattern, not on
// ordinary prose. Advisory findings are surfaced separately, never counted
// as failures, and skipped by the design hook unless a project opts in.
- advisory: true,
+ severity: 'advisory',
name: 'Em-dash overuse',
description:
'Em-dash saturation in body copy is an AI cadence tell. Advisory only: humans use em-dashes legitimately, so this fires only on saturation — at least 8 em-dashes (— or --) at a density near one per 500 characters of body text — never on a long article that uses a few. Prefer commas, colons, periods, or parentheses.',
@@ -1961,7 +1961,10 @@ function enclosingCssSelector(cssText, index) {
// `{` belongs to some other selector.
const closeBeforeIndex = cssText.lastIndexOf('}', index);
if (closeBeforeIndex > open) return null;
- const prevClose = Math.max(cssText.lastIndexOf('}', open - 1), cssText.lastIndexOf(';', open - 1));
+ // Ignore delimiters inside comments when locating the previous declaration.
+ // Keeping comment length intact preserves indices into the original source.
+ const beforeOpen = cssText.slice(0, open).replace(/\/\*[\s\S]*?\*\//g, comment => ' '.repeat(comment.length));
+ const prevClose = Math.max(beforeOpen.lastIndexOf('}'), beforeOpen.lastIndexOf(';'));
const raw = cssText.slice(prevClose + 1, open).replace(/\/\*[\s\S]*?\*\//g, '').trim().replace(/\s+/g, ' ');
if (!raw || raw.startsWith('@') || /^\d/.test(raw) || /[{}<]/.test(raw)) return null;
// Keyframe steps: percentage steps fail the digit test above, but `from`
@@ -5293,14 +5296,17 @@ function checkTypography() {
}
if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
+ // Report the actual primary face: the uniquely most-used family. The old
+ // 15% threshold labeled secondary faces as primary (e.g. an 82/18 split).
+ const ranked = [...fontUsage.entries()].sort((a, b) => b[1] - a[1]);
+ const [primary] = ranked;
+ const tied = ranked[1]?.[1] === primary?.[1];
+ if (primary && !tied) {
+ const [font, count] = primary;
const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ if (OVERUSED_FONTS.has(font) && !isBrandFontOnOwnDomain(font)) {
+ findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ }
}
}
@@ -8126,14 +8132,17 @@ if (IS_BROWSER) {
isHidden: isElementHidden(el),
findings: findings.map(f => {
const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
+ const severity = f.severity || ap?.severity || 'warning';
return {
type: f.type || f.id,
category: ap ? ap.category : 'quality',
- severity: f.severity || ap?.severity || 'warning',
+ severity,
// Advisory findings (em-dash overuse, etc.) are surfaced but never
// treated as failures; carry the flag so the overlay/extension can
// render them with the mildest affordance and consumers can filter.
- advisory: (ap && ap.advisory === true) || f.advisory === true,
+ // Per-finding promotions override the registry default, so derive
+ // this strictly from the effective severity.
+ advisory: severity === 'advisory',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
@@ -8175,6 +8184,381 @@ if (IS_BROWSER) {
else groupMap.set(el, [...kept]);
}
+ function pseudoElementHostSelector(selector) {
+ const raw = String(selector || '');
+ const legacyNames = new Set(['before', 'after', 'first-letter', 'first-line']);
+ const isNameChar = char => /[a-zA-Z0-9_-]/.test(char || '');
+ const consumeFunction = (start) => {
+ let depth = 0;
+ let quote = '';
+ for (let i = start; i < raw.length; i += 1) {
+ const char = raw[i];
+ if (char === '\\') {
+ i += 1;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '(') depth += 1;
+ if (char === ')' && --depth === 0) return i + 1;
+ }
+ return raw.length;
+ };
+
+ let output = '';
+ let found = false;
+ for (let i = 0; i < raw.length;) {
+ const char = raw[i];
+ if (char === '\\') {
+ output += raw.slice(i, Math.min(raw.length, i + 2));
+ i += 2;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ const quote = char;
+ const start = i;
+ i += 1;
+ while (i < raw.length) {
+ if (raw[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ const value = raw[i];
+ i += 1;
+ if (value === quote) break;
+ }
+ output += raw.slice(start, i);
+ continue;
+ }
+ if (char !== ':') {
+ output += char;
+ i += 1;
+ continue;
+ }
+
+ let end = i + 1;
+ let isPseudoElement = false;
+ if (raw[end] === ':') {
+ end += 1;
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = end > nameStart;
+ } else {
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = legacyNames.has(raw.slice(nameStart, end).toLowerCase());
+ }
+ if (!isPseudoElement) {
+ output += char;
+ i += 1;
+ continue;
+ }
+ if (raw[end] === '(') end = consumeFunction(end);
+ found = true;
+ if (!output || /[\s>+~,]/.test(output[output.length - 1])) output += '*';
+ i = end;
+ }
+ if (!found) return null;
+ return output.trim().replace(/,\s*(?=,|$)/g, '');
+ }
+
+ function selectorNodesForLiveDom(root, selector) {
+ const raw = String(selector || '').trim();
+ if (!raw) return null;
+ const fallback = pseudoElementHostSelector(raw);
+ if (fallback == null) {
+ // An empty result from a valid full selector is authoritative. In
+ // particular, do not broaden inactive :hover/:focus/:not() rules to
+ // their host element by stripping pseudo-classes.
+ try { return Array.from(root.querySelectorAll(raw)); }
+ catch { return null; }
+ }
+
+ // Resolve pseudo-elements to their originating live elements. An attached
+ // pseudo-element (`.card::before`) belongs to the element before it, while
+ // a hostless pseudo-element after a combinator (`main > ::before`) belongs
+ // to a matching element at that position (`main > *`). Replacing every
+ // pseudo indiscriminately with an empty string leaves the latter as the
+ // invalid selector `main >` and makes absent hosts indistinguishable from
+ // selectors the DOM API cannot parse.
+ if (!fallback || /^[,\s]*$/.test(fallback)) return null;
+ try { return Array.from(root.querySelectorAll(fallback)); }
+ catch { return null; }
+ }
+
+ let containerProbeSequence = 0;
+
+ function isContainerCssRule(rule) {
+ return rule?.constructor?.name === 'CSSContainerRule'
+ || /^\s*@container\b/i.test(rule?.cssText || '');
+ }
+
+ function styleRuleAppliesToLiveMatches(rule, matches) {
+ const style = rule?.style;
+ if (!style || !matches?.length || typeof getComputedStyle !== 'function') return false;
+ const sequence = ++containerProbeSequence;
+ const property = `--impeccable-container-probe-${sequence}-${Math.random().toString(36).slice(2)}`;
+ const value = `impeccable-container-active-${sequence}`;
+ const previousValue = style.getPropertyValue(property);
+ const previousPriority = style.getPropertyPriority(property);
+ try {
+ style.setProperty(property, value, 'important');
+ } catch {
+ return false;
+ }
+
+ const pseudoElements = [...new Set(
+ String(rule.selectorText || '').match(/::[a-zA-Z-]+(?:\([^)]*\))?/g) || [],
+ )];
+ try {
+ return matches.some(el => [null, ...pseudoElements].some(pseudo => {
+ try {
+ const computed = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el);
+ return computed.getPropertyValue(property).trim() === value;
+ } catch {
+ return false;
+ }
+ }));
+ } finally {
+ if (previousValue) style.setProperty(property, previousValue, previousPriority);
+ else style.removeProperty(property);
+ }
+ }
+
+ function conditionalCssRuleIsActive(rule) {
+ const type = Number(rule?.type);
+ const constructorName = rule?.constructor?.name || '';
+ if (constructorName === 'CSSMediaRule' || type === 4) {
+ const condition = rule.conditionText || rule.media?.mediaText || '';
+ if (!condition || typeof window.matchMedia !== 'function') return true;
+ try { return window.matchMedia(condition).matches; }
+ catch { return true; }
+ }
+ if (constructorName === 'CSSSupportsRule' || type === 12) {
+ const condition = rule.conditionText || '';
+ if (!condition || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return true;
+ try { return CSS.supports(condition); }
+ catch { return true; }
+ }
+ return true;
+ }
+
+ function splitCssCommaList(value) {
+ const parts = [];
+ let current = '';
+ let quote = '';
+ let escaped = false;
+ for (const char of String(value || '')) {
+ if (escaped) {
+ current += char;
+ escaped = false;
+ continue;
+ }
+ if (char === '\\') {
+ current += char;
+ escaped = true;
+ continue;
+ }
+ if (quote) {
+ current += char;
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ current += char;
+ continue;
+ }
+ if (char === ',') {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+ return parts;
+ }
+
+ function normalizeAnimationName(value) {
+ const name = String(value || '').trim();
+ if (name.length >= 2 && name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) {
+ return name.slice(1, -1);
+ }
+ return name;
+ }
+
+ function animationNamesDeclaredByRule(rule) {
+ const style = rule?.style;
+ if (!style) return [];
+ let value = '';
+ try {
+ value = style.animationName
+ || style.getPropertyValue?.('animation-name')
+ || style.webkitAnimationName
+ || style.getPropertyValue?.('-webkit-animation-name')
+ || '';
+ } catch {
+ return [];
+ }
+ return splitCssCommaList(value)
+ .map(normalizeAnimationName)
+ .filter(name => name && name.toLowerCase() !== 'none');
+ }
+
+ function keyframesRuleName(rule, cssText) {
+ const constructorName = rule?.constructor?.name || '';
+ const type = Number(rule?.type);
+ const isKeyframes = constructorName === 'CSSKeyframesRule'
+ || constructorName === 'WebKitCSSKeyframesRule'
+ || type === 7
+ || /^\s*@(?:-webkit-)?keyframes\b/i.test(cssText);
+ if (!isKeyframes) return '';
+ const match = String(cssText || '').match(/^\s*@(?:-webkit-)?keyframes\s+([^\s{]+)/i);
+ return normalizeAnimationName(rule?.name || match?.[1] || '');
+ }
+
+ function cssPropertyName(property) {
+ if (property.startsWith('--')) return property;
+ return property.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
+ }
+
+ function resolvedAnimationKeyframes(candidateNames) {
+ if (typeof document.getAnimations !== 'function') return null;
+ let animations;
+ try { animations = document.getAnimations(); }
+ catch { return null; }
+
+ const resolved = new Map();
+ const metadata = new Set(['offset', 'computedOffset', 'easing', 'composite']);
+ for (const animation of animations) {
+ const name = normalizeAnimationName(animation?.animationName || '');
+ if (!name || !candidateNames.has(name) || resolved.has(name)) continue;
+ let frames;
+ try { frames = animation.effect?.getKeyframes?.() || []; }
+ catch { continue; }
+ const blocks = [];
+ for (const frame of frames) {
+ const rawOffset = Number.isFinite(frame.computedOffset) ? frame.computedOffset : frame.offset;
+ if (!Number.isFinite(rawOffset)) continue;
+ const offset = Math.round(rawOffset * 1000000) / 10000;
+ const declarations = Object.entries(frame)
+ .filter(([property, value]) => !metadata.has(property) && value != null && value !== '')
+ .map(([property, value]) => `${cssPropertyName(property)}: ${value};`);
+ const easing = String(frame.easing || '').trim();
+ if (easing && easing.toLowerCase() !== 'linear') {
+ declarations.push(`animation-timing-function: ${easing};`);
+ }
+ if (declarations.length === 0) continue;
+ blocks.push(`${offset}% { ${declarations.join(' ')} }`);
+ }
+ if (blocks.length > 0) resolved.set(name, `@keyframes ${name} { ${blocks.join(' ')} }`);
+ }
+ return resolved;
+ }
+
+ // Read CSS that is absent from document.outerHTML. Inline <style> blocks are
+ // already present in the HTML pattern corpus, so limit this walk to linked
+ // stylesheets. Flatten grouping rules so each declaration keeps its selector,
+ // and admit only selector rules that target the live DOM. That prevents
+ // unused utilities from feeding both selector-scoped and page-level checks.
+ // Same-origin CSS and readable CORS sheets participate; browser security
+ // exceptions for cross-origin sheets are expected and skipped.
+ function linkedStylesheetText() {
+ const parts = [];
+ const seen = new Set();
+ const animationNames = new Set();
+ const keyframeCandidates = new Map();
+ const appendRules = (rules, requiresAppliedMatch = false) => {
+ for (const rule of rules) {
+ if (rule.styleSheet) {
+ appendSheet(rule.styleSheet);
+ continue;
+ }
+ const cssText = rule.cssText || '';
+ if (rule.selectorText) {
+ const matches = selectorNodesForLiveDom(document, rule.selectorText);
+ // Only declarations with a resolvable live host enter the corpus.
+ // Unresolvable selectors are uncertain, not evidence that a pattern
+ // rendered, and retaining them would leak unused CSS into findings.
+ if (
+ matches?.length > 0
+ && (!requiresAppliedMatch || styleRuleAppliesToLiveMatches(rule, matches))
+ ) {
+ parts.push(cssText);
+ for (const name of animationNamesDeclaredByRule(rule)) animationNames.add(name);
+ }
+ continue;
+ }
+ let nested = [];
+ let hasNestedRules = false;
+ try {
+ const ruleList = rule.cssRules;
+ hasNestedRules = ruleList != null;
+ nested = Array.from(ruleList || []);
+ } catch {
+ continue;
+ }
+ const keyframesName = keyframesRuleName(rule, cssText);
+ if (keyframesName) {
+ // Keyframes do not merge: when a name is defined more than once, the
+ // later effective definition replaces the earlier one.
+ keyframeCandidates.set(keyframesName, {
+ name: keyframesName,
+ cssText,
+ });
+ continue;
+ }
+ if (hasNestedRules) {
+ if (!conditionalCssRuleIsActive(rule)) continue;
+ appendRules(nested, requiresAppliedMatch || isContainerCssRule(rule));
+ continue;
+ }
+ // Other selector-less leaf at-rules cannot be tied to a rendered node.
+ }
+ };
+ const appendSheet = (sheet) => {
+ if (!sheet || seen.has(sheet)) return;
+ seen.add(sheet);
+ let rules;
+ try { rules = Array.from(sheet.cssRules || sheet.rules || []); }
+ catch { return; }
+ appendRules(rules);
+ };
+ let sheets;
+ try { sheets = Array.from(document.styleSheets || []); }
+ catch { return ''; }
+ for (const sheet of sheets) {
+ const owner = sheet.ownerNode;
+ if (owner?.tagName?.toLowerCase() !== 'link') continue;
+ if (!/\bstylesheet\b/i.test(owner.getAttribute?.('rel') || '')) continue;
+ appendSheet(sheet);
+ }
+ // Motion checks need the effective body of a live animation's keyframes.
+ // Let the browser resolve duplicate names across source order, imports,
+ // conditional groups, and cascade layers, then serialize those computed
+ // frames back into the pattern corpus. Browsers also make container-nested
+ // keyframes globally available, so lexical grouping is not a reliable
+ // activity signal. When the Web Animations API is unavailable, fall back to
+ // the last source-order definition referenced by a retained linked rule.
+ const resolvedKeyframes = resolvedAnimationKeyframes(new Set(keyframeCandidates.keys()));
+ if (resolvedKeyframes) {
+ parts.push(...resolvedKeyframes.values());
+ } else {
+ for (const candidate of keyframeCandidates.values()) {
+ if (!animationNames.has(candidate.name)) continue;
+ parts.push(candidate.cssText);
+ }
+ }
+ return parts.join('\n');
+ }
+
function browserFindingsFromMap(groupMap) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
@@ -8548,18 +8932,16 @@ if (IS_BROWSER) {
// (the CSS ships here, but the pattern never renders — the live DOM is
// ground truth in the browser), and a match under a data-impeccable-ignore
// ancestor is waived. Selector-less findings stay page-level.
- const scopedHtmlFindings = checkHtmlPatterns(docClone.outerHTML).filter(f => {
+ const html = docClone.outerHTML;
+ const corpora = buildHtmlPatternCorpora(html);
+ const linkedCss = linkedStylesheetText();
+ if (linkedCss) corpora.styleText += `\n${linkedCss}`;
+ const scopedHtmlFindings = checkHtmlPatterns(html, corpora).filter(f => {
if (!f.selector) return true;
- const query = String(f.selector).replace(/::?[a-zA-Z-]+(\([^)]*\))?/g, '').trim().replace(/,\s*(?=,|$)/g, '');
- if (!query || /^[,\s]*$/.test(query)) return true;
- let matches;
- try {
- matches = document.querySelectorAll(query);
- } catch {
- return true;
- }
+ const matches = selectorNodesForLiveDom(document, f.selector);
+ if (!matches) return false;
if (matches.length === 0) return false;
- return [...matches].some(el => !scopedIgnoreActive(el, f.id));
+ return matches.some(el => !scopedIgnoreActive(el, f.id));
});
if (scopedHtmlFindings.length > 0) {
const mapped = scopedHtmlFindings.map(f => {
diff --git a/.pi/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs b/.pi/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
index f3ff43c84..ac4bd0a7c 100644
--- a/.pi/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
+++ b/.pi/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
@@ -2,7 +2,7 @@ import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { finding } from '../../findings.mjs';
+import { deriveAdvisoryFlag, finding } from '../../findings.mjs';
import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
import { checkContentHiddenAtRest } from '../../rules/checks.mjs';
@@ -394,7 +394,7 @@ async function detectUrl(rawUrl, options = {}) {
// Per-finding severity promotion (e.g. hero-region pulsing dot)
// overrides the registry default carried by finding().
if (f.severity && f.severity !== item.severity) item.severity = f.severity;
- return item;
+ return deriveAdvisoryFlag(item);
});
}
diff --git a/.pi/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs b/.pi/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
index 84e6ab1f5..dac6939b0 100644
--- a/.pi/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
+++ b/.pi/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
@@ -9,7 +9,7 @@ import {
} from '../../design-system.mjs';
import { isFullPage } from '../../shared/page.mjs';
import { applyInlineIgnores } from '../../shared/inline-ignores.mjs';
-import { finding } from '../../findings.mjs';
+import { deriveAdvisoryFlag, finding } from '../../findings.mjs';
import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import {
checkElementBorders,
@@ -257,7 +257,7 @@ async function detectHtml(filePath, options = {}) {
// severity (e.g. a pulsing dot inside a header/nav landmark) that
// overrides the registry default.
if (f.severity) item.severity = f.severity;
- findings.push(item);
+ findings.push(deriveAdvisoryFlag(item));
}
// Text-content analyzers (em-dash overuse, marketing buzzwords,
// numbered section markers, aphoristic cadence) live in the regex
diff --git a/.pi/skills/impeccable/scripts/detector/findings.mjs b/.pi/skills/impeccable/scripts/detector/findings.mjs
index fa98dd935..ae7e134f9 100644
--- a/.pi/skills/impeccable/scripts/detector/findings.mjs
+++ b/.pi/skills/impeccable/scripts/detector/findings.mjs
@@ -4,6 +4,12 @@ function getAP(id) {
return getAntipattern(id);
}
+function deriveAdvisoryFlag(item) {
+ if (item.severity === 'advisory') item.advisory = true;
+ else delete item.advisory;
+ return item;
+}
+
function finding(id, filePath, snippet, line = 0) {
const ap = getAP(id);
const base = { antipattern: id, name: ap.name, description: ap.description, severity: ap.severity || 'warning', category: ap.category || null, file: filePath, line, snippet };
@@ -11,8 +17,7 @@ function finding(id, filePath, snippet, line = 0) {
// failures. Carry the flag on the finding so every consumer (CLI, JSON, hook)
// can partition without a registry lookup. Only stamped when true to keep the
// finding shape stable for the vast majority of rules.
- if (ap.advisory === true) base.advisory = true;
- return base;
+ return deriveAdvisoryFlag(base);
}
-export { getAP, finding };
+export { getAP, finding, deriveAdvisoryFlag };
diff --git a/.pi/skills/impeccable/scripts/detector/registry/antipatterns.mjs b/.pi/skills/impeccable/scripts/detector/registry/antipatterns.mjs
index 945307783..7c692c79a 100644
--- a/.pi/skills/impeccable/scripts/detector/registry/antipatterns.mjs
+++ b/.pi/skills/impeccable/scripts/detector/registry/antipatterns.mjs
@@ -233,7 +233,7 @@ const ANTIPATTERNS = [
// rather than a failure. It fires only on the AI saturation pattern, not on
// ordinary prose. Advisory findings are surfaced separately, never counted
// as failures, and skipped by the design hook unless a project opts in.
- advisory: true,
+ severity: 'advisory',
name: 'Em-dash overuse',
description:
'Em-dash saturation in body copy is an AI cadence tell. Advisory only: humans use em-dashes legitimately, so this fires only on saturation — at least 8 em-dashes (— or --) at a density near one per 500 characters of body text — never on a long article that uses a few. Prefer commas, colons, periods, or parentheses.',
@@ -588,9 +588,10 @@ function getAntipattern(id) {
// Advisory rules are detected and reported, but never treated as failures:
// the CLI lists them under a separate "Advisory" section, they do not affect
// exit codes or the failure count, and the design hook skips them by default.
-// The set is derived from the registry so a rule only needs `advisory: true`.
+// `severity` is the canonical registry field. The runtime finding serializer
+// derives its `advisory: true` compatibility/output flag from this set.
const ADVISORY_RULE_IDS = new Set(
- ANTIPATTERNS.filter(rule => rule.advisory === true).map(rule => rule.id),
+ ANTIPATTERNS.filter(rule => rule.severity === 'advisory').map(rule => rule.id),
);
function isAdvisoryRule(id) {
diff --git a/.pi/skills/impeccable/scripts/detector/rules/checks.mjs b/.pi/skills/impeccable/scripts/detector/rules/checks.mjs
index 579e1c12e..a24631ce9 100644
--- a/.pi/skills/impeccable/scripts/detector/rules/checks.mjs
+++ b/.pi/skills/impeccable/scripts/detector/rules/checks.mjs
@@ -688,7 +688,10 @@ function enclosingCssSelector(cssText, index) {
// `{` belongs to some other selector.
const closeBeforeIndex = cssText.lastIndexOf('}', index);
if (closeBeforeIndex > open) return null;
- const prevClose = Math.max(cssText.lastIndexOf('}', open - 1), cssText.lastIndexOf(';', open - 1));
+ // Ignore delimiters inside comments when locating the previous declaration.
+ // Keeping comment length intact preserves indices into the original source.
+ const beforeOpen = cssText.slice(0, open).replace(/\/\*[\s\S]*?\*\//g, comment => ' '.repeat(comment.length));
+ const prevClose = Math.max(beforeOpen.lastIndexOf('}'), beforeOpen.lastIndexOf(';'));
const raw = cssText.slice(prevClose + 1, open).replace(/\/\*[\s\S]*?\*\//g, '').trim().replace(/\s+/g, ' ');
if (!raw || raw.startsWith('@') || /^\d/.test(raw) || /[{}<]/.test(raw)) return null;
// Keyframe steps: percentage steps fail the digit test above, but `from`
@@ -4020,14 +4023,17 @@ function checkTypography() {
}
if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
+ // Report the actual primary face: the uniquely most-used family. The old
+ // 15% threshold labeled secondary faces as primary (e.g. an 82/18 split).
+ const ranked = [...fontUsage.entries()].sort((a, b) => b[1] - a[1]);
+ const [primary] = ranked;
+ const tied = ranked[1]?.[1] === primary?.[1];
+ if (primary && !tied) {
+ const [font, count] = primary;
const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ if (OVERUSED_FONTS.has(font) && !isBrandFontOnOwnDomain(font)) {
+ findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ }
}
}
diff --git a/.pi/skills/impeccable/scripts/hook-lib.mjs b/.pi/skills/impeccable/scripts/hook-lib.mjs
index 767fe65a6..6d8c3db81 100644
--- a/.pi/skills/impeccable/scripts/hook-lib.mjs
+++ b/.pi/skills/impeccable/scripts/hook-lib.mjs
@@ -138,17 +138,20 @@ export const IMMEDIATE_TIER_RULES = new Set([
// the agent is never nagged about a taste call a human might make on purpose.
// A project opts back in with `.impeccable/config.json`:
// { "detector": { "advisoryRules": "include" } }
-// This set is the hook's own copy of the registry's `advisory: true` rules,
-// mirroring how IMMEDIATE_TIER_RULES lists rule ids inline so the hook stays
-// self-contained and testable without loading the detector. Keep it in sync
-// with the registry (cli/engine/registry/antipatterns.mjs).
+// This legacy id fallback keeps older detector findings recognizable when they
+// carry neither the current runtime flag nor the canonical advisory severity.
+// Current findings are classified by their serialized metadata below.
export const ADVISORY_RULES = new Set([
'em-dash-overuse',
]);
export function isAdvisoryFinding(finding) {
const id = finding && normalizeIgnoreRule(finding.antipattern);
- return Boolean(id && (ADVISORY_RULES.has(id) || finding.advisory === true));
+ return Boolean(id && (
+ ADVISORY_RULES.has(id)
+ || finding.advisory === true
+ || finding.severity === 'advisory'
+ ));
}
export const DEFAULT_CONFIG = Object.freeze({
diff --git a/.qoder/skills/impeccable/scripts/detector/browser/injected/index.mjs b/.qoder/skills/impeccable/scripts/detector/browser/injected/index.mjs
index febf7f297..76fc558e5 100644
--- a/.qoder/skills/impeccable/scripts/detector/browser/injected/index.mjs
+++ b/.qoder/skills/impeccable/scripts/detector/browser/injected/index.mjs
@@ -1228,14 +1228,17 @@ if (IS_BROWSER) {
isHidden: isElementHidden(el),
findings: findings.map(f => {
const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
+ const severity = f.severity || ap?.severity || 'warning';
return {
type: f.type || f.id,
category: ap ? ap.category : 'quality',
- severity: f.severity || ap?.severity || 'warning',
+ severity,
// Advisory findings (em-dash overuse, etc.) are surfaced but never
// treated as failures; carry the flag so the overlay/extension can
// render them with the mildest affordance and consumers can filter.
- advisory: (ap && ap.advisory === true) || f.advisory === true,
+ // Per-finding promotions override the registry default, so derive
+ // this strictly from the effective severity.
+ advisory: severity === 'advisory',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
@@ -1277,6 +1280,381 @@ if (IS_BROWSER) {
else groupMap.set(el, [...kept]);
}
+ function pseudoElementHostSelector(selector) {
+ const raw = String(selector || '');
+ const legacyNames = new Set(['before', 'after', 'first-letter', 'first-line']);
+ const isNameChar = char => /[a-zA-Z0-9_-]/.test(char || '');
+ const consumeFunction = (start) => {
+ let depth = 0;
+ let quote = '';
+ for (let i = start; i < raw.length; i += 1) {
+ const char = raw[i];
+ if (char === '\\') {
+ i += 1;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '(') depth += 1;
+ if (char === ')' && --depth === 0) return i + 1;
+ }
+ return raw.length;
+ };
+
+ let output = '';
+ let found = false;
+ for (let i = 0; i < raw.length;) {
+ const char = raw[i];
+ if (char === '\\') {
+ output += raw.slice(i, Math.min(raw.length, i + 2));
+ i += 2;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ const quote = char;
+ const start = i;
+ i += 1;
+ while (i < raw.length) {
+ if (raw[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ const value = raw[i];
+ i += 1;
+ if (value === quote) break;
+ }
+ output += raw.slice(start, i);
+ continue;
+ }
+ if (char !== ':') {
+ output += char;
+ i += 1;
+ continue;
+ }
+
+ let end = i + 1;
+ let isPseudoElement = false;
+ if (raw[end] === ':') {
+ end += 1;
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = end > nameStart;
+ } else {
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = legacyNames.has(raw.slice(nameStart, end).toLowerCase());
+ }
+ if (!isPseudoElement) {
+ output += char;
+ i += 1;
+ continue;
+ }
+ if (raw[end] === '(') end = consumeFunction(end);
+ found = true;
+ if (!output || /[\s>+~,]/.test(output[output.length - 1])) output += '*';
+ i = end;
+ }
+ if (!found) return null;
+ return output.trim().replace(/,\s*(?=,|$)/g, '');
+ }
+
+ function selectorNodesForLiveDom(root, selector) {
+ const raw = String(selector || '').trim();
+ if (!raw) return null;
+ const fallback = pseudoElementHostSelector(raw);
+ if (fallback == null) {
+ // An empty result from a valid full selector is authoritative. In
+ // particular, do not broaden inactive :hover/:focus/:not() rules to
+ // their host element by stripping pseudo-classes.
+ try { return Array.from(root.querySelectorAll(raw)); }
+ catch { return null; }
+ }
+
+ // Resolve pseudo-elements to their originating live elements. An attached
+ // pseudo-element (`.card::before`) belongs to the element before it, while
+ // a hostless pseudo-element after a combinator (`main > ::before`) belongs
+ // to a matching element at that position (`main > *`). Replacing every
+ // pseudo indiscriminately with an empty string leaves the latter as the
+ // invalid selector `main >` and makes absent hosts indistinguishable from
+ // selectors the DOM API cannot parse.
+ if (!fallback || /^[,\s]*$/.test(fallback)) return null;
+ try { return Array.from(root.querySelectorAll(fallback)); }
+ catch { return null; }
+ }
+
+ let containerProbeSequence = 0;
+
+ function isContainerCssRule(rule) {
+ return rule?.constructor?.name === 'CSSContainerRule'
+ || /^\s*@container\b/i.test(rule?.cssText || '');
+ }
+
+ function styleRuleAppliesToLiveMatches(rule, matches) {
+ const style = rule?.style;
+ if (!style || !matches?.length || typeof getComputedStyle !== 'function') return false;
+ const sequence = ++containerProbeSequence;
+ const property = `--impeccable-container-probe-${sequence}-${Math.random().toString(36).slice(2)}`;
+ const value = `impeccable-container-active-${sequence}`;
+ const previousValue = style.getPropertyValue(property);
+ const previousPriority = style.getPropertyPriority(property);
+ try {
+ style.setProperty(property, value, 'important');
+ } catch {
+ return false;
+ }
+
+ const pseudoElements = [...new Set(
+ String(rule.selectorText || '').match(/::[a-zA-Z-]+(?:\([^)]*\))?/g) || [],
+ )];
+ try {
+ return matches.some(el => [null, ...pseudoElements].some(pseudo => {
+ try {
+ const computed = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el);
+ return computed.getPropertyValue(property).trim() === value;
+ } catch {
+ return false;
+ }
+ }));
+ } finally {
+ if (previousValue) style.setProperty(property, previousValue, previousPriority);
+ else style.removeProperty(property);
+ }
+ }
+
+ function conditionalCssRuleIsActive(rule) {
+ const type = Number(rule?.type);
+ const constructorName = rule?.constructor?.name || '';
+ if (constructorName === 'CSSMediaRule' || type === 4) {
+ const condition = rule.conditionText || rule.media?.mediaText || '';
+ if (!condition || typeof window.matchMedia !== 'function') return true;
+ try { return window.matchMedia(condition).matches; }
+ catch { return true; }
+ }
+ if (constructorName === 'CSSSupportsRule' || type === 12) {
+ const condition = rule.conditionText || '';
+ if (!condition || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return true;
+ try { return CSS.supports(condition); }
+ catch { return true; }
+ }
+ return true;
+ }
+
+ function splitCssCommaList(value) {
+ const parts = [];
+ let current = '';
+ let quote = '';
+ let escaped = false;
+ for (const char of String(value || '')) {
+ if (escaped) {
+ current += char;
+ escaped = false;
+ continue;
+ }
+ if (char === '\\') {
+ current += char;
+ escaped = true;
+ continue;
+ }
+ if (quote) {
+ current += char;
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ current += char;
+ continue;
+ }
+ if (char === ',') {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+ return parts;
+ }
+
+ function normalizeAnimationName(value) {
+ const name = String(value || '').trim();
+ if (name.length >= 2 && name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) {
+ return name.slice(1, -1);
+ }
+ return name;
+ }
+
+ function animationNamesDeclaredByRule(rule) {
+ const style = rule?.style;
+ if (!style) return [];
+ let value = '';
+ try {
+ value = style.animationName
+ || style.getPropertyValue?.('animation-name')
+ || style.webkitAnimationName
+ || style.getPropertyValue?.('-webkit-animation-name')
+ || '';
+ } catch {
+ return [];
+ }
+ return splitCssCommaList(value)
+ .map(normalizeAnimationName)
+ .filter(name => name && name.toLowerCase() !== 'none');
+ }
+
+ function keyframesRuleName(rule, cssText) {
+ const constructorName = rule?.constructor?.name || '';
+ const type = Number(rule?.type);
+ const isKeyframes = constructorName === 'CSSKeyframesRule'
+ || constructorName === 'WebKitCSSKeyframesRule'
+ || type === 7
+ || /^\s*@(?:-webkit-)?keyframes\b/i.test(cssText);
+ if (!isKeyframes) return '';
+ const match = String(cssText || '').match(/^\s*@(?:-webkit-)?keyframes\s+([^\s{]+)/i);
+ return normalizeAnimationName(rule?.name || match?.[1] || '');
+ }
+
+ function cssPropertyName(property) {
+ if (property.startsWith('--')) return property;
+ return property.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
+ }
+
+ function resolvedAnimationKeyframes(candidateNames) {
+ if (typeof document.getAnimations !== 'function') return null;
+ let animations;
+ try { animations = document.getAnimations(); }
+ catch { return null; }
+
+ const resolved = new Map();
+ const metadata = new Set(['offset', 'computedOffset', 'easing', 'composite']);
+ for (const animation of animations) {
+ const name = normalizeAnimationName(animation?.animationName || '');
+ if (!name || !candidateNames.has(name) || resolved.has(name)) continue;
+ let frames;
+ try { frames = animation.effect?.getKeyframes?.() || []; }
+ catch { continue; }
+ const blocks = [];
+ for (const frame of frames) {
+ const rawOffset = Number.isFinite(frame.computedOffset) ? frame.computedOffset : frame.offset;
+ if (!Number.isFinite(rawOffset)) continue;
+ const offset = Math.round(rawOffset * 1000000) / 10000;
+ const declarations = Object.entries(frame)
+ .filter(([property, value]) => !metadata.has(property) && value != null && value !== '')
+ .map(([property, value]) => `${cssPropertyName(property)}: ${value};`);
+ const easing = String(frame.easing || '').trim();
+ if (easing && easing.toLowerCase() !== 'linear') {
+ declarations.push(`animation-timing-function: ${easing};`);
+ }
+ if (declarations.length === 0) continue;
+ blocks.push(`${offset}% { ${declarations.join(' ')} }`);
+ }
+ if (blocks.length > 0) resolved.set(name, `@keyframes ${name} { ${blocks.join(' ')} }`);
+ }
+ return resolved;
+ }
+
+ // Read CSS that is absent from document.outerHTML. Inline <style> blocks are
+ // already present in the HTML pattern corpus, so limit this walk to linked
+ // stylesheets. Flatten grouping rules so each declaration keeps its selector,
+ // and admit only selector rules that target the live DOM. That prevents
+ // unused utilities from feeding both selector-scoped and page-level checks.
+ // Same-origin CSS and readable CORS sheets participate; browser security
+ // exceptions for cross-origin sheets are expected and skipped.
+ function linkedStylesheetText() {
+ const parts = [];
+ const seen = new Set();
+ const animationNames = new Set();
+ const keyframeCandidates = new Map();
+ const appendRules = (rules, requiresAppliedMatch = false) => {
+ for (const rule of rules) {
+ if (rule.styleSheet) {
+ appendSheet(rule.styleSheet);
+ continue;
+ }
+ const cssText = rule.cssText || '';
+ if (rule.selectorText) {
+ const matches = selectorNodesForLiveDom(document, rule.selectorText);
+ // Only declarations with a resolvable live host enter the corpus.
+ // Unresolvable selectors are uncertain, not evidence that a pattern
+ // rendered, and retaining them would leak unused CSS into findings.
+ if (
+ matches?.length > 0
+ && (!requiresAppliedMatch || styleRuleAppliesToLiveMatches(rule, matches))
+ ) {
+ parts.push(cssText);
+ for (const name of animationNamesDeclaredByRule(rule)) animationNames.add(name);
+ }
+ continue;
+ }
+ let nested = [];
+ let hasNestedRules = false;
+ try {
+ const ruleList = rule.cssRules;
+ hasNestedRules = ruleList != null;
+ nested = Array.from(ruleList || []);
+ } catch {
+ continue;
+ }
+ const keyframesName = keyframesRuleName(rule, cssText);
+ if (keyframesName) {
+ // Keyframes do not merge: when a name is defined more than once, the
+ // later effective definition replaces the earlier one.
+ keyframeCandidates.set(keyframesName, {
+ name: keyframesName,
+ cssText,
+ });
+ continue;
+ }
+ if (hasNestedRules) {
+ if (!conditionalCssRuleIsActive(rule)) continue;
+ appendRules(nested, requiresAppliedMatch || isContainerCssRule(rule));
+ continue;
+ }
+ // Other selector-less leaf at-rules cannot be tied to a rendered node.
+ }
+ };
+ const appendSheet = (sheet) => {
+ if (!sheet || seen.has(sheet)) return;
+ seen.add(sheet);
+ let rules;
+ try { rules = Array.from(sheet.cssRules || sheet.rules || []); }
+ catch { return; }
+ appendRules(rules);
+ };
+ let sheets;
+ try { sheets = Array.from(document.styleSheets || []); }
+ catch { return ''; }
+ for (const sheet of sheets) {
+ const owner = sheet.ownerNode;
+ if (owner?.tagName?.toLowerCase() !== 'link') continue;
+ if (!/\bstylesheet\b/i.test(owner.getAttribute?.('rel') || '')) continue;
+ appendSheet(sheet);
+ }
+ // Motion checks need the effective body of a live animation's keyframes.
+ // Let the browser resolve duplicate names across source order, imports,
+ // conditional groups, and cascade layers, then serialize those computed
+ // frames back into the pattern corpus. Browsers also make container-nested
+ // keyframes globally available, so lexical grouping is not a reliable
+ // activity signal. When the Web Animations API is unavailable, fall back to
+ // the last source-order definition referenced by a retained linked rule.
+ const resolvedKeyframes = resolvedAnimationKeyframes(new Set(keyframeCandidates.keys()));
+ if (resolvedKeyframes) {
+ parts.push(...resolvedKeyframes.values());
+ } else {
+ for (const candidate of keyframeCandidates.values()) {
+ if (!animationNames.has(candidate.name)) continue;
+ parts.push(candidate.cssText);
+ }
+ }
+ return parts.join('\n');
+ }
+
function browserFindingsFromMap(groupMap) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
@@ -1650,18 +2028,16 @@ if (IS_BROWSER) {
// (the CSS ships here, but the pattern never renders — the live DOM is
// ground truth in the browser), and a match under a data-impeccable-ignore
// ancestor is waived. Selector-less findings stay page-level.
- const scopedHtmlFindings = checkHtmlPatterns(docClone.outerHTML).filter(f => {
+ const html = docClone.outerHTML;
+ const corpora = buildHtmlPatternCorpora(html);
+ const linkedCss = linkedStylesheetText();
+ if (linkedCss) corpora.styleText += `\n${linkedCss}`;
+ const scopedHtmlFindings = checkHtmlPatterns(html, corpora).filter(f => {
if (!f.selector) return true;
- const query = String(f.selector).replace(/::?[a-zA-Z-]+(\([^)]*\))?/g, '').trim().replace(/,\s*(?=,|$)/g, '');
- if (!query || /^[,\s]*$/.test(query)) return true;
- let matches;
- try {
- matches = document.querySelectorAll(query);
- } catch {
- return true;
- }
+ const matches = selectorNodesForLiveDom(document, f.selector);
+ if (!matches) return false;
if (matches.length === 0) return false;
- return [...matches].some(el => !scopedIgnoreActive(el, f.id));
+ return matches.some(el => !scopedIgnoreActive(el, f.id));
});
if (scopedHtmlFindings.length > 0) {
const mapped = scopedHtmlFindings.map(f => {
diff --git a/.qoder/skills/impeccable/scripts/detector/cli/main.mjs b/.qoder/skills/impeccable/scripts/detector/cli/main.mjs
index 4476d04f1..3451d6c6b 100644
--- a/.qoder/skills/impeccable/scripts/detector/cli/main.mjs
+++ b/.qoder/skills/impeccable/scripts/detector/cli/main.mjs
@@ -37,13 +37,30 @@ function fileUrlToLocalPath(url) {
}
}
+const URL_TARGET_RE = /^(?:https?|file):\/\//i;
+
+// Some agent runners hand a shell-ready URL list to Node as one argv value.
+// A browser accepts the spaces as part of one encoded URL, producing a
+// plausible scan attributed to a bogus joined path. Expand only when every
+// whitespace-delimited token is independently a URL, preserving ordinary
+// filesystem paths that contain spaces.
+function expandJoinedUrlTargets(targets) {
+ return targets.flatMap((target) => {
+ if (!/\s/.test(target)) return [target];
+ const parts = target.trim().split(/\s+/).filter(Boolean);
+ return parts.length > 1 && parts.every(part => URL_TARGET_RE.test(part))
+ ? parts
+ : [target];
+ });
+}
+
// Advisory findings are detected but never treated as failures: they list in a
// separate, visually dimmed section, are excluded from the failure count that
// drives the exit code, and carry `"advisory": true` in JSON so consumers can
// filter. Every advisory finding carries the flag (stamped by the registry via
// findings.mjs).
function isAdvisory(finding) {
- return finding && finding.advisory === true;
+ return Boolean(finding && (finding.advisory === true || finding.severity === 'advisory'));
}
function partitionAdvisory(findings) {
@@ -168,6 +185,10 @@ Advisory findings:
counted as failures and never changing the exit code. They stay out of the
failure count so they never block automation. --no-advisory hides them.
+Output streams:
+ Human-readable findings go to stderr so stdout stays available for structured
+ output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.
+
Project config:
Respects .impeccable/config.json and .impeccable/config.local.json detector
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
@@ -185,7 +206,7 @@ Detection modes:
HTML files Static HTML/CSS analysis (default, catches linked CSS)
Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)
URLs Puppeteer full browser rendering (auto-detected;
- http(s):// and file:// URLs)
+ http(s):// and file:// URLs; accessible linked CSS included)
Examples:
impeccable detect src/
@@ -283,7 +304,7 @@ async function detectCli() {
const designSystem = loadDesignSystemForTarget(localPath, { cache: designSystemCache });
return designSystem ? { ...baseScanOptions, designSystem } : baseScanOptions;
};
- const targets = args.filter(a => !a.startsWith('--'));
+ const targets = expandJoinedUrlTargets(args.filter(a => !a.startsWith('--')));
if (helpMode) { printUsage(); process.exit(0); }
@@ -297,13 +318,12 @@ async function detectCli() {
// real cascade, real computed styles, real layout. Callers that want a
// browser-grade scan of a local artifact can pass file:///abs/path.html
// instead of the bare path (which stays on the static engine).
- const urlRe = /^(?:https?|file):\/\//i;
- const urlTargetCount = paths.filter(target => urlRe.test(target)).length;
+ const urlTargetCount = paths.filter(target => URL_TARGET_RE.test(target)).length;
const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
try {
for (const target of paths) {
- if (urlRe.test(target)) {
+ if (URL_TARGET_RE.test(target)) {
// A file:// URL points at a local artifact, so its design system
// resolves from that file's project. A remote http(s) URL has no
// local project — it gets base options (no design system), never
diff --git a/.qoder/skills/impeccable/scripts/detector/detect-antipatterns-browser.js b/.qoder/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
index e6899f569..460ffb45b 100644
--- a/.qoder/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
+++ b/.qoder/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
@@ -358,7 +358,7 @@ const ANTIPATTERNS = [
// rather than a failure. It fires only on the AI saturation pattern, not on
// ordinary prose. Advisory findings are surfaced separately, never counted
// as failures, and skipped by the design hook unless a project opts in.
- advisory: true,
+ severity: 'advisory',
name: 'Em-dash overuse',
description:
'Em-dash saturation in body copy is an AI cadence tell. Advisory only: humans use em-dashes legitimately, so this fires only on saturation — at least 8 em-dashes (— or --) at a density near one per 500 characters of body text — never on a long article that uses a few. Prefer commas, colons, periods, or parentheses.',
@@ -1961,7 +1961,10 @@ function enclosingCssSelector(cssText, index) {
// `{` belongs to some other selector.
const closeBeforeIndex = cssText.lastIndexOf('}', index);
if (closeBeforeIndex > open) return null;
- const prevClose = Math.max(cssText.lastIndexOf('}', open - 1), cssText.lastIndexOf(';', open - 1));
+ // Ignore delimiters inside comments when locating the previous declaration.
+ // Keeping comment length intact preserves indices into the original source.
+ const beforeOpen = cssText.slice(0, open).replace(/\/\*[\s\S]*?\*\//g, comment => ' '.repeat(comment.length));
+ const prevClose = Math.max(beforeOpen.lastIndexOf('}'), beforeOpen.lastIndexOf(';'));
const raw = cssText.slice(prevClose + 1, open).replace(/\/\*[\s\S]*?\*\//g, '').trim().replace(/\s+/g, ' ');
if (!raw || raw.startsWith('@') || /^\d/.test(raw) || /[{}<]/.test(raw)) return null;
// Keyframe steps: percentage steps fail the digit test above, but `from`
@@ -5293,14 +5296,17 @@ function checkTypography() {
}
if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
+ // Report the actual primary face: the uniquely most-used family. The old
+ // 15% threshold labeled secondary faces as primary (e.g. an 82/18 split).
+ const ranked = [...fontUsage.entries()].sort((a, b) => b[1] - a[1]);
+ const [primary] = ranked;
+ const tied = ranked[1]?.[1] === primary?.[1];
+ if (primary && !tied) {
+ const [font, count] = primary;
const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ if (OVERUSED_FONTS.has(font) && !isBrandFontOnOwnDomain(font)) {
+ findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ }
}
}
@@ -8126,14 +8132,17 @@ if (IS_BROWSER) {
isHidden: isElementHidden(el),
findings: findings.map(f => {
const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
+ const severity = f.severity || ap?.severity || 'warning';
return {
type: f.type || f.id,
category: ap ? ap.category : 'quality',
- severity: f.severity || ap?.severity || 'warning',
+ severity,
// Advisory findings (em-dash overuse, etc.) are surfaced but never
// treated as failures; carry the flag so the overlay/extension can
// render them with the mildest affordance and consumers can filter.
- advisory: (ap && ap.advisory === true) || f.advisory === true,
+ // Per-finding promotions override the registry default, so derive
+ // this strictly from the effective severity.
+ advisory: severity === 'advisory',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
@@ -8175,6 +8184,381 @@ if (IS_BROWSER) {
else groupMap.set(el, [...kept]);
}
+ function pseudoElementHostSelector(selector) {
+ const raw = String(selector || '');
+ const legacyNames = new Set(['before', 'after', 'first-letter', 'first-line']);
+ const isNameChar = char => /[a-zA-Z0-9_-]/.test(char || '');
+ const consumeFunction = (start) => {
+ let depth = 0;
+ let quote = '';
+ for (let i = start; i < raw.length; i += 1) {
+ const char = raw[i];
+ if (char === '\\') {
+ i += 1;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '(') depth += 1;
+ if (char === ')' && --depth === 0) return i + 1;
+ }
+ return raw.length;
+ };
+
+ let output = '';
+ let found = false;
+ for (let i = 0; i < raw.length;) {
+ const char = raw[i];
+ if (char === '\\') {
+ output += raw.slice(i, Math.min(raw.length, i + 2));
+ i += 2;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ const quote = char;
+ const start = i;
+ i += 1;
+ while (i < raw.length) {
+ if (raw[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ const value = raw[i];
+ i += 1;
+ if (value === quote) break;
+ }
+ output += raw.slice(start, i);
+ continue;
+ }
+ if (char !== ':') {
+ output += char;
+ i += 1;
+ continue;
+ }
+
+ let end = i + 1;
+ let isPseudoElement = false;
+ if (raw[end] === ':') {
+ end += 1;
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = end > nameStart;
+ } else {
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = legacyNames.has(raw.slice(nameStart, end).toLowerCase());
+ }
+ if (!isPseudoElement) {
+ output += char;
+ i += 1;
+ continue;
+ }
+ if (raw[end] === '(') end = consumeFunction(end);
+ found = true;
+ if (!output || /[\s>+~,]/.test(output[output.length - 1])) output += '*';
+ i = end;
+ }
+ if (!found) return null;
+ return output.trim().replace(/,\s*(?=,|$)/g, '');
+ }
+
+ function selectorNodesForLiveDom(root, selector) {
+ const raw = String(selector || '').trim();
+ if (!raw) return null;
+ const fallback = pseudoElementHostSelector(raw);
+ if (fallback == null) {
+ // An empty result from a valid full selector is authoritative. In
+ // particular, do not broaden inactive :hover/:focus/:not() rules to
+ // their host element by stripping pseudo-classes.
+ try { return Array.from(root.querySelectorAll(raw)); }
+ catch { return null; }
+ }
+
+ // Resolve pseudo-elements to their originating live elements. An attached
+ // pseudo-element (`.card::before`) belongs to the element before it, while
+ // a hostless pseudo-element after a combinator (`main > ::before`) belongs
+ // to a matching element at that position (`main > *`). Replacing every
+ // pseudo indiscriminately with an empty string leaves the latter as the
+ // invalid selector `main >` and makes absent hosts indistinguishable from
+ // selectors the DOM API cannot parse.
+ if (!fallback || /^[,\s]*$/.test(fallback)) return null;
+ try { return Array.from(root.querySelectorAll(fallback)); }
+ catch { return null; }
+ }
+
+ let containerProbeSequence = 0;
+
+ function isContainerCssRule(rule) {
+ return rule?.constructor?.name === 'CSSContainerRule'
+ || /^\s*@container\b/i.test(rule?.cssText || '');
+ }
+
+ function styleRuleAppliesToLiveMatches(rule, matches) {
+ const style = rule?.style;
+ if (!style || !matches?.length || typeof getComputedStyle !== 'function') return false;
+ const sequence = ++containerProbeSequence;
+ const property = `--impeccable-container-probe-${sequence}-${Math.random().toString(36).slice(2)}`;
+ const value = `impeccable-container-active-${sequence}`;
+ const previousValue = style.getPropertyValue(property);
+ const previousPriority = style.getPropertyPriority(property);
+ try {
+ style.setProperty(property, value, 'important');
+ } catch {
+ return false;
+ }
+
+ const pseudoElements = [...new Set(
+ String(rule.selectorText || '').match(/::[a-zA-Z-]+(?:\([^)]*\))?/g) || [],
+ )];
+ try {
+ return matches.some(el => [null, ...pseudoElements].some(pseudo => {
+ try {
+ const computed = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el);
+ return computed.getPropertyValue(property).trim() === value;
+ } catch {
+ return false;
+ }
+ }));
+ } finally {
+ if (previousValue) style.setProperty(property, previousValue, previousPriority);
+ else style.removeProperty(property);
+ }
+ }
+
+ function conditionalCssRuleIsActive(rule) {
+ const type = Number(rule?.type);
+ const constructorName = rule?.constructor?.name || '';
+ if (constructorName === 'CSSMediaRule' || type === 4) {
+ const condition = rule.conditionText || rule.media?.mediaText || '';
+ if (!condition || typeof window.matchMedia !== 'function') return true;
+ try { return window.matchMedia(condition).matches; }
+ catch { return true; }
+ }
+ if (constructorName === 'CSSSupportsRule' || type === 12) {
+ const condition = rule.conditionText || '';
+ if (!condition || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return true;
+ try { return CSS.supports(condition); }
+ catch { return true; }
+ }
+ return true;
+ }
+
+ function splitCssCommaList(value) {
+ const parts = [];
+ let current = '';
+ let quote = '';
+ let escaped = false;
+ for (const char of String(value || '')) {
+ if (escaped) {
+ current += char;
+ escaped = false;
+ continue;
+ }
+ if (char === '\\') {
+ current += char;
+ escaped = true;
+ continue;
+ }
+ if (quote) {
+ current += char;
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ current += char;
+ continue;
+ }
+ if (char === ',') {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+ return parts;
+ }
+
+ function normalizeAnimationName(value) {
+ const name = String(value || '').trim();
+ if (name.length >= 2 && name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) {
+ return name.slice(1, -1);
+ }
+ return name;
+ }
+
+ function animationNamesDeclaredByRule(rule) {
+ const style = rule?.style;
+ if (!style) return [];
+ let value = '';
+ try {
+ value = style.animationName
+ || style.getPropertyValue?.('animation-name')
+ || style.webkitAnimationName
+ || style.getPropertyValue?.('-webkit-animation-name')
+ || '';
+ } catch {
+ return [];
+ }
+ return splitCssCommaList(value)
+ .map(normalizeAnimationName)
+ .filter(name => name && name.toLowerCase() !== 'none');
+ }
+
+ function keyframesRuleName(rule, cssText) {
+ const constructorName = rule?.constructor?.name || '';
+ const type = Number(rule?.type);
+ const isKeyframes = constructorName === 'CSSKeyframesRule'
+ || constructorName === 'WebKitCSSKeyframesRule'
+ || type === 7
+ || /^\s*@(?:-webkit-)?keyframes\b/i.test(cssText);
+ if (!isKeyframes) return '';
+ const match = String(cssText || '').match(/^\s*@(?:-webkit-)?keyframes\s+([^\s{]+)/i);
+ return normalizeAnimationName(rule?.name || match?.[1] || '');
+ }
+
+ function cssPropertyName(property) {
+ if (property.startsWith('--')) return property;
+ return property.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
+ }
+
+ function resolvedAnimationKeyframes(candidateNames) {
+ if (typeof document.getAnimations !== 'function') return null;
+ let animations;
+ try { animations = document.getAnimations(); }
+ catch { return null; }
+
+ const resolved = new Map();
+ const metadata = new Set(['offset', 'computedOffset', 'easing', 'composite']);
+ for (const animation of animations) {
+ const name = normalizeAnimationName(animation?.animationName || '');
+ if (!name || !candidateNames.has(name) || resolved.has(name)) continue;
+ let frames;
+ try { frames = animation.effect?.getKeyframes?.() || []; }
+ catch { continue; }
+ const blocks = [];
+ for (const frame of frames) {
+ const rawOffset = Number.isFinite(frame.computedOffset) ? frame.computedOffset : frame.offset;
+ if (!Number.isFinite(rawOffset)) continue;
+ const offset = Math.round(rawOffset * 1000000) / 10000;
+ const declarations = Object.entries(frame)
+ .filter(([property, value]) => !metadata.has(property) && value != null && value !== '')
+ .map(([property, value]) => `${cssPropertyName(property)}: ${value};`);
+ const easing = String(frame.easing || '').trim();
+ if (easing && easing.toLowerCase() !== 'linear') {
+ declarations.push(`animation-timing-function: ${easing};`);
+ }
+ if (declarations.length === 0) continue;
+ blocks.push(`${offset}% { ${declarations.join(' ')} }`);
+ }
+ if (blocks.length > 0) resolved.set(name, `@keyframes ${name} { ${blocks.join(' ')} }`);
+ }
+ return resolved;
+ }
+
+ // Read CSS that is absent from document.outerHTML. Inline <style> blocks are
+ // already present in the HTML pattern corpus, so limit this walk to linked
+ // stylesheets. Flatten grouping rules so each declaration keeps its selector,
+ // and admit only selector rules that target the live DOM. That prevents
+ // unused utilities from feeding both selector-scoped and page-level checks.
+ // Same-origin CSS and readable CORS sheets participate; browser security
+ // exceptions for cross-origin sheets are expected and skipped.
+ function linkedStylesheetText() {
+ const parts = [];
+ const seen = new Set();
+ const animationNames = new Set();
+ const keyframeCandidates = new Map();
+ const appendRules = (rules, requiresAppliedMatch = false) => {
+ for (const rule of rules) {
+ if (rule.styleSheet) {
+ appendSheet(rule.styleSheet);
+ continue;
+ }
+ const cssText = rule.cssText || '';
+ if (rule.selectorText) {
+ const matches = selectorNodesForLiveDom(document, rule.selectorText);
+ // Only declarations with a resolvable live host enter the corpus.
+ // Unresolvable selectors are uncertain, not evidence that a pattern
+ // rendered, and retaining them would leak unused CSS into findings.
+ if (
+ matches?.length > 0
+ && (!requiresAppliedMatch || styleRuleAppliesToLiveMatches(rule, matches))
+ ) {
+ parts.push(cssText);
+ for (const name of animationNamesDeclaredByRule(rule)) animationNames.add(name);
+ }
+ continue;
+ }
+ let nested = [];
+ let hasNestedRules = false;
+ try {
+ const ruleList = rule.cssRules;
+ hasNestedRules = ruleList != null;
+ nested = Array.from(ruleList || []);
+ } catch {
+ continue;
+ }
+ const keyframesName = keyframesRuleName(rule, cssText);
+ if (keyframesName) {
+ // Keyframes do not merge: when a name is defined more than once, the
+ // later effective definition replaces the earlier one.
+ keyframeCandidates.set(keyframesName, {
+ name: keyframesName,
+ cssText,
+ });
+ continue;
+ }
+ if (hasNestedRules) {
+ if (!conditionalCssRuleIsActive(rule)) continue;
+ appendRules(nested, requiresAppliedMatch || isContainerCssRule(rule));
+ continue;
+ }
+ // Other selector-less leaf at-rules cannot be tied to a rendered node.
+ }
+ };
+ const appendSheet = (sheet) => {
+ if (!sheet || seen.has(sheet)) return;
+ seen.add(sheet);
+ let rules;
+ try { rules = Array.from(sheet.cssRules || sheet.rules || []); }
+ catch { return; }
+ appendRules(rules);
+ };
+ let sheets;
+ try { sheets = Array.from(document.styleSheets || []); }
+ catch { return ''; }
+ for (const sheet of sheets) {
+ const owner = sheet.ownerNode;
+ if (owner?.tagName?.toLowerCase() !== 'link') continue;
+ if (!/\bstylesheet\b/i.test(owner.getAttribute?.('rel') || '')) continue;
+ appendSheet(sheet);
+ }
+ // Motion checks need the effective body of a live animation's keyframes.
+ // Let the browser resolve duplicate names across source order, imports,
+ // conditional groups, and cascade layers, then serialize those computed
+ // frames back into the pattern corpus. Browsers also make container-nested
+ // keyframes globally available, so lexical grouping is not a reliable
+ // activity signal. When the Web Animations API is unavailable, fall back to
+ // the last source-order definition referenced by a retained linked rule.
+ const resolvedKeyframes = resolvedAnimationKeyframes(new Set(keyframeCandidates.keys()));
+ if (resolvedKeyframes) {
+ parts.push(...resolvedKeyframes.values());
+ } else {
+ for (const candidate of keyframeCandidates.values()) {
+ if (!animationNames.has(candidate.name)) continue;
+ parts.push(candidate.cssText);
+ }
+ }
+ return parts.join('\n');
+ }
+
function browserFindingsFromMap(groupMap) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
@@ -8548,18 +8932,16 @@ if (IS_BROWSER) {
// (the CSS ships here, but the pattern never renders — the live DOM is
// ground truth in the browser), and a match under a data-impeccable-ignore
// ancestor is waived. Selector-less findings stay page-level.
- const scopedHtmlFindings = checkHtmlPatterns(docClone.outerHTML).filter(f => {
+ const html = docClone.outerHTML;
+ const corpora = buildHtmlPatternCorpora(html);
+ const linkedCss = linkedStylesheetText();
+ if (linkedCss) corpora.styleText += `\n${linkedCss}`;
+ const scopedHtmlFindings = checkHtmlPatterns(html, corpora).filter(f => {
if (!f.selector) return true;
- const query = String(f.selector).replace(/::?[a-zA-Z-]+(\([^)]*\))?/g, '').trim().replace(/,\s*(?=,|$)/g, '');
- if (!query || /^[,\s]*$/.test(query)) return true;
- let matches;
- try {
- matches = document.querySelectorAll(query);
- } catch {
- return true;
- }
+ const matches = selectorNodesForLiveDom(document, f.selector);
+ if (!matches) return false;
if (matches.length === 0) return false;
- return [...matches].some(el => !scopedIgnoreActive(el, f.id));
+ return matches.some(el => !scopedIgnoreActive(el, f.id));
});
if (scopedHtmlFindings.length > 0) {
const mapped = scopedHtmlFindings.map(f => {
diff --git a/.qoder/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs b/.qoder/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
index f3ff43c84..ac4bd0a7c 100644
--- a/.qoder/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
+++ b/.qoder/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
@@ -2,7 +2,7 @@ import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { finding } from '../../findings.mjs';
+import { deriveAdvisoryFlag, finding } from '../../findings.mjs';
import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
import { checkContentHiddenAtRest } from '../../rules/checks.mjs';
@@ -394,7 +394,7 @@ async function detectUrl(rawUrl, options = {}) {
// Per-finding severity promotion (e.g. hero-region pulsing dot)
// overrides the registry default carried by finding().
if (f.severity && f.severity !== item.severity) item.severity = f.severity;
- return item;
+ return deriveAdvisoryFlag(item);
});
}
diff --git a/.qoder/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs b/.qoder/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
index 84e6ab1f5..dac6939b0 100644
--- a/.qoder/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
+++ b/.qoder/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
@@ -9,7 +9,7 @@ import {
} from '../../design-system.mjs';
import { isFullPage } from '../../shared/page.mjs';
import { applyInlineIgnores } from '../../shared/inline-ignores.mjs';
-import { finding } from '../../findings.mjs';
+import { deriveAdvisoryFlag, finding } from '../../findings.mjs';
import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import {
checkElementBorders,
@@ -257,7 +257,7 @@ async function detectHtml(filePath, options = {}) {
// severity (e.g. a pulsing dot inside a header/nav landmark) that
// overrides the registry default.
if (f.severity) item.severity = f.severity;
- findings.push(item);
+ findings.push(deriveAdvisoryFlag(item));
}
// Text-content analyzers (em-dash overuse, marketing buzzwords,
// numbered section markers, aphoristic cadence) live in the regex
diff --git a/.qoder/skills/impeccable/scripts/detector/findings.mjs b/.qoder/skills/impeccable/scripts/detector/findings.mjs
index fa98dd935..ae7e134f9 100644
--- a/.qoder/skills/impeccable/scripts/detector/findings.mjs
+++ b/.qoder/skills/impeccable/scripts/detector/findings.mjs
@@ -4,6 +4,12 @@ function getAP(id) {
return getAntipattern(id);
}
+function deriveAdvisoryFlag(item) {
+ if (item.severity === 'advisory') item.advisory = true;
+ else delete item.advisory;
+ return item;
+}
+
function finding(id, filePath, snippet, line = 0) {
const ap = getAP(id);
const base = { antipattern: id, name: ap.name, description: ap.description, severity: ap.severity || 'warning', category: ap.category || null, file: filePath, line, snippet };
@@ -11,8 +17,7 @@ function finding(id, filePath, snippet, line = 0) {
// failures. Carry the flag on the finding so every consumer (CLI, JSON, hook)
// can partition without a registry lookup. Only stamped when true to keep the
// finding shape stable for the vast majority of rules.
- if (ap.advisory === true) base.advisory = true;
- return base;
+ return deriveAdvisoryFlag(base);
}
-export { getAP, finding };
+export { getAP, finding, deriveAdvisoryFlag };
diff --git a/.qoder/skills/impeccable/scripts/detector/registry/antipatterns.mjs b/.qoder/skills/impeccable/scripts/detector/registry/antipatterns.mjs
index 945307783..7c692c79a 100644
--- a/.qoder/skills/impeccable/scripts/detector/registry/antipatterns.mjs
+++ b/.qoder/skills/impeccable/scripts/detector/registry/antipatterns.mjs
@@ -233,7 +233,7 @@ const ANTIPATTERNS = [
// rather than a failure. It fires only on the AI saturation pattern, not on
// ordinary prose. Advisory findings are surfaced separately, never counted
// as failures, and skipped by the design hook unless a project opts in.
- advisory: true,
+ severity: 'advisory',
name: 'Em-dash overuse',
description:
'Em-dash saturation in body copy is an AI cadence tell. Advisory only: humans use em-dashes legitimately, so this fires only on saturation — at least 8 em-dashes (— or --) at a density near one per 500 characters of body text — never on a long article that uses a few. Prefer commas, colons, periods, or parentheses.',
@@ -588,9 +588,10 @@ function getAntipattern(id) {
// Advisory rules are detected and reported, but never treated as failures:
// the CLI lists them under a separate "Advisory" section, they do not affect
// exit codes or the failure count, and the design hook skips them by default.
-// The set is derived from the registry so a rule only needs `advisory: true`.
+// `severity` is the canonical registry field. The runtime finding serializer
+// derives its `advisory: true` compatibility/output flag from this set.
const ADVISORY_RULE_IDS = new Set(
- ANTIPATTERNS.filter(rule => rule.advisory === true).map(rule => rule.id),
+ ANTIPATTERNS.filter(rule => rule.severity === 'advisory').map(rule => rule.id),
);
function isAdvisoryRule(id) {
diff --git a/.qoder/skills/impeccable/scripts/detector/rules/checks.mjs b/.qoder/skills/impeccable/scripts/detector/rules/checks.mjs
index 579e1c12e..a24631ce9 100644
--- a/.qoder/skills/impeccable/scripts/detector/rules/checks.mjs
+++ b/.qoder/skills/impeccable/scripts/detector/rules/checks.mjs
@@ -688,7 +688,10 @@ function enclosingCssSelector(cssText, index) {
// `{` belongs to some other selector.
const closeBeforeIndex = cssText.lastIndexOf('}', index);
if (closeBeforeIndex > open) return null;
- const prevClose = Math.max(cssText.lastIndexOf('}', open - 1), cssText.lastIndexOf(';', open - 1));
+ // Ignore delimiters inside comments when locating the previous declaration.
+ // Keeping comment length intact preserves indices into the original source.
+ const beforeOpen = cssText.slice(0, open).replace(/\/\*[\s\S]*?\*\//g, comment => ' '.repeat(comment.length));
+ const prevClose = Math.max(beforeOpen.lastIndexOf('}'), beforeOpen.lastIndexOf(';'));
const raw = cssText.slice(prevClose + 1, open).replace(/\/\*[\s\S]*?\*\//g, '').trim().replace(/\s+/g, ' ');
if (!raw || raw.startsWith('@') || /^\d/.test(raw) || /[{}<]/.test(raw)) return null;
// Keyframe steps: percentage steps fail the digit test above, but `from`
@@ -4020,14 +4023,17 @@ function checkTypography() {
}
if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
+ // Report the actual primary face: the uniquely most-used family. The old
+ // 15% threshold labeled secondary faces as primary (e.g. an 82/18 split).
+ const ranked = [...fontUsage.entries()].sort((a, b) => b[1] - a[1]);
+ const [primary] = ranked;
+ const tied = ranked[1]?.[1] === primary?.[1];
+ if (primary && !tied) {
+ const [font, count] = primary;
const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ if (OVERUSED_FONTS.has(font) && !isBrandFontOnOwnDomain(font)) {
+ findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ }
}
}
diff --git a/.qoder/skills/impeccable/scripts/hook-lib.mjs b/.qoder/skills/impeccable/scripts/hook-lib.mjs
index 767fe65a6..6d8c3db81 100644
--- a/.qoder/skills/impeccable/scripts/hook-lib.mjs
+++ b/.qoder/skills/impeccable/scripts/hook-lib.mjs
@@ -138,17 +138,20 @@ export const IMMEDIATE_TIER_RULES = new Set([
// the agent is never nagged about a taste call a human might make on purpose.
// A project opts back in with `.impeccable/config.json`:
// { "detector": { "advisoryRules": "include" } }
-// This set is the hook's own copy of the registry's `advisory: true` rules,
-// mirroring how IMMEDIATE_TIER_RULES lists rule ids inline so the hook stays
-// self-contained and testable without loading the detector. Keep it in sync
-// with the registry (cli/engine/registry/antipatterns.mjs).
+// This legacy id fallback keeps older detector findings recognizable when they
+// carry neither the current runtime flag nor the canonical advisory severity.
+// Current findings are classified by their serialized metadata below.
export const ADVISORY_RULES = new Set([
'em-dash-overuse',
]);
export function isAdvisoryFinding(finding) {
const id = finding && normalizeIgnoreRule(finding.antipattern);
- return Boolean(id && (ADVISORY_RULES.has(id) || finding.advisory === true));
+ return Boolean(id && (
+ ADVISORY_RULES.has(id)
+ || finding.advisory === true
+ || finding.severity === 'advisory'
+ ));
}
export const DEFAULT_CONFIG = Object.freeze({
diff --git a/.rovodev/skills/impeccable/scripts/detector/browser/injected/index.mjs b/.rovodev/skills/impeccable/scripts/detector/browser/injected/index.mjs
index febf7f297..76fc558e5 100644
--- a/.rovodev/skills/impeccable/scripts/detector/browser/injected/index.mjs
+++ b/.rovodev/skills/impeccable/scripts/detector/browser/injected/index.mjs
@@ -1228,14 +1228,17 @@ if (IS_BROWSER) {
isHidden: isElementHidden(el),
findings: findings.map(f => {
const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
+ const severity = f.severity || ap?.severity || 'warning';
return {
type: f.type || f.id,
category: ap ? ap.category : 'quality',
- severity: f.severity || ap?.severity || 'warning',
+ severity,
// Advisory findings (em-dash overuse, etc.) are surfaced but never
// treated as failures; carry the flag so the overlay/extension can
// render them with the mildest affordance and consumers can filter.
- advisory: (ap && ap.advisory === true) || f.advisory === true,
+ // Per-finding promotions override the registry default, so derive
+ // this strictly from the effective severity.
+ advisory: severity === 'advisory',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
@@ -1277,6 +1280,381 @@ if (IS_BROWSER) {
else groupMap.set(el, [...kept]);
}
+ function pseudoElementHostSelector(selector) {
+ const raw = String(selector || '');
+ const legacyNames = new Set(['before', 'after', 'first-letter', 'first-line']);
+ const isNameChar = char => /[a-zA-Z0-9_-]/.test(char || '');
+ const consumeFunction = (start) => {
+ let depth = 0;
+ let quote = '';
+ for (let i = start; i < raw.length; i += 1) {
+ const char = raw[i];
+ if (char === '\\') {
+ i += 1;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '(') depth += 1;
+ if (char === ')' && --depth === 0) return i + 1;
+ }
+ return raw.length;
+ };
+
+ let output = '';
+ let found = false;
+ for (let i = 0; i < raw.length;) {
+ const char = raw[i];
+ if (char === '\\') {
+ output += raw.slice(i, Math.min(raw.length, i + 2));
+ i += 2;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ const quote = char;
+ const start = i;
+ i += 1;
+ while (i < raw.length) {
+ if (raw[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ const value = raw[i];
+ i += 1;
+ if (value === quote) break;
+ }
+ output += raw.slice(start, i);
+ continue;
+ }
+ if (char !== ':') {
+ output += char;
+ i += 1;
+ continue;
+ }
+
+ let end = i + 1;
+ let isPseudoElement = false;
+ if (raw[end] === ':') {
+ end += 1;
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = end > nameStart;
+ } else {
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = legacyNames.has(raw.slice(nameStart, end).toLowerCase());
+ }
+ if (!isPseudoElement) {
+ output += char;
+ i += 1;
+ continue;
+ }
+ if (raw[end] === '(') end = consumeFunction(end);
+ found = true;
+ if (!output || /[\s>+~,]/.test(output[output.length - 1])) output += '*';
+ i = end;
+ }
+ if (!found) return null;
+ return output.trim().replace(/,\s*(?=,|$)/g, '');
+ }
+
+ function selectorNodesForLiveDom(root, selector) {
+ const raw = String(selector || '').trim();
+ if (!raw) return null;
+ const fallback = pseudoElementHostSelector(raw);
+ if (fallback == null) {
+ // An empty result from a valid full selector is authoritative. In
+ // particular, do not broaden inactive :hover/:focus/:not() rules to
+ // their host element by stripping pseudo-classes.
+ try { return Array.from(root.querySelectorAll(raw)); }
+ catch { return null; }
+ }
+
+ // Resolve pseudo-elements to their originating live elements. An attached
+ // pseudo-element (`.card::before`) belongs to the element before it, while
+ // a hostless pseudo-element after a combinator (`main > ::before`) belongs
+ // to a matching element at that position (`main > *`). Replacing every
+ // pseudo indiscriminately with an empty string leaves the latter as the
+ // invalid selector `main >` and makes absent hosts indistinguishable from
+ // selectors the DOM API cannot parse.
+ if (!fallback || /^[,\s]*$/.test(fallback)) return null;
+ try { return Array.from(root.querySelectorAll(fallback)); }
+ catch { return null; }
+ }
+
+ let containerProbeSequence = 0;
+
+ function isContainerCssRule(rule) {
+ return rule?.constructor?.name === 'CSSContainerRule'
+ || /^\s*@container\b/i.test(rule?.cssText || '');
+ }
+
+ function styleRuleAppliesToLiveMatches(rule, matches) {
+ const style = rule?.style;
+ if (!style || !matches?.length || typeof getComputedStyle !== 'function') return false;
+ const sequence = ++containerProbeSequence;
+ const property = `--impeccable-container-probe-${sequence}-${Math.random().toString(36).slice(2)}`;
+ const value = `impeccable-container-active-${sequence}`;
+ const previousValue = style.getPropertyValue(property);
+ const previousPriority = style.getPropertyPriority(property);
+ try {
+ style.setProperty(property, value, 'important');
+ } catch {
+ return false;
+ }
+
+ const pseudoElements = [...new Set(
+ String(rule.selectorText || '').match(/::[a-zA-Z-]+(?:\([^)]*\))?/g) || [],
+ )];
+ try {
+ return matches.some(el => [null, ...pseudoElements].some(pseudo => {
+ try {
+ const computed = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el);
+ return computed.getPropertyValue(property).trim() === value;
+ } catch {
+ return false;
+ }
+ }));
+ } finally {
+ if (previousValue) style.setProperty(property, previousValue, previousPriority);
+ else style.removeProperty(property);
+ }
+ }
+
+ function conditionalCssRuleIsActive(rule) {
+ const type = Number(rule?.type);
+ const constructorName = rule?.constructor?.name || '';
+ if (constructorName === 'CSSMediaRule' || type === 4) {
+ const condition = rule.conditionText || rule.media?.mediaText || '';
+ if (!condition || typeof window.matchMedia !== 'function') return true;
+ try { return window.matchMedia(condition).matches; }
+ catch { return true; }
+ }
+ if (constructorName === 'CSSSupportsRule' || type === 12) {
+ const condition = rule.conditionText || '';
+ if (!condition || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return true;
+ try { return CSS.supports(condition); }
+ catch { return true; }
+ }
+ return true;
+ }
+
+ function splitCssCommaList(value) {
+ const parts = [];
+ let current = '';
+ let quote = '';
+ let escaped = false;
+ for (const char of String(value || '')) {
+ if (escaped) {
+ current += char;
+ escaped = false;
+ continue;
+ }
+ if (char === '\\') {
+ current += char;
+ escaped = true;
+ continue;
+ }
+ if (quote) {
+ current += char;
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ current += char;
+ continue;
+ }
+ if (char === ',') {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+ return parts;
+ }
+
+ function normalizeAnimationName(value) {
+ const name = String(value || '').trim();
+ if (name.length >= 2 && name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) {
+ return name.slice(1, -1);
+ }
+ return name;
+ }
+
+ function animationNamesDeclaredByRule(rule) {
+ const style = rule?.style;
+ if (!style) return [];
+ let value = '';
+ try {
+ value = style.animationName
+ || style.getPropertyValue?.('animation-name')
+ || style.webkitAnimationName
+ || style.getPropertyValue?.('-webkit-animation-name')
+ || '';
+ } catch {
+ return [];
+ }
+ return splitCssCommaList(value)
+ .map(normalizeAnimationName)
+ .filter(name => name && name.toLowerCase() !== 'none');
+ }
+
+ function keyframesRuleName(rule, cssText) {
+ const constructorName = rule?.constructor?.name || '';
+ const type = Number(rule?.type);
+ const isKeyframes = constructorName === 'CSSKeyframesRule'
+ || constructorName === 'WebKitCSSKeyframesRule'
+ || type === 7
+ || /^\s*@(?:-webkit-)?keyframes\b/i.test(cssText);
+ if (!isKeyframes) return '';
+ const match = String(cssText || '').match(/^\s*@(?:-webkit-)?keyframes\s+([^\s{]+)/i);
+ return normalizeAnimationName(rule?.name || match?.[1] || '');
+ }
+
+ function cssPropertyName(property) {
+ if (property.startsWith('--')) return property;
+ return property.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
+ }
+
+ function resolvedAnimationKeyframes(candidateNames) {
+ if (typeof document.getAnimations !== 'function') return null;
+ let animations;
+ try { animations = document.getAnimations(); }
+ catch { return null; }
+
+ const resolved = new Map();
+ const metadata = new Set(['offset', 'computedOffset', 'easing', 'composite']);
+ for (const animation of animations) {
+ const name = normalizeAnimationName(animation?.animationName || '');
+ if (!name || !candidateNames.has(name) || resolved.has(name)) continue;
+ let frames;
+ try { frames = animation.effect?.getKeyframes?.() || []; }
+ catch { continue; }
+ const blocks = [];
+ for (const frame of frames) {
+ const rawOffset = Number.isFinite(frame.computedOffset) ? frame.computedOffset : frame.offset;
+ if (!Number.isFinite(rawOffset)) continue;
+ const offset = Math.round(rawOffset * 1000000) / 10000;
+ const declarations = Object.entries(frame)
+ .filter(([property, value]) => !metadata.has(property) && value != null && value !== '')
+ .map(([property, value]) => `${cssPropertyName(property)}: ${value};`);
+ const easing = String(frame.easing || '').trim();
+ if (easing && easing.toLowerCase() !== 'linear') {
+ declarations.push(`animation-timing-function: ${easing};`);
+ }
+ if (declarations.length === 0) continue;
+ blocks.push(`${offset}% { ${declarations.join(' ')} }`);
+ }
+ if (blocks.length > 0) resolved.set(name, `@keyframes ${name} { ${blocks.join(' ')} }`);
+ }
+ return resolved;
+ }
+
+ // Read CSS that is absent from document.outerHTML. Inline <style> blocks are
+ // already present in the HTML pattern corpus, so limit this walk to linked
+ // stylesheets. Flatten grouping rules so each declaration keeps its selector,
+ // and admit only selector rules that target the live DOM. That prevents
+ // unused utilities from feeding both selector-scoped and page-level checks.
+ // Same-origin CSS and readable CORS sheets participate; browser security
+ // exceptions for cross-origin sheets are expected and skipped.
+ function linkedStylesheetText() {
+ const parts = [];
+ const seen = new Set();
+ const animationNames = new Set();
+ const keyframeCandidates = new Map();
+ const appendRules = (rules, requiresAppliedMatch = false) => {
+ for (const rule of rules) {
+ if (rule.styleSheet) {
+ appendSheet(rule.styleSheet);
+ continue;
+ }
+ const cssText = rule.cssText || '';
+ if (rule.selectorText) {
+ const matches = selectorNodesForLiveDom(document, rule.selectorText);
+ // Only declarations with a resolvable live host enter the corpus.
+ // Unresolvable selectors are uncertain, not evidence that a pattern
+ // rendered, and retaining them would leak unused CSS into findings.
+ if (
+ matches?.length > 0
+ && (!requiresAppliedMatch || styleRuleAppliesToLiveMatches(rule, matches))
+ ) {
+ parts.push(cssText);
+ for (const name of animationNamesDeclaredByRule(rule)) animationNames.add(name);
+ }
+ continue;
+ }
+ let nested = [];
+ let hasNestedRules = false;
+ try {
+ const ruleList = rule.cssRules;
+ hasNestedRules = ruleList != null;
+ nested = Array.from(ruleList || []);
+ } catch {
+ continue;
+ }
+ const keyframesName = keyframesRuleName(rule, cssText);
+ if (keyframesName) {
+ // Keyframes do not merge: when a name is defined more than once, the
+ // later effective definition replaces the earlier one.
+ keyframeCandidates.set(keyframesName, {
+ name: keyframesName,
+ cssText,
+ });
+ continue;
+ }
+ if (hasNestedRules) {
+ if (!conditionalCssRuleIsActive(rule)) continue;
+ appendRules(nested, requiresAppliedMatch || isContainerCssRule(rule));
+ continue;
+ }
+ // Other selector-less leaf at-rules cannot be tied to a rendered node.
+ }
+ };
+ const appendSheet = (sheet) => {
+ if (!sheet || seen.has(sheet)) return;
+ seen.add(sheet);
+ let rules;
+ try { rules = Array.from(sheet.cssRules || sheet.rules || []); }
+ catch { return; }
+ appendRules(rules);
+ };
+ let sheets;
+ try { sheets = Array.from(document.styleSheets || []); }
+ catch { return ''; }
+ for (const sheet of sheets) {
+ const owner = sheet.ownerNode;
+ if (owner?.tagName?.toLowerCase() !== 'link') continue;
+ if (!/\bstylesheet\b/i.test(owner.getAttribute?.('rel') || '')) continue;
+ appendSheet(sheet);
+ }
+ // Motion checks need the effective body of a live animation's keyframes.
+ // Let the browser resolve duplicate names across source order, imports,
+ // conditional groups, and cascade layers, then serialize those computed
+ // frames back into the pattern corpus. Browsers also make container-nested
+ // keyframes globally available, so lexical grouping is not a reliable
+ // activity signal. When the Web Animations API is unavailable, fall back to
+ // the last source-order definition referenced by a retained linked rule.
+ const resolvedKeyframes = resolvedAnimationKeyframes(new Set(keyframeCandidates.keys()));
+ if (resolvedKeyframes) {
+ parts.push(...resolvedKeyframes.values());
+ } else {
+ for (const candidate of keyframeCandidates.values()) {
+ if (!animationNames.has(candidate.name)) continue;
+ parts.push(candidate.cssText);
+ }
+ }
+ return parts.join('\n');
+ }
+
function browserFindingsFromMap(groupMap) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
@@ -1650,18 +2028,16 @@ if (IS_BROWSER) {
// (the CSS ships here, but the pattern never renders — the live DOM is
// ground truth in the browser), and a match under a data-impeccable-ignore
// ancestor is waived. Selector-less findings stay page-level.
- const scopedHtmlFindings = checkHtmlPatterns(docClone.outerHTML).filter(f => {
+ const html = docClone.outerHTML;
+ const corpora = buildHtmlPatternCorpora(html);
+ const linkedCss = linkedStylesheetText();
+ if (linkedCss) corpora.styleText += `\n${linkedCss}`;
+ const scopedHtmlFindings = checkHtmlPatterns(html, corpora).filter(f => {
if (!f.selector) return true;
- const query = String(f.selector).replace(/::?[a-zA-Z-]+(\([^)]*\))?/g, '').trim().replace(/,\s*(?=,|$)/g, '');
- if (!query || /^[,\s]*$/.test(query)) return true;
- let matches;
- try {
- matches = document.querySelectorAll(query);
- } catch {
- return true;
- }
+ const matches = selectorNodesForLiveDom(document, f.selector);
+ if (!matches) return false;
if (matches.length === 0) return false;
- return [...matches].some(el => !scopedIgnoreActive(el, f.id));
+ return matches.some(el => !scopedIgnoreActive(el, f.id));
});
if (scopedHtmlFindings.length > 0) {
const mapped = scopedHtmlFindings.map(f => {
diff --git a/.rovodev/skills/impeccable/scripts/detector/cli/main.mjs b/.rovodev/skills/impeccable/scripts/detector/cli/main.mjs
index 4476d04f1..3451d6c6b 100644
--- a/.rovodev/skills/impeccable/scripts/detector/cli/main.mjs
+++ b/.rovodev/skills/impeccable/scripts/detector/cli/main.mjs
@@ -37,13 +37,30 @@ function fileUrlToLocalPath(url) {
}
}
+const URL_TARGET_RE = /^(?:https?|file):\/\//i;
+
+// Some agent runners hand a shell-ready URL list to Node as one argv value.
+// A browser accepts the spaces as part of one encoded URL, producing a
+// plausible scan attributed to a bogus joined path. Expand only when every
+// whitespace-delimited token is independently a URL, preserving ordinary
+// filesystem paths that contain spaces.
+function expandJoinedUrlTargets(targets) {
+ return targets.flatMap((target) => {
+ if (!/\s/.test(target)) return [target];
+ const parts = target.trim().split(/\s+/).filter(Boolean);
+ return parts.length > 1 && parts.every(part => URL_TARGET_RE.test(part))
+ ? parts
+ : [target];
+ });
+}
+
// Advisory findings are detected but never treated as failures: they list in a
// separate, visually dimmed section, are excluded from the failure count that
// drives the exit code, and carry `"advisory": true` in JSON so consumers can
// filter. Every advisory finding carries the flag (stamped by the registry via
// findings.mjs).
function isAdvisory(finding) {
- return finding && finding.advisory === true;
+ return Boolean(finding && (finding.advisory === true || finding.severity === 'advisory'));
}
function partitionAdvisory(findings) {
@@ -168,6 +185,10 @@ Advisory findings:
counted as failures and never changing the exit code. They stay out of the
failure count so they never block automation. --no-advisory hides them.
+Output streams:
+ Human-readable findings go to stderr so stdout stays available for structured
+ output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.
+
Project config:
Respects .impeccable/config.json and .impeccable/config.local.json detector
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
@@ -185,7 +206,7 @@ Detection modes:
HTML files Static HTML/CSS analysis (default, catches linked CSS)
Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)
URLs Puppeteer full browser rendering (auto-detected;
- http(s):// and file:// URLs)
+ http(s):// and file:// URLs; accessible linked CSS included)
Examples:
impeccable detect src/
@@ -283,7 +304,7 @@ async function detectCli() {
const designSystem = loadDesignSystemForTarget(localPath, { cache: designSystemCache });
return designSystem ? { ...baseScanOptions, designSystem } : baseScanOptions;
};
- const targets = args.filter(a => !a.startsWith('--'));
+ const targets = expandJoinedUrlTargets(args.filter(a => !a.startsWith('--')));
if (helpMode) { printUsage(); process.exit(0); }
@@ -297,13 +318,12 @@ async function detectCli() {
// real cascade, real computed styles, real layout. Callers that want a
// browser-grade scan of a local artifact can pass file:///abs/path.html
// instead of the bare path (which stays on the static engine).
- const urlRe = /^(?:https?|file):\/\//i;
- const urlTargetCount = paths.filter(target => urlRe.test(target)).length;
+ const urlTargetCount = paths.filter(target => URL_TARGET_RE.test(target)).length;
const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
try {
for (const target of paths) {
- if (urlRe.test(target)) {
+ if (URL_TARGET_RE.test(target)) {
// A file:// URL points at a local artifact, so its design system
// resolves from that file's project. A remote http(s) URL has no
// local project — it gets base options (no design system), never
diff --git a/.rovodev/skills/impeccable/scripts/detector/detect-antipatterns-browser.js b/.rovodev/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
index e6899f569..460ffb45b 100644
--- a/.rovodev/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
+++ b/.rovodev/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
@@ -358,7 +358,7 @@ const ANTIPATTERNS = [
// rather than a failure. It fires only on the AI saturation pattern, not on
// ordinary prose. Advisory findings are surfaced separately, never counted
// as failures, and skipped by the design hook unless a project opts in.
- advisory: true,
+ severity: 'advisory',
name: 'Em-dash overuse',
description:
'Em-dash saturation in body copy is an AI cadence tell. Advisory only: humans use em-dashes legitimately, so this fires only on saturation — at least 8 em-dashes (— or --) at a density near one per 500 characters of body text — never on a long article that uses a few. Prefer commas, colons, periods, or parentheses.',
@@ -1961,7 +1961,10 @@ function enclosingCssSelector(cssText, index) {
// `{` belongs to some other selector.
const closeBeforeIndex = cssText.lastIndexOf('}', index);
if (closeBeforeIndex > open) return null;
- const prevClose = Math.max(cssText.lastIndexOf('}', open - 1), cssText.lastIndexOf(';', open - 1));
+ // Ignore delimiters inside comments when locating the previous declaration.
+ // Keeping comment length intact preserves indices into the original source.
+ const beforeOpen = cssText.slice(0, open).replace(/\/\*[\s\S]*?\*\//g, comment => ' '.repeat(comment.length));
+ const prevClose = Math.max(beforeOpen.lastIndexOf('}'), beforeOpen.lastIndexOf(';'));
const raw = cssText.slice(prevClose + 1, open).replace(/\/\*[\s\S]*?\*\//g, '').trim().replace(/\s+/g, ' ');
if (!raw || raw.startsWith('@') || /^\d/.test(raw) || /[{}<]/.test(raw)) return null;
// Keyframe steps: percentage steps fail the digit test above, but `from`
@@ -5293,14 +5296,17 @@ function checkTypography() {
}
if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
+ // Report the actual primary face: the uniquely most-used family. The old
+ // 15% threshold labeled secondary faces as primary (e.g. an 82/18 split).
+ const ranked = [...fontUsage.entries()].sort((a, b) => b[1] - a[1]);
+ const [primary] = ranked;
+ const tied = ranked[1]?.[1] === primary?.[1];
+ if (primary && !tied) {
+ const [font, count] = primary;
const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ if (OVERUSED_FONTS.has(font) && !isBrandFontOnOwnDomain(font)) {
+ findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ }
}
}
@@ -8126,14 +8132,17 @@ if (IS_BROWSER) {
isHidden: isElementHidden(el),
findings: findings.map(f => {
const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
+ const severity = f.severity || ap?.severity || 'warning';
return {
type: f.type || f.id,
category: ap ? ap.category : 'quality',
- severity: f.severity || ap?.severity || 'warning',
+ severity,
// Advisory findings (em-dash overuse, etc.) are surfaced but never
// treated as failures; carry the flag so the overlay/extension can
// render them with the mildest affordance and consumers can filter.
- advisory: (ap && ap.advisory === true) || f.advisory === true,
+ // Per-finding promotions override the registry default, so derive
+ // this strictly from the effective severity.
+ advisory: severity === 'advisory',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
@@ -8175,6 +8184,381 @@ if (IS_BROWSER) {
else groupMap.set(el, [...kept]);
}
+ function pseudoElementHostSelector(selector) {
+ const raw = String(selector || '');
+ const legacyNames = new Set(['before', 'after', 'first-letter', 'first-line']);
+ const isNameChar = char => /[a-zA-Z0-9_-]/.test(char || '');
+ const consumeFunction = (start) => {
+ let depth = 0;
+ let quote = '';
+ for (let i = start; i < raw.length; i += 1) {
+ const char = raw[i];
+ if (char === '\\') {
+ i += 1;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '(') depth += 1;
+ if (char === ')' && --depth === 0) return i + 1;
+ }
+ return raw.length;
+ };
+
+ let output = '';
+ let found = false;
+ for (let i = 0; i < raw.length;) {
+ const char = raw[i];
+ if (char === '\\') {
+ output += raw.slice(i, Math.min(raw.length, i + 2));
+ i += 2;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ const quote = char;
+ const start = i;
+ i += 1;
+ while (i < raw.length) {
+ if (raw[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ const value = raw[i];
+ i += 1;
+ if (value === quote) break;
+ }
+ output += raw.slice(start, i);
+ continue;
+ }
+ if (char !== ':') {
+ output += char;
+ i += 1;
+ continue;
+ }
+
+ let end = i + 1;
+ let isPseudoElement = false;
+ if (raw[end] === ':') {
+ end += 1;
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = end > nameStart;
+ } else {
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = legacyNames.has(raw.slice(nameStart, end).toLowerCase());
+ }
+ if (!isPseudoElement) {
+ output += char;
+ i += 1;
+ continue;
+ }
+ if (raw[end] === '(') end = consumeFunction(end);
+ found = true;
+ if (!output || /[\s>+~,]/.test(output[output.length - 1])) output += '*';
+ i = end;
+ }
+ if (!found) return null;
+ return output.trim().replace(/,\s*(?=,|$)/g, '');
+ }
+
+ function selectorNodesForLiveDom(root, selector) {
+ const raw = String(selector || '').trim();
+ if (!raw) return null;
+ const fallback = pseudoElementHostSelector(raw);
+ if (fallback == null) {
+ // An empty result from a valid full selector is authoritative. In
+ // particular, do not broaden inactive :hover/:focus/:not() rules to
+ // their host element by stripping pseudo-classes.
+ try { return Array.from(root.querySelectorAll(raw)); }
+ catch { return null; }
+ }
+
+ // Resolve pseudo-elements to their originating live elements. An attached
+ // pseudo-element (`.card::before`) belongs to the element before it, while
+ // a hostless pseudo-element after a combinator (`main > ::before`) belongs
+ // to a matching element at that position (`main > *`). Replacing every
+ // pseudo indiscriminately with an empty string leaves the latter as the
+ // invalid selector `main >` and makes absent hosts indistinguishable from
+ // selectors the DOM API cannot parse.
+ if (!fallback || /^[,\s]*$/.test(fallback)) return null;
+ try { return Array.from(root.querySelectorAll(fallback)); }
+ catch { return null; }
+ }
+
+ let containerProbeSequence = 0;
+
+ function isContainerCssRule(rule) {
+ return rule?.constructor?.name === 'CSSContainerRule'
+ || /^\s*@container\b/i.test(rule?.cssText || '');
+ }
+
+ function styleRuleAppliesToLiveMatches(rule, matches) {
+ const style = rule?.style;
+ if (!style || !matches?.length || typeof getComputedStyle !== 'function') return false;
+ const sequence = ++containerProbeSequence;
+ const property = `--impeccable-container-probe-${sequence}-${Math.random().toString(36).slice(2)}`;
+ const value = `impeccable-container-active-${sequence}`;
+ const previousValue = style.getPropertyValue(property);
+ const previousPriority = style.getPropertyPriority(property);
+ try {
+ style.setProperty(property, value, 'important');
+ } catch {
+ return false;
+ }
+
+ const pseudoElements = [...new Set(
+ String(rule.selectorText || '').match(/::[a-zA-Z-]+(?:\([^)]*\))?/g) || [],
+ )];
+ try {
+ return matches.some(el => [null, ...pseudoElements].some(pseudo => {
+ try {
+ const computed = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el);
+ return computed.getPropertyValue(property).trim() === value;
+ } catch {
+ return false;
+ }
+ }));
+ } finally {
+ if (previousValue) style.setProperty(property, previousValue, previousPriority);
+ else style.removeProperty(property);
+ }
+ }
+
+ function conditionalCssRuleIsActive(rule) {
+ const type = Number(rule?.type);
+ const constructorName = rule?.constructor?.name || '';
+ if (constructorName === 'CSSMediaRule' || type === 4) {
+ const condition = rule.conditionText || rule.media?.mediaText || '';
+ if (!condition || typeof window.matchMedia !== 'function') return true;
+ try { return window.matchMedia(condition).matches; }
+ catch { return true; }
+ }
+ if (constructorName === 'CSSSupportsRule' || type === 12) {
+ const condition = rule.conditionText || '';
+ if (!condition || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return true;
+ try { return CSS.supports(condition); }
+ catch { return true; }
+ }
+ return true;
+ }
+
+ function splitCssCommaList(value) {
+ const parts = [];
+ let current = '';
+ let quote = '';
+ let escaped = false;
+ for (const char of String(value || '')) {
+ if (escaped) {
+ current += char;
+ escaped = false;
+ continue;
+ }
+ if (char === '\\') {
+ current += char;
+ escaped = true;
+ continue;
+ }
+ if (quote) {
+ current += char;
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ current += char;
+ continue;
+ }
+ if (char === ',') {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+ return parts;
+ }
+
+ function normalizeAnimationName(value) {
+ const name = String(value || '').trim();
+ if (name.length >= 2 && name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) {
+ return name.slice(1, -1);
+ }
+ return name;
+ }
+
+ function animationNamesDeclaredByRule(rule) {
+ const style = rule?.style;
+ if (!style) return [];
+ let value = '';
+ try {
+ value = style.animationName
+ || style.getPropertyValue?.('animation-name')
+ || style.webkitAnimationName
+ || style.getPropertyValue?.('-webkit-animation-name')
+ || '';
+ } catch {
+ return [];
+ }
+ return splitCssCommaList(value)
+ .map(normalizeAnimationName)
+ .filter(name => name && name.toLowerCase() !== 'none');
+ }
+
+ function keyframesRuleName(rule, cssText) {
+ const constructorName = rule?.constructor?.name || '';
+ const type = Number(rule?.type);
+ const isKeyframes = constructorName === 'CSSKeyframesRule'
+ || constructorName === 'WebKitCSSKeyframesRule'
+ || type === 7
+ || /^\s*@(?:-webkit-)?keyframes\b/i.test(cssText);
+ if (!isKeyframes) return '';
+ const match = String(cssText || '').match(/^\s*@(?:-webkit-)?keyframes\s+([^\s{]+)/i);
+ return normalizeAnimationName(rule?.name || match?.[1] || '');
+ }
+
+ function cssPropertyName(property) {
+ if (property.startsWith('--')) return property;
+ return property.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
+ }
+
+ function resolvedAnimationKeyframes(candidateNames) {
+ if (typeof document.getAnimations !== 'function') return null;
+ let animations;
+ try { animations = document.getAnimations(); }
+ catch { return null; }
+
+ const resolved = new Map();
+ const metadata = new Set(['offset', 'computedOffset', 'easing', 'composite']);
+ for (const animation of animations) {
+ const name = normalizeAnimationName(animation?.animationName || '');
+ if (!name || !candidateNames.has(name) || resolved.has(name)) continue;
+ let frames;
+ try { frames = animation.effect?.getKeyframes?.() || []; }
+ catch { continue; }
+ const blocks = [];
+ for (const frame of frames) {
+ const rawOffset = Number.isFinite(frame.computedOffset) ? frame.computedOffset : frame.offset;
+ if (!Number.isFinite(rawOffset)) continue;
+ const offset = Math.round(rawOffset * 1000000) / 10000;
+ const declarations = Object.entries(frame)
+ .filter(([property, value]) => !metadata.has(property) && value != null && value !== '')
+ .map(([property, value]) => `${cssPropertyName(property)}: ${value};`);
+ const easing = String(frame.easing || '').trim();
+ if (easing && easing.toLowerCase() !== 'linear') {
+ declarations.push(`animation-timing-function: ${easing};`);
+ }
+ if (declarations.length === 0) continue;
+ blocks.push(`${offset}% { ${declarations.join(' ')} }`);
+ }
+ if (blocks.length > 0) resolved.set(name, `@keyframes ${name} { ${blocks.join(' ')} }`);
+ }
+ return resolved;
+ }
+
+ // Read CSS that is absent from document.outerHTML. Inline <style> blocks are
+ // already present in the HTML pattern corpus, so limit this walk to linked
+ // stylesheets. Flatten grouping rules so each declaration keeps its selector,
+ // and admit only selector rules that target the live DOM. That prevents
+ // unused utilities from feeding both selector-scoped and page-level checks.
+ // Same-origin CSS and readable CORS sheets participate; browser security
+ // exceptions for cross-origin sheets are expected and skipped.
+ function linkedStylesheetText() {
+ const parts = [];
+ const seen = new Set();
+ const animationNames = new Set();
+ const keyframeCandidates = new Map();
+ const appendRules = (rules, requiresAppliedMatch = false) => {
+ for (const rule of rules) {
+ if (rule.styleSheet) {
+ appendSheet(rule.styleSheet);
+ continue;
+ }
+ const cssText = rule.cssText || '';
+ if (rule.selectorText) {
+ const matches = selectorNodesForLiveDom(document, rule.selectorText);
+ // Only declarations with a resolvable live host enter the corpus.
+ // Unresolvable selectors are uncertain, not evidence that a pattern
+ // rendered, and retaining them would leak unused CSS into findings.
+ if (
+ matches?.length > 0
+ && (!requiresAppliedMatch || styleRuleAppliesToLiveMatches(rule, matches))
+ ) {
+ parts.push(cssText);
+ for (const name of animationNamesDeclaredByRule(rule)) animationNames.add(name);
+ }
+ continue;
+ }
+ let nested = [];
+ let hasNestedRules = false;
+ try {
+ const ruleList = rule.cssRules;
+ hasNestedRules = ruleList != null;
+ nested = Array.from(ruleList || []);
+ } catch {
+ continue;
+ }
+ const keyframesName = keyframesRuleName(rule, cssText);
+ if (keyframesName) {
+ // Keyframes do not merge: when a name is defined more than once, the
+ // later effective definition replaces the earlier one.
+ keyframeCandidates.set(keyframesName, {
+ name: keyframesName,
+ cssText,
+ });
+ continue;
+ }
+ if (hasNestedRules) {
+ if (!conditionalCssRuleIsActive(rule)) continue;
+ appendRules(nested, requiresAppliedMatch || isContainerCssRule(rule));
+ continue;
+ }
+ // Other selector-less leaf at-rules cannot be tied to a rendered node.
+ }
+ };
+ const appendSheet = (sheet) => {
+ if (!sheet || seen.has(sheet)) return;
+ seen.add(sheet);
+ let rules;
+ try { rules = Array.from(sheet.cssRules || sheet.rules || []); }
+ catch { return; }
+ appendRules(rules);
+ };
+ let sheets;
+ try { sheets = Array.from(document.styleSheets || []); }
+ catch { return ''; }
+ for (const sheet of sheets) {
+ const owner = sheet.ownerNode;
+ if (owner?.tagName?.toLowerCase() !== 'link') continue;
+ if (!/\bstylesheet\b/i.test(owner.getAttribute?.('rel') || '')) continue;
+ appendSheet(sheet);
+ }
+ // Motion checks need the effective body of a live animation's keyframes.
+ // Let the browser resolve duplicate names across source order, imports,
+ // conditional groups, and cascade layers, then serialize those computed
+ // frames back into the pattern corpus. Browsers also make container-nested
+ // keyframes globally available, so lexical grouping is not a reliable
+ // activity signal. When the Web Animations API is unavailable, fall back to
+ // the last source-order definition referenced by a retained linked rule.
+ const resolvedKeyframes = resolvedAnimationKeyframes(new Set(keyframeCandidates.keys()));
+ if (resolvedKeyframes) {
+ parts.push(...resolvedKeyframes.values());
+ } else {
+ for (const candidate of keyframeCandidates.values()) {
+ if (!animationNames.has(candidate.name)) continue;
+ parts.push(candidate.cssText);
+ }
+ }
+ return parts.join('\n');
+ }
+
function browserFindingsFromMap(groupMap) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
@@ -8548,18 +8932,16 @@ if (IS_BROWSER) {
// (the CSS ships here, but the pattern never renders — the live DOM is
// ground truth in the browser), and a match under a data-impeccable-ignore
// ancestor is waived. Selector-less findings stay page-level.
- const scopedHtmlFindings = checkHtmlPatterns(docClone.outerHTML).filter(f => {
+ const html = docClone.outerHTML;
+ const corpora = buildHtmlPatternCorpora(html);
+ const linkedCss = linkedStylesheetText();
+ if (linkedCss) corpora.styleText += `\n${linkedCss}`;
+ const scopedHtmlFindings = checkHtmlPatterns(html, corpora).filter(f => {
if (!f.selector) return true;
- const query = String(f.selector).replace(/::?[a-zA-Z-]+(\([^)]*\))?/g, '').trim().replace(/,\s*(?=,|$)/g, '');
- if (!query || /^[,\s]*$/.test(query)) return true;
- let matches;
- try {
- matches = document.querySelectorAll(query);
- } catch {
- return true;
- }
+ const matches = selectorNodesForLiveDom(document, f.selector);
+ if (!matches) return false;
if (matches.length === 0) return false;
- return [...matches].some(el => !scopedIgnoreActive(el, f.id));
+ return matches.some(el => !scopedIgnoreActive(el, f.id));
});
if (scopedHtmlFindings.length > 0) {
const mapped = scopedHtmlFindings.map(f => {
diff --git a/.rovodev/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs b/.rovodev/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
index f3ff43c84..ac4bd0a7c 100644
--- a/.rovodev/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
+++ b/.rovodev/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
@@ -2,7 +2,7 @@ import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { finding } from '../../findings.mjs';
+import { deriveAdvisoryFlag, finding } from '../../findings.mjs';
import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
import { checkContentHiddenAtRest } from '../../rules/checks.mjs';
@@ -394,7 +394,7 @@ async function detectUrl(rawUrl, options = {}) {
// Per-finding severity promotion (e.g. hero-region pulsing dot)
// overrides the registry default carried by finding().
if (f.severity && f.severity !== item.severity) item.severity = f.severity;
- return item;
+ return deriveAdvisoryFlag(item);
});
}
diff --git a/.rovodev/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs b/.rovodev/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
index 84e6ab1f5..dac6939b0 100644
--- a/.rovodev/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
+++ b/.rovodev/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
@@ -9,7 +9,7 @@ import {
} from '../../design-system.mjs';
import { isFullPage } from '../../shared/page.mjs';
import { applyInlineIgnores } from '../../shared/inline-ignores.mjs';
-import { finding } from '../../findings.mjs';
+import { deriveAdvisoryFlag, finding } from '../../findings.mjs';
import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import {
checkElementBorders,
@@ -257,7 +257,7 @@ async function detectHtml(filePath, options = {}) {
// severity (e.g. a pulsing dot inside a header/nav landmark) that
// overrides the registry default.
if (f.severity) item.severity = f.severity;
- findings.push(item);
+ findings.push(deriveAdvisoryFlag(item));
}
// Text-content analyzers (em-dash overuse, marketing buzzwords,
// numbered section markers, aphoristic cadence) live in the regex
diff --git a/.rovodev/skills/impeccable/scripts/detector/findings.mjs b/.rovodev/skills/impeccable/scripts/detector/findings.mjs
index fa98dd935..ae7e134f9 100644
--- a/.rovodev/skills/impeccable/scripts/detector/findings.mjs
+++ b/.rovodev/skills/impeccable/scripts/detector/findings.mjs
@@ -4,6 +4,12 @@ function getAP(id) {
return getAntipattern(id);
}
+function deriveAdvisoryFlag(item) {
+ if (item.severity === 'advisory') item.advisory = true;
+ else delete item.advisory;
+ return item;
+}
+
function finding(id, filePath, snippet, line = 0) {
const ap = getAP(id);
const base = { antipattern: id, name: ap.name, description: ap.description, severity: ap.severity || 'warning', category: ap.category || null, file: filePath, line, snippet };
@@ -11,8 +17,7 @@ function finding(id, filePath, snippet, line = 0) {
// failures. Carry the flag on the finding so every consumer (CLI, JSON, hook)
// can partition without a registry lookup. Only stamped when true to keep the
// finding shape stable for the vast majority of rules.
- if (ap.advisory === true) base.advisory = true;
- return base;
+ return deriveAdvisoryFlag(base);
}
-export { getAP, finding };
+export { getAP, finding, deriveAdvisoryFlag };
diff --git a/.rovodev/skills/impeccable/scripts/detector/registry/antipatterns.mjs b/.rovodev/skills/impeccable/scripts/detector/registry/antipatterns.mjs
index 945307783..7c692c79a 100644
--- a/.rovodev/skills/impeccable/scripts/detector/registry/antipatterns.mjs
+++ b/.rovodev/skills/impeccable/scripts/detector/registry/antipatterns.mjs
@@ -233,7 +233,7 @@ const ANTIPATTERNS = [
// rather than a failure. It fires only on the AI saturation pattern, not on
// ordinary prose. Advisory findings are surfaced separately, never counted
// as failures, and skipped by the design hook unless a project opts in.
- advisory: true,
+ severity: 'advisory',
name: 'Em-dash overuse',
description:
'Em-dash saturation in body copy is an AI cadence tell. Advisory only: humans use em-dashes legitimately, so this fires only on saturation — at least 8 em-dashes (— or --) at a density near one per 500 characters of body text — never on a long article that uses a few. Prefer commas, colons, periods, or parentheses.',
@@ -588,9 +588,10 @@ function getAntipattern(id) {
// Advisory rules are detected and reported, but never treated as failures:
// the CLI lists them under a separate "Advisory" section, they do not affect
// exit codes or the failure count, and the design hook skips them by default.
-// The set is derived from the registry so a rule only needs `advisory: true`.
+// `severity` is the canonical registry field. The runtime finding serializer
+// derives its `advisory: true` compatibility/output flag from this set.
const ADVISORY_RULE_IDS = new Set(
- ANTIPATTERNS.filter(rule => rule.advisory === true).map(rule => rule.id),
+ ANTIPATTERNS.filter(rule => rule.severity === 'advisory').map(rule => rule.id),
);
function isAdvisoryRule(id) {
diff --git a/.rovodev/skills/impeccable/scripts/detector/rules/checks.mjs b/.rovodev/skills/impeccable/scripts/detector/rules/checks.mjs
index 579e1c12e..a24631ce9 100644
--- a/.rovodev/skills/impeccable/scripts/detector/rules/checks.mjs
+++ b/.rovodev/skills/impeccable/scripts/detector/rules/checks.mjs
@@ -688,7 +688,10 @@ function enclosingCssSelector(cssText, index) {
// `{` belongs to some other selector.
const closeBeforeIndex = cssText.lastIndexOf('}', index);
if (closeBeforeIndex > open) return null;
- const prevClose = Math.max(cssText.lastIndexOf('}', open - 1), cssText.lastIndexOf(';', open - 1));
+ // Ignore delimiters inside comments when locating the previous declaration.
+ // Keeping comment length intact preserves indices into the original source.
+ const beforeOpen = cssText.slice(0, open).replace(/\/\*[\s\S]*?\*\//g, comment => ' '.repeat(comment.length));
+ const prevClose = Math.max(beforeOpen.lastIndexOf('}'), beforeOpen.lastIndexOf(';'));
const raw = cssText.slice(prevClose + 1, open).replace(/\/\*[\s\S]*?\*\//g, '').trim().replace(/\s+/g, ' ');
if (!raw || raw.startsWith('@') || /^\d/.test(raw) || /[{}<]/.test(raw)) return null;
// Keyframe steps: percentage steps fail the digit test above, but `from`
@@ -4020,14 +4023,17 @@ function checkTypography() {
}
if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
+ // Report the actual primary face: the uniquely most-used family. The old
+ // 15% threshold labeled secondary faces as primary (e.g. an 82/18 split).
+ const ranked = [...fontUsage.entries()].sort((a, b) => b[1] - a[1]);
+ const [primary] = ranked;
+ const tied = ranked[1]?.[1] === primary?.[1];
+ if (primary && !tied) {
+ const [font, count] = primary;
const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ if (OVERUSED_FONTS.has(font) && !isBrandFontOnOwnDomain(font)) {
+ findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ }
}
}
diff --git a/.rovodev/skills/impeccable/scripts/hook-lib.mjs b/.rovodev/skills/impeccable/scripts/hook-lib.mjs
index 767fe65a6..6d8c3db81 100644
--- a/.rovodev/skills/impeccable/scripts/hook-lib.mjs
+++ b/.rovodev/skills/impeccable/scripts/hook-lib.mjs
@@ -138,17 +138,20 @@ export const IMMEDIATE_TIER_RULES = new Set([
// the agent is never nagged about a taste call a human might make on purpose.
// A project opts back in with `.impeccable/config.json`:
// { "detector": { "advisoryRules": "include" } }
-// This set is the hook's own copy of the registry's `advisory: true` rules,
-// mirroring how IMMEDIATE_TIER_RULES lists rule ids inline so the hook stays
-// self-contained and testable without loading the detector. Keep it in sync
-// with the registry (cli/engine/registry/antipatterns.mjs).
+// This legacy id fallback keeps older detector findings recognizable when they
+// carry neither the current runtime flag nor the canonical advisory severity.
+// Current findings are classified by their serialized metadata below.
export const ADVISORY_RULES = new Set([
'em-dash-overuse',
]);
export function isAdvisoryFinding(finding) {
const id = finding && normalizeIgnoreRule(finding.antipattern);
- return Boolean(id && (ADVISORY_RULES.has(id) || finding.advisory === true));
+ return Boolean(id && (
+ ADVISORY_RULES.has(id)
+ || finding.advisory === true
+ || finding.severity === 'advisory'
+ ));
}
export const DEFAULT_CONFIG = Object.freeze({
diff --git a/.trae-cn/skills/impeccable/scripts/detector/browser/injected/index.mjs b/.trae-cn/skills/impeccable/scripts/detector/browser/injected/index.mjs
index febf7f297..76fc558e5 100644
--- a/.trae-cn/skills/impeccable/scripts/detector/browser/injected/index.mjs
+++ b/.trae-cn/skills/impeccable/scripts/detector/browser/injected/index.mjs
@@ -1228,14 +1228,17 @@ if (IS_BROWSER) {
isHidden: isElementHidden(el),
findings: findings.map(f => {
const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
+ const severity = f.severity || ap?.severity || 'warning';
return {
type: f.type || f.id,
category: ap ? ap.category : 'quality',
- severity: f.severity || ap?.severity || 'warning',
+ severity,
// Advisory findings (em-dash overuse, etc.) are surfaced but never
// treated as failures; carry the flag so the overlay/extension can
// render them with the mildest affordance and consumers can filter.
- advisory: (ap && ap.advisory === true) || f.advisory === true,
+ // Per-finding promotions override the registry default, so derive
+ // this strictly from the effective severity.
+ advisory: severity === 'advisory',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
@@ -1277,6 +1280,381 @@ if (IS_BROWSER) {
else groupMap.set(el, [...kept]);
}
+ function pseudoElementHostSelector(selector) {
+ const raw = String(selector || '');
+ const legacyNames = new Set(['before', 'after', 'first-letter', 'first-line']);
+ const isNameChar = char => /[a-zA-Z0-9_-]/.test(char || '');
+ const consumeFunction = (start) => {
+ let depth = 0;
+ let quote = '';
+ for (let i = start; i < raw.length; i += 1) {
+ const char = raw[i];
+ if (char === '\\') {
+ i += 1;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '(') depth += 1;
+ if (char === ')' && --depth === 0) return i + 1;
+ }
+ return raw.length;
+ };
+
+ let output = '';
+ let found = false;
+ for (let i = 0; i < raw.length;) {
+ const char = raw[i];
+ if (char === '\\') {
+ output += raw.slice(i, Math.min(raw.length, i + 2));
+ i += 2;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ const quote = char;
+ const start = i;
+ i += 1;
+ while (i < raw.length) {
+ if (raw[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ const value = raw[i];
+ i += 1;
+ if (value === quote) break;
+ }
+ output += raw.slice(start, i);
+ continue;
+ }
+ if (char !== ':') {
+ output += char;
+ i += 1;
+ continue;
+ }
+
+ let end = i + 1;
+ let isPseudoElement = false;
+ if (raw[end] === ':') {
+ end += 1;
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = end > nameStart;
+ } else {
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = legacyNames.has(raw.slice(nameStart, end).toLowerCase());
+ }
+ if (!isPseudoElement) {
+ output += char;
+ i += 1;
+ continue;
+ }
+ if (raw[end] === '(') end = consumeFunction(end);
+ found = true;
+ if (!output || /[\s>+~,]/.test(output[output.length - 1])) output += '*';
+ i = end;
+ }
+ if (!found) return null;
+ return output.trim().replace(/,\s*(?=,|$)/g, '');
+ }
+
+ function selectorNodesForLiveDom(root, selector) {
+ const raw = String(selector || '').trim();
+ if (!raw) return null;
+ const fallback = pseudoElementHostSelector(raw);
+ if (fallback == null) {
+ // An empty result from a valid full selector is authoritative. In
+ // particular, do not broaden inactive :hover/:focus/:not() rules to
+ // their host element by stripping pseudo-classes.
+ try { return Array.from(root.querySelectorAll(raw)); }
+ catch { return null; }
+ }
+
+ // Resolve pseudo-elements to their originating live elements. An attached
+ // pseudo-element (`.card::before`) belongs to the element before it, while
+ // a hostless pseudo-element after a combinator (`main > ::before`) belongs
+ // to a matching element at that position (`main > *`). Replacing every
+ // pseudo indiscriminately with an empty string leaves the latter as the
+ // invalid selector `main >` and makes absent hosts indistinguishable from
+ // selectors the DOM API cannot parse.
+ if (!fallback || /^[,\s]*$/.test(fallback)) return null;
+ try { return Array.from(root.querySelectorAll(fallback)); }
+ catch { return null; }
+ }
+
+ let containerProbeSequence = 0;
+
+ function isContainerCssRule(rule) {
+ return rule?.constructor?.name === 'CSSContainerRule'
+ || /^\s*@container\b/i.test(rule?.cssText || '');
+ }
+
+ function styleRuleAppliesToLiveMatches(rule, matches) {
+ const style = rule?.style;
+ if (!style || !matches?.length || typeof getComputedStyle !== 'function') return false;
+ const sequence = ++containerProbeSequence;
+ const property = `--impeccable-container-probe-${sequence}-${Math.random().toString(36).slice(2)}`;
+ const value = `impeccable-container-active-${sequence}`;
+ const previousValue = style.getPropertyValue(property);
+ const previousPriority = style.getPropertyPriority(property);
+ try {
+ style.setProperty(property, value, 'important');
+ } catch {
+ return false;
+ }
+
+ const pseudoElements = [...new Set(
+ String(rule.selectorText || '').match(/::[a-zA-Z-]+(?:\([^)]*\))?/g) || [],
+ )];
+ try {
+ return matches.some(el => [null, ...pseudoElements].some(pseudo => {
+ try {
+ const computed = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el);
+ return computed.getPropertyValue(property).trim() === value;
+ } catch {
+ return false;
+ }
+ }));
+ } finally {
+ if (previousValue) style.setProperty(property, previousValue, previousPriority);
+ else style.removeProperty(property);
+ }
+ }
+
+ function conditionalCssRuleIsActive(rule) {
+ const type = Number(rule?.type);
+ const constructorName = rule?.constructor?.name || '';
+ if (constructorName === 'CSSMediaRule' || type === 4) {
+ const condition = rule.conditionText || rule.media?.mediaText || '';
+ if (!condition || typeof window.matchMedia !== 'function') return true;
+ try { return window.matchMedia(condition).matches; }
+ catch { return true; }
+ }
+ if (constructorName === 'CSSSupportsRule' || type === 12) {
+ const condition = rule.conditionText || '';
+ if (!condition || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return true;
+ try { return CSS.supports(condition); }
+ catch { return true; }
+ }
+ return true;
+ }
+
+ function splitCssCommaList(value) {
+ const parts = [];
+ let current = '';
+ let quote = '';
+ let escaped = false;
+ for (const char of String(value || '')) {
+ if (escaped) {
+ current += char;
+ escaped = false;
+ continue;
+ }
+ if (char === '\\') {
+ current += char;
+ escaped = true;
+ continue;
+ }
+ if (quote) {
+ current += char;
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ current += char;
+ continue;
+ }
+ if (char === ',') {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+ return parts;
+ }
+
+ function normalizeAnimationName(value) {
+ const name = String(value || '').trim();
+ if (name.length >= 2 && name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) {
+ return name.slice(1, -1);
+ }
+ return name;
+ }
+
+ function animationNamesDeclaredByRule(rule) {
+ const style = rule?.style;
+ if (!style) return [];
+ let value = '';
+ try {
+ value = style.animationName
+ || style.getPropertyValue?.('animation-name')
+ || style.webkitAnimationName
+ || style.getPropertyValue?.('-webkit-animation-name')
+ || '';
+ } catch {
+ return [];
+ }
+ return splitCssCommaList(value)
+ .map(normalizeAnimationName)
+ .filter(name => name && name.toLowerCase() !== 'none');
+ }
+
+ function keyframesRuleName(rule, cssText) {
+ const constructorName = rule?.constructor?.name || '';
+ const type = Number(rule?.type);
+ const isKeyframes = constructorName === 'CSSKeyframesRule'
+ || constructorName === 'WebKitCSSKeyframesRule'
+ || type === 7
+ || /^\s*@(?:-webkit-)?keyframes\b/i.test(cssText);
+ if (!isKeyframes) return '';
+ const match = String(cssText || '').match(/^\s*@(?:-webkit-)?keyframes\s+([^\s{]+)/i);
+ return normalizeAnimationName(rule?.name || match?.[1] || '');
+ }
+
+ function cssPropertyName(property) {
+ if (property.startsWith('--')) return property;
+ return property.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
+ }
+
+ function resolvedAnimationKeyframes(candidateNames) {
+ if (typeof document.getAnimations !== 'function') return null;
+ let animations;
+ try { animations = document.getAnimations(); }
+ catch { return null; }
+
+ const resolved = new Map();
+ const metadata = new Set(['offset', 'computedOffset', 'easing', 'composite']);
+ for (const animation of animations) {
+ const name = normalizeAnimationName(animation?.animationName || '');
+ if (!name || !candidateNames.has(name) || resolved.has(name)) continue;
+ let frames;
+ try { frames = animation.effect?.getKeyframes?.() || []; }
+ catch { continue; }
+ const blocks = [];
+ for (const frame of frames) {
+ const rawOffset = Number.isFinite(frame.computedOffset) ? frame.computedOffset : frame.offset;
+ if (!Number.isFinite(rawOffset)) continue;
+ const offset = Math.round(rawOffset * 1000000) / 10000;
+ const declarations = Object.entries(frame)
+ .filter(([property, value]) => !metadata.has(property) && value != null && value !== '')
+ .map(([property, value]) => `${cssPropertyName(property)}: ${value};`);
+ const easing = String(frame.easing || '').trim();
+ if (easing && easing.toLowerCase() !== 'linear') {
+ declarations.push(`animation-timing-function: ${easing};`);
+ }
+ if (declarations.length === 0) continue;
+ blocks.push(`${offset}% { ${declarations.join(' ')} }`);
+ }
+ if (blocks.length > 0) resolved.set(name, `@keyframes ${name} { ${blocks.join(' ')} }`);
+ }
+ return resolved;
+ }
+
+ // Read CSS that is absent from document.outerHTML. Inline <style> blocks are
+ // already present in the HTML pattern corpus, so limit this walk to linked
+ // stylesheets. Flatten grouping rules so each declaration keeps its selector,
+ // and admit only selector rules that target the live DOM. That prevents
+ // unused utilities from feeding both selector-scoped and page-level checks.
+ // Same-origin CSS and readable CORS sheets participate; browser security
+ // exceptions for cross-origin sheets are expected and skipped.
+ function linkedStylesheetText() {
+ const parts = [];
+ const seen = new Set();
+ const animationNames = new Set();
+ const keyframeCandidates = new Map();
+ const appendRules = (rules, requiresAppliedMatch = false) => {
+ for (const rule of rules) {
+ if (rule.styleSheet) {
+ appendSheet(rule.styleSheet);
+ continue;
+ }
+ const cssText = rule.cssText || '';
+ if (rule.selectorText) {
+ const matches = selectorNodesForLiveDom(document, rule.selectorText);
+ // Only declarations with a resolvable live host enter the corpus.
+ // Unresolvable selectors are uncertain, not evidence that a pattern
+ // rendered, and retaining them would leak unused CSS into findings.
+ if (
+ matches?.length > 0
+ && (!requiresAppliedMatch || styleRuleAppliesToLiveMatches(rule, matches))
+ ) {
+ parts.push(cssText);
+ for (const name of animationNamesDeclaredByRule(rule)) animationNames.add(name);
+ }
+ continue;
+ }
+ let nested = [];
+ let hasNestedRules = false;
+ try {
+ const ruleList = rule.cssRules;
+ hasNestedRules = ruleList != null;
+ nested = Array.from(ruleList || []);
+ } catch {
+ continue;
+ }
+ const keyframesName = keyframesRuleName(rule, cssText);
+ if (keyframesName) {
+ // Keyframes do not merge: when a name is defined more than once, the
+ // later effective definition replaces the earlier one.
+ keyframeCandidates.set(keyframesName, {
+ name: keyframesName,
+ cssText,
+ });
+ continue;
+ }
+ if (hasNestedRules) {
+ if (!conditionalCssRuleIsActive(rule)) continue;
+ appendRules(nested, requiresAppliedMatch || isContainerCssRule(rule));
+ continue;
+ }
+ // Other selector-less leaf at-rules cannot be tied to a rendered node.
+ }
+ };
+ const appendSheet = (sheet) => {
+ if (!sheet || seen.has(sheet)) return;
+ seen.add(sheet);
+ let rules;
+ try { rules = Array.from(sheet.cssRules || sheet.rules || []); }
+ catch { return; }
+ appendRules(rules);
+ };
+ let sheets;
+ try { sheets = Array.from(document.styleSheets || []); }
+ catch { return ''; }
+ for (const sheet of sheets) {
+ const owner = sheet.ownerNode;
+ if (owner?.tagName?.toLowerCase() !== 'link') continue;
+ if (!/\bstylesheet\b/i.test(owner.getAttribute?.('rel') || '')) continue;
+ appendSheet(sheet);
+ }
+ // Motion checks need the effective body of a live animation's keyframes.
+ // Let the browser resolve duplicate names across source order, imports,
+ // conditional groups, and cascade layers, then serialize those computed
+ // frames back into the pattern corpus. Browsers also make container-nested
+ // keyframes globally available, so lexical grouping is not a reliable
+ // activity signal. When the Web Animations API is unavailable, fall back to
+ // the last source-order definition referenced by a retained linked rule.
+ const resolvedKeyframes = resolvedAnimationKeyframes(new Set(keyframeCandidates.keys()));
+ if (resolvedKeyframes) {
+ parts.push(...resolvedKeyframes.values());
+ } else {
+ for (const candidate of keyframeCandidates.values()) {
+ if (!animationNames.has(candidate.name)) continue;
+ parts.push(candidate.cssText);
+ }
+ }
+ return parts.join('\n');
+ }
+
function browserFindingsFromMap(groupMap) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
@@ -1650,18 +2028,16 @@ if (IS_BROWSER) {
// (the CSS ships here, but the pattern never renders — the live DOM is
// ground truth in the browser), and a match under a data-impeccable-ignore
// ancestor is waived. Selector-less findings stay page-level.
- const scopedHtmlFindings = checkHtmlPatterns(docClone.outerHTML).filter(f => {
+ const html = docClone.outerHTML;
+ const corpora = buildHtmlPatternCorpora(html);
+ const linkedCss = linkedStylesheetText();
+ if (linkedCss) corpora.styleText += `\n${linkedCss}`;
+ const scopedHtmlFindings = checkHtmlPatterns(html, corpora).filter(f => {
if (!f.selector) return true;
- const query = String(f.selector).replace(/::?[a-zA-Z-]+(\([^)]*\))?/g, '').trim().replace(/,\s*(?=,|$)/g, '');
- if (!query || /^[,\s]*$/.test(query)) return true;
- let matches;
- try {
- matches = document.querySelectorAll(query);
- } catch {
- return true;
- }
+ const matches = selectorNodesForLiveDom(document, f.selector);
+ if (!matches) return false;
if (matches.length === 0) return false;
- return [...matches].some(el => !scopedIgnoreActive(el, f.id));
+ return matches.some(el => !scopedIgnoreActive(el, f.id));
});
if (scopedHtmlFindings.length > 0) {
const mapped = scopedHtmlFindings.map(f => {
diff --git a/.trae-cn/skills/impeccable/scripts/detector/cli/main.mjs b/.trae-cn/skills/impeccable/scripts/detector/cli/main.mjs
index 4476d04f1..3451d6c6b 100644
--- a/.trae-cn/skills/impeccable/scripts/detector/cli/main.mjs
+++ b/.trae-cn/skills/impeccable/scripts/detector/cli/main.mjs
@@ -37,13 +37,30 @@ function fileUrlToLocalPath(url) {
}
}
+const URL_TARGET_RE = /^(?:https?|file):\/\//i;
+
+// Some agent runners hand a shell-ready URL list to Node as one argv value.
+// A browser accepts the spaces as part of one encoded URL, producing a
+// plausible scan attributed to a bogus joined path. Expand only when every
+// whitespace-delimited token is independently a URL, preserving ordinary
+// filesystem paths that contain spaces.
+function expandJoinedUrlTargets(targets) {
+ return targets.flatMap((target) => {
+ if (!/\s/.test(target)) return [target];
+ const parts = target.trim().split(/\s+/).filter(Boolean);
+ return parts.length > 1 && parts.every(part => URL_TARGET_RE.test(part))
+ ? parts
+ : [target];
+ });
+}
+
// Advisory findings are detected but never treated as failures: they list in a
// separate, visually dimmed section, are excluded from the failure count that
// drives the exit code, and carry `"advisory": true` in JSON so consumers can
// filter. Every advisory finding carries the flag (stamped by the registry via
// findings.mjs).
function isAdvisory(finding) {
- return finding && finding.advisory === true;
+ return Boolean(finding && (finding.advisory === true || finding.severity === 'advisory'));
}
function partitionAdvisory(findings) {
@@ -168,6 +185,10 @@ Advisory findings:
counted as failures and never changing the exit code. They stay out of the
failure count so they never block automation. --no-advisory hides them.
+Output streams:
+ Human-readable findings go to stderr so stdout stays available for structured
+ output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.
+
Project config:
Respects .impeccable/config.json and .impeccable/config.local.json detector
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
@@ -185,7 +206,7 @@ Detection modes:
HTML files Static HTML/CSS analysis (default, catches linked CSS)
Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)
URLs Puppeteer full browser rendering (auto-detected;
- http(s):// and file:// URLs)
+ http(s):// and file:// URLs; accessible linked CSS included)
Examples:
impeccable detect src/
@@ -283,7 +304,7 @@ async function detectCli() {
const designSystem = loadDesignSystemForTarget(localPath, { cache: designSystemCache });
return designSystem ? { ...baseScanOptions, designSystem } : baseScanOptions;
};
- const targets = args.filter(a => !a.startsWith('--'));
+ const targets = expandJoinedUrlTargets(args.filter(a => !a.startsWith('--')));
if (helpMode) { printUsage(); process.exit(0); }
@@ -297,13 +318,12 @@ async function detectCli() {
// real cascade, real computed styles, real layout. Callers that want a
// browser-grade scan of a local artifact can pass file:///abs/path.html
// instead of the bare path (which stays on the static engine).
- const urlRe = /^(?:https?|file):\/\//i;
- const urlTargetCount = paths.filter(target => urlRe.test(target)).length;
+ const urlTargetCount = paths.filter(target => URL_TARGET_RE.test(target)).length;
const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
try {
for (const target of paths) {
- if (urlRe.test(target)) {
+ if (URL_TARGET_RE.test(target)) {
// A file:// URL points at a local artifact, so its design system
// resolves from that file's project. A remote http(s) URL has no
// local project — it gets base options (no design system), never
diff --git a/.trae-cn/skills/impeccable/scripts/detector/detect-antipatterns-browser.js b/.trae-cn/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
index e6899f569..460ffb45b 100644
--- a/.trae-cn/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
+++ b/.trae-cn/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
@@ -358,7 +358,7 @@ const ANTIPATTERNS = [
// rather than a failure. It fires only on the AI saturation pattern, not on
// ordinary prose. Advisory findings are surfaced separately, never counted
// as failures, and skipped by the design hook unless a project opts in.
- advisory: true,
+ severity: 'advisory',
name: 'Em-dash overuse',
description:
'Em-dash saturation in body copy is an AI cadence tell. Advisory only: humans use em-dashes legitimately, so this fires only on saturation — at least 8 em-dashes (— or --) at a density near one per 500 characters of body text — never on a long article that uses a few. Prefer commas, colons, periods, or parentheses.',
@@ -1961,7 +1961,10 @@ function enclosingCssSelector(cssText, index) {
// `{` belongs to some other selector.
const closeBeforeIndex = cssText.lastIndexOf('}', index);
if (closeBeforeIndex > open) return null;
- const prevClose = Math.max(cssText.lastIndexOf('}', open - 1), cssText.lastIndexOf(';', open - 1));
+ // Ignore delimiters inside comments when locating the previous declaration.
+ // Keeping comment length intact preserves indices into the original source.
+ const beforeOpen = cssText.slice(0, open).replace(/\/\*[\s\S]*?\*\//g, comment => ' '.repeat(comment.length));
+ const prevClose = Math.max(beforeOpen.lastIndexOf('}'), beforeOpen.lastIndexOf(';'));
const raw = cssText.slice(prevClose + 1, open).replace(/\/\*[\s\S]*?\*\//g, '').trim().replace(/\s+/g, ' ');
if (!raw || raw.startsWith('@') || /^\d/.test(raw) || /[{}<]/.test(raw)) return null;
// Keyframe steps: percentage steps fail the digit test above, but `from`
@@ -5293,14 +5296,17 @@ function checkTypography() {
}
if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
+ // Report the actual primary face: the uniquely most-used family. The old
+ // 15% threshold labeled secondary faces as primary (e.g. an 82/18 split).
+ const ranked = [...fontUsage.entries()].sort((a, b) => b[1] - a[1]);
+ const [primary] = ranked;
+ const tied = ranked[1]?.[1] === primary?.[1];
+ if (primary && !tied) {
+ const [font, count] = primary;
const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ if (OVERUSED_FONTS.has(font) && !isBrandFontOnOwnDomain(font)) {
+ findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ }
}
}
@@ -8126,14 +8132,17 @@ if (IS_BROWSER) {
isHidden: isElementHidden(el),
findings: findings.map(f => {
const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
+ const severity = f.severity || ap?.severity || 'warning';
return {
type: f.type || f.id,
category: ap ? ap.category : 'quality',
- severity: f.severity || ap?.severity || 'warning',
+ severity,
// Advisory findings (em-dash overuse, etc.) are surfaced but never
// treated as failures; carry the flag so the overlay/extension can
// render them with the mildest affordance and consumers can filter.
- advisory: (ap && ap.advisory === true) || f.advisory === true,
+ // Per-finding promotions override the registry default, so derive
+ // this strictly from the effective severity.
+ advisory: severity === 'advisory',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
@@ -8175,6 +8184,381 @@ if (IS_BROWSER) {
else groupMap.set(el, [...kept]);
}
+ function pseudoElementHostSelector(selector) {
+ const raw = String(selector || '');
+ const legacyNames = new Set(['before', 'after', 'first-letter', 'first-line']);
+ const isNameChar = char => /[a-zA-Z0-9_-]/.test(char || '');
+ const consumeFunction = (start) => {
+ let depth = 0;
+ let quote = '';
+ for (let i = start; i < raw.length; i += 1) {
+ const char = raw[i];
+ if (char === '\\') {
+ i += 1;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '(') depth += 1;
+ if (char === ')' && --depth === 0) return i + 1;
+ }
+ return raw.length;
+ };
+
+ let output = '';
+ let found = false;
+ for (let i = 0; i < raw.length;) {
+ const char = raw[i];
+ if (char === '\\') {
+ output += raw.slice(i, Math.min(raw.length, i + 2));
+ i += 2;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ const quote = char;
+ const start = i;
+ i += 1;
+ while (i < raw.length) {
+ if (raw[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ const value = raw[i];
+ i += 1;
+ if (value === quote) break;
+ }
+ output += raw.slice(start, i);
+ continue;
+ }
+ if (char !== ':') {
+ output += char;
+ i += 1;
+ continue;
+ }
+
+ let end = i + 1;
+ let isPseudoElement = false;
+ if (raw[end] === ':') {
+ end += 1;
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = end > nameStart;
+ } else {
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = legacyNames.has(raw.slice(nameStart, end).toLowerCase());
+ }
+ if (!isPseudoElement) {
+ output += char;
+ i += 1;
+ continue;
+ }
+ if (raw[end] === '(') end = consumeFunction(end);
+ found = true;
+ if (!output || /[\s>+~,]/.test(output[output.length - 1])) output += '*';
+ i = end;
+ }
+ if (!found) return null;
+ return output.trim().replace(/,\s*(?=,|$)/g, '');
+ }
+
+ function selectorNodesForLiveDom(root, selector) {
+ const raw = String(selector || '').trim();
+ if (!raw) return null;
+ const fallback = pseudoElementHostSelector(raw);
+ if (fallback == null) {
+ // An empty result from a valid full selector is authoritative. In
+ // particular, do not broaden inactive :hover/:focus/:not() rules to
+ // their host element by stripping pseudo-classes.
+ try { return Array.from(root.querySelectorAll(raw)); }
+ catch { return null; }
+ }
+
+ // Resolve pseudo-elements to their originating live elements. An attached
+ // pseudo-element (`.card::before`) belongs to the element before it, while
+ // a hostless pseudo-element after a combinator (`main > ::before`) belongs
+ // to a matching element at that position (`main > *`). Replacing every
+ // pseudo indiscriminately with an empty string leaves the latter as the
+ // invalid selector `main >` and makes absent hosts indistinguishable from
+ // selectors the DOM API cannot parse.
+ if (!fallback || /^[,\s]*$/.test(fallback)) return null;
+ try { return Array.from(root.querySelectorAll(fallback)); }
+ catch { return null; }
+ }
+
+ let containerProbeSequence = 0;
+
+ function isContainerCssRule(rule) {
+ return rule?.constructor?.name === 'CSSContainerRule'
+ || /^\s*@container\b/i.test(rule?.cssText || '');
+ }
+
+ function styleRuleAppliesToLiveMatches(rule, matches) {
+ const style = rule?.style;
+ if (!style || !matches?.length || typeof getComputedStyle !== 'function') return false;
+ const sequence = ++containerProbeSequence;
+ const property = `--impeccable-container-probe-${sequence}-${Math.random().toString(36).slice(2)}`;
+ const value = `impeccable-container-active-${sequence}`;
+ const previousValue = style.getPropertyValue(property);
+ const previousPriority = style.getPropertyPriority(property);
+ try {
+ style.setProperty(property, value, 'important');
+ } catch {
+ return false;
+ }
+
+ const pseudoElements = [...new Set(
+ String(rule.selectorText || '').match(/::[a-zA-Z-]+(?:\([^)]*\))?/g) || [],
+ )];
+ try {
+ return matches.some(el => [null, ...pseudoElements].some(pseudo => {
+ try {
+ const computed = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el);
+ return computed.getPropertyValue(property).trim() === value;
+ } catch {
+ return false;
+ }
+ }));
+ } finally {
+ if (previousValue) style.setProperty(property, previousValue, previousPriority);
+ else style.removeProperty(property);
+ }
+ }
+
+ function conditionalCssRuleIsActive(rule) {
+ const type = Number(rule?.type);
+ const constructorName = rule?.constructor?.name || '';
+ if (constructorName === 'CSSMediaRule' || type === 4) {
+ const condition = rule.conditionText || rule.media?.mediaText || '';
+ if (!condition || typeof window.matchMedia !== 'function') return true;
+ try { return window.matchMedia(condition).matches; }
+ catch { return true; }
+ }
+ if (constructorName === 'CSSSupportsRule' || type === 12) {
+ const condition = rule.conditionText || '';
+ if (!condition || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return true;
+ try { return CSS.supports(condition); }
+ catch { return true; }
+ }
+ return true;
+ }
+
+ function splitCssCommaList(value) {
+ const parts = [];
+ let current = '';
+ let quote = '';
+ let escaped = false;
+ for (const char of String(value || '')) {
+ if (escaped) {
+ current += char;
+ escaped = false;
+ continue;
+ }
+ if (char === '\\') {
+ current += char;
+ escaped = true;
+ continue;
+ }
+ if (quote) {
+ current += char;
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ current += char;
+ continue;
+ }
+ if (char === ',') {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+ return parts;
+ }
+
+ function normalizeAnimationName(value) {
+ const name = String(value || '').trim();
+ if (name.length >= 2 && name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) {
+ return name.slice(1, -1);
+ }
+ return name;
+ }
+
+ function animationNamesDeclaredByRule(rule) {
+ const style = rule?.style;
+ if (!style) return [];
+ let value = '';
+ try {
+ value = style.animationName
+ || style.getPropertyValue?.('animation-name')
+ || style.webkitAnimationName
+ || style.getPropertyValue?.('-webkit-animation-name')
+ || '';
+ } catch {
+ return [];
+ }
+ return splitCssCommaList(value)
+ .map(normalizeAnimationName)
+ .filter(name => name && name.toLowerCase() !== 'none');
+ }
+
+ function keyframesRuleName(rule, cssText) {
+ const constructorName = rule?.constructor?.name || '';
+ const type = Number(rule?.type);
+ const isKeyframes = constructorName === 'CSSKeyframesRule'
+ || constructorName === 'WebKitCSSKeyframesRule'
+ || type === 7
+ || /^\s*@(?:-webkit-)?keyframes\b/i.test(cssText);
+ if (!isKeyframes) return '';
+ const match = String(cssText || '').match(/^\s*@(?:-webkit-)?keyframes\s+([^\s{]+)/i);
+ return normalizeAnimationName(rule?.name || match?.[1] || '');
+ }
+
+ function cssPropertyName(property) {
+ if (property.startsWith('--')) return property;
+ return property.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
+ }
+
+ function resolvedAnimationKeyframes(candidateNames) {
+ if (typeof document.getAnimations !== 'function') return null;
+ let animations;
+ try { animations = document.getAnimations(); }
+ catch { return null; }
+
+ const resolved = new Map();
+ const metadata = new Set(['offset', 'computedOffset', 'easing', 'composite']);
+ for (const animation of animations) {
+ const name = normalizeAnimationName(animation?.animationName || '');
+ if (!name || !candidateNames.has(name) || resolved.has(name)) continue;
+ let frames;
+ try { frames = animation.effect?.getKeyframes?.() || []; }
+ catch { continue; }
+ const blocks = [];
+ for (const frame of frames) {
+ const rawOffset = Number.isFinite(frame.computedOffset) ? frame.computedOffset : frame.offset;
+ if (!Number.isFinite(rawOffset)) continue;
+ const offset = Math.round(rawOffset * 1000000) / 10000;
+ const declarations = Object.entries(frame)
+ .filter(([property, value]) => !metadata.has(property) && value != null && value !== '')
+ .map(([property, value]) => `${cssPropertyName(property)}: ${value};`);
+ const easing = String(frame.easing || '').trim();
+ if (easing && easing.toLowerCase() !== 'linear') {
+ declarations.push(`animation-timing-function: ${easing};`);
+ }
+ if (declarations.length === 0) continue;
+ blocks.push(`${offset}% { ${declarations.join(' ')} }`);
+ }
+ if (blocks.length > 0) resolved.set(name, `@keyframes ${name} { ${blocks.join(' ')} }`);
+ }
+ return resolved;
+ }
+
+ // Read CSS that is absent from document.outerHTML. Inline <style> blocks are
+ // already present in the HTML pattern corpus, so limit this walk to linked
+ // stylesheets. Flatten grouping rules so each declaration keeps its selector,
+ // and admit only selector rules that target the live DOM. That prevents
+ // unused utilities from feeding both selector-scoped and page-level checks.
+ // Same-origin CSS and readable CORS sheets participate; browser security
+ // exceptions for cross-origin sheets are expected and skipped.
+ function linkedStylesheetText() {
+ const parts = [];
+ const seen = new Set();
+ const animationNames = new Set();
+ const keyframeCandidates = new Map();
+ const appendRules = (rules, requiresAppliedMatch = false) => {
+ for (const rule of rules) {
+ if (rule.styleSheet) {
+ appendSheet(rule.styleSheet);
+ continue;
+ }
+ const cssText = rule.cssText || '';
+ if (rule.selectorText) {
+ const matches = selectorNodesForLiveDom(document, rule.selectorText);
+ // Only declarations with a resolvable live host enter the corpus.
+ // Unresolvable selectors are uncertain, not evidence that a pattern
+ // rendered, and retaining them would leak unused CSS into findings.
+ if (
+ matches?.length > 0
+ && (!requiresAppliedMatch || styleRuleAppliesToLiveMatches(rule, matches))
+ ) {
+ parts.push(cssText);
+ for (const name of animationNamesDeclaredByRule(rule)) animationNames.add(name);
+ }
+ continue;
+ }
+ let nested = [];
+ let hasNestedRules = false;
+ try {
+ const ruleList = rule.cssRules;
+ hasNestedRules = ruleList != null;
+ nested = Array.from(ruleList || []);
+ } catch {
+ continue;
+ }
+ const keyframesName = keyframesRuleName(rule, cssText);
+ if (keyframesName) {
+ // Keyframes do not merge: when a name is defined more than once, the
+ // later effective definition replaces the earlier one.
+ keyframeCandidates.set(keyframesName, {
+ name: keyframesName,
+ cssText,
+ });
+ continue;
+ }
+ if (hasNestedRules) {
+ if (!conditionalCssRuleIsActive(rule)) continue;
+ appendRules(nested, requiresAppliedMatch || isContainerCssRule(rule));
+ continue;
+ }
+ // Other selector-less leaf at-rules cannot be tied to a rendered node.
+ }
+ };
+ const appendSheet = (sheet) => {
+ if (!sheet || seen.has(sheet)) return;
+ seen.add(sheet);
+ let rules;
+ try { rules = Array.from(sheet.cssRules || sheet.rules || []); }
+ catch { return; }
+ appendRules(rules);
+ };
+ let sheets;
+ try { sheets = Array.from(document.styleSheets || []); }
+ catch { return ''; }
+ for (const sheet of sheets) {
+ const owner = sheet.ownerNode;
+ if (owner?.tagName?.toLowerCase() !== 'link') continue;
+ if (!/\bstylesheet\b/i.test(owner.getAttribute?.('rel') || '')) continue;
+ appendSheet(sheet);
+ }
+ // Motion checks need the effective body of a live animation's keyframes.
+ // Let the browser resolve duplicate names across source order, imports,
+ // conditional groups, and cascade layers, then serialize those computed
+ // frames back into the pattern corpus. Browsers also make container-nested
+ // keyframes globally available, so lexical grouping is not a reliable
+ // activity signal. When the Web Animations API is unavailable, fall back to
+ // the last source-order definition referenced by a retained linked rule.
+ const resolvedKeyframes = resolvedAnimationKeyframes(new Set(keyframeCandidates.keys()));
+ if (resolvedKeyframes) {
+ parts.push(...resolvedKeyframes.values());
+ } else {
+ for (const candidate of keyframeCandidates.values()) {
+ if (!animationNames.has(candidate.name)) continue;
+ parts.push(candidate.cssText);
+ }
+ }
+ return parts.join('\n');
+ }
+
function browserFindingsFromMap(groupMap) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
@@ -8548,18 +8932,16 @@ if (IS_BROWSER) {
// (the CSS ships here, but the pattern never renders — the live DOM is
// ground truth in the browser), and a match under a data-impeccable-ignore
// ancestor is waived. Selector-less findings stay page-level.
- const scopedHtmlFindings = checkHtmlPatterns(docClone.outerHTML).filter(f => {
+ const html = docClone.outerHTML;
+ const corpora = buildHtmlPatternCorpora(html);
+ const linkedCss = linkedStylesheetText();
+ if (linkedCss) corpora.styleText += `\n${linkedCss}`;
+ const scopedHtmlFindings = checkHtmlPatterns(html, corpora).filter(f => {
if (!f.selector) return true;
- const query = String(f.selector).replace(/::?[a-zA-Z-]+(\([^)]*\))?/g, '').trim().replace(/,\s*(?=,|$)/g, '');
- if (!query || /^[,\s]*$/.test(query)) return true;
- let matches;
- try {
- matches = document.querySelectorAll(query);
- } catch {
- return true;
- }
+ const matches = selectorNodesForLiveDom(document, f.selector);
+ if (!matches) return false;
if (matches.length === 0) return false;
- return [...matches].some(el => !scopedIgnoreActive(el, f.id));
+ return matches.some(el => !scopedIgnoreActive(el, f.id));
});
if (scopedHtmlFindings.length > 0) {
const mapped = scopedHtmlFindings.map(f => {
diff --git a/.trae-cn/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs b/.trae-cn/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
index f3ff43c84..ac4bd0a7c 100644
--- a/.trae-cn/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
+++ b/.trae-cn/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
@@ -2,7 +2,7 @@ import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { finding } from '../../findings.mjs';
+import { deriveAdvisoryFlag, finding } from '../../findings.mjs';
import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
import { checkContentHiddenAtRest } from '../../rules/checks.mjs';
@@ -394,7 +394,7 @@ async function detectUrl(rawUrl, options = {}) {
// Per-finding severity promotion (e.g. hero-region pulsing dot)
// overrides the registry default carried by finding().
if (f.severity && f.severity !== item.severity) item.severity = f.severity;
- return item;
+ return deriveAdvisoryFlag(item);
});
}
diff --git a/.trae-cn/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs b/.trae-cn/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
index 84e6ab1f5..dac6939b0 100644
--- a/.trae-cn/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
+++ b/.trae-cn/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
@@ -9,7 +9,7 @@ import {
} from '../../design-system.mjs';
import { isFullPage } from '../../shared/page.mjs';
import { applyInlineIgnores } from '../../shared/inline-ignores.mjs';
-import { finding } from '../../findings.mjs';
+import { deriveAdvisoryFlag, finding } from '../../findings.mjs';
import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import {
checkElementBorders,
@@ -257,7 +257,7 @@ async function detectHtml(filePath, options = {}) {
// severity (e.g. a pulsing dot inside a header/nav landmark) that
// overrides the registry default.
if (f.severity) item.severity = f.severity;
- findings.push(item);
+ findings.push(deriveAdvisoryFlag(item));
}
// Text-content analyzers (em-dash overuse, marketing buzzwords,
// numbered section markers, aphoristic cadence) live in the regex
diff --git a/.trae-cn/skills/impeccable/scripts/detector/findings.mjs b/.trae-cn/skills/impeccable/scripts/detector/findings.mjs
index fa98dd935..ae7e134f9 100644
--- a/.trae-cn/skills/impeccable/scripts/detector/findings.mjs
+++ b/.trae-cn/skills/impeccable/scripts/detector/findings.mjs
@@ -4,6 +4,12 @@ function getAP(id) {
return getAntipattern(id);
}
+function deriveAdvisoryFlag(item) {
+ if (item.severity === 'advisory') item.advisory = true;
+ else delete item.advisory;
+ return item;
+}
+
function finding(id, filePath, snippet, line = 0) {
const ap = getAP(id);
const base = { antipattern: id, name: ap.name, description: ap.description, severity: ap.severity || 'warning', category: ap.category || null, file: filePath, line, snippet };
@@ -11,8 +17,7 @@ function finding(id, filePath, snippet, line = 0) {
// failures. Carry the flag on the finding so every consumer (CLI, JSON, hook)
// can partition without a registry lookup. Only stamped when true to keep the
// finding shape stable for the vast majority of rules.
- if (ap.advisory === true) base.advisory = true;
- return base;
+ return deriveAdvisoryFlag(base);
}
-export { getAP, finding };
+export { getAP, finding, deriveAdvisoryFlag };
diff --git a/.trae-cn/skills/impeccable/scripts/detector/registry/antipatterns.mjs b/.trae-cn/skills/impeccable/scripts/detector/registry/antipatterns.mjs
index 945307783..7c692c79a 100644
--- a/.trae-cn/skills/impeccable/scripts/detector/registry/antipatterns.mjs
+++ b/.trae-cn/skills/impeccable/scripts/detector/registry/antipatterns.mjs
@@ -233,7 +233,7 @@ const ANTIPATTERNS = [
// rather than a failure. It fires only on the AI saturation pattern, not on
// ordinary prose. Advisory findings are surfaced separately, never counted
// as failures, and skipped by the design hook unless a project opts in.
- advisory: true,
+ severity: 'advisory',
name: 'Em-dash overuse',
description:
'Em-dash saturation in body copy is an AI cadence tell. Advisory only: humans use em-dashes legitimately, so this fires only on saturation — at least 8 em-dashes (— or --) at a density near one per 500 characters of body text — never on a long article that uses a few. Prefer commas, colons, periods, or parentheses.',
@@ -588,9 +588,10 @@ function getAntipattern(id) {
// Advisory rules are detected and reported, but never treated as failures:
// the CLI lists them under a separate "Advisory" section, they do not affect
// exit codes or the failure count, and the design hook skips them by default.
-// The set is derived from the registry so a rule only needs `advisory: true`.
+// `severity` is the canonical registry field. The runtime finding serializer
+// derives its `advisory: true` compatibility/output flag from this set.
const ADVISORY_RULE_IDS = new Set(
- ANTIPATTERNS.filter(rule => rule.advisory === true).map(rule => rule.id),
+ ANTIPATTERNS.filter(rule => rule.severity === 'advisory').map(rule => rule.id),
);
function isAdvisoryRule(id) {
diff --git a/.trae-cn/skills/impeccable/scripts/detector/rules/checks.mjs b/.trae-cn/skills/impeccable/scripts/detector/rules/checks.mjs
index 579e1c12e..a24631ce9 100644
--- a/.trae-cn/skills/impeccable/scripts/detector/rules/checks.mjs
+++ b/.trae-cn/skills/impeccable/scripts/detector/rules/checks.mjs
@@ -688,7 +688,10 @@ function enclosingCssSelector(cssText, index) {
// `{` belongs to some other selector.
const closeBeforeIndex = cssText.lastIndexOf('}', index);
if (closeBeforeIndex > open) return null;
- const prevClose = Math.max(cssText.lastIndexOf('}', open - 1), cssText.lastIndexOf(';', open - 1));
+ // Ignore delimiters inside comments when locating the previous declaration.
+ // Keeping comment length intact preserves indices into the original source.
+ const beforeOpen = cssText.slice(0, open).replace(/\/\*[\s\S]*?\*\//g, comment => ' '.repeat(comment.length));
+ const prevClose = Math.max(beforeOpen.lastIndexOf('}'), beforeOpen.lastIndexOf(';'));
const raw = cssText.slice(prevClose + 1, open).replace(/\/\*[\s\S]*?\*\//g, '').trim().replace(/\s+/g, ' ');
if (!raw || raw.startsWith('@') || /^\d/.test(raw) || /[{}<]/.test(raw)) return null;
// Keyframe steps: percentage steps fail the digit test above, but `from`
@@ -4020,14 +4023,17 @@ function checkTypography() {
}
if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
+ // Report the actual primary face: the uniquely most-used family. The old
+ // 15% threshold labeled secondary faces as primary (e.g. an 82/18 split).
+ const ranked = [...fontUsage.entries()].sort((a, b) => b[1] - a[1]);
+ const [primary] = ranked;
+ const tied = ranked[1]?.[1] === primary?.[1];
+ if (primary && !tied) {
+ const [font, count] = primary;
const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ if (OVERUSED_FONTS.has(font) && !isBrandFontOnOwnDomain(font)) {
+ findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ }
}
}
diff --git a/.trae-cn/skills/impeccable/scripts/hook-lib.mjs b/.trae-cn/skills/impeccable/scripts/hook-lib.mjs
index 767fe65a6..6d8c3db81 100644
--- a/.trae-cn/skills/impeccable/scripts/hook-lib.mjs
+++ b/.trae-cn/skills/impeccable/scripts/hook-lib.mjs
@@ -138,17 +138,20 @@ export const IMMEDIATE_TIER_RULES = new Set([
// the agent is never nagged about a taste call a human might make on purpose.
// A project opts back in with `.impeccable/config.json`:
// { "detector": { "advisoryRules": "include" } }
-// This set is the hook's own copy of the registry's `advisory: true` rules,
-// mirroring how IMMEDIATE_TIER_RULES lists rule ids inline so the hook stays
-// self-contained and testable without loading the detector. Keep it in sync
-// with the registry (cli/engine/registry/antipatterns.mjs).
+// This legacy id fallback keeps older detector findings recognizable when they
+// carry neither the current runtime flag nor the canonical advisory severity.
+// Current findings are classified by their serialized metadata below.
export const ADVISORY_RULES = new Set([
'em-dash-overuse',
]);
export function isAdvisoryFinding(finding) {
const id = finding && normalizeIgnoreRule(finding.antipattern);
- return Boolean(id && (ADVISORY_RULES.has(id) || finding.advisory === true));
+ return Boolean(id && (
+ ADVISORY_RULES.has(id)
+ || finding.advisory === true
+ || finding.severity === 'advisory'
+ ));
}
export const DEFAULT_CONFIG = Object.freeze({
diff --git a/.trae/skills/impeccable/scripts/detector/browser/injected/index.mjs b/.trae/skills/impeccable/scripts/detector/browser/injected/index.mjs
index febf7f297..76fc558e5 100644
--- a/.trae/skills/impeccable/scripts/detector/browser/injected/index.mjs
+++ b/.trae/skills/impeccable/scripts/detector/browser/injected/index.mjs
@@ -1228,14 +1228,17 @@ if (IS_BROWSER) {
isHidden: isElementHidden(el),
findings: findings.map(f => {
const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
+ const severity = f.severity || ap?.severity || 'warning';
return {
type: f.type || f.id,
category: ap ? ap.category : 'quality',
- severity: f.severity || ap?.severity || 'warning',
+ severity,
// Advisory findings (em-dash overuse, etc.) are surfaced but never
// treated as failures; carry the flag so the overlay/extension can
// render them with the mildest affordance and consumers can filter.
- advisory: (ap && ap.advisory === true) || f.advisory === true,
+ // Per-finding promotions override the registry default, so derive
+ // this strictly from the effective severity.
+ advisory: severity === 'advisory',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
@@ -1277,6 +1280,381 @@ if (IS_BROWSER) {
else groupMap.set(el, [...kept]);
}
+ function pseudoElementHostSelector(selector) {
+ const raw = String(selector || '');
+ const legacyNames = new Set(['before', 'after', 'first-letter', 'first-line']);
+ const isNameChar = char => /[a-zA-Z0-9_-]/.test(char || '');
+ const consumeFunction = (start) => {
+ let depth = 0;
+ let quote = '';
+ for (let i = start; i < raw.length; i += 1) {
+ const char = raw[i];
+ if (char === '\\') {
+ i += 1;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '(') depth += 1;
+ if (char === ')' && --depth === 0) return i + 1;
+ }
+ return raw.length;
+ };
+
+ let output = '';
+ let found = false;
+ for (let i = 0; i < raw.length;) {
+ const char = raw[i];
+ if (char === '\\') {
+ output += raw.slice(i, Math.min(raw.length, i + 2));
+ i += 2;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ const quote = char;
+ const start = i;
+ i += 1;
+ while (i < raw.length) {
+ if (raw[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ const value = raw[i];
+ i += 1;
+ if (value === quote) break;
+ }
+ output += raw.slice(start, i);
+ continue;
+ }
+ if (char !== ':') {
+ output += char;
+ i += 1;
+ continue;
+ }
+
+ let end = i + 1;
+ let isPseudoElement = false;
+ if (raw[end] === ':') {
+ end += 1;
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = end > nameStart;
+ } else {
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = legacyNames.has(raw.slice(nameStart, end).toLowerCase());
+ }
+ if (!isPseudoElement) {
+ output += char;
+ i += 1;
+ continue;
+ }
+ if (raw[end] === '(') end = consumeFunction(end);
+ found = true;
+ if (!output || /[\s>+~,]/.test(output[output.length - 1])) output += '*';
+ i = end;
+ }
+ if (!found) return null;
+ return output.trim().replace(/,\s*(?=,|$)/g, '');
+ }
+
+ function selectorNodesForLiveDom(root, selector) {
+ const raw = String(selector || '').trim();
+ if (!raw) return null;
+ const fallback = pseudoElementHostSelector(raw);
+ if (fallback == null) {
+ // An empty result from a valid full selector is authoritative. In
+ // particular, do not broaden inactive :hover/:focus/:not() rules to
+ // their host element by stripping pseudo-classes.
+ try { return Array.from(root.querySelectorAll(raw)); }
+ catch { return null; }
+ }
+
+ // Resolve pseudo-elements to their originating live elements. An attached
+ // pseudo-element (`.card::before`) belongs to the element before it, while
+ // a hostless pseudo-element after a combinator (`main > ::before`) belongs
+ // to a matching element at that position (`main > *`). Replacing every
+ // pseudo indiscriminately with an empty string leaves the latter as the
+ // invalid selector `main >` and makes absent hosts indistinguishable from
+ // selectors the DOM API cannot parse.
+ if (!fallback || /^[,\s]*$/.test(fallback)) return null;
+ try { return Array.from(root.querySelectorAll(fallback)); }
+ catch { return null; }
+ }
+
+ let containerProbeSequence = 0;
+
+ function isContainerCssRule(rule) {
+ return rule?.constructor?.name === 'CSSContainerRule'
+ || /^\s*@container\b/i.test(rule?.cssText || '');
+ }
+
+ function styleRuleAppliesToLiveMatches(rule, matches) {
+ const style = rule?.style;
+ if (!style || !matches?.length || typeof getComputedStyle !== 'function') return false;
+ const sequence = ++containerProbeSequence;
+ const property = `--impeccable-container-probe-${sequence}-${Math.random().toString(36).slice(2)}`;
+ const value = `impeccable-container-active-${sequence}`;
+ const previousValue = style.getPropertyValue(property);
+ const previousPriority = style.getPropertyPriority(property);
+ try {
+ style.setProperty(property, value, 'important');
+ } catch {
+ return false;
+ }
+
+ const pseudoElements = [...new Set(
+ String(rule.selectorText || '').match(/::[a-zA-Z-]+(?:\([^)]*\))?/g) || [],
+ )];
+ try {
+ return matches.some(el => [null, ...pseudoElements].some(pseudo => {
+ try {
+ const computed = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el);
+ return computed.getPropertyValue(property).trim() === value;
+ } catch {
+ return false;
+ }
+ }));
+ } finally {
+ if (previousValue) style.setProperty(property, previousValue, previousPriority);
+ else style.removeProperty(property);
+ }
+ }
+
+ function conditionalCssRuleIsActive(rule) {
+ const type = Number(rule?.type);
+ const constructorName = rule?.constructor?.name || '';
+ if (constructorName === 'CSSMediaRule' || type === 4) {
+ const condition = rule.conditionText || rule.media?.mediaText || '';
+ if (!condition || typeof window.matchMedia !== 'function') return true;
+ try { return window.matchMedia(condition).matches; }
+ catch { return true; }
+ }
+ if (constructorName === 'CSSSupportsRule' || type === 12) {
+ const condition = rule.conditionText || '';
+ if (!condition || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return true;
+ try { return CSS.supports(condition); }
+ catch { return true; }
+ }
+ return true;
+ }
+
+ function splitCssCommaList(value) {
+ const parts = [];
+ let current = '';
+ let quote = '';
+ let escaped = false;
+ for (const char of String(value || '')) {
+ if (escaped) {
+ current += char;
+ escaped = false;
+ continue;
+ }
+ if (char === '\\') {
+ current += char;
+ escaped = true;
+ continue;
+ }
+ if (quote) {
+ current += char;
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ current += char;
+ continue;
+ }
+ if (char === ',') {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+ return parts;
+ }
+
+ function normalizeAnimationName(value) {
+ const name = String(value || '').trim();
+ if (name.length >= 2 && name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) {
+ return name.slice(1, -1);
+ }
+ return name;
+ }
+
+ function animationNamesDeclaredByRule(rule) {
+ const style = rule?.style;
+ if (!style) return [];
+ let value = '';
+ try {
+ value = style.animationName
+ || style.getPropertyValue?.('animation-name')
+ || style.webkitAnimationName
+ || style.getPropertyValue?.('-webkit-animation-name')
+ || '';
+ } catch {
+ return [];
+ }
+ return splitCssCommaList(value)
+ .map(normalizeAnimationName)
+ .filter(name => name && name.toLowerCase() !== 'none');
+ }
+
+ function keyframesRuleName(rule, cssText) {
+ const constructorName = rule?.constructor?.name || '';
+ const type = Number(rule?.type);
+ const isKeyframes = constructorName === 'CSSKeyframesRule'
+ || constructorName === 'WebKitCSSKeyframesRule'
+ || type === 7
+ || /^\s*@(?:-webkit-)?keyframes\b/i.test(cssText);
+ if (!isKeyframes) return '';
+ const match = String(cssText || '').match(/^\s*@(?:-webkit-)?keyframes\s+([^\s{]+)/i);
+ return normalizeAnimationName(rule?.name || match?.[1] || '');
+ }
+
+ function cssPropertyName(property) {
+ if (property.startsWith('--')) return property;
+ return property.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
+ }
+
+ function resolvedAnimationKeyframes(candidateNames) {
+ if (typeof document.getAnimations !== 'function') return null;
+ let animations;
+ try { animations = document.getAnimations(); }
+ catch { return null; }
+
+ const resolved = new Map();
+ const metadata = new Set(['offset', 'computedOffset', 'easing', 'composite']);
+ for (const animation of animations) {
+ const name = normalizeAnimationName(animation?.animationName || '');
+ if (!name || !candidateNames.has(name) || resolved.has(name)) continue;
+ let frames;
+ try { frames = animation.effect?.getKeyframes?.() || []; }
+ catch { continue; }
+ const blocks = [];
+ for (const frame of frames) {
+ const rawOffset = Number.isFinite(frame.computedOffset) ? frame.computedOffset : frame.offset;
+ if (!Number.isFinite(rawOffset)) continue;
+ const offset = Math.round(rawOffset * 1000000) / 10000;
+ const declarations = Object.entries(frame)
+ .filter(([property, value]) => !metadata.has(property) && value != null && value !== '')
+ .map(([property, value]) => `${cssPropertyName(property)}: ${value};`);
+ const easing = String(frame.easing || '').trim();
+ if (easing && easing.toLowerCase() !== 'linear') {
+ declarations.push(`animation-timing-function: ${easing};`);
+ }
+ if (declarations.length === 0) continue;
+ blocks.push(`${offset}% { ${declarations.join(' ')} }`);
+ }
+ if (blocks.length > 0) resolved.set(name, `@keyframes ${name} { ${blocks.join(' ')} }`);
+ }
+ return resolved;
+ }
+
+ // Read CSS that is absent from document.outerHTML. Inline <style> blocks are
+ // already present in the HTML pattern corpus, so limit this walk to linked
+ // stylesheets. Flatten grouping rules so each declaration keeps its selector,
+ // and admit only selector rules that target the live DOM. That prevents
+ // unused utilities from feeding both selector-scoped and page-level checks.
+ // Same-origin CSS and readable CORS sheets participate; browser security
+ // exceptions for cross-origin sheets are expected and skipped.
+ function linkedStylesheetText() {
+ const parts = [];
+ const seen = new Set();
+ const animationNames = new Set();
+ const keyframeCandidates = new Map();
+ const appendRules = (rules, requiresAppliedMatch = false) => {
+ for (const rule of rules) {
+ if (rule.styleSheet) {
+ appendSheet(rule.styleSheet);
+ continue;
+ }
+ const cssText = rule.cssText || '';
+ if (rule.selectorText) {
+ const matches = selectorNodesForLiveDom(document, rule.selectorText);
+ // Only declarations with a resolvable live host enter the corpus.
+ // Unresolvable selectors are uncertain, not evidence that a pattern
+ // rendered, and retaining them would leak unused CSS into findings.
+ if (
+ matches?.length > 0
+ && (!requiresAppliedMatch || styleRuleAppliesToLiveMatches(rule, matches))
+ ) {
+ parts.push(cssText);
+ for (const name of animationNamesDeclaredByRule(rule)) animationNames.add(name);
+ }
+ continue;
+ }
+ let nested = [];
+ let hasNestedRules = false;
+ try {
+ const ruleList = rule.cssRules;
+ hasNestedRules = ruleList != null;
+ nested = Array.from(ruleList || []);
+ } catch {
+ continue;
+ }
+ const keyframesName = keyframesRuleName(rule, cssText);
+ if (keyframesName) {
+ // Keyframes do not merge: when a name is defined more than once, the
+ // later effective definition replaces the earlier one.
+ keyframeCandidates.set(keyframesName, {
+ name: keyframesName,
+ cssText,
+ });
+ continue;
+ }
+ if (hasNestedRules) {
+ if (!conditionalCssRuleIsActive(rule)) continue;
+ appendRules(nested, requiresAppliedMatch || isContainerCssRule(rule));
+ continue;
+ }
+ // Other selector-less leaf at-rules cannot be tied to a rendered node.
+ }
+ };
+ const appendSheet = (sheet) => {
+ if (!sheet || seen.has(sheet)) return;
+ seen.add(sheet);
+ let rules;
+ try { rules = Array.from(sheet.cssRules || sheet.rules || []); }
+ catch { return; }
+ appendRules(rules);
+ };
+ let sheets;
+ try { sheets = Array.from(document.styleSheets || []); }
+ catch { return ''; }
+ for (const sheet of sheets) {
+ const owner = sheet.ownerNode;
+ if (owner?.tagName?.toLowerCase() !== 'link') continue;
+ if (!/\bstylesheet\b/i.test(owner.getAttribute?.('rel') || '')) continue;
+ appendSheet(sheet);
+ }
+ // Motion checks need the effective body of a live animation's keyframes.
+ // Let the browser resolve duplicate names across source order, imports,
+ // conditional groups, and cascade layers, then serialize those computed
+ // frames back into the pattern corpus. Browsers also make container-nested
+ // keyframes globally available, so lexical grouping is not a reliable
+ // activity signal. When the Web Animations API is unavailable, fall back to
+ // the last source-order definition referenced by a retained linked rule.
+ const resolvedKeyframes = resolvedAnimationKeyframes(new Set(keyframeCandidates.keys()));
+ if (resolvedKeyframes) {
+ parts.push(...resolvedKeyframes.values());
+ } else {
+ for (const candidate of keyframeCandidates.values()) {
+ if (!animationNames.has(candidate.name)) continue;
+ parts.push(candidate.cssText);
+ }
+ }
+ return parts.join('\n');
+ }
+
function browserFindingsFromMap(groupMap) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
@@ -1650,18 +2028,16 @@ if (IS_BROWSER) {
// (the CSS ships here, but the pattern never renders — the live DOM is
// ground truth in the browser), and a match under a data-impeccable-ignore
// ancestor is waived. Selector-less findings stay page-level.
- const scopedHtmlFindings = checkHtmlPatterns(docClone.outerHTML).filter(f => {
+ const html = docClone.outerHTML;
+ const corpora = buildHtmlPatternCorpora(html);
+ const linkedCss = linkedStylesheetText();
+ if (linkedCss) corpora.styleText += `\n${linkedCss}`;
+ const scopedHtmlFindings = checkHtmlPatterns(html, corpora).filter(f => {
if (!f.selector) return true;
- const query = String(f.selector).replace(/::?[a-zA-Z-]+(\([^)]*\))?/g, '').trim().replace(/,\s*(?=,|$)/g, '');
- if (!query || /^[,\s]*$/.test(query)) return true;
- let matches;
- try {
- matches = document.querySelectorAll(query);
- } catch {
- return true;
- }
+ const matches = selectorNodesForLiveDom(document, f.selector);
+ if (!matches) return false;
if (matches.length === 0) return false;
- return [...matches].some(el => !scopedIgnoreActive(el, f.id));
+ return matches.some(el => !scopedIgnoreActive(el, f.id));
});
if (scopedHtmlFindings.length > 0) {
const mapped = scopedHtmlFindings.map(f => {
diff --git a/.trae/skills/impeccable/scripts/detector/cli/main.mjs b/.trae/skills/impeccable/scripts/detector/cli/main.mjs
index 4476d04f1..3451d6c6b 100644
--- a/.trae/skills/impeccable/scripts/detector/cli/main.mjs
+++ b/.trae/skills/impeccable/scripts/detector/cli/main.mjs
@@ -37,13 +37,30 @@ function fileUrlToLocalPath(url) {
}
}
+const URL_TARGET_RE = /^(?:https?|file):\/\//i;
+
+// Some agent runners hand a shell-ready URL list to Node as one argv value.
+// A browser accepts the spaces as part of one encoded URL, producing a
+// plausible scan attributed to a bogus joined path. Expand only when every
+// whitespace-delimited token is independently a URL, preserving ordinary
+// filesystem paths that contain spaces.
+function expandJoinedUrlTargets(targets) {
+ return targets.flatMap((target) => {
+ if (!/\s/.test(target)) return [target];
+ const parts = target.trim().split(/\s+/).filter(Boolean);
+ return parts.length > 1 && parts.every(part => URL_TARGET_RE.test(part))
+ ? parts
+ : [target];
+ });
+}
+
// Advisory findings are detected but never treated as failures: they list in a
// separate, visually dimmed section, are excluded from the failure count that
// drives the exit code, and carry `"advisory": true` in JSON so consumers can
// filter. Every advisory finding carries the flag (stamped by the registry via
// findings.mjs).
function isAdvisory(finding) {
- return finding && finding.advisory === true;
+ return Boolean(finding && (finding.advisory === true || finding.severity === 'advisory'));
}
function partitionAdvisory(findings) {
@@ -168,6 +185,10 @@ Advisory findings:
counted as failures and never changing the exit code. They stay out of the
failure count so they never block automation. --no-advisory hides them.
+Output streams:
+ Human-readable findings go to stderr so stdout stays available for structured
+ output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.
+
Project config:
Respects .impeccable/config.json and .impeccable/config.local.json detector
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
@@ -185,7 +206,7 @@ Detection modes:
HTML files Static HTML/CSS analysis (default, catches linked CSS)
Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)
URLs Puppeteer full browser rendering (auto-detected;
- http(s):// and file:// URLs)
+ http(s):// and file:// URLs; accessible linked CSS included)
Examples:
impeccable detect src/
@@ -283,7 +304,7 @@ async function detectCli() {
const designSystem = loadDesignSystemForTarget(localPath, { cache: designSystemCache });
return designSystem ? { ...baseScanOptions, designSystem } : baseScanOptions;
};
- const targets = args.filter(a => !a.startsWith('--'));
+ const targets = expandJoinedUrlTargets(args.filter(a => !a.startsWith('--')));
if (helpMode) { printUsage(); process.exit(0); }
@@ -297,13 +318,12 @@ async function detectCli() {
// real cascade, real computed styles, real layout. Callers that want a
// browser-grade scan of a local artifact can pass file:///abs/path.html
// instead of the bare path (which stays on the static engine).
- const urlRe = /^(?:https?|file):\/\//i;
- const urlTargetCount = paths.filter(target => urlRe.test(target)).length;
+ const urlTargetCount = paths.filter(target => URL_TARGET_RE.test(target)).length;
const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
try {
for (const target of paths) {
- if (urlRe.test(target)) {
+ if (URL_TARGET_RE.test(target)) {
// A file:// URL points at a local artifact, so its design system
// resolves from that file's project. A remote http(s) URL has no
// local project — it gets base options (no design system), never
diff --git a/.trae/skills/impeccable/scripts/detector/detect-antipatterns-browser.js b/.trae/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
index e6899f569..460ffb45b 100644
--- a/.trae/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
+++ b/.trae/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
@@ -358,7 +358,7 @@ const ANTIPATTERNS = [
// rather than a failure. It fires only on the AI saturation pattern, not on
// ordinary prose. Advisory findings are surfaced separately, never counted
// as failures, and skipped by the design hook unless a project opts in.
- advisory: true,
+ severity: 'advisory',
name: 'Em-dash overuse',
description:
'Em-dash saturation in body copy is an AI cadence tell. Advisory only: humans use em-dashes legitimately, so this fires only on saturation — at least 8 em-dashes (— or --) at a density near one per 500 characters of body text — never on a long article that uses a few. Prefer commas, colons, periods, or parentheses.',
@@ -1961,7 +1961,10 @@ function enclosingCssSelector(cssText, index) {
// `{` belongs to some other selector.
const closeBeforeIndex = cssText.lastIndexOf('}', index);
if (closeBeforeIndex > open) return null;
- const prevClose = Math.max(cssText.lastIndexOf('}', open - 1), cssText.lastIndexOf(';', open - 1));
+ // Ignore delimiters inside comments when locating the previous declaration.
+ // Keeping comment length intact preserves indices into the original source.
+ const beforeOpen = cssText.slice(0, open).replace(/\/\*[\s\S]*?\*\//g, comment => ' '.repeat(comment.length));
+ const prevClose = Math.max(beforeOpen.lastIndexOf('}'), beforeOpen.lastIndexOf(';'));
const raw = cssText.slice(prevClose + 1, open).replace(/\/\*[\s\S]*?\*\//g, '').trim().replace(/\s+/g, ' ');
if (!raw || raw.startsWith('@') || /^\d/.test(raw) || /[{}<]/.test(raw)) return null;
// Keyframe steps: percentage steps fail the digit test above, but `from`
@@ -5293,14 +5296,17 @@ function checkTypography() {
}
if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
+ // Report the actual primary face: the uniquely most-used family. The old
+ // 15% threshold labeled secondary faces as primary (e.g. an 82/18 split).
+ const ranked = [...fontUsage.entries()].sort((a, b) => b[1] - a[1]);
+ const [primary] = ranked;
+ const tied = ranked[1]?.[1] === primary?.[1];
+ if (primary && !tied) {
+ const [font, count] = primary;
const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ if (OVERUSED_FONTS.has(font) && !isBrandFontOnOwnDomain(font)) {
+ findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ }
}
}
@@ -8126,14 +8132,17 @@ if (IS_BROWSER) {
isHidden: isElementHidden(el),
findings: findings.map(f => {
const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
+ const severity = f.severity || ap?.severity || 'warning';
return {
type: f.type || f.id,
category: ap ? ap.category : 'quality',
- severity: f.severity || ap?.severity || 'warning',
+ severity,
// Advisory findings (em-dash overuse, etc.) are surfaced but never
// treated as failures; carry the flag so the overlay/extension can
// render them with the mildest affordance and consumers can filter.
- advisory: (ap && ap.advisory === true) || f.advisory === true,
+ // Per-finding promotions override the registry default, so derive
+ // this strictly from the effective severity.
+ advisory: severity === 'advisory',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
@@ -8175,6 +8184,381 @@ if (IS_BROWSER) {
else groupMap.set(el, [...kept]);
}
+ function pseudoElementHostSelector(selector) {
+ const raw = String(selector || '');
+ const legacyNames = new Set(['before', 'after', 'first-letter', 'first-line']);
+ const isNameChar = char => /[a-zA-Z0-9_-]/.test(char || '');
+ const consumeFunction = (start) => {
+ let depth = 0;
+ let quote = '';
+ for (let i = start; i < raw.length; i += 1) {
+ const char = raw[i];
+ if (char === '\\') {
+ i += 1;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '(') depth += 1;
+ if (char === ')' && --depth === 0) return i + 1;
+ }
+ return raw.length;
+ };
+
+ let output = '';
+ let found = false;
+ for (let i = 0; i < raw.length;) {
+ const char = raw[i];
+ if (char === '\\') {
+ output += raw.slice(i, Math.min(raw.length, i + 2));
+ i += 2;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ const quote = char;
+ const start = i;
+ i += 1;
+ while (i < raw.length) {
+ if (raw[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ const value = raw[i];
+ i += 1;
+ if (value === quote) break;
+ }
+ output += raw.slice(start, i);
+ continue;
+ }
+ if (char !== ':') {
+ output += char;
+ i += 1;
+ continue;
+ }
+
+ let end = i + 1;
+ let isPseudoElement = false;
+ if (raw[end] === ':') {
+ end += 1;
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = end > nameStart;
+ } else {
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = legacyNames.has(raw.slice(nameStart, end).toLowerCase());
+ }
+ if (!isPseudoElement) {
+ output += char;
+ i += 1;
+ continue;
+ }
+ if (raw[end] === '(') end = consumeFunction(end);
+ found = true;
+ if (!output || /[\s>+~,]/.test(output[output.length - 1])) output += '*';
+ i = end;
+ }
+ if (!found) return null;
+ return output.trim().replace(/,\s*(?=,|$)/g, '');
+ }
+
+ function selectorNodesForLiveDom(root, selector) {
+ const raw = String(selector || '').trim();
+ if (!raw) return null;
+ const fallback = pseudoElementHostSelector(raw);
+ if (fallback == null) {
+ // An empty result from a valid full selector is authoritative. In
+ // particular, do not broaden inactive :hover/:focus/:not() rules to
+ // their host element by stripping pseudo-classes.
+ try { return Array.from(root.querySelectorAll(raw)); }
+ catch { return null; }
+ }
+
+ // Resolve pseudo-elements to their originating live elements. An attached
+ // pseudo-element (`.card::before`) belongs to the element before it, while
+ // a hostless pseudo-element after a combinator (`main > ::before`) belongs
+ // to a matching element at that position (`main > *`). Replacing every
+ // pseudo indiscriminately with an empty string leaves the latter as the
+ // invalid selector `main >` and makes absent hosts indistinguishable from
+ // selectors the DOM API cannot parse.
+ if (!fallback || /^[,\s]*$/.test(fallback)) return null;
+ try { return Array.from(root.querySelectorAll(fallback)); }
+ catch { return null; }
+ }
+
+ let containerProbeSequence = 0;
+
+ function isContainerCssRule(rule) {
+ return rule?.constructor?.name === 'CSSContainerRule'
+ || /^\s*@container\b/i.test(rule?.cssText || '');
+ }
+
+ function styleRuleAppliesToLiveMatches(rule, matches) {
+ const style = rule?.style;
+ if (!style || !matches?.length || typeof getComputedStyle !== 'function') return false;
+ const sequence = ++containerProbeSequence;
+ const property = `--impeccable-container-probe-${sequence}-${Math.random().toString(36).slice(2)}`;
+ const value = `impeccable-container-active-${sequence}`;
+ const previousValue = style.getPropertyValue(property);
+ const previousPriority = style.getPropertyPriority(property);
+ try {
+ style.setProperty(property, value, 'important');
+ } catch {
+ return false;
+ }
+
+ const pseudoElements = [...new Set(
+ String(rule.selectorText || '').match(/::[a-zA-Z-]+(?:\([^)]*\))?/g) || [],
+ )];
+ try {
+ return matches.some(el => [null, ...pseudoElements].some(pseudo => {
+ try {
+ const computed = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el);
+ return computed.getPropertyValue(property).trim() === value;
+ } catch {
+ return false;
+ }
+ }));
+ } finally {
+ if (previousValue) style.setProperty(property, previousValue, previousPriority);
+ else style.removeProperty(property);
+ }
+ }
+
+ function conditionalCssRuleIsActive(rule) {
+ const type = Number(rule?.type);
+ const constructorName = rule?.constructor?.name || '';
+ if (constructorName === 'CSSMediaRule' || type === 4) {
+ const condition = rule.conditionText || rule.media?.mediaText || '';
+ if (!condition || typeof window.matchMedia !== 'function') return true;
+ try { return window.matchMedia(condition).matches; }
+ catch { return true; }
+ }
+ if (constructorName === 'CSSSupportsRule' || type === 12) {
+ const condition = rule.conditionText || '';
+ if (!condition || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return true;
+ try { return CSS.supports(condition); }
+ catch { return true; }
+ }
+ return true;
+ }
+
+ function splitCssCommaList(value) {
+ const parts = [];
+ let current = '';
+ let quote = '';
+ let escaped = false;
+ for (const char of String(value || '')) {
+ if (escaped) {
+ current += char;
+ escaped = false;
+ continue;
+ }
+ if (char === '\\') {
+ current += char;
+ escaped = true;
+ continue;
+ }
+ if (quote) {
+ current += char;
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ current += char;
+ continue;
+ }
+ if (char === ',') {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+ return parts;
+ }
+
+ function normalizeAnimationName(value) {
+ const name = String(value || '').trim();
+ if (name.length >= 2 && name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) {
+ return name.slice(1, -1);
+ }
+ return name;
+ }
+
+ function animationNamesDeclaredByRule(rule) {
+ const style = rule?.style;
+ if (!style) return [];
+ let value = '';
+ try {
+ value = style.animationName
+ || style.getPropertyValue?.('animation-name')
+ || style.webkitAnimationName
+ || style.getPropertyValue?.('-webkit-animation-name')
+ || '';
+ } catch {
+ return [];
+ }
+ return splitCssCommaList(value)
+ .map(normalizeAnimationName)
+ .filter(name => name && name.toLowerCase() !== 'none');
+ }
+
+ function keyframesRuleName(rule, cssText) {
+ const constructorName = rule?.constructor?.name || '';
+ const type = Number(rule?.type);
+ const isKeyframes = constructorName === 'CSSKeyframesRule'
+ || constructorName === 'WebKitCSSKeyframesRule'
+ || type === 7
+ || /^\s*@(?:-webkit-)?keyframes\b/i.test(cssText);
+ if (!isKeyframes) return '';
+ const match = String(cssText || '').match(/^\s*@(?:-webkit-)?keyframes\s+([^\s{]+)/i);
+ return normalizeAnimationName(rule?.name || match?.[1] || '');
+ }
+
+ function cssPropertyName(property) {
+ if (property.startsWith('--')) return property;
+ return property.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
+ }
+
+ function resolvedAnimationKeyframes(candidateNames) {
+ if (typeof document.getAnimations !== 'function') return null;
+ let animations;
+ try { animations = document.getAnimations(); }
+ catch { return null; }
+
+ const resolved = new Map();
+ const metadata = new Set(['offset', 'computedOffset', 'easing', 'composite']);
+ for (const animation of animations) {
+ const name = normalizeAnimationName(animation?.animationName || '');
+ if (!name || !candidateNames.has(name) || resolved.has(name)) continue;
+ let frames;
+ try { frames = animation.effect?.getKeyframes?.() || []; }
+ catch { continue; }
+ const blocks = [];
+ for (const frame of frames) {
+ const rawOffset = Number.isFinite(frame.computedOffset) ? frame.computedOffset : frame.offset;
+ if (!Number.isFinite(rawOffset)) continue;
+ const offset = Math.round(rawOffset * 1000000) / 10000;
+ const declarations = Object.entries(frame)
+ .filter(([property, value]) => !metadata.has(property) && value != null && value !== '')
+ .map(([property, value]) => `${cssPropertyName(property)}: ${value};`);
+ const easing = String(frame.easing || '').trim();
+ if (easing && easing.toLowerCase() !== 'linear') {
+ declarations.push(`animation-timing-function: ${easing};`);
+ }
+ if (declarations.length === 0) continue;
+ blocks.push(`${offset}% { ${declarations.join(' ')} }`);
+ }
+ if (blocks.length > 0) resolved.set(name, `@keyframes ${name} { ${blocks.join(' ')} }`);
+ }
+ return resolved;
+ }
+
+ // Read CSS that is absent from document.outerHTML. Inline <style> blocks are
+ // already present in the HTML pattern corpus, so limit this walk to linked
+ // stylesheets. Flatten grouping rules so each declaration keeps its selector,
+ // and admit only selector rules that target the live DOM. That prevents
+ // unused utilities from feeding both selector-scoped and page-level checks.
+ // Same-origin CSS and readable CORS sheets participate; browser security
+ // exceptions for cross-origin sheets are expected and skipped.
+ function linkedStylesheetText() {
+ const parts = [];
+ const seen = new Set();
+ const animationNames = new Set();
+ const keyframeCandidates = new Map();
+ const appendRules = (rules, requiresAppliedMatch = false) => {
+ for (const rule of rules) {
+ if (rule.styleSheet) {
+ appendSheet(rule.styleSheet);
+ continue;
+ }
+ const cssText = rule.cssText || '';
+ if (rule.selectorText) {
+ const matches = selectorNodesForLiveDom(document, rule.selectorText);
+ // Only declarations with a resolvable live host enter the corpus.
+ // Unresolvable selectors are uncertain, not evidence that a pattern
+ // rendered, and retaining them would leak unused CSS into findings.
+ if (
+ matches?.length > 0
+ && (!requiresAppliedMatch || styleRuleAppliesToLiveMatches(rule, matches))
+ ) {
+ parts.push(cssText);
+ for (const name of animationNamesDeclaredByRule(rule)) animationNames.add(name);
+ }
+ continue;
+ }
+ let nested = [];
+ let hasNestedRules = false;
+ try {
+ const ruleList = rule.cssRules;
+ hasNestedRules = ruleList != null;
+ nested = Array.from(ruleList || []);
+ } catch {
+ continue;
+ }
+ const keyframesName = keyframesRuleName(rule, cssText);
+ if (keyframesName) {
+ // Keyframes do not merge: when a name is defined more than once, the
+ // later effective definition replaces the earlier one.
+ keyframeCandidates.set(keyframesName, {
+ name: keyframesName,
+ cssText,
+ });
+ continue;
+ }
+ if (hasNestedRules) {
+ if (!conditionalCssRuleIsActive(rule)) continue;
+ appendRules(nested, requiresAppliedMatch || isContainerCssRule(rule));
+ continue;
+ }
+ // Other selector-less leaf at-rules cannot be tied to a rendered node.
+ }
+ };
+ const appendSheet = (sheet) => {
+ if (!sheet || seen.has(sheet)) return;
+ seen.add(sheet);
+ let rules;
+ try { rules = Array.from(sheet.cssRules || sheet.rules || []); }
+ catch { return; }
+ appendRules(rules);
+ };
+ let sheets;
+ try { sheets = Array.from(document.styleSheets || []); }
+ catch { return ''; }
+ for (const sheet of sheets) {
+ const owner = sheet.ownerNode;
+ if (owner?.tagName?.toLowerCase() !== 'link') continue;
+ if (!/\bstylesheet\b/i.test(owner.getAttribute?.('rel') || '')) continue;
+ appendSheet(sheet);
+ }
+ // Motion checks need the effective body of a live animation's keyframes.
+ // Let the browser resolve duplicate names across source order, imports,
+ // conditional groups, and cascade layers, then serialize those computed
+ // frames back into the pattern corpus. Browsers also make container-nested
+ // keyframes globally available, so lexical grouping is not a reliable
+ // activity signal. When the Web Animations API is unavailable, fall back to
+ // the last source-order definition referenced by a retained linked rule.
+ const resolvedKeyframes = resolvedAnimationKeyframes(new Set(keyframeCandidates.keys()));
+ if (resolvedKeyframes) {
+ parts.push(...resolvedKeyframes.values());
+ } else {
+ for (const candidate of keyframeCandidates.values()) {
+ if (!animationNames.has(candidate.name)) continue;
+ parts.push(candidate.cssText);
+ }
+ }
+ return parts.join('\n');
+ }
+
function browserFindingsFromMap(groupMap) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
@@ -8548,18 +8932,16 @@ if (IS_BROWSER) {
// (the CSS ships here, but the pattern never renders — the live DOM is
// ground truth in the browser), and a match under a data-impeccable-ignore
// ancestor is waived. Selector-less findings stay page-level.
- const scopedHtmlFindings = checkHtmlPatterns(docClone.outerHTML).filter(f => {
+ const html = docClone.outerHTML;
+ const corpora = buildHtmlPatternCorpora(html);
+ const linkedCss = linkedStylesheetText();
+ if (linkedCss) corpora.styleText += `\n${linkedCss}`;
+ const scopedHtmlFindings = checkHtmlPatterns(html, corpora).filter(f => {
if (!f.selector) return true;
- const query = String(f.selector).replace(/::?[a-zA-Z-]+(\([^)]*\))?/g, '').trim().replace(/,\s*(?=,|$)/g, '');
- if (!query || /^[,\s]*$/.test(query)) return true;
- let matches;
- try {
- matches = document.querySelectorAll(query);
- } catch {
- return true;
- }
+ const matches = selectorNodesForLiveDom(document, f.selector);
+ if (!matches) return false;
if (matches.length === 0) return false;
- return [...matches].some(el => !scopedIgnoreActive(el, f.id));
+ return matches.some(el => !scopedIgnoreActive(el, f.id));
});
if (scopedHtmlFindings.length > 0) {
const mapped = scopedHtmlFindings.map(f => {
diff --git a/.trae/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs b/.trae/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
index f3ff43c84..ac4bd0a7c 100644
--- a/.trae/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
+++ b/.trae/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
@@ -2,7 +2,7 @@ import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { finding } from '../../findings.mjs';
+import { deriveAdvisoryFlag, finding } from '../../findings.mjs';
import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
import { checkContentHiddenAtRest } from '../../rules/checks.mjs';
@@ -394,7 +394,7 @@ async function detectUrl(rawUrl, options = {}) {
// Per-finding severity promotion (e.g. hero-region pulsing dot)
// overrides the registry default carried by finding().
if (f.severity && f.severity !== item.severity) item.severity = f.severity;
- return item;
+ return deriveAdvisoryFlag(item);
});
}
diff --git a/.trae/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs b/.trae/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
index 84e6ab1f5..dac6939b0 100644
--- a/.trae/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
+++ b/.trae/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
@@ -9,7 +9,7 @@ import {
} from '../../design-system.mjs';
import { isFullPage } from '../../shared/page.mjs';
import { applyInlineIgnores } from '../../shared/inline-ignores.mjs';
-import { finding } from '../../findings.mjs';
+import { deriveAdvisoryFlag, finding } from '../../findings.mjs';
import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import {
checkElementBorders,
@@ -257,7 +257,7 @@ async function detectHtml(filePath, options = {}) {
// severity (e.g. a pulsing dot inside a header/nav landmark) that
// overrides the registry default.
if (f.severity) item.severity = f.severity;
- findings.push(item);
+ findings.push(deriveAdvisoryFlag(item));
}
// Text-content analyzers (em-dash overuse, marketing buzzwords,
// numbered section markers, aphoristic cadence) live in the regex
diff --git a/.trae/skills/impeccable/scripts/detector/findings.mjs b/.trae/skills/impeccable/scripts/detector/findings.mjs
index fa98dd935..ae7e134f9 100644
--- a/.trae/skills/impeccable/scripts/detector/findings.mjs
+++ b/.trae/skills/impeccable/scripts/detector/findings.mjs
@@ -4,6 +4,12 @@ function getAP(id) {
return getAntipattern(id);
}
+function deriveAdvisoryFlag(item) {
+ if (item.severity === 'advisory') item.advisory = true;
+ else delete item.advisory;
+ return item;
+}
+
function finding(id, filePath, snippet, line = 0) {
const ap = getAP(id);
const base = { antipattern: id, name: ap.name, description: ap.description, severity: ap.severity || 'warning', category: ap.category || null, file: filePath, line, snippet };
@@ -11,8 +17,7 @@ function finding(id, filePath, snippet, line = 0) {
// failures. Carry the flag on the finding so every consumer (CLI, JSON, hook)
// can partition without a registry lookup. Only stamped when true to keep the
// finding shape stable for the vast majority of rules.
- if (ap.advisory === true) base.advisory = true;
- return base;
+ return deriveAdvisoryFlag(base);
}
-export { getAP, finding };
+export { getAP, finding, deriveAdvisoryFlag };
diff --git a/.trae/skills/impeccable/scripts/detector/registry/antipatterns.mjs b/.trae/skills/impeccable/scripts/detector/registry/antipatterns.mjs
index 945307783..7c692c79a 100644
--- a/.trae/skills/impeccable/scripts/detector/registry/antipatterns.mjs
+++ b/.trae/skills/impeccable/scripts/detector/registry/antipatterns.mjs
@@ -233,7 +233,7 @@ const ANTIPATTERNS = [
// rather than a failure. It fires only on the AI saturation pattern, not on
// ordinary prose. Advisory findings are surfaced separately, never counted
// as failures, and skipped by the design hook unless a project opts in.
- advisory: true,
+ severity: 'advisory',
name: 'Em-dash overuse',
description:
'Em-dash saturation in body copy is an AI cadence tell. Advisory only: humans use em-dashes legitimately, so this fires only on saturation — at least 8 em-dashes (— or --) at a density near one per 500 characters of body text — never on a long article that uses a few. Prefer commas, colons, periods, or parentheses.',
@@ -588,9 +588,10 @@ function getAntipattern(id) {
// Advisory rules are detected and reported, but never treated as failures:
// the CLI lists them under a separate "Advisory" section, they do not affect
// exit codes or the failure count, and the design hook skips them by default.
-// The set is derived from the registry so a rule only needs `advisory: true`.
+// `severity` is the canonical registry field. The runtime finding serializer
+// derives its `advisory: true` compatibility/output flag from this set.
const ADVISORY_RULE_IDS = new Set(
- ANTIPATTERNS.filter(rule => rule.advisory === true).map(rule => rule.id),
+ ANTIPATTERNS.filter(rule => rule.severity === 'advisory').map(rule => rule.id),
);
function isAdvisoryRule(id) {
diff --git a/.trae/skills/impeccable/scripts/detector/rules/checks.mjs b/.trae/skills/impeccable/scripts/detector/rules/checks.mjs
index 579e1c12e..a24631ce9 100644
--- a/.trae/skills/impeccable/scripts/detector/rules/checks.mjs
+++ b/.trae/skills/impeccable/scripts/detector/rules/checks.mjs
@@ -688,7 +688,10 @@ function enclosingCssSelector(cssText, index) {
// `{` belongs to some other selector.
const closeBeforeIndex = cssText.lastIndexOf('}', index);
if (closeBeforeIndex > open) return null;
- const prevClose = Math.max(cssText.lastIndexOf('}', open - 1), cssText.lastIndexOf(';', open - 1));
+ // Ignore delimiters inside comments when locating the previous declaration.
+ // Keeping comment length intact preserves indices into the original source.
+ const beforeOpen = cssText.slice(0, open).replace(/\/\*[\s\S]*?\*\//g, comment => ' '.repeat(comment.length));
+ const prevClose = Math.max(beforeOpen.lastIndexOf('}'), beforeOpen.lastIndexOf(';'));
const raw = cssText.slice(prevClose + 1, open).replace(/\/\*[\s\S]*?\*\//g, '').trim().replace(/\s+/g, ' ');
if (!raw || raw.startsWith('@') || /^\d/.test(raw) || /[{}<]/.test(raw)) return null;
// Keyframe steps: percentage steps fail the digit test above, but `from`
@@ -4020,14 +4023,17 @@ function checkTypography() {
}
if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
+ // Report the actual primary face: the uniquely most-used family. The old
+ // 15% threshold labeled secondary faces as primary (e.g. an 82/18 split).
+ const ranked = [...fontUsage.entries()].sort((a, b) => b[1] - a[1]);
+ const [primary] = ranked;
+ const tied = ranked[1]?.[1] === primary?.[1];
+ if (primary && !tied) {
+ const [font, count] = primary;
const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ if (OVERUSED_FONTS.has(font) && !isBrandFontOnOwnDomain(font)) {
+ findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ }
}
}
diff --git a/.trae/skills/impeccable/scripts/hook-lib.mjs b/.trae/skills/impeccable/scripts/hook-lib.mjs
index 767fe65a6..6d8c3db81 100644
--- a/.trae/skills/impeccable/scripts/hook-lib.mjs
+++ b/.trae/skills/impeccable/scripts/hook-lib.mjs
@@ -138,17 +138,20 @@ export const IMMEDIATE_TIER_RULES = new Set([
// the agent is never nagged about a taste call a human might make on purpose.
// A project opts back in with `.impeccable/config.json`:
// { "detector": { "advisoryRules": "include" } }
-// This set is the hook's own copy of the registry's `advisory: true` rules,
-// mirroring how IMMEDIATE_TIER_RULES lists rule ids inline so the hook stays
-// self-contained and testable without loading the detector. Keep it in sync
-// with the registry (cli/engine/registry/antipatterns.mjs).
+// This legacy id fallback keeps older detector findings recognizable when they
+// carry neither the current runtime flag nor the canonical advisory severity.
+// Current findings are classified by their serialized metadata below.
export const ADVISORY_RULES = new Set([
'em-dash-overuse',
]);
export function isAdvisoryFinding(finding) {
const id = finding && normalizeIgnoreRule(finding.antipattern);
- return Boolean(id && (ADVISORY_RULES.has(id) || finding.advisory === true));
+ return Boolean(id && (
+ ADVISORY_RULES.has(id)
+ || finding.advisory === true
+ || finding.severity === 'advisory'
+ ));
}
export const DEFAULT_CONFIG = Object.freeze({
diff --git a/.vibe/skills/impeccable/scripts/detector/browser/injected/index.mjs b/.vibe/skills/impeccable/scripts/detector/browser/injected/index.mjs
index febf7f297..76fc558e5 100644
--- a/.vibe/skills/impeccable/scripts/detector/browser/injected/index.mjs
+++ b/.vibe/skills/impeccable/scripts/detector/browser/injected/index.mjs
@@ -1228,14 +1228,17 @@ if (IS_BROWSER) {
isHidden: isElementHidden(el),
findings: findings.map(f => {
const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
+ const severity = f.severity || ap?.severity || 'warning';
return {
type: f.type || f.id,
category: ap ? ap.category : 'quality',
- severity: f.severity || ap?.severity || 'warning',
+ severity,
// Advisory findings (em-dash overuse, etc.) are surfaced but never
// treated as failures; carry the flag so the overlay/extension can
// render them with the mildest affordance and consumers can filter.
- advisory: (ap && ap.advisory === true) || f.advisory === true,
+ // Per-finding promotions override the registry default, so derive
+ // this strictly from the effective severity.
+ advisory: severity === 'advisory',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
@@ -1277,6 +1280,381 @@ if (IS_BROWSER) {
else groupMap.set(el, [...kept]);
}
+ function pseudoElementHostSelector(selector) {
+ const raw = String(selector || '');
+ const legacyNames = new Set(['before', 'after', 'first-letter', 'first-line']);
+ const isNameChar = char => /[a-zA-Z0-9_-]/.test(char || '');
+ const consumeFunction = (start) => {
+ let depth = 0;
+ let quote = '';
+ for (let i = start; i < raw.length; i += 1) {
+ const char = raw[i];
+ if (char === '\\') {
+ i += 1;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '(') depth += 1;
+ if (char === ')' && --depth === 0) return i + 1;
+ }
+ return raw.length;
+ };
+
+ let output = '';
+ let found = false;
+ for (let i = 0; i < raw.length;) {
+ const char = raw[i];
+ if (char === '\\') {
+ output += raw.slice(i, Math.min(raw.length, i + 2));
+ i += 2;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ const quote = char;
+ const start = i;
+ i += 1;
+ while (i < raw.length) {
+ if (raw[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ const value = raw[i];
+ i += 1;
+ if (value === quote) break;
+ }
+ output += raw.slice(start, i);
+ continue;
+ }
+ if (char !== ':') {
+ output += char;
+ i += 1;
+ continue;
+ }
+
+ let end = i + 1;
+ let isPseudoElement = false;
+ if (raw[end] === ':') {
+ end += 1;
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = end > nameStart;
+ } else {
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = legacyNames.has(raw.slice(nameStart, end).toLowerCase());
+ }
+ if (!isPseudoElement) {
+ output += char;
+ i += 1;
+ continue;
+ }
+ if (raw[end] === '(') end = consumeFunction(end);
+ found = true;
+ if (!output || /[\s>+~,]/.test(output[output.length - 1])) output += '*';
+ i = end;
+ }
+ if (!found) return null;
+ return output.trim().replace(/,\s*(?=,|$)/g, '');
+ }
+
+ function selectorNodesForLiveDom(root, selector) {
+ const raw = String(selector || '').trim();
+ if (!raw) return null;
+ const fallback = pseudoElementHostSelector(raw);
+ if (fallback == null) {
+ // An empty result from a valid full selector is authoritative. In
+ // particular, do not broaden inactive :hover/:focus/:not() rules to
+ // their host element by stripping pseudo-classes.
+ try { return Array.from(root.querySelectorAll(raw)); }
+ catch { return null; }
+ }
+
+ // Resolve pseudo-elements to their originating live elements. An attached
+ // pseudo-element (`.card::before`) belongs to the element before it, while
+ // a hostless pseudo-element after a combinator (`main > ::before`) belongs
+ // to a matching element at that position (`main > *`). Replacing every
+ // pseudo indiscriminately with an empty string leaves the latter as the
+ // invalid selector `main >` and makes absent hosts indistinguishable from
+ // selectors the DOM API cannot parse.
+ if (!fallback || /^[,\s]*$/.test(fallback)) return null;
+ try { return Array.from(root.querySelectorAll(fallback)); }
+ catch { return null; }
+ }
+
+ let containerProbeSequence = 0;
+
+ function isContainerCssRule(rule) {
+ return rule?.constructor?.name === 'CSSContainerRule'
+ || /^\s*@container\b/i.test(rule?.cssText || '');
+ }
+
+ function styleRuleAppliesToLiveMatches(rule, matches) {
+ const style = rule?.style;
+ if (!style || !matches?.length || typeof getComputedStyle !== 'function') return false;
+ const sequence = ++containerProbeSequence;
+ const property = `--impeccable-container-probe-${sequence}-${Math.random().toString(36).slice(2)}`;
+ const value = `impeccable-container-active-${sequence}`;
+ const previousValue = style.getPropertyValue(property);
+ const previousPriority = style.getPropertyPriority(property);
+ try {
+ style.setProperty(property, value, 'important');
+ } catch {
+ return false;
+ }
+
+ const pseudoElements = [...new Set(
+ String(rule.selectorText || '').match(/::[a-zA-Z-]+(?:\([^)]*\))?/g) || [],
+ )];
+ try {
+ return matches.some(el => [null, ...pseudoElements].some(pseudo => {
+ try {
+ const computed = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el);
+ return computed.getPropertyValue(property).trim() === value;
+ } catch {
+ return false;
+ }
+ }));
+ } finally {
+ if (previousValue) style.setProperty(property, previousValue, previousPriority);
+ else style.removeProperty(property);
+ }
+ }
+
+ function conditionalCssRuleIsActive(rule) {
+ const type = Number(rule?.type);
+ const constructorName = rule?.constructor?.name || '';
+ if (constructorName === 'CSSMediaRule' || type === 4) {
+ const condition = rule.conditionText || rule.media?.mediaText || '';
+ if (!condition || typeof window.matchMedia !== 'function') return true;
+ try { return window.matchMedia(condition).matches; }
+ catch { return true; }
+ }
+ if (constructorName === 'CSSSupportsRule' || type === 12) {
+ const condition = rule.conditionText || '';
+ if (!condition || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return true;
+ try { return CSS.supports(condition); }
+ catch { return true; }
+ }
+ return true;
+ }
+
+ function splitCssCommaList(value) {
+ const parts = [];
+ let current = '';
+ let quote = '';
+ let escaped = false;
+ for (const char of String(value || '')) {
+ if (escaped) {
+ current += char;
+ escaped = false;
+ continue;
+ }
+ if (char === '\\') {
+ current += char;
+ escaped = true;
+ continue;
+ }
+ if (quote) {
+ current += char;
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ current += char;
+ continue;
+ }
+ if (char === ',') {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+ return parts;
+ }
+
+ function normalizeAnimationName(value) {
+ const name = String(value || '').trim();
+ if (name.length >= 2 && name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) {
+ return name.slice(1, -1);
+ }
+ return name;
+ }
+
+ function animationNamesDeclaredByRule(rule) {
+ const style = rule?.style;
+ if (!style) return [];
+ let value = '';
+ try {
+ value = style.animationName
+ || style.getPropertyValue?.('animation-name')
+ || style.webkitAnimationName
+ || style.getPropertyValue?.('-webkit-animation-name')
+ || '';
+ } catch {
+ return [];
+ }
+ return splitCssCommaList(value)
+ .map(normalizeAnimationName)
+ .filter(name => name && name.toLowerCase() !== 'none');
+ }
+
+ function keyframesRuleName(rule, cssText) {
+ const constructorName = rule?.constructor?.name || '';
+ const type = Number(rule?.type);
+ const isKeyframes = constructorName === 'CSSKeyframesRule'
+ || constructorName === 'WebKitCSSKeyframesRule'
+ || type === 7
+ || /^\s*@(?:-webkit-)?keyframes\b/i.test(cssText);
+ if (!isKeyframes) return '';
+ const match = String(cssText || '').match(/^\s*@(?:-webkit-)?keyframes\s+([^\s{]+)/i);
+ return normalizeAnimationName(rule?.name || match?.[1] || '');
+ }
+
+ function cssPropertyName(property) {
+ if (property.startsWith('--')) return property;
+ return property.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
+ }
+
+ function resolvedAnimationKeyframes(candidateNames) {
+ if (typeof document.getAnimations !== 'function') return null;
+ let animations;
+ try { animations = document.getAnimations(); }
+ catch { return null; }
+
+ const resolved = new Map();
+ const metadata = new Set(['offset', 'computedOffset', 'easing', 'composite']);
+ for (const animation of animations) {
+ const name = normalizeAnimationName(animation?.animationName || '');
+ if (!name || !candidateNames.has(name) || resolved.has(name)) continue;
+ let frames;
+ try { frames = animation.effect?.getKeyframes?.() || []; }
+ catch { continue; }
+ const blocks = [];
+ for (const frame of frames) {
+ const rawOffset = Number.isFinite(frame.computedOffset) ? frame.computedOffset : frame.offset;
+ if (!Number.isFinite(rawOffset)) continue;
+ const offset = Math.round(rawOffset * 1000000) / 10000;
+ const declarations = Object.entries(frame)
+ .filter(([property, value]) => !metadata.has(property) && value != null && value !== '')
+ .map(([property, value]) => `${cssPropertyName(property)}: ${value};`);
+ const easing = String(frame.easing || '').trim();
+ if (easing && easing.toLowerCase() !== 'linear') {
+ declarations.push(`animation-timing-function: ${easing};`);
+ }
+ if (declarations.length === 0) continue;
+ blocks.push(`${offset}% { ${declarations.join(' ')} }`);
+ }
+ if (blocks.length > 0) resolved.set(name, `@keyframes ${name} { ${blocks.join(' ')} }`);
+ }
+ return resolved;
+ }
+
+ // Read CSS that is absent from document.outerHTML. Inline <style> blocks are
+ // already present in the HTML pattern corpus, so limit this walk to linked
+ // stylesheets. Flatten grouping rules so each declaration keeps its selector,
+ // and admit only selector rules that target the live DOM. That prevents
+ // unused utilities from feeding both selector-scoped and page-level checks.
+ // Same-origin CSS and readable CORS sheets participate; browser security
+ // exceptions for cross-origin sheets are expected and skipped.
+ function linkedStylesheetText() {
+ const parts = [];
+ const seen = new Set();
+ const animationNames = new Set();
+ const keyframeCandidates = new Map();
+ const appendRules = (rules, requiresAppliedMatch = false) => {
+ for (const rule of rules) {
+ if (rule.styleSheet) {
+ appendSheet(rule.styleSheet);
+ continue;
+ }
+ const cssText = rule.cssText || '';
+ if (rule.selectorText) {
+ const matches = selectorNodesForLiveDom(document, rule.selectorText);
+ // Only declarations with a resolvable live host enter the corpus.
+ // Unresolvable selectors are uncertain, not evidence that a pattern
+ // rendered, and retaining them would leak unused CSS into findings.
+ if (
+ matches?.length > 0
+ && (!requiresAppliedMatch || styleRuleAppliesToLiveMatches(rule, matches))
+ ) {
+ parts.push(cssText);
+ for (const name of animationNamesDeclaredByRule(rule)) animationNames.add(name);
+ }
+ continue;
+ }
+ let nested = [];
+ let hasNestedRules = false;
+ try {
+ const ruleList = rule.cssRules;
+ hasNestedRules = ruleList != null;
+ nested = Array.from(ruleList || []);
+ } catch {
+ continue;
+ }
+ const keyframesName = keyframesRuleName(rule, cssText);
+ if (keyframesName) {
+ // Keyframes do not merge: when a name is defined more than once, the
+ // later effective definition replaces the earlier one.
+ keyframeCandidates.set(keyframesName, {
+ name: keyframesName,
+ cssText,
+ });
+ continue;
+ }
+ if (hasNestedRules) {
+ if (!conditionalCssRuleIsActive(rule)) continue;
+ appendRules(nested, requiresAppliedMatch || isContainerCssRule(rule));
+ continue;
+ }
+ // Other selector-less leaf at-rules cannot be tied to a rendered node.
+ }
+ };
+ const appendSheet = (sheet) => {
+ if (!sheet || seen.has(sheet)) return;
+ seen.add(sheet);
+ let rules;
+ try { rules = Array.from(sheet.cssRules || sheet.rules || []); }
+ catch { return; }
+ appendRules(rules);
+ };
+ let sheets;
+ try { sheets = Array.from(document.styleSheets || []); }
+ catch { return ''; }
+ for (const sheet of sheets) {
+ const owner = sheet.ownerNode;
+ if (owner?.tagName?.toLowerCase() !== 'link') continue;
+ if (!/\bstylesheet\b/i.test(owner.getAttribute?.('rel') || '')) continue;
+ appendSheet(sheet);
+ }
+ // Motion checks need the effective body of a live animation's keyframes.
+ // Let the browser resolve duplicate names across source order, imports,
+ // conditional groups, and cascade layers, then serialize those computed
+ // frames back into the pattern corpus. Browsers also make container-nested
+ // keyframes globally available, so lexical grouping is not a reliable
+ // activity signal. When the Web Animations API is unavailable, fall back to
+ // the last source-order definition referenced by a retained linked rule.
+ const resolvedKeyframes = resolvedAnimationKeyframes(new Set(keyframeCandidates.keys()));
+ if (resolvedKeyframes) {
+ parts.push(...resolvedKeyframes.values());
+ } else {
+ for (const candidate of keyframeCandidates.values()) {
+ if (!animationNames.has(candidate.name)) continue;
+ parts.push(candidate.cssText);
+ }
+ }
+ return parts.join('\n');
+ }
+
function browserFindingsFromMap(groupMap) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
@@ -1650,18 +2028,16 @@ if (IS_BROWSER) {
// (the CSS ships here, but the pattern never renders — the live DOM is
// ground truth in the browser), and a match under a data-impeccable-ignore
// ancestor is waived. Selector-less findings stay page-level.
- const scopedHtmlFindings = checkHtmlPatterns(docClone.outerHTML).filter(f => {
+ const html = docClone.outerHTML;
+ const corpora = buildHtmlPatternCorpora(html);
+ const linkedCss = linkedStylesheetText();
+ if (linkedCss) corpora.styleText += `\n${linkedCss}`;
+ const scopedHtmlFindings = checkHtmlPatterns(html, corpora).filter(f => {
if (!f.selector) return true;
- const query = String(f.selector).replace(/::?[a-zA-Z-]+(\([^)]*\))?/g, '').trim().replace(/,\s*(?=,|$)/g, '');
- if (!query || /^[,\s]*$/.test(query)) return true;
- let matches;
- try {
- matches = document.querySelectorAll(query);
- } catch {
- return true;
- }
+ const matches = selectorNodesForLiveDom(document, f.selector);
+ if (!matches) return false;
if (matches.length === 0) return false;
- return [...matches].some(el => !scopedIgnoreActive(el, f.id));
+ return matches.some(el => !scopedIgnoreActive(el, f.id));
});
if (scopedHtmlFindings.length > 0) {
const mapped = scopedHtmlFindings.map(f => {
diff --git a/.vibe/skills/impeccable/scripts/detector/cli/main.mjs b/.vibe/skills/impeccable/scripts/detector/cli/main.mjs
index 4476d04f1..3451d6c6b 100644
--- a/.vibe/skills/impeccable/scripts/detector/cli/main.mjs
+++ b/.vibe/skills/impeccable/scripts/detector/cli/main.mjs
@@ -37,13 +37,30 @@ function fileUrlToLocalPath(url) {
}
}
+const URL_TARGET_RE = /^(?:https?|file):\/\//i;
+
+// Some agent runners hand a shell-ready URL list to Node as one argv value.
+// A browser accepts the spaces as part of one encoded URL, producing a
+// plausible scan attributed to a bogus joined path. Expand only when every
+// whitespace-delimited token is independently a URL, preserving ordinary
+// filesystem paths that contain spaces.
+function expandJoinedUrlTargets(targets) {
+ return targets.flatMap((target) => {
+ if (!/\s/.test(target)) return [target];
+ const parts = target.trim().split(/\s+/).filter(Boolean);
+ return parts.length > 1 && parts.every(part => URL_TARGET_RE.test(part))
+ ? parts
+ : [target];
+ });
+}
+
// Advisory findings are detected but never treated as failures: they list in a
// separate, visually dimmed section, are excluded from the failure count that
// drives the exit code, and carry `"advisory": true` in JSON so consumers can
// filter. Every advisory finding carries the flag (stamped by the registry via
// findings.mjs).
function isAdvisory(finding) {
- return finding && finding.advisory === true;
+ return Boolean(finding && (finding.advisory === true || finding.severity === 'advisory'));
}
function partitionAdvisory(findings) {
@@ -168,6 +185,10 @@ Advisory findings:
counted as failures and never changing the exit code. They stay out of the
failure count so they never block automation. --no-advisory hides them.
+Output streams:
+ Human-readable findings go to stderr so stdout stays available for structured
+ output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.
+
Project config:
Respects .impeccable/config.json and .impeccable/config.local.json detector
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
@@ -185,7 +206,7 @@ Detection modes:
HTML files Static HTML/CSS analysis (default, catches linked CSS)
Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)
URLs Puppeteer full browser rendering (auto-detected;
- http(s):// and file:// URLs)
+ http(s):// and file:// URLs; accessible linked CSS included)
Examples:
impeccable detect src/
@@ -283,7 +304,7 @@ async function detectCli() {
const designSystem = loadDesignSystemForTarget(localPath, { cache: designSystemCache });
return designSystem ? { ...baseScanOptions, designSystem } : baseScanOptions;
};
- const targets = args.filter(a => !a.startsWith('--'));
+ const targets = expandJoinedUrlTargets(args.filter(a => !a.startsWith('--')));
if (helpMode) { printUsage(); process.exit(0); }
@@ -297,13 +318,12 @@ async function detectCli() {
// real cascade, real computed styles, real layout. Callers that want a
// browser-grade scan of a local artifact can pass file:///abs/path.html
// instead of the bare path (which stays on the static engine).
- const urlRe = /^(?:https?|file):\/\//i;
- const urlTargetCount = paths.filter(target => urlRe.test(target)).length;
+ const urlTargetCount = paths.filter(target => URL_TARGET_RE.test(target)).length;
const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
try {
for (const target of paths) {
- if (urlRe.test(target)) {
+ if (URL_TARGET_RE.test(target)) {
// A file:// URL points at a local artifact, so its design system
// resolves from that file's project. A remote http(s) URL has no
// local project — it gets base options (no design system), never
diff --git a/.vibe/skills/impeccable/scripts/detector/detect-antipatterns-browser.js b/.vibe/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
index e6899f569..460ffb45b 100644
--- a/.vibe/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
+++ b/.vibe/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
@@ -358,7 +358,7 @@ const ANTIPATTERNS = [
// rather than a failure. It fires only on the AI saturation pattern, not on
// ordinary prose. Advisory findings are surfaced separately, never counted
// as failures, and skipped by the design hook unless a project opts in.
- advisory: true,
+ severity: 'advisory',
name: 'Em-dash overuse',
description:
'Em-dash saturation in body copy is an AI cadence tell. Advisory only: humans use em-dashes legitimately, so this fires only on saturation — at least 8 em-dashes (— or --) at a density near one per 500 characters of body text — never on a long article that uses a few. Prefer commas, colons, periods, or parentheses.',
@@ -1961,7 +1961,10 @@ function enclosingCssSelector(cssText, index) {
// `{` belongs to some other selector.
const closeBeforeIndex = cssText.lastIndexOf('}', index);
if (closeBeforeIndex > open) return null;
- const prevClose = Math.max(cssText.lastIndexOf('}', open - 1), cssText.lastIndexOf(';', open - 1));
+ // Ignore delimiters inside comments when locating the previous declaration.
+ // Keeping comment length intact preserves indices into the original source.
+ const beforeOpen = cssText.slice(0, open).replace(/\/\*[\s\S]*?\*\//g, comment => ' '.repeat(comment.length));
+ const prevClose = Math.max(beforeOpen.lastIndexOf('}'), beforeOpen.lastIndexOf(';'));
const raw = cssText.slice(prevClose + 1, open).replace(/\/\*[\s\S]*?\*\//g, '').trim().replace(/\s+/g, ' ');
if (!raw || raw.startsWith('@') || /^\d/.test(raw) || /[{}<]/.test(raw)) return null;
// Keyframe steps: percentage steps fail the digit test above, but `from`
@@ -5293,14 +5296,17 @@ function checkTypography() {
}
if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
+ // Report the actual primary face: the uniquely most-used family. The old
+ // 15% threshold labeled secondary faces as primary (e.g. an 82/18 split).
+ const ranked = [...fontUsage.entries()].sort((a, b) => b[1] - a[1]);
+ const [primary] = ranked;
+ const tied = ranked[1]?.[1] === primary?.[1];
+ if (primary && !tied) {
+ const [font, count] = primary;
const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ if (OVERUSED_FONTS.has(font) && !isBrandFontOnOwnDomain(font)) {
+ findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ }
}
}
@@ -8126,14 +8132,17 @@ if (IS_BROWSER) {
isHidden: isElementHidden(el),
findings: findings.map(f => {
const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
+ const severity = f.severity || ap?.severity || 'warning';
return {
type: f.type || f.id,
category: ap ? ap.category : 'quality',
- severity: f.severity || ap?.severity || 'warning',
+ severity,
// Advisory findings (em-dash overuse, etc.) are surfaced but never
// treated as failures; carry the flag so the overlay/extension can
// render them with the mildest affordance and consumers can filter.
- advisory: (ap && ap.advisory === true) || f.advisory === true,
+ // Per-finding promotions override the registry default, so derive
+ // this strictly from the effective severity.
+ advisory: severity === 'advisory',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
@@ -8175,6 +8184,381 @@ if (IS_BROWSER) {
else groupMap.set(el, [...kept]);
}
+ function pseudoElementHostSelector(selector) {
+ const raw = String(selector || '');
+ const legacyNames = new Set(['before', 'after', 'first-letter', 'first-line']);
+ const isNameChar = char => /[a-zA-Z0-9_-]/.test(char || '');
+ const consumeFunction = (start) => {
+ let depth = 0;
+ let quote = '';
+ for (let i = start; i < raw.length; i += 1) {
+ const char = raw[i];
+ if (char === '\\') {
+ i += 1;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '(') depth += 1;
+ if (char === ')' && --depth === 0) return i + 1;
+ }
+ return raw.length;
+ };
+
+ let output = '';
+ let found = false;
+ for (let i = 0; i < raw.length;) {
+ const char = raw[i];
+ if (char === '\\') {
+ output += raw.slice(i, Math.min(raw.length, i + 2));
+ i += 2;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ const quote = char;
+ const start = i;
+ i += 1;
+ while (i < raw.length) {
+ if (raw[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ const value = raw[i];
+ i += 1;
+ if (value === quote) break;
+ }
+ output += raw.slice(start, i);
+ continue;
+ }
+ if (char !== ':') {
+ output += char;
+ i += 1;
+ continue;
+ }
+
+ let end = i + 1;
+ let isPseudoElement = false;
+ if (raw[end] === ':') {
+ end += 1;
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = end > nameStart;
+ } else {
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = legacyNames.has(raw.slice(nameStart, end).toLowerCase());
+ }
+ if (!isPseudoElement) {
+ output += char;
+ i += 1;
+ continue;
+ }
+ if (raw[end] === '(') end = consumeFunction(end);
+ found = true;
+ if (!output || /[\s>+~,]/.test(output[output.length - 1])) output += '*';
+ i = end;
+ }
+ if (!found) return null;
+ return output.trim().replace(/,\s*(?=,|$)/g, '');
+ }
+
+ function selectorNodesForLiveDom(root, selector) {
+ const raw = String(selector || '').trim();
+ if (!raw) return null;
+ const fallback = pseudoElementHostSelector(raw);
+ if (fallback == null) {
+ // An empty result from a valid full selector is authoritative. In
+ // particular, do not broaden inactive :hover/:focus/:not() rules to
+ // their host element by stripping pseudo-classes.
+ try { return Array.from(root.querySelectorAll(raw)); }
+ catch { return null; }
+ }
+
+ // Resolve pseudo-elements to their originating live elements. An attached
+ // pseudo-element (`.card::before`) belongs to the element before it, while
+ // a hostless pseudo-element after a combinator (`main > ::before`) belongs
+ // to a matching element at that position (`main > *`). Replacing every
+ // pseudo indiscriminately with an empty string leaves the latter as the
+ // invalid selector `main >` and makes absent hosts indistinguishable from
+ // selectors the DOM API cannot parse.
+ if (!fallback || /^[,\s]*$/.test(fallback)) return null;
+ try { return Array.from(root.querySelectorAll(fallback)); }
+ catch { return null; }
+ }
+
+ let containerProbeSequence = 0;
+
+ function isContainerCssRule(rule) {
+ return rule?.constructor?.name === 'CSSContainerRule'
+ || /^\s*@container\b/i.test(rule?.cssText || '');
+ }
+
+ function styleRuleAppliesToLiveMatches(rule, matches) {
+ const style = rule?.style;
+ if (!style || !matches?.length || typeof getComputedStyle !== 'function') return false;
+ const sequence = ++containerProbeSequence;
+ const property = `--impeccable-container-probe-${sequence}-${Math.random().toString(36).slice(2)}`;
+ const value = `impeccable-container-active-${sequence}`;
+ const previousValue = style.getPropertyValue(property);
+ const previousPriority = style.getPropertyPriority(property);
+ try {
+ style.setProperty(property, value, 'important');
+ } catch {
+ return false;
+ }
+
+ const pseudoElements = [...new Set(
+ String(rule.selectorText || '').match(/::[a-zA-Z-]+(?:\([^)]*\))?/g) || [],
+ )];
+ try {
+ return matches.some(el => [null, ...pseudoElements].some(pseudo => {
+ try {
+ const computed = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el);
+ return computed.getPropertyValue(property).trim() === value;
+ } catch {
+ return false;
+ }
+ }));
+ } finally {
+ if (previousValue) style.setProperty(property, previousValue, previousPriority);
+ else style.removeProperty(property);
+ }
+ }
+
+ function conditionalCssRuleIsActive(rule) {
+ const type = Number(rule?.type);
+ const constructorName = rule?.constructor?.name || '';
+ if (constructorName === 'CSSMediaRule' || type === 4) {
+ const condition = rule.conditionText || rule.media?.mediaText || '';
+ if (!condition || typeof window.matchMedia !== 'function') return true;
+ try { return window.matchMedia(condition).matches; }
+ catch { return true; }
+ }
+ if (constructorName === 'CSSSupportsRule' || type === 12) {
+ const condition = rule.conditionText || '';
+ if (!condition || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return true;
+ try { return CSS.supports(condition); }
+ catch { return true; }
+ }
+ return true;
+ }
+
+ function splitCssCommaList(value) {
+ const parts = [];
+ let current = '';
+ let quote = '';
+ let escaped = false;
+ for (const char of String(value || '')) {
+ if (escaped) {
+ current += char;
+ escaped = false;
+ continue;
+ }
+ if (char === '\\') {
+ current += char;
+ escaped = true;
+ continue;
+ }
+ if (quote) {
+ current += char;
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ current += char;
+ continue;
+ }
+ if (char === ',') {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+ return parts;
+ }
+
+ function normalizeAnimationName(value) {
+ const name = String(value || '').trim();
+ if (name.length >= 2 && name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) {
+ return name.slice(1, -1);
+ }
+ return name;
+ }
+
+ function animationNamesDeclaredByRule(rule) {
+ const style = rule?.style;
+ if (!style) return [];
+ let value = '';
+ try {
+ value = style.animationName
+ || style.getPropertyValue?.('animation-name')
+ || style.webkitAnimationName
+ || style.getPropertyValue?.('-webkit-animation-name')
+ || '';
+ } catch {
+ return [];
+ }
+ return splitCssCommaList(value)
+ .map(normalizeAnimationName)
+ .filter(name => name && name.toLowerCase() !== 'none');
+ }
+
+ function keyframesRuleName(rule, cssText) {
+ const constructorName = rule?.constructor?.name || '';
+ const type = Number(rule?.type);
+ const isKeyframes = constructorName === 'CSSKeyframesRule'
+ || constructorName === 'WebKitCSSKeyframesRule'
+ || type === 7
+ || /^\s*@(?:-webkit-)?keyframes\b/i.test(cssText);
+ if (!isKeyframes) return '';
+ const match = String(cssText || '').match(/^\s*@(?:-webkit-)?keyframes\s+([^\s{]+)/i);
+ return normalizeAnimationName(rule?.name || match?.[1] || '');
+ }
+
+ function cssPropertyName(property) {
+ if (property.startsWith('--')) return property;
+ return property.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
+ }
+
+ function resolvedAnimationKeyframes(candidateNames) {
+ if (typeof document.getAnimations !== 'function') return null;
+ let animations;
+ try { animations = document.getAnimations(); }
+ catch { return null; }
+
+ const resolved = new Map();
+ const metadata = new Set(['offset', 'computedOffset', 'easing', 'composite']);
+ for (const animation of animations) {
+ const name = normalizeAnimationName(animation?.animationName || '');
+ if (!name || !candidateNames.has(name) || resolved.has(name)) continue;
+ let frames;
+ try { frames = animation.effect?.getKeyframes?.() || []; }
+ catch { continue; }
+ const blocks = [];
+ for (const frame of frames) {
+ const rawOffset = Number.isFinite(frame.computedOffset) ? frame.computedOffset : frame.offset;
+ if (!Number.isFinite(rawOffset)) continue;
+ const offset = Math.round(rawOffset * 1000000) / 10000;
+ const declarations = Object.entries(frame)
+ .filter(([property, value]) => !metadata.has(property) && value != null && value !== '')
+ .map(([property, value]) => `${cssPropertyName(property)}: ${value};`);
+ const easing = String(frame.easing || '').trim();
+ if (easing && easing.toLowerCase() !== 'linear') {
+ declarations.push(`animation-timing-function: ${easing};`);
+ }
+ if (declarations.length === 0) continue;
+ blocks.push(`${offset}% { ${declarations.join(' ')} }`);
+ }
+ if (blocks.length > 0) resolved.set(name, `@keyframes ${name} { ${blocks.join(' ')} }`);
+ }
+ return resolved;
+ }
+
+ // Read CSS that is absent from document.outerHTML. Inline <style> blocks are
+ // already present in the HTML pattern corpus, so limit this walk to linked
+ // stylesheets. Flatten grouping rules so each declaration keeps its selector,
+ // and admit only selector rules that target the live DOM. That prevents
+ // unused utilities from feeding both selector-scoped and page-level checks.
+ // Same-origin CSS and readable CORS sheets participate; browser security
+ // exceptions for cross-origin sheets are expected and skipped.
+ function linkedStylesheetText() {
+ const parts = [];
+ const seen = new Set();
+ const animationNames = new Set();
+ const keyframeCandidates = new Map();
+ const appendRules = (rules, requiresAppliedMatch = false) => {
+ for (const rule of rules) {
+ if (rule.styleSheet) {
+ appendSheet(rule.styleSheet);
+ continue;
+ }
+ const cssText = rule.cssText || '';
+ if (rule.selectorText) {
+ const matches = selectorNodesForLiveDom(document, rule.selectorText);
+ // Only declarations with a resolvable live host enter the corpus.
+ // Unresolvable selectors are uncertain, not evidence that a pattern
+ // rendered, and retaining them would leak unused CSS into findings.
+ if (
+ matches?.length > 0
+ && (!requiresAppliedMatch || styleRuleAppliesToLiveMatches(rule, matches))
+ ) {
+ parts.push(cssText);
+ for (const name of animationNamesDeclaredByRule(rule)) animationNames.add(name);
+ }
+ continue;
+ }
+ let nested = [];
+ let hasNestedRules = false;
+ try {
+ const ruleList = rule.cssRules;
+ hasNestedRules = ruleList != null;
+ nested = Array.from(ruleList || []);
+ } catch {
+ continue;
+ }
+ const keyframesName = keyframesRuleName(rule, cssText);
+ if (keyframesName) {
+ // Keyframes do not merge: when a name is defined more than once, the
+ // later effective definition replaces the earlier one.
+ keyframeCandidates.set(keyframesName, {
+ name: keyframesName,
+ cssText,
+ });
+ continue;
+ }
+ if (hasNestedRules) {
+ if (!conditionalCssRuleIsActive(rule)) continue;
+ appendRules(nested, requiresAppliedMatch || isContainerCssRule(rule));
+ continue;
+ }
+ // Other selector-less leaf at-rules cannot be tied to a rendered node.
+ }
+ };
+ const appendSheet = (sheet) => {
+ if (!sheet || seen.has(sheet)) return;
+ seen.add(sheet);
+ let rules;
+ try { rules = Array.from(sheet.cssRules || sheet.rules || []); }
+ catch { return; }
+ appendRules(rules);
+ };
+ let sheets;
+ try { sheets = Array.from(document.styleSheets || []); }
+ catch { return ''; }
+ for (const sheet of sheets) {
+ const owner = sheet.ownerNode;
+ if (owner?.tagName?.toLowerCase() !== 'link') continue;
+ if (!/\bstylesheet\b/i.test(owner.getAttribute?.('rel') || '')) continue;
+ appendSheet(sheet);
+ }
+ // Motion checks need the effective body of a live animation's keyframes.
+ // Let the browser resolve duplicate names across source order, imports,
+ // conditional groups, and cascade layers, then serialize those computed
+ // frames back into the pattern corpus. Browsers also make container-nested
+ // keyframes globally available, so lexical grouping is not a reliable
+ // activity signal. When the Web Animations API is unavailable, fall back to
+ // the last source-order definition referenced by a retained linked rule.
+ const resolvedKeyframes = resolvedAnimationKeyframes(new Set(keyframeCandidates.keys()));
+ if (resolvedKeyframes) {
+ parts.push(...resolvedKeyframes.values());
+ } else {
+ for (const candidate of keyframeCandidates.values()) {
+ if (!animationNames.has(candidate.name)) continue;
+ parts.push(candidate.cssText);
+ }
+ }
+ return parts.join('\n');
+ }
+
function browserFindingsFromMap(groupMap) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
@@ -8548,18 +8932,16 @@ if (IS_BROWSER) {
// (the CSS ships here, but the pattern never renders — the live DOM is
// ground truth in the browser), and a match under a data-impeccable-ignore
// ancestor is waived. Selector-less findings stay page-level.
- const scopedHtmlFindings = checkHtmlPatterns(docClone.outerHTML).filter(f => {
+ const html = docClone.outerHTML;
+ const corpora = buildHtmlPatternCorpora(html);
+ const linkedCss = linkedStylesheetText();
+ if (linkedCss) corpora.styleText += `\n${linkedCss}`;
+ const scopedHtmlFindings = checkHtmlPatterns(html, corpora).filter(f => {
if (!f.selector) return true;
- const query = String(f.selector).replace(/::?[a-zA-Z-]+(\([^)]*\))?/g, '').trim().replace(/,\s*(?=,|$)/g, '');
- if (!query || /^[,\s]*$/.test(query)) return true;
- let matches;
- try {
- matches = document.querySelectorAll(query);
- } catch {
- return true;
- }
+ const matches = selectorNodesForLiveDom(document, f.selector);
+ if (!matches) return false;
if (matches.length === 0) return false;
- return [...matches].some(el => !scopedIgnoreActive(el, f.id));
+ return matches.some(el => !scopedIgnoreActive(el, f.id));
});
if (scopedHtmlFindings.length > 0) {
const mapped = scopedHtmlFindings.map(f => {
diff --git a/.vibe/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs b/.vibe/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
index f3ff43c84..ac4bd0a7c 100644
--- a/.vibe/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
+++ b/.vibe/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
@@ -2,7 +2,7 @@ import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { finding } from '../../findings.mjs';
+import { deriveAdvisoryFlag, finding } from '../../findings.mjs';
import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
import { checkContentHiddenAtRest } from '../../rules/checks.mjs';
@@ -394,7 +394,7 @@ async function detectUrl(rawUrl, options = {}) {
// Per-finding severity promotion (e.g. hero-region pulsing dot)
// overrides the registry default carried by finding().
if (f.severity && f.severity !== item.severity) item.severity = f.severity;
- return item;
+ return deriveAdvisoryFlag(item);
});
}
diff --git a/.vibe/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs b/.vibe/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
index 84e6ab1f5..dac6939b0 100644
--- a/.vibe/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
+++ b/.vibe/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
@@ -9,7 +9,7 @@ import {
} from '../../design-system.mjs';
import { isFullPage } from '../../shared/page.mjs';
import { applyInlineIgnores } from '../../shared/inline-ignores.mjs';
-import { finding } from '../../findings.mjs';
+import { deriveAdvisoryFlag, finding } from '../../findings.mjs';
import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import {
checkElementBorders,
@@ -257,7 +257,7 @@ async function detectHtml(filePath, options = {}) {
// severity (e.g. a pulsing dot inside a header/nav landmark) that
// overrides the registry default.
if (f.severity) item.severity = f.severity;
- findings.push(item);
+ findings.push(deriveAdvisoryFlag(item));
}
// Text-content analyzers (em-dash overuse, marketing buzzwords,
// numbered section markers, aphoristic cadence) live in the regex
diff --git a/.vibe/skills/impeccable/scripts/detector/findings.mjs b/.vibe/skills/impeccable/scripts/detector/findings.mjs
index fa98dd935..ae7e134f9 100644
--- a/.vibe/skills/impeccable/scripts/detector/findings.mjs
+++ b/.vibe/skills/impeccable/scripts/detector/findings.mjs
@@ -4,6 +4,12 @@ function getAP(id) {
return getAntipattern(id);
}
+function deriveAdvisoryFlag(item) {
+ if (item.severity === 'advisory') item.advisory = true;
+ else delete item.advisory;
+ return item;
+}
+
function finding(id, filePath, snippet, line = 0) {
const ap = getAP(id);
const base = { antipattern: id, name: ap.name, description: ap.description, severity: ap.severity || 'warning', category: ap.category || null, file: filePath, line, snippet };
@@ -11,8 +17,7 @@ function finding(id, filePath, snippet, line = 0) {
// failures. Carry the flag on the finding so every consumer (CLI, JSON, hook)
// can partition without a registry lookup. Only stamped when true to keep the
// finding shape stable for the vast majority of rules.
- if (ap.advisory === true) base.advisory = true;
- return base;
+ return deriveAdvisoryFlag(base);
}
-export { getAP, finding };
+export { getAP, finding, deriveAdvisoryFlag };
diff --git a/.vibe/skills/impeccable/scripts/detector/registry/antipatterns.mjs b/.vibe/skills/impeccable/scripts/detector/registry/antipatterns.mjs
index 945307783..7c692c79a 100644
--- a/.vibe/skills/impeccable/scripts/detector/registry/antipatterns.mjs
+++ b/.vibe/skills/impeccable/scripts/detector/registry/antipatterns.mjs
@@ -233,7 +233,7 @@ const ANTIPATTERNS = [
// rather than a failure. It fires only on the AI saturation pattern, not on
// ordinary prose. Advisory findings are surfaced separately, never counted
// as failures, and skipped by the design hook unless a project opts in.
- advisory: true,
+ severity: 'advisory',
name: 'Em-dash overuse',
description:
'Em-dash saturation in body copy is an AI cadence tell. Advisory only: humans use em-dashes legitimately, so this fires only on saturation — at least 8 em-dashes (— or --) at a density near one per 500 characters of body text — never on a long article that uses a few. Prefer commas, colons, periods, or parentheses.',
@@ -588,9 +588,10 @@ function getAntipattern(id) {
// Advisory rules are detected and reported, but never treated as failures:
// the CLI lists them under a separate "Advisory" section, they do not affect
// exit codes or the failure count, and the design hook skips them by default.
-// The set is derived from the registry so a rule only needs `advisory: true`.
+// `severity` is the canonical registry field. The runtime finding serializer
+// derives its `advisory: true` compatibility/output flag from this set.
const ADVISORY_RULE_IDS = new Set(
- ANTIPATTERNS.filter(rule => rule.advisory === true).map(rule => rule.id),
+ ANTIPATTERNS.filter(rule => rule.severity === 'advisory').map(rule => rule.id),
);
function isAdvisoryRule(id) {
diff --git a/.vibe/skills/impeccable/scripts/detector/rules/checks.mjs b/.vibe/skills/impeccable/scripts/detector/rules/checks.mjs
index 579e1c12e..a24631ce9 100644
--- a/.vibe/skills/impeccable/scripts/detector/rules/checks.mjs
+++ b/.vibe/skills/impeccable/scripts/detector/rules/checks.mjs
@@ -688,7 +688,10 @@ function enclosingCssSelector(cssText, index) {
// `{` belongs to some other selector.
const closeBeforeIndex = cssText.lastIndexOf('}', index);
if (closeBeforeIndex > open) return null;
- const prevClose = Math.max(cssText.lastIndexOf('}', open - 1), cssText.lastIndexOf(';', open - 1));
+ // Ignore delimiters inside comments when locating the previous declaration.
+ // Keeping comment length intact preserves indices into the original source.
+ const beforeOpen = cssText.slice(0, open).replace(/\/\*[\s\S]*?\*\//g, comment => ' '.repeat(comment.length));
+ const prevClose = Math.max(beforeOpen.lastIndexOf('}'), beforeOpen.lastIndexOf(';'));
const raw = cssText.slice(prevClose + 1, open).replace(/\/\*[\s\S]*?\*\//g, '').trim().replace(/\s+/g, ' ');
if (!raw || raw.startsWith('@') || /^\d/.test(raw) || /[{}<]/.test(raw)) return null;
// Keyframe steps: percentage steps fail the digit test above, but `from`
@@ -4020,14 +4023,17 @@ function checkTypography() {
}
if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
+ // Report the actual primary face: the uniquely most-used family. The old
+ // 15% threshold labeled secondary faces as primary (e.g. an 82/18 split).
+ const ranked = [...fontUsage.entries()].sort((a, b) => b[1] - a[1]);
+ const [primary] = ranked;
+ const tied = ranked[1]?.[1] === primary?.[1];
+ if (primary && !tied) {
+ const [font, count] = primary;
const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ if (OVERUSED_FONTS.has(font) && !isBrandFontOnOwnDomain(font)) {
+ findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ }
}
}
diff --git a/.vibe/skills/impeccable/scripts/hook-lib.mjs b/.vibe/skills/impeccable/scripts/hook-lib.mjs
index 767fe65a6..6d8c3db81 100644
--- a/.vibe/skills/impeccable/scripts/hook-lib.mjs
+++ b/.vibe/skills/impeccable/scripts/hook-lib.mjs
@@ -138,17 +138,20 @@ export const IMMEDIATE_TIER_RULES = new Set([
// the agent is never nagged about a taste call a human might make on purpose.
// A project opts back in with `.impeccable/config.json`:
// { "detector": { "advisoryRules": "include" } }
-// This set is the hook's own copy of the registry's `advisory: true` rules,
-// mirroring how IMMEDIATE_TIER_RULES lists rule ids inline so the hook stays
-// self-contained and testable without loading the detector. Keep it in sync
-// with the registry (cli/engine/registry/antipatterns.mjs).
+// This legacy id fallback keeps older detector findings recognizable when they
+// carry neither the current runtime flag nor the canonical advisory severity.
+// Current findings are classified by their serialized metadata below.
export const ADVISORY_RULES = new Set([
'em-dash-overuse',
]);
export function isAdvisoryFinding(finding) {
const id = finding && normalizeIgnoreRule(finding.antipattern);
- return Boolean(id && (ADVISORY_RULES.has(id) || finding.advisory === true));
+ return Boolean(id && (
+ ADVISORY_RULES.has(id)
+ || finding.advisory === true
+ || finding.severity === 'advisory'
+ ));
}
export const DEFAULT_CONFIG = Object.freeze({
diff --git a/plugin/skills/impeccable/scripts/detector/browser/injected/index.mjs b/plugin/skills/impeccable/scripts/detector/browser/injected/index.mjs
index febf7f297..76fc558e5 100644
--- a/plugin/skills/impeccable/scripts/detector/browser/injected/index.mjs
+++ b/plugin/skills/impeccable/scripts/detector/browser/injected/index.mjs
@@ -1228,14 +1228,17 @@ if (IS_BROWSER) {
isHidden: isElementHidden(el),
findings: findings.map(f => {
const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
+ const severity = f.severity || ap?.severity || 'warning';
return {
type: f.type || f.id,
category: ap ? ap.category : 'quality',
- severity: f.severity || ap?.severity || 'warning',
+ severity,
// Advisory findings (em-dash overuse, etc.) are surfaced but never
// treated as failures; carry the flag so the overlay/extension can
// render them with the mildest affordance and consumers can filter.
- advisory: (ap && ap.advisory === true) || f.advisory === true,
+ // Per-finding promotions override the registry default, so derive
+ // this strictly from the effective severity.
+ advisory: severity === 'advisory',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
@@ -1277,6 +1280,381 @@ if (IS_BROWSER) {
else groupMap.set(el, [...kept]);
}
+ function pseudoElementHostSelector(selector) {
+ const raw = String(selector || '');
+ const legacyNames = new Set(['before', 'after', 'first-letter', 'first-line']);
+ const isNameChar = char => /[a-zA-Z0-9_-]/.test(char || '');
+ const consumeFunction = (start) => {
+ let depth = 0;
+ let quote = '';
+ for (let i = start; i < raw.length; i += 1) {
+ const char = raw[i];
+ if (char === '\\') {
+ i += 1;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '(') depth += 1;
+ if (char === ')' && --depth === 0) return i + 1;
+ }
+ return raw.length;
+ };
+
+ let output = '';
+ let found = false;
+ for (let i = 0; i < raw.length;) {
+ const char = raw[i];
+ if (char === '\\') {
+ output += raw.slice(i, Math.min(raw.length, i + 2));
+ i += 2;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ const quote = char;
+ const start = i;
+ i += 1;
+ while (i < raw.length) {
+ if (raw[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ const value = raw[i];
+ i += 1;
+ if (value === quote) break;
+ }
+ output += raw.slice(start, i);
+ continue;
+ }
+ if (char !== ':') {
+ output += char;
+ i += 1;
+ continue;
+ }
+
+ let end = i + 1;
+ let isPseudoElement = false;
+ if (raw[end] === ':') {
+ end += 1;
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = end > nameStart;
+ } else {
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = legacyNames.has(raw.slice(nameStart, end).toLowerCase());
+ }
+ if (!isPseudoElement) {
+ output += char;
+ i += 1;
+ continue;
+ }
+ if (raw[end] === '(') end = consumeFunction(end);
+ found = true;
+ if (!output || /[\s>+~,]/.test(output[output.length - 1])) output += '*';
+ i = end;
+ }
+ if (!found) return null;
+ return output.trim().replace(/,\s*(?=,|$)/g, '');
+ }
+
+ function selectorNodesForLiveDom(root, selector) {
+ const raw = String(selector || '').trim();
+ if (!raw) return null;
+ const fallback = pseudoElementHostSelector(raw);
+ if (fallback == null) {
+ // An empty result from a valid full selector is authoritative. In
+ // particular, do not broaden inactive :hover/:focus/:not() rules to
+ // their host element by stripping pseudo-classes.
+ try { return Array.from(root.querySelectorAll(raw)); }
+ catch { return null; }
+ }
+
+ // Resolve pseudo-elements to their originating live elements. An attached
+ // pseudo-element (`.card::before`) belongs to the element before it, while
+ // a hostless pseudo-element after a combinator (`main > ::before`) belongs
+ // to a matching element at that position (`main > *`). Replacing every
+ // pseudo indiscriminately with an empty string leaves the latter as the
+ // invalid selector `main >` and makes absent hosts indistinguishable from
+ // selectors the DOM API cannot parse.
+ if (!fallback || /^[,\s]*$/.test(fallback)) return null;
+ try { return Array.from(root.querySelectorAll(fallback)); }
+ catch { return null; }
+ }
+
+ let containerProbeSequence = 0;
+
+ function isContainerCssRule(rule) {
+ return rule?.constructor?.name === 'CSSContainerRule'
+ || /^\s*@container\b/i.test(rule?.cssText || '');
+ }
+
+ function styleRuleAppliesToLiveMatches(rule, matches) {
+ const style = rule?.style;
+ if (!style || !matches?.length || typeof getComputedStyle !== 'function') return false;
+ const sequence = ++containerProbeSequence;
+ const property = `--impeccable-container-probe-${sequence}-${Math.random().toString(36).slice(2)}`;
+ const value = `impeccable-container-active-${sequence}`;
+ const previousValue = style.getPropertyValue(property);
+ const previousPriority = style.getPropertyPriority(property);
+ try {
+ style.setProperty(property, value, 'important');
+ } catch {
+ return false;
+ }
+
+ const pseudoElements = [...new Set(
+ String(rule.selectorText || '').match(/::[a-zA-Z-]+(?:\([^)]*\))?/g) || [],
+ )];
+ try {
+ return matches.some(el => [null, ...pseudoElements].some(pseudo => {
+ try {
+ const computed = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el);
+ return computed.getPropertyValue(property).trim() === value;
+ } catch {
+ return false;
+ }
+ }));
+ } finally {
+ if (previousValue) style.setProperty(property, previousValue, previousPriority);
+ else style.removeProperty(property);
+ }
+ }
+
+ function conditionalCssRuleIsActive(rule) {
+ const type = Number(rule?.type);
+ const constructorName = rule?.constructor?.name || '';
+ if (constructorName === 'CSSMediaRule' || type === 4) {
+ const condition = rule.conditionText || rule.media?.mediaText || '';
+ if (!condition || typeof window.matchMedia !== 'function') return true;
+ try { return window.matchMedia(condition).matches; }
+ catch { return true; }
+ }
+ if (constructorName === 'CSSSupportsRule' || type === 12) {
+ const condition = rule.conditionText || '';
+ if (!condition || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return true;
+ try { return CSS.supports(condition); }
+ catch { return true; }
+ }
+ return true;
+ }
+
+ function splitCssCommaList(value) {
+ const parts = [];
+ let current = '';
+ let quote = '';
+ let escaped = false;
+ for (const char of String(value || '')) {
+ if (escaped) {
+ current += char;
+ escaped = false;
+ continue;
+ }
+ if (char === '\\') {
+ current += char;
+ escaped = true;
+ continue;
+ }
+ if (quote) {
+ current += char;
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ current += char;
+ continue;
+ }
+ if (char === ',') {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+ return parts;
+ }
+
+ function normalizeAnimationName(value) {
+ const name = String(value || '').trim();
+ if (name.length >= 2 && name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) {
+ return name.slice(1, -1);
+ }
+ return name;
+ }
+
+ function animationNamesDeclaredByRule(rule) {
+ const style = rule?.style;
+ if (!style) return [];
+ let value = '';
+ try {
+ value = style.animationName
+ || style.getPropertyValue?.('animation-name')
+ || style.webkitAnimationName
+ || style.getPropertyValue?.('-webkit-animation-name')
+ || '';
+ } catch {
+ return [];
+ }
+ return splitCssCommaList(value)
+ .map(normalizeAnimationName)
+ .filter(name => name && name.toLowerCase() !== 'none');
+ }
+
+ function keyframesRuleName(rule, cssText) {
+ const constructorName = rule?.constructor?.name || '';
+ const type = Number(rule?.type);
+ const isKeyframes = constructorName === 'CSSKeyframesRule'
+ || constructorName === 'WebKitCSSKeyframesRule'
+ || type === 7
+ || /^\s*@(?:-webkit-)?keyframes\b/i.test(cssText);
+ if (!isKeyframes) return '';
+ const match = String(cssText || '').match(/^\s*@(?:-webkit-)?keyframes\s+([^\s{]+)/i);
+ return normalizeAnimationName(rule?.name || match?.[1] || '');
+ }
+
+ function cssPropertyName(property) {
+ if (property.startsWith('--')) return property;
+ return property.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
+ }
+
+ function resolvedAnimationKeyframes(candidateNames) {
+ if (typeof document.getAnimations !== 'function') return null;
+ let animations;
+ try { animations = document.getAnimations(); }
+ catch { return null; }
+
+ const resolved = new Map();
+ const metadata = new Set(['offset', 'computedOffset', 'easing', 'composite']);
+ for (const animation of animations) {
+ const name = normalizeAnimationName(animation?.animationName || '');
+ if (!name || !candidateNames.has(name) || resolved.has(name)) continue;
+ let frames;
+ try { frames = animation.effect?.getKeyframes?.() || []; }
+ catch { continue; }
+ const blocks = [];
+ for (const frame of frames) {
+ const rawOffset = Number.isFinite(frame.computedOffset) ? frame.computedOffset : frame.offset;
+ if (!Number.isFinite(rawOffset)) continue;
+ const offset = Math.round(rawOffset * 1000000) / 10000;
+ const declarations = Object.entries(frame)
+ .filter(([property, value]) => !metadata.has(property) && value != null && value !== '')
+ .map(([property, value]) => `${cssPropertyName(property)}: ${value};`);
+ const easing = String(frame.easing || '').trim();
+ if (easing && easing.toLowerCase() !== 'linear') {
+ declarations.push(`animation-timing-function: ${easing};`);
+ }
+ if (declarations.length === 0) continue;
+ blocks.push(`${offset}% { ${declarations.join(' ')} }`);
+ }
+ if (blocks.length > 0) resolved.set(name, `@keyframes ${name} { ${blocks.join(' ')} }`);
+ }
+ return resolved;
+ }
+
+ // Read CSS that is absent from document.outerHTML. Inline <style> blocks are
+ // already present in the HTML pattern corpus, so limit this walk to linked
+ // stylesheets. Flatten grouping rules so each declaration keeps its selector,
+ // and admit only selector rules that target the live DOM. That prevents
+ // unused utilities from feeding both selector-scoped and page-level checks.
+ // Same-origin CSS and readable CORS sheets participate; browser security
+ // exceptions for cross-origin sheets are expected and skipped.
+ function linkedStylesheetText() {
+ const parts = [];
+ const seen = new Set();
+ const animationNames = new Set();
+ const keyframeCandidates = new Map();
+ const appendRules = (rules, requiresAppliedMatch = false) => {
+ for (const rule of rules) {
+ if (rule.styleSheet) {
+ appendSheet(rule.styleSheet);
+ continue;
+ }
+ const cssText = rule.cssText || '';
+ if (rule.selectorText) {
+ const matches = selectorNodesForLiveDom(document, rule.selectorText);
+ // Only declarations with a resolvable live host enter the corpus.
+ // Unresolvable selectors are uncertain, not evidence that a pattern
+ // rendered, and retaining them would leak unused CSS into findings.
+ if (
+ matches?.length > 0
+ && (!requiresAppliedMatch || styleRuleAppliesToLiveMatches(rule, matches))
+ ) {
+ parts.push(cssText);
+ for (const name of animationNamesDeclaredByRule(rule)) animationNames.add(name);
+ }
+ continue;
+ }
+ let nested = [];
+ let hasNestedRules = false;
+ try {
+ const ruleList = rule.cssRules;
+ hasNestedRules = ruleList != null;
+ nested = Array.from(ruleList || []);
+ } catch {
+ continue;
+ }
+ const keyframesName = keyframesRuleName(rule, cssText);
+ if (keyframesName) {
+ // Keyframes do not merge: when a name is defined more than once, the
+ // later effective definition replaces the earlier one.
+ keyframeCandidates.set(keyframesName, {
+ name: keyframesName,
+ cssText,
+ });
+ continue;
+ }
+ if (hasNestedRules) {
+ if (!conditionalCssRuleIsActive(rule)) continue;
+ appendRules(nested, requiresAppliedMatch || isContainerCssRule(rule));
+ continue;
+ }
+ // Other selector-less leaf at-rules cannot be tied to a rendered node.
+ }
+ };
+ const appendSheet = (sheet) => {
+ if (!sheet || seen.has(sheet)) return;
+ seen.add(sheet);
+ let rules;
+ try { rules = Array.from(sheet.cssRules || sheet.rules || []); }
+ catch { return; }
+ appendRules(rules);
+ };
+ let sheets;
+ try { sheets = Array.from(document.styleSheets || []); }
+ catch { return ''; }
+ for (const sheet of sheets) {
+ const owner = sheet.ownerNode;
+ if (owner?.tagName?.toLowerCase() !== 'link') continue;
+ if (!/\bstylesheet\b/i.test(owner.getAttribute?.('rel') || '')) continue;
+ appendSheet(sheet);
+ }
+ // Motion checks need the effective body of a live animation's keyframes.
+ // Let the browser resolve duplicate names across source order, imports,
+ // conditional groups, and cascade layers, then serialize those computed
+ // frames back into the pattern corpus. Browsers also make container-nested
+ // keyframes globally available, so lexical grouping is not a reliable
+ // activity signal. When the Web Animations API is unavailable, fall back to
+ // the last source-order definition referenced by a retained linked rule.
+ const resolvedKeyframes = resolvedAnimationKeyframes(new Set(keyframeCandidates.keys()));
+ if (resolvedKeyframes) {
+ parts.push(...resolvedKeyframes.values());
+ } else {
+ for (const candidate of keyframeCandidates.values()) {
+ if (!animationNames.has(candidate.name)) continue;
+ parts.push(candidate.cssText);
+ }
+ }
+ return parts.join('\n');
+ }
+
function browserFindingsFromMap(groupMap) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
@@ -1650,18 +2028,16 @@ if (IS_BROWSER) {
// (the CSS ships here, but the pattern never renders — the live DOM is
// ground truth in the browser), and a match under a data-impeccable-ignore
// ancestor is waived. Selector-less findings stay page-level.
- const scopedHtmlFindings = checkHtmlPatterns(docClone.outerHTML).filter(f => {
+ const html = docClone.outerHTML;
+ const corpora = buildHtmlPatternCorpora(html);
+ const linkedCss = linkedStylesheetText();
+ if (linkedCss) corpora.styleText += `\n${linkedCss}`;
+ const scopedHtmlFindings = checkHtmlPatterns(html, corpora).filter(f => {
if (!f.selector) return true;
- const query = String(f.selector).replace(/::?[a-zA-Z-]+(\([^)]*\))?/g, '').trim().replace(/,\s*(?=,|$)/g, '');
- if (!query || /^[,\s]*$/.test(query)) return true;
- let matches;
- try {
- matches = document.querySelectorAll(query);
- } catch {
- return true;
- }
+ const matches = selectorNodesForLiveDom(document, f.selector);
+ if (!matches) return false;
if (matches.length === 0) return false;
- return [...matches].some(el => !scopedIgnoreActive(el, f.id));
+ return matches.some(el => !scopedIgnoreActive(el, f.id));
});
if (scopedHtmlFindings.length > 0) {
const mapped = scopedHtmlFindings.map(f => {
diff --git a/plugin/skills/impeccable/scripts/detector/cli/main.mjs b/plugin/skills/impeccable/scripts/detector/cli/main.mjs
index 4476d04f1..3451d6c6b 100644
--- a/plugin/skills/impeccable/scripts/detector/cli/main.mjs
+++ b/plugin/skills/impeccable/scripts/detector/cli/main.mjs
@@ -37,13 +37,30 @@ function fileUrlToLocalPath(url) {
}
}
+const URL_TARGET_RE = /^(?:https?|file):\/\//i;
+
+// Some agent runners hand a shell-ready URL list to Node as one argv value.
+// A browser accepts the spaces as part of one encoded URL, producing a
+// plausible scan attributed to a bogus joined path. Expand only when every
+// whitespace-delimited token is independently a URL, preserving ordinary
+// filesystem paths that contain spaces.
+function expandJoinedUrlTargets(targets) {
+ return targets.flatMap((target) => {
+ if (!/\s/.test(target)) return [target];
+ const parts = target.trim().split(/\s+/).filter(Boolean);
+ return parts.length > 1 && parts.every(part => URL_TARGET_RE.test(part))
+ ? parts
+ : [target];
+ });
+}
+
// Advisory findings are detected but never treated as failures: they list in a
// separate, visually dimmed section, are excluded from the failure count that
// drives the exit code, and carry `"advisory": true` in JSON so consumers can
// filter. Every advisory finding carries the flag (stamped by the registry via
// findings.mjs).
function isAdvisory(finding) {
- return finding && finding.advisory === true;
+ return Boolean(finding && (finding.advisory === true || finding.severity === 'advisory'));
}
function partitionAdvisory(findings) {
@@ -168,6 +185,10 @@ Advisory findings:
counted as failures and never changing the exit code. They stay out of the
failure count so they never block automation. --no-advisory hides them.
+Output streams:
+ Human-readable findings go to stderr so stdout stays available for structured
+ output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.
+
Project config:
Respects .impeccable/config.json and .impeccable/config.local.json detector
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
@@ -185,7 +206,7 @@ Detection modes:
HTML files Static HTML/CSS analysis (default, catches linked CSS)
Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)
URLs Puppeteer full browser rendering (auto-detected;
- http(s):// and file:// URLs)
+ http(s):// and file:// URLs; accessible linked CSS included)
Examples:
impeccable detect src/
@@ -283,7 +304,7 @@ async function detectCli() {
const designSystem = loadDesignSystemForTarget(localPath, { cache: designSystemCache });
return designSystem ? { ...baseScanOptions, designSystem } : baseScanOptions;
};
- const targets = args.filter(a => !a.startsWith('--'));
+ const targets = expandJoinedUrlTargets(args.filter(a => !a.startsWith('--')));
if (helpMode) { printUsage(); process.exit(0); }
@@ -297,13 +318,12 @@ async function detectCli() {
// real cascade, real computed styles, real layout. Callers that want a
// browser-grade scan of a local artifact can pass file:///abs/path.html
// instead of the bare path (which stays on the static engine).
- const urlRe = /^(?:https?|file):\/\//i;
- const urlTargetCount = paths.filter(target => urlRe.test(target)).length;
+ const urlTargetCount = paths.filter(target => URL_TARGET_RE.test(target)).length;
const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
try {
for (const target of paths) {
- if (urlRe.test(target)) {
+ if (URL_TARGET_RE.test(target)) {
// A file:// URL points at a local artifact, so its design system
// resolves from that file's project. A remote http(s) URL has no
// local project — it gets base options (no design system), never
diff --git a/plugin/skills/impeccable/scripts/detector/detect-antipatterns-browser.js b/plugin/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
index e6899f569..460ffb45b 100644
--- a/plugin/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
+++ b/plugin/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
@@ -358,7 +358,7 @@ const ANTIPATTERNS = [
// rather than a failure. It fires only on the AI saturation pattern, not on
// ordinary prose. Advisory findings are surfaced separately, never counted
// as failures, and skipped by the design hook unless a project opts in.
- advisory: true,
+ severity: 'advisory',
name: 'Em-dash overuse',
description:
'Em-dash saturation in body copy is an AI cadence tell. Advisory only: humans use em-dashes legitimately, so this fires only on saturation — at least 8 em-dashes (— or --) at a density near one per 500 characters of body text — never on a long article that uses a few. Prefer commas, colons, periods, or parentheses.',
@@ -1961,7 +1961,10 @@ function enclosingCssSelector(cssText, index) {
// `{` belongs to some other selector.
const closeBeforeIndex = cssText.lastIndexOf('}', index);
if (closeBeforeIndex > open) return null;
- const prevClose = Math.max(cssText.lastIndexOf('}', open - 1), cssText.lastIndexOf(';', open - 1));
+ // Ignore delimiters inside comments when locating the previous declaration.
+ // Keeping comment length intact preserves indices into the original source.
+ const beforeOpen = cssText.slice(0, open).replace(/\/\*[\s\S]*?\*\//g, comment => ' '.repeat(comment.length));
+ const prevClose = Math.max(beforeOpen.lastIndexOf('}'), beforeOpen.lastIndexOf(';'));
const raw = cssText.slice(prevClose + 1, open).replace(/\/\*[\s\S]*?\*\//g, '').trim().replace(/\s+/g, ' ');
if (!raw || raw.startsWith('@') || /^\d/.test(raw) || /[{}<]/.test(raw)) return null;
// Keyframe steps: percentage steps fail the digit test above, but `from`
@@ -5293,14 +5296,17 @@ function checkTypography() {
}
if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
+ // Report the actual primary face: the uniquely most-used family. The old
+ // 15% threshold labeled secondary faces as primary (e.g. an 82/18 split).
+ const ranked = [...fontUsage.entries()].sort((a, b) => b[1] - a[1]);
+ const [primary] = ranked;
+ const tied = ranked[1]?.[1] === primary?.[1];
+ if (primary && !tied) {
+ const [font, count] = primary;
const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ if (OVERUSED_FONTS.has(font) && !isBrandFontOnOwnDomain(font)) {
+ findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ }
}
}
@@ -8126,14 +8132,17 @@ if (IS_BROWSER) {
isHidden: isElementHidden(el),
findings: findings.map(f => {
const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
+ const severity = f.severity || ap?.severity || 'warning';
return {
type: f.type || f.id,
category: ap ? ap.category : 'quality',
- severity: f.severity || ap?.severity || 'warning',
+ severity,
// Advisory findings (em-dash overuse, etc.) are surfaced but never
// treated as failures; carry the flag so the overlay/extension can
// render them with the mildest affordance and consumers can filter.
- advisory: (ap && ap.advisory === true) || f.advisory === true,
+ // Per-finding promotions override the registry default, so derive
+ // this strictly from the effective severity.
+ advisory: severity === 'advisory',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
@@ -8175,6 +8184,381 @@ if (IS_BROWSER) {
else groupMap.set(el, [...kept]);
}
+ function pseudoElementHostSelector(selector) {
+ const raw = String(selector || '');
+ const legacyNames = new Set(['before', 'after', 'first-letter', 'first-line']);
+ const isNameChar = char => /[a-zA-Z0-9_-]/.test(char || '');
+ const consumeFunction = (start) => {
+ let depth = 0;
+ let quote = '';
+ for (let i = start; i < raw.length; i += 1) {
+ const char = raw[i];
+ if (char === '\\') {
+ i += 1;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '(') depth += 1;
+ if (char === ')' && --depth === 0) return i + 1;
+ }
+ return raw.length;
+ };
+
+ let output = '';
+ let found = false;
+ for (let i = 0; i < raw.length;) {
+ const char = raw[i];
+ if (char === '\\') {
+ output += raw.slice(i, Math.min(raw.length, i + 2));
+ i += 2;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ const quote = char;
+ const start = i;
+ i += 1;
+ while (i < raw.length) {
+ if (raw[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ const value = raw[i];
+ i += 1;
+ if (value === quote) break;
+ }
+ output += raw.slice(start, i);
+ continue;
+ }
+ if (char !== ':') {
+ output += char;
+ i += 1;
+ continue;
+ }
+
+ let end = i + 1;
+ let isPseudoElement = false;
+ if (raw[end] === ':') {
+ end += 1;
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = end > nameStart;
+ } else {
+ const nameStart = end;
+ while (isNameChar(raw[end])) end += 1;
+ isPseudoElement = legacyNames.has(raw.slice(nameStart, end).toLowerCase());
+ }
+ if (!isPseudoElement) {
+ output += char;
+ i += 1;
+ continue;
+ }
+ if (raw[end] === '(') end = consumeFunction(end);
+ found = true;
+ if (!output || /[\s>+~,]/.test(output[output.length - 1])) output += '*';
+ i = end;
+ }
+ if (!found) return null;
+ return output.trim().replace(/,\s*(?=,|$)/g, '');
+ }
+
+ function selectorNodesForLiveDom(root, selector) {
+ const raw = String(selector || '').trim();
+ if (!raw) return null;
+ const fallback = pseudoElementHostSelector(raw);
+ if (fallback == null) {
+ // An empty result from a valid full selector is authoritative. In
+ // particular, do not broaden inactive :hover/:focus/:not() rules to
+ // their host element by stripping pseudo-classes.
+ try { return Array.from(root.querySelectorAll(raw)); }
+ catch { return null; }
+ }
+
+ // Resolve pseudo-elements to their originating live elements. An attached
+ // pseudo-element (`.card::before`) belongs to the element before it, while
+ // a hostless pseudo-element after a combinator (`main > ::before`) belongs
+ // to a matching element at that position (`main > *`). Replacing every
+ // pseudo indiscriminately with an empty string leaves the latter as the
+ // invalid selector `main >` and makes absent hosts indistinguishable from
+ // selectors the DOM API cannot parse.
+ if (!fallback || /^[,\s]*$/.test(fallback)) return null;
+ try { return Array.from(root.querySelectorAll(fallback)); }
+ catch { return null; }
+ }
+
+ let containerProbeSequence = 0;
+
+ function isContainerCssRule(rule) {
+ return rule?.constructor?.name === 'CSSContainerRule'
+ || /^\s*@container\b/i.test(rule?.cssText || '');
+ }
+
+ function styleRuleAppliesToLiveMatches(rule, matches) {
+ const style = rule?.style;
+ if (!style || !matches?.length || typeof getComputedStyle !== 'function') return false;
+ const sequence = ++containerProbeSequence;
+ const property = `--impeccable-container-probe-${sequence}-${Math.random().toString(36).slice(2)}`;
+ const value = `impeccable-container-active-${sequence}`;
+ const previousValue = style.getPropertyValue(property);
+ const previousPriority = style.getPropertyPriority(property);
+ try {
+ style.setProperty(property, value, 'important');
+ } catch {
+ return false;
+ }
+
+ const pseudoElements = [...new Set(
+ String(rule.selectorText || '').match(/::[a-zA-Z-]+(?:\([^)]*\))?/g) || [],
+ )];
+ try {
+ return matches.some(el => [null, ...pseudoElements].some(pseudo => {
+ try {
+ const computed = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el);
+ return computed.getPropertyValue(property).trim() === value;
+ } catch {
+ return false;
+ }
+ }));
+ } finally {
+ if (previousValue) style.setProperty(property, previousValue, previousPriority);
+ else style.removeProperty(property);
+ }
+ }
+
+ function conditionalCssRuleIsActive(rule) {
+ const type = Number(rule?.type);
+ const constructorName = rule?.constructor?.name || '';
+ if (constructorName === 'CSSMediaRule' || type === 4) {
+ const condition = rule.conditionText || rule.media?.mediaText || '';
+ if (!condition || typeof window.matchMedia !== 'function') return true;
+ try { return window.matchMedia(condition).matches; }
+ catch { return true; }
+ }
+ if (constructorName === 'CSSSupportsRule' || type === 12) {
+ const condition = rule.conditionText || '';
+ if (!condition || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return true;
+ try { return CSS.supports(condition); }
+ catch { return true; }
+ }
+ return true;
+ }
+
+ function splitCssCommaList(value) {
+ const parts = [];
+ let current = '';
+ let quote = '';
+ let escaped = false;
+ for (const char of String(value || '')) {
+ if (escaped) {
+ current += char;
+ escaped = false;
+ continue;
+ }
+ if (char === '\\') {
+ current += char;
+ escaped = true;
+ continue;
+ }
+ if (quote) {
+ current += char;
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ current += char;
+ continue;
+ }
+ if (char === ',') {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+ return parts;
+ }
+
+ function normalizeAnimationName(value) {
+ const name = String(value || '').trim();
+ if (name.length >= 2 && name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) {
+ return name.slice(1, -1);
+ }
+ return name;
+ }
+
+ function animationNamesDeclaredByRule(rule) {
+ const style = rule?.style;
+ if (!style) return [];
+ let value = '';
+ try {
+ value = style.animationName
+ || style.getPropertyValue?.('animation-name')
+ || style.webkitAnimationName
+ || style.getPropertyValue?.('-webkit-animation-name')
+ || '';
+ } catch {
+ return [];
+ }
+ return splitCssCommaList(value)
+ .map(normalizeAnimationName)
+ .filter(name => name && name.toLowerCase() !== 'none');
+ }
+
+ function keyframesRuleName(rule, cssText) {
+ const constructorName = rule?.constructor?.name || '';
+ const type = Number(rule?.type);
+ const isKeyframes = constructorName === 'CSSKeyframesRule'
+ || constructorName === 'WebKitCSSKeyframesRule'
+ || type === 7
+ || /^\s*@(?:-webkit-)?keyframes\b/i.test(cssText);
+ if (!isKeyframes) return '';
+ const match = String(cssText || '').match(/^\s*@(?:-webkit-)?keyframes\s+([^\s{]+)/i);
+ return normalizeAnimationName(rule?.name || match?.[1] || '');
+ }
+
+ function cssPropertyName(property) {
+ if (property.startsWith('--')) return property;
+ return property.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
+ }
+
+ function resolvedAnimationKeyframes(candidateNames) {
+ if (typeof document.getAnimations !== 'function') return null;
+ let animations;
+ try { animations = document.getAnimations(); }
+ catch { return null; }
+
+ const resolved = new Map();
+ const metadata = new Set(['offset', 'computedOffset', 'easing', 'composite']);
+ for (const animation of animations) {
+ const name = normalizeAnimationName(animation?.animationName || '');
+ if (!name || !candidateNames.has(name) || resolved.has(name)) continue;
+ let frames;
+ try { frames = animation.effect?.getKeyframes?.() || []; }
+ catch { continue; }
+ const blocks = [];
+ for (const frame of frames) {
+ const rawOffset = Number.isFinite(frame.computedOffset) ? frame.computedOffset : frame.offset;
+ if (!Number.isFinite(rawOffset)) continue;
+ const offset = Math.round(rawOffset * 1000000) / 10000;
+ const declarations = Object.entries(frame)
+ .filter(([property, value]) => !metadata.has(property) && value != null && value !== '')
+ .map(([property, value]) => `${cssPropertyName(property)}: ${value};`);
+ const easing = String(frame.easing || '').trim();
+ if (easing && easing.toLowerCase() !== 'linear') {
+ declarations.push(`animation-timing-function: ${easing};`);
+ }
+ if (declarations.length === 0) continue;
+ blocks.push(`${offset}% { ${declarations.join(' ')} }`);
+ }
+ if (blocks.length > 0) resolved.set(name, `@keyframes ${name} { ${blocks.join(' ')} }`);
+ }
+ return resolved;
+ }
+
+ // Read CSS that is absent from document.outerHTML. Inline <style> blocks are
+ // already present in the HTML pattern corpus, so limit this walk to linked
+ // stylesheets. Flatten grouping rules so each declaration keeps its selector,
+ // and admit only selector rules that target the live DOM. That prevents
+ // unused utilities from feeding both selector-scoped and page-level checks.
+ // Same-origin CSS and readable CORS sheets participate; browser security
+ // exceptions for cross-origin sheets are expected and skipped.
+ function linkedStylesheetText() {
+ const parts = [];
+ const seen = new Set();
+ const animationNames = new Set();
+ const keyframeCandidates = new Map();
+ const appendRules = (rules, requiresAppliedMatch = false) => {
+ for (const rule of rules) {
+ if (rule.styleSheet) {
+ appendSheet(rule.styleSheet);
+ continue;
+ }
+ const cssText = rule.cssText || '';
+ if (rule.selectorText) {
+ const matches = selectorNodesForLiveDom(document, rule.selectorText);
+ // Only declarations with a resolvable live host enter the corpus.
+ // Unresolvable selectors are uncertain, not evidence that a pattern
+ // rendered, and retaining them would leak unused CSS into findings.
+ if (
+ matches?.length > 0
+ && (!requiresAppliedMatch || styleRuleAppliesToLiveMatches(rule, matches))
+ ) {
+ parts.push(cssText);
+ for (const name of animationNamesDeclaredByRule(rule)) animationNames.add(name);
+ }
+ continue;
+ }
+ let nested = [];
+ let hasNestedRules = false;
+ try {
+ const ruleList = rule.cssRules;
+ hasNestedRules = ruleList != null;
+ nested = Array.from(ruleList || []);
+ } catch {
+ continue;
+ }
+ const keyframesName = keyframesRuleName(rule, cssText);
+ if (keyframesName) {
+ // Keyframes do not merge: when a name is defined more than once, the
+ // later effective definition replaces the earlier one.
+ keyframeCandidates.set(keyframesName, {
+ name: keyframesName,
+ cssText,
+ });
+ continue;
+ }
+ if (hasNestedRules) {
+ if (!conditionalCssRuleIsActive(rule)) continue;
+ appendRules(nested, requiresAppliedMatch || isContainerCssRule(rule));
+ continue;
+ }
+ // Other selector-less leaf at-rules cannot be tied to a rendered node.
+ }
+ };
+ const appendSheet = (sheet) => {
+ if (!sheet || seen.has(sheet)) return;
+ seen.add(sheet);
+ let rules;
+ try { rules = Array.from(sheet.cssRules || sheet.rules || []); }
+ catch { return; }
+ appendRules(rules);
+ };
+ let sheets;
+ try { sheets = Array.from(document.styleSheets || []); }
+ catch { return ''; }
+ for (const sheet of sheets) {
+ const owner = sheet.ownerNode;
+ if (owner?.tagName?.toLowerCase() !== 'link') continue;
+ if (!/\bstylesheet\b/i.test(owner.getAttribute?.('rel') || '')) continue;
+ appendSheet(sheet);
+ }
+ // Motion checks need the effective body of a live animation's keyframes.
+ // Let the browser resolve duplicate names across source order, imports,
+ // conditional groups, and cascade layers, then serialize those computed
+ // frames back into the pattern corpus. Browsers also make container-nested
+ // keyframes globally available, so lexical grouping is not a reliable
+ // activity signal. When the Web Animations API is unavailable, fall back to
+ // the last source-order definition referenced by a retained linked rule.
+ const resolvedKeyframes = resolvedAnimationKeyframes(new Set(keyframeCandidates.keys()));
+ if (resolvedKeyframes) {
+ parts.push(...resolvedKeyframes.values());
+ } else {
+ for (const candidate of keyframeCandidates.values()) {
+ if (!animationNames.has(candidate.name)) continue;
+ parts.push(candidate.cssText);
+ }
+ }
+ return parts.join('\n');
+ }
+
function browserFindingsFromMap(groupMap) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
@@ -8548,18 +8932,16 @@ if (IS_BROWSER) {
// (the CSS ships here, but the pattern never renders — the live DOM is
// ground truth in the browser), and a match under a data-impeccable-ignore
// ancestor is waived. Selector-less findings stay page-level.
- const scopedHtmlFindings = checkHtmlPatterns(docClone.outerHTML).filter(f => {
+ const html = docClone.outerHTML;
+ const corpora = buildHtmlPatternCorpora(html);
+ const linkedCss = linkedStylesheetText();
+ if (linkedCss) corpora.styleText += `\n${linkedCss}`;
+ const scopedHtmlFindings = checkHtmlPatterns(html, corpora).filter(f => {
if (!f.selector) return true;
- const query = String(f.selector).replace(/::?[a-zA-Z-]+(\([^)]*\))?/g, '').trim().replace(/,\s*(?=,|$)/g, '');
- if (!query || /^[,\s]*$/.test(query)) return true;
- let matches;
- try {
- matches = document.querySelectorAll(query);
- } catch {
- return true;
- }
+ const matches = selectorNodesForLiveDom(document, f.selector);
+ if (!matches) return false;
if (matches.length === 0) return false;
- return [...matches].some(el => !scopedIgnoreActive(el, f.id));
+ return matches.some(el => !scopedIgnoreActive(el, f.id));
});
if (scopedHtmlFindings.length > 0) {
const mapped = scopedHtmlFindings.map(f => {
diff --git a/plugin/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs b/plugin/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
index f3ff43c84..ac4bd0a7c 100644
--- a/plugin/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
+++ b/plugin/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
@@ -2,7 +2,7 @@ import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { finding } from '../../findings.mjs';
+import { deriveAdvisoryFlag, finding } from '../../findings.mjs';
import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
import { checkContentHiddenAtRest } from '../../rules/checks.mjs';
@@ -394,7 +394,7 @@ async function detectUrl(rawUrl, options = {}) {
// Per-finding severity promotion (e.g. hero-region pulsing dot)
// overrides the registry default carried by finding().
if (f.severity && f.severity !== item.severity) item.severity = f.severity;
- return item;
+ return deriveAdvisoryFlag(item);
});
}
diff --git a/plugin/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs b/plugin/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
index 84e6ab1f5..dac6939b0 100644
--- a/plugin/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
+++ b/plugin/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
@@ -9,7 +9,7 @@ import {
} from '../../design-system.mjs';
import { isFullPage } from '../../shared/page.mjs';
import { applyInlineIgnores } from '../../shared/inline-ignores.mjs';
-import { finding } from '../../findings.mjs';
+import { deriveAdvisoryFlag, finding } from '../../findings.mjs';
import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import {
checkElementBorders,
@@ -257,7 +257,7 @@ async function detectHtml(filePath, options = {}) {
// severity (e.g. a pulsing dot inside a header/nav landmark) that
// overrides the registry default.
if (f.severity) item.severity = f.severity;
- findings.push(item);
+ findings.push(deriveAdvisoryFlag(item));
}
// Text-content analyzers (em-dash overuse, marketing buzzwords,
// numbered section markers, aphoristic cadence) live in the regex
diff --git a/plugin/skills/impeccable/scripts/detector/findings.mjs b/plugin/skills/impeccable/scripts/detector/findings.mjs
index fa98dd935..ae7e134f9 100644
--- a/plugin/skills/impeccable/scripts/detector/findings.mjs
+++ b/plugin/skills/impeccable/scripts/detector/findings.mjs
@@ -4,6 +4,12 @@ function getAP(id) {
return getAntipattern(id);
}
+function deriveAdvisoryFlag(item) {
+ if (item.severity === 'advisory') item.advisory = true;
+ else delete item.advisory;
+ return item;
+}
+
function finding(id, filePath, snippet, line = 0) {
const ap = getAP(id);
const base = { antipattern: id, name: ap.name, description: ap.description, severity: ap.severity || 'warning', category: ap.category || null, file: filePath, line, snippet };
@@ -11,8 +17,7 @@ function finding(id, filePath, snippet, line = 0) {
// failures. Carry the flag on the finding so every consumer (CLI, JSON, hook)
// can partition without a registry lookup. Only stamped when true to keep the
// finding shape stable for the vast majority of rules.
- if (ap.advisory === true) base.advisory = true;
- return base;
+ return deriveAdvisoryFlag(base);
}
-export { getAP, finding };
+export { getAP, finding, deriveAdvisoryFlag };
diff --git a/plugin/skills/impeccable/scripts/detector/registry/antipatterns.mjs b/plugin/skills/impeccable/scripts/detector/registry/antipatterns.mjs
index 945307783..7c692c79a 100644
--- a/plugin/skills/impeccable/scripts/detector/registry/antipatterns.mjs
+++ b/plugin/skills/impeccable/scripts/detector/registry/antipatterns.mjs
@@ -233,7 +233,7 @@ const ANTIPATTERNS = [
// rather than a failure. It fires only on the AI saturation pattern, not on
// ordinary prose. Advisory findings are surfaced separately, never counted
// as failures, and skipped by the design hook unless a project opts in.
- advisory: true,
+ severity: 'advisory',
name: 'Em-dash overuse',
description:
'Em-dash saturation in body copy is an AI cadence tell. Advisory only: humans use em-dashes legitimately, so this fires only on saturation — at least 8 em-dashes (— or --) at a density near one per 500 characters of body text — never on a long article that uses a few. Prefer commas, colons, periods, or parentheses.',
@@ -588,9 +588,10 @@ function getAntipattern(id) {
// Advisory rules are detected and reported, but never treated as failures:
// the CLI lists them under a separate "Advisory" section, they do not affect
// exit codes or the failure count, and the design hook skips them by default.
-// The set is derived from the registry so a rule only needs `advisory: true`.
+// `severity` is the canonical registry field. The runtime finding serializer
+// derives its `advisory: true` compatibility/output flag from this set.
const ADVISORY_RULE_IDS = new Set(
- ANTIPATTERNS.filter(rule => rule.advisory === true).map(rule => rule.id),
+ ANTIPATTERNS.filter(rule => rule.severity === 'advisory').map(rule => rule.id),
);
function isAdvisoryRule(id) {
diff --git a/plugin/skills/impeccable/scripts/detector/rules/checks.mjs b/plugin/skills/impeccable/scripts/detector/rules/checks.mjs
index 579e1c12e..a24631ce9 100644
--- a/plugin/skills/impeccable/scripts/detector/rules/checks.mjs
+++ b/plugin/skills/impeccable/scripts/detector/rules/checks.mjs
@@ -688,7 +688,10 @@ function enclosingCssSelector(cssText, index) {
// `{` belongs to some other selector.
const closeBeforeIndex = cssText.lastIndexOf('}', index);
if (closeBeforeIndex > open) return null;
- const prevClose = Math.max(cssText.lastIndexOf('}', open - 1), cssText.lastIndexOf(';', open - 1));
+ // Ignore delimiters inside comments when locating the previous declaration.
+ // Keeping comment length intact preserves indices into the original source.
+ const beforeOpen = cssText.slice(0, open).replace(/\/\*[\s\S]*?\*\//g, comment => ' '.repeat(comment.length));
+ const prevClose = Math.max(beforeOpen.lastIndexOf('}'), beforeOpen.lastIndexOf(';'));
const raw = cssText.slice(prevClose + 1, open).replace(/\/\*[\s\S]*?\*\//g, '').trim().replace(/\s+/g, ' ');
if (!raw || raw.startsWith('@') || /^\d/.test(raw) || /[{}<]/.test(raw)) return null;
// Keyframe steps: percentage steps fail the digit test above, but `from`
@@ -4020,14 +4023,17 @@ function checkTypography() {
}
if (totalTextElements >= 20) {
- // A font is "primary" if it's used by at least 15% of text elements
- const PRIMARY_THRESHOLD = 0.15;
- for (const [font, count] of fontUsage) {
+ // Report the actual primary face: the uniquely most-used family. The old
+ // 15% threshold labeled secondary faces as primary (e.g. an 82/18 split).
+ const ranked = [...fontUsage.entries()].sort((a, b) => b[1] - a[1]);
+ const [primary] = ranked;
+ const tied = ranked[1]?.[1] === primary?.[1];
+ if (primary && !tied) {
+ const [font, count] = primary;
const share = count / totalTextElements;
- if (share < PRIMARY_THRESHOLD) continue;
- if (!OVERUSED_FONTS.has(font)) continue;
- if (isBrandFontOnOwnDomain(font)) continue;
- findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ if (OVERUSED_FONTS.has(font) && !isBrandFontOnOwnDomain(font)) {
+ findings.push({ type: 'overused-font', detail: `Primary font: ${font} (${Math.round(share * 100)}% of text)` });
+ }
}
}
diff --git a/plugin/skills/impeccable/scripts/hook-lib.mjs b/plugin/skills/impeccable/scripts/hook-lib.mjs
index 767fe65a6..6d8c3db81 100644
--- a/plugin/skills/impeccable/scripts/hook-lib.mjs
+++ b/plugin/skills/impeccable/scripts/hook-lib.mjs
@@ -138,17 +138,20 @@ export const IMMEDIATE_TIER_RULES = new Set([
// the agent is never nagged about a taste call a human might make on purpose.
// A project opts back in with `.impeccable/config.json`:
// { "detector": { "advisoryRules": "include" } }
-// This set is the hook's own copy of the registry's `advisory: true` rules,
-// mirroring how IMMEDIATE_TIER_RULES lists rule ids inline so the hook stays
-// self-contained and testable without loading the detector. Keep it in sync
-// with the registry (cli/engine/registry/antipatterns.mjs).
+// This legacy id fallback keeps older detector findings recognizable when they
+// carry neither the current runtime flag nor the canonical advisory severity.
+// Current findings are classified by their serialized metadata below.
export const ADVISORY_RULES = new Set([
'em-dash-overuse',
]);
export function isAdvisoryFinding(finding) {
const id = finding && normalizeIgnoreRule(finding.antipattern);
- return Boolean(id && (ADVISORY_RULES.has(id) || finding.advisory === true));
+ return Boolean(id && (
+ ADVISORY_RULES.has(id)
+ || finding.advisory === true
+ || finding.severity === 'advisory'
+ ));
}
export const DEFAULT_CONFIG = Object.freeze({