GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / cosmic / tools/explore/verify

Test Vaccines and 1 more file

A test in the verify folder of Cosmic that checks Vaccines, using haversine and SHA-256. It runs one (`run_one`) and sets up (`setUp`).

474 lines of Python from cosmic, in 2 files. Topic: Kuiper, cosmos and drawing engines. Section 1167 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Review storage · cosmic / tools/explore/verify/review.py lines 1–163
  2. Test Vaccines test · cosmic / tools/explore/verify/test_vaccines.py lines 1–311

Review

A Python command-line tool in the verify folder of Cosmic that works with files under (`files_under`) and asserts missing (`asserts_missing`).

storagecosmic / tools/explore/verify/review.py · lines 1–163 of 163 · Entry point

What it does
It fetches data. Defines files_under, comments_and_strings, asserts_missing, scan, main. Uses libraries ast, json, os, re, sys. Side effects: reads or writes files; makes network requests; starts processes.
Inputs & outputs
In: command-line arguments. Out: JSON file.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It is built from the comments and strings helper (`comments_and_strings`) and the scan step (`scan`). Static review scan of the team's new/changed code under `tools/explore/`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
cosmic · tools/explore/verify · Python CLI
Uses
Vaccines (import), ast, json, os, re, sys, io, tokenize
Used by
none found
Produces
files_under, comments_and_strings, asserts_missing, scan, main
Defines here
files_under, comments_and_strings, asserts_missing, scan, 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/review.py:1-163 · blob 10ce93b1129599245a27a74a93d7116d839bfbae · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: unknown · users: none · canonical: supporting_data
#!/usr/bin/env python3
"""tools/explore/verify/review.py - static review scan of the team's new/changed code under tools/explore/.

Flags, with file:line, for a human reviewer to confirm (a flag is a CANDIDATE, not a verdict):
  network     urllib/requests/http.client/socket/fetch/XMLHttpRequest/WebSocket to anything but localhost
  write       open(...,'w'/'a'), write_text/bytes, json.dump to a path, makedirs, copy: path shown so the reviewer can
              see whether it is under /tmp, the agent's folder or an --out argument
  delete      os.remove/unlink/rmdir, shutil.rmtree, Path.unlink, rm -rf
  git         subprocess/os.system running git (read-only plumbing is noted, mutation is HIGH)
  exec        eval/exec/compile/new Function/pickle.load/yaml.load/subprocess shell=True
  secret      token-, key- or password-shaped literals
  religion    words from vaccines.RELIGIOUS_WORDS in comments and strings
  privacy     Kuiper check_proof.leaks digest match
  tests       test functions with no assertion

    python review.py FILE_OR_DIR ... [--json out.json]
"""
import ast
import json
import os
import re
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import vaccines as V  # noqa: E402

RULES = [
    ('network', 'HIGH', re.compile(r'\burllib\.request\b|\brequests\.(get|post|put|delete|Session)\b|\bhttp\.client\b|'
                                    r'\bsocket\.(socket|create_connection)\b|\burlopen\(|\bfetch\(\s*[\'"`]https?://|'
                                    r'new\s+WebSocket\(|XMLHttpRequest|\bcurl\b|\bwget\b|gh\s+api')),
    ('delete', 'HIGH', re.compile(r'\bos\.(remove|unlink|rmdir|removedirs)\(|shutil\.rmtree\(|\.unlink\(|\brm\s+-[rf]+|'
                                   r'fs\.(rm|rmSync|unlink|unlinkSync|rmdirSync)\(')),
    ('git', 'HIGH', re.compile(r'[\'"]git[\'"]\s*,|[\'"]git\s+(commit|push|add|reset|checkout|rm|clean|rebase|merge|tag)|'
                                r'os\.system\([^)]*git')),
    ('exec', 'HIGH', re.compile(r'(?<![\w.])(eval|exec)\(|new\s+Function\(|pickle\.loads?\(|yaml\.load\(|shell\s*=\s*True|'
                                 r'os\.system\(|child_process|execSync\(')),
    ('secret', 'HIGH', re.compile(r'(ghp_|github_pat_|sk-[A-Za-z0-9]{20}|AKIA[0-9A-Z]{16}|xox[bp]-)|'
                                   r'(?:[Aa][Pp][Ii][_-]?[Kk][Ee][Yy]|[Ss]ecret|[Pp]assword|passwd|[Tt]oken)\s*[:=]\s*[\'"][^\'"]{8,}[\'"]')),
    ('write', 'MEDIUM', re.compile(r'open\([^)]*[\'"][wa]b?\+?[\'"]|\.write_(text|bytes)\(|\bos\.makedirs\(|shutil\.(copy|move)|'
                                    r'fs\.(writeFileSync|writeFile|mkdirSync)\(')),
]
CODE_EXT = ('.py', '.js', '.mjs', '.html', '.css', '.sh')


