Repository avatar
AI Tools
v1.13.6
active

polish-design-tokens

io.github.maxdeng007/polish-design-tokens

Audit design tokens in AI-generated pages: scan hardcoded values, confirm fixes, re-audit clean

Documentation

polish — Design Token Superpower Tool

English | 中文

polish — Design Token Superpower Tool

Extract · Critique · Apply — a zero-dependency toolkit that closes the loop on CSS custom properties (design tokens). It scans stylesheets for token problems, classifies each finding, and auto-applies mechanical fixes while flagging judgmental ones for human decisions.

Works as a CLI, an MCP server for AI coding agents, or a Node.js module.

Built for frontend engineers and design-system maintainers who use CSS custom properties and need to keep them consistent as a project grows.

Repository: https://github.com/maxdeng007/polish-design-tokens

polish pipeline flow

Problem

Design tokens — CSS custom properties like --color-primary — are powerful but fragile. As projects grow, tokens drift: hardcoded colors creep in, duplicate values appear under different names, references dangle, and cascade overrides silently break consistency. Detecting these issues manually is tedious; fixing them is even more so.

polish automates the audit → fix pipeline:

  1. Extract — scan CSS/HTML files, build a declaration graph
  2. Critique — cross-reference declarations and references to find problems
  3. Apply — generate and execute patches for mechanical fixes, with backups

Important scope note: of the 13 finding types polish detects, only duplicate-value is auto-fixed. The remaining 12 are flagged for human or agent review — polish tells you what's wrong, but the decision on how to fix it is yours.

Why Not Stylelint or ESLint?

Stylelint and ESLint catch syntax errors and style-rule violations, but they don't understand token relationships. They can't tell you that --background duplicates --bg, or that a token you're referencing was never declared. polish builds a declaration graph and cross-references it to find exactly these structural token problems — then auto-fixes the mechanical ones and flags the rest for your judgment.

The mechanical/judgmental split is the core idea: problems with one safe answer are fixed automatically; problems that need a decision are surfaced, never silently patched.

Installation

From npm (recommended):

npm install -g polish-design-tokens

Or as a project dependency:

npm install polish-design-tokens --save-dev

From GitHub (if you want the latest source):

git clone https://github.com/maxdeng007/polish-design-tokens.git
cd polish-design-tokens/polish-mono
npm install -g .

Requires Node.js ≥ 18.

Install via an AI Coding Agent

For non-technical users. This path requires an AI coding agent with terminal access — an AI coding CLI or an IDE agent that can run commands on your machine. A plain chat window can't execute anything locally, so paste the prompt below into your agent, not a chat box; the agent will install polish, audit your project, and report back. No coding required.

Please help me audit the design tokens in my project using the "polish" tool.

1. Install the polish tool globally by running:
   npm install -g polish-design-tokens

2. Run an audit on my project directory at:
   [PASTE YOUR PROJECT PATH HERE]

3. Report what you find in plain language a designer can understand:
   - What token problems exist (hardcoded colors, duplicate values,
     dangling references, conflicts, etc.)
   - Which issues can be auto-fixed and which need my decision
   - A clear summary — not raw JSON

Do NOT apply any fixes or modify any files. Install, audit, and report only.

What's next: polish stays installed on your system after the audit — no reinstall needed. If you want to apply the mechanical fixes (duplicate values), just give your AI a follow-up prompt like: "Now apply the mechanical fixes to my project with backups." The AI will re-run the audit, generate patches, and apply them with automatic backups.

Safety notes:

  • polish audit and polish check are strictly read-only — they never modify files.
  • polish fix, polish apply, and the wizard's apply step modify files. Every apply run is strictly all-or-nothing with automatic backups (<file>.backup, later runs snapshot to <file>.backup.<runId>); a failed pre-validation writes nothing. Still, review the generated patches or the HTML report before applying, and work on a clean branch you can discard if anything goes wrong.
  • polish doctor --install executes shell commands and accesses the network to install optional skills — run it only if you're comfortable with that.

Optional Skills

polish works out of the box with zero dependencies. Four optional skills and tools enhance the experience — none are required for token auditing. Run polish doctor to check what's installed; it reports any missing skill with a ready-to-run install command. Pass --install to polish doctor to auto-install missing ones.

