Repository navigation
Expand file tree
/
Copy pathdev_check.py
More file actions
846 lines (739 loc) · 48.9 KB
/
Copy pathdev_check.py
File metadata and controls
846 lines (739 loc) · 48.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
#!/usr/bin/env python3
"""dev_check.py -- self-tests for the shared design system. Stdlib only.
python3 design/dev_check.py
What this exists to stop:
1. design.css drifting from tokens.json (it is generated; the check runs the
generator and byte-compares).
2. The palette silently becoming unreadable. Contrast is COMPUTED here, and
the colour-blindness separation the dataviz validator measured is recorded
in tokens.json with its verdicts pinned.
3. The one rule the whole system exists for going quietly missing: a label may
never be hidden, MEASURED and PREDICTED may never share styling.
"""
from __future__ import annotations
import json
import re
import subprocess
import sys
from pathlib import Path
HERE = Path(__file__).resolve().parent
TOKENS = json.loads((HERE / "tokens.json").read_text())
CSS = (HERE / "design.css").read_text() if (HERE / "design.css").exists() else ""
JS = (HERE / "design.js").read_text()
PASS, FAIL = [], []
def ok(name, cond, detail=""):
(PASS if cond else FAIL).append((name, detail))
# ---------------------------------------------------------------- colour ----
def srgb_to_lin(c):
c = c / 255.0
return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4
def luminance(hex_):
h = hex_.lstrip("#")
r, g, b = (int(h[i:i + 2], 16) for i in (0, 2, 4))
return 0.2126 * srgb_to_lin(r) + 0.7152 * srgb_to_lin(g) + 0.0722 * srgb_to_lin(b)
# EVERY theme carrying a palette, so a newly added one cannot slip past the contrast checks
# unverified. `instrument` was added 2026-08-19 and the loops named three themes literally,
# so it was skipped on the day it became the default.
ALL_THEMES = ("polarize", "dark", "light", "instrument", "instrument-dark", "fieldguide", "fieldguide-dark")
from build_css import _FAMILY_BORROW # noqa: E402 -- single source of truth for palette borrowing
def contrast(a, b):
la, lb = luminance(a), luminance(b)
hi, lo = max(la, lb), min(la, lb)
return (hi + 0.05) / (lo + 0.05)
HEX = re.compile(r"^#[0-9a-fA-F]{6}$")
def check_tokens():
ok("tokens.json has a schema", TOKENS.get("schema", "").startswith("design.tokens"))
ok("the choice not to use a component library is written down, with reasons",
bool(TOKENS.get("why_not_a_component_library", {}).get("why_it_is_not_used_here")))
ok("...and names the obvious alternative rather than pretending there is none",
"shadcn" in json.dumps(TOKENS["why_not_a_component_library"]).lower())
ok("...and says when to revisit the decision",
bool(TOKENS["why_not_a_component_library"].get("when_to_revisit")))
prov = TOKENS.get("palette_provenance", {})
ok("the palette records HOW it was validated", bool(prov.get("method")))
ok("...and names the script rather than claiming judgement",
"validate_palette" in prov.get("method", ""))
ok("...and records what FAILED as well as what passed",
"FAILS" in json.dumps(prov.get("results", {})))
ok("...and keeps the record of the defect it replaced",
"deuteranopia" in json.dumps(prov.get("results", {})))
for mode in ALL_THEMES:
for name, v in TOKENS["color"][mode].items():
# polarize's border/border-strong are intentionally rgba() hairlines
# (the Polarize handoff's own line tokens), not solid hex.
if name in ("shadow", "overlay", "note") or (mode == "polarize" and name in ("border", "border-strong")):
continue
ok(f"{mode}.{name} is a hex colour", bool(HEX.match(v)), v)
ink = TOKENS["audioInk"]
epistemic_hexes = {v[m].lower() for v in TOKENS["epistemic"]["families"].values() for m in ("dark", "light")}
audio_ink_hexes = {ink[name]["value"].lower() for name in ("clay", "ochre", "lichen")}
ok("audioInk colours are a separate namespace from the epistemic tier palette "
"(different semantic axis -- UI role vs. evidence quality -- must never overlap)",
not (epistemic_hexes & audio_ink_hexes), str(epistemic_hexes & audio_ink_hexes))
for f in ("literata-normal-variable.woff2", "literata-italic-400.woff2"):
ok(f"self-hosted font file {f} exists", (HERE / "fonts" / f).exists())
ok("self-hosted font licence text exists", (HERE / "fonts" / "LITERATA-OFL.txt").exists())
ok("self-hosted icon sprite exists", (HERE / "icons" / "polarize-icons.svg").exists())
def check_contrast():
for mode in ALL_THEMES:
bg = TOKENS["color"][mode]["background"]
card = TOKENS["color"][mode]["surface"]
fg = TOKENS["color"][mode]["foreground"]
muted = TOKENS["color"][mode]["muted-foreground"]
faint = TOKENS["color"][mode]["faint-foreground"]
ok(f"{mode}: body text clears WCAG AA (4.5:1)", contrast(fg, bg) >= 4.5,
f"{contrast(fg, bg):.2f}")
ok(f"{mode}: muted text clears AA for body size", contrast(muted, card) >= 4.5,
f"{contrast(muted, card):.2f}")
# Faint is used for section eyebrows and tooltip hints only -- large or
# supplementary text, so the AA-large bar (3:1) is the right one.
ok(f"{mode}: faint text clears AA-large (3:1)", contrast(faint, card) >= 3.0,
f"{contrast(faint, card):.2f}")
# polarize reuses "dark"'s epistemic/series hexes (see build_css.py's
# fam_mode fallback) rather than declaring its own -- so re-verify those
# SAME hexes against polarize's own (different) background/surface
# rather than re-reading tokens under a "polarize" key that doesn't exist.
# ONE borrow map, imported from the builder. Two copies of "which palette does this
# theme reuse" is how a theme ends up contrast-checked against the wrong background.
fam_mode = _FAMILY_BORROW.get(mode, mode)
# A tier badge is TEXT, so it is held to the text bar (4.5:1), not the
# 3:1 a chart mark gets.
for fam, v in TOKENS["epistemic"]["families"].items():
c = contrast(v[fam_mode], card)
ok(f"{mode}: tier colour '{fam}' is readable as text (4.5:1)", c >= 4.5,
f"{c:.2f}")
# Series colours are MARKS. The reference palette documents that three
# light slots sit under 3:1 and mitigates with the relief rule, so the
# check is that the rule is declared -- asserting a contrast the palette
# was never designed to meet would just mean re-stepping a validated set.
low = [i for i, s in enumerate(TOKENS["series"][fam_mode], 1)
if contrast(s, bg) < 3.0]
if mode in ("polarize", "dark"):
ok(f"{mode}: every series colour clears 3:1 on the page", not low, str(low))
else:
ok("light: the sub-3:1 series slots are covered by a declared relief rule",
bool(TOKENS["series"].get("relief_rule")), f"slots {low}")
# audioInk: clay/ochre/lichen-as-text (the tint-safe steps) against the
# polarize surface -- these are used for text (tag labels, timestamps),
# so held to 4.5:1 like the tier colours above, not the 3:1 a chart mark gets.
card = TOKENS["color"]["polarize"]["surface"]
ink = TOKENS["audioInk"]
for name, hexval in (("clay", ink["clay"]["value"]), ("ochre", ink["ochre"]["value"]),
("lichen (text-safe step)", ink["lichen"]["onTint"])):
c = contrast(hexval, card)
ok(f"polarize: audio ink '{name}' is readable as text (4.5:1)", c >= 4.5, f"{c:.2f}")
def check_epistemic():
tiers = TOKENS["epistemic"]["tiers"]
fams = TOKENS["epistemic"]["families"]
ids = [t["id"] for t in tiers]
ok("tier ids are unique", len(ids) == len(set(ids)))
for t in tiers:
ok(f"tier {t['id']} names a real family", t["family"] in fams, t["family"])
ok(f"tier {t['id']} carries a WORD label", bool(t["label"]))
ok(f"tier {t['id']} carries a GLYPH -- hue is never alone",
bool(t.get("glyph")))
ok(f"tier {t['id']} states what it means", len(t.get("meaning", "")) > 20)
# Every family must be reachable, or a colour is defined and never used.
used = {t["family"] for t in tiers}
ok("every family is used by at least one tier", used == set(fams), str(used ^ set(fams)))
# The three that must never be confused.
for a, b in (("measured", "predicted"), ("measured", "refuted"), ("predicted", "refuted")):
for mode in ("dark", "light"):
ca, cb = fams[a][mode], fams[b][mode]
ok(f"{mode}: {a} and {b} are different colours", ca.lower() != cb.lower())
# The tier ladder must be ordered, so a UI can sort by strength of claim.
weights = {t["id"]: t["weight"] for t in tiers}
ok("MEASURED outranks PREDICTED outranks SPEC outranks REFUTED",
weights["MEASURED"] > weights["PREDICTED"] > weights["SPEC"] > weights["REFUTED"])
# Series and tier palettes must not collide, or a chart line can impersonate
# an epistemic claim.
for mode in ("dark", "light"):
series = {s.lower() for s in TOKENS["series"][mode]}
tier_c = {v[mode].lower() for v in fams.values()}
overlap = series & tier_c
# Overlap is expected -- both draw from the same validated reference hues --
# so the rule is enforced by USAGE, not by hex. What must hold is that the
# series list is declared separately and carries its own cap.
ok(f"{mode}: the series palette declares an all-pairs cap",
isinstance(TOKENS["series"].get("all_pairs_cap"), int))
ok(f"{mode}: the cap is 3, matching what the validator actually passed",
TOKENS["series"]["all_pairs_cap"] == 3, str(overlap))
def check_css():
ok("design.css exists", bool(CSS))
proc = subprocess.run([sys.executable, str(HERE / "build_css.py"), "--check"],
capture_output=True, text=True)
ok("design.css is not stale (regenerates byte-identically)", proc.returncode == 0,
proc.stdout.strip())
ok("design.css says it is generated", "GENERATED from tokens.json" in CSS)
# THE rule, in CSS: measured and predicted must not share styling.
m = re.search(r"\.ui-measured\s*\{([^}]*)\}", CSS)
p = re.search(r"\.ui-predicted\s*\{([^}]*)\}", CSS)
ok("both .ui-measured and .ui-predicted exist", bool(m) and bool(p))
if m and p:
ok("MEASURED and PREDICTED do not share a declaration block",
m.group(1).strip() != p.group(1).strip())
ok("...they differ by COLOUR", "--measured" in m.group(1) and "--predicted" in p.group(1))
ok("...and by more than colour, so the distinction survives greyscale, "
"a projector and colour-blindness",
"italic" in p.group(1) and "italic" not in m.group(1))
# INSTRUMENT is the bare :root default from 2026-08-19 -- verified by position (its block
# must be the first ":root {" in the file).
first_root = CSS.index(":root {")
# To the END of the block, not a fixed character window -- the token list is ~850 chars and a
# 400-char window silently missed `color-scheme` at the bottom of it.
head = CSS[first_root:CSS.index("}", first_root)]
ok("instrument is declared first, as the bare :root default",
TOKENS["color"]["instrument"]["background"] in head)
ok("...and the bare :root carries the LIGHT palette, so an un-stamped page in a light OS "
"is not left on a dark ground", "color-scheme: light" in head)
# The three-state rule. Unlike every previous theme here, instrument has a real light/dark
# pair, so it must resolve correctly in all three viewer states -- and the un-stamped
# default-system state is the one most viewers are in and the one most often got wrong.
ok("instrument auto-switches to its dark half on prefers-color-scheme: dark",
"@media (prefers-color-scheme: dark)" in CSS
and TOKENS["color"]["instrument-dark"]["background"] in CSS)
media = CSS[CSS.index("@media (prefers-color-scheme: dark)"):]
ok("...guarded with :not([data-theme]) so an explicit stamp always beats the OS preference",
":root:not([data-theme])" in media[:media.index("}")+200])
ok("...and both halves are reachable by explicit stamp, so a toggle wins in either direction",
'[data-theme="instrument"]' in CSS and '[data-theme="instrument-dark"]' in CSS)
ok("light and dark (the pre-2026-08-04 look) remain available as explicit "
"opt-ins in BOTH directions", '[data-theme="light"]' in CSS and '[data-theme="dark"]' in CSS)
ok("polarize remains reachable by name -- the opt-out a project uses to keep its old look",
'[data-theme="polarize"]' in CSS)
ok("reduced motion is honoured", "prefers-reduced-motion" in CSS)
ok("focus is always visible", CSS.count(":focus-visible") >= 4)
# A local, self-hosted font file src is a relative url() with no scheme --
# this still catches an accidental fonts.googleapis.com/CDN reference.
body = CSS.split("*/", 1)[1]
ok("no webfont or CDN reference (self-hosted @font-face uses a local relative "
"url(), never http(s)://)", "@import" not in CSS and "http" not in body)
ok("the self-hosted serif @font-face block is present, and points locally",
"@font-face" in CSS and 'url("fonts/' in CSS)
for cls in (".ui-card", ".ui-btn", ".ui-field", ".ui-table", ".ui-tier",
".ui-marker", ".ui-tooltip", ".ui-drawer", ".ui-tabs", ".ui-rule",
".ui-eyebrow", ".ui-icon", ".ui-waveform", ".ui-transport",
".ui-region-marker", ".ui-spectrogram", ".ui-tag", ".ui-live-dot",
".ui-segmented", ".ui-popover"):
ok(f"design.css defines {cls}", cls in CSS)
def check_js():
for el in ("ui-tier", "ui-note", "ui-docs"):
ok(f"design.js defines <{el}>", f"customElements.define('{el}'" in JS)
ok("the rule is stated at the top of design.js",
"A LABEL may never be hidden" in JS)
# <ui-note> must empty itself and leave only a marker -- that IS the hiding.
ok("<ui-note> replaces its body with a marker",
"this.innerHTML = ''" in JS and "ui-marker" in JS)
# <ui-tier> must never create a marker or a disclosure.
tier_src = JS[JS.index("class UiTier"):JS.index("/* ------------------------------------------------------------------ note -- */")]
ok("<ui-tier> renders inline and cannot be collapsed",
"ui-marker" not in tier_src and "docs()" not in tier_src)
ok("<ui-tier> carries its glyph as well as its label",
"ui-tier__glyph" in tier_src)
ok("<ui-tier> is reachable by keyboard", "tabindex" in tier_src)
ok("the drawer closes on Escape", "'Escape'" in JS)
ok("the drawer does not depend on requestAnimationFrame -- it does not fire "
"in a hidden tab", "requestAnimationFrame(" not in JS)
ok("the drawer opens on ?", "'?'" in JS)
ok("...but not while typing in a field", "INPUT|TEXTAREA|SELECT" in JS)
ok("tooltips work from keyboard focus, not just hover", "focusin" in JS)
ok("a missing tokens.json degrades instead of failing the app",
"degrade, never fail to start" in JS.lower() or "console.warn('design" in JS)
ok("series colours are exposed to charts", "export function seriesColors" in JS)
# tokens.json + the icon sprite -- both same-folder, both degrade on failure.
ok("no network beyond the design folder itself",
JS.count("fetch(") == 2 and "tokens.json" in JS and "polarize-icons.svg" in JS)
ok("a missing icon sprite degrades instead of failing the app",
"icon sprite unavailable" in JS)
ok("the icon sprite is INLINED into the document, not left as a cross-document "
"<use> reference (verified unreliable in-browser -- silent failure, no error)",
"unreliable across browsers" in JS and "innerHTML = svgText" in JS)
def check_type_rule():
"""SANS-SERIF is the default for every theme and every project.
Set 2026-08-13 at the operator's request, repo-wide and forward-looking:
"use Inter or a nice sans-serif, and that goes for all future projects".
Pinned here because the whole point is that a NEW project inherits it with
zero configuration -- a rule nobody checks is a rule that lasts one theme.
"""
t = TOKENS["type"]
# A theme may name its own sans (fieldguide: Geist); it must still be a sans, never the serif.
SANS_FACES = {"sans": "Inter", "geist": "Geist"}
for theme, which in t["primaryByTheme"].items():
ok(f"theme '{theme}' uses a sans primary face", which in SANS_FACES,
f"got {which!r}")
ok("every alternative sans is a sans stack",
all(t[k].strip().startswith(f'"{v}"') and t[k].rstrip().endswith("sans-serif")
for k, v in SANS_FACES.items() if k != "sans"))
ok("an alternative sans ships one weight, so it can never be faux-bolded",
'"Geist";' in (HERE / "design.css").read_text() and "font-weight: 400;" in
(HERE / "design.css").read_text().split('font-family: "Geist";')[1][:200])
ok("the Geist face is self-hosted with its licence",
(HERE / "fonts" / "geist-400.woff2").exists() and (HERE / "fonts" / "GEIST-OFL.txt").exists())
ok("the sans stack names Inter first", t["sans"].strip().startswith("Inter"))
ok("the sans stack falls back to the system stack",
"-apple-system" in t["sans"] and t["sans"].rstrip().endswith("sans-serif"))
ok("mono is still a system stack", "ui-monospace" in t["mono"])
# The serif token stays available -- it is simply no longer anyone's primary.
ok("a serif token still exists for deliberate use", bool(t.get("serif")))
ok("but no theme uses it as primary", "serif" not in t["primaryByTheme"].values())
# And the generated CSS must actually agree with the tokens.
css = (HERE / "design.css").read_text()
for block_ in css.split("--font-primary:")[1:]:
decl = block_.split(";")[0]
ok("every --font-primary in the built CSS is a sans stack",
("Inter" in decl or "Geist" in decl) and "serif" not in decl.replace("sans-serif", ""),
decl.strip()[:60])
# Fonts referenced by @font-face must exist on disk. This was stale: the
# docs and the serve allow-list still named source-serif-4 files that had
# been replaced by Literata, so a consumer copying them served 404s.
import re as _re
for url in _re.findall(r'url\("([^"]+)"\)', css):
ok(f"@font-face file {url} exists", (HERE / url).exists())
# UPPERCASE IS ALWAYS MONO; THE DISPLAY SERIF IS NEVER UPPERCASED (operator, 2026-08-20).
# Found in veil-bypass: `.ui-card > h2` uppercased whatever heading landed in a card, so a
# `.ui-display` heading rendered as uppercase Instrument Serif -- the one combination the
# type system forbids. Every rule that says `text-transform: uppercase` must therefore either
# set the mono face in the same block or inherit it from the same selector's other block.
rules = _re.findall(r'([^{}]+)\{([^{}]*text-transform:\s*uppercase[^{}]*)\}', css)
ok("the built CSS still has uppercase rules to police", len(rules) >= 5, str(len(rules)))
for sel, body in rules:
sel = sel.strip().split("\n")[-1].strip()
ok(f"uppercase rule '{sel[:48]}' sets the mono face",
"var(--font-mono)" in body, "uppercase without mono")
ok(".ui-display explicitly refuses text-transform",
_re.search(r'\.ui-display\s*\{[^}]*text-transform:\s*none', css) is not None)
ok("a plain-h2 card kicker excludes .ui-display",
".ui-card > h2:not(.ui-display)" in css)
ok("the standfirst is body-sized, not enlarged",
_re.search(r'\.ui-standfirst\s*\{[^}]*font-size:\s*var\(--text-base\)', css) is not None)
# THE SANS IS NEVER BOLD AND NEVER TRACKED (operator, 2026-08-20). Weight >= 600 may appear
# only inside @font-face blocks (variable-font ranges); everywhere else the heaviest weight
# in the system is the mono's 500. Browser bold is reset at the source: plain headings and
# <strong> both render 400, with <strong> marked by ink instead of weight.
body_css = _re.sub(r'@font-face\s*\{[^}]*\}', '', css)
ok("no rule outside @font-face uses font-weight 600/700/bold",
not _re.search(r'font-weight:\s*(600|700|bold)', body_css))
ok("plain headings are reset to the regular weight",
_re.search(r'h1, h2, h3, h4, h5, h6\s*\{\s*font-weight:\s*400', css) is not None)
ok("<strong> is regular weight, marked by ink not bold",
_re.search(r'b, strong\s*\{\s*font-weight:\s*400;\s*color:\s*var\(--foreground\)', css) is not None)
# No sans-face rule tracks: every letter-spacing in the built CSS belongs to a block that is
# mono-faced, uppercase (therefore mono, per the rule above), the display serif's optical
# correction, or an explicit reset to 0.
for m in _re.finditer(r'([^{}]+)\{([^{}]*letter-spacing[^{}]*)\}', body_css):
sel, body = m.group(1).strip().split("\n")[-1].strip(), m.group(2)
legit = ("var(--font-mono)" in body or "uppercase" in body
or "letter-spacing: 0" in body or ".ui-display" in sel)
ok(f"letter-spacing in '{sel[:44]}' is mono/serif/reset, never tracked sans", legit)
def check_shadcn() -> None:
"""The shadcn bridge: generated from tokens.json, and refusing the --accent collision.
`salamander-tail` and `global-biocommunication-visualizer` both hold COPIED design values
with the drift risk merely recorded. A third hand-copy is what this prevents.
"""
import subprocess
from pathlib import Path
d = Path(__file__).parent / "shadcn"
if not d.is_dir():
print(" SKIP shadcn bridge not present")
return
r = subprocess.run([sys.executable, str(d / "build_shadcn.py"), "--check"],
capture_output=True, text=True)
ok("shadcn bridge is regenerated from tokens.json (no drift)", r.returncode == 0,
r.stdout.strip() + r.stderr.strip())
theme = (d / "theme.css").read_text()
tokens = json.loads((Path(__file__).parent / "tokens.json").read_text())
brand = tokens["color"]["instrument"]["accent"]
surface2 = tokens["color"]["instrument"]["surface-2"]
# THE collision. shadcn's --accent is a hover surface; ours is the brand teal. If these
# ever become the same value, every hover row in a React project turns saturated teal.
ok("shadcn --primary carries the BRAND colour", f"--primary: {brand};" in theme)
ok("shadcn --accent is the muted surface, NOT the brand colour",
f"--accent: {surface2};" in theme and f"--accent: {brand};" not in theme)
ok("the --accent collision is documented in the generated file",
"MUTED HOVER SURFACE" in theme)
ok("SHADCN.md warns against loading design.css and theme.css together",
"do not load" in (d / "SHADCN.md").read_text().lower())
# The three-channel rule must survive the port to React.
tsx = (d / "tier.tsx").read_text()
ok("Tier renders a glyph AND a label (colour is never load-bearing)",
"t.glyph" in tsx and "t.label" in tsx)
# Search the CODE, not the comment that explains the rule. The first version of this check
# matched tier.tsx's own header ("deliberately no `compact` ... prop") and failed on a file
# that was correct. `tree-signal-reader`, `stimulus-to-signal` and `translation-board` each
# recorded the same defect; weakening the check was the wrong repair in all three.
code = re.sub(r"/\*.*?\*/", "", tsx, flags=re.S)
code = re.sub(r"//.*", "", code)
ok("the prop check reads code, not the comment that describes it",
"deliberately no" in tsx and "deliberately no" not in code)
for prop in ("compact", "iconOnly", "hideLabel"):
ok(f"Tier has no `{prop}` prop — a hidden label is the failure the badge exists to stop",
prop not in code)
ok("Tier's vocabulary is generated, not hand-written",
"GENERATED by tools/design/shadcn/build_shadcn.py" in tsx)
ok("every epistemic tier reached the React component",
all(f'"{t["id"]}"' in tsx for t in tokens["epistemic"]["tiers"]))
# Prepared, not adopted: this must not have quietly been wired into a project.
# Only meaningful when mounted as the monorepo's tools/design submodule.
root = Path(__file__).resolve().parents[2]
if (root / "tools" / "REGISTRY.md").is_file():
wired = [p.name for p in (root / "projects").glob("*/package.json")
if "shadcn" in p.read_text()]
ok("shadcn is prepared but adopted nowhere yet (no project depends on it)",
not wired, str(wired))
else:
print("SKIP shadcn adoption check -- not mounted inside the audio-projects monorepo")
def check_layer(name: str) -> None:
"""A hand-written layer (publication.css, landing.css) is held to the same rules as design.css."""
path = HERE / name
ok(f"{name} exists", path.is_file())
if not path.is_file():
return
css = re.sub(r"/\*.*?\*/", "", path.read_text(), flags=re.S)
ok(f"{name} has no hex or rgb() colour literal",
not re.search(r"#[0-9a-fA-F]{3,8}\b|rgba?\(", css))
ok(f"{name} never bolds",
not re.search(r"font-weight:\s*(600|700|800|900|bold)", css))
blocks = re.findall(r"([^{}]+)\{([^{}]*)\}", css)
upper = [s.strip() for s, b in blocks if "uppercase" in b and "var(--font-mono)" not in b]
ok(f"{name}: every uppercase rule sets the mono face", not upper, str(upper[:3]))
tracked = [s.strip() for s, b in blocks if "letter-spacing" in b
and not any(k in b for k in ("var(--font-mono)", "uppercase", "var(--font-display)"))]
ok(f"{name}: the sans is never tracked", not tracked, str(tracked[:3]))
# A layer may read a variable it defines itself (e.g. docs.css's --docsite-* layout sizes)
# and the two pointer coordinates docs.js writes (--mx/--my); every other name is a token.
own = set(re.findall(r"(--[a-z0-9-]+)\s*:", css))
names = set(re.findall(r"var\((--[a-z0-9-]+)", css)) - {"--pub-accent", "--measure", "--tier-color", "--mx", "--my"} - own
system = (HERE / "shadcn" / "system.css").read_text() + (HERE / "shadcn" / "theme.css").read_text()
for where, text in (("design.css", CSS), ("the React theme", system)):
missing = sorted(n for n in names if f"{n}:" not in text)
ok(f"every token {name} reads is defined by {where}", not missing, str(missing))
ok(f"{name} only ever reads the brand colour through --pub-accent",
"var(--accent)" not in css.replace("var(--pub-accent, var(--accent))", ""))
def check_publication() -> None:
check_layer("publication.css")
def check_landing() -> None:
check_layer("landing.css")
css = (HERE / "landing.css").read_text() if (HERE / "landing.css").is_file() else ""
ok("landing.css honours prefers-reduced-motion", "prefers-reduced-motion" in css)
ok("landing.css imported by the React theme", '@import "../landing.css";' in (HERE / "src" / "theme.css").read_text())
def check_docs() -> None:
"""docs.css + docs.js: the documentation-site layer (DOCS-SITES.md)."""
check_layer("docs.css")
css = (HERE / "docs.css").read_text() if (HERE / "docs.css").is_file() else ""
ok("docs.css honours prefers-reduced-motion", "prefers-reduced-motion" in css)
ok("docs.css imported by the React theme", '@import "../docs.css";' in (HERE / "src" / "theme.css").read_text())
ok("docs.css code window reads only code/syntax tokens",
all(v in CSS for v in ("--code-background:", "--code-foreground:", "--syntax-keyword:")))
path = HERE / "docs.js"
ok("docs.js exists", path.is_file())
if not path.is_file():
return
js = path.read_text()
ok("docs.js exports renderPlot, highlight and init", all(f"export function {n}" in js for n in ("renderPlot", "highlight", "init")))
ok("docs.js has a type declaration", (HERE / "docs.d.ts").is_file())
ok("docs.js fetches only the search index the page names",
js.count("fetch(") == 1 and "fetch(box.dataset.uiSearch)" in js)
ok("docs.js never uses requestAnimationFrame or setInterval", "requestAnimationFrame" not in js and "setInterval" not in js)
ok("docs.js wraps every storage access in try",
all("try {" in line for line in js.splitlines() if "localStorage." in line))
ok("docs.js escapes what it writes into HTML", "const esc" in js and "innerHTML = highlight" in js)
ok("a verdict is always written as a word, not only a colour", "ui-verdicts__word" in js and "esc(i.verdict)" in js)
def lum(h: str) -> float:
c = [int(h.lstrip("#")[i:i + 2], 16) / 255 for i in (0, 2, 4)]
c = [x / 12.92 if x <= 0.03928 else ((x + 0.055) / 1.055) ** 2.4 for x in c]
return 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]
def ratio(a: str, b: str) -> float:
la, lb = sorted((lum(a), lum(b)), reverse=True)
return (la + 0.05) / (lb + 0.05)
code = TOKENS.get("code", {})
inks = {"foreground": code.get("foreground"), "muted": code.get("muted"), **code.get("syntax", {})}
low = {f"{k} on {s}": round(ratio(v, code[s]), 2) for k, v in inks.items() if v
for s in ("background", "bar") if ratio(v, code[s]) < 4.5}
ok("every code-window ink clears 4.5:1 on the panel and its bar (measured here)", bool(code) and not low, str(low))
def check_filter() -> None:
"""filter.js + the FILTERS section of publication.css: a filter panel for an index."""
path = HERE / "filter.js"
ok("filter.js exists", path.is_file())
if not path.is_file():
return
js = path.read_text()
code = re.sub(r"/\*.*?\*/|//[^\n]*", "", js, flags=re.S)
pub = (HERE / "publication.css").read_text()
ok("filter.js has a type declaration", (HERE / "filter.d.ts").is_file())
ok("filter.js exports its pure logic and the enhancer",
all(re.search(rf"export (function|const) {n}\b", js) for n in
("emptyState", "matches", "visible", "facetCount", "isFiltered", "readQuery", "toQuery", "initFilter", "init")))
ok("filter.js fetches nothing and stores nothing",
not re.search(r"\bfetch\(|localStorage|sessionStorage|XMLHttpRequest", code))
ok("filter.js never uses requestAnimationFrame or setInterval",
"requestAnimationFrame" not in code and "setInterval" not in code)
ok("filter.js carries state in aria-pressed, not a class",
code.count("setAttribute('aria-pressed'") >= 5 and "is-active" not in code and "is-selected" not in code)
ok("filter.js writes text with textContent, never interpolating page text into innerHTML",
"innerHTML = `<span></span>${X}`" in code and code.count("innerHTML") == 1)
ok("filter.js names every removable chip for a screen reader", "Remove filter: " in code)
ok("filter.js is shipped and exported by the package",
'"filter.js"' in (HERE / "package.json").read_text() and '"./filter.js": "./filter.js"' in (HERE / "package.json").read_text())
react = (HERE / "src" / "components" / "filter.tsx").read_text()
ok("the React filter uses filter.js's logic rather than a second copy",
'from "../../filter.js"' in react and "facetCount(" in react and "function matches" not in react)
ok("every React filter control is a button with aria-pressed",
react.count("aria-pressed=") >= 5 and 'type="checkbox"' not in react)
for cls in (".ui-filter", ".ui-facet", ".ui-tier--toggle", ".ui-check", ".ui-histo", ".ui-seg", ".ui-chip",
".ui-results__head", ".ui-results__empty", ".ui-shell--filter", ".ui-shell--single"):
ok(f"publication.css defines {cls}", re.search(re.escape(cls) + r"[\s,.:\[{]", pub) is not None)
block = pub[pub.index("FILTERS"):]
ok("a tier toggle names no tier colour (it inherits its family's)",
not re.search(r"--(measured|predicted|exploring|spec|refuted|tier-)", block))
ok("every filter control shows a focus ring",
all(f"{c}:focus-visible" in block for c in (".ui-facet__btn", ".ui-tier--toggle", ".ui-check", ".ui-histo__btn", ".ui-seg__btn", ".ui-chip")))
ok("the stacked filter layout puts the controls above the results",
re.search(r'\.ui-shell--filter\s*\{\s*grid-template-areas:\s*"brand"\s*"side"\s*"main"', pub) is not None)
def check_trajectory3d() -> None:
"""trajectory3d.js: a data view on a canvas, so it takes its colour from tokens and fetches nothing."""
path = HERE / "trajectory3d.js"
ok("trajectory3d.js exists", path.is_file())
if not path.is_file():
return
js = path.read_text()
code = re.sub(r"/\*.*?\*/|//[^\n]*", "", js, flags=re.S)
ok("trajectory3d.js exports mountTrajectory3D", "export function mountTrajectory3D(" in code)
for method in ("update", "setTime", "show", "resetView", "destroy"):
ok(f"trajectory3d.js handle has {method}()", re.search(rf"^ {method}\(", code, re.M) is not None)
ok("trajectory3d.js imports and fetches nothing", "fetch(" not in code and not re.search(r"^\s*import\b", code, re.M))
for token in ("--foreground", "--muted-foreground", "--series-1", "--series-4", "--font-mono"):
ok(f"trajectory3d.js reads {token}, which design.css defines", f"'{token}'" in code and f"{token}:" in CSS)
ok("trajectory3d.js names no tier colour (a series colour never impersonates a tier)",
not re.search(r"--(measured|predicted|exploring|spec|refuted|tier-)", code))
ok("trajectory3d.js has an accessible name and takes the keyboard", "aria-label" in code and "keydown" in code)
ok("trajectory3d.js leaves a plain scroll to the page", "if (!e.ctrlKey && !e.metaKey) return" in code)
ok("trajectory3d.js redraws on a theme change and cleans up after itself",
"MutationObserver" in code and "mo.disconnect()" in code and "ro.disconnect()" in code)
ok("trajectory3d.js has a type declaration", (HERE / "trajectory3d.d.ts").is_file())
pkg = json.loads((HERE / "package.json").read_text())
ok("package.json ships and exports trajectory3d.js",
{"trajectory3d.js", "trajectory3d.d.ts"} <= set(pkg["files"]) and pkg["exports"].get("./trajectory3d.js") == "./trajectory3d.js")
ok("INTEGRATION.md documents trajectory3d.js", "trajectory3d.js" in (HERE / "INTEGRATION.md").read_text())
def check_network3d() -> None:
"""network3d.js: a token-driven, dependency-free spatial node-link view."""
path = HERE / "network3d.js"
ok("network3d.js exists", path.is_file())
if not path.is_file():
return
js = path.read_text()
code = re.sub(r"/\*.*?\*/|//[^\n]*", "", js, flags=re.S)
ok("network3d.js exports mountNetwork3D", "export function mountNetwork3D(" in code)
for method in ("update", "resetView", "destroy"):
ok(f"network3d.js handle has {method}()", re.search(rf"^ {method}\(", code, re.M) is not None)
ok("network3d.js imports and fetches nothing", "fetch(" not in code and not re.search(r"^\s*import\b", code, re.M))
for token in ("--muted-foreground", "--series-", "--font-mono"):
ok(f"network3d.js reads {token}", f"'{token}" in code or f"`{token}" in code)
ok("network3d.js names no tier colour", not re.search(r"--(measured|predicted|exploring|spec|refuted|tier-)", code))
ok("network3d.js has an accessible name and keyboard controls", "aria-label" in code and "keydown" in code)
ok("network3d.js leaves plain scrolling to the page by default", "wheelZoom: false" in code)
ok("network3d.js redraws on theme changes and cleans up", "MutationObserver" in code and "mo.disconnect()" in code and "ro.disconnect()" in code)
ok("network3d.js has a type declaration", (HERE / "network3d.d.ts").is_file())
pkg = json.loads((HERE / "package.json").read_text())
ok("package.json ships and exports network3d.js",
{"network3d.js", "network3d.d.ts"} <= set(pkg["files"]) and pkg["exports"].get("./network3d.js") == "./network3d.js")
ok("INTEGRATION.md documents network3d.js", "network3d.js" in (HERE / "INTEGRATION.md").read_text())
def check_bandprominence() -> None:
"""bandprominence.js: a live data view, so it takes colour from tokens, fetches nothing, and labels its limits."""
path = HERE / "bandprominence.js"
ok("bandprominence.js exists", path.is_file())
if not path.is_file():
return
js = path.read_text()
code = re.sub(r"/\*.*?\*/|//[^\n]*", "", js, flags=re.S)
for name in ("mountBandProminence", "createBandProminence"):
ok(f"bandprominence.js exports {name}", f"export function {name}(" in code)
for method in ("push", "listenTo", "stopListening", "state", "update", "reset", "destroy"):
ok(f"bandprominence.js handle has {method}()", re.search(rf"^ {method}\(", code, re.M) is not None)
ok("bandprominence.js imports and fetches nothing", "fetch(" not in code and not re.search(r"^\s*import\b", code, re.M))
for token in ("--foreground", "--muted-foreground", "--font-mono"):
ok(f"bandprominence.js reads {token}, which design.css defines", f"'{token}'" in code and f"{token}:" in CSS)
ok("bandprominence.js colours bands from --series-1..5, which design.css defines",
"`--series-${i + 1}`" in code and all(f"--series-{k}:" in CSS for k in range(1, 6)))
ok("bandprominence.js names no tier colour", not re.search(r"--(measured|predicted|exploring|spec|refuted|tier-)", code))
ok("bandprominence.js marks a band above Nyquist instead of drawing it as zero", "above Nyquist" in code and "0.45 * rate" in code)
ok("bandprominence.js follows <signal-panel>'s event", "'signal-samples'" in code and "e.detail.values" in code)
ok("bandprominence.js dims a stale readout rather than hiding it", "STALE_S" in code and "opacity" in code)
ok("bandprominence.js draws on a timer, not requestAnimationFrame", "setInterval(" in code and "requestAnimationFrame" not in code)
ok("bandprominence.js has a type declaration", (HERE / "bandprominence.d.ts").is_file())
ok("the React BandProminence wraps bandprominence.js rather than copying it",
'from "../../../bandprominence.js"' in (HERE / "src/science/signals/BandProminence.tsx").read_text())
def check_controls() -> None:
"""controls.css + controls.js: hardware-style controls. The inks keep their one job each,
a hard limit is drawn rather than applied silently, and no tier colour is borrowed."""
check_layer("controls.css")
css = (HERE / "controls.css").read_text() if (HERE / "controls.css").is_file() else ""
body = re.sub(r"/\*.*?\*/", "", css, flags=re.S)
ok("controls.css honours prefers-reduced-motion", "prefers-reduced-motion" in css)
ok("controls.css imported by the React theme", '@import "../controls.css";' in (HERE / "src" / "theme.css").read_text())
ok("controls.css names no tier colour (the epistemic palette is reserved; a limit is an end-stop)",
not re.search(r"--(measured|predicted|exploring|spec|refuted|tier-)", body))
for ink in ("--clay", "--ochre", "--lichen-text"):
ok(f"controls.css reads {ink} with a fallback for themes that have no audio inks",
re.search(r"var\(" + ink + r",\s*var\(", body) is not None)
for cls in (".ui-control", ".ui-fader", ".ui-fader--ribbon", ".ui-fader--vertical", ".ui-fader__stop", ".ui-fader__mark",
".ui-knob", ".ui-tag--linked", ".ui-delta", ".ui-sync", ".ui-glide", ".ui-meter", ".ui-strip",
".ui-hazard", ".ui-hold", ".ui-timeline", ".ui-lane", ".ui-panner", ".ui-sheet", ".ui-tabbar", ".ui-night",
".ui-gauge", ".ui-keyboard", ".ui-keylane"):
ok(f"controls.css defines {cls}", re.search(re.escape(cls) + r"[\s,.:\[{>]", body) is not None)
ok("every sync state carries a glyph as well as its word",
all(re.search(r'\.ui-sync\[data-state="' + st + r'"\]::before\s*\{\s*content:', body) for st in ("saved", "saving", "offline", "conflict")))
ok("the end-stops are always drawn in the foreground ink",
re.search(r"\.ui-fader__stop\s*\{[^}]*background:\s*var\(--foreground\)", body) is not None)
ok("the control label clears 4.5:1 (muted, not faint)",
re.search(r"\.ui-control__name\s*\{[^}]*color:\s*var\(--muted-foreground\)", body) is not None)
path = HERE / "controls.js"
ok("controls.js exists", path.is_file())
if not path.is_file():
return
js = path.read_text()
code = re.sub(r"/\*.*?\*/|//[^\n]*", "", js, flags=re.S)
for name in ("toFrac", "fromFrac", "quantize", "snap", "fineGain", "formatValue", "parseEntry", "layoutScenes", "valueAt",
"pathPoint", "pathSamples", "initControl", "initHold", "mountTimeline", "mountLane", "mountPanner",
"isBlack", "noteName", "keyLayout", "spanLayout", "mountKeyboard", "mountKeyLane", "init"):
ok(f"controls.js exports {name}", re.search(rf"export (function|const) {name}\b", code) is not None)
ok("controls.js imports, fetches and stores nothing",
not re.search(r"^\s*import\b", code, re.M) and not re.search(r"\bfetch\(|localStorage|sessionStorage|XMLHttpRequest", code))
ok("controls.js never uses requestAnimationFrame or setInterval (the caller moves time)",
"requestAnimationFrame" not in code and "setInterval" not in code)
ok("controls.js writes page text with textContent, never innerHTML", "innerHTML" not in code)
ok("a disabled key names its reason", "unavailable:" in code)
ok("controls.js announces every detent with a bubbling ui-detent event",
"new CustomEvent('ui-detent', { bubbles: true" in code)
ok("controls.js keeps the native range input as the source of truth", "input[type=\"range\"]" in code and "aria-valuetext" in code)
ok("controls.js marks a control sitting on a hard limit", "data-at-limit" in code)
ok("controls.js names every timeline ending in words", all(w in code for w in ("met:", "timeout:", "no_data:", "open_loop:")))
ok("controls.js names no tier colour", not re.search(r"--(measured|predicted|exploring|spec|refuted|tier-)", code))
ok("controls.js has a type declaration", (HERE / "controls.d.ts").is_file())
pkg = json.loads((HERE / "package.json").read_text())
ok("package.json ships and exports controls.css and controls.js",
{"controls.css", "controls.js", "controls.d.ts"} <= set(pkg["files"])
and pkg["exports"].get("./controls.js") == "./controls.js" and pkg["exports"].get("./controls.css") == "./controls.css")
ok("INTEGRATION.md documents controls.js and its ui-detent event",
all(w in (HERE / "INTEGRATION.md").read_text() for w in ("controls.js", "ui-detent")))
react = (HERE / "src" / "components" / "controls.tsx")
ok("the React controls wrap controls.js rather than copying it",
react.is_file() and 'from "../../controls.js"' in react.read_text() and "function snap" not in react.read_text())
# The React Polarize theme: clay is the brand colour, and it is legible on the ground.
theme = (HERE / "shadcn" / "theme.css").read_text()
pol = TOKENS["color"]["polarize"]
blk = theme[theme.find(':root[data-theme="polarize"]'):]
blk = blk[:blk.find("}")]
ok("the React theme has a Polarize block", bool(blk))
ok("...whose --primary is clay and --accent the hover surface",
f"--primary: {pol['accent']};" in blk and f"--accent: {pol['surface-2']};" in blk)
ok("...with the ground as the text on clay, at AA", f"--primary-foreground: {pol['background']};" in blk
and contrast(pol["accent"], pol["background"]) >= 4.5, f"{contrast(pol['accent'], pol['background']):.2f}:1")
system = (HERE / "shadcn" / "system.css").read_text()
ok("the React system layer defines Polarize's three audio inks",
':root[data-theme="polarize"]' in system and all(f"--{k}:" in system for k in ("clay", "ochre", "lichen", "lichen-text")))
def check_react_mirror() -> None:
"""src/theme.css re-declares a few design.css classes for React documents; they must match."""
path = HERE / "src" / "theme.css"
if not path.is_file():
return
react = path.read_text()
def decls(css: str, cls: str) -> set[str]:
m = re.search(r"(?m)^\s*\." + re.escape(cls) + r"\s*\{([^}]*)\}", css)
return {d.strip() for d in m.group(1).replace("\n", " ").split(";") if d.strip()} if m else set()
# .ui-icon is deliberately NOT mirrored: design.css fills a sprite icon, and lucide
# icons are strokes, so `fill: currentColor` would paint them solid.
for cls in ("ui-label", "ui-standfirst", "ui-pill"):
a, b = decls(CSS, cls), decls(react, cls)
ok(f"React's .{cls} matches design.css", a == b and bool(a), f"design.css-only {sorted(a - b)}, react-only {sorted(b - a)}")
def check_package_imports() -> None:
"""src/ ships as source to other apps. An `@/` import there resolves against the
CONSUMER's alias, so it would silently pick up the host's own components."""
bad = [str(f.relative_to(HERE)) for f in (HERE / "src").rglob("*.ts*")
if re.search(r'from\s+"@/', f.read_text())]
ok("src/ uses relative imports only (no `@/` — it would resolve inside the consumer)", not bad, str(bad))
def check_datasets() -> None:
"""Demo data in a PUBLIC library, served from outside it. Every dataset folder names its
source, a licence that allows redistribution, and a content-addressed public URL with the
sha256 of what lives there; the reduction script ships beside it; the data itself does NOT
live in this repository. `--network` also downloads each file and checks its hash.
A recording of a person on a private bench has no licence here and cannot get past this."""
import hashlib
allowed = {"CC0", "CC-BY-4.0", "ODC-By-1.0", "public-domain-usgs", "public-domain", "OGL-Canada"}
base = "https://polarizetech-research-datasets.sfo3.digitaloceanspaces.com/derived/polarize-ui/"
root = HERE / "stories" / "datasets"
dirs = sorted(d for d in root.iterdir() if d.is_dir()) if root.is_dir() else []
decl = (root / "datasets.d.ts").read_text() if (root / "datasets.d.ts").exists() else ""
stories = "".join(p.read_text() for p in (HERE / "stories").rglob("*.stories.tsx"))
for d in dirs:
src = d / "SOURCE.json"
if not src.exists():
ok(f"dataset {d.name} has a SOURCE.json", False)
continue
meta = json.loads(src.read_text())
sha = meta.get("data_sha256", "")
ok(f"dataset {d.name}: licence allows redistribution", meta.get("licence") in allowed, meta.get("licence", "none"))
ok(f"dataset {d.name}: attribution and accession recorded", bool(meta.get("attribution")) and bool(meta.get("accession")))
ok(f"dataset {d.name}: a full sha256 is recorded", bool(re.fullmatch(r"[0-9a-f]{64}", sha)))
ok(f"dataset {d.name}: served from its content-addressed public URL",
meta.get("url") == f"{base}{d.name}/{sha[:16]}/data.json", meta.get("url", ""))
ok(f"dataset {d.name}: the data is NOT kept in this repository", not (d / "data.json").exists())
ok(f"dataset {d.name}: the reduction script ships with it", (d / "reduce.py").exists())
ok(f"dataset {d.name}: datasets.d.ts describes it", f'"virtual:dataset/{d.name}"' in decl)
ok(f"dataset {d.name}: every story loading it renders its attribution",
f"virtual:dataset/{d.name}\"" not in stories or f"datasets/{d.name}/SOURCE.json" in stories)
if "--network" in sys.argv:
import urllib.request
try:
body = urllib.request.urlopen(meta["url"], timeout=60).read()
ok(f"dataset {d.name}: the published file matches its sha256", hashlib.sha256(body).hexdigest() == sha)
except Exception as e:
ok(f"dataset {d.name}: the published file is readable anonymously", False, str(e))
ok("no story imports a data.json from this repository", not re.search(r'datasets/[^"]+/data\.json"', stories))
def check_diverging() -> None:
"""The diverging ramp is derived and checked by scripts/diverging.py, never hand-edited:
the two arms must match in lightness, stay apart for colour-blind readers, and meet at a
neutral zero that recedes toward the surface on both themes."""
sys.path.insert(0, str(HERE / "scripts"))
import diverging as D
div = TOKENS.get("diverging", {})
ok("diverging: tokens.json carries a diverging ramp", "steps" in div)
if "steps" not in div:
return
ok("diverging: its blue arm is the sequential ramp (no second copy that can drift)",
D.SEQ == TOKENS["sequential"]["steps"])
for mode in ("light", "dark"):
stops, worst, fails = D.check(mode)
ok(f"diverging {mode}: every derivation check passes", not fails, "; ".join(fails))
ok(f"diverging {mode}: tokens.json matches what the script derives", div["steps"][mode] == stops)
ok(f"diverging {mode}: 13 stops with zero in the middle", len(stops) == 13 and stops[6] == D.MID[mode])
for i in range(1, 14):
ok(f"diverging: design.css defines --div-{i}", f"--div-{i}:" in CSS)
heat = (HERE / "src" / "science" / "signals" / "Heatmap.tsx").read_text()
ok("diverging: Heatmap refuses a colour range that is not symmetric about zero",
"must be symmetric about zero" in heat)
def main() -> int:
check_tokens()
check_contrast()
check_epistemic()
check_type_rule()
check_css()
check_js()
check_shadcn()
check_publication()
check_landing()
check_trajectory3d()
check_network3d()
check_bandprominence()
check_filter()
check_controls()
check_docs()
check_react_mirror()
check_package_imports()
check_datasets()
check_diverging()
for name, detail in FAIL:
print(f"FAIL {name}" + (f" [{detail}]" if detail else ""))
print(f"\n{len(PASS)}/{len(PASS) + len(FAIL)} checks passed")
return 1 if FAIL else 0
if __name__ == "__main__":
raise SystemExit(main())