def files_under(paths):
    for p in paths:
        if os.path.isfile(p):
            yield p
        else:
            for dp, dns, fns in os.walk(p):
                dns[:] = sorted(d for d in dns if d not in V.SKIP_DIRS)
                for f in sorted(fns):
                    if f.endswith(CODE_EXT + ('.md', '.json')):
                        yield os.path.join(dp, f)


def comments_and_strings(path, text):
    """(line, text) of comments and string literals (Python via tokenize; others via a regex)."""
    out = []
    if path.endswith('.py'):
        import io as _io
        import tokenize
        try:
            for tok in tokenize.generate_tokens(_io.StringIO(text).readline):
                if tok.type in (tokenize.COMMENT, tokenize.STRING):
                    out.append((tok.start[0], tok.string))
        except Exception:
            pass
        return out
    for m in re.finditer(r'//[^\n]*|/\*.*?\*/|<!--.*?-->|"(?:\\.|[^"\\\n])*"|\'(?:\\.|[^\'\\\n])*\'|`[^`]*`|>[^<>]+<', text, re.S):
        out.append((text.count('\n', 0, m.start()) + 1, m.group(0)))
    return out


def asserts_missing(path, text):
    res = []
    if not (os.path.basename(path).startswith('test') and path.endswith('.py')):
        return res
    try:
        tree = ast.parse(text)
    except SyntaxError as e:
        return [(e.lineno or 0, 'test file does not parse')]
    for node in ast.walk(tree):
        if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name.startswith('test'):
            src = ast.get_source_segment(text, node) or ''
            if not re.search(r'\bassert|self\.assert|self\.fail|pytest\.raises|assertRaises|check\w*\(|expect\(|verify\w*\(', src):
                res.append((node.lineno, 'test %s has no assertion' % node.name))
            elif re.fullmatch(r'\s*def [^\n]*\n(\s*("""[^"]*"""|#[^\n]*)\n)*\s*(self\.)?assert(True)?\(?\s*True\)?\s*', src):
                res.append((node.lineno, 'test %s asserts only True' % node.name))
    return res


