GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Automation and CI / testcode / sandbox/tools

Poly Zone Browser and 10 more files

A JavaScript module in the tools folder of Testcode that draws small polygon, vertices, broken and crossed. It is built from the separated step (`separated`).

669 lines of JavaScript and Python from testcode, in 11 files. Topic: Automation and CI. Section 1867 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. Poly Zone Browser render · testcode / sandbox/tools/poly-zone.browser.cjs lines 1–260
  2. Polygon Boundaries Browser geodesy · testcode / sandbox/tools/polygon-boundaries.browser.cjs lines 1–44
  3. Polygon Distance Browser geodesy · testcode / sandbox/tools/polygon-distance.browser.cjs lines 1–35
  4. Polygon Remove Browser geodesy · testcode / sandbox/tools/polygon-remove.browser.cjs lines 1–43
  5. Polygon Vertex Limit Browser geodesy · testcode / sandbox/tools/polygon-vertex-limit.browser.cjs lines 1–36
  6. Prepare Layout Publication storage · testcode / sandbox/tools/prepare-layout-publication.py lines 1–24
  7. Print View render · testcode / sandbox/tools/print-view.js lines 1–31
  8. Source Download Browser render · testcode / sandbox/tools/source-download.browser.cjs lines 1–71
  9. Token Compaction other · testcode / sandbox/tools/token-compaction.mjs lines 1–61
  10. Tool Recovery Browser render · testcode / sandbox/tools/tool-recovery.browser.cjs lines 1–41
  11. Verify Composition Guard other · testcode / sandbox/tools/verify-composition-guard.mjs lines 1–23

Poly Zone Browser

A JavaScript module in the tools folder of Testcode that draws small polygon, vertices, broken and crossed. It is built from the separated step (`separated`).

rendertestcode / sandbox/tools/poly-zone.browser.cjs · lines 1–260 of 260 · Entry point · pattern coordinates (shared by 3 files)

