GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / pipelinenews / discovery/tests

Compile V8 Fast and 2 more files

A JavaScript module in the index folder of PipelineNews that reads major project news, solar and battery storage (BESS), using SHA-256 from the GridAtlas repository.

700 lines of JavaScript from pipelinenews, in 3 files. Topic: Electricity markets and data pipelines. Section 1016 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. Datacentre Binder Test test · pipelinenews / discovery/tests/datacentre-binder.test.mjs lines 1–70
  2. Project Binder Test test · pipelinenews / discovery/tests/project-binder.test.mjs lines 1–111
  3. Compile V8 Fast storage · pipelinenews / index/202608270055-compile-v8-fast.mjs lines 1–519

Datacentre Binder Test

A test in the tests folder of PipelineNews that checks Datacentre Binder, using SHA-256. It is built from the feature step (`feature`) and the bind step (`bind`).

testpipelinenews / discovery/tests/datacentre-binder.test.mjs · lines 1–70 of 70 · Entry point · pattern feature (shared by 12 files)

What it does
It tests its inputs. Defines feature, bind. Uses libraries node:test, node:assert/strict, node:fs, node:crypto. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'datacentre'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Downstream impact
Used directly by 1 file: PipelineNews BBC RSS Discovery Workflow (pipelinenews).
What it achieves
Tests `DATA_CENTRES` topic binds to released GridAtlas data-centre register site ids.
Why it matters
Run by PipelineNews BBC RSS Discovery Workflow.
Application
pipelinenews · discovery/tests · test
Uses
Datacentre Binder (import), node:test, node:assert/strict, node:fs, node:crypto
Used by
run by PipelineNews BBC RSS Discovery Workflow (workflow run)
Produces
feature, bind
Defines here
feature, bind
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 discovery/tests/datacentre-binder.test.mjs:1-70 · blob f6c13bfdc630e783d450bef428ca42de7f8c4ae1 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
// Tests: DATA_CENTRES topic binds to released GridAtlas data-centre register site ids.
// run: node --test discovery/tests/datacentre-binder.test.mjs
// Optional: PN_DC_REGISTER=<path to gridatlas data/uk_datacentre_pipeline_202610312133.geojson>
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {existsSync, readFileSync} from 'node:fs';
import {createHash} from 'node:crypto';
import {verifyRegisterBytes, buildSites, bindDataCentreItem, DC_REGISTER_PIN} from '../datacentre-binder.mjs';

// Features copied (fields trimmed) from the released register 202610312133.
const feature = (id, name, operator, status, precision, coordinates, notes = []) => ({type: 'Feature', id,
  geometry: coordinates ? {type: 'Point', coordinates} : null,
  properties: {id, name, operator, status, aliases: [], notes, location: {precision, local_authority: null},
    it_load_mw: {value: null}, grid_connection_mw: {value: null}, unclassified_mw: {value: null}, evidence_urls: []}});
const fixture = {type: 'FeatureCollection', features: [
  feature('dcuk-040ed031c3acf5bd', 'Cobalt Park Data Centres', 'Cobalt Park Data Centres; Nscale (GPU deployment); Stargate UK', 'announced', 'settlement', [-1.51, 55.02], ['place: Cobalt Park, Wallsend, North Tyneside']),
  feature('dcuk-c965f50f64d1cc7b', 'Wester Hermiston Data Centre Campus', null, 'announced', 'settlement', [-3.3, 55.92], ['place: Wester Hermiston, Edinburgh']),
  feature('dcuk-fbd3c5ebf03f1306', 'Virtus London8', 'Virtus', 'operational', 'exact_site', [-0.3, 51.5]),
  feature('dcuk-b3138b4825480353', 'Ark Data Centres', 'Ark Data Centres', 'operational', 'exact_site', [-0.8, 51.3]),
  feature('dcuk-0000000000000001', 'Ark Data Centres', 'Ark Data Centres', 'operational', 'exact_site', [-1.8, 51.5]),
  feature('dcuk-0000000000000000', 'Test Nowhere Data Centre', 'Example', 'in_planning', 'unknown', null),
]};
const bytes = Buffer.from(JSON.stringify(fixture));
const pin = {...DC_REGISTER_PIN, sha256: createHash('sha256').update(bytes).digest('hex'), sites: 6};
const register = buildSites(verifyRegisterBytes(bytes, pin));
const bind = (headline, extra = {}) => bindDataCentreItem({headline, ...extra}, register);

test('the register is refused unless its digest and site count match the pin', () => {
  assert.throws(() => verifyRegisterBytes(bytes), /does not match pin/);
  assert.throws(() => verifyRegisterBytes(bytes, {...pin, sites: 226}), /pin says 226/);
});

test('a named site in a data-centre headline is queued for review as its dc_site_id, never a REPD ref', () => {
  const r = bind('Plans for Wester Hermiston data centre campus go to councillors');
  assert.equal(r.outcome, 'SITE_NAME_MATCH_REVIEW');
  assert.equal(r.review_candidate.dc_site_id, 'dcuk-c965f50f64d1cc7b');
  assert.equal(r.category, 'DATA_CENTRE');
  assert.equal(r.publish, false, 'NL-019: a named site is queued for review, not published');
  assert.equal(r.dc_site_id, null);
  assert.equal(r.repd_ref, null);
  assert.equal(r.map_status, 'APPROXIMATE');
  assert.equal(bind('Virtus London8 data centre expansion approved').map_status, 'EXACT_SITE');
});

test('only the existing sector rule admits an item to the topic', () => {
  assert.equal(bind('Cobalt Park office block sold').outcome, 'NOT_DATA_CENTRE_TOPIC');
  assert.equal(bind('Cobalt Park data centres to host Stargate UK GPUs').review_candidate.dc_site_id, 'dcuk-040ed031c3acf5bd');
});

