GLOBALGRID2050 / EXPLORE CODE

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

Test Build

A test in the explore folder of Cosmic that checks Build and Agentdocs, using haversine using data from UK Power Networks open data and the GlobalGrid2050 and delta repositories.

700 lines of Python from cosmic, in 1 file. Topic: Kuiper, cosmos and drawing engines. Section 1138 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. Test Build test · cosmic / tools/explore/test_build.py lines 1–700

Test Build

A test in the explore folder of Cosmic that checks Build and Agentdocs, using haversine using data from UK Power Networks open data and the GlobalGrid2050 and delta repositories.

testcosmic / tools/explore/test_build.py · lines 1–700 of 927 · Entry point · pattern tearDownClass (shared by 3 files)

What it does
It tests A roads and overhead lines (OHL). Defines 64 functions or classes, including read, make_repo, Links, __init__, handle_starttag. Uses libraries contextlib, html.parser, io, json, os. 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: A roads, overhead lines (OHL), 132kV, 33kV.
Inputs & outputs
In: data source: UK Power Networks open data; data source: globalgrid2050 data; data source: delta data; GeoJSON file 132kv_ohl.geojson; JSON file build_graph.json; JSON file missing.json; DuckDB queries; command-line arguments. Out: JSON file; interactive map. Voltage levels named: 132kV, 33kV.
Downstream impact
It is itself an entry point (test); no other file was found loading it.
What it achieves
It makes repo (`make_repo`), checks links (`check_links`) and builds test (`BuildTest`). Tests for `tools/explore/build.py` (unittest, no network). Its code works with 132 kV and 33 kV. It reads `data/132kv_ohl.geojson`.
Why it matters
Guards the behaviour of Build and Agentdocs.
Application
cosmic · tools/explore · test
Uses
Build (import), Agentdocs (import), contextlib, html.parser, io, json, os, re, subprocess, sys
Used by
none found
Produces
read, make_repo, Links, parse, check_links, BuildTest, EdgeTest, SwarmV2Test
Defines here
read, make_repo, Links, __init__, handle_starttag, handle_data, handle_endtag, parse, check_links, ids, BuildTest, setUpClass, tearDownClass, f, section_html, test_titles, test_kind_and_name_words, test_achieves_from_name, test_achieves_from_readme, test_readme_context, test_drafts_never_rendered, test_readme_pick_rejects_process_records, test_labels_framed_as_rules, test_essay_promoted, test_licences, test_synopsis, test_graph_contract, test_agent_ingestion_fields, test_repo_page_tldr_and_folds, test_index_play_row_first
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/test_build.py:1-700 · blob dbf5152d60aa5a85c16ba8b93eb9407c76c640b8 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, process, storage · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
"""Tests for tools/explore/build.py (unittest, no network).

Builds two tiny git repositories (remotes https://github.com/Ventusltd/<name>) and an essays folder in a
temporary directory, runs build() into a temporary output folder and checks titles, README context,
essays, licences, synopses, build_graph.json against GRAPH-CONTRACT.md, sitemaps, JSON-LD and links.

Also a link checker for a real build:  python tools/explore/test_build.py --check-links /tmp/site/explore-code
"""
import contextlib
import html.parser
import io
import json
import os
import re
import subprocess
import sys
import tempfile
import unittest
import urllib.parse

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import build  # noqa: E402

MIT = """MIT License

Copyright (c) 2026 Ventus Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy of this software...
"""

