GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / globalgrid2050 / testcode/202609051152/pipeline/scripts/plugins

Canonical Project Table and 3 more files (part 1)

A JavaScript module in the plugins folder of GlobalGrid2050 that works with the Renewable Energy Planning Database (REPD) register.

664 lines of JavaScript from globalgrid2050, in 4 files. Topic: Electricity markets and data pipelines. Section 902 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. Canonical Project Controls transform · globalgrid2050 / testcode/202609051152/pipeline/scripts/plugins/canonical-project-controls.js lines 1–167
  2. Canonical Project Export transform · globalgrid2050 / testcode/202609051152/pipeline/scripts/plugins/canonical-project-export.js lines 1–129
  3. Canonical Project Table transform · globalgrid2050 / testcode/202609051152/pipeline/scripts/plugins/canonical-project-table.js lines 1–311
  4. Capacity Presentation V9 3 energy-data · globalgrid2050 / testcode/202609051152/pipeline/scripts/plugins/capacity-presentation-v9-3.js lines 1–57

Canonical Project Controls

A JavaScript module in the plugins folder of GlobalGrid2050 that works with solar and battery storage (BESS). It builds canonical project controls view (`buildCanonicalProjectControlsView`) and validates control (`validateControlValue`).

transformglobalgrid2050 / testcode/202609051152/pipeline/scripts/plugins/canonical-project-controls.js · lines 1–167 of 167 · version 2026-09-05 11:52 · pattern hasValidatedModel (shared by 4 files)

