GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / globalgrid2050 / uk_renewables_pipeline/202609051156/tests

Check V7 2 Project Model and 3 more files

A JavaScript module in the tests folder of GlobalGrid2050 that tests projects plugin, solar, the Renewable Energy Planning Database (REPD) register and battery storage (BESS).

623 lines of JavaScript and Python from globalgrid2050, in 4 files. Topic: Electricity markets and data pipelines. Section 924 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. Check Modules test · globalgrid2050 / uk_renewables_pipeline/202609051156/tests/check_modules.mjs lines 1–45
  2. Check V5 Parity test · globalgrid2050 / uk_renewables_pipeline/202609051156/tests/check_v5_parity.py lines 1–184
  3. Check V7 2 Project Controls test · globalgrid2050 / uk_renewables_pipeline/202609051156/tests/check_v7_2_project_controls.mjs lines 1–160
  4. Check V7 2 Project Model test · globalgrid2050 / uk_renewables_pipeline/202609051156/tests/check_v7_2_project_model.mjs lines 1–234

Check Modules

A JavaScript module in the tests folder of GlobalGrid2050.

testglobalgrid2050 / uk_renewables_pipeline/202609051156/tests/check_modules.mjs · lines 1–45 of 45 · version 2026-09-05 11:56 · Not reached from any entry point (candidate for review)

What it does
It tests its inputs. Uses libraries node:assert/strict.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'renewables'): 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
Its name says it checks modules.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · uk_renewables_pipeline/202609051156/tests · JavaScript module
Uses
State (import), Testcode — Pipeline (import), Plugin Host (import), Newspaper (import), node:assert/strict
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 uk_renewables_pipeline/202609051156/tests/check_modules.mjs:1-45 · blob 51bc97c99948301d857d778775cd53031c3bc800 · 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 assert from "node:assert/strict";

import { state } from "../scripts/core/state.js";
import { escapeHtml, isFinanceEvent, normaliseProject, titleCase } from "../scripts/core/utils.js";
import { startPlugins } from "../scripts/core/plugin-host.js";
import { signalForProject } from "../scripts/plugins/newspaper.js";

assert.equal(normaliseProject("Beacon Fen & Energy Park"), "beacon fen and energy park");
assert.equal(titleCase("UNDER CONSTRUCTION"), "Under Construction");
assert.equal(escapeHtml('<a href="x">&</a>'), "&lt;a href=&quot;x&quot;&gt;&amp;&lt;/a&gt;");
assert.equal(isFinanceEvent("financial close"), true);
assert.equal(isFinanceEvent("PROJECT UPDATE"), false);

state.newsItems = [
  { project: "Beacon Fen Energy Park", event: "CONSENT", published: "2026-08-01" },
  { project: "Beacon Fen Energy Park", event: "OPERATIONAL", published: "2026-08-02" },
  { project: "Coalburn II", event: "FINANCIAL CLOSE", published: "2026-08-03" },
  { project: "Cleve Hill", event: "ACQUISITION", published: "2026-08-04" },
];

assert.deepEqual(signalForProject("Beacon Fen Energy Park"), {
  label: "APPROVED*", cls: "approved", note: "headline 2026-08-01",
});
assert.deepEqual(signalForProject("Coalburn II"), {
  label: "FINANCED*", cls: "finance", note: "headline 2026-08-03",
});
assert.deepEqual(signalForProject("Cleve Hill"), {
  label: "M&A*", cls: "finance", note: "headline 2026-08-04",
});
assert.deepEqual(signalForProject("No Headline Project"), {
  label: "—", cls: "none", note: "no matched headline",
});

const order = [];
assert.deepEqual(startPlugins([
  { id: "one", start: () => order.push("one") },
  { id: "two", dependsOn: ["one"], start: () => order.push("two") },
]), ["one", "two"]);
assert.deepEqual(order, ["one", "two"]);
assert.throws(
  () => startPlugins([{ id: "two", dependsOn: ["one"], start() {} }]),
  /unmet dependencies/,
);

console.log("V7.1 module contract: PASS");

Check V5 Parity

A Python command-line tool in the tests folder of GlobalGrid2050 that tests Renewable Energy Planning Database (REPD) master, major project news, plugin and solar, using SHA-256.

testglobalgrid2050 / uk_renewables_pipeline/202609051156/tests/check_v5_parity.py · lines 1–184 of 184 · version 2026-09-05 11:56 · Entry point

