GLOBALGRID2050 / EXPLORE CODE

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

Controls and 4 more files

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

688 lines of JavaScript and Python from gridatlas, in 5 files. Topic: Maps, GIS and field navigation. Section 686 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. Handoff Test test · gridatlas / tools/satnav/walk/gate/handoff.test.mjs lines 1–148
  2. Browser render · gridatlas / tools/satnav/walk/gate/jobs/browser.py lines 1–187
  3. Controls render · gridatlas / tools/satnav/walk/gate/jobs/controls.mjs lines 1–221
  4. Observations transform · gridatlas / tools/satnav/walk/gate/jobs/observations.mjs lines 1–64
  5. Plan transform · gridatlas / tools/satnav/walk/gate/jobs/plan.mjs lines 1–68

Handoff Test

A test in the gate folder of GridAtlas that checks Handoff and Plan. It is built from the step step (`step`).

testgridatlas / tools/satnav/walk/gate/handoff.test.mjs · lines 1–148 of 148 · Not reached from any entry point (candidate for review) · pattern session (shared by 2 files)

What it does
It tests its inputs. Defines point, fix, session, step. Uses libraries node:assert/strict, node:fs, node:test. Side effects: reads or writes files.
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).
Inputs & outputs
In: JSON file road.json.
What it achieves
Defines `point`, `fix`, `session` and 1 more. It reads `./pilot/road.json`.
Why it matters
Guards the behaviour of Handoff and Plan.
Application
gridatlas · tools/satnav/walk/gate · test
Uses
Handoff (import), Plan (import), node:assert/strict, node:fs, node:test, ../../vendor/9698781539e549deaa6ecaa4a2b34610c1f9fd29/vendor/grid-distance-maths/src/geodesy.mjs, ../../vendor/9698781539e549deaa6ecaa4a2b34610c1f9fd29/nav/compass.mjs
Used by
none found
Produces
point, fix, session, step
Defines here
point, fix, session, step
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.test.mjs:1-148 · blob 2941969e8b3564f73842b12520cae69828218daf · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: agent_infra · users: landowner_planner, ai_agent · canonical: unreached_review
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import test from 'node:test';
import * as maths from '../../vendor/9698781539e549deaa6ecaa4a2b34610c1f9fd29/vendor/grid-distance-maths/src/geodesy.mjs';
import * as compass from '../../vendor/9698781539e549deaa6ecaa4a2b34610c1f9fd29/nav/compass.mjs';
import {createGateHandoff} from './handoff.mjs';
import {pilot} from './pilot/plan.mjs';

const road = JSON.parse(readFileSync(new URL('./pilot/road.json', import.meta.url)));
const gate = pilot.gate.centre;
const point = (east, north) => [gate[0] + east / 111319.49 / Math.cos(gate[1] * Math.PI / 180),
  gate[1] + north / 111319.49];
const fix = (east, north, accuracyM, timestampMs) => {
  const [longitude, latitude] = point(east, north);
  return {longitude, latitude, accuracyM, timestampMs};
};
function session(plan = pilot, saved = road) {
  const walk = createGateHandoff(plan, maths, compass);
  const available = walk.setRoad(saved);
  let time = 1000;
  const step = (east, north, accuracy = 4) => {
    time += 1000;
    return walk.locate(fix(east, north, accuracy, time), time);
  };
  return {walk, step, available};
}

test('locally routed approach ends at the selected roadside and preserves the bent driving distance', () => {
  const {step, available} = session();
  assert.equal(available, true);
  const start = step(-60, -8);
  assert.equal(start.leg, 'road');
  assert.equal(start.target, 'Pilot gate');
  assert.equal(Math.round(start.roadRemainingM), 63);
  assert.equal(Math.round(start.fieldLengthM), 60);
  assert.ok(start.roadLengthM > maths.distanceKm(...pilot.roadStart, ...pilot.gate.roadside) * 1000 + 2);
});

test('the 8 m pass at ±4 m stays on the road before, alongside and after the entrance', () => {
  const {step} = session();
  for (const east of [-20, -8, 0, 8, 20]) {
    const r = step(east, -8);
    assert.equal(r.leg, 'road');
    assert.equal(r.target, 'Pilot gate');
    if (east === 0) { assert.equal(r.nearby, true); assert.equal(Math.round(r.gateDistanceM), 8); }
  }
});

