GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / gridatlas / tools/secondary

Import UKPN and 9 more files

A Python command-line tool in the secondary folder of GridAtlas that reads UKPN secondary site transformers, grid UKPN secondary and UKPN transformers, using SHA-256 from UK Power Networks open data.

642 lines of JavaScript and Python from gridatlas, gridmachine1, in 10 files. Topic: Grid network and substations. Section 449 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. Import UKPN energy-data · gridatlas / tools/secondary/import_ukpn.py lines 1–130
  2. Single-Line Diagram (SLD) Build electrical · gridatlas / tools/sld/build.mjs lines 1–42
  3. Single-Line Diagram (SLD) Build Test test · gridatlas / tools/sld/build.test.mjs lines 1–36
  4. Single-Line Diagram (SLD) Map Removal Cleanup Test test · gridatlas / tools/sld/map-removal-cleanup.test.mjs lines 1–20
  5. Single-Line Diagram (SLD) Mobile Arrival Card Browser render · gridatlas / tools/sld/mobile-arrival-card.browser.py lines 1–95
  6. Single-Line Diagram (SLD) Mobile Arrival Card Test test · gridatlas / tools/sld/mobile-arrival-card.test.mjs lines 1–55
  7. Single-Line Diagram (SLD) Retire GridAtlas Layout storage · gridatlas / tools/sld/retire-gridatlas-layout.mjs lines 1–53
  8. Learning Networks transform · gridatlas / tools/train/fixtures/learning-networks.mjs lines 1–15
  9. VEDIC Road Topology transform · gridatlas / tools/vedic/road-topology.mjs lines 1–78
  10. Verify Interconnector Arrival energy-data · gridmachine1 / 202609071322-linux-handover/rig-kit/verify-interconnector-arrival.mjs lines 1–118

Import UKPN

A Python command-line tool in the secondary folder of GridAtlas that reads UKPN secondary site transformers, grid UKPN secondary and UKPN transformers, using SHA-256 from UK Power Networks open data.

energy-datagridatlas / tools/secondary/import_ukpn.py · lines 1–130 of 130 · Entry point · pattern read_source (shared by 3 files)

What it does
It loads UKPN secondary site transformers, grid UKPN secondary, UKPN transformers and UKPN sites. Defines read_source, compile_sites, main, export. Uses libraries argparse, hashlib, json, math, zipfile. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'ukpn'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Inputs & outputs
In: data source: UK Power Networks open data; GeoJSON file ukpn-secondary-site-transformers.geojson; GeoJSON file grid_ukpn_secondary.geojson; Parquet file grid_ukpn_secondary.parquet; Parquet file ukpn_transformers.parquet; Parquet file ukpn_sites.parquet; DuckDB queries; command-line arguments. Out: Parquet file.
Downstream impact
Used directly by 2 files: Audit UKPN (gridatlas); UKPN Secondary Columnar Workflow (data-grid-gb).
What it achieves
It reads source (`read_source`) and compiles sites (`compile_sites`). Compile the pinned UKPN source into the existing GridAtlas Parquet contract. It reads `ukpn-secondary-site-transformers.geojson`. It accepts `--output`.
Why it matters
Imported by UKPN Secondary Columnar Workflow, from Data Grid GB. Run by Audit UKPN.
Application
gridatlas · tools/secondary · Python CLI
Uses
argparse, hashlib, json, math, zipfile, collections, pathlib, duckdb
Used by
run by Audit UKPN (script call), named by URL in UKPN Secondary Columnar Workflow (estate URL)
Produces
read_source, compile_sites, main
Defines here
read_source, compile_sites, main, export
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/secondary/import_ukpn.py:1-130 · blob 11f3cf36270ec95e6d952aced98a26ca38c4d97e · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Compile the pinned UKPN source into the existing GridAtlas Parquet contract.