Skill / ToolWhat It DoesHow It Complements polish
awesome-design-md54 ready-to-use DESIGN.md files from brands like Vercel, Stripe, Linear, and NotionPowers polish_style_lookup — query a brand's design tokens (colors, typography, spacing) for a specific visual language
dembrandtDesign token analysis and classification toolComplementary token tool — polish audits your project; dembrandt helps classify and normalize token data
tasteFrontend art direction and design tasteInforms design decisions when polish flags judgmental findings (hardcoded colors, naming conflicts, cascade overrides)
impeccableProduction-grade frontend interface generationBuilds polished UI that uses your tokens consistently, working alongside polish's audit-and-fix pipeline

All four are optional. polish performs a complete token audit without any of them — install the ones that match your workflow.

Quick Start

For CLI users. The standard four-step pipeline:

# 1. Audit a project for token issues
polish audit ./my-project --ignore=node_modules,dist > findings.json

# 2. Convert findings to a ranked plan
polish plan findings.json > plan.json

# 3. Generate mechanical patches
polish diff plan.json > patches.json

# 4. Apply patches (creates .backup files automatically)
polish apply patches.json --target=./my-project

Or just run polish with no arguments to launch the interactive wizard — it walks you through all five steps with confirmation prompts, no JSON files or command flags to remember. See Interactive Wizard below.

One-shot commands. For quick, repeatable use without chaining JSON files:

# Read-only health check — exit code 1 if errors found, ready for CI
polish check ./my-project

# One-shot fix — scans, applies mechanical patches with backup, reports the rest
polish fix ./my-project

# Preview fixes without touching files
polish fix ./my-project --dry-run

# Generate an interactive HTML report — open in any browser, check decisions
polish report ./my-project

polish check never modifies files — it's safe to run in CI, pre-commit hooks, or any time you want a quick token health snapshot. polish fix collapses the full audit → plan → diff → apply pipeline into a single command, applying only mechanical fixes and flagging judgmental issues for your review. polish report produces a self-contained HTML file you can share with designers — it color-codes findings by severity and includes checkboxes for simple decisions (delete an orphan token, alias a duplicate value); check them and download a decisions.json to feed into polish confirm.

AI Agent Deployment

For AI coding agents. The most common workflow: give your AI coding agent (Qoder, Claude, etc.) the GitHub repo URL and ask it to set up and run polish. The agent will:

  1. Clone the repo or install from npm
  2. Register the MCP server (see below)
  3. Use polish_audit to scan the target project
  4. Use polish_plan → polish_diff → polish_apply to fix mechanical issues

All polish apply operations create .backup files before modifying any file. The run is strictly all-or-nothing: if a patch fails pre-validation nothing is written (status aborted), and an execution-time failure rolls every written file back from its backup (status rolledBack) — review the apply report and use polish rollback to restore.

Register the MCP server in one line (requires Node.js ≥ 18):

# Claude Code
claude mcp add polish -- npx -y polish-design-tokens@latest mcp

# Cursor — add to .cursor/mcp.json (project) or ~/.cursor/mcp.json (global)
{"mcpServers":{"polish":{"command":"npx","args":["-y","polish-design-tokens@latest","mcp"]}}}

# Windsurf — add to ~/.codeium/windsurf/mcp_config.json
{"mcpServers":{"polish":{"command":"npx","args":["-y","polish-design-tokens@latest","mcp"]}}}

The Pipeline

polish operates in three phases. Each phase reads the output of the previous one, so you can run the full chain or stop at any point.

findings.json → [polish plan] → plan.json → [polish diff] → patches.json → [polish apply] → files

1. Plan — classify and rank

Takes findings (from polish_audit) and produces an ordered action queue. Each finding is classified as:

  • Mechanical — safe to auto-fix. No human decision needed.
  • Judgmental — requires human judgment. Surfaced for manual review.

Findings are ranked by priority:

PriorityTypeDescriptionClassification
1conflictSame token name with different values in root scopeJudgmental
2danglingToken referenced but never declaredJudgmental
3runtime-driftInconsistent token values across pages at runtimeJudgmental
4orphanDeclared but never referencedJudgmental
5duplicate-valueMultiple token names sharing the same valueMechanical
6namespaceMultiple naming families coexistJudgmental
7hardcodedRaw color/space values used instead of token referencesJudgmental
8cascade-overrideCSS cascading produces unintended variationJudgmental
9state-variationToken values differ across component statesJudgmental
10theme-variationToken values differ across themesJudgmental
11dynamic-variableTokens with dynamic (non-static) valuesJudgmental
12tailwind-utility-varTailwind v4 per-utility variablesJudgmental
13literal-clusterThe same literal value is used repeatedly across the project — a token candidate.Judgmental

