GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / code-generator / apps/substation-finder/Si

Substation Intelligence V9 63 (part 6)

A JavaScript file in the substation finder folder of Code Generator that maps elizabeth line and uses data from the ventus-grid-engine repository. Served with the page at https://ventusltd.github.io/code-generator/apps/substation-finder/Si/.

700 lines of JavaScript from code-generator, in 1 file. Topic: Grid network and substations. Section 288 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. Substation Intelligence V9 63 geodesy · code-generator / apps/substation-finder/Si/202609062358-substation-intelligence-v9-63.js lines 3501–4200

Substation Intelligence V9 63

A JavaScript file in the substation finder folder of Code Generator that maps elizabeth line and uses data from the ventus-grid-engine repository. Served with the page at https://ventusltd.github.io/code-generator/apps/substation-finder/Si/.

Set aside from the main view: 100% of its lines are the same as atlas/cartridges/202611180026-substation-intelligence-v9-63.js (gridatlas), which stays. (near-copy-of, proposed by families.py). 99% of lines shared with Substation Intelligence V9 63; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9974 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/cartridges/202611180026-substation-intelligence-v9-63.js:1-8609 c6f9632fdb6e803baae03a54a542fe508431d153
  • sha256 d94b0de50deddac77643325b10fbe490ce44b8c406dbc6c67e6e7cadbdaa8ec6
  • target sha256 88c538b97bf426776cda436151741f17500a2136867d28362407550d72f9038f
  • group of 4 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

geodesycode-generator / apps/substation-finder/Si/202609062358-substation-intelligence-v9-63.js · lines 3501–4200 of 8590 · version 2026-09-06 23:58 (continued from section 283) · Not reached from any entry point (candidate for review) · pattern switchOn (shared by 4 files)