Source rows are preserved; map points are grouped by exact secondary site FLOC.
Requires duckdb. Run in a working directory, not an immutable shell.
"""
import argparse
import hashlib
import json
import math
import zipfile
from collections import defaultdict
from pathlib import Path

SHA = 'c75933d86f4872a5f54712c0a945c283bb9038323a2ae9567df51ba3ce1b75c5'
SOURCE = 'grid_ukpn_secondary'
def read_source(path):
    if hashlib.sha256(path.read_bytes()).hexdigest() != SHA:
        raise ValueError('source archive hash mismatch')
    with zipfile.ZipFile(path) as z:
        raw = json.loads(z.read('ukpn-secondary-site-transformers.geojson'))
    assert raw['type'] == 'FeatureCollection' and len(raw['features']) == 74719
    return raw['features']

def compile_sites(rows):
    sites = defaultdict(list)
    ids = set()
    for f in rows:
        p = f['properties']
        site, tx = p['secondarysitefunctionallocation'], p['transformerfunctionallocation']
        assert site and tx and p['dno'] in ('EPN','SPN','LPN')
        ids.add(tx)
        sites[site].append(f)
    assert len(sites) == 56309 and len(ids) == 74712
    mapped = []
    points = 0
    for site, group in sorted(sites.items()):
        coords = set()
        dnos = {f['properties']['dno'] for f in group}
        assert len(dnos) == 1
        for f in group:
            g = f['geometry']
            if g is None:
                continue
            c = g['coordinates']
            assert g['type'] == 'Point' and len(c) == 2 and all(math.isfinite(x) for x in c)
            assert -11 <= c[0] <= 3 and 49.5 <= c[1] <= 61.5
            coords.add(tuple(c))
            points += 1
        assert len(coords) <= 1
        if not coords:
            continue
        voltage = sorted({f['properties']['primarywinding'] for f in group
                          if isinstance(f['properties']['primarywinding'], (int,float))
                          and f['properties']['primarywinding'] > 0})
        p = dict(name=site, type='Secondary substation (transformer register)',
                 operator='UK Power Networks ('+next(iter(dnos))+')',
                 voltage=', '.join(f'{v:g} kV primary' for v in voltage),
                 transformer_count=len({f['properties']['transformerfunctionallocation'] for f in group}),
                 source='UK Power Networks secondary site transformers',asset_class='secondary_substation')
        mapped.append(dict(type='Feature',id=site,geometry=dict(type='Point',coordinates=list(next(iter(coords)))),properties=p))
    assert len(mapped) == 54558 and points == 56685
    return mapped

def main():
    p = argparse.ArgumentParser()
    p.add_argument('archive',type=Path)
    p.add_argument('--output',type=Path,required=True)
    a = p.parse_args()
    rows = read_source(a.archive)
    mapped = compile_sites(rows)
    a.output.mkdir(parents=True,exist_ok=True)
    j=lambda x: json.dumps(x,ensure_ascii=True,separators=(',',':'))
    geo = a.output/'grid_ukpn_secondary.geojson'
    geo.write_text(j(dict(type='FeatureCollection',features=mapped))+'\n',encoding='utf-8')
    import duckdb
    db=duckdb.connect()
    db.execute("SET threads=1")
    db.execute("""CREATE TABLE layer AS SELECT
      unnest(?::VARCHAR[]) AS source_id, unnest(?::BIGINT[]) AS feature_index,
      unnest(?::VARCHAR[]) AS feature_id, unnest(?::VARCHAR[]) AS geometry_json,
      unnest(?::VARCHAR[]) AS properties_json""", [
        [SOURCE]*len(mapped), list(range(len(mapped))), [f['id'] for f in mapped],
        [j(f['geometry']) for f in mapped], [j(f['properties']) for f in mapped]])
    def export(query, name):
        target=a.output/name
        escaped=str(target).replace("'","''")
        db.execute(f"COPY ({query}) TO '{escaped}' (FORMAT PARQUET, COMPRESSION ZSTD)")
        return target
    out=export('SELECT * FROM layer ORDER BY feature_index','grid_ukpn_secondary.parquet')
    assert db.execute('SELECT count(*),count(distinct feature_id) FROM layer').fetchone()==(54558,54558)
    props=[f['properties'] for f in rows]
    db.execute("""CREATE TABLE transformers AS SELECT
      unnest(?::BIGINT[]) AS source_row, unnest(?::VARCHAR[]) AS feature_json,
      unnest(?::VARCHAR[]) AS site_id, unnest(?::VARCHAR[]) AS transformer_id,
      unnest(?::VARCHAR[]) AS dno, unnest(?::DOUBLE[]) AS longitude,
      unnest(?::DOUBLE[]) AS latitude""", [
        list(range(len(rows))), [j(f) for f in rows],
        [p['secondarysitefunctionallocation'] for p in props],
        [p['transformerfunctionallocation'] for p in props], [p['dno'] for p in props],
        [f['geometry']['coordinates'][0] if f['geometry'] is not None else None for f in rows],
        [f['geometry']['coordinates'][1] if f['geometry'] is not None else None for f in rows]])
    rawout=export('SELECT * FROM transformers ORDER BY source_row','ukpn_transformers.parquet')
    db.execute("""CREATE TABLE sites AS SELECT site_id, min(dno) AS dno,
       count(*) AS source_records, count(DISTINCT transformer_id) AS transformer_count,
       min(longitude) AS longitude, min(latitude) AS latitude
       FROM transformers GROUP BY site_id""")
    sitesout=export('SELECT * FROM sites ORDER BY site_id','ukpn_sites.parquet')
    counts=db.execute("""SELECT count(*), count(DISTINCT transformer_id),
       count(DISTINCT site_id), count(longitude) FROM transformers""").fetchone()
    site_counts=db.execute('SELECT count(*), count(longitude) FROM sites').fetchone()
    assert counts==(74719,74712,56309,56685)
    assert site_counts==(56309,54558)
    assert db.execute('SELECT count(*) FROM sites WHERE longitude IS NULL AND latitude IS NULL').fetchone()[0]==1751
    assert db.execute('SELECT count(*) FROM transformers t ANTI JOIN sites s USING (site_id)').fetchone()[0]==0
    manifest=dict(schema='gridatlas.ukpn-secondary.v1', source_sha256=SHA,
      source_revision='2502549fed826106c70865047a540a170dd68919',
      source_url='https://ukpowernetworks.opendatasoft.com/explore/assets/ukpn-secondary-site-transformers/',
      source_updated='2025-11-27', acquisition_date='2026-12-01',
      licence='CC BY 4.0', attribution='UK Power Networks, UK Power Networks Secondary Site Transformers, 27 November 2025',
      transformation='Source records retained in original order; exact FLOC group; no coordinate inference; deduplicate map sites, preserve null locations and raw attributes; installed ratings are not headroom.',
      duckdb_version=duckdb.__version__, source_rows=counts[0], distinct_transformers=counts[1],
      distinct_sites=counts[2], point_rows=counts[3], map_rows=site_counts[1],
      unplaced_sites=site_counts[0]-site_counts[1],
      artifacts=[dict(path=x.name,bytes=x.stat().st_size,sha256=hashlib.sha256(x.read_bytes()).hexdigest())
        for x in (geo,out,rawout,sitesout)])
    (a.output/'manifest.json').write_text(j(manifest)+'\n',encoding='utf-8')
    print(j(manifest))

if __name__=='__main__':
    main()

Single-Line Diagram (SLD) Build

A JavaScript module in the tools folder of GridAtlas that reads generations, using SHA-256.

electricalgridatlas / tools/sld/build.mjs · lines 1–42 of 42 · pattern pinned (shared by 7 files)

What it does
It loads generations. Defines digest, buildSld, pinned, arg. Uses libraries node:fs, node:path, node:assert/strict, node:crypto, node:url. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'sld'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. README: "`build.mjs` restores source reproducibility for the accepted V9.190 and V9.191 SLD cartridges."
Inputs & outputs
In: JSON file generations.json; command-line arguments.
Downstream impact
Used directly by 5 files: Single-Line Diagram (SLD) Build Test (gridatlas); Single-Line Diagram (SLD) Map Removal Cleanup Test (gridatlas); Single-Line Diagram (SLD) Mobile Arrival Card Test (gridatlas); Cut Grid Explorer (gridatlas); and 1 more. Reached from 3 other entry points, including GridAtlas PR File Size Guard Workflow (gridatlas); CI PR Gate (gridatlas); Map Promotion Rehearsal (gridatlas).
What it achieves
It builds SLD (`buildSld`) and is built from the digest step (`digest`) and the pinned step (`pinned`). Rebuild the MAP receiver from a pinned immutable baseline and explicit source edits.
Why it matters
Run by Cut Grid Explorer and Grid Explorer Proof. Checked by 3 tests, including Single-Line Diagram (SLD) Build Test.
Application
gridatlas · tools/sld · JavaScript module
Uses
node:fs, node:path, node:assert/strict, node:crypto, node:url
Used by
imported by Single-Line Diagram (SLD) Build Test (import), imported by Single-Line Diagram (SLD) Map Removal Cleanup Test (import), imported by Single-Line Diagram (SLD) Mobile Arrival Card Test (import), run by Cut Grid Explorer (script call), run by Grid Explorer Proof (script call)
Produces
buildSld
Defines here
digest, buildSld, pinned, arg
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/sld/build.mjs:1-42 · blob aadf116ca4af0005a9c587236a7bd2f9b617b122 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
/** Rebuild the MAP receiver from a pinned immutable baseline and explicit source edits. */
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import {createHash} from 'node:crypto';
import {fileURLToPath} from 'node:url';

const ROOT=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'../..');
const digest=b=>createHash('sha256').update(b).digest('hex');
export function buildSld(generation,root=ROOT) {
  const registry=JSON.parse(fs.readFileSync(path.join(root,'tools/sld/generations.json')));
  const entry=registry.generations[generation];
  assert.ok(entry,`No SLD source recipe for ${generation}`);
  const pinned=input=>{
    const bytes=fs.readFileSync(path.join(root,input.path));
    assert.equal(digest(bytes),input.sha256,`Source pin drift: ${input.path}`);
    return bytes.toString('utf8');
  };
  let source=pinned(entry.base);
  const owner=pinned(entry.owner);
  const edits=JSON.parse(fs.readFileSync(path.join(root,entry.edits)));
  assert.ok(Array.isArray(edits)&&edits.length>0);
  for(const [index,edit] of edits.entries()) {
    assert.equal(typeof edit.before,'string');assert.ok(edit.before.length);
    assert.equal(typeof edit.after,'string');
    const at=source.indexOf(edit.before);
    assert.ok(at>=0,`Source edit ${index} no longer matches`);
    assert.equal(source.indexOf(edit.before,at+1),-1,`Source edit ${index} is ambiguous`);
    source=source.slice(0,at)+edit.after+source.slice(at+edit.before.length);
  }
  const built=Buffer.from(entry.header+owner+'\n'+source);
  assert.equal(digest(built),entry.output_sha256,'Rebuilt SLD differs from its registered output pin');
  return built;
}

if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)) {
  const arg=name=>process.argv[process.argv.indexOf(name)+1];
  assert.ok(process.argv.includes('--gen')&&process.argv.includes('--out'),'Use --gen G --out NEW_FILE');
  const built=buildSld(arg('--gen'));
  fs.writeFileSync(arg('--out'),built,{flag:'wx'});
  console.log(`SLD source rebuild: ${built.length} bytes sha256 ${digest(built)}`);
}

Single-Line Diagram (SLD) Build Test

A test in the tools folder of GridAtlas that checks Single-Line Diagram (SLD) Build.

testgridatlas / tools/sld/build.test.mjs · lines 1–36 of 36 · Entry point

What it does
It tests its inputs. Uses libraries node:test, node:assert/strict, node:fs, node:os, node:path. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'sld'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: JSON file generations.json.
Downstream impact
Used directly by 2 files: CI PR Gate (gridatlas); GridAtlas PR File Size Guard Workflow (gridatlas). Reached from 1 other entry point, including Map Promotion Rehearsal (gridatlas).
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
Run by CI PR Gate and GridAtlas PR File Size Guard Workflow.
Application
gridatlas · tools/sld · test
Uses
Single-Line Diagram (SLD) Build (import), node:test, node:assert/strict, node:fs, node:os, node:path, node:url
Used by
run by CI PR Gate (script call), run by GridAtlas PR File Size Guard Workflow (workflow run)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/sld/build.test.mjs:1-36 · blob 877f5d0f53bec1c60e7509841c84d27ba844e3fb · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import {fileURLToPath} from 'node:url';
import {buildSld} from './build.mjs';
const ROOT=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'../..');
const registry=JSON.parse(fs.readFileSync(path.join(ROOT,'tools/sld/generations.json')));

test('rebuilds every registered generation without the expected cartridge in its source tree',()=>{
  const root=fs.mkdtempSync(path.join(os.tmpdir(),'gridatlas-sld-source-'));
  try {
    const entry=registry.generations['202611161720'];
    const inputs = new Set(['tools/sld/generations.json', ...Object.values(registry.generations).flatMap(e => [e.base.path, e.owner.path, e.edits])]);
    for(const rel of inputs) {
      const to=path.join(root,rel);fs.mkdirSync(path.dirname(to),{recursive:true});fs.copyFileSync(path.join(ROOT,rel),to);
    }
    for(const generation of Object.keys(registry.generations)) {
      const expected=`atlas/cartridges/${generation}-sld-sandbox-v9-8.js`;
      assert.equal(fs.existsSync(path.join(root,expected)),false);
      assert.deepEqual(buildSld(generation,root),fs.readFileSync(path.join(ROOT,expected)));
    }
    // A changed source and a dropped edit must both fail, rather than copy the expected output.
    fs.appendFileSync(path.join(root,entry.base.path),'\n');
    assert.throws(()=>buildSld('202611161720',root),/Source pin drift/);
    fs.copyFileSync(path.join(ROOT,entry.base.path),path.join(root,entry.base.path));
    const edits=JSON.parse(fs.readFileSync(path.join(root,entry.edits)));edits.pop();
    fs.writeFileSync(path.join(root,entry.edits),JSON.stringify(edits));
    assert.throws(()=>buildSld('202611161720',root),/differs from its registered output pin/);
  } finally {assert.ok(path.resolve(root).startsWith(path.resolve(os.tmpdir())+path.sep));fs.rmSync(root,{recursive:true,force:true});}
});

test('unregistered generations fail closed',()=>{
  assert.throws(()=>buildSld('202611160000'),/No SLD source recipe/);
});

Single-Line Diagram (SLD) Map Removal Cleanup Test

A test in the tools folder of GridAtlas that checks Single-Line Diagram (SLD) Build. It is built from the extract step (`extract`) and the fixture step (`fixture`).

testgridatlas / tools/sld/map-removal-cleanup.test.mjs · lines 1–20 of 20 · Entry point · pattern extract (shared by 8 files)

What it does
It tests its inputs. Defines extract, fixture. Uses libraries node:test, node:assert/strict, node:fs, node:vm. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'sld'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: JSON file map-removal-cleanup-edits.json.
Downstream impact
Used directly by 1 file: GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
Regression over the real rebuilt SLD functions, including its inherited failure. It reads `./src/map-removal-cleanup-edits.json`.
Why it matters
Run by GridAtlas PR File Size Guard Workflow.
Application
gridatlas · tools/sld · test
Uses
Single-Line Diagram (SLD) Build (import), node:test, node:assert/strict, node:fs, node:vm
Used by
run by GridAtlas PR File Size Guard Workflow (workflow run)
Produces
extract, fixture
Defines here
extract, fixture
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/sld/map-removal-cleanup.test.mjs:1-20 · blob 655e1c4f2123aba25e521305614507b572db45e3 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
/** Regression over the real rebuilt SLD functions, including its inherited failure. */
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import vm from 'node:vm';
import {buildSld} from './build.mjs';
const original=buildSld('202611161720').toString('utf8');
const edits=JSON.parse(fs.readFileSync(new URL('./src/map-removal-cleanup-edits.json',import.meta.url)));
let modified=original;for(const e of edits){assert.equal(modified.split(e.before).length-1,1);modified=modified.replace(e.before,e.after);}new vm.Script(modified);
const extract=(source,name,indent=2)=>{const pad=' '.repeat(indent),start=source.indexOf(pad+'function '+name+'(');assert.ok(start>=0);return source.slice(start,source.indexOf('\n'+pad+'}',start)+indent+2);};
function fixture({removed=false,other=false}={}){
 const calls=[],map={getSource(){calls.push('getSource');if(removed)throw Error('style already destroyed');return{setData(){calls.push('setData');}};}},current=other?{}:map;
 const c={map,capturedMap:current,popupWatcher:{disconnect(){calls.push('disconnect');}},link:{last_selection:{name:'Before'},links_drawn:5,grid_scope:{before:true}},SRC:'route',SRC_NODES:'nodes',SRC_PIN:'pin',SCOPE_SRC:'scope',SCOPE_BLOCK:'scope-block',scopeResult:{before:true},currentRepdRef:'2470',currentDeclared:{},currentNeso:{},currentNearest400:{},document:{querySelectorAll(){return[];}},in  … [line shortened here: 831 characters; full line on GitHub]
 vm.createContext(c);vm.runInContext(['clearLinks','clearScope','clearPin'].map(n=>extract(modified,n)).join('\n')+'\n'+extract(modified,'cleanupRemovedMap',4),c);return{c,calls,map};
}
test('additive recipe applies exactly once and compiled successor preserves immutable base',()=>{assert.equal(original.includes('function cleanupRemovedMap'),false);assert.ok(modified.includes("map.on('remove', cleanupRemovedMap)"));assert.equal(edits.length,1);});
test('baseline clearLinks reproduces the inherited destroyed-style error',()=>{const f=fixture({removed:true});assert.throws(()=>f.c.clearLinks(),/style already destroyed/);assert.ok(f.calls.includes('getSource'));});
test('removed-map cleanup cancels work and clears state without any destroyed-style access',()=>{const f=fixture({removed:true});f.c.cleanupRemovedMap();assert.equal(f.c.capturedMap,null);assert.equal(f.calls.includes('getSource'),false);assert.deepEqual(f.calls,['disconnect','invalidate:clear','cancel-animation','disarm-card','remove-fallback','remove-block','clear-engine']);assert.equal(f.c.link  … [line shortened here: 710 characters; full line on GitHub]
test('removal of an obsolete map cannot clear a newer map selection',()=>{const f=fixture({removed:true,other:true});const current=f.c.capturedMap;f.c.cleanupRemovedMap();assert.equal(f.c.capturedMap,current);assert.deepEqual(f.calls,['disconnect']);assert.equal(f.c.link.last_selection.name,'Before');});
test('ordinary live clear still resets all existing route/node/pin source data',()=>{const f=fixture();f.c.clearLinks();assert.equal(f.calls.filter(c=>c==='setData').length,3);assert.equal(f.c.link.last_selection,null);});

Single-Line Diagram (SLD) Mobile Arrival Card Browser

A Python module in the tools folder of GridAtlas that reads mobile arrival card edits, using SHA-256. It is built from the candidate step (`candidate`).

rendergridatlas / tools/sld/mobile-arrival-card.browser.py · lines 1–95 of 95 · Not reached from any entry point (candidate for review) · pattern candidate (shared by 5 files)

What it does
It loads mobile arrival card edits. Defines main, candidate. Uses libraries asyncio, hashlib, json, os, pathlib. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'sld'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: JSON file mobile-arrival-card-edits.json; JSON file current.json. Out: JSON file receipt.json.
What it achieves
Only real-browser proof; intercepts pointer/hash and one cartridge.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · tools/sld · Python module
Uses
GridAtlas — Index Page (estate URL), GridAtlas — Atlas Page (estate URL), asyncio, hashlib, json, os, pathlib, datetime, playwright.async_api
Used by
none found
Produces
main
Defines here
main, candidate
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/sld/mobile-arrival-card.browser.py:1-95 · blob 0f7231512dd9a67c7cc84fe9e74fc072dc590dbd · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
"""Candidate-only real-browser proof; intercepts pointer/hash and one cartridge.

