@sloppy-ai/core 1.1.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/assets/check.d.ts +44 -0
  2. package/dist/assets/check.d.ts.map +1 -0
  3. package/dist/assets/check.js +132 -0
  4. package/dist/assets/check.js.map +1 -0
  5. package/dist/brief/kind.d.ts +29 -0
  6. package/dist/brief/kind.d.ts.map +1 -0
  7. package/dist/brief/kind.js +69 -0
  8. package/dist/brief/kind.js.map +1 -0
  9. package/dist/gate/guards.d.ts +28 -0
  10. package/dist/gate/guards.d.ts.map +1 -0
  11. package/dist/gate/guards.js +107 -0
  12. package/dist/gate/guards.js.map +1 -0
  13. package/dist/index.d.ts +3 -0
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +3 -0
  16. package/dist/index.js.map +1 -1
  17. package/dist/linter/design-contract.d.ts +17 -1
  18. package/dist/linter/design-contract.d.ts.map +1 -1
  19. package/dist/linter/design-contract.js +61 -3
  20. package/dist/linter/design-contract.js.map +1 -1
  21. package/dist/linter/index.d.ts.map +1 -1
  22. package/dist/linter/index.js +628 -372
  23. package/dist/linter/index.js.map +1 -1
  24. package/dist/linter/rule-metadata.d.ts.map +1 -1
  25. package/dist/linter/rule-metadata.js +19 -0
  26. package/dist/linter/rule-metadata.js.map +1 -1
  27. package/dist/linter/source-scan.d.ts.map +1 -1
  28. package/dist/linter/source-scan.js +32 -21
  29. package/dist/linter/source-scan.js.map +1 -1
  30. package/dist/linter/types.d.ts +10 -1
  31. package/dist/linter/types.d.ts.map +1 -1
  32. package/dist/linter/types.js +13 -0
  33. package/dist/linter/types.js.map +1 -1
  34. package/dist/looks/deal.d.ts +42 -0
  35. package/dist/looks/deal.d.ts.map +1 -0
  36. package/dist/looks/deal.js +126 -0
  37. package/dist/looks/deal.js.map +1 -0
  38. package/dist/looks/index.d.ts +21 -0
  39. package/dist/looks/index.d.ts.map +1 -1
  40. package/dist/looks/index.js +5 -0
  41. package/dist/looks/index.js.map +1 -1
  42. package/dist/looks/material.d.ts +72 -0
  43. package/dist/looks/material.d.ts.map +1 -0
  44. package/dist/looks/material.js +223 -0
  45. package/dist/looks/material.js.map +1 -0
  46. package/package.json +1 -1
@@ -51,7 +51,20 @@ const advice = {
51
51
  UNBOUNDED_INFINITE_MOTION: 'Replace unbounded infinite loops ("repeat: Infinity", "loop: true") with caused, finite transitions that settle cleanly.',
52
52
  REDUCED_MOTION_BLINDNESS: 'Honor reduced-motion accessibility via useReducedMotion(), <MotionConfig reducedMotion="user">, or prefers-reduced-motion checks.',
53
53
  LAYOUT_THRASH_ANIMATION: 'Animate compositor-friendly transform (x, y, scale, rotate) and opacity instead of layout-thrashing width, height, top, left, margin, or padding.',
54
- UNMANAGED_WEBGL_OR_MEDIA_LOOP: 'Clean up WebGL/Lottie/scroll instances with .dispose()/.destroy() on unmount, and throttle R3F <Canvas> with frameloop="demand" and bounded dpr.'
54
+ UNMANAGED_WEBGL_OR_MEDIA_LOOP: 'Clean up WebGL/Lottie/scroll instances with .dispose()/.destroy() on unmount, and throttle R3F <Canvas> with frameloop="demand" and bounded dpr.',
55
+ TRANSITION_ALL_SLOP: 'Replace `transition: all` / `transition-all` with an explicit property list so layout and inherited properties never animate by accident.',
56
+ SLOW_INTERACTION_MOTION: 'Keep direct interaction feedback inside roughly 300ms; reserve longer durations for large surfaces or storytelling, not hovers and taps.',
57
+ SCROLL_REVEAL_SATURATION: 'Render first-screen content visible in HTML; if the page reveals on scroll, keep it to one restrained motif that works without JavaScript.',
58
+ AUTOPLAY_MOTION_WITHOUT_CONTROL: 'Add a visible keyboard-operable pause control to any motion that starts automatically and runs longer than five seconds.',
59
+ FLASHING_ANIMATION: 'Remove the flash or keep it below three flashes per second; rapid light-to-dark alternation risks seizures.',
60
+ SCALE_FROM_ZERO: 'Enter from 0.9-0.96 scale with opacity instead of scale(0), so the element reads as a real object rather than a pop-in.',
61
+ CSS_LOOP_NO_REDUCED_GUARD: 'Add an `@media (prefers-reduced-motion: reduce)` (or `motion-safe:`) fallback for CSS loops so the animation stops or simplifies.',
62
+ VESTIBULAR_RISK_MOTION: 'Guard parallax, 3D tilt, and large zoom with reduced motion and keep the moving area small; large-area motion can trigger vestibular symptoms.',
63
+ UNEARNED_HOVER_LIFT: 'Reserve hover lift and scale for real interactive controls; static cards should respond to content, not pretend to be clickable.',
64
+ UNIFORM_ENTRANCE_MOTION: 'Keep one restrained entrance motif per page; render static text and navigation visible instead of fading in four or more identical blocks.',
65
+ ELASTIC_UI_EASING: 'Use a plain ease-out for routine surfaces; keep overshoot easing for one small expressive icon, never a dialog or a whole card.',
66
+ WILL_CHANGE_LEAK: 'Set will-change just before a known animation and remove it after; leaving it on many elements creates layers and memory pressure.',
67
+ OFF_CONTRACT_MOTION: 'Use a duration from the motion scale declared in DESIGN.md, or update the contract first so the scale stays the source of truth.'
55
68
  };
56
69
  const BANNER_CHARS = new Set(['-', '=', '_', '*', '#', '~']);
