In this section
- Arrival Layout render · testcode / sandbox/tools/arrival-layout.js lines 1–34
- Arrival Message render · testcode / sandbox/tools/arrival-message.py lines 1–14
- Browser Proof render · testcode / sandbox/tools/browser-proof.cjs lines 1–75
- Browser WebGL Probe render · testcode / sandbox/tools/browser-webgl-probe.mjs lines 1–24
- Build Composition Guard storage · testcode / sandbox/tools/build-composition-guard.mjs lines 1–30
- Build Controls Candidate storage · testcode / sandbox/tools/build-controls-candidate.py lines 1–35
- Build Offshore Candidate storage · testcode / sandbox/tools/build-offshore-candidate.py lines 1–129
- Build Poly Candidate storage · testcode / sandbox/tools/build-poly-candidate.mjs lines 1–62
- Build Tool Host Candidate storage · testcode / sandbox/tools/build-tool-host-candidate.mjs lines 1–45
- Build render · testcode / sandbox/tools/build.py lines 1–141
- Candidate Server ingest · testcode / sandbox/tools/candidate-server.cjs lines 1–24
- Composition Contract Browser render · testcode / sandbox/tools/composition-contract.browser.cjs lines 1–39
Arrival Layout
A JavaScript file in the tools folder of Testcode that maps owns the viewport; search and project details have separate slots.
rendertestcode / sandbox/tools/arrival-layout.js · lines 1–34 of 34 · Not reached from any entry point (candidate for review)
- What it does
- It draws its content. 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/tools · script
- Uses
- none found
- 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/tools/arrival-layout.js:1-34 · blob 1a78bdd9a569f798fb4e234a0916848ba168e0b3 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: unreached_review
/* Arrival layout: map owns the viewport; search and project details have separate slots. */
;(() => {
if (!new URLSearchParams(location.search).get('repd_ref')) return;
document.documentElement.classList.add('testcode-arrival');
const style=document.createElement('style');style.textContent=`
@media screen {
.testcode-arrival #gridatlas-menu-bar{position:fixed!important;top:0!important;left:0!important;right:0!important;width:100%!important;min-height:54px!important;box-sizing:border-box;z-index:5000!important}
.testcode-arrival .maplibregl-popup-content p{font-size:12px!important;line-height:1.5!important}
html.testcode-arrival, .testcode-arrival body{height:100%;overflow:hidden}
.testcode-arrival .dashboard{height:100dvh!important;min-height:0!important;padding:0!important;gap:0!important}
.testcode-arrival .map-container,.testcode-arrival #map-container{position:fixed!important;inset:54px 0 0!important;width:100%!important;height:auto!important;min-height:0!important;border:0!important;border-radius:0!important}
.testcode-arrival #map{position:absolute!important;inset:0!important;width:100%!important;height:100%!important}
.testcode-arrival .search-bar-wrapper{position:fixed!important;top:64px!important;left:16px!important;right:auto!important;width:340px!important;max-width:calc(100vw - 32px)!important;display:flex!important;gap:6px!important;z-index:3100!important}
.testcode-arrival .search-bar-wrapper>div{min-width:0!important;flex:1!important;width:auto!important}
.testcode-arrival .search-bar-wrapper input{min-width:0!important;width:100%!important;height:48px!important;font:16px system-ui!important}
.testcode-arrival #search-results{left:0!important;right:0!important;width:100%!important;min-width:0!important;box-sizing:border-box;white-space:normal}
.testcode-arrival .maplibregl-popup{position:fixed!important;left:16px!important;top:124px!important;right:auto!important;bottom:72px!important;width:340px!important;max-width:340px!important;transform:none!important;z-index:2100!important;display:flex!important}
.testcode-arrival .maplibregl-popup-content{width:100%!important;max-height:100%!important;overflow:auto!important;box-sizing:border-box;font-size:13px!important}
.testcode-arrival .maplibregl-popup-tip{display:none!important}
.testcode-arrival .maplibregl-popup.gridatlas-min{bottom:auto!important;height:auto!important;max-height:64px!important}
.testcode-arrival .scada-wrapper{position:fixed!important;right:12px!important;top:124px!important;bottom:72px!important;width:min(420px,calc(100vw - 24px))!important;max-height:calc(100dvh - 196px)!important;overflow:auto!important;z-index:4000!important;background:#08151cf5!important;display:block!important}
.testcode-arrival .scada-wrapper[data-gridatlas-collapsed="1"]{display:none!important}
.testcode-arrival #testcode-fit{position:fixed;right:12px;top:64px;min-height:44px;padding:8px 12px;color:#bdfaff;background:#08151cf2;border:1px solid #37656b;z-index:3200;font:14px system-ui;cursor:pointer}
.testcode-arrival .testcode-identity{font-size:10px;bottom:16px;left:16px;right:auto}
@media(max-width:700px){
.testcode-arrival .search-bar-wrapper{left:12px!important;width:calc(100vw - 24px)!important;max-width:none!important}
.testcode-arrival .maplibregl-popup{left:12px!important;right:12px!important;top:auto!important;bottom:70px!important;width:auto!important;max-width:none!important;height:40dvh!important;max-height:40dvh!important}
.testcode-arrival #testcode-fit{top:120px;min-height:44px}
.testcode-arrival .maplibregl-popup.gridatlas-min{top:auto!important;bottom:70px!important;height:auto!important}
.testcode-arrival .testcode-identity{bottom:8px;font-size:9px}
}
}
`;document.head.append(style);
})();Arrival Message
A Python module in the tools folder of Testcode covering the Renewable Energy Planning Database (REPD) register, using SHA-256.
rendertestcode / sandbox/tools/arrival-message.py · lines 1–14 of 14 · Not reached from any entry point (candidate for review)
- What it does
- It draws the REPD register. Uses libraries json, hashlib. 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.
- Inputs & outputs
- In: JSON file current.json.
- 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/tools · Python module
- Uses
- json, hashlib
- 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/tools/arrival-message.py:1-14 · blob 3b50fcac016a08295b4c016b6f40d14354b4ba3e · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: experimental · users: none · canonical: unreached_review
from pathlib import Path
import json,hashlib
r=Path(__file__).resolve().parents[1]/'202609051214'
p=r/'atlas/cartridges/202609051214-uk-gazetteer-flyto.js';s=p.read_text(encoding='utf8');s=s.replace("document.body.dataset.gridatlasRepdDeepLink='identified-no-geometry';\n return;", """document.body.dataset.gridatlasRepdDeepLink='identified-no-geometry';
resultsEl.innerHTML = '<h3>' + escapeHtml(exact.name) + '</h3><p>REPD ' + escapeHtml(repdRef) + ' / ' + escapeHtml(String(exact.capacity_mw)) + ' MW</p><p>Location unavailable: this Pipeline REPD snapshot supplies no coordinates. No map pin or grid-distance calculation can be shown.</p>';
Object.assign(resultsEl.style,{display:'block',position:'fixed',top:'128px',left:'12px',right:'12px',width:'auto',maxWidth:'420px',maxHeight:'60vh',overflow:'auto',zIndex:'6000',padding:'16px',background:'#08151c',color:'#e2f8ff',boxSizing:'border-box'});
return;""");p.write_text(s,encoding='utf8',newline='\n')
p=r/'pipeline/scripts/plugins/projects-v9-5-1.js';s=p.read_text(encoding='utf8');a=s.index(' const link = `<a class="action-link atlaslink"');b=s.index('\n}\n\nfunction renderTable()',a);s=s[:a]+''' const located = atlasCentresOnRepdPointV9_7(project);
const link = `<a class="action-link atlaslink" target="_blank" rel="noopener" href="${escapeHtml(href)}">${located ? "MAP" : "DETAILS"} ↗</a>`;
if (located) return link;
return `${link}<div class="map-note">No coordinates in the REPD record. Project details are available; map placement is unavailable.</div>`;'''+s[b:];p.write_text(s,encoding='utf8',newline='\n')
p=r/'atlas/current.json';j=json.loads(p.read_text(encoding='utf8'))
for x in j['cartridges']:x['sha256']=hashlib.sha256((r/'atlas'/x['path']).read_bytes()).hexdigest()
p.write_text(json.dumps(j,indent=2)+'\n',encoding='utf8',newline='\n')Browser Proof
A JavaScript module in the tools folder of Testcode that draws browser results, receivers and records.
rendertestcode / sandbox/tools/browser-proof.cjs · lines 1–75 of 75 · Not reached from any entry point (candidate for review)
- What it does
- It draws browser results, receivers and records. Defines save, check. Uses libraries fs, path. 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 receivers.json; CSV file all-records.csv. Out: JSON file browser-results.json.
- What it achieves
- Defines `save` and `check`.
- Why it matters
- No other file in the estate was found to import it.
- Application
- testcode · sandbox/tools · JavaScript module
- Uses
- fs, path
- Used by
- none found
- Produces
- save, check
- Defines here
- save, check
- 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/tools/browser-proof.cjs:1-75 · blob e95740616419e047ebd86b039529aeec9fda1e27 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: experimental · users: none · canonical: unreached_review
const fs=require('fs'),path=require('path');
const {chromium,devices}=require(process.env.PLAYWRIGHT_MODULE||'C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright');
const sandbox=path.resolve(__dirname,'..'),gen=process.env.TEST_GENERATION||fs.readFileSync(path.join(sandbox,'LATEST.txt'),'utf8').trim();
const base=process.env.TEST_BASE||`http://127.0.0.1:8877/testcode/${gen}/`;
const out=process.env.TEST_OUTPUT||path.join(sandbox,gen,'evidence');fs.mkdirSync(out,{recursive:true});
const report={generation:gen,base,started:new Date().toISOString(),browser:'Installed Google Chrome',profiles:[],checks:[],limitations:['Android profile is Chrome device emulation, not a physical Android browser or WebView.','Owner performs real iPhone testing.']};
const save=()=>fs.writeFileSync(path.join(out,'browser-results.json'),JSON.stringify(report,null,2));
function check(name,ok,detail){report.checks.push({name,ok:!!ok,detail});save();console.log(`${ok?'PASS':'FAIL'} ${name}: ${JSON.stringify(detail)}`);}
async function geometry(page){return page.evaluate(()=>{const a=document.querySelector('#tbody .atlaslink');a?.closest('tr').scrollIntoView({block:'center',inline:'nearest'});const r=a?.getBoundingClientRect();const h=r?document.elementFromPoint(r.x+r.width/2,r.y+r.height/2):null;return{rows:document.querySelectorAll('#tbody tr').length,nodes:document.querySelectorAll('*').length,total:document.qu … [line shortened here: 650 characters; full line on GitHub]
(async()=>{const browser=await chromium.launch({channel:'chrome',headless:true});report.browserVersion=browser.version();
try{
for(const profile of [{name:'desktop',viewport:{width:1400,height:900}},{name:'android-touch',...devices['Pixel 7']},{name:'android-receiver-stalled',...devices['Pixel 7'],stall:true}]){
const {name,stall,...options}=profile;console.log('START '+name);const ctx=await browser.newContext({...options,acceptDownloads:true});const page=await ctx.newPage();page.setDefaultTimeout(12000);
const run={name,errors:[]};report.profiles.push(run);page.on('pageerror',e=>run.errors.push(e.message));
if(stall)await ctx.route('**/deeplink/receivers.json',()=>{run.receiverIntercepted=true;});
const started=Date.now();await page.goto(base+'pipeline/',{waitUntil:'domcontentloaded',timeout:45000});
try{await page.waitForFunction(()=>document.querySelector('#resultsMeta')?.dataset.totalCount==='7680',null,{timeout:30000});}catch(e){run.loadError=e.message;}
run.firstRowsMs=Date.now()-started;run.geometry=await geometry(page);
check(name+' bounded rows',run.geometry.rows===50&&run.geometry.total==='7680',run.geometry);
check(name+' bounded DOM',run.geometry.nodes<6000,run.geometry.nodes);
if(name!=='desktop')check(name+' reachable MAP',run.geometry.map?.hit&&run.geometry.map.width>=48&&run.geometry.map.height>=48&&run.geometry.map.right<=run.geometry.viewport,run.geometry.map);
if(stall)check(name+' receiver actually stalled',run.receiverIntercepted,run.receiverIntercepted);
await page.screenshot({path:path.join(out,name+'-pipeline.png')});
if(!stall){
const first=await page.locator('#tbody tr').first().getAttribute('id');await page.locator('#pageNext').click();
const second=await page.locator('#tbody tr').first().getAttribute('id');check(name+' next page changes records',first!==second,{first,second});
await page.locator('#search').fill('8162');await page.waitForFunction(()=>document.querySelector('#resultsMeta')?.dataset.filteredCount==='1');
check(name+' search across full corpus',await page.locator('#tbody tr').first().getAttribute('id')==='repd-8162',await page.locator('#resultsMeta').textContent());
const link=await page.locator('#tbody .atlaslink').getAttribute('href');check(name+' MAP links paired candidate',link.includes(`/testcode/${gen}/atlas/`)&&link.includes('repd_ref=8162'),link);
if(name==='android-touch'){const popupPromise=page.waitForEvent('popup');await page.locator('#tbody .atlaslink').tap();const popup=await popupPromise;await popup.waitForFunction(()=>window.__GRIDATLAS_ATLAS__&&window.__GRIDATLAS_V9_MAP__,null,{timeout:45000});check('mobile MAP tap opens paired Atlas',popup.url().includes('/testcode/'+gen+'/atlas/')&&popup.url().includes('repd_ref=8162')&&await … [line shortened here: 498 characters; full line on GitHub]
await page.locator('#clearFilters').click().catch(async()=>{await page.getByText('CLEAR FILTERS',{exact:true}).click();});
await page.waitForFunction(()=>document.querySelector('#resultsMeta')?.dataset.filteredCount==='7680');
if(name==='desktop'){
const promise=page.waitForEvent('download');await page.getByText('EXPORT FILTERED CSV',{exact:true}).click();const dl=await promise;await dl.saveAs(path.join(out,'all-records.csv'));check('full CSV export',/7,680/.test(await page.locator('#exportMeta').textContent()),await page.locator('#exportMeta').textContent());
}
}
check(name+' no script errors',run.errors.length===0,run.errors);await ctx.close();
}
for(const profile of [{name:'desktop',viewport:{width:1400,height:900}},{name:'android-touch',...devices['Pixel 7']}]){
const {name,...options}=profile;console.log('START '+name+' atlas');const ctx=await browser.newContext({...options,acceptDownloads:true});const page=await ctx.newPage();page.setDefaultTimeout(15000);
const run={name:name+'-atlas',errors:[]};report.profiles.push(run);page.on('pageerror',e=>run.errors.push(e.message));
await page.goto(base+'atlas/',{waitUntil:'domcontentloaded',timeout:45000});
await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__&&document.querySelector('[data-gm-export]'),null,{timeout:45000});
await page.waitForFunction(()=>document.querySelector('.maplibregl-canvas')?.width>0);await page.waitForTimeout(1500);
run.search=await page.locator('.search-bar-wrapper').evaluate(el=>{const r=el.getBoundingClientRect();return{x:r.x,y:r.y,width:r.width,height:r.height,visible:r.width>0&&r.height>0,menu:!!el.closest('.gm-panel')};});
check(name+' persistent search',run.search.visible&&!run.search.menu&&run.search.y>=0,run.search);
check(name+' composed candidate generation',await page.evaluate(()=>window.__GRIDATLAS_ATLAS__.generation)===gen,await page.evaluate(()=>window.__GRIDATLAS_ATLAS__.generation));
await page.screenshot({path:path.join(out,name+'-atlas.png')});
const file=page.locator('.gm-title').filter({hasText:/^File$/i}).first();await file.click();
const imageButton=page.locator('[data-gm-export]').nth(1);const downloadPromise=page.waitForEvent('download',{timeout:15000});await imageButton.click();const download=await downloadPromise;await download.saveAs(path.join(out,name+'-map.png'));
check(name+' image download exists',fs.statSync(path.join(out,name+'-map.png')).size>5000,fs.statSync(path.join(out,name+'-map.png')).size);
await page.evaluate(()=>{window.__proofPrinted=0;window.print=()=>{window.__proofPrinted++;};});
const print=page.locator('[data-gm-export]').first();if(!await print.isVisible())await file.click();await print.click();
await page.waitForFunction(()=>window.__proofPrinted>0&&document.querySelector('.gpf-map')?.naturalWidth>0);
check(name+' print carries generation',(await page.locator('.gpf-stamp').textContent()).includes(gen),await page.locator('.gpf-stamp').textContent());
await page.emulateMedia({media:'print'});const cdp=await ctx.newCDPSession(page);run.pdf=[];
for(const landscape of [false,true]){
if(landscape){
await page.emulateMedia({media:'screen'});
if(!await print.isVisible())await file.click();
await page.evaluate(()=>{window.__proofPrinted=0;});await print.click();
await page.waitForFunction(()=>window.__proofPrinted>0&&document.querySelector('.gpf-map')?.naturalWidth>0);
await page.emulateMedia({media:'print'});
}
await page.screenshot({path:path.join(out,name+(landscape?'-landscape-print':'-portrait-print')+'.png')});
const {data}=await cdp.send('Page.printToPDF',{printBackground:true,paperWidth:8.27,paperHeight:11.69,landscape,preferCSSPageSize:false});const bytes=Buffer.from(data,'base64'),text=bytes.toString('latin1');
const facts={landscape,bytes:bytes.length,images:(text.match(/\/Subtype\s*\/Image/g)||[]).length,pages:(text.match(/\/Type\s*\/Page[^s]/g)||[]).length};run.pdf.push(facts);
fs.writeFileSync(path.join(out,name+(landscape?'-landscape':'-portrait')+'.pdf'),bytes);check(name+' print '+(landscape?'landscape':'portrait'),facts.images>0&&facts.pages===1,facts);
}
await page.screenshot({path:path.join(out,name+'-print.png')});
check(name+' Atlas no script errors',run.errors.length===0,run.errors);await ctx.close();
}
}catch(e){report.error=e.stack;check('harness completed',false,e.message);}finally{await browser.close();report.finished=new Date().toISOString();save();}
process.exitCode=report.checks.some(x=>!x.ok)||report.error?1:0;
})();Browser WebGL Probe
A JavaScript module in the tools folder of Testcode that draws firefox capabilities.
rendertestcode / sandbox/tools/browser-webgl-probe.mjs · lines 1–24 of 24 · Entry point
- What it does
- It draws firefox capabilities. Uses libraries node:module, node:fs, 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.
- Inputs & outputs
- Out: JSON file firefox-capabilities.json.
- Downstream impact
- Used directly by 1 file: Map PDF Workflow (testcode).
- What it achieves
- It writes `pdf-artifacts/firefox-capabilities.json`.
- Why it matters
- Run by Map PDF Workflow.
- Application
- testcode · sandbox/tools · JavaScript module
- Uses
- node:module, node:fs, playwright
- Used by
- run by Map PDF Workflow (workflow run)
- 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/tools/browser-webgl-probe.mjs:1-24 · blob 459c446c6fbea96270d110a8b1bb0513fb37190c · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: experimental · users: none · canonical: unknown
import {createRequire} from 'node:module';
import fs from 'node:fs';
const require=createRequire(import.meta.url);
const {firefox}=require('playwright');
const observations=[];
for(const headless of [true,false]){
const browser=await firefox.launch({headless});
try{
const page=await browser.newPage(),errors=[];
page.on('console',message=>{if(['error','warning'].includes(message.type()))errors.push(message.text());});
const capabilities=await page.evaluate(()=>['webgl2','webgl'].map(kind=>{
const canvas=document.createElement('canvas'),gl=canvas.getContext(kind);
if(!gl)return{kind,available:false};
const extension=gl.getExtension('WEBGL_debug_renderer_info');
const result={kind,available:true,version:gl.getParameter(gl.VERSION),renderer:gl.getParameter(gl.RENDERER),unmaskedRenderer:extension?gl.getParameter(extension.UNMASKED_RENDERER_WEBGL):null};
gl.getExtension('WEBGL_lose_context')?.loseContext();return result;
}));
observations.push({headless,browser:browser.version(),capabilities,errors});
}finally{await browser.close();}
}
fs.mkdirSync('pdf-artifacts',{recursive:true});
fs.writeFileSync('pdf-artifacts/firefox-capabilities.json',JSON.stringify(observations,null,2)+'\n');
console.log(JSON.stringify(observations,null,2));
if(!observations.find(row=>!row.headless).capabilities.some(row=>row.kind==='webgl2'&&row.available))throw Error('The headed Firefox runner does not provide WebGL2 for the map');Build Composition Guard
A JavaScript module in the tools folder of Testcode that reads publication and provenance, using SHA-256.
storagetestcode / sandbox/tools/build-composition-guard.mjs · lines 1–30 of 30 · Not reached from any entry point (candidate for review)
- What it does
- It loads publication and provenance. Defines blob, hash, write. Uses libraries node:fs, node:path, node:assert/strict, node:child_process, node:crypto. 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 current.json; JSON file publication.json; JSON file source-provenance.json.
- What it achieves
- Its name says it builds composition guard. Defines `blob`, `hash` and `write`. It writes `atlas/current.json`.
- Why it matters
- No other file in the estate was found to import it.
- Application
- testcode · sandbox/tools · JavaScript module
- Uses
- Atlas Composition Contract (script call), node:fs, node:path, node:assert/strict, node:child_process, node:crypto, node:url
- Used by
- none found
- Produces
- blob, hash, write
- Defines here
- blob, hash, write
- 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/tools/build-composition-guard.mjs:1-30 · blob 61d4759785a2c30e45d85ffb80ac3b5fcd6aa7f6 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem, process · domain stage: experimental · users: none · canonical: unreached_review
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import {execFileSync} from 'node:child_process';
import {createHash} from 'node:crypto';
import {fileURLToPath} from 'node:url';
const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'../..'),parent='202609060509';
const sourceCommit=execFileSync('git',['rev-parse','HEAD'],{cwd:root,encoding:'utf8'}).trim();
const blob=p=>execFileSync('git',['show',sourceCommit+':'+p],{cwd:root,maxBuffer:64*1024*1024});
const hash=b=>createHash('sha256').update(b).digest('hex');
const generation=new Date().toISOString().replace(/[-:T]/g,'').slice(0,12),destination=path.join(root,'sandbox',generation);assert(!fs.existsSync(destination));
const write=(p,b)=>{const file=path.join(destination,p);fs.mkdirSync(path.dirname(file),{recursive:true});fs.writeFileSync(file,b);};
const current=JSON.parse(blob(`sandbox/${parent}/atlas/current.json`));
for(const c of current.cartridges)if(c.path.startsWith('./'))c.path=`/testcode/${parent}/atlas/${c.path.slice(2)}`;
current.generation=generation;current.previous_generation=parent;current.composition_id=generation+'-testcode-atlas';current.live_route=`/testcode/${generation}/atlas/`;
current.testcode_increment={change:'Reject incomplete cartridge compositions before loading the shell',source_commit:sourceCommit,status:'candidate awaiting actual browser, CI and served-byte checks'};
write('atlas/current.json',JSON.stringify(current,null,2)+'\n');
const parentManifest=JSON.parse(blob(`sandbox/${parent}/publication.json`));
for(const f of parentManifest.files.filter(f=>f.path.startsWith('atlas/')&&!['atlas/current.json','atlas/index.html','atlas/source-provenance.json'].includes(f.path)&&!f.path.startsWith('atlas/cartridges/')))write(f.path,blob(`sandbox/${parent}/${f.path}`));
const contractPath='sandbox/capsules/atlas-composition-contract.mjs',contract=blob(contractPath);
const before=blob(`sandbox/${parent}/atlas/index.html`);
const hook=" invariant(Array.isArray(current.cartridge_order) && Array.isArray(current.cartridges), 'cartridge registry malformed');";
let html=before.toString();assert.equal(html.split(hook).length,2);
html=html.replace('Test Code Atlas '+parent,'Test Code Atlas '+generation).replace(hook,hook+'\n'+contract.toString().replace('export function','function')+'\n validateAtlasComposition(current);');
write('atlas/index.html',html);
write('atlas/source-provenance.json',JSON.stringify({schema:'gridatlas.composition-guard.v1',generation,parent,sourceCommit,contract:{path:contractPath,sha256:hash(contract)},parentIndexSha256:hash(before),indexSha256:hash(html),scope:'Pre-shell composition validation only; four executable cartridges, layout and tool-host initialization unchanged.'},null,2)+'\n');
write('index.html',`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Complete Atlas composition</title><body style="background:#0d1117;color:#7fe3d0;font:18px system-ui;padding:24px"><h1>Complete Atlas composition</h1><p>Atlas checks its complete cartridge set before starting. A failed load preserves your saved polygon.< … [line shortened here: 484 characters; full line on GitHub]
const files=[];function list(dir){for(const e of fs.readdirSync(dir,{withFileTypes:true})){const p=path.join(dir,e.name);if(e.isDirectory())list(p);else{const b=fs.readFileSync(p);files.push({path:path.relative(destination,p).split(path.sep).join('/'),bytes:b.length,sha256:hash(b)});}}}list(destination);
write('publication.json',JSON.stringify({generation,lane:'codex',name:'Validate the complete Atlas composition before starting',source_commit:sourceCommit,parent,status:'candidate awaiting browser and served-byte checks',files},null,2)+'\n');
console.log(JSON.stringify({generation,sourceCommit,files:files.length}));Build Controls Candidate
A Python module in the tools folder of Testcode covering publication and the Renewable Energy Planning Database (REPD) register, using SHA-256.
storagetestcode / sandbox/tools/build-controls-candidate.py · lines 1–35 of 35 · Not reached from any entry point (candidate for review)
- What it does
- Defines blob, write. Uses libraries datetime, hashlib, json, pathlib, subprocess. 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: the REPD register.
- Inputs & outputs
- In: JSON file current.json; JSON file publication.json.
- What it achieves
- It is built from the blob step (`blob`) and the write step (`write`). Publish a thin Atlas composition over the immutable 1906 baseline. It writes `atlas/current.json`.
- Why it matters
- No other file in the estate was found to import it.
- Application
- testcode · sandbox/tools · Python module
- Uses
- datetime, hashlib, json, pathlib, subprocess
- Used by
- none found
- Produces
- blob, write
- Defines here
- blob, write
- 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/tools/build-controls-candidate.py:1-35 · blob e143f52fef5f48b14f165c5db8958ed6a958f583 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: experimental · users: none · canonical: unreached_review
"""Publish a thin Atlas composition over the immutable 1906 baseline."""
import datetime, hashlib, json, pathlib, subprocess
ROOT=pathlib.Path(__file__).resolve().parents[1]
REPO=ROOT.parent
NOW=datetime.datetime.now(datetime.timezone.utc)
GEN=NOW.strftime('%Y%m%d%H%M')
DEST=ROOT/GEN
assert not DEST.exists(), 'Use a fresh UTC generation'
BASE='202609051906'
def blob(p): return subprocess.check_output(['git','-C',str(REPO),'show','HEAD:'+p])
def write(p,b):
p.parent.mkdir(parents=True,exist_ok=True)
p.write_bytes(b.encode() if isinstance(b,str) else b)
current=json.loads(blob(f'sandbox/{BASE}/atlas/current.json'))
current.update(generation=GEN,previous_generation=BASE,composition_id=GEN+'-testcode-atlas',live_route=f'/testcode/{GEN}/atlas/')
for item in current['cartridges']:
item['path']=f'/testcode/{BASE}/atlas/'+item['path'].removeprefix('./')
current['layout_cartridge']={'path':'./map-controls-layout.js','purpose':'Tools above Layers; unobstructed menus; readable address search; Elements label'}
layout=blob('sandbox/capsules/tool-layers/map-controls-layout.js')
current['layout_cartridge']['sha256']=hashlib.sha256(layout).hexdigest()
write(DEST/'atlas/map-controls-layout.js',layout)
write(DEST/'atlas/current.json',json.dumps(current,indent=2)+'\n')
index=blob(f'sandbox/{BASE}/atlas/index.html').decode().replace('Test Code Atlas '+BASE,'Test Code Atlas '+GEN)
write(DEST/'atlas/index.html',index)
write(DEST/'atlas/teleprinter-bootstrap.js',f"import '/testcode/{BASE}/atlas/teleprinter-bootstrap.js';\nimport {{mountMapControlsLayout}} from './map-controls-layout.js';\nmountMapControlsLayout();\n")
# Small identity shards are the only location-relative data in the reused search cartridge.
paths=subprocess.check_output(['git','-C',str(REPO),'ls-tree','-r','--name-only','HEAD',f'sandbox/{BASE}/atlas/data/repd-identities']).decode().splitlines()
for p in paths: write(DEST/'atlas/data/repd-identities'/pathlib.Path(p).name,blob(p))
write(DEST/'index.html',f'<!doctype html><html lang="en"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Atlas controls {GEN}</title><body style="background:#0d1117;color:#7fe3d0;font:18px system-ui;padding:24px"><h1>GridAtlas {GEN}</h1><p>Tools above Layers, clear dropdown menus, wider address search and Elements.</p><p><a style="color:inherit" href="atlas/">Open GridAtl … [line shortened here: 531 characters; full line on GitHub]
manifest={'generation':GEN,'lane':'codex','name':'Clear menus, tools above Layers, wider search, Elements','builtUTC':NOW.isoformat(),'builtLocal':NOW.astimezone().isoformat(),'status':'candidate awaiting browser and served-byte checks','source_commit':subprocess.check_output(['git','-C',str(REPO),'rev-parse','HEAD']).decode().strip(),'parent':BASE,'files':[]}
for p in sorted(DEST.rglob('*')):
if p.is_file():
b=p.read_bytes();manifest['files'].append({'path':p.relative_to(DEST).as_posix(),'bytes':len(b),'sha256':hashlib.sha256(b).hexdigest()})
write(DEST/'publication.json',json.dumps(manifest,indent=2)+'\n')
print(json.dumps({'generation':GEN,'files':len(manifest['files']),'bytes':sum(f['bytes'] for f in manifest['files'])}))Build Offshore Candidate
A Python module in the tools folder of Testcode covering publication and the Renewable Energy Planning Database (REPD) register, using SHA-256.
storagetestcode / sandbox/tools/build-offshore-candidate.py · lines 1–129 of 129 · Entry point · pattern digest (shared by 56 files)
- What it does
- Defines blob, digest, write, function, verify_candidate. Uses libraries datetime, hashlib, json, os, sys. 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: the REPD register.
- Inputs & outputs
- In: JSON file publication.json; JSON file current.json; command-line arguments.
- Downstream impact
- Used directly by 1 file: Offshore Route Workflow (testcode).
- What it achieves
- It verifies candidate (`verify_candidate`) and is built from the blob step (`blob`) and the digest step (`digest`). Compose the reviewed offshore correction over the tested Atlas controls release. It writes `atlas/current.json`.
- Why it matters
- Run by Offshore Route Workflow.
- Application
- testcode · sandbox/tools · Python module
- Uses
- datetime, hashlib, json, os, sys, pathlib, subprocess
- Used by
- run by Offshore Route Workflow (workflow run)
- Produces
- blob, digest, write, function, verify_candidate
- Defines here
- blob, digest, write, function, verify_candidate
- 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/tools/build-offshore-candidate.py:1-129 · blob 1389934e678974dc92bbdfa710d337533a605905 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: experimental · users: none · canonical: supporting_data
"""Compose the reviewed offshore correction over the tested Atlas controls release."""
import datetime
import hashlib
import json
import os
import sys
import pathlib
import subprocess
ROOT = pathlib.Path(__file__).resolve().parents[2]
OWNER = pathlib.Path(os.environ.get('GRIDATLAS_OWNER_REPO', 'C:/Users/vikra/atlas-offshore-scope-20260906'))
PARENT = '202609060228'
NOW = datetime.datetime.now(datetime.timezone.utc)
GEN = NOW.strftime('%Y%m%d%H%M')
DEST = ROOT / 'sandbox' / GEN
def blob(repo, path, sha='HEAD'):
return subprocess.check_output(['git', '-C', str(repo), 'show', f'{sha}:{path}'])
def digest(data):
return hashlib.sha256(data).hexdigest()
def write(path, data):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data.encode('utf-8') if isinstance(data, str) else data)
def function(source, name):
start = source.index(' function ' + name + '(')
end = source.index('\n }', start) + 4
return source[start:end]
def verify_candidate(generation):
assert len(generation) == 12 and generation.isdigit(), 'Invalid candidate generation'
candidate = ROOT / 'sandbox' / generation
manifest = json.loads((candidate / 'publication.json').read_bytes())
assert manifest['generation'] == generation
expected_files = {item['path'] for item in manifest['files']}
actual_files = {p.relative_to(candidate).as_posix() for p in candidate.rglob('*') if p.is_file()}
assert actual_files == expected_files | {'publication.json'}, 'Publication file closure differs'
for item in manifest['files']:
raw = (candidate / item['path']).read_bytes()
assert len(raw) == item['bytes'] and digest(raw) == item['sha256'], item['path']
current = json.loads((candidate / 'atlas/current.json').read_bytes())
pin = current['testcode_increment']
assert current['generation'] == generation
assert pin['source_functions'] == ['corridorBeside', 'openCorridorSheet']
assert manifest['source_commit'] == pin['owner_commit']
owner = blob(OWNER, pin['owner_path'], pin['owner_commit'])
assert digest(owner) == pin['owner_sha256'], 'Owner source identity mismatch'
parent = json.loads(blob(ROOT, f"sandbox/{manifest['parent']}/atlas/current.json"))
old = next(c for c in parent['cartridges'] if c['id'] == 'sld-sandbox')
original = blob(ROOT, 'sandbox/' + old['path'].removeprefix('/testcode/'))
assert digest(original) == old['sha256'] == pin['parent_cartridge_sha256']
expected = original.decode()
source = owner.decode()
for name in pin['source_functions']:
previous = function(expected, name)
assert expected.count(previous) == 1
expected = expected.replace(previous, function(source, name), 1)
start = source.index(' const OFFSHORE_CORRIDOR_NOTE =')
end = source.index(' function corridorBeside', start)
expected = expected.replace(' function corridorBeside', source[start:end] + ' function corridorBeside', 1)
cartridge = next(c for c in current['cartridges'] if c['id'] == 'sld-sandbox')
actual = (candidate / 'atlas' / cartridge['path']).read_bytes()
assert actual == expected.encode() and digest(actual) == cartridge['sha256'], 'Consumer differs from reviewed owner transformation'
for c in current['cartridges']:
relative = c['path']
dependency = ROOT / 'sandbox' / relative.removeprefix('/testcode/') if relative.startswith('/testcode/') else candidate / 'atlas' / relative
raw = blob(ROOT, dependency.relative_to(ROOT).as_posix()) if relative.startswith('/testcode/') else dependency.read_bytes()
assert digest(raw) == c['sha256'], 'Dependency identity mismatch: ' + relative
print(json.dumps({'generation':generation,'source_commit':pin['owner_commit'],'files':len(expected_files),'provenance':'PASS'}))
if '--verify-generation' in sys.argv:
verify_candidate(sys.argv[sys.argv.index('--verify-generation') + 1])
sys.exit(0)
assert not DEST.exists(), 'A published generation cannot be overwritten'
owner_sha = subprocess.check_output(['git', '-C', str(OWNER), 'rev-parse', 'HEAD']).decode().strip()
source_path = 'atlas/parts/202609060246-sld-sandbox-offshore-corridor-scope.js'
source_bytes = blob(OWNER, source_path, owner_sha)
source = source_bytes.decode()
current = json.loads(blob(ROOT, f'sandbox/{PARENT}/atlas/current.json'))
cartridge = next(c for c in current['cartridges'] if c['id'] == 'sld-sandbox')
baseline_path = 'sandbox/' + cartridge['path'].removeprefix('/testcode/')
baseline_bytes = blob(ROOT, baseline_path)
assert digest(baseline_bytes) == cartridge['sha256'], 'Parent source hash mismatch'
updated = baseline_bytes.decode()
for name in ['corridorBeside', 'openCorridorSheet']:
old = function(updated, name)
assert updated.count(old) == 1, 'Ambiguous consumer boundary'
updated = updated.replace(old, function(source, name), 1)
note_start = source.index(' const OFFSHORE_CORRIDOR_NOTE =')
note_end = source.index(' function corridorBeside', note_start)
updated = updated.replace(' function corridorBeside', source[note_start:note_end] + ' function corridorBeside', 1)
updated_bytes = updated.encode()
cartridge.update(path=f'./cartridges/{GEN}-sld-sandbox.js', generation=GEN,
sha256=digest(updated_bytes), version='testcode-' + GEN)
current.update(generation=GEN, previous_generation=PARENT,
composition_id=GEN + '-testcode-atlas', live_route=f'/testcode/{GEN}/atlas/')
current['testcode_increment'] = {
'change': 'Keep offshore straight-line measurements without highway corridor factors',
'owner_commit': owner_sha, 'owner_path': source_path,
'owner_sha256': digest(source_bytes), 'parent_cartridge_sha256': digest(baseline_bytes),
'source_functions': ['corridorBeside', 'openCorridorSheet'],
'status': 'candidate awaiting browser, CI and served-byte verification',
}
write(DEST / 'atlas' / cartridge['path'].removeprefix('./'), updated_bytes)
write(DEST / 'atlas/current.json', json.dumps(current, indent=2) + '\n')
for name in ['index.html', 'map-controls-layout.js', 'teleprinter-bootstrap.js']:
data = blob(ROOT, f'sandbox/{PARENT}/atlas/{name}')
if name == 'index.html':
data = data.replace(('Test Code Atlas ' + PARENT).encode(), ('Test Code Atlas ' + GEN).encode())
write(DEST / 'atlas' / name, data)
# Identity shards remain relative to the consumer; retain the exact baseline bytes.
paths = subprocess.check_output(['git', '-C', str(ROOT), 'ls-tree', '-r', '--name-only', 'HEAD',
f'sandbox/{PARENT}/atlas/data/repd-identities']).decode().splitlines()
for path in paths:
write(DEST / 'atlas/data/repd-identities' / pathlib.Path(path).name, blob(ROOT, path))
write(DEST / 'index.html', f'''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>GridAtlas {GEN}</title><body style="background:#0d1117;color:#7fe3d0;font:18px system-ui;padding:24px"><h1>GridAtlas {GEN}</h1><p>Offshore projects retain measured straight-line distances. Highway-derived corridor estimates are withheld for o … [line shortened here: 602 characters; full line on GitHub]
manifest = {'generation': GEN, 'lane': 'codex', 'name': current['testcode_increment']['change'],
'builtUTC': NOW.isoformat(), 'parent': PARENT, 'source_commit': owner_sha,
'status': 'candidate awaiting browser and served-byte checks', 'files': []}
for path in sorted(DEST.rglob('*')):
if path.is_file():
data = path.read_bytes()
manifest['files'].append({'path': path.relative_to(DEST).as_posix(), 'bytes': len(data), 'sha256': digest(data)})
write(DEST / 'publication.json', json.dumps(manifest, indent=2) + '\n')
print(json.dumps({'generation': GEN, 'owner_commit': owner_sha, 'files': len(manifest['files']),
'cartridge_sha256': digest(updated_bytes)}))Build Poly Candidate
A JavaScript module in the tools folder of Testcode that reads tool layers, provenance, publication and substations, using SHA-256. It is built from the list step (`list`).
storagetestcode / sandbox/tools/build-poly-candidate.mjs · lines 1–62 of 62 · Not reached from any entry point (candidate for review)
- What it does
- It loads tool layers, provenance, publication and substations. Defines blob, hash, write, list. Uses libraries node:fs, node:path, node:assert/strict, node:child_process, node:crypto. 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: substations.
- Inputs & outputs
- In: JSON file current.json; JSON file tool-layers.json; JSON file source-provenance.json; JSON file publication.json; command-line arguments.
- What it achieves
- Its name says it builds poly candidate. Defines `blob`, `hash`, `write` and 1 more. It writes `atlas/current.json`.
- Why it matters
- No other file in the estate was found to import it.
- Application
- testcode · sandbox/tools · JavaScript module
- Uses
- Token Compaction (script call), node:fs, node:path, node:assert/strict, node:child_process, node:crypto, node:url
- Used by
- none found
- Produces
- blob, hash, write, list
- Defines here
- blob, hash, write, list
- 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/tools/build-poly-candidate.mjs:1-62 · blob 052b022d6c902fa72f34c56e16c679d0187a7157 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem, process · domain stage: experimental · users: none · canonical: unreached_review
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import {execFileSync} from 'node:child_process';
import {createHash} from 'node:crypto';
import {fileURLToPath} from 'node:url';
import {compact,proveEquivalent,replaceMapEngine,replaceOptionalModule,PARSER} from './token-compaction.mjs';
const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'../..');
const args=process.argv.slice(2), arg=(key,fallback)=>{const i=args.indexOf('--'+key);return i<0?fallback:args[i+1];};
const owner=arg('owner',process.env.GRIDATLAS_REPO||'C:/Users/vikra/atlas-labels-20260906');
const ownerCommit=arg('commit');assert(/^[a-f0-9]{40}$/.test(ownerCommit),'Pin the full source commit');
const enginePath=arg('engine'),modulePath=arg('module'),parent=arg('parent','202609060300');
assert(/^\d{12}$/.test(parent));
const now=new Date(),generation=now.toISOString().replace(/[-:T]/g,'').slice(0,12);
const destination=path.join(root,'sandbox',generation);assert(!fs.existsSync(destination),'Immutable generation already exists');
const blob=(repo,p,sha='HEAD')=>execFileSync('git',['show',`${sha}:${p}`],{cwd:repo,maxBuffer:64*1024*1024});
const hash=b=>createHash('sha256').update(b).digest('hex');
const parentSourceCommit=execFileSync('git',['rev-parse','HEAD'],{cwd:root,encoding:'utf8'}).trim();
const write=(p,b)=>{const f=path.join(destination,p);fs.mkdirSync(path.dirname(f),{recursive:true});fs.writeFileSync(f,b);};
const current=JSON.parse(blob(root,`sandbox/${parent}/atlas/current.json`));
const cartridge=current.cartridges.find(c=>c.id==='substation-intelligence');assert(cartridge);
const parentPath=cartridge.path.startsWith('/testcode/')?'sandbox/'+cartridge.path.slice(10):`sandbox/${parent}/atlas/${cartridge.path.replace(/^\.\//,'')}`;
const before=blob(root,parentPath);assert.equal(hash(before),cartridge.sha256);
const engine=blob(owner,enginePath,ownerCommit),module=blob(owner,modulePath,ownerCommit);
// The parser selects the carried engine boundary. All sibling modules remain byte-identical before compaction.
let assembled=replaceMapEngine(before.toString(),engine.toString(),module.toString());
const optionalModules=[];
if(arg('extra-module')){
const extraPath=arg('extra-module'),schema=arg('extra-schema'),bytes=blob(owner,extraPath,ownerCommit);
assembled=replaceOptionalModule(assembled,bytes.toString(),schema);
optionalModules.push({path:extraPath,schema,sha256:hash(bytes)});
}
const payload='/* '+generation+'; source and token/AST compaction receipts in source-provenance.json. */\n'+compact(assembled);
proveEquivalent(assembled,payload);
assert(payload.length<=368640,'The established cartridge size ceiling remains in force');
for(const entry of current.cartridges) {
if(entry.path.startsWith('./'))entry.path=`/testcode/${parent}/atlas/${entry.path.slice(2)}`;
}
cartridge.path=`./cartridges/${generation}-substation-intelligence.js`;
cartridge.sha256=hash(payload);cartridge.generation=generation;cartridge.version='testcode-'+generation;
const title=arg('title','Polygon and circle measurements outside the active drawing area');
current.generation=generation;current.previous_generation=parent;current.composition_id=generation+'-testcode-atlas';current.live_route=`/testcode/${generation}/atlas/`;
current.testcode_increment={change:title,owner_commit:ownerCommit,owner_engine:enginePath,owner_module:modulePath,status:'candidate awaiting browser, CI and served-byte checks'};
write('atlas/'+cartridge.path.slice(2),payload);
write('atlas/current.json',JSON.stringify(current,null,2)+'\n');
for(const name of ['index.html','map-controls-layout.js','teleprinter-bootstrap.js']) {
let bytes=blob(root,`sandbox/${parent}/atlas/${name}`);
if(name==='index.html')bytes=Buffer.from(bytes.toString().replace('Test Code Atlas '+parent,'Test Code Atlas '+generation));
write('atlas/'+name,bytes);
}
const parentFiles=execFileSync('git',['ls-tree','--name-only','HEAD',`sandbox/${parent}/atlas/tool-layers.json`],{cwd:root,encoding:'utf8'}).trim();
if(parentFiles)write('atlas/tool-layers.json',blob(root,parentFiles));
const shards=execFileSync('git',['ls-tree','-r','--name-only','HEAD',`sandbox/${parent}/atlas/data/repd-identities`],{cwd:root,encoding:'utf8'}).trim().split('\n').filter(Boolean);
for(const p of shards)write('atlas/data/repd-identities/'+path.basename(p),blob(root,p));
const provenance={schema:'gridatlas.poly-candidate-provenance.v1',generation,parent,parentSourceCommit,ownerCommit,engine:{path:enginePath,sha256:hash(engine)},module:{path:modulePath,sha256:hash(module)},parentCartridge:{path:parentPath,sha256:hash(before)},assembledSha256:hash(assembled),payloadSha256:hash(payload),characters:payload.length,parser:PARSER,proof:'Exact token text and complete synt … [line shortened here: 489 characters; full line on GitHub]
if(optionalModules.length)provenance.optionalModules=optionalModules;
write('atlas/source-provenance.json',JSON.stringify(provenance,null,2)+'\n');
write('index.html',`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>GridAtlas ${generation}</title><body style="background:#0d1117;color:#7fe3d0;font:18px system-ui;padding:24px"><h1>GridAtlas ${generation}</h1><p>${title}</p><p><a style="color:inherit" href="atlas/">Open GridAtlas</a></p><p><a style="color:inherit" hre … [line shortened here: 474 characters; full line on GitHub]
const files=[];
function list(dir){for(const entry of fs.readdirSync(dir,{withFileTypes:true})){const p=path.join(dir,entry.name);if(entry.isDirectory())list(p);else{const b=fs.readFileSync(p);files.push({path:path.relative(destination,p).split(path.sep).join('/'),bytes:b.length,sha256:hash(b)});}}}
list(destination);write('publication.json',JSON.stringify({generation,lane:'codex',name:title,builtUTC:now.toISOString(),source_commit:ownerCommit,parent,status:'candidate awaiting browser and served-byte checks',files},null,2)+'\n');
console.log(JSON.stringify({generation,characters:payload.length,files:files.length,ownerCommit}));Build Tool Host Candidate
A JavaScript module in the tools folder of Testcode that reads tool layers, provenance, publication and the Renewable Energy Planning Database (REPD) register, using SHA-256.
storagetestcode / sandbox/tools/build-tool-host-candidate.mjs · lines 1–45 of 45 · Not reached from any entry point (candidate for review)
- What it does
- It loads tool layers, provenance, publication and the REPD register. Defines blob, hash, write. Uses libraries node:fs, node:path, node:assert/strict, node:child_process, node:crypto. 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: the REPD register.
- Inputs & outputs
- In: JSON file current.json; JSON file tool-layers.json; JSON file source-provenance.json; JSON file publication.json.
- What it achieves
- Its name says it builds tool host candidate. Defines `blob`, `hash` and `write`. It writes `atlas/current.json`.
- Why it matters
- No other file in the estate was found to import it.
- Application
- testcode · sandbox/tools · JavaScript module
- Uses
- node:fs, node:path, node:assert/strict, node:child_process, node:crypto, node:url
- Used by
- none found
- Produces
- blob, hash, write
- Defines here
- blob, hash, write
- 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/tools/build-tool-host-candidate.mjs:1-45 · blob a5dc0fe02adc612e818369847b725bd22a875a7d · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem, process · domain stage: experimental · users: none · canonical: unreached_review
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import {execFileSync} from 'node:child_process';
import {createHash} from 'node:crypto';
import {fileURLToPath} from 'node:url';
const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'../..');
const parent='202609060441',hostGeneration='202609052015',appGeneration='202609051906';
const sourceCommit=execFileSync('git',['rev-parse','HEAD'],{cwd:root,encoding:'utf8'}).trim();
const blob=p=>execFileSync('git',['show',sourceCommit+':'+p],{cwd:root,maxBuffer:64*1024*1024});
const hash=b=>createHash('sha256').update(b).digest('hex');
const generation=new Date().toISOString().replace(/[-:T]/g,'').slice(0,12),destination=path.join(root,'sandbox',generation);
assert(!fs.existsSync(destination),'Immutable generation already exists');
const write=(p,b)=>{const file=path.join(destination,p);fs.mkdirSync(path.dirname(file),{recursive:true});fs.writeFileSync(file,b);};
const current=JSON.parse(blob(`sandbox/${parent}/atlas/current.json`));
for(const cartridge of current.cartridges)if(cartridge.path.startsWith('./'))cartridge.path=`/testcode/${parent}/atlas/${cartridge.path.slice(2)}`;
current.generation=generation;current.previous_generation=parent;current.composition_id=generation+'-testcode-atlas';current.live_route=`/testcode/${generation}/atlas/`;
current.testcode_increment={change:'Recover an unavailable design tool without resetting the Atlas polygon',source_commit:sourceCommit,host_generation:hostGeneration,original_apps_generation:appGeneration,status:'candidate awaiting actual browser, CI and served-byte checks'};
write('atlas/current.json',JSON.stringify(current,null,2)+'\n');
for(const name of ['index.html','map-controls-layout.js']){let b=blob(`sandbox/${parent}/atlas/${name}`);if(name==='index.html')b=Buffer.from(b.toString().replace('Test Code Atlas '+parent,'Test Code Atlas '+generation));write('atlas/'+name,b);}
const identityPaths=execFileSync('git',['ls-tree','-r','--name-only',sourceCommit,`sandbox/${parent}/atlas/data/repd-identities`],{cwd:root,encoding:'utf8'}).trim().split('\n');
for(const p of identityPaths)write('atlas/data/repd-identities/'+path.basename(p),blob(p));
const pins=JSON.parse(blob(`sandbox/${appGeneration}/atlas/tool-layers.json`));
const tools=pins.tools.map(tool=>{const owner=pins.owners.find(owner=>owner.applications.some(app=>app.id===tool.id));assert(owner);return{...tool,owner:{repository:owner.repository,commit:owner.commit,release:owner.release,manifestSha256:owner.manifestSha256}};});
const registry=[...tools];
for(const owner of pins.owners)for(const app of owner.applications)if(!registry.some(tool=>tool.id===app.id))registry.push({id:app.id,title:'DC/AC LV Topology Review',entry:'../layer-apps/'+app.entry,owner:{repository:owner.repository,commit:owner.commit,release:owner.release,manifestSha256:owner.manifestSha256}});
const originalBootstrap=blob(`sandbox/${appGeneration}/atlas/teleprinter-bootstrap.js`);
const parentBootstrap=blob(`sandbox/${parent}/atlas/teleprinter-bootstrap.js`);
const layoutInitializer="import {mountMapControlsLayout} from './map-controls-layout.js';\nmountMapControlsLayout();\n";
assert.equal(parentBootstrap.toString(),`import '/testcode/${appGeneration}/atlas/teleprinter-bootstrap.js';\n`+layoutInitializer,'Account for the complete parent entrypoint before replacing its base import');
let bootstrap=originalBootstrap.toString().replaceAll("from '../teleprinter/",`from '/testcode/${appGeneration}/teleprinter/`)
.replace("from '../tool-layers/host.js'",`from '/testcode/${hostGeneration}/tool-layers/host.js'`)
.replace(/^mountToolLayers\([^\n]+$/m,`mountToolLayers(${JSON.stringify(tools)},new URL('/testcode/${appGeneration}/atlas/teleprinter-bootstrap.js',location.origin).href,${JSON.stringify(registry)});`)
.replace("new URL('../teleprinter/', import.meta.url)",`new URL('/testcode/${appGeneration}/teleprinter/', location.origin)`);
bootstrap+='\n'+layoutInitializer;
write('atlas/teleprinter-bootstrap.js',bootstrap);
write('atlas/tool-layers.json',JSON.stringify({...pins,tools,registry,hostGeneration},null,2)+'\n');
const dependencies=[],queue=[`sandbox/${hostGeneration}/tool-layers/host.js`],seen=new Set();
while(queue.length){const p=queue.shift();if(seen.has(p))continue;seen.add(p);const bytes=blob(p);dependencies.push({path:p,sha256:hash(bytes),bytes:bytes.length});for(const match of bytes.toString().matchAll(/from ['"]([^'"]+)['"]/g)){assert(match[1].startsWith('./'),'Only explicit sibling modules are accepted');queue.push(path.posix.normalize(path.posix.join(path.posix.dirname(p),match[1])));}}
const layout={parentBootstrapSha256:hash(parentBootstrap),sha256:hash(blob(`sandbox/${parent}/atlas/map-controls-layout.js`)),initializer:layoutInitializer};
write('atlas/source-provenance.json',JSON.stringify({schema:'gridatlas.tool-host-candidate.v1',generation,parent,sourceCommit,hostGeneration,appGeneration,originalBootstrapSha256:hash(originalBootstrap),bootstrapSha256:hash(bootstrap),layout,dependencies,scope:'Only consumer tool-host composition changes. All four executable Atlas cartridges, original iframe application paths and existing layout i … [line shortened here: 444 characters; full line on GitHub]
write('index.html',`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Recoverable design tools</title><body style="background:#0d1117;color:#7fe3d0;font:18px system-ui;padding:24px"><h1>Recoverable design tools</h1><p>Retry an unavailable tool while keeping your Atlas polygon and other open tools.</p><p><a style="color:in … [line shortened here: 460 characters; full line on GitHub]
const files=[];function list(dir){for(const entry of fs.readdirSync(dir,{withFileTypes:true})){const p=path.join(dir,entry.name);if(entry.isDirectory())list(p);else{const b=fs.readFileSync(p);files.push({path:path.relative(destination,p).split(path.sep).join('/'),bytes:b.length,sha256:hash(b)});}}}list(destination);
write('publication.json',JSON.stringify({generation,lane:'codex',name:'Recoverable design tools with preserved Atlas drawings',source_commit:sourceCommit,source_repository:'Ventusltd/testcode',parent,status:'candidate awaiting browser and served-byte checks',files},null,2)+'\n');
console.log(JSON.stringify({generation,sourceCommit,files:files.length,hostModules:dependencies.length}));Build
A Python module in the tools folder of Testcode that draws published, regional news and parts, using SHA-256, and uses data from the GridAtlas repository.
rendertestcode / sandbox/tools/build.py · lines 1–141 of 141 · Not reached from any entry point (candidate for review) · pattern replace (shared by 7 files)
- What it does
- It draws published, regional news and parts. Defines 6 functions or classes, including write, read, sha, head, replace. Uses libraries pathlib, json, hashlib, datetime, shutil. Side effects: changes the web page (DOM); 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. README: "Source inputs included the stopped agent's uncommitted menu fixes, identified by hash, plus the changes in tools/build.py and tools/print-view.js."
- Inputs & outputs
- In: data source: gridatlas data; JSON file PUBLISHED.json; JSON file build_manifest.json; JSON file regional_news.json; JSON file regional_manifest.json; JSON file current.json; JSON file parts.json; JSON file release.json.
- What it achieves
- It is built from the write step (`write`), the read step (`read`) and the sha step (`sha`). Build isolated, timestamped comparison candidates; never edit source products. It writes `index.html`.
- Why it matters
- No other file in the estate was found to import it.
- Application
- testcode · sandbox/tools · Python module
- Uses
- GridAtlas — Atlas Page (estate URL), pathlib, json, hashlib, datetime, shutil, re, subprocess, sys
- Used by
- none found
- Produces
- write, read, sha, head, replace, source
- Defines here
- write, read, sha, head, replace, source
- 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/tools/build.py:1-141 · blob 7c8c6fc282c1b2623d27c57d4fc8f9f2804f6f5a · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: experimental · users: none · canonical: unreached_review
"""Build isolated, timestamped comparison candidates; never edit source products."""
import pathlib, json, hashlib, datetime, shutil, re, subprocess, sys
ROOT=pathlib.Path(__file__).resolve().parents[1]
GITHUB=ROOT.parents[1]
PIPE=GITHUB/'globalgrid2050/uk_renewables_pipeline/v9.7'
PIPE_REF='313f56238b91dbe4f8104f286c1fd54cab05ba12'
ATLAS=GITHUB/'gridatlas-main-202609050200'
GEN=sys.argv[1] if len(sys.argv)>1 else datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%d%H%M')
DEST=ROOT/GEN
assert re.fullmatch(r'\d{12}',GEN)
if (DEST/'PUBLISHED.json').exists():raise SystemExit('Published timestamps are immutable; use a new one')
DEST.mkdir(exist_ok=True)
def write(p,s):p.parent.mkdir(parents=True,exist_ok=True);p.write_text(s,encoding='utf-8',newline='\n')
def read(p):return p.read_text(encoding='utf-8-sig').replace('\r\n','\n')
def sha(b):return hashlib.sha256(b).hexdigest()
def head(p):return subprocess.check_output(['git','-C',str(p),'rev-parse','HEAD']).decode().strip()
def replace(s,a,b):
if a not in s:raise ValueError('Expected source fragment missing: '+a[:90])
return s.replace(a,b)
provenance={'generation':GEN,'built_utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'pipeline_parent_commit':PIPE_REF,'atlas_parent_commit':head(ATLAS),'sources':[],'status':'candidate; not production validation','iphone':'user will test real iPhone'}
def source(p):
text=(subprocess.check_output(['git','-C',str(GITHUB/'globalgrid2050'),'show',PIPE_REF+':'+p.relative_to(GITHUB/'globalgrid2050').as_posix()]).decode('utf-8').replace('\r\n','\n') if p.is_relative_to(PIPE) else read(p));provenance['sources'].append({'path':str(p.relative_to(GITHUB)).replace('\\','/'),'sha256_lf':sha(text.encode())});return text
# Pipeline: use the actual existing product, retaining filters, news and full CSV export.
P=DEST/'pipeline'
for folder in ['scripts','styles','contracts']:
for f in (PIPE/folder).rglob('*'):
if f.is_file() and f.suffix in ['.js','.json','.css','.mjs']:
s=source(f).replace('../../dist/','/dist/')
write(P/f.relative_to(PIPE),s)
for f in ['data/v9.1/build_manifest.json','data/v9.7/regional_news.json','data/v9.7/regional_manifest.json']:
s=source(PIPE/f)
if 'build_manifest' in f:
obj=json.loads(s)
for part in obj['project_partitions']:part['path']='/uk_renewables_pipeline/v9.7/'+part['path']
s=json.dumps(obj,indent=2)+'\n'
write(P/f,s)
h=source(PIPE/'index.html')
h=replace(h,'<title>','<title>Test Code '+GEN+' · ')
h=re.sub(r'<nav\b[^>]*>.*?</nav>',f'''<nav aria-label="Version comparison" class="testcode-nav"><a href="../">Test Code {GEN}</a><a href="/uk_renewables_pipeline/v9.7/">Claude current Pipeline</a><a href="../atlas/" id="mapAtlasNav">Test Code Atlas</a><button type="button" id="export">Export CSV</button></nav>''',h,count=1,flags=re.S)
h=replace(h,'<tbody id="tbody"></tbody>','<tbody id="tbody"><tr><td colspan="11" role="status">Loading project records…</td></tr></tbody>')
h=replace(h,'<div class="tablewrap">','<nav id="projectPagination" aria-label="Project pages"></nav>\n <div class="tablewrap">')
h=replace(h,'</head>','<link rel="stylesheet" href="styles/testcode.css">\n</head>')
h=h.replace('../../repd_grid_atlasv8/','../atlas/').replace('V9.7 CANDIDATE',f'TEST CODE {GEN}')
write(P/'index.html',h)
f=P/'scripts/plugins/projects-v9-5-1.js';s=read(f)
s=replace(s,'let all = [];','let pageIndex = 0;\nconst PAGE_SIZE = 50;\nlet all = [];')
s=replace(s,'body.innerHTML = filtered.map((project) => {','pageIndex = Math.min(pageIndex, Math.max(0, Math.ceil(filtered.length / PAGE_SIZE) - 1));\n body.innerHTML = filtered.slice(pageIndex * PAGE_SIZE, (pageIndex + 1) * PAGE_SIZE).map((project) => {')
s=replace(s,' }).join("");\n}\n\nfunction updateResultSummary()', ''' }).join("");
const pagination = document.getElementById("projectPagination");
const pages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE));
pagination.innerHTML = `<button type="button" id="pagePrevious" ${pageIndex === 0 ? "disabled" : ""}>Previous</button><span role="status" aria-live="polite">Page ${pageIndex + 1} of ${pages} · ${filtered.length ? pageIndex * PAGE_SIZE + 1 : 0}–${Math.min((pageIndex + 1) * PAGE_SIZE, filtered.length)} of ${filtered.length.toLocaleString("en-GB")}</span><button type="button" id="pageNext" ${pageIn … [line shortened here: 451 characters; full line on GitHub]
for (const [id, delta] of [["pagePrevious", -1], ["pageNext", 1]]) {
document.getElementById(id).onclick = () => { pageIndex += delta; renderTable(); pagination.scrollIntoView({block:"start"}); };
}
}
function updateResultSummary()''')
s=replace(s,'function apply({ syncUrl = true } = {}) {','function apply({ syncUrl = true } = {}) {\n pageIndex = 0;')
# Candidate links stay inside the same timestamped comparison pair.
s=replace(s,' const href = atlasUrlV9_5_1(project);',' const canonicalHref = atlasUrlV9_5_1(project);\n const href = canonicalHref ? new URL("../atlas/" + new URL(canonicalHref).search, window.location.href).href : "";')
s=replace(s,' nav.href = route;', ' nav.href = new URL("../atlas/", window.location.href).href;')
write(f,s)
f=P/'scripts/data/canonical-projects-v9-1.js';s=read(f).replace('{ cache: "no-store" }','{ cache: "force-cache" }');write(f,s)
write(P/'styles/testcode.css','''
.testcode-nav{display:flex;gap:12px;flex-wrap:wrap;padding:12px;border-block:1px solid #28525a}
.testcode-nav a{min-height:44px;display:flex;align-items:center;font-size:13px}
#projectPagination{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:12px 0;scroll-margin-top:12px}
#projectPagination button{min-height:48px;min-width:78px;background:#101d23;color:#bdf9ff;border:1px solid #49747b;font:inherit;cursor:pointer}
#projectPagination button:disabled{opacity:.4;cursor:default}
#projectPagination span{font-size:13px;text-align:center}
.project-actions .map-note{flex:0 0 auto;max-width:145px}
@media(max-width:768px){
.tablewrap table{min-width:0}.tablewrap .hide-mobile{display:none}
.tablewrap table,.tablewrap tbody{display:block;width:100%}.tablewrap thead{display:none}
.tablewrap tr{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);border:1px solid #28434a;margin-bottom:12px;padding:10px;gap:12px;background:#0a1117}
.tablewrap td{display:block!important;min-width:0!important;width:auto!important;padding:0!important;border:0!important;overflow-wrap:anywhere;white-space:normal!important}
.tablewrap td.hide-mobile{display:none!important}.tablewrap td:first-child,.tablewrap td:last-child{grid-column:1/-1}
.tablewrap td::before{display:block;font-size:10px;color:#8aabb4;margin-bottom:4px}
.tablewrap td:nth-child(4)::before{content:"TECHNOLOGY"}.tablewrap td:nth-child(5)::before{content:"OFFICIAL STATUS"}
.tablewrap td:nth-child(6)::before{content:"CAPACITY"}.tablewrap td:nth-child(10)::before{content:"NEWS SIGNAL"}
.project-actions{display:flex!important;flex-direction:row!important;flex-wrap:wrap;gap:8px!important;align-items:center!important}
.project-actions .map-note{flex-basis:100%!important;max-width:none!important;order:5}
.action-link,.action-disabled,.copy-id{min-width:48px;min-height:48px;display:inline-flex;align-items:center;justify-content:center;box-sizing:border-box}
.site{min-width:130px}#projectPagination{gap:6px}.tablewrap{max-height:70dvh;overflow:auto;overscroll-behavior:contain}
.badge{white-space:normal}.project-actions .map-note{font-size:11px;line-height:1.45;max-width:110px}
}
''')
# Atlas: reassemble only the changed cartridge, retaining the immutable shell.
A=DEST/'atlas';current=json.loads(source(ATLAS/'atlas/current.json'))
atlasOrigin='https://ventusltd.github.io/gridatlas/atlas/'
current['previous_generation']=current['generation'];current['generation']=GEN
current['composition_id']=GEN+'-testcode-atlas';current['live_route']='/testcode/'+GEN+'/atlas/'
current['shell']['index']=atlasOrigin+current['shell']['index'].removeprefix('./')
current['shell']['base']=atlasOrigin+current['shell']['base'].removeprefix('./')
module=source(ATLAS/'atlas/modules/202609031958-menu-bar.js')
module=replace(module,' move(panels.File, ready.nodes.search);',' // Search stays on the map throughout initialization.\n if (ready.nodes.search) ready.nodes.search.setAttribute("data-testcode-search", "persistent");')
start=module.index(' function printView(doc) {');end=module.index(' /* Was anything actually drawn?',start)
module=module[:start]+read(ROOT/'tools/print-view.js')+'\n\n'+module[end:]
# Add visible candidate identity and persistent search without a second UI runtime.
module+=f'''\n;(() => {{
const style=document.createElement('style');style.textContent=`
.search-bar-wrapper{{display:flex!important;position:absolute!important;top:64px!important;left:12px!important;right:12px!important;width:auto!important;max-width:520px!important;z-index:1100!important;margin:0!important;transform:none!important}}
.search-bar-wrapper input{{min-height:48px!important;font-size:16px!important;width:100%!important;box-sizing:border-box}}
.testcode-identity{{position:fixed;right:12px;bottom:64px;z-index:2000;background:#08161fee;color:#aaf6ff;padding:8px;border:1px solid #36616a;font:12px monospace;text-decoration:none}}
@media print{{.testcode-identity,.search-bar-wrapper{{display:none!important}}}}
`;document.head.append(style);
const link=document.createElement('a');link.className='testcode-identity';link.href='/testcode/{GEN}/';link.textContent='Test Code · {GEN}';document.body.append(link);
}})();\n'''
write(A/'source/menu-bar.js',module)
for item in current['cartridges']:
originalPath=item['path'].removeprefix('./')
if item['id']=='substation-intelligence':
manifest=json.loads(source(ATLAS/'atlas'/item['assembled_from'].removeprefix('./')))
pieces=[];parts=[]
for part in manifest['assembled_from']:
text=module if part['path'].endswith('/202609031958-menu-bar.js') else source(ATLAS/part['path'])
pieces.append(text);parts.append({'source':part['path'],'sha256':sha(text.encode()),'bytes':len(text.encode())})
assembled=f'/* Test Code {GEN}; reassembled from individually hashed parts. */\n'+'\n'.join(pieces)
filename=f'cartridges/{GEN}-substation-intelligence.js';write(A/filename,assembled)
item.update(path='./'+filename,sha256=sha(assembled.encode()),generation=GEN,version='testcode-'+GEN,assembled_from='./parts.json')
write(A/'parts.json',json.dumps({'generation':GEN,'parts':parts,'sha256':item['sha256']},indent=2)+'\n')
else:
data=(ATLAS/'atlas'/originalPath).read_bytes().replace(b'\r\n',b'\n')
assert sha(data)==item['sha256'],originalPath
dest=A/originalPath;dest.parent.mkdir(parents=True,exist_ok=True);dest.write_bytes(data)
write(A/'current.json',json.dumps(current,indent=2)+'\n')
write(A/'index.html',source(ATLAS/'atlas/index.html').replace('<title>Grid Atlas</title>',f'<title>Test Code Atlas {GEN}</title>'))
write(DEST/'index.html',f'''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Test Code · {GEN}</title>
<style>body{{margin:0 auto;padding:24px;max-width:900px;background:#080f14;color:#e9f4f4;font:17px/1.6 system-ui}}a{{color:#9eeaff}}h1{{font-size:32px}}.pair{{display:grid;grid-template-columns:1fr 1fr;gap:18px;margin:24px 0}}article{{border:1px solid #34515c;padding:20px;background:#101e26}}article a{{display:block;padding:12px 0;min-height:28px}}small{{color:#b4c4ca}}@media(max-width:600px){{.pa … [line shortened here: 441 characters; full line on GitHub]
<a href="/">GlobalGrid2050</a><h1>Test Code</h1><p>Comparison build <strong>{GEN}</strong> UTC</p>
<div class="pair"><article><h2>Pipeline News</h2><p>50 rows per page. Search and CSV still cover all 7,680 records. MAP stays reachable on small screens.</p><a href="pipeline/">Open Test Code Pipeline →</a><a href="/uk_renewables_pipeline/202609051156/">Compare Claude’s current Pipeline</a></article>
<article><h2>Grid Atlas</h2><p>Search stays visible. Print captures the map before laying out the page. Save uses the map’s render frame.</p><a href="atlas/">Open Test Code Atlas →</a><a href="https://ventusltd.github.io/gridatlas/atlas/">Compare Claude’s current Atlas</a></article></div>
<p><a href="results.html">Browser test results</a> · <a href="release.json">Build record</a> · <a href="https://github.com/Ventusltd/testcode/tree/main/sandbox/{GEN}">Source on GitHub</a></p>
<p><small>These are comparison candidates. iPhone testing is being performed by the owner. They do not replace the existing published versions.</small></p></html>''')
write(DEST/'results.html','<!doctype html><meta charset="utf-8"><title>Test Code results</title><h1>Browser results pending</h1><p>This candidate has not yet completed browser verification.</p>')
write(DEST/'release.json',json.dumps(provenance,indent=2)+'\n')
write(ROOT/'LATEST.txt',GEN+'\n')
print(json.dumps({'generation':GEN,'directory':str(DEST),'files':len(list(DEST.rglob('*')))}))Candidate Server
A JavaScript module in the tools folder of Testcode that reads bytes (`readBytes`). It reads bytes (`readBytes`).
ingesttestcode / sandbox/tools/candidate-server.cjs · lines 1–24 of 24 · Entry point · pattern readBytes (shared by 2 files)
- What it does
- It loads data. Defines readBytes. Uses libraries node:fs, node:path, node:http, node:child_process. 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.
- Downstream impact
- Used directly by 8 files: Composition Guard Workflow (testcode); Map PDF Workflow (testcode); Measurement Clearance Workflow (testcode); Measurement Readouts Workflow (testcode); and 4 more.
- What it achieves
- Defines `readBytes`.
- Why it matters
- Run by 8 workflows and scripts, including Composition Guard Workflow, Map PDF Workflow and Measurement Clearance Workflow.
- Application
- testcode · sandbox/tools · JavaScript module
- Uses
- node:fs, node:path, node:http, node:child_process
- Used by
- run by Composition Guard Workflow (workflow run), run by Map PDF Workflow (workflow run), run by Measurement Clearance Workflow (workflow run), run by Measurement Readouts Workflow (workflow run), run by Polygon Distance Workflow (workflow run), run by Tool Recovery Workflow (workflow run), run by Vertex Limit Workflow (workflow run), run by Vertex Removal Workflow (workflow run)
- Produces
- readBytes
- Defines here
- readBytes
- 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/tools/candidate-server.cjs:1-24 · blob 0ef11bf1c3210e75cbbc8d015f786c7642684bb1 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: experimental · users: none · canonical: unknown
const fs=require('node:fs'),path=require('node:path'),http=require('node:http');
const {execFileSync}=require('node:child_process');
const root=path.resolve(__dirname,'../..');
const sourceCommit=execFileSync('git',['rev-parse','HEAD'],{cwd:root,encoding:'utf8'}).trim();
const committed=new Set(execFileSync('git',['ls-tree','-r','--name-only',sourceCommit],{cwd:root,encoding:'utf8',maxBuffer:16*1024*1024}).trim().split('\n'));
const cache=new Map();
function readBytes(repoPath,file){
if(!committed.has(repoPath))return fs.readFileSync(file); // Uncommitted candidate preview.
if(!cache.has(repoPath))cache.set(repoPath,execFileSync('git',['show',sourceCommit+':'+repoPath],{cwd:root,maxBuffer:64*1024*1024}));
return cache.get(repoPath);
}
const server = http.createServer((req,res) => {
const pathname = decodeURIComponent(new URL(req.url,'http://localhost').pathname);
const relative = pathname.startsWith('/testcode/') ? '/sandbox/' + pathname.slice(10) : pathname;
let file = path.resolve(root, '.' + relative);
if (!file.startsWith(root + path.sep)) return res.writeHead(403).end();
try {
if (fs.statSync(file).isDirectory()) file=path.join(file,'index.html');
const repoPath=path.relative(root,file).split(path.sep).join('/');
const bytes=readBytes(repoPath,file);
res.writeHead(200,{'Content-Type':({'.html':'text/html','.js':'text/javascript','.mjs':'text/javascript','.json':'application/json','.css':'text/css'})[path.extname(file)]||'application/octet-stream'}).end(bytes);
} catch {res.writeHead(404).end();}
});
server.listen(Number(process.env.TEST_PORT||8417),'127.0.0.1',()=>console.log('Candidate server ready '+server.address().port+' committed bytes '+sourceCommit));Composition Contract Browser
A JavaScript module in the tools folder of Testcode that fetches retained.
rendertestcode / sandbox/tools/composition-contract.browser.cjs · lines 1–39 of 39 · Entry point · pattern record (shared by 46 files)
- What it does
- It fetches retained. Defines record. Uses libraries node:fs, node:path, playwright, C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright. Side effects: changes the web page (DOM); reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
- 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 current.json; GeoJSON file retained.geojson; browser storage (getItem); command-line arguments. Out: JSON file results.json.
- Downstream impact
- Used directly by 4 files: Composition Guard Workflow (testcode); Measurement Readouts Workflow (testcode); Polygon Distance Workflow (testcode); Vertex Limit Workflow (testcode).
- What it achieves
- Defines `record`.
- Why it matters
- Run by 4 workflows and scripts, including Composition Guard Workflow, Measurement Readouts Workflow and Polygon Distance Workflow.
- Application
- testcode · sandbox/tools · JavaScript module
- Uses
- node:fs, node:path, playwright, C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright
- Used by
- run by Composition Guard Workflow (workflow run), run by Measurement Readouts Workflow (workflow run), run by Polygon Distance Workflow (workflow run), run by Vertex Limit Workflow (workflow run)
- Produces
- record
- Defines here
- record
- 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/tools/composition-contract.browser.cjs:1-39 · blob 18a892fdae9b0bb59b8751cc5a895b5046a3203d · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: experimental · users: none · canonical: unknown
const fs=require('node:fs'),path=require('node:path');
let pw;try{pw=require('playwright');}catch{pw=require('C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright');}
const base=process.argv[2],out=path.resolve(process.env.TEST_OUTPUT||'composition-contract-artifacts');fs.mkdirSync(out,{recursive:true});const checks=[];
const record=(name,pass,detail)=>{checks.push({name,pass:!!pass,detail});console.log(pass?'PASS':'FAIL',name);fs.writeFileSync(path.join(out,'results.json'),JSON.stringify({base,checks},null,2));};
(async()=>{const current=await(await fetch(new URL('current.json',base))).json();
const cases=current.cartridge_order.map(id=>({name:'missing-'+id,mutate:c=>{c.cartridge_order=c.cartridge_order.filter(x=>x!==id);c.cartridges=c.cartridges.filter(x=>x.id!==id);}}));
cases.push({name:'duplicate-registry',mutate:c=>c.cartridges.push(c.cartridges[0])},{name:'duplicate-order',mutate:c=>c.cartridge_order.push(c.cartridge_order[0])},{name:'order-omission',mutate:c=>c.cartridge_order.pop()},{name:'empty-composition',mutate:c=>{c.cartridges=[];c.cartridge_order=[];}});
const browser=await pw.chromium.launch();
try{for(const fixture of cases){const page=await browser.newPage({viewport:{width:393,height:852}});let shellRequests=0;try{
const altered=structuredClone(current);fixture.mutate(altered);
await page.route(new URL('current.json',base).href,route=>route.fulfill({status:200,contentType:'application/json',body:JSON.stringify(altered)}));
await page.route(current.shell.index,route=>{shellRequests++;return route.continue();});
await page.goto(base,{waitUntil:'domcontentloaded'});
await page.waitForFunction(()=>document.body.dataset.gridatlasRouter==='failed'||window.__GRIDATLAS_ATLAS__,null,{timeout:30000});
const state=await page.evaluate(()=>({failed:document.body.dataset.gridatlasRouter==='failed',message:document.body.innerText,composed:!!window.__GRIDATLAS_ATLAS__}));
record(fixture.name+' refuses the incomplete composition before loading any shell',state.failed&&!state.composed&&shellRequests===0,{...state,shellRequests});
await page.screenshot({path:path.join(out,fixture.name+'.png')});
}finally{await page.close();}}
// An actual saved outline must survive a temporarily bad composition response.
const page=await browser.newPage({viewport:{width:393,height:852}});
try{
await page.goto(base);await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__?.getSource('src-zonedraw-line'));
const scope=page.locator('.gm-title').filter({hasText:/^Scope$/});await scope.click();await page.locator('#btn-zonedraw').click();
const ring=[[1,51],[1.01,51],[1.01,51.01],[1,51.01],[1,51]];
await page.locator('#zonedraw-file').setInputFiles({name:'retained.geojson',mimeType:'application/geo+json',buffer:Buffer.from(JSON.stringify({type:'Polygon',coordinates:[ring]}))});
await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__.getSource('src-zonedraw-line')._data.features[0]?.geometry.coordinates.length===5);
const saved=await page.evaluate(()=>localStorage.getItem('gridatlas.polygon-draft.v1'));
record('Valid composition saves the actual imported outline',JSON.stringify(JSON.parse(saved).points)===JSON.stringify(ring.slice(0,-1)));
const routeUrl=new URL('current.json',base).href,altered=structuredClone(current);altered.cartridges=[];altered.cartridge_order=[];
await page.route(routeUrl,route=>route.fulfill({status:200,contentType:'application/json',body:JSON.stringify(altered)}));
await page.reload();await page.waitForFunction(()=>document.body.dataset.gridatlasRouter==='failed'||window.__GRIDATLAS_ATLAS__);
record('Composition failure preserves the exact saved draft',await page.evaluate(()=>document.body.dataset.gridatlasRouter==='failed')&&await page.evaluate(()=>localStorage.getItem('gridatlas.polygon-draft.v1'))===saved);
await page.unroute(routeUrl);await page.reload();await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__?.getSource('src-zonedraw-line'));
await scope.click();await page.locator('#btn-zonedraw').click();
const restored=await page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.getSource('src-zonedraw-line')._data.features[0]?.geometry.coordinates);
record('Restoring the valid composition recovers every polygon vertex',JSON.stringify(restored)===JSON.stringify(ring));
}finally{await page.close();}
}finally{await browser.close();}
})().catch(e=>{record('Contract review completes',false,e.stack);process.exitCode=1;}).finally(()=>{if(checks.some(c=>!c.pass))process.exitCode=1;});