In this section
- Test No Tmp test · cosmic / tools/explore/repokuiper/test_no_tmp.py lines 1–60
- Test Repokuiper test · cosmic / tools/explore/repokuiper/test_repokuiper.py lines 1–231
- Test Repokuiper API test · cosmic / tools/explore/repokuiper/test_repokuiper_api.py lines 1–153
- Test Repokuiper Galaxy test · cosmic / tools/explore/repokuiper/test_repokuiper_galaxy.py lines 1–195
Test No Tmp
A test in the repokuiper folder of Cosmic that checks Build. It is built from the tiny graph helper (`tiny_graph`).
testcosmic / tools/explore/repokuiper/test_no_tmp.py · lines 1–60 of 60 · Not reached from any entry point (candidate for review) · pattern test_source_has_no_host_paths (shared by 2 files)
- What it does
- It tests its inputs. Defines tiny_graph, test_source_has_no_host_paths, test_runs_from_env_only_and_copies_no_code, test_missing_graph_is_a_clear_error. Uses libraries json, os, re, subprocess, sys. Side effects: reads or writes files; starts processes.
- Inputs & outputs
- In: JSON file build_graph.json; JSON file demo.json. Out: JSON file.
- What it achieves
- CI check: `repokuiper/build.py` runs on a clean machine with only `build_graph.json` (no /tmp inputs, no clones).
- Why it matters
- Guards the behaviour of Build.
- Application
- cosmic · tools/explore/repokuiper · test
- Uses
- Build (import), json, os, re, subprocess, sys, tempfile
- Used by
- none found
- Produces
- tiny_graph, test_source_has_no_host_paths, test_runs_from_env_only_and_copies_no_code, test_missing_graph_is_a_clear_error
- Defines here
- tiny_graph, test_source_has_no_host_paths, test_runs_from_env_only_and_copies_no_code, test_missing_graph_is_a_clear_error
- 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_no_tmp.py:1-60 · blob 1382f88bdb9efaf45adde7880a5699936926a811 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: unreached_review
"""CI check: repokuiper/build.py runs on a clean machine with only build_graph.json (no /tmp inputs, no clones).
python -m pytest tools/explore/repokuiper/test_no_tmp.py -q
"""
import json
import os
import re
import subprocess
import sys
import tempfile
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import build # noqa: E402
def tiny_graph():
files = [{"id": i, "repo": "demo", "path": "src/f%d.js" % i, "lines": 10 + i, "role": "render",
"reachable": i % 2 == 0, "entry": i == 0, "section": 1, "title": "F%d" % i,
"synopsis": "Draws maps. " + "x" * 400, "signatures": ["export function draw%d(a, b) {" % i]}
for i in range(6)]
return {"schema": "explore-build-graph-v1", "cut": "ci", "files": files,
"edges": [[i, 0, "import"] for i in range(1, 6)],
"repos": [{"repo": "demo", "commit": "0" * 40, "visibility": "public"}],
"roles": [{"id": "render", "title": "Render", "colour": "#ff6666"}],
"sections": [{"section": 1, "url": "s/0001.html"}]}
def test_source_has_no_host_paths():
with open(os.path.join(HERE, "build.py"), encoding="utf-8") as fh:
assert re.search(r"['\"]/(tmp|home/claude)/", fh.read()) is None
def test_runs_from_env_only_and_copies_no_code():
work = tempfile.mkdtemp()
gpath = os.path.join(work, "build_graph.json")
with open(gpath, "w") as fh:
json.dump(tiny_graph(), fh)
out = os.path.join(work, "out")
env = dict(os.environ, EXPLORE_GRAPH=gpath, EXTRA_OUT=out)
env.pop("EXPLORE_SRC", None)
p = subprocess.run([sys.executable, os.path.join(HERE, "build.py")], cwd=work, env=env,
capture_output=True, text=True, timeout=120)
assert p.returncode == 0, p.stderr[-800:]
with open(os.path.join(out, "demo.json"), encoding="utf-8") as fh:
d = json.load(fh)
F = d["fields"]
for r in d["files"]:
assert r[F.index("synopsis")] == "Draws maps."
assert all("(" not in s and "function" not in s for s in r[F.index("signatures")])
assert os.path.isfile(os.path.join(out, "index.html"))
def test_missing_graph_is_a_clear_error():
work = tempfile.mkdtemp()
env = dict(os.environ)
env.pop("EXPLORE_GRAPH", None)
p = subprocess.run([sys.executable, os.path.join(HERE, "build.py"), "--out", work], cwd=work, env=env,
capture_output=True, text=True, timeout=60)
assert p.returncode != 0 and "build_graph.json not found" in p.stderrTest Repokuiper
A test in the explore folder of Cosmic that checks Build and Kuiper API, using SHA-256. It is built from the tree step (`tree`).
testcosmic / tools/explore/repokuiper/test_repokuiper.py · lines 1–231 of 231 · Not reached from any entry point (candidate for review) · pattern built (shared by 3 files)
- What it does
- It tests its inputs. Defines 21 functions or classes, including graph, built, _one_repo, _positions, _fake. Uses libraries copy, filecmp, json, os, sys. Side effects: changes the web page (DOM); reads or writes files.
- Inputs & outputs
- In: JSON file index.json; JSON file demo.json; JSON file lookup.json; JSON file identity-files.json. Out: JSON file demo.json; JSON file demo.overlays.json; JSON file index.json.
- What it achieves
- Defines `graph`, `built`, `test_layout_invariant_when_a_file_is_added` and 15 more. It reads `demo.json`.
- Why it matters
- Guards the behaviour of Build, Kuiper API and Kuiper Overlays.
- Application
- cosmic · tools/explore/repokuiper · test
- Uses
- Build (import), Kuiper API (import), Kuiper Overlays (import), copy, filecmp, json, os, sys, pytest, re
- Used by
- none found
- Produces
- graph, built, test_layout_invariant_when_a_file_is_added, test_position_depends_only_on_path, test_deterministic, test_every_repo_produced, test_json_size_per_repo, test_no_cdn, test_plugin_api_surface, test_modules_tagged_in_contract_order, test_failing_hook_hides_data_not_build, test_hook_cannot_overwrite_core_json
- Defines here
- graph, built, _one_repo, _positions, _fake, test_layout_invariant_when_a_file_is_added, test_position_depends_only_on_path, test_deterministic, tree, test_every_repo_produced, test_json_size_per_repo, test_no_cdn, test_plugin_api_surface, test_modules_tagged_in_contract_order, test_failing_hook_hides_data_not_build, test_hook_cannot_overwrite_core_json, test_ordinal_collisions_broken_by_full_hash, test_no_sibling_ordinals_collide_in_real_data, test_llms_block_added_once, test_lite_identity_cut_is_accepted, test_module_keys_do_not_clash
- 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.py:1-231 · blob 53410b7e7bb92c7094f416ac8636c139131617f4 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: unknown · users: none · canonical: unreached_review
"""Tests for repokuiper. Run: python3 -m pytest -q tools/explore/repokuiper/test_repokuiper.py"""
import copy
import filecmp
import json
import os
import sys
import pytest
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import build # noqa: E402
GRAPH = os.environ.get("REPOKUIPER_GRAPH", build.DEFAULT_GRAPH)
MAX_JSON_BYTES = 1_500_000 # largest real repo (globalgrid2050, 2,439 files) is ~1.2 MB
@pytest.fixture(scope="module")
def graph():
if not os.path.exists(GRAPH):
pytest.skip("build graph not present")
return json.load(open(GRAPH, encoding="utf-8"))
@pytest.fixture(scope="module")
def built(graph, tmp_path_factory):
out = tmp_path_factory.mktemp("rk1")
per = build.build(graph=graph, src="", out=str(out))
return out, per
def _one_repo(graph, repo, extra_files=()):
g = copy.deepcopy({k: graph[k] for k in ("roles", "edges", "sections", "repos", "cut", "base")})
files = [f for f in graph["files"] if f["repo"] == repo] + list(extra_files)
roles = [[r["id"], r["title"], r["colour"]] for r in g["roles"]]
role_ix = {r[0]: i for i, r in enumerate(roles)}
kinds = sorted({e[2] for e in g["edges"]})
edges_by_src = {}
for e in g["edges"]:
edges_by_src.setdefault(e[0], []).append(e)
return build.repo_data(g, repo, files, edges_by_src, {s["section"]: s["url"] for s in g["sections"]},
role_ix, {k: i for i, k in enumerate(kinds)}, {})
def _positions(d):
paths = build.folder_paths(d["folders"])
_, xy = build.layout(d["folders"], d["files"], d["band"])
return {(paths[f[1]] + "/" if paths[f[1]] else "") + f[0]: p for f, p in zip(d["files"], xy)}
def _fake(repo, path, fid):
return {"id": fid, "repo": repo, "path": path, "lines": 10, "role": "render", "reachable": True,
"entry": False, "section": 1, "title": "new", "synopsis": "", "signatures": []}
@pytest.mark.parametrize("repo", ["gridatlas", "ventus-grid-engine", "satnav"])
def test_layout_invariant_when_a_file_is_added(graph, repo):
before = _positions(_one_repo(graph, repo))
some = next(iter(before))
folder = some.rpartition("/")[0]
extra = [_fake(repo, (folder + "/" if folder else "") + "zz_added_here.js", 10**7),
_fake(repo, "brand-new-folder/deeper/aa_added.py", 10**7 + 1),
_fake(repo, "0_root_added.md", 10**7 + 2)]
after = _positions(_one_repo(graph, repo, extra))
assert len(after) == len(before) + 3
moved = [p for p in before if before[p] != after[p]]
assert moved == [], f"adding files moved {len(moved)} others"
def test_position_depends_only_on_path():
folders = [["", -1, 0], ["a", 0, build.ordinal("a/")]]
one = build.layout(folders, [["x.js", 1, build.ordinal("a/x.js")]])[1][0]
many = build.layout(folders, [["y.js", 1, build.ordinal("a/y.js")], ["x.js", 1, build.ordinal("a/x.js")]])[1][1]
assert one == many
assert build.ordinal("a/x.js") == int(__import__("hashlib").sha256(b"a/x.js").hexdigest()[:8], 16)
def test_deterministic(graph, built, tmp_path):
out1, _ = built
build.build(graph=graph, src="", out=str(tmp_path))
def tree(root):
return sorted(os.path.relpath(os.path.join(d, f), root) for d, _, fs in os.walk(root) for f in fs)
names = tree(out1)
assert names == tree(tmp_path) # including module data folders such as api/
match, mismatch, errors = filecmp.cmpfiles(out1, tmp_path, names, shallow=False)
assert not mismatch and not errors
def test_every_repo_produced(graph, built):
out, per = built
have_files = {f["repo"] for f in graph["files"]}
expected = {r["repo"] for r in graph["repos"] if r.get("visibility", "public") == "public" and r["repo"] in have_files}
assert set(per) == expected and len(expected) > 0
for repo in expected:
s = build.slug(repo)
assert os.path.exists(out / f"{s}.html") and os.path.exists(out / f"{s}.json")
page = open(out / f"{s}.html", encoding="utf-8").read()
assert "<noscript>" in page and 'data-json="%s.json"' % s in page and "http" not in page.split("<noscript>")[0].split("<body")[0]
d = json.load(open(out / f"{s}.json", encoding="utf-8"))
assert d["counts"]["files"] == sum(1 for f in graph["files"] if f["repo"] == repo)
assert all(d["folders"][i][1] < i for i in range(1, len(d["folders"]))) # parent before child
for asset in ("index.html", "index.json", "repokuiper.js", "repokuiper.css"):
assert os.path.exists(out / asset)
idx = json.load(open(out / "index.json", encoding="utf-8"))
assert len(idx["files"]) == len(expected)
def test_json_size_per_repo(built):
out, per = built
for repo, d in per.items():
size = os.path.getsize(out / f"{build.slug(repo)}.json")
assert size <= MAX_JSON_BYTES, (repo, size)
shown = sum(len(f[11]) for f in d["files"]) # function moons carried in the JSON
budget = 4000 + 600 * d["counts"]["files"] + 45 * shown # fixed header + per file + per function
assert size <= budget, (repo, size, budget)
def test_no_cdn(built):
out, _ = built
for name in ("repokuiper.js", "index.html", "gridatlas.html"):
text = open(out / name, encoding="utf-8").read()
assert "<script src=\"http" not in text and "cdn" not in text.lower()
# ---------------------------------------------------------------- plugin API (window.KUIPER, CONTRACT.md v1)
JS = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "repokuiper.js"), encoding="utf-8").read()
def test_plugin_api_surface():
assert "window.KUIPER = K" in JS
for name in ("use(", "onFrame(", "addOverlay(", "setStyler(", "addCardSection(", "addButton(", "addKey(",
"on(", "panel(", "legend(", "loadJSON(", "findPath", "visibleBodies(", "flyTo", "redraw("):
assert name in JS, name
def test_modules_tagged_in_contract_order(built):
out, _ = built
page = open(out / "gridatlas.html", encoding="utf-8").read()
present = build.modules()
pos = [page.index(f'src="repokuiper-{m}.js"') for m in present]
assert pos == sorted(pos)
assert all(page.index('src="repokuiper.js"') < p for p in pos)
for m in present:
assert os.path.exists(out / f"repokuiper-{m}.js")
def test_failing_hook_hides_data_not_build(tmp_path, monkeypatch, capsys):
g = __import__("test_no_tmp").tiny_graph()
hook = tmp_path / "kuiper_nav.py"
hook.write_text("def build(ctx):\n raise RuntimeError('boom')\n")
real = build.HERE
monkeypatch.setattr(build, "HERE", str(tmp_path))
for a in ("repokuiper.js", "repokuiper.css"):
(tmp_path / a).write_text(open(os.path.join(real, a), encoding="utf-8").read())
out = tmp_path / "out"
build.build(graph=g, src="", out=str(out))
assert (out / "demo.html").exists() and "module nav data hook failed" in capsys.readouterr().err
def test_hook_cannot_overwrite_core_json(tmp_path, monkeypatch):
g = __import__("test_no_tmp").tiny_graph()
(tmp_path / "kuiper_overlays.py").write_text("def build(ctx):\n return {'demo.json': {}, 'demo.overlays.json': {'a': 1}}\n")
real = build.HERE
monkeypatch.setattr(build, "HERE", str(tmp_path))
for a in ("repokuiper.js", "repokuiper.css"):
(tmp_path / a).write_text(open(os.path.join(real, a), encoding="utf-8").read())
out = tmp_path / "out"
build.build(graph=g, src="", out=str(out))
assert json.load(open(out / "demo.json"))["files"] # core data intact
def test_ordinal_collisions_broken_by_full_hash():
rows = [["a.js", 1, 7], ["b.js", 1, 7], ["c.js", 2, 7], ["d.js", 1, 9]]
paths = ["x/a.js", "x/b.js", "y/c.js", "x/d.js"]
fixed = build.break_ties(rows, paths)
assert fixed == 1
first = min(("x/a.js", 0), ("x/b.js", 1), key=lambda p: __import__("hashlib").sha256(p[0].encode()).hexdigest())[1]
assert rows[first][2] == 7 # first by full hash keeps its ordinal
other = 1 - first
assert rows[other][2] == build.ordinal_window(paths[other], 1)
assert rows[2][2] == 7 and rows[3][2] == 9 # other parents and non-colliders untouched
again = [["a.js", 1, 7], ["b.js", 1, 7], ["c.js", 2, 7], ["d.js", 1, 9]]
build.break_ties(again, paths)
assert again == rows # deterministic
def test_no_sibling_ordinals_collide_in_real_data(built):
_, per = built
for repo, d in per.items():
for rows in (d["folders"], d["files"]):
keys = [(r[1], r[2]) for r in rows[1 if rows is d["folders"] else 0:]]
assert len(keys) == len(set(keys)), repo
def test_llms_block_added_once(tmp_path):
import kuiper_api
(tmp_path / "kuiper" / "api").mkdir(parents=True)
(tmp_path / "kuiper" / "api" / "index.json").write_text("{}")
(tmp_path / "llms.txt").write_text("# x\n\n## Licences\n\n- a: MIT\n")
assert kuiper_api.add_to_llms(str(tmp_path), "https://example.invalid/explore-code/")
assert not kuiper_api.add_to_llms(str(tmp_path), "https://example.invalid/explore-code/")
t = (tmp_path / "llms.txt").read_text()
assert t.count("## Kuiper (agent API)") == 1 and t.index("## Kuiper") < t.index("## Licences")
assert "https://example.invalid/explore-code/kuiper/api/lookup.json" in t
def test_lite_identity_cut_is_accepted(tmp_path):
import kuiper_overlays as ko
g = __import__("test_no_tmp").tiny_graph()
per = {"demo": build.repo_data(g, "demo", g["files"], {}, {1: "s/0001.html"}, {"render": 0, "other": 1}, {"import": 0}, {})}
lite = {"_mode": "lite", "graph_cut": g["cut"], "counts": {}, "checks": {}, "files": {
"0": {"id": 0, "repo": "demo", "keys": {}, "verdict": {"verdict": "unique", "of_file": None, "similarity": None}}}}
p = tmp_path / "identity-files.json"
p.write_text(json.dumps(lite))
ident, words = ko.mode_identity(str(p), g, ko.Join(g, per))
assert "demo" in ident and words == {} # verdicts shown; no VEDIC candidates in lite mode, so no words
lite["graph_cut"] = "another cut"
p.write_text(json.dumps(lite))
assert ko.mode_identity(str(p), g, ko.Join(g, per)) == ({}, {})
def test_module_keys_do_not_clash():
import re
here = os.path.dirname(os.path.abspath(__file__))
owners = {}
for m in build.modules():
src = open(os.path.join(here, f"repokuiper-{m}.js"), encoding="utf-8").read()
keys = set(re.findall(r"addKey\('([^']+)'", src)) | set(re.findall(r"key: '([^']+)'", src))
keys |= set(re.findall(r"^\s+'([^']{1,10})': \(", src, re.M)) # keymap objects
for k in keys - {"Escape", "Backspace"}: # shared on purpose: close / step back
assert k not in owners, f"key {k!r} used by {owners[k]} and {m}"
owners[k] = mTest Repokuiper API
A test in the explore folder of Cosmic that checks Build and Kuiper API.
testcosmic / tools/explore/repokuiper/test_repokuiper_api.py · lines 1–153 of 153 · 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 11 functions or classes, including graph, overlays, run, test_rows_ids_keys_links, test_canonical_community_clarity_vedic. Uses libraries json, os, sys, pytest. Side effects: reads or writes files.
- Inputs & outputs
- In: JSON file index.galaxy.json; JSON file index.json; JSON file alpha.json; JSON file lookup.json; JSON file alpha.p0.json; JSON file alpha.p1.json; JSON file g.json. Out: JSON file.
- Downstream impact
- Used directly by 1 file: Test Repokuiper Speed (cosmic).
- What it achieves
- It is built from the graph step (`graph`), the overlays step (`overlays`) and the run step (`run`). Tests for `kuiper_api.py` (K5 agent API build hook). pytest, no network. It reads `index.json`.
- Why it matters
- Checked by Test Repokuiper Speed.
- Application
- cosmic · tools/explore/repokuiper · test
- Uses
- Build (import), Kuiper API (import), json, os, sys, pytest
- Used by
- imported by Test Repokuiper Speed (import)
- Produces
- graph, overlays, run, test_rows_ids_keys_links, test_canonical_community_clarity_vedic, test_index_and_guide, test_photon_rule_and_size, test_other_cut_or_missing_overlays_are_left_out, test_shards_when_large, test_standalone_main, test_real_site_budget
- Defines here
- graph, overlays, run, test_rows_ids_keys_links, test_canonical_community_clarity_vedic, test_index_and_guide, test_photon_rule_and_size, test_other_cut_or_missing_overlays_are_left_out, test_shards_when_large, test_standalone_main, 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_api.py:1-153 · blob 718ffe8b9bd8996b0f8b55ea567acff2d288bec9 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: unreached_review
"""Tests for kuiper_api.py (K5 agent API build hook). pytest, no network."""
import json
import os
import sys
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
CUT = '2026-12-05T00:00:00+00:00'
BASE = 'https://example.org/explore-code/'
def graph():
spec = (('alpha', ['a/x.js', 'a/y.js', 'b/z.py', 'main.html']), ('beta', ['m.js', 'n/o.js']))
files = []
for repo, paths in spec:
for p in paths:
files.append({'id': len(files), 'repo': repo, 'path': p, 'lines': 10 + len(files), 'role': 'logic',
'reachable': True, 'entry': p == 'main.html', 'signatures': ['def clampValue(x)'],
'section': 1 + len(files) % 2, 'block': 2, 'title': 'T ' + p, 'synopsis': 'SECRET CODE TEXT',
'canonical_status': 'production_core', 'duplicate_of': None, 'imports': [], 'dependents': []})
# ids: alpha a/x.js 0, a/y.js 1, b/z.py 2, main.html 3; beta m.js 4, n/o.js 5
edges = [[3, 0, 'script-src', ''], [0, 1, 'import', ''], [4, 5, 'import', ''], [5, 0, 'estate-url', ''],
[2, 4, 'comment-url', '']]
for a, b, k, _ in edges:
if k != 'comment-url':
files[a]['imports'].append(b)
files[b]['dependents'].append(a)
files[1]['duplicate_of'] = 0
files[1]['canonical_status'] = 'duplicate_candidate'
return {'cut': CUT, 'base': BASE, 'files': files, 'edges': edges,
'repos': [{'repo': 'alpha', 'commit': 'a' * 40}, {'repo': 'beta', 'commit': 'b' * 40}],
'roles': [{'id': 'logic', 'title': 'Logic', 'colour': '#66ccff'}],
'sections': [{'section': 1, 'url': 's/0001.html'}, {'section': 2, 'url': 's/0002.html'}]}
def overlays(out, cut=CUT):
"""What K3's hook writes for alpha (bodies sorted by path: a/x.js a/y.js b/z.py main.html)."""
k = {'source': 'x', 'cut': cut}
w = lambda n, d: open(os.path.join(out, 'alpha.ov-%s.json' % n), 'w').write(json.dumps(dict(d, key=k, n=4)))
w('community', {'legend': [['maps', '#00ffff', 3, 3], ['data', '#66ccff', 1, 2]], 'v': [0, 0, 1, -1]})
w('clarity', {'legend': [['Unique and in use', '#0f8', 3], ['Copies of other code', '#fa0', 1]], 'v': [0, 1, 0, 0]})
w('words', {'dict': [['CLAMP', 'GG2050-VEDIC-0007'], ['VALUE', '']], 'fw': [[0, 1], [0], [], []], 'v': [2, 1, 0, 0]})
w('identity', {'v': [0, 2, 0, 0], 'sim': [0, 91, 0, 0], 'of': [[1, '', 0], [2, 'beta', 0]]})
json.dump({'cut': cut, 'communities': [['grp', 'alpha', ['alpha', 'beta']]], 'rules': 'r'},
open(os.path.join(out, 'index.galaxy.json'), 'w'))
def run(tmp, cut=CUT, with_overlays=True):
g = graph()
out = tmp / 'kuiper'
out.mkdir()
if with_overlays:
overlays(str(out), cut)
saved, kb.MODULES = kb.MODULES, () # only this hook: other modules' hooks must not overwrite the fixture files
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})
rd = lambda n: json.load(open(out / 'api' / n))
return g, out, rd
def test_rows_ids_keys_links(tmp_path):
g, out, rd = run(tmp_path)
a = rd('alpha.json')
assert a['schema'] == 'repokuiper-api-v1' and a['n'] == 4 and a['cut'] == CUT
rows = a['rows']
assert [r['path'] for r in rows] == ['a/x.js', 'a/y.js', 'b/z.py', 'main.html']
assert [r['id'] for r in rows] == ['alpha:0', 'alpha:1', 'alpha:2', 'alpha:3']
x = rows[0]
assert x['key'] == 'alpha@%s a/x.js:1-10' % ('a' * 40) # no claim without a key
assert x['k'] == json.load(open(out / 'alpha.json'))['files'][0][2] # same resolved ordinal as the canvas
assert x['uses'] == [1] and x['used_by'] == [3, 'beta:1'] # ints same repo, strings across
assert rows[2]['uses'] == [] # comment links are mentions, not uses
assert x['view'] == BASE + 'kuiper/alpha.html#file=a/x.js'
assert x['page'] == BASE + 's/0001.html#f2'
assert rows[3]['reach'] == 'entry' and x['reach'] == 'reachable'
assert x['role'] == 'logic' and x['status'] == 'production_core'
def test_canonical_community_clarity_vedic(tmp_path):
_, _, rd = run(tmp_path)
rows = rd('alpha.json')['rows']
assert rows[1]['canonical'] == 'alpha:0' and rows[1]['status'] == 'duplicate_candidate'
assert rows[1]['near'] == 'alpha:0' and rows[1]['sim'] == 91
assert rows[2]['near'] == 'beta:0'
assert [r.get('community') for r in rows] == ['maps', 'maps', 'data', None]
assert rows[1]['clarity'] == 'Copies of other code'
assert rows[0]['vedic'] == [['CLAMP', 'GG2050-VEDIC-0007'], ['VALUE']]
lk = rd('lookup.json')
assert lk['paths']['alpha']['b/z.py'] == 2 and lk['paths']['beta']['n/o.js'] == 1
assert lk['vedic']['CLAMP'] == ['alpha:0', 'alpha:1'] and lk['vedic_ids']['GG2050-VEDIC-0007'] == 'CLAMP'
def test_index_and_guide(tmp_path):
_, out, rd = run(tmp_path)
ix = rd('index.json')
assert ix['counts'] == {'repos': 2, 'files': 6, 'lines': sum(10 + i for i in range(6)), 'links': 1}
al = next(r for r in ix['repos'] if r['repo'] == 'alpha')
assert al['community'] == 'grp' and al['entry_points'][0]['path'] == 'main.html' and al['entries'] == 1
assert al['links_in'] == [['beta', 1, 'estate-url']] and al['links_out'] == []
assert ['alpha', 'beta', 0, ''] not in ix['links'] and ['beta', 'alpha', 1, 'estate-url'] in ix['links']
txt = open(out / 'llms-kuiper.txt').read()
for s in ('api/lookup.json', 'used_by', 'canonical', '#file=', 'Worked examples', 'GET '):
assert s in txt
def test_photon_rule_and_size(tmp_path):
_, out, _ = run(tmp_path)
for n in os.listdir(out / 'api'):
s = open(out / 'api' / n).read()
assert 'SECRET CODE TEXT' not in s and 'clampValue' not in s # no synopses, no code text
assert 'SECRET CODE TEXT' not in open(out / 'llms-kuiper.txt').read()
def test_other_cut_or_missing_overlays_are_left_out(tmp_path):
_, _, rd = run(tmp_path, cut='1999-01-01T00:00:00+00:00')
rows = rd('alpha.json')['rows']
assert not any('community' in r or 'clarity' in r or 'vedic' in r for r in rows)
assert rd('index.json')['repos'][0]['community'] is None
def test_shards_when_large(tmp_path, monkeypatch):
monkeypatch.setattr(ka, 'MAX_BYTES', 10)
monkeypatch.setattr(ka, 'SHARD', 3)
_, out, rd = run(tmp_path, with_overlays=False)
man = rd('alpha.json')
assert 'rows' not in man and [s['file'] for s in man['shards']] == ['alpha.p0.json', 'alpha.p1.json']
assert rd('alpha.p1.json')['rows'][0]['id'] == 'alpha:3' # body i is in shards[i // SHARD]
def test_standalone_main(tmp_path):
g, out, rd = run(tmp_path)
(out / 'api' / 'lookup.json').unlink()
gp = tmp_path / 'g.json'
gp.write_text(json.dumps(g))
ka.main(['--graph', str(gp), '--site', str(tmp_path), '--out', str(out)])
assert rd('lookup.json')['paths']['alpha']['main.html'] == 3
@pytest.mark.skipif(not os.environ.get('KUIPER_SITE'), reason='set KUIPER_SITE=<explore-code> for the real-data budget')
def test_real_site_budget():
api = os.path.join(os.environ['KUIPER_SITE'], 'kuiper', 'api')
sizes = {n: os.path.getsize(os.path.join(api, n)) for n in os.listdir(api)}
assert max(v for n, v in sizes.items() if n != 'lookup.json') <= 260_000
assert sizes['lookup.json'] <= 400_000Test Repokuiper Galaxy
A test in the explore folder of Cosmic that checks Build and Kuiper Galaxy.
testcosmic / tools/explore/repokuiper/test_repokuiper_galaxy.py · lines 1–195 of 195 · Not reached from any entry point (candidate for review) · pattern built (shared by 3 files)
- What it does
- It tests its inputs. Defines 12 functions or classes, including graph, built, test_communities_arcs_and_determinism, test_tour_stops_have_keys_and_no_positions, test_photon_rule_and_budget. Uses libraries functools, http.server, json, os, re. Side effects: changes the web page (DOM); reads or writes files.
- Inputs & outputs
- In: JSON file index.json; JSON file index.galaxy.json. Out: JSON file index.json.
- What it achieves
- It is built from the graph step (`graph`), the built step (`built`) and the log message helper (`log_message`). Tests for the K4 estate galaxy: `kuiper_galaxy.py` (build hook) and `repokuiper-galaxy.js/`.CSS. pytest, no network. It reads `index.json` and writes `index.json`.
- Why it matters
- Guards the behaviour of Build and Kuiper Galaxy.
- Application
- cosmic · tools/explore/repokuiper · test
- Uses
- Build (import), Kuiper Galaxy (import), functools, http.server, json, os, re, sys, threading, pytest
- Used by
- none found
- Produces
- graph, built, test_communities_arcs_and_determinism, test_tour_stops_have_keys_and_no_positions, test_photon_rule_and_budget, test_cluster_index_uses_the_law, test_failing_input_leaves_no_galaxy, test_js_and_css_rules, test_browser_galaxy
- Defines here
- graph, built, test_communities_arcs_and_determinism, test_tour_stops_have_keys_and_no_positions, test_photon_rule_and_budget, test_cluster_index_uses_the_law, test_failing_input_leaves_no_galaxy, test_js_and_css_rules, _serve, Q, log_message, test_browser_galaxy
- 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_galaxy.py:1-195 · blob 12ba5104718bf8060d9a57e5a2648ba097712b84 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: unknown · users: none · canonical: unreached_review
"""Tests for the K4 estate galaxy: kuiper_galaxy.py (build hook) and repokuiper-galaxy.js/.css. pytest, no network.
The Playwright part (skipped when Playwright or Chromium is missing) serves a synthetic build over 127.0.0.1 and checks
the galaxy in the browser at 390x844 and 1366x768: no page errors, arcs and tour loaded, a star opens into its own
folders and files with the SAME positions as build.py layout() (the placement law), a tour runs to the end, no
sideways scroll.
"""
import functools
import http.server
import json
import os
import re
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_galaxy as kg # noqa: E402
CUT = '2026-12-05T00:00:00+00:00'
PALETTE = {'#000', '#0b0e14', '#2f343d', '#fff', '#a6adbb', '#66ccff', '#00ffff'}
def graph():
"""Five repositories: alpha<->beta linked hard, gamma linked to beta once, delta and epsilon alone."""
files = []
tree = {'alpha': ['a/x.js', 'a/y.js', 'a/deep/er/z.js', 'b/z.py', 'main.html'], 'beta': ['m.js', 'n/o.js', 'n/p.js'],
'gamma': ['g.py', 'h/i.py'], 'delta': ['d.md'], 'epsilon': ['e/f.js', 'e/g.js']}
for repo, paths in tree.items():
for p in paths:
files.append({'id': len(files), 'repo': repo, 'path': p, 'lines': 10 + 7 * len(files), 'role': 'logic',
'reachable': len(files) % 3 != 0, 'entry': p.endswith('.html'), 'signatures': ['def run(x)'],
'section': 1, 'title': p, 'synopsis': 'A file.', 'reached_from_entries': len(files) % 4})
ix = {(f['repo'], f['path']): f['id'] for f in files}
edges = [[ix['alpha', 'a/x.js'], ix['beta', 'm.js'], 'import'], [ix['alpha', 'a/y.js'], ix['beta', 'm.js'], 'import'],
[ix['beta', 'n/o.js'], ix['alpha', 'a/x.js'], 'link'], [ix['gamma', 'g.py'], ix['beta', 'n/p.js'], 'link'],
[ix['alpha', 'main.html'], ix['alpha', 'a/x.js'], 'script-src']]
return {'cut': CUT, 'base': 'https://example.invalid/explore-code/', 'files': files, 'edges': edges,
'repos': [{'repo': r, 'commit': c * 40} for r, c in zip(tree, 'abcde')],
'roles': [{'id': 'logic', 'title': 'Logic', 'colour': '#66ccff'}],
'sections': [{'section': 1, 'url': 's/0001.html'}]}
@pytest.fixture()
def built(tmp_path):
g = graph()
site = tmp_path / 'explore-code'
out = site / 'kuiper'
per = kb.build(graph=g, out=str(out), src='')
gal = kg.build({'graph': g, 'per_repo': per, 'index': json.load(open(out / 'index.json')), 'out': str(out),
'slug': kb.slug, 'extras_dir': os.path.dirname(HERE)})['index.galaxy.json']
return g, per, gal, site
# ------------------------------------------------------------------ the build hook
def test_communities_arcs_and_determinism(built):
g, per, gal, _ = built
groups = {c[0]: c[2] for c in gal['communities']}
assert groups[kg.STANDALONE] == ['delta', 'epsilon']
linked = [c for c in gal['communities'] if c[0] != kg.STANDALONE]
assert sorted(r for c in linked for r in c[2]) == ['alpha', 'beta', 'gamma']
arcs = {(a[0], a[1]): a for a in gal['arcs']}
assert arcs['alpha', 'beta'][2:4] == [2, 1] and arcs['beta', 'gamma'][2:4] == [0, 1]
assert arcs['alpha', 'beta'][5] == 'alpha/a/x.js -> beta/m.js' # a real edge, named by keys
assert ('alpha', 'alpha') not in arcs # inside-repo edges are not arcs
again = kg.galaxy(graph(), per)
assert json.dumps(again, sort_keys=True) == json.dumps(gal, sort_keys=True)
def test_tour_stops_have_keys_and_no_positions(built):
_, per, gal, _ = built
stops = gal['tour']
assert 5 <= len(stops) <= 8
for s in stops:
assert s['text'] and s['key'] and s['title'], s
assert not re.search(r'\b(x|y|theta|pos)\s*[:=]', json.dumps(s))
kinds = [s['kind'] for s in stops]
assert kinds[0] == 'galaxy' and kinds[-1] == 'end' and 'file' in kinds and 'arc' in kinds
f = next(s for s in stops if s['kind'] == 'file')
repo, path = f['target']
assert repo in per and f['key'].startswith(f"{repo}@{per[repo]['commit'][:12]} {path}:1-")
def test_photon_rule_and_budget(built):
g, _, gal, _ = built
text = json.dumps(gal)
assert len(text) <= 200_000
assert 'def run' not in text and 'signatures' not in text # no code text
for word in ('god', 'divine', 'sacred', 'holy', 'prayer', 'worship'):
assert not re.search(r'\b%s\b' % word, json.dumps(gal['tour']).lower())
def test_cluster_index_uses_the_law(built):
_, _, gal, site = built
idx = json.load(open(site / 'kuiper' / 'index.json'))
kg.cluster_index(idx, gal)
labels = [c[0] for c in gal['communities']]
assert [f[0] for f in idx['folders'][1:]] == labels
for name, parent, key in idx['folders'][1:]:
assert parent == 0 and key == kb.ordinal('group:' + name)
where = {r: i + 1 for i, c in enumerate(gal['communities']) for r in c[2]}
assert all(f[1] == where[f[0]] for f in idx['files'])
fx, files = kb.layout(idx['folders'], idx['files'], band=idx['band'])
assert len(files) == len(idx['files']) and 'positions' not in idx and 'xy' not in json.dumps(idx)
def test_failing_input_leaves_no_galaxy(tmp_path):
g = graph()
per = kb.build(graph=g, out=str(tmp_path / 'k'), src='')
g2 = dict(g, edges=[])
gal = kg.galaxy(g2, per)
assert gal['arcs'] == [] and [c[0] for c in gal['communities']] == [kg.STANDALONE]
assert 5 <= len(gal['tour']) <= 8
# ------------------------------------------------------------------ the page module
def test_js_and_css_rules():
js = open(os.path.join(HERE, 'repokuiper-galaxy.js'), encoding='utf-8').read()
css = open(os.path.join(HERE, 'repokuiper-galaxy.css'), encoding='utf-8').read()
assert "KUIPER.use('galaxy'" in js and 'if (!K.isIndex) return;' in js
assert not re.search(r'<script|import\s|cdn|unpkg|jsdelivr', js, re.I)
assert not re.search(r'fetch\(', js.split("K.addOverlay('gx-inside'")[1].split('function drawLoading')[0]) # no fetch per frame
css = re.sub(r'/\*.*?\*/', '', css, flags=re.S)
for c in {c.lower() for c in re.findall(r'#[0-9a-fA-F]{3,8}\b', css)}: # palette, optionally with alpha
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 and not p.startswith(('from', 'to')):
assert p.startswith(('#kp-gx-', '.gx-')), p
# ------------------------------------------------------------------ the browser
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.mark.parametrize('size', [(390, 844), (1366, 768)])
def test_browser_galaxy(built, size):
sync = pytest.importorskip('playwright.sync_api')
g, per, gal, site = built
out = site / 'kuiper'
idx = json.load(open(out / 'index.json'))
kg.cluster_index(idx, json.load(open(out / 'index.galaxy.json')))
json.dump(idx, open(out / 'index.json', 'w'))
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}')
pg = b.new_page(viewport={'width': size[0], 'height': size[1]})
errs = []
pg.on('pageerror', lambda e: errs.append(str(e)))
pg.goto(f'http://127.0.0.1:{srv.server_port}/kuiper/index.html')
pg.wait_for_function('window.__gx && window.__gx.G', timeout=15000)
assert pg.evaluate('__gx.arcs') == len(gal['arcs'])
i = pg.evaluate("KUIPER.D.files.findIndex(f => f[0] === 'alpha')")
pg.evaluate(f'__gx.enterRepo({i}, 0)')
pg.wait_for_function(f'__gx.loaded({i}) && __gx.active === {i}', timeout=15000)
lay = pg.evaluate(f'__gx.layout0({i})')
d = per['alpha']
fx, files = kb.layout(d['folders'], d['files'], band=d['band'])
for a, b2 in zip(lay['folders'], fx):
assert all(abs(u - v) < 1e-6 for u, v in zip(a, b2))
for a, b2 in zip(lay['files'], files):
assert all(abs(u - v) < 1e-6 for u, v in zip(a, b2))
pg.wait_for_timeout(900)
pg.evaluate('KUIPER.redraw()')
pg.wait_for_timeout(200)
assert pg.evaluate('__gx.drawn().files') >= 1
pg.evaluate('__gx.startTour()')
for _ in range(len(gal['tour']) + 1):
pg.evaluate('__gx.step(1)')
pg.wait_for_timeout(250)
assert pg.evaluate('__gx.tourAt') == pg.evaluate('__gx.stops') - 1
pg.keyboard.press('Escape')
assert pg.evaluate('__gx.tourAt') == -1
assert pg.evaluate('document.documentElement.scrollWidth') <= size[0]
assert not errs, errs
b.close()
finally:
srv.shutdown()