GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / pipelinenews / releases/javascript

JavaScript V8 Fast Runtime and 5 more files

A JavaScript module in PipelineNews that fetches queue (`FetchQueue`) and immutable (`fetchImmutable`), renders table (`renderTable`) and reads inputs for county and sort projects (units: MW), using EPSG:27700 and SHA-256.

627 lines of JavaScript from pipelinenews, in 6 files. Topic: Electricity markets and data pipelines. Section 1032 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. JavaScript V8 Fast Runtime energy-data · pipelinenews / releases/javascript/202609010719-v8-fast-runtime.js lines 701–942
  2. JavaScript App V9 6 2 other · pipelinenews / releases/javascript/202609010836-app-v9-6-2.js lines 1–28
  3. JavaScript Canonical Projects V9 1 render · pipelinenews / releases/javascript/202609010836-canonical-projects-v9-1.js lines 1–75
  4. JavaScript Canonical Projects V9 5 1 render · pipelinenews / releases/javascript/202609010836-canonical-projects-v9-5-1.js lines 1–33
  5. JavaScript News Regions transform · pipelinenews / releases/javascript/202609010836-news-regions.js lines 1–87
  6. JavaScript Newspaper V9 5 1 render · pipelinenews / releases/javascript/202609010836-newspaper-v9-5-1.js lines 1–162

JavaScript V8 Fast Runtime

A JavaScript module in PipelineNews that fetches queue (`FetchQueue`) and immutable (`fetchImmutable`), renders table (`renderTable`) and reads inputs for county and sort projects (units: MW), using EPSG:27700 and SHA-256.

energy-datapipelinenews / releases/javascript/202609010719-v8-fast-runtime.js · lines 701–942 of 942 · version 2026-09-01 07:19 (continued from section 1031) · Entry point · pattern openSectorIntelligence (shared by 4 files)

What it does
It draws the REPD register, battery storage (BESS), solar and wind. Defines 50 functions or classes, including FetchQueue, escapeHtml, normalise, invariant, arraysEqual. Side effects: changes the web page (DOM); makes network requests.
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: the REPD register, battery storage (BESS), solar, wind.
Inputs & outputs
Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326.
Downstream impact
Used directly by 1 file: V8 Fast Candidate (pipelinenews, https://ventusltd.github.io/pipelinenews/releases/202609010719-v8-fast-candidate.html). Reached from 125 other entry points, including GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); Homepage V002 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v002.html).
What it achieves
It fetches queue (`FetchQueue`), hashes JSON (`hashJson`) and fetches immutable (`fetchImmutable`). Its `downloadCsv` function gives CSV download or refusal from active table owner, filtered register rows and official detail partitions (VEDIC: export filtered projects). It responds to click, change and input events.
Why it matters
Loaded by the V8 Fast Candidate page at https://ventusltd.github.io/pipelinenews/releases/202609010719-v8-fast-candidate.html.
Application
pipelinenews · releases/javascript · JavaScript module
VEDIC
EXPORT FILTERED PROJECTS (GG2050-VEDIC-000060): Pipeline News · Renewable project register. active_table_owner, filtered_register_rows, official_detail_partitions → csv_download_or_refusal
Uses
JavaScript Atlas V8 Deep Link Cartridge (import)
Used by
loaded by V8 Fast Candidate (script src), mentioned in Standalone (comment link)
Produces
FetchQueue, escapeHtml, normalise, invariant, arraysEqual, hashJson, fetchImmutable, promise, dictionary, project, compactSearchText, formatNumber
Defines here
newsHtml, drawNews, bindNewsControls, loadNews, createGauge, loadCharts, openSectorIntelligence, bindSectorIntelligence, scheduleOptionalLoads, boot
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 releases/javascript/202609010719-v8-fast-runtime.js:701-942 · blob 8c5440bde1530575ada1a7f17cbfacd84f7903f4 · GitHub at these lines
State
achieves: code · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
  if (newsMode === "FINANCE" && !FINANCE_EVENTS.has(event)) return false;
  if (newsQuery) {
    const haystack = normalise([
      row[NEWS_FIELD.headline],
      row[NEWS_FIELD.project],
      row[NEWS_FIELD.operator],
      row[NEWS_FIELD.county],
      row[NEWS_FIELD.source],
      row[NEWS_FIELD.event],
      row[NEWS_FIELD.eventDetail],
      row[NEWS_FIELD.repdRef],
      row[NEWS_FIELD.projectId],
      row[NEWS_FIELD.relatedContextRepdRef],
      row[NEWS_FIELD.relatedContextProject],
      row[NEWS_FIELD.bindingLabel],
      JSON.stringify(row[NEWS_FIELD.relatedComponents] || []),
    ].join(" "));
    const tokens = normalise(newsQuery).split(" ").filter(Boolean);
    if (!tokens.every((token) => haystack.includes(token))) return false;
  }
  return true;
}

