The Design Engineer's Agent Stack

An AI coding agent can pass every test you have and still set a subtitle at 19px, hardcode #cccccc, and shift the layout on a phone. Tests check logic. No agent setup I have used checks craft until someone adds the checks. This post builds that layer: six checks that hold an agent’s work to a type scale, a color system, a stable layout, a Lighthouse budget, WCAG rules, and approved screenshots. The token checks run in three places, and the first is a hook that tells the agent about a violation while it is still working. The other checks run as commands, on your machine or in CI. I ran the configs and scripts below against the examples in this post before printing them, and a section near the end says what I tested and what I did not. Two sections after the checks, The Taste Layer and What the Stack Buys, cover what none of the checks can judge, which is whether the result is good. The FAQ and three reference sections come after them.

Update, November 16, 2026: I rebuilt this post. The April version described the stack as infrastructure I run, which I do not, and its snippets had not been run. Several of its numbers about this site were wrong. What changed from the April version lists each correction.

TL;DR

  • Design quality splits into parts a machine can check (token use, layout stability, performance budgets, WCAG rules, unintended visual change) and one it cannot (taste).
  • One Stylelint config, built-in rules only, reports the ordinary raw value: a font size, weight, spacing value or color that is not a token. One 150-line script reports the problems in declarations a change introduces. Both are a lint for honest mistakes, not a security boundary. The script runs in three places: a Claude Code PostToolUse hook, a git pre-commit hook, and CI.
  • Three Playwright specs cover layout at three widths, an axe scan with WCAG 2.2 tags, and screenshot baselines. Lighthouse CI holds the category scores and Cumulative Layout Shift.
  • I do not run this stack on this site. Counted on November 16, 2026, its CSS holds 691 raw font sizes beside 548 token uses and 2,850 raw color declarations, and its tertiary text color measures 3.66:1 on black, under the 4.5:1 that WCAG AA asks of body text. That drift is the argument for the stack.
  • Passing all six checks says no configured check found a violation in the files, pages and widths it covers. It does not say the work is good.

What Design Engineers Need From Agents

A pure engineer asks whether the code works. A design engineer asks six more questions.

Visual consistency. Spacing comes from the spacing scale, so the gaps between elements repeat. An agent that adds a card with margin-top: 13px instead of var(--spacing-md) has added noise that no unit test sees.

Typography discipline. Each font-size is a step in the type scale, and each font-weight is one of the weights the system defines. An agent that sets a subtitle to font-size: 19px has invented a step, and the hierarchy gets a little less legible.

Color system compliance. Each color is a token. An agent that writes color: #cccccc has made a contrast decision nobody reviewed. On this site’s dark theme that gray measures 13.08:1 against the black page. On the light theme the same literal sits on off-white at 1.53:1, far under the 4.5:1 that WCAG asks of body text, because a hardcoded value does not change when the theme does.1

Performance awareness. A visual change has a performance cost. Google’s Core Web Vitals put numbers on it: Largest Contentful Paint within 2.5 seconds, Cumulative Layout Shift of 0.1 or less, and Interaction to Next Paint of 200 milliseconds or less, each at the 75th percentile of real page loads.2 A lab run cannot see real users, but it can catch a regression before they do.

Accessibility. Semantic structure, heading order, labels, contrast, focus. A scanner finds the measurable part. The rest takes a keyboard, a screen reader, and a person.

Taste. The hardest to encode: coherence between elements, restraint in decoration, white space that is intended and not left over. Taste separates a layout that follows every rule and feels wrong from one that follows every rule and feels right.

Taste is a technical system with four parts: constraints, evaluation criteria, pattern recognition, and coherence. The first five questions fall under the first two parts. A token rule is a constraint and a budget is an evaluation criterion, and a machine can check both. The sixth question belongs to pattern recognition and coherence, which stay with a person.

Six Components of the Design Engineer’s Stack

None of the parts is new. Stylelint lints CSS, Lighthouse CI asserts on Lighthouse reports, axe-core scans a rendered page for WCAG failures, and Playwright compares screenshots. What an agent setup usually lacks is the assembly: the checks configured for one design system and placed where the agent gets the result while it is still working.

Component Question it answers Tool
1. Type and spacing tokens Is every size, weight and gap a step in a scale? Stylelint
2. Color tokens Is every color a token? Stylelint
3. Layout checks Does the page fit and hold still at the widths you list? Playwright
4. Lighthouse budget Does the page meet the budgets you set for performance and the audited basics? Lighthouse CI
5. Accessibility scan Does the rendered page break a WCAG rule a tool can detect? axe-core in Playwright
6. Visual regression Did anything change that was not meant to? Playwright

1. Type and Spacing Tokens

Robert Bringhurst’s rule for type sizes: “Use the old familiar scale, or use new scales of your own devising, but limit yourself, at first, to a modest set of distinct and related intervals.”3 In CSS the scale is a set of custom properties, and the check is that a size is written as one of them. Stylelint can make that check with rules it ships with.4 This is the whole .stylelintrc.json. Four of its patterns begin with the same long lookbehind, which only requires that the match is not inside a quoted string; the part to read in each is its tail. The token names are this site’s, so substitute yours:

{
  "rules": {
    "declaration-property-value-allowed-list": {
      "/^font-size$/i": ["/^var\\(--font-size-(xs|sm|base|lg|xl|[2-7]xl|display)\\)$/", "inherit"],
      "/^font-weight$/i": ["/^var\\(--font-weight-(normal|medium|semibold|bold|black)\\)$/", "inherit"],
      "/^(margin|padding|gap|row-gap|column-gap)/i": ["/^((var\\(--spacing-(xs|sm|md|lg|xl|[2-4]xl)\\)|0|auto)(\\s+|$))+$/"]
    },
    "declaration-property-value-disallowed-list": {
      "/^(?!--)/": [
        "/(?<=^([^\"']|\"(\\\\[\\s\\S]|[^\"\\\\])*\"|'(\\\\[\\s\\S]|[^'\\\\])*')*)(?<!url\\([^)\"']*)#[0-9a-f]{3,8}\\b/i",
        "/(?<=^([^\"']|\"(\\\\[\\s\\S]|[^\"\\\\])*\"|'(\\\\[\\s\\S]|[^'\\\\])*')*)\\b(rgba?|hsla?|hwb|lab|lch|oklab|oklch|color|color-mix)\\(/i",
        "/(?<=^([^\"']|\"(\\\\[\\s\\S]|[^\"\\\\])*\"|'(\\\\[\\s\\S]|[^'\\\\])*')*)\\\\/",
        "/(?<=^([^\"']|\"(\\\\[\\s\\S]|[^\"\\\\])*\"|'(\\\\[\\s\\S]|[^'\\\\])*')*)\\/\\*/"
      ]
    },
    "color-named": ["never", { "ignoreProperties": ["/^--/"] }],
    "property-disallowed-list": ["/^font$/i", "/\\\\/"]
  }
}

Take the three mistakes from the section above, plus a weight the system does not define:

