GLOBALGRID2050 / EXPLORE CODE

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

Kuiper Overlays and 1 more file

A Python command-line tool in the repokuiper folder of Cosmic that reads communities, drift, clarity and periodic, using SHA-256.

659 lines of Python from cosmic, in 2 files. Topic: Kuiper, cosmos and drawing engines. Section 1128 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. Kuiper Galaxy transform · cosmic / tools/explore/repokuiper/kuiper_galaxy.py lines 1–219
  2. Kuiper Overlays ingest · cosmic / tools/explore/repokuiper/kuiper_overlays.py lines 1–440

Kuiper Galaxy

A Python module in the repokuiper folder of Cosmic that works with cluster index (`cluster_index`) (units: kV), using SHA-256.

transformcosmic / tools/explore/repokuiper/kuiper_galaxy.py · lines 1–219 of 219 · Not reached from any entry point (candidate for review) · pattern ordinal (shared by 4 files)

What it does
It calculates its inputs. Defines 9 functions or classes, including ordinal, _pair_weights, communities, _commit, tour. Uses libraries __future__, hashlib, collections.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file index.galaxy.json.
Downstream impact
Used directly by 1 file: Test Repokuiper Galaxy (cosmic).
What it achieves
It is built from the ordinal step (`ordinal`), the communities step (`communities`) and the tour step (`tour`). The estate galaxy for `kuiper/index.html` (K4 build hook, contract v1 section 2).
Why it matters
Checked by Test Repokuiper Galaxy.
Application
cosmic · tools/explore/repokuiper · Python module
Uses
__future__, hashlib, collections
Used by
imported by Test Repokuiper Galaxy (import)
Produces
ordinal, communities, tour, galaxy, cluster_index, build
Defines here
ordinal, _pair_weights, communities, _commit, tour, _folder_paths, galaxy, cluster_index, build
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/kuiper_galaxy.py:1-219 · blob 142fad540091af72d93140f47bd34b82774cc854 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
"""kuiper_galaxy: the estate galaxy for kuiper/index.html (K4 build hook, contract v1 section 2).

    build(ctx) -> {"index.galaxy.json": {...}}

Everything comes from the build cut in ctx (the explore-build-graph-v1 dict and the per-repo data build.py made):
no network, no other source, no code text (photon rule), no stored positions (placement law).

  communities  repositories that link to each other, found by greedy modularity (Clauset-Newman-Moore) on the
               count of resolved cross-repository edges; ties broken by name, so the same cut gives the same groups.
               A group is named after its hub (the member with the most cross-repository edges). Repositories with
               no cross-repository edge share one group, "standalone".
  arcs         one per linked pair of repositories: [a, b, edges a->b, edges b->a, commonest kind, example key]
               where the example key names one real edge as "<repo>/<path> -> <repo>/<path>".
  tour         5-8 stops, each a plain sentence plus the key that backs it (Kuiper's first law).

cluster_index(index, galaxy) is for build.py (K1): it turns the communities into the index page's folders, so the
core engine places each group by the ordinal of its name and each repository by the ordinal of its own name inside
it, with the same law as every other Kuiper. Without it the index stays one flat disc and the galaxy still works.
"""
from __future__ import annotations

import hashlib
from collections import Counter, defaultdict

SCHEMA = "repokuiper-galaxy-v1"
RULES = ("galaxy-communities-v1: greedy modularity (Clauset-Newman-Moore) on resolved cross-repository edge counts "
         "(all edge kinds, both directions summed), merge while modularity rises, ties by name; hub = member with the "
         "most cross-repository edges; repositories with none share the group 'standalone'")
STANDALONE = "standalone"


def ordinal(s: str) -> int:
    return int(hashlib.sha256(s.encode("utf-8")).hexdigest()[:8], 16)


def _pair_weights(graph, repos):
    """{(a, b): n} undirected, a < b, plus directed counts, kinds and one example edge per direction."""
    by_id = {f["id"]: f for f in graph.get("files", [])}
    und, dirc, kinds, ex = Counter(), Counter(), defaultdict(Counter), {}
    for e in graph.get("edges", []):
        fa, fb = by_id.get(e[0]), by_id.get(e[1])
        if not fa or not fb:
            continue
        ra, rb = fa["repo"], fb["repo"]
        if ra == rb or ra not in repos or rb not in repos:
            continue
        p = (ra, rb) if ra < rb else (rb, ra)
        und[p] += 1
        dirc[(ra, rb)] += 1
        kinds[p][e[2]] += 1
        k = (ra, rb)
        cand = (fa["path"], fb["path"])
        if k not in ex or cand < ex[k]:          # smallest path pair: stable across runs
            ex[k] = cand
    return und, dirc, kinds, ex