What it does
It calculates solar and battery storage (BESS). Defines 9 functions or classes, including invariant, deepFreeze, hasValidatedModel, lifecycleViews, technologyOptions.
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: solar, battery storage (BESS).
Downstream impact
Used directly by 3 files: Projects (globalgrid2050); Check V7 2 Project Controls (globalgrid2050); Projects (globalgrid2050). Reached from 187 other entry points, including GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); GlobalGrid2050 — PipelineNews Intelligence Page (globalgrid2050, https://globalgrid2050.com/pipelinenews_intelligence/202609050309/).
What it achieves
Defines `invariant`, `deepFreeze`, `hasValidatedModel` and 6 more.
Why it matters
Imported by Projects. Checked by Check V7 2 Project Controls.
Application
globalgrid2050 · testcode/202609051152/pipeline/scripts/plugins · JavaScript module
Uses
Project State (import)
Used by
imported by Projects (import), imported by Check V7 2 Project Controls (import), imported by Projects (import), mentioned in Standalone (comment link)
Produces
buildCanonicalProjectControlsView, createCanonicalProjectControls
Defines here
invariant, deepFreeze, hasValidatedModel, lifecycleViews, technologyOptions, gaugeView, buildCanonicalProjectControlsView, validateControlValue, createCanonicalProjectControls
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/202609051152/pipeline/scripts/plugins/canonical-project-controls.js:1-167 · blob 8bc7ad18c98e1bd488a2f1b2a270aaba95d33271 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: production_core
import {
  resetCanonicalProjectFilters,
  setCanonicalProjectFilter,
} from "../core/project-state.js";

const SETTABLE_FILTERS = new Set([
  "technology",
  "lifecycleView",
  "officialStatus",
  "county",
  "region",
  "query",
]);

const SELECT_FILTER_OPTIONS = Object.freeze({
  officialStatus: "officialStatuses",
  county: "counties",
  region: "regions",
});

function invariant(condition, message) {
  if (!condition) throw new Error(`V7.2 canonical controls: ${message}`);
}

function deepFreeze(value) {
  if (!value || typeof value !== "object" || Object.isFrozen(value)) return value;
  Object.values(value).forEach(deepFreeze);
  return Object.freeze(value);
}

function hasValidatedModel(state) {
  return Boolean(state?.contract && Array.isArray(state.all) && state.all.length > 0);
}

function lifecycleViews(state) {
  const actualCounts = new Map([["ALL", state.all.length]]);
  for (const project of state.all) {
    actualCounts.set(project.lifecycle_view, (actualCounts.get(project.lifecycle_view) || 0) + 1);
  }
  return state.contract.lifecycle_views.map((view) => {
    const actual = actualCounts.get(view.id) || 0;
    invariant(actual === view.count, `${view.id} lifecycle count is ${actual}, expected ${view.count}`);
    return {
      id: view.id,
      label: view.label,
      count: actual,
      selected: state.filters.lifecycleView === view.id,
    };
  });
}

function technologyOptions(state) {
  const presentation = state.contract.interface.technology_labels_and_units;
  const counts = state.all.reduce((result, project) => {
    result[project.technology] = (result[project.technology] || 0) + 1;
    return result;
  }, { solar: 0, bess: 0 });
  return [
    { id: "all", label: "All", unit: null, count: state.all.length },
    { id: "solar", ...presentation.solar, count: counts.solar },
    { id: "bess", ...presentation.bess, count: counts.bess },
  ].map((option) => ({
    ...option,
    selected: state.filters.technology === option.id,
  }));
}

function gaugeView(state) {
  const { metrics } = state;
  return state.contract.interface.gauges.map((gauge) => {
    if (gauge.id === "solar_mwp") {
      return { ...gauge, value: metrics.solar_mwp, scope: "filtered_repd_records" };
    }
    if (gauge.id === "bess_mw") {
      return { ...gauge, value: metrics.bess_mw, scope: "filtered_repd_records" };
    }
    if (gauge.id === "project_count") {
      return { ...gauge, value: metrics.project_count, scope: "filtered_repd_records" };
    }
    invariant(gauge.id === "largest_project", `unknown gauge ${gauge.id}`);
    const largest = metrics.largest_project;
    return {
      ...gauge,
      value: largest?.capacity_mw ?? null,
      unit: largest?.capacity_unit ?? null,
      scope: "filtered_repd_records",
      project: largest ? {
        gg_project_id: largest.gg_project_id,
        name: largest.name,
        technology: largest.technology,
      } : null,
    };
  });
}

export function buildCanonicalProjectControlsView(state) {
  const available = hasValidatedModel(state);
  if (!available) {
    return deepFreeze({
      available: false,
      status: state?.status || "idle",
      error: state?.error || null,
      gauges: null,
      lifecycleViews: [],
      filters: state?.filters ? { ...state.filters } : null,
      filterOptions: null,
      search: null,
      resultCount: null,
      capacityBasis: "official_repd_record_capacity_not_development_deduplicated",
    });
  }

  invariant(state.contract.interface.combined_capacity_metric_forbidden === true, "combined capacity is not forbidden");
  invariant(state.contract.interface.gauges.length === 4, "four-gauge contract is absent");
  const exactIdentifiers = state.contract.interface.search_precedence.exact_identifier_fields;
  return deepFreeze({
    available: true,
    status: state.status,
    error: state.error,
    gauges: gaugeView(state),
    lifecycleViews: lifecycleViews(state),
    filters: { ...state.filters },
    filterOptions: {
      technology: technologyOptions(state),
      officialStatuses: ["All", ...state.filterOptions.officialStatuses],
      counties: ["All", ...state.filterOptions.counties],
      regions: ["All", ...state.filterOptions.regions],
    },
    search: {
      query: state.filters.query,
      fields: [...state.searchFields],
      exactIdentifierFields: [...exactIdentifiers],
      exactIdentifierPrecedence: true,
      placeholder: "Search project, REPD Ref, GlobalGrid ID, planning reference or authority",
    },
    resultCount: state.filtered.length,
    capacityBasis: "official_repd_record_capacity_not_development_deduplicated",
  });
}

function validateControlValue(state, key, value) {
  invariant(SETTABLE_FILTERS.has(key), `unknown filter ${key}`);
  const optionKey = SELECT_FILTER_OPTIONS[key];
  if (!optionKey) return;
  const allowed = value === "All" || state.filterOptions[optionKey].includes(value);
  invariant(allowed, `invalid ${key} ${value}`);
}

export function createCanonicalProjectControls(state) {
  invariant(state && typeof state === "object", "state is unavailable");
  return Object.freeze({
    snapshot() {
      return buildCanonicalProjectControlsView(state);
    },
    setFilter(key, value) {
      invariant(hasValidatedModel(state), "validated project model is unavailable");
      validateControlValue(state, key, value);
      setCanonicalProjectFilter(state, key, value);
      return buildCanonicalProjectControlsView(state);
    },
    reset() {
      invariant(hasValidatedModel(state), "validated project model is unavailable");
      resetCanonicalProjectFilters(state);
      return buildCanonicalProjectControlsView(state);
    },
  });
}

Canonical Project Export

A JavaScript module in the plugins folder of GlobalGrid2050 that joins refs (`joinRefs`) and builds canonical project CSV (`buildCanonicalProjectCsv`). It joins refs (`joinRefs`) and builds canonical project CSV (`buildCanonicalProjectCsv`).

Set aside from the main view: 93% of its lines are the same as uk_renewables_pipeline/v7/scripts/plugins/canonical-project-export.js (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 92% of lines shared with Canonical Project Export; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9266 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_renewables_pipeline/v7/scripts/plugins/canonical-project-export.js:1-125 1b06e9ad97590690d032b05b00e1ec63472b882a
  • sha256 3ec75298c9029a7b959022f80c43c00ea864eb98dbadaafb9de1de43b3679b8f
  • target sha256 6a89629b67f68f0b98686d8a7a42805c43a7c02abaa75547e46ad5ff9885e8f6
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

transformglobalgrid2050 / testcode/202609051152/pipeline/scripts/plugins/canonical-project-export.js · lines 1–129 of 129 · version 2026-09-05 11:52 · Not reached from any entry point (candidate for review) · pattern neutraliseSpreadsheetFormula (shared by 2 files)

What it does
It calculates its inputs. Defines 6 functions or classes, including invariant, joinRefs, neutraliseSpreadsheetFormula, quoteCsvCell, isoDate.
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.
Inputs & outputs
Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
Downstream impact
Used directly by 5 files: Projects (globalgrid2050); Check V7 2 Project Table Export (globalgrid2050); Check V8 1 Mvp (globalgrid2050); Check V9 0 (globalgrid2050); and 1 more.
What it achieves
Defines `invariant`, `joinRefs`, `neutraliseSpreadsheetFormula` and 3 more.
Why it matters
Imported by Projects. Checked by 4 tests, including Check V7 2 Project Table Export.
Application
globalgrid2050 · testcode/202609051152/pipeline/scripts/plugins · JavaScript module
Uses
Canonical Project Table (import)
Used by
imported by Projects (import), imported by Check V7 2 Project Table Export (import), imported by Check V8 1 Mvp (import), imported by Check V9 0 (import), imported by Check V9 0 (import), mentioned in Standalone (comment link)
Produces
neutraliseSpreadsheetFormula, quoteCsvCell, buildCanonicalProjectCsv
Defines here
invariant, joinRefs, neutraliseSpreadsheetFormula, quoteCsvCell, isoDate, buildCanonicalProjectCsv
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/202609051152/pipeline/scripts/plugins/canonical-project-export.js:1-129 · blob e5a394526242363db7b5286203f5aa904ee04cd3 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: duplicate_candidate
import {
  buildAtlasV8Url,
  buildCanonicalProjectTableView,
} from "./canonical-project-table.js";

const CSV_BOM = "\ufeff";
const CSV_MIME_TYPE = "text/csv;charset=utf-8";

function invariant(condition, message) {
  if (!condition) throw new Error(`V7.2 canonical export: ${message}`);
}

function joinRefs(values) {
  return values.join("|");
}

const VALUE_GETTERS = Object.freeze({
  site_name: ({ project }) => project.name,
  repd_ref: ({ project }) => project.repd_ref,
  gg_project_id: ({ project }) => project.gg_project_id,
  gg_development_id: ({ project }) => project.gg_development_id,
  identity_status: ({ project }) => project.identity_status,
  identity_confidence: ({ project }) => project.identity_confidence,
  technology: ({ project }) => project.technology_label,
  repd_technology: ({ project }) => project.repd_technology,
  official_capacity: ({ project }) => project.capacity_mw,
  capacity_unit: ({ project }) => project.capacity_unit,
  official_status: ({ project }) => project.status,
  derived_lifecycle: ({ project }) => project.lifecycle,
  derived_lifecycle_view: ({ project }) => project.lifecycle_view,
  operator: ({ project }) => project.operator,
  county: ({ project }) => project.county,
  region: ({ project }) => project.region,
  country: ({ project }) => project.country,
  planning_authority: ({ project }) => project.planning_authority,
  planning_reference: ({ project }) => project.planning_application_reference,
  repd_record_updated: ({ project }) => project.repd_record_updated,
  planning_application_submitted: ({ project }) => project.planning_application_submitted,
  planning_application_withdrawn: ({ project }) => project.planning_application_withdrawn,
  planning_permission_granted: ({ project }) => project.planning_permission_granted,
  planning_permission_refused: ({ project }) => project.planning_permission_refused,
  planning_permission_expired: ({ project }) => project.planning_permission_expired,
  under_construction: ({ project }) => project.under_construction,
  operational: ({ project }) => project.operational,
  repd_old_ref: ({ project }) => project.repd_old_ref,
  direct_related_repd_refs: ({ project }) => joinRefs(project.direct_related_repd_refs),
  planning_sibling_repd_refs: ({ project }) => joinRefs(project.planning_sibling_repd_refs),
  development_repd_refs: ({ project }) => joinRefs(project.development_repd_refs),
  relationships_json: ({ project }) => JSON.stringify(project.relationships),
  geometry_status: ({ project }) => project.geometry_status,
  easting: ({ project }) => project.easting,
  northing: ({ project }) => project.northing,
  source_crs: ({ metadata }) => metadata.geometry_policy.source_crs,
  longitude: ({ project }) => project.longitude,
  latitude: ({ project }) => project.latitude,
  atlas_url: ({ project }) => buildAtlasV8Url(project),
  output_crs: ({ metadata }) => metadata.geometry_policy.output_crs,
  coordinate_transform: ({ metadata }) => metadata.geometry_policy.transform,
  coordinate_use: ({ metadata }) => metadata.geometry_policy.use,
  source_dataset: ({ metadata }) => metadata.source_provenance.dataset,
  source_row: ({ project }) => project.source_row,
  projects_sha256: ({ metadata }) => metadata.projects_sha256,
  source_identity_sha256: ({ metadata }) => metadata.source_identity_sha256,
  source_coordinate_fixture_sha256: ({ metadata }) => metadata.source_coordinate_fixture_sha256,
  source_workbook_sha256: ({ metadata }) => metadata.source_workbook_sha256,
  reconciliation: ({ metadata }) => metadata.source_provenance.reconciliation,
  legacy_news_signal: ({ tableRow }) => tableRow.primary.legacyNews.label,
  legacy_news_note: ({ tableRow }) => tableRow.primary.legacyNews.note,
});

export function neutraliseSpreadsheetFormula(value) {
  if (typeof value !== "string") return value;
  return /^(?:[=+\-@]|\s+[=+\-@]|\t|\r|\n)/u.test(value) ? `'${value}` : value;
}

export function quoteCsvCell(value) {
  const safe = neutraliseSpreadsheetFormula(value ?? "");
  return `"${String(safe).replaceAll('"', '""')}"`;
}

function isoDate(value) {
  if (value === undefined) return new Date().toISOString().slice(0, 10);
  const parsed = typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value)
    ? new Date(`${value}T00:00:00Z`)
    : null;
  invariant(
    parsed && Number.isFinite(parsed.getTime()) && parsed.toISOString().slice(0, 10) === value,
    "date must be a valid YYYY-MM-DD value",
  );
  return value;
}

export function buildCanonicalProjectCsv(state, { legacySignalResolver, date } = {}) {
  const snapshot = Object.freeze({
    filtered: state?.filtered,
    contract: state?.contract,
    metadata: state?.metadata,
  });
  const table = buildCanonicalProjectTableView(state, { legacySignalResolver });
  invariant(table.available, "validated canonical project model is unavailable");
  invariant(
    state.filtered === snapshot.filtered
      && state.contract === snapshot.contract
      && state.metadata === snapshot.metadata,
    "canonical state changed while the export was being built",
  );
  invariant(snapshot.contract.interface.export.scope === "current filtered rows only", "filtered export contract is absent");
  invariant(snapshot.contract.interface.export.zero_results === "header only", "zero-result export contract is absent");
  const columns = snapshot.contract.interface.export.columns;
  invariant(Array.isArray(columns) && columns.length > 0, "export columns are absent");
  invariant(columns.every((column) => typeof VALUE_GETTERS[column.id] === "function"), "export contains an unknown column");
  invariant(snapshot.filtered.length === table.rows.length, "table and filtered export row counts disagree");

  const lines = [columns.map((column) => quoteCsvCell(column.label)).join(",")];
  snapshot.filtered.forEach((project, index) => {
    const context = { project, metadata: snapshot.metadata, tableRow: table.rows[index] };
    lines.push(columns.map((column) => quoteCsvCell(VALUE_GETTERS[column.id](context))).join(","));
  });
  const content = `${CSV_BOM}${lines.join("\r\n")}`;
  const filename = `globalgrid2050_uk_renewables_pipeline_v9_0_${isoDate(date)}.csv`;
  return Object.freeze({
    content,
    filename,
    mimeType: CSV_MIME_TYPE,
    rowCount: snapshot.filtered.length,
    columnCount: columns.length,
    encoding: "UTF-8 with BOM",
  });
}

Canonical Project Table

A JavaScript module in the plugins folder of GlobalGrid2050 that works with the Renewable Energy Planning Database (REPD) register.

Set aside from the main view: 91% of its lines are the same as uk_renewables_pipeline/v7/scripts/plugins/canonical-project-table.js (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 91% of lines shared with Canonical Project Table; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9127 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_renewables_pipeline/v7/scripts/plugins/canonical-project-table.js:1-283 a581ade3fd318c51cbaeeb03c6c82efa400b5b4e
  • sha256 e086946da97557054db908315fd38f4b8b67148d2a2fcc88a5a4cb1d567c8b99
  • target sha256 c5125a3701ab289d915e08aa631596fd5664cf23c6025dca1fb18a0b3717b94f
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

transformglobalgrid2050 / testcode/202609051152/pipeline/scripts/plugins/canonical-project-table.js · lines 1–311 of 311 · version 2026-09-05 11:52 · Not reached from any entry point (candidate for review) · pattern displayOfficialDate (shared by 2 files)

What it does
It calculates the REPD register. Defines 15 functions or classes, including invariant, deepFreeze, hasValidatedModel, isCanonicalOrder, displayOfficial.
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.
Inputs & outputs
Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
Downstream impact
Used directly by 5 files: Canonical Project Export (globalgrid2050); Projects (globalgrid2050); Check V7 2 Project Table Export (globalgrid2050); Check V8 1 Mvp (globalgrid2050); and 1 more.
What it achieves
It builds atlas v8 URL (`buildAtlasV8Url`), builds canonical news search URL (`buildCanonicalNewsSearchUrl`) and validates published metadata (`validatePublishedMetadata`). Defines `invariant`, `deepFreeze`, `hasValidatedModel` and 12 more.
Why it matters
Imported by Canonical Project Export and Projects. Checked by 3 tests, including Check V7 2 Project Table Export.
Application
globalgrid2050 · testcode/202609051152/pipeline/scripts/plugins · JavaScript module
Uses
Atlas Receiver V9 7 (import)
Used by
imported by Canonical Project Export (import), imported by Projects (import), imported by Check V7 2 Project Table Export (import), imported by Check V8 1 Mvp (import), imported by Check V9 0 (import), mentioned in Standalone (comment link)
Produces
buildAtlasV8Url, buildCanonicalNewsSearchUrl, buildCanonicalProjectTableView
Defines here
invariant, deepFreeze, hasValidatedModel, isCanonicalOrder, displayOfficial, displayCapacity, displayOfficialDate, buildAtlasV8Url, sameFlatRecord, buildCanonicalNewsSearchUrl, legacyNewsFor, validatePublishedMetadata, evidenceFor, rowFor, buildCanonicalProjectTableView
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/202609051152/pipeline/scripts/plugins/canonical-project-table.js:1-311 · blob 8c983a2777b1d5950891afe737d692c951879189 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: unreached_review
import { buildAtlasDeepLinkV9_7 } from "../core/atlas-receiver-v9-7.js";

const CAPACITY_BASIS = "official_repd_record_capacity_not_development_deduplicated";
const NO_RELATIONSHIPS = "none recorded";
const LEGACY_NEWS_AUTHORITY = "external legacy intelligence — unverified";

function invariant(condition, message) {
  if (!condition) throw new Error(`V7.2 canonical table: ${message}`);
}

function deepFreeze(value) {
  if (!value || typeof value !== "object" || Object.isFrozen(value)) return value;
  Object.values(value).forEach(deepFreeze);
  return Object.freeze(value);
}

function hasValidatedModel(state) {
  return Boolean(
    state?.contract
    && state?.metadata
    && Array.isArray(state.all)
    && state.all.length > 0
    && Array.isArray(state.filtered),
  );
}

function isCanonicalOrder(projects) {
  return projects.every((project, index) => {
    if (index === 0) return true;
    const previous = projects[index - 1];
    return previous.capacity_mw > project.capacity_mw
      || (
        previous.capacity_mw === project.capacity_mw
        && previous.gg_project_id.localeCompare(project.gg_project_id) <= 0
      );
  });
}

function displayOfficial(value, missingValueLabel) {
  return value === null || value === undefined || value === "" ? missingValueLabel : String(value);
}

function displayCapacity(project) {
  return `${new Intl.NumberFormat("en-GB", { maximumFractionDigits: 2 }).format(project.capacity_mw)} ${project.capacity_unit}`;
}

function displayOfficialDate(value, missingValueLabel) {
  if (!value) return missingValueLabel;
  const [year, month, day] = value.split("-");
  return `${day}/${month}/${year}`;
}

/* The name is kept because the CSV column it feeds is a published
   contract pinned by contracts/projects-plugin.v7.2.json and by
   tests/check_v9_0.mjs. What it BUILDS is now the receiver the engine
   publishes as canonical; renaming the column is a separate, governed
   decision and is recorded as an erratum rather than taken here. */
export function buildAtlasV8Url(project) {
  return buildAtlasDeepLinkV9_7(project);
}

function sameFlatRecord(left, right) {
  if (!left || !right || typeof left !== "object" || typeof right !== "object") return false;
  const keys = Object.keys(left).sort();
  return keys.join("\n") === Object.keys(right).sort().join("\n")
    && keys.every((key) => left[key] === right[key]);
}

export function buildCanonicalNewsSearchUrl(project) {
  const url = new URL("https://www.google.com/search");
  url.searchParams.set("q", `${project.name} ${project.technology_label} UK`);
  url.searchParams.set("tbm", "nws");
  return url.href;
}

function legacyNewsFor(project, resolver) {
  if (typeof resolver !== "function") {
    return {
      authority: LEGACY_NEWS_AUTHORITY,
      verified: false,
      status: "not_evaluated_in_isolated_v7_2",
      label: "not evaluated",
      note: "Trusted project-event binding is V7.3 scope",
    };
  }
  try {
    const result = resolver(project);
    const label = typeof result?.label === "string" && result.label.trim()
      ? result.label.trim()
      : "no matched legacy headline";
    const note = typeof result?.note === "string" && result.note.trim()
      ? result.note.trim()
      : "No legacy-news note supplied";
    return {
      authority: LEGACY_NEWS_AUTHORITY,
      verified: false,
      status: label === "no matched legacy headline" ? "no_match" : "legacy_match_unverified",
      label,
      note,
    };
  } catch {
    return {
      authority: LEGACY_NEWS_AUTHORITY,
      verified: false,
      status: "legacy_news_unavailable",
      label: "legacy news unavailable",
      note: "Legacy news resolver failed",
    };
  }
}

function validatePublishedMetadata(state) {
  const expected = state.contract.canonical_universe.published_snapshot;
  const actual = state.metadata;
  invariant(expected && typeof expected === "object", "published snapshot contract is absent");
  for (const field of [
    "projects_sha256",
    "source_identity_sha256",
    "source_coordinate_fixture_sha256",
    "source_workbook_sha256",
  ]) {
    invariant(actual[field] === expected[field], `${field} is not the contracted published value`);
  }
  invariant(sameFlatRecord(actual.source_provenance, expected.source_provenance), "source provenance is not the contracted published value");
  invariant(sameFlatRecord(actual.geometry_policy, expected.geometry_policy), "geometry policy is not the contracted published value");
}

function evidenceFor(project, state, inScopeRefs, missingValueLabel) {
  const milestoneFields = state.contract.interface.official_milestone_fields;
  const milestones = Object.fromEntries(milestoneFields.map((field) => [
    field,
    {
      value: project[field],
      display: displayOfficial(project[field], missingValueLabel),
      authority: "official REPD field",
    },
  ]));
  const relationships = project.relationships.map((relationship) => ({
    repdRef: relationship.repd_ref,
    type: relationship.type,
    sourceField: relationship.source_field,
    targetInCurrentUniverse: inScopeRefs.has(relationship.repd_ref),
  }));
  const metadata = state.metadata;
  return {
    identity: {
      ggDevelopmentId: project.gg_development_id,
      status: project.identity_status,
      confidence: project.identity_confidence,
    },
    officialPlanning: {
      authority: project.planning_authority,
      repdRecordUpdated: {
        value: project.repd_record_updated,
        display: displayOfficial(project.repd_record_updated, missingValueLabel),
      },
      milestones,
    },
    lifecycle: {
      value: project.lifecycle,
      view: project.lifecycle_view,
      derived: true,
      note: "Derived lifecycle; does not replace the official REPD status",
    },
    relationships: {
      items: relationships,
      display: relationships.length ? null : NO_RELATIONSHIPS,
      directRelatedRepdRefs: [...project.direct_related_repd_refs],
      planningSiblingRepdRefs: [...project.planning_sibling_repd_refs],
      developmentRepdRefs: [...project.development_repd_refs],
      outOfScopeTargetsRemainContextOnly: true,
    },
    geometry: {
      status: project.geometry_status,
      easting: project.easting,
      northing: project.northing,
      longitude: project.longitude,
      latitude: project.latitude,
      coordinateSource: project.coordinate_source,
      policy: { ...metadata.geometry_policy },
      contextOnly: true,
    },
    provenance: {
      kind: "published snapshot metadata",
      dataset: metadata.source_provenance.dataset,
      sourcePath: state.source,
      sourceRow: project.source_row,
      projectsSha256: metadata.projects_sha256,
      sourceIdentitySha256: metadata.source_identity_sha256,
      sourceCoordinateFixtureSha256: metadata.source_coordinate_fixture_sha256,
      sourceWorkbookSha256: metadata.source_workbook_sha256,
      canonicalIdentitySourceXlsxSha256: metadata.source_provenance.canonical_identity_source_xlsx_sha256,
      coordinateWorkbookCopySha256: metadata.source_provenance.coordinate_workbook_copy_sha256,
      reconciliation: metadata.source_provenance.reconciliation,
      note: "Published snapshot metadata; not recomputed by the browser",
    },
  };
}

function rowFor(project, state, inScopeRefs, resolver, missingValueLabel) {
  const legacyNews = legacyNewsFor(project, resolver);
  return {
    key: project.gg_project_id,
    primary: {
      project: project.name,
      location: [project.county, project.region, project.country].filter(Boolean).join(", "),
      operator: project.operator,
      technology: project.technology_label,
      officialStatus: project.status,
      capacity: {
        value: project.capacity_mw,
        unit: project.capacity_unit,
        display: displayCapacity(project),
        authority: "official REPD record",
      },
      repdRef: project.repd_ref,
      ggProjectId: project.gg_project_id,
      planningReference: displayOfficial(project.planning_application_reference, missingValueLabel),
      repdRecordUpdated: {
        value: project.repd_record_updated,
        display: displayOfficialDate(project.repd_record_updated, missingValueLabel),
        authority: "official REPD field",
      },
      atlas: {
        label: "Open Atlas V8",
        url: buildAtlasV8Url(project),
        exactFocusSupported: project.geometry_status === "valid",
        note: "Atlas V8 opens with canonical coordinates supplied, but does not yet consume the deep-link parameters",
      },
      legacyNews,
      news: {
        label: "Search news",
        url: buildCanonicalNewsSearchUrl(project),
        role: "external search context; not canonical evidence",
      },
    },
    evidence: evidenceFor(project, state, inScopeRefs, missingValueLabel),
  };
}

export function buildCanonicalProjectTableView(state, { legacySignalResolver } = {}) {
  if (!hasValidatedModel(state)) {
    return deepFreeze({
      available: false,
      status: state?.status || "idle",
      error: state?.error || null,
      columns: [],
      evidenceFields: [],
      rows: null,
      rowCount: null,
      missingValueLabel: null,
      capacityBasis: CAPACITY_BASIS,
    });
  }

  const snapshot = Object.freeze({
    all: state.all,
    filtered: state.filtered,
    contract: state.contract,
    metadata: state.metadata,
    source: state.source,
    status: state.status,
    error: state.error,
  });
  validatePublishedMetadata(snapshot);
  const primaryFields = snapshot.contract.interface.primary_table_fields;
  invariant(Array.isArray(primaryFields) && primaryFields.length === 13, "13-column table contract is absent");
  invariant(
    primaryFields.map((field) => field.label).join("\n")
      === snapshot.contract.interface.primary_table_columns.join("\n"),
    "table field labels do not match the frozen column order",
  );
  const canonicalById = new Map(snapshot.all.map((project) => [project.gg_project_id, project]));
  const inScopeRefs = new Set(snapshot.all.map((project) => project.repd_ref));
  invariant(
    snapshot.filtered.every((project) => canonicalById.get(project.gg_project_id) === project),
    "filtered rows are not exact canonical project objects",
  );
  invariant(
    new Set(snapshot.filtered.map((project) => project.gg_project_id)).size === snapshot.filtered.length,
    "filtered rows contain a duplicate canonical project",
  );
  invariant(isCanonicalOrder(snapshot.filtered), "filtered rows are not in canonical capacity/project-ID order");
  const missingValueLabel = snapshot.contract.interface.missing_value_label;
  const rows = snapshot.filtered.map((project) => rowFor(
    project,
    snapshot,
    inScopeRefs,
    legacySignalResolver,
    missingValueLabel,
  ));
  invariant(
    state.all === snapshot.all
      && state.filtered === snapshot.filtered
      && state.contract === snapshot.contract
      && state.metadata === snapshot.metadata
      && state.source === snapshot.source,
    "canonical state changed while the table view was being built",
  );
  return deepFreeze({
    available: true,
    status: snapshot.status,
    error: snapshot.error,
    columns: primaryFields.map((field) => ({ ...field })),
    evidenceFields: [...snapshot.contract.interface.evidence_fields],
    rows,
    rowCount: rows.length,
    missingValueLabel,
    capacityBasis: CAPACITY_BASIS,
  });
}

Capacity Presentation V9 3

A JavaScript module in the plugins folder of GlobalGrid2050 that parses display (`parseDisplayNumber`), formats whole MW v9 (`formatWholeMwV9_3`) and applies gauge (`applyGaugeValue`) (units: MW).

energy-dataglobalgrid2050 / testcode/202609051152/pipeline/scripts/plugins/capacity-presentation-v9-3.js · lines 1–57 of 57 · version 2026-09-05 11:52 · Entry point · pattern observe (shared by 13 files)

What it does
Defines 7 functions or classes, including parseDisplayNumber, formatWholeMwV9_3, applyGaugeValue, applyResultsSummary, applyWholeMwPresentationV9_3. Side effects: changes the web page (DOM).
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.
Downstream impact
Used directly by 15 files: GlobalGrid2050 — UK Renewables Pipeline Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/); UK Renewables Pipeline — V9 4 Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/v9.4/); UK Renewables Pipeline — V9 5 1 Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/v9.5.1/); UK Renewables Pipeline — V9 5 Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/v9.5/); and 11 more. Reached from 176 other entry points, including GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); GlobalGrid2050 — PipelineNews Intelligence Page (globalgrid2050, https://globalgrid2050.com/pipelinenews_intelligence/202609050309/).
What it achieves
It parses display number (`parseDisplayNumber`), formats whole MW v9 (`formatWholeMwV9_3`) and applies gauge (`applyGaugeValue`). Defines `parseDisplayNumber`, `formatWholeMwV9_3`, `applyGaugeValue` and 4 more. It responds to DOMContentLoaded events.
Why it matters
Loaded by the UK Renewables Pipeline page at https://globalgrid2050.com/uk_renewables_pipeline/202611280922/ and 14 other pages.
Application
globalgrid2050 · testcode/202609051152/pipeline/scripts/plugins · JavaScript module
Uses
none found
Used by
loaded by GlobalGrid2050 — UK Renewables Pipeline Page (script src), loaded by UK Renewables Pipeline — V9 4 Page (script src), loaded by UK Renewables Pipeline — V9 5 1 Page (script src), loaded by UK Renewables Pipeline — V9 5 Page (script src), loaded by UK Renewables Pipeline — V9 6 1 Page (script src), loaded by UK Renewables Pipeline — V9 6 2 Page (script src), loaded by UK Renewables Pipeline — V9 6 Page (script src), loaded by UK Renewables Pipeline — V9 7 Page (script src), and 7 more, mentioned in Standalone (comment link)
Produces
formatWholeMwV9_3, applyWholeMwPresentationV9_3
Defines here
parseDisplayNumber, formatWholeMwV9_3, applyGaugeValue, applyResultsSummary, applyWholeMwPresentationV9_3, observe, initialiseWholeMwPresentationV9_3
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/202609051152/pipeline/scripts/plugins/capacity-presentation-v9-3.js:1-57 · blob 9054ec9ba841807ad3887960f9e11e57a65065d8 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: production_core
const observers = [];

function parseDisplayNumber(value) {
  const numeric = Number(String(value ?? "").replaceAll(",", "").trim());
  return Number.isFinite(numeric) ? numeric : null;
}

export function formatWholeMwV9_3(value) {
  const numeric = parseDisplayNumber(value);
  return (numeric ?? 0).toLocaleString("en-GB", { maximumFractionDigits: 0 });
}

function applyGaugeValue() {
  const element = document.getElementById("v1");
  if (!element) return;
  const numeric = parseDisplayNumber(element.textContent);
  if (numeric === null) return;
  const formatted = formatWholeMwV9_3(numeric);
  if (element.textContent !== formatted) element.textContent = formatted;
  element.setAttribute("aria-label", `${formatted} megawatts filtered capacity`);
}

function applyResultsSummary() {
  const element = document.getElementById("resultsMeta");
  if (!element) return;
  const current = element.textContent || "";
  const formatted = current.replace(
    /(\d[\d,]*(?:\.\d+)?) MW · largest/,
    (_match, capacity) => `${formatWholeMwV9_3(capacity)} MW · largest`,
  );
  if (formatted !== current) element.textContent = formatted;
}

export function applyWholeMwPresentationV9_3() {
  applyGaugeValue();
  applyResultsSummary();
}

function observe(element) {
  if (!element) return;
  const observer = new MutationObserver(applyWholeMwPresentationV9_3);
  observer.observe(element, { childList: true, characterData: true, subtree: true });
  observers.push(observer);
}

function initialiseWholeMwPresentationV9_3() {
  observers.splice(0).forEach((observer) => observer.disconnect());
  applyWholeMwPresentationV9_3();
  observe(document.getElementById("v1"));
  observe(document.getElementById("resultsMeta"));
}

if (document.readyState === "loading") {
  document.addEventListener("DOMContentLoaded", initialiseWholeMwPresentationV9_3, { once: true });
} else {
  initialiseWholeMwPresentationV9_3();
}