What it does
It maps elizabeth line, london underground, UK metros trams and hs2. Defines 238 functions or classes, including deepFreeze, escapeHTML, normalizeStatus, fmt, haversine. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'substation'): 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: 750kV, 400kV, 275kV, 132kV, 66kV, 33kV.
Inputs & outputs
In: data source: ventus-grid-engine data; data source: data-federation-map-for-globalgrid2050-all-repos data; data source: spiders data; data source: npm data; GeoJSON file elizabeth_line.geojson; GeoJSON file london_underground.geojson; GeoJSON file uk_metros_trams.geojson; GeoJSON file hs2.geojson. Out: downloaded file gridatlas-; downloaded file globalgrid2050-grid-atlas-; interactive map; canvas drawing; SVG drawing. Voltage levels named: 750kV, 400kV, 275kV, 132kV, 66kV, 33kV, 11kV.
What it achieves
It normalizes status (`normalizeStatus`), toggles zone draw mode (`toggleZoneDrawMode`) and opens popup (`openPopup`). ASSEMBLED by `tools/build-cartridge.mjs` from the parts below. Its code works with 400 kV, 100 MVA and 132 kV. It responds to fullscreenchange, webkitfullscreenchange and click events.
Why it matters
No other file in the estate was found to import it.
Application
code-generator · apps/substation-finder/Si · script
VEDIC
SNAP LINE ENDS TO SUBSTATIONS (GG2050-VEDIC-000106): GridAtlas / Substations · Geospatial data processing. line_features, substation_point_features → Line features whose first and last vertices are moved onto the nearest substation point within tolerance; other geometry unchanged.
VEDIC
MEASURE (GG2050-VEDIC-000001): GridAtlas / Geodesy · Mathematics / Spherical geometry. coordinate_pair, coordinate_pair → distance_km
VEDIC
REPRESENT (GG2050-VEDIC-000002): GridAtlas / Geodesy · Computer science / Geometry processing. geojson_geometry → coordinate_pair_or_null
Uses
Spider Full Po Test (estate URL), Data — Grid Studies Public Page (estate URL)
Used by
none found
Produces
deepFreeze, escapeHTML, normalizeStatus, fmt, haversine, _zoneDrawGetRadius, _zoneDrawCirclePoints, _zoneDrawCalcArea, _zoneDrawUpdateLayers, _zoneDrawShowPopup, _zoneDrawShowPopupDebounced, _zoneDrawClear
Defines here
at, asString, asNumber, bandKey, index, ownerOfNode, relation, describe, at, band, count, byPair, boundaries, pin, url, encode, digestBytes, digestHex, verify
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Si/202609062358-substation-intelligence-v9-63.js:3501-4200 · blob 2c8121b277e1b152a96688f6a2e0d7ef83471376 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
        status: asString(row.status),
        asset,
        from_node: nearNode,
        to_node: farNode,
        from_site_code: nearSiteCode,
        to_site_code: farSiteCode,
        to_site_name: farSite ? farSite.name : null,
        within_this_site: !!farSiteCode && farSiteCode === nearSiteCode,
        /* trusted only where the site declares it; null otherwise */
        from_voltage_kv: graph.nodeVoltageKv(nearNode),
        to_voltage_kv: graph.has(farNode) ? graph.nodeVoltageKv(farNode) : null,
        transmission_owner: asString(row.transmission_owner),
        labels: Array.isArray(row.labels) ? row.labels.slice() : [],
        /* carried, never computed with */
        parameters_pct_100mva: graph.parametersOf(row),
        pair_published_today: graph.has(farNode)
          ? publishedToday(graph, nearNode, farNode)
          : { circuit: false, transformer: false }
      };
      if (asset === 'transformer') {
        entry.rating_mva = asNumber(row.rating_mva);
        entry.voltage_ratio_kv = asString(row.voltage_ratio_kv);
      } else {
        entry.circuit_type = asString(row.circuit_type);
        entry.ohl_km = asNumber(row.ohl_km);
        entry.cable_km = asNumber(row.cable_km);
        entry.ratings_mva = graph.ratingsOf(row);
      }
      return entry;
    }

    /**
     * Every planned change landing at one site, grouped by year and then
     * by status. A row landing on two nodes of the same site is reported
     * once, from the first node it is met at in sorted node order.
     *
     * @param key      site code or exact site name
     * @param options  { voltageKv } to restrict to rows landing on a node
     *                 the site declares at that voltage
     */
    function at(key, options) {
      const site = base.site(key);
      if (!site) return null;
      const opts = options || {};
      const voltageKv = Number.isFinite(opts.voltageKv) ? opts.voltageKv : null;

      const nodes = graph.nodesOfSite(site.code)
        .filter((name) => voltageKv == null || graph.nodeVoltageKv(name) === voltageKv);

      const seen = new Set();
      const entries = [];
      for (const nodeName of nodes) {
        for (const landing of byNode.get(nodeName) || []) {
          if (seen.has(landing.row)) continue;
          seen.add(landing.row);
          entries.push(describe(landing, nodeName));
        }
      }

      /* year -> status -> entries, in a stable presentation order */
      const years = new Map();
      for (const entry of entries) {
        const y = entry.year || 'unstated';
        if (!years.has(y)) years.set(y, new Map());
        const statuses = years.get(y);
        const s = entry.status || 'unstated';
        if (!statuses.has(s)) statuses.set(s, []);
        statuses.get(s).push(entry);
      }

      const by_year = [...years.entries()]
        .sort((a, b) => yearRank(a[0]) - yearRank(b[0]) || a[0].localeCompare(b[0]))
        .map(([year, statuses]) => {
          const by_status = [...statuses.entries()]
            .sort((a, b) => statusRank(a[0]) - statusRank(b[0]) || a[0].localeCompare(b[0]))
            .map(([status, list]) => {
              list.sort((a, b) => String(a.to_node).localeCompare(String(b.to_node)));
              const by_asset = {};
              for (const a of ASSETS) by_asset[a] = list.filter((e) => e.asset === a).length;
              return { status, entries: list, counts: { entries: list.length, by_asset } };
            });
          const counts = { entries: 0, by_status: {} };
          for (const group of by_status) {
            counts.entries += group.counts.entries;
            counts.by_status[group.status] = group.counts.entries;
          }
          return { year, by_status, counts };
        });

      const counts = { planned_changes: entries.length, by_year: {}, by_status: {}, by_asset: {} };
      for (const y of by_year) counts.by_year[y.year] = y.counts.entries;
      for (const e of entries) {
        const s = e.status || 'unstated';
        const a = e.asset || 'unstated';
        counts.by_status[s] = (counts.by_status[s] || 0) + 1;
        counts.by_asset[a] = (counts.by_asset[a] || 0) + 1;
      }
      counts.on_a_pair_published_today = entries
        .filter((e) => e.pair_published_today.circuit || e.pair_published_today.transformer).length;

      return {
        schema: SCHEMA,
        source: ACCEPTS,
        site: { code: site.code, name: site.name },
        requested_voltage_kv: voltageKv,
        scope: voltageKv == null
          ? 'rows landing on any node of this site; each entry carries the '
            + 'declared voltage of the node it lands on, and undeclared is '
            + 'undeclared'
          : 'rows landing on a node this site declares at ' + voltageKv + ' kV only',
        nodes_considered: nodes.length,
        by_year,
        counts,
        not_existing: NOT_EXISTING,
        not_a_commitment: NOT_A_COMMITMENT,
        not_an_assessment: NOT_AN_ASSESSMENT,
        impedance_basis: IMPEDANCE_BASIS
      };
    }

    return {
      schema: SCHEMA,
      source: ACCEPTS,
      counts: Object.assign({ planned_changes: rows.length }, tally),
      site: base.site,
      at
    };
  }

  NS.plannedChange = Object.freeze({
    schema: SCHEMA,
    accepts: ACCEPTS,
    requires: REQUIRES,
    status_order: STATUS_ORDER,
    not_existing: NOT_EXISTING,
    not_a_commitment: NOT_A_COMMITMENT,
    not_an_assessment: NOT_AN_ASSESSMENT,
    impedance_basis: IMPEDANCE_BASIS,
    index
  });
})();