def scan(path):
    text = V._read(path)
    lines = text.split('\n')
    flags = []
    is_test = os.path.basename(path).startswith('test')
    for n, line in enumerate(lines, 1):
        s = line.strip()
        if path.endswith('.md') or path.endswith('.json'):
            break
        for kind, sev, rx in RULES:
            if rx.search(line):
                if kind == 'network' and re.search(r'127\.0\.0\.1|localhost', line):
                    continue
                if kind == 'exec' and re.search(r'\.exec\(|re\.compile|regex|RegExp|\bexec\(\s*\)', line):
                    continue
                if kind == 'exec' and s.startswith(('#', '//', '*', "'", '"')):
                    continue
                if kind in ('network', 'git', 'exec', 'delete') and re.search(r'[\'"].*\b(fetch|eval|exec|git|urlopen|rm)\b.*[\'"]\s*[,:)]', line) and \
                        re.search(r'(re\.compile|RX|PAT|WORDS|=\s*\(|\'process\'|\'network\')', line):
                    continue  # a pattern table that detects the call, not a call
                sev2 = sev
                if kind == 'git' and not re.search(r'[\'"](commit|push|add|reset|checkout|clean|rebase|merge|tag|rm|config|remote)[\'"\s]', line):
                    sev2 = 'LOW'  # read-only git plumbing (rev-parse, ls-files, cat-file, log)
                if kind == 'delete' and re.search(r'tmp|tempfile|mkdtemp|TemporaryDirectory', line):
                    sev2 = 'LOW'
                if kind == 'network' and re.search(r'assert(IsNone|NotIn|False)|re\.search', line):
                    sev2 = 'LOW'  # a test asserting the call is absent
                if kind == 'write' and re.search(r'/tmp|tmp|args\.out|\bout\b|OUT|outdir|out_dir', line):
                    sev2 = 'LOW'
                if is_test and sev2 != 'HIGH':
                    sev2 = 'LOW'
                flags.append((sev2, kind, n, s[:160]))
    rx = re.compile(r'\b(%s)\b' % '|'.join(map(re.escape, V.RELIGIOUS_WORDS)), re.I)
    seen = set()
    for n, t in comments_and_strings(path, text) if not path.endswith(('.md', '.json')) else enumerate(lines, 1):
        for m in rx.finditer(t):
            w = m.group(1).lower()
            if (n, w) in seen:
                continue
            seen.add((n, w))
            guard = len(set(x.lower() for x in rx.findall(t))) >= 4 and '|' in t  # a detector's word list
            sev = 'LOW' if w == 'vedic' or guard else 'MEDIUM'  # VEDIC is the estate's existing statement name; reported, not ranked high
            flags.append((sev, 'religion', n, '"%s" in %s' % (m.group(1), ' '.join(t.split())[:120])))
    if V._leaks()(text):
        flags.append(('HIGH', 'privacy', 0, '%d token(s) match a non-public digest' % V._leaks()(text)))
    for n, msg in asserts_missing(path, text):
        flags.append(('MEDIUM', 'tests', n, msg))
    return flags


def main(argv):
    out_json = None
    if '--json' in argv:
        i = argv.index('--json')
        out_json = argv[i + 1]
        argv = argv[:i] + argv[i + 2:]
    allf = {}
    for p in files_under(argv):
        allf[p] = scan(p)
    order = {'HIGH': 0, 'MEDIUM': 1, 'LOW': 2}
    rows = sorted(((sev, kind, p, n, s) for p, fl in allf.items() for sev, kind, n, s in fl), key=lambda r: (order[r[0]], r[1], r[2], r[3]))
    for r in rows:
        print('%-6s %-8s %s:%d  %s' % r)
    if out_json:
        json.dump([dict(zip(('severity', 'kind', 'file', 'line', 'text'), r)) for r in rows], open(out_json, 'w'), indent=1)
    return 0


if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))

Test Vaccines

A test in the verify folder of Cosmic that checks Vaccines, using haversine and SHA-256. It runs one (`run_one`) and sets up (`setUp`).

testcosmic / tools/explore/verify/test_vaccines.py · lines 1–311 of 311 · Entry point · pattern run_one (shared by 2 files)

What it does
It tests its inputs. Defines 51 functions or classes, including run_one, page, chess_board, chess_games, Registry. Uses libraries hashlib, json, os, shutil, sys. Side effects: reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
Inputs & outputs
In: JSON file m.metrics.json; JSON file x.json; JSON file build_graph.json; JSON file board.json; JSON file games.json; JSON file x.metrics.json; JSON file p.json; DuckDB queries.
Downstream impact
It is itself an entry point (test); no other file was found loading it.
What it achieves
Self-test for `vaccines.py`, CVAA-style: every antibody must stay quiet on a healthy fixture and fire on a diseased one. python -m unittest `tools/explore/verify/test_vaccines.py`.
Why it matters
Guards the behaviour of Vaccines.
Application
cosmic · tools/explore/verify · test
Uses
Vaccines (import), hashlib, json, os, shutil, sys, tempfile, unittest, check_proof
Used by
none found
Produces
run_one, page, chess_board, chess_games, Registry, V1FirstLaw, V2Religion, V3Private, V4Hosts, V5Links, V6Contracts, V7Determinism
Defines here
run_one, page, chess_board, chess_games, Registry, test_five_sections_and_unique_ids, test_fail_closed, V1FirstLaw, test_pass, test_fail_no_key, test_fail_uncandidate, test_json_findings_and_llms, V2Religion, test_pass_code_excluded, test_fail, test_configurable, V3Private, setUp, tearDown, test_pass, test_fail, V4Hosts, test_pass, test_fail, V5Links, test_pass, test_fail, V6Contracts, graph, test_graph_pass_fail
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/test_vaccines.py:1-311 · blob f20d2c9af98344b9115b76fd3c82de49d899c2fb · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, storage · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
"""Self-test for vaccines.py, CVAA-style: every antibody must stay quiet on a healthy fixture and fire on a
diseased one.  python -m unittest tools/explore/verify/test_vaccines.py"""
import hashlib
import json
import os
import shutil
import sys
import tempfile
import unittest

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import vaccines as V  # noqa: E402

