GLOBALGRID2050 / EXPLORE CODE

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

Build and 1 more file

A Python command-line tool in the repokuiper folder of Cosmic that draws build graph and galaxy, using SHA-256. It runs hooks (`run_hooks`) and writes page (`write_page`).

700 lines of Python from cosmic, in 2 files. Topic: Kuiper, cosmos and drawing engines. Section 1126 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. Bench Speed render · cosmic / tools/explore/repokuiper/bench_speed.py lines 1–242
  2. Build render · cosmic / tools/explore/repokuiper/build.py lines 1–458

Bench Speed

A Python command-line tool in the repokuiper folder of Cosmic that reads lookup. It runs go (`run_go`) and runs manual (`run_manual`).

rendercosmic / tools/explore/repokuiper/bench_speed.py · lines 1–242 of 242 · Entry point · pattern targets (shared by 2 files)

What it does
It loads lookup. Defines 12 functions or classes, including serve, Q, log_message, targets, settle. Uses libraries __future__, argparse, functools, http.server, json. Side effects: changes the web page (DOM); reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
Inputs & outputs
In: JSON file index.json; JSON file lookup.json; command-line arguments. Out: JSON file; browser storage (setItem).
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
`bench_speed.py` (K5, TACHYON-29): how fast does a person find a file in Kuiper, with "go" versus by hand? It accepts `--json`.
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
__future__, argparse, functools, http.server, json, os, re, sys
Used by
none found
Produces
serve, targets, settle, fresh, query_for, run_go, run_manual, bench, main
Defines here
serve, Q, log_message, targets, settle, fresh, query_for, run_go, run_manual, reach, bench, 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/bench_speed.py:1-242 · blob 984c87a7b7cbc74df4294d299ddd256ae92ed0ea · 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
"""bench_speed.py (K5, TACHYON-29): how fast does a person find a file in Kuiper, with "go" versus by hand?

Serves a built explore-code folder over 127.0.0.1 and, in Chromium at 390x844 (phone, touch), times
"find these 5 files", every trial starting on the estate page kuiper/index.html:

  go      tap "go", type the shortest path suffix that puts the file first, tap the result: the galaxy flies
          into the repository's star straight to the file (done when its card is up)
  manual  the best a person could do by hand, executed by machine: tap the repository's star (travelling into its
          group first if needed), tap "open its Kuiper", then tap into each folder on the way and tap the file
          (done when its card is up); every tap is a real touch at the point a person would touch

The five files are the middle file (by path) of each of the five largest repositories: no cherry-picking.
Reports, per file and in total: seconds (wall clock, machine-executed, animations included), taps, typed characters,
and a human estimate from the keystroke-level model (KLM: find-and-tap 1.1 s pointing + 0.2 s touch + 1.35 s
looking for the next target before each manual tap; 0.28 s per typed character; one 1.35 s think before typing).

    python3 bench_speed.py <explore-code folder> [--json out.json]
"""
from __future__ import annotations

import argparse
import functools
import http.server
import json
import os
import re
import sys
import threading
import time

KLM_TAP, KLM_LOOK, KLM_CHAR = 1.3, 1.35, 0.28

PICK = r"""(target) => {
  // the next touch a person would make to reach body `target` on this page: [x, y, kind] or null when it is visible
  const K = KUIPER, A = K.arr, v = K.view(), safe = K.safeTop + 6;
  const onScreen = (x, y) => x > 8 && x < K.W - 8 && y > safe && y < v.cy + v.h / 2 - 6;
  const f = A.bfo[target];
  const chain = []; for (let g = f; g >= 0; g = A.fpar[g]) chain.unshift(g);
  const k = chain.indexOf(K.focus);
  const vis = K.visibleBodies();
  const bodyClear = (x, y, except) => vis.every((j) => {
    if (j === except) return true;
    const p = K.toScreen(A.bx[j], A.by[j]), r = Math.max(0.9, A.brw[j] * K.cam.s);
    return Math.hypot(p[0] - x, p[1] - y) > Math.max(r + 6, 16) + 2;
  });
  if (f === K.focus || (k >= 0 && !K.collapsed(f))) {
    const p = K.toScreen(A.bx[target], A.by[target]);
    if (onScreen(p[0], p[1])) return [p[0], p[1], 'body'];
  }
  if (k < 0) return [0, 0, 'back'];        // landed off the way (a sibling caught the tap): pull back one level
  const next = k + 1 < chain.length ? chain[k + 1] : f;
  const c = K.toScreen(A.fx[next], A.fy[next]), R = A.fr[next] * K.cam.s;
  // a point inside `next` where no body sits and no deeper folder off the chain would catch the tap
  const deeper = [];
  for (let g = 1; g < K.NF; g++) {
    if (A.fdepth[g] <= A.fdepth[next] || chain.includes(g)) continue;
    const Rg = A.fr[g] * K.cam.s; if (Rg < 14) continue;
    const q = K.toScreen(A.fx[g], A.fy[g]); deeper.push([q[0], q[1], Rg]);
  }
  for (const rr of [0.0, 0.3, 0.5, 0.7, 0.9, 0.97]) for (let a = 0; a < 24; a++) {
    const th = a / 24 * Math.PI * 2, x = c[0] + Math.cos(th) * R * rr, y = c[1] + Math.sin(th) * R * rr;
    if (!onScreen(x, y) || !bodyClear(x, y, -1)) continue;
    if (deeper.some((d) => Math.hypot(d[0] - x, d[1] - y) <= d[2])) continue;
    return [x, y, 'folder'];
  }
  return [c[0], c[1], 'folder-centre'];
}"""


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=folder))
    threading.Thread(target=srv.serve_forever, daemon=True).start()
    return srv