/**
 * Module: owner-boundary
 *
 * Which transmission owner the published assets at a site belong to, and
 * which circuits cross from one owner's network into another's.
 *
 * WHY THIS EXISTS
 * ---------------
 * Great Britain's transmission network is not one network. Appendix B
 * publishes a `transmission_owner` on every site, node, circuit and
 * transformer, and four values occur: NGET in England and Wales, SPT in
 * southern Scotland, SHET in the north of Scotland, and OFTO for the
 * offshore assets. Most circuits sit wholly inside one owner's network.
 * Sixty-two do not: their two ends are nodes that different owners
 * publish, and a circuit like that is the seam between two networks.
 *
 * That seam is worth naming because a connection near it involves more
 * than one party. It is a fact about who publishes what, read straight
 * off the product, and it is reported here with both owners named on
 * every boundary circuit so that nobody has to infer it from a map colour.
 *
 * WHAT IT IS NOT
 * --------------
 * Ownership is not a statement about who a project would contract with.
 * Connection agreements in Great Britain are made with the system operator
 * and the relevant owner under a framework this data does not describe,
 * and a site being NGET's says nothing about the counterparty, the process
 * or the terms of any connection at it. This module reports the published
 * owner of the published assets and stops there.
 *
 * Nor is an owner ever inferred. Forty-nine nodes publish no owner - all
 * of them on placeholder site codes such as OFFS and ONSH that the product
 * does not list as sites - and where a node's owner is not published it is
 * reported as unknown. A circuit with an unknown end is reported as
 * undetermined, not as a boundary and not as internal. Nothing is read
 * from a site name, a node code or a neighbour.
 *
 * TWO DIFFERENT FACTS, KEPT APART
 * -------------------------------
 * A circuit carries its own `transmission_owner`, and so do the nodes at
 * its two ends. A BOUNDARY circuit is one whose two END nodes belong to
 * different owners. Separately, seven circuits in the product carry an
 * owner that matches neither end - SPT and OFTO circuits between SHET
 * nodes at Hunterston, Inverness and Nedd. That is not a boundary by the
 * definition above; it is the asset's own published owner differing from
 * the owner of the nodes it lands on, and it is reported as exactly that.
 *
 * Voltages are trusted only where the site declares them and never decoded
 * from a node code; assets are counted per voltage and never across
 * voltages. R, X and B are carried and never computed with. No rating here
 * is headroom.
 *
 *   node tools/proofs/modules/202609012350-owner-boundary.proof.mjs
 */