def communities(und, repos):
    """Greedy modularity merge. Returns [[label, hub, [members sorted]], ...] largest first, standalone last."""
    deg = Counter()
    for (a, b), n in und.items():
        deg[a] += n
        deg[b] += n
    linked = sorted(r for r in repos if deg[r])
    m = float(sum(und.values()))
    com = {r: r for r in linked}
    members = {r: {r} for r in linked}
    while m > 0:
        tot = {c: sum(deg[x] for x in ms) for c, ms in members.items()}
        between = Counter()
        for (a, b), n in und.items():
            ca, cb = com[a], com[b]
            if ca != cb:
                between[(ca, cb) if ca < cb else (cb, ca)] += n
        best = None
        for (c1, c2) in sorted(between):
            dq = between[(c1, c2)] / m - tot[c1] * tot[c2] / (2 * m * m)
            if dq > 1e-12 and (best is None or dq > best[0] + 1e-12):
                best = (dq, c1, c2)
        if best is None:
            break
        _, c1, c2 = best
        for x in members[c2]:
            com[x] = c1
        members[c1] |= members.pop(c2)
    groups = []
    for ms in members.values():
        hub = sorted(ms, key=lambda r: (-deg[r], r))[0]
        groups.append([hub, hub, sorted(ms)])
    groups.sort(key=lambda g: (-len(g[2]), g[1]))
    alone = sorted(r for r in repos if not deg[r])
    if alone:
        groups.append([STANDALONE, "", alone])
    return groups, deg


def _commit(graph, repo):
    for r in graph.get("repos", []):
        if r["repo"] == repo:
            return r.get("commit", "")
    return ""


