GLOBALGRID2050 / EXPLORE CODE

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

Browser and 6 more files

A Python command-line tool in the gate folder of GridAtlas that checks baseline (`check_baseline`), covering road.

663 lines of JavaScript and Python from gridatlas, in 7 files. Topic: Maps, GIS and field navigation. Section 685 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. Direct Convergence 2km transform · gridatlas / tools/satnav/walk/direct-convergence-2km.mjs lines 1–53
  2. Direct Convergence Unlimited transform · gridatlas / tools/satnav/walk/direct-convergence-unlimited.mjs lines 1–45
  3. Direct transform · gridatlas / tools/satnav/walk/direct.mjs lines 1–43
  4. Direct Test test · gridatlas / tools/satnav/walk/direct.test.mjs lines 1–52
  5. Browser render · gridatlas / tools/satnav/walk/gate/browser.py lines 1–206
  6. Controls render · gridatlas / tools/satnav/walk/gate/controls.mjs lines 1–142
  7. Handoff transform · gridatlas / tools/satnav/walk/gate/handoff.mjs lines 1–122

Direct Convergence 2km

A JavaScript module in the walk folder of GridAtlas that creates direct walk (`createDirectWalk`) and sets targets (`setTargets`). It creates direct walk (`createDirectWalk`) and sets targets (`setTargets`).

transformgridatlas / tools/satnav/walk/direct-convergence-2km.mjs · lines 1–53 of 53 · pattern createDirectWalk (shared by 6 files)

What it does
It calculates its inputs. Defines 6 functions or classes, including samePin, walkTargets, createDirectWalk, setTargets, restart.
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: Convergence 2km Test (gridatlas). Reached from 3 other entry points, including GridAtlas PR File Size Guard Workflow (gridatlas); CI PR Gate (gridatlas); Map Promotion Rehearsal (gridatlas).
What it achieves
Its `createDirectWalk` function gives direct guidance session reporting choose, waiting, guiding or complete, with distance and bearing where available from Maths and compass modules, ordered targets and timestamped GPS fixes with accuracy (VEDIC: detect destination arrival).
Why it matters
Checked by Convergence 2km Test.
Application
gridatlas · tools/satnav/walk · JavaScript module
VEDIC
DETECT DESTINATION ARRIVAL (GG2050-VEDIC-000102): SatNav · Location and navigation data. Maths and compass modules, ordered targets and timestamped GPS fixes with accuracy → Direct guidance session reporting choose, waiting, guiding or complete, with distance and bearing where available.
Uses
Ordered Convergence 2km (import), Convergence 2km (import)
Used by
imported by Convergence 2km Test (import), mentioned in Standalone (comment link)
Produces
walkTargets, createDirectWalk
Defines here
samePin, walkTargets, createDirectWalk, setTargets, restart, locate
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/walk/direct-convergence-2km.mjs:1-53 · blob 9b3b93a7925843222dcccdbbc929a7d6655938ff · GitHub at these lines
State
achieves: code · context: readme_derived · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
import {createWaypointGuidance} from '../guidance/ordered-convergence-2km.mjs';

import {MAX_DIRECT_LEG_M,DIRECT_LEG_EPSILON_M} from '../guidance/convergence-2km.mjs';

const samePin = (a, b) => a?.id === b?.id && a.coordinate.every((n, i) => n === b.coordinate[i]);

// FROM is a saved design point. Direct guidance starts at the live measured
// position and targets the first VIA or TO. The final return leg is explicit.
export function walkTargets(pins, from, loop) {
  const targets = from ? pins.slice(1) : pins.slice();
  if (loop && from && pins.length >= 3) targets.push({id:'return-' + pins[0].id,coordinate:from});
  return targets;
}

export function createDirectWalk(maths, compass) {
  let ordered = createWaypointGuidance(maths, compass);
  let targets = [], arrived = false, lastTimestamp = -Infinity;
  function setTargets(next) {
    if (next.length === targets.length && next.every((pin, i) => samePin(pin, targets[i]))) return;
    const singleChanged = next.length === 1 || targets.length === 1;
    targets = next;
    if (singleChanged) {arrived = false; lastTimestamp = -Infinity;}
    ordered.setRoute(targets);
  }
  function restart() {
    arrived = false;
    lastTimestamp = -Infinity;
    ordered = createWaypointGuidance(maths, compass);
    ordered.setRoute(targets);
  }
  function locate(fix, now = Date.now()) {
    if (!targets.length) return {status:'choose'};
    const quality = compass.fixQuality(fix, now);
    if (quality !== 'usable') return {status:'waiting',quality};
    if (targets.length > 1) {
      const result = ordered.locate(fix,now);
      if (result.status === 'guiding' && (result.distanceM > MAX_DIRECT_LEG_M + DIRECT_LEG_EPSILON_M || result.deviationLimit === 'over-2-km')) return {...result,status:'over-limit'};
      return result;
    }
    if (fix.timestampMs < lastTimestamp) return {status:'waiting',quality:'out-of-order'};
    const metrics = compass.guide(fix,{coordinates:targets[0].coordinate},now);
    if (!metrics) return {status:'waiting'};
    if (!arrived && metrics.distanceM > MAX_DIRECT_LEG_M + DIRECT_LEG_EPSILON_M) {
      lastTimestamp = fix.timestampMs;
      return {status:'over-limit',distanceM:metrics.distanceM};
    }
    if (fix.timestampMs > lastTimestamp && metrics.distanceM + fix.accuracyM <= 15) arrived = true;
    lastTimestamp = fix.timestampMs;
    return arrived ? {status:'complete'} : {status:'guiding', targetIndex:0,
      distanceM:metrics.distanceM,remainingM:metrics.distanceM,bearingDeg:metrics.bearingDeg};
  }
  return {setTargets,restart,locate};
}

