GLOBALGRID2050 / EXPLORE CODE

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

Kuiper API and 1 more file

A Python command-line tool in the repokuiper folder of Cosmic that reads build graph, galaxy and lookup.

497 lines of Python from cosmic, in 2 files. Topic: Kuiper, cosmos and drawing engines. Section 1127 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. Build render · cosmic / tools/explore/repokuiper/build.py lines 459–471
  2. Kuiper API storage · cosmic / tools/explore/repokuiper/kuiper_api.py lines 1–484

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 459–471 of 471 (continued from section 1126) · 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
none
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:459-471 · 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
        sys.exit(f"repokuiper: {a.graph} lacks {', '.join(missing)}; is it an explore-build-graph-v1 file?")
    if a.src and not os.path.isdir(a.src):
        print(f"repokuiper: warning: --src {a.src!r} is not a folder; blob ids left out", file=sys.stderr)
        a.src = ""
    per = build(a.graph, a.src, a.out, a.repo, graph=g)
    sizes = {r: os.path.getsize(os.path.join(a.out, slug(r) + ".json")) for r in per}
    big = max(sizes, key=sizes.get) if sizes else None
    print(f"wrote {len(per)} repository Kuipers + index to {a.out}"
          + (f"; largest JSON {big} {sizes[big]:,} bytes" if big else ""))


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

Kuiper API

A Python command-line tool in the repokuiper folder of Cosmic that reads build graph, galaxy and lookup.

storagecosmic / tools/explore/repokuiper/kuiper_api.py · lines 1–484 of 484 · Entry point · pattern repo_api (shared by 2 files)

What it does
It loads build graph, galaxy and lookup. Defines 18 functions or classes, including _load, _dump, _order, _enc, Ids. Uses libraries __future__, argparse, json, os, sys. 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 build_graph.json; JSON file index.galaxy.json; JSON file lookup.json; JSON file index.json; command-line arguments.
Downstream impact
Used directly by 4 files: Extras (cosmic); Test Repokuiper (cosmic); Test Repokuiper API (cosmic); Test Repokuiper Speed (cosmic). Reached from 3 other entry points, including Ship (cosmic); Test Extras (cosmic); Test Ship (cosmic).
What it achieves
It adds llms (`add_to_llms`) and is built from the ids class (`Ids`) and the sid step (`sid`). A static, machine-readable Kuiper API so agents fly as fast as people (K5, TACHYON-29). It accepts `--graph`, `--site` and `--out`.
Why it matters
Run by Extras. Checked by 3 tests, including Test Repokuiper.
Application
cosmic · tools/explore/repokuiper · Python CLI
Uses
__future__, argparse, json, os, sys, collections, urllib.parse
Used by
run by Extras (script call), imported by Test Repokuiper (import), imported by Test Repokuiper API (import), imported by Test Repokuiper Speed (import)
Produces
Ids, repo_api, entry_points, cross_links, build, guide, llms_section, add_to_llms, main
Defines here
_load, _dump, _order, _enc, Ids, __init__, sid, ref, _overlay, _columns, repo_api, entry_points, cross_links, build, guide, llms_section, add_to_llms, 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_api.py:1-484 · blob 7624f942a5ef80b39be6ec15e2a0e745cfbfda66 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
#!/usr/bin/env python3
"""kuiper_api: a static, machine-readable Kuiper API so agents fly as fast as people (K5, TACHYON-29).

Build hook of the Kuiper plugin contract (build(ctx); it writes its own files and returns {}), also runnable alone
after the overlays refresh:  python3 kuiper_api.py --graph G --site S [--out S/kuiper]

Writes, beside the Kuiper pages (<out> = explore-code/kuiper):

    api/index.json        every repository: counts, entry points, community, cross-repository links, its API file
    api/lookup.json       path -> id per repository, VEDIC word -> ids: the one-fetch answer to "where is X"
    api/<slug>.json       every file of one repository (rows), or a manifest of api/<slug>.pN.json shards when large
    llms-kuiper.txt       the plain agent guide (where is X / what uses X / canonical copy of X in 1-2 fetches)

A file id is "<slug>:<i>", i = its body index in kuiper/<slug>.json (files sorted by path). Inside one repository
file, uses/used_by hold plain ints for the same repository and "<slug>:<i>" strings across repositories. A file's
human view is kuiper/<slug>.html#file=<path> (the deep link the canvas opens and selects).

Kuiper's first law: every row carries its key repo@commit path:1-lines (and blob when a clone was read). All data
comes from the same build cut: the graph, the per-repo Kuiper data, and the overlay/galaxy files the earlier hooks
wrote from that graph (community, Clarity, VEDIC words); a column whose source is missing or from another cut is
left out (null), never guessed. Photon rule: ids, keys, paths, short labels and numbers; no code text, no synopses.
Positions are never stored.
"""
from __future__ import annotations

