GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / gridatlas / tools/overnight/steps

Grid at Point and 1 more file

A JavaScript module in the steps folder of GridAtlas covering cables. It runs grid point (`runGridAtPoint`) and is built from the once step (`once`) and the show step (`show`).

613 lines of JavaScript from gridatlas, in 2 files. Topic: Maps, GIS and field navigation. Section 643 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. Injection Response render · gridatlas / tools/overnight/steps/202609012320-injection-response.mjs lines 1–242
  2. Grid at Point render · gridatlas / tools/overnight/steps/202609012330-grid-at-point.mjs lines 1–371

Injection Response

A JavaScript module in the steps folder of GridAtlas covering 400kV. It is built from the flow model for helper (`flowModelFor`) and the injection step (`injection`).

rendergridatlas / tools/overnight/steps/202609012320-injection-response.mjs · lines 1–242 of 242 · version 2026-09-01 23:20 · Not reached from any entry point (candidate for review) · pattern flowModelFor (shared by 10 files)

What it does
It lists and searches 400kV. Defines flowModelFor, injection. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): 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: 400kV.
Inputs & outputs
Voltage levels named: 400kV.
What it achieves
The Atlas answers where a project's power would actually go. Its code works with 400 kV, 100 MVA and 100 MW.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · tools/overnight/steps · JavaScript module
Uses
none found
Used by
none found
Produces
flowModelFor, injection
Defines here
flowModelFor, injection
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/overnight/steps/202609012320-injection-response.mjs:1-242 · blob d274a377eeb0930aea3eaa0954297ea2fb995d34 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/**
 * Step: the Atlas answers where a project's power would actually go.
 *
 * This is the powerflow, and it is the first computation in this estate
 * that solves anything rather than reporting a published figure.
 *
 * The standing rule has been that R, X and B are carried and never
 * computed with, because the ETYS node/branch dataset is not a solved
 * power-flow model merely because it contains them. That rule stands. What
 * it forbids is calling published parameters a solution; what it always
 * pointed at is a model that DECLARES itself - its equations, base, slack,
 * assumptions and validation - and is honest about what it cannot produce.
 *
 * A full AC load flow needs generation and load at every node, tap
 * positions, voltage set points and contingencies. None are published, so
 * none are invented and no load flow is claimed. An INJECTION RESPONSE
 * needs none of them: it is the linear sensitivity of branch flows to a
 * transfer between two declared points, and it depends only on topology
 * and series reactance, both of which are published.
 *
 * It is validated against networks whose answers are exact by hand -
 * parallel paths dividing inversely as their reactances, a symmetric ring
 * dividing two-thirds and one-third, reciprocity under reversal - to 1e-9,
 * and then power conservation is checked at all 339 intermediate buses of
 * the real 400 kV network. There is no commercial solver in this estate
 * and pretending one had been used would be worse than having none.
 *
 * The card uses the capacity Pipeline News already sends in the deep link,
 * so the journey from a project to "which circuits would carry my output"
 * is one click. What it never says is whether there is room: existing
 * flows are published nowhere, so the total - which is what decides
 * whether a circuit is full - cannot be computed by anyone here.
 */

const MODULE = 'atlas/modules/202609012320-injection-response.js';
const PROOF = 'tools/proofs/modules/202609012320-injection-response.proof.mjs';
const BODY = 'atlas/parts/202609012045-sld-sandbox-body.js';
const CI = 'tools/ci/202609012200-local-ci.mjs';