Direct Convergence Unlimited

A JavaScript module in the walk folder of GridAtlas that creates direct walk (`createDirectWalk`) and sets targets (`setTargets`). It creates direct walk (`createDirectWalk`) and sets targets (`setTargets`).

transformgridatlas / tools/satnav/walk/direct-convergence-unlimited.mjs · lines 1–45 of 45 · Not reached from any entry point (candidate for review) · pattern createDirectWalk (shared by 6 files)

What it does
It calculates its inputs. Defines 6 functions or classes, including samePin, walkTargets, createDirectWalk, setTargets, restart.
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: Distance Dock Proof (gridatlas).
What it achieves
Its `createDirectWalk` function gives direct guidance session reporting choose, waiting, guiding or complete, with distance and bearing where available from Maths and compass modules, ordered targets and timestamped GPS fixes with accuracy (VEDIC: detect destination arrival).
Why it matters
Imported by Distance Dock Proof.
Application
gridatlas · tools/satnav/walk · JavaScript module
VEDIC
DETECT DESTINATION ARRIVAL (GG2050-VEDIC-000102): SatNav · Location and navigation data. Maths and compass modules, ordered targets and timestamped GPS fixes with accuracy → Direct guidance session reporting choose, waiting, guiding or complete, with distance and bearing where available.
Uses
Ordered Convergence Unlimited (import)
Used by
imported by Distance Dock Proof (import)
Produces
walkTargets, createDirectWalk
Defines here
samePin, walkTargets, createDirectWalk, setTargets, restart, locate
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/walk/direct-convergence-unlimited.mjs:1-45 · blob e9dda6477d8cf369a655e1b5fa223f0c2534e1a7 · GitHub at these lines
State
achieves: code · context: readme_derived · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: duplicate_candidate
import {createWaypointGuidance} from '../guidance/ordered-convergence-unlimited.mjs';

const samePin = (a, b) => a?.id === b?.id && a.coordinate.every((n, i) => n === b.coordinate[i]);

// FROM is a saved design point. Direct guidance starts at the live measured
// position and targets the first VIA or TO. The final return leg is explicit.
export function walkTargets(pins, from, loop) {
  const targets = from ? pins.slice(1) : pins.slice();
  if (loop && from && pins.length >= 3) targets.push({id:'return-' + pins[0].id,coordinate:from});
  return targets;
}

export function createDirectWalk(maths, compass) {
  let ordered = createWaypointGuidance(maths, compass);
  let targets = [], arrived = false, lastTimestamp = -Infinity;
  function setTargets(next) {
    if (next.length === targets.length && next.every((pin, i) => samePin(pin, targets[i]))) return;
    const singleChanged = next.length === 1 || targets.length === 1;
    targets = next;
    if (singleChanged) {arrived = false; lastTimestamp = -Infinity;}
    ordered.setRoute(targets);
  }
  function restart() {
    arrived = false;
    lastTimestamp = -Infinity;
    ordered = createWaypointGuidance(maths, compass);
    ordered.setRoute(targets);
  }
  function locate(fix, now = Date.now()) {
    if (!targets.length) return {status:'choose'};
    const quality = compass.fixQuality(fix, now);
    if (quality !== 'usable') return {status:'waiting',quality};
    if (targets.length > 1) {
      return ordered.locate(fix,now);
    }
    if (fix.timestampMs < lastTimestamp) return {status:'waiting',quality:'out-of-order'};
    const metrics = compass.guide(fix,{coordinates:targets[0].coordinate},now);
    if (!metrics) return {status:'waiting'};
    if (fix.timestampMs > lastTimestamp && metrics.distanceM + fix.accuracyM <= 15) arrived = true;
    lastTimestamp = fix.timestampMs;
    return arrived ? {status:'complete'} : {status:'guiding', targetIndex:0,
      distanceM:metrics.distanceM,remainingM:metrics.distanceM,bearingDeg:metrics.bearingDeg};
  }
  return {setTargets,restart,locate};
}

Direct

A JavaScript module in the walk folder of GridAtlas that sets targets (`setTargets`). It creates direct walk (`createDirectWalk`) and sets targets (`setTargets`).

transformgridatlas / tools/satnav/walk/direct.mjs · lines 1–43 of 43 · pattern createDirectWalk (shared by 6 files)

What it does
It calculates its inputs. Defines 6 functions or classes, including samePin, walkTargets, createDirectWalk, setTargets, restart.
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 2 files: Direct Test (gridatlas); Handoff (gridatlas). Reached from 1 other entry point, including GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
Its `createDirectWalk` function gives direct guidance session reporting choose, waiting, guiding or complete, with distance and bearing where available from Maths and compass modules, ordered targets and timestamped GPS fixes with accuracy (VEDIC: detect destination arrival).
Why it matters
Imported by Handoff. Checked by Direct Test.
Application
gridatlas · tools/satnav/walk · JavaScript module
VEDIC
DETECT DESTINATION ARRIVAL (GG2050-VEDIC-000102): SatNav · Location and navigation data. Maths and compass modules, ordered targets and timestamped GPS fixes with accuracy → Direct guidance session reporting choose, waiting, guiding or complete, with distance and bearing where available.
Uses
Ordered (import)
Used by
imported by Direct Test (import), imported by Handoff (import)
Produces
walkTargets, createDirectWalk
Defines here
samePin, walkTargets, createDirectWalk, setTargets, restart, locate
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/walk/direct.mjs:1-43 · blob cd707422b244857ac4fba1f652d85dd015063652 · GitHub at these lines
State
achieves: code · context: readme_derived · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
import {createWaypointGuidance} from '../guidance/ordered.mjs';

