GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / globalgrid2050 / automation/energy_context_ui/20261118

Evidence Spec and 8 more files

A test in the browser folder of GlobalGrid2050 covering the Renewable Energy Planning Database (REPD) register, solar and battery storage (BESS), using SHA-256.

700 lines of JavaScript and Python from globalgrid2050, in 9 files. Topic: Electricity markets and data pipelines. Section 774 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. Verify Closure ingest · globalgrid2050 / automation/energy_context_ui/20261118/verify-closure.mjs lines 1–16
  2. View interaction · globalgrid2050 / automation/energy_context_ui/20261118/view.mjs lines 1–71
  3. News — Acquisition other · globalgrid2050 / automation/news/acquisition/__init__.py lines 1–1
  4. Analytics storage · globalgrid2050 / automation/news/acquisition/analytics.py lines 1–172
  5. Evidence Spec test · globalgrid2050 / automation/news/acquisition/browser/evidence.spec.mjs lines 1–213
  6. Harness Test test · globalgrid2050 / automation/news/acquisition/browser/harness.test.mjs lines 1–77
  7. News Priority Config other · globalgrid2050 / automation/news/acquisition/browser/news-priority.config.mjs lines 1–14
  8. News Priority Spec test · globalgrid2050 / automation/news/acquisition/browser/news-priority.spec.mjs lines 1–119
  9. Playwright Config other · globalgrid2050 / automation/news/acquisition/browser/playwright.config.mjs lines 1–17

Verify Closure

A JavaScript module in the energy context ui folder of GlobalGrid2050 that reads energy context, policy, review and facts, using SHA-256.

ingestglobalgrid2050 / automation/energy_context_ui/20261118/verify-closure.mjs · lines 1–16 of 16 · version 2026-11-18 · Not reached from any entry point (candidate for review) · pattern bytes (shared by 19 files)

What it does
It loads energy context, policy, review and facts. Defines bytes. Uses libraries node:assert/strict, node:fs, node:path, node:crypto. 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: JSON file energy-context.v945.json; JSON file closure.json; JSON file policy.json; JSON file review.json; JSON file facts.json; JSON file notice.json; command-line arguments.
What it achieves
Its name says it verifies closure. Defines `bytes`.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · automation/energy_context_ui/20261118 · JavaScript module
Uses
node:assert/strict, node:fs, node:path, node:crypto
Used by
none found
Produces
bytes
Defines here
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/energy_context_ui/20261118/verify-closure.mjs:1-16 · blob 94efb43f2818f2f29b8cdba4220dddb7e68fbee2 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import {resolve,relative} from 'node:path';
import {createHash} from 'node:crypto';
const release=resolve(process.argv[2]),root=resolve(release,'../..'),base='automation/energy_context_ui/20261118/';
const bytes=path=>readFileSync(resolve(root,path)),hash=data=>createHash('sha256').update(data).digest('hex');
const pin=JSON.parse(readFileSync(resolve(release,'contracts/energy-context.v945.json'))),raw=bytes(base+'closure.json');
assert.equal(pin.schema,'pipeline.energy-context.v1');assert.match(pin.sha256,/^[a-f0-9]{64}$/);assert.equal(hash(raw),pin.sha256,'context manifest pin');
const manifest=JSON.parse(raw);assert.equal(manifest.schema,'pipeline.energy-context-closure.v1');
const expected=['model.mjs','view.mjs','styles.css','policy.json','review.json','verify-closure.mjs'].map(x=>base+x).concat(['automation/document_facts_ui/20261117-v939/model.mjs','automation/document_facts_ui/20261117-v939/facts.json','automation/grid_notice_ui/20261117-v938/notice.json','automation/grid_notice_ui/20261117-v938/model.mjs']);
assert.deepEqual(Object.keys(manifest.files).sort(),expected.sort(),'complete explicit runtime/checker closure');
for(const [path,sha]of Object.entries(manifest.files)){assert(!relative(root,resolve(root,path)).startsWith('..'));assert.match(sha,/^[a-f0-9]{64}$/);assert.equal(hash(bytes(path)),sha,path);}
const html=readFileSync(resolve(release,'index.html'),'utf8');
for(const name of ['view.mjs','styles.css'])assert(html.includes('../../'+base+name+'" integrity="sha256-'+Buffer.from(manifest.files[base+name],'hex').toString('base64')+'"'),name+' actual-byte SRI');
const source=readFileSync(resolve(release,'scripts/plugins/live-news.js'),'utf8');assert.equal(source.split('getViewAdapter:function(){return qualityAdapter;},').length,2,'single existing-adapter getter');
console.log('V9.45 complete energy context shared SHA/SRI closure: PASS');

View

A JavaScript module in the energy context ui folder of GlobalGrid2050 that draws policy, review, facts and notice, using SHA-256.

interactionglobalgrid2050 / automation/energy_context_ui/20261118/view.mjs · lines 1–71 of 71 · version 2026-11-18 · Entry point · pattern newsQuery (shared by 2 files)