KEY = 'gridatlas@' + 'a' * 40 + ' atlas/x.js:1-10'
HEAD = '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>T</title></head><body>'
END = '</body></html>'


def run_one(vid, files, **kw):
    d = tempfile.mkdtemp(prefix='vk8-test-')
    try:
        for rel, body in files.items():
            p = os.path.join(d, rel)
            os.makedirs(os.path.dirname(p), exist_ok=True)
            with open(p, 'wb') as fh:
                fh.write(body if isinstance(body, bytes) else body.encode())
        o = V.Output(d, **kw)
        v = next(x for x in V.VACCINES if x['id'] == vid)
        return v['antibody'](o), o
    finally:
        shutil.rmtree(d, ignore_errors=True)


def page(body):
    return HEAD + body + END


def chess_board():
    sq = V._board_squares()
    pieces = []
    for s, (side, typ) in sorted(sq.items()):
        pieces.append({'id': '%s-%s-%s' % (side[0], typ, s), 'side': side, 'type': typ, 'square': s, 'community': 1,
                       'label': 'x', 'size': 1, 'lines': 1, 'repos': ['r'], 'role': 'other', 'centrality': 0.5,
                       'reach': 0.5, 'unique': 0.5, 'files': [1], 'why': 'rule'})
    return {'schema': 'explore-chess-board-v1', 'cut': 'c', 'rules_version': 'chess-rules-v1',
            'sides': {'white': 'a', 'black': 'b'}, 'pieces': pieces}


def chess_games(to='e4'):
    players = [{'id': 'w%d' % i, 'side': 'white', 'name': 'W', 'strategy': 's'} for i in range(5)] + \
              [{'id': 'b%d' % i, 'side': 'black', 'name': 'B', 'strategy': 's'} for i in range(5)]
    moves = [{'ply': 1, 'piece': 'w-pawn-e2', 'from': 'e2', 'to': to, 'capture': None, 'check': False, 'note': 'n'}]
    return {'schema': 'explore-chess-games-v1', 'players': players,
            'games': [{'white': 'w0', 'black': 'b0', 'seed': 1, 'result': '1/2-1/2', 'moves': moves}],
            'table': [{'player': 'w0', 'played': 1, 'won': 0, 'drawn': 1, 'lost': 0},
                      {'player': 'b0', 'played': 1, 'won': 0, 'drawn': 1, 'lost': 0}]}


class Registry(unittest.TestCase):
    def test_five_sections_and_unique_ids(self):
        ids = [v['id'] for v in V.VACCINES]
        self.assertEqual(len(ids), len(set(ids)))
        self.assertEqual(len(ids), 11)
        for v in V.VACCINES:
            for k in ('disease', 'symptom', 'dose', 'provenance'):
                self.assertTrue(v[k].strip(), (v['id'], k))

    def test_fail_closed(self):
        o = V.Output(tempfile.mkdtemp())
        V.VACCINES.append({'id': 'VX', 'name': 'crash', 'disease': '', 'symptom': '', 'dose': '', 'provenance': '',
                           'antibody': lambda o: 1 / 0})
        try:
            r = V.run_output(o, ['VX'])
            self.assertEqual(r['VX']['status'], 'FAIL')
            self.assertIn('CRASHED', r['VX']['findings'][0])
        finally:
            V.VACCINES.pop()


