GLOBALGRID2050 / EXPLORE CODE

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

Powerflow Stopship and 4 more files

A JavaScript module in the steps folder of GridAtlas that works with 400kV. It is built from the once step (`once`).

551 lines of JavaScript from gridatlas, in 5 files. Topic: Maps, GIS and field navigation. Section 645 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. Owner Boundary render · gridatlas / tools/overnight/steps/202609012350-owner-boundary.mjs lines 524–700
  2. Powerflow Stopship transform · gridatlas / tools/overnight/steps/202609020015-powerflow-stopship.mjs lines 1–210
  3. Build storage · gridatlas / tools/pipeline-lifecycle/build.mjs lines 1–44
  4. Map Removal Test test · gridatlas / tools/pipeline-lifecycle/map-removal.test.mjs lines 1–104
  5. Build storage · gridatlas / tools/pipeline-vicinity/build.mjs lines 1–16

Owner Boundary

A JavaScript module in the steps folder of GridAtlas that reads substation intelligence seed parts and substations, using haversine.

rendergridatlas / tools/overnight/steps/202609012350-owner-boundary.mjs · lines 524–700 of 700 · version 2026-09-01 23:50 (continued from section 644) · Not reached from any entry point (candidate for review) · pattern ownerModule (shared by 10 files)