57
70
  function isDividerBanner(trimmed) {
@@ -108,17 +121,35 @@ export function isAiNarrationComment(text) {
108
121
  return { isSlop: false };
109
122
  }
110
123
  const purple = '(?:purple|violet|indigo|fuchsia)';
124
+ const PURPLE_WORD_RE = /\b(?:purple|violet|indigo|fuchsia)\b/i;
125
+ const PURPLE_STOP_RE = /(?:from|via|to)-(?:purple|indigo|violet|fuchsia)(?:-|\b)|(?:from|via|to)-\[#/i;
126
+ const GRADIENT_BG_RE = /(?:bg-gradient-to-[\w-]+|bg-(?:radial|conic))/;
127
+ const ARBITRARY_GRADIENT_RE = /(?:bg-)?\[(?:linear|radial|conic)-gradient\([^\]]*\)\]/gi;
128
+ const HEX_COLOR_RE = /#([\da-f]{3}|[\da-f]{6})\b/ig;
129
+ const RGBA_COLOR_RE = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/ig;
130
+ const HSLA_COLOR_RE = /hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)%\s*,\s*(\d+(?:\.\d+)?)%/ig;
131
+ const SPACING_REGEXES = {
132
+ p: /^p-(\d+(?:\.\d+)?)$/,
133
+ px: /^px-(\d+(?:\.\d+)?)$/,
134
+ py: /^py-(\d+(?:\.\d+)?)$/
135
+ };
136
+ const CRITERIA_MAP = {
137
+ LOW_CONTRAST_GRAY: 'WCAG 1.4.3 Contrast (Minimum)',
138
+ FAKE_CONTROL_SLOP: 'WCAG 4.1.2 Name, Role, Value / 2.1.1 Keyboard',
139
+ SCROLL_HIJACKING: 'WCAG 2.1.1 Keyboard',
140
+ REDUCED_MOTION_BLINDNESS: 'WCAG 2.3.3 Animation from Interactions'
141
+ };
111
142
  function containsPurpleColor(value) {
112
- if (new RegExp(`\\b${purple}\\b`, 'i').test(value))
143
+ if (PURPLE_WORD_RE.test(value))
113
144
  return true;
114
145
  const colors = [];
115
- for (const m of value.matchAll(/#([\da-f]{3}|[\da-f]{6})\b/ig)) {
146
+ for (const m of value.matchAll(HEX_COLOR_RE)) {
116
147
  const raw = m[1].length === 3 ? [...m[1]].map(c => c + c).join('') : m[1];
117
148
  colors.push([0, 2, 4].map(i => parseInt(raw.slice(i, i + 2), 16)));
118
149
  }
119
- for (const m of value.matchAll(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/ig))
150
+ for (const m of value.matchAll(RGBA_COLOR_RE))
120
151
  colors.push([Number(m[1]), Number(m[2]), Number(m[3])]);
121
- for (const m of value.matchAll(/hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)%\s*,\s*(\d+(?:\.\d+)?)%/ig))
152
+ for (const m of value.matchAll(HSLA_COLOR_RE))
122
153
  if (Number(m[1]) % 360 >= 250 && Number(m[1]) % 360 <= 340 && Number(m[2]) > 12)
123
154
  return true;
124
155
  for (const rgb of colors) {
@@ -181,7 +212,11 @@ function color(token) {
181
212
  return base;
182
213
  }
183
214
  function has(tokens, re) { return tokens.some(t => re.test(t)); }
184
- function spacingAtLeastFour(token, prefix) { const match = token.match(new RegExp(`^${prefix}-(\\d+(?:\\.\\d+)?)$`)); return !!match && Number(match[1]) >= 4; }
215
+ function spacingAtLeastFour(token, prefix) {
216
+ const re = SPACING_REGEXES[prefix] ?? (SPACING_REGEXES[prefix] = new RegExp(`^${prefix}-(\\d+(?:\\.\\d+)?)$`));
217
+ const match = token.match(re);
218
+ return !!match && Number(match[1]) >= 4;
219
+ }
185
220
  function extractVisibleText(code, tags) {
186
221
  const spans = [];
187
222
  const parts = [];
@@ -247,8 +282,15 @@ function extractVisibleText(code, tags) {
247
282
  cursor = tag.end;
248
283
  }
249
284
  const offsetAt = (vIndex) => {
250
- for (const s of spans) {
251
- if (vIndex >= s.vStart && vIndex < s.vEnd)
285
+ let lo = 0, hi = spans.length - 1;
286
+ while (lo <= hi) {
287
+ const mid = (lo + hi) >>> 1;
288
+ const s = spans[mid];
289
+ if (vIndex < s.vStart)
290
+ hi = mid - 1;
291
+ else if (vIndex >= s.vEnd)
292
+ lo = mid + 1;
293
+ else
252
294
  return s.cStart + (vIndex - s.vStart);
253
295
  }
254
296
  return spans[0]?.cStart ?? 0;
@@ -291,12 +333,15 @@ export function auditCode(code, options = {}) {
291
333
  candidates.push({ type, severity: level ?? defaultLevel, at, message, evidence, context });
292
334
  };
293
335
  const selectorAt = (at) => {
294
- let found;
295
- for (const t of tags) {
296
- if (t.start <= at)
297
- found = t;
336
+ let lo = 0, hi = tags.length - 1, found;
337
+ while (lo <= hi) {
338
+ const mid = (lo + hi) >>> 1;
339
+ if (tags[mid].start <= at) {
340
+ found = tags[mid];
341
+ lo = mid + 1;
342
+ }
298
343
  else
299
- break;
344
+ hi = mid - 1;
300
345
  }
301
346
  if (!found)
302
347
  return undefined;
@@ -305,294 +350,306 @@ export function auditCode(code, options = {}) {
305
350
  };
306
351
  const tagClasses = tags.map(tag => ({ tag, tokens: classesFor(tag) }));
307
352
  const allowGradients = config?.brand?.allowGradients ?? false;
308
- // Gradient classes are grouped by element so gradient direction and stops can occur in any order.
309
- for (const { tag, tokens } of tagClasses) {
310
- const joined = tokens.join(' ');
311
- if (!allowGradients) {
312
- if (/(?:bg-gradient-to-[\w-]+|bg-(?:radial|conic))/.test(joined) && new RegExp(`(?:from|via|to)-${purple}(?:-|\\b)|(?:from|via|to)-\\[#`, 'i').test(joined) && containsPurpleColor(joined))
313
- push('PURPLE_GRADIENT_SLOP', tag.start, 'Purple-family gradient stop detected.');
314
- const arbitrary = joined.match(/(?:bg-)?\[(?:linear|radial|conic)-gradient\([^\]]*\)\]/gi);
315
- if (arbitrary?.some(containsPurpleColor))
316
- push('PURPLE_GRADIENT_SLOP', tag.start, 'Arbitrary gradient contains a purple-family color.');
317
- for (const attrName of ['style']) {
318
- const attr = tag.attributes.get(attrName);
319
- if (attr && /(?:linear|radial|conic)-gradient\(/i.test(attr.value) && containsPurpleColor(attr.value))
320
- push('PURPLE_GRADIENT_SLOP', attr.valueStart, 'Inline gradient contains a purple-family color.');
353
+ const designContract = options.designContract ?? resolveDesignContract(options.filepath, config);
354
+ let wordCount = 0;
355
+ if (!options.codeOnly) {
356
+ // Gradient classes are grouped by element so gradient direction and stops can occur in any order.
357
+ for (const { tag, tokens } of tagClasses) {
358
+ const joined = tokens.join(' ');
359
+ if (!allowGradients) {
360
+ if (GRADIENT_BG_RE.test(joined) && PURPLE_STOP_RE.test(joined) && containsPurpleColor(joined))
361
+ push('PURPLE_GRADIENT_SLOP', tag.start, 'Purple-family gradient stop detected.');
362
+ const arbitrary = joined.match(ARBITRARY_GRADIENT_RE);
363
+ if (arbitrary?.some(containsPurpleColor))
364
+ push('PURPLE_GRADIENT_SLOP', tag.start, 'Arbitrary gradient contains a purple-family color.');
365
+ for (const attrName of ['style']) {
366
+ const attr = tag.attributes.get(attrName);
367
+ if (attr && /(?:linear|radial|conic)-gradient\(/i.test(attr.value) && containsPurpleColor(attr.value))
368
+ push('PURPLE_GRADIENT_SLOP', attr.valueStart, 'Inline gradient contains a purple-family color.');
369
+ }
321
370
  }
322
- }
323
- if (tokens.includes('bg-clip-text') && (tokens.includes('text-transparent') || joined.includes('text-transparent'))) {
324
- if (joined.includes('bg-gradient-') || joined.includes('bg-linear-') || (joined.includes('from-') && joined.includes('to-'))) {
325
- push('HERO_GRADIENT_TEXT', tag.start, 'Hero gradient text (bg-clip-text with text-transparent and gradient) detected.');
371
+ if (tokens.includes('bg-clip-text') && (tokens.includes('text-transparent') || joined.includes('text-transparent'))) {
372
+ if (joined.includes('bg-gradient-') || joined.includes('bg-linear-') || (joined.includes('from-') && joined.includes('to-'))) {
373
+ push('HERO_GRADIENT_TEXT', tag.start, 'Hero gradient text (bg-clip-text with text-transparent and gradient) detected.');
374
+ }
375
+ }
376
+ const animation = tokens.find(t => /^(?:animate-(?:bounce|pulse|ping|spin)|animate-\[[^\]]+\])$/.test(t) && (/^animate-(?:bounce|pulse|ping|spin)$/.test(t) || /infinite|\b(?:infinite|alternate)\b/i.test(t)));
377
+ if (animation) {
378
+ const tagText = code.slice(tag.start, tag.end);
379
+ const signal = /Spinner|Loader|Loading|Skeleton|Shimmer|Placeholder|Progress/i.test(tag.name + ' ' + tokens.join(' ')) || /\brole\s*=\s*["'](?:status|progressbar)["']|\baria-busy(?:\s*=|\s|\/|>)/i.test(tagText);
380
+ const ancestors = ancestorsOf(tag).filter(x => /\baria-live\s*=/.test(code.slice(x.start, x.end)) || /\brole\s*=\s*["'](?:status|progressbar)["']|\baria-busy(?:\s*=|\s|\/|>)/i.test(code.slice(x.start, x.end)));
381
+ if (!signal && ancestors.length === 0)
382
+ push('UNEARNED_ANIMATION', tag.start, `Unearned looping animation "${animation}" detected.`);
326
383
  }
327
384
  }
328
- const animation = tokens.find(t => /^(?:animate-(?:bounce|pulse|ping|spin)|animate-\[[^\]]+\])$/.test(t) && (/^animate-(?:bounce|pulse|ping|spin)$/.test(t) || /infinite|\b(?:infinite|alternate)\b/i.test(t)));
329
- if (animation) {
330
- const tagText = code.slice(tag.start, tag.end);
331
- const signal = /Spinner|Loader|Loading|Skeleton|Shimmer|Placeholder|Progress/i.test(tag.name + ' ' + tokens.join(' ')) || /\brole\s*=\s*["'](?:status|progressbar)["']|\baria-busy(?:\s*=|\s|\/|>)/i.test(tagText);
332
- const ancestors = ancestorsOf(tag).filter(x => /\baria-live\s*=/.test(code.slice(x.start, x.end)) || /\brole\s*=\s*["'](?:status|progressbar)["']|\baria-busy(?:\s*=|\s|\/|>)/i.test(code.slice(x.start, x.end)));
333
- if (!signal && ancestors.length === 0)
334
- push('UNEARNED_ANIMATION', tag.start, `Unearned looping animation "${animation}" detected.`);
335
- }
336
- }
337
- const importAliases = new Map();
338
- let impPos = 0;
339
- while ((impPos = code.indexOf('import', impPos)) >= 0) {
340
- const prev = impPos > 0 ? code[impPos - 1] : '\n';
341
- const next = code[impPos + 6] || '';
342
- impPos += 6;
343
- if (/[A-Za-z0-9_$]/.test(prev) || (next && !/\s|\{/.test(next)))
344
- continue;
345
- const openBrace = code.indexOf('{', impPos);
346
- const semi = code.indexOf(';', impPos);
347
- if (openBrace < 0 || (semi >= 0 && semi < openBrace))
348
- continue;
349
- const closeBrace = code.indexOf('}', openBrace + 1);
350
- if (closeBrace < 0)
351
- break;
352
- const afterBrace = code.slice(closeBrace + 1, closeBrace + 80);
353
- if (/^\s*from\s*["'][^"'\n]+["']/.test(afterBrace)) {
354
- for (const part of code.slice(openBrace + 1, closeBrace).split(',')) {
355
- const asIdx = part.search(/\sas\s/);
356
- if (asIdx > 0) {
357
- const original = part.slice(0, asIdx).trim();
358
- const alias = part.slice(asIdx + 4).trim();
359
- if (original && alias)
360
- importAliases.set(alias, original);
385
+ const importAliases = new Map();
386
+ let impPos = 0;
387
+ while ((impPos = code.indexOf('import', impPos)) >= 0) {
388
+ const prev = impPos > 0 ? code[impPos - 1] : '\n';
389
+ const next = code[impPos + 6] || '';
390
+ impPos += 6;
391
+ if (/[A-Za-z0-9_$]/.test(prev) || (next && !/\s|\{/.test(next)))
392
+ continue;
393
+ const openBrace = code.indexOf('{', impPos);
394
+ const semi = code.indexOf(';', impPos);
395
+ if (openBrace < 0 || (semi >= 0 && semi < openBrace))
396
+ continue;
397
+ const closeBrace = code.indexOf('}', openBrace + 1);
398
+ if (closeBrace < 0)
399
+ break;
400
+ const afterBrace = code.slice(closeBrace + 1, closeBrace + 80);
401
+ if (/^\s*from\s*["'][^"'\n]+["']/.test(afterBrace)) {
402
+ for (const part of code.slice(openBrace + 1, closeBrace).split(',')) {
403
+ const asIdx = part.search(/\sas\s/);
404
+ if (asIdx > 0) {
405
+ const original = part.slice(0, asIdx).trim();
406
+ const alias = part.slice(asIdx + 4).trim();
407
+ if (original && alias)
408
+ importAliases.set(alias, original);
409
+ }
361
410
  }
362
411
  }
412
+ impPos = closeBrace + 1;
363
413
  }
364
- impPos = closeBrace + 1;
365
- }
366
- const iconNames = /^(?:Sparkles|LucideSparkles|Wand|MagicWand|Sparkle|IconSparkles|AiSparkle|SparkleIcon|MagicWand02)$/;
367
- for (const tag of tags)
368
- if (!tag.closing) {
369
- const base = tag.name.split('.').pop() || '';
370
- if (iconNames.test(base) || iconNames.test(importAliases.get(base) || ''))
371
- push('SPARKLE_ICON_OVERLOAD', tag.start, `Decorative sparkle or magic-wand component <${tag.name}> detected.`);
414
+ const iconNames = /^(?:Sparkles|LucideSparkles|Wand|MagicWand|Sparkle|IconSparkles|AiSparkle|SparkleIcon|MagicWand02)$/;
415
+ for (const tag of tags)
416
+ if (!tag.closing) {
417
+ const base = tag.name.split('.').pop() || '';
418
+ if (iconNames.test(base) || iconNames.test(importAliases.get(base) || ''))
419
+ push('SPARKLE_ICON_OVERLOAD', tag.start, `Decorative sparkle or magic-wand component <${tag.name}> detected.`);
420
+ }
421
+ const { text: visibleText, offsetAt } = extractVisibleText(code, scan.tags);
422
+ const phrases = /Powered\s+by\s+AI|AI[- ]Powered|Smart\s+AI|Magical\s+AI|AI\s+Assistant|AI\s+Generated|Generate\s+with\s+AI|Supercharge\b[^.\n]{0,50}\bAI\b|\u{2728}/igu;
423
+ let phrase;
424
+ while ((phrase = phrases.exec(visibleText))) {
425
+ push('MADE_UP_AI_BADGE', offsetAt(phrase.index), `Made-up AI marketing phrase "${phrase[0]}" detected.`);
372
426
  }
373
- const { text: visibleText, offsetAt } = extractVisibleText(code, scan.tags);
374
- const phrases = /Powered\s+by\s+AI|AI[- ]Powered|Smart\s+AI|Magical\s+AI|AI\s+Assistant|AI\s+Generated|Generate\s+with\s+AI|Supercharge\b[^.\n]{0,50}\bAI\b|\u{2728}/igu;
375
- let phrase;
376
- while ((phrase = phrases.exec(visibleText))) {
377
- push('MADE_UP_AI_BADGE', offsetAt(phrase.index), `Made-up AI marketing phrase "${phrase[0]}" detected.`);
378
- }
379
- const cliches = /\b(?:Unlock\s+the\s+power\s+of|Supercharge\s+your\s+(?:workflow|productivity|team|growth)|Seamless(?:ly)?\s+(?:integrate|connect|automate)|10x\s+your\s+(?:productivity|growth|output)|Revolutionize\s+the\s+way)\b/igu;
380
- let clicheMatch;
381
- while ((clicheMatch = cliches.exec(visibleText))) {
382
- push('AI_COPY_CLICHE', offsetAt(clicheMatch.index), `Generic AI marketing cliché "${clicheMatch[0]}" detected.`);
383
- }
384
- const negativeParallelism = /\b(?:not\s+just\s+[^,.!?\n]{2,40}[,—-]\s*(?:it['’]s|but)\b|\bnot\s+a\s+[^,.!?\n]{2,30}[,—-]\s*it['’]s\b)/igu;
385
- let npMatch;
386
- while ((npMatch = negativeParallelism.exec(visibleText))) {
387
- push('NEGATIVE_PARALLELISM', offsetAt(npMatch.index), `Negative parallelism copy cliché ("${npMatch[0].trim()}") detected.`);
388
- }
389
- const socialProof = /\b(?:(?:(?:[1-9][0-9]{0,2}(?:,\d{3})+|\d+(?:\.\d+)?[kKMB])\+\s*(?:users?|customers?|teams?|companies|developers)|(?:99\.99?%|100%)\s*(?:uptime|guarantee)|Loved\s+by\s+(?:thousands|millions)|Rated\s+5(?:\.0)?\s*(?:\/|out\s+of)\s*5\s*stars?))\b/igu;
390
- let spMatch;
391
- while ((spMatch = socialProof.exec(visibleText))) {
392
- push('FABRICATED_SOCIAL_PROOF', offsetAt(spMatch.index), `Fabricated social proof metric "${spMatch[0].trim()}" detected.`);
393
- }
394
- const chatbotPhrases = /\b(?:I\s+hope\s+this\s+helps[!.]?|In\s+conclusion,\s+|Overall,\s+(?:it|this)\s+|Let\s+me\s+know\s+if\s+you\s+(?:need|have)|It['’]s\s+important\s+to\s+note\s+that)\b/igu;
395
- let cbMatch;
396
- while ((cbMatch = chatbotPhrases.exec(visibleText))) {
397
- push('CHATBOT_SIGN_OFF_SLOP', offsetAt(cbMatch.index), `Leftover chatbot conversational phrasing "${cbMatch[0].trim()}" detected.`);
398
- }
399
- const loremIpsum = /\b(?:lorem\s+ipsum|dolor\s+sit\s+amet|consectetur\s+adipiscing|sed\s+do\s+eiusmod|john\s+doe|jane\s+doe)\b/igu;
400
- let liMatch;
401
- while ((liMatch = loremIpsum.exec(visibleText))) {
402
- push('LOREM_IPSUM_SLOP', offsetAt(liMatch.index), `Placeholder copy or filler name "${liMatch[0].trim()}" detected.`);
403
- }
404
- const emojiRegex = /\p{Emoji_Presentation}|\p{Emoji}\uFE0F/gu;
405
- let emojiMatch;
406
- while ((emojiMatch = emojiRegex.exec(visibleText))) {
407
- push('EMOJI_ICON_SLOP', offsetAt(emojiMatch.index), `Raw emoji "${emojiMatch[0]}" detected in UI text instead of an SVG icon.`);
408
- }
409
- for (const tag of tags) {
410
- const href = tag.attributes.get('href')?.value?.trim();
411
- if (href === '#' || href === 'javascript:void(0)') {
412
- push('DEAD_PLACEHOLDER_SLOP', tag.start, `Dead placeholder href="${href}" detected on <${tag.name}>.`);
427
+ const cliches = /\b(?:Unlock\s+the\s+power\s+of|Supercharge\s+your\s+(?:workflow|productivity|team|growth)|Seamless(?:ly)?\s+(?:integrate|connect|automate)|10x\s+your\s+(?:productivity|growth|output)|Revolutionize\s+the\s+way)\b/igu;
428
+ let clicheMatch;
429
+ while ((clicheMatch = cliches.exec(visibleText))) {
430
+ push('AI_COPY_CLICHE', offsetAt(clicheMatch.index), `Generic AI marketing cliché "${clicheMatch[0]}" detected.`);
413
431
  }
414
- const onClick = tag.attributes.get('onClick')?.value?.trim() || tag.attributes.get('onclick')?.value?.trim();
415
- if (onClick && /^\s*\(\s*\)\s*=>\s*\{\s*\}\s*$/.test(onClick)) {
416
- push('DEAD_PLACEHOLDER_SLOP', tag.start, 'Empty dead click handler onClick={() => {}} detected.');
432
+ const negativeParallelism = /\b(?:not\s+just\s+[^,.!?\n]{2,40}[,—-]\s*(?:it['’]s|but)\b|\bnot\s+a\s+[^,.!?\n]{2,30}[,—-]\s*it['’]s\b)/igu;
433
+ let npMatch;
434
+ while ((npMatch = negativeParallelism.exec(visibleText))) {
435
+ push('NEGATIVE_PARALLELISM', offsetAt(npMatch.index), `Negative parallelism copy cliché ("${npMatch[0].trim()}") detected.`);
417
436
  }
418
- }
419
- for (const tag of tags) {
420
- if (tag.name === 'div' || tag.name === 'span') {
421
- const hasOnClick = tag.attributes.has('onClick') || tag.attributes.has('onclick');
422
- if (hasOnClick) {
423
- const role = tag.attributes.get('role')?.value?.toLowerCase();
424
- const validRoles = ['button', 'tab', 'link', 'menuitem', 'option', 'switch', 'checkbox'];
425
- if (!role || !validRoles.includes(role)) {
426
- push('FAKE_CONTROL_SLOP', tag.start, `Inaccessible clickable <${tag.name}> lacks role="button" or keyboard accessibility.`);
427
- }
428
- }
437
+ const socialProof = /\b(?:(?:(?:[1-9][0-9]{0,2}(?:,\d{3})+|\d+(?:\.\d+)?[kKMB])\+\s*(?:users?|customers?|teams?|companies|developers)|(?:99\.99?%|100%)\s*(?:uptime|guarantee)|Loved\s+by\s+(?:thousands|millions)|Rated\s+5(?:\.0)?\s*(?:\/|out\s+of)\s*5\s*stars?))\b/igu;
438
+ let spMatch;
439
+ while ((spMatch = socialProof.exec(visibleText))) {
440
+ push('FABRICATED_SOCIAL_PROOF', offsetAt(spMatch.index), `Fabricated social proof metric "${spMatch[0].trim()}" detected.`);
429
441
  }
430
- }
431
- const cards = tagClasses.filter(({ tokens }) => has(tokens, /^rounded(?:-|$)/) && has(tokens, /^border(?:-|$)/) && (tokens.some(t => spacingAtLeastFour(t, 'p')) || (tokens.some(t => spacingAtLeastFour(t, 'px')) && tokens.some(t => spacingAtLeastFour(t, 'py')))) && (has(tokens, /^bg-/) || has(tokens, /^shadow-/)));
432
- if (cards.length >= (options.strict ? 3 : 4))
433
- push('BOXED_CARD_SYNDROME', cards[0].tag.start, `Found ${cards.length} repeated boxed card elements.`);
434
- for (const { tag, tokens } of tagClasses) {
435
- const frame = /^(Window|Mockup|BrowserWindow|DeviceFrame|PhoneFrame)$/.test(tag.name.split('.').pop() || '');
436
- const windowSurface = has(tokens, /^rounded(?:-|$)/) && has(tokens, /^shadow(?:-|$)/) && has(tokens, /^max-w-(?:xs|sm|md|lg|xl|[2-7]xl)$/);
437
- const generic = has(tokens, /^mx-auto$/) && has(tokens, /^my-[6-9](?:\b|$)/) && has(tokens, /^p-[6-9](?:\b|$)/) && windowSurface;
438
- const margin = has(tokens, /^m-[4-9](?:\b|$)/) || (has(tokens, /^my-[4-9]/) && has(tokens, /^mx-/)) || (has(tokens, /^mx-auto$/) && has(tokens, /^my-[4-9]/));
439
- const bleed = has(tokens, /^-m[xtb]-/) || tokens.includes('w-full') || tokens.includes('h-full') || tokens.includes('absolute') || has(tokens, /^inset-/) || has(tokens, /^rounded-t-/) || tokens.includes('overflow-hidden');
440
- if ((frame && margin && !bleed) || generic)
441
- push('UNANCHORED_FLOATING_WINDOW', tag.start, `Unanchored ${frame ? 'frame' : 'container'} has uniform outer spacing.`);
442
- }
443
- const layoutTags = tagClasses.filter(({ tokens }) => has(tokens, /^(?:flex|grid|inline-flex|inline-grid|items-|justify-|place-items-|text-center$|gap-|col-|row-)/));
444
- const centered = tagClasses.filter(({ tokens }) => has(tokens, /^(?:text-center|items-center|justify-center|place-items-center)$/));
445
- const hasLeadingEdge = tags.some(tag => has(getClasses(tag), /^(?:text-left|items-start|justify-start)$/));
446
- if (centered.length >= 8 && layoutTags.length > 0 && centered.length / layoutTags.length >= 0.75 && !hasLeadingEdge)
447
- push('CENTER_ALIGNED_EVERYTHING', centered[0].tag.start, `${centered.length} centered class occurrences span ${layoutTags.length} layout elements with no leading-edge anchor.`);
448
- for (const { tag, tokens } of tagClasses) {
449
- if (tag.name.toLowerCase() === 'svg' || /(?:icon|glyph)$/i.test(tag.name))
450
- continue;
451
- const fg = tokens.map(color).find((x, i) => x && tokens[i].startsWith('text-'));
452
- const hasOwnBackground = tokens.some(t => t.startsWith('bg-'));
453
- let bg = tokens.map(color).find((x, i) => x && tokens[i].startsWith('bg-'));
454
- // An unresolved own background (e.g. bg-emerald-500) must not be compared
455
- // against an ancestor surface; that produces a false contrast failure.
456
- if (fg && !bg && !hasOwnBackground)
457
- for (const ancestor of ancestorsOf(tag)) {
458
- const ancestorTokens = getClasses(ancestor);
459
- bg = ancestorTokens.map(color).find((x, i) => x && ancestorTokens[i].startsWith('bg-'));
460
- if (bg)
461
- break;
462
- }
463
- if (fg && bg) {
464
- const ratio = contrast(fg, bg);
465
- const isLarge = tokens.some(t => /text-(?:lg|xl|[2-9]xl)/.test(t) || (t === 'font-bold' && tokens.includes('text-base')));
466
- const minRatio = isLarge ? 3 : 4.5;
467
- if (ratio < minRatio)
468
- push('LOW_CONTRAST_GRAY', tag.start, `Text and background contrast is ${ratio.toFixed(2)}:1 (minimum ${minRatio}:1 required under WCAG).`);
442
+ const chatbotPhrases = /\b(?:I\s+hope\s+this\s+helps[!.]?|In\s+conclusion,\s+|Overall,\s+(?:it|this)\s+|Let\s+me\s+know\s+if\s+you\s+(?:need|have)|It['’]s\s+important\s+to\s+note\s+that)\b/igu;
443
+ let cbMatch;
444
+ while ((cbMatch = chatbotPhrases.exec(visibleText))) {
445
+ push('CHATBOT_SIGN_OFF_SLOP', offsetAt(cbMatch.index), `Leftover chatbot conversational phrasing "${cbMatch[0].trim()}" detected.`);
469
446
  }
470
- }
471
- // Repeated sibling-like tags are approximated by contiguous repeated opening tags with matching surface tokens.
472
- const surfaces = new Map();
473
- for (const { tag, tokens } of tagClasses) {
474
- const bg = tokens.find(t => /^bg-/.test(t)), border = tokens.filter(t => /^border(?:-|$)/.test(t)).join(' '), rounded = tokens.filter(t => /^rounded(?:-|$)/.test(t)).join(' '), shadow = tokens.filter(t => /^shadow(?:-|$)/.test(t)).join(' '), parentKey = parent.get(tag)?.start ?? -1;
475
- if (bg && (border || rounded)) {
476
- const key = `${parentKey}|${bg}|${border}|${rounded}|${shadow}`;
477
- surfaces.set(key, [...(surfaces.get(key) || []), tag]);
447
+ const loremIpsum = /\b(?:lorem\s+ipsum|dolor\s+sit\s+amet|consectetur\s+adipiscing|sed\s+do\s+eiusmod|john\s+doe|jane\s+doe)\b/igu;
448
+ let liMatch;
449
+ while ((liMatch = loremIpsum.exec(visibleText))) {
450
+ push('LOREM_IPSUM_SLOP', offsetAt(liMatch.index), `Placeholder copy or filler name "${liMatch[0].trim()}" detected.`);
478
451
  }
479
- }
480
- for (const group of surfaces.values())
481
- if (group.length >= 4) {
482
- push('FLAT_SURFACE_MONOTONY', group[0].start, `${group.length} elements repeat the same background, border, and rounding without an elevation step.`);
483
- break;
452
+ const emojiRegex = /\p{Emoji_Presentation}|\p{Emoji}\uFE0F/gu;
453
+ let emojiMatch;
454
+ while ((emojiMatch = emojiRegex.exec(visibleText))) {
455
+ push('EMOJI_ICON_SLOP', offsetAt(emojiMatch.index), `Raw emoji "${emojiMatch[0]}" detected in UI text instead of an SVG icon.`);
484
456
  }
485
- // Gen-2 defaults: the "anti-slop" palette swap. Detect-only, because the fix is
486
- // a brand decision declared in DESIGN.md, not a mechanical rewrite.
487
- const designContract = options.designContract ?? resolveDesignContract(options.filepath, config);
488
- const hasDarkGround = tagClasses.some(({ tokens }) => tokens.some(t => /^bg-(?:black|neutral-(?:900|950)|slate-(?:900|950)|zinc-(?:900|950)|stone-(?:900|950)|gray-(?:900|950))$/.test(t) || /^bg-\[#0[0-9a-f]{5}\]$/i.test(t)));
489
- if (!declaredAccentAllows(designContract, 'emerald') && !(config?.brand?.allowColors || []).some(c => /^(?:emerald|green|teal|lime)$/i.test(c))) {
490
- const emerald = tagClasses.flatMap(({ tag, tokens }) => tokens
491
- .filter(t => /(?:^|:)(?:bg|text|border|ring|from|via|to|fill|stroke|outline|decoration)-emerald-\d{3}(?:\/\d+)?$/.test(t))
492
- .map(token => ({ tag, token })));
493
- if (hasDarkGround && emerald.length)
494
- push('EMERALD_MONOCULTURE', emerald[0].tag.start, `Gen-2 emerald accent "${emerald[0].token}" on a dark ground with no declared brand token.`);
495
- }
496
- const blurCap = designContract.blurCap ?? config?.design?.blurCap ?? DEFAULT_BLUR_CAP;
497
- const blurElements = tagClasses.filter(({ tokens }) => tokens.some(t => /^backdrop-blur(?:-|$)/.test(t)));
498
- if (blurElements.length > blurCap)
499
- push('BLUR_OVERUSE', blurElements[blurCap].tag.start, `${blurElements.length} elements use backdrop-blur (cap ${blurCap}); glass is being used as the default surface.`);
500
- const glowPattern = /^(?:shadow|drop-shadow)-(?:emerald|green|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose|red|orange|amber|yellow|lime)(?:-\d{3})?(?:\/\d+)?$/;
501
- const glow = tagClasses.flatMap(({ tag, tokens }) => tokens.filter(t => glowPattern.test(t) || /^drop-shadow-\[.*(?:#[0-9a-f]{3,8}|rgba?\()/i.test(t)).map(token => ({ tag, token })));
502
- if (glow.length)
503
- push('GLOW_SHADOW', glow[0].tag.start, `Colored glow shadow "${glow[0].token}" detected; colored ambient glow is a Gen-1/Gen-2 default.`);
504
- // CPY-02: a pulsing green dot claiming live status without any telemetry binding.
505
- const claimsLiveStatus = /\b(?:all\s+systems\s+operational|systems?\s+operational|currently\s+live|live\s+status)\b/i.test(visibleText);
506
- const pulsingDot = tagClasses.some(({ tokens }) => tokens.some(t => /^animate-(?:pulse|ping)$/.test(t)) && tokens.some(t => /^(?:bg|from|fill)-(?:emerald|green)-\d{3}$/.test(t)));
507
- const wiredToTelemetry = /\b(?:fetch\(|useSWR|useQuery|statusUrl|statusUri|healthz|health-check|\/api\/(?:status|health))\b/i.test(code);
508
- if (claimsLiveStatus && pulsingDot && !wiredToTelemetry)
509
- push('STATUS_DOT_SLOP', tagClasses.find(({ tokens }) => tokens.includes('animate-pulse') || tokens.includes('animate-ping'))?.tag.start ?? tags[0]?.start ?? 0, 'Pulsing status dot claims live operational status but no health endpoint or telemetry binding exists.');
510
- // CPY-05: formulaic prose tics. Each sub-signal is reported at most once.
511
- const emDashCount = (visibleText.match(/[—–]/g) || []).length;
512
- const firstDash = visibleText.match(/[—–]/);
513
- if (emDashCount >= 3 && firstDash)
514
- push('AI_PROSE_FILLER', offsetAt(firstDash.index ?? 0), `${emDashCount} em/en dashes in visible copy; use commas or parentheses where they belong.`);
515
- const adjectiveTriplet = /\b(?:innovative|transformative|groundbreaking|cutting-edge|revolutionary|seamless|powerful|intuitive|scalable|robust)\b\s*,\s*(?:innovative|transformative|groundbreaking|cutting-edge|revolutionary|seamless|powerful|intuitive|scalable|robust)\b\s*,\s*and\s+(?:innovative|transformative|groundbreaking|cutting-edge|revolutionary|seamless|powerful|intuitive|scalable|robust)\b/iu;
516
- const tripletMatch = visibleText.match(adjectiveTriplet);
517
- if (tripletMatch)
518
- push('AI_PROSE_FILLER', offsetAt(tripletMatch.index ?? 0), `Adjective triplet "${tripletMatch[0]}" detected.`);
519
- const falseRange = visibleText.match(/\branging\s+from\s+[^.\n]{2,40}\s+to\s+[^.\n]{2,40}/iu);
520
- if (falseRange)
521
- push('AI_PROSE_FILLER', offsetAt(falseRange.index ?? 0), `Formulaic false range "${falseRange[0].trim()}" detected.`);
522
- const vagueAttribution = visibleText.match(/\b(?:studies|research|experts|industry\s+reports?)\s+(?:show|shows|suggest|suggests|say|says|indicate|indicates)\b/iu);
523
- if (vagueAttribution)
524
- push('AI_PROSE_FILLER', offsetAt(vagueAttribution.index ?? 0), `Vague attribution "${vagueAttribution[0]}" detected.`);
525
- const spelledMetric = visibleText.match(/\b(?:across|for|with|in)\s+(?:three|four|five|six|seven|eight|nine|ten)\s+(?:tools|teams|steps|platforms|workflows|minutes|seconds)\b/iu);
526
- if (spelledMetric)
527
- push('AI_PROSE_FILLER', offsetAt(spelledMetric.index ?? 0), `Spelled-out metric "${spelledMetric[0]}" detected; use numerals in UI copy.`);
528
- const lockedColors = new Set();
529
- for (const token of designContract.lockedTokens) {
530
- for (const match of token.matchAll(/#([0-9a-f]{3}|[0-9a-f]{6})\b/gi)) {
531
- const hex = match[1].toLowerCase();
532
- lockedColors.add(hex.length === 3 ? hex.split('').map((c) => c + c).join('') : hex);
457
+ for (const tag of tags) {
458
+ const href = tag.attributes.get('href')?.value?.trim();
459
+ if (href === '#' || href === 'javascript:void(0)') {
460
+ push('DEAD_PLACEHOLDER_SLOP', tag.start, `Dead placeholder href="${href}" detected on <${tag.name}>.`);
461
+ }
462
+ const onClick = tag.attributes.get('onClick')?.value?.trim() || tag.attributes.get('onclick')?.value?.trim();
463
+ if (onClick && /^\s*\(\s*\)\s*=>\s*\{\s*\}\s*$/.test(onClick)) {
464
+ push('DEAD_PLACEHOLDER_SLOP', tag.start, 'Empty dead click handler onClick={() => {}} detected.');
465
+ }
533
466
  }
534
- }
535
- for (const { tag, tokens } of tagClasses) {
536
- if (lockedColors.size) {
537
- const colorSource = [...tokens, tag.attributes.get('style')?.value || ''].join(' ');
538
- for (const match of colorSource.matchAll(/#([0-9a-f]{3}|[0-9a-f]{6})\b/gi)) {
539
- const raw = match[1].toLowerCase();
540
- const hex = raw.length === 3 ? raw.split('').map((c) => c + c).join('') : raw;
541
- if (!lockedColors.has(hex)) {
542
- push('DESIGN_TOKEN_DRIFT', tag.start, `Off-contract color "#${raw}" is not in the DESIGN.md palette (${[...lockedColors].map((c) => `#${c}`).join(', ')}).`);
543
- break;
467
+ for (const tag of tags) {
468
+ if (tag.name === 'div' || tag.name === 'span') {
469
+ const hasOnClick = tag.attributes.has('onClick') || tag.attributes.has('onclick');
470
+ if (hasOnClick) {
471
+ const role = tag.attributes.get('role')?.value?.toLowerCase();
472
+ const validRoles = ['button', 'tab', 'link', 'menuitem', 'option', 'switch', 'checkbox'];
473
+ if (!role || !validRoles.includes(role)) {
474
+ push('FAKE_CONTROL_SLOP', tag.start, `Inaccessible clickable <${tag.name}> lacks role="button" or keyboard accessibility.`);
475
+ }
544
476
  }
545
477
  }
546
478
  }
547
- const extremeZ = tokens.find(t => /^z-(?:\[?(?:999+|1000+|99999)\]?)$/.test(t) || /^z-\[\d{4,}\]/.test(t));
548
- if (extremeZ) {
549
- push('Z_INDEX_CHAOS', tag.start, `Arbitrary escalated z-index "${extremeZ}" detected instead of disciplined stacking tokens.`);
479
+ const cards = tagClasses.filter(({ tokens }) => has(tokens, /^rounded(?:-|$)/) && has(tokens, /^border(?:-|$)/) && (tokens.some(t => spacingAtLeastFour(t, 'p')) || (tokens.some(t => spacingAtLeastFour(t, 'px')) && tokens.some(t => spacingAtLeastFour(t, 'py')))) && (has(tokens, /^bg-/) || has(tokens, /^shadow-/)));
480
+ if (cards.length >= (options.strict ? 3 : 4))
481
+ push('BOXED_CARD_SYNDROME', cards[0].tag.start, `Found ${cards.length} repeated boxed card elements.`);
482
+ for (const { tag, tokens } of tagClasses) {
483
+ const frame = /^(Window|Mockup|BrowserWindow|DeviceFrame|PhoneFrame)$/.test(tag.name.split('.').pop() || '');
484
+ const windowSurface = has(tokens, /^rounded(?:-|$)/) && has(tokens, /^shadow(?:-|$)/) && has(tokens, /^max-w-(?:xs|sm|md|lg|xl|[2-7]xl)$/);
485
+ const generic = has(tokens, /^mx-auto$/) && has(tokens, /^my-[6-9](?:\b|$)/) && has(tokens, /^p-[6-9](?:\b|$)/) && windowSurface;
486
+ const margin = has(tokens, /^m-[4-9](?:\b|$)/) || (has(tokens, /^my-[4-9]/) && has(tokens, /^mx-/)) || (has(tokens, /^mx-auto$/) && has(tokens, /^my-[4-9]/));
487
+ const bleed = has(tokens, /^-m[xtb]-/) || tokens.includes('w-full') || tokens.includes('h-full') || tokens.includes('absolute') || has(tokens, /^inset-/) || has(tokens, /^rounded-t-/) || tokens.includes('overflow-hidden');
488
+ if ((frame && margin && !bleed) || generic)
489
+ push('UNANCHORED_FLOATING_WINDOW', tag.start, `Unanchored ${frame ? 'frame' : 'container'} has uniform outer spacing.`);
550
490
  }
551
- const styleAttr = tag.attributes.get('style')?.value;
552
- if (styleAttr && /zIndex\s*:\s*(?:9999|99999|10000)/i.test(styleAttr)) {
553
- push('Z_INDEX_CHAOS', tag.start, 'Arbitrary high z-index in inline style detected.');
491
+ const layoutTags = tagClasses.filter(({ tokens }) => has(tokens, /^(?:flex|grid|inline-flex|inline-grid|items-|justify-|place-items-|text-center$|gap-|col-|row-)/));
492
+ const centered = tagClasses.filter(({ tokens }) => has(tokens, /^(?:text-center|items-center|justify-center|place-items-center)$/));
493
+ const hasLeadingEdge = tags.some(tag => has(getClasses(tag), /^(?:text-left|items-start|justify-start)$/));
494
+ if (centered.length >= 8 && layoutTags.length > 0 && centered.length / layoutTags.length >= 0.75 && !hasLeadingEdge)
495
+ push('CENTER_ALIGNED_EVERYTHING', centered[0].tag.start, `${centered.length} centered class occurrences span ${layoutTags.length} layout elements with no leading-edge anchor.`);
496
+ for (const { tag, tokens } of tagClasses) {
497
+ if (tag.name.toLowerCase() === 'svg' || /(?:icon|glyph)$/i.test(tag.name))
498
+ continue;
499
+ const fg = tokens.map(color).find((x, i) => x && tokens[i].startsWith('text-'));
500
+ const hasOwnBackground = tokens.some(t => t.startsWith('bg-'));
501
+ let bg = tokens.map(color).find((x, i) => x && tokens[i].startsWith('bg-'));
502
+ // An unresolved own background (e.g. bg-emerald-500) must not be compared
503
+ // against an ancestor surface; that produces a false contrast failure.
504
+ if (fg && !bg && !hasOwnBackground)
505
+ for (const ancestor of ancestorsOf(tag)) {
506
+ const ancestorTokens = getClasses(ancestor);
507
+ bg = ancestorTokens.map(color).find((x, i) => x && ancestorTokens[i].startsWith('bg-'));
508
+ if (bg)
509
+ break;
510
+ }
511
+ if (fg && bg) {
512
+ const ratio = contrast(fg, bg);
513
+ const isLarge = tokens.some(t => /text-(?:lg|xl|[2-9]xl)/.test(t) || (t === 'font-bold' && tokens.includes('text-base')));
514
+ const minRatio = isLarge ? 3 : 4.5;
515
+ if (ratio < minRatio)
516
+ push('LOW_CONTRAST_GRAY', tag.start, `Text and background contrast is ${ratio.toFixed(2)}:1 (minimum ${minRatio}:1 required under WCAG).`);
517
+ }
554
518
  }
555
- }
556
- for (const tag of tags) {
557
- if (tag.name === 'html' || tag.name === 'body') {
558
- const tokens = getClasses(tag);
559
- if (tokens.includes('overflow-hidden')) {
560
- push('SCROLL_HIJACKING', tag.start, `Global overflow-hidden lock on <${tag.name}> disrupts native page scrolling.`);
519
+ // Repeated sibling-like tags are approximated by contiguous repeated opening tags with matching surface tokens.
520
+ const surfaces = new Map();
521
+ for (const { tag, tokens } of tagClasses) {
522
+ const bg = tokens.find(t => /^bg-/.test(t)), border = tokens.filter(t => /^border(?:-|$)/.test(t)).join(' '), rounded = tokens.filter(t => /^rounded(?:-|$)/.test(t)).join(' '), shadow = tokens.filter(t => /^shadow(?:-|$)/.test(t)).join(' '), parentKey = parent.get(tag)?.start ?? -1;
523
+ if (bg && (border || rounded)) {
524
+ const key = `${parentKey}|${bg}|${border}|${rounded}|${shadow}`;
525
+ surfaces.set(key, [...(surfaces.get(key) || []), tag]);
526
+ }
527
+ }
528
+ for (const group of surfaces.values())
529
+ if (group.length >= 4) {
530
+ push('FLAT_SURFACE_MONOTONY', group[0].start, `${group.length} elements repeat the same background, border, and rounding without an elevation step.`);
531
+ break;
561
532
  }
533
+ // Gen-2 defaults: the "anti-slop" palette swap. Detect-only, because the fix is
534
+ // a brand decision declared in DESIGN.md, not a mechanical rewrite.
535
+ const hasDarkGround = tagClasses.some(({ tokens }) => tokens.some(t => /^bg-(?:black|neutral-(?:900|950)|slate-(?:900|950)|zinc-(?:900|950)|stone-(?:900|950)|gray-(?:900|950))$/.test(t) || /^bg-\[#0[0-9a-f]{5}\]$/i.test(t)));
536
+ if (!declaredAccentAllows(designContract, 'emerald') && !(config?.brand?.allowColors || []).some(c => /^(?:emerald|green|teal|lime)$/i.test(c))) {
537
+ const emerald = tagClasses.flatMap(({ tag, tokens }) => tokens
538
+ .filter(t => /(?:^|:)(?:bg|text|border|ring|from|via|to|fill|stroke|outline|decoration)-emerald-\d{3}(?:\/\d+)?$/.test(t))
539
+ .map(token => ({ tag, token })));
540
+ if (hasDarkGround && emerald.length)
541
+ push('EMERALD_MONOCULTURE', emerald[0].tag.start, `Gen-2 emerald accent "${emerald[0].token}" on a dark ground with no declared brand token.`);
562
542
  }
563
- if (tag.attributes.has('onWheel') || tag.attributes.has('onwheel')) {
564
- push('SCROLL_HIJACKING', tag.start, 'Custom onWheel handler detected; risk of scroll hijacking or wheel interference.');
543
+ const blurCap = designContract.blurCap ?? config?.design?.blurCap ?? DEFAULT_BLUR_CAP;
544
+ const blurElements = tagClasses.filter(({ tokens }) => tokens.some(t => /^backdrop-blur(?:-|$)/.test(t)));
545
+ if (blurElements.length > blurCap)
546
+ push('BLUR_OVERUSE', blurElements[blurCap].tag.start, `${blurElements.length} elements use backdrop-blur (cap ${blurCap}); glass is being used as the default surface.`);
547
+ const glowPattern = /^(?:shadow|drop-shadow)-(?:emerald|green|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose|red|orange|amber|yellow|lime)(?:-\d{3})?(?:\/\d+)?$/;
548
+ const glow = tagClasses.flatMap(({ tag, tokens }) => tokens.filter(t => glowPattern.test(t) || /^drop-shadow-\[.*(?:#[0-9a-f]{3,8}|rgba?\()/i.test(t)).map(token => ({ tag, token })));
549
+ if (glow.length)
550
+ push('GLOW_SHADOW', glow[0].tag.start, `Colored glow shadow "${glow[0].token}" detected; colored ambient glow is a Gen-1/Gen-2 default.`);
551
+ // CPY-02: a pulsing green dot claiming live status without any telemetry binding.
552
+ const claimsLiveStatus = /\b(?:all\s+systems\s+operational|systems?\s+operational|currently\s+live|live\s+status)\b/i.test(visibleText);
553
+ const pulsingDot = tagClasses.some(({ tokens }) => tokens.some(t => /^animate-(?:pulse|ping)$/.test(t)) && tokens.some(t => /^(?:bg|from|fill)-(?:emerald|green)-\d{3}$/.test(t)));
554
+ const wiredToTelemetry = /\b(?:fetch\(|useSWR|useQuery|statusUrl|statusUri|healthz|health-check|\/api\/(?:status|health))\b/i.test(code);
555
+ if (claimsLiveStatus && pulsingDot && !wiredToTelemetry)
556
+ push('STATUS_DOT_SLOP', tagClasses.find(({ tokens }) => tokens.includes('animate-pulse') || tokens.includes('animate-ping'))?.tag.start ?? tags[0]?.start ?? 0, 'Pulsing status dot claims live operational status but no health endpoint or telemetry binding exists.');
557
+ // CPY-05: formulaic prose tics. Each sub-signal is reported at most once.
558
+ const emDashCount = (visibleText.match(/[—–]/g) || []).length;
559
+ const firstDash = visibleText.match(/[—–]/);
560
+ if (emDashCount >= 3 && firstDash)
561
+ push('AI_PROSE_FILLER', offsetAt(firstDash.index ?? 0), `${emDashCount} em/en dashes in visible copy; use commas or parentheses where they belong.`);
562
+ const adjectiveTriplet = /\b(?:innovative|transformative|groundbreaking|cutting-edge|revolutionary|seamless|powerful|intuitive|scalable|robust)\b\s*,\s*(?:innovative|transformative|groundbreaking|cutting-edge|revolutionary|seamless|powerful|intuitive|scalable|robust)\b\s*,\s*and\s+(?:innovative|transformative|groundbreaking|cutting-edge|revolutionary|seamless|powerful|intuitive|scalable|robust)\b/iu;
563
+ const tripletMatch = visibleText.match(adjectiveTriplet);
564
+ if (tripletMatch)
565
+ push('AI_PROSE_FILLER', offsetAt(tripletMatch.index ?? 0), `Adjective triplet "${tripletMatch[0]}" detected.`);
566
+ const falseRange = visibleText.match(/\branging\s+from\s+[^.\n]{2,40}\s+to\s+[^.\n]{2,40}/iu);
567
+ if (falseRange)
568
+ push('AI_PROSE_FILLER', offsetAt(falseRange.index ?? 0), `Formulaic false range "${falseRange[0].trim()}" detected.`);
569
+ const vagueAttribution = visibleText.match(/\b(?:studies|research|experts|industry\s+reports?)\s+(?:show|shows|suggest|suggests|say|says|indicate|indicates)\b/iu);
570
+ if (vagueAttribution)
571
+ push('AI_PROSE_FILLER', offsetAt(vagueAttribution.index ?? 0), `Vague attribution "${vagueAttribution[0]}" detected.`);
572
+ const spelledMetric = visibleText.match(/\b(?:across|for|with|in)\s+(?:three|four|five|six|seven|eight|nine|ten)\s+(?:tools|teams|steps|platforms|workflows|minutes|seconds)\b/iu);
573
+ if (spelledMetric)
574
+ push('AI_PROSE_FILLER', offsetAt(spelledMetric.index ?? 0), `Spelled-out metric "${spelledMetric[0]}" detected; use numerals in UI copy.`);
575
+ const lockedColors = new Set();
576
+ for (const token of designContract.lockedTokens) {
577
+ for (const match of token.matchAll(/#([0-9a-f]{3}|[0-9a-f]{6})\b/gi)) {
578
+ const hex = match[1].toLowerCase();
579
+ lockedColors.add(hex.length === 3 ? hex.split('').map((c) => c + c).join('') : hex);
580
+ }
565
581
  }
566
- }
567
- // CSS and inline declaration text; comments are excluded using the scanner mask, while tag values retain authored strings.
568
- if (!allowGradients) {
569
- const gradientRe = /(?:linear|radial|conic)-gradient\(/gi;
570
- let gm;
571
- while ((gm = gradientRe.exec(scan.masked))) {
572
- const at = gm.index;
573
- let depth = 1, p = at + gm[0].length;
574
- while (p < scan.masked.length && depth > 0) {
575
- if (scan.masked[p] === '(')
576
- depth++;
577
- else if (scan.masked[p] === ')')
578
- depth--;
579
- p++;
582
+ for (const { tag, tokens } of tagClasses) {
583
+ if (lockedColors.size) {
584
+ const colorSource = [...tokens, tag.attributes.get('style')?.value || ''].join(' ');
585
+ for (const match of colorSource.matchAll(/#([0-9a-f]{3}|[0-9a-f]{6})\b/gi)) {
586
+ const raw = match[1].toLowerCase();
587
+ const hex = raw.length === 3 ? raw.split('').map((c) => c + c).join('') : raw;
588
+ if (!lockedColors.has(hex)) {
589
+ push('DESIGN_TOKEN_DRIFT', tag.start, `Off-contract color "#${raw}" is not in the DESIGN.md palette (${[...lockedColors].map((c) => `#${c}`).join(', ')}).`);
590
+ break;
591
+ }
592
+ }
593
+ }
594
+ const extremeZ = tokens.find(t => /^z-(?:\[?(?:999+|1000+|99999)\]?)$/.test(t) || /^z-\[\d{4,}\]/.test(t));
595
+ if (extremeZ) {
596
+ push('Z_INDEX_CHAOS', tag.start, `Arbitrary escalated z-index "${extremeZ}" detected instead of disciplined stacking tokens.`);
580
597
  }
581
- const expr = scan.masked.slice(at, p);
582
- if (containsPurpleColor(expr) && !candidates.some(v => v.type === 'PURPLE_GRADIENT_SLOP' && Math.abs(v.at - at) < 120)) {
583
- push('PURPLE_GRADIENT_SLOP', at, 'CSS gradient contains a purple-family color.');
598
+ const styleAttr = tag.attributes.get('style')?.value;
599
+ if (styleAttr && /zIndex\s*:\s*(?:9999|99999|10000)/i.test(styleAttr)) {
600
+ push('Z_INDEX_CHAOS', tag.start, 'Arbitrary high z-index in inline style detected.');
601
+ }
602
+ }
603
+ for (const tag of tags) {
604
+ if (tag.name === 'html' || tag.name === 'body') {
605
+ const tokens = getClasses(tag);
606
+ if (tokens.includes('overflow-hidden')) {
607
+ push('SCROLL_HIJACKING', tag.start, `Global overflow-hidden lock on <${tag.name}> disrupts native page scrolling.`);
608
+ }
609
+ }
610
+ if (tag.attributes.has('onWheel') || tag.attributes.has('onwheel')) {
611
+ push('SCROLL_HIJACKING', tag.start, 'Custom onWheel handler detected; risk of scroll hijacking or wheel interference.');
612
+ }
613
+ }
614
+ // CSS and inline declaration text; comments are excluded using the scanner mask, while tag values retain authored strings.
615
+ if (!allowGradients) {
616
+ const gradientRe = /(?:linear|radial|conic)-gradient\(/gi;
617
+ let gm;
618
+ while ((gm = gradientRe.exec(scan.masked))) {
619
+ const at = gm.index;
620
+ let depth = 1, p = at + gm[0].length;
621
+ while (p < scan.masked.length && depth > 0) {
622
+ if (scan.masked[p] === '(')
623
+ depth++;
624
+ else if (scan.masked[p] === ')')
625
+ depth--;
626
+ p++;
627
+ }
628
+ const expr = scan.masked.slice(at, p);
629
+ if (containsPurpleColor(expr) && !candidates.some(v => v.type === 'PURPLE_GRADIENT_SLOP' && Math.abs(v.at - at) < 120)) {
630
+ push('PURPLE_GRADIENT_SLOP', at, 'CSS gradient contains a purple-family color.');
631
+ }
632
+ gradientRe.lastIndex = p;
584
633
  }
585
- gradientRe.lastIndex = p;
586
634
  }
635
+ const text = visibleText;
636
+ wordCount = (text.match(/[\p{L}\p{N}]+(?:['’][\p{L}]+)?/gu) || []).length;
637
+ const limits = { illustration: 12, 'feature-card': 18, hero: 32, application: 150, bento: 40 };
638
+ const configuredBudget = config?.wordBudget?.[options.componentType || 'default'];
639
+ const threshold = configuredBudget ?? (options.componentType ? limits[options.componentType] : (config?.wordBudget?.default ?? 60));
640
+ if (wordCount > threshold && !tags.some(tag => /^(?:Bar|Skeleton|Placeholder)$/.test(tag.name.split('.').pop() || '')))
641
+ push('WORD_BUDGET_EXCEEDED', tags[0]?.start ?? 0, `Visible word budget exceeded: ${wordCount} words, limit ${threshold}.`);
587
642
  }
588
- const text = visibleText;
589
- const wordCount = (text.match(/[\p{L}\p{N}]+(?:['’][\p{L}]+)?/gu) || []).length;
590
- const limits = { illustration: 12, 'feature-card': 18, hero: 32, application: 150, bento: 40 };
591
- const configuredBudget = config?.wordBudget?.[options.componentType || 'default'];
592
- const threshold = configuredBudget ?? (options.componentType ? limits[options.componentType] : (config?.wordBudget?.default ?? 60));
593
- if (wordCount > threshold && !tags.some(tag => /^(?:Bar|Skeleton|Placeholder)$/.test(tag.name.split('.').pop() || '')))
594
- push('WORD_BUDGET_EXCEEDED', tags[0]?.start ?? 0, `Visible word budget exceeded: ${wordCount} words, limit ${threshold}.`);
595
643
  const allComments = scan.comments.map(c => ({ ...c, line: sourceLocation(scan, c.at).line }));
644
+ const commentsByLine = new Map();
645
+ for (const c of allComments) {
646
+ let list = commentsByLine.get(c.line);
647
+ if (!list) {
648
+ list = [];
649
+ commentsByLine.set(c.line, list);
650
+ }
651
+ list.push(c);
652
+ }
596
653
  // COD-01: AI narration comments and decorative section divider banners
597
654
  for (const comment of allComments) {
598
655
  const check = isAiNarrationComment(comment.text);
@@ -601,20 +658,22 @@ export function auditCode(code, options = {}) {
601
658
  }
602
659
  }
603
660
  // LIV-01: Sterile surface and missing liveliness check
604
- const interactiveControls = tags.filter(t => t.name === 'button' || (t.name === 'a' && t.attributes.has('href')));
605
- const hasStylesheetImport = /\bimport\s+['"][^'"]+\.(?:css|scss|sass|less)['"]/.test(code);
606
- if (interactiveControls.length >= 2) {
607
- const hasMicroInteractions = interactiveControls.some(ctrl => {
608
- const tokens = getClasses(ctrl);
609
- if (tokens.some(t => /^(?:hover:|focus:|focus-visible:|active:|transition-|duration-|ease-|group-hover:)/.test(t)))
610
- return true;
611
- const styleVal = ctrl.attributes.get('style')?.value || '';
612
- if (/\b(?:transition|animation)\s*:/.test(styleVal))
613
- return true;
614
- return hasStylesheetImport && tokens.some(t => /^[a-z]+-[a-z0-9_-]+$/.test(t) && !/^(?:px|py|p|mx|my|m|bg|text|rounded|border|flex|grid|w|h)-/.test(t));
615
- });
616
- if (!hasMicroInteractions) {
617
- push('STERILE_SURFACE_SLOP', interactiveControls[0].start, 'Interactive controls lack hover, focus, or transition affordances, creating a sterile interface.');
661
+ if (!options.codeOnly) {
662
+ const interactiveControls = tags.filter(t => t.name === 'button' || (t.name === 'a' && t.attributes.has('href')));
663
+ const hasStylesheetImport = /\bimport\s+['"][^'"]+\.(?:css|scss|sass|less)['"]/.test(code);
664
+ if (interactiveControls.length >= 2) {
665
+ const hasMicroInteractions = interactiveControls.some(ctrl => {
666
+ const tokens = getClasses(ctrl);
667
+ if (tokens.some(t => /^(?:hover:|focus:|focus-visible:|active:|transition-|duration-|ease-|group-hover:)/.test(t)))
668
+ return true;
669
+ const styleVal = ctrl.attributes.get('style')?.value || '';
670
+ if (/\b(?:transition|animation)\s*:/.test(styleVal))
671
+ return true;
672
+ return hasStylesheetImport && tokens.some(t => /^[a-z]+-[a-z0-9_-]+$/.test(t) && !/^(?:px|py|p|mx|my|m|bg|text|rounded|border|flex|grid|w|h)-/.test(t));
673
+ });
674
+ if (!hasMicroInteractions) {
675
+ push('STERILE_SURFACE_SLOP', interactiveControls[0].start, 'Interactive controls lack hover, focus, or transition affordances, creating a sterile interface.');
676
+ }
618
677
  }
619
678
  }
620
679
  // COD-02: Chained type assertions (as unknown as T, as any as T)
@@ -682,77 +741,279 @@ export function auditCode(code, options = {}) {
682
741
  const at = match.index ?? 0;
683
742
  push('NON_NULL_ASSERTION_SLOP', at, `Unsafe non-null assertion ("${match[0]}") detected; use optional chaining or defensive guard.`);
684
743
  }
685
- // MOT-02: Unbounded infinite programmatic motion (Motion, Anime, Tween, Lottie, Rive, Magic UI)
686
- const isLoaderNear = (at) => /Spinner|Loader|Loading|Skeleton|Shimmer|Progress/i.test(code.slice(Math.max(0, at - 140), at + 140));
687
- for (const match of scan.masked.matchAll(/\brepeat\s*:\s*Infinity\b|\.repeat\s*\(\s*Infinity\s*\)/g)) {
688
- const at = match.index ?? 0;
689
- if (!isLoaderNear(at)) {
690
- push('UNBOUNDED_INFINITE_MOTION', at, `Unbounded infinite motion ("${match[0].trim()}") detected; animations should settle cleanly after a visible cause.`);
744
+ // MOT-02..MOT-18: Motion rules (skipped when codeOnly is true)
745
+ if (!options.codeOnly) {
746
+ // MOT-02: Unbounded infinite programmatic motion (Motion, Anime, Tween, Lottie, Rive, Magic UI)
747
+ const isLoaderNear = (at) => /Spinner|Loader|Loading|Skeleton|Shimmer|Progress/i.test(code.slice(Math.max(0, at - 140), at + 140));
748
+ for (const match of scan.masked.matchAll(/\brepeat\s*:\s*Infinity\b|\.repeat\s*\(\s*Infinity\s*\)/g)) {
749
+ const at = match.index ?? 0;
750
+ if (!isLoaderNear(at)) {
751
+ push('UNBOUNDED_INFINITE_MOTION', at, `Unbounded infinite motion ("${match[0].trim()}") detected; animations should settle cleanly after a visible cause.`);
752
+ }
691
753
  }
692
- }
693
- for (const match of scan.masked.matchAll(/\b(?:anime|lottie\.loadAnimation|new\s+(?:DotLottie|Rive))\s*\(\s*\{[^}]*\bloop\s*:\s*true\b/g)) {
694
- const at = match.index ?? 0;
695
- if (!isLoaderNear(at)) {
696
- push('UNBOUNDED_INFINITE_MOTION', at, 'Infinite programmatic loop ("loop: true") detected; bind playback to user state or hold after payoff.');
754
+ for (const match of scan.masked.matchAll(/\b(?:anime|lottie\.loadAnimation|new\s+(?:DotLottie|Rive))\s*\(\s*\{[^}]*\bloop\s*:\s*true\b/g)) {
755
+ const at = match.index ?? 0;
756
+ if (!isLoaderNear(at)) {
757
+ push('UNBOUNDED_INFINITE_MOTION', at, 'Infinite programmatic loop ("loop: true") detected; bind playback to user state or hold after payoff.');
758
+ }
697
759
  }
698
- }
699
- for (const tag of tags) {
700
- if (/^(?:DotLottieReact|Lottie)$/.test(tag.name) && tag.attributes.has('loop')) {
701
- const loopVal = tag.attributes.get('loop')?.value?.trim();
702
- if (!loopVal || loopVal === 'true') {
703
- push('UNBOUNDED_INFINITE_MOTION', tag.start, `<${tag.name} loop> runs indefinitely; trigger playback from an explicit interaction or finite state.`);
760
+ for (const tag of tags) {
761
+ if (/^(?:DotLottieReact|Lottie)$/.test(tag.name) && tag.attributes.has('loop')) {
762
+ const loopVal = tag.attributes.get('loop')?.value?.trim();
763
+ if (!loopVal || loopVal === 'true') {
764
+ push('UNBOUNDED_INFINITE_MOTION', tag.start, `<${tag.name} loop> runs indefinitely; trigger playback from an explicit interaction or finite state.`);
765
+ }
704
766
  }
705
767
  }
706
- }
707
- // MOT-03: Missing reduced-motion safeguard when active runtime motion/scroll/3D/Lottie libraries are invoked
708
- const runtimeMotionImport = /\bfrom\s+['"](?:motion(?:\/react)?|framer-motion|animejs|@react-spring\/[^'"]+|@formkit\/auto-animate|@tweenjs\/tween\.js|@theatre\/core|lenis|@studio-freight\/lenis|aos|rellax|lax\.js|atropos|splitting|vivus|three|@react-three\/fiber|pixi\.js|lottie-web|@lottiefiles\/dotlottie-(?:web|react)|@rive-app\/[^'"]+)['"]/.exec(code);
709
- const runtimeMotionCall = /<motion\.[a-z]+|\banime\s*\(|\buseSpring\s*\(|\buseAutoAnimate\s*\(|\bnew\s+(?:Lenis|Rellax|Vivus|THREE\.WebGLRenderer|PIXI\.Application|DotLottie|Rive)\b|\bAOS\.init\s*\(|\blax\.init\s*\(|\bSplitting\s*\(|<Canvas\b|\blottie\.loadAnimation\s*\(|\buseRive\s*\(|<DotLottieReact\b|<Atropos\b/.exec(code);
710
- if (runtimeMotionImport && runtimeMotionCall) {
711
- const hasReducedMotionGuard = /\b(?:useReducedMotion|MotionConfig|reducedMotion|prefers-reduced-motion|matchMedia)\b/.test(code);
712
- if (!hasReducedMotionGuard) {
713
- push('REDUCED_MOTION_BLINDNESS', runtimeMotionCall.index ?? runtimeMotionImport.index ?? 0, 'Active runtime animation/WebGL library used without a reduced-motion guard (useReducedMotion, MotionConfig, or prefers-reduced-motion).');
768
+ // MOT-03: Missing reduced-motion safeguard when active runtime motion/scroll/3D/Lottie libraries are invoked
769
+ const runtimeMotionImport = /\bfrom\s+['"](?:motion(?:\/react)?|framer-motion|animejs|@react-spring\/[^'"]+|@formkit\/auto-animate|@tweenjs\/tween\.js|@theatre\/core|lenis|@studio-freight\/lenis|aos|rellax|lax\.js|atropos|splitting|vivus|three|@react-three\/fiber|pixi\.js|lottie-web|@lottiefiles\/dotlottie-(?:web|react)|@rive-app\/[^'"]+)['"]/.exec(code);
770
+ const runtimeMotionCall = /<motion\.[a-z]+|\banime\s*\(|\buseSpring\s*\(|\buseAutoAnimate\s*\(|\bnew\s+(?:Lenis|Rellax|Vivus|THREE\.WebGLRenderer|PIXI\.Application|DotLottie|Rive)\b|\bAOS\.init\s*\(|\blax\.init\s*\(|\bSplitting\s*\(|<Canvas\b|\blottie\.loadAnimation\s*\(|\buseRive\s*\(|<DotLottieReact\b|<Atropos\b/.exec(code);
771
+ if (runtimeMotionImport && runtimeMotionCall) {
772
+ const hasReducedMotionGuard = /\b(?:useReducedMotion|MotionConfig|reducedMotion|prefers-reduced-motion|matchMedia)\b/.test(code);
773
+ if (!hasReducedMotionGuard) {
774
+ push('REDUCED_MOTION_BLINDNESS', runtimeMotionCall.index ?? runtimeMotionImport.index ?? 0, 'Active runtime animation/WebGL library used without a reduced-motion guard (useReducedMotion, MotionConfig, or prefers-reduced-motion).');
775
+ }
714
776
  }
715
- }
716
- // MOT-04: Layout-thrashing geometric animation (width/height/top/left/margin/padding)
717
- const layoutPropRe = /\b(?:width|height|top|left|right|bottom|margin(?:Top|Left|Right|Bottom)?|padding(?:Top|Left|Right|Bottom)?)\s*:/;
718
- const nonHeightLayoutPropRe = /\b(?:width|top|left|right|bottom|margin(?:Top|Left|Right|Bottom)?|padding(?:Top|Left|Right|Bottom)?)\s*:/;
719
- const layoutThrashMsg = 'Animating geometric layout properties triggers reflow thrashing; prefer transform (x, y, scale) and opacity.';
720
- const isPureAutoHeight = (expr, rawExpr) => /\bheight\s*:\s*['"]auto['"]/.test(rawExpr) && !nonHeightLayoutPropRe.test(expr);
721
- for (const tag of scan.tags) {
722
- for (const propName of ['animate', 'whileHover', 'whileTap', 'exit']) {
723
- const attr = tag.attributes.get(propName);
724
- if (!attr || !layoutPropRe.test(attr.value))
777
+ // MOT-04: Layout-thrashing geometric animation (width/height/top/left/margin/padding)
778
+ const layoutPropRe = /\b(?:width|height|top|left|right|bottom|margin(?:Top|Left|Right|Bottom)?|padding(?:Top|Left|Right|Bottom)?)\s*:/;
779
+ const nonHeightLayoutPropRe = /\b(?:width|top|left|right|bottom|margin(?:Top|Left|Right|Bottom)?|padding(?:Top|Left|Right|Bottom)?)\s*:/;
780
+ const layoutThrashMsg = 'Animating geometric layout properties triggers reflow thrashing; prefer transform (x, y, scale) and opacity.';
781
+ const isPureAutoHeight = (expr, rawExpr) => /\bheight\s*:\s*['"]auto['"]/.test(rawExpr) && !nonHeightLayoutPropRe.test(expr);
782
+ for (const tag of scan.tags) {
783
+ for (const propName of ['animate', 'whileHover', 'whileTap', 'exit']) {
784
+ const attr = tag.attributes.get(propName);
785
+ if (!attr || !layoutPropRe.test(attr.value))
786
+ continue;
787
+ const rawExpr = code.slice(attr.valueStart, attr.valueStart + attr.value.length);
788
+ if (isPureAutoHeight(attr.value, rawExpr))
789
+ continue;
790
+ push('LAYOUT_THRASH_ANIMATION', attr.valueStart, layoutThrashMsg);
791
+ }
792
+ }
793
+ for (const match of scan.masked.matchAll(/\banime\s*\(\s*\{[^}]*\b(?:width|height|top|left|right|bottom|margin(?:Top|Left|Right|Bottom)?|padding(?:Top|Left|Right|Bottom)?)\s*:/g)) {
794
+ const at = match.index ?? 0;
795
+ const rawSlice = code.slice(at, at + match[0].length + 24);
796
+ if (isPureAutoHeight(match[0], rawSlice))
725
797
  continue;
726
- const rawExpr = code.slice(attr.valueStart, attr.valueStart + attr.value.length);
727
- if (isPureAutoHeight(attr.value, rawExpr))
798
+ push('LAYOUT_THRASH_ANIMATION', at, layoutThrashMsg);
799
+ }
800
+ // MOT-05: Unmanaged WebGL, Lottie, or Smooth Scroll lifecycle / frame throttling
801
+ for (const tag of tags) {
802
+ if (tag.name === 'Canvas' && /\bfrom\s+['"]@react-three\/fiber['"]/.test(code)) {
803
+ const hasFrameloop = tag.attributes.has('frameloop');
804
+ const hasDpr = tag.attributes.has('dpr');
805
+ if (!hasFrameloop && !hasDpr) {
806
+ push('UNMANAGED_WEBGL_OR_MEDIA_LOOP', tag.start, 'React Three Fiber <Canvas> runs an unthrottled 60fps loop with unbounded DPR; set frameloop="demand" and/or dpr={[1, 2]}.');
807
+ }
808
+ }
809
+ }
810
+ const unmanagedInstance = /\b(?:new\s+(?:THREE\.WebGLRenderer|PIXI\.Application|DotLottie|Rive|Lenis|Rellax|Vivus)|lottie\.loadAnimation)\s*\(/.exec(scan.masked);
811
+ if (unmanagedInstance) {
812
+ const hasCleanup = /\.(?:dispose|destroy|cleanup|kill)\s*\(|\bcancelAnimationFrame\s*\(/.test(scan.masked);
813
+ if (!hasCleanup) {
814
+ push('UNMANAGED_WEBGL_OR_MEDIA_LOOP', unmanagedInstance.index ?? 0, `Imperative animation/WebGL instance ("${unmanagedInstance[0].trim()}") lacks .dispose()/.destroy() cleanup.`);
815
+ }
816
+ }
817
+ // MOT-06: Cross-property transition (transition: all / transition-all)
818
+ const transitionAllMessage = 'Cross-property transition ("transition: all") animates unknown properties and can drag layout with it.';
819
+ for (const match of scan.masked.matchAll(/\btransition(?:-property)?\s*:\s*all\b/gi)) {
820
+ push('TRANSITION_ALL_SLOP', match.index ?? 0, transitionAllMessage);
821
+ }
822
+ for (const match of code.matchAll(/\btransition(?:-property)?\s*:\s*['"`]\s*all\b/gi)) {
823
+ push('TRANSITION_ALL_SLOP', match.index ?? 0, transitionAllMessage);
824
+ }
825
+ for (const { tag, tokens } of tagClasses) {
826
+ if (tokens.includes('transition-all'))
827
+ push('TRANSITION_ALL_SLOP', tag.start, transitionAllMessage);
828
+ const styleAttr = tag.attributes.get('style');
829
+ if (styleAttr && /\btransition(?:-property)?\s*:\s*all\b/i.test(styleAttr.value))
830
+ push('TRANSITION_ALL_SLOP', styleAttr.valueStart, transitionAllMessage);
831
+ }
832
+ // MOT-07: Slow interaction feedback (above the declared ceiling, 600ms by default).
833
+ const motionContract = designContract.motion;
834
+ const feedbackCeilingMs = motionContract?.maxFeedback ?? 600;
835
+ const INTERACTIVE_TAGS = new Set(['a', 'button', 'input', 'select', 'textarea', 'summary', 'label', 'option']);
836
+ const hasInteractionVariant = (tokens) => tokens.some(t => /^(?:hover|active|focus|focus-visible|focus-within|group-hover|peer-hover|group-active):/.test(t));
837
+ const durationMs = (token) => {
838
+ const match = token.match(/(?:^|:)duration-(\d+|\[[^\]]+\])$/);
839
+ if (!match)
840
+ return null;
841
+ if (match[1].startsWith('[')) {
842
+ const raw = match[1].slice(1, -1);
843
+ const value = Number.parseFloat(raw);
844
+ return /ms$/.test(raw) ? value : Number.isFinite(value) ? value * 1000 : null;
845
+ }
846
+ const value = Number(match[1]);
847
+ return value >= 1 && value <= 30 ? value * 1000 : value;
848
+ };
849
+ for (const { tag, tokens } of tagClasses) {
850
+ const slow = tokens.find(t => { const ms = durationMs(t); return ms !== null && ms >= feedbackCeilingMs; });
851
+ if (!slow)
728
852
  continue;
729
- push('LAYOUT_THRASH_ANIMATION', attr.valueStart, layoutThrashMsg);
853
+ if (INTERACTIVE_TAGS.has(tag.name) || hasInteractionVariant(tokens) || tag.attributes.has('onClick')) {
854
+ push('SLOW_INTERACTION_MOTION', tag.start, `Slow interaction feedback ("${slow}") keeps a direct response from feeling immediate; the declared ceiling is ${feedbackCeilingMs}ms.`);
855
+ }
730
856
  }
731
- }
732
- for (const match of scan.masked.matchAll(/\banime\s*\(\s*\{[^}]*\b(?:width|height|top|left|right|bottom|margin(?:Top|Left|Right|Bottom)?|padding(?:Top|Left|Right|Bottom)?)\s*:/g)) {
733
- const at = match.index ?? 0;
734
- const rawSlice = code.slice(at, at + match[0].length + 24);
735
- if (isPureAutoHeight(match[0], rawSlice))
736
- continue;
737
- push('LAYOUT_THRASH_ANIMATION', at, layoutThrashMsg);
738
- }
739
- // MOT-05: Unmanaged WebGL, Lottie, or Smooth Scroll lifecycle / frame throttling
740
- for (const tag of tags) {
741
- if (tag.name === 'Canvas' && /\bfrom\s+['"]@react-three\/fiber['"]/.test(code)) {
742
- const hasFrameloop = tag.attributes.has('frameloop');
743
- const hasDpr = tag.attributes.has('dpr');
744
- if (!hasFrameloop && !hasDpr) {
745
- push('UNMANAGED_WEBGL_OR_MEDIA_LOOP', tag.start, 'React Three Fiber <Canvas> runs an unthrottled 60fps loop with unbounded DPR; set frameloop="demand" and/or dpr={[1, 2]}.');
857
+ // MOT-08: Scroll-reveal saturation: repeated whileInView/AOS reveals hide first-screen content until JS runs
858
+ const whileInViewCount = [...code.matchAll(/\bwhileInView\b/g)].length;
859
+ const aosSignal = /\bdata-aos\b|\bAOS\.init\s*\(/.test(code);
860
+ const observerReveal = /\buseInView\s*\(|\bIntersectionObserver\b/.test(code) && /\binitial\s*=\s*\{\{[^}]*\bopacity\s*:\s*0\b/.test(code);
861
+ const revealHasReducedGuard = /prefers-reduced-motion|useReducedMotion|MotionConfig|reducedMotion/.test(code);
862
+ if (!revealHasReducedGuard) {
863
+ if (whileInViewCount >= 2 || aosSignal) {
864
+ const at = code.search(/\bwhileInView\b|\bdata-aos\b|\bAOS\.init\s*\(/);
865
+ push('SCROLL_REVEAL_SATURATION', Math.max(0, at), `Scroll-reveal saturation (${whileInViewCount >= 2 ? `${whileInViewCount} whileInView reveals` : 'AOS reveals'}) hides content until JavaScript runs.`);
866
+ }
867
+ else if (observerReveal) {
868
+ push('SCROLL_REVEAL_SATURATION', Math.max(0, code.search(/\buseInView\s*\(|\bIntersectionObserver\b/)), 'Scroll-triggered reveal starts from opacity 0 and hides content until the observer runs.');
746
869
  }
747
870
  }
748
- }
749
- const unmanagedInstance = /\b(?:new\s+(?:THREE\.WebGLRenderer|PIXI\.Application|DotLottie|Rive|Lenis|Rellax|Vivus)|lottie\.loadAnimation)\s*\(/.exec(scan.masked);
750
- if (unmanagedInstance) {
751
- const hasCleanup = /\.(?:dispose|destroy|cleanup|kill)\s*\(|\bcancelAnimationFrame\s*\(/.test(scan.masked);
752
- if (!hasCleanup) {
753
- push('UNMANAGED_WEBGL_OR_MEDIA_LOOP', unmanagedInstance.index ?? 0, `Imperative animation/WebGL instance ("${unmanagedInstance[0].trim()}") lacks .dispose()/.destroy() cleanup.`);
871
+ // MOT-09: Autoplay motion without a pause control (WCAG 2.2.2 Pause, Stop, Hide)
872
+ const hasPauseControl = /(?:aria-label|title|alt)\s*=\s*["'][^"']*\bpause\b|\bpauseOnHover\b|\btogglePause\b|\bisPaused\b|animationPlayState|<button[^>]*>\s*Pause\b/i.test(code);
873
+ if (!hasPauseControl) {
874
+ for (const tag of tags) {
875
+ const classes = classesFor(tag).join(' ');
876
+ const raw = code.slice(tag.start, tag.end);
877
+ const marqueeClass = /(?:^|[\s:])(?:animate-(?:marquee|ticker)|marquee|ticker)\b/i.test(classes);
878
+ const isMarquee = tag.name === 'marquee' || marqueeClass || /\bdata-marquee\b/.test(raw);
879
+ const autoplayVideo = tag.name === 'video' && /\b(?:autoPlay|autoplay)\b/.test(raw) && /\bloop\b/.test(raw) && !/\bcontrols\b/.test(raw);
880
+ if (isMarquee)
881
+ push('AUTOPLAY_MOTION_WITHOUT_CONTROL', tag.start, 'Automatically running marquee/ticker motion offers no pause control; WCAG 2.2.2 requires one for motion over five seconds.');
882
+ else if (autoplayVideo)
883
+ push('AUTOPLAY_MOTION_WITHOUT_CONTROL', tag.start, 'Looping autoplay video offers no pause control; WCAG 2.2.2 requires one for motion over five seconds.');
884
+ }
885
+ if (/\bautoplay\s*=\s*\{\{/.test(code) && /\bloop\b/.test(code)) {
886
+ push('AUTOPLAY_MOTION_WITHOUT_CONTROL', Math.max(0, code.search(/\bautoplay\s*=\s*\{\{/)), 'Carousel autoplay with looping slides has no pause control; add a keyboard-operable pause (WCAG 2.2.2).');
887
+ }
754
888
  }
755
- }
889
+ // MOT-10: Flashing or strobe animation (WCAG 2.3.1 Three Flashes or Below Threshold)
890
+ const flashKeyframes = /@keyframes\s+(?:blink|flash|strobe)\b/i.exec(scan.masked);
891
+ const flashAnimation = /\banimation(?:-name)?\s*:\s*['"]?(?:blink|flash|strobe)\b/i.exec(scan.masked);
892
+ const flashToken = tags.find(tag => classesFor(tag).some(token => /^animate-\[[^\]]*(?:blink|flash|strobe)/i.test(token)));
893
+ if (flashKeyframes || flashAnimation || flashToken) {
894
+ const at = flashKeyframes?.index ?? flashAnimation?.index ?? flashToken?.start ?? 0;
895
+ push('FLASHING_ANIMATION', at, 'Flashing or strobe animation detected; rapid light-to-dark alternation risks seizures (WCAG 2.3.1).');
896
+ }
897
+ // MOT-11: Entrance from scale(0)
898
+ for (const tag of tags) {
899
+ const initial = tag.attributes.get('initial');
900
+ if (initial && /\bscale\s*:\s*0(?:\s*[,}])/.test(initial.value)) {
901
+ push('SCALE_FROM_ZERO', initial.valueStart, 'Entrance starts at scale(0); begin at 0.9-0.96 so the element reads as a shape, not a pop-in.');
902
+ }
903
+ }
904
+ const keyframeScaleZero = /@keyframes[^{]*\{(?:[^{}]|\{[^{}]*\})*?\bfrom\s*\{[^}]*scale\(\s*0(?:\s*,\s*0)?\s*\)/i.exec(scan.masked);
905
+ if (keyframeScaleZero)
906
+ push('SCALE_FROM_ZERO', keyframeScaleZero.index ?? 0, 'Entrance keyframe starts at scale(0); begin at 0.9-0.96 to avoid a pop-in.');
907
+ for (const { tag, tokens } of tagClasses) {
908
+ if (!tokens.includes('scale-0'))
909
+ continue;
910
+ if (tokens.some(t => /^(?:hover|group-hover|active|focus):|^animate-|^transition|^duration-/.test(t))) {
911
+ push('SCALE_FROM_ZERO', tag.start, 'Animated state starts at scale(0); begin at 0.9-0.96 so the element reads as a shape.');
912
+ }
913
+ }
914
+ // MOT-12: CSS loop without a reduced-motion guard
915
+ const progressAffordance = /\brole\s*=\s*["'](?:status|progressbar)["']|\baria-busy\b|Spinner|Loader|Loading|Skeleton/.test(code);
916
+ const cssInfinite = /\binfinite\b/.test(scan.masked) && (/@keyframes\b/.test(scan.masked) || /\banimation(?:-name)?\s*:/.test(scan.masked));
917
+ const tailwindLoop = tags.some(tag => classesFor(tag).some(t => /^animate-(?:bounce|pulse|ping|spin)$|^animate-\[[^\]]*infinite/.test(t)));
918
+ const hasReducedGuard = /prefers-reduced-motion|useReducedMotion|MotionConfig|reducedMotion|motion-safe:|motion-reduce:/.test(code);
919
+ if (!hasReducedGuard && !progressAffordance && (cssInfinite || tailwindLoop)) {
920
+ push('CSS_LOOP_NO_REDUCED_GUARD', Math.max(0, code.search(/@keyframes\b|\banimate-|\banimation(?:-name)?\s*:/)), 'Looping CSS animation has no prefers-reduced-motion fallback; add an @media (prefers-reduced-motion: reduce) or motion-safe guard.');
921
+ }
922
+ // MOT-13: Vestibular-risk parallax, background attachment, or 3D tilt (WCAG 2.3.3)
923
+ const parallaxSignal = /\bbackground-attachment\s*:\s*fixed\b|\bbg-fixed\b|\bdata-parallax\b|\bparallax\b/i.exec(code);
924
+ if (parallaxSignal)
925
+ push('VESTIBULAR_RISK_MOTION', parallaxSignal.index ?? 0, 'Full-area parallax or fixed background motion can trigger vestibular symptoms; keep it subtle, small, and reduced-motion guarded (WCAG 2.3.3).');
926
+ for (const { tag, tokens } of tagClasses) {
927
+ const joined = tokens.join(' ');
928
+ const tiltToken = tokens.some(t => /^(?:hover|group-hover|focus):rotate-[xy]-|^rotate-[xy]-\d+$/.test(t));
929
+ const perspective = tokens.some(t => /^perspective-|^transform-3d$|^transform-style-3d$/.test(t));
930
+ if (tiltToken && perspective) {
931
+ push('VESTIBULAR_RISK_MOTION', tag.start, '3D tilt on hover moves a large surface; guard it with reduced motion and keep the tilt small (WCAG 2.3.3).');
932
+ }
933
+ const styleAttr = tag.attributes.get('style');
934
+ if (styleAttr && /perspective\(/i.test(styleAttr.value) && /rotate[XY]\(/i.test(styleAttr.value)) {
935
+ push('VESTIBULAR_RISK_MOTION', styleAttr.valueStart, 'Inline 3D tilt can trigger vestibular symptoms; guard it with reduced motion (WCAG 2.3.3).');
936
+ }
937
+ if (/\bgroup-hover:-translate-[xy]-/.test(joined) && !INTERACTIVE_TAGS.has(tag.name)) {
938
+ push('VESTIBULAR_RISK_MOTION', tag.start, 'Group-hover travel moves a whole surface on hover; scope it to an interactive element and keep the distance small.');
939
+ }
940
+ }
941
+ // MOT-14: Hover lift/scale on a non-interactive surface
942
+ for (const { tag, tokens } of tagClasses) {
943
+ const lift = tokens.find(t => /^(?:hover|group-hover):-?translate-y-|^hover:scale-1(?:0[2-9]|[1-9]\d|[2-9]\d\d)$/.test(t));
944
+ if (!lift)
945
+ continue;
946
+ if (INTERACTIVE_TAGS.has(tag.name) || tag.attributes.has('onClick') || tag.attributes.has('role') || tag.attributes.has('href'))
947
+ continue;
948
+ const insideInteractive = ancestorsOf(tag).some(a => INTERACTIVE_TAGS.has(a.name) || a.attributes.has('onClick') || a.attributes.has('href'));
949
+ if (!insideInteractive) {
950
+ push('UNEARNED_HOVER_LIFT', tag.start, `Hover motion ("${lift}") on a non-interactive <${tag.name}> promises a click that never happens.`);
951
+ }
952
+ }
953
+ // MOT-15: Uniform entrance motion. One identical faded rise on four or more elements,
954
+ // or any mount animation on static reading content, is the page-builder default.
955
+ const READING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'nav']);
956
+ const startsHidden = (value) => /\bopacity\s*:\s*0(?:\.0+)?\b/.test(value);
957
+ const entrances = new Map();
958
+ let readingEntrance = null;
959
+ for (const tag of tags) {
960
+ const initial = tag.attributes.get('initial');
961
+ if (initial && startsHidden(initial.value) && READING_TAGS.has(tag.name.split('.').pop() || ''))
962
+ readingEntrance ??= initial.valueStart;
963
+ if (!initial || !startsHidden(initial.value) || tag.attributes.has('whileInView'))
964
+ continue; // MOT-08 owns scroll reveals
965
+ const animate = tag.attributes.get('animate')?.value;
966
+ if (!animate)
967
+ continue;
968
+ const signature = `${initial.value}|${animate}`.replace(/\s+/g, ' ').trim();
969
+ const entry = entrances.get(signature);
970
+ if (entry)
971
+ entry.count++;
972
+ else
973
+ entrances.set(signature, { at: tag.start, count: 1 });
974
+ }
975
+ if (readingEntrance !== null) {
976
+ push('UNIFORM_ENTRANCE_MOTION', readingEntrance, 'Entrance animation on static reading content delays the first paint; render headings, paragraphs, and navigation visible and animate one thing that matters.');
977
+ }
978
+ const uniformEntrance = [...entrances.values()].find(entry => entry.count >= 4);
979
+ if (uniformEntrance) {
980
+ push('UNIFORM_ENTRANCE_MOTION', uniformEntrance.at, `${uniformEntrance.count} elements share one identical entrance; keep one restrained reveal instead of a template fade-up applied to every block.`);
981
+ }
982
+ // MOT-16: Overshoot/elastic easing on routine UI motion (cubic-bezier y outside 0-1).
983
+ // Masked source covers CSS and inline styles; class tokens cover Tailwind arbitrary values.
984
+ const bezierRe = /cubic-bezier\(\s*(-?\d*\.?\d+)\s*,\s*(-?\d*\.?\d+)\s*,\s*(-?\d*\.?\d+)\s*,\s*(-?\d*\.?\d+)\s*\)/g;
985
+ const overshoot = (match) => [match[2], match[4]].some(y => Number(y) > 1.05 || Number(y) < -0.05);
986
+ const elasticAt = [...scan.masked.matchAll(bezierRe)].find(overshoot);
987
+ const elasticClass = tagClasses.find(({ tokens }) => tokens.some(token => [...token.matchAll(bezierRe)].some(overshoot)));
988
+ if (elasticAt || elasticClass) {
989
+ const tokenMatch = elasticClass ? [...elasticClass.tokens.join(' ').matchAll(bezierRe)][0] : undefined;
990
+ const bezier = elasticAt?.[0] ?? tokenMatch?.[0] ?? '';
991
+ if (bezier) {
992
+ push('ELASTIC_UI_EASING', elasticAt?.index ?? elasticClass?.tag.start ?? 0, `Overshoot easing "${bezier}" makes a routine surface bounce; routine UI enters on ease-out and overshoot stays on one small expressive icon.`);
993
+ }
994
+ }
995
+ // MOT-17: will-change left on permanently instead of hinted around one animation.
996
+ const willChangeDeclarations = [...scan.masked.matchAll(/will-?change\s*:\s*(?!\s*['"]?auto\b)/gi)];
997
+ const willChangeTokens = tagClasses.reduce((count, { tokens }) => count + tokens.filter(token => /^will-change-(?!auto$)/.test(token)).length, 0);
998
+ const willChangeCount = willChangeDeclarations.length + willChangeTokens;
999
+ if (willChangeCount >= 3) {
1000
+ const willChangeAt = willChangeDeclarations[0]?.index ?? tags.find(tag => classesFor(tag).some(token => /^will-change-(?!auto$)/.test(token)))?.start ?? 0;
1001
+ push('WILL_CHANGE_LEAK', willChangeAt, `will-change is declared ${willChangeCount} times and left on permanently; hint the layer just before a known animation and remove it after.`);
1002
+ }
1003
+ // MOT-18: A duration outside the motion scale declared in DESIGN.md.
1004
+ if (motionContract?.slow) {
1005
+ const slowLimit = motionContract.slow;
1006
+ for (const { tag, tokens } of tagClasses) {
1007
+ const offContract = tokens.find(token => {
1008
+ const ms = durationMs(token);
1009
+ return ms !== null && ms > slowLimit + 50;
1010
+ });
1011
+ if (offContract) {
1012
+ push('OFF_CONTRACT_MOTION', tag.start, `Duration "${offContract}" is outside the declared motion scale (slow ${slowLimit}ms).`);
1013
+ }
1014
+ }
1015
+ }
1016
+ } // end if (!options.codeOnly) for MOT-02..MOT-18
756
1017
  const ignoreFile = allComments.some(c => /sloppy-ignore-file/.test(c.text));
757
1018
  // `sloppy-allow-file` exempts named rules only, so reference specimens keep
758
1019
  // protection against every other anti-pattern.
@@ -815,22 +1076,23 @@ export function auditCode(code, options = {}) {
815
1076
  return { target: rest.slice(0, sepIdx).trim(), reason: rest.slice(sepIdx + sepLen).trim() };
816
1077
  };
817
1078
  // Check for inline override rationale: // sloppy-override: RULE <rationale>
1079
+ const nearbyComments = [
1080
+ ...(commentsByLine.get(loc.line - 1) || []),
1081
+ ...(commentsByLine.get(loc.line) || [])
1082
+ ];
818
1083
  let inlineRationale;
819
- for (const comment of allComments) {
820
- const cl = comment.line;
821
- if (cl === loc.line || cl + 1 === loc.line) {
822
- const body = cleanCommentBody(comment.text);
823
- const markerMatch = /(?:sloppy-override|@sloppy-override)/i.exec(body);
824
- if (markerMatch) {
825
- let rest = body.slice(markerMatch.index + markerMatch[0].length).replace(/^[:,]/, '').trim();
826
- const wsIdx = rest.search(/\s/);
827
- if (wsIdx > 0) {
828
- const ruleCandidate = rest.slice(0, wsIdx).trim().toUpperCase().replace(/-/g, '_');
829
- const resolved = RULE_ALIASES[ruleCandidate] || ruleCandidate;
830
- if (resolved === c.type || (ruleCode && resolved === ruleCode)) {
831
- inlineRationale = rest.slice(wsIdx + 1).trim();
832
- break;
833
- }
1084
+ for (const comment of nearbyComments) {
1085
+ const body = cleanCommentBody(comment.text);
1086
+ const markerMatch = /(?:sloppy-override|@sloppy-override)/i.exec(body);
1087
+ if (markerMatch) {
1088
+ let rest = body.slice(markerMatch.index + markerMatch[0].length).replace(/^[:,]/, '').trim();
1089
+ const wsIdx = rest.search(/\s/);
1090
+ if (wsIdx > 0) {
1091
+ const ruleCandidate = rest.slice(0, wsIdx).trim().toUpperCase().replace(/-/g, '_');
1092
+ const resolved = RULE_ALIASES[ruleCandidate] || ruleCandidate;
1093
+ if (resolved === c.type || (ruleCode && resolved === ruleCode)) {
1094
+ inlineRationale = rest.slice(wsIdx + 1).trim();
1095
+ break;
834
1096
  }
835
1097
  }
836
1098
  }
@@ -840,7 +1102,7 @@ export function auditCode(code, options = {}) {
840
1102
  const rationale = inlineRationale || configRationale;
841
1103
  const isOverruled = tier === 'reflex' && hasRationale;
842
1104
  const isStrict = Boolean(options.strict || config?.strict);
843
- const ignored = ignoreFile || allowedRules.has(c.type) || (ruleCode && allowedRules.has(ruleCode)) || allComments.some(comment => {
1105
+ const ignored = ignoreFile || allowedRules.has(c.type) || (ruleCode && allowedRules.has(ruleCode)) || nearbyComments.some(comment => {
844
1106
  const cl = comment.line;
845
1107
  const body = cleanCommentBody(comment.text);
846
1108
  if (cl + 1 === loc.line) {
@@ -886,12 +1148,6 @@ export function auditCode(code, options = {}) {
886
1148
  const metadata = RULE_METADATA[c.type];
887
1149
  const standardKind = metadata?.evidenceKinds.includes('standard');
888
1150
  const kind = standardKind ? 'standard' : (metadata?.evidenceKinds[0] ?? 'source');
889
- const criteria = {
890
- LOW_CONTRAST_GRAY: 'WCAG 1.4.3 Contrast (Minimum)',
891
- FAKE_CONTROL_SLOP: 'WCAG 4.1.2 Name, Role, Value / 2.1.1 Keyboard',
892
- SCROLL_HIJACKING: 'WCAG 2.1.1 Keyboard',
893
- REDUCED_MOTION_BLINDNESS: 'WCAG 2.3.3 Animation from Interactions'
894
- };
895
1151
  const evidence = {
896
1152
  kind,
897
1153
  description: c.message,
@@ -901,8 +1157,8 @@ export function auditCode(code, options = {}) {
901
1157
  selector: selectorAt(c.at),
902
1158
  ...(c.evidence ?? {})
903
1159
  };
904
- if (kind === 'standard' && criteria[c.type])
905
- evidence.criterion = criteria[c.type];
1160
+ if (kind === 'standard' && CRITERIA_MAP[c.type])
1161
+ evidence.criterion = CRITERIA_MAP[c.type];
906
1162
  const violation = {
907
1163
  id: `${(ruleCode || c.type).toLowerCase()}-${c.at}`,
908
1164
  ruleId: ruleCode || c.type,