class V1FirstLaw(unittest.TestCase):
    def test_pass(self):
        f, _ = run_one('V1', {'p.html': page('<section class="file" id="f1">Haversine. Evidence %s</section>'
                                             '<div class="card">duplicate of file 3 (CANDIDATE for review) blob %s</div>'
                                             % (KEY, 'b' * 40))})
        self.assertEqual(f, [])

    def test_fail_no_key(self):
        f, _ = run_one('V1', {'p.html': page('<section class="file" id="f1">Haversine distance</section>')})
        self.assertTrue(any('shows no key' in x for x in f))

    def test_fail_uncandidate(self):
        f, _ = run_one('V1', {'p.html': page('<div class="card">%s this is dead code, safe to delete</div>' % KEY)})
        self.assertTrue(any('without CANDIDATE' in x for x in f))

    def test_json_findings_and_llms(self):
        f, _ = run_one('V1', {'m.metrics.json': json.dumps({'findings': ['family 1: canonical file 12 x/y.js']}),
                              'llms-x.txt': '# x\n\n### A\nno source here\n'})
        self.assertEqual(len(f), 2)
        f, _ = run_one('V1', {'m.metrics.json': json.dumps({'findings': ['canonical file 12 r@abcdef1234:x/y.js']}),
                              'llms-x.txt': '# x\n\n### A\nSource: https://github.com/V/r/blob/%s/a.py#L1-L9\n' % ('c' * 40)})
        self.assertEqual(f, [])


class V2Religion(unittest.TestCase):
    def test_pass_code_excluded(self):
        f, _ = run_one('V2', {'p.html': page('<p>Cable derating.</p><pre><code>// holy cow</code></pre>')})
        self.assertEqual(f, [])

    def test_fail(self):
        f, _ = run_one('V2', {'p.html': page('<p>A sacred engine.</p>'), 'x.json': json.dumps({'title': 'Temple map'})})
        self.assertEqual({x.split('"')[1] for x in f}, {'sacred', 'temple'})

    def test_configurable(self):
        f, _ = run_one('V2', {'p.html': page('<p>A sacred engine with widgets.</p>')}, words=['widgets'])
        self.assertEqual(len(f), 1)
        self.assertIn('widgets', f[0])


class V3Private(unittest.TestCase):
    def setUp(self):
        sys.path.insert(0, V.KUIPER_TOOLS)
        import check_proof
        self.cp = check_proof
        self.dig = hashlib.sha256(b'zz-test-private-zz').hexdigest()[:24]
        check_proof.NOT_PUBLIC.add(self.dig)

    def tearDown(self):
        self.cp.NOT_PUBLIC.discard(self.dig)

    def test_pass(self):
        f, _ = run_one('V3', {'p.html': page('<p>gridatlas</p>')})
        self.assertEqual(f, [])

    def test_fail(self):
        f, _ = run_one('V3', {'p.html': page('<p>see zz-test-private-zz/readme</p>')})
        self.assertEqual(len(f), 1)
        self.assertNotIn('zz-test-private-zz', f[0])  # the guard does not spell what it guards


class V4Hosts(unittest.TestCase):
    def test_pass(self):
        f, _ = run_one('V4', {'search.html': page('<a href="https://github.com/x">src</a><script type="module">'
                                                  'const M = await import("https://cdn.jsdelivr.net/npm/@duckdb/duckdb-wasm@1/+esm");'
                                                  '</script>')})
        self.assertEqual(f, [])

    def test_fail(self):
        f, _ = run_one('V4', {'p.html': page('<script src="https://unpkg.com/leaflet.js"></script>'
                                             '<link rel="stylesheet" href="https://fonts.googleapis.com/x.css">'
                                             '<script>fetch("https://cdn.jsdelivr.net/npm/lodash")</script>')})
        hosts = {x.split(' ')[0] for x in f}
        self.assertEqual(hosts, {'unpkg.com', 'fonts.googleapis.com', 'cdn.jsdelivr.net'})


class V5Links(unittest.TestCase):
    def test_pass(self):
        f, _ = run_one('V5', {'a.html': page('<a href="b.html#x">b</a><a href="#top">t</a><a href="d/">d</a>'),
                              'b.html': page('<h2 id="x">x</h2>'), 'd/index.html': page('')})
        self.assertEqual(f, [])

    def test_fail(self):
        f, _ = run_one('V5', {'a.html': page('<a href="b.html#nope">b</a><a href="gone.html">g</a>'),
                              'b.html': page('<h2 id="x">x</h2>')})
        self.assertEqual(len(f), 2)