What it does
It draws small polygon, vertices, broken and crossed. Defines save, check, coordinates, separated. Uses libraries node:fs, node:path, node:http, node:child_process, C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright. 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.
Inputs & outputs
In: CSV file -vertices.csv; GeoJSON file -polygon.geojson; GeoJSON file broken.geojson; GeoJSON file crossed.geojson; GeoJSON file small-clockwise.geojson; GeoJSON file -small-polygon.geojson. Out: JSON file results.json; GeoJSON file -polygon.geojson.
Downstream impact
Used directly by 9 files: Composition Guard Workflow (testcode); Map PDF Workflow (testcode); Measurement Clearance Workflow (testcode); Measurement Readouts Workflow (testcode); and 5 more.
What it achieves
Defines `save`, `check`, `coordinates` and 1 more.
Why it matters
Run by 9 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, C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright
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 Poly Zone Workflow (workflow run), run by Polygon Distance Workflow (workflow run), run by Tool Recovery Workflow (workflow run), run by Vertex Limit Workflow (workflow run), and 1 more
Produces
save, check, coordinates, separated
Defines here
save, check, coordinates, separated
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/poly-zone.browser.cjs:1-260 · blob ca6b75d2a577ac8da565a2640f445136533cc854 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: experimental · users: none · canonical: unknown
const fs = require('node:fs');
const path = require('node:path');
const http = require('node:http');
const {execFileSync} = require('node:child_process');
let playwright;
try {playwright = require(process.env.PLAYWRIGHT_MODULE || 'playwright');}
catch (error) {
  if (process.env.PLAYWRIGHT_MODULE) throw error;
  playwright = require('C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright');
}
const root = path.resolve(__dirname, '../..');
const generation = process.env.TEST_GENERATION;
if (!/^\d{12}$/.test(generation || '')) throw Error('TEST_GENERATION must identify an immutable candidate');
const output = path.resolve(process.env.TEST_OUTPUT || 'poly-zone-artifacts');
fs.mkdirSync(output, {recursive:true});
const report = {generation, touchInput:process.env.TEST_TOUCH==='1'?'Native touchscreen tap and CDP touch drag on phone':'Mouse interactions in both viewport profiles', profiles:[], sourceMode:'Actual composed files; no request interception or source substitution', limitations:['Chrome phone emulation is not physical-device evidence.','Polygon coordinates and rendered labels are checked independen  … [line shortened here: 408 characters; full line on GitHub]
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=repoPath.startsWith('sandbox/202609051906/')
      ? execFileSync('git',['show','HEAD:'+repoPath],{cwd:root,maxBuffer:64*1024*1024}) : fs.readFileSync(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();}
});
function save(){fs.writeFileSync(path.join(output,'results.json'),JSON.stringify(report,null,2)+'\n');}
(async()=>{
  await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
  const base=process.env.TEST_BASE||`http://127.0.0.1:${server.address().port}/testcode/${generation}/atlas/`;
  report.base=base;
  const engine=process.env.TEST_ENGINE||'chromium';
  if(!['chromium','firefox','webkit'].includes(engine))throw Error('Unknown browser engine');
  if(engine!=='chromium'&&process.env.TEST_TOUCH==='1')throw Error('The touch-drag proof requires Chromium CDP');
  const browser=await playwright[engine].launch({headless:true,...(engine!=='chromium'||process.env.CHROME_CHANNEL==='chromium'?{}:{channel:process.env.CHROME_CHANNEL||'chrome'})});
  report.engine=engine;
  report.browser=browser.version();
  try {
    for(const profile of [{name:'desktop',viewport:{width:1440,height:900}},{name:'phone',viewport:{width:393,height:852},isMobile:true,hasTouch:true}]) {
      const {name,...options}=profile;
      if(engine==='firefox')delete options.isMobile;
      const context=await browser.newContext(options);
      const result={name,errors:[],checks:[]};report.profiles.push(result);
      const check=(label,pass,detail)=>{result.checks.push({name:label,pass:!!pass,detail});save();console.log(name,pass?'PASS':'FAIL',label);};
      try {
        await context.addInitScript(()=>{
          Object.defineProperty(window,'maplibregl',{configurable:true,set(value){
            Object.defineProperty(window,'maplibregl',{configurable:true,writable:true,value});
            value.Map=new Proxy(value.Map,{construct(target,args,newTarget){const map=Reflect.construct(target,args,newTarget);window.__POLY_TEST_MAP__=map;return map;}});
          }});
        });
        const page=await context.newPage();page.on('pageerror',e=>result.errors.push(e.message));
        await page.goto(base,{waitUntil:'domcontentloaded',timeout:60000});
        await page.waitForFunction(()=>window.__POLY_TEST_MAP__?.getSource('src-zonedraw-points')&&document.querySelector('#gridatlas-menu-bar .gm-title'),null,{timeout:60000});
        await page.evaluate(()=>window.__POLY_TEST_MAP__.jumpTo({center:[0.935,51.339],zoom:14}));
        const scope=page.locator('.gm-title').filter({hasText:/^Scope$/});
        await scope.click();await page.locator('#btn-zonedraw').click();
        await page.locator('#zonedraw-radius-input').fill('0.337');
        const canvas=page.locator('#map canvas.maplibregl-canvas');
        if(process.env.TEST_TOUCH==='1'&&name==='phone'){const r=await canvas.boundingBox();await page.touchscreen.tap(r.x+r.width/2,r.y+r.height/2);}else await canvas.click({position:{x:(await canvas.boundingBox()).width/2,y:(await canvas.boundingBox()).height/2}});
        await page.waitForFunction(()=>document.querySelector('.measurement-dock-values')?.textContent.includes('Hectares'),null,{timeout:30000});
        await page.waitForFunction(()=>!window.__POLY_TEST_MAP__.isMoving());
        const coordinates=()=>page.evaluate(()=>window.__POLY_TEST_MAP__.getSource('src-zonedraw-fill')._data.features[0]?.geometry.coordinates);
        const before=await coordinates();
        const separated=()=>page.evaluate(()=>{
          const a=document.querySelector('#map canvas').getBoundingClientRect(),b=document.querySelector('#gridatlas-measurement-dock').getBoundingClientRect();
          return {clear:a.right<=b.left+1||b.right<=a.left+1||a.bottom<=b.top+1||b.bottom<=a.top+1,canvas:{x:a.x,y:a.y,width:a.width,height:a.height},panel:{x:b.x,y:b.y,width:b.width,height:b.height},noHorizontalOverflow:document.documentElement.scrollWidth<=innerWidth};
        });
        const boxes=await separated();check('labels occupy a separate area from drawing canvas',boxes.clear,boxes);check('no page width overflow',boxes.noHorizontalOverflow);
        check('polygon drawn with 24 editable vertices',before?.[0]?.length===25);
        await page.screenshot({path:path.join(output,name+'-labels.png')});
        if(process.env.TEST_KEYBOARD==='1'){
          const collapse=page.getByRole('button',{name:'Collapse polygon measurements'});
          check('measurement collapse is a native named button',await collapse.count()===1);
          await collapse.focus();await page.keyboard.press('Enter');
          check('Enter collapses labels and preserves keyboard focus',await page.getByRole('button',{name:'Expand polygon measurements'}).evaluate(e=>e===document.activeElement&&e.getAttribute('aria-expanded')==='false'));
        }else await page.locator('#gridatlas-measurement-dock [title="Collapse"]').click();
        check('collapsing labels preserves exact geometry',JSON.stringify(await coordinates())===JSON.stringify(before));
        if(process.env.TEST_KEYBOARD==='1'){
          await page.keyboard.press('Space');
          check('Space expands labels and preserves keyboard focus',await page.getByRole('button',{name:'Collapse polygon measurements'}).evaluate(e=>e===document.activeElement&&e.getAttribute('aria-expanded')==='true'));
          check('measurement buttons have at least 44 pixel targets',await page.locator('#gridatlas-measurement-dock button').evaluateAll(buttons=>buttons.filter(button=>button.getBoundingClientRect().height).every(button=>button.getBoundingClientRect().height>=44)));
          check('Undo guidance describes edit history',(await page.locator('.measurement-dock-values').innerText()).includes('restores the previous edit'));
        }else await page.locator('.measurement-dock-values>div,.measurement-dock-values>button').click();
        check('expanding labels preserves exact geometry',JSON.stringify(await coordinates())===JSON.stringify(before));
        const vertex=await page.evaluate(()=>{
          const map=window.__POLY_TEST_MAP__,f=map.getSource('src-zonedraw-points')._data.features.find(f=>f.properties.kind==='vertex');
          const p=map.project(f.geometry.coordinates),r=map.getCanvas().getBoundingClientRect();return{x:p.x+r.left,y:p.y+r.top};
        });
        if(process.env.TEST_TOUCH==='1'&&name==='phone'){
          const cdp=await context.newCDPSession(page);
          await cdp.send('Input.dispatchTouchEvent',{type:'touchStart',touchPoints:[{x:vertex.x,y:vertex.y,id:1}]});
          for(let step=1;step<=5;step++)await cdp.send('Input.dispatchTouchEvent',{type:'touchMove',touchPoints:[{x:vertex.x+24*step/5,y:vertex.y+16*step/5,id:1}]});
          await cdp.send('Input.dispatchTouchEvent',{type:'touchEnd',touchPoints:[]});await cdp.detach();
        }else {await page.mouse.move(vertex.x,vertex.y);await page.mouse.down();await page.mouse.move(vertex.x+24,vertex.y+16,{steps:5});await page.mouse.up();}
        const afterDrag=await coordinates();check('corner drag edits the existing polygon',JSON.stringify(afterDrag)!==JSON.stringify(before)&&afterDrag[0].length===25);
        if(process.env.TEST_HISTORY==='1') {
          await page.locator('#btn-zonedraw-undo').click();
          check('Undo restores the whole outline before the drag',JSON.stringify(await coordinates())===JSON.stringify(before));
          await page.locator('#btn-zonedraw-redo').click();
          check('Redo restores the exact edited outline',JSON.stringify(await coordinates())===JSON.stringify(afterDrag));
          await page.locator('#btn-zonedraw-reset').click();
          await page.locator('#btn-zonedraw-undo').click();
          check('Undo recovers a deliberately reset polygon',JSON.stringify(await coordinates())===JSON.stringify(afterDrag));
          await page.locator('#btn-zonedraw-redo').click();
          check('Redo can repeat the reset',!(await coordinates()));
          await page.locator('#btn-zonedraw-undo').click();
        }
        if(process.env.TEST_LOCK==='1') {
          const held=await coordinates();
          const point=await page.evaluate(()=>{const m=window.__POLY_TEST_MAP__,p=m.project(m.getSource('src-zonedraw-fill')._data.features[0].geometry.coordinates[0][0]),r=m.getCanvas().getBoundingClientRect();return{x:p.x+r.left,y:p.y+r.top};});
          await page.locator('#btn-zonedraw-lock').click();
          check('lock hides vertex edit handles',await page.evaluate(()=>window.__POLY_TEST_MAP__.getSource('src-zonedraw-points')._data.features.length===0));
          const center=await page.evaluate(()=>window.__POLY_TEST_MAP__.getCenter().toArray());
          await page.mouse.move(point.x,point.y);await page.mouse.down();await page.mouse.move(point.x+35,point.y+20,{steps:5});await page.mouse.up();
          check('locked vertex drag leaves every coordinate intact',JSON.stringify(await coordinates())===JSON.stringify(held));
          check('locked polygon still allows map pan',JSON.stringify(await page.evaluate(()=>window.__POLY_TEST_MAP__.getCenter().toArray()))!==JSON.stringify(center));
          await page.locator('#btn-zonedraw-lock').click();
          check('unlock restores editable corner handles',await page.evaluate(()=>window.__POLY_TEST_MAP__.getSource('src-zonedraw-points')._data.features.some(f=>f.properties.kind==='vertex')));
        }
        if(process.env.TEST_FIT==='1') {
          const held=await coordinates();await page.locator('#btn-zonedraw-lock').click();
          const r=await canvas.boundingBox();await page.mouse.move(r.x+r.width*.6,r.y+r.height*.6);await page.mouse.down();await page.mouse.move(r.x+r.width*.1,r.y+r.height*.2,{steps:10});await page.mouse.up();
          await page.locator('#btn-zonedraw-fit').click();await page.waitForFunction(()=>!window.__POLY_TEST_MAP__.isMoving());
          const fitted=await page.evaluate(()=>{const m=window.__POLY_TEST_MAP__,r=m.getCanvas().getBoundingClientRect();return m.getSource('src-zonedraw-fill')._data.features[0].geometry.coordinates[0].every(c=>{const p=m.project(c);return p.x>=0&&p.x<=r.width&&p.y>=0&&p.y<=r.height;});});
          check('Fit polygon returns every vertex to the visible canvas',fitted);
          check('Fit polygon preserves exact coordinates and lock state',JSON.stringify(await coordinates())===JSON.stringify(held)&&await page.locator('#btn-zonedraw-lock').getAttribute('aria-pressed')==='true');
          await page.locator('#btn-zonedraw-lock').click();
        }
        if(process.env.TEST_RESET==='1') {
          const r=await canvas.boundingBox();await canvas.click({position:{x:r.width*.1,y:r.height*.75}});
          check('ordinary map click keeps edited polygon',JSON.stringify(await coordinates())===JSON.stringify(afterDrag));
          await page.locator('#btn-zonedraw-reset').click();
          check('explicit reset clears only the polygon',!(await coordinates()));
          await canvas.click({position:{x:r.width*.6,y:r.height*.5}});
          await page.waitForFunction(()=>window.__POLY_TEST_MAP__.getSource('src-zonedraw-fill')._data.features.length===1);
          check('new circle starts only after explicit reset',(await coordinates())[0].length===25);
        }
        await scope.click();await page.locator('#btn-radius-area').click();
        if(process.env.TEST_RESET==='1')check('changing tools preserves the drawn polygon',(await coordinates())?.[0]?.length===25);
        const areaCanvas=await canvas.boundingBox();await canvas.click({position:{x:areaCanvas.width/2,y:areaCanvas.height/2}});
        await page.waitForFunction(()=>document.querySelector('.measurement-dock-values')?.textContent.includes('Hectares'),null,{timeout:15000});
        check('circle measurements stay outside canvas',(await separated()).clear);
        const circle=await page.evaluate(()=>window.__POLY_TEST_MAP__.getSource('src-radius-area')._data.features);
        check('circle remains mapped',circle.length===1);
        await page.screenshot({path:path.join(output,name+'-circle.png')});
        await scope.click();await page.locator('#btn-radius-area').click();
        check('leaving measurement mode restores map layout',await page.locator('#gridatlas-measurement-dock').count()===0);
        if(process.env.TEST_RESET==='1') {
          const held=await coordinates();await scope.click();await page.locator('#btn-zonedraw').click();
          check('returning to Poly Zone restores its exact outline',JSON.stringify(await coordinates())===JSON.stringify(held));
        }
        if(process.env.TEST_EXPORT==='1') {
          const held=await coordinates();
          const pending=page.waitForEvent('download');await page.locator('#btn-zonedraw-export').click();
          const download=await pending;const file=path.join(output,name+'-polygon.geojson');await download.saveAs(file);
          const data=JSON.parse(fs.readFileSync(file,'utf8')),feature=data.features?.[0],ring=feature?.geometry?.coordinates?.[0];
          check('download is a single attributed GeoJSON polygon',data.type==='FeatureCollection'&&data.features.length===1&&feature.geometry.type==='Polygon'&&feature.properties.source==='User-drawn outline');
          check('download preserves every edited vertex and closes the ring',ring?.length===held[0].length&&JSON.stringify(ring[0])===JSON.stringify(ring.at(-1))&&ring.every(p=>held[0].some(q=>JSON.stringify(p)===JSON.stringify(q))));
          check('download contains positive area and perimeter in named units',feature.properties.area_m2>0&&feature.properties.perimeter_km>0);
          check('export leaves the working polygon untouched',JSON.stringify(await coordinates())===JSON.stringify(held));
        }
        if(process.env.TEST_CSV==='1') {
          const held=await coordinates(),pending=page.waitForEvent('download');await page.locator('#btn-zonedraw-csv').click();
          const file=path.join(output,name+'-vertices.csv');await(await pending).saveAs(file);const lines=fs.readFileSync(file,'utf8').trim().split(/\r?\n/),rows=lines.slice(1).map(line=>line.split(',').map(Number));
          check('CSV names coordinate and distance units explicitly',lines[0]==='vertex,longitude_deg,latitude_deg,chainage_m,next_segment_m');
          check('CSV preserves every vertex in drawn order',rows.length===held[0].length-1&&rows.every((row,i)=>row[0]===i+1&&row[1]===held[0][i][0]&&row[2]===held[0][i][1]));
          const geo=JSON.parse(fs.readFileSync(path.join(output,name+'-polygon.geojson'),'utf8'));let total=0;const chainage=rows.every(row=>{const correct=Math.abs(row[3]-total)<1e-8;total+=row[4];return correct;});
          check('CSV chainage includes the closing segment and matches exported perimeter',chainage&&Math.abs(total-geo.features[0].properties.perimeter_km*1000)<1e-7);
          check('CSV download keeps the working outline unchanged',JSON.stringify(await coordinates())===JSON.stringify(held));
        }
        if(process.env.TEST_IMPORT==='1') {
          const file=path.join(output,name+'-polygon.geojson');
          const saved=JSON.parse(fs.readFileSync(file,'utf8')).features[0].geometry.coordinates;
          await page.locator('#btn-zonedraw-reset').click();
          await page.locator('#zonedraw-file').setInputFiles(file);
          await page.waitForFunction(()=>document.querySelector('#zonedraw-storage-status')?.textContent.startsWith('Opened'));
          check('opening the downloaded file restores its exact ring',JSON.stringify(await coordinates())===JSON.stringify(saved));
          const held=await coordinates();
          if(process.env.TEST_REDRAW==='1')await page.waitForFunction(()=>!window.__POLY_TEST_MAP__.isMoving());
          await page.locator('#zonedraw-file').setInputFiles({name:'broken.geojson',mimeType:'application/geo+json',buffer:Buffer.from('{broken')});
          await page.waitForFunction(()=>document.querySelector('#zonedraw-storage-status')?.textContent.includes('not valid JSON'));
          check('invalid import keeps the entire existing outline',JSON.stringify(await coordinates())===JSON.stringify(held));
          if(process.env.TEST_REDRAW==='1'){
            await page.evaluate(()=>{const m=window.__POLY_TEST_MAP__;m.zoomTo(m.getZoom()+.1,{duration:200});});await page.waitForFunction(()=>!window.__POLY_TEST_MAP__.isMoving());
            check('map redraw preserves invalid-import feedback',(await page.locator('#zonedraw-storage-status').innerText()).includes('not valid JSON'));
          }

          const chooser=page.waitForEvent('filechooser');await page.locator('#btn-zonedraw-import').click();
          check('Open GeoJSON launches the native file chooser',!!(await chooser));
        }
        if(process.env.TEST_COORDINATE==='1') {
          const held=await coordinates();await page.locator('#zonedraw-coordinate-editor summary').click();
          await page.selectOption('#zonedraw-vertex','1');
          check('coordinate editor loads the selected exact vertex',Number(await page.locator('#zonedraw-longitude').inputValue())===held[0][1][0]&&Number(await page.locator('#zonedraw-latitude').inputValue())===held[0][1][1]);
          const changed=held[0][1][0]+.0001;await page.locator('#zonedraw-longitude').fill(String(changed));
          if(process.env.TEST_REDRAW==='1'){
            await page.evaluate(()=>{const m=window.__POLY_TEST_MAP__;m.zoomTo(m.getZoom()+.1,{duration:200});});await page.waitForFunction(()=>!window.__POLY_TEST_MAP__.isMoving());
            check('zoom finishing does not overwrite an unsaved coordinate',Number(await page.locator('#zonedraw-longitude').inputValue())===changed);
          }
          await page.locator('#btn-zonedraw-coordinate').click();
          const edited=await coordinates();check('numeric edit changes only the selected vertex',edited[0][1][0]===changed&&edited[0][1][1]===held[0][1][1]&&edited[0].every((p,i)=>i===1||JSON.stringify(p)===JSON.stringify(held[0][i])));
          await page.locator('#btn-zonedraw-undo').click();check('Undo restores exact pre-coordinate outline',JSON.stringify(await coordinates())===JSON.stringify(held));
          await page.locator('#zonedraw-longitude').fill('181');await page.locator('#btn-zonedraw-coordinate').click();
          check('out-of-range coordinate is rejected without mutation',JSON.stringify(await coordinates())===JSON.stringify(held)&&(await page.locator('#zonedraw-storage-status').innerText()).includes('has not changed'));
          await page.locator('#zonedraw-longitude').fill('');await page.locator('#btn-zonedraw-coordinate').click();check('blank coordinate is not converted to zero',JSON.stringify(await coordinates())===JSON.stringify(held));
          await page.locator('#btn-zonedraw-lock').click();check('polygon lock disables numeric edits',await page.locator('#btn-zonedraw-coordinate').isDisabled()&&await page.locator('#zonedraw-longitude').isDisabled());await page.locator('#btn-zonedraw-lock').click();
          await page.locator('#zonedraw-coordinate-editor summary').click();
        }
        if(process.env.TEST_VALIDITY==='1') {
          const held=await coordinates(),ring=[[.93,51.33],[.94,51.34],[.93,51.34],[.94,51.33],[.93,51.33]];
          await page.locator('#zonedraw-file').setInputFiles({name:'crossed.geojson',mimeType:'application/geo+json',buffer:Buffer.from(JSON.stringify({type:'Polygon',coordinates:[ring]}))});
          await page.locator('#zonedraw-validity-warning').waitFor({state:'visible'});
          check('crossed outline withholds area and GeoJSON',!(await coordinates())&&await page.locator('#btn-zonedraw-export').isDisabled()&&(await page.locator('.measurement-dock-values').innerText()).includes('Area not assessed'));
          const boundary=await page.evaluate(()=>window.__POLY_TEST_MAP__.getSource('src-zonedraw-line')._data.features[0].geometry.coordinates);
          check('crossed outline remains exactly drawn and editable',JSON.stringify(boundary)===JSON.stringify(ring)&&await page.evaluate(()=>window.__POLY_TEST_MAP__.getSource('src-zonedraw-points')._data.features.filter(f=>f.properties.kind==='vertex').length===4));
          check('validity warning remains outside the drawing canvas',(await separated()).clear);
          await page.locator('#btn-zonedraw-undo').click();
          check('Undo repairs the boundary and restores area and export',JSON.stringify(await coordinates())===JSON.stringify(held)&&await page.locator('#zonedraw-validity-warning').count()===0&&!(await page.locator('#btn-zonedraw-export').isDisabled()));
        }
        if(process.env.TEST_DRAFT==='1') {
          const held=await coordinates();
          await page.reload({waitUntil:'domcontentloaded'});
          await page.waitForFunction(()=>window.__POLY_TEST_MAP__?.getSource('src-zonedraw-points')&&document.querySelector('#gridatlas-menu-bar .gm-title'),null,{timeout:60000});
          await scope.click();await page.locator('#btn-zonedraw').click();
          check('reload restores every edited coordinate',JSON.stringify(await coordinates())===JSON.stringify(held));
          check('restoration is disclosed in controls',(await page.locator('#zonedraw-storage-status').innerText()).includes('Restored'));
          await page.locator('#btn-zonedraw-reset').click();
          await page.reload({waitUntil:'domcontentloaded'});
          await page.waitForFunction(()=>window.__POLY_TEST_MAP__?.getSource('src-zonedraw-points')&&document.querySelector('#gridatlas-menu-bar .gm-title'),null,{timeout:60000});
          await scope.click();await page.locator('#btn-zonedraw').click();
          check('reset remains cleared after reload',!(await coordinates()));
          await page.evaluate(()=>{Storage.prototype.setItem=function(){throw Error('Test storage denied');};});
          const r=await canvas.boundingBox();await canvas.click({position:{x:r.width/2,y:r.height/2}});
          check('storage denial keeps drawn geometry',(await coordinates())?.[0]?.length===25);
          check('storage denial has an honest status',(await page.locator('#zonedraw-storage-status').innerText()).includes('unavailable'));
        }
        if(process.env.TEST_WINDING==='1'){
          const x=179,y=85,d=1e-8,ring=[[x,y],[x,y+d],[x+d,y+d],[x+d,y],[x,y]];
          await page.locator('#zonedraw-file').setInputFiles({name:'small-clockwise.geojson',mimeType:'application/geo+json',buffer:Buffer.from(JSON.stringify({type:'Polygon',coordinates:[ring]}))});
          await page.waitForFunction(()=>window.__POLY_TEST_MAP__.getSource('src-zonedraw-fill')._data.features[0]?.geometry.coordinates[0].length===5);
          const pending=page.waitForEvent('download');await page.locator('#btn-zonedraw-export').click();const download=await pending;
          const file=path.join(output,name+'-small-polygon.geojson');await download.saveAs(file);
          const exported=JSON.parse(fs.readFileSync(file,'utf8')).features[0].geometry.coordinates[0],a=exported[0],b=exported[1],c=exported[2];
          check('small clockwise boundary exports counterclockwise',(b[0]-a[0])*(c[1]-a[1])-(b[1]-a[1])*(c[0]-a[0])>0);
          check('precision correction retains every original coordinate',JSON.stringify(exported.slice(0,-1).map(p=>JSON.stringify(p)).sort())===JSON.stringify(ring.slice(0,-1).map(p=>JSON.stringify(p)).sort()));
        }
        check('no uncaught script errors',result.errors.length===0,result.errors);
        result.pass=result.checks.every(c=>c.pass);
      }catch(error){result.error=error.stack;result.pass=false;console.log(name,error.message);}
      finally{await context.close();save();}
    }
  }finally{await browser.close();}
})().catch(error=>{report.error=error.stack;process.exitCode=1;}).finally(()=>{
  report.finishedUTC=new Date().toISOString();save();server.close();
  if(report.profiles.length!==2||report.profiles.some(p=>!p.pass))process.exitCode=1;
});