ALPHA = {
    'LICENSE': MIT,
    'README.md': '# Alpha\n\n[![ci](https://img.shields.io/x.svg)](https://example.org)\n\n'
                 'Alpha maps the 132kV overhead line network for grid engineers and planners.\n\n## More\n\n- a\n- b\n',
    '132kV/README.md': ('# 132kV\n\nThis folder holds the coordinates of the 132kV overhead lines used by route checks.\n'
                        '\nThe file ohl_coordinates.py returns the coordinates of each overhead line as pairs.\n'),
    '132kV/ohl_coordinates.py': 'def coords_of(line):\n    return [(p[0], p[1]) for p in line]\n',
    '132kV/route_check.py': ('from ohl_coordinates import coords_of\n\n\ndef check(line):\n    return len(coords_of(line))\n\n\n'
                             'if __name__ == "__main__":\n    print(check([]))\n'),
    'map/index.html': ('<!doctype html><html><head><title>OHL map</title><script src="app.js"></script></head>'
                       '<body><h1>132kV network map</h1><div id="map"></div></body></html>\n'),
    'map/app.js': ("const map = new maplibregl.Map({container: 'map'});\n"
                   "fetch('data/132kv_ohl.geojson').then(r => r.json());\n"
                   "fetch('https://ukpowernetworks.opendatasoft.com/api/records/1.0/search/?dataset=x');\n"
                   "map.addLayer({id: 'a_roads', type: 'line', source: 'roads'});\n"
                   "document.getElementById('map').innerHTML = '';\n"
                   "function drawLines() { return 1; }\n"),
    'employers_requirments_large_scale_solar/print/index.html': '<!doctype html><html><body><p>x</p></body></html>\n',
    'apps/substation-finder/Si/202609060537-substation-intelligence.js': (
        'function dockLayers(a) {\n  return a;\n}\nfunction restoreLayers(b) {\n  return b;\n}\n'),
    'orphan.js': 'function lonelyHelper(x) {\n  return x * 2;\n}\n',
    '.github/workflows/ci.yml': 'name: CI\non: push\njobs:\n  t:\n    runs-on: ubuntu-latest\n    steps:\n      - run: echo ok\n',
    'tests/test_alpha.py': 'def test_one():\n    assert 1 + 1 == 2\n',
}
BETA = {
    'README.md': '# Beta\n\nBeta keeps a small list of substations for testing the explorer build.\n',
    'lib/util.js': "export function addOne(x) {\n  return x + 1;\n}\n",
    'main.js': "import { addOne } from './lib/util.js';\nconsole.log(addOne(1));\n",
}
# --- Edge fixtures: one small estate with every edge kind (EdgeTest)
GG = {  # stands for globalgrid2050 (CNAME globalgrid2050.com)
    'CNAME': 'globalgrid2050.com\n',
    'index.html': ('<!doctype html><html><head><title>Home</title>\n'
                   '<script type="importmap">{"imports": {"lib": "./js/lib/mapped.js"}}</script>\n'
                   '<script src="js/app.js"></script>\n<script src="js/dupe.js"></script>\n'
                   '<link rel="stylesheet" href="css/site.css">\n<link rel="modulepreload" href="js/pre.mjs">\n'
                   '</head><body><iframe src="embed/frame.html"></iframe>\n'
                   '<a href="tools/">Tools</a> <a href="about.html">About</a>\n'
                   "<script>const w = new Worker('js/worker.js'); fetch('./partials/menu.html');</script>\n"
                   '</body></html>\n'),
    'about.html': '<!doctype html><html><body><p>About</p></body></html>\n',
    'tools/index.html': '<!doctype html><html><body><p>Tools</p></body></html>\n',
    'embed/frame.html': '<!doctype html><html><body><p>Frame</p></body></html>\n',
    'partials/menu.html': '<nav>menu</nav>\n',
    'js/app.js': ("const lazy = () => import('./lazy.js');\n"
                  "const glue = new URL('./wasm-glue.js', import.meta.url);\n"
                  "const c = require('./cjs.js');\n"),
    'js/lazy.js': 'export function lazyThing() {\n  return 1;\n}\n',
    'js/wasm-glue.js': 'export function glueThing() {\n  return 2;\n}\n',
    'js/cjs.js': 'module.exports = function cjsThing() { return 3; };\n',
    'js/pre.mjs': 'export const preThing = 4;\n',
    'js/lib/mapped.js': 'export const mappedThing = 5;\n',
    'js/worker.js': 'self.onmessage = (e) => postMessage(e.data);\n',
    'js/shared.js': 'export function sharedThing() {\n  return 6;\n}\n',
    'js/cdn_target.js': 'export const cdnThing = 7;\n',
    'js/blob_target.js': 'export const blobThing = 8;\n',
    'js/dupe.js': 'export const dupeThing = 99; // same blob as delta/vendorish/dupe.js\n',
    'py/raw_target.py': 'def raw_thing():\n    return 9\n',
    'py/doc_only.py': 'def doc_only():\n    return 10\n',
    'js/only_mentioned.js': 'export function onlyMentioned() {\n  return 11;\n}\n',
    'js/both.js': 'export const bothThing = 12;\n',
    'css/site.css': '@import "base.css";\nbody { color: #fff; }\n',
    'css/base.css': 'html { margin: 0; }\n',
    'pkg/__init__.py': '',
    'pkg/core.py': 'from . import helpers\nfrom .model import Thing\n\n\ndef core():\n    return helpers.h(), Thing\n',
    'pkg/helpers.py': 'def h():\n    return 1\n',
    'pkg/model.py': 'class Thing:\n    pass\n',
    'pkg/cli.py': 'from .core import core\n\n\ndef main():\n    return core()\n',
    'lib_py/sibling_lib.py': 'def sib():\n    return 1\n',
    'tools/run.py': ('import os\nimport sys\n\nHERE = os.path.dirname(os.path.abspath(__file__))\n'
                     "sys.path.insert(0, os.path.join(HERE, '..', 'lib_py'))\nimport sibling_lib  # noqa: E402\n\n"
                     'sibling_lib.sib()\n'),
    'tools/node_task.mjs': 'console.log("task");\n',
    'scripts/build.sh': 'set -e\npython3 scripts/gen.py --out x\n',
    'scripts/gen.py': 'def gen():\n    return 1\n',
    'releases/202601010000-widget.js': 'function widgetOld() {\n  return 1;\n}\n',
    'releases/202602010000-widget.js': 'function widgetNew() {\n  return 2;\n}\n',
    '.github/workflows/ci.yml': ('name: CI\non: push\njobs:\n  t:\n    runs-on: ubuntu-latest\n    steps:\n'
                                 '      - run: python tools/run.py\n      - run: bash scripts/build.sh\n'
                                 '      - run: |\n          node tools/node_task.mjs\n          python -m pkg.cli\n'
                                 '      - run: pip install pytest\n      - run: python -m pytest -q checks/\n'
                                 '      - run: node --test web/\n      - run: node cartridges/*/proof.mjs\n'
                                 '      - env:\n          VERIFIER: tools/verify.mjs\n        run: node "$VERIFIER"\n'
                                 '      - run: python -m py_compile tools/compiled_only.py\n'
                                 '      - run: bash scripts/suite/run.sh\n'),
    'checks/test_unit.py': 'def test_unit():\n    assert True\n',
    'checks/helper_tools.py': 'def helper():\n    return 1\n',
    'web/thing.test.mjs': 'import test from "node:test";\ntest("x", () => {});\n',
    'web/thing.mjs': 'export const thing = 1;\n',
    'cartridges/a/proof.mjs': 'console.log("a");\n',
    'cartridges/b/proof.mjs': 'console.log("b");\n',
    'tools/verify.mjs': 'console.log("verify");\n',
    'tools/compiled_only.py': 'X = 1\n',
    'scripts/suite/run.sh': 'HERE="$(cd "$(dirname "$0")" && pwd)"\nnode "$HERE/check.mjs"\n',
    'scripts/suite/check.mjs': ("import { spawnSync } from 'node:child_process';\n"
                                "const STEPS = [['one', 'scripts/suite/step_one.py']];\n"
                                "for (const [n, p] of STEPS) spawnSync('python3', [p]);\n"),
    'scripts/suite/step_one.py': 'print(1)\n',
    'dead.js': 'function nobodyCallsMe() {\n  return 0;\n}\n',
    'dead.py': 'def nobody_calls_me():\n    return 0\n',
}
DELTA = {
    'page.html': ('<!doctype html><html><head><script src="https://globalgrid2050.com/js/shared.js"></script>'
                  '<script src="loader.js"></script><script src="notes.js"></script></head><body><p>Delta</p></body></html>\n'),
    'loader.js': ("const A = 'https://raw.githubusercontent.com/Ventusltd/globalgrid2050/main/py/raw_target.py';\n"
                  "const B = 'https://cdn.jsdelivr.net/gh/Ventusltd/globalgrid2050@main/js/cdn_target.js';\n"
                  "const C = 'https://github.com/Ventusltd/globalgrid2050/blob/main/js/blob_target.js';\n"
                  "const D = 'https://ventusltd.github.io/delta/sub/';\n"
                  "const E = 'https://globalgrid2050.com/releases/202601010000-widget.js';\n"
                  "const F = 'https://ventusltd.github.io/delta/${name}.js';\n"),
    'sub/index.html': '<!doctype html><html><body><p>Sub</p></body></html>\n',
    'notes.js': ("// Source: https://github.com/Ventusltd/globalgrid2050/blob/main/js/only_mentioned.js#L1-L3\n"
                 "/* also https://globalgrid2050.com/js/both.js */\n"
                 "const both = 'https://globalgrid2050.com/js/both.js';\n"),
    'notes.py': ('"""Ported from https://raw.githubusercontent.com/Ventusltd/globalgrid2050/main/py/doc_only.py"""\n'
                 '# see https://globalgrid2050.com/py/doc_only.py\n'
                 'def notes():\n    return 1\n'),
    'vendorish/dupe.js': 'export const dupeThing = 99; // same blob as delta/vendorish/dupe.js\n',
}