def targets(site):
    ix = json.load(open(os.path.join(site, 'kuiper', 'api', 'index.json')))
    lk = json.load(open(os.path.join(site, 'kuiper', 'api', 'lookup.json')))
    out = []
    for r in sorted(ix['repos'], key=lambda r: -r['files'])[:5]:
        paths = sorted(lk['paths'][r['slug']])
        p = paths[len(paths) // 2]
        out.append({'repo': r['repo'], 'slug': r['slug'], 'path': p, 'i': lk['paths'][r['slug']][p]})
    return out


def settle(pg, ms=1600):
    """wait until the camera stops moving (or ms passes)"""
    t0, last = time.time(), None
    while time.time() - t0 < ms / 1000:
        cur = pg.evaluate('KUIPER.ready ? [KUIPER.cam.x, KUIPER.cam.y, KUIPER.cam.s, KUIPER.focus].map(v => +v.toFixed(3)).join() : ""')
        if cur and cur == last:
            return
        last = cur
        pg.wait_for_timeout(60)


def fresh(ctx, url, need_gx=True):
    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))
    pg.goto(url)
    pg.wait_for_function('window.__rkSpeed && window.__rkSpeed.ready' + (' && window.__gx' if need_gx else ''), timeout=20000)
    pg.evaluate('__rkSpeed.load()')
    pg.wait_for_function('__rkSpeed.find("index").length > 0', timeout=20000)
    settle(pg)
    return pg, errs


def query_for(pg, t):
    """what a person types: characters of the file name (or of its most distinctive word), one at a time, until the
    file comes first in the list; the shortest such query wins. Falls back to longer path suffixes."""
    name = t['path'].rsplit('/', 1)[-1]
    words = [name] + [w for w in re.split(r'[-_. ]+', name) if len(w) >= 3]
    first = lambda q: (lambda top: bool(top) and top[0] == t['slug'] and top[2] == t['path'])(
        pg.evaluate('(q) => __rkSpeed.find(q)[0]', q))
    best = None
    for w in words:
        for n in range(1, len(w) + 1):
            if best and n >= len(best):
                break
            if first(w[:n].lower()):
                best = w[:n].lower()
                break
    if best:
        return best
    segs = t['path'].split('/')
    for n in range(2, len(segs) + 1):
        q = '/'.join(segs[-n:])
        if first(q.lower()):
            return q.lower()
    return (t['slug'] + '/' + t['path']).lower()


def run_go(ctx, base, t):
    pg, errs = fresh(ctx, base + 'index.html')
    q = query_for(pg, t)
    star = pg.evaluate('(s) => KUIPER.D.files.findIndex(f => String(f[0]).toLowerCase() === s)', t['slug'])
    t0 = time.time()
    pg.tap('#kb-sp-go')
    pg.keyboard.type(q)
    pg.wait_for_selector('#kp-speed .sp-list li')
    pg.tap('#kp-speed .sp-list li >> nth=0')
    pg.wait_for_function('([b, j]) => __gx.sel && __gx.sel.i === b && __gx.sel.j === j', arg=[star, t['i']], timeout=20000)
    secs = time.time() - t0
    pg.close()
    return {'seconds': round(secs, 2), 'taps': 2, 'typed': len(q), 'query': q,
            'klm_seconds': round(KLM_LOOK + 2 * KLM_TAP + KLM_CHAR * len(q), 1), 'errors': errs}


