GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / globalgrid2050 / automation/convergence/tests

Test Build Renewable Energy Planning Database (REPD) Datacentres and 4 more files

A test in the tests folder of GlobalGrid2050 that checks Build Renewable Energy Planning Database (REPD) Datacentres and Build PipelineNews Context, using EPSG:27700 and Helmert.

696 lines of Python and JavaScript from globalgrid2050, in 5 files. Topic: Electricity markets and data pipelines. Section 773 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Test Build Renewable Energy Planning Database (REPD) Datacentres test · globalgrid2050 / automation/convergence/tests/test_build_repd_datacentres.py lines 1–359
  2. Browser Test test · globalgrid2050 / automation/energy_context_ui/20261118/browser.test.mjs lines 1–107
  3. Contracts Test test · globalgrid2050 / automation/energy_context_ui/20261118/contracts.test.mjs lines 1–78
  4. Model transform · globalgrid2050 / automation/energy_context_ui/20261118/model.mjs lines 1–76
  5. Prepare Preview storage · globalgrid2050 / automation/energy_context_ui/20261118/prepare_preview.py lines 1–76

Test Build Renewable Energy Planning Database (REPD) Datacentres

A test in the tests folder of GlobalGrid2050 that checks Build Renewable Energy Planning Database (REPD) Datacentres and Build PipelineNews Context, using EPSG:27700 and Helmert.

testglobalgrid2050 / automation/convergence/tests/test_build_repd_datacentres.py · lines 1–359 of 359 · Entry point · pattern repd_row (shared by 2 files)

What it does
It tests its inputs. Defines 29 functions or classes, including km_north, repd_row, dc_feature, write_inputs, node. Uses libraries __future__, csv, hashlib, json, math. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'datacentres'): 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: CSV file repd.csv; GeoJSON file dc.geojson; JSON file cp.json; JSON file datacentre_proximity.json; JSON file repd_datacentre_proximity_solar.json; JSON file colocation_candidates.json; JSON file rollup_cluster.json; JSON file rollup_region.json. Out: JSON file part-001.json; JSON file part-002.json. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
Downstream impact
Used directly by 1 file: GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
It writes inputs (`write_inputs`) and is built from the km north helper (`km_north`) and the REPD row helper (`repd_row`). Tests for `automation/convergence/build_repd_datacentres.py`. Synthetic fixtures only; no network.
Why it matters
Run by GlobalGrid2050 Project Signals Acid Workflow.
Application
globalgrid2050 · automation/convergence/tests · test
Uses
Build Renewable Energy Planning Database (REPD) Datacentres (sys.path import), Build PipelineNews Context (sys.path import), __future__, csv, hashlib, json, math, os, sys, pathlib
Used by
run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
km_north, repd_row, dc_feature, write_inputs, node, run, test_bng_to_wgs84_regression_points, test_bng_to_wgs84_matches_pyproj_if_present, test_haversine_one_degree_latitude, test_blank_capacity_is_unknown_not_zero, test_status_groups_and_excluded_statuses, test_technology_groups
Defines here
km_north, repd_row, dc_feature, write_inputs, node, run, A, test_bng_to_wgs84_regression_points, test_bng_to_wgs84_matches_pyproj_if_present, test_haversine_one_degree_latitude, test_blank_capacity_is_unknown_not_zero, test_status_groups_and_excluded_statuses, test_technology_groups, test_radius_boundaries_and_nearest, test_known_bad_coordinates_excluded_and_listed, test_wrong_crs_repd_degrees_rejected, test_wrong_crs_datacentre_swapped_axes_unplaced, test_unplaced_datacentre_keeps_row_with_null_metrics, test_duplicates_counted_once_most_advanced_kept, test_operator_match_is_strict, test_colocation_classes_and_false_matches, test_datacentre_mw_never_conflated, test_region_precision_points_not_used_for_project_radii, test_shared_nearest_transmission_node, test_clusters_need_three_sites_and_rollups, test_deterministic_bytes_and_manifest, test_real_inputs, A, test_pipelinenews_sidecar_keys_by_spine_ref
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/convergence/tests/test_build_repd_datacentres.py:1-359 · blob 702893922f96d5fa0789b099235d22f56db7fee0 · 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
"""Tests for automation/convergence/build_repd_datacentres.py. Synthetic fixtures only; no network.

The optional real-input test runs when CONVERGENCE_REAL_INPUTS=1 and the pinned files exist.
"""
from __future__ import annotations

import csv
import hashlib
import json
import math
import os
import sys
from pathlib import Path

import pytest

PKG = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PKG))

import build_repd_datacentres as B  # noqa: E402

COLS = ["Old Ref ID", "Ref ID", "Operator (or Applicant)", "Site Name", "Technology Type",
        "Installed Capacity (MWelec)", "Development Status", "Development Status (short)", "Address", "County",
        "Region", "Country", "X-coordinate", "Y-coordinate"]

# a point in Slough-ish west London, BNG metres
X0, Y0 = 500000.0, 180000.0
LAT0, LON0 = B.bng_to_wgs84(X0, Y0)


def km_north(lat, km):
    return round(lat + km / 111.195, 6)


def repd_row(ref, tech="Solar Photovoltaics", status="Awaiting Construction", mw="10", x=X0, y=Y0,
             site=None, op="Op Ltd", region="South East", country="England", addr=""):
    return {"Old Ref ID": "", "Ref ID": str(ref), "Operator (or Applicant)": op, "Site Name": site or "Site %s" % ref,
            "Technology Type": tech, "Installed Capacity (MWelec)": mw, "Development Status": status,
            "Development Status (short)": status, "Address": addr, "County": "Berkshire", "Region": region,
            "Country": country, "X-coordinate": "" if x is None else str(x), "Y-coordinate": "" if y is None else str(y)}


def dc_feature(i, lat, lon, status="operational", precision="exact_site", operator=None, name=None,
               it=None, gc=None, un=None, un_label=None, geometry=True):
    did = "dcuk-%016x" % i
    return {"type": "Feature", "id": did,
            "geometry": {"type": "Point", "coordinates": [lon, lat]} if geometry else None,
            "properties": {"id": did, "name": name or "DC %d" % i, "status": status, "operator": operator,
                           "location": {"lat": lat, "lon": lon, "precision": precision},
                           "it_load_mw": {"value": it, "label": None, "source_id": None},
                           "grid_connection_mw": {"value": gc, "label": None, "source_id": None},
                           "unclassified_mw": {"value": un, "label": un_label, "source_id": None},
                           "sources": [{"licence": "ODbL-1.0"}]}}


def write_inputs(tmp, rows, feats, nodes=None):
    rp = tmp / "repd.csv"
    with open(rp, "w", newline="", encoding="utf-8") as fh:
        w = csv.DictWriter(fh, fieldnames=COLS)
        w.writeheader()
        for r in rows:
            w.writerow(r)
    dp = tmp / "dc.geojson"
    dp.write_text(json.dumps({"type": "FeatureCollection", "metadata": {"title": "t"}, "features": feats}))
    cp = tmp / "cp.json"
    cp.write_text(json.dumps({"schema": "data-grid-gb.connection-points.v3", "connection_points": nodes or []}))
    return rp, dp, cp


def node(code, lat, lon):
    return {"site_code": code, "name": code + " NODE", "transmission_owner": "NGET", "voltages_kv": [400, 132],
            "location": {"lat": lat, "lon": lon}}


def run(tmp, rows, feats, nodes=None, out="out"):
    rp, dp, cp = write_inputs(tmp, rows, feats, nodes)

    class A:
        pass
    a = A()
    a.repd, a.identity, a.datacentres, a.connection_points, a.osm_substations = str(rp), None, str(dp), str(cp), None
    a.release, a.out = "test", str(tmp / out)
    man = B.run(a)
    o = tmp / out
    load = lambda n: json.loads((o / n).read_text())  # noqa: E731
    return man, o, load


# ---------------------------------------------------------------------------------------------- geodesy
def test_bng_to_wgs84_regression_points():
    # values agree with pyproj EPSG:27700 -> 4326 (Helmert) to < 0.1 m; frozen here as a regression
    assert B.bng_to_wgs84(530000, 180000) == (51.503991, -0.128354)
    assert B.bng_to_wgs84(146000, 530000) == (54.601125, -5.93421)     # Belfast: NI rows are BNG in REPD
    assert B.bng_to_wgs84(450000, 1150000) == (60.231239, -1.099095)   # Shetland


def test_bng_to_wgs84_matches_pyproj_if_present():
    pyproj = pytest.importorskip("pyproj")
    t = pyproj.Transformer.from_crs(27700, 4326, always_xy=True)
    for x, y in [(651409.903, 313177.270), (180000, 30000), (300000, 700000), (20000, 450000)]:
        lat, lon = B.bng_to_wgs84(x, y)
        lon2, lat2 = t.transform(x, y)
        assert B.haversine_km(lat, lon, lat2, lon2) < 0.005


def test_haversine_one_degree_latitude():
    assert abs(B.haversine_km(51, 0, 52, 0) - 111.195) < 0.01