What it does
It tests REPD master, major project news, plugin and solar. Defines 8 functions or classes, including check, sha256, title_case, project_fixture, news_fixture. Uses libraries __future__, hashlib, json, re, collections. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'renewables'): 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 repd_master.json; JSON file major_project_news_v5.json; JSON file plugin_manifest.json.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It is built from the project fixture helper (`project_fixture`), the news fixture helper (`news_fixture`) and the interface fixture helper (`interface_fixture`). Its name says it checks parity. Defines `check`, `sha256`, `title_case` and 4 more.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
globalgrid2050 · uk_renewables_pipeline/202609051156/tests · Python CLI
Uses
__future__, hashlib, json, re, collections, pathlib
Used by
none found
Produces
check, sha256, title_case, project_fixture, news_fixture, interface_fixture, module_fixture, main
Defines here
check, sha256, title_case, project_fixture, news_fixture, interface_fixture, module_fixture, 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 uk_renewables_pipeline/202609051156/tests/check_v5_parity.py:1-184 · blob d6cebd35dc03571beeef9347f755dd4932c08f71 · 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: production_core
#!/usr/bin/env python3
from __future__ import annotations

import hashlib
import json
import re
from collections import Counter
from pathlib import Path


ROOT = Path(__file__).resolve().parents[3]
V7 = ROOT / "uk_renewables_pipeline/v7"
FAILURES: list[str] = []


def check(name: str, condition: bool, detail: str = "") -> None:
    if not condition:
        FAILURES.append(f"{name}: {detail}")


