In this section
- Build render · cosmic / tools/explore/build.py lines 3501–3776
- Board storage · cosmic / tools/explore/chess/board.py lines 1–331
Build
A Python command-line tool in the explore folder of Cosmic that maps dictionary and build graph, using EPSG:27700 and EPSG:4326, and uses data from the GridAtlas, ventus-grid-engine and SatNav repositories.
rendercosmic / tools/explore/build.py · lines 3501–3776 of 3776 (continued from section 1080) · Entry point · pattern clean_comment (shared by 2 files)
- What it does
- It maps dictionary, build graph, words and solar. Defines 114 functions or classes, including words_of, git, ext, slug, load_leaks. Uses libraries argparse, collections, datetime, fnmatch, html. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain terms in the code: solar, 132kV, 33kV, 11kV, 11kV/400V, 400V. README: "`build.py` is the method"
- Inputs & outputs
- In: data source: gridatlas data; data source: ventus-grid-engine data; data source: satnav data; data source: solar-electrical-topology-analysis-engine-text-based data; JSON file dictionary.json; JSON file build_graph.json; Parquet file code.parquet; Parquet file words.parquet. Out: Parquet file; JSON file; interactive map; SVG drawing. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326, Web Mercator / EPSG:3857, ETRS89 / EPSG:4258. Voltage levels named: 132kV, 33kV, 11kV, 11kV/400V, 400V.
- Downstream impact
- Used directly by 3 files: Cadastre 27 (cosmic); Ship (cosmic); Test Build (cosmic). Reached from 1 other entry point, including Test Ship (cosmic).
- What it achieves
- It loads leaks (`load_leaks`), loads essays (`load_essays`) and cleans key (`clean_key`). The README says: `build.py` is the method. Its code works with 132 kV, 33 kV and 11 kV. It writes `words/index.html`.
- Why it matters
- Imported by Cadastre 27. Run by Ship. Checked by Test Build.
- Application
- cosmic · tools/explore · Python CLI
- Uses
- Describe (import), Agentdocs (import), GridAtlas — Index Page (estate URL), SatNav — Scope Page (estate URL), Solar Electrical Topology Analysis Engine Text Based — Index Page (estate URL), argparse, collections, datetime, fnmatch, html, json, os, posixpath
- Used by
- imported by Cadastre 27 (sys.path import), run by Ship (script call), imported by Test Build (import)
- Produces
- words_of, git, ext, slug, load_leaks, humanise, kind_of, name_words, stamp_note, title_parts, title_of, repo_title
- Defines here
- write_shard, kb, shard_refs, page_cost, word_page_of, write_parquet, put, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/build.py:3501-3776 · blob a82b6f8252f926b3e24b5469dc1f3b7b2ead6a33 · GitHub at these lines
- State
- achieves: readme · context: readme_derived · stage: output · effects: dom, filesystem, network, process, storage · domain stage: unknown · users: none · canonical: unknown
'tools/explore/build.py (rules %s); every statement is evidence-keyed and links to the exact commit and '
'lines. Fields per file: Source (GitHub commit URL with line range), Page (Explore Code section), '
'Synopsis, What it achieves (provenance), the four-part block, Signatures, VEDIC, domain_stage, '
'commercial_user, canonical_status, data_contracts, Edges. Rules: %sllms.txt (Agent Navigation Protocol) '
'and GRAPH-CONTRACT.md.\n' % (AUTHOR, stamp, agentdocs.RULES_VERSION, base))
shards = [] # (group, label, [(name, size)])
def write_shard(group, label, stem, title, intro, fis):
header = '# %s\n\n%s\n%s\n' % (title, legend_txt, intro)
parts = agentdocs.split_parts(stem, header, [blocks[i] for i in fis])
out_parts = []
for name, text in parts:
with open(os.path.join(out, name), 'w', encoding='utf-8', newline='\n') as fh:
fh.write(text)
out_parts.append((name, len(text.encode('utf-8'))))
shards.append((group, label, out_parts))
return out_parts
topic_shards = {}
for k, t, d, _ in TOPIC_RX:
fis = [i for i, f in enumerate(files) if f['topic'] == k]
if fis:
topic_shards[k] = write_shard('topic', t, k, '%s — %s (text shard)' % (t, SITE),
'Topic page: %stopics/%s.html. %s %d files.\n' % (base, k, d, len(fis)), fis)
core = [r for r in CORE_REPOS if r in by_repo]
start_here, repo_shards = {}, {}
for r in core:
# The front teaches (agent reading review): summary and live pages first, the most-used files next,
# tests and CI last (agentdocs.shard_order).
fis = sorted(repo_files[r], key=lambda i: agentdocs.shard_order(dict(
path=files[i]['path'], kind=files[i]['kind'], role=files[i]['role'], entry=files[i]['entry'],
published=files[i]['published'], n_dependents=len(imported_by.get(i, [])))))
start_here[r] = start_of(r)
live = [i for i in fis if files[i]['entry'] and files[i]['published']][:5]
summary = ('Summary%s: %s\n' % ({'core_hook_draft': ' (draft awaiting owner approval)', 'code': ' (from code evidence)'}
.get(descriptor_src(r), ''), descriptor(r, 1200)))
if live:
summary += 'Live pages: %s\n' % '; '.join('%s %s' % (files[i]['title'], files[i]['published']) for i in live)
summary += 'Order below: live entry pages, other entry points, most-used files; tests and CI last.\n'
repo_shards[r] = write_shard('repo', r, 'repo-' + slug(r), '%s (%s) — core production engine — %s (text shard)'
% (repo_title(r), r, SITE),
'Repository page: %srepos/%s.html. Licence: %s. Commit %s. %d files.\n%s'
% (base, slug(r), metas[r]['license'], metas[r]['commit'], len(fis), summary), fis)
for jn in journeys:
intro = ['Journey page: %s%s. Steps (%s):' % (base, jn['url'], jn['source'])]
for k, st in enumerate(jn['steps'], 1):
if not st['found']:
intro.append('%d. %s: not found in the public estate.%s' % (k, st['label'], ''.join(' ' + n for n in st['notes'])))
else:
intro.append('%d. %s: %s' % (k, st['label'], '; '.join('%s%s (found by %s: %s)' % (
l['repo'], '/' + l['folder'] if l['folder'] else '', l['evidence'], l['detail']) for l in st['locations'])))
intro.append('\nLinks between steps:')
intro += ['- ' + agentdocs.link_sentence(p, files) for p in jn['links']]
header = '# %s — %s (text shard)\n\n%s\n%s\n' % (jn['title'], SITE, legend_txt, '\n'.join(intro) + '\n')
body = []
for k, st in enumerate(jn['steps'], 1):
body.append('## Step %d: %s\n\n' % (k, st['label']) + ('' if st['found'] else 'Not found in the public estate.\n\n'))
body += [blocks[i] for i in dict.fromkeys(st['entry_files'] + st['key_files'])]
parts = agentdocs.split_parts('journey-' + jn['id'], header, body)
out_parts = []
for name, text in parts:
with open(os.path.join(out, name), 'w', encoding='utf-8', newline='\n') as fh:
fh.write(text)
out_parts.append((name, len(text.encode('utf-8'))))
jn['shard'] = out_parts[0][0]
shards.append(('journey', jn['title'], out_parts))
full_size = sum(len(b.encode('utf-8')) for b in blocks)
full_name = None
if full_size < 25 * 1024 * 1024:
full_name = 'llms-full.txt'
with open(os.path.join(out, full_name), 'w', encoding='utf-8', newline='\n') as fh:
fh.write('# %s — every file (text)\n\n%s\nOrdered by topic, repository and path.\n\n' % (SITE, legend_txt))
fh.writelines(blocks)
else:
full_name = 'llms-full-index.txt'
with open(os.path.join(out, full_name), 'w', encoding='utf-8', newline='\n') as fh:
fh.write('# %s — shard index\n\nllms-full.txt would be %d bytes, so it is not written; fetch the shards.\n\n%s'
% (SITE, full_size, ''.join('- %s%s (%d bytes)\n' % (base, n, z) for g, l, ps in shards for n, z in ps)))
full_bytes = os.path.getsize(os.path.join(out, full_name))
agent_files = ['llms.txt', full_name] + [n for g, l, ps in shards for n, z in ps]
# Crawl aids: sitemap index of an "essays" sitemap (hubs), a "code" sitemap (sections), an "agents" sitemap (text)
hubs = ['index.html', 'search.html', 'words/index.html'] + ['topics/%s.html' % k for k, *_ in TOPICS
if any(m['topic'] == k for m in section_meta)] + \
['repos/%s.html' % slug(r) for r in pub] + [jn['url'] for jn in journeys] + ['words/%s.html' % p for p in sorted(pages)]
code = [sname(i) for i in range(1, len(sections) + 1)]
lastmod = stamp[:10]
smaps = ('sitemap-essays.xml', 'sitemap-code.xml', 'sitemap-agents.xml')
for name, urls in zip(smaps, (hubs, code, agent_files + ['build_graph.json'])):
with open(os.path.join(out, name), 'w') as fh:
fh.write('<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'
+ ''.join('<url><loc>%s%s</loc><lastmod>%s</lastmod></url>\n' % (base, E(u), lastmod) for u in urls)
+ '</urlset>\n')
with open(os.path.join(out, 'sitemap.xml'), 'w') as fh:
fh.write('<?xml version="1.0" encoding="UTF-8"?>\n<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'
+ ''.join('<sitemap><loc>%s%s</loc><lastmod>%s</lastmod></sitemap>\n' % (base, n, lastmod)
for n in smaps) + '</sitemapindex>\n')
with open(os.path.join(out, 'robots-sitemaps.txt'), 'w') as fh:
fh.write(''.join('Sitemap: %s%s\n' % (base, n) for n in ('sitemap.xml',) + smaps))
# llms.txt: the routing index (agentdocs; owner brief requirement 1a), kept under ~15k tokens
def kb(z):
return '%.0f KB' % (z / 1024) if z < 1024 * 1024 else '%.1f MB' % (z / 1024 / 1024)
def shard_refs(parts):
return ', '.join('%s%s (%s)' % (base, n, agentdocs.size_label(z)) for n, z in parts)
def page_cost(rel):
pth = os.path.join(out, rel)
return ' (%s)' % agentdocs.size_label(os.path.getsize(pth)) if os.path.exists(pth) else ''
n_unr = len(files) - n_reach
canon_n = collections.Counter(f['canon'] for f in files)
L = ['# GlobalGrid2050 Explore Code', '',
'Attribution: %s. Source repositories: https://github.com/Ventusltd (%d public repositories, each read at its HEAD '
'commit). Code is under each repository\'s own licence (see Licences). Cut %s. Rules %s.' % (
AUTHOR, len(pub), stamp, agentdocs.RULES_VERSION), '',
'> The open code behind GlobalGrid2050: %s lines of unique code from %d public Ventusltd repositories, %d files in '
'%d static pages with the code as plain text. This file is a routing index: start from a core engine, a topic or '
'a journey below, then fetch the matching text shard or build_graph.json.' % (
format(total, ','), len(by_repo), len(files), len(sections)), '',
'## Elevator (read this first)', ''] + agentdocs.elevator(
' '.join(agentdocs.mission_sentences()[k] for k in agentdocs.ELEVATOR_MISSION),
[(repo_title(r), ('(draft) ' if descriptor_src(r) == 'core_hook_draft' else '') + descriptor(r, 200),
'%srepos/%s.html%s' % (base, slug(r), page_cost('repos/%s.html' % slug(r)))) for r in core],
'Sizes and token costs (characters / 4) stand beside every link; anything over 200k tokens says so.') + [
'', '## Domain and commercial mission (continued)', '',
' '.join(x for k, x in enumerate(agentdocs.mission_sentences()) if k not in agentdocs.ELEVATOR_MISSION)] + [
'', '## Core production engines (start here)', '',
'Chosen by the owner (CORE_REPOS in build.py). "Start here" is the repository page plus one entry point: a '
'GlobalGrid2050 homepage launch button into the repository (its Pages root page first), else its Pages root page, '
'else its published entry point reaching the most files, else any entry point reaching the most files.', '']
for r in core:
i, why_start = start_here[r]
L.append('- **%s** (%s): %sStart here: %srepos/%s.html%s%s · text shard: %s' % (
repo_title(r), r, {'readme': '', 'core_hook': '', 'core_hook_draft': '(one-line draft above, awaiting owner approval) '}.get(
descriptor_src(r), '(one line above from code evidence) '),
base, slug(r),
(' · entry point "%s" %s%s#f%d (%s; reaches %d files%s)' % (
files[i]['title'], base, sname(first_section[i][0]), first_section[i][1], why_start, reach_size.get(i, 0),
('; live at %s' % files[i]['published']) if files[i]['published'] else '')) if i is not None else '',
(' · site: %s' % metas[r]['pages']) if metas[r]['pages'] else '', shard_refs(repo_shards[r])))
L += ['', '## Topic hubs', '']
for k, t, d, _ in TOPIC_RX:
if k in topic_shards:
L.append('- **%s**: %s HTML: %stopics/%s.html · text: %s' % (t, d, base, k, shard_refs(topic_shards[k])))
L += ['', '## User journey slices', '',
'The four cross-repository workflows named in Ventus Ltd\'s brief, mapped to code by fixed rules (repository name, '
'GlobalGrid2050 homepage launch link, folder name). Steps or links that were not found are stated, never filled in.', '']
for jn in journeys:
L.append('- **%s**: %s. HTML: %s%s · text: %s%s' % (
jn['title'], ' → '.join(s['label'] + ('' if s['found'] else ' (not found in the public estate)') for s in jn['steps']),
base, jn['url'], base, jn['shard']))
L += ['', '## Agent navigation protocol', '',
'1. **Graph.** Fetch %sbuild_graph.json (one compact JSON file; contract: GRAPH-CONTRACT.md in Ventusltd/cosmic, '
'tools/explore). `files[i]` has repo, path, title, synopsis, achieves (+ achieves_provenance), why, role, stage, '
'entry, reachable, imports / dependents (file ids, "what it uses" / "what uses it"), edge_kinds, domain_stage, '
'commercial_user, data_contracts, canonical_status, duplicate_of, four_part, signatures, section and block. '
'`edges` is [[from_id, to_id, kind, via]]; `journeys` holds the slices above. Ids are stable within one cut only: '
'key on repo + path across cuts. Example: `jq \'.files[] | select(.repo=="satnav" and .entry) | .path\'`.' % base,
'2. **Tables.** DuckDB reads the Parquet tables over HTTP: `SELECT repo, path, line, text FROM '
'read_parquet(\'%sdata/code.parquet\') WHERE text ILIKE \'%%haversine%%\'` (every line; columns repo, path, line, '
'text, section, block). Also data/files.parquet (section, block, repo, commit_sha, path, blob_sha, line_from, '
'line_to, topic, capability), data/sections.parquet and data/words.parquet (definitions).' % base,
'3. **Confidence.** Where a statement came from, highest first: human (an essay written by people, '
'essay_status human) > comment (the file\'s own comment) > code (a VEDIC dictionary meaning matched by function '
'name) > readme (a README sentence naming the file) > name (the file name alone). Section pages show this as the '
'State line. Prefer higher tiers; treat name-only statements as hints.',
'4. **Labels.** domain_stage, commercial_user, data_contracts and canonical_status are fixed rules over evidence '
'(path and repository words, voltages and coordinate systems in the code, edges); `unknown` or empty means no '
'evidence, not "none". `domain_stage_evidence` says which rule decided. Note: %s; rules: %s' % (
LABELS_NOTE % agentdocs.RULES_VERSION, RULES_URL),
'5. **Reachability.** entry = an HTML page, workflow, CLI script, package entry or file a page/workflow loads. '
'reachable = reached from an entry point over resolved references of every kind (imports, page loads, links, '
'estate URLs, workflow and script calls; comment links are mentions and are not followed). Blind spots: paths '
'built at run time, JSON manifests, shell loops. %s' % reach_line,
'6. **Review rule.** %d files are not reached (canonical_status unreached_review or duplicate_candidate: %d '
'unreached_review, %d duplicate_candidate). They are candidates for review: never delete them, and never rely on '
'them as live behaviour, without review by a person.' % (n_unr, canon_n['unreached_review'],
canon_n['duplicate_candidate']),
'7. **Verify.** Every file is keyed repo@commit path:from-to with its blob SHA. Check any claim at '
'https://github.com/Ventusltd/<repo>/blob/<commit>/<path>#L<from>-L<to> (raw: '
'https://raw.githubusercontent.com/Ventusltd/<repo>/<commit>/<path>). Pages state what cannot be concluded: '
'whether code runs, is live, or is correct.',
'', '## Text shards and data', '',
'- Every file, one text: %s%s (%s)%s' % (base, full_name, agentdocs.size_label(full_bytes),
'' if full_name == 'llms-full.txt' else ' (index of shards; the full text would be too large)'),
'- Shards: %d topic, %d core engine and %d journey files listed above; each under 5 MB, split into -01, -02 parts '
'when larger.' % (sum(len(ps) for g, l, ps in shards if g == 'topic'), sum(len(ps) for g, l, ps in shards if g == 'repo'),
sum(len(ps) for g, l, ps in shards if g == 'journey')),
'- Graph: %sbuild_graph.json · Parquet: %sdata/code.parquet, %sdata/files.parquet, %sdata/sections.parquet, '
'%sdata/words.parquet' % (base, base, base, base, base),
'- Sitemaps: %ssitemap.xml (pages, sections, agent text) · visual explorer: %svisual/index.html' % (base, base),
'', '## Licences', '']
L += ['- %s: %s%s' % (r, metas[r]['license'], ' (CITATION.cff)' if metas[r]['citation'] else '') for r in pub]
llms = '\n'.join(L) + '\n'
with open(os.path.join(out, 'llms.txt'), 'w', encoding='utf-8', newline='\n') as fh:
fh.write(llms)
if agentdocs.approx_tokens(llms) > 15000:
print('WARNING: llms.txt is about %d tokens (budget 15000)' % agentdocs.approx_tokens(llms), file=sys.stderr)
dup = sum(c - 1 for c in site.titles.values() if c > 1)
print('%s lines, %d files, %d sections, %d repositories, %d words; left out: %s'
% (format(total, ','), len(files), len(sections), len(by_repo), len(words), lefts))
print('Licences: %s' % ', '.join('%s %d' % (k, v) for k, v in lic_count.most_common()))
print('Context: %d files with README context, %d with human essays; %d duplicate page titles'
% (sum(1 for f in files if f['context']), sum(1 for f in files if f['essay_status'] == 'human'), dup))
print(reach_line)
print('Edges: %d (%s); via: %s' % (len(edges), ', '.join('%s %d' % kv for kv in edge_count.most_common()),
', '.join('%s %d' % kv for kv in collections.Counter(e[3] or 'path' for e in edges).most_common())))
return {'edges': dict(edge_count),'files': len(files), 'sections': len(sections), 'readme_context': sum(1 for f in files if f['context']),
'licences': {r: metas[r]['license'] for r in pub}, 'entry': n_entry, 'reachable': n_reach,
'duplicate_titles': dup, 'llms_chars': len(llms), 'shards': [n for g, l, ps in shards for n, z in ps],
'largest_shard': max((z for g, l, ps in shards for n, z in ps), default=0), 'full': full_name,
'domain_stage': dict(collections.Counter(f['dstage'] for f in files)),
'commercial_user': dict(collections.Counter(u for f in files for u in f['users'])),
'canonical_status': dict(canon_n)}
def word_page_of(n):
c = n[:1].lower()
if not c.isalpha():
return 'symbols'
c2 = n[1:2].lower()
return c + (c2 if c2.isalpha() else '0')
def write_parquet(out, files, sections, section_meta, words, code_rows, stamp, topic_title):
import duckdb
import pyarrow as pa
os.makedirs(os.path.join(out, 'data'), exist_ok=True)
con = duckdb.connect()
def put(name, table, order):
con.register('t_' + name, table)
con.execute("COPY (SELECT * FROM t_%s ORDER BY %s) TO '%s' (FORMAT PARQUET, COMPRESSION ZSTD, ROW_GROUP_SIZE 100000)"
% (name, order, os.path.join(out, 'data', name + '.parquet').replace("'", "''")))
cols = list(zip(*code_rows))
put('code', pa.table({'repo': cols[0], 'path': cols[1], 'line': cols[2], 'text': cols[3], 'section': cols[4],
'block': cols[5]}), 'section, block, line')
fr = [(m['section'], bi, files[fi]['repo'], files[fi]['commit'], files[fi]['path'], files[fi]['blob'], a, b,
files[fi]['topic'], files[fi]['cap']) for m in section_meta for bi, (fi, a, b) in enumerate(m['parts'], 1)]
c = list(zip(*fr))
put('files', pa.table({'section': c[0], 'block': c[1], 'repo': c[2], 'commit_sha': c[3], 'path': c[4], 'blob_sha': c[5],
'line_from': c[6], 'line_to': c[7], 'topic': c[8], 'capability': c[9]}), 'section, block')
put('sections', pa.table({'section': [m['section'] for m in section_meta], 'topic': [m['topic'] for m in section_meta],
'lines': [m['lines'] for m in section_meta], 'repos': [m['repos'] for m in section_meta],
'summary': [m['summary'] for m in section_meta], 'cut': [stamp] * len(section_meta)}), 'section')
w = list(zip(*words)) if words else [[]] * 7
put('words', pa.table({'word': w[0], 'kind': w[1], 'repo': w[2], 'path': w[3], 'line': w[4], 'section': w[5],
'block': w[6]}), 'lower(word), repo, path, line')
con.close()
def main():
ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])
ap.add_argument('--src', required=True, help='folder with one clone per public repository')
ap.add_argument('--out', required=True)
ap.add_argument('--base', default='https://code.globalgrid2050.com/explore-code/')
ap.add_argument('--min', type=int, default=350)
ap.add_argument('--max', type=int, default=700)
ap.add_argument('--kuiper-tools', default='', help='kuiper-belt/tools, for the non-public digest check')
ap.add_argument('--essays', default=os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 'essays'),
help='Tier 1 human essays folder (default: essays/ in this repository)')
ap.add_argument('--repos', default='', help='comma-separated repository names to build (small test builds); default all')
ap.add_argument('--clean-manifest', default='', help='clean-manifest-v1 JSON (clean/CONTRACT.md section 6): set-aside '
'files leave the topic and repository lists and get a reason line; a "Set aside" page is added. '
'Missing or invalid: a warning, and the build runs as without it')
ap.add_argument('--duckdb-dir', default='', help='folder holding DUCKDB_FILES to copy into %s for self-hosted search '
'(optional; otherwise ship.py or the workflow places them; search falls back to jsDelivr)' % DUCKDB_PATH)
ap.add_argument('--version', action='version', version='explore build.py ' + GENERATOR_VERSION)
a = ap.parse_args()
build(a.src, a.out, a.base.rstrip('/') + '/', a.min, a.max, a.kuiper_tools, a.essays,
repos=[r.strip() for r in a.repos.split(',') if r.strip()] or None,
clean_manifest=a.clean_manifest or None, duckdb_dir=a.duckdb_dir or None)
if __name__ == '__main__':
main()Board
A Python command-line tool in the chess folder of Cosmic that reads build graph, using Louvain and PageRank. It loads JSON (`load_json`), labels propagation (`label_propagation`) and makes labels (`make_labels`).
storagecosmic / tools/explore/chess/board.py · lines 1–331 of 331 · Entry point · pattern label_propagation (shared by 2 files)
- What it does
- It loads build graph. Defines 11 functions or classes, including load_json, edge_lists, label_propagation, lab_communities, pagerank. Uses libraries argparse, json, math, os, re. Side effects: reads or writes files; starts processes.
- Inputs & outputs
- In: JSON file build_graph.json; JSON file board.json; command-line arguments. Out: JSON file.
- Downstream impact
- Used directly by 5 files: Page (cosmic); Test Board (cosmic); Test No Tmp (cosmic); CI Chess Gate (cosmic); and 1 more. Reached from 4 other entry points, including Ship (cosmic); Test Extras (cosmic); Test Page (cosmic).
- What it achieves
- Code chess board: assigns 32 code communities to the 32 chess pieces (writes `board.json`, `CONTRACT.md` v1). It accepts `--graph`, `--lab` and `--out`.
- Why it matters
- Imported by Page and CI Chess Gate. Run by Extras. Checked by 2 tests, including Test Board.
- Application
- cosmic · tools/explore/chess · Python CLI
- Uses
- Rules (import), argparse, json, math, os, re, sys
- Used by
- imported by Page (import), imported by Test Board (import), run by Test No Tmp (script call), imported by CI Chess Gate (sys.path import), run by Extras (script call)
- Produces
- load_json, edge_lists, label_propagation, lab_communities, pagerank, words_ok, make_labels, top_repo, build_board, ordinal, main
- Defines here
- load_json, edge_lists, label_propagation, lab_communities, pagerank, words_ok, make_labels, top_repo, build_board, ordinal, 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/chess/board.py:1-331 · blob e9bb4e44ebfd6f420f04f0515705873145292d95 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: supporting_data
#!/usr/bin/env python3
"""Code chess board: assigns 32 code communities to the 32 chess pieces (writes board.json, CONTRACT.md v1).
Usage: python tools/explore/chess/board.py [--graph build_graph.json] [--lab communities.json] [--out board.json]
Evidence only: every number comes from build_graph.json (files, edges, repos[].core, canonical_status,
role, reachable, name_words) or from the lab communities overlay. Nothing is invented.
Rules (deterministic; no clocks, no randomness):
1. Graph. Resolved edges of build_graph.json, excluding kind 'comment-url' (a mention, not a load),
self-loops dropped, duplicates merged. Direction: importer -> imported file.
2. Communities. If --lab names a file that exists, is an explore-lab-overlay-v1 'communities'
overlay and has the same cut and file count as build_graph.json, its Louvain column 'c' is used.
Otherwise label propagation over the undirected graph: every file starts with its own id as
label; sweeps in file id order, each file takes the label most frequent among its distinct
neighbours (ties -> smallest label), until no label changes (at most 60 sweeps). Isolated files
get no community. Computed communities are numbered by size (largest 0), ties by smallest file id.
3. Centrality ("the importance rule"). PageRank (d = 0.85, dangling mass spread uniformly) on the
community graph: one node per community, an arc weighted by the number of file edges from files of
one community to files of another. A community is central when other communities load its files.
Scaled to 0..1 by the maximum. Files inside a community are ordered by file-level PageRank on the
file graph (same parameters), most central first (ties by id); at most 200 are listed.
4. Selection. Score = size / largest size + centrality. The 32 highest-scoring communities (ties by
smaller id) go on the board; every other community is listed in `reserve`.
5. Sides. core share = share of a community's files that are in a CORE repo (build_graph repos[].core)
or have canonical_status production_core. The 16 with the highest core share are white, the other
16 black (ties by score, then id). This is the contract default made exact so each side has 16.
6. Pieces, per side. King = most central; queen = largest of the rest; the remaining 14 ranked by
centrality: rooks (a, h), bishops (c, f), knights (b, g), then pawns on files d, e, c, f, b, g, a, h
(the more central the nearer the centre). Squares are the standard starting squares; ids come
from rules.start_piece_ids() so games.json and the page share them.
7. Labels. From name_words (path words) shared by at least 2 files of the community: score = files in
the community with the word x log(all files / files with the word); version tokens (v7), numbers,
words under 3 letters and a few path fillers (index, src, lib, ...) are skipped, and a plural is
dropped when its singular already scored higher (test/tests). The top three words, written "A, b and c"; if two communities would share a label, the later one (by id) gets
its top repo appended in brackets, then its id.
8. why: one line from rules 5 and 6 with the measured numbers.
"""
import argparse
import json
import math
import os
import re
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import rules # noqa: E402
SCHEMA = 'explore-chess-board-v1'
# No host paths: extras.py sets EXPLORE_GRAPH / EXTRA_OUT; otherwise the current folder. Without a lab overlay
# communities are computed from build_graph.json (rule 2), so --lab is optional everywhere.
DEFAULT_GRAPH = os.environ.get('EXPLORE_GRAPH') or 'build_graph.json'
DEFAULT_LAB = os.environ.get('LAB_COMMUNITIES', '')
DEFAULT_OUT = os.path.join(os.environ.get('EXTRA_OUT') or '.', 'board.json')
EXCLUDED_KINDS = {'comment-url'}
MAX_FILES = 200
LP_SWEEPS = 60
LABEL_SKIP = {'index', 'src', 'lib', 'main', 'mod', 'modules', 'file', 'files', 'the', 'and', 'for', 'www', 'html'}
PAWN_FILES = 'decfbgah'
WHITE_RULE = ('the 16 board communities with the highest core share (files in a CORE repo of build_graph '
'repos[].core or with canonical_status production_core)')
BLACK_RULE = 'the other 16 board communities (lower core share)'
def load_json(path):
with open(path, encoding='utf-8') as fh:
return json.load(fh)
def edge_lists(graph):
"""Directed deduplicated arcs (src, dst) from resolved edges, comment-url excluded."""
n = len(graph['files'])
arcs = set()
for e in graph['edges']:
s, d, kind = e[0], e[1], e[2]
if kind in EXCLUDED_KINDS or s is None or d is None or s == d:
continue
if 0 <= s < n and 0 <= d < n:
arcs.add((s, d))
return sorted(arcs)
def label_propagation(n, arcs):
nbrs = [set() for _ in range(n)]
for s, d in arcs:
nbrs[s].add(d)
nbrs[d].add(s)
nbrs = [sorted(x) for x in nbrs]
lab = list(range(n))
for _ in range(LP_SWEEPS):
changed = 0
for v in range(n):
if not nbrs[v]:
continue
cnt = {}
for u in nbrs[v]:
cnt[lab[u]] = cnt.get(lab[u], 0) + 1
best = max(cnt.values())
new = min(k for k, c in cnt.items() if c == best)
if new != lab[v]:
lab[v] = new
changed += 1
if not changed:
break
groups = {}
for v in range(n):
if nbrs[v]:
groups.setdefault(lab[v], []).append(v)
order = sorted(groups.values(), key=lambda g: (-len(g), g[0]))
out = [-1] * n
for cid, members in enumerate(order):
for v in members:
out[v] = cid
return out
def lab_communities(path, graph):
"""Column 'c' of a matching lab overlay, else None."""
if not path or not os.path.exists(path):
return None
try:
lab = load_json(path)
except (OSError, ValueError):
return None
col = (lab.get('cols') or {}).get('c')
if (lab.get('schema') != 'explore-lab-overlay-v1' or lab.get('exp') != 'communities'
or lab.get('cut') != graph.get('cut') or not isinstance(col, list) or len(col) != len(graph['files'])):
return None
return col
def pagerank(n, weighted_arcs, d=0.85, tol=1e-12, max_iter=200):
out_w = [0.0] * n
for s, t, w in weighted_arcs:
out_w[s] += w
pr = [1.0 / n] * n
for _ in range(max_iter):
dangling = sum(pr[i] for i in range(n) if out_w[i] == 0)
base = (1 - d) / n + d * dangling / n
new = [base] * n
for s, t, w in weighted_arcs:
new[t] += d * pr[s] * w / out_w[s]
err = sum(abs(a - b) for a, b in zip(new, pr))
pr = new
if err < tol:
break
return pr
def words_ok(w):
return len(w) >= 3 and not re.fullmatch(r'v?\d+[a-z]?|\d.*', w) and w not in LABEL_SKIP
def make_labels(comms, files):
n = len(files)
df = {}
for f in files:
for w in set(f.get('name_words') or []):
df[w] = df.get(w, 0) + 1
labels, seen = {}, set()
for cid in sorted(comms):
members = comms[cid]
cnt = {}
for i in members:
for w in set(files[i].get('name_words') or []):
if words_ok(w):
cnt[w] = cnt.get(w, 0) + 1
scored = sorted(((c * math.log(n / df[w]), w) for w, c in cnt.items() if c >= 2), key=lambda x: (-x[0], x[1]))
top, stems = [], set()
for _, w in scored:
stem = w[:-1] if w.endswith('s') and len(w) > 3 else w
if stem not in stems:
stems.add(stem)
top.append(w)
if len(top) == 3:
break
if not top:
label = 'Unnamed group of %d files' % len(members)
elif len(top) == 1:
label = top[0].capitalize()
else:
label = top[0].capitalize() + (', ' + ', '.join(top[1:-1]) if len(top) > 2 else '') + ' and ' + top[-1]
if label in seen:
label = '%s (%s)' % (label, top_repo(members, files))
if label in seen:
label = '%s #%d' % (label, cid)
seen.add(label)
labels[cid] = label
return labels
def top_repo(members, files):
cnt = {}
for i in members:
cnt[files[i]['repo']] = cnt.get(files[i]['repo'], 0) + 1
return sorted(cnt.items(), key=lambda x: (-x[1], x[0]))[0][0]
def build_board(graph, lab_path=DEFAULT_LAB):
files = graph['files']
n = len(files)
arcs = edge_lists(graph)
col = lab_communities(lab_path, graph)
source = 'lab' if col is not None else 'computed'
if col is None:
col = label_propagation(n, arcs)
comms = {}
for i, c in enumerate(col):
if c is not None and c >= 0:
comms.setdefault(c, []).append(i)
file_pr = pagerank(n, [(s, d, 1.0) for s, d in arcs])
cids = sorted(comms)
index = {c: k for k, c in enumerate(cids)}
qw = {}
for s, d in arcs:
cs, cd = col[s], col[d]
if cs is None or cd is None or cs < 0 or cd < 0 or cs == cd:
continue
qw[(index[cs], index[cd])] = qw.get((index[cs], index[cd]), 0) + 1
qpr = pagerank(len(cids), [(a, b, float(w)) for (a, b), w in sorted(qw.items())])
qmax = max(qpr)
central = {c: qpr[index[c]] / qmax for c in cids}
core_repos = {r['repo'] for r in graph.get('repos', []) if r.get('core')}
max_size = max(len(m) for m in comms.values())
stats = {}
for c in cids:
m = comms[c]
role_cnt, repo_cnt = {}, {}
for i in m:
role_cnt[files[i].get('role') or 'other'] = role_cnt.get(files[i].get('role') or 'other', 0) + 1
repo_cnt[files[i]['repo']] = repo_cnt.get(files[i]['repo'], 0) + 1
stats[c] = {
'size': len(m),
'lines': sum(files[i].get('lines') or 0 for i in m),
'repos': [r for r, _ in sorted(repo_cnt.items(), key=lambda x: (-x[1], x[0]))],
'role': sorted(role_cnt.items(), key=lambda x: (-x[1], x[0]))[0][0],
'centrality': central[c],
'reach': sum(1 for i in m if files[i].get('reachable')) / len(m),
'unique': sum(1 for i in m if files[i].get('canonical_status') != 'duplicate_candidate') / len(m),
'core': sum(1 for i in m if files[i]['repo'] in core_repos
or files[i].get('canonical_status') == 'production_core') / len(m),
'score': len(m) / max_size + central[c],
'files': sorted(m, key=lambda i: (-file_pr[i], i))[:MAX_FILES],
}
ranked = sorted(cids, key=lambda c: (-stats[c]['score'], c))
board_c, reserve = ranked[:32], ranked[32:]
if len(board_c) < 32:
raise ValueError('only %d communities; the board needs 32' % len(board_c))
by_core = sorted(board_c, key=lambda c: (-stats[c]['core'], -stats[c]['score'], c))
sides = {'white': by_core[:16], 'black': by_core[16:]}
labels = make_labels(comms, files)
ids = rules.start_piece_ids()
cut_core = stats[by_core[15]]['core']
pieces = []
for side in ('white', 'black'):
members = sides[side]
back, front = ('1', '2') if side == 'white' else ('8', '7')
by_c = sorted(members, key=lambda c: (-stats[c]['centrality'], c))
king = by_c[0]
queen = sorted([c for c in members if c != king], key=lambda c: (-stats[c]['size'], c))[0]
rest = [c for c in by_c if c not in (king, queen)]
slots = [('king', 'e' + back, king, 'most central of the 16 %s communities' % side),
('queen', 'd' + back, queen, 'largest %s community after the king' % side)]
named = [('rook', 'a'), ('rook', 'h'), ('bishop', 'c'), ('bishop', 'f'), ('knight', 'b'), ('knight', 'g')]
for k, (typ, f) in enumerate(named):
slots.append((typ, f + back, rest[k], '%s most central %s community after king and queen'
% (ordinal(k + 1), side)))
for k, f in enumerate(PAWN_FILES):
slots.append(('pawn', f + front, rest[6 + k], '%s most central %s community after king and queen'
% (ordinal(k + 7), side)))
for typ, square, c, rank_why in slots:
s = stats[c]
pct = round(100 * s['core'])
if side == 'white':
side_why = 'white: %d%% of its files are core or production_core, in the top 16 core shares' % pct
else:
side_why = ('black: %d%% of its files are core or production_core, below the 16 white communities '
'(lowest white share %d%%)' % (pct, round(100 * cut_core)))
pieces.append({
'id': ids[square], 'side': side, 'type': typ, 'square': square, 'community': c,
'label': labels[c], 'size': s['size'], 'lines': s['lines'], 'repos': s['repos'], 'role': s['role'],
'centrality': round(s['centrality'], 4), 'reach': round(s['reach'], 4),
'unique': round(s['unique'], 4), 'files': s['files'],
'why': '%s: %s (centrality %.2f, %d files); %s.' % (typ.capitalize(), rank_why, s['centrality'],
s['size'], side_why),
})
return {
'schema': SCHEMA,
'cut': graph.get('cut'),
'rules_version': rules.RULES_VERSION,
'sides': {'white': WHITE_RULE, 'black': BLACK_RULE},
'communities_source': source,
'pieces': pieces,
'reserve': [{'community': c, 'label': labels[c], 'size': stats[c]['size'],
'centrality': round(stats[c]['centrality'], 4)} for c in reserve],
}
def ordinal(k):
return '%d%s' % (k, 'th' if 10 <= k % 100 <= 20 else {1: 'st', 2: 'nd', 3: 'rd'}.get(k % 10, 'th'))
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])
ap.add_argument('--graph', default=DEFAULT_GRAPH)
ap.add_argument('--lab', default=DEFAULT_LAB, help="lab communities overlay; '' to compute communities")
ap.add_argument('--out', default=DEFAULT_OUT)
a = ap.parse_args(argv)
if not os.path.isfile(a.graph):
sys.exit('board.py: build_graph.json not found at %r; pass --graph or set EXPLORE_GRAPH' % a.graph)
try:
graph = load_json(a.graph)
except ValueError as e:
sys.exit('board.py: %s is not valid JSON (%s)' % (a.graph, e))
if not isinstance(graph, dict) or not isinstance(graph.get('files'), list):
sys.exit('board.py: %s has no files list; is it a build_graph.json?' % a.graph)
board = build_board(graph, a.lab)
os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True)
with open(a.out, 'w', encoding='utf-8') as fh:
json.dump(board, fh, indent=1, ensure_ascii=False)
fh.write('\n')
print('wrote %s (%d pieces, %d reserve, communities %s)' % (a.out, len(board['pieces']), len(board['reserve']),
board['communities_source']))
if __name__ == '__main__':
main()