Polygon Boundaries Browser

A JavaScript module in the tools folder of Testcode that reads boundary and rectangle, using haversine. It is built from the vector step (`vector`) and the distance step (`distance`).

geodesytestcode / sandbox/tools/polygon-boundaries.browser.cjs · lines 1–44 of 44 · Entry point · pattern vector (shared by 5 files)

What it does
It loads boundary and rectangle. Defines check, coords, input, vector, distance. 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.
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: GeoJSON file boundary.geojson; command-line arguments. Out: GeoJSON file -rectangle.geojson; JSON file results.json.
Downstream impact
Used directly by 1 file: Tool Recovery Workflow (testcode).
What it achieves
Defines `check`, `coords`, `input` and 2 more.
Why it matters
Run by Tool Recovery 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 Tool Recovery Workflow (workflow run)
Produces
check, coords, input, vector, distance
Defines here
check, coords, input, vector, distance
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/polygon-boundaries.browser.cjs:1-44 · blob 309ceb5c51f1135705cce71de16214c868147e68 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · 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||'polygon-boundaries-artifacts');fs.mkdirSync(out,{recursive:true});
const reports=[];
(async()=>{const browser=await pw.chromium.launch();
 try{for(const viewport of [{width:393,height:852},{width:1440,height:900}]){
  const context=await browser.newContext({viewport}),page=await context.newPage(),report={viewport,checks:[],errors:[]};reports.push(report);
  const check=(name,pass,detail)=>{report.checks.push({name,pass:!!pass,detail});console.log(pass?'PASS':'FAIL',viewport.width,name);};
  page.on('pageerror',error=>report.errors.push(error.message));
  try{
   await page.goto(base,{waitUntil:'domcontentloaded'});await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__?.getSource('src-zonedraw-points'));
   await page.locator('.gm-title').filter({hasText:/^Scope$/}).click();await page.locator('#btn-zonedraw').click();
   const coords=()=>page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.getSource('src-zonedraw-fill')._data.features[0]?.geometry.coordinates[0]);
   const input=ring=>page.locator('#zonedraw-file').setInputFiles({name:'boundary.geojson',mimeType:'application/geo+json',buffer:Buffer.from(JSON.stringify({type:'Polygon',coordinates:[ring]}))});
   const rectangle=[[1,51],[1.01,51],[1.01,51.01],[1,51.01],[1,51]];await input(rectangle);
   await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__.getSource('src-zonedraw-fill')._data.features.length===1);
   const pending=page.waitForEvent('download');await page.locator('#btn-zonedraw-export').click();const download=await pending,file=path.join(out,viewport.width+'-rectangle.geojson');await download.saveAs(file);
   const feature=JSON.parse(fs.readFileSync(file,'utf8')).features[0],R=6378.137,rad=Math.PI/180;
   const area=R*R*(rectangle[1][0]-rectangle[0][0])*rad*(Math.sin(51.01*rad)-Math.sin(51*rad))*1e6;
   // Independent central angle from 3D unit-vector cross/dot, not haversine.
   const vector=([x,y])=>[Math.cos(y*rad)*Math.cos(x*rad),Math.cos(y*rad)*Math.sin(x*rad),Math.sin(y*rad)];
   const distance=(a,b)=>{a=vector(a);b=vector(b);const cross=[a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0]];return R*Math.atan2(Math.hypot(...cross),a.reduce((s,v,i)=>s+v*b[i],0));};
   const perimeter=rectangle.slice(0,-1).reduce((sum,p,i)=>sum+distance(p,rectangle[i+1]),0);
   check('Downloaded spherical rectangle area matches independent strip integral',Math.abs(feature.properties.area_m2-area)<area*1e-8,{actual:feature.properties.area_m2,expected:area});
   check('Downloaded hectares retain exact metric conversion',feature.properties.area_ha===feature.properties.area_m2/10000);
   check('Downloaded perimeter matches independent vector central angles',Math.abs(feature.properties.perimeter_km-perimeter)<1e-8,{actual:feature.properties.perimeter_km,expected:perimeter});
   const ring=Array.from({length:4096},(_,i)=>[1+.01*Math.cos(2*Math.PI*i/4096),51+.01*Math.sin(2*Math.PI*i/4096)]);ring.push(ring[0].slice());
   const start=Date.now();await input(ring);await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__.getSource('src-zonedraw-fill')._data.features[0]?.geometry.coordinates[0].length===4097);
   await page.waitForFunction(()=>!window.__GRIDATLAS_V9_MAP__.isMoving()&&window.__GRIDATLAS_V9_MAP__.isSourceLoaded('src-zonedraw-fill'));
   report.maximumImportMilliseconds=Date.now()-start;
   check('Maximum4096 vertices survive the actual import and map render',JSON.stringify(await coords())===JSON.stringify(ring),{milliseconds:report.maximumImportMilliseconds});
   await page.setViewportSize({width:viewport.height,height:viewport.width});
   await page.locator('#btn-zonedraw-fit').click();await page.waitForFunction(()=>!window.__GRIDATLAS_V9_MAP__.isMoving());
   check('Orientation change and Fit retain all4096 vertices',JSON.stringify(await coords())===JSON.stringify(ring));
   const tooMany=ring.slice(0,-1);tooMany.push([1.02,51.02]);tooMany.push(tooMany[0]);await input(tooMany);
   check('4097-vertex input is rejected without replacing the working polygon',JSON.stringify(await coords())===JSON.stringify(ring)&&(await page.locator('#zonedraw-storage-status').innerText()).includes('4096'));
   await page.reload({waitUntil:'domcontentloaded'});await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__?.getSource('src-zonedraw-points'));
   await page.locator('.gm-title').filter({hasText:/^Scope$/}).click();await page.locator('#btn-zonedraw').click();
   check('Reload restores the complete maximum-sized draft',JSON.stringify(await coords())===JSON.stringify(ring));
   check('Boundary cases cause no script errors',report.errors.length===0,report.errors);
  }catch(error){report.error=error.stack;check('Boundary review completes',false,error.message);}
  finally{await context.close();}
 }}finally{await browser.close();}
})().catch(error=>{reports.push({error:error.stack});process.exitCode=1;}).finally(()=>{fs.writeFileSync(path.join(out,'results.json'),JSON.stringify({base,reports},null,2)+'\n');if(reports.some(r=>r.error||r.checks?.some(c=>!c.pass)))process.exitCode=1;});

