GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / globalgrid2050 / pipelinenews_intelligence/202609050309/assets

GlobalGrid2050 — PipelineNews Intelligence (part 1)

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.

700 lines of JavaScript from globalgrid2050, in 1 file. Topic: Electricity markets and data pipelines. Section 860 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. GlobalGrid2050 — PipelineNews Intelligence energy-data · globalgrid2050 / pipelinenews_intelligence/202609050309/assets/202608291447-app.mjs lines 1–700

GlobalGrid2050 — PipelineNews Intelligence

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.

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

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

energy-dataglobalgrid2050 / pipelinenews_intelligence/202609050309/assets/202608291447-app.mjs · lines 1–700 of 2058 · version 2026-08-29 14:47 · Entry point · pattern openFederatedRelationships (shared by 3 files)

What it does
It draws engine graph, the REPD register, postcodes and substations. Defines 90 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: GlobalGrid2050 — PipelineNews Intelligence Page (globalgrid2050, https://globalgrid2050.com/pipelinenews_intelligence/202609050309/). Reached from 51 other entry points, including Homepage V037 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v037.html); Homepage V038 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v038.html); Homepage V039 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v039.html).
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://globalgrid2050.com/pipelinenews_intelligence/202609050309/.
Application
globalgrid2050 · pipelinenews_intelligence/202609050309/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
Atlas Pointer Deep Link (import)
Used by
loaded by GlobalGrid2050 — PipelineNews Intelligence Page (script src), mentioned in Standalone (comment link)
Produces
localityFor, gridFor, substationFor, metricChip, gridActionHtml, substationActionHtml, compareText, FetchQueue, escapeHtml, normalise, invariant, arraysEqual
Defines here
localityFor, gridFor, substationFor, metricChip, gridActionHtml, substationActionHtml, compareText, FetchQueue, escapeHtml, normalise, invariant, arraysEqual, hashJson, fetchImmutable, promise, dictionary, project, localitySearchText, searchTextFor, compactSearchText, formatNumber, displayDate, updatedTimestamp, atlasUrl, signalFor, relationshipSummary, rowHtml, ensureWindowControls, renderTable, updateSortHeader
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 pipelinenews_intelligence/202609050309/assets/202608291447-app.mjs:1-700 · blob 3029fcb7d0e78f0cb9454428609c25d4843a57d6 · 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
import { buildAtlasV9DeepLink } from "./202609040044-atlas-pointer-deep-link.mjs";

const GENERATION = "202608291447";
const EXPECTED_COMPILER_METHOD = "pipelinenews-atlas-pointer-exact-identity-successor-v2";
const EXPECTED_CACHE_IDENTITY = "d439dda1793f26dabad006df78dfce43e0add0e7c8a57e079e1fd3b6f0b24c6c";
const REGISTRY_URL = "data/202608291447-registry.json";
const WINDOW_SIZE = 100;
const NEWS_WINDOW_SIZE = 30;
const DETAIL_CONCURRENCY = 4;

const PROJECT_FIELDS = Object.freeze([
  "repd_ref",
  "gg_project_id",
  "name",
  "technology",
  "status",
  "capacity_mw",
  "county",
  "region",
  "operator",
  "repd_record_updated",
  "geometry_status",
  "latitude",
  "longitude",
]);

const NEWS_FIELDS = Object.freeze([
  "gg_article_id",
  "repd_ref",
  "gg_project_id",
  "project",
  "technology",
  "capacity_mw",
  "operator",
  "county",
  "country",
  "event",
  "headline",
  "published",
  "source",
  "url",
  "confidence",
  "canonical_relevant",
  "role",
  "eligible_for_news_signal",
  "regional_classification",
  "regional_technology",
  "regional_evidence",
  "event_detail",
  "relationship",
  "related_context_repd_ref",
  "related_context_project",
  "binding_label",
  "related_components",
  "evidence_snippet",
]);

const FIELD = Object.freeze({
  repdRef: 0,
  projectId: 1,
  name: 2,
  technology: 3,
  status: 4,
  capacity: 5,
  county: 6,
  region: 7,
  operator: 8,
  updated: 9,
  geometry: 10,
  latitude: 11,
  longitude: 12,
});

const NEWS_FIELD = Object.freeze({
  articleId: 0,
  repdRef: 1,
  projectId: 2,
  project: 3,
  technology: 4,
  capacity: 5,
  operator: 6,
  county: 7,
  country: 8,
  event: 9,
  headline: 10,
  published: 11,
  source: 12,
  url: 13,
  confidence: 14,
  canonical: 15,
  role: 16,
  eligible: 17,
  region: 18,
  regionalTechnology: 19,
  regionalEvidence: 20,
  eventDetail: 21,
  relationship: 22,
  relatedContextRepdRef: 23,
  relatedContextProject: 24,
  bindingLabel: 25,
  relatedComponents: 26,
  evidenceSnippet: 27,
});

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 TECHNOLOGIES = new Set(["all", "solar", "bess", "wind_onshore", "wind_offshore"]);
/* The four the product draws as tabs, and ALL. This list is the TABS, not the
   register: populateStatuses() adds every status the payload actually carries,
   so ?status= answers for all of them and a status DESNZ adds tomorrow needs no
   edit here. A hand-kept list of the register's own values is the mistake this
   product already made once with technology. */
const STATUS_TABS = Object.freeze(["All", "Operational", "Under Construction",
  "Awaiting Construction", "Application Submitted"]);
const STATUSES = new Set(STATUS_TABS);
const SORTS = new Set(["capacity_desc", "capacity_asc", "updated_desc", "updated_asc",
  "county_asc", "county_desc", "town_asc", "town_desc", "postcode_asc", "postcode_desc",
  "grid_asc", "grid_desc"]);

// Which heading each sort mode belongs to, so one function can drive every
// aria-sort and every indicator instead of five near-identical ones.
const SORT_HEADINGS = {
  capacity: { header: "capacityHeader", indicator: "capacitySortIndicator", asc: "capacity_asc", desc: "capacity_desc", first: "capacity_desc" },
  updated: { header: "repdUpdatedHeader", indicator: "updatedSortIndicator", asc: "updated_asc", desc: "updated_desc", first: "updated_desc" },
  county: { header: "countyHeader", indicator: "countySortIndicator", asc: "county_asc", desc: "county_desc", first: "county_asc" },
  town: { header: "townHeader", indicator: "townSortIndicator", asc: "town_asc", desc: "town_desc", first: "town_asc" },
  postcode: { header: "postcodeHeader", indicator: "postcodeSortIndicator", asc: "postcode_asc", desc: "postcode_desc", first: "postcode_asc" },
};

// The locality payload: town, postcode and planning authority, keyed by REPD
// ref. Resolved at BUILD time (see the cartridge's build_payload.py) so the
// table never touches the network. Null until it lands, and null forever if
// the fetch fails -- the table renders either way.
let locality = null;

function localityFor(item) {
  return (locality && locality[String(item.repd_ref)]) || null;
}

// The grid-distance payload: the nearest mapped circuit per REPD ref, carried
// across from the GRID panel's own payload and verified at build time against
// Ventusltd/grid-distance-maths. Slim on purpose -- the panel's payload is
// 5.5 MB and is fetched only when a user opens it; this is 240 KB and is
// fetched once at boot because a column needs every row.
//
// Null until it lands, and null forever if the fetch fails. The column then
// reads "-" and every other column is untouched.
let gridDistance = null;

function gridFor(item) {
  return (gridDistance && gridDistance[String(item.repd_ref)]) || null;
}

// A distance the register cannot support is a dash, never a zero and never a
// large number standing in for "not found". Absence from a mapped layer is not
// absence on the ground.
// The nearest 33 kV+ substation, keyed by REPD ref. Scope is 33 kV and above:
// 11 kV is rare for utility-scale export and where it occurs is often a private
// network behind the meter, so it is not a screening signal. Every one of the
// 5,800 substations in the Atlas layer qualifies, so nothing is filtered out at
// runtime -- the scope is a property of the layer, recorded in the payload.
let substation = null;

function substationFor(item) {
  return (substation && substation[String(item.repd_ref)]) || null;
}

// The sentence a distance can never answer. Held in one place so the two chips
// and the strip cannot drift apart.
const HEADROOM_CAVEAT = "Fault level and thermal headroom cannot be inferred from "
  + "distance: they depend on DNO network data such as source impedance, fault "
  + "infeed and existing committed connections, and are established by a "
  + "connection study.";

function metricChip({ ready, hit, located, label, unitSuffix, lines }) {
  if (!ready) return `<span class="action-metric pending">${label} \u2026</span>`;
  if (!hit || typeof hit.k !== "number") {
    // One sentence covered two different silences, and it asserted a search
    // that never ran. Counted on this cut: 3,047 of the 7,680 records carry a
    // distance and 4,633 do not, and the grid-distance payload's own coverage
    // block records no_circuit: 0 -- not one project was measured and came up
    // empty. "No mapped feature found for this project" therefore described
    // none of the 4,633 rows it was printed on. 4,605 of them hold a register
    // coordinate and were simply not measured; the other 28 have no coordinate
    // to measure from. The row already knows which it is.
    //
    // The mapped-layer caveat is not repeated here. It qualifies a distance
    // that was measured against an incomplete layer, and no distance was
    // measured for this row; it still stands, verbatim, on every chip that
    // carries a number and in the GRID + SUB strip.
    const why = located
      ? "Not measured. 3,047 of the 7,680 records in this cut carry a grid measurement and 4,633 do not. This project has a register coordinate and is one of the 4,605 unmeasured records that do: no search was run for it, so none failed."
      : "Not measurable. The register publishes no usable coordinate for this project, so there is no point on the ground to measure from. 28 of the 7,680 records are in that state, 26 missing and 2 invalid. The record stays searchable and exportable."
    return `<span class="action-metric" title="${why}">${label} -</span>`;
  }
  // No band attribute is emitted, so nothing downstream can style or read
  // a verdict back out of the DOM. The distance is the whole claim.
  const band = "";
  const title = escapeHtml(lines.filter(Boolean).join(" \u00b7 "));
  return `<span class="action-metric"${band} title="${title}">${label}`
    + `<b>${hit.k.toFixed(2)}</b><span class="unit">km${unitSuffix}</span></span>`;
}

// Distance to the nearest mapped circuit, at 33 kV and above.
function gridActionHtml(item) {
  const hit = gridFor(item);
  const lines = [];
  if (hit && typeof hit.k === "number") {
    lines.push(`Nearest mapped circuit ${hit.k.toFixed(2)} km${hit.v ? ` at ${hit.v} kV` : ""}`);
    if (typeof hit.t === "number") lines.push(`transmission ${hit.t.toFixed(2)} km${hit.tv ? ` (${hit.tv} kV)` : ""}`);
    if (typeof hit.d === "number") lines.push(`distribution ${hit.d.toFixed(2)} km${hit.dv ? ` (${hit.dv} kV)` : ""}`);
    lines.push("Straight-line to mapped geometry, not a cable route or a connection length.");
    lines.push(HEADROOM_CAVEAT);
  }
  return metricChip({
    ready: Boolean(gridDistance), hit, located: item.geometry_status === "valid",
    label: "GRID",
    unitSuffix: hit && hit.v ? ` \u00b7 ${hit.v}kV` : "", lines,
  });
}

// Distance to the nearest 33 kV+ substation -- for a scheme of a few tens of MW
// this is closer to where it would actually connect than the circuit is.
function substationActionHtml(item) {
  const hit = substationFor(item);
  const lines = [];
  if (hit && typeof hit.k === "number") {
    lines.push(`Nearest substation at 33 kV or above, ${hit.k.toFixed(2)} km`
      + (hit.n ? ` \u2014 ${hit.n}` : "")
      + (hit.v && hit.v.length ? ` (${hit.v.join("/")} kV)` : ""));
    lines.push("A mapped substation point does not confirm capacity, voltage suitability, connection rights, queue position or acceptance by any network party.");
    lines.push(HEADROOM_CAVEAT);
  }
  return metricChip({
    ready: Boolean(substation), hit, located: item.geometry_status === "valid",
    label: "SUB", unitSuffix: "", lines,
  });
}

// Blanks sort last in BOTH directions. A project with no postcode has not got
// a small postcode; pushing it to the bottom either way keeps the populated
// rows contiguous, which is the whole point of clustering by locality.
function compareText(leftText, rightText, direction) {
  const left = leftText || "";
  const right = rightText || "";
  if (!left && !right) return 0;
  if (!left) return 1;
  if (!right) return -1;
  return direction * left.localeCompare(right, "en-GB");
}
const FINANCE_EVENTS = new Set(["FINANCIAL CLOSE", "ACQUISITION"]);

const immutablePromises = new Map();

class FetchQueue {
  constructor(limit) {
    this.limit = limit;
    this.active = 0;
    this.maximumActive = 0;
    this.pending = [];
  }

  add(task) {
    return new Promise((resolve, reject) => {
      this.pending.push({ task, resolve, reject });
      this.drain();
    });
  }

  drain() {
    while (this.active < this.limit && this.pending.length) {
      const entry = this.pending.shift();
      this.active += 1;
      this.maximumActive = Math.max(this.maximumActive, this.active);
      Promise.resolve()
        .then(entry.task)
        .then(entry.resolve, entry.reject)
        .finally(() => {
          this.active -= 1;
          this.drain();
        });
    }
  }
}

const detailQueue = new FetchQueue(DETAIL_CONCURRENCY);
const detailPromises = new Map();
const detailByRef = new Map();
const charts = { capacity: null, projects: null, largest: null };

let registry = null;
let projectPayload = null;
let rows = [];
let dictionaries = null;
let searchSupplement = null;
let newsRows = [];
let filtered = [];
let updatedTimes = [];
let windowStart = 0;
let newsStart = 0;
let technology = "all";
let status = "All";
let county = "All";
let query = "";
let requestedRepdRef = "";
let sortMode = "capacity_desc";
let newsMode = "ALL";
let newsQuery = "";
let searchTimer = null;
let controlsBound = false;

const runtimeEvidence = {
  generation: GENERATION,
  detailConcurrency: DETAIL_CONCURRENCY,
  maximumDetailConcurrency: 0,
  detailRequests: 0,
  newsRequests: 0,
  searchRequests: 0,
  chartsReady: false,
  newsReady: false,
  searchReady: false,
  sectorIntelligenceImports: 0,
  sectorPayloadRequestsAtMount: 0,
  federatedRelationshipImports: 0,
  federatedRelationshipPayloadRequests: 0,
  projectIntelligenceImports: 0,
  projectIntelligencePayloadRequests: 0,
  localityRequests: 0,
  localityReady: false,
  gridDistanceRequests: 0,
  gridDistanceReady: false,
  substationRequests: 0,
  substationReady: false,
  gridProximityImports: 0,
  gridProximityPayloadRequests: 0,
  gbElectricityImports: 0,
  gbElectricityPayloadRequests: 0,
  widerFleetImports: 0,
  widerFleetPayloadRequests: 0,
};
globalThis.__PIPELINENEWS_FAST__ = runtimeEvidence;

function escapeHtml(value) {
  return String(value ?? "").replace(/[&<>"']/g, (character) => ({
    "&": "&amp;",
    "<": "&lt;",
    ">": "&gt;",
    '"': "&quot;",
    "'": "&#39;",
  })[character]);
}

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