def sha256(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def title_case(value: str) -> str:
    return " ".join(word[:1].upper() + word[1:].lower() for word in value.split(" "))


def project_fixture() -> None:
    geojson = json.loads((ROOT / "dist/repd_master.json").read_text(encoding="utf-8"))
    rows: list[dict[str, object]] = []
    counties: set[str] = set()
    for feature in geojson.get("features", []):
        properties = feature.get("properties") or {}
        try:
            capacity = float(properties.get("capacity") or 0)
        except (TypeError, ValueError):
            capacity = 0
        if capacity < 1:
            continue
        raw = str(properties.get("raw_tech") or "").lower()
        technology = properties.get("tech")
        if technology in {"solar", "solar_roof"}:
            category = "Solar"
        elif technology == "bess":
            category = "Battery Storage"
        elif technology == "wind":
            category = "Offshore Wind" if "offshore" in raw else "Onshore Wind"
        else:
            continue
        county = title_case(str(
            properties.get("county")
            or properties.get("County")
            or properties.get("lpa")
            or properties.get("local_planning_authority")
            or properties.get("region")
            or ""
        ).strip())
        if county.lower() in {"nan", "none"}:
            county = ""
        if county:
            counties.add(county)
        rows.append({"name": properties.get("name") or "Unknown Site", "cat": category, "mw": capacity})

    expected = {
        "Solar": (2667, 52866.1, 840.0),
        "Battery Storage": (1271, 126959.4, 1450.0),
        "Onshore Wind": (1192, 36107.9, 525.0),
        "Offshore Wind": (80, 46463.4, 4100.0),
    }
    check("legacy project row count", len(rows) == 5210, str(len(rows)))
    check("legacy populated county count", len(counties) == 152, str(len(counties)))
    check("legacy total capacity", abs(sum(float(row["mw"]) for row in rows) - 262396.8) < 0.05)
    check("legacy descending largest", max(float(row["mw"]) for row in rows) == 4100.0)
    for category, (count, capacity, largest) in expected.items():
        selected = [row for row in rows if row["cat"] == category]
        check(f"{category} count", len(selected) == count, str(len(selected)))
        check(
            f"{category} capacity",
            abs(sum(float(row["mw"]) for row in selected) - capacity) < 0.05,
            str(sum(float(row["mw"]) for row in selected)),
        )
        check(f"{category} largest", max(float(row["mw"]) for row in selected) == largest)


def news_fixture() -> None:
    payload = json.loads((ROOT / "dist/major_project_news_v5.json").read_text(encoding="utf-8"))
    items = payload.get("items") or []
    technology = Counter(str(item.get("technology") or "").lower() for item in items)
    events = Counter(str(item.get("event") or "").upper() for item in items)
    expected_events = {
        "CONSENT": 21,
        "CONSTRUCTION": 9,
        "OPERATIONAL": 1,
        "FINANCIAL CLOSE": 16,
        "ACQUISITION": 18,
        "PROJECT UPDATE": 60,
    }
    check("V5 headline count", payload.get("headline_count") == 125 and len(items) == 125)
    check("V5 eligible count", payload.get("eligible_projects") == 559)
    check("V5 horizon", payload.get("lookback_days") == 366)
    check("V5 solar stories", technology["solar"] == 69, str(technology))
    check("V5 BESS stories", technology["bess"] == 56, str(technology))
    for event, count in expected_events.items():
        check(f"V5 {event} stories", events[event] == count, str(events))
    check("V5 finance-filter fixture", events["FINANCIAL CLOSE"] + events["ACQUISITION"] == 34)


def interface_fixture() -> None:
    index = (V7 / "index.html").read_text(encoding="utf-8")
    expected_ids = {
        "county", "export", "g1", "g2", "g3", "v1", "v2", "v3", "newsMeta", "newsSearch",
        "newsTools", "search", "status", "stories", "tbody", "tech",
    }
    ids = set(re.findall(r'\bid="([^"]+)"', index))
    check("required DOM IDs", expected_ids <= ids, str(sorted(expected_ids - ids)))
    check("news control count", len(re.findall(r"\bdata-news=", index)) == 7)
    check("technology control count", len(re.findall(r"\bdata-tech=", index)) == 5)
    check("status control count", len(re.findall(r"\bdata-status=", index)) == 5)
    check("table column count", len(re.findall(r"<th(?:\s|>)", index)) == 8)
    check("Chart.js dependency", "https://cdn.jsdelivr.net/npm/chart.js" in index)
    check("V7.1 release label", "V7.1" in index)
    check("no page-level inline CSS", "<style>" not in index)
    check("no inline JavaScript", not re.search(r"<script(?![^>]*\bsrc=)[^>]*>", index))
    expected_links = [
        "../dashboard_v6_live.html", "../dashboard_v5_live.html", "../dashboard_v4_live.html",
        "../dashboard_v3_live_2026-08-22.html", "../dashboard_v2_2026-08-22.html", "../dashboard.html",
        "../../index.html", "../../repd_grid_atlasv8/",
    ]
    for link in expected_links:
        check(f"navigation link {link}", f'href="{link}"' in index)


def module_fixture() -> None:
    expected_css = "036dbfe43ef1ffb2c55ba277d49dec57ab7c7be976289226a5d568e1f1be319d"
    check("exact V5 CSS extraction", sha256(V7 / "styles/v7.css") == expected_css, sha256(V7 / "styles/v7.css"))
    state_source = (V7 / "scripts/core/state.js").read_text(encoding="utf-8")
    newspaper = (V7 / "scripts/plugins/newspaper.js").read_text(encoding="utf-8")
    projects = (V7 / "scripts/plugins/projects.js").read_text(encoding="utf-8")
    filters = (V7 / "scripts/plugins/project-filters.js").read_text(encoding="utf-8")
    table = (V7 / "scripts/plugins/project-table.js").read_text(encoding="utf-8")
    export = (V7 / "scripts/plugins/project-export.js").read_text(encoding="utf-8")
    app = (V7 / "scripts/app.js").read_text(encoding="utf-8")
    plugin_manifest = json.loads((V7 / "data/plugin_manifest.json").read_text(encoding="utf-8"))
    for path in ("../../dist/repd_master.json", "../../dist/major_project_news_v5.json"):
        check(f"same-origin path {path}", path in state_source)
    check("raw GitHub news fallback", "raw.githubusercontent.com/Ventusltd/globalgrid2050/main" in state_source)
    check("parallel news source collection", "Promise.allSettled" in newspaper)
    check("newest news edition selection", "payloadTime(right.data) - payloadTime(left.data)" in newspaper)
    check("news redraws loaded projects", "if (state.all.length) refreshProjects();" in newspaper)
    check("independent news load", "loadNews();" in app)
    check("independent project load", "loadProjects();" in app)
    check("stable plugin manifest version", plugin_manifest.get("version") == "7.1")
    check(
        "stable plugin order",
        [plugin.get("id") for plugin in plugin_manifest.get("plugins", [])] == ["gauges", "newspaper", "projects"],
    )
    check("plugin host entrypoint", "startPlugins([" in app)
    check("one-MW display floor", "if (mw < 1) return null;" in projects)
    check("descending-capacity rows", "right.mw - left.mw" in projects)
    check("filters separated from loader", "applyProjectFilters" in filters and "bindProjectFilters" in filters)
    check("table separated from loader", "drawProjectTable" in table)
    check("export separated from loader", "bindProjectExport" in export)
    check("CSV BOM", "\\ufeff" in export)
    check("zero-result export parity", "state.filtered.length ? state.filtered : state.all" in export)
    check("Google News project link", "google.com/search" in table and "tbm=nws" in table)


def main() -> int:
    interface_fixture()
    module_fixture()
    project_fixture()
    news_fixture()
    if FAILURES:
        print(f"V5 parity: FAIL ({len(FAILURES)} failures)")
        for failure in FAILURES:
            print(f"FAIL: {failure}")
        return 1
    print("V5 parity: PASS (interface, modules, 5,210 projects, 125 headlines)")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

Check V7 2 Project Controls

A JavaScript module in the tests folder of GlobalGrid2050 that tests projects plugin, the Renewable Energy Planning Database (REPD) register, battery storage (BESS) and solar.

testglobalgrid2050 / uk_renewables_pipeline/202609051156/tests/check_v7_2_project_controls.mjs · lines 1–160 of 160 · version 2026-09-05 11:56 · Not reached from any entry point (candidate for review)

What it does
It tests projects plugin, the REPD register, battery storage (BESS) and solar. Defines gaugeMap, resultRefs. Uses libraries node:assert/strict, node:fs/promises. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'renewables'): 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, battery storage (BESS), solar.
Inputs & outputs
In: JSON file projects-plugin.v7.2.json; JSON file projects.json.
What it achieves
It is built from the gauge map helper (`gaugeMap`) and the result refs helper (`resultRefs`). Its name says it checks project controls. Defines `gaugeMap` and `resultRefs`. It reads `contracts/projects-plugin.v7.2.json`.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · uk_renewables_pipeline/202609051156/tests · JavaScript module
Uses
Canonical Projects (import), Project State (import), Canonical Project Controls (import), node:assert/strict, node:fs/promises
Used by
none found
Produces
gaugeMap, resultRefs
Defines here
gaugeMap, resultRefs
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_renewables_pipeline/202609051156/tests/check_v7_2_project_controls.mjs:1-160 · blob 319e9210295c64125fdb0acf4e23a0f0ec0fa37c · 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 { readFile } from "node:fs/promises";