Polygon Distance Browser

A JavaScript module in the tools folder of Testcode that calculates great-circle distances and planar distances.

geodesytestcode / sandbox/tools/polygon-distance.browser.cjs · lines 1–35 of 35 · Entry point · pattern vector (shared by 5 files)

What it does
It loads data. Defines vector, distance, download. 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.
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: command-line arguments. Out: JSON file results.json.
Downstream impact
Used directly by 2 files: Measurement Readouts Workflow (testcode); Polygon Distance Workflow (testcode).
What it achieves
Defines `vector`, `distance` and `download`.
Why it matters
Run by 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 Measurement Readouts Workflow (workflow run), run by Polygon Distance Workflow (workflow run)
Produces
vector, distance, download
Defines here
vector, distance, download
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/polygon-distance.browser.cjs:1-35 · blob 830f1db198a666fb1a2368d2c992b78b9a98bd96 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · 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||'polygon-distance-artifacts');fs.mkdirSync(out,{recursive:true});
const reports=[],rad=Math.PI/180,R=6378.137;
const vector=([lon,lat])=>[Math.cos(lat*rad)*Math.cos(lon*rad),Math.cos(lat*rad)*Math.sin(lon*rad),Math.sin(lat*rad)];
function distance(a,b){a=vector(a);b=vector(b);return R*Math.atan2(Math.hypot(a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0]),a.reduce((sum,v,i)=>sum+v*b[i],0));}
const fixtures=[
 ['ordinary-site',[[1,51],[1.01,51],[1.01,51.01],[1,51.01]]],
 ['antipodal-first',[[0,-84.99],[180,84.99],[0,84.99]]],
 ['antipodal-closing',[[180,84.99],[0,84.99],[0,-84.99]]],
 ['near-antipodal',[[0,-84.99],[179.999999,84.989999],[0,84.99]]],
 ['southern-site',[[20,-51],[20.01,-51],[20.01,-51.01],[20,-51.01]]]
];
(async()=>{const browser=await pw.chromium.launch();try{
 const page=await browser.newPage({viewport:{width:1440,height:900}}),errors=[];page.on('pageerror',e=>errors.push(e.message));
 await page.goto(base);await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__?.getSource('src-zonedraw-points'));
 await page.locator('.gm-title').filter({hasText:/^Scope$/}).click();await page.locator('#btn-zonedraw').click();await page.keyboard.press('Escape');
 for(const [name,points] of fixtures){
  const r={name,checks:[]};reports.push(r);const check=(name,pass,detail)=>{r.checks.push({name,pass:!!pass,detail});console.log(pass?'PASS':'FAIL',r.name,name);};
  const ring=[...points,points[0]];
  await page.locator('#zonedraw-file').setInputFiles({name:name+'.geojson',mimeType:'application/geo+json',buffer:Buffer.from(JSON.stringify({type:'Polygon',coordinates:[ring]}))});
  await page.waitForFunction(()=>!window.__GRIDATLAS_V9_MAP__.isMoving());
  const download=async(id,extension)=>{const pending=page.waitForEvent('download');await page.locator(id).click();const file=path.join(out,name+extension);await(await pending).saveAs(file);return fs.readFileSync(file,'utf8');};
  const feature=JSON.parse(await download('#btn-zonedraw-export','.geojson')).features[0];
  const rows=(await download('#btn-zonedraw-csv','.csv')).trim().split(/\r?\n/).slice(1).map(line=>line.split(',').map(Number));
  const segments=points.map((p,i)=>distance(p,points[(i+1)%points.length]));
  const expected=segments.reduce((a,b)=>a+b,0),tolerance=name.includes('antipodal')?.001:1e-7;
  check('GeoJSON perimeter is finite and agrees with independent vector angles',Number.isFinite(feature.properties.perimeter_km)&&Math.abs(feature.properties.perimeter_km-expected)<tolerance,{actual:feature.properties.perimeter_km,expected,toleranceKm:tolerance});
  check('Every CSV distance and chainage is finite',rows.every(row=>row.every(Number.isFinite)),rows);
  check('CSV segments agree with independent vector angles',rows.length===points.length&&rows.every((row,i)=>Math.abs(row[4]/1000-segments[i])<tolerance));
  check('CSV closing chainage agrees with GeoJSON perimeter',Math.abs((rows.at(-1)[3]+rows.at(-1)[4])/1000-feature.properties.perimeter_km)<1e-7);
  check('Export preserves exact input coordinates',JSON.stringify(feature.geometry.coordinates[0])===JSON.stringify(ring)||JSON.stringify(feature.geometry.coordinates[0])===JSON.stringify([...points].reverse().concat([points.at(-1)])));
 }
 reports.push({name:'runtime',checks:[{name:'No script errors',pass:errors.length===0,detail:errors}]});
}finally{await browser.close();}})().catch(e=>{reports.push({error:e.stack});process.exitCode=1;}).finally(()=>{fs.writeFileSync(path.join(out,'results.json'),JSON.stringify({base,reports},null,2));if(reports.some(r=>r.error||r.checks?.some(c=>!c.pass)))process.exitCode=1;});

Polygon Remove Browser

A JavaScript module in the tools folder of Testcode covering vertices. It is built from the coords step (`coords`).

geodesytestcode / sandbox/tools/polygon-remove.browser.cjs · lines 1–43 of 43 · Entry point · pattern coords (shared by 6 files)

