GLOBALGRID2050 / EXPLORE CODE

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

Browser and 3 more files

A JavaScript module in the automation folder of GlobalGrid2050 that parses CSV (`parseCsv`), opens page (`openPage`) and downloads CSV (`downloadCsv`), covering transition context, projects and baseline, using SHA-256.

626 lines of JavaScript from globalgrid2050, in 4 files. Topic: Automation and CI. Section 1746 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/v928_preview/browser.mjs lines 1–240
  2. Invariants storage · globalgrid2050 / automation/v928_preview/invariants.mjs lines 1–137
  3. Serve ingest · globalgrid2050 / automation/v928_preview/serve.mjs lines 1–29
  4. Browser render · globalgrid2050 / automation/v929_preview/browser.mjs lines 1–220

Browser

A JavaScript module in the automation folder of GlobalGrid2050 that parses CSV (`parseCsv`), opens page (`openPage`) and downloads CSV (`downloadCsv`), covering transition context, projects and baseline, using SHA-256.

energy-dataglobalgrid2050 / automation/v928_preview/browser.mjs · lines 1–240 of 240 · Entry point · pattern allRows (shared by 3 files)

What it does
It draws transition context, projects and baseline. Defines 8 functions or classes, including sha, urlFor, pass, parseCsv, openPage. Uses libraries node:assert/strict, node:http, node:child_process, node:crypto, node:fs. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes.
Inputs & outputs
In: JSON file transition-context.json; JSON file projects.json; CSV file baseline-v924-all.csv; JSON file build_manifest.json; CSV file candidate-v928-all.csv. Out: JSON file browser.json.
Downstream impact
Used directly by 1 file: GlobalGrid2050 V928 Preview Acceptance Workflow (globalgrid2050).
What it achieves
It parses CSV (`parseCsv`), opens page (`openPage`) and downloads CSV (`downloadCsv`). Local integrated acceptance; external requests are blocked and recorded.
Why it matters
Run by GlobalGrid2050 V928 Preview Acceptance Workflow.
Application
globalgrid2050 · automation/v928_preview · JavaScript module
VEDIC
EXPORT FILTERED PROJECTS (GG2050-VEDIC-000060): Pipeline News · Renewable project register. active_table_owner, filtered_register_rows, official_detail_partitions → csv_download_or_refusal
Uses
node:assert/strict, node:http, node:child_process, node:crypto, node:fs, node:path, node:os, node:url
Used by
run by GlobalGrid2050 V928 Preview Acceptance Workflow (workflow run)
Produces
sha, urlFor, pass, parseCsv, openPage, allRows, downloadCsv, activate
Defines here
sha, urlFor, pass, parseCsv, openPage, allRows, downloadCsv, activate
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/v928_preview/browser.mjs:1-240 · blob e5e6d912becd87866747929cd6d092fe08e5d2ec · 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
/** Local integrated acceptance; external requests are blocked and recorded. */
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { readFileSync, existsSync, statSync, mkdirSync, writeFileSync } 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 CANDIDATE = resolve(ROOT, process.env.V928_CANDIDATE || 'uk_renewables_pipeline/202611161757');
const BASELINE = resolve(ROOT,'uk_renewables_pipeline/202611161244');
const OUT = resolve(process.env.V928_OUT || resolve(tmpdir(),'gg2050-v928-preview'));
const PLAYWRIGHT = process.env.V928_PLAYWRIGHT;
const { chromium } = PLAYWRIGHT ? await import(pathToFileURL(resolve(PLAYWRIGHT))) : await import('playwright');
mkdirSync(OUT,{recursive:true});
const sha = b => createHash('sha256').update(b).digest('hex');
const mime = {'.html':'text/html','.js':'text/javascript','.mjs':'text/javascript','.json':'application/json',
  '.geojson':'application/geo+json','.css':'text/css','.csv':'text/csv','.svg':'image/svg+xml','.png':'image/png'};
const server = createServer((req,res)=>{
  try {
    let file = resolve(ROOT, '.'+decodeURIComponent(new URL(req.url,'http://localhost').pathname));
    if (!file.startsWith(ROOT+sep)) {res.writeHead(403).end();return;}
    if (existsSync(file) && statSync(file).isDirectory()) file=resolve(file,'index.html');
    if(!existsSync(file)) {res.writeHead(404).end('Fixture not checked out');return;}
    res.writeHead(200,{'Content-Type':mime[extname(file)]||'application/octet-stream','Cache-Control':'no-store'});
    res.end(readFileSync(file));
  } catch {res.writeHead(500).end();}
});
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 receipt = {status:'RUNNING',utc:new Date().toISOString(),
  head:execFileSync('git',['rev-parse','HEAD'],{cwd:ROOT,encoding:'utf8'}).trim(),
  candidate:relative(ROOT,CANDIDATE).replaceAll('\\','/'),
  index_sha256:sha(readFileSync(resolve(CANDIDATE,'index.html'))),checks:[],blocked_external:[],
  limitations:['Localhost preview only; no deployment/public served-byte acceptance.',
    'External feeds and Chart.js CDN blocked: saved/unavailable states and numeric gauges tested, not live acquisition or chart rendering.',
    'All-row original MAP links are gated separately; this suite does not contact or certify the public GridAtlas receiver.',
    'Fixture records retain their provisional/quarantined states; browser success does not certify rights or project facts.']};