function newsHtml(row) {
  const regional = row[NEWS_FIELD.region];
  const technologyValue = newsTechnology(row);
  const articleClass = technologyValue.includes("BESS") ? "bess" : "solar";
  const projectName = row[NEWS_FIELD.project] || "";
  const capacity = Number(row[NEWS_FIELD.capacity] || 0);
  const role = String(row[NEWS_FIELD.role] || "");
  const relatedContextProject = String(row[NEWS_FIELD.relatedContextProject] || "");
  const relatedContextRef = String(row[NEWS_FIELD.relatedContextRepdRef] || "");
  const relatedComponents = Array.isArray(row[NEWS_FIELD.relatedComponents]) ? row[NEWS_FIELD.relatedComponents] : [];
  const eventDetail = String(row[NEWS_FIELD.eventDetail] || "").replaceAll("_", " ");
  const quality = role === "RELATED_MENTION"
    ? `<span class="news-quality unverified">${escapeHtml(row[NEWS_FIELD.bindingLabel] || "RELATED CONTEXT ONLY — NOT A PROJECT BINDING")}</span>${relatedContextProject ? ` · context: ${escapeHtml(relatedContextProject)}` : ""}${relatedContextRef ? ` · related REPD ${escapeHtml(relatedContextRef)}` : ""} · no project signal`
    : row[NEWS_FIELD.canonical] === true
    ? `<span class="news-quality relevant">RELEVANT ${Number(row[NEWS_FIELD.confidence] || 0)}%</span> · PRIMARY_MATCH · REPD ${escapeHtml(row[NEWS_FIELD.repdRef])}`
    : regional
      ? `<span class="news-quality relevant">${escapeHtml(regional === "INTERNATIONAL_OTHER" ? "INTERNATIONAL" : regional)}</span> · ${escapeHtml(row[NEWS_FIELD.regionalEvidence])} · regional discovery only · no REPD project signal`
      : '<span class="news-quality unverified">DISCOVERY ONLY</span> · no project signal';
  const componentNote = relatedComponents.length
    ? `<p>${relatedComponents.map((component) => `RELATED DEVELOPMENT · REPD ${escapeHtml(component.repd_ref || "unknown")} · ${escapeHtml(String(component.technology || "").toUpperCase())}${Number.isFinite(component.official_capacity_mw) ? ` · ${Number(component.official_capacity_mw).toLocaleString("en-GB")} MW` : " · official capacity unknown"} · no project signal`).join(" · ")}</p>`
    : "";
  return `<a class="story ${articleClass}" data-article-id="${escapeHtml(row[NEWS_FIELD.articleId])}" href="${escapeHtml(row[NEWS_FIELD.url])}" target="_blank" rel="noopener"><div class="kicker">${escapeHtml(technologyValue || "ENERGY")} · ${escapeHtml(row[NEWS_FIELD.event] || "PROJECT UPDATE")}${eventDetail ? ` · ${escapeHtml(eventDetail)}` : ""} · ${escapeHtml(row[NEWS_FIELD.published] || "")}</  … [line shortened here: 900 characters; full line on GitHub]
}

function drawNews() {
  const matches = newsRows.filter(newsMatches);
  const stories = document.getElementById("stories");
  if (newsStart >= matches.length) newsStart = 0;
  if (!matches.length) {
    stories.innerHTML = '<div class="news-empty">No headlines match this newspaper filter.</div>';
  } else {
    stories.innerHTML = matches.slice(newsStart, newsStart + NEWS_WINDOW_SIZE).map(newsHtml).join("");
  }
  let pager = document.getElementById("newsPager");
  if (!pager) {
    pager = document.createElement("div");
    pager.id = "newsPager";
    pager.className = "news-pager";
    pager.innerHTML = '<button id="newsPrevious" type="button">PREVIOUS 30</button><span id="newsWindowRange"></span><button id="newsMore" type="button">NEXT 30</button>';
    document.querySelector(".paper").after(pager);
    pager.querySelector("#newsPrevious").addEventListener("click", () => {
      newsStart = Math.max(0, newsStart - NEWS_WINDOW_SIZE);
      drawNews();
    });
    pager.querySelector("#newsMore").addEventListener("click", () => {
      newsStart += NEWS_WINDOW_SIZE;
      drawNews();
    });
  }
  const end = Math.min(matches.length, newsStart + NEWS_WINDOW_SIZE);
  const previous = pager.querySelector("#newsPrevious");
  const more = pager.querySelector("#newsMore");
  previous.disabled = newsStart === 0;
  more.disabled = end >= matches.length;
  pager.querySelector("#newsWindowRange").textContent = matches.length
    ? `${newsStart + 1}–${end} of ${matches.length.toLocaleString("en-GB")}`
    : "0 headlines";
  more.textContent = `NEXT ${Math.min(NEWS_WINDOW_SIZE, Math.max(0, matches.length - end))} · ${matches.length.toLocaleString("en-GB")} MATCHES`;
}

function bindNewsControls() {
  document.querySelectorAll("#newsTools button").forEach((button) => {
    button.addEventListener("click", () => {
      document.querySelectorAll("#newsTools button").forEach((candidate) => candidate.classList.remove("active"));
      button.classList.add("active");
      newsMode = button.dataset.news;
      newsStart = 0;
      drawNews();
    });
  });
  document.getElementById("newsSearch").addEventListener("input", (event) => {
    newsQuery = event.target.value.trim();
    newsStart = 0;
    drawNews();
  });
}

async function loadNews() {
  if (runtimeEvidence.newsReady) return;
  runtimeEvidence.newsRequests += 1;
  try {
    const payload = await fetchImmutable(registry.assets.news.path);
    invariant(payload.schema === registry.assets.news.schema, "news schema mismatch");
    invariant(payload.generation === registry.assets.news.generation, "news generation mismatch");
    invariant(payload.cache_identity === registry.assets.news.cache_identity, "news cache identity mismatch");
    invariant(arraysEqual(payload.fields, NEWS_FIELDS), "news field contract mismatch");
    invariant(payload.rows.length === registry.news_counts.all, "news count mismatch");
    newsRows = payload.rows;
    runtimeEvidence.newsReady = true;
    document.getElementById("newsMeta").textContent = `${registry.news_counts.uk} UK · ${registry.news_counts.international} international (${registry.news_counts.us} US · ${registry.news_counts.europe} Europe · ${registry.news_counts.other} other) · ${registry.news_counts.all} headlines · immutable compact edition`;
    drawNews();
  } catch (error) {
    console.error(error);
    document.getElementById("stories").innerHTML = '<div class="news-empty">Newspaper unavailable. REPD analytics remain live.</div>';
    document.getElementById("newsMeta").textContent = "newspaper unavailable";
  }
}

function createGauge(canvasId, colour) {
  const options = { responsive: true, maintainAspectRatio: false, circumference: 180, rotation: 270, cutout: "80%", plugins: { tooltip: { enabled: false }, legend: { display: false } } };
  return new globalThis.Chart(document.getElementById(canvasId), { type: "doughnut", data: { datasets: [{ data: [0, 1], backgroundColor: [colour, "#222"], borderWidth: 0 }] }, options });
}

async function loadCharts() {
  if (runtimeEvidence.chartsReady) return;
  await new Promise((resolve, reject) => {
    const script = document.createElement("script");
    script.src = registry.assets.chart.path;
    script.async = true;
    script.onload = resolve;
    script.onerror = () => reject(new Error("pinned Chart.js failed to load"));
    document.head.appendChild(script);
  });
  invariant(typeof globalThis.Chart === "function", "pinned Chart.js API unavailable");
  charts.capacity = createGauge("g1", "#ff00ff");
  charts.projects = createGauge("g2", "#00ffff");
  charts.largest = createGauge("g3", "#00ff88");
  runtimeEvidence.chartsReady = true;
  updateGauges({ count: filtered.length, capacity: filtered.reduce((sum, index) => sum + Number(rows[index][FIELD.capacity]), 0), largest: filtered.reduce((maximum, index) => Math.max(maximum, Number(rows[index][FIELD.capacity])), 0) });
}

async function openSectorIntelligence() {
  const button = document.getElementById("sectorIntelOpen");
  const host = document.getElementById("sectorIntelHost");
  const meta = document.getElementById("sectorIntelMeta");
  invariant(button && host && meta, "sector-intelligence controls are missing");
  if (host.dataset.sectorIntelligenceState === "ready") {
    host.hidden = !host.hidden;
    button.setAttribute("aria-expanded", String(!host.hidden));
    return;
  }
  if (host.dataset.sectorIntelligenceState === "loading") return;
  const entry = registry.supplemental_assets?.sector_intelligence;
  invariant(entry?.activation === "dynamic-import-on-user-open; payload-fetch-on-first-topic-selection", "sector activation changed");
  invariant(entry.project_bindings === 0 && entry.eligible_for_news_signal === false, "sector binding boundary changed");
  host.hidden = false;
  host.dataset.sectorIntelligenceState = "loading";
  button.setAttribute("aria-expanded", "true");
  meta.textContent = "LOAD · importing sector controls; no payload requested";
  runtimeEvidence.sectorIntelligenceImports += 1;
  invariant(runtimeEvidence.sectorIntelligenceImports === 1, "sector cartridge imported more than once");
  const cartridge = await import(`./${entry.cartridge.filename}`);
  invariant(cartridge.SECTOR_INTELLIGENCE_CARTRIDGE_CONTRACT.generation === GENERATION, "sector cartridge identity changed");
  const result = cartridge.mountSectorIntelligence({
    host,
    payloadAsset: {
      ...entry.payload,
      url: new URL(`../${entry.payload.path}`, import.meta.url).pathname.split("/releases/")[1],
    },
  });
  runtimeEvidence.sectorPayloadRequestsAtMount = result.payloadRequests;
  invariant(runtimeEvidence.sectorPayloadRequestsAtMount === 0, "sector payload requested at mount");
  meta.textContent = "WAIT · five topics · choose one to request the compact Parquet-derived payload";
}

function bindSectorIntelligence() {
  const button = document.getElementById("sectorIntelOpen");
  invariant(button, "sector-intelligence opener is missing");
  button.addEventListener("click", () => openSectorIntelligence().catch((error) => {
    console.error("sector intelligence", error);
    document.getElementById("sectorIntelMeta").textContent = "FAIL · sector intelligence unavailable";
  }));
}

function scheduleOptionalLoads() {
  setTimeout(() => {
    const schedule = globalThis.requestIdleCallback || ((callback) => setTimeout(callback, 0));
    schedule(() => loadNews(), { timeout: 1500 });
    schedule(() => loadCharts().catch((error) => console.error(error)), { timeout: 2000 });
  }, 1000);
}

async function boot() {
  registry = await fetchImmutable(REGISTRY_URL);
  invariant(registry.schema === "pipelinenews.v8.live-news-registry.v1", "registry schema mismatch");
  invariant(registry.generation === GENERATION, "registry generation mismatch");
  invariant(registry.compiler_method === EXPECTED_COMPILER_METHOD, "registry compiler method mismatch");
  invariant(registry.cache_identity === EXPECTED_CACHE_IDENTITY, "registry cache identity mismatch");
  invariant(await hashJson(registry.cache_contract) === EXPECTED_CACHE_IDENTITY, "registry cache contract digest mismatch");
  invariant(registry.cache_contract.compiler_method === EXPECTED_COMPILER_METHOD, "cache compiler method mismatch");
  invariant(arraysEqual(registry.cache_contract.project_index.fields, PROJECT_FIELDS), "registry project field contract mismatch");
  invariant(arraysEqual(registry.cache_contract.news_index.fields, NEWS_FIELDS), "registry news field contract mismatch");
  invariant(registry.cache_contract.news_index.stable_key === "gg_article_id", "registry news key contract mismatch");
  invariant(registry.cache_contract.runtime.physical_project_rows === WINDOW_SIZE, "project window contract mismatch");
  invariant(registry.cache_contract.runtime.physical_news_rows === NEWS_WINDOW_SIZE, "news window contract mismatch");
  invariant(registry.cache_contract.runtime.detail_fetch_concurrency === DETAIL_CONCURRENCY, "detail concurrency contract mismatch");
  projectPayload = await fetchImmutable(registry.assets.projects.path);
  invariant(projectPayload.schema === registry.assets.projects.schema, "project index schema mismatch");
  invariant(projectPayload.generation === registry.assets.projects.generation, "project generation mismatch");
  invariant(projectPayload.cache_identity === registry.assets.projects.cache_identity, "project cache identity mismatch");
  invariant(arraysEqual(projectPayload.fields, PROJECT_FIELDS), "project field contract mismatch");
  invariant(projectPayload.rows.length === registry.totals.project_count, "project index count mismatch");
  rows = projectPayload.rows;
  dictionaries = projectPayload.dictionaries;
  updatedTimes = rows.map((row) => {
    const value = row[FIELD.updated];
    const timestamp = value ? Date.parse(`${value}T00:00:00Z`) : NaN;
    return Number.isFinite(timestamp) ? timestamp : null;
  });
  bindProjectControls();
  bindNewsControls();
  bindSectorIntelligence();
  populateCounties();
  hydrateFiltersFromUrl();
  if (query) await ensureSearchSupplement();
  apply({ syncUrl: false });
  document.getElementById("releaseMeta").textContent = `Live News + five-topic sector intelligence candidate · ${rows.length.toLocaleString("en-GB")} canonical projects · ${registry.performance.maximum_physical_project_rows} physical rows · sector payload lazy · NOT DEPLOYED`;
  document.body.dataset.fastReady = "true";
  document.body.dataset.fastGeneration = GENERATION;
  globalThis.dispatchEvent(new CustomEvent("pipelinenews-fast-ready", { detail: { generation: GENERATION } }));
  scheduleOptionalLoads();
}

boot().catch((error) => {
  console.error(error);
  document.getElementById("tbody").innerHTML = '<tr><td colspan="11" class="fast-fail">Canonical Q2 REPD data unavailable. The fast candidate has failed closed.</td></tr>';
  document.getElementById("resultsMeta").textContent = "canonical data unavailable";
  document.body.dataset.fastFailed = "true";
});

JavaScript App V9 6 2

A JavaScript module in PipelineNews.

otherpipelinenews / releases/javascript/202609010836-app-v9-6-2.js · lines 1–28 of 28 · version 2026-09-01 08:36 · Entry point

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.
Downstream impact
Used directly by 1 file: PipelineNews — Releases Page (pipelinenews, https://ventusltd.github.io/pipelinenews/releases/202609010836-index.html). Reached from 2 other entry points, including PipelineNews Performance Audit Workflow (pipelinenews); Performance Audit (pipelinenews).
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name. Described from its file name only (a candidate, not yet checked against the code).
Why it matters
Loaded by the Releases page at https://ventusltd.github.io/pipelinenews/releases/202609010836-index.html.
Application
pipelinenews · releases/javascript · JavaScript module
Uses
Gauges V9 2 (import), JavaScript Newspaper V9 6 2 (import), JavaScript Projects V9 5 1 (import), Plugin Host (import)
Used by
loaded by PipelineNews — Releases Page (script src)
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
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 releases/javascript/202609010836-app-v9-6-2.js:1-28 · blob c6babb18cc9ccb9126a3a69c4339d467e320727b · GitHub at these lines
State
achieves: name · context: readme_derived · stage: unknown · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import { initialiseGaugesV9_2 } from "./202609010836-gauges.js";
import { bindNewspaperV9_6_2, loadNewsV9_6_2 } from "./202609010836-newspaper-v9-6-2.js";
import {
  bindProjectControlsV9_5_1,
  loadProjectsV9_5_1,
  refreshProjectsV9_5_1,
} from "./202609010836-projects-v9-5-1.js";
import { startPlugins } from "./202609010836-startplugins.js";

startPlugins([
  { id: "gauges", start: initialiseGaugesV9_2 },
  {
    id: "newspaper",
    dependsOn: ["gauges"],
    start() {
      bindNewspaperV9_6_2(refreshProjectsV9_5_1);
      loadNewsV9_6_2();
    },
  },
  {
    id: "projects",
    dependsOn: ["gauges", "newspaper"],
    start() {
      bindProjectControlsV9_5_1();
      loadProjectsV9_5_1();
    },
  },
]);

JavaScript Canonical Projects V9 1

A JavaScript module in PipelineNews that fetches solar, battery storage (BESS) and the Renewable Energy Planning Database (REPD) register. It fetches JSON (`fetchJson`) and loads canonical projects v9 (`loadCanonicalProjectsV9_1`).

Set aside from the main view: 91% of its lines are the same as testcode/202609051152/pipeline/scripts/data/canonical-projects-v9-1.js (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 90% of lines shared with Canonical Projects V9 1; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9062 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609051152/pipeline/scripts/data/canonical-projects-v9-1.js:1-75 b92a4a31a74e8d1b45ee5d32e5678324bd364d66
  • sha256 9377e0941c0cc99429a675d387726b72f1ebefe77cb8423ef4593027cb995617
  • target sha256 d6135413ca0c0527142ba6557b9f7cb286618b6478d1804469e2239f808b00c3
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

renderpipelinenews / releases/javascript/202609010836-canonical-projects-v9-1.js · lines 1–75 of 75 · version 2026-09-01 08:36 · pattern loadCanonicalProjects (shared by 12 files)

What it does
It fetches solar, battery storage (BESS) and the REPD register. Defines invariant, round2, fetchJson, loadCanonicalProjectsV9_1. Side effects: changes the web page (DOM); makes network requests.
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.
Inputs & outputs
In: JSON file 202608261927-release-v9-1.json; JSON file 202609010836-build-manifest-v9-1.json.
Downstream impact
Used directly by 1 file: JavaScript Canonical Projects V9 5 1 (pipelinenews). Reached from 6 other entry points, including PipelineNews — Releases Page (pipelinenews, https://ventusltd.github.io/pipelinenews/releases/202609010836-index.html); V8 Candidate (pipelinenews, https://ventusltd.github.io/pipelinenews/releases/202608262141-v8-candidate.html); PipelineNews Performance Audit Workflow (pipelinenews).
What it achieves
Defines `invariant`, `round2`, `fetchJson` and 1 more. Its code works with 1 MW.
Why it matters
Imported by JavaScript Canonical Projects V9 5 1.
Application
pipelinenews · releases/javascript · JavaScript module
Uses
none found
Used by
imported by JavaScript Canonical Projects V9 5 1 (import)
Produces
loadCanonicalProjectsV9_1
Defines here
invariant, round2, fetchJson, loadCanonicalProjectsV9_1
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 releases/javascript/202609010836-canonical-projects-v9-1.js:1-75 · blob 8b36ed46f7a8b7bf5583fce518833b231990ca32 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
const CONTRACT_URL = "../data/contracts/202608261927-release-v9-1.json";
const MANIFEST_URL = "manifests/202609010836-build-manifest-v9-1.json";
const ALLOWED_TECHNOLOGIES = new Set(["solar", "bess", "wind_onshore", "wind_offshore"]);

function invariant(condition, message) {
  if (!condition) throw new Error(`V9.1 canonical projects: ${message}`);
}

function round2(value) {
  return Math.round((value + Number.EPSILON) * 100) / 100;
}

async function fetchJson(path) {
  const response = await fetch(path, { cache: "no-store" });
  invariant(response.ok, `${path} returned HTTP ${response.status}`);
  invariant(new URL(response.url).origin === window.location.origin, `${path} redirected cross-origin`);
  return response.json();
}

export async function loadCanonicalProjectsV9_1() {
  const [contract, payload] = await Promise.all([fetchJson(CONTRACT_URL), fetchJson(MANIFEST_URL)]);
  invariant(contract.release === "9.1", "release contract mismatch");
  invariant(payload.schema === "globalgrid2050.v9.project-spine-build.v9.1", "project manifest schema mismatch");
  invariant(payload.release === "9.1", "project release mismatch");
  invariant(Array.isArray(payload.project_partitions) && payload.project_partitions.length > 0, "project partitions missing");
  invariant(payload.source_identity_sha256 === contract.source.identity_fixture_sha256, "identity hash mismatch");
  invariant(payload.source_coordinate_fixture_sha256 === contract.source.coordinate_fixture_sha256, "coordinate hash mismatch");
  invariant(payload.source_workbook_sha256 === contract.source.workbook_sha256, "workbook hash mismatch");

  const partitions = await Promise.all(payload.project_partitions.map(async (partition) => {
    const part = await fetchJson(partition.path);
    invariant(part.schema === "globalgrid2050.v9.project-partition.v9.1", `${partition.path} schema mismatch`);
    invariant(part.record_count === partition.record_count && part.projects.length === partition.record_count, `${partition.path} count mismatch`);
    return part.projects;
  }));
  const sourceProjects = partitions.flat();
  invariant(sourceProjects.length === payload.project_count, "partition total mismatch");

  const refs = new Set();
  const projectIds = new Set();
  let capacity = 0;
  let largest = 0;
  const counts = { solar: 0, bess: 0, wind_onshore: 0, wind_offshore: 0 };
  const projects = sourceProjects.map((project) => {
    invariant(typeof project.repd_ref === "string" && project.repd_ref, "missing REPD Ref");
    invariant(project.gg_project_id === `GG2050-REPD-${project.repd_ref}`, `invalid ID for ${project.repd_ref}`);
    invariant(project.identity_status === "REPD_BOUND" && project.identity_confidence === "authoritative", `unbound identity for ${project.repd_ref}`);
    invariant(ALLOWED_TECHNOLOGIES.has(project.technology), `out-of-scope technology for ${project.repd_ref}`);
    invariant(Number.isFinite(project.capacity_mw) && project.capacity_mw >= 1, `capacity below 1 MW for ${project.repd_ref}`);
    invariant(!refs.has(project.repd_ref), `duplicate REPD Ref ${project.repd_ref}`);
    invariant(!projectIds.has(project.gg_project_id), `duplicate project ID ${project.gg_project_id}`);
    refs.add(project.repd_ref);
    projectIds.add(project.gg_project_id);
    counts[project.technology] += 1;
    capacity += project.capacity_mw;
    largest = Math.max(largest, project.capacity_mw);
    return Object.freeze({ ...project });
  });

  const actual = {
    project_count: projects.length,
    capacity_mw: round2(capacity),
    largest_mw: largest,
    solar_count: counts.solar,
    bess_count: counts.bess,
    wind_onshore_count: counts.wind_onshore,
    wind_offshore_count: counts.wind_offshore,
  };
  Object.entries(contract.expected).forEach(([key, value]) => invariant(actual[key] === value, `${key} is ${actual[key]}, expected ${value}`));
  return Object.freeze({
    contract: Object.freeze(contract),
    metadata: Object.freeze({ ...payload, projects: undefined }),
    projects: Object.freeze(projects),
  });
}

JavaScript Canonical Projects V9 5 1

A JavaScript module in PipelineNews that fetches release (`fetchRelease`) (units: MW). It fetches release (`fetchRelease`) and loads canonical projects v9 (`loadCanonicalProjectsV9_5_1`).

renderpipelinenews / releases/javascript/202609010836-canonical-projects-v9-5-1.js · lines 1–33 of 33 · version 2026-09-01 08:36 · pattern fetchRelease (shared by 9 files)

What it does
It fetches data. Defines invariant, fetchRelease, loadCanonicalProjectsV9_5_1. Side effects: changes the web page (DOM); makes network requests.
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.
Inputs & outputs
In: JSON file 202608261737-release-v9-5-1.json.
Downstream impact
Used directly by 3 files: JavaScript Projects V8 Windowed (pipelinenews); JavaScript Projects V8 Foundation (pipelinenews); JavaScript Projects V9 5 1 (pipelinenews). Reached from 6 other entry points, including PipelineNews — Releases Page (pipelinenews, https://ventusltd.github.io/pipelinenews/releases/202609010836-index.html); V8 Candidate (pipelinenews, https://ventusltd.github.io/pipelinenews/releases/202608262141-v8-candidate.html); PipelineNews Performance Audit Workflow (pipelinenews).
What it achieves
Defines `invariant`, `fetchRelease` and `loadCanonicalProjectsV9_5_1`.
Why it matters
Imported by JavaScript Projects V8 Windowed, JavaScript Projects V8 Foundation and JavaScript Projects V9 5 1.
Application
pipelinenews · releases/javascript · JavaScript module
Uses
JavaScript Canonical Projects V9 1 (import)
Used by
imported by JavaScript Projects V8 Windowed (import), imported by JavaScript Projects V8 Foundation (import), imported by JavaScript Projects V9 5 1 (import)
Produces
loadCanonicalProjectsV9_5_1
Defines here
invariant, fetchRelease, loadCanonicalProjectsV9_5_1
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 releases/javascript/202609010836-canonical-projects-v9-5-1.js:1-33 · blob 25448a2c7d815e43cd3fc1d0763f42dc3e457fa4 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import { loadCanonicalProjectsV9_1 } from "./202609010836-canonical-projects-v9-1.js";

const RELEASE_URL = "../data/contracts/202608261737-release-v9-5-1.json";

function invariant(condition, message) {
  if (!condition) throw new Error(`V9.5.1 canonical projects: ${message}`);
}

async function fetchRelease() {
  const response = await fetch(RELEASE_URL, { cache: "no-store" });
  invariant(response.ok, `${RELEASE_URL} returned HTTP ${response.status}`);
  invariant(new URL(response.url).origin === window.location.origin, `${RELEASE_URL} redirected cross-origin`);
  return response.json();
}

export async function loadCanonicalProjectsV9_5_1() {
  const [release, model] = await Promise.all([fetchRelease(), loadCanonicalProjectsV9_1()]);
  invariant(release.release === "9.5.1", "release contract mismatch");
  invariant(release.frozen_parent?.release === "9.5", "frozen-parent release mismatch");
  invariant(release.data_parent?.release === "9.1", "data-parent release mismatch");
  invariant(model.contract.release === "9.1", "canonical data contract mismatch");
  invariant(model.projects.length === release.expected.project_count, "project count mismatch");
  invariant(model.metadata.capacity_mw === release.expected.capacity_mw, "capacity mismatch");
  invariant(model.metadata.largest_mw === release.expected.largest_mw, "largest project mismatch");
  invariant(model.metadata.geometry_count === release.expected.valid_geometry_count, "valid geometry count mismatch");
  invariant(model.metadata.missing_geometry_count === release.expected.missing_geometry_count, "missing geometry count mismatch");
  return Object.freeze({
    release: Object.freeze(release),
    dataContract: model.contract,
    metadata: Object.freeze({ ...model.metadata, ui_release: "9.5.1" }),
    projects: model.projects,
  });
}

JavaScript News Regions

A JavaScript module in PipelineNews that works with solar and battery storage (BESS). It classifies international v9 (`classifyInternationalV9_6_2`) and is built from the distinctive project tokens helper (`distinctiveProjectTokens`).

Set aside from the main view: 97% of its lines are the same as testcode/202609051152/pipeline/scripts/core/news-regions-v9-6-2.js (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 96% of lines shared with News Regions V9 6 2; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9688 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609051152/pipeline/scripts/core/news-regions-v9-6-2.js:1-87 0127ebdd379d54b7f87b781f496a28e3c3e65325
  • sha256 d510d732b66bf54b31ea2a745bb09f2f8056ece5c73cc0ef4921728adbedf925
  • target sha256 dd8a50414632200f9022bb19b934df50dab3785f1f88cfeadb133a4a207ccaa5
  • group of 4 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

transformpipelinenews / releases/javascript/202609010836-news-regions.js · lines 1–87 of 87 · version 2026-09-01 08:36 · pattern distinctiveProjectTokens (shared by 4 files)

What it does
It calculates solar and battery storage (BESS). Defines distinctiveProjectTokens, ukEvidenceV9_6_2, technology, classifyInternationalV9_6_2, regionalCountsV9_6_2.
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).
Downstream impact
Used directly by 1 file: JavaScript Newspaper V9 6 2 (pipelinenews). Reached from 6 other entry points, including PipelineNews — Releases Page (pipelinenews, https://ventusltd.github.io/pipelinenews/releases/202609010836-index.html); V8 Candidate (pipelinenews, https://ventusltd.github.io/pipelinenews/releases/202608262141-v8-candidate.html); PipelineNews Performance Audit Workflow (pipelinenews).
What it achieves
Defines `distinctiveProjectTokens`, `ukEvidenceV9_6_2`, `technology` and 2 more.
Why it matters
Imported by JavaScript Newspaper V9 6 2.
Application
pipelinenews · releases/javascript · JavaScript module
Uses
Testcode — Pipeline (import)
Used by
imported by JavaScript Newspaper V9 6 2 (import)
Produces
ukEvidenceV9_6_2, classifyInternationalV9_6_2, regionalCountsV9_6_2
Defines here
distinctiveProjectTokens, ukEvidenceV9_6_2, technology, classifyInternationalV9_6_2, regionalCountsV9_6_2
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 releases/javascript/202609010836-news-regions.js:1-87 · blob 4452c36e6d2559e93cddf541ed7310680eac8edc · 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 { normaliseProject } from "./202609010836-utils.js";

const SOLAR = /\b(?:solar|photovoltaic(?:s)?|pv|agrivoltaic(?:s)?)\b/i;
const BESS = /\b(?:bess|battery|batteries|energy storage|grid storage)\b/i;

const UK = /\b(?:uk|u\.k\.|united kingdom|britain|british|england|english|scotland|scottish|wales|welsh|northern ireland|north yorkshire|lincolnshire|nottinghamshire|devon|cornish|cumbria|suffolk|kent|surrey|gloucestershire|oxfordshire|warwickshire|yorkshire|essex|norfolk|somerset|dorset|lancashire|derbyshire|leicestershire|cambridgeshire|bedfordshire|hertfordshire|buckinghamshire|worcestershire|s  … [line shortened here: 535 characters; full line on GitHub]

const US = /\b(?:us(?!\$)|u\.s\.(?!\$)|usa|u\.s\.a\.|united states|american|new jersey|virginia|california|arizona|texas|new york|florida|illinois|ohio|pennsylvania|colorado|nevada|oregon|washington state|massachusetts|connecticut|maryland|michigan|minnesota|wisconsin|georgia|north carolina|south carolina|tennessee|kentucky|indiana|iowa|kansas|missouri|oklahoma|new mexico|utah|idaho|montana|wyomin  … [line shortened here: 566 characters; full line on GitHub]

const EUROPE = /\b(?:europe|european union|eu|ireland|irish|germany|german|france|french|spain|spanish|italy|italian|netherlands|dutch|belgium|belgian|poland|polish|portugal|portuguese|greece|greek|denmark|danish|sweden|swedish|norway|norwegian|finland|finnish|austria|austrian|switzerland|swiss|czechia|czech|romania|romanian|bulgaria|bulgarian|hungary|hungarian|croatia|croatian|serbia|serbian|slov  … [line shortened here: 541 characters; full line on GitHub]

const OTHER = /\b(?:australia|australian|canada|india|china|chinese|south africa|new zealand|japan|japanese|brazil|brazilian|mexico|mexican|uae|united arab emirates|saudi arabia|taiwan|philippines|chile|argentina|africa|asia|latin america|middle east)\b/i;

const GENERIC_PROJECT = new Set([
  "and", "the", "farm", "solar", "battery", "bess", "storage", "energy", "park", "site",
  "road", "lane", "wind", "offshore", "onshore", "project", "phase", "extension", "facility",
  "system", "scheme", "development", "power", "limited", "ltd", "centre", "center",
  "grid", "services", "complex", "south", "north", "east", "west", "southern", "northern",
  "eastern", "western", "california", "virginia", "jersey", "australia", "germany", "france",
  "spain", "italy", "ireland", "romania", "greece", "chile", "japan",
]);

function distinctiveProjectTokens(item) {
  return normaliseProject(item.project || "")
    .split(" ")
    .filter((token) => token.length >= 5 && !GENERIC_PROJECT.has(token));
}

export function ukEvidenceV9_6_2(item) {
  if (item?.canonical_relevant === true) return "canonical REPD PRIMARY_MATCH";
  const headline = String(item?.headline || "");
  if (UK.test(headline)) return "explicit UK geography";
  const normalisedHeadline = normaliseProject(headline);
  const projectToken = distinctiveProjectTokens(item).find((token) => normalisedHeadline.includes(token));
  if (projectToken && String(item?.county || "").trim()) return `UK project token ${projectToken}`;
  return "";
}

function technology(headline) {
  const solar = SOLAR.test(headline);
  const bess = BESS.test(headline);
  if (solar && bess) return "SOLAR + BESS";
  if (solar) return "SOLAR";
  if (bess) return "BESS";
  return "";
}

export function classifyInternationalV9_6_2(item) {
  const headline = String(item?.headline || "");
  const classifiedTechnology = technology(headline);
  if (!classifiedTechnology || ukEvidenceV9_6_2(item)) return null;

  let region = "";
  let evidence = "";
  if (US.test(headline)) {
    region = "US";
    evidence = "explicit US geography";
  } else if (EUROPE.test(headline)) {
    region = "EUROPE";
    evidence = "explicit European geography";
  } else if (OTHER.test(headline)) {
    region = "INTERNATIONAL_OTHER";
    evidence = "explicit non-UK geography";
  }
  if (!region) return null;

  return Object.freeze({
    region,
    technology: classifiedTechnology,
    evidence,
    project_signal_eligible: false,
    canonical_identity: false,
  });
}

export function regionalCountsV9_6_2(items) {
  const counts = { international: 0, us: 0, europe: 0, other: 0 };
  for (const item of items || []) {
    const result = classifyInternationalV9_6_2(item);
    if (!result) continue;
    counts.international += 1;
    if (result.region === "US") counts.us += 1;
    else if (result.region === "EUROPE") counts.europe += 1;
    else counts.other += 1;
  }
  return Object.freeze(counts);
}

JavaScript Newspaper V9 5 1

A JavaScript module in PipelineNews that draws major project news, battery storage (BESS), the Renewable Energy Planning Database (REPD) register and solar.

Set aside from the main view: 94% of its lines are the same as testcode/202609051152/pipeline/scripts/plugins/newspaper-v9-5-1.js (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 94% of lines shared with Newspaper V9 5 1; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9431 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609051152/pipeline/scripts/plugins/newspaper-v9-5-1.js:1-163 c990407d2fd47ccfd9b94ab7c34230dce6741007
  • sha256 b6407b79ea0ef07581faa4680b5771fe982ebebac18bb96f2ae0399898b35ef6
  • target sha256 f0925133d5d29113b113d241ccee5869bf9484a7319050913d7cd6b9cec5cf86
  • group of 4 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

renderpipelinenews / releases/javascript/202609010836-newspaper-v9-5-1.js · lines 1–162 of 162 · version 2026-09-01 08:36 · pattern itemTechnology (shared by 7 files)

What it does
It draws major project news, battery storage (BESS), the REPD register and solar. Defines 14 functions or classes, including refreshProjects, canonicalItem, indexNewsItems, signalLabel, signalForProjectV9_5_1. Side effects: changes the web page (DOM); makes network requests.
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: battery storage (BESS), the REPD register, solar.
Inputs & outputs
In: JSON file 202608261927-major-project-news-v9-5-1.json.
Downstream impact
Used directly by 4 files: JavaScript Projects V8 Windowed (pipelinenews); JavaScript Projects V8 Foundation (pipelinenews); JavaScript Newspaper V9 6 2 (pipelinenews); JavaScript Projects V9 5 1 (pipelinenews). Reached from 6 other entry points, including PipelineNews — Releases Page (pipelinenews, https://ventusltd.github.io/pipelinenews/releases/202609010836-index.html); V8 Candidate (pipelinenews, https://ventusltd.github.io/pipelinenews/releases/202608262141-v8-candidate.html); PipelineNews Performance Audit Workflow (pipelinenews).
What it achieves
It refreshes projects (`refreshProjects`), indexes news (`indexNewsItems`) and draws news v9 (`drawNewsV9_5_1`). Defines `refreshProjects`, `canonicalItem`, `indexNewsItems` and 11 more.
Why it matters
Imported by 4 files, including JavaScript Projects V8 Windowed, JavaScript Projects V8 Foundation and JavaScript Newspaper V9 6 2.
Application
pipelinenews · releases/javascript · JavaScript module
Uses
JavaScript State (import), Testcode — Pipeline (import)
Used by
imported by JavaScript Projects V8 Windowed (import), imported by JavaScript Projects V8 Foundation (import), imported by JavaScript Newspaper V9 6 2 (import), imported by JavaScript Projects V9 5 1 (import)
Produces
signalForProjectV9_5_1, drawNewsV9_5_1, loadNewsV9_5_1, bindNewspaperV9_5_1
Defines here
refreshProjects, canonicalItem, indexNewsItems, signalLabel, signalForProjectV9_5_1, itemTechnology, newsMatches, drawNewsV9_5_1, validPayload, payloadTime, fetchPayload, renderNews, loadNewsV9_5_1, bindNewspaperV9_5_1
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 releases/javascript/202609010836-newspaper-v9-5-1.js:1-162 · blob 237435a3834f6e8a950413fe304a32592129e5fc · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import { state } from "./202609010836-state.js";
import { escapeHtml, isFinanceEvent, normaliseProject } from "./202609010836-utils.js";

const NEWS_SOURCES = Object.freeze([
  ["PipelineNews", "../data/news/202608261927-major-project-news-v9-5-1.json"],
]);

let refreshProjects = () => {};
let newsIndex = new Map();

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 indexNewsItems(items) {
  newsIndex = new Map();
  for (const item of items.filter(canonicalItem)) {
    const key = String(item.repd_ref);
    const previous = newsIndex.get(key);
    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)) {
      newsIndex.set(key, item);
    }
  }
}

function signalLabel(item) {
  const event = String(item.event || "PROJECT UPDATE").toUpperCase();
  if (event === "CONSENT") return { label: "APPROVED*", cls: "approved" };
  if (event === "OPERATIONAL") return { label: "OPERATIONAL*", cls: "operational" };
  if (event === "CONSTRUCTION") return { label: "CONSTRUCTION*", cls: "construction" };
  if (["FINANCIAL CLOSE", "ACQUISITION"].includes(event)) {
    return { label: event === "ACQUISITION" ? "M&A*" : "FINANCED*", cls: "finance" };
  }
  return { label: `${event}*`.slice(0, 22), cls: "" };
}

export function signalForProjectV9_5_1(project) {
  const item = newsIndex.get(String(project.repd_ref));
  if (!item) return { label: "—", cls: "none", note: "no exact canonical PRIMARY_MATCH" };
  return {
    ...signalLabel(item),
    note: `canonical PRIMARY_MATCH ${Number(item.confidence || 0)}% · unverified event · ${item.published || "date unavailable"}`,
  };
}

function itemTechnology(item) {
  return String(item.canonical_technology || item.technology || "").toUpperCase();
}

function newsMatches(item) {
  const event = String(item.event || "").toUpperCase();
  const technology = itemTechnology(item);
  if (state.newsMode === "RELEVANT" && item.canonical_relevant !== true) return false;
  if (state.newsMode === "SOLAR" && technology !== "SOLAR") return false;
  if (state.newsMode === "BESS" && technology !== "BESS") return false;
  if (state.newsMode === "CONSENT" && event !== "CONSENT") return false;
  if (state.newsMode === "CONSTRUCTION" && event !== "CONSTRUCTION") return false;
  if (state.newsMode === "OPERATIONAL" && event !== "OPERATIONAL") return false;
  if (state.newsMode === "FINANCE" && !isFinanceEvent(event)) return false;
  if (state.newsQuery) {
    const haystack = normaliseProject([
      item.headline, item.canonical_project, item.project, item.operator, item.county,
      item.source, item.event, item.repd_ref, item.gg_project_id,
    ].join(" "));
    const tokens = normaliseProject(state.newsQuery).split(" ").filter(Boolean);
    if (!tokens.every((token) => haystack.includes(token))) return false;
  }
  return true;
}

export function drawNewsV9_5_1() {
  const stories = document.getElementById("stories");
  const rows = state.newsItems.filter(newsMatches);
  if (!rows.length) {
    stories.innerHTML = '<div class="news-empty">No headlines match this newspaper filter.</div>';
    return;
  }
  stories.innerHTML = rows.map((item) => {
    const technology = itemTechnology(item);
    const articleClass = technology === "BESS" ? "bess" : "solar";
    const project = item.canonical_project || item.project || "";
    const capacity = Number(item.canonical_capacity_mw ?? item.capacity_mw ?? 0);
    const quality = item.canonical_relevant === true
      ? `<span class="news-quality relevant">RELEVANT ${Number(item.confidence || 0)}%</span> · PRIMARY_MATCH · REPD ${escapeHtml(item.repd_ref)}`
      : '<span class="news-quality unverified">DISCOVERY ONLY</span> · no project signal';
    return `<a class="story ${articleClass}" href="${escapeHtml(item.url)}" target="_blank" rel="noopener"><div class="kicker">${escapeHtml(technology)} · ${escapeHtml(item.event || "PROJECT UPDATE")} · ${escapeHtml(item.published || "")}</div><h3>${escapeHtml(item.headline || project)}</h3><p><span class="project">${escapeHtml(project)}${capacity ? ` · ${capacity.toLocaleString("en-GB")} MW` : ""  … [line shortened here: 636 characters; full line on GitHub]
  }).join("");
}