function invariant(condition, message) {
  if (!condition) throw new Error(`PipelineNews V9 timestamped runtime: ${message}`);
}

function arraysEqual(left, right) {
  return Array.isArray(left) && Array.isArray(right)
    && left.length === right.length
    && left.every((value, index) => value === right[index]);
}

async function hashJson(value) {
  invariant(globalThis.crypto?.subtle, "Web Crypto unavailable for cache-contract verification");
  const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify(value)));
  return [...new Uint8Array(digest)].map((value) => value.toString(16).padStart(2, "0")).join("");
}

async function fetchImmutable(url, { timeoutMs = 15000 } = {}) {
  const target = new URL(url, document.baseURI);
  invariant(target.origin === location.origin, `cross-origin cartridge rejected: ${target.href}`);
  const key = target.href;
  if (immutablePromises.has(key)) return immutablePromises.get(key);
  const promise = (async () => {
    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), timeoutMs);
    try {
      const response = await fetch(target, { cache: "force-cache", signal: controller.signal });
      invariant(response.ok, `${target.pathname} returned HTTP ${response.status}`);
      return response.json();
    } finally {
      clearTimeout(timeout);
    }
  })();
  immutablePromises.set(key, promise);
  promise.catch(() => immutablePromises.delete(key));
  return promise;
}