function pass(name,details={}) {receipt.checks.push({name,status:'PASS',...details});console.log('PASS:',name);}
function parseCsv(input) {
  const text=input.replace(/^\ufeff/,'');const records=[];let row=[],cell='',quoted=false;
  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==='\r'||c==='\n')&&!quoted){if(c==='\r'&&text[i+1]==='\n')i++;row.push(cell);records.push(row);row=[];cell='';}
    else cell+=c;
  }
  assert.equal(quoted,false,'CSV quoted field must terminate');
  if(cell.length||row.length){row.push(cell);records.push(row);}return records;
}
async function openPage(browser,width,folder,tamper=false,publication=false) {
  const context=await browser.newContext({viewport:{width,height:1000},acceptDownloads:true});
  const page=await context.newPage();
  const failures=[];page.on('pageerror',e=>failures.push(String(e)));
  await context.route('**/*',async route=>{
    const url=new URL(route.request().url());
    if(publication && url.origin==='https://publication-preview.invalid') {
      const response=await route.fetch({url:origin+url.pathname+url.search});
      return route.fulfill({response});
    }
    if(url.origin!==origin) {receipt.blocked_external.push(url.origin+url.pathname);return route.abort();}
    if(tamper==='context-manifest' && url.pathname.endsWith('/automation/v928_context/preview/manifest.json')) {
      return route.fulfill({status:404,contentType:'application/json',body:'{}'});
    }
    if(tamper==='context-data' && url.pathname.endsWith('/automation/v928_context/preview/transition-context.json')) {
      return route.fulfill({status:200,contentType:'application/json',body:readFileSync(resolve(ROOT,'.'+url.pathname),'utf8')+' '});
    }
    if(tamper && url.pathname===new URL(urlFor(CANDIDATE)+'global-datacentres/projects.json').pathname) {
      const raw=readFileSync(resolve(ROOT,'.'+url.pathname),'utf8');
      return route.fulfill({status:200,contentType:'application/json',body:raw+' '});
    }
    return route.continue();
  });
  await page.goto(publication?urlFor(folder).replace(origin,'https://publication-preview.invalid'):urlFor(folder),{waitUntil:'domcontentloaded'});
  await page.waitForFunction(()=>Number(document.getElementById('tbody')?.dataset.total)>0);
  return {context,page,failures};
}
async function allRows(page) {
  await page.locator('#clearFilters').click();
  await page.waitForFunction(()=>document.getElementById('tbody')?.dataset.total==='7775');
  assert.equal(await page.locator('#v2').innerText(),'7,775');
}
async function downloadCsv(page,name) {
  const event=page.waitForEvent('download');await page.locator('#exportInline').click();
  const download=await event;const path=resolve(OUT,name);await download.saveAs(path);
  const bytes=readFileSync(path);return {bytes,rows:parseCsv(bytes.toString('utf8')),sha256:sha(bytes)};
}
async function activate(page,id) {
  const tab=page.locator('#'+id);await tab.focus();await page.keyboard.press('Enter');
  await page.waitForFunction(id=>document.getElementById(id)?.getAttribute('aria-selected')==='true',id);
  const panelId=await tab.getAttribute('aria-controls');
  assert.ok(panelId, id+' controls a panel');
  const panel=page.locator('#'+panelId);assert.equal(await panel.isVisible(),true,id+' panel visible');
  assert.equal(await panel.getAttribute('aria-labelledby'),id,id+' panel accessible name follows selected tab');
}
let browser;
try {
  browser=await chromium.launch({headless:true});receipt.browser=browser.version();
  // Frozen baseline is exercised through its existing controls, not a duplicated exporter.
  const base=await openPage(browser,1440,BASELINE);
  await allRows(base.page);
  await base.page.waitForFunction(()=>!/^loading/i.test(document.getElementById('newsMeta')?.textContent||'loading'));
  const baselineCsv=await downloadCsv(base.page,'baseline-v924-all.csv');
  assert.equal(baselineCsv.rows.length,7776);
  await base.context.close();
  pass('V9.24 baseline browser exports full canonical CSV',{rows:7775,sha256:baselineCsv.sha256});
  for(const width of [390,393,1440]) {
    const {context,page,failures}=await openPage(browser,width,CANDIDATE);
    const blocks=page.locator('main > section');assert.equal(await blocks.count(),2,'exactly two principal blocks');
    const titles=[];
    for(const block of await blocks.all()) titles.push(await block.locator('h2').first().innerText());
    const normalised=titles.map(s=>s.replace(/\s+/g,' ').trim().toUpperCase());
    assert.deepEqual(normalised,['GLOBALGRID2050 HEADLINES','REPD PIPELINE ANALYTICS'],'principal headings');
    const tabs=page.locator('#officialRegister [role="tab"]');assert.equal(await tabs.count(),4,'four principal tabs');
    assert.deepEqual((await tabs.allTextContents()).map(s=>s.replace(/\s+/g,' ').trim()),['Solar','BESS','Grid','Data Centres']);
    assert.equal(await page.getByRole('columnheader',{name:'NEWS SIGNAL',exact:true}).count(),0,'withdrawn signal column');
    assert.equal(await page.locator('#solar1000Pilot').isVisible().catch(()=>false),false);
    const headings=await page.locator('main h1, main h2, main h3').allTextContents();
    assert.ok(!headings.some(s=>/REGISTER CHANGES: JULY TO OCTOBER|SOLAR 1000 EVIDENCE PILOT/i.test(s)));
    await activate(page,'solarTab');
    await page.waitForFunction(()=>document.getElementById('tbody')?.dataset.total==='3604');
    await page.locator('#solarTab').focus();await page.keyboard.press('ArrowRight');
    assert.equal(await page.locator('#bessTab').evaluate(n=>n===document.activeElement),true,'ArrowRight moves tab focus');
    await page.keyboard.press('Enter');
    await page.waitForFunction(()=>document.getElementById('bessTab')?.getAttribute('aria-selected')==='true');
    const tech=await page.locator('#tbody tr .badge').allTextContents();assert.ok(tech.length>0&&tech.every(t=>/battery/i.test(t)),'BESS rows only');
    await page.locator('#bessTab').focus();await page.keyboard.press('End');
    assert.equal(await page.locator('#datacentreTab').evaluate(n=>n===document.activeElement),true,'End focuses final tab');
    await page.keyboard.press('Home');
    assert.equal(await page.locator('#solarTab').evaluate(n=>n===document.activeElement),true,'Home focuses first tab');
    await activate(page,'solarTab');await allRows(page);
    await page.locator('#search').fill('8162');
    await page.waitForFunction(()=>[...document.querySelectorAll('#tbody tr')].some(tr=>tr.id==='repd-8162'));
    const mapHref=await page.locator('#repd-8162 a.atlaslink').getAttribute('href');
    const baselineReceiver=await import(pathToFileURL(resolve(BASELINE,'scripts/core/atlas-receiver-v9-7.js')));
    const dataManifest=JSON.parse(readFileSync(resolve(BASELINE,'data/v9.1/build_manifest.json'),'utf8'));
    const original=dataManifest.project_partitions.flatMap(p=>JSON.parse(readFileSync(resolve(BASELINE,p.path),'utf8')).projects)
      .find(p=>String(p.repd_ref)==='8162');
    assert.equal(mapHref,baselineReceiver.buildAtlasDeepLinkV9_7(original),'rendered search result original MAP route');
    const note = width <= 768 ? page.locator('#repd-8162 .mobile-machine-note') : page.locator('#repd-8162 .machine-note-cell .machine-note-button');
    await note.click();
    assert.equal(await page.locator('.machine-note-dialog').isVisible(),true,'Machine Read Notes remain reachable after signal column removal');
    assert.match(await page.locator('.machine-note-dialog').innerText(),/INSUFFICIENT EVIDENCE|NOT INDEPENDENTLY VERIFIED/);
    await page.locator('.machine-note-close').click();
    const searched=await downloadCsv(page,`candidate-search-${width}.csv`);
    const refColumn=searched.rows[0].indexOf('REPD Ref');assert.ok(refColumn>=0);
    assert.ok(searched.rows.slice(1).some(r=>r[refColumn]==='8162'),'searched CSV contains correct REPD identity');
    await allRows(page);
    await page.waitForFunction(()=>!/^loading/i.test(document.getElementById('newsMeta')?.textContent||'loading'));
    if(width===1440) {
      const candidateCsv=await downloadCsv(page,'candidate-v928-all.csv');
      assert.deepEqual(candidateCsv.rows,baselineCsv.rows,'all exported fields and row order equal V9.24');
      pass('full candidate CSV equals V9.24 across all canonical fields and 7,775 rows',{sha256:candidateCsv.sha256});
    }
    await page.waitForFunction(()=>['snapshot','unavailable','failed'].includes(document.getElementById('newsStatus')?.dataset.state));
    const sourceState=await page.locator('#newsStatus').getAttribute('data-state');
    assert.ok(['snapshot','unavailable','failed'].includes(sourceState),'offline headline state disclosed: '+sourceState);
    assert.ok(await page.locator('#liveNews .ln-item').count()>0,'pinned existing source headlines remain useful offline');
    for(const row of await page.locator('#liveNews .ln-item').all()) {
      assert.match(await row.locator('.ln-title').getAttribute('href'),/^https:\/\//,'original source HTTPS link');
      assert.ok((await row.locator('.ln-meta').innerText()).includes('·'),'publisher/date attribution');
    }
    assert.doesNotMatch(await page.locator('#liveNews').innerText(),/\bPriority\s+\d/i,'internal ranking stays hidden');
    const geometry=await page.evaluate(()=>({viewport:innerWidth,width:document.documentElement.scrollWidth,
      font:getComputedStyle(document.body).fontFamily,background:getComputedStyle(document.body).backgroundColor}));
    assert.ok(geometry.width<=width+2,'page remains within viewport');assert.match(geometry.font,/mono|courier/i,'V9.24 monospace family');
    await page.evaluate(()=>{document.querySelector('.main').scrollTop=0;window.scrollTo(0,0);});
    await page.screenshot({path:resolve(OUT,`preview-solar-${width}.png`)});
    await activate(page,'gridTab');
    await page.waitForFunction(()=>document.getElementById('gridDirectory')?.dataset.state==='directory-only');
    assert.equal(await page.locator('#gridDirectory .grid-source').count(),14,'source directories remain distinct from project events');
    assert.match(await page.locator('#gridPanel').innerText(),/REVIEW_REQUIRED|review required|unassessed|restricted|source|unavailable/i,'honest grid state');
    await page.screenshot({path:resolve(OUT,`preview-grid-${width}.png`)});
    await activate(page,'datacentreTab');
    await page.waitForFunction(()=>document.querySelectorAll('#datacentreHost .ggdc-table tbody tr').length===54);
    assert.match(await page.locator('#datacentreHost').innerText(),/not assessed|not_assessed/i);
    assert.doesNotMatch(await page.locator('#datacentreHost').innerText(),/100 verified operating/i);
    await page.screenshot({path:resolve(OUT,`preview-datacentre-${width}.png`)});
    await page.locator('#datacentreHost [data-kind="global"]').click();
    await page.waitForFunction(()=>document.querySelectorAll('#datacentreHost .ggdc-table tbody tr').length===100);
    const globalDownloadEvent=page.waitForEvent('download');
    await page.locator('#datacentreHost button.ggdc-download').click();
    const globalDownload=await globalDownloadEvent;
    const globalCsvPath=resolve(OUT,`candidate-global-datacentres-${width}.csv`);
    await globalDownload.saveAs(globalCsvPath);
    assert.equal(parseCsv(readFileSync(globalCsvPath,'utf8')).length,101,'Global view must export all 100 displayed leads, not the UK subset');
    const country=page.locator('#datacentreHost select[aria-label="Country"]');
    const foreign=await country.locator('option').evaluateAll(options=>options.find(o=>o.value&&o.textContent!=='United Kingdom').value);
    await country.selectOption(foreign);
    const foreignRows=await page.locator('#datacentreHost .ggdc-table tbody tr').count();
    assert.ok(foreignRows>0&&foreignRows<100,'foreign country filter yields a bounded visible subset');
    const foreignDownloadEvent=page.waitForEvent('download');
    await page.locator('#datacentreHost button.ggdc-download').click();
    const foreignDownload=await foreignDownloadEvent;
    const foreignCsvPath=resolve(OUT,`candidate-country-datacentres-${width}.csv`);
    await foreignDownload.saveAs(foreignCsvPath);
    assert.equal(parseCsv(readFileSync(foreignCsvPath,'utf8')).length,foreignRows+1,'country CSV matches displayed foreign leads');
    await page.locator('#contextDisclosure > summary').click();
    await page.waitForFunction(()=>document.querySelector('#contextHost [data-transition-context-root]')?.dataset.state==='available');
    assert.equal(await page.locator('#contextHost [data-context-id]').count(),14);
    assert.equal(await page.locator('#contextHost [data-figure-claim]').count(),3);
    assert.deepEqual(await page.locator('#contextHost').evaluate(host=>[...host.childNodes].filter(n=>n.nodeType===Node.TEXT_NODE&&n.textContent.trim()).map(n=>n.textContent)),[],'successful Context mount removes unavailable placeholder');
    await activate(page,'solarTab');assert.equal(await page.locator('#tbody').isVisible(),true,'return from optional modules preserves canonical table');
    assert.deepEqual(failures,[],'uncaught browser JavaScript errors');
    pass(`integrated frame, keyboard tabs, search, CSV, original MAP, offline source states and optional hosts at ${width}`,{geometry,headline_state:sourceState});
    await context.close();
  }
  const bad=await openPage(browser,393,CANDIDATE,true);
  await activate(bad.page,'datacentreTab');
  await bad.page.waitForFunction(()=>/unavailable/i.test(document.getElementById('datacentreHost')?.innerText||''));
  assert.equal(await bad.page.locator('#datacentreHost .ggdc-table tbody tr').count(),0,'integrated corrupted source clears DC rows');
  await activate(bad.page,'solarTab');await allRows(bad.page);
  await bad.page.screenshot({path:resolve(OUT,'preview-after-dc-integrity-failure-393.png')});
  await bad.context.close();pass('Data Centre corrupted served bytes fail closed while canonical REPD remains usable');
  for (const scenario of ['context-manifest','context-data']) {
    const missing=await openPage(browser,393,CANDIDATE,scenario);
    await missing.page.locator('#contextDisclosure > summary').click();
    await missing.page.waitForFunction(()=>/Context unavailable/.test(document.getElementById('contextHost')?.textContent||''));
    assert.equal(await missing.page.locator('#contextHost [data-context-id], #contextHost [data-figure-claim]').count(),0);
    await allRows(missing.page);
    await missing.context.close();
    pass(scenario+' fails closed without context figures or REPD regression');
  }
  const production=await openPage(browser,393,CANDIDATE,false,true);
  assert.equal(await production.page.locator('#contextDisclosure').isVisible(),false,'unaccepted preview-only Context stays withheld on publication host');
  assert.equal(await production.page.locator('#contextHost [data-context-id], #contextHost [data-figure-claim]').count(),0);
  await allRows(production.page);
  await production.context.close();
  pass('production host withholds preview-only Context and retains complete REPD register');
  receipt.status='PASS';
} catch(error) {receipt.status='FAIL';receipt.failure=error.stack||String(error);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));
}