.card { margin-top: 13px; }
.card-title { font-size: 19px; font-weight: 650; }
.card-meta { color: #cccccc; }

Stylelint reports each one:

$ npx stylelint examples/card.css

examples/card.css
  1:21  ✖  Disallowed value "13px" for property "margin-top"  declaration-property-value-allowed-list
  2:26  ✖  Disallowed value "19px" for property "font-size"   declaration-property-value-allowed-list
  2:45  ✖  Disallowed value "650" for property "font-weight"  declaration-property-value-allowed-list
  3:21  ✖  Disallowed value "#cccccc" for property "color"    declaration-property-value-disallowed-list

✖ 4 problems (4 errors, 0 warnings)

Before the details, what this config is for. It catches the ordinary mistake, a raw size, a raw color or a weight with no token, at the moment an agent or a person makes it. It is a lint, not a security boundary. CSS has many ways to spell one thing, and CSS written to get past these patterns can get past them. It does report the evasions I know of: property names in capitals, escapes such as f\6f nt-size, a string continued over a line, a quote hidden in a comment inside a value, mostly by refusing the construct outright. Three things it does not cover are listed under the color rules, and How I Tested This says how those evasions were found.

Six choices in these rules are deliberate:

  • Property names match in any case. Each key is a regular expression with the i flag, because CSS property names are case-insensitive and FONT-SIZE: 19px is the same declaration as font-size: 19px.
  • Steps are listed by name. var(--font-size-md) fails because the scale has no md step, and var(--font-size-lg, 19px) fails because a raw fallback is a second, unreviewed size.
  • The font shorthand is disallowed. font: 600 19px/1.2 system-ui sets a size and a weight in a property the first rule never reads.
  • Backslash escapes are rejected. CSS lets f\6f nt-size stand for font-size and r\67 b( for rgb(. These rules compare the text as written and do not decode escapes, so the config reports a backslash in a property name, and one in the value of a property that is not a custom property when it sits outside a quoted string.
  • A comment left inside a value is refused. Stylelint’s parser drops a comment that has space around it, as in 0 /* note */ auto, but in my tests it kept one that touches its neighbors, as in url(a)/*x*/#fff. A quote inside a kept comment would throw off the string handling described under the color rules, so the config reports /* outside a quoted string in those values.
  • Spacing takes tokens, 0 or auto. The key covers margin, padding and gap with their longhands, row-gap and column-gap included. Offsets such as top and inset are left to you: add them if your layout sets them from the scale. A value that has to break the rule, such as a negative margin built with calc(), gets a stylelint-disable-next-line comment with a reason. The exception then sits in the diff where a reviewer sees it.

2. Color Tokens

The color rules are in the same file. declaration-property-value-disallowed-list is keyed on /^(?!--)/, which matches every property that is not a custom property, and its patterns look for a hex value, a color-function name, a backslash or a comment marker in the value. color-named reports red, with custom properties exempted through its ignoreProperties option. Together they aim at one thing: a raw color belongs in the value of a custom property and not elsewhere.

Stylelint parses the file, so it knows which property each value belongs to. A token defined in the middle of a multi-line :root block passes, and border: 1px solid rgba(255, 255, 255, 0.6) fails although the color is the third word of the value. The value itself is still matched as text, not parsed. Each pattern therefore begins with a lookbehind that requires every quote before the match to be closed, including a string that an escaped line break continues onto the next line, which keeps content: "#123" and url("sprite(1).svg#fade") from being read as colors. The hex pattern has a second lookbehind for an unquoted url(sprite.svg#fade). This is pattern matching with patches, not a CSS value parser, and it holds for the cases I tested.

Three limits. The rule does not stop an agent from defining a new custom property and using it. That arrives in the diff as a new token, which is the right thing for a person to review. color-named does not report transparent, currentColor or system color keywords such as CanvasText, so those pass. And a token is not a contrast guarantee. My tertiary text token is white at 40% opacity. On the black page it composites to 3.66:1, which clears WCAG’s 3:1 for large text and misses the 4.5:1 for body-size text.15 Contrast belongs to the accessibility scan in component 5.

3. Layout Checks

Two failures hide at widths nobody looked at: content wider than the viewport, and content that moves after it paints. Components 3, 5 and 6 are Playwright specs, and they share one playwright.config.js that starts the site and sets the base URL. The test site is two small static pages, / and /blog/:

import { defineConfig } from '@playwright/test';

export default defineConfig({
  testDir: 'tests',
  use: { baseURL: 'http://127.0.0.1:4173' },
  webServer: {
    // Any command that serves the site on this port.
    command: 'python3 -m http.server 4173 --directory site',
    url: 'http://127.0.0.1:4173',
    reuseExistingServer: !process.env.CI,
  },
});

The layout spec loads the page at three widths and asserts on both failures:

import { test, expect } from '@playwright/test';

for (const width of [375, 768, 1440]) {
  test(`layout holds at ${width}px`, async ({ page }) => {
    await page.setViewportSize({ width, height: 900 });
    await page.addInitScript(() => {
      window.layoutShift = 0;
      new PerformanceObserver((list) => {
        for (const entry of list.getEntries())
          if (!entry.hadRecentInput) window.layoutShift += entry.value;
      }).observe({ type: 'layout-shift', buffered: true });
    });
    await page.goto('/');
    await page.waitForTimeout(1000);

    const { measured, overflow, shift } = await page.evaluate(() => ({
      measured: PerformanceObserver.supportedEntryTypes.includes('layout-shift'),
      overflow: document.documentElement.scrollWidth - document.documentElement.clientWidth,
      shift: window.layoutShift,
    }));
    expect(measured, 'browser reports layout-shift entries').toBe(true);
    expect(overflow, 'pixels of horizontal overflow').toBe(0);
    expect(shift, 'layout shift during load').toBeLessThanOrEqual(0.1);
  });
}

The shift number is the sum of the layout-shift entries the page’s main frame reports from navigation until one second after the load event. CLS is the largest burst of shifts, not the total, so for the entries that window observes, the sum is at least as large as their CLS, and holding it to 0.1 is at least as strict.6 It is not a CLS measurement. CLS covers the whole life of the page and counts shifts inside iframes; the spec sees neither a shift that happens later, such as one after an interaction, nor one inside an iframe. The first assertion makes the test fail in a browser that does not report layout-shift entries, so the spec cannot pass without measuring. I ran it in Playwright’s Chromium, where it measures, and in Playwright’s WebKit, where that assertion failed.

Against the clean home page all three widths passed. Against a copy that injects a banner 240px tall 300 milliseconds after load and contains a block with a fixed width of 600px, all three failed: the 375px test with 249 pixels of horizontal overflow, the 768px test, where the block fits, with a shift of 0.227, and the 1440px test with a shift of 0.107.

4. Lighthouse Budget

Lighthouse CI runs Lighthouse several times against a served page and fails the build when an assertion does not hold. This is lighthouserc.json:

{
  "ci": {
    "collect": {
      "startServerCommand": "python3 -u -m http.server 4173 --directory site",
      "startServerReadyPattern": "Serving HTTP",
      "url": ["http://127.0.0.1:4173/", "http://127.0.0.1:4173/blog/"],
      "numberOfRuns": 3
    },
    "assert": {
      "assertions": {
        "categories:performance": ["error", { "minScore": 0.9, "aggregationMethod": "median" }],
        "categories:accessibility": ["error", { "minScore": 1, "aggregationMethod": "pessimistic" }],
        "categories:best-practices": ["error", { "minScore": 1, "aggregationMethod": "pessimistic" }],
        "categories:seo": ["error", { "minScore": 1, "aggregationMethod": "pessimistic" }],
        "cumulative-layout-shift": ["error", { "maxNumericValue": 0.1, "aggregationMethod": "pessimistic" }]
      }
    }
  }
}

What the keys do, from the Lighthouse CI configuration docs:7

  • categories:<id> asserts on a category score from 0 to 1. A bare performance is not a category key. Lighthouse CI reads it as an audit ID, finds no such audit, and fails the run whatever the score was.
  • cumulative-layout-shift is an audit ID, asserted on its numeric value. The 0.1 limit is Google’s line for a good score.6 Set it lower if the page already sits under a lower number.
  • numberOfRuns collects three reports for each URL, because scores move between runs.
  • aggregationMethod sets how the asserted value is aggregated across the three runs before it is compared with the threshold. The default is optimistic, the value most likely to pass, so I set it by hand: median for performance, the noisy score, and pessimistic, the value least likely to pass, for the rest.
  • startServerCommand is whatever serves your site, and startServerReadyPattern is the text it prints once it is listening.

Set each minimum at a number the page holds today. A budget the page already misses fails every build and says nothing about the change in front of it. These are absolute budgets, not a comparison with the previous build: a performance score that falls from 100 to 95 still passes a minimum of 0.9.

npx lhci autorun exited 0 on the clean test site. On the copy with the late banner it exited 1 with CLS at 0.232 against the 0.1 limit and performance at 0.89 against 0.9. On a copy with low-contrast text it exited 1 with accessibility at 0.9. By default Lighthouse loads the page at one emulated phone width, 412px in the reports I collected, which is why the layout spec in component 3 checks each width on its own.

5. Accessibility Scan

axe-core runs inside a real browser against the rendered page, so it works from computed styles and not from markup alone. @axe-core/playwright puts it in a Playwright test:

import { test, expect } from '@playwright/test';
import AxeBuilder from '@axe-core/playwright';

for (const path of ['/', '/blog/']) {
  test(`axe finds no WCAG A or AA violations on ${path}`, async ({ page }) => {
    await page.goto(path);
    const results = await new AxeBuilder({ page })
      .withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'wcag22aa'])
      .analyze();
    expect(results.violations).toEqual([]);
  });
}

Each tag covers one WCAG version at one level, so wcag22aa alone would run only what WCAG 2.2 added at AA. The list names every version and level the scan should include.8 The 2.2 tag belongs there: W3C “advises the use of WCAG 2.2 to maximize future applicability of accessibility efforts.”1 The assertion is toEqual([]), with no allowance for known violations. axe also returns an incomplete array, which its documentation calls review items: nodes it could not decide either way. This spec does not read it, so a pass means axe found no failure it was sure of, not that nothing needs review.8

Against a copy of the test site whose card text was white at 40% opacity on #111111, the scan failed the home page on axe’s color-contrast rule: 3.81:1 measured, 4.5:1 expected. The second page, which that change did not touch, passed, and both pages of the clean site passed.

What a scan cannot find stays manual. Playwright’s documentation says so directly: “many accessibility problems can only be discovered through manual testing.”9 Focus after an HTMX swap, keyboard order through dynamic content, and what a screen reader announces on a state change need scripted interaction or a person.

6. Visual Regression

The five checks above each test a property. A screenshot comparison is the broad one: it fails when a captured page differs, by more than the tolerance you set, from the last version a person approved. Playwright’s toHaveScreenshot does it in a few lines:

import { test, expect } from '@playwright/test';

for (const width of [375, 768, 1440]) {
  test(`home page matches its baseline at ${width}px`, async ({ page }) => {
    await page.setViewportSize({ width, height: 900 });
    await page.goto('/');
    await expect(page).toHaveScreenshot(`home-${width}.png`, {
      fullPage: true,
      maxDiffPixelRatio: 0.001,
    });
  });
}

The first run has nothing to compare against. It writes the baseline images and fails with a message that begins “A snapshot doesn’t exist.” Later runs compare, and maxDiffPixelRatio lets one pixel in a thousand differ before a test fails. Whether a pixel counts as different is a separate setting, threshold, which I left at its default of 0.2.10 To stand in for a side effect, I added 3px of padding to the card, a change small enough to miss in review. All three widths failed. At 375px the page had grown from 1002px to 1010px tall, and 7,064 pixels differed.

Three things to know before trusting it. Baselines belong to a platform: mine were written as home-375-darwin.png, and Playwright warns that rendering varies with the OS, hardware and headless mode, so the baselines have to come from the environment that will compare them.10 A screenshot covers only what it captures: here, one page at three widths, at rest, with nothing hovered, focused or open. And a diff says that something changed, not whether the change is an improvement. A person looks at the diff, then fixes the page or accepts the new look with npx playwright test --update-snapshots.

Hosted services such as Percy and Chromatic pair the same kind of comparison with a review screen. BackstopJS, which the earlier version of this post named beside them, now opens its README with “BackstopJS needs a new maintainer/owner.”11

Where the Checks Run

A check that runs after the agent has finished produces a report for me to read. A check that runs while the agent works gives it the chance to correct the line. The token rules run in three places from one script, tools/token-lint.mjs.

My codebase is not clean, and many are not. A check that answers every edit with hundreds of old problems is unusable, so the script reports what the change introduces.

It lints the whole file and reports the problems in declarations the change introduces, along with any problem that sits outside every declaration, such as a syntax error. As a hook it compares the file on disk with the last commit; at commit (--cached), the staged copy with the last commit; in CI (a range A...B), the commit at B with the merge base of A and B. The rule I am aiming at is short: if the earlier version holds the same declaration, character for character, under the same headers, it is not new; otherwise it is. When in doubt, the script would rather report an old problem again than miss a new one. What Counts as New has the whole rule; this is the script:

#!/usr/bin/env node
// Reports Stylelint problems only in the CSS declarations a change introduces.
//   Claude Code PostToolUse hook:  node tools/token-lint.mjs          (tool call JSON on stdin)
//   git pre-commit hook:           node tools/token-lint.mjs --cached
//   CI:                            node tools/token-lint.mjs origin/main...HEAD
import { execFileSync } from 'node:child_process';
import { readFileSync } from 'node:fs';
import { basename, dirname } from 'node:path';
import postcss from 'postcss';
import stylelint from 'stylelint';

// File names are passed to git as literal paths, never as patterns.
const git = (...args) =>
  execFileSync('git', args, {
    encoding: 'utf8',
    env: { ...process.env, GIT_LITERAL_PATHSPECS: '1' },
    maxBuffer: 64 * 1024 * 1024,
    stdio: ['ignore', 'pipe', 'ignore'],
  });

// Runs git for the two calls that locate the repository; outside one, says so and stops.
// Only git's closing newline is removed, because a path may begin or end with a space.
const repo = (...args) => {
  try {
    return git('rev-parse', ...args).replace(/\n$/, '');
  } catch {
    console.error('token-lint: not inside a git repository, so nothing was checked.');
    process.exit(1);
  }
};

const [range = 'HEAD'] = process.argv.slice(2);
const hook = process.argv.length === 2;
let files;
if (hook) {
  const file = JSON.parse(readFileSync(0, 'utf8')).tool_input?.file_path ?? '';
  if (!file.endsWith('.css')) process.exit(0);
  process.chdir(dirname(file));
  files = [repo('--show-prefix') + basename(file)];
}
process.chdir(repo('--show-toplevel'));
if (!hook) {
  files = git('diff', '--name-only', '-z', '--diff-filter=ACMR', range).split('\0');
  files = files.filter((file) => file.endsWith('.css'));
}

// The two versions each mode compares. An empty revision is the index; null is the file on disk.
//   hook, or one revision:  that revision (HEAD for the hook)  ->  disk
//   --cached:               HEAD                               ->  index
//   A...B (or A..B):        the merge base of A and B (or A)   ->  B
const dots = /\.\.\.?/;
function versions() {
  if (range === '--cached') return ['HEAD', ''];
  if (!dots.test(range)) return [range, null];
  const [a, b] = range.split(dots).map((revision) => revision || 'HEAD');
  return [range.includes('...') ? git('merge-base', a, b).trim() : a, b];
}
const [before, after] = versions();
const show = (revision, file) => git('show', `${revision}:${file}`);

// CSS turns CRLF, a lone CR and a form feed into LF before it reads anything, so both versions
// get the same treatment. Nothing else in the text is changed before it is compared.
const lf = (code) => code.replace(/\r\n?|\f/g, '\n');

// Every declaration in a stylesheet, keyed by source text alone: the characters of the
// declaration itself, and before them the header of each rule and at-rule around it, from the
// header's first character through its opening brace. Where the text cannot be pinned down
// exactly, the key is a symbol, which equals nothing, so the declaration counts as new.
function declarations(code) {
  const root = postcss.parse(code);
  const { css } = root.source.input; // the text PostCSS read: the same, less a byte-order mark
  const lineStart = [0];
  for (let i = css.indexOf('\n'); i !== -1; i = css.indexOf('\n', i + 1)) lineStart.push(i + 1);
  const index = ({ line, column }) => lineStart[line - 1] + column - 1;

  // PostCSS does not record where a header's brace is. Its length comes from the pieces PostCSS
  // parsed, and the text is used only if the file holds exactly those characters there.
  const header = ({ type, name, params, selector, raws, source }) => {
    const pieces =
      type === 'atrule'
        ? ['@', name, raws.afterName, raws.params?.raw ?? params, raws.between, '{']
        : [raws.selector?.raw ?? selector, raws.between, '{'];
    const from = index(source.start);
    const text = css.slice(from, from + pieces.join('').length);
    return text === pieces.join('') ? text : Symbol('header not found');
  };

  // A declaration ends at its semicolon. Without one, PostCSS drops trailing white space from
  // the end it reports, escaped white space included, so the text runs on to the closing brace
  // of the rule around it (or to the end of the file, outside any rule).
  const declaration = ({ parent, source: { start, end } }) => {
    if (css[index(end)] === ';') return css.slice(index(start), index(end) + 1);
    if (parent.type === 'root') return css.slice(index(start));
    const brace = index(parent.source.end);
    return css[brace] === '}' ? css.slice(index(start), brace) : Symbol('closing brace not found');
  };

  const found = [];
  root.walkDecls((decl) => {
    const { start, end } = decl.source;
    const parts = [declaration(decl)];
    for (let node = decl.parent; node.type !== 'root'; node = node.parent)
      parts.unshift(header(node));
    const key = parts.some((part) => typeof part === 'symbol') ? Symbol() : JSON.stringify(parts);
    found.push({ key, start, end });
  });
  return found;
}
// A version that is missing or does not parse has no declarations.
const declarationsOrNone = (read) => {
  try {
    return declarations(read());
  } catch {
    return [];
  }
};
const notAfter = (a, b) => a.line < b.line || (a.line === b.line && a.column <= b.column);

const problems = [];
for (const file of files) {
  const code = lf(after === null ? readFileSync(file, 'utf8') : show(after, file));
  // Count each declaration of the earlier version; one in the new version is new when no
  // earlier declaration with the same key is left to pair it with.
  const earlier = new Map();
  for (const { key } of declarationsOrNone(() => lf(show(before, file))))
    earlier.set(key, (earlier.get(key) ?? 0) + 1);
  const current = declarationsOrNone(() => code);
  const introduced = new Set(
    current.filter(({ key }) => {
      const left = earlier.get(key) ?? 0;
      earlier.set(key, left - 1);
      return left < 1;
    }),
  );

  const { results } = await stylelint.lint({ code, codeFilename: file });
  for (const w of results[0].warnings) {
    const decl = current.find(({ start, end }) => notAfter(start, w) && notAfter(w, end));
    // A problem outside every declaration, such as a syntax error, is always reported.
    if (!decl || introduced.has(decl)) problems.push(`${file}:${w.line}:${w.column}  ${w.text}`);
  }
}

if (problems.length) {
  console.error(
    `Design tokens: ${problems.length} problem(s) in declarations this change introduces. ` +
      `Use a token defined in :root instead of a raw value.\n${problems.join('\n')}`,
  );
  process.exit(2);
}

The script needs PostCSS beside Stylelint (npm install --save-dev stylelint postcss).

While the Agent Edits

This goes in .claude/settings.json:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "node",
            "args": ["${CLAUDE_PROJECT_DIR}/tools/token-lint.mjs"]
          }
        ]
      }
    ]
  }
}