def tour(graph, per_repo, groups, arcs, deg):
    """5-8 stops. Each: {kind, target, text, key}. Targets are names/paths, never indices or positions."""
    cut = graph.get("cut", "")
    nfiles = sum(d["counts"]["files"] for d in per_repo.values())
    nlines = sum(d["counts"]["lines"] for d in per_repo.values())
    nreach = sum(d["counts"]["reachable"] for d in per_repo.values())
    stops = [{
        "kind": "galaxy", "target": "", "title": "The whole estate",
        "text": f"Each star here is one public repository: {len(per_repo)} of them, {nfiles:,} files and "
                f"{nlines:,} lines. A star's place comes from the sha256 of its name, so it never moves when others change.",
        "key": f"build cut {cut}; k = sha256(repository name)[:32 bits]"}]
    linked = [g for g in groups if g[0] != STANDALONE]
    if linked:
        g = max(linked, key=lambda g: (sum(per_repo[r]["counts"]["files"] for r in g[2]), g[1]))
        inside = sum(a[2] + a[3] for a in arcs if a[0] in g[2] and a[1] in g[2])
        stops.append({
            "kind": "cluster", "target": g[0], "title": "Repositories that link gather together",
            "text": f"Repositories that link to each other sit in one group. The {g[0]} group holds {len(g[2])} "
                    f"repositories joined by {inside:,} links between them.",
            "key": f"{g[1]}@{_commit(graph, g[1])[:12]} is the hub; {RULES.split(':')[0]}"})
    big = max(per_repo, key=lambda r: (per_repo[r]["counts"]["files"], r))
    c = per_repo[big]["counts"]
    stops.append({
        "kind": "repo", "target": big, "title": f"{big}, the largest",
        "text": f"{big} is the largest repository: {c['files']:,} files and {c['lines']:,} lines, "
                f"{c['reachable']:,} of them reachable from {c['entries']:,} entry points.",
        "key": f"{big}@{per_repo[big]['commit'][:12]}"})
    if arcs:
        a = max(arcs, key=lambda a: (a[2] + a[3], a[0], a[1]))
        src, dst, n = (a[0], a[1], a[2]) if a[2] >= a[3] else (a[1], a[0], a[3])
        exk = a[5] if a[2] >= a[3] else a[6]
        stops.append({
            "kind": "arc", "target": [src, dst], "title": "The brightest arc",
            "text": f"Faint arcs join repositories whose files point at each other. The brightest runs from {src} "
                    f"to {dst}: {n:,} links, mostly of the kind '{a[4]}'.",
            "key": f"{src}@{per_repo[src]['commit'][:7]} {exk.split(' -> ')[0].split('/', 1)[1]} -> "
                   f"{dst}@{per_repo[dst]['commit'][:7]} {exk.split(' -> ')[1].split('/', 1)[1]}"})
    # a file deep inside the largest repository: the one reached from the most entry points
    d = per_repo[big]
    paths = _folder_paths(d["folders"])
    best = max(range(len(d["files"])), key=lambda i: (d["files"][i][10] or 0, -i)) if d["files"] else None
    if best is not None:
        f = d["files"][best]
        p = (paths[f[1]] + "/" if paths[f[1]] else "") + f[0]
        stops.append({
            "kind": "file", "target": [big, p], "title": "Inside a repository",
            "text": f"Zoom into a star and it opens into folders and files. {f[0]} is reached from {f[10]:,} entry "
                    f"points, more than any other file in {big}.",
            "key": f"{big}@{d['commit'][:12]} {p}:1-{f[3]}" + (f" blob {f[9]}" if f[9] else "")})
    if nfiles - nreach:
        # the repository with most unreached files, other than the largest (already a stop) when there is a choice
        pool = [r for r in per_repo if r != big and per_repo[r]["counts"]["files"] > per_repo[r]["counts"]["reachable"]]
        dim = max(pool or [big], key=lambda r: (per_repo[r]["counts"]["files"] - per_repo[r]["counts"]["reachable"], r))
        u = per_repo[dim]["counts"]["files"] - per_repo[dim]["counts"]["reachable"]
        stops.append({
            "kind": "repo", "target": dim, "title": "Dim stars",
            "text": f"Dim bodies are files that no entry point reaches: {nfiles - nreach:,} of {nfiles:,} in the estate. "
                    f"{dim} holds {u:,} of them.",
            "key": f"reachable flag in build_graph.json, cut {cut}; {dim}@{per_repo[dim]['commit'][:12]}"})
    # stop 7 (a real place) is added in the browser from Drone View's own places.json when it loads
    stops.append({
        "kind": "end", "target": "", "title": "Your turn",
        "text": "Tap any star for its card, pinch or scroll to zoom, drag to pan, back to pull out. "
                "Keys: w tour, g arcs, f find, r random star, e edges, l names, h home.",
        "key": "every card shows its key: repository@commit, path, blob and ordinal"})
    return stops[:8]


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 galaxy(graph, per_repo):
    repos = set(per_repo)
    und, dirc, kinds, ex = _pair_weights(graph, repos)
    groups, deg = communities(und, repos)
    arcs = []
    for (a, b) in sorted(und):
        kind = sorted(kinds[(a, b)].items(), key=lambda kv: (-kv[1], kv[0]))[0][0]
        exa = ex.get((a, b))
        exb = ex.get((b, a))
        arcs.append([a, b, dirc[(a, b)], dirc[(b, a)], kind,
                     f"{a}/{exa[0]} -> {b}/{exa[1]}" if exa else "", f"{b}/{exb[0]} -> {a}/{exb[1]}" if exb else ""])
    return {
        "schema": SCHEMA, "cut": graph.get("cut", ""), "rules": RULES,
        "fields": {"communities": ["label", "hub", "members"],
                   "arcs": ["a", "b", "edges a->b", "edges b->a", "commonest kind", "example a->b", "example b->a"]},
        "communities": groups, "degree": {r: deg[r] for r in sorted(repos) if deg[r]},
        "arcs": arcs, "tour": tour(graph, per_repo, groups, arcs, deg),
    }


def cluster_index(index, gal):
    """For build.py: make each community a folder of the index universe (key = ordinal('group:' + label)) and put
    each repository in its group. Positions stay computed from ordinals in the browser; nothing is stored."""
    where = {}
    folders = [["", -1, 0]]
    for label, _hub, members in gal["communities"]:
        folders.append([label, 0, ordinal("group:" + label)])
        for r in members:
            where[r] = len(folders) - 1
    for f in index["files"]:
        f[1] = where.get(f[0], 0)
    index["folders"] = folders
    index["band"] = [0.08, 0.86]
    index["law"] = ("k = sha256(name)[:32 bits]; u = k/2^32; theta = frac(k*0.6180339887498949)*2pi; group k from "
                    "'group:'+label, d = R0*(0.44+0.40*sqrt(u)), R = 0.24*R0; repository d = R*(0.08+0.86*sqrt(u)); R0 = 1000")
    return index


def build(ctx):
    gal = galaxy(ctx["graph"], ctx["per_repo"])
    return {"index.galaxy.json": gal}

Kuiper Overlays

A Python command-line tool in the repokuiper folder of Cosmic that reads communities, drift, clarity and periodic, using SHA-256.

ingestcosmic / tools/explore/repokuiper/kuiper_overlays.py · lines 1–440 of 440 · Entry point · pattern _exists (shared by 3 files)

