GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / globalgrid2050 / testcode/202609060349/pipeline/assets

Testcode — Pipeline (part 3)

A JavaScript module in the assets folder of GlobalGrid2050 covering pipeline filtered and engine graph, using EPSG:27700 and SHA-256, and uses data from the ventus-grid-engine repository.

697 lines of JavaScript from globalgrid2050, in 1 file. Topic: Electricity markets and data pipelines. Section 913 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. Testcode — Pipeline energy-data · globalgrid2050 / testcode/202609060349/pipeline/assets/202608291447-app.mjs lines 1401–2097

Testcode — Pipeline

A JavaScript module in the assets folder of GlobalGrid2050 covering pipeline filtered and engine graph, using EPSG:27700 and SHA-256, and uses data from the ventus-grid-engine repository.

Set aside from the main view: 92% of its lines are the same as releases/202611132345-pipelinenews/assets/202608291447-app.mjs (pipelinenews), which stays. (near-copy-of, proposed by families.py). 92% of lines shared with Releases — PipelineNews; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9244 to pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 releases/202611132345-pipelinenews/assets/202608291447-app.mjs:1-2082 c117027cd73a354235c49f217b1cbe780becca50
  • sha256 5471b7d72f9c025853484c5581de282674d975e5b35f3245856a1db92ce68aa9
  • target sha256 18a65716f320460c65da7326ae8348be1647cc20b9fbacffa056dcc298a1a00b
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

energy-dataglobalgrid2050 / testcode/202609060349/pipeline/assets/202608291447-app.mjs · lines 1401–2097 of 2097 · version 2026-08-29 14:47 (continued from section 911) · Entry point · pattern bindProvisionalProjects (shared by 2 files)

