GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / gridatlas / tools/satnav/field-reliability

Offline Plan and 8 more files

A JavaScript module in the field reliability folder of GridAtlas that formats distance (`formatDistance`), shows pin (`showPin`) and draws SVG graphics. It formats distance (`formatDistance`) and shows pin (`showPin`).

651 lines of Python and JavaScript from gridatlas, in 9 files. Topic: Maps, GIS and field navigation. Section 673 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. Offline Plan interaction · gridatlas / tools/satnav/field-reliability/offline-plan.mjs lines 1–179
  2. State transform · gridatlas / tools/satnav/field-reliability/state.mjs lines 1–17
  3. State Test test · gridatlas / tools/satnav/field-reliability/state.test.mjs lines 1–33
  4. SatNav G203 04 Saved Plan Test test · gridatlas / tools/satnav/g203-04-saved-plan.test.mjs lines 1–55
  5. SatNav G203 Dock Browser render · gridatlas / tools/satnav/g203-dock-browser.py lines 1–156
  6. SatNav G203 Soak interaction · gridatlas / tools/satnav/g203-soak.py lines 1–48
  7. SatNav G203 Swarm 05 Offline Browser render · gridatlas / tools/satnav/g203-swarm-05-offline-browser.py lines 1–119
  8. SatNav G203 Verify Composition ingest · gridatlas / tools/satnav/g203-verify-composition.mjs lines 1–12
  9. SatNav G203 Viewport Browser render · gridatlas / tools/satnav/g203-viewport-browser.py lines 1–32

Offline Plan

A JavaScript module in the field reliability folder of GridAtlas that formats distance (`formatDistance`), shows pin (`showPin`) and draws SVG graphics. It formats distance (`formatDistance`) and shows pin (`showPin`).

interactiongridatlas / tools/satnav/field-reliability/offline-plan.mjs · lines 1–179 of 179 · Not reached from any entry point (candidate for review) · pattern offlinePlanDocument (shared by 2 files)

What it does
It draws its content. Defines 11 functions or classes, including fieldPlan, displayPlan, byId, formatDistance, showPin. Side effects: changes the web page (DOM); uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage field_execution (path word 'field'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Inputs & outputs
Out: SVG drawing.
What it achieves
Saves the planned pins on this device only, after the user presses Save. It responds to statechange events.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · tools/satnav/field-reliability · JavaScript module
VEDIC
SAVE OFFLINE PLAN (GG2050-VEDIC-000100): SatNav · Location and navigation data. DOM container, selected pins callback, distance and bearing functions, secure browser with service worker and Cache Storage → Offline plan controls and a locally cached standalone HTML plan after the user presses Save.
Uses
none found
Used by
none found
Produces
offlinePlanDocument, mountOfflinePlan
Defines here
fieldPlan, displayPlan, byId, formatDistance, showPin, offlinePlanDocument, activateWorker, finish, cleanup, mountOfflinePlan, change
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/satnav/field-reliability/offline-plan.mjs:1-179 · blob 47497dbdc4416d4b90905372f466f72da3164a74 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, storage · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unreached_review
// SPDX-License-Identifier: Apache-2.0
// Saves the planned pins on this device only, after the user presses Save.
const cacheName = 'ventus-satnav-offline-plans-v1';

function fieldPlan(pins, maths) {
  if (!Array.isArray(pins) || pins.length < 2 || pins.length > 20000) {
    throw new Error('Choose between 2 and 20,000 plan pins before saving.');
  }
  const coordinates = pins.map(pin => {
    const at = pin?.coordinate ?? pin;
    if (!Array.isArray(at) || at.length !== 2 || !at.every(Number.isFinite)
        || Math.abs(at[0]) > 180 || Math.abs(at[1]) > 90) {
      throw new Error('A plan pin has invalid coordinates.');
    }
    return [at[0], at[1]];
  });
  let totalM = 0;
  const legs = coordinates.slice(1).map((to, i) => {
    const from = coordinates[i];
    const metres = maths.distanceKm(...from, ...to) * 1000;
    const bearing = metres > 0 ? maths.initialBearingDeg(...from, ...to) : null;
    if (!Number.isFinite(metres) || metres < 0 || (bearing !== null && !Number.isFinite(bearing))) {
      throw new Error('Unable to measure the selected plan.');
    }
    totalM += metres;
    return [Math.round(metres), bearing === null ? null : (Math.round(bearing) + 360) % 360];
  });
  return {coordinates, legs, totalM: Math.round(totalM), savedAt: new Date().toISOString()};
}

// This function is embedded in the saved HTML so it can run without a network or dependencies.
function displayPlan() {
  const plan = JSON.parse(document.getElementById('saved-plan').textContent);
  const points = plan.coordinates;
  const byId = id => document.getElementById(id);
  const formatDistance = m => m < 1000 ? m + ' m' : (m / 1000).toLocaleString('en-GB', {maximumFractionDigits: 2}) + ' km';
  const scope = new URL('./', location.href);
  const previous = byId('previous'), next = byId('next');
  let index = 0;
  let x = points[0][0];
  const projected = points.map(([lng, lat], i) => {
    if (i) x += ((lng - points[i - 1][0] + 540) % 360) - 180;
    return [x, lat];
  });
  let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
  for (const [lng, lat] of projected) {
    minX = Math.min(minX, lng); maxX = Math.max(maxX, lng);
    minY = Math.min(minY, lat); maxY = Math.max(maxY, lat);
  }
  const cos = Math.max(0.000001, Math.cos((minY + maxY) * Math.PI / 360));
  const scaleX = (maxX - minX) * cos;
  const scaleY = maxY - minY;
  const scale = Math.min(scaleX ? 284 / scaleX : Infinity, scaleY ? 150 / scaleY : Infinity);
  const factor = Number.isFinite(scale) ? scale : 1;
  const chart = projected.map(([lng, lat]) => [
    +(160 + (lng - (minX + maxX) / 2) * cos * factor).toFixed(2),
    +(90 - (lat - (minY + maxY) / 2) * factor).toFixed(2),
  ]);
  byId('line').setAttribute('points', chart.map(p => p.join(',')).join(' '));
  byId('summary').textContent = points.length.toLocaleString('en-GB') + ' pins · ' + formatDistance(plan.totalM) + ' planned';
  byId('saved-at').textContent = 'Saved ' + new Date(plan.savedAt).toLocaleString('en-GB');
  function showPin() {
    const [lng, lat] = points[index], leg = plan.legs[index];
    byId('pin').textContent = 'Pin ' + (index + 1) + ' of ' + points.length;
    byId('coordinate').textContent = lat.toFixed(5) + '°, ' + lng.toFixed(5) + '°';
    byId('leg').textContent = leg
      ? 'To next pin: ' + formatDistance(leg[0]) + (leg[1] === null ? '' : ' · ' + leg[1] + '° true')
      : 'Last planned pin';
    byId('marker').setAttribute('cx', chart[index][0]);
    byId('marker').setAttribute('cy', chart[index][1]);
    previous.disabled = index === 0; next.disabled = index === points.length - 1;
  }
  previous.onclick = () => { if (index > 0) index--; showPin(); };
  next.onclick = () => { if (index < points.length - 1) index++; showPin(); };
  byId('reload').onclick = () => location.reload();
  byId('forget').onclick = async () => {
    try {
      const cache = await caches.open('ventus-satnav-offline-plans-v1');
      await cache.delete(new URL('__saved-field-plan__', scope));
      const message = document.createElement('p');
      message.textContent = 'Saved plan removed from this device.';
      document.querySelector('main').replaceChildren(message, byId('reload'));
    } catch {
      byId('saved-at').textContent = 'Could not remove the saved plan. Try again.';
    }
  };
  showPin();
}

export function offlinePlanDocument(pins, maths) {
  const data = fieldPlan(pins, maths);
  // Only validated number pairs, measured legs and our own ISO date reach the data element.
  return `<!doctype html><html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1"><title>Saved field plan · Ventus SatNav</title>
<style>
*{box-sizing:border-box}body{margin:0;background:#07151a;color:#e4f6f7;font:1rem/1.45 system-ui,sans-serif}
main{max-width:40rem;margin:auto;padding:1rem}h1{margin:.4rem 0}p{margin:.5rem 0}svg{display:block;width:100%;max-height:38vh;border:1px solid #48777c;border-radius:.5rem;background:#0a2026}
button{min-height:44px;margin:.2rem .25rem .2rem 0;padding:.35rem .85rem;color:inherit;background:#123239;border:1px solid #56868a;border-radius:.4rem;font:inherit}
button:focus-visible{outline:2px solid white}button:disabled{opacity:.48}small{color:#b1ced0}footer{margin-top:.8rem}
</style></head><body><main><h1>Saved field plan</h1><p id="summary"></p>
<svg viewBox="0 0 320 180" role="img" aria-label="North-up diagram of the planned pins"><polyline id="line" fill="none" stroke="#58d9e3" stroke-width="2.5"/><circle id="marker" r="5.5" fill="#ffdc73" stroke="#07151a" stroke-width="2"/></svg>
<p><small>Planned straight lines · North up · GPS off</small></p>
<section aria-live="polite"><strong id="pin"></strong><p id="coordinate"></p><p id="leg"></p></section>
<button id="previous" type="button">Previous pin</button><button id="next" type="button">Next pin</button>
<footer><p><small id="saved-at"></small></p><button id="reload" type="button">Reopen live map</button><button id="forget" type="button">Forget saved plan</button>
<p><small>Check access rights, restrictions and safe working arrangements before entering land.</small></p></footer>
</main><script type="application/json" id="saved-plan">${JSON.stringify(data)}</script>
<script>(${displayPlan.toString()})()</script></body></html>`;
}

async function activateWorker(scope) {
  const workerURL = new URL('../satnav-offline-plan-202611281315-worker.js', scope);
  const previousWorkerURL = new URL('../satnav-offline-plan-20261128-worker.js', scope);
  const existing = await navigator.serviceWorker.getRegistration(scope);
  if (existing?.scope === scope.href) {
    for (const worker of [existing.active, existing.installing, existing.waiting]) {
      if (worker && worker.scriptURL !== workerURL.href && worker.scriptURL !== previousWorkerURL.href) throw new Error('This version uses a different offline map.');
    }
    if (existing.active?.state === 'activated' && existing.active.scriptURL === workerURL.href) return;
  }
  const registration = await navigator.serviceWorker.register(workerURL, {scope: scope.pathname});
  const worker = registration.installing || registration.waiting || registration.active;
  if (!worker) throw new Error('Offline access did not start. Try again while online.');
  if (worker.state === 'activated') return;
  await new Promise((resolve, reject) => {
    const finish = () => {
      if (worker.state === 'activated') { cleanup(); resolve(); }
      if (worker.state === 'redundant') { cleanup(); reject(new Error('Offline access could not start.')); }
    };
    const cleanup = () => { clearTimeout(timeout); worker.removeEventListener('statechange', finish); };
    const timeout = setTimeout(() => { cleanup(); reject(new Error('Offline access timed out. Try again.')); }, 15000);
    worker.addEventListener('statechange', finish);
    finish();
  });
}

export function mountOfflinePlan({container, getPins, maths}) {
  const scope = new URL('./', location.href);
  if (!/\/atlas\/v\/satnav-[\w.-]+\/$/.test(scope.pathname)) throw new Error('A versioned SatNav entry is required.');
  const key = new URL('__saved-field-plan__', scope);
  const area = document.createElement('details');
  area.innerHTML = '<summary>Offline plan</summary><p>Save selected pins on this device for offline reading.</p><button type="button">Save plan</button> <button type="button">Forget saved plan</button><p role="status"></p>';
  const [save, forget] = area.querySelectorAll('button');
  const status = area.querySelector('[role="status"]');
  container.append(area);
  if (!window.isSecureContext || !('serviceWorker' in navigator) || !('caches' in window)) {
    save.disabled = forget.disabled = true;
    status.textContent = 'Offline saving is unavailable in this browser.';
    return area;
  }

  async function change(action) {
    save.disabled = forget.disabled = true;
    try {
      if (action === 'save') {
        const html = offlinePlanDocument(getPins(), maths);
        await activateWorker(scope);
        const cache = await caches.open(cacheName);
        await cache.put(key, new Response(html, {headers: {
          'Content-Type': 'text/html; charset=utf-8',
          'Content-Security-Policy': "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'",
          'Cache-Control': 'no-store',
        }}));
        status.textContent = 'Saved. Reopen this map address offline to read the plan.';
      } else {
        const cache = await caches.open(cacheName);
        await cache.delete(key);
        status.textContent = 'Saved plan removed from this device.';
      }
    } catch (error) {
      status.textContent = error?.message || 'Could not change the saved plan on this device.';
    } finally {
      save.disabled = forget.disabled = false;
    }
  }
  save.onclick = () => change('save');
  forget.onclick = () => change('forget');
  return area;
}

State

A JavaScript module in the field reliability folder of GridAtlas. It is built from the assess field state helper (`assessFieldState`).

transformgridatlas / tools/satnav/field-reliability/state.mjs · lines 1–17 of 17

What it does
It calculates its inputs. Defines assessFieldState.
Why it exists in the grid workflow
Domain stage field_execution (path word 'field'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Downstream impact
Used directly by 1 file: State Test (gridatlas). Reached from 1 other entry point, including GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
Pure field-state adapter: no watch, cache, DOM, or permission side effects.
Why it matters
Checked by State Test.
Application
gridatlas · tools/satnav/field-reliability · JavaScript module
Uses
none found
Used by
imported by State Test (import)
Produces
assessFieldState
Defines here
assessFieldState
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/satnav/field-reliability/state.mjs:1-17 · blob 65be28ceecca12c214fac0595f1599b935653d9f · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
// Pure field-state adapter: no watch, cache, DOM, or permission side effects.
// Inject pinned SatNav compass fixQuality. resumedAt is the epoch ms of foreground resumption.
// verifiedOfflineResources must mean an independently verified complete resource set, not navigator.onLine.
export function assessFieldState({tracking=false,hidden=false,resumedAt=null,fix=null,now=Date.now(),networkOnline=null,verifiedOfflineResources=false,permissionDenied=false}={},fixQuality){
  if(typeof fixQuality!=="function")throw new TypeError("canonical fixQuality required");
  if(!Number.isFinite(now)|| (resumedAt!==null&&!Number.isFinite(resumedAt)))throw new TypeError("invalid clock");
  const offline=networkOnline===false;
  const mapAvailability=offline?(verifiedOfflineResources===true?"verified-cache":"offline-unverified"):"not-verified";
  const quality=fixQuality(fix,now);
  let gpsState;
  if(permissionDenied)gpsState="denied";
  else if(!tracking)gpsState="stopped";
  else if(hidden)gpsState="background";
  else if(resumedAt!==null&&(!fix||!Number.isFinite(fix.timestampMs)||fix.timestampMs<resumedAt))gpsState="awaiting-resume-fix";
  else gpsState=quality;
  return {gpsState,showMeasuredFix:!hidden&&tracking&&!permissionDenied&&["usable","poor"].includes(gpsState),canGuide:gpsState==="usable",mapAvailability};
}

State Test

A test in the field reliability folder of GridAtlas that checks State. It runs tests (`runTests`).

testgridatlas / tools/satnav/field-reliability/state.test.mjs · lines 1–33 of 33 · Entry point · pattern runTests (shared by 7 files)

What it does
It tests its inputs. Defines runTests. Uses libraries node:url, node:path.
Why it exists in the grid workflow
Domain stage field_execution (path word 'field'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Inputs & outputs
In: command-line arguments.
Downstream impact
Used directly by 1 file: GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
Defines `runTests`.
Why it matters
Run by GridAtlas PR File Size Guard Workflow.
Application
gridatlas · tools/satnav/field-reliability · test
Uses
State (import), node:url, node:path
Used by
run by GridAtlas PR File Size Guard Workflow (workflow run)
Produces
runTests
Defines here
runTests
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/satnav/field-reliability/state.test.mjs:1-33 · blob 3d6b6d88b61185de457abc9ee79be8741a02f15b · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
// Run with Node; pass a local copy of the exact pinned compass module as first argument.
import {pathToFileURL} from 'node:url';
import {resolve} from 'node:path';
import {assessFieldState} from './state.mjs';
function runTests(assess,quality){
 const fix={longitude:0,latitude:51,accuracyM:8,timestampMs:10000};
 const base={tracking:true,fix,now:10500};
 const cases=[
 ["usable",{}, "usable",true,true,"not-verified"],
 ["poor",{fix:{...fix,accuracyM:31}},"poor",true,false,"not-verified"],
 ["stale",{now:20001},"stale",false,false,"not-verified"],
 ["future",{now:9999},"stale",false,false,"not-verified"],
 ["invalid",{fix:{...fix,latitude:91}},"invalid",false,false,"not-verified"],
 ["missing",{fix:null},"missing",false,false,"not-verified"],
 ["stopped",{tracking:false},"stopped",false,false,"not-verified"],
 ["denied",{permissionDenied:true},"denied",false,false,"not-verified"],
 ["hidden",{hidden:true},"background",false,false,"not-verified"],
 ["resume old",{resumedAt:10100},"awaiting-resume-fix",false,false,"not-verified"],
 ["resume fresh",{resumedAt:10000},"usable",true,true,"not-verified"],
 ["resume poor",{resumedAt:10000,fix:{...fix,accuracyM:31}},"poor",true,false,"not-verified"],
 ["offline GPS independent",{networkOnline:false},"usable",true,true,"offline-unverified"],
 ["verified cache",{networkOnline:false,verifiedOfflineResources:true},"usable",true,true,"verified-cache"],
 ["online not proof",{networkOnline:true,verifiedOfflineResources:true},"usable",true,true,"not-verified"]
 ];
 for(const [name,over,gpsState,showMeasuredFix,canGuide,mapAvailability] of cases){
 const actual=assess({...base,...over},quality),expected={gpsState,showMeasuredFix,canGuide,mapAvailability};
 if(JSON.stringify(actual)!==JSON.stringify(expected))throw new Error(name+": "+JSON.stringify(actual));
 }
 return cases.length;
}
if(!process.argv[2])throw new Error('Supply local pinned SatNav nav/compass.mjs path');
const {fixQuality}=await import(pathToFileURL(resolve(process.argv[2])).href);
console.log(runTests(assessFieldState,fixQuality)+' field state cases passed');

SatNav G203 04 Saved Plan Test

A test in the tools folder of GridAtlas that checks G203 04 SatNav Walk Saved Plan. It is built from the fixture step (`fixture`).

testgridatlas / tools/satnav/g203-04-saved-plan.test.mjs · lines 1–55 of 55 · Entry point · pattern fixture (shared by 30 files)

What it does
It tests its inputs. Defines fixture. Uses libraries node:test, node:assert/strict, node:fs, node:vm. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Downstream impact
Used directly by 1 file: GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
G203-04: actual cartridge source executed in a small mocked browser; real browser acceptance separate.
Why it matters
Run by GridAtlas PR File Size Guard Workflow.
Application
gridatlas · tools/satnav · test
Uses
G203 04 SatNav Walk Saved Plan (new URL import.meta.url), node:test, node:assert/strict, node:fs, node:vm
Used by
run by GridAtlas PR File Size Guard Workflow (workflow run)
Produces
fixture
Defines here
fixture
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/satnav/g203-04-saved-plan.test.mjs:1-55 · blob cd10a1e3642b1e080d0864757d146a1bc4f07e66 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
// G203-04: actual cartridge source executed in a small mocked browser; real browser acceptance separate.
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import {runInNewContext} from 'node:vm';
const source = readFileSync(new URL('../../atlas/modules/20261202-g203-04-satnav-walk-saved-plan.js', import.meta.url), 'utf8');
// This file lives at tools/satnav; resolve from that directory, not cwd.
function fixture(path, secure = true) {
  const controls = [{disabled:false}, {disabled:false,before(el){controls.push(el);}}];
  const status={textContent:''}, notices=[], events=new Map(), storage=new Map();
  const area={querySelectorAll:()=>controls,querySelector:()=>status,set innerHTML(value){}};
  let pins=[{coordinate:[0,51]},{coordinate:[0.001,51]}], restores=0, observerCount=0, workerCalls=0;
  const scope=new URL('./','https://example.test'+path);
  const survey={getPins:()=>pins,maths:{distanceKm:()=>0.07,initialBearingDeg:()=>90},replacePlan(at){restores++;pins=at.map(coordinate=>({coordinate}));}};
  const document={
    getElementById:id=>id==='satnav-field-tools'?{append:el=>notices.push(el)}:{satnavSurvey:survey},
    addEventListener:(name,fn)=>events.set(name,fn),removeEventListener:name=>events.delete(name),
    createElement(tag){
      if(tag==='details') return area;
      if(tag==='template') return {set innerHTML(value){this.content={querySelector:()=>({textContent:value.match(/<script type="application\/json" id="saved-plan">([\s\S]*?)<\/script>/)[1]})};}};
      return {setAttribute(){},textContent:'',disabled:false};
    }
  };
  const cache={put:async(key,value)=>storage.set(String(key),value),delete:async key=>storage.delete(String(key))};
  const caches={open:async()=>cache,match:async key=>storage.get(String(key))?.clone()};
  const navigator={serviceWorker:{getRegistration:async()=>undefined,register:async(url,opts)=>{
    workerCalls++;assert.equal(url.href,new URL('../satnav-offline-plan-202611281315-worker.js',scope).href);assert.equal(opts.scope,scope.pathname);
    return {active:{state:'activated'}};
  }}};
  runInNewContext(source,{URL,Response,document,location:{href:scope.href},navigator,window:{isSecureContext:secure,caches},caches,
    MutationObserver:class{observe(){observerCount++;}},console:{error(){}}});
  return {controls,status,notices,area,storage,scope,events,stats:()=>({restores,observerCount,workerCalls})};
}
test('numbered and legacy immutable entry mount; invalid scope refuses',()=>{
  for(const path of ['/gridatlas/atlas/v/202612020056/','/gridatlas/atlas/v/202612020205/','/gridatlas/atlas/v/202612020901/','/gridatlas/atlas/v/satnav-test/']){
    const f=fixture(path);assert.equal(f.notices[0],f.area);assert.equal(f.controls.length,3);assert.equal(f.stats().observerCount,1);assert.equal(f.events.has('satnav:ready'),false);
  }
  for(const path of ['/gridatlas/atlas/','/gridatlas/atlas/v/not-version/','/gridatlas/atlas/v/20261202020/']){
    const f=fixture(path);assert.notEqual(f.notices[0],f.area);assert.equal(f.stats().observerCount,0);
  }
});
test('explicit save, restore and forget use this release key and never auto-restore',async()=>{
  const f=fixture('/gridatlas/atlas/v/202612020901/');
  assert.equal(f.stats().restores,0);assert.equal(f.stats().workerCalls,0);
  const [save,forget,restore]=f.controls;
  await save.onclick();assert.equal(f.stats().workerCalls,1);assert.equal(f.storage.size,1);
  assert.ok(f.storage.has(new URL('__saved-field-plan__',f.scope).href));
  await restore.onclick();assert.equal(f.stats().restores,1);assert.match(f.status.textContent,/Saved plan loaded/);
  await forget.onclick();assert.equal(f.storage.size,0);
  await restore.onclick();assert.match(f.status.textContent,/No saved plan/);assert.equal(f.stats().restores,1);
});
test('insecure context degrades without worker or restoration',()=>{
  const f=fixture('/gridatlas/atlas/v/202612020901/',false);
  assert.ok(f.controls.every(c=>c.disabled));assert.equal(f.stats().workerCalls,0);assert.equal(f.stats().restores,0);
});

SatNav G203 Dock Browser

A Python command-line tool in the tools folder of GridAtlas that opens map (`open_map`).

rendergridatlas / tools/satnav/g203-dock-browser.py · lines 1–156 of 156 · Entry point · pattern diagnostic (shared by 2 files)

What it does
It lists and searches its content. Defines open_map, diagnostic, historical, row_ok, run. Uses libraries os, json, re, pathlib, runpy. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Downstream impact
Used directly by 1 file: GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
It is built from the diagnostic step (`diagnostic`), the historical step (`historical`) and the row ok helper (`row_ok`). G203-01 real-map dock comparison; injected layout is not a published release.
Why it matters
Run by GridAtlas PR File Size Guard Workflow.
Application
gridatlas · tools/satnav · Python CLI
Uses
os, json, re, pathlib, runpy, playwright.sync_api
Used by
run by GridAtlas PR File Size Guard Workflow (workflow run)
Produces
open_map, diagnostic, historical, row_ok, run
Defines here
open_map, diagnostic, historical, row_ok, run
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/satnav/g203-dock-browser.py:1-156 · blob 8b9596218d532977962136d3beef3e331b53846a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
"""G203-01 real-map dock comparison; injected layout is not a published release."""
import os
import json
import re
from pathlib import Path
from runpy import run_path
from playwright.sync_api import sync_playwright, expect
ROOT=Path(__file__).resolve().parents[2]
READY=run_path(str(ROOT/'tools/satnav/convergence-browser.py'))['READY']
BASE=os.getenv('G203_TEST_ORIGIN','http://127.0.0.1:8873')
CANDIDATE=os.getenv('G203_CANDIDATE_ROUTE')
SELECTORS=['#satnav-toggle','#gridatlas-mobile-tray>button:text-matches("Grid$", "i")',
           '#gridatlas-mobile-tray>button:text-matches("Subs$", "i")','#gridatlas-dash-toggle']
VIEWS=[(320,568),(393,852),(852,393),(1440,900),(2560,1440)]
GEOMETRY="""()=>{const tray=[...document.querySelectorAll('#gridatlas-mobile-tray>button')];
const nodes=[document.getElementById('satnav-toggle'),tray.find(b=>/Grid$/i.test(b.textContent.trim())),tray.find(b=>/Subs$/i.test(b.textContent.trim())),document.getElementById('gridatlas-dash-toggle')];
return nodes.map(e=>{if(!e)return null;const r=e.getBoundingClientRect();return {label:e.textContent.trim(),x:r.x,y:r.y,w:r.width,h:r.height,hit:e.contains(document.elementFromPoint(r.x+r.width/2,r.y+r.height/2))}})}"""
INVENTORY="""()=>[...document.querySelectorAll('#gridatlas-mobile-tray>button,#gridatlas-menu-bar button,#btn-gridpoint')].map(b=>({id:b.id,label:b.textContent.trim(),parent:b.parentElement.id,hidden:b.hidden,pressed:b.getAttribute('aria-pressed'),expanded:b.getAttribute('aria-expanded'),disabled:b.disabled,rect:b.getBoundingClientRect().toJSON()}))"""
def open_map(page,route,require_dock=True):
    page.goto(BASE+route,wait_until='domcontentloaded',timeout=90000)
    page.wait_for_function(READY,timeout=120000)
    if require_dock:
        for s in SELECTORS:
            page.locator(s).wait_for(state='visible',timeout=30000)

def diagnostic(page):
    return {"url":page.url,"viewport":page.viewport_size,
            "geometry":page.evaluate(GEOMETRY),"inventory":page.evaluate(INVENTORY)}

def historical(browser,name,w,h,generation):
    with browser.new_context(viewport={'width':w,'height':h},has_touch=w<900) as ctx:
        page=ctx.new_page()
        try:
            open_map(page,'/atlas/v/'+generation+'/',require_dock=w<900)
            if w>=900:
                # Historical desktops expose the same native layer inputs through
                # the Grid menu; the mobile shortcut tray need not be visible.
                page.wait_for_function('()=>document.documentElement.classList.contains("gridatlas-menu-hosted")')
                menu=page.locator('#gridatlas-menu-bar .gm-title').filter(has_text=re.compile(r'^Grid$'))
                expect(menu).to_be_visible()
                menu.click()
                for key in ('400','subs'):
                    proxy=page.locator('[data-gridatlas-layer-proxy="engine:'+key+'"]')
                    native=page.locator('#scada-ui-container input[data-layer-id="'+key+'"]')
                    expect(proxy).to_be_visible()
                    assert native.count()==1
                    before=native.is_checked()
                    assert proxy.is_checked()==before
                    proxy.click()
                    assert native.is_checked()!=before
                    proxy.click()
                    assert native.is_checked()==before
                for selector in ('#satnav-toggle','#gridatlas-dash-toggle'):
                    expect(page.locator(selector)).to_be_visible()
            print(name,w,h,generation,'historical comparison',json.dumps(diagnostic(page)),flush=True)
        except Exception:
            print(name,w,h,generation,'historical failure',json.dumps(diagnostic(page)),flush=True)
            raise
def row_ok(rects,w,h):
    return all(r['w']>=44 and r['h']>=44 and r['x']>=0 and r['y']>=0 and
               r['x']+r['w']<=w+1 and r['y']+r['h']<=h+1 and r['hit'] for r in rects) and (
               max(r['y'] for r in rects)-min(r['y'] for r in rects)<=1 and
               all(a['x']+a['w']<=b['x']+1 for a,b in zip(rects,rects[1:])) and rects[0]['x']<w/2)
def run(browser,name,w,h):
    with browser.new_context(viewport={'width':w,'height':h},has_touch=w<900) as ctx:
        page=ctx.new_page()
        assert CANDIDATE, 'A composed candidate route is mandatory'
        try:
            open_map(page,CANDIDATE)
        except Exception:
            print(name,w,h,'candidate open failure',json.dumps(diagnostic(page)),flush=True)
            raise
        page.wait_for_function("()=>document.documentElement.hasAttribute('data-g203-compact-dock')")
        page.wait_for_function('()=>document.documentElement.classList.contains("gridatlas-menu-hosted")')
        page.wait_for_function('()=>{const a=('+GEOMETRY+')();return a.every(r=>r&&r.h>=44)&&Math.max(...a.map(r=>r.y))-Math.min(...a.map(r=>r.y))<=1}')
        rects=page.evaluate(GEOMETRY)
        print(name,w,h,'candidate geometry',json.dumps(rects),'native inventory',json.dumps(page.evaluate(INVENTORY)),flush=True)
        assert row_ok(rects,w,h), rects
        toggle=page.locator('#satnav-toggle')
        initial=toggle.get_attribute('aria-expanded')
        toggle.click()
        assert toggle.get_attribute('aria-expanded')!=initial
        toggle.click()
        assert toggle.get_attribute('aria-expanded')==initial
        # Native regional menu adopts Scope/Clear and retains hidden Tools.
        # Prove the functions remain present and operational; no child-count shortcut.
        tray=page.locator('#gridatlas-mobile-tray')
        for label in ('Grid','Subs'):
            chip=tray.locator('button').filter(has_text=re.compile(label+r'$'))
            assert chip.count()==1, (label,page.evaluate(INVENTORY))
            chip.wait_for(state='visible')
            ids=['400','275','220','132','66'] if label=='Grid' else ['subs']
            boxes=page.locator('#scada-ui-container input[data-layer-id]').evaluate_all('(a,ids)=>a.filter(b=>ids.includes(b.dataset.layerId)).map(b=>({id:b.dataset.layerId,checked:b.checked}))',ids)
            assert sorted(b['id'] for b in boxes)==sorted(ids), boxes
            ukpn=page.locator('#scada-ui-container input[data-layer-id="ukpn_secondary"]')
            assert ukpn.count()==1 and not ukpn.is_checked()
            for _ in range(2):
                expected=chip.get_attribute('aria-pressed')!='true'
                chip.click()
                assert chip.get_attribute('aria-pressed')==str(expected).lower()
                actual=page.locator('#scada-ui-container input[data-layer-id]').evaluate_all('(a,ids)=>a.filter(b=>ids.includes(b.dataset.layerId)).map(b=>b.checked)',ids)
                assert len(actual)==len(ids) and all(v==expected for v in actual), actual
                assert not ukpn.is_checked(), 'GRID/SUBS must not enable UKPN'
        menu=page.locator('#gridatlas-menu-bar')
        tools=tray.locator('button').filter(has_text=re.compile(r'^Tools'))
        assert tools.count()==1, 'original Tools control missing'
        assert menu.locator('.gm-title').count()==6, 'replacement native menus missing'
        scope_title=menu.locator('.gm-title').filter(has_text=re.compile(r'^Scope$'))
        scope_title.click()
        scope=menu.locator('button').filter(has_text=re.compile(r'◎ Scope$'))
        clear=menu.locator('button').filter(has_text=re.compile(r'✕ Clear$'))
        for control in (scope,clear,menu.locator('#btn-gridpoint')):
            assert control.count()==1
            control.wait_for(state='visible')
        initial_scope=scope.get_attribute('aria-pressed')
        scope.click()
        assert scope.get_attribute('aria-pressed')!=initial_scope
        if not scope.is_visible(): scope_title.click()
        scope.click()
        assert scope.get_attribute('aria-pressed')==initial_scope
        if not clear.is_visible(): scope_title.click()
        clear.click()
        layers=page.locator('#gridatlas-dash-toggle')
        state_js="""()=>({full:!!(document.fullscreenElement||document.webkitFullscreenElement||document.body.classList.contains('fs-active')||document.getElementById('map-container')?.classList.contains('is-fullscreen')),curtain:document.getElementById('fs-curtain')?.classList.contains('curtain-open'),collapsed:window.__GRIDATLAS_DASH__?.collapsed})"""
        before=page.evaluate(state_js)
        layers.click()
        after=page.evaluate(state_js)
        key='curtain' if before['full'] else 'collapsed'
        assert isinstance(before[key],bool) and after[key]!=before[key], (before,after)
        layers.click()
        assert page.evaluate(state_js)[key]==before[key]
        assert page.locator('#g203-native-dock #satnav-toggle').count()==1
        assert page.locator('#g203-native-dock #gridatlas-dash-toggle').count()==1
        print(name,w,h,'composed candidate geometry, semantic native controls and opt-in UKPN PASS',flush=True)
if __name__=='__main__':
    failures=[]
    with sync_playwright() as p:
        for name in os.getenv('LINE_TEST_BROWSERS','chromium,webkit').split(','):
            opts={'args':['--use-gl=angle','--use-angle=swiftshader','--enable-webgl','--enable-unsafe-swiftshader']} if name=='chromium' else {}
            browser=getattr(p,name).launch(**opts)
            try:
                for w,h in VIEWS:
                    try:
                        run(browser,name,w,h)
                    except Exception as exc:
                        failures.append((name,w,h,'candidate',str(exc)))
                        print('FAIL',failures[-1],flush=True)
                for w,h in VIEWS:
                    for generation in ('202612020056','202612020205'):
                        try:
                            historical(browser,name,w,h,generation)
                        except Exception as exc:
                            failures.append((name,w,h,generation,str(exc)))
                            print('FAIL',failures[-1],flush=True)
            finally:browser.close()
    assert not failures, failures

SatNav G203 Soak

A Python module in the tools folder of GridAtlas.

interactiongridatlas / tools/satnav/g203-soak.py · lines 1–48 of 48 · Not reached from any entry point (candidate for review)

What it does
Uses libraries os, time, json, pathlib, runpy. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work. Domain terms in the code: 11kV.
Inputs & outputs
Voltage levels named: 11kV.
What it achieves
Matched 30-minute candidate soak; simulated GPS, actual application, no auto-reload.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · tools/satnav · Python module
Uses
os, time, json, pathlib, runpy, playwright.sync_api
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
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/satnav/g203-soak.py:1-48 · blob e6a210fde0d7eddc8646a5fdeb0d2c5289043358 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unreached_review
"""Matched 30-minute candidate soak; simulated GPS, actual application, no auto-reload.
Reports page JS heap where exposed; does not measure GPU, worker or device process RAM."""
import os,time,json
from pathlib import Path
from runpy import run_path
from playwright.sync_api import sync_playwright
root=Path(__file__).resolve().parent
ready=run_path(str(root/'convergence-browser.py'))['READY']
gps=run_path(str(root/'compact-browser.py'))['GPS_SPY']
name=os.environ['G203_BROWSER'];enabled=os.environ['G203_UKPN']=='on'
site='http://127.0.0.1:8873/atlas/v/202612020930/'
with sync_playwright() as p:
    opts={'args':['--use-gl=angle','--use-angle=swiftshader','--enable-webgl','--enable-unsafe-swiftshader']} if name=='chromium' else {}
    browser=getattr(p,name).launch(**opts)
    ctx=browser.new_context(viewport={'width':393,'height':852},has_touch=True,is_mobile=True)
    ctx.add_init_script(gps)
    ctx.add_init_script("""window.__g203Soak={losses:0,restores:0};document.addEventListener('webglcontextlost',()=>window.__g203Soak.losses++,true);document.addEventListener('webglcontextrestored',()=>window.__g203Soak.restores++,true)""")
    page=ctx.new_page();crashes=[];errors=[];nav=[]
    page.on('crash',lambda:crashes.append('crash'))
    page.on('pageerror',lambda e:errors.append(str(e)))
    page.on('framenavigated',lambda f:nav.append(f.url) if f==page.main_frame else None)
    page.goto(site,wait_until='domcontentloaded',timeout=90000)
    page.wait_for_function(ready,timeout=120000)
    page.evaluate("""on=>{const s=document.querySelector('#satnav-compact').satnavSurvey,m=s.getMap();m.jumpTo({center:[0.1,51.5],zoom:13});s.replacePlan([[0.1,51.5],[0.1,51.505]]);const box=document.querySelector('#scada-ui-container input[data-layer-id=ukpn_secondary]');if(box.checked!==on)box.click();}""",enabled)
    page.locator('#satnav-toggle').click()
    page.locator('#satnav-walk-start').click()
    page.evaluate("window.__lineGpsTest.emit([0.1,51.5001],4)")
    page.locator('#satnav-toggle').click()
    if enabled:
        page.wait_for_function("()=>window.__GRIDATLAS_UKPN_DATA__.viewportQueries>0",timeout=120000)
    start=time.monotonic();cycle=0;max_heap=0;baseline_nav=len(nav)
    while time.monotonic()-start<1800:
        page.evaluate("""i=>{const m=window.__GRIDATLAS_V9_MAP__;window.__lineGpsTest.emit([0.1,51.5001+(i%15)*.0001],4);m.jumpTo({center:[0.1+(i%4)*.015,51.5],zoom:12+(i%3)});const t=document.querySelector('#satnav-toggle');t.click();t.click();}""",cycle)
        if cycle%4==0:
            page.evaluate("""()=>{const b=document.querySelector('#scada-ui-container input[data-layer-id="11kv"]');if(b)b.click();}""")
        sample=page.evaluate("""()=>({heap:performance.memory?.usedJSHeapSize??null,gps:window.__lineGpsTest.records,gl:window.__g203Soak,ukpn:window.__GRIDATLAS_UKPN_DATA__,tracking:document.querySelector('#satnav-compact').satnavSurvey.isTracking(),route:location.pathname})""")
        if sample['heap'] is not None:max_heap=max(max_heap,sample['heap'])
        print(json.dumps({'cycle':cycle,'elapsed':round(time.monotonic()-start),'sample':sample}),flush=True)
        assert not crashes and len(nav)==baseline_nav,(crashes,nav)
        assert sample['tracking'] and len(sample['gps']['starts'])==1 and not sample['gps']['stops'],sample
        assert not sample['gl']['losses'],sample
        assert not errors,errors
        if not enabled:assert sample['ukpn']['mapRequests']==0,sample
        cycle+=1
        page.wait_for_timeout(30000)
    assert time.monotonic()-start>=1800
    print(json.dumps({'elapsed':time.monotonic()-start,'cycles':cycle,'max_page_js_heap_bytes':max_heap or None,'crashes':crashes,'pageerrors':errors,'ukpn':enabled,'browser':name}),flush=True)
    ctx.close();browser.close()

SatNav G203 Swarm 05 Offline Browser

A Python command-line tool in the tools folder of GridAtlas that works with no gps (`no_gps`).

rendergridatlas / tools/satnav/g203-swarm-05-offline-browser.py · lines 1–119 of 119 · Entry point

What it does
It loads data. Defines 7 functions or classes, including live, pins, put, no_gps, key_present. Uses libraries os, pathlib, runpy, playwright.sync_api. Side effects: changes the web page (DOM); reads or writes files; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Downstream impact
Used directly by 1 file: GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
It is built from the live step (`live`), the pins step (`pins`) and the put step (`put`). G203-SWARM-05: exact composed route, real service worker and CacheStorage.
Why it matters
Run by GridAtlas PR File Size Guard Workflow.
Application
gridatlas · tools/satnav · Python CLI
Uses
os, pathlib, runpy, playwright.sync_api
Used by
run by GridAtlas PR File Size Guard Workflow (workflow run)
Produces
live, pins, put, no_gps, key_present, save, run
Defines here
live, pins, put, no_gps, key_present, save, run
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/satnav/g203-swarm-05-offline-browser.py:1-119 · blob fc08e2a93ab31e24a73a8b05d472426fe1e08c39 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, storage · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
"""G203-SWARM-05: exact composed route, real service worker and CacheStorage.
Run with the existing candidate HTTP server at 127.0.0.1:8873.
No production deployment; browser emulation is not physical iPhone acceptance.
"""
import os
from pathlib import Path
from runpy import run_path
from playwright.sync_api import sync_playwright, expect

ROOT = Path(__file__).resolve().parent
READY = run_path(str(ROOT / 'convergence-browser.py'))['READY']
GPS_SPY = run_path(str(ROOT / 'compact-browser.py'))['GPS_SPY']
ORIGIN = os.getenv('G203_TEST_ORIGIN', 'http://127.0.0.1:8873')
ROUTE = os.environ['G203_CANDIDATE_ROUTE']
assert ROUTE.startswith('/atlas/v/') and ROUTE.rstrip('/').split('/')[-1].isdigit()
URL = ORIGIN.rstrip('/') + ROUTE
PLAN_A = [[0.1, 51.5], [0.101, 51.501], [0.102, 51.502]]
PLAN_B = [[0.2, 51.6], [0.201, 51.601]]
CACHE = 'ventus-satnav-offline-plans-v1'
OTHER = ORIGIN.rstrip('/') + '/atlas/v/202612020205/__saved-field-plan__'

def live(page):
    page.goto(URL, wait_until='domcontentloaded', timeout=90000)
    page.wait_for_function(READY, timeout=120000)
    page.evaluate("document.querySelector('#satnav-compact').satnavSurvey.setPanelOpen(true)")
    area = page.locator('#satnav-field-tools details').filter(
        has=page.locator('summary', has_text='Offline plan'))
    expect(area).to_have_count(1)
    area.evaluate("(e) => e.open = true")
    return area

def pins(page):
    return page.evaluate("document.querySelector('#satnav-compact').satnavSurvey.getPins().map(p=>p.coordinate)")

def put(page, points):
    page.evaluate("p=>document.querySelector('#satnav-compact').satnavSurvey.replacePlan(p)", points)

def no_gps(page):
    assert page.evaluate("window.__lineGpsTest.records.starts.length") == 0
    assert not page.evaluate("document.querySelector('#satnav-compact')?.satnavSurvey.isTracking() ?? false")

def key_present(page):
    return page.evaluate("async ([c,k])=>!!(await caches.match(new URL('__saved-field-plan__',location.href),{cacheName:c}))", [CACHE, OTHER])

def save(area):
    area.get_by_role('button', name='Save plan', exact=True).click()
    expect(area.get_by_role('status')).to_contain_text('Saved. Reopen', timeout=25000)

def run(browser, name):
    with browser.new_context(viewport={'width':393,'height':852}, has_touch=True,
                             service_workers='allow') as ctx:
        ctx.add_init_script(GPS_SPY)
        page = ctx.new_page()
        area = live(page)
        no_gps(page)
        assert not key_present(page)
        put(page, PLAN_A)
        save(area)
        assert key_present(page)
        page.wait_for_function("navigator.serviceWorker.controller !== null", timeout=25000)
        assert page.evaluate("async()=> (await navigator.serviceWorker.getRegistration(location.href)).scope") == URL
        page.evaluate("async ([c,k])=>{const x=await caches.open(c);await x.put(k,new Response('other generation sentinel'))}", [CACHE, OTHER])
        put(page, PLAN_B)
        area.get_by_role('button', name='Use saved plan').click()
        expect(area.get_by_role('status')).to_contain_text('3 pins')
        assert pins(page) == PLAN_A
        no_gps(page)
        put(page, PLAN_B)
        save(area)
        ctx.set_offline(True)
        page.reload(wait_until='domcontentloaded', timeout=30000)
        expect(page.get_by_role('heading', name='Saved field plan')).to_be_visible()
        expect(page.locator('#summary')).to_contain_text('2 pins')
        expect(page.locator('#pin')).to_have_text('Pin 1 of 2')
        page.get_by_role('button', name='Next pin').click()
        expect(page.locator('#pin')).to_have_text('Pin 2 of 2')
        no_gps(page)
        ctx.set_offline(False)
        area = live(page)
        no_gps(page)
        area.get_by_role('button', name='Use saved plan').click()
        expect(area.get_by_role('status')).to_contain_text('2 pins')
        assert pins(page) == PLAN_B
        no_gps(page)
        area.get_by_role('button', name='Forget saved plan').click()
        expect(area.get_by_role('status')).to_contain_text('removed')
        assert not key_present(page)
        assert page.evaluate("async ([c,k])=>await (await caches.match(k,{cacheName:c})).text()", [CACHE, OTHER]) == 'other generation sentinel'
        area.get_by_role('button', name='Use saved plan').click()
        expect(area.get_by_role('status')).to_contain_text('No saved plan')
        ctx.set_offline(True)
        response = page.reload(wait_until='domcontentloaded', timeout=30000)
        assert response is not None and response.status == 503
        expect(page.locator('body')).to_contain_text('no saved field plan')
        no_gps(page)
        print(name, 'PASS: save, explicit restore, replacement, offline viewer, online recovery, generation isolation, forget, offline 503, GPS remains off', flush=True)
    with browser.new_context(viewport={'width':393,'height':852}) as ctx:
        ctx.add_init_script(GPS_SPY)
        ctx.add_init_script("""Object.defineProperty(CacheStorage.prototype,'open',{
          configurable:true,value:async()=>{throw new Error('Storage denied by test');}})""")
        page = ctx.new_page()
        area = live(page)
        put(page, PLAN_A)
        area.get_by_role('button', name='Save plan', exact=True).click()
        expect(area.get_by_role('status')).to_contain_text('Storage denied by test', timeout=25000)
        expect(area.get_by_role('button', name='Save plan', exact=True)).to_be_enabled()
        assert pins(page) == PLAN_A
        no_gps(page)
        print(name, 'PASS: injected storage denial is visible and recoverable', flush=True)

if __name__ == '__main__':
    with sync_playwright() as p:
        for name in os.getenv('LINE_TEST_BROWSERS','chromium,webkit').split(','):
            opts = {'args':['--use-gl=angle','--use-angle=swiftshader','--enable-webgl','--enable-unsafe-swiftshader']} if name == 'chromium' else {}
            browser = getattr(p,name).launch(**opts)
            try:
                run(browser,name)
            finally:
                browser.close()

SatNav G203 Verify Composition

A JavaScript module in the tools folder of GridAtlas that uses SHA-256.

ingestgridatlas / tools/satnav/g203-verify-composition.mjs · lines 1–12 of 12 · Entry point

What it does
It loads data. Uses libraries node:fs, node:crypto, node:path, node:assert/strict. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Inputs & outputs
In: JSON file current.json.
Downstream impact
Used directly by 1 file: GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
It reads `atlas/current.json`.
Why it matters
Run by GridAtlas PR File Size Guard Workflow.
Application
gridatlas · tools/satnav · JavaScript module
Uses
node:fs, node:crypto, node:path, node:assert/strict
Used by
run by GridAtlas PR File Size Guard 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
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/satnav/g203-verify-composition.mjs:1-12 · blob f64efe43e6320f5fbd318730e86f4d0ce59f3900 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
import {readFileSync} from 'node:fs';
import {createHash} from 'node:crypto';
import {resolve} from 'node:path';
import assert from 'node:assert/strict';
const root=resolve('atlas/v/202612020930'),j=JSON.parse(readFileSync(resolve(root,'current.json')));
assert.equal(j.generation,'202612020930');assert.equal(j.composition_version,'v9.203');
const byId=new Map(j.cartridges.map(c=>[c.id,c]));assert.equal(byId.size,j.cartridge_order.length);
const seen=new Set();
for(const id of j.cartridge_order){const c=byId.get(id);assert.ok(c);if(c.slot==='after-cartridge')assert.ok(seen.has(c.after));const b=readFileSync(resolve(root,c.path));assert.equal(b.length,c.bytes,id);assert.equal(createHash('sha256').update(b).digest('hex'),c.sha256,id);seen.add(id)}
for(const p of j.runtime_dependency_pins){const b=readFileSync(resolve(p.path));assert.equal(b.length,p.bytes,p.path);assert.equal(createHash('sha256').update(b).digest('hex'),p.sha256,p.path)}
assert.equal(JSON.parse(readFileSync('atlas/current.json')).composition_version,'v9.197');
console.log('PASS',seen.size,'cartridges and',j.runtime_dependency_pins.length,'runtime dependency pins; fallback unchanged');

SatNav G203 Viewport Browser

A Python command-line tool in the tools folder of GridAtlas. It is built from the run step (`run`).

rendergridatlas / tools/satnav/g203-viewport-browser.py · lines 1–32 of 32 · Entry point

What it does
Defines run. Uses libraries os, pathlib, runpy, playwright.sync_api. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
G203: real pinned UK Power Networks (UKPN) viewport, no duplicate download, source eviction and neon regression.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
gridatlas · tools/satnav · Python CLI
Uses
os, pathlib, runpy, playwright.sync_api
Used by
none found
Produces
run
Defines here
run
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/satnav/g203-viewport-browser.py:1-32 · blob da8bba43789f1e99a39a7109e2e0c8f1a109585e · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
"""G203: real pinned UKPN viewport, no duplicate download, source eviction and neon regression."""
import os
from pathlib import Path
from runpy import run_path
from playwright.sync_api import sync_playwright,expect
root=Path(__file__).resolve().parent
ready=run_path(str(root/'convergence-browser.py'))['READY']
site='http://127.0.0.1:8873'+os.environ['G203_CANDIDATE_ROUTE']
def run(browser,name):
    with browser.new_context(viewport={'width':393,'height':852},has_touch=True) as ctx:
        page=ctx.new_page()
        page.goto(site,wait_until='domcontentloaded',timeout=90000)
        page.wait_for_function(ready,timeout=120000)
        page.wait_for_function("()=>document.querySelector('#scada-ui-container input[data-layer-id=ukpn_secondary]')")
        page.evaluate("""()=>{const m=window.__GRIDATLAS_V9_MAP__,box=document.querySelector('#scada-ui-container input[data-layer-id=ukpn_secondary]');if(box.checked)throw Error('UKPN not opt-in');m.jumpTo({center:[0.1,51.5],zoom:13});box.click()}""")
        page.wait_for_function("""()=>{const d=window.__GRIDATLAS_UKPN_DATA__,s=window.__GRIDATLAS_V9_MAP__.getSource('src-ukpn_secondary')?.serialize().data;return d.viewportQueries>=1&&s?.features?.length>0&&s.features.length<54558}""",timeout=120000)
        first=page.evaluate("""()=>{const d=window.__GRIDATLAS_UKPN_DATA__,s=window.__GRIDATLAS_V9_MAP__.getSource('src-ukpn_secondary').serialize().data;return {rows:s.features.length,requests:d.mapRequests,queries:d.viewportQueries}}""")
        page.evaluate("()=>window.__GRIDATLAS_V9_MAP__.jumpTo({center:[0.7,51.6],zoom:13})")
        page.wait_for_function("n=>window.__GRIDATLAS_UKPN_DATA__.viewportQueries>n",arg=first['queries'],timeout=120000)
        page.wait_for_function("""()=>{const s=window.__GRIDATLAS_V9_MAP__.getSource('src-ukpn_secondary').serialize().data;return s.features.length>0&&s.features.every(f=>f.geometry.coordinates[0]>0.3)}""",timeout=120000)
        second=page.evaluate("()=>({...window.__GRIDATLAS_UKPN_DATA__})")
        assert first['requests']==second['mapRequests']==1,(first,second)
        page.evaluate("()=>document.querySelector('#scada-ui-container input[data-layer-id=ukpn_secondary]').click()")
        page.wait_for_function("()=>window.__GRIDATLAS_V9_MAP__.getSource('src-ukpn_secondary').serialize().data.features.length===0",timeout=30000)
        print(name,'real UKPN viewport and eviction PASS',first,second,flush=True)
if __name__=='__main__':
    with sync_playwright() as p:
        for name in os.environ.get('LINE_TEST_BROWSERS','chromium,webkit').split(','):
            opts={'args':['--use-gl=angle','--use-angle=swiftshader','--enable-webgl','--enable-unsafe-swiftshader']} if name=='chromium' else {}
            b=getattr(p,name).launch(**opts)
            try:run(b,name)
            finally:b.close()