Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
#!/usr/bin/env python3
"""Theme tokens — WCAG contrast verification (design gate).
Computes WCAG 2.1 relative-luminance contrast ratios for every critical
text/surface, accent-on-surface, and status pair in both light and dark
modes, and asserts the floors from the redesign plan:
- body text on primary surfaces >= 7.0 (AAA)
- secondary text / large text / status >= 4.5 (AA)
- interactive / non-text UI >= 3.0
Semi-transparent tokens (borders, muted fills) are alpha-composited over
their surface before the ratio is computed, so the numbers reflect what a
user actually sees.
This gate ships with the ui package so every consumer verifies the SAME
canonical token set. Consumers extend (never fork) via JSON config:
contrast-check.py [--extend config.json ...]
where config.json may contain:
{
"light": { "token-name": "#RRGGBB or rgba(...)" , ... },
"dark": { "token-name": "..." , ... },
"checks": [ ["fg-token", "bg-token", 4.5, "Label"], ... ]
}
Extension tokens are merged into the base palettes (consumer-only tokens
should use fresh names; redefining a canonical token is allowed but means
the consumer has diverged — prefer not to). Extension checks are appended
to the base check list and run in both modes.
Exits non-zero if any required pair misses its floor (CI gate).
"""
from __future__ import annotations
import argparse
import json
import re
import sys
# --------------------------------------------------------------------------
# Color helpers
# --------------------------------------------------------------------------
def _hex_to_rgb(h: str) -> tuple[float, float, float]:
h = h.lstrip("#")
if len(h) == 3:
h = "".join(c * 2 for c in h)
return tuple(int(h[i : i + 2], 16) / 255 for i in (0, 2, 4))
def _parse(color: str) -> tuple[float, float, float, float]:
"""Return (r, g, b, alpha) in 0..1 from a hex or rgba() string."""
color = color.strip()
if color.startswith("#"):
r, g, b = _hex_to_rgb(color)
return r, g, b, 1.0
m = re.match(r"rgba?\(([^)]+)\)", color)
if not m:
raise ValueError(f"unparseable color: {color}")
parts = [p.strip() for p in m.group(1).split(",")]
r, g, b = (int(parts[i]) / 255 for i in range(3))
a = float(parts[3]) if len(parts) > 3 else 1.0
return r, g, b, a
def _composite(fg: str, bg: str) -> tuple[float, float, float]:
"""Alpha-composite fg over an opaque bg, return opaque rgb."""
fr, fg_, fb, fa = _parse(fg)
br, bg_, bb, _ = _parse(bg)
return (
fr * fa + br * (1 - fa),
fg_ * fa + bg_ * (1 - fa),
fb * fa + bb * (1 - fa),
)
def _lin(c: float) -> float:
return c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.4
def _lum(rgb: tuple[float, float, float]) -> float:
r, g, b = (_lin(c) for c in rgb)
return 0.2126 * r + 0.7152 * g + 0.0722 * b
def contrast(fg: str, bg: str) -> float:
"""WCAG contrast ratio of fg over (opaque) bg, compositing alpha first."""
fg_rgb = _composite(fg, bg)
bg_rgb = _composite(bg, bg)
l1, l2 = _lum(fg_rgb), _lum(bg_rgb)
hi, lo = max(l1, l2), min(l1, l2)
return (hi + 0.05) / (lo + 0.05)
# --------------------------------------------------------------------------
# Token values (must mirror packages/ui/styles/globals.css)
# --------------------------------------------------------------------------
LIGHT = {
"bg-root": "#FBF6F1",
"bg-surface": "#FFFFFF",
"bg-elevated": "#F7F4F1",
"bg-inset": "#F0EBE6",
"bg-canvas": "#F0EBE6", # --color-bg-canvas → var(--color-bg-inset)
"text-primary": "#241B2C",
"text-secondary": "#5E5360",
"focus-ring": "#5E5360", # --color-focus-ring → var(--color-text-secondary)
"field-bg": "#F5F1ED",
# --color-action-soft-hover (ink 11%) composited on the page and a card.
"action-soft-page": "#E3DEDB", "action-soft-card": "#E7E6E8",
"text-tertiary": "#8C7F88",
"text-inverse": "#FFFFFF",
"text-on-accent": "#241B2C",
"action-primary": "#241B2C", "action-primary-hover": "#3B2F45", "text-on-action": "#FFFFFF",
"accent-primary": "#A16215",
"accent-fill": "#F59520",
"accent-secondary": "#58436C",
"border-default": "rgba(88,67,108,0.12)",
"border-active": "rgba(176,107,18,0.90)",
"success": "#1D8155",
"warning": "#856700",
"error": "#B23A2E",
"info": "#3F6EA5",
# Blueprint diagram ink (light) — KG canvas + mermaid.
"diagram-node-fill": "#241B2C",
"diagram-node-fill-2": "#4A4152",
"diagram-node-text": "#FBF6F1",
"diagram-node-border": "#241B2C",
"gradient-ember-end": "#F7A94D",
# KG node faces (light) — paper cards with ink outline.
"kg-node-fill": "#FFFDF8",
"kg-node-fill-2": "#F3ECE2",
"kg-node-text": "#241B2C",
"kg-node-border": "#241B2C",
"kg-node-border-2": "#8C7F88",
# Textured face composite: 0.78 warm-white wash over the paper photo
# (avg ~#E6E8E9) — what text actually sits on.
"kg-node-face-textured": "#FAF8F4",
# Community family hubs (light) — graph clustering palette.
"community-1": "#C0641A", "community-2": "#58436C", "community-3": "#B23A2E",
"community-4": "#6B7A3D", "community-5": "#B06A86", "community-6": "#4A5D7A",
"community-7": "#A8821F", "community-8": "#8A7A66", "community-9": "#7A2F4A",
"community-10": "#B85A38", "community-11": "#2F6B66", "community-12": "#5E5360",
# Series (light): the community 1, 2, info, 4, 5, 7, 3 and 6 values.
# The share tail is exempt: it is always named.
"series-1": "#C0641A", "series-2": "#58436C", "series-3": "#3F6EA5",
"series-4": "#6B7A3D", "series-5": "#B06A86", "series-6": "#A8821F",
"series-7": "#B23A2E", "series-8": "#4A5D7A",
# Heat steps (light): --color-accent-primary mixed into --color-bg-surface
# at 10/26/50%, then accent-primary and accent-hover.
"heat-1": "#F6EFE8", "heat-2": "#E7D6C2", "heat-3": "#D0B08A",
"heat-4": "#A16215", "heat-5": "#824F10",
# Release moment ground and glow band (What's new dialog).
"release-ground": "#FBF6F1", "release-card": "#FFFFFF", "release-glow-1": "#F8DFC2", "release-glow-2": "#E8DEEF", "release-glow-3": "#DDE7F3",
}
DARK = {
"bg-root": "#0E0E0F",
"bg-surface": "#141416",
"bg-elevated": "#191A1C",
"bg-inset": "#0A0A0B",
"bg-canvas": "#0A0A0B", # --color-bg-canvas → var(--color-bg-inset)
"text-primary": "#EEEAF4",
"text-secondary": "#A79DB3",
"focus-ring": "#A79DB3", # --color-focus-ring → var(--color-text-secondary)
"field-bg": "#101012",
# --color-action-soft-hover (white 12%) composited on a card and elevated.
"action-soft-page": "#353537", "action-soft-card": "#303032",
"text-tertiary": "#786F84",
"text-inverse": "#17131D",
"text-on-accent": "#17131D",
"action-primary": "#F2F2F3", "action-primary-hover": "#D6D6D9", "text-on-action": "#0E0E0F",
"accent-primary": "#F59520",
"accent-fill": "#F59520",
"accent-secondary": "#A98FC4",
"border-default": "rgba(213,197,232,0.10)",
"border-active": "rgba(245,149,32,0.55)",
"success": "#34D399",
"warning": "#E8B339",
"error": "#E06A5A",
"info": "#7DA7D9",
# Blueprint diagram ink (dark) — border carries canvas separation.
"diagram-node-fill": "#322A3E",
"diagram-node-fill-2": "#261F30",
"diagram-node-text": "#EEEAF4",
"diagram-node-border": "rgba(222,210,235,0.45)",
"gradient-ember-end": "#F7A94D",
# KG node faces (dark) — alias back to the solid ink blocks.
"kg-node-fill": "#322A3E",
"kg-node-fill-2": "#261F30",
"kg-node-text": "#EEEAF4",
"kg-node-border": "rgba(222,210,235,0.45)",
"kg-node-border-2": "rgba(222,210,235,0.45)",
# Textured face composite: 0.85 ink wash (#322A3E) over the paper photo.
"kg-node-face-textured": "#4D4658",
# Community family hubs (dark) — lifted to read on the near-black canvas.
"community-1": "#F59520", "community-2": "#A98FC4", "community-3": "#E06A5A",
"community-4": "#A9BB6F", "community-5": "#D795B1", "community-6": "#8FA3C0",
"community-7": "#D9B04A", "community-8": "#B8A68E", "community-9": "#C4708F",
"community-10": "#EBA585", "community-11": "#6FB3AB", "community-12": "#A79DB3",
# Series (dark): the same hues' dark values.
"series-1": "#F59520", "series-2": "#A98FC4", "series-3": "#7DA7D9",
"series-4": "#A9BB6F", "series-5": "#D795B1", "series-6": "#D9B04A",
"series-7": "#E06A5A", "series-8": "#8FA3C0",
# Heat steps (dark): --color-accent-primary mixed into the dark card at
# 12/26/42/75%, then accent-primary.
"heat-1": "#2F2317", "heat-2": "#4E3619", "heat-3": "#724A1A",
"heat-4": "#BD751E", "heat-5": "#F59520",
"release-ground": "#111013", "release-card": "#1B191E", "release-glow-1": "#2B1C0E", "release-glow-2": "#1F1729", "release-glow-3": "#121A26",
}
# (fg, bg, floor, label) — floor is the WCAG ratio the pair must meet.
CHECKS = [
("text-primary", "bg-root", 7.0, "Body text on page"),
("text-primary", "bg-surface", 7.0, "Body text on card"),
("text-primary", "bg-elevated", 7.0, "Body text on elevated"),
("text-secondary", "bg-root", 4.5, "Secondary text on page"),
("text-secondary", "bg-surface", 4.5, "Secondary text on card"),
("text-tertiary", "bg-surface", 3.0, "Tertiary/hint on card"),
("accent-primary", "bg-surface", 4.5, "Accent text on card"),
("accent-primary", "bg-root", 4.5, "Accent text on page"),
("accent-secondary", "bg-surface", 4.5, "Plum link-alt on card"),
("text-on-accent", "accent-fill", 4.5, "Text on accent fill (CTA)"),
("text-inverse", "accent-primary", 4.5, "Text on accent-primary fill"),
("text-on-action", "action-primary", 4.5, "Text on primary action (ink button)"),
("text-on-action", "action-primary-hover", 4.5, "Text on primary action hover"),
# Neutral state roles: control-selected/-text alias the action pair, the tab
# underline is text-primary and bars are text-secondary (non-text, 3:1).
("text-on-action", "action-primary", 4.5, "Text on selected segment or switch"),
("action-primary", "bg-surface", 3.0, "Selected control / tab underline on card"),
("action-primary", "bg-root", 3.0, "Selected control / tab underline on page"),
("text-tertiary", "bg-surface", 3.0, "Selected chip border on card"),
("text-tertiary", "bg-root", 3.0, "Selected chip border on page"),
("text-secondary", "bg-surface", 3.0, "Progress and data bar on card"),
("text-secondary", "bg-inset", 3.0, "Progress and data bar on inset track"),
("text-secondary", "bg-elevated", 3.0, "Progress and data bar on elevated track"),
# Keyboard focus ring (non-text, 3:1) on every ground a control sits on.
*[("focus-ring", bg, 3.0, f"Focus ring on {bg}") for bg in ("bg-root", "bg-surface", "bg-elevated", "bg-inset")],
# Form fields: the value, a disabled value and the placeholder on the well.
("text-primary", "field-bg", 7.0, "Field value"),
("text-secondary", "field-bg", 4.5, "Disabled field value"),
("text-tertiary", "field-bg", 3.0, "Field placeholder"),
# Soft-ink copy-prompt button: its label at the hovered (strongest) fill.
("text-primary", "action-soft-page", 4.5, "Soft action label on page"),
("text-primary", "action-soft-card", 4.5, "Soft action label on card"),
("success", "bg-surface", 4.5, "Success text on card"),
("warning", "bg-surface", 4.5, "Warning text on card"),
("warning", "bg-root", 4.5, "Warning text on page"),
("warning", "bg-elevated", 4.5, "Warning text on elevated"),
("error", "bg-surface", 4.5, "Error text on card"),
("info", "bg-surface", 4.5, "Info text on card"),
("border-active", "bg-surface", 3.0, "Active border on card"),
# Blueprint ink nodes (KG canvas): text on both ink weights; the node
# boundary (fill in light, border in dark) must separate from the canvas.
("diagram-node-text", "diagram-node-fill", 4.5, "Ink node text on primary fill"),
("diagram-node-text", "diagram-node-fill-2", 4.5, "Ink node text on secondary fill"),
("diagram-node-border", "bg-canvas", 3.0, "Ink node boundary on canvas"),
("kg-node-text", "kg-node-fill", 4.5, "KG card text on primary face"),
("kg-node-text", "kg-node-fill-2", 4.5, "KG card text on secondary face"),
("kg-node-border", "bg-canvas", 3.0, "KG card outline on canvas"),
("kg-node-border-2", "bg-canvas", 3.0, "KG supporting outline on canvas"),
("kg-node-text", "kg-node-face-textured", 4.5, "KG card text on textured face"),
("text-on-accent", "gradient-ember-end", 4.5, "Text on ember gradient end"),
# Community hubs are non-text node fills on the graph canvas — floor 3.0:1.
*[
(f"community-{n}", "bg-canvas", 3.0, f"Community {n} hub on canvas")
for n in range(1, 13)
],
# Chart series (bars, wedges, legend swatches) are non-text UI on page and card.
*[
(f"series-{n}", bg, 3.0, f"Series {n} on {where}")
for n in range(1, 9)
for bg, where in (("bg-root", "page"), ("bg-surface", "card"))
],
# Heatmap cells print their value: ink on the light steps, card colour on the dark.
*[("text-primary", f"heat-{n}", 4.5, f"Value on heat step {n}") for n in (1, 2, 3)],
*[("bg-surface", f"heat-{n}", 4.5, f"Value on heat step {n}") for n in (4, 5)],
# What's new: ink on the ground and both glow stops (the band carries the
# heading only, so links sit on the ground), and the series accents
# beside the release figures.
*[
(fg, bg, floor, f"{fg} on {bg}")
for bg in ("release-ground", "release-glow-1", "release-glow-2", "release-glow-3")
for fg, floor in (("text-primary", 7.0), ("text-secondary", 4.5))
],
("accent-primary", "release-ground", 4.5, "accent-primary on release-ground"),
*[
(fg, "release-card", floor, f"{fg} on release-card")
for fg, floor in (("text-primary", 7.0), ("text-secondary", 4.5), ("accent-primary", 4.5))
],
*[(f"series-{n}", "release-ground", 3.0, f"Series {n} on release ground") for n in range(1, 6)],
]
def _load_extensions(paths: list[str]) -> tuple[dict, dict, list]:
"""Merge extension configs: extra tokens per mode + extra checks."""
light, dark, checks = dict(LIGHT), dict(DARK), list(CHECKS)
for path in paths:
with open(path, encoding="utf-8") as f:
ext = json.load(f)
light.update(ext.get("light", {}))
dark.update(ext.get("dark", {}))
for entry in ext.get("checks", []):
fg, bg, floor, label = entry
checks.append((fg, bg, float(floor), label))
return light, dark, checks
def run(extend: list[str]) -> int:
light, dark, checks = _load_extensions(extend)
failures = 0
rows: list[str] = []
for mode, tokens in (("Light", light), ("Dark", dark)):
rows.append(f"\n### {mode} mode\n")
rows.append("| Pair | Ratio | Floor | Result |")
rows.append("|------|-------|-------|--------|")
for fg, bg, floor, label in checks:
try:
ratio = contrast(tokens[fg], tokens[bg])
except KeyError as e:
print(
f"contrast gate config error: token {e} not defined for "
f"{mode.lower()} mode (check '{label}'). Extension configs "
"must define referenced tokens in BOTH light and dark.",
file=sys.stderr,
)
return 2
ok = ratio >= floor
if not ok:
failures += 1
mark = "PASS" if ok else "**FAIL**"
rows.append(f"| {label} | {ratio:.2f} | {floor:.1f} | {mark} |")
print("\n".join(rows))
print(f"\n**Total pairs:** {len(checks) * 2} · **Failures:** {failures}")
return 1 if failures else 0
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument(
"--extend",
action="append",
default=[],
metavar="JSON",
help="JSON file adding consumer tokens (light/dark maps) and checks; repeatable",
)
args = parser.parse_args()
return run(args.extend)
if __name__ == "__main__":
sys.exit(main())