ESSAY = '---\ntitle: Why the 132kV lines matter\n---\n# Heading in essay\n\nPeople wrote this about **132kV** lines.\n\n- one\n- two\n'


def read(path):
    with open(path, encoding='utf-8') as fh:
        return fh.read()


def make_repo(root, name, files):
    d = os.path.join(root, name)
    for p, text in files.items():
        full = os.path.join(d, p)
        os.makedirs(os.path.dirname(full), exist_ok=True)
        with open(full, 'w') as fh:
            fh.write(text)
    run = lambda *a: subprocess.run(['git', '-C', d] + list(a), check=True, capture_output=True)
    run('init', '-q')
    run('config', 'user.email', 't@example.org')
    run('config', 'user.name', 'T')
    run('add', '-A')
    run('commit', '-qm', 'init')
    run('remote', 'add', 'origin', 'https://github.com/Ventusltd/%s' % name)


class Links(html.parser.HTMLParser):
    def __init__(self):
        super().__init__()
        self.links, self.ids, self.ld = [], set(), []
        self._ld = False

    def handle_starttag(self, tag, attrs):
        a = dict(attrs)
        for k in ('href', 'src'):
            if a.get(k):
                self.links.append(a[k])
        for k in ('id', 'name'):
            if a.get(k) and tag != 'meta':
                self.ids.add(a[k])
        self._ld = tag == 'script' and a.get('type') == 'application/ld+json'

    def handle_data(self, data):
        if self._ld:
            self.ld.append(data)

    def handle_endtag(self, tag):
        self._ld = False


def parse(path):
    p = Links()
    with open(path, encoding='utf-8') as fh:
        p.feed(fh.read())
    return p


def check_links(root, anchors=True):
    """Every relative href/src in every .html under root resolves to a file (and its #anchor, if anchors)."""
    bad, pages, n = [], {}, 0
    for dp, dn, fn in os.walk(root):
        for f in fn:
            if f.endswith('.html'):
                pages[os.path.join(dp, f)] = None
    cache = {}

    def ids(path):
        if path not in cache:
            cache[path] = parse(path).ids
        return cache[path]
    for page in pages:
        for link in parse(page).links:
            if re.match(r'^[a-z][a-z0-9+.-]*:', link, re.I) or link.startswith('//') or '${' in link:
                continue
            n += 1
            u = urllib.parse.urlsplit(link)
            target = os.path.normpath(os.path.join(os.path.dirname(page), urllib.parse.unquote(u.path))) if u.path else page
            if not os.path.exists(target):
                bad.append((page, link))
            elif anchors and u.fragment and target.endswith('.html') and u.fragment not in ids(target):
                bad.append((page, link))
    return n, bad


class BuildTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.tmp = tempfile.TemporaryDirectory()
        t = cls.tmp.name
        src = os.path.join(t, 'src')
        make_repo(src, 'alpha', ALPHA)
        make_repo(src, 'beta', BETA)
        es = os.path.join(t, 'essays', 'alpha')
        os.makedirs(es)
        with open(os.path.join(es, '132kV.md'), 'w') as fh:
            fh.write(ESSAY)
        with open(os.path.join(t, 'essays', 'README.md'), 'w') as fh:
            fh.write('# format notes, not an essay\n')
        os.makedirs(os.path.join(t, 'essays', 'drafts'))
        with open(os.path.join(t, 'essays', 'drafts', 'beta.md'), 'w') as fh:
            fh.write('---\nstatus: draft — AI-assisted, awaiting owner approval\n---\n# Beta draft\n\nDRAFTMARKER one.\n')
        os.makedirs(os.path.join(t, 'essays', 'beta'))
        with open(os.path.join(t, 'essays', 'beta', 'lib.md'), 'w') as fh:  # a draft placed in the approved path
            fh.write('---\nstatus: draft\n---\n# Lib draft\n\nDRAFTMARKER two.\n')
        cls.out = os.path.join(t, 'out', 'explore-code')
        err = io.StringIO()
        with contextlib.redirect_stderr(err), contextlib.redirect_stdout(io.StringIO()):
            cls.stats = build.build(src, cls.out, 'https://example.org/explore-code/', 10, 40,
                                    os.path.join(t, 'nowhere'), os.path.join(t, 'essays'))
        cls.log = err.getvalue()
        with open(os.path.join(cls.out, 'build_graph.json'), encoding='utf-8') as fh:
            cls.g = json.load(fh)
        cls.byp = {(f['repo'], f['path']): f for f in cls.g['files']}

    @classmethod
    def tearDownClass(cls):
        cls.tmp.cleanup()

    def f(self, repo, path):
        return self.byp[(repo, path)]

    def section_html(self, repo, path):
        f = self.f(repo, path)
        with open(os.path.join(self.out, 's', '%04d.html' % f['section']), encoding='utf-8') as fh:
            return fh.read()

    # --- titles and name evidence
    def test_titles(self):
        self.assertEqual(self.f('alpha', '132kV/ohl_coordinates.py')['title'], '132kV Overhead Line (OHL) Coordinates')
        self.assertEqual(self.f('alpha', 'employers_requirments_large_scale_solar/print/index.html')['title'],
                         "Employers' Requirements, Large-Scale Solar — Print Page")
        si = self.f('alpha', 'apps/substation-finder/Si/202609060537-substation-intelligence.js')
        self.assertEqual(si['title'], 'Substation Intelligence')
        self.assertIn('version 2026-09-06 05:37', self.section_html('alpha', si['path']))
        self.assertEqual(build.title_of('x', 'cables/202609051921-cable_sizing.py'), 'Cable Sizing')
        page = self.section_html('alpha', '132kV/ohl_coordinates.py')
        self.assertRegex(page, r'<h2>132kV Overhead Line \(OHL\) Coordinates</h2>')

    def test_kind_and_name_words(self):
        self.assertEqual(self.f('alpha', 'map/index.html')['kind'], 'page')
        self.assertEqual(self.f('alpha', 'tests/test_alpha.py')['kind'], 'test')
        self.assertEqual(self.f('alpha', '.github/workflows/ci.yml')['kind'], 'workflow')
        self.assertEqual(self.f('alpha', '132kV/route_check.py')['kind'], 'Python CLI')
        self.assertIn('requirements', self.f('alpha', 'employers_requirments_large_scale_solar/print/index.html')['name_words'])

    def test_achieves_from_name(self):
        si = self.f('alpha', 'apps/substation-finder/Si/202609060537-substation-intelligence.js')
        self.assertEqual(si['achieves'], 'Defines `dockLayers` and `restoreLayers`.')
        self.assertEqual(si['achieves_provenance'], 'name')
        self.assertNotIn('Not stated in the file', self.section_html('alpha', si['path']))

    def test_achieves_from_readme(self):
        f = self.f('alpha', '132kV/ohl_coordinates.py')
        self.assertEqual(f['achieves_provenance'], 'readme')
        self.assertIn('returns the coordinates of each overhead line', f['achieves'])  # a README line naming the file
        page = self.f('alpha', 'map/index.html')
        # no purpose evidence: nothing restated; describe-3 adds only a literal source fact (R4b rating as written)
        self.assertEqual(page['achieves'], 'Its code works with 132 kV.')

    # --- context tiers
    def test_readme_context(self):
        f = self.f('beta', 'main.js')
        self.assertEqual(f['essay_status'], 'readme_derived')
        self.assertIn('small list of substations', f['context'])
        page = self.section_html('beta', 'main.js')
        self.assertIn('Environment and domain context', page)
        self.assertEqual(page.count('Beta keeps a small list'), 1)  # once per folder README per page
        self.assertEqual(self.g['repos'][0]['readme_summary'][:5], 'Alpha')
        self.assertNotIn('shields', self.g['repos'][0]['readme_summary'])

    def test_drafts_never_rendered(self):
        for root, dirs, names in os.walk(self.out):
            for n in names:
                if n.endswith(('.html', '.txt', '.json')):
                    self.assertNotIn('DRAFTMARKER', read(os.path.join(root, n)), os.path.join(root, n))
        self.assertNotEqual(self.f('beta', 'lib/util.js')['essay_status'], 'human')
        self.assertEqual({k for k in build.load_essays(os.path.join(self.tmp.name, 'essays'))},
                         {('alpha', 'folder', '132kV')})

    def test_readme_pick_rejects_process_records(self):
        text = ('# Engine\n\nThis record documents how the working method was clarified during an AI assisted session.\n\n'
                '**Progress policy:** No numerical programme-completion percentage is claimed.\n\n'
                'Engine computes cable ratings and voltage drop for 33kV solar sites from editable text inputs.\n')
        s, sc = build.readme_pick(text, 'engine')
        self.assertTrue(s.startswith('Engine computes cable ratings'), s)
        self.assertGreaterEqual(sc, build.README_THRESHOLD)
        self.assertEqual(build.readme_pick('# X\n\nDated: 2026-06-14.\n\nThis record documents the session.\n', 'x'),
                         ('', None))
        s, sc = build.readme_pick('# x\n\nNotes kept here about various things over time.\n', 'x')
        self.assertLess(sc, build.README_THRESHOLD)

    def test_labels_framed_as_rules(self):
        page = self.section_html('beta', 'main.js')
        self.assertIn('rule-based first approximations', page)
        self.assertIn('GRAPH-CONTRACT.md', page)
        llms = read(os.path.join(self.out, 'llms.txt'))
        self.assertIn('rule-based first approximations from code and path evidence', llms)
        r = self.g['repos'][0]
        self.assertIn(r['descriptor_provenance'], ('readme', 'code'))
        self.assertTrue(r['descriptor'])

    def test_essay_promoted(self):
        f = self.f('alpha', '132kV/route_check.py')
        self.assertEqual(f['essay_status'], 'human')
        page = self.section_html('alpha', f['path'])
        self.assertIn('Written by people', page)
        self.assertIn('People wrote this about <strong>132kV</strong> lines.', page)
        self.assertLess(page.index('Written by people'), page.index('In this section'))
        self.assertEqual(self.f('alpha', 'orphan.js')['essay_status'], 'readme_derived')

    # --- licences
    def test_licences(self):
        lic = {r['repo']: r for r in self.g['repos']}
        self.assertEqual(lic['alpha']['license'], 'MIT')
        self.assertEqual(lic['alpha']['license_file'], 'LICENSE')
        self.assertEqual(lic['beta']['license'], 'none found')
        self.assertIsNone(lic['beta']['license_file'])
        self.assertIn('WARNING: beta: no LICENSE', self.log)
        self.assertNotIn('WARNING: alpha', self.log)
        self.assertEqual(build.license_of('GNU AFFERO GENERAL PUBLIC LICENSE\n Version 3'), 'AGPL-3.0')
        self.assertEqual(build.license_of('CERN Open Hardware Licence'), 'other (see LICENSE)')
        with open(os.path.join(self.out, 'repos', 'beta.html')) as fh:
            self.assertIn('none found', fh.read())

    # --- synopsis
    def test_synopsis(self):
        s = self.f('alpha', 'map/app.js')['synopsis']
        for want in ('maps', '132kV overhead lines', 'A roads', 'UK Power Networks open data'):
            self.assertIn(want, s)
        self.assertNotIn('Part of', s)
        self.assertTrue(self.f('alpha', '132kV/route_check.py')['synopsis'].startswith('A Python command-line tool'))
        self.assertTrue(self.f('alpha', 'map/index.html')['synopsis'].startswith('A web page'))
        self.assertIn('<p class="syn">%s' % self.f('alpha', 'map/app.js')['synopsis'][:20],
                      self.section_html('alpha', 'map/app.js'))

    # --- graph contract
    def test_graph_contract(self):
        g = self.g
        self.assertEqual(g['schema'], 'explore-build-graph-v1')
        for k in ('cut', 'base', 'topics', 'repos', 'sections', 'files', 'roles'):
            self.assertIn(k, g)
        self.assertEqual([r['id'] for r in g['roles']], [k for k, t, c in build.ROLES])
        self.assertEqual(g['roles'][0]['colour'], '#00ffff')
        for r in g['repos']:
            self.assertRegex(r['commit'], r'^[0-9a-f]{40}$')
            self.assertIsInstance(r['citation'], bool)
        for s in g['sections']:
            self.assertTrue(os.path.exists(os.path.join(self.out, s['url'])))
            self.assertIsInstance(s['title'], str)
        types = {'id': int, 'repo': str, 'path': str, 'folder_hierarchy': list, 'lang': str, 'lines': int, 'section': int,
                 'block': int, 'title': str, 'achieves': str, 'why': str, 'context': str, 'essay_status': str, 'stage': str,
                 'imports': list, 'imports_external': list, 'dependents': list, 'defines': list, 'pure': bool,
                 'role': str, 'pattern': str, 'entry': bool, 'reachable': bool, 'synopsis': str, 'kind': str,
                 'name_words': list}
        n = len(g['files'])
        for i, f in enumerate(g['files']):
            self.assertEqual(f['id'], i)
            for k, t in types.items():
                self.assertIsInstance(f[k], t, k)
            self.assertIn(f['stage'], ('ingest', 'transform', 'output', 'unknown'))
            self.assertIn(f['essay_status'], ('human', 'readme_derived', 'auto'))
            self.assertIn(f['role'], [r['id'] for r in g['roles']])
            self.assertLessEqual(len(f['defines']), 30)
            for j in f['imports']:
                self.assertTrue(0 <= j < n)
                self.assertIn(i, g['files'][j]['dependents'])
            for j in f['dependents']:
                self.assertIn(i, g['files'][j]['imports'])
            if f['entry']:
                self.assertTrue(f['reachable'])

    def test_agent_ingestion_fields(self):
        import agentdocs
        g = self.g
        self.assertEqual(g['rules_version'], agentdocs.RULES_VERSION)
        self.assertEqual([s['id'] for s in g['domain_stages']], agentdocs.STAGE_IDS)
        for f in g['files']:
            self.assertIn(f['domain_stage'], agentdocs.STAGE_IDS)
            self.assertIsInstance(f['domain_stage_evidence'], str)
            self.assertTrue(set(f['commercial_user']) <= set(agentdocs.USERS))
            self.assertEqual(sorted(f['data_contracts']), ['crs', 'in', 'out', 'voltages'])
            self.assertIn(f['canonical_status'], agentdocs.CANONICAL)
            self.assertTrue(f['duplicate_of'] is None or isinstance(f['duplicate_of'], int))
            self.assertTrue(set(f['four_part']) <= {'does', 'why', 'io', 'impact'})
            self.assertTrue(all(v for v in f['four_part'].values()))  # omitted, never empty
            self.assertIsInstance(f['signatures'], list)
            if not f['reachable']:
                self.assertIn(f['canonical_status'], ('unreached_review', 'duplicate_candidate'))
        app = self.f('alpha', 'map/app.js')
        self.assertIn('GeoJSON file 132kv_ohl.geojson', app['data_contracts']['in'])
        self.assertIn('data source: UK Power Networks open data', app['data_contracts']['in'])
        self.assertIn('132kV', app['data_contracts']['voltages'])
        self.assertEqual(app['domain_stage'], 'upstream_foresight')  # voltage rule: only 132kV named
        self.assertIn('Map', app['four_part']['impact'])
        self.assertEqual(self.f('alpha', 'orphan.js')['canonical_status'], 'unreached_review')
        self.assertEqual(self.f('alpha', '132kV/ohl_coordinates.py')['signatures'], ['coords_of(line)'])
        page = self.section_html('alpha', 'map/app.js')
        self.assertIn('<dl class="v four"><dt>What it does</dt>', page)
        self.assertLess(page.index('What it does'), page.index('What it achieves'))
        self.assertIn('domain stage: upstream_foresight', page)
        # journeys: none of the named steps exist in this fixture, and each says so
        self.assertEqual([j['id'] for j in g['journeys']], ['a', 'b', 'c', 'd'])
        self.assertFalse(any(s['found'] for j in g['journeys'] for s in j['steps']))
        jp = read(os.path.join(self.out, 'journeys', 'b.html'))
        self.assertIn('Step 5: Metals &amp; Cable Prices', jp)
        self.assertIn('Not found in the public estate', jp)
        self.assertIn('No direct code link found between', jp)
        self.assertIn('href="journeys/a.html"', read(os.path.join(self.out, 'index.html')))

    def test_repo_page_tldr_and_folds(self):
        page = read(os.path.join(self.out, 'repos', 'alpha.html'))
        tl = re.search(r'<ol class="tldr"[^>]*>(.*?)</ol>', page)
        self.assertTrue(tl)
        self.assertLessEqual(tl.group(1).count('<li>'), 5)
        self.assertIn('<b>Size:</b>', tl.group(1))
        self.assertLess(page.index('class="tldr"'), page.index('More about this repository'))
        self.assertIn('<details class="fold" id="d-', page)  # folder lists fold; #d-<folder> links still open them
        self.assertIn('d.open=true', page)

    def test_index_play_row_first(self):
        page = read(os.path.join(self.out, 'index.html'))
        self.assertLess(page.index('class="cards play"'), page.index('<p>The open code behind GlobalGrid2050'))

    def test_near_copy_share(self):
        rec = {'category': 'near-copy-of', 'evidence': ['line-jaccard 0.934 to x@1 a.js:1-9 b']}
        self.assertEqual(build.near_copy_pct(rec), 93)
        self.assertIsNone(build.near_copy_pct({'category': 'noise-generated', 'evidence': ['line-jaccard 0.9']}))
        self.assertIsNone(build.near_copy_pct({'category': 'near-copy-of', 'evidence': ['no number']}))

    def test_llms_index_and_shards(self):
        import agentdocs
        llms = read(os.path.join(self.out, 'llms.txt'))
        self.assertLess(agentdocs.approx_tokens(llms), 15000)
        self.assertEqual(self.stats['llms_chars'], len(llms))
        for want in ("## Elevator (read this first)", "## Domain and commercial mission (continued)",
                     '## Topic hubs', '## User journey slices', '## Agent navigation protocol',
                     'human (an essay written by people', 'never delete them', '#L<from>-L<to>',
                     'https://example.org/explore-code/llms-maps-gis.txt', 'https://example.org/explore-code/topics/maps-gis.html',
                     'https://example.org/explore-code/llms-journey-a.txt', 'llms-full.txt'):
            self.assertIn(want, llms)
        self.assertNotIn('## Sections', llms)  # the routing index no longer lists every section
        shard = read(os.path.join(self.out, 'llms-maps-gis.txt'))
        self.assertIn('### Alpha — Map', shard)
        self.assertRegex(shard, r'- Source: https://github.com/Ventusltd/alpha/blob/[0-9a-f]{40}/map/app.js#L1-L6')
        self.assertIn('- Inputs & outputs: In: data source: UK Power Networks open data', shard)
        self.assertIn('domain_stage: upstream_foresight', shard)
        full = read(os.path.join(self.out, 'llms-full.txt'))
        self.assertEqual(full.count('\n### '), len(self.g['files']))
        agents = read(os.path.join(self.out, 'sitemap-agents.xml'))
        for n in self.stats['shards'] + ['llms.txt', 'llms-full.txt', 'build_graph.json']:
            self.assertIn('https://example.org/explore-code/%s<' % n, agents)
            self.assertTrue(os.path.exists(os.path.join(self.out, n)), n)
        self.assertIn('Sitemap: https://example.org/explore-code/sitemap-agents.xml',
                      read(os.path.join(self.out, 'robots-sitemaps.txt')))
        self.assertIn('sitemap-agents.xml', read(os.path.join(self.out, 'sitemap.xml')))
        self.assertIn('journeys/c.html', read(os.path.join(self.out, 'sitemap-essays.xml')))

    def test_function_signals(self):
        app, idx = self.f('alpha', 'map/app.js'), self.f('alpha', 'map/index.html')
        self.assertIn(idx['id'], app['dependents'])
        self.assertFalse(app['pure'])
        self.assertEqual(app['stage'], 'output')
        self.assertTrue(app['reachable'])
        self.assertTrue(self.f('alpha', '132kV/route_check.py')['entry'])
        coords = self.f('alpha', '132kV/ohl_coordinates.py')
        self.assertTrue(coords['pure'])
        self.assertEqual(coords['stage'], 'transform')
        self.assertTrue(coords['reachable'])
        self.assertEqual(coords['why'], 'Imported by 132kV Route Check.')
        orphan = self.f('alpha', 'orphan.js')
        self.assertFalse(orphan['entry'])
        self.assertFalse(orphan['reachable'])
        self.assertIn('Not reached from any entry point (candidate for review)', self.section_html('alpha', 'orphan.js'))
        self.assertEqual(self.f('alpha', 'tests/test_alpha.py')['role'], 'test')
        self.assertEqual(self.f('alpha', '.github/workflows/ci.yml')['role'], 'automation')
        self.assertEqual(self.f('alpha', 'map/index.html')['role'], 'render')
        self.assertIn('section.file', read(os.path.join(self.out, 'explore.css')))
        self.assertIn('class="file r-', self.section_html('alpha', 'orphan.js'))

    def test_reachability_reported(self):
        with open(os.path.join(self.out, 'llms.txt')) as fh:
            llms = fh.read()
        self.assertTrue(llms.startswith('# GlobalGrid2050 Explore Code\n\nAttribution: Ventus Ltd — GlobalGrid2050.'))
        self.assertIn('Reachability:', llms)
        self.assertIn('- alpha: MIT', llms)
        with open(os.path.join(self.out, 'index.html')) as fh:
            idx = fh.read()
        for want in ('Colours: what each file does', 'About this estate', 'Licences', 'All repositories A–Z',
                     'Supporting data, simulation and R&amp;D', 'Reachability:', '<details>'):
            self.assertIn(want, idx)
        self.assertLess(idx.index('Start with a topic'), idx.index('Supporting data'))
        self.assertLess(idx.index('Supporting data'), idx.index('All repositories A–Z'))

    # --- SEO
    def test_sitemaps_and_seo(self):
        for n in ('sitemap.xml', 'sitemap-essays.xml', 'sitemap-code.xml', 'robots-sitemaps.txt'):
            self.assertTrue(os.path.exists(os.path.join(self.out, n)), n)
        with open(os.path.join(self.out, 'sitemap.xml')) as fh:
            sm = fh.read()
        self.assertIn('<sitemapindex', sm)
        self.assertIn('https://example.org/explore-code/sitemap-code.xml', sm)
        with open(os.path.join(self.out, 'sitemap-code.xml')) as fh:
            self.assertIn('/s/0001.html', fh.read())
        with open(os.path.join(self.out, 'robots-sitemaps.txt')) as fh:
            self.assertIn('Sitemap: https://example.org/explore-code/sitemap.xml', fh.read())
        titles, lds = [], 0
        for dp, dn, fn in os.walk(self.out):
            for name in fn:
                if not name.endswith('.html'):
                    continue
                path = os.path.join(dp, name)
                text = read(path)
                titles.append(re.search(r'<title>(.*?)</title>', text).group(1))
                self.assertIn('<meta name="author" content="Ventus Ltd — GlobalGrid2050">', text)
                self.assertIn('<link rel="canonical" href="https://example.org/explore-code/', text)
                self.assertIn('Part of:', text)
                for block in parse(path).ld:
                    d = json.loads(block)
                    lds += 1
                    if d.get('@type') == 'SoftwareSourceCode':
                        self.assertEqual(d['author']['name'], 'Ventus Ltd')
                        self.assertTrue(d['codeRepository'].startswith('https://github.com/Ventusltd/'))
                if '/s/' in path:
                    self.assertIn('SoftwareSourceCode', text)
        self.assertEqual(len(titles), len(set(titles)), 'page titles must be unique')
        self.assertGreater(lds, 1)
        alpha = [s for s in self.g['sections'] if 'alpha' in s['repos']][0]
        text = read(os.path.join(self.out, alpha['url']))
        d = json.loads(parse(os.path.join(self.out, alpha['url'])).ld[0])
        self.assertTrue(d['license'].startswith('https://github.com/Ventusltd/alpha/blob/'))
        self.assertIn('href="../repos/alpha.html"', text)
        self.assertIn('href="../topics/', text)

    def test_links_resolve(self):
        n, bad = check_links(self.out)
        self.assertGreater(n, 50)
        # visual/ is written by visualise.py beside the pages in the real build, not by build().
        self.assertEqual([b for b in bad if not b[1].startswith('visual/')], [])

    def test_markdown_and_readme_helpers(self):
        self.assertEqual(build.readme_summary('# T\n\n[![b](x)](y)\n\n- link\n- list\n\nA real paragraph about **cables** and '
                                              '[conductors](http://x) here.\n'),
                         'A real paragraph about cables and conductors here.')
        h = build.md_html('# H\n\nText with `code` and [link](https://x.org).\n\n1. a\n2. b\n\n```\n<x>\n```\n')
        self.assertIn('<h2>H</h2>', h)
        self.assertIn('<code>code</code>', h)
        self.assertIn('<a href="https://x.org">link</a>', h)
        self.assertIn('<ol><li>a</li><li>b</li></ol>', h)
        self.assertIn('&lt;x&gt;', h)
        self.assertNotIn('<a href="javascript', build.md_html('[x](javascript:alert(1))'))


