GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / cosmic / tools/explore

Build (part 2)

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.

700 lines of Python from cosmic, in 1 file. Topic: Kuiper, cosmos and drawing engines. Section 1081 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Build render · cosmic / tools/explore/build.py lines 701–1400

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 701–1400 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
readme_summary, license_of, load_essays, near_copy_pct, clean_key, load_clean_manifest, md_inline, link, md_html, flush, essay_html, scan, blob, definitions, clean_comment, capability_of, exports_of, load_vedic, vedic_matches, topic_of, _attrs, _python_refs, _split_top, py_path_expr, python_syspath_dirs
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:701-1400 · 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
    characters; trimmed to 400 characters. ('', None) when no paragraph qualifies. repo (the repository slug) and
    the README's first heading count as the subject; paragraphs before the second heading are the opening."""
    paras = _readme_paragraphs(text)
    title = next((h for h, _ in paras if h), '')
    names = {re.sub(r'[^a-z0-9]', '', x.lower()) for x in (repo, repo.replace('-', ' '))} | \
            {re.sub(r'[^a-z0-9]', '', title.lower())} | {w for w in re.findall(r'[a-z0-9]{4,}', title.lower())}
    names = {n for n in names if len(n) >= 4 or n == re.sub(r'[^a-z0-9]', '', repo.lower())}
    cands = []
    for k, (h, p) in enumerate(paras):
        plain = _readme_usable(p)
        if plain:
            cands.append((k, h, plain, readme_score(plain, h, names, opening=h in ('', title), lead=not cands)))
    ok = [c for c in cands if c[3] is not None]
    if not ok:
        return '', None
    good = [c for c in ok if c[3] >= README_THRESHOLD]
    best = good[0] if good else max(ok, key=lambda c: (c[3], -c[0]))
    out = best[2]
    if len(out) < 80:
        nxt = [c for c in ok if c[0] > best[0] and c[1] == best[1]]
        if nxt and nxt[0][3] >= 3:
            out = out + ' ' + nxt[0][2]
    return trim(out, 400), best[3]


def readme_summary(text, repo=''):
    """Opening summary of a README: the best-scoring descriptive paragraph (readme_pick), badges, headings, lists and
    tables skipped; '' when every paragraph is a process record, policy, log or instruction."""
    return readme_pick(text, repo)[0]


LICENCE_RULES = [
    ('AGPL-3.0', r'GNU AFFERO GENERAL PUBLIC LICENSE'),
    ('LGPL-2.1', r'GNU LESSER GENERAL PUBLIC LICENSE[\s\S]{0,200}Version 2\.1'),
    ('LGPL-3.0', r'GNU LESSER GENERAL PUBLIC LICENSE[\s\S]{0,200}Version 3'),
    ('LGPL', r'GNU LESSER GENERAL PUBLIC LICENSE'),
    ('GPL-3.0', r'GNU GENERAL PUBLIC LICENSE[\s\S]{0,200}Version 3'),
    ('GPL-2.0', r'GNU GENERAL PUBLIC LICENSE[\s\S]{0,200}Version 2'),
    ('Apache-2.0', r'Apache License[\s\S]{0,200}Version 2\.0'),
    ('MPL-2.0', r'Mozilla Public License,?\s+(Version|v\.?)\s*2\.0'),
    ('MIT', r'\bMIT License\b|Permission is hereby granted, free of charge'),
    ('BSD-3-Clause', r'Redistribution and use in source and binary forms[\s\S]*Neither the name'),
    ('BSD-2-Clause', r'Redistribution and use in source and binary forms'),
    ('CC-BY-4.0', r'Attribution 4\.0 International'),
    ('CC0-1.0', r'CC0 1\.0 Universal'),
    ('Unlicense', r'This is free and unencumbered software released into the public domain'),
]


def license_of(text):
    """SPDX id from a licence file's own text; never assumed."""
    if text is None:
        return 'none found'
    for spdx, rx in LICENCE_RULES:
        if re.search(rx, text, re.I if spdx in ('MIT', 'Unlicense') else 0):
            return spdx
    return 'other (see LICENSE)'


