In this section
- Extras render · cosmic / tools/explore/extras.py lines 1–700
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 1–700 of 891 · 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
- picture_svg, first_sentence, slim_kuiper, slim_identity, audit_mass, walk, folder_bytes, read_text, write_text, show, log, warn, find_generator, parse_flags, supply, expand, build_command, prune, html_files, page_title, fix_paths, write_listing, run_extra, run_post, card
- 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:1-700 · 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
"""Explore Code extras: a post-build step that adds the team's extra experiences to a built site.
python tools/explore/extras.py --site _site/explore-code --graph _site/explore-code/build_graph.json [--link-index]
It never changes build.py's output except where asked (--link-index) and never breaks the site:
1. For each extra whose generator exists (Clarity, per-repo Kuiper, Code chess, Identity genome, Lab overlays),
run its generator(s) as subprocesses into a staging folder, then move the result to explore-code/<slug>/.
A missing generator is skipped silently (listed as pending); a failing, timing-out or empty one is skipped
with a warning (and a GitHub "::warning::" line), and its partial output is discarded.
2. Write explore-code/more.html: an "Explore more" hub, one card per available experience (picture, one line
of plain English, link), mobile first, in the site palette.
3. Write explore-code/sitemap-extras.xml (more.html and every page of every integrated extra) and add it to
robots-sitemaps.txt; write explore-code/llms-extras.txt (plain-text routing list for agents);
write explore-code/extras.json (machine-readable record of what ran, what was skipped and why).
4. With --link-index only: add an "Explore more" link to index.html's <nav> and a section to llms.txt
(idempotent). The durable fix belongs in build.py / agentdocs.py; see EXTRAS.md.
Interface discovery (see EXTRAS.md for the full contract): extras.py reads each generator's source for
argparse flags and supplies the ones it recognises (--graph, --site, --out, --base, --src),
with per-step overrides where a generator's flags mean something else (chess: --out is a file).
Every generator also gets the environment variables EXPLORE_SITE, EXPLORE_GRAPH, EXPLORE_BASE, EXTRA_OUT and
runs with its staging folder as working directory. A generator that needs a required flag extras.py cannot
supply is skipped with a warning naming the flag.
Exit status is 0 unless --strict is given and an existing extra failed.
"""
import argparse
import datetime
import html
import json
import os
import re
import shutil
import subprocess
import sys
import time
from xml.sax.saxutils import escape as xml_escape
HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.dirname(os.path.dirname(HERE))
# Generators may live in tools/explore/<pkg>/ (as lab/ and chess/ do), at the repository root, or in tools/.
SEARCH_ROOTS = [HERE, REPO, os.path.join(REPO, 'tools')]
DEFAULT_TIMEOUT = int(os.environ.get('EXTRAS_TIMEOUT', '900'))
PALETTE = {'bg': '#000', 'panel': '#0b0e14', 'line': '#2f343d', 'text': '#fff', 'muted': '#a6adbb',
'link': '#66ccff', 'accent': '#00ffff'}
# ---------------------------------------------------------------------------------------------------------------
# Pictures: small inline SVGs in the site palette, one per experience (an extra may override with preview.png/svg).
SVG = {
'clarity': '<rect x="10" y="14" width="60" height="62" rx="4" fill="#0b0e14" stroke="#2f343d"/>'
'<g stroke="#a6adbb" stroke-width="3"><path d="M18 26h40M18 36h30M24 46h34M18 56h22M24 66h28"/></g>'
'<path d="M78 45h14m-6-6 6 6-6 6" stroke="#00ffff" stroke-width="3" fill="none"/>'
'<rect x="98" y="14" width="52" height="62" rx="4" fill="#0b0e14" stroke="#00ffff"/>'
'<g stroke="#fff" stroke-width="3"><path d="M106 28h36M106 40h30M106 52h36M106 64h20"/></g>',
'kuiper': '<circle cx="80" cy="45" r="9" fill="#ffff00"/>'
'<ellipse cx="80" cy="45" rx="60" ry="24" fill="none" stroke="#2f343d"/>'
'<ellipse cx="80" cy="45" rx="38" ry="15" fill="none" stroke="#2f343d"/>'
'<g fill="#00ffff"><circle cx="22" cy="42" r="2.5"/><circle cx="40" cy="62" r="2"/><circle cx="70" cy="69" r="3"/>'
'<circle cx="118" cy="61" r="2.5"/><circle cx="138" cy="44" r="2"/><circle cx="112" cy="24" r="3"/>'
'<circle cx="60" cy="22" r="2"/><circle cx="46" cy="36" r="2"/></g>'
'<g fill="#66ccff"><circle cx="100" cy="35" r="2"/><circle cx="96" cy="56" r="2.5"/><circle cx="57" cy="51" r="2"/></g>',
'chess': '<g transform="translate(44 5)">' + ''.join(
'<rect x="%d" y="%d" width="10" height="10" fill="%s"/>' % (c * 10, r * 10, '#2f343d' if (r + c) % 2 else '#0b0e14')
for r in range(8) for c in range(8)) +
'<rect width="80" height="80" fill="none" stroke="#a6adbb"/>'
'<circle cx="45" cy="75" r="3.5" fill="#fff"/><circle cx="35" cy="5" r="3.5" fill="#00ffff"/>'
'<circle cx="45" cy="45" r="3" fill="#fff"/><circle cx="35" cy="35" r="3" fill="#00ffff"/></g>',
'identity': '<g fill="none" stroke-width="3"><path d="M30 15c40 0 60 60 100 60" stroke="#00ffff"/>'
'<path d="M30 75c40 0 60-60 100-60" stroke="#66ccff"/></g>'
'<g stroke="#a6adbb" stroke-width="2"><path d="M46 21v48M62 30v30M98 30v30M114 21v48"/></g>'
'<circle cx="80" cy="45" r="4" fill="#fff"/>',
'lab': '<path d="M66 12h28M72 12v24l-24 40h64l-24-40V12" fill="#0b0e14" stroke="#a6adbb" stroke-width="2.5"/>'
'<path d="M56 64h48l6 12H50z" fill="#00ffff" opacity=".5"/>'
'<g fill="#00ff88"><circle cx="72" cy="56" r="3"/><circle cx="86" cy="50" r="2"/></g>'
'<g stroke="#2f343d"><path d="M14 80l20-20 14 8 12-14M106 50l14 10 12-18 16 8"/></g>',
'visual': '<g stroke="#2f343d" stroke-width="2"><path d="M30 45L70 22M30 45l40 26M70 22l50 10M70 71l50-14M120 32v25"/></g>'
'<circle cx="30" cy="45" r="8" fill="#66ccff"/><circle cx="70" cy="22" r="7" fill="#00ff88"/>'
'<circle cx="70" cy="71" r="7" fill="#ffae00"/><circle cx="120" cy="32" r="8" fill="#ff6666"/>'
'<circle cx="120" cy="57" r="6" fill="#00ffff"/>',
'search': '<rect x="20" y="22" width="96" height="26" rx="4" fill="#0b0e14" stroke="#2f343d"/>'
'<path d="M30 35h50" stroke="#a6adbb" stroke-width="3"/>'
'<circle cx="122" cy="52" r="14" fill="none" stroke="#00ffff" stroke-width="4"/>'
'<path d="M132 62l14 14" stroke="#00ffff" stroke-width="5"/>'
'<g stroke="#2f343d" stroke-width="3"><path d="M20 62h70M20 72h50"/></g>',
'periodic': ''.join('<rect x="%d" y="%d" width="14" height="14" rx="2" fill="%s" stroke="#2f343d"/>' % (
14 + c * 17, 10 + r * 18, ['#00ffff', '#66ccff', '#00ff88', '#ffae00', '#ffff00', '#ff6666'][(r * 3 + c) % 6]
if (r, c) not in ((0, 2), (0, 3), (0, 4), (0, 5), (0, 6)) else '#000')
for r in range(4) for c in range(8) if not (r == 0 and 1 < c < 7)) +
'<rect x="133" y="64" width="14" height="14" rx="2" fill="none" stroke="#a6adbb" stroke-dasharray="3 2"/>',
'show': '<rect x="44" y="18" width="72" height="58" rx="6" fill="#0b0e14" stroke="#2f343d" transform="rotate(-8 80 47)"/>'
'<rect x="44" y="16" width="72" height="58" rx="6" fill="#0b0e14" stroke="#2f343d" transform="rotate(5 80 45)"/>'
'<rect x="44" y="14" width="72" height="58" rx="6" fill="#0b0e14" stroke="#00ffff"/>'
'<circle cx="64" cy="34" r="8" fill="#ffff00"/><path d="M52 64l18-16 12 10 10-8 14 14z" fill="#66ccff"/>'
'<g fill="#a6adbb"><circle cx="72" cy="82" r="2"/><circle cx="80" cy="82" r="2" fill="#00ffff"/><circle cx="88" cy="82" r="2"/></g>',
'laws': '<circle cx="80" cy="45" r="10" fill="#ffae00"/>'
'<g fill="none" stroke="#2f343d"><circle cx="80" cy="45" r="24"/><circle cx="80" cy="45" r="38"/></g>'
'<circle cx="104" cy="45" r="4" fill="#00ffff"/><circle cx="53" cy="32" r="3" fill="#66ccff"/>'
'<path d="M104 45q-10-22-24-24" stroke="#00ffff" stroke-dasharray="3 3" fill="none"/>'
'<g stroke="#a6adbb" stroke-width="2"><path d="M18 20h14M25 13v14M136 70h12"/></g>',
'pilot': '<path d="M0 78l30-14 26 8 30-20 28 12 46-18v44H0z" fill="#0b0e14" stroke="#2f343d"/>'
'<g stroke="#a6adbb" stroke-width="1.5" fill="none"><path d="M34 70l6-22 6 22M37 58h6"/>'
'<path d="M104 60l6-24 6 24M107 46h6"/><path d="M40 48q35 -10 70 -12" stroke="#ffae00"/></g>'
'<rect x="128" y="56" width="12" height="9" fill="#00ff88"/>'
'<path d="M70 22l22 6-22 6 4-6z" fill="#00ffff"/><path d="M60 28h10" stroke="#00ffff"/>',}
def picture_svg(key):
return ('<svg viewBox="0 0 160 90" role="img" aria-hidden="true" focusable="false" '
'xmlns="http://www.w3.org/2000/svg">%s</svg>' % SVG.get(key, SVG['lab']))
# ---------------------------------------------------------------------------------------------------------------
# Mass (owner rule, 2026-12-05: "be like a photon without mass"). An installed extra references code and data by
# key or link (section pages carry the code); it must not copy code text or slices of build_graph.json again.
# slim_* functions trim known heavy columns in the integration layer, keeping what the page draws; audit_mass()
# flags anything that still looks like copied code (long multi-line strings) in extras.json and as a warning.
def first_sentence(t, cap=140):
t = (t or '').strip()
m = re.match(r'(.+?[.!?])(\s|$)', t)
t = m.group(1) if m else t
return t if len(t) <= cap else t[:cap - 1].rstrip() + '…'
def slim_kuiper(stage):
"""Per-repo Kuiper JSON: synopsis -> first sentence (<= 140 chars), signatures -> function names only.
repokuiper.js uses len(signatures) for moons and shows each as a heading, so names keep the page whole."""
for f in os.listdir(stage):
if not f.endswith('.json'):
continue
p = os.path.join(stage, f)
try:
d = json.loads(read_text(p))
except ValueError:
continue
if not (isinstance(d, dict) and isinstance(d.get('fields'), list) and isinstance(d.get('files'), list)):
continue
F = d['fields']
si = F.index('synopsis') if 'synopsis' in F else None
gi = F.index('signatures') if 'signatures' in F else None
for r in d['files']:
if si is not None and si < len(r) and isinstance(r[si], str):
r[si] = first_sentence(r[si])
if gi is not None and gi < len(r) and isinstance(r[gi], list):
r[gi] = [re.sub(r'^(?:export\s+|async\s+|def\s+|function\s+|class\s+)+', '',
str(x)).split('(')[0].strip()[:48] for x in r[gi]]
write_text(p, json.dumps(d, ensure_ascii=False, separators=(',', ':')))
def slim_identity(stage):
"""identity-files.json: drop per-file 'path' and keys.commit (both are inside keys.key and build_graph)."""
p = os.path.join(stage, 'identity-files.json')
if not os.path.isfile(p):
return
d = json.loads(read_text(p))
files = d.get('files')
recs = files.values() if isinstance(files, dict) else files if isinstance(files, list) else []
for r in recs:
if isinstance(r, dict) and isinstance(r.get('keys'), dict) and r['keys'].get('key'):
r.pop('path', None)
r['keys'].pop('commit', None)
write_text(p, json.dumps(d, ensure_ascii=False, separators=(',', ':')))
def audit_mass(d, max_str=2000, max_lines=8):
"""Return a short list of findings: JSON strings that look like copied code or text bodies."""
found = []
def walk(o, path, fname):
if len(found) >= 10:
return
if isinstance(o, str):
if len(o) > max_str or o.count('\n') > max_lines:
found.append('%s:%s (%d chars, %d lines)' % (fname, path or '/', len(o), o.count('\n') + 1))
elif isinstance(o, dict):
for k, v in o.items():
walk(v, path + '/' + str(k), fname)
elif isinstance(o, list):
for v in o:
walk(v, path + '/[]', fname)
for root, _, files in os.walk(d):
for f in files:
if f.endswith('.json'):
try:
walk(json.loads(read_text(os.path.join(root, f))), '', os.path.relpath(os.path.join(root, f), d))
except ValueError:
pass
return found
def folder_bytes(d):
return sum(os.path.getsize(os.path.join(r, f)) for r, _, fs in os.walk(d) for f in fs)
# ---------------------------------------------------------------------------------------------------------------
# The extras. Each step names candidate generator files (relative to a search root); the first that exists is used.
# A step marked optional may be missing without the extra being pending.
EXTRAS = [
{'slug': 'lab', 'title': 'Intelligence lab', 'owner': 'lab agent',
'desc': 'Try the experimental views: code communities, the most important files, a wafer map and predicted links.',
'steps': [{'files': ['lab/run.py'], 'entry_candidates': ['lab.html']}]},
{'slug': 'clarity', 'title': 'Clarity: pictograms of what is real', 'owner': 'PRISM-23',
'desc': 'Pictograms of what is real (unique, copies, not reached).',
'steps': [{'files': ['translator/clarity.py']}]},
{'slug': 'kuiper', 'title': 'Kuiper for each repository', 'owner': 'PERIHELION-38',
'desc': 'See each repository as its own small solar system of files, sized and coloured by what they do.',
'slim': slim_kuiper,
'steps': [{'files': ['repokuiper/build.py']}]},
{'slug': 'identity', 'title': 'Code identity genome', 'owner': 'identity agent',
'desc': 'A fingerprint of each repository: the mix of roles, stages and patterns that makes it what it is.',
# genome.py writes JSON only (no page yet): integrated as data (llms-extras.txt), no hub card until a page exists.
'data_ok': True, 'timeout': 1200,
# publish the per-file view only (11 MB); identity.json (42 MB), extract.jsonl, jobs.json and stage/ are scratch.
'keep': ['*.html', '*.css', '*.js', '*.svg', '*.png', 'identity-files.json', 'extra.json', 'README.md'],
'slim': slim_identity,
'steps': [{'files': ['identity/genome.py'], 'args': {'--fingerprints': '?{src}/vedic-/fingerprints'}}]},
{'slug': 'chess', 'title': 'Code chess', 'owner': 'GAMBIT-44, GAMBIT-05, GAMBIT-61',
'desc': 'A playful map of how code communities relate, not a judgement.',
# index.html inlines its data and data.json is the same data: board.json / games.json are not published twice.
'keep': ['*.html', '*.css', '*.js', '*.svg', '*.png', 'data.json', 'extra.json'],
# board.py and tournament.py take --out as a FILE; tournament.py's --games is a count, not a path.
'steps': [{'files': ['chess/board.py'], 'args': {'--out': '{out}/board.json', '--lab': '{lab_communities}'}},
{'files': ['chess/tournament.py'], 'args': {'--board': '{out}/board.json', '--out': '{out}/games.json',
'--games': None}},
{'files': ['chess/page.py'], 'args': {'--board': '{out}/board.json', '--games': '{out}/games.json',
'--out': '{out}'}}]},
{'slug': 'periodic', 'title': 'Periodic table of the code', 'owner': 'periodic agents (QUANTA-19 and team)',
'desc': 'The code estate as a periodic table: each element is a kind of code with its evidence and files; '
'unsettled proposals are labelled CANDIDATE.',
'timeout': 1800,
# map -> props -> furnace (single pass, --once) -> feed. Inputs that are absent are left to each tool's fallback.
'drop': ['furnace-work'],
'steps': [{'files': ['periodic/map.py'],
'args': {'--graph': '{graph}', '--out': '{out}/periodic.json',
'--identity': '?{site}/identity/identity-files.json', '--starmaker': '?{src}/star-maker',
'--elements': '?{src}/elements', '--stars': '?{src}/stars'}},
{'files': ['periodic/props.py'],
'args': {'--graph': '{graph}', '--site': None, '--periodic': '{out}/periodic.json',
'--identity': '?{site}/identity/identity-files.json', '--src': '?{src}',
'--out': '{out}/props.json', '--catalogue': None, '--blobs': None}},
{'files': ['periodic/furnace/run.py'], 'optional': True,
'args': {'--graph': '{graph}', '--out': '{out}/furnace-work', '--once': None}, 'flags': ['--once']},
{'files': ['periodic/feed.py'],
'args': {'--site': '{site}', '--graph': '{graph}', '--out': '{out}', '--base': '{base}',
'--periodic': '{out}/periodic.json', '--props': '?{out}/props.json',
'--furnace': '?{out}/furnace-work', '--write-fixture': None}}]},
{'slug': 'laws', 'title': 'Estate laws (demo)', 'owner': 'GRAVITON-64',
'desc': 'Nine physics analogies measured on the code graph, each a toggle that changes the drawing. '
'Analogies, not physics.',
# laws.py needs inputs that exist only on the team machine, so the committed demo is published as-is.
'steps': [{'files': ['laws/demo/index.html'], 'copy': ['laws/demo/index.html', 'laws/demo/data.js']}]},
{'slug': 'bigbang', 'title': 'Big Bang translation tournament', 'owner': 'rule writers (arbiter TALLY-58)',
'desc': 'Rule sets compete to explain code in plain English; a judge scores every move.',
# arena.py reads sources from a hard-coded folder; wait until it takes --src (the clones on the build machine).
'data_ok': True,
'steps': [{'files': ['bigbang/page.py', 'bigbang/arena.py'], 'require_flags': ['--src']}]},
# Stories run last (phase 'late': after the pre-hub post steps), so every other extra and pilot/ exist in --site.
{'slug': 'show', 'title': 'Stories: the best experiments, one swipe at a time', 'owner': 'presentations agent',
'desc': 'Short guided stories for newcomers: one picture and one or two plain sentences per card, each linking '
'to the real page.', 'phase': 'late',
'steps': [{'files': ['presentations/show.py'], 'args': {'--site': '{site}', '--out': '{out}', '--graph': '{graph}',
'--only': None, '--about': None}}]},
]
# Site-wide post-processors, run in place over the whole site. 'pre' runs after the extras and before Stories and
# the hub (so pilot/ exists and visualise overlays use the fresh same-cut outputs); 'post' runs after the hub (so the
# play layer also reaches more.html and Stories). They must be idempotent; a failure is a warning, never a broken
# publish.
POST = [
{'slug': 'seethrough', 'title': 'See Through substation links (theme/seethrough_index.py)', 'when': 'pre',
'files': ['theme/seethrough_index.py'], 'args': {'--site': '{site}', '--src': '?{src}', '--inject': None,
'--seethrough': None, '--base': None}},
{'slug': 'theme', 'title': 'Play layer and Pilot (theme/inject.py)', 'when': 'pre',
'files': ['theme/inject.py'], 'args': {'--site': '{site}', '--quiet': None}},
{'slug': 'visualise', 'title': 'Visualiser overlays from the extras (visualise.py)', 'when': 'pre',
'files': ['visualise.py'],
'args': {'--graph': '{graph}', '--out': '{site}/visual', '--from-parquet': None, '--dump-graph': None,
'--lab': '?{site}/lab', '--clarity': '?{site}/clarity/clarity.json',
'--periodic': '?{site}/periodic/periodic.json', '--laws': '?{site}/laws/laws.json'}},
# Kuiper intelligence modes (K3): identity, VEDIC words, element and Faraday pulse need identity/, periodic/ and
# laws/ from this same build, so they are added to kuiper/ here, after those extras ran.
{'slug': 'kuiper-overlays', 'title': 'Kuiper overlay modes from identity, periodic and laws (repokuiper/kuiper_overlays.py)',
'when': 'pre', 'files': ['repokuiper/kuiper_overlays.py'], 'args': {'--graph': '{graph}', '--site': '{site}', '--out': '{site}/kuiper', '--src': '?{src}'}},
# K5 agent API again, after the overlays above, so community, Clarity and VEDIC columns reach kuiper/api/; it also
# adds the Kuiper block to llms.txt (idempotent).
{'slug': 'kuiper-api', 'title': 'Kuiper agent API from the refreshed overlays (repokuiper/kuiper_api.py)',
'when': 'pre', 'files': ['repokuiper/kuiper_api.py'], 'args': {'--graph': '{graph}', '--site': '{site}', '--out': '{site}/kuiper', '--base': '{base}'}},
{'slug': 'theme', 'title': 'Play layer again, for the hub and Stories (theme/inject.py, idempotent)', 'when': 'post',
'files': ['theme/inject.py'], 'args': {'--site': '{site}', '--quiet': None}},
]
# Core site pages shown on the hub when present (they are not generated here). pilot/ is written by theme/inject.py.
BUILTIN = [
{'slug': 'pilot', 'title': 'Drone View: fly over the places the code names', 'href': 'pilot/index.html',
'desc': 'Fly over real coordinates written in the code, with the grid lines, pylons and substations around them, '
'and the files that name each place.'},
{'slug': 'visual', 'title': 'Visualiser', 'href': 'visual/index.html',
'desc': 'Follow the code as a picture: from data coming in, to working it out, to what you see on screen.'},
{'slug': 'search', 'title': 'Search all code', 'href': 'search.html',
'desc': 'Type a word and find every file and page that uses it, right in your browser.'},
]
FLAG_RE = re.compile(r"add_argument\(\s*((?:['\"][-\w]+['\"]\s*,\s*)*['\"][-\w]+['\"])([^)]*)\)")
GRAPH_FLAGS = {'--graph', '--build-graph', '--build_graph', '--input', '--in', '--graph-json'}
SITE_FLAGS = {'--site', '--site-dir', '--explore', '--explore-code', '--root'}
OUT_FLAGS = {'--out', '--out-dir', '--outdir', '--output', '--output-dir', '--dest', '-o'}
BASE_FLAGS = {'--base', '--base-url'}
def read_text(p):
with open(p, encoding='utf-8', errors='replace') as fh:
return fh.read()
def write_text(p, s):
with open(p, 'w', encoding='utf-8') as fh:
fh.write(s)
def show(p):
"""A path for logs: relative to the repository when inside it."""
r = os.path.relpath(p, REPO)
return p if r.startswith('..') else r
def log(msg):
print('[extras] ' + msg, flush=True)
def warn(msg):
print('[extras] WARNING: ' + msg, flush=True)
if os.environ.get('GITHUB_ACTIONS'):
print('::warning::extras: ' + msg.replace('\n', ' '), flush=True)
def find_generator(candidates, roots=None):
for rel in candidates:
for root in roots or SEARCH_ROOTS:
p = os.path.join(root, rel)
if os.path.isfile(p):
return p
return None
def parse_flags(src):
"""Return {flag: {'aliases': [...], 'required': bool}} for every argparse option in the source."""
flags = {}
for m in FLAG_RE.finditer(src):
names = re.findall(r"['\"]([-\w]+)['\"]", m.group(1))
opts = [n for n in names if n.startswith('-')]
if not opts:
continue
info = {'aliases': opts, 'required': bool(re.search(r'required\s*=\s*True', m.group(2))),
'store_true': bool(re.search(r"action\s*=\s*['\"]store_(true|false)", m.group(2)))}
for o in opts:
flags[o] = info
positional = [m for m in re.findall(r"add_argument\(\s*['\"]([a-z_]\w*)['\"]", src)]
return flags, positional
def supply(flag, ctx):
"""The value extras.py supplies for a flag, or None if it does not know one."""
f = flag.lower()
out = ctx['out']
if f in GRAPH_FLAGS:
return ctx['graph']
if f in SITE_FLAGS:
return ctx['site']
if f in OUT_FLAGS:
return out
if f in BASE_FLAGS:
return ctx['base'] + ctx['slug'] + '/'
if f in ('--communities',):
p = os.path.join(ctx.get('lab_out') or '', 'communities.json')
return p if ctx.get('lab_out') and os.path.isfile(p) else None
if f in ('--visual', '--visual-graph'):
p = os.path.join(ctx['site'], 'visual', 'graph.json')
return p if os.path.isfile(p) else None
if f in ('--src', '--clones'):
return ctx.get('src')
return None
def expand(template, ctx):
"""Fill {out}, {site}, {graph}, {base}, {src}, {lab}, {lab_communities}; None if a needed value is unknown."""
lab = ctx.get('lab_out')
comm = os.path.join(lab, 'communities.json') if lab else None
vals = {'out': ctx['out'], 'site': ctx['site'], 'slug': ctx.get('slug', ''), 'graph': ctx['graph'], 'base': ctx['base'], 'src': ctx.get('src'),
'lab': lab, 'lab_communities': comm if comm and os.path.isfile(comm) else ''}
optional = template.startswith('?')
try:
val = template[1:].format(**{k: v for k, v in vals.items() if v is not None}) if optional else \
template.format(**{k: v for k, v in vals.items() if v is not None})
except KeyError:
return None
if optional and not os.path.exists(val):
return None # '?{site}/x.json': pass the flag only when that file or folder exists
return val
def build_command(gen, ctx, overrides=None):
"""Return (argv, problem). problem is a string when a required flag cannot be supplied.
overrides: {flag: template or None}; a template wins over the generic rule, None omits the flag."""
overrides = overrides or {}
with open(gen, encoding='utf-8', errors='replace') as fh:
src = fh.read()
flags, positional = parse_flags(src)
argv = [sys.executable, gen]
seen = set()
for flag, info in flags.items():
key = id(info)
if key in seen:
continue
seen.add(key)
if info['store_true']:
continue
val = None
hit = [al for al in info['aliases'] if al in overrides]
if hit:
val = overrides[hit[0]]
val = expand(val, ctx) if val is not None else None
if val is None and info['required']:
return argv, 'needs %s, which extras.py cannot supply' % '/'.join(info['aliases'])
if val is not None:
argv += [hit[0], val]
continue
for alias in sorted(info['aliases'], key=lambda a: (not a.startswith('--'), a)):
val = supply(alias, ctx)
if val is not None:
flag = alias
break
if val is not None:
argv += [flag, val]
elif info['required']:
return argv, 'needs %s, which extras.py cannot supply' % '/'.join(info['aliases'])
known = {al for info in flags.values() for al in info['aliases']}
for flag, tmpl in overrides.items():
if flag not in known and tmpl is not None:
val = expand(tmpl, ctx)
if val is not None: # flags defined in a loop (map.py, laws.py) are invisible to the regex
argv += [flag, val]
if positional:
return argv, 'takes positional argument(s) %s; expected flags --graph/--site/--out' % ', '.join(positional)
return argv, None
def prune(d, keep):
"""Delete every file under d whose name matches none of the glob patterns in keep (then empty folders)."""
import fnmatch
for root, dirs, files in os.walk(d, topdown=False):
for f in files:
if not any(fnmatch.fnmatch(f, k) for k in keep):
os.remove(os.path.join(root, f))
for sub in dirs:
try:
os.rmdir(os.path.join(root, sub))
except OSError:
pass
def html_files(d):
out = []
for root, _, files in os.walk(d):
for f in files:
if f.endswith('.html'):
out.append(os.path.relpath(os.path.join(root, f), d).replace(os.sep, '/'))
return sorted(out)
def page_title(path):
try:
with open(path, encoding='utf-8', errors='replace') as fh:
m = re.search(r'<title>(.*?)</title>', fh.read(20000), re.S | re.I)
return html.unescape(m.group(1).strip()) if m else ''
except OSError:
return ''
def fix_paths(stage, site, final):
"""Make generated pages portable: absolute staging/site paths (and the lab's /tmp layout) become relative."""
for rel in html_files(stage):
d = rel.count('/')
up_extra, up_site = '../' * d, '../' * (d + 1)
subs = [(stage.rstrip('/') + '/', up_extra), (final.rstrip('/') + '/', up_extra), (site.rstrip('/') + '/', up_site),
('/tmp/site7/explore-code/', up_site), ('/site7/explore-code/', up_site),
('/tmp/lab-out/', up_extra), ('"/lab-out/', '"' + up_extra), ("'/lab-out/", "'" + up_extra)]
p = os.path.join(stage, rel)
with open(p, encoding='utf-8', errors='replace') as fh:
s = fh.read()
t = re.sub(r'(?:\.\./)+site7/explore-code/', up_site, s)
for a, b in subs:
t = t.replace(a, b)
if t != s:
with open(p, 'w', encoding='utf-8') as fh:
fh.write(t)
def write_listing(stage, title, pages):
items = ''.join('<li><a href="%s">%s</a></li>' % (html.escape(p), html.escape(page_title(os.path.join(stage, p)) or p))
for p in pages)
with open(os.path.join(stage, 'index.html'), 'w', encoding='utf-8') as fh:
fh.write('<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" '
'content="width=device-width,initial-scale=1"><title>%s: Explore Code</title>'
'<link rel="stylesheet" href="../explore.css"></head><body><header><p class="brand">EXPLORE CODE</p>'
'<h1>%s</h1></header><nav><a href="../index.html">Explore Code</a><a href="../more.html">Explore more</a>'
'</nav><main><ul class="links">%s</ul></main></body></html>' % (html.escape(title), html.escape(title), items))
def run_extra(ex, ctx, timeout, roots=None):
"""Run one extra. Returns a record dict with status 'ok' | 'pending' | 'failed'."""
rec = {'slug': ex['slug'], 'title': ex['title'], 'owner': ex['owner'], 'desc': ex['desc'], 'steps': []}
gens = []
for st in ex['steps']:
g = find_generator(st['files'], roots)
if not g and not st.get('optional'):
rec['status'] = 'pending'
rec['reason'] = 'generator not found: ' + ' or '.join(st['files'])
return rec
if g and st.get('require_flags'):
have, _ = parse_flags(read_text(g))
missing = [f for f in st['require_flags'] if f not in have]
if missing:
rec['status'] = 'pending'
rec['reason'] = '%s does not take %s yet' % (show(g), ', '.join(missing))
return rec
gens.append((st, g))
site = ctx['site']
stage = os.path.join(site, '.extras-staging', ex['slug'])
final = os.path.join(site, ex['slug'])
shutil.rmtree(stage, ignore_errors=True)
os.makedirs(stage)
sctx = dict(ctx, out=stage, slug=ex['slug'])
env = dict(os.environ, EXPLORE_SITE=site, EXPLORE_GRAPH=ctx['graph'], EXPLORE_BASE=ctx['base'],
EXTRA_OUT=stage, EXTRA_SLUG=ex['slug'], PYTHONDONTWRITEBYTECODE='1')
t0 = time.time()
try:
for st, g in gens:
if not g:
continue
if st.get('copy'):
for rel in st['copy']:
srcf = find_generator([rel], roots)
if not srcf:
raise RuntimeError('copy step: %s not found' % rel)
shutil.copy(srcf, os.path.join(stage, os.path.basename(rel)))
rec['steps'].append({'copy': st['copy']})
log('%s: copied %s' % (ex['slug'], ', '.join(st['copy'])))
continue
argv, problem = build_command(g, sctx, st.get('args'))
argv += st.get('flags', [])
rec['steps'].append({'generator': show(g), 'argv': [show(x) if x == g else x for x in argv[1:]]})
if problem:
raise RuntimeError('%s %s' % (show(g), problem))
log('%s: %s' % (ex['slug'], ' '.join(argv[1:])))
left = max(1, timeout - (time.time() - t0))
try:
p = subprocess.run(argv, cwd=stage, env=env, capture_output=True, text=True, timeout=left)
except subprocess.TimeoutExpired:
raise RuntimeError('%s timed out after %d s' % (show(g), timeout))
if p.returncode != 0:
tail = (p.stderr or p.stdout or '').strip().splitlines()[-6:]
raise RuntimeError('%s exited %d: %s' % (show(g), p.returncode, ' | '.join(tail)))
for rel in ex.get('drop', []):
t = os.path.join(stage, rel)
shutil.rmtree(t, ignore_errors=True) if os.path.isdir(t) else (os.path.exists(t) and os.remove(t))
if ex.get('keep'):
prune(stage, ex['keep'])
if ex.get('slim'):
before = folder_bytes(stage)
try:
ex['slim'](stage)
log('%s: slimmed %.1f MB -> %.1f MB' % (ex['slug'], before / 1e6, folder_bytes(stage) / 1e6))
except Exception as e: # noqa: BLE001 - slimming is best effort; the unslimmed output still works
warn('%s: slimming skipped (%s)' % (ex['slug'], e))
mass = audit_mass(stage)
rec['bytes'] = folder_bytes(stage)
if mass:
rec['mass_findings'] = mass
warn('%s: looks like copied code/text (photon rule): %s' % (ex['slug'], '; '.join(mass[:3])))
# Find the entry page.
pages = html_files(stage)
entry = None
if 'index.html' in pages:
entry = 'index.html'
else:
for st, _ in gens:
for c in st.get('entry_candidates', []):
if c in pages:
shutil.copy(os.path.join(stage, c), os.path.join(stage, 'index.html'))
entry = 'index.html'
break
if entry:
break
if not entry and len(pages) == 1:
entry = pages[0]
elif not entry and pages:
write_listing(stage, ex['title'], pages)
entry = 'index.html'
if not entry:
data = sorted(f for f in os.listdir(stage) if f.endswith(('.json', '.txt', '.csv', '.jsonl')))
if not (ex.get('data_ok') and data):
raise RuntimeError('produced no HTML page in %s' % stage)
shutil.rmtree(final, ignore_errors=True)
shutil.move(stage, final)
rec.update(status='data', entry=None, preview=None, pages=[], data=[ex['slug'] + '/' + f for f in data],
seconds=round(time.time() - t0, 1))
log('%s: data only (%d files, %.1f s); no hub card until it writes a page' % (ex['slug'], len(data), rec['seconds']))
return rec
fix_paths(stage, site, final)
meta_p = os.path.join(stage, 'extra.json')
if os.path.isfile(meta_p):
try:
with open(meta_p, encoding='utf-8') as fh:
meta = json.load(fh)
for k in ('title', 'desc', 'description'):
if isinstance(meta.get(k), str) and meta[k].strip():
rec['desc' if k == 'description' else k] = meta[k].strip()[:200]
if isinstance(meta.get('entry'), str) and os.path.isfile(os.path.join(stage, meta['entry'])):
entry = meta['entry']
except (ValueError, OSError) as e:
warn('%s: extra.json unreadable (%s); using defaults' % (ex['slug'], e))
preview = next((f for f in ('preview.svg', 'preview.png', 'preview.jpg', 'preview.webp', 'thumb.png')
if os.path.isfile(os.path.join(stage, f))), None)
shutil.rmtree(final, ignore_errors=True)
shutil.move(stage, final)
rec.update(status='ok', entry=ex['slug'] + '/' + entry, preview=(ex['slug'] + '/' + preview) if preview else None,
pages=[ex['slug'] + '/' + p for p in html_files(final)],
data=sorted(ex['slug'] + '/' + f for f in os.listdir(final) if f.endswith(('.json', '.txt', '.csv'))),
seconds=round(time.time() - t0, 1))
log('%s: ok (%d pages, %.1f s)' % (ex['slug'], len(rec['pages']), rec['seconds']))
except Exception as e: # noqa: BLE001 - an extra must never break the site
shutil.rmtree(stage, ignore_errors=True)
rec.update(status='failed', reason=str(e)[:600], seconds=round(time.time() - t0, 1))
warn('%s skipped: %s' % (ex['slug'], rec['reason']))
return rec
def run_post(pp, ctx, timeout, roots=None):
"""Run one site-wide post-processor in place. Returns a record with status ok | pending | failed."""
rec = {'slug': pp['slug'], 'title': pp['title']}
g = find_generator(pp['files'], roots)
if not g:
rec.update(status='pending', reason='not found: ' + ' or '.join(pp['files']))
log('%s: pending (%s)' % (pp['slug'], rec['reason']))
return rec
argv, problem = build_command(g, dict(ctx, out=ctx['site'], slug=pp['slug']), pp.get('args'))
rec['argv'] = [show(x) if x == g else x for x in argv[1:]]
t0 = time.time()
try:
if problem:
raise RuntimeError('%s %s' % (show(g), problem))
log('%s: %s' % (pp['slug'], ' '.join(rec['argv'])))
p = subprocess.run(argv, cwd=ctx['site'], capture_output=True, text=True, timeout=timeout,
env=dict(os.environ, EXPLORE_SITE=ctx['site'], EXPLORE_GRAPH=ctx['graph'],
EXPLORE_BASE=ctx['base'], PYTHONDONTWRITEBYTECODE='1'))
if p.returncode != 0:
tail = (p.stderr or p.stdout or '').strip().splitlines()[-6:]
raise RuntimeError('%s exited %d: %s' % (show(g), p.returncode, ' | '.join(tail)))
rec.update(status='ok', seconds=round(time.time() - t0, 1))
log('%s: ok (%.1f s)' % (pp['slug'], rec['seconds']))
except subprocess.TimeoutExpired:
rec.update(status='failed', reason='timed out after %d s' % timeout)
warn('%s: %s (site left as the post-processor left it; it must be idempotent)' % (pp['slug'], rec['reason']))
except Exception as e: # noqa: BLE001
rec.update(status='failed', reason=str(e)[:600], seconds=round(time.time() - t0, 1))
warn('%s failed: %s' % (pp['slug'], rec['reason']))
return rec
# ---------------------------------------------------------------------------------------------------------------
# Hub page, sitemap, llms-extras.txt
CSS = """*{box-sizing:border-box}body{background:#000;color:#fff;margin:0;font:16px/1.5 ui-monospace,Menlo,Consolas,monospace}
header,nav,main,footer{max-width:1100px;margin:0 auto;padding:0 16px}a{color:#66ccff}
.brand{color:#00ffff;margin:18px 0 2px;font-size:13px;letter-spacing:.06em}h1{font-size:22px;margin:4px 0 6px}
.lede{color:#a6adbb;margin:0 0 12px;max-width:760px}
nav{display:flex;gap:16px;flex-wrap:wrap;padding-top:10px;padding-bottom:10px;border-bottom:1px solid #2f343d}
nav a{padding:4px 0}
.cards{list-style:none;padding:0;margin:18px auto;display:grid;grid-template-columns:1fr;gap:14px}
@media(min-width:620px){.cards{grid-template-columns:repeat(2,1fr)}}@media(min-width:980px){.cards{grid-template-columns:repeat(3,1fr)}}
.card{background:#0b0e14;border:1px solid #2f343d;border-radius:8px;overflow:hidden;display:flex;flex-direction:column}
.card:hover,.card:focus-within{border-color:#00ffff}
.card a.pic{display:block;background:#000;border-bottom:1px solid #2f343d;aspect-ratio:16/9}
.card svg,.card img{display:block;width:100%;height:100%;object-fit:cover}
.card .body{padding:12px 14px 14px;display:flex;flex-direction:column;gap:6px;flex:1}
.card h2{font-size:16px;margin:0}.card h2 a{color:#fff;text-decoration:none}.card h2 a:hover{color:#00ffff}
.card p{margin:0;color:#a6adbb;font-size:14px;flex:1}
.card .go{align-self:flex-start;color:#000;background:#00ffff;border-radius:4px;padding:8px 14px;text-decoration:none;
font-weight:700;font-size:14px;min-height:44px;display:inline-flex;align-items:center}
.card .go:focus-visible,.card h2 a:focus-visible{outline:2px solid #66ccff;outline-offset:2px}
.tag{color:#a6adbb;font-size:12px}.empty{color:#a6adbb}
footer{color:#a6adbb;font-size:12px;border-top:1px solid #2f343d;padding-top:10px;padding-bottom:24px}"""
def card(key, title, desc, href, preview=None, tag=''):
pic = ('<img src="%s" alt="" loading="lazy" width="320" height="180">' % html.escape(preview)) if preview \