What it does
It loads substation intelligence seed parts and substations. Defines lf, once, ownerModule, ownership. Side effects: changes the web page (DOM); reads or writes files.
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: substations.
Inputs & outputs
In: JSON file current.json; JSON file 202609012350-substation-intelligence-seed-parts.json.
What it achieves
It is built from the once step (`once`), the owner module helper (`ownerModule`) and the ownership step (`ownership`). The computation leaves the sandbox, and ownership arrives.
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
lf, once, ownerModule, ownership
Defines here
none
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/202609012350-owner-boundary.mjs:524-700 · blob 096034f1050bc1a85dffe372dbfc1c4d29c997b3 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
      const TOP = 'vm.runInContext(geodesySource, geodesyBox, { filename: \'geodesy.js\' });';
      if (p2.split(TOP).length - 1 !== 1) throw new Error('geodesy load anchor is not unique');
      write(allVersions, p2.replace(TOP, [
        TOP,
        '',
        '/* The cartridge currently served, and the modules its siblings give it. */',
        'const CURRENT_COMPOSITION = JSON.parse(',
        "  await readFile(join(REPO, 'atlas', 'current.json'), 'utf8'));",
        'const currentSandboxFile = (() => {',
        "  const entry = (CURRENT_COMPOSITION.cartridges || []).find(c => c.id === 'sld-sandbox');",
        "  return entry ? String(entry.path).split('/').pop() : null;",
        '})();',
        'const siblingModules = await (async () => {',
        '  const out = [];',
        '  for (const entry of (CURRENT_COMPOSITION.cartridges || [])) {',
        "    if (entry.id === 'sld-sandbox' || !entry.assembled_from) continue;",
        '    let manifest;',
        '    try {',
        '      manifest = JSON.parse(await readFile(',
        "        join(REPO, 'atlas', String(entry.assembled_from).replace(/^\\.\\//, '')), 'utf8'));",
        '    } catch { continue; }',
        '    for (const part of (manifest.assembled_from || [])) {',
        "      if (part.role !== 'module') continue;",
        "      out.push(await readFile(join(REPO, part.path), 'utf8'));",
        '    }',
        '  }',
        "  return out.join('\\n');",
        '})();',
      ].join('\n')));
    }

    /* ── 6c. a schema requirement can live in another cartridge ───────
       The sandbox still FETCHES the transmission network - ensureTopology
       is in its body - but the schema it is validated against lives in
       the module, which moved. So the parity proof found the product
       named by the sandbox's bytes and the schema nowhere in them.

       The fetch is genuinely per-cartridge and stays checked per
       cartridge. The schema is a property of the COMPOSITION: the bytes
       that fetch and the bytes that validate ship together and are loaded
       together. Falling back to the composition for the schema keeps the
       real guarantee - a product is validated before it is believed -
       without asserting a layout the composition no longer has. */
    {
      const parity = 'tools/proofs/202609012214-data-contract-parity.proof.mjs';
      const p = read(parity);
      const OLD = '    const schema = p.schema_in_bytes || schemaFromModule(source, p.product);';
      if (p.split(OLD).length - 1 !== 1) throw new Error('parity schema anchor is not unique');
      write(parity, p.replace(OLD, [
        '    /* The schema may be declared by a module in a sibling cartridge:',
        '       since 202609012350 the network modules live in the cartridge',
        '       the shell loads first, while the fetch stayed in the sandbox.',
        '       Both ship in the same composition and load together, so the',
        '       composition is where the requirement is looked for. */',
        '    const schema = p.schema_in_bytes',
        '      || schemaFromModule(source, p.product)',
        '      || schemaFromModule(compositionSource, p.product);',
      ].join('\n')));

      const p2 = read(parity);
      const SRC_ANCHOR = '  const source = read(rel);';
      if (p2.split(SRC_ANCHOR).length - 1 !== 1) throw new Error('parity source anchor is not unique');
      write(parity, p2.replace(SRC_ANCHOR, [
        '  const source = read(rel);',
        '  /* every cartridge this composition serves, for the sibling lookup */',
        '  const compositionSource = (current.cartridges || [])',
        "    .map(c => read(path.join('atlas', String(c.path).replace('./', ''))))",
        "    .join('\\n');",
      ].join('\n')));
    }

    /* ── 6d. module-parity loads the sandbox too ─────────────────────
       The last harness with the same root cause. It compares the geodesy
       module against the measurement the served sandbox exposes, and it
       cannot get that measurement out of a cartridge whose geodesy now
       arrives from a sibling. Same fix, same reason. */
    {
      const parity = 'tools/proofs/modules/202609011950-module-parity.proof.mjs';
      const p = read(parity);
      const ANCHOR = 'const sandboxBox = sandboxContext();\n'
        + 'vm.createContext(sandboxBox);\n'
        + "vm.runInContext(sandboxSource, sandboxBox, { filename: 'sld-sandbox.js' });";
      if (p.split(ANCHOR).length - 1 !== 1) throw new Error('module-parity anchor is not unique');
      write(parity, p.replace(ANCHOR, [
        '/* The modules the composition supplies from another cartridge. Since',
        '   202609012350 the sandbox does not carry its own geodesy, so running',
        '   it alone throws before it registers anything to compare against. */',
        'const composition = JSON.parse(',
        "  await readFile(join(REPO, 'atlas', 'current.json'), 'utf8'));",
        'const siblingModules = await (async () => {',
        '  const out = [];',
        '  for (const entry of (composition.cartridges || [])) {',
        "    if (entry.id === 'sld-sandbox' || !entry.assembled_from) continue;",
        '    let manifest;',
        '    try {',
        '      manifest = JSON.parse(await readFile(',
        "        join(REPO, 'atlas', String(entry.assembled_from).replace(/^\\.\\//, '')), 'utf8'));",
        '    } catch { continue; }',
        '    for (const part of (manifest.assembled_from || [])) {',
        "      if (part.role !== 'module') continue;",
        "      out.push(await readFile(join(REPO, part.path), 'utf8'));",
        '    }',
        '  }',
        "  return out.join('\\n');",
        '})();',
        '',
        'const sandboxBox = sandboxContext();',
        'vm.createContext(sandboxBox);',
        "if (siblingModules) vm.runInContext(siblingModules, sandboxBox, { filename: 'siblings.js' });",
        "vm.runInContext(sandboxSource, sandboxBox, { filename: 'sld-sandbox.js' });",
      ].join('\n')));
    }

    /* ── 6. 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 computation left the sandbox, and ownership arrived\\n');",
      '',
      "/* The move is the point of this generation, so it is asserted from both",
      "   sides: the modules must be GONE from the sandbox cartridge and PRESENT",
      "   in the served composition. Checking only one side would pass a",
      "   composition that had lost them entirely. */",
      "check('the five network modules are no longer in the sandbox cartridge',",
      "  !/gridatlas\\.module\\.network-topology\\.v1/.test(cartridgeSource)",
      "  && !/gridatlas\\.module\\.electrical-distance\\.v1/.test(cartridgeSource)",
      "  && !/gridatlas\\.module\\.rating-envelope\\.v1/.test(cartridgeSource)",
      "  && !/gridatlas\\.module\\.injection-response\\.v1/.test(cartridgeSource)",
      "  && !/gridatlas\\.module\\.planned-change/.test(cartridgeSource));",
      "check('the sandbox cartridge is back under the 400 kB boundary with room to spare',",
      "  cartridgeSource.length < 340000, `${cartridgeSource.length} bytes`);",
      "check('the sandbox still CALLS them, from the cartridge that now carries them',",
      "  /window\\.__GRIDATLAS_MODULES__\\?\\.networkTopology/.test(cartridgeSource)",
      "  && /window\\.__GRIDATLAS_MODULES__\\?\\.ownerBoundary/.test(cartridgeSource));",
      "check('the card names the owners present',",
      "  /<b>Transmission owner/.test(cartridgeSource));",
      "check('a seam is named as a seam, with both ends said to differ',",
      "  /the two ends are published under different owners/.test(cartridgeSource));",
      "check('a null owner is reported as unknown and never taken from the site',",
      "  /publishes no owner and is /.test(cartridgeSource)",
      "  && /never taken from the site/.test(cartridgeSource));",
      "check('an asset whose owner matches neither end is kept out of the boundary count',",
      "  /reported as itself, not as a boundary/.test(cartridgeSource));",
      "check('the page refuses the counterparty reading',",
      "  /who a project would contract with/.test(cartridgeSource));",
      "check('the ownership state is published for review',",
      "  /window\\.__GRIDATLAS_OWNERSHIP__ = ownerState;/.test(cartridgeSource));",
      "",
      "/* The other half of the move, read from the served composition rather",
      "   than from this cartridge. */",
      "{",
      "  const composed = JSON.parse(",
      "    await readFile(join(REPO, 'atlas', 'current.json'), 'utf8'));",
      "  const sub = (composed.cartridges || []).find(c => c.id === 'substation-intelligence');",
      "  check('substation-intelligence is assembled from parts, not a monolith',",
      "    !!sub && typeof sub.assembled_from === 'string');",
      "  const subSource = await readFile(",
      "    join(REPO, 'atlas', sub.path.replace(/^\\.\\//, '')), 'utf8');",
      "  check('the five network modules are in the cartridge that owns the network',",
      "    /gridatlas\\.module\\.network-topology\\.v1/.test(subSource)",
      "    && /gridatlas\\.module\\.electrical-distance\\.v1/.test(subSource)",
      "    && /gridatlas\\.module\\.rating-envelope\\.v1/.test(subSource)",
      "    && /gridatlas\\.module\\.injection-response\\.v1/.test(subSource)",
      "    && /gridatlas\\.module\\.planned-change/.test(subSource));",
      "  check('the new owner-boundary module is there too',",
      "    /gridatlas\\.module\\.owner-boundary/.test(subSource));",
      "  check('it still carries the V8 engine verbatim, which is its slot contract',",
      "    subSource.includes('PART 2 - the network, as its operator publishes it'));",
      "  check('it is under the boundary as well',",
      "    subSource.length < 400000, `${subSource.length} bytes`);",
      "}",
      '',
      TAIL
    ].join('\n')));
  }
};

