GLOBALGRID2050 / EXPLORE CODE

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

Shift and 1 more file (part 1)

A JavaScript module in the overnight folder of GridAtlas that fetches shift log, using SHA-256 from GitHub API.

515 lines of JavaScript from gridatlas, in 2 files. Topic: Maps, GIS and field navigation. Section 641 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. Shift storage · gridatlas / tools/overnight/202609012200-shift.mjs lines 1–329
  2. Sizing Arithmetic render · gridatlas / tools/overnight/steps/202609012205-sizing-arithmetic.mjs lines 1–186

Shift

A JavaScript module in the overnight folder of GridAtlas that fetches shift log, using SHA-256 from GitHub API.

storagegridatlas / tools/overnight/202609012200-shift.mjs · lines 1–329 of 329 · version 2026-09-01 22:00 · Not reached from any entry point (candidate for review) · pattern untracked (shared by 2 files)

What it does
It fetches shift log. Defines 17 functions or classes, including flag, opt, utcNow, sha256, lf. Uses libraries node:fs, node:path, node:child_process, node:crypto, node:url. Side effects: reads or writes files; makes network requests; starts processes.
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: data source: GitHub API; JSON file shift-log.json; JSON file current.json; command-line arguments.
What it achieves
It is built from the flag step (`flag`), the opt step (`opt`) and the utc now helper (`utcNow`). The night shift: one queued step per invocation, cut on this laptop, proven here, pushed to GitHub, verified live. It reads `atlas/current.json`.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · tools/overnight · JavaScript module
Uses
GridAtlas Recompose (script call), Run Current (script call), Parts Integrity Proof (script call), All Versions Proof (script call), Data Contract Parity Proof (script call), Local CI (script call), GridAtlas — Atlas Page (estate URL), node:fs, node:path, node:child_process, node:crypto, node:url
Used by
none found
Produces
flag, opt, utcNow, sha256, lf, slash, run, git, status, untracked, record, stage
Defines here
flag, opt, utcNow, sha256, lf, slash, run, git, status, untracked, record, stage, undo, fail, read, write, patch
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/202609012200-shift.mjs:1-329 · blob eb5aa903c59e92edb09231d6b41fab46c86e3c7a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/**
 * The night shift: one queued step per invocation, cut on this laptop,
 * proven here, pushed to GitHub, verified live.
 *
 * Asked for on 1 Sep 2026: ten GridAtlas versions overnight, each stamped at
 * the UTC moment it is cut, the laptop doing the compute and GitHub being
 * the version control and the deployment engine. The reviewer is the agent
 * that wakes between runs, reads shift-log.json, and improves this file.
 *
 *   node tools/overnight/202609012200-shift.mjs            # next pending step
 *   node tools/overnight/202609012200-shift.mjs --step tools/overnight/steps/<file>
 *   node tools/overnight/202609012200-shift.mjs --dry      # apply + prove, no cut
 *
 * A step is a module under tools/overnight/steps/ exporting
 *   { id, version, scope, note, brings?: [untracked files it wrote by hand],
 *     addModules?: [], replaceModules?: ['old=new'], proofs?: [paths],
 *     postProofs?: [paths that need the composed manifest; run after the cut],
 *     apply({ root, patch, read, write }) }
 * and it is applied to the working tree, checked, composed by recompose
 * (which reads the clock), proven, committed with a subject stamped from the
 * clock, pushed to main, and watched until the live bytes match.
 *
 * Fail closed: any red anywhere and the working tree is put back to what it
 * was before the step was applied, the reason is written to the log, and
 * the process exits non-zero so the next wake reads why before anything
 * else is attempted. Nothing shipped is amended; a failed step is not cut
 * and its stamp is never used.
 *
 * First lesson, 22:03 UTC: the first draft's undo ran `git clean` on
 * tools/proofs and deleted the proof the step had brought, on a
 * PRECONDITION failure, before anything had been applied. The undo now
 * removes only files that appeared after the step was applied, and never
 * runs before that point.
 *
 * Second and third lessons, 22:09-22:10 UTC, both caught by the gates and
 * both undone cleanly: recompose could not be told the name of a proof it
 * had not yet renamed (it now accepts {generation} in --proof), and the
 * sandbox proof pinned by regex a line the step moved into the module (a
 * step is now handed the proof's path and patches it before the cut).
 *
 * After 22:11 UTC: the step's proofs run again after compose; GitHub's own
 * workflow runs for the commit must all conclude success or the outcome is
 * live-but-ci-not-green and the step is not marked done. The board's
 * request for a Chrome interaction receipt stands open: the extension is
 * not connected tonight, and a Node simulation is recorded as what it is.
 */

import fs from 'node:fs';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { fileURLToPath, pathToFileURL } from 'node:url';

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
const STEPS = path.join(ROOT, 'tools', 'overnight', 'steps');
const LOG = path.join(ROOT, 'tools', 'overnight', 'shift-log.json');
const LIVE = 'https://ventusltd.github.io/gridatlas/atlas/';
const API = 'https://api.github.com/repos/Ventusltd/gridatlas';

const flag = (name) => process.argv.includes(name);
const opt = (name) => { const at = process.argv.indexOf(name); return at > 0 ? process.argv[at + 1] : null; };
const utcNow = () => new Date().toISOString().replace(/[-:T]/g, '').slice(0, 12);
const sha256 = (buf) => createHash('sha256').update(buf).digest('hex');
const lf = (s) => String(s).split('\r\n').join('\n');
const slash = (p) => String(p).split('\\').join('/');

function run(cmd, args, { cwd = ROOT, allowFail = false, quiet = false } = {}) {
  const r = spawnSync(cmd, args, { cwd, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, shell: false });
  const out = (r.stdout || '') + (r.stderr || '');
  if (!quiet) process.stdout.write(out.length > 6000 ? out.slice(-6000) : out);
  if (r.status !== 0 && !allowFail) throw new Error(`${cmd} ${args.join(' ')} exited ${r.status}`);
  return { status: r.status, out };
}
const git = (...args) => run('git', args, { quiet: true }).out.trim();
/* not trimmed: the first column is a space for a modified file */
const status = () => run('git', ['status', '--porcelain'], { quiet: true }).out.split('\n').filter(Boolean);
const untracked = () => git('ls-files', '--others', '--exclude-standard').split('\n').filter(Boolean).map(slash);

const log = fs.existsSync(LOG) ? JSON.parse(fs.readFileSync(LOG, 'utf8')) : { schema: 'gridatlas.shift-log.v1', runs: [] };
function record(entry) {
  log.runs.push(entry);
  fs.writeFileSync(LOG, JSON.stringify(log, null, 2) + '\n');
}

/* ── choose the step ─────────────────────────────────────────────────── */
const done = new Set(log.runs.filter(r => r.outcome === 'live').map(r => r.step));
let stepPath = opt('--step');
if (!stepPath) {
  const pending = fs.readdirSync(STEPS).filter(f => f.endsWith('.mjs')).sort().filter(f => !done.has(f));
  if (!pending.length) { console.log('no pending step'); process.exit(0); }
  stepPath = path.join(STEPS, pending[0]);
}
const stepFile = path.basename(stepPath);
const step = (await import(pathToFileURL(path.resolve(stepPath)).href)).default;
for (const key of ['id', 'version', 'scope', 'note', 'apply']) {
  if (!step[key]) { console.error(`step ${stepFile} lacks ${key}`); process.exit(2); }
}
const dry = flag('--dry');
const startedAt = new Date().toISOString();
console.log(`\n\x1b[1mshift step ${step.id} -> ${step.version}\x1b[0m  (${stepFile})  ${startedAt}${dry ? '  [dry]' : ''}`);

const entry = { step: stepFile, id: step.id, version: step.version, started_at: startedAt, dry, stages: [] };
const stage = (name, detail) => { entry.stages.push({ name, at: new Date().toISOString(), ...detail }); console.log(`  \x1b[36m${name}\x1b[0m ${detail ? JSON.stringify(detail).slice(0, 200) : ''}`); };

/* the undo: tracked files back to HEAD, and only the untracked files that
   appeared AFTER the step was applied are removed. Armed after apply. */
let untrackedBefore = null;
function undo() {
  if (untrackedBefore === null) return;
  run('git', ['checkout', '--', '.'], { allowFail: true, quiet: true });
  const before = new Set(untrackedBefore);
  for (const p of untracked()) if (!before.has(p)) fs.rmSync(path.join(ROOT, p), { force: true, recursive: true });
}
function fail(reason, extra = {}) {
  entry.outcome = 'failed'; entry.reason = reason; entry.finished_at = new Date().toISOString(); Object.assign(entry, extra);
  console.log(`\n\x1b[31mFAILED: ${reason}\x1b[0m`);
  undo();
  record(entry);
  process.exit(1);
}

/* ── preconditions: clean tree, in step with origin/main ─────────────── */
/* The tree may hold the runner and steps (committed on their own below) and
   the untracked files a step BRINGS - a proof written by hand for it. */
const brings = new Set((step.brings || []).map(slash));
const dirty = status();
const dirtyElsewhere = dirty.filter(l => !slash(l.slice(3)).startsWith('tools/overnight/') && !(l.startsWith('??') && brings.has(slash(l.slice(3)))));
if (dirtyElsewhere.length) fail('working tree not clean before the step', { dirty: dirtyElsewhere.slice(0, 20) });
for (const p of brings) if (!fs.existsSync(path.join(ROOT, p))) fail(`the step says it brings ${p}, and it is not there`);

run('git', ['fetch', 'origin', '--quiet'], { quiet: true });
const head = git('rev-parse', 'HEAD');
const originMain = git('rev-parse', 'origin/main');
if (head !== originMain) {
  const base = git('merge-base', 'HEAD', 'origin/main');
  if (base === head) {
    /* origin/main moved ahead (another agent pushed); take it, fast-forward only */
    run('git', ['merge', '--ff-only', 'origin/main'], { quiet: true });
    stage('fast-forwarded to origin/main', { from: head.slice(0, 7), to: originMain.slice(0, 7) });
  } else if (base !== originMain) {
    /* Diverged. At 22:20 UTC another agent pushed four commits to main
       while this worktree held only its own shift-log commit on top of the
       cut. When everything on OUR side is under tools/overnight/, the
       rebase is mechanical and the night shift does it; anything else is
       a merge for a human. Stash-free: the precondition above has already
       confined the dirty tree to tools/overnight and the brought files,
       and rebase carries a dirty tree only if it is untouched by both
       sides, so the overnight edits are committed first as tooling. */
    const ours = git('diff', '--name-only', `${base}..HEAD`).split('\n').map(slash).filter(Boolean);
    if (ours.length && ours.every(p => p.startsWith('tools/overnight/'))) {
      run('git', ['add', 'tools/overnight'], { quiet: true });
      const r0 = run('git', ['commit', '-q', '-m', `${utcNow()}: overnight - tooling before rebase onto origin/main`], { allowFail: true, quiet: true });
      const r = run('git', ['rebase', '--quiet', 'origin/main'], { allowFail: true, quiet: true });
      if (r.status !== 0) { run('git', ['rebase', '--abort'], { allowFail: true, quiet: true }); fail('rebase of the overnight log onto origin/main did not apply cleanly', { output: r.out.slice(-1500) }); }
      stage('rebased overnight commits onto origin/main', { from: head.slice(0, 7), onto: originMain.slice(0, 7), ours, tooling_committed: r0.status === 0 });
    } else {
      fail('origin/main has diverged from this worktree with non-overnight commits on our side; a human merges, not the night shift', { head, origin_main: originMain, ours });
    }
  }
}

/* the step and the runner are committed on their own before the cut */
if (dirty.some(l => slash(l.slice(3)).startsWith('tools/overnight/')) && !dry) {
  run('git', ['add', 'tools/overnight'], { quiet: true });
  run('git', ['commit', '-q', '-m', `${utcNow()}: overnight - step ${step.id} authored`], { quiet: true });
  stage('tooling committed', { commit: git('rev-parse', '--short', 'HEAD') });
}

/* ── apply the step ─────────────────────────────────────────────────── */
const read = (rel) => fs.readFileSync(path.join(ROOT, rel), 'utf8');
const write = (rel, text) => { fs.mkdirSync(path.dirname(path.join(ROOT, rel)), { recursive: true }); fs.writeFileSync(path.join(ROOT, rel), text); };
function patch(rel, pairs) {
  let text = read(rel);
  for (const [from, to, label] of pairs) {
    const count = text.split(from).length - 1;
    if (count !== 1) throw new Error(`${rel}: anchor found ${count} times (${label || from.slice(0, 60)})`);
    text = text.replace(from, () => to);
  }
  write(rel, text);
}
untrackedBefore = untracked();
try {
  /* The sandbox proof travels with the cartridge and is renamed at the cut,
     so a step that moves text the proof pins is handed the proof's current
     path and patches it here, before recompose renames it. Second lesson,
     22:10 UTC: the sizing step moved a text the proof pinned by regex. */
  const sandboxProofs = fs.readdirSync(path.join(ROOT, 'tools', 'proofs')).filter(f => f.endsWith('-sld-sandbox.proof.mjs'));
  if (sandboxProofs.length !== 1) fail('expected exactly one sld-sandbox proof before apply', { sandboxProofs });
  await step.apply({ root: ROOT, read, write, patch, run, sandboxProof: `tools/proofs/${sandboxProofs[0]}` });
} catch (error) { fail(`apply: ${error.message}`); }
const changed = status().map(l => slash(l.slice(3))).filter(p => !p.startsWith('tools/overnight/'));
stage('applied', { changed });
if (!changed.length) fail('the step changed nothing');

/* every changed script must parse */
for (const rel of changed.filter(f => f.endsWith('.js') || f.endsWith('.mjs'))) {
  if (!fs.existsSync(path.join(ROOT, rel))) continue;
  const r = run(process.execPath, ['--check', rel], { allowFail: true, quiet: true });
  if (r.status !== 0) fail(`node --check ${rel}`, { output: r.out.slice(0, 2000) });
}
stage('syntax checked');

/* the step's own proofs, before the cut (module parity etc.) */
for (const proof of step.proofs || []) {
  const r = run(process.execPath, [proof], { allowFail: true });
  const m = r.out.match(/(\d+)\/(\d+) passed/);
  stage(`step proof ${path.basename(proof)}`, { status: r.status, tally: m ? m[1] + '/' + m[2] : undefined });
  if (r.status !== 0) fail(`step proof red: ${proof}`);
}

/* ── compose: recompose reads the clock ─────────────────────────────── */
const proofs = fs.readdirSync(path.join(ROOT, 'tools', 'proofs')).filter(f => f.endsWith('-sld-sandbox.proof.mjs'));
if (proofs.length !== 1) fail('expected exactly one sld-sandbox proof', { proofs });
const before = JSON.parse(read('atlas/current.json'));
if (dry) {
  entry.outcome = 'dry'; entry.finished_at = new Date().toISOString(); record(entry);
  console.log('\n--dry: applied, checked and step-proven; not composing. The working tree is left as applied.');
  process.exit(0);
}
/* Which cartridges this cut restamps. One, until 202609012350, when the
   sandbox reached 95% of its 400 kB boundary and the computation had to
   move to the cartridge that already owns the network concern - which
   means restamping both halves of the move in a single generation, or
   shipping a composition where the modules exist twice or not at all. */
const restamped = step.restamp && step.restamp.length ? step.restamp : ['sld-sandbox'];
const composeArgs = ['tools/recompose.mjs', '--version', step.version,
  '--scope', step.scope, '--note', step.note];
for (const id of restamped) {
  composeArgs.push('--restamp', id);
  composeArgs.push('--proof', `tools/proofs/{generation}-${id}.proof.mjs`);
}
for (const m of step.addModules || []) composeArgs.push('--add-module', m);
for (const m of step.removeModules || []) composeArgs.push('--remove-module', m);
for (const m of step.partsFrom || []) composeArgs.push('--parts-from', m);
for (const m of step.replaceModules || []) composeArgs.push('--replace-module', m);
{
  const r = run(process.execPath, composeArgs, { allowFail: true });
  if (r.status !== 0) fail('recompose refused the cut', { output: r.out.slice(-3000) });
}
const current = JSON.parse(read('atlas/current.json'));
const generation = current.generation;
if (generation === before.generation) fail('recompose did not advance the generation');
if (current.previous_generation !== before.generation) fail('the chain is broken: previous_generation is not the generation just superseded');
stage('composed', { generation, version: step.version, previous: before.generation });

/* ── prove everything ───────────────────────────────────────────────── */
const gates = [
  ['sandbox proof', [`tools/proofs/${generation}-sld-sandbox.proof.mjs`]],
  ['run-current', ['tools/proofs/run-current.mjs']],
  ['parts integrity', ['tools/proofs/202609012105-parts-integrity.proof.mjs']],
  ['all versions', ['tools/proofs/202609012150-all-versions.proof.mjs']],
  ['data-contract parity', ['tools/proofs/202609012214-data-contract-parity.proof.mjs']],
  ['local CI (proofs, deep scan, stamps, cvaa)', ['tools/ci/202609012200-local-ci.mjs']],
];
/* the step's own proofs run again, now against the composed tree: a proof
   that reads current.json must see the generation it will ship with */
for (const proof of [...(step.proofs || []), ...(step.postProofs || [])]) gates.push([`step proof after compose ${path.basename(proof)}`, [proof]]);
for (const [name, args] of gates) {
  if (!fs.existsSync(path.join(ROOT, args[0]))) fail(`gate missing: ${args[0]}`);
  const r = run(process.execPath, args, { allowFail: true });
  const m = r.out.match(/(\d+)\/(\d+) passed/);
  stage(`gate ${name}`, { status: r.status, tally: m ? m[1] + '/' + m[2] : undefined });
  if (r.status !== 0) fail(`gate red: ${name}`, { output: r.out.slice(-3000) });
}

/* ── commit from the clock, push, watch it go live ──────────────────── */
const stamp = utcNow();
run('git', ['add', '-A'], { quiet: true });
run('git', ['commit', '-q', '-m', `${generation}-gridatlas-${step.version}: ${step.note}`], { quiet: true });
const commit = git('rev-parse', 'HEAD');
untrackedBefore = null; /* committed: nothing left to undo */
stage('committed', { commit: commit.slice(0, 7), subject_stamp: generation, clock_at_commit: stamp });
{
  /* One refspec, not two. `HEAD:main HEAD` was written for a DETACHED head
     in a worktree, where the bare `HEAD` pushed the iteration branch and
     `HEAD:main` promoted it. Run from the ordinary checkout, where HEAD IS
     refs/heads/main, git sees two sources for one destination and refuses:
     "dst ref refs/heads/main receives from more than one src". The cut was
     committed and never pushed, and the shift stopped. 202609012234. */
  const r = run('git', ['push', 'origin', 'HEAD:main'], { allowFail: true, quiet: true });
  if (r.status !== 0) { entry.outcome = 'committed-not-pushed'; entry.reason = r.out.slice(-1500); entry.finished_at = new Date().toISOString(); record(entry); process.exit(1); }
}
stage('pushed');

const sld = current.cartridges.find(c => c.id === 'sld-sandbox');
const localBytes = fs.readFileSync(path.join(ROOT, 'atlas', sld.path.replace('./', '')));
const localSha = sha256(lf(localBytes.toString('utf8')));
const deadline = Date.now() + 12 * 60 * 1000;
let live = null;
while (Date.now() < deadline) {
  await new Promise(r => setTimeout(r, 20000));
  try {
    const t = Date.now();
    const c = await (await fetch(`${LIVE}current.json?t=${t}`, { cache: 'no-store' })).json();
    if (c.generation === generation) {
      const bytes = await (await fetch(`${LIVE}${sld.path.replace('./', '')}?t=${t}`, { cache: 'no-store' })).text();
      live = { generation: c.generation, version: c.composition_version, cartridge_sha_matches: sha256(lf(bytes)) === localSha, at: new Date().toISOString() };
      break;
    }
    process.stdout.write(`  live is ${c.generation}, waiting for ${generation}\r`);
  } catch (error) { process.stdout.write(`  live check: ${error.message}\r`); }
}
/* GitHub's own CI on the commit is a RECEIPT, not a witness: every workflow
   run for this sha must have concluded, and concluded success. A missing or
   unreadable API answer is recorded as such, never read as a pass. */
let actions = null;
const ciDeadline = Date.now() + 10 * 60 * 1000;
while (Date.now() < ciDeadline) {
  try {
    const runs = await (await fetch(`${API}/actions/runs?per_page=10&head_sha=${commit}`, { cache: 'no-store' })).json();
    actions = (runs.workflow_runs || []).map(r => ({ name: r.name, status: r.status, conclusion: r.conclusion, url: r.html_url }));
    if (actions.length && actions.every(r => r.status === 'completed')) break;
  } catch (error) { actions = { unreadable: error.message }; }
  await new Promise(r => setTimeout(r, 30000));
}
entry.actions = actions;
const ciGreen = Array.isArray(actions) && actions.length > 0 && actions.every(r => r.conclusion === 'success');
entry.live = live;
entry.generation = generation;
entry.commit = commit;
entry.finished_at = new Date().toISOString();
if (!live) { entry.outcome = 'pushed-not-seen-live'; entry.reason = 'Pages did not serve the generation within 12 minutes'; record(entry); process.exit(1); }
if (!live.cartridge_sha_matches) { entry.outcome = 'live-bytes-differ'; record(entry); process.exit(1); }
if (!ciGreen) { entry.outcome = 'live-but-ci-not-green'; entry.reason = 'GitHub workflow runs for the commit did not all conclude success within 10 minutes'; record(entry); process.exit(1); }
entry.outcome = 'live';
record(entry);
run('git', ['add', LOG], { quiet: true });
run('git', ['commit', '-q', '-m', `${utcNow()}: overnight - ${step.version} ${generation} verified live`], { quiet: true });
console.log(`\n\x1b[32m${step.version} ${generation} is live; cartridge sha matches\x1b[0m`);

Sizing Arithmetic

A JavaScript module in the steps folder of GridAtlas that applies development stage defaults (`applyDevelopmentStageDefaults`) and mounting bifacial (`applyMountingBifacial`) and computes screening finance (`computeScreeningFinance`).

rendergridatlas / tools/overnight/steps/202609012205-sizing-arithmetic.mjs · lines 1–186 of 186 · version 2026-09-01 22:05 · Not reached from any entry point (candidate for review) · pattern computeScreeningFinance (shared by 10 files)

What it does
Defines 6 functions or classes, including activePhysicalInputs, applyDevelopmentStageDefaults, applyMountingBifacial, computeScreeningFinance, computeSldStats. 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.
What it achieves
It applies development stage defaults (`applyDevelopmentStageDefaults`), applies mounting bifacial (`applyMountingBifacial`) and computes screening finance (`computeScreeningFinance`). The sizing arithmetic leaves the body for a module.
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
activePhysicalInputs, applyDevelopmentStageDefaults, applyMountingBifacial, computeScreeningFinance, computeSldStats, fitToStatedCapacity
Defines here
activePhysicalInputs, applyDevelopmentStageDefaults, applyMountingBifacial, computeScreeningFinance, computeSldStats, fitToStatedCapacity
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/202609012205-sizing-arithmetic.mjs:1-186 · blob 1b057dc6a4028ec45f9c6a1cb31ad5981d3ed218 · 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 sizing arithmetic leaves the body for a module.
 *
 * 529 lines of the sld-sandbox body (activePhysicalInputs through
 * fitToStatedCapacity) are pure arithmetic over an inputs object, plus the
 * finance port and the two-variable capacity fit. They close over `sld`
 * and FINANCE_DEFAULTS and nothing else, so they can be parameterised on
 * those and lifted out verbatim. The extraction is MECHANICAL: this step
 * slices the block out of the body at run time and applies a fixed list of
 * signature substitutions, each of which must match exactly once, so the
 * module carries every comment and every expression the body carried. The
 * parity proof then evaluates the last inline copy and the module side by
 * side on the same inputs and compares value for value.
 *
 * The body keeps one-line delegations under the same names, so every
 * caller in the layout and the finance panel is untouched.
 */

const MODULE = 'atlas/modules/202609012205-sizing-arithmetic.js';
const PROOF = 'tools/proofs/modules/202609012205-sizing-arithmetic.proof.mjs';
const BODY = 'atlas/parts/202609012045-sld-sandbox-body.js';

const BLOCK_START = '  /* ── the sizing arithmetic, carried across unchanged ─────────────────── */\n';
const BLOCK_END = '  sld.fitToStatedCapacity = fitToStatedCapacity;\n';

const HEADER = `/**
 * Module: sizing-arithmetic
 *
 * The screening arithmetic of the SLD sandbox: physical inputs to array
 * statistics, the three named ratios (design, export, headroom), the
 * string and central topologies with their corrected nameplates, the
 * finance port of gis-sld-v5-finance.js, and the two-variable fit that
 * lands a layout on the capacity the register states.
 *
 * Lifted out of the sld-sandbox body at generation 202609012205 (UTC),
 * expression for expression. The body closed over its state object and
 * its finance defaults; here both are parameters. Nothing else changed,
 * and the parity proof evaluates the last inline copy beside this module
 * on the same inputs and asserts identical values.
 *
 * WHAT IT WILL NOT DO
 * It grades nothing. A ratio below one is stated with its meaning; an
 * export set by the transformers is stated as the design fact it is. The
 * finance figures are a screening model with the reference's own inputs
 * and are labelled as such by the panel that shows them.
 *
 * Pure. No DOM, no network, no state of its own: fitToStatedCapacity
 * mutates the state object it is handed, as the body's did, and says so.
 */
(() => {
  const NS = window.__GRIDATLAS_MODULES__ = window.__GRIDATLAS_MODULES__ || {};
  if (NS.sizingArithmetic) return;

`;

const FOOTER = `
  NS.sizingArithmetic = Object.freeze({
    generation: '202609012205',
    DEVELOPMENT_STAGES,
    DEVELOPMENT_SUCCESS,
    BIFACIAL_BY_GCR,
    FIT_OUTER_MAX,
    FIT_INNER_MAX,
    financeNumber,
    physicalInputs,
    buildStats,
    consistency,
    stringStats,
    centralStats,
    applyDevelopmentStageDefaults,
    applyMountingBifacial,
    screeningFinance,
    computeStats,
    fitToStatedCapacity
  });
})();
`;

/* Each substitution must match exactly once, or the extraction stops. */
const SUBSTITUTIONS = [
  ['function activePhysicalInputs() {\n    const i = sld.inputs;', 'function physicalInputs(inputs) {\n    const i = inputs;'],
  ['function buildStats(o) {\n    const p = activePhysicalInputs();', 'function buildStats(inputs, o) {\n    const p = physicalInputs(inputs);'],
  ['function computeStringStats() {\n    const i = sld.inputs;', 'function stringStats(inputs) {\n    const i = inputs;'],
  ['function computeCentralStats() {\n    const i = sld.inputs;', 'function centralStats(inputs) {\n    const i = inputs;'],
  ['function applyMountingBifacial(mode, gcrValue) {\n    const values = sld.finance[mode];', 'function applyMountingBifacial(financeByMode, mode, gcrValue) {\n    const values = (financeByMode || {})[mode];'],
  ['function computeScreeningFinance(financeInputs, stats) {\n    const f = financeInputs || FINANCE_DEFAULTS;', 'function screeningFinance(financeInputs, stats, context) {\n    const f = financeInputs || (context && context.defaults) || {};'],
  ["const centralInverterAc = (stats?.mode || sld.inputs.mode) === 'central'", "const centralInverterAc = (stats?.mode || (context && context.fallbackMode)) === 'central'"],
  [`  const computeSldStats = () => {
    const stats = sld.inputs.mode === 'string'
      ? computeStringStats() : computeCentralStats();
    // Same object, so nothing can read a capacity without the check that says
    // whether the capacities agree with each other.
    stats.mode = sld.inputs.mode;
    stats.consistency = consistency(sld.inputs, stats);
    stats.finance = computeScreeningFinance(sld.finance[sld.inputs.mode], stats);
    return stats;
  };
  sld.computeFinance = computeScreeningFinance;
  sld.applyDevelopmentStage = applyDevelopmentStageDefaults;
  sld.applyMountingBifacial = applyMountingBifacial;
`, `  function computeStats(inputs, financeByMode, defaults) {
    const stats = inputs.mode === 'string'
      ? stringStats(inputs) : centralStats(inputs);
    // Same object, so nothing can read a capacity without the check that says
    // whether the capacities agree with each other.
    stats.mode = inputs.mode;
    stats.consistency = consistency(inputs, stats);
    stats.finance = screeningFinance((financeByMode || {})[inputs.mode], stats,
      { fallbackMode: inputs.mode, defaults });
    return stats;
  }
`],
  ['function fitToStatedCapacity() {\n    sld.fitResidualPct = null;', 'function fitToStatedCapacity(sld, computeSldStats) {\n    sld.fitResidualPct = null;'],
];

const DELEGATIONS = `  /* ── the sizing arithmetic, in its module ────────────────────────────
     Lifted out at 202609012205 into atlas/modules/202609012205-sizing-
     arithmetic.js, proven value-for-value against the last inline copy.
     These delegations keep every caller's name; the module is handed the
     state and the defaults the body used to close over. Absent module:
     fail by name, never quietly compute nothing. */
  const SIZING = (window.__GRIDATLAS_MODULES__ || {}).sizingArithmetic;
  if (!SIZING) throw new Error('sld-sandbox: the sizing-arithmetic module is not composed');
  const { DEVELOPMENT_STAGES, financeNumber } = SIZING;

  function activePhysicalInputs() { return SIZING.physicalInputs(sld.inputs); }
  function applyDevelopmentStageDefaults(financeInputs, stageValue) {
    return SIZING.applyDevelopmentStageDefaults(financeInputs, stageValue);
  }
  function applyMountingBifacial(mode, gcrValue) {
    return SIZING.applyMountingBifacial(sld.finance, mode, gcrValue);
  }
  function computeScreeningFinance(financeInputs, stats) {
    return SIZING.screeningFinance(financeInputs, stats,
      { fallbackMode: sld.inputs.mode, defaults: FINANCE_DEFAULTS });
  }
  const computeSldStats = () => SIZING.computeStats(sld.inputs, sld.finance, FINANCE_DEFAULTS);
  sld.computeFinance = computeScreeningFinance;
  sld.applyDevelopmentStage = applyDevelopmentStageDefaults;
  sld.applyMountingBifacial = applyMountingBifacial;

  function fitToStatedCapacity() { return SIZING.fitToStatedCapacity(sld, computeSldStats); }
  sld.fitToStatedCapacity = fitToStatedCapacity;
`;

export default {
  id: 'sizing-arithmetic',
  version: 'v9.69',
  scope: 'sld-sandbox: the sizing arithmetic (physical inputs, the three named ratios, string and central nameplates, the finance port and the two-variable capacity fit) leaves the body for the sizing-arithmetic module, lifted mechanically expression for expression and proven value-for-value against the last inline copy; the body keeps one-line delegations so no caller changes',
  note: '529 lines of sizing arithmetic become a module, proven equal to the inline copy on every input tried',
  brings: [PROOF],
  addModules: [MODULE],
  proofs: [PROOF],
  apply({ read, write, patch, sandboxProof }) {
    /* the sandbox proof pinned the central-mode fallback by its inline
       spelling; the module spells it on its context parameter */
    patch(sandboxProof, [[
      "/\\(stats\\?\\.mode \\|\\| sld\\.inputs\\.mode\\) === 'central'/.test(cartridgeSource)",
      "/\\(stats\\?\\.mode \\|\\| \\(context && context\\.fallbackMode\\)\\) === 'central'/.test(cartridgeSource)",
      'central OPEX basis check follows the text into the module']]);
    const body = read(BODY);
    const start = body.indexOf(BLOCK_START);
    const end = body.indexOf(BLOCK_END, start);
    if (start < 0 || end < 0) throw new Error('the sizing block is not where the step expects it');
    let block = body.slice(start + BLOCK_START.length, end);
    for (const [from, to] of SUBSTITUTIONS) {
      const count = block.split(from).length - 1;
      if (count !== 1) throw new Error(`substitution matched ${count} times: ${from.slice(0, 60)}`);
      block = block.replace(from, () => to);
    }
    /* four calls into buildStats, all of the same shape */
    const calls = block.split('return buildStats({').length - 1;
    if (calls !== 4) throw new Error(`expected 4 buildStats calls, found ${calls}`);
    block = block.split('return buildStats({').join('return buildStats(i, {');
    /* outside the fit, no CODE line may read the body state; the comment
       recording the deleted auto-reconciler names sld.inputs.z_strings and
       is history, so comment lines are skipped */
    const beforeFit = block.replace(/function fitToStatedCapacity[\s\S]*$/, '');
    const codeOnly = beforeFit.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/[^\n]*/g, '');
    const leak = codeOnly.split('\n').find(l => /\bsld\./.test(l));
    if (leak) throw new Error('the module still reads the body state outside the fit: ' + leak.trim());
    if (/\bFINANCE_DEFAULTS\b/.test(block)) throw new Error('the module still names FINANCE_DEFAULTS');
    write(MODULE, HEADER + block + FOOTER);
    write(BODY, body.slice(0, start) + DELEGATIONS + body.slice(end + BLOCK_END.length));
  }
};