GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / pipelinenews / releases/202611132345-pipelinenews/assets

Releases — PipelineNews (part 3)

A JavaScript module in the assets folder covering engine graph, the Renewable Energy Planning Database (REPD) register and postcodes, using EPSG:27700 and SHA-256, and uses data from the ventus-grid-engine repository.

682 lines of JavaScript from pipelinenews, in 1 file. Topic: Electricity markets and data pipelines. Section 1027 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. Releases — PipelineNews energy-data · pipelinenews / releases/202611132345-pipelinenews/assets/202608291447-app.mjs lines 1401–2082

Releases — PipelineNews

A JavaScript module in the assets folder covering engine graph, the Renewable Energy Planning Database (REPD) register and postcodes, using EPSG:27700 and SHA-256, and uses data from the ventus-grid-engine repository.

energy-datapipelinenews / releases/202611132345-pipelinenews/assets/202608291447-app.mjs · lines 1401–2082 of 2082 · version 2026-08-29 14:47 (continued from section 1025) · Entry point · pattern bindProvisionalProjects (shared by 2 files)

What it does
It draws engine graph, the REPD register, postcodes and substations. Defines 92 functions or classes, including localityFor, gridFor, substationFor, metricChip, gridActionHtml. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (path 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, postcodes, substations, 132kV, 33kV, 11kV.
Inputs & outputs
In: data source: ventus-grid-engine data; JSON file 202608291447-registry.json; JSON file engine-graph.json. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326. Voltage levels named: 132kV, 33kV, 11kV.
Downstream impact
Used directly by 1 file: Releases — PipelineNews Page (pipelinenews, https://ventusltd.github.io/pipelinenews/releases/202611132345-pipelinenews/).
What it achieves
It compares text (`compareText`), fetches queue (`FetchQueue`) and hashes JSON (`hashJson`). Its `downloadCsv` function gives CSV download or refusal from active table owner, filtered register rows and official detail partitions (VEDIC: export filtered projects). Its code works with 33 kV, 1 MW and 11 kV. It responds to click, change and input events.
Why it matters
Loaded by the page of the same name at https://ventusltd.github.io/pipelinenews/releases/202611132345-pipelinenews/.
Application
pipelinenews · releases/202611132345-pipelinenews/assets · 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
PipelineNews Atlas Pointer Deep Link (import)
Used by
loaded by Releases — PipelineNews Page (script src)
Produces
localityFor, gridFor, substationFor, metricChip, gridActionHtml, substationActionHtml, compareText, FetchQueue, escapeHtml, normalise, invariant, arraysEqual
Defines here
bindNewsControls, loadNews, newsBound, newsSector, createGauge, loadCharts, openSectorIntelligence, bindSectorIntelligence, openFederatedRelationships, bindFederatedRelationships, scheduleOptionalLoads, openProjectIntelligence, bindProjectIntelligence, openGridProximity, bindGridProximity, loadSubstation33kv, loadGridDistance, loadLocality, openGbElectricityContext, bindGbElectricityContext, openWiderFleet, engineGenome, engineFocusHref, renderEngineNodes, bindEstateLinks, bindWiderFleet, bindProvisionalProjects, bindBbcRssIntelligence, 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/202611132345-pipelinenews/assets/202608291447-app.mjs:1401-2082 · blob c117027cd73a354235c49f217b1cbe780becca50 · 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
  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");
    // BOUND keeps its caption; SECTOR is real trade news with no project
    // established, so it carries none. Everything else goes.
    //
    // The sector test reads the headline, which is an inference and is treated
    // as one: it decides what to SHOW, and is never used to claim a story is
    // about a project.
    const NEWS_SECTOR = /\b(solar|pv|photovolta|battery|bess|storage|ldes|grid|inverter|substation|transmission|curtail|ppa|renewab|wind|electrolys|interconnector|flexibilit|flexitricity|energy hub|energy park|power plant|megawatt|data ?centres?|datacentres?|data ?centers?)\b/i;
    const NEWS_CAPACITY = /\b\d[\d,.]*\s?(mw|mwh|gw|gwh|kw)\b/i;
    const NEWS_OFFTOPIC = /\b(care home|care centre|care award|ring road|dibden|solent gateway)\b/i;
    // Engineering and business only. Geopolitics is somebody else's page.
    const NEWS_NEUTRAL = /\b(iran|ukraine|russia|israel|gaza|war|sanction|missile|conflict)\b/i;

    const newsBound = (row) =>
      row[NEWS_FIELD.eligible] === true
      && row[NEWS_FIELD.canonical] === true
      && String(row[NEWS_FIELD.role] || "") === "PRIMARY_MATCH"
      && String(row[NEWS_FIELD.repdRef] || "").trim() !== "";

    const newsSector = (row) => {
      const headline = String(row[NEWS_FIELD.headline] || "");
      if (NEWS_OFFTOPIC.test(headline) || NEWS_NEUTRAL.test(headline)) return false;
      return NEWS_SECTOR.test(headline) || NEWS_CAPACITY.test(headline);
    };

    const allNews = payload.rows;
    newsRows = allNews.filter((row) => newsBound(row) || newsSector(row));
    runtimeEvidence.newsBound = allNews.filter(newsBound).length;
    runtimeEvidence.newsSector = newsRows.length - runtimeEvidence.newsBound;
    runtimeEvidence.newsDropped = allNews.length - newsRows.length;
    runtimeEvidence.newsReady = true;
    document.getElementById("newsMeta").textContent =
      `${runtimeEvidence.newsBound.toLocaleString("en-GB")} bound to a REPD project · `
      + `${runtimeEvidence.newsSector.toLocaleString("en-GB")} sector headlines, no project binding · `
      + `${runtimeEvidence.newsDropped.toLocaleString("en-GB")} withheld as off-topic · 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_clean
    || 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 === entry.generation, "sector cartridge identity changed");
  const result = cartridge.mountSectorIntelligence({
    host,
    payloadAsset: {
      ...entry.payload,
      url: entry.payload.path,
    },
  });
  runtimeEvidence.sectorPayloadRequestsAtMount = result.payloadRequests;
  invariant(runtimeEvidence.sectorPayloadRequestsAtMount === 0, "sector payload requested at mount");
  meta.textContent = "WAIT · one evidenced topic · choose it 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";
  }));
}

async function openFederatedRelationships() {
  const button = document.getElementById("federatedRelationshipOpen");
  const host = document.getElementById("federatedRelationshipHost");
  const meta = document.getElementById("federatedRelationshipMeta");
  invariant(button && host && meta, "federated relationship controls are missing");
  if (host.dataset.federatedRelationshipState === "ready") {
    host.hidden = !host.hidden;
    button.setAttribute("aria-expanded", String(!host.hidden));
    return;
  }
  if (host.dataset.federatedRelationshipState === "loading") return;
  const entry = registry.supplemental_assets?.relationship_governance_status;
  invariant(entry?.activation === "dynamic-import-on-user-open; projection-fetch-after-explicit-open", "relationship activation changed");
  invariant(entry.rows === 3 && entry.project_bindings === 0 && entry.eligible_for_join_rows === 0, "relationship boundary changed");
  host.hidden = false;
  host.dataset.federatedRelationshipState = "loading";
  button.setAttribute("aria-expanded", "true");
  meta.textContent = "LOAD · importing controls and verifying one compact payload";
  runtimeEvidence.federatedRelationshipImports += 1;
  invariant(runtimeEvidence.federatedRelationshipImports === 1, "relationship cartridge imported more than once");
  const cartridge = await import(`./${entry.cartridge.filename}`);
  invariant(cartridge.FEDERATED_RELATIONSHIP_CARTRIDGE_CONTRACT.generation === entry.generation, "relationship cartridge identity changed");
  const result = await cartridge.mountFederatedRelationships({
    host,
    payloadAsset: {
      ...entry.payload,
      url: entry.payload.path.replace(/^releases\//u, ""),
    },
  });
  runtimeEvidence.federatedRelationshipPayloadRequests += result.payloadRequests;
  invariant(runtimeEvidence.federatedRelationshipPayloadRequests === 1 && result.projectBindings === 0, "relationship request or binding boundary changed");
  meta.textContent = "OK · 3 governance rows · all ABSTAIN · zero project bindings";
}

function bindFederatedRelationships() {
  const button = document.getElementById("federatedRelationshipOpen");
  invariant(button, "relationship opener is missing");
  button.addEventListener("click", () => openFederatedRelationships().catch((error) => {
    console.error("federated relationships", error);
    document.getElementById("federatedRelationshipMeta").textContent = "FAIL · relationship evidence unavailable; core product unchanged";
    document.getElementById("federatedRelationshipHost").dataset.federatedRelationshipState = "failed";
  }));
}

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 openProjectIntelligence() {
  const button = document.getElementById("projectIntelOpen");
  const host = document.getElementById("projectIntelHost");
  const meta = document.getElementById("projectIntelMeta");
  invariant(button && host && meta, "project-intelligence controls are missing");
  if (host.dataset.projectIntelligenceState === "ready") {
    host.hidden = !host.hidden;
    button.setAttribute("aria-expanded", String(!host.hidden));
    return;
  }
  if (host.dataset.projectIntelligenceState === "loading") return;
  const entry = registry.supplemental_assets?.project_intelligence;
  invariant(entry?.activation === "dynamic-import-on-user-open; payload-fetch-on-first-tab-selection", "project intelligence activation changed");
  invariant(entry.project_bindings === 0 && entry.eligible_for_news_signal === false, "project intelligence binding boundary changed");
  host.hidden = false;
  host.dataset.projectIntelligenceState = "loading";
  button.setAttribute("aria-expanded", "true");
  meta.textContent = "LOAD \u00b7 importing derived controls; no payload requested";
  runtimeEvidence.projectIntelligenceImports += 1;
  invariant(runtimeEvidence.projectIntelligenceImports === 1, "project intelligence cartridge imported more than once");
  const cartridge = await import(`./${entry.cartridge.filename}`);
  invariant(cartridge.PROJECT_INTELLIGENCE_CARTRIDGE_CONTRACT.generation === entry.generation, "project intelligence cartridge identity changed");
  invariant(cartridge.PROJECT_INTELLIGENCE_CARTRIDGE_CONTRACT.additive_only === true, "project intelligence cartridge is no longer additive-only");
  const result = cartridge.mountProjectIntelligence({
    host,
    payloadAsset: { ...entry.payload, url: entry.payload.path },
  });
  runtimeEvidence.projectIntelligencePayloadRequests = result.payloadRequests;
  invariant(runtimeEvidence.projectIntelligencePayloadRequests === 0 && result.projectBindings === 0, "project intelligence payload requested at mount, or a binding appeared");
  host.dataset.projectIntelligenceState = "ready";
  meta.textContent = "WAIT \u00b7 five tabs \u00b7 choose one to request the compact derived index";
}

function bindProjectIntelligence() {
  const button = document.getElementById("projectIntelOpen");
  invariant(button, "project-intelligence opener is missing");
  button.addEventListener("click", () => openProjectIntelligence().catch((error) => {
    console.error("project intelligence", error);
    document.getElementById("projectIntelMeta").textContent = "FAIL \u00b7 project intelligence unavailable; core product unchanged";
    document.getElementById("projectIntelHost").dataset.projectIntelligenceState = "failed";
  }));
}

async function openGridProximity() {
  const button = document.getElementById("gridProximityOpen");
  const host = document.getElementById("gridProximityHost");
  const meta = document.getElementById("gridProximityMeta");
  invariant(button && host && meta, "grid-proximity controls are missing");
  if (host.dataset.gridProximityState === "ready") {
    host.hidden = !host.hidden;
    button.setAttribute("aria-expanded", String(!host.hidden));
    return;
  }
  if (host.dataset.gridProximityState === "loading") return;
  const entry = registry.supplemental_assets?.grid_proximity;
  invariant(entry?.activation === "dynamic-import-on-user-open; payload-fetch-on-first-tab-selection", "grid proximity activation changed");
  invariant(entry.project_bindings === 0 && entry.eligible_for_news_signal === false, "grid proximity binding boundary changed");
  host.hidden = false;
  host.dataset.gridProximityState = "loading";
  button.setAttribute("aria-expanded", "true");
  meta.textContent = "LOAD \u00b7 importing derived controls; no payload requested";
  runtimeEvidence.gridProximityImports += 1;
  invariant(runtimeEvidence.gridProximityImports === 1, "grid proximity cartridge imported more than once");
  const cartridge = await import(`./${entry.cartridge.filename}`);
  invariant(cartridge.GRID_PROXIMITY_CARTRIDGE_CONTRACT.generation === entry.generation, "grid proximity cartridge identity changed");
  invariant(cartridge.GRID_PROXIMITY_CARTRIDGE_CONTRACT.additive_only === true, "grid proximity cartridge is no longer additive-only");
  const result = cartridge.mountGridProximity({
    host,
    payloadAsset: { ...entry.payload, url: entry.payload.path },
  });
  runtimeEvidence.gridProximityPayloadRequests = result.payloadRequests;
  invariant(runtimeEvidence.gridProximityPayloadRequests === 0 && result.projectBindings === 0, "grid proximity payload requested at mount, or a binding appeared");
  host.dataset.gridProximityState = "ready";
  meta.textContent = "WAIT \u00b7 five tabs \u00b7 choose one to request the derived proximity index";
}

function bindGridProximity() {
  const button = document.getElementById("gridProximityOpen");
  invariant(button, "grid-proximity opener is missing");
  button.addEventListener("click", () => openGridProximity().catch((error) => {
    console.error("grid proximity", error);
    document.getElementById("gridProximityMeta").textContent = "FAIL \u00b7 grid proximity unavailable; core product unchanged";
    document.getElementById("gridProximityHost").dataset.gridProximityState = "failed";
  }));
}

async function loadSubstation33kv() {
  const entry = registry.supplemental_assets?.grid_actions_inline;
  if (!entry) return;
  try {
    runtimeEvidence.substationRequests += 1;
    const payload = await fetchImmutable(entry.payload.path);
    invariant(payload.schema === entry.payload.schema, "substation schema mismatch");
    invariant(payload.generation === entry.generation, "substation generation mismatch");
    invariant(payload.substation && typeof payload.substation === "object", "substation index missing");
    substation = payload.substation;
    runtimeEvidence.substationReady = true;
  } catch (error) {
    // A substation payload that will not load must not take the table with it.
    substation = null;
  }
}

async function loadGridDistance() {
  const entry = registry.supplemental_assets?.grid_distance_column;
  const note = document.getElementById("gridDistanceNote");
  if (!entry) {
    if (note) note.textContent = "GRID \u00b7 not in this release";
    return;
  }
  try {
    runtimeEvidence.gridDistanceRequests += 1;
    const payload = await fetchImmutable(entry.payload.path);
    invariant(payload.schema === entry.payload.schema, "grid-distance schema mismatch");
    invariant(payload.generation === entry.generation, "grid-distance generation mismatch");
    invariant(payload.grid && typeof payload.grid === "object", "grid-distance index missing");
    gridDistance = payload.grid;
    runtimeEvidence.gridDistanceReady = true;
    if (note) {
      const counts = payload.bands?.counts || {};
      const strong = (counts.STRONG || 0).toLocaleString("en-GB");
      note.textContent = `GRID + SUB \u00b7 BETA \u00b7 in the ACTIONS column, beside MAP \u00b7 `
        + `straight-line km to the nearest mapped circuit and to the nearest substation at 33 kV or above \u00b7 nearest mapped is not nearest: of the 886 transmission substations NESO names at 132 kV and above, the Atlas locates 502 and publishes the other 384 without coordinates rather than dropping them, so the nearest mapped substation may not be the nearest substation \u00b7 `
        + `${(payload.projects || 0).toLocaleString("en-GB")} projects measured, ${strong} within 2 km of a circuit \u00b7 no MVA rating is quoted here; the ratings the Atlas shows are per season, named, and never summed \u2014 NESO publishes a winter rating for all 1,392 circuits and a summer rating for 1,276, and summer differs from winter on 1,081 of those \u00b7 `
        + `not a cable route, and not headroom \u2014 fault level and thermal headroom need DNO network data such as source impedance and a connection study \u00b7 the published transmission network is now answerable: MAP opens the circuits that land at the declared site, their ratings in every season the operator publishes, how many circuits away its neighbours are, and where this output would fl  … [line shortened here: 427 characters; full line on GitHub]
      // The full scope of the BETA sits on hover rather than in the strip, so
      // the caveat is one gesture away without crowding the filter row.
      note.title = [
        payload.caveat?.distance,
        payload.caveat?.headroom,
        payload.caveat?.coverage,
        payload.beta?.not_covered?.length
          ? "Not covered in this beta: " + payload.beta.not_covered.join("; ")
          : "",
        payload.earth_model
          ? `Measured on ${payload.earth_model.formula} at R = ${payload.earth_model.radius_km} km using ${payload.earth_model.implementation}; every published distance re-measured and reproduced at build time.`
          : "",
      ].filter(Boolean).join("\n\n");
    }
  } catch (error) {
    // A grid payload that will not load must not take the table with it.
    gridDistance = null;
    if (note) note.textContent = "GRID \u00b7 unavailable in this session";
  }
}