What it does
It draws pipeline filtered, engine graph, the REPD register and postcodes. Defines 95 functions or classes, including localityFor, gridFor, substationFor, updateMetricCoverage, describe. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: the REPD register, postcodes, 33kV, 11kV.
Inputs & outputs
In: data source: ventus-grid-engine data; JSON file 202608291447-registry.json; JSON file engine-graph.json. Out: GeoJSON file pipeline-202609060334-filtered.geojson; downloaded file pipeline-202609060334-filtered.geojson. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326. Voltage levels named: 33kV, 11kV.
Downstream impact
Used directly by 1 file: Testcode — Pipeline Page (globalgrid2050, https://globalgrid2050.com/testcode/202609060345/pipeline/). Reached from 20 other entry points, including Homepage V073 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v073.html); Homepage V074 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v074.html); Homepage V075 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v075.html).
What it achieves
It updates metric coverage (`updateMetricCoverage`), compares text (`compareText`) and fetches queue (`FetchQueue`). 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://globalgrid2050.com/testcode/202609060345/pipeline/.
Application
globalgrid2050 · testcode/202609060349/pipeline/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
Geometry Filter (import), Metric Coverage (import), Project GeoJSON (import), Wider Metrics (import), Metric Details (import), Atlas Pointer Deep Link (import)
Used by
loaded by Testcode — Pipeline Page (script src)
Produces
localityFor, gridFor, substationFor, updateMetricCoverage, describe, metricChip, gridActionHtml, substationActionHtml, compareText, FetchQueue, escapeHtml, normalise
Defines here
drawNews, 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
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609060349/pipeline/assets/202608291447-app.mjs:1401-2097 · blob db47fc5cb6331117b9f1202d46a3299a627c57a0 · GitHub at these lines
State
achieves: code · context: readme_derived · stage: output · effects: dom, network · domain stage: experimental · users: none · canonical: production_core
    ? `<span class="news-quality relevant">RELEVANT ${Number(row[NEWS_FIELD.confidence] || 0)}%</span> · PRIMARY_MATCH · REPD ${escapeHtml(row[NEWS_FIELD.repdRef])}`
    : regional
      ? `<span class="news-quality relevant">${escapeHtml(regional === "INTERNATIONAL_OTHER" ? "INTERNATIONAL" : regional)}</span> · ${escapeHtml(row[NEWS_FIELD.regionalEvidence])} · regional discovery only · no REPD project signal`
      : '<span class="news-quality unverified">DISCOVERY ONLY</span> · no project signal';
  const componentNote = relatedComponents.length
    ? `<p>${relatedComponents.map((component) => `RELATED DEVELOPMENT · REPD ${escapeHtml(component.repd_ref || "unknown")} · ${escapeHtml(String(component.technology || "").toUpperCase())}${Number.isFinite(component.official_capacity_mw) ? ` · ${Number(component.official_capacity_mw).toLocaleString("en-GB")} MW` : " · official capacity unknown"} · no project signal`).join(" · ")}</p>`
    : "";
  return `<a class="story ${articleClass}" data-article-id="${escapeHtml(row[NEWS_FIELD.articleId])}" href="${escapeHtml(row[NEWS_FIELD.url])}" target="_blank" rel="noopener"><div class="kicker">${escapeHtml(technologyValue || "ENERGY")} · ${escapeHtml(row[NEWS_FIELD.event] || "PROJECT UPDATE")}${eventDetail ? ` · ${escapeHtml(eventDetail)}` : ""} · ${escapeHtml(row[NEWS_FIELD.published] || "")}</  … [line shortened here: 994 characters; full line on GitHub]
}

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

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

async function loadNews() {
  if (runtimeEvidence.newsReady) return;
  runtimeEvidence.newsRequests += 1;
  try {
    const payload = await fetchImmutable(registry.assets.news.path);
    invariant(payload.schema === registry.assets.news.schema, "news schema mismatch");
    invariant(payload.generation === registry.assets.news.generation, "news generation mismatch");
    invariant(payload.cache_identity === registry.assets.news.cache_identity, "news cache identity mismatch");
    invariant(arraysEqual(payload.fields, NEWS_FIELDS), "news field contract mismatch");
    invariant(payload.rows.length === registry.news_counts.all, "news count mismatch");
    // 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() {
  for(const entry of [registry.supplemental_assets?.wider_sub_coverage,registry.supplemental_assets?.grid_actions_inline].filter(Boolean)) {
    try {
      runtimeEvidence.substationRequests += 1;
      const payload=await fetchImmutable(entry.payload.path);
      invariant(payload.schema===entry.payload.schema && payload.generation===entry.generation,'sub coverage identity mismatch');
      invariant(payload.substation && typeof payload.substation==='object' && !Array.isArray(payload.substation),'sub coverage index missing');
      substation=payload.substation;
      runtimeEvidence.substationReady=true;
      runtimeEvidence.subCoverageSource=entry.generation;
      return;
    } catch(error) { runtimeEvidence.subCoverageFallback=true; }
  }
  substation=null;
}

async function loadGridDistance() {
  for(const entry of [registry.supplemental_assets?.wider_grid_coverage,registry.supplemental_assets?.grid_distance_column].filter(Boolean)) {
    try {
      runtimeEvidence.gridDistanceRequests += 1;
      const payload=await fetchImmutable(entry.payload.path);
      invariant(payload.schema===entry.payload.schema && payload.generation===entry.generation,'grid coverage identity mismatch');
      invariant(payload.grid && typeof payload.grid==='object' && !Array.isArray(payload.grid),'grid coverage index missing');
      gridDistance=payload.grid;
      runtimeEvidence.gridDistanceReady=true;
      runtimeEvidence.gridCoverageSource=entry.generation;
      return;
    } catch(error) { runtimeEvidence.gridCoverageFallback=true; }
  }
  gridDistance=null;
}

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,
    metricActions: row => widerMetricActions(row, gridDistance) + ' ' + widerMetricActions(row, substation, 'SUB'),
    metricLookup: (ref,label) => (label==='SUB'?substation:gridDistance)?.[ref]?.k,
    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 === 4, "wider fleet must expose selector, filter, order and its own GeoJSON export");
  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();
  updateMetricCoverage();
  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";
});