function dictionary(name, index) {
  return dictionaries[name][index] ?? "";
}

function project(index) {
  const row = rows[index];
  return {
    index,
    row,
    repd_ref: row[FIELD.repdRef],
    gg_project_id: row[FIELD.projectId],
    name: row[FIELD.name],
    technology: dictionary("technology", row[FIELD.technology]),
    status: dictionary("status", row[FIELD.status]),
    capacity_mw: Number(row[FIELD.capacity]),
    county: dictionary("county", row[FIELD.county]),
    region: dictionary("region", row[FIELD.region]),
    operator: dictionary("operator", row[FIELD.operator]),
    repd_record_updated: row[FIELD.updated],
    geometry_status: dictionary("geometry_status", row[FIELD.geometry]),
    latitude: row[FIELD.latitude],
    longitude: row[FIELD.longitude],
  };
}

// The prebuilt search index (generation 202608270055) predates these columns,
// and it is an immutable asset behind a cache_identity invariant, so it cannot
// be extended. County and region were always in it; town, postcode and
// planning authority are appended here instead, at query time.
const localitySearchCache = new Map();

function localitySearchText(index) {
  if (!locality) return "";                 // nothing to cache yet
  if (localitySearchCache.has(index)) return localitySearchCache.get(index);
  const place = locality[String(project(index).repd_ref)];
  let text = "";
  if (place) {
    // Both spellings of the postcode, so "CT19 4RH" and "CT194RH" both hit,
    // and so does the bare outcode.
    const postcode = place.postcode || "";
    text = normalise([place.town, place.authority, postcode,
                      postcode.replace(/\s+/gu, "")].filter(Boolean).join(" "));
  }
  localitySearchCache.set(index, text);
  return text;
}