async function loadLocality() {
  const entry = registry.supplemental_assets?.table_locality_sort;
  const note = document.getElementById("localityNote");
  if (!entry) {
    if (note) note.textContent = "TOWN + POSTCODE · not in this release";
    return;
  }
  try {
    runtimeEvidence.localityRequests += 1;
    const payload = await fetchImmutable(entry.payload.path);
    invariant(payload.schema === entry.payload.schema, "locality schema mismatch");
    invariant(payload.generation === entry.generation, "locality generation mismatch");
    invariant(payload.locality && typeof payload.locality === "object", "locality index missing");
    locality = payload.locality;
    runtimeEvidence.localityReady = true;
    const counts = payload.counts || {};
    const sourced = (counts.bua || 0) + (counts.parish || 0) + (counts.ward || 0);
    if (note) {
      note.textContent = `TOWN · ${sourced.toLocaleString("en-GB")} from ONS postcode lookup, `
        + `${(counts.derived || 0).toLocaleString("en-GB")} from the REPD address line (dimmed), `
        + `${(counts.none || 0).toLocaleString("en-GB")} unsourceable · `
        + `POSTCODE · ${(counts.postcode || 0).toLocaleString("en-GB")} official REPD values, `
        + `blank offshore`;
      note.title = payload.sources?.town || "";
    }
  } catch (error) {
    // A locality payload that will not load must not take the table with it.
    locality = null;
    if (note) note.textContent = "TOWN + POSTCODE · unavailable in this session";
  }
}