Powerflow Stopship

A JavaScript module in the steps folder of GridAtlas that works with 400kV. It is built from the once step (`once`).

transformgridatlas / tools/overnight/steps/202609020015-powerflow-stopship.mjs · lines 1–210 of 210 · version 2026-09-02 00:15 · Not reached from any entry point (candidate for review)

What it does
It calculates 400kV. Defines once.
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
Codex's powerflow stop-ship, closed. Its code works with 400 kV and 100 MVA.
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
Defines here
once
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/202609020015-powerflow-stopship.mjs:1-210 · blob a2f9c9637a0791758278d05ee271cce978ccb2ce · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/**
 * Step: Codex's powerflow stop-ship, closed.
 *
 * I asked for an adversarial review of the powerflow in the handshake at
 * 202609012325 and got one at 202609020030. Both findings are real, both
 * are P0, and both are the same shape: the proof tested a case the
 * production caller never takes.
 *
 * FINDING 1 - THE CALLER CHOSE A DISCONNECTED SLACK
 * -------------------------------------------------
 * The card asked for the first bus that was not the injection bus. The
 * 400 kV induced graph is not connected - 573 buses, 238 components - so
 * that bus is normally in a different component, and a transfer between
 * two components does not exist. West Burton was paired with ABHA41,
 * which is disconnected from 572 of 573 buses; the solve ran 2,292
 * iterations to a residual of about 1.7e13.
 *
 * The proof did not catch it because the proof picked a CONNECTED distant
 * slack by hand. That gap is the whole reason a broken composition
 * shipped with a green proof, and the successor proof now runs the
 * production path itself against the real product.
 *
 * Worse: acceptance checked Kirchhoff at the injection bus only, which a
 * disconnected pair can satisfy while the solve has not converged at all.
 * The card was gated on exactly that, so it could have printed an
 * impossible transfer. It did not for West Burton - the error was 1.5e11
 * and the card suppressed itself - but that was luck, not the gate.
 *
 * FINDING 2 - PARALLEL CIRCUITS COLLAPSED
 * ---------------------------------------
 * Edges were de-duplicated by endpoints, kind and reactance, so two
 * genuine parallel circuits publishing the same reactance became one: 22
 * groups covering 45 published rows at 400 kV. Two parallel circuits
 * carry twice what one carries at the same angle. The model went from 437
 * modelled branches to 459 when the row itself became the identity.
 *
 * WHAT SHIPS
 * ----------
 *   - the successor module: components computed and named, a DECLARED
 *     sink rule, acceptance requiring convergence AND a global residual
 *     AND Kirchhoff at EVERY bus, and row-identity edges;
 *   - the card asks for the declared sink instead of an arbitrary bus,
 *     gates on `publishable` rather than one bus balancing, and says so
 *     plainly when the answer is not available rather than going quiet.
 *
 * A field called `available` was renamed `publishable` on the way: on a
 * grid computation "available" reads as available CAPACITY, which is the
 * one thing this module refuses to claim. My own headroom check caught it.
 */

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

export default {
  id: 'powerflow-stopship',
  version: 'v9.77',

  restamp: ['substation-intelligence', 'sld-sandbox'],

  scope: 'the powerflow stops choosing an arbitrary withdrawal bus: the published 400 kV network has 238 connected components, a transfer across two of them does not exist, and the card was asking for one - it now uses a declared sink rule, refuses a cross-component transfer before the solver is asked, accepts an answer only on convergence AND a global residual AND Kirchhoff at every bus rather th  … [line shortened here: 595 characters; full line on GitHub]

  note: 'Codex stop-ship 202609020030, both findings accepted in full. The first proof passed while production was broken because it chose a connected slack by hand and the caller chose the first lexicographic bus; the successor proof runs the production path itself. Modelled branches went 437 to 459 when the published row became the edge identity.',

  brings: [NEW_MODULE, NEW_PROOF],
  replaceModules: [`${OLD_MODULE}=${NEW_MODULE}`],
  proofs: [NEW_PROOF],

  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);
    };

    /* ── the caller asks for a declared sink, and gates on the right thing ── */
    once(`          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;`,
      `          /* The withdrawal bus is DECLARED, not the first one to hand.
             ------------------------------------------------------------
             This took model.buses.find(b => b !== injection), which on a
             network with 238 components is almost always a bus the
             injection cannot reach. Codex found it at 202609020030. The
             module now publishes the rule it uses and the component it
             solved in, and refuses a cross-component transfer outright. */
          const slackNode = typeof mod.sinkFor === 'function'
            ? mod.sinkFor(model, here) : null;
          if (!slackNode) return null;
          const r = mod.respond(model, { atNode: here, slackNode, mw, minimumShare: 0.05 });
          /* publishable, not validation.passes: a disconnected pair can
             balance at the injection bus while the solve has not converged
             at all, and the old gate would have let that print. */
          return r && r.publishable === true ? r : (r || null);`,
      'declared sink');

    /* ── an unavailable answer is stated, not silent ─────────────────── */
    once(`      if (injection && injection.branches.length) {`,
      `      if (injection && injection.publishable !== true) {
        /* Saying nothing looks identical to having nothing to say. When
           the model cannot solve this transfer the reader is told, with
           the reason, rather than left with a card that quietly lost a
           section. */
        out += caveat(\`<b>Where the power would flow:</b> not available here. \`
          + escapeHtml(String(injection.reason
            || 'the solve did not meet its acceptance conditions'))
          + \` No figure is shown rather than one that has not converged.\`);
        powerflow.refused += 1;
      }
      if (injection && injection.publishable === true && injection.branches.length) {`,
      'unavailable state');

    once(`        + \`(declared DC model, 100 MVA base, transfer to \${escapeHtml(injection.slack_node)}): \``,
      `        + \`(declared DC model, 100 MVA base, transfer to \${escapeHtml(injection.slack_node)}, \`
          + \`solved in a component of \${injection.component
            ? injection.component.buses_in_component : '?'} buses): \``,
      'name the component');

    once(`  const powerflow = { answered: 0, worst_kirchhoff_error: 0 };`,
      `  const powerflow = { answered: 0, refused: 0, worst_kirchhoff_error: 0 };`,
      'refusal counter');

    write(BODY, body);

    /* ── the CI carries the successor proof ──────────────────────────── */
    const ci = read(CI);
    const OLD_CI = `  ['injection response (powerflow)', ['tools/proofs/modules/202609012320-injection-response.proof.mjs']],`;
    if (ci.split(OLD_CI).length - 1 !== 1) throw new Error('CI powerflow gate anchor is not unique');
    write(CI, ci.replace(OLD_CI,
      `  ['injection response (powerflow)', ['tools/proofs/modules/202609020015-injection-response.proof.mjs']],`));

    /* ── checks that pinned the module's VERSION must follow it ───────
       Several existing checks assert the module is present by matching
       `injection-response.v1`, and one slices the served bytes between
       that marker and the module's export to prove it reads no resistance
       or susceptance. The module is v2 now. Pinning the exact version was
       right - it is how a silent downgrade would be caught - so the
       pattern is moved forward rather than loosened to match any version,
       and the check that the OLD one is gone is kept beside it. */
    {
      const p = read(sandboxProof);
      const swaps = [
        // presence, in the sandbox proof's own module list
        ['/gridatlas\\.module\\.injection-response\\.v1/.test(composedSource)',
         '/gridatlas\\.module\\.injection-response\\.v2/.test(composedSource)'],
        ['/gridatlas\\.module\\.injection-response\\.v1/.test(subSource)',
         '/gridatlas\\.module\\.injection-response\\.v2/.test(subSource)'],
        // the r/b slice markers
        ["const start = composedSource.indexOf('gridatlas.module.injection-response.v1');",
         "const start = composedSource.indexOf('gridatlas.module.injection-response.v2');"],
        // the old acceptance gate, replaced by publishable
        ["check('an answer that fails its own Kirchhoff check is discarded, not printed',\n"
         + '  /r\\.validation && r\\.validation\\.passes \\? r : null/.test(cartridgeSource));',
         "check('an answer that fails its own acceptance is discarded, not printed',\n"
         + '  /r\\.publishable === true \\? r :/.test(cartridgeSource));'],
      ];
      let t = p;
      for (const [from, to] of swaps) {
        if (t.split(from).length - 1 !== 1) {
          throw new Error(`version-pinned check anchor is not unique: ${from.slice(0, 60)}`);
        }
        t = t.replace(from, () => to);
      }
      write(sandboxProof, t);
    }

    /* ── 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 powerflow stop-ship, closed\\n');",
      '',
      "check('the successor powerflow module is what ships',",
      "  /gridatlas\\.module\\.injection-response\\.v2/.test(composedSource)",
      "  && !/gridatlas\\.module\\.injection-response\\.v1/.test(composedSource));",
      "check('the card asks for a DECLARED sink, never the first bus to hand',",
      "  /mod\\.sinkFor\\(model, here\\)/.test(cartridgeSource)",
      "  && !/model\\.buses\\.find\\(b => b !== model\\.busOf\\(here\\)\\)/.test(cartridgeSource));",
      "check('the card gates on publishable, not on one bus balancing',",
      "  /r\\.publishable === true \\? r :/.test(cartridgeSource)",
      "  && !/r\\.validation && r\\.validation\\.passes \\? r : null/.test(cartridgeSource));",
      "check('an unavailable answer is stated to the reader, not swallowed',",
      "  /not available here/.test(cartridgeSource)",
      "  && /rather than one that has not converged/.test(cartridgeSource));",
      "check('the card names the component the transfer was solved in',",
      "  /solved in a component of/.test(cartridgeSource));",
      "check('refusals are counted for review',",
      "  /powerflow\\.refused \\+= 1;/.test(cartridgeSource));",
      "/* Pinned in fragments: these are concatenated string literals in the",
      "   module source, so the sentence never appears contiguously there -",
      "   the module proof matches the runtime string, which does. */",
      "check('the served module refuses a cross-component transfer',",
      "  /connected components of the published network/.test(composedSource));",
      "check('the served module accepts on all three conditions, not one',",
      "  /worst_bus_error_mw/.test(composedSource)",
      "  && /solved\\.residual < 1e-6/.test(composedSource));",
      "check('the served module keys edges on the published row, not its values',",
      "  /if \\(seen\\.has\\(entry\\.row\\)\\) continue;/.test(composedSource));",
      "check('the sink rule is published so a reader can see what was assumed',",
      "  /bus in the SAME component as the injection/.test(composedSource));",
      '',
      TAIL
    ].join('\n')));
  }
};

Build

A JavaScript module in the pipeline lifecycle folder of GridAtlas that reads generations, using SHA-256. It applies edits (`applyEdits`) and builds substation (`buildSubstation`).

storagegridatlas / tools/pipeline-lifecycle/build.mjs · lines 1–44 of 44 · pattern digest (shared by 56 files)

What it does
It loads generations. Defines digest, applyEdits, buildSubstation, arg. Uses libraries node:fs, node:path, node:assert/strict, node:crypto, node:url. Side effects: reads or writes files.
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.
Inputs & outputs
In: JSON file generations.json; command-line arguments.
Downstream impact
Used directly by 3 files: Map Removal Test (gridatlas); Cut Grid Explorer (gridatlas); Grid Explorer Proof (gridatlas). Reached from 1 other entry point, including GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
Successor-only recipe for the inherited Pipeline News map lifecycle.
Why it matters
Run by Cut Grid Explorer and Grid Explorer Proof. Checked by Map Removal Test.
Application
gridatlas · tools/pipeline-lifecycle · JavaScript module
Uses
node:fs, node:path, node:assert/strict, node:crypto, node:url
Used by
imported by Map Removal Test (import), run by Cut Grid Explorer (script call), run by Grid Explorer Proof (script call)
Produces
applyEdits, buildSubstation
Defines here
digest, applyEdits, buildSubstation, arg
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/pipeline-lifecycle/build.mjs:1-44 · blob fe39e0c45dbde2fa87d5013da9268ab09f8315f9 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/** Successor-only recipe for the inherited Pipeline News map lifecycle. */
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { fileURLToPath } from 'node:url';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
const digest = bytes => createHash('sha256').update(bytes).digest('hex');

export function applyEdits(source, edits) {
  assert.ok(Array.isArray(edits) && edits.length);
  for (const [i, edit] of edits.entries()) {
    assert.equal(typeof edit.before, 'string');
    assert.ok(edit.before.length);
    assert.equal(typeof edit.after, 'string');
    const at = source.indexOf(edit.before);
    assert.ok(at >= 0, `Pipeline lifecycle edit ${i} missing`);
    assert.equal(source.indexOf(edit.before, at + 1), -1, `Pipeline lifecycle edit ${i} ambiguous`);
    source = source.slice(0, at) + edit.after + source.slice(at + edit.before.length);
  }
  return source;
}

export function buildSubstation(generation, root = ROOT) {
  const registry = JSON.parse(fs.readFileSync(path.join(root, 'tools/pipeline-lifecycle/generations.json')));
  const entry = registry.generations[generation];
  assert.ok(entry, `No Pipeline lifecycle source recipe for ${generation}`);
  const base = fs.readFileSync(path.join(root, entry.base.path));
  assert.equal(base.length, entry.base.bytes, 'Pipeline lifecycle base length drift');
  assert.equal(digest(base), entry.base.sha256, 'Pipeline lifecycle base digest drift');
  const edits = JSON.parse(fs.readFileSync(path.join(root, entry.edits)));
  const built = Buffer.from(applyEdits(base.toString('utf8'), edits));
  assert.equal(built.length, entry.output_bytes, 'Pipeline lifecycle output length drift');
  assert.equal(digest(built), entry.output_sha256, 'Pipeline lifecycle output digest drift');
  return built;
}

if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
  const arg = name => process.argv[process.argv.indexOf(name) + 1];
  assert.ok(process.argv.includes('--gen') && process.argv.includes('--out'), 'Use --gen G --out NEW_FILE');
  const built = buildSubstation(arg('--gen'));
  fs.writeFileSync(arg('--out'), built, { flag: 'wx' });
  console.log(`Pipeline lifecycle rebuild: ${built.length} bytes sha256 ${digest(built)}`);
}

Map Removal Test

A test in the pipeline lifecycle folder of GridAtlas that checks Build and Substation Intelligence V9 63. It is built from the extract step (`extract`) and the fixture step (`fixture`).

testgridatlas / tools/pipeline-lifecycle/map-removal.test.mjs · lines 1–104 of 104 · Entry point · pattern extract (shared by 8 files)

What it does
It tests its inputs. Defines extract, fixture. Uses libraries node:test, node:assert/strict, node:fs, node:vm. Side effects: changes the web page (DOM); reads or writes files.
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.
Inputs & outputs
In: JSON file map-removal-edits.json.
Downstream impact
Used directly by 1 file: GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
Exercises real inherited/patched functions; VM evaluates only pinned local test inputs. It reads `./src/map-removal-edits.json`.
Why it matters
Run by GridAtlas PR File Size Guard Workflow.
Application
gridatlas · tools/pipeline-lifecycle · test
Uses
Build (import), Substation Intelligence V9 63 (new URL import.meta.url), node:test, node:assert/strict, node:fs, node:vm
Used by
run by GridAtlas PR File Size Guard Workflow (workflow run)
Produces
extract, fixture
Defines here
extract, fixture
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/pipeline-lifecycle/map-removal.test.mjs:1-104 · blob 2bdba104e4aad1d421efbea310955b6cf12732d5 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/** Exercises real inherited/patched functions; VM evaluates only pinned local test inputs. */
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import vm from 'node:vm';
import { applyEdits, buildSubstation } from './build.mjs';

const base = fs.readFileSync(new URL('../../atlas/cartridges/202609062358-substation-intelligence-v9-63.js', import.meta.url), 'utf8');
const edits = JSON.parse(fs.readFileSync(new URL('./src/map-removal-edits.json', import.meta.url)));
const patched = applyEdits(base, edits);
const extract = (source, name) => {
  source = source.slice(source.indexOf(" * Module: pipeline-news-layers"));
  const start = source.indexOf('  function ' + name + '(') >= 0
    ? source.indexOf('  function ' + name + '(') : source.indexOf('  async function ' + name + '(');
  assert.ok(start >= 0, name);
  return source.slice(start, source.indexOf('\n  }', start) + 4);
};
function fixture(source = patched, { waiting = false } = {}) {
  const callbacks = [], removed = [], clears = [], accesses = [], changes = [];
  let destroyed = false, resolveWait;
  const map = {
    addSource() {}, on(event, fn) { assert.equal(event, 'remove'); removed.push(fn); },
    getLayer(id) { accesses.push(id); if (destroyed) throw Error('style already destroyed'); return {}; },
    setLayoutProperty() { accesses.push('layout'); }
  };
  const box = { checked: true };
  const state = { installed: false, selection: { lon: 0, lat: 51 }, counts: {}, active: ['a'] };
  let selection = state.selection;
  const c = { map, window: { __GRIDATLAS_V9_MAP__: map }, state, removedMaps: new WeakSet(), installedMap: null,
    register: waiting ? null : [{ name: 'live' }], REGISTER_SOURCE: 'src-repd', CONTROLS: [{ id: 'a', keep: () => true }],
    document: { getElementById(id) { return id === 'scada-ui-container' ? { querySelector: () => true } : null; },
      querySelector: () => box, querySelectorAll: () => [] },
    buildGroup() {}, bind() {}, readSelection() { accesses.push('selection'); return destroyed ? null : selection; },
    readRegisterSource() { accesses.push('register'); if (destroyed) throw Error('style already destroyed'); return null; },
    primeRegister: () => true, near: rows => rows, collection: rows => rows,
    ensureLayers() { accesses.push('ensureLayers'); return { sourceId: 'pn' }; },
    setSourceData() { accesses.push('setData'); }, paintLabels() { changes.push('labels'); }, note() {},
    setInterval(fn) { callbacks.push(fn); return callbacks.length; }, clearInterval(id) { clears.push(id); },
    setTimeout(resolve) { resolveWait = resolve; }
  };
  vm.createContext(c);
  vm.runInContext(['setVisibility', 'loadRegister', 'refresh', 'install'].map(name => extract(source, name)).join('\n'), c);
  c.install();
  return { c, map, callbacks, removed, clears, accesses, changes, state,
    remove() { destroyed = true; for (const fn of removed) fn(); },
    clearSelection() { selection = null; }, resolveWait() { resolveWait(); } };
}

test('successor recipe is exact-once, compiles, and refuses unknown generations/double application', () => {
  assert.ok(!base.includes('const removedMaps = new WeakSet()'));
  assert.throws(() => applyEdits(patched, edits), /missing/);
  assert.throws(() => applyEdits(base + edits[0].before, edits), /ambiguous/);
  assert.throws(() => buildSubstation('not-registered'), /No Pipeline/);
  new vm.Script(buildSubstation('202611180026').toString('utf8'));
  assert.equal(buildSubstation('202611180026').toString('utf8'), patched);
});