test('a fresh roadside, opening and onwards sequence switches once and follows the original field pins', () => {
  const {step, walk} = session();
  assert.equal(step(0, -12).leg, 'road');
  assert.equal(step(0, 0).leg, 'road');
  const r = step(0, 12);
  assert.equal(r.enteredBy, 'crossing');
  assert.equal(r.target, 'Turning pin');
  assert.equal(Math.round(r.remainingM), 48);
  assert.equal(walk.startField(), false);
  const detour = step(0, -4);
  assert.ok(detour.remainingM > r.remainingM);
  assert.equal(step(0, 30).target, 'Pilot asset');
  assert.equal(step(30, 30).status, 'complete');
});

test('a crossing wider than the known opening stays on road until manually started', () => {
  const {step, walk} = session();
  step(0, -12); step(0, 0, 9);
  const r = step(0, 12);
  assert.equal(r.leg, 'road');
  assert.equal(r.nearby, true);
  assert.equal(walk.startField(), true);
  assert.equal(step(0, 13).enteredBy, 'manual');
});

test('wrong-road and parallel crossings outside the agreed opening cannot qualify', () => {
  for (const path of [[[8,-12],[8,0],[8,12]], [[-12,6], [0,6], [12,6]], [[0,12],[0,0],[0,-12]],
    [[0,-12],[0,12]], [[0,-12],[14,0],[0,12]], [[0,-12],[0,0],[0,-12],[0,12]]]) {
    const {step} = session();
    for (const [east, north] of path) assert.equal(step(east, north).leg, 'road', JSON.stringify(path));
  }
});

test('stale, weak, missing, out-of-order, duplicate and gapped observations cannot complete a crossing', () => {
  const invalid = [
    [fix(0,0,4,2000), 13000], [fix(0,0,75,2000), 2000], [null, 2000],
    [fix(0,0,4,999), 2000], [fix(0,0,4,1000), 1000], [fix(0,0,4,14000), 2000],
    [fix(0,0,4,8000), 8000],
  ];
  for (const [sample, now] of invalid) {
    const {walk} = session();
    walk.locate(fix(0,-12,4,1000),1000);
    assert.equal(walk.locate(sample, now).leg, 'road');
    const end = Math.max(now, 2000) + 1000;
    assert.equal(walk.locate(fix(0,12,4,end),end).leg, 'road');
  }
  const {step} = session();
  step(0, -12);
  const r = step(0, -8, 75);
  assert.equal(r.quality, 'poor');
  assert.equal(r.nearby, true);
  assert.equal(r.roadRemainingM, null);
});

test('an uncertain pass can recover using a later fresh sequence back through the agreed opening', () => {
  const {step} = session();
  step(0,-12); step(0,0,75); assert.equal(step(0,12).leg,'road');
  step(0,-12); step(0,0); assert.equal(step(0,12).enteredBy,'crossing');
});

test('without an oriented opening only deliberate field start is possible', () => {
  const plan = structuredClone(pilot);
  delete plan.gate.fieldSide;
  delete plan.gate.widthM;
  const {step, walk} = session(plan);
  step(0,-12); step(0,0); assert.equal(step(0,12).leg,'road');
  assert.equal(walk.startField(),true);
});

test('a locked entrance or unconfirmed choice between two gates cannot start a field leg', () => {
  for (const gate of [{...pilot.gate,locked:true}, {...pilot.gate,agreed:false}]) {
    const {step, walk} = session({...pilot,gate});
    step(0,-12); step(0,0); assert.equal(step(0,12).leg,'road');
    assert.equal(walk.startField(),false);
  }
});

test('wrong endpoint, other gate, disconnected track and missing road preserve the field-only plan', () => {
  const wrong = structuredClone(road);
  wrong.response.routes[0].geometry.coordinates[wrong.response.routes[0].geometry.coordinates.length - 1] = point(0,6);
  const wrongSnap = structuredClone(road);
  wrongSnap.response.waypoints[1].location = point(0,6);
  for (const saved of [null, {...road,gateId:'other'}, wrong, wrongSnap, {response:{code:'NoRoute'}}]) {
    const {step,walk,available} = session(pilot,saved);
    assert.equal(available,false);
    step(0,-12); step(0,0); assert.equal(step(0,12).leg,'road');
    assert.equal(walk.startField(),true);
    assert.equal(step(0,30).target,'Pilot asset');
  }
});