class EdgeTest(unittest.TestCase):
    """Every edge kind, estate URLs across repositories, workflow -> script, and a truly unreferenced file."""

    @classmethod
    def setUpClass(cls):
        cls.tmp = tempfile.TemporaryDirectory()
        t = cls.tmp.name
        src = os.path.join(t, 'src')
        make_repo(src, 'globalgrid2050', GG)
        make_repo(src, 'delta', DELTA)
        cls.out = os.path.join(t, 'out', 'explore-code')
        with contextlib.redirect_stderr(io.StringIO()), contextlib.redirect_stdout(io.StringIO()):
            cls.stats = build.build(src, cls.out, 'https://example.org/explore-code/', 10, 40, os.path.join(t, 'nowhere'),
                                    os.path.join(t, 'no-essays'))
        with open(os.path.join(cls.out, 'build_graph.json'), encoding='utf-8') as fh:
            cls.g = json.load(fh)
        cls.byp = {(f['repo'], f['path']): f for f in cls.g['files']}

    @classmethod
    def tearDownClass(cls):
        cls.tmp.cleanup()

    def f(self, repo, path):
        return self.byp[(repo, path)]

    def edge(self, a, b):
        """[(kind, via)] of edges from file a to file b ((repo, path) pairs)."""
        ia, ib = self.f(*a)['id'], self.f(*b)['id']
        return [(k, v) for x, y, k, v in self.g['edges'] if x == ia and y == ib]

    def assertEdge(self, a, b, kind, via=None):
        got = self.edge(a, b)
        self.assertIn(kind, [k for k, v in got], '%s -> %s: %s' % (a, b, got))
        if via is not None:
            self.assertIn((kind, via), got)

    def test_html_edges(self):
        idx = ('globalgrid2050', 'index.html')
        g = lambda p: ('globalgrid2050', p)
        self.assertEdge(idx, g('js/app.js'), 'script-src', '')
        self.assertEdge(idx, g('css/site.css'), 'stylesheet')
        self.assertEdge(idx, g('js/pre.mjs'), 'modulepreload')
        self.assertEdge(idx, g('embed/frame.html'), 'iframe')
        self.assertEdge(idx, g('about.html'), 'link')
        self.assertEdge(idx, g('tools/index.html'), 'link', 'index')  # directory URL -> folder/index.html
        self.assertEdge(idx, g('js/lib/mapped.js'), 'import-map')
        self.assertEdge(idx, g('js/worker.js'), 'worker')
        self.assertEdge(idx, g('partials/menu.html'), 'fetch')
        self.assertEdge(g('css/site.css'), g('css/base.css'), 'stylesheet')

    def test_js_edges(self):
        g = lambda p: ('globalgrid2050', p)
        self.assertEdge(g('js/app.js'), g('js/lazy.js'), 'dynamic-import')
        self.assertEdge(g('js/app.js'), g('js/wasm-glue.js'), 'url-import-meta')
        self.assertEdge(g('js/app.js'), g('js/cjs.js'), 'require')
        for p in ('js/lazy.js', 'js/wasm-glue.js', 'js/cjs.js', 'js/lib/mapped.js', 'js/worker.js', 'css/base.css'):
            self.assertTrue(self.f(*g(p))['reachable'], p)

    def test_python_edges(self):
        g = lambda p: ('globalgrid2050', p)
        self.assertEdge(g('pkg/core.py'), g('pkg/helpers.py'), 'python-relative')
        self.assertEdge(g('pkg/core.py'), g('pkg/model.py'), 'python-relative')
        self.assertEdge(g('pkg/cli.py'), g('pkg/core.py'), 'python-relative')
        self.assertEdge(g('tools/run.py'), g('lib_py/sibling_lib.py'), 'sys-path')
        self.assertEqual(build.py_path_expr('str(Path(__file__).resolve().parents[1] / "scripts")', {}, 'a/b/c.py'),
                         ('path', 'a/scripts'))
        self.assertEqual(build.python_syspath_dirs('t/x.py', ['HERE = os.path.dirname(os.path.abspath(__file__))',
                                                              'sys.path.insert(0, HERE)']), ['t'])

    def test_workflow_and_script_edges(self):
        g = lambda p: ('globalgrid2050', p)
        wf = g('.github/workflows/ci.yml')
        self.assertEdge(wf, g('tools/run.py'), 'workflow-run', 'root')
        self.assertEdge(wf, g('scripts/build.sh'), 'workflow-run')
        self.assertEdge(wf, g('tools/node_task.mjs'), 'workflow-run')
        self.assertEdge(wf, g('pkg/cli.py'), 'workflow-run')  # python -m pkg.cli
        self.assertEdge(g('scripts/build.sh'), g('scripts/gen.py'), 'script-call')
        for p in ('tools/run.py', 'scripts/build.sh', 'tools/node_task.mjs', 'pkg/cli.py'):
            self.assertTrue(self.f(*g(p))['entry'], p)  # called by a workflow
        self.assertTrue(self.f(*g('tools/run.py'))['why'].startswith('Run by '), self.f(*g('tools/run.py'))['why'])
        for p in ('scripts/gen.py', 'lib_py/sibling_lib.py', 'pkg/helpers.py', 'pkg/model.py'):
            self.assertTrue(self.f(*g(p))['reachable'], p)

    def test_test_runners_globs_and_variables(self):
        g = lambda p: ('globalgrid2050', p)
        wf = g('.github/workflows/ci.yml')
        self.assertEdge(wf, g('checks/test_unit.py'), 'workflow-run', 'discover')  # pytest default rules
        self.assertEqual(self.edge(wf, g('checks/helper_tools.py')), [])
        self.assertEqual(self.edge(wf, g('pkg/helpers.py')), [])  # "pip install pytest" collects nothing
        self.assertEdge(wf, g('web/thing.test.mjs'), 'workflow-run', 'discover')  # node --test default rules
        self.assertEqual(self.edge(wf, g('web/thing.mjs')), [])
        self.assertEdge(wf, g('cartridges/a/proof.mjs'), 'workflow-run', 'glob')
        self.assertEdge(wf, g('cartridges/b/proof.mjs'), 'workflow-run', 'glob')
        self.assertEdge(wf, g('tools/verify.mjs'), 'workflow-run')  # node "$VERIFIER"
        self.assertEdge(wf, g('tools/compiled_only.py'), 'workflow-run', 'discover')  # py_compile
        self.assertEdge(g('scripts/suite/run.sh'), g('scripts/suite/check.mjs'), 'script-call', 'shell-dir')
        self.assertEdge(g('scripts/suite/check.mjs'), g('scripts/suite/step_one.py'), 'script-call', 'root+string')
        self.assertTrue(self.f(*g('scripts/suite/step_one.py'))['reachable'])
        self.assertFalse(self.f(*g('checks/helper_tools.py'))['reachable'])