test('real baseline poll reproduces inherited destroyed-style failure', () => {
  const f = fixture(base);
  f.callbacks[0]();
  f.remove();
  assert.throws(() => f.callbacks[0](), /style already destroyed/);
  assert.equal(f.clears.length, 0);
});

test('remove clears captured poll; even an already queued callback never reads destroyed style', () => {
  const f = fixture(); f.remove(); f.accesses.length = 0; f.changes.length = 0;
  f.callbacks[0]();
  assert.deepEqual(f.clears, [1]);
  assert.deepEqual(f.accesses, []); assert.deepEqual(f.changes, []);
  assert.equal(f.state.installed, false); assert.equal(f.state.selection, null);
  assert.equal(f.c.install(), false);
});

test('live poll and refresh retain layer updates', async () => {
  const f = fixture(); f.callbacks[0]();
  assert.ok(f.accesses.includes('selection'));
  await f.c.refresh(f.map, f.c.CONTROLS[0]);
  assert.ok(f.accesses.includes('ensureLayers')); assert.ok(f.accesses.includes('setData'));
});

test('removal during register hydration exits without another source/style read', async () => {
  const f = fixture(patched, { waiting: true });
  const pending = f.c.refresh(f.map, f.c.CONTROLS[0]);
  f.remove(); f.accesses.length = 0; f.changes.length = 0;
  f.resolveWait(); await pending;
  assert.deepEqual(f.accesses, []); assert.deepEqual(f.changes, []);
});

test('removal after resolved register but before refresh continuation prevents layer writes', async () => {
  const f = fixture(); const pending = f.c.refresh(f.map, f.c.CONTROLS[0]);
  f.remove(); f.accesses.length = 0; await pending;
  assert.deepEqual(f.accesses, []);
});

test('old map removal and in-flight refresh cannot clear newer installed map state', async () => {
  const f = fixture(); const pending = f.c.refresh(f.map, f.c.CONTROLS[0]);
  const newer = {}; f.c.installedMap = newer;
  const selection = f.state.selection, counts = f.state.counts, active = f.state.active;
  f.remove(); f.callbacks[0](); await pending;
  assert.equal(f.c.installedMap, newer); assert.equal(f.state.installed, true);
  assert.equal(f.state.selection, selection); assert.equal(f.state.counts, counts);
  assert.equal(f.state.active, active); assert.deepEqual(f.clears, [1]);
});

Build

A JavaScript module in the pipeline vicinity folder of GridAtlas that uses SHA-256.

storagegridatlas / tools/pipeline-vicinity/build.mjs · lines 1–16 of 16 · Entry point

What it does
It loads data. Uses libraries node:fs, node:crypto. Side effects: reads or writes files.
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.
Inputs & outputs
In: command-line arguments.
Downstream impact
It is itself an entry point (JavaScript module); no other file was found loading it.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
gridatlas · tools/pipeline-vicinity · JavaScript module
Uses
node:fs, node:crypto
Used by
none found
Produces
none declared
Defines here
none
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/pipeline-vicinity/build.mjs:1-16 · blob 5135b4d3c2936b1dbc8a3a3d308fdc1b9f5964f9 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env node
import fs from 'node:fs';import path from 'node:path';
import {createHash} from 'node:crypto';import {fileURLToPath} from 'node:url';
const G='202611222000',expected='0c4c7d39433e2ab084bccc159bf5fad963f4014d391a1daa18882896a87ef05d';
const args=process.argv.slice(2);let gen,out;
for(let i=0;i<args.length;i++){
 if(args[i]==='--generation')gen=args[++i];
 else if(args[i]==='--out')out=args[++i];
 else throw Error('unknown flag '+args[i]);
}
if(gen!==G||!out)throw Error('expected --generation '+G+' --out FILE');
const src=path.join(path.dirname(fileURLToPath(import.meta.url)),'src',G+'-entry.js');
const bytes=fs.readFileSync(src),hash=createHash('sha256').update(bytes).digest('hex');
if(hash!==expected)throw Error('source SHA mismatch: '+hash);
fs.writeFileSync(out,bytes);
console.log('PASS source-built native VICINITY '+bytes.length+' B '+hash);