In this section
- VEDIC Regional Core transform · gridatlas / tools/vedic/regional-core.mjs lines 1–95
- VEDIC Regional Core Test test · gridatlas / tools/vedic/regional-core.test.mjs lines 1–48
- VEDIC Regional Io ingest · gridatlas / tools/vedic/regional-io.mjs lines 1–95
- VEDIC Regional Stream Test test · gridatlas / tools/vedic/regional-stream.test.mjs lines 1–70
- VEDIC Snapshot Routing transform · gridatlas / tools/vedic/snapshot-routing.mjs lines 1–39
- VEDIC Snapshot Routing Test test · gridatlas / tools/vedic/snapshot-routing.test.mjs lines 1–38
- Build storage · gridatlas / tools/vicinity-controls/build.mjs lines 1–24
- Build storage · gridatlas / tools/vicinity-focus/build.mjs lines 1–23
- Asset Context Test test · gridatlas / tools/vicinity/asset-context.test.mjs lines 1–14
- Browser Test test · gridatlas / tools/vicinity/browser.test.mjs lines 1–165
- Build storage · gridatlas / tools/vicinity/build.mjs lines 1–27
VEDIC Regional Core
A JavaScript module in the tools folder of GridAtlas that tiles cover (`tileCover`) and identity (`tileIdentity`) and creates regional pool (`createRegionalPool`). It creates regional pool (`createRegionalPool`) and sets desired (`setDesired`).
transformgridatlas / tools/vedic/regional-core.mjs · lines 1–95 of 95 · Not reached from any entry point (candidate for review) · pattern setDesired (shared by 2 files)
- What it does
- It calculates its inputs. Defines 20 functions or classes, including tileCover, mm, orient, on, opposite.
- Why it exists in the grid workflow
- Domain stage agent_infra (path word 'vedic'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Downstream impact
- Used directly by 2 files: VEDIC Regional Core Test (gridatlas); VEDIC Regional Io (gridatlas).
- What it achieves
- VEDIC exact tile cover v1; independent, network-free projected-metre capability.
- Why it matters
- Imported by VEDIC Regional Io. Checked by VEDIC Regional Core Test.
- Application
- gridatlas · tools/vedic · JavaScript module
- Uses
- none found
- Used by
- imported by VEDIC Regional Core Test (import), imported by VEDIC Regional Io (import)
- Produces
- tileCover, regionalWindow, tileIdentity, createRegionalPool
- Defines here
- tileCover, mm, orient, on, opposite, cross, near, hit, inside, boxDist, regionalWindow, tileIdentity, createRegionalPool, snapshot, evict, oldest, setDesired, admit, settle, clear
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/vedic/regional-core.mjs:1-95 · blob 27fc62e7cc2cebc5bad648417bb775895acebde5 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
// VEDIC exact tile cover v1; independent, network-free projected-metre capability.
export function tileCover(points,{pitch=2048,origin=[0,0],radius=0,metric="euclidean",maxCandidates=100000,maxTiles=20000}={}){
// Exact predicate on a declared millimetre lattice; no geographic transform or I/O.
const mm=x=>{if(!Number.isFinite(x)||Math.abs(x)>1e7||Math.abs(x*1000-Math.round(x*1000))>0.00001)throw RangeError("expected bounded millimetre-aligned metres");return Math.round(x*1000)};
if(!Array.isArray(points)||!Array.isArray(origin)||origin.length!==2||!["euclidean","square"].includes(metric)||!Number.isSafeInteger(maxCandidates)||maxCandidates<1||!Number.isSafeInteger(maxTiles)||maxTiles<1)throw RangeError("invalid cover options");
const p=mm(pitch),r=mm(radius),ox=mm(origin[0]),oy=mm(origin[1]);
if(p<1000||r<0)throw RangeError("pitch >= 1m and radius >= 0 required");
const path=points.map(q=>{if(!Array.isArray(q)||q.length!==2)throw RangeError("point");return [mm(q[0])-ox,mm(q[1])-oy]});
const B=BigInt, sq=x=>x*x, min=(a,b)=>a<b?a:b,max=(a,b)=>a>b?a:b;
const orient=(a,b,c)=>(b[0]-a[0])*(c[1]-a[1])-(b[1]-a[1])*(c[0]-a[0]);
const on=(a,b,c)=>orient(a,b,c)===0n&&min(a[0],b[0])<=c[0]&&c[0]<=max(a[0],b[0])&&min(a[1],b[1])<=c[1]&&c[1]<=max(a[1],b[1]);
const opposite=(a,b)=>(a<0n&&b>0n)||(a>0n&&b<0n);
const cross=(a,b,c,d)=>{const u=orient(a,b,c),v=orient(a,b,d),w=orient(c,d,a),z=orient(c,d,b);return (opposite(u,v)&&opposite(w,z))||on(a,b,c)||on(a,b,d)||on(c,d,a)||on(c,d,b)};
const near=(a,b,c,R)=>{const dx=b[0]-a[0],dy=b[1]-a[1],x=c[0]-a[0],y=c[1]-a[1],l=sq(dx)+sq(dy),t=x*dx+y*dy;if(t<=0n)return sq(x)+sq(y)<=R;if(t>=l)return sq(c[0]-b[0])+sq(c[1]-b[1])<=R;return sq(dx*y-dy*x)<=R*l};
const hit=(a,b,x,y)=>{let l=B(x),d=B(y),h=l+B(p),u=d+B(p),R=B(r);
if(metric==="square"){l-=R;d-=R;h+=R;u+=R}
const inside=q=>l<=q[0]&&q[0]<=h&&d<=q[1]&&q[1]<=u;
const corners=[[l,d],[h,d],[h,u],[l,u]];
if(inside(a)||inside(b)||corners.some((c,i)=>cross(a,b,c,corners[(i+1)%4])))return true;
if(metric==="square"||r===0)return false;
const boxDist=q=>sq(max(0n,max(l-q[0],q[0]-h)))+sq(max(0n,max(d-q[1],q[1]-u)));
return boxDist(a)<=sq(R)||boxDist(b)<=sq(R)||corners.some(c=>near(a,b,c,sq(R)))};
const out=new Map();let candidates=0;
for(let k=0;k<path.length;k++){
if(k===0&&path.length>1)continue;
const a=path[Math.max(0,k-1)],b=path[k],A=a.map(B),C=b.map(B);
const y0=Math.floor((Math.min(a[1],b[1])-r)/p)-1,y1=Math.floor((Math.max(a[1],b[1])+r)/p);
if(y1-y0+1>maxCandidates-candidates)throw RangeError("candidate budget exceeded");
for(let j=y0;j<=y1;j++){
// Conservative floating-point strip bounds, padded by one full cell; exact BigInt predicate decides membership.
let t0=0,t1=1,dy=b[1]-a[1];
if(dy!==0){let v=(j*p-r-a[1])/dy,w=((j+1)*p+r-a[1])/dy;t0=Math.max(0,Math.min(v,w));t1=Math.min(1,Math.max(v,w));if(t0>t1)continue}
else if(a[1]<j*p-r||a[1]>(j+1)*p+r)continue;
const v=a[0]+(b[0]-a[0])*t0,w=a[0]+(b[0]-a[0])*t1;
const i0=Math.floor((Math.min(v,w)-r)/p)-1,i1=Math.floor((Math.max(v,w)+r)/p)+1;
if(i1-i0+1>maxCandidates-candidates)throw RangeError("candidate budget exceeded");
for(let i=i0;i<=i1;i++){candidates++;if(hit(A,C,i*p,j*p)){const key=i+"/"+j;out.set(key,{i,j,e0:(i*p+ox)/1000,n0:(j*p+oy)/1000,size:p/1000});if(out.size>maxTiles)throw RangeError("tile budget exceeded")}}
}}
return [...out.values()].sort((a,b)=>a.j-b.j||a.i-b.i);
}
export function regionalWindow(center,{pitch=2048,origin=[0,0],width=10000,halo=0,maxTiles=256}={}){
if(!Array.isArray(center)||center.length!==2||!center.every(Number.isFinite)||!Number.isFinite(width)||width<=0||!Number.isFinite(halo)||halo<0)throw RangeError("window");
const half=width/2+halo;
// A square buffer around a point gives exact closed square acquisition.
return tileCover([center],{pitch,origin,radius:half,metric:"square",maxTiles,maxCandidates:Math.max(1024,maxTiles*8)});
}
export function tileIdentity({dataset,revision,crs,pitch,origin=[0,0],i,j,representation}){
const fields=[dataset,revision,crs,representation];if(fields.some(v=>typeof v!=="string"||!v.length)||!Array.isArray(origin)||origin.length!==2||!origin.every(Number.isFinite)||!Number.isFinite(pitch)||pitch<=0||!Number.isSafeInteger(i)||!Number.isSafeInteger(j))throw RangeError("tile identity");
return JSON.stringify(["vedic.tile.v1",...fields,pitch,...origin,i,j]);
}
export function createRegionalPool({maxBytes,maxConcurrent=2,maxEntries=64}={}){
if(![maxBytes,maxConcurrent,maxEntries].every(x=>Number.isSafeInteger(x)&&x>0))throw RangeError("pool limits");
let desired=new Map(),serial=0,clock=0;const resident=new Map(),active=new Map();
const snapshot=()=>({residentBytes:[...resident.values()].reduce((s,v)=>s+v.bytes,0),reservedBytes:[...active.values()].reduce((s,v)=>s+v.peakBytes,0),resident:resident.size,inflight:active.size});
const evict=key=>{const item=resident.get(key);if(!item)return;resident.delete(key);return key};
const oldest=()=>[...resident.entries()].sort((a,b)=>Number(desired.has(a[0]))-Number(desired.has(b[0]))||a[1].stamp-b[1].stamp)[0]?.[0];
function setDesired(entries){
if(!Array.isArray(entries)||entries.length>maxEntries)throw RangeError("desired count");
const next=new Map();
for(const x of entries){if(typeof x?.key!=="string"||!x.key||!Number.isSafeInteger(x.peakBytes)||x.peakBytes<1||x.peakBytes>maxBytes||next.has(x.key))throw RangeError("desired entry");next.set(x.key,{key:x.key,peakBytes:x.peakBytes})}
desired=next;const cancel=[],evicted=[];
for(const [id,x] of active)if(!desired.has(x.key)&&!x.cancelled){x.cancelled=true;cancel.push(id)}
for(const [key,x] of resident)if(desired.has(key))x.stamp=++clock;
// Keep unneeded cache entries until admission requires eviction.
return {cancel,evicted};
}
function admit(){
const started=[],evicted=[];
for(const x of desired.values()){
if(active.size>=maxConcurrent)break;
if(resident.has(x.key)||[...active.values()].some(a=>a.key===x.key))continue;
let s=snapshot();
while(resident.size&&(s.residentBytes+s.reservedBytes+x.peakBytes>maxBytes||resident.size+active.size>=maxEntries)){
// Do not thrash desired residents; report partial admission instead.
const k=oldest();if(desired.has(k))break;evicted.push(evict(k));s=snapshot();
}
if(s.residentBytes+s.reservedBytes+x.peakBytes>maxBytes||resident.size+active.size>=maxEntries)continue;
const token=++serial;active.set(token,{...x,cancelled:false});started.push({token,...x});
}
return {started,evicted};
}
function settle(token,{bytes=0,ok=false}={}){
const x=active.get(token);if(!x)return {accepted:false,reason:"unknown-token"};
// Caller must only settle after the decoder and transfer actually terminate.
if(!Number.isSafeInteger(bytes)||bytes<0||bytes>x.peakBytes){active.delete(token);return {accepted:false,reason:"reservation-exceeded"}}
active.delete(token);
if(!ok||x.cancelled||!desired.has(x.key))return {accepted:false,reason:"failed-or-stale"};
resident.set(x.key,{bytes,stamp:++clock});return {accepted:true,key:x.key};
}
function clear(){return setDesired([])}
return {setDesired,admit,settle,clear,snapshot};
}VEDIC Regional Core Test
A test in the tools folder of GridAtlas that checks VEDIC Regional Core, using EPSG:27700.
testgridatlas / tools/vedic/regional-core.test.mjs · lines 1–48 of 48 · Not reached from any entry point (candidate for review) · pattern oracle (shared by 4 files)
- What it does
- It tests its inputs. Defines 6 functions or classes, including runTests, ids, key, oracle, clip.
- Why it exists in the grid workflow
- Domain stage agent_infra (path word 'vedic'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
- What it achieves
- It runs tests (`runTests`) and is built from the oracle step (`oracle`) and the clip step (`clip`). Defines `runTests`, `ids`, `key` and 3 more.
- Why it matters
- Guards the behaviour of VEDIC Regional Core.
- Application
- gridatlas · tools/vedic · test
- Uses
- VEDIC Regional Core (import)
- Used by
- none found
- Produces
- runTests, ids, key, oracle, clip, dist
- Defines here
- runTests, ids, key, oracle, clip, dist
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/vedic/regional-core.test.mjs:1-48 · blob 478df03f94561e11a1e35f81d122ddcff6887046 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
import {tileCover,regionalWindow,tileIdentity,createRegionalPool} from "./regional-core.mjs";
function runTests(){
let assertions=0,zeroComparisons=0,bufferComparisons=0;const check=(v,m)=>{assertions++;if(!v)throw Error(m)};
const ids=a=>a.map(t=>t.i+"/"+t.j).join(",");
const key=(i,j)=>i+"/"+j;
// Independent parametric clipping + floating Euclidean distance via point-to-edge projections.
function oracle(a,b,x,y,p,r,metric){
const l=x*p,d=y*p,h=l+p,u=d+p;
function clip(L,D,H,U){let lo=0,hi=1;for(const [v,w,m,M] of [[a[0],b[0],L,H],[a[1],b[1],D,U]]){if(v===w){if(v<m||v>M)return false;continue}let t=(m-v)/(w-v),s=(M-v)/(w-v);lo=Math.max(lo,Math.min(t,s));hi=Math.min(hi,Math.max(t,s));}return lo<=hi+1e-14}
if(metric==="square")return clip(l-r,d-r,h+r,u+r);
if(clip(l,d,h,u))return true;if(!r)return false;
const dist=(q,c,e)=>{let dx=e[0]-c[0],dy=e[1]-c[1],den=dx*dx+dy*dy,t=den?Math.max(0,Math.min(1,((q[0]-c[0])*dx+(q[1]-c[1])*dy)/den)):0;return Math.hypot(q[0]-c[0]-t*dx,q[1]-c[1]-t*dy)};
const corners=[[l,d],[h,d],[h,u],[l,u]];
return Math.min(...corners.flatMap((c,i)=>[dist(c,a,b),dist(a,c,corners[(i+1)%4]),dist(b,c,corners[(i+1)%4])]))<=r+1e-9;
}
let state=12345;const draw=()=>{state=(Math.imul(1664525,state)+1013904223)>>>0;return Math.floor(state/4294967296*20001)-10000};
const cases=[[[1948,2058],[2058,1948]],[[0,0],[4096,4096]],[[0,0],[0,4096]],[[0,0],[0,0]],[[-2048,-2048],[2048,2048]]];
for(let k=0;k<10000;k++)cases.push([[draw(),draw()],[draw(),draw()]]);
for(const [a,b] of cases){
const actual=new Set(tileCover([a,b]).map(t=>key(t.i,t.j)));let expected=0;
for(let j=Math.floor(Math.min(a[1],b[1])/2048)-1;j<=Math.floor(Math.max(a[1],b[1])/2048);j++)for(let i=Math.floor(Math.min(a[0],b[0])/2048)-1;i<=Math.floor(Math.max(a[0],b[0])/2048);i++){const hit=oracle(a,b,i,j,2048,0,"euclidean");zeroComparisons++;check(actual.has(key(i,j))===hit,"zero oracle");expected+=Number(hit)}
check(actual.size===expected,"no extra tiles");
}
for(let k=0;k<1000;k++){
const a=[draw(),draw()],b=[draw(),draw()],r=k%5===0?0:1+Math.abs(draw()%1200);
for(const metric of ["square","euclidean"]){
const actual=new Set(tileCover([a,b],{radius:r,metric}).map(t=>key(t.i,t.j)));let expected=0;
for(let j=Math.floor((Math.min(a[1],b[1])-r)/2048)-1;j<=Math.floor((Math.max(a[1],b[1])+r)/2048);j++)for(let i=Math.floor((Math.min(a[0],b[0])-r)/2048)-1;i<=Math.floor((Math.max(a[0],b[0])+r)/2048);i++){const hit=oracle(a,b,i,j,2048,r,metric);bufferComparisons++;check(actual.has(key(i,j))===hit,"buffer oracle");expected+=Number(hit)}
check(actual.size===expected,"no extra buffer tiles");check(ids(tileCover([a,b],{radius:r,metric}))===ids(tileCover([b,a],{radius:r,metric})),"reversal");
}}
check(ids(tileCover([[1948,2058],[2058,1948]]))==="0/0,1/0,0/1","inherited defect");
check(tileCover([[0,0]]).length===4,"corner");check(tileCover([[1,1]],{pitch:1,radius:1,metric:"euclidean"}).length===12,"tangent");
check(tileCover([[0,0],[50000,0]]).length>regionalWindow([0,0]).length,"long path");
check(regionalWindow([0,0]).length===36,"aligned window");check(regionalWindow([1024,1024]).length===25,"offset window");
check(regionalWindow([0,0],{halo:500}).length<=49,"halo");
check(ids(tileCover([[0,0],[1,1],[1,1]]))===ids(tileCover([[0,0],[1,1]])),"repeat");
check(tileIdentity({dataset:"road",revision:"v1",crs:"EPSG:27700",pitch:2048,i:-1,j:2,representation:"graph"})!==tileIdentity({dataset:"road",revision:"v2",crs:"EPSG:27700",pitch:2048,i:-1,j:2,representation:"graph"}),"revision key");
for(const action of [()=>tileCover([[NaN,1]]),()=>tileCover([[1,1]],{radius:-1}),()=>tileCover([[1.0001,1]]),()=>tileCover([[0,0],[1e6,1e6]],{maxCandidates:10})]){let threw=false;try{action()}catch{threw=true}check(threw,"invalid/budget")}
const pool=createRegionalPool({maxBytes:100,maxConcurrent:2,maxEntries:3});
pool.setDesired([{key:"a",peakBytes:60},{key:"b",peakBytes:40}]);let s=pool.admit().started;check(s.length===2,"concurrency");check(pool.snapshot().reservedBytes===100,"reserve");
const c=pool.setDesired([{key:"c",peakBytes:60}]);check(c.cancel.length===2,"cancel");check(pool.admit().started.length===0,"no early release");check(!pool.settle(s[0].token,{ok:true,bytes:30}).accepted,"late discard");
let n=pool.admit().started;check(n.length===1,"admit after settle");check(!pool.settle(s[1].token,{ok:true,bytes:20}).accepted,"second stale");check(pool.settle(n[0].token,{ok:true,bytes:60}).accepted,"commit");
pool.setDesired([{key:"d",peakBytes:80}]);let d=pool.admit();check(d.evicted[0]==="c"&&d.started.length===1,"eviction");check(pool.snapshot().residentBytes+pool.snapshot().reservedBytes<=100,"bounded");
check(!pool.settle(d.started[0].token,{ok:true,bytes:81}).accepted,"overflow reject");check(pool.snapshot().reservedBytes===0,"release");
for(let k=0;k<1000;k++){pool.setDesired([{key:"cycle-"+k,peakBytes:80}]);let a=pool.admit();check(a.started.length===1,"cycle admit");check(pool.settle(a.started[0].token,{ok:true,bytes:60}).accepted,"cycle settle");const v=pool.snapshot();check(v.residentBytes+v.reservedBytes<=100&&v.inflight===0,"cycle bound")}
return {assertions,zeroComparisons,bufferComparisons,segments:cases.length,bufferedSegments:2000,cycles:1000};
}
console.log(JSON.stringify(runTests()));VEDIC Regional Io
A JavaScript module in the tools folder of GridAtlas that reads verified shard (`readVerifiedShard`), creates shard session (`createShardSession`) and syncs desired (`syncDesired`), using SHA-256.
ingestgridatlas / tools/vedic/regional-io.mjs · lines 1–95 of 95 · Not reached from any entry point (candidate for review) · pattern setDesired (shared by 2 files)
- What it does
- It lists and searches its content. Defines 10 functions or classes, including readVerifiedShard, createShardSession, drop, syncDesired, pump.
- Why it exists in the grid workflow
- Domain stage agent_infra (path word 'vedic'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Downstream impact
- Used directly by 3 files: VEDIC Snapshot Provider V9214 Test (gridatlas); VEDIC Snapshot Provider (gridatlas); VEDIC Regional Stream Test (gridatlas).
- What it achieves
- It reads verified shard (`readVerifiedShard`), creates shard session (`createShardSession`) and syncs desired (`syncDesired`). Regional shard transport. No map, DOM, routing provider, or national fallback.
- Why it matters
- Imported by VEDIC Snapshot Provider. Checked by 2 tests, including VEDIC Snapshot Provider V9214 Test.
- Application
- gridatlas · tools/vedic · JavaScript module
- Uses
- VEDIC Regional Core (import)
- Used by
- imported by VEDIC Snapshot Provider V9214 Test (import), imported by VEDIC Snapshot Provider (import), imported by VEDIC Regional Stream Test (import)
- Produces
- readVerifiedShard, createShardSession
- Defines here
- readVerifiedShard, createShardSession, drop, syncDesired, pump, setDesired, borrow, idle, snapshot, close
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/vedic/regional-io.mjs:1-95 · blob ad41dd991fc88fe89188ade64ca20e10596ed0d8 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
// Regional shard transport. No map, DOM, routing provider, or national fallback.
import {createRegionalPool} from "./regional-core.mjs";
export async function readVerifiedShard(entry,{signal,fetcher=globalThis.fetch,subtle=globalThis.crypto?.subtle}={}){
if(!Number.isSafeInteger(entry.bytes)||entry.bytes<1||!/^([0-9a-f]{64})$/.test(entry.sha256)||!subtle)throw Error("invalid shard manifest or digest runtime");
if(signal?.aborted)throw Error("aborted");
const response=await fetcher(entry.url,{signal,redirect:"error",credentials:"omit"});
if(!response.ok||!response.body)throw Error("shard transport unavailable");
const reader=response.body.getReader(); let completed=false;
try{
const bytes=new Uint8Array(entry.bytes);let offset=0;
while(true){
if(signal?.aborted)throw Error("aborted");
const {done,value}=await reader.read();
if(done){completed=true;break}
if(!(value instanceof Uint8Array)||value.length>bytes.length-offset)throw Error("shard byte limit");
bytes.set(value,offset);offset+=value.length;
}
if(signal?.aborted||offset!==bytes.length)throw Error("stale or truncated shard");
const digest=new Uint8Array(await subtle.digest("SHA-256",bytes));
if(signal?.aborted)throw Error("aborted");
if(Array.from(digest,x=>x.toString(16).padStart(2,"0")).join("")!==entry.sha256)throw Error("shard digest mismatch");
return bytes;
}finally{
try{if(!completed)await reader.cancel()}finally{reader.releaseLock()}
}
}
// Scope: raw byte residency only. Browser/decoder/GPU allocations are not measured by this ledger.
// The caller must use trusted, immutable manifests and an authorised geographically partitioned endpoint.
export function createShardSession({maxBytes,maxEntries=64,maxConcurrent=2,fetcher,subtle}={}){
const pool=createRegionalPool({maxBytes,maxEntries,maxConcurrent});
let desired=new Map(),closed=false;const residents=new Map(),active=new Map(),failed=new Map();
const drop=key=>residents.delete(key);
function syncDesired(){
const {cancel,evicted}=pool.setDesired([...desired.values()].filter(e=>!failed.has(e.key)).map(({key,peakBytes})=>({key,peakBytes})));
for(const key of evicted)drop(key);
for(const token of cancel)active.get(token)?.controller.abort();
}
function pump(){
if(closed)return;
syncDesired();
const {started,evicted}=pool.admit();
for(const key of evicted)drop(key); // release raw reference before starting replacement work
for(const job of started){
const controller=new AbortController(),entry=desired.get(job.key);
const record={controller,promise:null};active.set(job.token,record);
record.promise=(async()=>{
let data=null,error=null;
try{data=await readVerifiedShard(entry,{signal:controller.signal,fetcher,subtle})}
catch(e){error=String(e)}
const settled=pool.settle(job.token,{bytes:data?.byteLength??0,ok:!!data&&!closed&&!controller.signal.aborted});
if(settled.accepted&&!closed)residents.set(job.key,data);
if(error&&!controller.signal.aborted&&!closed&&desired.has(job.key))failed.set(job.key,error);
active.delete(job.token);
if(!closed)pump();
})();
}
}
function setDesired(entries){
if(closed)throw Error("session closed");
if(!Array.isArray(entries)||entries.length>maxEntries)throw Error("too many desired shards");
const next=new Map();
for(const x of entries){
if(typeof x?.key!=="string"||!x.key||[...next.keys()].some(k=>JSON.parse(k)[0]===x.key)||typeof x.url!=="string"||!Number.isSafeInteger(x.bytes)||x.bytes<1||!/^([0-9a-f]{64})$/.test(x.sha256))throw Error("invalid manifest entry");
const url=new URL(x.url);if(url.protocol!=="https:"||url.username||url.password)throw Error("HTTPS shard URL required");
// Estimate raw buffer + digest/transport overhead; not a hard browser process limit.
const peakBytes=x.bytes*3+65536;
if(!Number.isSafeInteger(peakBytes)||peakBytes>maxBytes)throw Error("shard exceeds admission budget");
// Identity includes immutable content digest; URL rotation cannot substitute a different payload.
const key=JSON.stringify([x.key,x.sha256,x.bytes]);
if(next.has(key))throw Error("duplicate immutable shard");
next.set(key,{...x,key,peakBytes});
}
desired=next;failed.clear();pump();
}
function borrow(key,fn){
if(closed||typeof fn!=="function")throw Error("unavailable session");
const k=[...desired.keys()].find(k=>desired.get(k).key===k&&JSON.parse(k)[0]===key);
if(!k||!residents.has(k))return false;
// Synchronous borrower contract: do not retain or mutate buffer; no physical GC guarantee.
const result=fn(residents.get(k));
if(result&&typeof result.then==="function")throw Error("async borrow prohibited");
return true;
}
async function idle(){while(active.size)await Promise.all([...active.values()].map(x=>x.promise));return snapshot()}
function snapshot(){return {...pool.snapshot(),rawOwnedBytes:[...residents.values()].reduce((n,b)=>n+b.byteLength,0),desired:desired.size,failed:[...failed.entries()],closed}}
async function close(){
closed=true;desired.clear();pool.clear();for(const x of active.values())x.controller.abort();
residents.clear();failed.clear();await idle();
// Pool metadata is intentionally not reused after terminal close.
return snapshot();
}
return {setDesired,borrow,idle,snapshot,close};
}VEDIC Regional Stream Test
A test in the tools folder of GridAtlas that checks VEDIC Regional Io and VEDIC Road Topology, using SHA-256.
testgridatlas / tools/vedic/regional-stream.test.mjs · lines 1–70 of 70 · Not reached from any entry point (candidate for review) · pattern rejects (shared by 2 files)
- What it does
- It tests its inputs. Defines 9 functions or classes, including check, equal, rejects, e, good. Uses libraries node:assert/strict, node:crypto, node:fs. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage agent_infra (path word 'vedic'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: command-line arguments.
- What it achieves
- It is built from the good step (`good`), the fetcher step (`fetcher`) and the rel step (`rel`). Defines `check`, `equal`, `rejects` and 3 more.
- Why it matters
- Guards the behaviour of VEDIC Regional Io and VEDIC Road Topology.
- Application
- gridatlas · tools/vedic · test
- Uses
- VEDIC Regional Io (import), VEDIC Road Topology (import), node:assert/strict, node:crypto, node:fs
- Used by
- none found
- Produces
- check, equal, rejects, e, good, fetcher, n, w, rel
- Defines here
- check, equal, rejects, e, good, fetcher, n, w, rel
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/vedic/regional-stream.test.mjs:1-70 · blob 352ba6887c0fc811b89e758372701e8f48c18670 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
import assert from "node:assert/strict";
import {createHash,webcrypto} from "node:crypto";
import {readFileSync} from "node:fs";
import {readVerifiedShard,createShardSession} from "./regional-io.mjs";
import {compileTopology} from "./road-topology.mjs";
let assertions=0;
const check=(value,message)=>{assert.ok(value,message);assertions++};
const equal=(a,b)=>{assert.deepEqual(a,b);assertions++};
async function rejects(fn,pattern){await assert.rejects(fn,pattern);assertions++}
const bytes=new Uint8Array([1,2,3,4]);
const hash=createHash("sha256").update(bytes).digest("hex");
const e=key=>({key,url:"https://example.invalid/"+key,bytes:4,sha256:hash});
const good=async()=>new Response(new ReadableStream({start(c){c.enqueue(bytes.slice(0,2));c.enqueue(bytes.slice(2));c.close()}}));
equal(await readVerifiedShard(e("A"),{fetcher:good,subtle:webcrypto.subtle}),bytes);
await rejects(()=>readVerifiedShard({...e("A"),sha256:"0".repeat(64)},{fetcher:good,subtle:webcrypto.subtle}),/digest/);
await rejects(()=>readVerifiedShard(e("A"),{fetcher:async()=>new Response(new Uint8Array(5)),subtle:webcrypto.subtle}),/byte limit/);
await rejects(()=>readVerifiedShard(e("A"),{fetcher:async()=>new Response(new Uint8Array(3)),subtle:webcrypto.subtle}),/truncated/);
let cancel=0,completeOld,started=[];
const fetcher=async(url,{signal})=>{
const key=url.split("/").pop();started.push(key);
if(key==="slow"){
signal.addEventListener("abort",()=>cancel++,{once:true});
return await new Promise(resolve=>{completeOld=()=>resolve(new Response(bytes))});
}
return good();
};
const session=createShardSession({maxBytes:65548,maxConcurrent:1,maxEntries:2,fetcher,subtle:webcrypto.subtle});
session.setDesired([e("slow")]);await Promise.resolve();
session.setDesired([e("new")]);
equal(cancel,1);equal(started,["slow"]);equal(session.snapshot().reservedBytes,65548);
completeOld();await session.idle();equal(started,["slow","new"]);
check(!session.borrow("slow",()=>{}));check(session.borrow("new",b=>equal([...b],[1,2,3,4])));
for(let i=0;i<1000;i++){
session.setDesired([e("window"+i)]);
const s=await session.idle();check(s.residentBytes+s.reservedBytes<=65548);check(s.rawOwnedBytes<=8);
check(session.borrow("window"+i,()=>{}));
}
await session.close();equal(session.snapshot().rawOwnedBytes,0);equal(session.snapshot().inflight,0);
const failed=createShardSession({maxBytes:70000,maxEntries:2,maxConcurrent:1,fetcher:async()=>new Response(null,{status:503}),subtle:webcrypto.subtle});
failed.setDesired([e("bad")]);await failed.idle();equal(failed.snapshot().failed.length,1);equal(failed.snapshot().inflight,0);await failed.close();
const n=(id,lat,lon)=>({id:String(id),lat,lon});
const w=(id,nodes,tags={})=>({id:String(id),nodes:nodes.map(String),tags:{highway:"residential",...tags}});
const rel=(id,from,via,to,rule)=>({id:String(id),tags:{type:"restriction",restriction:rule},members:[{role:"from",type:"way",ref:String(from)},{role:"via",type:"node",ref:String(via)},{role:"to",type:"way",ref:String(to)}]});
const source={nodes:[n(1,0,0),n(2,1,1),n(3,2,2),n(4,1,1),n(5,1,2),n(6,1,0),n(7,0,2)],ways:[w(10,[1,2,3]),w(11,[4,5],{bridge:"yes",layer:"1"}),w(12,[2,6],{oneway:"-1"}),w(13,[2,7],{access:"private"}),w(14,[2,5],{motor_vehicle:"no"}),w(15,[2,7],{highway:"footway"})],relations:[rel(100,10,2,12,"no_left_turn")]};
const d=compileTopology(source,"driving");
check(!d.edges.some(x=>["13","14","15"].includes(x.way)));
check(d.edges.some(x=>x.way==="12"&&x.from==="6"&&x.to==="2"));
check(!d.edges.some(x=>x.way==="12"&&x.from==="2"&&x.to==="6"));
check(!d.turnAllowed("10:1:1","11:1:1")); // crossing coordinate, no shared node
check(!d.completeForPilot); // restriction targets missing direction; conservative block
const walking=compileTopology(source,"walking");check(walking.completeForPilot);check(walking.edges.some(x=>x.way==="14"));check(walking.edges.some(x=>x.way==="15"));
check(walking.turnAllowed("10:1:1","12:1:1"));
const s2={...source,ways:source.ways.map(x=>x.id==="12"?w(12,[2,6]):x)};
const restricted=compileTopology(s2,"driving");check(restricted.completeForPilot);check(!restricted.turnAllowed("10:1:1","12:1:1"));check(restricted.turnAllowed("10:1:1","10:2:1"));
const only=compileTopology({...s2,relations:[rel(101,10,2,12,"only_right_turn")]},"driving");check(only.turnAllowed("10:1:1","12:1:1"));check(!only.turnAllowed("10:1:1","10:2:1"));
const malformed=compileTopology({...s2,ways:[...s2.ways,w(99,[1,999])]},"driving");check(!malformed.completeForPilot);check(!malformed.turnAllowed("10:1:1","10:2:1"));
const viaWay={...rel(102,10,2,12,"no_right_turn"),members:[{role:"from",type:"way",ref:"10"},{role:"via",type:"way",ref:"11"},{role:"to",type:"way",ref:"12"}]};
check(!compileTopology({...s2,relations:[viaWay]},"driving").completeForPilot);
for(let i=0;i<500;i++){
const shifted={...s2,nodes:s2.nodes.map(n=>({...n,lon:n.lon+0.00001*i}))};
const graph=compileTopology(shifted,"driving");check(graph.completeForPilot);equal(graph.edges,restricted.edges);check(!graph.turnAllowed("10:1:1","11:1:1"));
}
console.log(JSON.stringify({syntheticAssertions:assertions,windowCycles:1000,coordinatePerturbations:500}));
if(process.argv[2]){
const source=JSON.parse(readFileSync(process.argv[2],"utf8"));
for(const mode of ["walking","driving"]){
const g=compileTopology(source,mode);
console.log(JSON.stringify({source:"bounded OSM pilot",mode,nodes:g.vertices.size,edges:g.edges.length,issues:g.issues.slice(0,30),issueCount:g.issues.length,completeForPilot:g.completeForPilot}));
}
}VEDIC Snapshot Routing
A JavaScript module in the tools folder of GridAtlas that builds routing graph (`buildRoutingGraph`) and routes candidate (`routeCandidate`). It builds routing graph (`buildRoutingGraph`) and routes candidate (`routeCandidate`).
transformgridatlas / tools/vedic/snapshot-routing.mjs · lines 1–39 of 39 · Not reached from any entry point (candidate for review) · pattern speed (shared by 2 files)
- What it does
- It calculates its inputs. Defines 7 functions or classes, including buildRoutingGraph, conditional, nodeAllowed, distance, speed.
- Why it exists in the grid workflow
- Domain stage agent_infra (path word 'vedic'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Downstream impact
- Used directly by 4 files: VEDIC Snapshot Provider V9214 Test (gridatlas); VEDIC Snapshot Provider (gridatlas); VEDIC Snapshot Provider Test (gridatlas); VEDIC Snapshot Routing Test (gridatlas).
- What it achieves
- VEDIC E03: bounded snapshot pilot, not a live navigation provider.
- Why it matters
- Imported by VEDIC Snapshot Provider. Checked by 3 tests, including VEDIC Snapshot Provider V9214 Test.
- Application
- gridatlas · tools/vedic · JavaScript module
- Uses
- VEDIC Road Topology (import)
- Used by
- imported by VEDIC Snapshot Provider V9214 Test (import), imported by VEDIC Snapshot Provider (import), imported by VEDIC Snapshot Provider Test (import), imported by VEDIC Snapshot Routing Test (import)
- Produces
- buildRoutingGraph, routeCandidate, weakComponents
- Defines here
- buildRoutingGraph, conditional, nodeAllowed, distance, speed, routeCandidate, fail
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/vedic/snapshot-routing.mjs:1-39 · blob 01c65025b5ebe548fa1f63c110314ad58af28412 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
// VEDIC E03: bounded snapshot pilot, not a live navigation provider.
import {compileTopology} from './road-topology.mjs';
export function buildRoutingGraph(source,mode,compiler=compileTopology){
const base=compiler(source,mode), ways=new Map(source.ways.map(w=>[w.id,w])), permit=new Set(["yes","designated","permissive"]);
const accessKeys=mode==="walking"?["foot","access"]:["motorcar","motor_vehicle","vehicle","access"];
const quarantined=new Map(), nodes=base.vertices;
const conditional=t=>Object.keys(t).some(k=>k.endsWith(":conditional")&&/^(access|vehicle|motor_vehicle|motorcar|foot|oneway)/.test(k));
const nodeAllowed=n=>{const t=n.tags??{},v=accessKeys.map(k=>t[k]).find(v=>v!==undefined);if(conditional(t))return false;if(v!==undefined)return permit.has(v);return !t.barrier};
const distance=(a,b)=>{const rad=Math.PI/180,dlat=(b.lat-a.lat)*rad,dlon=(b.lon-a.lon)*rad,h=Math.sin(dlat/2)**2+Math.cos(a.lat*rad)*Math.cos(b.lat*rad)*Math.sin(dlon/2)**2;return Math.max(1,Math.round(6371008.8*2*Math.asin(Math.min(1,Math.sqrt(h)))*1000))};
function speed(t){const v=t.maxspeed;if(v!==undefined){const m=String(v).match(/^(\d+(?:\.\d+)?)\s*(mph|km\/h|kph)?$/);if(!m||Number(m[1])<=0)return null;return Math.min(30,Number(m[1])*(m[2]==="mph"?1.609344:1));}return t.highway==="service"?10:20}
const edges=[],adj=new Map(),active=new Set();
for(const e of base.edges){const a=nodes.get(e.from),b=nodes.get(e.to),t=ways.get(e.way).tags??{};let reason=null;
if(!nodeAllowed(a)||!nodeAllowed(b))reason="node-access-or-barrier";
else if(Object.keys(t).some(k=>/^(access|vehicle|motor_vehicle|motorcar|foot):(forward|backward)(:|$)/.test(k)))reason="directional-access-unsupported";
else if(mode==="driving"&&Object.keys(t).some(k=>/^(maxheight|maxweight|maxwidth|maxlength|maxaxleload|hazmat)(:|$)/.test(k)))reason="vehicle-restriction-unsupported";
if(reason){quarantined.set(e.id,reason);continue}
const mm=distance(a,b),kph=mode==="driving"?speed(t):null,ms=kph===null?null:Math.max(1,Math.ceil(mm*3.6/kph));
const x={...e,mm,ms,speedBasis:kph===null?null:t.maxspeed===undefined?"class-model":"capped-tag-model",bridge:t.bridge??null,tunnel:t.tunnel??null,highway:t.highway};
edges.push(x);active.add(x.from);active.add(x.to);if(!adj.has(x.from))adj.set(x.from,[]);adj.get(x.from).push(x)
}
return {mode,edges,adj,active,quarantined,issues:base.issues,turnAllowed:base.turnAllowed,sourceVertices:nodes};
}
export function routeCandidate(g,start,end,objective="shortest",{maxStates=100000}={}){
const fail=reason=>({status:"unavailable",reason});
if(!["shortest","estimated-fastest"].includes(objective)||objective==="estimated-fastest"&&g.mode!=="driving")return fail("objective");
if(g.issues.length)return fail("unresolved-topology");
if(!g.active.has(start)||!g.active.has(end))return fail("endpoint-not-in-eligible-graph");
if(!Number.isSafeInteger(maxStates)||maxStates<1)return fail("invalid-budget");
if(objective==="estimated-fastest"&&g.edges.some(e=>e.ms===null))return fail("unresolved-speed-model");
const first={node:start,last:null,cost:0,mm:0,ms:0,prev:null},key=q=>JSON.stringify([q.node,q.last]),best=new Map([[key(first),0]]),queue=[first];let expanded=0;
while(queue.length){queue.sort((a,b)=>b.cost-a.cost);const q=queue.pop();if(q.cost!==best.get(key(q)))continue;if(++expanded>maxStates)return fail("state-budget");
if(q.node===end){const edges=[];for(let p=q;p.prev;p=p.prev)edges.push(p.last);return {status:"candidate",objective,distanceMm:q.mm,estimatedMs:objective==="estimated-fastest"?q.ms:null,edges:edges.reverse(),expanded,scope:"mapped snapshot only; not legal or live route certification"}}
for(const e of g.adj.get(q.node)??[]){if(q.last!==null&&!g.turnAllowed(q.last,e.id))continue;const cost=q.cost+(objective==="shortest"?e.mm:e.ms),r={node:e.to,last:e.id,cost,mm:q.mm+e.mm,ms:q.ms+(e.ms??0),prev:q},k=key(r);if(!Number.isSafeInteger(cost))return fail("cost-overflow");if(cost>=(best.get(k)??Infinity))continue;best.set(k,cost);queue.push(r)}
}
return fail("no-connection-in-snapshot");
}
export function weakComponents(g){const adj=new Map();for(const e of g.edges){for(const [a,b] of [[e.from,e.to],[e.to,e.from]]){if(!adj.has(a))adj.set(a,new Set());adj.get(a).add(b)}}const seen=new Set(),sizes=[];for(const a of adj.keys()){if(seen.has(a))continue;const q=[a];seen.add(a);let n=0;while(q.length){const x=q.pop();n++;for(const b of adj.get(x))if(!seen.has(b)){seen.add(b);q.push(b)}}si … [line shortened here: 442 characters; full line on GitHub]VEDIC Snapshot Routing Test
A test in the tools folder of GridAtlas that checks VEDIC Snapshot Routing, using SHA-256.
testgridatlas / tools/vedic/snapshot-routing.test.mjs · lines 1–38 of 38 · Not reached from any entry point (candidate for review) · pattern digest (shared by 56 files)
- What it does
- It tests its inputs. Defines digest, w. Uses libraries node:assert/strict, node:fs, node:crypto. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage agent_infra (path word 'vedic'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: JSON file topology.json; command-line arguments.
- What it achieves
- Defines `digest`. It reads `/topology.json`.
- Why it matters
- Guards the behaviour of VEDIC Snapshot Routing.
- Application
- gridatlas · tools/vedic · test
- Uses
- VEDIC Snapshot Routing (import), node:assert/strict, node:fs, node:crypto
- Used by
- none found
- Produces
- digest, w
- Defines here
- digest, w
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/vedic/snapshot-routing.test.mjs:1-38 · blob 0f4eb882d6ce538e3d8367a5d2c499720a821de1 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import {createHash} from 'node:crypto';
import {buildRoutingGraph,routeCandidate,weakComponents} from './snapshot-routing.mjs';
const dir=process.argv[2];if(!dir)throw Error('verified fixture required');
const digest=p=>createHash('sha256').update(readFileSync(dir+'/'+p)).digest('hex');
assert.equal(digest('source.osm'),'5eecad95c1fa2b5df5f776eafee23f0cd297f92c437bec393b883a7b397a9bfd');
assert.equal(digest('topology.json'),'50372236298639e6f1d35c9059c755716614b5ddcfa4bd177837514e689ed7d6');
const s=JSON.parse(readFileSync(dir+'/topology.json','utf8'));
let comparisons=0;
for(const mode of ['walking','driving']){
const g=buildRoutingGraph(s,mode);assert.equal(g.issues.length,0);assert.ok(g.edges.length>0);
assert.ok(g.quarantined.size>0);
for(const e of g.edges)assert.ok(!g.quarantined.has(e.id));
for(const objective of mode==='walking'?['shortest']:['shortest','estimated-fastest']){
let mapped=0,unavailable=0;
const w=e=>objective==='shortest'?e.mm:e.ms;
for(const start of g.active){
// Independent Bellman-Ford on incoming-edge states; no priority queue or adjacency.
const d=g.edges.map(e=>e.from===start?w(e):Infinity);
for(let pass=0;pass<g.edges.length;pass++){let changed=false;
for(let i=0;i<g.edges.length;i++)if(Number.isFinite(d[i]))for(let j=0;j<g.edges.length;j++){
const a=g.edges[i],b=g.edges[j];if(a.to===b.from&&g.turnAllowed(a.id,b.id)&&d[i]+w(b)<d[j]){d[j]=d[i]+w(b);changed=true}
}if(!changed)break;
}
for(const end of g.active){
const oracle=start===end?0:Math.min(Infinity,...d.filter((_,i)=>g.edges[i].to===end));
const r=routeCandidate(g,start,end,objective);
assert.equal(r.status==='candidate'?(objective==='shortest'?r.distanceMm:r.estimatedMs):Infinity,oracle);
comparisons++;
if(r.status==='candidate'){mapped++;let at=start,last=null,mm=0,ms=0;for(const id of r.edges){const e=g.edges.find(x=>x.id===id);assert.equal(e.from,at);if(last!==null)assert.ok(g.turnAllowed(last,id));at=e.to;last=id;mm+=e.mm;ms+=e.ms??0}assert.equal(at,end);assert.equal(mm,r.distanceMm);if(objective==='estimated-fastest')assert.equal(ms,r.estimatedMs)}
else{unavailable++;assert.ok(!('edges' in r))}
}
}
console.log(JSON.stringify({mode,objective,edges:g.edges.length,quarantined:g.quarantined.size,components:weakComponents(g),mapped,unavailable}));
}
}
console.log(JSON.stringify({fixture:'original exact OSM bytes',oracleComparisons:comparisons}));Build
A JavaScript module in the vicinity controls folder of GridAtlas that uses SHA-256. It is built from the flag step (`flag`).
storagegridatlas / tools/vicinity-controls/build.mjs · lines 1–24 of 24 · Not reached from any entry point (candidate for review)
- What it does
- It loads data. Defines flag. Uses libraries node:fs, node:path, node:assert/strict, node:crypto, node:url. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- In: command-line arguments.
- What it achieves
- `V9.196/V9.197` independently reproducible vicinity control cartridges.
- Why it matters
- No other file in the estate was found to import it.
- Application
- gridatlas · tools/vicinity-controls · JavaScript module
- Uses
- node:fs, node:path, node:assert/strict, node:crypto, node:url
- Used by
- none found
- Produces
- flag
- Defines here
- flag
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/vicinity-controls/build.mjs:1-24 · blob 8cea300a14d0b873040b21a6e924ebea41c4f498 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/* V9.196/V9.197 independently reproducible vicinity control cartridges.
* Only source files, never the expected published target, enter the clean tree.
*/
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import {createHash} from 'node:crypto';
import {fileURLToPath} from 'node:url';
const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'../..');
const args=process.argv.slice(2);
const flag=x=>{const i=args.indexOf(x);return i<0?null:args[i+1]};
const G=flag('--generation')||flag('--gen');
const ledger={
'202611222325':{bytes:3865,sha256:'26754dc642ff6554bb55d25a65e422a16981141f0af5e0b8df9543498176f0f6'},
'202611222343':{bytes:7367,sha256:'97cb8d05c7c0855b3bdd02ba614f470fbe2d489ed2db7181ca0b7edd5313c8fc'}
};
assert.ok(Object.hasOwn(ledger,G),'unregistered generation');
const out=flag('--out');assert.ok(out&&typeof out==='string'&&!out.startsWith('--'));
const data=fs.readFileSync(path.join(root,'tools/vicinity-controls/src/'+G+'-vicinity-controls-rescue.js'));
assert.equal(data.length,ledger[G].bytes,'source length drift');
assert.equal(createHash('sha256').update(data).digest('hex'),ledger[G].sha256,'source SHA-256 drift');
fs.mkdirSync(path.dirname(path.resolve(out)),{recursive:true});
fs.writeFileSync(path.resolve(out),data);
console.log('PASS '+G+' original vicinity controls cartridge independently reproduced');Build
A JavaScript module in the vicinity focus folder of GridAtlas that uses SHA-256. It is built from the flag step (`flag`).
storagegridatlas / tools/vicinity-focus/build.mjs · lines 1–23 of 23 · Not reached from any entry point (candidate for review)
- What it does
- It loads data. Defines flag. Uses libraries node:fs, node:path, node:assert/strict, node:crypto, node:url. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- In: command-line arguments.
- What it achieves
- V9.195 immutable vicinity-focus cartridge source build.
- Why it matters
- No other file in the estate was found to import it.
- Application
- gridatlas · tools/vicinity-focus · JavaScript module
- Uses
- node:fs, node:path, node:assert/strict, node:crypto, node:url
- Used by
- none found
- Produces
- flag
- Defines here
- flag
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/vicinity-focus/build.mjs:1-23 · blob 5a56ceb26451071252fe8098a8834670ddf2c20f · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/* V9.195 immutable vicinity-focus cartridge source build.
* Copy the exact source register in an empty tree; refuse other generations,
* corrupted source or a missing output path. No live files are edited.
*/
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import {createHash} from 'node:crypto';
import {fileURLToPath} from 'node:url';
const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'../..');
const args=process.argv.slice(2);
const flag=(x)=>{const i=args.indexOf(x);return i<0?null:args[i+1]};
const generation=flag('--generation')||flag('--gen');
const out=flag('--out');
assert.equal(generation,'202611222130','only the pinned V9.195 source may be built');
assert.ok(out&&typeof out==='string'&&!out.startsWith('--'),'an explicit output path is required');
const src=path.join(root,'tools/vicinity-focus/src/202611222130-vicinity-focus.js');
const data=fs.readFileSync(src);
assert.equal(data.length,10350,'source length drift');
assert.equal(createHash('sha256').update(data).digest('hex'),'8ea2546b2a1fab3007d3b7a81aa509baae323051b888afd252edb6bc4726f14e','source SHA-256 drift');
fs.mkdirSync(path.dirname(path.resolve(out)),{recursive:true});
fs.writeFileSync(path.resolve(out),data);
console.log('PASS vicinity-focus source built byte for byte at '+path.resolve(out));Asset Context Test
A test in the vicinity folder of GridAtlas that checks Geodesy.
testgridatlas / tools/vicinity/asset-context.test.mjs · lines 1–14 of 14 · Entry point · pattern feature (shared by 12 files)
- What it does
- It tests battery storage (BESS), solar and the REPD register. Defines feature, map, collect. Uses libraries node:test. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: battery storage (BESS), solar, the REPD register.
- Downstream impact
- Used directly by 1 file: GridAtlas PR File Size Guard Workflow (gridatlas).
- What it achieves
- Defines `feature`, `map` and `collect`.
- Why it matters
- Run by GridAtlas PR File Size Guard Workflow.
- Application
- gridatlas · tools/vicinity · test
- Uses
- Geodesy (new URL import.meta.url), node:test
- Used by
- run by GridAtlas PR File Size Guard Workflow (workflow run)
- Produces
- feature, map, collect
- Defines here
- feature, map, collect
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/vicinity/asset-context.test.mjs:1-14 · blob 508017f7da8962e6a7cbfc41296cdb11caecc8ed · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import test from 'node:test';import assert from 'node:assert/strict';import fs from 'node:fs';import vm from 'node:vm';import {collectAssetContext} from './src/asset-context.mjs';
const ctx={window:{}};vm.runInNewContext(fs.readFileSync(new URL('../../atlas/modules/202609011950-geodesy.js',import.meta.url),'utf8'),ctx);const geodesy=ctx.window.__GRIDATLAS_MODULES__.geodesy,origin={at:[-0.4,51.5]};
const feature=(id,tech,capacity,at=[-0.401,51.5],extra={})=>({type:'Feature',id,geometry:{type:'Point',coordinates:at},properties:{name:id,repd_ref:id,tech,capacity,...extra}});
const map=features=>({getSource(id){assert.equal(id,'src-repd');return{serialize(){return{data:{type:'FeatureCollection',features}};}};}});
const collect=(extra={})=>collectAssetContext({origin,radiusKm:10,geodesy,...extra});const cat=(result,id)=>result.categories.find(c=>c.id===id);
test('full REPD GeoJSON gives typed generation/storage, distance and stable reference without source writes',()=>{const f=[feature('2470','solar',5),feature('2','bess',null),feature('3','wind',8,[2,55])],before=JSON.stringify(f),r=collect({map:map(f)});assert.equal(cat(r,'generation').count,1);assert.equal(cat(r,'generation').rows[0].originId,'repd:2470');assert.equal(cat(r,'generation').rows[0].c … [line shortened here: 548 characters; full line on GitHub]
test('missing/unloaded owner datasets remain NOT_LOADED rather than pretending an empty dataset was searched',()=>{const r=collect();for(const c of r.categories){assert.equal(c.availability,'NOT_LOADED');assert.equal(c.count,0);}const empty=collect({map:map([])});assert.equal(cat(empty,'generation').availability,'NOT_LOADED');assert.equal(cat(empty,'datacentre').availability,'NOT_LOADED');});
test('unknown, blank, zero, nonfinite and false power stay null; source strings are admitted only as positive decimals',()=>{const values=[null,'',0,NaN,Infinity,false,'unknown','5'];const r=collect({map:map(values.map((v,i)=>feature(String(i),'solar',v)))});assert.deepEqual(cat(r,'generation').rows.map(r=>r.capacityMw),[null,null,null,null,null,null,null,5]);});
test('coincident postcode-centroid data-centre IDs stay distinct and retain precision and separate MW metrics',()=>{const dots=['DC-A','DC-B'].map((id,i)=>({k:'c',dc:1,a:[-0.401,51.5],n:id,p:{id,location:{precision:'POSTCODE_CENTROID_APPROXIMATE'},it_load_mw:{value:i?null:10},grid_connection_mw:{value:20},unclassified_mw:{value:7}}})),r=collect({registry:{ukOfftakers:{state:{data:{dots}}}}}),c=cat … [line shortened here: 768 characters; full line on GitHub]
test('source IDs deduplicate repeated rows; missing IDs and coordinate coincidence do not invent or merge identity',()=>{const dots=[{k:'a',a:[-0.4,51.5],n:'A',p:{id:'A'}},{k:'a',a:[-0.4,51.5],n:'A',p:{id:'A'}},{k:'a',a:[-0.4,51.5],n:'No ID',p:{}},{k:'a',a:[-0.4,51.5],n:'No ID',p:{}}];const c=cat(collect({registry:{ukOfftakers:{state:{data:{dots}}}}}),'demand-context');assert.equal(c.count,3);asse … [line shortened here: 452 characters; full line on GitHub]
test('listed conventional MW is not current generation and industry emissions never become demand MW',()=>{const dots=[{k:'b',a:[-0.4,51.5],n:'Closed plant',p:{id:'B',status:'closed',size_metric:{unit:'MW installed',value:100}}},{k:'a',a:[-0.4,51.5],n:'Industry',p:{id:'A',size_metric:{unit:'ktCO2e',value:500}}}];const r=collect({registry:{ukOfftakers:{state:{data:{dots}}}}});assert.equal(cat(r,'co … [line shortened here: 680 characters; full line on GitHub]
test('integer bounds, null-island, canonical distance, result cap and no network are enforced',()=>{for(const radiusKm of [0,51,1.5,true,null])assert.throws(()=>collect({radiusKm}));assert.throws(()=>collect({origin:{at:[0,0]}}));let calls=0;const f=[feature('A','solar',1),feature('B','solar',2)];const c=cat(collect({map:map(f),limit:1,geodesy:{...geodesy,distanceKm(...args){calls++;return geodesy … [line shortened here: 550 characters; full line on GitHub]
test('native BESS layer variants remain storage rather than generation',()=>{const r=collect({map:map(['bess','bess_operational','bess-planning','battery_storage'].map((tech,i)=>feature(String(i),tech,3)))});assert.equal(cat(r,'storage').count,4);assert.equal(cat(r,'generation').count,0);});Browser Test
A test in the vicinity folder of GridAtlas that checks Build and Model, using SHA-256.
testgridatlas / tools/vicinity/browser.test.mjs · lines 1–165 of 165 · Entry point · pattern snapshot (shared by 43 files)
- What it does
- It tests the REPD register. Defines 7 functions or classes, including intent, snapshot, visibleTap, open, ownData. Uses libraries node:fs, node:path, node:os, node:assert/strict, node:crypto. Side effects: changes the web page (DOM); reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register, 400kV, 275kV, 132kV, 66kV, 33kV.
- Inputs & outputs
- In: JSON file receipt.json. Out: JSON file receipt.json; JSON file failure.json. Voltage levels named: 400kV, 275kV, 132kV, 66kV, 33kV, 11kV.
- Downstream impact
- Used directly by 1 file: GridAtlas PR File Size Guard Workflow (gridatlas).
- What it achieves
- It is built from the intent step (`intent`), the snapshot step (`snapshot`) and the visible tap helper (`visibleTap`). Independent native Android QA. Injection mode never counts as publication acceptance. Its code works with 11 kV, 132 kV and 275 kV.
- Why it matters
- Run by GridAtlas PR File Size Guard Workflow.
- Application
- gridatlas · tools/vicinity · test
- Uses
- Browser Test (script call), Build (script call), Model (script call), Serve (script call), node:fs, node:path, node:os, node:assert/strict, node:crypto, node:url, node:child_process
- Used by
- run by GridAtlas PR File Size Guard Workflow (workflow run)
- Produces
- intent, snapshot, visibleTap, open, ownData, assertOwnPoints, sourceFingerprint
- Defines here
- intent, snapshot, visibleTap, open, ownData, assertOwnPoints, sourceFingerprint
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/vicinity/browser.test.mjs:1-165 · blob d2d9b6d1074fbf1e0d308ba0ead4ddb33507d357 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/** Independent native Android QA. Injection mode never counts as publication acceptance. */
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import assert from 'node:assert/strict';
import {createHash} from 'node:crypto';
import {pathToFileURL,fileURLToPath} from 'node:url';
import {execFileSync} from 'node:child_process';
import {runTrainUiAcceptance} from '../train/browser.test.mjs';
const atlasRoot=path.resolve(process.env.VICINITY_ATLAS_ROOT||path.join(path.dirname(fileURLToPath(import.meta.url)),'../..'));
const {assemble}=await import(pathToFileURL(path.join(atlasRoot,'tools/vicinity/build.mjs')).href);
const {parseVicinityIntent}=await import(pathToFileURL(path.join(atlasRoot,'tools/vicinity/src/model.mjs')).href);
const generation=process.env.VICINITY_BROWSER_GENERATION||'202611172355';
const injecting=process.env.VICINITY_BROWSER_INJECT==='1';
const browserName=process.env.VICINITY_BROWSER_ENGINE||'chromium';
const output=process.env.VICINITY_BROWSER_OUTPUT||path.join(os.tmpdir(),'vicinity-independent-'+new Date().toISOString().replace(/[:.]/g,'-'));
fs.mkdirSync(output,{recursive:true});
fs.rmSync(path.join(output,'receipt.json'),{force:true});
const pwModule=process.env.PLAYWRIGHT_MODULE;
const pw=await import(pwModule&&path.isAbsolute(pwModule)?pathToFileURL(pwModule).href:pwModule||'playwright');
const {createPreviewServer}=await import(pathToFileURL(path.join(atlasRoot,'tools/journey/serve.mjs')).href);
const server=await createPreviewServer(),base='http://127.0.0.1:'+server.address().port;
const compiled=assemble({generation});
console.log(JSON.stringify({startedUTC:new Date().toISOString(),output,generation,browser:browserName,candidateSha:compiled.sha256,injecting}));
const dc={at:[-0.404504,51.496403],type:'datacentre',id:'dcuk-04bb759f3d52d660',name:'Source-listed London data centre'};
const repd={at:[2.1708996,52.1374391],type:'repd',id:'repd:2470',name:'East Anglia 3 (EA 3)'};
const errors=[],failed=[],layouts=[],origins=[],radiusChecks=[],renderChecks=[],trainDiagnostics={};
const startedUTC=new Date().toISOString(),coldStarted=performance.now(),runtimeResponses=[],responseReads=[];
const sourceHead=execFileSync('git',['rev-parse','HEAD'],{cwd:atlasRoot,encoding:'utf8'}).trim();
let browser,page,baselineLayers=[],baselineSource=null,lastTouchDiagnostic=null;
function intent(origin,radius=10){const q=new URLSearchParams({journey:'vicinity',origin_type:origin.type,origin_id:origin.id,latitude:String(origin.at[1]),longitude:String(origin.at[0]),radius_km:String(radius),name:origin.name});return q.toString();}
async function snapshot(){return page.evaluate(()=>window.__GRIDATLAS_MODULES__.gridVicinity.snapshot());}
async function visibleTap(locator){
lastTouchDiagnostic={phase:'scroll',locator:String(locator)};await locator.scrollIntoViewIfNeeded();
const target=await locator.evaluate(e=>{const rect=node=>{if(!node)return null;const r=node.getBoundingClientRect();return{x:r.x,y:r.y,width:r.width,height:r.height,top:r.top,right:r.right,bottom:r.bottom,left:r.left};},selector=node=>node?node.tagName.toLowerCase()+(node.id?'#'+node.id:'')+(node.getAttribute('class')?'.'+node.getAttribute('class').trim().split(/\s+/).slice(0,3).join('.'):''):nul … [line shortened here: 1,158 characters; full line on GitHub]
lastTouchDiagnostic=target;assert.equal(target.uncovered,true,'whole touch target is uncovered: '+target.text);if(target.button)assert.ok(target.height>=44,'primary touch target is at least44px');await locator.tap();
}
async function open(origin,radius=10){await page.evaluate(o=>window.__GRIDATLAS_MODULES__.gridVicinity.open(o),{origin,radiusKm:radius});}
async function ownData(){return page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.getSource('gridatlas-vicinity-context')?.serialize().data);}
async function assertOwnPoints(radius){const data=await ownData();assert.ok(data);const points=data.features.filter(f=>f.properties.kind==='substation');assert.ok(points.every(f=>Number.isFinite(f.properties.km)&&f.properties.km>=0&&f.properties.km<=radius));return points;}
async function sourceFingerprint(){return page.evaluate(()=>{const m=window.__GRIDATLAS_V9_MAP__,s=m.getSource('src-subs');return s?JSON.stringify(s.serialize().data):null;});}
try{
browser=await pw[browserName].launch({headless:true,...(browserName==='chromium'?{args:['--use-gl=angle','--use-angle=swiftshader','--enable-webgl','--ignore-gpu-blocklist']}: {})});
const context=await browser.newContext({...pw.devices[browserName==='webkit'?'iPhone 13':'Pixel 7'],viewport:{width:393,height:852}});
page=await context.newPage();page.on('response',r=>{if(r.url().includes('/atlas/')&&/\.(?:js|json)$/.test(new URL(r.url()).pathname))responseReads.push(r.body().then(b=>runtimeResponses.push({url:r.url(),status:r.status(),bytes:b.length,sha256:createHash('sha256').update(b).digest('hex')})).catch(error=>runtimeResponses.push({url:r.url(),bodyUnavailable:String(error.message)})));});page.on('pagee … [line shortened here: 541 characters; full line on GitHub]
await page.goto(base+'/atlas/v/'+generation+'/?'+intent(dc),{waitUntil:'domcontentloaded',timeout:90000});
await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__&&window.__GRIDATLAS_MODULES__?.geodesy,null,{timeout:90000});
await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__?.getStyle()?.layers?.length>0,null,{timeout:90000});
baselineLayers=await page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.getStyle().layers.filter(l=>!l.id.startsWith('gridatlas-vicinity-')&&!l.id.startsWith('gridatlas-train-')).map(l=>l.id));
if(injecting)await page.addScriptTag({content:compiled.body});
await page.waitForFunction(()=>window.__GRIDATLAS_MODULES__?.gridVicinity?.snapshot().opened,null,{timeout:90000});
await page.waitForFunction(()=>window.__GRIDATLAS_MODULES__.gridVicinity.snapshot().matching>1,null,{timeout:90000});
await page.waitForFunction(()=>{const m=window.__GRIDATLAS_MODULES__?.menuBar;return m?.installed||m?.failure;},null,{timeout:90000});
const coldReadyMs=performance.now()-coldStarted;
const menu=await page.evaluate(()=>window.__GRIDATLAS_MODULES__.menuBar);
assert.equal(menu.installed,true,JSON.stringify(menu));assert.equal(menu.layer_controls,63);
const panel=page.getByRole('region',{name:'Vicinity familiarisation'}),close=page.getByRole('button',{name:'Close vicinity explorer',exact:true});
const initial=await snapshot();assert.equal(initial.origin.id,dc.id);assert.deepEqual(initial.origin.at,dc.at);assert.equal(initial.radiusKm,10);assert.equal(initial.realConnectionsInferred,0);
assert.equal(await page.locator('#gridatlas-vicinity').count(),1);assert.match(await panel.innerText(),/Spatial vicinity, connectivity unknown/);
await visibleTap(page.getByRole('button',{name:'Show physical grid',exact:true}));
const physicalControls=await page.evaluate(()=>['400','275','220','132','66','subs'].map(id=>{const e=document.querySelector('#scada-ui-container input[data-layer-id=\"'+id+'\"]');return{id,present:!!e,checked:e?.checked};}));
assert.ok(physicalControls.filter(c=>c.present).length>0);assert.ok(physicalControls.every(c=>!c.present||c.checked));
await page.screenshot({path:path.join(output,'physical-grid-origin.png')});
baselineSource=await sourceFingerprint();
const sourceCoverage=await page.evaluate(()=>{const m=window.__GRIDATLAS_V9_MAP__;return{fullSubstationFeatures:m.getSource('src-subs')?.serialize().data?.features?.length??null,visibleTileFeatures:m.querySourceFeatures('src-subs').length};});
assert.equal(sourceCoverage.fullSubstationFeatures,5800);
const sourceVoltage=panel.getByRole('group',{name:'Source voltage tags',exact:true});
const slider=page.getByRole('slider',{name:'Vicinity radius in kilometres'});
radiusChecks.push({radius:10,matching:initial.matching,shown:(await assertOwnPoints(10)).length});
const radiusOneStarted=performance.now();await slider.focus();await page.keyboard.press('Home');assert.equal((await snapshot()).radiusKm,1);radiusChecks.push({radius:1,durationMs:performance.now()-radiusOneStarted,matching:(await snapshot()).matching,shown:(await assertOwnPoints(1)).length});
const radiusFiftyStarted=performance.now();await page.keyboard.press('End');assert.equal((await snapshot()).radiusKm,50);radiusChecks.push({radius:50,durationMs:performance.now()-radiusFiftyStarted,matching:(await snapshot()).matching,shown:(await assertOwnPoints(50)).length});
// Native owner actions load real generation/storage/off-taker context asynchronously.
const assetsBefore=(await snapshot()).assetContext;assert.ok(assetsBefore);
const assetsStarted=performance.now();await visibleTap(page.getByRole('button',{name:'Load existing asset layers',exact:true}));
await page.waitForFunction(()=>{const ns=window.__GRIDATLAS_MODULES__,c=ns.gridVicinity.snapshot().assetContext?.categories,dc=c?.find(x=>x.id==='datacentre');return c?.find(x=>x.id==='generation')?.availability==='LOADED'&&dc?.availability==='LOADED'&&(dc.rows.some(r=>r.source==='ukOfftakers.data-centre-pipeline')||!!ns.ukOfftakers?.state.pe);},null,{timeout:120000});
const assetContext=(await snapshot()).assetContext,assetRefreshMs=performance.now()-assetsStarted;
for(const id of ['generation','storage','datacentre','conventional','demand-context']){const category=assetContext.categories.find(c=>c.id===id);assert.equal(category.availability,'LOADED',id);assert.ok(category.count>0,id+' actual nearby positive count at50km');assert.ok(category.rows.every(r=>r.km<=50&&r.demandMw===null&&r.facilityVerified===null));assert.ok(category.rows.every(r=>r.capacityMw= … [line shortened here: 426 characters; full line on GitHub]
const dcContext=panel.locator('[data-vicinity-category=\"datacentre\"]');await visibleTap(dcContext.locator('summary'));
assert.match(await dcContext.innerText(),/Actual electricity demand unknown/);
// Lifecycle regression: unchanged owner data must not replace an open category's controls.
const assetBeforeRefresh=JSON.stringify((await snapshot()).assetContext);
await dcContext.evaluate(e=>{window.__vicinityCategory=e;window.__vicinityAssetButton=e.querySelector('button');window.__GRIDATLAS_V9_MAP__.fire('sourcedata',{sourceId:'src-repd'});});
await page.waitForTimeout(180);assert.equal(JSON.stringify((await snapshot()).assetContext),assetBeforeRefresh);
assert.equal(await dcContext.evaluate(e=>e===window.__vicinityCategory&&e.open&&e.querySelector('button')===window.__vicinityAssetButton),true,'unchanged source refresh preserves open controls');
const assetRow=assetContext.categories.find(c=>c.id==='datacentre').rows[0];
await visibleTap(dcContext.getByRole('button',{name:/^Find stations near /}).first());
assert.equal((await snapshot()).modelStations.length,0,'context asset does not become a station stop');
await visibleTap(panel.locator('.train-search-results').getByRole('button').first());
const contextBound=(await snapshot()).train.itinerary.stops.at(-1);assert.ok(contextBound.stationId.startsWith('grid_substations:'));assert.notEqual(contextBound.stationId,assetRow.originId||assetRow.id);
await visibleTap(page.getByRole('button',{name:'Clear selected stops',exact:true}));
const docs=panel.locator('.vic-document-context');await visibleTap(docs.locator('summary'));assert.match(await docs.innerText(),/Sea Link/);assert.match(await docs.innerText(),/No association|not linked|unassociated/i);
assert.equal((await snapshot()).documentContext.verifiedAssetJoins,0);
// Native Android taps operate voltage labels; no script-driven state changes.
for(const name of ['400 kV','275 kV','132 kV','66 kV','11 kV','Other stated voltage','Voltage not stated']){const box=sourceVoltage.getByRole('checkbox',{name,exact:true});if(await box.isChecked())await visibleTap(box);}
assert.deepEqual((await snapshot()).selectedBands,['33']);
const filtered=await assertOwnPoints(50);assert.ok(filtered.length>1);assert.ok(filtered.every(f=>f.properties.voltage.split(' / ').some(v=>/^33(?: kV)?$/.test(v))));
const added=panel.locator('.vic-results').getByRole('button',{name:/^Add .+ to my model$/});await visibleTap(added.nth(0));await visibleTap(added.nth(1));
const scenario=await snapshot();assert.equal(scenario.modelStations.length,2);assert.ok(scenario.train.itinerary.stops.every(row=>row.stationId.startsWith('grid_substations:')));
await visibleTap(panel.locator('.train-stops').getByRole('button',{name:/^Remove /}).first());assert.equal((await snapshot()).modelStations.length,1);
await visibleTap(page.getByRole('button',{name:'Clear selected stops',exact:true}));assert.equal((await snapshot()).modelStations.length,0);
const trainAcceptance=await runTrainUiAcceptance({page,panel,snapshot,visibleTap,output,pageErrors:errors,diagnostics:trainDiagnostics});
assert.equal(await sourceFingerprint(),baselineSource,'native source geometry is never rewritten by a local model');
await visibleTap(sourceVoltage.getByRole('checkbox',{name:'33 kV',exact:true}));assert.deepEqual((await snapshot()).selectedBands,[]);assert.equal((await snapshot()).matching,0);assert.equal((await assertOwnPoints(50)).length,0);
await visibleTap(sourceVoltage.getByRole('checkbox',{name:'Voltage not stated',exact:true}));assert.deepEqual((await snapshot()).selectedBands,['unknown']);assert.ok((await assertOwnPoints(50)).every(f=>f.properties.voltage==='Not stated'));
// Restore every filter before checking origin types.
for(const box of await sourceVoltage.getByRole('checkbox').all())if(!(await box.isChecked()))await visibleTap(box);
for(const origin of [repd,dc]){await open(origin,50);const s=await snapshot();assert.equal(s.origin.id,origin.id);assert.deepEqual(s.origin.at,origin.at);assert.equal(s.realConnectionsInferred,0);if(origin.type==='repd')assert.ok(s.matching>0,'full loaded source includes the known coastal stations within EA3 50 km');origins.push({type:origin.type,id:s.origin.id,at:s.origin.at,matching:s.matching} … [line shortened here: 429 characters; full line on GitHub]
await open(dc,50);
const station=(await ownData()).features.find(f=>f.properties.kind==='substation');assert.ok(station);
const realStation=await page.evaluate(at=>{const ns=window.__GRIDATLAS_MODULES__,f=window.__GRIDATLAS_V9_MAP__.getSource('src-subs').serialize().data.features.find(f=>{const p=ns.geodesy.representativePoint(f.geometry);return p&&p.every((v,i)=>v===at[i]);});return{id:String(f.id),at:ns.geodesy.representativePoint(f.geometry),name:f.properties.name||'Unnamed mapped substation'};},station.geometry. … [line shortened here: 413 characters; full line on GitHub]
await open({...realStation,type:'substation'},10);assert.equal((await snapshot()).origin.id,realStation.id);origins.push({type:'substation',...realStation,matching:(await snapshot()).matching});
// Native result control supplies the actual station's coordinates, without a nearest-identity guess.
const recenter=panel.locator('.vic-results').getByRole('button',{name:/^Use .+ as origin$/}).first();await visibleTap(recenter);assert.equal((await snapshot()).origin.type,'substation');
await visibleTap(close);assert.equal(await page.evaluate(()=>!!window.__GRIDATLAS_V9_MAP__.getSource('gridatlas-vicinity-context')),false);
const grid=page.locator('#gridatlas-menu-bar-title-4');await grid.tap();const nativeLaunch=page.locator('#gridatlas-menu-bar-panel-4 [data-vicinity-group]').getByRole('button',{name:/^Explore nearby grid/});await visibleTap(nativeLaunch);assert.equal((await snapshot()).opened,true);await visibleTap(close);assert.equal(await grid.evaluate(e=>e===document.activeElement&&e.getClientRects().length>0) … [line shortened here: 407 characters; full line on GitHub]
await open(dc,10);
// Keep both orientations inside the same native map lifecycle. Exit browser Fullscreen API
// before Chromium's window resize because Windows rejects Browser.setWindowBounds while fullscreen.
const exitedFullscreen=await page.evaluate(async()=>{if(document.fullscreenElement){await document.exitFullscreen();return true;}return false;});
for(const [width,height]of[[393,852],[852,393]]){
await page.setViewportSize({width,height});await page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.resize());
const layout=await panel.evaluate(e=>{const p=e.getBoundingClientRect();return{x:p.x,y:p.y,width:p.width,height:p.height,overflow:document.documentElement.scrollWidth>innerWidth};});
assert.ok(layout.x>=0&&layout.y>=0&&layout.x+layout.width<=width+1&&layout.y+layout.height<=height+1,JSON.stringify(layout));assert.equal(layout.overflow,false);
const chrome=await page.evaluate(()=>({menu:document.getElementById('gridatlas-menu-bar')?.getBoundingClientRect().bottom||0,layers:document.getElementById('gridatlas-dash-toggle')?.getBoundingClientRect().top||innerHeight}));
const closeBounds=await close.boundingBox();assert.ok(closeBounds.y>=chrome.menu,'the entire Close touch target clears the native menu');assert.ok(layout.y+layout.height<=chrome.layers,'vicinity panel clears native Layers including its docked-card lift');
await visibleTap(close);await page.locator('.vic-launch').tap();assert.equal((await snapshot()).opened,true);
if(!(await snapshot()).origin){await visibleTap(page.getByRole('button',{name:'Use map centre',exact:true}));assert.equal((await snapshot()).origin.type,'map-centre');await open(dc,10);}
await page.screenshot({path:path.join(output,'vicinity-'+width+'x'+height+'.png')});layouts.push({width,height,layout,chrome,closeBounds});
if(height<480){
await visibleTap(close);await page.evaluate(()=>window.__GRIDATLAS_MODULES__.gridJourneyPreview.open());
const journey=page.locator('#gridatlas-gj03');await visibleTap(journey.getByRole('button',{name:'Load SYNTHETIC demonstration',exact:true}));await journey.getByRole('combobox',{name:'Explicit starting node'}).selectOption('A1');
await page.waitForFunction(()=>window.__GRIDATLAS_MODULES__.gridJourneyPreview.snapshot().steps===8,null,{timeout:30000});
await visibleTap(journey.getByRole('button',{name:'Next',exact:true}));await visibleTap(journey.getByRole('button',{name:'Reset',exact:true}));assert.equal(await page.evaluate(()=>window.__GRIDATLAS_MODULES__.gridJourneyPreview.snapshot().step),0);
await visibleTap(journey.getByRole('button',{name:'Close Grid Journey',exact:true}));await open(dc,10);
}
}
// Malformed input is explicit, then a native map-centre action recovers without invented identity.
await page.evaluate(()=>window.__GRIDATLAS_MODULES__.gridVicinity.open({origin:{at:[0,0],id:'bad',type:'repd'},radiusKm:10}));assert.equal((await snapshot()).origin,null);assert.equal((await snapshot()).matching,null);assert.equal(await ownData(),undefined);assert.match(await page.locator('.vic-error').innerText(),/valid located origin/);
await visibleTap(page.getByRole('button',{name:'Use map centre',exact:true}));assert.equal((await snapshot()).origin.type,'map-centre');assert.equal((await snapshot()).origin.id,null);
// Optional news failures degrade independently; the valid physical origin stays useful.
await page.evaluate(o=>window.__GRIDATLAS_MODULES__.gridVicinity.open(o),{origin:dc,radiusKm:10,newsContextUrl:'https://globalgrid2050.com/uk_renewables_pipeline/202611171940/',newsTopic:'datacentre'});
const goodNews=new URL((await snapshot()).newsHref);assert.equal(goodNews.searchParams.get('news_origin_id'),dc.id);assert.equal(goodNews.hash,'#headlinesHeading');
await page.evaluate(o=>window.__GRIDATLAS_MODULES__.gridVicinity.open(o),{origin:dc,radiusKm:10,newsContextUrl:'https://evil.example/not-allowed/',newsTopic:'grid'});
assert.equal((await snapshot()).origin.id,dc.id);assert.equal((await snapshot()).phase,'READY');assert.equal((await snapshot()).newsHref,null);assert.ok((await snapshot()).matching>0);
await page.evaluate(options=>window.__GRIDATLAS_MODULES__.gridVicinity.open(options),parseVicinityIntent('?journey=vicinity&radius_km=10'));assert.equal((await snapshot()).phase,'CHOOSE_ORIGIN');assert.equal((await snapshot()).origin,null);assert.equal(await ownData(),undefined);
await visibleTap(page.getByRole('button',{name:'Use map centre',exact:true}));assert.equal((await snapshot()).phase,'READY');assert.equal((await snapshot()).origin.type,'map-centre');
// The same controller handles explicit events; opaque IDs are retained, never interpreted as topology.
await page.evaluate(()=>window.dispatchEvent(new CustomEvent('gridatlas:vicinity-open',{detail:{origin:{at:[-0.1,51.5],type:'datacentre',id:'DC-WD-Q',name:'Opaque producer contract fixture'},radiusKm:10}})));assert.equal((await snapshot()).origin.id,'DC-WD-Q');
// Existing source and layer collisions remain byte/object-identical through close and destroy.
await visibleTap(close);
await page.evaluate(()=>{const m=window.__GRIDATLAS_V9_MAP__;m.addSource('vicinity-independent-foreign',{type:'geojson',data:{type:'FeatureCollection',features:[]}});m.addLayer({id:'gridatlas-vicinity-radius',type:'line',source:'vicinity-independent-foreign'});window.__vicinityForeign=m.getLayer('gridatlas-vicinity-radius');});
await open(dc,10);assert.equal((await snapshot()).sourceUnavailable,true);assert.equal(await page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.getLayer('gridatlas-vicinity-radius')===window.__vicinityForeign),true);await visibleTap(close);assert.equal(await page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.getLayer('gridatlas-vicinity-radius')===window.__vicinityForeign),true);
await page.evaluate(()=>{const m=window.__GRIDATLAS_V9_MAP__;m.removeLayer('gridatlas-vicinity-radius');m.removeSource('vicinity-independent-foreign');});
await open(dc,10);await page.evaluate(()=>window.__GRIDATLAS_MODULES__.gridVicinity.destroy());assert.equal(await page.locator('#gridatlas-vicinity').count(),0);assert.equal(await page.locator('[data-vicinity-group]').count(),0);
const finalLayers=await page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.getStyle().layers.map(l=>l.id));assert.ok(baselineLayers.every(id=>finalLayers.includes(id)),'all inherited native layers remain');assert.equal(await sourceFingerprint(),baselineSource);
await page.evaluate(()=>window.__GRIDATLAS_MODULES__.gridVicinity.mount().open({origin:{at:[-0.1,51.5],type:'map-centre',id:null},radiusKm:1}));assert.equal((await snapshot()).opened,true);await page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.remove());assert.equal((await snapshot()).alive,false);assert.equal(await page.locator('#gridatlas-vicinity').count(),0);
// Span the inherited 1000ms selection poll: immediate assertions miss queued teardown work.
await page.waitForTimeout(1200);
assert.deepEqual(errors,[]);await Promise.all(responseReads);
if(!injecting){const served=runtimeResponses.find(r=>r.url.endsWith('/atlas/modules/'+generation+'-grid-vicinity.js'));assert.ok(served,'browser actually received candidate module');assert.equal(served.sha256,compiled.sha256);assert.equal(served.bytes,compiled.bytes);}
const actualModule=injecting?compiled.body:fs.readFileSync(path.join(atlasRoot,'atlas/modules/'+generation+'-grid-vicinity.js'),'utf8').replace(/\r\n/g,'\n');
const receipt={result:'PASS',postMapRemovalObservationMs:1200,sourceHead,coldReadyMs,runtimeResponses,trainDiagnostics,trainAcceptance,startedUTC,finishedUTC:new Date().toISOString(),mode:injecting?'CANDIDATE_MODULE_INJECTION_NOT_PUBLIC_ACCEPTANCE':'LOCAL_FULL_COMPOSITION',browser:browserName,device:browserName==='webkit'?'iPhone 13 software regression':'Pixel 7 Android touch emulation',generatio … [line shortened here: 822 characters; full line on GitHub]
fs.writeFileSync(path.join(output,'receipt.json'),JSON.stringify(receipt,null,2)+'\n');console.log(JSON.stringify({result:'PASS',output,generation,matching:initial.matching,loaded:initial.loadedRecords}));
}catch(e){if(page)await page.screenshot({path:path.join(output,'failure.png')}).catch(()=>{});fs.writeFileSync(path.join(output,'failure.json'),JSON.stringify({sourceHead,generation,candidateSha:compiled.sha256,trainDiagnostics,runtimeResponses,lastTouchDiagnostic,error:e.message,stack:e.stack,errors,failed,snapshot:page?await snapshot().catch(()=>null):null},null,2));throw e;}
finally{await browser?.close();await new Promise(resolve=>server.close(resolve));}Build
A JavaScript module in the vicinity folder of GridAtlas that reads station, using SHA-256.
storagegridatlas / tools/vicinity/build.mjs · lines 1–27 of 27 · pattern assemble (shared by 13 files)
- What it does
- It loads station. Defines assemble, read, trainRead. Uses libraries node:fs, node:path, node:url, node:crypto. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. README: "`build.mjs` deterministically assembles `src/model.mjs`, `src/bootstrap.js` and `src/vicinity.css` into one bounded module."
- Inputs & outputs
- In: JSON file station-source.json; command-line arguments.
- Downstream impact
- Used directly by 4 files: Cut Grid Explorer (gridatlas); Grid Explorer Proof (gridatlas); Browser Test (gridatlas); Model Test (gridatlas). Reached from 1 other entry point, including GridAtlas PR File Size Guard Workflow (gridatlas).
- What it achieves
- It is built from the assemble step (`assemble`), the read step (`read`) and the train read helper (`trainRead`). The README says: `build.mjs` deterministically assembles `src/model.mjs`, `src/bootstrap.js` and `src/vicinity.css` into one bounded module.
- Why it matters
- Run by Cut Grid Explorer and Grid Explorer Proof. Checked by 2 tests, including Browser Test.
- Application
- gridatlas · tools/vicinity · JavaScript module
- Uses
- node:fs, node:path, node:url, node:crypto
- Used by
- run by Cut Grid Explorer (script call), run by Grid Explorer Proof (script call), run by Browser Test (script call), imported by Model Test (import)
- Produces
- ROOT, BUDGET, assemble
- Defines here
- assemble, read, trainRead
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/vicinity/build.mjs:1-27 · blob 920d87e11ca9179212671a82b5bae2f458a2d7c9 · GitHub at these lines
- State
- achieves: readme · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import fs from 'node:fs';
import path from 'node:path';
import {fileURLToPath} from 'node:url';
import {createHash} from 'node:crypto';
export const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
// Native journey search, law and motion remain a small additive module within the 500k repository ceiling.
export const BUDGET = 140000;
export function assemble({root = ROOT, generation = 'UNRELEASED'} = {}) {
if (!/^(?:UNRELEASED|\d{12})$/.test(generation)) throw new Error('Invalid generation');
const read = p => fs.readFileSync(path.join(root, 'tools/vicinity', p), 'utf8').replace(/\r\n/g, '\n');
const model = read('src/model.mjs').replace(/^export /gm, '');
const adapters = [['asset-context.mjs', 'collectAssetContext'], ['document-context.mjs', 'documentContextFor']].map(([file, api]) =>
`const ${api} = (() => {\n${read('src/' + file).replace(/^export /gm, '')}\nreturn ${api};\n})();`).join('\n');
const trainRead = file => fs.readFileSync(path.join(root,'tools/train',file),'utf8').replace(/\r\n/g,'\n').replace(/^import .*;\s*$/gm,'').replace(/^export /gm,'');
const train = `const TRAIN_STATION_SOURCE_PIN=${JSON.stringify(JSON.parse(fs.readFileSync(path.join(root,'tools/train/station-source.json'),'utf8')))};\nconst TrainCore=(()=>{\n${['src/station-index.mjs','src/scenario-stations.mjs','src/itinerary.mjs','src/place-bridge.mjs','src/route-plan.mjs','src/train-motion.mjs','fixtures/learning-networks.mjs'].map(trainRead).join('\n')}\nreturn {buildStat … [line shortened here: 575 characters; full line on GitHub]
const body = `/* GridAtlas vicinity ${generation}: source-built spatial context, no inferred circuits. */\n(() => {\n'use strict';\nconst VICINITY_GENERATION=${JSON.stringify(generation)};\nconst VICINITY_CSS=${JSON.stringify(read('src/vicinity.css'))};\n${model}\n${adapters}\n${train}\n${read('src/bootstrap.js')}\n})();\n`;
if (Buffer.byteLength(body) > BUDGET) throw new Error(`Vicinity module exceeds ${BUDGET} bytes`);
return {body, bytes: Buffer.byteLength(body), sha256: createHash('sha256').update(body).digest('hex')};
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const args = process.argv.slice(2), option = key => { const i = args.indexOf(key); return i < 0 ? undefined : args[i + 1]; };
const generation = option('--generation') || 'UNRELEASED', output = option('--out');
const result = assemble({generation});
if (output) { fs.mkdirSync(path.dirname(path.resolve(output)), {recursive: true}); fs.writeFileSync(output, result.body); }
console.log(JSON.stringify({generation, bytes: result.bytes, sha256: result.sha256, output: output || null}));
}