export default {
  id: 'injection-response',
  version: 'v9.73',
  scope: 'the Atlas solves a declared DC injection response on the published node/branch model and reports which circuits would carry a project\'s stated capacity and what fraction each takes, with the equations, the 100 MVA base, the named slack and every assumption carried in the answer; validated to 1e-9 against networks whose solutions are exact by hand and checked for power conservation at ev  … [line shortened here: 522 characters; full line on GitHub]
  note: 'the first computation here that solves rather than reports; resistance and susceptance are untouched because the declared DC model says they are, a zero-reactance branch is shorted as the busbar it physically is rather than given an invented reactance, and a branch with no published reactance is skipped and counted',

  brings: [MODULE, PROOF],
  addModules: [MODULE],
  proofs: [PROOF],

  apply({ read, write, patch, sandboxProof }) {
    let body = read(BODY);

    const ANCHOR = `  function ratingModule() {`;
    if (body.split(ANCHOR).length - 1 !== 1) throw new Error('ratingModule anchor is not unique');
    body = body.replace(ANCHOR, `  function flowModule() {
    try { return window.__GRIDATLAS_MODULES__?.injectionResponse || null; }
    catch (_) { return null; }
  }

  /* The 400 kV model is built once per session and kept: assembling it
     walks every published node, and a card that rebuilt it per click
     would be doing that work again for an answer it already had.

     The node list comes from topology.nodes400, which ensureTopology
     records while it already has the parsed product in hand. Rebuilding
     it here would mean either keeping a second copy of the 10 MB payload
     alive or asking the graph for something it does not expose. */
  let flowModel = null;
  function flowModelFor(index) {
    if (flowModel) return flowModel;
    const mod = flowModule();
    if (!mod || !index || typeof index.graph !== 'function') return null;
    const names = topology.nodes400;
    if (!Array.isArray(names) || !names.length) return null;
    try {
      flowModel = mod.assemble(index.graph(), names,
        { voltageKv: 400, includeTransformers: false });
      return flowModel;
    } catch (_) { return null; }
  }

${ANCHOR}`);

    /* the injection sentence, after the ratings and the reach */
    const REACH = `      /* Electrical distance, beside the one-hop view.`;
    if (body.split(REACH).length - 1 !== 1) throw new Error('electrical anchor is not unique');
    body = body.replace(REACH, `      /* Where the project's own power would go.
         ---------------------------------------------------------------
         Pipeline News sends capacity_mw on every deep link, so the
         question "where would MY output flow" is answerable the moment a
         project is selected. The slack is NAMED in the sentence: a
         transfer has two ends and quoting one of them is meaningless.
         What is deliberately absent is any statement about room. */
      const injection = (() => {
        const mod = flowModule();
        if (!mod || kv !== 400) return null;
        /* The project's own stated capacity where the deep link carried
           one, and a declared 100 MW probe otherwise - labelled as such in
           the sentence, never presented as the project's figure. */
        const mw = Number.isFinite(currentCapacityMw) && currentCapacityMw > 0
          ? currentCapacityMw : 100;
        const model = flowModelFor(topology.index);
        if (!model) return null;
        try {
          const graph = topology.index.graph();
          const here = graph.nodesOfSite(point.site_code)
            .filter(n => graph.nodeVoltageKv(n) === 400).sort()[0];
          if (!here) return null;
          const slackNode = model.buses.find(b => b !== model.busOf(here));
          if (!slackNode) return null;
          const r = mod.respond(model, { atNode: here, slackNode, mw, minimumShare: 0.05 });
          return r && r.validation && r.validation.passes ? r : null;
        } catch (_) { return null; }
      })();
      if (injection && injection.branches.length) {
        const top = injection.branches.slice(0, 3);
        out += caveat(\`<b>Where \${injection.injected_mw} MW would flow</b> \`
          + \`(declared DC model, 100 MVA base, transfer to \${escapeHtml(injection.slack_node)}): \`
          + top.map(b => \`\${escapeHtml(b.from_node)}-\${escapeHtml(b.to_node)} \`
            + \`\${Math.round(Math.abs(b.share_of_injection) * 100)}%\`
            + (b.published_ratings_mva && b.published_ratings_mva.summer
              ? \` (summer rating \${b.published_ratings_mva.summer} MVA)\` : '')).join(', ')
          + \`. Flat 1.0 pu voltages, small angles, no losses, no taps, intact network. \`
          + \`This is the response to a NEW injection, not a loading: what is already \`
          + \`flowing on these circuits is published nowhere, so whether there is room \`
          + \`for it cannot be computed here by anyone.\`);
        powerflow.answered += 1;
        powerflow.worst_kirchhoff_error = Math.max(powerflow.worst_kirchhoff_error,
          injection.validation.kirchhoff_error);
      }

${REACH}`);

    const STATE = `  window.__GRIDATLAS_RATINGS__ = rating;`;
    if (body.split(STATE).length - 1 !== 1) throw new Error('ratings state anchor is not unique');
    body = body.replace(STATE, `${STATE}

  /* Published so a reviewer can ask the page whether any answer it gave
     failed its own conservation check. A solve that has not converged
     produces plausible-looking flows that are wrong, so the error is
     surfaced rather than trusted. */
  const powerflow = { answered: 0, worst_kirchhoff_error: 0 };
  window.__GRIDATLAS_POWERFLOW__ = powerflow;`);

    /* The in-memory edits land first. Everything below reads BODY from
       disk, so a patch() called before this write would be silently
       discarded by it - which is exactly what happened on the first run
       of this step, and the sandbox proof caught it. */
    write(BODY, body);

    /* ── the 400 kV node list, recorded where the product is parsed ──
       ensureTopology already holds the whole 10 MB payload for one tick.
       Taking the node list there costs one pass and keeps no second copy
       of the payload alive; asking for it later would mean either
       re-fetching or exposing something the graph does not offer. */
    patch(BODY, [
      [`        topology.index = index;`,
       `        topology.index = index;
        /* the buses the declared DC model is built over. 400 kV only:
           a DC model that walks a transformer without its tap position
           is modelling something the product does not describe, and the
           taps are not published. */
        topology.nodes400 = (product.nodes || [])
          .filter(n => n && n.voltage_consistent_with_site === true && n.voltage_kv === 400)
          .map(n => n.node);`,
       'ensureTopology records the 400 kV nodes'],
    ]);

    /* ── the capacity the deep link carried, at module scope ─────────── */
    patch(BODY, [
      [`  let currentNearest400 = null;`,
       `  let currentNearest400 = null;
  /* The capacity Pipeline News sent, kept where the network card can
     reach it. Without this the powerflow answer would have to invent a
     figure, and an invented megawatt is exactly the kind of number that
     gets quoted back as the project's own. */
  let currentCapacityMw = null;`,
       'module-scope capacity slot'],
      [`        let stated = Number(q.get('capacity_mw'));`,
       `        let stated = Number(q.get('capacity_mw'));
        currentCapacityMw = Number.isFinite(stated) && stated > 0 ? stated : null;`,
       'capacity captured on arrival'],
      [`            if (Number.isFinite(cap) && cap > 0) stated = cap;`,
       `            if (Number.isFinite(cap) && cap > 0) stated = cap;
            currentCapacityMw = Number.isFinite(stated) && stated > 0 ? stated : null;`,
       'capacity updated when the search lane resolves it'],
    ]);

    patch(CI, [
      [`  ['rating envelope', ['tools/proofs/modules/202609012250-rating-envelope.proof.mjs']]
];`,
       `  ['rating envelope', ['tools/proofs/modules/202609012250-rating-envelope.proof.mjs']],
  ['injection response (powerflow)', ['tools/proofs/modules/202609012320-injection-response.proof.mjs']]
];`, 'CI gate list'],
    ]);

    const proof = read(sandboxProof);
    const TAIL = `console.log(\`\\n\${passed}/\${passed + failures.length} checks passed\`);`;
    if (proof.split(TAIL).length - 1 !== 1) throw new Error('sandbox proof tail anchor is not unique');
    write(sandboxProof, proof.replace(TAIL, `console.log('\\na declared powerflow, and what it refuses to say\\n');

check('the injection-response module is in the served cartridge',
  /gridatlas\\.module\\.injection-response\\.v1/.test(cartridgeSource));
check('it is evaluated before the body that calls it',
  cartridgeSource.indexOf('gridatlas.module.injection-response.v1')
    < cartridgeSource.indexOf('function flowModule('));
check('the served bytes never read resistance or susceptance into the flow model', (() => {
  const start = cartridgeSource.indexOf('gridatlas.module.injection-response.v1');
  const end = cartridgeSource.indexOf('NS.injectionResponse = Object.freeze');
  if (start < 0 || end < 0) return false;
  const mod = cartridgeSource.slice(start, end);
  return !/r_pct_100mva/.test(mod) && !/b_pct_100mva/.test(mod) && /x_pct_100mva/.test(mod);
})());
check('the card names the slack, because a transfer has two ends',
  /transfer to \\\$\\{escapeHtml\\(injection\\.slack_node\\)\\}/.test(cartridgeSource));
check('the card states the model assumptions where the reader sees them',
  /Flat 1\\.0 pu voltages, small angles, no losses, no taps, intact network/.test(cartridgeSource));
check('the card says plainly it is not a loading',
  /not a loading/.test(cartridgeSource)
  && /whether there is room/.test(cartridgeSource));
check('an answer that fails its own Kirchhoff check is discarded, not printed',
  /r\\.validation && r\\.validation\\.passes \\? r : null/.test(cartridgeSource));
check('the powerflow uses the capacity the deep link carries',
  /currentCapacityMw/.test(cartridgeSource)
  && /currentCapacityMw = Number\\.isFinite\\(stated\\)/.test(cartridgeSource));
check('the 400 kV node list is recorded once, where the product is already parsed',
  /topology\\.nodes400 = \\(product\\.nodes/.test(cartridgeSource));
check('the powerflow is scoped to 400 kV, never walked through an unmodelled tap',
  /kv !== 400\\) return null;/.test(cartridgeSource));
check('the conservation error is published for review',
  /window\\.__GRIDATLAS_POWERFLOW__ = powerflow;/.test(cartridgeSource));
check('the served bytes claim no headroom anywhere in the flow module', (() => {
  const start = cartridgeSource.indexOf('gridatlas.module.injection-response.v1');
  const end = cartridgeSource.indexOf('NS.injectionResponse = Object.freeze');
  const mod = cartridgeSource.slice(start, end)
    .split(/const NOT_A_[A-Z_]+ =[\\s\\S]*?';/).join(' ');
  return !/headroom/i.test(mod);
})());

${TAIL}`));
  }
};