import { buildCanonicalProjectModel } from "../scripts/data/canonical-projects.js";
import {
  beginCanonicalProjectLoad,
  commitCanonicalProjectModel,
  createCanonicalProjectState,
  failCanonicalProjectLoad,
} from "../scripts/core/project-state.js";
import {
  buildCanonicalProjectControlsView,
  createCanonicalProjectControls,
} from "../scripts/plugins/canonical-project-controls.js";

const v7Url = new URL("../", import.meta.url);
const contract = JSON.parse(await readFile(new URL("contracts/projects-plugin.v7.2.json", v7Url), "utf8"));
const payload = JSON.parse(await readFile(new URL("data/v7.2/projects.json", v7Url), "utf8"));
const model = buildCanonicalProjectModel(payload, contract);

const gaugeMap = (view) => Object.fromEntries(view.gauges.map((gauge) => [gauge.id, gauge]));
const resultRefs = (state) => state.filtered.map((project) => project.repd_ref);

const unavailableState = createCanonicalProjectState();
beginCanonicalProjectLoad(unavailableState);
failCanonicalProjectLoad(unavailableState, "first load unavailable");
const unavailable = buildCanonicalProjectControlsView(unavailableState);
assert.equal(unavailable.available, false);
assert.equal(unavailable.status, "error");
assert.equal(unavailable.gauges, null);
assert.equal(unavailable.resultCount, null);
assert.equal(unavailable.error, "first load unavailable");

const state = createCanonicalProjectState();
commitCanonicalProjectModel(state, model);
const controls = createCanonicalProjectControls(state);
let view = controls.snapshot();
let gauges = gaugeMap(view);