class V6Contracts(unittest.TestCase):
    def graph(self):
        fl = {'id': 0, 'repo': 'r', 'path': 'a.py', 'folder_hierarchy': ['r'], 'lang': 'Python', 'lines': 3, 'section': 1,
              'block': 1, 'title': 'A', 'achieves': '', 'why': '', 'context': '', 'essay_status': 'auto', 'stage': 'unknown',
              'imports': [], 'imports_external': [], 'dependents': [], 'defines': [], 'pure': True, 'role': 'other',
              'pattern': '', 'entry': False, 'reachable': False, 'canonical_status': 'unreached_review',
              'domain_stage': 'unknown', 'commercial_user': [], 'data_contracts': {}, 'four_part': {}, 'signatures': [],
              'edge_kinds': []}
        return {'schema': 'explore-build-graph-v1', 'cut': 'c', 'base': 'b', 'topics': [],
                'repos': [{'repo': 'r', 'commit': 'a' * 40, 'license': 'MIT', 'citation': False, 'readme_summary': ''}],
                'sections': [{'section': 1, 'url': 's/1.html', 'topic': 't', 'repos': ['r'], 'lines': 3, 'title': 'S'}],
                'files': [fl], 'edges': [], 'roles': [{'id': 'other', 'title': 'O', 'colour': '#a6adbb'}]}

    def test_graph_pass_fail(self):
        f, _ = run_one('V6', {'build_graph.json': json.dumps(self.graph())})
        self.assertEqual(f, [])
        g = self.graph()
        g['files'][0]['role'] = 'magic'
        g['files'][0]['imports'] = [9]
        f, _ = run_one('V6', {'build_graph.json': json.dumps(g)})
        self.assertTrue(any('role' in x for x in f) and any('outside 0..n-1' in x for x in f))

    def test_chess_pass_fail(self):
        f, _ = run_one('V6', {'board.json': json.dumps(chess_board()), 'games.json': json.dumps(chess_games())})
        self.assertEqual([x for x in f if 'INCONCLUSIVE' not in x], [])
        b = chess_board()
        b['pieces'][0]['square'] = 'e5'
        f, _ = run_one('V6', {'board.json': json.dumps(b), 'games.json': json.dumps(chess_games('e5'))})
        self.assertTrue(any('starting square' in x for x in f))
        try:
            sys.path.append(V.PYLIB)
            import chess  # noqa
            self.assertTrue(any('illegal' in x for x in f))
        except ImportError:
            pass

    def test_lab_metrics(self):
        ov = json.dumps({'schema': 'explore-lab-overlay-v1', 'exp': 'x', 'rules': 'r', 'cut': 'c', 'n': 2,
                         'state': 'measurement', 'key': 'k', 'cols': {'a': [1, 2]}})
        good = {'exp': 'x', 'rules': 'r', 'hypothesis': 'h', 'algorithm': 'a', 'cut': 'c', 'deterministic': True,
                'overlay_sha256': hashlib.sha256(ov.encode()).hexdigest(), 'verdict': 'v'}
        f, _ = run_one('V6', {'x.json': ov, 'x.metrics.json': json.dumps(good)})
        self.assertEqual(f, [])
        bad = dict(good, overlay_sha256='0' * 64)
        f, _ = run_one('V6', {'x.json': ov.replace('[1, 2]', '[1]'), 'x.metrics.json': json.dumps(bad)})
        self.assertTrue(any('length' in x for x in f) and any('hashes to' in x for x in f))


class V7Determinism(unittest.TestCase):
    def test_recorded_hash(self):
        ov = '{"a":1}'
        m = {'deterministic': True, 'overlay_sha256': hashlib.sha256(ov.encode()).hexdigest()}
        f, _ = run_one('V7', {'x.json': ov, 'x.metrics.json': json.dumps(m)})
        self.assertEqual(f, [])
        f, _ = run_one('V7', {'x.json': ov, 'x.metrics.json': json.dumps(dict(m, deterministic=False))})
        self.assertEqual(len(f), 1)
        f, _ = run_one('V7', {'x.json': '{"a":2}', 'x.metrics.json': json.dumps(m)})
        self.assertEqual(len(f), 1)

    def test_digest_compare(self):
        out = []
        V._cmp_digest({'a': '1', 'b': '2'}, {'a': '1', 'b': '3'}, 'L', out)
        self.assertEqual(out, ['L: b differs (bytes)'])