async function openGbElectricityContext() {
  const button = document.getElementById("gbElectricityOpen");
  const host = document.getElementById("gbElectricityHost");
  const meta = document.getElementById("gbElectricityMeta");
  invariant(button && host && meta, "GB electricity context controls are missing");
  if (host.dataset.gbElectricityState === "ready") {
    host.hidden = !host.hidden;
    button.setAttribute("aria-expanded", String(!host.hidden));
    return;
  }
  if (host.dataset.gbElectricityState === "loading") return;
  const entry = registry.supplemental_assets?.gb_electricity_context;
  invariant(entry?.activation === "dynamic-import-and-attested-payload-fetch-on-user-open", "GB electricity activation changed");
  invariant(entry.project_bindings === 0 && entry.eligible_for_news_signal === false, "GB electricity project boundary changed");
  host.hidden = false;
  host.dataset.gbElectricityState = "loading";
  button.setAttribute("aria-expanded", "true");
  meta.textContent = "LOAD · reading the attested 4 kB historic rollup";
  runtimeEvidence.gbElectricityImports += 1;
  invariant(runtimeEvidence.gbElectricityImports === 1, "GB electricity cartridge imported more than once");
  const cartridge = await import(`./${entry.cartridge.filename}`);
  invariant(cartridge.GB_ELECTRICITY_CONTEXT_CONTRACT.generation === entry.generation, "GB electricity cartridge identity changed");
  invariant(cartridge.GB_ELECTRICITY_CONTEXT_CONTRACT.additive_only === true, "GB electricity cartridge is no longer additive-only");
  const result = await cartridge.mountGbElectricityContext({
    host,
    payloadAsset: { ...entry.payload, url: entry.payload.path },
  });
  runtimeEvidence.gbElectricityPayloadRequests = result.payloadRequests;
  invariant(result.payloadRequests === 1 && result.projectBindings === 0, "GB electricity request or project boundary changed");
  meta.textContent = `OK · ${result.years} calendar years · ${result.completeDays.toLocaleString("en-GB")} complete days`;
}

