GLOBALGRID2050 / EXPLORE CODE

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

Test Agentdocs

A test in the explore folder of Cosmic that checks Agentdocs and Kuiper Belt — See Through Page, using EPSG:27700 and EPSG:4326 using data from ukpn.example and the kuiper-belt repository.

356 lines of Python from cosmic, in 1 file. Topic: Kuiper, cosmos and drawing engines. Section 1137 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 Agentdocs test · cosmic / tools/explore/test_agentdocs.py lines 1–356

Test Agentdocs

A test in the explore folder of Cosmic that checks Agentdocs and Kuiper Belt — See Through Page, using EPSG:27700 and EPSG:4326 using data from ukpn.example and the kuiper-belt repository.

testcosmic / tools/explore/test_agentdocs.py · lines 1–356 of 356 · Entry point · pattern Budget (shared by 2 files)

What it does
It tests cables. Defines 36 functions or classes, including F, DomainStage, test_path_words_and_precedence, test_repo_words_then_voltages_then_topic, test_enum_closed. Uses libraries os, sys, unittest. Side effects: changes the web page (DOM); reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain terms in the code: cables, 400kV, 132kV, 33kV, 11kV, 11kV/400V.
Inputs & outputs
In: data source: ukpn.example; data source: kuiper-belt data; GeoJSON file 132kv_ohl.geojson; JSON file x.json; browser storage (getItem); form fields (user input); command-line arguments. Out: CSV file routes.csv; Excel file boq.xlsx; CSV file repd.csv; Parquet file repd.parquet; downloaded file boq.xlsx; browser storage (setItem); interactive map. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326, Web Mercator / EPSG:3857. Voltage levels named: 400kV, 132kV, 33kV, 11kV, 11kV/400V, 6.6kV, 400V.
Downstream impact
It is itself an entry point (test); no other file was found loading it.
What it achieves
It sets up (`setUp`) and is built from the domain stage class (`DomainStage`) and the commercial user class (`CommercialUser`). Tests for `tools/explore/agentdocs.py` (unittest, no network): every enum rule, data-contract extraction, four-part omission rules, signatures, shard splitting, journeys (found and not found) and the llms.txt budget. Its code works with 33 kV, 11 kV and 132 kV. It reads `data/132kv_ohl.geojson` and writes `out/routes.csv`.
Why it matters
Guards the behaviour of Agentdocs and Kuiper Belt — See Through Page.
Application
cosmic · tools/explore · test
Uses
Agentdocs (import), Kuiper Belt — See Through Page (estate URL), os, sys, unittest
Used by
none found
Produces
F, DomainStage, CommercialUser, DataContracts, Canonical, Signatures, FourPart, Shards, Journeys, Budget
Defines here
F, DomainStage, test_path_words_and_precedence, test_repo_words_then_voltages_then_topic, test_enum_closed, CommercialUser, test_stage_users_and_words, DataContracts, test_coordinate_systems, test_voltages, test_files_apis_and_outputs, test_sources_need_reads_and_python_writes, test_contract_words, Canonical, files, test_rules, Signatures, test_python, test_javascript, FourPart, test_omission, test_content_from_evidence, Shards, test_split, test_block, Journeys, setUp, test_mapping, test_no_homepage, test_unresolved_homepage_links
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_agentdocs.py:1-356 · blob bfbb371e699f303ca6629e23326b78a8b3bd4246 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
"""Tests for tools/explore/agentdocs.py (unittest, no network): every enum rule, data-contract extraction,
four-part omission rules, signatures, shard splitting, journeys (found and not found) and the llms.txt budget.

Run:  python tools/explore/test_agentdocs.py
"""
import os
import sys
import unittest

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


def F(text='', **kw):
    f = {'repo': 'r', 'path': 'x.js', 'text': text, 'low': text.lower(), 'effects': [], 'reads': False,
         'writes': False, 'kind': 'JavaScript module', 'name_words': []}
    f.update(kw)
    return f