Claude Code runs a PostToolUse hook after a tool call succeeds and passes the call as JSON on stdin. For Edit and Write the path is in tool_input.file_path. A shell command has no such field, so the script exits quietly for it, as it does for any file that is not a stylesheet.12 Because the write has already happened, the script reads the finished file from disk, which is how a token defined mid-block gets judged in context. Exit code 2 does not undo the write. It shows the script’s stderr to the model: the file, the line, and the value that is not a token.

I tested the hook two ways. First I piped it the JSON that the hooks reference documents for each tool:

Input Result
Edit that adds font-size: 19px exit 2, names the line
Edit that adds font-size: 1.25rem or .5rem exit 2
Edit that adds font-weight: 800 exit 2
Edit that adds FONT-SIZE: 19px in capitals exit 2
Edit that changes only the second line of a two-line margin to 13px exit 2
Edit that deletes only the comment marks around an old font-size: 19px exit 2
Edit that only re-indents an old rule and its declarations exit 0
Edit that moves an old rule’s opening brace to its own line exit 2
Edit that wraps the value of an old margin: 13px … onto two lines exit 2
Edit that adds color: #cccccc exit 2
Write that creates a stylesheet with a raw size and a raw color exit 2, two problems
Edit that uses tokens only exit 0
Edit that adds a token inside a multi-line :root {} exit 0
Clean Edit in a file with an old font-size: 15px exit 0
Bash running git commit -m "fix #123 header" exit 0
Edit to a Markdown file that mentions font-size: 19px exit 0

