Editorial diagram design for Claude Code, Codex, GitHub Copilot, Cursor, Factory Droid, Qoder, and Pi. 45 diagram types. Self-contained HTML + SVG. No shadows. No Mermaid slop.
fix(verifiers): land chart verifier fixes from nine PRs (#350)
Cathryn Lavery9cc2a269e903
diff --git a/scripts/test-verify-axonometric-plan.py b/scripts/test-verify-axonometric-plan.pyindex 53a62bf..93c28a5 100644--- a/scripts/test-verify-axonometric-plan.py+++ b/scripts/test-verify-axonometric-plan.py@@ -18,6 +18,7 @@ import subprocessimport sysimport tempfilefrom pathlib import Path+from decimal import DecimalROOT = Path(__file__).resolve().parent.parentCHECKER = ROOT / "scripts/verify-axonometric-plan.py"@@ -106,6 +107,21 @@ def main() -> int:first_box = re.search(r'<g data-box [^>]*>.*?</g>', office, re.S).group(0)booth_tag = re.search(r'<g data-role="tag" data-name="Booth".*?</g>', office, re.S).group(0)+ # Inline SVG spans style the label without changing its visible name.+ with tempfile.TemporaryDirectory(prefix="verify-label-spans-") as tmp:+ for label, replacement in (+ ("styled span", '<tspan font-weight="600">Open office</tspan>'),+ ("mixed nested span text", 'Open <tspan>of<tspan>fi</tspan>ce</tspan>'),+ ("undrawn title and desc", 'Open office<title>Open office tag</title><desc>Desks</desc>'),+ ):+ path = Path(tmp) / "label-span.html"+ path.write_text(office.replace(">Open office</text>", ">" + replacement + "</text>", 1), encoding="utf-8")+ code, output = run(str(path))+ if code != 0:+ failures.append(f"{label} failed: {output}")+ else:+ print(f"OK: {label} retains the declared name")+cases = {"silhouette vertex moved": (once(r'(data-box [^>]*><path data-role="silhouette" d="M )(-?\d+(?:\.\d+)?)', shift(3), office),@@ -164,6 +180,27 @@ def main() -> int:else:print(f"OK: fails on {name}")+ # Standard SVG numeric spellings do not change the projected silhouette.+ with tempfile.TemporaryDirectory(prefix="silhouette-numeric-") as tmp:+ original = (ASSETS / "example-axonometric-plan-coffee-shop.html").read_text(encoding="utf-8")+ for signed in (False, True):+ def reencode_path(match):+ def number(token):+ text = token.group(0)+ if text in ("0", "1"):+ return text # SVG arc flags are single digits, not numbers.+ encoded = format(Decimal(text), "E")+ return ("+" if signed and not encoded.startswith("-") else "") + encoded+ return match.group(1) + re.sub(r"-?\d+(?:\.\d+)?", number, match.group(2)) + match.group(3)+ encoded = re.sub(r'(<path\b[^>]*?\bd=")([^"]+)(")', reencode_path, original)+ path = Path(tmp) / "numeric.html"+ path.write_text(encoded, encoding="utf-8")+ code, output = run(str(path))+ if code:+ failures.append(f"valid scientific path spelling (signed={signed}) rejected: {output}")+ else:+ print(f"OK: scientific path spelling, signed={signed}")+code, _ = run()if code != 2:failures.append(f"usage error should exit 2, got {code}")diff --git a/scripts/test-verify-beeswarm.py b/scripts/test-verify-beeswarm.pyindex 1bc5573..9ad0cc5 100644--- a/scripts/test-verify-beeswarm.py+++ b/scripts/test-verify-beeswarm.py@@ -223,6 +223,21 @@ class Harness:def run_cases(h: Harness) -> int:++ separated = ''.join(dot(i * 10, drawn_cy=150 + i * 10) for i in range(24))+ h.expect_clean("a separated value axis remains measurable", document(separated, TICKS))+ collapsed = ''.join(dot(i * 10, drawn_cx=500, drawn_cy=150 + i * 10)+ for i in range(24))+ collapsed_ticks = ''.join(tick(value, position=500) for value in (0, 100, 200, 400))+ h.expect_finding("distinct values cannot share a zero scale despite legal dodge",+ document(collapsed, collapsed_ticks), "zero or non-finite scale")+ inverted = ''.join(dot(i * 10, drawn_cx=1000 - cx(i * 10), drawn_cy=150 + i * 10)+ for i in range(24))+ inverted_ticks = ''.join(tick(value, position=1000 - cx(value))+ for value in (0, 100, 200, 400))+ h.expect_clean("a finite nonzero inverted axis remains measurable",+ document(inverted, inverted_ticks))+# ── Positive polarity: honest figures pass ────────────────────────────for path in SHIPPED:found = verify.check(path)diff --git a/scripts/test-verify-bubble.py b/scripts/test-verify-bubble.pyindex b5cdbce..585eccf 100644--- a/scripts/test-verify-bubble.py+++ b/scripts/test-verify-bubble.py@@ -211,6 +211,23 @@ class Harness:def run_cases(h: Harness) -> int:++ collapsed_x = re.sub(r'cx="[^"]*"', 'cx="500"', honest())+ collapsed_x = re.sub(r'(<text data-tick="x"[^>]* x=")[^"]*',+ r'\g<1>500', collapsed_x)+ h.expect_finding("distinct x values cannot collapse onto one column",+ collapsed_x, "zero or non-finite scale")+ collapsed_y = re.sub(r'cy="[^"]*"', 'cy="250"', honest())+ collapsed_y = re.sub(r'(<text data-tick="y"[^>]* y=")[^"]*',+ r'\g<1>254', collapsed_y)+ h.expect_finding("distinct y values cannot collapse onto one row",+ collapsed_y, "zero or non-finite scale")+ inverted = re.sub(r'cx="([^"]*)"',+ lambda m: 'cx="%g"' % (1000 - float(m.group(1))), honest())+ inverted = re.sub(r'(<text data-tick="x"[^>]* x=")([^"]*)',+ lambda m: m.group(1) + str(1000 - float(m.group(2))), inverted)+ h.expect_clean("a finite nonzero inverted axis remains measurable", inverted)+# ── Positive polarity: honest figures pass ────────────────────────────for path in SHIPPED:found = verify.check(path)diff --git a/scripts/test-verify-dumbbell.py b/scripts/test-verify-dumbbell.pyindex 8845386..5738070 100644--- a/scripts/test-verify-dumbbell.py+++ b/scripts/test-verify-dumbbell.py@@ -101,6 +101,21 @@ def test_identical_and_tiny_values():ok(ceiling > floor, "sub-unit magnitudes still yield a usable domain")+def test_small_domains_round_outward():+ for values in ([4e-13, 9e-13], [-9e-13, -4e-13],+ [-4e-13, 9e-13], [0, 9e-13], [-9e-13, 0],+ [4e-100, 9e-100], [1e-13, 1e-13]):+ floor, ceiling = resolve_domain(values)+ ok(floor <= min(values) <= max(values) <= ceiling,+ "small values %r remain inside the outward-rounded domain" % (values,))+ ok(all(verify_dumbbell.PLOT_X0 <= scale(value, floor, ceiling)+ <= verify_dumbbell.PLOT_X0 + verify_dumbbell.PLOT_WIDTH+ for value in values),+ "small values %r map inside the prescribed plot" % (values,))+ ok(resolve_domain([4e-13, 9e-13]) == (0.0, 1e-12),+ "small positive data chooses the first enclosing ladder magnitude")++def test_empty_and_non_finite_rejected():"""The other polarity: garbage in must raise, not return a silent domain."""for label, values in (("empty input", []),@@ -187,6 +202,7 @@ def main() -> int:test_zero_touching_domains()test_sign_cases_resolve()test_identical_and_tiny_values()+ test_small_domains_round_outward()test_empty_and_non_finite_rejected()test_truncated_bounds_are_detected()test_scaling_preserves_gap_ratios()diff --git a/scripts/test-verify-exploded.py b/scripts/test-verify-exploded.pyindex 2b9863f..adda83d 100644--- a/scripts/test-verify-exploded.py+++ b/scripts/test-verify-exploded.py@@ -18,6 +18,7 @@ import subprocessimport sysimport tempfilefrom pathlib import Path+from decimal import DecimalROOT = Path(__file__).resolve().parent.parentCHECKER = ROOT / "scripts/verify-exploded.py"@@ -103,6 +104,21 @@ def main() -> int:crowded = page(module, module.FIGURES["exploded-phone"]())module.explode = real_explode+ # Inline SVG spans style the label without changing its visible name.+ with tempfile.TemporaryDirectory(prefix="verify-label-spans-") as tmp:+ for label, replacement in (+ ("styled span", '<tspan font-weight="600">Data</tspan>'),+ ("mixed nested span text", 'D<tspan>a<tspan>t</tspan></tspan>a'),+ ("undrawn title and desc", 'Data<title>Data part</title><desc>Storage layer</desc>'),+ ):+ path = Path(tmp) / "label-span.html"+ path.write_text(stack.replace(">Data</text>", ">" + replacement + "</text>", 1), encoding="utf-8")+ code, output = run(str(path))+ if code != 0:+ failures.append(f"{label} failed: {output}")+ else:+ print(f"OK: {label} retains the declared name")+cases = {"silhouette vertex moved": (once(r'(data-role="silhouette" d="M )(-?\d+(?:\.\d+)?)', bump_first_number, stack),@@ -181,6 +197,53 @@ def main() -> int:else:print(f"OK: fails on {name}")+ # Standard SVG numeric spellings do not change the projected silhouette.+ with tempfile.TemporaryDirectory(prefix="silhouette-numeric-") as tmp:+ original = (ASSETS / "example-exploded-phone.html").read_text(encoding="utf-8")+ for signed in (False, True):+ def reencode_path(match):+ def number(token):+ text = token.group(0)+ if text in ("0", "1"):+ return text # SVG arc flags are single digits, not numbers.+ encoded = format(Decimal(text), "E")+ return ("+" if signed and not encoded.startswith("-") else "") + encoded+ return match.group(1) + re.sub(r"-?\d+(?:\.\d+)?", number, match.group(2)) + match.group(3)+ encoded = re.sub(r'(<path\b[^>]*?\bd=")([^"]+)(")', reencode_path, original)+ path = Path(tmp) / "numeric.html"+ path.write_text(encoded, encoding="utf-8")+ code, output = run(str(path))+ if code:+ failures.append(f"valid scientific path spelling (signed={signed}) rejected: {output}")+ else:+ print(f"OK: scientific path spelling, signed={signed}")++ spec = importlib.util.spec_from_file_location("verify_exploded_numeric", CHECKER)+ verifier = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(verifier)+ points, arcs, _ = verifier.parse_path("M .5 +.25 L -1e1 2E+1 Z")+ if points != [(0.5, 0.25), (-10.0, 20.0)] or arcs != [False, False]:+ failures.append(f"signed/leading-decimal operands misread: {points}, {arcs}")+ for malformed in ("M 1e+ 2 L 3 4 Z", "M 1e999 2 L 3 4 Z", "M 1 2 q 3 4 Z",+ "M 1 2 A 3 4 0 0e0 1 5 6 Z", "M 1 2 A 3 4 0 0 1.0 5 6 Z"):+ try:+ verifier.parse_path(malformed)+ except (ValueError, IndexError):+ print("OK: malformed, non-finite, or unsupported path is rejected")+ else:+ failures.append(f"invalid path accepted: {malformed}")++ with tempfile.TemporaryDirectory(prefix="silhouette-flag-") as tmp:+ changed = once(r'(data-role="silhouette" d="M [^"]*? A [\d.]+ [\d.]+ 0 )0( 1 )',+ r'\g<1>0e0\2', phone)+ path = Path(tmp) / "invalid-flag.html"+ path.write_text(changed, encoding="utf-8")+ code, output = run(str(path))+ if not code or "arc flags must be literal 0 or 1" not in output:+ failures.append(f"invalid native arc flag accepted: {output}")+ else:+ print("OK: invalid numeric arc-flag spelling is rejected by public verifier")+code, _ = run()if code != 2:failures.append(f"usage error should exit 2, got {code}")diff --git a/scripts/test-verify-heatmap.py b/scripts/test-verify-heatmap.pyindex 7feb140..0559bc5 100644--- a/scripts/test-verify-heatmap.py+++ b/scripts/test-verify-heatmap.py@@ -337,12 +337,73 @@ def main() -> int:"dark focal value text fails 4.5:1 contrast against the actual dark underlay",)++ with tempfile.TemporaryDirectory() as tmp:+ d = Path(tmp)+ for factor in (250_000_000, 1_000_000_000, 10_000_000_000):+ scaled = re.sub(r'data-value="(\d+)"',+ lambda m: 'data-value="%d"' % (int(m.group(1)) * factor),+ original)+ code, output = run(write(d, f"billion-counts-{factor}.html", scaled))+ if code != 0:+ failures.append(f"finite counts scaled by {factor} were rejected: {output.strip()}")+ for invalid in ("nan", "inf", "-1", "1e400"):+ changed = original.replace('data-value="4"', f'data-value="{invalid}"', 1)+ code, output = run(write(d, "invalid-value.html", changed))+ if code == 0 or "expected 30 cells" not in output or "Traceback" in output:+ failures.append(f"invalid {invalid} did not retain grid completeness finding: {output.strip()}")+ print("OK: billion-scale counts preserve the grid; non-finite/negative values remain findings")++ with tempfile.TemporaryDirectory() as tmp:+ d = Path(tmp)+ for original_source, label in ((original, "light"),+ (GOOD_DARK.read_text(encoding="utf-8"), "dark")):+ pixel_lengths = re.sub(r'\b(x|y|width|height)="([-+0-9.eE]+)"',+ lambda m: f'{m.group(1)}="{m.group(2)}px"', original_source)+ code, output = run(write(d, f"pixel-lengths-{label}.html", pixel_lengths))+ if code != 0:+ failures.append(f"equivalent pixel lengths {label} were rejected: {output.strip()}")+ # Supported coordinate syntax must not bypass the contrast comparison.+ for template, theme in ((original, "light"),+ (GOOD_DARK.read_text(encoding="utf-8"), "dark")):+ bad_contrast = template.replace('x="578" y="149" fill="#111111"',+ 'x="578" y="149" fill="#ffffff"', 1)+ for notation in ("px", "exponent-px"):+ def length(match: re.Match[str]) -> str:+ number = match.group(2)+ if notation == "exponent-px":+ number = f"{float(number):.4e}"+ return f'{match.group(1)}="{number}px"'+ changed = re.sub(r'\b(x|y|width|height)="([-+0-9.eE]+)"', length, bad_contrast)+ code, output = run(write(d, f"bad-contrast-{theme}-{notation}.html", changed))+ if code == 0 or "below WCAG AA" not in output or "Traceback" in output:+ failures.append(f"{theme}/{notation} bypassed contrast failure: {output.strip()}")+ for length in ("520%", "unknown", "nan", "1e400px"):+ changed = original.replace(FOCAL_CELL, FOCAL_CELL.replace('x="520"', f'x="{length}"'), 1)+ code, output = run(write(d, "unsupported-length.html", changed))+ if code == 0 or "focal-text contrast measurement" not in output or "Traceback" in output:+ failures.append(f"unsupported length {length!r} lacked a named finding: {output.strip()}")+ print("OK: equivalent pixel lengths pass; unsupported/non-finite lengths are named findings")++ # Translucent foregrounds compose against the cell beneath them, not paper.+ with tempfile.TemporaryDirectory() as tmp:+ d = Path(tmp)+ for template, theme in ((original, "light"),+ (GOOD_DARK.read_text(encoding="utf-8"), "dark")):+ for alpha, expected_pass in (("0.8", True), ("0.2", False)):+ changed = template.replace('x="578" y="149" fill="#111111"',+ f'x="578" y="149" fill="rgba(17,17,17,{alpha})"', 1)+ code, output = run(write(d, f"alpha-{theme}-{alpha}.html", changed))+ if (code == 0) != expected_pass or (not expected_pass and "below WCAG AA" not in output):+ failures.append(f"alpha foreground {theme}/{alpha} unexpected result: {output.strip()}")+ print("OK: translucent AA foregrounds pass; weak-alpha text still fails in both themes")+if failures:for f in failures:print("FAIL:", f, file=sys.stderr)return 1- print(f"OK — {13 + 3} cases ({3} positive, {13} negative), all passed.")+ print("OK — every heatmap verifier case passed.")return 0diff --git a/scripts/test-verify-polar.py b/scripts/test-verify-polar.pyindex be43509..d338002 100644--- a/scripts/test-verify-polar.py+++ b/scripts/test-verify-polar.py@@ -498,6 +498,78 @@ def main() -> int:),]+ # Presentation attributes follow the actual SVG ancestor paint semantics.+ for attribute in ('visibility="hidden"', 'display="none"', 'opacity="0"'):+ cases.append((+ f"ancestor {attribute}",+ VALID.replace('data-polar-category="c1"', f'data-polar-category="c1" {attribute}'),+ "explicitly hidden",+ ))+ for attribute in ('display="none"', 'opacity="0"'):+ cases.append((+ f"ancestor {attribute} cannot be restored",+ VALID.replace('data-polar-category="c1"', f'data-polar-category="c1" {attribute}')+ .replace('<text data-polar-value-label="">25</text>',+ '<text data-polar-value-label="" display="inline" opacity="1" visibility="visible">25</text>'),+ "explicitly hidden",+ ))+ cases.append((+ "hidden chart ancestor",+ VALID.replace('<body>', '<body><div style="display:none">').replace('</body>', '</div></body>'),+ "explicitly hidden",+ ))+ for style in ("display:none!important; display:block",+ "display: none ! important ; display:block",+ "visibility:hidden !important; visibility:visible"):+ cases.append((+ f"inline important ancestor {style}",+ VALID.replace('<body>', f'<body><div style="{style}">').replace('</body>', '</div></body>'),+ "explicitly hidden",+ ))+ cases.append((+ "child explicit inherit retains hidden visibility",+ VALID.replace('data-polar-category="c1"', 'data-polar-category="c1" visibility="hidden"')+ .replace('<text data-polar-value-label="">25</text>',+ '<text data-polar-value-label="" visibility="inherit">25</text>'),+ "explicitly hidden",+ ))+ for css in ("body { display:none; }", "body { visibility:hidden; }",+ ":root { opacity:0%; }", ".wrapper { opacity:-1; }",+ "body { display:none!important; display:block; }"):+ cases.append((+ f"stylesheet ancestor hiding {css}",+ VALID.replace('<body>', f'<head><style>{css}</style></head><body class="wrapper">'),+ "CSS visibility rules can hide chart ancestors",+ ))+ for value in ("0%", "-1", "-10%"):+ cases.append((+ f"ancestor opacity {value}",+ VALID.replace('data-polar-category="c1"', f'data-polar-category="c1" opacity="{value}"'),+ "explicitly hidden",+ ))+ positive_visibility = [+ ("visible child overrides hidden parent", VALID.replace(+ 'data-polar-category="c1"', 'data-polar-category="c1" visibility="hidden"'+ ).replace('<text data-polar-value-label="">25</text>',+ '<text data-polar-value-label="" visibility="visible">25</text>')),+ ("initial visibility restores child", VALID.replace(+ 'data-polar-category="c1"', 'data-polar-category="c1" visibility="hidden"'+ ).replace('<text data-polar-value-label="">25</text>',+ '<text data-polar-value-label="" visibility="initial">25</text>')),+ ("hidden sibling does not affect categories", VALID.replace(+ '<svg ', '<div hidden><br/></div><svg ', 1)),+ ("ordinary stylesheet layout", VALID.replace('<body>',+ '<head><style>body { display:flex; opacity:50%; visibility:visible; }</style></head><body>')),+ ("important visible declaration wins", VALID.replace('<body>',+ '<body><div style="display:block!important; display:none">').replace('</body>', '</div></body>')),+ ("percentage opacity remains visible", VALID.replace(+ 'data-polar-category="c1"', 'data-polar-category="c1" opacity="50%"')),+ ("invalid opacity is ignored", VALID.replace(+ 'data-polar-category="c1"', 'data-polar-category="c1" opacity="invalid"')),+ ("ordinary visible category", VALID.replace(+ 'data-polar-category="c1"', 'data-polar-category="c1" visibility="visible" opacity="0.5"')),+ ]+failures: list[str] = []with tempfile.TemporaryDirectory() as scratch:root = Path(scratch)@@ -507,8 +579,16 @@ def main() -> int:if findings != []:failures.append(f"valid fixture: expected no findings, got {findings}")- for label, source, expected in cases:- path = root / f"{label.replace(' ', '-')}.html"+ # Index-based names: labels contain characters Windows forbids in paths.+ for index, (label, source) in enumerate(positive_visibility):+ path = root / f"positive-{index}.html"+ path.write_text(source, encoding="utf-8")+ findings = module.check(path)+ if findings:+ failures.append(f"{label}: expected no findings, got {findings}")++ for index, (label, source, expected) in enumerate(cases):+ path = root / f"case-{index}.html"path.write_text(source, encoding="utf-8")findings = module.check(path)if not findings:diff --git a/scripts/test-verify-slopegraph.py b/scripts/test-verify-slopegraph.pyindex 37f2c04..8a09775 100644--- a/scripts/test-verify-slopegraph.py+++ b/scripts/test-verify-slopegraph.py@@ -221,6 +221,19 @@ def main() -> int:def run_cases(h: Harness) -> int:++ collapsed = document(''.join(+ series(name, frm, to, y1=250, y2=250)+ + labels(name, frm, to, y_from=250, y_to=250)+ for name, frm, to in ROWS))+ h.expect_finding("distinct values cannot collapse to a flat value axis",+ collapsed, "zero or non-finite scale")+ inverted = document(''.join(+ series(name, frm, to, y1=500-y(frm), y2=500-y(to))+ + labels(name, frm, to, y_from=500-y(frm), y_to=500-y(to))+ for name, frm, to in ROWS))+ h.expect_clean("a finite nonzero inverted axis remains measurable", inverted)+# ── Negative half: honest figures must stay silent ────────────────────h.expect_clean("an honest slopegraph reports nothing", honest(ROWS))diff --git a/scripts/test-verify-waterfall.py b/scripts/test-verify-waterfall.pyindex 5da1949..602603c 100644--- a/scripts/test-verify-waterfall.py+++ b/scripts/test-verify-waterfall.py@@ -12,7 +12,9 @@ Exit: 0 all pass, 1 a case failed.from __future__ import annotations+import reimport subprocess+from decimal import Decimalimport sysimport tempfilefrom pathlib import Path@@ -23,10 +25,11 @@ GOOD = ROOT / "skills/diagram-design/assets/example-waterfall.html"SHIPPED = sorted(GOOD.parent.glob("example-waterfall*.html"))-def run(*args: str) -> tuple[int, str]:+def run(*args: str, timeout: float | None = None) -> tuple[int, str]:result = subprocess.run([sys.executable, str(CHECKER), *args],capture_output=True,+ timeout=timeout,text=True,encoding="utf-8",errors="replace",@@ -40,6 +43,26 @@ def write(directory: Path, name: str, source: str) -> Path:return path+def decimal_budget(source: str, factor: str, cents: bool = False) -> str:+ """Render the shipped walk in another unit, with exact decimal declarations."""+ values = [Decimal(n) * Decimal(factor) for n in (240, 64, -38, 22, -52)]+ if cents:+ values = [v + d for v, d in zip(values, map(Decimal, (".1", ".1", "-.1", ".1", "-.3")))]+ values.append(sum(values))+ formatted = [str(v) if i in (0, 5) else f"{v:+}" for i, v in enumerate(values)]+ it = iter(formatted)+ result = re.sub(r'data-value="[^"]+"', lambda m: f'data-value="{next(it)}"', source)+ levels = [values[0]]+ for value in values[1:-1]:+ levels.append(levels[-1] + value)+ it = iter(levels)+ result = re.sub(r'data-carry="[^"]+"', lambda m: f'data-carry="{next(it)}"', result)+ for old, new in zip(("240", "+64", "−38", "+22", "−52", "236"), formatted):+ result = result.replace(f">{old}</text>", f">{new.replace('-', '−')}</text>")+ return result+++def main() -> int:source = GOOD.read_text(encoding="utf-8")failures: list[str] = []@@ -78,6 +101,12 @@ def main() -> int:'<rect x="688" y="146" width="96" height="70" fill="rgba(235,108,54,0.12)"',"shared scale puts",),+ (+ "bridge top lie: its bottom stays at the correct running level",+ '<rect x="688" y="146" width="96" height="50" fill="rgba(235,108,54,0.12)"',+ '<rect x="688" y="136" width="96" height="60" fill="rgba(235,108,54,0.12)"',+ "top edge drawn",+ ),("missing carry: a gap has no connector conserving the total",'<line x1="496" y1="167" x2="544" y2="167" stroke="rgba(45,49,66,0.55)" stroke-width="1" data-carry="266"/>',@@ -187,15 +216,20 @@ def main() -> int:with tempfile.TemporaryDirectory() as tmp:directory = Path(tmp)+ bridge_paths: list[Path] = []for index, (name, old, new, expected) in enumerate(cases):if old not in source:failures.append(f"fixture drift: {name} — mutation target not found in {GOOD.name}")continuemutated = source.replace(old, new)path = write(directory, f"example-waterfall-mutant-{index}.html", mutated)+ if name.startswith("bridge"):+ bridge_paths.append(path)code, output = run(str(path))if code == 0:failures.append(f"checker stayed quiet on: {name}")+ elif code != 1 or "Traceback" in output:+ failures.append(f"checker must return findings without crashing on {name}:\n{output}")elif expected not in output:failures.append(f"checker fired on {name} but without naming the lie "@@ -204,6 +238,12 @@ def main() -> int:else:print(f"OK: fails on {name}")+ code, output = run(*(str(path) for path in bridge_paths), str(GOOD))+ if code != 1 or "Traceback" in output or any(f"FAIL {path}" not in output for path in bridge_paths) or f"OK {GOOD}" not in output:+ failures.append(f"geometry findings must not stop checks of remaining files:\n{output}")+ else:+ print("OK: bridge findings do not stop subsequent file checks")+# Usage contract: no arguments is an error, not a silent pass.code, _ = run()if code != 2:@@ -211,12 +251,35 @@ def main() -> int:else:print("OK: usage error exits 2")+ with tempfile.TemporaryDirectory() as tmp:+ d = Path(tmp)+ budget = decimal_budget(source, "1000000", cents=True)+ small = decimal_budget(source, "0.001")+ scientific = small.replace('data-value="0.240"', 'data-value="2.40e-1"')+ decimal_cases = (+ ("large dollars and cents", budget, True, ""),+ ("small fractional units", small, True, ""),+ ("equivalent exponent declaration", scientific, True, ""),+ ("one-cent end mismatch", budget.replace('data-value="235999999.9"', 'data-value="235999999.91"'), False, "running total must conserve"),+ ("one-cent carry mismatch", budget.replace('data-carry="240000000.1"', 'data-carry="240000000.11"'), False, "carry declares"),+ ("one-cent printed mismatch", budget.replace('>+64000000.1</text>', '>+64000000.11</text>'), False, "no printed label"),+ ("tiny real discrepancy", small.replace('data-value="0.236"', 'data-value="0.2360000001"'), False, "running total must conserve"),+ ("nonzero underflow", source.replace('data-value="+64"', 'data-value="+1e-1000000000"'), False, "is not a number"),+ ("running overflow", source.replace('data-value="240"', 'data-value="1.6e308"').replace('data-value="+64"', 'data-value="+1.6e308"'), False, "running total must remain finite"),+ )+ for index, (name, changed, expected_pass, fragment) in enumerate(decimal_cases):+ code, output = run(str(write(d, f"decimal-{index}.html", changed)), timeout=10)+ if (code == 0) != expected_pass or (not expected_pass and fragment not in output) or "Traceback" in output:+ failures.append(f"decimal case {name} unexpected result: {output}")+ else:+ print(f"OK: decimal case {name}")+if failures:print("\nFAIL verify-waterfall tests:")for failure in failures:print(f" - {failure}")return 1- print(f"\nOK: verify-waterfall passes {len(SHIPPED)} shipped files and fails all {len(cases)} mutations")+ print(f"\nOK: verify-waterfall passes {len(SHIPPED)} shipped files and fails all {len(cases)} mutations; 9 decimal controls pass")return 0diff --git a/scripts/verify-beeswarm.py b/scripts/verify-beeswarm.pyindex 7dd1079..1960bd9 100644--- a/scripts/verify-beeswarm.py+++ b/scripts/verify-beeswarm.py@@ -543,6 +543,12 @@ def check_scale(dots: list, findings: list, source: str, name: str):return None, Noneslope, intercept = fit(points)+ if slope == 0 or not all(map(math.isfinite, (slope, intercept))):+ findings.append(+ "%s: the value axis has a zero or non-finite scale — distinct "+ "values must map to distinct finite positions" % name+ )+ return None, Noneif len(points) >= 4:for index, (value, drawn) in enumerate(points):peers = points[:index] + points[index + 1:]diff --git a/scripts/verify-bubble.py b/scripts/verify-bubble.pyindex 54f173a..606766e 100644--- a/scripts/verify-bubble.py+++ b/scripts/verify-bubble.py@@ -641,6 +641,13 @@ def check_axis(bubbles: list, axis: str, findings: list, name: str):)return None, None+ if slope == 0 or not all(map(math.isfinite, (slope, intercept))):+ findings.append(+ "%s:%d: the %s axis has a zero or non-finite scale — distinct "+ "values must map to distinct finite positions" % (name, line, axis)+ )+ return None, None+# A bubble whose PEERS all share one value cannot be measured: the# leave-one-out fit for it is degenerate, so `outliers` skips it, and the# full-set fit passes exactly through wherever it was drawn — its positiondiff --git a/scripts/verify-dumbbell.py b/scripts/verify-dumbbell.pyindex 8b9974c..2c1e19f 100644--- a/scripts/verify-dumbbell.py+++ b/scripts/verify-dumbbell.py@@ -91,7 +91,9 @@ def _nice_magnitude(value: float) -> float:base = 10.0 ** exponentfor step in (1.0, 2.0, 2.5, 5.0, 10.0):candidate = step * base- if candidate >= magnitude - 1e-12:+ # Bounds must enclose the data even when its unit is much smaller+ # than a fixed epsilon. The ladder already provides outward rounding.+ if candidate >= magnitude:return candidatereturn 10.0 * base@@ -188,6 +190,10 @@ def check_domain_rules():("crossing zero", [-20, 5, 40, -3]),("single identical pair", [7, 7]),("tiny magnitudes", [0.0004, 0.0009]),+ ("small positive magnitudes", [4e-13, 9e-13]),+ ("small negative magnitudes", [-9e-13, -4e-13]),+ ("small crossing-zero magnitudes", [-4e-13, 9e-13]),+ ("small zero-touching magnitudes", [0, 9e-13]),]for label, values in cases:try:diff --git a/scripts/verify-exploded.py b/scripts/verify-exploded.pyindex 736e648..51251c3 100644--- a/scripts/verify-exploded.py+++ b/scripts/verify-exploded.py@@ -80,7 +80,17 @@ class Tree(HTMLParser):self.cur = node.parentdef handle_data(self, data):+ # A label's visible name includes inline tspan descendants, in source+ # order, as well as text before and after them. <title> and <desc> are+ # never drawn, so their text stays out of the label.self.cur.text += data+ if self.cur.tag in ("title", "desc"):+ return+ for ancestor in self.cur.ancestors():+ if ancestor.tag in ("title", "desc"):+ return+ if ancestor.tag == "text":+ ancestor.text += data# ---------------------------------------------------------------- projection (independent of the builder)@@ -139,18 +149,35 @@ def silhouette_poly(origin, r, z0, z1, n=24):def parse_path(d):"""Return (endpoints, is_arc, arcs as (rx, ry, rotation, large-arc, sweep)) for an absolute M/L/A/Z path."""- tokens = re.findall(r"[MLAZ]|-?\d+(?:\.\d+)?", d)+ token_re = re.compile(r"[MLAZ]|[-+]?(?:\d*\.\d+|\d+\.?\d*)(?:[eE][-+]?\d+)?")+ tokens = []+ end = 0+ for match in token_re.finditer(d):+ if d[end:match.start()].strip(" \t\r\n,"):+ raise ValueError(f"unsupported path token {d[end:match.start()]!r}")+ tokens.append(match.group())+ end = match.end()+ if d[end:].strip(" \t\r\n,"):+ raise ValueError(f"unsupported path token {d[end:]!r}")++ def operand(index):+ value = float(tokens[index])+ if not math.isfinite(value):+ raise ValueError("non-finite path operand")+ return valuepts, arcs, radii = [], [], []i = 0while i < len(tokens):cmd = tokens[i]if cmd in ("M", "L"):- pts.append((float(tokens[i + 1]), float(tokens[i + 2])))+ pts.append((operand(i + 1), operand(i + 2)))arcs.append(False)i += 3elif cmd == "A":- radii.append(tuple(float(tokens[i + k]) for k in range(1, 6)))- pts.append((float(tokens[i + 6]), float(tokens[i + 7])))+ if tokens[i + 4] not in {"0", "1"} or tokens[i + 5] not in {"0", "1"}:+ raise ValueError("arc flags must be literal 0 or 1")+ radii.append(tuple(operand(i + k) for k in range(1, 6)))+ pts.append((operand(i + 6), operand(i + 7)))arcs.append(True)i += 8elif cmd == "Z":diff --git a/scripts/verify-heatmap.py b/scripts/verify-heatmap.pyindex 4ce6dc8..e6f46a7 100644--- a/scripts/verify-heatmap.py+++ b/scripts/verify-heatmap.py@@ -49,6 +49,7 @@ Exit: 0 clean, 1 findings, 2 usage.from __future__ import annotationsimport argparse+import mathimport reimport sysfrom pathlib import Path@@ -80,6 +81,29 @@ CSS_MOVES_MARK_RE = re.compile()+LENGTH_RE = re.compile(+ r"(?P<number>[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?)(?:px)?",+ re.IGNORECASE,+)+++def _length_px(raw: str | None, field: str, errors: list[str] | None) -> float | None:+ """Measure finite unitless/pixel SVG lengths for focal-text contrast."""+ if raw is None:+ return None+ match = LENGTH_RE.fullmatch(raw.strip())+ if match is not None:+ value = float(match.group("number"))+ if math.isfinite(value):+ return value+ if errors is not None:+ errors.append(+ f"unsupported or non-finite {field} length {raw!r} for focal-text "+ "contrast measurement; use a finite unitless or px length"+ )+ return None++def _attr(attrs_str: str, name: str) -> str | None:m = re.search(r"\b" + re.escape(name) + r'\s*=\s*"([^"]*)"', attrs_str)return m.group(1) if m else None@@ -215,7 +239,7 @@ def parse_axis_labels(source: str) -> tuple[list[str], list[str], set[str], set[return declared_rows, declared_cols, duplicate_rows, duplicate_cols-def parse_cells(source: str) -> list[dict]:+def parse_cells(source: str, errors: list[str] | None = None) -> list[dict]:"""Return list of cell dicts: row, col, value, opacity, focal."""source_clean = COMMENT_RE.sub("", source)cells: list[dict] = []@@ -231,7 +255,7 @@ def parse_cells(source: str) -> list[dict]:value = float(val_str)except ValueError:continue- if not (0.0 <= value < 1e9) or value != value: # reject nan/inf/negative+ if not math.isfinite(value) or value < 0: # unsigned finite rates/countscontinuefill = _attr(attrs_str, "fill") or ""@@ -265,17 +289,17 @@ def parse_cells(source: str) -> list[dict]:"opacity": opacity,"focal": focal,"fill": fill,- "x": float(x) if x is not None else None,- "y": float(y) if y is not None else None,- "width": float(width) if width is not None else None,- "height": float(height) if height is not None else None,+ "x": _length_px(x, "x", errors),+ "y": _length_px(y, "y", errors),+ "width": _length_px(width, "width", errors),+ "height": _length_px(height, "height", errors),})return cells-def parse_text_labels(source: str) -> list[dict]:+def parse_text_labels(source: str, errors: list[str] | None = None) -> list[dict]:"""Return SVG text labels with their fill, x, y, and rendered text."""source_clean = COMMENT_RE.sub("", source)texts: list[dict] = []@@ -290,8 +314,8 @@ def parse_text_labels(source: str) -> list[dict]:texts.append({"fill": fill,- "x": float(x) if x is not None else None,- "y": float(y) if y is not None else None,+ "x": _length_px(x, "x", errors),+ "y": _length_px(y, "y", errors),"text": text_content.group(1).strip() if text_content else "",})@@ -314,7 +338,8 @@ def check_file(path: Path) -> list[str]:"cell geometry without changing the attributes this checker reads")- cells = parse_cells(source)+ geometry_errors: list[str] = []+ cells = parse_cells(source, geometry_errors)if not cells:errors.append(@@ -455,7 +480,8 @@ def check_file(path: Path) -> list[str]:if canvas_underlay is None:canvas_underlay = (245, 245, 245)- text_labels = parse_text_labels(source)+ text_labels = parse_text_labels(source, geometry_errors)+ errors.extend(f"{path.name}: {finding}" for finding in geometry_errors)for focal in focal_cells:bg_rgb = _parse_color(focal["fill"], canvas_underlay)if bg_rgb is None:@@ -469,7 +495,7 @@ def check_file(path: Path) -> list[str]:continueif not (x0 <= text["x"] <= x0 + width and y0 <= text["y"] <= y0 + height):continue- text_rgb = _parse_color(text["fill"])+ text_rgb = _parse_color(text["fill"], bg_rgb)if text_rgb is None:continueratio = _contrast_ratio(text_rgb, bg_rgb)diff --git a/scripts/verify-polar.py b/scripts/verify-polar.pyindex 060745b..aad2e3f 100644--- a/scripts/verify-polar.py+++ b/scripts/verify-polar.py@@ -48,6 +48,7 @@ CSS_COMBINATOR = re.compile(r"\s+|[>+~]")class ValueLabel:attrs: dict[str, str]text: str+ hidden: bool@dataclass@@ -167,13 +168,21 @@ def _allowed_stylesheet(href: str) -> bool:def _style_property(attrs: dict[str, str], property_name: str) -> str | None:+ # The last declaration wins, except that an !important declaration beats+ # any later normal one, as in the CSS cascade.result: str | None = None+ result_important = Falsefor declaration in attrs.get("style", "").split(";"):if ":" not in declaration:continuename, raw_value = declaration.split(":", 1)- if name.strip().casefold() == property_name:- result = raw_value.split("!", 1)[0].strip().casefold()+ if name.strip().casefold() != property_name:+ continue+ value, _, priority = raw_value.partition("!")+ important = re.fullmatch(r"\s*important\s*", priority, re.I) is not None+ if important or not result_important:+ result = value.strip().casefold()+ result_important = result_important or importantreturn result@@ -194,6 +203,7 @@ class PolarParser(HTMLParser):self.style_blocks: list[str] = []self.stylesheet_urls: list[str] = []self._stack: list[str] = []+ self._visibility_stack: list[tuple[bool, str]] = []self._style_stack: list[tuple[int, int]] = []self._chart_depth: int | None = Noneself._chart: Chart | None = None@@ -219,6 +229,10 @@ class PolarParser(HTMLParser):else:data[key] = raw_value or ""depth = len(self._stack)+ parent_state = (+ self._visibility_stack[-1] if self._visibility_stack else (False, "visible")+ )+ visibility_state = _visibility_state(data, parent_state)if tag == "style":self.style_blocks.append("")@@ -291,7 +305,14 @@ class PolarParser(HTMLParser):current = self._current_category()if current is not None:if tag == "text" and "data-polar-value-label" in data:- label = ValueLabel(attrs=data, text="")+ label = ValueLabel(+ attrs=data,+ text="",+ hidden=(+ visibility_state[0]+ or visibility_state[1] in {"hidden", "collapse"}+ ),+ )current.value_labels.append(label)self._value_label_stack.append((depth, label))if tag == "line":@@ -323,6 +344,7 @@ class PolarParser(HTMLParser):if tag not in VOID_ELEMENTS:self._stack.append(tag)+ self._visibility_stack.append(visibility_state)def handle_data(self, data: str) -> None:if self._style_stack:@@ -344,6 +366,7 @@ class PolarParser(HTMLParser):self.parse_findings.append(f"mismatched closing tag </{tag}>")returnself._stack.pop()+ self._visibility_stack.pop()depth = len(self._stack)while self._style_stack and self._style_stack[-1][0] >= depth:@@ -379,30 +402,45 @@ def _point(attrs: dict[str, str], x_key: str, y_key: str) -> tuple[float, float]return x, y-def _explicitly_hidden(attrs: dict[str, str]) -> bool:- if "hidden" in attrs or attrs.get("aria-hidden", "").strip().casefold() == "true":- return True- if attrs.get("display", "").strip().casefold() == "none":- return True- if attrs.get("visibility", "").strip().casefold() == "hidden":- return True- if "opacity" in attrs and _float(attrs["opacity"].strip()) == 0:- return True- for declaration in attrs.get("style", "").split(";"):- if ":" not in declaration:- continue- name, raw_value = declaration.split(":", 1)- name = name.strip().casefold()- value = raw_value.split("!", 1)[0].strip().casefold()- if (name == "display" and value == "none") or (- name == "visibility" and value == "hidden"- ):- return True- if name == "opacity" and _float(value) == 0:- return True+def _opacity(value: str) -> float:+ if value.endswith("%"):+ return _float(value[:-1]) / 100+ return _float(value)+++def _stylesheet_can_hide_ancestors(css: str) -> bool:+ # Without a CSS cascade engine, a hiding rule on an allowed HTML selector+ # cannot prove readable labels. Reject the rule rather than guessing which+ # ancestor or competing declaration wins; ordinary layout remains allowed.+ without_comments = re.sub(r"/\*.*?\*/", "", css, flags=re.DOTALL)+ for _, declarations in CSS_RULE.findall(without_comments):+ for declaration in declarations.split(";"):+ suppressed, visibility = _visibility_state({"style": declaration}, (False, "visible"))+ if suppressed or visibility in {"hidden", "collapse"}:+ return Truereturn False+def _visibility_state(+ attrs: dict[str, str], parent: tuple[bool, str]+) -> tuple[bool, str]:+ # Display and group opacity suppress all descendants. Visibility is inherited+ # but can be restored explicitly on a child, unlike those ancestor effects.+ suppressed, visibility = parent+ suppressed = suppressed or (+ "hidden" in attrs+ or attrs.get("aria-hidden", "").strip().casefold() == "true"+ or _presentation_property(attrs, "display") == "none"+ or _opacity(_presentation_property(attrs, "opacity")) <= 0+ )+ own_visibility = _presentation_property(attrs, "visibility")+ if own_visibility in {"visible", "hidden", "collapse"}:+ visibility = own_visibility+ elif own_visibility == "initial":+ visibility = "visible"+ return suppressed, visibility++def check(path: Path) -> list[str]:"""Return all contract violations found in one HTML document."""@@ -419,6 +457,8 @@ def check(path: Path) -> list[str]:findings.append("CSS stylesheet loading is forbidden in polar documents")if any(_contains_geometry_css(css) for css in parser.style_blocks):findings.append("CSS geometry properties are forbidden in polar documents")+ if any(_stylesheet_can_hide_ancestors(css) for css in parser.style_blocks):+ findings.append("CSS visibility rules can hide chart ancestors")if any(_stylesheet_can_target_chart(css) for css in parser.style_blocks):findings.append("CSS selectors must not target data-polar-chart")if any(not _allowed_stylesheet(href) for href in parser.stylesheet_urls):@@ -668,7 +708,7 @@ def check(path: Path) -> list[str]:else:label = category.value_labels[0]label_value = _float(label.text.strip())- if _explicitly_hidden(label.attrs):+ if label.hidden:findings.append(f"category {category.name!r} value label is explicitly hidden")if not isfinite(label_value):findings.append(f"category {category.name!r} value label must be finite numeric")diff --git a/scripts/verify-slopegraph.py b/scripts/verify-slopegraph.pyindex 475eaee..0bce267 100644--- a/scripts/verify-slopegraph.py+++ b/scripts/verify-slopegraph.py@@ -625,6 +625,15 @@ def check_scale(series: list, findings: list, name: str) -> None:left_fit = fit(left)right_fit = fit(right)+ if any(slope is not None and+ (slope == 0 or not all(map(math.isfinite, (slope, intercept))))+ for slope, intercept in (left_fit, right_fit)):+ findings.append(+ "%s:%d: a value axis has a zero or non-finite scale — distinct "+ "values must map to distinct finite positions" % (name, line)+ )+ return+if left_fit[0] is not None and right_fit[0] is not None:slope_drift = abs(left_fit[0] - right_fit[0]) * spanif slope_drift > SCALE_TOLERANCE:diff --git a/scripts/verify-waterfall.py b/scripts/verify-waterfall.pyindex e97603e..569faf2 100644--- a/scripts/verify-waterfall.py+++ b/scripts/verify-waterfall.py@@ -51,6 +51,8 @@ import htmlimport mathimport reimport sys+from decimal import Decimal, InvalidOperation+from fractions import Fractionfrom pathlib import PathROOT = Path(__file__).resolve().parent.parent@@ -79,11 +81,11 @@ GEOMETRY_TOLERANCE = 0.75# A carry must reach both bars it connects. 2px forgives stroke caps, nothing# more.CARRY_SPAN_TOLERANCE = 2.0-VALUE_TOLERANCE = 1e-9+HORIZONTAL_TOLERANCE = 1e-9MAX_BARS = 8MAX_SUBTOTALS = 1ACCENT_STROKES = {"#eb6c36", "#f08a59"}-SIGN_CHARS = {"+": 1.0, "-": -1.0, "\u2212": -1.0}+SIGN_CHARS = {"+": 1, "-": -1, "\u2212": -1}def attrs_of(tag_attrs: str) -> dict[str, str]:@@ -98,6 +100,26 @@ def parse_number(raw: str) -> float | None:return None+def parse_exact_number(raw: str) -> Fraction | None:+ """Keep finite decimal declarations exact; geometry still uses floats."""+ projected = parse_number(raw)+ if projected is None:+ return None+ if projected == 0:+ # Inspect only the decimal coefficient/exponent before constructing a+ # rational denominator; nonzero underflow is not representable geometry.+ try:+ if not Decimal(raw).is_zero():+ return None+ except InvalidOperation:+ return None+ return Fraction(0)+ try:+ return Fraction(raw)+ except (ValueError, ZeroDivisionError):+ return None++def transform_carrier(attrs: dict[str, str]) -> str | None:"""Describe an attribute or inline style that can move verified geometry."""if "transform" in attrs:@@ -173,13 +195,14 @@ def check_transforms(source: str, errors: list[str]) -> None:class Bar:- __slots__ = ("role", "value", "name", "x", "y", "w", "h", "fill", "stroke", "index")+ __slots__ = ("role", "value", "exact_value", "name", "x", "y", "w", "h", "fill", "stroke", "index")- def __init__(self, index: int, role: str, value: float, name: str,+ def __init__(self, index: int, role: str, value: Fraction, name: str,x: float, y: float, w: float, h: float, fill: str, stroke: str) -> None:self.index = indexself.role = role- self.value = value+ self.value = float(value)+ self.exact_value = valueself.name = nameself.x, self.y, self.w, self.h = x, y, w, hself.fill = fill@@ -198,20 +221,20 @@ class Bar:return f"{self.name!r} (bar {self.index + 1})"-def parse_signed(raw: str, *, signed_required: bool) -> tuple[float | None, bool]:+def parse_signed(raw: str, *, signed_required: bool) -> tuple[Fraction | None, bool]:"""Return (value, had_explicit_sign) for a declared or printed value."""text = raw.strip()if not text:return None, Falsesign = SIGN_CHARS.get(text[0])if sign is not None:- magnitude = parse_number(text[1:].strip())+ magnitude = parse_exact_number(text[1:].strip())if magnitude is None:return None, Truereturn sign * magnitude, Trueif signed_required:- return parse_number(text), False- return parse_number(text), False+ return parse_exact_number(text), False+ return parse_exact_number(text), Falsedef parse_bars(source: str, errors: list[str]) -> list[Bar]:@@ -286,39 +309,43 @@ def check_structure(bars: list[Bar], errors: list[str]) -> bool:return True-def running_levels(bars: list[Bar], errors: list[str]) -> list[tuple[float, float]] | None:+def running_levels(bars: list[Bar], errors: list[str]) -> list[tuple[Fraction, Fraction]] | None:"""Return each bar's (level_before, level_after); None when conservation fails."""- levels: list[tuple[float, float]] = []- running = bars[0].value- levels.append((0.0, running))+ levels: list[tuple[Fraction, Fraction]] = []+ running = bars[0].exact_value+ levels.append((Fraction(0), running))conserved = Truefor bar in bars[1:]:if bar.role == "delta":before = running- running += bar.value- if not math.isfinite(running):+ running += bar.exact_value+ try:+ finite_running = math.isfinite(float(running))+ except OverflowError:+ finite_running = False+ if not finite_running:errors.append(f"{bar.label}: the running total must remain finite")return Nonelevels.append((before, running))if running < 0:errors.append(- f"{bar.label}: the running total falls to {running:g}; this grammar anchors totals "+ f"{bar.label}: the running total falls to {float(running):g}; this grammar anchors totals ""at a zero floor and cannot draw a negative walk")conserved = Falseelse:- if abs(running - bar.value) > VALUE_TOLERANCE:+ if running != bar.exact_value:errors.append(- f"{bar.label}: declares {bar.value:g} but the walk arrives at {running:g}; "+ f"{bar.label}: declares {bar.value:g} but the walk arrives at {float(running):g}; ""the running total must conserve")conserved = Falselevels.append((running, running))- running = bar.value+ running = bar.exact_valuereturn levels if conserved else None-def check_geometry(bars: list[Bar], levels: list[tuple[float, float]], errors: list[str]) -> tuple[float, float] | None:+def check_geometry(bars: list[Bar], levels: list[tuple[Fraction, Fraction]], errors: list[str]) -> tuple[float, float] | None:start = bars[0]if start.h <= 0:errors.append(f"{start.label}: the start anchor has no height; no scale can be fitted")@@ -338,31 +365,31 @@ def check_geometry(bars: list[Bar], levels: list[tuple[float, float]], errors: lif abs(bar.y - expected_top) > GEOMETRY_TOLERANCE:errors.append(f"{bar.label}: top edge drawn at y={bar.y:g} but the shared scale puts "- f"the {hi:g} level at y={expected_top:.1f}"+ f"the {float(hi):g} level at y={expected_top:.1f}")if abs(bar.bottom - expected_bottom) > GEOMETRY_TOLERANCE:errors.append(f"{bar.label}: bottom edge drawn at y={bar.bottom:g} but the shared scale puts "- f"the {lo:g} level at y={expected_bottom:.1f}"+ f"the {float(lo):g} level at y={expected_bottom:.1f}")return baseline, scale-def check_carries(source: str, bars: list[Bar], levels: list[tuple[float, float]],+def check_carries(source: str, bars: list[Bar], levels: list[tuple[Fraction, Fraction]],baseline: float, scale: float, errors: list[str]) -> None:- carries: list[tuple[float, float, float, float, str]] = []+ carries: list[tuple[float, float, float, Fraction, str]] = []for match in LINE_RE.finditer(source):attrs = attrs_of(match.group("attrs"))declared = attrs.get("data-carry")if declared is None:continue- value = parse_number(declared)+ value = parse_exact_number(declared)coords = [parse_number(attrs.get(key, "")) for key in ("x1", "y1", "x2", "y2")]if value is None or any(v is None for v in coords):errors.append(f"carry {declared!r}: non-numeric data-carry or coordinates")continuex1, y1, x2, y2 = coords # type: ignore[assignment]- if abs(y1 - y2) > VALUE_TOLERANCE:+ if abs(y1 - y2) > HORIZONTAL_TOLERANCE:errors.append(f"carry {declared!r}: a carry is horizontal; drawn from y={y1:g} to y={y2:g}")continuecarries.append((min(x1, x2), max(x1, x2), y1, value, declared))@@ -382,19 +409,19 @@ def check_carries(source: str, bars: list[Bar], levels: list[tuple[float, float]errors.append(f"{gap_label}: {len(matched)} carries cross one gap; a gap has one running total")continue_, _, y, value, declared = matched[0]- if abs(value - level) > VALUE_TOLERANCE:+ if value != level:errors.append(- f"{gap_label}: carry declares {declared} but the running total between these bars is {level:g}"+ f"{gap_label}: carry declares {declared} but the running total between these bars is {float(level):g}")expected_y = baseline - scale * levelif abs(y - expected_y) > GEOMETRY_TOLERANCE:errors.append(- f"{gap_label}: carry drawn at y={y:g} but the {level:g} level sits at y={expected_y:.1f}"+ f"{gap_label}: carry drawn at y={y:g} but the {float(level):g} level sits at y={expected_y:.1f}")-def printed_values(source: str, bar: Bar) -> list[tuple[float, bool]]:- values: list[tuple[float, bool]] = []+def printed_values(source: str, bar: Bar) -> list[tuple[Fraction, bool]]:+ values: list[tuple[Fraction, bool]] = []for match in TEXT_RE.finditer(source):attrs = attrs_of(match.group("attrs"))x, y = (parse_number(attrs.get(key, "")) for key in ("x", "y"))@@ -417,7 +444,7 @@ def check_printed(source: str, bars: list[Bar], errors: list[str]) -> None:printed = printed_values(source, bar)needs_sign = bar.role == "delta"hit = any(- abs(value - bar.value) <= VALUE_TOLERANCE and (signed or not needs_sign)+ value == bar.exact_value and (signed or not needs_sign)for value, signed in printed)if not hit:diff --git a/skills/diagram-design/references/type-axonometric-plan.md b/skills/diagram-design/references/type-axonometric-plan.mdindex a77a088..933d7a5 100644--- a/skills/diagram-design/references/type-axonometric-plan.md+++ b/skills/diagram-design/references/type-axonometric-plan.md@@ -57,9 +57,11 @@ A floor plan can reveal by zone the same way. Give each zone's furniture a `step- The plate: one `<g data-plate data-rect="x0 y0 x1 y1 r" data-z="0" data-t="t">`.- Each box: a `<g data-box>` with `data-rect`, `data-z` (the plate top, or 8 above it for a tree canopy), `data-h`, `data-kind` (`wall`, `furniture`, `building`, `tree`, `rack`), and for a building `data-name`. Its first path is `data-role="silhouette"`.- Each room: a `<g data-room data-name data-rect>`.-- Each tag: a `<g data-role="tag" data-name data-at="x y z">` with a backing `<rect>` and a `<text data-role="name">`. The point sits inside the room it names at the plate top, or on the building's roof.+- Each tag: a `<g data-role="tag" data-name data-at="x y z">` with a backing `<rect>` and a `<text data-role="name">`. Its complete text, including inline `<tspan>` descendants, must match the tag's `data-name`. The point sits inside the room it names at the plate top, or on the building's roof.- The focal room or building carries `data-focal`.+The silhouette verifier accepts signed decimal and scientific-notation coordinates within the existing absolute M/L/A/Z path contract. Every operand must be finite; projected vertices, corner radii, and arc flags are still checked. This does not add relative path commands.+## Anti-patterns- Full-height walls that hide the rooms behind them.diff --git a/skills/diagram-design/references/type-bar.md b/skills/diagram-design/references/type-bar.mdindex bca091d..ffcb230 100644--- a/skills/diagram-design/references/type-bar.md+++ b/skills/diagram-design/references/type-bar.md@@ -91,7 +91,7 @@ Values 34 and 71 on a 0–100 domain compute to 458.4 and 739.6, rounded to 458### Dumbbell honesty rules-- **Never truncate the value axis.** `floor` and `ceil` follow the data's range, never its observed extremes — taking `min` and `max` as the bounds *is* the truncation. With `lo` and `hi` the smallest and largest values, the four cases are exhaustive: `lo >= 0` anchors `floor = 0` and rounds `ceil` up past `hi`; `hi <= 0` anchors `ceil = 0` and rounds `floor` down past `lo`; `lo < 0 < hi` brackets both sides, and zero then falls inside the plot — give it a line at its scaled position in the axis-line weight, since it is what every gap is read against. The fourth case is the one a sign-based rule drops: **when every value is zero**, `lo == hi == 0` would make `ceil - floor` zero and the position formula divide by zero, so take a finite fallback span (`floor = 0`, `ceil = 1` in the data's unit) and let every dot sit on the floor, which is the truth. Data that merely *touches* zero is covered by the first two cases, not a special one. `scripts/verify-dumbbell.py` implements this and proves finite coordinates for all four. The plot width is fixed, so narrowing the domain raises px-per-unit and draws every gap wider: across the same 760px, an 8-point gap is 61px on a 0–100 axis and 152px on a 40–80 axis. Ratios *between* rows survive the zoom — what inflates is each gap's size against the frame, which is how a reader judges whether a gap is large. The gap is the entire claim, which makes this the most common way a dumbbell lies.+- **Never truncate the value axis.** `floor` and `ceil` follow the data's range, never its observed extremes — taking `min` and `max` as the bounds *is* the truncation. With `lo` and `hi` the smallest and largest values, the four cases are exhaustive: `lo >= 0` anchors `floor = 0` and rounds `ceil` up past `hi` (including fractional data smaller than a fixed absolute tolerance); `hi <= 0` anchors `ceil = 0` and rounds `floor` down past `lo`; `lo < 0 < hi` brackets both sides, and zero then falls inside the plot — give it a line at its scaled position in the axis-line weight, since it is what every gap is read against. The fourth case is the one a sign-based rule drops: **when every value is zero**, `lo == hi == 0` would make `ceil - floor` zero and the position formula divide by zero, so take a finite fallback span (`floor = 0`, `ceil = 1` in the data's unit) and let every dot sit on the floor, which is the truth. Data that merely *touches* zero is covered by the first two cases, not a special one. `scripts/verify-dumbbell.py` implements this and proves finite coordinates for all four. The plot width is fixed, so narrowing the domain raises px-per-unit and draws every gap wider: across the same 760px, an 8-point gap is 61px on a 0–100 axis and 152px on a 40–80 axis. Ratios *between* rows survive the zoom — what inflates is each gap's size against the frame, which is how a reader judges whether a gap is large. The gap is the entire claim, which makes this the most common way a dumbbell lies.- **Both dots share one scale and one unit.** Label both endpoints with their real values. Labelling only the focal end asks the reader to take the geometry on trust.- **The connector is a gap, not a trajectory.** It encodes the distance between two values and nothing about what lies between them — no intermediate points, no rate, no guarantee the change was monotonic. Do not narrate it as movement.- **State the row order** in the legend or source line: by one endpoint, by signed change, by absolute change, or by an order the subject supplies (chronological, geographic, ordinal). "By gap" alone is ambiguous — say signed or absolute. What is not allowed is an unstated order, which reads as arbitrary.diff --git a/skills/diagram-design/references/type-exploded.md b/skills/diagram-design/references/type-exploded.mdindex 8f917d7..b2793ae 100644--- a/skills/diagram-design/references/type-exploded.md+++ b/skills/diagram-design/references/type-exploded.md@@ -84,9 +84,11 @@ An exploded view may open as the assembled object and explode once, because watc- The figure: one `<g data-exploded data-origin="ox oy" data-gap="g">` wrapping every part.- Each part: a `<g>` with `data-part` (key), `data-name` (the label text), `data-rect="x0 y0 x1 y1 r"`, `data-z`, `data-t`, `data-level`, optional `data-kind="housing"` for a container and `data-focal` for the focal part. Animated parts add `data-closed-z`.-- Inside each part: the first `<path data-role="silhouette">` is the part's outline at its declared box, and a `<g data-role="label">` holds a `<line data-role="leader">` and a `<text data-role="name">`.+- Inside each part: the first `<path data-role="silhouette">` is the part's outline at its declared box, and a `<g data-role="label">` holds a `<line data-role="leader">` and a `<text data-role="name">`. Its complete text, including inline `<tspan>` descendants, must match the part's `data-name`.- Trace lines carry `data-role="trace"`.+The silhouette verifier accepts signed decimal and scientific-notation coordinates within the existing absolute M/L/A/Z path contract. Every operand must be finite; projected vertices, corner radii, and arc flags are still checked. This does not add relative path commands.+## Anti-patterns- Hand-placed coordinates, or a CSS `transform` standing in for geometry.diff --git a/skills/diagram-design/references/type-heatmap.md b/skills/diagram-design/references/type-heatmap.mdindex c345791..c3a1efa 100644--- a/skills/diagram-design/references/type-heatmap.md+++ b/skills/diagram-design/references/type-heatmap.md@@ -58,7 +58,7 @@ Every cell is two overlapping `<rect>` elements: a paper-fill underlay (no data## Declaring the values-**Every drawn cell is bound to its row, column, and value.** The paper underlay carries nothing. The data rect carries all three.+**Every drawn cell is bound to its row, column, and value.** Declared data values are finite and nonnegative; unsigned counts may exceed one billion. NaN, infinity, and negative values are rejected rather than weakening grid completeness. The paper underlay carries nothing. The data rect carries all three.| Binding | Without it ||---|---|@@ -69,4 +69,8 @@ Every cell is two overlapping `<rect>` elements: a paper-fill underlay (no data`scripts/verify-heatmap.py` enforces the complete `rows × cols` grid, the monotone fill ramp on non-focal cells, and at most one focal cell. It does **not** verify cell geometry (position, width, height) because both axes are categorical — position encodes "which row/column", and that is carried by the label, not by a scale the checker can measure against.+Focal-text contrast measurement accepts finite unitless and explicit `px` coordinates. Unsupported relative units or malformed lengths produce a named measurement finding, never a traceback; this does not add a quantitative cell-geometry check.++Focal-text contrast composites translucent foreground text against the resolved focal-cell fill before measuring WCAG AA. The 4.5:1 minimum applies to that foreground/background pair in both themes.+**No `transform` on any verified element.** Bake any coordinate offsets directly into `x`/`y` attributes.diff --git a/skills/diagram-design/references/type-line.md b/skills/diagram-design/references/type-line.mdindex 810707c..3b49a5d 100644--- a/skills/diagram-design/references/type-line.md+++ b/skills/diagram-design/references/type-line.md@@ -39,7 +39,7 @@## Variants-- **Slopegraph:** exactly two states, several series, read as slope and rank change. Full spec below.+- **Slopegraph:** exactly two states, several series, read as slope and rank change. Full spec below. Its shared quantitative scale must be finite and nonzero; a flat value axis cannot encode distinct values.- **Ridgeline:** one distribution per series, stacked with deliberate overlap on one shared amplitude. Full spec below.- **Streamgraph:** many periods, few layers, read as a total and its composition breathing. Full spec below.- **Bump chart:** rank movement across 3–6 ordered snapshots, position only. Full spec below.diff --git a/skills/diagram-design/references/type-polar.md b/skills/diagram-design/references/type-polar.mdindex bed1d03..40bc4f3 100644--- a/skills/diagram-design/references/type-polar.md+++ b/skills/diagram-design/references/type-polar.md@@ -109,7 +109,7 @@ The minimal examples use the full 1000×520 canvas. The full-editorial example p- 4–8 categories.- Exactly one quantitative series.- At most one focal category.-- Five grid rings and one numeric value label per category.+- Five grid rings and one numeric value label per category. Numeric labels must be visible through their ancestors: ancestor `display="none"` and zero opacity suppress descendants, while an explicit child `visibility="visible"` can restore inherited hidden visibility.- Static output only; split or change type rather than adding interaction or another encoding.## When not to usediff --git a/skills/diagram-design/references/type-scatter.md b/skills/diagram-design/references/type-scatter.mdindex a73d419..b9ddd1f 100644--- a/skills/diagram-design/references/type-scatter.md+++ b/skills/diagram-design/references/type-scatter.md@@ -61,7 +61,7 @@ Not for: a third value that is really a category (use the focal accent or facet**Area encodes the third value — never radius.** Radius-proportional sizing squares the claim: a 6× value reads as 36× the ink. `scripts/verify-bubble.py` gates it, along with the two axis scales.-- **One linear scale per axis, every bubble on it.** A bubble nudged aside because two crowd each other reads as a different number; crowded bubbles are data, and the honest fixes are a hairline of separation (which the largest-first rule provides) or fewer items — never a moved centre.+- **One finite, nonzero linear scale per axis, every bubble on it.** A bubble nudged aside because two crowd each other reads as a different number; crowded bubbles are data, and the honest fixes are a hairline of separation (which the largest-first rule provides) or fewer items — never a moved centre.- **Axes include zero, or the source line states the bounds.** A bubble's position is read against the origin in a way a slopegraph's is not. No log scale without saying so — and area next to a log axis is a reading most audiences get wrong, so prefer not at all.- **Omitted items are counted in the footnote.** A bubble chart with the inconvenient giant quietly missing is the same lie as a truncated axis.- **A non-positive magnitude cannot be a bubble.** Area has no sign; omit the item and say so.@@ -69,7 +69,7 @@ Not for: a third value that is really a category (use the focal accent or facet#### Declaring the values-**Every drawn quantity is bound to an attribute stating the value it encodes.** The data circle carries all three values; the paper underlay is scenery and carries nothing.+**Every drawn quantity is bound to an attribute stating the value it encodes.** A zero-slope value axis collapses distinct values to one position and is rejected, including in the beeswarm variant. The data circle carries all three values; the paper underlay is scenery and carries nothing.```svg<!-- A bubble: position from two shared linear scales, area from the size.diff --git a/skills/diagram-design/references/type-waterfall.md b/skills/diagram-design/references/type-waterfall.mdindex 76c6959..f5d23fa 100644--- a/skills/diagram-design/references/type-waterfall.md+++ b/skills/diagram-design/references/type-waterfall.md@@ -58,6 +58,7 @@ Endpoint positions round to the nearest integer pixel and never snap to the 4px## Waterfall honesty rules+- **Decimal declarations conserve exactly.** Fractional budgets use exact decimal arithmetic for totals, carries, and printed-value identity; geometry retains its pixel-rounding allowance. A binary floating point accumulation error must not reject a reconciled dollar-and-cent walk, and an actual decimal discrepancy is still a failure.- **The running total must conserve.** Start + every signed bridge = each subtotal and the end total, exactly — the declared `data-value`s must reconcile before geometry is even considered. A waterfall that doesn't add up is not approximately right, it is wrong.- **Bridges span exactly their two running levels.** Each bar's drawn top and bottom must sit where the shared scale puts the running totals before and after it (±0.75px for integer rounding). Stretching one bridge "for legibility" moves money that doesn't exist.- **Every carry sits at the level it transports,** spanning its full gap, and declares that value. A carry drawn at the wrong height reconnects the walk to a different total.