function searchTextFor(index) {
  const base = searchSupplement?.[index] || compactSearchText(index);
  const extra = localitySearchText(index);
  return extra ? `${base} ${extra}` : base;
}

function compactSearchText(index) {
  const item = project(index);
  return normalise([
    item.name,
    item.operator,
    item.repd_ref,
    item.gg_project_id,
    item.technology,
    item.status,
    item.capacity_mw,
    item.county,
    item.region,
    item.repd_record_updated,
    item.geometry_status,
  ].join(" "));
}

function formatNumber(value) {
  return (Number(value) || 0).toLocaleString("en-GB", { maximumFractionDigits: 2 });
}

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 updatedTimestamp(index) {
  return updatedTimes[index] ?? null;
}

function atlasUrl(item) {
  return buildAtlasV9DeepLink(item);
}

function signalFor(item) {
  const signal = registry.signals[item.repd_ref];
  if (!signal) return { label: "—", cls: "none", note: "no exact canonical PRIMARY_MATCH" };
  const [eventValue, confidence, published] = signal;
  const event = String(eventValue || "PROJECT UPDATE").toUpperCase();
  if (event === "CONSENT") return { label: "APPROVED*", cls: "approved", note: `canonical PRIMARY_MATCH ${confidence}% · unverified event · ${published}` };
  if (event === "OPERATIONAL") return { label: "OPERATIONAL*", cls: "operational", note: `canonical PRIMARY_MATCH ${confidence}% · unverified event · ${published}` };
  if (event === "CONSTRUCTION") return { label: "CONSTRUCTION*", cls: "construction", note: `canonical PRIMARY_MATCH ${confidence}% · unverified event · ${published}` };
  if (FINANCE_EVENTS.has(event)) return { label: event === "ACQUISITION" ? "M&A*" : "FINANCED*", cls: "finance", note: `canonical PRIMARY_MATCH ${confidence}% · unverified event · ${published}` };
  return { label: `${event}*`.slice(0, 22), cls: "", note: `canonical PRIMARY_MATCH ${confidence}% · unverified event · ${published}` };
}

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