class V8A11y(unittest.TestCase):
    def test_pass(self):
        f, _ = run_one('V8', {'p.html': page('<img src="x.png" alt=""><label>Q <input id="q"></label>'
                                             '<button aria-label="Close"></button><a href="x.html">x</a>')})
        self.assertEqual(f, [])

    def test_fail(self):
        f, _ = run_one('V8', {'p.html': '<html><head><title></title></head><body><img src="x.png"><input id="q" '
                                        'placeholder="search"><button></button><a href="x.html"></a></body></html>'})
        kinds = {x.split(':')[0] for x in f}
        self.assertEqual(kinds, {'no <html lang>', 'empty or missing <title>', '<img> without alt',
                                 '<input> with no accessible name', '<button> with no accessible name',
                                 '<a> with no accessible name'})


class V9Contrast(unittest.TestCase):
    def test_pass(self):
        f, _ = run_one('V9', {'s.css': 'body{background:#000;color:#fff}a{color:#66ccff}.badge{color:#000}'
                                       '.badge.r-x{background:#00ffff}', 'p.html': page('')})
        self.assertEqual(f, [])

    def test_fail(self):
        f, _ = run_one('V9', {'s.css': 'body{background:#000;color:#fff}.dim{color:#333}.badge{color:#000}'
                                       '.badge.r-o{background:#4c5a65}', 'p.html': page('')})
        self.assertEqual(len(f), 2)

    def test_ratio(self):
        self.assertAlmostEqual(V.contrast((0, 0, 0, 1), (255, 255, 255, 1)), 21.0, places=3)


class V10Mobile(unittest.TestCase):
    def setUp(self):
        try:
            import playwright  # noqa
        except ImportError:
            self.skipTest('playwright not installed')

    def test_pass(self):
        f, o = run_one('V10', {'index.html': page('<style>body{margin:0;font-size:16px}a{display:inline-block;'
                                                  'min-height:44px;min-width:44px;padding:10px}</style><nav><a href="#">Home</a></nav>'
                                                  '<p>Read <a href="#">this</a> in a sentence.</p>')})
        self.assertEqual(f, [], o.notes)

    def test_fail(self):
        f, _ = run_one('V10', {'index.html': page('<div style="width:900px">wide</div><button>x</button>'
                                                  '<script>console.error("boom")</script>')})
        joined = ' '.join(f)
        self.assertIn('horizontal scroll', joined)
        self.assertIn('tap targets', joined)
        self.assertIn('console errors', joined)


class V11Clean(unittest.TestCase):
    K = 'r@' + 'a' * 40 + ' a.py:1-3 ' + 'b' * 40

    def doc(self, **rec):
        r = {'file_id': 0, 'key': self.K, 'category': 'noise-minified', 'reason': 'Minified: one line of 9,000 characters.',
             'evidence': ['avg line length 9000'], 'confidence': 0.9, 'proposer': 'noise.py'}
        r.update(rec)
        return json.dumps({'schema': 'clean-proposals-v1', 'graph_cut': 'c', 'proposals': [r]})

    def graph(self, reachable):
        return json.dumps({'schema': 'explore-build-graph-v1', 'cut': 'c', 'files': [{'id': 0, 'reachable': reachable}]})

    def test_pass(self):
        f, _ = run_one('V11', {'p.json': self.doc(), 'build_graph.json': self.graph(True)})
        self.assertEqual(f, [])

    def test_fail(self):
        f, _ = run_one('V11', {'p.json': self.doc(key='a.py', evidence=[], reason='delete it', category='junk'),
                               'build_graph.json': self.graph(True)})
        j = ' '.join(f)
        for s in ('key missing', 'no evidence', 'outside the contract', 'never delete', 'reachable'):
            self.assertIn(s, j)


if __name__ == '__main__':
    unittest.main()