Then I ran it in a real session: Claude Code 2.1.325, headless, in a scratch project with this configuration. I asked it to append .badge { font-size: 19px; } to a stylesheet with one Edit. The edit landed, the hook ran, and the session received this:

PostToolUse:Edit hook blocking error from command: "node ${CLAUDE_PROJECT_DIR}/tools/token-lint.mjs": [node ${CLAUDE_PROJECT_DIR}/tools/token-lint.mjs]: Design tokens: 1 problem(s) in declarations this change introduces. Use a token defined in :root instead of a raw value.
static/css/site.css:12:21  Disallowed value "19px" for property "font-size" (declaration-property-value-allowed-list)

That is one live case, not the whole table. It shows the configuration loads and the message reaches the agent; the raw value stays in the file until the agent or a person fixes it.

One gap: the hook does not see CSS that the agent rewrites through a shell command. The reference says a PostToolUse hook matching Edit|Write does not run when a Bash command rewrites the same file.12 The next two places cover that.

At Commit

#!/bin/sh
exec node tools/token-lint.mjs --cached

Saved as .git/hooks/pre-commit and made executable, this lints the staged version of each staged stylesheet. In a scratch repository it stopped a commit that staged font-size: 19px, let a commit through that used tokens, and judged the staged content when the working copy differed from it. Git’s documentation says the hook “can be bypassed with the --no-verify option,”13 so it is a convenience for the honest case and not the gate.