Invariants

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

storageglobalgrid2050 / automation/v928_preview/invariants.mjs · lines 1–137 of 137 · Entry point · pattern population (shared by 6 files)

What it does
It loads pipeline headlines snapshot and snapshot provenance. Defines 7 functions or classes, including bytes, json, sha, git, pass. 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 registry.json; JSON file pipeline_headlines.snapshot.json; JSON file snapshot-provenance.json; JSON file candidates.json; JSON file homepage_v142-metrics.json. Out: JSON file invariants.json.
Downstream impact
Used directly by 1 file: GlobalGrid2050 V928 Preview Acceptance Workflow (globalgrid2050).
What it achieves
It is built from the bytes step (`bytes`), the JSON step (`json`) and the sha step (`sha`). Independent preservation gate. Imports the established MAP contract; no network.
Why it matters
Run by GlobalGrid2050 V928 Preview Acceptance Workflow.
Application
globalgrid2050 · automation/v928_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 V928 Preview Acceptance Workflow (workflow run)
Produces
bytes, json, sha, git, pass, population, directoryBytes
Defines here
bytes, json, sha, git, pass, population, directoryBytes
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/v928_preview/invariants.mjs:1-137 · blob 58d814f98326f82635474d00471452f8b5d5c1ea · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: production_core
/** Independent preservation gate. Imports the established MAP contract; no network. */
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, relative, sep } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';