What it does
It lists and searches vertices. Defines check, activate, input, coords. 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.
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: GeoJSON file vertices.geojson; command-line arguments. Out: JSON file results.json.
Downstream impact
Used directly by 6 files: Composition Guard Workflow (testcode); Measurement Clearance Workflow (testcode); Measurement Readouts Workflow (testcode); Polygon Distance Workflow (testcode); and 2 more.
What it achieves
Defines `check`, `activate`, `input` and 1 more.
Why it matters
Run by 6 workflows and scripts, including Composition Guard Workflow, Measurement Clearance Workflow and Measurement Readouts 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 Clearance Workflow (workflow run), run by Measurement Readouts Workflow (workflow run), run by Polygon Distance Workflow (workflow run), run by Vertex Limit Workflow (workflow run), run by Vertex Removal Workflow (workflow run)
Produces
check, activate, input, coords
Defines here
check, activate, input, coords
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/polygon-remove.browser.cjs:1-43 · blob 3e126f77b62e3435af042fbe5f51fb8ab7c13544 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · 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||'polygon-remove-artifacts');fs.mkdirSync(out,{recursive:true});const reports=[];
(async()=>{const browser=await pw.chromium.launch();
 try{for(const viewport of [{width:393,height:852},{width:1440,height:900}]){
  const phone=viewport.width<700,context=await browser.newContext({viewport,isMobile:phone,hasTouch:phone}),page=await context.newPage(),r={viewport,checks:[],errors:[]};reports.push(r);
  const check=(name,pass,detail)=>{r.checks.push({name,pass:!!pass,detail});console.log(pass?'PASS':'FAIL',viewport.width,name);};
  page.on('pageerror',e=>r.errors.push(e.message));
  const activate=locator=>phone?locator.tap():locator.click();
  try{
   await page.goto(base,{waitUntil:'domcontentloaded'});await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__?.getSource('src-zonedraw-line'));
   await activate(page.locator('.gm-title').filter({hasText:/^Scope$/}));await activate(page.locator('#btn-zonedraw'));
   const ring=[[1,51],[1.01,51],[1.01,51.01],[1,51.01],[1,51]];
   const input=points=>page.locator('#zonedraw-file').setInputFiles({name:'vertices.geojson',mimeType:'application/geo+json',buffer:Buffer.from(JSON.stringify({type:'Polygon',coordinates:[points]}))});
   const coords=()=>page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.getSource('src-zonedraw-line')._data.features[0]?.geometry.coordinates.slice(0,-1));
   await input(ring);await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__.getSource('src-zonedraw-line')._data.features[0]?.geometry.coordinates.length===5);
   await activate(page.locator('#zonedraw-coordinate-editor summary'));
   const remove=page.getByRole('button',{name:'Remove selected vertex',exact:true});await remove.waitFor({state:'visible',timeout:10000});
   const original=await coords();await page.locator('#zonedraw-vertex').selectOption('1');await activate(remove);
   const expected=original.filter((_,i)=>i!==1);check('Removal changes only the selected vertex',JSON.stringify(await coords())===JSON.stringify(expected));
   check('A triangle cannot lose another vertex',await remove.isDisabled());
   await activate(page.locator('#btn-zonedraw-undo'));check('Undo restores the exact four-vertex outline',JSON.stringify(await coords())===JSON.stringify(original));
   await activate(page.locator('#btn-zonedraw-redo'));check('Redo repeats the exact removal',JSON.stringify(await coords())===JSON.stringify(expected));
   await activate(page.locator('#btn-zonedraw-undo'));await activate(page.locator('#btn-zonedraw-lock'));check('Locked outline disables vertex removal',await remove.isDisabled());
   await activate(page.locator('#btn-zonedraw-lock'));await page.locator('#zonedraw-vertex').selectOption('3');await activate(remove);
   check('Removing the last vertex keeps its neighbours unchanged',JSON.stringify(await coords())===JSON.stringify(original.slice(0,3)));
   check('Vertex selection remains in range after removal',(await page.locator('#zonedraw-vertex').inputValue())==='2');
   const repeated=[ring[0],ring[1],ring[1],ring[2],ring[3],ring[0]];await input(repeated);
   await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__.getSource('src-zonedraw-line')._data.features[0]?.geometry.coordinates.length===6);
   check('Coincident vertex preserves the invalid boundary for repair',await page.locator('#btn-zonedraw-export').isDisabled());
   await page.locator('#zonedraw-vertex').selectOption('2');await activate(remove);
   check('Removing the duplicate repairs the exact original boundary',JSON.stringify(await coords())===JSON.stringify(original));
   check('Repair restores assessed area and GeoJSON export',await page.locator('#btn-zonedraw-export').isEnabled()&&await page.locator('#zonedraw-validity-warning').count()===0);
   await activate(page.locator('#btn-zonedraw-undo'));check('Undo can restore the invalid boundary without discarding it',JSON.stringify(await coords())===JSON.stringify(repeated.slice(0,-1))&&await page.locator('#btn-zonedraw-export').isDisabled());
   await activate(page.locator('#btn-zonedraw-redo'));await page.reload();await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__?.getSource('src-zonedraw-line')&&document.querySelector('#btn-zonedraw'));
   await activate(page.locator('.gm-title').filter({hasText:/^Scope$/}));await activate(page.locator('#btn-zonedraw'));
   check('Reload retains the repaired outline exactly',JSON.stringify(await coords())===JSON.stringify(original));
   check('Removal causes no script errors',r.errors.length===0,r.errors);
   await page.screenshot({path:path.join(out,viewport.width+'-repaired.png')});
  }catch(e){r.error=e.stack;check('Vertex removal completes',false,e.message);await page.screenshot({path:path.join(out,viewport.width+'-failure.png')}).catch(()=>{});}
  finally{await context.close();}
 }}finally{await browser.close();}
})().catch(e=>{reports.push({error:e.stack});process.exitCode=1;}).finally(()=>{fs.writeFileSync(path.join(out,'results.json'),JSON.stringify({base,reports},null,2));if(reports.some(r=>r.error||r.checks?.some(c=>!c.pass)))process.exitCode=1;});

Polygon Vertex Limit Browser

A JavaScript module in the tools folder of Testcode that reads maximum.

geodesytestcode / sandbox/tools/polygon-vertex-limit.browser.cjs · lines 1–36 of 36 · Entry point · pattern coords (shared by 6 files)

What it does
It loads maximum. Defines check, activate, coords. 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; 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: GeoJSON file maximum.geojson; browser storage (getItem); command-line arguments. Out: JSON file results.json.
Downstream impact
Used directly by 3 files: Measurement Readouts Workflow (testcode); Polygon Distance Workflow (testcode); Vertex Limit Workflow (testcode).
What it achieves
Defines `check`, `activate` and `coords`.
Why it matters
Run by Measurement Readouts Workflow, Polygon Distance Workflow and Vertex Limit 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 Measurement Readouts Workflow (workflow run), run by Polygon Distance Workflow (workflow run), run by Vertex Limit Workflow (workflow run)
Produces
check, activate, coords
Defines here
check, activate, coords
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/polygon-vertex-limit.browser.cjs:1-36 · blob cb651476555384535012360a447711c2b207a05a · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, 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||'polygon-vertex-limit-artifacts');fs.mkdirSync(out,{recursive:true});const reports=[];
const engine=process.env.BROWSER_ENGINE||'chromium';
if(!['chromium','firefox','webkit'].includes(engine))throw Error('Unsupported browser engine: '+engine);
(async()=>{const browser=await pw[engine].launch();
 try{for(const viewport of [{width:393,height:852},{width:1440,height:900}]){
  const phone=viewport.width<700,context=await browser.newContext({viewport,...(engine==='firefox'?{}:{isMobile:phone}),hasTouch:phone}),page=await context.newPage(),r={viewport,checks:[],errors:[]};reports.push(r);
  const check=(name,pass,detail)=>{r.checks.push({name,pass:!!pass,detail});console.log(pass?'PASS':'FAIL',viewport.width,name);};page.on('pageerror',e=>r.errors.push(e.message));
  const activate=l=>phone?l.tap():l.click();
  try{
   await page.goto(base);await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__?.getSource('src-zonedraw-points'));
   await activate(page.locator('.gm-title').filter({hasText:/^Scope$/}));await activate(page.locator('#btn-zonedraw'));await page.keyboard.press('Escape');
   const points=[[1,51],[1.01,51],[1.01,51.01],...Array.from({length:4093},(_,i)=>[1.01-.01*(i+1)/4093,51.01])];
   const ring=[...points,points[0]];
   await page.locator('#zonedraw-file').setInputFiles({name:'maximum.geojson',mimeType:'application/geo+json',buffer:Buffer.from(JSON.stringify({type:'Polygon',coordinates:[ring]}))});
   await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__.getSource('src-zonedraw-points')._data.features.filter(f=>f.properties.kind==='vertex').length===4096&&!window.__GRIDATLAS_V9_MAP__.isMoving());
   const coords=()=>page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.getSource('src-zonedraw-line')._data.features[0]?.geometry.coordinates.slice(0,-1));
   const addCorner=async()=>{const target=await page.evaluate(()=>{const m=window.__GRIDATLAS_V9_MAP__,f=m.getSource('src-zonedraw-points')._data.features.find(f=>f.properties.kind==='mid'&&f.properties.edgeIdx===0&&f.properties.t===.5);if(!f)throw Error('Actual first-edge midpoint is not rendered');const p=m.project(f.geometry.coordinates),r=m.getCanvas().getBoundingClientRect();return{x:r.x+p.x,  … [line shortened here: 579 characters; full line on GitHub]
   const draft=await page.evaluate(()=>localStorage.getItem('gridatlas.polygon-draft.v1'));await addCorner();
   check('Clicking a midpoint at the vertex limit preserves every coordinate',JSON.stringify(await coords())===JSON.stringify(points));
   check('Maximum-size polygon keeps its assessed fill and export',await page.locator('#btn-zonedraw-export').isEnabled()&&await page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.getSource('src-zonedraw-fill')._data.features.length===1));
   check('Vertex limit explains how to continue editing',(await page.locator('#zonedraw-storage-status').innerText()).includes('4096'));
   check('Refused insertion leaves the saved draft untouched',await page.evaluate(()=>localStorage.getItem('gridatlas.polygon-draft.v1'))===draft);
   await activate(page.locator('#btn-zonedraw-undo'));check('Refused insertion does not consume an Undo step',!(await coords()));
   await activate(page.locator('#btn-zonedraw-redo'));check('Redo restores the original maximum boundary',JSON.stringify(await coords())===JSON.stringify(points));
   await activate(page.locator('#zonedraw-coordinate-editor summary'));await page.locator('#zonedraw-vertex').selectOption('4095');await activate(page.locator('#btn-zonedraw-remove'));
   const reduced=await coords(),inserted=await addCorner(),expected=reduced.slice();expected.splice(1,0,inserted);
   check('Removing a corner permits one real midpoint insertion',JSON.stringify(await coords())===JSON.stringify(expected)&&expected.length===4096);
   await activate(page.locator('#btn-zonedraw-undo'));check('Undo restores the exact boundary before the permitted insertion',JSON.stringify(await coords())===JSON.stringify(reduced));
   check('Limit handling produces no script errors',r.errors.length===0,r.errors);
   await page.screenshot({path:path.join(out,viewport.width+'-limit.png')});
  }catch(e){r.error=e.stack;check('Vertex-limit review completes',false,e.message);}
  finally{await context.close();}
 }}finally{await browser.close();}
})().catch(e=>{reports.push({error:e.stack});process.exitCode=1;}).finally(()=>{fs.writeFileSync(path.join(out,'results.json'),JSON.stringify({base,engine,reports},null,2));if(reports.some(r=>r.error||r.checks?.some(c=>!c.pass)))process.exitCode=1;});

Prepare Layout Publication

A Python module in the tools folder of Testcode that reads five journeys, provenance, real chrome five and the Renewable Energy Planning Database (REPD) register, using SHA-256.

storagetestcode / sandbox/tools/prepare-layout-publication.py · lines 1–24 of 24 · Not reached from any entry point (candidate for review)