test('an operator alone (Ark runs 4 listed sites) or a place alone is not a site identity', () => {
  const op = bind('Ark Data Centres plans new data centre');
  assert.equal(op.outcome, 'OPERATOR_ONLY');
  assert.equal(op.dc_site_id, null);
  assert.equal(bind('More data centres approved for west London').outcome, 'TOPIC_ONLY');
});

test('missing geometry stays NO MAP with no coordinates invented', () => {
  const r = bind('Test Nowhere Data Centre approved');
  assert.equal(r.outcome, 'SITE_NAME_MATCH_REVIEW');
  assert.equal(r.map_status, 'NO_MAP');
  assert.equal(r.latitude, null);
  assert.equal(r.longitude, null);
});

test('the released register, when present, matches the pin (226 sites)', {skip: !existsSync(process.env.PN_DC_REGISTER ?? '/nonexistent')}, () => {
  const released = buildSites(verifyRegisterBytes(readFileSync(process.env.PN_DC_REGISTER)));
  assert.equal(released.sites.length, 226);
  assert.equal(released.sites.filter(site => site.map_status === 'NO_MAP').length, 1);
  assert.equal(bindDataCentreItem({headline: 'Wester Hermiston data centre campus plans lodged'}, released).review_candidate.dc_site_id, 'dcuk-c965f50f64d1cc7b');
});

Project Binder Test

A test in the tests folder of PipelineNews that checks Project Binder. It is built from the bind step (`bind`).

testpipelinenews / discovery/tests/project-binder.test.mjs · lines 1–111 of 111 · Entry point

What it does
It tests solar, battery storage (BESS) and the REPD register. Defines P, bind. Uses libraries node:test, node:assert/strict.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'pipelinenews'): 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, battery storage (BESS), the REPD register.
Downstream impact
Used directly by 1 file: PipelineNews BBC RSS Discovery Workflow (pipelinenews).
What it achieves
Tests register-driven project binder. Names and refs are real Renewable Energy Planning Database (REPD) Q3 2026 entries. Its code works with 49.2 MW, 1.2 GW and 20 MW.
Why it matters
Run by PipelineNews BBC RSS Discovery Workflow.
Application
pipelinenews · discovery/tests · test
Uses
Project Binder (import), node:test, node:assert/strict
Used by
run by PipelineNews BBC RSS Discovery Workflow (workflow run)
Produces
P, bind
Defines here
P, bind
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 discovery/tests/project-binder.test.mjs:1-111 · blob b7617585064d200a5caca73417e4dbd2083034e2 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
// Tests: register-driven project binder. Names and refs are real REPD Q3 2026 entries.
// run: node --test discovery/tests/project-binder.test.mjs
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {buildGazetteer, bindItem, nameForms, reportedMw} from '../project-binder.mjs';

const P = (repd_ref, name, technology, county, operator, capacity_mw, status = 'Awaiting Construction') => ({repd_ref, name, technology, county, operator, capacity_mw, status});
const projects = [
  P('1621', 'Solar Farm', 'solar', 'Dorset', 'Unknown', 5, 'Abandoned'),
  P('5482', 'York Solar Farm', 'solar', 'North Yorkshire', 'Hive Energy', 30),
  P('14550', 'Dean Moor Solar Farm & Battery Storage', 'solar', 'Cumbria', 'FVS Dean Moor Ltd', 150),
  P('13599', 'Beacon Fen Energy Park', 'solar', 'Lincolnshire', 'Low Carbon Limited', 400),
  P('13600', 'Beacon Fen Energy Park', 'bess', 'Lincolnshire', 'Low Carbon Limited', 600),
  P('5967', 'Kells Solar Farm', 'solar', 'Co. Derry / Londonderry', 'Elgin Energy EsCo', 25, 'Revised'),
  P('6012', 'Kells Solar Farm', 'solar', 'Co. Antrim', 'Elgin Energy EsCo', 50, 'Application Submitted'),
  P('11974', 'Hessay Solar Farm', 'solar', 'North Yorkshire', 'Recurrent Energy', 40),
  P('11034', 'Coalburn Energy - Battery Storage', 'bess', 'Strathclyde', 'Alcemi Storage Development Limited', 500, 'Operational'),
  P('12206', 'Coalburn II Energy Storage Facility - Battery Storage Facility', 'bess', 'Lanarkshire', 'Alcemi Storage Development Limited', 1000, 'Under Construction'),
  P('8100', 'Camblesforth Solar Farm', 'solar', 'North Yorkshire', 'Enray Power', 49.9),
  P('21493', 'Camblesforth Solar Farm', 'bess', 'North Yorkshire', 'Enray Power', 10),
  P('9050', 'Bypass Solar Farm', 'solar', 'Somerset', 'Somebody', 5),
  P('3000', 'Unknown Capacity Solar Park', 'solar', 'Kent', 'Somebody', null),
];
const g = buildGazetteer(projects);
const bind = (headline, extra = {}) => bindItem({headline, ...extra}, g);

test('a project literally named "Solar Farm" is never an identity', () => {
  assert.equal(bind('Solar farm plan rejected by council').outcome, 'NO_MATCH');
  assert.equal(nameForms('Solar Farm').length, 1);
});

test('place names are not projects: "near York village" stays unmatched, "bypass" too', () => {
  assert.notEqual(bind('Solar farm planned for site near York village').outcome, 'NAME_MATCH_REVIEW');
  assert.notEqual(bind('Plans revealed for major new solar farm near Burton Joyce bypass').outcome, 'NAME_MATCH_REVIEW');
});

test('a full or stripped register name in the headline is queued for review, not published', () => {
  const r = bind('Dean Moor Solar Farm development consent decision announced');
  assert.equal(r.outcome, 'NAME_MATCH_REVIEW');
  assert.equal(r.review_candidate.repd_ref, '14550');
  assert.equal(r.review_candidate.gg_project_id, 'GG2050-REPD-14550');
  // NL-019: a name match is a review item, never a published binding.
  assert.equal(r.publish, false);
  assert.equal(r.repd_ref, null);
  assert.equal(r.gg_project_id, null);
  assert.equal(bind('Triple Point acquires 49.2MW Hessay Solar project from Recurrent Energy').review_candidate.repd_ref, '11974');
});