assert.equal(view.available, true);
assert.equal(view.status, "ready");
assert.equal(view.resultCount, 766);
assert.equal(view.gauges.length, 4);
assert.equal("combined_capacity" in gauges, false);
assert.equal(gauges.solar_mwp.value, 34073.49);
assert.equal(gauges.solar_mwp.unit, "MWp");
assert.equal(gauges.bess_mw.value, 106338.18);
assert.equal(gauges.bess_mw.unit, "MW");
assert.equal(gauges.project_count.value, 766);
assert.equal(gauges.largest_project.value, 1450);
assert.equal(gauges.largest_project.unit, "MW");
assert.equal(gauges.largest_project.project.gg_project_id, "GG2050-REPD-12453");
assert.equal(view.capacityBasis, "official_repd_record_capacity_not_development_deduplicated");
assert.deepEqual(view.lifecycleViews.map(({ id, count }) => [id, count]), [
  ["ALL", 766],
  ["CURRENT", 670],
  ["DISPUTED", 3],
  ["HISTORICAL", 63],
  ["REVIEW", 30],
]);
assert.deepEqual(view.filterOptions.technology.map(({ id, count }) => [id, count]), [
  ["all", 766],
  ["solar", 384],
  ["bess", 382],
]);
assert.deepEqual(view.search.exactIdentifierFields, ["repd_ref", "gg_project_id"]);
assert.equal(view.search.exactIdentifierPrecedence, true);
assert.equal(Object.isFrozen(view), true);
assert.equal(Object.isFrozen(view.gauges), true);
assert.equal(Object.isFrozen(view.lifecycleViews), true);

view = controls.setFilter("technology", "solar");
gauges = gaugeMap(view);
assert.equal(view.resultCount, 384);
assert.equal(gauges.solar_mwp.value, 34073.49);
assert.equal(gauges.bess_mw.value, 0);
assert.equal(gauges.largest_project.value, 840);
assert.equal(gauges.largest_project.unit, "MWp");
assert.equal(gauges.largest_project.project.gg_project_id, "GG2050-REPD-12588");

view = controls.setFilter("technology", "bess");
gauges = gaugeMap(view);
assert.equal(view.resultCount, 382);
assert.equal(gauges.solar_mwp.value, 0);
assert.equal(gauges.bess_mw.value, 106338.18);
assert.equal(gauges.largest_project.value, 1450);
assert.equal(gauges.largest_project.unit, "MW");

controls.reset();
for (const [lifecycleView, count, solarMwp, bessMw, largest, unit] of [
  ["CURRENT", 670, 31453.53, 96540.88, 1450, "MW"],
  ["DISPUTED", 3, 200, 99.9, 125, "MWp"],
  ["HISTORICAL", 63, 1509.07, 6648.7, 1000, "MW"],
  ["REVIEW", 30, 910.89, 3048.7, 1450, "MW"],
]) {
  view = controls.setFilter("lifecycleView", lifecycleView);
  gauges = gaugeMap(view);
  assert.equal(view.resultCount, count);
  assert.equal(gauges.solar_mwp.value, solarMwp);
  assert.equal(gauges.bess_mw.value, bessMw);
  assert.equal(gauges.largest_project.value, largest);
  assert.equal(gauges.largest_project.unit, unit);
  controls.reset();
}

for (const [query, expected] of [
  ["13599", ["13599"]],
  ["GG2050-REPD-13599", ["13599"]],
  ["GG2050-DEV-E13842D4D80DEC", ["13600", "13599"]],
  ["EN010151", ["13600", "13599"]],
  ["Beacon Fen", ["13600", "13599"]],
]) {
  controls.setFilter("query", query);
  assert.deepEqual(resultRefs(state), expected);
  controls.reset();
}

controls.setFilter("technology", "bess");
view = controls.setFilter("query", "13599");
gauges = gaugeMap(view);
assert.equal(view.resultCount, 0);
assert.equal(gauges.solar_mwp.value, 0);
assert.equal(gauges.bess_mw.value, 0);
assert.equal(gauges.project_count.value, 0);
assert.equal(gauges.largest_project.value, null);
assert.equal(gauges.largest_project.unit, null);
assert.equal(gauges.largest_project.project, null);

view = controls.reset();
assert.equal(view.resultCount, 766);
const filtersBeforeInvalid = state.filters;
assert.throws(() => controls.setFilter("county", "Not a canonical county"), /invalid county/);
assert.equal(state.filters, filtersBeforeInvalid);
assert.throws(() => controls.setFilter("unknown", "value"), /unknown filter/);
assert.equal(state.filters, filtersBeforeInvalid);

const retainedMetrics = state.metrics;
beginCanonicalProjectLoad(state);
view = controls.snapshot();
assert.equal(view.available, true);
assert.equal(view.status, "refreshing");
failCanonicalProjectLoad(state, new Error("refresh unavailable"));
view = controls.snapshot();
assert.equal(view.available, true);
assert.equal(view.status, "stale");
assert.equal(state.metrics, retainedMetrics);
assert.equal(gaugeMap(view).project_count.value, 766);