def run_manual(ctx, base, t):
    pg, errs = fresh(ctx, base + 'index.html')
    star = pg.evaluate('(s) => KUIPER.D.files.findIndex(f => String(f[0]).toLowerCase() === s)', t['slug'])
    taps, notes = 0, []
    t0 = time.time()

    def reach(target, done_js):
        nonlocal taps
        for _ in range(40):
            if pg.evaluate(done_js):
                return True
            pick = pg.evaluate(PICK, target)
            if pick is None:
                notes.append('no tap point')
                return False
            if pick[2] == 'back':
                pg.tap('#tools button[data-k="Backspace"]')
                notes.append('back')
            else:
                pg.touchscreen.tap(pick[0], pick[1])
            taps += 1
            settle(pg)
            if pick[2] == 'body' and not pg.evaluate(done_js):      # crowded: a person would zoom in once
                pg.evaluate('(t) => { const p = KUIPER.toScreen(KUIPER.arr.bx[t], KUIPER.arr.by[t]); KUIPER.zoomAt(p[0], p[1], 2.5); }', target)
                taps += 1
                notes.append('zoom')
                settle(pg)
        return False

    reach(star, f'__rk.sel === {star}')
    # "open its Kuiper" on the star's card
    pg.tap('#card .links a >> nth=0')
    taps += 1
    pg.wait_for_function('window.__rkSpeed && window.__rkSpeed.ready', timeout=20000)
    settle(pg)
    ok = reach(t['i'], f'__rk.sel === {t["i"]}')
    secs = time.time() - t0
    pg.close()
    return {'seconds': round(secs, 2), 'taps': taps, 'typed': 0, 'ok': ok, 'notes': sorted(set(notes)),
            'klm_seconds': round(taps * (KLM_TAP + KLM_LOOK), 1), 'errors': errs}


def bench(site, width=390, height=844):
    from playwright.sync_api import sync_playwright
    srv = serve(site)
    base = 'http://127.0.0.1:%d/kuiper/' % srv.server_port
    rows = []
    try:
        with sync_playwright() as p:
            br = p.chromium.launch()
            ctx = br.new_context(viewport={'width': width, 'height': height}, device_scale_factor=2,
                                 has_touch=True, is_mobile=True)
            ctx.add_init_script("try { localStorage.setItem('kuiper-nav-hint-v1', '1'); } catch (e) {}")
            for t in targets(site):
                rows.append({'file': t['slug'] + '/' + t['path'], 'go': run_go(ctx, base, t),
                             'manual': run_manual(ctx, base, t)})
            br.close()
    finally:
        srv.shutdown()
    tot = {m: {k: round(sum(r[m][k] for r in rows), 2) for k in ('seconds', 'taps', 'typed', 'klm_seconds')}
           for m in ('go', 'manual')}
    return {'viewport': [width, height], 'files': rows, 'total': tot,
            'errors': sorted({e for r in rows for m in ('go', 'manual') for e in r[m]['errors']})}


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])
    ap.add_argument('site', help='built explore-code folder (with kuiper/ and kuiper/api/)')
    ap.add_argument('--json', help='write the full result here')
    a = ap.parse_args(argv)
    r = bench(a.site)
    for row in r['files']:
        g, m = row['go'], row['manual']
        print('%-70s go %5.2fs %d taps + %2d chars (KLM %4.1fs) | by hand %5.2fs %2d taps (KLM %4.1fs)%s'
              % (row['file'][:70], g['seconds'], g['taps'], g['typed'], g['klm_seconds'], m['seconds'], m['taps'],
                 m['klm_seconds'], '' if m.get('ok') else ' NOT REACHED'))
    t = r['total']
    print('TOTAL 5 files: go %.1fs, %d taps + %d chars (KLM %.1fs) | by hand %.1fs, %d taps (KLM %.1fs) | errors %d'
          % (t['go']['seconds'], t['go']['taps'], t['go']['typed'], t['go']['klm_seconds'], t['manual']['seconds'],
             t['manual']['taps'], t['manual']['klm_seconds'], len(r['errors'])))
    if a.json:
        json.dump(r, open(a.json, 'w'), indent=1)
    return 0 if not r['errors'] and all(x['manual'].get('ok') for x in r['files']) else 1


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

Build

A Python command-line tool in the repokuiper folder of Cosmic that draws build graph and galaxy, using SHA-256. It runs hooks (`run_hooks`) and writes page (`write_page`).

rendercosmic / tools/explore/repokuiper/build.py · lines 1–458 of 471 · Entry point · pattern module_tags (shared by 2 files)

