GLOBALGRID2050 / EXPLORE CODE

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

Test Repokuiper Overlays and 3 more files

A test in the explore folder of Cosmic that checks Build and Kuiper Overlays, using SHA-256.

511 lines of Python from cosmic, in 4 files. Topic: Kuiper, cosmos and drawing engines. Section 1135 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. Test Repokuiper Nav test · cosmic / tools/explore/repokuiper/test_repokuiper_nav.py lines 1–113
  2. Test Repokuiper Overlays test · cosmic / tools/explore/repokuiper/test_repokuiper_overlays.py lines 1–151
  3. Test Repokuiper Speed test · cosmic / tools/explore/repokuiper/test_repokuiper_speed.py lines 1–138
  4. Verify Playwright render · cosmic / tools/explore/repokuiper/verify_playwright.py lines 1–109

Test Repokuiper Nav

A test in the explore folder of Cosmic that checks Build. It is built from the read step (`read`).

testcosmic / tools/explore/repokuiper/test_repokuiper_nav.py · lines 1–113 of 113 · Not reached from any entry point (candidate for review) · pattern test_registers_as_plugin_and_no_network (shared by 2 files)

What it does
It tests its inputs. Defines 9 functions or classes, including read, test_files_exist, test_registers_as_plugin_and_no_network, test_css_palette_only, test_css_does_not_restyle_core_ids. Uses libraries json, os, re, shutil, subprocess. Side effects: reads or writes files; makes network requests; starts processes.
Why it exists in the grid workflow
Domain stage field_execution (path word 'nav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Inputs & outputs
In: command-line arguments.
What it achieves
Tests for the K2 navigation module (`repokuiper-nav.js` / .CSS).
Why it matters
Guards the behaviour of Build.
Application
cosmic · tools/explore/repokuiper · test
Uses
Build (script call), json, os, re, shutil, subprocess, pytest
Used by
none found
Produces
read, test_files_exist, test_registers_as_plugin_and_no_network, test_css_palette_only, test_css_does_not_restyle_core_ids, test_tap_targets_44px, test_input_keys_do_not_reach_core, test_reduced_motion_respected, test_pure_helpers_under_node
Defines here
read, test_files_exist, test_registers_as_plugin_and_no_network, test_css_palette_only, test_css_does_not_restyle_core_ids, test_tap_targets_44px, test_input_keys_do_not_reach_core, test_reduced_motion_respected, test_pure_helpers_under_node
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/repokuiper/test_repokuiper_nav.py:1-113 · blob 65e947acb45ce5ab26d21cce9937c8e40beb634c · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, network, process · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unreached_review
"""Tests for the K2 navigation module (repokuiper-nav.js / .css). No network.

Static rules (palette, no CDN, scoped CSS, 44px taps, plugin registration) always run; the pure helpers
(hash parsing, ranking, common ancestor) run under node when it is installed."""
import json
import os
import re
import shutil
import subprocess

import pytest

HERE = os.path.dirname(os.path.abspath(__file__))
JS = os.path.join(HERE, "repokuiper-nav.js")
CSS = os.path.join(HERE, "repokuiper-nav.css")
PALETTE = {"#000", "#0b0e14", "#2f343d", "#fff", "#a6adbb", "#66ccff", "#00ffff"}
CORE_IDS = ["sky", "hud", "line1", "line2", "crumb", "tools", "card", "find", "q", "list", "help", "err"]


def read(p):
    with open(p, encoding="utf-8") as f:
        return f.read()


def test_files_exist():
    assert os.path.isfile(JS) and os.path.isfile(CSS)


def test_registers_as_plugin_and_no_network():
    s = read(JS)
    assert "KUIPER.use('nav'" in s
    assert not re.search(r"https?://", s), "no absolute URLs (no CDN, no network)"
    assert "fetch(" not in s, "nav loads no data"
    assert "eval(" not in s and "innerHTML = location" not in s


def test_css_palette_only():
    s = re.sub(r"/\*.*?\*/", "", read(CSS), flags=re.S)
    cols = {c.lower() for c in re.findall(r"#[0-9a-fA-F]{3,8}\b", s)}
    # #000c etc. are palette black with alpha
    base = {c[:4] if len(c) == 5 else c for c in cols}
    assert base <= PALETTE, base - PALETTE


def test_css_does_not_restyle_core_ids():
    s = re.sub(r"/\*.*?\*/", "", read(CSS), flags=re.S)
    for sel in re.findall(r"([^{}]+)\{", s):
        if sel.strip().startswith("@"):
            continue
        for cid in CORE_IDS:
            assert not re.search(r"#%s(?![\w-])" % re.escape(cid), sel), (cid, sel)
        for part in sel.split(","):
            part = part.strip()
            assert part.startswith(("#kp-nav-", ".nav-")), part


def test_tap_targets_44px():
    s = read(CSS)
    assert re.search(r"\.nav-btn\{[^}]*min-height:44px", s)
    assert re.search(r"\.nav-list li\{[^}]*min-height:44px", s)
    assert "font-size:16px" in s  # search input: no iOS zoom-on-focus


def test_input_keys_do_not_reach_core():
    s = read(JS)
    assert "e.stopPropagation();" in s.split("qEl.addEventListener('keydown'")[1][:200]


def test_reduced_motion_respected():
    s = read(JS)
    assert "K.reducedMotion" in s and "reduced()" in s


NODE = shutil.which("node")


@pytest.mark.skipif(not NODE, reason="node not installed")
def test_pure_helpers_under_node():
    prog = r"""
const n = require(process.argv[1]);
const out = {};
out.h1 = n.parseHash('#file=src/a%20b/c.js&fn=run');
out.h2 = n.parseHash('#folder=docs');
out.h3 = n.parseHash('#bad=%E0%A4%A&file=x');
out.m1 = n.makeHash('file', 'src/a b/c.js', 'run');
out.m2 = n.makeHash('folder', '');
out.round = n.parseHash(n.makeHash('file', 'a/b c#d.js')).file;
const L = (s) => s.toLowerCase();
out.s_exact = n.score('build.py', 'tools/build.py', 'build.py');
out.s_prefix = n.score('build.py', 'tools/build.py', 'bui');
out.s_sub = n.score('rebuild.py', 'tools/rebuild.py', 'build');
out.s_path = n.score('x.py', 'build/x.py', 'build');
out.s_fuzzy = n.score('repokuiper.js', 'tools/repokuiper.js', 'rkjs');
out.s_none = n.score('a.py', 'b/a.py', 'zzz');
// folders: 0 root, 1 a (0), 2 b (1), 3 c (1), 4 d (0)
const fpar = [-1, 0, 1, 1, 0], fdepth = [0, 1, 2, 2, 1];
out.ca1 = n.commonAncestor(2, 3, fpar, fdepth);
out.ca2 = n.commonAncestor(2, 4, fpar, fdepth);
out.ca3 = n.commonAncestor(2, 1, fpar, fdepth);
console.log(JSON.stringify(out));
"""
    r = subprocess.run([NODE, "-e", prog, JS], capture_output=True, text=True, timeout=30)
    assert r.returncode == 0, r.stderr
    o = json.loads(r.stdout)
    assert o["h1"] == {"file": "src/a b/c.js", "fn": "run"}
    assert o["h2"] == {"folder": "docs"}
    assert o["h3"] == {"file": "x"}
    assert o["m1"] == "#file=src/a%20b/c.js&fn=run"
    assert o["m2"] == ""
    assert o["round"] == "a/b c#d.js"
    assert o["s_exact"] > o["s_prefix"] > o["s_sub"] > o["s_path"] > o["s_fuzzy"] > 0
    assert o["s_none"] == -1
    assert (o["ca1"], o["ca2"], o["ca3"]) == (1, 0, 1)

Test Repokuiper Overlays

A test in the explore folder of Cosmic that checks Build and Kuiper Overlays, using SHA-256.

testcosmic / tools/explore/repokuiper/test_repokuiper_overlays.py · lines 1–151 of 151 · Not reached from any entry point (candidate for review) · pattern test_real_site_budget (shared by 2 files)

What it does
It tests its inputs. Defines 9 functions or classes, including graph, site, run, test_modes_line_up_with_bodies, test_other_cut_hides_modes. Uses libraries json, os, sys, subprocess, pytest. Side effects: reads or writes files; starts processes.
Inputs & outputs
In: JSON file index.json; JSON file alpha.overlays.json; JSON file alpha.ov-community.json; JSON file alpha.ov-drift.json; JSON file alpha.ov-identity.json; JSON file alpha.ov-words.json; JSON file index.overlays.json; JSON file keys.json. Out: JSON file keys.json; JSON file communities.json; JSON file drift.json; JSON file clarity.json; JSON file identity-files.json; JSON file dictionary.json.
What it achieves
It is built from the graph step (`graph`), the site step (`site`) and the run step (`run`). Tests for `kuiper_overlays.py` (K3 overlays build hook). pytest, no network. It reads `index.json`.
Why it matters
Guards the behaviour of Build and Kuiper Overlays.
Application
cosmic · tools/explore/repokuiper · test
Uses
Build (import), Kuiper Overlays (import), json, os, sys, subprocess, pytest
Used by
none found
Produces
graph, site, run, test_modes_line_up_with_bodies, test_other_cut_hides_modes, test_missing_sources_hide_modes, test_photon_rule_and_real_names_kept, test_vedic_ids_from_dictionary_at_graph_commit, test_real_site_budget
Defines here
graph, site, run, test_modes_line_up_with_bodies, test_other_cut_hides_modes, test_missing_sources_hide_modes, test_photon_rule_and_real_names_kept, test_vedic_ids_from_dictionary_at_graph_commit, test_real_site_budget
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/repokuiper/test_repokuiper_overlays.py:1-151 · blob cc37fb3fb69470e180475beacc3278216ff7158a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: unreached_review
"""Tests for kuiper_overlays.py (K3 overlays build hook). pytest, no network."""
import json
import os
import sys

import subprocess

import pytest

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import build as kb  # noqa: E402
import kuiper_overlays as ko  # noqa: E402

CUT = '2026-12-05T00:00:00+00:00'


def graph():
    files = []
    for repo, paths in (('alpha', ['a/x.js', 'a/y.js', 'b/z.py', 'main.html']), ('beta', ['m.js', 'n/o.js'])):
        for p in paths:
            files.append({'id': len(files), 'repo': repo, 'path': p, 'lines': 10, 'role': 'logic',
                          'reachable': True, 'entry': p == 'main.html', 'signatures': ['def clampValue(x)'],
                          'section': '', 'title': p})
    return {'cut': CUT, 'base': '', 'files': files, 'edges': [[3, 0, 'load'], [0, 1, 'import'], [4, 5, 'import']],
            'repos': [{'repo': 'alpha', 'commit': 'a' * 40}, {'repo': 'beta', 'commit': 'b' * 40}],
            'roles': [{'id': 'logic', 'title': 'Logic', 'colour': '#66ccff'}], 'sections': []}


def site(tmp, g, cut=CUT, vedic=True):
    s = tmp / 'explore-code'
    (s / 'lab').mkdir(parents=True)
    keys = ['%s@%s:%s' % (f['repo'], 'c' * 12, f['path']) for f in g['files']]
    (s / 'lab' / 'keys.json').write_text(json.dumps({'cut': cut, 'k': keys}))
    (s / 'lab' / 'communities.json').write_text(json.dumps({
        'cut': cut, 'n': str(len(keys)), 'rules': 'r', 'cols': {'c': [0, 0, 1, 0, 1, -1]},
        'legend': {'c': ['id', 'label', 'size', 'hub_file'], 'rows': [[0, 'maps', 3, 3], [1, 'data', 2, 2]]}}))
    (s / 'lab' / 'drift.json').write_text(json.dumps({
        'cut': cut, 'n': str(len(keys)), 'rules': 'r', 'cols': {'fam': [0, 0, -1, -1, 0, -1]},
        'edges': [0, 1, 900, 0, 4, 800], 'safe_review': [1]}))
    (s / 'clarity').mkdir()
    (s / 'clarity' / 'clarity.json').write_text(json.dumps({
        'cut': cut, 'categories': ['core', 'copy'], 'titles': {'core': 'Unique', 'copy': 'Copy'},
        'file_category': ['core', 'copy', 'core', 'core', 'copy', 'core']}))
    (s / 'identity').mkdir()
    fl = {}
    for f in g['files']:
        fl[str(f['id'])] = {'verdict': {'verdict': 'near-copy-of' if f['id'] == 1 else 'unique',
                                        'of_file': 0 if f['id'] == 1 else None, 'similarity': 0.9 if f['id'] == 1 else None},
                            'vedic': {'candidates': [{'word': 'CLAMP', 'score': 60}, {'word': 'VALUE', 'score': 50}] if vedic else []}}
    (s / 'identity' / 'identity-files.json').write_text(json.dumps({'graph': {'cut': cut, 'sha256': 'f' * 64}, 'files': fl}))
    return s


def run(tmp, g, s, src=''):
    out = s / 'kuiper'
    per = kb.build(graph=g, out=str(out), src='')
    idx = json.load(open(out / 'index.json'))
    return ko.build({'graph': g, 'per_repo': per, 'index': idx, 'out': str(out), 'site': str(s), 'src': src,
                     'extras_dir': os.path.dirname(HERE), 'slug': kb.slug})


def test_modes_line_up_with_bodies(tmp_path):
    g = graph()
    res = run(tmp_path, g, site(tmp_path, g))
    man = res['alpha.overlays.json']
    assert {'community', 'drift', 'clarity', 'identity', 'words'} <= set(man['modes'])
    for name, m in man['modes'].items():
        d = res['alpha.ov-%s.json' % m['file'][3:]] if 'file' in m else None
        if d:
            assert len(d['v']) == man['n'] == 4
            assert d['key']['source'] and d['key']['cut'] == CUT     # no claim without a key
    # bodies sorted by path: a/x.js(0) a/y.js(1) b/z.py(2) main.html(3)
    com = res['alpha.ov-community.json']
    assert [com['legend'][v][0] for v in com['v']] == ['maps', 'maps', 'data', 'maps']
    assert com['legend'][0][3] == 3                          # hub main.html is body 3 of alpha
    dr = res['alpha.ov-drift.json']
    assert dr['links'] == [[0, 1, 900]] and dr['safe'] == [1] and dr['outside'] == [[0, 'beta', 1]]
    idn = res['alpha.ov-identity.json']
    assert idn['v'][1] == 2 and idn['sim'][1] == 90 and idn['of'] == [[1, '', 0]]
    w = res['alpha.ov-words.json']
    assert [w['dict'][k][0] for k in w['fw'][0]] == ['CLAMP', 'VALUE']
    assert w['title'] == 'VEDIC words'
    assert 'identity' in res['index.overlays.json']['modes']


def test_other_cut_hides_modes(tmp_path):
    g = graph()
    s = site(tmp_path, g, cut='1999-01-01T00:00:00+00:00')
    os.remove(s / 'lab' / 'keys.json')                       # without keys the cut must match
    res = run(tmp_path, g, s)
    assert res['alpha.overlays.json']['modes'] == {}
    assert not [k for k in res if '.ov-' in k]


def test_missing_sources_hide_modes(tmp_path):
    g = graph()
    s = tmp_path / 'explore-code'
    s.mkdir()
    res = run(tmp_path, g, s)
    assert res['beta.overlays.json']['modes'] == {}


def test_photon_rule_and_real_names_kept(tmp_path):
    g = graph()
    s = site(tmp_path, g)
    c = json.load(open(s / 'lab' / 'communities.json'))
    c['legend']['rows'][0][1] = 'shared VEDIC fingerprints'
    (s / 'lab' / 'communities.json').write_text(json.dumps(c))
    res = run(tmp_path, g, s)
    blob = json.dumps(res)
    assert 'shared VEDIC fingerprints' in blob               # real tool names are shown as they are
    assert 'def clampValue' not in blob                      # no code text
    for name, obj in res.items():
        assert len(json.dumps(obj, separators=(',', ':'))) <= 60000, name


def test_vedic_ids_from_dictionary_at_graph_commit(tmp_path):
    src = tmp_path / 'src'
    repo = src / 'vedic-'
    (repo / 'data').mkdir(parents=True)
    (repo / 'data' / 'dictionary.json').write_text(json.dumps({'entries': [
        {'word': 'CLAMP', 'gg_id': 'GG2050-VEDIC-000042'}]}))
    git = ['git', '-C', str(repo), '-c', 'user.email=t@t', '-c', 'user.name=t']
    subprocess.run(['git', 'init', '-q', str(repo)], check=True)
    subprocess.run(git + ['add', '.'], check=True)
    subprocess.run(git + ['commit', '-qm', 'd'], check=True)
    head = subprocess.run(git + ['rev-parse', 'HEAD'], capture_output=True, check=True, text=True).stdout.strip()
    g = graph()
    g['repos'].append({'repo': 'vedic-', 'commit': head})
    res = run(tmp_path, g, site(tmp_path, g), src=str(src))
    w = res['alpha.ov-words.json']
    assert dict(map(tuple, w['dict'])) == {'CLAMP': 'GG2050-VEDIC-000042', 'VALUE': ''}
    assert w['ids_key']['source'] == 'vedic-@%s:data/dictionary.json' % head
    g['repos'][-1]['commit'] = '0' * 40                      # another commit: no ids, words still shown
    res = run(tmp_path / 'b', g, site(tmp_path / 'b', g), src=str(src)) if (tmp_path / 'b').mkdir() is None else None
    assert all(not x[1] for x in res['alpha.ov-words.json']['dict'])


REAL = os.environ.get('KUIPER_SITE', '')


@pytest.mark.skipif(not (REAL and os.path.isdir(os.path.join(REAL, 'kuiper'))), reason='KUIPER_SITE not set')
def test_real_site_budget(tmp_path):
    g = json.load(open(os.path.join(REAL, 'build_graph.json')))
    out = tmp_path / 'kuiper'
    per = kb.build(graph=g, out=str(out), src='')
    res = ko.build({'graph': g, 'per_repo': per, 'index': json.load(open(out / 'index.json')), 'out': str(out),
                    'site': REAL, 'extras_dir': os.path.dirname(HERE), 'slug': kb.slug})
    for name, obj in res.items():
        assert len(json.dumps(obj, separators=(',', ':'), ensure_ascii=False).encode()) <= 60000, name

Test Repokuiper Speed

A test in the explore folder of Cosmic that checks Build and Kuiper API. It is built from the log message helper (`log_message`) and the site step (`site`).

testcosmic / tools/explore/repokuiper/test_repokuiper_speed.py · lines 1–138 of 138 · Not reached from any entry point (candidate for review) · pattern test_registers_as_plugin_and_no_network (shared by 2 files)

What it does
It tests cables. Defines 8 functions or classes, including test_registers_as_plugin_and_no_network, test_css_palette_scoped_and_tap_targets, test_search_ranking_under_node, _serve, Q. Uses libraries functools, http.server, json, os, re. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain terms in the code: cables.
Inputs & outputs
In: JSON file lookup.json; JSON file index.json. Out: browser storage (setItem).
What it achieves
Tests for `repokuiper-speed.js/`.CSS (K5 light speed plugin). pytest, no network. It reads `api/lookup.json`.
Why it matters
Guards the behaviour of Build, Kuiper API and Test Repokuiper API.
Application
cosmic · tools/explore/repokuiper · test
Uses
Build (import), Kuiper API (import), Test Repokuiper API (import), functools, http.server, json, os, re, shutil, subprocess, sys
Used by
none found
Produces
test_registers_as_plugin_and_no_network, test_css_palette_scoped_and_tap_targets, test_search_ranking_under_node, site, test_browser_speed
Defines here
test_registers_as_plugin_and_no_network, test_css_palette_scoped_and_tap_targets, test_search_ranking_under_node, _serve, Q, log_message, site, test_browser_speed
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/repokuiper/test_repokuiper_speed.py:1-138 · blob e28ffc1541ff1090c5b257443e4fcb9674aab316 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, process, storage · domain stage: unknown · users: none · canonical: unreached_review
"""Tests for repokuiper-speed.js/.css (K5 light speed plugin). pytest, no network.

Static rules (plugin registration, no CDN, palette, scoped CSS, 44px taps), the pure search helpers under node, and
(skipped without Playwright/Chromium) a synthetic build with kuiper_api.py served over 127.0.0.1 at 390x844 and
1366x768: palette opens with Ctrl/Cmd+K and the phone button, finds across repositories, a same-repo jump selects the
file, a cross-repo jump lands on the other universe at that file, copy agent link, what-uses-this, no errors, no
sideways scroll.
"""
import functools
import http.server
import json
import os
import re
import shutil
import subprocess
import sys
import threading

import pytest

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import build as kb  # noqa: E402
import kuiper_api as ka  # noqa: E402
import test_repokuiper_api as ta  # noqa: E402

JS = os.path.join(HERE, 'repokuiper-speed.js')
CSS = os.path.join(HERE, 'repokuiper-speed.css')
PALETTE = {'#000', '#0b0e14', '#2f343d', '#fff', '#a6adbb', '#66ccff', '#00ffff'}
NODE = shutil.which('node')


def test_registers_as_plugin_and_no_network():
    js = open(JS, encoding='utf-8').read()
    assert "KUIPER.use('speed'" in js
    assert not re.search(r'<script|^\s*import\s|cdn|unpkg|jsdelivr|https?://', js, re.I | re.M)
    assert "fetch('api/lookup.json')" in js                 # the same static API agents read
    assert 'onFrame' not in js and 'addOverlay' not in js     # nothing per frame


def test_css_palette_scoped_and_tap_targets():
    css = re.sub(r'/\*.*?\*/', '', open(CSS, encoding='utf-8').read(), flags=re.S)
    for c in {c.lower() for c in re.findall(r'#[0-9a-fA-F]{3,8}\b', css)}:
        assert (c[:4] if len(c) in (4, 5) else c[:7]) in PALETTE, c
    for sel in re.findall(r'(^|})\s*([^{}@]+)\{', css):
        for part in sel[1].split(','):
            p = part.strip()
            if p:
                assert p.startswith(('#kp-speed', '.sp-', '#card:not([hidden]) ~ #kp-speed')), p
    assert 'min-height:44px' in css and 'prefers-reduced-motion' in css


@pytest.mark.skipif(not NODE, reason='node not installed')
def test_search_ranking_under_node():
    code = ("const s=require(%r);const L={paths:{a:{'x/cable.js':0,'y/z.html':1},b:{'cable.js':0,'q/runner_template.sh':1}},"
            "vedic:{CLAMP:['a:0']}};const S=s.indexLookup(L);S.L=L;"
            "console.log(JSON.stringify([s.search(S,'cable','b').map(h=>h[1][0]+'/'+h[1][2]),"
            "s.search(S,'clamp','')[0][2],s.search(S,'rnr','')[0][1][2],s.search(S,'b','')[0][1][0],s.handTaps(3)]))" % JS)
    out = json.loads(subprocess.run([NODE, '-e', code], capture_output=True, text=True, check=True).stdout)
    assert out[0][:2] == ['b/cable.js', 'a/x/cable.js']       # this repository first on a tie
    assert out[1] == 'VEDIC CLAMP' and out[2] == 'q/runner_template.sh' and out[3] == 'b' and out[4] == 4


def _serve(folder):
    class Q(http.server.SimpleHTTPRequestHandler):
        def log_message(self, *a):
            pass
    srv = http.server.ThreadingHTTPServer(('127.0.0.1', 0), functools.partial(Q, directory=str(folder)))
    threading.Thread(target=srv.serve_forever, daemon=True).start()
    return srv


@pytest.fixture()
def site(tmp_path):
    g = ta.graph()
    out = tmp_path / 'explore-code' / 'kuiper'
    saved = kb.MODULES
    kb.MODULES = tuple(m for m in saved if m != 'api') + (() if 'speed' in saved else ('speed',))
    try:
        per = kb.build(graph=g, out=str(out), src='')
    finally:
        kb.MODULES = saved
    ka.build({'graph': g, 'per_repo': per, 'index': json.load(open(out / 'index.json')), 'out': str(out), 'slug': kb.slug})
    return tmp_path / 'explore-code'


@pytest.mark.parametrize('size', [(390, 844), (1366, 768)])
def test_browser_speed(site, size):
    sync = pytest.importorskip('playwright.sync_api')
    phone = size[0] < 760
    srv = _serve(site)
    try:
        with sync.sync_playwright() as p:
            try:
                b = p.chromium.launch()
            except Exception as e:  # noqa: BLE001
                pytest.skip(f'no chromium: {e}')
            ctx = b.new_context(viewport={'width': size[0], 'height': size[1]}, has_touch=phone, is_mobile=phone)
            ctx.add_init_script("try { localStorage.setItem('kuiper-nav-hint-v1', '1'); } catch (e) {}")
            pg = ctx.new_page()
            errs = []
            pg.on('pageerror', lambda e: errs.append(str(e)))
            pg.on('console', lambda m: m.type == 'error' and errs.append(m.text))
            base = f'http://127.0.0.1:{srv.server_port}/kuiper/'
            pg.goto(base + 'alpha.html')
            pg.wait_for_function('window.__rkSpeed && window.__rkSpeed.ready', timeout=15000)
            pg.evaluate('__rkSpeed.load()')
            if phone:
                pg.tap('#kb-sp-go')
                assert pg.evaluate("document.getElementById('kb-sp-go').getBoundingClientRect().height") >= 44
            else:
                pg.keyboard.press('Control+k')
            assert pg.evaluate("!document.getElementById('kp-speed').hidden")
            pg.keyboard.type('z.py')
            pg.wait_for_selector('#kp-speed .sp-list li')
            pg.keyboard.press('Enter')
            pg.wait_for_function("__rk.sel >= 0 && KUIPER.bodyPath(__rk.sel) === 'b/z.py'", timeout=5000)
            pg.click('#card [data-sp=copy]')
            txt = pg.evaluate('__rkSpeed.lastCopied')
            assert '/kuiper/alpha.html#file=b/z.py' in txt and 'key alpha@' in txt and 'id alpha:2' in txt
            pg.evaluate("__rkSpeed.goFile('alpha', 0, 'a/x.js')")
            pg.wait_for_function("__rk.sel === 0", timeout=5000)
            pg.click('#card [data-sp=uses]')
            pg.wait_for_function("document.querySelectorAll('#kp-speed-uses .sp-list li').length === 2", timeout=5000)
            assert pg.evaluate('document.documentElement.scrollWidth') <= size[0]
            pg.click('#kp-speed-uses li[data-sp-use="beta:1"]')                # across repositories
            pg.wait_for_function("location.pathname.endsWith('beta.html') && window.__rk && __rk.sel >= 0", timeout=10000)
            assert pg.evaluate('KUIPER.bodyPath(__rk.sel)') == 'n/o.js'
            assert len(pg.evaluate('__rkSpeed.trail')) >= 2
            pg.goto(base + 'index.html')
            pg.wait_for_function('window.__rkSpeed && window.__rkSpeed.ready', timeout=15000)
            pg.evaluate('__rkSpeed.load()')
            assert pg.evaluate("__rkSpeed.find('o.js')[0]") == ['beta', 1, 'n/o.js']
            assert pg.evaluate('document.documentElement.scrollWidth') <= size[0]
            assert not errs, errs
            b.close()
    finally:
        srv.shutdown()

Verify Playwright

A Python command-line tool in the repokuiper folder of Cosmic. It is built from the serve step (`serve`), the quiet class (`Quiet`) and the log message helper (`log_message`).

rendercosmic / tools/explore/repokuiper/verify_playwright.py · lines 1–109 of 109 · Entry point · pattern serve (shared by 8 files)

What it does
It loads data. Defines serve, Quiet, log_message, main. Uses libraries argparse, functools, http.server, json, os. Side effects: changes the web page (DOM); reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
Inputs & outputs
In: command-line arguments. Out: browser storage (setItem).
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Headless Chromium check of the repokuiper pages at four screen sizes. It accepts `--out` and `--shots`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
cosmic · tools/explore/repokuiper · Python CLI
Uses
Build (import), argparse, functools, http.server, json, os, sys, threading, playwright.sync_api
Used by
none found
Produces
serve, main
Defines here
serve, Quiet, log_message, 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/repokuiper/verify_playwright.py:1-109 · blob 4fb6fac580dc1fa08f50b1b813bae899bd6f7c9f · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process, storage · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
"""Headless Chromium check of the repokuiper pages at four screen sizes.

Serves the output folder over http, opens each page, and records: console errors, frame timing
(draw cost and frame interval over a frame loop), JS layout vs build.py layout parity, a screenshot,
and on the phone a tapped body's card. Prints one JSON report; exit 1 on any failure.

    python3 verify_playwright.py [--out /tmp/vk/3/kuiper] [--shots /tmp/vk/3/shots] repo ...
"""
import argparse
import functools
import http.server
import json
import os
import sys
import threading

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import build  # noqa: E402

from playwright.sync_api import sync_playwright  # noqa: E402

ALL_SIZES = [("phone", 390, 844, True), ("tablet", 820, 1180, True), ("laptop", 1366, 768, False), ("desktop", 1920, 1080, False)]
SIZES = [s for s in ALL_SIZES if s[0] in ("phone", "laptop")] if os.environ.get("RK_ALL_SIZES") != "1" else ALL_SIZES


def serve(folder):
    class Quiet(http.server.SimpleHTTPRequestHandler):
        def log_message(self, *a):
            pass
    h = functools.partial(Quiet, directory=folder)
    srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), h)
    threading.Thread(target=srv.serve_forever, daemon=True).start()
    return srv