const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '../..');
const CANDIDATE = resolve(ROOT, process.env.V928_CANDIDATE || 'uk_renewables_pipeline/202611161757');
const BASELINE = resolve(ROOT, 'uk_renewables_pipeline/202611161244');
const BASE_SHA = '65bcc01e0d7e4dc073e759345727e53cf7a95752';
const HISTORY_BASE_SHA = process.env.V928_BASE_SHA || execFileSync('git',['rev-parse','origin/main'],{cwd:ROOT,encoding:'utf8'}).trim();
const OUT = process.env.V928_OUT ? resolve(process.env.V928_OUT) : null;
assert.ok(CANDIDATE.startsWith(ROOT + sep), 'candidate must be inside this repository');
const bytes = p => readFileSync(p);
const json = p => JSON.parse(bytes(p).toString('utf8'));
const sha = 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']),
  preservation_base: BASE_SHA, historical_base: HISTORY_BASE_SHA, candidate: relative(ROOT, CANDIDATE).replaceAll('\\', '/'),
  baseline: relative(ROOT, BASELINE).replaceAll('\\', '/'), checks: [], limitations: [
    'Offline gate proves original link construction, not execution of the public GridAtlas receiver.',
    'Preserved records and fixture source states are not live-source or publication acceptance.'] };