import argparse
import json
import os
import sys
from collections import Counter, defaultdict
from urllib.parse import quote

SCHEMA = 'repokuiper-api-v1'
SHARD = 250                 # rows per shard when a repository file would be larger than MAX_BYTES
MAX_BYTES = 250_000
ENTRY_LIST = 8
LINK_LIST = 12
MENTION_KINDS = ('comment-url',)   # comment links are mentions, not uses (as in the graph's reachability walk)


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


def _dump(path, obj):
    s = json.dumps(obj, separators=(',', ':'), ensure_ascii=False)
    with open(path, 'w', encoding='utf-8') as fh:
        fh.write(s)
    return len(s.encode('utf-8'))


def _order(r):
    return (1, r) if isinstance(r, str) else (0, '%012d' % r)


def _enc(path):
    return '/'.join(quote(p, safe='') for p in path.split('/'))


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

    def __init__(self, g, per_repo, slug):
        by = defaultdict(list)
        for f in g['files']:
            if f.get('repo') in per_repo:
                by[f['repo']].append((f['path'], f['id']))
        self.of, self.gid, self.paths, self.slug = {}, {}, {}, slug
        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_api: %s bodies do not line up with the graph; left out' % repo, file=sys.stderr)
                continue
            self.paths[repo] = [p for p, _ in lst]
            for i, (_, gid) in enumerate(lst):
                self.of[gid] = (repo, i)
                self.gid[(repo, i)] = gid

    def sid(self, gid):
        hit = self.of.get(gid)
        return '%s:%d' % (self.slug(hit[0]), hit[1]) if hit else None

    def ref(self, gid, repo):
        """int inside the same repository, '<slug>:<i>' across."""
        hit = self.of.get(gid)
        if not hit:
            return None
        return hit[1] if hit[0] == repo else '%s:%d' % (self.slug(hit[0]), hit[1])


def _overlay(out, slug_, mode, cut):
    d = _load(os.path.join(out, '%s.ov-%s.json' % (slug_, mode)))
    if not d or (cut and (d.get('key') or {}).get('cut') not in (cut, None, '')):
        return None
    return d


def _columns(out, slug_, n, cut):
    """community / clarity labels and VEDIC words per body, from the overlay files of the same cut."""
    com, cla, words = [None] * n, [None] * n, [[] for _ in range(n)]
    keys = {}
    d = _overlay(out, slug_, 'community', cut)
    if d and len(d.get('v') or []) == n:
        leg = d['legend']
        com = [leg[v][0] if 0 <= v < len(leg) else None for v in d['v']]
        keys['community'] = d.get('key')
    d = _overlay(out, slug_, 'clarity', cut)
    if d and len(d.get('v') or []) == n:
        leg = d['legend']
        cla = [leg[v][0] if 0 <= v < len(leg) else None for v in d['v']]
        keys['clarity'] = d.get('key')
    d = _overlay(out, slug_, 'words', cut)
    if d and len(d.get('fw') or []) == n:
        dic = d.get('dict') or []
        words = [[dic[k] for k in row if 0 <= k < len(dic)] for row in d['fw']]
        keys['vedic'] = d.get('key')
        if d.get('ids_key'):
            keys['vedic_ids'] = d['ids_key']
    near = {}
    d = _overlay(out, slug_, 'identity', cut)
    if d and d.get('n') == n:
        for row in d.get('of') or []:  # [body, other repo ('' = same), other body]
            if len(row) == 3:
                near[row[0]] = (row[1], row[2], (d.get('sim') or [0] * n)[row[0]])
        keys['identity'] = d.get('key')
    return com, cla, words, near, keys