What it does
It loads communities, drift, clarity and periodic. Defines 21 functions or classes, including _vis, _load, _exists, _key, Join. Uses libraries __future__, argparse, json, os, subprocess. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file communities.json; JSON file drift.json; JSON file clarity.json; JSON file periodic.json; JSON file importance.json; JSON file keys.json; JSON file identity-files.json; JSON file dictionary.json.
Downstream impact
Used directly by 3 files: Extras (cosmic); Test Repokuiper (cosmic); Test Repokuiper Overlays (cosmic). Reached from 3 other entry points, including Ship (cosmic); Test Extras (cosmic); Test Ship (cosmic).
What it achieves
It indexes modes (`index_modes`) and is built from the join class (`Join`) and the column step (`column`). Intelligence overlays for every repository Kuiper (K3, ALBEDO-47). It accepts `--graph`, `--site` and `--out`.
Why it matters
Run by Extras. Checked by 2 tests, including Test Repokuiper.
Application
cosmic · tools/explore/repokuiper · Python CLI
Uses
__future__, argparse, json, os, subprocess, sys, collections, visualise
Used by
run by Extras (script call), imported by Test Repokuiper (import), imported by Test Repokuiper Overlays (import)
Produces
Join, mode_community, mode_drift, mode_clarity, mode_periodic, mode_importance, mode_identity, vedic_ids, faraday, index_modes, build, main
Defines here
_vis, _load, _exists, _key, Join, __init__, column, _cats_local, mode_community, mode_drift, mode_clarity, mode_periodic, mode_importance, mode_identity, vedic_ids, faraday, index_modes, share, build, put, 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/kuiper_overlays.py:1-440 · blob 4b69b592c2d8b157e41f890b83a8248169d4d676 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: unknown
#!/usr/bin/env python3
"""kuiper_overlays: intelligence overlays for every repository Kuiper (K3, ALBEDO-47).

Build hook of the Kuiper-4 plugin contract: build(ctx) -> {filename: JSON object}. For each repository it writes
<slug>.overlays.json (a manifest: titles, legends, keys) and, per mode, <slug>.ov-<mode>.json, fetched only when
that mode is chosen; index.overlays.json (inline) serves the estate page. Every mode is a small per-body column (index =
position of the body in <slug>.json's files list) plus its own legend and the key of its source:

    community  lab communities (lab/communities.json, matched through lab/keys.json)
    drift      near-copy families and links (lab/drift.json; CANDIDATE)
    clarity    unique / copy / via / unreached (clarity/clarity.json)
    identity   unique / family-shared / near-copy-of verdicts (identity/identity-files.json)
    words      VEDIC words of the file's function clusters (identity-files.json 'vedic' candidates), with the
               GG2050-VEDIC id from vedic-@<graph commit>:data/dictionary.json where one exists (needs --src clones)
    element    periodic element of the code (periodic/periodic.json)
    importance size by lab importance (lab/importance.json)
    faraday    the measured Faraday rate (laws/laws.json law FA, only when it HOLDS)

Kuiper's first law: a mode is emitted only when its source lines up with the graph (same cut, or lab keys that name
repo@commit:path); otherwise it is left out and the page hides it. Photon rule: ids, short labels, numbers; never
code text. Positions are never stored. Readers are reused from tools/explore/visualise.py where they exist.

Standalone (to refresh after later extras have run):  python3 kuiper_overlays.py --graph G --site S [--out S/kuiper]
"""
from __future__ import annotations

import argparse
import json
import os
import subprocess
import sys
from collections import Counter, defaultdict

HERE = os.path.dirname(os.path.abspath(__file__))
SCHEMA = 'repokuiper-overlays-v1'
MAX_WORDS = 3
DIM = '#2f343d'
OTHER = '#4c5a65'  # every category past the site palette
CLARITY_COLOURS = {'core': '#00ff88', 'copy': '#ffae00', 'via': '#66ccff', 'unreached': '#4c5a65'}
VERDICTS = [['unique', 'Unique', '#00ffff'], ['family-shared', 'Shares function families', '#66ccff'],
            ['near-copy-of', 'Near copy of another file', '#ffae00']]
WORD_COLOURS = ['#4c5a65', '#66ccff', '#00ffff', '#ffffff']  # 0 words .. 3 words


def _vis(extras_dir):
    """tools/explore/visualise.py, for its tested readers (lab, clarity, periodic, laws). None if unavailable."""
    for d in (extras_dir, os.path.dirname(HERE)):
        if d and os.path.isfile(os.path.join(d, 'visualise.py')):
            if d not in sys.path:
                sys.path.insert(0, d)
            try:
                import visualise  # noqa: E402
                return visualise
            except Exception as e:  # a broken sibling must not break the Kuiper build
                print('kuiper_overlays: visualise.py not importable (%s)' % e, file=sys.stderr)
                return None
    return None