(() => {
  'use strict';

  const NS = window.__GRIDATLAS_MODULES__ = window.__GRIDATLAS_MODULES__ || {};
  if (NS.ownerBoundary) return;

  const SCHEMA = 'gridatlas.module.owner-boundary.v1';
  const ACCEPTS = 'data-grid-gb.transmission-network.v1';
  const REQUIRES = 'gridatlas.module.network-topology.graph.v1';

  const NOT_A_COUNTERPARTY =
    'The transmission owner is the party the network operator publishes '
    + 'as owning an asset. It is not a statement about who a project would '
    + 'contract with, under what process, or on what terms; none of that '
    + 'is in any published appendix.';

  const NOT_AN_ASSESSMENT =
    'An ownership boundary is a fact about who publishes which asset. It '
    + 'says nothing about whether any project can connect on either side '
    + 'of it, and a rating on a boundary circuit is that circuit\'s rating, '
    + 'not a spare allowance across the boundary.';

  const NEVER_INFERRED =
    'An owner is reported only where the product publishes one on the '
    + 'record in question. A node with no published owner is unknown, a '
    + 'circuit with an unknown end is undetermined, and nothing is read '
    + 'from a site name, a node code or a neighbour.';

  const UNKNOWN = 'unknown';
  const UNDECLARED = 'undeclared';

  const asString = (v) => (typeof v === 'string' && v.length ? v : null);
  const asNumber = (v) => (Number.isFinite(v) ? v : null);
  const bandKey = (kv) => (kv == null ? UNDECLARED : String(kv));

  /**
   * @param product  the parsed data-grid-gb transmission-network payload
   * @returns an index, or null if the schema is not the one this reads
   */
  function index(product) {
    if (!product || product.schema !== ACCEPTS) return null;
    const topology = NS.networkTopology;
    if (!topology || typeof topology.index !== 'function') return null;
    const base = topology.index(product);
    if (!base || typeof base.graph !== 'function') return null;
    const graph = base.graph();
    if (!graph || graph.schema !== REQUIRES) return null;

    /* The owner of a NODE, from the node record and nowhere else. The
       graph does not hand this out, so it is read from the product here;
       the graph is still the only authority on which nodes exist, which
       site they belong to and what voltage may be trusted. */
    const nodeOwner = new Map();
    for (const node of product.nodes || []) {
      if (node && node.node) nodeOwner.set(node.node, asString(node.transmission_owner));
    }
    const ownerOfNode = (name) => (nodeOwner.has(name) ? nodeOwner.get(name) : null);

    /**
     * The relation between the two ends of a branch, by published owner.
     *   'boundary'     both ends published, and they differ
     *   'internal'     both ends published, and they agree
     *   'undetermined' at least one end publishes no owner
     */
    function relation(nearOwner, farOwner) {
      if (nearOwner == null || farOwner == null) return 'undetermined';
      return nearOwner === farOwner ? 'internal' : 'boundary';
    }

    function describe(entry, nearNode) {
      const row = entry.row;
      const farNode = row[entry.far];
      const nearOwner = ownerOfNode(nearNode);
      const farOwner = graph.has(farNode) ? ownerOfNode(farNode) : null;
      const assetOwner = asString(row.transmission_owner);
      const nearSiteCode = graph.nodeSiteCode(nearNode) || null;
      const farSiteCode = graph.has(farNode) ? graph.nodeSiteCode(farNode) || null : null;
      const farSite = farSiteCode ? graph.siteByCode(farSiteCode) : null;
      const out = {
        kind: entry.kind,
        from_node: nearNode,
        to_node: farNode,
        from_site_code: nearSiteCode,
        to_site_code: farSiteCode,
        to_site_name: farSite ? farSite.name : null,
        within_this_site: !!farSiteCode && farSiteCode === nearSiteCode,
        from_voltage_kv: graph.nodeVoltageKv(nearNode),
        to_voltage_kv: graph.has(farNode) ? graph.nodeVoltageKv(farNode) : null,
        /* the three published owners, each named for what it is */
        from_owner: nearOwner || UNKNOWN,
        to_owner: farOwner || UNKNOWN,
        asset_owner: assetOwner || UNKNOWN,
        ends: relation(nearOwner, farOwner),
        /* the asset's own owner set against the ends it lands on; null
           where either end is unknown, because "matches neither" cannot
           be said of an end that has not been published */
        asset_owner_matches_an_end: assetOwner && nearOwner && farOwner
          ? (assetOwner === nearOwner || assetOwner === farOwner)
          : null,
        /* carried, never computed with */
        parameters_pct_100mva: graph.parametersOf(row)
      };
      if (entry.kind === 'circuit') {
        out.circuit_type = asString(row.circuit_type);
        out.ohl_km = asNumber(row.ohl_km);
        out.cable_km = asNumber(row.cable_km);
        out.ratings_mva = graph.ratingsOf(row);
      } else {
        out.rating_mva = asNumber(row.rating_mva);
        out.voltage_ratio_kv = asString(row.voltage_ratio_kv);
      }
      return out;
    }

    /**
     * Ownership at one site: the site's own published owner, the owner of
     * each of its nodes, the assets landing on those nodes counted per
     * owner within each voltage, and every boundary branch named with both
     * owners.
     *
     * @param key      site code or exact site name
     * @param options  { voltageKv } to restrict to nodes the site declares
     *                 at that voltage
     */
    function at(key, options) {
      const site = base.site(key);
      if (!site) return null;
      const opts = options || {};
      const voltageKv = Number.isFinite(opts.voltageKv) ? opts.voltageKv : null;

      const nodeNames = graph.nodesOfSite(site.code)
        .filter((name) => voltageKv == null || graph.nodeVoltageKv(name) === voltageKv);

      const nodes = nodeNames.map((name) => ({
        node: name,
        voltage_kv: graph.nodeVoltageKv(name),
        transmission_owner: ownerOfNode(name) || UNKNOWN
      }));

      /* Assets are counted once per site even when both ends are here,
         and grouped under the declared voltage of the node they were
         first met at in sorted node order. */
      const seen = new Set();
      const bands = new Map();
      const boundary_circuits = [];
      const boundary_transformers = [];
      const undetermined = [];
      const asset_owner_differs = [];

      function band(kv) {
        const k = bandKey(kv);
        if (!bands.has(k)) {
          bands.set(k, { voltage_kv: kv, by_owner: {}, circuits: 0, transformers: 0, nodes: 0 });
        }
        return bands.get(k);
      }
      function count(b, owner, what) {
        const o = owner || UNKNOWN;
        if (!b.by_owner[o]) b.by_owner[o] = { nodes: 0, circuits: 0, transformers: 0 };
        b.by_owner[o][what] += 1;
        b[what] += 1;
      }

      for (const n of nodes) count(band(n.voltage_kv), n.transmission_owner, 'nodes');

      for (const nodeName of nodeNames) {
        for (const entry of graph.edgesAt(nodeName)) {
          if (seen.has(entry.row)) continue;
          seen.add(entry.row);
          const d = describe(entry, nodeName);
          const b = band(d.from_voltage_kv);
          count(b, d.asset_owner === UNKNOWN ? null : d.asset_owner,
            entry.kind === 'circuit' ? 'circuits' : 'transformers');
          if (d.ends === 'boundary') {
            (entry.kind === 'circuit' ? boundary_circuits : boundary_transformers).push(d);
          } else if (d.ends === 'undetermined') {
            undetermined.push(d);
          }
          if (d.asset_owner_matches_an_end === false) asset_owner_differs.push(d);
        }
      }

      const by_voltage = [...bands.entries()]
        .sort((a, b) => {
          if (a[0] === UNDECLARED) return 1;
          if (b[0] === UNDECLARED) return -1;
          return Number(b[0]) - Number(a[0]);
        })
        .map(([, b]) => b);

      const owners = new Set();
      for (const b of by_voltage) for (const o of Object.keys(b.by_owner)) owners.add(o);

      const byPair = (list) => list.sort((a, b) =>
        String(a.from_node).localeCompare(String(b.from_node))
        || String(a.to_node).localeCompare(String(b.to_node)));

      return {
        schema: SCHEMA,
        source: ACCEPTS,
        site: {
          code: site.code,
          name: site.name,
          transmission_owner: asString(site.transmission_owner) || UNKNOWN
        },
        requested_voltage_kv: voltageKv,
        scope: voltageKv == null
          ? 'every node of this site, counted within its own declared voltage; '
            + 'no count here spans two voltages'
          : 'nodes this site declares at ' + voltageKv + ' kV only',
        nodes,
        by_voltage,
        owners_present: [...owners].sort(),
        boundary_circuits: byPair(boundary_circuits),
        boundary_transformers: byPair(boundary_transformers),
        undetermined: byPair(undetermined),
        asset_owner_differs_from_both_ends: byPair(asset_owner_differs),
        counts: {
          nodes: nodes.length,
          nodes_with_unknown_owner: nodes.filter((n) => n.transmission_owner === UNKNOWN).length,
          owners_present: owners.size,
          circuits: by_voltage.reduce((s, b) => s + b.circuits, 0),
          transformers: by_voltage.reduce((s, b) => s + b.transformers, 0),
          boundary_circuits: boundary_circuits.length,
          boundary_transformers: boundary_transformers.length,
          undetermined: undetermined.length,
          asset_owner_differs_from_both_ends: asset_owner_differs.length
        },
        not_a_counterparty: NOT_A_COUNTERPARTY,
        never_inferred: NEVER_INFERRED,
        not_an_assessment: NOT_AN_ASSESSMENT
      };
    }

    /**
     * Every boundary branch in the product, each reported once, with both
     * owners named. The seam between the networks as a list.
     */
    function boundaries() {
      const out = [];
      const seen = new Set();
      const pairs = {};
      for (const [kind, rows] of [['circuit', product.circuits], ['transformer', product.transformers]]) {
        for (const row of rows || []) {
          if (!row || seen.has(row)) continue;
          seen.add(row);
          const d = describe({ kind, row, near: 'node_1', far: 'node_2' }, row.node_1);
          if (d.ends !== 'boundary') continue;
          out.push(d);
          const pair = [d.from_owner, d.to_owner].sort().join('/');
          pairs[pair] = (pairs[pair] || 0) + 1;
        }
      }
      return {
        schema: SCHEMA,
        source: ACCEPTS,
        branches: out.sort((a, b) =>
          String(a.from_node).localeCompare(String(b.from_node))
          || String(a.to_node).localeCompare(String(b.to_node))),
        counts: {
          boundary_circuits: out.filter((d) => d.kind === 'circuit').length,
          boundary_transformers: out.filter((d) => d.kind === 'transformer').length,
          by_owner_pair: pairs
        },
        not_a_counterparty: NOT_A_COUNTERPARTY,
        never_inferred: NEVER_INFERRED,
        not_an_assessment: NOT_AN_ASSESSMENT
      };
    }

    const ownerTally = {};
    for (const node of product.nodes || []) {
      const o = (node && asString(node.transmission_owner)) || UNKNOWN;
      ownerTally[o] = (ownerTally[o] || 0) + 1;
    }

    return {
      schema: SCHEMA,
      source: ACCEPTS,
      counts: {
        nodes: nodeOwner.size,
        nodes_by_owner: ownerTally
      },
      site: base.site,
      at,
      boundaries
    };
  }

  NS.ownerBoundary = Object.freeze({
    schema: SCHEMA,
    accepts: ACCEPTS,
    requires: REQUIRES,
    unknown: UNKNOWN,
    not_a_counterparty: NOT_A_COUNTERPARTY,
    never_inferred: NEVER_INFERRED,
    not_an_assessment: NOT_AN_ASSESSMENT,
    index
  });
})();