def load_essays(essays_dir):
    """Tier 1: {(repo, kind, path): essay}; kind is 'repo', 'folder' or 'file'. Never loaded: essays/drafts/ (AI-assisted
    drafts awaiting the owner's approval) and any file whose front matter status begins with 'draft'; only approved
    essays under essays/<repo>/ are shown as "Written by people"."""
    out = {}
    if not essays_dir or not os.path.isdir(essays_dir):
        return out
    for root, dirs, names in os.walk(essays_dir):
        if os.path.relpath(root, essays_dir) == '.':
            dirs[:] = [d for d in dirs if d.lower() != 'drafts']
        dirs.sort()
        for n in sorted(names):
            if not n.lower().endswith('.md'):
                continue
            full = os.path.join(root, n)
            rel = os.path.relpath(full, essays_dir).replace(os.sep, '/')
            if '/' not in rel:
                continue  # essays/README.md and other top-level notes describe the format
            repo, rest = rel.split('/', 1)
            if rest == 'index.md':
                key = (repo, 'repo', '')
            elif rest.endswith('.essay.md'):
                key = (repo, 'file', rest[:-len('.essay.md')])
            else:
                key = (repo, 'folder', rest[:-3])
            meta, body = front_matter(open(full, encoding='utf-8').read())
            if meta.get('status', '').lower().startswith('draft'):
                continue
            m = re.search(r'^#\s+(.+)$', body, re.M)
            title = meta.get('title') or (md_strip(m.group(1)) if m else '') or \
                (repo_title(repo) if key[1] == 'repo' else title_of(repo, key[2] if key[1] == 'file' else key[2] + '/x')
                 .replace(' X', '').strip())
            out[key] = {'key': key, 'title': title, 'body': body, 'source': 'essays/' + rel, 'id': 'essay-' + slug(rel[:-3])}
    return out


CLEAN_CATEGORY_TITLE = {  # clean/CONTRACT.md section 3, in plain English, in its category order
    'noise-generated': 'Written by a tool', 'noise-vendored': 'Third-party code copied in',
    'noise-minified': 'Minified or bundled', 'noise-data-blob': 'Data written as code',
    'near-copy-of': 'Near copy of a file that stays', 'family-older-than': 'Older version of a file that stays',
    'unit-duplicate-of': 'Made entirely of code repeated from elsewhere'}


def near_copy_pct(rec):
    """Share of lines a near copy has in common with the file that stays, from the clean manifest's evidence
    ('line-jaccard 0.93 to <key>', clean/families.py) as a whole percentage, or None."""
    if (rec or {}).get('category') != 'near-copy-of':
        return None
    for x in rec.get('evidence') or []:
        m = re.match(r'line-jaccard\s+([01](?:\.\d+)?)\b', str(x))
        if m:
            return int(float(m.group(1)) * 100)
    return None


def clean_key(key):
    """Parse a clean-contract key '<repo>@<commit> <path>:<first>-<last> <blob>' -> (repo, path, blob) or None."""
    if not isinstance(key, str) or '@' not in key:
        return None
    repo, rest = key.split('@', 1)
    if ' ' not in rest:
        return None
    rest = rest.split(' ', 1)[1]
    if ' ' not in rest:
        return None
    loc, blob = rest.rsplit(' ', 1)
    if ':' not in loc:
        return None
    return repo, loc.rsplit(':', 1)[0], blob


def load_clean_manifest(path, files, cut=None):
    """--clean-manifest (clean/CONTRACT.md section 6). Returns ({file index: set-aside record}, info) where each record
    gains 'target_fi' (the file that stays, or None). Fail-safe: a missing or unreadable manifest, or a wrong schema,
    is a WARNING and returns ({}, None) so the site builds as without the flag. Files are matched on repo + path (a
    new build always has a new cut, so graph_cut is only compared and reported); when the key carries a blob that
    differs from the file built now, the file changed since the manifest and stays in the main view."""
    warn = lambda m: print('WARNING: --clean-manifest: %s' % m, file=sys.stderr)
    if not path:
        return {}, None
    try:
        with open(path, encoding='utf-8') as fh:
            man = json.load(fh)
    except (OSError, ValueError) as e:
        warn('%s not read (%s); building without it' % (path, e))
        return {}, None
    if not isinstance(man, dict) or man.get('schema') != 'clean-manifest-v1':
        warn('%s: schema is not clean-manifest-v1; building without it' % path)
        return {}, None
    at = {(f['repo'], f['path']): i for i, f in enumerate(files)}
    out, stale, missing = {}, 0, 0
    for rec in man.get('set_aside') or []:
        k = clean_key(rec.get('key'))
        if not k or rec.get('category') not in CLEAN_CATEGORY_TITLE:
            missing += 1
            continue
        fi = at.get(k[:2])
        if fi is None:
            missing += 1
            continue
        if k[2] not in ('-', '') and files[fi].get('blob') and k[2] != files[fi]['blob']:
            stale += 1
            continue
        t = clean_key(rec.get('target')) if rec.get('target') else None
        out[fi] = dict(rec, target_fi=at.get(t[:2]) if t else None)
    info = {'path': path, 'graph_cut': man.get('graph_cut'), 'dry_run': man.get('dry_run'),
            'summary': man.get('summary', ''), 'stale': stale, 'not_in_build': missing, 'set_aside': len(out)}
    if cut and man.get('graph_cut') and man['graph_cut'] != cut:
        info['cut_note'] = 'manifest cut %s; matched on repository and path' % man['graph_cut']
    if stale:
        warn('%d set-aside records name a file whose blob changed since the manifest; those files stay in the main view' % stale)
    if missing:
        warn('%d set-aside records name files not in this build (or are malformed); ignored' % missing)
    return out, info


