references/report-format.md
# SLDS Quality Report Format
Guidelines for generating quality reports. **Default to the compact format** and expand sections when the user requests detail.
---
## Default: Compact Report
Always start with this format. It gives the user the full picture in a glanceable summary.
````markdown
# SLDS Quality Scorecard: `{component-name}`
**Path:** `{component-path}` | **Complexity:** {small|medium|large} ({n} files, {n} lines)
**Generated:** {date}
## Automated Grade: {grade} ({score}/100)
{grade-description}
**Manual Review Gate:** {Pass|Advisory|Blocking}
**Final Recommendation:** {Ready for production|Ready with follow-ups|Needs work|Failing}
| Category | Score | Grade |
|----------|-------|-------|
| Linter Compliance | {score}/100 | {status-emoji} {grade} |
| Theming | {score}/100 | {status-emoji} {grade} |
| Accessibility | {score}/100 | {status-emoji} {grade} |
| Code Quality | {score}/100 | {status-emoji} {grade} |
| Component Usage | {score}/100 | {status-emoji} {grade} |
**Issues:** {n} critical | {n} warnings | {n} info
### Top Issues
1. **{issue}** — `{file}:{line}` — {recommendation}
2. **{issue}** — `{file}:{line}` — {recommendation}
3. **{issue}** — `{file}:{line}` — {recommendation}
> Automated score reflects linter + script findings only. Manual review can still block ship.
>
> {accessibility-disclaimer-if-scored}
*Ask for the full report to see all findings, code examples, and action items.*
````
### When to Show Compact
- First response to a quality audit request
- Quick validation mode
- Auditing multiple components (show compact for each)
---
## Expanded: Full Report
Show this when the user asks to "expand", "show details", "full report", or "show all findings". Build on top of the compact report — don't repeat the summary, just add the detail sections below it.
````markdown
---
## Critical Issues ({count})
Issues that **must be fixed** before deployment.
### {issue-category}
| # | File | Line | Issue | Recommendation |
|---|------|------|-------|----------------|
| 1 | `{file}` | {line} | {description} | {fix} |
| 2 | `{file}` | {line} | {description} | {fix} |
**Example fix:**
```css
/* Before */
{problematic-code}
/* After */
{fixed-code}
```
---
## Warnings ({count})
Issues that **should be fixed** but are not blocking.
| # | File | Line | Issue | Impact |
|---|------|------|-------|--------|
| 1 | `{file}` | {line} | {description} | {impact} |
---
## Info ({count})
Suggestions for improvement.
| # | Category | Finding | Suggestion |
|---|----------|---------|------------|
| 1 | {category} | {finding} | {suggestion} |
---
## Detailed Findings
### Manual Review Gate
**Gate:** {Pass|Advisory|Blocking}
| Review Area | Outcome | Notes |
|-------------|---------|-------|
| Loading states | {Pass|Advisory|Blocking} | {notes} |
| Error states | {Pass|Advisory|Blocking} | {notes} |
| Empty states | {Pass|Advisory|Blocking} | {notes} |
| Disabled states | {Pass|Advisory|Blocking} | {notes} |
| Semantic HTML | {Pass|Advisory|Blocking} | {notes} |
| Blueprint compliance | {Pass|Advisory|Blocking} | {notes} |
---
### Linter Compliance
**Violations Found:** {count}
| Rule | Count | Files Affected |
|------|-------|----------------|
| `slds/class-override` | {count} | {files} |
| `slds/lwc-token-to-slds-hook` | {count} | {files} |
| `slds/no-hardcoded-values` | {count} | {files} |
<details>
<summary>Full Linter Output</summary>
```json
{linter-output}
```
</details>
---
### Theming
**Hooks Usage Summary:**
| Hook Type | Used | Missing Fallback | Issues |
|-----------|------|------------------|--------|
| Color Hooks | {count} | {count} | {count} |
| Spacing Hooks | {count} | {count} | {count} |
| Typography Hooks | {count} | {count} | {count} |
**Hook Pairing Analysis:**
| Background Hook | Paired Text Hook | Status |
|-----------------|------------------|--------|
| `--slds-g-color-surface-1` | `--slds-g-color-on-surface-2` | {status} |
---
### Accessibility
> This section checks attribute presence only. It does not validate contrast ratios, keyboard flows, or screen reader behavior. Passing here does not guarantee WCAG compliance.
| Check | Status | Details |
|-------|--------|---------|
| Lightning input labels | {status} | {count} inputs, {count} labeled |
| Icon alternative text | {status} | {count} icons, {count} with alt |
| Image alt attributes | {status} | {count} images, {count} with alt |
| Heading hierarchy | {status} | {sequence} |
| Focus indicators | {status} | {findings} |
---
### Code Quality
| Metric | Value | Status |
|--------|-------|--------|
| Total CSS lines | {count} | {status} |
| !important usage | {count} | {status} |
| Inline styles | {count} | {status} |
| High z-index values | {count} | {status} |
---
### Component Usage
| Element Type | Native Count | LBC Alternative | Recommendation |
|--------------|-------------|-----------------|----------------|
| Inputs | {count} | `<lightning-input>` | {recommendation} |
| Buttons | {count} | `<lightning-button>` | {recommendation} |
| Selects | {count} | `<lightning-combobox>` | {recommendation} |
---
## Action Items
### Must Fix (Critical)
- [ ] {action-item}
### Should Fix (Warnings)
- [ ] {action-item}
### Nice to Have (Info)
- [ ] {action-item}
---
## Next Steps
1. Address all **{count} critical issues** immediately
2. Review and fix **{count} warnings** before code review
3. Consider **{count} suggestions** for future improvements
4. Re-run validation to confirm fixes
**Estimated Effort:** {estimate}
````
---
## JSON Output
For programmatic consumption (e.g., CI integration or tracking over time). Produce this only when explicitly requested or when auditing multiple components for comparison.
```json
{
"component": "{component-name}",
"path": "{component-path}",
"timestamp": "{iso-date}",
"complexity": {
"classification": "medium",
"totalFiles": 4,
"totalLines": 280
},
"scores": {
"automatedOverall": 85,
"automatedGrade": "B",
"categories": {
"linter": { "score": 100, "grade": "A" },
"theming": { "score": 80, "grade": "B" },
"accessibility": { "score": 75, "grade": "C" },
"codeQuality": { "score": 90, "grade": "A" },
"componentUsage": { "score": 85, "grade": "B" }
}
},
"manualReview": {
"gate": "Advisory",
"findings": []
},
"finalRecommendation": "Ready with follow-ups",
"findings": {
"critical": [],
"warnings": [],
"info": []
},
"summary": {
"filesAnalyzed": 4,
"totalLines": 280,
"critical": 0,
"warnings": 2,
"info": 3
}
}
```
---
## Status Indicators
| Score Range | Emoji | Meaning |
|-------------|-------|---------|
| 90-100 | ✅ | Excellent |
| 80-89 | 🟢 | Good |
| 70-79 | 🟡 | Acceptable |
| 60-69 | 🟠 | Needs Work |
| 0-59 | 🔴 | Critical |
---
## Grade Descriptions
| Grade | Description |
|-------|-------------|
| A | **Excellent** - Strong automated result. Requires a passing manual review gate before calling it production-ready. |
| B | **Good** - Solid automated result. Requires manual review before a production recommendation. |
| C | **Acceptable** - Automated issues should be addressed before production. |
| D | **Needs Work** - Significant automated issues require attention before code review. |
| F | **Critical** - Automated checks found blocking issues. Not suitable for deployment. |
---
## Report Delivery Guidelines
1. **Always default to compact** — show the scorecard first, expand on request
2. **Separate automated grade from final recommendation** — manual review can override ship readiness
3. **Group by severity** — critical issues first, then warnings, then info
4. **Include actionable recommendations** — every finding should have a clear fix
5. **Provide code examples** — show before/after for complex fixes in the expanded report
6. **Note complexity** — a "B" on a large component means something different than a "B" on a small one
7. **Add accessibility disclaimer** — when the accessibility score is included, note it checks attribute presence only
scripts/analyze-quality.cjs
#!/usr/bin/env node
/**
* SLDS Quality Analyzer
*
* Analyzes CSS and HTML files for SLDS quality issues beyond what the linter catches.
*
* Usage: node analyze-quality.cjs <component-path> [--hooks-index <path>]
*
* Output: JSON with findings categorized by severity
*/
const fs = require('fs');
const path = require('path');
function resolveHooksIndexPath(args) {
const idx = args.indexOf('--hooks-index');
if (idx !== -1 && idx + 1 < args.length) {
return path.resolve(args[idx + 1]);
}
return null;
}
let HOOKS_INDEX_PATH = null;
// Severity levels
const CRITICAL = 'critical';
const WARNING = 'warning';
const INFO = 'info';
// Detection patterns
// NOTE: Checks that the SLDS linter already handles are excluded here to avoid
// double-counting. The linter covers: slds/class-override (L001),
// slds/lwc-token-to-slds-hook (L002), slds/no-hardcoded-values (L003).
// This script focuses on what the linter does NOT catch.
const PATTERNS = {
// CSS patterns (linter-complementary only)
css: {
missingFallback: {
pattern: /var\(--slds-g-[^,)]+\)/g,
severity: CRITICAL,
id: 'T002',
message: 'SLDS hook without fallback value',
recommendation: 'Add fallback: var(--slds-g-color-surface-1, #fff)'
},
important: {
pattern: /!important/g,
severity: WARNING,
id: 'Q001',
message: '!important declaration found',
recommendation: 'Remove !important, use proper specificity'
},
magicPixels: {
pattern: /\b(?:margin(?:-[a-z-]+)?|padding(?:-[a-z-]+)?|gap|row-gap|column-gap)\s*:\s*(\d+)px\b(?![^;]*var\()/g,
severity: WARNING,
id: 'T021',
message: 'Magic pixel value not using spacing hook',
recommendation: 'Use var(--slds-g-spacing-*) or utility class'
},
highZindex: {
pattern: /z-index\s*:\s*(\d{3,})/g,
severity: WARNING,
id: 'Q021',
message: 'High z-index value',
recommendation: 'Use defined z-index scale'
},
outlineNone: {
pattern: /outline\s*:\s*none/g,
severity: WARNING,
id: 'A021',
message: 'Focus outline removed without alternative',
recommendation: 'Provide alternative focus indicator'
}
},
// JS patterns (inline styles and dynamic class manipulation)
js: {
inlineStyleJS: {
pattern: /\.style\.\w+\s*=/g,
severity: WARNING,
id: 'Q025',
message: 'Inline style manipulation in JavaScript',
recommendation: 'Use CSS classes instead of direct style property assignment'
},
classListManipulation: {
pattern: /\.classList\.(add|remove|toggle)\(\s*['"]slds-/g,
severity: WARNING,
id: 'Q012',
message: 'Dynamic SLDS class manipulation in JavaScript',
recommendation: 'Prefer declarative class bindings; avoid manipulating slds-* classes directly'
}
},
// HTML patterns
html: {
inlineStyle: {
pattern: /style\s*=\s*["'][^"']+["']/gi,
severity: WARNING,
id: 'Q002',
message: 'Inline style attribute',
recommendation: 'Move styles to CSS file'
},
lightningInputNoLabel: {
pattern: /<lightning-input(?![^>]*\blabel\b)[^>]*>/gi,
severity: CRITICAL,
id: 'A001',
message: 'Lightning input without label attribute',
recommendation: 'Add label attribute to lightning-input'
},
iconNoAlt: {
pattern: /<lightning-icon(?![^>]*alternative-text)[^>]*>/gi,
severity: CRITICAL,
id: 'A004',
message: 'Icon without alternative-text',
recommendation: 'Add alternative-text (or empty string for decorative)'
},
imgNoAlt: {
pattern: /<img(?![^>]*\balt\b)[^>]*>/gi,
severity: CRITICAL,
id: 'A005',
message: 'Image without alt attribute',
recommendation: 'Add alt attribute'
},
positiveTabindex: {
pattern: /tabindex\s*=\s*["']([1-9]\d*)["']/gi,
severity: WARNING,
id: 'A020',
message: 'Positive tabindex value',
recommendation: 'Use tabindex="0" or "-1" only'
},
clickableDiv: {
pattern: /<div[^>]*onclick[^>]*>/gi,
severity: WARNING,
id: 'A022',
message: 'Div with click handler instead of button',
recommendation: 'Use <button> or <lightning-button> for interactive elements'
},
nativeInput: {
pattern: /<input\s/gi,
severity: WARNING,
id: 'C001',
message: 'Native input element',
recommendation: 'Consider <lightning-input> for built-in labeling and validation'
},
nativeButton: {
pattern: /<button\s(?![^>]*class\s*=\s*["'][^"']*slds-button)/gi,
severity: WARNING,
id: 'C002',
message: 'Native button element',
recommendation: 'Consider <lightning-button> for SLDS styling consistency (suppressed if slds-button class present)'
},
nativeSelect: {
pattern: /<select\s/gi,
severity: WARNING,
id: 'C004',
message: 'Native select element',
recommendation: 'Consider <lightning-combobox> for consistency'
}
}
};
/**
* Find all files with given extensions in directory
*/
function findFiles(dir, extensions) {
const files = [];
function walk(currentDir) {
try {
const items = fs.readdirSync(currentDir);
for (const item of items) {
const fullPath = path.join(currentDir, item);
const stat = fs.statSync(fullPath);
if (stat.isDirectory() && !item.startsWith('.') && item !== 'node_modules') {
walk(fullPath);
} else if (stat.isFile()) {
const ext = path.extname(item).toLowerCase();
if (extensions.includes(ext)) {
files.push(fullPath);
}
}
}
} catch (err) {
// Skip directories we can't read
}
}
walk(dir);
return files;
}
/**
* Analyze a single file
*/
function analyzeFile(filePath, patterns) {
const findings = [];
const content = fs.readFileSync(filePath, 'utf-8');
const lines = content.split('\n');
for (const [name, config] of Object.entries(patterns)) {
const regex = new RegExp(config.pattern.source, config.pattern.flags);
let match;
while ((match = regex.exec(content)) !== null) {
// Find line number
const beforeMatch = content.substring(0, match.index);
const lineNumber = beforeMatch.split('\n').length;
const lineContent = lines[lineNumber - 1] || '';
findings.push({
id: config.id,
severity: config.severity,
file: filePath,
line: lineNumber,
column: match.index - beforeMatch.lastIndexOf('\n'),
match: match[0].substring(0, 50),
message: config.message,
recommendation: config.recommendation,
context: lineContent.trim().substring(0, 80)
});
}
}
return findings;
}
/**
* Analyze heading hierarchy in HTML
*/
function analyzeHeadings(filePath) {
const findings = [];
const content = fs.readFileSync(filePath, 'utf-8');
const headingRegex = /<h([1-6])[^>]*>/gi;
const headings = [];
let match;
while ((match = headingRegex.exec(content)) !== null) {
headings.push({
level: parseInt(match[1]),
index: match.index
});
}
// Check for skipped levels
for (let i = 1; i < headings.length; i++) {
const prev = headings[i - 1].level;
const curr = headings[i].level;
if (curr > prev + 1) {
const beforeMatch = content.substring(0, headings[i].index);
const lineNumber = beforeMatch.split('\n').length;
findings.push({
id: 'A010',
severity: WARNING,
file: filePath,
line: lineNumber,
message: `Skipped heading level: h${prev} to h${curr}`,
recommendation: `Use h${prev + 1} instead of h${curr}`
});
}
}
return findings;
}
/**
* Load valid hook tokens from hooks-index.json
*/
let _validHooks = null;
function loadValidHooks() {
if (_validHooks) return _validHooks;
if (!HOOKS_INDEX_PATH) return null;
try {
const data = JSON.parse(fs.readFileSync(HOOKS_INDEX_PATH, 'utf-8'));
_validHooks = new Set(data.hooks.map(h => h.token));
} catch {
console.error(`WARNING: Could not load hooks-index.json at ${HOOKS_INDEX_PATH}`);
console.error('Invented-hook detection (T051) will be skipped.');
_validHooks = null;
}
return _validHooks;
}
/**
* Check for invented hooks (T051) — hooks referenced in CSS that don't exist in metadata
*/
function analyzeInventedHooks(filePath) {
const findings = [];
const validHooks = loadValidHooks();
if (!validHooks) return findings; // skip if metadata unavailable
const content = fs.readFileSync(filePath, 'utf-8');
const lines = content.split('\n');
const hookRef = /var\((--slds-g-[^,)]+)/g;
let match;
while ((match = hookRef.exec(content)) !== null) {
const hookName = match[1].trim();
if (!validHooks.has(hookName)) {
const beforeMatch = content.substring(0, match.index);
const lineNumber = beforeMatch.split('\n').length;
const lineContent = lines[lineNumber - 1] || '';
findings.push({
id: 'T051',
severity: CRITICAL,
file: filePath,
line: lineNumber,
match: hookName,
message: `Invented hook — "${hookName}" does not exist in hooks-index.json`,
recommendation: 'Verify the hook exists via: node scripts/search-hooks.cjs --prefix "' + hookName + '"',
context: lineContent.trim().substring(0, 80)
});
}
}
return findings;
}
/**
* Check for hook pairing issues
*/
function analyzeHookPairing(filePath) {
const findings = [];
const content = fs.readFileSync(filePath, 'utf-8');
// Find all background hooks
const bgHookRegex = /--slds-g-color-(surface|accent|success|warning|error|info)(?:-container)?-\d/g;
const textHookRegex = /--slds-g-color-on-(surface|accent|success|warning|error|info)(?:-container)?-\d/g;
const bgHooks = content.match(bgHookRegex) || [];
const textHooks = content.match(textHookRegex) || [];
// Extract families
const bgFamilies = new Set(bgHooks.map(h => {
const match = h.match(/--slds-g-color-(\w+(?:-container)?)-\d/);
return match ? match[1] : null;
}).filter(Boolean));
const textFamilies = new Set(textHooks.map(h => {
const match = h.match(/--slds-g-color-on-(\w+(?:-container)?)-\d/);
return match ? match[1] : null;
}).filter(Boolean));
// Check for mismatches
for (const bgFamily of bgFamilies) {
const expectedTextFamily = bgFamily.replace('-container', '');
if (!textFamilies.has(expectedTextFamily) && !textFamilies.has(bgFamily)) {
findings.push({
id: 'T010',
severity: WARNING,
file: filePath,
message: `Background hook family '${bgFamily}' may lack matching text hook`,
recommendation: `Pair with --slds-g-color-on-${expectedTextFamily}-*`
});
}
}
return findings;
}
/**
* Calculate scores from findings
*/
function calculateScores(findings) {
const weights = {
[CRITICAL]: 10,
[WARNING]: 3,
[INFO]: 1
};
// NOTE: Linter findings (L001, L002, L003) come from the SLDS linter output,
// not from this script. They should be merged in by the calling agent.
// This script only produces findings for the other categories.
const categories = {
theming: { issues: 0, ids: ['T002', 'T010', 'T011', 'T021', 'T051'] },
accessibility: { issues: 0, ids: ['A001', 'A004', 'A005', 'A010', 'A020', 'A021', 'A022'] },
codeQuality: { issues: 0, ids: ['Q001', 'Q002', 'Q012', 'Q021', 'Q025'] },
componentUsage: { issues: 0, ids: ['C001', 'C002', 'C004'] }
};
// Count weighted issues per category
for (const finding of findings) {
const weight = weights[finding.severity];
for (const [category, config] of Object.entries(categories)) {
if (config.ids.includes(finding.id)) {
config.issues += weight;
break;
}
}
}
// Calculate scores
const scores = {};
for (const [category, config] of Object.entries(categories)) {
scores[category] = Math.max(0, 100 - config.issues);
}
return scores;
}
/**
* Get grade from score
*/
function getGrade(score) {
if (score >= 90) return 'A';
if (score >= 80) return 'B';
if (score >= 70) return 'C';
if (score >= 60) return 'D';
return 'F';
}
/**
* Main analysis function
*/
function analyze(componentPath) {
const resolvedPath = path.resolve(componentPath);
if (!fs.existsSync(resolvedPath)) {
console.error(`Error: Path does not exist: ${resolvedPath}`);
process.exit(1);
}
const findings = [];
// Find and analyze CSS files
const cssFiles = findFiles(resolvedPath, ['.css']);
for (const file of cssFiles) {
findings.push(...analyzeFile(file, PATTERNS.css));
findings.push(...analyzeHookPairing(file));
findings.push(...analyzeInventedHooks(file));
}
// Find and analyze HTML files
const htmlFiles = findFiles(resolvedPath, ['.html']);
for (const file of htmlFiles) {
findings.push(...analyzeFile(file, PATTERNS.html));
findings.push(...analyzeHeadings(file));
}
// Find and analyze JS files
const jsFiles = findFiles(resolvedPath, ['.js']);
for (const file of jsFiles) {
findings.push(...analyzeFile(file, PATTERNS.js));
}
// Calculate scores
const scores = calculateScores(findings);
// Organize findings by severity
const organized = {
critical: findings.filter(f => f.severity === CRITICAL),
warning: findings.filter(f => f.severity === WARNING),
info: findings.filter(f => f.severity === INFO)
};
// Calculate total lines for complexity classification
let totalLines = 0;
for (const file of [...cssFiles, ...htmlFiles, ...jsFiles]) {
totalLines += fs.readFileSync(file, 'utf-8').split('\n').length;
}
const totalFiles = cssFiles.length + htmlFiles.length + jsFiles.length;
let complexity = 'small';
if (totalFiles >= 7 || totalLines >= 500) complexity = 'large';
else if (totalFiles >= 3 || totalLines >= 100) complexity = 'medium';
// Build result
const result = {
component: path.basename(resolvedPath),
path: resolvedPath,
timestamp: new Date().toISOString(),
complexity: {
classification: complexity,
totalFiles,
totalLines
},
note: "These are automated category scores only. Combine them with SLDS linter results and the required Step 3 manual review gate in SKILL.md before making a final ship recommendation.",
scores: {
theming: { score: scores.theming, grade: getGrade(scores.theming) },
accessibility: { score: scores.accessibility, grade: getGrade(scores.accessibility) },
codeQuality: { score: scores.codeQuality, grade: getGrade(scores.codeQuality) },
componentUsage: { score: scores.componentUsage, grade: getGrade(scores.componentUsage) }
},
findings: organized,
summary: {
filesAnalyzed: totalFiles,
cssFiles: cssFiles.length,
htmlFiles: htmlFiles.length,
jsFiles: jsFiles.length,
totalLines,
critical: organized.critical.length,
warnings: organized.warning.length,
info: organized.info.length
}
};
return result;
}
// CLI entry point
if (require.main === module) {
const args = process.argv.slice(2);
const positionalArgs = args.filter((a, i) => !a.startsWith('--') && (i === 0 || !args[i - 1].startsWith('--')));
if (positionalArgs.length === 0) {
console.log('SLDS Quality Analyzer');
console.log('Usage: node analyze-quality.cjs <component-path> [--hooks-index <path>]');
console.log('');
console.log('Options:');
console.log(' --hooks-index <path> Path to hooks-index.json (optional; enables T051 invented-hook detection)');
console.log('');
console.log('Output: JSON analysis of SLDS quality issues');
process.exit(0);
}
HOOKS_INDEX_PATH = resolveHooksIndexPath(args);
const result = analyze(positionalArgs[0]);
console.log(JSON.stringify(result, null, 2));
}
module.exports = { analyze, PATTERNS };
SKILL.md
---
name: design-systems-slds-validate
description: "Audit Lightning Web Components for SLDS design-system compliance and produce a scored quality report. Runs the SLDS linter and analyzes CSS for theming hook usage and pairing, scoring SLDS findings across categories into an overall grade. Use when asked to \"score my component's SLDS\", \"SLDS scorecard\", \"SLDS quality report\", \"audit SLDS compliance\", \"how good is my SLDS\", \"check SLDS quality\", \"rate my SLDS styling\", \"evaluate my component's SLDS\", \"is this component's SLDS ready to ship?\", \"look at my LWC for SLDS issues\", \"audit SLDS before I submit\", \"review my component's SLDS before code review\", or any time a user wants an SLDS quality assessment or SLDS production-readiness check on an LWC. Not for fixing violations (use design-systems-slds2-migrate), building new components (use design-systems-slds-apply), or accessibility/WCAG/ARIA audits (use experience-accessibility-validate)."
metadata:
version: "1.0"
domains: ["Design Systems"]
relatedSkills:
- "design-systems-slds-apply"
- "design-systems-slds2-migrate"
- "experience-accessibility-validate"
cliTools:
- tool: ["npx"]
semver: ">=7.0.0"
- tool: ["node"]
semver: ">=18.0.0"
---
# SLDS Quality Audit
Audit Lightning Web Components for SLDS compliance and produce an automated scorecard plus a required manual review gate. Combines SLDS linter output with supplementary static analysis to catch what the linter misses.
## Scope
Also valid for: auditing SLDS compliance across a project or component set, and before/after quality comparison after making changes.
Not for:
- **Fixing** linter violations — use `design-systems-slds2-migrate` instead
- **Building** new components — use `design-systems-slds-apply` instead
- **Just running the linter** — run `npx @salesforce-ux/slds-linter@latest lint .` directly
- **Full WCAG accessibility audit** — this skill checks attribute presence only (labels, alt text, focus indicators), not contrast ratios, keyboard flows, or screen reader behavior
- **Framework-specific template auditing** beyond `.css`, `.html`, and `.js` files — JSX/TSX/Vue/Svelte outputs need additional manual review
---
## Quality Validation Process
```text
1. Run SLDS Linter → Collect violation counts (linter's job)
2. Run Analyze Script → Check what linter doesn't cover (supplementary)
3. Agent Review → Required manual review gate
4. Score & Grade → Compute automated score + final recommendation
5. Generate Report → Produce formatted scorecard
```
## Step 1: Run SLDS Linter
Run the linter to collect baseline violation data:
```bash
npx @salesforce-ux/slds-linter@latest lint <component-path> 2>&1
```
Count violations by rule. These feed directly into the **Linter Compliance** score:
| Rule | Impact |
|------|--------|
| `slds/class-override` | Breaks theming, dark mode |
| `slds/lwc-token-to-slds-hook` | SLDS 1 technical debt |
| `slds/no-hardcoded-values` | Breaks theming, accessibility |
**Linter Compliance Score** = `100 - (total_violations × 10)`, minimum 0.
**If the linter is unavailable** (no Node.js, no network access, CI sandbox restrictions): skip this step, note "Linter not run" in the report header, mark Linter Compliance as N/A, and compute the Overall score using the remaining 4 categories renormalized to 100%:
```text
Overall (linter unavailable) = (Theming × 0.29) + (Accessibility × 0.29)
+ (CodeQuality × 0.21) + (ComponentUsage × 0.21)
```
## Step 2: Run Supplementary Analysis
Run the analyze script to catch issues the linter doesn't cover. The bundled analyzer scans `.css`, `.html`, and `.js` files only:
```bash
node scripts/analyze-quality.cjs <component-path>
```
The script outputs JSON with findings organized by severity. It checks:
### CSS Checks (linter-complementary)
| Check | What It Catches | Severity |
|-------|----------------|----------|
| Missing fallbacks | `var(--slds-g-*)` without a fallback value | Critical |
| Invented hooks (T051) | `--slds-g-*` tokens not found in `hooks-index.json` (requires `--hooks-index`) | Critical |
| Hook pairing | Background hooks without matching foreground hooks | Warning |
| `!important` | Specificity overrides | Warning |
| Magic pixel values | Hardcoded `px` not using spacing hooks | Warning |
| High z-index | z-index values > 99 | Warning |
| Outline removal | `outline: none` without alternative focus style | Warning |
### JS Checks
| Check | What It Catches | Severity |
|-------|----------------|----------|
| Inline style assignment | `.style.*=` direct property assignment | Warning |
| SLDS class manipulation | Dynamic `.classList.add('slds-*')` manipulation | Warning |
### HTML Checks
| Check | What It Catches | Severity |
|-------|----------------|----------|
| LBC input labels | `<lightning-input>` without `label` attribute | Critical |
| Icon alt text | `<lightning-icon>` without `alternative-text` | Critical |
| Image alt text | `<img>` without `alt` | Critical |
| Heading hierarchy | Skipped heading levels (h2 to h4) | Warning |
| Positive tabindex | `tabindex` values other than 0 or -1 | Warning |
| Clickable divs | `<div onclick>` instead of `<button>` | Warning |
| Inline styles | `style="..."` attributes | Warning |
| Native elements | `<input>`, `<button>`, `<select>` where LBC alternatives exist | Warning |
### Hook Pairing Validation
The script checks that background/foreground hooks are semantically paired:
```text
surface-* backgrounds → on-surface-* text
surface-container-* bg → on-surface-* text
accent-* backgrounds → on-accent-* text
accent-container-* bg → on-accent-* text
```
> **Limitation:** Hook pairing is checked at the file level, not per-selector. A file with `surface-1` in `.classA` and `on-accent-1` in `.classB` would pass because both surface and accent families are present. Review pairing correctness per-selector during manual review (Step 3).
### Invented Hook Detection (T051)
The script cross-references every `--slds-g-*` token in CSS against `hooks-index.json`. Any hook not found in metadata is flagged as critical — this catches the most common agent mistake of inventing hooks from naming patterns.
## Step 3: Agent Manual Review
These checks require understanding the component's purpose and cannot be automated reliably. Review each and classify findings as either:
- **Blocking** — incorrect blueprint structure, missing required states, or semantic/interaction issues that make the component not production-ready
- **Advisory** — worthwhile improvements that do not block shipping on their own
| Review Area | What to Look For |
|-------------|-----------------|
| Loading states | Does the component show a spinner or skeleton when fetching data? |
| Error states | Are errors surfaced to the user with actionable messages? |
| Empty states | Is there a meaningful empty state when no data exists? |
| Disabled states | Do interactive elements visually and functionally handle disabled? |
| Semantic HTML | Are `<nav>`, `<article>`, `<section>` used where appropriate? |
| SLDS blueprint compliance | Do cards, modals, forms follow SLDS blueprint structure? |
> Manual review findings are not automated, but they do affect the final recommendation. Do not report an automated grade as the only verdict.
## Step 4: Calculate Automated Scores and Final Recommendation
### Component Complexity
Before scoring, classify the component to give the score context:
| Complexity | Criteria | Report Note |
|------------|----------|-------------|
| Small | 1-2 files, < 100 total lines | Score is high-confidence (small surface area) |
| Medium | 3-6 files, 100-500 total lines | Score reflects typical component |
| Large | 7+ files, 500+ total lines | Score reflects absolute issue count — even well-built large components may score lower |
Include the complexity classification in the report header. This prevents misreading a "B" on a 1000-line component vs. a "B" on a 20-line component.
### Automated Scoring Formula
```text
Category Score = 100 - (critical_issues × 10) - (warnings × 3) - (info × 1)
Minimum score: 0
```
### Categories and Weights
| Category | Weight | Source |
|----------|--------|--------|
| Linter Compliance | 30% | SLDS linter output (Step 1) |
| Theming | 20% | Script: fallbacks, hook pairing (Step 2) |
| Accessibility | 20% | Script: labels, alt text, focus (Step 2) |
| Code Quality | 15% | Script: !important, inline styles, z-index (Step 2) |
| Component Usage | 15% | Script: native elements (Step 2) plus manual semantic/blueprint review (Step 3) |
### Automated Overall Score
```text
Overall = (Linter × 0.30) + (Theming × 0.20) + (Accessibility × 0.20)
+ (CodeQuality × 0.15) + (ComponentUsage × 0.15)
```
### Automated Grade Thresholds
| Score | Grade | Meaning |
|-------|-------|---------|
| 90-100 | A | Excellent automated score |
| 80-89 | B | Good automated score |
| 70-79 | C | Acceptable automated score |
| 60-69 | D | Weak automated score |
| 0-59 | F | Failing automated score |
### Manual Review Gate
After computing the automated score, apply the manual review outcome:
| Gate | When to use it | Effect on final recommendation |
|------|----------------|-------------------------------|
| Pass | No manual findings | Final recommendation can follow the automated score |
| Advisory | Only non-blocking manual findings | Final recommendation can be "Ready with follow-ups" at best |
| Blocking | One or more blocking manual findings | Final recommendation is **not ready for production**, regardless of automated grade |
### Final Recommendation Rules
Use both the automated score and the manual review gate:
| Final Recommendation | Conditions |
|----------------------|------------|
| Ready for production | Automated grade A/B, no critical findings, manual gate = Pass |
| Ready with follow-ups | Automated grade A/B, no critical findings, manual gate = Advisory |
| Needs work | Any critical findings, automated grade C/D, or manual gate = Blocking |
| Failing | Automated grade F |
## Step 5: Generate Quality Report
Use the template in **[report-format.md](references/report-format.md)** to produce the final report. Default to the **compact format** for initial output and expand sections on request.
The report includes:
- Executive summary with automated grade and final recommendation
- Manual review gate outcome (`Pass`, `Advisory`, or `Blocking`)
- Scores by category with visual indicators
- Detailed findings organized by severity
- Specific code locations and recommendations
- Checklist of required actions
---
## Quick Validation Mode
For a rapid quality check without full analysis:
1. Run linter: `npx @salesforce-ux/slds-linter@latest lint <path>`
2. Count violations by type
3. Report summary only
```text
Quick Quality Check: <component-name>
─────────────────────────────────────
Linter Violations:
• Class Override: 0
• Deprecated Tokens: 3
• Hardcoded Values: 5
Quick Automated Grade: C (estimated)
Run full validation for detailed report.
```
---
## Edge Cases and False Positives
| Situation | Guidance |
|-----------|----------|
| **Headless components** (JS-only, no HTML) | Skip HTML checks; score only CSS + linter categories |
| **Wrapper/container components** | May legitimately have minimal CSS; don't penalize low hook usage |
| **Intentional native elements** | `<button>` inside custom SLDS blueprints is correct; suppress C002 if inside an `slds-*` blueprint structure |
| **Components outside LEX** | LWR/Experience Cloud components may not use Lightning Base Components; note context in report |
| **Test/demo components** | Lower the bar — note in report but don't block on warnings |
If a check produces a false positive, note it in the report as "suppressed" with justification rather than silently dropping it.
---
## References
- **[Quality Checks](references/quality-checks.md)** - Complete list of all quality checks with detection patterns
- **[Report Format](references/report-format.md)** - Quality report template and formatting guide
- **[Analyze Script](scripts/analyze-quality.cjs)** - Automated analysis for linter-complementary checks
- **design-systems-slds2-migrate skill** - How to fix linter violations
- **design-systems-slds-apply skill** - Guide for building new components with correct patterns