class DomainStage(unittest.TestCase):
    def test_path_words_and_precedence(self):
        self.assertEqual(A.domain_stage_of('globalgrid2050', ['solar', 'design', 'studio'], 'solar-storage', [])[0],
                         'sub33kv_design')
        # experimental beats every other stage; procurement beats design (33kv price estimator)
        self.assertEqual(A.domain_stage_of('satnav', ['sandbox', 'route'], 'maps-gis', [])[0], 'experimental')
        st, ev = A.domain_stage_of('globalgrid2050', ['33kv', 'uk', 'dap', 'price', 'estimator'], 'cables', [])
        self.assertEqual(st, 'hv_procurement')
        self.assertIn("path word", ev)
        self.assertEqual(A.domain_stage_of('x', ['apps', 'substation', 'finder'], 'web-apps', [])[0], 'upstream_foresight')
        self.assertEqual(A.domain_stage_of('x', ['lidar', 'tiles'], 'maps-gis', [])[0], 'site_feasibility')
        self.assertEqual(A.domain_stage_of('x', ['compass'], 'web-apps', [])[0], 'field_execution')
        self.assertEqual(A.domain_stage_of('x', ['agents', 'start'], 'web-apps', [])[0], 'agent_infra')

    def test_repo_words_then_voltages_then_topic(self):
        st, ev = A.domain_stage_of('satnav', ['index'], 'web-apps', [])
        self.assertEqual((st, ev), ('field_execution', "repository name word 'satnav'"))
        self.assertEqual(A.domain_stage_of('alpha', ['app'], 'web-apps', ['400kV', '132kV'])[0], 'upstream_foresight')
        self.assertEqual(A.domain_stage_of('alpha', ['app'], 'web-apps', ['33kV', '11kV/400V', '400V'])[0], 'sub33kv_design')
        # mixed voltages fall through to the topic
        self.assertEqual(A.domain_stage_of('alpha', ['app'], 'markets-data', ['132kV', '33kV'])[0], 'upstream_foresight')
        self.assertEqual(A.domain_stage_of('alpha', ['app'], 'agents-ai', [])[0], 'agent_infra')
        self.assertEqual(A.domain_stage_of('alpha', ['app'], 'kuiper-cosmos', []), ('unknown', ''))

    def test_enum_closed(self):
        for st in A.STAGE_ORDER:
            self.assertIn(st, A.STAGE_IDS)
        self.assertEqual(set(A.STAGE_IDS), {'upstream_foresight', 'site_feasibility', 'sub33kv_design', 'hv_procurement',
                                            'field_execution', 'agent_infra', 'experimental', 'unknown'})


class CommercialUser(unittest.TestCase):
    def test_stage_users_and_words(self):
        self.assertEqual(A.commercial_users_of('hv_procurement', []), ['EPC_contractor', 'procurement_buyer'])
        self.assertEqual(A.commercial_users_of('agent_infra', []), ['ai_agent'])
        self.assertEqual(A.commercial_users_of('upstream_foresight', ['repd']), ['IPP_developer', 'ICP_grid_engineer'])
        self.assertEqual(A.commercial_users_of('unknown', ['farm', 'prices']), ['landowner_planner', 'procurement_buyer'])
        self.assertEqual(A.commercial_users_of('experimental', ['x']), [])
        self.assertEqual(A.commercial_users_of('unknown', []), [])
        for us in A.STAGE_USERS.values():
            self.assertTrue(set(us) <= set(A.USERS))