def _load(p):
    try:
        with open(p, encoding='utf-8') as fh:
            return json.load(fh)
    except (OSError, ValueError):
        return None


def _exists(p):
    return bool(p) and os.path.exists(p)


def _key(site, rel, cut):
    return {'source': rel, 'cut': cut or ''}


class Join:
    """graph file id -> (repo, body index in <slug>.json). Bodies are sorted by path, as build.py writes them."""

    def __init__(self, g, per_repo):
        by = defaultdict(list)
        for gid, f in enumerate(g['files']):
            if f.get('repo') in per_repo:
                by[f['repo']].append((f['path'], gid))
        self.map = {}
        self.n = {}
        for repo, lst in by.items():
            lst.sort()
            names = [b[0] for b in per_repo[repo]['files']]
            if len(lst) != len(names) or any(p.rpartition('/')[2] != n for (p, _), n in zip(lst, names)):
                print('kuiper_overlays: %s bodies do not line up with the graph; skipped' % repo, file=sys.stderr)
                continue
            self.n[repo] = len(lst)
            for i, (_, gid) in enumerate(lst):
                self.map[gid] = (repo, i)

    def column(self, col, default=-1):
        """Graph-indexed column -> {repo: [value per body]}."""
        out = {r: [default] * n for r, n in self.n.items()}
        for gid, v in enumerate(col):
            hit = self.map.get(gid)
            if hit:
                out[hit[0]][hit[1]] = v
        return out


def _cats_local(col_by_repo, cats, palette, pattern):
    """Per repo: renumber categories to those present, largest first; the largest get the site palette."""
    res = {}
    for repo, col in col_by_repo.items():
        cnt = Counter(v for v in col if v >= 0)
        if not cnt:
            continue
        order = [c for c, _ in sorted(cnt.items(), key=lambda kv: (-kv[1], kv[0]))]
        ix = {c: k for k, c in enumerate(order)}
        leg = []
        for k, c in enumerate(order):
            colour = palette[k] if k < len(palette) else OTHER  # few colours: fewer canvas batches, readable legend
            leg.append([cats[c][0], colour, cnt[c]])
        res[repo] = (leg, [ix.get(v, -1) for v in col], order)
    return res


def mode_community(vis, lab, g, J, pal):
    ov = vis.read_lab(lab, g).get('community') if vis else None
    if not ov:
        return {}
    out = {}
    hub_of = {k: c[2] for k, c in enumerate(ov['cats'])}
    for repo, (leg, v, order) in _cats_local(J.column(ov['v']), ov['cats'], pal,
                                             lambda c: vis.pattern_colour('community:%d' % c)).items():
        for k, c in enumerate(order):
            hit = J.map.get(hub_of.get(c, -1))
            leg[k].append(hit[1] if hit and hit[0] == repo else -1)  # hub body inside this repository, else -1
        out[repo] = {'title': 'Lab communities', 'state': 'measurement', 'legend': leg, 'v': v,
                     'key': _key(None, 'lab/communities.json', ov.get('cut')), 'rules': ov.get('rules', '')[:160]}
    return out


def mode_drift(vis, lab, g, J, pal):
    ov = vis.read_lab(lab, g).get('drift') if vis else None
    if not ov:
        return {}
    fam = J.column(ov['fam'])
    links, outside = defaultdict(list), defaultdict(Counter)
    e = ov['e']
    for k in range(0, len(e) - 2, 3):
        a, b, s = J.map.get(e[k]), J.map.get(e[k + 1]), e[k + 2]
        if a and b and a[0] == b[0]:
            links[a[0]].append([a[1], b[1], int(s)])
        else:
            for x, y in ((a, b), (b, a)):
                if x and y:
                    outside[x[0]][(x[1], y[0])] += 1
    safe = defaultdict(list)
    for gid in ov.get('safe') or []:
        hit = J.map.get(gid)
        if hit:
            safe[hit[0]].append(hit[1])
    out = {}
    cats = defaultdict(lambda: ['family'])
    for repo, (leg, v, order) in _cats_local(fam, cats, pal, lambda c: vis.pattern_colour('family:%d' % c)).items():
        for k, c in enumerate(order):
            leg[k][0] = 'family %d' % c
        xs = sorted([i, r, n] for (i, r), n in outside[repo].items())
        out[repo] = {'title': 'Near-copy drift', 'state': 'CANDIDATE', 'legend': leg, 'v': v,
                     'links': sorted(links[repo]), 'outside': xs, 'safe': sorted(safe[repo]),
                     'key': _key(None, 'lab/drift.json', ov.get('cut')), 'rules': ov.get('rules', '')[:160]}
    return out


