impeccable 3.2.1 → 3.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -82,6 +82,15 @@ const GENERIC_FONTS = new Set([
82
82
  const WCAG_LARGE_TEXT_PX = 18 * (96 / 72);
83
83
  const WCAG_LARGE_BOLD_TEXT_PX = 14 * (96 / 72);
84
84
 
85
+ // Em-dash overuse (advisory) thresholds, shared by the regex/static-HTML
86
+ // analyzer and the browser DOM check so both fire on the same saturation
87
+ // pattern. Two gates must hold: an absolute floor of EM_DASH_FLOOR dashes, and
88
+ // a density of at least one dash per EM_DASH_CHARS_PER_DASH characters of body
89
+ // text. A long article that uses a few em-dashes is left alone; a short,
90
+ // dash-per-clause page is not.
91
+ const EM_DASH_FLOOR = 8;
92
+ const EM_DASH_CHARS_PER_DASH = 500;
93
+
85
94
  // Serif faces that show up in italic-display heroes. The rule also fires when
86
95
  // the primary face is unknown but the stack ends in the generic `serif` token,
87
96
  // which catches custom/private faces with a serif fallback.
@@ -134,9 +143,9 @@ const ANTIPATTERNS = [
134
143
  id: 'single-font',
135
144
  category: 'slop',
136
145
  scopes: ['type'],
137
- name: 'Single font for everything',
146
+ name: 'Single font without hierarchy',
138
147
  description:
139
- 'Only one font family is used for the entire page. Pair a distinctive display font with a refined body font to create typographic hierarchy.',
148
+ 'Only one font family is used for the entire page. A single family can work when weight and size contrast carry the hierarchy; otherwise pair a distinctive display font with a refined body font.',
140
149
  skillSection: 'Typography',
141
150
  skillGuideline: 'only one font family for the entire page',
142
151
  },
@@ -206,15 +215,60 @@ const ANTIPATTERNS = [
206
215
  skillSection: 'Motion',
207
216
  skillGuideline: 'bounce or elastic easing',
208
217
  },
218
+ {
219
+ id: 'pulsing-dot',
220
+ category: 'slop',
221
+ name: 'Pulsing status dot',
222
+ description:
223
+ 'Small pulsing status dots simulate liveness decoratively. Reserve pulse animation for indicators tied to genuinely live, changing data; a static indicator with clear labeling is honest and calmer.',
224
+ skillSection: 'Motion',
225
+ skillGuideline: 'decorative pulsing status dot',
226
+ },
227
+ {
228
+ id: 'blinking-cursor',
229
+ category: 'slop',
230
+ severity: 'advisory',
231
+ name: 'Decorative blinking cursor',
232
+ description:
233
+ 'A blinking text cursor animated into a hero or landing section simulates typing where no input exists. It borrows the dev-tool aesthetic as decoration. Real editable fields draw their own caret; anywhere else, let the composition hold attention without a fake prompt.',
234
+ skillSection: 'Motion',
235
+ },
236
+ {
237
+ id: 'shape-assembled-illustration',
238
+ category: 'slop',
239
+ severity: 'advisory',
240
+ name: 'Shape-assembled illustration',
241
+ description:
242
+ 'A large inline SVG that builds a pictorial scene from a pile of primitive shapes reads as placeholder clip art, not illustration. Icons, logos, and data graphics are fine at their scale; a hero-sized visual deserves real artwork, a photograph, or a deliberately drawn graphic.',
243
+ skillSection: 'Imagery',
244
+ },
209
245
  {
210
246
  id: 'dark-glow',
211
247
  category: 'slop',
212
- name: 'Dark mode with glowing accents',
248
+ name: 'Glowing shadow accents',
249
+ description:
250
+ 'Colored glow shadows — a zero-offset chromatic halo (box- or text-shadow) on any background, or any colored blurred shadow on a dark background — are the default "cool" look of AI-generated UIs. Use neutral elevation shadows and subtle, purposeful lighting instead.',
251
+ skillSection: 'Color & Contrast',
252
+ skillGuideline: 'dark mode with glowing accents',
253
+ },
254
+ {
255
+ id: 'radial-halo',
256
+ category: 'slop',
257
+ name: 'Radial-gradient background halo',
213
258
  description:
214
- 'Dark backgrounds with colored box-shadow glows are the default "cool" look of AI-generated UIs. Use subtle, purposeful lighting instead — or skip the dark theme entirely.',
259
+ 'A chromatic radial-gradient wash — saturated at the center, fading to transparent — used as a decorative background glow on a dark page. Same tell as glowing shadows, drawn with a gradient instead of a shadow. Ground the surface with a solid or subtly shifted background instead.',
215
260
  skillSection: 'Color & Contrast',
216
261
  skillGuideline: 'dark mode with glowing accents',
217
262
  },
263
+ {
264
+ id: 'marquee',
265
+ category: 'slop',
266
+ name: 'Auto-scrolling marquee',
267
+ description:
268
+ 'Continuously auto-scrolling content demands attention it has not earned and hides half its content at any moment. Reserve motion for content that changes; let readers move at their own pace.',
269
+ skillSection: 'Motion',
270
+ skillGuideline: 'auto-scrolling marquee',
271
+ },
218
272
  {
219
273
  id: 'icon-tile-stack',
220
274
  category: 'slop',
@@ -257,22 +311,27 @@ const ANTIPATTERNS = [
257
311
  skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
258
312
  },
259
313
  {
260
- id: 'numbered-section-markers',
314
+ id: 'numbered-section-labels',
261
315
  category: 'slop',
262
- scopes: ['layout'],
316
+ scopes: ['type'],
263
317
  severity: 'advisory',
264
- name: 'Numbered section markers (01 / 02 / 03)',
318
+ name: 'Tiny numbered section labels',
265
319
  description:
266
- 'Numbered display markers as section labels (01, 02, 03) are the AI editorial scaffold one tier deeper than tracked eyebrow chips. If you find yourself reaching for them, choose a different section cadence.',
320
+ 'Small numeric index labels riding next to section headings, repeated section after section, are AI editorial scaffolding — a page numbering its own chapters instead of earning structure. Let hierarchy, content, and rhythm carry the sequence.',
267
321
  skillSection: 'Layout & Space',
268
322
  skillGuideline: 'numbered section markers',
269
323
  },
270
324
  {
271
325
  id: 'em-dash-overuse',
272
326
  category: 'slop',
327
+ // Advisory: humans use em-dashes legitimately, so this rule is opt-in noise
328
+ // rather than a failure. It fires only on the AI saturation pattern, not on
329
+ // ordinary prose. Advisory findings are surfaced separately, never counted
330
+ // as failures, and skipped by the design hook unless a project opts in.
331
+ advisory: true,
273
332
  name: 'Em-dash overuse',
274
333
  description:
275
- 'More than two em-dashes (— or --) in body copy is an AI cadence tell. Use commas, colons, periods, or parentheses instead.',
334
+ '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.',
276
335
  skillSection: 'Copy',
277
336
  skillGuideline: 'no em dashes',
278
337
  },
@@ -325,6 +384,49 @@ const ANTIPATTERNS = [
325
384
  },
326
385
 
327
386
  // ── Quality: general design and accessibility issues ──
387
+ {
388
+ id: 'script-error',
389
+ category: 'quality',
390
+ severity: 'error',
391
+ name: 'Uncaught script error on load',
392
+ description:
393
+ 'A script threw an uncaught exception or failed to parse while the page loaded. Broken JavaScript silently kills reveals, interactions, and dynamic content, and can leave most of a page invisible. Fix the error before judging anything else.',
394
+ },
395
+ {
396
+ id: 'content-hidden-at-rest',
397
+ category: 'quality',
398
+ severity: 'error',
399
+ scopes: ['layout'],
400
+ name: 'Content invisible at rest',
401
+ description:
402
+ 'A large share of the page text sits at opacity 0 or visibility hidden even after every reveal handler had a chance to run. This is the failed-reveal signature: the content shipped but never becomes visible. Make content visible by default and let JavaScript enhance its entrance instead of gating its existence.',
403
+ },
404
+ {
405
+ id: 'edge-flush-cards',
406
+ category: 'quality',
407
+ scopes: ['layout'],
408
+ name: 'Cards flush against the scroller edge',
409
+ description:
410
+ 'Cards inside a horizontal scroller or tab panel sit flush against the container edge at rest while keeping a gutter on the other side, so their edges and rounded corners get cut off. Usually the panel is sized wider than its clip box. Keep a consistent inset on both sides.',
411
+ },
412
+ {
413
+ id: 'text-occlusion',
414
+ category: 'quality',
415
+ scopes: ['layout'],
416
+ name: 'Text occluded by an overlapping element',
417
+ description:
418
+ 'Text is painted under an opaque element or a second text run, so part of it cannot be read. A decorative box, a stacked layer, or an inline element with leaked padding lands on the words instead of beside them. Give overlapping layers room, or move the text out from under the layer above it.',
419
+ skillSection: 'Layout & Space',
420
+ },
421
+ {
422
+ id: 'first-viewport-column-overflow',
423
+ category: 'quality',
424
+ scopes: ['layout'],
425
+ name: 'One column stretches the first viewport',
426
+ description:
427
+ 'A multi-column opening section lets one column run far past the fold while its sibling fits in a single viewport, so the short column floats in dead space and the fold falls deep inside one section. Balance the columns, cap the tall one, or let the long content flow below the opening row.',
428
+ skillSection: 'Layout & Space',
429
+ },
328
430
  {
329
431
  id: 'gray-on-color',
330
432
  category: 'quality',
@@ -394,6 +496,15 @@ const ANTIPATTERNS = [
394
496
  description:
395
497
  'Heading levels should not skip (e.g. h1 then h3 with no h2). Screen readers use heading hierarchy for navigation. Skipping levels breaks the document outline.',
396
498
  },
499
+ {
500
+ id: 'heading-rhythm',
501
+ category: 'quality',
502
+ scopes: ['layout', 'type'],
503
+ name: 'Heading crowded against the previous block',
504
+ description:
505
+ 'A heading binds to the content it introduces, so the rendered space above it should exceed the space below it. When headings across a page sit as close or closer to the block above than to their own content, every section reads as if it captions the previous one. Open up the space above each heading.',
506
+ skillSection: 'Layout & Space',
507
+ },
397
508
  {
398
509
  id: 'justified-text',
399
510
  category: 'quality',
@@ -410,6 +521,14 @@ const ANTIPATTERNS = [
410
521
  description:
411
522
  'Body text below 12px is hard to read, especially on high-DPI screens. Use at least 14px for body content, 16px is ideal.',
412
523
  },
524
+ {
525
+ id: 'undersized-ui-text',
526
+ category: 'quality',
527
+ scopes: ['type'],
528
+ name: 'Undersized functional text',
529
+ description:
530
+ 'Interactive and content-bearing UI text (links, buttons, nav items, labels, table cells, meta rows, timecodes) below 11px is a legibility failure, not a style choice. WCAG sets no absolute pixel floor, but functional text under 11px is a defensible quality bar: it fails on high-DPI and small viewports and it degrades tap and read targets. The 11px floor holds even inside a footer; only non-interactive legal smallprint gets the softer 10px floor. Being ON the DESIGN.md size ramp does not exempt a value here: adding 8px to the ramp launders the token but not the legibility problem, and that is exactly the escape hatch this rule closes. Exempts sup/sub, visually-hidden (sr-only) text, and code/terminal contexts. Decorative letterspaced micro-labels are still functional and stay in scope.',
531
+ },
413
532
  {
414
533
  id: 'all-caps-body',
415
534
  category: 'quality',
@@ -438,6 +557,13 @@ const ANTIPATTERNS = [
438
557
  skillSection: 'Layout & Space',
439
558
  skillGuideline: 'content wider than its container',
440
559
  },
560
+ {
561
+ id: 'repeated-container-text',
562
+ category: 'quality',
563
+ name: 'Same text repeated inside one container',
564
+ description:
565
+ 'The same literal text rendered three or more times in structurally different spots inside a single card or panel is redundant messaging — usually a status or label wired into every slot of a template. Say it once, in the slot where it matters most.',
566
+ },
441
567
  {
442
568
  id: 'clipped-overflow-container',
443
569
  category: 'quality',
@@ -490,12 +616,11 @@ const ANTIPATTERNS = [
490
616
  skillGuideline: 'font size outside the project design system',
491
617
  },
492
618
 
493
- // ── Provider tells: opt-in via --gpt / --gemini (gated off by default) ──
619
+ // ── Common generated-UI tells ───────────────────────────────────────────
494
620
  {
495
621
  id: 'gpt-thin-border-wide-shadow',
496
622
  category: 'slop',
497
623
  severity: 'advisory',
498
- gated: 'gpt',
499
624
  name: 'Hairline border with wide shadow',
500
625
  description:
501
626
  'A hairline border paired with a wide, diffuse shadow is a recurring generated-UI signature. Commit to one — a defined edge or a soft elevation — rather than both at once.',
@@ -506,7 +631,6 @@ const ANTIPATTERNS = [
506
631
  id: 'repeating-stripes-gradient',
507
632
  category: 'slop',
508
633
  severity: 'advisory',
509
- gated: 'gpt',
510
634
  name: 'Repeating-gradient stripes',
511
635
  description:
512
636
  'Repeating-gradient stripes used as surface decoration are a recurring generated-UI signature. Reach for a deliberate texture or leave the surface plain.',
@@ -517,10 +641,9 @@ const ANTIPATTERNS = [
517
641
  id: 'codex-grid-background',
518
642
  category: 'slop',
519
643
  severity: 'advisory',
520
- gated: 'gpt',
521
644
  name: 'Decorative grid-line background',
522
645
  description:
523
- 'A two-axis grid drawn with hairline linear-gradient layers ("1px, transparent 1px" on both axes) is a recurring generated-UI signature. Reserve grid overlays for actual canvas, map, blueprint, or measurement surfaces; elsewhere use product structure or a plain surface.',
646
+ 'A decorative grid or line-field background drawn with hairline linear-gradient layers tiled by a fixed pixel cell is a recurring generated-UI signature. Reserve grid overlays for actual canvas, map, blueprint, or measurement surfaces; elsewhere use product structure or a plain surface.',
524
647
  skillSection: 'Visual Details',
525
648
  skillGuideline: 'two-axis grid-line gradient background',
526
649
  },
@@ -528,7 +651,6 @@ const ANTIPATTERNS = [
528
651
  id: 'theater-slop-phrase',
529
652
  category: 'slop',
530
653
  severity: 'advisory',
531
- gated: 'gpt',
532
654
  name: 'Theater framing copy',
533
655
  description:
534
656
  'Dismissing something as "theater" is a recurring generated-copy tic. Say plainly what the thing does or does not do.',
@@ -539,7 +661,6 @@ const ANTIPATTERNS = [
539
661
  id: 'image-hover-transform',
540
662
  category: 'slop',
541
663
  severity: 'advisory',
542
- gated: 'gemini',
543
664
  name: 'Image hover transform',
544
665
  description:
545
666
  'Scaling or rotating an image on hover is a recurring generated-UI signature. Let imagery sit still, or use a subtler, purposeful interaction.',
@@ -698,8 +819,15 @@ const DETECTOR_IS_BROWSER = typeof window !== 'undefined';
698
819
 
699
820
  // ─── Section 3: Pure Detection ──────────────────────────────────────────────
700
821
 
701
- function checkBorders(tag, widths, colors, radius) {
702
- if (BORDER_SAFE_TAGS.has(tag)) return [];
822
+ function checkBorders(tag, widths, colors, radius, opts = {}) {
823
+ // Badge-shaped <span>s (own visible background) are a real stripe target
824
+ // for the top/bottom variant — the inline-tag exemption exists to quiet
825
+ // text-level borders, not chips. They skip the left/right arms below.
826
+ const spanBadge = tag === 'span' && !!opts.badgeLike;
827
+ if (BORDER_SAFE_TAGS.has(tag) && !spanBadge) return [];
828
+ // A live status/alert region wears a colored single-edge border as a
829
+ // severity accent (toast, snackbar, callout), not as the side-tab tell.
830
+ if (opts.statusContext) return [];
703
831
  const findings = [];
704
832
  const sides = ['Top', 'Right', 'Bottom', 'Left'];
705
833
 
@@ -715,10 +843,20 @@ function checkBorders(tag, widths, colors, radius) {
715
843
  const isSide = side === 'Left' || side === 'Right';
716
844
 
717
845
  if (isSide) {
846
+ if (spanBadge) continue;
718
847
  if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
719
848
  else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
720
849
  } else {
721
850
  if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
851
+ // Horizontal variant of the side-tab stripe: a thick chromatic accent
852
+ // riding the top or bottom edge of a card/badge/container. Same
853
+ // dominant-edge + chroma gates as left/right, 3-12px band. Selected-
854
+ // tab underlines are exempt via opts.tabContext (adapters look for
855
+ // tablist/nav/tab ancestors and aria-selected); links, buttons,
856
+ // table cells, and <hr> never reach here (BORDER_SAFE_TAGS).
857
+ else if (!opts.tabContext && w >= 3 && w <= 12) {
858
+ findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
859
+ }
722
860
  }
723
861
  }
724
862
 
@@ -740,16 +878,26 @@ function isEmojiOnlyText(text) {
740
878
  function checkColors(opts) {
741
879
  const { tag, textColor, bgColor, effectiveBg, effectiveBgStops, fontSize, fontWeight, hasDirectText, isEmojiOnly, bgClip, bgImage, classList } = opts;
742
880
  if (SAFE_TAGS.has(tag)) {
743
- // Exception for <a> and <button> elements styled as buttons. SAFE_TAGS
744
- // exists to suppress contrast noise on inline links and unstyled controls,
745
- // where the element has no own background and the contrast against the
746
- // ancestor surface is already the intended visual. When the element has
747
- // its own opaque background and direct text, it is a styled button — and
748
- // contrast on its own surface is a real, frequent bug worth flagging.
749
- const isStyledButton = (tag === 'a' || tag === 'button')
750
- && hasDirectText
751
- && bgColor && bgColor.a > 0.5;
752
- if (!isStyledButton) return [];
881
+ // Exception for elements styled as controls or chips. SAFE_TAGS exists to
882
+ // suppress contrast noise on inline links and unstyled spans, where the
883
+ // element has no own background and the contrast against the ancestor
884
+ // surface is already the intended visual. When the element paints its own
885
+ // opaque background under direct text, it is a styled button, chip, or
886
+ // badge regardless of tag, and contrast on its own surface is a real,
887
+ // frequent bug worth flagging. (The shipped miss: a <span> severity chip
888
+ // whose white text lost a specificity fight and rendered muted-on-red at
889
+ // 1.2:1; the old a/button-only exception never looked at it.) The 9px
890
+ // font floor keeps sub-text decorations out.
891
+ const isStyledControl = hasDirectText
892
+ && ((bgColor && bgColor.a > 0.5)
893
+ // A gradient painted on the element itself is an own surface the
894
+ // same way a solid background is. Without this branch a nav CTA
895
+ // built as `<a>` with `background: linear-gradient(…)` and a text
896
+ // color that fails against every stop sails through on the
897
+ // SAFE_TAGS suppression (the shipped escape).
898
+ || (bgImage && /gradient/i.test(bgImage)))
899
+ && fontSize >= 9;
900
+ if (!isStyledControl) return [];
753
901
  }
754
902
  const findings = [];
755
903
 
@@ -786,7 +934,11 @@ function checkColors(opts) {
786
934
  // like `text-paper/60` on `bg-ink` sections are the FP pattern.
787
935
  const isAlphaFallbackFP = !DETECTOR_IS_BROWSER && !effectiveBg && (textColor.a != null && textColor.a < 1);
788
936
  if (!isAlphaFallbackFP) {
789
- findings.push({ id: 'low-contrast', snippet: `${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
937
+ // Near-threshold ratios (e.g. 4.497) would round to the threshold
938
+ // itself at one decimal and read as "4.5 needs 4.5" — show two
939
+ // decimals there so the finding stays legible.
940
+ const ratioLabel = ratio.toFixed(1) === threshold.toFixed(1) ? ratio.toFixed(2) : ratio.toFixed(1);
941
+ findings.push({ id: 'low-contrast', snippet: `${ratioLabel}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
790
942
  }
791
943
  }
792
944
  }
@@ -832,6 +984,27 @@ function checkColors(opts) {
832
984
  return findings;
833
985
  }
834
986
 
987
+ // WCAG contrast for the :hover state of an element whose hover rules change
988
+ // its text color and/or background. The classic miss: a nav CTA whose
989
+ // author-intended hover pair passes AA, but a broader selector (e.g.
990
+ // `.nav-links a:hover`) wins the specificity fight and swaps in a color
991
+ // that fails. Only fires on elements that present as styled controls —
992
+ // direct text plus an opaque-ish own background in either state — so plain
993
+ // inline links keep the same suppression they get in checkColors.
994
+ function checkHoverContrast(opts) {
995
+ const { tag, textColor, bg, ownBgAlpha, fontSize, fontWeight, hasDirectText, isEmojiOnly } = opts;
996
+ if (!hasDirectText || isEmojiOnly || !textColor || !bg) return [];
997
+ if (SAFE_TAGS.has(tag) && !(ownBgAlpha != null && ownBgAlpha > 0.5)) return [];
998
+ const ratio = contrastRatio(textColor, bg);
999
+ const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
1000
+ const threshold = isLargeText ? 3.0 : 4.5;
1001
+ if (ratio >= threshold) return [];
1002
+ return [{
1003
+ id: 'low-contrast',
1004
+ snippet: `:hover state ${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bg)}`,
1005
+ }];
1006
+ }
1007
+
835
1008
  function isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg) {
836
1009
  if (!hasShadow && !hasBorder) return false;
837
1010
  return hasRadius || hasBg;
@@ -977,26 +1150,57 @@ function isAccentColor(cssColor) {
977
1150
  return false;
978
1151
  }
979
1152
 
1153
+ function resolveHeroHeadingSizePx(value) {
1154
+ const input = String(value || '').trim().toLowerCase();
1155
+ if (!input) return 0;
1156
+
1157
+ const simpleLengthPx = (token) => {
1158
+ const match = /^(-?\d*\.?\d+)\s*(px|rem|em|%)?$/.exec(String(token || '').trim());
1159
+ if (!match) return null;
1160
+ const amount = Number(match[1]);
1161
+ if (!Number.isFinite(amount)) return null;
1162
+ if (match[2] === 'rem' || match[2] === 'em') return amount * 16;
1163
+ if (match[2] === '%') return amount * 0.16;
1164
+ return amount;
1165
+ };
1166
+
1167
+ const direct = simpleLengthPx(input);
1168
+ if (direct !== null) return direct;
1169
+
1170
+ // Static CSS engines cannot resolve viewport units, but clamp's min/max
1171
+ // bounds still tell us whether the heading can ever reach hero scale.
1172
+ const clamp = /^clamp\((.*)\)$/.exec(input);
1173
+ if (clamp) {
1174
+ const parts = clamp[1].split(',');
1175
+ if (parts.length === 3) {
1176
+ const bounds = [simpleLengthPx(parts[0]), simpleLengthPx(parts[2])]
1177
+ .filter((candidate) => candidate !== null);
1178
+ if (bounds.length > 0) return Math.max(...bounds);
1179
+ }
1180
+ }
1181
+
1182
+ return 0;
1183
+ }
1184
+
980
1185
  // Sibling-relationship rule. Anchor on a hero-scale h1, look at the
981
1186
  // previousElementSibling, and gate on EITHER the classic tracked-
982
1187
  // uppercase eyebrow OR the modern accent-colored bold eyebrow.
983
1188
  function checkHeroEyebrow(opts) {
984
1189
  const {
985
1190
  headingTag, headingText, headingFontSize,
1191
+ headingInApplicationContext,
986
1192
  siblingTag, siblingText, siblingTextTransform,
987
1193
  siblingFontSize, siblingLetterSpacing,
988
1194
  siblingFontWeight, siblingColor,
1195
+ siblingHasAccentDashPseudo,
989
1196
  } = opts;
990
1197
  if (headingTag !== 'h1') return [];
991
- // We previously gated on headingFontSize >= 48 to anchor "hero scale".
992
- // But modern hero h1s use clamp() / vw / var(--text-*), none of which
993
- // jsdom can resolve — the computed value comes back as "2em" or
994
- // "var(--text-9xl)" and parseFloat returns 2 or NaN. The gate fails
995
- // on virtually every Tailwind v4 / framework build. The other gates
996
- // (sibling text 2-60 chars, font-size ≤ 14px, accent-bold OR
997
- // tracked-caps) are tight enough to avoid false positives on non-
998
- // hero h1s — a tiny tan label directly above any h1 is the
999
- // antipattern regardless of how big the h1 ends up.
1198
+ // This is specifically a marketing-hero cliché, not a ban on compact
1199
+ // context labels in product UI (for example, a station name inside a tab
1200
+ // panel). Browser-computed sizes are reliable; the static adapter also
1201
+ // resolves ordinary px/rem/em and clamp() bounds before reaching here.
1202
+ if (headingInApplicationContext) return [];
1203
+ if (!(headingFontSize >= 48)) return [];
1000
1204
  if (!siblingTag) return [];
1001
1205
  // An h2 above an h1 is a different anti-pattern (heading hierarchy / dual
1002
1206
  // headings) — never an eyebrow.
@@ -1017,11 +1221,16 @@ function checkHeroEyebrow(opts) {
1017
1221
  const weight = Number(siblingFontWeight) || 400;
1018
1222
  const isAccentBold = weight >= 700 && isAccentColor(siblingColor || '');
1019
1223
 
1020
- if (!isClassicTracked && !isAccentBold) return [];
1224
+ // Branch C: dash-prefix eyebrow — sentence case, low tracking, regular
1225
+ // weight, but announced by a short chromatic ::before/::after bar
1226
+ // (the kicker dash). Same label-above-headline pattern, third styling.
1227
+ const isDashPrefixed = !!siblingHasAccentDashPseudo;
1228
+
1229
+ if (!isClassicTracked && !isAccentBold && !isDashPrefixed) return [];
1021
1230
 
1022
1231
  const headingTextSnippet = (headingText || '').trim().slice(0, 60);
1023
1232
  const eyebrowSnippet = text.slice(0, 40);
1024
- const style = isClassicTracked ? 'tracked-caps' : 'accent-bold';
1233
+ const style = isClassicTracked ? 'tracked-caps' : isAccentBold ? 'accent-bold' : 'dash-prefix';
1025
1234
  return [{
1026
1235
  id: 'hero-eyebrow-chip',
1027
1236
  snippet: `eyebrow chip (${style}) "${eyebrowSnippet}" above ${headingTag} "${headingTextSnippet}"`,
@@ -1082,38 +1291,872 @@ function checkMotion(opts) {
1082
1291
  return findings;
1083
1292
  }
1084
1293
 
1294
+ // Locate the color token in a single shadow layer. Returns
1295
+ // { color, start, end } where color is the parsed {r,g,b,a} (null when the
1296
+ // token exists but can't be parsed — e.g. an unresolved var() or an exotic
1297
+ // color space), or null when no color token is present at all. Handles both
1298
+ // serialization orders: computed style puts the color first
1299
+ // ("rgb(…) 0px 0px 20px"), authored CSS usually puts it last
1300
+ // ("0 0 20px #3b82f6").
1301
+ function findShadowColor(layer) {
1302
+ const fn = layer.match(/(?:rgba?|hsla?|hwb|oklch|oklab|lch|lab|color)\([^)]*\)/i);
1303
+ if (fn) return { color: parseAnyColor(fn[0]), start: fn.index, end: fn.index + fn[0].length };
1304
+ const hex = layer.match(/#[0-9a-fA-F]{3,8}\b/);
1305
+ if (hex) return { color: parseAnyColor(hex[0]), start: hex.index, end: hex.index + hex[0].length };
1306
+ const wordRe = /[a-zA-Z][a-zA-Z]*/g;
1307
+ let m;
1308
+ while ((m = wordRe.exec(layer)) !== null) {
1309
+ const named = CSS_NAMED_COLORS[m[0].toLowerCase()];
1310
+ if (named) return { color: { ...named, a: 1 }, start: m.index, end: m.index + m[0].length };
1311
+ }
1312
+ return null;
1313
+ }
1314
+
1315
+ // Extract the length values of a shadow layer in declaration order, with the
1316
+ // color token removed so its components aren't misread as lengths. Handles
1317
+ // computed-style px values AND authored unitless zeros ("0 0 20px"); rem/em
1318
+ // approximate at 16px. Result order is offset-x, offset-y, blur, [spread].
1319
+ function extractShadowLengths(layer, colorStart, colorEnd) {
1320
+ const stripped = colorStart != null
1321
+ ? layer.slice(0, colorStart) + ' ' + layer.slice(colorEnd)
1322
+ : layer;
1323
+ const vals = [];
1324
+ const re = /(-?\d*\.?\d+)(px|rem|em)?/g;
1325
+ let m;
1326
+ while ((m = re.exec(stripped)) !== null) {
1327
+ let v = parseFloat(m[1]);
1328
+ if (m[2] === 'rem' || m[2] === 'em') v *= 16;
1329
+ vals.push(v);
1330
+ }
1331
+ return vals;
1332
+ }
1333
+
1085
1334
  function checkGlow(opts) {
1086
- const { boxShadow, effectiveBg } = opts;
1087
- if (!boxShadow || boxShadow === 'none') return [];
1088
- if (!effectiveBg) return [];
1335
+ const { boxShadow, textShadow, effectiveBg } = opts;
1336
+ const onDarkBg = effectiveBg ? relativeLuminance(effectiveBg) < 0.1 : false;
1337
+
1338
+ // Scan one shadow list. Two glow tells, in any color format:
1339
+ // 1. Zero-offset chromatic halo (0 0 Npx <color>) — slop on ANY
1340
+ // background; the light radiates evenly outward, which is never how
1341
+ // real elevation shadows behave. Achromatic zero-offset shadows stay
1342
+ // legal (soft ambient elevation), as do focus rings (blur 0).
1343
+ // 2. Any chromatic shadow with real blur on a dark background — the
1344
+ // classic dark-mode glow accent.
1345
+ const scan = (value, prop) => {
1346
+ if (!value || value === 'none') return null;
1347
+ // Split multiple shadows (commas not inside parentheses)
1348
+ for (const layer of value.split(/,(?![^(]*\))/)) {
1349
+ const colorInfo = findShadowColor(layer);
1350
+ // No color token, or one we can't resolve (unresolved var(), exotic
1351
+ // color space): don't guess — skip rather than false-positive.
1352
+ if (!colorInfo || !colorInfo.color) continue;
1353
+ const color = colorInfo.color;
1354
+ if (!hasChroma(color, 30)) continue;
1355
+ const vals = extractShadowLengths(layer, colorInfo.start, colorInfo.end);
1356
+ // Third value is blur (offset-x, offset-y, blur, [spread])
1357
+ if (vals.length < 3 || vals[2] <= 4) continue;
1358
+ if (vals[0] === 0 && vals[1] === 0) {
1359
+ return { id: 'dark-glow', snippet: `Zero-offset ${prop} glow (${colorToHex(color)})` };
1360
+ }
1361
+ if (onDarkBg) {
1362
+ return { id: 'dark-glow', snippet: `Colored ${prop} glow (${colorToHex(color)}) on dark background` };
1363
+ }
1364
+ }
1365
+ return null;
1366
+ };
1089
1367
 
1090
- // Only flag on dark backgrounds (luminance < 0.1)
1091
- const bgLum = relativeLuminance(effectiveBg);
1092
- if (bgLum >= 0.1) return [];
1368
+ const found = scan(boxShadow, 'box-shadow') || scan(textShadow, 'text-shadow');
1369
+ return found ? [found] : [];
1370
+ }
1093
1371
 
1094
- // Split multiple shadows (commas not inside parentheses)
1095
- const parts = boxShadow.split(/,(?![^(]*\))/);
1096
- for (const shadow of parts) {
1097
- const colorMatch = shadow.match(/rgba?\([^)]+\)/);
1098
- if (!colorMatch) continue;
1099
- const color = parseRgb(colorMatch[0]);
1100
- if (!color || !hasChroma(color, 30)) continue;
1372
+ // Collect CSS custom property declarations from raw stylesheet/HTML text.
1373
+ // First declaration wins (:root declarations usually come first); good
1374
+ // enough for the single-level var() resolution the text engines need.
1375
+ function collectCssCustomProps(content) {
1376
+ const map = new Map();
1377
+ const re = /(--[\w-]+)\s*:\s*([^;{}]+)/g;
1378
+ let m;
1379
+ while ((m = re.exec(content)) !== null) {
1380
+ if (!map.has(m[1])) map.set(m[1], m[2].trim());
1381
+ }
1382
+ return map;
1383
+ }
1101
1384
 
1102
- // Extract px values — in computed style: "color Xpx Ypx BLURpx [SPREADpx]"
1103
- const afterColor = shadow.substring(shadow.indexOf(colorMatch[0]) + colorMatch[0].length);
1104
- const beforeColor = shadow.substring(0, shadow.indexOf(colorMatch[0]));
1105
- const pxVals = [...beforeColor.matchAll(/([\d.]+)px/g), ...afterColor.matchAll(/([\d.]+)px/g)]
1106
- .map(m => parseFloat(m[1]));
1385
+ // Text-level glow scan shared by the regex engine and the page-level HTML
1386
+ // pattern pass. Resolves single-level var() refs against custom properties
1387
+ // collected from the same text, then applies the same two glow tells as
1388
+ // checkGlow: zero-offset chromatic halo (any background) and chromatic
1389
+ // blurred shadow when the page has a dark background. Returns
1390
+ // [{ index, snippet }] — index is the offset of the shadow declaration.
1391
+ // Dark-page heuristic for raw CSS/HTML text: dark hex/rgb literals, Tailwind
1392
+ // dark bg utilities, or a ROOT-scoped (body/html/:root or <body style>)
1393
+ // background that resolves — via var() — to a dark color. The var/modern-
1394
+ // color extension is deliberately root-scoped: a light page with one dark
1395
+ // accent chip must not turn every tinted drop shadow into a "dark page"
1396
+ // signal. Shared by the glow and radial-halo text scanners.
1397
+ function cssTextHasDarkRootBg(content, customProps) {
1398
+ const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/i;
1399
+ const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
1400
+ if (darkBgRe.test(content) || twDarkBg.test(content)) return true;
1401
+ const rootScopes = [];
1402
+ const blockRe = /(?:^|[}\s,;>])(?:body|html|:root)\s*(?:,[^{]*)?\{([^}]*)\}/gi;
1403
+ let sm;
1404
+ while ((sm = blockRe.exec(content)) !== null) rootScopes.push(sm[1]);
1405
+ const inlineBody = content.match(/<body[^>]*\bstyle\s*=\s*"([^"]*)"/i);
1406
+ if (inlineBody) rootScopes.push(inlineBody[1]);
1407
+ for (const scope of rootScopes) {
1408
+ const bgRe = /background(?:-color)?\s*:\s*([^;{}]+)/gi;
1409
+ let bm;
1410
+ while ((bm = bgRe.exec(scope)) !== null) {
1411
+ const c = parseAnyColor(resolveVarRefs(bm[1].trim(), customProps));
1412
+ if (c && (c.a ?? 1) > 0.5 && relativeLuminance(c) < 0.1) return true;
1413
+ }
1414
+ }
1415
+ return false;
1416
+ }
1107
1417
 
1108
- // Third value is blur (offset-x, offset-y, blur, [spread])
1109
- if (pxVals.length >= 3 && pxVals[2] > 4) {
1110
- return [{ id: 'dark-glow', snippet: `Colored glow (${colorToHex(color)}) on dark background` }];
1418
+ function scanCssTextForGlow(content) {
1419
+ const customProps = collectCssCustomProps(content);
1420
+ const hasDarkBg = cssTextHasDarkRootBg(content, customProps);
1421
+
1422
+ const results = [];
1423
+ const shadowRe = /\b(box-shadow|text-shadow)\s*:\s*([^;{}]+)/gi;
1424
+ let m;
1425
+ while ((m = shadowRe.exec(content)) !== null) {
1426
+ const prop = m[1].toLowerCase();
1427
+ const value = resolveVarRefs(m[2].trim(), customProps);
1428
+ for (const layer of value.split(/,(?![^(]*\))/)) {
1429
+ const colorInfo = findShadowColor(layer);
1430
+ if (!colorInfo || !colorInfo.color || !hasChroma(colorInfo.color, 30)) continue;
1431
+ const vals = extractShadowLengths(layer, colorInfo.start, colorInfo.end);
1432
+ if (vals.length < 3 || vals[2] <= 4) continue;
1433
+ const zeroOffset = vals[0] === 0 && vals[1] === 0;
1434
+ if (!zeroOffset && !hasDarkBg) continue;
1435
+ results.push({
1436
+ index: m.index,
1437
+ snippet: zeroOffset
1438
+ ? `Zero-offset ${prop} glow (${colorToHex(colorInfo.color)})`
1439
+ : `Colored ${prop} glow (${colorToHex(colorInfo.color)}) on dark page`,
1440
+ });
1441
+ break; // one finding per declaration
1111
1442
  }
1112
1443
  }
1444
+ return results;
1445
+ }
1113
1446
 
1447
+ // Decorative grid or line-field backgrounds drawn with hairline
1448
+ // linear-gradient layers tiled by a fixed pixel cell. Shared by the HTML
1449
+ // pattern pass and the regex source engine so standalone CSS, component
1450
+ // styles, and inline styles receive the same coverage. Both signals must
1451
+ // co-occur in one declaration block; unrelated rules must not add up across
1452
+ // the file. Returns [{ index, snippet }], capped at one finding per source to
1453
+ // match the page-level HTML check's existing behavior.
1454
+ function scanCssTextForGridBackground(content) {
1455
+ const hairlineRe = /\b\d{1,3}px\s*,\s*transparent\s+\d{1,3}px/gi;
1456
+ const invertedHairlineRe = /transparent\s+calc\(100%\s*-\s*\d{1,3}px\)/gi;
1457
+ const sizeDeclPxRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\b/i;
1458
+ const sizeDeclPxPairRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\s+\d{1,3}px/i;
1459
+ const shorthandPxAnyRe = /\/\s*\d{1,3}px\b/;
1460
+ const shorthandPxPairRe = /\/\s*\d{1,3}px\s+\d{1,3}px/;
1461
+ const bgDeclRe = /\bbackground(?:-image)?\s*:\s*([^;{}"']*)/gi;
1462
+ const blockRe = /\{([^{}]*)\}|style\s*=\s*"([^"]*)"|style\s*=\s*'([^']*)'/gi;
1463
+ let blk;
1464
+ while ((blk = blockRe.exec(content)) !== null) {
1465
+ const block = blk[1] || blk[2] || blk[3] || '';
1466
+ let hairlineCount = 0;
1467
+ let bgJoined = '';
1468
+ let bm;
1469
+ bgDeclRe.lastIndex = 0;
1470
+ while ((bm = bgDeclRe.exec(block)) !== null) {
1471
+ hairlineCount += (bm[1].match(hairlineRe) || []).length;
1472
+ hairlineCount += (bm[1].match(invertedHairlineRe) || []).length;
1473
+ bgJoined += `${bm[1]};`;
1474
+ }
1475
+ if (hairlineCount === 0) continue;
1476
+ const hasPxCell = sizeDeclPxRe.test(block) || shorthandPxAnyRe.test(bgJoined);
1477
+ const hasPxPairCell = sizeDeclPxPairRe.test(block) || shorthandPxPairRe.test(bgJoined);
1478
+ if ((hairlineCount >= 2 && hasPxCell) || hasPxPairCell) {
1479
+ return [{
1480
+ index: blk.index,
1481
+ snippet: hairlineCount >= 2
1482
+ ? 'two-axis grid-line gradient background'
1483
+ : 'px-tiled hairline line-field background',
1484
+ }];
1485
+ }
1486
+ }
1114
1487
  return [];
1115
1488
  }
1116
1489
 
1490
+ // Decorative chromatic halo drawn as a radial-gradient background on a dark
1491
+ // page: a saturated center stop dissolving to transparent. The gradient
1492
+ // sibling of the dark-glow shadow tell. Mechanical gates, in order:
1493
+ // * page has a dark root background (shared heuristic with the glow scan)
1494
+ // * declaration has no url() layer (photographic imagery is exempt)
1495
+ // * the gradient's first color stop is chromatic (RGB spread >= 24) and
1496
+ // visible (alpha >= 0.7 — deliberately translucent light-scene washes
1497
+ // composite with content instead of painting a flat halo, and stay legal)
1498
+ // * the gradient's last stop is transparent / near-zero alpha
1499
+ // * no small pixel-sized stop positions (<= 24px = dot/texture patterns)
1500
+ // * not a repeating-* gradient
1501
+ // Achromatic vignettes fail the chroma gate; panel sheens that fade to an
1502
+ // opaque surface color fail the transparent-end gate.
1503
+ function scanCssTextForRadialHalo(content) {
1504
+ const customProps = collectCssCustomProps(content);
1505
+ if (!cssTextHasDarkRootBg(content, customProps)) return [];
1506
+
1507
+ const findings = [];
1508
+ const seen = new Set();
1509
+ const declRe = /background(?:-image)?\s*:\s*([^;{}]+)/gi;
1510
+ let m;
1511
+ while ((m = declRe.exec(content)) !== null) {
1512
+ const value = resolveVarRefs(m[1].trim(), customProps);
1513
+ if (/url\s*\(/i.test(value)) continue;
1514
+
1515
+ const gradRe = /(repeating-)?radial-gradient\(/gi;
1516
+ let g;
1517
+ while ((g = gradRe.exec(value)) !== null) {
1518
+ if (g[1]) continue; // repeating-* = pattern, not halo
1519
+ // Balanced-paren capture of the gradient arguments.
1520
+ let depth = 0, end = -1;
1521
+ const open = value.indexOf('(', g.index);
1522
+ for (let i = open; i < value.length; i++) {
1523
+ if (value[i] === '(') depth++;
1524
+ else if (value[i] === ')') { depth--; if (depth === 0) { end = i; break; } }
1525
+ }
1526
+ if (end < 0) break;
1527
+ const args = splitTopLevelCommas(value.slice(open + 1, end));
1528
+ if (args.length < 2) continue;
1529
+
1530
+ // Optional prelude (shape / size / `at <pos>`) carries no color.
1531
+ const colorTokenRe = /(?:rgba?|hsla?|oklch|oklab|lab|lch|hwb|color-mix)\([^)]*(?:\([^)]*\))?[^)]*\)|#[0-9a-f]{3,8}\b|\btransparent\b/i;
1532
+ const stops = args.filter(a => colorTokenRe.test(a));
1533
+ if (stops.length < 2) continue;
1534
+
1535
+ // Dot/texture exemption: px-sized stop positions mean a repeating
1536
+ // background-size pattern, not a page-scale halo.
1537
+ const pxStop = stops.some(s => {
1538
+ const pm = s.match(/(-?[\d.]+)px\b/);
1539
+ return pm && Math.abs(parseFloat(pm[1])) <= 24;
1540
+ });
1541
+ if (pxStop) continue;
1542
+
1543
+ const first = stops[0].match(colorTokenRe);
1544
+ const last = stops[stops.length - 1].match(colorTokenRe);
1545
+ if (!first || !last) continue;
1546
+
1547
+ const lastColor = /^transparent$/i.test(last[0]) ? { r: 0, g: 0, b: 0, a: 0 } : parseAnyColor(last[0]);
1548
+ if (!lastColor || (lastColor.a ?? 1) > 0.05) continue;
1549
+
1550
+ const firstColor = /^transparent$/i.test(first[0]) ? null : parseAnyColor(first[0]);
1551
+ if (!firstColor) continue;
1552
+ if ((firstColor.a ?? 1) < 0.7) continue;
1553
+ const spread = Math.max(firstColor.r, firstColor.g, firstColor.b) - Math.min(firstColor.r, firstColor.g, firstColor.b);
1554
+ if (spread < 24) continue;
1555
+
1556
+ const snippet = `radial-gradient halo (${colorToHex(firstColor)} → transparent) on dark page`;
1557
+ if (seen.has(snippet)) continue;
1558
+ seen.add(snippet);
1559
+ findings.push({ index: m.index, snippet });
1560
+ }
1561
+ }
1562
+ return findings;
1563
+ }
1564
+
1565
+ // ---------------------------------------------------------------------------
1566
+ // Text-level CSS rule-block scanners (pseudo-element stripes, pulsing dots)
1567
+ // ---------------------------------------------------------------------------
1568
+
1569
+ // Iterate `selector { declarations }` pairs in raw CSS/HTML text. The block
1570
+ // body excludes braces, so nested structures (@media, @keyframes) naturally
1571
+ // yield their innermost rules with the innermost selector text. Callers
1572
+ // create the regex locally — a shared /g instance is not re-entrant.
1573
+ const CSS_RULE_BLOCK_SOURCE = String.raw`([^{};]+)\{([^{}]*)\}`;
1574
+
1575
+ // Parse a declaration block into a prop → value map (last declaration wins,
1576
+ // approximating the cascade inside one block). Values keep their raw text
1577
+ // with any !important suffix stripped.
1578
+ function parseCssDeclBlock(block) {
1579
+ const decls = new Map();
1580
+ for (const part of String(block || '').split(';')) {
1581
+ const idx = part.indexOf(':');
1582
+ if (idx <= 0) continue;
1583
+ const prop = part.slice(0, idx).trim().toLowerCase();
1584
+ const value = part.slice(idx + 1).replace(/\s*!important\s*$/i, '').trim();
1585
+ if (prop && value) decls.set(prop, value);
1586
+ }
1587
+ return decls;
1588
+ }
1589
+
1590
+ function cssLengthToPx(value) {
1591
+ const m = String(value || '').trim().match(/^(-?[\d.]+)(px|rem|em)$/i);
1592
+ if (!m) return null;
1593
+ const n = parseFloat(m[1]);
1594
+ return m[2].toLowerCase() === 'px' ? n : n * 16;
1595
+ }
1596
+
1597
+ function isZeroOffset(value) {
1598
+ return value != null && /^-?0(?:px|%|rem|em)?$/.test(String(value).trim());
1599
+ }
1600
+
1601
+ // Side-tab variant: the accent stripe drawn as an absolutely-positioned
1602
+ // ::before/::after pseudo-element (narrow colored box hugging a vertical
1603
+ // edge) instead of a border-left/right. The element-level border checks
1604
+ // never see it — pseudo-elements aren't part of the DOM the cascade walks —
1605
+ // so this scans stylesheet text directly, mirroring the border rule's
1606
+ // gates: >= 3px thick, chromatic fill, full height against a side edge.
1607
+ function scanCssTextForPseudoStripe(content) {
1608
+ const customProps = collectCssCustomProps(content);
1609
+ const findings = [];
1610
+ const seen = new Set();
1611
+ const ruleRe = new RegExp(CSS_RULE_BLOCK_SOURCE, 'g');
1612
+ let m;
1613
+ while ((m = ruleRe.exec(content)) !== null) {
1614
+ const selector = m[1].trim();
1615
+ if (!/::?(?:before|after)\b/i.test(selector)) continue;
1616
+ // Keep the border rule's prose exemptions (blockquote bars etc.).
1617
+ if (/\b(?:blockquote|pre|code|nav|hr)\b/i.test(selector)) continue;
1618
+ const decls = parseCssDeclBlock(m[2]);
1619
+ const position = decls.get('position');
1620
+ if (position !== 'absolute' && position !== 'fixed') continue;
1621
+
1622
+ const widthPx = cssLengthToPx(resolveVarRefs(
1623
+ decls.get('width') || decls.get('inline-size') || '', customProps));
1624
+ const heightPx = cssLengthToPx(resolveVarRefs(
1625
+ decls.get('height') || decls.get('block-size') || '', customProps));
1626
+ const verticalCandidate = widthPx != null && widthPx >= 3 && widthPx <= 12;
1627
+ // Horizontal variant (top/bottom stripe) carries extra exemptions:
1628
+ // link/button underline affordances, selected-state indicators
1629
+ // (aria-selected="true", aria-current, active/current/selected class
1630
+ // hints), and state-conditional (:hover/:focus/...) affordances are
1631
+ // not stripes. Tab-strip membership alone ([role=tab], .tabs, bare
1632
+ // [aria-selected]) is NOT exempt — a stripe on every tab in the
1633
+ // group is decoration; only the selected item's underline stays.
1634
+ const horizontalCandidate = heightPx != null && heightPx >= 3 && heightPx <= 12
1635
+ && !/(?:^|[\s>+~,(])(?:a|button|summary|tr|td|th|table|li)(?![\w-])/i.test(selector)
1636
+ && !/\[aria-selected\s*[*^$|~]?=\s*["']?true/i.test(selector)
1637
+ && !/\[aria-current(?!\s*[*^$|~]?=\s*["']?false)/i.test(selector)
1638
+ && !/(?:^|[\s._[-])(?:active|current|selected|btn[\w-]*|button[\w-]*|link[\w-]*)(?![\w])/i.test(selector)
1639
+ && !/:(?:hover|focus|focus-visible|focus-within|active|checked)\b/i.test(selector);
1640
+ if (!verticalCandidate && !horizontalCandidate) continue;
1641
+
1642
+ // Resolve edge offsets, letting an `inset` shorthand fill the gaps.
1643
+ const offsets = {
1644
+ top: decls.get('top'), right: decls.get('right'),
1645
+ bottom: decls.get('bottom'), left: decls.get('left'),
1646
+ };
1647
+ const inset = decls.get('inset');
1648
+ if (inset) {
1649
+ const p = inset.split(/\s+/);
1650
+ const [t, r, b, l] =
1651
+ p.length === 1 ? [p[0], p[0], p[0], p[0]]
1652
+ : p.length === 2 ? [p[0], p[1], p[0], p[1]]
1653
+ : p.length === 3 ? [p[0], p[1], p[2], p[1]]
1654
+ : p;
1655
+ if (offsets.top == null) offsets.top = t;
1656
+ if (offsets.right == null) offsets.right = r;
1657
+ if (offsets.bottom == null) offsets.bottom = b;
1658
+ if (offsets.left == null) offsets.left = l;
1659
+ }
1660
+ if (offsets.left == null) offsets.left = decls.get('inset-inline-start');
1661
+ if (offsets.right == null) offsets.right = decls.get('inset-inline-end');
1662
+
1663
+ const heightValue = String(resolveVarRefs(
1664
+ decls.get('height') || decls.get('block-size') || '', customProps)).trim();
1665
+ const widthValue = String(resolveVarRefs(
1666
+ decls.get('width') || decls.get('inline-size') || '', customProps)).trim();
1667
+
1668
+ let edge = null;
1669
+ let thicknessPx = null;
1670
+ if (verticalCandidate) {
1671
+ // Full-height stripes hug both corners; the "floating" variant backs
1672
+ // off each end by a small inset (top/bottom a few px) so the bar
1673
+ // clears the card's corners. Both read as the same side-tab accent —
1674
+ // corner treatment is styling, not a different pattern.
1675
+ const topPx = cssLengthToPx(resolveVarRefs(String(offsets.top ?? ''), customProps));
1676
+ const bottomPx = cssLengthToPx(resolveVarRefs(String(offsets.bottom ?? ''), customProps));
1677
+ const fullHeight = (isZeroOffset(offsets.top) && isZeroOffset(offsets.bottom))
1678
+ || /^100(?:\.0*)?%$/.test(heightValue)
1679
+ || (topPx != null && bottomPx != null
1680
+ && topPx >= 0 && topPx <= 20 && bottomPx >= 0 && bottomPx <= 20);
1681
+ if (fullHeight) {
1682
+ edge = isZeroOffset(offsets.left) ? 'left'
1683
+ : isZeroOffset(offsets.right) ? 'right' : null;
1684
+ thicknessPx = widthPx;
1685
+ }
1686
+ }
1687
+ if (!edge && horizontalCandidate) {
1688
+ const fullWidth = (isZeroOffset(offsets.left) && isZeroOffset(offsets.right))
1689
+ || /^100(?:\.0*)?%$/.test(widthValue);
1690
+ if (fullWidth) {
1691
+ edge = isZeroOffset(offsets.top) ? 'top'
1692
+ : isZeroOffset(offsets.bottom) ? 'bottom' : null;
1693
+ thicknessPx = heightPx;
1694
+ }
1695
+ }
1696
+ if (!edge) continue;
1697
+
1698
+ // Chromatic fill only — a neutral hairline divider is not an accent
1699
+ // stripe. Unresolvable colors err toward detection, matching the
1700
+ // border rule's unknown-format default.
1701
+ const bg = String(resolveVarRefs(
1702
+ decls.get('background-color') || decls.get('background') || '', customProps)).trim();
1703
+ if (!bg || /^(?:none|transparent|inherit|initial|unset|currentcolor)$/i.test(bg)) continue;
1704
+ const colorToken = bg.match(/(?:rgba?|hsla?|oklch|oklab|lab|lch|hwb)\([^)]*\)|#[0-9a-f]{3,8}\b/i);
1705
+ const parsed = parseAnyColor(colorToken ? colorToken[0] : bg);
1706
+ if (parsed) {
1707
+ if ((parsed.a ?? 1) < 0.1) continue;
1708
+ const spread = Math.max(parsed.r, parsed.g, parsed.b) - Math.min(parsed.r, parsed.g, parsed.b);
1709
+ if (spread < 30) continue;
1710
+ } else if (/^(?:white|black|gray|grey|silver)$/i.test(bg)) {
1711
+ continue;
1712
+ }
1713
+
1714
+ if (seen.has(selector)) continue;
1715
+ seen.add(selector);
1716
+ findings.push({
1717
+ id: 'side-tab',
1718
+ snippet: `${selector} — absolute ${thicknessPx}px pseudo-element stripe (${edge}: 0)`,
1719
+ });
1720
+ }
1721
+ return findings;
1722
+ }
1723
+
1724
+ // Side-tab stripe drawn as a single-edge inset box-shadow
1725
+ // (x or y offset 3-12px, other axis 0, no blur/spread, chromatic color):
1726
+ // paints a bar along one edge with no border property involved, so the
1727
+ // element-level border checks never see it. Selection-state indicators
1728
+ // are exempt — an inset stripe on [aria-current] / .active / [role=tab]
1729
+ // marks the selected item; the same stripe unconditionally on every item
1730
+ // is decoration and flags.
1731
+ function scanCssTextForInsetStripe(content) {
1732
+ const customProps = collectCssCustomProps(content);
1733
+ const findings = [];
1734
+ const seen = new Set();
1735
+ const ruleRe = new RegExp(CSS_RULE_BLOCK_SOURCE, 'g');
1736
+ let m;
1737
+ while ((m = ruleRe.exec(content)) !== null) {
1738
+ const selector = m[1].trim();
1739
+ // Selection-state contexts: current-item markers and interaction
1740
+ // states. Tab-strip membership alone ([role=tab], .tabs, bare
1741
+ // [aria-selected]) is NOT exempt — a stripe on every tab in the
1742
+ // group is decoration; only the selected item's indicator stays.
1743
+ if (/:(?:hover|focus|focus-visible|focus-within|active|checked|target)\b/i.test(selector)) continue;
1744
+ if (/\[aria-selected\s*[*^$|~]?=\s*["']?true/i.test(selector)) continue;
1745
+ if (/\[aria-current(?!\s*[*^$|~]?=\s*["']?false)/i.test(selector)) continue;
1746
+ if (/(?:^|[\s._[-])(?:active|current|selected)(?![\w])/i.test(selector)) continue;
1747
+ // Structural tags where a single-edge inset shadow is depth/quoting,
1748
+ // not an accent stripe.
1749
+ if (/(?:^|[\s>+~,(])(?:button|hr|tr|td|th|table|blockquote|pre|code)(?![\w-])/i.test(selector)) continue;
1750
+
1751
+ const decls = parseCssDeclBlock(m[2]);
1752
+ const shadow = decls.get('box-shadow');
1753
+ if (!shadow || !/\binset\b/i.test(shadow)) continue;
1754
+ // Narrow fixed-width elements (logo marks, icon glyphs) use inset
1755
+ // fills as artwork, not edge stripes. Stripe targets — cards, badges,
1756
+ // menu items — are wider or leave width to layout.
1757
+ const declaredWidth = cssLengthToPx(resolveVarRefs(decls.get('width') || decls.get('inline-size') || '', customProps));
1758
+ if (declaredWidth != null && declaredWidth <= 40) continue;
1759
+ const value = resolveVarRefs(shadow, customProps);
1760
+ for (const layer of value.split(/,(?![^(]*\))/)) {
1761
+ if (!/\binset\b/i.test(layer)) continue;
1762
+ const colorInfo = findShadowColor(layer);
1763
+ // Unresolvable colors (currentColor, external vars): don't guess.
1764
+ if (!colorInfo || !colorInfo.color) continue;
1765
+ const c = colorInfo.color;
1766
+ if ((c.a ?? 1) < 0.1) continue;
1767
+ const chroma = Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b);
1768
+ if (chroma < 30) continue;
1769
+ const vals = extractShadowLengths(layer, colorInfo.start, colorInfo.end);
1770
+ const x = vals[0] || 0, y = vals[1] || 0, blur = vals[2] || 0, sp = vals[3] || 0;
1771
+ if (blur !== 0 || sp !== 0) continue;
1772
+ const ax = Math.abs(x), ay = Math.abs(y);
1773
+ const isStripe = (ax >= 3 && ax <= 12 && ay === 0) || (ay >= 3 && ay <= 12 && ax === 0);
1774
+ if (!isStripe) continue;
1775
+ if (seen.has(selector)) break;
1776
+ seen.add(selector);
1777
+ const edge = ay === 0 ? (x > 0 ? 'left' : 'right') : (y > 0 ? 'top' : 'bottom');
1778
+ findings.push({
1779
+ id: 'side-tab',
1780
+ snippet: `${selector} — inset box-shadow ${ay === 0 ? ax : ay}px stripe (${edge})`,
1781
+ });
1782
+ break;
1783
+ }
1784
+ }
1785
+ return findings;
1786
+ }
1787
+
1788
+ // Collect @keyframes names whose body travels horizontally — the marquee
1789
+ // loop. X travel is measured across every translateX/translate/translate3d
1790
+ // X component in the body: a centered element animating something else
1791
+ // keeps a constant -50% X (zero travel) and never qualifies, while a
1792
+ // ticker moves from its resting position to a large offset. Keyframes
1793
+ // with a single X sample that also vary scale/opacity read as pulses or
1794
+ // breathes, not marquees.
1795
+ function collectMarqueeKeyframes(content) {
1796
+ const names = new Set();
1797
+ const re = /@(?:-webkit-)?keyframes\s+([\w-]+)\s*\{/g;
1798
+ let m;
1799
+ while ((m = re.exec(content)) !== null) {
1800
+ let depth = 1;
1801
+ let i = re.lastIndex;
1802
+ while (i < content.length && depth > 0) {
1803
+ const ch = content.charCodeAt(i);
1804
+ if (ch === 0x7b /* { */) depth++;
1805
+ else if (ch === 0x7d /* } */) depth--;
1806
+ i++;
1807
+ }
1808
+ const body = content.slice(re.lastIndex, Math.max(re.lastIndex, i - 1));
1809
+ re.lastIndex = i;
1810
+
1811
+ // Only percentage travel qualifies: a content marquee translates by a
1812
+ // fraction of its own (unknown) track width, so generated tickers use
1813
+ // -50% / -100%. Pixel-travel loops are bespoke product animations —
1814
+ // sweeping playheads, progress indicators — not marquees.
1815
+ const pct = [];
1816
+ const xRe = /\btranslate(?:X|3d)?\(\s*(-?[\d.]+)%/gi;
1817
+ let xm;
1818
+ while ((xm = xRe.exec(body)) !== null) pct.push(parseFloat(xm[1]));
1819
+ if (pct.length === 0) continue;
1820
+ if (pct.length === 1 && /\bscale\(|\bopacity\s*:/i.test(body)) continue;
1821
+ // Implicit start: a lone declared X animates from the element's
1822
+ // resting position, so its magnitude is the travel.
1823
+ const travelPct = pct.length > 1 ? Math.max(...pct) - Math.min(...pct) : Math.abs(pct[0]);
1824
+ if (travelPct >= 20) names.add(m[1]);
1825
+ }
1826
+ return names;
1827
+ }
1828
+
1829
+ // Auto-scrolling marquee: a <marquee> element, or an infinite animation
1830
+ // bound to a keyframe loop that travels a large horizontal distance.
1831
+ // Rotation/opacity animations never qualify (no X travel); JS-driven
1832
+ // carousels with user controls have no infinite CSS X-loop to match.
1833
+ function scanCssTextForMarquee(content) {
1834
+ const findings = [];
1835
+ if (/<marquee\b/i.test(content)) {
1836
+ findings.push({ id: 'marquee', snippet: '<marquee> element' });
1837
+ }
1838
+ const marqueeKeyframes = collectMarqueeKeyframes(content);
1839
+ if (marqueeKeyframes.size === 0) return findings;
1840
+ const seen = new Set();
1841
+ const ruleRe = new RegExp(CSS_RULE_BLOCK_SOURCE, 'g');
1842
+ let m;
1843
+ while ((m = ruleRe.exec(content)) !== null) {
1844
+ const selector = m[1].trim();
1845
+ const decls = parseCssDeclBlock(m[2]);
1846
+ for (const name of infiniteAnimationNames(decls)) {
1847
+ if (!marqueeKeyframes.has(name)) continue;
1848
+ const key = `${selector} ${name}`;
1849
+ if (seen.has(key)) continue;
1850
+ seen.add(key);
1851
+ findings.push({ id: 'marquee', snippet: `${selector} — infinite horizontal loop animation "${name}"` });
1852
+ }
1853
+ }
1854
+ return findings;
1855
+ }
1856
+
1857
+ // Collect @keyframes names and whether each one reads as a "pulse" —
1858
+ // i.e. it varies opacity, scale, or box-shadow. Rotation-only keyframes
1859
+ // (spinners) are explicitly not pulses.
1860
+ function collectPulseKeyframes(content) {
1861
+ const map = new Map();
1862
+ const re = /@(?:-webkit-)?keyframes\s+([\w-]+)\s*\{/g;
1863
+ let m;
1864
+ while ((m = re.exec(content)) !== null) {
1865
+ let depth = 1;
1866
+ let i = re.lastIndex;
1867
+ while (i < content.length && depth > 0) {
1868
+ const ch = content.charCodeAt(i);
1869
+ if (ch === 0x7b /* { */) depth++;
1870
+ else if (ch === 0x7d /* } */) depth--;
1871
+ i++;
1872
+ }
1873
+ const body = content.slice(re.lastIndex, Math.max(re.lastIndex, i - 1));
1874
+ const pulses = /\bopacity\s*:/i.test(body)
1875
+ || /\bbox-shadow\s*:/i.test(body)
1876
+ || /\btransform\s*:[^;{}]*\bscale/i.test(body);
1877
+ if (!map.has(m[1]) || pulses) map.set(m[1], pulses);
1878
+ re.lastIndex = i;
1879
+ }
1880
+ return map;
1881
+ }
1882
+
1883
+ const ANIMATION_VALUE_KEYWORDS = new Set([
1884
+ 'ease', 'ease-in', 'ease-out', 'ease-in-out', 'linear',
1885
+ 'infinite', 'alternate', 'alternate-reverse', 'normal', 'reverse',
1886
+ 'none', 'forwards', 'backwards', 'both', 'running', 'paused',
1887
+ 'step-start', 'step-end', 'inherit', 'initial', 'unset',
1888
+ ]);
1889
+
1890
+ // Extract animation names that run with iteration-count: infinite from a
1891
+ // declaration block (shorthand layers or animation-name + iteration-count).
1892
+ function infiniteAnimationNames(decls) {
1893
+ const out = [];
1894
+ const shorthand = decls.get('animation');
1895
+ if (shorthand) {
1896
+ for (const layer of shorthand.split(/,(?![^(]*\))/)) {
1897
+ if (!/\binfinite\b/i.test(layer)) continue;
1898
+ const name = layer.split(/\s+/).find(t =>
1899
+ /^[a-zA-Z_-][\w-]*$/.test(t) && !ANIMATION_VALUE_KEYWORDS.has(t.toLowerCase()));
1900
+ if (name) out.push(name);
1901
+ }
1902
+ }
1903
+ const nameDecl = decls.get('animation-name');
1904
+ if (nameDecl && /\binfinite\b/i.test(decls.get('animation-iteration-count') || '')) {
1905
+ for (const raw of nameDecl.split(',')) {
1906
+ const t = raw.trim();
1907
+ if (t && t.toLowerCase() !== 'none') out.push(t);
1908
+ }
1909
+ }
1910
+ return out;
1911
+ }
1912
+
1913
+ function isRoundDotRadius(radiusValue, w, h) {
1914
+ if (!radiusValue) return false;
1915
+ const first = String(radiusValue).trim().split(/\s+/)[0];
1916
+ const pct = first.match(/^([\d.]+)%$/);
1917
+ if (pct) return parseFloat(pct[1]) >= 40;
1918
+ const px = cssLengthToPx(first);
1919
+ if (px == null) return false;
1920
+ return px >= 999 || px >= 0.4 * Math.min(w, h);
1921
+ }
1922
+
1923
+ // Remove @media blocks whose condition is prefers-reduced-motion: reduce.
1924
+ // Those blocks describe the accessibility fallback, not the default
1925
+ // experience that ships — an `animation: none` reset inside one must not
1926
+ // mask the resting-state animation the page plays for everyone else.
1927
+ function stripReducedMotionBlocks(content) {
1928
+ const re = /@media[^{]*prefers-reduced-motion\s*:\s*reduce[^{]*\{/gi;
1929
+ let out = '';
1930
+ let last = 0;
1931
+ let m;
1932
+ while ((m = re.exec(content)) !== null) {
1933
+ let depth = 1;
1934
+ let i = re.lastIndex;
1935
+ while (i < content.length && depth > 0) {
1936
+ const ch = content.charCodeAt(i);
1937
+ if (ch === 0x7b /* { */) depth++;
1938
+ else if (ch === 0x7d /* } */) depth--;
1939
+ i++;
1940
+ }
1941
+ out += content.slice(last, m.index);
1942
+ last = i;
1943
+ re.lastIndex = i;
1944
+ }
1945
+ return out + content.slice(last);
1946
+ }
1947
+
1948
+ // Source-index ranges of <header> and <nav> landmark elements in an HTML
1949
+ // string. Lets string-level scans decide whether a matched element sits in
1950
+ // the page chrome (the hero/nav region) without needing a DOM.
1951
+ function landmarkSourceRanges(content) {
1952
+ const ranges = [];
1953
+ for (const tag of ['header', 'nav']) {
1954
+ const re = new RegExp(`<${tag}\\b|</${tag}\\s*>`, 'gi');
1955
+ const stack = [];
1956
+ let m;
1957
+ while ((m = re.exec(content)) !== null) {
1958
+ if (m[0].charAt(1) === '/') {
1959
+ const start = stack.pop();
1960
+ if (start != null) ranges.push([start, m.index]);
1961
+ } else {
1962
+ stack.push(m.index);
1963
+ }
1964
+ }
1965
+ }
1966
+ return ranges;
1967
+ }
1968
+
1969
+ function indexInSourceRanges(index, ranges) {
1970
+ return ranges.some(([start, end]) => index >= start && index < end);
1971
+ }
1972
+
1973
+ // Does any element targeted by the final compound of `selector` appear
1974
+ // inside a header/nav landmark range of the HTML source? Resolves the last
1975
+ // .class or #id token of the selector against class/id attributes; a
1976
+ // tag-only compound is never resolvable this way and returns false
1977
+ // (conservative: no promotion without placement evidence).
1978
+ function selectorHitsLandmark(content, selector, ranges) {
1979
+ if (!ranges || ranges.length === 0) return false;
1980
+ const last = selector.split(/[\s>+~]+/).filter(Boolean).pop() || '';
1981
+ const idMatch = last.match(/#([A-Za-z_][\w-]*)/);
1982
+ const classMatch = last.match(/\.([A-Za-z_][\w-]*)/);
1983
+ let attrRe = null;
1984
+ if (idMatch) {
1985
+ const id = idMatch[1].replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1986
+ attrRe = new RegExp(`<[a-zA-Z][^>]*\\bid\\s*=\\s*["']${id}["']`, 'gi');
1987
+ } else if (classMatch) {
1988
+ const cls = classMatch[1].replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1989
+ attrRe = new RegExp(`<[a-zA-Z][^>]*\\bclass\\s*=\\s*["'][^"']*(?<![\\w-])${cls}(?![\\w-])[^"']*["']`, 'gi');
1990
+ }
1991
+ if (!attrRe) return false;
1992
+ let m;
1993
+ while ((m = attrRe.exec(content)) !== null) {
1994
+ if (indexInSourceRanges(m.index, ranges)) return true;
1995
+ }
1996
+ return false;
1997
+ }
1998
+
1999
+ // Small circular indicator bound to an infinite pulse animation — the
2000
+ // decorative "live" dot. Gates: tiny (<= 16px square-ish), round
2001
+ // (border-radius >= 40% or pill values), and an infinite animation whose
2002
+ // keyframes vary opacity/scale/box-shadow (or a pulse/blink/ping name when
2003
+ // the keyframes aren't in the scanned text). Rotation-only animations
2004
+ // (spinners) never flag.
2005
+ //
2006
+ // Declarations for one selector are merged across rule blocks before the
2007
+ // predicate runs: size in the base rule plus the animation added in a
2008
+ // second block (or inside a matching @media block) is the construction
2009
+ // that ships. prefers-reduced-motion: reduce overrides are stripped first
2010
+ // so their animation resets don't mask the default experience. A dot whose
2011
+ // element sits inside a header/nav landmark is the hero liveness cliché
2012
+ // and is promoted to error severity; occurrences elsewhere keep the
2013
+ // registry default severity.
2014
+ function scanCssTextForPulsingDot(content) {
2015
+ const customProps = collectCssCustomProps(content);
2016
+ const keyframes = collectPulseKeyframes(content);
2017
+ const heroRanges = landmarkSourceRanges(content);
2018
+ const findings = [];
2019
+ const seen = new Set();
2020
+
2021
+ // Merge declarations per selector across rule blocks, approximating the
2022
+ // cascade: later declarations for the same property win. Comma lists are
2023
+ // split so `.a, .b { … }` contributes to both selectors. Comments are
2024
+ // stripped first so they neither pollute selector keys nor smuggle a
2025
+ // comma into the selector-list split.
2026
+ const scanText = stripReducedMotionBlocks(content).replace(/\/\*[\s\S]*?\*\//g, ' ');
2027
+ const merged = new Map();
2028
+ const ruleRe = new RegExp(CSS_RULE_BLOCK_SOURCE, 'g');
2029
+ let m;
2030
+ while ((m = ruleRe.exec(scanText)) !== null) {
2031
+ const decls = parseCssDeclBlock(m[2]);
2032
+ if (decls.size === 0) continue;
2033
+ for (const rawSelector of m[1].split(',')) {
2034
+ const selector = rawSelector.trim();
2035
+ if (!selector || selector.startsWith('@')) continue;
2036
+ let acc = merged.get(selector);
2037
+ if (!acc) {
2038
+ acc = new Map();
2039
+ merged.set(selector, acc);
2040
+ }
2041
+ for (const [prop, value] of decls) acc.set(prop, value);
2042
+ }
2043
+ }
2044
+
2045
+ for (const [selector, decls] of merged) {
2046
+ const names = infiniteAnimationNames(decls);
2047
+ if (names.length === 0) continue;
2048
+ const pulseName = names.find(n => {
2049
+ const known = keyframes.get(n);
2050
+ if (known != null) return known;
2051
+ return /pulse|blink|ping/i.test(n);
2052
+ });
2053
+ if (!pulseName) continue;
2054
+
2055
+ const w = cssLengthToPx(resolveVarRefs(
2056
+ decls.get('width') || decls.get('inline-size') || '', customProps));
2057
+ const h = cssLengthToPx(resolveVarRefs(
2058
+ decls.get('height') || decls.get('block-size') || '', customProps));
2059
+ if (w == null || h == null || w < 2 || h < 2 || w > 16 || h > 16) continue;
2060
+
2061
+ const radius = resolveVarRefs(decls.get('border-radius') || '', customProps);
2062
+ if (!isRoundDotRadius(radius, w, h)) continue;
2063
+
2064
+ if (seen.has(selector)) continue;
2065
+ seen.add(selector);
2066
+ const inLandmark = selectorHitsLandmark(content, selector, heroRanges);
2067
+ findings.push({
2068
+ id: 'pulsing-dot',
2069
+ snippet: `${selector} — ${w}x${h}px dot with infinite "${pulseName}" animation${inLandmark ? ' in header/nav' : ''}`,
2070
+ selector,
2071
+ ...(inLandmark ? { severity: 'error' } : {}),
2072
+ });
2073
+ }
2074
+
2075
+ // Tailwind utilities: animate-ping / animate-pulse on a tiny rounded-full
2076
+ // element declared entirely in the class attribute.
2077
+ const classRe = /class\s*=\s*(?:"([^"]*)"|'([^']*)')/gi;
2078
+ let cm;
2079
+ while ((cm = classRe.exec(content)) !== null) {
2080
+ const cls = cm[1] || cm[2] || '';
2081
+ const anim = cls.match(/\banimate-(ping|pulse)\b/);
2082
+ if (!anim) continue;
2083
+ if (!/\brounded-full\b/.test(cls)) continue;
2084
+ if (!/\b(?:w|h|size)-(?:1|1\.5|2|2\.5|3|3\.5|4)\b/.test(cls)) continue;
2085
+ const key = `tw:${cls}`;
2086
+ if (seen.has(key)) continue;
2087
+ seen.add(key);
2088
+ const inLandmark = indexInSourceRanges(cm.index, heroRanges);
2089
+ findings.push({
2090
+ id: 'pulsing-dot',
2091
+ snippet: `animate-${anim[1]} on tiny rounded-full element${inLandmark ? ' in header/nav' : ''}`,
2092
+ ...(inLandmark ? { severity: 'error' } : {}),
2093
+ });
2094
+ }
2095
+
2096
+ return findings;
2097
+ }
2098
+
2099
+ // Shape-assembled illustration: a large inline SVG composing a pictorial
2100
+ // scene from many primitive shapes (rect / circle / ellipse / polygon) in
2101
+ // several fill colors — the clip-art hero mascot. Gates keep the legitimate
2102
+ // SVG population out:
2103
+ // • icons and logos: intrinsic size gate (>= 200px on both axes, from
2104
+ // width/height attributes or the viewBox when no explicit size is set)
2105
+ // • charts / labeled diagrams: more than two <text>/<tspan> nodes exempts
2106
+ // the graphic (axis labels, callouts)
2107
+ // • line drawings / technical diagrams: primitive count < 8 or fewer
2108
+ // than 3 distinct fills never qualifies (stroke-only art has no fills)
2109
+ // • tiling background textures: any <pattern> definition exempts
2110
+ function scanHtmlForShapeAssembledIllustration(html) {
2111
+ const findings = [];
2112
+ const svgRe = /<svg\b[^>]*>[\s\S]*?<\/svg>/gi;
2113
+ let m;
2114
+ while ((m = svgRe.exec(html)) !== null) {
2115
+ const block = m[0];
2116
+ const openTag = (block.match(/^<svg\b[^>]*>/i) || [''])[0];
2117
+
2118
+ // Data-bearing or annotated graphics: axis labels and callout text
2119
+ // mark a chart or diagram, not a mascot.
2120
+ const textCount = (block.match(/<(?:text|tspan)\b/gi) || []).length;
2121
+ if (textCount > 2) continue;
2122
+ // Tiling texture definitions are decorative backgrounds, not scenes.
2123
+ if (/<pattern\b/i.test(block)) continue;
2124
+
2125
+ const primitives = (block.match(/<(?:rect|circle|ellipse|polygon)\b/gi) || []).length;
2126
+ if (primitives < 8) continue;
2127
+
2128
+ // Intrinsic size: explicit width/height attributes win; fall back to
2129
+ // the viewBox box. Percentage or missing sizes stay unresolvable on
2130
+ // that axis and the viewBox speaks for them.
2131
+ const attrDim = (name) => {
2132
+ // (?<![-\w]) keeps compound attributes like stroke-width from
2133
+ // masquerading as the svg's own width.
2134
+ const am = openTag.match(new RegExp(`(?<![-\\w])${name}\\s*=\\s*["']\\s*([\\d.]+)(?:px)?\\s*["']`, 'i'));
2135
+ return am ? parseFloat(am[1]) : null;
2136
+ };
2137
+ const vb = openTag.match(/\bviewBox\s*=\s*["']\s*[-\d.]+[\s,]+[-\d.]+[\s,]+([\d.]+)[\s,]+([\d.]+)\s*["']/i);
2138
+ const w = attrDim('width') ?? (vb ? parseFloat(vb[1]) : null);
2139
+ const h = attrDim('height') ?? (vb ? parseFloat(vb[2]) : null);
2140
+ if (w == null || h == null || w < 200 || h < 200) continue;
2141
+
2142
+ // Distinct fill paints (attributes and inline styles), excluding
2143
+ // non-paints. Multiple fills are what turn a shape pile into a scene.
2144
+ const fills = new Set();
2145
+ for (const fm of block.matchAll(/\bfill\s*[:=]\s*["']?\s*([^"';>}\s]+)/gi)) {
2146
+ const paint = fm[1].trim().toLowerCase();
2147
+ if (!paint || ['none', 'transparent', 'currentcolor', 'inherit'].includes(paint)) continue;
2148
+ fills.add(paint);
2149
+ }
2150
+ if (fills.size < 3) continue;
2151
+
2152
+ findings.push({
2153
+ id: 'shape-assembled-illustration',
2154
+ snippet: `inline <svg> scene: ${primitives} primitive shapes, ~${Math.round(w)}x${Math.round(h)}px, ${fills.size} fill colors`,
2155
+ });
2156
+ }
2157
+ return findings;
2158
+ }
2159
+
1117
2160
  /**
1118
2161
  * Regex-on-HTML checks shared between browser and Node page-level detection.
1119
2162
  * These don't need DOM access, just the raw HTML string.
@@ -1147,6 +2190,16 @@ function checkHtmlPatterns(html) {
1147
2190
  findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
1148
2191
  }
1149
2192
 
2193
+ // --- Borders ---
2194
+
2195
+ // Side-tab accent stripe drawn as an absolutely-positioned pseudo-element
2196
+ // (no border property involved, so the element-level border checks and
2197
+ // the border-left regexes never see it).
2198
+ findings.push(...scanCssTextForPseudoStripe(html));
2199
+
2200
+ // Side-tab accent stripe drawn as a single-edge inset box-shadow.
2201
+ findings.push(...scanCssTextForInsetStripe(html));
2202
+
1150
2203
  // --- Layout ---
1151
2204
 
1152
2205
  // Monotonous spacing
@@ -1222,33 +2275,34 @@ function checkHtmlPatterns(html) {
1222
2275
  }
1223
2276
  }
1224
2277
 
1225
- // --- Dark glow ---
2278
+ // Pulsing status dots (tiny circular elements on infinite pulse animations)
2279
+ findings.push(...scanCssTextForPulsingDot(html));
1226
2280
 
1227
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
1228
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
1229
- if (darkBgRe.test(html) || twDarkBg.test(html)) {
1230
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
1231
- let shm;
1232
- while ((shm = shadowRe.exec(html)) !== null) {
1233
- const val = shm[1];
1234
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
1235
- if (!colorMatch) continue;
1236
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
1237
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue;
1238
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
1239
- if (pxVals.length >= 3 && pxVals[2] > 4) {
1240
- findings.push({ id: 'dark-glow', snippet: `Colored glow (rgb(${r},${g},${b})) on dark page` });
1241
- break;
1242
- }
1243
- }
2281
+ // Shape-assembled illustrations (large pictorial SVGs built from primitives)
2282
+ findings.push(...scanHtmlForShapeAssembledIllustration(html));
2283
+
2284
+ // Auto-scrolling marquees (<marquee> or infinite horizontal loop animations)
2285
+ findings.push(...scanCssTextForMarquee(html));
2286
+
2287
+ // --- Dark glow / chromatic halo shadows ---
2288
+
2289
+ const glowHits = scanCssTextForGlow(html);
2290
+ if (glowHits.length > 0) {
2291
+ findings.push({ id: 'dark-glow', snippet: glowHits[0].snippet });
2292
+ }
2293
+
2294
+ // Radial-gradient background halo (gradient-drawn sibling of dark-glow)
2295
+ const haloHits = scanCssTextForRadialHalo(html);
2296
+ if (haloHits.length > 0) {
2297
+ findings.push({ id: 'radial-halo', snippet: haloHits[0].snippet });
1244
2298
  }
1245
2299
 
1246
- // --- Provider tells (gated): repeating-gradient stripes (GPT) ---
2300
+ // --- Generated-UI tells: repeating-gradient stripes ---
1247
2301
  if (/repeating-(?:linear|radial|conic)-gradient\s*\(/i.test(html)) {
1248
2302
  findings.push({ id: 'repeating-stripes-gradient', snippet: 'repeating-gradient decorative stripes' });
1249
2303
  }
1250
2304
 
1251
- // --- Provider tells (gated): two-axis grid-line background (Codex/GPT) ---
2305
+ // --- Generated-UI tells: two-axis grid-line background ---
1252
2306
  // The Codex grid tell is two hairline `linear-gradient(... <color> 1px,
1253
2307
  // transparent 1px)` layers (one per axis) tiled by a repeating
1254
2308
  // `background-size` cell. Both signals must co-occur in the SAME style block
@@ -1261,30 +2315,12 @@ function checkHtmlPatterns(html) {
1261
2315
  // in for the second axis. Colors like `oklch(96% 0.012 82 / 0.055)` carry
1262
2316
  // nested parens, so match the hairline stop directly rather than parsing
1263
2317
  // whole gradient layers.
1264
- {
1265
- const hairlineRe = /\b\d{1,3}px\s*,\s*transparent\s+\d{1,3}px/gi;
1266
- const gridSizeRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\b/i;
1267
- const bgDeclRe = /\bbackground(?:-image)?\s*:\s*([^;{}"']*)/gi;
1268
- const blockRe = /\{([^{}]*)\}|style\s*=\s*"([^"]*)"|style\s*=\s*'([^']*)'/gi;
1269
- let blk;
1270
- while ((blk = blockRe.exec(html)) !== null) {
1271
- const block = blk[1] || blk[2] || blk[3] || '';
1272
- if (!gridSizeRe.test(block)) continue;
1273
- let hairlineCount = 0;
1274
- let bm;
1275
- bgDeclRe.lastIndex = 0;
1276
- while ((bm = bgDeclRe.exec(block)) !== null) {
1277
- const stops = bm[1].match(hairlineRe);
1278
- if (stops) hairlineCount += stops.length;
1279
- }
1280
- if (hairlineCount >= 2) {
1281
- findings.push({ id: 'codex-grid-background', snippet: 'two-axis grid-line gradient background' });
1282
- break;
1283
- }
1284
- }
2318
+ const gridHits = scanCssTextForGridBackground(html);
2319
+ if (gridHits.length > 0) {
2320
+ findings.push({ id: 'codex-grid-background', snippet: gridHits[0].snippet });
1285
2321
  }
1286
2322
 
1287
- // --- Provider tells (gated): "X theater" framing copy (GPT) ---
2323
+ // --- Generated-copy tells: "X theater" framing copy ---
1288
2324
  // Lives here (regex-on-HTML) rather than in the text-content analyzers so it
1289
2325
  // runs in the bundled browser path too, not just the CLI/static path.
1290
2326
  {
@@ -1296,7 +2332,7 @@ function checkHtmlPatterns(html) {
1296
2332
  if (tm) findings.push({ id: 'theater-slop-phrase', snippet: `"${tm[0].trim()}"` });
1297
2333
  }
1298
2334
 
1299
- // --- Provider tells (gated): image hover transform (Gemini) ---
2335
+ // --- Generated-UI tells: image hover transform ---
1300
2336
  // A CSS `img...:hover { transform: ... }` rule, or a Tailwind hover:scale /
1301
2337
  // hover:rotate / hover:translate utility on an <img>. Each distinct
1302
2338
  // mechanism is its own finding.
@@ -1325,7 +2361,11 @@ function checkHtmlPatterns(html) {
1325
2361
  // `background: #abc`. Real browsers always decompose, so the fallback is
1326
2362
  // a no-op there.
1327
2363
  function readOwnBackgroundColor(el, computedStyle) {
1328
- const bg = parseRgb(computedStyle.backgroundColor);
2364
+ // Real browsers keep wide-gamut/computed color functions (oklch(), oklab(),
2365
+ // color-mix() results) in getComputedStyle output, which plain parseRgb
2366
+ // misses — a flat oklch button background would silently skip every
2367
+ // contrast check without the parseAnyColor fallback.
2368
+ const bg = parseRgb(computedStyle.backgroundColor) || parseAnyColor(computedStyle.backgroundColor);
1329
2369
  if (DETECTOR_IS_BROWSER || (bg && bg.a >= 0.1)) return bg;
1330
2370
  const rawStyle = el.getAttribute?.('style') || '';
1331
2371
  const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
@@ -1347,6 +2387,18 @@ function readOwnBackgroundColor(el, computedStyle) {
1347
2387
 
1348
2388
  function resolveBackground(el, win, customPropMap) {
1349
2389
  let current = el;
2390
+ // Translucent layers (0.1 < a < 1) found on the way down to an opaque
2391
+ // base. A browser composites these over the base; the old behavior
2392
+ // either returned them as-if-opaque (browser mode) or skipped them
2393
+ // entirely (static mode), both of which misstate the effective surface
2394
+ // for contrast checks (e.g. `background: color-mix(in oklab, var(--hot)
2395
+ // 16%, transparent)` chips on dark pages).
2396
+ const overlays = [];
2397
+ const flatten = (base) => {
2398
+ let acc = base;
2399
+ for (let i = overlays.length - 1; i >= 0; i--) acc = compositeColorOver(overlays[i], acc);
2400
+ return acc;
2401
+ };
1350
2402
  while (current && current.nodeType === 1) {
1351
2403
  const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
1352
2404
  const bgImage = style.backgroundImage || '';
@@ -1359,7 +2411,9 @@ function resolveBackground(el, win, customPropMap) {
1359
2411
  // decorative. The old behavior bailed on any gradient ancestor, which
1360
2412
  // caused massive false-positive contrast findings on grain-textured
1361
2413
  // body backgrounds.
1362
- let bg = parseRgb(style.backgroundColor);
2414
+ // Real browsers serialize wide-gamut computed values as oklab()/oklch()
2415
+ // (e.g. any color-mix() result), which plain parseRgb misses.
2416
+ let bg = parseRgb(style.backgroundColor) || parseAnyColor(style.backgroundColor);
1363
2417
  if (!DETECTOR_IS_BROWSER && (!bg || bg.a < 0.1)) {
1364
2418
  // jsdom returns literal "var(--X)" / "oklch(...)" strings. Resolve
1365
2419
  // through customPropMap so Tailwind v4 color tokens become RGB.
@@ -1379,7 +2433,8 @@ function resolveBackground(el, win, customPropMap) {
1379
2433
  }
1380
2434
 
1381
2435
  if (bg && bg.a > 0.1) {
1382
- if (DETECTOR_IS_BROWSER || bg.a >= 0.5) return bg;
2436
+ if (bg.a >= 0.99) return flatten(bg);
2437
+ overlays.push(bg);
1383
2438
  }
1384
2439
  // No solid bg-color at this level. If THIS level has a gradient/url
1385
2440
  // with no underlying solid color we can read:
@@ -1395,13 +2450,13 @@ function resolveBackground(el, win, customPropMap) {
1395
2450
  // bgs worth checking against).
1396
2451
  if (hasGradientOrUrl) {
1397
2452
  if (current.tagName === 'BODY' || current.tagName === 'HTML') {
1398
- return { r: 255, g: 255, b: 255, a: 1 };
2453
+ return flatten({ r: 255, g: 255, b: 255, a: 1 });
1399
2454
  }
1400
2455
  return null;
1401
2456
  }
1402
2457
  current = current.parentElement;
1403
2458
  }
1404
- return { r: 255, g: 255, b: 255 };
2459
+ return flatten({ r: 255, g: 255, b: 255, a: 1 });
1405
2460
  }
1406
2461
 
1407
2462
  // Walk parents looking for a gradient background and return its color stops.
@@ -1463,6 +2518,43 @@ function resolveBorderRadiusPx(el, style, widthPx, win) {
1463
2518
 
1464
2519
  // Browser adapters — call getComputedStyle/getBoundingClientRect on live DOM
1465
2520
 
2521
+ // Selected-state context for accent stripes. Only an actual selection
2522
+ // marker exempts the stripe as the standard active-item indicator:
2523
+ // aria-selected="true", aria-current (any non-false value), or an
2524
+ // active/current/selected class hint. Tab-strip MEMBERSHIP alone
2525
+ // ([role=tablist]/[role=tab]/.tabs ancestry, aria-selected="false")
2526
+ // deliberately does not — a chromatic stripe repeated on every tab in
2527
+ // the group, or on every menu item, is decoration, not state; the
2528
+ // selected item's own underline stays legal.
2529
+ function isTabContextElement(el) {
2530
+ if (!el) return false;
2531
+ try {
2532
+ if (el.closest?.('[aria-selected="true"], [aria-current]:not([aria-current="false"])')) return true;
2533
+ } catch { /* selector engine differences — fall through to class scan */ }
2534
+ let cur = el, depth = 0;
2535
+ while (cur && cur.nodeType === 1 && depth < 6) {
2536
+ const cls = String(cur.getAttribute?.('class') || cur.className || '');
2537
+ if (/(?:^|[\s_-])(?:active|current|selected)(?:$|[\s_-])/i.test(cls)) return true;
2538
+ cur = cur.parentElement;
2539
+ depth++;
2540
+ }
2541
+ return false;
2542
+ }
2543
+
2544
+ // Status-surface context for accent borders. On a live status/alert region
2545
+ // (role=status|alert|alertdialog|log, or aria-live=polite|assertive) a colored
2546
+ // single-edge border is the established severity-accent convention — a toast,
2547
+ // snackbar, or callout bar — not the decorative side-tab tell. The element
2548
+ // itself or a wrapping live region qualifies. This never fires from the
2549
+ // CSS-only / regex scanners, which have no role information.
2550
+ function isStatusContextElement(el) {
2551
+ if (!el) return false;
2552
+ try {
2553
+ if (el.closest?.('[role="status"], [role="alert"], [role="alertdialog"], [role="log"], [aria-live="polite"], [aria-live="assertive"]')) return true;
2554
+ } catch { /* selector engine differences — fall through */ }
2555
+ return false;
2556
+ }
2557
+
1466
2558
  function checkElementBordersDOM(el) {
1467
2559
  const tag = el.tagName.toLowerCase();
1468
2560
  if (BORDER_SAFE_TAGS.has(tag)) return [];
@@ -1475,7 +2567,105 @@ function checkElementBordersDOM(el) {
1475
2567
  widths[s] = parseFloat(style[`border${s}Width`]) || 0;
1476
2568
  colors[s] = style[`border${s}Color`] || '';
1477
2569
  }
1478
- return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0);
2570
+ const ownBg = parseRgb(style.backgroundColor) || parseAnyColor(style.backgroundColor);
2571
+ return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0, {
2572
+ tabContext: isTabContextElement(el),
2573
+ statusContext: isStatusContextElement(el),
2574
+ badgeLike: !!(ownBg && (ownBg.a ?? 1) > 0.1),
2575
+ });
2576
+ }
2577
+
2578
+ // Browser-side twin of scanCssTextForPseudoStripe. The text scanner reads
2579
+ // stylesheet source, so a stripe whose color only exists at runtime (an
2580
+ // inline per-card custom property, a JS-assigned var) or whose geometry
2581
+ // resolves in layout never matches it. In a real browser the pseudo-element's
2582
+ // computed style carries the actual used color and px geometry — check those
2583
+ // directly. Gates mirror the text scanner: 3-12px thick, chromatic fill,
2584
+ // spanning (nearly) the full edge; corner rounding on the host card is
2585
+ // irrelevant. Exemptions stay narrow: structural/prose tags, real selection
2586
+ // markers (isTabContextElement), and button/link affordances for the
2587
+ // horizontal variant.
2588
+ function checkElementPseudoStripeDOM(el) {
2589
+ const tag = el.tagName.toLowerCase();
2590
+ if (BORDER_SAFE_TAGS.has(tag) || tag === 'summary') return [];
2591
+ if (el.closest?.('nav, blockquote, pre')) return [];
2592
+ if (!isRenderedForBrowserRule(el)) return [];
2593
+ const rect = el.getBoundingClientRect();
2594
+ if (rect.width < 40 || rect.height < 20) return [];
2595
+ if (isTabContextElement(el)) return [];
2596
+
2597
+ const findings = [];
2598
+ for (const which of ['::before', '::after']) {
2599
+ let ps;
2600
+ try { ps = getComputedStyle(el, which); } catch { continue; }
2601
+ if (!ps || ps.content === 'none' || ps.content === '') continue;
2602
+ if (ps.position !== 'absolute' && ps.position !== 'fixed') continue;
2603
+ if ((parseFloat(ps.opacity) || 0) <= 0.01 || ps.display === 'none') continue;
2604
+ const w = parseFloat(ps.width) || 0;
2605
+ const h = parseFloat(ps.height) || 0;
2606
+ if (!(w > 0 && h > 0)) continue;
2607
+
2608
+ // Used values: for absolutely-positioned boxes the browser resolves
2609
+ // both edge offsets after layout, so left/right (and top/bottom) are
2610
+ // real distances, never "auto".
2611
+ const left = parseFloat(ps.left);
2612
+ const right = parseFloat(ps.right);
2613
+ const top = parseFloat(ps.top);
2614
+ const bottom = parseFloat(ps.bottom);
2615
+ const hugs = (v) => Number.isFinite(v) && v >= -2 && v <= 2;
2616
+
2617
+ let edge = null;
2618
+ let thickness = null;
2619
+ // Vertical stripe: narrow box spanning (nearly) the full height of the
2620
+ // host, hugging its left or right edge. "Nearly" tolerates the floating
2621
+ // variant that backs off each end by a small inset.
2622
+ if (w >= 3 && w <= 12 && h >= rect.height - 44 && h >= rect.height * 0.5) {
2623
+ edge = hugs(left) ? 'left' : hugs(right) ? 'right' : null;
2624
+ thickness = w;
2625
+ }
2626
+ // Horizontal stripe riding the top or bottom edge. Button/link-styled
2627
+ // hosts keep their underline affordances.
2628
+ if (!edge && h >= 3 && h <= 12 && w >= rect.width - 44 && w >= rect.width * 0.5) {
2629
+ const cls = String(el.getAttribute?.('class') || el.className || '');
2630
+ if (!/(?:^|[\s_-])(?:btn|button|link)(?:$|[\s\w_-])/i.test(cls)) {
2631
+ edge = hugs(top) ? 'top' : hugs(bottom) ? 'bottom' : null;
2632
+ thickness = h;
2633
+ }
2634
+ }
2635
+ if (!edge) continue;
2636
+
2637
+ const bg = parseRgb(ps.backgroundColor) || parseAnyColor(ps.backgroundColor);
2638
+ if (!bg || (bg.a ?? 1) < 0.1) continue;
2639
+ if (Math.max(bg.r, bg.g, bg.b) - Math.min(bg.r, bg.g, bg.b) < 30) continue;
2640
+
2641
+ findings.push({
2642
+ id: 'side-tab',
2643
+ snippet: `${classSelector(el)}${which} — absolute ${thickness}px pseudo-element stripe (${edge})`,
2644
+ });
2645
+ }
2646
+ return findings;
2647
+ }
2648
+
2649
+ // Full-cover surface pseudo (browser): a ::before/::after positioned
2650
+ // absolute/fixed whose box covers (nearly) the whole host and carries an
2651
+ // opaque background. That pseudo is the element's visible surface even
2652
+ // though the element's own background-color reads transparent — the nav-CTA
2653
+ // construction that otherwise escapes every own-background contrast gate.
2654
+ function readPseudoSurfaceDOM(el, rect) {
2655
+ for (const which of ['::before', '::after']) {
2656
+ let ps;
2657
+ try { ps = getComputedStyle(el, which); } catch { continue; }
2658
+ if (!ps || ps.content === 'none' || ps.content === '') continue;
2659
+ if (ps.position !== 'absolute' && ps.position !== 'fixed') continue;
2660
+ if (ps.display === 'none' || (parseFloat(ps.opacity) || 1) < 0.9) continue;
2661
+ const w = parseFloat(ps.width) || 0;
2662
+ const h = parseFloat(ps.height) || 0;
2663
+ if (w < rect.width - 4 || h < rect.height - 4) continue;
2664
+ const bg = parseRgb(ps.backgroundColor) || parseAnyColor(ps.backgroundColor);
2665
+ if (!bg || (bg.a ?? 1) < 0.9) continue;
2666
+ return bg;
2667
+ }
2668
+ return null;
1479
2669
  }
1480
2670
 
1481
2671
  function checkElementColorsDOM(el) {
@@ -1488,11 +2678,24 @@ function checkElementColorsDOM(el) {
1488
2678
  const style = getComputedStyle(el);
1489
2679
  const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
1490
2680
  const hasDirectText = directText.trim().length > 0;
1491
- const effectiveBg = resolveBackground(el);
2681
+ let effectiveBg = resolveBackground(el);
2682
+ let ownBg = readOwnBackgroundColor(el, style);
2683
+ if (!ownBg || (ownBg.a ?? 1) <= 0.5) {
2684
+ const pseudoSurface = readPseudoSurfaceDOM(el, rect);
2685
+ if (pseudoSurface) {
2686
+ ownBg = pseudoSurface;
2687
+ effectiveBg = pseudoSurface;
2688
+ }
2689
+ }
1492
2690
  return checkColors({
1493
2691
  tag,
1494
- textColor: parseRgb(style.color),
1495
- bgColor: readOwnBackgroundColor(el, style),
2692
+ // Chrome serializes computed colors specified in modern spaces as
2693
+ // oklch()/oklab() strings; without the parseAnyColor fallback the text
2694
+ // color comes back null and the low-contrast / gray-on-color checks
2695
+ // silently never run (the shipped miss: a nav CTA whose text color was
2696
+ // an oklch token near its own oklch background).
2697
+ textColor: parseRgb(style.color) || parseAnyColor(style.color),
2698
+ bgColor: ownBg,
1496
2699
  effectiveBg,
1497
2700
  effectiveBgStops: effectiveBg ? null : resolveGradientStops(el),
1498
2701
  fontSize: parseFloat(style.fontSize) || 16,
@@ -1553,6 +2756,21 @@ function checkElementItalicSerifDOM(el) {
1553
2756
  });
1554
2757
  }
1555
2758
 
2759
+ function domAccentDashPseudo(el) {
2760
+ for (const which of ['::before', '::after']) {
2761
+ let ps;
2762
+ try { ps = getComputedStyle(el, which); } catch { continue; }
2763
+ if (!ps || ps.content === 'none' || ps.content === '') continue;
2764
+ const w = parseFloat(ps.width) || 0;
2765
+ const h = parseFloat(ps.height) || 0;
2766
+ if (!(w >= 8 && w <= 80 && h >= 1 && h <= 6)) continue;
2767
+ const bg = parseRgb(ps.backgroundColor) || parseAnyColor(ps.backgroundColor);
2768
+ if (!bg || (bg.a ?? 1) < 0.1) continue;
2769
+ if (Math.max(bg.r, bg.g, bg.b) - Math.min(bg.r, bg.g, bg.b) >= 30) return true;
2770
+ }
2771
+ return false;
2772
+ }
2773
+
1556
2774
  function checkElementHeroEyebrowDOM(el) {
1557
2775
  const tag = el.tagName.toLowerCase();
1558
2776
  if (tag !== 'h1') return [];
@@ -1564,6 +2782,7 @@ function checkElementHeroEyebrowDOM(el) {
1564
2782
  headingTag: tag,
1565
2783
  headingText: el.textContent || '',
1566
2784
  headingFontSize: parseFloat(headStyle.fontSize) || 0,
2785
+ headingInApplicationContext: !!el.closest('[role="tabpanel"], [role="dialog"], [role="application"], dialog'),
1567
2786
  siblingTag: sibling.tagName.toLowerCase(),
1568
2787
  siblingText: sibling.textContent || '',
1569
2788
  siblingTextTransform: sibStyle.textTransform || '',
@@ -1571,6 +2790,7 @@ function checkElementHeroEyebrowDOM(el) {
1571
2790
  siblingLetterSpacing: parseFloat(sibStyle.letterSpacing) || 0,
1572
2791
  siblingFontWeight: sibStyle.fontWeight || '',
1573
2792
  siblingColor: sibStyle.color || '',
2793
+ siblingHasAccentDashPseudo: domAccentDashPseudo(sibling),
1574
2794
  });
1575
2795
  }
1576
2796
 
@@ -1635,8 +2855,10 @@ function resolveVarRefs(raw, customPropMap, depth = 0) {
1635
2855
  // detector's contrast / color checks.
1636
2856
  function oklchToRgb(L, C, H) {
1637
2857
  const hRad = (H * Math.PI) / 180;
1638
- const a = C * Math.cos(hRad);
1639
- const b = C * Math.sin(hRad);
2858
+ return oklabToRgb(L, C * Math.cos(hRad), C * Math.sin(hRad));
2859
+ }
2860
+
2861
+ function oklabToRgb(L, a, b) {
1640
2862
  const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
1641
2863
  const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
1642
2864
  const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
@@ -1656,13 +2878,178 @@ function oklchToRgb(L, C, H) {
1656
2878
  };
1657
2879
  }
1658
2880
 
1659
- // Extended color parser: rgb/rgba/hex/oklch. Returns null on no match.
1660
- // Use this when the input might be any CSS color form; use plain parseRgb
1661
- // when you only expect computed rgb() values from real browsers.
2881
+ function hslToRgb(h, s, l) {
2882
+ h = ((h % 360) + 360) % 360;
2883
+ const c = (1 - Math.abs(2 * l - 1)) * s;
2884
+ const x = c * (1 - Math.abs(((h / 60) % 2) - 1));
2885
+ const m0 = l - c / 2;
2886
+ const [r, g, b] =
2887
+ h < 60 ? [c, x, 0] :
2888
+ h < 120 ? [x, c, 0] :
2889
+ h < 180 ? [0, c, x] :
2890
+ h < 240 ? [0, x, c] :
2891
+ h < 300 ? [x, 0, c] : [c, 0, x];
2892
+ return {
2893
+ r: Math.round((r + m0) * 255),
2894
+ g: Math.round((g + m0) * 255),
2895
+ b: Math.round((b + m0) * 255),
2896
+ a: 1,
2897
+ };
2898
+ }
2899
+
2900
+ function hwbToRgb(h, w, bl) {
2901
+ if (w + bl >= 1) {
2902
+ const g = Math.round((w / (w + bl)) * 255);
2903
+ return { r: g, g, b: g, a: 1 };
2904
+ }
2905
+ const base = hslToRgb(h, 1, 0.5);
2906
+ const mix = (c) => Math.round(((c / 255) * (1 - w - bl) + w) * 255);
2907
+ return { r: mix(base.r), g: mix(base.g), b: mix(base.b), a: 1 };
2908
+ }
2909
+
2910
+ // Common CSS named colors — the handful that actually show up in generated
2911
+ // UIs, not the full 148-name spec list. Includes the achromatic names so a
2912
+ // named gray parses (and correctly reads as no-chroma) instead of being
2913
+ // treated as an unknown color.
2914
+ const CSS_NAMED_COLORS = {
2915
+ black: { r: 0, g: 0, b: 0 },
2916
+ white: { r: 255, g: 255, b: 255 },
2917
+ gray: { r: 128, g: 128, b: 128 },
2918
+ grey: { r: 128, g: 128, b: 128 },
2919
+ silver: { r: 192, g: 192, b: 192 },
2920
+ dimgray: { r: 105, g: 105, b: 105 },
2921
+ darkgray: { r: 169, g: 169, b: 169 },
2922
+ lightgray: { r: 211, g: 211, b: 211 },
2923
+ gainsboro: { r: 220, g: 220, b: 220 },
2924
+ whitesmoke: { r: 245, g: 245, b: 245 },
2925
+ red: { r: 255, g: 0, b: 0 },
2926
+ crimson: { r: 220, g: 20, b: 60 },
2927
+ tomato: { r: 255, g: 99, b: 71 },
2928
+ coral: { r: 255, g: 127, b: 80 },
2929
+ salmon: { r: 250, g: 128, b: 114 },
2930
+ orange: { r: 255, g: 165, b: 0 },
2931
+ gold: { r: 255, g: 215, b: 0 },
2932
+ yellow: { r: 255, g: 255, b: 0 },
2933
+ olive: { r: 128, g: 128, b: 0 },
2934
+ lime: { r: 0, g: 255, b: 0 },
2935
+ green: { r: 0, g: 128, b: 0 },
2936
+ teal: { r: 0, g: 128, b: 128 },
2937
+ turquoise: { r: 64, g: 224, b: 208 },
2938
+ cyan: { r: 0, g: 255, b: 255 },
2939
+ aqua: { r: 0, g: 255, b: 255 },
2940
+ skyblue: { r: 135, g: 206, b: 235 },
2941
+ dodgerblue: { r: 30, g: 144, b: 255 },
2942
+ blue: { r: 0, g: 0, b: 255 },
2943
+ navy: { r: 0, g: 0, b: 128 },
2944
+ indigo: { r: 75, g: 0, b: 130 },
2945
+ rebeccapurple: { r: 102, g: 51, b: 153 },
2946
+ purple: { r: 128, g: 0, b: 128 },
2947
+ violet: { r: 238, g: 130, b: 238 },
2948
+ orchid: { r: 218, g: 112, b: 214 },
2949
+ magenta: { r: 255, g: 0, b: 255 },
2950
+ fuchsia: { r: 255, g: 0, b: 255 },
2951
+ hotpink: { r: 255, g: 105, b: 180 },
2952
+ pink: { r: 255, g: 192, b: 203 },
2953
+ maroon: { r: 128, g: 0, b: 0 },
2954
+ };
2955
+
2956
+ // Split a string on top-level commas (ignoring commas nested in parens).
2957
+ function splitTopLevelCommas(str) {
2958
+ const parts = [];
2959
+ let depth = 0, start = 0;
2960
+ for (let i = 0; i < str.length; i++) {
2961
+ const ch = str[i];
2962
+ if (ch === '(') depth++;
2963
+ else if (ch === ')') depth = Math.max(0, depth - 1);
2964
+ else if (ch === ',' && depth === 0) {
2965
+ parts.push(str.slice(start, i).trim());
2966
+ start = i + 1;
2967
+ }
2968
+ }
2969
+ const tail = str.slice(start).trim();
2970
+ if (tail) parts.push(tail);
2971
+ return parts;
2972
+ }
2973
+
2974
+ // Evaluate a CSS color-mix() expression to {r,g,b,a}. Returns null when
2975
+ // the expression can't be resolved (unresolved var(), unknown colors).
2976
+ //
2977
+ // Mixing is done with premultiplied alpha in sRGB regardless of the
2978
+ // declared interpolation space. That is exact for the dominant generated-UI
2979
+ // pattern — `color-mix(in oklab, <color> N%, transparent)` — where the
2980
+ // result is simply <color> at alpha N% in ANY rectangular space, and a
2981
+ // close-enough approximation for opaque-opaque mixes (the detector only
2982
+ // consumes these values for contrast/chroma thresholds, not for display).
2983
+ function parseColorMix(str) {
2984
+ const m = String(str).trim().match(/^color-mix\(/i);
2985
+ if (!m) return null;
2986
+ // Balanced-paren capture of the arguments.
2987
+ let depth = 0, end = -1;
2988
+ const open = str.indexOf('(');
2989
+ for (let i = open; i < str.length; i++) {
2990
+ if (str[i] === '(') depth++;
2991
+ else if (str[i] === ')') { depth--; if (depth === 0) { end = i; break; } }
2992
+ }
2993
+ if (end < 0) return null;
2994
+ const args = splitTopLevelCommas(str.slice(open + 1, end));
2995
+ if (args.length !== 3 || !/^in\s/i.test(args[0])) return null;
2996
+
2997
+ const parseComponent = (component) => {
2998
+ // Percentage may lead or trail the color per spec.
2999
+ let pct = null;
3000
+ let colorStr = component;
3001
+ const trail = component.match(/\s+([\d.]+)%$/);
3002
+ const lead = component.match(/^([\d.]+)%\s+/);
3003
+ if (trail) { pct = parseFloat(trail[1]); colorStr = component.slice(0, trail.index).trim(); }
3004
+ else if (lead) { pct = parseFloat(lead[1]); colorStr = component.slice(lead[0].length).trim(); }
3005
+ let color;
3006
+ if (/^transparent$/i.test(colorStr)) color = { r: 0, g: 0, b: 0, a: 0 };
3007
+ else color = parseAnyColor(colorStr);
3008
+ if (!color) return null;
3009
+ return { color, pct };
3010
+ };
3011
+
3012
+ const c1 = parseComponent(args[1]);
3013
+ const c2 = parseComponent(args[2]);
3014
+ if (!c1 || !c2) return null;
3015
+ let p1 = c1.pct, p2 = c2.pct;
3016
+ if (p1 == null && p2 == null) { p1 = 50; p2 = 50; }
3017
+ else if (p1 == null) p1 = 100 - p2;
3018
+ else if (p2 == null) p2 = 100 - p1;
3019
+ const sum = p1 + p2;
3020
+ if (sum <= 0) return null;
3021
+ // Per spec: weights normalize to sum; when sum < 100 the result alpha is
3022
+ // additionally scaled by sum/100.
3023
+ const w1 = p1 / sum, w2 = p2 / sum;
3024
+ const alphaScale = sum < 100 ? sum / 100 : 1;
3025
+ const a1 = c1.color.a ?? 1, a2 = c2.color.a ?? 1;
3026
+ const a = (a1 * w1 + a2 * w2) * alphaScale;
3027
+ if (a <= 0) return { r: 0, g: 0, b: 0, a: 0 };
3028
+ const mix = (ch) => Math.round((c1.color[ch] * a1 * w1 + c2.color[ch] * a2 * w2) / (a1 * w1 + a2 * w2));
3029
+ return { r: mix('r'), g: mix('g'), b: mix('b'), a: Math.min(1, a) };
3030
+ }
3031
+
3032
+ // Composite a translucent color over an opaque(ish) base (simple
3033
+ // source-over in sRGB). Returns an opaque {r,g,b,a:1}.
3034
+ function compositeColorOver(top, base) {
3035
+ const a = top.a ?? 1;
3036
+ return {
3037
+ r: Math.round(top.r * a + base.r * (1 - a)),
3038
+ g: Math.round(top.g * a + base.g * (1 - a)),
3039
+ b: Math.round(top.b * a + base.b * (1 - a)),
3040
+ a: 1,
3041
+ };
3042
+ }
3043
+
3044
+ // Extended color parser: rgb/rgba/hex/oklch/oklab/hsl/hwb/color-mix/common
3045
+ // named colors. Returns null on no match. Use this when the input might be
3046
+ // any CSS color form; use plain parseRgb when you only expect computed rgb()
3047
+ // values from real browsers.
1662
3048
  function parseAnyColor(s) {
1663
3049
  if (!s || typeof s !== 'string') return null;
1664
3050
  const str = s.trim();
1665
3051
  if (str === 'transparent' || str === 'currentcolor' || str === 'inherit') return null;
3052
+ if (/^color-mix\(/i.test(str)) return parseColorMix(str);
1666
3053
  let m;
1667
3054
  m = str.match(/rgba?\(\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)(?:\s*[,/]\s*([\d.]+))?\s*\)/);
1668
3055
  if (m) return { r: Math.round(+m[1]), g: Math.round(+m[2]), b: Math.round(+m[3]), a: m[4] !== undefined ? +m[4] : 1 };
@@ -1700,6 +3087,41 @@ function parseAnyColor(s) {
1700
3087
  }
1701
3088
  return rgb;
1702
3089
  }
3090
+ // OKLAB — a/b are signed axes; percentages map 100% → 0.4.
3091
+ m = str.match(/oklab\(\s*([\d.]+)(%?)\s+(-?[\d.]+)(%?)\s+(-?[\d.]+)(%?)(?:\s*\/\s*([\d.]+)(%)?)?\s*\)/i);
3092
+ if (m) {
3093
+ const L = m[2] === '%' ? parseFloat(m[1]) / 100 : parseFloat(m[1]);
3094
+ const a = m[4] === '%' ? parseFloat(m[3]) * 0.004 : parseFloat(m[3]);
3095
+ const b = m[6] === '%' ? parseFloat(m[5]) * 0.004 : parseFloat(m[5]);
3096
+ const rgb = oklabToRgb(L, a, b);
3097
+ if (m[7] !== undefined) {
3098
+ const alpha = parseFloat(m[7]);
3099
+ rgb.a = m[8] === '%' ? alpha / 100 : alpha;
3100
+ }
3101
+ return rgb;
3102
+ }
3103
+ // HSL/HSLA — comma or space syntax, optional deg on hue.
3104
+ m = str.match(/hsla?\(\s*(-?[\d.]+)(?:deg)?\s*[,\s]\s*([\d.]+)%\s*[,\s]\s*([\d.]+)%(?:\s*[,/]\s*([\d.]+)(%)?)?\s*\)/i);
3105
+ if (m) {
3106
+ const rgb = hslToRgb(parseFloat(m[1]), parseFloat(m[2]) / 100, parseFloat(m[3]) / 100);
3107
+ if (m[4] !== undefined) {
3108
+ const alpha = parseFloat(m[4]);
3109
+ rgb.a = m[5] === '%' ? alpha / 100 : alpha;
3110
+ }
3111
+ return rgb;
3112
+ }
3113
+ // HWB — hue whiteness% blackness%.
3114
+ m = str.match(/hwb\(\s*(-?[\d.]+)(?:deg)?\s+([\d.]+)%\s+([\d.]+)%(?:\s*\/\s*([\d.]+)(%)?)?\s*\)/i);
3115
+ if (m) {
3116
+ const rgb = hwbToRgb(parseFloat(m[1]), parseFloat(m[2]) / 100, parseFloat(m[3]) / 100);
3117
+ if (m[4] !== undefined) {
3118
+ const alpha = parseFloat(m[4]);
3119
+ rgb.a = m[5] === '%' ? alpha / 100 : alpha;
3120
+ }
3121
+ return rgb;
3122
+ }
3123
+ const named = CSS_NAMED_COLORS[str.toLowerCase()];
3124
+ if (named) return { ...named, a: 1 };
1703
3125
  return null;
1704
3126
  }
1705
3127
 
@@ -1821,13 +3243,177 @@ function collectRepeatedSectionKickerCandidates(doc, getStyle, resolveLetterSpac
1821
3243
  return candidates;
1822
3244
  }
1823
3245
 
1824
- function checkRepeatedSectionKickersDOM() {
1825
- const candidates = collectRepeatedSectionKickerCandidates(
3246
+ function checkRepeatedSectionKickersDOM() {
3247
+ const candidates = collectRepeatedSectionKickerCandidates(
3248
+ document,
3249
+ (el) => getComputedStyle(el),
3250
+ (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
3251
+ );
3252
+ return checkRepeatedSectionKickers({ candidates });
3253
+ }
3254
+
3255
+ // ── Numbered section labels ─────────────────────────────────────────────────
3256
+ // Sibling of the repeated-kicker rule: instead of a tracked uppercase word,
3257
+ // the section scaffold is a tiny numeric index riding beside each section
3258
+ // heading — bare and zero-padded, or an index joined to a short micro-label
3259
+ // by a separator glyph. The kicker rule deliberately excludes bare 1-2 digit
3260
+ // labels; this rule owns that shape.
3261
+
3262
+ const NUMBERED_LABEL_TAGS = new Set(['span', 'p', 'div', 'small', 'em', 'strong', 'b']);
3263
+
3264
+ // Returns { index, text } when the trimmed text reads as a section index
3265
+ // label, else null. Two accepted shapes: a zero-padded/two-digit bare index,
3266
+ // or a 1-2 digit index followed by a non-word separator and a short label.
3267
+ function parseNumberedLabelText(rawText) {
3268
+ const text = (rawText || '').replace(/\s+/g, ' ').trim();
3269
+ if (!text || text.length > 40) return null;
3270
+ let m = /^(\d{2})$/.exec(text);
3271
+ if (!m) m = /^(\d{1,2})\s*[^\w\s]\s*\S/.exec(text);
3272
+ if (!m) return null;
3273
+ const index = parseInt(m[1], 10);
3274
+ if (!Number.isFinite(index) || index > 40) return null;
3275
+ return { index, text };
3276
+ }
3277
+
3278
+ function isNumberedSectionLabelCandidate(opts) {
3279
+ const {
3280
+ headingTag, headingText, headingFontSize,
3281
+ labelTag, labelIndex, labelText,
3282
+ labelFontSize, labelLetterSpacing, labelFontWeight,
3283
+ labelFontFamily, labelTextTransform, labelColor,
3284
+ } = opts;
3285
+ if (!['h2', 'h3', 'h4'].includes(headingTag)) return false;
3286
+ if (!headingText || headingText.length < 3) return false;
3287
+ if (!labelTag || !NUMBERED_LABEL_TAGS.has(labelTag)) return false;
3288
+ if (labelIndex == null || !labelText) return false;
3289
+ // Tiny rendered size is the tell — a display-scale section number is a
3290
+ // different (deliberate) device and stays legal.
3291
+ if (!(labelFontSize > 0 && labelFontSize <= 13)) return false;
3292
+ // The heading must be visibly larger where we can resolve its size.
3293
+ // clamp()/var() sizes come back unparseable (0) in the static engine —
3294
+ // the remaining gates carry the check there.
3295
+ if (headingFontSize > 0 && headingFontSize < labelFontSize * 1.3) return false;
3296
+ // Deliberate micro-label styling separates the scaffold from incidental
3297
+ // small text: mono face, bold weight, tracking, uppercase, or accent color.
3298
+ const weight = Number(labelFontWeight) || 400;
3299
+ return /mono/i.test(labelFontFamily || '')
3300
+ || weight >= 600
3301
+ || (labelLetterSpacing || 0) >= 0.5
3302
+ || (labelTextTransform || '') === 'uppercase'
3303
+ || isAccentColor(labelColor || '');
3304
+ }
3305
+
3306
+ function collectNumberedSectionLabelCandidates(doc, getStyle, resolveLetterSpacing) {
3307
+ const candidates = [];
3308
+ const seenLabels = new Set();
3309
+ for (const heading of doc.querySelectorAll('h2, h3, h4')) {
3310
+ if (heading.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
3311
+ // The index sits either directly before the heading, or before the
3312
+ // wrapper the heading leads (label | <div><h2>…</h2>…</div>).
3313
+ let label = heading.previousElementSibling;
3314
+ if (!label) {
3315
+ const parent = heading.parentElement;
3316
+ const firstChild = parent?.children?.[0];
3317
+ if (firstChild === heading) label = parent.previousElementSibling;
3318
+ }
3319
+ if (!label || seenLabels.has(label)) continue;
3320
+ if (label.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
3321
+ if (HEADING_TAGS.has(label.tagName.toLowerCase())) continue;
3322
+ if (isRepeatedKickerCardContext(heading, label)) continue;
3323
+
3324
+ const labelText = cleanInlineText(label) || (label.textContent || '').replace(/\s+/g, ' ').trim();
3325
+ const parsed = parseNumberedLabelText(labelText);
3326
+ if (!parsed) continue;
3327
+
3328
+ const headingStyle = getStyle(heading);
3329
+ const labelStyle = getStyle(label);
3330
+ const headingText = (heading.textContent || '').replace(/\s+/g, ' ').trim();
3331
+ const headingFontSize = resolveLetterSpacing(headingStyle.fontSize || '', 16) || parseFloat(headingStyle.fontSize) || 0;
3332
+ const labelFontSize = resolveLetterSpacing(labelStyle.fontSize || '', 16) || parseFloat(labelStyle.fontSize) || 0;
3333
+
3334
+ if (!isNumberedSectionLabelCandidate({
3335
+ headingTag: heading.tagName.toLowerCase(),
3336
+ headingText,
3337
+ headingFontSize,
3338
+ labelTag: label.tagName.toLowerCase(),
3339
+ labelIndex: parsed.index,
3340
+ labelText: parsed.text,
3341
+ labelFontSize,
3342
+ labelLetterSpacing: resolveLetterSpacing(labelStyle.letterSpacing || '', labelFontSize),
3343
+ labelFontWeight: labelStyle.fontWeight || '',
3344
+ labelFontFamily: labelStyle.fontFamily || '',
3345
+ labelTextTransform: labelStyle.textTransform || '',
3346
+ labelColor: labelStyle.color || '',
3347
+ })) {
3348
+ continue;
3349
+ }
3350
+
3351
+ seenLabels.add(label);
3352
+ candidates.push({
3353
+ index: parsed.index,
3354
+ labelText: parsed.text.slice(0, 24),
3355
+ headingTag: heading.tagName.toLowerCase(),
3356
+ headingText: headingText.replace(/^"|"$/g, '').slice(0, 60),
3357
+ });
3358
+ }
3359
+ return candidates;
3360
+ }
3361
+
3362
+ function checkNumberedSectionLabels(opts) {
3363
+ const { candidates, minCount = 2 } = opts;
3364
+ if (!Array.isArray(candidates) || candidates.length < minCount) return [];
3365
+ // A repeated identical number is some other device; the scaffold counts up.
3366
+ const distinctIndices = new Set(candidates.map(c => c.index));
3367
+ if (distinctIndices.size < 2) return [];
3368
+ return candidates.map(candidate => ({
3369
+ id: 'numbered-section-labels',
3370
+ snippet: `tiny numbered label "${candidate.labelText}" beside ${candidate.headingTag} "${candidate.headingText}" (${candidates.length} on page)`,
3371
+ }));
3372
+ }
3373
+
3374
+ function checkNumberedSectionLabelsFromDoc(doc, win) {
3375
+ const candidates = collectNumberedSectionLabelCandidates(
3376
+ doc,
3377
+ (el) => win.getComputedStyle(el),
3378
+ (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
3379
+ );
3380
+ return checkNumberedSectionLabels({ candidates });
3381
+ }
3382
+
3383
+ function checkNumberedSectionLabelsDOM() {
3384
+ const candidates = collectNumberedSectionLabelCandidates(
1826
3385
  document,
1827
3386
  (el) => getComputedStyle(el),
1828
3387
  (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
1829
3388
  );
1830
- return checkRepeatedSectionKickers({ candidates });
3389
+ return checkNumberedSectionLabels({ candidates });
3390
+ }
3391
+
3392
+ // Em-dash overuse (ADVISORY) — pure logic shared by the browser DOM check.
3393
+ // Mirrors the regex/static-HTML analyzer in engines/regex/detect-text.mjs:
3394
+ // two gates (absolute floor + density) so a long article using a few dashes is
3395
+ // left alone while a short, dash-per-clause page is flagged. Operates on
3396
+ // already-rendered text, so no HTML-entity decoding is needed (the browser has
3397
+ // resolved `&mdash;` to the literal glyph). Exported for jsdom unit tests.
3398
+ function checkEmDashOveruse(text) {
3399
+ const body = typeof text === 'string' ? text.replace(/\s+/g, ' ') : '';
3400
+ let count = 0;
3401
+ const re = /[—]|--(?=\S)/g;
3402
+ while (re.exec(body) !== null) count++;
3403
+ if (count < EM_DASH_FLOOR) return [];
3404
+ if (body.length > count * EM_DASH_CHARS_PER_DASH) return [];
3405
+ return [{ id: 'em-dash-overuse', snippet: `${count} em-dashes in body text` }];
3406
+ }
3407
+
3408
+ function checkEmDashOveruseDOM() {
3409
+ const body = document.body;
3410
+ if (!body) return [];
3411
+ // innerText reflects rendered, visible text; fall back to textContent for
3412
+ // engines (jsdom) that don't compute innerText.
3413
+ const text = typeof body.innerText === 'string' && body.innerText
3414
+ ? body.innerText
3415
+ : (body.textContent || '');
3416
+ return checkEmDashOveruse(text);
1831
3417
  }
1832
3418
 
1833
3419
  function checkElementMotionDOM(el) {
@@ -1846,7 +3432,14 @@ function checkElementMotionDOM(el) {
1846
3432
  function checkElementGlowDOM(el) {
1847
3433
  const tag = el.tagName.toLowerCase();
1848
3434
  const style = getComputedStyle(el);
1849
- if (!style.boxShadow || style.boxShadow === 'none') return [];
3435
+ const boxShadow = style.boxShadow && style.boxShadow !== 'none' ? style.boxShadow : '';
3436
+ // text-shadow inherits: only check the element that introduces it, so one
3437
+ // declaration doesn't produce a finding on every descendant.
3438
+ let textShadow = style.textShadow && style.textShadow !== 'none' ? style.textShadow : '';
3439
+ if (textShadow && el.parentElement && getComputedStyle(el.parentElement).textShadow === textShadow) {
3440
+ textShadow = '';
3441
+ }
3442
+ if (!boxShadow && !textShadow) return [];
1850
3443
  // Use parent's background — glow radiates outward, so the surrounding context matters
1851
3444
  // If resolveBackground returns null (gradient), try to infer from the gradient colors
1852
3445
  let parentBg = el.parentElement ? resolveBackground(el.parentElement) : resolveBackground(el);
@@ -1869,7 +3462,7 @@ function checkElementGlowDOM(el) {
1869
3462
  cur = cur.parentElement;
1870
3463
  }
1871
3464
  }
1872
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg: parentBg });
3465
+ return checkGlow({ tag, boxShadow, textShadow, effectiveBg: parentBg });
1873
3466
  }
1874
3467
 
1875
3468
  function checkElementAIPaletteDOM(el) {
@@ -2050,6 +3643,27 @@ function textDescendantsFlushSides(el, rect) {
2050
3643
  return flush;
2051
3644
  }
2052
3645
 
3646
+ // Screen-reader-only ("visually hidden") text is exempt from the tiny-text
3647
+ // floors: it is never rendered, so its size is irrelevant. Detect the two
3648
+ // standard idioms — a known sr-only class on the element or an ancestor, and
3649
+ // the clip / 1px-box pattern. Works in both jsdom (declared styles) and the
3650
+ // browser (computed styles).
3651
+ const SR_ONLY_SELECTOR = '.sr-only, .visually-hidden, .visuallyhidden, .screen-reader, .screen-reader-only, .screenreader, .a11y-hidden, .hidden-visually, [class*="sr-only" i], [class*="visually-hidden" i], [class*="visuallyhidden" i], [class*="screen-reader" i], [class*="screenreader" i]';
3652
+ function isVisuallyHidden(el, style) {
3653
+ if ((el.matches && el.matches(SR_ONLY_SELECTOR)) || (el.closest && el.closest(SR_ONLY_SELECTOR))) return true;
3654
+ const pos = style.position || '';
3655
+ if (pos === 'absolute' || pos === 'fixed') {
3656
+ const clip = style.clip || '';
3657
+ const clipPath = style.clipPath || style.webkitClipPath || style['clip-path'] || '';
3658
+ if (/rect\(\s*0/.test(clip) || /inset\(\s*(?:50%|99|100%)/.test(clipPath)) return true;
3659
+ const w = parseFloat(style.width);
3660
+ const h = parseFloat(style.height);
3661
+ const overflow = style.overflow || '';
3662
+ if ((w === 1 || h === 1) && (overflow === 'hidden' || overflow === 'clip')) return true;
3663
+ }
3664
+ return false;
3665
+ }
3666
+
2053
3667
  // Pure quality checks. Most run on computed CSS and DOM-only inputs (work in
2054
3668
  // jsdom and the browser). Two checks (line-length, cramped-padding) gate on
2055
3669
  // element rect dimensions, which jsdom can't compute — pass `rect: null` from
@@ -2334,6 +3948,60 @@ function checkQuality(opts) {
2334
3948
  }
2335
3949
  }
2336
3950
 
3951
+ // --- Undersized functional / UI text ---
3952
+ // Complements `tiny-text` above, which owns long body copy and deliberately
3953
+ // EXEMPTS the UI furniture layer (nav, footer, links, buttons, labels,
3954
+ // uppercase micro-labels). This rule targets exactly that blind spot: the
3955
+ // interactive and short content-bearing text — nav items, buttons, labels,
3956
+ // table cells, meta rows, timecodes — shipped below an 11px floor.
3957
+ //
3958
+ // The live failure it closes: a build shipped its entire furniture layer at
3959
+ // 8px, and the design hook waved it through because 8px had been added to
3960
+ // the DESIGN.md size ramp. Being on the ramp is a token argument, not a
3961
+ // legibility one, so this rule ignores the design system entirely — a value
3962
+ // on the ramp is still flagged.
3963
+ //
3964
+ // Floors: 11px for anything functional. The floor holds inside a footer;
3965
+ // only NON-interactive legal smallprint gets the softer 10px floor. Exempts
3966
+ // sup/sub, visually-hidden (sr-only) text, and code/terminal contexts.
3967
+ // Uppercase letterspaced micro-labels are still functional — not exempt.
3968
+ {
3969
+ const directText = [...el.childNodes]
3970
+ .filter(n => n.nodeType === 3)
3971
+ .map(n => n.textContent || '')
3972
+ .join('')
3973
+ .replace(/\s+/g, ' ')
3974
+ .trim();
3975
+ const dtLen = directText.length;
3976
+ const UI_SKIP_TAGS = new Set(['sub', 'sup', 'script', 'style', 'title', 'option']);
3977
+ const notRendered = style.display === 'none' || style.visibility === 'hidden' || style.visibility === 'collapse';
3978
+ // jsdom resolves the parent chain in resolveFontSizePx, so em/rem/%-sized
3979
+ // text that computes at or above the floor never reaches here. The browser
3980
+ // adapter additionally catches values only resolvable with real layout
3981
+ // (e.g. viewport-relative units, cascade winners set in linked sheets).
3982
+ if (fontSize > 0 && fontSize < 11 && dtLen >= 2 && !UI_SKIP_TAGS.has(tag) && !notRendered) {
3983
+ const EXEMPT_CONTEXT = 'pre, code, kbd, samp, var, svg, [aria-hidden="true"], [class*="terminal" i], [class*="console" i], [class*="code" i], [class*="mock" i], [class*="editor" i], [class*="syntax" i], [class*="diff" i]';
3984
+ const isExemptContext = (el.matches && el.matches(EXEMPT_CONTEXT)) || (el.closest && el.closest(EXEMPT_CONTEXT));
3985
+ if (!isExemptContext && !isVisuallyHidden(el, style)) {
3986
+ const INTERACTIVE = 'a[href], button, summary, label, select, textarea, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="menuitemcheckbox"], [role="menuitemradio"], [role="option"], [role="checkbox"], [role="radio"], [role="switch"], [role="treeitem"], [tabindex]';
3987
+ const FURNITURE = 'nav, [role="navigation"], td, th, [role="gridcell"], [role="cell"], caption, figcaption, dt, dd, footer, [class*="meta" i], [class*="label" i], [class*="badge" i], [class*="chip" i], [class*="pill" i], [class*="tag" i], [class*="kicker" i], [class*="eyebrow" i], [class*="breadcrumb" i], [class*="timestamp" i], [class*="category" i], [class*="caption" i], [class*="nav" i]';
3988
+ const SMALLPRINT = 'small, footer, [class*="legal" i], [class*="copyright" i], [class*="fineprint" i], [class*="fine-print" i], [class*="smallprint" i], [class*="small-print" i], [class*="disclaimer" i], [class*="disclosure" i], [class*="footnote" i]';
3989
+ const isInteractive = (el.matches && el.matches(INTERACTIVE)) || (el.closest && el.closest(INTERACTIVE));
3990
+ const isFurniture = (el.matches && el.matches(FURNITURE)) || (el.closest && el.closest(FURNITURE));
3991
+ const isSmallprint = (el.matches && el.matches(SMALLPRINT)) || (el.closest && el.closest(SMALLPRINT));
3992
+ const floor = (!isInteractive && isSmallprint) ? 10 : 11;
3993
+ // Fire on functional text only: interactive, structural furniture, or
3994
+ // any short (<=20-char) run — the label / meta / timecode shape. Long
3995
+ // non-furniture body copy stays with `tiny-text`, so the two rules
3996
+ // never double-flag the same element.
3997
+ if (fontSize < floor && (isInteractive || isFurniture || dtLen <= 20)) {
3998
+ const excerpt = directText.slice(0, 40);
3999
+ findings.push({ id: 'undersized-ui-text', snippet: `${fontSize}px functional text "${excerpt}" (below ${floor}px floor)` });
4000
+ }
4001
+ }
4002
+ }
4003
+ }
4004
+
2337
4005
  // --- All-caps body text ---
2338
4006
  if (hasDirectText && textLen > 30 && style.textTransform === 'uppercase') {
2339
4007
  if (!['h1','h2','h3','h4','h5','h6'].includes(tag)) {
@@ -2426,7 +4094,7 @@ function checkElementQuality(el, style, tag, window) {
2426
4094
  return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null, win: window });
2427
4095
  }
2428
4096
 
2429
- function checkElementBorders(tag, style, overrides, resolvedRadius) {
4097
+ function checkElementBorders(tag, style, overrides, resolvedRadius, el = null) {
2430
4098
  const sides = ['Top', 'Right', 'Bottom', 'Left'];
2431
4099
  const widths = {}, colors = {};
2432
4100
  for (const s of sides) {
@@ -2453,7 +4121,12 @@ function checkElementBorders(tag, style, overrides, resolvedRadius) {
2453
4121
  const radius = resolvedRadius != null
2454
4122
  ? resolvedRadius
2455
4123
  : (parseFloat(style.borderRadius) || 0);
2456
- return checkBorders(tag, widths, colors, radius);
4124
+ const ownBg = parseAnyColor(style.backgroundColor);
4125
+ return checkBorders(tag, widths, colors, radius, {
4126
+ tabContext: isTabContextElement(el),
4127
+ statusContext: isStatusContextElement(el),
4128
+ badgeLike: !!(ownBg && (ownBg.a ?? 1) > 0.1),
4129
+ });
2457
4130
  }
2458
4131
 
2459
4132
  function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInheritRule) {
@@ -2494,12 +4167,32 @@ function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInhe
2494
4167
  }
2495
4168
  }
2496
4169
 
4170
+ // Own background: resolve var()/oklch() tokens through the custom-property
4171
+ // map first (mirrors the textColor path above). Without this a chip whose
4172
+ // background is `var(--sev)` reads as no-own-bg in the static engine and
4173
+ // the styled-control contrast exception never engages.
4174
+ let ownBg = (customPropMap ? parseColorResolved(style.backgroundColor, customPropMap) : null)
4175
+ || readOwnBackgroundColor(el, style);
4176
+
4177
+ // Full-cover surface pseudo (static): the cascade pass marks elements
4178
+ // whose ::before/::after paints an opaque covering surface. When the
4179
+ // element itself has no usable own background, that pseudo is the real
4180
+ // surface for contrast purposes.
4181
+ let finalEffectiveBg = effectiveBg;
4182
+ if ((!ownBg || (ownBg.a ?? 1) <= 0.5) && typeof window.getPseudoSurface === 'function') {
4183
+ const pseudoSurface = window.getPseudoSurface(el);
4184
+ if (pseudoSurface) {
4185
+ ownBg = pseudoSurface;
4186
+ finalEffectiveBg = pseudoSurface;
4187
+ }
4188
+ }
4189
+
2497
4190
  return checkColors({
2498
4191
  tag,
2499
4192
  textColor,
2500
- bgColor: readOwnBackgroundColor(el, style),
2501
- effectiveBg,
2502
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el, window),
4193
+ bgColor: ownBg,
4194
+ effectiveBg: finalEffectiveBg,
4195
+ effectiveBgStops: finalEffectiveBg ? null : resolveGradientStops(el, window),
2503
4196
  fontSize: parseFloat(style.fontSize) || 16,
2504
4197
  fontWeight: parseInt(style.fontWeight) || 400,
2505
4198
  hasDirectText,
@@ -2510,6 +4203,50 @@ function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInhe
2510
4203
  });
2511
4204
  }
2512
4205
 
4206
+ // Static-engine adapter for hover-state contrast. Relies on the static
4207
+ // cascade's hover pass (css-cascade.mjs) exposing a per-element hover style
4208
+ // via window.getHoverStyle — present only when a :hover rule changed the
4209
+ // element's color or background-color relative to its resting state.
4210
+ function checkElementHoverContrast(el, style, tag, window) {
4211
+ if (typeof window.getHoverStyle !== 'function') return [];
4212
+ const hover = window.getHoverStyle(el);
4213
+ if (!hover) return [];
4214
+
4215
+ const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
4216
+ if (directText.trim().length === 0) return [];
4217
+
4218
+ const textColor = parseAnyColor(hover.color);
4219
+ if (!textColor || (textColor.a != null && textColor.a < 1)) return [];
4220
+
4221
+ const restingOwnBg = parseAnyColor(style.backgroundColor);
4222
+ const hoverOwnBg = parseAnyColor(hover.backgroundColor);
4223
+ const ownBg = hoverOwnBg || restingOwnBg;
4224
+
4225
+ // Effective hover background: the element's own hover bg composited over
4226
+ // whatever sits underneath. Bail when the surface can't be resolved to a
4227
+ // solid color — gradient ancestors are handled (as at rest) by the
4228
+ // resting-state check, not duplicated here.
4229
+ let bg = null;
4230
+ if (ownBg && ownBg.a >= 0.99) {
4231
+ bg = ownBg;
4232
+ } else {
4233
+ const under = resolveBackground(el.parentElement || el, window, null);
4234
+ if (!under) return [];
4235
+ bg = ownBg && ownBg.a > 0.1 ? compositeColorOver(ownBg, under) : under;
4236
+ }
4237
+
4238
+ return checkHoverContrast({
4239
+ tag,
4240
+ textColor,
4241
+ bg,
4242
+ ownBgAlpha: ownBg ? ownBg.a ?? 1 : null,
4243
+ fontSize: parseFloat(style.fontSize) || 16,
4244
+ fontWeight: parseInt(style.fontWeight) || 400,
4245
+ hasDirectText: true,
4246
+ isEmojiOnly: isEmojiOnlyText(directText),
4247
+ });
4248
+ }
4249
+
2513
4250
  function checkElementIconTile(el, tag, window) {
2514
4251
  if (!HEADING_TAGS.has(tag)) return [];
2515
4252
  const sibling = el.previousElementSibling;
@@ -2578,7 +4315,8 @@ function checkElementHeroEyebrow(el, style, tag, window, customPropMap) {
2578
4315
  return checkHeroEyebrow({
2579
4316
  headingTag: tag,
2580
4317
  headingText: el.textContent || '',
2581
- headingFontSize: parseFloat(headingFontSizeRaw) || 0,
4318
+ headingFontSize: resolveHeroHeadingSizePx(headingFontSizeRaw),
4319
+ headingInApplicationContext: !!el.closest?.('[role="tabpanel"], [role="dialog"], [role="application"], dialog'),
2582
4320
  siblingTag: sibling.tagName.toLowerCase(),
2583
4321
  siblingText: sibling.textContent || '',
2584
4322
  siblingTextTransform: sibStyle.textTransform || '',
@@ -2586,6 +4324,11 @@ function checkElementHeroEyebrow(el, style, tag, window, customPropMap) {
2586
4324
  siblingLetterSpacing: resolveLengthPx(letterSpacingRaw, siblingFontSize) || 0,
2587
4325
  siblingFontWeight: fontWeightRaw || '',
2588
4326
  siblingColor: colorRaw || '',
4327
+ // Static cascade marks elements matched by a ::before/::after rule
4328
+ // whose geometry is a short chromatic dash (css-cascade.mjs).
4329
+ siblingHasAccentDashPseudo: typeof window.hasAccentDashPseudo === 'function'
4330
+ ? window.hasAccentDashPseudo(sibling)
4331
+ : false,
2589
4332
  });
2590
4333
  }
2591
4334
 
@@ -2609,8 +4352,10 @@ function checkElementMotion(tag, style) {
2609
4352
  }
2610
4353
 
2611
4354
  function checkElementGlow(tag, style, effectiveBg) {
2612
- if (!style.boxShadow || style.boxShadow === 'none') return [];
2613
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg });
4355
+ const boxShadow = style.boxShadow && style.boxShadow !== 'none' ? style.boxShadow : '';
4356
+ const textShadow = style.textShadow && style.textShadow !== 'none' ? style.textShadow : '';
4357
+ if (!boxShadow && !textShadow) return [];
4358
+ return checkGlow({ tag, boxShadow, textShadow, effectiveBg });
2614
4359
  }
2615
4360
 
2616
4361
  // ─── Section 6: Page-Level Checks ───────────────────────────────────────────
@@ -2720,6 +4465,157 @@ function checkLayout() {
2720
4465
  return findings;
2721
4466
  }
2722
4467
 
4468
+ // Heading rhythm (browser-only): a heading binds to the content it
4469
+ // introduces, so its rendered space above must exceed its space below.
4470
+ // Margins alone can't be trusted (collapsing, flex rows, section padding),
4471
+ // so this measures actual getBoundingClientRect gaps between the heading
4472
+ // and the nearest content genuinely above / below it. Fires only when two
4473
+ // or more headings violate the principle — a single occurrence is noise.
4474
+ function checkHeadingRhythmDOM() {
4475
+ const MIN_VIOLATIONS = 2;
4476
+ const CARD_EXEMPT_HEIGHT = 200;
4477
+ const MAX_BELOW_PX = 160; // beyond this the heading isn't binding to nearby content at all
4478
+ const MIN_DEFICIT_PX = 12;
4479
+
4480
+ function isVisibleFlow(el) {
4481
+ const style = getComputedStyle(el);
4482
+ if (style.display === 'none' || style.visibility === 'hidden') return false;
4483
+ if (parseFloat(style.opacity || '1') <= 0.05) return false;
4484
+ if (style.position === 'absolute' || style.position === 'fixed' || style.position === 'sticky') return false;
4485
+ const rect = el.getBoundingClientRect();
4486
+ return rect.width >= 1 && rect.height >= 1;
4487
+ }
4488
+
4489
+ // Edges only count when they share the heading's column — grid layouts
4490
+ // put content beside a heading, and a far-away element in another column
4491
+ // says nothing about the heading's vertical rhythm.
4492
+ function overlapsX(sr, rect) {
4493
+ return Math.min(sr.right, rect.right) - Math.max(sr.left, rect.left) >= 8;
4494
+ }
4495
+
4496
+ // Does this container draw its own top boundary (background, top border,
4497
+ // shadow)? Crossing out of such a container means the container edge is
4498
+ // the separator above the heading, not raw whitespace — exempt.
4499
+ function hasOwnTopBoundary(el) {
4500
+ const style = getComputedStyle(el);
4501
+ const bg = parseAnyColor(style.backgroundColor || '');
4502
+ if (bg && (bg.a ?? 1) > 0.05) return true;
4503
+ if ((parseFloat(style.borderTopWidth) || 0) > 0) return true;
4504
+ if (style.boxShadow && style.boxShadow !== 'none') return true;
4505
+ return false;
4506
+ }
4507
+
4508
+ // Eyebrows, kickers, and index labels sitting directly on top of a
4509
+ // heading belong to the heading's own cluster — space above is measured
4510
+ // from the top of the cluster, not from the label to the heading.
4511
+ function clusterTop(h, rect) {
4512
+ const headingFontSize = parseFloat(getComputedStyle(h).fontSize) || 16;
4513
+ let topEl = h;
4514
+ let top = rect.top;
4515
+ for (let i = 0; i < 3; i++) {
4516
+ const sib = topEl.previousElementSibling;
4517
+ if (!sib || !isVisibleFlow(sib)) break;
4518
+ const sr = sib.getBoundingClientRect();
4519
+ if (!overlapsX(sr, rect)) break;
4520
+ const gap = top - sr.bottom;
4521
+ if (gap < 0 || gap >= 28 || sr.height > 60) break;
4522
+ const text = (sib.textContent || '').trim();
4523
+ const sibFontSize = parseFloat(getComputedStyle(sib).fontSize) || 16;
4524
+ const labelLike = sibFontSize < headingFontSize * 0.75 || text.length <= 40;
4525
+ if (!labelLike || text.length > 80) break;
4526
+ topEl = sib;
4527
+ top = sr.top;
4528
+ }
4529
+ return { topEl, top };
4530
+ }
4531
+
4532
+ // Nearest content edge strictly above the heading cluster. Walks
4533
+ // previous siblings, then out through ancestors. Skips elements that
4534
+ // vertically overlap (flex-row companions, sticky rails) or sit in
4535
+ // another column. Returns null when nothing qualifies — first content
4536
+ // on the page, or the top of a visually bounded container.
4537
+ function edgeAbove(startEl, top, rect) {
4538
+ let node = startEl;
4539
+ while (node && node !== document.body) {
4540
+ let sib = node.previousElementSibling;
4541
+ while (sib) {
4542
+ if (isVisibleFlow(sib)) {
4543
+ const sr = sib.getBoundingClientRect();
4544
+ if (sr.bottom <= top + 2 && overlapsX(sr, rect)) return sr.bottom;
4545
+ }
4546
+ sib = sib.previousElementSibling;
4547
+ }
4548
+ const parent = node.parentElement;
4549
+ if (!parent || parent === document.body) return null;
4550
+ // Leaving a container upward: if it draws its own top edge, that
4551
+ // edge separates the heading from whatever sits above.
4552
+ if (hasOwnTopBoundary(parent)) return null;
4553
+ node = parent;
4554
+ }
4555
+ return null;
4556
+ }
4557
+
4558
+ // Nearest content edge strictly below the heading — the block the
4559
+ // heading introduces. Crosses wrappers freely (headings often share a
4560
+ // row wrapper with an eyebrow or index label).
4561
+ function edgeBelow(h, rect) {
4562
+ let node = h;
4563
+ while (node && node !== document.body) {
4564
+ let sib = node.nextElementSibling;
4565
+ while (sib) {
4566
+ if (isVisibleFlow(sib)) {
4567
+ const sr = sib.getBoundingClientRect();
4568
+ if (sr.top >= rect.bottom - 2 && overlapsX(sr, rect)) return sr.top;
4569
+ }
4570
+ sib = sib.nextElementSibling;
4571
+ }
4572
+ node = node.parentElement;
4573
+ }
4574
+ return null;
4575
+ }
4576
+
4577
+ function insideSmallCard(h) {
4578
+ let cur = h.parentElement;
4579
+ while (cur && cur !== document.body) {
4580
+ if (isCardLikeDOM(cur)) {
4581
+ const cr = cur.getBoundingClientRect();
4582
+ if (cr.height < CARD_EXEMPT_HEIGHT) return true;
4583
+ }
4584
+ cur = cur.parentElement;
4585
+ }
4586
+ return false;
4587
+ }
4588
+
4589
+ const candidates = [];
4590
+ for (const h of document.querySelectorAll('h2, h3, h4')) {
4591
+ if (!isVisibleFlow(h)) continue;
4592
+ const text = (h.textContent || '').trim().replace(/\s+/g, ' ');
4593
+ if (text.length < 3) continue;
4594
+ const rect = h.getBoundingClientRect();
4595
+ const belowTop = edgeBelow(h, rect);
4596
+ if (belowTop == null) continue; // heading introduces nothing measurable
4597
+ const { topEl, top } = clusterTop(h, rect);
4598
+ const aboveBottom = edgeAbove(topEl, top, rect);
4599
+ if (aboveBottom == null) continue; // first content, or bounded container
4600
+ if (insideSmallCard(h)) continue;
4601
+ const above = Math.max(0, top - aboveBottom);
4602
+ const below = Math.max(0, belowTop - rect.bottom);
4603
+ if (below < 6 || below > MAX_BELOW_PX) continue;
4604
+ // Violation: the space above clearly fails to exceed the space below.
4605
+ // Near-equal gaps are ambiguous rather than inverted, so they pass.
4606
+ if (above < below * 0.75 && below - above >= MIN_DEFICIT_PX) {
4607
+ candidates.push({ el: h, tag: h.tagName.toLowerCase(), text: text.slice(0, 60), above, below });
4608
+ }
4609
+ }
4610
+
4611
+ if (candidates.length < MIN_VIOLATIONS) return [];
4612
+ return candidates.map(c => ({
4613
+ type: 'heading-rhythm',
4614
+ detail: `${c.tag} "${c.text}" has ${Math.round(c.above)}px above vs ${Math.round(c.below)}px below — it reads as bound to the block above (${candidates.length} headings on page)`,
4615
+ el: c.el,
4616
+ }));
4617
+ }
4618
+
2723
4619
  // Node page-level checks — take document/window as parameters
2724
4620
 
2725
4621
  function checkPageTypography(doc, win) {
@@ -2862,6 +4758,135 @@ function checkPageLayout(doc, win) {
2862
4758
  return findings;
2863
4759
  }
2864
4760
 
4761
+ // ── Repeated text inside one container ──────────────────────────────────────
4762
+ // The same literal string rendered 3+ times in structurally different spots
4763
+ // inside one bordered/elevated container — typically a status word wired
4764
+ // into every slot of a card template. Legitimate repetition is structural:
4765
+ // table columns, calendar grids, nav/menu lists, and templated sibling rows
4766
+ // all repeat text in *parallel* positions, so occurrences whose element
4767
+ // paths inside the container are identical (or live in dedicated repetition
4768
+ // structures) never count. Only 3+ occurrences at 3+ distinct structural
4769
+ // positions flag.
4770
+
4771
+ const REPEATED_TEXT_SKIP_SELECTOR = [
4772
+ 'table',
4773
+ 'select',
4774
+ 'datalist',
4775
+ 'nav',
4776
+ 'menu',
4777
+ '[role="navigation"]',
4778
+ '[role="menu"]',
4779
+ '[role="menubar"]',
4780
+ '[role="listbox"]',
4781
+ '[role="grid"]',
4782
+ '[role="tablist"]',
4783
+ '[role="radiogroup"]',
4784
+ '[aria-hidden="true"]',
4785
+ ].join(',');
4786
+
4787
+ const REPEATED_TEXT_CONTAINER_TAGS = new Set([
4788
+ 'div', 'section', 'article', 'aside', 'main', 'figure', 'form', 'fieldset', 'details', 'li',
4789
+ ]);
4790
+
4791
+ // A container worth attributing text to: visibly bounded (border on most
4792
+ // sides or an elevation shadow) and surface-like (radius or own background).
4793
+ function isRepeatedTextContainer(style) {
4794
+ if (!style) return false;
4795
+ const hasShadow = !!(style.boxShadow && style.boxShadow !== 'none' && style.boxShadow !== '');
4796
+ const borderSides = ['Top', 'Right', 'Bottom', 'Left']
4797
+ .filter(side => (parseFloat(style[`border${side}Width`]) || 0) >= 1).length;
4798
+ const hasBorder = borderSides >= 3;
4799
+ const hasRadius = (parseFloat(style.borderRadius) || 0) > 0;
4800
+ const bg = parseRgb(style.backgroundColor) || parseAnyColor(style.backgroundColor);
4801
+ const hasBg = !!(bg && (bg.a ?? 1) > 0.1);
4802
+ return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
4803
+ }
4804
+
4805
+ function collectRepeatedContainerTextFindings(doc, getStyle, opts = {}) {
4806
+ const isVisible = opts.isVisible || (() => true);
4807
+ const findings = [];
4808
+
4809
+ const containers = [];
4810
+ const containerSet = new Set();
4811
+ for (const el of doc.querySelectorAll('*')) {
4812
+ if (!REPEATED_TEXT_CONTAINER_TAGS.has(el.tagName.toLowerCase())) continue;
4813
+ if (el.closest?.(REPEATED_TEXT_SKIP_SELECTOR)) continue;
4814
+ if (!isRepeatedTextContainer(getStyle(el))) continue;
4815
+ containers.push(el);
4816
+ containerSet.add(el);
4817
+ }
4818
+
4819
+ for (const container of containers) {
4820
+ if (!isVisible(container)) continue;
4821
+ const descendants = container.querySelectorAll('*');
4822
+ // Page-scale wrappers that merely happen to carry a background are not
4823
+ // the "one card" this rule reasons about.
4824
+ if (descendants.length > 250) continue;
4825
+
4826
+ const groups = new Map();
4827
+ for (const d of descendants) {
4828
+ // Attribute text to the innermost container only.
4829
+ let anc = d.parentElement;
4830
+ let ownedByInner = false;
4831
+ while (anc && anc !== container) {
4832
+ if (containerSet.has(anc)) { ownedByInner = true; break; }
4833
+ anc = anc.parentElement;
4834
+ }
4835
+ if (ownedByInner) continue;
4836
+ if (d.closest?.(REPEATED_TEXT_SKIP_SELECTOR)) continue;
4837
+ // Icon-font glyph names read as text but render as symbols.
4838
+ if (/icon|material-symbols|(?:^|\s)fa[srlbd]?(?:\s|-|$)/i.test(String(d.getAttribute?.('class') || ''))) continue;
4839
+ if (!isVisible(d)) continue;
4840
+
4841
+ const direct = [...d.childNodes]
4842
+ .filter(n => n.nodeType === 3)
4843
+ .map(n => n.textContent)
4844
+ .join(' ')
4845
+ .replace(/\s+/g, ' ')
4846
+ .trim();
4847
+ if (direct.length < 4 || direct.length > 48) continue;
4848
+ if (!/[a-zA-Z]/.test(direct)) continue;
4849
+
4850
+ // Structural signature: the element path from the occurrence up to
4851
+ // the container. Parallel/templated repetition shares one signature.
4852
+ const sig = [];
4853
+ for (let cur = d; cur && cur !== container; cur = cur.parentElement) {
4854
+ const cls = String(cur.getAttribute?.('class') || '')
4855
+ .trim().split(/\s+/).filter(Boolean).sort().join('.');
4856
+ sig.push(cur.tagName.toLowerCase() + (cls ? `.${cls}` : ''));
4857
+ }
4858
+ if (!groups.has(direct)) groups.set(direct, []);
4859
+ groups.get(direct).push(sig.join('>'));
4860
+ }
4861
+
4862
+ for (const [text, sigs] of groups) {
4863
+ if (sigs.length < 3) continue;
4864
+ if (new Set(sigs).size < 3) continue;
4865
+ findings.push({
4866
+ id: 'repeated-container-text',
4867
+ snippet: `"${text.slice(0, 40)}" rendered ${sigs.length}× in distinct spots inside ${classSelector(container)}`,
4868
+ });
4869
+ }
4870
+ }
4871
+ return findings;
4872
+ }
4873
+
4874
+ function checkRepeatedContainerTextFromDoc(doc, win) {
4875
+ return collectRepeatedContainerTextFindings(
4876
+ doc,
4877
+ (el) => win.getComputedStyle(el),
4878
+ { isVisible: (el) => String(win.getComputedStyle(el).display || '') !== 'none' },
4879
+ );
4880
+ }
4881
+
4882
+ function checkRepeatedContainerTextDOM() {
4883
+ return collectRepeatedContainerTextFindings(
4884
+ document,
4885
+ (el) => getComputedStyle(el),
4886
+ { isVisible: isRenderedForBrowserRule },
4887
+ );
4888
+ }
4889
+
2865
4890
  // ─── Cream / beige palette (the default "tasteful" AI surface) ────────────────
2866
4891
  // A warm, lightly-tinted off-white page background — light, with R≥G≥B and a
2867
4892
  // small warm tint (not white, not a strong color). The current reflex surface.
@@ -2975,7 +5000,7 @@ function checkElementOversizedH1DOM(el) {
2975
5000
  return checkOversizedH1({ tag, fontSize, headingText, rect, viewportWidth, viewportHeight });
2976
5001
  }
2977
5002
 
2978
- // ─── GPT tell: hairline border + wide diffuse shadow (gated --gpt) ────────────
5003
+ // ─── Generated-UI tell: hairline border + wide diffuse shadow ────────────────
2979
5004
  const CSS_COLOR_TOKEN_RE = /(?:rgba?|hsla?|oklch|oklab|lab|lch|color)\([^)]*\)|#[0-9a-fA-F]{3,8}\b|\b(?:black|white|transparent|currentcolor)\b/gi;
2980
5005
 
2981
5006
  function shadowLayerAlpha(layer) {
@@ -3300,9 +5325,645 @@ function checkElementTextOverflowDOM(el) {
3300
5325
  if (el.clientWidth > 0 && delta >= 16) {
3301
5326
  return [{ id: 'text-overflow', snippet: `${classSelector(el)} overflows its box by ${Math.round(delta)}px` }];
3302
5327
  }
5328
+
5329
+ // Inline text owners have no client geometry (clientWidth/scrollWidth are
5330
+ // both 0), so the scrollWidth path above never sees them. Their overflow
5331
+ // registers only on a block ancestor, and that ancestor has no direct text
5332
+ // so the ownership gate skips it. (The shipped miss: a nowrap inline
5333
+ // <span> spilling 45px past its fixed-width grid cell.) Measure the inline
5334
+ // box against the padding box of its nearest block container instead.
5335
+ if (el.clientWidth === 0 && rect && rect.width > 0) {
5336
+ let container = el.parentElement;
5337
+ while (container && container.clientWidth === 0) container = container.parentElement;
5338
+ if (!container) return [];
5339
+ // Transforms make rect comparisons lie; skip anything on that path.
5340
+ for (let p = el; p && p !== container.parentElement; p = p.parentElement) {
5341
+ const t = getComputedStyle(p).transform;
5342
+ if (t && t !== 'none') return [];
5343
+ }
5344
+ const cRect = container.getBoundingClientRect();
5345
+ const contentRight = cRect.left + container.clientLeft + container.clientWidth;
5346
+ const spill = rect.right - contentRight;
5347
+ if (spill >= 16) {
5348
+ return [{ id: 'text-overflow', snippet: `${classSelector(el)} overflows its container by ${Math.round(spill)}px` }];
5349
+ }
5350
+ }
3303
5351
  return [];
3304
5352
  }
3305
5353
 
5354
+ // ---------------------------------------------------------------------------
5355
+ // Blinking cursor (browser-only)
5356
+ // ---------------------------------------------------------------------------
5357
+
5358
+ // Block / underscore glyphs commonly used as a fake text cursor.
5359
+ const CURSOR_GLYPH_RE = /^[_|▀-▟■▮❙❚|]$/;
5360
+
5361
+ // How far down the page still counts as the first-viewport / hero region.
5362
+ // Hero compositions regularly run past a literal viewport height, so the
5363
+ // gate is a landing-region budget, not an exact fold line.
5364
+ const CURSOR_FIRST_VIEWPORT_PX = 1200;
5365
+
5366
+ // Do the named @keyframes only toggle visibility (opacity dropping to ~0 or
5367
+ // visibility:hidden), i.e. a blink rather than a fade/move/spin? Walks the
5368
+ // live CSSOM; cross-origin sheets are skipped.
5369
+ function keyframesToggleVisibilityDOM(name) {
5370
+ if (!name) return false;
5371
+ for (const sheet of document.styleSheets) {
5372
+ let rules;
5373
+ try { rules = sheet.cssRules || sheet.rules; } catch { continue; }
5374
+ if (!rules) continue;
5375
+ const stack = [...rules];
5376
+ while (stack.length) {
5377
+ const rule = stack.shift();
5378
+ if (rule.cssRules && rule.type !== 7) { stack.push(...rule.cssRules); continue; }
5379
+ if (rule.type !== 7 || rule.name !== name) continue; // 7 = KEYFRAMES_RULE
5380
+ let togglesOut = false;
5381
+ for (const frame of rule.cssRules || []) {
5382
+ const fs = frame.style;
5383
+ if (!fs) continue;
5384
+ for (let i = 0; i < fs.length; i++) {
5385
+ const prop = fs[i];
5386
+ if (prop === 'opacity') {
5387
+ if ((parseFloat(fs.getPropertyValue('opacity')) || 0) <= 0.15) togglesOut = true;
5388
+ } else if (prop === 'visibility') {
5389
+ if (/hidden/i.test(fs.getPropertyValue('visibility'))) togglesOut = true;
5390
+ } else if (prop !== 'animation-timing-function') {
5391
+ return false; // keyframes animate something else — not a blink
5392
+ }
5393
+ }
5394
+ }
5395
+ return togglesOut;
5396
+ }
5397
+ }
5398
+ return false;
5399
+ }
5400
+
5401
+ // Decorative blinking cursor: a small block / underscore element bound to an
5402
+ // infinite blink animation, sitting in the first-viewport region of a page.
5403
+ // Real editable surfaces (inputs, textareas, contenteditable, role=textbox)
5404
+ // draw their own caret and are exempt. Round pulsing dots stay with the
5405
+ // pulsing-dot rule.
5406
+ function checkElementBlinkingCursorDOM(el) {
5407
+ const tag = el.tagName.toLowerCase();
5408
+ if (['input', 'textarea', 'select', 'img', 'svg', 'script', 'style'].includes(tag)) return [];
5409
+ const style = getComputedStyle(el);
5410
+
5411
+ const iterations = (style.animationIterationCount || '').split(',').map(s => s.trim());
5412
+ if (!iterations.includes('infinite')) return [];
5413
+ const names = (style.animationName || '').split(',').map(s => s.trim()).filter(n => n && n !== 'none');
5414
+ if (names.length === 0) return [];
5415
+ const blinkName = names.find(n => /blink|caret|cursor/i.test(n))
5416
+ || names.find(n => keyframesToggleVisibilityDOM(n));
5417
+ if (!blinkName) return [];
5418
+
5419
+ // Real caret contexts are exempt.
5420
+ if (el.isContentEditable || el.closest('[contenteditable=""], [contenteditable="true"], [role="textbox"]')) return [];
5421
+
5422
+ const rect = el.getBoundingClientRect();
5423
+ if (rect.width <= 0 || rect.height <= 0) return [];
5424
+
5425
+ // First-viewport gate: the hero cliché, not a footer terminal.
5426
+ const pageTop = rect.top + (window.scrollY || 0);
5427
+ if (pageTop > CURSOR_FIRST_VIEWPORT_PX) return [];
5428
+
5429
+ // Cursor shape: a lone block/underscore glyph, or an empty solid
5430
+ // rectangle sized like a text caret (block or underscore form).
5431
+ const text = (el.textContent || '').trim();
5432
+ const glyphCursor = text.length === 1 && CURSOR_GLYPH_RE.test(text);
5433
+ let blockCursor = false;
5434
+ if (!glyphCursor) {
5435
+ if (text.length > 0 || el.childElementCount > 0) return [];
5436
+ const bg = parseAnyColor(style.backgroundColor || '');
5437
+ const filled = bg && (bg.a ?? 1) > 0.2;
5438
+ const hasBorderFill = ['Left', 'Right', 'Bottom'].some(
5439
+ side => (parseFloat(style[`border${side}Width`]) || 0) >= 1,
5440
+ );
5441
+ if (!filled && !hasBorderFill) return [];
5442
+ const vertical = rect.width >= 1 && rect.width <= 24 && rect.height >= 6 && rect.height <= 48 && rect.height >= rect.width;
5443
+ const underscore = rect.height >= 1 && rect.height <= 6 && rect.width >= 4 && rect.width <= 24;
5444
+ if (!vertical && !underscore) return [];
5445
+ // Round dots are the pulsing-dot rule's territory.
5446
+ const radiusPx = parseFloat(style.borderRadius) || 0;
5447
+ if (radiusPx >= 0.4 * Math.min(rect.width, rect.height)) return [];
5448
+ blockCursor = true;
5449
+ }
5450
+ if (!glyphCursor && !blockCursor) return [];
5451
+
5452
+ // Hero-region promotion: a fake caret blinking in the first ~900px or
5453
+ // inside the page chrome is the shipped hero cliché, not an incidental
5454
+ // flourish. Promote those from the registry's advisory to warning;
5455
+ // lower first-viewport occurrences keep the default severity.
5456
+ const inHeroRegion = pageTop <= 900
5457
+ || !!(el.closest && el.closest('header, nav, [role="banner"], [role="navigation"]'));
5458
+ return [{
5459
+ id: 'blinking-cursor',
5460
+ snippet: `${classSelector(el)} — ${Math.round(rect.width)}x${Math.round(rect.height)}px blinking cursor (animation "${blinkName}") in the first viewport`,
5461
+ ...(inHeroRegion ? { severity: 'warning' } : {}),
5462
+ }];
5463
+ }
5464
+
5465
+ // ---------------------------------------------------------------------------
5466
+ // Content invisible at rest (browser-only, driven by the URL engine)
5467
+ // ---------------------------------------------------------------------------
5468
+
5469
+ // Tags whose text never renders, or whose hidden state is legitimate UI
5470
+ // (templates, dialogs, native select options). Text inside them stays out of
5471
+ // both the numerator and the denominator.
5472
+ const HIDDEN_TEXT_EXCLUDE_TAGS = new Set([
5473
+ 'script', 'style', 'noscript', 'template', 'title', 'head', 'meta', 'link',
5474
+ 'option', 'optgroup', 'select', 'datalist', 'dialog',
5475
+ ]);
5476
+
5477
+ // Measure how many text characters currently render invisible (computed
5478
+ // opacity ~0 or visibility hidden anywhere on the ancestor chain) versus
5479
+ // visible. display:none / [hidden] / aria-hidden subtrees are legitimately
5480
+ // hidden UI (menus, tab panels, templates): they are excluded from the
5481
+ // denominator entirely rather than counted as invisible.
5482
+ function measureHiddenTextDOM() {
5483
+ const cache = new Map();
5484
+ function stateOf(el) {
5485
+ if (!el || el.nodeType !== 1 || el === document.documentElement) return 'visible';
5486
+ const cached = cache.get(el);
5487
+ if (cached) return cached;
5488
+ let state;
5489
+ const tag = el.tagName.toLowerCase();
5490
+ if (HIDDEN_TEXT_EXCLUDE_TAGS.has(tag)) {
5491
+ state = 'excluded';
5492
+ } else {
5493
+ const parentState = stateOf(el.parentElement);
5494
+ if (parentState === 'excluded') {
5495
+ state = 'excluded';
5496
+ } else {
5497
+ const style = getComputedStyle(el);
5498
+ if (style.display === 'none' || el.hidden || el.getAttribute('aria-hidden') === 'true'
5499
+ || String(style.contentVisibility || '').toLowerCase() === 'hidden') {
5500
+ state = 'excluded';
5501
+ } else if (parentState === 'invisible'
5502
+ || (parseFloat(style.opacity) || 0) <= 0.02
5503
+ || /^(hidden|collapse)$/.test(style.visibility)) {
5504
+ state = 'invisible';
5505
+ } else {
5506
+ state = 'visible';
5507
+ }
5508
+ }
5509
+ }
5510
+ cache.set(el, state);
5511
+ return state;
5512
+ }
5513
+
5514
+ let totalChars = 0;
5515
+ let hiddenChars = 0;
5516
+ const hiddenSamples = [];
5517
+ for (const el of document.querySelectorAll('body *')) {
5518
+ let len = 0;
5519
+ for (const node of el.childNodes) {
5520
+ if (node.nodeType === 3) len += node.textContent.replace(/\s+/g, ' ').trim().length;
5521
+ }
5522
+ if (!len) continue;
5523
+ const state = stateOf(el);
5524
+ if (state === 'excluded') continue;
5525
+ totalChars += len;
5526
+ if (state === 'invisible') {
5527
+ hiddenChars += len;
5528
+ if (hiddenSamples.length < 3) {
5529
+ const text = String(el.textContent || '').replace(/\s+/g, ' ').trim().slice(0, 40);
5530
+ if (text) hiddenSamples.push(text);
5531
+ }
5532
+ }
5533
+ }
5534
+ return { totalChars, hiddenChars, hiddenSamples };
5535
+ }
5536
+
5537
+ // Pure threshold check over a measureHiddenTextDOM() result. The URL engine
5538
+ // calls it AFTER a reveal sweep (scroll through the document so every
5539
+ // IntersectionObserver / scroll reveal had its chance to fire, then back to
5540
+ // the top): a healthy reveal-on-scroll page drops to ~0 invisible text after
5541
+ // the sweep, while a page whose reveal script died keeps most of its text at
5542
+ // opacity 0 forever. Fires only when the invisible share stays above 30%
5543
+ // with a real amount of text behind it.
5544
+ function checkContentHiddenAtRest({ totalChars = 0, hiddenChars = 0, hiddenSamples = [] } = {}) {
5545
+ if (totalChars < 200 || hiddenChars < 150) return [];
5546
+ const share = hiddenChars / totalChars;
5547
+ if (share <= 0.3) return [];
5548
+ const sample = hiddenSamples.length ? ` (e.g. "${hiddenSamples[0]}")` : '';
5549
+ return [{
5550
+ id: 'content-hidden-at-rest',
5551
+ snippet: `${Math.round(share * 100)}% of page text (${hiddenChars} of ${totalChars} chars) stays at opacity 0 / visibility hidden after reveal handlers ran${sample}`,
5552
+ }];
5553
+ }
5554
+
5555
+ // ---------------------------------------------------------------------------
5556
+ // Edge-flush cards in horizontal scrollers (browser-only)
5557
+ // ---------------------------------------------------------------------------
5558
+
5559
+ // A visually-defined card (own opaque background, or borders on 2+ sides)
5560
+ // inside a horizontal scroller, sitting flush against one edge of the
5561
+ // scroller's clip box at rest while keeping a clear gutter on the other
5562
+ // side. The canonical bug: the first snap panel is sized wider than the
5563
+ // scroller, so its cards end exactly at the clip edge with their rounded
5564
+ // corners cut, while every sibling panel keeps its inset. Cards that extend
5565
+ // far past the edge are deliberate peeks and stay exempt.
5566
+ function checkEdgeFlushCardsDOM() {
5567
+ const findings = [];
5568
+ const vh = window.innerHeight || 800;
5569
+ const isScroller = (s) => /(auto|scroll)/.test(s.overflowX || '') || /(auto|scroll)/.test(s.overflow || '');
5570
+
5571
+ for (const scroller of document.querySelectorAll('*')) {
5572
+ const style = getComputedStyle(scroller);
5573
+ if (!isScroller(style)) continue;
5574
+ if (scroller.scrollWidth <= scroller.clientWidth + 8) continue;
5575
+ // At rest only: a user-scrolled or snapped-forward scroller legitimately
5576
+ // shows cut cards at both edges.
5577
+ if (scroller.scrollLeft > 4) continue;
5578
+ const scRect = scroller.getBoundingClientRect();
5579
+ if (scRect.width < 120 || scRect.height < 60) continue;
5580
+ // Landing-region gate: the defect matters where the page opens.
5581
+ if (scRect.top + (window.scrollY || 0) > 2 * vh) continue;
5582
+ const contentLeft = scRect.left + scroller.clientLeft;
5583
+ const contentRight = contentLeft + scroller.clientWidth;
5584
+
5585
+ const flush = [];
5586
+ for (const card of scroller.querySelectorAll('*')) {
5587
+ if (!isRenderedForBrowserRule(card)) continue;
5588
+ // Attribute cards to their nearest scroller only (nested scrollers).
5589
+ let owner = card.parentElement;
5590
+ while (owner && owner !== scroller && !isScroller(getComputedStyle(owner))) owner = owner.parentElement;
5591
+ if (owner !== scroller) continue;
5592
+ const cs = getComputedStyle(card);
5593
+ const rect = card.getBoundingClientRect();
5594
+ if (rect.width < 80 || rect.height < 40) continue;
5595
+ const bg = parseAnyColor(cs.backgroundColor || '');
5596
+ const hasBg = !!(bg && (bg.a ?? 1) > 0.5);
5597
+ const borderSides = ['Top', 'Right', 'Bottom', 'Left']
5598
+ .filter(side => (parseFloat(cs[`border${side}Width`]) || 0) > 0).length;
5599
+ if (!hasBg && borderSides < 2) continue;
5600
+ const leftGutter = rect.left - contentLeft;
5601
+ const rightGap = contentRight - rect.right;
5602
+ // Flush right with a left gutter, or the mirror. The -24 floor keeps
5603
+ // deliberately peeking next-cards (cut mid-card) exempt.
5604
+ const flushRight = leftGutter >= 6 && rightGap < 8 && rightGap > -24;
5605
+ const flushLeft = rightGap >= 6 && leftGutter < 8 && leftGutter > -24;
5606
+ if (!flushRight && !flushLeft) continue;
5607
+ flush.push({ card, edge: flushRight ? 'right' : 'left', gap: Math.round(flushRight ? rightGap : leftGutter) });
5608
+ }
5609
+ if (flush.length === 0) continue;
5610
+ const worst = flush.reduce((a, b) => (b.gap < a.gap ? b : a));
5611
+ findings.push({
5612
+ el: scroller,
5613
+ type: 'edge-flush-cards',
5614
+ detail: `${flush.length} card${flush.length === 1 ? '' : 's'} flush against the ${worst.edge} edge of ${classSelector(scroller)} at rest (${worst.gap}px gap, e.g. ${classSelector(worst.card)})`,
5615
+ });
5616
+ }
5617
+ return findings;
5618
+ }
5619
+
5620
+ // ---------------------------------------------------------------------------
5621
+ // Text occlusion / element overlap (browser-only)
5622
+ // ---------------------------------------------------------------------------
5623
+
5624
+ // An opaque decorated box: a near-solid background fill or two-plus visible
5625
+ // borders make it hide whatever sits behind it. Gradient / image fills are
5626
+ // deliberately excluded — a scrim gradient over hero imagery is a contrast
5627
+ // layer, not an occluder, and belongs to the pixel low-contrast rule.
5628
+ function isOpaqueDecoratedBox(cs) {
5629
+ if (!cs) return false;
5630
+ const bg = parseAnyColor(cs.backgroundColor || '');
5631
+ if (bg && (bg.a ?? 1) > 0.6) return true;
5632
+ const borderSides = ['Top', 'Right', 'Bottom', 'Left'].filter((side) => {
5633
+ if ((parseFloat(cs[`border${side}Width`]) || 0) <= 0) return false;
5634
+ const bc = parseAnyColor(cs[`border${side}Color`] || '');
5635
+ return bc && (bc.a ?? 1) > 0.3;
5636
+ }).length;
5637
+ return borderSides >= 2;
5638
+ }
5639
+
5640
+ // Is this element lifted out of normal flow into a layer that can cover
5641
+ // siblings? Two normal-flow blocks stacked vertically cannot truly hide each
5642
+ // other's ink — an overlap between their rects is line-box bleed from tight
5643
+ // leading (a display headline reaching up over the line before it), not
5644
+ // occlusion. Only out-of-flow positioning (absolute / fixed / sticky) moves an
5645
+ // element off its own row onto the pixels of another; an in-place transform or
5646
+ // relative nudge on a display headline does not.
5647
+ function isLayeredElement(el) {
5648
+ for (let cur = el; cur && cur.nodeType === 1 && cur !== document.body; cur = cur.parentElement) {
5649
+ const pos = String(getComputedStyle(cur).position || 'static');
5650
+ if (pos === 'absolute' || pos === 'fixed' || pos === 'sticky') return true;
5651
+ }
5652
+ return false;
5653
+ }
5654
+
5655
+ function elementDirectText(el) {
5656
+ let t = '';
5657
+ for (const node of el.childNodes || []) {
5658
+ if (node.nodeType === 3) t += node.textContent;
5659
+ }
5660
+ return t.trim();
5661
+ }
5662
+
5663
+ // Rendered gate that, unlike isRenderedForBrowserRule, does NOT exempt
5664
+ // aria-hidden subtrees: a decorative aria-hidden box still paints on screen
5665
+ // and can still visually cover real text.
5666
+ function isPaintedForOcclusion(el) {
5667
+ for (let cur = el; cur && cur.nodeType === 1; cur = cur.parentElement) {
5668
+ const style = getComputedStyle(cur);
5669
+ const visibility = String(style.visibility || '').toLowerCase();
5670
+ if (style.display === 'none' || visibility === 'hidden' || visibility === 'collapse') return false;
5671
+ if ((parseFloat(style.opacity) || 0) <= 0.05) return false;
5672
+ if (String(style.contentVisibility || '').toLowerCase() === 'hidden') return false;
5673
+ }
5674
+ return true;
5675
+ }
5676
+
5677
+ // Detects text that is actually painted UNDER an opaque box or another text
5678
+ // run (the reader can't read it), plus two structural overlap tells the
5679
+ // elementFromPoint probe can't reach: a large headline whose edge tucks behind
5680
+ // an opaque card, and an inline element whose leaked padding-box (a common
5681
+ // class-name-collision bug) covers a sibling.
5682
+ //
5683
+ // The occlusion probe is viewport-bound: elementFromPoint only answers for the
5684
+ // scan's current viewport (scroll 0), so the ground-truth paths cover the
5685
+ // first-viewport composition where collisions matter most. The inline-leak
5686
+ // path is pure geometry and runs anywhere on the page.
5687
+ const OCCLUSION_TEXT_SKIP_TAGS = new Set(['script', 'style', 'noscript', 'template', 'title']);
5688
+
5689
+ function checkTextOcclusionDOM() {
5690
+ const findings = [];
5691
+ const seenVictims = new Set();
5692
+ const vw = window.innerWidth || 1280;
5693
+ const vh = window.innerHeight || 800;
5694
+
5695
+ const isFloated = (cs) => {
5696
+ const f = String(cs.cssFloat || cs.float || 'none').toLowerCase();
5697
+ return f === 'left' || f === 'right';
5698
+ };
5699
+ const isMarqueeish = (el, cs) => {
5700
+ if (el.tagName === 'MARQUEE') return true;
5701
+ const ident = `${el.getAttribute?.('class') || ''} ${el.getAttribute?.('id') || ''}`;
5702
+ if (/\b(marquee|ticker|scroller|carousel|conveyor)\b/i.test(ident)) return true;
5703
+ const anim = String(cs.animationName || '').toLowerCase();
5704
+ return /marquee|ticker|scroll/.test(anim);
5705
+ };
5706
+ // A fixed or sticky overlay (status bar, toolbar, sticky header) floats above
5707
+ // scrolling content by design — whatever sits under it at rest scrolls clear,
5708
+ // so it is not occluding the page.
5709
+ const isPinnedOverlay = (el) => {
5710
+ for (let cur = el; cur && cur.nodeType === 1 && cur !== document.body; cur = cur.parentElement) {
5711
+ const pos = String(getComputedStyle(cur).position || 'static');
5712
+ if (pos === 'fixed' || pos === 'sticky') return true;
5713
+ }
5714
+ return false;
5715
+ };
5716
+
5717
+ // Collect renderable text owners in / near the first viewport for the
5718
+ // elementFromPoint probe. SVG <text> counts too.
5719
+ const textEls = [];
5720
+ for (const el of document.querySelectorAll('body *')) {
5721
+ const tag = el.tagName.toLowerCase();
5722
+ if (OCCLUSION_TEXT_SKIP_TAGS.has(tag)) continue;
5723
+ const inSvg = !!el.closest('svg');
5724
+ if (inSvg && tag !== 'text') continue;
5725
+ const text = inSvg ? (el.textContent || '').trim() : elementDirectText(el);
5726
+ if (text.length < 2) continue;
5727
+ if (!isPaintedForOcclusion(el)) continue;
5728
+ let rect; try { rect = el.getBoundingClientRect(); } catch { continue; }
5729
+ if (rect.width < 6 || rect.height < 6) continue;
5730
+ // Viewport-bound probe: keep text whose box overlaps the live viewport.
5731
+ if (rect.bottom <= 0 || rect.top >= vh) continue;
5732
+ textEls.push({ el, rect, text, inSvg });
5733
+ }
5734
+
5735
+ for (const victim of textEls) {
5736
+ const { el, rect, text } = victim;
5737
+ if (seenVictims.has(el)) continue;
5738
+ const style = getComputedStyle(el);
5739
+ if (isScreenReaderOnlyTextStyle(style, { width: rect.width, height: rect.height, clientWidth: el.clientWidth, clientHeight: el.clientHeight })) continue;
5740
+
5741
+ const cols = Math.max(6, Math.min(30, Math.round(rect.width / 12)));
5742
+ const rows = Math.max(1, Math.min(4, Math.round(rect.height / 14)));
5743
+ let total = 0;
5744
+ let occluded = 0;
5745
+ let occluderEl = null;
5746
+ let occluderKind = '';
5747
+ for (let i = 0; i < cols; i++) {
5748
+ const x = rect.left + rect.width * ((i + 0.5) / cols);
5749
+ if (x < 1 || x > vw - 1) continue;
5750
+ for (let j = 0; j < rows; j++) {
5751
+ const y = rect.top + rect.height * ((j + 0.5) / rows);
5752
+ if (y < 1 || y > vh - 1) continue;
5753
+ total++;
5754
+ const top = document.elementFromPoint(x, y);
5755
+ if (!top) continue;
5756
+ // Text visible here: the probe returns the text itself, a descendant,
5757
+ // or one of its ancestors (the text's own container / background).
5758
+ if (top === el || el.contains(top) || top.contains(el)) continue;
5759
+ const topCs = getComputedStyle(top);
5760
+ if (isFloated(topCs) || isMarqueeish(top, topCs) || isPinnedOverlay(top)) continue;
5761
+ const topTag = top.tagName.toLowerCase();
5762
+ // Text sitting under a raw image/video is contrast territory (deduped
5763
+ // against the pixel low-contrast rule); leave those alone here.
5764
+ if (['img', 'video', 'canvas', 'picture'].includes(topTag)) continue;
5765
+ const topHasText = elementDirectText(top).length > 0 || !!top.closest('svg');
5766
+ if (isOpaqueDecoratedBox(topCs)) {
5767
+ occluded++;
5768
+ if (!occluderEl) { occluderEl = top; occluderKind = 'box'; }
5769
+ } else if (topHasText) {
5770
+ occluded++;
5771
+ if (!occluderEl) { occluderEl = top; occluderKind = 'text'; }
5772
+ }
5773
+ }
5774
+ }
5775
+ if (total === 0 || !occluderEl) continue;
5776
+ const occFrac = occluded / total;
5777
+ // A solid box's paint fills its rect, so box coverage is real at a lower
5778
+ // bar. Text coverage rides on elementFromPoint returning the occluder's box
5779
+ // (line box / container), which can exceed its actual glyph ink, so the
5780
+ // text bar is higher — partial overlaps below it are crowding, not burial.
5781
+ if (occFrac < (occluderKind === 'text' ? 0.45 : 0.3)) continue;
5782
+
5783
+ // (i) Substantial occlusion: a real slab of the text is behind something.
5784
+ if (occluderKind === 'text') {
5785
+ // Two SVG texts inside the same emblem (concentric arcs, monogram) are one
5786
+ // decorative unit, not a collision.
5787
+ const victimSvg = el.closest('svg');
5788
+ const occSvg = occluderEl.closest('svg');
5789
+ if (victimSvg && occSvg && victimSvg === occSvg) continue;
5790
+ // Both sides in plain flow: the overlap is line-box bleed from tight
5791
+ // leading (a big headline reaching up over its own eyebrow), not one text
5792
+ // run painted over another.
5793
+ if (!isLayeredElement(el) && !isLayeredElement(occluderEl)) continue;
5794
+ }
5795
+ seenVictims.add(el);
5796
+ findings.push({
5797
+ el,
5798
+ type: 'text-occlusion',
5799
+ detail: `${classSelector(el)} "${text.slice(0, 24)}" is ${Math.round(occFrac * 100)}% covered by ${occluderKind === 'text' ? 'overlapping text' : 'an opaque element'} (${classSelector(occluderEl)})`,
5800
+ });
5801
+ }
5802
+
5803
+ // (ii) Headline overhanging an opaque card: a display-scale line whose bulk
5804
+ // sits outside a bounded content card but whose edge clips into it. The text
5805
+ // may still paint on top and stay readable, but the two layers were dropped
5806
+ // on the same pixels — a placement collision, not a composition.
5807
+ const cards = [];
5808
+ for (const el of document.querySelectorAll('body *')) {
5809
+ if (el.closest('svg')) continue;
5810
+ if (!isPaintedForOcclusion(el)) continue;
5811
+ const cs = getComputedStyle(el);
5812
+ const bg = parseAnyColor(cs.backgroundColor || '');
5813
+ const bgImg = cs.backgroundImage || '';
5814
+ if (!bg || (bg.a ?? 1) <= 0.7) continue;
5815
+ if (bgImg && bgImg !== 'none' && /(gradient|url)\(/i.test(bgImg)) continue;
5816
+ const hasBorder = ['Top', 'Right', 'Bottom', 'Left'].some((s) => (parseFloat(cs[`border${s}Width`]) || 0) > 0);
5817
+ const hasShadow = cs.boxShadow && cs.boxShadow !== 'none';
5818
+ if (!hasBorder && !hasShadow) continue;
5819
+ if (isPinnedOverlay(el)) continue;
5820
+ let cr; try { cr = el.getBoundingClientRect(); } catch { continue; }
5821
+ if (cr.width < 100 || cr.width > 0.8 * vw || cr.height < 60) continue;
5822
+ cards.push({ el, rect: cr });
5823
+ }
5824
+ for (const victim of textEls) {
5825
+ const { el, rect, text } = victim;
5826
+ if (seenVictims.has(el)) continue;
5827
+ const style = getComputedStyle(el);
5828
+ if ((parseFloat(style.fontSize) || 16) < 40) continue;
5829
+ let lineHeight = parseFloat(style.lineHeight);
5830
+ if (!Number.isFinite(lineHeight)) lineHeight = (parseFloat(style.fontSize) || 16) * 1.2;
5831
+ const centerX = rect.left + rect.width / 2;
5832
+ for (const card of cards) {
5833
+ if (card.el === el || el.contains(card.el) || card.el.contains(el)) continue;
5834
+ const ix = Math.max(0, Math.min(rect.right, card.rect.right) - Math.max(rect.left, card.rect.left));
5835
+ const iy = Math.max(0, Math.min(rect.bottom, card.rect.bottom) - Math.max(rect.top, card.rect.top));
5836
+ if (ix < 8 || iy < 0.5 * lineHeight) continue;
5837
+ // The headline's bulk must sit outside the card — only its edge clips in.
5838
+ if (centerX >= card.rect.left && centerX <= card.rect.right) continue;
5839
+ if (ix > 0.5 * rect.width) continue;
5840
+ seenVictims.add(el);
5841
+ findings.push({
5842
+ el,
5843
+ type: 'text-occlusion',
5844
+ detail: `${classSelector(el)} "${text.slice(0, 24)}" overhangs ${classSelector(card.el)} by ${Math.round(ix)}px — the headline and the card collide`,
5845
+ });
5846
+ break;
5847
+ }
5848
+ }
5849
+
5850
+ // (iii) Inline padding leak: an inline element with an opaque background and
5851
+ // large vertical padding paints a filled block whose padding-box overflows
5852
+ // its line (inline padding reserves no vertical space), so the fill lands on
5853
+ // the content above and below instead of enclosing its own text. The
5854
+ // canonical bug is a class-name collision that hands a decorative marker a
5855
+ // payoff card's padding. The tell is a rendered height several times the line
5856
+ // height, which distinguishes the leak from a padded inline highlight.
5857
+ for (const el of document.querySelectorAll('body *')) {
5858
+ if (el.closest('svg')) continue;
5859
+ if (!isPaintedForOcclusion(el)) continue;
5860
+ const cs = getComputedStyle(el);
5861
+ if (cs.display !== 'inline') continue;
5862
+ const bg = parseAnyColor(cs.backgroundColor || '');
5863
+ if (!bg || (bg.a ?? 1) <= 0.6) continue;
5864
+ const padTop = parseFloat(cs.paddingTop) || 0;
5865
+ const padBottom = parseFloat(cs.paddingBottom) || 0;
5866
+ if (padTop + padBottom < 24) continue;
5867
+ let rect; try { rect = el.getBoundingClientRect(); } catch { continue; }
5868
+ if (rect.width < 12 || rect.height < 24) continue;
5869
+ const fontSize = parseFloat(cs.fontSize) || 16;
5870
+ let lineHeight = parseFloat(cs.lineHeight);
5871
+ if (!Number.isFinite(lineHeight)) lineHeight = fontSize * 1.4;
5872
+ // The padding box has to overflow the line by a clear margin — a padded
5873
+ // inline highlight sits at roughly one line height, the leak at several.
5874
+ if (rect.height < 2.2 * lineHeight) continue;
5875
+ if (seenVictims.has(el)) continue;
5876
+ // Name a neighbour the fill lands on, if one is nearby (paint state aside,
5877
+ // reveal-on-scroll siblings still occupy the space it covers).
5878
+ let overlaps = null;
5879
+ for (const other of el.parentElement ? el.parentElement.children : []) {
5880
+ if (other === el || el.contains(other) || other.contains(el)) continue;
5881
+ if (getComputedStyle(other).display === 'none') continue;
5882
+ const oRect = other.getBoundingClientRect();
5883
+ const ix = Math.max(0, Math.min(rect.right, oRect.right) - Math.max(rect.left, oRect.left));
5884
+ const iy = Math.max(0, Math.min(rect.bottom, oRect.bottom) - Math.max(rect.top, oRect.top));
5885
+ if (ix > 4 && iy > 4 && (other.textContent || '').trim().length > 0) { overlaps = other; break; }
5886
+ }
5887
+ seenVictims.add(el);
5888
+ findings.push({
5889
+ el,
5890
+ type: 'text-occlusion',
5891
+ detail: `${classSelector(el)} is an inline element whose opaque fill leaks ${Math.round(rect.height)}px past its line${overlaps ? ` onto ${classSelector(overlaps)}` : ''}`,
5892
+ });
5893
+ }
5894
+
5895
+ return findings;
5896
+ }
5897
+
5898
+ // ---------------------------------------------------------------------------
5899
+ // First-viewport column overflow — the stretched-hero signature (browser-only)
5900
+ // ---------------------------------------------------------------------------
5901
+
5902
+ // A multi-column composition that opens the page (grid/flex with two or more
5903
+ // side-by-side columns, each a real share of the width) where one column's
5904
+ // content runs far past the fold while its sibling fits inside a single
5905
+ // viewport. The row stretches to the tall column, so the short one floats in a
5906
+ // screen-and-a-half of dead space and the fold falls deep inside a single
5907
+ // section. Single-column pages and full-page heroes (no sibling column) are
5908
+ // exempt because there is no fitting sibling to contrast against.
5909
+ function checkFirstViewportColumnOverflowDOM() {
5910
+ const findings = [];
5911
+ const vw = window.innerWidth || 1280;
5912
+ const vh = window.innerHeight || 800;
5913
+ const isMultiCol = (s) => /(^|inline-)(grid|flex)$/.test(String(s.display || ''));
5914
+
5915
+ for (const el of document.querySelectorAll('body *')) {
5916
+ const style = getComputedStyle(el);
5917
+ if (!isMultiCol(style)) continue;
5918
+ let rect; try { rect = el.getBoundingClientRect(); } catch { continue; }
5919
+ if (rect.width < 0.5 * vw) continue;
5920
+ const pageTop = rect.top + (window.scrollY || 0);
5921
+ const pageBottom = pageTop + rect.height;
5922
+ // The fold must fall inside this container: it opens within the first
5923
+ // viewport and runs past it.
5924
+ if (pageTop >= vh * 0.9 || pageBottom <= vh) continue;
5925
+
5926
+ // Direct children that read as side-by-side columns: a real width share,
5927
+ // not full-bleed (stacked single column), sharing the container's top row.
5928
+ const cols = [];
5929
+ for (const child of el.children) {
5930
+ const cs = getComputedStyle(child);
5931
+ if (cs.display === 'none') continue;
5932
+ if (String(cs.position || '') === 'absolute' || String(cs.position || '') === 'fixed') continue;
5933
+ let cr; try { cr = child.getBoundingClientRect(); } catch { continue; }
5934
+ const wShare = cr.width / rect.width;
5935
+ if (wShare < 0.25 || wShare > 0.9) continue;
5936
+ if (cr.height < 40) continue;
5937
+ // Content extent: how far the child's own content actually reaches,
5938
+ // independent of a stretched row height.
5939
+ let contentBottom = cr.top;
5940
+ for (const d of child.querySelectorAll('*')) {
5941
+ const ds = getComputedStyle(d);
5942
+ if (ds.position === 'absolute' || ds.position === 'fixed') continue;
5943
+ if (ds.display === 'none' || ds.visibility === 'hidden') continue;
5944
+ let dr; try { dr = d.getBoundingClientRect(); } catch { continue; }
5945
+ if (dr.width > 0 && dr.height > 0) contentBottom = Math.max(contentBottom, dr.bottom);
5946
+ }
5947
+ cols.push({ child, top: cr.top, contentH: contentBottom - cr.top });
5948
+ }
5949
+ if (cols.length < 2) continue;
5950
+ // Side-by-side: the two candidate columns must share the top row.
5951
+ cols.sort((a, b) => b.contentH - a.contentH);
5952
+ const tall = cols[0];
5953
+ const shortest = cols[cols.length - 1];
5954
+ if (Math.abs(tall.top - shortest.top) > 0.25 * vh) continue;
5955
+ if (tall.contentH <= vh * 1.4) continue;
5956
+ if (shortest.contentH > vh) continue;
5957
+
5958
+ findings.push({
5959
+ el,
5960
+ type: 'first-viewport-column-overflow',
5961
+ detail: `${classSelector(el)} opens the page with one column running ${Math.round(tall.contentH / vh * 100)}% of the viewport tall while a sibling fits in ${Math.round(shortest.contentH / vh * 100)}% — the fold falls deep inside the section`,
5962
+ });
5963
+ }
5964
+ return findings;
5965
+ }
5966
+
3306
5967
  // --- cli/engine/browser/injected/index.mjs ---
3307
5968
  const IS_BROWSER = typeof window !== 'undefined';
3308
5969
 
@@ -4528,7 +7189,11 @@ if (IS_BROWSER) {
4528
7189
  return {
4529
7190
  type: f.type || f.id,
4530
7191
  category: ap ? ap.category : 'quality',
4531
- severity: ap?.severity || 'warning',
7192
+ severity: f.severity || ap?.severity || 'warning',
7193
+ // Advisory findings (em-dash overuse, etc.) are surfaced but never
7194
+ // treated as failures; carry the flag so the overlay/extension can
7195
+ // render them with the mildest affordance and consumers can filter.
7196
+ advisory: (ap && ap.advisory === true) || f.advisory === true,
4532
7197
  detail: f.detail || f.snippet,
4533
7198
  ignoreValue: f.ignoreValue || f.value || '',
4534
7199
  name: ap ? ap.name : (f.type || f.id),
@@ -4764,10 +7429,7 @@ if (IS_BROWSER) {
4764
7429
  const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
4765
7430
  const designSystem = browserDesignSystemConfig();
4766
7431
  const designSeen = { fonts: new Set(), colors: new Set(), radii: new Set() };
4767
- // Note: provider-gated rules (--gpt / --gemini) are NOT filtered here. In a
4768
- // real browser env (detector page, live overlay, extension) running every
4769
- // check is free, so we always surface them; the gating is purely a CLI
4770
- // output concern, applied in the Node engines' detect* return paths.
7432
+ // All deterministic rules run in the browser and extension path.
4771
7433
 
4772
7434
  for (const el of document.querySelectorAll('*')) {
4773
7435
  // Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
@@ -4783,6 +7445,7 @@ if (IS_BROWSER) {
4783
7445
 
4784
7446
  const findings = [
4785
7447
  ...checkElementBordersDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
7448
+ ...checkElementPseudoStripeDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
4786
7449
  ...checkElementColorsDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
4787
7450
  ...checkElementMotionDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
4788
7451
  ...checkElementGlowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
@@ -4794,6 +7457,7 @@ if (IS_BROWSER) {
4794
7457
  ...checkElementClippedOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
4795
7458
  ...checkElementGptBorderShadowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
4796
7459
  ...checkElementTextOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
7460
+ ...checkElementBlinkingCursorDOM(el).map(f => ({ type: f.id, detail: f.snippet, ...(f.severity ? { severity: f.severity } : {}) })),
4797
7461
  ...checkElementDesignSystemDOM(el, designSystem, designSeen),
4798
7462
  ].filter(f => _ruleOk(f.type));
4799
7463
 
@@ -4832,12 +7496,66 @@ if (IS_BROWSER) {
4832
7496
  addBrowserFindings(groupMap, document.body, sectionKickerFindings);
4833
7497
  }
4834
7498
 
7499
+ const numberedLabelFindings = checkNumberedSectionLabelsDOM()
7500
+ .map(f => ({ type: f.id, detail: f.snippet }))
7501
+ .filter(f => _ruleOk(f.type));
7502
+ if (numberedLabelFindings.length > 0) {
7503
+ pageLevelFindings.push(...numberedLabelFindings);
7504
+ addBrowserFindings(groupMap, document.body, numberedLabelFindings);
7505
+ }
7506
+
7507
+ const repeatedTextFindings = checkRepeatedContainerTextDOM()
7508
+ .map(f => ({ type: f.id, detail: f.snippet }))
7509
+ .filter(f => _ruleOk(f.type));
7510
+ if (repeatedTextFindings.length > 0) {
7511
+ pageLevelFindings.push(...repeatedTextFindings);
7512
+ addBrowserFindings(groupMap, document.body, repeatedTextFindings);
7513
+ }
7514
+
7515
+ // Em-dash overuse (advisory): browser parity with the static/regex path.
7516
+ // Reads rendered body text so it catches dashes written as HTML entities.
7517
+ // serializeFindings stamps the advisory flag from the registry.
7518
+ const emDashFindings = checkEmDashOveruseDOM()
7519
+ .map(f => ({ type: f.id, detail: f.snippet }))
7520
+ .filter(f => _ruleOk(f.type));
7521
+ if (emDashFindings.length > 0) {
7522
+ pageLevelFindings.push(...emDashFindings);
7523
+ addBrowserFindings(groupMap, document.body, emDashFindings);
7524
+ }
7525
+
4835
7526
  const layoutFindings = checkLayout().filter(f => _ruleOk(f.type));
4836
7527
  for (const f of layoutFindings) {
4837
7528
  const el = f.el || document.body;
4838
7529
  addBrowserFindings(groupMap, el, [{ type: f.type, detail: f.detail || f.snippet }]);
4839
7530
  }
4840
7531
 
7532
+ // Heading rhythm (browser-only: needs real layout for the gap math)
7533
+ const headingRhythmFindings = checkHeadingRhythmDOM().filter(f => _ruleOk(f.type));
7534
+ for (const f of headingRhythmFindings) {
7535
+ addBrowserFindings(groupMap, f.el || document.body, [{ type: f.type, detail: f.detail }]);
7536
+ }
7537
+
7538
+ // Edge-flush cards in horizontal scrollers (browser-only: needs real
7539
+ // layout for the scroller clip box vs card rect math)
7540
+ const edgeFlushFindings = checkEdgeFlushCardsDOM().filter(f => _ruleOk(f.type));
7541
+ for (const f of edgeFlushFindings) {
7542
+ addBrowserFindings(groupMap, f.el || document.body, [{ type: f.type, detail: f.detail }]);
7543
+ }
7544
+
7545
+ // Text occlusion / element overlap (browser-only: needs real layout +
7546
+ // elementFromPoint to confirm what actually paints on top)
7547
+ const occlusionFindings = checkTextOcclusionDOM().filter(f => _ruleOk(f.type));
7548
+ for (const f of occlusionFindings) {
7549
+ addBrowserFindings(groupMap, f.el || document.body, [{ type: f.type, detail: f.detail }]);
7550
+ }
7551
+
7552
+ // First-viewport column overflow — the stretched-hero signature
7553
+ // (browser-only: needs real layout for the content-extent math)
7554
+ const colOverflowFindings = checkFirstViewportColumnOverflowDOM().filter(f => _ruleOk(f.type));
7555
+ for (const f of colOverflowFindings) {
7556
+ addBrowserFindings(groupMap, f.el || document.body, [{ type: f.type, detail: f.detail }]);
7557
+ }
7558
+
4841
7559
  // Page-level quality checks (headings, etc.)
4842
7560
  const qualityFindings = checkPageQualityDOM().filter(f => _ruleOk(f.type));
4843
7561
  if (qualityFindings.length > 0) {
@@ -4863,7 +7581,25 @@ if (IS_BROWSER) {
4863
7581
  }
4864
7582
  const htmlPatternFindings = checkHtmlPatterns(docClone.outerHTML);
4865
7583
  if (htmlPatternFindings.length > 0) {
4866
- const mapped = htmlPatternFindings.map(f => ({ type: f.id, detail: f.snippet })).filter(f => _ruleOk(f.type));
7584
+ const mapped = htmlPatternFindings.map(f => {
7585
+ const item = { type: f.id, detail: f.snippet };
7586
+ if (f.severity) {
7587
+ item.severity = f.severity;
7588
+ } else if (f.id === 'pulsing-dot' && f.selector) {
7589
+ // The string scan promotes header/nav dots on its own; with a live
7590
+ // layout also promote dots resting in the first ~900px of the page
7591
+ // (the hero region), which the source scan cannot measure.
7592
+ try {
7593
+ const dotEl = document.querySelector(f.selector);
7594
+ if (dotEl) {
7595
+ const rect = dotEl.getBoundingClientRect();
7596
+ const pageTop = rect.top + (window.scrollY || 0);
7597
+ if (pageTop <= 900) item.severity = 'error';
7598
+ }
7599
+ } catch { /* unresolvable selector: keep registry severity */ }
7600
+ }
7601
+ return item;
7602
+ }).filter(f => _ruleOk(f.type));
4867
7603
  pageLevelFindings.push(...mapped);
4868
7604
  addBrowserFindings(groupMap, document.body, mapped);
4869
7605
  }
@@ -5237,6 +7973,9 @@ if (IS_BROWSER) {
5237
7973
  window.impeccableDetectAsync = detectAsync;
5238
7974
  window.impeccableScan = scan;
5239
7975
  window.impeccableScanAsync = scanAsync;
7976
+ // Raw measurement for the URL engine's content-hidden-at-rest pass: it
7977
+ // drives a reveal sweep from Node and thresholds the result itself.
7978
+ window.impeccableMeasureHiddenText = measureHiddenTextDOM;
5240
7979
  window.impeccableCollectVisualContrastCandidates = collectVisualContrastCandidates;
5241
7980
  window.impeccableAnalyzeVisualContrast = analyzeVisualContrast;
5242
7981
  window.impeccableGetLastVisualContrastAnalyses = () => lastVisualContrastAnalyses.slice();