test('restart discards an incomplete crossing and any prior field arrival', () => {
  const {step,walk} = session();
  step(0,-12); step(0,0); walk.restart();
  assert.equal(step(0,12).leg,'road');
  assert.equal(walk.startField(),true);
  step(0,30); assert.equal(step(30,30).status,'complete');
  walk.restart();
  assert.equal(step(30,30).leg,'road');
});

Browser

A Python command-line tool in the jobs folder of GridAtlas that draws south meadow fictional and local entrance.

rendergridatlas / tools/satnav/walk/gate/jobs/browser.py · lines 1–187 of 187 · Entry point · pattern position (shared by 9 files)

What it does
It draws south meadow fictional and local entrance. Defines load, position, check, emit. Uses libraries functools, json, math, os, threading. 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 south-meadow-fictional.json; JSON file local-entrance.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 load step (`load`), the position step (`position`) and the check step (`check`). Load two jobs through the phone UI and replay a visit to the second entrance.
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/jobs · Python CLI
Uses
functools, json, math, os, threading, copy, http.server, pathlib
Used by
none found
Produces
load, position, check
Defines here
load, position, check, emit
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/jobs/browser.py:1-187 · blob 558b22c902149f2b49a5f8f6c41221ea1121bfa3 · 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
"""Load two jobs through the phone UI and replay a visit to the second entrance."""
import functools
import json
import math
import os
import threading
from copy import deepcopy
from http.server import ThreadingHTTPServer
from pathlib import Path
from runpy import run_path
from urllib.parse import urlsplit

from playwright.sync_api import expect, sync_playwright

HERE = Path(__file__).resolve().parent
GATE = run_path(str(HERE.parent / 'browser.py'))
HELPERS = GATE['HELPERS']
ENTRY = '/atlas/v/satnav-road-to-field-202611281725/'
JOB = json.loads((HERE / 'south-meadow-fictional.json').read_text())


def load(page, doc):
    layout = page.locator('#satnav-layout')
    if layout.get_attribute('open') is None:
        layout.locator('summary').tap()
    with page.expect_file_chooser() as opened:
        layout.get_by_role('button', name='Import layout or job').tap()
    opened.value.set_files({'name': 'local-entrance.json', 'mimeType': 'application/json',
                            'buffer': json.dumps(doc).encode()})
    return layout.get_by_role('status')


def position(x, y):
    lng, lat = JOB['gate']['centre']
    return [lng + x / (111319.49 * math.cos(math.radians(lat))), lat + y / 111319.49]