def md_inline(t):
    out = []
    for p in re.split(r'(`[^`\n]+`)', t):
        if len(p) > 1 and p.startswith('`') and p.endswith('`'):
            out.append('<code>%s</code>' % E(p[1:-1]))
            continue
        p = E(p, quote=False)

        def link(m):
            url = html.unescape(m.group(2))
            if re.match(r'(https?://|mailto:)', url):
                return '<a href="%s">%s</a>' % (E(url), m.group(1))
            return m.group(1)
        p = re.sub(r'\[([^\]]+)\]\(([^)\s]+)\)', link, p)
        p = re.sub(r'\*\*(.+?)\*\*', r'<strong>\1</strong>', p)
        p = re.sub(r'(?<![\w*])\*(?!\s)(.+?)(?<!\s)\*(?![\w*])', r'<em>\1</em>', p)
        out.append(p)
    return ''.join(out)


def md_html(text):
    """Minimal markdown: headings, paragraphs, lists, links, inline and fenced code."""
    out, para, items, fence, code = [], [], [], None, []
    lt = [None]

    def flush():
        if para:
            out.append('<p>%s</p>' % md_inline(' '.join(para)))
            para.clear()
        if items:
            out.append('<%s>%s</%s>' % (lt[0], ''.join('<li>%s</li>' % md_inline(i) for i in items), lt[0]))
            items.clear()
    for line in text.split('\n'):
        s = line.strip()
        if fence is not None:
            if s.startswith(fence):
                out.append('<pre><code>%s</code></pre>' % E('\n'.join(code)))
                fence, code = None, []
            else:
                code.append(line)
            continue
        if s.startswith(('```', '~~~')):
            flush()
            fence, code = s[:3], []
            continue
        h = re.match(r'^(#{1,6})\s+(.*)$', s)
        lm = re.match(r'^([-*+]|\d+[.)])\s+(.*)$', s)
        if not s:
            flush()
        elif h:
            flush()
            lv = min(6, len(h.group(1)) + 1)
            out.append('<h%d>%s</h%d>' % (lv, md_inline(h.group(2).strip('# ')), lv))
        elif lm:
            if para:
                flush()
            kind = 'ol' if lm.group(1)[0].isdigit() else 'ul'
            if items and lt[0] != kind:
                flush()
            lt[0] = kind
            items.append(lm.group(2))
        elif items and line.startswith((' ', '\t')):
            items[-1] += ' ' + s
        else:
            if items:
                flush()
            para.append(s)
    if fence is not None:
        out.append('<pre><code>%s</code></pre>' % E('\n'.join(code)))
    flush()
    return ''.join(out)


def essay_html(es):
    return ('<article class="essay" id="%s"><p class="prov">Written by people · provenance: human · '
            '<span class="k">%s</span></p>%s</article>' % (es['id'], E(es['source']), md_html(es['body'])))