# ---------------------------------------------------------------------------------------------- core rules
def test_blank_capacity_is_unknown_not_zero(tmp_path):
    rows = [repd_row(1, mw="10"), repd_row(2, mw="", x=X0 + 100, site="Other")]
    feats = [dc_feature(1, LAT0, LON0)]
    _, _, load = run(tmp_path, rows, feats)
    c = load("datacentre_proximity.json")["records"][0]["radii"]["5"]["solar"]["consented"]
    assert c == {"count": 2, "mw_stated": 10.0, "count_mw_unknown": 1}


def test_status_groups_and_excluded_statuses(tmp_path):
    rows = [repd_row(1, status="Operational"), repd_row(2, status="Under Construction", site="b"),
            repd_row(3, status="Awaiting Construction", site="c"), repd_row(4, status="Application Submitted", site="d"),
            repd_row(5, status="Appeal Lodged", site="e"), repd_row(6, status="Application Refused", site="f"),
            repd_row(7, status="Revised", site="g"), repd_row(8, status="Abandoned", site="h")]
    _, _, load = run(tmp_path, rows, [dc_feature(1, LAT0, LON0)])
    s = load("datacentre_proximity.json")["records"][0]["radii"]["5"]["solar"]
    assert [s[k]["count"] for k in B.STATUS_ORDER] == [1, 1, 1, 2]


def test_technology_groups(tmp_path):
    rows = [repd_row(1, tech="Battery"), repd_row(2, tech="Wind Onshore", site="w"),
            repd_row(3, tech="Wind Offshore", site="o"), repd_row(4, tech="Biomass (dedicated)", site="bio")]
    _, _, load = run(tmp_path, rows, [dc_feature(1, LAT0, LON0)])
    r = load("datacentre_proximity.json")["records"][0]["radii"]["5"]
    assert r["battery"]["consented"]["count"] == 1
    assert r["wind_onshore"]["consented"]["count"] == 1
    assert r["wind_offshore"]["consented"]["count"] == 1
    assert sum(r["solar"][s]["count"] for s in B.STATUS_ORDER) == 0


def test_radius_boundaries_and_nearest(tmp_path):
    # projects at about 3, 7, 20 and 40 km north of the data centre (BNG northing offsets)
    rows = [repd_row(i, y=Y0 + d * 1000, site="s%d" % i, mw=str(i)) for i, d in ((1, 3), (2, 7), (3, 20), (4, 40))]
    rows.append(repd_row(5, y=Y0 + 70000, site="far"))
    _, _, load = run(tmp_path, rows, [dc_feature(1, LAT0, LON0)])
    rec = load("datacentre_proximity.json")["records"][0]
    counts = [rec["radii"][str(r)]["solar"]["consented"]["count"] for r in B.RADII_KM]
    assert counts == [1, 2, 3, 4]
    assert rec["radii"]["50"]["solar"]["consented"]["mw_stated"] == 10.0
    assert rec["nearest_by_technology"]["solar"]["ref"] == "1"
    assert 2.9 < rec["nearest_by_technology"]["solar"]["distance_km"] < 3.1
    assert rec["nearest_by_technology"]["battery"] is None


def test_known_bad_coordinates_excluded_and_listed(tmp_path):
    rows = [repd_row(18561), repd_row(18562, tech="Battery"), repd_row(9, site="good")]
    man, _, load = run(tmp_path, rows, [dc_feature(1, LAT0, LON0)])
    assert {e["ref"] for e in man["excluded_repd_geography"]} == {"18561", "18562"}
    assert all(e["reason"] == "known_wrong_coordinates" for e in man["excluded_repd_geography"])
    assert load("datacentre_proximity.json")["records"][0]["radii"]["50"]["solar"]["consented"]["count"] == 1


# ---------------------------------------------------------------------------------------------- negative cases
def test_wrong_crs_repd_degrees_rejected(tmp_path):
    # lat/lon written into the BNG columns: never treated as metres
    rows = [repd_row(1, x=-0.59, y=51.5), repd_row(2, x=0.5, y=51.5, site="b"), repd_row(3, x=None, y=None, site="c"),
            repd_row(4, x=900000, y=100000, site="d")]
    man, _, load = run(tmp_path, rows, [dc_feature(1, LAT0, LON0)])
    why = {e["ref"]: e["reason"] for e in man["excluded_repd_geography"]}
    assert why == {"1": "coordinates_look_like_degrees_not_bng", "2": "coordinates_look_like_degrees_not_bng",
                   "3": "no_coordinates", "4": "coordinates_outside_bng_range"}
    assert man["stats"]["repd_live_target_projects_located"] == 0


def test_wrong_crs_datacentre_swapped_axes_unplaced(tmp_path):
    feats = [dc_feature(1, LON0, LAT0), dc_feature(2, LAT0, LON0)]   # first has lat/lon swapped
    man, _, load = run(tmp_path, [repd_row(1)], feats)
    recs = {r["id"]: r for r in load("datacentre_proximity.json")["records"]}
    bad = recs["dcuk-%016x" % 1]
    assert bad["lat"] is None and bad["radii"] is None and bad["precision"] == "rejected"
    assert man["datacentres_geometry_rejected"] == [{"id": "dcuk-%016x" % 1, "reason": "outside_uk_wgs84_bounds"}]


def test_unplaced_datacentre_keeps_row_with_null_metrics(tmp_path):
    feats = [dc_feature(1, None, None, geometry=False, status="in_planning")]
    feats[0]["properties"]["location"] = {"lat": None, "lon": None, "precision": None}
    _, _, load = run(tmp_path, [repd_row(1)], feats)
    r = load("datacentre_proximity.json")["records"][0]
    assert r["lat"] is None and r["radii"] is None and r["nearest_transmission_node"] is None
    assert r["precision"] == "unknown" and r["proximity_reliable"] is False


def test_duplicates_counted_once_most_advanced_kept(tmp_path):
    rows = [repd_row(10, status="Awaiting Construction", site="Feldon Vale Solar Farm", mw="49.9"),
            repd_row(12, status="Operational", site="Feldon Vale  solar farm", mw="49.9"),
            repd_row(13, status="Operational", site="Different", mw="49.9")]
    man, o, load = run(tmp_path, rows, [dc_feature(1, LAT0, LON0)])
    s = load("datacentre_proximity.json")["records"][0]["radii"]["5"]["solar"]
    assert s["operational"]["count"] == 2 and s["consented"]["count"] == 0
    assert man["repd_duplicates_collapsed"] == [{"ref": "10", "kept_ref": "12"}]
    proj = load("repd_datacentre_proximity_solar.json")
    i = proj["columns"].index("duplicate_of")
    byref = {r[0]: r for r in proj["rows"]}
    assert byref["10"][i] == "12" and byref["12"][i] is None


def test_operator_match_is_strict():
    k = B.operator_keys
    assert k("Digital Realty Ltd") == k("Digital Realty") == ["digital realty"]
    assert k("Global Digital Realty") != k("Digital Realty")
    assert k("Slough Holdings UK Limited (SDC Capital Partners)") == k("Slough")
    assert k("Cobalt Park Data Centres; Nscale (GPU deployment); Stargate UK") == ["cobalt park", "nscale", "stargate"]
    assert k("UK Ltd") == [] and k("") == [] and k(None) == []
    assert k("Abc") == []   # too short to be evidence


def test_colocation_classes_and_false_matches(tmp_path):
    rows = [
        # A + B: same operator at the same point
        repd_row(1, op="Redcentric Ltd", site="Lowfields Way - Solar"),
        # B only: same operator, far away
        repd_row(2, op="Redcentric", site="Elsewhere", y=Y0 + 30000),
        # not a match: operator shares a word only
        repd_row(3, op="Global Redcentric Partners", site="Nope", y=Y0 + 20000),
        # E: REPD text mentions a data centre
        repd_row(4, site="Energy Park & Data Centre", y=Y0 + 10000, op="X Energy"),
        # town-name tokens shared with the DC name but common across REPD: not class C
        *[repd_row(100 + i, site="Milton Keynes solar %d" % i, x=X0 + 1500, y=Y0 + 300 * i, op="Op %d" % i)
          for i in range(12)],
        # distinctive shared tokens within 2 km: class C
        repd_row(50, site="Wapseys Wood battery", x=X0 + 1000, y=Y0, op="Someone"),
    ]
    feats = [dc_feature(1, LAT0, LON0, operator="Redcentric", name="Redcentric Milton Keynes Wapseys Wood")]
    man, _, load = run(tmp_path, rows, feats)
    c = load("colocation_candidates.json")["records"]
    got = {(r["evidence_class"], r["repd"]["ref"]) for r in c}
    assert ("A_same_site_and_operator", "1") in got
    assert ("B_operator_match", "1") in got and ("B_operator_match", "2") in got
    assert not any(ref == "3" for cls, ref in got if cls.startswith(("A", "B")))
    assert ("E_repd_text_mentions_datacentre", "4") in got
    assert ("C_same_site_name_and_proximity", "50") in got
    assert not any(cls.startswith("C") and ref.startswith("10") for cls, ref in got)
    e = [r for r in c if r["evidence_class"].startswith("E")][0]
    assert e["evidence"]["nearest_within_name_match_km"] is False