function pass(name, details) { receipt.checks.push({ name, status: 'PASS', ...details }); console.log('PASS:', name); }
async function population(folder) {
  const manifest = json(resolve(folder, 'data/v9.1/build_manifest.json'));
  const rows = [];
  for (const part of manifest.project_partitions) {
    const raw = bytes(resolve(folder, part.path));
    assert.equal(sha(raw), part.sha256, `${folder}/${part.path} pinned bytes`);
    const doc = JSON.parse(raw.toString('utf8'));
    assert.equal(doc.projects.length, part.record_count, `${part.path} declared count`);
    rows.push(...doc.projects);
  }
  for (const part of manifest.atlas_partitions) {
    const raw = bytes(resolve(folder, part.path));
    assert.equal(sha(raw), part.sha256, `${part.path} atlas pinned bytes`);
    assert.equal(JSON.parse(raw).features.length, part.feature_count, `${part.path} atlas count`);
  }
  assert.equal(rows.length, 7775, 'canonical REPD universe');
  assert.equal(rows.filter(r => r.technology === 'solar').length, 3604, 'canonical solar universe');
  assert.equal(new Set(rows.map(r => String(r.repd_ref))).size, 7775, 'unique canonical REPD identities');
  return {manifest, rows};
}
try {
  const originalRegistry = JSON.parse(execFileSync('git',['show',BASE_SHA+':automation/pipeline_release/registry.json'],{cwd:ROOT,encoding:'utf8'}));
  const currentRegistry = json(resolve(ROOT,'automation/pipeline_release/registry.json'));
  assert.deepEqual(currentRegistry.versions.slice(0,originalRegistry.versions.length),originalRegistry.versions,
    'all pre-existing release records, Unicode and probes must retain their exact meanings');
  for (const key of Object.keys(originalRegistry).filter(key=>!['versions','release_candidate'].includes(key))) {
    assert.deepEqual(currentRegistry[key],originalRegistry[key], 'unrelated registry metadata '+key);
  }
  pass('prior release registry records and unrelated metadata preserved, including Unicode');
  function directoryBytes(folder) {
    return readdirSync(folder).reduce((total, name) => {
      if (name === '__pycache__') return total;
      const file = resolve(folder, name);
      return total + (statSync(file).isDirectory() ? directoryBytes(file) : statSync(file).size);
    }, 0);
  }
  const editionBytes = directoryBytes(CANDIDATE);
  assert.ok(editionBytes <= 18 * 1024 * 1024, 'actual working candidate must fit 18 MiB, including newly staged/untracked assets');
  pass('actual complete candidate fits unchanged 18 MiB budget', {bytes: editionBytes, limit: 18 * 1024 * 1024});
  const snapshot = bytes(resolve(CANDIDATE, 'news/pipeline_headlines.snapshot.json'));
  const snapshotReceipt = json(resolve(CANDIDATE, 'news/snapshot-provenance.json'));
  const originalSnapshot = execFileSync('git', ['show', snapshotReceipt.source_commit + ':' + snapshotReceipt.source_path], {cwd:ROOT});
  assert.deepEqual(snapshot, originalSnapshot, 'saved headline snapshot must retain exact existing owner-feed bytes');
  assert.equal(sha(snapshot), snapshotReceipt.sha256);
  assert.equal(JSON.parse(snapshot).items.length, snapshotReceipt.items);
  pass('source-attributed headline snapshot equals pinned existing feed', {items:snapshotReceipt.items,source_commit:snapshotReceipt.source_commit,sha256:snapshotReceipt.sha256});
  const [candidate, baseline] = await Promise.all([population(CANDIDATE), population(BASELINE)]);
  assert.deepEqual(candidate.rows, baseline.rows, 'every official row and its order must equal frozen V9.24');
  pass('canonical 7,775 rows / 3,604 solar with complete V9.24 record parity', {record_count:7775, solar_count:3604});
  for (const rel of ['solar1000/manifest.json', 'solar1000/candidates.json']) {
    assert.deepEqual(bytes(resolve(CANDIDATE, rel)), bytes(resolve(BASELINE, rel)), `${rel} frozen bytes`);
  }
  const selected = json(resolve(CANDIDATE, 'solar1000/manifest.json'));
  assert.equal(selected.selection, 'numeric-repd-ref-ascending');
  assert.equal(selected.ids.length, 1000);
  assert.deepEqual(selected.ids, candidate.rows.filter(r => r.technology === 'solar')
    .map(r => String(r.repd_ref)).sort((a,b) => Number(a)-Number(b)).slice(0,1000));
  assert.equal(selected.independently_verified, 0);
  assert.equal(selected.not_researched, 998);
  const leads = json(resolve(CANDIDATE, 'solar1000/candidates.json'));
  assert.equal(leads.length, 2);
  assert.ok(leads.every(r => r.rights_basis === 'unknown' && r.verification === 'provisional_candidate_only'));
  pass('ordered Solar-1000 identities, seed/provenance bytes and provisional source states preserved',
    {selection_sha256:sha(bytes(resolve(CANDIDATE,'solar1000/manifest.json'))), first:selected.ids[0], last:selected.ids.at(-1)});
  const candidateReceiver = await import(pathToFileURL(resolve(CANDIDATE,'scripts/core/atlas-receiver-v9-7.js')));
  const baselineReceiver = await import(pathToFileURL(resolve(BASELINE,'scripts/core/atlas-receiver-v9-7.js')));
  let located = 0;
  for (let i=0; i<candidate.rows.length; i++) {
    const row = candidate.rows[i];
    const original = baselineReceiver.buildAtlasDeepLinkV9_7(baseline.rows[i]);
    const href = candidateReceiver.buildAtlasDeepLinkV9_7(row);
    assert.equal(href, original, `REPD ${row.repd_ref}: original MAP route/parameters`);
    const url = new URL(href);
    assert.equal(url.searchParams.get('repd_ref'), String(row.repd_ref));
    assert.equal(url.searchParams.get('technology'), row.technology);
    if (candidateReceiver.atlasCentresOnRepdPointV9_7(row)) located++;
  }
  const legacy = 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', {located, ref_only:7775-located, legacy});
  const changed = new Set([
    ...git(['diff','--name-only',HISTORY_BASE_SHA,'--']).split(/\r?\n/),
    ...git(['ls-files','--others','--exclude-standard']).split(/\r?\n/),
  ].filter(Boolean));
  const historical=protectedEditionChanges({cwd:ROOT,base:HISTORY_BASE_SHA});
  assert.deepEqual(historical,[],'every numeric edition present at the pinned published base remains immutable');
  const restoreFiles = new Set(['homepage_versions/homepage_v142.html','homepage_versions/homepage_v142-metrics.json']);
  for (const path of restoreFiles) {
    assert.equal(git(['ls-tree', BASE_SHA, '--', path]), '', 'original V142 restore point was additive against its original source base');
    if (git(['ls-tree', HISTORY_BASE_SHA, '--', path])) {
      assert.deepEqual(bytes(resolve(ROOT,path)),execFileSync('git',['show',HISTORY_BASE_SHA+':'+path],{cwd:ROOT}),'existing restore point remains immutable');
    }
  }
  const oldRestoreReadme = execFileSync('git',['show',BASE_SHA+':homepage_versions/README.md'],{cwd:ROOT,encoding:'utf8'});
  assert.ok(bytes(resolve(ROOT,'homepage_versions/README.md')).toString('utf8').replaceAll('\r\n','\n').startsWith(oldRestoreReadme.replaceAll('\r\n','\n')),
    'restore-point ledger retains its entire prior history');
  const currentRestoreReadme = execFileSync('git',['show',HISTORY_BASE_SHA+':homepage_versions/README.md'],{cwd:ROOT,encoding:'utf8'});
  assert.ok(bytes(resolve(ROOT,'homepage_versions/README.md')).toString('utf8').replaceAll('\r\n','\n').startsWith(currentRestoreReadme.replaceAll('\r\n','\n')), 'restore-point ledger retains the current published history too');
  const forbidden = [...changed].filter(p =>
    !restoreFiles.has(p) && p !== 'homepage_versions/README.md' && (
    /^(?:index\.html|catalogue\/homepage-owner\.json|homepage-shell\/|homepage_versions\/|homepage_v\d+\.html)/.test(p)));
  assert.deepEqual(forbidden, [], 'historical editions and operative homepage bytes must remain unchanged');
  pass('historical editions and operative homepage preserved against source base');
  receipt.source_sha256 = Object.fromEntries(['index.html','data/v9.1/build_manifest.json','solar1000/manifest.json']
    .map(p=>[p,sha(bytes(resolve(CANDIDATE,p)))]));
  receipt.status = 'PASS';
} catch(error) {
  receipt.status = 'FAIL'; receipt.failure = error.stack || String(error); throw error;
} finally {
  if (OUT) { mkdirSync(OUT,{recursive:true}); writeFileSync(resolve(OUT,'invariants.json'),JSON.stringify(receipt,null,2)+'\n'); }
}

