Scans source code — or a live deployed page — for design-token, motion, and component-state drift against your own design system.
This is the open-source scanning engine behind Maddox Engine — the same code the hosted dashboard and GitHub Action run, extracted so you can run it locally or in CI with no account required.
- Colors — every hex literal in your source (or a live page's rendered HTML/CSS), matched against your
@themetokens by exact value, then by RGB distance for near-misses. - Motion — durations and easings used in code, checked against your real motion tokens (duration against duration, ease against ease — never cross-compared). Source-scan only; see
--urlbelow. - Component states — an explicit contract you write yourself (a JSON file naming which states each kind of component must cover:
disabled,loading,error, and so on). Confirms the state is referenced in the file; it doesn't verify it renders correctly — that's a static source check, not a visual one. Source-scan only.
This is a source-code and rendered-output scanner, not a pixel/DOM visual-regression tool. It checks the values a page actually ships against the tokens that are supposed to govern them, so it catches drift that renders identically to a real token (and so produces zero visual diff) but was never written as one.
npx maddox-engine <target-source-dir> <path-to-globals.css-with-@theme-block> [options]Options:
-
--project <name>— project name (defaults to the target directory's basename, or the URL's hostname in--urlmode) -
--motion <path>— path to a JSON file of motion tokens (e.g. a vendored copy of your motion-tokens export) -
--states <path>— path to a state-contract JSON file (see below). No effect in--urlmode. -
--tokens-studio <path>— path to a Tokens Studio / W3C Design Tokens JSON export (see below); merged with, and taking precedence over,@themeon any path both define -
--figma-file <file-key>— pull color/spacing tokens from a Figma file's Variables (see below); requires an Enterprise Figma plan -
--url <page-url>— scan a deployed page instead of local source (see below); pass a placeholder like-for<target-source-dir>when using this alone -
--apply-fixes— write near-miss color/font-size/spacing suggestions back into source files (see below); not available with--url -
--format text|json|markdown— output format (default:text) -
--fail-below <0-100>— exit non-zero if the drift health score falls below this threshold; omit to never fail (unless your workspace has central rules) -
--api-key <key>— upload the result to Maddox Cloud (see below); theMADDOX_API_KEYenvironment variable does the same and is the safer choice, because a flag value can end up in shell history -
--exclude <glob>— skip matching files or directories (repeatable); a.maddoxignorefile in the target directory (one glob per line) is applied too. Test, spec, story and mock files are skipped by default.
Put a maddox.config.json at your project root and run npx maddox-engine with no paths. Command-line flags still override it.
{
"theme": "app/globals.css",
"source": "app",
"motion": "motion-tokens.json",
"states": "state-contract.json",
"tokensStudio": "tokens.json",
"exclude": ["legacy/**"],
"project": "web"
}Only theme is required. source defaults to the folder holding the config, and project to that folder's name. Paths are relative to the config file and must stay inside the project. Maddox looks for the config in the current folder and its parents, stopping at the repository root.
npx maddox-engine check app/components/Card.tsx
cat proposed.css | npx maddox-engine check app/styles/card.css --stdin --format jsonChecks one file, or proposed content passed on stdin, against the tokens in maddox.config.json, with the same rules as a full scan (test, story and ignored files are skipped). It prints only drift, with the nearest token and suggested fix. Local only: it never uploads and never reads your API key. Exit codes: 0 no drift or the file is skipped, 1 drift found, 2 the check could not run.
Runs after Edit, Write or MultiEdit and tells the agent only about newly introduced drift in that edit (never repeating the same finding in a session, and staying silent on non-style files or missing config). Add to .claude/settings.json (or .claude/settings.local.json) in a project with maddox.config.json:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write|MultiEdit",
"hooks": [
{
"type": "command",
"command": "npx maddox-engine hook claude-code"
}
]
}
]
}
}Pass --insist (maddox hook claude-code --insist) to return a "block" decision so Claude addresses the drift before continuing. For faster runs, install maddox-engine locally and point "command" at ./node_modules/.bin/maddox hook claude-code.
Checks staged files against maddox.config.json and exits 1 when a commit adds new drift over HEAD (pass --all to fail on any existing drift in staged files). In .git/hooks/pre-commit (chmod +x .git/hooks/pre-commit):
#!/bin/sh
npx maddox-engine hook pre-commitRequires Node 20 or later.
Maddox reads your tokens from every @theme block (including @theme inline) and resolves var() references from :root, so the shadcn pattern (--color-background: var(--background)) works. Projects that keep their palette in plain :root variables are read too: when there's no @theme block, or the @theme block defines no colours or sizes (fonts only, for example), the :root variables are the tokens. Token values can be hex, rgb(), hsl(), bare HSL triplets (222.2 47.4% 11.2%, common in Tailwind v3 / shadcn :root blocks), or oklch(). Dark-mode overrides are not read. If no usable tokens are found it exits with an error instead of scoring everything as drift.
With no @theme block at all (plain CSS or a Tailwind v3 style setup), the :root variables are used as the tokens.
Comments and token definitions (a custom property declaration such as --color-brand: #123456;) are not usages. A kind of value is only compared when your theme has tokens of that kind, so a project without font-size tokens gets no font-size findings. Font sizes are compared against font-size tokens (--text-* or a name containing font-size) when the theme has any, and otherwise against non-excluded length tokens (skipping --radius*, --spacing*, and similar layout namespaces).
What Maddox reads from .ts, .tsx, .js, .jsx and .css files (a tailwind.config.* defines tokens, so it is skipped):
- Colors: hex (
#rgb,#rgba,#rrggbb,#rrggbbaa) andrgb()/rgba()/hsl()/hsla()/oklch()with literal values, in CSS, JS strings and Tailwind arbitrary classes (bg-[#123456],shadow-[0_0_0_1px_#123456]). Token references such ashsl(var(--primary))and fully transparent values are not usages. - Font sizes: CSS
font-size:, JSXfontSize: "15px"orfontSize: 15(a number is px, as in React), and Tailwindtext-[15px]. - Spacing:
padding,marginandgap(every side, CSS or camelCase) in CSS and style objects, and Tailwindp-[13px],mt-[1.5rem],gap-x-[6px],space-y-[..]. Spacing is compared against named spacing tokens (--spacing-4,--space-md,--gap-sm); Tailwind v4's bare--spacingbase is a multiplier, not a step, so it is not used. - Motion: duration, delay, stagger, ease and spring values.
For intentional values such as a chart palette or a set of theme presets, opt out in the source with a comment:
// maddox-ignore-next-line
const accent = "#eb6834";
const palette = [
// maddox-ignore-start
"#2a78d6",
"#eb6834",
// maddox-ignore-end
];
const brand = "#123456"; // maddox-ignoreLocal scans, --apply-fixes and the GitHub Action's PR comments are free, open source and unlimited. To keep scan history and trends, and (on Team and Scale) see exactly which drifts each pull request adds or fixes compared with your main branch, connect to Maddox Cloud with an API key:
export MADDOX_API_KEY=<your-key>
npx maddox-engine ./src ./src/app/globals.cssAn upload problem never changes the scan result or its exit code. If your monthly limit is reached or the upload fails, the CLI prints a message and carries on, so --fail-below still decides whether the build passes. Without a key, nothing is sent over the network. The free plan includes 1 project, 5 uploaded scans a month and 30 days of history; Team includes 5 projects and 12 months, Scale is unlimited. See pricing. If an upload is over a plan limit, the CLI prints the reason and carries on. MADDOX_API_URL overrides the endpoint.
On Scale, the workspace owner sets CI rules once in the dashboard, and every scan run with the workspace's API key applies them:
- Minimum health score: fails the build below it, as
--fail-belowdoes. A--fail-belowflag passed on the command line takes precedence. - Fail on new drift: fails a pull request that adds drift compared with your main branch. Pushes to main are never failed by this rule, and it is skipped (with a message) when there is no earlier main-branch scan to compare with.
- Approved exceptions: values such as an intentional campaign colour are left out of the report, the score,
--apply-fixesand the upload.
If the rules can't be loaded, the scan carries on with your local flags and says so.
Exit codes: 0 passed, 1 drift failed --fail-below or a central rule, 2 the scan could not run (bad arguments, no usable tokens, an error).
npx maddox-engine ./src ./src/app/globals.css --project my-app --fail-below 80An optional JSON file mapping a component-name pattern to the state names that component kind must cover:
{
"Button": ["disabled", "loading"],
"*Input": ["error", "disabled"]
}Ground truth is explicit — nothing is inferred about which states a component "should" have.
If your tokens live in Figma via the Tokens Studio plugin rather than (or alongside) a Tailwind @theme block, export them to JSON and point --tokens-studio at the file. A single-set export (the whole file is one token tree) and a multi-set export (top-level keys are set names, e.g. global, dark) are both supported — for a multi-set export, every set is merged, later sets overriding earlier ones by path. {alias} references are resolved automatically. Only token types that resolve to a single comparable value (color, spacing, sizing, fontSizes, borderRadius, dimension) are used — composite types like typography or boxShadow describe a bundle of properties, not one value to diff against, and are skipped rather than misclassified.
If your tokens live in native Figma Variables rather than Tokens Studio, --figma-file <file-key> pulls them directly from Figma's Variables REST API. This requires an Enterprise Figma plan — the endpoint returns a 403 for any other plan, regardless of the token's own permissions. Get the file key from the file's URL (figma.com/design/:file_key/...).
export MADDOX_FIGMA_TOKEN=figd_... # a personal access token with file_variables:read scope
npx maddox-engine ./src ./src/app/globals.css --figma-file abc123XYZThe token is read from MADDOX_FIGMA_TOKEN (a personal access token, sent via the X-Figma-Token header) or MADDOX_FIGMA_OAUTH_TOKEN (an OAuth2 access token, sent via Authorization: Bearer) — never pass it as a CLI flag, which would leak it into shell history and process listings.
Only COLOR and FLOAT-typed variables are used, resolved to each variable's default mode, following alias references to their underlying value. FLOAT variables have no unit in Figma's API — treated as pixels, matching Figma's own UI default for spacing/sizing/radius scales; a variable actually meant as a unitless multiplier will resolve wrong. STRING/BOOLEAN variables are skipped, same policy as Tokens Studio's composite types. When more than one ground-truth source is given, Figma Variables take precedence over Tokens Studio, which takes precedence over @theme CSS — Figma sits earliest in a real design-to-code pipeline, so a later step is more likely to be the stale one.
npx maddox-engine - ./src/app/globals.css --url https://example.com --format text--url fetches the page's rendered HTML plus every same-origin <link rel="stylesheet"> it links to, and runs the same color/font-size/spacing/motion extraction against what's actually shipped — not what's in the repo at scan time. This is the difference between a source-linter and a production check: a stale CDN cache, a build step that silently drops a token, or a config typo can all make the deployed page diverge from what the source says, and only a live-URL scan catches that.
Two things don't carry over to --url mode:
- Motion — durations/eases only ever appear in rendered HTML/CSS as static literals if a component hardcodes them there, which real motion libraries don't do (they animate via the JS runtime). Motion findings are dropped from every
--urlscan rather than surfaced as noise from unrelated CSS. - Component states — state-completeness is a "is this identifier referenced in this file's source" check; a fetched, already-rendered page has no source to check.
--statesis accepted but has no effect in--urlmode.
Third-party stylesheets (a different origin than the page itself, e.g. a font CDN) are never fetched — only same-origin CSS, so findings only ever point at code the project actually owns.
Every near-miss finding with a resolved nearest token gets a suggestion — the concrete replacement text (var(--token-name) for a CSS value, or motionTokens.path.to.value for a motion token). By default it's advisory text for you to apply yourself; pass --apply-fixes to write it back into the file. An unrecognized value with no close match, and a missing-state finding, never get a suggestion — there's no safe mechanical fix for either.
npx maddox-engine ./src ./src/app/globals.css --suggest-tokensLists colours your code uses again and again that your theme doesn't name (5 or more uses by default; change it with --min-uses 3), most used first, as a ready-to-paste @theme block with the score you'd get by adding them. That covers values with no close token, translucent overlays, and deliberate shades a fix can't safely replace, such as two stops of a gradient. Each gets a readable name from what it's used for, its hue and its lightness (#0b3b33 used as a background → --color-bg-teal-900, rgba(255,255,255,0.06) → --color-white-a6). The role prefix means a suggestion never reuses one of Tailwind's built-in palette names (--color-teal-900), which would recolour existing classes; names never clash with your existing tokens, and they're a starting point to rename. Maddox never edits your theme: adding a token is a design decision. With --format json, the suggestions are under suggestedTokens.
npx maddox-engine ./src ./src/app/globals.css --apply-fixes--apply-fixes writes every color/font-size/spacing near-miss suggestion straight into the source file it was found in, replacing that exact literal, at its exact position on the line, with var(--token-name). The replacement is written to stay valid where it lands:
- Inside a Tailwind arbitrary value, it carries a type hint:
bg-[#123457]becomesbg-[color:var(--color-brand)]andtext-[15px]becomestext-[length:var(--text-base)], so Tailwind never reads a size as a color. - A JS number becomes a string:
fontSize: 15becomesfontSize: "var(--text-base)". - Two equal values on one line are fixed separately, so
fontSize: "15px", padding: "15px"gets a font-size token and a spacing token.
It's scoped deliberately narrow:
-
Translucent colors are never applied.
rgba(…, 0.5)or#12345680would lose its transparency as a plain token, so it stays advisory-only. -
Opaque and translucent colors are never matched to each other.
#ffffffis notrgba(255, 255, 255, 0.06), however close the channels are. -
A token is suggested only where its name fits. A background isn't pointed at a token named for text (
--color-text-*,--color-ink), and so on for text and borders. Names that say nothing about their use (--color-brand,--color-hw-body) fit anywhere. -
Some fixes are held, not applied, and listed with the reason: values inside Framer Motion animation props or GSAP tweens (they can't animate
var()), fixes that would make neighbouring stops of a gradient the same token (flattening a deliberate shade-to-shade gradient), and anything in an email or HTML template (email clients don't support CSS variables). -
Token references are already correct and are never listed as fixes.
-
Motion suggestions are never applied.
motionTokens.path.to.valueassumes an import namedmotionTokensexists in that file's scope — there's no way to verify that per-file, and applying it blind could silently break the build. Motion findings always stay advisory-only. -
State findings never had a suggestion to apply.
-
If a finding's position no longer holds its reported value (the file changed since the scan ran), it's skipped rather than guessed at.
-
Not available with
--url— a fetched page has no local file to write to.
This is a real edit to your working tree, not a dry run — review the diff (git diff) before committing, same as you would any other automated change.
match counts fully, near-miss counts half (it drifted, but is still recognizably close to a real token), unrecognized and a missing required state count for nothing. A scan with zero checks scores 100.
Using a token by name counts as a match: var(--color-paper), including inside Tailwind brackets such as text-[length:var(--text-sm)]. References to variables that aren't design tokens (Tailwind's own --tw-*, for example) aren't counted either way, and a variable defined from another (--surface: var(--color-paper)) is a definition, not a use. So replacing drifted values with their tokens, by hand or with --apply-fixes, raises the score.
The CLI's own text/markdown/JSON output stays a flat file:line list — the right shape for a PR comment or a CI log. If you're building your own dashboard or report on top of this package, fileToRoute(file) and groupByRoute(findings) are also exported for grouping findings by the actual Next.js App Router route a file belongs to, rather than its raw path:
import { audit, loadGroundTruth, fileToRoute, groupByRoute } from "maddox-engine";
const groundTruth = loadGroundTruth("./src/app/globals.css", {});
const { findings } = await audit("./src", groundTruth);
fileToRoute("app/dashboard/page.tsx"); // "/dashboard"
fileToRoute("app/(auth)/login/page.tsx"); // "/login" — route groups are invisible in the real URL
fileToRoute("app/work/[id]/page.tsx"); // "/work/[id]" — dynamic segments kept as Next.js represents them
fileToRoute("components/Button.tsx"); // "Shared (non-route files)"
groupByRoute(findings); // [{ route, findings }, ...], real routes first, shared bucket lastOnly page.*/layout.* files directly under an app/ (or src/app/) directory get a real route — this deliberately does not trace the import graph to attribute a shared component to the page(s) that render it, since a component used by five different pages has no single "real" route, and guessing one would misattribute drift. Everything else lands in a "Shared (non-route files)" bucket instead. A layout keeps its route group in its own label (/(auth) (layout)) even though a page at the same URL doesn't, since two different layouts can legitimately wrap the same URL from different subtrees.
import ... from "maddox-engine" pulls in everything, including scan.ts/groundTruth.ts/tokensStudio.ts/applyFixes.ts — all of which read the filesystem (node:fs, node:path). A bundler building a browser/client bundle (Next.js's "use client", Vite, etc.) can't resolve those, and the build fails even if the client code never actually calls a Node-dependent function — a bundler loads a module's own top-level imports regardless of which export is used.
If you're grouping or diffing findings inside a client component (e.g. rendering fileToRoute/groupByRoute output, or re-running diffUsages against data already fetched server-side), import from the /client subpath instead — it only re-exports modules with zero node:* imports anywhere in their own graph:
import { fileToRoute, groupByRoute, diffUsages, healthScore } from "maddox-engine/client";audit/auditUrl/loadGroundTruth/anything that reads a file or fetches a URL still needs the package root, and stays server-side (an API route, a server component, a build script) — /client only has the pure data-transformation half.
This repo is also a GitHub Action — omrdev1/maddox-cli — that runs a scan, posts the markdown report as a PR comment (updating the same comment on later pushes rather than piling up new ones), and optionally fails the build via fail-below.
- uses: actions/checkout@v4
- uses: omrdev1/maddox-cli@v0
with:
target-dir: src
theme-css: src/app/globals.css
github-token: ${{ secrets.GITHUB_TOKEN }}
fail-below: "80"With an api-key, each uploaded scan records its branch, commit and pull request. A pull request scan is then compared with the latest scan of its base branch, and the PR comment leads with what changed:
This PR adds 2 new drifts and fixes 1 compared with
main, followed by a table of the new ones.
Values are matched by file, kind and value, not line number, so moving code around is not reported as new drift. For this to work, run the Action on pushes to your main branch as well as on pull requests, so there is a baseline to compare with:
on:
pull_request:
push:
branches: [main]Outside GitHub Actions, the CLI reads the branch and commit from the local git checkout. In other CI systems, set MADDOX_BRANCH, MADDOX_BASE_BRANCH and MADDOX_COMMIT_SHA.
Inputs:
target-dir(required unlessurlis set) — directory to scantheme-css(required) — path to the CSS file containing the@themeblockmotion-tokens— path to a motion-tokens JSON filestates— path to a state-contract JSON file. No effect whenurlis set.tokens-studio— path to a Tokens Studio / W3C Design Tokens JSON exportfigma-file/figma-token/figma-token-type— pull tokens from a Figma file's Variables; requires an Enterprise Figma plan.figma-tokenshould be a secret (${{ secrets.FIGMA_TOKEN }}), never a literal value.url— a deployed page URL to scan instead of local sourcegithub-token(required) — for posting the PR comment, usually${{ secrets.GITHUB_TOKEN }}fail-below— fail the build below this health score; omit for comment-only (unless your workspace has central rules). If the scan can't run (for example, a wrongtheme-csspath), the check fails only whenfail-beloworapi-keyis set.api-key/api-url— optional, upload results to a Maddox Engine dashboard account for scan history and drift trends across projects (a separate hosted product, not required to use the Action itself). When an upload succeeds, the PR comment links to the run on the dashboard. The PR comment is updated in place on every push, never duplicated.
@v0 follows every compatible 0.x release, so you get fixes without editing your workflow. For fully reproducible runs, pin an exact release such as @v0.9.0 or a commit SHA. @main is the development branch and can change at any time.
MIT, copyright Grafikui Ltd. Contributions are welcome under the same licence, see CONTRIBUTING.md. Report security problems privately, see SECURITY.md.
"Maddox", "Maddox Engine" and the Maddox logo are trade marks of Grafikui Ltd and are not covered by the MIT License. The hosted service at maddoxengine.com has its own Terms of Service and Privacy Policy.