class DataContracts(unittest.TestCase):
    def test_coordinate_systems(self):
        self.assertEqual(A.crs_in("proj4.defs('epsg:27700', ...)"), ['OSGB36 / EPSG:27700 (British National Grid)'])
        self.assertEqual(A.crs_in('convert osgb36 to wgs84'), ['OSGB36 / EPSG:27700 (British National Grid)',
                                                               'WGS84 / EPSG:4326'])
        self.assertEqual(A.crs_in('const bng = toGrid(p)'), ['OSGB36 / EPSG:27700 (British National Grid)'])
        self.assertEqual(A.crs_in('easting = 1; northing = 2'), ['OSGB36 / EPSG:27700 (British National Grid)'])
        self.assertEqual(A.crs_in('crs: "EPSG:4326"'.lower()), ['WGS84 / EPSG:4326'])
        self.assertEqual(A.crs_in('epsg:3857 tiles'), ['Web Mercator / EPSG:3857'])
        self.assertEqual(A.crs_in('lat lng latitude longitude'), [])  # lat/lng alone is not a datum

    def test_voltages(self):
        self.assertEqual(A.voltages_in('132kv ohl and 33 kv cable, 11kv/400v substation, 6.6kv, 400v ac'),
                         ['132kV', '33kV', '11kV/400V', '6.6kV', '400V'])
        self.assertEqual(A.voltages_in('kvp=1, x2kv', ''), [])
        self.assertEqual(A.voltages_in('nothing', '132kv ohl'), ['132kV'])  # path words count

    def test_files_apis_and_outputs(self):
        text = ("fetch('data/132kv_ohl.geojson')\nfetch('https://ukpn.example/api')\n"
                "fs.writeFileSync('out/routes.csv', s)\nlocalStorage.setItem('k', v)\nconst a = localStorage.getItem('k')\n"
                "a.download = 'boq.xlsx'\nconst m = new maplibregl.Map({})\n<input id=q>\n")
        dc = A.data_contracts_of(F(text, effects=['network', 'dom', 'storage'], reads=True, kind='page'),
                                 ['UK Power Networks open data'])
        self.assertIn('data source: UK Power Networks open data', dc['in'])
        self.assertIn('GeoJSON file 132kv_ohl.geojson', dc['in'])
        self.assertIn('CSV file routes.csv', dc['out'])
        self.assertNotIn('CSV file routes.csv', dc['in'])
        self.assertIn('browser storage (getItem)', dc['in'])
        self.assertIn('browser storage (setItem)', dc['out'])
        self.assertIn('downloaded file boq.xlsx', dc['out'])
        self.assertIn('form fields (user input)', dc['in'])
        self.assertIn('web page', dc['out'])
        self.assertIn('interactive map', dc['out'])
        self.assertEqual(dc['crs'], [])

    def test_sources_need_reads_and_python_writes(self):
        self.assertEqual(A.data_contracts_of(F('x'), ['Elexon BMRS'])['in'], [])
        py = "import argparse, pandas as pd\ndf = pd.read_csv('repd.csv')\ndf.to_parquet('repd.parquet')\n"
        dc = A.data_contracts_of(F(py, path='a.py', reads=True, writes=True, effects=['filesystem']))
        self.assertIn('CSV file repd.csv', dc['in'])
        self.assertIn('Parquet file repd.parquet', dc['out'])
        self.assertIn('command-line arguments', dc['in'])
        wf = 'jobs:\n  b:\n    steps:\n      - uses: actions/deploy-pages@v4\n      - run: git push\n'
        dc = A.data_contracts_of(F(wf, path='.github/workflows/p.yml', kind='workflow'))
        self.assertEqual(dc['out'], ['GitHub Pages deployment', 'commits pushed to the repository'])
        self.assertEqual(A.data_contracts_of(F('package.json "x.json"'))['in'], ['JSON file x.json'])

    def test_contract_words(self):
        self.assertEqual(A.contracts_words({'in': [], 'out': [], 'crs': [], 'voltages': []}), '')
        w = A.contracts_words({'in': ['a'], 'out': ['b'], 'crs': ['WGS84 / EPSG:4326'], 'voltages': ['11kV']})
        self.assertEqual(w, 'In: a. Out: b. Coordinate systems named: WGS84 / EPSG:4326. Voltage levels named: 11kV.')