const samePin = (a, b) => a?.id === b?.id && a.coordinate.every((n, i) => n === b.coordinate[i]);

// FROM is a saved design point. Direct guidance starts at the live measured
// position and targets the first VIA or TO. The final return leg is explicit.
export function walkTargets(pins, from, loop) {
  const targets = from ? pins.slice(1) : pins.slice();
  if (loop && from && pins.length >= 3) targets.push({id:'return-' + pins[0].id,coordinate:from});
  return targets;
}

export function createDirectWalk(maths, compass) {
  let ordered = createWaypointGuidance(maths, compass);
  let targets = [], arrived = false, lastTimestamp = -Infinity;
  function setTargets(next) {
    if (next.length === targets.length && next.every((pin, i) => samePin(pin, targets[i]))) return;
    const singleChanged = next.length === 1 || targets.length === 1;
    targets = next;
    if (singleChanged) {arrived = false; lastTimestamp = -Infinity;}
    ordered.setRoute(targets);
  }
  function restart() {
    arrived = false;
    lastTimestamp = -Infinity;
    ordered = createWaypointGuidance(maths, compass);
    ordered.setRoute(targets);
  }
  function locate(fix, now = Date.now()) {
    if (!targets.length) return {status:'choose'};
    const quality = compass.fixQuality(fix, now);
    if (quality !== 'usable') return {status:'waiting',quality};
    if (targets.length > 1) return ordered.locate(fix,now);
    if (fix.timestampMs < lastTimestamp) return {status:'waiting',quality:'out-of-order'};
    const metrics = compass.guide(fix,{coordinates:targets[0].coordinate},now);
    if (!metrics) return {status:'waiting'};
    if (fix.timestampMs > lastTimestamp && metrics.distanceM + fix.accuracyM <= 15) arrived = true;
    lastTimestamp = fix.timestampMs;
    return arrived ? {status:'complete'} : {status:'guiding', targetIndex:0,
      distanceM:metrics.distanceM,remainingM:metrics.distanceM,bearingDeg:metrics.bearingDeg};
  }
  return {setTargets,restart,locate};
}

Direct Test

A test in the walk folder of GridAtlas that checks Direct.

testgridatlas / tools/satnav/walk/direct.test.mjs · lines 1–52 of 52 · Entry point

What it does
It tests its inputs. Defines north, fix. Uses libraries node:test, node:assert/strict.
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
Defines `north` and `fix`.
Why it matters
Run by GridAtlas PR File Size Guard Workflow.
Application
gridatlas · tools/satnav/walk · test
Uses
Direct (import), node:test, node:assert/strict, ../vendor/9698781539e549deaa6ecaa4a2b34610c1f9fd29/nav/compass.mjs, ../vendor/9698781539e549deaa6ecaa4a2b34610c1f9fd29/vendor/grid-distance-maths/src/geodesy.mjs
Used by
run by GridAtlas PR File Size Guard Workflow (workflow run)
Produces
north, fix
Defines here
north, fix
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/walk/direct.test.mjs:1-52 · blob 08be57ba8b869bd01a9d252d58b3af4ee1fb12d3 · 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
import test from 'node:test';
import assert from 'node:assert/strict';
import * as compass from '../vendor/9698781539e549deaa6ecaa4a2b34610c1f9fd29/nav/compass.mjs';
import * as maths from '../vendor/9698781539e549deaa6ecaa4a2b34610c1f9fd29/vendor/grid-distance-maths/src/geodesy.mjs';
import {createDirectWalk,walkTargets} from './direct.mjs';

const origin = {id:'start',coordinate:[-1.5,51.5]};
const north = metres => [origin.coordinate[0],origin.coordinate[1] + metres / (maths.R_ATLAS * 1000) * 180 / Math.PI];
const destination = {id:'end',coordinate:north(63)};
const fix = (coordinate, timestampMs, accuracyM = 4) => ({longitude:coordinate[0],latitude:coordinate[1],accuracyM,timestampMs});

test('the measured approach can shorten or lengthen while the fixed plan stays at 63 m',() => {
  const walk = createDirectWalk(maths,compass);
  walk.setTargets(walkTargets([origin,destination],origin.coordinate,false));
  for (const [i,metres] of [0,28,14].entries()) {
    const result = walk.locate(fix(north(metres),1000+i),1000+i);
    assert.equal(result.status,'guiding');
    assert.equal(Math.round(result.distanceM),63-metres);
    assert.equal(Math.round(result.bearingDeg),0);
  }
  assert.equal(walk.locate(fix(destination.coordinate,1020,60),1020).status,'waiting');
  assert.equal(walk.locate(fix(destination.coordinate,1000),15000).status,'waiting');
  assert.equal(walk.locate(fix(north(53),15001,8),15001).status,'guiding');
  assert.equal(walk.locate(fix(destination.coordinate,15002),15002).status,'complete');
  assert.equal(Math.round(maths.distanceKm(...origin.coordinate,...destination.coordinate)*1000),63);
});