function bindGbElectricityContext() {
  const button = document.getElementById("gbElectricityOpen");
  invariant(button, "GB electricity context opener is missing");
  button.addEventListener("click", () => openGbElectricityContext().catch((error) => {
    console.error("GB electricity context", error);
    document.getElementById("gbElectricityMeta").textContent = "FAIL · historic GB context unavailable; core product unchanged";
    document.getElementById("gbElectricityHost").dataset.gbElectricityState = "failed";
  }));
}

async function openWiderFleet() {
  const meta = document.getElementById("widerFleetMeta");
  const host = document.getElementById("widerFleetHost");
  invariant(meta && host, "wider fleet nodes are missing");
  const entry = registry.supplemental_assets?.map_corpus_contract;
  invariant(entry?.activation === "eager-tab-injection-after-spine-controls-bound", "wider fleet activation changed");
  invariant(entry.project_bindings === 0 && entry.eligible_for_news_signal === false, "wider fleet project boundary changed");
  invariant(entry.reads_spine_payload === false, "wider fleet started reading the spine");
  runtimeEvidence.widerFleetImports += 1;
  invariant(runtimeEvidence.widerFleetImports === 1, "wider fleet cartridge imported more than once");
  const cartridge = await import(`./${entry.cartridge.filename}`);
  invariant(cartridge.WIDER_FLEET_CONTRACT.generation === entry.generation, "wider fleet cartridge identity changed");
  invariant(cartridge.WIDER_FLEET_CONTRACT.additive_only === true, "wider fleet cartridge is no longer additive-only");
  invariant(cartridge.WIDER_FLEET_CONTRACT.control_in_product_technology_row === "select", "wider fleet control left the product technology row");
  invariant(cartridge.WIDER_FLEET_CONTRACT.deep_linkable === true, "wider fleet stopped answering ?technology=");
  invariant(cartridge.WIDER_FLEET_CONTRACT.drives_summary_seam === true, "wider fleet stopped driving the spine summary seam");
  invariant(cartridge.WIDER_FLEET_CONTRACT.releases_on_spine_repaint === true, "wider fleet stopped letting go when the spine repaints");
  invariant(cartridge.WIDER_FLEET_CONTRACT.owns_the_pager_while_showing === true, "wider fleet stopped holding the pager while it holds the table");
  invariant(cartridge.WIDER_FLEET_CONTRACT.export_policy === "declines", "wider fleet changed its export policy without saying so");
  const result = await cartridge.mountWiderFleet({
    host,
    payloadAsset: { ...entry.payload, url: entry.payload.path },
    /* Handed over, not reached for. The cartridge still reads no spine
       payload and holds no spine state: it calls one function with the
       figures it is already showing, and the spine decides what those
       figures mean for the counter, the gauges, the arcs and the CSV. */
    presentSummary,
    /* Handed over for the same reason presentSummary is: so the cut can be
       told the product took its table back, rather than this file keeping a
       list of the controls that do it. */
    onSpineRepaint,
  });
  runtimeEvidence.widerFleetPayloadRequests = result.payloadRequests;
  invariant(result.payloadRequests === 1 && result.projectBindings === 0, "wider fleet request or project boundary changed");
  invariant(result.optionsAdded === entry.repd_technology_types, "wider fleet option count no longer matches the attested cut");
  invariant(result.controlsAdded === 1, "wider fleet put more than one control in the technology row");
  invariant(result.exportPolicy === "declines", "wider fleet started writing the spine 50-column CSV");
  meta.textContent = `OK \u00b7 ${result.optionsAdded} more REPD technology types in one control \u00b7 ${result.projects.toLocaleString("en-GB")} projects \u00b7 ${result.gigawatts} GW${result.deepLinked ? ` \u00b7 deep link \u00b7 ${result.deepLinked}` : ""}`;
}

