GLOBALGRID2050 / EXPLORE CODE

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

JavaScript Projects V9 5 1 and 4 more files

A JavaScript module in PipelineNews covering the Renewable Energy Planning Database (REPD) register, solar, battery storage (BESS) and wind, using EPSG:27700 and SHA-256, and uses data from the GridAtlas repository.

699 lines of JavaScript from pipelinenews, in 5 files. Topic: Electricity markets and data pipelines. Section 1059 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 News Regions transform · pipelinenews / ui/javascript/202608261742-news-regions.js lines 1–87
  2. JavaScript Canonical Projects V9 5 1 render · pipelinenews / ui/javascript/202608261754-canonical-projects-v9-5-1.js lines 1–33
  3. JavaScript Newspaper V9 5 1 render · pipelinenews / ui/javascript/202608261755-newspaper-v9-5-1.js lines 1–163
  4. JavaScript Newspaper V9 6 2 render · pipelinenews / ui/javascript/202608261802-newspaper-v9-6-2.js lines 1–77
  5. JavaScript Projects V9 5 1 energy-data · pipelinenews / ui/javascript/202608261804-projects-v9-5-1.js lines 1–339

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 673126663b69f67c73dfed4f6393e56e7779514e612559f0b6aad88a4354037f
  • target sha256 dd8a50414632200f9022bb19b934df50dab3785f1f88cfeadb133a4a207ccaa5
  • group of 4 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

transformpipelinenews / ui/javascript/202608261742-news-regions.js · lines 1–87 of 87 · version 2026-08-26 17:42 · Not reached from any entry point (candidate for review) · 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 2 files: Compare V9 6 2 to Compiled (pipelinenews); JavaScript Newspaper V9 6 2 (pipelinenews).
What it achieves
Defines `distinctiveProjectTokens`, `ukEvidenceV9_6_2`, `technology` and 2 more.
Why it matters
Imported by JavaScript Newspaper V9 6 2. Run by Compare V9 6 2 to Compiled.
Application
pipelinenews · ui/javascript · JavaScript module
Uses
Testcode — Pipeline (import)
Used by
run by Compare V9 6 2 to Compiled (script call), 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 ui/javascript/202608261742-news-regions.js:1-87 · blob 80df6f8fad63e9aaeaa4a1e508c33f8a43fccddc · 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: duplicate_candidate
import { normaliseProject } from "./202608261630-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 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`).

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

Evidence
  • line-jaccard 0.9231 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609051152/pipeline/scripts/data/canonical-projects-v9-5-1.js:1-33 b632ccdf34f2ae41a2ddf39c3ed415726bee265a
  • sha256 4e6f3351576c898e0c1c3d5018ae40dd28b0e28a86cb9c513ea8b5e099118060
  • target sha256 7e4bd9108eeaeb1b557e1b4f6ef4d8053f4429a4df46d5e5c8f886c4da88029b
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

renderpipelinenews / ui/javascript/202608261754-canonical-projects-v9-5-1.js · lines 1–33 of 33 · version 2026-08-26 17:54 · Not reached from any entry point (candidate for review) · 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 release.v9.5.1.json.
Downstream impact
Used directly by 2 files: Compare V9 6 2 to Compiled (pipelinenews); JavaScript Projects V9 5 1 (pipelinenews).
What it achieves
Defines `invariant`, `fetchRelease` and `loadCanonicalProjectsV9_5_1`.
Why it matters
Imported by JavaScript Projects V9 5 1. Run by Compare V9 6 2 to Compiled.
Application
pipelinenews · ui/javascript · JavaScript module
Uses
Canonical Projects V9 1 (import)
Used by
run by Compare V9 6 2 to Compiled (script call), 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 ui/javascript/202608261754-canonical-projects-v9-5-1.js:1-33 · blob 9f186b02031d9420fb2f997699487cf8f15ea561 · 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: duplicate_candidate
import { loadCanonicalProjectsV9_1 } from "./202608261752-canonical-projects-v9-1.js";

const RELEASE_URL = "contracts/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 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, and uses data from the GlobalGrid2050 repository.

Set aside from the main view: 95% 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). 95% 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.9512 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609051152/pipeline/scripts/plugins/newspaper-v9-5-1.js:1-163 c990407d2fd47ccfd9b94ab7c34230dce6741007
  • sha256 9a3436bae58d3a982285c2caf77830b11f0a157a99255b623cd822c89bf81549
  • target sha256 f0925133d5d29113b113d241ccee5869bf9484a7319050913d7cd6b9cec5cf86
  • group of 4 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