def test_datacentre_mw_never_conflated(tmp_path):
    feats = [dc_feature(1, LAT0, LON0, it=100.0), dc_feature(2, km_north(LAT0, 1), LON0, gc=50.0),
             dc_feature(3, km_north(LAT0, 2), LON0, un=100.0, un_label="battery energy storage capacity"),
             dc_feature(4, km_north(LAT0, 3), LON0, status="in_planning")]
    _, _, load = run(tmp_path, [repd_row(1)], feats)
    proj = load("repd_datacentre_proximity_solar.json")
    row = dict(zip(proj["columns"], proj["rows"][0]))
    assert row["r5km_datacentres"] == 4 and row["r5km_operational"] == 3 and row["r5km_pipeline"] == 1
    assert row["r5km_it_load_mw_stated"] == 100.0 and row["r5km_it_load_mw_known_sites"] == 1
    assert row["r5km_grid_connection_mw_stated"] == 50.0 and row["r5km_grid_connection_mw_known_sites"] == 1
    assert "unclassified" not in " ".join(proj["columns"])
    dcp = {r["id"]: r for r in load("datacentre_proximity.json")["records"]}
    assert dcp["dcuk-%016x" % 3]["unclassified_mw_label"] == "battery energy storage capacity"


def test_region_precision_points_not_used_for_project_radii(tmp_path):
    feats = [dc_feature(1, LAT0, LON0, precision="region")]
    _, _, load = run(tmp_path, [repd_row(1)], feats)
    proj = load("repd_datacentre_proximity_solar.json")
    row = dict(zip(proj["columns"], proj["rows"][0]))
    assert row["r50km_datacentres"] == 0 and row["dc1_id"] is None
    dc = load("datacentre_proximity.json")["records"][0]
    assert dc["proximity_reliable"] is False and dc["radii"]["5"]["solar"]["consented"]["count"] == 1


def test_shared_nearest_transmission_node(tmp_path):
    nodes = [node("AAAA", LAT0, LON0), node("BBBB", km_north(LAT0, 60), LON0)]
    rows = [repd_row(1, y=Y0 + 5000), repd_row(2, y=Y0 + 25000, site="b", tech="Battery"),
            repd_row(3, y=Y0 + 55000, site="c")]
    _, _, load = run(tmp_path, rows, [dc_feature(1, LAT0, LON0)], nodes=nodes)
    r = load("datacentre_proximity.json")["records"][0]
    assert r["nearest_transmission_node"]["site_code"] == "AAAA"
    assert r["shared_node"]["repd_refs"] == ["1", "2"]
    assert r["shared_node"]["by_technology"]["battery"]["consented"]["count"] == 1


def test_clusters_need_three_sites_and_rollups(tmp_path):
    feats = [dc_feature(i, km_north(LAT0, 4 * i), LON0) for i in range(3)]          # chain of 3 at 4 km steps
    feats += [dc_feature(10 + i, km_north(LAT0, 200 + 4 * i), LON0) for i in range(2)]  # pair: not a cluster
    rows = [repd_row(1, y=Y0 + 1000), repd_row(2, y=Y0 + 12000, site="b", tech="Battery", mw="")]
    _, _, load = run(tmp_path, rows, feats)
    cl = load("rollup_cluster.json")["records"]
    assert [c["cluster_id"] for c in cl] == ["DCC01"] and cl[0]["sites"] == 3
    assert cl[0]["largest_consented_within_25km"]["solar"][0]["ref"] == "1"
    assert cl[0]["largest_consented_within_25km"]["battery"][0]["capacity_mw"] is None
    reg = {(r["level"], r["name"]): r for r in load("rollup_region.json")["records"]}
    assert reg[("region", "South East")]["repd"]["solar"]["consented"]["count"] == 1
    assert reg[("country", "England")]["datacentres"] == 5


def test_deterministic_bytes_and_manifest(tmp_path):
    rows = [repd_row(i, y=Y0 + 1000 * i, site="s%d" % i) for i in range(1, 30)]
    feats = [dc_feature(i, km_north(LAT0, 3 * i), LON0) for i in range(5)]
    m1, o1, _ = run(tmp_path, rows, feats, out="a")
    m2, o2, _ = run(tmp_path, rows, feats, out="b")
    names = sorted(p.name for p in o1.iterdir())
    assert names == sorted(p.name for p in o2.iterdir())
    for n in names:
        assert (o1 / n).read_bytes() == (o2 / n).read_bytes(), n
    for e in m1["outputs"]:
        assert hashlib.sha256((o1 / e["file"]).read_bytes()).hexdigest() == e["sha256"]
    assert {i["role"] for i in m1["inputs"]} == {"repd_register", "datacentre_baseline", "transmission_nodes"}
    assert "schema.json" in names and "manifest.json" in names


# ---------------------------------------------------------------------------------------------- real inputs
REAL = {
    "repd": "/home/claude/gg-wt/repd-2026q3.csv",
    "identity": "/home/claude/gg-wt/dist/project_identity_2026q3.json",
    "datacentres": "/home/claude/gridatlas/data/uk_datacentre_pipeline_202610312133.geojson",
    "connection_points": "/home/claude/data-grid-gb/derived/connection-points.v3.json",
    "osm_substations": "/home/claude/globalgrid2050/grid_substations.geojson",
}


@pytest.mark.skipif(os.environ.get("CONVERGENCE_REAL_INPUTS") != "1" or not all(map(os.path.exists, REAL.values())),
                    reason="set CONVERGENCE_REAL_INPUTS=1 with the pinned inputs present")
def test_real_inputs(tmp_path):
    class A:
        pass
    a = A()
    for k, v in REAL.items():
        setattr(a, k, v)
    a.release, a.out = "2026q3", str(tmp_path / "out")
    m = B.run(a)
    s = m["stats"]
    assert s["repd_records"] == 14967 and s["datacentres"] == 226 and s["datacentres_placed"] == 225
    ins = {i["role"]: i for i in m["inputs"]}
    assert ins["datacentre_baseline"]["sha256"] == "87337db5d3bf7959f7f605d3abd029dd4196ab24a79107ceb95210c5b7751654"
    assert {"18561", "18562"} <= {e["ref"] for e in m["excluded_repd_geography"]}
    for e in m["outputs"]:
        assert e["bytes"] < B.MAX_FILE_BYTES, e


# ---------------------------------------------------------------------------------------------- Pipeline News sidecar
def test_pipelinenews_sidecar_keys_by_spine_ref(tmp_path):
    import build_pipelinenews_context as P
    rows = [repd_row(1), repd_row(2, tech="Battery", site="b"), repd_row(3, x=None, y=None, site="c"),
            repd_row(4, site="not in spine")]
    _, o, _ = run(tmp_path, rows, [dc_feature(1, km_north(LAT0, 2), LON0, it=50.0)])
    rel = tmp_path / "202611132345"
    (rel / "data" / "v9.1" / "projects").mkdir(parents=True)
    (rel / "data" / "v9.1" / "projects" / "part-001.json").write_text(json.dumps(
        {"projects": [{"repd_ref": "2"}, {"repd_ref": "1"}, {"repd_ref": "3"}]}))
    doc = P.build(o, rel)
    assert [r[0] for r in doc["rows"]] == ["1", "2"]          # spine order by ref, ref 4 not in the spine
    assert doc["no_coordinates"] == ["3"]
    row = dict(zip(doc["columns"], doc["rows"][0]))
    assert row["nearest_dc_id"] == "dcuk-%016x" % 1 and 1.9 < row["nearest_dc_km"] < 2.1
    assert row["it_load_mw_stated_within_25km"] == 50.0
    assert not any(str(r[0]).startswith("dcuk-") for r in doc["rows"])   # no data-centre id posing as a REPD ref
    (rel / "data" / "v9.1" / "projects" / "part-002.json").write_text(json.dumps({"projects": [{"repd_ref": "1"}]}))
    with pytest.raises(SystemExit):
        P.build(o, rel)

Browser Test

A test in the energy context ui folder of GlobalGrid2050 covering the Renewable Energy Planning Database (REPD) register and solar.

testglobalgrid2050 / automation/energy_context_ui/20261118/browser.test.mjs · lines 1–107 of 107 · version 2026-11-18 · Entry point