function validPayload(payload) {
  return payload
    && payload.schema === "globalgrid2050.major-project-news.v9.5.1"
    && payload.release === "9.5.1"
    && Array.isArray(payload.all_items)
    && Array.isArray(payload.canonical_items)
    && payload.all_headline_count === payload.all_items.length
    && payload.relevant_headline_count === payload.canonical_items.length
    && payload.v9_4_baseline_headline_count === 125
    && payload.all_items.every((item) => typeof item.canonical_relevant === "boolean")
    && payload.canonical_items.every(canonicalItem)
    && payload.beacon_fen_contract?.repd_ref === "13599"
    && payload.beacon_fen_contract?.official_capacity_mw === 400;
}

function payloadTime(payload) {
  const timestamp = Date.parse(String(payload?.updated || ""));
  return Number.isFinite(timestamp) ? timestamp : 0;
}

async function fetchPayload(label, url) {
  const target = new URL(url, window.location.href);
  target.searchParams.set("v", Date.now());
  const response = await fetch(target, { cache: "no-store" });
  if (!response.ok) throw new Error(`${label} ${response.status}`);
  const data = await response.json();
  if (!validPayload(data)) throw new Error(`${label} invalid V9.5.1 payload`);
  return { label, data };
}

function renderNews(payload, label) {
  state.newsItems = payload.all_items;
  indexNewsItems(payload.canonical_items);
  document.getElementById("newsMeta").textContent = `${payload.relevant_headline_count} relevant / ${payload.all_headline_count} headlines · ${payload.v9_4_baseline_headline_count} V9.4 baseline retained · ${String(payload.updated || "").slice(0, 10)} · ${label}`;
  drawNewsV9_5_1();
  if (state.all.length) refreshProjects();
}