/* ── THE ESTATE, IN THIS PRODUCT'S OWN MENU ───────────────────────────

   Vikram, 2026-09-05: "why are the drop down engines here NOT in the menus of
   gridatlas and pipelinenews". They are now, in both of this page's navs --
   the desktop sidebar and the RELEASES popover a phone opens -- because those
   are the two places a reader of THIS product already goes for a link.

   The forty-four nodes are not listed in this file. They are read from the
   graph the engine itself publishes, so a node added there appears here with
   no edit, and no second naming scheme can drift from it. Each row links to
   ?graph=engine-graph&focus=<label>, and the receiver matches on the node's
   own label -- exact first, then case-insensitively -- so the string in the
   link is the string the graph published.

   CROSS-ORIGIN, AND CHECKED RATHER THAN ASSUMED. This page is served from
   globalgrid2050.com and the genome is on ventusltd.github.io, so the fetch is
   cross-origin. GitHub Pages answers it with Access-Control-Allow-Origin: *
   -- verified against the live URL with a real Origin header before this was
   written, not assumed from the fact that it is public.

   IT IS ALSO NOT ALLOWED TO FAIL QUIETLY. A menu whose contents silently do
   not load is worse than a menu that does not offer them, because the reader
   cannot tell an empty estate from a broken one. So the list is fetched only
   when the reader asks for it, the failure prints its own reason in the menu
   where the list would have been, and the promise is cleared so the next tap
   is a real retry. The ENGINE GRAPH link above it is a plain anchor and works
   whether any of this runs or not.

   No MutationObserver, and nothing here observes the DOM: the toggle writes
   into one container it owns, once, on a click. */