renderpipelinenews / ui/javascript/202608261755-newspaper-v9-5-1.js · lines 1–163 of 163 · version 2026-08-26 17:55 · Not reached from any entry point (candidate for review) · 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: data source: globalgrid2050 data; JSON file major_project_news_v9_5_1.json.
Downstream impact
Used directly by 3 files: Compare V9 6 2 to Compiled (pipelinenews); JavaScript Newspaper V9 6 2 (pipelinenews); JavaScript Projects V9 5 1 (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 JavaScript Newspaper V9 6 2 and JavaScript Projects V9 5 1. Run by Compare V9 6 2 to Compiled.
Application
pipelinenews · ui/javascript · JavaScript module
Uses
State (import), Testcode — Pipeline (import)
Used by
run by Compare V9 6 2 to Compiled (script call), 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 ui/javascript/202608261755-newspaper-v9-5-1.js:1-163 · blob 17508c9a3ec6e6f81de9abbda2655f15e2673807 · 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: duplicate_candidate
import { state } from "./202608261632-state.js";
import { escapeHtml, isFinanceEvent, normaliseProject } from "./202608261630-utils.js";

const NEWS_SOURCES = Object.freeze([
  ["Pages", "../../dist/major_project_news_v9_5_1.json"],
  ["GitHub main", "https://raw.githubusercontent.com/Ventusltd/globalgrid2050/main/dist/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();
  };
}

JavaScript Newspaper V9 6 2

A JavaScript module in PipelineNews that queries matches (`queryMatches`) and draws regional (`drawRegional`) and news v9 (`drawNewsV9_6_2`), covering solar and battery storage (BESS).

renderpipelinenews / ui/javascript/202608261802-newspaper-v9-6-2.js · lines 1–77 of 77 · version 2026-08-26 18:02 · Not reached from any entry point (candidate for review) · pattern drawRegional (shared by 7 files)

What it does
It draws solar and battery storage (BESS). Defines 6 functions or classes, including queryMatches, regionalRows, drawRegional, drawNewsV9_6_2, loadNewsV9_6_2. Side effects: changes the web page (DOM).
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 2 files: Compare V9 6 2 to Compiled (pipelinenews); JavaScript App V9 6 2 (pipelinenews).
What it achieves
It queries matches (`queryMatches`), draws regional (`drawRegional`) and draws news v9 (`drawNewsV9_6_2`). Defines `queryMatches`, `regionalRows`, `drawRegional` and 3 more.
Why it matters
Imported by JavaScript App V9 6 2. Run by Compare V9 6 2 to Compiled.
Application
pipelinenews · ui/javascript · JavaScript module
Uses
State (import), Testcode — Pipeline (import), JavaScript News Regions (import), JavaScript Newspaper V9 5 1 (import)
Used by
run by Compare V9 6 2 to Compiled (script call), imported by JavaScript App V9 6 2 (import)
Produces
drawNewsV9_6_2, loadNewsV9_6_2, bindNewspaperV9_6_2
Defines here
queryMatches, regionalRows, drawRegional, drawNewsV9_6_2, loadNewsV9_6_2, bindNewspaperV9_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 ui/javascript/202608261802-newspaper-v9-6-2.js:1-77 · blob 049b634e9dfa635031d3fd67aec6d4bd5083c77f · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
import { state } from "./202608261632-state.js";
import { escapeHtml, normaliseProject } from "./202608261630-utils.js";
import { classifyInternationalV9_6_2, regionalCountsV9_6_2 } from "./202608261742-news-regions.js";
import { bindNewspaperV9_5_1, drawNewsV9_5_1, loadNewsV9_5_1 } from "./202608261755-newspaper-v9-5-1.js";

const REGIONAL_MODES = new Set(["INTERNATIONAL", "US", "EUROPE"]);

function queryMatches(item) {
  if (!state.newsQuery) return true;
  const haystack = normaliseProject([
    item.headline, item.project, item.operator, item.source, item.event,
  ].join(" "));
  return normaliseProject(state.newsQuery).split(" ").filter(Boolean)
    .every((token) => haystack.includes(token));
}

function regionalRows() {
  return state.newsItems.flatMap((item) => {
    const classification = classifyInternationalV9_6_2(item);
    if (!classification || !queryMatches(item)) return [];
    if (state.newsMode === "US" && classification.region !== "US") return [];
    if (state.newsMode === "EUROPE" && classification.region !== "EUROPE") return [];
    return [{ item, classification }];
  });
}

function drawRegional() {
  const stories = document.getElementById("stories");
  const rows = regionalRows();
  if (!rows.length) {
    stories.innerHTML = '<div class="news-empty">No location-verified international solar or battery headlines match this filter.</div>';
    return;
  }
  stories.innerHTML = rows.map(({ item, classification }) => {
    const articleClass = classification.technology.includes("BESS") ? "bess" : "solar";
    const region = classification.region === "INTERNATIONAL_OTHER" ? "INTERNATIONAL" : classification.region;
    return `<a class="story ${articleClass}" href="${escapeHtml(item.url)}" target="_blank" rel="noopener"><div class="kicker">${escapeHtml(classification.technology)} · ${escapeHtml(item.event || "PROJECT UPDATE")} · ${escapeHtml(item.published || "")}</div><h3>${escapeHtml(item.headline || "International solar and storage update")}</h3><p><span class="project">${escapeHtml(region)}</span>${item.  … [line shortened here: 640 characters; full line on GitHub]
  }).join("");
}

export function drawNewsV9_6_2() {
  if (REGIONAL_MODES.has(state.newsMode)) {
    drawRegional();
    return;
  }
  if (state.newsMode === "UK") {
    state.newsMode = "RELEVANT";
    drawNewsV9_5_1();
    state.newsMode = "UK";
    return;
  }
  drawNewsV9_5_1();
}

export async function loadNewsV9_6_2() {
  await loadNewsV9_5_1();
  const counts = regionalCountsV9_6_2(state.newsItems);
  const uk = state.newsItems.filter((item) => item.canonical_relevant === true).length;
  document.getElementById("newsMeta").textContent = `${uk} UK · ${counts.international} international (${counts.us} US · ${counts.europe} Europe · ${counts.other} other) · ${state.newsItems.length} headlines · Pages`;
  drawNewsV9_6_2();
}

export function bindNewspaperV9_6_2(onNewsLoaded) {
  bindNewspaperV9_5_1(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_6_2();
    };
  });
  document.getElementById("newsSearch").oninput = (event) => {
    state.newsQuery = event.target.value.trim();
    drawNewsV9_6_2();
  };
}

JavaScript Projects V9 5 1

A JavaScript module in PipelineNews covering the Renewable Energy Planning Database (REPD) register, solar, battery storage (BESS) and wind, using EPSG:27700 and SHA-256, and uses data from the GridAtlas repository.

Set aside from the main view: 94% of its lines are the same as releases/javascript/202609010836-projects-v9-5-1.js (pipelinenews), which stays. (near-copy-of, proposed by families.py). 93% of lines shared with JavaScript Projects V9 5 1; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9375 to pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 releases/javascript/202609010836-projects-v9-5-1.js:1-336 a1bc729affef792c99b6466bc502df3e64bc7c68
  • sha256 16ce91d395bb4a14de51214b50d712ec4db0635473590d4c96f12afb846dd836
  • target sha256 6a8d72adf8a08460521cacd56ff8501ee1ac78b605318b6bb3f00a077e1ccd4d
  • group of 5 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

energy-datapipelinenews / ui/javascript/202608261804-projects-v9-5-1.js · lines 1–339 of 339 · version 2026-08-26 18:04 · Not reached from any entry point (candidate for review) · pattern gridAnalyticsEngine (shared by 2 files)

What it does
It draws the REPD register, solar, battery storage (BESS) and wind. Defines 21 functions or classes, including gridAnalyticsEngineV1, atlasUrlV9_5_1, displayDate, repdUpdatedTimestamp, compareProjectUpdatesV9_5_1. Side effects: changes the web page (DOM).
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, solar, battery storage (BESS), wind.
Inputs & outputs
Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326.
Downstream impact
Used directly by 2 files: Compare V9 6 2 to Compiled (pipelinenews); JavaScript App V9 6 2 (pipelinenews).
What it achieves
It compares project updates v9 (`compareProjectUpdatesV9_5_1`), updates sort header (`updateSortHeader`) and renders table (`renderTable`). 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 events.
Why it matters
Imported by JavaScript App V9 6 2. Run by Compare V9 6 2 to Compiled.
Application
pipelinenews · ui/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
Testcode — Pipeline (import), State (import), Project Filter V9 2 (import), JavaScript Canonical Projects V9 5 1 (import), Gauges V9 2 (import), JavaScript Newspaper V9 5 1 (import)
Used by
run by Compare V9 6 2 to Compiled (script call), imported by JavaScript App V9 6 2 (import)
Produces
gridAnalyticsEngineV1, atlasUrlV9_5_1, compareProjectUpdatesV9_5_1, loadProjectsV9_5_1, refreshProjectsV9_5_1, bindProjectControlsV9_5_1
Defines here
gridAnalyticsEngineV1, atlasUrlV9_5_1, displayDate, repdUpdatedTimestamp, compareProjectUpdatesV9_5_1, updateSortHeader, relationshipSummary, renderTable, updateResultSummary, syncFilterUrl, apply, populateCounties, setButtonState, hydrateFiltersFromUrl, csvCell, downloadCsv, clearFilters, copyProjectId, loadProjectsV9_5_1, refreshProjectsV9_5_1, bindProjectControlsV9_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 ui/javascript/202608261804-projects-v9-5-1.js:1-339 · blob ea87579915aecfd9edaea4c2409f98f52ff6015b · GitHub at these lines
State
achieves: code · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
import { escapeHtml } from "./202608261630-utils.js";
import { state } from "./202608261632-state.js";
import {
  buildProjectSearchTextV9_2,
  projectMatchesV9_2,
  summariseProjectsV9_2,
  tokeniseSearchV9_2,
} from "./202608261640-filters.js";
import { loadCanonicalProjectsV9_5_1 } from "./202608261754-canonical-projects-v9-5-1.js";
import {
  formatCapacityV9_2,
  formatLargestV9_2,
  setGaugeUniverseV9_2,
  updateGaugesV9_2,
} from "./202608261725-gauges.js";
import { signalForProjectV9_5_1 } from "./202608261755-newspaper-v9-5-1.js";

const LABELS = Object.freeze({
  solar: "Solar",
  bess: "Battery Storage",
  wind_onshore: "Onshore Wind",
  wind_offshore: "Offshore Wind",
});
const COLOURS = Object.freeze({ solar: "#ffff00", bess: "#ffae00", wind_onshore: "#00ffff", wind_offshore: "#0066ff" });
const UNITS = Object.freeze({ solar: "MWp", bess: "MW", wind_onshore: "MW", wind_offshore: "MW" });
const ALLOWED_TECHNOLOGIES = new Set(["all", "solar", "bess", "wind_onshore", "wind_offshore"]);
const ALLOWED_STATUSES = new Set(["All", "Operational", "Under Construction", "Awaiting Construction", "Application Submitted"]);
const ALLOWED_SORTS = new Set(["capacity_desc", "updated_desc", "updated_asc"]);

// The row declares which Ventus cable question the MAP action will answer.
// Keep this deterministic and derived from the canonical technology; the Atlas
// must not infer a different engine after arrival.
export function gridAnalyticsEngineV1(project) {
  const explicit = String(project?.grid_engine || "").trim();
  if (explicit) return explicit;
  const technology = String(project?.technology || "").trim().toLowerCase();
  if (technology === "wind_offshore") return "VENTUS OFFSHORE DETERMINISTIC";
  if (technology === "interconnector") return "VENTUS INTERCONNECTOR";
  return "VENTUS ONSHORE";
}

let all = [];
let filtered = [];
let metadata = null;
let release = null;
let searchIndex = new Map();
let technology = "all";
let status = "All";
let county = "All";
let query = "";
let sortMode = "capacity_desc";
let controlsBound = false;

export function atlasUrlV9_5_1(project) {
  if (project.geometry_status !== "valid") return "";
  const url = new URL("https://ventusltd.github.io/gridatlas/202608300453-atlas-v9/");
  url.searchParams.set("repd_ref", project.repd_ref);
  url.searchParams.set("project", project.name);
  url.searchParams.set("technology", project.technology);
  url.searchParams.set("grid_engine", gridAnalyticsEngineV1(project));
  url.searchParams.set("capacity_mw", project.capacity_mw);
  url.searchParams.set("latitude", project.latitude);
  url.searchParams.set("longitude", project.longitude);
  url.searchParams.set("zoom", "12");
  return url.href;
}

function displayDate(value) {
  if (!value) return "not supplied by REPD";
  const [year, month, day] = String(value).split("-");
  return year && month && day ? `${day}/${month}/${year}` : String(value);
}

function repdUpdatedTimestamp(project) {
  if (!project.repd_record_updated) return null;
  const value = Date.parse(`${project.repd_record_updated}T00:00:00Z`);
  return Number.isFinite(value) ? value : null;
}

export function compareProjectUpdatesV9_5_1(left, right, direction = "desc") {
  const leftTime = repdUpdatedTimestamp(left);
  const rightTime = repdUpdatedTimestamp(right);
  if (leftTime === null && rightTime === null) return 0;
  if (leftTime === null) return 1;
  if (rightTime === null) return -1;
  return direction === "asc" ? leftTime - rightTime : rightTime - leftTime;
}

function updateSortHeader() {
  const header = document.getElementById("repdUpdatedHeader");
  const button = document.getElementById("sortUpdated");
  const indicator = document.getElementById("updatedSortIndicator");
  if (!header || !button || !indicator) return;
  if (sortMode === "updated_desc") {
    header.setAttribute("aria-sort", "descending");
    indicator.textContent = "▼";
    button.setAttribute("aria-label", "REPD updated date sorted newest first; click for oldest first");
    button.title = "Newest first — click for oldest first";
    return;
  }
  if (sortMode === "updated_asc") {
    header.setAttribute("aria-sort", "ascending");
    indicator.textContent = "▲";
    button.setAttribute("aria-label", "REPD updated date sorted oldest first; click for newest first");
    button.title = "Oldest first — click for newest first";
    return;
  }
  header.setAttribute("aria-sort", "none");
  indicator.textContent = "↕";
  button.setAttribute("aria-label", "Sort by REPD updated date, newest first");
  button.title = "Click for newest first";
}

function relationshipSummary(project) {
  const development = Array.isArray(project.development_repd_refs) ? project.development_repd_refs.length : 0;
  const direct = Array.isArray(project.direct_related_repd_refs) ? project.direct_related_repd_refs.length : 0;
  const siblings = Array.isArray(project.planning_sibling_repd_refs) ? project.planning_sibling_repd_refs.length : 0;
  return `${development} development · ${direct} direct · ${siblings} planning sibling record(s)`;
}

function renderTable() {
  const body = document.getElementById("tbody");
  body.innerHTML = filtered.map((project) => {
    const label = LABELS[project.technology];
    const gridEngine = gridAnalyticsEngineV1(project);
    const unit = UNITS[project.technology];
    const location = [project.county, project.region].filter(Boolean).join(" · ");
    const signal = signalForProjectV9_5_1(project);
    const news = new URL("https://www.google.com/search");
    news.searchParams.set("q", `${project.name} ${label} UK`);
    news.searchParams.set("tbm", "nws");
    const atlas = atlasUrlV9_5_1(project);
    const mapAction = atlas
      ? `<a class="action-link atlaslink" target="_blank" rel="noopener" href="${escapeHtml(atlas)}">MAP ↗</a>`
      : '<span class="action-disabled" title="REPD geometry is unavailable; the record remains searchable and exportable">NO MAP</span>';
    const planning = project.planning_application_reference || "not supplied by REPD";
    const authority = project.planning_authority || "not supplied by REPD";
    const developmentId = project.gg_development_id || "not assigned";
    const updated = displayDate(project.repd_record_updated);
    return `<tr id="repd-${escapeHtml(project.repd_ref)}" data-repd-updated="${escapeHtml(project.repd_record_updated || "")}"><td class="site">${escapeHtml(project.name)}<div class="project-meta">REPD ${escapeHtml(project.repd_ref)} · ${escapeHtml(project.gg_project_id)} · UPDATED ${escapeHtml(updated)}</div><div class="mobile-extra">${escapeHtml([location, project.operator].filter(Boolean).join(  … [line shortened here: 2,174 characters; full line on GitHub]
  }).join("");
}

function updateResultSummary() {
  const summary = summariseProjectsV9_2(filtered);
  const element = document.getElementById("resultsMeta");
  element.textContent = `${summary.count.toLocaleString("en-GB")} of ${all.length.toLocaleString("en-GB")} records · ${formatCapacityV9_2(summary.capacity_mw)} MW · largest ${formatLargestV9_2(summary.largest_mw)} MW`;
  element.classList.toggle("is-filtered", summary.count !== all.length);
  element.dataset.filteredCount = String(summary.count);
  element.dataset.totalCount = String(all.length);
}

function syncFilterUrl() {
  const url = new URL(window.location.href);
  for (const parameter of ["technology", "status", "county", "q", "sort"]) url.searchParams.delete(parameter);
  if (technology !== "all") url.searchParams.set("technology", technology);
  if (status !== "All") url.searchParams.set("status", status);
  if (county !== "All") url.searchParams.set("county", county);
  if (query) url.searchParams.set("q", query);
  if (sortMode !== "capacity_desc") url.searchParams.set("sort", sortMode);
  history.replaceState(null, "", url);
}

function apply({ syncUrl = true } = {}) {
  const tokens = tokeniseSearchV9_2(query);
  filtered = all.filter((project) => projectMatchesV9_2(project, {
    technology,
    status,
    county,
    tokens,
  }, searchIndex.get(project.repd_ref)));
  if (sortMode === "updated_desc") filtered.sort((left, right) => compareProjectUpdatesV9_5_1(left, right, "desc"));
  if (sortMode === "updated_asc") filtered.sort((left, right) => compareProjectUpdatesV9_5_1(left, right, "asc"));
  state.filtered = filtered;
  updateGaugesV9_2(filtered);
  renderTable();
  updateResultSummary();
  updateSortHeader();
  if (syncUrl) syncFilterUrl();
}

function populateCounties() {
  const select = document.getElementById("county");
  select.replaceChildren(new Option("🌍 ALL COUNTIES", "All"));
  [...new Set(all.map((project) => project.county).filter(Boolean))]
    .sort((left, right) => left.localeCompare(right, "en-GB"))
    .forEach((value) => select.add(new Option(`📍 ${value}`, value)));
}

function setButtonState(container, dataKey, selected) {
  document.querySelectorAll(`${container} .btn`).forEach((button) => {
    const active = button.dataset[dataKey] === selected;
    button.classList.toggle("active", active);
    button.setAttribute("aria-pressed", String(active));
  });
}

function hydrateFiltersFromUrl() {
  const parameters = new URLSearchParams(window.location.search);
  const requestedTechnology = parameters.get("technology") || "all";
  const requestedStatus = parameters.get("status") || "All";
  const requestedCounty = parameters.get("county") || "All";
  const requestedSort = parameters.get("sort") || "capacity_desc";
  technology = ALLOWED_TECHNOLOGIES.has(requestedTechnology) ? requestedTechnology : "all";
  status = ALLOWED_STATUSES.has(requestedStatus) ? requestedStatus : "All";
  county = [...document.getElementById("county").options].some((option) => option.value === requestedCounty)
    ? requestedCounty
    : "All";
  query = parameters.get("q") || "";
  sortMode = ALLOWED_SORTS.has(requestedSort) ? requestedSort : "capacity_desc";
  setButtonState("#tech", "technology", technology);
  setButtonState("#status", "officialStatus", status);
  document.getElementById("county").value = county;
  document.getElementById("search").value = query;
  document.getElementById("sortProjects").value = sortMode;
}

function csvCell(value) {
  let text = value === null || value === undefined ? "" : String(value);
  if (/^(?:[=+\-@]|\s+[=+\-@]|\t|\r|\n)/u.test(text)) text = `'${text}`;
  return `"${text.replaceAll('"', '""')}"`;
}

function downloadCsv(event) {
  event.preventDefault();
  const headers = ["Site Name", "REPD Ref", "GlobalGrid Project ID", "GlobalGrid Development ID", "Identity Status", "Identity Confidence", "Technology", "Grid Analytics Engine", "Official REPD Technology", "Official REPD Capacity", "Capacity Unit", "Official REPD Status", "Derived Lifecycle", "Operator or Applicant", "County", "Region", "Country", "Planning Authority", "Planning Application Refer  … [line shortened here: 1,155 characters; full line on GitHub]
  const rows = filtered.map((project) => {
    const signal = signalForProjectV9_5_1(project);
    return [project.name, project.repd_ref, project.gg_project_id, project.gg_development_id, project.identity_status, project.identity_confidence, LABELS[project.technology], gridAnalyticsEngineV1(project), project.repd_technology, project.capacity_mw, UNITS[project.technology], project.status, project.lifecycle, project.operator, project.county, project.region, project.country, project.planning_  … [line shortened here: 1,424 characters; full line on GitHub]
  });
  const content = `\ufeff${[headers, ...rows].map((row) => row.map(csvCell).join(",")).join("\r\n")}`;
  const url = URL.createObjectURL(new Blob([content], { type: "text/csv;charset=utf-8" }));
  const anchor = document.createElement("a");
  anchor.href = url;
  anchor.download = `globalgrid2050_uk_renewables_pipeline_v9_5_1_${new Date().toISOString().slice(0, 10)}.csv`;
  anchor.click();
  URL.revokeObjectURL(url);
  document.getElementById("exportMeta").textContent = `${filtered.length.toLocaleString("en-GB")} filtered records exported`;
}

function clearFilters(event) {
  event.preventDefault();
  technology = "all";
  status = "All";
  county = "All";
  query = "";
  sortMode = "capacity_desc";
  setButtonState("#tech", "technology", technology);
  setButtonState("#status", "officialStatus", status);
  document.getElementById("county").value = county;
  document.getElementById("search").value = "";
  document.getElementById("sortProjects").value = sortMode;
  apply();
}

async function copyProjectId(button) {
  const value = button.dataset.copyId;
  try {
    await navigator.clipboard.writeText(value);
  } catch {
    const field = document.createElement("textarea");
    field.value = value;
    field.setAttribute("readonly", "");
    field.style.position = "fixed";
    field.style.opacity = "0";
    document.body.appendChild(field);
    field.select();
    document.execCommand("copy");
    field.remove();
  }
  const original = button.textContent;
  button.textContent = "COPIED";
  button.classList.add("copied");
  setTimeout(() => {
    button.textContent = original;
    button.classList.remove("copied");
  }, 1200);
}

export async function loadProjectsV9_5_1() {
  try {
    const model = await loadCanonicalProjectsV9_5_1();
    all = [...model.projects];
    filtered = all;
    metadata = model.metadata;
    release = model.release;
    searchIndex = new Map(all.map((project) => [project.repd_ref, buildProjectSearchTextV9_2(project)]));
    state.all = all;
    state.filtered = filtered;
    state.canonicalModel = model;
    setGaugeUniverseV9_2(all);
    populateCounties();
    hydrateFiltersFromUrl();
    apply({ syncUrl: false });
    document.getElementById("releaseMeta").textContent = `V9.5.1 interface · V${release.data_parent.release} canonical data spine · all ${all.length.toLocaleString("en-GB")} qualifying records loaded`;
  } catch (error) {
    console.error(error);
    document.getElementById("tbody").innerHTML = '<tr><td colspan="11" style="text-align:center;color:#ff6666">Canonical Q2 REPD data unavailable. V9.5.1 has failed closed.</td></tr>';
    document.getElementById("resultsMeta").textContent = "canonical data unavailable";
  }
}

export function refreshProjectsV9_5_1() {
  if (metadata) renderTable();
}

export function bindProjectControlsV9_5_1() {
  if (controlsBound) return;
  controlsBound = true;
  document.querySelectorAll("#tech .btn").forEach((button) => {
    button.onclick = () => {
      technology = button.dataset.technology;
      setButtonState("#tech", "technology", technology);
      apply();
    };
  });
  document.querySelectorAll("#status .btn").forEach((button) => {
    button.onclick = () => {
      status = button.dataset.officialStatus;
      setButtonState("#status", "officialStatus", status);
      apply();
    };
  });
  document.getElementById("county").onchange = (event) => { county = event.target.value; apply(); };
  document.getElementById("sortProjects").onchange = (event) => { sortMode = event.target.value; apply(); };
  document.getElementById("sortUpdated").onclick = () => {
    sortMode = sortMode === "updated_desc" ? "updated_asc" : "updated_desc";
    document.getElementById("sortProjects").value = sortMode;
    apply();
  };
  document.getElementById("search").oninput = (event) => { query = event.target.value.trim(); apply(); };
  document.getElementById("export").onclick = downloadCsv;
  document.getElementById("exportInline").onclick = downloadCsv;
  document.getElementById("clearFilters").onclick = clearFilters;
  document.getElementById("tbody").addEventListener("click", (event) => {
    const button = event.target.closest(".copy-id");
    if (button) copyProjectId(button);
  });
}