def mode_clarity(vis, p, g, J):
    ov = vis.read_clarity(p, g) if vis and _exists(p) else None
    if not ov:
        return {}
    out = {}
    for repo, v in J.column(ov['v']).items():
        cnt = Counter(x for x in v if x >= 0)
        if not cnt:
            continue
        leg = [[c[0], c[1], cnt.get(k, 0)] for k, c in enumerate(ov['cats'])]
        out[repo] = {'title': 'Clarity', 'state': 'measurement', 'legend': leg, 'v': v,
                     'key': _key(None, 'clarity/clarity.json', ov.get('cut'))}
    return out


def mode_periodic(vis, p, g, J):
    ov = vis.read_periodic(p, g) if vis and _exists(p) else None
    if not ov:
        return {}
    out = {}
    per_ix = {c[2]: k for k, c in enumerate(ov['cats'])}
    for repo, col in J.column(ov['v']).items():
        used = sorted({x for x in col if x >= 0})
        if not used:
            continue
        ix = {e: k for k, e in enumerate(used)}
        els = [[x[0], x[1], str(x[2])[:40], x[3], x[4]] for x in (ov['els'][e] for e in used)]  # sym,num,title,period,status
        v = [ix.get(x, -1) for x in col]
        cnt = Counter(ov['els'][x][3] for x in col if x >= 0)
        leg = [[c[0], c[1], cnt.get(c[2], 0)] for c in ov['cats'] if cnt.get(c[2])]
        lix = {c[0]: k for k, c in enumerate(leg)}
        pc = [lix[ov['cats'][per_ix[e[3]]][0]] for e in els]  # element -> legend row (its period)
        out[repo] = {'title': 'Periodic element', 'state': 'measurement; CANDIDATE where marked', 'legend': leg,
                     'v': v, 'els': els, 'el_row': pc, 'key': _key(None, 'periodic/periodic.json', ov.get('cut'))}
    return out


def mode_importance(vis, lab, g, J):
    d = _load(os.path.join(lab, 'importance.json'))
    if not d or not vis:
        return {}
    keys = (_load(os.path.join(lab, 'keys.json')) or {}).get('k')
    al = vis.aligner(g, d.get('cut'), int(d.get('n') or 0) or None, keys)
    cols = d.get('cols') or {}
    pr, bt = cols.get('pr') or [], cols.get('bt') or []
    if al is None or not pr:
        return {}
    col = [-1] * len(g['files'])
    for i in range(len(pr)):
        j = al(i)
        if j is not None:
            col[j] = max(int(pr[i] or 0), int(bt[i] or 0) if i < len(bt) else 0)
    out = {}
    for repo, v in J.column(col).items():
        if max(v) <= 0:
            continue
        out[repo] = {'title': 'Importance (size)', 'state': 'measurement', 'size': True,
                     'legend': [['least important', '#2f343d', 0], ['most important', '#00ffff', 1000]], 'v': v,
                     'key': _key(None, 'lab/importance.json', d.get('cut')), 'rules': (d.get('scale') or '')[:120]}
    return out


def mode_identity(p, g, J, src=None):
    d = _load(p) if _exists(p) else None
    # full identity writes graph.cut; lite identity (CI without the full genome inputs) writes graph_cut
    if not d or ((d.get('graph') or {}).get('cut') or d.get('graph_cut')) != g.get('cut'):
        if d:
            print('kuiper_overlays: identity is from another cut; identity and words left out', file=sys.stderr)
        return {}, {}
    vix = {v[0]: k for k, v in enumerate(VERDICTS)}
    vids, vkey = vedic_ids(g, src)
    ident, words = {}, {}
    cols = {r: {'v': [-1] * n, 'sim': [0] * n, 'of': {}, 'w': [[] for _ in range(n)]} for r, n in J.n.items()}
    for sid, f in (d.get('files') or {}).items():
        hit = J.map.get(int(sid))
        if not hit:
            continue
        c = cols[hit[0]]
        ver = f.get('verdict') or {}
        c['v'][hit[1]] = vix.get(ver.get('verdict'), -1)
        if ver.get('similarity'):
            c['sim'][hit[1]] = int(round(100 * float(ver['similarity'])))
        of = J.map.get(ver.get('of_file')) if isinstance(ver.get('of_file'), int) else None
        if of:
            c['of'][hit[1]] = [of[0] if of[0] != hit[0] else '', of[1]]
        cand = sorted((f.get('vedic') or {}).get('candidates') or [], key=lambda x: -float(x.get('score') or 0))
        seen = []
        for x in cand:
            w = str(x.get('word') or '').strip().upper()[:32]
            if w and w not in seen:
                seen.append(w)
            if len(seen) >= MAX_WORDS:
                break
        c['w'][hit[1]] = seen
    key = {'source': 'identity/identity-files.json', 'cut': g.get('cut', ''),
           'graph_sha256': (d.get('graph') or {}).get('sha256', '')}
    for repo, c in cols.items():
        cnt = Counter(x for x in c['v'] if x >= 0)
        if cnt:
            ident[repo] = {'title': 'Identity', 'state': 'measurement',
                           'legend': [[t, col, cnt.get(k, 0)] for k, (_, t, col) in enumerate(VERDICTS)],
                           'v': c['v'], 'sim': c['sim'], 'of': sorted([i] + o for i, o in c['of'].items()), 'key': key}
        dic, fw = [], []
        dix = {}
        for ws in c['w']:
            row = []
            for w in ws:
                if w not in dix:
                    dix[w] = len(dic)
                    dic.append([w, vids.get(w, '')])  # VEDIC word and its GG2050-VEDIC id where the dictionary has one
                row.append(dix[w])
            fw.append(row)
        if dic:
            n = Counter(len(r) for r in fw)
            words[repo] = {'title': 'VEDIC words', 'state': 'CANDIDATE: VEDIC words for this file\'s function clusters',
                           'legend': [['%d word%s' % (k, '' if k == 1 else 's'), WORD_COLOURS[k], n.get(k, 0)]
                                      for k in range(MAX_WORDS + 1)],
                           'v': [len(r) for r in fw], 'dict': dic, 'fw': fw, 'key': key}
            if vkey:
                words[repo]['ids_key'] = vkey
    return ident, words


