In this section
- View interaction · globalgrid2050 / automation/news_quality_ui/20261117-v937/view.mjs lines 1–29
- Browser storage · globalgrid2050 / automation/pipeline_legal_evidence/browser.py lines 1–54
- Install ingest · globalgrid2050 / automation/pipeline_legal_evidence/install.py lines 1–22
- Link transform · globalgrid2050 / automation/pipeline_legal_evidence/link.mjs lines 1–27
- Link Test test · globalgrid2050 / automation/pipeline_legal_evidence/link.test.mjs lines 1–24
- Live V977 storage · globalgrid2050 / automation/pipeline_legal_evidence/live_v977.py lines 1–49
- Preview ingest · globalgrid2050 / automation/pipeline_legal_evidence/preview.py lines 1–72
- Journey Entry interaction · globalgrid2050 / automation/pipeline_public/journey-entry.mjs lines 1–56
- Browser Check automation · globalgrid2050 / automation/pipeline_release/browser_check.mjs lines 1–223
- Build Datacentre Context automation · globalgrid2050 / automation/pipeline_release/build_datacentre_context.py lines 1–74
- Build Register Events automation · globalgrid2050 / automation/pipeline_release/build_register_events.py lines 1–46
View
A JavaScript module in the news quality ui folder of GlobalGrid2050 that draws health (`drawHealth`). It draws health (`drawHealth`) and is built from the attach step (`attach`).
interactionglobalgrid2050 / automation/news_quality_ui/20261117-v937/view.mjs · lines 1–29 of 29 · version 2026-11-17 · Entry point · pattern attach (shared by 32 files)
- What it does
- It draws its content. Defines el, values, drawHealth, update, attach. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): 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 2 files: GlobalGrid2050 — UK Renewables Pipeline Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/); Header (globalgrid2050). Reached from 7 other entry points, including GlobalGrid2050 Pipeline Legal Evidence Workflow (globalgrid2050); GlobalGrid2050 V934 Preview Acceptance Workflow (globalgrid2050); V923 Public Readback Workflow (neural-link-between-agents).
- What it achieves
- Defines `values`, `drawHealth`, `update` and 1 more. It responds to input, change and click events.
- Why it matters
- Loaded by the UK Renewables Pipeline page at https://globalgrid2050.com/uk_renewables_pipeline/202611280922/. Also imported by Header.
- Application
- globalgrid2050 · automation/news_quality_ui/20261117-v937 · JavaScript module
- Uses
- Model (import)
- Used by
- loaded by GlobalGrid2050 — UK Renewables Pipeline Page (script src), imported by Header (import)
- Produces
- el, values, drawHealth, update, attach
- Defines here
- el, values, drawHealth, update, attach
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news_quality_ui/20261117-v937/view.mjs:1-29 · blob 22f36a4fd425811a95a7d44e8b1f9a99acefdc6d · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import {auditHealth,classification,selectEntries} from './model.mjs';
const doc=document,list=doc.getElementById('liveNews');
if(list){
const el=(tag,text)=>{const n=doc.createElement(tag);if(text!==undefined)n.textContent=text;return n;};
const host=el('div');host.className='pn-news-quality';const tools=el('div');tools.className='pn-news-filter-tools';
const query=el('input');query.type='search';query.placeholder='Search title, source or topic';query.setAttribute('aria-label','Filter news titles, sources or topics');
const selects={};for(const [id,label] of [['source','Publisher'],['topic','Topic'],['category','Category'],['kind','Ranking source type']]){const wrapper=el('label',label+' '),select=el('select');select.setAttribute('aria-label','News '+label.toLowerCase());selects[id]=select;wrapper.append(select);tools.append(wrapper);}
const clear=el('button','Clear news filters');clear.type='button';const count=el('span');count.setAttribute('role','status');tools.prepend(query);tools.append(clear,count);
const details=el('details'),summary=el('summary','Source health & provenance'),health=el('div');details.append(summary,health);host.append(tools,details);list.before(host);
let current=null,revision='',healthBuilt=false;
function values(entries,key,ranked){return [...new Set(entries.flatMap(entry=>key==='source'?[entry.item.source]:key==='category'?[entry.item.category]:key==='topic'?classification(entry,ranked).topics:[classification(entry,ranked).kind]).filter(v=>typeof v==='string'&&v))].sort((a,b)=>a.localeCompare(b));}
function drawHealth(){
if(!current)return;const audit=auditHealth(current.doc);health.replaceChildren();
health.append(el('p',audit.articles===null?'Article and publisher metadata unavailable.':`${audit.articles} original articles; ${audit.publishers.length} distinct credited publisher labels${audit.unknownPublishers?`; ${audit.unknownPublishers} publisher credits unavailable`:''}. Publishers and feeds are different counts.`));
health.append(el('p',audit.available?`${audit.ok} of ${audit.feeds} feed checks succeeded; ${audit.failed} failed.`:audit.reason));
health.append(el('p',`Collection clock: ${audit.collectionClock||'Unknown'}. Recorded status: ${audit.status}. Display: ${current.source}. Publisher dates and first-collected clocks stay separate.`));
health.append(el('p',current.ranked?'Ranking metadata is exact-input and current; its source types are classifications, not source verification.':'Ranking source type unavailable: Unclassified. Saved, stale, rejected or missing priority metadata supplies no source authority.'));
const publishers=el('ul');for(const [name,total] of audit.publishers.slice(0,20))publishers.append(el('li',`${name}: ${total} credited articles`));health.append(publishers);if(audit.publishers.length>20)health.append(el('p',`${audit.publishers.length-20} further publisher labels available in the Publisher filter.`));
if(audit.available&&audit.failed)for(const f of audit.failedSources.slice(0,5))health.append(el('p',`Failed feed: ${f.source} (${f.url})`));healthBuilt=true;
}
function apply(reset=true){if(!current)return;const filter={query:query.value,...Object.fromEntries(Object.entries(selects).map(([k,n])=>[k,n.value]))},selected=selectEntries(current.entries,filter,current.ranked);count.textContent=current.doc?`${selected.length} of ${current.entries.length} original headlines match`:'Headlines unavailable';host.dataset.filteredCount=String(selected.length);curre … [line shortened here: 425 characters; full line on GitHub]
function update(view){
const key=JSON.stringify(view.entries.map(entry=>[entry.item.link,entry.item.title,entry.item.source,entry.item.category,classification(entry,view.ranked)]));const same=key===revision;revision=key;current=view;healthBuilt=false;
for(const [id,select] of Object.entries(selects)){const selected=select.value;select.replaceChildren(new Option('All '+(id==='kind'?'types':id==='source'?'publishers':id==='category'?'categories':'topics'),''));for(const value of values(view.entries,id,view.ranked))select.add(new Option(value,value));if([...select.options].some(o=>o.value===selected))select.value=selected;}
apply(!same);if(details.open)drawHealth();
}
query.addEventListener('input',()=>apply());for(const select of Object.values(selects))select.addEventListener('change',()=>apply());clear.addEventListener('click',()=>{query.value='';for(const select of Object.values(selects))select.value='';apply();});details.addEventListener('toggle',()=>{if(details.open&&!healthBuilt)drawHealth();});
const attach=()=>window.pipelineHeadlines?.attachView?.(update);if(window.pipelineHeadlines)attach();else window.addEventListener('pipeline-news-ready',attach,{once:true});
}Browser
A Python command-line tool in the pipeline legal evidence folder of GlobalGrid2050 covering acceptance. It is built from the run step (`run`).
storageglobalgrid2050 / automation/pipeline_legal_evidence/browser.py · lines 1–54 of 54 · Entry point
- What it does
- Defines run. Uses libraries argparse, json, os, pathlib, threading. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): 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: command-line arguments. Out: JSON file acceptance.json.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- Exercise the full PipelineNews project panel and the public legal reader.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- globalgrid2050 · automation/pipeline_legal_evidence · Python CLI
- Uses
- Preview (import), argparse, json, os, pathlib, threading, urllib.parse, playwright.sync_api
- Used by
- none found
- Produces
- run
- Defines here
- run
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/pipeline_legal_evidence/browser.py:1-54 · blob b6c656f2f2afc2b0f4864f1c30a11efba9ac34ba · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Exercise the full PipelineNews project panel and the public legal reader."""
import argparse
import json
import os
from pathlib import Path
from threading import Thread
from urllib.parse import parse_qs, urlsplit
from playwright.sync_api import expect, sync_playwright
from preview import EDITION, Preview, ThreadingHTTPServer
def run(output):
output.mkdir(parents=True, exist_ok=True)
with ThreadingHTTPServer(("127.0.0.1", 0), Preview) as server, sync_playwright() as driver:
Thread(target=server.serve_forever, daemon=True).start()
with driver.chromium.launch(executable_path=os.getenv("CHROME_BIN")) as browser:
page = browser.new_page(viewport={"width": 1280, "height": 850})
base = f"http://127.0.0.1:{server.server_port}"
page.goto(base + EDITION + "?technology=all&q=9873", wait_until="domcontentloaded", timeout=180000)
row = page.locator("#repd-9873")
expect(row).to_be_visible(timeout=240000)
expected_name = row.locator(".compact-project-name").text_content().strip()
report = {"reference": "9873", "edition": "202611232245", "viewports": []}
for width in (1280, 390):
page.set_viewport_size({"width": width, "height": 850})
detail = row.locator("details.project-record")
if detail.get_attribute("open") is None:
detail.locator("summary").click()
action = detail.get_by_role("link", name="Legal evidence", exact=True)
expect(action).to_be_visible()
action.scroll_into_view_if_needed()
page.screenshot(path=output / f"PipelineNews-{width}.png")
report["viewports"].append(width)
target = action.get_attribute("href")
parsed = urlsplit(target)
params = parse_qs(parsed.query)
assert (parsed.scheme, parsed.netloc, parsed.path) == ("https", "ventusltd.github.io", "/legislation/legal-evidence/")
assert params["repd_ref"] == ["9873"] and params["project"] == [expected_name]
assert params["source_release"] == ["202611232245"]
action.click(timeout=60000)
expect(page.locator("#context")).to_contain_text(expected_name, timeout=60000)
expect(page.locator("#context")).to_contain_text("202611232245")
return_url = "https://globalgrid2050.com" + EDITION + "?technology=all&q=9873"
expect(page.locator("#pipeline")).to_have_attribute("href", return_url)
page.screenshot(path=output / "legal-reader.png")
report.update(receiver=parsed.scheme + "://" + parsed.netloc + parsed.path, return_url=return_url)
(output / "acceptance.json").write_text(json.dumps(report, indent=2) + "\n")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("output", type=Path)
run(parser.parse_args().output)Install
A Python command-line tool in the pipeline legal evidence folder of GlobalGrid2050 that creates a candidate project renderer from the selected version, without editing its input.
ingestglobalgrid2050 / automation/pipeline_legal_evidence/install.py · lines 1–22 of 22 · Entry point · pattern patch (shared by 11 files)
- What it does
- It loads data. Defines patch. Uses libraries argparse, pathlib. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): 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: command-line arguments.
- Downstream impact
- Used directly by 1 file: Preview (globalgrid2050). Reached from 1 other entry point, including Browser (globalgrid2050).
- What it achieves
- Defines `patch`.
- Why it matters
- Imported by Preview.
- Application
- globalgrid2050 · automation/pipeline_legal_evidence · Python CLI
- Uses
- argparse, pathlib
- Used by
- imported by Preview (import)
- Produces
- patch
- Defines here
- patch
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/pipeline_legal_evidence/install.py:1-22 · blob bb795e54ed8bdbd07fc320a5d9ab76f2bb8d379f · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, EPC_contractor, ICP_grid_engineer · canonical: production_core
"""Create a candidate project renderer from the selected version, without editing its input."""
import argparse
from pathlib import Path
IMPORT = 'import { legalEvidenceAction } from "../../../../automation/pipeline_legal_evidence/link.mjs";'
MARKER = '<div><b>PROJECT NAME</b><span>${escapeHtml(project.name)}</span></div>'
def patch(source):
if source.count(MARKER) != 1 or IMPORT in source:
raise ValueError("Expected one unmodified REPD project-detail template")
return IMPORT + "\n" + source.replace(MARKER, MARKER + "${legalEvidenceAction(project)}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("source", type=Path)
parser.add_argument("output", type=Path, help="new file; existing files are protected")
args = parser.parse_args()
result = patch(args.source.read_text(encoding="utf-8"))
with args.output.open("x", encoding="utf-8") as output:
output.write(result)Link
A JavaScript module in the pipeline legal evidence folder of GlobalGrid2050 using data from the legislation repository.
transformglobalgrid2050 / automation/pipeline_legal_evidence/link.mjs · lines 1–27 of 27
- What it does
- It calculates its inputs. Defines legalEvidenceURL, legalEvidenceAction.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): 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 3 files: Link Test (globalgrid2050); Projects V9 8 (globalgrid2050); Report Model (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/). Reached from 17 other entry points, including GlobalGrid2050 — UK Renewables Pipeline Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/); Report A4 (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/); GlobalGrid2050 Pipeline Legal Evidence Workflow (globalgrid2050).
- What it achieves
- It is built from the legal evidence URL helper (`legalEvidenceURL`) and the legal evidence action helper (`legalEvidenceAction`). Defines `legalEvidenceURL` and `legalEvidenceAction`.
- Why it matters
- Imported by Projects V9 8 and Report Model. Checked by Link Test.
- Application
- globalgrid2050 · automation/pipeline_legal_evidence · JavaScript module
- Uses
- Legislation — Legal Evidence Page (estate URL)
- Used by
- imported by Link Test (import), imported by Projects V9 8 (import), imported by Report Model (import)
- Produces
- legalEvidenceURL, legalEvidenceAction
- Defines here
- legalEvidenceURL, legalEvidenceAction
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/pipeline_legal_evidence/link.mjs:1-27 · blob ac6ab4b5606cb37ec406f2f1107589343349feac · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
const reader = "https://ventusltd.github.io/legislation/legal-evidence/";
const nations = new Set(["England", "Scotland", "Wales", "Northern Ireland"]);
export function legalEvidenceURL(project, pathname = globalThis.location?.pathname ?? "") {
const ref = String(project?.repd_ref ?? "");
if (!/^[1-9]\d*$/.test(ref) || project.gg_project_id !== "GG2050-REPD-" + ref)
return null;
const url = new URL(reader);
url.searchParams.set("source_app", "pipelinenews");
url.searchParams.set("repd_ref", ref);
const release = /^\/uk_renewables_pipeline\/(\d{12})\/(?:index\.html)?$/.exec(pathname);
if (release) url.searchParams.set("source_release", release[1]);
for (const [key, value] of Object.entries({
project: project.name, technology: project.technology, status: project.status,
jurisdiction: nations.has(project.country) ? project.country : undefined,
})) {
if (typeof value === "string" && value.trim()) url.searchParams.set(key, value.trim());
}
if (project.capacity_known === true && Number.isFinite(project.capacity_mw) && project.capacity_mw >= 0)
url.searchParams.set("mw", String(project.capacity_mw));
return url.href;
}
export function legalEvidenceAction(project) {
const href = legalEvidenceURL(project);
return href ? '<div style="grid-column:1/-1"><a class="action-link" href="' + href.replaceAll("&", "&") + '">Legal evidence</a></div>' : "";
}Link Test
A test in the pipeline legal evidence folder of GlobalGrid2050 that checks Link.
testglobalgrid2050 / automation/pipeline_legal_evidence/link.test.mjs · lines 1–24 of 24 · Entry point
- What it does
- It tests solar. Uses libraries node:assert/strict, node:test.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): 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: solar.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Pipeline Legal Evidence Workflow (globalgrid2050).
- 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 GlobalGrid2050 Pipeline Legal Evidence Workflow.
- Application
- globalgrid2050 · automation/pipeline_legal_evidence · test
- Uses
- Link (import), node:assert/strict, node:test
- Used by
- run by GlobalGrid2050 Pipeline Legal Evidence 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
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/pipeline_legal_evidence/link.test.mjs:1-24 · blob 569ee0e3ba8b35c39c20659d8c73c3fe1442fd11 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: unknown · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import assert from "node:assert/strict";
import {test} from "node:test";
import {legalEvidenceURL, legalEvidenceAction} from "./link.mjs";
const fixture = {repd_ref:"999999",gg_project_id:"GG2050-REPD-999999",name:"Fictional A & B",technology:"solar",status:"Application Submitted",country:"Wales",capacity_known:true,capacity_mw:32.4};
test("encode a canonical project into the reader", () => {
const link = new URL(legalEvidenceURL(fixture));
assert.equal(link.origin, "https://ventusltd.github.io");
assert.equal(link.pathname, "/legislation/legal-evidence/");
assert.deepEqual(Object.fromEntries(link.searchParams),{source_app:"pipelinenews",repd_ref:"999999",project:"Fictional A & B",technology:"solar",status:"Application Submitted",jurisdiction:"Wales",mw:"32.4"});
assert.match(legalEvidenceAction(fixture), /Legal evidence/);
});
test("unknown and mismatched records", () => {
assert.equal(legalEvidenceAction({...fixture,gg_project_id:"interconnector"}),"");
const url = new URL(legalEvidenceURL({...fixture,country:"Offshore",capacity_known:false}));
assert.equal(url.searchParams.has("jurisdiction"),false);
assert.equal(url.searchParams.has("mw"),false);
});
test("retain the edition identity of this rendered project", () => {
const pathname = "/uk_renewables_pipeline/202611232245/";
assert.equal(new URL(legalEvidenceURL(fixture, pathname)).searchParams.get("source_release"), "202611232245");
assert.equal(new URL(legalEvidenceURL(fixture, "/unexpected/")).searchParams.has("source_release"), false);
});Live V977
A Python command-line tool in the pipeline legal evidence folder of GlobalGrid2050 covering the Renewable Energy Planning Database (REPD) register. It is built from the run step (`run`).
storageglobalgrid2050 / automation/pipeline_legal_evidence/live_v977.py · lines 1–49 of 49 · Entry point
- What it does
- Defines run. Uses libraries json, os, pathlib, urllib.parse, playwright.sync_api. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): 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: the REPD register.
- Inputs & outputs
- Out: JSON file receipt.json.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Pipeline V977 Live Workflow (globalgrid2050).
- What it achieves
- Open the production REPD edition, its public legal reader and the reader's original data source.
- Why it matters
- Run by GlobalGrid2050 Pipeline V977 Live Workflow.
- Application
- globalgrid2050 · automation/pipeline_legal_evidence · Python CLI
- Uses
- json, os, pathlib, urllib.parse, playwright.sync_api
- Used by
- run by GlobalGrid2050 Pipeline V977 Live Workflow (workflow run)
- Produces
- run
- Defines here
- run
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/pipeline_legal_evidence/live_v977.py:1-49 · blob 1aaa4b19b6dc0e8488192df31dae3598b1e688bd · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Open the production REPD edition, its public legal reader and the reader's original data source."""
import json
import os
from pathlib import Path
from urllib.parse import parse_qs, urljoin, urlsplit
from playwright.sync_api import expect, sync_playwright
def run(output):
homepage = "https://globalgrid2050.com/"
edition = urljoin(homepage, "uk_renewables_pipeline/202611280048/")
output.mkdir(parents=True, exist_ok=True)
with sync_playwright() as driver, driver.chromium.launch(executable_path=os.getenv("CHROME_BIN")) as browser:
page = browser.new_page(viewport={"width": 1280, "height": 850})
page.goto(homepage, wait_until="domcontentloaded")
expect(page.locator("a.launch", has_text="Open Pipeline News").first).to_have_attribute("href", edition)
page.goto(edition + "?technology=all&q=9873", wait_until="domcontentloaded", timeout=120000)
row = page.locator("#repd-9873")
expect(row).to_be_visible(timeout=120000)
project = row.locator(".compact-project-name").text_content().strip()
for width in (1280, 390):
page.set_viewport_size({"width": width, "height": 850})
detail = row.locator("details.project-record")
if detail.get_attribute("open") is None:
detail.locator("summary").click()
action = detail.get_by_role("link", name="Legal evidence")
expect(action).to_be_visible()
action.scroll_into_view_if_needed()
page.screenshot(path=output / f"pipeline-{width}.png")
action.click(timeout=60000)
expect(page.locator("#context")).to_contain_text(project, timeout=60000)
expect(page.locator("#context")).to_contain_text("202611280048")
parsed = urlsplit(page.url)
assert (parsed.scheme, parsed.netloc, parsed.path) == ("https", "ventusltd.github.io", "/legislation/legal-evidence/")
assert parse_qs(parsed.query)["repd_ref"] == ["9873"]
expect(page.locator("#pipeline")).to_have_attribute("href", edition + "?technology=all&q=9873", timeout=60000)
expect(page.locator("#source-edition")).to_have_attribute("href", edition + "?technology=all&q=9873", timeout=60000)
return_url = page.locator("#pipeline").get_attribute("href")
assert urlsplit(return_url).netloc == "globalgrid2050.com"
assert parse_qs(urlsplit(return_url).query) == {"technology":["all"], "q":["9873"]}
page.screenshot(path=output / "reader.png")
page.locator("#pipeline").click(timeout=60000)
expect(page.locator("#repd-9873")).to_be_visible(timeout=120000)
(output / "receipt.json").write_text(json.dumps({"edition": edition, "repd_ref":"9873", "project":project,"viewports":[1280,390],"return_url":return_url}, indent=2)+"\n")
if __name__ == "__main__":
run(Path("acceptance"))Preview
A Python command-line tool in the pipeline legal evidence folder of GlobalGrid2050 that sends bytes (`send_bytes`). It is built from the preview class (`Preview`) and the do get helper (`do_GET`).
ingestglobalgrid2050 / automation/pipeline_legal_evidence/preview.py · lines 1–72 of 72 · Entry point · pattern do_GET (shared by 7 files)
- What it does
- It fetches data. Defines Preview, do_GET, send_bytes. Uses libraries argparse, mimetypes, os, http.server, pathlib. Side effects: reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): 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: command-line arguments.
- Downstream impact
- Used directly by 1 file: Browser (globalgrid2050).
- What it achieves
- Serve the accepted PipelineNews shell with its candidate renderer on localhost. It accepts `--port`.
- Why it matters
- Imported by Browser.
- Application
- globalgrid2050 · automation/pipeline_legal_evidence · Python CLI
- Uses
- Install (import), argparse, mimetypes, os, http.server, pathlib, urllib.error, urllib.parse, urllib.request
- Used by
- imported by Browser (import)
- Produces
- Preview
- Defines here
- Preview, do_GET, send_bytes
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/pipeline_legal_evidence/preview.py:1-72 · blob 3645968b6a415833d50316586336e7da45fd669c · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Serve the accepted PipelineNews shell with its candidate renderer on localhost."""
import argparse
import mimetypes
import os
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.parse import urlsplit
from urllib.request import urlopen
from install import patch
ROOT = Path(__file__).resolve().parent
ORIGIN = "https://globalgrid2050.com"
EDITION = "/uk_renewables_pipeline/202611232245/"
RENDERER = EDITION + "scripts/plugins/projects-v9-8.js"
HELPER = "/automation/pipeline_legal_evidence/link.mjs"
class Preview(BaseHTTPRequestHandler):
def do_GET(self):
path = urlsplit(self.path).path
if path == "/":
self.send_response(302)
self.send_header("Location", EDITION + "?technology=all&q=9873")
self.end_headers()
return
if path == HELPER:
self.send_bytes((ROOT / "link.mjs").read_bytes(), "application/javascript")
return
if not path.startswith(("/uk_renewables_pipeline/", "/automation/", "/dist/")) or ".." in path or "%" in path:
self.send_error(404)
return
try:
checkout = os.getenv("PIPELINE_CHECKOUT")
local = Path(checkout) / path.lstrip("/") if checkout else None
if local and local.is_dir():
local = local / "index.html"
if local and local.is_file():
body = local.read_bytes()
mime = mimetypes.guess_type(local.name)[0] or "application/octet-stream"
else:
with urlopen(ORIGIN + path, timeout=40) as response:
body = response.read(20_000_001)
if len(body) > 20_000_000:
raise ValueError("Upstream resource too large")
mime = response.headers.get_content_type()
if path == RENDERER:
body = patch(body.decode("utf-8")).encode("utf-8")
self.send_bytes(body, mime)
except HTTPError as exc:
self.send_error(exc.code)
except (URLError, TimeoutError, ValueError) as exc:
self.send_error(502, str(exc))
except (BrokenPipeError, ConnectionResetError):
pass
def send_bytes(self, body, mime):
self.send_response(200)
self.send_header("Content-Type", mime)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--port", type=int, default=8765)
args = parser.parse_args()
with ThreadingHTTPServer(("127.0.0.1", args.port), Preview) as server:
print(f"Open http://127.0.0.1:{args.port}/", flush=True)
server.serve_forever()Journey Entry
A JavaScript module in the pipeline public folder of GlobalGrid2050 covering the Renewable Energy Planning Database (REPD) register and substations, using SHA-256, and uses data from the GridAtlas repository.
interactionglobalgrid2050 / automation/pipeline_public/journey-entry.mjs · lines 1–56 of 56 · Not reached from any entry point (candidate for review)
- What it does
- It draws the REPD register and substations. Uses libraries node:assert/strict, node:fs, node:crypto, node:path, node:url. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (voltage levels 400kV (all 132kV or above)): 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: the REPD register, substations, 400kV.
- Inputs & outputs
- In: data source: gridatlas data. Out: JSON file receipt.json. Voltage levels named: 400kV.
- What it achieves
- Unintercepted public sender -> accepted Vicinity controller. Its code works with 400 kV.
- Why it matters
- No other file in the estate was found to import it.
- Application
- globalgrid2050 · automation/pipeline_public · JavaScript module
- Uses
- GridAtlas — Atlas Page (estate URL), node:assert/strict, node:fs, node:crypto, node:path, node:url
- 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
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/pipeline_public/journey-entry.mjs:1-56 · blob 8fcefa07d054396c3c986df51f75ecc2adea34c0 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/* Unintercepted public sender -> accepted Vicinity controller. Device emulation
* is bounded integration evidence, never physical-phone or fleet certification. */
import assert from 'node:assert/strict';
import {readFileSync,writeFileSync,mkdirSync} from 'node:fs';
import {createHash} from 'node:crypto';
import {resolve,dirname} from 'node:path';
import {fileURLToPath,pathToFileURL} from 'node:url';
const root=resolve(dirname(fileURLToPath(import.meta.url)),'../..');
const edition=process.env.PN_PUBLIC_EDITION,generation=process.env.EXPECTED_ATLAS_GENERATION;
assert.match(edition||'',/^\d{12}$/,'explicit published Pipeline edition required');assert.match(generation||'',/^\d{12}$/,'explicit accepted Atlas generation required');
const source='https://globalgrid2050.com/uk_renewables_pipeline/'+edition+'/';
const expected=createHash('sha256').update(readFileSync(resolve(root,'uk_renewables_pipeline/'+edition+'/index.html'))).digest('hex');
const pw=await import(pathToFileURL(process.env.PLAYWRIGHT_MODULE||'D:/githubfiles/.qa-tools/node/node_modules/playwright/index.mjs').href);
const out=process.env.PN_PUBLIC_OUT||resolve(root,'work/public-journey-entry');mkdirSync(out,{recursive:true});
const report={source,expectedAtlasGeneration:generation,scope:'actual public bounded entry sample; no interception, injected runtime or inferred connections',results:[]};
try{for(const [engine,device]of [['chromium','Pixel 7'],['webkit','iPhone 13']]){
const browser=await pw[engine].launch({headless:true});
try{for(const kind of ['repd','substation','datacentre','manual']){
const context=await browser.newContext(pw.devices[device]),page=await context.newPage(),errors=[];page.on('pageerror',e=>errors.push(e.message));
const row={engine,device,kind,started:new Date().toISOString(),errors};report.results.push(row);
try{
const response=await page.goto(source,{waitUntil:'domcontentloaded',timeout:60000});assert.equal(response.status(),200);assert.equal(createHash('sha256').update(await response.body()).digest('hex'),expected);
await page.waitForFunction(()=>Number(document.querySelector('#tbody')?.dataset.total)>0,null,{timeout:60000});
let link;
if(kind==='repd'){await page.locator('#clearFilters').tap();await page.locator('#search').fill('12588');link=page.locator('#tbody .pn-journey-link[href*="repd_ref=12588"]').first()}
else if(kind==='substation'){await page.locator('.pipeline-tabs [data-view="grid"]').tap();link=page.locator('#gridLayerHost .pn-journey-link').first()}
else if(kind==='datacentre'){await page.locator('.pipeline-tabs [data-view="datacentre"]').tap();await page.waitForFunction(()=>document.getElementById('datacentreHost')?.dataset.locationsState==='available',null,{timeout:60000});link=page.locator('#datacentreHost .ggdc-location-actions .pn-journey-link').first()}
else link=page.locator('#journeyAtlasNav');
await link.waitFor({state:'visible',timeout:60000});await link.scrollIntoViewIfNeeded();const href=await link.getAttribute('href'),url=new URL(href);row.href=href;assert.equal(url.origin+url.pathname,'https://ventusltd.github.io/gridatlas/atlas/');assert.equal(url.searchParams.get('journey'),'vicinity');
if(kind!=='manual')assert.equal(url.searchParams.get('origin_type'),kind);
row.hit=await link.evaluate(a=>{const r=a.getBoundingClientRect(),h=document.elementFromPoint(r.x+r.width/2,r.y+r.height/2);return{width:r.width,height:r.height,reachable:h===a||a.contains(h)}});assert.ok(row.hit.reachable&&row.hit.width>=44&&row.hit.height>=44);
await link.tap();await page.waitForURL('https://ventusltd.github.io/gridatlas/atlas/**',{timeout:30000});assert.equal(context.pages().length,1);
await page.waitForFunction(()=>window.__GRIDATLAS_MODULES__?.gridVicinity?.snapshot().opened,null,{timeout:100000});
const panel=page.getByRole('region',{name:'Vicinity familiarisation'});await panel.waitFor({state:'visible'});
row.arrival=await page.evaluate(()=>({url:location.href,generation:document.documentElement.dataset.gridatlasGeneration,router:document.body.dataset.gridatlasRouter,state:window.__GRIDATLAS_MODULES__.gridVicinity.snapshot()}));
const arrived=new URL(row.arrival.url);assert.equal(arrived.origin+arrived.pathname,'https://ventusltd.github.io/gridatlas/atlas/');assert.equal(row.arrival.generation,generation);assert.notEqual(row.arrival.router,'failed');assert.equal(row.arrival.state.realConnectionsInferred,0);assert.equal(row.arrival.state.error,null);
if(kind!=='manual'){
const state=row.arrival.state;assert.equal(state.origin.type,kind);assert.equal(state.origin.id,url.searchParams.get('origin_id'));assert.deepEqual(state.origin.at,[Number(url.searchParams.get('longitude')),Number(url.searchParams.get('latitude'))]);assert.equal(state.radiusKm,Number(url.searchParams.get('radius_km')));
if(url.searchParams.has('name'))assert.equal(state.origin.name,url.searchParams.get('name'));
assert.equal(arrived.searchParams.get('origin_id'),state.origin.id);
}
await page.getByRole('slider',{name:'Vicinity radius in kilometres'}).focus();await page.keyboard.press('End');assert.equal(await page.evaluate(()=>window.__GRIDATLAS_MODULES__.gridVicinity.snapshot().radiusKm),50);await page.keyboard.press('Home');assert.equal(await page.evaluate(()=>window.__GRIDATLAS_MODULES__.gridVicinity.snapshot().radiusKm),1);
const checkbox=panel.getByRole('checkbox',{name:'400 kV',exact:true});await checkbox.uncheck();assert.equal(await page.evaluate(()=>window.__GRIDATLAS_MODULES__.gridVicinity.snapshot().selectedBands.includes('400')),false);
await page.setViewportSize({width:844,height:390});await page.waitForTimeout(250);const box=await panel.boundingBox();assert.ok(box.x>=0&&box.y>=0&&box.x+box.width<=845&&box.y+box.height<=391);assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1));
await page.screenshot({path:resolve(out,engine+'-'+kind+'.png')});
await page.goBack({waitUntil:'domcontentloaded'});await page.waitForURL(source+'**');assert.equal(new URL(page.url()).origin+new URL(page.url()).pathname,source);
if(kind==='repd')await page.waitForFunction(()=>document.querySelector('#search')?.value==='12588',null,{timeout:60000});
if(kind==='datacentre')await page.waitForFunction(()=>document.querySelector('.pipeline-tabs [data-view="datacentre"]')?.getAttribute('aria-selected')==='true',null,{timeout:60000});
assert.deepEqual(errors,[]);row.pass=true;
}catch(e){row.pass=false;row.error=String(e);throw e}
finally{row.finished=new Date().toISOString();writeFileSync(resolve(out,'receipt.json'),JSON.stringify(report,null,2)+'\n');await context.close()}
}}finally{await browser.close()}
}
report.pass=true;
}finally{report.finished=new Date().toISOString();writeFileSync(resolve(out,'receipt.json'),JSON.stringify(report,null,2)+'\n')}
console.log(JSON.stringify(report));Browser Check
A JavaScript module in the pipeline release folder of GlobalGrid2050 that runs probe (`runProbe`), covering the Renewable Energy Planning Database (REPD) register, using SHA-256.
automationglobalgrid2050 / automation/pipeline_release/browser_check.mjs · lines 1–223 of 223 · Entry point · pattern listen (shared by 7 files)
- What it does
- It draws the REPD register. Defines 11 functions or classes, including sleep, send, runProbe, visitBlocked, evaluate. Uses libraries node:child_process, node:fs, node:crypto, node:os, node:path. 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 (topic 'markets-data'): 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: the REPD register.
- Inputs & outputs
- In: command-line arguments.
- Downstream impact
- Used directly by 1 file: Verify (globalgrid2050). Reached from 5 other entry points, including GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); GlobalGrid2050 Publish Pipeline V923 Ledger Workflow (globalgrid2050); GlobalGrid2050 V923 Six Hour Python Repair Workflow (globalgrid2050).
- What it achieves
- It runs probe (`runProbe`) and is built from the sleep step (`sleep`) and the send step (`send`). Load Pipeline News version pages in headless Chrome and record what a reader's browser sees.
- Why it matters
- Run by Verify.
- Application
- globalgrid2050 · automation/pipeline_release · JavaScript module
- Uses
- node:child_process, node:fs, node:crypto, node:os, node:path
- Used by
- run by Verify (script call)
- Produces
- sleep, send, runProbe, visitBlocked, evaluate, visit, listen, fail, evaluate, q, links
- Defines here
- sleep, send, runProbe, visitBlocked, evaluate, visit, listen, fail, evaluate, q, links
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/pipeline_release/browser_check.mjs:1-223 · blob 12b6f01125d2ff6a6387dd4eaf3a32b4588dea4e · 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: production_core
#!/usr/bin/env node
/* browser_check.mjs - load Pipeline News version pages in headless Chrome and
* record what a reader's browser sees. No dependencies: Node 22 (built-in
* WebSocket and fetch) and a Chrome binary, driven over the DevTools protocol.
*
* Usage: node browser_check.mjs <base url ending in /uk_renewables_pipeline/> <out.json> <id> [<id> ...]
* For each version and each viewport (desktop 1440x900, phone 390x844) it records:
* the results line and record count, rows drawn, uncaught page errors, console
* errors, failed requests (same-origin and external apart), horizontal overflow
* on the phone, and the MAP links of the first rows.
*/
import { spawn } from "node:child_process";
import { mkdtempSync, readFileSync, writeFileSync, existsSync, rmSync, readdirSync } from "node:fs";
import { createHash } from "node:crypto";
import { tmpdir } from "node:os";
import { join } from "node:path";
const [base, outPath, ...ids] = process.argv.slice(2);
if (!base || !outPath || !ids.length) { console.error("usage: browser_check.mjs <base> <out.json> <id>..."); process.exit(2); }
const CHROME = process.env.CHROME_BIN || ["/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser"].find(existsSync);
const VIEWPORTS = [
{ name: "desktop", width: 1440, height: 900, mobile: false },
{ name: "phone", width: 390, height: 844, mobile: true },
];
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
// Start Chrome and wait for its DevTools port; a slow start gets a second attempt.
let profile = "", chrome = null, wsUrl = "";
for (let attempt = 1; attempt <= 3 && !wsUrl; attempt += 1) {
profile = mkdtempSync(join(tmpdir(), "pn-chrome-"));
chrome = spawn(CHROME, ["--headless=new", "--no-sandbox", "--disable-gpu", "--disable-dev-shm-usage", "--remote-debugging-port=0",
`--user-data-dir=${profile}`, "--no-first-run", "about:blank"], { stdio: "ignore" });
for (let i = 0; i < 300 && !wsUrl; i += 1) {
await sleep(100);
const f = join(profile, "DevToolsActivePort");
if (existsSync(f)) { const [port, path] = readFileSync(f, "utf8").trim().split("\n"); if (path) wsUrl = `ws://127.0.0.1:${port}${path}`; }
}
if (!wsUrl) { console.error(`Chrome did not open its DevTools port in 30 s (attempt ${attempt})`); chrome.kill("SIGKILL"); }
}
if (!wsUrl) { console.error("Chrome did not start"); process.exit(2); }
const ws = new WebSocket(wsUrl);
await new Promise((res, rej) => { ws.onopen = res; ws.onerror = rej; });
let seq = 0;
const waiting = new Map();
const listeners = new Set();
ws.onmessage = (ev) => {
const msg = JSON.parse(ev.data);
if (msg.id && waiting.has(msg.id)) { const { res, rej } = waiting.get(msg.id); waiting.delete(msg.id); msg.error ? rej(new Error(msg.error.message)) : res(msg.result); }
else for (const l of listeners) l(msg);
};
const send = (method, params = {}, sessionId) => new Promise((res, rej) => {
const id = ++seq; waiting.set(id, { res, rej }); ws.send(JSON.stringify({ id, method, params, sessionId }));
});
// Probes that need the public internet (a CDN script, for example) run only where it is reachable.
const EXTERNAL = !!process.env.GITHUB_ACTIONS || process.env.PROBE_EXTERNAL === '1';
const PROBES = process.env.PROBES_FILE ? JSON.parse(readFileSync(process.env.PROBES_FILE, "utf8")) : {};
/* A probe looks at one named thing on the page and says whether it is as expected.
* With `search` it first types that text in the table search (a REPD Ref ID) and looks
* inside the row `row`; without, it looks at the page. `contains`, `not_contains` and
* `attrs` are checked on the element `selector`; `link_selector` + `link_regex` on a link
* inside it; `js` is an expression that must be true in the page. The row's MAP href is returned so the caller can compare it with the contract. */
async function runProbe(evaluate, probe) {
if (probe.search != null) {
await evaluate("document.querySelector('#solarTab')?.click(); document.querySelector('#clearFilters')?.click()");
await evaluate(`(() => { const i = document.querySelector('#search'); i.value = ${JSON.stringify(String(probe.search))}; i.dispatchEvent(new Event('input', { bubbles: true })); })()`);
await sleep(1500);
}
const result = await evaluate(`(async (p) => {
const scope = p.row ? document.getElementById(p.row) : document;
if (!scope) return { pass: false, detail: 'row not drawn: ' + p.row };
if (p.js) { let ok = false; try { ok = !!(await (0, eval)(p.js)); } catch (e) { ok = false; } return { pass: ok, detail: ok ? '' : 'expression is not true: ' + p.js }; }
const node = scope.querySelector(p.selector);
if (!node) return { pass: false, detail: 'element not found: ' + p.selector };
const text = node.textContent, faults = [];
for (const s of p.contains || []) if (!text.includes(s)) faults.push('missing text: ' + s);
for (const s of p.not_contains || []) if (text.includes(s)) faults.push('unexpected text: ' + s);
for (const [k, v] of Object.entries(p.attrs || {})) if (node.getAttribute(k) !== v) faults.push('attribute ' + k + ' is ' + node.getAttribute(k) + ', expected ' + v);
let link = null;
if (p.link_selector) {
link = node.querySelector(p.link_selector)?.href || '';
if (p.link_regex === null ? link !== '' : !(new RegExp(p.link_regex).test(link))) faults.push('link is ' + (link || 'absent'));
}
return { pass: faults.length === 0, detail: faults.join('; '), text: text.slice(0, 600), link, map_href: p.row ? (scope.querySelector('a.atlaslink')?.href || '') : null, ref: p.row ? p.row.replace(/^repd-/, '') : null };
})(${JSON.stringify(probe)})`).catch((e) => ({ pass: false, detail: String(e) }));
return { name: probe.name, ...result };
}
/* A probe with `block` loads the page afresh with those URL patterns refused, to see what the
* page says when a file it needs cannot be read. */
async function visitBlocked(id, probe) {
const { targetId } = await send("Target.createTarget", { url: "about:blank" });
const { sessionId } = await send("Target.attachToTarget", { targetId, flatten: true });
const evaluate = async (expression) => (await send("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true }, sessionId)).result?.value;
await send("Network.enable", {}, sessionId);
await send("Network.setBlockedURLs", { urls: probe.block }, sessionId);
await send("Page.navigate", { url: `${base}${id}/` }, sessionId);
let complete = false;
for (let i = 0; i < 240 && !complete; i += 1) { await sleep(250); complete = await evaluate("document.querySelector('#tbody')?.dataset.complete === 'true'").catch(() => false); }
await sleep(1500);
await evaluate("document.querySelector('#clearFilters')?.click()");
const meta = await evaluate("document.querySelector('#resultsMeta')?.textContent || ''");
const result = await runProbe(evaluate, probe);
if (!/of 7,775 records/.test(meta)) { result.pass = false; result.detail = `${result.detail}; table did not complete with the file blocked: ${meta}`; }
await send("Target.closeTarget", { targetId });
return result;
}
async function visit(id, vp) {
const url = `${base}${id}/`;
const origin = new URL(url).origin;
const { targetId } = await send("Target.createTarget", { url: "about:blank" });
const { sessionId } = await send("Target.attachToTarget", { targetId, flatten: true });
const rec = { viewport: vp.name, url, page_errors: [], console_errors: [], failed_same_origin: [], failed_external: [] };
const requests = new Map();
const listen = (msg) => {
if (msg.sessionId !== sessionId) return;
const p = msg.params || {};
if (msg.method === "Runtime.exceptionThrown") rec.page_errors.push(String(p.exceptionDetails?.exception?.description || p.exceptionDetails?.text).slice(0, 300));
if (msg.method === "Runtime.consoleAPICalled" && p.type === "error") rec.console_errors.push(p.args.map((a) => a.value ?? a.description ?? "").join(" ").slice(0, 300));
if (msg.method === "Network.requestWillBeSent") requests.set(p.requestId, p.request.url);
const fail = (u, why) => (u.startsWith(origin) ? rec.failed_same_origin : rec.failed_external).push(`${why} ${u}`.slice(0, 300));
if (msg.method === "Network.loadingFailed" && !p.canceled) fail(requests.get(p.requestId) || "?", p.errorText || "failed");
if (msg.method === "Network.responseReceived" && p.response.status >= 400) fail(p.response.url, String(p.response.status));
};
listeners.add(listen);
await send("Runtime.enable", {}, sessionId);
await send("Network.enable", {}, sessionId);
await send("Page.enable", {}, sessionId);
await send("Emulation.setDeviceMetricsOverride", { width: vp.width, height: vp.height, deviceScaleFactor: 1, mobile: vp.mobile }, sessionId);
await send("Page.navigate", { url }, sessionId);
const evaluate = async (expression) => (await send("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true }, sessionId)).result?.value;
let complete = false;
for (let i = 0; i < 240 && !complete; i += 1) {
await sleep(250);
complete = await evaluate("document.querySelector('#tbody')?.dataset.complete === 'true'").catch(() => false);
}
await sleep(Number(process.env.SETTLE_MS || 2500));
// Compare the complete official register/CSV across versions, even when a
// successor opens its Solar tab by default. Category behavior has its own probes.
await evaluate("document.querySelector('#clearFilters')?.click()");
await sleep(100);
const state = await evaluate(`(() => {
const q = (s) => document.querySelector(s);
const meta = q('#resultsMeta')?.textContent || '';
const rows = [...document.querySelectorAll('#tbody tr')];
const links = (sel) => rows.map((r) => r.querySelector(sel)?.href || '').filter(Boolean);
return {
results_meta: meta,
record_count: Number((meta.match(/of ([\\d,]+) records/) || [])[1]?.replace(/,/g, '') || NaN),
rows_drawn: rows.length,
map_links: links('a.map-link, a[href*="gridatlas/atlas/"]').length,
first_map_link: links('a.map-link, a[href*="gridatlas/atlas/"]')[0] || '',
drawn_map_links: rows.map((r) => [r.id.replace(/^repd-/, ''), r.querySelector('a.atlaslink')?.href || '']).filter((x) => x[1]),
title: document.title,
h1: q('h1')?.textContent || '',
overflow: document.documentElement.scrollWidth > document.documentElement.clientWidth,
features: {
newspaper: !!q('section.newspaper'),
datacentre_news_panel: !!q('#dcNews'),
nearest_datacentres: document.querySelectorAll('[data-feature="nearest-datacentres"]').length,
register_changes_in_rows: document.querySelectorAll('[data-feature="register-change"]').length,
gridatlas_state_file: !!document.querySelector('script[src*="gridatlas-state.js"]'),
gridatlas_state_notes: document.querySelectorAll('.ga-state').length,
register_changes_section: !!q('#regChanges'),
},
};
})()`).catch((e) => ({ error: String(e) }));
Object.assign(rec, { complete }, state);
if (!vp.mobile) {
// CSV export of the unfiltered table: row count, header and a hash of the body.
const dir = mkdtempSync(join(tmpdir(), "pn-csv-"));
try {
await send("Browser.setDownloadBehavior", { behavior: "allow", downloadPath: dir });
await evaluate("document.querySelector('#exportInline')?.click()");
let file = "";
for (let i = 0; i < 60 && !file; i += 1) { await sleep(250); file = readdirSync(dir).find((f) => f.endsWith(".csv")) || ""; }
if (file) {
const lines = readFileSync(join(dir, file), "utf8").replace(/^\uFEFF/, "").split("\r\n").filter((l) => l.length);
rec.csv = { rows: lines.length - 1, header: lines[0], header_sha256: createHash("sha256").update(lines[0]).digest("hex"), body_sha256: createHash("sha256").update(lines.slice(1).join("\n")).digest("hex") };
} else rec.csv = { error: "no CSV file was downloaded" };
} catch (e) { rec.csv = { error: String(e) }; }
rmSync(dir, { recursive: true, force: true });
}
{
rec.probes = [];
for (const probe of PROBES[id] || []) {
if (probe.block || (probe.needs_external && !EXTERNAL)) continue;
rec.probes.push(await runProbe(evaluate, probe));
}
await evaluate(`(() => { const i = document.querySelector('#search'); i.value = ''; i.dispatchEvent(new Event('input', { bubbles: true })); })()`);
}
if (process.env.PROBE_SEARCH) {
// Optional probe: type a search and report the first row, to look at one named project.
await evaluate(`(() => { const i = document.querySelector('#search'); i.value = ${JSON.stringify(process.env.PROBE_SEARCH)}; i.dispatchEvent(new Event('input', { bubbles: true })); })()`);
await sleep(1500);
rec.probe = await evaluate(`(() => { const tr = document.querySelector('#tbody tr'); return { rows: document.querySelectorAll('#tbody tr').length, register_change: tr?.querySelector('[data-feature="register-change"]')?.textContent || '', changes_listed: document.querySelectorAll('#regChanges .rc-item').length, notes: document.querySelectorAll('.ga-state').length, nearest_datacentre: tr?.queryS … [line shortened here: 848 characters; full line on GitHub]
}
if (process.env.SHOT_DIR) {
const shot = await send("Page.captureScreenshot", { format: "png" }, sessionId).catch(() => null);
if (shot) writeFileSync(join(process.env.SHOT_DIR, `${id}-${vp.name}.png`), Buffer.from(shot.data, "base64"));
}
listeners.delete(listen);
await send("Target.closeTarget", { targetId });
return rec;
}
const out = {};
for (const id of ids) {
out[id] = [];
for (const vp of VIEWPORTS) {
const rec = await visit(id, vp).catch((e) => ({ viewport: vp.name, error: String(e) }));
if (!vp.mobile && rec.probes) for (const probe of PROBES[id] || []) if (probe.block) rec.probes.push(await visitBlocked(id, probe).catch((e) => ({ name: probe.name, pass: false, detail: String(e) })));
out[id].push(rec);
console.log(`${id} ${vp.name}: complete=${rec.complete} records=${rec.record_count} rows=${rec.rows_drawn} page_errors=${rec.page_errors?.length} same_origin_failed=${rec.failed_same_origin?.length} external_failed=${rec.failed_external?.length}`);
}
}
writeFileSync(outPath, JSON.stringify(out, null, 1) + "\n");
ws.close();
chrome.kill();
await sleep(300);
rmSync(profile, { recursive: true, force: true });Build Datacentre Context
A Python command-line tool in the pipeline release folder of GlobalGrid2050 that reads PipelineNews datacentre context, datacentre proximity, nearest datacentre and datacentres, using SHA-256.
automationglobalgrid2050 / automation/pipeline_release/build_datacentre_context.py · lines 1–74 of 74 · Entry point
- What it does
- It loads PipelineNews datacentre context, datacentre proximity, nearest datacentre and datacentres. Defines sha, main. Uses libraries hashlib, json, shutil, sys, pathlib. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'datacentre'): 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: JSON file pipelinenews_datacentre_context.json; JSON file datacentre_proximity.json; JSON file nearest_datacentre.json; JSON file datacentres.json; command-line arguments. Out: JSON file datacentres.json.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It is built from the sha step (`sha`). Copy the Renewable Energy Planning Database (REPD) and data-centre proximity context into a version folder.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- globalgrid2050 · automation/pipeline_release · Python CLI
- Uses
- hashlib, json, shutil, sys, pathlib
- Used by
- none found
- Produces
- sha, main
- Defines here
- sha, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/pipeline_release/build_datacentre_context.py:1-74 · blob 507f5787acddcd4ae8d2f983b4a2a22439e681bd · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Copy the REPD and data-centre proximity context into a version folder.
build_datacentre_context.py <version folder> [<data-centre register geojson>]
With the register file (GridAtlas data/uk_datacentre_pipeline_<generation>.geojson, the convergence
build's own input) each site also carries the register's source entries: dataset, licence as recorded,
licence status as recorded, attribution and source link. Without it the sources are left out.
Writes, under <version folder>/convergence/:
nearest_datacentre.json byte copy of dist/convergence/2026q3/pipelinenews/pipelinenews_datacentre_context.json
(one row per REPD Ref ID: nearest register site, straight-line km, counts within 10/25/50 km)
datacentres.json the 226 register sites reduced to what the page shows: the register's own id, name,
status, operator, point and its precision, and the register's own MW fields
manifest.json sources and sha256 of both
Nothing is computed here: every figure is the convergence build's. Blank MW stays null (unknown).
"""
import hashlib
import json
import shutil
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
SIDE = "dist/convergence/2026q3/pipelinenews/pipelinenews_datacentre_context.json"
PROX = "dist/convergence/2026q3/datacentre_proximity.json"
KEEP = ["id", "name", "status", "operator", "precision", "proximity_reliable", "lat", "lon", "it_load_mw", "grid_connection_mw", "unclassified_mw", "unclassified_mw_label"]
ATTRIBUTION = ("Data-centre sites: © OpenStreetMap contributors, ODbL 1.0; contains public sector information licensed under the Open Government Licence v3.0. "
"Source licence status recorded as unverified in the register; shown for screening only.")
LICENCE_STATE = "shown with attribution; licence status unverified at source"
def sha(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def main():
out = Path(sys.argv[1]) / "convergence"
out.mkdir(exist_ok=True)
shutil.copyfile(ROOT / SIDE, out / "nearest_datacentre.json")
prox = json.loads((ROOT / PROX).read_text())
sites = [{k: r.get(k) for k in KEEP} for r in prox["records"]]
register = None
if len(sys.argv) > 2:
raw = Path(sys.argv[2]).read_bytes()
features = {f["id"]: f["properties"] for f in json.loads(raw)["features"]}
assert set(features) == {s["id"] for s in sites}, "register ids and convergence ids differ"
licences = {}
for s in sites:
s["sources"] = [{k: src.get(k) for k in ("id", "dataset", "licence", "licence_status", "licence_url", "attribution", "url", "retrieved")} for src in features[s["id"]].get("sources", [])]
assert s["sources"], "site without a source entry: " + s["id"]
for src in s["sources"]:
key = "%s (%s)" % (src["licence"], src["licence_status"])
licences[key] = licences.get(key, 0) + 1
register = {"file": "data/" + Path(sys.argv[2]).name, "repository": "https://github.com/Ventusltd/gridatlas", "sha256": hashlib.sha256(raw).hexdigest(),
"source_entries": sum(licences.values()), "source_entries_by_licence_and_status": licences}
doc = {"schema": "globalgrid2050.pipeline-news.datacentre-sites.v1",
"note": "UK data-centre register sites as carried by the convergence build; ids are the register's own. MW fields are the register's and are null when not stated. A point with precision other than exact_site or settlement is not used for distance.",
"source": PROX, "source_sha256": sha(ROOT / PROX), "register": register,
"attribution": ATTRIBUTION, "licence_state": LICENCE_STATE, "sites": sites}
(out / "datacentres.json").write_text(json.dumps(doc, ensure_ascii=False, separators=(",", ":")) + "\n")
manifest = {"schema": "globalgrid2050.pipeline-news.datacentre-context-manifest.v1",
"caveat": "Straight-line distance between published points. Proximity is screening context only: it is not a grid connection, a capacity statement or a relationship between a project and a data centre.",
"attribution": ATTRIBUTION, "licence_state": LICENCE_STATE, "register": register,
"files": [{"file": "nearest_datacentre.json", "source": SIDE, "sha256": sha(out / "nearest_datacentre.json"), "rows": len(json.loads((out / "nearest_datacentre.json").read_text())["rows"])},
{"file": "datacentres.json", "source": PROX, "source_sha256": doc["source_sha256"], "sha256": sha(out / "datacentres.json"), "sites": len(sites)}]}
(out / "manifest.json").write_text(json.dumps(manifest, indent=1) + "\n")
print(json.dumps(manifest["files"]))
if __name__ == "__main__":
main()Build Register Events
A Python command-line tool in the pipeline release folder of GlobalGrid2050 that reads register changes and the Renewable Energy Planning Database (REPD) register, using SHA-256.
automationglobalgrid2050 / automation/pipeline_release/build_register_events.py · lines 1–46 of 46 · Entry point
- What it does
- It loads register changes and the REPD register. Defines main. Uses libraries hashlib, json, sys, pathlib. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): 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: the REPD register.
- Inputs & outputs
- In: JSON file repd_events_2026q3.json; JSON file build_manifest.json; command-line arguments. Out: JSON file register_changes.json.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- Reduce the REPD register-change events to the rows a Pipeline News version carries.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- globalgrid2050 · automation/pipeline_release · Python CLI
- Uses
- hashlib, json, sys, pathlib
- Used by
- none found
- Produces
- main
- Defines here
- main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/pipeline_release/build_register_events.py:1-46 · blob ebc6b66fe2ab559db657f2a0e5501aab5744720f · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Reduce the REPD register-change events to the rows a Pipeline News version carries.
build_register_events.py <version folder>
Reads dist/news/repd_events_2026q3.json (events derived from comparing the July and October
2026 REPD releases) and writes <version folder>/events/register_changes.json with the events
whose REPD Ref ID is in the version's spine, in the feed's own order. Nothing is rescored or
reworded: type, date, headline and score are the feed's. Keyed by REPD Ref ID only.
"""
import hashlib
import json
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
SRC = "dist/news/repd_events_2026q3.json"
def main():
folder = Path(sys.argv[1])
raw = (ROOT / SRC).read_bytes()
feed = json.loads(raw)
refs = set()
manifest = json.loads((folder / "data/v9.1/build_manifest.json").read_text())
for part in manifest["project_partitions"]:
refs |= {str(p["repd_ref"]) for p in json.loads((folder / part["path"]).read_text())["projects"]}
events = [{"ref": str(e["ref"]), "type": e["event_type"], "date": e.get("event_date"), "date_source": e.get("event_date_source"),
"headline": e["headline"], "score": e.get("score"), "previous_status": e.get("previous_status"), "status": e.get("status")}
for e in feed["events"] if str(e["ref"]) in refs]
counts = {}
for e in events:
counts[e["type"]] = counts.get(e["type"], 0) + 1
out = {"schema": "globalgrid2050.pipeline-news.register-changes.v1",
"label": "Register changes, %s to %s REPD" % (feed["previous"]["label"], feed["new"]["label"]),
"note": "Changes found by comparing two official REPD releases. These are register events, not news stories: each line is generated from REPD fields only. A status change is dated by the register and can lag the real-world decision.",
"source": SRC, "source_sha256": hashlib.sha256(raw).hexdigest(), "source_events": feed["event_count"],
"events_in_this_version": len(events), "projects_with_an_event": len({e["ref"] for e in events}),
"max_score": feed.get("max_score"), "counts": counts, "events": events}
(folder / "events").mkdir(exist_ok=True)
(folder / "events/register_changes.json").write_text(json.dumps(out, ensure_ascii=False, separators=(",", ":")) + "\n")
print(json.dumps({k: out[k] for k in ("events_in_this_version", "projects_with_an_event", "source_events", "counts")}))
if __name__ == "__main__":
main()