class Canonical(unittest.TestCase):
    def files(self):
        body = '\n'.join('line %d' % k for k in range(8))
        return [
            {'repo': 'gridatlas', 'path': 'atlas/index.html', 'text': '<html>', 'reachable': True, 'entry': True,
             'pattern': '', 'defines': [], 'lines': 1, 'role': 'render'},                                       # 0 core
            {'repo': 'gridatlas', 'path': 'lib/a.js', 'text': body, 'reachable': True, 'entry': False,
             'pattern': '', 'defines': [], 'lines': 8, 'role': 'transform'},                                   # 1 core (dependent)
            {'repo': 'other', 'path': 'copy/a.js', 'text': body.replace('line', 'line  '), 'reachable': False,
             'entry': False, 'pattern': '', 'defines': [], 'lines': 8, 'role': 'transform'},                    # 2 dup of 1
            {'repo': 'other', 'path': 'old.js', 'text': 'a\nb', 'reachable': False, 'entry': False, 'pattern': '',
             'defines': [], 'lines': 2, 'role': 'other'},                                                      # 3 unreached
            {'repo': 'data-grid-gb', 'path': 'x.py', 'text': 'q', 'reachable': True, 'entry': True, 'pattern': '',
             'defines': [], 'lines': 1, 'role': 'ingest'},                                                     # 4 supporting
            {'repo': 'other', 'path': 'store.js', 'text': 'z', 'reachable': True, 'entry': True, 'pattern': '',
             'defines': [], 'lines': 1, 'role': 'storage'},                                                    # 5 supporting
            {'repo': 'other', 'path': 'page.html', 'text': 'p', 'reachable': True, 'entry': True, 'pattern': '',
             'defines': [], 'lines': 1, 'role': 'render'},                                                     # 6 unknown
            {'repo': 'm', 'path': 'v1/dist.js', 'text': 'a1', 'reachable': True, 'entry': True,
             'pattern': 'distanceKm', 'defines': ['distanceKm', 'toRad'], 'lines': 100, 'role': 'geodesy'},     # 7 kept
            {'repo': 'm', 'path': 'v2/dist.js', 'text': 'a2', 'reachable': False, 'entry': False,
             'pattern': 'distanceKm', 'defines': ['toRad', 'distanceKm'], 'lines': 110, 'role': 'geodesy'},     # 8 dup of 7
            {'repo': 'm', 'path': 'v3/dist.js', 'text': 'a3', 'reachable': False, 'entry': False,
             'pattern': 'distanceKm', 'defines': ['toRad', 'distanceKm'], 'lines': 300, 'role': 'geodesy'},     # 9 too different
            {'repo': 'gridatlas', 'path': 'lib/b.js', 'text': body, 'reachable': True, 'entry': True,
             'pattern': '', 'defines': [], 'lines': 8, 'role': 'transform'},                                   # 10 core copy: stays core
        ]

    def test_rules(self):
        st = A.canonical_statuses(self.files(), {1: [0]}, {'gridatlas'})
        self.assertEqual(st[0], ('production_core', None))
        self.assertEqual(st[1], ('production_core', None))
        self.assertEqual(st[2][0], 'duplicate_candidate')
        self.assertIn(st[2][1], (1, 10))
        self.assertEqual(st[3], ('unreached_review', None))
        self.assertEqual(st[4], ('supporting_data', None))
        self.assertEqual(st[5], ('supporting_data', None))
        self.assertEqual(st[6], ('unknown', None))
        self.assertEqual(st[7], ('unknown', None))
        self.assertEqual(st[8], ('duplicate_candidate', 7))
        self.assertEqual(st[9], ('unreached_review', None))
        self.assertEqual(st[10], ('production_core', None))
        self.assertTrue(all(s in A.CANONICAL for s, d in st))


class Signatures(unittest.TestCase):
    def test_python(self):
        py = 'def size(cable,\n         length=1.0):  # metres\n    pass\n\nclass Route(Base):\n    def walk(self, a):\n        pass\n'
        self.assertEqual(A.signatures_of('a.py', py, ['size']), ['size(cable, length=1.0)', 'class Route', 'walk(self, a)'])

    def test_javascript(self):
        js = ('export function haversine(a, b) {\n}\nconst f = (x, y) => x;\nconst g = async z => z;\n'
              'export class Line {\n  draw(ctx, opts) {\n  }\n  if (x) {\n  }\n}\nfunction lonely() {}\nexport { lonely };\n')
        sig = A.signatures_of('m.js', js)
        self.assertEqual(sig[:3], ['export haversine(a, b)', 'export class Line', 'export lonely()'])
        self.assertIn('f(x, y)', sig)
        self.assertIn('g(z)', sig)
        self.assertIn('draw(ctx, opts)', sig)
        self.assertFalse(any(s.startswith('if(') for s in sig))
        self.assertEqual(A.signatures_of('s.sh', 'build() {\n  :\n}\n'), ['build()'])
        self.assertEqual(A.signatures_of('a.css', 'a{}'), [])
        self.assertEqual(A.signatures_of('m.js', 'function secretName(a) {}', leaks=lambda s: s == 'secretName'), [])