Only mechanical findings (duplicate-value) produce patches in the next phase.

2. Diff — generate patches

Reads the plan and generates concrete patches for mechanical items only. Each patch specifies:

  • type: replace (before → after), add (insert new declaration), delete, or rewrite
  • file / line: exact location
  • before / after: the exact text change
  • reason: human-readable explanation

Patches for duplicate-value target the secondary token's location and alias it to the primary — never the primary itself (preventing self-referencing aliases).

3. Apply — execute with backup

Applies patches to files with automatic backup protection. Each file is backed up before modification. The result reports what was applied and any failures.

Input

polish reads local files — it does not fetch from URLs or online resources.

Provide a directory path (recommended) or a single file path as the target. When given a directory, polish recursively scans every supported file inside it, automatically skipping common build and dependency directories (node_modules, dist, .git, etc.) and binary files.

The same target parameter is used across all three entry points — CLI, MCP, and Node.js API.

CLI Usage

polish                                 # Launch the interactive wizard
polish wizard [--target=dir] [--ignore=a,b]  # Guided pipeline with confirmation prompts
polish audit  <target> [--ignore=a,b] [--summary]  # Scan and output findings
polish check  <target> [--ignore=a,b]              # Health check: read-only summary, exit code = errors
polish fix    <target> [--ignore=a,b] [--dry-run]  # One-shot fix: apply mechanical patches with backup
polish report <target> [--ignore=a,b] [--output=f] # Generate interactive HTML report
polish plan  <findings.json> [--summary]   # Convert findings to an ordered action list
polish diff  <plan.json> [--summary]       # Generate mechanical patches from a plan
polish apply <patches.json> [--target=dir] [--summary]    # Apply patches (creates .backup files)
polish rollback <backups.json> [--target=dir] [--summary]  # Restore files from an apply run backup manifest
polish confirm <decisions.json> [--target=dir] [--summary]  # Apply designer-confirmed judgmental decisions
polish seed  <target> [--output=dir] [--force] [--summary]   # Generate a draft tokens.css + tokens.seed.json from literal clusters
polish demo  [--target=dir]                                # Generate a reproducible sample AI-generated project
polish init  [target] [--mode=auto|generate|migrate|greenfield] [--starter=brand]
              [--agent=claude|cursor|windsurf|none] [--force]
              # One-command onboarding: detect the mode, write the token contract
polish agent init [--claude] [--cursor] [--windsurf] [--target=dir] [--force]
              # Write agent rule files for Claude Code / Cursor / Windsurf
polish vocab <target|--starter=brand> [--summary]     # Read root tokens (or a brand starter) as a vocab
polish instructions [<target>]                          # Print the token contract instructions text
polish preflight <file> [--vocab=dir] [--summary]      # Read-only check of a file against a vocab (exit 1 if drift)
polish doctor [--install] [--summary]      # Check optional deps; --install auto-installs missing ones
polish explain <finding-type>              # Explain what a finding type means and how to fix it
polish mcp                       # Start MCP server (JSON-RPC over stdin/stdout)

--summary prints a human-readable summary instead of raw JSON — ideal when reading results in a terminal. Works for all commands:

polish audit ./my-project --summary
# Token Audit Summary
# ...
# Found 130 issues:
#   [Judgmental] 10 conflict
#   [Mechanical] 34 duplicate-value
# ...

When output goes to a terminal, findings are color-coded by severity — red for errors, yellow for warnings, green for informational. Colors are automatically disabled when output is piped or redirected.

--install (doctor only) automatically installs missing optional dependencies. Without it, doctor just reports what's missing and shows the install commands to run manually:

polish doctor              # Check what's installed, show install commands for missing
polish doctor --install    # Check and auto-install missing optional dependencies

polish explain prints a plain-language explanation of any finding type — what it means, why it matters, and how to fix it. Run it when you see a finding type in your report and want to understand it without reading the docs:

polish explain conflict
polish explain hardcoded

polish confirm applies designer-confirmed decisions for judgmental findings — the ones that polish diff cannot auto-fix because they need a human decision. Pass a decisions JSON file and a target directory; polish re-scans the target, resolves each decision into a patch, and applies it with backup protection.

// decisions.json
{
  "decisions": [
    { "action": "delete", "token": "--primary" },
    { "action": "alias", "from": "--heading", "to": "--text" },
    { "action": "rename", "from": "--bg", "to": "--background" }
  ]
}
polish confirm decisions.json --target=./my-project --summary

Three decision actions are supported:

ActionEffectUse for
deleteRemoves the token declarationOrphan tokens
aliasReplaces the value with var(--to)Duplicate values with a chosen primary
renameRewrites all occurrences across filesNamespace fragmentation

The same decisions can be collected interactively via the wizard's Confirm step (Step 3 of 5).

polish report generates a self-contained, interactive HTML report — open it in any browser to review findings without touching the CLI or JSON. Findings are color-coded by severity and grouped into error/warn/info sections. Each card shows the finding type, file and line, evidence, and a suggestion; color values render with a swatch so you can see the color at a glance. Simple decisions (delete an orphan token, alias a duplicate value) get a checkbox — check the ones you agree with and click Download or Copy decisions.json to export them. The report shows the exact polish confirm command to run next, or you can hand decisions.json to an AI agent to apply.

polish report ./my-project                       # Writes polish-report.html into the target
polish report ./my-project --output=report.html   # Writes to a specific path
polish report ./my-project --ignore=node_modules  # Skip directories

The HTML is fully self-contained — no external CSS, JS, or network requests — so you can share it by email, drop it in a repo, or open it offline.

Interactive Wizard

Running polish with no arguments (or polish wizard) launches an interactive wizard that walks you through the entire pipeline — audit, plan, confirm, diff, and apply — step by step with confirmation prompts. No JSON files to redirect, no command flags to remember.

polish
# ▸ Polish — Design Token Superpower Tool
#
# Step 1: Audit
# Project directory to scan [.]: .
# Scanning...
#   Found 130 issues: 10 conflict, 34 duplicate-value, ...
# Proceed to build an action plan? [Y/n/q] y
#
# Step 2: Plan
#   10 judgmental actions (review recommended)
#   34 mechanical actions (auto-fixable)
# Proceed to review decisions and generate patches? [Y/n/q] y
#
# Step 3: Confirm
#   2 judgmental finding(s) need your decision:
#   Delete --primary? [y/N/q] y
#   ✓ will delete --primary
#   1 patch(es) from confirmed decisions
#
# Step 4: Patch
#   Generated 35 patches (34 mechanical + 1 confirmed).
# Apply patches now? [Y/n/q] y
#
#   ✓ 35 patches applied, 0 failed
#   2 backup files created
# Done.

At each step you can answer y (continue), n (skip to the next step), or q (quit entirely — no changes are made). You can also pass --target=dir and --ignore=a,b to skip the initial directory and ignore-pattern prompts.

The wizard never modifies files until you confirm at the apply step. Even then, every modified file is backed up with a .backup suffix before any change is written.

Without --summary, all commands output raw JSON for piping and programmatic use.

MCP Server

polish exposes 12 tools via the Model Context Protocol, so any AI coding agent (Qoder, Claude, etc.) can drive the full pipeline.