def check(browser, width, height, url):
    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(GATE['network'], host=urlsplit(url).hostname, broken_road=False))
        page = ctx.new_page()
        requests = []
        page.on('request', lambda request: requests.append((request.method, request.url)))
        page.goto(url, wait_until='commit')
        page.wait_for_function("document.querySelector('#satnav-compact')?.openSatnavGateJob && document.querySelector('#satnav-layout') && window.__GRIDATLAS_V9_MAP__?.getLayer('l-sat')", timeout=60000)
        mode = page.locator('#satnav-walk-mode')
        guide = page.locator('#satnav-walk-guidance')
        start = page.locator('#satnav-walk-start')
        stop = page.locator('#satnav-walk-stop')
        manual = page.locator('#satnav-start-field')
        layout = page.locator('#satnav-layout')
        mode.select_option('gate')
        expect(guide).to_contain_text('63 m saved driving route')
        initial = HELPERS['pins'](page, 3)
        saved_road = "window.__GRIDATLAS_V9_MAP__.getSource('satnav-saved-road').serialize().data.features"
        previous_road = page.evaluate(saved_road)
        expect(load(page, JOB)).to_contain_text('Meadow Gate · 12 m opening · Meadow pump')
        expect(mode).to_have_value('job')
        expect(page.locator('#satnav-to .satnav-job-name')).to_be_visible()
        expect(page.locator('#satnav-to .satnav-job-name')).to_have_text('Meadow pump')
        expect(page.locator('#satnav-from .satnav-job-name')).to_have_text('Meadow Gate')
        new_pins = HELPERS['pins'](page, 3, initial)
        coords = [JOB['gate']['centre']] + [p['coordinate'] for p in JOB['fieldPins']]
        assert [p['at'] for p in new_pins] == coords
        assert all(a['at'] != b['at'] for a, b in zip(initial, new_pins))
        new_road = page.evaluate(saved_road)
        assert new_road != previous_road and new_road[0]['geometry'] == JOB['savedRoad']['response']['routes'][0]['geometry']
        assert page.evaluate('''at => {
          const m=window.__GRIDATLAS_V9_MAP__, el=m.getCanvas(), r=el.getBoundingClientRect(), px=m.project(at);
          return document.elementFromPoint(px.x + r.left, px.y + r.top) === el;
        }''', JOB['gate']['centre'])
        expect(page.get_by_role('button', name='Replay gate checks')).to_be_hidden()
        invalid = deepcopy(JOB)
        del invalid['gate']['widthM']
        expect(load(page, invalid)).to_contain_text('measured opening width')
        with page.expect_file_chooser() as cancelled:
            layout.get_by_role('button', name='Import layout or job').tap()
        cancelled.value.set_files([])
        assert HELPERS['pins'](page, 3) == new_pins and page.evaluate(saved_road) == new_road
        expect(guide).to_contain_text('Road · Meadow Gate')
        assert page.evaluate('window.__lineGpsTest.records.starts') == []
        layout.locator('summary').tap()

        def emit(x, y, accuracy=3, age=0):
            HELPERS['emit_fix'](page, position(x, y), accuracy, age)
            if not age:
                HELPERS['measured'](page, position(x, y))

        start.tap()
        for x in (16, 0, -16):
            emit(x, 8)
            expect(guide).to_contain_text('Road · Meadow Gate')
            if x == 0:
                expect(guide).to_contain_text('0 m road remaining · 8 m to entrance')
        stop.tap()
        start.tap()
        emit(0, 12)
        emit(0, 0, 9)
        emit(0, -13)
        expect(guide).to_contain_text('Road · Meadow Gate')
        expect(page.locator('#satnav-gate-actions')).to_contain_text('Entrance nearby · Start field leg')
        stop.tap()
        start.tap()
        emit(0, 12)
        emit(0, 0)
        page.evaluate('''() => {
          for (const hidden of [true, false]) {
            Object.defineProperty(document, 'hidden', {configurable:true, value:hidden});
            document.dispatchEvent(new Event('visibilitychange'));
          }
          delete document.hidden;
        }''')
        emit(0, 0, age=20000)
        emit(0, -13)
        expect(guide).to_contain_text('Road · Meadow Gate')
        emit(0, 12)
        emit(0, 0)
        emit(0, -13)
        expect(guide).to_contain_text('Field · Straight line · Willow turn')
        expect(page.locator('#satnav-to .satnav-job-name')).to_have_text('Meadow pump')
        expect(page.locator('#satnav-gate-switch')).to_contain_text('Automatic switch')
        emit(0, -30)
        expect(guide).to_contain_text('Meadow pump')
        stop.tap()
        start.tap()
        emit(0, -13)
        expect(guide).to_contain_text('Road · Meadow Gate')
        stop.tap()
        for road, warning in [(None, 'Saved road unavailable for Meadow Gate'),
                              ({**JOB['savedRoad'], 'gateId':'wrong'}, 'Check the saved driving approach to Meadow Gate')]:
            expect(load(page, {**JOB, 'savedRoad':road})).to_contain_text(warning)
            assert page.evaluate(saved_road) == []
            assert HELPERS['pins'](page, 3) == new_pins
            layout.locator('summary').tap()
            manual.tap()
            emit(0, -13)
            expect(guide).to_contain_text('Field · Straight line · Willow turn')
            expect(page.locator('#satnav-gate-switch')).to_contain_text('Manual field start')
            stop.tap()
        survey = page.locator('#satnav-survey')
        survey.locator('summary').tap()
        survey.locator('[data-device]').fill('Replay handset')
        survey.locator('[data-browser]').fill('Replay engine')
        with page.expect_download() as exported:
            survey.get_by_role('button', name='Export GeoJSON').tap()
        evidence = json.loads(exported.value.path().read_bytes())['gateEvidence']
        assert evidence['generation'] == page.evaluate('window.__GRIDATLAS_ATLAS__.generation')
        assert evidence['device'] == 'Replay handset' and evidence['safariVersion'] == 'Replay engine'
        assert evidence['planned'][0]['gate']['widthM'] == 12
        assert evidence['planned'][0]['savedRoad'] == new_road[0]['geometry']
        assert len(evidence['walks']) == 6 and not evidence['truncated']
        switches = [[e['source'] for e in walk['events'] if e['event'] == 'field-switch'] for walk in evidence['walks']]
        assert switches == [[], [], ['automatic'], [], ['manual'], ['manual']], switches
        resumed = next(e for e in evidence['walks'][2]['events'] if e['event'] == 'page-visible')
        assert 'Road · Meadow Gate' in resumed['guidance'] and 'fresh GPS' in resumed['guidance']
        observations = [e for e in evidence['walks'][0]['events'] if e['event'] == 'observation' and e['measured']]
        assert len(observations) == 3
        assert all(e['leg'] == 'road' and e['target'] == 'Meadow Gate' and e['accuracyM'] == 3 for e in observations)
        assert round(observations[1]['roadRemainingM']) == 0 and round(observations[1]['entranceDistanceM']) == 8
        assert observations[1]['gapMs'] == observations[1]['fixTimeMs'] - observations[0]['fixTimeMs']
        assert evidence['planned'][0]['gate']['centre'] != observations[1]['measured']
        assert all(walk['events'][-1]['event'] == 'end' for walk in evidence['walks'])
        for walk in evidence['walks'][-2:]:
            assert any(e['event'] == 'start-on-foot' and e['source'] == 'manual' for e in walk['events'])
        records = page.evaluate('window.__lineGpsTest.records')
        assert records['starts'] == records['stops'] and len(records['starts']) == 6
        assert not any(method != 'GET' or 'Meadow' in path or 'south-opening' in path or 'local-entrance.json' in path
                       for method, path in requests)
        print(f'{browser.browser_type.name} {width}×{height}: opposite-side import, cancel, named targets, both distances, three gate cases, stale GPS, restart, field fallback and exported switch evidence passed', flush=True)