test('the most specific name wins: "Coalburn II" is not "Coalburn"', () => {
  assert.equal(bind('Meadow Partners acquires ground lease for Coalburn II Battery Energy Storage System').review_candidate.repd_ref, '12206');
  assert.equal(bind('Zenobe closes financing for 200-MW Coalburn BESS project in Scotland').review_candidate.repd_ref, '11034');
});

test('co-located components: technology cue picks the component, otherwise generation is primary and storage related', () => {
  const plain = bind('Beacon Fen Energy Park development consent decision announced');
  assert.equal(plain.review_candidate.repd_ref, '13599');
  assert.match(plain.reason, /DEFAULT_GENERATING_COMPONENT/);
  assert.deepEqual(plain.related_components.map(c => c.repd_ref), ['13600']);
  assert.equal(bind('Beacon Fen Energy Park battery storage approved').review_candidate.repd_ref, '13600');
});

test('two developments with one name abstain unless county corroborates', () => {
  const r = bind('Kells solar farm plan setback after archaeological find');
  assert.equal(r.outcome, 'AMBIGUOUS');
  assert.deepEqual(r.candidates.map(c => c.repd_ref), ['5967', '6012']);
  assert.equal(bind('Kells solar farm plan setback', {snippet: 'The site in Co. Antrim ...'}).review_candidate.repd_ref, '6012');
});

test('a name only in the snippet is related context, never a primary binding', () => {
  const r = bind('Lincolnshire farmer says turning to solar is only way to survive', {snippet: 'The Beacon Fen Energy Park in nearby Heckington was the latest to be approved.'});
  assert.equal(r.outcome, 'CONTEXT_ONLY');
  assert.equal(r.repd_ref, null);
});

test('foreign conflict rejects unless the item also carries a UK signal', () => {
  assert.equal(bind('Hessay Solar project lessons for United States developers').outcome, 'REJECT');
  assert.equal(bind('UK Hessay Solar project lessons for United States developers').outcome, 'NAME_MATCH_REVIEW');
});

test('reported MW is checked against the register; blank register capacity is unknown, not zero', () => {
  assert.deepEqual(reportedMw('new 1,900MW scheme and 25 MWh battery, 1.2GW total'), [1900, 1200]);
  assert.equal(bind('Government approves new 1,900MW Camblesforth solar farm').capacity_check.status, 'CONFLICT');
  assert.equal(bind('Triple Point acquires 49.2MW Hessay Solar project').capacity_check.status, 'CONSISTENT_DC_AC_BAND');
  const unknown = bind('Unknown Capacity Solar Park reaches 20MW milestone');
  assert.equal(unknown.capacity_check.status, 'UNKNOWN');
  assert.equal(unknown.capacity_check.register_mw, null);
});

test('a previous site name kept as an alias after a register rename still binds', () => {
  const renamed = [P('12820', 'Camsiscan Farm, Craigie - Kilmarnock South Battery Energy Storage System', 'bess', 'Ayrshire', 'Noriker Power Limited / CIP', 49.9)];
  const before = buildGazetteer(renamed);
  const after = buildGazetteer(renamed, {extraAliases: new Map([['12820', ['Camsiscan Farm, Craigie - Battery Energy Storage System']]])});
  const item = {headline: 'Camsiscan Farm Craigie battery energy storage system approved'};
  assert.equal(bindItem(item, after).review_candidate.repd_ref, '12820');
  // The four Q2->Q3 2026 site renames all keep their leading site name, so the first
  // name segment ("Camsiscan Farm") binds even without the alias.
  assert.equal(bindItem(item, before).review_candidate.repd_ref, '12820');
  const exotic = buildGazetteer([P('1', 'Brand New Name Solar Farm', 'solar', 'Kent', 'X', 10)], {extraAliases: new Map([['1', ['Old Hilltop Solar Farm']]])});
  assert.equal(bindItem({headline: 'Old Hilltop Solar Farm approved'}, exotic).review_candidate.repd_ref, '1');
});

test('no outcome of the binder publishes a REPD ref (NL-019 review-queue rule)', () => {
  const headlines = ['Dean Moor Solar Farm development consent decision announced', 'Kells solar farm plan setback',
    'Beacon Fen Energy Park battery storage approved', 'Solar farm plan rejected by council', 'UK Hessay Solar project lessons for United States developers'];
  for (const headline of headlines) {
    const r = bind(headline, {snippet: 'The site in Co. Antrim, Cumbria, Lincolnshire ...'});
    assert.equal(r.publish, false);
    assert.equal(r.repd_ref, null);
    assert.equal(r.gg_project_id, null);
  }
});

Compile V8 Fast

A JavaScript module in the index folder of PipelineNews that reads major project news, solar and battery storage (BESS), using SHA-256 from the GridAtlas repository.

storagepipelinenews / index/202608270055-compile-v8-fast.mjs · lines 1–519 of 619 · version 2026-08-27 00:55 · Not reached from any entry point (candidate for review) · pattern stableArticleId (shared by 2 files)