Add to your MCP config (mcp.json, .mcp.json, or your agent's config):

{
  "mcpServers": {
    "polish": {
      "command": "polish",
      "args": ["mcp"]
    }
  }
}

If polish is not on the agent's PATH, use npx instead:

{
  "mcpServers": {
    "polish": {
      "command": "npx",
      "args": ["-y", "polish-design-tokens", "mcp"]
    }
  }
}

Available tools:

ToolDescription
polish_extractExtract token declarations from a directory
polish_auditScan + cross-reference to produce findings
polish_measureNormalize runtime observation data for audit
polish_planConvert findings to a ranked, classified action queue
polish_diffGenerate mechanical patches from a plan
polish_applyExecute patches with backup protection and automatic rollback on failure
polish_rollbackRestore files from an apply run's backup manifest
polish_doctorCheck optional dependencies and environment health
polish_style_lookupQuery brand DESIGN.md design token data
polish_seedGenerate a draft tokens.css + tokens.seed.json from repeated literal values
polish_vocabRead-only project token vocabulary grouped by kind, with gap analysis
polish_preflightRead-only generation-time check that flags hardcoded literals before they land in the page

Node.js API

import { plan, generateDiffs, apply } from 'polish-design-tokens';
import { extract, audit, runPipeline, measure, runWizard } from 'polish-design-tokens';

// Full pipeline: scan → audit → plan → diff (does NOT apply)
const { graph, findings, plan, patches } = runPipeline('./my-project');

// Interactive wizard (audit → plan → diff → apply with prompts)
const wizardResult = await runWizard({ target: './my-project' });

// Manual step-by-step
const graph = extract('./my-project');
const report = audit('./my-project');
const actions = plan(report.findings);
const patches = generateDiffs(actions);
const result = await apply(patches, './my-project');

API Reference

FunctionSignatureDescription
extract(target: string, ignore?: string[]) → DeclarationGraphScan a directory for token declarations and references
audit(target: string, ignore?: string[], observation?: RuntimeObservation) → AuditReportScan + cross-reference to produce findings
runPipeline(target: string, ignore?: string[], observation?: RuntimeObservation) → PipelineResultFull pipeline: extract → audit → plan → diff (no apply)
scan(target: string, opts?: { ignore?: string[] }) → DeclarationGraphLow-level scan, same as extract
cross(graph: DeclarationGraph, observation?: RuntimeObservation) → AuditReportJudge findings from a declaration graph
measure(docs?: unknown[]) → RuntimeObservationNormalize runtime observation data for audit
plan(findings: Finding[]) → PlanAction[]Rank and classify findings into an action queue
generateDiffs(planItems: PlanAction[]) → Patch[]Generate mechanical patches from a plan
apply(patches: Patch[], target?: string) → Promise<ApplyResult>Apply patches with backup protection (target defaults to cwd)
confirm(decisions: Decision[], graph: DeclarationGraph) → { patches: Patch[], unmatched: Array<{ decision: Decision; reason: string }> }Resolve designer-confirmed decisions into patches
seed(target: string, opts?: { output?: string, force?: boolean }) → SeedResultGenerate a draft token system (tokens.css + tokens.seed.json) from literal clusters
init(target: string, opts?: { mode?, starter?, agent?, force? }) → Promise<InitResult>One-command onboarding: detect the mode and write the token contract
agentInit(target: string, opts?: { platforms?, force? }) → Promise<AgentInitResult>Write agent rule files for Claude Code / Cursor / Windsurf
vocab(target: string) → VocabRead root tokens from a directory or .css file as a structured vocab
starterVocab(brand: string) → VocabBuild a starter vocab from a bundled brand reference set
instructions(opts?: { target?: string }) → stringGenerate the design token contract text
preflight(opts: { code, lang, vocab? }) → PreflightResultRead-only generation-time literal check on code text
createDemo(opts?: { target?: string }) → DemoResultWrite the reproducible sample AI-generated project
DEFAULT_SYSTEMDefaultSystemThe built-in default system (naming vocabulary + numeric scales)
renderDefaultCss() → stringRender the polish-default tokens.css draft
scaleStepOf`(kind: string, value: string) → numbernull`
roleOfProperty`(property: string) → NamingRolenull`
suggestName(cluster, opts?: { existingNames?: Set<string> }) → NameSuggestionSuggest a semantic name (or null fallback) for one literal cluster
generateReport(report: AuditReport) → stringGenerate a self-contained interactive HTML report
runWizard(opts?: WizardOptions) → Promise<WizardResult>Interactive guided pipeline with confirmation prompts

TypeScript definitions are bundled — no @types package needed. All types are exported from the package root.

Format Support

polish scans the following file types. Each is parsed for CSS custom property declarations and var() references:

File TypeExtensionsWhat is Extracted
CSS.cssAll --name: value declarations and var(--name) references
SCSS / LESS.scss, .lessSame as CSS
HTML.html, .htm<style> blocks, inline style="" attributes, <script> style objects
JavaScript / TypeScript.js, .ts, .jsx, .tsx, .mjs, .cjsInline style objects and setProperty() calls; JSX text content is ignored
Vue / Svelte.vue, .svelte<template> inline styles, <script> style objects, <style> blocks

Files inside node_modules, dist, build, .git, .next, .cache, and other common build/dependency directories are automatically skipped. Use the ignore option to exclude additional path fragments.

MCP Integration Details

All 10 MCP tools accept and return JSON. Key parameters:

  • polish_extract — { target: string, ignore?: string[] } → DeclarationGraph
  • polish_audit — { target: string, ignore?: string[], observation?: object } → { findings, summary, graphSummary, observation }
  • polish_measure — { documents: unknown[] } → RuntimeObservation
  • polish_plan — { findings: Finding[] } → { plan, summary }
  • polish_diff — { plan: PlanAction[], target?: string } → { patches, preview }
  • polish_apply — { patches: Patch[], target: string } → ApplyResult
  • polish_rollback — { backups: { file, backup }[], target: string } → RollbackResult
  • polish_doctor — {} → dependency health check
  • polish_style_lookup — { brand?: string } → brand design token reference
  • polish_seed — { target: string, output?: string, force?: boolean } → { tokensCss, seedFile, outputFiles, tokenCount, clusterCount }

The polish_style_lookup tool falls back to bundled brand data (Vercel, Stripe, Linear, Notion, Anthropic, GitHub, shadcn, Figma) when no external skill files are found, making it work on any machine without additional setup.

Static vs Runtime Analysis

polish-design-tokens performs static analysis — it scans source files (CSS, SCSS, HTML, JS/TS) to find token declarations, references, and conflicts. This works on any project, any environment, no extra setup required.

Runtime measurement (checking actual rendered values in a live browser) is available via the measure() function, exported from this package. It detects runtime-drift and hardcoded findings that only appear when tokens are evaluated in a real browser. This requires Chrome DevTools to be available. A companion MCP package can wrap measure() with browser automation if you prefer not to call it directly.

For most use cases — auditing a project's source, fixing mechanical issues, and verifying token consistency — the static pipeline in polish-design-tokens is sufficient. Use measure() (or a browser-automation companion) when you need to verify what users actually see in the browser.

What It Finds

Mechanical (auto-fixable by polish diff + polish apply):

  • duplicate-value — Two or more token names share the same value. Fix: make secondary tokens alias the primary.

Judgmental (flagged for human review, no auto-patch):

  • dangling — A token is referenced but never declared. Requires supplying a canonical value — auto-inserting inherit can produce invalid or broken CSS.
  • hardcoded — Raw color or space values used directly instead of token references. Requires choosing the right token to map to. Detected only with runtime measurement (measure()); static scans won't produce it.
  • conflict — Same token name declared with different values. Requires choosing a canonical value.
  • cascade-override — Normal CSS cascading produces unintended value variation. Requires deciding whether to refactor or accept.
  • namespace — Multiple naming conventions coexist (e.g. --color-* and --bg-*). Requires unifying naming.
  • orphan — Declared but never referenced. Requires deciding to remove or keep.
  • runtime-drift — Token values differ across pages when measured at runtime. Requires investigating the source. Detected only with runtime measurement (measure()); static scans won't produce it.
  • state-variation — Token values differ across component states (e.g., :hover, :focus). Requires deciding whether to split into separate tokens or accept the variation.
  • theme-variation — Token values differ across themes (e.g., dark/light). Requires deciding whether to formalize the theme structure.
  • dynamic-variable — Tokens with dynamic (non-static) values, such as those computed at runtime. Requires deciding how to handle the dynamic behavior.
  • literal-cluster (info / judgmental / priority 13) — The same literal value is used repeatedly across the project — a token candidate.

Bridge from no tokens

Projects with no existing token system can still adopt polish. literal-cluster findings surface repeated literal values (colors, spacing, radii, font sizes) as token candidates. The flow:

  1. Run polish seed <target> to generate a draft tokens.css and an authoritative tokens.seed.json (naming map + tokenize decisions).
  2. Edit the token names in tokens.seed.json to match your conventions.
  3. Run polish confirm tokens.seed.json --target=<target> to replace the literals with var() references.

Backups and rollback apply as usual — every confirm run is backed up before it writes, and a failed run is rolled back.

Semantic auto-naming. seed derives a suggested name for every literal cluster from three signals: the property (color → text, background → surface, border-color → border), the selector (component words like .card / .btn → variant), and the value (px values → nearest default scale step). Names are tiered by confidence, following a prefer-no-wrong-name policy:

TierWhenExampleApplied
highProperty and component-selector signal--color-surface-card, --space-2Yes — adopted automatically
mediumA single signal--color-text, --radius-4Yes, but polish confirm prints the suggestions for review first
lowNo signal, or a triggered guard--color-1, --space-3Yes — falls back to the ordinal name

Four guards keep wrong names out: the role/variant words must come from the built-in vocabulary, conflicting roles (a value used as both background and text) demotes to an ordinal, a name already taken by an earlier cluster or a declared root token demotes the later one, and scale collisions skip taken names so tokens.css never gets two --space-2 declarations. tokens.css marks non-high names provisional; each tokens.seed.json map entry carries namingConfidence and suggestionBasis, and chosenName stays the single authority for confirm.

Greenfield projects can start from the built-in default system instead of an empty scaffold:

polish init . --mode=greenfield --starter=polish-default

This writes tokens.css with the default scale steps (--space-2: 8px, --radius-4: 8px, --font-size-2: 14px, …) plus the colour semantic layer as names-only guidance — colour values are deliberately left to you. Or run polish init . with no options and let it auto-detect: generate (tokens exist), migrate (literals exist → seeds a draft), or greenfield.

Troubleshooting

polish_style_lookup returns found: false No external design-md skill files were found, and no brand name was provided. Pass a brand parameter (e.g. "vercel", "stripe") to use the bundled brand data, or install the awesome-design-md skill for full coverage.

polish apply reports before text not found The patch's before string doesn't match the file content exactly — whitespace, quotes, or line content may differ. Check the .backup file (created before each apply) and regenerate patches from a fresh audit.

runtime-drift findings appear with no observation data Runtime findings (runtime-drift, hardcoded) require a RuntimeObservation from measure(). Static-only audits won't produce them. Call measure() with browser-observed variable data and pass it as the observation parameter to audit() or cross().

Large projects scan slowly The scanner is zero-dependency and single-threaded. For projects with thousands of files, use the ignore option to exclude directories that don't contain tokens. Binary files (detected by null bytes) are skipped automatically.

Performance Notes

  • Scan is O(n × m) where n is the number of files and m is the average file size. The parser uses a single-pass state machine for CSS and regex-based extraction for HTML/JS — no AST parsing overhead.
  • Cross is O(d²) in the worst case for conflict detection, where d is the number of declarations per token name. In practice, most tokens have fewer than 10 declarations, so this is negligible.
  • Apply reads each file once and writes it once, regardless of how many patches target it. Backups are created once per file.
  • The tool has zero runtime dependencies — no npm install required at runtime beyond the package itself.

Why Use It

  • Closes the loop — extract → critique → apply, no manual patching
  • Safe — only mechanical fixes are auto-applied; judgmental ones are flagged
  • Backed up — automatic file backups before any apply
  • Agent-ready — MCP protocol lets any AI coding agent drive the pipeline
  • Zero dependencies — pure JavaScript, works anywhere Node.js runs

Repo Structure

DirectoryDescription
polish-mono/Unified npm package for distribution (polish-design-tokens) — core tool, CLI, MCP server, tests
examples/Sample projects with known token issues
docs/Design specs and implementation plans

Examples

See examples/walkthrough/ — a complete, runnable walkthrough of the full pipeline (audit → plan → diff → apply) on a demo project with real pipeline outputs, including a visual flow diagram and terminal screenshots.

Also see examples/legacy-token-audit/noah-sample/ — an archived artifact from the token-audit era: a rich test case covering all finding types, including a real-world stylesheet with duplicate values, hardcoded colors, and dangling references. Generated by the old tool, kept for reference.

Show your migration

Real migrations are the best proof this works. If you used polish to tokenize an AI-generated or legacy project, share your story:

  1. Open a Migration Story issue
  2. Paste a real before snippet (hardcoded values) and the after snippet (the same code with var(--*) token references)
  3. Paste your polish check <project> --summary output — it should show Health: clean

Real files and real output only — no marketing fluff. Approved stories are read by everyone deciding whether to adopt polish.

License

MIT

NPM
polish-design-tokens
Install Command
npm install polish-design-tokens