What it does
It draws build graph and galaxy. Defines 20 functions or classes, including sig_name, first_sentence, ordinal, ordinal_window, break_ties. Uses libraries __future__, argparse, hashlib, html, json. Side effects: changes the web page (DOM); reads or writes files; starts processes.
Why it exists in the grid workflow
README: "`build.py` is the method"
Inputs & outputs
In: JSON file build_graph.json; JSON file index.json; JSON file index.galaxy.json; form fields (user input); command-line arguments. Out: JSON file.
Downstream impact
Used directly by 9 files: Extras (cosmic); Test No Tmp (cosmic); Test Repokuiper (cosmic); Test Repokuiper API (cosmic); and 5 more. Reached from 3 other entry points, including Ship (cosmic); Test Extras (cosmic); Test Ship (cosmic).
What it achieves
Repokuiper: every repository gets its own Kuiper. It accepts `--graph`, `--src` and `--out`.
Why it matters
Imported by Verify Playwright. Run by Extras. Checked by 7 tests, including Test No Tmp.
Application
cosmic · tools/explore/repokuiper · Python CLI
Uses
__future__, argparse, hashlib, html, json, math, os, re
Used by
run by Extras (script call), imported by Test No Tmp (import), imported by Test Repokuiper (import), imported by Test Repokuiper API (import), imported by Test Repokuiper Galaxy (import), run by Test Repokuiper Nav (script call), imported by Test Repokuiper Overlays (import), imported by Test Repokuiper Speed (import), and 1 more
Produces
sig_name, first_sentence, ordinal, ordinal_window, break_ties, polar, layout, slug, git_blobs, repo_data, index_data, header_line
Defines here
sig_name, first_sentence, ordinal, ordinal_window, break_ties, polar, layout, slug, git_blobs, repo_data, index_data, header_line, noscript_list, folder_paths, modules, module_tags, run_hooks, write_page, build, 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/build.py:1-458 · blob dd7ec3a14f34fe24a21ac05ea7890c487bcb18ec · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
"""repokuiper: every repository gets its own Kuiper.

Reads the explore build graph (explore-build-graph-v1) and writes, per public repository in it:

    <out>/<repo>.html   a canvas universe of that repository (vanilla JS, no CDN)
    <out>/<repo>.json   the compact data the page draws, precomputed here

plus <out>/index.html (+ index.json), a universe whose bodies are the repositories, and the shared
engine <out>/repokuiper.js and <out>/repokuiper.css.

THE PLACEMENT LAW (Kuiper's first law, "no claim without a key", applied to position):
every body carries a permanent ordinal k = the first 32 bits of sha256(path), where the path is the
file's (or folder's) path inside its repository. Positions are computed from k, never stored:

    u = k / 2^32,  theta = frac(k * 0.6180339887498949) * 2*pi       (the golden-angle law)
    a folder sits in its parent's annulus:  d = R_parent * (0.44 + 0.40*sqrt(u)), R = 0.24*R_parent
    a file sits in its folder's core:       d = R_folder * (0.04 + 0.34*sqrt(u))

Nothing in a body's position depends on any other body, so adding, removing or editing a file never
moves another one (one exception: in the rare case of a 32-bit ordinal collision between siblings, break_ties()
gives the later one, by full hash, the next 32-bit window of its own hash). A position is stable for a given
simulation time t (orbits turn with t); a rename is a new path, so a renamed file gets a new ordinal and a new place. layout() below is the reference implementation; repokuiper.js computes the same
numbers in the browser (the Playwright check compares them).

The blob id shown in each card is the git blob of the file at the graph's commit, read from the local
clone with `git ls-tree` (read-only). Where no clone holds that commit the card says so.
"""
from __future__ import annotations

import argparse
import hashlib
import html
import json
import math
import os
import re
import shutil
import subprocess
import sys
from collections import Counter, defaultdict

HERE = os.path.dirname(os.path.abspath(__file__))
# No host paths: extras.py passes --graph/--src/--out and sets EXPLORE_GRAPH / EXTRA_OUT; otherwise the current
# folder. Without clones (--src '' or a folder without the repo) cards say the blob id is unavailable.
DEFAULT_GRAPH = os.environ.get("EXPLORE_GRAPH") or "build_graph.json"
DEFAULT_SRC = os.environ.get("EXPLORE_SRC", "")
DEFAULT_OUT = os.environ.get("EXTRA_OUT") or "kuiper"
GITHUB_OWNER = "Ventusltd"

PHI_FRAC = 0.6180339887498949
TWO_PI = 2 * math.pi
R0 = 1000.0
CHILD_IN, CHILD_SPAN, CHILD_R = 0.44, 0.40, 0.24
FILE_IN, FILE_SPAN = 0.04, 0.34
MAX_SIGS = 80
# Plugin modules (contract /tmp/vk/kuiper4/CONTRACT.md, window.KUIPER in repokuiper.js): each repokuiper-<name>.js
# (+ .css) that exists beside this file is tagged on every page in this order and copied to <out>; an optional
# kuiper_<name>.py with build(ctx) -> {filename: obj} writes that module's small data JSON from the same build cut.
MODULES = ("nav", "overlays", "galaxy", "speed")
# data hooks run in MODULES order, then these (api, K5, last: it reads what the overlays and galaxy hooks wrote)
LATE_HOOKS = ("api",)
SIG_CHARS = 60


# Photon rule (owner, 2026-12-05): reference code by key or link, never copy code text. A signature becomes its
# function name (the page draws one moon per name) and a synopsis its first sentence; the section page has the rest.
_SIG_PREFIX = re.compile(r"^(?:export\s+|async\s+|def\s+|function\s+|class\s+)+")


def sig_name(sig) -> str:
    return _SIG_PREFIX.sub("", str(sig)).split("(")[0].strip()[:48]


def first_sentence(t: str, cap: int = 140) -> str:
    t = (t or "").strip()
    m = re.match(r"(.+?[.!?])(\s|$)", t)
    t = m.group(1) if m else t
    return t if len(t) <= cap else t[:cap - 1].rstrip() + "\u2026"


# ---------------------------------------------------------------- the law (reference implementation)