What it does
It draws policy, review, facts and notice. Defines 13 functions or classes, including el, link, newsQuery, newsSelect, showContext. Side effects: changes the web page (DOM); 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: JSON file policy.json; JSON file review.json; JSON file facts.json; JSON file notice.json.
Downstream impact
Used directly by 2 files: News Compact (globalgrid2050); GlobalGrid2050 — UK Renewables Pipeline Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/). Reached from 4 other entry points, including GlobalGrid2050 Pipeline Legal Evidence Workflow (globalgrid2050); V923 Public Readback Workflow (neural-link-between-agents); A4 Legal Model (globalgrid2050).
What it achieves
It shows context (`showContext`), renders main (`renderMain`) and draws policy (`drawPolicy`). Defines `link`, `newsQuery`, `newsSelect` and 9 more. It responds to click, pipeline and DOMContentLoaded events.
Why it matters
Loaded by the UK Renewables Pipeline page at https://globalgrid2050.com/uk_renewables_pipeline/202611280922/. Also imported by News Compact.
Application
globalgrid2050 · automation/energy_context_ui/20261118 · JavaScript module
Uses
Model (import)
Used by
imported by News Compact (import), loaded by GlobalGrid2050 — UK Renewables Pipeline Page (script src)
Produces
el, link, newsQuery, newsSelect, showContext, renderMain, topicFilter, buttons, drawPolicy, drawRelated, selectOrigin, rememberNews
Defines here
el, link, newsQuery, newsSelect, showContext, renderMain, topicFilter, buttons, drawPolicy, drawRelated, selectOrigin, rememberNews, connectEntry
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/energy_context_ui/20261118/view.mjs:1-71 · blob 613c39de7e668a81521b3b9f0e3dfb2e9ed9b123 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import {acceptedPolicy,acceptedGridContext,policySource,relatedHeadlines,contextForOrigin,infrastructureEntries,newsContextBase,newsContextUrl,requestedContext} from './model.mjs';
const D=document,news=D.querySelector('.pn-news-quality'),grid=D.getElementById('gridPanel');
const el=(tag,text)=>{const n=D.createElement(tag);if(text!==undefined)n.textContent=text;return n;};
const link=(text,url)=>{const a=el('a',text);a.href=url;a.target='_blank';a.rel='noopener noreferrer';return a;};
let origin=null,policy=null,gridContext=null,feed=window.pipelineHeadlineDocument,requestApplied=false,activeTopic=null,newsApi=null,viewAdapter=null,lastView=null;
const returnKey='pipelineEnergyNewsReturn',filterKinds=['source','topic','category','kind'];
const newsQuery=()=>D.querySelector('.pn-news-header-search input');
const newsSelect=kind=>D.querySelector('.pn-news-filter-tools select[aria-label="News '+({source:'publisher',topic:'topic',category:'category',kind:'ranking source type'}[kind])+'"]');
const policyPanel=el('details'),summary=el('summary','AI demand, clean energy and grid policy');policyPanel.className='pn-energy-context';policyPanel.id='energyPolicyContext';policyPanel.append(summary);
const body=el('div');policyPanel.append(body);news?.append(policyPanel);
const related=el('details'),relatedBody=el('div');related.className='pn-energy-context';related.id='journeyNewsContext';related.append(el('summary','Journey context — original news and official sources'),relatedBody);grid?.append(related);
const contextStatus=el('div'),contextLabel=el('span'),allHeadlines=el('button','All original headlines');contextStatus.className='pn-news-context-status';contextStatus.id='headlineContextStatus';contextStatus.hidden=true;contextStatus.setAttribute('role','status');allHeadlines.type='button';contextStatus.append(contextLabel,allHeadlines);D.getElementById('liveNews')?.before(contextStatus);
const topicLabels={datacentre:'data-centre infrastructure',grid:'grid infrastructure',storage:'storage and flexibility',renewables:'energy transition',solar:'solar',wind:'wind'};
function showContext(){contextStatus.hidden=!activeTopic;contextStatus.dataset.topic=activeTopic||'';contextLabel.textContent=activeTopic?'Headline context: '+topicLabels[activeTopic]+'. Reset for the complete original view.':'';}
function renderMain(view=lastView){if(!viewAdapter||!view)return false;viewAdapter({...view,entries:infrastructureEntries(view.entries,activeTopic)});showContext();return true;}
function connectNews(){const api=window.pipelineHeadlines;if(newsApi===api&&viewAdapter)return true;const adapter=api?.getViewAdapter?.();if(typeof adapter!=='function')return false;newsApi=api;viewAdapter=adapter;api.attachView(view=>{lastView=view;renderMain(view);});const clear=D.querySelector('.pn-news-filter-tools button');clear?.addEventListener('click',()=>{requestApplied=true;activeTopic=n  … [line shortened here: 433 characters; full line on GitHub]
allHeadlines.addEventListener('click',()=>{requestApplied=true;activeTopic=null;const clear=D.querySelector('.pn-news-filter-tools button');if(clear)clear.click();else renderMain();});
function topicFilter(topic){
 const select=D.querySelector('.pn-news-filter-tools select[aria-label="News topic"]'),category=D.querySelector('.pn-news-filter-tools select[aria-label="News category"]'),query=D.querySelector('.pn-news-header-search input');
 if(!select||!query)return false;
 for(const node of D.querySelectorAll('.pn-news-filter-tools select'))node.value='';query.value='';
 if(connectNews()){activeTopic=topic;renderMain();D.getElementById('headlinesHeading')?.scrollIntoView({block:'start'});return true;}
 if([...select.options].some(o=>o.value===topic)){select.value=topic;select.dispatchEvent(new Event('change',{bubbles:true}));}
 else if(category&&[...category.options].some(o=>o.value===topic)){category.value=topic;category.dispatchEvent(new Event('change',{bubbles:true}));}
 else{query.value={grid:'grid',storage:'storage',renewables:'renewable',datacentre:'datacentre'}[topic]||topic;query.dispatchEvent(new Event('input',{bubbles:true}));}
 D.getElementById('headlinesHeading')?.scrollIntoView({block:'start'});return true;
}
function buttons(host){
 const controls=el('div');controls.className='pn-energy-actions';
 for(const [topic,label] of [['datacentre','Data-centre news'],['grid','Grid infrastructure news'],['storage','Storage and flexibility'],['renewables','Energy-transition news']]){
  const button=el('button',label);button.type='button';button.dataset.newsTopic=topic;button.addEventListener('click',()=>{requestApplied=true;const ok=topicFilter(topic);status.textContent=ok?'Applied '+label.toLowerCase()+' to the existing news controls; zero matches is a valid result.':'News controls are not available yet.';});controls.append(button);
 }const status=el('p');status.setAttribute('role','status');host.append(controls,status);
}
function drawPolicy(){
 body.replaceChildren();body.append(el('p','Explore renewable supply, AI electricity demand and grid upgrades using the existing news topics.' ));buttons(body);
 body.append(link('UK Government Data Centre Covenant',policySource));
 if(gridContext){const upgrade=el('details');upgrade.dataset.officialContext='planning:EN020026';upgrade.append(el('summary','Official grid-upgrade context — Sea Link'),el('p',`Consent decision ${gridContext.decision.value} (DAY); proposed transmission up to ${gridContext.planned_upper_bound.value} ${gridContext.planned_upper_bound.unit}. Not commissioned or available capacity; no selected-asset a  … [line shortened here: 898 characters; full line on GitHub]
 if(!policy){body.append(el('p','Policy facts await source-integrity and independent review. The official publication remains available.'));return;}
 body.append(el('p',`${policy.publisher} · published ${policy.published_date.value} (DAY). National policy context; no project compliance assessment.`));
 const ul=el('ul');for(const theme of policy.themes){const li=el('li');li.append(link(theme.label,policy.source_url+'#'+theme.fragment));ul.append(li);}body.append(ul);
 for(const q of policy.quantities)body.append(el('p',`${q.id==='new_facility_pue'?'PUE '+q.value+' or better':q.value+' '+q.unit} — ${q.meaning}.`));
 const details=el('details');details.append(el('summary','Source and fact provenance'),el('p',`Retrieved ${policy.retrieved_at}. Source SHA-256 ${policy.source_sha256}.`));
 for(const q of policy.quantities)details.append(el('p',`${q.id}: ${q.locator}; paragraph SHA-256 ${q.text_sha256}`));
 details.append(link('Open Government Licence v3.0',policy.rights.licence_url),el('p','Government-authored facts only. No image or third-party material reproduced.'));body.append(details);
}
function drawRelated(){
 relatedBody.replaceChildren();const context=contextForOrigin(origin);
 relatedBody.append(el('p',context?`${context.origin_type.toUpperCase()} ${context.origin_id}: topic context only. Headlines are not evidence of a connection, supply agreement or project association.`:'Choose a REPD project, data centre or substation JOURNEY to retain its origin while exploring related news topics.'));
 buttons(relatedBody);
 if(context){const items=relatedHeadlines(feed,origin);const ul=el('ul');for(const {item} of items){const li=el('li');li.append(link(item.title,item.link),el('span',` — ${item.source}; ${item.date?'publisher date '+item.date:item.first_seen?'first collected '+item.first_seen:'article date unknown'}`));ul.append(li);}relatedBody.append(items.length?ul:el('p','No matching topic headlines in the curr  … [line shortened here: 447 characters; full line on GitHub]
 relatedBody.append(link('Official Data Centre Covenant policy context',policySource),el('p','Behind the meter: documented on-site generation, storage and demand. Front of meter: documented network assets and upgrades. A nearby asset is not a proven supplier or connection.'));
}
function selectOrigin(value){origin=contextForOrigin(value);drawRelated();return !!origin;}
function rememberNews(savedOrigin=origin){const query=newsQuery();if(!query||query.value.length>2048)return;const filters={query:query.value,...Object.fromEntries(filterKinds.map(kind=>[kind,newsSelect(kind)?.value||'']))};try{history.replaceState({...history.state,[returnKey]:{path:location.pathname,filters,origin:savedOrigin,contextTopic:activeTopic}},'');}catch{}}
function restoreNews(saved){const query=newsQuery();if(!query||!saved?.filters||typeof saved.filters.query!=='string'||saved.filters.query.length>2048)return false;if(saved.contextTopic&&requestedContext('?news_topic='+encodeURIComponent(saved.contextTopic))&&connectNews()){activeTopic=saved.contextTopic;renderMain();}let complete=true;query.value=saved.filters.query;for(const kind of filterKinds)  … [line shortened here: 702 characters; full line on GitHub]
function connectEntry(){const api=window.pipelineJourneyEntry,base=newsContextBase(location.origin+location.pathname);if(!base||api?.schema!=='pipeline.journey-entry.v1'||typeof api.setNewsContextUrl!=='function')return false;try{api.setNewsContextUrl(base);return true;}catch{return false;}}
window.pipelineEnergyContext={selectOrigin,topic:()=>activeTopic,newsBase:()=>newsContextBase(location.origin+location.pathname),newsUrl:value=>newsContextUrl(location.origin+location.pathname,value)};
window.addEventListener('pipeline-news-ready',()=>queueMicrotask(connectNews));D.addEventListener('DOMContentLoaded',connectNews,{once:true});connectNews();
window.addEventListener('pipeline-journey-ready',connectEntry);connectEntry();
window.addEventListener('pipeline-journey-origin',event=>{if(selectOrigin(event.detail))rememberNews();});
D.addEventListener('click',event=>{if(event.target.closest?.('#journeyAtlasNav'))rememberNews(null);},true);
for(const node of [newsQuery(),...filterKinds.map(newsSelect)].filter(Boolean))for(const type of ['input','change'])node.addEventListener(type,event=>{if(event.isTrusted)requestApplied=true;});
const applyRequest=()=>{if(requestApplied||!Array.isArray(feed?.items))return;const saved=history.state?.[returnKey];if(saved?.path===location.pathname){setTimeout(()=>{if(!requestApplied)requestApplied=restoreNews(saved);},0);return;}const request=requestedContext(location.search);if(request){if(request.origin)selectOrigin(request.origin);setTimeout(()=>{if(!requestApplied)requestApplied=topicFil  … [line shortened here: 427 characters; full line on GitHub]
window.addEventListener('pipeline-feed-loaded',event=>{feed=event.detail;drawRelated();applyRequest();});
drawPolicy();drawRelated();
if(feed)applyRequest();
async function boundedText(name,max){const response=await fetch(new URL(name,import.meta.url),{signal:AbortSignal.timeout(4000)});if(!response.ok)throw Error('Source unavailable');const reader=response.body.getReader(),chunks=[];let size=0;try{for(;;){const {done,value}=await reader.read();if(done)break;size+=value.length;if(size>max)throw Error('Source bound exceeded');chunks.push(value);}}finall  … [line shortened here: 604 characters; full line on GitHub]
try{const [a,b]=await Promise.all([boundedText('policy.json',16000),boundedText('review.json',8000)]);policy=await acceptedPolicy(a,JSON.parse(b));}catch{}
policyPanel.dataset.state=policy?'source-qualified':'withheld';drawPolicy();
try{const [facts,notice]=await Promise.all([boundedText('../../document_facts_ui/20261117-v939/facts.json',16000),boundedText('../../grid_notice_ui/20261117-v938/notice.json',16000)]);gridContext=await acceptedGridContext(facts,JSON.parse(notice));}catch{}
policyPanel.dataset.gridContext=gridContext?'source-qualified':'withheld';drawPolicy();

News — Acquisition

A Python module in the automation folder of GlobalGrid2050.

otherglobalgrid2050 / automation/news/acquisition/__init__.py · lines 1–1 of 1

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: Prospecting (globalgrid2050); Test Acquisition Analytics (globalgrid2050); Test Acquisition Run (globalgrid2050). Reached from 5 other entry points, including GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); Build Prospecting Priority (globalgrid2050).
What it achieves
Solar-only research acquisition; machine associations are always provisional.
Why it matters
Imported by Prospecting. Checked by 2 tests, including Test Acquisition Analytics.
Application
globalgrid2050 · automation/news/acquisition · Python module
Uses
none found
Used by
imported by Prospecting (import), imported by Test Acquisition Analytics (import), imported by Test Acquisition Run (import)
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/news/acquisition/__init__.py:1-1 · blob e41e2c6b2473b37bf0be5268c367d03a27e73504 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Solar-only research acquisition; machine associations are always provisional."""

Analytics

A Python module in the acquisition folder of GlobalGrid2050 that reads projects, using SHA-256.

storageglobalgrid2050 / automation/news/acquisition/analytics.py · lines 1–172 of 172 · pattern _connect (shared by 2 files)

What it does
It loads projects. Defines 9 functions or classes, including _require, _json, _sha, _rows, _connect. Uses libraries __future__, datetime, hashlib, json, pathlib. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
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: Parquet file projects.parquet; Parquet file evidence.parquet; DuckDB queries.
Downstream impact
Used directly by 3 files: News — Acquisition (globalgrid2050); Test Acquisition Analytics (globalgrid2050); Test Acquisition Run (globalgrid2050). Reached from 2 other entry points, including GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
Immutable analytical Parquet projection; SQLite remains the operational store.
Why it matters
Imported by News — Acquisition. Checked by 2 tests, including Test Acquisition Analytics.
Application
globalgrid2050 · automation/news/acquisition · Python module
Uses
Evidence Store (relative import), __future__, datetime, hashlib, json, pathlib, tempfile, duckdb
Used by
imported by News — Acquisition (relative import), imported by Test Acquisition Analytics (import), imported by Test Acquisition Run (import)
Produces
validate_analytics, export_analytics
Defines here
_require, _json, _sha, _rows, _connect, _literal, _receipt, validate_analytics, export_analytics
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/acquisition/analytics.py:1-172 · blob 0e9c10a971e275ab9c7b4fa83c34b12dba97c3fb · 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
"""Immutable analytical Parquet projection; SQLite remains the operational store.

Pinned upstream conventions and integration boundary are in ANALYTICS.md.
"""
from __future__ import annotations

from datetime import datetime
import hashlib
import json
from pathlib import Path
import tempfile

import duckdb

from .evidence_store import EvidenceValidationError, validate_snapshot

SCHEMA = "globalgrid2050.solar-evidence.analytics.v1"
TABLES = {
    "projects": [
        ("project_id", "VARCHAR"), ("name", "VARCHAR"),
        ("latitude", "DOUBLE"), ("longitude", "DOUBLE"), ("status", "VARCHAR"),
        ("evidence_count", "BIGINT"), ("provisional_count", "BIGINT"),
        ("verified_count", "BIGINT"), ("last_event", "VARCHAR"),
        ("last_researched_at", "VARCHAR"),
    ],
    "evidence": [
        ("project_id", "VARCHAR"), ("id", "VARCHAR"), ("url", "VARCHAR"),
        ("title", "VARCHAR"), ("pub_date", "VARCHAR"), ("source_id", "VARCHAR"),
        ("publisher", "VARCHAR"), ("status", "VARCHAR"), ("match_method", "VARCHAR"),
        ("first_seen", "VARCHAR"), ("last_seen", "VARCHAR"),
    ],
}
ORDERS = {"projects": "project_id", "evidence": "project_id, url"}


def _require(condition, message):
    if not condition:
        raise EvidenceValidationError(message)


def _json(value):
    return (json.dumps(value, sort_keys=True, ensure_ascii=False,
                       allow_nan=False, indent=2) + "\n").encode("utf-8")


def _sha(data):
    return hashlib.sha256(data).hexdigest()


def _rows(payload):
    # Independent Python reference for complete DuckDB readback comparison.
    projects = sorted(payload["projects"], key=lambda row: row["project_id"])
    evidence = sorted(
        ({**article, "project_id": project["project_id"]}
         for project in projects for article in project["evidence"]),
        key=lambda row: (row["project_id"], row["url"]),
    )
    return {name: [tuple(row[column] for column, _ in TABLES[name]) for row in rows]
            for name, rows in (("projects", projects), ("evidence", evidence))}


def _connect():
    connection = duckdb.connect(":memory:")
    connection.execute("SET threads=1")
    connection.execute("SET preserve_insertion_order=true")
    return connection


def _literal(path):
    # COPY's destination is SQL syntax; values elsewhere use bound parameters.
    return "'" + Path(path).as_posix().replace("'", "''") + "'"


def _receipt(directory, manifest):
    return {"schema": SCHEMA, "directory": directory.name,
            "manifest": directory.name + "/manifest.json",
            "sha256": _sha((directory / "manifest.json").read_bytes()),
            "project_count": manifest["project_count"],
            "evidence_count": manifest["evidence_count"], "review_required": True}


def validate_analytics(directory, payload, *, expected_project_ids):
    """Read-only verification of every artifact and every projected source row."""
    validate_snapshot(payload, expected_project_ids)
    directory = Path(directory)
    names = {"projects.parquet", "evidence.parquet", "manifest.json"}
    _require(directory.is_dir() and not directory.is_symlink(), "Missing analytical directory")
    _require({p.name for p in directory.iterdir()} == names
             and all((directory / n).is_file() and not (directory / n).is_symlink() for n in names),
             "Analytical artifact closure mismatch")
    manifest = json.loads((directory / "manifest.json").read_text(encoding="utf-8"))
    expected_rows = _rows(payload)
    expected_header = {
        "schema": SCHEMA, "source_snapshot_sha256": _sha(_json(payload)),
        "generated_at": payload["generated_at"], "seed_release": payload["seed_release"],
        "project_count": payload["project_count"], "evidence_count": payload["evidence_count"],
        "review_required": True, "sources": payload["sources"],
    }
    _require(set(manifest) == set(expected_header) | {"runtime", "artifacts"}
             and all(manifest[key] == value for key, value in expected_header.items()),
             "Analytical source identity mismatch")
    _require(manifest["runtime"] == {"duckdb": duckdb.__version__, "threads": 1},
             "Analytical runtime mismatch; immutable rebuild requires a new generation")
    _require(set(manifest["artifacts"]) == set(TABLES), "Analytical artifact manifest mismatch")
    with _connect() as connection:
        for table, columns in TABLES.items():
            path = directory / (table + ".parquet")
            data = path.read_bytes()
            expected = {"path": path.name, "sha256": _sha(data), "bytes": len(data),
                        "rows": len(expected_rows[table]), "columns": [list(c) for c in columns],
                        "compression": "ZSTD"}
            _require(manifest["artifacts"][table] == expected, "Analytical artifact hash/schema mismatch")
            relation = connection.read_parquet(str(path))
            _require(list(zip(relation.columns, map(str, relation.types))) == columns,
                     "Analytical Parquet schema mismatch")
            relation.create_view(table)
            actual = connection.execute(f"SELECT * FROM {table} ORDER BY {ORDERS[table]}").fetchall()
            _require(actual == expected_rows[table], "Analytical full-row comparison failed")
            codecs = connection.execute("SELECT DISTINCT compression FROM parquet_metadata(?)", [str(path)]).fetchall()
            _require(all(c[0] == "ZSTD" for c in codecs), "Unexpected analytical compression")
        invalid = connection.execute("""
            SELECT count(*) FROM projects p LEFT JOIN
              (SELECT project_id, count(*) AS n FROM evidence GROUP BY project_id) e
              USING(project_id)
            WHERE p.evidence_count <> coalesce(e.n, 0)
               OR p.provisional_count <> coalesce(e.n, 0) OR p.verified_count <> 0
        """).fetchone()[0]
        orphans = connection.execute("""
            SELECT count(*) FROM evidence e ANTI JOIN projects p USING(project_id)
        """).fetchone()[0]
        _require(invalid == 0 and orphans == 0, "Analytical project/evidence closure mismatch")
    return _receipt(directory, manifest)


def export_analytics(payload, out_dir, *, expected_project_ids):
    """Write validated immutable Parquet alongside snapshots; never move pointers."""
    expected_project_ids = list(expected_project_ids)
    validate_snapshot(payload, expected_project_ids)
    stamp = datetime.fromisoformat(payload["generated_at"].replace("Z", "+00:00")).strftime("%Y%m%dT%H%M%SZ")
    out_dir = Path(out_dir)
    target = out_dir / ("analytics_" + stamp)
    if target.exists():
        return validate_analytics(target, payload, expected_project_ids=expected_project_ids)
    out_dir.mkdir(parents=True, exist_ok=True)
    rows = _rows(payload)
    with tempfile.TemporaryDirectory(prefix=".analytics-build-", dir=out_dir) as temporary:
        staged = Path(temporary) / target.name
        staged.mkdir()
        artifacts = {}
        with _connect() as connection:
            for table, columns in TABLES.items():
                ddl = ", ".join(f"{name} {kind}" for name, kind in columns)
                connection.execute(f"CREATE TABLE {table} ({ddl})")
                if rows[table]:
                    placeholders = ",".join("?" for _ in columns)
                    connection.executemany(f"INSERT INTO {table} VALUES ({placeholders})", rows[table])
                path = staged / (table + ".parquet")
                connection.execute(f"COPY (SELECT * FROM {table} ORDER BY {ORDERS[table]}) "
                                   f"TO {_literal(path)} (FORMAT PARQUET, COMPRESSION ZSTD, ROW_GROUP_SIZE 100000)")
                data = path.read_bytes()
                artifacts[table] = {"path": path.name, "sha256": _sha(data), "bytes": len(data),
                                    "rows": len(rows[table]), "columns": [list(c) for c in columns],
                                    "compression": "ZSTD"}
        manifest = {"schema": SCHEMA, "source_snapshot_sha256": _sha(_json(payload)),
                    "generated_at": payload["generated_at"], "seed_release": payload["seed_release"],
                    "project_count": payload["project_count"], "evidence_count": payload["evidence_count"],
                    "review_required": True, "sources": payload["sources"],
                    "runtime": {"duckdb": duckdb.__version__, "threads": 1}, "artifacts": artifacts}
        (staged / "manifest.json").write_bytes(_json(manifest))
        receipt = validate_analytics(staged, payload, expected_project_ids=expected_project_ids)
        staged.rename(target)
    return receipt

Evidence Spec

A test in the browser folder of GlobalGrid2050 covering the Renewable Energy Planning Database (REPD) register, solar and battery storage (BESS), using SHA-256.

testglobalgrid2050 / automation/news/acquisition/browser/evidence.spec.mjs · lines 1–213 of 213 · Not reached from any entry point (candidate for review) · pattern fixture (shared by 30 files)

What it does
It tests the REPD register, solar and battery storage (BESS). Defines fixture, installRoutes, ready. Uses libraries @playwright/test, node:fs/promises, node:crypto. Side effects: changes the web page (DOM); 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, solar, battery storage (BESS).
Inputs & outputs
In: JSON file latest.json; JSON file evidence.json; JSON file projects.json.
What it achieves
It is built from the install routes helper (`installRoutes`). Defines `fixture`, `installRoutes` and `ready`. It reads `../../../../uk_renewables_pipeline/202611161630/solar1000/manifest.json`.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · automation/news/acquisition/browser · test
Uses
@playwright/test, node:fs/promises, node:crypto
Used by
none found
Produces
fixture, installRoutes, ready
Defines here
fixture, installRoutes, ready
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/acquisition/browser/evidence.spec.mjs:1-213 · blob 0176de7370394c91c7c28fb3e706bc25dd4328c6 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
import {test,expect} from '@playwright/test';
import {readFile} from 'node:fs/promises';
import {createHash} from 'node:crypto';
const release='/uk_renewables_pipeline/202611161630/';
const pointerURL='https://raw.githubusercontent.com/Ventusltd/globalgrid2050/pipeline-evidence-data/dist/news/evidence/latest.json';
const manifest=JSON.parse(await readFile(new URL('../../../../uk_renewables_pipeline/202611161630/solar1000/manifest.json',import.meta.url)));
const schema='globalgrid2050.solar-evidence.provisional.v1';
const generated='2026-11-16T16:30:00Z';
const researchScope='Completed bounded feed scan using strict name/REPD-ID matching; not independent project-first research. No match is not proof no evidence exists.';
const hostileTitle='TEST FIXTURE ONLY: REPD 1018 <img src=x onerror="window.evidenceInjected=true">';
function fixture(){
  const projects=manifest.ids.map((id,i)=>({project_id:id,name:'Synthetic browser fixture',status:i?'RESEARCH_ATTEMPTED_NO_EVIDENCE':'PROVISIONAL',evidence_count:i?0:1,provisional_count:i?0:1,verified_count:0,last_event:null,last_researched_at:generated,evidence:i?[]:[{id:'fixture',url:'https://example.org/test-only-solar-article',title:hostileTitle,pub_date:generated,source_id:'fixture_only',publ  … [line shortened here: 516 characters; full line on GitHub]
  const data={schema,generated_at:generated,source_run_at:generated,seed_release:'202611161244',project_count:1000,evidence_count:1,verified_count:0,review_required:true,sources:[{id:'fixture_only',status:'ok',url:'https://example.org/test-only-feed',rights_review_url:'https://example.org/test-only-rights-receipt',fetched_at:generated,http_status:200,response_sha256:'a'.repeat(64),eligible_for_pub  … [line shortened here: 497 characters; full line on GitHub]
  const body=JSON.stringify(data);
  return {body,pointer:{schema,generated_at:generated,snapshot:'snapshot_20261116T163000Z',json:'snapshot_20261116T163000Z/evidence.json',sha256:{'evidence.json':createHash('sha256').update(body).digest('hex')},project_count:1000,evidence_count:1,review_required:true}};
}
async function installRoutes(page,mode='valid'){
  const localOrigin=new URL(test.info().project.use.baseURL).origin;
  const f=fixture();
  if(mode==='bad-digest')f.pointer.sha256['evidence.json']='0'.repeat(64);
  const data=JSON.parse(f.body);
  if(mode==='invalid-status')data.projects[0].status='VERIFIED';
  if(mode==='no-sources')data.sources=[];
  if(mode==='failed-source')data.sources[0].status='failed';
  if(mode==='unknown-rights')data.sources[0].rights_status='unknown';
  if(mode==='probe-only')data.sources[0].probe_only=true;
  if(mode==='not-eligible')data.sources[0].eligible_for_publication=false;
  if(mode==='missing-rights-receipt')delete data.sources[0].rights_review_url;
  if(mode==='duplicate-source')data.sources.push({...data.sources[0]});
  if(mode==='missing-source-reference')data.projects[0].evidence[0].source_id='unrecorded';
  if(mode==='invalid-run-time')data.source_run_at='2026-02-30T16:30:00Z';
  if(mode==='run-after-generation')data.source_run_at='2026-11-17T16:30:00Z';
  if(mode==='incorrect-scope')data.research_scope='All projects independently researched and verified';
  if(mode==='invalid-http-receipt')data.sources[0].http_status=403;
  if(mode==='invalid-source-hash')data.sources[0].response_sha256='not-a-hash';
  if(mode==='source-after-run')data.sources[0].fetched_at='2026-11-17T16:30:00Z';
  if(mode==='stale'){
    const old='2026-11-08T16:30:00Z';
    data.source_run_at=old;data.sources[0].fetched_at=old;
    for(const project of data.projects){
      project.last_researched_at=old;
      for(const article of project.evidence){article.first_seen=old;article.last_seen=old;article.pub_date=old;}
    }
  }
  if(mode==='retained-source'){
    data.sources[0].fetched_at='2026-11-01T16:30:00Z';
    data.sources.push({...data.sources[0],id:'current_fixture_only',fetched_at:generated});
    Object.assign(data.projects[0].evidence[0],{first_seen:'2026-11-01T16:30:00Z',last_seen:'2026-11-01T16:30:00Z',pub_date:'2026-11-01T16:30:00Z'});
  }
  f.body=JSON.stringify(data);
  if(mode!=='bad-digest')f.pointer.sha256['evidence.json']=createHash('sha256').update(f.body).digest('hex');
  await page.clock.setFixedTime(new Date('2026-11-17T16:30:00Z'));
  await page.route('**/*',async route=>{
    const url=route.request().url();
    if(url===pointerURL){
      if(mode==='unavailable')return route.fulfill({status:503,body:'source unavailable'});
      return route.fulfill({contentType:'application/json',body:JSON.stringify(f.pointer)});
    }
    if(url===new URL(f.pointer.json,pointerURL).href)return route.fulfill({contentType:'application/json',body:f.body});
    if(url.startsWith(localOrigin+'/'))return route.continue();
    // Keep browser smoke deterministic. External service availability is a
    // separate live gate, never inferred from these intercepted test responses.
    return route.abort();
  });
}
async function ready(page){
  await page.goto(release);
  await expect(page.locator('#evidenceCoverage')).toHaveAttribute('data-selection-count','1000');
  await expect(page.locator('#tbody')).toHaveAttribute('data-complete','true');
  await expect(page.locator('#resultsMeta')).toContainText('7,775');
}
test('provisional evidence, escaping, search, map contract, and full CSV',async({page},testInfo)=>{
  const errors=[];page.on('pageerror',error=>errors.push(error.message));
  await installRoutes(page);await ready(page);
  await expect(page.locator('#solar1000Pilot')).toHaveCount(0);
  await expect(page.getByRole('tab',{name:'UK projects',exact:true})).toHaveAttribute('aria-selected','true');
  await expect(page.getByRole('tab',{name:'Global data centres',exact:true})).toBeVisible();
  expect(await page.evaluate(()=>Boolean(document.querySelector('.newspaper').compareDocumentPosition(document.querySelector('#officialRegister')) & Node.DOCUMENT_POSITION_FOLLOWING))).toBe(true);
  await page.screenshot({path:testInfo.outputPath('dashboard-overview.png')});
  await expect(page.locator('[data-evidence-status]')).toContainText('1 provisional matches');
  await page.locator('#search').fill('1018');
  await page.locator('#repd-1018 .project-record > summary').click();
  const panel=page.locator('[data-evidence-project="1018"]');
  await expect(panel.locator('summary')).toHaveText('Evidence · Provisional: 1');
  await panel.locator('summary').click();
  await expect(panel.locator('a')).toHaveText(hostileTitle);
  await expect(panel.locator('a')).toHaveAttribute('href','https://example.org/test-only-solar-article');
  await expect(panel.locator('a')).toHaveAttribute('target','_blank');
  await expect(panel.locator('img')).toHaveCount(0);
  expect(await page.evaluate(()=>window.evidenceInjected)).toBeUndefined();
  const panelBox=await panel.boundingBox();
  expect(panelBox.x).toBeGreaterThanOrEqual(0);
  expect(panelBox.x+panelBox.width).toBeLessThanOrEqual(page.viewportSize().width);
  await page.locator('#repd-1018 .project-record').screenshot({path:testInfo.outputPath('evidence-panel.png')});
  const map=page.locator('#repd-1018 a.atlaslink');
  await expect(map).toHaveAttribute('target','_blank');
  const mapURL=new URL(await map.getAttribute('href'));
  expect(mapURL.protocol).toBe('https:');expect(mapURL.searchParams.get('repd_ref')).toBe('1018');
  expect(mapURL.searchParams.get('technology')).toBe('solar');
  await page.locator('#search').fill('1019');
  await page.locator('#repd-1019 .project-record > summary').click();
  await expect(page.locator('[data-evidence-project="1019"] summary')).toHaveText('Evidence · Provisional: 0');
  await page.locator('#clearFilters').click();
  await expect(page.locator('#resultsMeta')).toContainText('7,775');
  const downloadPromise=page.waitForEvent('download');
  await page.locator('#exportInline').click();
  const download=await downloadPromise;
  const csv=await readFile(await download.path(),'utf8');
  expect(csv).toContain('1018');
  expect(csv.trim().split(/\r?\n/)).toHaveLength(7776);
  expect(errors).toEqual([]);
});
for(const mode of ['unavailable','bad-digest','invalid-status','no-sources','failed-source','unknown-rights','probe-only','not-eligible','missing-rights-receipt','duplicate-source','missing-source-reference','invalid-run-time','run-after-generation','incorrect-scope','invalid-http-receipt','invalid-source-hash','source-after-run'])test(`${mode} evidence preserves register and maps`,async({page})=>  … [line shortened here: 401 characters; full line on GitHub]
  await installRoutes(page,mode);await ready(page);
  await expect(page.locator('[data-evidence-status]')).toContainText('Evidence unavailable');
  await page.locator('#search').fill('1018');
  await page.locator('#repd-1018 .project-record > summary').click();
  await expect(page.locator('[data-evidence-project="1018"] summary')).toHaveText('Evidence · Unavailable');
  await expect(page.locator('#repd-1018 a.atlaslink')).toHaveAttribute('href',/repd_ref=1018/);
  await page.locator('#search').fill('');
  await page.locator('[data-technology="solar"]').click();
  await expect(page.locator('#resultsMeta')).toContainText('3,604');
});

test('stale collection remains explicitly overdue even when snapshot generation is recent',async({page})=>{
  await installRoutes(page,'stale');await ready(page);
  const status=page.locator('[data-evidence-status]');
  await expect(status).toContainText('Evidence snapshot 2026-11-16T16:30:00Z');
  await expect(status).toContainText('Last successful collection: 2026-11-08T16:30:00Z');
  await expect(status).toContainText('Overdue: more than 7 days since collection');
  await page.locator('#search').fill('1018');
  await page.locator('#repd-1018 .project-record > summary').click();
  const panel=page.locator('[data-evidence-project="1018"]');
  await expect(panel.locator('summary')).toContainText('Provisional: 1');
  await panel.locator('summary').click();
  await expect(panel).toContainText('Last successful collection: 2026-11-08T16:30:00Z');
});
test('retained evidence can reference an older successful source receipt',async({page})=>{
  await installRoutes(page,'retained-source');await ready(page);
  await expect(page.locator('[data-evidence-status]')).toContainText('1 provisional matches');
  await expect(page.locator('[data-evidence-status]')).toContainText('Last successful collection: 2026-11-16T16:30:00Z');
  await page.locator('#search').fill('1018');
  await page.locator('#repd-1018 .project-record > summary').click();
  await expect(page.locator('[data-evidence-project="1018"] summary')).toContainText('Provisional: 1');
});

test('one pipeline switches datasets without changing UK filters, totals or exports',async({page},testInfo)=>{
  await installRoutes(page);await ready(page);
  const uk=page.getByRole('tab',{name:'UK projects',exact:true});
  const global=page.getByRole('tab',{name:'Global data centres',exact:true});
  await global.click();
  await expect(global).toHaveAttribute('aria-selected','true');
  await expect(page.locator('#globalProjectPanel')).toBeVisible();
  await expect(page.locator('#ukProjectsPanel')).toBeHidden();
  await expect(page.locator('#globalDatacentres')).toBeVisible();
  await expect(page.locator('#globalDcCount')).toHaveText('12 of 12 sites shown');
  await page.locator('#officialRegister').evaluate(node=>node.scrollIntoView({block:'start',behavior:'instant'}));
  await page.screenshot({path:testInfo.outputPath('global-pipeline.png')});
  await global.press('ArrowLeft');
  await expect(uk).toBeFocused();
  await expect(uk).toHaveAttribute('aria-selected','true');
  await expect(page.locator('#resultsMeta')).toContainText('7,775');
  await page.locator('[data-technology="bess"]').click();
  await expect(page.locator('[data-technology="bess"]')).toHaveAttribute('aria-pressed','true');
  await global.click();await uk.click();
  await expect(page.locator('[data-technology="bess"]')).toHaveAttribute('aria-pressed','true');
  await page.locator('#clearFilters').click();
  await expect(page.locator('#resultsMeta')).toContainText('7,775');
});

test('global data centres keep sourced identities, country filters and unknown capacities',async({page},testInfo)=>{
  await installRoutes(page);await ready(page);
  await page.getByRole('tab',{name:'Global data centres',exact:true}).click();
  const cards=page.locator('#globalDatacentres [data-dc-id]');
  await expect(cards).toHaveCount(12);
  await expect(page.locator('#globalDatacentres')).toContainText('12 source-indexed sites in 10 countries');
  await expect(page.locator('#globalDatacentres')).toContainText('not a comprehensive worldwide register');
  await page.locator('#globalDcSearch').fill('Utah');
  await expect(cards).toHaveCount(1);
  await expect(cards.first()).toHaveAttribute('data-dc-id','DC-WD-Q12857142');
  await expect(cards.first()).toContainText('IT load: not reported');
  await expect(cards.first().locator('a[href*="openstreetmap.org"]')).toHaveAttribute('target','_blank');
  await expect(cards.first().locator('a[href*="wikidata.org/w/index.php"]')).toHaveAttribute('href',/oldid=\d+/);
  await page.locator('#globalDcSearch').fill('');
  await page.locator('#globalDcCountry').selectOption('Q668');
  await expect(cards).toHaveCount(1);
  await expect(cards.first()).toContainText('Yotta NM1');
  await expect(cards.first()).toContainText('Map unavailable');
  await expect(cards.first().locator('a[href*="openstreetmap.org"]')).toHaveCount(0);
  await page.locator('#globalDcCountry').selectOption('Q39');
  await expect(cards.first()).toContainText('Swiss Fort Knox');
  await expect(cards.first()).toContainText('approximate source point');
  await page.locator('#globalDcCountry').selectOption('');
  await page.locator('#globalDcSearch').fill('no such fixture site');
  await expect(cards).toHaveCount(0);
  await expect(page.locator('#globalDcCount')).toHaveText('0 of 12 sites shown');
  await page.locator('#globalDcSearch').fill('');
  await page.locator('#officialRegister').evaluate(node=>node.scrollIntoView({block:'start',behavior:'instant'}));
  await page.screenshot({path:testInfo.outputPath('global-data-centres.png')});
  await page.getByRole('tab',{name:'UK projects',exact:true}).click();
  await expect(page.locator('#resultsMeta')).toContainText('7,775');
});

test('global dataset failure leaves UK register available and does not invent sites',async({page})=>{
  await installRoutes(page);
  await page.route('**/global-datacentres/projects.json',route=>route.fulfill({status:503,body:'unavailable'}));
  await ready(page);
  await page.getByRole('tab',{name:'Global data centres',exact:true}).click();
  await expect(page.locator('#globalDatacentres .gdc-error')).toContainText('unavailable');
  await expect(page.locator('#globalDatacentres [data-dc-id]')).toHaveCount(0);
  await page.getByRole('tab',{name:'UK projects',exact:true}).click();
  await expect(page.locator('#resultsMeta')).toContainText('7,775');
});

Harness Test

A test in the browser folder of GlobalGrid2050 that checks Server and Playwright Config. It is built from the unused port helper (`unusedPort`).

testglobalgrid2050 / automation/news/acquisition/browser/harness.test.mjs · lines 1–77 of 77 · Entry point

What it does
It tests its inputs. Defines unusedPort, start. Uses libraries node:test, node:assert/strict, node:child_process, node:net, node:events. Side effects: 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.
Inputs & outputs
In: data source: 127.0.0.1:${port}${release}.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050).
What it achieves
Defines `unusedPort` and `start`.
Why it matters
Run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow.
Application
globalgrid2050 · automation/news/acquisition/browser · test
Uses
Server (script call), Playwright Config (script call), node:test, node:assert/strict, node:child_process, node:net, node:events, node:timers/promises, node:url
Used by
run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run)
Produces
unusedPort, start
Defines here
unusedPort, start
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/acquisition/browser/harness.test.mjs:1-77 · blob c3497e60753e68f839b68a073462c3d1750ddbcf · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: network, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
// Run with: node --test harness.test.mjs
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {spawn,execFileSync} from 'node:child_process';
import {createServer} from 'node:net';
import {once} from 'node:events';
import {setTimeout as delay} from 'node:timers/promises';
import {fileURLToPath} from 'node:url';
import {getTestPort} from './server.mjs';

const cwd=fileURLToPath(new URL('.',import.meta.url));
const release='/uk_renewables_pipeline/202611161630/';

test('default and explicit port configuration share one loopback origin',()=>{
  assert.equal(getTestPort({}),4173);
  for(const value of [undefined,'1','4187','65535']){
    const env={...process.env};
    delete env.EVIDENCE_TEST_PORT;
    if(value!==undefined)env.EVIDENCE_TEST_PORT=value;
    const output=execFileSync(process.execPath,['--input-type=module','-e',
      "import c from './playwright.config.mjs'; console.log(JSON.stringify({base:c.use.baseURL,ready:c.webServer.url,reuse:c.webServer.reuseExistingServer}))"],{cwd,env,encoding:'utf8'});
    const config=JSON.parse(output);
    const origin=`http://127.0.0.1:${getTestPort(env)}`;
    assert.deepEqual(config,{base:origin,ready:origin+release,reuse:false});
  }
});

test('invalid ports fail before opening a listener',()=>{
  for(const value of ['', '0', '-1', '65536', '4187.5', '4187abc', ' 4187', '1e3']){
    assert.throws(()=>getTestPort({EVIDENCE_TEST_PORT:value}),/integer from 1 to 65535/);
  }
});

async function unusedPort(){
  const server=createServer().listen(0,'127.0.0.1');
  await once(server,'listening');
  const port=server.address().port;
  await new Promise((resolve,reject)=>server.close(error=>error?reject(error):resolve()));
  return port;
}

async function start(port,t){
  const child=spawn(process.execPath,['server.mjs'],{cwd,env:{...process.env,EVIDENCE_TEST_PORT:String(port)},stdio:['ignore','ignore','pipe']});
  let stderr='';
  child.stderr.on('data',chunk=>stderr+=chunk);
  t.after(async()=>{
    if(child.exitCode===null && child.signalCode===null){
      const stopped=once(child,'exit');
      child.kill();
      await stopped;
    }
  });
  for(let attempt=0;attempt<100;attempt++){
    assert.equal(child.exitCode,null,stderr);
    try{
      const response=await fetch(`http://127.0.0.1:${port}${release}`,{signal:AbortSignal.timeout(500)});
      assert.equal(response.status,200);
      assert.match(response.headers.get('content-type'),/text\/html/);
      assert.match(await response.text(),/<!doctype html>/i);
      return child;
    }catch(error){
      if(attempt===99)throw error;
      await delay(50);
    }
  }
}

test('two distinct ports serve the candidate concurrently without reusing a server',{timeout:15000},async t=>{
  const firstPort=await unusedPort();
  const first=await start(firstPort,t);
  const secondPort=await unusedPort();
  assert.notEqual(secondPort,firstPort);
  const second=await start(secondPort,t);
  assert.equal(first.exitCode,null);
  assert.equal(second.exitCode,null);
  assert.notEqual(first.pid,second.pid);
});

News Priority Config

A JavaScript module in the browser folder of GlobalGrid2050.

otherglobalgrid2050 / automation/news/acquisition/browser/news-priority.config.mjs · lines 1–14 of 14 · Not reached from any entry point (candidate for review)

What it does
Uses libraries @playwright/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.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name. Described from its file name only (a candidate, not yet checked against the code).
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · automation/news/acquisition/browser · JavaScript module
Uses
Server (import), @playwright/test
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/news/acquisition/browser/news-priority.config.mjs:1-14 · blob 8bc68354b4c960cd922d6c488d1c08f021e915b8 · 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: unreached_review
import {defineConfig} from '@playwright/test';
import {getTestPort} from './server.mjs';
const baseURL=`http://127.0.0.1:${getTestPort()}`;
export default defineConfig({
  testDir:'.', testMatch:'news-priority.spec.mjs', timeout:45000,
  fullyParallel:true, workers:3, reporter:[['list']],
  use:{baseURL,headless:true,channel:process.env.BROWSER_CHANNEL || undefined},
  projects:[
    {name:'mobile',use:{viewport:{width:375,height:812}}},
    {name:'tablet',use:{viewport:{width:768,height:1024}}},
    {name:'desktop',use:{viewport:{width:1440,height:900}}}
  ],
  webServer:{command:'node server.mjs',url:`${baseURL}/uk_renewables_pipeline/202611161734/`,reuseExistingServer:false}
});

News Priority Spec

A test in the browser folder of GlobalGrid2050 covering solar.

testglobalgrid2050 / automation/news/acquisition/browser/news-priority.spec.mjs · lines 1–119 of 119 · Not reached from any entry point (candidate for review) · pattern install (shared by 42 files)

What it does
It tests solar. Defines install, ready. Uses libraries @playwright/test, node:child_process, node:fs/promises, node:url. Side effects: changes the web page (DOM); reads or writes files; 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: solar.
Inputs & outputs
In: JSON file pipeline_headlines.json; JSON file .rank.json; JSON file pipeline_headlines.snapshot.json.
What it achieves
Defines `install` and `ready`.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · automation/news/acquisition/browser · test
Uses
@playwright/test, node:child_process, node:fs/promises, node:url
Used by
none found
Produces
install, ready
Defines here
install, ready
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/acquisition/browser/news-priority.spec.mjs:1-119 · blob 0b20779017b8ee1a6ba290d599d4afe804d06ff6 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
import {test,expect} from '@playwright/test';
import {execFileSync} from 'node:child_process';
import {readFile} from 'node:fs/promises';
import {fileURLToPath} from 'node:url';
const root=fileURLToPath(new URL('../../../../',import.meta.url));
const release='/uk_renewables_pipeline/202611161734/';
const live='https://raw.githubusercontent.com/Ventusltd/globalgrid2050/pipeline-news-data/dist/pipeline_headlines.json';
const rankURL=live.replace(/\.json$/,'.rank.json');
const fixed='2026-11-16T14:00:00Z';
// Python producer supplies the actual sidecar consumed by browser JS.
const fixture=JSON.parse(execFileSync(process.env.PYTHON || 'python',['-c',`
import json
from automation.news.build_news_priority import build
from automation.news.tests.test_news_priority_export import document,raw
from automation.news.tests.test_news_algorithm import article
d=document([
 article('https://www.bloomberg.com/news/test-only', 'TEST FIXTURE: UK solar project financing announced', source='Bloomberg',date='2026-11-16T13:00:00Z'),
 article('https://www.gov.uk/news/test-only', 'TEST FIXTURE: UK solar planning policy announced <img src=x onerror=alert(1)>', source='GOV.UK',category='policy',date='2026-11-15T13:00:00Z'),
 article('https://news.example/undated','TEST FIXTURE: UK grid construction planned', source='Example publisher',date=None)
])
b=raw(d)
print(json.dumps({'body':b.decode(),'sidecar':build(b)}))
`],{cwd:root,encoding:'utf8'}));

async function install(page, mode='valid'){
  const d=JSON.parse(fixture.body), s=structuredClone(fixture.sidecar);
  let body=fixture.body;
  if(mode==='digest')s.input_sha256='0'.repeat(64);
  if(mode==='profile')s.profile_sha256='0'.repeat(64);
  if(mode==='duplicate')s.entries[1]=structuredClone(s.entries[0]);
  if(mode==='rank')s.entries[0].rank=2;
  if(mode==='source')s.entries[0].source='Unattributed';
  if(mode==='title')s.entries[0].title='Substituted headline';
  if(mode==='missing')s.entries.pop();
  if(mode==='foreign-link')s.entries[0].link='https://other.example/elsewhere';
  if(mode==='extra-field')s.entries[0].verification_status='VERIFIED';
  if(mode==='clock')s.as_of='2026-11-16T13:06:14Z';
  if(mode==='partial'||mode==='failed'){
    d.status=mode; d.counts.feeds_ok=mode==='failed'?0:49;d.counts.feeds_failed=mode==='failed'?50:1;
    body=JSON.stringify(d);
    const rebuilt=execFileSync(process.env.PYTHON||'python',['-c','import sys,json; from automation.news.build_news_priority import build; print(json.dumps(build(sys.stdin.buffer.read())))'],{cwd:root,input:body,encoding:'utf8'});
    Object.assign(s,JSON.parse(rebuilt));
  }
  await page.clock.setFixedTime(new Date(mode==='stale'?'2026-11-19T14:00:00Z':mode==='future'?'2026-11-16T13:00:00Z':fixed));
  const origin=new URL(test.info().project.use.baseURL).origin;
  await page.route('**/*',async route=>{
    const url=route.request().url();
    if(url===live)return mode==='snapshot'?route.fulfill({status:503,body:'unavailable'}):route.fulfill({contentType:'application/json',body});
    if(url===rankURL){
      if(mode==='timeout')return new Promise(()=>{});
      return mode==='unavailable'?route.fulfill({status:404,body:'unavailable'}):route.fulfill({contentType:'application/json',body:JSON.stringify(s)});
    }
    if(mode==='snapshot'&&url===origin+release+'news/pipeline_headlines.snapshot.json')return route.fulfill({contentType:'application/json',body});
    if(url.startsWith(origin+'/'))return route.continue();
    return route.abort();
  });
}

async function ready(page){
  await page.goto(release);
  await expect(page.locator('#tbody')).toHaveAttribute('data-complete','true');
  await expect(page.locator('#resultsMeta')).toContainText('7,775');
  await expect(page.locator('#liveNews .ln-item')).toHaveCount(3);
  await page.waitForFunction(()=>['accepted','rejected','unavailable'].includes(window.pipelineHeadlinePriorityState)
    || document.getElementById('newsStatus').getAttribute('data-state')==='snapshot');
}

test('priority is visible, credits retained, policy shown, text escaped and core pipeline intact',async({page},info)=>{
  const errors=[];page.on('pageerror',e=>errors.push(e.message));
  await install(page);await ready(page);
  await expect(page.locator('#newsStatus')).toHaveAttribute('data-order','priority');
  await expect(page.locator('#liveNews .ln-title').first()).toContainText('planning policy');
  await expect(page.locator('#liveNews .ln-priority').first()).toContainText('Priority 1 · Government source');
  await expect(page.locator('#liveNews')).toContainText('Bloomberg');
  await expect(page.locator('#liveNews')).toContainText('Publisher date unknown');
  await expect(page.locator('#liveNews img')).toHaveCount(0);
  await expect(page.locator('#liveNews .ln-title').first()).toHaveAttribute('href','https://www.gov.uk/news/test-only');
  await expect(page.locator('#liveNews .ln-title').first()).toHaveAttribute('rel','noopener noreferrer');
  await expect(page.locator('#newsStatus')).toContainText('not project verification');
  await expect(page.locator('#evidenceCoverage')).toHaveAttribute('data-selection-count','1000');
  await page.locator('#search').fill('1018');
  await expect(page.locator('#repd-1018 a.atlaslink')).toHaveAttribute('href',/repd_ref=1018/);
  await page.locator('#clearFilters').click();
  const downloading=page.waitForEvent('download');await page.locator('#exportInline').click();
  const csv=await readFile(await (await downloading).path(),'utf8');
  expect(csv.trim().split(/\r?\n/)).toHaveLength(7776);
  await page.getByRole('tab',{name:'Global data centres',exact:true}).click();
  await expect(page.locator('#globalProjectPanel')).toContainText('12');
  await page.getByRole('tab',{name:'UK projects',exact:true}).click();
  expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true);
  await page.locator('.newspaper').first().screenshot({path:info.outputPath('v926-news-block.png')});
  await page.screenshot({path:info.outputPath('v926-news-and-pipeline.png')});
  expect(errors).toEqual([]);
});

for(const mode of ['digest','profile','duplicate','rank','source','title','missing','foreign-link','extra-field','clock','unavailable','timeout']){
  test(`invalid priority ${mode} keeps credited date fallback`,async({page})=>{
    await install(page,mode);await ready(page);
    await expect(page.locator('#newsStatus')).toHaveAttribute('data-order','date');
    await expect(page.locator('#newsStatus')).toContainText('Priority unavailable');
    await expect(page.locator('#liveNews .ln-priority')).toHaveCount(0);
    await expect(page.locator('#liveNews')).toContainText('planning policy');
    await expect(page.locator('#liveNews .ln-title').first()).toHaveAttribute('href','https://www.bloomberg.com/news/test-only');
  });
}
for(const mode of ['stale','snapshot','failed','future']){
  test(`${mode} cannot promote a matching old rank`,async({page})=>{
    await install(page,mode);await ready(page);
    await expect(page.locator('#newsStatus')).toHaveAttribute('data-order','date');
    await expect(page.locator('#newsStatus')).toHaveAttribute('data-state',mode==='stale'?'overdue':mode);
    await expect(page.locator('#liveNews .ln-priority')).toHaveCount(0);
  });
}
test('partial source health remains explicit with accepted priority',async({page})=>{
  await install(page,'partial');await ready(page);
  await expect(page.locator('#newsStatus')).toHaveAttribute('data-order','priority');
  await expect(page.locator('#newsStatus')).toHaveAttribute('data-state','partial');
  await expect(page.locator('#newsStatus')).toContainText('49 sources succeeded, 1 failed');
});

Playwright Config

A JavaScript module in the browser folder of GlobalGrid2050.

otherglobalgrid2050 / automation/news/acquisition/browser/playwright.config.mjs · lines 1–17 of 17

What it does
Uses libraries @playwright/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.
Downstream impact
Used directly by 1 file: Harness Test (globalgrid2050). Reached from 1 other entry point, including GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050).
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name. Described from its file name only (a candidate, not yet checked against the code).
Why it matters
Checked by Harness Test.
Application
globalgrid2050 · automation/news/acquisition/browser · JavaScript module
Uses
Server (import), @playwright/test
Used by
run by Harness Test (script call)
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/news/acquisition/browser/playwright.config.mjs:1-17 · blob 12918dfd41d13883a9536f7c948bfb211472ccf3 · 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 {defineConfig} from '@playwright/test';
import {getTestPort} from './server.mjs';
const baseURL=`http://127.0.0.1:${getTestPort()}`;
export default defineConfig({
  testDir: '.', testMatch: 'evidence.spec.mjs', timeout: 45000,
  fullyParallel: true, workers: 3,
  reporter: [['list']],
  use: {baseURL, headless: true},
  projects: [
    {name:'mobile', use:{viewport:{width:375,height:812}}},
    {name:'phone390', use:{viewport:{width:390,height:844}}},
    {name:'phone393', use:{viewport:{width:393,height:852}}},
    {name:'tablet', use:{viewport:{width:768,height:1024}}},
    {name:'desktop', use:{viewport:{width:1440,height:900}}}
  ],
  webServer: {command:'node server.mjs', url:`${baseURL}/uk_renewables_pipeline/202611161630/`, reuseExistingServer:false}
});