def repo_api(g, repo, d, gfiles, ids, out, slug, base, kbase, sec_url):
    s = slug(repo)
    n = len(d['files'])
    commit = d['commit']
    paths = ids.paths[repo]
    com, cla, words, near, keys = _columns(out, s, n, g.get('cut', ''))
    roles = [r[0] for r in d.get('roles') or []]
    rows = []
    for i, b in enumerate(d['files']):
        p = paths[i]
        gf = gfiles[ids.gid[(repo, i)]]
        reach = 'entry' if b[5] & 2 else ('reachable' if b[5] & 1 else 'unreached')
        uses = sorted({r for r in (ids.ref(x, repo) for x in gf.get('imports') or []) if r is not None}, key=_order)
        used = sorted({r for r in (ids.ref(x, repo) for x in gf.get('dependents') or []) if r is not None}, key=_order)
        row = {
            'id': '%s:%d' % (s, i), 'path': p, 'title': b[7][:90],
            'key': '%s@%s %s:1-%d' % (repo, commit, p, b[3]),
            'k': b[2], 'lines': b[3], 'role': roles[b[4]] if b[4] < len(roles) else 'other',
            'reach': reach, 'from': b[10], 'uses': uses, 'used_by': used,
            'status': gf.get('canonical_status') or 'unknown',
            'view': '%s%s.html#file=%s' % (kbase, s, _enc(p)),
        }
        if b[9]:
            row['blob'] = b[9]
        sec = gf.get('section')
        if sec in sec_url:
            row['page'] = base + sec_url[sec] + ('#f%d' % gf['block'] if gf.get('block') else '')
        dup = gf.get('duplicate_of')
        if isinstance(dup, int):
            cid = ids.sid(dup)
            if cid:
                row['canonical'] = cid
        if i in near:
            orepo, ob, sim = near[i]
            row['near'] = '%s:%d' % (slug(orepo) if orepo else s, ob)
            if sim:
                row['sim'] = sim
        if com[i]:
            row['community'] = com[i]
        if cla[i]:
            row['clarity'] = cla[i]
        if words[i]:
            row['vedic'] = [[w[0], w[1]] if len(w) > 1 and w[1] else [w[0]] for w in words[i]]
        rows.append(row)
    head = {
        'schema': SCHEMA, 'repo': repo, 'slug': s, 'commit': commit, 'cut': g.get('cut', ''), 'gh': d.get('gh', ''),
        'base': base, 'view': '%s%s.html' % (kbase, s), 'n': n, 'counts': d.get('counts', {}),
        'law': 'Kuiper\'s first law: every row has its key repo@commit path:1-lines; verify at '
               'https://github.com/<owner>/<repo>/blob/<commit>/<path>#L1-L<lines>',
        'ids': 'id = <slug>:<i>, i = body index in kuiper/<slug>.json (files sorted by path); in uses/used_by an int '
               'is a body of this repository, a string is <slug>:<i> in another',
        'sources': dict({'graph': 'build_graph.json', 'kuiper': '%s.json' % s}, **keys),
    }
    return head, rows


def entry_points(rows):
    """Entry points first by shallowest path, then index pages, then most files using them; up to ENTRY_LIST."""
    es = [r for r in rows if r['reach'] == 'entry']
    es.sort(key=lambda r: (r['path'].count('/'), 0 if r['path'].rsplit('/', 1)[-1] == 'index.html' else 1,
                           -len(r['uses']), r['path']))
    return [{'id': r['id'], 'path': r['path'], 'view': r['view']} for r in es[:ENTRY_LIST]], len(es)


