GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Automation and CI / globalgrid2050 / automation/v931_preview

Browser and 2 more files (part 1)

A JavaScript module in the automation folder of GlobalGrid2050 that verifies locations (`verifyLocations`), resets price trace (`resetPriceTrace`), verifies prices (`verifyPrices`) and draws on a canvas (units: MWh), using SHA-256.

539 lines of JavaScript from globalgrid2050, in 3 files. Topic: Automation and CI. Section 1748 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. Browser energy-data · globalgrid2050 / automation/v931_preview/browser.mjs lines 1–322
  2. Contracts Test test · globalgrid2050 / automation/v931_preview/contracts.test.mjs lines 1–103
  3. Invariants storage · globalgrid2050 / automation/v931_preview/invariants.mjs lines 1–114

Browser

A JavaScript module in the automation folder of GlobalGrid2050 that verifies locations (`verifyLocations`), resets price trace (`resetPriceTrace`), verifies prices (`verifyPrices`) and draws on a canvas (units: MWh), using SHA-256.

energy-dataglobalgrid2050 / automation/v931_preview/browser.mjs · lines 1–322 of 322 · Entry point · pattern assertPriceDrawing (shared by 3 files)

What it does
It draws DC locations, prices, DC global and snapshot provenance. Defines 21 functions or classes, including sha, priceBytes, urlFor, pass, download. Uses libraries node:assert/strict, node:http, node:crypto, node:child_process, node:fs. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes.
Inputs & outputs
In: JSON file dc-locations.v930.json; JSON file prices.v931.json; JSON file index.json; JSON file 2026.json; JSON file 2025.json; CSV file v929-all.csv; CSV file v929-dc-global.csv; JSON file build_manifest.json. Out: JSON file browser.json; canvas drawing.
Downstream impact
Used directly by 1 file: GlobalGrid2050 V931 Preview Acceptance Workflow (globalgrid2050).
What it achieves
It verifies locations (`verifyLocations`), resets price trace (`resetPriceTrace`) and verifies prices (`verifyPrices`). Real integrated V9.31 browser acceptance against exact source-byte fixtures.
Why it matters
Run by GlobalGrid2050 V931 Preview Acceptance Workflow.
Application
globalgrid2050 · automation/v931_preview · JavaScript module
Uses
node:assert/strict, node:http, node:crypto, node:child_process, node:fs, node:path, node:os, node:url
Used by
run by GlobalGrid2050 V931 Preview Acceptance Workflow (workflow run)
Produces
sha, priceBytes, urlFor, pass, download, open, fullWidth, painted, settleTouch, touchTap, touchDrag, orientationScreenshot
Defines here
sha, priceBytes, urlFor, pass, download, open, fullWidth, painted, settleTouch, touchTap, touchDrag, orientationScreenshot, tab, allRepd, dcOriginalLinks, dcGlobal, verifyLocations, resetPriceTrace, priceRange, assertPriceDrawing, verifyPrices
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/v931_preview/browser.mjs:1-322 · blob a85bee31021aa6e7b2e1e513c387fe43f2547fbf · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, process · domain stage: unknown · users: none · canonical: production_core
/** Real integrated V9.31 browser acceptance against exact source-byte fixtures. */
import assert from 'node:assert/strict';
import {createServer} from 'node:http';
import {createHash} from 'node:crypto';
import {execFileSync} from 'node:child_process';
import {readFileSync,writeFileSync,mkdirSync,statSync,existsSync} from 'node:fs';
import {dirname,resolve,relative,extname,sep} from 'node:path';
import {tmpdir} from 'node:os';
import {fileURLToPath,pathToFileURL} from 'node:url';
const ROOT=resolve(dirname(fileURLToPath(import.meta.url)),'../..');
const EDITION=process.env.V931_CANDIDATE||'uk_renewables_pipeline/202611170243';
const candidate=resolve(ROOT,EDITION),baseline=resolve(ROOT,'uk_renewables_pipeline/202611170147');
const OUT=resolve(process.env.V931_OUT||resolve(tmpdir(),'gg2050-v931-preview'));
const {chromium}=process.env.V931_PLAYWRIGHT
  ? await import(pathToFileURL(resolve(process.env.V931_PLAYWRIGHT))) : await import('playwright');
const {catalogue}=await import(pathToFileURL(resolve(candidate,'scripts/layers/catalogue.mjs')));
const sha=b=>createHash('sha256').update(b).digest('hex');
mkdirSync(OUT,{recursive:true});
const receipt={status:'RUNNING',utc:new Date().toISOString(),head:execFileSync('git',['rev-parse','HEAD'],{cwd:ROOT,encoding:'utf8'}).trim(),edition:EDITION,index_sha256:sha(readFileSync(resolve(candidate,'index.html'))),checks:[],sources:[],blocked_external:[],limitations:[
  'Local integrated browser proof; no deployment, public served-byte or native-phone acceptance.',
  'Pinned GridAtlas source bytes are replayed exactly; no claim of fresh network-state data or typed substation arrival.',
  'External feeds, Chart.js CDN and original V6 workspace navigation are blocked; saved news and the independently linked workspace are tested.',
  'Prices are historical Elexon system-sell observations grouped by source-declared settlement date; complete source-day coverage does not certify stored UTC alignment.',
  'Android UA, touch gestures and screen orientation are Chromium emulation on this host, not a native Android handset/browser process.',
  'All-row MAP construction is checked separately; this browser suite does not execute the public GridAtlas receiver.']};