def main(argv=None):
    ap = argparse.ArgumentParser()
    ap.add_argument("--out", default=build.DEFAULT_OUT)
    ap.add_argument("--shots", default="/tmp/vk/3/shots")
    ap.add_argument("repos", nargs="*", default=["index", "gridatlas", "satnav", "ventus-grid-engine", "law", "globalgrid2050"])
    a = ap.parse_args(argv)
    os.makedirs(a.shots, exist_ok=True)
    srv = serve(a.out)
    url = f"http://127.0.0.1:{srv.server_address[1]}/"
    report, ok = [], True
    with sync_playwright() as p:
        br = p.chromium.launch()
        for name, w, h, touch in SIZES:
            ctx = br.new_context(viewport={"width": w, "height": h}, device_scale_factor=2 if touch else 1,
                                 has_touch=touch, is_mobile=touch)
            ctx.add_init_script("try { localStorage.setItem('kuiper-nav-hint-v1', '1'); } catch (e) {}")  # returning visitor
            for repo in a.repos:
                page = ctx.new_page()
                errors = []
                # a 404 for a sibling site section (../seethrough/, ../pilot/: present on the live site, optional links)
                # is not an error of this page; a 404 for a Kuiper file beside the page is
                page.on("console", lambda m, e=errors: m.type == "error" and not m.text.startswith("Failed to load resource") and e.append(m.text))
                page.on("response", lambda r, e=errors: r.status >= 400 and "/" not in r.url.split("/", 3)[3] and e.append(f"{r.status} {r.url}"))
                page.on("pageerror", lambda x, e=errors: e.append(str(x)))
                page.goto(url + build.slug(repo) + ".html")
                page.wait_for_function("window.__rk && window.__rk.ready", timeout=15000)
                page.wait_for_timeout(1500)  # a frame loop of ~90 frames
                stats = page.evaluate("__rk.stats()")
                bench = page.evaluate("__rk.bench(120)")
                rec = {"size": name, "repo": repo, "errors": errors, "raf_dt_mean": round(stats["dt_mean"], 1),
                       "draw_ms_mean": round(bench["mean"], 2), "draw_ms_p50": round(bench["p50"], 2), "draw_ms_p95": round(bench["p95"], 2),
                       "sideways": page.evaluate("document.documentElement.scrollWidth > innerWidth + 1"),
                       "kuiper_api": page.evaluate("!!(window.KUIPER && KUIPER.ready && KUIPER.version === 1)"),
                       "modules": page.evaluate("[...document.scripts].map(s => s.getAttribute('src')).filter(s => s && s.startsWith('repokuiper-'))"),
                       "lod": page.evaluate("__rk.lod()")}
                if repo != "index":
                    d = json.load(open(os.path.join(a.out, build.slug(repo) + ".json")))
                    fx, files = build.layout(d["folders"], d["files"], d["band"])
                    js = page.evaluate("__rk.layout0()")
                    rec["layout_max_diff"] = max([abs(x - y) for p1, p2 in zip(files, js["files"]) for x, y in zip(p1, p2)] or [0])
                page.screenshot(path=os.path.join(a.shots, f"{build.slug(repo)}-{name}.png"))
                if name == "phone" or repo == "gridatlas":
                    page.evaluate("__rk.pause(true)")
                    vis = page.evaluate("__rk.visible()")
                    if vis:
                        i = max(vis, key=lambda v: v[1])[0]
                        x, y = page.evaluate(f"__rk.screenOf({i})")
                        if touch:
                            page.touchscreen.tap(x, y)
                        else:
                            page.mouse.click(x, y)
                        page.wait_for_timeout(300)
                        rec["tapped"] = i
                        rec["card_open"] = page.evaluate("!document.getElementById('card').hidden && __rk.sel >= 0")
                        page.screenshot(path=os.path.join(a.shots, f"{build.slug(repo)}-{name}-card.png"))
                    else:
                        rec["card_open"] = False
                fail = bool(errors) or rec["sideways"] or not rec["kuiper_api"] or rec["draw_ms_p50"] > 16 or rec.get("layout_max_diff", 0) > 1e-9 or rec.get("card_open") is False
                rec["PASS"] = not fail
                ok &= not fail
                report.append(rec)
                page.close()
            ctx.close()
        br.close()
    srv.shutdown()
    for r in report:
        print(json.dumps(r))
    print("ALL PASS" if ok else "FAILURES")
    return 0 if ok else 1


if __name__ == "__main__":
    sys.exit(main())