In this section
- Extras render · cosmic / tools/explore/extras.py lines 701–891
- Extract ingest · cosmic / tools/explore/identity/extract.mjs lines 1–54
- Genome storage · cosmic / tools/explore/identity/genome.py lines 1–455
Extras
A Python command-line tool in the explore folder of Cosmic that draws identity, board, games and periodic. It audits mass (`audit_mass`), reads text (`read_text`) and writes text (`write_text`).
rendercosmic / tools/explore/extras.py · lines 701–891 of 891 (continued from section 1100) · Entry point · pattern html_files (shared by 2 files)
- What it does
- It draws identity, board, games and periodic. Defines 33 functions or classes, including picture_svg, first_sentence, slim_kuiper, slim_identity, audit_mass. Uses libraries argparse, datetime, html, json, os. Side effects: changes the web page (DOM); reads or writes files; starts processes.
- Inputs & outputs
- In: JSON file identity-files.json; JSON file extra.json; JSON file data.json; JSON file board.json; JSON file games.json; JSON file periodic.json; JSON file props.json; JSON file clarity.json. Out: JSON file; SVG drawing.
- Downstream impact
- Used directly by 2 files: Ship (cosmic); Test Extras (cosmic). Reached from 1 other entry point, including Test Ship (cosmic).
- What it achieves
- Explore Code extras: a post-build step that adds the team's extra experiences to a built site. It accepts `--site`, `--graph` and `--base`.
- Why it matters
- Run by Ship. Checked by Test Extras.
- Application
- cosmic · tools/explore · Python CLI
- Uses
- Explore — Lab (script call), Clarity (script call), Build (script call), Genome (script call), Board (script call), Tournament (script call), Page (script call), Map (script call), and 10 more, argparse, datetime, html, json, os, re, shutil, subprocess
- Used by
- run by Ship (script call), imported by Test Extras (import)
- Produces
- picture_svg, first_sentence, slim_kuiper, slim_identity, audit_mass, folder_bytes, read_text, write_text, show, log, warn, find_generator
- Defines here
- hub_items, write_hub, write_sitemap, write_llms, link_index, main, run_phase, run_posts
- 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/extras.py:701-891 · blob c1c4bbf8e0aa5bae9c3a8751500e1171e867e366 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: unknown · users: none · canonical: unknown
else picture_svg(key)
return ('<li class="card"><a class="pic" href="%s" tabindex="-1" aria-hidden="true">%s</a><div class="body">'
'<h2><a href="%s">%s</a></h2><p>%s</p>%s<a class="go" href="%s" aria-label="Open %s">Open</a></div></li>'
% (html.escape(href), pic, html.escape(href), html.escape(title), html.escape(desc),
('<span class="tag">%s</span>' % html.escape(tag)) if tag else '', html.escape(href), html.escape(title)))
def hub_items(records, site, registry=None):
items = []
order = {e['slug']: i for i, e in enumerate(registry if registry is not None else EXTRAS)}
for r in sorted(records, key=lambda r: order.get(r['slug'], len(order))):
if r.get('status') == 'ok':
items.append({'key': r['slug'], 'title': r['title'], 'desc': r['desc'], 'href': r['entry'],
'preview': r.get('preview'), 'tag': 'New'})
for b in BUILTIN:
if os.path.isfile(os.path.join(site, b['href'])):
items.append({'key': b['slug'], 'title': b['title'], 'desc': b['desc'], 'href': b['href'], 'preview': None, 'tag': ''})
return items
def write_hub(site, base, records, cut, registry=None):
items = hub_items(records, site, registry)
cards = ''.join(card(i['key'], i['title'], i['desc'], i['href'], i['preview'], i['tag']) for i in items)
if not cards:
cards = '<li class="empty">No extra experiences in this build yet.</li>'
ld = json.dumps({'@context': 'https://schema.org', '@type': 'CollectionPage', 'name': 'Explore more',
'url': base + 'more.html', 'author': {'@type': 'Organization', 'name': 'Ventus Ltd'},
'hasPart': [{'@type': 'WebPage', 'name': i['title'], 'url': base + i['href']} for i in items]},
ensure_ascii=False).replace('</', '<\\/')
page = ('<!doctype html><html lang="en"><head><meta charset="utf-8">'
'<meta name="viewport" content="width=device-width,initial-scale=1">'
'<title>Explore more: GlobalGrid2050 Explore Code</title>'
'<meta name="description" content="More ways into the open code behind GlobalGrid2050: pictogram view (Clarity), '
'periodic table, stories, Pilot, repository solar systems, code chess and experiments.">'
'<meta name="author" content="Ventus Ltd — GlobalGrid2050"><meta name="theme-color" content="#000000">'
'<link rel="canonical" href="%s"><style>%s</style><script type="application/ld+json">%s</script></head><body>'
'<header><p class="brand">GLOBALGRID2050 · EXPLORE CODE</p><h1>Explore more</h1>'
'<p class="lede">Other ways to explore the same open code. Pick a card to start.</p></header>'
'<nav aria-label="Site"><a href="index.html">Explore Code home</a><a href="search.html">Search</a>'
'<a href="llms-extras.txt">llms-extras.txt</a></nav>'
'<main><ul class="cards">%s</ul></main>'
'<footer>Ventus Ltd — GlobalGrid2050. Built from cut %s. Pages added by tools/explore/extras.py.</footer>'
'</body></html>') % (html.escape(base + 'more.html'), CSS, ld, cards, html.escape(cut or 'unknown'))
with open(os.path.join(site, 'more.html'), 'w', encoding='utf-8') as fh:
fh.write(page)
return items
def write_sitemap(site, base, records, cut):
day = (cut or datetime.date.today().isoformat())[:10]
urls = ['more.html'] + [p for r in records if r.get('status') == 'ok' for p in r['pages']]
body = ''.join('<url><loc>%s</loc><lastmod>%s</lastmod></url>' % (xml_escape(base + u), day) for u in urls[:50000])
with open(os.path.join(site, 'sitemap-extras.xml'), 'w', encoding='utf-8') as fh:
fh.write('<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'
+ body + '</urlset>\n')
rs = os.path.join(site, 'robots-sitemaps.txt')
line = 'Sitemap: %ssitemap-extras.xml' % base
existing = read_text(rs) if os.path.isfile(rs) else ''
if line not in existing:
with open(rs, 'a', encoding='utf-8') as fh:
fh.write(('' if not existing or existing.endswith('\n') else '\n') + line + '\n')
return len(urls)
def write_llms(site, base, records, items, cut):
L = ['# GlobalGrid2050 Explore Code: more experiences', '',
'Attribution: Ventus Ltd — GlobalGrid2050. Source repositories: https://github.com/Ventusltd. Cut %s.' % (cut or 'unknown'),
'', '> Extra views of the same open code, generated after the main build by tools/explore/extras.py. '
'Human hub: %smore.html. Main index: %sllms.txt.' % (base, base), '', '## Experiences', '']
for i in items:
L.append('- **%s**: %s HTML: %s' % (i['title'], i['desc'], base + i['href']))
data = [r for r in records if r.get('status') in ('ok', 'data') and r.get('data')]
if data:
L += ['', '## Machine-readable data', '']
for r in data:
ds = sorted(r['data'], key=lambda d: (not d.endswith(('/index.json', '/data.json', '/board.json')), d))
L += ['- %s: %s' % (r['title'], base + d) for d in ds[:8]]
if len(ds) > 8:
L.append('- %s: and %d more JSON/text files in %s%s/ (listed in %sextras.json)' % (
r['title'], len(ds) - 8, base, r['slug'], base))
with open(os.path.join(site, 'llms-extras.txt'), 'w', encoding='utf-8') as fh:
fh.write('\n'.join(L) + '\n')
def link_index(site, base):
"""Opt-in: link more.html from index.html's nav and llms.txt. Idempotent."""
idx = os.path.join(site, 'index.html')
if os.path.isfile(idx):
s = read_text(idx)
if 'href="more.html"' not in s and '</nav>' in s:
write_text(idx, s.replace('</nav>', '<a href="more.html">Explore more</a></nav>', 1))
ll = os.path.join(site, 'llms.txt')
if os.path.isfile(ll):
s = read_text(ll)
if 'llms-extras.txt' not in s:
write_text(ll, s.rstrip('\n') + ('\n\n## Explore more\n\n- Extra experiences (pictogram view (Clarity), periodic table, stories, Pilot, '
'code chess, per-repository Kuiper, lab views): HTML %smore.html · text %sllms-extras.txt\n'
% (base, base)))
def main(argv=None, extras=None, roots=None, posts=None):
ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])
ap.add_argument('--site', required=True, help='the built explore-code folder')
ap.add_argument('--graph', help='build_graph.json (default: <site>/build_graph.json)')
ap.add_argument('--base', help='public base URL (default: from build_graph.json, else EXPLORE_BASE)')
ap.add_argument('--src', help='folder of repository clones, passed to generators that take --src')
ap.add_argument('--only', default='', help='comma-separated slugs to run (default: all)')
ap.add_argument('--skip', default='', help='comma-separated slugs to skip')
ap.add_argument('--timeout', type=int, default=DEFAULT_TIMEOUT, help='seconds per extra (default %(default)s)')
ap.add_argument('--link-index', action='store_true', help='also link more.html from index.html and llms.txt')
ap.add_argument('--strict', action='store_true', help='exit 1 if an existing extra failed')
a = ap.parse_args(argv)
site = os.path.abspath(a.site)
graph = os.path.abspath(a.graph or os.path.join(site, 'build_graph.json'))
if not os.path.isdir(site):
warn('site folder %s does not exist; nothing to do' % site)
return 1 if a.strict else 0
cut, gbase = '', ''
try:
with open(graph, encoding='utf-8') as fh:
g = json.load(fh)
cut, gbase = g.get('cut', ''), g.get('base', '')
del g
except (OSError, ValueError) as e:
warn('cannot read %s (%s); extras that need it will fail and be skipped' % (graph, e))
base = a.base or gbase or os.environ.get('EXPLORE_BASE') or ''
if base and not base.endswith('/'):
base += '/'
only = {x for x in a.only.split(',') if x}
skip = {x for x in a.skip.split(',') if x}
ctx = {'site': site, 'graph': graph, 'base': base, 'src': os.path.abspath(a.src) if a.src else None, 'lab_out': None}
if os.path.isfile(os.path.join(site, 'lab', 'communities.json')):
ctx['lab_out'] = os.path.join(site, 'lab') # from an earlier run; refreshed below if the lab runs
records, post = [], []
def run_phase(phase):
for ex in (extras if extras is not None else EXTRAS):
if ex.get('phase', 'main') != phase or (only and ex['slug'] not in only) or ex['slug'] in skip:
continue
rec = run_extra(ex, ctx, max(a.timeout, ex.get('timeout', 0)), roots)
if rec['status'] == 'pending':
log('%s: pending (%s)' % (ex['slug'], rec['reason']))
if ex['slug'] == 'lab' and rec['status'] == 'ok':
ctx['lab_out'] = os.path.join(site, 'lab')
records.append(rec)
def run_posts(when):
for pp in (posts if posts is not None else POST):
if pp.get('when', 'post') != when or (only and pp['slug'] not in only) or pp['slug'] in skip:
continue
r = run_post(pp, ctx, a.timeout, roots)
r['when'] = when
post.append(r)
run_phase('main')
run_posts('pre')
run_phase('late')
shutil.rmtree(os.path.join(site, '.extras-staging'), ignore_errors=True)
# With --only/--skip, keep earlier results (extras.json) for extras not run now, if their folder is still there.
prev_p = os.path.join(site, 'extras.json')
if (only or skip) and os.path.isfile(prev_p):
try:
ran = {r['slug'] for r in records}
for r in json.loads(read_text(prev_p)).get('extras', []):
if r.get('slug') not in ran and r.get('status') in ('ok', 'data') and \
os.path.isdir(os.path.join(site, r['slug'])):
records.append(r)
except (ValueError, KeyError, TypeError):
pass
items = write_hub(site, base, records, cut, extras)
n = write_sitemap(site, base, records, cut)
write_llms(site, base, records, items, cut)
if a.link_index and items:
link_index(site, base)
run_posts('post')
with open(os.path.join(site, 'extras.json'), 'w', encoding='utf-8') as fh:
json.dump({'schema': 'explore-extras-v1', 'cut': cut, 'base': base,
'extras': records, 'post': post, 'hub': [i['href'] for i in items]}, fh, indent=1, ensure_ascii=False)
ok = [r['slug'] for r in records if r['status'] == 'ok']
failed = [r['slug'] for r in records if r['status'] == 'failed']
pending = [r['slug'] for r in records if r['status'] == 'pending']
data_only = [r['slug'] for r in records if r['status'] == 'data']
if data_only:
log('data only (no card): ' + ', '.join(data_only))
log('integrated: %s; failed: %s; pending: %s; hub cards %d; sitemap-extras %d urls' % (
', '.join(ok) or 'none', ', '.join(failed) or 'none', ', '.join(pending) or 'none', len(items), n))
return 1 if (a.strict and (failed or any(p['status'] == 'failed' for p in post))) else 0
if __name__ == '__main__':
sys.exit(main())Extract
A JavaScript module in the identity folder of Cosmic that runs the estate's OWN extraction code over the Explore Code files, using SHA-256.
ingestcosmic / tools/explore/identity/extract.mjs · lines 1–54 of 54 · Not reached from any entry point (candidate for review)
- What it does
- It loads data. Uses libraries node:fs, node:url. Side effects: reads or writes files.
- Inputs & outputs
- In: command-line arguments.
- What it achieves
- No statement of purpose was found in the file, a README line naming it, or its name.
- Why it matters
- No other file in the estate was found to import it.
- Application
- cosmic · tools/explore/identity · JavaScript module
- Uses
- node:fs, node:url
- Used by
- none found
- Produces
- none declared
- 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/identity/extract.mjs:1-54 · blob df3c648f70da8f13ffad4150cf57b44b70c9349b · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: unknown · users: none · canonical: unreached_review
// identity/extract.mjs — run the estate's OWN extraction code over the Explore Code files.
//
// Nothing here re-implements a hash. Two estate modules are executed unchanged:
// * stars/modular-star/lib.mjs (Modular Star: tablet = git blob id, element = sha256 of body lines,
// family = sha256('js\0' + acorn token key) or functions.py's ast.dump key for Python).
// lib.mjs imports bare 'acorn', 'acorn-walk', 'acorn-loose' and 'node:sqlite', so genome.py stages a
// byte-identical copy of lib.mjs + functions.py in a scratch dir next to a node_modules that links the
// installed acorn/acorn-walk; acorn-loose is not installed on this machine, so the stage holds a shim
// that throws, and lib.mjs's own catch records "Parse failed" for the (rare) files that need it.
// * spiders/species/genome-spider/lib/markers.mjs (genome-spider function hashes, constants and the
// earth-radius family), imported straight from the read-only source tree (it needs only node:crypto).
//
// Usage: node extract.mjs <staged-lib.mjs> <markers.mjs> <jobs.json> <out.jsonl>
// jobs.json = [{id, abs, path}], one output line per job.
import fs from 'node:fs';
import { pathToFileURL } from 'node:url';
const [libPath, markersPath, jobsPath, outPath] = process.argv.slice(2);
const lib = await import(pathToFileURL(libPath).href);
const markers = await import(pathToFileURL(markersPath).href);
const jobs = JSON.parse(fs.readFileSync(jobsPath, 'utf8'));
const out = fs.openSync(outPath, 'w');
for (const job of jobs) {
const bytes = fs.readFileSync(job.abs);
const rec = { id: job.id, blob: lib.gitBlobId(bytes), sha256: lib.sha256(bytes).toString('hex') };
const lang = lib.langOf(job.path);
rec.ms_lang = lang;
if (lang) {
const lines = lib.splitLines(bytes);
const { issue, functions } = lib.extractAny(lang, bytes);
rec.ms_issue = issue;
rec.ms_functions = [];
for (const f of functions) {
if (f.last > lines.length) continue; // same guard as lib.ingestFile
const body = Buffer.concat(lines.slice(f.first - 1, f.last));
rec.ms_functions.push({
first: f.first, last: f.last, name: f.name, kind: f.kind,
family_sha: Buffer.from(f.family).toString('hex'),
element_sha: lib.sha256(body).toString('hex'),
needs: f.needs ?? null, standalone: !!f.standalone,
});
}
}
// genome-spider reads files as utf8 text and only scans .js/.mjs/.cjs/.py for markers (spider.mjs:307).
if (/\.(js|mjs|cjs|py)$/.test(job.path)) {
const text = bytes.toString('utf8');
rec.gs_functions = markers.extractFunctions(text);
rec.gs_constants = markers.extractNamedConstants(text);
rec.gs_family_hits = markers.extractKnownFamilyHits(text);
}
fs.writeSync(out, JSON.stringify(rec) + '\n');
}
fs.closeSync(out);Genome
A Python command-line tool in the identity folder of Cosmic that reads jobs, rules, units and electron, using SHA-256. It loads JSON (`load_json`), runs extract (`run_extract`) and builds lite (`build_lite`).
storagecosmic / tools/explore/identity/genome.py · lines 1–455 of 824 · Entry point · pattern preference (shared by 2 files)
- What it does
- It loads jobs, rules, units and electron. Defines 24 functions or classes, including sha256_file, load_json, run_extract, modular_numbers, vedic_clusters. Uses libraries argparse, collections, glob, hashlib, importlib.util. Side effects: reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- README: "`genome.py` gives every file in `build_graph.json`, and every function inside it, the identity keys the estate already uses."
- Inputs & outputs
- In: JSON file jobs.json; JSON file rules.json; Parquet file units.parquet; Parquet file candidates.parquet; JSON file electron.json; JSON file entangled.json; JSON file functions.json; JSON file surfaces.json. Out: JSON file.
- Downstream impact
- Used directly by 3 files: Families (cosmic); Extras (cosmic); Test Genome (cosmic). Reached from 7 other entry points, including CI (cosmic); Ship (cosmic); Test Apply (cosmic).
- What it achieves
- The estate's own permanent identities and genome for every Explore Code file. It accepts `--graph`, `--src` and `--fingerprints`.
- Why it matters
- Imported by Families. Run by Extras. Checked by Test Genome.
- Application
- cosmic · tools/explore/identity · Python CLI
- Uses
- argparse, collections, glob, hashlib, importlib.util, json, math, os
- Used by
- imported by Families (sys.path import), run by Extras (script call), imported by Test Genome (import)
- Produces
- sha256_file, load_json, run_extract, modular_numbers, vedic_clusters, estate_blobs, norm_lines, preference, logical_group_key, build, default_path, work_dir
- Defines here
- sha256_file, load_json, run_extract, modular_numbers, vedic_clusters, estate_blobs, norm_lines, preference, logical_group_key, build, key_of, near_root, shells
- 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/identity/genome.py:1-455 · blob 82d260d119c6ebcca00de149b81cdc029f2b7484 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process, storage · domain stage: unknown · users: none · canonical: supporting_data
#!/usr/bin/env python3
"""identity/genome.py: the estate's own permanent identities and genome for every Explore Code file.
Writes /tmp/vk/7/identity.json (full, with a per-function view) and identity-files.json (files only),
keyed by build_graph file id. Every claim carries a key (Kuiper's first law: no claim without a key):
a file sha256, a git blob id, a Modular Star family number or family sha, a genome-spider function hash,
or a Vedic cluster id. Nothing is placed by narrative or model judgement.
Sources (see README.md for exact-versus-approximate):
file keys sha256 of bytes and git blob id (= Modular Star tablet key), commit from build_graph
Modular Star stars/modular-star/lib.mjs run unchanged (identity/extract.mjs) for family/element shas;
family numbers from stars/code/f/*.json places at the pinned commit
Spiders genome spiders/species/genome-spider/lib/markers.mjs run unchanged; markers recomputed over
the build_graph files; dead code / uncomposed matched from the committed genome.json
Quantum Twin star-quantum-twin concepts: shells K/L/M, P(AWAY)=M/(K+L+M), theta, twin, entanglement
Elements family:<n>, block:<Sym>, surface:<url> keys from elements/catalogue + its pinned register
Vedic fingerprints/candidates.py cluster_units() re-run in memory over out/units.parquet
Usage: python3 genome.py [--graph G] [--src S] [--out DIR] [--reuse-extract] [--lite]
Defaults work on a clean CI machine: graph $EXPLORE_GRAPH or _site/explore-code/build_graph.json, src $EXPLORE_SRC or
./clones, out $EXPLORE_WORK/7 or _work/7. Without node, acorn, a needed clone or the fingerprints parquet, it writes the
keys-only lite identity (build_lite) instead of failing.
"""
import argparse
import collections
import glob
import hashlib
import importlib.util
import json
import math
import os
import posixpath
import re
import shutil
import subprocess
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
SCHEMA = "explore-identity-v1"
SUBSTANTIAL_LINES = 5 # a shared function counts towards "family-shared" only if it spans >= 5 lines
NEAR_JACCARD = 0.8 # same threshold as Vedic fingerprints rules.json cluster.near_jaccard
COMMON_LINE_FILES = 60 # lines found in more files than this are ignored when proposing near pairs
TS_PREFIX = re.compile(r"^(\d{8,14})-(.+)$") # genome-spider lib/classify.mjs TIMESTAMP_PREFIX
RELEASE_SEG = re.compile(r"(^|/)(releases?|archive|backup|old|site_versions|homepage_versions|nightly|\d{8,14})(/|$)")
def sha256_file(path):
h = hashlib.sha256()
with open(path, "rb") as fh:
for chunk in iter(lambda: fh.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def load_json(path):
with open(path, encoding="utf-8") as fh:
return json.load(fh)
# ----------------------------------------------------------------------------------------- extraction
def run_extract(graph, src, out_dir, reuse):
"""Run identity/extract.mjs (estate code, unchanged) over every file. Returns {id: record}."""
out = os.path.join(out_dir, "extract.jsonl")
if not (reuse and os.path.exists(out)):
stage = os.path.join(out_dir, "stage")
shutil.rmtree(stage, ignore_errors=True)
os.makedirs(os.path.join(stage, "node_modules", "acorn-loose"))
ms = os.path.join(src, "stars", "modular-star")
for name in ("lib.mjs", "functions.py"):
shutil.copyfile(os.path.join(ms, name), os.path.join(stage, name))
for mod in ("acorn", "acorn-walk"):
target = next((p for p in (f"/opt/node-tools/node_modules/{mod}", f"/opt/npm-tools/node_modules/{mod}")
if os.path.isdir(p)), None)
if not target:
raise SystemExit(f"{mod} not installed; cannot run the Modular Star extractor")
os.symlink(target, os.path.join(stage, "node_modules", mod))
shim = os.path.join(stage, "node_modules", "acorn-loose")
with open(os.path.join(shim, "package.json"), "w") as fh:
fh.write('{"name":"acorn-loose","type":"module","exports":"./index.js"}')
with open(os.path.join(shim, "index.js"), "w") as fh:
fh.write("export function parse(){ throw new Error('acorn-loose is not installed on this machine'); }\n")
jobs = [{"id": f["id"], "abs": os.path.join(src, f["repo"], f["path"]), "path": f["path"]} for f in graph["files"]]
jobs_path = os.path.join(out_dir, "jobs.json")
with open(jobs_path, "w") as fh:
json.dump(jobs, fh)
markers = os.path.join(src, "spiders", "species", "genome-spider", "lib", "markers.mjs")
subprocess.run(["node", "--no-warnings", os.path.join(HERE, "extract.mjs"),
os.path.join(stage, "lib.mjs"), markers, jobs_path, out], check=True)
recs = {}
with open(out, encoding="utf-8") as fh:
for line in fh:
r = json.loads(line)
recs[r["id"]] = r
return recs
# ----------------------------------------------------------------------------------------- Modular Star
def modular_numbers(graph, recs, src):
"""Family numbers: exact where a published place sits at the pinned commit on the same lines and name;
matched where our reproduced family sha was calibrated to a number by such a place."""
commit = {r["repo"]: r["commit"] for r in graph["repos"]}
by_path = {(f["repo"], f["path"]): f["id"] for f in graph["files"]}
fams = {}
for path in sorted(glob.glob(os.path.join(src, "stars", "code", "f", "*.json"))):
for k, v in load_json(path).items():
fams[int(k)] = v
exact = {} # (file id, first, last, name) -> n
sha2n = collections.defaultdict(set)
n2sha = collections.defaultdict(set)
estate_places = collections.defaultdict(set) # n -> {(repo, path)} across the whole published record
unmatched = 0
for n, v in fams.items():
for p in v["places"]:
repo = p["repo"].split("/", 1)[1]
estate_places[n].add((repo, p["path"]))
fid = by_path.get((repo, p["path"]))
if fid is None or p["commit"] != commit.get(repo):
continue
hits = [x for x in recs[fid].get("ms_functions") or []
if x["first"] == p["first"] and x["last"] == p["last"] and x["name"] == p["name"]]
if not hits:
unmatched += 1
continue
for x in hits:
exact[(fid, x["first"], x["last"], x["name"])] = n
sha2n[x["family_sha"]].add(n)
n2sha[n].add(x["family_sha"])
calib = {s: next(iter(ns)) for s, ns in sha2n.items() if len(ns) == 1}
checks = {
"published_families": len(fams),
"places_at_pinned_commit_matched": len(exact),
"places_at_pinned_commit_unmatched": unmatched,
"family_sha_to_several_numbers": sum(1 for ns in sha2n.values() if len(ns) > 1),
"number_to_several_family_shas": sum(1 for ss in n2sha.values() if len(ss) > 1),
"calibrated_family_shas": len(calib),
}
return fams, exact, calib, estate_places, checks
# ----------------------------------------------------------------------------------------- Vedic
def vedic_clusters(fp_dir):
spec = importlib.util.spec_from_file_location("vedic_candidates", os.path.join(fp_dir, "candidates.py"))
mod = importlib.util.module_from_spec(spec)
sys.path.insert(0, fp_dir)
try:
spec.loader.exec_module(mod)
finally:
sys.path.remove(fp_dir)
rules = mod.load_rules(os.path.join(fp_dir, "rules.json"))
units = mod.load_units(os.path.join(fp_dir, "out", "units.parquet"))
is_stop = mod.stop_matcher(rules)
kept, dropped = [], {}
for u in units:
if (u["n_tokens"] or 0) < rules["cluster"]["min_tokens"]:
dropped[u["unit_id"]] = "below min_tokens"
elif is_stop(u["name"]):
dropped[u["unit_id"]] = "stop name"
else:
kept.append(u)
kept.sort(key=lambda u: u["unit_id"])
clusters, _stats = mod.cluster_units(kept, rules)
unit_cluster, cluster_size, cluster_repos = {}, {}, {}
for idx in clusters:
ids = [kept[i]["unit_id"] for i in idx]
cid = mod.cluster_id(ids)
cluster_size[cid] = len(ids)
cluster_repos[cid] = len({kept[i]["repo"] for i in idx})
for i in ids:
unit_cluster[i] = cid
import pyarrow.parquet as pq
cand = pq.read_table(os.path.join(fp_dir, "out", "candidates.parquet"),
columns=["cluster_id", "suggested_word", "score"]).to_pylist()
cand = {c["cluster_id"]: c for c in cand}
check = {"units": len(units), "clusters_reproduced": len(cluster_size),
"candidate_clusters_published": len(cand),
"candidate_clusters_reproduced": sum(1 for c in cand if c in cluster_size)}
return units, unit_cluster, cluster_size, cluster_repos, cand, dropped, check
# ----------------------------------------------------------------------------------------- estate blobs
def estate_blobs(graph, src):
"""git blob id -> [(repo, path)] for every tracked file at HEAD of every graph repo (exact, from git)."""
out = collections.defaultdict(list)
heads = {}
for r in sorted(x["repo"] for x in graph["repos"]):
d = os.path.join(src, r)
try:
heads[r] = subprocess.run(["git", "-C", d, "rev-parse", "HEAD"], capture_output=True, text=True,
check=True).stdout.strip()
tree = subprocess.run(["git", "-C", d, "ls-tree", "-r", "-z", "HEAD"], capture_output=True,
check=True).stdout
except (subprocess.CalledProcessError, FileNotFoundError):
continue
for ent in tree.split(b"\0"):
if not ent:
continue
meta, _, path = ent.partition(b"\t")
parts = meta.split()
if len(parts) == 3 and parts[1] == b"blob":
out[parts[2].decode()].append((r, path.decode("utf-8", "surrogateescape")))
return out, heads
# ----------------------------------------------------------------------------------------- helpers
def norm_lines(path):
try:
with open(path, "rb") as fh:
data = fh.read()
except OSError:
return set()
out = set()
for raw in data.split(b"\n"):
s = b" ".join(raw.split())
if len(s) >= 4:
out.add(hashlib.blake2b(s, digest_size=8).digest())
return out
def preference(f):
"""Deterministic 'which copy is the original' order (smaller is preferred). Documented in README."""
p = f["path"]
return (0 if f["reachable"] else 1,
0 if f["canonical_status"] == "production_core" else 1,
1 if RELEASE_SEG.search(p) else 0,
len(p), f["repo"], p, f["id"])
def logical_group_key(path):
d, _, base = path.rpartition("/")
m = TS_PREFIX.match(base)
return f"{d}::{m.group(2) if m else base}"
# ----------------------------------------------------------------------------------------- build
def build(args):
graph = load_json(args.graph)
files = graph["files"]
fid = {f["id"]: f for f in files}
commit = {r["repo"]: r["commit"] for r in graph["repos"]}
os.makedirs(args.out, exist_ok=True)
recs = run_extract(graph, args.src, args.out, args.reuse_extract)
missing = [f["id"] for f in files if f["id"] not in recs]
if missing:
raise SystemExit(f"extract.jsonl misses {len(missing)} files")
def key_of(f):
r = recs[f["id"]]
return f"{f['repo']}@{commit.get(f['repo'], '-')} {f['path']}:1-{max(1, f['lines'])} {r['blob']}"
# --- Modular Star numbers
fams, exact, calib, estate_places, ms_check = modular_numbers(graph, recs, args.src)
# --- Star Quantum Twin, Elements, genome-spider records
sqt = os.path.join(args.src, "star-quantum-twin", "data")
atoms = load_json(os.path.join(sqt, "electron.json"))["atoms"]
atoms_by_name = collections.defaultdict(list)
for a in atoms:
atoms_by_name[a["name"]].append(a)
entangled = load_json(os.path.join(sqt, "entangled.json"))["entanglements"]
ent_by_def = {(e["defined_in"], e["name"]): e for e in entangled}
el = os.path.join(args.src, "elements")
el_funcs = {int(x["key"].split(":")[1]): x for x in load_json(os.path.join(el, "catalogue", "functions.json"))}
surfaces = sorted((x["url"] for x in load_json(os.path.join(el, "catalogue", "surfaces.json"))), key=len, reverse=True)
reg_path = sorted(glob.glob(os.path.join(el, "inputs", "blocks-*.json")))[-1]
blocks_by_file = collections.defaultdict(set)
for b in load_json(reg_path)["blocks"]:
for fl in b["files"]:
blocks_by_file[(fl["repo"].split("/", 1)[-1], fl["path"])].add("block:" + b["symbol"])
gs_genome = load_json(os.path.join(args.src, "spiders", "species", "genome-spider", "data", "genome.json"))
gs_dead = {(d.get("repo", "").split("/")[-1], d.get("path")) for d in gs_genome["markers"].get("dead_code", [])}
gs_uncomposed = {(d.get("repo", "").split("/")[-1], d.get("path")) for d in gs_genome["markers"].get("uncomposed", [])}
# --- Vedic
units, unit_cluster, cluster_size, cluster_repos, cand, dropped, vd_check = vedic_clusters(args.fingerprints)
units_by_file = collections.defaultdict(list)
for u in units:
if commit.get(u["repo"]) == u["commit"]:
units_by_file[(u["repo"], u["path"])].append(u)
blobs, heads = estate_blobs(graph, args.src)
head_mismatch = sorted(r for r, h in heads.items() if commit.get(r) != h)
# --- exact copy groups (sha256 of bytes)
by_sha = collections.defaultdict(list)
for f in files:
by_sha[recs[f["id"]]["sha256"]].append(f["id"])
group_of, canon_of = {}, {}
for sha, ids in by_sha.items():
ordered = sorted(ids, key=lambda i: preference(fid[i]))
for i in ids:
group_of[i] = sha
canon_of[i] = ordered[0]
# --- near copies: line-set Jaccard over normalised lines, on canonical representatives only
reps = sorted({canon_of[f["id"]] for f in files})
lines = {i: norm_lines(os.path.join(args.src, fid[i]["repo"], fid[i]["path"])) for i in reps}
inv = collections.defaultdict(list)
for i in reps:
for h in lines[i]:
inv[h].append(i)
shared = collections.Counter()
for h, ids in inv.items():
if 1 < len(ids) <= COMMON_LINE_FILES:
for a in range(len(ids)):
for b in range(a + 1, len(ids)):
shared[(ids[a], ids[b])] += 1
near = collections.defaultdict(list) # rep -> [(jaccard, other rep)]
for (a, b), c in shared.items():
la, lb = lines[a], lines[b]
if not la or not lb or c < NEAR_JACCARD * min(len(la), len(lb)) * 0.5:
continue
inter = len(la & lb)
jac = inter / len(la | lb)
if jac >= NEAR_JACCARD:
near[a].append((round(jac, 4), b))
near[b].append((round(jac, 4), a))
near_target = {}
for i in reps:
better = [(j, o) for j, o in near[i] if preference(fid[o]) < preference(fid[i])]
if better:
j, o = sorted(better, key=lambda t: (-t[0], preference(fid[t[1]])))[0]
near_target[i] = (o, j)
# a near-copy's target may itself be a near-copy: follow to the root (preference strictly decreases)
def near_root(i):
seen, j_min = set(), 1.0
while i in near_target and i not in seen:
seen.add(i)
i, j = near_target[i]
j_min = min(j_min, j)
return i, j_min
# "group" for excluding internal sharing: exact group + near-copy cluster root
cluster_root = {}
for f in files:
r = canon_of[f["id"]]
cluster_root[f["id"]] = near_root(r)[0] if r in near_target else r
# --- function-level indexes
fam_files = collections.defaultdict(set) # family key -> file ids (graph)
name_fams = collections.defaultdict(set) # name -> {(family key, repo)}
gs_name = collections.defaultdict(set) # genome-spider name -> {(hash, file id)}
const_vals = collections.defaultdict(set)
redo = collections.defaultdict(list)
func_rows = {}
for f in files:
r = recs[f["id"]]
rows = []
for x in r.get("ms_functions") or []:
n = exact.get((f["id"], x["first"], x["last"], x["name"]))
basis = "exact"
if n is None:
n = calib.get(x["family_sha"])
basis = "matched" if n is not None else "unnumbered"
fkey = f"family:{n}" if n is not None else "familysha:" + x["family_sha"][:16]
rows.append({**x, "family": n, "family_basis": basis, "fkey": fkey})
fam_files[fkey].add(f["id"])
if x["name"] not in ("(anonymous)", "default"):
name_fams[x["name"]].add((fkey, f["repo"]))
func_rows[f["id"]] = rows
for g in r.get("gs_functions") or []:
gs_name[g["name"]].add((g["hash"], f["id"]))
for c in r.get("gs_constants") or []:
const_vals[c["name"]].add(c["value"])
redo[(f["repo"], logical_group_key(f["path"]))].append(f["id"])
# --- quantum shells from build_graph dependents
def shells(f):
K = L = M = 0
valence, paired = set(), False
fdir = posixpath.dirname(f["path"])
for d in f["dependents"]:
g = fid.get(d)
if g is None:
continue
if re.search(r"(test|proof|spec)", g["path"], re.I):
paired = True
if g["repo"] != f["repo"]:
M += 1
valence.add(g["repo"])
elif posixpath.dirname(g["path"]) == fdir:
K += 1
else:
L += 1
tot = K + L + M
p = M / tot if tot else None
if tot == 0:
pole = "unbound"
elif M == 0:
pole = "HOME"
elif K + L == 0:
pole = "AWAY"
else:
pole = "superposed"
return {"K": K, "L": L, "M": M, "p_away": None if p is None else round(p, 4),
"theta": None if p is None else round(2 * math.asin(math.sqrt(p)), 4),
"pole": pole, "valence": len(valence), "valence_repos": sorted(valence),
"spin": "paired" if paired else "unpaired"}
sigs = {}
for f in files:
m = {}
for s in f.get("signatures") or []:
nm = s.split("(", 1)[0].strip()
m.setdefault(nm, s)
sigs[f["id"]] = m
out_files = {}
verdicts = collections.Counter()
for f in files:
i = f["id"]
r = recs[i]
own_cluster = cluster_root[i]
keys = {"sha256": r["sha256"], "git_blob": r["blob"], "commit": commit.get(f["repo"]), "key": key_of(f)}
# genome-spider genome
gsf = r.get("gs_functions")
dup_agree, dup_disagree = [], []
for g in gsf or []:
others = {(h, o) for h, o in gs_name[g["name"]] if o != i and cluster_root[o] != own_cluster}
if not others:
continue
if any(h == g["hash"] for h, _ in others):
dup_agree.append(g["name"])
else:
dup_disagree.append(g["name"])
drift = sorted({c["name"] for c in r.get("gs_constants") or [] if len(const_vals[c["name"]]) > 1})
earth = sorted({h["value"] for h in r.get("gs_family_hits") or []})
rgroup = redo[(f["repo"], logical_group_key(f["path"]))]
if gsf is None:
gcode, ghash = "GS-none", None
else:
ghash = hashlib.sha256("\n".join(sorted(g["hash"] for g in gsf)).encode()).hexdigest()[:12] if gsf else "0"
gcode = (f"GS-{ghash}-D{len(set(dup_agree))}V{len(set(dup_disagree))}"
f"K{len(drift)}E{len(earth)}R{len(rgroup) - 1}")
genome = {"code": gcode, "functions_hash": ghash, "functions": len(gsf or []),
"duplication_agree": sorted(set(dup_agree)), "duplication_disagree": sorted(set(dup_disagree)),
"drift_constants": drift, "earth_radius_values": earth,
"re_doing_group": sorted(rgroup) if len(rgroup) > 1 else [],
"dead_code_record": (f["repo"], f["path"]) in gs_dead,
"uncomposed_record": (f["repo"], f["path"]) in gs_uncomposed}
# Modular Star + Elements + function view
funcs, shared_keys, fam_list = [], set(), []
el_fams, el_blocks = set(), set(blocks_by_file.get((f["repo"], f["path"]), ()))
for x in func_rows[i]:
span = x["last"] - x["first"] + 1
in_graph = {o for o in fam_files[x["fkey"]] if o != i and cluster_root[o] != own_cluster}
estate = set()
if x["family"] is not None:
fam_list.append(x["family"])
estate = {pl for pl in estate_places.get(x["family"], ()) if pl != (f["repo"], f["path"])}
if x["family"] in el_funcs:
el_fams.add(f"family:{x['family']}")
if el_funcs[x["family"]].get("block"):
el_blocks.add(el_funcs[x["family"]]["block"])
twins = sorted({rp for fk, rp in name_fams.get(x["name"], ()) if fk != x["fkey"] and rp != f["repo"]})