Serve

A JavaScript module in the automation folder of GlobalGrid2050.

ingestglobalgrid2050 / automation/v928_preview/serve.mjs · lines 1–29 of 29 · Not reached from any entry point (candidate for review)

What it does
It loads data. Uses libraries node:http, node:fs, node:path, node:url. Side effects: reads or writes files.
What it achieves
Loopback-only preview; no deployment or write endpoint.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · automation/v928_preview · JavaScript module
Uses
node:http, node:fs, node:path, node:url
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/v928_preview/serve.mjs:1-29 · blob 6f12a2a2d1267f76a6e2e3fbcb28c585a48e7d2d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: unknown · users: none · canonical: unreached_review
/** Loopback-only preview; no deployment or write endpoint. */
import {createServer} from 'node:http';
import {existsSync,readFileSync,statSync} from 'node:fs';
import {dirname,extname,resolve,sep} from 'node:path';
import {fileURLToPath} from 'node:url';
const root=resolve(dirname(fileURLToPath(import.meta.url)),'../..');
const port=Number(process.env.V928_PORT||17828);
if(!Number.isInteger(port)||port<1||port>65535)throw new Error('Invalid loopback preview port');
const deadline=process.env.V928_DEADLINE_UTC?Date.parse(process.env.V928_DEADLINE_UTC):null;
if(deadline!==null&&(!Number.isFinite(deadline)||deadline<=Date.now()))throw new Error('Preview window has expired');
const types={'.html':'text/html','.js':'text/javascript','.mjs':'text/javascript','.css':'text/css',
  '.json':'application/json','.geojson':'application/geo+json','.csv':'text/csv','.png':'image/png','.svg':'image/svg+xml'};
const server=createServer((req,res)=>{
  try{
    if(!['GET','HEAD'].includes(req.method)){res.writeHead(405).end();return;}
    const path=decodeURIComponent(new URL(req.url,'http://localhost').pathname);
    if(path.split('/').some(part=>part.startsWith('.'))){res.writeHead(403).end();return;}
    let file=resolve(root,'.'+path);
    if(!file.startsWith(root+sep)){res.writeHead(403).end();return;}
    if(existsSync(file)&&statSync(file).isDirectory())file=resolve(file,'index.html');
    if(!existsSync(file)||!statSync(file).isFile()){res.writeHead(404).end();return;}
    res.writeHead(200,{'Content-Type':types[extname(file)]||'application/octet-stream',
      'Cache-Control':'no-store','X-Content-Type-Options':'nosniff'});
    res.end(req.method==='HEAD'?undefined:readFileSync(file));
  }catch{res.writeHead(400).end();}
});
server.listen(port,'127.0.0.1',()=>console.log(`Non-live preview: http://127.0.0.1:${port}/uk_renewables_pipeline/202611161757/`));
if(deadline!==null)setTimeout(()=>server.close(),deadline-Date.now());
for(const signal of ['SIGINT','SIGTERM'])process.on(signal,()=>server.close());