VEDIC_REPO = 'vedic-'
VEDIC_DICT = 'data/dictionary.json'


def vedic_ids(g, src):
    """VEDIC dictionary word -> GG2050-VEDIC id, read from the vedic- clone AT THE GRAPH'S COMMIT (same cut,
    read-only `git show`). Returns ({}, None) when there is no clone or no dictionary at that commit."""
    meta = next((r for r in g.get('repos') or [] if r.get('repo') == VEDIC_REPO), None)
    path = os.path.join(src or '', VEDIC_REPO)
    if not meta or not src or not os.path.isdir(path):
        return {}, None
    try:
        raw = subprocess.run(['git', '-C', path, 'show', '%s:%s' % (meta['commit'], VEDIC_DICT)],
                             capture_output=True, check=True, timeout=60).stdout
        d = json.loads(raw.decode('utf-8'))
    except (subprocess.SubprocessError, OSError, ValueError):
        return {}, None
    ids = {}
    for e in d.get('entries') or []:
        w, gid = str(e.get('word') or '').strip().upper(), str(e.get('gg_id') or '')
        if w and gid.startswith('GG2050-VEDIC-') and w not in ids:
            ids[w] = gid
    return ids, {'source': '%s@%s:%s' % (VEDIC_REPO, meta['commit'], VEDIC_DICT), 'cut': g.get('cut', '')}


def faraday(vis, p, g):
    if not vis or not _exists(p):
        return None
    try:
        fa = vis.read_faraday(p, g)
    except (OSError, ValueError, KeyError, TypeError):
        return None
    if not fa or fa.get('cut') != g.get('cut'):
        return None  # same build cut or nothing
    return {'title': 'Faraday pulse', 'state': 'law HOLDS (analogy, not physics)', 'k': fa['k'], 'n': fa['n'],
            'p': fa['p'], 'lift': fa.get('lift'), 'law': str(fa.get('law') or '')[:160],
            'key': {'source': 'laws/laws.json FA', 'cut': fa.get('cut', '')}}


def index_modes(per_repo_modes, index):
    """Estate page: one aggregate per repository body (bodies are repositories, in index.json order)."""
    repos = [b[0] for b in index.get('files') or []]
    modes = {}

    def share(mode, good, title, legend_title):
        vals = []
        for r in repos:
            m = per_repo_modes.get(r, {}).get(mode)
            if not m:
                vals.append(-1)
                continue
            n = sum(1 for x in m['v'] if x >= 0)
            vals.append(int(round(100 * sum(1 for x in m['v'] if x == good) / n)) if n else -1)
        if any(v >= 0 for v in vals):
            src = next(per_repo_modes[r][mode]['key'] for r in repos if mode in per_repo_modes.get(r, {}))
            modes[mode] = {'title': title, 'state': 'measurement', 'pct': True, 'v': vals, 'key': src,
                           'legend': [[legend_title + ' 0%', '#2f343d', 0], [legend_title + ' 100%', '#00ffff', 100]]}

    share('identity', 0, 'Identity: share of unique files', 'unique')
    share('clarity', 0, 'Clarity: share unique and in use', 'core')
    return modes


