GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Automation and CI / globalgrid2050 / automation/grid_notice_ui/20261117-v938

Catalogue and 11 more files

A JavaScript module in the primary note ui folder of GlobalGrid2050 that works with part, pipeline headlines, solar and the Renewable Energy Planning Database (REPD) register, using SHA-256.

625 lines of JavaScript from globalgrid2050, in 12 files. Topic: Automation and CI. Section 1741 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. View render · globalgrid2050 / automation/grid_notice_ui/20261117-v938/view.mjs lines 1–19
  2. Entry Browser render · globalgrid2050 / automation/journey_entry_ui/20261118/entry.browser.mjs lines 1–34
  3. Model transform · globalgrid2050 / automation/journey_entry_ui/20261118/model.mjs lines 1–37
  4. Model Test test · globalgrid2050 / automation/journey_entry_ui/20261118/model.test.mjs lines 1–36
  5. Verify Closure ingest · globalgrid2050 / automation/journey_entry_ui/20261118/verify-closure.mjs lines 1–18
  6. View Browser interaction · globalgrid2050 / automation/journey_entry_ui/20261118/view.browser.mjs lines 1–39
  7. View interaction · globalgrid2050 / automation/journey_entry_ui/20261118/view.mjs lines 1–97
  8. Browser render · globalgrid2050 / automation/journey_return_ui/20261118/browser.mjs lines 1–38
  9. Restore Test test · globalgrid2050 / automation/journey_return_ui/20261118/restore.test.mjs lines 1–56
  10. Verify Closure ingest · globalgrid2050 / automation/journey_return_ui/20261118/verify-closure.mjs lines 1–10
  11. Catalogue transform · globalgrid2050 / automation/primary_note_ui/b5eed3d2ae878c78e5153be06ef531c11fff2148/catalogue.mjs lines 1–122
  12. Model transform · globalgrid2050 / automation/primary_note_ui/b5eed3d2ae878c78e5153be06ef531c11fff2148/model.mjs lines 1–119

View

A JavaScript module in the grid notice ui folder of GlobalGrid2050 that draws notice and the Renewable Energy Planning Database (REPD) register.

renderglobalgrid2050 / automation/grid_notice_ui/20261117-v938/view.mjs · lines 1–19 of 19 · version 2026-11-17 · Entry point

What it does
It draws notice and the REPD register. Defines el. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain terms in the code: the REPD register.
Inputs & outputs
In: JSON file notice.json.
Downstream impact
Used directly by 1 file: GlobalGrid2050 — UK Renewables Pipeline Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/). Reached from 4 other entry points, including GlobalGrid2050 Pipeline Legal Evidence Workflow (globalgrid2050); V923 Public Readback Workflow (neural-link-between-agents); A4 Legal Model (globalgrid2050).
What it achieves
Its code works with 2 GW. It responds to input events.
Why it matters
Loaded by the UK Renewables Pipeline page at https://globalgrid2050.com/uk_renewables_pipeline/202611280922/.
Application
globalgrid2050 · automation/grid_notice_ui/20261117-v938 · JavaScript module
Uses
Model (import)
Used by
loaded by GlobalGrid2050 — UK Renewables Pipeline Page (script src)
Produces
el
Defines here
el
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/grid_notice_ui/20261117-v938/view.mjs:1-19 · blob 5a516bca2352e3b507fcdff928224585b709d1f8 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: production_core
import {acceptedNotice} from './model.mjs';
const doc=document,panel=doc.getElementById('gridPanel'),layer=doc.getElementById('gridLayerHost');
if(panel&&layer){
 const el=(tag,text)=>{const n=doc.createElement(tag);if(text!==undefined)n.textContent=text;return n;};
 const host=el('div');host.className='pn-grid-notice';host.dataset.state='loading';host.append(el('p','Source-qualified government notice loading.'));layer.after(host);
 try{
  const response=await fetch(new URL('notice.json',import.meta.url),{cache:'no-store'});if(!response.ok)throw Error('Notice unavailable');const f=await acceptedNotice(await response.json());if(!f)throw Error('Independent fact-rights review required');
  host.replaceChildren();host.dataset.state='reviewed-facts';host.dataset.noticeCount='1';host.append(el('h3','Government grid notice'),el('p','1 source-qualified notice · 2 government documents · not a grid asset or REPD update count'));
  const filter=el('input'),count=el('p','1 of 1 source-qualified notices match');filter.type='search';filter.placeholder='Filter notice title, operator or source';filter.setAttribute('aria-label','Filter government grid notices');count.setAttribute('role','status');host.append(filter,count);
  const record=el('article');record.append(el('h4','Sea Link · EN020026'),el('p','Consented · 30 October 2026 (DAY precision). Reported network operator: NGET. Government publishers are separate from the operator.'),el('p','Proposed Suffolk–Kent HVDC transmission link; planned upper bound up to 2 GW, not current available or commissioned capacity.'));
  const details=el('details'),summary=el('summary','Source dates, attribution and known unknowns');details.append(summary);
  for(const d of f.documents){
   const p=el('p'),a=el('a',d.publisher);a.href=d.url;a.target='_blank';a.rel='noopener noreferrer';p.append(a,' · published '+d.published_date.value+' (DAY); retrieved '+d.retrieved_at);details.append(p);
   for(const [name,date]of Object.entries(d.milestones||{}))details.append(el('p',name.replaceAll('_',' ')+': '+date.value+' (DAY)'));
  }
  details.append(el('p','Narrow government-authored facts under the stated Open Government Licence v3.0 only. Images and linked third-party material are excluded.'),el('p','Current capacity, commissioning, connection, project joins and coordinates remain unknown. No REPD/ETYS match, cross-border interconnector row or VERIFIED association is created.'));record.append(details);host.append(record);
  filter.addEventListener('input',()=>{record.hidden=!['Sea Link EN020026 NGET consented Suffolk Kent HVDC',...f.documents.map(d=>d.publisher)].join(' ').toLocaleLowerCase().includes(filter.value.trim().toLocaleLowerCase());host.dataset.filteredCount=record.hidden?'0':'1';count.textContent=(record.hidden?'0':'1')+' of 1 source-qualified notices match';});host.dataset.filteredCount='1';
 }catch{host.dataset.state='withheld';host.replaceChildren(el('p','Source-qualified government notices unavailable: source integrity or independent fact-rights review is pending. Existing Grid layers remain separate and usable.'));}
}

Entry Browser

A JavaScript module in the journey entry ui folder of GlobalGrid2050 covering the Renewable Energy Planning Database (REPD) register and substations. It is built from the inspect step (`inspect`).

renderglobalgrid2050 / automation/journey_entry_ui/20261118/entry.browser.mjs · lines 1–34 of 34 · version 2026-11-18 · Not reached from any entry point (candidate for review) · pattern inspect (shared by 40 files)

What it does
It draws the REPD register and substations. Defines inspect. Uses libraries node:assert/strict, node:http, node:fs, node:path, node:url. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain terms in the code: the REPD register, substations. README: "`entry.browser.mjs` exercises the real Pipeline host and existing pinned remote Data Centre/substation inputs at 393/1440."
Inputs & outputs
Out: JSON file receipt.json.
Downstream impact
Used directly by 1 file: Browser (globalgrid2050).
What it achieves
Source-host integration. PREVIEW=1 composes the additive module into V9.42 only in a local HTTP response; this is not public/edition acceptance.
Why it matters
Imported by Browser.
Application
globalgrid2050 · automation/journey_entry_ui/20261118 · JavaScript module
Uses
node:assert/strict, node:http, node:fs, node:path, node:url
Used by
imported by Browser (import)
Produces
inspect
Defines here
inspect
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/journey_entry_ui/20261118/entry.browser.mjs:1-34 · blob 073de91043341febc05a06e6e2148483a9db7401 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: unknown · users: none · canonical: unreached_review
/* Source-host integration. PREVIEW=1 composes the additive module into V9.42
 * only in a local HTTP response; this is not public/edition acceptance. */
import assert from 'node:assert/strict';
import {createServer} from 'node:http';
import {readFileSync,writeFileSync,mkdirSync,existsSync} from 'node:fs';
import {resolve,dirname,extname,sep} from 'node:path';
import {fileURLToPath,pathToFileURL} from 'node:url';
const root=resolve(dirname(fileURLToPath(import.meta.url)),'../../..');
const edition=process.env.PN_JOURNEY_EDITION||'202611172355',preview=process.env.PN_JOURNEY_HOST_PREVIEW==='1';
assert.match(edition,/^\d{12}$/);const output=process.env.PN_JOURNEY_OUT||resolve(root,'work/journey-entry');mkdirSync(output,{recursive:true});
const {chromium}=await import(pathToFileURL(process.env.PLAYWRIGHT_MODULE||'D:/githubfiles/.qa-tools/node/node_modules/playwright/index.mjs').href);
const entryPath='/uk_renewables_pipeline/'+edition+'/';
for(const file of ['view.mjs','model.mjs','styles.css'])assert.ok(existsSync(new URL('./'+file,import.meta.url)),'materialize Journey module in sparse checkout: '+file);
const server=createServer((req,res)=>{try{const url=new URL(req.url,'http://local');let p=resolve(root,'.'+decodeURIComponent(url.pathname));assert.ok(p.startsWith(root+sep));if(url.pathname.endsWith('/'))p=resolve(p,'index.html');let bytes=readFileSync(p);if(url.pathname===entryPath||url.pathname===entryPath+'index.html'){
 const html=bytes.toString();if(preview)bytes=Buffer.from(html.replace('</body>','<link rel="stylesheet" href="/automation/journey_entry_ui/20261118/styles.css"><script type="module" src="/automation/journey_entry_ui/20261118/view.mjs"></script></body>'));else assert.ok(html.includes('journey_entry_ui/20261118/view.mjs'),'actual candidate must load Journey entry itself');
 }res.setHeader('Content-Type',({'.html':'text/html','.js':'text/javascript','.mjs':'text/javascript','.json':'application/json','.css':'text/css'})[extname(p)]||'application/octet-stream');res.end(bytes)}catch{res.writeHead(404).end()}});