/* ══════════════════════════════════════════════════════════════════════
   pinned-products - the runtime data this Atlas reads, by commit and by digest
   ══════════════════════════════════════════════════════════════════════

   A published Atlas release is immutable. Three of its runtime fetches were
   not: they named a BRANCH.

     data-grid-gb        main/derived/connection-points.v3.json
     data-grid-gb        main/derived/gb-transmission-network.v1.json
     data-gb-electricity main/derived/price-decade-rollup.json

   The only defence was a schema string, and a schema string defends SHAPE
   and is blind to VALUES. On 2026-09-03 that stopped being theoretical. A
   correction on data-grid-gb - branch codex/20260903-phase0-integrity,
   commit b91e45b - publishes deduplicated transformer counts under the
   IDENTICAL schema `data-grid-gb.connection-points.v3`:

     COWLEY   transformers  10 -> 5
     ABHAM    transformers   4 -> 2
     located                502 -> 489     (886 points either way)

   Every record in the file differs. A factor of two on a number the card
   prints, invisible to every check the consumer had. An immutable release
   would have changed what it said with none of its own bytes changing.

   So the ref is a commit and the bytes are hashed. The NESO inputs upstream
   are pinned by SHA-256 with exactly this rationale - document ids are
   stable and "latest" links are not - and the discipline simply had not
   reached the estate's own last hop.

   MOVING A PIN IS A CUT, AND THAT IS THE POINT. A data correction and a map
   release become one event a reader can see. It is also a real cost: the
   correction above does NOT reach a reader until the pin moves here. That is
   the right trade, because the alternative is not knowing which of the two
   numbers is on the card - and this file is where a human decides.

   This module lives in the substation-intelligence cartridge, which the
   shell evaluates before the sandbox, so both consumers read one table
   rather than each carrying its own copy of the constants and the digest
   arithmetic.
   ══════════════════════════════════════════════════════════════════════ */