What it does
It tests the REPD register and solar. Uses libraries node:assert/strict, node:http, node:fs, 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 (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.
Inputs & outputs
Out: JSON file receipt.json.
Downstream impact
Used directly by 1 file: GlobalGrid2050 V934 Preview Acceptance Workflow (globalgrid2050).
What it achieves
Deterministic actual saved-feed replay against the inherited Pipeline page. Its code works with 2 GW.
Why it matters
Run by GlobalGrid2050 V934 Preview Acceptance Workflow.
Application
globalgrid2050 · automation/energy_context_ui/20261118 · test
Uses
node:assert/strict, node:http, node:fs, node:path, node:url
Used by
run by GlobalGrid2050 V934 Preview Acceptance 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/energy_context_ui/20261118/browser.test.mjs:1-107 · blob b3aa5d6cab5dae8404b6a83a5cba7643e31a9b77 · 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: production_core
// Deterministic actual saved-feed replay against the inherited Pipeline page.
// This is integration evidence, not public served acceptance or live collection proof.
import assert from 'node:assert/strict';
import {createServer} from 'node:http';
import {readFileSync,mkdirSync,writeFileSync} from 'node:fs';
import {resolve,dirname,extname,sep} from 'node:path';
import {fileURLToPath} from 'node:url';
const {chromium}=await import(process.env.PLAYWRIGHT_IMPORT||'playwright');
const root=resolve(process.env.PN_CONTEXT_ROOT||resolve(dirname(fileURLToPath(import.meta.url)),'../../..')),edition=process.env.PN_CONTEXT_EDITION||'202611171940',out=resolve(process.env.PN_CONTEXT_OUTPUT||'work/energy-context');mkdirSync(out,{recursive:true});
const server=createServer((req,res)=>{try{const pathname=decodeURIComponent(new URL(req.url,'http://local').pathname),path=resolve(root,'.'+pathname+(pathname.endsWith('/')?'index.html':''));assert.ok(path.startsWith(root+sep));res.setHeader('Content-Type',({'.html':'text/html','.js':'text/javascript','.mjs':'text/javascript','.css':'text/css','.json':'application/json'})[extname(path)]||'applicat  … [line shortened here: 483 characters; full line on GitHub]
await new Promise(r=>server.listen(0,'127.0.0.1',r));const origin='http://127.0.0.1:'+server.address().port,canonicalReplay=process.env.PN_CONTEXT_CANONICAL_REPLAY==='true',start=canonicalReplay?'https://globalgrid2050.com':origin,browser=await chromium.launch(),receipts=[];
try{for(const width of [1440,393,390]){
 const context=await browser.newContext({viewport:{width,height:844},isMobile:width<500,hasTouch:width<500,reducedMotion:width===390?'reduce':'no-preference'}),page=await context.newPage(),errors=[];page.on('pageerror',e=>errors.push(e.message));
 await context.route('**/*',route=>{if(route.request().url().startsWith(origin))return route.continue();const u=new URL(route.request().url());if(canonicalReplay&&u.origin===start){try{const pathname=decodeURIComponent(u.pathname),path=resolve(root,'.'+pathname+(pathname.endsWith('/')?'index.html':''));assert.ok(path.startsWith(root+sep));return route.fulfill({status:200,contentType:({'.html':'tex  … [line shortened here: 673 characters; full line on GitHub]
 await page.goto(`${start}/uk_renewables_pipeline/${edition}/?news_topic=grid&news_origin_type=repd&news_origin_id=2470`,{waitUntil:'domcontentloaded'});
 await page.waitForFunction(()=>window.pipelineHeadlineDocument?.items?.length>0&&document.querySelector('.pn-news-quality'),null,{timeout:20000});
 if(process.env.PN_CONTEXT_INTEGRATED!=='true'){
  await page.addStyleTag({url:start+'/automation/energy_context_ui/20261118/styles.css'});
  await page.addScriptTag({type:'module',url:start+'/automation/energy_context_ui/20261118/view.mjs'});
 }
 await page.waitForFunction(()=>['withheld','source-qualified'].includes(document.getElementById('energyPolicyContext')?.dataset.state));
 const state=await page.locator('#energyPolicyContext').getAttribute('data-state');
 const hasTopicHook=await page.evaluate(()=>typeof window.pipelineHeadlines?.getViewAdapter==='function');
 assert.equal(state,'source-qualified','actual two independent policy receipts required');
 await page.waitForFunction(()=>['withheld','source-qualified'].includes(document.getElementById('energyPolicyContext')?.dataset.gridContext));
 assert.equal(await page.locator('#energyPolicyContext').getAttribute('data-grid-context'),'source-qualified');
 await page.waitForFunction(()=>window.pipelineEnergyContext.topic()==='grid'||document.querySelector('.pn-news-filter-tools select[aria-label="News topic"]').value==='grid'||document.querySelector('.pn-news-header-search input').value==='grid');
 await page.locator('#energyPolicyContext>summary').click();
 assert.equal(await page.locator('#energyPolicyContext a[href*="data-centre-covenant"]').count()>0,true);
 assert.match(await page.locator('#energyPolicyContext').innerText(),/PUE 1\.3 or better/);assert.match(await page.locator('#energyPolicyContext').innerText(),/no project compliance assessment/);
 await page.locator('[data-official-context="planning:EN020026"]>summary').click();assert.match(await page.locator('[data-official-context]').innerText(),/proposed transmission up to 2 GW/);
 assert.equal(await page.locator('[data-official-context] a').count(),2);
 await page.locator('#energyPolicyContext').screenshot({path:resolve(out,`policy-${width}.png`)});
 await page.getByRole('button',{name:'Read exact grid-document facts',exact:true}).click();
 assert.equal(await page.locator('.pn-document-facts').evaluate(e=>e.open),true);
 const before=await page.evaluate(()=>JSON.stringify(window.pipelineHeadlineDocument));
 await page.locator('#energyPolicyContext button[data-news-topic="grid"]').click();
 assert.equal(await page.evaluate(()=>window.pipelineEnergyContext.topic()==='grid'||document.querySelector('.pn-news-filter-tools select[aria-label="News topic"]').value==='grid'||document.querySelector('.pn-news-header-search input').value==='grid'),true);
 await page.locator('#energyPolicyContext button[data-news-topic="datacentre"]').click();
 const selection=await page.evaluate(()=>[document.querySelector('.pn-news-filter-tools select[aria-label="News topic"]').value,document.querySelector('.pn-news-filter-tools select[aria-label="News category"]').value,document.querySelector('.pn-news-header-search input').value]);
 if(hasTopicHook){assert.equal(await page.evaluate(()=>window.pipelineEnergyContext.topic()),'datacentre');assert.equal(await page.locator('#liveNews .ln-title').evaluateAll(as=>as.some(a=>/Nvidia Earnings|Markets Wrap|Anthropic.*IPO|India Stock Market/.test(a.textContent))),false);}
 await page.evaluate(()=>window.pipelineHeadlines.render(window.pipelineHeadlineDocument,'snapshot'));
 await page.waitForTimeout(50);
 assert.deepEqual(await page.evaluate(()=>[document.querySelector('.pn-news-filter-tools select[aria-label="News topic"]').value,document.querySelector('.pn-news-filter-tools select[aria-label="News category"]').value,document.querySelector('.pn-news-header-search input').value]),selection,'feed redraw must preserve user filter after return context applied');
 if(process.env.PN_CONTEXT_RETURN_REPLAY==='true'||process.env.PN_CONTEXT_ASYNC_ENTRY==='true'){
  assert.ok(canonicalReplay,'async opt-in requires an explicitly labelled canonical-origin fixture');
  await page.locator('.pipeline-tabs [data-view="solar"]').click();await page.locator('#clearFilters').click();
  await page.waitForFunction(()=>document.querySelector('#tbody')?.dataset.total==='7775');
  const locationBefore=page.url(),mapsBefore=await page.locator('#tbody a.atlaslink:not(.pn-journey-link)').evaluateAll(items=>items.map(a=>a.href));
  if(!await page.evaluate(()=>!!window.pipelineJourneyEntry)){
   assert.notEqual(process.env.PN_CONTEXT_INTEGRATED,'true','integrated source must own its entry runtime');
   await page.addStyleTag({url:start+'/automation/journey_entry_ui/20261118/styles.css'});
   await page.addScriptTag({type:'module',url:start+'/automation/journey_entry_ui/20261118/view.mjs'});
  }else assert.equal(await page.locator('script[src*="journey_entry_ui/20261118/view.mjs"]').count(),1,'actual integrated entry is not injected twice');
  await page.waitForFunction(()=>window.pipelineJourneyEntry&&document.querySelector('#tbody .pn-journey-link')?.href.includes('news_context_url='));
  assert.equal(page.url(),locationBefore,'late entry readiness cannot auto-navigate');
  assert.deepEqual(await page.locator('#tbody a.atlaslink:not(.pn-journey-link)').evaluateAll(items=>items.map(a=>a.href)),mapsBefore);
  const newsState=expected=>{if(!window.pipelineEnergyContext||!document.querySelector('.pn-news-header-search input'))return false;const state={query:document.querySelector('.pn-news-header-search input').value,...Object.fromEntries(['publisher','topic','category','ranking source type'].map(kind=>[kind,document.querySelector('.pn-news-filter-tools select[aria-label="News '+kind+'"]').value])),con  … [line shortened here: 516 characters; full line on GitHub]
  for(const kind of ['publisher','ranking source type']){const select=page.locator('.pn-news-filter-tools select[aria-label="News '+kind+'"]'),value=await select.evaluate(node=>[...node.options].find(o=>o.value)?.value);if(value)await select.selectOption(value);}
  await page.locator('.pn-news-header-search input').fill('data');const wanted=await page.evaluate(newsState);
  const target=page.locator('#tbody .pn-journey-link').first(),url=new URL(await target.getAttribute('href'));assert.equal(url.searchParams.get('news_context_url'),`${start}/uk_renewables_pipeline/${edition}/`);
  // Suppress only fixture outbound navigation; actual source handlers store state.
  await page.evaluate(()=>document.addEventListener('click',event=>event.preventDefault(),{once:true}));await target.click();
  assert.equal(await page.evaluate(()=>history.state.pipelineEnergyNewsReturn.origin?.origin_type),'repd');
  await page.reload({waitUntil:'domcontentloaded'});await page.waitForFunction(newsState,wanted);
  assert.deepEqual(await page.evaluate(newsState),wanted,'typed cold reload retains every News filter and explicit context');
  assert.equal(await page.evaluate(()=>history.state.pipelineEnergyNewsReturn.origin?.origin_type),'repd','manual follows a saved typed origin without clearing it artificially');
  await page.locator('.pn-news-header-search input').fill('battery');const manualWanted=await page.evaluate(newsState),manual=page.locator('#journeyAtlasNav');await manual.waitFor();
  assert.equal(new URL(await manual.getAttribute('href')).searchParams.get('news_context_url'),`${start}/uk_renewables_pipeline/${edition}/`);
  await page.evaluate(()=>document.addEventListener('click',event=>event.preventDefault(),{once:true}));await manual.click();
  assert.equal(await page.evaluate(()=>history.state.pipelineEnergyNewsReturn.origin),null,'manual entry creates no asset association');
  await page.reload({waitUntil:'domcontentloaded'});await page.waitForFunction(newsState,manualWanted);
  assert.deepEqual(await page.evaluate(newsState),manualWanted,'manual cold reload retains every News filter and explicit context');
  if(hasTopicHook){await page.locator('#headlineContextStatus button').click();assert.equal(await page.evaluate(()=>window.pipelineEnergyContext.topic()),null);while(await page.locator('#liveNews .ln-more').count())await page.locator('#liveNews .ln-more').click();const all=await page.locator('#liveNews .ln-title').evaluateAll(as=>as.map(a=>a.href).sort());const original=await page.evaluate(()=>win  … [line shortened here: 558 characters; full line on GitHub]
  // Synthetic late-ranking-option lifecycle; original article/feed data is unchanged.
  await page.evaluate(()=>{const topic=document.querySelector('.pn-news-filter-tools select[aria-label="News topic"]');if(![...topic.options].some(o=>o.value==='storage'))topic.add(new Option('Storage','storage'));topic.value='storage';topic.dispatchEvent(new Event('change'));window.dispatchEvent(new CustomEvent('pipeline-journey-origin',{detail:{origin_type:'repd',origin_id:'repd:2470',technology  … [line shortened here: 418 characters; full line on GitHub]
  await page.reload({waitUntil:'domcontentloaded'});await page.waitForFunction(()=>window.pipelineEnergyContext&&window.pipelineHeadlineDocument?.items?.length>0);
  await page.evaluate(()=>{const topic=document.querySelector('.pn-news-filter-tools select[aria-label="News topic"]');if(![...topic.options].some(o=>o.value==='storage'))topic.add(new Option('Storage','storage'));window.dispatchEvent(new CustomEvent('pipeline-feed-loaded',{detail:window.pipelineHeadlineDocument}));});
  await page.waitForFunction(()=>document.querySelector('.pn-news-filter-tools select[aria-label="News topic"]')?.value==='storage',null,{timeout:3000});
  await page.evaluate(()=>window.dispatchEvent(new CustomEvent('pipeline-journey-origin',{detail:{origin_type:'repd',origin_id:'repd:2470',technology:'battery'}})));
  await page.reload({waitUntil:'domcontentloaded'});await page.waitForFunction(()=>window.pipelineEnergyContext&&window.pipelineHeadlineDocument?.items?.length>0);
  await page.locator('.pn-news-header-search input').fill('solar');
  await page.evaluate(()=>{const topic=document.querySelector('.pn-news-filter-tools select[aria-label="News topic"]');if(![...topic.options].some(o=>o.value==='storage'))topic.add(new Option('Storage','storage'));window.dispatchEvent(new CustomEvent('pipeline-feed-loaded',{detail:window.pipelineHeadlineDocument}));});
  await page.waitForTimeout(50);assert.equal(await page.locator('.pn-news-header-search input').inputValue(),'solar','genuine user input cancels a pending metadata restore');
 }
 await page.evaluate(()=>window.dispatchEvent(new CustomEvent('pipeline-journey-origin',{detail:{origin_type:'datacentre',origin_id:'dc:synthetic-origin'}})));
 await page.locator('#gridTab').click();await page.locator('#journeyNewsContext>summary').click();
 assert.match(await page.locator('#journeyNewsContext').innerText(),/DATACENTRE dc:synthetic-origin: topic context only/);
 assert.equal(await page.evaluate(()=>JSON.stringify(window.pipelineHeadlineDocument)),before);
 await page.evaluate(()=>window.dispatchEvent(new CustomEvent('pipeline-feed-loaded',{detail:null})));assert.match(await page.locator('#journeyNewsContext').innerText(),/No matching topic headlines/);
 assert.equal(await page.evaluate(()=>window.pipelineEnergyContext.selectOrigin({origin_type:'unknown',origin_id:'2470'})),false);assert.match(await page.locator('#journeyNewsContext').innerText(),/Choose a REPD project/);
 assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1),true);
 assert.equal(await page.locator('.pn-energy-context input').count(),0,'existing sole news search retained');
 await page.screenshot({path:resolve(out,`context-${width}.png`)});
 if(hasTopicHook){
  await page.goto(`${start}/uk_renewables_pipeline/${edition}/`,{waitUntil:'domcontentloaded'});await page.waitForFunction(()=>window.pipelineHeadlineDocument?.items?.length>0&&window.pipelineEnergyContext);
  assert.equal(await page.evaluate(()=>window.pipelineEnergyContext.topic()),null);assert.equal(await page.locator('#headlineContextStatus').isHidden(),true,'default view remains complete and uncluttered');
  const original=await page.evaluate(()=>JSON.stringify(window.pipelineHeadlineDocument)),query=await page.locator('.pn-news-header-search input').elementHandle();
  await page.locator('#energyPolicyContext>summary').click();await page.locator('#energyPolicyContext button[data-news-topic="datacentre"]').click();
  await page.locator('#headlineContextStatus button').focus();await page.keyboard.press('Enter');assert.equal(await page.evaluate(()=>window.pipelineEnergyContext.topic()),null);
  await page.locator('#liveNews .ln-more').click();assert.equal(await page.locator('#liveNews .ln-title').count(),24);
  await page.evaluate(()=>window.pipelineHeadlines.render(window.pipelineHeadlineDocument,'snapshot'));assert.equal(await page.locator('#liveNews .ln-title').count(),24,'same-input feed redraw retains expanded original view');
  assert.equal(await query.evaluate(node=>node===document.querySelector('.pn-news-header-search input')),true,'existing sole search node retained');assert.equal(await page.evaluate(()=>JSON.stringify(window.pipelineHeadlineDocument)),original);
 }
 assert.deepEqual(errors,[]);receipts.push({width,reduced_motion:width===390,source:'actual_saved_feed_replay',canonical_origin_fixture:canonicalReplay,async_entry:process.env.PN_CONTEXT_ASYNC_ENTRY==='true',return_replay:process.env.PN_CONTEXT_RETURN_REPLAY==='true',main_context_hook:hasTopicHook,policy_state:state,synthetic_origin:true,original_feed_unchanged:true,errors});await context.close();
}}finally{await browser.close();await new Promise(r=>server.close(r));writeFileSync(resolve(out,'receipt.json'),JSON.stringify({edition,public_acceptance:false,receipts},null,2)+'\n');}
console.log(JSON.stringify(receipts));

Contracts Test

A test in the energy context ui folder of GlobalGrid2050 that checks Model.

testglobalgrid2050 / automation/energy_context_ui/20261118/contracts.test.mjs · lines 1–78 of 78 · version 2026-11-18 · Entry point · pattern article (shared by 4 files)

What it does
It tests its inputs. Defines article. Uses libraries node:test, node:assert/strict, node:fs. 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 policy.json; JSON file review.json; JSON file facts.json; JSON file notice.json; JSON file pipeline_headlines.snapshot.json.
Downstream impact
Used directly by 1 file: GlobalGrid2050 V934 Preview Acceptance Workflow (globalgrid2050).
What it achieves
Defines `article`. It reads `./policy.json`.
Why it matters
Run by GlobalGrid2050 V934 Preview Acceptance Workflow.
Application
globalgrid2050 · automation/energy_context_ui/20261118 · test
Uses
Model (import), node:test, node:assert/strict, node:fs
Used by
run by GlobalGrid2050 V934 Preview Acceptance Workflow (workflow run)
Produces
article
Defines here
article
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/contracts.test.mjs:1-78 · blob 206acb24615933fe8d1ac9cafa9eca1aa965643e · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import test from 'node:test';
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import {acceptedPolicy,acceptedGridContext,policyHash,policySource,contextForOrigin,validOrigin,classifyHeadline,infrastructureEntries,relatedHeadlines,newsContextBase,newsContextUrl,requestedContext} from './model.mjs';
const bytes=readFileSync(new URL('./policy.json',import.meta.url),'utf8'),data=JSON.parse(bytes);
const dc={origin_type:'datacentre',origin_id:'dc:example'},repd={origin_type:'repd',origin_id:'2470',technology:'solar'};
const article=(title,link='https://publisher.example/story',extra={})=>({title,link,source:'Original publisher',date:'2026-11-17',first_seen:'2026-11-17T10:00:00Z',...extra});
const approval=()=>({state:'APPROVED_FACTS_ONLY',policy_sha256:policyHash,source_sha256:data.source_sha256,scope:data.rights.scope,reviews:[{role:'GRID_ANALYSER',decision:'PASS',reference:'https://github.com/Ventusltd/neural-link-between-agents/issues/42#issuecomment-100'},{role:'TRAIN_CONDUCTOR',decision:'PASS',reference:'https://github.com/Ventusltd/neural-link-between-agents/issues/42#issuecomm  … [line shortened here: 413 characters; full line on GitHub]

test('actual pinned policy yields national facts only under synthetic approval',async()=>{
 const result=await acceptedPolicy(bytes,approval());assert.equal(result.source_url,policySource);assert.equal(result.themes.length,5);assert.equal(result.quantities.length,2);assert.equal(result.quantities[1].comparison,'AT_MOST');assert.match(result.quantities[1].meaning,/1\.3 or better/);assert.equal(result.project_compliance,null);assert.equal(result.available_capacity,null);assert.deepEqual(r  … [line shortened here: 429 characters; full line on GitHub]
});
test('actual independent review receipts admit policy; pending or altered reviews fail closed',async()=>{
 const recorded=JSON.parse(readFileSync(new URL('./review.json',import.meta.url)));assert.ok(await acceptedPolicy(bytes,recorded));
 const pending={...recorded,state:'REVIEW_REQUIRED',reviews:[]};assert.equal(await acceptedPolicy(bytes,pending),null);
 for(const mutate of [r=>r.reviews[1].role=r.reviews[0].role,r=>r.reviews[1].reference=r.reviews[0].reference,r=>r.reviews[1].reference='https://evil.test/fake',r=>r.source_sha256='0'.repeat(64),r=>r.reviews[0].decision='PENDING']){const r=approval();mutate(r);assert.equal(await acceptedPolicy(bytes,r),null);}
});
test('changed source/fact bytes or project compliance cannot pass policy pin',async()=>{
 for(const mutate of [d=>d.quantities[0].value='6000',d=>d.source_url='javascript:alert(1)',d=>d.project_compliance=true,d=>d.connections.push('nearby'),d=>d.themes[0].fragment='evil']){const d=JSON.parse(bytes);mutate(d);assert.equal(await acceptedPolicy(JSON.stringify(d),approval()),null);}
});
test('three origin kinds retain stable identity and explicitly only topic context',()=>{
 for(const o of [repd,dc,{origin_type:'substation',origin_id:'site:XYZ'}]){const result=contextForOrigin(o);assert.equal(result.origin_id,o.origin_id);assert.equal(result.association,'TOPIC_CONTEXT_ONLY');assert.equal(result.compliance,null);assert.equal(result.connection,null);}
 assert.deepEqual(contextForOrigin(repd).topics,['solar']);assert.deepEqual(contextForOrigin(dc).topics,['datacentre','grid']);
 assert.deepEqual(contextForOrigin({...repd,technology:'battery'}).topics,['storage']);
 assert.equal(contextForOrigin({...repd,origin_id:'repd:2470'}).origin_id,'repd:2470');
});
test('unknown origin, malformed REPD, oversized and URL IDs are refused',()=>{
 for(const o of [{},null,{origin_type:'repd',origin_id:'abc'},{origin_type:'repd',origin_id:'2470<script>'},{origin_type:'datacentre',origin_id:'https://evil.test'},{origin_type:'substation',origin_id:'x'.repeat(121)}])assert.equal(validOrigin(o),null);
});
test('headline classifier handles UK/US data-centre spelling without AI substring false positives',()=>{
 for(const title of ['Data centres and grid','Data-center demand','Datacenter demand','AI energy infrastructure'])assert.ok(classifyHeadline(article(title)).includes('datacentre'));
 assert.deepEqual(classifyHeadline(article('Retail train delays')),[]);
});
test('original article fields and clocks preserved, tracking duplicates suppressed only in context',()=>{
 const first=article('AI power and grid','https://publisher.example/story?utm_source=a'),duplicate=article('Different label','https://publisher.example/story?utm_source=b',{technology:'datacentre'}),other=article('Solar expansion','https://publisher.example/solar');
 const doc={items:[first,duplicate,other]},before=JSON.stringify(doc),result=relatedHeadlines(doc,dc);assert.equal(result.length,1);assert.equal(result[0].item,first);assert.equal(result[0].item.link,first.link);assert.equal(JSON.stringify(doc),before);
});
test('possible match never becomes exact project news or Journey origin',()=>{
 const item=article('Local retail plan','https://publisher.example/retail',{possible_match:{repd_ref:'2470',site_name:'Example'}});assert.deepEqual(relatedHeadlines({items:[item]},repd),[]);
});
test('unsafe URLs, missing credits and arbitrary count inputs do not produce links',()=>{
 for(const bad of ['javascript:alert(1)','https://user:pass@publisher.example/x','http://publisher.example/x','https://127.0.0.1/x','https://host.internal/x'])assert.deepEqual(relatedHeadlines({items:[article('Data centre grid',bad)]},dc),[]);
 assert.deepEqual(relatedHeadlines({items:[article('Grid',{},{source:''})]},dc),[]);assert.deepEqual(relatedHeadlines({items:Array(201).fill(article('Grid'))},dc),[]);
 assert.deepEqual(relatedHeadlines({items:[article('Grid','https://publisher.example/x',{date:'x'.repeat(65)})]},dc),[]);
 assert.deepEqual(relatedHeadlines({items:[article('Grid')]},dc,{limit:100}),[]);
});
test('context links point to current immutable Pipeline edition, no open redirects',()=>{
 const base='https://globalgrid2050.com/uk_renewables_pipeline/202611171940/';const url=new URL(newsContextUrl(base,dc));assert.equal(url.searchParams.get('news_origin_id'),'dc:example');assert.equal(url.searchParams.get('news_topic'),'datacentre');assert.equal(url.hash,'#headlinesHeading');
 for(const bad of ['https://evil.test/uk_renewables_pipeline/202611171940/','https://globalgrid2050.com/','javascript:alert(1)',base+'?q=1',base+'#redirect',base.replace('globalgrid2050.com','globalgrid2050.com:8443'),base.replace('globalgrid2050.com','evil@globalgrid2050.com')]){assert.equal(newsContextUrl(bad,dc),null);assert.equal(newsContextBase(bad),null);}
 assert.equal(newsContextBase(base),base);assert.equal(newsContextBase(base+'index.html'),base+'index.html');
});
test('requested context has bounded topics and treats bad origin independently',()=>{
 assert.deepEqual(requestedContext('?news_topic=grid&news_origin_type=repd&news_origin_id=2470'),{topic:'grid',origin:{origin_type:'repd',origin_id:'2470',technology:null}});
 assert.equal(requestedContext('?news_topic=<script>'),null);assert.deepEqual(requestedContext('?news_topic=grid&news_origin_type=evil'),{topic:'grid',origin:null});
});
test('existing approved government producer yields planning context, never a selected-asset connection',async()=>{
 const facts=readFileSync(new URL('../../document_facts_ui/20261117-v939/facts.json',import.meta.url),'utf8'),notice=JSON.parse(readFileSync(new URL('../../grid_notice_ui/20261117-v938/notice.json',import.meta.url)));
 const context=await acceptedGridContext(facts,notice);assert.equal(context.project,'planning:EN020026');assert.equal(context.decision.precision,'DAY');assert.equal(context.decision.value,'2026-10-30');assert.equal(context.planned_upper_bound.value,'2');assert.equal(context.planned_upper_bound.unit,'GW');assert.match(context.planned_upper_bound.meaning,/not current, available or commissioned/);ass  … [line shortened here: 579 characters; full line on GitHub]
 assert.equal(await acceptedGridContext(facts+' ',notice),null);assert.equal(await acceptedGridContext(facts,{...notice,publishable:false}),null);
});
test('missing feeds and unknown origins produce no context articles',()=>{
 assert.deepEqual(relatedHeadlines(null,repd),[]);assert.deepEqual(relatedHeadlines({items:[]},repd),[]);assert.deepEqual(relatedHeadlines({items:[article('Grid')]},{origin_type:'unknown',origin_id:'2470'}),[]);
});
test('actual pinned saved feed distinguishes energy infrastructure from generic AI finance',()=>{
 const feed=JSON.parse(readFileSync(new URL('../../../uk_renewables_pipeline/202611171940/news/pipeline_headlines.snapshot.json',import.meta.url)));assert.equal(feed.items.length,71);
 for(const index of [0,8,9,11]){assert.equal(feed.items[index].category,'datacentre');assert.equal(classifyHeadline(feed.items[index]).includes('datacentre'),false,'AI finance alone is not infrastructure context');}
 for(const index of [1,3,4,5,6,10,12,13])assert.ok(classifyHeadline(feed.items[index]).includes('datacentre'));
 for(const index of [18,45,68])assert.ok(classifyHeadline(feed.items[index]).includes('grid'),'actual pylon/power-cable/transmission items retained');
 for(const index of [17,19,40,57])assert.ok(classifyHeadline(feed.items[index]).includes('storage'),'battery/BESS/LDES context retained');
});
test('explicit main-list infrastructure filtering preserves original references, clocks and default complete view',()=>{
 const feed=JSON.parse(readFileSync(new URL('../../../uk_renewables_pipeline/202611171940/news/pipeline_headlines.snapshot.json',import.meta.url))),entries=feed.items.map((item,index)=>({item,index})),before=JSON.stringify(entries);
 assert.equal(infrastructureEntries(entries,null),entries);assert.deepEqual(infrastructureEntries(entries,'unknown'),[]);
 const selected=infrastructureEntries(entries,'datacentre');for(const index of [0,8,9,11])assert.equal(selected.some(entry=>entry.index===index),false);
 for(const index of [1,3,4,5,6,10,12,13])assert.ok(selected.some(entry=>entry.index===index));
 assert.ok(selected.every(entry=>entry===entries[entry.index]));assert.deepEqual(selected.map(e=>e.index),selected.map(e=>e.index).sort((a,b)=>a-b));assert.equal(JSON.stringify(entries),before);
 assert.ok(infrastructureEntries(entries,'grid').some(entry=>entry.index===45));
});

Model

A JavaScript module in the energy context ui folder of GlobalGrid2050 that works with solar, wind, the Renewable Energy Planning Database (REPD) register and substations, using SHA-256.

transformglobalgrid2050 / automation/energy_context_ui/20261118/model.mjs · lines 1–76 of 76 · version 2026-11-18 · pattern safeUrl (shared by 5 files)

What it does
It calculates solar, wind, the REPD register and substations. Defines 12 functions or classes, including safeUrl, digest, validOrigin, contextForOrigin, classifyHeadline.
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, wind, the REPD register, substations.
Downstream impact
Used directly by 2 files: Contracts Test (globalgrid2050); View (globalgrid2050). Reached from 7 other entry points, including GlobalGrid2050 — UK Renewables Pipeline Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/); GlobalGrid2050 Pipeline Legal Evidence Workflow (globalgrid2050); GlobalGrid2050 V934 Preview Acceptance Workflow (globalgrid2050).
What it achieves
It classifies headline (`classifyHeadline`) and is built from the safe URL helper (`safeUrl`) and the valid origin helper (`validOrigin`). Defines `safeUrl`, `digest`, `validOrigin` and 9 more.
Why it matters
Imported by View. Checked by Contracts Test.
Application
globalgrid2050 · automation/energy_context_ui/20261118 · JavaScript module
Uses
Model (import)
Used by
imported by Contracts Test (import), imported by View (import)
Produces
policySource, policyHash, validOrigin, contextForOrigin, classifyHeadline, infrastructureEntries, relatedHeadlines, newsContextBase, newsContextUrl, requestedContext, acceptedGridContext, acceptedPolicy
Defines here
safeUrl, digest, validOrigin, contextForOrigin, classifyHeadline, infrastructureEntries, relatedHeadlines, newsContextBase, newsContextUrl, requestedContext, acceptedGridContext, acceptedPolicy
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/model.mjs:1-76 · blob 43cdd1dac8fb8cf30f6de14c0f7b472bda02ce08 · 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
import {acceptedDocuments} from '../../document_facts_ui/20261117-v939/model.mjs';
export const policySource='https://www.gov.uk/government/publications/data-centre-covenant/the-data-centre-covenant';
export const policyHash='e2ba6c89c9bfd47456442ccb4c20e12d8297682630bca4b135da9a2e83a6d1ff';
const originKinds=new Set(['repd','datacentre','substation']);
const topics=new Set(['datacentre','grid','renewables','storage','solar','wind']);
const themes={datacentre:/\b(?:data[ -]?cent(?:re|er)s?|AI (?:power|energy|infrastructure|demand))\b/i,grid:/\b(?:grid|substation|transmission|distribution|connection|network upgrade|pylon|power cable|overhead line)s?\b/i,storage:/\b(?:battery|batteries|storage|BESS|LDES|pumped hydro|flexibility)\b/i,solar:/\b(?:solar|photovoltaic|PV)\b/i,wind:/\b(?:wind|offshore|onshore)\b/i,renewables:/\b(?:rene  … [line shortened here: 455 characters; full line on GitHub]
const safeUrl=value=>{try{const u=new URL(value);return typeof value==='string'&&u.protocol==='https:'&&!u.username&&!u.password&&(!u.port||u.port==='443')&&!/(^|\.)(localhost|local|internal)$/.test(u.hostname)&&u.hostname.includes('.')&&!/^[\d.]+$/.test(u.hostname)?u:null;}catch{return null;}};
const digest=async text=>Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',new TextEncoder().encode(text)))).map(v=>v.toString(16).padStart(2,'0')).join('');

export function validOrigin(origin){
 if(!origin||!originKinds.has(origin.origin_type)||typeof origin.origin_id!=='string'||!/^[\w:.-]{1,120}$/.test(origin.origin_id))return null;
 if(origin.origin_type==='repd'&&!/^(?:repd:)?\d+$/.test(origin.origin_id))return null;
 return {origin_type:origin.origin_type,origin_id:origin.origin_id,technology:typeof origin.technology==='string'?origin.technology.slice(0,50):null};
}
export function contextForOrigin(origin){
 const value=validOrigin(origin);if(!value)return null;
 const technology=value.technology?.toLowerCase()||'';
 const selected=value.origin_type==='datacentre'?['datacentre','grid']:value.origin_type==='substation'?['grid']:['solar','wind','storage'].filter(t=>t==='storage'?/storage|battery|bess/.test(technology):technology.includes(t));
 return {...value,topics:selected.length?selected:['renewables','grid'],association:'TOPIC_CONTEXT_ONLY',compliance:null,connection:null};
}
export function classifyHeadline(item){
 if(!item||typeof item.title!=='string'||typeof item.source!=='string')return [];
 // Existing discovery categories alone cannot turn generic AI stock/IPO news
 // into power-infrastructure context. Require the original title or technology.
 const text=[item.title,item.technology].filter(v=>typeof v==='string').join(' ');
 return Object.entries(themes).filter(([,rule])=>rule.test(text)).map(([topic])=>topic);
}
export function infrastructureEntries(entries,topic){
 if(!Array.isArray(entries))return [];
 if(topic===null)return entries;
 if(!topics.has(topic))return [];
 const selected=topic==='renewables'?['renewables','solar','wind','storage']:[topic];
 return entries.filter(entry=>classifyHeadline(entry.item).some(value=>selected.includes(value)));
}
export function relatedHeadlines(doc,origin,{limit=6}={}){
 const context=contextForOrigin(origin);if(!context||!Array.isArray(doc?.items)||doc.items.length>200||!Number.isInteger(limit)||limit<1||limit>12)return [];
 const seen=new Set(),result=[];
 for(const item of doc.items){
  const url=safeUrl(item?.link);if(!url||typeof item.title!=='string'||!item.title.trim()||item.title.length>600||typeof item.source!=='string'||!item.source.trim()||item.source.length>160||[item.date,item.first_seen].some(v=>v!==undefined&&v!==null&&(typeof v!=='string'||v.length>64)))continue;
  const matches=classifyHeadline(item).filter(t=>context.topics.includes(t));if(!matches.length)continue;
  // Only the duplicate key is normalised; original publisher URL/text/clocks remain untouched.
  url.hash='';for(const key of [...url.searchParams.keys()])if(/^utm_/i.test(key))url.searchParams.delete(key);
  if(seen.has(url.href))continue;seen.add(url.href);
  result.push({item,topics:matches,association:'TOPIC_CONTEXT_ONLY'});if(result.length===limit)break;
 }
 return result;
}
export function newsContextBase(base){
 return typeof base==='string'&&/^https:\/\/globalgrid2050\.com\/uk_renewables_pipeline\/\d{12}\/(?:index\.html)?$/.test(base)?base:null;
}
export function newsContextUrl(base,origin){
 const context=contextForOrigin(origin),accepted=newsContextBase(base);if(!context||!accepted)return null;const url=new URL(accepted);
 url.searchParams.set('news_topic',context.topics[0]);url.searchParams.set('news_origin_type',context.origin_type);url.searchParams.set('news_origin_id',context.origin_id);url.hash='headlinesHeading';return url.href;
}
export function requestedContext(search){
 const p=new URLSearchParams(search),topic=p.get('news_topic');if(!topics.has(topic))return null;
 const origin=validOrigin({origin_type:p.get('news_origin_type'),origin_id:p.get('news_origin_id')});return {topic,origin};
}
export async function acceptedGridContext(facts,notice){
 const bundle=await acceptedDocuments(facts,notice);if(!bundle)return null;
 const documents=bundle.documents.map(d=>({title:d.title,publisher:d.publisher,source_url:d.source_url,source_sha256:d.source_version,published_date:d.published_date,retrieved_at:d.retrieved_at}));
 const decision=bundle.documents.flatMap(d=>d.facts).find(f=>f.id==='consent_decision');
 const capacity=bundle.documents.flatMap(d=>d.facts).find(f=>f.id==='planned_transmission_upper_bound');
 if(!decision||!capacity)return null;
 return {project:'planning:EN020026',title:'Sea Link',documents,decision:decision.value,planned_upper_bound:{value:capacity.value,unit:capacity.unit,meaning:capacity.meaning},association:'OFFICIAL_PROJECT_CONTEXT_ONLY',selected_asset_association:null,connections:[],available_capacity:null};
}
export async function acceptedPolicy(bytes,review){
 try{
  if(typeof bytes!=='string'||bytes.length>16000||await digest(bytes)!==policyHash)return null;
  const data=JSON.parse(bytes);
  if(data.schema!=='globalgrid2050.energy-policy-context.v1'||data.source_url!==policySource||data.scope!=='NATIONAL_POLICY_CONTEXT_ONLY'||data.publisher!=='HM Treasury'||data.project_compliance!==null||data.available_capacity!==null||data.connections.length||data.asset_associations.length||data.themes.length!==5||data.quantities.length!==2)return null;
  if(review?.state!=='APPROVED_FACTS_ONLY'||review.policy_sha256!==policyHash||review.source_sha256!==data.source_sha256||review.scope!==data.rights.scope||!Array.isArray(review.reviews)||review.reviews.length!==2)return null;
  const roles=new Set(),refs=new Set();for(const r of review.reviews){if(!['GRID_ANALYSER','TRAIN_CONDUCTOR','INDEPENDENT_REVIEWER'].includes(r.role)||roles.has(r.role)||refs.has(r.reference)||r.decision!=='PASS'||!/^https:\/\/github\.com\/Ventusltd\/[\w.-]+\/(?:issues|pull)\/\d+#issuecomment-\d+$/.test(r.reference))return null;roles.add(r.role);refs.add(r.reference);}
  return data;
 }catch{return null;}
}

Prepare Preview

A Python command-line tool in the energy context ui folder of GlobalGrid2050 covering sources, projects, major project news and preview receipt, using SHA-256.

storageglobalgrid2050 / automation/energy_context_ui/20261118/prepare_preview.py · lines 1–76 of 76 · version 2026-11-18 · Entry point

What it does
Defines main. Uses libraries pathlib, argparse, base64, hashlib, io. Side effects: 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. README: "`prepare_preview.py --source-ref --edition --output ` creates a disposable, SRI-wired integrated preview from exact Git archive bytes and copies this module into it."
Inputs & outputs
In: JSON file sources.json; JSON file projects.json; JSON file major_project_news_v9_5_1.json; command-line arguments. Out: JSON file preview-receipt.json.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Create a disposable integrated preview without reserving/editing an edition. It accepts `--source-ref`, `--edition` and `--output`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
globalgrid2050 · automation/energy_context_ui/20261118 · Python CLI
Uses
pathlib, argparse, base64, hashlib, io, json, re, shutil
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/energy_context_ui/20261118/prepare_preview.py:1-76 · blob 8f6bb47f5ab72b6c07d83f84792b212bf161662c · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Create a disposable integrated preview without reserving/editing an edition."""
from pathlib import Path
import argparse,base64,hashlib,io,json,re,shutil,subprocess,zipfile


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--source-ref',required=True)
    parser.add_argument('--edition',required=True)
    parser.add_argument('--output',type=Path,required=True)
    parser.add_argument('--journey-ref',help='Optional exact sender commit, copied for explicit async fixture loading')
    parser.add_argument('--news-hook',action='store_true',help='Preview the new-edition-only current-view getter')
    args=parser.parse_args()
    if not re.fullmatch('[a-f0-9]{40}',args.source_ref) or not re.fullmatch('[0-9]{12}',args.edition):
        raise SystemExit('Exact source commit and dated edition required')
    if args.journey_ref and not re.fullmatch('[a-f0-9]{40}',args.journey_ref):
        raise SystemExit('Exact Journey sender commit required')
    root=Path(__file__).resolve().parents[3]
    output=args.output.resolve()
    if output.exists() or output==root or root in output.parents:
        raise SystemExit('Use a new disposable output outside the source worktree')
    source_index=subprocess.check_output(['git','-C',str(root),'show',f'{args.source_ref}:uk_renewables_pipeline/{args.edition}/index.html'])
    references=re.findall(r'(?:src|href)="\.\./\.\./(automation/[^"?]+)',source_index.decode('utf-8'))
    shared=sorted({str(Path(value).parent).replace('\\','/') for value in references})
    # Existing dynamic imports/data consumers are outside direct HTML tags.
    # Reuse their committed closure; never replace a missing input with a mock.
    shared+=['automation/primary_note_ui','automation/news/grid_watch/sources.json',
             'uk_renewables_pipeline/202611161747/global-datacentres/projects.json',
             'dist/major_project_news_v9_5_1.json']
    archive=subprocess.check_output(['git','-C',str(root),'archive','--format=zip',args.source_ref,f'uk_renewables_pipeline/{args.edition}',*shared],timeout=90)
    if len(archive)>100_000_000:
        raise SystemExit('Archive bound exceeded')
    with zipfile.ZipFile(io.BytesIO(archive)) as files:
        if sum(item.file_size for item in files.infolist())>200_000_000:
            raise SystemExit('Expanded preview bound exceeded')
        for item in files.infolist():
            if not (output/item.filename).resolve().is_relative_to(output):
                raise SystemExit('Unsafe archive path')
        output.mkdir(parents=True)
        files.extractall(output)
    if args.journey_ref:
        sender=subprocess.check_output(['git','-C',str(root),'archive','--format=zip',args.journey_ref,'automation/journey_entry_ui/20261118'],timeout=30)
        with zipfile.ZipFile(io.BytesIO(sender)) as files:
            for item in files.infolist():
                if not (output/item.filename).resolve().is_relative_to(output):
                    raise SystemExit('Unsafe sender archive path')
            files.extractall(output)
    module=Path(__file__).resolve().parent
    target=output/'automation/energy_context_ui/20261118'
    shutil.copytree(module,target,dirs_exist_ok=True,ignore=shutil.ignore_patterns('__pycache__','*.pyc'))
    index=output/f'uk_renewables_pipeline/{args.edition}/index.html'
    original=index.read_bytes()
    if original!=source_index:
        raise SystemExit('Archive index differs from committed source')
    styles=base64.b64encode(hashlib.sha256((module/'styles.css').read_bytes()).digest()).decode()
    script=base64.b64encode(hashlib.sha256((module/'view.mjs').read_bytes()).digest()).decode()
    tags=f'<link rel="stylesheet" href="../../automation/energy_context_ui/20261118/styles.css" integrity="sha256-{styles}">\n<script type="module" src="../../automation/energy_context_ui/20261118/view.mjs" integrity="sha256-{script}"></script>\n'
    text=original.decode('utf-8')
    if text.count('</body>')!=1 or 'energy_context_ui/20261118/view.mjs' in text:
        raise SystemExit('Unexpected predecessor context inclusion')
    index.write_text(text.replace('</body>',tags+'</body>'),encoding='utf-8',newline='\n')
    hook_delta=0
    if args.news_hook:
        renderer=output/f'uk_renewables_pipeline/{args.edition}/scripts/plugins/live-news.js'
        before=renderer.read_bytes();code=before.decode('utf-8');needle='attachView: function(adapter)'
        if code.count(needle)!=1:raise SystemExit('Unexpected existing news adapter API')
        renderer.write_text(code.replace(needle,'getViewAdapter:function(){return qualityAdapter;},'+needle),encoding='utf-8',newline='\n');hook_delta=renderer.stat().st_size-len(before)
    receipt={'scope':'LOCAL_REVERSIBLE_PREVIEW_ONLY','source_ref':args.source_ref,'edition':args.edition,'original_index_sha256':hashlib.sha256(original).hexdigest(),'index_bytes_before':len(original),'index_bytes_after':index.stat().st_size,'edition_bytes_delta':index.stat().st_size-len(original),'style_sha256':hashlib.sha256((module/'styles.css').read_bytes()).hexdigest(),'module_sha256':hashlib  … [line shortened here: 509 characters; full line on GitHub]
    receipt['journey_sender_ref']=args.journey_ref
    receipt['news_hook_bytes']=hook_delta
    receipt['total_edition_bytes_delta']=receipt['edition_bytes_delta']+hook_delta
    (output/'preview-receipt.json').write_text(json.dumps(receipt,indent=2)+'\n')
    print(json.dumps(receipt,indent=2))


if __name__=='__main__':main()