What it does
It loads five journeys, provenance, real chrome five and the REPD register. Defines read, write. Uses libraries pathlib, json, hashlib, subprocess, 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: the REPD register.
Inputs & outputs
In: JSON file five-journeys.json; JSON file release.json; JSON file 10919-provenance.json; JSON file real-chrome-five.json.
What it achieves
Its name says it prepares layout publication. Defines `read` and `write`. It reads `evidence/five-journeys.json` and writes `results.html`.
Why it matters
No other file in the estate was found to import it.
Application
testcode · sandbox/tools · Python module
Uses
pathlib, json, hashlib, subprocess, shutil
Used by
none found
Produces
read, write
Defines here
read, 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/prepare-layout-publication.py:1-24 · blob a7307b5277d23840ed3791613681d1467ef2a9d4 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, process · domain stage: experimental · users: none · canonical: unreached_review
from pathlib import Path
import json,hashlib,subprocess,shutil
R=Path(__file__).resolve().parents[1];G='202609051300';D=R/G
W=Path('C:/Users/vikra/globalgrid-testcode-publication')
def read(p):return p.read_text(encoding='utf-8-sig')
def write(p,s):p.write_text(s,encoding='utf8',newline='\n')
checks=json.loads(read(D/'evidence/five-journeys.json'))['checks'];assert len(checks)==10 and all(c['ok'] for c in checks)
p=D/'index.html';s=read(p);start=s.index('<p>Arrival correction:');end=s.index('<div class="pair">',start)
s=s[:start]+'<p>Five Pipeline-to-MAP journeys retested in Chrome. Search and calculation cards stay separate; the map frames the project and measured endpoints. Morgan now calculates from a labelled approximate Crown Estate lease-area centre. <a href="../202609051214/">Previous Test Code build 202609051214</a>.</p>'+s[end:];write(p,s)
p=D/'pipeline/index.html';s=read(p).replace('Missing geometry remains in search and CSV and opens DETAILS with the missing-location reason.','Records without REPD geometry remain in search and CSV. Morgan MAP uses an attributed approximate Crown Estate lease-area centre; other unresolved locations open DETAILS.');write(p,s)
p=D/'release.json';j=json.loads(read(p));j['changes'].append('Morgan REPD 10919 uses a pinned Crown Estate lease-area centroid for explicitly approximate grid screening.');j['changes']=[v for v in j['changes'] if 'Retain pinned' not in v];j['limitations']=['Other coordinate-less records, including REPD 11613, remain unresolved.','General search Parquet failure is not fixed by this exact-arrival pa  … [line shortened here: 595 characters; full line on GitHub]
rows=''.join(f'<tr><td>{c["profile"]}</td><td>{c["ref"]}</td><td>Calculation and layout checked</td><td><a href="evidence/{c["profile"]}-{c["ref"]}.png">Screenshot</a></td></tr>' for c in checks)
real=json.loads(read(D/'evidence/real-chrome-five.json'))
links=''.join(f'<li>REPD {c["ref"]}: <a href="evidence/{c["screenshot"]}">Real Chrome screenshot</a></li>' for c in real)
write(D/'results.html','<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Test Code '+G+' evidence</title><style>body{max-width:1000px;margin:24px auto;padding:16px;background:#08151c;color:#e3f5fa;font:16px/1.5 system-ui}a{color:#9eeaff}td,th{padding:8px;border-bottom:1px solid #456}table{width:100%}</style><a href="./">Test Code</a><h1  … [line shortened here: 1,670 characters; full line on GitHub]
shutil.copytree(D,W/'testcode'/G,dirs_exist_ok=True)
# Snapshot latest remote homepage, preserving concurrent Claude publications.
p=W/'index.html';raw=p.read_bytes();s=raw.decode('utf8');F=W/'homepage_versions';n=max(int(p.stem.split('v')[-1]) for p in F.glob('homepage_v*.html'))+1
snap=F/f'homepage_v{n:03d}.html';before=len(list(F.iterdir()));snap.write_bytes(raw)
head=subprocess.check_output(['git','-C',str(W),'rev-parse','HEAD']).decode().strip()
with (F/'README.md').open('a',encoding='utf8') as o:o.write(f'\n\n## Snapshot v{n:03d}\nSource: {head}. File {snap.name}. Folder files before {before}, after {before+1}.\nLines {len(s.splitlines())}; words {len(s.split())}; characters {len(s)}. SHA256 {hashlib.sha256(raw).hexdigest()}.\nIntention: append Test Code {G}, preserving Claude builds and previous Test Code links.\n')
assert '<h2>Test Code</h2>' in s
s=s.replace('<h2>Test Code</h2>','<h2>Test Code</h2>\n<p><a href="./testcode/'+G+'/">Grid calculation and mobile layout correction - '+G+' UTC</a>: five Chrome MAP journeys with screenshots; Morgan uses an attributed approximate lease-area centre.</p>').replace('Latest correction - 202609051214 UTC','Earlier correction - 202609051214 UTC');write(p,s)
print(snap.name)

Print View

A JavaScript file in the tools folder of Testcode. It is built from the print view helper (`printView`), the capture step (`capture`) and the clean step (`clean`).

Set aside from the main view: The function `printView` (lines 1-31) is the same code, apart from spacing and comments, as `printView` kept in code-generator apps/substation-finder/Si/202609060537-substation-intelligence.js (lines 3954-3983); it is the whole file. (unit-duplicate-of, proposed by units.py). The file that stays: Substation Intelligence. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • exact_hash equal: 9409d5601e897a63 (target code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Si/202609060537-substation-intelligence.js:3954-3983 fd8aeb8a8884da62dc50991d5f4bf8cc48b33c43)
  • cluster of 12 units in 6 files across 3 repositories
  • files otherwise different: unit exact_hash Jaccard between the two files 0.01 (< 0.8)
  • target chosen by canonical_status unreached_review, not a core repository, not reached

rendertestcode / sandbox/tools/print-view.js · lines 1–31 of 31 · Not reached from any entry point (candidate for review) · pattern printView (shared by 13 files)

What it does
It draws its content. Defines printView, capture, clean. 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. 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."
What it achieves
The README says: 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`. It responds to afterprint events.
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
printView, capture, clean
Defines here
printView, capture, clean
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/print-view.js:1-31 · blob fe36826bdd03afecdbff4e6c9553931ee182331b · GitHub at these lines
State
achieves: readme · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: unreached_review
  function printView(doc) {
    var map = window.__GRIDATLAS_V9_MAP__;
    var canvas = map && map.getCanvas && map.getCanvas();
    if (!canvas) return;
    var capture = function () {
      var url;
      try { url = canvas.toDataURL('image/png'); } catch (_) { return; }
      if (looksBlank(canvas)) return;
      var old = doc.getElementById('gridatlas-print-furniture');
      if (old) old.remove();
      var furniture = buildPrintFurniture(doc);
      var image = doc.createElement('img');
      image.className = 'gpf-map'; image.alt = 'Current Grid Atlas map'; image.src = url;
      furniture.appendChild(image);
      var style = doc.getElementById('gridatlas-print-css');
      if (!style) { style = doc.createElement('style'); style.id = 'gridatlas-print-css'; doc.head.appendChild(style); }
      style.textContent = '#gridatlas-print-furniture{display:none}' +
        '@media print{@page{size:auto;margin:8mm}html,body{margin:0!important;padding:0!important;height:auto!important;overflow:visible!important;background:white!important}' +
        'body>*:not(#gridatlas-print-furniture){display:none!important}' +
        '#gridatlas-print-furniture{display:block!important;position:fixed;inset:0;box-sizing:border-box;padding:4mm;background:white;color:#101c22;font:11px/1.4 system-ui}' +
        '.gpf-head{font-size:12px;letter-spacing:2px}.gpf-brand{font-weight:bold;margin-right:10px}.gpf-title{font-size:18px;margin-top:3mm}' +
        '.gpf-map{position:absolute;left:4mm;top:22mm;width:calc(100% - 8mm);height:calc(100% - 42mm);object-fit:contain}' +
        '.gpf-foot{position:absolute;left:4mm;right:4mm;bottom:3mm;display:flex;gap:12px;justify-content:space-between;font-size:9px}.gpf-stamp{white-space:nowrap}}';
      var clean = function () { furniture.remove(); window.removeEventListener('afterprint', clean); };
      window.addEventListener('afterprint', clean);
      image.decode().then(function () { window.print(); }).catch(clean);
      // Keep the snapshot while a mobile print/share dialog is open.
      window.setTimeout(clean, 300000);
    };
    map.once('render', capture); map.triggerRepaint();
  }

Source Download Browser

A JavaScript module in the tools folder of Testcode that draws tool layers, using SHA-256.

rendertestcode / sandbox/tools/source-download.browser.cjs · lines 1–71 of 71 · Not reached from any entry point (candidate for review)

What it does
It draws tool layers. Defines hash, blob, check. Uses libraries node:fs, node:path, node:crypto, node:child_process, playwright. 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.
Inputs & outputs
In: JSON file current.json; JSON file tool-layers.json; command-line arguments. Out: JSON file results.json.
What it achieves
Defines `hash`, `blob` and `check`.
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:crypto, node:child_process, playwright, C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright
Used by
none found
Produces
hash, blob, check
Defines here
hash, blob, 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/source-download.browser.cjs:1-71 · blob 35b68b11875ecdb1eee7d7bcc53d543e53c7660c · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: experimental · users: none · canonical: unreached_review
const fs=require('node:fs'),path=require('node:path');
const {createHash}=require('node:crypto');
const {execFileSync}=require('node:child_process');
const hash=bytes=>createHash('sha256').update(bytes).digest('hex');
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||'source-download-artifacts');
const generation=new URL(base).pathname.match(/^\/testcode\/(\d{12})\/atlas\/$/)?.[1];
if(!generation)throw Error('Pass an immutable TestCode Atlas URL');
const root=path.resolve(__dirname,'../..'),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});
fs.mkdirSync(out,{recursive:true});
const results=[];
(async()=>{
 const browser=await pw[process.env.TEST_ENGINE||'chromium'].launch();
 try{for(const viewport of [{width:393,height:852}]){
  const ratio=Number(process.env.TEST_DPR||1);
  const context=await browser.newContext({viewport,deviceScaleFactor:ratio}),page=await context.newPage();
  const receipt={viewport,checks:[],errors:[]};results.push(receipt);
  const check=(name,pass,detail)=>{receipt.checks.push({name,pass:!!pass,detail});console.log(pass?'PASS':'FAIL',viewport.width,name);};
  page.on('pageerror',e=>receipt.errors.push(e.message));
  try{
   await page.goto(base,{waitUntil:'domcontentloaded'});
   await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__?.getSource('src-zonedraw-points'));
   await page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.jumpTo({center:[0.935,51.339],zoom:14}));
   await page.locator('.gm-title').filter({hasText:/^Scope$/}).click();
   await page.locator('#btn-zonedraw').click();
   await page.locator('#zonedraw-radius-input').fill('0.337');
   const canvas=page.locator('#map canvas.maplibregl-canvas'),box=await canvas.boundingBox();
   await canvas.click({position:{x:box.width/2,y:box.height/2}});
   await page.waitForFunction(()=>document.querySelector('.measurement-dock-values')?.textContent.includes('Hectares'));
   await page.waitForFunction(()=>!window.__GRIDATLAS_V9_MAP__.isMoving());
   receipt.visibleMeasurements=await page.locator('.measurement-dock-values').innerText();
   receipt.screenCanvas=await canvas.boundingBox();
   receipt.geometry=await page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.getSource('src-zonedraw-fill')._data);
   await page.screenshot({path:path.join(out,viewport.width+'-screen.png')});
   const menu=page.locator('#gridatlas-menu-bar .gm-menu').filter({has:page.locator('[data-gm-export]')}).first();
   await menu.locator('.gm-title').click();
   const pending=page.waitForEvent('download',{timeout:240000}).catch(error=>({failed:error.message}));
   await page.locator('[data-codex-print-source]').click();
   const download=await pending;if(download.failed)throw Error(download.failed+' '+await page.locator('#codex-teleprinter #status').innerText());
   const filename=path.join(out,'atlas-runtime-source.txt');await download.saveAs(filename);
   const bytes=fs.readFileSync(filename),text=bytes.toString('utf8');
   const manifest=JSON.parse(text.split('===== BEGIN DIAGNOSTIC MANIFEST =====\n')[1].split('\n===== END DIAGNOSTIC MANIFEST =====')[0]);
   receipt.manifest={complete:manifest.complete,observedResourcesComplete:manifest.observedResourcesComplete,counts:manifest.counts,failures:manifest.failures,discoveryWarnings:manifest.discoveryWarnings};
   check('Source download honestly declares browser discovery incomplete',manifest.complete===false&&text.includes('Completeness: INCOMPLETE'));
   check('Source download records current release URL',manifest.state.url===base);
   check('Source download retains exact drawn polygon',JSON.stringify(manifest.state.map.sources['src-zonedraw-fill'].data)===JSON.stringify(receipt.geometry));
   let verified=0;const headers=[...text.matchAll(/===== BEGIN RESOURCE ("[^\n]+?") \| originalBytes=(\d+) \| encoding=([^ ]+) \| sha256=([a-f0-9]+) =====\n/g)];
   for(const match of headers){const end=text.indexOf('\n===== END RESOURCE '+match[1]+' =====',match.index+match[0].length);if(end<0)throw Error('Missing resource boundary');const value=text.slice(match.index+match[0].length,end),body=Buffer.from(value,match[3]==='base64'?'base64':'utf8');if(body.length!==Number(match[2])||hash(body)!==match[4])throw Error('Resource hash mismatch '+match[1]);veri  … [line shortened here: 408 characters; full line on GitHub]
   check('Every downloaded resource body matches its own full byte hash',verified===manifest.counts.included,{verified});
   const current=JSON.parse(blob('sandbox/'+generation+'/atlas/current.json'));
   const cartridge=current.cartridges.find(c=>c.id==='substation-intelligence');
   check('Runtime source includes exact current executable cartridge',manifest.resources.some(resource=>resource.url===new URL(cartridge.path,base).href&&resource.sha256===cartridge.sha256&&resource.status==='included'));
   check('Runtime source includes every pinned executable cartridge',current.cartridges.every(cartridge=>manifest.resources.some(resource=>resource.url===new URL(cartridge.path,base).href&&resource.sha256===cartridge.sha256&&resource.status==='included')));
   check('Runtime source contains the exact router document',manifest.resources.some(resource=>resource.url===base&&resource.sha256===hash(blob('sandbox/'+generation+'/atlas/index.html'))&&resource.status==='included'));
   const pinsPath='sandbox/'+generation+'/atlas/tool-layers.json';
   const pins=JSON.parse(blob(pinsPath));
   if(pins.hostGeneration){
    const prefix='sandbox/'+pins.hostGeneration+'/tool-layers/';
    const files=execFileSync('git',['ls-tree','-r','--name-only',sourceCommit,prefix],{cwd:root,encoding:'utf8'}).trim().split('\n').filter(p=>p.endsWith('.js'));
    check('Runtime source contains every pinned tool host module',files.length>0&&files.every(p=>manifest.resources.some(resource=>resource.url===new URL('/testcode/'+p.slice(8),base).href&&resource.sha256===hash(blob(p))&&resource.status==='included')),{files});
   }
   receipt.download={bytes:bytes.length,sha256:hash(bytes),filename:download.suggestedFilename()};
   check('Source capture causes no uncaught script errors',receipt.errors.length===0,receipt.errors);
  }catch(error){receipt.error=error.stack;check('Source download completes',false,error.message);}
  finally{await context.close();}
 }}finally{await browser.close();}
})().catch(error=>{results.push({error:error.stack});process.exitCode=1;}).finally(()=>{
 fs.writeFileSync(path.join(out,'results.json'),JSON.stringify({base,generation,sourceCommit,results},null,2)+'\n');
 if(results.some(r=>r.error||r.checks?.some(c=>!c.pass)))process.exitCode=1;
});

Token Compaction

A JavaScript module in the tools folder of Testcode that replaces map engine (`replaceMapEngine`) and optional module (`replaceOptionalModule`), using SHA-256.

othertestcode / sandbox/tools/token-compaction.mjs · lines 1–61 of 61 · pattern tokens (shared by 8 files)

What it does
It lists and searches its content. Defines 8 functions or classes, including hash, syntax, canonical, tokens, proveEquivalent. Uses libraries node:assert/strict, node:fs, node:path, node:crypto, 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 2 files: Build Poly Candidate (testcode); Verify Poly Candidate (testcode). Reached from 7 other entry points, including Map PDF Workflow (testcode); Measurement Clearance Workflow (testcode); Measurement Readouts Workflow (testcode).
What it achieves
It proves equivalent (`proveEquivalent`), replaces map engine (`replaceMapEngine`) and replaces optional module (`replaceOptionalModule`). Build-time token compaction. Executable token text and complete syntax trees must agree.
Why it matters
Run by Build Poly Candidate and Verify Poly Candidate.
Application
testcode · sandbox/tools · JavaScript module
Uses
node:assert/strict, node:fs, node:path, node:crypto, node:child_process, node:url
Used by
run by Build Poly Candidate (script call), run by Verify Poly Candidate (script call)
Produces
PARSER, proveEquivalent, compact, replaceMapEngine, replaceOptionalModule
Defines here
hash, syntax, canonical, tokens, proveEquivalent, compact, replaceMapEngine, replaceOptionalModule
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/token-compaction.mjs:1-61 · blob 83e4cf9ecf89dee07d1724a7537a15edc9e8ccd9 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: experimental · users: none · canonical: unknown
// Adapted from GridAtlas f417f17 tools/compact-modules.mjs; parser/token/AST checks retained.
/** Build-time token compaction. Executable token text and complete syntax trees must agree. */
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import {createHash} from 'node:crypto';
import {execFileSync} from 'node:child_process';
import {fileURLToPath} from 'node:url';

const ROOT=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
const parserSource=process.binding('natives')['internal/deps/acorn/acorn/dist/acorn'];
assert.equal(typeof parserSource,'string','This build requires Node with its bundled Acorn parser; no regex fallback is allowed');
const parserModule={exports:{}};
new Function('exports','module',parserSource)(parserModule.exports,parserModule);
const acorn=parserModule.exports;
const hash=s=>createHash('sha256').update(s).digest('hex');
export const PARSER=Object.freeze({name:'Acorn bundled in Node',version:acorn.version,node:process.version,sha256:hash(parserSource)});
const syntax=source=>acorn.parse(source,{ecmaVersion:'latest'});
const canonical=ast=>JSON.stringify(ast,(key,value)=>['start','end','loc','range'].includes(key)?undefined:value);
function tokens(source) {
  const list=[];acorn.parse(source,{ecmaVersion:'latest',onToken:list});
  return list.map(token=>source.slice(token.start,token.end));
}
export function proveEquivalent(before,after) {
  assert.deepEqual(tokens(after),tokens(before),'Executable token text changed');
  assert.equal(canonical(syntax(after)),canonical(syntax(before)),'Syntax tree changed (including automatic semicolon insertion)');
}
export function compact(source) {
  const list=[],comments=[];
  acorn.parse(source,{ecmaVersion:'latest',onToken:list,onComment:comments});
  let result='',cursor=0;
  for(const token of list) {
    const gap=source.slice(cursor,token.start);
    result+=(/[\r\n]/.test(gap)?'\n':gap?' ':'')+source.slice(token.start,token.end);
    cursor=token.end;
  }
  // Retain licensing/preservation comments, never treating text inside literals as comments.
  const notices=comments.filter(c=>/@license|@preserve|copyright|SPDX-License-Identifier|permission is hereby granted/i.test(c.value));
  if(notices.length)result=notices.map(c=>source.slice(c.start,c.end)).join('\n')+'\n'+result;
  proveEquivalent(source,result);
  return result;
}

export function replaceMapEngine(source,engine,module) {
  const dockNodes=syntax(source).body.filter(n=>n.type==='ExpressionStatement'&&n.expression.type==='CallExpression'&&source.slice(n.start,n.end).includes('gridatlas.measurement-dock.v1'));
  assert(dockNodes.length<=1,'At most one measurement dock module may be carried');
  if(dockNodes.length){const n=dockNodes[0];source=source.slice(0,n.start)+source.slice(n.end);}
  const nodes=syntax(source).body.filter(n=>n.type==="ExpressionStatement"&&n.expression.type==="AssignmentExpression"&&n.expression.left.type==="MemberExpression"&&n.expression.left.object.name==="window"&&n.expression.left.property.name==="initVentusMap");
  assert.equal(nodes.length,1,"Exactly one carried engine assignment required");
  const n=nodes[0]; return source.slice(0,n.start)+module+"\n"+engine+source.slice(n.end);
}

export function replaceOptionalModule(source,module,schema) {
  assert(/^gridatlas\.[a-z0-9-]+\.v\d+$/.test(schema),'Explicit optional module schema required');
  const nodes=syntax(source).body.filter(n=>n.type==='ExpressionStatement'&&n.expression.type==='CallExpression'&&source.slice(n.start,n.end).includes(schema));
  assert(nodes.length<=1,'Optional module must not accumulate duplicates');
  if(nodes.length){const n=nodes[0];source=source.slice(0,n.start)+source.slice(n.end);}
  assert(module.includes(schema),'Pinned module must declare its schema');
  syntax(module);
  return source+'\n'+module+'\n';
}

Tool Recovery Browser

A JavaScript module in the tools folder of Testcode covering cables.

rendertestcode / sandbox/tools/tool-recovery.browser.cjs · lines 1–41 of 41 · Entry point · pattern coordinates (shared by 3 files)

What it does
It draws cables. Defines check, coordinates. 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.
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: cables.
Inputs & outputs
In: command-line arguments. Out: JSON file results.json.
Downstream impact
Used directly by 7 files: Composition Guard Workflow (testcode); Measurement Clearance Workflow (testcode); Measurement Readouts Workflow (testcode); Polygon Distance Workflow (testcode); and 3 more.
What it achieves
Defines `check` and `coordinates`.
Why it matters
Run by 7 workflows and scripts, including Composition Guard Workflow, Measurement Clearance Workflow and Measurement Readouts 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 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
check, coordinates
Defines here
check, coordinates
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/tool-recovery.browser.cjs:1-41 · blob 0674178085a63c36c71af04b411dbbdaa2eb49aa · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · 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||'tool-recovery-artifacts');fs.mkdirSync(out,{recursive:true});const reports=[];
(async()=>{const browser=await pw.chromium.launch();
 try{for(const viewport of [{width:393,height:852},{width:1440,height:900}]){
  const context=await browser.newContext({viewport}),page=await context.newPage(),report={viewport,checks:[],errors:[]};reports.push(report);
  const check=(name,pass,detail)=>{report.checks.push({name,pass:!!pass,detail});console.log(pass?'PASS':'FAIL',viewport.width,name);};
  page.on('pageerror',error=>report.errors.push(error.message));
  let attempts=0;
  await page.route('**/layer-apps/solar-bess-topology-v7/cable-geometry-visualiser/index.html',async route=>{
   attempts++;if(attempts===1)await route.fulfill({status:503,contentType:'text/html',body:'<!doctype html><title>Temporary fixture outage</title><p>Tool unavailable in this deliberate negative fixture.</p>'});else await route.continue();
  });
  try{
   await page.goto(base,{waitUntil:'domcontentloaded'});await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__?.getSource('src-zonedraw-points'));
   const scope=page.locator('.gm-title').filter({hasText:/^Scope$/});await scope.click();await page.locator('#btn-zonedraw').click();
   const canvas=page.locator('#map canvas.maplibregl-canvas'),box=await canvas.boundingBox();await canvas.click({position:{x:box.width/2,y:box.height/2}});
   const coordinates=()=>page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.getSource('src-zonedraw-fill')._data.features[0]?.geometry.coordinates);
   const held=await coordinates();await scope.click();await page.locator('#btn-zonedraw').click();
   const launch=page.getByRole('button',{name:'Cable Geometry',exact:true});await launch.click();
   const layer=page.getByRole('dialog',{name:'Cable Geometry',exact:true});
   const retry=layer.getByRole('button',{name:'Retry tool loading',exact:true});
   await retry.waitFor({state:'attached',timeout:15000});
   check('Unavailable tool exposes its own recovery control',await retry.count()===1);
   if(!(await retry.count()))throw Error('The carried host has no recovery control');
   await retry.waitFor({state:'visible'});check('Failed tool is not reported as ready',await layer.locator('[data-tool-readiness]').getAttribute('data-interface')==='unrecognised');
   check('Failed iframe leaves Atlas polygon unchanged',JSON.stringify(await coordinates())===JSON.stringify(held));
   await retry.click();await layer.getByRole('button',{name:'Keep working',exact:true}).click();check('Cancel retry does not reload the tool',attempts===1);
   await retry.click();await layer.getByRole('button',{name:'Confirm restart',exact:true}).click();
   await layer.locator('[data-drawing="ready"]').waitFor();check('Confirmed retry loads the actual original tool',attempts===2);
   const frame=page.frameLocator('iframe[title="Cable Geometry"]');await frame.locator('#route_name').fill('Retained separate tool state');await frame.locator('#route_name').press('Tab');
   await layer.getByRole('button',{name:'Close - return to GridAtlas',exact:true}).click();
   check('Closing the recovered tool restores launcher focus',await launch.evaluate(e=>e===document.activeElement));
   await launch.click();check('Reopening preserves the same iframe and its edited input',await page.locator('iframe[title="Cable Geometry"]').count()===1&&(await frame.locator('#route_name').inputValue())==='Retained separate tool state');
   await frame.locator('#route_name').focus();await page.keyboard.press('Escape');check('Escape inside the original tool returns to Atlas',!(await layer.isVisible()));
   await scope.click();await page.locator('#btn-zonedraw').click();check('Returning to Poly Zone retains every original vertex',JSON.stringify(await coordinates())===JSON.stringify(held));
   check('Recovery produces no uncaught script errors',report.errors.length===0,report.errors);
   await page.screenshot({path:path.join(out,viewport.width+'-recovered.png')});
  }catch(error){report.error=error.stack;await page.screenshot({path:path.join(out,viewport.width+'-failure.png')}).catch(()=>{});check('Tool recovery completes',false,error.message);}
  finally{report.attempts=attempts;await context.close();}
 }}finally{await browser.close();}
})().catch(error=>{reports.push({error:error.stack});process.exitCode=1;}).finally(()=>{fs.writeFileSync(path.join(out,'results.json'),JSON.stringify({base,fixture:'First Cable iframe request returns explicit HTTP503; retry loads actual original files',reports},null,2)+'\n');if(reports.some(r=>r.error||r.checks?.some(c=>!c.pass)))process.exitCode=1;});

Verify Composition Guard

A JavaScript module in the tools folder of Testcode covering publication and provenance, using SHA-256.

othertestcode / sandbox/tools/verify-composition-guard.mjs · lines 1–23 of 23 · Entry point · pattern source (shared by 13 files)

What it does
It lists and searches publication and provenance. Defines blob, source. Uses libraries node:assert/strict, node:path, node:url, node:child_process, node:crypto. Side effects: 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 publication.json; JSON file source-provenance.json; JSON file current.json; command-line arguments.
Downstream impact
Used directly by 1 file: Composition Guard Workflow (testcode).
What it achieves
Its name says it verifies composition guard. Defines `blob` and `source`.
Why it matters
Run by Composition Guard Workflow.
Application
testcode · sandbox/tools · JavaScript module
Uses
node:assert/strict, node:path, node:url, node:child_process, node:crypto
Used by
run by Composition Guard Workflow (workflow run)
Produces
blob, source
Defines here
blob, 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/verify-composition-guard.mjs:1-23 · blob 0fcc0d8f255c0c3e2052b7f12ead2c11290ce64a · GitHub at these lines
State
achieves: name · context: readme_derived · stage: unknown · effects: process · domain stage: experimental · users: none · canonical: unknown
import assert from 'node:assert/strict';
import path from 'node:path';
import {fileURLToPath} from 'node:url';
import {execFileSync} from 'node:child_process';
import {createHash} from 'node:crypto';
const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'../..'),generation=process.argv[2];assert(/^\d{12}$/.test(generation||''));
const blob=(p,ref='HEAD')=>execFileSync('git',['show',ref+':'+p],{cwd:root,maxBuffer:64*1024*1024});const hash=b=>createHash('sha256').update(b).digest('hex');
const prefix=`sandbox/${generation}/`,manifest=JSON.parse(blob(prefix+'publication.json')),p=JSON.parse(blob(prefix+'atlas/source-provenance.json'));
assert.equal(p.schema,'gridatlas.composition-guard.v1');assert.equal(p.generation,generation);assert.equal(manifest.generation,generation);assert.equal(p.sourceCommit,manifest.source_commit);
for(const f of manifest.files){const b=blob(prefix+f.path);assert.equal(b.length,f.bytes);assert.equal(hash(b),f.sha256);}
const source=q=>blob(q,p.sourceCommit),contract=source(p.contract.path),before=source(`sandbox/${p.parent}/atlas/index.html`);
assert.equal(hash(contract),p.contract.sha256);assert.equal(hash(before),p.parentIndexSha256);
const hook="      invariant(Array.isArray(current.cartridge_order) && Array.isArray(current.cartridges), 'cartridge registry malformed');";
const expected=before.toString().replace('Test Code Atlas '+p.parent,'Test Code Atlas '+generation).replace(hook,hook+'\n'+contract.toString().replace('export function','function')+'\n      validateAtlasComposition(current);');
assert.equal(blob(prefix+'atlas/index.html').toString(),expected);assert.equal(hash(expected),p.indexSha256);
const current=JSON.parse(blob(prefix+'atlas/current.json')),parent=JSON.parse(source(`sandbox/${p.parent}/atlas/current.json`));
for(const c of parent.cartridges)if(c.path.startsWith('./'))c.path=`/testcode/${p.parent}/atlas/${c.path.slice(2)}`;
assert.deepEqual(current.cartridges,parent.cartridges);assert.deepEqual(current.cartridge_order,parent.cartridge_order);
assert.deepEqual(current.layout_cartridge,parent.layout_cartridge);
for(const c of current.cartridges){assert(c.path.startsWith('/testcode/'));const q='sandbox/'+c.path.slice(10);assert.equal(hash(blob(q)),c.sha256);assert.deepEqual(blob(q),source(q));}
for(const f of manifest.files.filter(f=>f.path.startsWith('atlas/')&&!['atlas/current.json','atlas/index.html','atlas/source-provenance.json'].includes(f.path)))assert.deepEqual(blob(prefix+f.path),source(`sandbox/${p.parent}/${f.path}`),f.path);
assert.equal(hash(blob(prefix+'atlas/map-controls-layout.js')),current.layout_cartridge.sha256);
console.log(`PASS ${generation}: ${manifest.files.length} published files, exact router reconstruction, unchanged four cartridges and carried initialization`);