const ENGINE_GRAPH_URL = "https://ventusltd.github.io/ventus-grid-engine/?graph=engine-graph";
const ENGINE_GENOME_URL = "https://ventusltd.github.io/ventus-grid-engine/genome/engine-graph.json";
/* Read order for the kinds the genome publishes today. It is a PREFERENCE, not
   a whitelist: any kind not named here is appended in the order it is met, so a
   new one is visible rather than silently dropped. */
const ENGINE_KIND_ORDER = ["canonical", "extract", "reference", "fragment"];

let engineGenomePromise = null;

function engineGenome() {
  if (!engineGenomePromise) {
    engineGenomePromise = fetch(ENGINE_GENOME_URL, { mode: "cors", cache: "no-store" })
      .then((response) => {
        if (!response.ok) throw new Error(`genome HTTP ${response.status}`);
        return response.json();
      })
      .then((genome) => {
        if (!Array.isArray(genome?.nodes) || !genome.nodes.length) {
          throw new Error("genome carries no nodes");
        }
        return genome;
      })
      .catch((error) => {
        // Cleared, so the next tap is a retry and not the same stale rejection.
        engineGenomePromise = null;
        throw error;
      });
  }
  return engineGenomePromise;
}

function engineFocusHref(label) {
  const url = new URL(ENGINE_GRAPH_URL);
  url.searchParams.set("focus", label);
  return url.href;
}