class FourPart(unittest.TestCase):
    def test_omission(self):
        self.assertEqual(A.what_it_does('', [], [], [], []), '')
        self.assertEqual(A.why_it_exists('unknown', '', [], ''), '')
        self.assertEqual(A.four_part_html({'does': '', 'why': '', 'io': '', 'impact': ''}), '')
        files = [{'title': 'Lonely', 'repo': 'r', 'kind': 'JavaScript module', 'entry': False, 'published': ''}]
        self.assertEqual(A.downstream_impact(0, files, {}, {}), '')
        html = A.four_part_html({'does': 'It maps cables.', 'why': '', 'io': 'In: a.', 'impact': ''})
        self.assertIn('<dt>What it does</dt>', html)
        self.assertIn('<dt>Inputs &amp; outputs</dt>', html)
        self.assertNotIn('Why it exists', html)
        self.assertNotIn('Downstream impact', html)

    def test_content_from_evidence(self):
        d = A.what_it_does('fetches', ['substations'], ['a', 'b', 'c', 'd', 'e', 'f'], ['numpy', './x.js'], ['network'])
        self.assertEqual(d, 'It fetches substations. Defines 6 functions or classes, including a, b, c, d, e. '
                            'Uses libraries numpy. Side effects: makes network requests.')
        w = A.why_it_exists('sub33kv_design', "path word 'cable'", ['cables', '33kV'], 'The file x.py sizes cables.')
        self.assertTrue(w.startswith("Domain stage sub33kv_design (path word 'cable'): inside-the-fence"))
        self.assertIn('Domain terms in the code: cables, 33kV.', w)
        self.assertIn('README: "The file x.py sizes cables."', w)
        self.assertEqual(A.why_it_exists('unknown', '', [], 'x.py does y.'), 'README: "x.py does y."')
        files = [{'title': 'Lib', 'repo': 'r', 'kind': 'JavaScript module', 'entry': False, 'published': ''},
                 {'title': 'Map', 'repo': 'r', 'kind': 'page', 'entry': True, 'published': 'https://e.org/map/'},
                 {'title': 'Home', 'repo': 'r', 'kind': 'page', 'entry': True, 'published': 'https://e.org/'},
                 {'title': 'Tool', 'repo': 'r', 'kind': 'Python CLI', 'entry': True, 'published': ''}]
        imp = A.downstream_impact(0, files, {0: [1]}, {0: [1, 2]})
        self.assertEqual(imp, 'Used directly by 1 file: Map (r, https://e.org/map/). Reached from 1 other entry point, '
                              'including Home (r, https://e.org/).')
        self.assertEqual(A.downstream_impact(2, files, {}, {}), 'It is itself an entry point, published at https://e.org/.')
        self.assertIn('no other file was found loading it', A.downstream_impact(3, files, {}, {}))


class Shards(unittest.TestCase):
    def test_split(self):
        one = A.split_parts('cables', '# H\n', ['a' * 10, 'b' * 10], limit=1000)
        self.assertEqual([n for n, t in one], ['llms-cables.txt'])
        blocks = ['x' * 400 + '\n' for _ in range(10)]
        parts = A.split_parts('maps-gis', '# H\n', blocks, limit=1000)
        names = [n for n, t in parts]
        self.assertEqual(names[0], 'llms-maps-gis.txt')
        self.assertEqual(names[1:3], ['llms-maps-gis-01.txt', 'llms-maps-gis-02.txt'])
        for n, t in parts:
            self.assertLessEqual(len(t.encode()), 1000, n)
        self.assertIn('llms-maps-gis-01.txt', parts[0][1])  # the unsplit name indexes the parts
        self.assertEqual(sum(t.count('x' * 400) for n, t in parts[1:]), 10)  # every block once
        big = A.split_parts('t', '# H\n', ['y' * 3000, 'z'], limit=1000)
        self.assertEqual(len(big), 3)  # index + oversize block alone + the rest

    def test_block(self):
        g = {'title': 'T', 'repo': 'r', 'path': 'p.js', 'lang': 'JavaScript', 'lines': 3, 'role': 'render', 'stage': 'output',
             'entry': False, 'reachable': False, 'synopsis': 'S.', 'achieves': '', 'achieves_provenance': 'name',
             'four': {'does': 'It draws.', 'why': '', 'io': '', 'impact': ''}, 'signatures': ['f(a)'], 'vedic': [],
             'domain_stage': 'unknown', 'commercial_user': [], 'canonical_status': 'unreached_review',
             'data_contracts': {'in': [], 'out': [], 'crs': [], 'voltages': []}, 'essay_status': 'auto'}
        b = A.shard_block(g, 'https://e.org/', 's/0001.html#f1', 'https://github.com/Ventusltd/r/blob/c/p.js#L1-L3')
        self.assertIn('- Source: https://github.com/Ventusltd/r/blob/c/p.js#L1-L3', b)
        self.assertIn('not reached (candidate for review)', b)
        self.assertIn('- What it does: It draws.', b)
        self.assertNotIn('Why it exists', b)
        self.assertIn('`f(a)`', b)
        self.assertIn('canonical_status: unreached_review', b)