def build(ctx):
    g, per_repo, out = ctx['graph'], ctx['per_repo'], ctx.get('out') or ''
    slug = ctx.get('slug') or (lambda r: r.lower())
    site = ctx.get('site') or os.path.dirname(os.path.abspath(out))
    vis = _vis(ctx.get('extras_dir'))
    J = Join(g, per_repo)
    pal = list(getattr(vis, 'TOPIC_COLOURS', ['#00ffff', '#66ccff', '#ffffff']))
    lab = os.path.join(site, 'lab')
    modes = defaultdict(dict)

    def put(name, res):
        for repo, m in res.items():
            modes[repo][name] = m

    steps = [
        ('community', lambda: mode_community(vis, lab, g, J, pal) if os.path.isdir(lab) else {}),
        ('drift', lambda: mode_drift(vis, lab, g, J, pal) if os.path.isdir(lab) else {}),
        ('clarity', lambda: mode_clarity(vis, os.path.join(site, 'clarity', 'clarity.json'), g, J)),
        ('element', lambda: mode_periodic(vis, os.path.join(site, 'periodic', 'periodic.json'), g, J)),
        ('importance', lambda: mode_importance(vis, lab, g, J) if os.path.isdir(lab) else {}),
    ]
    for name, fn in steps:
        try:
            put(name, fn())
        except Exception as e:  # one bad source hides one mode, never the page
            print('kuiper_overlays: %s left out (%s: %s)' % (name, type(e).__name__, e), file=sys.stderr)
    try:
        ident, words = mode_identity(os.path.join(site, 'identity', 'identity-files.json'), g, J,
                                     ctx.get('src') or os.environ.get('EXPLORE_SRC', ''))
        put('identity', ident)
        put('words', words)
    except Exception as e:
        print('kuiper_overlays: identity left out (%s: %s)' % (type(e).__name__, e), file=sys.stderr)
    fa = faraday(vis, os.path.join(site, 'laws', 'laws.json'), g)
    files = {}
    for repo in per_repo:
        man = {}
        for name, m in sorted(modes.get(repo, {}).items()):
            fn = '%s.ov-%s.json' % (slug(repo), name)
            files[fn] = (dict(m, schema=SCHEMA, mode=name, repo=repo, n=len(per_repo[repo]['files'])))
            man[name] = {k: files[fn][k] for k in ('title', 'state', 'legend', 'key', 'size') if k in files[fn]}
            man[name]['file'] = 'ov-' + name
            if len(man[name]['legend']) > 12:  # the manifest stays small; the mode file has every row
                man[name]['legend'] = man[name]['legend'][:12] + [['%d more' % (len(m['legend']) - 12), DIM, 0]]
        if fa:
            man['faraday'] = fa
        files[slug(repo) + '.overlays.json'] = {'schema': SCHEMA, 'repo': repo, 'cut': g.get('cut', ''),
                                                'n': len(per_repo[repo]['files']), 'modes': man}
    idx = ctx.get('index')
    if idx:
        files['index.overlays.json'] = ({'schema': SCHEMA, 'repo': '', 'cut': g.get('cut', ''), 'inline': True,
                                              'n': len(idx.get('files') or []), 'modes': index_modes(modes, idx)})
    return files


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])
    ap.add_argument('--graph', required=True)
    ap.add_argument('--site', required=True, help='explore-code folder holding lab/, clarity/, identity/, periodic/')
    ap.add_argument('--out', help='kuiper folder (default <site>/kuiper)')
    ap.add_argument('--src', default=os.environ.get('EXPLORE_SRC', ''), help='folder of clones (for VEDIC ids)')
    a = ap.parse_args(argv)
    out = a.out or os.path.join(a.site, 'kuiper')
    g = _load(a.graph)
    if not g:
        sys.exit('kuiper_overlays: cannot read %s' % a.graph)
    per_repo = {}
    for meta in g.get('repos') or []:
        d = _load(os.path.join(out, meta['repo'].lower() + '.json'))
        if d and d.get('repo') == meta['repo']:
            per_repo[meta['repo']] = d
    res = build({'graph': g, 'per_repo': per_repo, 'index': _load(os.path.join(out, 'index.json')), 'out': out,
                 'site': a.site, 'src': a.src, 'extras_dir': os.path.dirname(HERE), 'slug': lambda r: r.lower()})
    big = 0
    for name, obj in res.items():
        s = json.dumps(obj, separators=(',', ':'), ensure_ascii=False)
        big = max(big, len(s))
        with open(os.path.join(out, name), 'w', encoding='utf-8') as fh:
            fh.write(s)
    print('kuiper_overlays: wrote %d files to %s; largest %d bytes' % (len(res), out, big))


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