def ordinal(path: str) -> int:
    """Permanent ordinal: first 32 bits of sha256 of the path inside the repository."""
    return int(hashlib.sha256(path.encode("utf-8")).hexdigest()[:8], 16)


def ordinal_window(path: str, w: int) -> int:
    """32-bit window w of sha256(path); window 0 is the ordinal."""
    h = hashlib.sha256(path.encode("utf-8")).hexdigest()
    return int(h[8 * w:8 * w + 8], 16)


def break_ties(rows, paths, parent_ix=1, key_ix=2):
    """32-bit ordinals can collide (about 0.07% for 2,439 paths); two siblings with the same k would sit on the same
    spot. Within one parent, colliders are ordered by their full sha256; the first keeps k, each later one takes the
    next 32-bit window of its own hash that no sibling uses. Deterministic, and nothing else moves. Returns the count."""
    seen, groups = {}, {}
    for i, r in enumerate(rows):
        groups.setdefault((r[parent_ix], r[key_ix]), []).append(i)
        seen.setdefault(r[parent_ix], set()).add(r[key_ix])
    fixed = 0
    for (parent, _k), ix in sorted(groups.items(), key=lambda kv: (str(kv[0][0]), kv[0][1])):
        if len(ix) < 2:
            continue
        ix.sort(key=lambda i: hashlib.sha256(paths[i].encode("utf-8")).hexdigest())
        for i in ix[1:]:
            w = 1
            while ordinal_window(paths[i], w) in seen[parent] and w < 7:
                w += 1
            rows[i][key_ix] = ordinal_window(paths[i], w)
            seen[parent].add(rows[i][key_ix])
            fixed += 1
    return fixed


def polar(k: int, inner: float, span: float, radius: float):
    u = k / 4294967296.0
    th = ((k * PHI_FRAC) % 1.0) * TWO_PI
    d = radius * (inner + span * math.sqrt(u))
    return d * math.cos(th), d * math.sin(th)


def layout(folders, files, band=(FILE_IN, FILE_SPAN)):
    """Positions at t=0. folders: [[name, parent, key]] (parent < own index, root first);
    files: [[name, folder, key, ...]]. Returns (folder_xyR, file_xy)."""
    fx = []
    for i, f in enumerate(folders):
        if f[1] < 0:
            fx.append((0.0, 0.0, R0))
            continue
        px, py, pr = fx[f[1]]
        dx, dy = polar(f[2], CHILD_IN, CHILD_SPAN, pr)
        fx.append((px + dx, py + dy, pr * CHILD_R))
    out = []
    for f in files:
        px, py, pr = fx[f[1]]
        dx, dy = polar(f[2], band[0], band[1], pr)
        out.append((px + dx, py + dy))
    return fx, out


# ---------------------------------------------------------------- data

def slug(repo: str) -> str:
    return repo.lower()


def git_blobs(src: str, repo: str, commit: str) -> dict:
    path = os.path.join(src, repo)
    if not os.path.isdir(path):
        return {}
    try:
        out = subprocess.run(["git", "-C", path, "ls-tree", "-r", "--full-tree", commit],
                             capture_output=True, check=True, timeout=120).stdout
    except (subprocess.SubprocessError, OSError):
        return {}
    blobs = {}
    for line in out.decode("utf-8", "surrogateescape").splitlines():
        meta, _, p = line.partition("\t")
        parts = meta.split()
        if len(parts) == 3 and parts[1] == "blob":
            if p.startswith('"'):  # git quotes unusual paths; decode the C-style escapes
                try:
                    p = p[1:-1].encode("latin-1").decode("unicode_escape").encode("latin-1").decode("utf-8")
                except Exception:
                    pass
            blobs[p] = parts[2]
    return blobs