for (const liveFile of [
  "index.html",
  "scripts/app.js",
  "scripts/plugins/gauges.js",
  "scripts/plugins/project-filters.js",
  "scripts/plugins/projects.js",
]) {
  const text = await readFile(new URL(liveFile, v7Url), "utf8");
  assert.equal(text.includes("canonical-project-controls"), false, `${liveFile} imports isolated controls`);
}

console.log("V7.2 canonical project controls: PASS (gauges, lifecycle filters and search remain isolated)");

Check V7 2 Project Model

A JavaScript module in the tests folder of GlobalGrid2050 that tests projects plugin, solar, the Renewable Energy Planning Database (REPD) register and battery storage (BESS).

testglobalgrid2050 / uk_renewables_pipeline/202609051156/tests/check_v7_2_project_model.mjs · lines 1–234 of 234 · version 2026-09-05 11:56 · Not reached from any entry point (candidate for review) · pattern fetchImpl (shared by 2 files)

What it does
It tests projects plugin, solar, the REPD register and battery storage (BESS). Defines fetchImpl. Uses libraries node:assert/strict, node:fs/promises. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'renewables'): 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, the REPD register, battery storage (BESS).
Inputs & outputs
In: JSON file projects-plugin.v7.2.json; JSON file projects.json.
What it achieves
It is built from the fetch impl helper (`fetchImpl`). Its name says it checks project model. Defines `fetchImpl`. It reads `contracts/projects-plugin.v7.2.json`.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · uk_renewables_pipeline/202609051156/tests · JavaScript module
Uses
Canonical Projects (import), Project State (import), UK Renewables Pipeline — V7 Page (estate URL), node:assert/strict, node:fs/promises
Used by
none found
Produces
fetchImpl
Defines here
fetchImpl
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_renewables_pipeline/202609051156/tests/check_v7_2_project_model.mjs:1-234 · blob 1a72ce320a99e5cd03a072e0138d7220635e03c9 · 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 { readFile } from "node:fs/promises";

import {
  buildCanonicalProjectModel,
  CanonicalProjectError,
  canonicalProjectMetrics,
  isSameOriginRelativePath,
  loadCanonicalProjectModel,
  searchCanonicalProjects,
} from "../scripts/data/canonical-projects.js";
import {
  beginCanonicalProjectLoad,
  commitCanonicalProjectModel,
  createCanonicalProjectState,
  failCanonicalProjectLoad,
  resetCanonicalProjectFilters,
  setCanonicalProjectFilter,
} from "../scripts/core/project-state.js";

const v7Url = new URL("../", import.meta.url);
const contract = JSON.parse(await readFile(new URL("contracts/projects-plugin.v7.2.json", v7Url), "utf8"));
const payload = JSON.parse(await readFile(new URL("data/v7.2/projects.json", v7Url), "utf8"));
const model = buildCanonicalProjectModel(payload, contract);

assert.equal(model.version, "7.2");
assert.equal(model.source, "data/v7.2/projects.json");
assert.equal(model.projects.length, 766);
assert.equal(new Set(model.projects.map((project) => project.gg_development_id)).size, 718);
assert.deepEqual(model.metrics, {
  solar_mwp: 34073.49,
  bess_mw: 106338.18,
  project_count: 766,
  largest_project: {
    gg_project_id: "GG2050-REPD-12453",
    name: "Thorpe Marsh Power Station - Battery Energy Storage",
    technology: "bess",
    capacity_mw: 1450,
    capacity_unit: "MW",
  },
});
assert.equal(model.projects[0].gg_project_id, "GG2050-REPD-12453");
assert.equal(Object.isFrozen(model.projects), true);
assert.equal(Object.isFrozen(model.projects[0]), true);
assert.equal(Object.isFrozen(model.projects[0].relationships), true);

const byRef = new Map(model.projects.map((project) => [project.repd_ref, project]));
assert.equal(byRef.get("13599").technology_label, "Solar");
assert.equal(byRef.get("13599").capacity_unit, "MWp");
assert.equal(byRef.get("13600").technology_label, "Battery Storage");
assert.equal(byRef.get("13600").capacity_unit, "MW");
assert.equal(byRef.get("11034").lifecycle_view, "CURRENT");
assert.equal(byRef.get("6502").lifecycle_view, "CURRENT");
assert.equal(byRef.get("12453").lifecycle_view, "REVIEW");
assert.equal(byRef.get("20966").technology, "bess");

