GLOBALGRID2050 / EXPLORE CODE

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

Browser and 4 more files

A JavaScript module in the automation folder of GlobalGrid2050 that draws DC locations, DC global, snapshot provenance and pipeline headlines snapshot, using SHA-256.

559 lines of JavaScript from globalgrid2050, in 5 files. Topic: Automation and CI. Section 1747 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. Contracts Test test · globalgrid2050 / automation/v929_preview/contracts.test.mjs lines 1–100
  2. Invariants storage · globalgrid2050 / automation/v929_preview/invariants.mjs lines 1–63
  3. Browser render · globalgrid2050 / automation/v930_preview/browser.mjs lines 1–231
  4. Contracts Test test · globalgrid2050 / automation/v930_preview/contracts.test.mjs lines 1–78
  5. Invariants storage · globalgrid2050 / automation/v930_preview/invariants.mjs lines 1–87

Contracts Test

A test in the automation folder of GlobalGrid2050 that checks Registry and Model, using SHA-256 using data from the GridAtlas repository.

testglobalgrid2050 / automation/v929_preview/contracts.test.mjs · lines 1–100 of 100 · Entry point

What it does
It tests substations. Defines spec. Uses libraries node:test, node:assert/strict, node:crypto.
Why it exists in the grid workflow
Domain stage sub33kv_design (voltage levels 33kV (all 33kV or below)): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: substations, 33kV.
Inputs & outputs
In: JSON file pinned.json. Voltage levels named: 33kV.
Downstream impact
Used directly by 5 files: GlobalGrid2050 V929 Preview Acceptance Workflow (globalgrid2050); GlobalGrid2050 V930 Preview Acceptance Workflow (globalgrid2050); GlobalGrid2050 V931 Preview Acceptance Workflow (globalgrid2050); GlobalGrid2050 V932 Preview Acceptance Workflow (globalgrid2050); and 1 more.
What it achieves
Defines `spec`. Its code works with 33 kV.
Why it matters
Run by 5 workflows and scripts, including GlobalGrid2050 V929 Preview Acceptance Workflow, GlobalGrid2050 V930 Preview Acceptance Workflow and GlobalGrid2050 V931 Preview Acceptance Workflow.
Application
globalgrid2050 · automation/v929_preview · test
Uses
Registry (import), Model (import), Views (import), URL Policy (import), GridAtlas — Atlas Page (estate URL), node:test, node:assert/strict, node:crypto
Used by
run by GlobalGrid2050 V929 Preview Acceptance Workflow (workflow run), run by GlobalGrid2050 V930 Preview Acceptance Workflow (workflow run), run by GlobalGrid2050 V931 Preview Acceptance Workflow (workflow run), run by GlobalGrid2050 V932 Preview Acceptance Workflow (workflow run), run by GlobalGrid2050 V933 Preview Acceptance Workflow (workflow run)
Produces
spec
Defines here
spec
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/v929_preview/contracts.test.mjs:1-100 · blob be135b1ad1a64d2c691012064fbedf94d963c115 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {createHash} from 'node:crypto';
import {createDataRegistry,validateRegistry} from '../../uk_renewables_pipeline/202611162354/scripts/layers/registry.mjs';
import {assetRows,selectRows,locationLink,latestHeadlines,voltageLabel} from '../../uk_renewables_pipeline/202611162354/scripts/layers/model.mjs';
import {assetCsv} from '../../uk_renewables_pipeline/202611162354/scripts/layers/views.mjs';
import {priceWorkspaceUrl,publicHttpsUrl} from '../../uk_renewables_pipeline/202611162354/scripts/layers/url-policy.mjs';
const source={type:'FeatureCollection',features:[{type:'Feature',id:'source:1',properties:{name:'Named substation',voltage:'132000'},geometry:{type:'Point',coordinates:[-1,52]}}]};
const bytes=Buffer.from(JSON.stringify(source));
const digest=createHash('sha256').update(bytes).digest('hex');
function spec(){return {schema:'globalgrid2050.pipeline-layers.v1',layers:[{id:'test',label:'Test',group:'Grid',owner:'Owner',renderer:'assets',data:{url:'https://example.org/pinned.json',sha256:digest,maxBytes:4096,rows:1,schema:'geojson.FeatureCollection'}}]};}
test('lazy source is fetched once; returned data cannot corrupt the cached snapshot',async()=>{
  let calls=0;const registry=createDataRegistry(spec(),{fetchImpl:async()=>{calls++;return new Response(bytes);}});
  assert.equal(calls,0);const a=await registry.load('test');a.features.length=0;
  const b=await registry.load('test');assert.equal(b.features.length,1);assert.equal(calls,1);
});
test('caller cannot mutate accepted manifest or its exposed dataset pins',async()=>{
  const manifest=spec();const registry=createDataRegistry(manifest,{fetchImpl:async()=>new Response(bytes)});
  manifest.layers[0].data.sha256='0'.repeat(64);
  assert.throws(()=>{registry.layers[0].data.sha256='0'.repeat(64);},TypeError);
  assert.equal((await registry.load('test')).features.length,1);
});
test('changed bytes fail before parsing or rendering and allow an explicit retry',async()=>{
  let bad=true;const registry=createDataRegistry(spec(),{fetchImpl:async()=>new Response(bad?Buffer.concat([bytes,Buffer.from(' ')]):bytes)});
  await assert.rejects(registry.load('test'),/integrity/);bad=false;assert.equal((await registry.load('test')).features.length,1);
});
test('a warmed source cannot bypass another layer’s stricter schema/count/byte contract',async()=>{
  const manifest=spec(),second=structuredClone(manifest.layers[0]);second.id='strict';second.data.rows=2;second.data.maxBytes=1;second.data.schema='WRONG';manifest.layers.push(second);
  const registry=createDataRegistry(manifest,{fetchImpl:async()=>new Response(bytes)});
  assert.equal((await registry.load('test')).features.length,1);
  await assert.rejects(registry.load('strict'),/byte budget/);
});
test('stream size is enforced without trusting the declared content length',async()=>{
  const manifest=spec();manifest.layers[0].data.maxBytes=1;
  const registry=createDataRegistry(manifest,{fetchImpl:async()=>new Response(bytes)});
  await assert.rejects(registry.load('test'),/byte budget/);
});
test('failed HTTP, redirected inputs, count mismatch and unknown layers fail closed',async()=>{
  const failed=createDataRegistry(spec(),{fetchImpl:async()=>new Response('unavailable',{status:503})});
  await assert.rejects(failed.load('test'),/unavailable/);
  const manifest=spec();manifest.layers[0].data.rows=2;
  await assert.rejects(createDataRegistry(manifest,{fetchImpl:async()=>new Response(bytes)}).load('test'),/schema\/count/);
  await assert.rejects(failed.load('not-present'),/Unknown/);
});
test('invalid catalogue identities, unsafe URLs and unbounded browser products are rejected',()=>{
  const duplicate=spec();duplicate.layers.push(structuredClone(duplicate.layers[0]));assert.throws(()=>validateRegistry(duplicate),/duplicate/);
  for(const url of ['http://example.org/file','javascript:alert(1)','https://user:password@example.org/file']){const x=spec();x.layers[0].data.url=url;assert.throws(()=>validateRegistry(x));}
  const big=spec();big.layers[0].data.rows=100000;assert.throws(()=>validateRegistry(big),/row policy/);
});
test('missing names and locations remain unknown, with original source IDs',()=>{
  const collection=structuredClone(source);collection.features[0].properties={};collection.features[0].geometry=null;
  const [row]=assetRows(collection,'substation');assert.equal(row.name,null);assert.equal(row.coordinates,null);assert.equal(locationLink(row),null);assert.equal(row.sourceId,'source:1');
});
test('null/string coordinates do not become locations and duplicate identities are refused',()=>{
  const collection=structuredClone(source);collection.features[0].geometry.coordinates=[null,'52'];
  assert.equal(assetRows(collection,'substation')[0].coordinates,null);
  collection.features.push(collection.features[0]);assert.throws(()=>assetRows(collection,'substation'),/Duplicate/);
});
test('location links carry no fabricated REPD identity, MW or connection status',()=>{
  const row=assetRows(source,'substation')[0],url=new URL(locationLink(row));
  assert.equal(url.origin+url.pathname,'https://ventusltd.github.io/gridatlas/atlas/');assert.equal(url.searchParams.get('technology'),'substation');
  assert.equal(url.searchParams.get('longitude'),'-1');assert.equal(url.searchParams.has('repd_ref'),false);assert.equal(url.searchParams.has('capacity_mw'),false);
});
test('published OSM voltage remains voltage rather than capacity, with unknowns retained',()=>{
  assert.equal(voltageLabel('132000;33000'),'132 / 33 kV');assert.equal(voltageLabel(null),'Not recorded');
  assert.equal(voltageLabel('unknown'),'unknown');assert.equal(voltageLabel('0'),'0');
});
test('search and CSV cover the same selected rows; deliberate cross-domain overlap is retained',()=>{
  const rows=[...assetRows(source,'substation'),...assetRows(source,'offtaker')];assert.equal(rows.length,2);
  const selected=selectRows(rows,'source:1');assert.equal(selected.length,2);assert.equal(assetCsv(selected).split('\r\n').length,4);
  rows[0].name='=HYPERLINK("malicious")';assert.ok(assetCsv(rows).includes("'=HYPERLINK"));
});
test('downloaded records retain original source URLs, licences and dataset-level attribution',()=>{
  const input=structuredClone(source);input.features[0].properties.sources=[{name:'NAEI',url:'https://naei.example/record',licence:'OGL v3.0'}];
  const rows=assetRows(input,'offtaker');const csv=assetCsv(rows,{sourceUrl:'https://source.example/pinned.json',datasetAttribution:{database:'ODbL',credit:'OpenStreetMap contributors'}});
  for(const value of ['https://naei.example/record','OGL v3.0','https://source.example/pinned.json','ODbL','OpenStreetMap contributors'])assert.ok(csv.includes(value),value);
});
test('ticker selects ten latest dated distinct HTTPS headlines without unsafe URLs',()=>{
  const items=Array.from({length:12},(_,i)=>({title:'Item '+i,link:'https://publisher.example/'+i,date:`2026-11-${String(i+1).padStart(2,'0')}`,source:'Publisher'}));
  items.push({...items[0]},{title:'Unsafe',link:'javascript:alert(1)',date:'2026-11-15'});
  const result=latestHeadlines(items);assert.equal(result.length,10);assert.equal(result[0].title,'Item 11');assert.equal(result.at(-1).title,'Item 2');
});
test('impossible dates, future publication and private-address headlines are withheld',()=>{
  const common={title:'Synthetic source title',source:'Fixture',link:'https://publisher.example/article'};
  const asOf=Date.parse('2026-11-16T23:00:00Z');
  for(const date of ['2026-02-30','2026-11-31T12:00:00Z','2099-01-01','2026-11-17T00:00:00Z','2026-11-16T25:00:00Z'])assert.deepEqual(latestHeadlines([{...common,date}],10,{asOf}),[],date);
  for(const link of ['https://127.0.0.1/private','https://[::1]/private','https://localhost/private','https://router.local/private','https://192.168.0.1/private','https://localhost./private','https://router.local./private','https://router.internal./private','https://localhost%2e/private'])assert.deepEqual(latestHeadlines([{...common,date:'2026-11-16',link}],10,{asOf}),[],link);
  assert.equal(latestHeadlines([{...common,date:'2024-02-29'}],10,{asOf}).length,1);
});
test('Prices URLs reject at both the registry and renderer URL-policy boundary',()=>{
  for(const url of ['javascript:alert(1)','https://127.0.0.1/private','https://evil.example/graphs']) {
    const manifest=spec();manifest.layers.push({id:'prices',label:'Prices',group:'Prices',owner:'Fixture',renderer:'prices',url});
    assert.throws(()=>validateRegistry(manifest),undefined,url);assert.throws(()=>priceWorkspaceUrl(url),undefined,url);
  }
  assert.equal(priceWorkspaceUrl('https://globalgrid2050.com/uk_energy_tracking_v6/'),'https://globalgrid2050.com/uk_energy_tracking_v6/');
  assert.throws(()=>publicHttpsUrl('https://127.1/private'));
});
test('blank and non-identity source values cannot become fabricated asset keys',()=>{
  for(const id of ['', '   ',null,{},true,NaN]){const value=structuredClone(source);value.features[0].id=id;assert.throws(()=>assetRows(value,'substation'),/source identity/,String(id));}
});