Grid at Point

A JavaScript module in the steps folder of GridAtlas covering cables. It runs grid point (`runGridAtPoint`) and is built from the once step (`once`) and the show step (`show`).

rendergridatlas / tools/overnight/steps/202609012330-grid-at-point.mjs · lines 1–371 of 371 · version 2026-09-01 23:30 · Not reached from any entry point (candidate for review) · pattern topologyBlockHtml (shared by 10 files)

What it does
It draws cables. Defines once, runGridAtPoint, show, topologyBlockHtml, reflect. Side effects: changes the web page (DOM); uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): 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: cables.
Inputs & outputs
In: browser storage (getItem). Out: browser storage (setItem).
What it achieves
The grid computation stops needing a project. It responds to click events.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · tools/overnight/steps · JavaScript module
Uses
none found
Used by
none found
Produces
once, runGridAtPoint, show, topologyBlockHtml, reflect
Defines here
once, runGridAtPoint, show, topologyBlockHtml, reflect
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/overnight/steps/202609012330-grid-at-point.mjs:1-371 · blob 0ab4da419c2b769ca3b93c044753418504d36343 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/**
 * Step: the grid computation stops needing a project.
 *
 * Everything built tonight - the published circuits and transformers, the
 * seasonal ratings, the electrical distance in hops, the declared DC
 * powerflow - has only been reachable by arriving from Pipeline News with
 * a project in the URL. That is one journey, and it is the wrong one to
 * be the only one: the interesting question is often asked of a place, not
 * of a scheme that already exists.
 *
 * TWO CHANGES
 * -----------
 * 1. A tool in the tray arms "grid at point". The next click on open map
 *    resolves the nearest published connection points and renders the
 *    whole stack against the nearest one. The arming is explicit and
 *    follows the Scope chip's existing rule: a map that analysed every
 *    stray tap would put a card over the thing the reader was looking at.
 *
 * 2. The layers dash collapses and restores. It is 816 px tall on a
 *    desktop and occupies most of a phone, and until now the only way past
 *    it was fullscreen - which is a different mode with a different
 *    layout. A reader who wants to look at the map should not have to
 *    change mode to do it. The choice is remembered per browser.
 *
 * THE CAVEAT THAT HAS TO TRAVEL WITH "NEAREST"
 * --------------------------------------------
 * The owner product publishes 886 connection points and locates 502 of
 * them; the other 384 are published without coordinates because "a site
 * nobody has mapped is published without coordinates rather than dropped".
 * So "the nearest connection point" is really "the nearest of the 502 that
 * anyone has mapped", and there may be a closer one that OpenStreetMap has
 * never had a node for. The card says so every time. It is also a
 * straight-line distance and not a cable route, and it is not a statement
 * that anything can connect there.
 */