In CI

#!/bin/sh
# Stops at the first check that fails and exits with that check's status.
set -e
node tools/token-lint.mjs origin/main...HEAD
npx playwright test
npx lhci autorun

Saved as tools/design-checks.sh, this is the gate. Given a range such as origin/main...HEAD, the token script lists the stylesheets that differ and lints each as it stands in the commit the range ends at. set -e stops the script at the first check that fails and makes it exit with that check’s status. Without it a shell script exits with the status of its last command, so a failed token check followed by a passing Lighthouse run would exit 0. I tested the script with stand-ins for the three commands, failing the first, the second and the third in turn. It is a script, not a workflow file: I ran each real command locally and have not run any of this inside a CI service. The commit hook and the CI script check the change whoever wrote it, a person or any agent. That part of the stack does not depend on Claude Code.

What This Site Has Today

I do not run this stack on blakecrosley.com. My design engineering posts describe the type scale, the color tokens and the Lighthouse work. The repository defines the tokens and holds none of the checks: no Stylelint config, no Lighthouse CI config, no axe spec, no screenshot baselines. Here is what that looks like, counted from static/css on November 16, 2026.5

The tokens exist. I built the tokens first and the components never. :root in styles.css defines 12 font sizes from 0.75rem to 5rem, five weights (400, 500, 600, 700, 900), eight spacing steps, and 13 colors, each overridden for the light theme. My earlier typography post says 13 steps and four weights; the stylesheet has 12 and five.

Use is partial. Counted across 75 stylesheets:

Declarations Total Use a token Raw Note
font-size 1,241 548 691 312 of the 548 add a raw fallback after the token name, as in var(--font-size-sm, 0.875rem). The remaining two are one inherit and one reference to a step that does not exist, described below.
font-weight 512 104 408 299 of the raw values are ones a token already holds (600, 700, 500, 400, bold or normal). 109 are weights no token holds (650, 800 or 550).
Raw color, outside the token definitions 2,850 not counted 2,850 2,844 hold a hex value or a color function, and six the name white.

Most of it sits outside the main stylesheet, in files written for individual interactive posts: styles.css itself accounts for 77 of the raw sizes and 230 of the raw colors.

The config finds things. Run over a copy of those stylesheets, the config from component 1 returned 6,034 problems, which is why the script reports what a change introduces and not the whole file. One of them is a step that does not exist: infrastructure-stack.css asks for var(--font-size-md, 1rem), and the scale has no md.

One tier misses AA. White text on the black page measures 21:1 at full opacity, 8.6:1 at 65%, and 3.66:1 at 40%. The first two clear AAA’s 7:1. The third misses AA’s 4.5:1 at body sizes.1 My earlier post on this color system gives 13.7:1 for the 65% tier and 8.4:1 for the 40% tier; those figures are wrong, and these are the computed ones.

The scores moved. I ran Lighthouse 13.6.0 against the live home page on November 16, 2026, three runs each for mobile and desktop. All six reported performance 100, best practices 100, SEO 100, CLS 0.000, and accessibility 93. Two days earlier the same six runs scored performance between 95 and 100, with the other numbers the same.14 Two audits cost the accessibility score. One is the 40% tier on 12px text: two footer lines, which Lighthouse reports as 3.65:1 on black, and on desktop ten guide-listing labels as well, at 3.44:1 on #0a0a0a. The other is the footer links, which fail the WCAG 2.2 target-size audit on both of its conditions: they are 23.8px tall against a 24px minimum, and they do not have enough clear space around them to make up for it.

In January 2026 I measured 100 in all four categories on this site, with CLS at 0.033. Whether the page changed or the audit did, nothing in the repository was watching the number. A diagnostic run on November 16 agrees with Lighthouse. It used the axe tags from component 5 and the layout measurement from component 3, but it logged what it found instead of asserting on it. On the live home page axe reported color-contrast, target-size and one label-content-name-mismatch, and the layout measurement found no overflow and no shift at 375, 768 or 1440px.

That is the case for the stack, made by the site of the person recommending it. Tokens without a check are a convention, and these counts are what a convention looks like with nothing enforcing it.

The Taste Layer

The six components catch violations. None of them catches the output that follows every rule and still feels wrong.

Picture a card with token font sizes, token colors, no layout shift, a clean Lighthouse run, no axe violations and no screenshot diff. Its title crowds the image, its line length strains reading, and its hover state snaps where it should ease. Every check passes. The card is correct. The card is not good.

Taste operates above the rule layer. The six components handle constraints and evaluation criteria. Pattern recognition and coherence need a person going back through the work, a second pass and a third, each time asking not whether the rules hold but whether the result deserves to ship. The pride check ends on “Did I leave the codebase better than I found it?” The Steve test ends on “Would I sign my name to this without flinching?” Neither question has a linter.

What the Stack Buys

Without checks, drift can accumulate in increments too small to see in any one diff: a font size here, a hex value there, a footer link a fraction of a pixel short. The counts from my own CSS are what the aggregate looks like.

With the checks, the agent can still make the mistake. What changes is when someone finds out: on the same turn for a token, at commit for what the hook missed, in CI for layout, performance, accessibility and visual change. That is a narrower promise than “cannot drift,” which is what the earlier version of this post claimed. The checks cover the properties they name, in the declarations a change introduces, on the pages and widths the specs list. A page nobody listed is unchecked.

What that buys is attention. A reviewer who no longer hunts for 19px and #cccccc can spend the review on the taste layer, the questions the checks cannot answer.


FAQ

Do I need all six components to start?

No. Start with the Stylelint config and the script, because token violations are the cheapest to check and the config is one file. Add Lighthouse CI and the axe spec next; each needs only a served page. The layout spec needs a browser that reports layout shifts, and the screenshot spec needs baselines made in the environment that will compare them, so they come last.