const searchFields = contract.interface.search_fields;
assert.deepEqual(searchCanonicalProjects(model.projects, "13599", searchFields).map((project) => project.repd_ref), ["13599"]);
assert.deepEqual(searchCanonicalProjects(model.projects, "GG2050-REPD-13599", searchFields).map((project) => project.repd_ref), ["13599"]);
assert.deepEqual(searchCanonicalProjects(model.projects, "GG2050-DEV-E13842D4D80DEC", searchFields).map((project) => project.repd_ref).sort(), ["13599", "13600"]);
assert.deepEqual(searchCanonicalProjects(model.projects, "EN010151", searchFields).map((project) => project.repd_ref).sort(), ["13599", "13600"]);
assert.deepEqual(searchCanonicalProjects(model.projects, "Beacon Fen", searchFields).map((project) => project.repd_ref).sort(), ["13599", "13600"]);

assert.equal(isSameOriginRelativePath("data/v7.2/projects.json"), true);
assert.equal(isSameOriginRelativePath("../dist/projects.json"), false);
assert.equal(isSameOriginRelativePath("https://example.com/projects.json"), false);
assert.equal(isSameOriginRelativePath("//example.com/projects.json"), false);

const requested = [];
const fetchImpl = async (path, options) => {
  requested.push({ path, options });
  const value = path === "contracts/projects-plugin.v7.2.json" ? contract : payload;
  return { ok: true, status: 200, async json() { return structuredClone(value); } };
};
const loaded = await loadCanonicalProjectModel({ fetchImpl });
assert.equal(loaded.projects.length, 766);
assert.deepEqual(requested.map((request) => request.path), [
  "contracts/projects-plugin.v7.2.json",
  "data/v7.2/projects.json",
]);
assert.equal(requested.every((request) => request.options.credentials === "same-origin"), true);
assert.equal(requested.every((request) => request.options.cache === "no-store"), true);

const browserBase = "https://globalgrid2050.com/uk_renewables_pipeline/v7/";
let redirectFetches = 0;
await assert.rejects(
  loadCanonicalProjectModel({
    baseUrl: browserBase,
    fetchImpl: async (path) => {
      redirectFetches += 1;
      if (redirectFetches === 1) {
        return {
          ok: true,
          status: 200,
          url: `${browserBase}${path}`,
          async json() { return structuredClone(contract); },
        };
      }
      return {
        ok: true,
        status: 200,
        url: "https://assets.publishing.service.gov.uk/projects.json",
        async json() { return structuredClone(payload); },
      };
    },
  }),
  (error) => error instanceof CanonicalProjectError && error.code === "SOURCE_ORIGIN",
);
assert.equal(redirectFetches, 2);

const externalContract = structuredClone(contract);
externalContract.release_state.target_project_source = "https://assets.publishing.service.gov.uk/projects.json";
let externalFetches = 0;
await assert.rejects(
  loadCanonicalProjectModel({
    fetchImpl: async () => {
      externalFetches += 1;
      return { ok: true, status: 200, async json() { return externalContract; } };
    },
  }),
  /not a safe same-origin relative path/,
);
assert.equal(externalFetches, 1);

await assert.rejects(
  loadCanonicalProjectModel({ fetchImpl: async () => { throw new Error("offline"); } }),
  (error) => error instanceof CanonicalProjectError && error.code === "NETWORK",
);
await assert.rejects(
  loadCanonicalProjectModel({ fetchImpl: async () => ({ ok: false, status: 503 }) }),
  (error) => error instanceof CanonicalProjectError && error.code === "HTTP",
);
await assert.rejects(
  loadCanonicalProjectModel({ fetchImpl: async () => ({ ok: true, status: 200, async json() { throw new SyntaxError("bad JSON"); } }) }),
  (error) => error instanceof CanonicalProjectError && error.code === "JSON",
);

