Spacing Anomalies: Inconsistent margins, paddings, or grid alignment.
This is a complex tool. I need to break down the architecture, the "AI" aspect, and the implementation details.
1. High-Level Architecture:
The tool needs to sit in the CI/CD pipeline or run as a local development tool. It takes a component (code/rendered output) as input and produces a report.
Input: Source code (JSX/Vue/HTML), Storybook stories, or screenshots/DOM snapshots.
Core Engine: The analysis logic.
AI Layer: The "Assistant" part. Instead of just hard-coded rules, use an LLM (Large Language Model) to interpret context, suggest fixes, and handle fuzzy logic (e.g., "This looks like a header but has body styling").
Output: A CLI report, a browser extension overlay, or a PR comment.
2. Deconstructing the Features:
Design Token Drift:
Traditional approach: AST (Abstract Syntax Tree) parsing to check if hardcoded values exist instead of variables.
AI approach: The LLM analyzes the intention. If a developer uses #3b5998 (Facebook blue) instead of the brand token var(--color-primary), the AI can flag it and suggest the token semantically based on the component's context.
Contrast Regressions:
Traditional approach: Calculating luminance ratios (WCAG math). This requires rendered colors.
AI approach: The AI can analyze screenshots or computed styles. It can distinguish between "decorative text" (lower contrast okay-ish, though not strictly accessible) and "critical CTA" (must be high contrast). It can suggest accessible color alternatives that still fit the aesthetic.
Spacing Anomalies:
Traditional approach: Visual regression testing (pixel diff) or DOM measurement.
AI approach: Visual segmentation. The AI looks at the rendered component and identifies visual rhythm. Is that margin 8px or 9px? Does it break the 8-point grid? Is the alignment off-center?
3. The "Engineering" (Implementation Plan):
I will propose a solution involving a Python/Node.js backend, leveraging Puppeteer/Playwright for rendering, and an OpenAI/Anthropic API for the AI reasoning.
Step-by-Step Implementation Strategy:
Step 1: The Audit Context (The "Eye"): We need to see what the computer sees. This means taking screenshots and extracting DOM data (computed styles).
Step 2: Token Definition (The "Law"): We need a JSON/YAML file defining the design system tokens.
Step 3: The AI Agent (The "Brain"): A prompt engineering strategy.
Input: Image of component + JSON of computed styles + JSON of Design Tokens.
System Prompt: "You are a strict Design System Auditor."
Step 4: Automated Fixes (The "Action"): The output shouldn't just be "Bad", it should be "Change margin-top: 15px to spacing-md."
4. Drafting the Code Structure:
I'll provide a conceptual codebase. A full working app is too large, so I will focus on the core logic of the Auditor.
Module 1: Capture. Use Playwright to get the screenshot and computed styles.
Module 2: Analysis.
Token Drift: Compare computed styles against token definitions.
Contrast: Standard math check first (fast), AI interpretation second (context).
Spacing: Check against a base unit (e.g., 4px or 8px).
Module 3: AI Synthesis. Send findings to an LLM to generate a human-readable, actionable report.
5. Refining the "AI" part:
Pure rule-based checking is often brittle. The AI's value add here is semantic validation. For example, a rule-based checker sees #000000. A token system has color-text-primary as #000000. The rule checker is happy. But what if the background is dark? The AI sees the context.
Wait, the prompt asks for "Token Drift". This usually means using a raw value instead of a variable. I need to make sure the tool checks the source code or the mapping of styles.
Correction: It's hard to map computed styles back to variable names reliably without source code analysis. I will assume the tool analyzes the visual outcome and CSS values against the design system manifest.
6. Structuring the Output:
I will present this as a "System Design & Implementation Guide".
Architecture Diagram: Conceptual.
The Design Manifest: The source of truth.
The Audit Script: Python code using Playwright and OpenAI.
The "Drift" Detector: Regex/AST parser simulation (simplified for the example).
The AI Reasoner: The prompt logic.
Self-Correction/Refinement during thought process:Initial thought: Just use an LLM to look at a screenshot.
Critique: LLMs are bad at exact pixel counting.
Better approach: Hybrid. Use scripts to measure exact pixels/contrast. Feed those measurements to the LLM with a screenshot for context. The LLM acts as the judge and reporter.
Let's write the code. I will use Python (standard for data/scripting) with a mock "Design System" and a mock "Component".
Feature 1: Token Drift.
Logic: Parse CSS/Styles. If value (e.g., 14px) is not in the allowed token map (e.g., font-size-sm), flag it.
Feature 2: Contrast.
Logic: Get computed foreground/background. Calculate ratio. If < 4.5, flag it.
Feature 3: Spacing.
Logic: Get padding/margin. Check if divisible by base_unit (e.g., 4).
The AI Twist:
Instead of just printing "Error: Line 5", we feed these raw errors into an LLM:
"I found these 3 errors in the 'Button' component. Here is a screenshot. Please explain why these hurt the UX and write the fix code."
Final Plan:
Define the inputs: Design Tokens + Component URL.
The Scanner (Python): Uses Playwright to scrape computed styles.
The Validator (Logic): Runs the math checks.
The Interpreter (LLM): Generates the final report.
I will structure the response to be modular and actionable.
Detailed Code thought:
I need a class ComponentAuditor.
Methods: audit_tokens, audit_contrast, audit_spacing.
Main runner: run_audit.
Integration: OpenAI API call at the end.
Double check contrast logic:
Relative luminance formula. (R+0.05)/(G+0.05).
I'll use a library concept or a helper function to keep it clean.
Double check token drift:
If the CSS says color: #4287f5 but the token list says primary-blue: #4287f5, we flag it as "Un aliased value detected".
Double check spacing:value % base_unit != 0.
The Result: A "CLI" tool that outputs a report.
Let's write it.
This solution engineers a Design System Auditor Agent. It operates in two phases:
Computational Analysis (Deterministic): It uses script injection to measure exact pixels, color ratios, and style computation to detect drift and accessibility issues.
AI Synthesis (Generative): It packages these findings into a structured prompt for an LLM (like GPT-4) to provide semantic reasoning, suggest code fixes, and identify "false positives" where a deviation might be intentional.
System Architecture
The Manifest: A JSON file defining the "Source of Truth" for design tokens (colors, spacing units, typography).
The Scanner (Node/Puppeteer): A headless browser script that traverses the DOM, computes styles, and captures visual data.
The Evaluator: A logic layer that calculates contrast ratios and modular scale violations.
The AI Auditor: An interface that sends the violation context to an LLM for actionable reporting.
1. The Source of Truth (Design Manifest)
First, we define the rules. This acts as the constraint layer for the AI.
This script performs the heavy lifting. It uses Puppeteer to load a component, extracts the styles, and compares them against the manifest.
Prerequisites:npm install puppeteer chromatic ai openai
javascript
3. The AI Interface (Semantic Reasoning)
This component takes the raw JSON violations and asks an AI to analyze them in the context of the codebase. This solves the "false positive" problem common in static analysis.
javascript
// ai-analyzer.js
const { OpenAI } = require('openai');
// Initialize OpenAI (ensure OPENAI_API_KEY is set in env)
const openai = new OpenAI();
async function generateAuditReport(violations) {
if (violations.length === 0) return "No violations found. System healthy.";
const violationLog = violations.map(v =>
`[${v.severity}] ${v.type}: ${v.message} | Context: ${v.context || 'N/A'}`
).join('\n');
const systemPrompt = `
You are a Senior Frontend Architect and Accessibility Expert.
You have been provided a list of Design System violations detected by an automated scanner.
Your task:
1. Filter out likely false positives (e.g., temporary overlays, hidden elements).
2. Group related issues (e.g., a button style affecting 10 buttons counts as 1 global issue).
3. Provide code snippets for the most efficient fix using CSS variables or Tailwind classes.
4. Prioritize accessibility (Contrast) over aesthetic drift (Spacing).
`;
try {
const response = await openai.chat.completions.create({
model: "gpt-4o",
messages: [
{ role: "system", content: systemPrompt },
{ role: "user", content: `Analyze the following violation log:\n\n${violationLog}` }
],
temperature: 0.1,
});
return response.choices[0].message.content;
} catch (error) {
console.error("AI Analysis failed:", error);
return "Raw Log:\n" + violationLog;
}
}
module.exports = generateAuditReport;
4. Execution Entry Point
The script that ties the deterministic scanner to the AI auditor.
javascript
// index.js
const ComponentAuditor = require('./auditor-core');
const generateAuditReport = require('./ai-analyzer');
async function run() {
const TARGET_URL = process.argv[2] || 'http://localhost:3000';
console.log(`🔍 Auditing ${TARGET_URL}...`);
const auditor = new ComponentAuditor(TARGET_URL);
try {
const violations = await auditor.audit();
console.log(`⚠️ Found ${violations.length} raw signals.`);
console.log("🤖 Invoking AI for synthesis and remediation...");
const finalReport = await generateAuditReport(violations);
console.log("\n--- AUDIT REPORT ---\n");
console.log(finalReport);
} catch (error) {
console.error("Audit Failed:", error);
}
}
run();
How It Works
Drift Detection (The "Style" Check):
The checkTokenDrift function converts computed RGB values to Hex and checks if they exist in the design-manifest.json. If a developer hardcoded #0052CD (off by one digit), the system flags it.
Contrast Regression (The "Access" Check):
The checkContrastRatios function implements the WCAG 2.0 luminance contrast formula. It retrieves the foreground and background color of every visible text node. If a designer chooses a light grey on white, this catches it immediately.
Spacing Anomalies (The "Rhythm" Check):
The checkSpacingAnomalies ensures that all margins and padding adhere to a modular scale (e.g., a 4px or 8px grid). It detects "magic numbers" (like 13px or 17px) that often creep in during rushed development.
AI Synthesis:
Instead of outputting a raw CSV file, the AI groups the errors. If 50 buttons have low contrast, the AI summarizes: "Global Button Component: Text color insufficient on Primary Background." It then outputs the specific CSS variable fix.
// auditor-core.js
const puppeteer = require('puppeteer');
const manifest = require('./design-manifest.json');
class ComponentAuditor {
constructor(url) {
this.url = url;
this.violations = [];
}
async init() {
this.browser = await puppeteer.launch({ headless: "new" });
this.page = await this.browser.newPage();
await this.page.goto(this.url, { waitUntil: 'networkidle0' });
}
async audit() {
await this.init();
// 1. Scan DOM elements
const rawNodes = await this.page.evaluate(this.extractDOMStyles);
// 2. Analyze for violations
this.checkTokenDrift(rawNodes);
this.checkContrastRatios(rawNodes);
this.checkSpacingAnomalies(rawNodes);
await this.browser.close();
return this.violations;
}
// Browser-context function to extract computed styles
extractDOMStyles() {
const elements = document.querySelectorAll('*');
const data = [];
elements.forEach((el) => {
const styles = window.getComputedStyle(el);
data.push({
tag: el.tagName,
text: el.innerText?.substring(0, 50),
color: styles.color,
bgColor: styles.backgroundColor,
fontSize: styles.fontSize,
fontFamily: styles.fontFamily,
margin: styles.margin,
padding: styles.padding,
bounds: el.getBoundingClientRect()
});
});
return data;
}
checkTokenDrift(nodes) {
nodes.forEach(node => {
const allowedColors = Object.values(manifest.tokens.colors);
// Convert RGB string to Hex for comparison
const currentHex = this.rgbToHex(node.color);
if (currentHex && !allowedColors.includes(currentHex)) {
this.violations.push({
type: 'TOKEN_DRIFT',
message: `Color ${currentHex} found in "${node.tag}" is not in design system.`,
suggestion: `Closest match: ${this.findClosestToken(currentHex, 'colors')}`,
severity: 'MEDIUM'
});
}
});
}
checkContrastRatios(nodes) {
nodes.forEach(node => {
if (!node.text || node.text.trim() === '') return; // Skip empty nodes
const fg = this.parseColor(node.color);
const bg = this.parseColor(node.bgColor);
if (fg && bg) {
const ratio = this.getContrastRatio(fg, bg);
if (ratio < manifest.rules.min_contrast_ratio) {
this.violations.push({
type: 'CONTRAST_REGRESSION',
message: `Contrast ratio ${ratio.toFixed(2)} is below WCAG AA standard (4.5).`,
context: `Text: "${node.text.trim()}"`,
severity: 'HIGH'
});
}
}
});
}
checkSpacingAnomalies(nodes) {
const base = manifest.tokens.spacing.base;
nodes.forEach(node => {
const props = ['margin', 'padding'];
props.forEach(prop => {
const values = node[prop].split(' ').map(v => parseInt(v));
values.forEach(val => {
// Check if value is a multiple of the base grid (allowing small float tolerance)
if (val > 0 && (val % base !== 0)) {
this.violations.push({
type: 'SPACING_ANOMALY',
message: `Non-standard ${prop} of ${val}px detected.`,
suggestion: `Adjust to nearest multiple of ${base}px.`,
severity: 'LOW'
});
}
});
});
});
}
// --- Helper Utilities ---
rgbToHex(rgb) {
if (!rgb || rgb === 'transparent' || rgb.includes('rgba(0, 0, 0, 0)')) return null;
const match = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)/);
if (!match) return null;
return "#" + [match[1], match[2], match[3]].map(x => {
const hex = parseInt(x).toString(16);
return hex.length === 1 ? "0" + hex : hex;
}).join('').toUpperCase();
}
parseColor(colorStr) {
// Implementation of luminance parsing logic
// returns { r, g, b }
const match = colorStr.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)/);
if(!match) return null;
return { r: parseInt(match[1]), g: parseInt(match[2]), b: parseInt(match[3]) };
}
getLuminance(r, g, b) {
const [rs, gs, bs] = [r, g, b].map(c => {
c = c / 255;
return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
});
return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
}
getContrastRatio(fg, bg) {
const L1 = this.getLuminance(fg.r, fg.g, fg.b);
const L2 = this.getLuminance(bg.r, bg.g, bg.b);
const lighter = Math.max(L1, L2);
const darker = Math.min(L1, L2);
return (lighter + 0.05) / (darker + 0.05);
}
findClosestToken(hex, type) {
// Simple string distance or color distance logic would go here
return "Unknown Token";
}
}
module.exports = ComponentAuditor;