Run with the QA Python environment containing Playwright. This is not public
release acceptance: all other native Atlas assets use their actual URLs.
"""
import asyncio
import hashlib
import json
import os
from pathlib import Path
from datetime import datetime, timezone
from playwright.async_api import async_playwright

ROOT = Path(__file__).resolve().parents[2]
OUT = Path(os.environ.get('MOBILE_CARD_OUTPUT', str(ROOT / 'work/mobile-arrival-card')))


async def main():
    OUT.mkdir(parents=True, exist_ok=True)
    source = (ROOT / 'atlas/cartridges/202611161720-sld-sandbox-v9-8.js').read_text(encoding='utf-8')
    for edit in json.loads((ROOT / 'tools/sld/src/mobile-arrival-card-edits.json').read_text(encoding='utf-8')):
        assert source.count(edit['before']) == 1
        source = source.replace(edit['before'], edit['after'])
    pointer = json.loads((ROOT / 'atlas/current.json').read_text(encoding='utf-8'))
    digest = hashlib.sha256(source.encode()).hexdigest()
    for entry in pointer['cartridges']:
        if entry['id'] == 'sld-sandbox':
            entry['sha256'] = digest
    receipt = {'mode': 'CANDIDATE_INTERCEPTION_NOT_PUBLIC_ACCEPTANCE', 'startedUTC': datetime.now(timezone.utc).isoformat(), 'candidateSha256': digest, 'errors': [], 'requestFailures': [], 'interceptions': []}
    try:
        async with async_playwright() as p:
            browser = await p.chromium.launch(channel='chrome', headless=True, args=['--use-gl=angle', '--use-angle=swiftshader', '--enable-webgl', '--ignore-gpu-blocklist'])
            context = await browser.new_context(viewport={'width': 390, 'height': 844}, has_touch=True, is_mobile=True)
            page = await context.new_page()
            page.on('pageerror', lambda e: receipt['errors'].append(str(e)))
            page.on('requestfailed', lambda r: receipt['requestFailures'].append({'url': r.url, 'failure': r.failure}))

            async def candidate(route):
                url = route.request.url
                if url.split('?')[0].endswith('/atlas/current.json'):
                    receipt['interceptions'].append(url)
                    await route.fulfill(body=json.dumps(pointer), content_type='application/json')
                elif url.split('?')[0].endswith('/202611161720-sld-sandbox-v9-8.js'):
                    receipt['interceptions'].append(url)
                    await route.fulfill(body=source, content_type='text/javascript')
                else:
                    await route.continue_()
            await context.route('https://ventusltd.github.io/gridatlas/**', candidate)
            await page.goto('https://ventusltd.github.io/gridatlas/atlas/?repd_ref=2470&technology=wind_offshore&latitude=52.1374391&longitude=2.1708996&zoom=12', wait_until='domcontentloaded', timeout=60000)
            print('receiver loaded', flush=True)
            summary = page.locator('.gridatlas-arrival-summary').first
            await summary.wait_for(timeout=120000)
            await page.wait_for_function("() => window.__GRIDATLAS_NEON_LINKS__?.last_selection?.name === 'East Anglia 3 (EA 3)'", timeout=120000)
            selection = await page.evaluate('() => window.__GRIDATLAS_NEON_LINKS__.last_selection')
            assert selection['name'] == 'East Anglia 3 (EA 3)'
            text = await summary.inner_text()
            assert selection['nearest_name'] in text
            assert f"{selection['nearest_km']:.1f} km straight-line" in text
            assert 'Screening only; connection unverified.' in text
            popup = page.locator('.maplibregl-popup').first
            assert 'gridatlas-min' in (await popup.get_attribute('class'))
            details = page.get_by_role('button', name='Show project details', exact=True)
            box = await details.bounding_box()
            assert box['height'] >= 44 and box['width'] >= 44
            rect = await summary.bounding_box()
            assert rect['x'] >= 0 and rect['y'] >= 0 and rect['x'] + rect['width'] <= 391 and rect['y'] + rect['height'] <= 845
            assert await summary.evaluate('(e) => {const r=e.getBoundingClientRect(); const hit=document.elementFromPoint(r.x+r.width/2,r.y+r.height/2);return e===hit||e.contains(hit)}')
            await page.screenshot(path=str(OUT / 'compact.png'))
            await details.tap()
            await page.locator('.neon-km').first.wait_for(state='visible')
            assert 'gridatlas-min' not in (await popup.get_attribute('class'))
            assert await page.get_by_role('button', name='Minimise project details', exact=True).get_attribute('aria-expanded') == 'true'
            await page.wait_for_timeout(12000)
            assert 'gridatlas-min' not in (await popup.get_attribute('class')), 'identity reconciliation must retain reader restore'
            await page.screenshot(path=str(OUT / 'details.png'))
            await page.get_by_role('button', name='Minimise project details', exact=True).tap()
            assert 'gridatlas-min' in (await popup.get_attribute('class'))
            await page.set_viewport_size({'width': 844, 'height': 390})
            await page.wait_for_timeout(500)
            rect = await summary.bounding_box()
            assert rect['x'] >= 0 and rect['y'] >= 0 and rect['x'] + rect['width'] <= 845 and rect['y'] + rect['height'] <= 391
            assert not await page.evaluate('() => document.documentElement.scrollWidth > innerWidth')
            assert not receipt['errors']
            assert len(receipt['interceptions']) >= 2
            receipt.update({'result': 'PASS', 'renderedSummary': text, 'selection': selection, 'firstDetailsTouch': 'PASS', 'manualRestoreSurvives12Seconds': True, 'rotation': '844x390 bounded', 'physicalHandset': 'UNKNOWN', 'finishedUTC': datetime.now(timezone.utc).isoformat()})
            await browser.close()
    except Exception as e:
        receipt.update({'result': 'FAIL', 'failure': str(e)})
        raise
    finally:
        (OUT / 'receipt.json').write_text(json.dumps(receipt, indent=2), encoding='utf-8')
        print(json.dumps({k: v for k, v in receipt.items() if k not in ['requestFailures', 'interceptions']}), flush=True)


asyncio.run(main())

Single-Line Diagram (SLD) Mobile Arrival Card Test

A test in the tools folder of GridAtlas that checks Single-Line Diagram (SLD) Build.

testgridatlas / tools/sld/mobile-arrival-card.test.mjs · lines 1–55 of 55 · Entry point · pattern fixture (shared by 30 files)

What it does
It tests substations. Defines fixture. Uses libraries node:test, node:assert/strict, node:fs, node:vm. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'sld'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: substations.
Inputs & outputs
In: JSON file mobile-arrival-card-edits.json.
Downstream impact
Used directly by 1 file: GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
Defines `fixture`. It reads `./src/mobile-arrival-card-edits.json`.
Why it matters
Run by GridAtlas PR File Size Guard Workflow.
Application
gridatlas · tools/sld · test
Uses
Single-Line Diagram (SLD) Build (import), node:test, node:assert/strict, node:fs, node:vm
Used by
run by GridAtlas PR File Size Guard Workflow (workflow run)
Produces
fixture
Defines here
fixture
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/sld/mobile-arrival-card.test.mjs:1-55 · blob 66b37251e2a1965352d15acc024083a6c8324083 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import vm from 'node:vm';
import {buildSld} from './build.mjs';

const edits = JSON.parse(fs.readFileSync(new URL('./src/mobile-arrival-card-edits.json', import.meta.url)));
const accepted = buildSld('202611161720').toString('utf8');
const helper = edits[0].after.replace('  function addCardBar(content) {\n', '');
function fixture(minimised = true) {
  const button = {style: {}, attrs: {}, setAttribute(k, v) { this.attrs[k] = v; }};
  const label = {style: {}, children: [], querySelector() { return this.children[0]; }, appendChild(n) { this.children.push(n); }};
  const popup = {classList: {contains() { return minimised; }}, querySelector() { return button; }};
  const content = {closest() { return popup; }, querySelector() { return label; }};
  const context = {document: {createElement() { return {style: {}, setAttribute() {}}; }}};
  vm.createContext(context); vm.runInContext(helper, context);
  return {context, content, button, label};
}
test('all edits apply exactly once to rebuilt accepted source and compile without changing history', () => {
  let source = accepted;
  for (const edit of edits) {
    assert.equal(source.split(edit.before).length - 1, 1);
    source = source.replace(edit.before, edit.after);
  }
  new vm.Script(source);
  assert.equal(accepted.includes('function renderArrivalCardSummary'), false);
  assert.ok(source.includes('cardPreference = { key: cardPreferenceKey(), minimised:'));
  assert.ok(source.includes('? cardPreference.minimised'));
});
test('collapsed card exposes nearest name, distance and screening scope with labelled Details', () => {
  const f = fixture();
  f.context.renderArrivalCardSummary(f.content, [{name: 'Nearest A', km: 38.627}], 'to-substation');
  assert.equal(f.label.children[0].textContent, 'Nearest mapped substation: Nearest A | 38.6 km straight-line. Screening only; connection unverified.');
  assert.equal(f.button.textContent, 'Details');
  assert.equal(f.button.attrs['aria-expanded'], 'false');
  assert.equal(f.button.style.minHeight, '44px');
  assert.equal(f.button.attrs['aria-label'], 'Show project details');
});
test('a replacement selection updates one summary without stale name or HTML injection', () => {
  const f = fixture(false);
  f.context.renderArrivalCardSummary(f.content, [{name: 'Old', km: 1}], 'to-substation');
  f.context.renderArrivalCardSummary(f.content, [{name: '<img src=x>', km: 0}], 'from-substation');
  assert.equal(f.label.children.length, 1);
  assert.equal(f.label.children[0].textContent, 'Nearest mapped project: <img src=x> | 0.0 km straight-line. Screening only; connection unverified.');
  assert.equal(f.button.textContent, 'Map');
  assert.equal(f.button.attrs['aria-expanded'], 'true');
});
test('beyond-radius distance stays visible and absent/nonfinite distance stays unknown', () => {
  const f = fixture();
  const links = []; links.beyondRadiusNearest = {name: 'Beyond', km: 52};
  f.context.renderArrivalCardSummary(f.content, links, 'to-substation');
  assert.match(f.label.children[0].textContent, /Beyond \| 52.0 km straight-line/);
  f.context.renderArrivalCardSummary(f.content, [{name: 'Unknown', km: NaN}], 'to-substation');
  assert.equal(f.label.children[0].textContent, 'No mapped substation distance available. Connection unverified.');
});

Single-Line Diagram (SLD) Retire GridAtlas Layout

A JavaScript module in the tools folder that reads substations. It is built from the retire layout helper (`retireLayout`) and the exact step (`exact`).

storagegridatlas / tools/sld/retire-gridatlas-layout.mjs · lines 1–53 of 53 · pattern exact (shared by 7 files)

What it does
It loads substations. Defines retireLayout, exact. Uses libraries node:fs, node:path, node:url. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'layout'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: substations.
Inputs & outputs
In: command-line arguments.
Downstream impact
Used directly by 1 file: Single-Line Diagram (SLD) Sandbox Proof (gridatlas). Reached from 1 other entry point, including GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
Surgical no-layout derivative from immutable V9.191 SLD carrier.
Why it matters
Imported by Single-Line Diagram (SLD) Sandbox Proof.
Application
gridatlas · tools/sld · JavaScript module
Uses
node:fs, node:path, node:url
Used by
imported by Single-Line Diagram (SLD) Sandbox Proof (import)
Produces
sourcePath, outputPath, retireLayout
Defines here
retireLayout, exact
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/sld/retire-gridatlas-layout.mjs:1-53 · blob c6a8cfc46a42893e22d41fd7b75e277150c713e1 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
/* Surgical no-layout derivative from immutable V9.191 SLD carrier.
 * Exact transformations protect the complete Grid Engine from truncation.
 */
import fs from 'node:fs';
import path from 'node:path';
import {fileURLToPath} from 'node:url';
const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'../..');
export const sourcePath='atlas/cartridges/202611161720-sld-sandbox-v9-8.js';
export const outputPath='atlas/modules/202611222130-sld-without-layout.js';
export const retireLayout = function retireLayout(source){
  function exact(a,b,description){
    const n=source.split(a).length-1;
    if(n!==1)throw Error(description+': expected one source anchor, got '+n);
    source=source.replace(a,b);
  }
  exact('        + `<button class="neon-layout" type="button">Lay out a scheme here &#9656;</button>`\n',
        '', 'layout card entry');
  exact('  function renderSldPanel() {\n',
        '  function renderSldPanel() {\n    return; // retired: layout panel never mounted\n',
        'layout panel guard');
  exact('  function openSldAt(map, gridNode, name, voltage) {\n',
        '  function openSldAt(map, gridNode, name, voltage) {\n    return false; // retired: no substation-triggered layout\n',
        'direct substation layout entry');
  exact('  function openSldFromProject(map, selection) {\n',
        '  function openSldFromProject(map, selection) {\n    return false; // retired: no project-triggered layout\n',
        'project layout entry');
  const start='  function installSld(map) {\n';
  const end='\n  }\n})();';
  const i=source.indexOf(start),j=i<0?-1:source.indexOf(end,i);
  if(i<0||j<0||source.indexOf(start,i+1)>=0)throw Error('installSld boundaries not unique');
  const removed=source.slice(i,j+5);
  for(const required of ['installSldStyles();','ensureSldLayers(map);','attachSldDragging(map);','openSldAt(map, at, properties.name','keepLayersInFullscreen();','armCorridorGestures(map);'])if(!removed.includes(required))throw Error('installSld evidence drift: '+required);
  const kept='  function installSld(map) {\n'
    +'    // Preserve fullscreen layers and corridors, not Layout Sandbox UI.\n'
    +'    try { keepLayersInFullscreen(); }\n'
    +"    catch (error) { link.failures.push('fullscreen: ' + String(error?.message || error)); }\n"
    +'    try { armCorridorGestures(map); }\n'
    +"    catch (error) { link.failures.push('corridor sheet: ' + String(error?.message || error)); }\n"
    +'  }';
  source=source.slice(0,i)+kept+source.slice(j+5);
  return source;
};
if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)){
 const expected=retireLayout(fs.readFileSync(path.join(root,sourcePath),'utf8'));
 const file=path.join(root,outputPath);
 if(process.argv.includes('--check')){
   if(fs.readFileSync(file,'utf8')!==expected)throw Error('layout retirement generated bytes differ');
   console.log('PASS deterministic GridAtlas Layout Sandbox retirement: '+Buffer.byteLength(expected)+' bytes');
 }else{
   fs.writeFileSync(file,expected);
   console.log('wrote '+outputPath);
 }
}

Learning Networks

A JavaScript module in the fixtures folder of GridAtlas that works with train learning fixture (`trainLearningFixture`). It is built from the train learning fixture helper (`trainLearningFixture`).

transformgridatlas / tools/train/fixtures/learning-networks.mjs · lines 1–15 of 15 · pattern trainLearningFixture (shared by 2 files)

What it does
It calculates its inputs. Defines trainLearningFixture.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Downstream impact
Used directly by 1 file: Route Plan Test (gridatlas). Reached from 1 other entry point, including GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
Original fictional teaching networks; no railway geography, names or artwork.
Why it matters
Checked by Route Plan Test.
Application
gridatlas · tools/train/fixtures · JavaScript module
Uses
none found
Used by
imported by Route Plan Test (import)
Produces
trainLearningFixture
Defines here
trainLearningFixture
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/train/fixtures/learning-networks.mjs:1-15 · blob 765a321f35bd272e64e1d62d8d34e53e857ad4ce · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/** Original fictional teaching networks; no railway geography, names or artwork. */
export function trainLearningFixture(kind = 'local') {
  const names = kind === 'express' ? ['Harbour', 'Highland', 'Far Reach']
    : kind === 'branch' ? ['Junction', 'West Branch', 'Junction', 'East Branch']
    : ['Central', 'Interchange', 'Gardens', 'Terminus'];
  const spacing = kind === 'express' ? 2 : 0.04;
  return {schema: 'gridatlas.train.fixture.v1', synthetic: true,
    title: kind === 'express' ? 'Fictional express learning journey'
      : kind === 'branch' ? 'Fictional branch and junction journey' : 'Fictional local and interchange journey',
    stops: names.map((name, i) => ({stationId: 'synthetic-' + name.toLowerCase().replaceAll(' ', '-'),
      id: 'synthetic-' + name.toLowerCase().replaceAll(' ', '-'), stopId: 'visit-' + i, name, kv: 400,
      at: [kind === 'branch' && i === 2 ? -1 : -1 + i * spacing, 52 + (i % 2) * spacing / 2],
      source: 'SYNTHETIC_TEACHING_FIXTURE'})),
    note: 'Original invented example. Lines require the same explicit simulated-journey action; no real electrical or railway connection is asserted.'};
}

VEDIC Road Topology

A JavaScript module in the tools folder of GridAtlas that works with motorways. It compiles topology (`compileTopology`) and turns allowed (`turnAllowed`).

transformgridatlas / tools/vedic/road-topology.mjs · lines 1–78 of 78 · Not reached from any entry point (candidate for review) · pattern direction (shared by 2 files)

What it does
It calculates motorways. Defines 7 functions or classes, including id, tags, direction, eligible, compileTopology.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'vedic'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). Domain terms in the code: motorways.
Downstream impact
Used directly by 2 files: VEDIC Regional Stream Test (gridatlas); VEDIC Snapshot Routing (gridatlas).
What it achieves
Conservative, source-ID-preserving topology pilot; not a legal-route certification.
Why it matters
Imported by VEDIC Snapshot Routing. Checked by VEDIC Regional Stream Test.
Application
gridatlas · tools/vedic · JavaScript module
Uses
none found
Used by
imported by VEDIC Regional Stream Test (import), imported by VEDIC Snapshot Routing (import)
Produces
compileTopology
Defines here
id, tags, direction, eligible, compileTopology, add, turnAllowed
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/vedic/road-topology.mjs:1-78 · blob bae9caf00461b033d789f6e165f7396ae90298f5 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
// Conservative, source-ID-preserving topology pilot; not a legal-route certification.
const WALK=new Set(["residential","living_street","service","unclassified","tertiary","secondary","primary","footway","path","pedestrian","steps","track"]);
const DRIVE=new Set(["motorway","motorway_link","trunk","trunk_link","primary","primary_link","secondary","secondary_link","tertiary","tertiary_link","residential","living_street","service","unclassified"]);
const permit=new Set(["yes","designated","permissive"]);
const deny=new Set(["no","private","destination","customers","delivery","agricultural","forestry"]);
const id=x=>typeof x==="string"&&/^[1-9][0-9]*$/.test(x);
const tags=x=>x&&typeof x==="object"&&!Array.isArray(x)?x:{};
function direction(t,mode){
  const keys=mode==="walking"?["oneway:foot"]:["oneway:motorcar","oneway:motor_vehicle","oneway"];
  const v=keys.map(k=>t[k]).find(x=>x!==undefined);
  if(v===undefined)return mode==="driving"&&(t.junction==="roundabout"||t.highway==="motorway"||t.highway==="motorway_link")?1:0;
  return ["yes","true","1"].includes(v)?1:v==="-1"?-1:["no","false","0"].includes(v)?0:null;
}
function eligible(t,mode){
  if(Object.keys(t).some(k=>k.endsWith(":conditional")&&/^(access|vehicle|motor_vehicle|motorcar|foot|oneway)/.test(k)))return false;
  const keys=mode==="walking"?["foot","access"]:["motorcar","motor_vehicle","vehicle","access"];
  const v=keys.map(k=>t[k]).find(x=>x!==undefined);
  if(v!==undefined&&(!permit.has(v)||deny.has(v)))return false;
  return (mode==="walking"?WALK:DRIVE).has(t.highway)&&t.area!=="yes"&&t.construction===undefined;
}
export function compileTopology(source,mode,{maxNodes=50000,maxWays=10000,maxRelations=10000,maxEdges=100000,maxWayRefs=500000}={}){
  if(!["walking","driving"].includes(mode))throw Error("mode");
  const {nodes,ways,relations}=source;
  if(!Array.isArray(nodes)||!Array.isArray(ways)||!Array.isArray(relations)||nodes.length>maxNodes||ways.length>maxWays||relations.length>maxRelations)throw Error("source budget");
  const vertices=new Map(),edges=[],byWay=new Map(),byEdge=new Map(),restrictions=new Map(),issues=[];
  const wayIds=new Set(),relationIds=new Set();let refs=0;
  for(const n of nodes){
    if(!id(n.id)||vertices.has(n.id)||!Number.isFinite(n.lat)||Math.abs(n.lat)>90||!Number.isFinite(n.lon)||Math.abs(n.lon)>180)throw Error("invalid node");
    vertices.set(n.id,n);
  }
  const add=(w,k,a,b,d)=>{
    if(edges.length>=maxEdges)throw Error("edge budget");
    const e={id:w.id+":"+k+":"+d,way:w.id,from:a,to:b,direction:d};
    edges.push(e);byEdge.set(e.id,e);
    if(!byWay.has(w.id))byWay.set(w.id,[]);byWay.get(w.id).push(e);
  };
  for(const w of ways){
    if(!id(w.id)||wayIds.has(w.id)||!Array.isArray(w.nodes))throw Error("invalid way");
    wayIds.add(w.id);refs+=w.nodes.length;if(refs>maxWayRefs)throw Error("way reference budget");
    const t=tags(w.tags);if(!eligible(t,mode))continue;
    const d=direction(t,mode);if(d===null){issues.push("unknown-direction:"+w.id);continue}
    for(let k=1;k<w.nodes.length;k++){
      const a=w.nodes[k-1],b=w.nodes[k];
      if(!vertices.has(a)||!vertices.has(b)){issues.push("missing-node:"+w.id+":"+k);continue}
      if(a===b)continue;
      // A coordinate crossing is not a shared node. Retain original node identities, even if coordinates coincide.
      if(d!==-1)add(w,k,a,b,1);
      if(d!==1)add(w,k,b,a,-1);
    }
  }
  for(const r of relations){
    if(!id(r.id)||relationIds.has(r.id))throw Error("invalid relation");relationIds.add(r.id);
    const t=tags(r.tags);if(t.type!=="restriction"&&!String(t.type??"").startsWith("restriction:"))continue;
    const except=String(t.except??"").split(";").map(x=>x.trim());
    if(mode==="walking"&&except.includes("foot")||mode==="driving"&&except.some(x=>["motorcar","motor_vehicle","vehicle"].includes(x)))continue;
    if(mode==="walking"&&t["restriction:foot"]===undefined&&!Object.keys(t).some(k=>k.startsWith("restriction:foot:"))&&t.type!=="restriction:foot")continue;
    if(mode==="driving"&&t.type==="restriction:foot")continue;
    const rule=mode==="walking"?t["restriction:foot"]??t.restriction:t["restriction:motorcar"]??t["restriction:motor_vehicle"]??t.restriction;
    const m=Array.isArray(r.members)?r.members:[],f=m.filter(x=>x.role==="from"),v=m.filter(x=>x.role==="via"),to=m.filter(x=>x.role==="to");
    const supported=typeof rule==="string"&&/^(no|only)_(left_turn|right_turn|straight_on|u_turn)$/.test(rule)&&!Object.keys(t).some(k=>k.startsWith("restriction")&&k.endsWith(":conditional"))&&f.length===1&&v.length===1&&to.length===1&&f[0].type==="way"&&v[0].type==="node"&&to[0].type==="way"&&vertices.has(v[0].ref)&&wayIds.has(f[0].ref)&&wayIds.has(to[0].ref)&&(f[0].ref!==to[0].ref||rule==="no_u  … [line shortened here: 408 characters; full line on GitHub]
    if(!supported){issues.push("unsupported-restriction:"+r.id);continue}
    const via=v[0].ref,from=f[0].ref,target=to[0].ref;
    if(!byWay.get(from)?.some(e=>e.to===via)||!byWay.get(target)?.some(e=>e.from===via)){issues.push("incomplete-restriction:"+r.id);continue}
    const key=JSON.stringify([via,from]);
    if(!restrictions.has(key))restrictions.set(key,[]);
    restrictions.get(key).push({id:r.id,rule,target});
  }
  function turnAllowed(inId,outId){
    const a=byEdge.get(inId),b=byEdge.get(outId);
    if(!a||!b||a.to!==b.from||issues.length)return false;
    for(const r of restrictions.get(JSON.stringify([a.to,a.way]))??[]){
      if(r.rule==="no_u_turn"&&r.target===a.way){if(b.way===a.way&&b.to===a.from)return false;continue}
      if(r.rule.startsWith("no_")&&b.way===r.target||r.rule.startsWith("only_")&&b.way!==r.target)return false;
    }
    return true;
  }
  return {vertices,edges,issues,turnAllowed,completeForPilot:issues.length===0};
}

Verify Interconnector Arrival

A JavaScript module in the rig kit folder of Gridmachine1 that fetches interconnectors and the Renewable Energy Planning Database (REPD) register.

energy-datagridmachine1 / 202609071322-linux-handover/rig-kit/verify-interconnector-arrival.mjs · lines 1–118 of 118 · version 2026-09-07 13:22 · Not reached from any entry point (candidate for review)

What it does
It fetches interconnectors and the REPD register. Uses libraries node:fs, node:path, node:http, file:///C:/Users/vikra/LocalCI/PipelineNews-GridAtlas/v004/node_modules/playwright/index.mjs. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'interconnector'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: interconnectors, the REPD register.
Inputs & outputs
In: data source: 127.0.0.1:${PORT}; command-line arguments.
What it achieves
Does an interconnector MAP link fire the span model at both ends?
Why it matters
No other file in the estate was found to import it.
Application
gridmachine1 · 202609071322-linux-handover/rig-kit · JavaScript module
Uses
Range (import), node:fs, node:path, node:http, file:///C:/Users/vikra/LocalCI/PipelineNews-GridAtlas/v004/node_modules/playwright/index.mjs
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridmachine1@16cd3db49d03e6faa0e4e24f06f08184422049be 202609071322-linux-handover/rig-kit/verify-interconnector-arrival.mjs:1-118 · blob 89cc79a2c524e15a6a7b546fc4dbaa018b1775b3 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
// Does an interconnector MAP link fire the span model at both ends?
//
// Driven offline against the mirror with the network cut. Three arrivals:
// BritNed (both converters held: frame the span, card open, GB end measured,
// far end reported as no coverage), Viking Link (GB converter only: no line to
// frame, state says why, no failure card), and a REPD control (11386) whose
// project arrival must be untouched by the handover.
import fs from 'node:fs';
import path from 'node:path';
import http from 'node:http';
import { serveWithRange, serveOptions, mimeFor } from './range.mjs';
import { chromium } from 'file:///C:/Users/vikra/LocalCI/PipelineNews-GridAtlas/v004/node_modules/playwright/index.mjs';

const MIRROR = 'D:/gridatlas-ci/offline-sandbox/deps';
const PORT = 8909;
const VERSION = process.argv[2];
if (!/^\d{12}$/.test(VERSION || '')) throw new Error('usage: verify-interconnector-arrival.mjs <stamp>');

const misses = [];
const server = http.createServer((req, res) => {
  const url = decodeURIComponent(req.url.split('?')[0]);
  let target = path.join(MIRROR, url.replace(/^\/+/, ''));
  if (fs.existsSync(target) && fs.statSync(target).isDirectory()) target = path.join(target, 'index.html');
  if (!fs.existsSync(target)) { misses.push(url); res.writeHead(404).end('not in mirror'); return; }
  if (req.method === 'OPTIONS') return serveOptions(res);
  serveWithRange(req, res, target, mimeFor(target));
}).listen(PORT);

const BASE = `http://127.0.0.1:${PORT}/ventusltd.github.io/gridatlas/atlas/v/${VERSION}/`;
const CASES = [
  { name: 'BritNed both ends', url: BASE + '?interconnector=INTNED&technology=interconnector&project=BritNed&capacity_mw=1000&anchor=midpoint&latitude=51.69895&longitude=2.36873&zoom=7',
    expect: { status: 'RESOLVED', card: 'OPEN', handed: true, minZoom: 6, gbMeasured: true } },
  { name: 'Viking Link GB end only', url: BASE + '?interconnector=INTVKL&technology=interconnector&project=Viking+Link&capacity_mw=1400&anchor=gb_converter&latitude=52.9314&longitude=-0.22093&zoom=10',
    expect: { status: 'NOT_DRAWABLE', card: 'OPEN', handed: true, minZoom: 9 } },
  { name: 'control: REPD 11386 project arrival', url: BASE + '?repd_ref=11386&technology=solar&latitude=53.734542&longitude=-0.2023162&zoom=12',
    expect: { status: undefined, card: undefined, handed: false } },
];

const browser = await chromium.launch();
const rows = [];
for (const c of CASES) {
  const ctx = await browser.newContext({ viewport: { width: 1400, height: 900 } });
  await ctx.route('**/*', async (route) => {
    const u = new URL(route.request().url());
    if (u.hostname === '127.0.0.1') return route.continue();
    try {
      const hdr = route.request().headers(); const fwd = {}; if (hdr.range) fwd.Range = hdr.range;
      const m = await fetch(`http://127.0.0.1:${PORT}/${u.hostname}${u.pathname}${u.search}`, { method: route.request().method(), headers: fwd });
      if (!m.ok) return route.abort();
      const headers = { 'content-type': m.headers.get('content-type') || 'application/octet-stream', 'access-control-allow-origin': '*',
        'access-control-expose-headers': 'Content-Range, Content-Length, Accept-Ranges', 'accept-ranges': 'bytes' };
      for (const h of ['content-range', 'content-length']) { const v = m.headers.get(h); if (v) headers[h] = v; }
      return route.fulfill({ status: m.status, headers, body: route.request().method() === 'HEAD' ? Buffer.alloc(0) : Buffer.from(await m.arrayBuffer()) });
    } catch { return route.abort(); }
  });
  const page = await ctx.newPage();
  const errors = [];
  page.on('pageerror', (e) => errors.push(String(e).slice(0, 160)));
  const out = { name: c.name };
  try {
    await page.goto(c.url, { waitUntil: 'domcontentloaded', timeout: 45000 });
    await page.waitForFunction(() => window.__GRIDATLAS_INTERCONNECTORS__ && window.__GRIDATLAS_INTERCONNECTORS__.loaded, null, { timeout: 45000 }).catch(() => {});
    await page.waitForTimeout(6000);
    Object.assign(out, await page.evaluate(() => {
      const ic = window.__GRIDATLAS_INTERCONNECTORS__ || {};
      const a = ic.arrival || null;
      // the project arrival lane publishes its `link` state as __GRIDATLAS_NEON_LINKS__
      const lane = window.__GRIDATLAS_NEON_LINKS__ || {};
      const rec = lane.arrival_reconciliation || null;
      const map = window.__GRIDATLAS_V9_MAP__;
      let vis = null;
      try { vis = map.getLayoutProperty('l-interconnectors', 'visibility'); } catch (_) {}
      const popup = document.querySelector('.maplibregl-popup-content');
      const text = document.body.innerText || '';
      return {
        loaded: Boolean(ic.loaded), links: (ic.links || []).length, error: ic.error || null,
        status: a ? a.status : undefined, card: a ? a.card : undefined, framed: a ? a.framed : undefined,
        gb_nearest: a && a.ends ? a.ends[0].nearest_name + ' ' + a.ends[0].nearest_km + ' km' : null,
        far: a && a.ends && a.ends[1] ? a.ends[1].coverage : (a && a.ends ? "not held" : null),
        handed: rec ? rec.status === 'HANDED_TO_INTERCONNECTORS' : false,
        reconciliation: rec ? rec.status : null,
        layer_visibility: vis,
        popup_text: popup ? popup.innerText.replace(/\s+/g, ' ').slice(0, 160) : null,
        failCard: /did not fly to a safe map point|identity check failed|TRY AGAIN/i.test(text),
        nearest_on_page: /Nearest\s+\d+\s*kV substation:/.test(text),
        zoom: map && map.getZoom ? Number(map.getZoom().toFixed(2)) : null,
      };
    }));
  } catch (e) { out.error = String(e).slice(0, 120); }
  out.pageErrors = errors.slice(0, 2);
  rows.push(out);
  await ctx.close();
}
await browser.close();
server.close();

let pass = true;
for (const [i, r] of rows.entries()) {
  const e = CASES[i].expect;
  // `loaded` guards against a vacuous pass: a composition the composer refused
  // loads nothing, and "no arrival state" would then match the control's
  // expectation for free. The control must also have produced a project answer.
  const controlAnswered = e.handed === false ? r.nearest_on_page === true : true;
  const zoomOk = e.minZoom === undefined ? true : (r.zoom !== null && r.zoom >= e.minZoom);
  const gbOk = e.gbMeasured ? /\d km/.test(String(r.gb_nearest)) && !/null/.test(String(r.gb_nearest)) : true;
  const ok = r.loaded === true && controlAnswered && zoomOk && gbOk && r.status === e.status
    && (e.card === undefined ? true : r.card === e.card) && r.handed === e.handed && !r.failCard;
  if (!ok) pass = false;
  console.log(`  ${ok ? 'PASS' : 'FAIL'}  ${r.name}`);
  console.log(`        loaded ${r.loaded} links ${r.links} status ${r.status} card ${r.card} framed ${r.framed} layer ${r.layer_visibility} zoom ${r.zoom}`);
  console.log(`        GB end ${r.gb_nearest} · far ${r.far} · lane ${r.reconciliation} · nearest-on-page ${r.nearest_on_page} · failCard ${r.failCard}`);
  if (r.popup_text) console.log(`        card: ${r.popup_text}`);
  if (r.error) console.log(`        ERROR ${r.error}`);
  if (r.pageErrors.length) console.log(`        pageerror: ${r.pageErrors.join(' | ')}`);
}
if (misses.length) console.log('  mirror misses: ' + [...new Set(misses)].slice(0, 3).join(' | ').slice(0, 200));
console.log(pass ? `  ${VERSION}: interconnector arrival PASS` : `  ${VERSION}: FAIL`);
process.exit(pass ? 0 : 1);