def repo_data(g, repo, files, edges_by_src, sec_url, role_ix, kind_ix, blobs):
    """Compact per-repo JSON. Files sorted by path (the listing order); position uses the key only."""
    files = sorted(files, key=lambda f: f["path"])
    local = {f["id"]: i for i, f in enumerate(files)}
    # folders: every directory prefix, sorted so a parent always precedes its children
    dirs = set()
    for f in files:
        parts = f["path"].split("/")[:-1]
        for n in range(1, len(parts) + 1):
            dirs.add("/".join(parts[:n]))
    dirs = sorted(dirs, key=lambda p: (p.count("/"), p))
    dix = {"": 0}
    folders = [["", -1, 0]]
    for p in dirs:
        parent = p.rpartition("/")[0]
        dix[p] = len(folders)
        folders.append([p.rpartition("/")[2], dix[parent], ordinal(p + "/")])
    out_files = []
    nsig = 0
    for f in files:
        d, _, name = f["path"].rpartition("/")
        flags = (1 if f.get("reachable") else 0) | (2 if f.get("entry") else 0) | (4 if f.get("pure") else 0)
        sigs = [sig_name(s) for s in (f.get("signatures") or [])[:MAX_SIGS]]
        nsig += len(f.get("signatures") or [])
        reached = f.get("reached_from_entries")
        reached = len(reached) if isinstance(reached, list) else (reached or 0)
        out_files.append([
            name, dix[d], ordinal(f["path"]), int(f.get("lines") or 0), role_ix.get(f.get("role"), role_ix["other"]),
            flags, sec_url.get(f.get("section"), ""), f.get("title") or name, first_sentence(f.get("synopsis") or ""),
            blobs.get(f["path"], ""), reached, sigs, f.get("lang") or "", f.get("canonical_status") or "",
        ])
    break_ties(folders, [""] + [p + "/" for p in dirs])
    break_ties(out_files, [f["path"] for f in files])
    inner, cross_out, cross_in = [], 0, 0
    for f in files:
        for e in edges_by_src.get(f["id"], ()):
            if e[1] in local:
                inner.append([local[f["id"]], local[e[1]], kind_ix[e[2]]])
            else:
                cross_out += 1
    ids = set(local)
    for e in g["edges"]:
        if e[1] in ids and e[0] not in ids:
            cross_in += 1
    inner.sort()
    meta = next(r for r in g["repos"] if r["repo"] == repo)
    counts = {
        "files": len(files),
        "lines": sum(f[3] for f in out_files),
        "reachable": sum(1 for f in out_files if f[5] & 1),
        "entries": sum(1 for f in out_files if f[5] & 2),
        "folders": len(folders) - 1,
        "sections": len({f[6] for f in out_files if f[6]}),
        "functions": nsig,
        "edges_inside": len(inner),
        "edges_out": cross_out,
        "edges_in": cross_in,
    }
    return {
        "schema": "repokuiper-v1",
        "law": "k = sha256(path)[:32 bits]; u = k/2^32; theta = frac(k*0.6180339887498949)*2pi; "
               "folder d = Rp*(0.44+0.40*sqrt(u)), R = 0.24*Rp; file d = Rf*(0.04+0.34*sqrt(u)); R0 = 1000",
        "repo": repo, "commit": meta["commit"], "license": meta.get("license") or "",
        "cut": g.get("cut", ""), "base": g.get("base", ""), "gh": f"https://github.com/{GITHUB_OWNER}/{repo}",
        "repo_page": f"repos/{slug(repo)}.html",
        "summary": meta.get("readme_summary") or "",
        "fields": ["name", "folder", "key", "lines", "role", "flags(1 reachable,2 entry,4 pure)", "section",
                   "title", "synopsis", "blob", "reached_from_entries", "signatures", "lang", "canonical_status"],
        "band": [FILE_IN, FILE_SPAN], "folders": folders, "files": out_files, "edges": inner, "counts": counts,
    }


def index_data(g, per_repo, role_ix):
    """The estate universe: each repository is one body, keyed by sha256 of its name."""
    files = []
    for repo in sorted(per_repo, key=str.lower):
        d = per_repo[repo]
        roles = Counter(f[4] for f in d["files"])
        dom = roles.most_common(1)[0][0] if roles else role_ix["other"]
        c = d["counts"]
        syn = (f"{c['files']} files, {c['lines']:,} lines, {c['reachable']} reachable, "
               f"{c['entries']} entries, {c['functions']} functions. ") + (d["summary"][:220])
        files.append([repo, 0, ordinal(repo), c["lines"], dom, 1 if c["reachable"] else 0,
                      d["repo_page"], repo, syn, "", 0, [], "", "", slug(repo) + ".html", d["commit"]])
    break_ties(files, [f[0] for f in files])
    counts = {"repos": len(files), "files": sum(d["counts"]["files"] for d in per_repo.values()),
              "lines": sum(d["counts"]["lines"] for d in per_repo.values()),
              "reachable": sum(d["counts"]["reachable"] for d in per_repo.values()),
              "functions": sum(d["counts"]["functions"] for d in per_repo.values())}
    return {"schema": "repokuiper-index-v1", "repo": "", "commit": "", "cut": g.get("cut", ""), "base": g.get("base", ""),
            "gh": f"https://github.com/{GITHUB_OWNER}", "law": "k = sha256(repository name)[:32 bits]; u = k/2^32; theta = frac(k*0.6180339887498949)*2pi; "
                   "d = R0*(0.08+0.86*sqrt(u)); R0 = 1000", "band": [0.08, 0.86],
            "folders": [["", -1, 0]], "files": files, "edges": [], "counts": counts}


# ---------------------------------------------------------------- pages