What it does
It loads major project news, solar and battery storage (BESS). Defines 21 functions or classes, including absolute, sha256, jsonBytes, readPinned, replaceExactly. Uses libraries node:assert/strict, node:crypto, node:fs, node:fs/promises, node:path. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'pipelinenews'): 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, battery storage (BESS).
Inputs & outputs
In: data source: gridatlas data; JSON file 202608261927-build-manifest-v9-1.json; JSON file 202608261927-release-v9-1.json; JSON file 202608261721-release-v9-6-2.json; JSON file 202608261927-major-project-news-v9-5-1.json; command-line arguments.
What it achieves
It reads pinned (`readPinned`), replaces exactly (`replaceExactly`) and searches text (`searchText`). Its name says it compiles fast. Defines `absolute`, `sha256`, `jsonBytes` and 17 more.
Why it matters
No other file in the estate was found to import it.
Application
pipelinenews · index · JavaScript module
Uses
UK Renewables Pipeline — V9 6 1 Page (estate URL), UK Renewables Pipeline — V9 6 Page (estate URL), UK Renewables Pipeline — V9 5 1 Page (estate URL), UK Renewables Pipeline — V9 5 Page (estate URL), UK Renewables Pipeline — V9 4 Page (estate URL), UK Renewables Pipeline — V9 Page (estate URL), UK Renewables Pipeline — V8 Page (estate URL), UK Renewables Pipeline — V7 Page (estate URL), and 5 more, node:assert/strict, node:crypto, node:fs, node:fs/promises, node:path, node:url
Used by
none found
Produces
absolute, sha256, jsonBytes, readPinned, replaceExactly, normalise, searchText, makeDictionary, projectCartridge, loadProjects, validateProjects, compileProjects
Defines here
absolute, sha256, jsonBytes, readPinned, replaceExactly, normalise, searchText, makeDictionary, projectCartridge, loadProjects, validateProjects, compileProjects, canonicalItem, compileSignals, stableArticleId, compileNews, rewriteHtml, build
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 index/202608270055-compile-v8-fast.mjs:1-519 · blob 82db0db0f9df5eb3351666b52e1982c0c03d4b5a · 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: unreached_review
import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { constants } from "node:fs";
import { access, mkdir, readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";

const GENERATION = "202608270055";
const BASE_GENERATION = "202608261927";
const COMPILER_FILE = `${GENERATION}-compile-v8-fast.mjs`;
const COMPILER_METHOD = "pipelinenews-v8-fast-dictionary-index-lazy-detail-v1";
const REPOSITORY_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const PROJECT_SCHEMA = "pipelinenews.v8.fast-project-index.v1";
const SEARCH_SCHEMA = "pipelinenews.v8.fast-search-index.v1";
const NEWS_SCHEMA = "pipelinenews.v8.fast-news-index.v1";

const INPUTS = Object.freeze({
  template: "ui/templates/202608261927-shell-v9-6-2.html",
  runtime: "ui/javascript/202608270055-v8-fast-runtime.js",
  overrideStyle: "ui/styles/202608270055-v8-fast-overrides.css",
  styles: [
    "ui/styles/202608261740-v7-foundation.css",
    "ui/styles/202608261614-mobile.css",
    "ui/styles/202608261927-v9-3.css",
    "ui/styles/202608261927-v9-4.css",
    "ui/styles/202608261927-v9-5-1.css",
    "ui/styles/202608261927-v9-6-1.css",
  ],
  sourceManifest: "data/manifests/202608261927-build-manifest-v9-1.json",
  releaseContract: "data/contracts/202608261927-release-v9-1.json",
  trustedContract: "data/contracts/202608261721-release-v9-6-2.json",
  news: "data/news/202608261927-major-project-news-v9-5-1.json",
  newsRegions: "ui/javascript/202608261742-news-regions.js",
  utils: "ui/javascript/202608261630-utils.js",
  vendor: "releases/vendor/202608261927-chart-umd.min.js",
});

const PINNED_SHA256 = Object.freeze({
  "ui/templates/202608261927-shell-v9-6-2.html": "06382e57a58e460defcdd3c460ad01b93aa4c4578065348afa846b446e6d34ae",
  "ui/javascript/202608270055-v8-fast-runtime.js": "70d49f2a40dbfa87b0a3b1bd3fe12e186551f64b3fc33c0066ba7561bc9d6534",
  "ui/styles/202608270055-v8-fast-overrides.css": "9ad5d52f9c898afe4ada9b9b4ae6e73c36f073d533ce1e9ed2e5793f07ae80b5",
  "ui/styles/202608261740-v7-foundation.css": "036dbfe43ef1ffb2c55ba277d49dec57ab7c7be976289226a5d568e1f1be319d",
  "ui/styles/202608261614-mobile.css": "9855b9c11255a85f477873d07cca45b057aedcdc8a6cc4aab2d29a0ffaac9b85",
  "ui/styles/202608261927-v9-3.css": "219782d5f3fba11b8418a5b46075a8b1b918eed272f6bc2360f6b1060c1f2e9b",
  "ui/styles/202608261927-v9-4.css": "39f7d0fd3ff42e82407c1f5129444e6cc308ef5c0ec551d43c7396ac53310d17",
  "ui/styles/202608261927-v9-5-1.css": "79ff5b1db85ae82a381fbad061c0122e7151bb9c9c7ba80c549051761f0bfae3",
  "ui/styles/202608261927-v9-6-1.css": "851b0827ca2aa0950438c98ae3cf6cc7dce33667d37458122ea38bb2c6da2f81",
  "data/manifests/202608261927-build-manifest-v9-1.json": "67976a1bbcaf383ed7121b13060db3b864db9ce33dfc721a88b59c8ca8b8e06c",
  "data/contracts/202608261927-release-v9-1.json": "bc21070f44aae1d32da333e4954816acd907aa8c9fa9cb639c64d651f7fd4259",
  "data/contracts/202608261721-release-v9-6-2.json": "661bb4f226ac3c75811f9e1d36546602f401491a5c21e1ddebccda170da92ece",
  "data/news/202608261927-major-project-news-v9-5-1.json": "cea104c3e9cfc07971680afdf5f64073e1d4825b63bfaf4e969266df8386ebbd",
  "ui/javascript/202608261742-news-regions.js": "673126663b69f67c73dfed4f6393e56e7779514e612559f0b6aad88a4354037f",
  "ui/javascript/202608261630-utils.js": "bec300e2720e0793bc08434e91c0ea0dd8c3d8e36e79b97172e4d5270f01eda0",
  "releases/vendor/202608261927-chart-umd.min.js": "48444a82d4edcb5bec0f1965faacdde18d9c17db3063d042abada2f705c9f54a",
});

const PROJECT_FIELDS = Object.freeze([
  "repd_ref",
  "gg_project_id",
  "name",
  "technology",
  "status",
  "capacity_mw",
  "county",
  "region",
  "operator",
  "repd_record_updated",
  "geometry_status",
  "latitude",
  "longitude",
]);
const DICTIONARY_FIELDS = Object.freeze(["technology", "status", "county", "region", "operator", "geometry_status"]);
const NEWS_FIELDS = Object.freeze([
  "gg_article_id",
  "repd_ref",
  "gg_project_id",
  "project",
  "technology",
  "capacity_mw",
  "operator",
  "county",
  "country",
  "event",
  "headline",
  "published",
  "source",
  "url",
  "confidence",
  "canonical_relevant",
  "role",
  "eligible_for_news_signal",
  "regional_classification",
  "regional_technology",
  "regional_evidence",
]);

function absolute(relativePath) {
  const resolved = path.resolve(REPOSITORY_ROOT, relativePath);
  assert.ok(resolved.startsWith(`${REPOSITORY_ROOT}${path.sep}`), `path escapes repository: ${relativePath}`);
  return resolved;
}

function sha256(bytes) {
  return createHash("sha256").update(bytes).digest("hex");
}

function jsonBytes(value, pretty = false) {
  return Buffer.from(`${JSON.stringify(value, null, pretty ? 2 : 0)}\n`);
}

async function readPinned(relativePath, encoding = null) {
  const bytes = await readFile(absolute(relativePath));
  assert.equal(sha256(bytes), PINNED_SHA256[relativePath], `input hash changed: ${relativePath}`);
  return encoding ? bytes.toString(encoding) : bytes;
}

function replaceExactly(source, from, to, expectedCount = 1) {
  const actualCount = source.split(from).length - 1;
  assert.equal(actualCount, expectedCount, `replacement count for ${JSON.stringify(from)}`);
  return source.split(from).join(to);
}

function normalise(value) {
  return String(value ?? "")
    .normalize("NFKD")
    .replace(/[\u0300-\u036f]/g, "")
    .toLocaleLowerCase("en-GB")
    .replace(/&/g, " and ")
    .replace(/[^a-z0-9.-]+/g, " ")
    .replace(/\s+/g, " ")
    .trim();
}

function searchText(project) {
  const relationshipRefs = [
    ...(Array.isArray(project.direct_related_repd_refs) ? project.direct_related_repd_refs : []),
    ...(Array.isArray(project.planning_sibling_repd_refs) ? project.planning_sibling_repd_refs : []),
    ...(Array.isArray(project.development_repd_refs) ? project.development_repd_refs : []),
  ];
  return normalise([
    project.name,
    project.operator,
    project.repd_ref,
    project.gg_project_id,
    project.gg_development_id,
    project.repd_old_ref,
    project.repd_technology,
    project.technology,
    project.status,
    project.lifecycle,
    project.capacity_mw,
    project.county,
    project.region,
    project.country,
    project.planning_authority,
    project.planning_application_reference,
    project.repd_record_updated,
    project.geometry_status,
    relationshipRefs.join(" "),
  ].join(" "));
}

function makeDictionary(projects, field) {
  const values = [...new Set(projects.map((project) => project[field] ?? ""))].sort();
  return { values, indexes: new Map(values.map((value, index) => [value, index])) };
}

function projectCartridge(index) {
  return `data/projects/${BASE_GENERATION}-project-partition-v9-1-${String(index + 1).padStart(2, "0")}.json`;
}

async function loadProjects(sourceManifest, inputRecords) {
  assert.equal(sourceManifest.schema, "globalgrid2050.v9.project-spine-build.v9.1");
  assert.equal(sourceManifest.project_count, 7680);
  assert.equal(sourceManifest.source_record_count, 14657);
  assert.equal(sourceManifest.project_partitions.length, 16);
  const projects = [];
  const detailPartitions = [];
  for (let index = 0; index < sourceManifest.project_partitions.length; index += 1) {
    const declaration = sourceManifest.project_partitions[index];
    const relativePath = projectCartridge(index);
    const bytes = await readFile(absolute(relativePath));
    assert.equal(sha256(bytes), declaration.sha256, `project partition hash ${index + 1}`);
    const payload = JSON.parse(bytes);
    assert.equal(payload.schema, "globalgrid2050.v9.project-partition.v9.1");
    assert.equal(payload.record_count, declaration.record_count);
    assert.equal(payload.projects.length, declaration.record_count);
    projects.push(...payload.projects);
    detailPartitions.push({
      path: `../${relativePath}`,
      sha256: declaration.sha256,
      bytes: bytes.length,
      record_count: declaration.record_count,
      activation: "project-detail-or-export",
    });
    inputRecords.push({ path: relativePath, bytes: bytes.length, sha256: declaration.sha256 });
  }
  assert.equal(projects.length, 7680);
  return { projects, detailPartitions };
}

function validateProjects(projects, releaseContract, sourceManifest) {
  const technologies = new Set(["solar", "bess", "wind_onshore", "wind_offshore"]);
  const refs = new Set();
  const ids = new Set();
  const counts = { solar: 0, bess: 0, wind_onshore: 0, wind_offshore: 0 };
  let capacity = 0;
  let largest = 0;
  let geometryCount = 0;
  let previousCapacity = Infinity;
  for (const project of projects) {
    assert.ok(typeof project.repd_ref === "string" && project.repd_ref);
    assert.equal(project.gg_project_id, `GG2050-REPD-${project.repd_ref}`);
    assert.equal(project.identity_status, "REPD_BOUND");
    assert.equal(project.identity_confidence, "authoritative");
    assert.ok(technologies.has(project.technology));
    assert.ok(Number.isFinite(project.capacity_mw) && project.capacity_mw >= 1);
    assert.ok(!refs.has(project.repd_ref), `duplicate REPD Ref ${project.repd_ref}`);
    assert.ok(!ids.has(project.gg_project_id), `duplicate project ID ${project.gg_project_id}`);
    assert.ok(project.capacity_mw <= previousCapacity, "canonical project order is no longer capacity-descending");
    previousCapacity = project.capacity_mw;
    refs.add(project.repd_ref);
    ids.add(project.gg_project_id);
    counts[project.technology] += 1;
    capacity += project.capacity_mw;
    largest = Math.max(largest, project.capacity_mw);
    if (project.geometry_status === "valid") geometryCount += 1;
  }
  const actual = {
    project_count: projects.length,
    capacity_mw: Math.round((capacity + Number.EPSILON) * 100) / 100,
    largest_mw: largest,
    solar_count: counts.solar,
    bess_count: counts.bess,
    wind_onshore_count: counts.wind_onshore,
    wind_offshore_count: counts.wind_offshore,
  };
  assert.deepEqual(actual, releaseContract.expected);
  assert.equal(actual.project_count, sourceManifest.project_count);
  assert.equal(actual.capacity_mw, sourceManifest.capacity_mw);
  assert.equal(geometryCount, sourceManifest.geometry_count);
  return { ...actual, geometry_count: geometryCount, missing_geometry_count: projects.length - geometryCount };
}

function compileProjects(projects, cacheIdentity) {
  const compiled = {};
  const lookup = {};
  for (const field of DICTIONARY_FIELDS) {
    const dictionary = makeDictionary(projects, field);
    compiled[field] = dictionary.values;
    lookup[field] = dictionary.indexes;
  }
  const rows = projects.map((project) => [
    project.repd_ref,
    project.gg_project_id,
    project.name,
    lookup.technology.get(project.technology),
    lookup.status.get(project.status),
    project.capacity_mw,
    lookup.county.get(project.county ?? ""),
    lookup.region.get(project.region ?? ""),
    lookup.operator.get(project.operator ?? ""),
    project.repd_record_updated,
    lookup.geometry_status.get(project.geometry_status ?? ""),
    project.latitude,
    project.longitude,
  ]);
  return {
    schema: PROJECT_SCHEMA,
    generation: GENERATION,
    cache_identity: cacheIdentity,
    fields: PROJECT_FIELDS,
    dictionaries: compiled,
    rows,
  };
}

function canonicalItem(item) {
  return item
    && item.role === "PRIMARY_MATCH"
    && item.eligible_for_news_signal === true
    && String(item.repd_ref || "")
    && item.gg_project_id === `GG2050-REPD-${item.repd_ref}`;
}

function compileSignals(items) {
  const best = new Map();
  for (const item of items.filter(canonicalItem)) {
    const ref = String(item.repd_ref);
    const previous = best.get(ref);
    const candidateDate = Date.parse(String(item.published || "")) || 0;
    const previousDate = previous ? Date.parse(String(previous.published || "")) || 0 : 0;
    if (!previous || Number(item.confidence || 0) > Number(previous.confidence || 0)
      || (Number(item.confidence || 0) === Number(previous.confidence || 0) && candidateDate > previousDate)) {
      best.set(ref, item);
    }
  }
  return Object.fromEntries([...best].sort(([left], [right]) => left.localeCompare(right)).map(([ref, item]) => [
    ref,
    [String(item.event || "PROJECT UPDATE").toUpperCase(), Number(item.confidence || 0), item.published || "date unavailable"],
  ]));
}

function stableArticleId(item) {
  if (typeof item.gg_article_id === "string" && item.gg_article_id) return item.gg_article_id;
  assert.ok(typeof item.url === "string" && item.url, "news discovery row has no immutable URL");
  return `GG2050-NEWS-${sha256(Buffer.from(item.url)).slice(0, 16).toUpperCase()}`;
}

async function compileNews(news, cacheIdentity, trustedContract) {
  assert.equal(news.schema, "globalgrid2050.major-project-news.v9.5.1");
  assert.equal(news.release, "9.5.1");
  assert.equal(news.all_items.length, 133);
  assert.equal(news.canonical_items.length, 45);
  assert.equal(news.all_headline_count, 133);
  assert.equal(news.relevant_headline_count, 45);
  assert.equal(news.v9_4_baseline_headline_count, 125);
  assert.ok(news.canonical_items.every(canonicalItem));
  assert.equal(news.beacon_fen_contract?.repd_ref, "13599");
  assert.equal(news.beacon_fen_contract?.official_capacity_mw, 400);
  assert.equal(trustedContract.schema, "globalgrid2050.uk-renewables.release.v9.6.2");
  assert.equal(trustedContract.release, "9.6.2");
  assert.equal(trustedContract.expected.all_headline_count, news.all_headline_count);
  assert.equal(trustedContract.expected.uk_headline_count, news.relevant_headline_count);
  assert.equal(trustedContract.expected.beacon_fen_repd_ref, news.beacon_fen_contract.repd_ref);

  const module = await import(pathToFileURL(absolute(INPUTS.newsRegions)).href);
  const counts = { all: 133, uk: 45, international: 0, us: 0, europe: 0, other: 0 };
  const rows = news.all_items.map((item) => {
    const regional = module.classifyInternationalV9_6_2(item);
    if (regional) {
      counts.international += 1;
      if (regional.region === "US") counts.us += 1;
      else if (regional.region === "EUROPE") counts.europe += 1;
      else counts.other += 1;
    }
    return [
      stableArticleId(item),
      item.repd_ref || "",
      item.gg_project_id || "",
      item.canonical_project || item.project || "",
      item.canonical_technology || item.technology || "",
      item.canonical_capacity_mw ?? item.capacity_mw ?? null,
      item.operator || "",
      item.county || "",
      item.country || "",
      item.event || "PROJECT UPDATE",
      item.headline || "",
      item.published || "",
      item.source || "",
      item.url || "",
      Number(item.confidence || 0),
      item.canonical_relevant === true,
      item.role || "",
      item.eligible_for_news_signal === true,
      regional?.region || "",
      regional?.technology || "",
      regional?.evidence || "",
    ];
  });
  assert.equal(new Set(rows.map((row) => row[0])).size, rows.length, "compiled news IDs must be unique");
  const expectedCounts = {
    all: trustedContract.expected.all_headline_count,
    uk: trustedContract.expected.uk_headline_count,
    international: trustedContract.expected.international_headline_count,
    us: trustedContract.expected.us_headline_count,
    europe: trustedContract.expected.europe_headline_count,
    other: trustedContract.expected.international_other_headline_count,
  };
  assert.deepEqual(counts, expectedCounts);
  return {
    payload: { schema: NEWS_SCHEMA, generation: GENERATION, cache_identity: cacheIdentity, fields: NEWS_FIELDS, rows },
    counts,
    signals: compileSignals(news.canonical_items),
  };
}

function rewriteHtml(template) {
  const oldStyles = [
    "styles/v7.css?v=9.6.2",
    "styles/mobile.css?v=9.6.2",
    "styles/v9-3.css?v=9.6.2",
    "styles/v9-4.css?v=9.6.2",
    "styles/v9-5-1.css?v=9.6.2",
    "styles/v9-6-1.css?v=9.6.2",
  ];
  let source = template;
  source = replaceExactly(source, `<link rel="stylesheet" href="${oldStyles[0]}">`, `<link rel="stylesheet" href="styles/${GENERATION}-v8-fast.css">`);
  for (const oldStyle of oldStyles.slice(1)) source = replaceExactly(source, `\n  <link rel="stylesheet" href="${oldStyle}">`, "");
  source = replaceExactly(source, '\n  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>', "");
  source = replaceExactly(source, '\n  <script type="module" src="scripts/app-v9-6-2.js?v=9.6.2"></script>\n  <script type="module" src="scripts/plugins/capacity-presentation-v9-3.js?v=9.6.2"></script>', `\n  <script type="module" src="javascript/${GENERATION}-v8-fast-runtime.js"></script>`);
  source = source.replaceAll("V9.6.2", "V8 FAST CANDIDATE");
  source = replaceExactly(source, "V8 FAST CANDIDATE LIVE VALIDATED", "V8 FAST CANDIDATE · NOT DEPLOYED");
  source = replaceExactly(source, "V8 FAST CANDIDATE · UK + INTERNATIONAL NEWS · LIVE VALIDATED · 24 August 2026", "V8 FAST CANDIDATE · UK + INTERNATIONAL NEWS · BUILD VERIFIED · NOT DEPLOYED");
  const navigation = [
    ["../v9.6.1/", "https://globalgrid2050.com/uk_renewables_pipeline/v9.6.1/"],
    ["../v9.6/", "https://globalgrid2050.com/uk_renewables_pipeline/v9.6/"],
    ["../v9.5.1/", "https://globalgrid2050.com/uk_renewables_pipeline/v9.5.1/"],
    ["../v9.5/", "https://globalgrid2050.com/uk_renewables_pipeline/v9.5/"],
    ["../v9.4/", "https://globalgrid2050.com/uk_renewables_pipeline/v9.4/"],
    ["../v9/", "https://globalgrid2050.com/uk_renewables_pipeline/v9/"],
    ["../v8/", "https://globalgrid2050.com/uk_renewables_pipeline/v8/"],
    ["../v7/", "https://globalgrid2050.com/uk_renewables_pipeline/v7/"],
    ["../dashboard_v6_live.html", "https://globalgrid2050.com/uk_renewables_pipeline/dashboard_v6_live.html"],
    ["../dashboard_v5_live.html", "https://globalgrid2050.com/uk_renewables_pipeline/dashboard_v5_live.html"],
    ["../dashboard_v4_live.html", "https://globalgrid2050.com/uk_renewables_pipeline/dashboard_v4_live.html"],
    ["../dashboard_v3_live_2026-08-22.html", "https://globalgrid2050.com/uk_renewables_pipeline/dashboard_v3_live_2026-08-22.html"],
    ["../dashboard_v2_2026-08-22.html", "https://globalgrid2050.com/uk_renewables_pipeline/dashboard_v2_2026-08-22.html"],
    ["../dashboard.html", "https://globalgrid2050.com/uk_renewables_pipeline/dashboard.html"],
    ["../../index.html", "https://globalgrid2050.com/"],
    ["../../repd_grid_atlasv8/", "https://ventusltd.github.io/gridatlas/202608300453-atlas-v9/"],
  ];
  for (const [from, to] of navigation) source = replaceExactly(source, from, to);
  source = replaceExactly(source, "<body>", `<body data-fast-generation="${GENERATION}">`);
  source = replaceExactly(source, "Loading canonical release contract…", "Loading compact canonical project index…");
  return `${source.trimEnd()}\n`;
}

async function build() {
  assert.equal(path.basename(fileURLToPath(import.meta.url)), COMPILER_FILE);
  const sourceCommit = process.env.SOURCE_COMMIT;
  const runId = process.env.GITHUB_RUN_ID;
  assert.match(sourceCommit || "", /^[a-f0-9]{40}$/u, "SOURCE_COMMIT must be an exact 40-character Git SHA");
  assert.ok(runId, "GITHUB_RUN_ID is required");
  const compilerBytes = await readFile(fileURLToPath(import.meta.url));
  const compilerSha = sha256(compilerBytes);
  const inputRecords = [];

  const sourceManifestBytes = await readPinned(INPUTS.sourceManifest);
  const sourceManifest = JSON.parse(sourceManifestBytes);
  const releaseContractBytes = await readPinned(INPUTS.releaseContract);
  const releaseContract = JSON.parse(releaseContractBytes);
  const trustedContractBytes = await readPinned(INPUTS.trustedContract);
  const trustedContract = JSON.parse(trustedContractBytes);
  const newsBytes = await readPinned(INPUTS.news);
  const news = JSON.parse(newsBytes);
  for (const inputPath of [INPUTS.sourceManifest, INPUTS.releaseContract, INPUTS.trustedContract, INPUTS.news, INPUTS.newsRegions, INPUTS.utils, INPUTS.vendor, INPUTS.template, INPUTS.runtime, INPUTS.overrideStyle, ...INPUTS.styles]) {
    const bytes = await readPinned(inputPath);
    inputRecords.push({ path: inputPath, bytes: bytes.length, sha256: sha256(bytes) });
  }

  const { projects, detailPartitions } = await loadProjects(sourceManifest, inputRecords);
  const totals = validateProjects(projects, releaseContract, sourceManifest);
  assert.equal(totals.project_count, trustedContract.expected.project_count);
  assert.equal(totals.capacity_mw, trustedContract.expected.capacity_mw);
  const cacheContract = {
    schema: "pipelinenews.v8.fast-cache-contract.v1",
    compiler_method: COMPILER_METHOD,
    compiler: { path: `index/${COMPILER_FILE}`, sha256: compilerSha },
    sources: {
      project_manifest_sha256: sha256(sourceManifestBytes),
      release_contract_sha256: sha256(releaseContractBytes),
      trusted_v9_6_2_contract_sha256: sha256(trustedContractBytes),
      news_sha256: sha256(newsBytes),
    },
    project_index: { schema: PROJECT_SCHEMA, fields: PROJECT_FIELDS, dictionary_fields: DICTIONARY_FIELDS, stable_key: "repd_ref", detail_locator: "floor(global_row_index/500)" },
    search_index: { schema: SEARCH_SCHEMA, row_alignment: "global_project_row_index", activation: "first-nonempty-search" },
    news_index: { schema: NEWS_SCHEMA, fields: NEWS_FIELDS, stable_key: "gg_article_id", activation: "idle-after-core-ready" },
    runtime: { physical_project_rows: 50, physical_news_rows: 30, detail_fetch_concurrency: 4, immutable_cache_mode: "force-cache" },
  };
  const cacheIdentity = sha256(Buffer.from(JSON.stringify(cacheContract)));
  const cachePrefix = cacheIdentity.slice(0, 12);

  const projectPayload = compileProjects(projects, cacheIdentity);
  const searchPayload = { schema: SEARCH_SCHEMA, generation: GENERATION, cache_identity: cacheIdentity, row_alignment: "global_project_row_index", rows: projects.map(searchText) };
  const compiledNews = await compileNews(news, cacheIdentity, trustedContract);
  const projectBytes = jsonBytes(projectPayload);
  const searchBytes = jsonBytes(searchPayload);
  const compiledNewsBytes = jsonBytes(compiledNews.payload);
  assert.ok(projectBytes.length <= 1_310_720, `compact project index is ${projectBytes.length} bytes`);

  const projectFile = `${GENERATION}-${cachePrefix}-v8-fast-projects.json`;
  const searchFile = `${GENERATION}-${cachePrefix}-v8-fast-search.json`;
  const newsFile = `${GENERATION}-${cachePrefix}-v8-fast-news.json`;
  const registry = {
    schema: "pipelinenews.v8.fast-registry.v1",
    generation: GENERATION,
    compiler_method: COMPILER_METHOD,
    cache_identity: cacheIdentity,
    cache_contract: cacheContract,
    lifecycle: ["WAIT", "QUEUED", "LOAD", "INDEX", "OK", "EMPTY", "FAIL"],
    totals,
    news_counts: compiledNews.counts,
    signals: compiledNews.signals,
    assets: {
      projects: { path: `data/${projectFile}`, schema: PROJECT_SCHEMA, sha256: sha256(projectBytes), bytes: projectBytes.length, activation: "boot" },
      search: { path: `data/${searchFile}`, schema: SEARCH_SCHEMA, sha256: sha256(searchBytes), bytes: searchBytes.length, activation: "first-nonempty-search" },
      news: { path: `data/${newsFile}`, schema: NEWS_SCHEMA, sha256: sha256(compiledNewsBytes), bytes: compiledNewsBytes.length, activation: "idle-after-core-ready" },
      chart: { path: `vendor/${BASE_GENERATION}-chart-umd.min.js`, sha256: PINNED_SHA256[INPUTS.vendor], bytes: (await readPinned(INPUTS.vendor)).length, activation: "idle-after-core-ready" },
    },
    detail_schema: "globalgrid2050.v9.project-partition.v9.1",
    detail_partition_size: 500,
    detail_partitions: detailPartitions,
    source: {
      dataset: sourceManifest.source_dataset,
      source_record_count: sourceManifest.source_record_count,
      projects_sha256: sourceManifest.projects_sha256,
      identity_sha256: sourceManifest.source_identity_sha256,
      coordinate_fixture_sha256: sourceManifest.source_coordinate_fixture_sha256,
      workbook_sha256: sourceManifest.source_workbook_sha256,
      admitted_project_count: 7680,
      candidate_delta: { count: 23, status: "held-fail-closed" },
    },
    performance: {
      maximum_physical_project_rows: 50,
      maximum_physical_news_rows: 30,
      maximum_dom_elements: 5000,
      maximum_initial_decoded_bytes: 2_000_000,
      maximum_mobile_interaction_ms: 200,
      maximum_desktop_interaction_ms: 100,
      maximum_ordinary_long_task_ms: 200,
      maximum_detail_fetch_concurrency: 4,
    },
    companies_house: "deferred-phase-two",
    deployment: "not-authorised",
  };
  const registryBytes = jsonBytes(registry, true);

  let runtimeSource = replaceExactly(await readPinned(INPUTS.runtime, "utf8"), "__FAST_GENERATION__", GENERATION);