const sourceBytes=new Map();
const locationSpec=JSON.parse(readFileSync(resolve(candidate,'contracts/dc-locations.v930.json')));
let locationBytes;
if(process.env.V931_DATA_SOURCE)locationBytes=readFileSync(resolve(process.env.V931_DATA_SOURCE));
else{const response=await fetch(locationSpec.input.url,{redirect:'error',signal:AbortSignal.timeout(15000)});assert.ok(response.ok);locationBytes=Buffer.from(await response.arrayBuffer());}
assert.equal(locationBytes.length,183561);assert.equal(sha(locationBytes),'6f68e078d9b57057acdda679288730e638553f68df884dfd747c5049e56ea88e');
const locationData=JSON.parse(locationBytes),byId=new Map(locationData.features.map(f=>[f.id,f]));
sourceBytes.set(locationSpec.input.url,locationBytes);
receipt.sources.push({id:'dc-address-locations',url:locationSpec.input.url,sha256:sha(locationBytes),bytes:locationBytes.length,transport:process.env.V931_DATA_SOURCE?'explicit data-owner fixture, exact immutable bytes':'immutable HTTPS source'});
let baselineDCLinks,baselineDCCsv;
const priceSpec=JSON.parse(readFileSync(resolve(candidate,'contracts/prices.v931.json')));
const priceModel=await import(pathToFileURL(resolve(ROOT,'automation/price_daily_ui',priceSpec.producer.commit,'model.mjs')));
async function priceBytes(name,pin){
  let raw;if(process.env.V931_PRICE_SOURCE)raw=readFileSync(resolve(process.env.V931_PRICE_SOURCE,name));
  else{const response=await fetch(priceSpec.input.base+name,{redirect:'error',signal:AbortSignal.timeout(15000)});assert.ok(response.ok);raw=Buffer.from(await response.arrayBuffer());}
  assert.equal(raw.length,pin.bytes);assert.equal(sha(raw),pin.sha256);sourceBytes.set(priceSpec.input.base+name,raw);return raw;
}
const priceIndex=priceModel.validateIndex(JSON.parse(await priceBytes('index.json',priceSpec.input.index))),priceYears=new Map();
await Promise.all(priceIndex.parts.map(async part=>priceYears.set(part.year,{...JSON.parse(await priceBytes(part.path,part))})));
receipt.sources.push({id:'historical-daily-system-sell',repository:priceSpec.input.repository,commit:priceSpec.input.commit,index_sha256:priceSpec.input.index.sha256,index_bytes:priceSpec.input.index.bytes,annual_parts:priceIndex.parts.length,transport:process.env.V931_PRICE_SOURCE?'explicit existing owner bytes, every pin checked then replayed':'immutable HTTPS owner bytes, every pin checked then  … [line shortened here: 413 characters; full line on GitHub]
for(const layer of catalogue.layers.filter(l=>l.data)){
  let raw,transport;
  try{const response=await fetch(layer.data.url,{signal:AbortSignal.timeout(12000),redirect:'error'});if(!response.ok)throw Error('HTTP '+response.status);raw=Buffer.from(await response.arrayBuffer());transport='immutable HTTPS URL';}
  catch{
    if(!process.env.GRIDATLAS_SOURCE)throw Error('Pinned source transport failed; set GRIDATLAS_SOURCE to an existing owner checkout for exact-byte replay.');
    const rel=new URL(layer.data.url).pathname.split('/').slice(4).join('/');
    raw=readFileSync(resolve(process.env.GRIDATLAS_SOURCE,rel));transport='existing owner checkout, exact pinned bytes';
  }
  assert.equal(sha(raw),layer.data.sha256,layer.id+' actual source SHA256');assert.ok(raw.length<=layer.data.maxBytes);
  const doc=JSON.parse(raw);assert.equal(doc.features.length,layer.data.rows);
  sourceBytes.set(layer.data.url,raw);receipt.sources.push({id:layer.id,url:layer.data.url,sha256:sha(raw),bytes:raw.length,rows:doc.features.length,transport});
}
const subs=JSON.parse(sourceBytes.get(catalogue.layers.find(l=>l.id==='substations').data.url));
const named=subs.features.filter(f=>typeof f.properties?.name==='string'&&f.properties.name.trim()).length;
assert.equal(named,4460);assert.equal(subs.features.length-named,1340);
const mime={'.html':'text/html','.mjs':'text/javascript','.js':'text/javascript','.css':'text/css','.json':'application/json','.geojson':'application/json','.svg':'image/svg+xml','.png':'image/png'};
const server=createServer((req,res)=>{try{let p=resolve(ROOT,'.'+decodeURIComponent(new URL(req.url,'http://local').pathname));if(!p.startsWith(ROOT+sep)){res.writeHead(403).end();return;}if(statSync(p).isDirectory())p=resolve(p,'index.html');res.writeHead(200,{'Content-Type':mime[extname(p)]||'application/octet-stream','Cache-Control':'no-store'});res.end(readFileSync(p));}catch{res.writeHead(404  … [line shortened here: 412 characters; full line on GitHub]
await new Promise(r=>server.listen(0,'127.0.0.1',r));const origin='http://127.0.0.1:'+server.address().port;
const urlFor=dir=>origin+'/'+relative(ROOT,dir).replaceAll('\\','/')+'/';
const pass=(name,details={})=>{receipt.checks.push({name,status:'PASS',...details});console.log('PASS:',name);};
function csv(text){const records=[];let row=[],cell='',quoted=false;text=text.replace(/^\ufeff/,'');for(let i=0;i<text.length;i++){const c=text[i];if(c==='"'&&quoted&&text[i+1]==='"'){cell+='"';i++;}else if(c==='"')quoted=!quoted;else if(c===','&&!quoted){row.push(cell);cell='';}else if((c==='\n'||c==='\r')&&!quoted){if(c==='\r'&&text[i+1]==='\n')i++;row.push(cell);records.push(row);row=[];cell=''  … [line shortened here: 514 characters; full line on GitHub]
async function download(page,button,name){const event=page.waitForEvent('download');await button.click();const d=await event,p=resolve(OUT,name);await d.saveAs(p);const raw=readFileSync(p);return{rows:csv(raw.toString('utf8')),sha256:sha(raw)};}
async function open(browser,width,folder,{corrupt=false,reducedMotion=false,mobile=false,height=1000}={}){
  const context=await browser.newContext({viewport:{width,height},acceptDownloads:true,reducedMotion:reducedMotion?'reduce':'no-preference',
    ...(mobile?{isMobile:true,hasTouch:true,deviceScaleFactor:2.625,userAgent:'Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/159.0.0.0 Mobile Safari/537.36'}:{})}),page=await context.newPage(),errors=[],requests=[];
  page.on('pageerror',e=>errors.push(e.message));
  await context.route('**/*',route=>{const u=route.request().url();requests.push(u);
    if(u.startsWith(origin+'/')){
      const pathname=new URL(u).pathname;
      const manifest=(corrupt==='dc-manifest'&&pathname.endsWith('/contracts/dc-locations.v930.json'))||(corrupt==='price-manifest'&&pathname.endsWith('/contracts/prices.v931.json'));
      const module=(corrupt==='dc-module'&&pathname.endsWith('/automation/dc_location_ui/'+locationSpec.producer.commit+'/actions.mjs'))||(corrupt==='price-module'&&pathname.endsWith('/automation/price_daily_ui/'+priceSpec.producer.commit+'/view.mjs'));
      if(manifest||module){const raw=readFileSync(resolve(ROOT,'.'+pathname));return route.fulfill({status:200,contentType:module?'text/javascript':'application/json',body:Buffer.concat([raw,Buffer.from(' ')])});}
      return route.continue();
    }
    if(sourceBytes.has(u)){let raw=sourceBytes.get(u);if((corrupt===true&&u===catalogue.layers.find(l=>l.id==='substations').data.url)||(corrupt==='dc-source'&&u===locationSpec.input.url)||(corrupt==='price-index'&&u===priceSpec.input.base+'index.json')||(corrupt==='price-year'&&u===priceSpec.input.base+'2026.json'))raw=Buffer.concat([raw,Buffer.from(' ')]);return route.fulfill({status:200,content  … [line shortened here: 493 characters; full line on GitHub]
  await context.addInitScript(()=>{
    window.__pricePaths=[];window.__priceLabels=[];window.__priceHollow=0;const paths=new WeakMap(),arcs=new WeakMap();
    for(const name of ['beginPath','moveTo','lineTo','stroke','fillText','arc','fill']){const original=CanvasRenderingContext2D.prototype[name];CanvasRenderingContext2D.prototype[name]=function(...args){
      if(this.canvas.closest('.pn-daily-prices')){
        if(name==='beginPath'){paths.set(this,[]);arcs.delete(this);}
        if(name==='moveTo'||name==='lineTo'){const p=paths.get(this)||[];p.push({kind:name,x:args[0],y:args[1]});paths.set(this,p);}
        if(name==='stroke'&&['#00ffff','#ffcc00','#ff3333'].includes(this.strokeStyle)&&(paths.get(this)||[]).length)window.__pricePaths.push({color:this.strokeStyle,points:paths.get(this).map(p=>({...p}))});
        if(name==='fillText')window.__priceLabels.push(String(args[0]));
        if(name==='arc')arcs.set(this,args[2]);
        if(name==='fill'&&arcs.get(this)===3&&this.fillStyle==='#05070c')window.__priceHollow++;
      }return original.apply(this,args);
    };}
  });
  await page.goto(urlFor(folder),{waitUntil:'domcontentloaded'});await page.waitForFunction(()=>Number(document.getElementById('tbody')?.dataset.total)>0);
  return{context,page,errors,requests};
}
async function fullWidth(page){
  const layout=await page.evaluate(()=>{const main=document.querySelector('main'),r=main.getBoundingClientRect(),s=getComputedStyle(main),b=getComputedStyle(document.body),h=getComputedStyle(document.documentElement);return{viewport:innerWidth,mainLeft:r.left,mainWidth:r.width,mainMarginLeft:s.marginLeft,documentWidth:document.documentElement.scrollWidth,mainOverflowY:s.overflowY,bodyDisplay:b.dis  … [line shortened here: 563 characters; full line on GitHub]
  assert.equal(layout.asideCount,0,'removed sidebar has no visible or hidden DOM remnant');assert.ok(Math.abs(layout.mainLeft)<=1,'main begins at viewport left: '+JSON.stringify(layout));assert.ok(Math.abs(layout.mainWidth-layout.viewport)<=2,'main uses full viewport width: '+JSON.stringify(layout));assert.ok(layout.documentWidth<=layout.viewport+2,'document has no lateral overflow: '+JSON.stringi  … [line shortened here: 589 characters; full line on GitHub]
  return layout;
}
async function painted(page,selector){
  const target=page.locator(selector).first();await target.scrollIntoViewIfNeeded();
  const paint=await target.evaluate(n=>{
    const r=n.getBoundingClientRect(),s=getComputedStyle(n);
    let left=Math.max(0,r.left),right=Math.min(innerWidth,r.right),top=Math.max(0,r.top),bottom=Math.min(innerHeight,r.bottom);
    // A wide table row may begin offscreen after native horizontal scrolling.
    // Test the visible intersection, including the scroll container's borders.
    for(let a=n.parentElement;a;a=a.parentElement){
      if(a===document.documentElement)continue; // Root scrolling clips to the viewport above.
      const style=getComputedStyle(a),box=a.getBoundingClientRect();
      if(/auto|scroll|hidden|clip/.test(style.overflowX)){left=Math.max(left,box.left+a.clientLeft);right=Math.min(right,box.left+a.clientLeft+a.clientWidth);}
      if(/auto|scroll|hidden|clip/.test(style.overflowY)){top=Math.max(top,box.top+a.clientTop);bottom=Math.min(bottom,box.top+a.clientTop+a.clientHeight);}
    }
    const x=(left+right)/2,y=(top+bottom)/2,hit=right>left&&bottom>top?document.elementFromPoint(x,y):null;
    return{width:r.width,height:r.height,top:r.top,left:r.left,visible:{left,right,top,bottom},hitPoint:{x,y},display:s.display,visibility:s.visibility,opacity:s.opacity,text:n.textContent.trim().slice(0,120),hit:!!hit&&(n===hit||n.contains(hit)),viewport:{width:innerWidth,height:innerHeight}};
  });
  assert.ok(paint.width>0&&paint.height>0&&paint.display!=='none'&&paint.visibility==='visible'&&Number(paint.opacity)>0&&paint.text.length>0&&paint.hit,'visible painted target '+selector+': '+JSON.stringify(paint));return paint;
}
async function settleTouch(page){await page.evaluate(async()=>{let previous='',stable=0;const end=performance.now()+2500;while(performance.now()<end){await new Promise(requestAnimationFrame);const state=[scrollY,visualViewport.pageTop,...[...document.querySelectorAll('.tablewrap')].map(n=>n.scrollLeft)].join('|');if(state===previous)stable++;else stable=0;previous=state;if(stable>=8)return;}});}
async function touchTap(page,selector){await settleTouch(page);await page.locator(selector).first().tap();}
async function touchDrag(session,{x,y,dx=0,dy=0}){
  await session.send('Input.dispatchTouchEvent',{type:'touchStart',touchPoints:[{x,y,id:1,radiusX:2,radiusY:2,force:1}]});
  for(let step=1;step<=10;step++){await session.send('Input.dispatchTouchEvent',{type:'touchMove',touchPoints:[{x:x+dx*step/10,y:y+dy*step/10,id:1,radiusX:2,radiusY:2,force:1}]});await new Promise(r=>setTimeout(r,16));}
  await session.send('Input.dispatchTouchEvent',{type:'touchEnd',touchPoints:[]});
}
async function orientationScreenshot(session,name,size){
  // Playwright's screenshot helper restores its cached context viewport. Capture
  // directly through CDP so synthetic landscape metrics remain unchanged.
  const result=await session.send('Page.captureScreenshot',{format:'png',fromSurface:true,captureBeyondViewport:false});
  const png=Buffer.from(result.data,'base64'),width=png.readUInt32BE(16),height=png.readUInt32BE(20);
  assert.ok(Math.abs(width/height-size.width/size.height)<.005,'PNG must match actual requested orientation: '+JSON.stringify({name,width,height,requested:size}));
  writeFileSync(resolve(OUT,name),png);return{file:name,width,height,sha256:sha(png)};
}
async function tab(page,id){await page.locator('#'+id).click();await page.waitForFunction(id=>document.getElementById(id)?.getAttribute('aria-selected')==='true',id);const panel=await page.locator('#'+id).getAttribute('aria-controls');assert.equal(await page.locator('#'+panel).isVisible(),true);}
async function allRepd(page){await tab(page,'solarTab');await page.locator('#clearFilters').click();await page.waitForFunction(()=>document.getElementById('tbody')?.dataset.total==='7775');}
async function dcOriginalLinks(page){return page.locator('#datacentreHost tbody tr').evaluateAll(rows=>Object.fromEntries(rows.map(row=>[row.querySelector('.ggdc-id')?.textContent.trim(),[...row.querySelectorAll('a')].filter(a=>!a.closest('.ggdc-location-actions')).map(a=>a.href)])));}
async function dcGlobal(page){await page.locator('#datacentreHost').getByRole('button',{name:/^Global leads/}).click();await page.waitForFunction(()=>document.querySelectorAll('#datacentreHost tbody tr').length===100);}
async function verifyLocations(page,width){
  await page.waitForFunction(()=>document.getElementById('datacentreHost')?.dataset.locationsState==='available');
  assert.equal(await page.locator('#datacentreHost .ggdc-screen-actions').count(),34);
  await dcGlobal(page);await page.waitForFunction(()=>document.querySelectorAll('#datacentreHost .ggdc-reported-address').length===38);
  assert.equal(await page.locator('#datacentreHost .ggdc-reported-address > p').count(),39);
  const actual=await page.locator('#datacentreHost tbody tr').evaluateAll(rows=>rows.map(row=>({id:row.querySelector('.ggdc-id')?.textContent.trim(),addresses:[...row.querySelectorAll('.ggdc-reported-address > p')].map(n=>n.textContent),screen:!!row.querySelector('.ggdc-screen-actions')})));
  for(const row of actual){const feature=byId.get(row.id);assert.ok(feature,'exact original ID');assert.deepEqual(row.addresses,feature.properties.addresses.map(a=>a.text));assert.equal(row.screen,!!feature.geometry&&feature.properties.country.code==='GB');}
  assert.equal(actual.filter(x=>x.screen).length,34);assert.deepEqual(await dcOriginalLinks(page),baselineDCLinks);
  assert.equal(await page.locator('#datacentreHost .ggdc-screen-location').allTextContents().then(x=>x.filter(v=>v.startsWith('Approx. postcode:')).length),25);
  assert.equal(await page.locator('#datacentreHost .ggdc-screen-footnote').count(),1);assert.match(await page.locator('#datacentreHost .ggdc-screen-footnote').innerText(),/UK screening coverage.*not a grid-capacity assessment/);
  const disclosure=page.locator('#datacentreHost .ggdc-location-sources');assert.equal(await disclosure.count(),1);assert.equal(await disclosure.getAttribute('open'),null);
  await disclosure.locator('summary').click();const text=await disclosure.innerText();for(const credit of [...new Set(locationData.features.flatMap(f=>f.properties.location_precision==='POSTCODE_CENTROID_APPROXIMATE'?f.properties.geometry_attribution:[]))])assert.ok(text.includes(credit));
  assert.equal(await disclosure.getByRole('link',{name:'Source GeoJSON (100 records)'}).getAttribute('href'),locationSpec.input.url);
  assert.equal(await disclosure.getByRole('link',{name:'Postcode-provider terms'}).getAttribute('href'),'https://postcodes.io/docs/licences/');await disclosure.locator('summary').click();
  const exported=await download(page,page.locator('#datacentreHost button.ggdc-download'),`v931-dc-global-${width}.csv`);assert.deepEqual(exported.rows,baselineDCCsv.rows,'optional locations never rewrite original100-record CSV');
  const search=page.getByRole('searchbox',{name:'Search Data Centre records'});
  for(const feature of [locationData.features.find(f=>f.properties.country.code!=='GB'&&f.properties.addresses.length),locationData.features.find(f=>!f.geometry&&f.properties.addresses.length)]){
    assert.ok(feature,'real foreign/null-geometry address fixture exists');await search.fill(feature.id);await page.waitForFunction(()=>document.querySelectorAll('#datacentreHost tbody tr').length===1);
    assert.deepEqual(await page.locator('#datacentreHost .ggdc-reported-address > p').allTextContents(),feature.properties.addresses.map(a=>a.text));assert.equal(await page.locator('#datacentreHost .ggdc-screen-actions').count(),0);
  }
  await search.fill('CyrusOne LON1');await page.waitForFunction(()=>document.querySelectorAll('#datacentreHost .ggdc-screen-actions').length===1);assert.match(await page.locator('#datacentreHost .ggdc-screen-location').innerText(),/Approx\. postcode/);
  await tab(page,'solarTab');await tab(page,'datacentreTab');assert.equal(await search.inputValue(),'CyrusOne LON1');assert.equal(await page.locator('#datacentreHost .ggdc-location-sources').count(),1);assert.equal(await page.locator('#datacentreHost .ggdc-screen-footnote').count(),1);
  await search.fill('');await page.waitForFunction(()=>document.querySelectorAll('#datacentreHost .ggdc-reported-address').length===38);
  await painted(page,'#datacentreHost tbody tr');await page.screenshot({path:resolve(OUT,`v931-dc-global-${width}.png`)});
  pass('actual host100ID join/38addressrecords/39statements/34GBScreen/source links and originalCSV preserved across filters',{width});
}
async function resetPriceTrace(page){await page.evaluate(()=>{window.__pricePaths=[];window.__priceLabels=[];window.__priceHollow=0;});}
async function priceRange(page,end,days='30'){
  await resetPriceTrace(page);await page.getByLabel('Daily window',{exact:true}).selectOption(days);
  await page.getByLabel('Window end date',{exact:true}).fill(end);await page.getByLabel('Window end date',{exact:true}).dispatchEvent('change');
  await page.waitForFunction(()=>document.querySelector('.pn-daily-prices')?.dataset.state==='available');
}
async function assertPriceDrawing(page,rows){
  await page.evaluate(()=>new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r))));
  const actual=await page.locator('#pricesLayerHost canvas').evaluate(canvas=>{
    const r=canvas.getBoundingClientRect(),pixels=canvas.getContext('2d').getImageData(0,0,canvas.width,canvas.height).data;let colored=0;
    for(let i=0;i<pixels.length;i+=4)if(pixels[i+1]>150&&(pixels[i]>150||pixels[i+2]>150))colored++;
    return{series:JSON.parse(canvas.dataset.series),paths:window.__pricePaths,labels:window.__priceLabels,hollow:window.__priceHollow,canvas:{width:r.width,height:r.height,backingWidth:canvas.width,backingHeight:canvas.height,colored}};
  });
  const fields=[['maximum_observed_gbp_per_mwh','#ffcc00'],['mean_available_gbp_per_mwh','#00ffff'],['minimum_observed_gbp_per_mwh','#ff3333']];
  for(const [field,color] of fields){const groups=priceModel.segments(rows,field),receipt=actual.series.find(s=>s.field===field);assert.deepEqual(receipt.segments,groups.map(g=>g.map(p=>p.date)));
    const draws=actual.paths.filter(p=>p.color===color).slice(-groups.length);assert.deepEqual(draws.map(p=>p.points.length),groups.map(g=>g.length),'actual Canvas2D paths preserve each source gap');
    assert.ok(draws.every(p=>p.points[0].kind==='moveTo'&&p.points.slice(1).every(q=>q.kind==='lineTo')));
  }
  assert.ok(actual.canvas.width>=240&&actual.canvas.height>=300&&actual.canvas.colored>100,'actual chart paints visible colored pixels');return actual;
}
async function verifyPrices(page,width,requests){
  assert.equal(requests.filter(u=>u.startsWith(priceSpec.input.base)).length,0,'price source remains lazy until the owner category is opened');
  await tab(page,'pricesTab');await page.waitForFunction(()=>document.querySelector('#pricesLayerHost .pn-daily-prices')?.dataset.state==='available');
  assert.equal(await page.locator('#pricesLayerHost .pn-daily-prices').count(),1);assert.equal(await page.locator('#pricesLayerHost iframe').count(),0);
  assert.match(await page.locator('#pricesLayerHost .pnd-source').innerText(),/Latest source date: 2026-10-31.*historical Elexon system-sell.*GBP\/MWh/);
  assert.match(await page.locator('#pricesLayerHost .pnd-note').innerText(),/source-declared.*Complete source-day coverage does not certify stored UTC alignment/);
  assert.match(await page.locator('#pricesLayerHost .pnd-quality').innerText(),/106,668.*without timestamp repair/);
  assert.match(await page.locator('#pricesLayerHost .pnd-status').innerText(),/^2026-10-02 to 2026-10-31/);
  assert.deepEqual(requests.filter(u=>u.startsWith(priceSpec.input.base)).map(u=>u.slice(priceSpec.input.base.length)),['index.json','2026.json'],'only index and selected source year load');
  const defaultRows=priceYears.get(2026).rows.filter(r=>r.date>='2026-10-02'),drawing=await assertPriceDrawing(page,defaultRows);assert.ok(drawing.labels.some(t=>/LOW £-28\.49/.test(t)),'actual negative observed low remains a negative GBP chart annotation');
  assert.match(await page.locator('#pricesLayerHost .pnd-stats').innerText(),/-28\.49/);
  await page.locator('#pricesLayerHost canvas').scrollIntoViewIfNeeded();await page.screenshot({path:resolve(OUT,`v931-prices-default-${width}.png`)});
  const disclosure=page.locator('#pricesLayerHost .pn-daily-prices > details');assert.equal(await disclosure.getAttribute('open'),null);await disclosure.locator('summary').click();
  assert.equal(await disclosure.getByRole('link',{name:'Pinned data index',exact:true}).getAttribute('href'),priceSpec.input.base+'index.json');assert.match(await disclosure.innerText(),/unweighted mean of available daily means.*Partial days can affect/);
  const original=page.locator('#pricesPanel').getByRole('link',{name:'Open the original electricity workspace',exact:true});assert.equal(await original.getAttribute('href'),'https://globalgrid2050.com/uk_energy_tracking_v6/');assert.equal(await original.getAttribute('target'),'_blank');
  await priceRange(page,'2026-07-04');await page.waitForFunction(()=>document.querySelector('.pnd-status').textContent.startsWith('2026-06-05 to 2026-07-04'));
  const gapRows=priceYears.get(2026).rows.filter(r=>r.date>='2026-06-05'&&r.date<='2026-07-04'),gap=await assertPriceDrawing(page,gapRows);assert.equal(gap.series[1].segments.length,2);assert.ok(gap.hollow>=3,'partial day is drawn with hollow markers in every series');
  assert.match(await page.locator('#pricesLayerHost .pnd-coverage').innerText(),/16 complete source days.*1 partial.*13 missing/);
  assert.equal(await page.locator('#pricesLayerHost tbody tr').filter({hasText:'NO_OBSERVATIONS'}).count(),13);assert.equal(await page.locator('#pricesLayerHost tbody tr').filter({hasText:'PARTIAL_SOURCE_DAY'}).count(),1);
  await page.locator('#pricesLayerHost canvas').scrollIntoViewIfNeeded();await page.screenshot({path:resolve(OUT,`v931-prices-gap-${width}.png`)});
  // No UI window is short enough to contain only the thirteen missing days.
  // Exercise the same imported canvas runtime against those actual owner rows.
  const missingRows=priceYears.get(2026).rows.filter(r=>r.date>='2026-06-18'&&r.date<='2026-06-30');
  const empty=await page.evaluate(async({url,rows})=>{const {drawDaily}=await import(url),host=document.getElementById('pricesLayerHost'),canvas=document.createElement('canvas');host.querySelector('.pn-daily-prices').append(canvas);canvas.style.width='300px';canvas.style.height='350px';window.__pricePaths=[];window.__priceLabels=[];const result=drawDaily(canvas,{start:'2026-06-18',end:'2026-06-30'  … [line shortened here: 624 characters; full line on GitHub]
  assert.equal(empty.paths,0);assert.ok(empty.result.every(s=>s.segments.length===0));assert.ok(empty.labels.includes('No reported prices in this window'));
  await page.getByLabel('Source year',{exact:true}).selectOption('2025');await page.waitForFunction(()=>document.querySelector('.pnd-status').textContent.startsWith('2025-01-01 to 2025-12-31'));assert.equal(await page.getByLabel('Daily window',{exact:true}).inputValue(),'year');assert.equal(await page.locator('#pricesLayerHost tbody tr').count(),365);
  await priceRange(page,'2099-01-01');assert.equal(await page.getByLabel('Window end date',{exact:true}).inputValue(),'2026-10-31');await page.waitForFunction(()=>document.querySelector('.pnd-status').textContent.startsWith('2026-10-02 to 2026-10-31'));
  assert.equal(requests.filter(u=>u===priceSpec.input.base+'2026.json').length,1,'returning to accepted 2026 reuses immutable cache');assert.equal(requests.filter(u=>u===priceSpec.input.base+'2025.json').length,1);
  await tab(page,'solarTab');await tab(page,'pricesTab');assert.equal(await page.locator('#pricesLayerHost .pn-daily-prices').count(),1);assert.equal(requests.filter(u=>u===priceSpec.input.base+'index.json').length,1,'returning category reuses accepted index');
  await fullWidth(page);pass('historical daily host lazy index/year cache, actual Canvas2D negative/gapped/partial/empty paths, source clocks and bounded year/date controls',{width,defaultDays:30,gapMissingDays:13,actualAllMissingRuntimeProbe:true});
}
let browser;
try{
  browser=await chromium.launch({headless:true});receipt.browser=browser.version();
  if(!process.env.V931_ROTATION_ONLY){
  const b=await open(browser,1440,baseline);await allRepd(b.page);await b.page.waitForFunction(()=>!/^loading/i.test(document.getElementById('newsMeta')?.textContent||'loading'));
  const oldCsv=await download(b.page,b.page.locator('#exportInline'),'v929-all.csv');assert.equal(oldCsv.rows.length,7776);
  await tab(b.page,'datacentreTab');await b.page.waitForFunction(()=>document.querySelectorAll('#datacentreHost tbody tr').length===54);await dcGlobal(b.page);baselineDCLinks=await dcOriginalLinks(b.page);baselineDCCsv=await download(b.page,b.page.locator('#datacentreHost button.ggdc-download'),'v929-dc-global.csv');await b.context.close();
  pass('frozen V9.30 browser CSV establishes complete original population',{rows:7775,sha256:oldCsv.sha256});
  for(const width of [390,393,1440]){
    const {context,page,errors,requests}=await open(browser,width,candidate);
    assert.equal(await page.locator('main > section').count(),2);
    const fullWidthLayout=await fullWidth(page);await painted(page,'.release-header');
    assert.deepEqual((await page.locator('main > section').evaluateAll(nodes=>nodes.map(n=>n.querySelector('h2')?.textContent.replace(/\s+/g,' ').trim().toUpperCase()))),['GLOBALGRID2050 HEADLINES','REPD PIPELINE ANALYTICS']);
    assert.deepEqual((await page.locator('.pipeline-tabs > [role=tab]').allTextContents()).map(x=>x.trim()),['Solar','BESS','Grid','Data Centres','Offtakers','Prices']);
    assert.equal(requests.filter(u=>sourceBytes.has(u)).length,0,'asset source layers remain lazy before selection');
    await page.waitForFunction(()=>document.getElementById('tbody')?.dataset.total==='3604');
    await tab(page,'bessTab');assert.ok((await page.locator('#tbody tr .badge').allTextContents()).every(t=>/battery/i.test(t)));
    await allRepd(page);await page.locator('#search').fill('8162');await page.waitForFunction(()=>document.getElementById('repd-8162'));
    const receiver=await import(pathToFileURL(resolve(baseline,'scripts/core/atlas-receiver-v9-7.js'))),m=JSON.parse(readFileSync(resolve(baseline,'data/v9.1/build_manifest.json')));
    const row=m.project_partitions.flatMap(p=>JSON.parse(readFileSync(resolve(baseline,p.path))).projects).find(p=>String(p.repd_ref)==='8162');
    assert.equal(await page.locator('#repd-8162 a.atlaslink').getAttribute('href'),receiver.buildAtlasDeepLinkV9_7(row));
    await allRepd(page);await page.waitForFunction(()=>!/^loading/i.test(document.getElementById('newsMeta')?.textContent||'loading'));
    if(width===1440){const actual=await download(page,page.locator('#exportInline'),'v931-all.csv');assert.deepEqual(actual.rows,oldCsv.rows);pass('all 7,775 exported CSV rows/fields/order equal frozen V9.30',{sha256:actual.sha256});}
    await page.waitForFunction(()=>document.querySelectorAll('#headlineTicker ul:not([aria-hidden]) li').length===10);
    assert.equal(await page.locator('#newsStatus').getAttribute('data-state'),'snapshot');
    const tickerLabel=await page.locator('#headlineTicker .pn-ticker-label').textContent();
    assert.match(tickerLabel,/Latest available.*source unavailable.*saved snapshot collected.*articles may be older/i);
    const sourceClock=JSON.parse(readFileSync(resolve(candidate,'news/snapshot-provenance.json'))).generated_at;
    const clock=new Date(sourceClock),clockLabel=clock.toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric',timeZone:'UTC'})+' '+String(clock.getUTCHours()).padStart(2,'0')+':'+String(clock.getUTCMinutes()).padStart(2,'0')+' UTC';
    assert.ok(tickerLabel.includes(clockLabel),'ticker preserves original source collection clock');
    const headlineItems=JSON.parse(readFileSync(resolve(candidate,'news/pipeline_headlines.snapshot.json'))).items;
    const sourceLinks=new Set(headlineItems.map(x=>x.link));
    for(const a of await page.locator('#headlineTicker ul:not([aria-hidden]) a').all())assert.ok(sourceLinks.has(await a.getAttribute('href')));
    assert.equal(await page.locator('#headlineTicker a').first().evaluate(n=>getComputedStyle(n).color),'rgb(255, 85, 85)');
    await page.locator('#headlineTicker button').click();assert.equal(await page.locator('#headlineTicker').evaluate(n=>n.classList.contains('pn-paused')),true);
    await tab(page,'gridTab');await page.waitForFunction(()=>document.querySelector('#gridLayerHost .pn-count')?.textContent.includes('5,800'));
    assert.match(await page.locator('#gridLayerHost .pn-count').innerText(),/4,460 source names/);assert.equal(await page.locator('#gridLayerHost tbody tr').count(),100);
    await page.locator('#gridLayerHost').getByRole('button',{name:'Next',exact:true}).click();assert.match(await page.locator('#gridLayerHost .pn-tools').last().innerText(),/Page 2/);
    const search=page.locator('#gridLayerHost input[type=search]');await search.fill('grid_substations:0');assert.match(await page.locator('#gridLayerHost tbody').innerText(),/Name not recorded/);
    await search.fill('Barrow');const selected=await download(page,page.locator('#gridLayerHost').getByRole('button',{name:'Export results'}),`substations-search-${width}.csv`);assert.ok(selected.rows.length>1);
    const map=new URL(await page.locator('#gridLayerHost tbody a').first().getAttribute('href'));assert.equal(map.searchParams.has('repd_ref'),false);assert.equal(map.searchParams.has('capacity_mw'),false);assert.ok(map.searchParams.has('longitude')&&map.searchParams.has('latitude'));
    await search.fill('');await page.locator('#gridLayerHost').getByRole('button',{name:'2D locations'}).click();assert.equal(await page.locator('#gridLayerHost canvas').isVisible(),true);
    await page.locator('#gridLayerHost').getByRole('button',{name:'Analytics',exact:true}).click();assert.ok(await page.locator('#gridLayerHost meter').count()>0);
    await page.locator('#gridLayerHost').getByRole('tab',{name:'Grid Projects',exact:true}).click();await page.waitForFunction(()=>document.querySelector('#gridLayerHost .pn-panel').textContent.includes('No independently approved'));
    assert.equal(await page.locator('#gridLayerHost tbody tr').count(),0);
    await tab(page,'offtakersTab');await page.waitForFunction(()=>document.querySelector('#offtakersLayerHost .pn-count')?.textContent.includes('1,568'));
    const offtakersCsv=await download(page,page.locator('#offtakersLayerHost').getByRole('button',{name:'Export results'}),`offtakers-${width}.csv`);
    assert.equal(offtakersCsv.rows.length,1569);assert.ok(offtakersCsv.rows[0].includes('Source record'));const exported=JSON.stringify(offtakersCsv.rows);assert.match(exported,/ODbL/);assert.match(exported,/OGL/);assert.match(exported,/NAEI/);
    await verifyPrices(page,width,requests);
    await tab(page,'datacentreTab');await page.waitForFunction(()=>document.querySelectorAll('#datacentreHost .ggdc-table tbody tr').length===54);
    await verifyLocations(page,width);
    await tab(page,'gridTab');await page.locator('#gridLayerHost').getByRole('tab',{name:'Substations',exact:true}).click();await page.waitForFunction(()=>document.querySelector('#gridLayerHost .pn-count')?.textContent.includes('5,800'));
    assert.equal(requests.filter(u=>u===catalogue.layers.find(l=>l.id==='substations').data.url).length,1,'returning to Grid reuses pinned source cache');
    await page.locator('#pricesTab').focus();await page.keyboard.press('Home');assert.equal(await page.locator('#solarTab').evaluate(n=>n===document.activeElement),true);
    await page.waitForFunction(()=>document.getElementById('tbody')?.dataset.total==='3604');
    const geometry=await page.evaluate(()=>({viewport:innerWidth,width:document.documentElement.scrollWidth,font:getComputedStyle(document.body).fontFamily}));assert.ok(geometry.width<=width+2);assert.match(geometry.font,/mono|courier/i);
    await page.screenshot({path:resolve(OUT,`v931-solar-${width}.png`)});await tab(page,'gridTab');await page.screenshot({path:resolve(OUT,`v931-grid-${width}.png`)});
    assert.deepEqual(errors,[]);pass('integrated categories, provenance, ticker, search/CSV/MAP, cache and controls',{width,substations:5800,named:4460,unnamed:1340,offtakers:1568,geometry,fullWidthLayout});await context.close();
  }
  }
  const rotating=await open(browser,390,candidate,{mobile:true,height:844});
  await tab(rotating.page,'datacentreTab');await rotating.page.waitForFunction(()=>document.getElementById('datacentreHost')?.dataset.locationsState==='available');await dcGlobal(rotating.page);
  await rotating.page.getByRole('searchbox',{name:'Search Data Centre records'}).fill('CyrusOne LON1');await rotating.page.waitForFunction(()=>document.querySelectorAll('#datacentreHost .ggdc-screen-actions').length===1);
  await rotating.page.locator('.ggdc-reported-address summary').tap();
  const session=await rotating.context.newCDPSession(rotating.page),states=[];
  for(const [name,size] of [['portrait',{width:390,height:844}],['landscape',{width:915,height:412}],['portrait-return',{width:390,height:844}]]){
    await rotating.page.setViewportSize(size);
    await session.send('Emulation.setDeviceMetricsOverride',{...size,screenWidth:size.width,screenHeight:size.height,deviceScaleFactor:2.625,mobile:true,screenOrientation:{type:name==='landscape'?'landscapePrimary':'portraitPrimary',angle:name==='landscape'?90:0}});
    await rotating.page.waitForFunction(size=>Math.abs(innerWidth-size.width)<=1&&Math.abs(innerHeight-size.height)<=2,size);
    const layout=await fullWidth(rotating.page),paint=await painted(rotating.page,'#datacentreHost .ggdc-reported-address > p');
    assert.equal(await rotating.page.getByRole('searchbox',{name:'Search Data Centre records'}).inputValue(),'CyrusOne LON1');assert.equal(await rotating.page.locator('.ggdc-reported-address').getAttribute('open'),'');
    assert.equal(await rotating.page.locator('#datacentreHost .ggdc-screen-actions').count(),1);assert.equal(await rotating.page.locator('#datacentreHost .ggdc-screen-footnote').count(),1);assert.equal(await rotating.page.locator('#datacentreHost .ggdc-location-sources').count(),1);
    const screenshot=await orientationScreenshot(session,`v931-dc-${name}.png`,size);states.push({name,...size,layout,paint,screenshot});
  }
  assert.deepEqual(rotating.errors,[]);await rotating.context.close();pass('Android-UA/touch-emulated DC portrait-landscape-return preserves address disclosure/search/Screen/onefooter',{states,actualHandset:false});
  const priceRotation=await open(browser,393,candidate,{mobile:true,height:851});await tab(priceRotation.page,'pricesTab');await priceRotation.page.waitForFunction(()=>document.querySelector('.pn-daily-prices')?.dataset.state==='available');
  await priceRange(priceRotation.page,'2026-07-04');await priceRotation.page.waitForFunction(()=>document.querySelector('.pnd-status').textContent.startsWith('2026-06-05 to 2026-07-04'));
  const priceSession=await priceRotation.context.newCDPSession(priceRotation.page),priceStates=[];
  for(const [name,size] of [['portrait',{width:393,height:851}],['landscape',{width:915,height:412}],['portrait-return',{width:393,height:851}]]){
    await priceRotation.page.setViewportSize(size);await priceSession.send('Emulation.setDeviceMetricsOverride',{...size,screenWidth:size.width,screenHeight:size.height,deviceScaleFactor:2.625,mobile:true,screenOrientation:{type:name==='landscape'?'landscapePrimary':'portraitPrimary',angle:name==='landscape'?90:0}});
    await priceRotation.page.waitForFunction(size=>Math.abs(innerWidth-size.width)<=1&&Math.abs(innerHeight-size.height)<=2,size);const layout=await fullWidth(priceRotation.page);
    assert.equal(await priceRotation.page.getByLabel('Window end date',{exact:true}).inputValue(),'2026-07-04');assert.equal(await priceRotation.page.locator('#pricesLayerHost .pn-daily-prices').count(),1);
    const chart=await assertPriceDrawing(priceRotation.page,priceYears.get(2026).rows.filter(r=>r.date>='2026-06-05'&&r.date<='2026-07-04'));await priceRotation.page.locator('#pricesLayerHost canvas').scrollIntoViewIfNeeded();
    const screenshot=await orientationScreenshot(priceSession,`v931-prices-${name}.png`,size);priceStates.push({name,...size,layout,canvas:chart.canvas,screenshot});
  }
  assert.deepEqual(priceRotation.errors,[]);await priceRotation.context.close();pass('Android-UA/touch-emulated Prices rotation keeps one painted gap chart and selected source window',{states:priceStates,actualHandset:false});
  for(const corrupt of ['price-manifest','price-module','price-index','price-year']){
    const test=await open(browser,393,candidate,{corrupt});await tab(test.page,'pricesTab');await test.page.waitForFunction(()=>document.getElementById('pricesLayerHost')?.dataset.priceState==='unavailable');
    assert.equal(await test.page.locator('#pricesLayerHost canvas:visible').count(),0);assert.equal(await test.page.locator('#pricesLayerHost tbody tr').count(),0);assert.equal(await test.page.locator('#pricesLayerHost .pnd-stats:not([hidden])').count(),0);
    assert.equal(await test.page.locator('#pricesPanel').getByRole('link',{name:'Open the original electricity workspace',exact:true}).getAttribute('href'),'https://globalgrid2050.com/uk_energy_tracking_v6/');
    await allRepd(test.page);assert.equal(await test.page.locator('#tbody').getAttribute('data-total'),'7775');await tab(test.page,'datacentreTab');await test.page.waitForFunction(()=>document.getElementById('datacentreHost')?.dataset.locationsState==='available');
    assert.equal(await test.page.locator('#datacentreHost tbody tr').count(),54);assert.equal(await test.page.locator('#datacentreHost .ggdc-screen-actions').count(),34);await dcGlobal(test.page);assert.deepEqual(await dcOriginalLinks(test.page),baselineDCLinks);
    assert.deepEqual(test.errors,[]);await test.context.close();pass('price corruption withholds chart/results while all REPD rows, original workspace and DC locations/maps remain usable',{corrupt});
  }
  for(const corrupt of ['dc-manifest','dc-module','dc-source']){
    const test=await open(browser,390,candidate,{corrupt});await tab(test.page,'datacentreTab');await test.page.waitForFunction(()=>document.getElementById('datacentreHost')?.dataset.locationsState==='unavailable');
    assert.equal(await test.page.locator('#datacentreHost tbody tr').count(),54);assert.equal(await test.page.locator('#datacentreHost .ggdc-location-actions').count(),0);assert.equal(await test.page.locator('#datacentreHost .ggdc-screen-footnote').count(),0);
    assert.match(await test.page.locator('#datacentreHost .dc-location-status').innerText(),/Additional location data unavailable/);await dcGlobal(test.page);assert.deepEqual(await dcOriginalLinks(test.page),baselineDCLinks);
    await test.page.getByRole('searchbox',{name:'Search Data Centre records'}).fill('CyrusOne LON1');await test.page.waitForFunction(()=>document.querySelectorAll('#datacentreHost tbody tr').length===1);await allRepd(test.page);assert.equal(await test.page.locator('#tbody').getAttribute('data-total'),'7775');assert.deepEqual(test.errors,[]);await test.context.close();
    pass('optional location corruption fails closed without changing original DC controls/maps or REPD',{corrupt});
  }
  const bad=await open(browser,393,candidate,{corrupt:true,reducedMotion:true});await tab(bad.page,'gridTab');await bad.page.waitForFunction(()=>document.querySelector('#gridLayerHost .pn-panel')?.dataset.state==='unavailable');assert.equal(await bad.page.locator('#gridLayerHost tbody tr').count(),0);
  await allRepd(bad.page);assert.equal(await bad.page.locator('#tbody').getAttribute('data-total'),'7775');await tab(bad.page,'offtakersTab');await bad.page.waitForFunction(()=>document.querySelector('#offtakersLayerHost .pn-count')?.textContent.includes('1,568'));
  await bad.page.waitForFunction(()=>document.querySelector('#headlineTicker .pn-ticker-track'));assert.equal(await bad.page.locator('#headlineTicker .pn-ticker-track').evaluate(n=>getComputedStyle(n).animationName),'none');assert.deepEqual(bad.errors,[]);await bad.context.close();
  pass('corrupt pinned substation source fails closed while REPD/Offtakers remain usable; reduced motion suppresses ticker animation');receipt.status='PASS';
}catch(error){receipt.status='FAIL';receipt.failure=error.stack;throw error;}
finally{receipt.blocked_external=[...new Set(receipt.blocked_external)];writeFileSync(resolve(OUT,'browser.json'),JSON.stringify(receipt,null,2)+'\n');if(browser)await browser.close();await new Promise(r=>server.close(r));}

Contracts Test

A test in the automation folder of GlobalGrid2050 that checks Model, using SHA-256. It is built from the fixture step (`fixture`) and the actual step (`actual`).

testglobalgrid2050 / automation/v931_preview/contracts.test.mjs · lines 1–103 of 103 · Entry point · pattern fixture (shared by 30 files)

What it does
It tests its inputs. Defines sha, pin, row, fixture, actual. Uses libraries node:test, node:assert/strict, node:crypto, node:fs, node:path. Side effects: changes the web page (DOM); reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
Inputs & outputs
In: JSON file 2026.json; JSON file sources.json; Parquet file daily.parquet; JSON file index.json; JSON file 2017.json.
Downstream impact
Used directly by 1 file: GlobalGrid2050 V931 Preview Acceptance Workflow (globalgrid2050).
What it achieves
Defines `sha`, `pin`, `row` and 2 more. It reads `index.json`.
Why it matters
Run by GlobalGrid2050 V931 Preview Acceptance Workflow.
Application
globalgrid2050 · automation/v931_preview · test
Uses
Model (import), node:test, node:assert/strict, node:crypto, node:fs, node:path
Used by
run by GlobalGrid2050 V931 Preview Acceptance Workflow (workflow run)
Produces
sha, pin, row, fixture, actual
Defines here
sha, pin, row, fixture, actual
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/v931_preview/contracts.test.mjs:1-103 · blob a5c1b8a6b5830a6a83d9d8494f09bc9328f0085a · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: unknown · users: none · canonical: production_core
import test from 'node:test';
import assert from 'node:assert/strict';
import {createHash} from 'node:crypto';
import {readFileSync} from 'node:fs';
import {resolve} from 'node:path';
import {createStore} from '../price_daily_ui/78d5360239e1a5fcffa83fcb30d5937c5521acb9/model.mjs';
import {SOURCE,dateMs,expectedPeriods,validateIndex,validateYear,readPinned,segments,summarise,trailingWindow} from '../price_daily_ui/78d5360239e1a5fcffa83fcb30d5937c5521acb9/model.mjs';
const sha=raw=>createHash('sha256').update(raw).digest('hex');
const pin=path=>({path,bytes:100,sha256:'a'.repeat(64)});
const row=(date,mean,priced=48,expected=48)=>({date,expected_periods:expected,observed_periods:priced,priced_periods:priced,
 coverage_status:priced===0?'NO_OBSERVATIONS':priced===expected?'COMPLETE_SOURCE_DAY':'PARTIAL_SOURCE_DAY',utc_alignment_mismatches:0,
 price_coverage_pct:Math.round(100000000*priced/expected)/1000000,mean_available_gbp_per_mwh:mean,
 minimum_observed_gbp_per_mwh:mean===null?null:mean-10,maximum_observed_gbp_per_mwh:mean===null?null:mean+10});
function fixture(){
 const rows=[row('2026-01-01',-5),row('2026-01-02',null,0),row('2026-01-03',15,24)];
 const part={...pin('2026.json'),year:2026,calendar_days:3,observed_days:2,complete_days:1,partial_days:1,missing_days:1};
 const index={schema:'data-gb-electricity.system-sell-daily.v1.index',unit:'GBP/MWh',price_basis:'ELEXON_SYSTEM_SELL_PRICE',
  first_date:'2026-01-01',last_date:'2026-01-03',rows:3,source_periods:72,observed_periods:72,priced_periods:72,
  utc_alignment_mismatches:0,producer_sha256:'b'.repeat(64),calendar_quality:'Source-declared dates retained',sources:pin('sources.json'),parquet:pin('daily.parquet'),parts:[part]};
 const data={schema:'data-gb-electricity.system-sell-daily.v1',year:2026,unit:'GBP/MWh',price_basis:'ELEXON_SYSTEM_SELL_PRICE',rows};return {index,part,data,rows};
}
test('GB spring and autumn days are46/50; ordinary leap days48',()=>{
 assert.equal(expectedPeriods('2026-03-29'),46);assert.equal(expectedPeriods('2026-10-25'),50);assert.equal(expectedPeriods('2016-10-30'),50);assert.equal(expectedPeriods('2024-02-29'),48);
 assert.throws(()=>dateMs('2026-02-29'));assert.throws(()=>expectedPeriods('1995-01-01'));
});
test('accepted daily schema distinguishes missing, partial and complete',()=>{
 const {index,part,data}=fixture();assert.equal(validateIndex(index),index);assert.equal(validateYear(data,part,index),data.rows);
});
test('index rejects swapped basis, traversal, duplicate years and false coverage',()=>{
 for(const mutate of [i=>i.price_basis='MARKET_INDEX',i=>i.parts[0].path='../2026.json',i=>i.parts.push(i.parts[0]),i=>i.parts[0].complete_days=2,i=>i.source_periods=73,i=>i.sources.path='https://bad.example/a']){
  const {index}=fixture();mutate(index);assert.throws(()=>validateIndex(index));
 }
});
test('daily row validation rejects null-to-zero, fake completeness and impossible clocks',()=>{
 for(const mutate of [d=>d.rows[1].mean_available_gbp_per_mwh=0,d=>d.rows[2].coverage_status='COMPLETE_SOURCE_DAY',d=>d.rows[0].utc_alignment_mismatches=49,d=>d.rows[0].minimum_observed_gbp_per_mwh=100,d=>d.rows[2].date='2026-01-04']){
  const {index,part,data}=fixture();mutate(data);assert.throws(()=>validateYear(data,part,index));
 }
});
test('negative values remain prices; missing days break every series withoutzero',()=>{
 const {rows}=fixture();for(const field of ['mean_available_gbp_per_mwh','minimum_observed_gbp_per_mwh','maximum_observed_gbp_per_mwh']){
  const result=segments(rows,field);assert.deepEqual(result.map(g=>g.map(p=>p.date)),[['2026-01-01'],['2026-01-03']]);
 }
 assert.equal(segments(rows,'mean_available_gbp_per_mwh')[0][0].value,-5);
});
test('omitted calendar rows also break connected paths; realzero stays',()=>{
 const rows=[row('2026-01-01',0),row('2026-01-03',3)];const groups=segments(rows,'mean_available_gbp_per_mwh');
 assert.equal(groups.length,2);assert.equal(groups[0][0].value,0);
});
test('partial days are retained and marked; clock quality is independent',()=>{
 const {rows}=fixture();rows[0].utc_alignment_mismatches=48;
 const s=summarise(rows);assert.equal(s.clockMismatches,48);assert.equal(s.completeDays,1);assert.equal(s.partialDays,1);assert.equal(s.missingDays,1);
 assert.equal(s.dailyMean,5);assert.equal(s.priced,72);assert.equal(s.expected,144);assert.equal(s.low,-15);
 assert.equal(segments(rows,'mean_available_gbp_per_mwh')[1][0].partial,true);
});
test('all-missing windows have null summary values without an indicative baseline',()=>{
 const s=summarise([row('2026-01-01',null,0)]);assert.equal(s.dailyMean,null);assert.equal(s.high,null);assert.equal(s.low,null);
});
test('last30source days anchorOct31 even when wallclock differs',()=>{
 assert.deepEqual(trailingWindow('2026-10-31',30,'2016-01-01'),{start:'2026-10-02',end:'2026-10-31'});
 assert.deepEqual(trailingWindow('2016-01-03',30,'2016-01-01'),{start:'2016-01-01',end:'2016-01-03'});
 assert.throws(()=>trailingWindow('2026-10-31',1000,'2016-01-01'));
});
test('bounded immutable loader rejects changed, excessive and short bytes',async()=>{
 const raw=new TextEncoder().encode('{"fixture":"metadata only"}'),p={bytes:raw.length,sha256:sha(raw)},url=SOURCE.base+'2026.json';
 assert.deepEqual(await readPinned(url,p,async()=>new Response(raw)),{fixture:'metadata only'});
 await assert.rejects(readPinned(url,{...p,sha256:'0'.repeat(64)},async()=>new Response(raw)),/SHA/);
 await assert.rejects(readPinned(url,{...p,bytes:raw.length-1},async()=>new Response(raw)),/byte limit/);
 await assert.rejects(readPinned(url,{...p,bytes:raw.length+1},async()=>new Response(raw)),/exact bytes/);
});
test('invalid endpoint or bounds fail before transport; redirects andHTTPerrorsreject',async()=>{
 for(const [url,p] of [['https://127.0.0.1/',{bytes:2,sha256:'a'.repeat(64)}],[SOURCE.base+'../index.json',{bytes:2,sha256:'a'.repeat(64)}],[SOURCE.base+'index.json',{bytes:Infinity,sha256:'a'.repeat(64)}]]){
  let called=false;await assert.rejects(readPinned(url,p,async()=>{called=true;return new Response('{}');}));assert.equal(called,false);
 }
 await assert.rejects(readPinned(SOURCE.base+'index.json',{bytes:2,sha256:sha('{}')},async()=>new Response('{}',{status:503})),/HTTP/);
 await assert.rejects(readPinned(SOURCE.base+'index.json',{bytes:2,sha256:sha('{}')},async()=>({ok:true,redirected:true})),/HTTP/);
});

const actualBytes=new Map();
async function actual(name){
 if(!actualBytes.has(name))actualBytes.set(name,(async()=>{
  if(process.env.V931_PRICE_SOURCE)return readFileSync(resolve(process.env.V931_PRICE_SOURCE,name));
  const response=await fetch(SOURCE.base+name,{redirect:'error',signal:AbortSignal.timeout(15000)});assert.ok(response.ok);return Buffer.from(await response.arrayBuffer());
 })());return actualBytes.get(name);
}
test('independent: nested accepted pins and cached rows cannot be changed or self-certify altered annual data',async()=>{
 const original=await actual('2017.json');const altered=Buffer.from(original);altered[altered.length-2]^=1;assert.equal(altered.length,original.length);
 let malicious=true;const store=await createStore(async url=>new Response(url.endsWith('/2017.json')&&malicious?altered:await actual(url.slice(SOURCE.base.length))));
 const part=store.index.parts.find(p=>p.year===2017),originalPin=structuredClone(part);
 assert(Object.isFrozen(store.index.parts)&&Object.isFrozen(part));
 for(const change of [()=>part.sha256=sha(altered),()=>part.path='2026.json',()=>store.index.parts.splice(1,1),()=>store.window=async()=>({})])assert.throws(change,TypeError);
 assert.deepEqual(part,originalPin);await assert.rejects(store.window('2017-01-01','2017-01-02'),/SHA-256/);
 malicious=false;const window=await store.window('2017-01-01','2017-01-02');assert.deepEqual(window.rows,JSON.parse(original).rows.slice(0,2));
 for(const change of [()=>window.rows[0].mean_available_gbp_per_mwh=99999,()=>window.rows.splice(0,1),()=>window.start='2099-01-01'])assert.throws(change,TypeError);
 assert.deepEqual((await store.window('2017-01-01','2017-01-02')).rows,JSON.parse(original).rows.slice(0,2));
});
test('independent: actual missing and partial source days stay distinct; negative history and source bounds survive',async()=>{
 const store=await createStore(async url=>new Response(await actual(url.slice(SOURCE.base.length))));
 const missing=await store.window('2026-06-18','2026-06-30');assert.equal(missing.rows.length,13);assert(missing.rows.every(r=>r.coverage_status==='NO_OBSERVATIONS'&&r.mean_available_gbp_per_mwh===null));
 assert.deepEqual(segments(missing.rows,'mean_available_gbp_per_mwh'),[]);assert.equal(summarise(missing.rows).dailyMean,null);
 const year=await store.window('2026-01-01','2026-10-31');assert(year.rows.some(r=>r.minimum_observed_gbp_per_mwh<0));assert.equal(summarise(year.rows).partialDays,1);
 const broken=segments(year.rows.filter(r=>r.date>='2026-06-15'&&r.date<='2026-07-02'),'mean_available_gbp_per_mwh');assert.equal(broken.length,2);assert.equal(broken[0].at(-1).date,'2026-06-17');assert.equal(broken[1][0].date,'2026-07-01');
 const clamped=await store.window('2026-10-25','2099-01-01');assert.equal(clamped.end,'2026-10-31');assert.equal(clamped.rows.length,7);
});

Invariants

A JavaScript module in the automation folder of GlobalGrid2050 that fetches prices, DC locations and projects, using SHA-256.

storageglobalgrid2050 / automation/v931_preview/invariants.mjs · lines 1–114 of 114 · Entry point · pattern priceInput (shared by 3 files)

What it does
It fetches prices, DC locations and projects. Defines 6 functions or classes, including bytes, git, pass, treeBytes, population. Uses libraries node:assert/strict, node:crypto, node:child_process, node:fs, node:path. Side effects: reads or writes files; makes network requests; starts processes; uses storage (browser storage, DuckDB or Parquet).
Inputs & outputs
In: JSON file build_manifest.json; JSON file prices.v931.json; JSON file index.json; JSON file dc-locations.v930.json; JSON file projects.json; JSON file layers-v929.json; JSON file candidates.json; JSON file pipeline_headlines.snapshot.json. Out: JSON file invariants.json.
Downstream impact
Used directly by 1 file: GlobalGrid2050 V931 Preview Acceptance Workflow (globalgrid2050).
What it achieves
It is built from the bytes step (`bytes`), the git step (`git`) and the pass step (`pass`). Exact-source and historical-preservation acceptance for the formal V9.31 edition.
Why it matters
Run by GlobalGrid2050 V931 Preview Acceptance Workflow.
Application
globalgrid2050 · automation/v931_preview · JavaScript module
Uses
Edition History (script call), node:assert/strict, node:crypto, node:child_process, node:fs, node:path, node:url
Used by
run by GlobalGrid2050 V931 Preview Acceptance Workflow (workflow run)
Produces
bytes, git, pass, treeBytes, population, priceInput
Defines here
bytes, git, pass, treeBytes, population, priceInput
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/v931_preview/invariants.mjs:1-114 · blob d6ae99ead6f71449993e103266cdf67e8af73566 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process, storage · domain stage: unknown · users: none · canonical: production_core
/** Exact-source and historical-preservation acceptance for the formal V9.31 edition. */
import assert from 'node:assert/strict';
import {protectedEditionChanges} from '../pipeline_release/edition_history.mjs';
import {createHash} from 'node:crypto';
import {execFileSync} from 'node:child_process';
import {readFileSync,readdirSync,statSync,mkdirSync,writeFileSync} from 'node:fs';
import {dirname,resolve,basename,relative} from 'node:path';
import {fileURLToPath,pathToFileURL} from 'node:url';
const ROOT=resolve(dirname(fileURLToPath(import.meta.url)),'../..');
const EDITION=process.env.V931_CANDIDATE||'uk_renewables_pipeline/202611170243';
const candidate=resolve(ROOT,EDITION),baseline=resolve(ROOT,'uk_renewables_pipeline/202611170147');
const sourceBase=process.env.V931_BASE_SHA||execFileSync('git',['rev-parse','origin/main'],{cwd:ROOT,encoding:'utf8'}).trim();
const out=process.env.V931_OUT;
const bytes=p=>readFileSync(p),json=p=>JSON.parse(bytes(p)),hash=b=>createHash('sha256').update(b).digest('hex');
const git=args=>execFileSync('git',args,{cwd:ROOT,encoding:'utf8'}).trim();
const receipt={status:'RUNNING',utc:new Date().toISOString(),head:git(['rev-parse','HEAD']),edition:EDITION,
  historical_base:sourceBase,checks:[],limitations:['Source-byte and local data/MAP-construction acceptance only; no public GridAtlas execution or source-rights approval.']};
const pass=(name,details={})=>{receipt.checks.push({name,status:'PASS',...details});console.log('PASS:',name);};
function treeBytes(dir){return readdirSync(dir).filter(n=>n!=='__pycache__').reduce((total,name)=>{const p=resolve(dir,name);return total+(statSync(p).isDirectory()?treeBytes(p):statSync(p).size);},0);}
function population(folder){
  const manifest=json(resolve(folder,'data/v9.1/build_manifest.json')),rows=[];
  for(const part of manifest.project_partitions){const raw=bytes(resolve(folder,part.path));assert.equal(hash(raw),part.sha256,part.path);const projects=JSON.parse(raw).projects;assert.equal(projects.length,part.record_count);rows.push(...projects);}
  for(const part of manifest.atlas_partitions){const raw=bytes(resolve(folder,part.path));assert.equal(hash(raw),part.sha256);assert.equal(JSON.parse(raw).features.length,part.feature_count);}
  assert.equal(rows.length,7775);assert.equal(rows.filter(x=>x.technology==='solar').length,3604);assert.equal(new Set(rows.map(x=>String(x.repd_ref))).size,7775);
  return rows;
}
try{
  const priceContractBytes=bytes(resolve(candidate,'contracts/prices.v931.json')),priceContract=JSON.parse(priceContractBytes);
  const priceProducer='78d5360239e1a5fcffa83fcb30d5937c5521acb9',priceCache=resolve(ROOT,'automation/price_daily_ui',priceProducer);
  assert.equal(priceContract.producer.commit,priceProducer);assert.deepEqual(Object.keys(priceContract.files).sort(),['canvas.mjs','model.mjs','styles.css','view.mjs']);
  for(const [name,pin] of Object.entries(priceContract.files)){
    const raw=bytes(resolve(priceCache,name)),donor=execFileSync('git',['show',priceProducer+':automation/news/price-daily-ui/'+name],{cwd:ROOT});
    assert.deepEqual(raw,donor,name+' actual accepted producer bytes');assert.equal(raw.length,pin.bytes);assert.equal(hash(raw),pin.sha256);
    assert.equal(createHash('sha1').update(Buffer.concat([Buffer.from(`blob ${raw.length}\0`),raw])).digest('hex'),pin.git_blob);
  }
  const priceBoot=bytes(resolve(candidate,'scripts/plugins/prices-v931.mjs')).toString('utf8');assert.ok(priceBoot.includes("const manifestHash = '"+hash(priceContractBytes)+"'"));
  const priceModel=await import(pathToFileURL(resolve(priceCache,'model.mjs')));assert.deepEqual(priceContract.input,priceModel.SOURCE);
  assert.equal(priceModel.SOURCE.commit,'cf48c8d6fdd9ab686c4af7261149d81a0129f7fc');assert.equal(priceModel.SOURCE.index.sha256,'3c3ad8e0d8169b4bc253dabbad2a7d35b64984f40accce1abd016e1ca15a1e8e');assert.equal(priceModel.SOURCE.index.bytes,3616);
  async function priceInput(name,pin){
    let raw;if(process.env.V931_PRICE_SOURCE)raw=bytes(resolve(process.env.V931_PRICE_SOURCE,name));
    else{const response=await fetch(priceModel.SOURCE.base+name,{redirect:'error',signal:AbortSignal.timeout(15000)});assert.ok(response.ok);raw=Buffer.from(await response.arrayBuffer());}
    assert.equal(raw.length,pin.bytes);assert.equal(hash(raw),pin.sha256,name+' immutable source bytes');return raw;
  }
  const priceIndex=priceModel.validateIndex(JSON.parse(await priceInput('index.json',priceModel.SOURCE.index)));
  const annualRows=(await Promise.all(priceIndex.parts.map(async part=>priceModel.validateYear(JSON.parse(await priceInput(part.path,part)),part,priceIndex)))).flat();
  const priceSources=JSON.parse(await priceInput(priceIndex.sources.path,priceIndex.sources));await priceInput(priceIndex.parquet.path,priceIndex.parquet);
  const priceSummary=priceModel.summarise(annualRows),expected={daily_rows:annualRows.length,source_parts:priceSources.files.length,source_prices:priceSummary.priced,complete_days:priceSummary.completeDays,partial_days:priceSummary.partialDays,missing_days:priceSummary.missingDays,utc_disagreements:priceSummary.clockMismatches,first_date:annualRows[0].date,last_date:annualRows.at(-1).date};
  assert.deepEqual(expected,{daily_rows:3957,source_parts:188,source_prices:189270,complete_days:3919,partial_days:25,missing_days:13,utc_disagreements:106668,first_date:'2016-01-01',last_date:'2026-10-31'});assert.deepEqual(priceContract.expected,expected);
  assert.equal(priceSources.input_grain.rows,189270);assert.equal(priceSources.utc_alignment_mismatches,106668);assert.equal(new Set(priceSources.files.map(p=>p.path)).size,188);
  assert.match(priceIndex.calendar_quality,/Source-declared/);assert.match(priceContract.scope,/no interpolation.*realtime/);
  pass('four exact price donor blobs and accepted source/index/annual/hash provenance preserve source-day gaps/partial/UTC distinctions',{producer:priceProducer,source:priceModel.SOURCE.commit,runtime_bytes:Object.values(priceContract.files).reduce((n,p)=>n+p.bytes,0),expected,transport:process.env.V931_PRICE_SOURCE?'existing data-owner bytes matched to immutable pins':'immutable source-owner HTTP  … [line shortened here: 405 characters; full line on GitHub]
  const contractPath=resolve(candidate,'contracts/dc-locations.v930.json'),contractBytes=bytes(contractPath),contract=JSON.parse(contractBytes);
  const donorCommit='83e7c36d08ef98f3665f7f35b8637405391dc4be';
  assert.equal(contract.producer.commit,donorCommit);assert.deepEqual(Object.keys(contract.files).sort(),['actions.css','actions.mjs']);
  const cache=resolve(ROOT,'automation/dc_location_ui',donorCommit);
  for(const [name,pin] of Object.entries(contract.files)){
    const local=bytes(resolve(cache,name)),donor=execFileSync('git',['show',donorCommit+':automation/news/dc-locations/'+name],{cwd:ROOT});
    assert.deepEqual(local,donor,name+' actual immutable producer bytes');assert.equal(hash(local),pin.sha256);assert.equal(local.length,pin.bytes);
    assert.equal(createHash('sha1').update(Buffer.concat([Buffer.from(`blob ${local.length}\0`),local])).digest('hex'),pin.git_blob);
  }
  const boot=bytes(resolve(candidate,'scripts/plugins/dc-locations-v930.mjs')).toString('utf8');
  assert.ok(boot.includes("const manifestHash = '"+hash(contractBytes)+"'"),'host pins exact accepted manifest bytes');
  const imported=await import(pathToFileURL(resolve(cache,'actions.mjs')));assert.deepEqual(contract.input,imported.INPUT);
  assert.equal(contract.input.sha256,'6f68e078d9b57057acdda679288730e638553f68df884dfd747c5049e56ea88e');assert.equal(contract.input.bytes,183561);
  let input,transport;
  if(process.env.V931_DATA_SOURCE){input=bytes(resolve(process.env.V931_DATA_SOURCE));transport='explicit existing data-owner file, byte checked';}
  else{const response=await fetch(contract.input.url,{redirect:'error',signal:AbortSignal.timeout(15000)});assert.equal(response.ok,true);input=Buffer.from(await response.arrayBuffer());transport='immutable data-owner HTTPS source';}
  assert.equal(input.length,contract.input.bytes);assert.equal(hash(input),contract.input.sha256);
  const locations=JSON.parse(input),indexed=imported.indexLocations(locations),oldDC=json(resolve(baseline,'global-datacentres/projects.json')).records;
  assert.deepEqual([...indexed.keys()].sort(),oldDC.map(x=>x.id).sort(),'exact100originalIDs; no name-based join');
  const observed={records:locations.features.length,with_address:locations.features.filter(f=>f.properties.addresses.length).length,address_statements:locations.features.flatMap(f=>f.properties.addresses).length,with_geometry:locations.features.filter(f=>f.geometry).length,wikidata_reported_points:locations.features.filter(f=>f.properties.location_precision==='WIKIDATA_REPORTED_POINT').length,post  … [line shortened here: 673 characters; full line on GitHub]
  assert.deepEqual(observed,{records:100,with_address:38,address_statements:39,with_geometry:64,wikidata_reported_points:39,postcode_centroids:25,unknown_geometry:36,screenable_gb_records:34});assert.deepEqual(contract.expected,observed);
  assert.ok(locations.features.every(f=>f.properties.facility_identity_review==='NOT_INDEPENDENTLY_VERIFIED'&&f.properties.grid_connection_assessed===false));
  pass('exact83e cartridge/cache/host-manifest pins and100originalIDs/38addressrecords/39statements/34GBscreens',{donorCommit,observed,source_sha256:hash(input),transport,cache_bytes:treeBytes(cache)});
  const pageSource=bytes(resolve(candidate,'index.html')).toString('utf8');
  assert.ok(pageSource.includes('integrity="sha256-'+createHash('sha256').update(bytes(resolve(priceCache,'styles.css'))).digest('base64')+'"'),'price CSS SRI');
  assert.ok(pageSource.includes('https://globalgrid2050.com/uk_energy_tracking_v6/'),'original independent V6 workspace link retained');
  assert.ok(!bytes(resolve(candidate,'scripts/plugins/layers-v929.mjs')).toString('utf8').includes("prices: {host:"),'only the new price owner mounts the Prices category');
  const cssSRI='sha256-'+createHash('sha256').update(bytes(resolve(cache,'actions.css'))).digest('base64');assert.ok(pageSource.includes('integrity="'+cssSRI+'"'),'optional CSS is pinned by SRI');
  assert.doesNotMatch(pageSource,/<aside\b|class=["'][^"']*\bsidebar\b/i,'new edition must not restore the removed navigation sidebar');
  for(const required of ['class="release-header"','aria-label="Pipeline navigation"','../versions.html','../202611170147/','id="mapAtlasNav"','id="export"'])assert.ok(pageSource.includes(required),'compact navigation retains '+required);
  pass('sidebar markup removed; compact header preserves Versions, previous edition, MAP and CSV navigation');
  const pins=json(resolve(candidate,'contracts/layers-v929.json'));
  assert.equal(pins.source_commit,'8f94299afc8628908dc8bf461cb5ea607560332b');assert.equal(pins.files.length,8);
  for(const pin of pins.files){
    const raw=bytes(resolve(candidate,'scripts/layers',basename(pin.path)));
    const donor=execFileSync('git',['show',pins.source_commit+':'+pin.path],{cwd:ROOT});
    assert.deepEqual(raw,donor,pin.path+' must match the actual immutable donor, not only a self-declared manifest');
    assert.equal(hash(raw),pin.sha256,pin.path+' exact donor bytes');assert.equal(raw.length,pin.bytes);
    assert.equal(createHash('sha1').update(Buffer.concat([Buffer.from(`blob ${raw.length}\0`),raw])).digest('hex'),pin.git_blob);
  }
  pass('eight imported runtime assets exactly match reviewed donor Git blobs/SHA-256',{source_commit:pins.source_commit});
  const size=treeBytes(candidate);assert.ok(size<=18*1024*1024,`${size} exceeds 18 MiB`);pass('complete working edition fits unchanged 18 MiB budget',{bytes:size,limit:18*1024*1024});
  const current=population(candidate),original=population(baseline);assert.deepEqual(current,original);
  pass('all 7,775 official records and order equal frozen V9.30; 3,604 solar',{records:7775,solar:3604});
  for(const name of ['solar1000/manifest.json','solar1000/candidates.json'])assert.deepEqual(bytes(resolve(candidate,name)),bytes(resolve(baseline,name)),name);
  const selected=json(resolve(candidate,'solar1000/manifest.json'));assert.equal(selected.ids.length,1000);assert.equal(selected.independently_verified,0);
  assert.deepEqual(selected.ids,current.filter(x=>x.technology==='solar').map(x=>String(x.repd_ref)).sort((a,b)=>Number(a)-Number(b)).slice(0,1000));
  pass('ordered immutable Solar-1000 and provisional receipt bytes equal frozen V9.30',{sha256:hash(bytes(resolve(candidate,'solar1000/manifest.json')))});
  const receiver=await import(pathToFileURL(resolve(candidate,'scripts/core/atlas-receiver-v9-7.js')));
  const oldReceiver=await import(pathToFileURL(resolve(baseline,'scripts/core/atlas-receiver-v9-7.js')));
  for(let i=0;i<current.length;i++)assert.equal(receiver.buildAtlasDeepLinkV9_7(current[i]),oldReceiver.buildAtlasDeepLinkV9_7(original[i]),String(current[i].repd_ref));
  const existing=execFileSync(process.execPath,[resolve(candidate,'tests/check_map_contract_all_rows.mjs')],{cwd:ROOT,encoding:'utf8'}).trim();
  pass('all 7,775 original MAP routes and established all-row contract preserved',{established_check:existing});
  const snapshot=bytes(resolve(candidate,'news/pipeline_headlines.snapshot.json')),source=json(resolve(candidate,'news/snapshot-provenance.json'));
  assert.deepEqual(bytes(resolve(candidate,'news/snapshot-provenance.json')),bytes(resolve(baseline,'news/snapshot-provenance.json')),'original source clock/provenance receipt bytes preserved');
  assert.equal(hash(snapshot),source.sha256);assert.equal(JSON.parse(snapshot).items.length,71);assert.deepEqual(snapshot,bytes(resolve(baseline,'news/pipeline_headlines.snapshot.json')));
  pass('original saved 71-headline source bytes and publication clock preserved',{source_commit:source.source_commit,generated_at:source.generated_at,sha256:source.sha256});
  const historical=protectedEditionChanges({cwd:ROOT,base:sourceBase});
  assert.deepEqual(historical,[],'all numeric edition trees present in the pinned base remain immutable, including staged/unstaged changes and deletions');
  pass('every historical edition tree remains unchanged against origin/main',{base:sourceBase});
  receipt.status='PASS';
}catch(error){receipt.status='FAIL';receipt.failure=error.stack;throw error;}
finally{if(out){mkdirSync(out,{recursive:true});writeFileSync(resolve(out,'invariants.json'),JSON.stringify(receipt,null,2)+'\n');}}