GLOBALGRID2050 / EXPLORE CODE

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

Build (part 5)

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 1084 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 2801–3500

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 2801–3500 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
repo_story, hook_of, descriptor_src, descriptor, lic_badges, lic_html, folder_block, aside_li, other_file, start_of, anchor, role_strip, repo_line, gh_url, vedic_lines, block
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:2801-3500 · 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
                   E('\n'.join(l if len(l) <= LINE_CAP else l[:LINE_CAP] + '  … [line shortened here: %s characters; full line on GitHub]' % format(len(l), ',')
                               for l in f['lines'][a - 1:b]))))
            toc.append('<li><a href="#f%d">%s</a> %s · %s / %s lines %d–%d</li>'
                       % (bi, E(f['title']), badge(f['role']), E(f['repo']), E(f['path']), a, b))
        dom = files[sec_dom[si - 1]]
        summary = '%s lines of %s from %s, in %d file%s.' % (
            format(lines_n, ','), ' and '.join('%s' % l for l, c in langs.most_common(3)),
            ', '.join(repos[:3]) + (' and %d more' % (len(repos) - 3) if len(repos) > 3 else ''),
            len(parts), '' if len(parts) == 1 else 's')
        title = sec_title[si - 1]
        desc = '%s %s' % (dom['synopsis'], summary)
        section_meta.append({'section': si, 'topic': topic, 'repos': repos, 'lines': lines_n, 'summary': summary,
                             'parts': parts, 'title': title, 'synopsis': dom['synopsis']})
        prev = '<a href="../%s" rel="prev">← Section %d</a>' % (sname(si - 1), si - 1) if si > 1 else ''
        nxt = '<a href="../%s" rel="next">Section %d →</a>' % (sname(si + 1), si + 1) if si < len(sections) else ''
        nav = ('<nav>%s<a href="../topics/%s.html">%s</a><a href="../repos/%s.html">%s</a><a href="../index.html">All topics</a>'
               '<a href="../search.html">Search</a>%s</nav>' % (prev, topic, E(topic_title[topic]), slug(dom['repo']),
                                                                E(dom['repo']), nxt))
        f0 = files[parts[0][0]]
        ess_link = None
        if f0['essay']:
            ess_link = '<a href="../%s#%s">%s</a>' % (sname(essay_home[f0['essay']['id']]), f0['essay']['id'], E(f0['essay']['title']))
        elif f0['repo_essay']:
            ess_link = '<a href="../repos/%s.html#%s">%s</a>' % (slug(f0['repo']), f0['repo_essay']['id'], E(f0['repo_essay']['title']))
        essays_html = ''.join(essay_html(es) for es in essays_here if essay_home.get(es['id']) == si) + \
            ''.join('<p class="prov">Written by people: <a href="../%s#%s">%s</a> (essay on this folder)</p>'
                    % (sname(essay_home[es['id']]), es['id'], E(es['title'])) for es in essays_here if essay_home.get(es['id']) != si)
        langs1 = langs.most_common(1)[0][0]
        ld = {'@context': 'https://schema.org', '@type': 'SoftwareSourceCode', 'name': title, 'description': desc[:300],
              'url': base + sname(si), 'codeRepository': 'https://github.com/Ventusltd/%s' % f0['repo'],
              'programmingLanguage': langs1, 'author': ventus_org(), 'provider': ventus_org(),
              'isPartOf': {'@type': 'WebSite', 'name': SITE, 'url': base}}
        if lic_url(f0['repo']) and lic_of(f0['repo']) != 'none found':
            ld['license'] = lic_url(f0['repo'])
        body = ('<header><p class="brand">GLOBALGRID2050 / EXPLORE CODE</p>%s<h1>%s</h1><p class="syn">%s</p>'
                '<p>%s Topic: %s. Section %d of %d.</p><p class="k">Cut %s. A copy for reading; the repository at the stated commit is the source.</p>'
                '<p class="k labels">In the State lines below, %s: <a href="%s">the rules</a>.</p>'
                '</header>%s<main>%s<h2>In this section</h2><ol>%s</ol>%s</main>%s'
                % (crumbs(topic, f0['repo'], posixpath.dirname(f0['path']) or '/', '../', ess_link), E(title),
                   E(dom['synopsis']), E(summary), E(topic_title[topic]), si, len(sections), stamp,
                   E((LABELS_NOTE % agentdocs.RULES_VERSION).replace('domain_stage, commercial_user and canonical_status',
                                                                     'domain stage, users and canonical status')),
                   E(RULES_URL), nav, essays_html,
                   ''.join(toc), ''.join(blocks), nav))
        site.write(sname(si), '%s — %s' % (title, SITE), desc, body, 1, ld)

    # Repository pages
    by_repo = collections.defaultdict(list)
    for m in section_meta:
        for r in m['repos']:
            by_repo[r].append(m)
    repo_files = collections.defaultdict(list)
    for fi, f in enumerate(files):
        repo_files[f['repo']].append(fi)

    # Cross-repository use: other repositories' files that load this one's published data or code by URL
    xref = collections.defaultdict(set)
    XREF = re.compile(r'(?:ventusltd\.github\.io|raw\.githubusercontent\.com/ventusltd|cdn\.jsdelivr\.net/gh/ventusltd)/([\w.-]+)')
    lower_repo = {r.lower(): r for r in metas}
    for i, f in enumerate(files):
        if 'ventusltd' in f['low']:
            for m in set(XREF.findall(f['low'])):
                r = lower_repo.get(m.rstrip('.'))
                if r and r != f['repo']:
                    xref[r].add(i)

    def repo_story(r):
        fis = repo_files[r]
        verbs, objs, srcs = collections.Counter(), collections.Counter(), collections.Counter()
        for fi in fis:
            v, o, sr = files[fi].get('syn_parts', ('', [], []))
            if v:
                verbs[v] += 1
            objs.update(set(o))
            srcs.update(set(sr))
        roles = collections.Counter(files[fi]['role'] for fi in fis)
        top_o = [o for o, c in objs.most_common(5) if c >= 2] or [o for o, c in objs.most_common(3)]
        ach = 'Across its %d file%s' % (len(fis), '' if len(fis) == 1 else 's')
        vs = [v for v, c in verbs.most_common(3)]
        ach += (', the code mostly %s.' % join_words(vs)) if vs else ':'
        if top_o:
            ach += ' Key elements: %s.' % join_words(top_o)
        if srcs:
            ach += ' Data sources: %s.' % join_words([x for x, c in srcs.most_common(4)])
        ach += ' Main functions: %s.' % ', '.join('%s (%d files)' % (ROLE_TITLE[k].split(' (')[0].lower(), c)
                                                 for k, c in roles.most_common(3))
        users = xref.get(r, set())
        inner = sum(1 for fi in fis if imported_by.get(fi))
        why = []
        if users:
            ur = collections.Counter(files[i]['repo'] for i in users)
            why.append('Loaded by URL from %d file%s in %d other repositor%s: %s.' % (
                len(users), '' if len(users) == 1 else 's', len(ur), 'y' if len(ur) == 1 else 'ies',
                join_words(['%s (%d)' % (x, c) for x, c in ur.most_common(5)])))
        if inner:
            most = sorted(fis, key=lambda fi: -len(imported_by.get(fi, [])))[:3]
            why.append('%d of its files %s imported by other files in the repository; most used: %s.' % (
                inner, 'is' if inner == 1 else 'are', join_words(['%s (%d)' % (files[fi]['title'], len(imported_by[fi])) for fi in most if imported_by.get(fi)])))
        return ach, ' '.join(why), users

    def hook_of(r):
        """An owner-pending CORE_HOOKS draft, used only when no human essay covers the repository page."""
        return CORE_HOOKS.get(r, '') if (r, 'repo', '') not in essays else ''

    def descriptor_src(r):
        """'core_hook_draft' for a CORE_HOOKS text (draft awaiting owner approval; a human essay overrides it),
        'readme' when the root README's chosen paragraph is strong enough (root_ok), else 'code'."""
        if hook_of(r):
            return 'core_hook' if CORE_HOOKS_STATUS == 'owner_approved' else 'core_hook_draft'
        return 'readme' if root_ok(r) else 'code'

    def descriptor(r, n=160):
        """One line on what a repository is: the root README's chosen paragraph (first sentence) when root_ok, else
        a synopsis aggregated from its files' evidence (repo_story: verbs, key elements, data sources, functions)."""
        root = metas[r]['readmes'].get('', ('', '', None))[1]
        if hook_of(r):
            m = re.match(r'(.{20,}?[.!?])(\s|$)', hook_of(r))
            return trim(hook_of(r) if n >= 400 else (m.group(1) if m else hook_of(r)), n)
        if root and root_ok(r):
            m = re.match(r'(.{20,}?[.!?])(\s|$)', root)
            return trim(m.group(1) if m else root, n)
        fis = repo_files[r]
        if fis:
            return trim(repo_story(r)[0], n)
        tops = collections.Counter(files[fi]['path'].split('/')[0] for fi in fis if '/' in files[fi]['path'])
        roles = collections.Counter(files[fi]['role'] for fi in fis)
        return trim('Code%s; mostly %s.' % (
            (' in ' + join_words([humanise(t) or t for t, c in tops.most_common(3)])) if tops else '',
            join_words([ROLE_TITLE[k].split(' (')[0].lower() for k, c in roles.most_common(2)])), n)

    def lic_badges(r):
        m = metas[r]
        out = '<span class="lic">%s</span>' % E(m['license']) if m['license_file'] else '<span class="lic none">no licence found</span>'
        return out + (' <span class="lic">CITATION</span>' if m['citation'] else '')

    def lic_html(r, up):
        m = metas[r]
        lic = m['license']
        if m['license_file']:
            lic = '<a href="%s">%s</a> (from %s)' % (E(lic_url(r)), E(lic), E(m['license_file']))
        else:
            lic = '<span class="flag">none found</span> (no LICENSE file at the repository root)'
        return 'Licence: %s · CITATION.cff: %s' % (lic, 'present' if m['citation'] else 'not found')

    for r, ms in by_repo.items():
        meta = metas[r]
        folders = collections.defaultdict(list)
        for fi in repo_files[r]:
            if main_view(fi):
                folders[posixpath.dirname(files[fi]['path']) or '/'].append(fi)
        n_aside_r = sum(1 for fi in repo_files[r] if not main_view(fi))
        main_topic = collections.Counter(files[fi]['topic'] for fi in repo_files[r]).most_common(1)[0][0]

        # Folder lists fold (phone first): each folder is a <details>, open only when the repository has few folders.
        # Large repositories list names only; the synopsis lives once on the section page (photon rule: link by key).
        n_main = sum(len(v) for v in folders.values())
        big = n_main > REPO_SYNOPSIS_MAX
        few = len(folders) <= 3

        def folder_block(folder, fis):
            rd = meta['readmes'].get('' if folder == '/' else folder)
            ctx = ('<p class="k">README: %s</p>' % E(rd[1])) if rd and rd[1] and folder != '/' else ''
            items = ''.join(('<li>%s %s</li>' % (flink(fi, '../'), badge(files[fi]['role']))) if big else
                            ('<li>%s %s<br><span class="k">%s</span></li>' % (flink(fi, '../'), badge(files[fi]['role']),
                                                                              E(files[fi]['synopsis']))) for fi in fis)
            return '<details class="fold" id="d-%s"%s><summary><h3>%s</h3> <span class="k">%d file%s</span></summary>%s<ul>%s</ul></details>' % (
                slug(folder), ' open' if few else '', E(folder), len(fis), '' if len(fis) == 1 else 's', ctx, items)
        fl = ''.join(folder_block(folder, fis) for folder, fis in sorted(folders.items()))
        if big:
            fl = ('<p class="k">%s files: names only here; each file\'s synopsis is on its section page.</p>'
                  % format(n_main, ',')) + fl
        n_lines = sum(len(files[fi]['lines']) for fi in repo_files[r])
        root = meta['readmes'].get('', ('', '', None))
        if not root_ok(r):
            root = (root[0], '', root[2])
        tier = ''
        if (r, 'repo', '') in essays:
            tier = essay_html(essays[(r, 'repo', '')])
        elif hook_of(r):
            tier = '<p class="k">Descriptor above: %s (%s). A human essay on this repository replaces it.</p>' % (
                'approved by the owner' if CORE_HOOKS_STATUS == 'owner_approved' else 'a draft awaiting owner approval',
                E(CORE_HOOKS_SOURCE))
        elif root[1]:
            tier = ('<p class="k">Descriptor above: the descriptive paragraph chosen from <a href="https://github.com/Ventusltd/%s/blob/%s/%s">%s</a> '
                    '(environment and domain context, readme_derived).</p>' % (E(r), meta['commit'], urllib.parse.quote(root[0]), E(root[0])))
        else:
            tier = ('<p class="k">Descriptor above: aggregated from the evidence of its files (provenance: code); %s</p>'
                    % ('no paragraph of %s describes what the code is or does strongly enough to be shown.' % E(root[0])
                       if root[0] else 'no README at the repository root.'))
        ess_list = [es for k, es in sorted(essays.items()) if k[0] == r and k[1] != 'repo' and es['id'] in essay_home]
        ess_html = ('<h2>Written by people</h2><ul>%s</ul>' % ''.join(
            '<li><a href="../%s#%s">%s</a> · %s</li>' % (sname(essay_home[es['id']]), es['id'], E(es['title']), E(es['source']))
            for es in ess_list)) if ess_list else ''
        rt = repo_title(r)
        n_entry = sum(1 for fi in repo_files[r] if files[fi]['entry'])
        n_unr = sum(1 for fi in repo_files[r] if not files[fi]['reachable'])
        syn = ('%s: %s lines of unique code in %d files.' % (rt, format(n_lines, ','), len(repo_files[r])) +
               (' Published at %s.' % meta['pages'] if meta['pages'] else ''))
        ach, why, users = repo_story(r)
        # TL;DR (agent reading review): five lines at most, each from evidence already on this page or linked by key.
        ents_r = [fi for fi in repo_files[r] if files[fi]['entry'] and main_view(fi)]
        top_entry = max(ents_r, key=lambda i: (bool(files[i]['published']), reach_size.get(i, 0), -i)) if ents_r else None
        top_secs = sorted(ms, key=lambda m: (-m['lines'], m['section']))[:3]
        tldr = ['<li><b>What:</b> %s%s</li>' % (E(descriptor(r, 160)), ' <span class="k">(draft)</span>'
                                                 if descriptor_src(r) == 'core_hook_draft' else ''),
                '<li><b>Size:</b> %s lines in %d files, %d sections.</li>' % (format(n_lines, ','), len(repo_files[r]), len(ms))]
        if meta['pages']:
            tldr.append('<li><b>Live:</b> <a href="%s">%s</a></li>' % (E(meta['pages']), E(meta['pages'])))
        if top_entry is not None:
            tldr.append('<li><b>Start here:</b> %s</li>' % flink(top_entry, '../'))
        if top_secs:
            tldr.append('<li><b>Largest sections:</b> %s</li>' % ', '.join(
                '<a href="../%s">%s</a>' % (sname(m['section']), E(m['title'])) for m in top_secs))
        tldr_html = '<ol class="tldr" aria-label="In short">%s</ol>' % ''.join(tldr[:5])
        sec_items = ['<li><a href="../%s">%s</a> · section %d</li>' % (sname(m['section']), E(m['title']), m['section'])
                     for m in ms]
        if len(sec_items) > SECTION_FOLD:
            sec_html = ('<ul class="links">%s</ul><details class="fold"><summary>All %d sections</summary>'
                        '<ul class="links">%s</ul></details>' % (''.join(sec_items[:SECTION_FOLD]), len(sec_items),
                                                                 ''.join(sec_items[SECTION_FOLD:])))
        else:
            sec_html = '<ul class="links">%s</ul>' % ''.join(sec_items)
        users_html = ''
        if users:
            seen_u, links_u = set(), []
            for i in sorted(users, key=lambda i: (files[i]['repo'], files[i]['title'])):
                key = (files[i]['repo'], files[i]['title'])
                if key not in seen_u and len(links_u) < 12:
                    seen_u.add(key)
                    si_, bi_ = first_section[i]
                    links_u.append('<a href="../%s#f%d">%s / %s</a>' % (sname(si_), bi_, E(files[i]['repo']), E(files[i]['title'])))
            users_html = '<p class="k">Used from: %s</p>' % ', '.join(links_u)
        body = ('<header><p class="brand">GLOBALGRID2050 / EXPLORE CODE</p>%s<h1>%s</h1>%s'
                '<details class="fold more"><summary>More about this repository</summary><p class="syn">%s</p>'
                '<dl class="v"><dt>What it achieves</dt><dd>%s</dd><dt>Why it matters</dt><dd>%s</dd></dl>%s'
                '<p class="k">%s</p>'
                '<p>%s lines of unique code in %d files, across %d sections. %d entry points; %d files not reached from any '
                'entry point (candidates for review, not deletion). <a href="https://github.com/Ventusltd/%s">Repository on '
                'GitHub</a> at %s.%s</p></details></header>'
                '<nav><a href="../index.html">All topics</a><a href="../topics/%s.html">%s</a><a href="../search.html">Search</a></nav>'
                '<main>%s%s<h2>Sections</h2>%s<h2>Files by folder</h2>%s%s</main>%s'
                % (crumbs(main_topic, r, None, '../'), E('%s (%s)' % (rt, r) if rt != r else r), tldr_html,
                   E(hook_of(r) or root[1] or descriptor(r, 400)), E(ach),
                   E(why) or 'No other repository was found loading it by URL, and no file inside it is imported by another.',
                   users_html, lic_html(r, '../'),
                   format(n_lines, ','), len(repo_files[r]), len(ms), n_entry, n_unr, E(r), meta['commit'][:12],
                   (' Published at <a href="%s">%s</a>.' % (E(meta['pages']), E(meta['pages']))) if meta['pages'] else '',
                   main_topic, E(topic_title[main_topic]), tier, ess_html, sec_html, fl,
                   ('<p class="k">%d file%s of this repository %s set aside from this list (copies, older versions or '
                    'tool output); each keeps its section page. <a href="../set-aside.html#r-%s">Set aside (%d), with '
                    'reasons</a>.</p>' % (n_aside_r, '' if n_aside_r == 1 else 's', 'is' if n_aside_r == 1 else 'are',
                                          slug(r), n_aside_r)) if n_aside_r else '', FOLD_OPEN_JS))
        desc = (hook_of(r) or root[1] or 'Every unique code file in the %s repository, by folder, with plain-English titles and synopses.' % r)
        site.write('repos/%s.html' % slug(r), '%s (%s): code explained — %s' % (rt, r, SITE) if rt != r else
                   '%s: code explained — %s' % (r, SITE), desc, body, 1)

    # Topic pages
    for k, t, d, _ in TOPIC_RX:
        ms = [m for m in section_meta if m['topic'] == k]
        if not ms:
            continue
        rs = collections.Counter(files[fi]['repo'] for fi in range(len(files)) if files[fi]['topic'] == k and main_view(fi))
        caps = [(fi, files[fi]['cap']) for fi in range(len(files))
                if files[fi]['topic'] == k and files[fi]['cap'] and main_view(fi)][:40]
        n_aside_t = sum(1 for fi in set_aside if files[fi]['topic'] == k)
        body = ('<header><p class="brand">GLOBALGRID2050 / EXPLORE CODE</p>%s<h1>%s</h1><p>%s</p><p>%d sections, %s lines '
                'from %d repositories.</p></header><nav><a href="../index.html">All topics</a><a href="../search.html">Search</a></nav>'
                '<main><h2>Repositories</h2><ul class="links">%s</ul><h2>What the code says it does</h2><ul>%s</ul>'
                '<h2>Sections</h2><ol>%s</ol>%s</main>'
                % (crumbs(k, None, None, '../'), E(t), E(d), len(ms), format(sum(m['lines'] for m in ms), ','), len(rs),
                   ''.join('<li><a href="../repos/%s.html">%s</a> (%d files)</li>' % (slug(r), E(r), c) for r, c in rs.most_common()),
                   ''.join('<li>%s: %s</li>' % (flink(fi, '../'), E(c)) for fi, c in caps),
                   ''.join('<li value="%d"><a href="../%s">%s</a> · %s</li>' % (m['section'], sname(m['section']), E(m['title']), E(m['summary']))
                           for m in ms),
                   ('<p class="k">%d file%s in this topic %s set aside from the lists above. <a href="../set-aside.html">'
                    'Set aside, with reasons</a>.</p>' % (n_aside_t, '' if n_aside_t == 1 else 's',
                                                          'is' if n_aside_t == 1 else 'are')) if n_aside_t else ''))
        site.write('topics/%s.html' % k, '%s: GlobalGrid2050 code explained — %s' % (t, SITE), d, body, 1)

    # Words
    grouped = collections.OrderedDict()
    for w in sorted(words, key=lambda w: (w[0].lower(), w[0], w[5], w[6])):
        grouped.setdefault(w[0], []).append(w)
    pages = collections.defaultdict(list)
    for n, locs in grouped.items():
        pages[word_page_of(n)].append((n, locs))
    wcrumb = '<p class="crumbs">Part of: <a href="../index.html">Explore Code</a> / <a href="index.html">Words A–Z</a></p>'
    for pg, entries in pages.items():
        tr = ''.join('<tr id="%s"><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>' % (
            slug(n), E(n), E(locs[0][1]),
            ' '.join(sorted({'<a href="../%s#f%d">%d</a>' % (sname(w[5]), w[6], w[5]) for w in locs})),
            ' · '.join(E(e['word']) for e in vedic.get(n, [])[:2] if len(n) >= 8 and re.search(r'[a-z][A-Z]', n))) for n, locs in entries)
        body = ('<header><p class="brand">GLOBALGRID2050 / EXPLORE CODE / WORDS</p>%s<h1>Words: %s</h1><p>Functions, classes and '
                'workflows defined in the code. The numbers are sections; each opens at the defining file. VEDIC shows a curated '
                'meaning where one exists.</p></header><nav><a href="index.html">Words A–Z</a><a href="../index.html">All topics</a>'
                '<a href="../search.html">Search</a></nav><main><table><thead><tr><th>Word</th><th>Kind</th><th>Sections</th>'
                '<th>VEDIC</th></tr></thead><tbody>%s</tbody></table></main>' % (wcrumb, E(pg), tr))
        site.write('words/%s.html' % pg, 'Code words %s — %s' % (pg, SITE),
                   'Defined functions and classes beginning %s: %s.' % (pg, ', '.join(n for n, l in entries[:8])), body, 1)
    body = ('<header><p class="brand">GLOBALGRID2050 / EXPLORE CODE</p><p class="crumbs">Part of: <a href="../index.html">'
            'Explore Code</a></p><h1>Words A–Z</h1><p>%s distinct words naming %s '
            'definitions.</p></header><nav><a href="../index.html">All topics</a><a href="../search.html">Search</a></nav><main><ul class="links">%s</ul></main>'
            % (format(len(grouped), ','), format(len(words), ','),
               ''.join('<li><a href="%s.html">%s</a> (%d)</li>' % (p, E(p), len(pages[p])) for p in sorted(pages))))
    site.write('words/index.html', 'Code words A–Z — %s' % SITE, 'Alphabetical dictionary of the code estate.', body, 1)

    # Set aside, with reasons (--clean-manifest; clean/CONTRACT.md section 6). Links only: the code stays on its one
    # section page, the evidence beside it there.
    if clean_info:
        cat_n = collections.Counter(rec['category'] for rec in set_aside.values())
        by_r = collections.defaultdict(list)
        for fi in sorted(set_aside, key=lambda i: (files[i]['repo'].lower(), files[i]['path'])):
            by_r[files[fi]['repo']].append(fi)

        def aside_li(fi):
            rec = set_aside[fi]
            stays = rec.get('target_fi')
            return '<li>%s · %s / %s<br><span class="k">%s: %s%s</span></li>' % (
                flink(fi, ''), E(files[fi]['repo']), E(files[fi]['path']), E(CLEAN_CATEGORY_TITLE[rec['category']]),
                E(rec.get('reason') or ''), (' Stays: %s.' % flink(stays, '')) if stays in first_section else '')
        rows = ''.join('<tr id="c-%s"><td>%s</td><td>%s</td><td>%d</td></tr>' % (c, E(t), E(c), cat_n[c])
                       for c, t in CLEAN_CATEGORY_TITLE.items())
        body = ('<header><p class="brand">GLOBALGRID2050 / EXPLORE CODE</p><p class="crumbs">Part of: <a href="index.html">'
                'Explore Code</a> / Set aside</p><h1>Set aside (%d), with reasons</h1><p class="syn">These files are left out '
                'of the topic and repository lists so the main view shows authored, unique code. Nothing was deleted: each '
                'file keeps its section page, which says why it was set aside and shows the evidence. They are candidates '
                'for review by a person.</p><p class="k">%s%s</p></header>'
                '<nav><a href="index.html">All topics</a><a href="search.html">Search</a></nav><main>'
                '<h2>By reason</h2><table><thead><tr><th>Reason</th><th>Category</th><th>Files</th></tr></thead><tbody>%s'
                '</tbody></table><h2>By repository</h2>%s</main>'
                % (len(set_aside), E(clean_info.get('summary') or ''),
                   ' Status: a dry run awaiting owner review.' if clean_info.get('dry_run') else '', rows,
                   ''.join('<h3 id="r-%s"><a href="repos/%s.html">%s</a> (%d)</h3><ul>%s</ul>' % (
                       slug(r), slug(r), E(r), len(fis), ''.join(aside_li(fi) for fi in fis)) for r, fis in sorted(by_r.items()))
                   or '<p>No file in this build is set aside.</p>'))
        site.write('set-aside.html', 'Set aside, with reasons — %s' % SITE,
                   'Files left out of the main Explore Code view (copies, older versions, tool output), each with its reason.',
                   body, 0)

    # Licences, reachability
    pub = sorted(by_repo, key=str.lower)
    for r in pub:
        if metas[r]['license'] == 'none found':
            print('WARNING: %s: no LICENSE file found at the repository root' % r, file=sys.stderr)
    lic_count = collections.Counter(metas[r]['license'] for r in pub)
    n_entry = sum(1 for f in files if f['entry'])
    n_reach = sum(1 for f in files if f['reachable'])
    edge_count = collections.Counter(e[2] for e in edges)
    reach_line = 'Reachability: %d entry points, %d files reachable from them, %d files not reached (candidates for review, never deletion).' % (
        n_entry, n_reach, len(files) - n_reach) + (' Reached means: by a walk over %d resolved references of %d kinds '
                                                   '(imports, page loads, links, estate URLs, workflow and script calls; '
                                                   'comment links are shown as mentions, not followed).'
                                                   % (sum(1 for e in edges if e[2] != 'comment-url'),
                                                      len(edge_count) - ('comment-url' in edge_count)))

    # User journey slices (agentdocs.JOURNEYS, the four journeys named in the owner's brief)
    # The homepage is read from the clone even when its page is left out (very long lines); only link texts and
    # addresses are used, each checked against the non-public digests.
    hp = by_path.get(('globalgrid2050', 'index.html'))
    hp_text = files[hp]['text'] if hp is not None else (
        git(metas['globalgrid2050']['dir'], 'show', 'HEAD:index.html') if metas.get('globalgrid2050', {}).get('dir') else '')
    hp_links = [(t, h) for t, h in agentdocs.homepage_links(hp_text) if not leaks(t) and not leaks(h)]
    resolve_id = lambda u: (resolver.resolve_url(u) or (None,))[0]
    trees = {}

    def other_file(r, p):
        if r not in trees:
            d = metas.get(r, {}).get('dir')
            trees[r] = set(git(d, 'ls-tree', '-r', '--name-only', 'HEAD').split('\n')) if d else set()
        p = p.rstrip('/')
        for c in (p, p + '.md', p + '/index.md', p + '/README.md', p + '.html', p + '/index.html'):
            if c and c in trees[r] and not leaks(c):
                return c
        return ''
    journeys = agentdocs.resolve_journeys(files, list(metas), hp_links, resolve_id, edges, reach_size, imported_by,
                                          resolver.url, other_file)
    # "Start here" per core repository: a homepage launch button into it (its Pages root page first, else the one
    # reaching most files), else its Pages root page, else its published entry point reaching most files, else any
    # entry point reaching most files.
    hp_targets = [j for j in (resolve_id(h) for t, h in agentdocs.homepage_links(hp_text, launch_only=True)
                              if not leaks(t) and not leaks(h)) if j is not None]

    def start_of(r):
        fis = repo_files_all.get(r, [])
        root = by_path.get((r, posixpath.join(resolver.pages_root.get(r, ''), 'index.html')))
        cands = [j for j in hp_targets if files[j]['repo'] == r]
        if cands:
            return max(cands, key=lambda j: (j == root, reach_size.get(j, 0), -j)), 'homepage launch button'
        if root is not None:
            return root, 'Pages root page'
        ents = [i for i in fis if files[i]['entry']]
        pubs = [i for i in ents if files[i]['published']]
        if pubs:
            return max(pubs, key=lambda i: (reach_size.get(i, 0), -i)), 'published entry point reaching most files'
        if ents:
            return max(ents, key=lambda i: (reach_size.get(i, 0), -i)), 'entry point reaching most files'
        return (fis[0], 'first file') if fis else (None, '')
    repo_files_all = collections.defaultdict(list)
    for i, f in enumerate(files):
        repo_files_all[f['repo']].append(i)
    for jn in journeys:
        rows = []
        for k, st in enumerate(jn['steps'], 1):
            notes = ''.join('<p class="k">%s</p>' % E(n) for n in st['notes'])
            if not st['found']:
                rows.append('<h2 id="step-%d">Step %d: %s</h2><p class="flag">Not found in the public estate (no repository, '
                            'homepage launch link or folder name maps this step to code).</p>%s' % (k, k, E(st['label']), notes))
                continue
            def anchor(l):  # repository pages anchor folders that hold files directly: the first at or below
                if not l['folder']:
                    return ''
                ds = sorted({posixpath.dirname(files[i]['path']) for i in repo_files_all[l['repo']]
                             if files[i]['path'].startswith(l['folder'] + '/')})
                return '#d-%s' % slug(ds[0]) if ds else ''
            locs = ''.join('<li><a href="../repos/%s.html%s">%s%s</a> · found by %s: %s · %d files</li>' % (
                slug(l['repo']), anchor(l), E(l['repo']),
                ('/' + E(l['folder'])) if l['folder'] else '', E(l['evidence']), E(l['detail']), l['files'])
                for l in st['locations'])
            ents = ''.join('<li>%s %s · %s%s</li>' % (flink(i, '../'), badge(files[i]['role']), E(files[i]['repo']),
                                                      (' · published at <a href="%s">%s</a>' % (E(files[i]['published']), E(files[i]['published'])))
                                                      if files[i]['published'] else '') for i in st['entry_files'] if main_view(i))
            keys = ''.join('<li>%s · used by %d files</li>' % (flink(i, '../'), len(imported_by[i])) for i in st['key_files']
                           if main_view(i))
            rows.append('<h2 id="step-%d">Step %d: %s</h2><ul>%s</ul>%s<h3>Entry points</h3><ul>%s</ul>%s' % (
                k, k, E(st['label']), locs, notes, ents or '<li>none found</li>',
                ('<h3>Most-used files</h3><ul>%s</ul>' % keys) if keys else ''))
        lk = ''.join('<li>%s</li>' % E(agentdocs.link_sentence(p, files)) for p in jn['links'])
        body = ('<header><p class="brand">GLOBALGRID2050 / EXPLORE CODE / JOURNEYS</p><p class="crumbs">Part of: '
                '<a href="../index.html">Explore Code</a> / User journey slices</p><h1>%s</h1><p class="syn">A cross-repository '
                'workflow %s: %s. Each step is mapped to public code by fixed rules (repository name, a GlobalGrid2050 '
                'homepage launch link, or folder name); links between steps are the resolved references the build found. '
                'A step or link that is not found is said plainly, never filled in.</p></header>'
                '<nav><a href="../index.html">All topics</a>%s<a href="../%s">Text for agents</a></nav>'
                '<main>%s<h2>Links between steps</h2><ul>%s</ul></main>'
                % (E(jn['title']), E(jn['source']), E(' → '.join(s['label'] for s in jn['steps'])),
                   ''.join('<a href="%s.html">Journey %s</a>' % (j2['id'], j2['id'].upper()) for j2 in journeys if j2 is not jn),
                   jn['shard'], ''.join(rows), lk))
        site.write(jn['url'], '%s — %s' % (jn['title'], SITE),
                   '%s: %s, mapped to public GlobalGrid2050 code with evidence.' % (jn['title'], ' → '.join(s['label'] for s in jn['steps'])),
                   body, 1)

    # Index
    total = sum(len(f['lines']) for f in files)
    lefts = ', '.join('%s %s' % (format(v, ','), k) for k, v in sorted(left.items()) if v) or 'nothing'
    def role_strip(k):  # a 6px bar of the topic's file roles, in the visualiser's palette (real counts)
        rc = collections.Counter(f['role'] for fi, f in enumerate(files) if f['topic'] == k and main_view(fi))
        n = sum(rc.values()) or 1
        return '<span class="strip" aria-hidden="true">%s</span>' % ''.join(
            '<i style="width:%.1f%%;background:%s"></i>' % (100.0 * rc[rk] / n, c) for rk, t, c in ROLES if rc[rk])
    tlist = ''.join('<li><a class="t" href="topics/%s.html">%s</a>%s<span class="n">%d sections</span>%s</li>' % (
        k, E(t), E(d), sum(1 for m in section_meta if m['topic'] == k), role_strip(k)) for k, t, d, _ in TOPIC_RX
        if any(m['topic'] == k for m in section_meta))
    def repo_line(r):
        rt = repo_title(r)
        return '<li><a href="repos/%s.html"><strong>%s</strong></a>%s · %s · %d sections %s</li>' % (
            slug(r), E(rt), (' <span class="k">(%s)</span>' % E(r)) if rt != r else '', E(descriptor(r)),
            len(by_repo[r]), ('<span class="k">(draft description awaiting owner approval)</span>'
                              if descriptor_src(r) == 'core_hook_draft' else ''))
    core = [r for r in CORE_REPOS if r in by_repo]
    support = collections.defaultdict(list)
    for r in pub:
        if r not in core:
            support[collections.Counter(files[fi]['topic'] for fi in repo_files[r]).most_common(1)[0][0]].append(r)
    rlist = ('<h2>Core production engines</h2><p class="k">Chosen by the owner.</p><ul>%s</ul>'
             '<details><summary>Supporting data, simulation and R&amp;D</summary>%s</details>'
             % (''.join(repo_line(r) for r in core),
                ''.join('<h3>%s</h3><ul>%s</ul>' % (E(topic_title[k]), ''.join(repo_line(r) for r in support[k]))
                        for k, *_x in TOPICS if support.get(k))))
    azlist = ('<details><summary>All repositories A–Z (%d)</summary><ul class="links">%s</ul></details>'
              % (len(pub), ''.join('<li><a href="repos/%s.html">%s</a> (%d sections)</li>' % (slug(r), E(r), len(by_repo[r])) for r in pub)))
    jlist = ('<h2>User journey slices</h2><p class="k">The four cross-repository workflows named in Ventus Ltd\'s brief, '
             'mapped to public code with evidence; steps or links not found are said plainly.</p><ul>%s</ul>'
             '<h2>For AI agents</h2><p><a href="llms.txt">llms.txt</a> (routing index and agent navigation protocol), '
             'per-topic, per-engine and per-journey text shards listed there, <a href="build_graph.json">build_graph.json</a> '
             '(@@GRAPHSIZE@@; every file with its edges, domain stage, users, data contracts and canonical status) and the Parquet tables '
             'in <a href="search.html">search</a>.</p>'
             % ''.join('<li><a href="%s">%s</a>: %s (<a href="%s">text</a>)</li>' % (
                 jn['url'], E(jn['title']), E(' → '.join(s['label'] + ('' if s['found'] else ' (not found)') for s in jn['steps'])),
                 jn['shard']) for jn in journeys))
    role_n = collections.Counter(f['role'] for f in files)
    legend = ''.join('<li>%s %s: %d files</li>' % (badge(k), E(t), role_n[k]) for k, t, c in ROLES)
    ltable = ''.join('<tr><td><a href="repos/%s.html">%s</a></td><td>%s</td><td>%s</td><td>%s</td></tr>' % (
        slug(r), E(r), E(metas[r]['license']) if metas[r]['license_file'] else '<span class="flag">none found</span>',
        E(metas[r]['license_file'] or '—'), 'yes' if metas[r]['citation'] else 'no') for r in pub)
    j0 = journeys[0]['url'] if journeys else None
    play = ''.join([
        '<li><a class="t" href="visual/index.html">Estate galaxy</a>Fly through every file as a map of stars; tap one to '
        'read what it does.<span class="n">Visualiser</span></li>',
        '<li hidden data-probe="chess/index.html"><a class="t">Code chess</a>Groups of related code play chess, every move '
        'explained.<span class="n">Game</span></li>',
        '<li hidden data-probe="kuiper/index.html"><a class="t">Kuiper for each repository</a>Each repository as its own '
        'small solar system of files.<span class="n">Worlds</span></li>',
        ('<li><a class="t" href="%s">Journeys</a>Follow real work across repositories, step by step: %s.<span class="n">%d '
         'journeys</span></li>' % (j0, E(journeys[0]['title']), len(journeys))) if j0 else '',
        '<li><a class="t" id="surprise" href="%s">Surprise me</a>Open a random page of the code estate.<span class="n">'
        '%d sections</span></li>' % (sname(1), len(sections)),
        '<li hidden data-probe="more.html"><a class="t">Explore more</a>Every extra experience in one place.'
        '<span class="n">Hub</span></li>'])
    aside_link = ('<p class="k">Clean view: copies, older versions and tool output are left out of these lists. '
                  '<a href="set-aside.html">Set aside (%d), with reasons</a>.</p>' % len(set_aside)) if clean_info else ''
    about = ('<h2>About this estate</h2><p>Ventus Ltd states its purpose for Explore Code as follows. It is a plain-English '
             'translation layer and dependency map, so that people who do not use GitHub (energy professionals, planners, '
             'landowners, procurement teams) and AI agents can read, search and understand this domain engineering code '
             'without cloning each repository. Ventus Ltd describes the code volume as the byproduct of rapid, ground-up '
             'application iteration and fine-tuning, and this map as the first step before dead-code distillation and '
             'functional visualisation.</p><p>In Ventus Ltd\'s words, modelling the full upstream TSO/DNO network '
             '(gridatlas, 132kV, data-interconnectors) provides upstream engineering foresight, while its commercial '
             'execution is deliberately bounded to HV materials procurement and inside-the-fence electrical and civil design '
             'below 33kV. Its on-road and off-road SatNav work (satnav, lidar, soil) starts from the observation, as Ventus '
             'Ltd puts it, that about 92% of the UK landmass is off-road private land while roads and homes cover about 8%, '
             'and that standard SatNavs fail at the farm gate: using open utility coordinates (for example UK Power Networks\' '
             'secondary 11kV/400V substations), it aims to bridge the public road network to exact off-road coordinates, '
             'access gates, terrain slope (LiDAR), ground-bearing limits (soil) and overhead or buried electrical hazards.</p>')
    body = ('<header><p class="brand">GLOBALGRID2050</p><p class="crumbs">Part of: <a href="https://globalgrid2050.com/">'
            'GlobalGrid2050</a></p><h1>Explore Code</h1><section class="playrow" aria-label="Play"><h2>Play</h2>'
            '<ul class="cards play">%s</ul></section><p>The open code behind GlobalGrid2050, built '
            'for the energy transition, explained in plain English and readable by people and AI agents. %s lines of unique '
            'code from %d public repositories in %d sections, grouped by what the code is for. Each file carries a plain-English '
            'title and synopsis, what it achieves, why it matters (what uses it), and a link to the exact lines on GitHub.</p>'
            '<p class="syn">Ventus Ltd states that this estate is for engineers, developers, procurement teams, landowners and '
            'planners, and AI agents who need to read the code without cloning it. In its words, it bridges upstream GB grid '
            'topology (the TSO/DNO network) with sub-33kV inside-the-fence site design, HV materials procurement, and on-road '
            'and off-road field SatNav.</p>'
            '<details class="k"><summary>About this build</summary><p class="k">Generator %s. Cut %s. Left out: %s. %s%s '
            'Companion to <a href="https://globalgrid2050.com/kuiper/">Kuiper</a>.</p></details></header>'
            '<nav aria-label="Site"><a href="https://globalgrid2050.com/">GlobalGrid2050</a><a href="visual/index.html">Visualiser</a>'
            '<a href="search.html">Search all code</a><a href="words/index.html">Words A–Z</a>'
            '<a data-probe="more.html" hidden>Explore more</a><a href="llms.txt">llms.txt</a></nav>'
            '<main><h2>Start with a topic</h2><ul class="cards">%s</ul>%s%s%s<details><summary>Colours: what each file does</summary>'
            '<p>Each file block on a '
            'section page has a coloured stripe and badge for its function, decided by fixed rules from its names, '
            'definitions and calls. The State line names where "What it achieves" came from: comment (the file\'s own '
            'comment), code (a VEDIC meaning matched by function name), readme (file name plus a README sentence naming it) '
            'or name (the file name alone).</p><ul class="links">%s</ul></details><details><summary>About this estate</summary>%s</details>'
            '<details><summary>Licences</summary><p>Detected from each repository\'s own LICENSE file; code is under each '
            'repository\'s own licence.</p><table><thead><tr><th>Repository</th><th>Licence</th><th>File</th><th>CITATION.cff</th></tr></thead>'
            '<tbody>%s</tbody></table></details>%s</main><script>%s</script>'
            % (play, format(total, ','), len(by_repo), len(sections), GENERATOR_VERSION, stamp, E(lefts), E(reach_line),
               (' Clean view: %d files set aside from the lists (<a href="set-aside.html">with reasons</a>).' % len(set_aside))
               if clean_info else '', tlist, aside_link, rlist, jlist, legend,
               about.replace('<h2>About this estate</h2>', ''), ltable, azlist, PLAY_JS % len(sections)))
    ld = {'@context': 'https://schema.org', '@graph': [
        {'@type': 'WebSite', '@id': base + '#site', 'name': SITE, 'url': base, 'publisher': ventus_org(), 'author': ventus_org(),
         'potentialAction': {'@type': 'SearchAction', 'target': base + 'search.html'}},
        {'@type': 'CollectionPage', 'name': 'Explore Code', 'url': base + 'index.html', 'isPartOf': {'@id': base + '#site'},
         'about': 'Open energy-transition code from public Ventusltd repositories', 'author': ventus_org(),
         'hasPart': [{'@type': 'CollectionPage', 'name': t, 'url': base + 'topics/%s.html' % k} for k, t, d, _ in TOPIC_RX
                     if any(m['topic'] == k for m in section_meta)]}]}
    index_page = (body, ld)  # written after build_graph.json, whose size it names

    # Tables
    write_parquet(out, files, sections, section_meta, words, code_rows, stamp, topic_title)

    # Search (DuckDB in the browser over code.parquet)
    search_js = r"""
const VER='1.29.0',EXTV='v1.1.1',CDN='https://cdn.jsdelivr.net/npm/@duckdb/duckdb-wasm@'+VER+'/dist/',LOCAL=new URL(DUCK,location.href).href;let conn=null,loading=null;
const st=document.getElementById('st'),res=document.getElementById('res'),q=document.getElementById('q'),bar=document.getElementById('bar'),fb=document.getElementById('fb');
const say=t=>{st.textContent=t};const prog=p=>{bar.hidden=false;bar.firstChild.style.width=Math.max(2,Math.min(100,p))+'%'};
const mb=b=>(b/1048576).toFixed(1)+' MB';
async function have(u){try{const r=await fetch(u,{method:'HEAD',cache:'no-cache'});return r.ok}catch(e){return false}}
async function engine(){
 const local=await have(LOCAL+'VERSION');let duckdb,bundles;
 if(local){duckdb=await import(LOCAL+'duckdb-browser.mjs');const m=await have(LOCAL+'duckdb-mvp.wasm');
  bundles={eh:{mainModule:LOCAL+'duckdb-eh.wasm',mainWorker:LOCAL+'duckdb-browser-eh.worker.js'},
   mvp:m?{mainModule:LOCAL+'duckdb-mvp.wasm',mainWorker:LOCAL+'duckdb-browser-mvp.worker.js'}:{mainModule:CDN+'duckdb-mvp.wasm',mainWorker:CDN+'duckdb-browser-mvp.worker.js'}}}
 else{duckdb=await import('https://cdn.jsdelivr.net/npm/@duckdb/duckdb-wasm@'+VER+'/+esm');bundles=duckdb.getJsDelivrBundles()}
 const b=await duckdb.selectBundle(bundles);const same=b.mainWorker.startsWith(location.origin);
 const u=same?null:URL.createObjectURL(new Blob([`importScripts(${JSON.stringify(b.mainWorker)});`],{type:'text/javascript'}));
 const d=new duckdb.AsyncDuckDB(new duckdb.ConsoleLogger(duckdb.LogLevel.WARNING),new Worker(u||b.mainWorker));
 await d.instantiate(b.mainModule,b.pthreadWorker,p=>{if(p&&p.bytesTotal){prog(80*p.bytesLoaded/p.bytesTotal);say('Loading the search engine ('+(local?'from this site':'from jsDelivr')+'): '+mb(p.bytesLoaded)+' of '+mb(p.bytesTotal)+'…')}});
 if(u)URL.revokeObjectURL(u);prog(85);const c=await d.connect();
 if(local){const v=b.mainModule.includes('-eh')?'wasm_eh':'wasm_mvp';
  if(await have(LOCAL+'ext/'+EXTV+'/'+v+'/parquet.duckdb_extension.wasm'))await c.query(`SET custom_extension_repository='${LOCAL}ext'`)}
 return c}
function db(){if(conn)return Promise.resolve(conn);if(!loading){say('Loading the search engine…');prog(2);loading=engine().then(c=>conn=c,e=>{loading=null;throw e})}return loading}
const esc=s=>String(s).replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
async function run(e){e&&e.preventDefault();const t=q.value.trim();if(t.length<3){say('Type at least 3 characters.');return}
 fb.hidden=true;history.replaceState(null,'','?q='+encodeURIComponent(t));
 try{const c=await db();say('Searching '+NLINES+' lines…');prog(90);const url=new URL('data/code.parquet',location.href).href;
 const s=await c.prepare(`SELECT repo,path,line,text,section,block FROM read_parquet('${url}') WHERE text ILIKE ? LIMIT 300`);
 const r=(await s.query('%'+t+'%')).toArray();await s.close();prog(100);bar.hidden=true;
 res.innerHTML=r.map(x=>`<li><a href="s/${String(x.section).padStart(WIDTH,'0')}.html#f${x.block}">${esc(x.repo)} / ${esc(x.path)}:${x.line}</a><pre><code>${esc(String(x.text).slice(0,300))}</code></pre></li>`).join('');
 say(r.length+(r.length==300?'+':'')+' matches for “'+t+'”')}
 catch(err){bar.hidden=true;console.warn(err);say('Search could not load (the network is slow or offline, or a download was blocked).');fb.hidden=false}}
document.getElementById('f').onsubmit=run;
document.querySelectorAll('[data-q]').forEach(b=>b.addEventListener('click',()=>{q.value=b.dataset.q;run()}));
const q0=new URLSearchParams(location.search).get('q');if(q0){q.value=q0;run()}
"""
    pq = os.path.join(out, 'data', 'code.parquet')
    pq_note = '%.0f MB' % (os.path.getsize(pq) / 1048576.0) if os.path.exists(pq) else 'about 16 MB'
    chips = ''.join('<li><button type="button" data-q="%s">%s</button></li>' % (E(w), E(w))
                    for w in ('haversine', 'derating', 'substation', '33kV'))
    body = ('<header><p class="brand">GLOBALGRID2050 / EXPLORE CODE</p><p class="crumbs">Part of: <a href="index.html">Explore Code</a> / Search</p>'
            '<h1>Search all code</h1><p>Searches every line of the %s with DuckDB running in your browser, reading the '
            '<a href="data/code.parquet">code.parquet</a> table.</p>'
            '<p class="k">The first search downloads the search engine (about 36 MB, served compressed where the browser '
            'allows) and the code table (%s), so it is best on Wi-Fi; later searches reuse them. Browsing by '
            '<a href="index.html">topic</a> or <a href="words/index.html">Words A–Z</a> needs no download.</p></header>'
            '<nav aria-label="Site"><a href="index.html">All topics</a><a href="words/index.html">Words A–Z</a></nav><main>'
            '<form id="f" role="search"><label for="q">Search all code</label> <input id="q" type="search" name="q" '
            'placeholder="e.g. haversine, derating, substation" autocomplete="off" enterkeyhint="search"> '
            '<button>Search</button></form><ul class="chips" aria-label="Examples">%s</ul>'
            '<div id="bar" class="bar" hidden><i></i></div><p id="st" class="k" role="status" aria-live="polite"></p>'
            '<div id="fb" class="aside" hidden><p>Search could not load here. Try a <a href="index.html">topic</a> or '
            '<a href="words/index.html">Words A–Z</a>; every file is also listed on its <a href="index.html">repository page</a>.</p></div>'
            '<ol id="res"></ol><noscript>Search needs JavaScript. '
            'Browse by <a href="index.html">topic</a> or <a href="words/index.html">word</a> instead.</noscript></main>'
            '<script type="module">const NLINES=%s,WIDTH=%d,DUCK=%s;%s</script>'
            % (format(total, ',') + ' lines', pq_note, chips, json.dumps(format(total, ',')), width, json.dumps(DUCKDB_PATH), search_js))
    site.write('search.html', 'Search the GlobalGrid2050 code — %s' % SITE, 'Full-text search over every line of the code estate.', body, 0)
    if duckdb_dir:  # optional: place a prepared vendor folder (see DUCKDB_FILES); missing -> warning, CDN fallback stays
        dd = os.path.join(out, DUCKDB_PATH)
        have = [n for n in DUCKDB_FILES if os.path.isfile(os.path.join(duckdb_dir, n))]
        if 'duckdb-browser.mjs' in have and 'duckdb-eh.wasm' in have and 'duckdb-browser-eh.worker.js' in have and 'VERSION' in have:
            os.makedirs(dd, exist_ok=True)
            for n in have + [e for e in DUCKDB_EXT if os.path.isfile(os.path.join(duckdb_dir, e))]:
                os.makedirs(os.path.dirname(os.path.join(dd, n)), exist_ok=True)
                shutil.copyfile(os.path.join(duckdb_dir, n), os.path.join(dd, n))
        else:
            print('WARNING: --duckdb-dir %s lacks %s; search.html will use jsDelivr' % (
                duckdb_dir, ', '.join(n for n in DUCKDB_FILES[:3] + ('VERSION',) if n not in have)), file=sys.stderr)


    # Machine-readable graph (GRAPH-CONTRACT.md)
    def gh_url(i):
        f = files[i]
        return 'https://github.com/Ventusltd/%s/blob/%s/%s#L1-L%d' % (f['repo'], f['commit'], urllib.parse.quote(f['path']),
                                                                    max(1, len(f['lines'])))

    def vedic_lines(f):
        return ['%s (%s): %s%s. %s -> %s' % (e['word'], e.get('gg_id', ''), e.get('estate_group') or '',
                                             (' · ' + e['discipline']) if e.get('discipline') else '',
                                             ', '.join(e.get('inputs') or []), e.get('output') or '') for e in f['vedic'][:3]]
    gfiles = [{
        'id': i, 'repo': f['repo'], 'path': f['path'],
        'folder_hierarchy': [f['repo']] + f['path'].split('/')[:-1],
        'lang': LANG.get(ext(f['path']), ext(f['path']).upper() or 'text'), 'lines': len(f['lines']),
        'section': first_section[i][0], 'block': first_section[i][1], 'title': f['title'],
        'synopsis': f['synopsis'], 'achieves': f['achieves'], 'achieves_provenance': f['achieves_src'], 'description_note': f.get('desc_note', ''), 'why': f['why'], 'context': f['context'],
        'essay_status': f['essay_status'], 'stage': f['stage'], 'role': f['role'], 'pattern': f['pattern'],
        'entry': f['entry'], 'reachable': f['reachable'], 'kind': f['kind'], 'name_words': f['name_words'],
        'imports': f['links'], 'edge_kinds': f['link_kinds'], 'imports_external': f['ext_imports'],
        'dependents': imported_by.get(i, []), 'mentions': f['mentions'], 'mentioned_by': mentioned_by.get(i, []),
        'defines': [n for n, k, ln in f['defs'] if not leaks(n)][:30], 'pure': not f['effects'],
        'published': f['published'], 'domain_stage': f['dstage'], 'domain_stage_evidence': f['dstage_ev'],
        'commercial_user': f['users'], 'data_contracts': f['dc'], 'canonical_status': f['canon'],
        'duplicate_of': f['dup_of'], 'four_part': agentdocs.compact_four_part({k: v for k, v in f['four'].items() if v}, f['dstage']),
        'signatures': f['sigs'], 'reached_from_entries': len(reached_by.get(i, [])),
    } for i, f in enumerate(files)]
    if clean_info:  # additive (clean/CONTRACT.md section 6): main | <category>
        for i, g in enumerate(gfiles):
            g['clean_status'] = set_aside[i]['category'] if i in set_aside else 'main'
    graph = {
        'schema': 'explore-build-graph-v1', 'rules_version': agentdocs.RULES_VERSION, 'cut': stamp, 'base': base,
        'generator_version': GENERATOR_VERSION,
        'roles': [{'id': k, 'title': t, 'colour': c} for k, t, c in ROLES],
        'domain_stages': [{'id': k, 'title': t, 'meaning': d} for k, t, d in agentdocs.DOMAIN_STAGES],
        'commercial_users': agentdocs.USERS, 'canonical_statuses': agentdocs.CANONICAL,
        'provenance_confidence': agentdocs.CONFIDENCE,
        'topics': [{'id': k, 'title': t, 'sections': sum(1 for m in section_meta if m['topic'] == k)} for k, t, d, _ in TOPIC_RX
                   if any(m['topic'] == k for m in section_meta)],
        'repos': [{'repo': r, 'commit': metas[r]['commit'], 'license': metas[r]['license'],
                   'license_file': metas[r]['license_file'], 'citation': metas[r]['citation'],
                   'readme_summary': metas[r]['readmes'].get('', ('', ''))[1] if root_ok(r) else '',
                   'descriptor': descriptor(r, 400), 'descriptor_provenance': descriptor_src(r),
                   **({'descriptor_status': CORE_HOOKS_STATUS, 'descriptor_source': CORE_HOOKS_SOURCE} if hook_of(r) else {}),
                   'core': r in CORE_REPOS} for r in pub],
        'sections': [{'section': m['section'], 'url': sname(m['section']), 'topic': m['topic'], 'repos': m['repos'],
                      'lines': m['lines'], 'title': m['title']} for m in section_meta],
        'files': gfiles,
        'edge_kinds': [{'id': k, 'verb': v, 'label': l, 'evidence': d} for k, v, l, d in EDGE_KINDS],
        'edges': edges,
        'journeys': journeys,
    }
    if clean_info:
        graph['clean'] = {k: clean_info[k] for k in ('graph_cut', 'dry_run', 'summary', 'set_aside', 'stale', 'not_in_build')}
        graph['clean']['page'] = 'set-aside.html'
    with open(os.path.join(out, 'build_graph.json'), 'w', encoding='utf-8') as fh:
        json.dump(graph, fh, ensure_ascii=False, separators=(',', ':'))
    gz = os.path.getsize(os.path.join(out, 'build_graph.json'))
    site.write('index.html', 'Explore Code: GlobalGrid2050 open energy-transition code, explained',
               'The open code behind GlobalGrid2050 in plain English: cables, solar and storage, grid networks, maps, '
               'markets and AI agents, readable by people and AI.',
               index_page[0].replace('@@GRAPHSIZE@@', '%.1f MB' % (gz / 1048576.0) if gz >= 1048576 else '%d KB' % max(1, gz // 1024)),
               0, index_page[1])

    # Agent text shards (agentdocs.py): per topic, per core repository, per journey; llms-full.txt if small enough
    def block(i):
        g = dict(gfiles[i], vedic=vedic_lines(files[i]), four=files[i]['four'])
        if files[i]['dup_of'] is not None:
            d = files[files[i]['dup_of']]
            g['duplicate_of_label'] = '%s/%s' % (d['repo'], d['path'])
        kinds = collections.Counter(files[i]['link_kinds'])
        g['edges_summary'] = 'uses %d estate file%s%s; used by %d; mentioned by %d' % (
            len(files[i]['links']), '' if len(files[i]['links']) == 1 else 's',
            (' (%s)' % ', '.join('%s %d' % kv for kv in kinds.most_common())) if kinds else '',
            len(imported_by.get(i, [])), len(mentioned_by.get(i, [])))
        return agentdocs.shard_block(g, base, '%s#f%d' % (sname(first_section[i][0]), first_section[i][1]), gh_url(i))
    blocks = [block(i) for i in range(len(files))]
    legend_txt = ('Attribution: %s. Cut %s. Generated deterministically from the public Ventusltd repositories by '