function renderEngineNodes(host, genome) {
  const groups = new Map();
  for (const node of genome.nodes) {
    const kind = String(node.type || "other");
    if (!groups.has(kind)) groups.set(kind, []);
    groups.get(kind).push(node);
  }
  const kinds = [
    ...ENGINE_KIND_ORDER.filter((kind) => groups.has(kind)),
    ...[...groups.keys()].filter((kind) => !ENGINE_KIND_ORDER.includes(kind)),
  ];
  host.replaceChildren();
  for (const kind of kinds) {
    const heading = document.createElement("b");
    heading.className = "engine-kind";
    heading.textContent = `${kind.toUpperCase()} · ${groups.get(kind).length}`;
    host.appendChild(heading);
    for (const node of groups.get(kind)) {
      const link = document.createElement("a");
      link.href = engineFocusHref(node.label);
      link.target = "_blank";
      link.rel = "noopener";
      link.textContent = node.label;
      if (node.reason) link.title = node.reason;
      host.appendChild(link);
    }
  }
}

function bindEstateLinks() {
  document.querySelectorAll("[data-engine-nodes]").forEach((button) => {
    const host = button.parentElement?.querySelector("[data-engine-node-list]");
    if (!host) return;
    button.addEventListener("click", async () => {
      if (!host.hidden) {
        host.hidden = true;
        button.setAttribute("aria-expanded", "false");
        return;
      }
      host.hidden = false;
      button.setAttribute("aria-expanded", "true");
      if (host.dataset.engineState === "ready") return;
      host.dataset.engineState = "loading";
      host.replaceChildren(Object.assign(document.createElement("i"),
        { className: "engine-note", textContent: "reading the engine genome…" }));
      try {
        const genome = await engineGenome();
        renderEngineNodes(host, genome);
        host.dataset.engineState = "ready";
        button.textContent = `ENGINE NODES · ${genome.nodes.length}`;
      } catch (error) {
        host.dataset.engineState = "failed";
        host.replaceChildren(Object.assign(document.createElement("i"),
          { className: "engine-note engine-failed",
            textContent: `ENGINE NODES UNAVAILABLE · ${error.message} · `
              + "the ENGINE GRAPH link above still opens the graph itself. Tap again to retry." }));
      }
    });
  });
}

