In this section
- Estate storage · kuiper-belt / tools/estate.py lines 1–236
- Explore Code storage · kuiper-belt / tools/explore_code.py lines 1–415
Estate
A Python command-line tool in the tools folder of Kuiper Belt that reads estate network and estate bodies, using SHA-256.
storagekuiper-belt / tools/estate.py · lines 1–236 of 236 · Entry point · pattern classify (shared by 27 files)
- What it does
- It loads estate network and estate bodies. Defines git, main, classify, home_of. Uses libraries argparse, hashlib, json, math, os. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). README: "`tools/estate.py` is not yet written."
- Inputs & outputs
- In: JSON file estate-network.json; JSON file estate-bodies.json; JSON file bodies.json; command-line arguments. Out: JSON file.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It is built from the git step (`git`), the classify step (`classify`) and the home of helper (`home_of`). Draw the estate as a belt, at blob depth. It accepts `--roots`, `--out` and `--depth`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- kuiper-belt · tools · Python CLI
- Uses
- argparse, hashlib, json, math, os, statistics, subprocess, sys
- Used by
- none found
- Produces
- git, main
- Defines here
- git, main, classify, home_of
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- kuiper-belt@26fba12ab1b5bab8e71934ab86c58273e5f32682 tools/estate.py:1-236 · blob c7fa34a54ba82db777e17e38c86f6b53d26cbf4d · 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
"""tools/estate.py - draw the estate as a belt, at blob depth.
python tools/estate.py --roots <dir> --out data/<run-id>/ [--depth blob|repo]
A body is a distinct blob SHA, not a path. Git issued every one of those keys already, derived
from content, permanent, never repeating, so no key issuance is required and the whole estate is
covered. Identical content in many places is ONE body whose mass carries its membership count:
copies are brightness, not clutter.
Positions are computed, never stored. Every constant used is printed to rules.txt. The same commits
and the same flags produce a byte identical estate-network.json on any machine.
Emits the shape the existing wafer already fetches: {stations, edges}, x and y in the unit square.
"""
import argparse, hashlib, json, math, os, statistics, subprocess, sys
from datetime import datetime, timezone
# ---- constants, all printed with every run ----
A_MIN, A_MAX = 0.16, 0.92 # the drawable annulus, in unit square radii
GOLDEN = 2.399963229728653 # the angle the estate's own law already uses
E_CLAMP = 0.95 # L3
RES_MAX_PQ, RES_TOL = 8, 0.05 # L6
COLD_DAYS, HOT_DAYS, DETACHED_DAYS = 14, 7, 60
SCATTER_RATIO = 4.0
def git(cwd, args):
try:
return subprocess.run(['git'] + args, cwd=cwd, capture_output=True, text=True,
encoding='utf-8', errors='replace').stdout.strip()
except Exception:
return ''
def main():
ap = argparse.ArgumentParser()
ap.add_argument('--roots', default='.')
ap.add_argument('--out', default=None)
ap.add_argument('--depth', default='blob', choices=['blob', 'repo', 'file', 'commit'])
ap.add_argument('--seed', default=None)
ap.add_argument('--asof', default=None)
args = ap.parse_args()
if args.depth in ('file', 'commit'):
print(f'REFUSED: depth {args.depth} is not yet built. A partial answer is worse than none.')
return 2
asof = args.asof or datetime.now(timezone.utc).astimezone().isoformat(timespec='seconds')
now = datetime.now(timezone.utc)
roots = [r for r in args.roots.split(',') if r]
run_id = now.strftime('%Y%m%dT%H%M%SZ')
out = args.out or os.path.join('data', run_id)
seed = args.seed or run_id
# ---- gather ----
repos = []
for root in roots:
if not os.path.isdir(root):
continue
for name in sorted(os.listdir(root)):
d = os.path.join(root, name)
if os.path.isdir(os.path.join(d, '.git')):
repos.append((name, d))
if not repos:
print('FAIL: zero repositories. A check that examines nothing refuses.')
return 1
blobs = {} # sha -> {size, copies, repos:set, name}
repo_info = {}
for name, d in repos:
tree = git(d, ['ls-tree', '-r', '-l', 'HEAD'])
n_paths = 0
for line in tree.splitlines():
parts = line.split(None, 4)
if len(parts) < 5 or parts[1] != 'blob':
continue
sha, size, path = parts[2], parts[3], parts[4]
try:
size = int(size)
except ValueError:
size = 0
n_paths += 1
b = blobs.setdefault(sha, {'size': size, 'copies': 0, 'repos': set(), 'name': path})
b['copies'] += 1
b['repos'].add(name)
# cadence, for the repo's class, which its blobs inherit
log = git(d, ['log', '--date=unix', '--format=%cd', '-n', '400'])
stamps = sorted(int(x) for x in log.split() if x.isdigit())
gaps = [b - a for a, b in zip(stamps, stamps[1:])] if len(stamps) > 2 else []
med = statistics.median(gaps) if gaps else 0
ecc = min(E_CLAMP, statistics.pstdev(gaps) / med) if med else None
last = stamps[-1] if stamps else 0
age_days = (now.timestamp() - last) / 86400 if last else 9e9
repo_info[name] = {'paths': n_paths, 'commits': len(stamps), 'median_gap': med,
'first': stamps[0] if stamps else 9999999999,
'e': ecc, 'age_days': age_days,
'max_gap_ratio': (max(gaps) / med) if gaps and med else 0}
if not blobs:
print('FAIL: zero bodies. A check that examines nothing refuses.')
return 1
# ---- the shepherd is computed, never declared (L1) ----
max_c = max(r['commits'] for r in repo_info.values()) or 1
max_p = max(r['paths'] for r in repo_info.values()) or 1
scores = sorted(((r['commits'] / max_c + r['paths'] / max_p, n) for n, r in repo_info.items()),
reverse=True)
shepherd = scores[0][1]
shep = repo_info[shepherd]
def classify(name):
r = repo_info[name]
if name == shepherd:
return 'shepherd'
if r['age_days'] > DETACHED_DAYS:
return 'detached'
if r['max_gap_ratio'] > SCATTER_RATIO:
return 'scattered'
if shep['median_gap'] and r['median_gap']:
ratio = r['median_gap'] / shep['median_gap']
for q in range(1, RES_MAX_PQ + 1):
for p in range(1, RES_MAX_PQ + 1):
if abs(ratio - p / q) / (p / q) <= RES_TOL:
return 'resonant'
if r['age_days'] <= HOT_DAYS:
return 'classical-hot'
if r['age_days'] >= COLD_DAYS:
return 'classical-cold'
return 'classical-hot'
# ---- place, deterministically, from each body's own key ----
# Radius is age in the estate, not alphabetical rank of a hash. On the wafer r = sqrt(key)
# means something because the key is the order a line entered the estate, so radius is time.
# Sorting by blob SHA would sort by randomness and the field would carry no depth. Bodies are
# therefore ordered by the first commit of the oldest repository that holds them, then by key
# to break ties deterministically. Oldest work sits at the pupil, tonight's at the rim.
def home_of(sha):
return min(blobs[sha]['repos'], key=lambda n: (repo_info[n]['first'], n))
# LOOK OUT, LOOK BACK. In the night sky distance IS time: the further away a star, the older
# the light reaching you. Proxima is four years old, Andromeda two and a half million, and both
# arrive in the same instant. The belt now obeys the same rule, so flying outward is flying
# backward through the estate. Newest work at the pupil, where you are standing; oldest at the
# rim, furthest away and furthest into the past. Ties broken by key so the run stays byte
# identical.
order = sorted(blobs, key=lambda s: (-repo_info[home_of(s)]['first'], s))
stations = []
bodies = []
n_bodies = len(blobs)
for i, sha in enumerate(order):
b = blobs[sha]
home = home_of(sha)
cls = classify(home)
# The estate's own placement law, unchanged: r from the body's ordinal among sorted
# keys, theta by the golden angle. Position encodes identity, neighbours are related,
# and density is uniform. Class is a property of a body, never a position: moving a
# body because of its class would be colouring without a function.
k = i
r = A_MIN + (A_MAX - A_MIN) * math.sqrt((k + 0.5) / n_bodies)
theta = (k * GOLDEN) % (2 * math.pi)
# Centred on zero, matching every existing system. Measured from the live files:
# underground x [-0.893, 0.900], grid400 x [-0.537, 0.537], uk y [-0.900, 0.900].
# The renderer multiplies straight through with no centring, so a unit-square dataset
# would draw in the +x/+y quadrant at half scale. SPEC.md said "unit square"; SPEC.md
# was inferred from prose rather than measured, and was wrong.
x = round(r * math.cos(theta), 6)
y = round(r * math.sin(theta), 6)
# The renderer's contract, taken from tools/networks.py in the drawing engine and not
# inferred: stations are [x, y, name], edges are [i, j] index pairs. The name is the key.
stations.append([x, y, sha])
bodies.append({'k': i, 'id': sha, 'x': x, 'y': y, 'm': b['size'],
'copies': b['copies'], 'class': cls, 'home': home, 'open': False})
# A belt needs no edges. Bodies orbit independently, and an invented edge would be a claim
# without a key. Stated rather than implied.
edges = []
os.makedirs(out, exist_ok=True)
law = ('one body per distinct blob SHA; r = a_min + (a_max - a_min) * sqrt((k + 0.5) / n) '
'with k the body ordinal among sorted keys; theta = k * ' + str(GOLDEN) + '; '
'class is a property and never a position; no edges, because an unmeasured edge '
'would be a claim without a key')
net = {'name': 'estate', 'source': 'the tracked files of every repository under --roots, by blob SHA',
'attribution': 'content identifiers issued by git; no third party data',
'law': law, 'stations': stations, 'edges': edges}
net_json = json.dumps(net, sort_keys=True, separators=(',', ':'))
with open(os.path.join(out, 'estate-network.json'), 'w', newline='\n') as f:
f.write(net_json)
with open(os.path.join(out, 'estate-bodies.json'), 'w', newline='\n') as f:
json.dump({'schema': 'estate-bodies-v1', 'run': run_id, 'bodies': bodies},
f, separators=(',', ':'), sort_keys=True)
by_class = {}
for s in bodies:
by_class[s['class']] = by_class.get(s['class'], 0) + 1
total_paths = sum(r['paths'] for r in repo_info.values())
rules = [
f'asof {asof}', f'seed {seed}', f'depth {args.depth}',
f'roots {args.roots}', f'a_min {A_MIN}', f'a_max {A_MAX}',
f'golden_angle {GOLDEN}', f'e_clamp {E_CLAMP}',
f'resonance_tolerance {RES_TOL}', f'resonance_max_pq {RES_MAX_PQ}',
f'cold_days {COLD_DAYS}', f'hot_days {HOT_DAYS}', f'detached_days {DETACHED_DAYS}',
f'scatter_ratio {SCATTER_RATIO}',
f'shepherd {shepherd}',
'shepherd_top_three ' + '; '.join(f'{n} {s:.4f}' for s, n in scores[:3]),
f'git {git(repos[0][1], ["--version"])}',
'open_probe none, every body recorded dim',
]
with open(os.path.join(out, 'rules.txt'), 'w', newline='\n') as f:
f.write('\n'.join(rules) + '\n')
bodies_path = os.path.join(out, 'bodies.json')
with open(bodies_path, 'w', newline='\n') as f:
json.dump({'run': run_id, 'shepherd': shepherd, 'repositories': len(repos),
'tracked_paths': total_paths, 'bodies': len(stations),
'by_class': by_class}, f, indent=1, sort_keys=True)
os.makedirs('proof', exist_ok=True)
digest = hashlib.sha256(net_json.encode()).hexdigest()
proof = {'run': run_id, 'asof': asof, 'digest': digest,
'bodies': len(stations), 'tracked_paths': total_paths,
'repositories': len(repos), 'shepherd': shepherd, 'by_class': by_class,
'dim': len(stations), 'score_dim_over_all': 1.0,
'command': 'python tools/estate.py ' + ' '.join(sys.argv[1:])}
with open(os.path.join('proof', f'{run_id}-estate.json'), 'w', newline='\n') as f:
json.dump(proof, f, indent=1, sort_keys=True)
print(f'repositories {len(repos)} tracked paths {total_paths} bodies {len(stations)}')
print(f'shepherd {shepherd} ({scores[0][0]:.4f})')
for k in sorted(by_class):
print(f' {k:<16} {by_class[k]}')
print(f'estate-network.json digest {digest}')
print(f'dim {len(stations)} of {len(stations)}: no destination probe ran, so nothing is open')
return 0
if __name__ == '__main__':
sys.exit(main())Explore Code
A Python command-line tool in the tools folder of Kuiper Belt that reads sections and words.
storagekuiper-belt / tools/explore_code.py · lines 1–415 of 415 · Entry point · pattern definitions (shared by 2 files)
- What it does
- It loads sections and words. Defines 11 functions or classes, including git, ext, definitions, scan, sectionise. Uses libraries argparse, collections, datetime, hashlib, html. Side effects: reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: Parquet file sections.parquet; Parquet file files.parquet; Parquet file words.parquet; DuckDB queries; command-line arguments. Out: Parquet file.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It writes Parquet (`write_parquet`) and is built from the git step (`git`) and the ext step (`ext`). The estate's unique code, sorted into keyed, crawlable pages. It accepts `--src`, `--out` and `--min`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- kuiper-belt · tools · Python CLI
- Uses
- Check Proof (import), argparse, collections, datetime, hashlib, html, os, re, shutil
- Used by
- none found
- Produces
- git, ext, definitions, scan, sectionise, page, summary, write_parquet, build, main
- Defines here
- git, ext, definitions, scan, sectionise, flush, page, summary, write_parquet, build, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- kuiper-belt@26fba12ab1b5bab8e71934ab86c58273e5f32682 tools/explore_code.py:1-415 · blob 78aef08a0adf4e4ef8452f04972b2f4e38d5ebd6 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process, storage · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
#!/usr/bin/env python3
r"""tools/explore_code.py - Explore Code: the estate's unique code, sorted into keyed, crawlable pages.
Method (the Kuiper first law applied to reading code):
1. Every public Ventusltd repository is read at its HEAD commit. The commit SHA is recorded.
2. Code files only (by extension), no vendored or minified files, nothing over 1 MB.
3. Unique: a blob (git object SHA) is kept once, wherever it appears. Of a family of
timestamped versions (same path once 20YYMMDD[hhmm] stamps are masked) only the newest
is kept; the older ones remain in their repositories and in Kuiper's history.
4. Any file whose path matches a non-public repository digest (check_proof.leaks) is left
out and counted, so the pages pass K1.
5. Files are sorted by repository then path and cut into sections of at most --max lines
(default 2000) and, where a file boundary allows, at least --min (default 1000). A file
longer than a section is split by line range.
6. Each section is one small static HTML page with no script: a header per file giving
repo, commit, path, blob SHA and line range, and a link to the pinned raw file
(raw.githubusercontent.com at that commit, plain text any agent can fetch) and to GitHub at
those lines. No code is copied: the repository at the stated commit is the only source.
7. Translation, as the VEDIC dictionary does it: each section gets a plain-English summary
computed from what it contains, and every defined function, class and workflow becomes a
word in an alphabetical dictionary that points to its section and line.
Usage:
python tools/explore_code.py --src DIR_OF_CLONES --out explore-code
Nothing here is an opinion: run it again on the same commits and the same pages come out.
"""
import argparse
import collections
import datetime
import hashlib
import html
import os
import re
import shutil
import subprocess
import sys
import urllib.parse
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
from check_proof import leaks # noqa: E402
BASE = 'https://ventusltd.github.io/kuiper-belt/explore-code/'
README = 'https://github.com/Ventusltd/kuiper-belt/blob/main/explore-code/README.md'
EXT = re.compile(r'\.(py|js|mjs|cjs|ts|tsx|jsx|html|htm|css|sh|ps1|bat|yml|yaml|sql|rs|go|c|cc|cpp|h|hpp|'
r'java|kt|swift|rb|php|r|jl|lua|toml|glsl|wgsl|vue|svelte)$', re.I)
SKIP = re.compile(r'(^|/)(node_modules|vendor|third_party|dist|build|\.git)/|\.min\.(js|css)$', re.I)
STAMP = re.compile(r'(?<!\d)(20\d{6}(?:T?\d{4,6}Z?)?)(?!\d)')
LANG = {'py': 'Python', 'js': 'JavaScript', 'mjs': 'JavaScript', 'cjs': 'JavaScript', 'ts': 'TypeScript',
'tsx': 'TypeScript', 'jsx': 'JavaScript', 'html': 'HTML', 'htm': 'HTML', 'css': 'CSS', 'sh': 'Shell',
'ps1': 'PowerShell', 'bat': 'Batch', 'yml': 'YAML', 'yaml': 'YAML', 'sql': 'SQL', 'toml': 'TOML'}
JS_DEF = [(re.compile(r'^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)'), 'function'),
(re.compile(r'^\s*(?:export\s+)?(?:default\s+)?class\s+([A-Za-z_$][\w$]*)'), 'class'),
(re.compile(r'^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?'
r'(?:function\b|\([^)]*\)\s*=>|[A-Za-z_$][\w$]*\s*=>)'), 'function')]
PY_DEF = [(re.compile(r'^\s*(?:async\s+)?def\s+([A-Za-z_]\w*)'), 'function'),
(re.compile(r'^\s*class\s+([A-Za-z_]\w*)'), 'class')]
SH_DEF = [(re.compile(r'^\s*(?:function\s+)?([A-Za-z_][\w-]*)\s*\(\)\s*\{'), 'function')]
YML_DEF = [(re.compile(r'^name:\s*["\']?([^"\'#\n]{2,80})'), 'workflow')]
def git(d, *a, binary=False):
r = subprocess.run(['git', '-C', d] + list(a), capture_output=True)
return r.stdout if binary else r.stdout.decode('utf-8', 'replace').strip()
def ext(path):
return path.rsplit('.', 1)[-1].lower() if '.' in path else ''
def definitions(path, lines):
e = ext(path)
rules = PY_DEF if e == 'py' else SH_DEF if e in ('sh',) else YML_DEF if e in ('yml', 'yaml') else \
JS_DEF if e in ('js', 'mjs', 'cjs', 'ts', 'tsx', 'jsx', 'html', 'htm', 'vue', 'svelte') else []
out = []
for i, line in enumerate(lines, 1):
if len(line) > 400:
continue
for rx, kind in rules:
m = rx.match(line)
if m:
out.append((m.group(1).strip(), kind, i))
break
return out
def scan(src):
files, left_out = [], collections.Counter()
seen = set()
for repo_dir in sorted(os.listdir(src), key=str.lower):
d = os.path.join(src, repo_dir)
if not os.path.isdir(os.path.join(d, '.git')):
continue
url = git(d, 'config', '--get', 'remote.origin.url')
if not url.lower().startswith('https://github.com/ventusltd/'):
continue
repo = url.rstrip('/').split('/')[-1]
repo = repo[:-4] if repo.endswith('.git') else repo
if leaks(repo):
continue
commit = git(d, 'rev-parse', 'HEAD')
when = git(d, 'log', '-1', '--format=%cI')
listing = git(d, 'ls-tree', '-r', '-l', '-z', 'HEAD', binary=True).decode('utf-8', 'replace')
items = []
for ent in listing.split('\0'):
if '\t' not in ent:
continue
meta, path = ent.split('\t', 1)
mode, typ, sha, size = meta.split()
if typ != 'blob' or size == '-' or not 0 < int(size) <= 1_000_000:
continue
if EXT.search(path) and not SKIP.search(path):
items.append((path, sha))
p = subprocess.Popen(['git', '-C', d, 'cat-file', '--batch'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
for path, sha in items:
p.stdin.write((sha + '\n').encode())
p.stdin.flush()
hdr = p.stdout.readline().split()
if len(hdr) < 3 or hdr[1] == b'missing':
left_out['not fetched'] += 1
continue
n = int(hdr[2])
data = p.stdout.read(n)
p.stdout.read(1)
if sha in seen:
continue
seen.add(sha)
if b'\0' in data[:8000]:
continue
text = data.decode('utf-8', 'replace')
lines = text.split('\n')
if lines and lines[-1] == '':
lines.pop()
if not lines or n / len(lines) > 400:
left_out['minified or one-line'] += 1
continue
files.append({'repo': repo, 'commit': commit, 'when': when, 'path': path, 'blob': sha,
'lines': lines})
p.stdin.close()
p.wait()
print('scanned %-55s %6d code files' % (repo, len(items)), file=sys.stderr)
newest = {}
for f in files:
fam = f['repo'] + '|' + STAMP.sub('#', f['path'])
key = (max(STAMP.findall(f['path']) or ['']), f['path'])
if fam not in newest or key > newest[fam][0]:
newest[fam] = (key, f)
kept = []
for _, f in newest.values():
if leaks(f['path']):
left_out['matches a non-public digest'] += 1
continue
kept.append(f)
left_out['older timestamped versions'] = len(files) - len(newest)
kept.sort(key=lambda f: (f['repo'].lower(), f['path']))
return kept, left_out
def sectionise(files, lo, hi):
sections, cur, n = [], [], 0
def flush():
nonlocal cur, n
if cur:
sections.append(cur)
cur, n = [], 0
for fi, f in enumerate(files):
start, total = 1, len(f['lines'])
while start <= total:
left = total - start + 1
if n + left <= hi:
cur.append((fi, start, total))
n += left
start = total + 1
elif n >= lo:
flush()
else:
take = hi - n
cur.append((fi, start, start + take - 1))
start += take
n += take
flush()
flush()
return sections
CSS = """body{background:#000;color:#eee;font:15px/1.55 ui-monospace,Menlo,Consolas,monospace;margin:0}
header,nav,footer,main{max-width:1100px;margin:0 auto;padding:0 18px}a{color:#66ccff}
.brand{color:#66ccff;margin:22px 0 4px}h1{font-size:22px;margin:4px 0 8px}h2{font-size:15px;margin:26px 0 6px;
overflow-wrap:anywhere}nav{display:flex;gap:18px;flex-wrap:wrap;padding-top:10px;padding-bottom:10px;
border-bottom:1px solid #333}.k{color:#999;font-size:12px;overflow-wrap:anywhere}table{border-collapse:collapse;width:100%;font-size:13px}
td,th{border-bottom:1px solid #222;padding:5px 8px;text-align:left;vertical-align:top}th{color:#66ccff}
li{margin:10px 0}p{max-width:900px}:target{outline:1px solid #66ccff}
"""
def page(title, body, desc, canonical, extra_head=''):
return ('<!doctype html><html lang="en"><head><meta charset="utf-8">'
'<meta name="viewport" content="width=device-width,initial-scale=1">'
'<title>%s</title><meta name="description" content="%s"><meta name="robots" content="index,follow">'
'<link rel="canonical" href="%s"><link rel="stylesheet" href="%s">%s</head><body>%s</body></html>\n'
% (html.escape(title), html.escape(desc), canonical, 'explore.css' if '/s/' not in canonical
and '/words/' not in canonical else '../explore.css', extra_head, body))
def summary(parts, files, defs):
langs = collections.Counter()
for fi, a, b in parts:
langs[LANG.get(ext(files[fi]['path']), ext(files[fi]['path']).upper() or 'text')] += b - a + 1
repos = []
for fi, _, _ in parts:
if files[fi]['repo'] not in repos:
repos.append(files[fi]['repo'])
kinds = collections.Counter(k for _, k, _, _ in defs)
names = [n for n, k, _, _ in defs if k in ('function', 'class')]
lines = sum(b - a + 1 for _, a, b in parts)
nfiles = len({fi for fi, _, _ in parts})
s = '%s lines of %s from %s, in %d file%s.' % (
format(lines, ','), ' and '.join('%s (%s)' % (l, format(c, ',')) for l, c in langs.most_common(3)),
', '.join(repos[:4]) + (' and %d more' % (len(repos) - 4) if len(repos) > 4 else ''),
nfiles, '' if nfiles == 1 else 's')
if kinds:
s += ' Defines ' + ', '.join('%d %s%s' % (c, k, 'es' if k == 'class' and c != 1 else 's' if c != 1 else '')
for k, c in kinds.most_common()) + '.'
if names:
s += ' Including ' + ', '.join(names[:8]) + '.'
return s, repos, langs
def write_parquet(out, manifest_sections, words, stamp):
"""The data backend, as data-grid-gb keeps its tables: Parquet, queryable by DuckDB over HTTP."""
try:
import duckdb
except ImportError:
print('duckdb not installed: Parquet tables skipped (pip install duckdb)', file=sys.stderr)
return False
os.makedirs(os.path.join(out, 'data'), exist_ok=True)
con = duckdb.connect()
con.execute('CREATE TABLE sections(section INTEGER, url VARCHAR, lines INTEGER, repos VARCHAR[], summary VARCHAR, cut VARCHAR)')
con.executemany('INSERT INTO sections VALUES (?,?,?,?,?,?)',
[(m['section'], m['url'], m['lines'], m['repos'], m['summary'], stamp) for m in manifest_sections])
con.execute('CREATE TABLE files(section INTEGER, block INTEGER, repo VARCHAR, commit_sha VARCHAR, path VARCHAR, '
'blob_sha VARCHAR, line_from INTEGER, line_to INTEGER, raw_url VARCHAR, github_url VARCHAR)')
rows = []
for m in manifest_sections:
for bi, f in enumerate(m['files'], 1):
q = urllib.parse.quote(f['path'])
rows.append((m['section'], bi, f['repo'], f['commit'], f['path'], f['blob'], f['from'], f['to'],
'https://raw.githubusercontent.com/Ventusltd/%s/%s/%s' % (f['repo'], f['commit'], q),
'https://github.com/Ventusltd/%s/blob/%s/%s#L%d-L%d' % (f['repo'], f['commit'], q, f['from'], f['to'])))
con.executemany('INSERT INTO files VALUES (?,?,?,?,?,?,?,?,?,?)', rows)
con.execute('CREATE TABLE words(word VARCHAR, kind VARCHAR, repo VARCHAR, path VARCHAR, line INTEGER, '
'section INTEGER, block INTEGER)')
con.executemany('INSERT INTO words VALUES (?,?,?,?,?,?,?)', [tuple(w) for w in words])
for t, order in (('sections', 'section'), ('files', 'section, block'), ('words', 'lower(word), repo, path, line')):
con.execute("COPY (SELECT * FROM %s ORDER BY %s) TO '%s' (FORMAT PARQUET, COMPRESSION ZSTD)"
% (t, order, os.path.join(out, 'data', t + '.parquet').replace("'", "''")))
con.close()
return True
def build(src, out, lo, hi):
files, left_out = scan(src)
sections = sectionise(files, lo, hi)
total_lines = sum(len(f['lines']) for f in files)
stamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%S+00:00')
width = max(4, len(str(len(sections))))
name = lambda i: 's/%0*d.html' % (width, i)
keep = os.path.join(out, 'README.md')
readme = open(keep, encoding='utf-8').read() if os.path.isfile(keep) else None
if os.path.isdir(out):
shutil.rmtree(out)
os.makedirs(os.path.join(out, 's'))
os.makedirs(os.path.join(out, 'words'))
io_w = lambda rel, s: open(os.path.join(out, rel), 'w', encoding='utf-8', newline='\n').write(s)
io_w('explore.css', CSS)
if readme:
io_w('README.md', readme)
index_rows, words, manifest_sections = [], [], []
for si, parts in enumerate(sections, 1):
defs = []
blocks = []
for bi, (fi, a, b) in enumerate(parts, 1):
f = files[fi]
for nm, kind, ln in definitions(f['path'], f['lines'][a - 1:b]):
if not leaks(nm):
defs.append((nm, kind, a + ln - 1, (bi, fi)))
gh = 'https://github.com/Ventusltd/%s/blob/%s/%s#L%d-L%d' % (f['repo'], f['commit'], urllib.parse.quote(f['path']), a, b)
raw = 'https://raw.githubusercontent.com/Ventusltd/%s/%s/%s' % (f['repo'], f['commit'], urllib.parse.quote(f['path']))
blocks.append('<li id="f%d"><h2>%s / %s · lines %d–%d of %d</h2>'
'<a href="%s">raw at %s</a> · <a href="%s">GitHub lines %d–%d</a>'
'<br><span class="k">blob %s</span></li>'
% (bi, html.escape(f['repo']), html.escape(f['path']), a, b, len(f['lines']),
html.escape(raw), f['commit'][:12], html.escape(gh), a, b, f['blob']))
text, repos, langs = summary(parts, files, defs)
lines = sum(b - a + 1 for _, a, b in parts)
prev = '<a href="../%s" rel="prev">← Section %d</a>' % (name(si - 1), si - 1) if si > 1 else '<span></span>'
nxt = '<a href="../%s" rel="next">Section %d →</a>' % (name(si + 1), si + 1) if si < len(sections) else '<span></span>'
nav = '<nav>%s<a href="../index.html">Explore Code index</a><a href="../words/index.html">Words</a>%s</nav>' % (prev, nxt)
body = ('<header><p class="brand">GLOBALGRID2050 / KUIPER / EXPLORE CODE</p><h1>Section %d of %d</h1>'
'<p>%s</p><p class="k">Cut %s. Every link is pinned to a commit: the raw file is the source.</p>'
'</header>%s<main><ol>%s</ol></main>%s'
% (si, len(sections), html.escape(text), stamp, nav, ''.join(blocks), nav))
io_w(name(si), page('Explore Code section %d of %d: %s' % (si, len(sections), ', '.join(repos[:3])),
body, text, BASE + name(si)))
first, last = parts[0], parts[-1]
index_rows.append((si, repos, lines, len({p[0] for p in parts}),
'%s:%d' % (files[first[0]]['path'], first[1]),
'%s:%d' % (files[last[0]]['path'], last[2]), text, list(langs)))
manifest_sections.append({'section': si, 'url': BASE + name(si), 'lines': lines, 'repos': repos,
'summary': text,
'files': [{'repo': files[fi]['repo'], 'commit': files[fi]['commit'],
'path': files[fi]['path'], 'blob': files[fi]['blob'],
'from': a, 'to': b} for fi, a, b in parts]})
for nm, kind, ln, (bi, fi) in defs:
words.append((nm, kind, files[fi]['repo'], files[fi]['path'], ln, si, bi))
# Index: static and complete for crawlers; the script adds VEDIC-style search, filters and 100-row pages.
rows = ''.join('<tr><td><a href="%s">%d</a></td><td>%s</td><td>%s</td><td>%d</td>'
'<td class="k">%s → %s</td><td>%s</td></tr>'
% (name(r[0]), r[0],
html.escape(', '.join(r[1])), format(r[2], ','), r[3], html.escape(r[4]), html.escape(r[5]),
html.escape(r[6])) for r in index_rows)
left = ', '.join('%s %s' % (format(v, ','), k) for k, v in sorted(left_out.items()) if v)
intro = ('<p>%s lines of unique code from %d public repositories, sorted by repository and path into %d sections '
'of %d to %d lines. Each section page lists its files under headers, keyed '
'<code>repo@commit path:from-to</code> with blob SHA, linked to the pinned raw file. No code is copied. '
'Unique means each git blob once, and only the newest of each family of timestamped versions. '
'Left out: %s.</p><p class="k">Cut %s. Method: <a href="%s">README</a>. Machine-readable: '
'<a href="llms.txt">llms.txt</a> · '
'<a href="sitemap.xml">sitemap.xml</a> · Parquet for DuckDB: <a href="data/sections.parquet">sections</a>, '
'<a href="data/files.parquet">files</a>, <a href="data/words.parquet">words</a>. Translation: <a href="words/index.html">Words</a>, every defined '
'function, class and workflow, A to Z.</p>'
% (format(total_lines, ','), len({f['repo'] for f in files}), len(sections), lo, hi, left or 'nothing', stamp,
README))
body = ('<header><p class="brand">GLOBALGRID2050 / KUIPER</p><h1>Explore Code</h1>%s</header>'
'<nav><a href="../">Kuiper</a><a href="../agents/">Modular agent start</a><a href="words/index.html">Words</a>'
'<a href="https://globalgrid2050.com/">GlobalGrid2050</a></nav><main><table><thead><tr><th>Section</th>'
'<th>Repositories</th><th>Lines</th><th>Files</th><th>From → to</th><th>Plain English</th></tr></thead>'
'<tbody>%s</tbody></table></main>' % (intro, rows))
io_w('index.html', page('Explore Code: the GlobalGrid2050 code estate in %d sections' % len(sections), body,
'Unique code from the Ventusltd public repositories, sorted into keyed '
'sections of up to %d lines linking to pinned raw files.' % hi, BASE + 'index.html'))
# Words: the VEDIC-style dictionary, static pages of 1,000 words, A to Z.
grouped = collections.OrderedDict()
for w in sorted(words, key=lambda w: (w[0].lower(), w[0], w[5], w[6], w[4])):
grouped.setdefault((w[0], w[1]), []).append(w)
entries = list(grouped.items())
groups = collections.OrderedDict()
for e in entries:
c = e[0][0][0].lower()
groups.setdefault(c if c.isalpha() else 'symbols', []).append(e)
word_pages = []
for g, ws in groups.items():
for k in range(0, len(ws), 1000):
word_pages.append(('%s-%02d' % (g, k // 1000 + 1), ws[k:k + 1000]))
for wi, (wn, ws) in enumerate(word_pages):
tr = ''.join('<tr><td>%s</td><td>%s</td><td>%s</td></tr>'
% (html.escape(nm), kind, ' '.join(sorted({'<a href="../%s#f%d">%d</a>' % (name(w[5]), w[6], w[5])
for w in locs})))
for (nm, kind), locs in ws)
first, last = ws[0][0][0], ws[-1][0][0]
pv = '<a href="%s.html">← %s</a>' % (word_pages[wi - 1][0], word_pages[wi - 1][0]) if wi else '<span></span>'
nx = '<a href="%s.html">%s →</a>' % (word_pages[wi + 1][0], word_pages[wi + 1][0]) if wi + 1 < len(word_pages) else '<span></span>'
nav = '<nav>%s<a href="index.html">Words A–Z</a><a href="../index.html">Explore Code index</a>%s</nav>' % (pv, nx)
body = ('<header><p class="brand">GLOBALGRID2050 / KUIPER / EXPLORE CODE / WORDS</p><h1>Words %s to %s</h1>'
'<p>Each word is a function, class or workflow defined in the code. The numbers are the sections that '
'define it; each opens at the file.</p></header>%s<main><table><thead><tr><th>Word</th><th>Kind</th>'
'<th>Sections</th></tr></thead><tbody>%s</tbody></table></main>%s'
% (html.escape(first), html.escape(last), nav, tr, nav))
io_w('words/%s.html' % wn, page('Explore Code words %s to %s' % (first[:30], last[:30]), body,
'Dictionary of defined functions and classes, %s to %s.' % (first[:30], last[:30]),
BASE + 'words/%s.html' % wn))
li = ''.join('<li><a href="%s.html">%s</a> · %s to %s (%d words)</li>'
% (wn, wn, html.escape(ws[0][0][0][:40]), html.escape(ws[-1][0][0][:40]), len(ws)) for wn, ws in word_pages)
body = ('<header><p class="brand">GLOBALGRID2050 / KUIPER / EXPLORE CODE</p><h1>Words A–Z</h1><p>%s defined '
'functions, classes and workflows, alphabetical, in pages of 1,000.</p></header><nav><a href="../index.html">'
'Explore Code index</a></nav><main><ol>%s</ol></main>' % (format(len(words), ','), li))
io_w('words/index.html', page('Explore Code words A to Z', body, 'Alphabetical dictionary of the code estate.',
BASE + 'words/index.html'))
# Crawl aids.
urls = [BASE + 'index.html', BASE + 'words/index.html'] + [BASE + name(i) for i in range(1, len(sections) + 1)] + \
[BASE + 'words/%s.html' % wn for wn, _ in word_pages]
io_w('sitemap.xml', '<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'
+ ''.join('<url><loc>%s</loc></url>\n' % u for u in urls) + '</urlset>\n')
io_w('llms.txt', '# Explore Code (GlobalGrid2050 / Kuiper)\n\n> %s lines of unique code from %d public Ventusltd '
'repositories in %d static section pages of %d-%d lines. Each page lists files keyed '
'repo@commit path:from-to with blob SHA and a pinned raw.githubusercontent.com link (plain text). Cut %s.\n\n- Index: %sindex.html\n- Words A-Z: %swords/index.html\n- Method: %s\n- Parquet for DuckDB (every section, file, commit, blob, line range and word): %sdata/sections.parquet, %sdata/files.parquet, %sdata/words.parquet\n'
' e.g. SELECT * FROM \'%sdata/files.parquet\' WHERE path LIKE \'%%satnav%%\';\n\n'
'## Sections\n\n' % (format(total_lines, ','), len({f['repo'] for f in files}), len(sections), lo, hi, stamp,
BASE, BASE, README, BASE, BASE, BASE, BASE)
+ ''.join('- [Section %d](%s): %s\n' % (m['section'], m['url'], m['summary']) for m in manifest_sections))
pq = write_parquet(out, manifest_sections, words, stamp)
print('Parquet tables: %s' % ('written' if pq else 'skipped'))
print('%s lines, %d files, %d sections, %d words, left out: %s'
% (format(total_lines, ','), len(files), len(sections), len(words), left or 'nothing'))
def main():
ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])
ap.add_argument('--src', required=True, help='folder holding one clone per public repository')
ap.add_argument('--out', default=os.path.join(HERE, '..', 'explore-code'))
ap.add_argument('--min', type=int, default=1000)
ap.add_argument('--max', type=int, default=2000)
a = ap.parse_args()
build(a.src, a.out, a.min, a.max)
if __name__ == '__main__':
main()