await new Promise(r=>server.listen(0,'127.0.0.1',r));const base='http://127.0.0.1:'+server.address().port;
const browser=await chromium.launch(),report={scope:preview?'controlled local host composition; not a published edition':'actual local candidate entry integration',edition,results:[]};
try{for(const width of [393,1440]){
 const context=await browser.newContext({viewport:{width,height:852},isMobile:width<500,hasTouch:width<500}),page=await context.newPage(),errors=[];page.on('pageerror',e=>errors.push(e.message));
 const result={width,started:new Date().toISOString(),errors,consoleErrors:[],httpErrors:[]};report.results.push(result);page.on('console',m=>{if(m.type()==='error')result.consoleErrors.push(m.text())});page.on('response',r=>{if(r.status()>=400)result.httpErrors.push({url:r.url(),status:r.status()})});
 const inspect=async link=>{
  await link.scrollIntoViewIfNeeded();return link.evaluate(a=>{const r=a.getBoundingClientRect(),h=document.elementFromPoint(r.x+r.width/2,r.y+r.height/2);return{href:a.href,width:r.width,height:r.height,reachable:h===a||a.contains(h)}});
 };
 try{
 await page.goto(base+entryPath+'?technology=all',{waitUntil:'domcontentloaded'});await page.waitForFunction(()=>Number(document.querySelector('#tbody')?.dataset.total)>0);
 await page.locator('#clearFilters').click();await page.locator('#search').fill('2470');const repd=page.locator('#tbody .pn-journey-link').first();await repd.waitFor();result.repd=await inspect(repd);assert.equal(new URL(result.repd.href).searchParams.get('origin_id'),'repd:2470');assert.ok(result.repd.reachable&&result.repd.width>=62&&result.repd.height>=44);await page.screenshot({path:resolve(ou  … [line shortened here: 429 characters; full line on GitHub]
 await page.locator('.pipeline-tabs [data-view="grid"]').click();const sub=page.locator('#gridLayerHost tr[data-source-id] .pn-journey-link').first();await sub.waitFor({timeout:60000});result.substation=await inspect(sub);assert.equal(new URL(result.substation.href).searchParams.get('origin_type'),'substation');assert.ok(result.substation.reachable&&result.substation.width>=62&&result.substation.h  … [line shortened here: 484 characters; full line on GitHub]
 await page.locator('.pipeline-tabs [data-view="datacentre"]').click();await page.waitForFunction(()=>document.getElementById('datacentreHost')?.dataset.locationsState==='available',null,{timeout:60000});const dc=page.locator('#datacentreHost .ggdc-location-actions .pn-journey-link').first();await dc.waitFor();result.datacentre=await inspect(dc);assert.equal(new URL(result.datacentre.href).searchP  … [line shortened here: 610 characters; full line on GitHub]
 assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));assert.deepEqual(errors,[]);assert.deepEqual(result.httpErrors.filter(r=>r.url.startsWith(base)),[],'same-origin source assets must load');result.pass=true;
 }catch(e){result.pass=false;result.error=String(e);result.debug=await page.evaluate(()=>({api:!!window.pipelineJourneyEntry,total:document.querySelector('#tbody')?.dataset.total,query:document.querySelector('#search')?.value,maps:[...document.querySelectorAll('#tbody a.atlaslink')].slice(0,3).map(a=>a.outerHTML),journeyCount:document.querySelectorAll('.pn-journey-link').length}));throw e}
 finally{result.finished=new Date().toISOString();writeFileSync(resolve(output,'receipt.json'),JSON.stringify(report,null,2)+'\n');await context.close()}
}}finally{await browser.close();await new Promise(r=>server.close(r))}
console.log(JSON.stringify(report));

Model

A JavaScript module in the journey entry ui folder of GlobalGrid2050 that works with the Renewable Energy Planning Database (REPD) register and uses data from the GridAtlas repository.

transformglobalgrid2050 / automation/journey_entry_ui/20261118/model.mjs · lines 1–37 of 37 · version 2026-11-18

What it does
It calculates the REPD register. Defines checkedOrigin, checkedNewsContextBase, buildJourneyUrl, mapOrigin.
Why it exists in the grid workflow
Domain terms in the code: the REPD register.
Downstream impact
Used directly by 3 files: Map Entry (globalgrid2050); Model Test (globalgrid2050); View (globalgrid2050). Reached from 6 other entry points, including GlobalGrid2050 — UK Renewables Pipeline Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/); GlobalGrid2050 Pipeline Legal Evidence Workflow (globalgrid2050); GlobalGrid2050 V934 Preview Acceptance Workflow (globalgrid2050).
What it achieves
It builds journey URL (`buildJourneyUrl`) and maps origin (`mapOrigin`). Defines `checkedOrigin`, `checkedNewsContextBase`, `buildJourneyUrl` and 1 more.
Why it matters
Imported by Map Entry and View. Checked by Model Test.
Application
globalgrid2050 · automation/journey_entry_ui/20261118 · JavaScript module
Uses
GridAtlas — Atlas Page (estate URL)
Used by
imported by Map Entry (import), imported by Model Test (import), imported by View (import)
Produces
checkedOrigin, checkedNewsContextBase, buildJourneyUrl, mapOrigin
Defines here
checkedOrigin, checkedNewsContextBase, buildJourneyUrl, mapOrigin
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/journey_entry_ui/20261118/model.mjs:1-37 · blob 114498019804450c1c5bf3a9bf485e6cc05e49f0 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: production_core
const receiver='https://ventusltd.github.io/gridatlas/atlas/';
const kinds=new Set(['repd','datacentre','substation']);
export function checkedOrigin(value){
  if(!value||!kinds.has(value.origin_type)||typeof value.origin_id!=='string'||!value.origin_id.trim()||value.origin_id.length>160||/[\s\x00-\x1f\x7f]/.test(value.origin_id))return null;
  if(value.origin_type==='repd'&&!/^repd:[1-9]\d*$/.test(value.origin_id))return null;
  const {latitude,longitude}=value;
  if(typeof latitude!=='number'||typeof longitude!=='number'||!Number.isFinite(latitude)||!Number.isFinite(longitude)||Math.abs(latitude)>90||Math.abs(longitude)>180||(latitude===0&&longitude===0))return null;
  return Object.freeze({origin_type:value.origin_type,origin_id:value.origin_id,latitude,longitude,
    ...(typeof value.name==='string'&&value.name.trim()?{name:value.name.trim().slice(0,200)}:{}),
    ...(typeof value.technology==='string'?{technology:value.technology.slice(0,80)}:{})});
}
export function checkedNewsContextBase(value){
  if(typeof value!=='string')return null;
  let u;try{u=new URL(value)}catch{return null}
  if(u.origin!=='https://globalgrid2050.com'||u.username||u.password||u.port||u.search||u.hash||!/^\/uk_renewables_pipeline\/\d{12}\/(?:index\.html)?$/.test(u.pathname))return null;
  return u.href;
}
export function buildJourneyUrl(mapHref,origin,{radiusKm=10,newsContextUrl}={}){
  const checked=checkedOrigin(origin);if(!checked||!Number.isInteger(radiusKm)||radiusKm<1||radiusKm>50)return null;
  let url;try{url=new URL(mapHref)}catch{return null}
  if(url.origin+url.pathname!==receiver||url.username||url.password||url.port||url.hash)return null;
  for(const key of ['repd_ref','latitude','longitude','technology'])if(url.searchParams.getAll(key).length>1)return null;
  if(checked.origin_type==='repd'&&url.searchParams.get('repd_ref')!==checked.origin_id.slice(5))return null;
  if(!url.searchParams.get('latitude')?.trim()||!url.searchParams.get('longitude')?.trim()||Number(url.searchParams.get('latitude'))!==checked.latitude||Number(url.searchParams.get('longitude'))!==checked.longitude)return null;
  url.searchParams.delete('news_context_url');
  for(const [key,value]of Object.entries({journey:'vicinity',origin_type:checked.origin_type,origin_id:checked.origin_id,latitude:checked.latitude,longitude:checked.longitude,radius_km:radiusKm}))url.searchParams.set(key,String(value));
  if(checked.name&&!url.searchParams.has('project'))url.searchParams.set('project',checked.name);
  if(checked.name&&!url.searchParams.has('name'))url.searchParams.set('name',checked.name);
  if(newsContextUrl!==undefined){const base=checkedNewsContextBase(newsContextUrl);if(!base)return null;url.searchParams.set('news_context_url',base)}
  return url.href;
}
export function mapOrigin(mapHref,{origin_type,origin_id,name}={}){
  let url;try{url=new URL(mapHref)}catch{return null}
  const latitude=url.searchParams.get('latitude'),longitude=url.searchParams.get('longitude');
  if(latitude===null||longitude===null||!latitude.trim()||!longitude.trim())return null;
  return checkedOrigin({origin_type,origin_id,name,latitude:Number(latitude),longitude:Number(longitude),technology:url.searchParams.get('technology')||undefined});
}

Model Test

A test in the journey entry ui folder of GlobalGrid2050 that checks Model and GridAtlas — Atlas Page using data from the GridAtlas repository.

testglobalgrid2050 / automation/journey_entry_ui/20261118/model.test.mjs · lines 1–36 of 36 · version 2026-11-18 · Entry point

What it does
It tests the REPD register and substations. Uses libraries node:test, node:assert/strict.
Why it exists in the grid workflow
Domain terms in the code: the REPD register, substations.
Downstream impact
Used directly by 1 file: GlobalGrid2050 V934 Preview Acceptance Workflow (globalgrid2050).
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
Run by GlobalGrid2050 V934 Preview Acceptance Workflow.
Application
globalgrid2050 · automation/journey_entry_ui/20261118 · test
Uses
Model (import), GridAtlas — Atlas Page (estate URL), node:test, node:assert/strict
Used by
run by GlobalGrid2050 V934 Preview Acceptance Workflow (workflow run)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/journey_entry_ui/20261118/model.test.mjs:1-36 · blob b3b763bacda805e15b8ac9d11faf18013a364ad8 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: unknown · effects: none found · domain stage: unknown · users: none · canonical: production_core
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {buildJourneyUrl,checkedOrigin,mapOrigin,checkedNewsContextBase} from './model.mjs';
const href='https://ventusltd.github.io/gridatlas/atlas/?repd_ref=2470&technology=wind_offshore&latitude=52.1374391&longitude=2.1708996&zoom=12';
const origin={origin_type:'repd',origin_id:'repd:2470',latitude:52.1374391,longitude:2.1708996,name:'East Anglia 3'};
test('REPD journey preserves legacy receiver identity, geometry and technology',()=>{
 const url=new URL(buildJourneyUrl(href,origin));
 for(const [key,value]of new URL(href).searchParams)assert.equal(url.searchParams.get(key),value);
 assert.equal(url.searchParams.get('journey'),'vicinity');assert.equal(url.searchParams.get('origin_id'),'repd:2470');assert.equal(url.searchParams.get('radius_km'),'10');
 assert.equal(url.searchParams.get('name'),'East Anglia 3');
});
test('data centre and substation IDs remain opaque source identities',()=>{
 for(const [kind,id]of [['datacentre','DC-WD-Q100'],['substation','grid_substations:0']]){
 const h='https://ventusltd.github.io/gridatlas/atlas/?latitude=51&longitude=-1&project=Source';
 const o=mapOrigin(h,{origin_type:kind,origin_id:id});assert.equal(new URL(buildJourneyUrl(h,o,{radiusKm:50})).searchParams.get('origin_id'),id);
 }
});
test('missing, nonnumeric, substituted identity/point and out-of-range radius refuse',()=>{
 for(const o of [null,{...origin,latitude:null},{...origin,longitude:Infinity},{...origin,latitude:91},{...origin,latitude:0,longitude:0},{...origin,origin_id:'repd:999'},{...origin,origin_type:'interconnector'},{...origin,origin_id:'repd:2470\n'}])assert.equal(buildJourneyUrl(href,o),null);
 for(const radiusKm of [0,51,10.5,NaN,'10'])assert.equal(buildJourneyUrl(href,origin,{radiusKm}),null);
 assert.equal(buildJourneyUrl(href,{...origin,latitude:52}),null);
 assert.equal(mapOrigin('https://ventusltd.github.io/gridatlas/atlas/?repd_ref=2470',{origin_type:'repd',origin_id:'repd:2470'}),null);
});
test('unsafe receivers and duplicate legacy parameters cannot become journey links',()=>{
 for(const h of ['javascript:alert(1)',href.replace('ventusltd.github.io','example.com'),href.replace('https:','http:'),href+'#other',href+'&repd_ref=999',href+'&latitude=52'])assert.equal(buildJourneyUrl(h,origin),null);
 assert.equal(checkedOrigin({...origin,origin_id:'repd:2470 invalid'}),null);
});
test('optional news context is an immutable canonical base without redirects or incoming query',()=>{
 const base='https://globalgrid2050.com/uk_renewables_pipeline/202611172355/';
 assert.equal(new URL(buildJourneyUrl(href,origin)).searchParams.has('news_context_url'),false);
 assert.equal(new URL(buildJourneyUrl(href+'&news_context_url=https://example.com/',origin)).searchParams.has('news_context_url'),false);
 assert.equal(new URL(buildJourneyUrl(href,origin,{newsContextUrl:base})).searchParams.get('news_context_url'),base);
 for(const value of [base+'?q=x',base+'#x',base.replace('globalgrid2050.com','example.com'),base.replace('https:','http:'),base.replace('globalgrid2050.com','user@globalgrid2050.com'),base.replace('globalgrid2050.com','globalgrid2050.com:444'),base.replace('202611172355','current')]){
  assert.equal(checkedNewsContextBase(value),null);assert.equal(buildJourneyUrl(href,origin,{newsContextUrl:value}),null);
 }
});

Verify Closure

A JavaScript module in the journey entry ui folder of GlobalGrid2050 that reads journey entry, using SHA-256.

ingestglobalgrid2050 / automation/journey_entry_ui/20261118/verify-closure.mjs · lines 1–18 of 18 · version 2026-11-18 · Not reached from any entry point (candidate for review)

What it does
It loads journey entry. Uses libraries node:fs, node:path, node:crypto, node:assert/strict. Side effects: reads or writes files.
Inputs & outputs
In: JSON file journey-entry.v943.json; command-line arguments.
Downstream impact
Used directly by 1 file: Verify Closure (globalgrid2050).
What it achieves
Its name says it verifies closure.
Why it matters
Imported by a file of the same name.
Application
globalgrid2050 · automation/journey_entry_ui/20261118 · JavaScript module
Uses
node:fs, node:path, node:crypto, node:assert/strict
Used by
imported by Verify Closure (import)
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/journey_entry_ui/20261118/verify-closure.mjs:1-18 · blob 494797216a3eec7e147c12389109b533831ab13e · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: unknown · users: none · canonical: unreached_review
import {readFileSync} from 'node:fs';
import {resolve,relative} from 'node:path';
import {createHash} from 'node:crypto';
import assert from 'node:assert/strict';
const release=resolve(process.argv[2]),root=resolve(release,'../..');
const contract=JSON.parse(readFileSync(resolve(release,'contracts/journey-entry.v943.json')));
assert.equal(contract.schema,'pipeline.journey-entry.v1');
for(const [path,hash] of Object.entries(contract.files)){
 const target=resolve(root,path);assert(!relative(root,target).startsWith('..'));
 assert.equal(createHash('sha256').update(readFileSync(target)).digest('hex'),hash,path);
}
const html=readFileSync(resolve(release,'index.html'),'utf8');
for(const name of ['styles.css','view.mjs']){
 const path='automation/journey_entry_ui/20261118/'+name;
 const sri='sha256-'+Buffer.from(contract.files[path],'hex').toString('base64');
 assert(html.includes('../../'+path+'" integrity="'+sri+'"'),name+' SRI');
}
console.log('V9.43 shared Journey closure: PASS');

View Browser

A JavaScript module in the journey entry ui folder of GlobalGrid2050 that reads the Renewable Energy Planning Database (REPD) register and substations from the GridAtlas repository.

interactionglobalgrid2050 / automation/journey_entry_ui/20261118/view.browser.mjs · lines 1–39 of 39 · version 2026-11-18 · Entry point

What it does
It loads the REPD register and substations. Uses libraries node:assert/strict, node:http, node:fs, node:path, node:module. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain terms in the code: the REPD register, substations.
Inputs & outputs
In: data source: gridatlas data; form fields (user input).
Downstream impact
Used directly by 1 file: GlobalGrid2050 V934 Preview Acceptance Workflow (globalgrid2050).
What it achieves
It responds to pipeline events.
Why it matters
Run by GlobalGrid2050 V934 Preview Acceptance Workflow.
Application
globalgrid2050 · automation/journey_entry_ui/20261118 · JavaScript module
Uses
GridAtlas — Atlas Page (estate URL), node:assert/strict, node:http, node:fs, node:path, node:module, node:url
Used by
run by GlobalGrid2050 V934 Preview Acceptance Workflow (workflow run)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/journey_entry_ui/20261118/view.browser.mjs:1-39 · blob 1ed3d631370376e286b0f094edb071f7ed9484ad · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: unknown · users: none · canonical: production_core
import assert from 'node:assert/strict';
import {createServer} from 'node:http';
import {readFileSync} from 'node:fs';
import {resolve,dirname} from 'node:path';
import {createRequire} from 'node:module';
import {fileURLToPath} from 'node:url';
const root=resolve(dirname(fileURLToPath(import.meta.url)),'../..');
const {chromium}=createRequire(resolve(process.env.PLAYWRIGHT_MODULE_ROOT||'D:/githubfiles/.qa-tools/node','package.json'))('playwright');
const maps={repd:'https://ventusltd.github.io/gridatlas/atlas/?repd_ref=2470&technology=wind_offshore&latitude=52&longitude=2&zoom=12',sub:'https://ventusltd.github.io/gridatlas/atlas/?technology=substation&latitude=51&longitude=-1&project=Sub',dc:'https://ventusltd.github.io/gridatlas/atlas/?technology=datacentre&latitude=52&longitude=-1&project=DC'};
const fixture=`<!doctype html><meta name="viewport" content="width=device-width,initial-scale=1"><style>a{display:inline-block;min-height:44px;min-width:44px}.project-actions{width:124px}</style><link rel="stylesheet" href="/styles.css"><a id="mapAtlasNav" href="https://ventusltd.github.io/gridatlas/atlas/">MAP ATLAS</a><div id="tech"><button aria-pressed="true" data-technology="all">All</button><  … [line shortened here: 1,432 characters; full line on GitHub]
const server=createServer((req,res)=>{const name=new URL(req.url,'http://local').pathname.slice(1);if(['model.mjs','view.mjs','navigation.mjs','styles.css'].includes(name)){res.setHeader('content-type',name.endsWith('.css')?'text/css':'text/javascript');res.end(readFileSync(name==='navigation.mjs'?resolve(root,'mobile_map_ui/20261118-v942/navigation.mjs'):new URL('./'+name,import.meta.url)))}else{  … [line shortened here: 462 characters; full line on GitHub]
await new Promise(r=>server.listen(0,'127.0.0.1',r));const browser=await chromium.launch();
try{for(const mobile of [true,false]){
 const context=await browser.newContext({viewport:{width:mobile?393:1440,height:852},isMobile:mobile,hasTouch:mobile});const page=await context.newPage(),errors=[];page.on('pageerror',e=>errors.push(e.message));
 await page.goto('http://127.0.0.1:'+server.address().port);await page.waitForFunction(()=>document.querySelectorAll('.pn-journey-link').length===4);
 const entries=await page.locator('.pn-journey-link').evaluateAll(links=>links.map(a=>({text:a.textContent,url:a.href,target:a.target})));
 assert.equal(entries.filter(a=>new URL(a.url).searchParams.get('origin_type')==='repd').length,1);assert.equal(entries.filter(a=>new URL(a.url).searchParams.get('origin_type')==='substation').length,1);assert.equal(entries.filter(a=>new URL(a.url).searchParams.get('origin_type')==='datacentre').length,1);
 if(mobile){const boxes=await page.locator('#tbody .project-actions').evaluate(el=>{const [map,journey]=[el.querySelector('a:not(.pn-journey-link)'),el.querySelector('.pn-journey-link')].map(a=>a.getBoundingClientRect());return{map:{x:map.x,y:map.y,w:map.width,h:map.height},journey:{x:journey.x,y:journey.y,w:journey.width,h:journey.height}}});assert.ok(Math.abs(boxes.map.y-boxes.journey.y)<1&&boxe  … [line shortened here: 502 characters; full line on GitHub]
 assert.equal(await page.locator('.pn-journey-unavailable').count(),1);assert.equal(await page.locator('#tbody a:not(.pn-journey-link)').getAttribute('href'),maps.repd);
 await page.locator('#tbody .pn-journey-link').focus();assert.equal(await page.locator('#tbody .pn-journey-link').evaluate(a=>a===document.activeElement),true);
 if(!mobile){
   await page.evaluate(()=>{window.originEvents=[];window.addEventListener('pipeline-journey-origin',e=>window.originEvents.push(e.detail))});
   const opened=context.waitForEvent('page');await page.locator('#tbody .pn-journey-link').click();await(await opened).close();
   assert.equal(await page.evaluate(()=>window.originEvents.length),1);
 }
 await page.evaluate(()=>{const row=document.querySelector('#tbody tr');row.replaceWith(row.cloneNode(true))});await page.waitForTimeout(100);assert.equal(await page.locator('#tbody .pn-journey-link').count(),1);assert.deepEqual(errors,[]);
 if(!mobile){
   const opened=context.waitForEvent('page');await page.locator('#tbody .pn-journey-link').click();await(await opened).close();
   assert.equal(await page.evaluate(()=>window.originEvents.length),2,'cloned Journey action must still emit its checked origin');
 }
 assert.ok(entries.every(a=>!new URL(a.url).searchParams.has('news_context_url')),'entry release does not predeclare contextual news');
 const contextBase='https://globalgrid2050.com/uk_renewables_pipeline/202611172355/';
 await page.evaluate(base=>window.pipelineJourneyEntry.setNewsContextUrl(base),contextBase);
 const linked=await page.locator('.pn-journey-link').evaluateAll(as=>as.map(a=>a.href));
 assert.ok(linked.every(h=>new URL(h).searchParams.get('news_context_url')===contextBase),'explicit later opt-in reaches assets and manual Layers entry');
 const rejected=await page.evaluate(()=>{try{window.pipelineJourneyEntry.setNewsContextUrl('https://example.com/');return false}catch{return true}});assert.equal(rejected,true);
 assert.deepEqual(await page.locator('.pn-journey-link').evaluateAll(as=>as.map(a=>a.href)),linked);
 console.log(JSON.stringify({mobile,entries,unavailable:1,sourceHrefUnchanged:true,rerenderSingular:true,pass:true}));await context.close();
}}finally{await browser.close();await new Promise(r=>server.close(r))}

View

A JavaScript module in the journey entry ui folder of GlobalGrid2050 covering the Renewable Energy Planning Database (REPD) register and uses data from the GridAtlas repository.

interactionglobalgrid2050 / automation/journey_entry_ui/20261118/view.mjs · lines 1–97 of 97 · version 2026-11-18 · Not reached from any entry point (candidate for review) · pattern rememberCategory (shared by 2 files)

What it does
It draws the REPD register. Defines action, refresh, rememberCategory, restore, dcRestore. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain terms in the code: the REPD register.
What it achieves
It is built from the remember category helper (`rememberCategory`), the restore step (`restore`) and the dc restore helper (`dcRestore`). Defines `action`, `refresh`, `rememberCategory` and 2 more. It responds to click and pipeline events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · automation/journey_entry_ui/20261118 · JavaScript module
Uses
Model (import), GridAtlas — Atlas Page (estate URL)
Used by
none found
Produces
action, refresh, rememberCategory, restore, dcRestore
Defines here
action, refresh, rememberCategory, restore, dcRestore
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/journey_entry_ui/20261118/view.mjs:1-97 · blob 26d45a958d031791d9eddc4b8b55e92339a88cac · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: duplicate_candidate
import {buildJourneyUrl,mapOrigin,checkedNewsContextBase} from './model.mjs';
const document=globalThis.document;
const canonical='https://ventusltd.github.io/gridatlas/atlas/';
const stateKey='pipelineJourneyReturn';
const origins=new WeakMap();
let newsContextUrl;
function action(map,identity,parent){
  const existing=parent.querySelector(':scope > .pn-journey-action');
  const origin=map?mapOrigin(map.href,identity):null;
  const href=origin?buildJourneyUrl(map.href,origin,{newsContextUrl}):null;
  const signature=JSON.stringify([identity.origin_type,identity.origin_id,href]);
  if(existing?.dataset.signature===signature){if(href)origins.set(existing,origin);return}
  existing?.remove();
  const element=document.createElement(href?'a':'span');element.className='pn-journey-action';element.dataset.signature=signature;
  if(href){
    element.classList.add('action-link','atlaslink','pn-journey-link');element.href=href;element.target='_blank';element.rel='noopener noreferrer';element.textContent='JOURNEY';
    element.title='Explore nearby assets and documented network connectivity; not a connection assessment';origins.set(element,origin);
  }else{
    element.classList.add('pn-journey-unavailable');element.textContent='JOURNEY: location unavailable';
  }
  if(map?.parentElement===parent)map.after(element);else parent.append(element);
}
function refresh(){
 for(const map of document.querySelectorAll('#tbody a.atlaslink:not(.pn-journey-link)')){
   const url=new URL(map.href),ref=url.searchParams.get('repd_ref');if(!/^[1-9]\d*$/.test(ref||''))continue;
   const row=map.closest('tr'),name=row?.querySelector('.site')?.firstChild?.textContent?.trim();
   action(map,{origin_type:'repd',origin_id:'repd:'+ref,name},map.parentElement);
 }
 for(const row of document.querySelectorAll('#gridLayerHost tr[data-source-id]')){
   const map=[...row.querySelectorAll('a:not(.pn-journey-link)')].find(a=>a.href.startsWith(canonical));
   if(!map)continue;
   action(map,{origin_type:'substation',origin_id:row.dataset.sourceId,name:row.querySelector('strong')?.textContent},map.parentElement);
 }
 for(const row of document.querySelectorAll('#datacentreHost .ggdc-table tbody tr')){
   const id=row.querySelector('.ggdc-id')?.textContent?.trim();if(!/^DC-WD-Q[1-9]\d*$/.test(id||''))continue;
   const actions=row.querySelector('.ggdc-location-actions');
   const map=actions&&[...actions.querySelectorAll('a:not(.pn-journey-link)')].find(a=>a.href.startsWith(canonical));
   const parent=actions||row.lastElementChild;if(!parent)continue;
   // A late source-backed location replaces the unavailable placeholder.
   if(actions)row.querySelector('td > .pn-journey-unavailable')?.remove();
   action(map,{origin_type:'datacentre',origin_id:id,name:row.querySelector('.ggdc-identity')?.firstChild?.textContent},parent);
 }
 const map=document.getElementById('mapAtlasNav');
 if(map&&!document.getElementById('journeyAtlasNav')){
   const a=document.createElement('a');a.id='journeyAtlasNav';a.className='atlaslink pn-journey-link';a.textContent='GRID JOURNEYS';a.href=canonical+'?journey=vicinity';a.target='_blank';a.rel='noopener noreferrer';map.after(a);
 }
 const nav=document.getElementById('journeyAtlasNav');if(nav){
   const url=new URL(canonical);url.searchParams.set('journey','vicinity');
   if(newsContextUrl)url.searchParams.set('news_context_url',newsContextUrl);
   nav.href=url.href;
 }
}
let queued=false;
new MutationObserver(()=>{if(!queued){queued=true;queueMicrotask(()=>{queued=false;refresh()})}}).observe(document.body,{childList:true,subtree:true});
refresh();
// Only a later accepted news-context component opts into this metadata. The
// entry release never points to an unpublished or arbitrary return destination.
window.pipelineJourneyEntry=Object.freeze({schema:'pipeline.journey-entry.v1',setNewsContextUrl(value){
  const base=checkedNewsContextBase(value);if(!base)throw Error('Invalid immutable news context base');
  newsContextUrl=base;refresh();
}});
window.dispatchEvent(new Event('pipeline-journey-ready'));
function rememberCategory(){
 const category=document.querySelector('.pipeline-tabs [aria-selected="true"]')?.dataset.view;
 const dc=document.getElementById('datacentreHost');
 const state={category,x:scrollX,y:scrollY,
   dcQuery:dc?.querySelector('input[type="search"]')?.value,
   dcKind:dc?.querySelector('[data-kind][aria-pressed="true"]')?.dataset.kind,
   dcCountry:dc?.querySelector('select[aria-label="Country"]')?.value};
 try{history.replaceState({...history.state,[stateKey]:state},'')}catch{/* Native link remains usable. */}
}
document.addEventListener('click',event=>{
 const a=event.target.closest?.('.pn-journey-link');if(!a)return;
 // V9.42's existing atlaslink handler owns native target and filter recovery.
 rememberCategory();
 const origin=origins.get(a);if(origin)window.dispatchEvent(new CustomEvent('pipeline-journey-origin',{detail:origin}));
},true);
// Restore the existing category controls only after the original app finishes
// its default-category initialization. BFCache keeps its live nodes unchanged.
const saved=history.state?.[stateKey];
if(saved&&['solar','bess','grid','datacentre','offtakers','prices'].includes(saved.category)){
 let restored=false;
 const restore=()=>{if(restored)return;restored=true;queueMicrotask(()=>{
   document.querySelector('.pipeline-tabs [data-view="'+saved.category+'"]')?.click();
   if(saved.category!=='datacentre'){scrollTo(saved.x,saved.y);return}
   const dcRestore=()=>{
     const dc=document.getElementById('datacentreHost'),input=dc?.querySelector('input[type="search"]');if(!input)return;
     if(['uk','global'].includes(saved.dcKind))dc.querySelector('[data-kind="'+saved.dcKind+'"]')?.click();
     input.value=saved.dcQuery||'';input.dispatchEvent(new Event('input',{bubbles:true}));
     const country=dc.querySelector('select[aria-label="Country"]');if(country&&[...country.options].some(o=>o.value===saved.dcCountry)){country.value=saved.dcCountry;country.dispatchEvent(new Event('change',{bubbles:true}))}
     scrollTo(saved.x,saved.y);
   };
   window.addEventListener('pipeline-datacentre-ready',dcRestore,{once:true});dcRestore();
 })};
 window.addEventListener('pipeline-projects-rendered',restore,{once:true});
 if(document.getElementById('tbody')?.dataset.complete==='true')restore();
}

Browser

A JavaScript module in the journey return ui folder of GlobalGrid2050 covering battery storage (BESS) and solar, and uses data from the GridAtlas repository.

renderglobalgrid2050 / automation/journey_return_ui/20261118/browser.mjs · lines 1–38 of 38 · version 2026-11-18 · Not reached from any entry point (candidate for review)

What it does
It draws battery storage (BESS) and solar. Defines sourceState, value. Uses libraries node:assert/strict, node:http, node:fs, node:path, node:url. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain terms in the code: battery storage (BESS), solar.
Inputs & outputs
In: data source: gridatlas data. Out: JSON file receipt.json.
What it achieves
It is built from the source state helper (`sourceState`) and the value step (`value`). Full local candidate source -> real Atlas -> cold Back.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · automation/journey_return_ui/20261118 · JavaScript module
Uses
GridAtlas — Atlas Page (estate URL), node:assert/strict, node:http, node:fs, node:path, node:url
Used by
none found
Produces
sourceState, value
Defines here
sourceState, value
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/journey_return_ui/20261118/browser.mjs:1-38 · blob 4ef49b90768738eb7f66a69f00f88bca76acbda1 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: unknown · users: none · canonical: unreached_review
// Full local candidate source -> real Atlas -> cold Back. No intercepted runtime/data.
import assert from 'node:assert/strict';
import {createServer} from 'node:http';
import {readFileSync,writeFileSync,mkdirSync} from 'node:fs';
import {resolve,dirname,extname,sep} from 'node:path';
import {fileURLToPath,pathToFileURL} from 'node:url';
const root=resolve(dirname(fileURLToPath(import.meta.url)),'../../..'),edition=process.env.PN_JOURNEY_EDITION||'202611180451';
const out=process.env.JOURNEY_RETURN_OUT||resolve(root,'work/journey-return');mkdirSync(out,{recursive:true});
const {chromium}=await import(pathToFileURL(process.env.PLAYWRIGHT_MODULE||'D:/githubfiles/.qa-tools/node/node_modules/playwright/index.mjs').href);
const server=createServer((req,res)=>{try{const u=new URL(req.url,'http://local');let p=resolve(root,'.'+decodeURIComponent(u.pathname));assert.ok(p.startsWith(root+sep));if(u.pathname.endsWith('/'))p=resolve(p,'index.html');res.setHeader('Content-Type',({'.html':'text/html','.js':'text/javascript','.mjs':'text/javascript','.json':'application/json','.css':'text/css'})[extname(p)]||'application/oc  … [line shortened here: 472 characters; full line on GitHub]
await new Promise(r=>server.listen(0,'127.0.0.1',r));const base='http://127.0.0.1:'+server.address().port,entry='/uk_renewables_pipeline/'+edition+'/';
const report={scope:'LOCAL_FULL_CANDIDATE_COLD_BACK_REGRESSION_NOT_PUBLIC_ACCEPTANCE',edition,cases:[]};
function sourceState(expected){
 const value=id=>document.getElementById(id)?.value??null;
 const category=document.querySelector('.pipeline-tabs [aria-selected="true"]')?.dataset.view??null;
 const dc=document.getElementById('datacentreHost');
 const state={category,technology:document.querySelector('#tech [aria-pressed="true"]')?.dataset.technology??null,status:document.querySelector('#status [aria-pressed="true"]')?.dataset.officialStatus??null,county:value('county'),query:value('search'),sort:value('sortProjects'),years:Object.fromEntries(['submittedYear','updatedYear','operationalYear'].map(id=>[id,document.querySelector('[data-year  … [line shortened here: 682 characters; full line on GitHub]
 return expected?JSON.stringify(state)===JSON.stringify(expected):state;
}
const browser=await chromium.launch({headless:true,args:['--use-gl=angle','--use-angle=swiftshader','--enable-webgl','--ignore-gpu-blocklist']});
try{for(const category of ['solar','bess'])for(const technology of ['all','wind_offshore']){
 const context=await browser.newContext({viewport:{width:393,height:852},isMobile:true,hasTouch:true}),page=await context.newPage(),errors=[];page.on('pageerror',e=>errors.push(e.message));
 const row={category,technology,errors,phase:'source-load'};report.cases.push(row);
 try{
 await page.goto(base+entry+'?technology=all',{waitUntil:'domcontentloaded'});await page.waitForFunction(()=>document.querySelector('#tbody')?.dataset.complete==='true');
 await page.locator('.pipeline-tabs [data-view="'+category+'"]').tap();await page.locator('#tech [data-technology="'+technology+'"]').tap();
 const ref=technology==='all'?'12588':'2470';await page.locator('#search').fill(ref);if(technology==='all')await page.locator('#county').selectOption('Oxfordshire');
 const sort=await page.locator('#sortProjects').evaluate(s=>[...s.options].find(o=>o.value!==s.value)?.value);assert.ok(sort,'real nondefault sort option required');await page.locator('#sortProjects').selectOption(sort);
 const target=page.locator('#tbody .pn-journey-link[href*="repd_ref='+ref+'"]').first();await target.waitFor();row.before=await page.evaluate(sourceState);assert.equal(row.before.category,category);assert.equal(row.before.technology,technology);assert.equal(row.before.query,ref);row.beforeTime=await page.evaluate(()=>performance.timeOrigin);
 row.phase='native-arrival';await target.tap();await page.waitForURL('https://ventusltd.github.io/gridatlas/atlas/**');await page.waitForFunction(id=>window.__GRIDATLAS_MODULES__?.gridVicinity?.snapshot().origin?.id===id,'repd:'+ref,{timeout:100000});assert.equal(await page.evaluate(()=>document.documentElement.dataset.gridatlasGeneration),'202611180026');
 await page.evaluate(async()=>{if(document.fullscreenElement)await document.exitFullscreen()});row.phase='cold-back';await page.goBack({waitUntil:'domcontentloaded'});await page.waitForURL(base+entry+'**');row.first=await page.evaluate(sourceState);
 await page.waitForFunction(sourceState,row.before,{timeout:60000});row.after=await page.evaluate(sourceState);row.afterTime=await page.evaluate(()=>performance.timeOrigin);assert.notEqual(row.beforeTime,row.afterTime,'a complete cold-document replay is required');assert.deepEqual(row.after,row.before,'all actual controls and category must match, no fields omitted');
 row.phase='trusted-controls';await page.locator('.pipeline-tabs [data-view="bess"]').tap();assert.equal(await page.evaluate(()=>document.querySelector('#tech [aria-pressed="true"]').dataset.technology),'bess');await page.locator('.pipeline-tabs [data-view="bess"]').press('Home');assert.equal(await page.evaluate(()=>document.querySelector('#tech [aria-pressed="true"]').dataset.technology),'solar')  … [line shortened here: 401 characters; full line on GitHub]
 assert.deepEqual(errors,[]);row.pass=true;row.phase='complete';
 }catch(error){row.pass=false;row.error=String(error);row.last=await page.evaluate(sourceState);row.readiness=await page.evaluate(()=>({url:location.href,ready:document.readyState,complete:document.querySelector('#tbody')?.dataset.complete,total:document.querySelector('#tbody')?.dataset.total}));await page.screenshot({path:resolve(out,category+'-'+technology+'-failure.png')}).catch(()=>{});throw e  … [line shortened here: 405 characters; full line on GitHub]
 finally{writeFileSync(resolve(out,'receipt.json'),JSON.stringify(report,null,2)+'\n');await context.close()}
}}finally{await browser.close();await new Promise(r=>server.close(r));}
console.log(JSON.stringify(report));

Restore Test

A test in the journey return ui folder of GlobalGrid2050 covering solar and battery storage (BESS). It is built from the node class (`Node`) and the custom event class (`CustomEvent`).

testglobalgrid2050 / automation/journey_return_ui/20261118/restore.test.mjs · lines 1–56 of 56 · version 2026-11-18 · Entry point · pattern fixture (shared by 30 files)

What it does
It tests solar and battery storage (BESS). Defines fixture, Node, CustomEvent. Uses libraries node:test, node:assert/strict, node:vm, node:fs, node:path. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain terms in the code: solar, battery storage (BESS).
Downstream impact
Used directly by 1 file: GlobalGrid2050 V934 Preview Acceptance Workflow (globalgrid2050).
What it achieves
Its name says it restores test. Defines `fixture`, `Node` and `CustomEvent`.
Why it matters
Run by GlobalGrid2050 V934 Preview Acceptance Workflow.
Application
globalgrid2050 · automation/journey_return_ui/20261118 · test
Uses
node:test, node:assert/strict, node:vm, node:fs, node:path
Used by
run by GlobalGrid2050 V934 Preview Acceptance Workflow (workflow run)
Produces
fixture, Node, CustomEvent
Defines here
fixture, Node, CustomEvent
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/journey_return_ui/20261118/restore.test.mjs:1-56 · blob 602c244d527c5980762c1fa2b93ff37d1dbacc94 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: unknown · users: none · canonical: production_core
import test from 'node:test';
import assert from 'node:assert/strict';
import vm from 'node:vm';
import {readFileSync} from 'node:fs';
import {resolve} from 'node:path';
const edition=process.env.PN_JOURNEY_EDITION||'202611180451';
const source=readFileSync(resolve('uk_renewables_pipeline',edition,'scripts/plugins/preview-v928.js'),'utf8');
// Deterministic DOM-event model of the actual complete plugin, not browser proof.
function fixture({saved,technology='all',query='12588'}={}){
 const state={technology,query,county:'Oxfordshire',sort:'capacity_asc',years:{submittedYear:'2023',updatedYear:'All',operationalYear:'All'}},calls=[];
 const tasks=[],nodes=new Map(),listeners=new Map();let active=null;
 class Node{
  constructor(id,view){this.id=id;this.dataset=view?{view}:{};this.attributes={};this.events=new Map();this.hidden=false;this.children=[];this.style={};if(view)this.attributes['aria-controls']=['solar','bess'].includes(view)?'repdPanel':view==='grid'?'gridPanel':view==='datacentre'?'datacentrePanel':view+'Panel';}
  addEventListener(type,fn){this.events.set(type,[...(this.events.get(type)||[]),fn]);}
  emit(type,event={}){for(const fn of this.events.get(type)||[])fn({target:this,isTrusted:false,preventDefault(){},...event});}
  click(){this.emit('click');}
  setAttribute(k,v){this.attributes[k]=String(v);}
  getAttribute(k){return this.attributes[k];}
  focus(){active=this;}
  append(...children){this.children.push(...children);}
  replaceChildren(...children){this.children=children;}
  querySelector(selector){return selector==='.ggdc-table'&&this.hasTable?{}:null;}
 }
 const views=['solar','bess','grid','datacentre','offtakers','prices'],tabs=views.map(view=>new Node(view+'Tab',view));
 for(const tab of tabs){nodes.set(tab.id,tab);tab.attributes['aria-selected']=String(tab.dataset.view==='solar');}
 for(const id of ['repdPanel','gridPanel','datacentrePanel','offtakersPanel','pricesPanel','tbody','contextDisclosure','contextHost','gridSourcesHost'])nodes.set(id,new Node(id));
 nodes.get('tbody').dataset.complete='false';
 const document={getElementById:id=>{if(!nodes.has(id))nodes.set(id,new Node(id));return nodes.get(id)},querySelectorAll:selector=>selector==='.pipeline-tabs [role="tab"]'?tabs:[],querySelector:selector=>selector.startsWith('#tech ')?{click(){const technology=selector.split('"')[1];state.technology=technology;calls.push({...state,years:{...state.years}});}}:null,createElement:tag=>new Node(tag),cr  … [line shortened here: 447 characters; full line on GitHub]
 const window={addEventListener(type,fn){listeners.set(type,[...(listeners.get(type)||[]),fn]);},dispatchEvent(event){for(const fn of listeners.get(event.type)||[])fn(event);},GGDataCentreUI:{mount:async host=>{host.hasTable=true;}}};
 class CustomEvent{constructor(type,{detail}={}){this.type=type;this.detail=detail;}}
 const history={state:saved?{pipelineJourneyReturn:{category:saved}}:null};
 const context=vm.createContext({document,window,history,location:{href:'https://globalgrid2050.com/example/?technology='+technology+'&q='+query,hostname:'globalgrid2050.com'},URL,CustomEvent,TextDecoder,queueMicrotask:fn=>tasks.push(fn),fetch:async()=>{throw Error('Offline source directory fixture');},console});
 vm.runInContext(source,context);
 return{state,calls,history,tab:view=>tabs.find(tab=>tab.dataset.view===view),category:()=>tabs.find(tab=>tab.attributes['aria-selected']==='true')?.dataset.view,focused:()=>active?.dataset.view,complete(){nodes.get('tbody').dataset.complete='true';window.dispatchEvent(new CustomEvent('pipeline-projects-rendered'));while(tasks.length)tasks.shift()();}};
}
for(const category of ['solar','bess'])for(const technology of ['all','wind_offshore']){
 test('cold '+category+' restores '+technology+' and nondefault query/filter state without re-query',()=>{
  const f=fixture({saved:category,technology,query:technology==='all'?'12588':'2470'}),before=structuredClone(f.state);f.complete();f.tab(category).click();
  assert.equal(f.category(),category);assert.deepEqual(f.state,before);assert.equal(f.calls.length,0,'category-only restore must not click the technology filter');
  f.tab(category).click();assert.equal(f.state.technology,category);assert.equal(f.calls.length,1,'the history marker must be consumed exactly once');
 });
}
test('trusted mouse and keyboard keep normal solar/BESS defaults after restore',()=>{
 const f=fixture({saved:'solar'});f.complete();f.tab('solar').click();f.tab('bess').emit('click',{isTrusted:true});assert.equal(f.state.technology,'bess');
 f.tab('bess').emit('keydown',{isTrusted:true,key:'Home'});assert.equal(f.state.technology,'solar');assert.equal(f.focused(),'solar');assert.equal(f.calls.length,2);
});
for(const selected of ['bess','grid','datacentre'])test('early trusted '+selected+' wins over late initialisation and saved restore',async()=>{
 const f=fixture({saved:'solar',technology:'solar'});f.tab(selected).emit('click',{isTrusted:true});const before=structuredClone(f.state);f.complete();f.tab('solar').click();
 assert.equal(f.category(),selected);assert.deepEqual(f.state,before);await Promise.resolve();
});
test('early trusted keyboard choice survives first project completion',()=>{
 const f=fixture({saved:'solar',technology:'solar'});f.tab('solar').emit('keydown',{isTrusted:true,key:'ArrowRight'});f.complete();f.tab('solar').click();assert.equal(f.category(),'bess');assert.equal(f.state.technology,'bess');
});
test('BFCache-like retained DOM does not reinitialise from later history state',()=>{
 const f=fixture({technology:'all'});f.complete();f.tab('bess').emit('click',{isTrusted:true});f.state.technology='wind_offshore';const before=structuredClone(f.state);f.history.state={pipelineJourneyReturn:{category:'bess'}};f.complete();assert.deepEqual(f.state,before);assert.equal(f.category(),'bess');
});

Verify Closure

A JavaScript module in the journey return ui folder of GlobalGrid2050 that reads journey return, using SHA-256.

ingestglobalgrid2050 / automation/journey_return_ui/20261118/verify-closure.mjs · lines 1–10 of 10 · version 2026-11-18 · Not reached from any entry point (candidate for review)

What it does
It loads journey return. Uses libraries node:fs, node:path, node:crypto, node:assert/strict. Side effects: reads or writes files.
Inputs & outputs
In: JSON file journey-return.v944.json; command-line arguments.
What it achieves
Its name says it verifies closure.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · automation/journey_return_ui/20261118 · JavaScript module
Uses
Verify Closure (import), node:fs, node:path, node:crypto, node:assert/strict
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/journey_return_ui/20261118/verify-closure.mjs:1-10 · blob 7ba104886135be46dfdb88b4c91cf9b84fee6de1 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: unknown · users: none · canonical: unreached_review
import '../../journey_entry_ui/20261118/verify-closure.mjs';
import {readFileSync} from 'node:fs';
import {resolve} from 'node:path';
import {createHash} from 'node:crypto';
import assert from 'node:assert/strict';
const release=resolve(process.argv[2]);
const pin=JSON.parse(readFileSync(resolve(release,'contracts/journey-return.v944.json')));
assert.equal(pin.schema,'pipeline.journey-return.v944');
assert.equal(createHash('sha256').update(readFileSync(resolve(release,'scripts/plugins/preview-v928.js'))).digest('hex'),pin.preview_sha256);
console.log('V9.44 own preview and immutable shared Journey closure: PASS');

Catalogue

A JavaScript module in the primary note ui folder of GlobalGrid2050 that works with part, pipeline headlines, solar and the Renewable Energy Planning Database (REPD) register, using SHA-256.

transformglobalgrid2050 / automation/primary_note_ui/b5eed3d2ae878c78e5153be06ef531c11fff2148/catalogue.mjs · lines 1–122 of 122 · pattern freeze (shared by 6 files)

What it does
It calculates part, pipeline headlines, solar and the REPD register. Defines freeze.
Why it exists in the grid workflow
Domain terms in the code: solar, the REPD register.
Inputs & outputs
In: JSON file part-001.json; JSON file pipeline_headlines.json.
Downstream impact
Used directly by 2 files: Model (globalgrid2050); Contracts Test (globalgrid2050). Reached from 4 other entry points, including GlobalGrid2050 V932 Preview Acceptance Workflow (globalgrid2050); GlobalGrid2050 V933 Preview Acceptance Workflow (globalgrid2050); Contracts Test (globalgrid2050).
What it achieves
It is built from the freeze step (`freeze`). Curated trust catalogue. A hostname or caller flag cannot add a source.
Why it matters
Imported by Model. Checked by Contracts Test.
Application
globalgrid2050 · automation/primary_note_ui/b5eed3d2ae878c78e5153be06ef531c11fff2148 · JavaScript module
Uses
none found
Used by
imported by Model (import), imported by Contracts Test (import)
Produces
CATALOGUE
Defines here
freeze
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/primary_note_ui/b5eed3d2ae878c78e5153be06ef531c11fff2148/catalogue.mjs:1-122 · blob 541d5169f36cf3b3d8447d418e792ef08eb51d5d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: production_core
/* Curated trust catalogue. A hostname or caller flag cannot add a source. */
function freeze(value){if(value&&typeof value==='object'){for(const child of Object.values(value))freeze(child);Object.freeze(value);}return value;}
export const CATALOGUE=freeze({
  "schema": "globalgrid2050.primary-note-source-catalogue.v1",
  "review": {
    "status": "NARROW_GOVERNMENT_FACTS_REVIEWED",
    "independent_review_at": "2026-11-17T02:41:05.452826+00:00",
    "curated_at": "2026-11-17T03:16:20Z",
    "method": "Two-session primary PDF, exact canonical identity and terms review; not a publisher-wide rights grant"
  },
  "source": {
    "id": "desnz-en010147-002440",
    "author": "Department for Energy Security and Net Zero",
    "authorship": "GOVERNMENT_DECISION_LETTER",
    "url": "https://nsip-documents.planninginspectorate.gov.uk/published-documents/EN010147-002440-Botley%20West%20Solar%20Farm%20-%20Secretary%20of%20State%20for%20Energy%20Security%20and%20Net%20Zero%20Decision%20Letter.pdf",
    "sha256": "335eff9eed9c8e32658fe70186d2f02f4bf82a92ffbed1eaa835ac7ced0f857e",
    "bytes": 1247918,
    "retrieved_at": "2026-11-17T02:08:14.252676+00:00",
    "headers": {
      "Content-Type": "application/pdf",
      "Content-Length": "1247918",
      "Last-Modified": "Tue, 10 Nov 2026 16:20:36 GMT",
      "ETag": "0x8DF3F468DAAB111"
    },
    "document_date": "2026-11-10",
    "document_stated_publication_date": "2026-11-10",
    "allowed_claim": "DEVELOPMENT_CONSENT_REFUSED",
    "planning_reference": "EN010147",
    "locators": {
      "decision": "paragraph 3.9, page 5",
      "application_date": "paragraph 1.1, page 1",
      "original_proposal": "paragraph 1.9, page 2",
      "later_capacity_uncertainty": "paragraph 4.14, page 8",
      "publication": "Annex A, page 114"
    },
    "project_url": "https://national-infrastructure-consenting.planninginspectorate.gov.uk/projects/EN010147",
    "project_url_scope": "Supplementary navigation only; not a newly reviewed project-page status"
  },
  "rights": {
    "status": "REVIEWED_NARROW_OGL_FACT_PARAPHRASE",
    "scope": "GOVERNMENT_AUTHORED_DECISION_FACTS_ONLY",
    "licence_url": "https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/",
    "attribution": "Contains public sector information licensed under the Open Government Licence v3.0.",
    "exclusions": [
      "Third-party and applicant documents, maps and photographs",
      "Personal information",
      "Standalone departmental logos and crests",
      "Official endorsement"
    ],
    "terms_receipts": [
      {
        "url": "https://national-infrastructure-consenting.planninginspectorate.gov.uk/terms-and-conditions",
        "bytes": 74533,
        "sha256": "6b64ce231a8a7bd91860fa4eb0a1d0109acf4174c0eb814c1090b48f3af95733",
        "retrieved_at": "2026-11-17T02:14:30.331250+00:00"
      },
      {
        "url": "https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/",
        "bytes": 10450,
        "sha256": "f5b2b9f2af63647cde889fa6c3508f5705925295b74912c68caa28dd37e64aa5",
        "retrieved_at": "2026-11-17T02:14:30.443798+00:00"
      }
    ],
    "review_limit": "Terms reviewed from supplied original HTML and exact receipt hashes; independent fresh web reader could not open those terms pages. Fresh primary PDF bytes were independently matched."
  },
  "canonical": {
    "edition": "202611170147",
    "expected_population": 7775,
    "partition": "data/v9.1/projects/part-001.json",
    "partition_sha256": "1dec5e14cb05d5d47a3543d66a8970a5dc6e74e3cd444c1471befba2fad0a2aa",
    "fields": {
      "repd_ref": "12588",
      "gg_project_id": "GG2050-REPD-12588",
      "planning_application_reference": "EN010147",
      "name": "Botley West, Botley - Botley West Solar Project",
      "operator": "Photovolt Development Partners & SolarFive",
      "county": "Oxfordshire",
      "country": "England",
      "technology": "solar",
      "capacity_known": true,
      "capacity_mw": 840,
      "status": "Application Submitted",
      "repd_record_updated": "2024-12-16",
      "planning_application_submitted": "2024-11-15",
      "latitude": 51.8132088,
      "longitude": -1.3489728
    }
  },
  "news_metadata": {
    "source_url": "https://raw.githubusercontent.com/Ventusltd/globalgrid2050/c7343d45a6842ad05c88d5aa958e111df623c807/dist/pipeline_headlines.json",
    "sha256": "f19f17df1780f118b4d7823a88dddc03264626888418a50369df722507ab6c26",
    "bytes": 39620,
    "read_at": "2026-11-17T03:14:42.759038+00:00",
    "feed_generated_at": "2026-11-17T00:27:34Z",
    "article_url": "https://www.solarpowerportal.co.uk/solar-planning/uk-government-refuses-840mw-botley-west-solar-farm-in-first-ever-solar-nsip-no",
    "publisher": "Solar Power Portal",
    "published_at": "2026-11-11T12:29:34Z",
    "first_seen": "2026-11-14T10:47:43Z",
    "basis": "EXISTING_FEED_METADATA_ONLY",
    "article_body_reviewed": false,
    "publisher_content_rights": "NOT_ASSESSED"
  },
  "claim": {
    "type": "DEVELOPMENT_CONSENT_REFUSED",
    "decision_date": "2026-11-10",
    "planning_reference": "EN010147",
    "statement": "The government decision letter for EN010147 records refusal of development consent on 10 November 2026. The association with REPD12588 is provisional; the frozen REPD status remains Application Submitted.",
    "source_application_submitted": "2024-11-14",
    "capacity_context": {
      "original_application_repd_baseline_mw": 840,
      "basis": "ORIGINAL_APPLICATION_AND_FROZEN_REPD_BASELINE",
      "later_reduction_reported": true,
      "final_reduced_capacity_mw": null
    },
    "unknowns": {
      "judicial_review_status": null,
      "later_project_status": null,
      "current_installed_capacity_mw": null,
      "electrical_connection_status": null
    }
  }
});

Model

A JavaScript module in the primary note ui folder of GlobalGrid2050 that builds primary notes (`buildPrimaryNotes`), covering notes, using SHA-256.

transformglobalgrid2050 / automation/primary_note_ui/b5eed3d2ae878c78e5153be06ef531c11fff2148/model.mjs · lines 1–119 of 119 · pattern buildPrimaryNotes (shared by 2 files)

What it does
It calculates notes. Defines 14 functions or classes, including requireValid, freeze, jsonCopy, serial, keys.
Inputs & outputs
In: JSON file notes.json.
Downstream impact
Used directly by 3 files: Contracts Test (globalgrid2050); Contracts Test (globalgrid2050); Invariants (globalgrid2050). Reached from 2 other entry points, including GlobalGrid2050 V932 Preview Acceptance Workflow (globalgrid2050); GlobalGrid2050 V933 Preview Acceptance Workflow (globalgrid2050).
What it achieves
It builds primary notes (`buildPrimaryNotes`) and is built from the require valid helper (`requireValid`) and the freeze step (`freeze`). Offline curated primary notes. This validates one reviewed association, not a matcher.
Why it matters
Run by Invariants. Checked by 2 tests, including Contracts Test.
Application
globalgrid2050 · automation/primary_note_ui/b5eed3d2ae878c78e5153be06ef531c11fff2148 · JavaScript module
Uses
Catalogue (import), ./notes.json
Used by
imported by Contracts Test (import), run by Contracts Test (script call), run by Invariants (script call)
Produces
utcInstant, CURATED_NOTES, buildPrimaryNotes
Defines here
requireValid, freeze, jsonCopy, serial, keys, same, https, utcInstant, day, canonical, field, clocks, validate, buildPrimaryNotes
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/primary_note_ui/b5eed3d2ae878c78e5153be06ef531c11fff2148/model.mjs:1-119 · blob e03ff37655970a1bf65e539cae361b28445d7311 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: production_core
/* Offline curated primary notes. This validates one reviewed association, not a matcher. */
import data from './notes.json' with {type:'json'};
import {CATALOGUE} from './catalogue.mjs';
const SCHEMA='globalgrid2050.primary-notes.v1';
const NOTE_ID='PRIMARY-EN010147-002440-REFUSAL-20261110';
const requireValid=(ok,why)=>{if(!ok)throw Error('Primary note withheld: '+why);};
function freeze(value){if(value&&typeof value==='object'){for(const child of Object.values(value))freeze(child);Object.freeze(value);}return value;}
function jsonCopy(value,seen=new Set(),depth=0){
  requireValid(depth<=20,'JSON depth');
  if(value===null||typeof value==='boolean')return value;
  if(typeof value==='string'){requireValid(value.length<=20000,'JSON text bound');return value;}
  if(typeof value==='number'){requireValid(Number.isFinite(value),'finite JSON number');return value;}
  requireValid(value&&typeof value==='object'&&!seen.has(value),'plain acyclic JSON required');
  const array=Array.isArray(value),prototype=Object.getPrototypeOf(value);
  requireValid(array?prototype===Array.prototype:prototype===Object.prototype||prototype===null,'plain JSON prototype');
  const own=Reflect.ownKeys(value);requireValid(own.length<=1000,'JSON member bound');
  seen.add(value);const result=array?[]:Object.create(null);
  for(const key of own){
    if(array&&key==='length')continue;
    const descriptor=Object.getOwnPropertyDescriptor(value,key);
    requireValid(typeof key==='string'&&descriptor.enumerable&&'value'in descriptor,'JSON accessors or hidden fields forbidden');
    if(array)requireValid(/^(0|[1-9]\d*)$/.test(key)&&Number(key)<value.length,'JSON array keys');
    result[key]=jsonCopy(descriptor.value,seen,depth+1);
  }
  if(array)requireValid(result.length===value.length&&Object.keys(result).length===value.length,'dense JSON arrays required');
  seen.delete(value);return result;
}
const serial=value=>value&&typeof value==='object'?Array.isArray(value)?'['+value.map(serial).join(',')+']':'{'+Object.keys(value).sort().map(k=>JSON.stringify(k)+':'+serial(value[k])).join(',')+'}':JSON.stringify(value);
function keys(value,wanted,role){requireValid(value&&typeof value==='object'&&!Array.isArray(value)&&serial(Object.keys(value).sort())===serial([...wanted].sort()),role+' fields');}
function same(actual,expected,role){requireValid(serial(actual)===serial(expected),role+' differs from reviewed catalogue');}
function https(value){
  requireValid(typeof value==='string'&&!/[\u0000-\u0020]/.test(value),'unsafe URL');let url;
  try{url=new URL(value);}catch{throw Error('Primary note withheld: unsafe URL');}
  requireValid(url.protocol==='https:'&&url.hostname&&!url.username&&!url.password&&!url.port&&!url.hash,'unsafe URL');return value;
}
// Compare actual UTC instants at nanosecond precision, including receipt fractions.
export function utcInstant(value){
  requireValid(typeof value==='string','UTC timestamp');
  const match=value.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?(Z|\+00:00)$/);
  requireValid(match,'UTC timestamp');const [year,month,day,hour,minute,second]=match.slice(1,7).map(Number);
  requireValid(year>=1900&&year<=2100&&hour<24&&minute<60&&second<60,'UTC range');
  const ms=Date.UTC(year,month-1,day,hour,minute,second);
  requireValid(new Date(ms).toISOString().slice(0,19)===value.slice(0,19),'UTC calendar');
  return BigInt(ms)*1000000n+BigInt((match[7]||'').padEnd(9,'0'));
}
function day(value){requireValid(typeof value==='string'&&/^\d{4}-\d{2}-\d{2}$/.test(value),'date');return utcInstant(value+'T00:00:00Z');}
function canonical(projects){
  requireValid(Array.isArray(projects)&&Object.getPrototypeOf(projects)===Array.prototype,'plain canonical array required');
  const population=CATALOGUE.canonical.expected_population,length=Object.getOwnPropertyDescriptor(projects,'length');
  requireValid(length&&'value'in length&&length.value===population,'complete canonical population required');
  const members=Reflect.ownKeys(projects);
  requireValid(members.length===population+1&&members.every(key=>key==='length'||typeof key==='string'&&/^(0|[1-9]\d*)$/.test(key)&&Number(key)<population),'canonical array JSON members');
  const refs=new Set(),ids=new Set(),matches=[];
  const field=(row,name)=>{const d=Object.getOwnPropertyDescriptor(row,name);requireValid(!d||'value'in d,'canonical accessors forbidden');return d?.value;};
  for(let index=0;index<population;index++){
    const descriptor=Object.getOwnPropertyDescriptor(projects,String(index));
    requireValid(descriptor&&descriptor.enumerable&&'value'in descriptor,'dense canonical array data required');
    const row=descriptor.value;
    requireValid(row&&typeof row==='object','canonical row');const ref=field(row,'repd_ref'),id=field(row,'gg_project_id');
    requireValid(typeof ref==='string'&&/^[1-9]\d*$/.test(ref)&&id==='GG2050-REPD-'+ref,'canonical original IDs');
    requireValid(!refs.has(ref)&&!ids.has(id),'duplicate canonical identity');refs.add(ref);ids.add(id);
    if(field(row,'planning_application_reference')===CATALOGUE.source.planning_reference)matches.push(row);
  }
  requireValid(matches.length===1,'exact planning reference must be unique');const row=jsonCopy(matches[0]);
  for(const [field,expected] of Object.entries(CATALOGUE.canonical.fields))requireValid(Object.is(row[field],expected),'canonical '+field+' mismatch');
  return row;
}
function clocks(note,cutoff){
  const source=note.source,review=note.evidence_review,news=note.news_metadata;
  const moments=[source.retrieved_at,review.independent_review_at,review.curated_at,news.read_at,news.feed_generated_at,news.published_at,news.first_seen,
    ...note.rights.terms_receipts.map(r=>r.retrieved_at)];
  requireValid(moments.every(value=>utcInstant(value)<=cutoff),'future receipt, publication or evaluation clock');
  for(const value of [source.document_date,source.document_stated_publication_date,note.claim.decision_date,note.claim.source_application_submitted])requireValid(day(value)<=cutoff,'future document/event date');
  const modified=Date.parse(source.headers['Last-Modified']);requireValid(Number.isFinite(modified)&&BigInt(modified)*1000000n<=cutoff,'future/invalid HTTP clock');
  requireValid(day(note.claim.decision_date)<=day(source.document_date)&&day(source.document_stated_publication_date)<=utcInstant(source.retrieved_at),'decision/publication chronology');
  requireValid(utcInstant(source.retrieved_at)<=utcInstant(review.independent_review_at)&&note.rights.terms_receipts.every(r=>utcInstant(r.retrieved_at)<=utcInstant(review.independent_review_at)),'primary review chronology');
  requireValid(utcInstant(news.published_at)<=utcInstant(news.first_seen)&&utcInstant(news.first_seen)<=utcInstant(news.feed_generated_at)&&
    utcInstant(news.feed_generated_at)<=utcInstant(news.read_at)&&utcInstant(news.read_at)<=utcInstant(review.curated_at)&&
    utcInstant(review.independent_review_at)<=utcInstant(review.curated_at),'auxiliary metadata/curation chronology');
}
function validate(note,row,cutoff){
  note=jsonCopy(note);
  keys(note,['id','association','binding','source','rights','claim','news_metadata','evidence_review'],'note');
  requireValid(note.id===NOTE_ID&&note.association==='PROVISIONAL','only reviewed provisional association allowed');
  keys(note.binding,['repd_ref','gg_project_id','planning_reference','canonical_edition','canonical_partition','canonical_partition_sha256'],'binding');
  requireValid(note.binding.repd_ref===row.repd_ref&&note.binding.gg_project_id===row.gg_project_id&&
    note.binding.planning_reference===row.planning_application_reference,'exact binding mismatch');
  same(note.binding,{repd_ref:row.repd_ref,gg_project_id:row.gg_project_id,planning_reference:row.planning_application_reference,
    canonical_edition:CATALOGUE.canonical.edition,canonical_partition:CATALOGUE.canonical.partition,canonical_partition_sha256:CATALOGUE.canonical.partition_sha256},'canonical snapshot');
  requireValid(note.source&&note.rights&&note.claim&&note.news_metadata&&note.evidence_review&&
    Array.isArray(note.rights.terms_receipts)&&note.source.headers,'source/rights/claim receipts required');
  for(const field of ['source','rights','claim','news_metadata'])keys(note[field],Object.keys(CATALOGUE[field]),field);
  keys(note.evidence_review,Object.keys(CATALOGUE.review),'evidence review');
  for(const receipt of note.rights.terms_receipts)keys(receipt,['url','bytes','sha256','retrieved_at'],'rights receipt');
  for(const url of [note.source.url,note.source.project_url,note.rights.licence_url,note.news_metadata.source_url,note.news_metadata.article_url,...note.rights.terms_receipts.map(r=>r.url)])https(url);
  clocks(note,cutoff);
  // Exact trusted document and claim scope, not caller rights flags or a common hostname.
  same(note.source,CATALOGUE.source,'source receipt');same(note.rights,CATALOGUE.rights,'narrow rights evidence');
  same(note.claim,CATALOGUE.claim,'bounded decision claim');same(note.news_metadata,CATALOGUE.news_metadata,'auxiliary metadata');
  same(note.evidence_review,CATALOGUE.review,'actual review metadata');
  return freeze(note);
}
export const CURATED_NOTES=freeze(data);
export function buildPrimaryNotes(projects,options={}){
  requireValid(options&&typeof options==='object'&&!Array.isArray(options)&&Object.keys(options).every(k=>['asOf','records'].includes(k)),'unsupported evaluation options');
  const {asOf,records=CURATED_NOTES.notes}=options;
  const cutoff=utcInstant(asOf);same(CURATED_NOTES.schema,SCHEMA,'curated schema');const row=canonical(projects);
  requireValid(Array.isArray(records)&&records.length<=10,'bounded note records');const proposals=jsonCopy(records),ids=new Set(),bindings=new Set();
  for(const record of proposals){
    requireValid(record&&typeof record==='object','note object');const binding=record.binding?.gg_project_id;
    requireValid(!ids.has(record.id)&&!bindings.has(binding),'duplicate note/binding');ids.add(record.id);bindings.add(binding);
  }
  requireValid(proposals.length<=1,'one reviewed decision only');
  const accepted=proposals.map(record=>validate(record,row,cutoff));
  const byRef=Object.create(null),byId=Object.create(null);
  for(const note of accepted){byRef[note.binding.repd_ref]=[note];byId[note.binding.gg_project_id]=[note];}
  return freeze({schema:SCHEMA,validated_as_of:asOf,association_count:accepted.length,verified_count:0,solar1000_verified_delta:0,
    by_repd_ref:byRef,by_project_id:byId});
}