Does the stack work with build tools?

For a site whose styles are written as plain CSS files, the checks do not depend on how it is built: Stylelint reads the source files, and Playwright and Lighthouse read whatever the server serves. With a build step, lint the source and point the browser checks at the built output. The script selects only .css files. Sass, CSS-in-JS, inline styles and utility classes in templates need a different way to select and parse the source, or a check against the generated CSS. I have only run it against plain CSS with no build step, where the file the agent writes is the file that ships.

Does it only work with Claude Code?

The edit-time hook is Claude Code’s. The pre-commit hook and the CI commands run on the change itself and do not care which agent, or which person, wrote it.

Can agents learn taste without the stack?

I would not rely on it. A prompt can list the tokens, and an agent given the scale can use it. But a prompt is a request and a failing check is a fact. The stack does not teach taste. It removes the rule violations so that a person’s attention goes to taste.

How do visual regression tests handle intentional changes?

An intentional change that moves more pixels than the tolerance allows fails the comparison like any other. A person reviews the diff and runs npx playwright test --update-snapshots to accept it as the new baseline. The value is in the unintended part: an agent changes a button color on purpose and moves the card by three pixels by accident, and the screenshot shows both.


What Counts as New

This is the detail behind the short rule given with the script, for whoever needs to predict what it will report.

To decide which declarations a change introduces, the script parses two versions of the file with PostCSS, the parser Stylelint is built on. A declaration in the newer version is new unless the older version holds a counterpart. Two declarations are counterparts when two pieces of source text are identical, character for character. One is the declaration itself, from the first character of its property (or of a prefix hack such as the * in *color) through its semicolon. A last declaration with no semicolon runs to the closing brace of its rule, because the parser’s own end point for it leaves out trailing characters that can matter. The other is the header of every rule and at-rule around it, from the header’s first character through its opening brace. The text is compared as it stands in the file. The one change made to both versions before comparing is the one CSS makes before it reads a stylesheet: CRLF, a lone CR and a form feed each become LF. Counterparts pair off one for one, so a second identical declaration is new.

The script compares source text, and not the fields a parser hands back, because parsed fields can lose characters that matter: a no-break space that a trim removed, an escaped tab that the parser stored outside the value. Problems are matched to declarations by line and then by column, which also holds on a line more than a million characters long. Comparing source text costs more re-reports, and where the script cannot pin the text down exactly it treats the declaration as new.

What does not count as a change is text outside those two pieces:

  • the indentation before a declaration or a rule
  • blank lines
  • comments between declarations
  • the order of declarations inside one rule
  • a byte-order mark at the start of the file
  • other rules added or removed around it

What does count is a changed character inside them. In my tests each of these reports the declaration as new, old problem included, and a change to a header does it for every declaration under that header:

  • a space added before a colon, a semicolon or an opening brace
  • a brace moved to its own line
  • a selector list joined onto one line
  • a value wrapped onto two lines
  • a comment inside a selector or a declaration
  • a no-break space
  • !important
  • a change of case
  • a semicolon added to a last declaration that had none
  • a space or a comment added before the closing brace after such a declaration

That is the choice I made. Two spellings one character apart can mean different things in CSS, inside a string, an attribute value or an escape.

Three more things follow from the rule:

  • A declaration moved under a different header is new, and so is every declaration under a selector that was renamed.
  • A declaration that a deletion brings into force, such as one that sat inside a comment, is new although none of its own characters changed.
  • A file with no earlier version under its name, a new or renamed one, is new throughout, as is a file whose earlier version was empty or did not parse.

What the comparison cannot see is order, and context outside the compared text. It knows the headers around a declaration, not which rule the declaration sits in or where it falls in the cascade. So it does not detect:

  • a move between two rules with identical headers
  • a reordering of declarations or rules
  • a change elsewhere that lets an old declaration win, such as deleting the declaration that overrode it
  • a statement at-rule, because it looks only at declarations: an added @import or @layer, or an @namespace whose binding changes, which alters what a selector such as n|a matches while every character of the rule stays the same

Two more behaviors are deliberate. The script needs a git repository: outside one it says so in one line and exits 1 without checking anything. File names come from git separated by NUL bytes and go back to it as literal paths, so the paths I tried worked: spaces and an accent in a name, and a directory name that begins or ends with a space.

How I Tested This

Everything ran on November 16, 2026, on macOS with Node 22.22.0: Stylelint 17.16.0, PostCSS 8.5.33, @playwright/test 1.65.1, @axe-core/playwright 4.14.0 with axe-core 4.14.0, and @lhci/cli 0.16.1 with Lighthouse 13.6.0. Stylelint 18.0.0 was the newest release that day. Its package.json declares Node ^22.22.2 || ^24.15.0 || >=26.0.0, so npm warned of an unsupported engine when I installed it on Node 22.22.0. It ran anyway, and the config gave the same output on my example files as it did on 17.16.0. I have not run 18.0.0 on a Node version it supports.

The specs and the Lighthouse CI config ran against a test site of two static pages, once clean and once in copies broken one way each. The token script’s harness makes 238 checks over 237 runs of the script in scratch folders: through the hook, staged, over a commit range, and outside a repository. Tried in all three modes: multi-line declarations, declarations that a deletion brings into force, changes outside every declaration and header, single-character changes inside them (a no-break space, a zero-width space, a moved brace, an escaped space against an escaped tab), declarations with no semicolon, comments left inside values, a line longer than a million characters, moved declarations, the four undetected cases described above, an earlier version that is empty or does not parse, strings continued over a line, and file names with spaces and an accent.

A second model, OpenAI’s Codex, reviewed the config and the script five times, reading the code and running its own probes, and I fixed what each pass found before the next. Every pass confirmed the earlier fixes and then found something rarer. Across the five passes the findings moved from mistakes anyone makes (a violation on an unchanged line, a declaration uncovered by a deletion) to CSS nobody writes by accident (white space that is not white space, an escaped character at the very end of a declaration). That is the evidence for calling these two files a lint and not a boundary. The checks script ran with stand-ins for its three commands. The hook also ran once inside a live Claude Code 2.1.325 session, on the 19px case, with the script as printed here. Not tested: the rest of the hook’s cases in a live session; the checks script inside a CI service; and any of it against a build pipeline.