const BODY = 'atlas/parts/202609012045-sld-sandbox-body.js';

export default {
  id: 'grid-at-point',
  version: 'v9.74',

  scope: 'the grid computation is reachable from the map itself: a tool arms a point query, and a click on open map resolves the nearest published connection points and renders the published circuits, the seasonal ratings, the electrical distance in hops and the declared powerflow against the nearest one, saying every time that 384 of the 886 published points have no coordinates so the nearest MAP  … [line shortened here: 561 characters; full line on GitHub]

  note: 'the arming is explicit, following the Scope chip: a map that analysed every stray tap would cover the thing the reader was looking at. Distance to a point is straight-line and is not a cable route, and nothing here says anything can connect.',

  apply({ read, write, sandboxProof }) {
    let body = read(BODY);

    const once = (from, to, label) => {
      const n = body.split(from).length - 1;
      if (n !== 1) throw new Error(`anchor found ${n} times: ${label}`);
      body = body.replace(from, () => to);
    };

    /* ── 1. state ────────────────────────────────────────────────────── */
    once(`  let scopeArmed = false;`,
      `  let scopeArmed = false;
  /* Armed explicitly, like the scope. Published on the link object so a
     reviewer can ask the page which modes are live. */
  let pointArmed = false;`,
      'scope state');

    /* ── 2. the tool in the tray ─────────────────────────────────────── */
    once(`    const grid = quickChip('\\u26a1 Grid', GRID_LINE_LAYERS);`,
      `    /* The tray tool. The shell owns .map-controls and the shell is
       immutable, so the button is added by this cartridge at runtime and
       removed again if the cartridge is not composed - there is no orphan
       control left behind claiming a feature that is not present. */
    (function addGridPointTool() {
      const tray = document.querySelector('.map-controls');
      if (!tray || document.getElementById('btn-gridpoint')) return;
      const button = document.createElement('button');
      button.className = 'map-ctrl-btn';
      button.id = 'btn-gridpoint';
      button.type = 'button';
      button.textContent = '\\u25c8 Grid At Point';
      button.setAttribute('aria-pressed', 'false');
      button.title = 'Click anywhere on the map for the published network at the nearest mapped connection point';
      button.addEventListener('click', (event) => {
        event.stopPropagation();
        pointArmed = !pointArmed;
        button.setAttribute('aria-pressed', String(pointArmed));
        button.style.outline = pointArmed ? '1px solid currentColor' : '';
        link.grid_point_armed = pointArmed;
        if (!pointArmed) clearScope();
      });
      tray.appendChild(button);
    }());

    const grid = quickChip('\\u26a1 Grid', GRID_LINE_LAYERS);`,
      'tray tool');

    /* ── 3. the click ────────────────────────────────────────────────── */
    once(`          clearLinks();
          if (scopeArmed) await runGridScope(map, [event.lngLat.lng, event.lngLat.lat]);
          return;`,
      `          clearLinks();
          if (pointArmed) await runGridAtPoint(map, event.lngLat.lng, event.lngLat.lat);
          if (scopeArmed) await runGridScope(map, [event.lngLat.lng, event.lngLat.lat]);
          return;`,
      'click branch');

    /* ── 4. the answer ───────────────────────────────────────────────── */
    once(`  function topologyBlockHtml(queries) {`,
      `  /* The published network at an arbitrary point.
     ---------------------------------------------------------------------
     The connection-points cartridge already resolves a position to the
     nearest published sites, so this does not measure anything itself -
     a second distance implementation in this file is exactly the drift
     that put two geodesies in one cartridge. It resolves, states the
     limit of what "nearest" can mean here, and hands the nearest name to
     the block that already renders circuits, ratings, hops and flow. */
  async function runGridAtPoint(map, lon, lat) {
    const gl = window.maplibregl;
    if (!gl?.Popup) return;
    const network = window.__GRIDATLAS_NETWORK__ || null;
    const show = (html) => {
      try {
        return new gl.Popup({ maxWidth: '380px', closeOnClick: false })
          .setLngLat([lon, lat]).setHTML(html).addTo(map);
      } catch (error) {
        noteFailure('grid at point: ' + String(error?.message || error));
        return null;
      }
    };

    if (!network || typeof network.nearest !== 'function' || !network.loaded) {
      show('<p class="neon-caveat"><b>Grid at point:</b> the connection-points '
        + 'cartridge has not loaded, so no published site can be named. '
        + 'Nothing is inferred from its absence.</p>');
      return;
    }

    /* nearest() returns { point, km } pairs, sorted. It owns the distance;
       measuring again here would be the second implementation that put
       two geodesies in one cartridge earlier tonight. */
    let found = [];
    try { found = network.nearest(lon, lat, { limit: 5 }) || []; }
    catch (_) { found = []; }
    if (!Array.isArray(found)) found = found ? [found] : [];

    const points = Number(network.points || 0);
    const located = Number(network.located || 0);
    const unlocated = points - located;

    if (!found.length) {
      show('<p class="neon-caveat"><b>Grid at point:</b> no published connection '
        + 'point with coordinates resolved here. ' + unlocated + ' of the '
        + points + ' published points carry no coordinates at all, so this is '
        + 'a statement about the mapped set and not about the network.</p>');
      pointQuery.answered += 1;
      return;
    }

    const rows = found.map(entry => escapeHtml(String(entry.point?.name || '?'))
      + (Number.isFinite(entry.km) ? ' \\u00b7 ' + entry.km.toFixed(1) + ' km' : ''));

    const popup = show('<div class="neon-hd">Grid at this point'
      + '<span class="neon-beta">published network</span></div>'
      + '<p class="neon-caveat"><b>Nearest mapped connection points:</b> '
      + rows.join(', ') + '.</p>'
      + '<p class="neon-caveat">Straight-line distance from where you clicked - '
      + 'not a cable route, and not a statement that anything can connect at any '
      + 'of them. ' + unlocated + ' of the ' + points + ' published connection '
      + 'points have no coordinates, so the nearest <i>mapped</i> point may not '
      + 'be the nearest point.</p>'
      /* fillTopologyBlocks() selects by CLASS, not by a data attribute.
         Getting that wrong would have produced a block that renders its
         loading line forever and never fills. */
      + '<div class="' + TOPOLOGY_BLOCK + '" data-queries="'
      + escapeHtml(JSON.stringify([{ name: String(found[0].point?.name || ''), kv: null }])) + '">'
      + '<p class="neon-caveat"><b>Transmission network:</b> loading\\u2026</p></div>');

    pointQuery.answered += 1;
    if (!popup) return;
    try { await ensureTopology(); } catch (_) { /* the block reports its own state */ }
    fillTopologyBlocks();
  }

  function topologyBlockHtml(queries) {`,
      'the point answer');

    /* ── 5. state published for review ───────────────────────────────── */
    once(`  window.__GRIDATLAS_POWERFLOW__ = powerflow;`,
      `  window.__GRIDATLAS_POWERFLOW__ = powerflow;

  /* How many point queries the reader ran. A feature nobody can reach is
     indistinguishable from a feature that does not work, and this is the
     number that tells them apart. */
  const pointQuery = { answered: 0 };
  window.__GRIDATLAS_POINT_QUERY__ = pointQuery;`,
      'point query state');

    /* ── 6. the layers dash collapses ────────────────────────────────── */
    once(`  window.__GRIDATLAS_POINT_QUERY__ = pointQuery;`,
      `  window.__GRIDATLAS_POINT_QUERY__ = pointQuery;

  /* The layers dash collapses without entering fullscreen.
     ---------------------------------------------------------------------
     The dash is 816 px tall on a desktop and takes most of a phone, and
     the only way past it has been fullscreen - a different mode with a
     different layout, which is a large thing to ask of a reader who just
     wants to see the map. This collapses it in place and leaves a tab to
     bring it back.

     The choice is remembered per browser and every storage access is
     wrapped: a private window, cleared site data or a browser set to
     block storage all throw here, and a thrown error must not take the
     control with it. */
  (function dashCollapse() {
    const KEY = 'gridatlas.dash.collapsed';
    const dash = document.querySelector('.dashboard');
    if (!dash || document.getElementById('gridatlas-dash-toggle')) return;

    const style = document.createElement('style');
    style.textContent = '.dashboard[data-gridatlas-collapsed="1"]{max-height:0;'
      + 'overflow:hidden;padding-top:0;padding-bottom:0;border:0;}'
      + '#gridatlas-dash-toggle{position:fixed;right:12px;bottom:12px;z-index:9999;'
      + 'font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;'
      + 'letter-spacing:.08em;padding:8px 12px;border-radius:6px;cursor:pointer;'
      + 'background:#0d1117;color:#7fe3d0;border:1px solid #2b3a44;}'
      + '#gridatlas-dash-toggle:focus-visible{outline:2px solid #7fe3d0;outline-offset:2px;}';
    document.head.appendChild(style);

    const toggle = document.createElement('button');
    toggle.id = 'gridatlas-dash-toggle';
    toggle.type = 'button';

    let collapsed = false;
    try { collapsed = window.localStorage.getItem(KEY) === '1'; } catch (_) { collapsed = false; }

    function reflect() {
      if (collapsed) dash.setAttribute('data-gridatlas-collapsed', '1');
      else dash.removeAttribute('data-gridatlas-collapsed');
      toggle.textContent = collapsed ? '\\u25b4 LAYERS' : '\\u25be HIDE LAYERS';
      toggle.setAttribute('aria-pressed', String(collapsed));
      toggle.setAttribute('aria-label', collapsed
        ? 'Show the layers panel' : 'Hide the layers panel');
      /* MapLibre sizes itself to its container and will not notice the
         page reflowing under it. */
      try { if (window.map && typeof window.map.resize === 'function') window.map.resize(); }
      catch (_) { /* the control still works without the resize */ }
    }

    toggle.addEventListener('click', () => {
      collapsed = !collapsed;
      try { window.localStorage.setItem(KEY, collapsed ? '1' : '0'); } catch (_) { /* per-viewer nicety only */ }
      reflect();
    });

    document.body.appendChild(toggle);
    reflect();
    window.__GRIDATLAS_DASH__ = {
      get collapsed() { return collapsed; },
      toggle: () => { toggle.click(); return collapsed; }
    };
  }());`,
      'dash collapse');

    write(BODY, body);

    /* ── 7a. a positional guard becomes an enumerated one ─────────────
       The existing check proved the 10 MB product is not fetched at page
       load by scanning a SPAN of the file - everything between the
       declared table and topologyBlockHtml - for a call to the loader.
       The guarantee is right and must not be lost; the mechanism is
       positional, so any on-demand caller written inside that span turns
       it red for the wrong reason, which is what runGridAtPoint just did.

       It is replaced by an enumerated one: every call site is located,
       the enclosing function is named, and each name must be on an
       allow-list. That is a stronger claim than the span version - it
       covers the whole file rather than one region - and adding a caller
       now requires declaring it here, which is the point. */
    {
      const p = read(sandboxProof);
      const OLD = [
        "check('the module is never asked at load: the boot path does not touch the loader', (() => {",
        "  const boot = cartridgeSource.indexOf('function topologyBlockHtml(queries)');",
        "  const before = cartridgeSource.slice(cartridgeSource.indexOf('const DECLARED = '), boot);",
        "  return !/ensureTopology\\(\\)/.test(before.replace(/function ensureTopology\\(\\)[\\s\\S]*?\\n  \\}\\n/, ''));",
        "})());"
      ].join('\n');
      if (p.split(OLD).length - 1 !== 1) throw new Error('boot-path check anchor is not unique');
      const NEW = [
        "check('the loader is called only from named on-demand paths, never at load', (() => {",
        "  /* Every caller is enumerated. A new one must be added here, which",
        "     is the guarantee: the 10 MB product is fetched when a reader asks",
        "     a question, and never because the page opened. */",
        "  const ALLOWED = new Set(['topologyBlockHtml', 'runGridAtPoint']);",
        "  const found = [];",
        "  let at = cartridgeSource.indexOf('ensureTopology()');",
        "  while (at >= 0) {",
        "    const before = cartridgeSource.slice(0, at);",
        "    /* the declaration is not a call site; skip `function ensureTopology()` */",
        "    if (!/function\\s+$/.test(before.slice(-12))) {",
        "      const m = [...before.matchAll(/function\\s+(\\w+)\\s*\\(/g)].pop();",
        "      found.push(m ? m[1] : '<top level>');",
        "    }",
        "    at = cartridgeSource.indexOf('ensureTopology()', at + 1);",
        "  }",
        "  if (!found.length) return false;   // the loader vanished entirely",
        "  const strays = found.filter(name => !ALLOWED.has(name));",
        "  if (strays.length) console.log('    unexpected ensureTopology caller(s): ' + strays.join(', '));",
        "  return strays.length === 0;",
        "})());"
      ].join('\n');
      write(sandboxProof, p.split(OLD).join(NEW));
    }

    /* ── 7. the gate ─────────────────────────────────────────────────── */
    const proof = read(sandboxProof);
    const TAIL = 'console.log(`\\n${passed}/${passed + failures.length} checks passed`);';
    if (proof.split(TAIL).length - 1 !== 1) throw new Error('sandbox proof tail anchor is not unique');
    write(sandboxProof, proof.replace(TAIL, [
      "console.log('\\nthe grid computation without a project, and a dash that gets out of the way\\n');",
      '',
      "check('a tool is added to the shell tray, which the cartridge does not own',",
      "  /id = 'btn-gridpoint'/.test(cartridgeSource)",
      "  && /document\\.querySelector\\('\\.map-controls'\\)/.test(cartridgeSource));",
      "check('the tool does not duplicate itself if the cartridge runs twice',",
      "  /document\\.getElementById\\('btn-gridpoint'\\)\\) return;/.test(cartridgeSource));",
      "check('arming is explicit, as it is for the scope',",
      "  /let pointArmed = false;/.test(cartridgeSource)",
      "  && /pointArmed = !pointArmed;/.test(cartridgeSource));",
      "check('an unarmed click still does nothing new',",
      "  /if \\(pointArmed\\) await runGridAtPoint/.test(cartridgeSource));",
      "check('the point query never measures a distance itself',",
      "  (() => {",
      "    const start = cartridgeSource.indexOf('async function runGridAtPoint');",
      "    const end = cartridgeSource.indexOf('function topologyBlockHtml');",
      "    if (start < 0 || end < 0 || end < start) return false;",
      "    const fn = cartridgeSource.slice(start, end);",
      "    return /network\\.nearest\\(lon, lat/.test(fn)",
      "      && !/Math\\.atan2|Math\\.asin|6378\\.137/.test(fn);",
      "  })());",
      "/* A plain substring, not a regex: fillTopologyBlocks selects by CLASS",
      "   and getting this wrong produces a block that shows its loading line",
      "   forever and never fills - which no other check here would catch. */",
      "check('the block it writes is found by the filler, which selects by class',",
      "  cartridgeSource.includes(`'<div class=\"' + TOPOLOGY_BLOCK + '\" data-queries=\"'`)",
      "  && /querySelectorAll\\('\\.' \\+ TOPOLOGY_BLOCK\\)/.test(cartridgeSource));",
      "check('the reader is told that nearest MAPPED is not nearest',",
      "  /the nearest <i>mapped<\\/i> point may not/.test(cartridgeSource));",
      "check('the reader is told it is a straight line and not a cable route',",
      "  /not a cable route/.test(cartridgeSource));",
      "check('the point answer never claims anything can connect',",
      "  /not a statement that anything can connect/.test(cartridgeSource));",
      "check('an absent connection-points cartridge is an absence, not a guess',",
      "  /Nothing is inferred from its absence/.test(cartridgeSource));",
      "check('the layers dash can be collapsed without entering fullscreen',",
      "  /gridatlas-dash-toggle/.test(cartridgeSource)",
      "  && /data-gridatlas-collapsed/.test(cartridgeSource));",
      "check('the collapsed choice is remembered, and every storage access is guarded',",
      "  /localStorage\\.getItem\\(KEY\\)/.test(cartridgeSource)",
      "  && /localStorage\\.setItem\\(KEY/.test(cartridgeSource)",
      "  && (cartridgeSource.match(/catch \\(_\\) \\{ collapsed = false; \\}/) || []).length === 1);",
      "check('the map is told to resize when the dash moves under it',",
      "  /window\\.map\\.resize\\(\\)/.test(cartridgeSource));",
      "check('the toggle is reachable and labelled for assistive technology',",
      "  /aria-pressed/.test(cartridgeSource) && /aria-label/.test(cartridgeSource)",
      "  && /focus-visible/.test(cartridgeSource));",
      "check('both new surfaces are published for review',",
      "  /window\\.__GRIDATLAS_POINT_QUERY__ = pointQuery;/.test(cartridgeSource)",
      "  && /window\\.__GRIDATLAS_DASH__ = \\{/.test(cartridgeSource));",
      '',
      TAIL
    ].join('\n')));
  }
};