function rowHtml(index) {
  const item = project(index);
  const label = LABELS[item.technology];
  const signal = signalFor(item);
  const locationText = [item.county, item.region].filter(Boolean).join(" · ");
  const place = localityFor(item);
  // A town the register cannot source is a dash, never a guess. One taken from
  // the address rather than from ONS is shown dimmed and says so on hover.
  const townCell = !locality
    ? "…"
    : place?.town
      ? (place.town_source === "derived"
        ? `<span class="derived" title="Derived from the REPD address line; no postcode in the register to resolve against ONS">${escapeHtml(place.town)}</span>`
        : `<span title="ONS Postcode Directory (${escapeHtml(place.town_source)})">${escapeHtml(place.town)}</span>`)
      : "-";
  const news = new URL("https://www.google.com/search");
  news.searchParams.set("q", `${item.name} ${label} UK`);
  news.searchParams.set("tbm", "nws");
  const atlas = atlasUrl(item);
  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>';
  return `<tr id="repd-${escapeHtml(item.repd_ref)}" data-project-index="${index}"><td class="site">${escapeHtml(item.name)}<div class="project-meta">REPD ${escapeHtml(item.repd_ref)} · ${escapeHtml(item.gg_project_id)} · UPDATED ${escapeHtml(displayDate(item.repd_record_updated))}</div><div class="mobile-extra">${escapeHtml([locationText, item.operator].filter(Boolean).join(" | "))}</div><details  … [line shortened here: 1,831 characters; full line on GitHub]
}

function ensureWindowControls() {
  let panel = document.getElementById("projectWindowControls");
  if (panel) return panel;
  panel = document.createElement("div");
  panel.id = "projectWindowControls";
  panel.className = "project-window-controls";
  /* The buttons said PREVIOUS 50 and NEXT 50 and moved WINDOW_SIZE, which is
     100: from "1-100 of 7,680" one press reached "101-200 of 7,680". They also
     serve the wider-fleet cut, whose own page is 50, so no single number on
     these two buttons can be true of both. The range readout beside them
     already states the window exactly, for whichever cut is showing, so the
     number comes off the buttons rather than being made wrong in a second
     place. */
  panel.innerHTML = '<button type="button" data-window="previous">PREVIOUS</button><span data-window-range></span><button type="button" data-window="next">NEXT</button>';
  document.querySelector(".tablewrap").after(panel);
  panel.addEventListener("click", (event) => {
    const action = event.target.closest("[data-window]")?.dataset.window;
    if (!action) return;
    if (action === "previous") windowStart = Math.max(0, windowStart - WINDOW_SIZE);
    if (action === "next") windowStart = Math.min(Math.floor(Math.max(0, filtered.length - 1) / WINDOW_SIZE) * WINDOW_SIZE, windowStart + WINDOW_SIZE);
    renderTable();
  });
  return panel;
}

function renderTable() {
  const body = document.getElementById("tbody");
  const page = filtered.slice(windowStart, windowStart + WINDOW_SIZE);
  body.innerHTML = page.map(rowHtml).join("");
  const panel = ensureWindowControls();
  const end = Math.min(filtered.length, windowStart + WINDOW_SIZE);
  panel.querySelector("[data-window-range]").textContent = filtered.length
    ? `${windowStart + 1}–${end} of ${filtered.length.toLocaleString("en-GB")}`
    : "0 records";
  panel.querySelector('[data-window="previous"]').disabled = windowStart === 0;
  panel.querySelector('[data-window="next"]').disabled = end >= filtered.length;
}

function updateSortHeader() {
  for (const spec of Object.values(SORT_HEADINGS)) {
    const header = document.getElementById(spec.header);
    const indicator = document.getElementById(spec.indicator);
    if (!header || !indicator) continue;
    if (sortMode === spec.desc) {
      header.setAttribute("aria-sort", "descending");
      indicator.textContent = "▼";
    } else if (sortMode === spec.asc) {
      header.setAttribute("aria-sort", "ascending");
      indicator.textContent = "▲";
    } else {
      header.setAttribute("aria-sort", "none");
      indicator.textContent = "↕";
    }
  }
}

function updateChart(chart, value, maximum) {
  if (!chart) return;
  chart.data.datasets[0].data = [value, Math.max(maximum - value, 0)];
  chart.update("none");
}

function updateGauges(summary) {
  document.getElementById("v1").textContent = formatNumber(summary.capacity);
  document.getElementById("v2").textContent = summary.count.toLocaleString("en-GB");
  document.getElementById("v3").textContent = formatNumber(summary.largest);
  updateChart(charts.capacity, summary.capacity, registry.totals.capacity_mw || 1);
  updateChart(charts.projects, summary.count, registry.totals.project_count || 1);
  updateChart(charts.largest, summary.largest, registry.totals.largest_mw || 1);
}

function updateSummary(summary) {
  const element = document.getElementById("resultsMeta");
  element.textContent = `${summary.count.toLocaleString("en-GB")} of ${summary.total.toLocaleString("en-GB")} records · ${formatNumber(summary.capacity)} MW · largest ${formatNumber(summary.largest)} MW`;
  element.classList.toggle("is-filtered", summary.count !== summary.total);
  element.dataset.filteredCount = String(summary.count);
  element.dataset.totalCount = String(summary.total);
}

/* ── THE SUMMARY SEAM ─────────────────────────────────────────────

   Five surfaces of this product are derived from one summary: the record
   counter's four figures and its dataset, the three gauge numbers, the three
   gauge ARCS, and what EXPORT FILTERED CSV writes. Until this generation the
   maths behind them lived in two files. apply() computed a summary and drove
   the counter and the gauges from it; the wider-fleet cartridge computed the
   same three quantities itself and wrote only the gauge TEXT. Everything it
   did not write kept the previous technology's answer, and nothing announced
   it. Measured on 202609031308 and on 202609030009 before it, across all
   twenty wider-fleet technologies:

     counter    kept the previous technology's count, total, MW and largest
     dataset    kept is-filtered, filteredCount 3563, totalCount 7680
     arcs       g1/g2/g3 unchanged across a switch, byte for byte on toDataURL
     the page   on FLYWHEELS, #v3 read 400 while the counter read largest 840
     the CSV    exported 3,563 solar rows with one flywheel on screen, and
                said "3,563 filtered records exported" while doing it

   Four of those were visible and one left the building. Patching the visible
   three would have left the duplication that produced all five in place, so
   the fix is this function instead: ONE entry point, which every cut on the
   product's table calls with the figures it is showing, and which owns every
   surface a summary drives. A cut that is not the spine's own passes an
   exportProvider as well, because a cut that cannot honestly fill the spine's
   50-column CSV must say so rather than let the spine write somebody else's
   rows under its heading.

   `total` is the counter's second figure and is part of the shape for the
   same reason the other three are. The spine's own total is its register,
   rows.length, which is what it has always been and what a call that omits
   the field still gets. A wider-fleet cut is NOT part of that register --
   there is no flywheel among the spine's 7,680 -- so "1 of 7,680 records"
   would have been a fifth wrong number invented by the fix. It passes its
   own.

   Called with null, this restores nothing and repaints nothing. It drops the
   export provider and clears the export strip, and the spine's own apply()
   puts the product's figures back, as it already did. */

const EXPORT_META_DEFAULT = "CSV contains the current filtered rows only";

/* The export answer for the cut currently on screen. null means the spine's
   own `filtered` array is what EXPORT FILTERED CSV should write -- and that
   is the only state in which `filtered` describes the rows a reader can
   actually see. */
let presentedExport = null;

function presentSummary(summary) {
  presentedExport = null;
  const exportMeta = document.getElementById("exportMeta");
  if (exportMeta) {
    exportMeta.textContent = EXPORT_META_DEFAULT;
    exportMeta.classList.remove("is-declined");
    delete exportMeta.dataset.exportDeclinedColumns;
  }
  if (!summary) return;
  const shaped = {
    count: summary.count,
    total: typeof summary.total === "number" ? summary.total : rows.length,
    capacity: summary.capacity,
    largest: summary.largest,
  };
  updateSummary(shaped);
  updateGauges(shaped);
  presentedExport = typeof summary.exportProvider === "function"
    ? summary.exportProvider
    : null;
}

/* ── THE RELEASE SEAM ─────────────────────────────────

   The other half of the summary seam. presentSummary() lets a cut that is not
   the spine's own SAY what it is showing. This lets it be TOLD that the spine
   has taken the table back.

   Measured on 202609040144, live, with WIDER FLEET set to Landfill Gas
   (275 rows, 787.87 MW):