Browser

A JavaScript module in the automation folder of GlobalGrid2050 that draws snapshot provenance, pipeline headlines snapshot and substations, using SHA-256, and uses data from the GridAtlas repository.

renderglobalgrid2050 / automation/v929_preview/browser.mjs · lines 1–220 of 220 · Entry point · pattern orientationScreenshot (shared by 5 files)

What it does
It draws snapshot provenance, pipeline headlines snapshot and substations. Defines 13 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.
Why it exists in the grid workflow
Domain terms in the code: substations.
Inputs & outputs
In: data source: gridatlas data; CSV file v928-all.csv; JSON file build_manifest.json; CSV file v929-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 V929 Preview Acceptance Workflow (globalgrid2050).
What it achieves
It is built from the sha step (`sha`), the URL for helper (`urlFor`) and the pass step (`pass`). Real integrated V9.29 browser acceptance against exact source-byte fixtures.
Why it matters
Run by GlobalGrid2050 V929 Preview Acceptance Workflow.
Application
globalgrid2050 · automation/v929_preview · JavaScript module
Uses
GridAtlas — Atlas Page (estate URL), node:assert/strict, node:http, node:crypto, node:child_process, node:fs, node:path, node:os, node:url
Used by
run by GlobalGrid2050 V929 Preview Acceptance Workflow (workflow run), mentioned in Standalone (comment link)
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
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/browser.mjs:1-220 · blob 6ddd8f8f43e0f74bd9f43f6a4addf1b3e9a72a77 · 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.29 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.V929_CANDIDATE||'uk_renewables_pipeline/202611162354';
const candidate=resolve(ROOT,EDITION),baseline=resolve(ROOT,'uk_renewables_pipeline/202611161757');
const OUT=resolve(process.env.V929_OUT||resolve(tmpdir(),'gg2050-v929-preview'));
const {chromium}=process.env.V929_PLAYWRIGHT
  ? await import(pathToFileURL(resolve(process.env.V929_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();
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+'/'))return route.continue();if(sourceBytes.has(u)){let raw=sourceBytes.get(u);if(corrupt&&u===catalogue.layers.find(l=>l.id==='substations').data.url)raw=Buffer.concat([raw,Buffer.from(' ')]);return route.fulfill({status:200,contentType:'application/json',body:raw});}receipt.blocked_external  … [line shortened here: 433 characters; full line on GitHub]
  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');}
let browser;
try{
  browser=await chromium.launch({headless:true});receipt.browser=browser.version();
  if(!process.env.V929_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'),'v928-all.csv');assert.equal(oldCsv.rows.length,7776);await b.context.close();
  pass('frozen V9.28 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'),'v929-all.csv');assert.deepEqual(actual.rows,oldCsv.rows);pass('all 7,775 exported CSV rows/fields/order equal frozen V9.28',{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 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,`v929-solar-${width}.png`)});await tab(page,'gridTab');await page.screenshot({path:resolve(OUT,`v929-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();
  }
  }
  for(const profile of [
    {id:'pixel7',portrait:{width:412,height:839},landscape:{width:915,height:412}},
    {id:'compact393',portrait:{width:393,height:851},landscape:{width:851,height:393}},
    {id:'narrow390',portrait:{width:390,height:844},landscape:{width:844,height:390}},
  ]){
    const {context,page,errors}=await open(browser,profile.portrait.width,candidate,{mobile:true,height:profile.portrait.height});
    const session=await context.newCDPSession(page),orientations=[];
    // Keep Grid rendering on a second genuinely touch-selected page. A post-pan
    // compatibility-click suppression in the emulator must not mask rotation paint.
    const gridCompanion=await open(browser,profile.portrait.width,candidate,{mobile:true,height:profile.portrait.height});
    const gridSession=await gridCompanion.context.newCDPSession(gridCompanion.page);
    await touchTap(gridCompanion.page,'#gridTab');await gridCompanion.page.waitForFunction(()=>document.querySelector('#gridLayerHost .pn-count')?.textContent.includes('5,800'));
    await page.locator('#search').fill('8162');await page.waitForFunction(()=>document.getElementById('repd-8162'));assert.match(await page.locator('#repd-8162 a.atlaslink').getAttribute('href'),/repd_ref=8162/);await page.locator('#search').fill('');
    assert.match(await page.evaluate(()=>navigator.userAgent),/Android.*Pixel 7/);assert.equal(await page.evaluate(()=>navigator.maxTouchPoints>0),true);
    for(const [name,size] of [['portrait',profile.portrait],['landscape',profile.landscape],['portrait-return',profile.portrait]]){
      await session.send('Emulation.setDeviceMetricsOverride',{...size,deviceScaleFactor:2.625,mobile:true,screenWidth:size.width,screenHeight:size.height,screenOrientation:{type:name==='landscape'?'landscapePrimary':'portraitPrimary',angle:name==='landscape'?90:0}});
      await gridSession.send('Emulation.setDeviceMetricsOverride',{...size,deviceScaleFactor:2.625,mobile:true,screenWidth:size.width,screenHeight:size.height,screenOrientation:{type:name==='landscape'?'landscapePrimary':'portraitPrimary',angle:name==='landscape'?90:0}});
      await page.waitForFunction(size=>screen.width===size.width&&screen.height===size.height,size,{timeout:2500});
      await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve))));
      const viewport=await page.evaluate(()=>({width:innerWidth,height:innerHeight,physical:{width:screen.width,height:screen.height},visual:{width:visualViewport.width,height:visualViewport.height,scale:visualViewport.scale}}));
      assert.ok(Math.abs(viewport.width-size.width)<=1&&Math.abs(viewport.height-size.height)<=2,'rotation must retain requested CSS viewport without intrinsic-overflow shrink-to-fit: '+JSON.stringify({profile:profile.id,name,requested:size,actual:viewport}));
      assert.ok(Math.abs(viewport.visual.width*viewport.visual.scale-size.width)<=2,'actual visual viewport fills requested physical orientation');
      await page.evaluate(()=>window.scrollTo(0,0));
      const layout=await fullWidth(page),header=await painted(page,'.release-header');
      assert.equal(await page.locator('.release-links a').count(),6);assert.equal(await page.locator('#mapAtlasNav').getAttribute('href'),'https://ventusltd.github.io/gridatlas/atlas/');
      const headerScreenshot=await orientationScreenshot(session,`rotation-${profile.id}-${name}-header.png`,size);
      assert.ok(Math.abs((await page.evaluate(()=>innerWidth))-size.width)<=1,'taking proof must not reset landscape viewport');
      await page.waitForFunction(()=>document.getElementById('tbody')?.dataset.total==='3604');
      const rowPaint=await painted(page,'#tbody tr');
      const wrap=page.locator('#repdPanel .tablewrap');await wrap.scrollIntoViewIfNeeded();
      const table=await wrap.evaluate(n=>({client:n.clientWidth,scroll:n.scrollWidth,left:n.scrollLeft,overflow:getComputedStyle(n).overflowX}));
      assert.ok(table.client<=viewport.width,'table overflow remains inside viewport');
      if(table.scroll>table.client+2){
        await wrap.evaluate(n=>n.scrollLeft=0);const r=await wrap.boundingBox();
        const point={x:Math.max(20,Math.min(viewport.width-20,r.x+r.width*.75)),y:(Math.max(0,r.y)+Math.min(viewport.height,r.y+r.height))/2};
        table.touchTarget=await page.evaluate(p=>{const n=document.elementFromPoint(p.x,p.y),w=document.querySelector('#repdPanel .tablewrap');return{point:p,target:n?.tagName,inWrapper:!!n&&w.contains(n),rect:w.getBoundingClientRect().toJSON(),touchAction:getComputedStyle(w).touchAction,visualViewport:{scale:visualViewport.scale,offsetTop:visualViewport.offsetTop,height:visualViewport.height}};},  … [line shortened here: 407 characters; full line on GitHub]
        assert.equal(table.touchTarget.inWrapper,true,'touch drag must start inside actual scroll container: '+JSON.stringify(table.touchTarget));
        await touchDrag(session,{...point,dx:-Math.min(200,viewport.width*.45)});
        try{await page.waitForFunction(()=>document.querySelector('#repdPanel .tablewrap').scrollLeft>0,null,{timeout:2500});}catch(error){throw Error('Trusted touch horizontal pan did not move table: '+JSON.stringify({...table,after:await wrap.evaluate(n=>n.scrollLeft)}),{cause:error});}table.touchScrollLeft=await wrap.evaluate(n=>n.scrollLeft);
      }
      await page.evaluate(()=>window.scrollTo(0,0));
      const scrollBefore=await page.evaluate(()=>scrollY);
      await touchDrag(session,{x:viewport.width-6,y:Math.floor(viewport.height*.8),dy:-Math.min(320,Math.floor(viewport.height*.6))});
      await page.waitForFunction(before=>scrollY>before,scrollBefore,{timeout:2500});
      const nativeScroll=await page.evaluate(()=>({y:scrollY,scrollHeight:document.scrollingElement.scrollHeight,clientHeight:document.scrollingElement.clientHeight}));
      assert.ok(nativeScroll.scrollHeight>nativeScroll.clientHeight);
      receipt.rotation_in_progress={profile:profile.id,name,...size,viewport,layout,header,rowPaint,table,nativeScroll,touchMethod:'trusted CDP touchStart/move/end; Playwright actionability-checked locator.tap'};
      await page.evaluate(()=>{window.__rotationTouchRecords=[];for(const name of ['touchstart','touchend','click'])document.addEventListener(name,event=>window.__rotationTouchRecords.push({type:event.type,id:event.target.id,tag:event.target.tagName,trusted:event.isTrusted}),{capture:true,once:true});});
      await touchTap(page,'#solarTab');await new Promise(r=>setTimeout(r,350));await touchTap(page,'#solarTab');
      receipt.rotation_in_progress.postPanTap=await page.evaluate(()=>({target:'solarTab',selected:document.getElementById('solarTab').getAttribute('aria-selected'),events:window.__rotationTouchRecords,url:location.href,scrollY}));
      receipt.rotation_in_progress.postPanTap.pages=context.pages().length;
      const gridLayout=await fullWidth(gridCompanion.page),gridPaint=await painted(gridCompanion.page,'#gridLayerHost tbody tr');assert.equal(await gridCompanion.page.locator('#gridLayerHost tbody tr').count(),100);
      const gridScreenshot=await orientationScreenshot(gridSession,`rotation-${profile.id}-${name}-grid.png`,size);
      assert.equal(await page.locator('#tbody').getAttribute('data-total'),'3604');
      orientations.push({name,...size,viewport,layout,header,headerScreenshot,rowPaint,table,nativeScroll,gridLayout,gridPaint,gridScreenshot,sourceRows:5800,searchAndMapIdentity:'REPD8162 checked before panning; canonical population retained',postPanTouchEvents:receipt.rotation_in_progress.postPanTap.events});
    }
    assert.deepEqual(errors,[]);assert.deepEqual(gridCompanion.errors,[]);pass('Android-UA/touch-emulated rotation remains full-width and painted with native scrolling',{profile:profile.id,orientations,actualHandset:false,touchNavigation:'Grid selected by real touch before panning on companion rotation page; post-pan compatibility-click suppression is recorded rather than substituted with JS/mouse  … [line shortened here: 602 characters; full line on GitHub]
  }
  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));}