PAGE = """<!doctype html>
<html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>{title}</title>
<meta name="description" content="{desc}">
<link rel="stylesheet" href="repokuiper.css">{mod_css}
</head><body data-json="{json}" data-index="{is_index}">
<canvas id="sky" aria-label="{aria}"></canvas>
<header id="hud"><div id="line1">{line1}</div><div id="line2"><span id="crumb"></span></div>
<nav id="tools"><button data-k="Backspace" title="pull back (backspace)">&#8592; back</button><button data-k="h" title="home (h)">home</button><button data-k="e" title="edges (e)">edges</button><button data-k="l" title="names (l)">names</button><button data-k="x" title="x-ray (x)">x-ray</button><button data-k="p" title="pause (p)">pause</button><button data-k="f" title="find (f)">find</button><but  … [line shortened here: 467 characters; full line on GitHub]
<aside id="card" hidden></aside>
<div id="find" hidden><input id="q" type="search" placeholder="filter by path or title" autocomplete="off"><ol id="list"></ol></div>
<div id="help" hidden><p><b>{law_title}</b></p><p>Every body's position is computed from its permanent ordinal, never stored: k is the first 32 bits of sha256 of its path, r grows with &radic;k and &theta; = k &times; golden angle. Folders are orbits; each folder's files sit in its core and its sub-folders in its annulus. Adding a file never moves another.</p><p>Colour = role, brightness = reachab  … [line shortened here: 860 characters; full line on GitHub]
<div id="err" hidden></div>
<noscript><div class="ns"><h1>{h1}</h1><p>{line1}</p>{nolist}</div></noscript>
<script src="repokuiper.js"></script>{mod_js}
</body></html>
"""


def header_line(d):
    c = d["counts"]
    unreached = c["files"] - c["reachable"]
    return (f"<b>{html.escape(d['repo'])}</b> @ <code>{d['commit'][:7]}</code> &middot; {c['files']:,} files "
            f"&middot; {c['lines']:,} lines &middot; {c['reachable']:,} reachable ({unreached:,} unreached) &middot; "
            f"{c['entries']:,} entries &middot; {c['functions']:,} functions &middot; {c['folders']:,} folders &middot; "
            f"{c['edges_inside']:,} resolved edges inside, {c['edges_out']:,} out / {c['edges_in']:,} in across repos")


def noscript_list(d):
    base = d["base"]
    by = defaultdict(list)
    paths = folder_paths(d["folders"])
    for f in d["files"]:
        by[f[1]].append(f)
    parts = []
    for fi in sorted(by, key=lambda i: paths[i]):
        parts.append(f"<h2>{html.escape(paths[fi] or '/')}</h2><ul>")
        for f in by[fi]:
            href = base + f[6] if f[6] else d["gh"]
            parts.append(f'<li><a href="{html.escape(href)}">{html.escape(f[0])}</a> '
                         f'&middot; {f[3]} lines &middot; {html.escape(f[7])}</li>')
        parts.append("</ul>")
    return "".join(parts)


def folder_paths(folders):
    out = []
    for name, parent, _ in folders:
        out.append("" if parent < 0 else (out[parent] + "/" + name if out[parent] else name))
    return out


def modules():
    return [m for m in MODULES if os.path.isfile(os.path.join(HERE, f"repokuiper-{m}.js"))]


def module_tags():
    css = "".join(f'\n<link rel="stylesheet" href="repokuiper-{m}.css">' for m in modules()
                  if os.path.isfile(os.path.join(HERE, f"repokuiper-{m}.css")))
    js = "".join(f'\n<script src="repokuiper-{m}.js"></script>' for m in modules())
    return css, js


_SAFE_NAME = re.compile(r"^[A-Za-z0-9_.-]+\.json$")


def run_hooks(g, per_repo, idx, out, src=""):
    """Call each kuiper_<name>.py build(ctx); a failing hook is reported and its data left out (the mode hides).
    A module may also define cluster_index(idx, result) to regroup the index universe (K4: one folder per repo
    community); it runs before index.html/index.json are written and a failure leaves the index flat."""
    import importlib.util
    written = {}
    for m in tuple(MODULES) + LATE_HOOKS:
        path = os.path.join(HERE, f"kuiper_{m}.py")
        if not os.path.isfile(path):
            continue
        try:
            spec = importlib.util.spec_from_file_location(f"kuiper_{m}", path)
            mod = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(mod)
            res = mod.build({"graph": g, "per_repo": per_repo, "index": idx, "slug": slug, "out": out,
                             "extras_dir": os.path.dirname(HERE), "src": src}) or {}
            for fname, obj in sorted(res.items()):
                if not _SAFE_NAME.match(fname) or fname in ("index.json",) or any(fname == slug(r) + ".json" for r in per_repo):
                    raise ValueError(f"refusing output name {fname!r}")
                with open(os.path.join(out, fname), "w", encoding="utf-8") as fh:
                    json.dump(obj, fh, separators=(",", ":"), ensure_ascii=False, sort_keys=True)
                written[fname] = m
            if hasattr(mod, "cluster_index") and "index.galaxy.json" in res:
                trial = json.loads(json.dumps(idx))
                mod.cluster_index(trial, res["index.galaxy.json"])
                assert len(trial["files"]) == len(idx["files"])
                assert all(trial["folders"][i][1] < i for i in range(1, len(trial["folders"])))
                idx.clear()
                idx.update(trial)
        except Exception as e:  # noqa: BLE001 - a module's data is optional by contract
            print(f"repokuiper: warning: module {m} data hook failed ({type(e).__name__}: {e}); its mode stays hidden",
                  file=sys.stderr)
    return written