test('TO first, GPS origin capture, destination replacement and restart',() => {
  const walk = createDirectWalk(maths,compass);
  walk.setTargets(walkTargets([destination],null,false));
  assert.equal(walk.locate(null,1000).status,'waiting');
  assert.equal(walk.locate(fix(destination.coordinate,1001),1001).status,'complete');
  walk.setTargets(walkTargets([origin,destination],origin.coordinate,false));
  assert.equal(walk.locate(fix(origin.coordinate,1002),1002).status,'complete');
  walk.setTargets([{...destination,coordinate:north(100)}]);
  assert.equal(Math.round(walk.locate(fix(origin.coordinate,1003),1003).distanceM),100);
  walk.restart();
  assert.equal(walk.locate(null,1004).status,'waiting');
  assert.equal(walk.locate(fix(origin.coordinate,1005),1005).status,'guiding');
});

test('multiple pins and a perimeter visit ordered targets before returning to FROM',() => {
  const walk = createDirectWalk(maths,compass);
  const via = {id:'via',coordinate:north(28)};
  walk.setTargets(walkTargets([origin,via,destination],origin.coordinate,true));
  assert.equal(walk.locate(fix(origin.coordinate,101),101).targetId,via.id);
  assert.equal(walk.locate(fix(via.coordinate,102),102).targetId,destination.id);
  assert.equal(walk.locate(fix(destination.coordinate,103),103).targetId,'return-start');
  assert.equal(walk.locate(fix(origin.coordinate,104),104).status,'complete');
  walk.setTargets(walkTargets([origin],origin.coordinate,false));
  assert.equal(walk.locate(fix(origin.coordinate,105),105).status,'choose');
});

Browser

A Python command-line tool in the gate folder of GridAtlas that checks baseline (`check_baseline`), covering road.

rendergridatlas / tools/satnav/walk/gate/browser.py · lines 1–206 of 206 · Entry point · pattern QuietHandler (shared by 3 files)

What it does
Defines 7 functions or classes, including QuietHandler, log_message, point, emit, network. Uses libraries functools, math, os, threading, http.server. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage field_execution (path word 'gate'): 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 road.json; JSON file style.json.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It is built from the quiet handler class (`QuietHandler`), the log message helper (`log_message`) and the point step (`point`). Gate acceptance through the isolated GridAtlas phone map with synthetic GPS.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
gridatlas · tools/satnav/walk/gate · Python CLI
Uses
functools, math, os, threading, http.server, pathlib, runpy, urllib.parse
Used by
none found
Produces
QuietHandler, point, emit, network, check_baseline, check
Defines here
QuietHandler, log_message, point, emit, network, check_baseline, check
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/walk/gate/browser.py:1-206 · blob 9efcf341ab9cd860c8d9b176a82c807902a53b72 · 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
"""Gate acceptance through the isolated GridAtlas phone map with synthetic GPS."""
import functools
import math
import os
import threading
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from runpy import run_path
from urllib.parse import urlsplit

from playwright.sync_api import expect, sync_playwright

ROOT = Path(__file__).resolve().parents[4]
HELPERS = run_path(str(ROOT / 'tools/satnav/waypoint-browser.py'))
PILOT = '/atlas/v/satnav-gate-pilot/?pilot'
MAP = 'window.__GRIDATLAS_V9_MAP__'
GATE = [-1.5, 51.5]


class QuietHandler(SimpleHTTPRequestHandler):
    def log_message(self, *_):
        pass


def point(east, north):
    return [GATE[0] + east / (111319.49 * math.cos(math.radians(GATE[1]))),
            GATE[1] + north / 111319.49]


def emit(page, east, north, accuracy=4):
    at = point(east, north)
    HELPERS['emit_fix'](page, at, accuracy)
    HELPERS['measured'](page, at)


def network(route, host, broken_road):
    url = urlsplit(route.request.url)
    if broken_road and url.path.endswith('/pilot/road.json'):
        return route.fulfill(status=503, body='Road fixture unavailable')
    if url.hostname == host or url.scheme in ('blob', 'data'):
        return route.continue_()
    if url.hostname == 'cdn.jsdelivr.net' and '/maplibre-gl@3.6.2/dist/' in url.path:
        directory = os.environ.get('MAPLIBRE_DIST')
        if directory:
            return route.fulfill(path=Path(directory) / Path(url.path).name,
                                 headers={'Access-Control-Allow-Origin': '*'})
        return route.continue_()
    if url.path.endswith('/style.json'):
        return route.fulfill(json={'version': 8, 'sources': {}, 'layers': [
            {'id': 'background', 'type': 'background', 'paint': {'background-color': '#18232b'}}]},
            headers={'Access-Control-Allow-Origin': '*'})
    return route.abort()


def check_baseline(browser, engine, base):
    with browser.new_context(viewport={'width': 390, 'height': 664}, is_mobile=True, has_touch=True) as ctx:
        ctx.add_init_script(HELPERS['GPS_SPY'])
        ctx.route('**/*', functools.partial(network, host=urlsplit(base).hostname, broken_road=False))
        page = ctx.new_page()
        page.goto(base, wait_until='commit')
        page.wait_for_function("document.querySelector('#satnav-compact')?.satnavSurvey?.getMap()?.getLayer('l-sat') && document.querySelector('#satnav-walk-start')", timeout=60000)
        for control, at in [('from',point(-60,0)), ('to',point(0,60)), ('add',GATE)]:
            page.locator('#satnav-' + control).tap()
            pixel = HELPERS['clear_map_pixel'](page, 14)
            page.evaluate("""([at,x,y]) => {
              const m=window.__GRIDATLAS_V9_MAP__, r=m.getCanvas().getBoundingClientRect();
              m.easeTo({center:at,zoom:18,offset:[x-r.left-r.width/2,y-r.top-r.height/2],duration:0});
            }""", [at,pixel['x'],pixel['y']])
            page.touchscreen.tap(pixel['x'],pixel['y'])
        planned = HELPERS['pins'](page, 3)
        assert HELPERS['surface_distance'](GATE, planned[1]['at']) < 1
        page.locator('#satnav-walk-start').tap()
        guide = page.locator('#satnav-walk-guidance')
        emit(page, -60, 0)
        expect(guide).to_contain_text('Waypoint 1 of 2')
        emit(page, 0, -8)
        expect(guide).to_contain_text('Waypoint 2 of 2')
        page.locator('#satnav-walk-stop').tap()
        print(f'{engine} baseline · FROM, TO and + Pin reproduced the 8 m false advance', flush=True)


def check(browser, engine, width, height, url, broken_road=False):
    with browser.new_context(viewport={'width': width, 'height': height}, is_mobile=True, has_touch=True) as ctx:
        ctx.add_init_script(HELPERS['GPS_SPY'])
        ctx.route('**/*', functools.partial(network, host=urlsplit(url).hostname, broken_road=broken_road))
        page = ctx.new_page()
        page.goto(url, wait_until='commit')
        page.wait_for_function("document.querySelector('#satnav-compact')?.satnavSurvey?.getMap()?.getLayer('l-sat') && document.querySelector('#satnav-start-field')", timeout=60000)
        start, stop = page.locator('#satnav-walk-start'), page.locator('#satnav-walk-stop')
        guide, manual = page.locator('#satnav-walk-guidance'), page.locator('#satnav-start-field')
        initial = HELPERS['pins'](page, 3)
        assert initial[-1]['at'] == [-1.4995671, 51.5002695]
        assert page.evaluate('window.__lineGpsTest.records.starts') == []
        if broken_road:
            expect(guide).to_contain_text('Saved road unavailable')
            manual.tap()
            emit(page, 0, 12)
            expect(guide).to_contain_text('Field · Straight line · Turning pin')
            emit(page, 0, 30)
            expect(guide).to_contain_text('Pilot asset')
            assert HELPERS['pins'](page, 3) == initial
            stop.tap()
            print(f'{engine} {width}×{height} · HTTP 503 kept the field plan available', flush=True)
            return

        expect(guide).to_contain_text('63 m saved driving route · 60 m field')
        assert page.evaluate(MAP + ".getSource('satnav-saved-road').serialize().data.features[0].geometry.coordinates.length") == 5
        page.get_by_role('button', name='Replay gate checks').tap()
        expect(page.locator('#satnav-gate-actions output')).to_have_text(
            '8 m beside gate → Road · Through gate → Field · Uncertain crossing → Road')
        assert page.evaluate('window.__lineGpsTest.records.starts') == []

        start.tap()
        for x in (-20, -8, 0, 8, 20):
            emit(page, x, -8)
            expect(guide).to_contain_text('Road · Pilot gate')
            if x == 0:
                expect(guide).to_contain_text('8 m to entrance')
                expect(manual).to_have_text('Start field leg')
        controls = page.locator('#gridatlas-dash-toggle')
        controls.tap()
        layer = page.locator('#fs-curtain input[data-layer-id="400"]')
        initial_layer = layer.is_checked()
        layer.tap()
        assert layer.is_checked() != initial_layer
        layer.tap()
        controls.tap()
        page.locator('#satnav-location').tap()
        expect(guide).to_contain_text('Road · Pilot gate')
        assert page.evaluate('window.__lineGpsTest.records.starts') == [1]
        stop.tap()
        expect(guide).to_have_text('Walk stopped')

        # Starting the road leg while GPS is already on must reuse that watch.
        page.locator('#satnav-location').tap()
        emit(page, 0, -20)
        start.tap()
        emit(page, 0, -12)
        before = page.evaluate("""() => {
          const m=window.__GRIDATLAS_V9_MAP__; window.originalGateMap=m;
          window.originalGatePosition=m.getSource('gridatlas-satnav-position');
          return m.getZoom();
        }""")
        emit(page, 0, 0)
        expect(guide).to_contain_text('Road · Pilot gate')
        emit(page, 0, 12)
        expect(guide).to_contain_text('Field · Straight line · Turning pin')
        expect(guide).to_contain_text('48 m remaining')
        emit(page, 0, 30)
        expect(guide).to_contain_text('Pilot asset')
        emit(page, 30, 30)
        expect(guide).to_contain_text('Arrived at Pilot asset')
        assert page.evaluate("""() => {
          const m=window.__GRIDATLAS_V9_MAP__;
          return m===window.originalGateMap && window.originalGatePosition===m.getSource('gridatlas-satnav-position')
            && m.getPaintProperty('gridatlas-satnav-position-gps','circle-color')==='#ffdf61';
        }""")
        assert abs(page.evaluate(MAP + '.getZoom()') - before) < 1e-5
        assert HELPERS['pins'](page, 3) == initial
        stop.tap()

        start.tap()
        emit(page, 0, -12)
        emit(page, 0, 0, 9)
        emit(page, 0, 12)
        expect(guide).to_contain_text('Road · Pilot gate')
        expect(page.locator('#satnav-gate-actions')).to_contain_text('Entrance nearby · Start field leg')
        manual.tap()
        expect(guide).to_contain_text('Field · Straight line')
        assert HELPERS['pins'](page, 3) == initial
        stop.tap()
        page.evaluate('at => window.__waypointSample(at,0,0)', GATE)
        expect(guide).to_have_text('Walk stopped')
        HELPERS['measured'](page, None)
        assert page.evaluate('window.__lineGpsTest.records') == {'starts':[1,2,3], 'stops':[1,2,3]}

        page.locator('#satnav-walk-mode').select_option('direct')
        expect(page.locator('#satnav-gate-actions')).to_be_hidden()
        start.tap()
        emit(page, 0, -12)
        expect(guide).to_contain_text('Direct to pin')
        stop.tap()
        print(f'{engine} {width}×{height} · roadside, confirmed, ambiguous, Layers, marker, zoom, original TO, Stop and direct walk passed', flush=True)


if __name__ == '__main__':
    server = ThreadingHTTPServer(('127.0.0.1', 0), functools.partial(QuietHandler, directory=ROOT))
    threading.Thread(target=server.serve_forever, daemon=True).start()
    try:
        url = os.environ.get('GATE_TEST_URL', f'http://127.0.0.1:{server.server_port}{PILOT}')
        with sync_playwright() as pw:
            for engine in os.environ.get('LINE_TEST_BROWSERS', 'chromium,webkit').split(','):
                options = {}
                if engine == 'chromium':
                    options['args'] = ['--use-gl=angle','--use-angle=swiftshader','--enable-webgl','--enable-unsafe-swiftshader']
                    if os.environ.get('CHROMIUM_PATH'):
                        options['executable_path'] = os.environ['CHROMIUM_PATH']
                with getattr(pw, engine).launch(**options) as browser:
                    print(f'{engine} {browser.version}', flush=True)
                    check_baseline(browser, engine, f'http://127.0.0.1:{server.server_port}/atlas/v/satnav-walk-202611281345/')
                    for size in ((390,664), (664,390)):
                        check(browser, engine, *size, url)
                    check(browser, engine, 390, 664, url, broken_road=True)
    finally:
        server.shutdown()
        server.server_close()

Controls

A JavaScript module in the gate folder of GridAtlas that maps road. It attaches map (`attachMap`) and loads road (`loadRoad`).

rendergridatlas / tools/satnav/walk/gate/controls.mjs · lines 1–142 of 142 · Not reached from any entry point (candidate for review) · pattern mountGateControls (shared by 2 files)

What it does
It maps road. Defines 10 functions or classes, including metres, mountGateControls, selected, framePlan, draw. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage field_execution (path word 'gate'): 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 road.json.
What it achieves
Defines `metres`, `mountGateControls`, `selected` and 7 more.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · tools/satnav/walk/gate · JavaScript module
Uses
Handoff (import), Plan (import), Replay (import)
Used by
none found
Produces
mountGateControls
Defines here
metres, mountGateControls, selected, framePlan, draw, attachMap, loadRoad, select, matchesPlan, describe
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/walk/gate/controls.mjs:1-142 · blob ba42599e05e24205b4dac975277d74ec2b204d9f · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unreached_review
import {createGateHandoff} from './handoff.mjs';
import {pilot} from './pilot/plan.mjs';
import {replayGateChecks} from './pilot/replay.mjs';

const roadURL = new URL('./pilot/road.json', import.meta.url);
const coordinates = [pilot.gate.centre, ...pilot.fieldPins.map(pin => pin.coordinate)];
const sourceId = 'satnav-saved-road';
const metres = value => Math.round(value) + ' m';

export function mountGateControls({api, compass, message, start, mode, render}) {
  const gate = createGateHandoff(pilot, api.maths, compass);
  mode.add(new Option('Road to field · Pilot asset', 'gate'));
  const actions = document.createElement('div');
  actions.id = 'satnav-gate-actions';
  actions.hidden = true;
  const context = document.createElement('span');
  const manual = document.createElement('button');
  manual.type = 'button';
  manual.id = 'satnav-start-field';
  const replay = document.createElement('button');
  replay.type = 'button';
  replay.textContent = 'Replay gate checks';
  const findings = document.createElement('output');
  findings.setAttribute('aria-live', 'polite');
  actions.append(context, manual, replay, findings);
  message.after(actions);
  const selected = () => mode.value === 'gate';

  let revision = 0, roadStatus = 'idle', savedRoad = null, geometry = null, map = null, framePending = false;

  replay.onclick = () => {
    if (!savedRoad) return;
    findings.textContent = replayGateChecks(savedRoad, api.maths, compass).map(({label, leg}) =>
      label + ' → ' + (leg === 'road' ? 'Road' : 'Field')).join(' · ');
  };
  function framePlan() {
    if (!framePending || !map) return;
    framePending = false;
    if (api.isTracking()) return;
    const bounds = [pilot.roadStart, ...coordinates].reduce(([sw, ne], [x, y]) =>
      [[Math.min(sw[0], x), Math.min(sw[1], y)], [Math.max(ne[0], x), Math.max(ne[1], y)]],
      [[180, 90], [-180, -90]]);
    map.fitBounds(bounds, {padding:55, maxZoom:17, duration:0});
  }
  function draw() {
    if (!map?.getLayer('l-sat')) return;
    const data = {type:'FeatureCollection', features:geometry && selected()
      ? [{type:'Feature', properties:{method:'Saved driving route'}, geometry}] : []};
    const source = map.getSource(sourceId);
    if (source) source.setData(data);
    else if (data.features.length) map.addSource(sourceId, {type:'geojson', data});
    if (data.features.length && !map.getLayer(sourceId)) {
      map.addLayer({id:sourceId, type:'line', source:sourceId,
        paint:{'line-color':'#78adff', 'line-width':5}}, map.getLayer('gridatlas-satnav-waypoints-via') ? 'gridatlas-satnav-waypoints-via' : undefined);
    }
  }
  function attachMap() {
    const next = api.getMap();
    if (next === map) return;
    map?.off('style.load', draw);
    map = next;
    map?.on('style.load', draw);
    framePlan();
    draw();
  }
  async function loadRoad(epoch) {
    try {
      const response = await fetch(roadURL);
      if (!response.ok) throw new Error('Saved road unavailable');
      const saved = await response.json();
      if (epoch !== revision) return;
      if (!gate.setRoad(saved)) throw new Error('Saved road endpoint mismatch');
      roadStatus = 'ready';
      savedRoad = saved;
      geometry = saved.response.routes[0].geometry;
    } catch {
      if (epoch !== revision) return;
      roadStatus = 'unavailable';
    }
    draw();
    render();
  }
  function select() {
    revision++;
    gate.restart();
    gate.setRoad(null);
    geometry = null;
    savedRoad = null;
    framePending = selected();
    findings.textContent = '';
    actions.hidden = true;
    draw();
    if (!selected()) return;
    roadStatus = 'loading';
    api.replacePlan(coordinates);
    framePlan();
    void loadRoad(revision);
  }
  function matchesPlan() {
    const pins = api.getPins();
    return pins.length === coordinates.length && pins.every((pin, i) =>
      pin.coordinate.every((value, j) => value === coordinates[i][j]));
  }
  manual.onclick = () => {
    if (!selected()) return;
    if (!start.hidden) start.click();
    if (start.hidden && gate.startField()) render();
  };
  function describe(active, stopped) {
    const result = gate.locate(active ? api.getFix() : null);
    const onRoad = result.leg === 'road';
    const offer = onRoad && result.agreed && !result.locked &&
      (!active || result.nearby || roadStatus === 'unavailable');
    replay.hidden = active || roadStatus !== 'ready';
    if (active) findings.textContent = '';
    actions.hidden = !offer;
    context.textContent = active && result.nearby ? 'Entrance nearby · ' : '';
    manual.textContent = active ? 'Start field leg' : 'Start on foot';
    if (!active && stopped) return 'Walk stopped';
    if (!onRoad) {
      const label = 'Field · Straight line';
      if (result.status === 'complete') return label + ' · Arrived at ' + pilot.assetName;
      if (result.status !== 'guiding') return label + ' · Waiting for accurate, fresh GPS';
      const bearing = Number.isFinite(result.bearingDeg) ? ' · ' + (Math.round(result.bearingDeg) % 360) + '° true' : '';
      return label + ' · ' + result.target + bearing + ' · ' + metres(result.remainingM) + ' remaining';
    }
    if (result.locked) return 'Gate locked · Choose another entrance';
    if (!result.agreed) return 'Choose entrance';
    const parts = ['Road · ' + result.target];
    if (roadStatus === 'loading') parts.push('Loading saved road');
    else if (!result.roadAvailable) parts.push('Saved road unavailable');
    else if (!active) parts.push(metres(result.roadLengthM) + ' saved driving route');
    else if (result.quality !== 'usable') parts.push('Waiting for accurate, fresh GPS');
    else if (result.roadRemainingM !== null) parts.push(metres(result.roadRemainingM) + ' road remaining');
    else parts.push('Position on saved road uncertain');
    if (Number.isFinite(result.gateDistanceM)) parts.push(metres(result.gateDistanceM) + ' to entrance');
    parts.push(metres(result.fieldLengthM) + ' field');
    if (!active) parts.push('Synthetic pilot');
    return parts.join(' · ');
  }
  return {selected, select, matchesPlan, attachMap, describe, restart: gate.restart};
}

Handoff

A JavaScript module in the gate folder of GridAtlas that sets road (`setRoad`). It creates gate handoff (`createGateHandoff`) and sets road (`setRoad`).

transformgridatlas / tools/satnav/walk/gate/handoff.mjs · lines 1–122 of 122 · Not reached from any entry point (candidate for review) · pattern validPoint (shared by 6 files)

What it does
It calculates its inputs. Defines 9 functions or classes, including validPoint, createGateHandoff, metres, position, setRoad.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'handoff'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Downstream impact
Used directly by 5 files: Controls (gridatlas); Handoff Test (gridatlas); Controls (gridatlas); Plan (gridatlas); and 1 more.
What it achieves
Its `createGateHandoff` function gives road or field leg, crossing or manual entry state, quality and available guidance metrics from Agreed gate plan with geometry and width, saved road route (VEDIC: detect gate crossing).
Why it matters
Imported by 4 files, including Controls, Plan and Replay. Checked by Handoff Test.
Application
gridatlas · tools/satnav/walk/gate · JavaScript module
VEDIC
DETECT GATE CROSSING (GG2050-VEDIC-000098): SatNav · Location and navigation data. Agreed gate plan with geometry and width, saved road route, maths and compass modules, timestamped GPS fixes → Road or field leg, crossing or manual entry state, quality and available guidance metrics.
Uses
Direct (import), Route Follower (import)
Used by
imported by Controls (import), imported by Handoff Test (import), imported by Controls (import), imported by Plan (import), imported by Replay (import)
Produces
createGateHandoff
Defines here
validPoint, createGateHandoff, metres, position, setRoad, enterField, restart, observe, locate
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/walk/gate/handoff.mjs:1-122 · blob d10d92161c141e360eccf25e3d3221c476fb9503 · GitHub at these lines
State
achieves: code · context: readme_derived · stage: transform · effects: none found · domain stage: agent_infra · users: landowner_planner, ai_agent · canonical: unreached_review
import {createDirectWalk} from '../direct.mjs';
import {createRouteFollower} from '../../line/route-follower.mjs';

const NEAR_GATE_M = 35;
const MAX_GAP_MS = 6000;
const SNAP_TOLERANCE_M = 2;
const validPoint = p => Array.isArray(p) && p.length === 2 && p.every(Number.isFinite)
  && Math.abs(p[0]) <= 180 && Math.abs(p[1]) <= 90;

export function createGateHandoff(plan, maths, compass) {
  const gate = plan.gate;
  const metres = (a, b) => maths.distanceKm(...a, ...b) * 1000;
  const field = createDirectWalk(maths, compass);
  field.setTargets(plan.fieldPins);
  const pins = [gate.centre, ...plan.fieldPins.map(pin => pin.coordinate)];
  const fieldLengthM = pins.slice(1).reduce((sum, at, i) => sum + metres(pins[i], at), 0);
  const axis = validPoint(gate.fieldSide) && metres(gate.centre, gate.fieldSide) >= 3
    ? maths.initialBearingDeg(...gate.centre, ...gate.fieldSide) : null;

  function position(at) {
    const distance = metres(gate.centre, at);
    const angle = (maths.initialBearingDeg(...gate.centre, ...at) - axis) * Math.PI / 180;
    return {along: distance * Math.cos(angle), across: distance * Math.sin(angle), distance};
  }

  let route = null, roadLengthM = null, leg = 'road', lastTime = -Infinity;
  let stage = 'approach', enteredBy = null;

  function setRoad(saved) {
    route = null;
    roadLengthM = null;
    stage = 'approach';
    const response = saved?.response;
    const geometry = response?.routes?.[0]?.geometry;
    const coords = geometry?.coordinates;
    const snaps = response?.waypoints;
    if (!gate.agreed || !validPoint(gate.roadside) || saved?.gateId !== gate.id ||
        response?.code !== 'Ok' || !Array.isArray(coords) || coords.length < 2 ||
        !Array.isArray(snaps) || snaps.length !== 2) return false;
    const endpoints = [plan.roadStart, gate.roadside];
    const tips = [coords[0], coords.at(-1)];
    if (!endpoints.every((at, i) => validPoint(at) && validPoint(tips[i]) && validPoint(snaps[i]?.location)
        && metres(at, tips[i]) <= SNAP_TOLERANCE_M && metres(at, snaps[i].location) <= SNAP_TOLERANCE_M)) return false;
    try {
      route = createRouteFollower(geometry, maths);
    } catch {
      return false;
    }
    roadLengthM = coords.slice(1).reduce((sum, at, i) => sum + metres(coords[i], at), 0);
    return true;
  }

  function enterField(reason) {
    if (leg !== 'road' || !gate.agreed || gate.locked) return false;
    leg = 'field';
    enteredBy = reason;
    field.restart();
    return true;
  }

  function restart() {
    leg = 'road';
    enteredBy = null;
    lastTime = -Infinity;
    stage = 'approach';
    field.restart();
  }

  const roadEnd = validPoint(gate.roadside) && axis !== null ? position(gate.roadside) : null;

  function observe(at, fix) {
    const p = position(at);
    if (!route || axis === null || !Number.isFinite(gate.widthM) || gate.widthM <= 0 ||
        !roadEnd || roadEnd.along >= -1 || roadEnd.distance > NEAR_GATE_M || Math.abs(roadEnd.across) > gate.widthM / 2 ||
        p.distance > NEAR_GATE_M || Math.abs(p.across) + fix.accuracyM > gate.widthM / 2) {
      stage = 'approach';
      return;
    }
    const uncertainty = Math.max(1, fix.accuracyM);
    if (p.along < -uncertainty) stage = 'roadside';
    else if (Math.abs(p.along) <= uncertainty) {
      if (stage === 'roadside') stage = 'opening';
    } else {
      if (stage === 'opening' && p.along >= uncertainty + 2) {
        enterField('crossing');
        stage = 'approach';
      } else if (stage !== 'opening') stage = 'approach';
    }
  }

  function locate(fix, now = Date.now()) {
    const quality = compass.fixQuality(fix, now);
    const at = fix ? [fix.longitude, fix.latitude] : null;
    const fresh = quality === 'usable';
    const nearby = validPoint(at) && ['usable', 'poor'].includes(quality) && metres(gate.centre, at) <= NEAR_GATE_M;
    let sampleQuality = quality;
    if (!fresh) stage = 'approach';
    if (Number.isFinite(fix?.timestampMs) && fix.timestampMs <= now) {
      if (fix.timestampMs < lastTime) {
        sampleQuality = 'out-of-order';
        stage = 'approach';
      } else if (fix.timestampMs > lastTime) {
        if (fix.timestampMs - lastTime > MAX_GAP_MS) stage = 'approach';
        lastTime = fix.timestampMs;
        if (fresh && leg === 'road' && gate.agreed && !gate.locked) observe(at, fix);
      }
    }
    const measured = sampleQuality === 'usable';
    if (leg === 'field') {
      const result = measured ? field.locate(fix, now) : {status:'waiting'};
      const target = plan.fieldPins[result.targetIndex ?? 0];
      return {leg, enteredBy, quality: sampleQuality, status: result.status, target: target?.name,
        remainingM: result.status === 'complete' ? 0 : result.remainingM, bearingDeg: result.bearingDeg};
    }
    const projection = measured && route ? route(fix, now) : null;
    return {leg, quality: sampleQuality, nearby, target: gate.name, roadAvailable: Boolean(route),
      roadLengthM, roadRemainingM: projection?.status === 'ok' && !projection.offRoute ? projection.remainingM : null,
      gateDistanceM: measured ? metres(at, gate.centre) : null, fieldLengthM,
      locked: Boolean(gate.locked), agreed: Boolean(gate.agreed)};
  }
  return {locate, setRoad, startField: () => enterField('manual'), restart};
}