def cross_links(g, ids, slug):
    pair = defaultdict(Counter)
    for e in g['edges']:
        if e[2] in MENTION_KINDS:
            continue
        a, b = ids.of.get(e[0]), ids.of.get(e[1])
        if a and b and a[0] != b[0]:
            pair[(a[0], b[0])][e[2]] += 1
    out = []
    for (a, b), c in sorted(pair.items()):
        out.append([slug(a), slug(b), sum(c.values()), c.most_common(1)[0][0]])
    return out


def build(ctx):
    g, per_repo, out = ctx['graph'], ctx['per_repo'], ctx.get('out') or 'kuiper'
    slug = ctx.get('slug') or (lambda r: r.lower())
    base = g.get('base') or ''
    kbase = base + 'kuiper/'
    api = os.path.join(out, 'api')
    os.makedirs(api, exist_ok=True)
    gfiles = {f['id']: f for f in g['files']}
    ids = Ids(g, per_repo, slug)
    sec_url = {sct['section']: sct['url'] for sct in g.get('sections') or []}
    gal = _load(os.path.join(out, 'index.galaxy.json'))
    if gal and gal.get('cut') != g.get('cut'):
        gal = None
    group = {}
    for c in (gal or {}).get('communities') or []:
        for m in c[2]:
            group[m] = c[0]
    links = cross_links(g, ids, slug)
    lout, lin = defaultdict(list), defaultdict(list)
    for a, b, nn, kind in links:
        lout[a].append([b, nn, kind])
        lin[b].append([a, nn, kind])
    lookup = {'schema': SCHEMA + '-lookup', 'cut': g.get('cut', ''), 'base': base, 'kuiper': kbase,
              'shard': SHARD, 'paths': {}, 'vedic': {}, 'vedic_ids': {}}
    words = defaultdict(list)
    repos, sizes = [], {}
    for repo in sorted(per_repo, key=str.lower):
        if repo not in ids.paths:
            continue
        s = slug(repo)
        head, rows = repo_api(g, repo, per_repo[repo], gfiles, ids, out, slug, base, kbase, sec_url)
        whole = dict(head, rows=rows)
        size = len(json.dumps(whole, separators=(',', ':'), ensure_ascii=False).encode('utf-8'))
        if size <= MAX_BYTES:
            sizes[s + '.json'] = _dump(os.path.join(api, s + '.json'), whole)
            shards = []
        else:
            shards = []
            for k in range(0, len(rows), SHARD):
                fn = '%s.p%d.json' % (s, k // SHARD)
                sizes[fn] = _dump(os.path.join(api, fn), dict(head, part=k // SHARD, rows=rows[k:k + SHARD]))
                shards.append({'file': fn, 'from': k, 'to': min(len(rows), k + SHARD) - 1})
            sizes[s + '.json'] = _dump(os.path.join(api, s + '.json'),
                                       dict(head, shard=SHARD, shards=shards,
                                            note='rows are in shards: body i is in shards[i // %d]' % SHARD))
        lookup['paths'][s] = {r['path']: i for i, r in enumerate(rows)}
        for r in rows:
            for w in r.get('vedic') or []:
                words[w[0]].append(r['id'])
                if len(w) > 1:
                    lookup['vedic_ids'][w[1]] = w[0]
        eps, ne = entry_points(rows)
        c = per_repo[repo].get('counts', {})
        repos.append({
            'repo': repo, 'slug': s, 'commit': head['commit'], 'files': c.get('files', len(rows)),
            'lines': c.get('lines'), 'reachable': c.get('reachable'), 'entries': ne, 'folders': c.get('folders'),
            'functions': c.get('functions'), 'edges': {'inside': c.get('edges_inside'), 'out': c.get('edges_out'),
                                                       'in': c.get('edges_in')},
            'community': group.get(repo), 'entry_points': eps,
            'links_out': sorted(lout[s], key=lambda x: -x[1])[:LINK_LIST],
            'links_in': sorted(lin[s], key=lambda x: -x[1])[:LINK_LIST],
            'api': 'api/%s.json' % s, 'shards': len(shards), 'view': '%s%s.html' % (kbase, s),
            'repo_page': base + per_repo[repo].get('repo_page', ''), 'gh': per_repo[repo].get('gh', ''),
        })
    lookup['vedic'] = {w: sorted(set(v)) for w, v in sorted(words.items())}
    index = {
        'schema': SCHEMA + '-index', 'cut': g.get('cut', ''), 'base': base, 'kuiper': kbase,
        'guide': kbase + 'llms-kuiper.txt', 'lookup': kbase + 'api/lookup.json', 'shard': SHARD,
        'counts': {'repos': len(repos), 'files': sum(r['files'] for r in repos),
                   'lines': sum(r['lines'] or 0 for r in repos), 'links': len(links)},
        'fields': {'links': ['from slug', 'to slug', 'resolved uses from -> to', 'commonest kind'],
                   'links_out/links_in': ['other slug', 'uses', 'commonest kind']},
        'communities': [{'label': c[0], 'hub': c[1], 'members': c[2]} for c in (gal or {}).get('communities') or []],
        'communities_rules': (gal or {}).get('rules', ''),
        'repos': repos, 'links': links,
    }
    sizes['index.json'] = _dump(os.path.join(api, 'index.json'), index)
    sizes['lookup.json'] = _dump(os.path.join(api, 'lookup.json'), lookup)
    with open(os.path.join(out, 'llms-kuiper.txt'), 'w', encoding='utf-8') as fh:
        fh.write(guide(index, lookup, out, slug))
    big = max((k for k in sizes if k not in ('index.json', 'lookup.json')), key=sizes.get, default=None)
    print('kuiper_api: wrote api/ for %d repositories (%d files); lookup %d bytes; largest %s %d bytes'
          % (len(repos), index['counts']['files'], sizes['lookup.json'], big, sizes.get(big, 0)))
    return {}


def guide(index, lookup, out, slug):
    """llms-kuiper.txt, with worked examples taken from this very build (so every example is checkable)."""
    K = index['kuiper']
    big = max(index['repos'], key=lambda r: r['files'])
    s = big['slug']
    paths = lookup['paths'][s]
    # example 1: a well-used file; example 2: a duplicate with a canonical; example 3: a VEDIC word
    best, used_n, dup = None, -1, None
    d = _load(os.path.join(out, 'api', s + '.json')) or {}
    rows = d.get('rows')
    if rows is None:
        rows = []
        for sh in d.get('shards') or []:
            rows += (_load(os.path.join(out, 'api', sh['file'])) or {}).get('rows') or []
    for r in rows:
        if len(r['used_by']) > used_n and r['path'].count('/') >= 1:
            best, used_n = r, len(r['used_by'])
        if dup is None and r.get('canonical'):
            dup = r
    ex_file = best or (rows[0] if rows else None)
    word = next(iter(lookup['vedic']), None)
    L = []
    w = L.append
    w('# Kuiper for agents: find any file of the GlobalGrid2050 estate in one or two fetches')
    w('')
    w('Cut %s. Ventus Ltd, public Ventusltd repositories: %d repositories, %d files. Generated by '
      'tools/explore/repokuiper/kuiper_api.py from the same build graph as the Kuiper pages; nothing here is '
      'hand-written data. Photon rule: the API holds ids, keys, paths and short labels, never code text; read code '
      'at the key (GitHub) or on the section page.' % (index['cut'], index['counts']['repos'], index['counts']['files']))
    w('')
    w('## The four URLs')
    w('')
    w('- %sapi/lookup.json  path -> id for every file (grouped by repository slug), VEDIC word -> file ids, '
      'GG2050-VEDIC id -> word. One fetch answers "where is X".' % K)
    w('- %sapi/index.json   every repository: counts, entry points, community, cross-repository links '
      '(links_out / links_in), and its API file.' % K)
    w('- %sapi/<slug>.json  every file of one repository: id, path, key, blob, k (ordinal), role, reach, '
      'uses, used_by, status, canonical, near, community, clarity, vedic, page, view. When large it is a '
      'manifest: the row of body i is in shards[i // %d].file (api/<slug>.p<i // %d>.json), at position '
      'i %% %d.' % (K, SHARD, SHARD, SHARD))
    w('- %s<slug>.html#file=<path>  the human view: opens that repository\'s universe and selects the file. '
      'Hand this to a person.' % K)
    w('')
    w('## Ids and fields')
    w('')
    w('- id = "<slug>:<i>": i is the body index in kuiper/<slug>.json (files sorted by path). Stable within one '
      'cut; across cuts key on repository + path.')
    w('- In a repository file, uses / used_by hold ints for files of the same repository and "<slug>:<i>" '
      'strings for other repositories. uses = what the file loads or imports (resolved references of every kind '
      'except comment links); used_by = the files that load or import it.')
    w('- key = "repo@commit path:1-lines" (Kuiper\'s first law: no claim without a key). Verify at '
      'https://github.com/Ventusltd/<repo>/blob/<commit>/<path>#L1-L<lines>. blob = git blob id when a clone '
      'was read.')
    w('- reach = entry | reachable | unreached; from = how many entry points reach it. status = '
      'canonical_status from the graph (production_core, supporting_data, duplicate_candidate, '
      'unreached_review, unknown).')
    w('- canonical = id of the file this one duplicates (graph duplicate_of); near = id of the file it is a near '
      'copy of (identity verdict), sim = similarity %. No canonical and no near: this file is its own canonical '
      'copy as far as the evidence goes.')
    w('- community = lab community label, clarity = Clarity group, vedic = [[WORD, GG2050-VEDIC id]] '
      '(CANDIDATE words for the file\'s function clusters). Missing = no evidence on this cut, not "none".')
    w('- page = the Explore Code section page (code as plain text, line by line).')
    w('')
    w('## Recipes')
    w('')
    w('Where is X (a file name or path)? Fetch api/lookup.json; search the keys of paths[<slug>] (or of every '
      'slug) for X; the value i gives id <slug>:<i> and the view %s<slug>.html#file=<path>. 1 fetch.' % K)
    w('')
    w('What uses X? lookup.json -> id; fetch api/<slug>.json (or its shard) and read rows[i].used_by. 2 fetches. '
      'Ints are bodies of the same repository: their paths are rows[int].path in the same file.')
    w('')
    w('What is the canonical copy of X? Same two fetches; rows[i].canonical (exact duplicate of) or rows[i].near '
      '(near copy of, with sim) names the canonical id; if neither is present the file is its own canonical copy. '
      'status "duplicate_candidate" marks files the graph found duplicated.')
    w('')
    w('Which repositories link to Y? api/index.json -> repos[slug=Y].links_in (and links_out). 1 fetch.')
    w('')
    w('Which files carry the VEDIC word W? api/lookup.json -> vedic[W] (ids). 1 fetch.')
    w('')
    w('## Worked examples (from this build)')
    w('')
    if ex_file:
        i = paths[ex_file['path']]
        w('1. Where is %s?' % ex_file['path'].rsplit('/', 1)[-1])
        w('   GET %sapi/lookup.json -> paths["%s"]["%s"] = %d -> id %s' % (K, s, ex_file['path'], i, ex_file['id']))
        w('   Human view: %s' % ex_file['view'])
        w('   Key: %s' % ex_file['key'])
        w('')
        loc = 'api/%s.json' % s if 'rows' in d else 'api/%s.p%d.json' % (s, i // SHARD)
        w('2. What uses %s?' % ex_file['path'])
        w('   GET %s%s -> rows[%d].used_by = %s (%d files)'
          % (K, loc, i % SHARD if 'rows' not in d else i, json.dumps(ex_file['used_by'][:6]) + ('...' if used_n > 6 else ''), used_n))
        w('')
    if dup:
        i = paths[dup['path']]
        loc = 'api/%s.json' % s if 'rows' in d else 'api/%s.p%d.json' % (s, i // SHARD)
        w('3. What is the canonical copy of %s?' % dup['path'])
        w('   GET %sapi/lookup.json -> id %s; GET %s%s -> rows[%d].canonical = "%s"'
          % (K, dup['id'], K, loc, i % SHARD if 'rows' not in d else i, dup['canonical']))
        cs, ci = dup['canonical'].split(':')
        cpath = next((p for p, j in lookup['paths'].get(cs, {}).items() if j == int(ci)), '')
        w('   Canonical: %s%s.html#file=%s' % (K, cs, _enc(cpath)))
        w('')
    if word:
        w('4. Which files carry the VEDIC word %s?' % word)
        w('   GET %sapi/lookup.json -> vedic["%s"] = %s' % (K, word, json.dumps(lookup['vedic'][word][:5])))
        w('')
    w('5. Which repositories use %s?' % s)
    w('   GET %sapi/index.json -> repos[slug="%s"].links_in = %s' % (K, s, json.dumps(big['links_in'][:3])))
    w('')
    w('## Hand a person the exact view')
    w('')
    w('Give %s<slug>.html#file=<url-encoded path> (folders: #folder=<path>). People can also press Ctrl/Cmd+K '
      '(or the "go" button on a phone) on any Kuiper page and type part of a path; "copy agent link" on each card '
      'gives the view link, the key and the API row.' % K)
    w('')
    w('## Repositories (slug: files, API file)')
    w('')
    for r in index['repos']:
        w('- %s: %d files, %s%s%s' % (r['slug'], r['files'], K, r['api'],
                                      ' (%d shards)' % r['shards'] if r['shards'] else ''))
    w('')
    return '\n'.join(L)


LLMS_HEAD = '## Kuiper (agent API)'


def llms_section(base):
    """The Kuiper block for llms.txt (text: /tmp/vk/kuiper5/llms-section.md, K5); base = the explore-code URL."""
    k = base.rstrip('/') + '/kuiper/'
    return '\n'.join([
        LLMS_HEAD, '',
        'Kuiper draws every repository as a universe; the same data is a static API for agents. Find any file in 1-2 fetches.',
        '- Guide: %sllms-kuiper.txt (worked examples from this build)' % k,
        '- %sapi/lookup.json: path -> id per repository, VEDIC word -> ids ("where is X", 1 fetch)' % k,
        '- %sapi/index.json: repositories, counts, entry points, communities, cross-repository links' % k,
        '- %sapi/<slug>.json: each file\'s id, key, blob, ordinal, role, reach, uses / used_by, canonical / near copy, '
        'community, Clarity group, VEDIC words, section page and view (large repositories: shards <slug>.pN.json, '
        'body i in shard i // 250)' % k,
        '- Hand a person the exact view: %s<slug>.html#file=<path>' % k, ''])


def add_to_llms(site, base):
    """Idempotent: put the Kuiper block in <site>/llms.txt (before '## Licences' when present) once api/ exists."""
    ll = os.path.join(site, 'llms.txt')
    if not (os.path.isfile(ll) and os.path.isfile(os.path.join(site, 'kuiper', 'api', 'index.json'))):
        return False
    with open(ll, encoding='utf-8') as fh:
        text = fh.read()
    if LLMS_HEAD in text:
        return False
    block = llms_section(base)
    if '\n## Licences' in text:
        text = text.replace('\n## Licences', '\n' + block + '\n## Licences', 1)
    else:
        text = text.rstrip('\n') + '\n\n' + block
    with open(ll, 'w', encoding='utf-8', newline='\n') as fh:
        fh.write(text)
    return True


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')
    ap.add_argument('--out', help='kuiper folder (default <site>/kuiper)')
    ap.add_argument('--base', default=os.environ.get('EXPLORE_BASE', 'https://code.globalgrid2050.com/explore-code/'),
                    help='explore-code URL for the llms.txt Kuiper block')
    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_api: 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
    build({'graph': g, 'per_repo': per_repo, 'index': _load(os.path.join(out, 'index.json')), 'out': out,
           'slug': lambda r: r.lower()})
    if os.path.abspath(out) == os.path.abspath(os.path.join(a.site, 'kuiper')) and add_to_llms(a.site, a.base):
        print('kuiper_api: added the Kuiper block to llms.txt')


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