What Changed From the April Version

The April version described the stack as infrastructure I run. It said “The infrastructure runs Lighthouse in headless Chrome against the staging deployment” and “The gate runs in CI using lighthouse-ci,” and it had a section titled “How the Stack Maps to My Infrastructure.” I do not run it: this site’s repository holds none of these checks. Its snippets had not been run. Both hooks searched .tool_input.command, a field only shell commands carry, so neither saw a CSS edit, and the Lighthouse CI config named its categories with keys Lighthouse CI does not know. It also misdescribed this site: “three weights: 700, 400, and 300” (there are five weight tokens, and 300 is not one), “exactly ten tokens” (the palette has 13 color tokens), a “13-step scale” (the scale has 12 steps), and “every tier passes AAA” (the tertiary text tier does not). A phrase it put in quotation marks under Jony Ive’s name is not in the profile it cited, and I could not find the Nathan Curtis article it cited, so both are gone. The snippets in this version were run before they were printed, the testing section above says what was not exercised, and the numbers about this site come from three places, all on November 16, 2026: counts taken from its CSS, contrast ratios computed from its tokens, and Lighthouse figures measured on the live site.

Three things in the code changed after the rebuild was first published. The script decided what a change had touched by counting added lines, so it missed a violation that Stylelint placed on an unchanged line of a changed declaration, and it could not see a declaration that a deletion brought into force. It now compares the source text of each declaration, and of the headers around it, before and after the change. Property names in capitals or with escapes passed the config. And the three CI commands, printed without set -e, could exit 0 after a failed check.

Sources


  1. W3C, Web Content Accessibility Guidelines (WCAG) 2.2. Success Criterion 1.4.3 Contrast (Minimum) asks for “a contrast ratio of at least 4.5:1” for text and “at least 3:1” for large-scale text; 1.4.6 Contrast (Enhanced) asks for 7:1. The same document says “the W3C advises the use of WCAG 2.2 to maximize future applicability of accessibility efforts.” ↩↩↩↩

  2. Philip Walton, “Web Vitals”, web.dev. “LCP should occur within 2.5 seconds of when the page first starts loading,” “pages should have a INP of 200 milliseconds or less,” and “a good threshold to measure is the 75th percentile of page loads.” ↩

  3. Robert Bringhurst, The Elements of Typographic Style, section 3.1.1, “Don’t compose without a scale,” as quoted in Richard Rutter, The Elements of Typographic Style Applied to the Web. ↩

  4. Stylelint, declaration-property-value-allowed-list: “Use this rule to enforce a subset of values for a property as a convention.” The plugin stylelint-declaration-strict-value is a dedicated alternative for the same job. I used the built-in rules and did not test the plugin. ↩

  5. Author’s count of the 75 authored stylesheets in static/css at commit 253f49ade on November 16, 2026, excluding the generated styles.min.css and critical.css, with comments stripped. Contrast ratios use the WCAG relative-luminance formula on each color composited over #000000. ↩↩

  6. Milica Mihajlija and Philip Walton, “Cumulative Layout Shift (CLS)”, web.dev. “To provide a good user experience, sites should strive to have a CLS score of 0.1 or less,” and “CLS is a measure of the largest burst of layout shift scores for every unexpected layout shift that occurs during the entire lifecycle of a page.” On iframes: “The API does not report layout-shift entries for shifts that occur within iframes but the metric does as they are part of the user experience of the page.” ↩↩

  7. Lighthouse CI, “Configuration”. Category assertions “are keyed by categories:<categoryId>,” the default options are {"aggregationMethod": "optimistic", "minScore": 1}, and optimistic means “Use the value that is most likely to pass from all runs.” ↩

  8. Deque, axe-core API documentation, the table of tags: wcag2a, wcag2aa, wcag21a, wcag21aa and wcag22aa each name one WCAG version and level. ↩↩

  9. Playwright, “Accessibility testing”. ↩

  10. Playwright, “Visual comparisons”. “For consistent screenshots, run tests in the same environment where the baseline screenshots were generated.” The maxDiffPixelRatio option is described under toHaveScreenshot in the PageAssertions API reference: “An acceptable ratio of pixels that are different to the total amount of pixels, between 0 and 1.” ↩↩

  11. BackstopJS, README, read November 16, 2026. ↩

  12. Anthropic, Claude Code hooks reference. The Edit and Write inputs carry file_path; for PostToolUse, exit code 2 “Shows stderr to Claude; the tool already ran”; and “Claude Code doesn’t run a PostToolUse hook matching Edit|Write when a Bash command or a process outside Claude Code rewrites the same file.” ↩↩

  13. Git, githooks documentation, under pre-commit. ↩

  14. Author’s measurement. Lighthouse 13.6.0 run from the command line against https://blakecrosley.com/ on November 16, 2026, default mobile settings and the desktop preset, three runs each. On November 14 the same six runs scored performance 95, 100 and 99 on mobile and 99, 100 and 100 on desktop, with accessibility 93. Lighthouse’s 3.65:1 and my 3.66:1 are the same ratio, 3.657: I round it, and axe, which Lighthouse runs for this audit, cuts it to two decimals. ↩

Related Posts

Taste Is Infrastructure: Encoding Aesthetic Judgment for AI

Agents have capability without opinion. The quality ceiling depends on how well you encode aesthetic judgment into hooks…

8 min read

Chat Is the Wrong Interface for AI Agents

Chat works for prompting but fails for agent operations. Six interface patterns replace the scrolling text window with r…

16 min read

SF Pro: Variable Axes, Optical Sizing, And The Dynamic Type Contract

Apple's system font ships with three variable axes and continuous optical sizing. The vocabulary that makes typography w…

12 min read