class Journeys(unittest.TestCase):
    def setUp(self):
        mk = lambda repo, path, entry=False: {'repo': repo, 'path': path, 'title': path, 'entry': entry}
        self.files = [mk('pipelinenews', 'index.html', True),                     # 0
                      mk('gridatlas', 'atlas/index.html', True),                  # 1
                      mk('kuiper-belt', 'see-through/index.html', True),          # 2
                      mk('globalgrid2050', 'index.html', True),                   # 3
                      mk('globalgrid2050', 'solar-design-studio/a/index.html', True),  # 4
                      mk('neural-link-between-agents', 'x.js'),                   # 5
                      mk('globalgrid2050', 'copper_prices/index.html', True),     # 6
                      mk('data_uk_dno_and_tso', 'build.py', True)]                # 7
        self.repos = sorted({f['repo'] for f in self.files})
        self.home = ('<a class="launch" href="https://globalgrid2050.com/copper_prices/">Open Metals &amp; Cable '
                     'Prices &rarr;</a><a href="https://ventusltd.github.io/kuiper-belt/see-through/">Open See Through</a>')
        urls = {'https://globalgrid2050.com/copper_prices/': 6, 'https://ventusltd.github.io/kuiper-belt/see-through/': 2}
        self.resolve = urls.get
        self.edges = [[0, 1, 'estate-url', 'url'], [5, 3, 'link', '']]

    def test_mapping(self):
        js = A.resolve_journeys(self.files, self.repos, A.homepage_links(self.home), self.resolve, self.edges, {}, {1: [0]})
        self.assertEqual([j['id'] for j in js], ['a', 'b', 'c', 'd'])
        a = {s['label']: s for s in js[0]['steps']}
        self.assertEqual(a['PipelineNews']['locations'][0]['evidence'], 'repository name')  # compact equality
        self.assertEqual(a['GridAtlas']['locations'][0]['repo'], 'gridatlas')
        st = a['See Through']['locations']
        self.assertEqual((st[0]['repo'], st[0]['folder'], st[0]['evidence']), ('kuiper-belt', 'see-through', 'homepage launch link'))
        self.assertIn('folder name', st[0]['detail'])  # the folder rule found the same place: merged, not repeated
        self.assertEqual(len(st), 1)
        self.assertFalse(a['LiDAR']['found'])
        self.assertEqual(a['LiDAR']['locations'], [])
        b = {s['label']: s for s in js[1]['steps']}
        self.assertEqual(b['Solar Design Studio']['locations'][0]['folder'], 'solar-design-studio')
        self.assertEqual(b['Metals & Cable Prices']['locations'][0]['evidence'], 'homepage launch link')
        self.assertEqual(b['Metals & Cable Prices']['entry_files'][0], 6)
        c = {s['label']: s for s in js[2]['steps']}
        self.assertEqual(c['Data UK DNO/TSO']['locations'][0]['repo'], 'data_uk_dno_and_tso')
        d = {s['label']: s for s in js[3]['steps']}
        self.assertEqual(d['Neural Link']['locations'][0]['evidence'], 'repository name (contains the label words)')
        links = js[0]['links']
        self.assertEqual((links[0]['from'], links[0]['to'], links[0]['count']), ('PipelineNews', 'GridAtlas', 1))
        self.assertEqual(links[1]['count'], 0)
        self.assertEqual(A.link_sentence(links[1], self.files), 'No direct code link found between GridAtlas and See Through.')
        self.assertIn('1 resolved reference between PipelineNews and GridAtlas', A.link_sentence(links[0], self.files))

    def test_no_homepage(self):
        js = A.resolve_journeys(self.files, self.repos, [], lambda u: None, [], {}, {})
        b = {s['label']: s for s in js[1]['steps']}
        self.assertFalse(b['Metals & Cable Prices']['found'])
        self.assertEqual(b['Metals & Cable Prices']['notes'], [])

    def test_unresolved_homepage_links(self):
        links = A.homepage_links('<a href="https://globalgrid2050.com/metal_prices/">Open Metals &amp; Cable Prices</a>'
                                 '<a href="https://ventusltd.github.io/kuiper-belt/see-through/">Open See Through</a>')
        self.assertEqual(links[0], ('Open Metals & Cable Prices', 'https://globalgrid2050.com/metal_prices/'))
        self.assertEqual(A.homepage_links('<a class="card launch" href="/x/">Open X &rarr;</a><a href="/y/">Y</a>',
                                          launch_only=True), [('Open X', '/x/')])
        maps = {'https://globalgrid2050.com/metal_prices/': ('globalgrid2050', 'metal_prices/'),
                'https://ventusltd.github.io/kuiper-belt/see-through/': ('kuiper-belt', 'see-through/')}
        files = [{'repo': 'kuiper-belt', 'path': 'see-through/v1/app.js', 'title': 'App', 'entry': True},
                 {'repo': 'globalgrid2050', 'path': 'other.js', 'title': 'O', 'entry': False}]
        js = A.resolve_journeys(files, ['kuiper-belt', 'globalgrid2050'], links, lambda u: None, [], {}, {},
                                maps.get, lambda r, p: 'metal_prices.md' if r == 'globalgrid2050' else '')
        a = {s['label']: s for s in js[0]['steps']}
        loc = a['See Through']['locations'][0]  # page not code, but its folder holds estate files
        self.assertEqual((loc['repo'], loc['folder'], loc['evidence'], loc['target']),
                         ('kuiper-belt', 'see-through', 'homepage launch link', None))
        b = {s['label']: s for s in js[1]['steps']}
        self.assertFalse(b['Metals & Cable Prices']['found'])
        self.assertEqual(b['Metals & Cable Prices']['notes'], [
            'The homepage links "Open Metals & Cable Prices" to https://globalgrid2050.com/metal_prices/, but no code file '
            'in the public estate serves that address; globalgrid2050/metal_prices.md holds it, which is not code.'])