export async function loadNewsV9_5_1() {
  const settled = await Promise.allSettled(NEWS_SOURCES.map(([label, url]) => fetchPayload(label, url)));
  const good = settled.filter((result) => result.status === "fulfilled").map((result) => result.value);
  if (!good.length) {
    document.getElementById("stories").innerHTML = '<div class="news-empty">V9.5.1 newspaper unavailable. REPD analytics below remain live.</div>';
    document.getElementById("newsMeta").textContent = "newspaper unavailable";
    return;
  }
  good.sort((left, right) => payloadTime(right.data) - payloadTime(left.data)
    || right.data.all_items.length - left.data.all_items.length);
  renderNews(good[0].data, good[0].label);
}

export function bindNewspaperV9_5_1(onNewsLoaded) {
  refreshProjects = onNewsLoaded;
  document.querySelectorAll("#newsTools button").forEach((button) => {
    button.onclick = () => {
      document.querySelectorAll("#newsTools button").forEach((candidate) => candidate.classList.remove("active"));
      button.classList.add("active");
      state.newsMode = button.dataset.news;
      drawNewsV9_5_1();
    };
  });
  document.getElementById("newsSearch").oninput = (event) => {
    state.newsQuery = event.target.value.trim();
    drawNewsV9_5_1();
  };
}