In this section
- Vaccines render · cosmic / tools/explore/verify/vaccines.py lines 701–1400
Vaccines
A Python command-line tool in the verify folder of Cosmic that fetches build graph, metrics, board and games, using SHA-256.
rendercosmic / tools/explore/verify/vaccines.py · lines 701–1400 of 1956 (continued from section 1168) · Entry point · pattern handle_startendtag (shared by 2 files)
- What it does
- It fetches build graph, metrics, board and games. Defines 85 functions or classes, including now, overlay_digest_ok, sha256_file, _leaks, Summary. Uses libraries argparse, collections, colorsys, hashlib, html. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes; uses storage (browser storage, DuckDB or Parquet).
- Inputs & outputs
- In: JSON file build_graph.json; JSON file keys.json; JSON file .metrics.json; JSON file board.json; JSON file games.json; JSON file identity.json; JSON file cache.json; JSON file findings.json. Out: JSON file findings.json.
- Downstream impact
- Used directly by 2 files: Review (cosmic); Test Vaccines (cosmic).
- What it achieves
- It checks build graph (`check_build_graph`), checks board (`check_board`) and checks games (`check_games`). The independent verifier for Explore Code outputs, CVAA-style. It accepts `--minutes`, `--every` and `--report`.
- Why it matters
- Imported by Review. Checked by Test Vaccines.
- Application
- cosmic · tools/explore/verify · Python CLI
- Uses
- argparse, collections, colorsys, hashlib, html, html.parser, io, json
- Used by
- imported by Review (import), imported by Test Vaccines (import)
- Produces
- now, overlay_digest_ok, sha256_file, Summary, summarise, Output, vaccine, has_key, candidate_ok, v_first_law, v_religion, v_private
- Defines here
- v_links, _type, check_build_graph, b, _board_squares, check_board, check_games, check_overlay, check_metrics, contract_keys_for, _top_keys, _all_keys, v_contracts, _dir_digest, _cmp_digest, _tools_hash, v_determinism, v_a11y, parse_colour, blend, luminance, ch, contrast, css_rules, hexs, v_contrast
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/verify/vaccines.py:701-1400 · blob 2e40e2a09c2fc5d90fdee1e73de884d95e6b3dea · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, process, storage · domain stage: unknown · users: none · canonical: unknown
'Links are computed by the build; a computed link that does not resolve is a build defect.')
def v_links(o):
out = []
n = 0
for rel in o.html_files:
s = o.summary(rel)
for tag, attr, val, relv, line in s.refs:
if attr not in ('href', 'src') or (tag == 'link' and 'canonical' in relv):
continue
target, frag = _resolve_local(o, rel, val)
if target is None:
continue
n += 1
if not os.path.exists(target):
out.append('%s:%d <%s %s="%s"> -> missing file' % (rel, line, tag, attr, val[:120]))
continue
if frag and frag != 'top' and target.endswith(('.html', '.htm')):
ids = s.ids if os.path.abspath(target) == os.path.abspath(o.p(rel)) else o.summary_abs(target).ids
if frag not in ids:
out.append('%s:%d <%s %s="%s"> -> no id "%s" in target' % (rel, line, tag, attr, val[:120], frag))
o.notes['V5'].append('%d internal references checked' % n)
return out
# ---- V6 contracts
HEX40 = re.compile(r'^[0-9a-f]{40}$')
SQUARE = re.compile(r'^[a-h][1-8]$')
ROLES = {'geodesy', 'electrical', 'energy-data', 'ingest', 'transform', 'render', 'interaction', 'storage', 'test',
'automation', 'docs-config', 'other'}
EDGE_KINDS = {'import', 'python-relative', 'sys-path', 'require', 'dynamic-import', 'url-import-meta', 'worker',
'script-src', 'stylesheet', 'modulepreload', 'import-map', 'iframe', 'link', 'fetch', 'estate-url',
'comment-url', 'script-call', 'workflow-run'}
def _type(v, t):
return isinstance(v, t) and not (t in (int, (int, float)) and isinstance(v, bool))
def check_build_graph(g, rel, out, o=None):
need = {'schema': str, 'cut': str, 'base': str, 'topics': list, 'repos': list, 'sections': list, 'files': list}
for k, t in need.items():
if not _type(g.get(k), t):
out.append('%s: top-level "%s" missing or not %s' % (rel, k, t.__name__))
if g.get('schema') != 'explore-build-graph-v1':
out.append('%s: schema %r != explore-build-graph-v1' % (rel, g.get('schema')))
files = g.get('files') or []
n = len(files)
for r in g.get('repos') or []:
if not HEX40.match(str(r.get('commit', ''))):
out.append('%s: repos[%s].commit is not 40 hex' % (rel, r.get('repo')))
if len(r.get('readme_summary') or '') > 400:
out.append('%s: repos[%s].readme_summary > 400 chars' % (rel, r.get('repo')))
for k, t in (('repo', str), ('license', str), ('citation', bool)):
if not _type(r.get(k), t):
out.append('%s: repos[%s].%s missing or not %s' % (rel, r.get('repo'), k, t.__name__))
secs = {s.get('section') for s in g.get('sections') or []}
for s in g.get('sections') or []:
for k, t in (('section', int), ('url', str), ('topic', str), ('repos', list), ('lines', int), ('title', str)):
if not _type(s.get(k), t):
out.append('%s: sections[%s].%s missing or not %s' % (rel, s.get('section'), k, t.__name__))
req = {'id': int, 'repo': str, 'path': str, 'folder_hierarchy': list, 'lang': str, 'lines': int, 'section': int,
'block': int, 'title': str, 'achieves': str, 'why': str, 'context': str, 'essay_status': str, 'stage': str,
'imports': list, 'imports_external': list, 'dependents': list, 'defines': list, 'pure': bool,
'role': str, 'pattern': str, 'entry': bool, 'reachable': bool, 'canonical_status': str,
'domain_stage': str, 'commercial_user': list, 'data_contracts': dict, 'four_part': dict, 'signatures': list}
enums = {'essay_status': {'human', 'readme_derived', 'auto'}, 'stage': {'ingest', 'transform', 'output', 'unknown'},
'role': ROLES, 'canonical_status': {'production_core', 'supporting_data', 'duplicate_candidate',
'unreached_review', 'unknown'},
'domain_stage': {'upstream_foresight', 'site_feasibility', 'sub33kv_design', 'hv_procurement',
'field_execution', 'agent_infra', 'experimental', 'unknown'}}
users = {'IPP_developer', 'EPC_contractor', 'ICP_grid_engineer', 'landowner_planner', 'procurement_buyer', 'ai_agent'}
bad = collections.Counter()
ex = {}
for i, f in enumerate(files):
def b(msg):
bad[msg] += 1
ex.setdefault(msg, i)
if f.get('id') != i:
b('files[i].id != i')
for k, t in req.items():
if k not in f:
b('file missing field "%s"' % k)
elif not _type(f[k], t):
b('file field "%s" not %s' % (k, t.__name__))
for k, vals in enums.items():
if k in f and f[k] not in vals:
b('file field "%s" value %r outside the contract' % (k, f[k]))
for k in ('imports', 'dependents', 'mentions', 'mentioned_by'):
for j in f.get(k) or []:
if not (_type(j, int) and 0 <= j < n):
b('file "%s" holds an id outside 0..n-1' % k)
break
if 'edge_kinds' in f and len(f['edge_kinds']) != len(f.get('imports') or []):
b('edge_kinds not parallel to imports')
if len(f.get('defines') or []) > 30:
b('defines longer than 30')
if len(f.get('signatures') or []) > 40:
b('signatures longer than 40')
if set(f.get('commercial_user') or []) - users:
b('commercial_user outside the contract')
if set((f.get('four_part') or {}).keys()) - {'does', 'why', 'io', 'impact'}:
b('four_part has keys outside does/why/io/impact')
if f.get('duplicate_of') is not None and not (_type(f['duplicate_of'], int) and 0 <= f['duplicate_of'] < n):
b('duplicate_of not a file id')
if f.get('section') not in secs:
b('section not in sections')
if f.get('canonical_status') == 'duplicate_candidate' and f.get('duplicate_of') is None:
b('duplicate_candidate without duplicate_of')
for msg, c in sorted(bad.items()):
out.append('%s: %s (%d files, first id %d)' % (rel, msg, c, ex[msg]))
for k, e in enumerate(g.get('edges') or []):
if not (isinstance(e, list) and len(e) == 4 and _type(e[0], int) and _type(e[1], int)
and 0 <= e[0] < n and 0 <= e[1] < n and e[2] in EDGE_KINDS and isinstance(e[3], str)):
out.append('%s: edges[%d] malformed: %s' % (rel, k, json.dumps(e)[:100]))
break
for r in g.get('roles') or []:
if r.get('id') not in ROLES or not re.match(r'^#[0-9a-fA-F]{6}$', str(r.get('colour', ''))):
out.append('%s: roles entry malformed: %s' % (rel, r))
if 'roles' not in g:
out.append('%s: top-level "roles" missing (v1 additions)' % rel)
for j in g.get('journeys') or []:
for k in ('id', 'title', 'url', 'steps', 'links'):
if k not in j:
out.append('%s: journey %s missing "%s"' % (rel, j.get('id'), k))
def _board_squares():
order = ['rook', 'knight', 'bishop', 'queen', 'king', 'bishop', 'knight', 'rook']
sq = {}
for i, f in enumerate('abcdefgh'):
sq[f + '1'] = ('white', order[i])
sq[f + '2'] = ('white', 'pawn')
sq[f + '7'] = ('black', 'pawn')
sq[f + '8'] = ('black', order[i])
return sq
def check_board(d, rel, out):
for k, t in (('schema', str), ('cut', str), ('rules_version', str), ('sides', dict), ('pieces', list)):
if not _type(d.get(k), t):
out.append('%s: "%s" missing or not %s' % (rel, k, t.__name__))
start = _board_squares()
seen_id, seen_sq = set(), set()
pieces = d.get('pieces') or []
if len(pieces) > 32:
out.append('%s: %d pieces (> 32)' % (rel, len(pieces)))
req = {'id': str, 'side': str, 'type': str, 'square': str, 'community': int, 'label': str, 'size': int,
'lines': int, 'repos': list, 'role': str, 'centrality': (int, float), 'reach': (int, float),
'unique': (int, float), 'files': list, 'why': str}
for p in pieces:
pid = p.get('id')
for k, t in req.items():
if not _type(p.get(k), t):
out.append('%s: piece %s field "%s" missing or wrong type' % (rel, pid, k))
if pid in seen_id:
out.append('%s: duplicate piece id %s' % (rel, pid))
seen_id.add(pid)
sq = p.get('square')
if sq in seen_sq:
out.append('%s: two pieces on %s' % (rel, sq))
seen_sq.add(sq)
if not SQUARE.match(str(sq)) or start.get(sq) != (p.get('side'), p.get('type')):
out.append('%s: piece %s (%s %s) not on a standard starting square (%s)' % (rel, pid, p.get('side'), p.get('type'), sq))
for k in ('centrality', 'reach', 'unique'):
v = p.get(k)
if _type(v, (int, float)) and not 0 <= v <= 1:
out.append('%s: piece %s %s=%s outside 0..1' % (rel, pid, k, v))
if len(p.get('files') or []) > 200:
out.append('%s: piece %s lists > 200 files' % (rel, pid))
if d.get('rules_version') and d.get('rules_version') != 'chess-rules-v1':
out.append('%s: rules_version %r (contract says chess-rules-v1)' % (rel, d.get('rules_version')))
def check_games(d, rel, out, board=None):
for k in ('schema', 'players', 'games', 'table'):
if k not in d:
out.append('%s: "%s" missing' % (rel, k))
players = {p.get('id'): p for p in d.get('players') or []}
sides = collections.Counter(p.get('side') for p in players.values())
if sides.get('white') != 5 or sides.get('black') != 5:
out.append('%s: players are %s (contract: 5 white, 5 black)' % (rel, dict(sides)))
pieces = {p['id']: p for p in (board or {}).get('pieces') or [] if 'id' in p}
try:
if PYLIB not in sys.path:
sys.path.append(PYLIB)
import chess
except ImportError:
chess = None
out.append('%s: python-chess unavailable; legality not replayed (INCONCLUSIVE)' % rel)
for gi, g in enumerate(d.get('games') or []):
tag = '%s: games[%d] (%s v %s seed %s)' % (rel, gi, g.get('white'), g.get('black'), g.get('seed'))
if players.get(g.get('white'), {}).get('side') != 'white' or players.get(g.get('black'), {}).get('side') != 'black':
out.append('%s players not on their sides' % tag)
if g.get('result') not in ('1-0', '0-1', '1/2-1/2'):
out.append('%s result %r' % (tag, g.get('result')))
moves = g.get('moves') or []
if [m.get('ply') for m in moves] != list(range(1, len(moves) + 1)):
out.append('%s ply numbers not 1..%d' % (tag, len(moves)))
if chess is None:
continue
bd = chess.Board()
loc = {sq: pid for pid, p in pieces.items() for sq in [p.get('square')]}
ok = True
for m in moves:
fr, to = m.get('from'), m.get('to')
if not (SQUARE.match(str(fr)) and SQUARE.match(str(to))):
out.append('%s ply %s bad squares %s-%s' % (tag, m.get('ply'), fr, to))
ok = False
break
cand = [mv for mv in bd.legal_moves if chess.square_name(mv.from_square) == fr and chess.square_name(mv.to_square) == to]
promo = m.get('promotion')
if len(cand) > 1:
want = {'q': chess.QUEEN, 'r': chess.ROOK, 'b': chess.BISHOP, 'n': chess.KNIGHT}.get(str(promo or 'q')[:1].lower(), chess.QUEEN)
cand = [mv for mv in cand if mv.promotion == want] or cand[:1]
if not cand:
out.append('%s ply %s %s %s-%s is illegal' % (tag, m.get('ply'), m.get('piece'), fr, to))
ok = False
break
mv = cand[0]
if pieces:
if loc.get(fr) != m.get('piece'):
out.append('%s ply %s piece %s but %s is on %s' % (tag, m.get('ply'), m.get('piece'), loc.get(fr), fr))
ok = False
break
cap = bd.is_capture(mv)
if bool(m.get('capture')) != cap:
out.append('%s ply %s capture flag %r but capture=%s' % (tag, m.get('ply'), m.get('capture'), cap))
if pieces and m.get('capture') and cap:
cs = to
if bd.is_en_passant(mv):
cs = to[0] + fr[1]
if loc.get(cs) != m.get('capture'):
out.append('%s ply %s captures %r but %s is on %s' % (tag, m.get('ply'), m.get('capture'), loc.get(cs), cs))
# move the ids
if pieces:
pid = loc.pop(fr, None)
if bd.is_en_passant(mv):
loc.pop(to[0] + fr[1], None)
loc[to] = pid
if bd.is_castling(mv):
rank = fr[1]
rf, rt = ('h' + rank, 'f' + rank) if to[0] == 'g' else ('a' + rank, 'd' + rank)
loc[rt] = loc.pop(rf, None)
bd.push(mv)
if bool(m.get('check')) != bd.is_check():
out.append('%s ply %s check flag %r but check=%s' % (tag, m.get('ply'), m.get('check'), bd.is_check()))
if ok and moves:
if bd.is_checkmate():
want = '1-0' if bd.turn == chess.BLACK else '0-1'
if g.get('result') != want:
out.append('%s ends in mate but result %r (expected %s)' % (tag, g.get('result'), want))
elif bd.is_stalemate() or bd.is_insufficient_material():
if g.get('result') != '1/2-1/2':
out.append('%s ends drawn by rule but result %r' % (tag, g.get('result')))
elif not g.get('adjudication') and not g.get('reason') and g.get('result') != '1/2-1/2' and not bd.can_claim_draw():
o_note = '%s decisive result %r without mate and no adjudication field' % (tag, g.get('result'))
out.append(o_note)
tab = {t.get('player'): t for t in d.get('table') or []}
cnt = collections.defaultdict(lambda: [0, 0, 0, 0])
for g in d.get('games') or []:
for side, pid in (('white', g.get('white')), ('black', g.get('black'))):
c = cnt[pid]
c[0] += 1
r = g.get('result')
if r == '1/2-1/2':
c[2] += 1
elif (r == '1-0') == (side == 'white'):
c[1] += 1
else:
c[3] += 1
for pid, (pl, w, dr, l) in cnt.items():
t = tab.get(pid)
if not t or (t.get('played'), t.get('won'), t.get('drawn'), t.get('lost')) != (pl, w, dr, l):
out.append('%s: table row for %s does not re-add from games (expected %d/%d/%d/%d)' % (rel, pid, pl, w, dr, l))
def check_overlay(d, rel, out, o):
for k in ('schema', 'exp', 'rules', 'cut', 'n', 'state', 'key', 'cols'):
if k not in d:
out.append('%s: "%s" missing (lab overlay contract)' % (rel, k))
n = d.get('n')
for c, v in (d.get('cols') or {}).items():
if not isinstance(v, list) or len(v) != n:
out.append('%s: cols.%s length %s != n %s' % (rel, c, len(v) if isinstance(v, list) else '?', n))
def check_metrics(d, rel, out, o):
ov = rel[:-len('.metrics.json')] + '.json'
for k in ('exp', 'rules', 'hypothesis', 'algorithm', 'cut', 'deterministic', 'overlay_sha256', 'verdict'):
if k not in d:
out.append('%s: "%s" missing' % (rel, k))
if os.path.exists(o.p(ov)):
h = sha256_file(o.p(ov))
if d.get('overlay_sha256') and not overlay_digest_ok(o.p(ov), d['overlay_sha256'], o, 'V6'):
out.append('%s: overlay_sha256 %s.. but %s hashes to %s..' % (rel, d['overlay_sha256'][:12], ov, h[:12]))
if d.get('overlay_bytes') is not None and os.path.getsize(o.p(ov)) != d['overlay_bytes']:
out.append('%s: overlay_bytes %s but file is %d' % (rel, d['overlay_bytes'], os.path.getsize(o.p(ov))))
CONTRACT_FILES = None
def contract_keys_for(schema, o):
"""Generic: find a *CONTRACT*.md that names this schema and return the JSON keys its blocks name."""
global CONTRACT_FILES
if CONTRACT_FILES is None:
CONTRACT_FILES = []
for dp, dns, fns in os.walk(EXPLORE):
dns[:] = [d for d in dns if d not in SKIP_DIRS]
CONTRACT_FILES += sorted((os.path.join(dp, f) for f in fns if f.endswith('.md')),
key=lambda p: 'CONTRACT' not in p.upper())
cands = CONTRACT_FILES + [o.p(f) for f in o.files if 'CONTRACT' in f.upper() and f.endswith('.md')]
for c in cands:
t = io.open(c, encoding='utf-8', errors='replace').read()
for blk in re.findall(r'```json\n(.*?)```', t, re.S):
if '"%s"' % schema in blk:
return c, _top_keys(re.sub(r'//[^\n]*', '', blk))
return None, None
def _top_keys(blk):
"""Keys at depth 1 of a pseudo-JSON contract block (nested example items may be legitimately absent)."""
keys, depth, i = set(), 0, 0
for m in re.finditer(r'[{}\[\]]|"([A-Za-z_][A-Za-z0-9_]*)"\s*:', blk):
s = m.group(0)
if s in '{[':
depth += 1
elif s in '}]':
depth -= 1
elif depth == 1:
keys.add(m.group(1))
return keys
def _all_keys(x, acc):
if isinstance(x, dict):
for k, v in x.items():
acc.add(k)
_all_keys(v, acc)
elif isinstance(x, list):
for v in x[:200]:
_all_keys(v, acc)
return acc
@vaccine('V6', 'contracts',
'A writer and its readers drift apart: a field is renamed, dropped or filled outside its contract.',
'A JSON file fails its contract (GRAPH-CONTRACT.md, chess/CONTRACT.md, lab overlay contract) or a recorded '
'hash/sum does not re-add.',
'every build',
'GRAPH-CONTRACT.md and chess/CONTRACT.md: change only by bumping schema and updating every reader.')
def v_contracts(o):
out = []
checked = 0
board_by_dir = {}
for rel in o.json_files:
d = o.json(rel)
if isinstance(d, dict) and d.get('schema') == 'explore-chess-board-v1':
board_by_dir[os.path.dirname(rel)] = d
for rel in o.json_files:
d = o.json(rel)
if isinstance(d, Exception):
out.append('%s: not valid JSON (%s)' % (rel, str(d)[:100]))
continue
if not isinstance(d, dict):
continue
sch = d.get('schema')
if sch == 'explore-build-graph-v1' or os.path.basename(rel) == 'build_graph.json':
check_build_graph(d, rel, out, o)
elif sch == 'explore-chess-board-v1':
check_board(d, rel, out)
elif sch == 'explore-chess-games-v1':
check_games(d, rel, out, board_by_dir.get(os.path.dirname(rel)) or next(iter(board_by_dir.values()), None))
elif sch == 'explore-lab-overlay-v1':
check_overlay(d, rel, out, o)
elif rel.endswith('.metrics.json') and 'overlay_sha256' in d:
check_metrics(d, rel, out, o)
elif sch == 'explore-lab-keys-v1':
n = len(d.get('k') or [])
if len(d.get('blob') or []) != n:
out.append('%s: k and blob lengths differ' % rel)
bad = [i for i, k in enumerate(d.get('k') or []) if not KEY_RX.match(k)]
if bad:
out.append('%s: %d keys not repo@commit:path (first index %d)' % (rel, len(bad), bad[0]))
elif sch == 'explore-visual-v1':
for k in ('cut', 'roles', 'n', 'e'):
if k not in d:
out.append('%s: "%s" missing (visualise.py contract)' % (rel, k))
elif sch:
cf, keys = contract_keys_for(sch, o)
if not cf:
o.notes['V6'].append('%s: schema %r has no contract file to check against (UNCHECKED)' % (rel, sch))
continue
missing = sorted(keys - set(d))
if missing:
out.append('%s: keys named in %s absent: %s' % (rel, os.path.relpath(cf, EXPLORE), ', '.join(missing[:20])))
else:
o.notes['V6'].append('%s: no "schema" field (UNCHECKED)' % rel)
continue
checked += 1
if not checked:
o.status_override['V6'] = 'N/A'
o.notes['V6'].append('%d JSON files checked against a contract' % checked)
return out
# ---- V7 determinism
def _dir_digest(d, mask=None):
res = {}
for dp, dns, fns in os.walk(d):
for fn in fns:
p = os.path.join(dp, fn)
b = open(p, 'rb').read()
if mask:
for m in mask:
b = b.replace(m.encode(), b'<MASKED>')
res[os.path.relpath(p, d)] = hashlib.sha256(b).hexdigest()
return res
def _cmp_digest(a, b, label, out, limit=12):
diff = sorted(k for k in set(a) | set(b) if a.get(k) != b.get(k))
for k in diff[:limit]:
out.append('%s: %s differs (%s)' % (label, k, 'missing in one' if k not in a or k not in b else 'bytes'))
if len(diff) > limit:
out.append('%s: ... %d more differing files' % (label, len(diff) - limit))
return diff
def _tools_hash():
h = hashlib.sha256()
for dp, dns, fns in os.walk(EXPLORE):
dns[:] = sorted(d for d in dns if d not in SKIP_DIRS and d != 'verify')
for fn in sorted(fns):
if fn.endswith(('.py', '.html', '.css', '.js')):
h.update(fn.encode())
h.update(open(os.path.join(dp, fn), 'rb').read())
return h.hexdigest()
@vaccine('V7', 'determinism',
'The same input gives different bytes, so nobody can tell a change of evidence from noise.',
'Two rebuilds from one input differ, or a recorded output hash does not match the file.',
'every build',
'visualise.py docstring ("same graph in, byte-identical files out"); lab common.py (each experiment ran twice, '
'overlay_sha256 recorded); chess CONTRACT ("players are deterministic given a seed").')
def v_determinism(o):
out = []
did = 0
tmp = tempfile.mkdtemp(prefix='vk8-det-', dir='/tmp/vk/8') if os.path.isdir('/tmp/vk/8') else tempfile.mkdtemp()
try:
for rel in o.files:
if os.path.basename(rel) != 'build_graph.json':
continue
site = os.path.dirname(o.p(rel))
vis = os.path.join(EXPLORE, 'visualise.py')
if os.path.exists(vis):
th = _tools_hash()
digs = []
for k in ('a', 'b'):
od = os.path.join(tmp, 'vis-' + k)
r = subprocess.run([sys.executable, vis, '--graph', o.p(rel), '--out', od], capture_output=True, text=True, timeout=600)
if r.returncode:
out.append('visualise.py failed: %s' % r.stderr.strip()[-300:])
break
digs.append(_dir_digest(od))
if len(digs) == 2:
did += 1
if th != _tools_hash():
o.notes['V7'].append('tools changed during the visualise rebuild: INCONCLUSIVE')
else:
if not _cmp_digest(digs[0], digs[1], 'visualise.py rebuild A vs B', out):
o.notes['V7'].append('visualise.py run twice on %s: %d files byte-identical' % (rel, len(digs[0])))
pub = os.path.join(site, 'visual')
if os.path.isdir(pub):
d = _cmp_digest(digs[0], {k: v for k, v in _dir_digest(pub).items() if k in digs[0] or True},
'visualise.py rebuild vs published visual/', [], 0)
if d:
o.notes['V7'].append('published visual/ differs from a fresh visualise.py run in %d files '
'(%s): built by older code or another graph, not a determinism fault'
% (len(d), ', '.join(d[:4])))
if o.rebuild_site:
g = o.json(rel)
# Snapshot the tools (and essays) first, so teammates editing build.py mid-run cannot make the
# two rebuilds differ: both runs use the same frozen code.
snap = os.path.join(tmp, 'snap')
shutil.copytree(EXPLORE, os.path.join(snap, 'tools', 'explore'),
ignore=shutil.ignore_patterns('__pycache__', 'verify'))
essays = os.path.join(os.path.dirname(os.path.dirname(EXPLORE)), 'essays')
if os.path.isdir(essays):
shutil.copytree(essays, os.path.join(snap, 'essays'))
th = _tools_hash()
digs = []
for k in ('a', 'b'):
od = os.path.join(tmp, 'site-' + k)
cmd = [sys.executable, os.path.join(snap, 'tools', 'explore', 'build.py'), '--src', o.rebuild_site,
'--out', od, '--kuiper-tools', KUIPER_TOOLS]
r = subprocess.run(cmd, capture_output=True, text=True, timeout=1800)
if r.returncode:
out.append('build.py rebuild failed: %s' % r.stderr.strip()[-300:])
break
gg = json.load(open(os.path.join(od, 'build_graph.json')))
digs.append((gg['cut'], od))
if len(digs) == 2:
did += 1
if th != _tools_hash():
o.notes['V7'].append('tools in the working tree changed during the rebuild; both rebuilds used '
'one frozen snapshot, so the A/B comparison stands')
if True:
cuts = [digs[0][0], digs[1][0], digs[0][0][:10]]
da = {k: v for k, v in _dir_digest(digs[0][1], cuts).items() if not k.endswith('.parquet')}
db = {k: v for k, v in _dir_digest(digs[1][1], cuts).items() if not k.endswith('.parquet')}
if not _cmp_digest(da, db, 'build.py rebuild A vs B (cut stamp masked, parquet excluded)', out):
o.notes['V7'].append('build.py run twice: %d files identical after masking the cut stamp' % len(da))
dp_ = _cmp_digest(da, {k: v for k, v in _dir_digest(site, [g.get('cut', '@@'), g.get('cut', '@@')[:10]]).items()
if not k.endswith('.parquet')}, 'x', [], 0)
o.notes['V7'].append('rebuild vs the published build under test: %d of %d files differ (expected if the '
'tools changed since that build)' % (len(dp_), len(da)))
for rel in o.files:
if rel.endswith('.metrics.json'):
d = o.json(rel)
if isinstance(d, dict) and 'deterministic' in d:
did += 1
if d.get('deterministic') is not True:
out.append('%s: records deterministic=%r' % (rel, d.get('deterministic')))
ov = rel[:-len('.metrics.json')] + '.json'
if os.path.exists(o.p(ov)) and d.get('overlay_sha256') and not overlay_digest_ok(o.p(ov), d['overlay_sha256'], o, 'V7'):
out.append('%s: overlay bytes no longer match the recorded sha256' % ov)
chess_dir = os.path.join(EXPLORE, 'chess')
names = {os.path.basename(f): f for f in o.files}
if 'board.json' in names and os.path.exists(os.path.join(chess_dir, 'board.py')):
did += 1
res = []
for k in ('a', 'b'):
od = os.path.join(tmp, 'chess-' + k)
os.makedirs(od, exist_ok=True)
r = subprocess.run([sys.executable, os.path.join(chess_dir, 'board.py'), '--help'], capture_output=True, text=True, timeout=60)
args = []
if '--out' in r.stdout:
args = ['--out', os.path.join(od, 'board.json')]
r = subprocess.run([sys.executable, os.path.join(chess_dir, 'board.py')] + args, capture_output=True, text=True,
timeout=600, cwd=od)
f = os.path.join(od, 'board.json')
res.append(sha256_file(f) if os.path.exists(f) else None)
if None in res:
o.notes['V7'].append('chess board.py has no --out option I could use; recorded only (INCONCLUSIVE for chess)')
elif res[0] != res[1]:
out.append('chess board.py: two runs give different board.json bytes')
elif res[0] != sha256_file(o.p(names['board.json'])):
o.notes['V7'].append('published board.json differs from a fresh board.py run (input or code changed)')
finally:
shutil.rmtree(tmp, ignore_errors=True)
if not did:
o.status_override['V7'] = 'N/A'
return out
# ---- V8 accessibility markup
@vaccine('V8', 'a11y-markup',
'A page cannot be used with a screen reader or found by title.',
'No <html lang>, empty <title>, an image without alt, a control or link with no accessible name.',
'every build',
'WCAG 2.2 A: 3.1.1, 2.4.2, 1.1.1, 4.1.2.')
def v_a11y(o):
out = []
agg = collections.defaultdict(list)
for rel in o.html_files:
s = o.summary(rel)
if not s.lang:
agg['no <html lang>'].append(rel)
if not (s.title or '').strip():
agg['empty or missing <title>'].append(rel)
for line, a in s.imgs:
if 'alt' not in a and a.get('role') != 'presentation' and a.get('aria-hidden') != 'true':
agg['<img> without alt'].append('%s:%d' % (rel, line))
for c in s.controls:
a = c['attrs']
nm = ' '.join(''.join(c['name']).split())
typ = a.get('type', '').lower()
named = bool(nm or c.get('in_label') or a.get('aria-label') or a.get('aria-labelledby') or a.get('title')
or (a.get('id') and a['id'] in s.label_for)
or (c['tag'] == 'input' and typ in ('submit', 'button', 'reset', 'image') and (a.get('value') or a.get('alt'))))
if not named:
agg['<%s> with no accessible name' % c['tag']].append('%s:%d' % (rel, c['line']))
for k, v in agg.items():
out.append('%s: %d, e.g. %s' % (k, len(v), ', '.join(v[:8])))
if not o.html_files:
o.status_override['V8'] = 'N/A'
return out
# ---- V9 contrast
NAMED = {'white': '#ffffff', 'black': '#000000', 'red': '#ff0000', 'green': '#008000', 'blue': '#0000ff',
'yellow': '#ffff00', 'cyan': '#00ffff', 'aqua': '#00ffff', 'magenta': '#ff00ff', 'gray': '#808080',
'grey': '#808080', 'silver': '#c0c0c0', 'orange': '#ffa500', 'navy': '#000080', 'lime': '#00ff00'}
def parse_colour(v, var=None):
if not v:
return None
v = v.strip().lower()
if var:
for _ in range(4):
m = re.search(r'var\(\s*(--[\w-]+)\s*(?:,\s*([^)]+))?\)', v)
if not m:
break
v = v.replace(m.group(0), var.get(m.group(1), m.group(2) or ''))
m = re.search(r'#([0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3,4})\b', v)
if m:
h = m.group(1)
if len(h) in (3, 4):
h = ''.join(c * 2 for c in h)
r, g, b = int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)
a = int(h[6:8], 16) / 255 if len(h) == 8 else 1.0
return (r, g, b, a)
m = re.search(r'rgba?\(\s*([\d.]+)[ ,]+([\d.]+)[ ,]+([\d.]+)(?:\s*[,/]\s*([\d.]+%?))?\s*\)', v)
if m:
a = m.group(4)
a = 1.0 if a is None else (float(a[:-1]) / 100 if a.endswith('%') else float(a))
return (float(m.group(1)), float(m.group(2)), float(m.group(3)), a)
for w in re.findall(r'[a-z]+', v):
if w in NAMED:
return parse_colour(NAMED[w])
if w in ('transparent',):
return (0, 0, 0, 0.0)
return None
def blend(fg, bg):
a = fg[3]
return (fg[0] * a + bg[0] * (1 - a), fg[1] * a + bg[1] * (1 - a), fg[2] * a + bg[2] * (1 - a), 1.0)
def luminance(c):
def ch(x):
x = x / 255
return x / 12.92 if x <= 0.03928 else ((x + 0.055) / 1.055) ** 2.4
return 0.2126 * ch(c[0]) + 0.7152 * ch(c[1]) + 0.0722 * ch(c[2])
def contrast(a, b):
la, lb = luminance(a), luminance(b)
return (max(la, lb) + 0.05) / (min(la, lb) + 0.05)
def css_rules(css):
css = re.sub(r'/\*.*?\*/', '', css, flags=re.S)
css = re.sub(r'@(media|supports|layer|container)[^{]*\{', '', css)
rules = []
for m in re.finditer(r'([^{}@]+)\{([^{}]*)\}', css):
decl = {}
for d in m.group(2).split(';'):
if ':' in d:
k, v = d.split(':', 1)
decl[k.strip().lower()] = v.strip()
for sel in m.group(1).split(','):
rules.append((sel.strip(), decl))
return rules
def hexs(c):
return '#%02x%02x%02x' % tuple(int(round(x)) for x in c[:3])
@vaccine('V9', 'a11y-contrast',
'Text is drawn in a colour too close to its background to read.',
'A CSS rule (or palette colour used for text) gives a contrast ratio under 4.5:1.',
'every build',
'WCAG 2.2 AA 1.4.3 (4.5:1 for body text); palette from GRAPH-CONTRACT.md.')
def v_contrast(o):
out = []
sheets = []
seen = set()
for rel in o.by_ext('.css'):
sheets.append((rel, o.text(rel)))
for rel in o.html_files:
s = o.summary(rel)
for t in s.styles:
h = hashlib.md5(t.encode()).hexdigest()
if h not in seen:
seen.add(h)
sheets.append((rel + ' <style>', t))
rules = []
for src, css in sheets:
rules += [(src, sel, d) for sel, d in css_rules(css)]
var = {}
for src, sel, d in rules:
for k, v in d.items():
if k.startswith('--'):
var[k] = v
page_bg = (255, 255, 255, 1.0)
page_fg = (0, 0, 0, 1.0)
for src, sel, d in rules:
if sel in ('body', 'html', ':root'):
bg = parse_colour(d.get('background-color') or d.get('background'), var)
fg = parse_colour(d.get('color'), var)
if bg and bg[3] > 0:
page_bg = bg
if fg:
page_fg = fg