class Budget(unittest.TestCase):
    def test_mission_block(self):
        n = len(A.MISSION.split())
        self.assertTrue(135 <= n <= 165, n)
        self.assertTrue(A.MISSION.startswith('Ventus Ltd states'))

    def test_token_estimate(self):
        self.assertEqual(A.approx_tokens('x' * 60000), 15000)

    def test_token_cost_labels_and_warning(self):
        self.assertEqual(A.size_label(16 * 1024), '16 KB, ~4k tokens')
        self.assertNotIn('too big', A.token_cost(800000))
        self.assertIn('too big for one read (over 200k tokens)', A.token_cost(4 * 1024 * 1024))

    def test_elevator_fits_and_splits_mission_once(self):
        ss = A.mission_sentences()
        self.assertEqual(' '.join(ss), A.MISSION)
        hook = 'GridAtlas is an open-source browser map of UK renewable energy projects and the electricity grid around them.'
        lines = A.elevator(' '.join(ss[k] for k in A.ELEVATOR_MISSION),
                           [('Engine %d' % i, hook, 'https://example.org/repos/e%d.html (10 KB, ~3k tokens)' % i)
                            for i in range(6)], 'Sizes stand beside every link.')
        words = sum(1 for x in lines for w in x.split() if not w.startswith('http'))
        self.assertLessEqual(words, A.ELEVATOR_WORDS)
        self.assertEqual(sum(1 for x in lines if x.startswith('- **Engine')), 6)
        self.assertIn('map of UK renewable', '\n'.join(lines))  # hooks keep their meaning, not cut to a stub

    def test_shard_order_teaches_first(self):
        fs = [{'path': '.github/workflows/ci.yml', 'kind': 'workflow'}, {'path': 'tests/test_a.py', 'kind': 'test'},
              {'path': 'lib/util.js', 'n_dependents': 9}, {'path': 'lib/rare.js', 'n_dependents': 1},
              {'path': 'app/index.html', 'entry': True, 'published': 'https://x/app/'},
              {'path': 'tool/cli.py', 'entry': True}]
        got = [f['path'] for f in sorted(fs, key=A.shard_order)]
        self.assertEqual(got, ['app/index.html', 'tool/cli.py', 'lib/util.js', 'lib/rare.js',
                               '.github/workflows/ci.yml', 'tests/test_a.py'])


if __name__ == '__main__':
    unittest.main()