In this section
- Vaccines render · cosmic / tools/explore/verify/vaccines.py lines 1401–1956
- Explore — Visual Style Sheet render · cosmic / tools/explore/visual/app.css lines 1–53
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 1401–1956 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
- sample_pages, _Server, __init__, close, v_mobile, route, _graph_for_cut, _check_clean_record, v_clean, run_output, merge_newer, discover, run_paths, vname, load_words, write_report, extra_from_files, main
- 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:1401-1956 · 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
page_bg = blend(page_bg, (255, 255, 255, 1))
by_sel = collections.defaultdict(dict)
for src, sel, d in rules:
by_sel[sel].update(d)
checked = 0
bad = {}
for src, sel, d in rules:
fg = parse_colour(d.get('color'), var)
bgv = d.get('background-color') or d.get('background')
bg = parse_colour(bgv, var)
if not fg and not bg:
continue
if ':hover' in sel or '::selection' in sel or 'placeholder' in sel:
continue
if bg and not fg:
# text colour from a component rule: ".badge.r-x" -> ".badge"
for part in re.findall(r'\.[\w-]+', sel):
for cand in (part, sel.split(part)[0] + part):
c2 = parse_colour(by_sel.get(cand, {}).get('color'), var)
if c2:
fg = c2
break
if fg:
break
if not fg:
continue # a background with no text colour of its own: decorative
if fg and (not bg or bg[3] == 0):
if any(o2 != sel and o2.startswith(sel) and (by_sel[o2].get('background') or by_sel[o2].get('background-color'))
for o2 in by_sel):
continue # a base class whose variants set the background (".badge" -> ".badge.r-x"): checked there
bg = page_bg
bgb = blend(bg, page_bg)
fgb = blend(fg, bgb)
r = contrast(fgb, bgb)
checked += 1
if r < 4.5:
bad[(sel, hexs(fgb), hexs(bgb))] = (src, r)
for (sel, f, b), (src, r) in sorted(bad.items(), key=lambda kv: kv[1][1]):
out.append('%s: "%s" text %s on %s = %.2f:1' % (src, sel, f, b, r))
for rel in o.html_files[:400]:
s = o.summary(rel)
for line, st in s.inline_styles:
d = dict((k.strip().lower(), v.strip()) for k, v in (x.split(':', 1) for x in st.split(';') if ':' in x))
fg = parse_colour(d.get('color'), var)
bg = parse_colour(d.get('background') or d.get('background-color'), var)
if fg and bg:
checked += 1
r = contrast(blend(fg, page_bg), blend(bg, page_bg))
if r < 4.5:
out.append('%s:%d style="%s" = %.2f:1' % (rel, line, st[:80], r))
for rel in o.json_files:
if os.path.basename(rel) in ('build_graph.json',):
g = o.json(rel)
for role in (g.get('roles') or []) if isinstance(g, dict) else []:
c = parse_colour(role.get('colour'))
if c:
checked += 1
r = contrast(c, page_bg)
if r < 4.5:
out.append('%s: role palette "%s" %s on page background %s = %.2f:1 (used for text/badges)'
% (rel, role.get('id'), role.get('colour'), hexs(page_bg), r))
if not checked:
o.status_override['V9'] = 'N/A'
o.notes['V9'].append('%d colour pairs checked; page background %s' % (checked, hexs(page_bg)))
return out
# ---- V10 mobile
MOBILE_JS = r'''() => {
const vw = document.documentElement.clientWidth;
const sw = Math.max(document.documentElement.scrollWidth, document.body ? document.body.scrollWidth : 0);
const small = [];
const sel = 'a[href],button,input:not([type=hidden]),select,textarea,summary,[role=button],[role=link],[role=tab]';
for (const el of document.querySelectorAll(sel)) {
const r = el.getBoundingClientRect();
if (r.width === 0 || r.height === 0) continue;
const cs = getComputedStyle(el);
if (cs.visibility === 'hidden' || cs.display === 'none') continue;
if (el.tagName === 'A' && cs.display === 'inline') {
// links inside a sentence are exempt (WCAG 2.5.8 inline exception)
const p = el.parentElement;
const own = (el.textContent || '').trim().length;
const ptxt = p ? (p.textContent || '').trim().length : 0;
if (p && ptxt > own + 2 && !['NAV'].includes(p.tagName) && !p.closest('nav')) continue;
}
if (el.closest('pre,code')) continue;
if (r.height < 40 || r.width < 40) {
const label = (el.getAttribute('aria-label') || el.textContent || el.value || el.tagName).trim().slice(0, 40);
small.push(`${el.tagName.toLowerCase()} "${label}" ${Math.round(r.width)}x${Math.round(r.height)}`);
}
}
return {vw, sw, small};
}'''
def sample_pages(o, k=8):
hs = o.html_files
if not hs:
return []
pick = []
prefs = ['index.html', 'search.html', 'visual/index.html', 'journeys/a.html', 'chess/index.html', 'clarity/index.html']
for p in prefs:
for h in hs:
if h == p or h.endswith('/' + p):
if h not in pick:
pick.append(h)
break
by_dir = collections.OrderedDict()
for h in hs:
by_dir.setdefault(os.path.dirname(h), []).append(h)
for dname, lst in by_dir.items():
if len(pick) >= k:
break
if not any(os.path.dirname(x) == dname for x in pick):
pick.append(lst[0])
i = 0
while len(pick) < min(k, len(hs)):
h = hs[(i * 7919) % len(hs)]
if h not in pick:
pick.append(h)
i += 1
return pick[:k]
class _Server:
def __init__(self, root):
import http.server
import socketserver
handler = lambda *a, **kw: http.server.SimpleHTTPRequestHandler(*a, directory=root, **kw) # noqa
http.server.SimpleHTTPRequestHandler.log_message = lambda *a, **k: None
socketserver.TCPServer.allow_reuse_address = True
self.httpd = socketserver.ThreadingTCPServer(('127.0.0.1', 0), handler)
self.port = self.httpd.server_address[1]
threading.Thread(target=self.httpd.serve_forever, daemon=True).start()
def close(self):
self.httpd.shutdown()
self.httpd.server_close()
@vaccine('V10', 'mobile',
'The site works on a desk and breaks on a phone.',
'At 390x844 a sampled page scrolls sideways, has tap targets under 40px, logs console errors or requests a '
'non-allow-listed host.',
'every build',
'Owner request: mobile sanity via Playwright headless Chromium at 390x844 on a sample of pages.')
def v_mobile(o):
out = []
if not o.mobile_enabled:
o.status_override['V10'] = 'N/A'
o.notes['V10'].append('disabled (--no-mobile)')
return out
pages = sample_pages(o)
if not pages:
o.status_override['V10'] = 'N/A'
return out
try:
from playwright.sync_api import sync_playwright
except ImportError:
o.status_override['V10'] = 'INCONCLUSIVE'
o.notes['V10'].append('playwright not installed')
return out
serve_root = os.path.dirname(o.base_dir.rstrip('/'))
prefix = '/' + os.path.basename(o.base_dir.rstrip('/'))
srv = _Server(serve_root)
inconclusive = []
try:
with sync_playwright() as p:
b = p.chromium.launch()
ctx = b.new_context(viewport={'width': 390, 'height': 844}, device_scale_factor=2, is_mobile=True, has_touch=True)
for rel in pages:
pg = ctx.new_page()
errs, blocked_ok, blocked_bad = [], [], []
def route(r, blocked_ok=blocked_ok, blocked_bad=blocked_bad):
u = urllib.parse.urlsplit(r.request.url)
if u.scheme in ('data', 'blob') or (u.hostname or '') in LOCAL_HOSTS:
return r.continue_()
(blocked_ok if host_allowed(u.hostname, r.request.url) else blocked_bad).append(r.request.url)
return r.abort()
pg.route('**/*', route)
pg.on('console', lambda m, errs=errs: errs.append(m.text[:160]) if m.type == 'error' else None)
pg.on('pageerror', lambda e, errs=errs: errs.append('pageerror: ' + str(e)[:160]))
url = 'http://127.0.0.1:%d%s/%s' % (srv.port, prefix, urllib.parse.quote(rel))
try:
pg.goto(url, wait_until='load', timeout=45000)
pg.wait_for_timeout(1200)
m = pg.evaluate(MOBILE_JS)
except Exception as e:
out.append('%s: failed to load (%s)' % (rel, str(e)[:120]))
pg.close()
continue
if m['vw'] > 391:
out.append('%s: no responsive viewport (layout is %dpx wide on a 390px phone; add <meta name=viewport>)' % (rel, m['vw']))
elif m['sw'] > m['vw'] + 1:
out.append('%s: horizontal scroll (content %dpx wide in a %dpx viewport)' % (rel, m['sw'], m['vw']))
if m['small']:
out.append('%s: %d tap targets under 40px, e.g. %s' % (rel, len(m['small']), '; '.join(m['small'][:5])))
for u in sorted(set(blocked_bad))[:5]:
out.append('%s: requested non-allow-listed host %s' % (rel, u[:120]))
if errs:
if blocked_ok:
inconclusive.append('%s: %d console errors while the allow-listed CDN (%s) was unreachable offline; '
'first: %s' % (rel, len(errs), urllib.parse.urlsplit(blocked_ok[0]).hostname, errs[0]))
else:
out.append('%s: %d console errors, first: %s' % (rel, len(errs), ' | '.join(errs[:2])))
pg.close()
b.close()
finally:
srv.close()
o.notes['V10'].append('sampled: ' + ', '.join(pages))
o.notes['V10'] += inconclusive
return out
# ---- V11 cleaning records
CLEAN_KEY = re.compile(r'^[A-Za-z0-9_.-]+@[0-9a-f]{40} .+:\d+-\d+ (?:[0-9a-f]{40}|-)$')
CLEAN_CATS = {'noise-generated', 'noise-vendored', 'noise-minified', 'noise-data-blob', 'near-copy-of',
'family-older-than', 'unit-duplicate-of', 'keep'}
DELETE_WORDS = re.compile(r'\b(delete|deleted|deleting|remove from (?:the )?(?:repo|repository|source)|rm -rf|git rm|'
r'unlink|purge|wipe)\b', re.I)
GRAPH_CACHE = {}
def _graph_for_cut(cut, o):
cands = [o.p(f) for f in o.files if os.path.basename(f) == 'build_graph.json']
cands += sorted(os.path.join('/tmp', x, 'explore-code', 'build_graph.json') for x in os.listdir('/tmp') if re.match(r'site\d+$', x))
for c in cands:
if not os.path.exists(c):
continue
if c not in GRAPH_CACHE:
try:
g = json.load(open(c))
GRAPH_CACHE[c] = (g.get('cut'), g.get('files') or [])
except Exception:
continue
if GRAPH_CACHE[c][0] == cut:
return c, GRAPH_CACHE[c][1]
return None, None
def _check_clean_record(r, where, out, files, setaside):
if not isinstance(r, dict):
out.append('%s: not an object' % where)
return
key = r.get('key', '')
if not CLEAN_KEY.match(str(key)):
out.append('%s: key missing or malformed: %r' % (where, str(key)[:100]))
cat = str(r.get('category', ''))
tok = cat.split(' ', 1)[0]
if tok not in CLEAN_CATS:
out.append('%s: category %r outside the contract' % (where, cat[:60]))
elif ' ' in cat and not CLEAN_KEY.match(cat.split(' ', 1)[1]):
out.append('%s: target key malformed in category %r' % (where, cat[:100]))
if 'evidence' in r or 'reason' in r or not setaside:
if not r.get('evidence') or not isinstance(r.get('evidence'), list):
out.append('%s: no evidence list' % where)
blob = ' '.join([str(r.get('reason', '')), cat] + [str(e) for e in r.get('evidence') or []])
m = DELETE_WORDS.search(NEGATION.sub('', str(r.get('reason', '')) + ' ' + cat))
if m:
out.append('%s: proposes "%s" (cleaning may only set aside, never delete source)' % (where, m.group(0)))
fid = r.get('file_id')
if setaside and files is not None and isinstance(fid, int) and 0 <= fid < len(files):
f = files[fid]
if f.get('reachable') or f.get('canonical_status') == 'production_core' or f.get('entry'):
reason = str(r.get('reason', '')).strip()
if len(reason) < 12 or not r.get('evidence'):
out.append('%s: file %d is reachable/entry/production_core but set aside without a reason and evidence'
% (where, fid))
@vaccine('V11', 'clean-records',
'Cleaning quietly becomes deletion, or files leave the main view with no evidence anyone can check.',
'A clean proposal or manifest record has no key or evidence, proposes deleting source, uses a category outside '
'the contract, or sets aside a reachable file without a reason.',
'every clean run',
'clean/CONTRACT.md (clean-proposals-v1, clean-manifest-v1): "Nothing is ever deleted from any source repository."')
def v_clean(o):
out = []
checked = 0
for rel in o.json_files:
d = o.json(rel)
if not isinstance(d, dict) or d.get('schema') not in ('clean-proposals-v1', 'clean-manifest-v1'):
continue
if os.path.islink(o.p(rel)):
continue
gp, files = _graph_for_cut(d.get('graph_cut'), o)
if files is None:
o.notes['V11'].append('%s: no build_graph.json with cut %s found; reachability not checked' % (rel, d.get('graph_cut')))
if d['schema'] == 'clean-proposals-v1':
for i, r in enumerate(d.get('proposals') or []):
checked += 1
sa = isinstance(r, dict) and str(r.get('category', '')).split(' ')[0] != 'keep' and not (
str(r.get('category', '')).startswith('unit-duplicate-of') and not r.get('covers_whole_file'))
_check_clean_record(r, '%s: proposals[%d]' % (rel, i), out, files, sa)
else:
if d.get('dry_run') is not True:
o.notes['V11'].append('%s: dry_run is %r (approved manifest)' % (rel, d.get('dry_run')))
for i, r in enumerate(d.get('set_aside') or []):
checked += 1
_check_clean_record(r, '%s: set_aside[%d]' % (rel, i), out, files, True)
for i, r in enumerate(d.get('main_view') or []):
if not CLEAN_KEY.match(str(r.get('key', ''))):
out.append('%s: main_view[%d] key malformed' % (rel, i))
c = d.get('counts') or {}
mv, sa = len(d.get('main_view') or []), len(d.get('set_aside') or [])
if files is not None and mv + sa != len(files):
out.append('%s: main_view %d + set_aside %d != %d files in the graph' % (rel, mv, sa, len(files)))
ids = [r.get('file_id') for r in (d.get('main_view') or []) + (d.get('set_aside') or [])]
if len(ids) != len(set(ids)):
out.append('%s: a file is in both main_view and set_aside (or twice)' % rel)
if c.get('main_view') not in (None, mv) or c.get('set_aside') not in (None, sa):
out.append('%s: counts do not re-add (main_view %s/%d, set_aside %s/%d)' % (rel, c.get('main_view'), mv, c.get('set_aside'), sa))
if files is not None:
reach = sum(1 for r in d.get('set_aside') or [] if isinstance(r.get('file_id'), int)
and r['file_id'] < len(files) and files[r['file_id']].get('reachable'))
o.notes['V11'].append('%s: %d set aside, %d of them reachable (each must carry reason + evidence)' % (rel, sa, reach))
if not checked:
o.status_override['V11'] = 'N/A'
o.notes['V11'].append('%d clean records checked' % checked)
return out
# ------------------------------------------------------------------ runner
def run_output(o, only=None):
res = {}
for v in VACCINES:
if only and v['id'] not in only and v['name'] not in only:
continue
t0 = time.time()
try:
f = v['antibody'](o)
except Exception:
f = ['ANTIBODY CRASHED (fail-closed): ' + traceback.format_exc().strip().split('\n')[-1]]
st = o.status_override.get(v['id'])
if f:
st = 'FAIL'
elif not st:
st = 'PASS'
res[v['id']] = {'status': st, 'findings': f, 'notes': list(o.notes.get(v['id'], [])),
'seconds': round(time.time() - t0, 1), 'at': now()}
return res
def merge_newer(res, path):
"""Fold in per-vaccine results from findings.json that are newer than ours (a parallel partial run, e.g. the
slow site-rebuild determinism check, must not be overwritten by the watch loop)."""
if not os.path.exists(path):
return res
try:
old = json.load(open(path))
except Exception:
return res
for k, v in old.items():
if k not in res:
continue
for vid, x in v.get('res', {}).items():
mine = res[k]['res'].get(vid)
if mine is None or x.get('at', '') > mine.get('at', ''):
res[k]['res'][vid] = x
return res
def discover():
outs = []
sites = sorted(d for d in (os.path.join('/tmp', x, 'explore-code') for x in os.listdir('/tmp') if re.match(r'site\d+$', x))
if os.path.isdir(d))
sites = [s for s in sites if int(re.search(r'site(\d+)', s).group(1)) >= 7]
outs += sites
if os.path.isdir('/tmp/lab-out'):
outs.append('/tmp/lab-out')
if os.path.isdir('/tmp/vk'):
for n in sorted(os.listdir('/tmp/vk')):
d = os.path.join('/tmp/vk', n)
if n == '8' or not os.path.isdir(d):
continue
has = False
for dp, dns, fns in os.walk(d):
dns[:] = [x for x in dns if x not in SKIP_DIRS]
if 'build_graph.json' in fns and dp != d:
outs.append(dp)
if any(os.path.splitext(f)[1].lower() in ('.html', '.json', '.txt', '.md') for f in fns):
has = True
if has:
outs.append(d)
return outs
def run_paths(paths, args, cache=None):
results = {}
for pth in paths:
o = Output(pth, rebuild_site=args.rebuild_site if '/tmp/site' in pth else None, mobile=not args.no_mobile,
words=load_words(args.words))
# nested explore sites are reported on their own; skip them inside a parent output
if any(q != pth and q.startswith(pth.rstrip('/') + '/') for q in paths):
nested = [os.path.relpath(q, pth) for q in paths if q != pth and q.startswith(pth.rstrip('/') + '/')]
o.files = [f for f in o.files if not any(f.startswith(n + '/') for n in nested)]
fp = o.fingerprint() + CODE_VERSION + ('R' if o.rebuild_site else '')
if cache is not None and cache.get(pth, {}).get('fp') in (fp, fp + 'R'):
results[pth] = cache[pth]
continue
t0 = time.time()
print('[%s] verifying %s (%d files, kinds %s)' % (now(), pth, len(o.files), ','.join(sorted(o.kinds())) or '-'), flush=True)
r = run_output(o, args.only.split(',') if args.only else None)
results[pth] = {'fp': fp, 'at': now(), 'files': len(o.files), 'kinds': sorted(o.kinds()), 'res': r,
'seconds': round(time.time() - t0)}
if cache is not None:
cache[pth] = results[pth]
for vid, x in r.items():
print(' %-4s %-13s %-12s %d findings (%ss)' % (vid, vname(vid), x['status'], len(x['findings']), x['seconds']), flush=True)
return results
def vname(vid):
return next(v['name'] for v in VACCINES if v['id'] == vid)
def load_words(path):
if not path:
return RELIGIOUS_WORDS
return [w.strip().lower() for w in io.open(path, encoding='utf-8') if w.strip() and not w.startswith('#')]
def write_report(results, path, history=None, extra_sections=()):
vids = [v['id'] for v in VACCINES]
L = ['# Vaccines report: independent verification of Explore Code outputs', '',
'Generated %s by `tools/explore/verify/vaccines.py` (Vikram\'s Assistant 8, the team\'s independent verifier). '
'A vaccine is a named failure mode plus its executable antibody; zero findings = immune. FAIL lists the exact '
'failing items (first %d per vaccine; counts are exact). N/A = nothing of that kind in the output. '
'INCONCLUSIVE = could not be measured here (the reason is given). The verifier edits nothing it checks.' % (now(), CAP), '']
L += ['## Matrix', '', '| output | kinds | ' + ' | '.join('%s %s' % (v, vname(v)) for v in vids) + ' |',
'|---|---|' + '---|' * len(vids)]
for pth, r in results.items():
cells = []
for v in vids:
x = r['res'].get(v)
if not x:
cells.append('-')
elif x['status'] == 'FAIL':
cells.append('**FAIL** %d' % len(x['findings']))
else:
cells.append(x['status'])
L.append('| `%s` | %s | %s |' % (pth, ', '.join(r['kinds']) or '-', ' | '.join(cells)))
L += ['']
for pth, r in results.items():
L += ['## `%s`' % pth, '', '%d files, verified %s in %ss (fingerprint %s).' % (r['files'], r['at'], r['seconds'], r['fp']), '']
for v in vids:
x = r['res'].get(v)
if not x:
continue
L.append('### %s %s: %s' % (v, vname(v), x['status'] + (' (%d)' % len(x['findings']) if x['findings'] else '')))
for n in x['notes'][:8]:
L.append('- note: ' + n.replace('\n', ' '))
for f in x['findings'][:CAP]:
L.append('- ' + f.replace('\n', ' ').replace('|', '\\|'))
if len(x['findings']) > CAP:
L.append('- ... and %d more (full list in /tmp/vk/8/findings.json)' % (len(x['findings']) - CAP))
L.append('')
for title, body in extra_sections:
L += ['## ' + title, '', body.rstrip(), '']
if history:
L += ['## Run history', ''] + ['- ' + h for h in history] + ['']
L += ['## The vaccines (CVAA five sections)', '']
for v in VACCINES:
L += ['### %s %s' % (v['id'], v['name']), '', '- Disease: ' + v['disease'], '- Symptom: ' + v['symptom'],
'- Antibody: `%s()` in vaccines.py' % v['antibody'].__name__, '- Dose: ' + v['dose'],
'- Provenance: ' + v['provenance'], '']
os.makedirs(os.path.dirname(path), exist_ok=True)
io.open(path, 'w', encoding='utf-8').write('\n'.join(L))
json.dump(results, io.open(os.path.join(os.path.dirname(path), 'findings.json'), 'w', encoding='utf-8'), indent=1)
def extra_from_files():
"""Other sections (e.g. the code review) are kept in /tmp/vk/8/sections/*.md and appended verbatim."""
d = '/tmp/vk/8/sections'
res = []
if os.path.isdir(d):
for f in sorted(os.listdir(d)):
if f.endswith('.md'):
t = io.open(os.path.join(d, f), encoding='utf-8').read()
title, _, body = t.partition('\n')
res.append((title.lstrip('# ').strip(), body))
return res
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])
sub = ap.add_subparsers(dest='cmd', required=True)
for name in ('run', 'watch'):
s = sub.add_parser(name)
if name == 'run':
s.add_argument('paths', nargs='*')
else:
s.add_argument('--minutes', type=float, default=90)
s.add_argument('--every', type=float, default=10)
s.add_argument('--report', default=REPORT)
s.add_argument('--rebuild-site', default=None, help='clones folder: rebuild the site twice (slow)')
s.add_argument('--no-mobile', action='store_true')
s.add_argument('--only', default='')
s.add_argument('--words', default=None)
sub.add_parser('list')
a = ap.parse_args(argv)
if a.cmd == 'list':
for v in VACCINES:
print('%s %s\n Disease: %s\n Symptom: %s\n Dose: %s\n Provenance: %s\n' % (
v['id'], v['name'], v['disease'], v['symptom'], v['dose'], v['provenance']))
return 0
os.makedirs(STATE, exist_ok=True)
cache_p = os.path.join(STATE, 'cache.json')
cache = json.load(open(cache_p)) if os.path.exists(cache_p) and a.cmd == 'watch' else {}
fj = os.path.join(os.path.dirname(a.report or REPORT), 'findings.json')
if a.cmd == 'watch' and os.path.exists(fj):
for k, v in json.load(open(fj)).items():
cache.setdefault(k, v)
hist_p = os.path.join(STATE, 'history.json')
history = json.load(open(hist_p)) if os.path.exists(hist_p) else []
if a.cmd == 'run':
paths = a.paths or discover()
res = run_paths(paths, a)
cache = json.load(open(cache_p)) if os.path.exists(cache_p) else {}
if not a.only:
cache.update(res)
json.dump(cache, open(cache_p, 'w'))
fails = sum(1 for r in res.values() for x in r['res'].values() if x['status'] == 'FAIL')
history.append('%s run over %d outputs: %d FAIL cells' % (now(), len(res), fails))
json.dump(history, open(hist_p, 'w'))
if a.report:
old = {}
if os.path.exists(os.path.join(os.path.dirname(a.report), 'findings.json')) and a.report == REPORT:
old = json.load(open(os.path.join(os.path.dirname(a.report), 'findings.json')))
for k, v in res.items(): # merge per vaccine, so a partial (--only) run keeps the other results
if k in old and a.only:
old[k]['res'].update(v['res'])
old[k]['at'] = v['at']
else:
old[k] = v
write_report(old, a.report, history, extra_from_files())
return 1 if fails else 0
end = time.time() + a.minutes * 60
while True:
paths = discover()
res = run_paths(paths, a, cache)
json.dump(cache, open(cache_p, 'w'))
fails = sum(1 for r in res.values() for x in r['res'].values() if x['status'] == 'FAIL')
res = merge_newer(res, os.path.join(os.path.dirname(a.report), 'findings.json'))
history.append('%s watch pass over %d outputs: %d FAIL cells' % (now(), len(res), fails))
json.dump(history, open(hist_p, 'w'))
write_report(res, a.report, history, extra_from_files())
if time.time() + a.every * 60 > end:
break
time.sleep(a.every * 60)
return 0
if __name__ == '__main__':
sys.exit(main())Explore — Visual Style Sheet
A style sheet in the tools folder of Cosmic.
rendercosmic / tools/explore/visual/app.css · lines 1–53 of 53 · Not reached from any entry point (candidate for review)
- What it does
- Side effects: changes the web page (DOM).
- What it achieves
- No statement of purpose was found in the file, a README line naming it, or its name. Described from its file name only (a candidate, not yet checked against the code).
- Why it matters
- No other file in the estate was found to import it.
- Application
- cosmic · tools/explore/visual · style sheet
- Uses
- none found
- Used by
- none found
- Produces
- none declared
- Defines here
- none
- 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/visual/app.css:1-53 · blob 67cda7cc6c2c3fdfb96c1f1123bfc201c9b9eec8 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unreached_review
:root{--bg:#000;--panel:#0b0e14;--line:#2f343d;--ink:#fff;--muted:#a6adbb;--link:#66ccff;--accent:#00ffff;--sel:#0066ff}
*{box-sizing:border-box}html,body{margin:0;height:100%;background:var(--bg);color:var(--ink);font:13px/1.45 ui-monospace,Menlo,Consolas,monospace}
a{color:var(--link)}button,select,input{background:var(--panel);color:var(--ink);border:1px solid var(--line);font:inherit;padding:4px 7px;border-radius:0}
select{max-width:190px}
button:hover,select:hover{border-color:var(--accent)}label{color:var(--muted);white-space:nowrap}input[type=checkbox]{padding:0;accent-color:#00ffff}
#bar{display:flex;flex-wrap:wrap;gap:6px 10px;align-items:center;padding:6px 10px;border-bottom:1px solid var(--line);background:var(--bg)}
.brand{color:var(--link);letter-spacing:.08em;text-decoration:none;font-weight:bold}
#tabs{display:flex;gap:2px}#tabs button[aria-selected=true]{border-color:var(--accent);color:var(--accent)}
#cmd{position:relative;flex:1 1 260px;min-width:200px}#q{width:100%}
#sug{position:absolute;top:100%;left:0;right:0;z-index:20;background:var(--panel);border:1px solid var(--accent);max-height:60vh;overflow:auto}
#sug div{padding:4px 8px;cursor:pointer;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}#sug div.on,#sug div:hover{background:#12202a}
#sug small{color:var(--muted)}
#stage{position:relative;height:calc(100vh - 46px);height:calc(100dvh - 46px);overflow:hidden}
#cv{display:block;width:100%;height:100%;touch-action:none;cursor:crosshair}
#flow{position:absolute;inset:0;overflow:auto;padding:12px 16px 60px;background:var(--bg)}
#flow table{border-collapse:collapse;font-size:12px}#flow td,#flow th{border:1px solid #161a20;padding:3px 6px;text-align:right;min-width:42px}
#flow th{color:var(--muted);font-weight:normal;white-space:nowrap}#flow th.row{text-align:left}#flow td.c{cursor:pointer}#flow td.c:hover{outline:1px solid var(--accent)}
#flow h2{font-size:14px;color:var(--link);margin:18px 0 6px}#flow p{color:var(--muted);max-width:820px}
#tip{position:absolute;z-index:15;pointer-events:none;max-width:380px;background:rgba(11,14,20,.96);border:1px solid var(--line);padding:7px 9px;font-size:12px}
#tip b{color:var(--ink)}#tip .m,#info .m{color:var(--muted)}
#legendbox{position:absolute;left:8px;bottom:30px;z-index:10;background:rgba(11,14,20,.92);border:1px solid var(--line);padding:6px 8px;max-height:46%;overflow:auto;max-width:300px}
#legtitle{display:block;width:100%;text-align:left;border:0;padding:0;background:none;color:var(--accent);margin-bottom:3px;cursor:pointer}#legtitle:after{content:' ▾';color:var(--muted)}#legtitle[aria-expanded=false]:after{content:' ▸'}#legend{list-style:none;margin:0;padding:0}
#legend li{cursor:pointer;padding:1px 0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}#legend li.off{opacity:.3;text-decoration:line-through}
#legend i{display:inline-block;width:10px;height:10px;margin-right:6px;vertical-align:-1px}#legend small{color:var(--muted)}#legnote{color:var(--muted);font-size:11px;margin-top:4px;max-width:280px}
#info{position:absolute;right:0;top:0;bottom:0;width:min(400px,92vw);z-index:12;background:rgba(11,14,20,.97);border-left:1px solid var(--line);padding:10px 12px 40px;overflow:auto}
#info h2{font-size:15px;margin:0 22px 4px 0;color:var(--ink)}#info h3{font-size:12px;color:var(--link);margin:12px 0 3px}
#info dl{display:grid;grid-template-columns:max-content 1fr;gap:1px 10px;margin:6px 0}#info dt{color:var(--link)}#info dd{margin:0;overflow-wrap:anywhere}
#info ul{list-style:none;padding:0;margin:0}#info li{padding:2px 0;cursor:pointer;overflow-wrap:anywhere}#info li:hover{color:var(--accent)}
#info .x{position:absolute;right:8px;top:6px}#info .open{display:inline-block;margin:6px 6px 0 0;padding:5px 9px;border:1px solid var(--accent);color:var(--accent);text-decoration:none}
.sw{display:inline-block;width:9px;height:9px;margin-right:5px}
#status{position:absolute;right:8px;bottom:6px;color:var(--muted);font-size:11px;pointer-events:none}
.vh{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
.skip{position:absolute;left:-999px;top:0;z-index:50;background:var(--panel);padding:10px}.skip:focus{left:8px}
:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
#ftoggle{display:none}
#load{position:absolute;left:50%;top:40%;transform:translate(-50%,-50%);width:min(320px,80vw);z-index:30;text-align:center;color:var(--muted)}
#load[hidden]{display:none}#loadbar{height:4px;width:0;background:var(--accent);margin-bottom:8px;transition:width .2s}
#toast{position:absolute;left:50%;top:10px;transform:translateX(-50%);z-index:25;background:rgba(11,14,20,.96);border:1px solid var(--accent);color:var(--ink);padding:6px 12px;max-width:90vw;pointer-events:none}
#info .lead{color:var(--muted);margin:4px 0}
#plain{max-width:1100px;margin:0 auto;padding:10px 18px 40px;border-top:1px solid var(--line)}#plain h1{font-size:18px}#plain h2{font-size:15px;color:var(--link)}
.ns{padding:10px 18px;color:var(--muted)}
@media (max-width:760px){#bar{gap:4px 6px;padding:4px 6px}#bar .more{display:none}#bar.open .more{display:inline-flex}
#ftoggle{display:inline-block;order:1}.brand{flex:1 1 auto}#tabs{flex:1 1 100%;order:2}#tabs button{flex:1 1 0;padding:4px 2px;white-space:nowrap}#tabs .k{display:none}
#cmd{flex:1 1 100%;order:3}#bar .more{order:4}#status{max-width:62vw;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
#info{top:auto;left:0;width:auto;height:42%;border-left:0;border-top:1px solid var(--line)}
#legendbox{max-height:34%;font-size:12px;bottom:34px}#legendbox.closed{padding:0 8px}#status{font-size:10px}
#flow{overflow-x:auto}}
/* phones and touch: 16px controls (no iOS zoom), 44px taps */
@media (max-width:760px),(pointer:coarse){button,select,input,#legtitle{font-size:16px}
button,select,input[type=search],.brand{min-height:44px}#bar label{min-height:44px;align-items:center;gap:6px;font-size:14px}
input[type=checkbox]{width:22px;height:22px}#sug div{padding:12px 10px}#legend li{padding:12px 0}#info li{padding:10px 0}
#info .x{min-width:44px}#info .open{padding:12px 14px}.brand{display:inline-flex;align-items:center}#flow td.c{padding:12px 8px}}
@media (prefers-reduced-motion:reduce){*{transition:none!important}}