In this section
- Agentdocs render · cosmic / tools/explore/agentdocs.py lines 1–700
Agentdocs
A Python module in the explore folder of Cosmic that maps composer, jsconfig, 33kV and substations, using EPSG:27700 and EPSG:4326.
rendercosmic / tools/explore/agentdocs.py · lines 1–700 of 924 · Entry point · pattern _compact (shared by 2 files)
- What it does
- It maps composer, jsconfig, 33kV and substations. Defines 41 functions or classes, including words_of, _stage_from_words, voltages_in, crs_in, _add. Uses libraries collections, hashlib, html, posixpath, re. Side effects: changes the web page (DOM); reads or writes files; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain terms in the code: 33kV, substations, 400kV, 275kV, 132kV, 11kV.
- Inputs & outputs
- In: browser storage (getItem); browser IndexedDB; DuckDB queries; user-supplied file (file picker); form fields (user input); command-line arguments. Out: CSV file x.csv; downloaded file x.csv; interactive map; SVG drawing. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326, Web Mercator / EPSG:3857, ETRS89 / EPSG:4258, UTM. Voltage levels named: 400kV, 275kV, 132kV, 33kV, 11kV, 11kV/400V, 6.6kV, 1500V.
- Downstream impact
- Used directly by 3 files: Build (cosmic); Test Agentdocs (cosmic); Test Build (cosmic). Reached from 3 other entry points, including Cadastre 27 (cosmic); Ship (cosmic); Test Ship (cosmic).
- What it achieves
- It splits parts (`split_parts`), sizes label (`size_label`) and finds step (`find_step`). Defines `words_of`, `voltages_in`, `crs_in` and 28 more. Its code works with 33 kV, 132 kV and 11 kV.
- Why it matters
- Imported by Build. Checked by 2 tests, including Test Agentdocs.
- Application
- cosmic · tools/explore · Python module
- Uses
- collections, hashlib, html, posixpath, re
- Used by
- imported by Build (import), imported by Test Agentdocs (import), imported by Test Build (import)
- Produces
- words_of, voltages_in, crs_in, data_contracts_of, contracts_words, domain_stage_of, commercial_users_of, canonical_statuses, entry_reach, signatures_of, what_it_does, why_it_exists
- Defines here
- words_of, _stage_from_words, voltages_in, crs_in, _add, data_contracts_of, contracts_words, domain_stage_of, commercial_users_of, _norm_hash, canonical_statuses, nlines, rank, entry_reach, _params_at, _clean_params, signatures_of, _join, what_it_does, why_it_exists, compact_four_part, downstream_impact, name, four_part_html, shard_block, split_parts, approx_tokens, token_cost, size_label, _cap
- 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/agentdocs.py:1-700 · blob 80e530ff52856be49421e4a62fd011773fbd3196 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, storage · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
r"""tools/explore/agentdocs.py - agent ingestion layer for Explore Code (owner brief 2026-12-05, requirements 1-4).
Called by build.py. Deterministic and evidence-only: every label below comes from a fixed rule over evidence the
build already holds (path and repository name words, role, topic, edges, data sources, data file names, code
text, README sentences, VEDIC matches). Where the evidence is absent the value is `unknown`, an empty list, or the
part is omitted. Nothing here calls a language model. Mission wording is restricted to Ventus Ltd's stated purpose
in the owner's brief, and attributed as such. RULES_VERSION changes whenever a rule below changes.
domain_stage (one of DOMAIN_STAGES; first rule that yields a stage wins):
1 path words (folder and file names inside the repository, timestamps dropped) against STAGE_WORDS, the stages
tried in precedence order experimental, agent_infra, hv_procurement, field_execution, site_feasibility,
sub33kv_design, upstream_foresight (the first stage with any matching word wins);
2 repository name words, same table and order;
3 voltage levels found in the code (see data_contracts): all >= 132kV -> upstream_foresight; all <= 33kV ->
sub33kv_design; mixed or none -> next rule;
4 topic: agents-ai -> agent_infra; grid-network, markets-data -> upstream_foresight; solar-storage, cables ->
sub33kv_design; maps-gis -> site_feasibility;
5 unknown.
`domain_stage_evidence` records which rule and word decided it.
commercial_user (list, canonical order IPP_developer, EPC_contractor, ICP_grid_engineer, landowner_planner,
procurement_buyer, ai_agent; may be empty):
the users of the domain_stage in STAGE_USERS (none for experimental and unknown), plus every user whose
USER_WORDS appear among the repository and path words.
data_contracts ({"in": [...], "out": [...], "crs": [...], "voltages": [...]}), from the code text only:
in data sources named by URL (build.py HOSTS) when the file reads or fetches; data files named in the code
(GeoJSON, CSV, Parquet, ...; not on a write line); browser storage reads (localStorage.getItem,
sessionStorage.getItem, indexedDB); DuckDB / SQLite; form fields (<input>, <select>, <textarea>); a file
picker (type="file", FileReader); command-line arguments (argparse, sys.argv, process.argv).
out data files named on a write line (open(..,'w'), writeFileSync, to_csv, to_parquet, json.dump, ...); named
downloads (a.download = 'x.csv'); browser storage writes (setItem); a web page (kind page); an interactive
map (MapLibre / Leaflet / OpenLayers / Mapbox); a canvas or WebGL drawing; an SVG drawing; a figure
(savefig); a GitHub Pages deployment and commits pushed back (workflows).
crs coordinate systems named in the code: OSGB36 / EPSG:27700 (British National Grid) from epsg:27700, osgb36,
osgb, "british national grid", bng, or easting together with northing; WGS84 / EPSG:4326 from epsg:4326,
wgs84, "wgs 84"; Web Mercator / EPSG:3857 from epsg:3857, epsg:900913, "web mercator"; ETRS89 from etrs89,
epsg:4258; UTM from "utm zone" or epsg:326NN. Latitude/longitude alone is not evidence of a datum.
voltages voltage levels written in the code or path (132kV, 33kV, 11kV/400V, 6.6kV, 400V, 1500V ...), highest
first. Each list is capped (8) and deduplicated.
canonical_status (first match wins):
production_core reachable, in CORE_REPOS, and an entry point or has dependents;
duplicate_candidate a near-identical copy of a kept file: same text once whitespace and blank lines are
ignored (>= 5 non-blank lines), or the same pattern key with the same set of >= 2 defined
names and a line count within 25% of the kept file. The kept member of each group is the
first by: production_core, reachable, entry point, most dependents, newest path timestamp,
most lines, lowest id; `duplicate_of` names it. A production_core file is never a candidate;
unreached_review not reachable from any entry point;
supporting_data reachable, and in a repository whose name has the word "data", or role energy-data or storage;
unknown everything else.
Neither duplicate_candidate nor unreached_review is a reason to delete: both mean "review by a person first".
Four-part block (every file; each part omitted when it has no evidence, never padded):
What it does verb and elements from the synopsis evidence, definitions (count and first names),
external libraries, side effects in words.
Why it exists in the grid workflow the domain_stage meaning (from the brief) when the stage is not unknown, the
domain terms found in the code (substations, cables, voltages, ...), and a README sentence that
names the file.
Inputs & outputs data_contracts in words.
Downstream impact direct dependents (titles, published URLs) and the entry points from which the file is
reached (published pages and workflows first); for an entry point, where it is published.
User journey slices (JOURNEYS, the four journeys named in the brief): each step label is found by, in order,
1 repository name: the label's words (stop words &, and, or, the dropped) equal the repository name's words, or
their letters run together are equal ("PipelineNews" = pipelinenews);
2 a launch link on the GlobalGrid2050 homepage (globalgrid2050 index.html) whose text, after a leading Open /
Read / Enter / the, equals the label; its address is resolved to an estate file like any estate URL;
3 when no repository name matched: repositories whose name words include every label word ("Neural Link" ->
neural-link-between-agents); then, outside those, folders whose name words, with the repository's, include
every label word and share at least one with the folder name, at the shallowest depth found.
The homepage is read from the globalgrid2050 clone at HEAD even when its page is left out of the sections
(very long lines); only its link texts and addresses are used.
A homepage link whose address maps to a folder holding estate files counts as a location even when the page
itself is not a code file; one whose address no code file serves becomes a note (naming any non-code file, e.g.
a Markdown page, that holds it). Entry points of a step: homepage link targets first, then published entry points,
then others, each by the number of files they reach.
A step with no location is shown as "not found in the public estate". Links between steps are the build's own
resolved edges between the files of the two steps' locations, either direction; none found is said plainly.
"""
import collections
import hashlib
import html
import posixpath
import re
RULES_VERSION = 'explore-agent-rules-v1'
E = html.escape
DOMAIN_STAGES = [
('upstream_foresight', 'Upstream foresight',
'upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the '
'REPD pipeline, data centres), which Ventus Ltd states it models for foresight'),
('site_feasibility', 'Site feasibility',
'substation-to-site feasibility (terrain, LiDAR and connection evidence before design), a journey named in '
'Ventus Ltd\'s brief'),
('sub33kv_design', 'Sub-33kV design',
'inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial '
'execution boundary'),
('hv_procurement', 'HV procurement',
'HV materials procurement, which Ventus Ltd states is within its commercial execution boundary'),
('field_execution', 'Field execution',
'on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, '
'electrical hazards), as Ventus Ltd describes its SatNav work'),
('agent_infra', 'Agent infrastructure',
'AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd\'s brief)'),
('experimental', 'Experimental',
'work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it '
'is not part of a production workflow'),
('unknown', 'Unknown', ''),
]
STAGE_IDS = [k for k, t, d in DOMAIN_STAGES]
STAGE_TITLE = {k: t for k, t, d in DOMAIN_STAGES}
STAGE_MEANING = {k: d for k, t, d in DOMAIN_STAGES}
STAGE_ORDER = ['experimental', 'agent_infra', 'hv_procurement', 'field_execution', 'site_feasibility',
'sub33kv_design', 'upstream_foresight']
STAGE_WORDS = {
'experimental': set('experiment experiments experimental sandbox sandboxes prototype prototypes poc scratch '
'playground archive archived legacy old deprecated wip draft drafts trial trials spike buggy '
'testcode'.split()),
'agent_infra': set('agent agents vedic cvaa neural spider spiders gemini claude chatgpt codex llm llms mcp prompt '
'prompts teleprinter tokens kuiper brain handoff'.split()),
'hv_procurement': set('price prices pricing procurement boq bom quote quotes tender supplier suppliers metal metals '
'copper aluminium aluminum lme cost costs estimator estimate estimates purchase'.split()),
'field_execution': set('satnav compass route routes routing navigation navigate nav field gate gates offroad farm '
'walk gps waypoint waypoints'.split()),
'site_feasibility': set('lidar terrain feasibility elevation dem dtm dsm flood constraint constraints planning '
'landowner parcel parcels'.split()),
'sub33kv_design': set('solar pv bess battery inverter inverters string strings layout design sld cable cables '
'derating trench drill soil earthing 33kv 11kv lv dc ac panel panels array arrays topology '
'conductor conductors switchgear repower repowering floating irradiance yield ampacity'.split()),
'upstream_foresight': set('gridatlas atlas tso dno dnos 132kv 275kv 400kv interconnector interconnectors '
'transmission repd renewables pipelinenews datacentre datacentres neso elexon bmrs market '
'markets generation ukpn ssen substation substations'.split()),
}
TOPIC_STAGE = {'agents-ai': 'agent_infra', 'grid-network': 'upstream_foresight', 'markets-data': 'upstream_foresight',
'solar-storage': 'sub33kv_design', 'cables': 'sub33kv_design', 'maps-gis': 'site_feasibility'}
USERS = ['IPP_developer', 'EPC_contractor', 'ICP_grid_engineer', 'landowner_planner', 'procurement_buyer', 'ai_agent']
STAGE_USERS = {'upstream_foresight': ['IPP_developer', 'ICP_grid_engineer'],
'site_feasibility': ['IPP_developer', 'landowner_planner'],
'sub33kv_design': ['EPC_contractor', 'ICP_grid_engineer'],
'hv_procurement': ['procurement_buyer', 'EPC_contractor'],
'field_execution': ['EPC_contractor', 'landowner_planner'],
'agent_infra': ['ai_agent']}
USER_WORDS = {
'IPP_developer': set('repd ipp developer developers renewables'.split()),
'EPC_contractor': set('epc construction install installation trench drill'.split()),
'ICP_grid_engineer': set('icp adoption contestable dno ukpn ssen substation substations'.split()),
'landowner_planner': set('landowner landowners planning planner planners farm parcel parcels gate gates'.split()),
'procurement_buyer': set('price prices procurement boq bom supplier suppliers tender cost costs estimator'.split()),
'ai_agent': set('agent agents llm llms mcp prompt prompts vedic'.split()),
}
CANONICAL = ['production_core', 'supporting_data', 'duplicate_candidate', 'unreached_review', 'unknown']
CONFIDENCE = ['human', 'comment', 'code', 'readme', 'name']
STAMP = re.compile(r'(?<!\d)(20\d{6}(?:T?\d{4,6}Z?)?)(?!\d)')
def words_of(s):
s = STAMP.sub(' ', s)
s = re.sub(r'([a-z0-9])([A-Z])', r'\1 \2', s)
return [w for w in re.split(r'[^a-z0-9]+', s.lower()) if w]
def _stage_from_words(words):
ws = set(words)
for st in STAGE_ORDER:
hit = sorted(ws & STAGE_WORDS[st])
if hit:
return st, hit[0]
return None, None
# ---------------------------------------------------------------- data contracts
CRS_RULES = [
('OSGB36 / EPSG:27700 (British National Grid)',
re.compile(r'epsg[:\s]*27700|\bosgb(?:36)?\b|british\s+national\s+grid|\bbng\b')),
('WGS84 / EPSG:4326', re.compile(r'epsg[:\s]*4326|\bwgs\s?-?84\b')),
('Web Mercator / EPSG:3857', re.compile(r'epsg[:\s]*(?:3857|900913)|web\s?mercator')),
('ETRS89 / EPSG:4258', re.compile(r'\betrs\s?89\b|epsg[:\s]*4258')),
('UTM', re.compile(r'\butm\s+zone\b|epsg[:\s]*326\d\d\b')),
]
KV_RX = re.compile(r'(?<![\w.])(\d{1,3}(?:\.\d{1,2})?)\s?kv(?:\s?/\s?(\d{3})\s?v)?(?![a-z0-9])')
V_RX = re.compile(r'(?<![\w.])(230|400|415|690|1000|1500)\s?v(?:ac|dc)?(?![a-z0-9])')
FILE_TYPES = {'geojson': 'GeoJSON', 'topojson': 'TopoJSON', 'json': 'JSON', 'csv': 'CSV', 'parquet': 'Parquet',
'pmtiles': 'PMTiles', 'xlsx': 'Excel', 'xls': 'Excel', 'gpkg': 'GeoPackage', 'kml': 'KML', 'gpx': 'GPX',
'tif': 'GeoTIFF', 'tiff': 'GeoTIFF', 'las': 'LiDAR point cloud', 'laz': 'LiDAR point cloud',
'shp': 'Shapefile', 'xml': 'XML', 'pdf': 'PDF', 'png': 'PNG image', 'svg': 'SVG'}
DATA_NAME = re.compile(r'''[`'"/]([\w.\-]+\.(geojson|topojson|json|csv|parquet|pmtiles|xlsx|xls|gpkg|kml|gpx|tiff?|las|laz|shp))'''
r'''(?:\?[^`'"]*)?[`'"]''', re.I)
NOT_DATA_NAME = {'package.json', 'package-lock.json', 'tsconfig.json', 'manifest.json', 'composer.json', 'jsconfig.json'}
WRITE_LINE = re.compile(r'''(?<![\w.])open\([^)\n]*['"][wax]b?\+?['"]|writeFileSync|\bwriteFile\(|json\.dump\(|\.to_csv\(|'''
r'''\.to_parquet\(|\.to_file\(|\.write_text\(|\.write_bytes\(|\bCOPY\b.*\bTO\b|np\.save\(|savefig\(|'''
r'''>\s*[\w./-]+\.\w+\s*$|\.download\s*=|download=''')
DOWNLOAD = re.compile(r'''\.download\s*=\s*[`'"]([^`'"$]{3,60})[`'"]|\bdownload=["']([^"'$]{3,60})["']''')
GENERIC_WRITES = [(re.compile(r'\.to_parquet\(|\bCOPY\b[^\n]*\bTO\b[^\n]*parquet', re.I), 'Parquet file'),
(re.compile(r'\.to_csv\('), 'CSV file'), (re.compile(r'json\.dump\(|JSON\.stringify\([^\n]*writeFile'), 'JSON file'),
(re.compile(r'savefig\('), 'figure image'), (re.compile(r'\.to_file\('), 'geodata file')]
MAP_RX = re.compile(r'maplibregl\.|\bL\.map\(|new\s+ol\.Map|mapboxgl\.', re.I)
def voltages_in(low, extra=''):
"""Voltage levels written in the (lower-case) text and path words, highest first, as 132kV, 11kV/400V, 400V."""
hay = (extra + '\n' + low) if extra else low
found = {}
if 'kv' in hay:
for m in KV_RX.finditer(hay):
v = float(m.group(1))
if v <= 0 or v > 800:
continue
label = ('%g' % v) + 'kV' + ('/' + m.group(2) + 'V' if m.group(2) else '')
found.setdefault(label, v * 1000)
for m in V_RX.finditer(hay):
found.setdefault(m.group(1) + 'V', float(m.group(1)))
return [k for k, v in sorted(found.items(), key=lambda kv: (-kv[1], kv[0]))][:8]
def crs_in(low):
out = [label for label, rx in CRS_RULES if rx.search(low)]
if out[:1] != [CRS_RULES[0][0]] and re.search(r'\beastings?\b', low) and re.search(r'\bnorthings?\b', low):
out.insert(0, CRS_RULES[0][0])
return out
def _add(xs, x, cap=8):
if x and x not in xs and len(xs) < cap:
xs.append(x)
def data_contracts_of(f, sources=()):
"""{"in", "out", "crs", "voltages"} from the code text of build.py file dict f (see module docstring)."""
text = f.get('text') or '\n'.join(f.get('lines') or [])
low = f.get('low') or text.lower()
eff = set(f.get('effects') or [])
reads = bool(f.get('reads')) or bool(eff & {'network', 'storage', 'filesystem'})
ins, outs = [], []
if reads:
for s in sources:
_add(ins, 'data source: %s' % s)
if any(x in low for x in ('.json', '.csv', '.parquet', '.pmtiles', '.xls', '.gpkg', '.kml', '.gpx', '.tif', '.las',
'.laz', '.shp')):
for line in text.split('\n'):
if len(line) > 2000:
line = line[:2000]
for m in DATA_NAME.finditer(line):
name, e = m.group(1), m.group(2).lower()
if name.lower() in NOT_DATA_NAME or STAMP.fullmatch(name.split('.')[0] or ''):
continue
item = '%s file %s' % (FILE_TYPES.get(e, e.upper()), name)
_add(outs if WRITE_LINE.search(line) else ins, item)
for m in DOWNLOAD.finditer(text):
_add(outs, 'downloaded file %s' % (m.group(1) or m.group(2)).strip())
if f.get('writes'):
for rx, label in GENERIC_WRITES:
if rx.search(text) and not any(o.startswith(label.split()[0]) for o in outs):
_add(outs, label)
if re.search(r'(?:local|session)Storage\.getItem|(?:local|session)Storage\[', text):
_add(ins, 'browser storage (getItem)')
if re.search(r'(?:local|session)Storage\.setItem', text):
_add(outs, 'browser storage (setItem)')
if 'indexeddb' in low:
_add(ins, 'browser IndexedDB')
if re.search(r'\bduckdb\b', low):
_add(ins, 'DuckDB queries')
if re.search(r'\bsqlite3\b', low):
_add(ins, 'SQLite database')
if re.search(r'type=["\']?file\b|\bFileReader\b', text):
_add(ins, 'user-supplied file (file picker)')
if re.search(r'<(?:input|select|textarea)\b', low):
_add(ins, 'form fields (user input)')
if re.search(r'\bargparse\b|\bsys\.argv\b|\bprocess\.argv\b', text):
_add(ins, 'command-line arguments')
kind = f.get('kind') or ''
if kind == 'page':
_add(outs, 'web page')
if MAP_RX.search(text) or (re.search(r'\bleaflet\b', low) and 'dom' in eff):
_add(outs, 'interactive map')
if re.search(r"getContext\(\s*['\"](?:webgl2?|webgpu)['\"]|navigator\.gpu|new\s+THREE\.", text):
_add(outs, 'WebGL/WebGPU drawing')
elif re.search(r"getContext\(\s*['\"]2d['\"]", text):
_add(outs, 'canvas drawing')
if re.search(r'<svg\b|createElementNS\([^)]*svg', text):
_add(outs, 'SVG drawing')
if kind == 'workflow' or (f.get('path') or '').startswith('.github/workflows/'):
if re.search(r'deploy-pages|upload-pages-artifact|gh-pages', text):
_add(outs, 'GitHub Pages deployment')
if re.search(r'git\s+push', text):
_add(outs, 'commits pushed to the repository')
return {'in': ins, 'out': outs, 'crs': crs_in(low),
'voltages': voltages_in(low, ' '.join(f.get('name_words') or []))}
def contracts_words(dc):
"""Inputs & outputs in words, '' when the contract is empty."""
parts = []
if dc.get('in'):
parts.append('In: %s.' % '; '.join(dc['in']))
if dc.get('out'):
parts.append('Out: %s.' % '; '.join(dc['out']))
if dc.get('crs'):
parts.append('Coordinate systems named: %s.' % ', '.join(dc['crs']))
if dc.get('voltages'):
parts.append('Voltage levels named: %s.' % ', '.join(dc['voltages']))
return ' '.join(parts)
# ---------------------------------------------------------------- stage, users
def domain_stage_of(repo, path_words, topic, voltages):
"""(stage, evidence) by the documented rule."""
st, w = _stage_from_words(path_words)
if st:
return st, "path word '%s'" % w
st, w = _stage_from_words(words_of(repo))
if st:
return st, "repository name word '%s'" % w
kv = []
for v in voltages or []:
m = re.match(r'([\d.]+)(kV|V)', v)
if m:
kv.append(float(m.group(1)) * (1 if m.group(2) == 'kV' else 0.001))
if kv and min(kv) >= 132:
return 'upstream_foresight', 'voltage levels %s (all 132kV or above)' % ', '.join(voltages)
if kv and max(kv) <= 33:
return 'sub33kv_design', 'voltage levels %s (all 33kV or below)' % ', '.join(voltages)
if topic in TOPIC_STAGE:
return TOPIC_STAGE[topic], "topic '%s'" % topic
return 'unknown', ''
def commercial_users_of(stage, words):
ws = set(words)
got = set(STAGE_USERS.get(stage, []))
for u, kw in USER_WORDS.items():
if ws & kw:
got.add(u)
return [u for u in USERS if u in got]
# ---------------------------------------------------------------- canonical status
def _norm_hash(text):
lines = [re.sub(r'\s+', '', l) for l in text.split('\n')]
lines = [l for l in lines if l]
if len(lines) < 5:
return None
return hashlib.sha1('\n'.join(lines).encode('utf-8', 'replace')).hexdigest()
def canonical_statuses(files, dependents, core_repos):
"""[(status, duplicate_of or None)] per file, by the documented rule. files: dicts with repo, path, text or
lines, reachable, entry, pattern, defines (names) and lines; dependents: {id: [ids]}."""
n = len(files)
core = [bool(f.get('reachable')) and f['repo'] in core_repos and (bool(f.get('entry')) or bool(dependents.get(i)))
for i, f in enumerate(files)]
def nlines(f):
ls = f.get('lines')
return len(ls) if isinstance(ls, list) else int(ls or 0)
def rank(i):
f = files[i]
m = STAMP.findall(f['path'])
return (core[i], bool(f.get('reachable')), bool(f.get('entry')), len(dependents.get(i, [])),
max(m) if m else '', nlines(f), -i)
groups = collections.defaultdict(list)
for i, f in enumerate(files):
h = _norm_hash(f.get('text') if f.get('text') is not None else '\n'.join(f.get('lines') or []))
if h:
groups[('text', h)].append(i)
names = sorted(set(f.get('defines') or []))
if f.get('pattern') and len(names) >= 2:
groups[('pattern', f['pattern'], tuple(names))].append(i)
dup_of = {}
for key, ids in groups.items():
if len(ids) < 2:
continue
kept = max(ids, key=rank)
for i in ids:
if i == kept or core[i] or i in dup_of:
continue
if key[0] == 'pattern':
a, b = nlines(files[i]), nlines(files[kept])
if not b or abs(a - b) > 0.25 * b:
continue
dup_of[i] = kept
out = []
for i, f in enumerate(files):
if core[i]:
out.append(('production_core', None))
elif i in dup_of:
out.append(('duplicate_candidate', dup_of[i]))
elif not f.get('reachable'):
out.append(('unreached_review', None))
elif 'data' in words_of(f['repo']) or f.get('role') in ('energy-data', 'storage'):
out.append(('supporting_data', None))
else:
out.append(('unknown', None))
return out
# ---------------------------------------------------------------- reach from entry points
def entry_reach(links, entries):
"""{file id: [entry ids that reach it]} and {entry id: number of files it reaches}, over forward links."""
reached_by = collections.defaultdict(list)
size = {}
for e in entries:
seen = {e}
stack = [e]
while stack:
i = stack.pop()
for j in links[i]:
if j not in seen:
seen.add(j)
stack.append(j)
size[e] = len(seen) - 1
for j in seen:
if j != e:
reached_by[j].append(e)
return reached_by, size
# ---------------------------------------------------------------- signatures
SIG_RULES = {
'py': [re.compile(r'^[ \t]*(?:async[ \t]+)?def[ \t]+([A-Za-z_]\w*)[ \t]*\(', re.M),
re.compile(r'^[ \t]*class[ \t]+([A-Za-z_]\w*)[ \t]*(?=[(:])', re.M)],
'js': [re.compile(r'^[ \t]*(?:export[ \t]+)?(?:default[ \t]+)?(?:async[ \t]+)?function[ \t]*\*?[ \t]*([A-Za-z_$][\w$]*)[ \t]*\(', re.M),
re.compile(r'^[ \t]*(?:export[ \t]+)?(?:const|let|var)[ \t]+([A-Za-z_$][\w$]*)[ \t]*=[ \t]*(?:async[ \t]*)?(?:function\b[^(\n]*)?\(', re.M),
re.compile(r'^[ \t]*(?:export[ \t]+)?(?:const|let|var)[ \t]+([A-Za-z_$][\w$]*)[ \t]*=[ \t]*(?:async[ \t]+)?([A-Za-z_$][\w$]*)[ \t]*=>', re.M),
re.compile(r'^[ \t]*(?:export[ \t]+)?(?:default[ \t]+)?class[ \t]+([A-Za-z_$][\w$]*)', re.M),
re.compile(r'^[ \t]+(?:static[ \t]+)?(?:async[ \t]+)?([A-Za-z_$][\w$]*)[ \t]*\(([^()\n]*)\)[ \t]*\{', re.M)],
'sh': [re.compile(r'^[ \t]*(?:function[ \t]+)?([A-Za-z_][\w-]*)[ \t]*\(\)[ \t]*\{', re.M)],
}
SIG_LANG = {'py': 'py', 'js': 'js', 'mjs': 'js', 'cjs': 'js', 'ts': 'js', 'tsx': 'js', 'jsx': 'js', 'html': 'js',
'htm': 'js', 'vue': 'js', 'svelte': 'js', 'sh': 'sh'}
JS_EXPORTED = re.compile(r'^[ \t]*export[ \t]+(?:default[ \t]+)?(?:async[ \t]+)?(?:function[ \t]*\*?|class|const|let|var)[ \t]+'
r'([A-Za-z_$][\w$]*)', re.M)
JS_EXPORT_LIST = re.compile(r'^[ \t]*export[ \t]*\{([^}]*)\}', re.M)
NOT_METHOD = {'if', 'for', 'while', 'switch', 'catch', 'function', 'return', 'with', 'else', 'do', 'try', 'new', 'typeof'}
def _params_at(text, pos, cap=300):
"""Balanced parameter text starting just after an opening parenthesis at text[pos-1]."""
depth, i, end = 1, pos, min(len(text), pos + cap)
while i < end:
c = text[i]
if c in '([{':
depth += 1
elif c in ')]}':
depth -= 1
if depth == 0:
return text[pos:i]
i += 1
return None
def _clean_params(p):
p = re.sub(r'#[^\n]*|//[^\n]*|/\*.*?\*/', '', p, flags=re.S)
p = re.sub(r'\s+', ' ', p).strip().rstrip(',')
return p if len(p) <= 120 else p[:117] + '...'
def signatures_of(path, text, exports=(), leaks=lambda s: 0, cap=40):
"""['name(params)', 'class Name', 'export name(params)'] from the code, exported first. Evidence only.
`exports` is accepted for compatibility; JavaScript exports are read from the text itself."""
e = path.rsplit('.', 1)[-1].lower() if '.' in path.rsplit('/', 1)[-1] else ''
lang = SIG_LANG.get(e)
if not lang:
return []
exp = set()
if lang == 'js': # exported means written with `export` (Python and shell have no export statement)
exp = set(JS_EXPORTED.findall(text))
for grp in JS_EXPORT_LIST.findall(text):
exp.update(x.split(' as ')[0].strip() for x in grp.split(',') if x.strip())
found = []
seen = set()
for k, rx in enumerate(SIG_RULES[lang]):
for m in rx.finditer(text):
name = m.group(1)
if name in NOT_METHOD or leaks(name):
continue
src = m.group(0)
if lang == 'sh':
sig = name + '()'
elif lang == 'py' and k == 1 or lang == 'js' and k == 3:
sig = 'class ' + name
elif lang == 'js' and k == 2:
sig = '%s(%s)' % (name, m.group(2))
elif lang == 'js' and k == 4:
sig = '%s(%s)' % (name, _clean_params(m.group(2)))
else:
p = _params_at(text, m.end()) if src.endswith('(') else None
if p is None:
continue
sig = '%s(%s)' % (name, _clean_params(p))
if name in seen:
continue
seen.add(name)
found.append((0 if name in exp else 1, m.start(), ('export ' if name in exp else '') + sig))
found.sort()
return [s for a, b, s in found[:cap]]
# ---------------------------------------------------------------- four-part block
EFFECT_WORDS = {'dom': 'changes the web page (DOM)', 'network': 'makes network requests', 'storage': 'uses storage '
'(browser storage, DuckDB or Parquet)', 'filesystem': 'reads or writes files', 'process': 'starts processes'}
def _join(xs):
xs = list(xs)
return xs[0] if len(xs) == 1 else ', '.join(xs[:-1]) + ' and ' + xs[-1] if xs else ''
def what_it_does(verb, objects, defines, ext_imports, effects, kind=''):
s = []
if verb and objects:
s.append('It %s %s.' % (verb, _join(objects[:4])))
elif verb and verb not in ('runs',):
s.append('It %s %s.' % (verb, 'data' if verb in ('fetches', 'loads') else 'its inputs' if verb == 'calculates'
else 'its inputs' if verb == 'tests' else 'its content'))
elif verb == 'runs' and kind == 'workflow':
s.append('It runs automated jobs on GitHub Actions.')
defs = [d for d in defines if d]
if defs:
s.append('Defines %d function%s or class%s, including %s.' % (
len(defs), '' if len(defs) == 1 else 's', '' if len(defs) == 1 else 'es', ', '.join(defs[:5]))
if len(defs) > 5 else 'Defines %s.' % ', '.join(defs))
libs = [x for x in ext_imports if not re.match(r'^(?:\.|/|https?:)', x)][:5]
if libs:
s.append('Uses libraries %s.' % ', '.join(libs))
if effects:
s.append('Side effects: %s.' % '; '.join(EFFECT_WORDS[e] for e in effects if e in EFFECT_WORDS))
return ' '.join(s)
def why_it_exists(stage, stage_evidence, domain_terms, readme_sentence):
s = []
if stage and stage != 'unknown':
s.append('Domain stage %s (%s): %s.' % (stage, stage_evidence, STAGE_MEANING[stage]))
if domain_terms:
s.append('Domain terms in the code: %s.' % ', '.join(domain_terms[:6]))
if readme_sentence:
s.append('README: "%s"' % readme_sentence.strip().rstrip())
return ' '.join(s)
def compact_four_part(parts, stage):
"""four_part for build_graph.json: the stage meaning (the same text for every file of a stage, already in the
top-level domain_stages[].meaning) is replaced by a pointer to it; pages and shards keep the full sentence."""
out = dict(parts)
if out.get('why') and stage in STAGE_MEANING:
out['why'] = out['why'].replace(': %s.' % STAGE_MEANING[stage], ' (meaning: see domain_stages).', 1)
return out
def downstream_impact(fid, files, dependents, reached_by, published=''):
"""Which pages, tools and workflows rely on file fid, from edges only."""
f = files[fid]
s = []
def name(j):
g = files[j]
u = g.get('published') or ''
return '%s (%s%s)' % (g['title'], g['repo'], (', ' + u) if u else '')
deps = dependents.get(fid, [])
if deps:
s.append('Used directly by %d file%s: %s%s.' % (len(deps), '' if len(deps) == 1 else 's',
'; '.join(name(j) for j in deps[:4]),
'; and %d more' % (len(deps) - 4) if len(deps) > 4 else ''))
eps = [e for e in reached_by.get(fid, []) if e not in deps]
if eps:
eps = sorted(eps, key=lambda e: (not files[e].get('published'), files[e].get('kind') != 'workflow',
files[e]['repo'], files[e]['title']))
s.append('Reached from %d other entry point%s, including %s.' % (
len(eps), '' if len(eps) == 1 else 's', '; '.join(name(j) for j in eps[:3])))
if f.get('entry'):
u = published or f.get('published') or ''
if u:
s.append('It is itself an entry point, published at %s.' % u)
elif not deps:
s.append('It is itself an entry point (%s); no other file was found loading it.' % (f.get('kind') or 'file'))
return ' '.join(s)
FOUR_TITLES = [('does', 'What it does'), ('why', 'Why it exists in the grid workflow'), ('io', 'Inputs & outputs'),
('impact', 'Downstream impact')]
def four_part_html(parts):
rows = ''.join('<dt>%s</dt><dd>%s</dd>' % (E(t), E(parts[k])) for k, t in FOUR_TITLES if parts.get(k))
return '<dl class="v four">%s</dl>' % rows if rows else ''
# ---------------------------------------------------------------- shards
SHARD_LIMIT = 5 * 1024 * 1024
def shard_block(f, base, page_url, gh_url):
"""One file in plain Markdown for an llms-*.txt shard. f is a graph-like dict (see build.py)."""
L = ['### %s' % f['title'], '',
'- File: %s/%s (%s, %d lines) · role %s · stage %s%s' % (
f['repo'], f['path'], f['lang'], f['lines'], f['role'], f['stage'],
' · entry point' if f.get('entry') else '' if f.get('reachable') else ' · not reached (candidate for review)'),
'- Source: %s' % gh_url, '- Page: %s%s' % (base, page_url)]
if f.get('published'):
L.append('- Published at: %s' % f['published'])
if f.get('synopsis'):
L.append('- Synopsis: %s' % f['synopsis'])
if f.get('achieves'):
L.append('- What it achieves (%s): %s' % (f.get('achieves_provenance') or '', f['achieves']))
for k, t in FOUR_TITLES:
if f.get('four', {}).get(k):
L.append('- %s: %s' % (t, f['four'][k]))
if f.get('signatures'):
L.append('- Signatures: %s' % '; '.join('`%s`' % s for s in f['signatures'][:25]) +
(' (and %d more)' % (len(f['signatures']) - 25) if len(f['signatures']) > 25 else ''))
for v in f.get('vedic') or []:
L.append('- VEDIC: %s' % v)
dc = f.get('data_contracts') or {}
L.append('- domain_stage: %s · commercial_user: %s · canonical_status: %s%s · essay_status: %s' % (
f['domain_stage'], ', '.join(f.get('commercial_user') or []) or 'none', f['canonical_status'],
(' (duplicate of %s)' % f['duplicate_of_label']) if f.get('duplicate_of_label') else '', f.get('essay_status', '')))
L.append('- data_contracts: in [%s]; out [%s]; crs [%s]; voltages [%s]' % (
'; '.join(dc.get('in', [])), '; '.join(dc.get('out', [])), '; '.join(dc.get('crs', [])),
', '.join(dc.get('voltages', []))))
if f.get('edges_summary'):
L.append('- Edges: %s' % f['edges_summary'])
return '\n'.join(L) + '\n\n'
def split_parts(stem, header, blocks, limit=SHARD_LIMIT):
"""[(file name, text)]: one llms-<stem>.txt, or, when the blocks pass `limit` bytes, llms-<stem>-01.txt, -02 ...
plus llms-<stem>.txt as a short index of the parts (so the unsplit name always exists). A single block larger
than the limit gets a part of its own."""
parts, cur, size = [], [], 0
hsize = len(header.encode('utf-8')) + 200
for b in blocks:
n = len(b.encode('utf-8'))
if cur and size + n + hsize > limit:
parts.append(cur)
cur, size = [], 0
cur.append(b)
size += n
if cur or not parts:
parts.append(cur)
if len(parts) == 1:
return [('llms-%s.txt' % stem, header + '\n' + ''.join(parts[0]))]
out = []
for k, p in enumerate(parts, 1):
out.append(('llms-%s-%02d.txt' % (stem, k),
header + '\nPart %d of %d (split to stay under %d MB).\n\n' % (k, len(parts), limit // (1024 * 1024))
+ ''.join(p)))
index = header + '\nThis shard is split into %d parts (each under %d MB):\n\n%s' % (
len(parts), limit // (1024 * 1024), ''.join('- %s\n' % n for n, t in out))
return [('llms-%s.txt' % stem, index)] + out
def approx_tokens(text):
return len(text) // 4
TOKEN_WARN = 200000 # an agent cannot read a file above this in one go: say so beside the link
def token_cost(nbytes):
"""'~4k tokens' (characters / 4, like approx_tokens) for a link, with a warning above TOKEN_WARN."""
t = int(nbytes) // 4
s = '~%d tokens' % t if t < 1000 else '~%dk tokens' % round(t / 1000) if t < 10 ** 6 else '~%.1fM tokens' % (t / 1e6)
if t > TOKEN_WARN:
s += ': too big for one read (over 200k tokens); use the parts, the repository page summary or a DuckDB query'
return s
def size_label(nbytes):
"""'16 KB, ~4k tokens' for a link in llms.txt."""
z = int(nbytes)
kb = '%.0f KB' % (z / 1024) if z < 1024 * 1024 else '%.1f MB' % (z / 1024 / 1024)
return '%s, %s' % (kb, token_cost(z))
def _cap(text, n):
ws = text.split()
return text if len(ws) <= n else ' '.join(ws[:n]).rstrip(',;:') + '\u2026'
ELEVATOR_WORDS = 300
def mission_sentences():
"""MISSION split into its sentences (owner brief, unchanged): the elevator takes some, the mission section the
rest, so no sentence is printed twice."""
return re.split(r'(?<=[.!?])\s+(?=[A-Z])', MISSION)
ELEVATOR_MISSION = (0, 1, 4) # purpose, what GlobalGrid2050 bridges, who Explore Code is for
def _words(lines):
return sum(1 for x in lines for w in x.split() if not w.startswith(('http://', 'https://')))