def write_page(out, name, d, is_index=False):
    if is_index:
        c = d["counts"]
        line1 = (f"<b>Every repository its own Kuiper</b> &middot; {c['repos']} repositories &middot; "
                 f"{c['files']:,} files &middot; {c['lines']:,} lines &middot; {c['reachable']:,} reachable "
                 f"&middot; {c['functions']:,} functions &middot; tap a body, then open its Kuiper")
        items = "".join(f'<li><a href="{f[14]}">{html.escape(f[0])}</a> &middot; {html.escape(f[8][:120])}</li>'
                        for f in d["files"])
        nolist = f"<ul>{items}</ul>"
        title, h1 = "Repository Kuipers", "Every repository its own Kuiper"
        up = ""
        desc = f"{c['repos']} repositories, each drawn as its own Kuiper universe."
    else:
        line1 = header_line(d)
        nolist = noscript_list(d)
        title = f"{d['repo']} Kuiper"
        h1 = f"{d['repo']} @ {d['commit'][:7]}"
        up = '<a id="up" href="index.html">all repos</a>'
        desc = f"Kuiper universe of {d['repo']}: {d['counts']['files']} files placed by permanent ordinal."
    mod_css, mod_js = module_tags()
    page = PAGE.format(mod_css=mod_css, mod_js=mod_js, title=html.escape(title), desc=html.escape(desc), json=name + ".json",
                       is_index="1" if is_index else "0", aria=html.escape(title + ": canvas universe"),
                       line1=line1, up=up, law_title="No claim without a key; no position without an ordinal.",
                       cut=html.escape(d["cut"]), law=html.escape(d["law"]), h1=html.escape(h1), nolist=nolist)
    with open(os.path.join(out, name + ".html"), "w", encoding="utf-8") as fh:
        fh.write(page)
    with open(os.path.join(out, name + ".json"), "w", encoding="utf-8") as fh:
        json.dump(d, fh, separators=(",", ":"), ensure_ascii=False, sort_keys=False)


def build(graph_path=DEFAULT_GRAPH, src=DEFAULT_SRC, out=DEFAULT_OUT, repos=None, graph=None):
    g = graph if graph is not None else json.load(open(graph_path, encoding="utf-8"))
    os.makedirs(out, exist_ok=True)
    roles = [[r["id"], r["title"], r["colour"]] for r in g["roles"]]
    role_ix = {r[0]: i for i, r in enumerate(roles)}
    if "other" not in role_ix:
        role_ix["other"] = len(roles)
        roles.append(["other", "Other", "#4c5a65"])
    kinds = sorted({e[2] for e in g["edges"]})
    kind_ix = {k: i for i, k in enumerate(kinds)}
    sec_url = {s["section"]: s["url"] for s in g["sections"]}
    by_repo = defaultdict(list)
    for f in g["files"]:
        by_repo[f["repo"]].append(f)
    edges_by_src = defaultdict(list)
    for e in g["edges"]:
        edges_by_src[e[0]].append(e)
    per_repo = {}
    for meta in g["repos"]:
        repo = meta["repo"]
        if repos and repo not in repos:
            continue
        if meta.get("visibility", "public") != "public" or not by_repo.get(repo):
            continue
        blobs = git_blobs(src, repo, meta["commit"]) if src else {}
        d = repo_data(g, repo, by_repo[repo], edges_by_src, sec_url, role_ix, kind_ix, blobs)
        d["roles"], d["kinds"] = roles, kinds
        per_repo[repo] = d
        write_page(out, slug(repo), d)
    idx = index_data(g, per_repo, role_ix)
    idx["roles"], idx["kinds"] = roles, kinds
    run_hooks(g, per_repo, idx, out, src)
    write_page(out, "index", idx, is_index=True)
    assets = ["repokuiper.js", "repokuiper.css"]
    for m in modules():
        assets += [a for a in (f"repokuiper-{m}.js", f"repokuiper-{m}.css") if os.path.isfile(os.path.join(HERE, a))]
    for asset in assets:
        shutil.copyfile(os.path.join(HERE, asset), os.path.join(out, asset))
    return per_repo


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--graph", default=DEFAULT_GRAPH)
    ap.add_argument("--src", default=DEFAULT_SRC, help="directory of git clones for blob ids ('' to skip)")
    ap.add_argument("--out", default=DEFAULT_OUT)
    ap.add_argument("--repo", action="append", help="only these repositories (repeatable)")
    a = ap.parse_args(argv)
    if not os.path.isfile(a.graph):
        sys.exit(f"repokuiper: build_graph.json not found at {a.graph!r}; pass --graph or set EXPLORE_GRAPH")
    try:
        with open(a.graph, encoding="utf-8") as fh:
            g = json.load(fh)
    except ValueError as e:
        sys.exit(f"repokuiper: {a.graph} is not valid JSON ({e})")
    missing = [k for k in ("files", "edges", "repos", "roles", "sections") if not isinstance(g.get(k), list)]
    if missing: