GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Websites and apps / testcode / /

Testcode — Run and 11 more files

A JavaScript module that reads engines and testcode run. It is built from the is required helper (`isRequired`), the checkout for helper (`checkoutFor`) and the run step (`run`).

687 lines of JavaScript and Python from testcode, in 12 files. Topic: Websites and apps. Section 2014 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. Testcode — Run storage · testcode / run.mjs lines 1–221
  2. Browser Adapter render · testcode / sandbox/capsules/grid-compute/browser-adapter.js lines 1–19
  3. Detector transform · testcode / sandbox/capsules/grid-compute/detector.mjs lines 1–45
  4. Industrial Candidate storage · testcode / sandbox/capsules/grid-compute/industrial-candidate.py lines 1–44
  5. Industrial Diagnostic render · testcode / sandbox/capsules/grid-compute/industrial-diagnostic.cjs lines 1–5
  6. Offshore Candidate storage · testcode / sandbox/capsules/grid-compute/offshore-candidate.py lines 1–68
  7. Package Results storage · testcode / sandbox/capsules/grid-compute/package-results.py lines 1–51
  8. Prepare render · testcode / sandbox/capsules/grid-compute/prepare.py lines 1–101
  9. Publication Candidate render · testcode / sandbox/capsules/grid-compute/publication-candidate.py lines 1–41
  10. Release Metadata automation · testcode / sandbox/capsules/grid-compute/release-metadata.py lines 1–11
  11. Capsules — Grid Compute render · testcode / sandbox/capsules/grid-compute/run.mjs lines 1–60
  12. Screenshot Policy storage · testcode / sandbox/capsules/grid-compute/screenshot-policy.py lines 1–21

Testcode — Run

A JavaScript module that reads engines and testcode run. It is built from the is required helper (`isRequired`), the checkout for helper (`checkoutFor`) and the run step (`run`).

storagetestcode / run.mjs · lines 1–221 of 221 · Entry point

What it does
It loads engines and testcode run. Defines isRequired, checkoutFor, run, line, blocks. Uses libraries node:child_process, node:fs, node:path, node:url. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage experimental (repository name word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. README: "It is enforced by `run.mjs` rather than described by it: the network phase does not execute while an offline gate is red, and the runner says so in words rather than skipping quietly."
Inputs & outputs
In: JSON file engines.json; command-line arguments. Out: JSON file testcode-run.json.
Downstream impact
Used directly by 1 file: Testcode Workflow (testcode).
What it achieves
The estate's test engine. Offline first, always.
Why it matters
Run by Testcode Workflow.
Application
testcode · / · JavaScript module
Uses
Checkout (script call), node:child_process, node:fs, node:path, node:url
Used by
run by Testcode Workflow (workflow run)
Produces
isRequired, checkoutFor, run, line, blocks
Defines here
isRequired, checkoutFor, run, line, blocks
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 run.mjs:1-221 · blob e2404aeccfbd41d150ea73a134804feffd2ad5af · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: experimental · users: none · canonical: supporting_data
/* run.mjs — the estate's test engine. Offline first, always.
 *
 *   node run.mjs                 offline gates only. This is the default,
 *                                because this is the one that must pass before
 *                                anything else is allowed to happen.
 *   node run.mjs --with-network  offline gates, then the network ones, and only
 *                                if every offline gate passed.
 *   node run.mjs --list          what is registered, and what is not green.
 *   node run.mjs --registry P    run a different registry. This exists so the
 *                                runner itself can be shown going red: a gate
 *                                that has never been watched fail is a claim,
 *                                not a measurement.
 *
 * The ordering is the point, and it is enforced here rather than described:
 * a network gate cannot run until every offline gate has passed, because a
 * gate that needs the network cannot tell you anything when the network is
 * what has changed.
 *
 * ABSENT IS NOT PASSED, AND IT IS NOT NEUTRAL EITHER.
 * ---------------------------------------------------------------------------
 * Until 2026-09-05 this file printed the right words and then did the wrong
 * thing. `offlineFailures` counted 'fail' and 'timeout' and not 'absent', so a
 * registry naming clones that do not exist produced, verbatim:
 *
 *     0 passed · 0 failed · 3 not present
 *     A gate that is not present has not passed. It is reported as absent,
 *     never counted as green — a skip is not a pass.
 *     EXIT=0
 *
 * — and the network phase ran anyway, with ZERO offline gates having passed.
 * The ordering rule the header above calls "enforced here rather than
 * described" was bypassed by deleting a directory. A gate you can silence by
 * removing its clone is a gate an accident can remove.
 *
 * So absence blocks, exactly like failure, unless the registry says in writing
 * that a gate is optional (`"required": false`). Nothing is optional today.
 *
 * Each gate runs in its OWN child process. That is not ceremony: a gate signals
 * failure by exiting non-zero, so importing them into one process would let the
 * first failure kill the run and hide the state of every gate after it. A
 * report that stops at the first problem is how a second problem survives to
 * production.
 *
 * It reports what happened. It does not grade the estate.
 */
import { spawnSync } from 'node:child_process';
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { resolveCheckout, branchOf } from './lib/checkout.mjs';

const ROOT = path.dirname(fileURLToPath(import.meta.url));

const withNetwork = process.argv.includes('--with-network');
const listOnly = process.argv.includes('--list');
const registryFlag = process.argv.indexOf('--registry');
const registryPath = registryFlag >= 0 && process.argv[registryFlag + 1]
    ? path.resolve(process.cwd(), process.argv[registryFlag + 1])
    : path.join(ROOT, 'engines.json');

if (!existsSync(registryPath)) {
    console.error(`no registry at ${registryPath}`);
    process.exit(1);
}
const registry = JSON.parse(readFileSync(registryPath, 'utf8'));
/* The registry's own directory is the estate root the paths are relative to,
   so --registry can point at a fixture estate without lying about ../ */
const BASE = path.dirname(registryPath);

/* A gate is required unless the registry says otherwise, in writing. */
const isRequired = (engine) => engine.required !== false;

if (listOnly) {
    console.log(`${registry.engines.length} gates registered — ${registryPath}\n`);
    for (const e of registry.engines) {
        console.log(`${e.network ? 'network' : 'offline'}  ${isRequired(e) ? 'required' : 'OPTIONAL'}  ${e.id.padEnd(28)} ${e.repo}`);
        if (e.status) console.log(`         ${e.status}`);
        for (const d of e.known_defects || []) console.log(`         known: ${d}`);
    }
    process.exit(0);
}

/* Which checkout a gate is run against, and say it out loud.
   ------------------------------------------------------------------------
   The first run of this engine proved the gridatlas composition against
   ../gridatlas, which on this machine is parked on a candidate branch at an
   older generation. It passed, and it was measuring the wrong bytes. A gate
   that reports PASS about a checkout nobody asked about is worse than no gate.

   The first fix — "prefer a sibling on main" — traded that for something
   worse, because it was written as

       candidates.find((c) => c.branch === 'main') || candidates[0]

   and the `||` is a silent fallback to readdir order. Measured going from
   exit 0 to exit 1 across two runs with nothing changed on disk.

   So the registry now says which checkout, in writing. Default: the declared
   `path`, and only that. An engine that genuinely has to choose between
   sibling clones declares `"checkout": { "search": "siblings", "branch": "…" }`
   and gets exactly-one-or-fail from lib/checkout.mjs. There is no fallback in
   either branch of that choice. */
function checkoutFor(engine) {
    const policy = engine.checkout;
    if (!policy || policy === 'declared') {
        const dir = path.resolve(BASE, engine.path);
        return existsSync(dir)
            ? { ok: true, dir, branch: branchOf(dir), why: `declared path ${engine.path}` }
            : { ok: false, dir, branch: null, why: `no clone at ${engine.path}` };
    }
    if (policy.search === 'siblings') {
        const direct = path.resolve(BASE, engine.path);
        return resolveCheckout({
            parent: path.dirname(direct),
            base: path.basename(direct),
            declared: policy.declared || null,
            branch: policy.branch || 'main',
            mustContain: policy.must_contain || []
        });
    }
    return { ok: false, dir: null, branch: null, why: `unknown checkout policy ${JSON.stringify(policy)}` };
}

function run(engine) {
    const required = isRequired(engine);
    const chosen = checkoutFor(engine);
    if (!chosen.ok) {
        return { id: engine.id, required, state: 'absent', detail: chosen.why, ms: 0, branch: chosen.branch || null };
    }
    const cwd = chosen.dir;
    const started = Date.now();
    const [command, ...args] = engine.command;
    const result = spawnSync(command, args, {
        cwd, encoding: 'utf8', shell: process.platform === 'win32', timeout: 15 * 60 * 1000
    });
    const ms = Date.now() - started;
    const output = `${result.stdout || ''}${result.stderr || ''}`;
    /* The last line that says something. A gate's own summary is better
       evidence than anything this runner could invent about it. */
    const summary = output.trim().split('\n').filter(Boolean).slice(-1)[0] || '';
    if (result.error && result.error.code === 'ETIMEDOUT') {
        return { id: engine.id, required, state: 'timeout', detail: '15 minutes', ms, summary, checkout: path.basename(cwd), branch: chosen.branch };
    }
    return {
        id: engine.id,
        required,
        checkout: path.basename(cwd),
        branch: chosen.branch,
        state: result.status === 0 ? 'pass' : 'fail',
        code: result.status,
        ms,
        summary: summary.slice(0, 140)
    };
}

const MARK = { pass: 'ok  ', fail: 'FAIL', absent: 'GONE', timeout: 'TIME' };
const line = (o) => `${MARK[o.state]}  ${o.id.padEnd(26)} ${String(o.branch || '?').padEnd(24)} ${(o.ms / 1000).toFixed(1)}s  ${o.summary || o.detail || ''}`;

/* Blocking, not "failing": a required gate that is not there has told you
   nothing, and nothing is not permission to continue. */
const blocks = (r) => r.state === 'fail' || r.state === 'timeout' || (r.state === 'absent' && r.required);

const offline = registry.engines.filter((e) => !e.network);
const network = registry.engines.filter((e) => e.network);
const results = [];

console.log(`offline gates — ${offline.length}\n`);
for (const engine of offline) {
    const outcome = run(engine);
    results.push({ ...outcome, phase: 'offline' });
    console.log(line(outcome));
}

const offlineBlocking = results.filter(blocks);

if (withNetwork) {
    if (offlineBlocking.length) {
        const failed = offlineBlocking.filter((r) => r.state !== 'absent').length;
        const gone = offlineBlocking.filter((r) => r.state === 'absent').length;
        console.log(`\nnetwork gates NOT RUN — ${failed} offline gate(s) did not pass and ${gone} required gate(s) are not present.`);
        console.log('That ordering is the rule, not a convenience: a gate that needs the');
        console.log('network cannot tell you anything when the network is what has changed.');
        console.log('An absent gate blocks for the same reason a failing one does — it has');
        console.log('not told you the thing you were going to rely on.');
        for (const r of offlineBlocking) console.log(`      ${r.id}: ${r.state} — ${r.detail || r.summary || ''}`);
    } else {
        console.log(`\nnetwork gates — ${network.length}\n`);
        for (const engine of network) {
            const outcome = run(engine);
            results.push({ ...outcome, phase: 'network' });
            console.log(line(outcome));
            if (engine.known_constraint) console.log(`      note: ${engine.known_constraint}`);
        }
    }
}

const passed = results.filter((r) => r.state === 'pass').length;
const absent = results.filter((r) => r.state === 'absent').length;
const absentRequired = results.filter((r) => r.state === 'absent' && r.required).length;
const failed = results.filter((r) => r.state === 'fail' || r.state === 'timeout').length;
const blocking = results.filter(blocks).length;

const report = {
    schema: 'globalgrid2050.testcode.run.v2',
    generated_utc: new Date().toISOString(),
    registry: path.relative(ROOT, registryPath).replace(/\\/g, '/') || path.basename(registryPath),
    ran_network: withNetwork && !offlineBlocking.length,
    counts: { passed, failed, absent, absent_required: absentRequired, blocking },
    results
};
writeFileSync(path.join(process.cwd(), 'testcode-run.json'), JSON.stringify(report, null, 2) + '\n');

console.log(`\n${passed} passed · ${failed} failed · ${absent} not present (${absentRequired} of them required)`);
if (absent) {
    console.log('A gate that is not present has not passed. It is reported as absent,');
    console.log('never counted as green — a skip is not a pass — and while it is');
    console.log('required its absence blocks the run and the exit code, exactly as a');
    console.log('failure does.');
}
console.log(`${blocking} blocking`);
process.exit(blocking ? 1 : 0);

Browser Adapter

A JavaScript file in the grid compute folder of Testcode that draws grid substations. It is built from the show step (`show`).

rendertestcode / sandbox/capsules/grid-compute/browser-adapter.js · lines 1–19 of 19 · Not reached from any entry point (candidate for review)

What it does
It draws grid substations. Defines show. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
What it achieves
Embedded after the unmodified engine observer and geodesy functions.
Why it matters
No other file in the estate was found to import it.
Application
testcode · sandbox/capsules/grid-compute · script
Uses
none found
Used by
none found
Produces
show
Defines here
show
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/capsules/grid-compute/browser-adapter.js:1-19 · blob 730d2d2308b0cf72bec6a347d2b49099261c47a7 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: experimental · users: none · canonical: unreached_review
// Embedded after the unmodified engine observer and geodesy functions.
const query=new URLSearchParams(window.location.search);
const expected={kind:query.get('testcode_entity_kind')||'repd',id:query.get('repd_ref')||query.get('testcode_entity_id')||'unselected'};
const caseId=query.get('testcode_case')||expected.kind+'-'+expected.id;
const visitId=query.get('testcode_visit')||('visit-'+Date.now()+'-'+Math.random().toString(16).slice(2,8));
const records=[];
function show(record){
 let badge=document.getElementById('testcode-compute-receipt');
 if(!badge&&document.body){badge=document.createElement('div');badge.id='testcode-compute-receipt';badge.style.cssText='position:fixed;bottom:3px;left:190px;right:160px;z-index:15000;background:#102330;color:#fff;padding:6px;font:11px monospace;pointer-events:none';document.body.append(badge);}
 if(badge)badge.textContent='TEST CODE '+caseId+' | '+record.status.toUpperCase()+' | '+(record.summary?record.summary.measured_count+' measured | ':'')+visitId;
}
const observer=createComputeObserver({onEvent:record=>{
 const envelope={schema:'testcode.browser-compute-event.v1',case_id:caseId,visit_id:visitId,url:window.location.href,at_utc:new Date().toISOString(),record};records.push(envelope);show(record);
 fetch(new URL('/__testcode/receipt',window.location.href),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(envelope),keepalive:true}).catch(error=>{console.error('Test Code receipt could not be saved',error);});
}});
window.__TESTCODE_GRID_DETECTOR__={expected,caseId,visitId,records,...observer};
const lon=query.has('longitude')?Number(query.get('longitude')):null;
const lat=query.has('latitude')?Number(query.get('latitude')):null;
observer.request({entity:expected,location:Number.isFinite(lon)&&Number.isFinite(lat)?{lon,lat}:null,operation:'route-requested',dataset:'grid_substations.geojson'});

Detector

A JavaScript module in the grid compute folder of Testcode. It is built from the backend for helper (`backendFor`).

transformtestcode / sandbox/capsules/grid-compute/detector.mjs · lines 1–45 of 45 · Not reached from any entry point (candidate for review) · pattern assess (shared by 5 files)

What it does
It calculates its inputs. Defines backendFor, assess.
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Downstream impact
Used directly by 2 files: Detector Proof (testcode); Capsules — Grid Compute (testcode).
What it achieves
Defines `backendFor` and `assess`.
Why it matters
Imported by Detector Proof and Capsules — Grid Compute.
Application
testcode · sandbox/capsules/grid-compute · JavaScript module
Uses
../../../../ventus-grid-engine/engine/compute-observer.js, ../../../../ventus-grid-engine/engine/v9-nearest-search.js, ../../../../ventus-grid-engine/engine/v9-geodesy.js
Used by
imported by Detector Proof (import), imported by Capsules — Grid Compute (import)
Produces
backendFor, assess
Defines here
backendFor, assess
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/capsules/grid-compute/detector.mjs:1-45 · blob 1d2c8b375a25ae3eb227a6b1894013532344dc28 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: unreached_review
import { createComputeObserver } from '../../../../ventus-grid-engine/engine/compute-observer.js';
import { index } from '../../../../ventus-grid-engine/engine/v9-nearest-search.js';
import { representativePoint, voltagesKv } from '../../../../ventus-grid-engine/engine/v9-geodesy.js';

export function backendFor(collection) {
  const points=collection.features.map(f=>{
    const at=representativePoint(f.geometry);
    return {id:String(f.id??''),name:f.properties?.name||'',location:at?{lon:at[0],lat:at[1]}:null,voltages_kv:voltagesKv(f.properties)};
  });
  const lookup=index(points);
  return async c=>{
    const observer=createComputeObserver();const entity={kind:c.kind,id:c.entity_id};
    const location=c.has_location?{lon:c.longitude,lat:c.latitude}:null;
    const id=observer.request({entity,location,operation:'backend nearest-grid',dataset:'pinned grid_substations.geojson'});
    return observer.run(id,request=>{
      const local=lookup.nearest(location.lon,location.lat,{minimumKv:33,limit:5}).filter(x=>x.km<=40);
      const transmission=lookup.nearest(location.lon,location.lat,{minimumKv:400,limit:1});
      const measured=[...local,...(transmission?[transmission]:[])];
      return {entity,origin:request.location,search_completed:true,scanned_count:lookup.located,
        measurements:measured.map(({point,km})=>({node_id:point.name||'coordinate:'+point.location.lon+','+point.location.lat,...point.location,km}))};
    });
  };
}

export function assess(c,records,presentation,backend) {
  const latest=records.at(-1)?.record;
  const selected=latest?.entity?.kind===c.kind && latest?.entity?.id===c.entity_id;
  const actualCall=latest?.operation==='Atlas selectAt / nearest-grid';
  const started=actualCall && latest.events?.some(e=>e.status==='started');
  const completed=started && latest.status==='completed';
  const originMatches=c.has_location && latest?.location?.lon===c.longitude && latest?.location?.lat===c.latitude;
  const parity=completed && backend.status==='completed' && backend.measurements.every(expected=>latest.measurements.some(actual=>Math.abs(actual.lon-expected.lon)<1e-8&&Math.abs(actual.lat-expected.lat)<1e-8&&Math.abs(actual.km-expected.km)<1e-6));
  const mapRendered=presentation?.sourceLineCount>0 && presentation?.renderedLineCount>0;
  const engineFired=Boolean(selected&&actualCall&&completed&&originMatches&&parity);
  let outcome='PASS';
  if(!selected)outcome=latest?'WRONG_ENTITY':'NO_RECEIPT';
  else if(!started)outcome='ENGINE_NOT_FIRED';
  else if(!completed)outcome='ENGINE_'+String(latest.status).toUpperCase();
  else if(!originMatches)outcome='WRONG_OR_UNVERIFIED_LOCATION';
  else if(!parity)outcome='BACKEND_RESULT_MISMATCH';
  else if(!mapRendered)outcome='COMPUTED_BUT_NOT_DRAWN';
  return {passed:outcome==='PASS',outcome,engine_fired:engineFired,map_result_drawn:Boolean(mapRendered),
    investigation:outcome==='PASS'?null:engineFired?'Why did computation complete without a visible map result?':'Why did the grid computation not fire for this entity?',
    checks:{selected,actualCall,started:Boolean(started),completed:Boolean(completed),originMatches:Boolean(originMatches),backendParity:Boolean(parity)},latest};
}

Industrial Candidate

A Python module in the grid compute folder of Testcode that reads cases, grid substations and offshore provenance, using SHA-256.

storagetestcode / sandbox/capsules/grid-compute/industrial-candidate.py · lines 1–44 of 44 · Not reached from any entry point (candidate for review)

What it does
It loads cases, grid substations and offshore provenance. Defines read, write, dump. Uses libraries pathlib, json, shutil, datetime, hashlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: JSON file candidate.json; JSON file current.json; JSON file cases.json; GeoJSON file grid_substations.geojson; JSON file offshore-provenance.json; GeoJSON file wind-sites.geojson; JSON file final-candidate.json; JSON file run.json. Coordinate systems named: WGS84 / EPSG:4326.
What it achieves
It is built from the read step (`read`), the write step (`write`) and the dump step (`dump`). Join CO2 map clicks to actual grid computation, preserving industrial units. It reads `atlas/current.json`.
Why it matters
No other file in the estate was found to import it.
Application
testcode · sandbox/capsules/grid-compute · Python module
Uses
pathlib, json, shutil, datetime, hashlib
Used by
none found
Produces
read, write, dump
Defines here
read, write, dump
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/capsules/grid-compute/industrial-candidate.py:1-44 · blob 0310786db03ba747f238696de20d05c169b8c3ef · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: experimental · users: none · canonical: unreached_review
"""Join CO2 map clicks to actual grid computation, preserving industrial units."""
from pathlib import Path
import json,shutil,datetime,hashlib
H=Path(__file__).resolve().parent;c=json.loads((H/'candidate.json').read_text());old=c['generation'];G=datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%d%H%M');assert G!=old
D=Path(c['build']).parent/G;O=Path(c['output']).parent/(G+'-grid-compute-100');shutil.copytree(c['build'],D);O.mkdir()
def read(p):return p.read_text(encoding='utf-8-sig')
def write(p,s):p.parent.mkdir(parents=True,exist_ok=True);p.write_text(s,encoding='utf8',newline='\n')
def dump(p,x):write(p,json.dumps(x,indent=2,ensure_ascii=False)+'\n')
j=json.loads(read(D/'atlas/current.json'))
for cart in j['cartridges']:
 p=D/'atlas'/cart['path'];s=read(p).replace(old,G)
 if cart['id']=='sld-sandbox':
  s=s.replace('  let currentNearest400 = null;','  let currentNearest400 = null;\n  let currentIndustrialEntity = null;',1)
  s=s.replace("return isProjectTech(tech) || feature.layer?.id === SUBS_LAYER_ID;","return isProjectTech(tech) || tech === 'naei_emitter' || feature.layer?.id === SUBS_LAYER_ID;",1)
  needle="        const origin = representativePoint(hit.geometry)\n          || [event.lngLat.lng, event.lngLat.lat];"
  replacement="""        // Rendered GeoJSON features are tile-quantised. Recover the selected
        // source feature before measuring; never use the expected test point.
        const sourceData = map.getSource(hit.source)?._data;
        const candidates = tech === 'naei_emitter' ? (sourceData?.features || []).filter(f =>
          f.properties?.name === properties.name && f.properties?.operator === properties.operator &&
          Math.abs(f.geometry?.coordinates?.[0] - hit.geometry?.coordinates?.[0]) < 0.001 &&
          Math.abs(f.geometry?.coordinates?.[1] - hit.geometry?.coordinates?.[1]) < 0.001) : [];
        const exactHit = candidates.length === 1 ? candidates[0] : null;
        const origin = representativePoint(exactHit?.geometry || hit.geometry)
          || [event.lngLat.lng, event.lngLat.lat];
        currentIndustrialEntity = tech === 'naei_emitter'
          ? {kind:'industrial',id:String(properties.name || '')+'@'+origin.map(n=>n.toFixed(6)).join(',')}
          : null;"""
  assert needle in s;s=s.replace(needle,replacement,1)
  needle="const entity={kind:fromSubstation?'substation':(currentRepdRef?'repd':detector.expected.kind),id:String(currentRepdRef||detector.expected.id)};"
  assert needle in s;s=s.replace(needle,"const entity=currentIndustrialEntity || {kind:fromSubstation?'substation':(currentRepdRef?'repd':detector.expected.kind),id:String(currentRepdRef||detector.expected.id)};",1)
 dest='cartridges/'+G+'-'+cart['id']+'.js';write(D/'atlas'/dest,s);p.unlink();cart.update(path='./'+dest,generation=G,sha256=hashlib.sha256(s.encode()).hexdigest())
j.update(generation=G,previous_generation=old,composition_id=G+'-industrial-grid-compute',live_route='/testcode/'+G+'/atlas/');dump(D/'atlas/current.json',j)
for rel in ['index.html','pipeline/index.html','atlas/source/menu-bar.js']:
 p=D/rel;write(p,read(p).replace(old,G))
manifest=json.loads(read(Path(c['case_manifest'])))
for row in manifest['cases']:
 if row['kind']=='industrial':
  row['source_entity_id']=row['entity_id'];row['entity_id']=row['name']+'@'+format(row['longitude'],'.6f')+','+format(row['latitude'],'.6f');row['identity_method']='Exact source name and WGS84 coordinates; Parquet projection omits the original NAEI ID.'
manifest['generation']=G;dump(O/'cases.json',manifest);dump(D/'cases.json',manifest)
for p in Path(c['output']).glob('*'):
 if p.name in ['grid_substations.geojson','offshore-provenance.json'] or p.name.endswith('wind-sites.geojson'):shutil.copyfile(p,O/p.name)
shutil.copytree(D,Path(c['webroot'])/'testcode'/G)
new={**c,'generation':G,'output':str(O),'build':str(D),'case_manifest':str(O/'cases.json'),'base':c['base'].replace(old,G)};dump(H/'final-candidate.json',new);dump(O/'run.json',new);print(json.dumps(new,indent=2))

Industrial Diagnostic

A JavaScript module in the grid compute folder of Testcode.

rendertestcode / sandbox/capsules/grid-compute/industrial-diagnostic.cjs · lines 1–5 of 5 · Not reached from any entry point (candidate for review)

What it does
It lists and searches its content. Uses libraries C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
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.
Application
testcode · sandbox/capsules/grid-compute · JavaScript module
Uses
C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright
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
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/capsules/grid-compute/industrial-diagnostic.cjs:1-5 · blob ea6d2daf49dcc5bfae3eacc3109a65f3bee516ce · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: unreached_review
const {chromium}=require('C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright');
(async()=>{const b=await chromium.launch({channel:'chrome',headless:true});const p=await b.newPage({viewport:{width:1400,height:900}});p.on('response',r=>{if(/heavy|naei|parquet/.test(r.url()))console.log('HTTP',r.status(),r.url())});p.on('pageerror',e=>console.log('ERROR',String(e)));
await p.goto('http://127.0.0.1:8877/testcode/202609051329/atlas/?testcode_entity_kind=industrial&testcode_entity_id=3973');await p.getByRole('button',{name:'File',exact:true}).waitFor();
await p.locator('input[data-layer-id="naei_co2"]:visible').last().check();await p.waitForTimeout(6000);
console.log(JSON.stringify(await p.evaluate(()=>{let m=window.__GRIDATLAS_V9_MAP__;return {boxes:[...document.querySelectorAll('[data-layer-id="naei_co2"]')].map(e=>({checked:e.checked})),sources:Object.entries(m.getStyle().sources).filter(([k])=>/naei|heavy/.test(k)).map(([k,s])=>({id:k,type:s.type,count:s.data?.features?.length,examples:m.querySourceFeatures(k).slice(0,2).map(f=>({id:f.id,proper  … [line shortened here: 606 characters; full line on GitHub]

Offshore Candidate

A Python module in the grid compute folder of Testcode that reads crown estate scotland wind sites, crown estate wind sites, offshore provenance and cases, using SHA-256.

storagetestcode / sandbox/capsules/grid-compute/offshore-candidate.py · lines 1–68 of 68 · Not reached from any entry point (candidate for review)

What it does
It loads crown estate scotland wind sites, crown estate wind sites, offshore provenance and cases. Defines read, write, dump, sha. Uses libraries pathlib, json, hashlib, datetime, shutil. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: 400kV.
Inputs & outputs
In: JSON file latest.json; GeoJSON file crown-estate-scotland-wind-sites.geojson; GeoJSON file crown-estate-wind-sites.geojson; JSON file -provenance.json; JSON file current.json; JSON file cases.json; JSON file offshore-provenance.json; GeoJSON file grid_substations.geojson. Coordinate systems named: WGS84 / EPSG:4326. Voltage levels named: 400kV.
What it achieves
It is built from the read step (`read`), the write step (`write`) and the dump step (`dump`). Preserve the failing baseline; add attributed offshore areas and missing drawn results. Its code works with 1000 MW, 400 kV and 960 MW. It reads `atlas/current.json`.
Why it matters
No other file in the estate was found to import it.
Application
testcode · sandbox/capsules/grid-compute · Python module
Uses
pathlib, json, hashlib, datetime, shutil
Used by
none found
Produces
read, write, dump, sha
Defines here
read, write, dump, sha
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/capsules/grid-compute/offshore-candidate.py:1-68 · blob 569de02c8c19f3afd46c1c6d5c5a8ec0b53a94f1 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: experimental · users: none · canonical: unreached_review
"""Preserve the failing baseline; add attributed offshore areas and missing drawn results."""
from pathlib import Path
import json,hashlib,datetime,shutil
H=Path(__file__).resolve().parent
cfg=json.loads((H/'latest.json').read_text()); old=cfg['generation']
G=datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%d%H%M')
assert G!=old
D=Path(cfg['build']).parent/G; O=Path(cfg['output']).parent/(G+'-grid-compute-100')
shutil.copytree(cfg['build'],D); O.mkdir()
def read(p): return p.read_text(encoding='utf-8-sig')
def write(p,s): p.parent.mkdir(parents=True,exist_ok=True);p.write_text(s,encoding='utf8',newline='\n')
def dump(p,x): write(p,json.dumps(x,ensure_ascii=False,indent=2)+'\n')
def sha(p): return hashlib.sha256(p.read_bytes()).hexdigest()
manifest=json.loads(read(Path(cfg['case_manifest'])))
joins=[('11613','crown-estate-scotland-wind-sites.geojson','OBJECTID_1',24,'Property_Description','Buchan Offshore Wind Farm','Crown Estate Scotland','https://www.arcgis.com/home/item.html?id=1f27fd9899e04cebbf40779ba75f69f5'),('11109','crown-estate-wind-sites.geojson','OBJECTID',58,'Name_Prop','R4 Project 2 (Dogger Bank South East)','The Crown Estate','https://www.arcgis.com/home/item.html?id=22a  … [line shortened here: 642 characters; full line on GitHub]
provenance=[]
for ref,file,idkey,fid,namekey,name,owner,url in joins:
 source=Path(cfg['output'])/file; geo=json.loads(read(source))
 f=next(f for f in geo['features'] if f['properties'][idkey]==fid)
 assert f['properties'][namekey]==name, f['properties']
 geom=f['geometry'];polys=[geom['coordinates']] if geom['type']=='Polygon' else geom['coordinates']
 # Signed ring moments, with exterior areas positive and interior areas negative.
 moments=[]
 for poly in polys:
  for i,ring in enumerate(poly):
   pairs=list(zip(ring,ring[1:]));cross=[p[0]*q[1]-q[0]*p[1] for p,q in pairs];a=sum(cross)
   if not a: continue
   x=sum((p[0]+q[0])*v for (p,q),v in zip(pairs,cross))/(3*a)
   y=sum((p[1]+q[1])*v for (p,q),v in zip(pairs,cross))/(3*a)
   moments.append((abs(a)*(1 if i==0 else -1),x,y))
 area=sum(m[0] for m in moments);lon=sum(a*x for a,x,y in moments)/area;lat=sum(a*y for a,x,y in moments)/area
 assert -10<lon<5 and 49<lat<62
 meta={'repd_ref':ref,'source':owner,'source_url':url,'source_sha256':sha(source),'source_feature_id':fid,'source_feature_name':name,'retrieved_utc':datetime.datetime.fromtimestamp(source.stat().st_mtime,datetime.timezone.utc).isoformat(),'method':'Planar area-weighted polygon centroid in WGS84; approximate screening origin, not a surveyed turbine, landfall or agreed grid connection.','longitude':  … [line shortened here: 572 characters; full line on GitHub]
 if ref=='11613':meta.update(identity_evidence='https://buchanoffshorewind.com/project/',capacity_note='REPD retains 1000 MW; Crown Estate Scotland polygon lists 960 MW. Capacity was not overwritten.')
 shard=D/'atlas/data/repd-identities'/(str(int(ref)//1000)+'.json'); data=json.loads(read(shard));row=data[ref]
 assert row.get('longitude') is None and row.get('latitude') is None
 row.update(longitude=lon,latitude=lat,geometry_status='approximate_lease_area_centre',coordinate_source=owner,location_provenance=meta);dump(shard,data)
 dump(D/('atlas/data/project-areas/'+ref+'.geojson'),{'type':'FeatureCollection','features':[f]});dump(D/('atlas/data/project-areas/'+ref+'-provenance.json'),meta)
 c=next(c for c in manifest['cases'] if c['entity_id']==ref);c.update(longitude=lon,latitude=lat,has_location=True,geometry_source=owner,location_provenance=meta)
 shutil.copyfile(source,O/file);provenance.append(meta)
j=json.loads(read(D/'atlas/current.json'))
for c in j['cartridges']:
 p=D/'atlas'/c['path'];s=read(p).replace(old,G)
 if c['id']=='sld-sandbox':
  needle="    if (direction === 'to-substation' && currentDeclared?.at) {"
  assert needle in s
  s=s.replace(needle,"""    // Draw the measured transmission result even beyond the 40 km nearby search.
    // This is indicative straight-line screening, never an agreed connection.
    if (direction === 'to-substation' && currentNearest400?.at &&
        !links.some(l => l.at[0] === currentNearest400.at[0] && l.at[1] === currentNearest400.at[1])) {
      const t = currentNearest400;
      lines.push({type:'Feature',properties:{colour:'#ffd166',strength:0.75,km:t.km,role:'indicative-nearest-transmission'},geometry:{type:'LineString',coordinates:[origin,t.at]}});
      nodes.push({type:'Feature',properties:{colour:'#ffd166',label:`Indicative 400 kV · ${t.km.toFixed(2)} km`},geometry:{type:'Point',coordinates:t.at}});
    }
"""+needle,1)
  s=s.replace("+' | '+record.status.toUpperCase()", "+' | ENGINE '+record.status.toUpperCase()")
 dest='cartridges/'+G+'-'+c['id']+'.js';write(D/'atlas'/dest,s)
 if p!=D/'atlas'/dest:p.unlink()
 c.update(path='./'+dest,generation=G,sha256=hashlib.sha256(s.encode()).hexdigest())
j.update(generation=G,previous_generation=old,composition_id=G+'-offshore-compute-results',live_route='/testcode/'+G+'/atlas/');dump(D/'atlas/current.json',j)
for rel in ['index.html','pipeline/index.html','atlas/source/menu-bar.js']:
 p=D/rel;write(p,read(p).replace(old,G))
p=D/'pipeline/scripts/plugins/projects-v9-5-1.js';s=read(p);s=s.replace("String(project.repd_ref) === '10919'", "['10919','11613','11109','13735'].includes(String(project.repd_ref))");write(p,s)
manifest.update(generation=G,baseline_generation=old);dump(O/'cases.json',manifest);dump(D/'cases.json',manifest);dump(O/'offshore-provenance.json',provenance)
shutil.copyfile(Path(cfg['output'])/'grid_substations.geojson',O/'grid_substations.geojson')
shutil.copytree(D,Path(cfg['webroot'])/'testcode'/G)
new={**cfg,'generation':G,'output':str(O),'build':str(D),'base':cfg['base'].replace(old,G),'case_manifest':str(O/'cases.json')};dump(H/'candidate.json',new);dump(O/'run.json',new)
print(json.dumps(new,indent=2))

Package Results

A Python module in the grid compute folder of Testcode that reads publish candidate, backend browser report, cross browser report and baseline summary, using SHA-256.

storagetestcode / sandbox/capsules/grid-compute/package-results.py · lines 1–51 of 51 · Not reached from any entry point (candidate for review) · pattern compact (shared by 10 files)

What it does
It loads publish candidate, backend browser report, cross browser report and baseline summary. Defines read, dump, digest, compact. Uses libraries pathlib, json, hashlib, datetime, shutil. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: 400kV.
Inputs & outputs
In: JSON file publish-candidate.json; JSON file backend-browser-report.json; JSON file cross-browser-report.json; JSON file results.json; JSON file baseline-summary.json; JSON file codex-chrome-visits.json; JSON file extension-visits.json; JSON file code-sha256.json. Voltage levels named: 400kV.
What it achieves
It is built from the read step (`read`), the dump step (`dump`) and the digest step (`digest`). Publish compact observations and code; never include screenshots. Its code works with 400 kV. It reads `backend-browser-report.json`.
Why it matters
No other file in the estate was found to import it.
Application
testcode · sandbox/capsules/grid-compute · Python module
Uses
Release Metadata (script call), pathlib, json, hashlib, datetime, shutil, subprocess, html, re
Used by
none found
Produces
read, dump, digest, compact
Defines here
read, dump, digest, compact
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/capsules/grid-compute/package-results.py:1-51 · blob 42fcd17b926a5492c077968b7c5426d1b5c39841 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: experimental · users: none · canonical: unreached_review
"""Publish compact observations and code; never include screenshots."""
from pathlib import Path
import json,hashlib,datetime,shutil,subprocess,html,re,sys
H=Path(__file__).resolve().parent;TC=H.parents[2];cfg=json.loads((H/'publish-candidate.json').read_text());G=cfg['generation'];O=Path(cfg['output']);D=Path(cfg['build']);WEB=Path(cfg['webroot']);SRC=Path('C:/Users/vikra/testcode-source-publication')
def read(p):return p.read_text(encoding='utf-8-sig')
def dump(p,x):p.parent.mkdir(parents=True,exist_ok=True);p.write_text(json.dumps(x,ensure_ascii=False,indent=2)+'\n',encoding='utf8',newline='\n')
def digest(p):return hashlib.sha256(p.read_bytes()).hexdigest()
report=json.loads(read(O/'backend-browser-report.json'));cross=json.loads(read(O/'cross-browser-report.json'))
assert report.get('finished_utc') and report['counts']['tested']==110
assert cross.get('finished_utc') and cross['counts']['tested']==35
assert len({r['case_id'] for r in report['checks'] if r['kind']=='repd'})==100
def compact(r):
 keys=['case_id','name','kind','technology','browser','browser_version','visit_id','url','passed','outcome','engine_fired','map_result_drawn','investigation','checks']
 d={k:r.get(k) for k in keys};latest=r.get('latest') or {};d['measurement_origin']=latest.get('location');d['measurements']=latest.get('measurements');d['engine_events']=latest.get('events');d['map_geometry']=r.get('raw',{}).get('presentation');d['error']=r.get('error');return d
summary={'schema':'testcode.grid-compute-observations.v1','generation':G,'finished_utc':report['finished_utc'],'repd':{'tested':100,'passed':sum(r['passed'] for r in report['checks'] if r['kind']=='repd')},'industrial':{'tested':10,'passed':sum(r['passed'] for r in report['checks'] if r['kind']=='industrial')},'cross_browser':cross['counts'],'screenshots':'Disabled and deleted by user instruction;  … [line shortened here: 834 characters; full line on GitHub]
dump(O/'results.json',summary);dump(D/'results.json',summary)
base=TC/'screenshots/202609051320-grid-compute-100/backend-browser-report.json';baseline=json.loads(read(base));dump(O/'baseline-summary.json',{'generation':'202609051320','counts':baseline['counts'],'checks':[compact(r) for r in baseline['checks']]})
visits=json.loads(read(TC/'screenshots/202609051329-grid-compute-100/codex-chrome-visits.json'))
for v in visits:
 v.pop('saved',None);v.update(screenshot='deleted at user request',method='Actual connected Chrome extension; Pipeline search then MAP click; DOM observation and actual computation receipt recorded; tab closed.')
 observed=read(TC/('screenshots/202609051329-grid-compute-100/codex-repd-'+v['ref']+'.txt'));match=re.search(r'visit-\d+-[a-f0-9]+',observed)
 assert match,'Missing correlated receipt for '+v['ref']
 receipt=TC/('screenshots/202609051320-grid-compute-100/receipts/'+match.group()+'.jsonl');events=[json.loads(line) for line in read(receipt).splitlines()];actual=events[-1]['record']
 v.update(visit_id=match.group(),engine_status=actual['status'],entity=actual['entity'],location=actual['location'],measurements=actual.get('measurements'),engine_events=actual['events'],visible_observation=next((line for line in observed.splitlines() if 'Nearest 400 kV substation:' in line),'No nearest-substation paragraph'),dom_observation_sha256=hashlib.sha256(observed.encode()).hexdigest())
dump(O/'extension-visits.json',{'generation':'202609051329','count':len(visits),'visits':visits})
code=O/'code';code.mkdir(exist_ok=True)
for p in H.iterdir():
 if p.suffix in ['.mjs','.cjs','.js','.py','.ps1','.md']:shutil.copyfile(p,code/p.name)
dump(O/'code-sha256.json',{p.name:digest(p) for p in code.iterdir() if p.is_file()})
failure_rows=''.join('<li>'+html.escape(r['case_id']+' — '+r['name']+' — '+r['outcome'])+'</li>' for r in report['checks'] if not r['passed'])
p=D/'index.html';s=read(p);needle='<h1>Grid computation detector '+G+'</h1>';assert needle in s
notice=needle+'<p><strong>Measured result: '+str(summary['repd']['passed'])+'/100 REPD and '+str(summary['industrial']['passed'])+'/10 industrial cases passed.</strong> '+str(cross['counts']['passed'])+'/35 representative cross-browser visits passed. Missing coordinates remain failed; no screenshots are stored.</p><p><a href="results.json">Read the coded observations</a> · <a href="https://github.  … [line shortened here: 583 characters; full line on GitHub]
s=s.replace(needle,notice,1);p.write_text(s,encoding='utf8',newline='\n')
shutil.copytree(D,WEB/'testcode'/G,dirs_exist_ok=True)
shutil.copytree(D,SRC/'sandbox'/G,dirs_exist_ok=True)
capsule=SRC/'sandbox/capsules/grid-compute';capsule.mkdir(parents=True,exist_ok=True)
for p in code.iterdir():shutil.copyfile(p,capsule/p.name)
shutil.copyfile(H/'publish-candidate.json',capsule/'publish-candidate.json')
ev=capsule/'results'/G;ev.mkdir(parents=True,exist_ok=True)
for name in ['results.json','baseline-summary.json','extension-visits.json','code-sha256.json','offshore-provenance.json']:shutil.copyfile(O/name,ev/name)
if (O/'final-chrome-observations.json').exists():shutil.copyfile(O/'final-chrome-observations.json',ev/'final-chrome-observations.json')
for p in O.glob('*wind-sites.geojson'):shutil.copyfile(p,ev/p.name)
# Measure and save a restore point before editing homepage navigation.
home=WEB/'index.html';before=read(home);versions=WEB/'homepage_versions';files=list(versions.glob('homepage_v*.html'));n=max(int(p.stem.split('_v')[1]) for p in files)+1;snapshot=versions/f'homepage_v{n:03}.html'
measurement={'file_count':len(list(versions.iterdir())),'html_version_file':snapshot.name,'line_count':len(before.splitlines()),'word_count':len(before.split()),'character_count':len(before),'sha256':digest(home),'source_commit':subprocess.check_output(['git','rev-parse','HEAD'],cwd=WEB,text=True).strip(),'intention':'Append the measured grid-compute Test Code candidate and retain earlier comparis  … [line shortened here: 561 characters; full line on GitHub]
assert '<h2>Test Code</h2>' in before
entry='<h2>Test Code</h2>\n<p><a href="./testcode/'+G+'/">Grid compute detector — '+G+' UTC</a>: 100 REPD records plus 10 industrial sites; '+str(summary['repd']['passed'])+'/100 REPD and '+str(summary['industrial']['passed'])+'/10 industrial cases pass. <a href="./testcode/'+G+'/results.json">Coded results and remaining failures</a>. No screenshots retained.</p>'
after=before.replace('<h2>Test Code</h2>',entry,1).replace('five Chrome MAP journeys with screenshots; Morgan uses an attributed approximate lease-area centre.','earlier comparison build; superseded by the detector above. Screenshot files were removed.')
home.write_text(after,encoding='utf8',newline='\n')
subprocess.run([sys.executable,str(H/'release-metadata.py')],check=True)
print(json.dumps({'generation':G,'repd':summary['repd'],'industrial':summary['industrial'],'cross_browser':summary['cross_browser'],'result_bytes':(D/'results.json').stat().st_size,'snapshot':str(snapshot)},indent=2))

Prepare

A Python module in the grid compute folder of Testcode that reads published, Renewable Energy Planning Database (REPD) browser registry, heavy emitters UK and grid substations, using SHA-256.

rendertestcode / sandbox/capsules/grid-compute/prepare.py · lines 1–101 of 101 · Not reached from any entry point (candidate for review) · pattern located (shared by 9 files)

What it does
It loads published, REPD browser registry, heavy emitters UK and grid substations. Defines 6 functions or classes, including read, write, dump, digest, located. Uses libraries pathlib, json, hashlib, datetime, shutil. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: JSON file PUBLISHED.json; JSON file repd_browser_registry_202608290716.json; JSON file heavy_emitters_uk.json; GeoJSON file grid_substations.geojson; JSON file cases.json; JSON file current.json; JSON file detector-build.json; JSON file latest.json.
What it achieves
It is built from the read step (`read`), the write step (`write`) and the dump step (`dump`). Freeze the sample, source bytes and an instrumented comparison build. It reads `cases.json` and writes `index.html`.
Why it matters
No other file in the estate was found to import it.
Application
testcode · sandbox/capsules/grid-compute · Python module
Uses
pathlib, json, hashlib, datetime, shutil, html
Used by
none found
Produces
read, write, dump, digest, located, rank
Defines here
read, write, dump, digest, located, rank
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/capsules/grid-compute/prepare.py:1-101 · blob 10785e175e72bc6b2a9ad7e0d1eabdfdba83da98 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: experimental · users: none · canonical: unreached_review
"""Freeze the sample, source bytes and an instrumented comparison build."""
from pathlib import Path
import json,hashlib,datetime,shutil,html
ROOT=Path('C:/Users/vikra/OneDrive/Documents/GitHub');TC=ROOT/'testcode';HERE=Path(__file__).resolve().parent
G=datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%d%H%M');SEED='grid-compute-100-v1'
OUT=TC/'screenshots'/(G+'-grid-compute-100');OUT.mkdir(parents=True,exist_ok=False)
D=TC/'sandbox'/G;WEB=Path('C:/Users/vikra/globalgrid-testcode-publication')
def read(p):return p.read_text(encoding='utf-8-sig')
def write(p,s):p.parent.mkdir(parents=True,exist_ok=True);p.write_text(s,encoding='utf8',newline='\n')
def dump(p,x):write(p,json.dumps(x,indent=2,ensure_ascii=False)+'\n')
def digest(p):return hashlib.sha256(p.read_bytes()).hexdigest()
shutil.copytree(TC/'sandbox/202609051300',D,ignore=shutil.ignore_patterns('evidence','PUBLISHED.json','live-*','*console.txt'))
sources=[];pinned={}
for p in (D/'atlas/data/repd-identities').glob('*.json'):
 pinned.update(json.loads(read(p)));sources.append({'path':str(p.relative_to(D)),'sha256':digest(p)})
registry=ROOT/'gridatlas-main-202609050200/data/repd_browser_registry_202608290716.json'
bio=[r for r in json.loads(read(registry))['records'] if r['technology']=='biomass']
sources.append({'path':str(registry),'sha256':digest(registry)})
def located(r):return isinstance(r.get('longitude'),(int,float)) and isinstance(r.get('latitude'),(int,float)) and (r['longitude'] or r['latitude'])
def rank(r):return hashlib.sha256((SEED+str(r['repd_ref'])).encode()).hexdigest()
cases=[]
for tech in ['solar','bess','wind_onshore','wind_offshore','biomass']:
 pool=bio if tech=='biomass' else [r for r in pinned.values() if r['technology']==tech]
 pool=sorted(pool,key=rank);selected=[]
 # Retain known failures and missing locations instead of selecting only good rows.
 forced=['10919','11613','2484','17559','10772'] if tech=='wind_offshore' else (['12588'] if tech=='solar' else [])
 for ref in forced:
  r=next((r for r in pool if str(r['repd_ref'])==ref),None)
  if r:selected.append(r)
 for r in [r for r in pool if not located(r)][:2]+pool:
  if str(r['repd_ref']) not in {str(x['repd_ref']) for x in selected}:selected.append(r)
  if len(selected)==20:break
 assert len(selected)==20
 for r in selected:
  ref=str(r['repd_ref']);cases.append({'case_id':'repd-'+ref,'kind':'repd','entity_id':ref,'technology':tech,'name':r['name'],'longitude':r.get('longitude'),'latitude':r.get('latitude'),'capacity_mw':r.get('capacity_mw'),'repd_technology':r.get('repd_technology',tech),'source':'registry-202608290716' if tech=='biomass' else 'pipeline-pinned-202609051300','geometry_source':r.get('coordinate_source'  … [line shortened here: 442 characters; full line on GitHub]
assert len(cases)==100 and len({c['entity_id'] for c in cases})==100
industrial=ROOT/'globalgrid2050/heavy_emitters_uk.json';features=json.loads(read(industrial))['features']
features=sorted(features,key=lambda f:hashlib.sha256((SEED+'industrial'+str(f['properties'].get('id'))).encode()).hexdigest())
seen=set()
for f in features:
 p=f['properties'];key=str(p.get('id'));point=f['geometry'].get('coordinates')
 if key in seen or not point or f['geometry']['type']!='Point':continue
 seen.add(key);cases.append({'case_id':'industrial-'+key,'kind':'industrial','entity_id':key,'technology':'naei_emitter','name':p['name'],'longitude':point[0],'latitude':point[1],'emission_tco2e':p.get('emission_tco2e'),'sector':p.get('sector'),'capacity_mw':None,'source':'heavy_emitters_uk.json','has_location':True,'feature':f})
 if len(seen)==10:break
assert len(cases)==110
sources.append({'path':str(industrial),'sha256':digest(industrial)})
subs=ROOT/'gridatlas/atlas/releases/202608300453-atlas-v9/data/grid_substations.geojson'
shutil.copyfile(subs,OUT/'grid_substations.geojson');sources.append({'path':str(subs),'sha256':digest(subs)})
dump(OUT/'cases.json',{'schema':'testcode.grid-compute-cases.v1','seed':SEED,'generation':G,'repd_count':100,'industrial_count':10,'sources':sources,'cases':cases})
dump(D/'cases.json',json.loads(read(OUT/'cases.json')))
engine=ROOT/'ventus-grid-engine/engine'
for name in ['compute-observer.js','v9-geodesy.js','v9-nearest-search.js']:
 shutil.copyfile(engine/name,OUT/'code'/name) if (OUT/'code').exists() else ((OUT/'code').mkdir(),shutil.copyfile(engine/name,OUT/'code'/name))
runtime=read(HERE/'browser-adapter.js')
geodesy=read(engine/'v9-geodesy.js').replace('export ','')
observer=read(engine/'compute-observer.js').replace("import { distanceKm } from './v9-geodesy.js';",'').replace('export ','')
prefix=';(()=>{\nconst {distanceKm}=(()=>{\n'+geodesy+'\nreturn {distanceKm};})();\n'+observer+'\n'+runtime+'\n})();\n'
j=json.loads(read(D/'atlas/current.json'));patches=[]
for c in j['cartridges']:
 p=D/'atlas'/c['path'];s=read(p).replace('202609051300',G)
 if c['id']=='sld-sandbox':
  s=prefix+s
  old='''    async function selectAt(origin, name, tech, fromSubstation, statedMw,
      expectedArrivalEpoch = null) {'''
  new='''    async function selectAtActual(origin, name, tech, fromSubstation, statedMw,
      expectedArrivalEpoch = null, recordComputation = null) {'''
  assert old in s;s=s.replace(old,new,1)
  old="""      drawLinks(map, origin, name, tech,
        nearestSubstations(origin[0], origin[1], subs), 'to-substation', statedMw);"""
  new="""      const measuredLinks = nearestSubstations(origin[0], origin[1], subs);
      recordComputation?.({search_completed:true,scanned_count:subs.length, measurements:[...measuredLinks,currentNearest400].filter(Boolean).map(row=>({node_id:row.name || ('coordinate:'+row.at.join(',')),lon:row.at[0],lat:row.at[1],km:row.km}))});
      drawLinks(map, origin, name, tech, measuredLinks, 'to-substation', statedMw);"""
  assert old in s;s=s.replace(old,new,1)
  old='    link.selectAt = selectAt;'
  new='''    async function selectAt(origin,name,tech,fromSubstation,statedMw,expectedArrivalEpoch=null) {
      const detector=window.__TESTCODE_GRID_DETECTOR__;
      const entity={kind:fromSubstation?'substation':(currentRepdRef?'repd':detector.expected.kind),id:String(currentRepdRef||detector.expected.id)};
      const id=detector.request({entity,location:{lon:origin[0],lat:origin[1]},operation:'Atlas selectAt / nearest-grid',dataset:'grid_substations.geojson'});
      let originalReturn;await detector.run(id,async request=>{
        let result=null;
        originalReturn=await selectAtActual(origin,name,tech,fromSubstation,statedMw,expectedArrivalEpoch,value=>{result=value;});
        if(!result)throw new Error('Actual selection returned without completing a grid measurement');
        return {...result,entity:request.entity,origin:request.location};
      });return originalReturn;
    }
    link.selectAt = selectAt;'''
  assert old in s;s=s.replace(old,new,1);patches.append('Wrapper at actual selectAt closure, receipt from actual nearestSubstations + nearestTransmission return values; original return retained.')
 if s!=read(p):
  dest=f'cartridges/{G}-{c["id"]}.js';write(D/'atlas'/dest,s);p.unlink();c.update(path='./'+dest,sha256=hashlib.sha256(s.encode()).hexdigest(),generation=G)
j.update(generation=G,previous_generation='202609051300',composition_id=G+'-compute-detector',live_route='/testcode/'+G+'/atlas/');dump(D/'atlas/current.json',j)
for p in [D/'pipeline/index.html',D/'atlas/source/menu-bar.js']:write(p,read(p).replace('202609051300',G))
dump(D/'detector-build.json',{'generation':G,'predecessor':'202609051300','patches':patches,'engine_sources':{n:digest(engine/n) for n in ['compute-observer.js','v9-geodesy.js']},'purpose':'Observe actual computation; missing data and unsupported click paths retained as failures.'})
rows=''.join('<tr><td>'+html.escape(c['case_id'])+'</td><td>'+html.escape(c['technology'])+'</td><td>'+html.escape(c['name'])+'</td><td><button data-case="'+c['case_id']+'">Visit</button></td></tr>' for c in cases)
write(D/'index.html','<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Test Code compute detector '+G+'</title><style>body{background:#08151c;color:#e6f4f4;font:16px system-ui;margin:24px}td,th{padding:10px;border-bottom:1px solid #456}button,a{font:inherit;color:#9eeaff;background:#152c36;padding:12px}table{width:100%}</style><h1>Grid   … [line shortened here: 776 characters; full line on GitHub]
write(D/'capsule-launch.js',read(HERE/'capsule-launch.js'))
shutil.copytree(D,WEB/'testcode'/G)
config={'generation':G,'output':str(OUT),'build':str(D),'webroot':str(WEB),'base':'http://127.0.0.1:8877/testcode/'+G+'/','case_manifest':str(OUT/'cases.json')}
dump(HERE/'latest.json',config);dump(OUT/'run.json',config)
for p in HERE.glob('*'):
 if p.is_file():shutil.copyfile(p,OUT/'code'/p.name)
print(json.dumps(config,indent=2))

Publication Candidate

A Python module in the grid compute folder of Testcode that fetches publish candidate, heavy emitters UK, cases and grid substations, using SHA-256.

rendertestcode / sandbox/capsules/grid-compute/publication-candidate.py · lines 1–41 of 41 · Not reached from any entry point (candidate for review)

What it does
It fetches publish candidate, heavy emitters UK, cases and grid substations. Defines read, write, dump. Uses libraries pathlib, json, shutil, datetime, hashlib. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: JSON file final-candidate.json; JSON file heavy_emitters_uk.json; JSON file current.json; JSON file cases.json; GeoJSON file grid_substations.geojson; JSON file offshore-provenance.json; GeoJSON file wind-sites.geojson; JSON file detector-build.json.
What it achieves
It is built from the read step (`read`), the write step (`write`) and the dump step (`dump`). Freeze browser-neutral industrial data delivery and public-safe local logging. It reads `atlas/current.json`.
Why it matters
No other file in the estate was found to import it.
Application
testcode · sandbox/capsules/grid-compute · Python module
Uses
pathlib, json, shutil, datetime, hashlib
Used by
none found
Produces
read, write, dump
Defines here
read, write, dump
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/capsules/grid-compute/publication-candidate.py:1-41 · blob c869204ac04df4990f7c6dc0b7afe41ff01a2532 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: experimental · users: none · canonical: unreached_review
"""Freeze browser-neutral industrial data delivery and public-safe local logging."""
from pathlib import Path
import json,shutil,datetime,hashlib
H=Path(__file__).resolve().parent;c=json.loads((H/'final-candidate.json').read_text());old=c['generation'];G=datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%d%H%M');assert G!=old
D=Path(c['build']).parent/G;O=Path(c['output']).parent/(G+'-grid-compute-100');shutil.copytree(c['build'],D);O.mkdir()
def read(p):return p.read_text(encoding='utf-8-sig')
def write(p,s):p.parent.mkdir(parents=True,exist_ok=True);p.write_text(s,encoding='utf8',newline='\n')
def dump(p,x):write(p,json.dumps(x,indent=2,ensure_ascii=False)+'\n')
source=Path('C:/Users/vikra/OneDrive/Documents/GitHub/globalgrid2050/heavy_emitters_uk.json');dest=D/'atlas/data/heavy_emitters_uk.json';shutil.copyfile(source,dest)
j=json.loads(read(D/'atlas/current.json'))
for cart in j['cartridges']:
 p=D/'atlas'/cart['path'];s=read(p).replace(old,G)
 if cart['id']=='streaming-parquet-bridge':
  needle='    const readyKey = mapReadyKey(pathname);';assert needle in s
  s=s.replace(needle,"""    // A pinned 722 KB GeoJSON keeps industrial identities and works without
    // a second-origin Parquet/WASM round trip before a site can be selected.
    if (legacyStem(pathname) === 'heavy_emitters_uk') {
      return nativeFetch(new URL('./data/heavy_emitters_uk.json', location.href), {...(init || {}), cache:'force-cache'});
    }
"""+needle,1)
 if cart['id']=='sld-sandbox':
  s=s.replace("fetch(new URL('/__testcode/receipt'", "if(['127.0.0.1','localhost'].includes(location.hostname))fetch(new URL('/__testcode/receipt'",1)
  s=s.replace("const entity=currentIndustrialEntity ||", "const entity=(tech === 'naei_emitter' ? currentIndustrialEntity : null) ||",1)
  s=s.replace("id:String(properties.name || '')+'@'+origin.map(n=>n.toFixed(6)).join(',')", "id:properties.id != null ? String(properties.id) : String(properties.name || '')+'@'+origin.map(n=>n.toFixed(6)).join(',')",1)
  s=s.replace('bottom:3px;left:190px;right:160px;', 'bottom:3px;left:8px;right:8px;max-height:28px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;')
 if cart['id']=='substation-intelligence':
  needle=" if (!new URLSearchParams(location.search).get('repd_ref')) return;\n document.documentElement.classList.add('testcode-arrival');"
  assert needle in s;s=s.replace(needle," // The same usable layout also applies when opening industrial layers.\n document.documentElement.classList.add('testcode-arrival');",1)
 dest='cartridges/'+G+'-'+cart['id']+'.js';write(D/'atlas'/dest,s);p.unlink();cart.update(path='./'+dest,generation=G,sha256=hashlib.sha256(s.encode()).hexdigest())
j.update(generation=G,previous_generation=old,composition_id=G+'-grid-compute-capsule',live_route='/testcode/'+G+'/atlas/');dump(D/'atlas/current.json',j)
for rel in ['index.html','pipeline/index.html','atlas/source/menu-bar.js']:
 p=D/rel;write(p,read(p).replace(old,G))
manifest=json.loads(read(Path(c['case_manifest'])))
for row in manifest['cases']:
 if row['kind']=='industrial':row.update(entity_id=row['source_entity_id'],identity_method='Original NAEI ID retained in pinned same-origin GeoJSON.')
manifest['generation']=G;dump(O/'cases.json',manifest);dump(D/'cases.json',manifest)
for p in Path(c['output']).glob('*'):
 if p.name in ['grid_substations.geojson','offshore-provenance.json'] or p.name.endswith('wind-sites.geojson'):shutil.copyfile(p,O/p.name)
meta=json.loads(read(D/'detector-build.json'));meta.update(generation=G,predecessor=old,engine_commit='f9531a7',screenshots='disabled by user; coded observations only',industrial_data={'source':str(source),'sha256':hashlib.sha256(source.read_bytes()).hexdigest(),'bytes':source.stat().st_size},patches=meta['patches']+['Draw measured nearest transmission outside 40 km local search.','Crown Estate an  … [line shortened here: 695 characters; full line on GitHub]
shutil.copytree(D,Path(c['webroot'])/'testcode'/G)
new={**c,'generation':G,'output':str(O),'build':str(D),'case_manifest':str(O/'cases.json'),'base':c['base'].replace(old,G)};dump(H/'publish-candidate.json',new);dump(O/'run.json',new);print(json.dumps(new,indent=2))

Release Metadata

A Python module in the grid compute folder of Testcode that reads publish candidate, detector build and the Renewable Energy Planning Database (REPD) register.

automationtestcode / sandbox/capsules/grid-compute/release-metadata.py · lines 1–11 of 11 · Not reached from any entry point (candidate for review)

What it does
It loads publish candidate, detector build and the REPD register. Uses libraries pathlib, json, html, datetime, shutil. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: the REPD register.
Inputs & outputs
In: JSON file publish-candidate.json; JSON file results.json; JSON file detector-build.json. Out: JSON file release.json.
Downstream impact
Used directly by 1 file: Package Results (testcode).
What it achieves
Replace inherited release claims with this candidate's measured outcomes.
Why it matters
Run by Package Results.
Application
testcode · sandbox/capsules/grid-compute · Python module
Uses
pathlib, json, html, datetime, shutil
Used by
run by Package Results (script call)
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
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/capsules/grid-compute/release-metadata.py:1-11 · blob 1799dad7837ed4a078916b6927cc7ab6ba6d45d4 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: experimental · users: none · canonical: unreached_review
"""Replace inherited release claims with this candidate's measured outcomes."""
from pathlib import Path
import json,html,datetime,shutil
H=Path(__file__).resolve().parent;c=json.loads((H/'publish-candidate.json').read_text());G=c['generation'];D=Path(c['build']);r=json.loads((D/'results.json').read_text());meta=json.loads((D/'detector-build.json').read_text())
release={'generation':G,'predecessor':'202609051300','built_utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'engine_commit':'f9531a7','changes':meta['patches']+['Usable layer-panel layout also applies to industrial visits.'],'results':{'repd':r['repd'],'industrial':r['industrial'],'cross_browser':r['cross_browser']},'limitations':r['limits']+['General free-text Parquet search is outs  … [line shortened here: 489 characters; full line on GitHub]
rows=''.join('<tr><td>'+html.escape(x['case_id'])+'</td><td>'+html.escape(x['name'])+'</td><td>'+html.escape(x['technology'])+'</td><td>'+html.escape(x['outcome'])+'</td></tr>' for x in r['checks'])
page='<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Grid compute observations '+G+'</title><style>body{background:#08151c;color:#e6f4f4;font:16px system-ui;margin:24px}a{color:#9eeaff}td,th{padding:9px;border-bottom:1px solid #456}table{width:100%}</style><a href="./">Test Code</a><h1>Grid compute observations '+G+'</h1><p>94/100 dis  … [line shortened here: 837 characters; full line on GitHub]
for root in [D,Path(c['webroot'])/'testcode'/G,Path('C:/Users/vikra/testcode-source-publication/sandbox')/G]:
 (root/'release.json').write_text(json.dumps(release,indent=2)+'\n',encoding='utf8',newline='\n');(root/'results.html').write_text(page,encoding='utf8',newline='\n')
shutil.copyfile(__file__,Path('C:/Users/vikra/testcode-source-publication/sandbox/capsules/grid-compute/release-metadata.py'))
print('Release metadata and readable results now describe '+G)

Capsules — Grid Compute

A JavaScript module in the sandbox folder of Testcode that reads grid substations and the Renewable Energy Planning Database (REPD) register, using SHA-256.

rendertestcode / sandbox/capsules/grid-compute/run.mjs · lines 1–60 of 60 · Not reached from any entry point (candidate for review)

What it does
It loads grid substations and the REPD register. Defines save. Uses libraries node:fs, playwright, C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: the REPD register. README: "It is enforced by `run.mjs` rather than described by it: the network phase does not execute while an offline gate is red, and the runner says so in words rather than skipping quietly."
Inputs & outputs
In: JSON file latest.json; GeoJSON file grid_substations.geojson.
What it achieves
It is built from the save step (`save`). The README says: It is enforced by `run.mjs` rather than described by it: the network phase does not execute while an offline gate is red, and the runner says so in words rather than skipping quietly.
Why it matters
No other file in the estate was found to import it.
Application
testcode · sandbox/capsules/grid-compute · JavaScript module
Uses
Detector (import), node:fs, playwright, C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright
Used by
none found
Produces
save
Defines here
save
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/capsules/grid-compute/run.mjs:1-60 · blob db260ddaad58e81f98a63be76dea686b0ac1bcb7 · GitHub at these lines
State
achieves: readme · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: experimental · users: none · canonical: unreached_review
import fs from 'node:fs';import path from 'node:path';import crypto from 'node:crypto';import {createRequire} from 'node:module';
import {backendFor,assess} from './detector.mjs';
const require=createRequire(import.meta.url);let pw;try{pw=require('playwright');}catch{pw=require('C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright');}
const here=path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Z]:)/,'$1'));
const config=JSON.parse(fs.readFileSync(path.join(here,process.env.CAPSULE_CONFIG||'latest.json')));const out=config.output;
fs.mkdirSync(out,{recursive:true});
const manifest=JSON.parse(fs.readFileSync(config.case_manifest));
if(manifest.repd_count!==100||manifest.cases.filter(c=>c.kind==='repd').length!==100||new Set(manifest.cases.filter(c=>c.kind==='repd').map(c=>c.entity_id)).size!==100)throw Error('The corpus must contain exactly 100 distinct REPD IDs');
const backend=backendFor(JSON.parse(fs.readFileSync(path.join(out,'grid_substations.geojson'))));
if(process.env.CAPSULE_KIND)manifest.cases=manifest.cases.filter(c=>c.kind===process.env.CAPSULE_KIND);
if(process.env.CAPSULE_CASES){const wanted=new Set(process.env.CAPSULE_CASES.split(','));manifest.cases=manifest.cases.filter(c=>wanted.has(c.case_id));if(manifest.cases.length!==wanted.size)throw Error('Requested case missing from corpus');}
const report={schema:'testcode.grid-compute-capsule.v1',started_utc:new Date().toISOString(),base:config.base,repd_required:100,industrial_required:10,checks:[]};
const browsers=process.env.CAPSULE_BROWSERS?.split(',')||['chrome'];const limit=Number(process.env.CAPSULE_LIMIT)||manifest.cases.length;
const profiles={chrome:{engine:'chromium',channel:'chrome'},edge:{engine:'chromium',channel:'msedge'},firefox:{engine:'firefox'},webkit:{engine:'webkit'},'chrome-android-emulation':{engine:'chromium',channel:'chrome',context:{...pw.devices['Pixel 7']}},'webkit-iphone-emulation':{engine:'webkit',context:{...pw.devices['iPhone 13']}}};
function save(){fs.writeFileSync(path.join(out,(process.env.CAPSULE_REPORT||'backend-browser-report')+'.json'),JSON.stringify(report,null,2));}
function urlFor(c,visit){const u=new URL('atlas/',config.base);for(const [k,v]of Object.entries({testcode_case:c.case_id,testcode_visit:visit,testcode_entity_kind:c.kind,testcode_entity_id:c.entity_id}))u.searchParams.set(k,v);if(c.kind==='repd'){for(const [k,v]of Object.entries({repd_ref:c.entity_id,technology:c.technology,project:c.name,capacity_mw:c.capacity_mw}))if(v!=null)u.searchParams.set(k  … [line shortened here: 526 characters; full line on GitHub]
for(const profileName of browsers){
 const profile=profiles[profileName];if(!profile)throw Error('Unknown browser '+profileName);
 const b=await pw[profile.engine].launch({headless:true,...(profile.channel?{channel:profile.channel}:{})});
 let next=0;
 try{await Promise.all([0,1].map(async worker=>{
  const context=await b.newContext({viewport:{width:1400,height:900},...profile.context});
  try{while(next<limit){const c=manifest.cases[next++];const visit='auto-'+profileName+'-'+c.case_id;const page=await context.newPage();page.setDefaultTimeout(45000);
   const consoleErrors=[];const networkFailures=[];const dataHashes=[];
   page.on('pageerror',e=>consoleErrors.push(String(e)));page.on('requestfailed',r=>networkFailures.push({url:r.url(),error:r.failure()}));
   page.on('response',async r=>{if(r.url().endsWith('grid_substations.geojson'))try{dataHashes.push({url:r.url(),status:r.status(),sha256:crypto.createHash('sha256').update(await r.body()).digest('hex')});}catch{}});
   let raw=null,error=null;const backendReceipt=await backend(c);
   try{
    await page.goto(urlFor(c,visit),{waitUntil:'domcontentloaded'});
    await page.waitForFunction(()=>window.__TESTCODE_GRID_DETECTOR__);
    if(c.kind==='industrial'){
      await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__?.getLayer('l-naei_co2'));
      await page.getByRole('button',{name:'File',exact:true}).waitFor({state:'visible'});
      await page.locator('#gridatlas-dash-toggle').waitFor({state:'visible'});
      const showLayers=page.getByRole('button',{name:'Show the layers panel',exact:true});
      if(await showLayers.isVisible())await showLayers.click();
      const checkbox=page.locator('input[data-layer-id="naei_co2"]:visible').last();
      await checkbox.check();
      // Resolve neighbouring industrial sites 30 m apart through normal zoom.
      await page.evaluate(point=>window.__GRIDATLAS_V9_MAP__.jumpTo({center:point,zoom:17}),[c.longitude,c.latitude]);
      await page.waitForFunction(expected=>window.__GRIDATLAS_V9_MAP__.querySourceFeatures('src-naei_co2').some(f=>f.properties.name===expected.name),{name:c.name},{timeout:20000});
      await page.getByRole('button',{name:'Hide the layers panel',exact:true}).click();
      const point=await page.evaluate(at=>{const m=window.__GRIDATLAS_V9_MAP__,r=m.getContainer().getBoundingClientRect(),p=m.project(at);return {x:r.x+p.x,y:r.y+p.y};},[c.longitude,c.latitude]);
      await page.mouse.click(point.x,point.y);await page.waitForTimeout(1800);
    }else{
      await page.waitForFunction(()=>{const r=window.__TESTCODE_GRID_DETECTOR__?.snapshot();const owner=window.__GRIDATLAS_PLACE_SEARCH__?.deep_link;return (r?.operation==='Atlas selectAt / nearest-grid'&&['completed','failed','unsupported','completed_empty'].includes(r.status))||['FAILED','IDENTIFIED_NO_GEOMETRY','NOT_IN_ACTIVE_REGISTER'].includes(owner?.status);});
      await page.waitForTimeout(1600);
    }
    raw=await page.evaluate(()=>{const d=window.__TESTCODE_GRID_DETECTOR__,m=window.__GRIDATLAS_V9_MAP__;const layers=m?.getStyle()?.layers?.filter(l=>l.source==='gridatlas-neon-links'&&l.type==='line').map(l=>l.id)||[];return {records:d?.records||[],owner:window.__GRIDATLAS_PLACE_SEARCH__?.deep_link,body:document.body.innerText,presentation:{sourceLineCount:m?.getSource('gridatlas-neon-links')?._  … [line shortened here: 598 characters; full line on GitHub]
   }catch(e){error=String(e);raw=await page.evaluate(()=>({records:window.__TESTCODE_GRID_DETECTOR__?.records||[],body:document.body.innerText,owner:window.__GRIDATLAS_PLACE_SEARCH__?.deep_link})).catch(()=>({records:[]}));}
   // User policy: retain compact coded observations, never screenshot files.
   const screenshot=null;
   const verdict=assess(c,raw.records,raw.presentation,backendReceipt);
   const result={case_id:c.case_id,kind:c.kind,technology:c.technology,name:c.name,browser:profileName,browser_version:b.version(),visit_id:visit,url:page.url(),screenshot,backend:backendReceipt,...verdict,error,raw,consoleErrors,networkFailures,dataHashes};
   fs.writeFileSync(path.join(out,visit+'.json'),JSON.stringify(result,null,2));report.checks.push(result);save();console.log(profileName,c.case_id,verdict.outcome);await page.close();
  }}finally{await context.close();}
 }));}finally{await b.close();}
}
report.finished_utc=new Date().toISOString();report.counts={tested:report.checks.length,passed:report.checks.filter(c=>c.passed).length,engine_fired:report.checks.filter(c=>c.engine_fired).length};save();console.log(JSON.stringify(report.counts));
process.exitCode=report.checks.every(c=>c.passed)?0:1;

Screenshot Policy

A Python module in the grid compute folder of Testcode that reads screenshot git policy.

storagetestcode / sandbox/capsules/grid-compute/screenshot-policy.py · lines 1–21 of 21 · Not reached from any entry point (candidate for review)

What it does
It loads screenshot git policy. Uses libraries pathlib, subprocess, json, datetime. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: JSON file SCREENSHOT-GIT-POLICY.json.
What it achieves
Stop tracking generated test screenshots; do not rewrite history or delete user images.
Why it matters
No other file in the estate was found to import it.
Application
testcode · sandbox/capsules/grid-compute · Python module
Uses
pathlib, subprocess, json, datetime
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
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/capsules/grid-compute/screenshot-policy.py:1-21 · blob 0c39f91e0608fe464ec0fb8af9dcdceb00478fae · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: experimental · users: none · canonical: unreached_review
"""Stop tracking generated test screenshots; do not rewrite history or delete user images."""
from pathlib import Path
import subprocess,json,datetime
repos=[Path('C:/Users/vikra/OneDrive/Documents/GitHub/testcode'),Path('C:/Users/vikra/testcode-source-publication'),Path('C:/Users/vikra/globalgrid-testcode-publication')]
records=[]
for repo in repos:
 tracked=subprocess.check_output(['git','ls-files','-z'],cwd=repo).decode().split('\0')
 images=[p for p in tracked if Path(p).suffix.lower() in ['.png','.jpg','.jpeg','.webp'] and any('evidence' in part or part.startswith('compatibility-') or part=='screenshots' for part in Path(p).parts)]
 size=sum((repo/p).stat().st_size for p in images if (repo/p).exists())
 for i in range(0,len(images),50):subprocess.run(['git','rm','--cached','--ignore-unmatch','--',*images[i:i+50]],cwd=repo,check=True,stdout=subprocess.DEVNULL)
 patterns=['screenshots/**/*.png','screenshots/**/*.jpg','screenshots/**/*.jpeg','screenshots/**/*.webp']
 for root in ['sandbox','testcode']:
  for ext in ['png','jpg','jpeg','webp']:
   patterns += [f'{root}/**/evidence*/**/*.{ext}',f'{root}/**/compatibility*/**/*.{ext}',f'{root}/compatibility-*/**/*.{ext}']
 p=repo/'.gitignore';existing=p.read_text() if p.exists() else ''
 extra=[s for s in patterns if s not in existing.splitlines()]
 if extra:p.write_text(existing.rstrip()+'\n# Temporary browser test screenshots: code and text/JSON receipts are retained.\n'+'\n'.join(extra)+'\n',encoding='utf8',newline='\n')
 records.append({'repo':str(repo),'removed_from_current_index':len(images),'bytes_excluded':size,'files':images})
out=Path(__file__).resolve().parents[3]/'screenshots'/'SCREENSHOT-GIT-POLICY.json'
out.write_text(json.dumps({'utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'history_rewritten':False,'local_images_deleted':False,'repositories':records},indent=2)+'\n')
print(json.dumps([{k:v for k,v in r.items() if k!='files'} for r in records],indent=2))