const duplicatePayload = structuredClone(payload);
duplicatePayload.projects[1].gg_project_id = duplicatePayload.projects[0].gg_project_id;
await assert.rejects(async () => buildCanonicalProjectModel(duplicatePayload, contract), /invalid project ID|duplicate GlobalGrid/);
const windPayload = structuredClone(payload);
windPayload.projects[0].technology = "wind";
await assert.rejects(async () => buildCanonicalProjectModel(windPayload, contract), /out-of-scope technology/);
const newsPollutedPayload = structuredClone(payload);
newsPollutedPayload.projects[0].headline = "Unverified headline";
await assert.rejects(async () => buildCanonicalProjectModel(newsPollutedPayload, contract), /news-derived fact/);
const shortPayload = structuredClone(payload);
shortPayload.projects.pop();
await assert.rejects(async () => buildCanonicalProjectModel(shortPayload, contract), /project count mismatch|solar count mismatch|BESS count mismatch/);
const wrongSchemaPayload = structuredClone(payload);
wrongSchemaPayload.schema = "wrong.schema";
await assert.rejects(
  async () => buildCanonicalProjectModel(wrongSchemaPayload, contract),
  (error) => error instanceof CanonicalProjectError && error.code === "SCHEMA",
);
const thresholdPayload = structuredClone(payload);
thresholdPayload.projects.find((project) => project.technology === "solar").capacity_mw = 49;
await assert.rejects(async () => buildCanonicalProjectModel(thresholdPayload, contract), /exclusive capacity threshold/);
const duplicateRefPayload = structuredClone(payload);
duplicateRefPayload.projects[1].repd_ref = duplicateRefPayload.projects[0].repd_ref;
duplicateRefPayload.projects[1].gg_project_id = duplicateRefPayload.projects[0].gg_project_id;
duplicateRefPayload.projects[1].development_repd_refs.push(duplicateRefPayload.projects[0].repd_ref);
await assert.rejects(async () => buildCanonicalProjectModel(duplicateRefPayload, contract), /duplicate GlobalGrid project ID|duplicate REPD Ref/);

const state = createCanonicalProjectState();
assert.equal(state.status, "idle");
beginCanonicalProjectLoad(state);
assert.equal(state.status, "loading");
commitCanonicalProjectModel(state, model);
assert.equal(state.status, "ready");
assert.equal(state.all.length, 766);
assert.equal(state.filtered.length, 766);
assert.equal(state.metrics.project_count, 766);
assert.equal(state.filterOptions.officialStatuses.includes("Appeal Lodged"), true);

setCanonicalProjectFilter(state, "technology", "solar");
assert.equal(state.filtered.length, 384);
assert.deepEqual(state.metrics, {
  solar_mwp: 34073.49,
  bess_mw: 0,
  project_count: 384,
  largest_project: {
    gg_project_id: "GG2050-REPD-12588",
    name: "Botley West, Botley - Botley West Solar Project",
    technology: "solar",
    capacity_mw: 840,
    capacity_unit: "MWp",
  },
});
setCanonicalProjectFilter(state, "technology", "bess");
setCanonicalProjectFilter(state, "query", "13599");
assert.equal(state.filtered.length, 0);
resetCanonicalProjectFilters(state);
setCanonicalProjectFilter(state, "technology", "all");
setCanonicalProjectFilter(state, "lifecycleView", "DISPUTED");
assert.equal(state.filtered.length, 3);
setCanonicalProjectFilter(state, "lifecycleView", "HISTORICAL");
assert.equal(state.filtered.length, 63);
setCanonicalProjectFilter(state, "lifecycleView", "REVIEW");
assert.equal(state.filtered.length, 30);
resetCanonicalProjectFilters(state);
setCanonicalProjectFilter(state, "query", "13599");
assert.deepEqual(state.filtered.map((project) => project.repd_ref), ["13599"]);
setCanonicalProjectFilter(state, "officialStatus", "No such status");
assert.equal(state.filtered.length, 0);
assert.deepEqual(canonicalProjectMetrics(state.filtered), {
  solar_mwp: 0,
  bess_mw: 0,
  project_count: 0,
  largest_project: null,
});

resetCanonicalProjectFilters(state);
const retainedProjects = state.all;
const retainedMetrics = state.metrics;
beginCanonicalProjectLoad(state);
assert.equal(state.status, "refreshing");
failCanonicalProjectLoad(state, new Error("refresh unavailable"));
assert.equal(state.status, "stale");
assert.equal(state.error, "refresh unavailable");
assert.equal(state.all, retainedProjects);
assert.equal(state.metrics, retainedMetrics);

const emptyState = createCanonicalProjectState();
beginCanonicalProjectLoad(emptyState);
failCanonicalProjectLoad(emptyState, "first load failed");
assert.equal(emptyState.status, "error");
assert.equal(emptyState.all.length, 0);
assert.throws(() => setCanonicalProjectFilter(state, "unknown", "x"), /unknown filter/);
const filtersBeforeInvalid = state.filters;
assert.throws(() => setCanonicalProjectFilter(state, "lifecycleView", "NOT_A_VIEW"), /invalid lifecycle view/);
assert.equal(state.filters, filtersBeforeInvalid);

console.log("V7.2 canonical project adapter/state: PASS (766 projects, isolated from live V7.1)");