In this section
- Layout Import Test test · gridatlas / tools/satnav/interchange/layout-import.test.mjs lines 1–170
- SatNav Line Browser render · gridatlas / tools/satnav/line-browser.py lines 1–216
- Orient15 Recovery transform · gridatlas / tools/satnav/line/orient15-recovery.mjs lines 1–113
- Orient15 Recovery Test test · gridatlas / tools/satnav/line/orient15-recovery.test.mjs lines 1–63
- Orient16 Recovery Safe transform · gridatlas / tools/satnav/line/orient16-recovery-safe.mjs lines 1–120
Layout Import Test
A test in the interchange folder of GridAtlas that checks Layout Import and GeoJSON Interchange, using EPSG:27700.
testgridatlas / tools/satnav/interchange/layout-import.test.mjs · lines 1–170 of 170 · Entry point · pattern feature (shared by 12 files)
- What it does
- It tests cables and 33kV. Defines feature, collection, fix. Uses libraries node:test, node:assert/strict, node:fs. 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. Domain terms in the code: cables, 33kV.
- Inputs & outputs
- Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid). Voltage levels named: 33kV.
- Downstream impact
- Used directly by 1 file: GridAtlas PR File Size Guard Workflow (gridatlas).
- What it achieves
- Defines `feature`, `collection` and `fix`. Its code works with 33 kV. It reads `./fixtures/native-gis-sld.geojson`.
- Why it matters
- Run by GridAtlas PR File Size Guard Workflow.
- Application
- gridatlas · tools/satnav/interchange · test
- Uses
- Layout Import (import), GeoJSON Interchange (import), node:test, node:assert/strict, node:fs
- Used by
- run by GridAtlas PR File Size Guard Workflow (workflow run)
- Produces
- feature, collection, fix
- Defines here
- feature, collection, 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/interchange/layout-import.test.mjs:1-170 · blob c8a36f60ceec8b91152950093652040ef61eb65e · 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 test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { readLayout, layoutChoices, walkLayoutChoice } from './layout-import.mjs';
import { exportGeoJSON as legacySurvey } from './geojson-interchange.mjs';
const A = [-1.1, 52], B = [-1.101, 52.001], C = [-1.102, 52];
const feature = (type, coordinates, properties = {}) => ({ type: 'Feature', geometry: { type, coordinates }, properties });
const collection = (...features) => ({ type: 'FeatureCollection', features });
const snapshot = {
schema: 'ventus.gis-route.v1', status: 'available', committed: true, pins: [{ financialOnly: true }],
route: feature('LineString', [A, B], {type: 'export_cable', export_cable_length_km: 0.14, measurement_method: 'manual'}),
};
const fix = (coords, timestampMs) => feature('Point', coords, { satnavRole: 'walked-fix', timestampMs, accuracyM: 4 });
test('reads the GIS snapshot route and preserves the finance model', () => {
const original = structuredClone(snapshot);
const result = readLayout(snapshot);
assert.deepEqual(result.features[0], feature('LineString',[A,B],{satnavRole:'planned-route', type:'export_cable'}));
result.features[0].geometry.coordinates[0][0] = 0;
assert.deepEqual(snapshot, original);
for (const status of ['empty','editing','ambiguous','invalid','unavailable']) {
assert.throws(() => readLayout({ ...snapshot, status }));
}
});
test('walks the export cable in a full GIS SLD engineering file without connecting equipment points', () => {
const equipments = Array.from({length: 52}, () => feature('Point', C, {type: 'central_inverter'}));
const data = collection(
...equipments,
feature('Point', A, {type: 'poi', selected_substation_name: 'Test grid node'}),
feature('LineString', [B, C], {type: '33kv_radial', role: 'collector_trunk'}),
feature('LineString', [A, B], {type: '33kv_radial', role: 'block_branch'}),
feature('Point', C, {type: 'export_cable_pin', pin_index: 1, committed_to_route: true}),
feature('Polygon', [[A, B, C, A]], {type: 'array_boundary', fin_total_capex_gbp: 100}),
feature('LineString', [A, C, B], {type: 'export_cable', routed_by_pins: true}),
fix(B, 100),
);
const before = structuredClone(data);
const result = readLayout(data);
const choices = layoutChoices(result);
assert.equal(choices[0].label, 'Export cable 1');
assert.equal(choices.some(c => c.role === 'waypoints'), false);
const names = choices.map(c => c.label);
for (const label of ['Test grid node', 'Central inverter 52', '33 kV collector trunk 1',
'33 kV block branch 1', 'Cable pin 1', 'Array boundary 1']) assert.ok(names.includes(label));
let selected;
walkLayoutChoice({replacePlan: points => { selected = points; }}, result, choices[0]);
assert.deepEqual(selected, [A, C, B]);
assert.deepEqual(readLayout(JSON.stringify(result)), result);
assert.deepEqual(data, before);
assert.ok(!JSON.stringify(result).includes('fin_total_capex_gbp'));
});
test('recognised GIS electrical roles cannot promote a measured track or bypass other role checks', () => {
const measured = feature('LineString', [A, B], {
type: '33kv_radial', role: 'collector_trunk', satnavRole: 'walked-track',
timestampMs: [5, 8],
});
assert.deepEqual(layoutChoices(readLayout(measured)), []);
for (const props of [
{type: '33kv_radial', role: 'walked-track', satnavRole: 'planned-route'},
{type: 'export_cable', role: 'collector_trunk'},
{type: '33kv_radial', role: 'unrecognised'},
]) assert.throws(() => readLayout(feature('LineString', [A, B], props)));
});
test('round-trips a financial sandbox drawing exported by the native pinned scripts', () => {
// Synthetic controls, two central inverter blocks and one committed cable pin.
// gis-sld-v5-drawing.js fd8e16f and gis-sld-v5-export.js 619f4f9, release 202609052024.
const raw = JSON.parse(readFileSync(new URL('./fixtures/native-gis-sld.geojson', import.meta.url), 'utf8'));
const cable = raw.features.find(f=>f.properties.type === 'export_cable');
assert.equal(raw.features.length, 15);
const result = readLayout(raw);
const choices = layoutChoices(result);
assert.deepEqual(choices[0], {index:2, label:'Export cable 1', role:'planned-route'});
assert.ok(choices.some(c=>c.label === '33 kV collector trunk 1'));
assert.ok(choices.some(c=>c.label === '33 kV block branch 2'));
assert.ok(choices.some(c=>c.label === 'Central inverter 2'));
assert.equal(choices.some(c=>c.role === 'waypoints'), false);
let plan;
walkLayoutChoice({replacePlan: points=>{plan=points;}},result,choices[0]);
assert.deepEqual(plan,cable.geometry.coordinates);
assert.deepEqual(readLayout(JSON.stringify(result)),result);
assert.ok(!JSON.stringify(result).includes('fin_total_capex_gbp'));
raw.features.push(feature('LineString',[A,C],{type:'33kv_projection_only'}),feature('Point',B));
const extended = readLayout(raw);
assert.equal(layoutChoices(extended).some(c=>c.index === 15 || c.role === 'waypoints'),false);
assert.throws(()=>walkLayoutChoice({},extended,{index:15}),/design/);
});
test('ordered waypoints, selected cable and perimeter become plans; individual point changes TO', () => {
const layout = readLayout(collection(feature('Point', A, { name: 'Start' }), feature('Point', B),
feature('LineString', [B,C]), feature('Polygon', [[A,B,C,A]])));
const choices = layoutChoices(layout);
const applied = [];
const survey = { setDestination: p => applied.push(['to',p]), replacePlan: p => applied.push(['plan',p]) };
for (const i of [0,1,3,4]) walkLayoutChoice(survey, layout, choices[i]);
assert.deepEqual(applied, [['plan',[A,B]],['to',A],['plan',[B,C]],['plan',[A,B,C,A]]]);
applied[1][1][0] = 0;
assert.deepEqual(layout.features[0].geometry.coordinates, A);
});
test('retains separate recorded segments and exact singletons through a GeoJSON round trip', () => {
const survey = collection(feature('LineString',[A,B],{satnavRole:'planned-route',name:'Cable'}),
feature('LineString',[A,B],{satnavRole:'walked-track',timestampMs:[100,102],accuracyM:[4,5]}),
fix(C,150));
const actual = readLayout(survey);
assert.deepEqual(readLayout(JSON.stringify(actual)), survey);
assert.deepEqual(layoutChoices(actual).map(c=>c.label),['Cable']);
for (const index of [1,2]) assert.throws(() => walkLayoutChoice({},actual,{index}), /design/);
assert.deepEqual(layoutChoices(readLayout(fix(C,150))), []);
});
test('imports original ordered-fix survey codec without promoting fixes to design points', () => {
const file = legacySurvey({ pins:[A,B], plannedRoute:[A,B], walkedTrack:[
{ coordinate:A, timestamp:10, accuracy:3 }, { coordinate:C, timestamp:20, accuracy:4 },
]});
file.features.reverse();
const got = readLayout(file);
assert.deepEqual(got.features.map(f=>f.properties.satnavRole),['waypoint','waypoint','planned-route','walked-fix','walked-fix']);
assert.deepEqual(got.features[3], feature('Point',A,{ satnavRole:'walked-fix',timestampMs:10,accuracyM:3,order:0 }));
assert.deepEqual(readLayout(JSON.stringify(got)), got);
});
test('rejects ambiguous or invalid geometry, roles, IDs, measurement and reference systems', () => {
const item = feature('Point', A);
const projected = {type:'name',properties:{name:'EPSG:27700'}};
for (const file of [
feature('Point',[1,100]),
feature('Polygon',[[A,B,C,A],[A,B,C,A]]),
collection({...item,id:4},{...item,id:4}),
feature('Point',A,{ satnavRole:'waypoint',role:'walked-fix',timestamp:1,accuracy:4 }),
feature('Point',A,{ satnavRole:'walked-fix',accuracyM:-1 }),
feature('LineString',[A,B],{ satnavRole:'walked-track',timestampMs:[20,10],accuracyM:[1,1] }),
{ ...item, crs:projected }, {...snapshot, route:{...snapshot.route,crs:projected}},
{ ...item,geometry:{...item.geometry,crs:projected}},
{ type:'FeatureCollection',features:[] }, {type:'GeometryCollection',geometries:[]},
]) assert.throws(() => readLayout(file));
assert.deepEqual(readLayout({...item,crs:{type:'name',properties:{name:'OGC:CRS84'}}}), readLayout(item));
});
test('a measured fix with unknown accuracy remains a recorded point', () => {
const recorded = readLayout(feature('Point', A, { role: 'walked-fix', timestamp: 230 }));
assert.deepEqual(recorded.features[0].properties, {satnavRole:'walked-fix',timestampMs:230});
assert.deepEqual(layoutChoices(recorded), []);
});
test('orders source pins by explicit order and a singleton by its global recorded sample index', () => {
const data = collection(feature('Point',B,{role:'waypoint',order:1}),feature('Point',A,{role:'waypoint',order:0}),
feature('LineString',[A,B],{role:'walked-track'}),feature('Point',C,{role:'walked-fix',order:2,timestamp:40,accuracy:3}));
const result = readLayout(data);
assert.deepEqual(result.features.slice(0,2).map(f=>f.geometry.coordinates),[A,B]);
assert.deepEqual(result.features[3].properties, {satnavRole:'walked-fix',order:2,timestampMs:40,accuracyM:3});
});
test('labels the separate GIS export cable and radial circuit for selection', () => {
const result = readLayout(collection(feature('LineString',[A,B],{type:'export_cable'}),
feature('LineString',[B,C],{type:'33kv_radial'})));
assert.deepEqual(layoutChoices(result).map(choice=>choice.label), ['Export cable 1','33 kV radial 1']);
});
test('supports the full 20,000-pin design, its line and 20,000 recorded positions together', () => {
const route = Array.from({length:20000},(_,i)=>[i/1000,50]);
const track = feature('LineString',route,{satnavRole:'walked-track'});
const pins = route.map(at => feature('Point', at));
const layout = readLayout(collection(...pins,feature('LineString',route),track));
assert.equal(layout.features.length,20002);
assert.throws(() => readLayout(collection(...layout.features, track)), /20,000/);
});SatNav Line Browser
A Python command-line tool in the tools folder of GridAtlas using data from the SatNav repository. It maps canvas tap (`map_canvas_tap`), checks basemap (`check_basemap`) and checks browser (`check_browser`).
rendergridatlas / tools/satnav/line-browser.py · lines 1–216 of 216 · Entry point · pattern surface_distance (shared by 2 files)
- What it does
- It lists and searches its content. Defines 7 functions or classes, including surface_distance, leg_point, map_canvas_tap, overlay_roles, check_basemap. Uses libraries math, os, re, urllib.parse, playwright.sync_api. Side effects: changes the web page (DOM).
- 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
- Detached browser checks for the GridAtlas line-tracking practice preview.
- 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
- math, os, re, urllib.parse, playwright.sync_api
- Used by
- none found
- Produces
- surface_distance, leg_point, map_canvas_tap, overlay_roles, check_basemap, check_browser, run
- Defines here
- surface_distance, leg_point, map_canvas_tap, overlay_roles, check_basemap, check_browser, 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/line-browser.py:1-216 · blob 2b634a3c360769fe70e7875a9d9277bfadd1a0cc · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
"""Detached browser checks for the GridAtlas line-tracking practice preview."""
import math
import os
import re
from urllib.parse import parse_qs, urlsplit
from playwright.sync_api import expect, sync_playwright
SITE = os.environ.get(
'LINE_TEST_URL', 'http://127.0.0.1:8873/atlas/v/satnav-line-preview/'
)
P1 = 'https://ventusltd.github.io/satnav/preview/9698781539e549deaa6ecaa4a2b34610c1f9fd29/nav/'
SOURCE = 'gridatlas-satnav-line-position'
SECTION = 'selected-section'
MEASURED = 'measured-gps'
RING = 'gps-accuracy'
NEAREST = 'nearest-on-section'
GPS_SPY = """(() => {
let nextId = 0;
const watches = new Map();
const records = { starts: [], stops: [] };
Object.defineProperty(navigator, 'geolocation', {
configurable: true,
value: {
watchPosition(success, error) {
const id = ++nextId;
watches.set(id, { success, error });
records.starts.push(id);
return id;
},
clearWatch(id) {
records.stops.push(id);
watches.delete(id);
},
},
});
window.__lineGpsTest = {
records,
emit(coordinates, accuracy, age = 0) {
const coords = { longitude: coordinates[0], latitude: coordinates[1], accuracy };
const result = { coords, timestamp: Date.now() - age };
for (const { success } of watches.values()) success(result);
},
};
})()"""
def surface_distance(first, second):
lon1, lat1 = map(math.radians, first)
lon2, lat2 = map(math.radians, second)
a = math.sin((lat2 - lat1) / 2) ** 2
b = math.cos(lat1) * math.cos(lat2) * math.sin((lon2 - lon1) / 2) ** 2
return 6_371_000 * 2 * math.asin(min(1, math.sqrt(a + b)))
def leg_point(start, end, fraction, offset):
lon, lat = [a + (b - a) * fraction for a, b in zip(start, end)]
x_scale = 111_195 * math.cos(math.radians(lat))
y_scale = 111_195
east = (end[0] - start[0]) * x_scale
north = (end[1] - start[1]) * y_scale
norm = math.hypot(east, north)
return [lon + offset * north / (norm * x_scale), lat - offset * east / (norm * y_scale)]
def map_canvas_tap(page, excluded=None):
target = page.wait_for_function("""excluded => {
const map = window.__GRIDATLAS_V9_MAP__;
if (map.isMoving()) return null;
const canvas = map.getCanvas();
const rect = canvas.getBoundingClientRect();
for (const fraction of [.83, .74, .65, .54, .44]) {
const y = Math.round(rect.top + rect.height * fraction);
for (const side of [.24, .7, .42, .57]) {
const x = Math.round(rect.left + rect.width * side);
if (excluded && Math.hypot(x - excluded.x, y - excluded.y) < 90) continue;
if (document.elementFromPoint(x, y) !== canvas) continue;
return {x, y, coordinates: map.unproject([x - rect.left, y - rect.top]).toArray()};
}
}
return null;
}""", arg=excluded, timeout=15000).json_value()
page.touchscreen.tap(target['x'], target['y'])
return target
def overlay_roles(page, required, absent=()):
data = page.wait_for_function("""({source, required, absent}) => {
const data = window.__GRIDATLAS_V9_MAP__?.getSource(source)?.serialize()?.data;
if (!Array.isArray(data?.features)) return null;
const found = Object.fromEntries(data.features.map(feature => [feature.properties.role, feature]));
return required.every(role => found[role]) && absent.every(role => !found[role]) ? found : null;
}""", arg={'source': SOURCE, 'required': required, 'absent': absent}, timeout=15000)
return data.json_value()
def check_basemap(page, selector, visibility, geometry):
page.locator(selector).tap()
page.wait_for_function(
"""visibility => window.__GRIDATLAS_V9_MAP__.getLayoutProperty('l-sat', 'visibility') === visibility""",
arg=visibility,
)
assert overlay_roles(page, [SECTION])[SECTION]['geometry']['coordinates'] == geometry
def check_browser(browser, label):
context = browser.new_context(
viewport={'width': 390, 'height': 664},
is_mobile=True,
has_touch=True,
)
context.add_init_script(GPS_SPY)
page = context.new_page()
errors = []
page.on('pageerror', lambda error: errors.append(str(error)))
page.goto(SITE, wait_until='domcontentloaded')
page.wait_for_function("window.__GRIDATLAS_V9_MAP__?.getLayer('l-sat')", timeout=45000)
expect(page.locator('#line-open')).to_be_visible(timeout=45000)
page.locator('#line-open').tap()
page.locator('#line-draw').tap()
assert page.evaluate('window.__lineGpsTest.records.starts') == []
page.evaluate("""window.__GRIDATLAS_V9_MAP__.jumpTo({center: [-1.5, 51.5], zoom: 15})""")
discarded_point = map_canvas_tap(page)
overlay_roles(page, ['start-point'], absent=[SECTION])
page.locator('#line-cancel').tap()
expect(page.locator('#line-status')).to_have_text('Selection cancelled.')
map_canvas_tap(page, discarded_point)
overlay_roles(page, [], absent=['start-point', SECTION])
print(f'{label}: cancellation removes the start point and disarms map taps', flush=True)
page.locator('#line-draw').tap()
first = map_canvas_tap(page)
second = map_canvas_tap(page, first)
expected_section = [first['coordinates'], second['coordinates']]
selected = overlay_roles(page, [SECTION])[SECTION]
geometry = selected['geometry']['coordinates']
assert len(geometry) == 2
assert 80 < surface_distance(*geometry) < 1000
for expected, actual in zip(expected_section, geometry):
assert surface_distance(expected, actual) < 2, 'Selected vertex differs from canvas tap'
assert page.evaluate('window.__lineGpsTest.records.starts') == []
print(f'{label}: two real map taps created a practice section without starting GPS', flush=True)
check_basemap(page, '#line-satellite', 'visible', geometry)
check_basemap(page, '#line-dark', 'none', geometry)
print(f'{label}: dark and satellite controls preserved the selected section', flush=True)
expect(page.locator('#line-start')).to_be_enabled()
page.locator('#line-start').tap()
assert page.evaluate('window.__lineGpsTest.records.starts') == [1]
expected_fix = leg_point(*geometry, fraction=0.35, offset=40)
page.evaluate('at => window.__lineGpsTest.emit(at, 8)', expected_fix)
overlay = overlay_roles(page, [SECTION, MEASURED, RING, NEAREST])
actual_fix = overlay[MEASURED]['geometry']['coordinates']
nearest = overlay[NEAREST]['geometry']['coordinates']
assert actual_fix == expected_fix, 'Measured GPS has been moved'
assert abs(surface_distance(actual_fix, nearest) - 40) < 2
ring = overlay[RING]['geometry']['coordinates'][0]
assert len(ring) >= 25 and ring[0] == ring[-1]
assert all(abs(surface_distance(actual_fix, edge) - 8) < 0.2 for edge in ring), (
'Accuracy ring must be centred on measured GPS'
)
assert overlay[SECTION]['geometry']['coordinates'] == geometry
expect(page.locator('#line-accuracy')).to_contain_text('8')
offset = re.search(r'([0-9]+(?:\.[0-9]+)?)\s*m\b', page.locator('#line-offset').inner_text())
assert offset and abs(float(offset[1]) - 40) < 2
expect(page.locator('#line-progress')).to_be_visible()
before_progress = page.locator('#line-progress').inner_text()
next_fix = leg_point(*geometry, fraction=0.65, offset=40)
page.evaluate('at => window.__lineGpsTest.emit(at, 8)', next_fix)
expect(page.locator('#line-progress')).not_to_have_text(before_progress)
print(f'{label}: exact GPS marker, 8 m accuracy circle, separate 40 m offset and updating progress', flush=True)
page.evaluate('at => window.__lineGpsTest.emit(at, 75)', expected_fix)
overlay_roles(page, [SECTION, MEASURED, RING], absent=[NEAREST])
page.evaluate('at => window.__lineGpsTest.emit(at, 8, 12000)', expected_fix)
overlay_roles(page, [SECTION], absent=[MEASURED, RING, NEAREST])
page.locator('#line-stop').tap()
assert page.evaluate('window.__lineGpsTest.records.stops') == [1]
assert not errors, errors
print(f'{label}: poor and stale data withheld projection and Stop cleared the watch', flush=True)
page.locator('#line-compass').tap()
page.wait_for_url(P1 + '?*', timeout=20000)
expect(page.locator('#destination')).to_have_text('Practice line end', timeout=20000)
params = parse_qs(urlsplit(page.url).query)
assert params['mode'] == ['compass']
destination = [float(params['longitude'][0]), float(params['latitude'][0])]
assert surface_distance(geometry[-1], destination) < 0.01
assert page.evaluate('window.__lineGpsTest.records.starts') == []
print(f'{label}: compass handoff kept the exact end point and waited for Start', flush=True)
context.close()
def run():
requested = os.environ.get('LINE_TEST_BROWSERS', 'webkit,chromium').split(',')
with sync_playwright() as playwright:
for engine in requested:
options = {}
if engine == 'chromium':
options['args'] = [
'--enable-webgl', '--use-gl=angle', '--use-angle=swiftshader',
'--enable-unsafe-swiftshader',
]
browser = getattr(playwright, engine).launch(**options)
try:
check_browser(browser, engine)
finally:
browser.close()
if __name__ == '__main__':
run()Orient15 Recovery
A JavaScript module in the line folder of GridAtlas that sets journey (`setJourney`). It creates recovery (`createRecovery`) and sets journey (`setJourney`).
transformgridatlas / tools/satnav/line/orient15-recovery.mjs · lines 1–113 of 113 · Not reached from any entry point (candidate for review) · pattern createRecovery (shared by 3 files)
- What it does
- It calculates its inputs. Defines 22 functions or classes, including point, finite, createRecovery, now, policy.
- 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: Orient15 Recovery Test (gridatlas).
- What it achieves
- Defines `point`, `finite`, `createRecovery` and 19 more.
- Why it matters
- Checked by Orient15 Recovery Test.
- Application
- gridatlas · tools/satnav/line · JavaScript module
- Uses
- Route Follower (import)
- Used by
- imported by Orient15 Recovery Test (import)
- Produces
- policies, createRecovery
- Defines here
- point, finite, createRecovery, now, policy, usable, clearOutput, cancel, clearRoute, invalidate, snapshot, setJourney, start, stop, pause, resume, network, requestRoute, current, evaluate, tick, ingest
- 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/line/orient15-recovery.mjs:1-113 · blob f2611fbf6103e07709271ad2941de3863d55bd1e · 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
// SPDX-License-Identifier: Apache-2.0
// ORIENT-15 candidate: pure recovery ownership; no GPS watch, camera writes or network service.
import {createRouteFollower} from './route-follower.mjs';
export const policies = Object.freeze({
walking:Object.freeze({margin:20,accuracy:15,maxSpeed:3,fixAge:8000,confirm:3,span:2000}),
driving:Object.freeze({margin:35,accuracy:30,maxSpeed:55,fixAge:5000,confirm:3,span:2000}),
direct:Object.freeze({accuracy:30,fixAge:10000})
});
const point=p=>Array.isArray(p)&&p.length===2&&p.every(Number.isFinite)&&Math.abs(p[0])<=180&&Math.abs(p[1])<=90;
const finite=n=>Number.isFinite(n);
export function createRecovery({maths,provider=null,clock=Date.now,timeoutMs=8000,cooldownMs=10000}){
if(!finite(timeoutMs)||timeoutMs<=0||!finite(cooldownMs)||cooldownMs<0)throw Error('INVALID_BUDGET');
let mode='walking',target=null,objective='shortest',revision=0,serial=0,fix=null,last=-Infinity,online=true,active=false,paused=false;
let route=null,pending=null,progress=null,off=[],attemptAt=-Infinity,status='choose',output=null;
const now=()=>clock();
const policy=()=>policies[mode];
const usable=(f,t)=>f&&point([f.longitude,f.latitude])&&finite(f.accuracyM)&&f.accuracyM>=0&&f.accuracyM<=policy().accuracy&&finite(f.timestampMs)&&f.timestampMs<=t&&t-f.timestampMs<=policy().fixAge;
const clearOutput=()=>{output=null;};
function cancel(){const p=pending;pending=null;if(p)p.abort.abort();}
function clearRoute(){route=null;progress=null;off=[];clearOutput();}
function invalidate(next){cancel();clearRoute();status=next;}
function snapshot(){
return {mode,target:target?.slice()??null,objective,revision,status,active,follow:!paused,
request:pending?.id??null,geometry:output?.kind==='route'?structuredClone(route.geometry):null,
instruction:output?structuredClone(output):null};
}
function setJourney({mode:m,target:t,objective:o='shortest'}){
if(!Object.hasOwn(policies,m)||!point(t)||!['shortest','fastest'].includes(o)||(m!=='driving'&&o!=='shortest'))throw Error('INVALID_JOURNEY');
revision++;invalidate('ready');mode=m;target=t.slice();objective=o;active=false;attemptAt=-Infinity;
// Explicit mode selection is required. Existing fix and camera pause are retained.
return snapshot();
}
function start(){if(!target)return snapshot();active=true;status='waiting-gps';return tick();}
function stop(){active=false;invalidate('stopped');return snapshot();}
function pause(){paused=true;return snapshot();}
function resume(){paused=false;return snapshot();}
function network(value){
online=Boolean(value);
if(active&&mode!=='direct'&&!online)invalidate('offline');
if(online&&status==='offline'){attemptAt=-Infinity;status='waiting-gps';return tick();}
return snapshot();
}
function requestRoute(t){
if(pending||!active||mode==='direct'||!online||!usable(fix,t))return;
if(!provider){status='unavailable';return;}
if(t-attemptAt<cooldownMs){status='retry-wait';return;}
attemptAt=t;clearRoute();status='routing';
const job={id:++serial,revision,deadline:t+timeoutMs,abort:new AbortController()};
pending=job;
const req={mode,objective,target:target.slice(),origin:[fix.longitude,fix.latitude],revision,requestId:job.id,signal:job.abort.signal};
const current=()=>pending===job&&job.revision===revision&&active&&online&&mode===req.mode;
Promise.resolve().then(()=>{if(current())return provider(req);}).then(result=>{
if(!current())return;
if(now()>=job.deadline||!usable(fix,now())){invalidate('waiting-gps');return;}
pending=null;
if(result?.eligible!==true||result?.graphRevision==null||result?.requestId!==job.id||result?.revision!==revision||result?.mode!==mode||result?.objective!==objective){invalidate('unavailable');return;}
try{
const geometry=structuredClone(result.geometry);
const locate=createRouteFollower(geometry,maths);
route={geometry,locate,graphRevision:result.graphRevision};
status='tracking';evaluate(fix,now());
}catch{invalidate('unavailable');}
}).catch(()=>{if(current())invalidate('unavailable');});
}
function evaluate(f,t){
clearOutput();
if(mode==='direct'){
const d=maths.distanceKm(f.longitude,f.latitude,...target)*1000;
const b=d>0?maths.initialBearingDeg(f.longitude,f.latitude,...target):null;
if(!finite(d)||d<0){status='uncertain';return;}
status='manual';output={kind:'direct',distanceM:d,bearingDeg:finite(b)?b:null};return;
}
if(!online){invalidate('offline');return;}
if(!route){requestRoute(t);return;}
const p=route.locate(f,t);
if(p.status!=='ok'||!finite(p.progressM)||!finite(p.offsetM)){off=[];status='uncertain';return;}
const q=policy();
if(p.offsetM-f.accuracyM>q.margin){
status='suspect';if(off.at(-1)!==f.timestampMs)off.push(f.timestampMs);
if(off.length>q.confirm)off.shift();
if(off.length===q.confirm&&off.at(-1)-off[0]>=q.span){invalidate('deviated');requestRoute(t);}
return;
}
off=[];
if(progress){
const dt=(f.timestampMs-progress.time)/1000;
const allowance=q.maxSpeed*Math.max(0,dt)+f.accuracyM+progress.accuracy+10;
if(dt<0||Math.abs(p.progressM-progress.metres)>allowance){status='uncertain';return;}
}
progress={metres:p.progressM,time:f.timestampMs,accuracy:f.accuracyM};
status='tracking';
output={kind:'route',remainingM:p.remainingM,segmentIndex:p.segmentIndex,next:route.geometry.coordinates[p.segmentIndex+1].slice(),graphRevision:route.graphRevision};
}
function tick(){
if(!active)return snapshot();
const t=now();
if(!usable(fix,t)){invalidate('waiting-gps');return snapshot();}
if(mode!=='direct'&&!online){invalidate('offline');return snapshot();}
if(pending&&t>=pending.deadline){invalidate('timeout');return snapshot();}
if(!pending)evaluate(fix,t);
return snapshot();
}
function ingest(f){
const t=now();
if(!active)return snapshot();
if(!finite(f?.timestampMs)||f.timestampMs<=last)return tick();
// A future timestamp must not poison the ordering ledger.
if(f.timestampMs>t){invalidate('waiting-gps');return snapshot();}
last=f.timestampMs;fix={...f};
return tick();
}
return {setJourney,start,stop,pause,resume,network,ingest,tick,snapshot};
}Orient15 Recovery Test
A test in the line folder of GridAtlas that checks Orient15 Recovery. It is built from the sample step (`sample`).
testgridatlas / tools/satnav/line/orient15-recovery.test.mjs · lines 1–63 of 63 · Not reached from any entry point (candidate for review) · pattern harness (shared by 3 files)
- What it does
- It tests its inputs. Defines xy, settle, harness, provider, sample. Uses libraries 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.
- What it achieves
- Defines `settle`, `harness`, `provider` and 1 more.
- Why it matters
- Guards the behaviour of Orient15 Recovery.
- Application
- gridatlas · tools/satnav/line · test
- Uses
- Orient15 Recovery (import), node:assert/strict
- Used by
- none found
- Produces
- xy, settle, harness, provider, sample
- Defines here
- xy, settle, harness, provider, sample
- 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/line/orient15-recovery.test.mjs:1-63 · blob 4e2fa4aba5fbfff893d103f7dc24e2e9e5a3d27a · 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
// SPDX-License-Identifier: Apache-2.0
import assert from 'node:assert/strict';
import {createRecovery} from './orient15-recovery.mjs';
let checks=0;const eq=(a,b)=>{assert.deepEqual(a,b);checks++;};
const xy=(x,y)=>[x/100000,y/100000];
const maths={distanceKm:(a,b,c,d)=>Math.hypot(c-a,d-b)*100,
initialBearingDeg:(a,b,c,d)=>(Math.atan2(c-a,d-b)*180/Math.PI+360)%360,
distanceToSegmentKm:(x,y,a,b,c,d)=>{const t=Math.max(0,Math.min(1,((x-a)*(c-a)+(y-b)*(d-b))/((c-a)**2+(d-b)**2)));const foot=[a+t*(c-a),b+t*(d-b)];return {t,foot,km:Math.hypot(x-foot[0],y-foot[1])*100};}};
const settle=async()=>{for(let i=0;i<8;i++)await Promise.resolve();};
function harness(opts={}){
let t=100000;const calls=[];
const provider=req=>new Promise(resolve=>calls.push({req,resolve}));
const c=createRecovery({maths,provider,clock:()=>t,timeoutMs:4000,cooldownMs:0,...opts});
const sample=(x,y,a=4,advance=1000)=>{t+=advance;return c.ingest({longitude:xy(x,y)[0],latitude:xy(x,y)[1],accuracyM:a,timestampMs:t});};
const journey=(mode='walking',target=xy(200,0),objective='shortest')=>{c.setJourney({mode,target,objective});c.start();};
const resolve=(i,coords=[xy(0,0),xy(200,0)],over={})=>{const {req}=calls[i];calls[i].resolve({eligible:true,graphRevision:'synthetic-A',requestId:req.requestId,revision:req.revision,mode:req.mode,objective:req.objective,geometry:{type:'LineString',coordinates:coords},...over});};
return {c,calls,sample,journey,resolve,advance:n=>{t+=n;return c.tick();}};
}
for(const mode of ['walking','driving']){
const h=harness();h.journey(mode);h.sample(0,0);await settle();eq(h.calls.length,1);h.resolve(0);await settle();eq(h.c.snapshot().status,'tracking');
const offset=mode==='walking'?30:45;
eq(h.sample(5,offset).status,'suspect');eq(h.c.snapshot().geometry,null);eq(h.sample(6,offset).status,'suspect');
// Same fix/tick must not count as an independent observation.
for(let i=0;i<10;i++)eq(h.c.tick().status,'suspect');
eq(h.sample(7,offset).status,'routing');await settle();eq(h.calls.length,2);eq(h.calls[1].req.origin,xy(7,offset));eq(h.c.snapshot().target,xy(200,0));
h.resolve(1,[xy(7,offset),xy(200,0)]);await settle();eq(h.c.snapshot().status,'tracking');
eq(h.c.network(false).geometry,null);eq(h.c.snapshot().status,'offline');eq(h.c.network(true).status,'routing');await settle();eq(h.calls.length,3);
h.c.stop();eq(h.calls[2].req.signal.aborted,true);h.resolve(2);await settle();eq(h.c.snapshot().status,'stopped');eq(h.c.snapshot().instruction,null);
}
{
const h=harness();h.journey('driving');h.sample(0,0);await settle();h.resolve(0);await settle();
eq(h.sample(3,30).status,'tracking'); // same displacement is suspect for walking
eq(h.sample(4,0,50).status,'waiting-gps');eq(h.c.snapshot().geometry,null);
h.sample(5,0);await settle();eq(h.calls.length,2);h.resolve(1);await settle();
eq(h.advance(5001).status,'waiting-gps');eq(h.c.snapshot().instruction,null);
}
{
const h=harness();h.journey();h.sample(0,0);await settle();eq(h.advance(4000).status,'timeout');eq(h.calls[0].req.signal.aborted,true);h.resolve(0);await settle();eq(h.c.snapshot().geometry,null);
}
{
const h=harness();h.journey();h.sample(0,0);await settle();h.resolve(0,[xy(0,0),xy(100,100),xy(0,100),xy(100,0)]);await settle();
eq(h.sample(50,50).status,'uncertain');eq(h.c.snapshot().instruction,null);eq(h.c.snapshot().geometry,null);
}
{
const h=harness();h.journey();h.sample(0,0);await settle();h.resolve(0);await settle();
eq(h.sample(150,0).status,'uncertain');eq(h.c.snapshot().geometry,null);
}
{
const h=harness({provider:null});h.journey('walking');eq(h.sample(0,0).status,'unavailable');eq(h.c.snapshot().instruction,null);
h.journey('direct');eq(h.sample(10,0).status,'manual');eq(h.c.snapshot().instruction.kind,'direct');eq(h.c.network(false).instruction.kind,'direct');
eq(h.c.pause().follow,false);h.journey('direct',xy(300,0));eq(h.c.snapshot().follow,false);eq(h.c.resume().follow,true);eq(h.c.snapshot().target,xy(300,0));
eq(h.advance(10001).instruction,null);
}
for(let i=0;i<1000;i++){
const h=harness();h.journey('walking');h.sample(0,0);await settle();
h.c.pause();h.journey(i%2?'direct':'driving',xy(400+i,0),i%2?'shortest':'fastest');
eq(h.calls[0].req.signal.aborted,true);h.sample(1,0);await settle();h.resolve(0);await settle();
const s=h.c.snapshot();eq(s.target,xy(400+i,0));eq(s.follow,false);eq(s.geometry,null);
eq(s.instruction?.kind??null,i%2?'direct':null);eq(s.status,i%2?'manual':'routing');
if(i%2===0){h.resolve(1,undefined,{requestId:-1});await settle();eq(h.c.snapshot().status,'unavailable');}
h.c.stop();eq(h.c.snapshot().instruction,null);
}
console.log(JSON.stringify({suite:'ORIENT-15',assertions:checks,raceScenarios:1000,status:'PASS',geometry:'synthetic planar maths; real route-follower imported'}));Orient16 Recovery Safe
A JavaScript module in the line folder of GridAtlas that sets journey (`setJourney`). It creates recovery (`createRecovery`) and sets journey (`setJourney`).
transformgridatlas / tools/satnav/line/orient16-recovery-safe.mjs · lines 1–120 of 120 · Not reached from any entry point (candidate for review) · pattern createRecovery (shared by 3 files)
- What it does
- It calculates its inputs. Defines 23 functions or classes, including point, finite, createRecovery, now, policy.
- 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: Orient16 Recovery Safe Test (gridatlas); Valhalla Provider Test (gridatlas).
- What it achieves
- Defines `point`, `finite`, `createRecovery` and 20 more.
- Why it matters
- Checked by 2 tests, including Orient16 Recovery Safe Test.
- Application
- gridatlas · tools/satnav/line · JavaScript module
- Uses
- Route Follower (import)
- Used by
- imported by Orient16 Recovery Safe Test (import), imported by Valhalla Provider Test (import)
- Produces
- policies, createRecovery
- Defines here
- point, finite, createRecovery, now, policy, usable, clearOutput, cancel, clearRoute, invalidate, snapshot, setJourney, start, stop, pause, resume, network, requestRoute, current, close, evaluate, tick, ingest
- 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/line/orient16-recovery-safe.mjs:1-120 · blob feeb1c776e95e7b3c141428aee21a594d857f81c · 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
// SPDX-License-Identifier: Apache-2.0
// ORIENT-16 derived candidate: pure recovery ownership; no GPS watch, camera writes or network service.
import {createRouteFollower} from './route-follower.mjs';
export const policies = Object.freeze({
walking:Object.freeze({margin:20,accuracy:15,maxSpeed:3,fixAge:8000,confirm:3,span:2000}),
driving:Object.freeze({margin:35,accuracy:30,maxSpeed:55,fixAge:5000,confirm:3,span:2000}),
direct:Object.freeze({accuracy:30,fixAge:10000})
});
const point=p=>Array.isArray(p)&&p.length===2&&p.every(Number.isFinite)&&Math.abs(p[0])<=180&&Math.abs(p[1])<=90;
const finite=n=>Number.isFinite(n);
export function createRecovery({maths,provider=null,clock=Date.now,timeoutMs=8000,cooldownMs=10000,maxAttempts=3}){
if(!finite(timeoutMs)||timeoutMs<=0||!finite(cooldownMs)||cooldownMs<0)throw Error('INVALID_BUDGET');
if(!Number.isInteger(maxAttempts)||maxAttempts<1||maxAttempts>10)throw Error('INVALID_ATTEMPTS');
let attempts=0,terminal=false;
let mode='walking',target=null,objective='shortest',revision=0,serial=0,fix=null,last=-Infinity,online=true,active=false,paused=false;
let route=null,pending=null,progress=null,off=[],attemptAt=-Infinity,status='choose',output=null;
const now=()=>clock();
const policy=()=>policies[mode];
const usable=(f,t)=>f&&point([f.longitude,f.latitude])&&finite(f.accuracyM)&&f.accuracyM>=0&&f.accuracyM<=policy().accuracy&&finite(f.timestampMs)&&f.timestampMs<=t&&t-f.timestampMs<=policy().fixAge;
const clearOutput=()=>{output=null;};
function cancel(){const p=pending;pending=null;if(p)p.abort.abort();}
function clearRoute(){route=null;progress=null;off=[];clearOutput();}
function invalidate(next){cancel();clearRoute();status=next;}
function snapshot(){
return {mode,target:target?.slice()??null,objective,revision,status,active,follow:!paused,
request:pending?.id??null,geometry:output?.kind==='route'?structuredClone(route.geometry):null,
instruction:output?structuredClone(output):null};
}
function setJourney({mode:m,target:t,objective:o='shortest'}){
if(!Object.hasOwn(policies,m)||!point(t)||!['shortest','fastest'].includes(o)||(m!=='driving'&&o!=='shortest'))throw Error('INVALID_JOURNEY');
revision++;invalidate('ready');mode=m;target=t.slice();objective=o;active=false;attemptAt=-Infinity;attempts=0;terminal=false;
// Explicit mode selection is required. Existing fix and camera pause are retained.
return snapshot();
}
function start(){if(!target)return snapshot();active=true;status='waiting-gps';return tick();}
function stop(){active=false;invalidate('stopped');return snapshot();}
function pause(){paused=true;return snapshot();}
function resume(){paused=false;return snapshot();}
function network(value){
online=Boolean(value);
if(active&&mode!=='direct'&&!online)invalidate('offline');
if(online&&status==='offline'){attemptAt=-Infinity;status='waiting-gps';return tick();}
return snapshot();
}
function requestRoute(t){
if(pending||!active||mode==='direct'||!online||!usable(fix,t))return;
if(!provider||terminal){status='unavailable';return;}
if(attempts>=maxAttempts){status='retry-exhausted';return;}
if(t-attemptAt<cooldownMs){status='retry-wait';return;}
attemptAt=t;attempts++;clearRoute();status='routing';
const job={id:++serial,revision,deadline:t+timeoutMs,abort:new AbortController()};
pending=job;
const req={mode,objective,target:target.slice(),origin:[fix.longitude,fix.latitude],revision,requestId:job.id,signal:job.abort.signal};
const current=()=>pending===job&&job.revision===revision&&active&&online&&mode===req.mode;
Promise.resolve().then(()=>{if(current())return provider(req);}).then(result=>{
if(!current())return;
if(now()>=job.deadline||!usable(fix,now())){invalidate('waiting-gps');return;}
pending=null;
if(result?.terminal===true){terminal=true;invalidate('unavailable');return;}
if(result?.eligible!==true||result?.graphRevision==null||result?.requestId!==job.id||result?.revision!==revision||result?.mode!==mode||result?.objective!==objective){invalidate('unavailable');return;}
try{
const geometry=structuredClone(result.geometry);
const coords=geometry?.coordinates;
const close=(a,b)=>point(a)&&point(b)&&maths.distanceKm(...a,...b)*1000<=policy().accuracy;
if(!Array.isArray(coords)||!close(coords[0],req.origin)||!close(coords.at(-1),req.target)){terminal=true;invalidate('unavailable');return;}
const locate=createRouteFollower(geometry,maths);
route={geometry,locate,graphRevision:result.graphRevision};
status='tracking';evaluate(fix,now());
}catch{invalidate('unavailable');}
}).catch(()=>{if(current())invalidate('unavailable');});
}
function evaluate(f,t){
clearOutput();
if(mode==='direct'){
const d=maths.distanceKm(f.longitude,f.latitude,...target)*1000;
const b=d>f.accuracyM?maths.initialBearingDeg(f.longitude,f.latitude,...target):null;
if(!finite(d)||d<0){status='uncertain';return;}
status='manual';output={kind:'direct',distanceM:d,bearingDeg:finite(b)?b:null};return;
}
if(!online){invalidate('offline');return;}
if(!route){requestRoute(t);return;}
const p=route.locate(f,t);
if(p.status!=='ok'||!finite(p.progressM)||!finite(p.offsetM)){off=[];status='uncertain';return;}
const q=policy();
if(p.offsetM-f.accuracyM>q.margin){
status='suspect';if(off.at(-1)!==f.timestampMs)off.push(f.timestampMs);
if(off.length>q.confirm)off.shift();
if(off.length===q.confirm&&off.at(-1)-off[0]>=q.span){invalidate('deviated');requestRoute(t);}
return;
}
off=[];
if(progress){
const dt=(f.timestampMs-progress.time)/1000;
const allowance=q.maxSpeed*Math.max(0,dt)+f.accuracyM+progress.accuracy+10;
if(dt<0||Math.abs(p.progressM-progress.metres)>allowance){status='uncertain';return;}
}
progress={metres:p.progressM,time:f.timestampMs,accuracy:f.accuracyM};
status='tracking';
output={kind:'route',remainingM:p.remainingM,segmentIndex:p.segmentIndex,next:route.geometry.coordinates[p.segmentIndex+1].slice(),graphRevision:route.graphRevision};
}
function tick(){
if(!active)return snapshot();
const t=now();
if(!usable(fix,t)){invalidate('waiting-gps');return snapshot();}
if(mode!=='direct'&&!online){invalidate('offline');return snapshot();}
if(pending&&t>=pending.deadline){invalidate('timeout');return snapshot();}
if(!pending)evaluate(fix,t);
return snapshot();
}
function ingest(f){
const t=now();
if(!active)return snapshot();
if(!finite(f?.timestampMs)||f.timestampMs<=last)return tick();
// A future timestamp must not poison the ordering ledger.
if(f.timestampMs>t){invalidate('waiting-gps');return snapshot();}
last=f.timestampMs;fix={...f};
return tick();
}
return {setJourney,start,stop,pause,resume,network,ingest,tick,snapshot};
}