function bindWiderFleet() {
  // Eager, and deliberately not awaited: the tabs must be on the UI without
  // anyone clicking anything, and a failure here must not delay or break the
  // product's own boot.
  openWiderFleet().catch((error) => {
    console.error("wider fleet", error);
    const meta = document.getElementById("widerFleetMeta");
    if (meta) meta.textContent = "FAIL \u00b7 wider fleet tabs unavailable; core product unchanged";
  });
}

async function bindProvisionalProjects() {
  const host=document.getElementById('provisionalProjectsHost');
  try {
    const entry=registry.supplemental_assets.provisional_projects;
    const payload=await fetchImmutable(entry.payload.path);
    const module=await import('../'+entry.cartridge.path);
    invariant(module.CONTRACT.generation===entry.generation,'provisional module generation mismatch');
    const result=module.mount({host,payload,official:rows.map((_,index)=>project(index)),source:{path:registry.assets.projects.path,sha256:registry.assets.projects.sha256}});
    window.__provisionalProjects=result;
  }catch(error){host.textContent='Pending project records unavailable: '+error.message;}
}
async function bindBbcRssIntelligence() {
  const host=document.getElementById('bbcRssIntelligenceHost');
  try {
    const entry=registry.supplemental_assets.bbc_rss_intelligence;
    const payload=await fetchImmutable(entry.payload.path);
    invariant(payload.schema==='pipelinenews.bbc-rss-pipeline-payload.v1','RSS panel payload schema mismatch');
    const module=await import('../'+entry.cartridge.path);
    invariant(module.CONTRACT.generation===entry.generation,'RSS panel module generation mismatch');
    window.__bbcRssIntelligence=module.mount({host,payload:payload.rss,evidence:payload.evidence,projects:()=>window.__provisionalProjects?.projects || payload.projects,official:rows.map((_,index)=>project(index))});
  }catch(error){host.textContent='BBC RSS discovery unavailable: '+error.message;}
}
async function boot() {
  registry = await fetchImmutable(REGISTRY_URL);
  invariant(registry.schema === "pipelinenews.v9.timestamp-folder-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;
  });
  // Fetched in parallel with nothing else pending, and awaited before the
  // first apply() so the table paints once, with the columns populated. It is
  // allowed to fail: town and postcode fall back to "-", every other column
  // and every sort except town/postcode is unaffected.
  await loadLocality();
  await loadGridDistance();
  await loadSubstation33kv();
  bindProjectControls();
  bindNewsControls();
  bindSectorIntelligence();
  await bindBbcRssIntelligence();
  await bindProvisionalProjects();
  bindWiderFleet();
  bindGbElectricityContext();
  bindEstateLinks();
  // Relationship abstention ledger withdrawn from the product UI.
  bindGridProximity();
  // Project mixed-taxonomy panel withdrawn from the product UI.
  populateCounties();
  // Before hydrateFiltersFromUrl, because it is what puts the register's other
  // ten statuses into STATUSES -- so ?status=Abandoned arrives instead of being
  // coerced to All.
  populateStatuses();
  hydrateFiltersFromUrl();
  if (query && !requestedRepdRef) await ensureSearchSupplement();
  apply({ syncUrl: false });
  document.getElementById("releaseMeta").textContent = `Live News + evidenced sector intelligence + Atlas V9 deep-link successor · 132 shown headlines · 4 withheld off-topic · ${rows.length.toLocaleString("en-GB")} canonical projects · ${registry.performance.maximum_physical_project_rows} physical rows · TIMESTAMPED RELEASE · POINTER-CONTROLLED`;
  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="13" class="fast-fail">Canonical Q2 REPD data unavailable. The timestamped release has failed closed.</td></tr>';
  document.getElementById("resultsMeta").textContent = "canonical data unavailable";
  document.body.dataset.fastFailed = "true";
});