(() => {
  'use strict';

  const SCHEMA = 'gridatlas.module.pinned-products.v1';
  const RAW = 'https://raw.githubusercontent.com/Ventusltd/';

  /* Each entry: the repository, the 40-character commit the Atlas was built
     against, the path, and the SHA-256 of the bytes served at that commit.
     `bytes` is recorded beside the digest because a truncated response is
     the failure mode a digest catches last and a length catches first. */
  const PINS = {
    'connection-points.v3': {
      repository: 'data-grid-gb',
      ref: '1c9909d1138704b29235c27fd769436dda8a0b18',
      path: 'derived/connection-points.v3.json',
      sha256: '11e28859a6d17cc8ee4047c2032d55d043be98f7123743f3b2b03225e07a4c0c',
      bytes: 2896561,
      schema: 'data-grid-gb.connection-points.v3'
    },
    'gb-transmission-network.v1': {
      repository: 'data-grid-gb',
      ref: '1c9909d1138704b29235c27fd769436dda8a0b18',
      path: 'derived/gb-transmission-network.v1.json',
      sha256: 'fc331cc20b061f85adf18d890762a164328a1c5e84acef6a23d35d36f849fc8a',
      bytes: 10069966,
      schema: 'data-grid-gb.transmission-network.v1'
    },
    'price-decade-rollup': {
      repository: 'data-gb-electricity',
      ref: 'd310e3cec8cd14bc7cd3eef1e37037197bcb0798',
      path: 'derived/price-decade-rollup.json',
      sha256: '18da5059c93cf09f6036bfcaabf56afaedf16d5f03e664c3cf0b0cff1dca970d',
      bytes: 6873,
      schema: 'data-gb-electricity.price-decade-rollup.v2'
    }
  };

  function pin(id) {
    return Object.prototype.hasOwnProperty.call(PINS, id) ? PINS[id] : null;
  }

  function url(id) {
    const entry = pin(id);
    return entry ? RAW + entry.repository + '/' + entry.ref + '/' + entry.path : null;
  }

  /* Absent crypto is NOT a mismatch.
     ------------------------------------------------------------------
     `crypto.subtle` exists only in a secure context, so a page served over
     plain http - a local check-out, a preview server - has no digest to
     offer. That is reported as unverified and the product is still read.
     Only a real disagreement between the bytes and the recorded digest
     refuses, because refusing on absence would make the Atlas unusable
     anywhere but production while proving nothing about the bytes. */
  function encode(text) {
    try {
      return typeof TextEncoder === 'function'
        ? new TextEncoder().encode(text) : null;
    } catch (_) { return null; }
  }

  async function digestBytes(bytes) {
    try {
      const subtle = (window.crypto || {}).subtle;
      if (!subtle || !bytes) return null;
      const digest = await subtle.digest('SHA-256', bytes);
      return Array.from(new Uint8Array(digest))
        .map(byte => byte.toString(16).padStart(2, '0')).join('');
    } catch (_) {
      /* A thrown digest is an unavailable digest, not a wrong one. */
      return null;
    }
  }

  async function digestHex(text) {
    return digestBytes(encode(text));
  }

  /**
   * @returns { state, sha256, expected, ref, bytes_seen, bytes_expected }
   *   state is 'verified', 'MISMATCH', or a stated reason it is unverified.
   *   Only 'MISMATCH' means the caller must refuse.
   *
   * `bytes_seen` is BYTES. The first cut of this module reported
   * `text.length`, which is UTF-16 code units: the node/branch product is
   * 10,069,964 characters and 10,069,966 bytes, so the field disagreed with
   * the `bytes` it was being compared against by two, on a file that was
   * entirely correct. A length is checked as well as a digest because
   * truncation is the failure a length names immediately and a digest only
   * says "different" about.
   */
  async function verify(id, text) {
    const entry = pin(id);
    const bytes = encode(text);
    const seen = bytes ? bytes.length : null;
    if (!entry) {
      return { state: 'unverified: no pin for ' + String(id), sha256: null,
        expected: null, ref: null, bytes_seen: seen, bytes_expected: null };
    }
    const digest = await digestBytes(bytes);
    const answer = { sha256: digest, expected: entry.sha256, ref: entry.ref,
      bytes_seen: seen, bytes_expected: entry.bytes };
    if (seen !== null && seen !== entry.bytes) {
      answer.state = 'MISMATCH';
      answer.detail = 'the response at ' + entry.ref + ' is ' + seen
        + ' bytes, not the recorded ' + entry.bytes;
    } else if (digest === null) {
      answer.state = 'unverified: no subtle crypto in this context';
    } else if (digest === entry.sha256) {
      answer.state = 'verified';
    } else {
      answer.state = 'MISMATCH';
      answer.detail = 'bytes at ' + entry.ref + ' hash to ' + digest
        + ', not the recorded ' + entry.sha256;
    }
    return answer;
  }

  const NS = (window.__GRIDATLAS_MODULES__ = window.__GRIDATLAS_MODULES__ || {});
  NS.pinnedProducts = Object.freeze({
    schema: SCHEMA,
    ids: Object.freeze(Object.keys(PINS)),
    pin,
    url,
    digestHex,
    verify,
    why: 'A branch ref lets an immutable release change what it says without '
      + 'any of its own bytes changing. The schema string defends shape and is '
      + 'blind to values: a correction to data-grid-gb halves published '
      + 'transformer counts under the same schema. The ref is a commit and the '
      + 'bytes are hashed, so a data correction and a map release are one event.',
    not_an_assessment: 'A pin says which bytes were read. It says nothing '
      + 'about whether those bytes are right.'
  });
})();

/* ══════════════════════════════════════════════════════════════════════
   version-ledger - what every generation of this Atlas changed
   ══════════════════════════════════════════════════════════════════════

   The page shows its own version history (202609010204, v9.40), and the cut
   writes the newest row rather than a human appending it (202609012130,
   v9.65, after v9.64 shipped a ledger whose newest entry named v9.63 and so
   told a reader it was running the generation before the one it was running).

   It lived in the sandbox body. That is 13,655 characters of pure data in the
   cartridge with the least room: the sandbox stood at 339,367 characters
   against the 340,000 guard its own proof asserts, and every cut adds another
   row. Three card-facing changes could not be made without either raising
   that guard - which v9.76 considered and rejected, and so did every cut
   tonight - or moving something out.

   So it moves to the cartridge that has room, exactly as the five network
   modules did at v9.76. The shell evaluates substation-intelligence before
   the sandbox, so the sandbox reads it the same way it reads geodesy.

   The array literal below keeps its exact original spelling, because that
   spelling is what tools/recompose.mjs matches when it appends a row at the
   cut. Naming it here in full would be matched too - and was: the first
   version of this comment quoted the declaration, recompose found the comment
   before it found the data, and tried to JSON.parse this sentence. A comment
   that a tool reads is code. The