Invariants

A JavaScript module in the automation folder of GlobalGrid2050 that reads pipeline headlines snapshot and snapshot provenance, using SHA-256.

storageglobalgrid2050 / automation/v929_preview/invariants.mjs · lines 1–63 of 63 · Entry point · pattern treeBytes (shared by 5 files)

What it does
It loads pipeline headlines snapshot and snapshot provenance. Defines 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; starts processes.
Inputs & outputs
In: JSON file build_manifest.json; JSON file layers-v929.json; JSON file candidates.json; JSON file pipeline_headlines.snapshot.json; JSON file snapshot-provenance.json. Out: JSON file invariants.json.
Downstream impact
Used directly by 1 file: GlobalGrid2050 V929 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.29 edition.
Why it matters
Run by GlobalGrid2050 V929 Preview Acceptance Workflow.
Application
globalgrid2050 · automation/v929_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 V929 Preview Acceptance Workflow (workflow run)
Produces
bytes, git, pass, treeBytes, population
Defines here
bytes, git, pass, treeBytes, population
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/v929_preview/invariants.mjs:1-63 · blob 3d004e127216a7f0695c2e7b914a55ca7c9c9b97 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: production_core
/** Exact-source and historical-preservation acceptance for the formal V9.29 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.V929_CANDIDATE||'uk_renewables_pipeline/202611162354';
const candidate=resolve(ROOT,EDITION),baseline=resolve(ROOT,'uk_renewables_pipeline/202611161757');
const sourceBase=process.env.V929_BASE_SHA||execFileSync('git',['rev-parse','origin/main'],{cwd:ROOT,encoding:'utf8'}).trim();
const out=process.env.V929_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 pageSource=bytes(resolve(candidate,'index.html')).toString('utf8');
  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','../202611161757/','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.28; 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.28',{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');}}

Browser

A JavaScript module in the automation folder of GlobalGrid2050 that draws DC locations, DC global, snapshot provenance and pipeline headlines snapshot, using SHA-256.

renderglobalgrid2050 / automation/v930_preview/browser.mjs · lines 1–231 of 231 · Entry point · pattern dcOriginalLinks (shared by 4 files)

What it does
It draws DC locations, DC global, snapshot provenance and pipeline headlines snapshot. Defines 16 functions or classes, including sha, urlFor, pass, download, open. 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; CSV file v929-all.csv; CSV file v929-dc-global.csv; JSON file build_manifest.json; CSV file v930-all.csv; JSON file snapshot-provenance.json; JSON file pipeline_headlines.snapshot.json. Out: JSON file browser.json.
Downstream impact
Used directly by 1 file: GlobalGrid2050 V930 Preview Acceptance Workflow (globalgrid2050).
What it achieves
It verifies locations (`verifyLocations`) and is built from the sha step (`sha`) and the URL for helper (`urlFor`). Real integrated V9.30 browser acceptance against exact source-byte fixtures.
Why it matters
Run by GlobalGrid2050 V930 Preview Acceptance Workflow.
Application
globalgrid2050 · automation/v930_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 V930 Preview Acceptance Workflow (workflow run)
Produces
sha, urlFor, pass, download, open, fullWidth, painted, settleTouch, touchTap, touchDrag, orientationScreenshot, tab
Defines here
sha, urlFor, pass, download, open, fullWidth, painted, settleTouch, touchTap, touchDrag, orientationScreenshot, tab, allRepd, dcOriginalLinks, dcGlobal, verifyLocations
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/v930_preview/browser.mjs:1-231 · blob d2772dce6b66f96f57aa9ea1aa2886417d736cbd · 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.30 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.V930_CANDIDATE||'uk_renewables_pipeline/202611170147';
const candidate=resolve(ROOT,EDITION),baseline=resolve(ROOT,'uk_renewables_pipeline/202611162354');
const OUT=resolve(process.env.V930_OUT||resolve(tmpdir(),'gg2050-v930-preview'));
const {chromium}=process.env.V930_PLAYWRIGHT
  ? await import(pathToFileURL(resolve(process.env.V930_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 Prices iframe navigation are blocked; existing saved headline and explicit frame URL are tested.',
  'Original Prices can show indicative baselines and stale observations; frame wiring is not actual-price-series acceptance.',
  '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.V930_DATA_SOURCE)locationBytes=readFileSync(resolve(process.env.V930_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.V930_DATA_SOURCE?'explicit data-owner fixture, exact immutable bytes':'immutable HTTPS source'});
let baselineDCLinks,baselineDCCsv;
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');
      const module=corrupt==='dc-module'&&pathname.endsWith('/automation/dc_location_ui/'+locationSpec.producer.commit+'/actions.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))raw=Buffer.concat([raw,Buffer.from(' ')]);return route.fulfill({status:200,contentType:'application/json',body:raw});}receipt.blocked_external.push(u);return route.abort();});
  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'),`v930-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,`v930-dc-global-${width}.png`)});
  pass('actual host100ID join/38addressrecords/39statements/34GBScreen/source links and originalCSV preserved across filters',{width});
}
let browser;
try{
  browser=await chromium.launch({headless:true});receipt.browser=browser.version();
  if(!process.env.V930_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.29 browser CSV establishes complete original population',{rows:7775,sha256:oldCsv.sha256});
  for(const width of [390,915,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'),'v930-all.csv');assert.deepEqual(actual.rows,oldCsv.rows);pass('all 7,775 exported CSV rows/fields/order equal frozen V9.29',{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 tab(page,'pricesTab');await page.locator('#pricesLayerHost').getByRole('button',{name:'Show original graphs here'}).waitFor();assert.equal(await page.locator('#pricesLayerHost iframe').count(),0);
    assert.match(await page.locator('#pricesLayerHost').innerText(),/observation dates/);assert.match(await page.locator('#pricesLayerHost').innerText(),/indicative price baselines/);
    await page.locator('#pricesLayerHost').getByRole('button',{name:'Show original graphs here'}).click();assert.equal(await page.locator('#pricesLayerHost iframe').getAttribute('src'),'https://globalgrid2050.com/uk_energy_tracking_v6/');
    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,`v930-solar-${width}.png`)});await tab(page,'gridTab');await page.screenshot({path:resolve(OUT,`v930-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,`v930-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});
  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 Actions, using SHA-256.

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

What it does
It tests postcodes. Defines fixture. Uses libraries node:test, node:assert/strict, node:crypto.
Why it exists in the grid workflow
Domain terms in the code: postcodes.
Downstream impact
Used directly by 1 file: GlobalGrid2050 V930 Preview Acceptance Workflow (globalgrid2050).
What it achieves
Defines `fixture`.
Why it matters
Run by GlobalGrid2050 V930 Preview Acceptance Workflow.
Application
globalgrid2050 · automation/v930_preview · test
Uses
Actions (import), node:test, node:assert/strict, node:crypto
Used by
run by GlobalGrid2050 V930 Preview Acceptance Workflow (workflow run)
Produces
fixture
Defines here
fixture
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/v930_preview/contracts.test.mjs:1-78 · blob ff6e7e210f989f1d0650fa4a9bf3127c77d8d089 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · 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 {indexLocations,screenUrl,loadLocations,INPUT} from '../dc_location_ui/83e7c36d08ef98f3665f7f35b8637405391dc4be/actions.mjs';

function fixture() {
  return {type:'FeatureCollection',schema:'data-grid-gb.dc-address-locations.v1',
    counts:{records:1,with_geometry:1,unknown_geometry:0,postcode_centroids:1,with_address:1},
    features:[{type:'Feature',id:'DC-WD-Q1',geometry:{type:'Point',coordinates:[-0.1,51.5]},properties:{
      id:'DC-WD-Q1',wikidata_id:'Q1',name:'SYNTHETIC <site>',country:{code:'GB'},
      addresses:[{text:'1 Synthetic Street, London SW1A 1AA'}],location_precision:'POSTCODE_CENTROID_APPROXIMATE',
      source_revision_url:'https://www.wikidata.org/w/index.php?title=Q1&oldid=1',
      geometry_licence:'OS OpenData: GB postcode source terms',geometry_licence_url:'https://postcodes.io/docs/licences/',
      geometry_attribution:['SYNTHETIC attribution'],grid_connection_assessed:false,facility_identity_review:'NOT_INDEPENDENTLY_VERIFIED',
      screening_url:'javascript:globalThis.__probe=1'}}]};
}

test('exact original IDs and actual counts are required',()=>{
 const d=fixture();assert.equal(indexLocations(d).size,1);
 d.features.push(structuredClone(d.features[0]));d.counts.records=2;
 assert.throws(()=>indexLocations(d),/identity/);
});
test('count mismatches and false verification claims reject',()=>{
 const d=fixture();d.counts.with_geometry=0;assert.throws(()=>indexLocations(d),/counts/);
 const e=fixture();e.features[0].properties.facility_identity_review='VERIFIED';assert.throws(()=>indexLocations(e),/scope/);
});
test('unsafe or unrelated source-revision links reject',()=>{
 for(const url of ['javascript:alert(1)','https://127.0.0.1/a','https://www.wikidata.org/w/index.php?title=Q2&oldid=1','https://u@www.wikidata.org/w/index.php?title=Q1&oldid=1','https://www.wikidata.org/w/index.php?title=Q1&title=Q2&oldid=1']){
  const d=fixture();d.features[0].properties.source_revision_url=url;assert.throws(()=>indexLocations(d));
 }
});
test('direct action reconstruction ignores executable producer URL',()=>{
 const f=fixture().features[0];const u=new URL(screenUrl(f));assert.equal(u.origin,'https://ventusltd.github.io');
 assert.equal(u.searchParams.get('project'),'SYNTHETIC <site>');assert.equal(u.searchParams.has('repd_ref'),false);
 assert.equal(u.searchParams.has('capacity_mw'),false);assert.equal(globalThis.__probe,undefined);
});
test('direct action caller cannot bypass coordinate validation',()=>{
 for(const xy of [[0,0],[NaN,51],[-0.1,91],[true,51]]){
  const f=fixture().features[0];f.geometry.coordinates=xy;assert.throws(()=>screenUrl(f));
 }
});
test('missing points remain without screening actions',()=>{
 const d=fixture();d.features[0].geometry=null;d.features[0].properties.location_precision='UNKNOWN';
 Object.assign(d.counts,{with_geometry:0,unknown_geometry:1,postcode_centroids:0});
 assert.equal(screenUrl(indexLocations(d).get('DC-WD-Q1')),null);
});
test('foreign and unknown country points keep geometry without a GB screening route',()=>{
 for(const country of [{code:'FR'},{code:'US'},{code:'UK'},{code:null},undefined]){
  const d=fixture(),f=d.features[0];f.properties.country=country;
  f.geometry.coordinates=[7.73,48.58];f.properties.location_precision='WIKIDATA_REPORTED_POINT';
  f.properties.geometry_licence='CC0-1.0';f.properties.geometry_licence_url='https://www.wikidata.org/wiki/Wikidata:Copyright';
  d.counts.postcode_centroids=0;
  assert.equal(indexLocations(d).size,1);assert.deepEqual(f.geometry.coordinates,[7.73,48.58]);
  assert.equal(screenUrl(f),null);
 }
});
test('postcode points require their own terms and GB bounds',()=>{
 for(const mutate of [p=>p.geometry_licence='CC0-1.0',p=>p.geometry_licence_url='https://bad.example/terms']){
  const d=fixture();mutate(d.features[0].properties);assert.throws(()=>indexLocations(d),/terms/);
 }
 const d=fixture();d.features[0].geometry.coordinates=[2.35,48.85];assert.throws(()=>indexLocations(d),/terms/);
 const credit=fixture();credit.features[0].properties.geometry_attribution=[{text:'not text'}];
 assert.throws(()=>indexLocations(credit),/rights/);
});
test('pinned bounded loader rejects altered or excessive source bytes',async()=>{
 const bytes=new TextEncoder().encode(JSON.stringify(fixture()));
 const pin={url:INPUT.url,bytes:bytes.length,sha256:createHash('sha256').update(bytes).digest('hex')};
 assert.equal((await loadLocations(async()=>new Response(bytes),pin)).size,1);
 await assert.rejects(loadLocations(async()=>new Response(bytes),{...pin,sha256:'0'.repeat(64)}),/digest/);
 await assert.rejects(loadLocations(async()=>new Response(bytes),{...pin,bytes:bytes.length-1}),/byte limit/);
 await assert.rejects(loadLocations(async()=>new Response(bytes),{...pin,bytes:bytes.length+1}),/byte count/);
});
test('invalid pin bounds or endpoints reject before any network call',async()=>{
 for(const bad of [{bytes:NaN},{bytes:Infinity},{bytes:-1},{bytes:2147483647},{url:'https://127.0.0.1/'},{url:'javascript:alert(1)'},{sha256:'bad'}]){
  let fetched=false;await assert.rejects(loadLocations(async()=>{fetched=true;return new Response('{}');},{...INPUT,...bad}),/source contract/);
  assert.equal(fetched,false);
 }
});

Invariants

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

storageglobalgrid2050 / automation/v930_preview/invariants.mjs · lines 1–87 of 87 · Entry point · pattern treeBytes (shared by 5 files)

What it does
It fetches DC locations and projects. Defines 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.
Inputs & outputs
In: JSON file build_manifest.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; JSON file snapshot-provenance.json. Out: JSON file invariants.json.
Downstream impact
Used directly by 1 file: GlobalGrid2050 V930 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.30 edition.
Why it matters
Run by GlobalGrid2050 V930 Preview Acceptance Workflow.
Application
globalgrid2050 · automation/v930_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 V930 Preview Acceptance Workflow (workflow run)
Produces
bytes, git, pass, treeBytes, population
Defines here
bytes, git, pass, treeBytes, population
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/v930_preview/invariants.mjs:1-87 · blob 3ba85094d3962a49dc61cee84e15f1035381f590 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: unknown · users: none · canonical: production_core
/** Exact-source and historical-preservation acceptance for the formal V9.30 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.V930_CANDIDATE||'uk_renewables_pipeline/202611170147';
const candidate=resolve(ROOT,EDITION),baseline=resolve(ROOT,'uk_renewables_pipeline/202611162354');
const sourceBase=process.env.V930_BASE_SHA||execFileSync('git',['rev-parse','origin/main'],{cwd:ROOT,encoding:'utf8'}).trim();
const out=process.env.V930_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 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.V930_DATA_SOURCE){input=bytes(resolve(process.env.V930_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');
  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','../202611162354/','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.29; 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.29',{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');}}