GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / gridatlas / tools/proofs

Original Single-Line Diagram (SLD) Finance Fixture and 1 more file

A JavaScript module in the proofs folder of GridAtlas that makes element (`makeElement`), parses elements (`parseElements`) and makes harness (`makeHarness`) (units: MW, MVA, MWh), using SHA-256.

660 lines of JavaScript from gridatlas, in 2 files. Topic: Grid network and substations. Section 447 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. Original Single-Line Diagram (SLD) Finance Fixture electrical · gridatlas / tools/proofs/202609010002-original-sld-finance-fixture.mjs lines 1–351
  2. Single-Line Diagram (SLD) Styles Proof electrical · gridatlas / tools/proofs/202609040400-sld-styles.proof.mjs lines 1–309

Original Single-Line Diagram (SLD) Finance Fixture

A JavaScript module in the proofs folder of GridAtlas that makes element (`makeElement`), parses elements (`parseElements`) and makes harness (`makeHarness`) (units: MW, MVA, MWh), using SHA-256.

electricalgridatlas / tools/proofs/202609010002-original-sld-finance-fixture.mjs · lines 1–351 of 351 · version 2026-09-01 00:02 · Entry point · pattern attributes (shared by 2 files)

What it does
It loads data. Defines 9 functions or classes, including valueAfter, sha256, attributes, makeElement, parseElements. Uses libraries node:assert/strict, node:crypto, node:fs, node:path, node:vm. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'sld'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: form fields (user input); command-line arguments.
Downstream impact
It is itself an entry point (JavaScript module); no other file was found loading it.
What it achieves
It makes element (`makeElement`), parses elements (`parseElements`) and makes harness (`makeHarness`). Execute the original GlobalGrid2050 GIS SLD electrical and finance engines against a deliberately small DOM, then emit a deterministic JSON oracle.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
gridatlas · tools/proofs · JavaScript module
Uses
node:assert/strict, node:crypto, node:fs, node:path, node:vm
Used by
none found
Produces
valueAfter, sha256, attributes, makeElement, parseElements, makeHarness, applyOverrides, prefixed, runCase
Defines here
valueAfter, sha256, attributes, makeElement, parseElements, makeHarness, applyOverrides, prefixed, runCase
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/proofs/202609010002-original-sld-finance-fixture.mjs:1-351 · blob dfcebeea5f12c0a245f9aec677191c429a7655ab · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env node

/**
 * Execute the original GlobalGrid2050 GIS SLD electrical and finance engines
 * against a deliberately small DOM, then emit a deterministic JSON oracle.
 *
 * This is not a transcription of the formulas. The functions under test are
 * evaluated directly from the original repository so drift is visible in the
 * recorded source hashes and in the output comparison.
 *
 * Usage:
 *   node tools/proofs/202609010002-original-sld-finance-fixture.mjs \
 *     --original <gis-sld-financial-sandbox-directory>
 *   node tools/proofs/202609010002-original-sld-finance-fixture.mjs \
 *     --original <directory> --check tools/proofs/fixtures/202609010002-original-sld-finance.json
 *   node tools/proofs/202609010002-original-sld-finance-fixture.mjs \
 *     --original <directory> --write tools/proofs/fixtures/202609010002-original-sld-finance.json
 */

import assert from "node:assert/strict";
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import vm from "node:vm";

const args = process.argv.slice(2);
const valueAfter = flag => {
  const at = args.indexOf(flag);
  if (at < 0 || !args[at + 1]) throw new Error(`missing ${flag} value`);
  return args[at + 1];
};

const originalDir = path.resolve(valueAfter("--original"));
const checkAt = args.indexOf("--check");
const checkPath = checkAt >= 0 ? path.resolve(valueAfter("--check")) : null;
const writeAt = args.indexOf("--write");
const writePath = writeAt >= 0 ? path.resolve(valueAfter("--write")) : null;
assert.ok(!(checkPath && writePath), "use either --check or --write, not both");

const SOURCE_FILES = [
  "index.html",
  "gis-sld-v5-helpers.js",
  "gis-sld-v5-state.js",
  "gis-sld-v5-calculations.js",
  "gis-sld-v5-finance.js",
];

const sources = Object.fromEntries(SOURCE_FILES.map(name => {
  const absolute = path.join(originalDir, name);
  return [name, fs.readFileSync(absolute, "utf8")];
}));

function sha256(text) {
  return crypto.createHash("sha256").update(text).digest("hex");
}

function attributes(markup) {
  const out = {};
  for (const match of markup.matchAll(/([:\w-]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g)) {
    const [, key, doubleQuoted, singleQuoted, bare] = match;
    out[key.toLowerCase()] = doubleQuoted ?? singleQuoted ?? bare ?? true;
  }
  return out;
}

function makeElement(id, attrs = {}) {
  return {
    id,
    type: String(attrs.type || "text"),
    value: attrs.value === true || attrs.value == null ? "" : String(attrs.value),
    checked: attrs.checked === true,
    step: attrs.step == null ? "" : String(attrs.step),
    options: [],
    selectedIndex: -1,
    style: {},
    classList: { add() {}, remove() {}, toggle() {} },
    closest() { return null; },
    addEventListener() {},
    dispatchEvent() { return true; },
  };
}

function parseElements(html) {
  const elements = new Map();

  for (const match of html.matchAll(/<input\b([^>]*)>/gi)) {
    const attrs = attributes(match[1]);
    if (!attrs.id) continue;
    elements.set(String(attrs.id), makeElement(String(attrs.id), attrs));
  }

  for (const match of html.matchAll(/<select\b([^>]*)>([\s\S]*?)<\/select>/gi)) {
    const attrs = attributes(match[1]);
    if (!attrs.id) continue;
    const el = makeElement(String(attrs.id), attrs);
    el.options = [...match[2].matchAll(/<option\b([^>]*)>([\s\S]*?)<\/option>/gi)].map(optionMatch => {
      const optionAttrs = attributes(optionMatch[1]);
      return {
        value: optionAttrs.value === true || optionAttrs.value == null ? "" : String(optionAttrs.value),
        text: optionMatch[2].replace(/<[^>]+>/g, "").trim(),
        selected: optionAttrs.selected === true,
      };
    });
    el.selectedIndex = Math.max(0, el.options.findIndex(option => option.selected));
    el.value = el.options[el.selectedIndex]?.value || "";
    elements.set(el.id, el);
  }

  return elements;
}

function makeHarness() {
  const elements = parseElements(sources["index.html"]);
  const used = new Set();
  const document = {
    readyState: "loading",
    getElementById(id) {
      used.add(String(id));
      return elements.get(String(id)) || null;
    },
    addEventListener() {},
  };
  const context = vm.createContext({
    Array,
    console,
    document,
    Event: class Event {},
    Math,
    Number,
    parseFloat,
    parseInt,
    setTimeout,
    clearTimeout,
  });

  for (const name of SOURCE_FILES.slice(1)) {
    vm.runInContext(sources[name], context, { filename: name });
  }
  vm.runInContext("migrateFinanceUnitsToWp()", context);

  return { context, elements, used };
}

function applyOverrides(elements, overrides) {
  for (const [id, override] of Object.entries(overrides)) {
    const el = elements.get(id);
    assert.ok(el, `fixture override references missing original element ${id}`);
    if (typeof override === "object" && override !== null) {
      if ("selectedIndex" in override) {
        assert.ok(el.options[override.selectedIndex], `${id} selectedIndex is outside its options`);
        el.selectedIndex = override.selectedIndex;
        el.value = el.options[override.selectedIndex].value;
      }
      if ("value" in override) el.value = String(override.value);
      if ("checked" in override) el.checked = Boolean(override.checked);
    } else {
      el.value = String(override);
    }
  }
}

const FINANCE_STRESS = {
  price: 72,
  other: 8,
  yield: 1050,
  bifacial: 7.5,
  losses: 1.5,
  deg: 0.45,
  opex: 18000,
  epc_ex: 0.31,
  flood: { checked: true },
  flood_rate: 0.04,
  modules: 0.17,
  other_capex: 0.11,
  fixed_capex: 2500000,
  cont: 9,
  loss_dc_string: 0.4,
  loss_lv_dc: 0.2,
  loss_lv_ac: 0.3,
  loss_tx: 0.8,
  loss_other: 0.2,
  bess_mw: 50,
  bess_mwh: 100,
  bess_capex: 250000,
  bess_cycles: 250,
  bess_spread: 60,
  bess_eff: 88,
  dev_stage: { selectedIndex: 3 },
  dev_cost_mw: 0.055,
  dev_module_mwp: 0.18,
  dev_epc_mw: 0.65,
  dev_owner_mw: 0.11,
  dev_grid_mw: 0.25,
  dev_exit_mwp: 1.3,
  dev_npv_mwp: 1.15,
  dev_success: 55,
  dev_years: 5,
};

function prefixed(prefix, values) {
  return Object.fromEntries(Object.entries(values).map(([key, value]) => [`${prefix}_${key}`, value]));
}

const CASES = [
  { id: "string_reference_defaults", mode: "string", prefix: "fin_string", overrides: {} },
  { id: "central_reference_defaults", mode: "central", prefix: "fin_central", overrides: {} },
  {
    id: "string_full_finance_path",
    mode: "string",
    prefix: "fin_string",
    overrides: {
      mod_wp: 700,
      mod_l: 2.42,
      mod_w: 1.31,
      mounting_type: 0.35,
      gross_factor: 1.5,
      dc_ac_ratio: 1.25,
      string_inv_kva: 330,
      string_skid_mva: 8.5,
      x_mods: 28,
      z_strings: 20,
      y_invs: 24,
      s_subs: 4,
      b_cols: 5,
      mods_pallet: 31,
      mods_container: 620,
      spare_pct: 1.5,
      ...prefixed("fin_string", FINANCE_STRESS),
    },
  },
  {
    id: "central_full_finance_path",
    mode: "central",
    prefix: "fin_central",
    overrides: {
      mod_wp_c: 700,
      mod_l_c: 2.42,
      mod_w_c: 1.31,
      mounting_type_c: 0.35,
      gross_factor_c: 1.5,
      inv_dc_mw_c: 5.6,
      inv_ac_mw_c: 4.5,
      central_skid_mva_c: 4.5,
      x_mods_c: 28,
      str_per_cb_c: 24,
      combiner_limit_kwdc_c: 500,
      // Deliberately greater than one so the original central AC double-count
      // is captured and a corrected port cannot accidentally claim parity.
      inv_per_mv_c: 2,
      mv_per_ring_c: 3,
      rings_c: 5,
      mods_pallet_c: 31,
      mods_container_c: 620,
      spare_pct_c: 1.5,
      ...prefixed("fin_central", FINANCE_STRESS),
    },
    centralReferenceDoubleCount: true,
  },
];

function runCase(spec) {
  const { context, elements, used } = makeHarness();
  applyOverrides(elements, spec.overrides);
  used.clear();
  const expression = spec.mode === "string"
    ? `(() => { const stats = computeStringStats(); return JSON.stringify({ stats, finance: computeFinance(${JSON.stringify(spec.prefix)}, stats) }); })()`
    : `(() => { const stats = computeCentralStats(); return JSON.stringify({ stats, finance: computeFinance(${JSON.stringify(spec.prefix)}, stats) }); })()`;
  const result = JSON.parse(vm.runInContext(expression, context));
  const inputs = Object.fromEntries([...used].sort().map(id => {
    const el = elements.get(id);
    // Optional controls are deliberately observable: the original central
    // engine probes central_rating_mode even though the V7 page does not ship
    // that element, then falls back to preset mode.
    return [id, el ? (el.type === "checkbox" ? el.checked : el.value) : null];
  }));
  const output = { id: spec.id, mode: spec.mode, inputs, ...result };
  if (spec.centralReferenceDoubleCount) {
    const invPerSkid = Number(inputs.inv_per_mv_c);
    const correctedAcMw = result.stats.ac_mw / invPerSkid;
    const excessAnnualOpex = (result.stats.ac_mw - correctedAcMw) * result.finance.opexRate;
    output.reference_defect = {
      code: "CENTRAL_AC_DOUBLE_COUNT",
      original_ac_mw: result.stats.ac_mw,
      corrected_ac_mw: correctedAcMw,
      corrected_dc_ac_ratio: result.stats.dc_mwp / correctedAcMw,
      corrected_surplus25: result.finance.surplus25 + excessAnnualOpex * 25,
      corrected_surplus35: result.finance.surplus35 + excessAnnualOpex * 35,
      contract: "The port must match the original inputs and unaffected outputs, but must use the corrected values above instead of reproducing the known AC double-count.",
    };
  }
  return output;
}

const calculations = sources["gis-sld-v5-calculations.js"];
const allExecutableSource = Object.entries(sources)
  .filter(([name]) => name.endsWith(".js"))
  .map(([, source]) => source)
  .join("\n");
const stringDefault = Number(sources["index.html"].match(/id="z_strings"\s+value="([^"]+)"/)?.[1]);
const declaredStringRatio = Number(sources["index.html"].match(/id="dc_ac_ratio"\s+value="([^"]+)"/)?.[1]);

assert.equal(stringDefault, 18, "original z_strings default drifted");
assert.equal(declaredStringRatio, 1.2, "original declared string ratio drifted");
assert.match(calculations, /const x = intVal\("x_mods"\), z = intVal\("z_strings"\)/);
assert.match(calculations, /ac_mw_direct != null \? ac_mw_direct/);
assert.match(calculations, /dc_ac_ratio: actual_dc_ac/);
assert.doesNotMatch(allExecutableSource, /setInputValue\("z_strings"/);
assert.doesNotMatch(allExecutableSource, /\$\("z_strings"\)\s*\.value\s*=/);

const executedCases = CASES.map(runCase);
const defaultStringCase = executedCases.find(item => item.id === "string_reference_defaults");
const centralDefectCase = executedCases.find(item => item.id === "central_full_finance_path");
assert.equal(defaultStringCase.inputs.z_strings, "18");
assert.notEqual(defaultStringCase.stats.dc_ac_ratio, declaredStringRatio,
  "the original must expose its calculated ratio rather than silently presenting the declared ratio");
assert.equal(centralDefectCase.reference_defect.original_ac_mw,
  centralDefectCase.reference_defect.corrected_ac_mw * Number(centralDefectCase.inputs.inv_per_mv_c));
assert.ok(centralDefectCase.finance.bessMwh > 0 && centralDefectCase.finance.totalLoss > 0,
  "full-path case must exercise BESS and specialist electrical losses");

const fixture = {
  schema: "globalgrid2050.original-sld-electrical-finance-fixture.v1",
  provenance: {
    original_directory_name: path.basename(originalDir),
    sha256: Object.fromEntries(Object.entries(sources).map(([name, source]) => [name, sha256(source)])),
    execution: "Original helper, state, calculation and finance JavaScript evaluated in a minimal DOM parsed from the original index.html.",
  },
  reference_behavior: {
    z_strings_default: stringDefault,
    declared_string_dc_ac_ratio: declaredStringRatio,
    z_strings_is_independent_input: true,
    reason: "The original reads z_strings directly. Its string AC is supplied by skid export, so buildStats recomputes actual DC/AC and does not use the declared ratio to alter z_strings.",
    known_central_defect: "Original central ac_mw_direct multiplies total_blocks by both central_skid_mva and inv_per_mv even though total_blocks already includes inv_per_mv. A corrected port must encode an explicit expected divergence for inv_per_mv greater than one.",
  },
  cases: executedCases,
};

const rendered = JSON.stringify(fixture, null, 2) + "\n";
if (checkPath) {
  const expected = fs.readFileSync(checkPath, "utf8").replace(/\r\n/g, "\n");
  assert.equal(rendered, expected, `fixture drift: regenerate ${checkPath} only after reviewing original source changes`);
  console.log(`PASS: original SLD electrical/finance fixture matches ${checkPath}`);
  console.log(`PASS: ${fixture.cases.length} cases execute the original engine; z_strings remains independent`);
} else if (writePath) {
  fs.mkdirSync(path.dirname(writePath), { recursive: true });
  fs.writeFileSync(writePath, rendered, "utf8");
  console.log(`WROTE: ${writePath}`);
  console.log(`PASS: ${fixture.cases.length} cases execute the original engine; central defect divergence is explicit`);
} else {
  process.stdout.write(rendered);
}

Single-Line Diagram (SLD) Styles Proof

A JavaScript module in the proofs folder of GridAtlas that reads substations, using SHA-256.

electricalgridatlas / tools/proofs/202609040400-sld-styles.proof.mjs · lines 1–309 of 309 · version 2026-09-04 04:00 · Not reached from any entry point (candidate for review) · pattern digest (shared by 56 files)

What it does
It loads substations. Defines 7 functions or classes, including lf, raw, json, digest, rawDigest. Uses libraries node:assert/strict, node:crypto, node:fs, node:path, node:vm. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'sld'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: substations.
Inputs & outputs
In: JSON file current.json.
What it achieves
It is built from the raw step (`raw`), the JSON step (`json`) and the digest step (`digest`). V9.107 stylesheet-hoist proof.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · tools/proofs · JavaScript module
Uses
node:assert/strict, node:crypto, node:fs, node:path, node:vm, node:url
Used by
none found
Produces
lf, raw, json, digest, rawDigest, assertManifestBytes, trailingWhitespaceLines
Defines here
lf, raw, json, digest, rawDigest, assertManifestBytes, trailingWhitespaceLines
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/proofs/202609040400-sld-styles.proof.mjs:1-309 · blob 63128e98851804da16a5549ea1092e351f86fe90 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
/**
 * v9.107 stylesheet-hoist proof.
 *
 * The cut is deliberately mechanical: seven template-literal CSS values move
 * from sld-sandbox into the earlier-loading substation-intelligence cartridge.
 * Installation timing and DOM ownership stay in the sandbox. This proof uses
 * the preserved v9.106 part as the oracle and fails if any CSS value changes,
 * either concatenated style is moved, the module is absent from served bytes,
 * or either cartridge crosses the existing ceiling.
 */

import assert from 'node:assert/strict';
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import vm from 'node:vm';
import { fileURLToPath } from 'node:url';

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
const OLD_PART = 'atlas/parts/202609040229-sld-sandbox-arrival-identity.js';
const NEW_PART = 'atlas/parts/202609040400-sld-sandbox-style-hoist.js';
const STYLE_MODULE = 'atlas/modules/202609040400-sld-styles.js';
const CARRIED_ENGINE =
  'atlas/parts/202609040229-ventus-corev8engine-exact-repd-delegation.js';
const ATTRIBUTES = '.gitattributes';
const OLD_SLD = 'atlas/cartridges/202609040337-sld-sandbox-v9-8.js';
const OLD_SUBSTATION =
  'atlas/cartridges/202609040337-substation-intelligence-v9-63.js';
const BOUNDARY = 409600;
const CEILING = Math.floor(BOUNDARY * 0.9);

const lf = relative => fs.readFileSync(path.join(ROOT, relative), 'utf8')
  .replace(/\r\n/g, '\n');
const raw = relative => fs.readFileSync(path.join(ROOT, relative));
const json = relative => JSON.parse(lf(relative));
const digest = text => crypto.createHash('sha256').update(text, 'utf8').digest('hex');
const rawDigest = bytes => crypto.createHash('sha256').update(bytes).digest('hex');

const oldPart = lf(OLD_PART);
const newPart = lf(NEW_PART);
const moduleSource = lf(STYLE_MODULE);
const templateAssignment = /style\.textContent\s*=\s*(`(?:\\.|[^`])*`);/g;
const legacyExpressions = [...oldPart.matchAll(templateAssignment)].map(match => match[1]);

assert.equal(legacyExpressions.length, 7,
  'the preserved v9.106 body must contain exactly seven authorised templates');
assert.equal([...newPart.matchAll(templateAssignment)].length, 0,
  'no template style assignment may remain in the successor body');

const context = vm.createContext({ window: {} });
vm.runInContext(moduleSource, context, { filename: STYLE_MODULE });
const styles = context.window.__GRIDATLAS_MODULES__?.sldStyles;
assert.equal(styles?.schema, 'gridatlas.module.sld-styles.v1');
assert.equal(Object.isFrozen(styles), true, 'the style API is immutable');
assert.deepEqual(
  [...Object.keys(styles)],
  ['schema', 'neonBlock', 'bootStatus', 'versionLedger', 'mobileTray',
    'gbConditions', 'sldPanel', 'fullscreenLayers'],
  'the module exposes only the seven authorised factories'
);
assert.throws(
  () => vm.runInContext(moduleSource, context, { filename: STYLE_MODULE }),
  /sld-styles module registered twice/,
  'a duplicate module must not silently replace the first one'
);

const cases = [
  { call: 'neonBlock', name: 'BLOCK_CLASS', value: 'gridatlas-neon-block',
    selector: '.gridatlas-neon-block' },
  { call: 'bootStatus', name: 'STATUS_ID', value: 'gridatlas-boot-status',
    selector: '#gridatlas-boot-status' },
  { call: 'versionLedger', name: 'LEDGER_ID', value: 'gridatlas-version-ledger',
    selector: '#gridatlas-version-ledger' },
  { call: 'mobileTray', name: 'TRAY_ID', value: 'gridatlas-mobile-tray',
    selector: '#gridatlas-mobile-tray' },
  { call: 'gbConditions', name: 'GB_ID', value: 'gridatlas-gb-conditions',
    selector: '#gridatlas-gb-conditions' },
  { call: 'sldPanel', name: 'PANEL_ID', value: 'gridatlas-sld-panel',
    selector: '#gridatlas-sld-panel' },
  { call: 'fullscreenLayers', name: null, value: null,
    selector: '.gridatlas-fs-layers' }
];

const cssDigests = {};
for (let index = 0; index < cases.length; index += 1) {
  const item = cases[index];
  const legacy = vm.runInNewContext(`(${legacyExpressions[index]})`,
    item.name ? { [item.name]: item.value } : {});
  const moved = item.name ? styles[item.call](item.value) : styles[item.call]();
  assert.equal(moved, legacy, `${item.call} CSS differs from v9.106`);
  assert.ok(moved.includes(item.selector), `${item.call} lost ${item.selector}`);
  cssDigests[item.call] = digest(moved);
}

const expectedCalls = [
  'style.textContent = SLD_STYLES.neonBlock(BLOCK_CLASS);',
  'style.textContent = SLD_STYLES.bootStatus(STATUS_ID);',
  'style.textContent = SLD_STYLES.versionLedger(LEDGER_ID);',
  'style.textContent = SLD_STYLES.mobileTray(TRAY_ID);',
  'style.textContent = SLD_STYLES.gbConditions(GB_ID);',
  'style.textContent = SLD_STYLES.sldPanel(PANEL_ID);',
  'style.textContent = SLD_STYLES.fullscreenLayers();'
];
const actualCalls = newPart.split('\n')
  .map(line => line.trim())
  .filter(line => line.startsWith('style.textContent = SLD_STYLES.'));
assert.deepEqual(actualCalls, expectedCalls,
  'each authorised call site must be one exact line');

const binding = "\n  const SLD_STYLES = (window.__GRIDATLAS_MODULES__ || {}).sldStyles;\n"
  + "  if (SLD_STYLES?.schema !== 'gridatlas.module.sld-styles.v1') {\n"
  + "    throw new Error('sld-sandbox requires the sld-styles module');\n"
  + '  }\n';
assert.equal(newPart.includes(binding), true, 'the fail-fast binding is exact');
assert.throws(
  () => vm.runInNewContext(newPart, { window: {} }, { filename: NEW_PART }),
  /sld-sandbox requires the sld-styles module/,
  'an absent module must fail before the sandbox creates an unstyled surface'
);
assert.throws(
  () => vm.runInNewContext(newPart,
    { window: { __GRIDATLAS_MODULES__: { sldStyles: { schema: 'wrong' } } } },
    { filename: NEW_PART }),
  /sld-sandbox requires the sld-styles module/,
  'an incompatible module must fail rather than silently render unstyled'
);

/* Reconstruct the old body. Exact equality proves the binding and seven call
   substitutions are the whole source change, including the two concatenated
   corridor/dash style assignments that were not authorised to move. */
let reconstructed = newPart.replace(binding, '');
for (let index = 0; index < expectedCalls.length; index += 1) {
  reconstructed = reconstructed.replace(expectedCalls[index],
    `style.textContent = ${legacyExpressions[index]};`);
}
assert.equal(reconstructed, oldPart,
  'the successor body contains a change outside the authorised mechanical move');
assert.equal((newPart.match(/style\.textContent\s*=/g) || []).length, 9,
  'seven module calls plus the two retained concatenated styles must remain');
assert.equal(newPart.includes("style.textContent =\n      '.gridatlas-corridor-open"), true,
  'the corridor style remains in the sandbox');
assert.equal(newPart.includes(
  "style.textContent = '.scada-wrapper[data-gridatlas-collapsed=\"1\"]"), true,
  'the dash style remains in the sandbox');

/* FROM HERE DOWN: is the v9.107 wiring still reachable in whatever is
   actually live, not "is v9.107 itself still the live generation".
   ------------------------------------------------------------------------
   This proof is carried forward by every future sld-sandbox and
   substation-intelligence cut (recompose.mjs renames it, never restates
   it), and this repository composes cartridges independently -- "the
   composition carries mixed stamps and should" is recompose.mjs's own
   documented contract. The first version of this section asserted
   `current.composition_version === 'v9.107'` and
   `sld.generation === substation.generation === current.generation`: true
   for exactly one generation, and false the moment either cartridge was
   ever cut again on its own, which is the normal case, not an edge one.
   It also required the SLD body part to be BYTE-IDENTICAL to the original
   NEW_PART forever, which would forbid this cartridge from ever being
   touched again for any other reason.

   What must actually stay true, indefinitely, is narrower: the style
   module is still wired into substation-intelligence, and the sandbox's
   own body still carries the fail-fast binding and the seven call sites
   -- the WIRING, not the FILENAME or the COMPOSITION VERSION NUMBER. */
const current = json('atlas/current.json');
assert.ok(current.cartridge_order.indexOf('substation-intelligence')
  < current.cartridge_order.indexOf('sld-sandbox'),
  'the style owner must execute before its consumer');
const byId = new Map(current.cartridges.map(entry => [entry.id, entry]));
const sld = byId.get('sld-sandbox');
const substation = byId.get('substation-intelligence');
assert.ok(sld, 'the live composition must still carry sld-sandbox');
assert.ok(substation, 'the live composition must still carry substation-intelligence');

const sldPartsPath = path.posix.join('atlas', sld.assembled_from.replace(/^\.\//, ''));
const substationPartsPath = path.posix.join(
  'atlas', substation.assembled_from.replace(/^\.\//, ''));
const sldPartsManifest = json(sldPartsPath);
const substationPartsManifest = json(substationPartsPath);
const sldParts = sldPartsManifest.assembled_from;
const substationParts = substationPartsManifest.assembled_from;
// The one 'part'-role entry is the sandbox's own body, whatever generation
// it is now -- a later cut is free to supersede NEW_PART with a reviewed
// successor, the same way substation-intelligence's own carried engine has
// superseded shell scripts before it. What is checked below is that the
// successor still CARRIES the hoist wiring, not that it IS NEW_PART.
const sldPartEntry = sldParts.find(entry => entry.role === 'part');
const styleModuleEntry = substationParts.find(entry => entry.role === 'module'
  && entry.path === STYLE_MODULE);
assert.ok(sldPartEntry,
  'the SLD parts manifest must name a body part');
assert.ok(styleModuleEntry,
  'the substation parts manifest must carry the style module');

const assertManifestBytes = (entry, relative, label) => {
  const bytes = raw(relative);
  assert.equal(entry.bytes, bytes.length, `${label} manifest byte count drifted`);
  assert.equal(entry.sha256, rawDigest(bytes), `${label} manifest digest drifted`);
};
// Integrity against the manifest's OWN recorded path, whatever generation
// that part is now -- not against the original v9.107 file, which a later,
// reviewed successor is entitled to supersede.
assertManifestBytes(sldPartEntry, sldPartEntry.path, 'SLD body part');
assertManifestBytes(styleModuleEntry, STYLE_MODULE, 'style module');

const sldSource = lf(path.posix.join('atlas', sld.path.replace(/^\.\//, '')));
const substationSource = lf(path.posix.join(
  'atlas', substation.path.replace(/^\.\//, '')));
assertManifestBytes(sldPartsManifest,
  path.posix.join('atlas', sld.path.replace(/^\.\//, '')), 'SLD cartridge');
assertManifestBytes(substationPartsManifest,
  path.posix.join('atlas', substation.path.replace(/^\.\//, '')),
  'substation cartridge');
// The durable claim: the served cartridge still carries the fail-fast
// binding and calls every one of the seven style factories by exactly the
// call sites verified above -- checked by content, not by requiring the
// live body to still be byte-identical to the original v9.107 file.
assert.equal(sldSource.includes(binding), true,
  'the fail-fast style-module binding must reach the served SLD cartridge');
for (const call of expectedCalls) {
  assert.equal(sldSource.includes(call), true,
    `served SLD cartridge is missing call site: ${call}`);
}
assert.equal(substationSource.includes(moduleSource.trimEnd()), true,
  'the style module must reach the served earlier cartridge');
const substationBody = substationParts.find(entry => entry.role === 'part');
assert.ok(substationBody, 'the receiving cartridge must still have its body part');
const substationBodySource = lf(substationBody.path).trimEnd();
assert.equal(substationSource.indexOf(moduleSource.trimEnd())
  < substationSource.indexOf(substationBodySource), true,
  'the style module must be evaluated before the substation body ends');

const oldSldChars = lf(OLD_SLD).length;
const oldSubstationChars = lf(OLD_SUBSTATION).length;
const sldChars = sldSource.length;
const substationChars = substationSource.length;
assert.ok(sldChars < CEILING, `SLD ${sldChars} crosses ${CEILING}`);
assert.ok(substationChars < CEILING,
  `substation ${substationChars} crosses ${CEILING}`);
/* 17000 was the exact margin the original v9.107 cut measured (17916), and
   was never going to survive as an ongoing minimum -- every legitimate
   feature added to the sandbox afterwards spends a little of it. The spend,
   kept as a ledger rather than re-floored silently each time:

     17916   v9.107, the hoist itself
    -4482    v9.109 technology buckets           -> 13434
    -4011    v9.112 iOS Safari visible-time      ->  9423
             arrival (deferred start, bounded
             retry on visibilitychange)

   Each of those is a feature that had to be written somewhere, not erosion of
   the hoist. Re-floating the floor to just under whatever today measures is
   how a guard quietly dies, so it is set once, well below, at the level where
   it still does its ONE job: catching a hoist that was actually reverted --
   which would return the whole 17916 at once and land far under this number.

   The real budget is the CEILING assertion above, and it is enforced: the SLD
   cartridge measures 357,580 against a 368,640 ceiling at this generation,
   11,060 to spare. That is the number to watch, and it is checked, not
   narrated. */
assert.ok(oldSldChars - sldChars >= 5000,
  `the hoist looks reverted, not merely spent: only ${oldSldChars - sldChars} chars saved against the original 17916`);
assert.ok(substationChars > oldSubstationChars,
  'the receiving cartridge did not grow, so the module likely missed served bytes');

const trailingWhitespaceLines = source => source.split('\n')
  .filter(line => /[ \t]+$/.test(line));
const inheritedTrailingWhitespace = trailingWhitespaceLines(lf(CARRIED_ENGINE));
assert.equal(inheritedTrailingWhitespace.length, 58,
  'the preserved V8 receiver trailing-whitespace inventory changed');
assert.deepEqual(trailingWhitespaceLines(lf(OLD_SUBSTATION)),
  inheritedTrailingWhitespace,
  'the prior cartridge did not preserve exactly the receiver whitespace');
assert.deepEqual(trailingWhitespaceLines(substationSource),
  inheritedTrailingWhitespace,
  'the new cartridge introduced or removed trailing whitespace');
// Named by the CARTRIDGE'S OWN generation, not the whole composition's --
// substation-intelligence and sld-sandbox are cut independently, so
// current.generation (a pointer to whichever cartridge was cut most
// recently) is frequently neither cartridge's own identity.
const substationWhitespaceExemptions = lf(ATTRIBUTES).split('\n')
  .map(line => line.trim())
  .filter(line => line && !line.startsWith('#'))
  .filter(line => line.includes(substation.generation) && line.endsWith(' -whitespace'));
assert.deepEqual(substationWhitespaceExemptions, [
  `atlas/cartridges/${substation.generation}-substation-intelligence-v9-63.js -whitespace`
], 'the live substation-intelligence cartridge with inherited V8 bytes must be exempt, and only it');

console.log(JSON.stringify({
  status: 'PASS',
  generation: current.generation,
  version: current.composition_version,
  css_exact_parity: cssDigests,
  call_sites: actualCalls.length,
  inherited_v8_trailing_whitespace_lines: inheritedTrailingWhitespace.length,
  sld: {
    chars: sldChars,
    enforced_headroom: CEILING - sldChars,
    boundary_headroom: BOUNDARY - sldChars,
    previous_chars: oldSldChars
  },
  substation: {
    chars: substationChars,
    enforced_headroom: CEILING - substationChars,
    boundary_headroom: BOUNDARY - substationChars,
    previous_chars: oldSubstationChars
  }
}, null, 2));