# ---------------------------------------------------------------- reading
def scan(src, leaks, only=None):
    """Read every public clone under src; only = optional set of repository names (--repos, for small test builds)."""
    files, left = [], collections.Counter()
    seen = {}
    metas = {}
    for repo_dir in sorted(os.listdir(src), key=str.lower):
        d = os.path.join(src, repo_dir)
        if not os.path.isdir(os.path.join(d, '.git')):
            continue
        url = git(d, 'config', '--get', 'remote.origin.url')
        if not url.lower().startswith('https://github.com/ventusltd/'):
            continue
        repo = url.rstrip('/').split('/')[-1]
        repo = repo[:-4] if repo.endswith('.git') else repo
        if leaks(repo) or (only and repo not in only):
            continue
        commit = git(d, 'rev-parse', 'HEAD')
        listing = git(d, 'ls-tree', '-r', '-l', '-z', 'HEAD', binary=True).decode('utf-8', 'replace')
        items, extra = [], []
        meta = {'repo': repo, 'dir': d, 'commit': commit, 'readmes': {}, 'license_text': None, 'license_file': None,
                'citation': False, 'packages': {}}
        for ent in listing.split('\0'):
            if '\t' not in ent:
                continue
            m_, path = ent.split('\t', 1)
            mode, typ, sha, size = m_.split()
            if typ != 'blob' or size == '-':
                continue
            if path == '.nojekyll':
                meta['nojekyll'] = True
            elif path == 'CNAME' and 0 < int(size) < 300:
                extra.append(('cname', path, sha))
            if 0 < int(size) <= 1_000_000 and EXT.search(path) and not SKIP.search(path):
                items.append((path, sha))
            if SKIP.search(path) or not 0 < int(size) <= 1_000_000:
                continue
            base_ = path.rsplit('/', 1)[-1]
            if README_RX.search(path):
                extra.append(('readme', path, sha))
            elif '/' not in path and LICENSE_RX.match(base_):
                if meta['license_file'] is None or len(path) < len(meta['license_file']):
                    meta['license_file'] = path
                    meta['_license_sha'] = sha
            elif path.lower() == 'citation.cff':
                meta['citation'] = True
            elif base_ == 'package.json':
                extra.append(('package', path, sha))
        if meta.get('_license_sha'):
            extra.append(('license', meta['license_file'], meta.pop('_license_sha')))
        p = subprocess.Popen(['git', '-C', d, 'cat-file', '--batch'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)

        def blob(sha):
            p.stdin.write((sha + '\n').encode())
            p.stdin.flush()
            hdr = p.stdout.readline().split()
            if len(hdr) < 3 or hdr[1] == b'missing':
                return None
            data = p.stdout.read(int(hdr[2]))
            p.stdout.read(1)
            return data
        for kind, path, sha in extra:
            data = blob(sha)
            if data is None:
                continue
            text = data.decode('utf-8', 'replace')
            if kind == 'readme':
                folder = posixpath.dirname(path)
                prev = meta['readmes'].get(folder)
                if prev and prev[0].lower().endswith('.md') and not path.lower().endswith('.md'):
                    continue
                s, sc = readme_pick(text, repo)
                if s and leaks(s):
                    s, sc = '', None
                meta['readmes'][folder] = (path, s, sc)
                meta.setdefault('readme_sentences', {})[folder] = describe.readme_sentences(text)
            elif kind == 'cname':
                cn = text.strip().split('\n')[0].strip()
                if re.match(r'^[a-z0-9.-]+\.[a-z]{2,}$', cn, re.I):
                    meta['cname'] = cn
            elif kind == 'license':
                meta['license_text'] = text
            elif kind == 'package':
                try:
                    meta['packages'][path] = json.loads(text)
                except ValueError:
                    pass
        meta['license'] = license_of(meta['license_text'])
        metas[repo] = meta
        for path, sha in items:
            data = blob(sha)
            if data is None:
                left['not fetched'] += 1
                continue
            n = len(data)
            if sha in seen:
                meta.setdefault('dups', {})[path] = seen[sha]  # same blob kept once elsewhere; edges follow it
                continue
            if b'\0' in data[:8000]:
                continue
            seen[sha] = (repo, path)
            lines = data.decode('utf-8', 'replace').split('\n')
            if lines and lines[-1] == '':
                lines.pop()
            if not lines or n / len(lines) > 400:
                left['minified or one-line'] += 1
                continue
            files.append({'repo': repo, 'commit': commit, 'path': path, 'blob': sha, 'lines': lines})
        p.stdin.close()
        p.wait()
    newest = {}
    for f in files:
        fam = f['repo'] + '|' + STAMP.sub('#', f['path'])
        key = (max(STAMP.findall(f['path']) or ['']), f['path'])
        if fam not in newest or key > newest[fam][0]:
            newest[fam] = (key, f)
    left['older timestamped versions'] = len(files) - len(newest)
    kept = []
    for _, f in newest.values():
        if leaks(f['path']) or leaks('\n'.join(f['lines'])):
            left['matches a non-public digest'] += 1
            continue
        kept.append(f)
    return kept, left, metas


# ---------------------------------------------------------------- understanding
def definitions(path, lines):
    e = ext(path)
    rules = PY_DEF if e == 'py' else SH_DEF if e == 'sh' else YML_DEF if e in ('yml', 'yaml') else \
        JS_DEF if e in JSX else []
    out = []
    for i, line in enumerate(lines, 1):
        if len(line) <= 400:
            for rx, kind in rules:
                m = rx.match(line)
                if m:
                    out.append((m.group(1).strip(), kind, i))
                    break
    return out


STATUS_NOTE = re.compile(
    r'^\W*(copied|copy of|retired|deprecated|legacy|archived|frozen|superseded|do not (edit|modify)|auto-?generated|'
    r'generated (by|from)|candidate|regional candidate|v\d+(\.\d+)*\s*[:\-]|version\s+\d|orient-?\d|generation\s+\d|'
    r'eslint|@ts-|prettier|spdx|copyright|licen[cs]e|todo|fixme|hack|note:|see |https?://|family #|\d{8,})',
    re.I)


def clean_comment(text):
    text = re.sub(r'<[^>]+>', ' ', text)
    text = re.sub(r'\s+', ' ', text).strip(' -=*#/!"\'')
    if len(text) < 12 or not re.search(r'[a-zA-Z]{3,}\s+[a-zA-Z]{2,}', text):
        return ''
    if STATUS_NOTE.search(text) or text.isupper():
        return ''
    m = re.match(r'(.{12,220}?[.!?])(\s|$)', text)
    return (m.group(1) if m else text[:200].rsplit(' ', 1)[0] + '…')


def capability_of(path, lines):
    """The file's own statement of purpose: leading docstring or comment, HTML title, workflow name."""
    e = ext(path)
    head = '\n'.join(lines[:60])
    if e in ('html', 'htm'):
        for rx in (r'<meta\s+name=["\']description["\']\s+content=["\']([^"\']+)', r'<title>([^<]+)</title>'):
            m = re.search(rx, head, re.I)
            if m and clean_comment(m.group(1)):
                return clean_comment(m.group(1))
    if e in ('yml', 'yaml'):
        m = re.search(r'^name:\s*["\']?([^"\'#\n]+)', head, re.M)
        c = ''
        cm = re.findall(r'^\s*#\s?(.*)$', head, re.M)
        if cm:
            c = clean_comment(' '.join(cm[:6]))
        return c or ('Workflow "%s".' % m.group(1).strip() if m else '')
    if e == 'py':
        m = re.search(r'^\s*(?:#![^\n]*\n)?(?:#[^\n]*\n)*\s*[rubRUB]*("""|\'\'\')(.*?)\1', head, re.S)
        if m and clean_comment(m.group(2)):
            return clean_comment(re.sub(r'^[\w./-]+\s+-\s+', '', m.group(2).strip()))
    block = re.match(r'\s*(?:#![^\n]*\n)?\s*/\*\*?(.*?)\*/', head, re.S)
    if block and clean_comment(block.group(1)):
        return clean_comment(block.group(1))
    cm = []
    for line in lines[:40]:
        s = line.strip()
        if s.startswith(('//', '#')) and not s.startswith('#!'):
            cm.append(s.lstrip('/#').strip())
        elif s and cm:
            break
        elif s and not s.startswith(("'use", '"use', '<!doctype', '<!DOCTYPE', '<html', '<meta', '<head')):
            if not cm:
                continue
    return clean_comment(' '.join(cm)) if cm else ''


def exports_of(path, lines, defs):
    e = ext(path)
    if e in JSX:
        ex = [m.group(1) for l in lines if (m := JS_EXPORT.match(l))]
        if ex:
            return ex
    if e == 'py':
        return [n for n, k, i in defs if not n.startswith('_') and not lines[i - 1].startswith((' ', '\t'))]
    return [n for n, k, i in defs if k != 'workflow']


def load_vedic(src):
    """Curated meanings from vedic-/data/dictionary.json, indexed by the function each translates."""
    p = os.path.join(src, 'vedic-', 'data', 'dictionary.json')
    by_name = collections.defaultdict(list)
    if not os.path.isfile(p):
        print('VEDIC dictionary not found at %s; statements use comments only' % p, file=sys.stderr)
        return by_name
    for e in json.load(open(p, encoding='utf-8')).get('entries', []):
        parts = (e.get('translation_ref') or '').split(':')
        ref = parts[-1].strip()
        if ref and e.get('word'):
            e = dict(e, _modules=[t.lower() for t in parts[:-1] if t and not t.isdigit() and t not in ('source', 'engine')])
            by_name[ref].append(e)
    return by_name


def vedic_matches(f, vedic):
    """A meaning attaches only to a distinctive name, or where its module appears in the file's path."""
    out, path = [], (f['repo'] + '/' + f['path']).lower()
    for n, k, i in f['defs']:
        distinctive = len(n) >= 8 and re.search(r'[a-z][A-Z]', n)
        for e in vedic.get(n, []):
            if (distinctive or any(m in path for m in e['_modules'])) and e not in out:
                out.append(e)
    return out


def topic_of(f):
    words = words_of(f['repo'] + '/' + f['path'])
    if f['path'].startswith('.github/'):
        return 'automation'
    for k, t, d, kws in TOPIC_RX:
        for w in words:
            if w in kws or any(len(kw) >= 5 and w.startswith(kw) for kw in kws):
                return k
    return 'web-apps'


# ---------------------------------------------------------------- references (edges), evidence only
# Every edge is (from file, to file, kind, via). Kinds, each found by its own expression below:
EDGE_KINDS = [
    # kind              used-by verb        label                     where it is read
    ('import',          'imported by',      'import',                 'JS/TS static import/export-from; Python import / from-import'),
    ('python-relative', 'imported by',      'relative import',        'Python from . import x / from .x import y'),
    ('sys-path',        'imported by',      'sys.path import',        'Python import found through a sys.path.insert/append dir'),
    ('require',         'required by',      'require',                "JS require('./x')"),
    ('dynamic-import',  'imported by',      'dynamic import',         "JS import('./x')"),
    ('url-import-meta', 'referenced by',    'new URL import.meta.url', "JS new URL('./x', import.meta.url)"),
    ('worker',          'started by',       'worker',                 'new Worker / SharedWorker / importScripts / serviceWorker.register'),
    ('script-src',      'loaded by',        'script src',             '<script src>, el.src = "x.js"'),
    ('stylesheet',      'loaded by',        'stylesheet',             '<link rel=stylesheet href>, CSS @import'),
    ('modulepreload',   'preloaded by',     'modulepreload',          '<link rel=modulepreload|preload|prefetch href>'),
    ('import-map',      'mapped by',        'import map',             '<script type=importmap> imports/scopes targets'),
    ('iframe',          'embedded by',      'iframe',                 '<iframe src>, <frame src>'),
    ('link',            'linked from',      'link',                   '<a href>, meta refresh, location.href = / window.open( to a same-site page'),
    ('fetch',           'fetched by',       'fetch',                  "fetch('x.js|.mjs|.json|.html'), relative or estate URL"),
    ('estate-url',      'named by URL in',  'estate URL',             'any other absolute URL into the estate (Pages, CNAME host, raw, jsDelivr, GitHub blob)'),
    ('comment-url',     'mentioned in',     'comment link',           'an estate URL found only inside comments or docstrings (a mention, not a load: '
                                                                          'kept in "edges", never in imports/dependents or reachability)'),
    ('script-call',     'run by',           'script call',            'python/node/bash x in shell, Python subprocess, child_process, package.json scripts'),
    ('workflow-run',    'run by',           'workflow run',           'GitHub workflow run: lines (python x.py, node x.mjs, bash x.sh, ./x.sh) and local uses:'),
]
EDGE_VERB = {k: v for k, v, l, d in EDGE_KINDS}
EDGE_LABEL = {k: l for k, v, l, d in EDGE_KINDS}
# via: how the target was found. '' = the path as written; 'url' = an absolute estate URL; 'index' = a
# directory URL resolved to folder/index.html; 'family' = the path names an older timestamped version, mapped
# to the kept newest member; 'duplicate' = the path holds a blob kept once elsewhere; 'pages-root' = resolved
# against the repository's Pages root, not the file's folder; 'root' = a script path resolved from the
# repository root. Joined with '+' when more than one applies.
EXT_KINDS = ('import', 'python-relative', 'require', 'dynamic-import', 'worker', 'script-src', 'stylesheet',
             'modulepreload', 'import-map')  # unresolved specs of these kinds are listed as external uses
Q = r'''['"`]'''
JS_STATIC = re.compile(r'''(?m)^[ \t]*(?:import|export)\s+(?:[^'"`;()]*?\sfrom\s*)?['"]([^'"\n]+)['"]''')
JS_DYN = re.compile(r'''(?<![\w.$])import\(\s*['"`]([^'"`\n$]+)['"`]\s*[,)]''')
JS_REQ = re.compile(r'''(?<![\w.$])require\(\s*['"]([^'"\n]+)['"]\s*\)''')
JS_URL = re.compile(r'''new\s+URL\(\s*['"`]([^'"`\n$]+)['"`]\s*,\s*import\.meta\.url''')
JS_WORK = re.compile(r'''(?:new\s+(?:Shared)?Worker\(\s*|importScripts\(\s*|serviceWorker\.register\(\s*)['"`]([^'"`\n$]+)['"`]''')
JS_SRCSET = re.compile(r'''\.src\s*=\s*['"`]([^'"`\n$]+\.m?js(?:\?[^'"`]*)?)['"`]''')
JS_FETCH = re.compile(r'''(?<![\w.$])fetch\(\s*['"`]([^'"`\n$]+)['"`]''')
JS_NAV = re.compile(r'''(?:location(?:\.href)?\s*=|location\.(?:assign|replace)\(|window\.open\()\s*['"`]([^'"`\n$]+)['"`]''')
HTML_TAG = re.compile(r'''<(script|link|iframe|frame|a|area)\b([^>]*)>''', re.I)
HTML_ATTR = re.compile(r'''([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))''')
HTML_IMAPS = re.compile(r'''<script[^>]*type=["']?importmap["']?[^>]*>(.*?)</script>''', re.I | re.S)
HTML_REFRESH = re.compile(r'''<meta[^>]+http-equiv=["']?refresh["']?[^>]*content=["'][^"']*url=([^"'>\s]+)''', re.I)
CSS_IMPORT = re.compile(r'''@import\s+(?:url\(\s*)?['"]?([^'")\s;]+)''')
PY_FROM = re.compile(r'^\s*from\s+(\.*)([\w.]*)\s+import\s+(.+)$')
PY_IMP = re.compile(r'^\s*import\s+([\w.]+(?:\s+as\s+\w+)?(?:\s*,\s*[\w.]+(?:\s+as\s+\w+)?)*)\s*(?:#.*)?$')
PY_SYSPATH = re.compile(r'sys\.path\.(?:insert\(\s*-?\d+\s*,|append\()\s*(.+?)\)\s*(?:#.*)?$')
PY_ASSIGN = re.compile(r'^([A-Za-z_]\w*)\s*=\s*(.+?)\s*(?:#.*)?$')
SCRIPT_EXT = r'(?:py|m?js|cjs|ts|sh|ps1|bat|R|rb)'
CMD = re.compile(r'''(?:^|[\s;&|('"`\[=]|run:\s*)(?:python3?(?:\.\d+)?|py|node|deno\s+run|bash|sh|zsh|pwsh|powershell'''
                 r'''(?:\s+-File)?|Rscript|ruby|tsx|ts-node|npx\s+(?:tsx|ts-node))\s+(?:-[\w-]+(?:=\S+)?\s+)*['"]?'''
                 r'''([\w./$*{][\w./{}$*-]*?\.''' + SCRIPT_EXT + r''')(?![\w.])''')
# Test runners that discover files by their documented default rules: pytest (test_*.py, *_test.py, conftest.py),
# python -m unittest [discover -s DIR -p PATTERN] (test*.py), node --test (*.test.js, test-*.js, test/ folders, ...).
TEST_RUN = re.compile(r'''(?:^|[\s;&|('"`]|run:\s*)(?:python3?(?:\.\d+)?\s+-m\s+)?(pytest|unittest|py_compile|node\s+--test)(?![\w=<>.-])([^;&|\n#]*)''')
CMD_MOD = re.compile(r'''(?:^|[\s;&|('"`])python3?(?:\.\d+)?\s+-m\s+([A-Za-z_][\w.]*)''')
CMD_EXEC = re.compile(r'''(?:^|[\s;&|('"`]|run:\s*)(\.{1,2}/[\w./-]+\.(?:sh|py|mjs|js|ps1))\b''')
PY_SUB = re.compile(r'''(?:['"](?:python3?|node|bash|sh)['"]|sys\.executable)\s*,\s*(?:['"]-[\w-]+['"]\s*,\s*)*'''
                    r'''(?:str\()?[^,\]\n]*?['"]([\w./-]+\.(?:py|m?js|sh))['"]''')
SH_HERE = re.compile(r'''^\s*(?:export\s+|local\s+|readonly\s+)?([A-Za-z_]\w*)=["']?\$\((?:cd\s+)?["']?\$\(dirname\s''', re.M)
SH_ENV = re.compile(r'''^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*[:=]\s*['"]?([\w./-]+\.''' + SCRIPT_EXT + r''')['"]?\s*$''', re.M)
CMD_VAR = re.compile(r'''(?:python3?|node|bash|sh|pwsh)\s+(?:-[\w-]+\s+)*["']?\$(?:\{\{\s*env\.(\w+)\s*\}\}|\{?(\w+)\}?)["']?(?:\s|$)''')
STR_PATH = re.compile(r'''['"`]((?:\.{1,2}/)?[\w.-]+(?:/[\w.-]+)*\.''' + SCRIPT_EXT + r''')['"`]''')
WF_USES = re.compile(r'''^\s*-?\s*uses:\s*['"]?(\./[\w./-]+)''', re.M)
WF_WD = re.compile(r'''working-directory:\s*['"]?([\w./-]+)''')
CD_RX = re.compile(r'''(?:^|[;&|]\s*|\s)cd\s+['"]?([\w./-]+)['"]?\s*(?:&&|;)''')


def _attrs(s):
    return {m.group(1).lower(): next(g for g in m.groups()[1:] if g is not None) for m in HTML_ATTR.finditer(s)}


def _python_refs(lines):
    out = []
    i, n = 0, len(lines)
    while i < n:
        line = lines[i]
        i += 1
        if 'import' not in line or len(line) > 400:
            continue
        m = PY_FROM.match(line)
        if m:
            names = m.group(3)
            if names.strip().startswith('(') and ')' not in names:
                while i < n and ')' not in names:
                    names += ' ' + lines[i]
                    i += 1
            names = [w.split(' as ')[0].strip() for w in re.sub(r'#[^\n]*', '', names).strip('() \\').split(',')]
            names = tuple(w for w in names if re.match(r'^[A-Za-z_]\w*$', w))
            dots, mod = m.group(1), m.group(2)
            out.append(('python-relative' if dots else 'import', dots + mod, names))
            continue
        m = PY_IMP.match(line)
        if m:
            for part in m.group(1).split(','):
                out.append(('import', part.split(' as ')[0].strip(), ()))
    return out


def _split_top(s, sep):
    parts, depth, cur, q = [], 0, '', None
    i = 0
    while i < len(s):
        c = s[i]
        if q:
            cur += c
            if c == q:
                q = None
        elif c in '\'"':
            q = c
            cur += c
        elif c in '([{':
            depth += 1
            cur += c
        elif c in ')]}':
            depth -= 1
            cur += c
        elif depth == 0 and s.startswith(sep, i):
            parts.append(cur)
            cur = ''
            i += len(sep)
            continue
        else:
            cur += c
        i += 1
    parts.append(cur)
    return [p.strip() for p in parts]


def py_path_expr(expr, env, fpath, depth=0):
    """A repository-relative path for a simple Python path expression (Path(__file__).resolve().parents[1] / "x",
    os.path.join(os.path.dirname(__file__), '..', 'src'), HERE, str(ROOT / "scripts")), or None."""
    if depth > 12:
        return None
    e = re.sub(r'\.(?:resolve|absolute|expanduser)\(\)', '', expr.strip())
    m = re.match(r'^[rbuf]?([\'"])(.*)\1$', e)
    if m:
        return ('lit', m.group(2))
    if e == '__file__':
        return ('path', fpath)
    if re.match(r'^[A-Za-z_]\w*$', e):
        return env.get(e)
    parts = _split_top(e, '/')
    if len(parts) > 1:
        base = py_path_expr(parts[0], env, fpath, depth + 1)
        if not base or base[0] != 'path':
            return None
        p = base[1]
        for x in parts[1:]:
            v = py_path_expr(x, env, fpath, depth + 1)
            if not v:
                return None
            p = posixpath.join(p, v[1])
        return ('path', posixpath.normpath(p))
    m = re.match(r'^(.*)\.parent$', e)
    if m:
        v = py_path_expr(m.group(1), env, fpath, depth + 1)
        return ('path', posixpath.dirname(v[1])) if v and v[0] == 'path' else None
    m = re.match(r'^(.*)\.parents\[(\d+)\]$', e)
    if m:
        v = py_path_expr(m.group(1), env, fpath, depth + 1)
        if not v or v[0] != 'path':
            return None
        p = v[1]
        for _ in range(int(m.group(2)) + 1):
            p = posixpath.dirname(p)
        return ('path', p)
    m = re.match(r'^([\w.]+)\((.*)\)$', e, re.S)
    if m:
        fn, args = m.group(1), _split_top(m.group(2), ',')
        if fn in ('str', 'Path', 'pathlib.Path', 'os.path.abspath', 'os.path.realpath', 'os.fspath', 'os.path.normpath') and len(args) == 1:
            return py_path_expr(args[0], env, fpath, depth + 1)
        if fn == 'os.path.dirname' and len(args) == 1:
            v = py_path_expr(args[0], env, fpath, depth + 1)
            return ('path', posixpath.dirname(v[1])) if v and v[0] == 'path' else None
        if fn in ('os.path.join', 'Path', 'pathlib.Path') and len(args) > 1:
            vs = [py_path_expr(a, env, fpath, depth + 1) for a in args]
            if not all(vs) or vs[0][0] != 'path':
                return None
            return ('path', posixpath.normpath(posixpath.join(*[v[1] for v in vs])))
    return None


def python_syspath_dirs(path, lines):
    """Repository-relative folders added to sys.path by this file (only those the expression evaluator can follow)."""
    env, dirs = {}, []
    text_has = any('sys.path' in l for l in lines)
    if not text_has:
        return dirs
    for line in lines:
        if len(line) > 300:
            continue
        m = PY_ASSIGN.match(line)
        if m and m.group(1) != 'sys':
            v = py_path_expr(m.group(2), env, path)
            if v:
                env[m.group(1)] = v
            continue
        m = PY_SYSPATH.search(line)