if __name__ == '__main__':
    with ThreadingHTTPServer(('127.0.0.1', 0), functools.partial(GATE['QuietHandler'], directory=GATE['ROOT'])) as server:
        threading.Thread(target=server.serve_forever, daemon=True).start()
        url = f'http://127.0.0.1:{server.server_port}' + os.environ.get('SATNAV_JOB_ENTRY', ENTRY)
        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:
                    for size in ((390, 664), (664, 390)):
                        check(browser, *size, url)
        server.shutdown()

Controls

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

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

What it does
It maps road. Defines 14 functions or classes, including metres, mountGateControls, isJob, selected, framePlan. 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`, `isJob` and 11 more. It responds to visibilitychange and click events.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · tools/satnav/walk/gate/jobs · JavaScript module
Uses
Handoff (import), Observations (import), Plan (import), Replay (import)
Used by
none found
Produces
mountGateControls
Defines here
metres, mountGateControls, isJob, selected, framePlan, draw, attachMap, loadRoad, begin, select, useJob, matchesPlan, describe, end
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/jobs/controls.mjs:1-221 · blob 3cc1c1d82f83e81c0195b03967d447745706fec8 · 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 {createGateLog} from './observations.mjs';
import {pilot} from '../pilot/plan.mjs';
import {replayGateChecks} from '../pilot/replay.mjs';

const roadURL = new URL('../pilot/road.json', import.meta.url);
const sourceId = 'satnav-saved-road';
const metres = value => Math.round(value) + ' m';

export function mountGateControls({api, compass, message, start, mode, render, isActive}) {
  let imported = null, plan = pilot, gate = null, coordinates = [];
  const panel = document.getElementById('satnav-compact');
  const log = createGateLog(window.__GRIDATLAS_ATLAS__.generation, navigator.userAgent, navigator.platform);
  panel.satnavGateLog = log;
  let startedAt = 0;
  const jobOption = new Option('', 'job');
  const isJob = () => mode.value === 'job' && imported !== null;
  const endpoints = ['from', 'to'].map(id => {
    const name = document.createElement('strong');
    name.className = 'satnav-job-name';
    document.querySelector('#satnav-' + id).append(name);
    return name;
  });
  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);
  const switchNote = document.createElement('p');
  switchNote.id = 'satnav-gate-switch';
  switchNote.setAttribute('role', 'status');
  switchNote.hidden = true;
  message.after(switchNote, actions);
  const selected = () => mode.value === 'gate' || isJob();

  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() && !isJob()) return;
    const bounds = [plan.roadStart, plan.gate.roadside, plan.gate.fieldSide, ...(geometry?.coordinates ?? []), ...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]]);
    let padding = 55;
    if (isJob()) {
      const canvas = map.getCanvas().getBoundingClientRect();
      const panelBox = panel.getBoundingClientRect();
      const header = document.getElementById('gridatlas-menu-bar')?.getBoundingClientRect();
      const left = Math.ceil(panelBox.right - canvas.left) + 12;
      const top = Math.max(16, Math.ceil((header?.bottom ?? canvas.top) - canvas.top) + 12);
      if (canvas.width - left > 64 && canvas.height - top > 90) {
        padding = {left, top, right:16, bottom:55};
      }
    }
    map.fitBounds(bounds, {padding, 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 begin(action = 'start-walk') {
    gate?.restart();
    startedAt = Date.now();
    if (selected()) log.start(plan, geometry, action);
  }
  function select() {
    log.stop('changed plan or mode');
    switchNote.hidden = true;
    revision++;
    plan = isJob() ? imported.plan : pilot;
    gate = isJob() ? imported.model : createGateHandoff(plan, api.maths, compass);
    coordinates = [plan.gate.centre, ...plan.fieldPins.map(pin => pin.coordinate)];
    gate.restart();
    for (const [i, label] of endpoints.entries()) {
      label.textContent = isJob() ? [plan.gate.name, plan.assetName][i] : '';
      label.parentElement.classList.toggle('satnav-job-endpoint', isJob());
    }
    geometry = null;
    savedRoad = null;
    framePending = selected();
    findings.textContent = '';
    actions.hidden = true;
    draw();
    if (!selected()) return;
    roadStatus = isJob() ? (imported.warning ? 'unavailable' : 'ready') : 'loading';
    geometry = isJob() ? imported.geometry : null;
    if (isActive()) begin('select-guidance');
    api.replacePlan(coordinates);
    framePlan();
    draw();
    if (!isJob()) void loadRoad(revision);
  }
  function useJob(job) {
    imported = job;
    jobOption.textContent = 'Road to field · ' + job.plan.assetName;
    if (!jobOption.parentElement) mode.add(jobOption);
    mode.value = 'job';
    select();
  }

  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;
    const action = start.hidden ? 'start-field-leg' : 'start-on-foot';
    if (!start.hidden) start.click();
    if (start.hidden) {
      log.append(action, {source:'manual'});
      if (gate.startField()) render();
    }
  };
  function describe(active, stopped) {
    let fix = active ? api.getFix() : null;
    if (fix && fix.timestampMs < startedAt) fix = null;
    const result = gate.locate(fix);
    if (active) log.observe(fix, result, plan.assetName);
    const onRoad = result.leg === 'road';
    if (!active || onRoad || !isJob()) switchNote.hidden = true;
    else if (switchNote.hidden) {
      const automatic = result.enteredBy === 'crossing';
      const when = new Date(automatic && fix ? fix.timestampMs : Date.now());
      const clock = when.toLocaleTimeString([], {hour:'2-digit', minute:'2-digit', second:'2-digit', hour12:false});
      switchNote.textContent = (automatic ? 'Automatic switch' : 'Manual field start') + ' · ' + clock + ' · ' + plan.gate.name;
      switchNote.hidden = false;
    }
    const offer = onRoad && result.agreed && !result.locked &&
      (!active || result.nearby || roadStatus === 'unavailable');
    replay.hidden = isJob() || 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 ' + plan.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 plan.gate.name + ' 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(isJob() ? imported.warning : '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 && !isJob()) parts.push('Synthetic pilot');
    if (isJob() && plan.synthetic) parts.push('Fictional job');
    return parts.join(' · ');
  }
  document.addEventListener('visibilitychange', () => {
    log.append(document.hidden ? 'page-hidden' : 'page-visible', {source:'browser', guidance:message.textContent});
  });
  document.addEventListener('click', event => {
    const control = event.target.closest?.('#satnav-compact button, #satnav-compact summary, #gridatlas-dash-toggle, #fs-curtain input[data-layer-id]');
    if (!control || [start, manual].includes(control)) return;
    log.append('tap', {source:'manual', control:control.id || control.dataset.layerId || control.textContent.trim().slice(0,80)});
  }, true);
  function end(reason) {
    log.stop(reason);
    gate?.restart();
  }
  return {selected, select, useJob, matchesPlan, attachMap, describe, begin, end};
}

Observations

A JavaScript module in the jobs folder of GridAtlas that creates gate log (`createGateLog`).

transformgridatlas / tools/satnav/walk/gate/jobs/observations.mjs · lines 1–64 of 64 · Not reached from any entry point (candidate for review) · pattern observe (shared by 13 files)

What it does
It calculates its inputs. Defines 6 functions or classes, including createGateLog, append, start, observe, stop.
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.
Downstream impact
Used directly by 1 file: Controls (gridatlas).
What it achieves
It creates gate log (`createGateLog`) and is built from the append step (`append`) and the start step (`start`). Observations are held only for this page and included in an explicit survey export.
Why it matters
Imported by Controls.
Application
gridatlas · tools/satnav/walk/gate/jobs · JavaScript module
Uses
none found
Used by
imported by Controls (import)
Produces
createGateLog
Defines here
createGateLog, append, start, observe, stop, snapshot
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/jobs/observations.mjs:1-64 · blob 0eceaa50df9550c6474f8e4d44acbf91a61fc056 · 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: unreached_review
// Observations are held only for this page and included in an explicit survey export.
export function createGateLog(generation, userAgent, platform) {
  const plans = [], sessions = [], planIds = new Map();
  let session = null, lastFixTime = null, lastState = null, seenLeg = null;
  let count = 0, truncated = false;

  function append(event, data = {}) {
    if (!session) return;
    if (count >= 20000) { truncated = true; return; }
    session.events.push({timeMs:Date.now(), event, ...data});
    count++;
  }

  function start(plan, road, action) {
    if (count >= 20000) { truncated = true; return; }
    if (!planIds.has(plan)) {
      planIds.set(plan, plans.length);
      plans.push({gate:plan.gate, assetName:plan.assetName, roadStart:plan.roadStart, savedRoad:road,
        fieldPins:plan.fieldPins, synthetic:plan.synthetic === true || plan.source?.startsWith('Synthetic') === true});
    }
    session = {planIndex:planIds.get(plan), events:[]};
    sessions.push(session);
    lastFixTime = null;
    lastState = null;
    seenLeg = 'road';
    append(action, {source:'manual', leg:'road', target:plan.gate.name});
  }

  function observe(fix, result, assetName) {
    if (!session) return;
    const state = {
      leg:result.leg, target:result.status === 'complete' ? assetName : result.target ?? null,
      quality:result.quality, status:result.status ?? null, roadRemainingM:result.roadRemainingM ?? null,
      entranceDistanceM:result.gateDistanceM ?? null, fieldRemainingM:result.remainingM ?? null,
    };
    if (result.leg !== seenLeg) {
      seenLeg = result.leg;
      append('field-switch', {source:result.enteredBy === 'crossing' ? 'automatic' : 'manual',
        fixTimeMs:fix?.timestampMs ?? null, ...state});
    }
    // Rendering may run several times for one GPS observation.
    if (lastState && lastState.fix === fix && lastState.leg === result.leg) return;
    lastState = {fix, leg:result.leg};
    const time = fix?.timestampMs;
    const gapMs = Number.isFinite(time) && lastFixTime !== null ? time - lastFixTime : null;
    if (Number.isFinite(time)) lastFixTime = time;
    append('observation', {fixTimeMs:time ?? null, gapMs, measured:fix ? [fix.longitude, fix.latitude] : null,
      accuracyM:fix?.accuracyM ?? null, ...state});
  }

  function stop(reason) {
    append('end', {reason});
    session = null;
  }

  function snapshot(device, safariVersion) {
    if (!sessions.length) return null;
    const safari = /Version\/([\d.]+).*Safari\//.exec(userAgent);
    return {schema:'ventus.satnav.gate-evidence.v1', generation, device:device || platform || null,
      safariVersion:safariVersion || (safari && !/CriOS|FxiOS|EdgiOS/.test(userAgent) ? safari[1] : null),
      userAgent, planned:plans, walks:sessions, truncated};
  }
  return {start, observe, append, stop, snapshot, hasWalks:() => sessions.length > 0};
}

Plan

A JavaScript module in the jobs folder of GridAtlas that prepares gate job (`prepareGateJob`). It prepares gate job (`prepareGateJob`).

transformgridatlas / tools/satnav/walk/gate/jobs/plan.mjs · lines 1–68 of 68 · Not reached from any entry point (candidate for review) · pattern point (shared by 35 files)

What it does
It calculates its inputs. Defines label, point, prepareGateJob.
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
Coordinate systems named: WGS84 / EPSG:4326.
Downstream impact
Used directly by 1 file: Plan Test (gridatlas).
What it achieves
Defines `label`, `point` and `prepareGateJob`.
Why it matters
Checked by Plan Test.
Application
gridatlas · tools/satnav/walk/gate/jobs · JavaScript module
Uses
Handoff (import)
Used by
imported by Plan Test (import)
Produces
JOB_SCHEMA, prepareGateJob
Defines here
label, point, prepareGateJob
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/jobs/plan.mjs:1-68 · blob 42173570888be9cb77732be912107210b06682a9 · 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: unreached_review
import {createGateHandoff} from '../handoff.mjs';

export const JOB_SCHEMA = 'ventus.satnav.gate-job.v1';

function label(value, field) {
  if (typeof value !== 'string' || !value.trim()) throw Error('Missing ' + field + '.');
  if (value.length > 200) throw Error('Shorten ' + field + ' to 200 characters.');
  return value.trim();
}

function point(value, field) {
  if (!Array.isArray(value) || value.length !== 2 || !value.every(Number.isFinite) ||
      Math.abs(value[0]) > 180 || Math.abs(value[1]) > 90) {
    throw Error('Check ' + field + '. Use [longitude, latitude] in WGS84.');
  }
  return value.slice();
}

// A missing job item rejects the import. An explicitly unavailable or wrong
// approach leaves a complete, named field plan which can be started on foot.
export function prepareGateJob(doc, maths, compass) {
  if (doc?.schema !== JOB_SCHEMA) throw Error('Choose a SatNav entrance job.');
  const input = doc.gate;
  if (!input) throw Error('Missing agreed entrance.');
  const gate = {
    id: label(input.id, 'entrance reference'),
    name: label(input.name, 'entrance name'),
    centre: point(input.centre, 'entrance centre'),
    roadside: point(input.roadside, 'roadside arrival point'),
    fieldSide: point(input.fieldSide, 'point inside the field'),
    widthM: input.widthM,
    agreed: input.agreed === true,
    locked: input.locked ?? false,
  };
  if (!gate.agreed) throw Error('Confirm the agreed entrance for ' + gate.name + '.');
  if (typeof gate.locked !== 'boolean') throw Error('Check the locked status of ' + gate.name + '.');
  if (!Number.isFinite(gate.widthM) || gate.widthM <= 0) throw Error('Enter the measured opening width in metres for ' + gate.name + '.');
  if (maths.distanceKm(...gate.centre, ...gate.fieldSide) * 1000 < 3) throw Error('Place the field-side point at least 3 m inside ' + gate.name + '.');

  const roadStart = point(doc.roadStart, 'start of the saved driving approach');
  const assetName = label(doc.assetName, 'asset name');
  if (!Array.isArray(doc.fieldPins) || !doc.fieldPins.length || doc.fieldPins.length >= 20000) {
    throw Error('Provide 1 to 19,999 ordered field pins ending at ' + assetName + '.');
  }
  const ids = new Set([gate.id]);
  const fieldPins = doc.fieldPins.map((pin, index) => {
    const field = 'field pin ' + (index + 1);
    const id = label(pin?.id, field + ' reference');
    if (ids.has(id)) throw Error('Use a unique reference for ' + field + '.');
    ids.add(id);
    return {id, name:label(pin.name, field + ' name'), coordinate:point(pin.coordinate, field)};
  });
  if (fieldPins.at(-1).name !== assetName) throw Error('The last field pin must be the destination, ' + assetName + '.');
  if (!Object.hasOwn(doc, 'savedRoad')) throw Error('Missing saved driving approach. Supply savedRoad, or null for a field-only job.');

  const plan = {gate, assetName, roadStart, fieldPins, synthetic:doc.synthetic === true};
  const model = createGateHandoff(plan, maths, compass);
  const bearing = maths.initialBearingDeg(...gate.centre, ...gate.fieldSide);
  const roadsideBearing = maths.initialBearingDeg(...gate.centre, ...gate.roadside);
  const offset = maths.distanceKm(...gate.centre, ...gate.roadside) * 1000;
  const angle = (roadsideBearing - bearing) * Math.PI / 180;
  const besideGate = offset <= 35 && offset * Math.cos(angle) < -1 && Math.abs(offset * Math.sin(angle)) <= gate.widthM / 2;
  let warning = '';
  if (doc.savedRoad === null) warning = 'Saved road unavailable for ' + gate.name;
  else if (!besideGate || !model.setRoad(doc.savedRoad)) warning = 'Check the saved driving approach to ' + gate.name;
  const geometry = !warning ? doc.savedRoad.response.routes[0].geometry : null;
  return {plan, model, geometry, warning};
}