GLOBALGRID2050 / EXPLORE CODE

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

Mapped Footpaths and 14 more files

A JavaScript module in the pedestrian folder of GridAtlas that reads sections (`readSections`) and creates bristol footpath router (`createBristolFootpathRouter`). It reads sections (`readSections`) and creates bristol footpath router (`createBristolFootpathRouter`).

700 lines of JavaScript and Shell and Python from gridatlas, in 15 files. Topic: Maps, GIS and field navigation. Section 682 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. Mapped Footpaths ingest · gridatlas / tools/satnav/pedestrian/mapped-footpaths.mjs lines 1–155
  2. Mapped Footpaths Test test · gridatlas / tools/satnav/pedestrian/mapped-footpaths.test.mjs lines 1–107
  3. Perimeter transform · gridatlas / tools/satnav/perimeter/perimeter.mjs lines 1–50
  4. Perimeter Test test · gridatlas / tools/satnav/perimeter/perimeter.test.mjs lines 1–30
  5. SatNav Place ingest · gridatlas / tools/satnav/place.mjs lines 1–27
  6. Regional Benchmark storage · gridatlas / tools/satnav/regional/regional-benchmark.py lines 1–48
  7. Regional Config other · gridatlas / tools/satnav/regional/regional-config.mjs lines 1–3
  8. Regional Gateway ingest · gridatlas / tools/satnav/regional/regional-gateway.mjs lines 1–34
  9. Regional Pilot automation · gridatlas / tools/satnav/regional/regional-pilot.sh lines 1–79
  10. Valhalla Provider ingest · gridatlas / tools/satnav/regional/valhalla-provider.mjs lines 1–41
  11. Valhalla Provider Test test · gridatlas / tools/satnav/regional/valhalla-provider.test.mjs lines 1–32
  12. VEDIC Snapshot Provider V9214 Test test · gridatlas / tools/satnav/regional/vedic-snapshot-provider-v9214.test.mjs lines 1–21
  13. VEDIC Snapshot Provider transform · gridatlas / tools/satnav/regional/vedic-snapshot-provider.mjs lines 1–50
  14. VEDIC Snapshot Provider Test test · gridatlas / tools/satnav/regional/vedic-snapshot-provider.test.mjs lines 1–20
  15. SatNav Serve other · gridatlas / tools/satnav/serve.mjs lines 1–3

Mapped Footpaths

A JavaScript module in the pedestrian folder of GridAtlas that reads sections (`readSections`) and creates bristol footpath router (`createBristolFootpathRouter`). It reads sections (`readSections`) and creates bristol footpath router (`createBristolFootpathRouter`).

ingestgridatlas / tools/satnav/pedestrian/mapped-footpaths.mjs · lines 1–155 of 155 · pattern createBristolFootpathRouter (shared by 2 files)

What it does
It lists and searches its content. Defines 8 functions or classes, including same, valid, unavailable, readSections, consecutive.
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: Bristol (gridatlas); Mapped Footpaths Test (gridatlas). Reached from 1 other entry point, including GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
The Bristol extract has section IDs and shapes but no cross-path junction IDs.
Why it matters
Imported by Bristol. Checked by Mapped Footpaths Test.
Application
gridatlas · tools/satnav/pedestrian · JavaScript module
Uses
none found
Used by
imported by Bristol (import), imported by Mapped Footpaths Test (import), mentioned in Standalone (comment link)
Produces
createBristolFootpathRouter
Defines here
same, valid, unavailable, readSections, consecutive, chainsFor, locate, createBristolFootpathRouter
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/pedestrian/mapped-footpaths.mjs:1-155 · blob 44d18c1e8c58462ec0a78d90c614e7c0d199c84e · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
// SPDX-License-Identifier: Apache-2.0
// The Bristol extract has section IDs and shapes but no cross-path junction IDs.
const COUNCIL_LAYER = 'https://maps2.bristol.gov.uk/server2/rest/services/ext/ll_transport/MapServer/0';
const SNAP_M = 12;
const same = (a, b) => a[0] === b[0] && a[1] === b[1];
const valid = p => Array.isArray(p) && p.length === 2 && p.every(Number.isFinite)
  && Math.abs(p[0]) <= 180 && Math.abs(p[1]) <= 90;
const unavailable = reason => ({ status: 'unavailable', reason });

function readSections(collection) {
  if (collection?.type !== 'FeatureCollection' || collection.source?.url !== COUNCIL_LAYER
      || !Array.isArray(collection.features) || collection.features.length > 2000) {
    throw new Error('Invalid Bristol footpath source');
  }
  const routes = new Map();
  const seen = new Set();
  let pointCount = 0;
  for (const feature of collection.features) {
    const props = feature?.properties;
    if (props?.STATUS !== 'FP' || feature.geometry?.type !== 'LineString') continue;
    const match = /^(BCC\/[0-9A-Z]+)\/(\d+)$/.exec(props.ROUTE_CODE);
    if (!match) continue;
    const [, route, digits] = match;
    const sequence = Number(digits);
    const key = route + '/' + sequence;
    if (seen.has(key)) throw new Error('Duplicate footpath section');
    seen.add(key);
    const points = feature.geometry.coordinates;
    pointCount += points?.length || 0;
    if (pointCount > 20000 || !Array.isArray(points) || points.length < 2 || !points.every(valid)) {
      throw new Error('Invalid footpath geometry');
    }
    if (!routes.has(route)) routes.set(route, []);
    routes.get(route).push({ route, code: props.ROUTE_CODE, sequence, points: points.map(p => [...p]) });
  }
  return routes;
}

function consecutive(a, b) {
  return a && b && b.sequence === a.sequence + 10;
}

function chainsFor(routes, maths) {
  const chains = [];
  for (const sections of routes.values()) {
    sections.sort((a, b) => a.sequence - b.sequence);
    let chain, last;
    for (const [i, section] of sections.entries()) {
      let points = section.points;
      const first = points[0], end = points.at(-1);
      if (consecutive(sections[i - 1], section) && (same(last, first) || same(last, end))) {
        if (same(last, end)) points = [...points].reverse();
      } else {
        chain = { route: section.route, segments: [], lengthM: 0 };
        chains.push(chain);
        const next = sections[i + 1];
        if (consecutive(section, next)
            && (same(first, next.points[0]) || same(first, next.points.at(-1)))) {
          points = [...points].reverse();
        }
      }
      for (let j = 1; j < points.length; j++) {
        const a = points[j - 1], b = points[j];
        if (same(a, b)) continue;
        const lengthM = maths.distanceKm(...a, ...b) * 1000;
        if (!Number.isFinite(lengthM) || lengthM <= 0 || lengthM > 1000) throw new Error('Unsupported footpath segment');
        chain.segments.push({ a, b, first: j === 1, last: j === points.length - 1,
          code: section.code, startM: chain.lengthM, lengthM });
        chain.lengthM += lengthM;
      }
      last = points.at(-1);
    }
  }
  return chains;
}

function locate(point, chains, maths) {
  if (!valid(point)) return unavailable('invalid-point');
  const hits = [];
  for (const chain of chains) {
    for (const seg of chain.segments) {
      const hit = maths.distanceToSegmentKm(...point, ...seg.a, ...seg.b);
      const offsetM = hit.km * 1000;
      if (offsetM <= SNAP_M) {
        let junction = null;
        if (seg.first && hit.t === 0) junction = seg.a;
        if (seg.last && hit.t === 1) junction = seg.b;
        hits.push({ chain, offsetM, point: junction ?? hit.foot, junction, atM: seg.startM + hit.t * seg.lengthM });
      }
    }
  }
  hits.sort((a, b) => a.offsetM - b.offsetM);
  const best = hits[0];
  if (!best) return unavailable('outside-coverage');
  const positions = new Map();
  for (const h of hits) {
    if (h.offsetM > best.offsetM + 1) break;
    const prior = positions.get(h.chain);
    if (prior && Math.abs(h.atM - prior.atM) > 3) return unavailable('ambiguous-tap');
    if (!prior) positions.set(h.chain, h);
  }
  // A tap on a shared section endpoint can belong to either recorded path.
  // Intersecting or closely parallel shapes elsewhere provide no junction evidence.
  if (positions.size > 1 && [...positions.values()].some(h =>
    !best.junction || !h.junction || !same(h.junction, best.junction))) return unavailable('ambiguous-tap');
  return { positions };
}

// The caller supplies the pinned Ventus distanceKm/distanceToSegmentKm functions.
// Pins select positions on the mapped line. The measured GPS fix stays independent.
export function createBristolFootpathRouter(collection, maths) {
  const chains = chainsFor(readSections(collection), maths);
  return function route(from, to, excludedSections = []) {
    if (!Array.isArray(excludedSections) || !excludedSections.every(x => typeof x === 'string')) {
      return unavailable('invalid-closures');
    }
    const blocked = new Set(excludedSections);
    const fromHits = locate(from, chains, maths);
    if (fromHits.status) return fromHits;
    const toHits = locate(to, chains, maths);
    if (toHits.status) return toHits;
    const shared = [...fromHits.positions.keys()].filter(chain => toHits.positions.has(chain));
    if (!shared.length) return unavailable('no-mapped-connection');
    if (shared.length > 1) return unavailable('ambiguous-tap');
    const start = fromHits.positions.get(shared[0]), finish = toHits.positions.get(shared[0]);
    const reverse = finish.atM < start.atM;
    const [lo, hi] = reverse ? [finish, start] : [start, finish];
    if (hi.atM - lo.atM < 0.01) return unavailable('same-position');
    const coordinates = [[...lo.point]];
    const sectionCodes = [];
    for (const seg of lo.chain.segments) {
      const endM = seg.startM + seg.lengthM;
      if (endM <= lo.atM || seg.startM >= hi.atM) continue;
      if (blocked.has(seg.code)) return unavailable('excluded-section');
      if (sectionCodes.at(-1) !== seg.code) sectionCodes.push(seg.code);
      if (endM < hi.atM) coordinates.push([...seg.b]);
    }
    coordinates.push([...hi.point]);
    if (reverse) {
      coordinates.reverse();
      sectionCodes.reverse();
    }
    return {
      status: 'mapped',
      route: start.chain.route,
      sectionCodes,
      geometry: { type: 'LineString', coordinates },
      distanceM: hi.atM - lo.atM,
      fromOffsetM: start.offsetM,
      toOffsetM: finish.offsetM,
      currentAccess: 'unverified',
      source: COUNCIL_LAYER,
    };
  };
}

Mapped Footpaths Test

A test in the pedestrian folder of GridAtlas that checks Mapped Footpaths using data from the grid-distance-maths repository.

testgridatlas / tools/satnav/pedestrian/mapped-footpaths.test.mjs · lines 1–107 of 107 · Entry point · pattern synthetic (shared by 7 files)

What it does
It tests its inputs. Defines source, endpoints, section, synthetic, interp. Uses libraries node:assert/strict, node:crypto, node:fs/promises, node:test. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Inputs & outputs
In: data source: grid-distance-maths data.
Downstream impact
Used directly by 1 file: GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
It is built from the synthetic step (`synthetic`) and the interp step (`interp`). Defines `source`, `endpoints`, `section` and 2 more. It reads `bristol-footpaths.geojson`.
Why it matters
Run by GridAtlas PR File Size Guard Workflow.
Application
gridatlas · tools/satnav/pedestrian · test
Uses
Mapped Footpaths (import), node:assert/strict, node:crypto, node:fs/promises, node:test
Used by
run by GridAtlas PR File Size Guard Workflow (workflow run)
Produces
source, endpoints, section, synthetic, interp
Defines here
source, endpoints, section, synthetic, interp
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/pedestrian/mapped-footpaths.test.mjs:1-107 · blob cc0f973c1d293108e8411447a94662406fb8c969 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem, network · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
// SPDX-License-Identifier: Apache-2.0
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import test from 'node:test';
import { createBristolFootpathRouter } from './mapped-footpaths.mjs';

const revision = '8e91b07d8312acca5bcaef43e839f06a3b1d642a';
const upstream = 'https://raw.githubusercontent.com/Ventusltd/grid-distance-maths/' + revision + '/src/geodesy.mjs';
const bytes = process.env.SATNAV_GEODESY_FILE
  ? await readFile(process.env.SATNAV_GEODESY_FILE)
  : Buffer.from(await (await fetch(upstream)).arrayBuffer());
const blob = createHash('sha1').update('blob ' + bytes.length + '\0').update(bytes).digest('hex');
assert.equal(blob, '5a0320ca6db05273fae14f786b20223b088bc60b');
const maths = await import('data:text/javascript;base64,' + bytes.toString('base64'));
const bundle = JSON.parse(await readFile(new URL('bristol-footpaths.geojson', import.meta.url)));
const route = createBristolFootpathRouter(bundle, maths);
const source = code => bundle.features.find(f => f.properties.ROUTE_CODE === code).geometry.coordinates;
const endpoints = (first, last) => [source(first)[0], source(last).at(-1)];
const route21 = endpoints('BCC/21/10', 'BCC/21/30');
const route25 = endpoints('BCC/25/10', 'BCC/25/50');
const route38 = endpoints('BCC/38/10', 'BCC/38/30');
const section = (code, coords, status = 'FP') => ({ type: 'Feature',
  properties: { ROUTE_CODE: code, STATUS: status }, geometry: { type: 'LineString', coordinates: coords } });
const synthetic = features => createBristolFootpathRouter({ ...bundle, features }, maths);

for (const [id, points, expectedM, count] of [
  ['BCC/21', route21, 578.2, 3], ['BCC/25', route25, 1276.4, 5], ['BCC/38', route38, 342.0, 3],
]) {
  test(id + ' follows the mapped geometry in both directions', () => {
    const forward = route(...points), backward = route(points[1], points[0]);
    assert.equal(forward.status, 'mapped');
    assert.equal(forward.route, id);
    assert.equal(forward.currentAccess, 'unverified');
    assert.ok(Math.abs(forward.distanceM - expectedM) < 2);
    assert.equal(forward.sectionCodes.length, count);
    assert.deepEqual(backward.sectionCodes, [...forward.sectionCodes].reverse());
    assert.deepEqual(backward.geometry.coordinates, [...forward.geometry.coordinates].reverse());
    assert.deepEqual(forward.geometry.coordinates[0], points[0]);
    assert.deepEqual(forward.geometry.coordinates.at(-1), points[1]);
    const sum = forward.geometry.coordinates.slice(1).reduce((total, b, i) =>
      total + maths.distanceKm(...forward.geometry.coordinates[i], ...b) * 1000, 0);
    assert.ok(Math.abs(sum - forward.distanceM) < 0.01);
    assert.ok(forward.distanceM > maths.distanceKm(...points[0], ...points[1]) * 1000 + 2);
  });
}

test('clipping within an original segment excludes off-path taps from geometry', () => {
  const [a, b] = source('BCC/21/10');
  const interp = t => a.map((v, i) => v + t * (b[i] - v));
  const from = interp(0.3), to = interp(0.7);
  from[1] += 0.00002;
  const before = [...from];
  const answer = route(from, to);
  assert.equal(answer.status, 'mapped');
  assert.ok(answer.fromOffsetM > 0 && answer.fromOffsetM < 3);
  assert.notDeepEqual(answer.geometry.coordinates[0], from);
  assert.equal(answer.geometry.coordinates.length, 2);
  assert.deepEqual(from, before);
});

test('coverage, separate routes and identical selections have explicit outcomes', () => {
  assert.equal(route([0, 0], route21[0]).reason, 'outside-coverage');
  assert.equal(route([NaN, 52], route21[0]).reason, 'invalid-point');
  assert.equal(route(route21[0], route38[1]).reason, 'no-mapped-connection');
  assert.equal(route(route21[0], route21[0]).reason, 'same-position');
});

test('supplied closure blocks only journeys which use that section', () => {
  assert.equal(route(...route21, ['BCC/21/20']).reason, 'excluded-section');
  assert.equal(route(...route21, ['BCC/25/30']).status, 'mapped');
  assert.equal(route(...route21, null).reason, 'invalid-closures');
  const coords = source('BCC/21/10');
  assert.equal(route(coords[0], coords.at(-1), ['BCC/21/20']).status, 'mapped');
});

const a = [-2.63,51.50], b = [-2.629,51.50], c = [-2.628,51.50], d = [-2.627,51.50];
test('unknown access and missing section prevent traversing the gap', () => {
  const go = synthetic([section('BCC/X/10',[a,b]),section('BCC/X/20',[b,c],'FPS'),section('BCC/X/30',[c,d])]);
  assert.equal(go(a,d).reason, 'no-mapped-connection');
});

test('sections with a geographic gap cannot be traversed', () => {
  const go = synthetic([section('BCC/X/10',[a,b]),section('BCC/X/20',[c,d])]);
  assert.equal(go(a,d).reason, 'no-mapped-connection');
});

test('an interior line crossing cannot create a mapped pedestrian junction', () => {
  const p=[-2.6285,51.50], south=[p[0],p[1]-.001], north=[p[0],p[1]+.001];
  const go=synthetic([section('BCC/X/10',[a,d]),section('BCC/Y/10',[south,north])]);
  assert.equal(go(p,north).reason,'ambiguous-tap');
  assert.equal(go(a,north).reason,'no-mapped-connection');
});

test('source order and feature orientation do not set the walking direction', () => {
  const go=synthetic([section('BCC/X/20',[b,c]),section('BCC/X/10',[b,a])]);
  assert.deepEqual(go(a,c).geometry.coordinates,[a,b,c]);
});

test('snapshot validation and output do not corrupt input or future routes', () => {
  assert.throws(() => createBristolFootpathRouter({...bundle, source:{url:'unknown'}},maths));
  assert.throws(() => synthetic([section('BCC/X/10',[a,b]),section('BCC/X/10',[c,d])]));
  assert.throws(() => synthetic([section('BCC/X/10',[a,[Infinity,51.50]])]));
  const first=route(...route21);
  first.geometry.coordinates[1][0]=0;
  assert.notEqual(route(...route21).geometry.coordinates[1][0],0);
});

Perimeter

A JavaScript module in the SatNav folder of GridAtlas. It is built from the fail step (`fail`), the valid step (`valid`) and the same step (`same`).

transformgridatlas / tools/satnav/perimeter/perimeter.mjs · lines 1–50 of 50 · pattern closed (shared by 3 files)

What it does
It calculates its inputs. Defines 8 functions or classes, including buildPerimeter, fail, valid, same, cross.
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: Perimeter Test (gridatlas); Model (gridatlas). Reached from 2 other entry points, including GridAtlas PR File Size Guard Workflow (gridatlas); Model Test (gridatlas).
What it achieves
SV05: Pure local field-perimeter adapter; no GPS, routing or access authority. blob .
Why it matters
Imported by Model. Checked by Perimeter Test.
Application
gridatlas · tools/satnav/perimeter · JavaScript module
Uses
none found
Used by
imported by Perimeter Test (import), imported by Model (import)
Produces
buildPerimeter
Defines here
buildPerimeter, fail, valid, same, cross, on, hit, closed
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/perimeter/perimeter.mjs:1-50 · blob 392660163d695d7ee0eaf6d6ae7991ea691e131b · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
// SPDX-License-Identifier: Apache-2.0
// SV05: Pure local field-perimeter adapter; no GPS, routing or access authority.
// Source: atlas/parts/202609060254-ventus-corev8engine-polyzone-grabbable.js
// blob bd3287c17a42bf0bf08b1b75f1d023a5d53795ea. Inject canonical distanceKm.
// Local simple rings only, <=1000 vertices, latitudes within ±85°, no antimeridian.
export function buildPerimeter(vertices, maths) {
  const fail = code => { throw new Error(code); };
  if (!Array.isArray(vertices) || vertices.length < 3 || vertices.length > 1001) fail("INVALID_VERTEX_COUNT");
  const valid = p => Array.isArray(p) && p.length === 2 && p.every(Number.isFinite) && Math.abs(p[0]) <= 180 && Math.abs(p[1]) <= 85;
  if (!vertices.every(valid)) fail("INVALID_COORDINATE");
  if (typeof maths?.distanceKm !== "function") fail("MISSING_DISTANCE_MATHS");
  const same = (a,b) => a[0] === b[0] && a[1] === b[1];
  const pts = vertices.map(p => p.slice());
  if (same(pts[0],pts.at(-1))) pts.pop();
  if (pts.length < 3 || pts.length > 1000) fail("INVALID_VERTEX_COUNT");
  if (new Set(pts.map(p => p.join(","))).size !== pts.length) fail("DUPLICATE_VERTEX");
  const lons = pts.map(p => p[0]);
  if (Math.max(...lons)-Math.min(...lons) >= 180) fail("UNSUPPORTED_LONGITUDE_SPAN");
  const cross = (a,b,c) => (b[0]-a[0])*(c[1]-a[1])-(b[1]-a[1])*(c[0]-a[0]);
  const on = (a,b,c) => Math.min(a[0],b[0])<=c[0] && c[0]<=Math.max(a[0],b[0]) && Math.min(a[1],b[1])<=c[1] && c[1]<=Math.max(a[1],b[1]);
  const hit = (a,b,c,d) => {
    const x=cross(a,b,c), y=cross(a,b,d), z=cross(c,d,a), w=cross(c,d,b);
    return (x===0&&on(a,b,c))||(y===0&&on(a,b,d))||(z===0&&on(c,d,a))||(w===0&&on(c,d,b))||(Math.sign(x)*Math.sign(y)<0&&Math.sign(z)*Math.sign(w)<0);
  };
  const n=pts.length;
  for(let i=0;i<n;i++){
    const a=pts[(i+n-1)%n],b=pts[i],c=pts[(i+1)%n];
    if(cross(a,b,c)===0 && ((a[0]-b[0])*(c[0]-b[0])+(a[1]-b[1])*(c[1]-b[1])>0)) fail("BACKTRACKING_EDGE");
  }
  for(let i=0;i<n;i++)for(let j=i+2;j<n;j++){
    if(i===0&&j===n-1) continue;
    if(hit(pts[i],pts[(i+1)%n],pts[j],pts[(j+1)%n])) fail("SELF_INTERSECTION");
  }
  // Adapted from GridAtlas polyzone _zoneDrawCalcArea: spherical area,
  // same 6378.137 km radius, subtract constant terms to reduce cancellation.
  const rad=Math.PI/180, R=6378.137, sin0=Math.sin(pts[0][1]*rad);
  let sum=0, perimeterM=0, exceedsFollowerSegmentLimit=false;
  for(let i=0;i<n;i++){
    const a=pts[i],b=pts[(i+1)%n];
    const km=maths.distanceKm(...a,...b);
    if(!Number.isFinite(km)||km<=0) fail("INVALID_EDGE_DISTANCE");
    perimeterM+=km*1000;
    if(km>1) exceedsFollowerSegmentLimit=true;
    sum+=(b[0]-a[0])*rad*((Math.sin(a[1]*rad)-sin0)+(Math.sin(b[1]*rad)-sin0));
  }
  const areaM2=Math.abs(sum)*R*R*500000;
  if(!Number.isFinite(areaM2)||areaM2<=0) fail("DEGENERATE_POLYGON");
  const closed=()=>[...pts.map(p=>p.slice()),pts[0].slice()];
  return {perimeterM,areaM2,areaHa:areaM2/10000,polygon:{type:"Polygon",coordinates:[closed()]},plannedWalk:{type:"LineString",coordinates:closed()},exceedsFollowerSegmentLimit,approximate:true,plannedOnly:true};
}

Perimeter Test

A test in the SatNav folder of GridAtlas that checks Perimeter. It runs tests (`runTests`).

testgridatlas / tools/satnav/perimeter/perimeter.test.mjs · lines 1–30 of 30 · Entry point · pattern rejects (shared by 2 files)

What it does
It tests its inputs. Defines runTests, check, rejects.
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 `runTests`, `check` and `rejects`.
Why it matters
Run by GridAtlas PR File Size Guard Workflow.
Application
gridatlas · tools/satnav/perimeter · test
Uses
Perimeter (import)
Used by
run by GridAtlas PR File Size Guard Workflow (workflow run)
Produces
runTests, check, rejects
Defines here
runTests, check, rejects
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/perimeter/perimeter.test.mjs:1-30 · blob 04dbf4d02d64a6beb2fc1a3e9e9e5cf4950bdb48 · 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 {buildPerimeter} from './perimeter.mjs';
function runTests(build) {
  const rad=Math.PI/180,R=6378.137;
  const maths={distanceKm(a,b,c,d){const h=Math.sin((d-b)*rad/2)**2+Math.cos(b*rad)*Math.cos(d*rad)*Math.sin((c-a)*rad/2)**2;return 2*R*Math.asin(Math.sqrt(Math.min(1,h)));}};
  const p=[[0,0],[0.001,0],[0.001,0.001],[0,0.001]], original=JSON.stringify(p);
  let passed=0;
  const check=(v,m)=>{if(!v)throw Error(m);passed++;};
  const rejects=(v,code)=>{let got;try{build(v,maths)}catch(e){got=e.message;}check(got===code,`expected ${code}, got ${got}`);};
  const a=build(p,maths),b=build([...p,p[0]],maths),c=build([...p].reverse(),maths);
  check(a.plannedWalk.coordinates.length===5,"closure count");
  check(JSON.stringify(a.plannedWalk.coordinates[0])===JSON.stringify(a.plannedWalk.coordinates.at(-1)),"return to start");
  check(Math.abs(a.perimeterM-445.278)<0.01,"known equatorial perimeter");
  check(Math.abs(a.areaM2-12392.029)<0.1,"known equatorial area");
  check(a.areaM2===b.areaM2&&a.perimeterM===b.perimeterM,"normalise existing closure");
  check(Math.abs(a.areaM2-c.areaM2)<1e-6,"orientation independent area");
  check(JSON.stringify(p)===original,"input immutable");
  a.polygon.coordinates[0][0][0]=50;
  check(a.plannedWalk.coordinates[0][0]===0&&p[0][0]===0,"outputs independent");
  check(!a.exceedsFollowerSegmentLimit&&a.plannedOnly&&a.approximate,"planned semantics");
  check(build([[0,0],[0.02,0],[0.02,0.02],[0,0.02]],maths).exceedsFollowerSegmentLimit,"long leg flag");
  rejects([[0,0],[1,1],[0,1],[1,0]],"SELF_INTERSECTION");
  rejects([[0,0],[1,0],[0,0],[0,1]],"DUPLICATE_VERTEX");
  rejects([[0,0],[1,0],[0.5,0],[0,1]],"BACKTRACKING_EDGE");
  rejects([[179,0],[-179,0],[-179,1]],"UNSUPPORTED_LONGITUDE_SPAN");
  rejects([[0,0],[1,0],[1,90]],"INVALID_COORDINATE");
  rejects([[0,0],[1,0]],"INVALID_VERTEX_COUNT");
  rejects([[0,0],[1,0],[2,0]],"BACKTRACKING_EDGE");
  return passed;
}
console.log(`${runTests(buildPerimeter)} perimeter assertions passed`);

SatNav Place

A JavaScript module in the tools folder of GridAtlas that parses destination (`parseDestination`) and builds destination (`buildDestination`). It parses destination (`parseDestination`) and builds destination (`buildDestination`).

ingestgridatlas / tools/satnav/place.mjs · lines 1–27 of 27 · Not reached from any entry point (candidate for review) · pattern buildDestination (shared by 2 files)

What it does
Defines coordinate, parseDestination, buildDestination.
Why it exists in the grid workflow
Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Inputs & outputs
Coordinate systems named: WGS84 / EPSG:4326.
Downstream impact
Used directly by 1 file: Preview — Nav (satnav).
What it achieves
Coordinate contract: GeoJSON order [longitude, latitude], WGS84.
Why it matters
Imported by Preview — Nav, from SatNav.
Application
gridatlas · tools/satnav · JavaScript module
VEDIC
READ DESTINATION LINK (GG2050-VEDIC-000064): SatNav · Location and navigation data. url_query_string → destination_record_or_null
VEDIC
BUILD DESTINATION LINK (GG2050-VEDIC-000065): SatNav · Location and navigation data. longitude_latitude_degrees, mode_optional, name_optional, asset_source_and_id_optional → navigation_query_string
Uses
none found
Used by
imported by Preview — Nav (import), mentioned in Standalone (comment link)
Produces
parseDestination, buildDestination
Defines here
coordinate, parseDestination, buildDestination
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/place.mjs:1-27 · blob 546272b50712ba2f2f3b73f0fe148aa8e2535f1c · 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
// Coordinate contract: GeoJSON order [longitude, latitude], WGS84.
const modes = new Set(['compass','road_to_field','foot_survey','cable_trench']);
function coordinate(value,max) {
  if(typeof value!=='string'||!value.trim()||!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(value.trim())) throw new Error('invalid coordinate');
  const n=Number(value); if(!Number.isFinite(n)||Math.abs(n)>max) throw new Error('coordinate out of range');return n;
}
export function parseDestination(search) {
  const p=new URLSearchParams(search);
  for(const k of ['latitude','longitude','to','name','mode','source','id']) if(p.getAll(k).length>1)throw new Error('duplicate '+k);
  const mode=p.get('mode')??'compass';if(!modes.has(mode))throw new Error('invalid mode');
  const lat=p.get('latitude'),lon=p.get('longitude'),legacy=p.get('to');
  if(legacy!==null&&(lat!==null||lon!==null))throw new Error('conflicting coordinates');
  let pair;
  if(legacy!==null){const a=legacy.split(',');if(a.length!==2)throw new Error('invalid legacy coordinates');pair=[coordinate(a[1],180),coordinate(a[0],90)];}
  else if(lat!==null||lon!==null)pair=[coordinate(lon,180),coordinate(lat,90)];
  else return null;
  const source=p.get('source'),id=p.get('id');
  if((source===null)!==(id===null)||source===''||id==='')throw new Error('incomplete asset identity');
  return {coordinates:pair,mode,name:p.get('name')??'',asset:source===null?null:{source,id},accessStatus:'unverified'};
}
export function buildDestination({coordinates,mode='compass',name='',asset=null}){
  if(!Array.isArray(coordinates)||coordinates.length!==2||!coordinates.every(Number.isFinite))throw new Error('invalid coordinates');
  const [lon,lat]=coordinates;if(Math.abs(lon)>180||Math.abs(lat)>90||!modes.has(mode))throw new Error('invalid destination');
  const p=new URLSearchParams({latitude:String(lat),longitude:String(lon),mode,name});
  if(asset!==null){if(typeof asset.source!=='string'||typeof asset.id!=='string'||!asset.source||!asset.id)throw new Error('invalid asset');p.set('source',asset.source);p.set('id',asset.id);}
  return '?'+p.toString();
}

Regional Benchmark

A Python module in the SatNav folder of GridAtlas that fetches benchmark rows and benchmark summary. It is built from the dist step (`dist`).

storagegridatlas / tools/satnav/regional/regional-benchmark.py · lines 1–48 of 48 · Entry point

What it does
It fetches benchmark rows and benchmark summary. Defines dist. Uses libraries json, math, pathlib, sys, time. Side effects: reads or writes files; makes network requests; starts processes.
Why it exists in the grid workflow
Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Inputs & outputs
In: command-line arguments. Out: JSON file benchmark-rows.json; JSON file benchmark-summary.json.
Downstream impact
It is itself an entry point (Python module); no other file was found loading it.
What it achieves
ORIENT-17.2: public fixture measurements, not an independent access oracle.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
gridatlas · tools/satnav/regional · Python module
Uses
json, math, pathlib, sys, time, urllib.request, collections
Used by
none found
Produces
dist
Defines here
dist
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/satnav/regional/regional-benchmark.py:1-48 · blob 66b243734a252439a54f0c301dcd53e8feb08738 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
#!/usr/bin/env python3
"""ORIENT-17.2: public fixture measurements, not an independent access oracle."""
import json, math, pathlib, sys, time, urllib.request
from collections import defaultdict
URL, ROOT = sys.argv[1], pathlib.Path(sys.argv[2])
# Public city landmarks; no owner coordinates. First call per pair is not process-cold.
FIXTURES = {
    "central": ((51.5074,-0.1278),(51.513,-0.117)),
    "southbank": ((51.5033,-0.1196),(51.5055,-0.0754)),
    "west": ((51.5154,-0.1755),(51.5044,-0.2187)),
    "north": ((51.5320,-0.1240),(51.5413,-0.1464)),
}
def dist(a,b):
    p,q=map(math.radians,(a[0],b[0]))
    h=math.sin((q-p)/2)**2+math.cos(p)*math.cos(q)*math.sin(math.radians(b[1]-a[1])/2)**2
    return 6371008.8*2*math.asin(min(1,math.sqrt(h)))
rows=[]
for name,(a,b) in FIXTURES.items():
    for mode in ("pedestrian","auto"):
        for objective,options in (("recommended",{}),("distance",{"shortest":True,"disable_hierarchy_pruning":True})):
            for attempt in range(6):
                body=json.dumps({"locations":[{"lat":p[0],"lon":p[1]} for p in (a,b)],"costing":mode,"costing_options":{mode:options},"units":"kilometers"}).encode()
                start=time.perf_counter()
                row={"fixture":name,"mode":mode,"objective_requested":objective,"attempt":attempt,"request_bytes":len(body),"straight_m":dist(a,b)}
                try:
                    with urllib.request.urlopen(urllib.request.Request(URL+"/route",data=body,headers={"Content-Type":"application/json"}),timeout=25) as res:
                        data=res.read(8_000_001)
                    if len(data)>8_000_000: raise ValueError("oversize")
                    trip=json.loads(data)["trip"]
                    length=trip["summary"]["length"]*1000
                    assert trip["status"]==0 and length>0 and trip["legs"] and all(x.get("shape") for x in trip["legs"])
                    row.update(ok=True,response_bytes=len(data),distance_m=length,estimated_s=trip["summary"]["time"],maneuvers=sum(len(x.get("maneuvers",[])) for x in trip["legs"]))
                except Exception as exc:
                    row.update(ok=False,error=type(exc).__name__)
                row["latency_ms"]=round((time.perf_counter()-start)*1000,3)
                rows.append(row)
                # Persist incrementally, including failures.
                (ROOT/"benchmark-rows.json").write_text(json.dumps(rows,indent=2))
groups=defaultdict(list)
for row in rows: groups[(row["mode"],row["objective_requested"],"first-pair" if row["attempt"]==0 else "repeat")].append(row)
summary=[]
for key,rs in groups.items():
    ok=[x for x in rs if x["ok"]]
    times=sorted(x["latency_ms"] for x in ok)
    summary.append(dict(mode=key[0],objective=key[1],temperature=key[2],attempts=len(rs),success=len(ok),failure=len(rs)-len(ok),p50_ms=times[(len(times)-1)//2] if times else None,p95_ms=times[math.ceil(.95*len(times))-1] if times else None))
(ROOT/"benchmark-summary.json").write_text(json.dumps({"groups":summary,"process_cold":"not measured","optimality":"not proven","access_oracle":"not performed","rows":len(rows)},indent=2))
print(json.dumps(summary))
if any(not x["ok"] for x in rows): sys.exit(9)

Regional Config

A JavaScript module in the SatNav folder of GridAtlas.

othergridatlas / tools/satnav/regional/regional-config.mjs · lines 1–3 of 3 · Not reached from any entry point (candidate for review)

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 3 files: Orient17 Regional Proof (gridatlas); Orient17b Proof (gridatlas); Orient17a Proof (gridatlas).
What it achieves
Deployment-owned immutable configuration. Disabled until a controlled same-origin service and verified graph exist.
Why it matters
Imported by Orient17 Regional Proof, Orient17b Proof and Orient17a Proof.
Application
gridatlas · tools/satnav/regional · JavaScript module
Uses
none found
Used by
imported by Orient17 Regional Proof (dynamic import), imported by Orient17b Proof (dynamic import), imported by Orient17a Proof (dynamic import)
Produces
regionalConfig
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/satnav/regional/regional-config.mjs:1-3 · blob 8275aa2715dece31e22693cae605ecb507988605 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unreached_review
// Deployment-owned immutable configuration. Disabled until a controlled same-origin service and verified graph exist.
// No public fallback, no location disclosure by default.
export const regionalConfig=Object.freeze({endpoint:null,graphRevision:null});

Regional Gateway

A JavaScript module in the SatNav folder of GridAtlas. It is built from the send step (`send`).

ingestgridatlas / tools/satnav/regional/regional-gateway.mjs · lines 1–34 of 34 · Not reached from any entry point (candidate for review)

What it does
It fetches data. Defines send. Uses libraries node:http. Side effects: makes network requests.
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
Loopback-only private upstream gateway. Deploy behind a controlled same-origin HTTPS reverse proxy.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · tools/satnav/regional · JavaScript module
Uses
node:http
Used by
none found
Produces
send
Defines here
send
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/regional/regional-gateway.mjs:1-34 · blob d4ad98a19e61091b90919662893dd3bbb8b615b6 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: network · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unreached_review
// SPDX-License-Identifier: Apache-2.0
// Loopback-only private upstream gateway. Deploy behind a controlled same-origin HTTPS reverse proxy.
// Reverse proxy must disable request-body/query logging and enforce rate limits/auth as appropriate.
import {createServer} from 'node:http';
const graph=process.env.GRIDATLAS_GRAPH_REVISION, upstream=new URL(process.env.VALHALLA_LOOPBACK??'http://127.0.0.1:8002'), site=process.env.GRIDATLAS_SITE_ORIGIN;
if(!/^[a-f0-9]{64}$/.test(graph??'')||upstream.protocol!=='http:'||upstream.hostname!=='127.0.0.1'||upstream.pathname!=='/'||upstream.search||upstream.hash||upstream.username||upstream.password||!site||!['https:','http:'].includes(new URL(site).protocol)||new URL(site).origin!==site)throw Error('Invalid deployment configuration');
let inflight=0;
function send(res,status,body){res.writeHead(status,{'Content-Type':'application/json','Cache-Control':'no-store','X-Content-Type-Options':'nosniff','X-GridAtlas-Graph-Revision':graph});res.end(body);}
const server=createServer(async(req,res)=>{
 if(req.method!=='POST'||req.url!=='/satnav-routing/route'||req.headers.origin!==site||!/^application\/json(?:;|$)/i.test(req.headers['content-type']??'')){send(res,403,'{"error":"request rejected"}');return;}
 if(inflight>=4){send(res,429,'{"error":"busy"}');return;}
 inflight++;
 const abort=new AbortController();const timer=setTimeout(()=>abort.abort(),6500);
 res.on('close',()=>abort.abort());
 try{
  let n=0;const chunks=[];
  for await(const part of req){n+=part.length;if(n>4096){send(res,413,'{"error":"oversize"}');return;}chunks.push(part);}
  const obj=JSON.parse(Buffer.concat(chunks).toString('utf8'));
  const mode=obj.costing;
  const loc=obj.locations;
  if(!['pedestrian','auto'].includes(mode)||!Array.isArray(loc)||loc.length!==2||!loc.every(p=>Number.isFinite(p?.lon)&&Number.isFinite(p?.lat)&&p.lon>=-.6&&p.lon<=.4&&p.lat>=51.2&&p.lat<=51.8)){send(res,422,'{"error":"unsupported location or mode"}');return;}
  const shortest=obj.costing_options?.[mode]?.shortest===true;
  // Reconstruct from allowlisted fields: no arbitrary costing, ignore_access, or external locations.
  const payload={locations:loc.map(({lon,lat})=>({lon,lat,radius:15,search_cutoff:15})),costing:mode,units:'kilometers',costing_options:{[mode]:shortest?{shortest:true,disable_hierarchy_pruning:true}:{}},directions_type:'instructions'};
  const reply=await fetch(new URL('/route',upstream),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload),signal:abort.signal,redirect:'error'});
  if(!reply.ok){send(res,reply.status>=500?503:422,'{"error":"route unavailable"}');return;}
  const reader=reply.body.getReader();const data=[];let size=0;
  try{for(;;){const {done,value}=await reader.read();if(done)break;size+=value.byteLength;if(size>4_000_000){await reader.cancel();send(res,502,'{"error":"route too large"}');return;}data.push(Buffer.from(value));}}finally{reader.releaseLock();}
  send(res,200,Buffer.concat(data));
 }catch{if(!res.headersSent)send(res,503,'{"error":"route unavailable"}');}
 finally{clearTimeout(timer);inflight--;}
});
server.requestTimeout=8000;server.headersTimeout=5000;server.maxHeadersCount=30;
server.listen(Number(process.env.GATEWAY_PORT??8003),'127.0.0.1');

Regional Pilot

A shell script in the SatNav folder of GridAtlas that uses SHA-256.

automationgridatlas / tools/satnav/regional/regional-pilot.sh · lines 1–79 of 79 · Entry point

What it does
It fetches data. Side effects: reads or writes files; makes network requests; starts processes.
Why it exists in the grid workflow
Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Inputs & outputs
In: JSON file status.json; command-line arguments. Out: JSON file source-manifest.json.
Downstream impact
It is itself an entry point (shell script); no other file was found loading it.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
gridatlas · tools/satnav/regional · shell script
Uses
none found
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/satnav/regional/regional-pilot.sh:1-79 · blob 0b260ad184eed5771b6880ee27f9f3293e5abd4b · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
#!/usr/bin/env bash
# ORIENT-17.1: reproducible regional pilot, isolated from GridAtlas and production.
set -euo pipefail
umask 022
ROOT="$(realpath -m "${1:?usage: bash regional-pilot.sh NEW_EMPTY_WORK_DIR}")"
[[ "$ROOT" != / && ! -e "$ROOT" ]] || { echo "Choose a new work directory" >&2; exit 2; }
mkdir -p "$ROOT/raw" "$ROOT/engine"
BASE=https://download.geofabrik.de/europe/united-kingdom/england/greater-london
PBF=greater-london-261101.osm.pbf
IMAGE=ghcr.io/valhalla/valhalla-scripted@sha256:8d455db95ac26b14f6cd1deddd2fdbee2be3fa7648b3fbb6eedc2874bfdf314a
NAME=orient17-london-$$
trap 'rc=$?; docker logs "$NAME" > "$ROOT/engine.log" 2>&1 || true; docker rm -f "$NAME" >/dev/null 2>&1 || true; echo "$rc" > "$ROOT/exit-code.txt"' EXIT
date -u +%FT%TZ > "$ROOT/started.utc"
# An offline staged input is accepted only with a separately pinned SHA-256.
# No fallback to a different extract or mutable latest URL.
if [[ -n "${STAGED_PBF_DIR:-}" ]]; then
  [[ "${EXPECTED_PBF_SHA256:-}" =~ ^[0-9a-f]{64}$ ]] || { echo "Staged input requires independently verified SHA-256" >&2; exit 4; }
  cp "$STAGED_PBF_DIR/$PBF" "$STAGED_PBF_DIR/$PBF.md5" "$ROOT/raw/"
else
  for f in "$PBF.md5" "$PBF"; do
    curl --fail --location --proto '=https' --proto-redir '=https' --connect-timeout 15 --retry 3 --retry-connrefused --retry-max-time 90 --max-time 600 "$BASE/$f" -o "$ROOT/raw/$f" 2>>"$ROOT/acquisition.txt" || { echo "Acquisition failed: $f" | tee -a "$ROOT/acquisition.txt" >&2; exit 7; }
  done
fi
expected="$(awk 'NR==1 {print $1}' "$ROOT/raw/$PBF.md5")"
[[ "$expected" =~ ^[0-9a-fA-F]{32}$ ]] || exit 3
actual="$(md5sum "$ROOT/raw/$PBF" | cut -d' ' -f1)"
[[ "${expected,,}" == "$actual" ]] || { echo "Source MD5 mismatch" >&2; exit 3; }
sha="$(sha256sum "$ROOT/raw/$PBF" | cut -d' ' -f1)"
# Optional frozen SHA supplied by subsequent builds; never substitute a moving latest extract.
[[ -z "${EXPECTED_PBF_SHA256:-}" || "$sha" == "$EXPECTED_PBF_SHA256" ]] || exit 4
python3 - "$ROOT" "$BASE/$PBF" "$sha" "$actual" "$IMAGE" <<'PY'
import json, pathlib, sys, datetime
r=pathlib.Path(sys.argv[1])
p=next(r.joinpath("raw").glob("*.pbf"))
manifest=dict(schema=1, region="GB-Greater-London", source_url=sys.argv[2],
    archive_date="2026-11-01", fetched_utc=datetime.datetime.now(datetime.timezone.utc).isoformat(),
    source_sha256=sys.argv[3], source_md5=sys.argv[4], source_bytes=p.stat().st_size,
    engine_image=sys.argv[5], engine_platform="linux/amd64",
    licence="ODbL-1.0", attribution="OpenStreetMap contributors; Geofabrik extract",
    licence_url="https://www.openstreetmap.org/copyright", graph_status="NOT_VERIFIED")
(r/"source-manifest.json").write_text(json.dumps(manifest,indent=2)+"\n")
PY
# Build from the verified local bytes; no second source download.
cp "$ROOT/raw/$PBF" "$ROOT/engine/$PBF"
docker pull --platform linux/amd64 "$IMAGE"
docker run -d --name "$NAME" --platform linux/amd64 -p 127.0.0.1::8002 \
  -e server_threads=2 -e use_default_speeds_config=False -v "$ROOT/engine:/custom_files" "$IMAGE" > "$ROOT/container.id"
PORT="$(docker port "$NAME" 8002/tcp | awk -F: 'NR==1 {print $NF}')"
[[ "$PORT" =~ ^[0-9]+$ ]] || exit 5
# Public landmark pair, no private survey positions.
URL="http://127.0.0.1:$PORT"
ready=0
for ((i=0;i<180;i++)); do
  if curl -fsS --max-time 3 "$URL/status" > "$ROOT/status.json"; then ready=1; break; fi
  [[ "$(docker inspect -f '{{.State.Running}}' "$NAME")" == true ]] || break
  sleep 5
done
docker logs "$NAME" > "$ROOT/engine.log" 2>&1 || true
[[ "$ready" == 1 ]] || { echo "Engine not ready; inspect engine.log" >&2; exit 6; }
for mode in pedestrian auto; do
  payload="$(printf '{"locations":[{"lat":51.5074,"lon":-0.1278},{"lat":51.513,"lon":-0.117}],"costing":"%s","units":"kilometers"}' "$mode")"
  curl -fsS --max-time 30 -H 'Content-Type: application/json' --data "$payload" "$URL/route" > "$ROOT/$mode.json"
done
python3 - "$ROOT" <<'PY'
import json, pathlib, sys
r=pathlib.Path(sys.argv[1])
for mode in ("pedestrian","auto"):
    trip=json.loads((r/(mode+".json")).read_text())["trip"]
    assert trip["status"]==0 and trip["summary"]["length"]>0 and trip["legs"], mode
print("Two real-provider smoke responses validated; NOT route optimality or access acceptance.")
PY
# Hash all generated graph/config bytes separately from the staged source.
(cd "$ROOT/engine" && find . -type f ! -name '*.osm.pbf' -print0 | sort -z | xargs -0 -r sha256sum) > "$ROOT/graph-files.txt"
[[ -s "$ROOT/graph-files.txt" ]] || { echo "Graph hash inventory empty" >&2; exit 8; }
sha256sum "$ROOT/graph-files.txt" > "$ROOT/graph-inventory-sha256.txt"
du -sb "$ROOT/raw" "$ROOT/engine" > "$ROOT/storage-bytes.txt"
python3 "$(dirname "$0")/regional-benchmark.py" "$URL" "$ROOT"
docker stats --no-stream "$NAME" > "$ROOT/container-stats.txt"
date -u +%FT%TZ > "$ROOT/finished.utc"

Valhalla Provider

A JavaScript module in the regional folder of GridAtlas that decodes shape (`decodeShape`) and creates regional provider (`createRegionalProvider`). It decodes shape (`decodeShape`) and creates regional provider (`createRegionalProvider`).

ingestgridatlas / tools/satnav/regional/valhalla-provider.mjs · lines 1–41 of 41 · Not reached from any entry point (candidate for review) · pattern delta (shared by 9 files)

What it does
It lists and searches its content. Defines point, decodeShape, delta, createRegionalProvider, metres.
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: Valhalla Provider Test (gridatlas).
What it achieves
Controlled Valhalla adapter. No discovery, public demo endpoint, GPS watch or camera ownership.
Why it matters
Checked by Valhalla Provider Test.
Application
gridatlas · tools/satnav/regional · JavaScript module
Uses
none found
Used by
imported by Valhalla Provider Test (import)
Produces
decodeShape, createRegionalProvider
Defines here
point, decodeShape, delta, createRegionalProvider, metres
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/regional/valhalla-provider.mjs:1-41 · blob ce13abd231af39906e77b598542ea9b31fe7b49d · 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
// SPDX-License-Identifier: Apache-2.0
// Controlled Valhalla adapter. No discovery, public demo endpoint, GPS watch or camera ownership.
const point=p=>Array.isArray(p)&&p.length===2&&p.every(Number.isFinite)&&Math.abs(p[0])<=180&&Math.abs(p[1])<=90;
const hash=/^[0-9a-f]{64}$/;
const cap=20000;
export function decodeShape(s){
 if(typeof s!=='string'||!s.length||s.length>400000)throw Error('SHAPE');
 let i=0,lat=0,lon=0;const out=[];
 function delta(){let n=0,shift=0,b;do{if(i>=s.length||shift>30)throw Error('ENCODING');b=s.charCodeAt(i++)-63;if(b<0||b>63)throw Error('ENCODING');n+=(b&31)*2**shift;shift+=5;}while(b&32);return n%2?-(n+1)/2:n/2;}
 while(i<s.length){lat+=delta();lon+=delta();const p=[lon/1e6,lat/1e6];if(!point(p)||out.length>=cap)throw Error('COORDINATE');out.push(p);}
 if(out.length<2)throw Error('SHAPE');return out;
}
export function createRegionalProvider({endpoint,graphRevision,maths,fetcher=globalThis.fetch,origin=globalThis.location?.origin}={}){
 if(!endpoint||!hash.test(graphRevision??'')||!maths||typeof fetcher!=='function'||!origin)return null;
 const url=new URL(endpoint,origin);
 // Same-origin reverse proxy only; no cross-origin disclosure, no URL query or credentials.
 if(url.origin!==origin||url.pathname!=='/satnav-routing/route'||url.search||url.hash||url.username||url.password)return null;
 if(url.protocol!=='https:'&&!(url.protocol==='http:'&&['127.0.0.1','localhost'].includes(url.hostname)))return null;
 const metres=(a,b)=>maths.distanceKm(...a,...b)*1000;
 return async req=>{
  const {mode,objective,target,origin:from,revision,requestId,signal}=req;
  if(!point(from)||!point(target)||!['walking','driving'].includes(mode)||!['shortest','fastest'].includes(objective)||(mode==='walking'&&objective!=='shortest'))return {terminal:true};
  const costing=mode==='walking'?'pedestrian':'auto';
  const payload={locations:[from,target].map(([lon,lat])=>({lon,lat,radius:15,search_cutoff:15})),costing,units:'kilometers',costing_options:{[costing]:objective==='shortest'?{shortest:true,disable_hierarchy_pruning:true}:{}},directions_type:'instructions'};
  const res=await fetcher(url.href,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload),signal,credentials:'omit',cache:'no-store',redirect:'error',referrerPolicy:'no-referrer'});
  if(!res.ok)return {terminal:[400,401,403,404,422].includes(res.status)};
  if(res.headers.get('X-GridAtlas-Graph-Revision')!==graphRevision)return {terminal:true};
  const len=Number(res.headers.get('content-length')??0);if(len>4_000_000)return {terminal:true};
  const reader=res.body?.getReader();if(!reader)return {terminal:true};
  let size=0;const decoder=new TextDecoder('utf-8',{fatal:true});let raw='';
  try{for(;;){const {done,value}=await reader.read();if(done)break;size+=value.byteLength;if(size>4_000_000){await reader.cancel();return {terminal:true};}raw+=decoder.decode(value,{stream:true});}raw+=decoder.decode();}finally{reader.releaseLock();}
  const trip=JSON.parse(raw)?.trip;
  if(trip?.status!==0||trip.legs?.length!==1||!Number.isFinite(trip.summary?.length)||trip.summary.length<=0)return {terminal:true};
  const coordinates=decodeShape(trip.legs[0].shape);
  // Reject rather than invent a connector to an inaccessible/off-network target.
  if(metres(from,coordinates[0])>15||metres(target,coordinates.at(-1))>15)return {terminal:true};
  if(!coordinates.slice(1).some((p,i)=>metres(p,coordinates[i])>0))return {terminal:true};
  const maneuvers=(trip.legs[0].maneuvers??[]).filter(m=>Number.isInteger(m.begin_shape_index)&&m.begin_shape_index>=0&&m.begin_shape_index<coordinates.length&&typeof m.instruction==='string').map(m=>({index:m.begin_shape_index,instruction:m.instruction.slice(0,300)}));
  return {eligible:true,graphRevision,revision,requestId,mode,objective,geometry:{type:'LineString',coordinates},maneuvers,objectiveVerified:false,accessVerified:false,liveTraffic:false};
 };
}

Valhalla Provider Test

A test in the regional folder of GridAtlas that checks Valhalla Provider and Orient16 Recovery Safe.

testgridatlas / tools/satnav/regional/valhalla-provider.test.mjs · lines 1–32 of 32 · Not reached from any entry point (candidate for review) · pattern response (shared by 6 files)

What it does
It tests its inputs. Defines encode, response. 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 `encode` and `response`.
Why it matters
Guards the behaviour of Valhalla Provider and Orient16 Recovery Safe.
Application
gridatlas · tools/satnav/regional · test
Uses
Valhalla Provider (import), Orient16 Recovery Safe (import), node:assert/strict
Used by
none found
Produces
encode, response
Defines here
encode, response
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/regional/valhalla-provider.test.mjs:1-32 · blob ee3519086a3134cd76cd015523b062a39b429f87 · 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 assert from 'node:assert/strict';
import {decodeShape,createRegionalProvider} from './valhalla-provider.mjs';
import {createRecovery} from '../line/orient16-recovery-safe.mjs';
const maths={distanceKm:(x,y,a,b)=>Math.hypot((x-a)*69,(y-b)*111),initialBearingDeg:()=>0,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)));return {t,foot:[a+t*(c-a),b+t*(d-b)],km:Math.hypot((x-a-t*(c-a))*69,(y-b-t*(d-b))*111)}}};
const from=[-.12,51.5],target=[-.119,51.501],graphRevision='a'.repeat(64);
function encode(points){let last=[0,0],s='';for(const [x,y] of points){const next=[Math.round(y*1e6),Math.round(x*1e6)];for(let i=0;i<2;i++){let d=next[i]-last[i],n=d<0?-2*d-1:2*d;while(n>=32){s+=String.fromCharCode((n%32+32)+63);n=Math.floor(n/32)}s+=String.fromCharCode(n+63)}last=next}return s}
const shape=encode([from,target]);
assert.deepEqual(decodeShape(shape),[from,target]);
for(const bad of ['', '!', '~', encode([[0,91],[1,92]])])assert.throws(()=>decodeShape(bad));
const response=(points=[from,target],hash=graphRevision,status=200)=>new Response(JSON.stringify({trip:{status:0,summary:{length:.15},legs:[{shape:encode(points),maneuvers:[{begin_shape_index:0,instruction:'Continue'}]}]}}),{status,headers:{'X-GridAtlas-Graph-Revision':hash}});
let seen;
const config={endpoint:'/satnav-routing/route',graphRevision,maths,origin:'https://test.invalid'};
const provider=createRegionalProvider({...config,fetcher:async(url,options)=>{seen={url,options};return response()}});
const req={mode:'walking',objective:'shortest',origin:from,target,revision:3,requestId:7,signal:new AbortController().signal};
const good=await provider(req);
assert.equal(good.eligible,true);assert.equal(good.objectiveVerified,false);assert.equal(good.accessVerified,false);assert.equal(good.liveTraffic,false);assert.deepEqual(good.geometry.coordinates,[from,target]);
assert.equal(seen.url,'https://test.invalid/satnav-routing/route');
assert.equal(seen.options.credentials,'omit');assert.equal(seen.options.redirect,'error');assert.equal(seen.options.signal,req.signal);
assert.equal(JSON.parse(seen.options.body).costing,'pedestrian');assert.equal(JSON.parse(seen.options.body).costing_options.pedestrian.disable_hierarchy_pruning,true);
await provider({...req,mode:'driving',objective:'fastest'});assert.equal(JSON.parse(seen.options.body).costing,'auto');
assert.equal(createRegionalProvider({...config,endpoint:'https://third-party.invalid/satnav-routing/route'}),null);
assert.equal(createRegionalProvider({...config,graphRevision:null}),null);
for(const res of [response([from,target],'b'.repeat(64)),response([from,[0,0]]),response([from,from]),response([from,target],graphRevision,403)]){
 const p=createRegionalProvider({...config,fetcher:async()=>res});assert.equal((await p(req)).terminal,true);
}
let now=100000;const recovery=createRecovery({maths,provider,clock:()=>now});
recovery.setJourney({mode:'walking',target});recovery.start();recovery.ingest({longitude:from[0],latitude:from[1],accuracyM:3,timestampMs:now});
for(let i=0;i<20;i++)await new Promise(resolve=>setTimeout(resolve,0));
assert.equal(recovery.tick().status,'tracking');assert.deepEqual(recovery.snapshot().target,target);assert.deepEqual(recovery.snapshot().geometry.coordinates,[from,target]);
recovery.network(false);assert.equal(recovery.snapshot().geometry,null);assert.equal(recovery.snapshot().status,'offline');
recovery.stop();assert.equal(recovery.snapshot().active,false);
console.log('ORIENT-17.2 adapter contracts PASS (synthetic transport only)');

VEDIC Snapshot Provider V9214 Test

A test in the regional folder of GridAtlas that checks VEDIC Snapshot Provider and VEDIC Snapshot Routing, using SHA-256.

testgridatlas / tools/satnav/regional/vedic-snapshot-provider-v9214.test.mjs · lines 1–21 of 21 · Not reached from any entry point (candidate for review)

What it does
It tests its inputs. Defines make. Uses libraries node:assert/strict, node:fs, node:crypto. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'vedic'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: command-line arguments.
What it achieves
Defines `make`.
Why it matters
Guards the behaviour of VEDIC Snapshot Provider, VEDIC Snapshot Routing and VEDIC Regional Io.
Application
gridatlas · tools/satnav/regional · test
Uses
VEDIC Snapshot Provider (import), VEDIC Snapshot Routing (import), VEDIC Regional Io (import), node:assert/strict, node:fs, node:crypto, ../vendor/9698781539e549deaa6ecaa4a2b34610c1f9fd29/vendor/grid-distance-maths/src/geodesy.mjs
Used by
none found
Produces
make
Defines here
make
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/regional/vedic-snapshot-provider-v9214.test.mjs:1-21 · blob 6c46a1c07ec8d47908bbd447943bf3612be8c59a · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import {webcrypto} from 'node:crypto';
import {createSnapshotProvider,snapshot} from './vedic-snapshot-provider.mjs';
import * as maths from '../vendor/9698781539e549deaa6ecaa4a2b34610c1f9fd29/vendor/grid-distance-maths/src/geodesy.mjs';
import {buildRoutingGraph} from '../../vedic/snapshot-routing.mjs';
import {readVerifiedShard} from '../../vedic/regional-io.mjs';
const raw=process.argv[2]?readFileSync(process.argv[2]):Buffer.from(await readVerifiedShard(snapshot,{subtle:webcrypto.subtle}));assert.equal(raw.length,snapshot.bytes);
let calls=0;
const p=createSnapshotProvider({maths,subtle:webcrypto.subtle,fetcher:async(url,opts)=>{assert.equal(url,snapshot.url);assert.equal(opts.referrerPolicy,'no-referrer');assert.equal(opts.credentials,'omit');assert.equal(opts.body,undefined);calls++;return new Response(raw);}});
const make=(mode,origin,target,objective='shortest')=>({mode,origin,target,objective,requestId:1,revision:2,signal:new AbortController().signal});
assert.equal((await p(make('walking',[0,0],[0,1]))).reason,'outside-oxford-snapshot');assert.equal(calls,0);
for(const mode of ['walking','driving']){
 const graph=buildRoutingGraph(JSON.parse(raw),mode);let successes=0;
 for(const e of graph.edges){const a=graph.sourceVertices.get(e.from),b=graph.sourceVertices.get(e.to),origin=[a.lon,a.lat],target=[b.lon,b.lat];const r=await p(make(mode,origin,target));if(r.eligible){assert.equal(r.accessVerified,false);assert.equal(r.graphRevision,snapshot.sha256);assert.equal(r.revision,2);assert.ok(r.geometry.coordinates.length>=2);successes++;}}
 assert.ok(successes>0,mode+' must produce a real snapshot route');console.log(mode,successes,'real snapshot edge journeys');
}
assert.equal(calls,2);
const corrupt=createSnapshotProvider({maths,subtle:webcrypto.subtle,fetcher:async()=>new Response(new Uint8Array(raw.length))});
await assert.rejects(corrupt(make('walking',[-1.2582305,51.7527993],[-1.258093,51.7528296])),/digest mismatch/);
console.log('VEDIC snapshot provider PASS; no claim of live access or full regional coverage');

VEDIC Snapshot Provider

A JavaScript module in the regional folder of GridAtlas covering topology, using SHA-256 and uses data from the neural-link-between-agents repository. It selects node (`selectNode`) and creates snapshot provider (`createSnapshotProvider`).

transformgridatlas / tools/satnav/regional/vedic-snapshot-provider.mjs · lines 1–50 of 50 · Not reached from any entry point (candidate for review) · pattern inside (shared by 23 files)

What it does
It calculates topology. Defines inside, point, selectNode, createSnapshotProvider, fail.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'vedic'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file topology.json.
Downstream impact
Used directly by 2 files: VEDIC Snapshot Provider V9214 Test (gridatlas); VEDIC Snapshot Provider Test (gridatlas).
What it achieves
Explicit, bounded OSM pilot only. No GPS data leaves the browser.
Why it matters
Checked by 2 tests, including VEDIC Snapshot Provider V9214 Test.
Application
gridatlas · tools/satnav/regional · JavaScript module
Uses
VEDIC Snapshot Routing (import), VEDIC Regional Io (import)
Used by
imported by VEDIC Snapshot Provider V9214 Test (import), imported by VEDIC Snapshot Provider Test (import)
Produces
snapshot, selectNode, createSnapshotProvider
Defines here
inside, point, selectNode, createSnapshotProvider, fail
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/satnav/regional/vedic-snapshot-provider.mjs:1-50 · blob 4ef928a8698a545e302f2cc4ed7dd829f1a1dd74 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
// SPDX-License-Identifier: Apache-2.0
// Explicit, bounded OSM pilot only. No GPS data leaves the browser.
import {buildRoutingGraph,routeCandidate} from '../../vedic/snapshot-routing.mjs';
import {readVerifiedShard} from '../../vedic/regional-io.mjs';
export const snapshot=Object.freeze({
 url:'https://raw.githubusercontent.com/Ventusltd/neural-link-between-agents/62b7eac15510397c2f1e4f79da3981fe82de68a9/SESSIONS/2026-12-02-SATNAV-ORIENT-20/FIXTURES/vedic-e02-osm-oxford/contents/topology.json',
 bytes:371462,sha256:'50372236298639e6f1d35c9059c755716614b5ddcfa4bd177837514e689ed7d6',
 bbox:Object.freeze([-1.2600,51.7510,-1.2580,51.7530]),date:'2026-12-03',
 attribution:'OpenStreetMap contributors · ODbL 1.0'
});
const inside=p=>Array.isArray(p)&&p.length===2&&p.every(Number.isFinite)&&p[0]>=snapshot.bbox[0]&&p[0]<=snapshot.bbox[2]&&p[1]>=snapshot.bbox[1]&&p[1]<=snapshot.bbox[3];
const point=n=>[n.lon,n.lat];
export function selectNode(graph,at,maths){
 const hits=[];
 for(const id of graph.active){const n=graph.sourceVertices.get(id),p=point(n);if(!inside(p))continue;const d=maths.distanceKm(...at,...p)*1000;if(Number.isFinite(d)&&d<=10)hits.push({id,p,d});}
 hits.sort((a,b)=>a.d-b.d||a.id.localeCompare(b.id));
 // Distinct topological nodes at a similar distance are ambiguous; never invent connectors.
 return hits.length&&(!hits[1]||hits[1].d-hits[0].d>3)?hits[0]:null;
}
export function createSnapshotProvider({maths,fetcher=globalThis.fetch,subtle=globalThis.crypto?.subtle}={}){
 if(!maths||typeof fetcher!=='function'||!subtle)return null;
 // One graph at a time; mode change discards the prior decoded graph.
 let retained=null;
 return async req=>{
  const {mode,objective,origin,target,signal,requestId,revision}=req;
  const fail=reason=>({terminal:true,reason});
  if(!inside(origin)||!inside(target))return fail('outside-oxford-snapshot');
  if(!['walking','driving'].includes(mode)||!['shortest','fastest'].includes(objective)||mode==='walking'&&objective!=='shortest')return fail('unsupported-objective');
  if(signal?.aborted)return fail('cancelled');
  let graph=retained?.mode===mode?retained.graph:null;
  if(!graph){
   const bytes=await readVerifiedShard(snapshot,{signal,subtle,fetcher:(url,opts)=>fetcher(url,{...opts,referrerPolicy:'no-referrer',cache:'force-cache'})});
   if(signal?.aborted)return fail('cancelled');
   const data=JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(bytes));
   graph=buildRoutingGraph(data,mode);
   if(signal?.aborted)return fail('cancelled');
   retained={mode,graph};
  }
  if(graph.issues.length)return fail('unresolved-topology');
  const from=selectNode(graph,origin,maths),to=selectNode(graph,target,maths);
  if(!from||!to||from.id===to.id)return fail('ambiguous-or-identical-snap');
  const result=routeCandidate(graph,from.id,to.id,objective==='fastest'?'estimated-fastest':'shortest',{maxStates:20000});
  if(result.status!=='candidate'||!result.edges.length||result.edges.length>2000)return fail(result.reason??'empty-route');
  const byId=new Map(graph.edges.map(e=>[e.id,e]));
  let at=from.id,last=null;const coordinates=[from.p];
  for(const id of result.edges){const e=byId.get(id);if(!e||e.from!==at||(last!==null&&!graph.turnAllowed(last,id)))return fail('invalid-route-chain');at=e.to;last=id;const p=point(graph.sourceVertices.get(at));if(!inside(p))return fail('route-exits-pilot');coordinates.push(p);}
  if(at!==to.id||signal?.aborted)return fail('stale-or-invalid-endpoint');
  return {eligible:true,graphRevision:snapshot.sha256,requestId,revision,mode,objective,geometry:{type:'LineString',coordinates},distanceMm:result.distanceMm,estimatedMs:result.estimatedMs,accessVerified:false,objectiveVerified:false,liveTraffic:false,source:snapshot.attribution};
 };
}

VEDIC Snapshot Provider Test

A test in the regional folder of GridAtlas that checks VEDIC Snapshot Provider and VEDIC Snapshot Routing, using SHA-256.

testgridatlas / tools/satnav/regional/vedic-snapshot-provider.test.mjs · lines 1–20 of 20 · Not reached from any entry point (candidate for review)

What it does
It tests its inputs. Defines make. Uses libraries node:assert/strict, node:fs, node:crypto. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'vedic'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: command-line arguments.
What it achieves
Defines `make`.
Why it matters
Guards the behaviour of VEDIC Snapshot Provider and VEDIC Snapshot Routing.
Application
gridatlas · tools/satnav/regional · test
Uses
VEDIC Snapshot Provider (import), VEDIC Snapshot Routing (import), node:assert/strict, node:fs, node:crypto, ../vendor/9698781539e549deaa6ecaa4a2b34610c1f9fd29/vendor/grid-distance-maths/src/geodesy.mjs
Used by
none found
Produces
make
Defines here
make
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/regional/vedic-snapshot-provider.test.mjs:1-20 · blob 6ccbc39bbdf15d3fd028d93acd18c7a78f34642a · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import {webcrypto} from 'node:crypto';
import {createSnapshotProvider,snapshot} from './vedic-snapshot-provider.mjs';
import * as maths from '../vendor/9698781539e549deaa6ecaa4a2b34610c1f9fd29/vendor/grid-distance-maths/src/geodesy.mjs';
import {buildRoutingGraph} from '../../vedic/snapshot-routing.mjs';
const raw=readFileSync(process.argv[2]);assert.equal(raw.length,snapshot.bytes);
let calls=0;
const p=createSnapshotProvider({maths,subtle:webcrypto.subtle,fetcher:async(url,opts)=>{assert.equal(url,snapshot.url);assert.equal(opts.referrerPolicy,'no-referrer');assert.equal(opts.credentials,'omit');assert.equal(opts.body,undefined);calls++;return new Response(raw);}});
const make=(mode,origin,target,objective='shortest')=>({mode,origin,target,objective,requestId:1,revision:2,signal:new AbortController().signal});
assert.equal((await p(make('walking',[0,0],[0,1]))).reason,'outside-oxford-snapshot');assert.equal(calls,0);
for(const mode of ['walking','driving']){
 const graph=buildRoutingGraph(JSON.parse(raw),mode);let successes=0;
 for(const e of graph.edges){const a=graph.sourceVertices.get(e.from),b=graph.sourceVertices.get(e.to),origin=[a.lon,a.lat],target=[b.lon,b.lat];const r=await p(make(mode,origin,target));if(r.eligible){assert.equal(r.accessVerified,false);assert.equal(r.graphRevision,snapshot.sha256);assert.equal(r.revision,2);assert.ok(r.geometry.coordinates.length>=2);successes++;}}
 assert.ok(successes>0,mode+' must produce a real snapshot route');console.log(mode,successes,'real snapshot edge journeys');
}
assert.equal(calls,2);
const corrupt=createSnapshotProvider({maths,subtle:webcrypto.subtle,fetcher:async()=>new Response(new Uint8Array(raw.length))});
await assert.rejects(corrupt(make('walking',[-1.2582305,51.7527993],[-1.258093,51.7528296])),/digest mismatch/);
console.log('VEDIC snapshot provider PASS; no claim of live access or full regional coverage');

SatNav Serve

A JavaScript module in the tools folder of GridAtlas.

othergridatlas / tools/satnav/serve.mjs · lines 1–3 of 3 · Entry point

Why it exists in the grid workflow
Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Inputs & outputs
In: command-line arguments.
Downstream impact
Used directly by 1 file: GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name. Described from its file name only (a candidate, not yet checked against the code).
Why it matters
Run by GridAtlas PR File Size Guard Workflow.
Application
gridatlas · tools/satnav · JavaScript module
Uses
Serve (import)
Used by
run by GridAtlas PR File Size Guard Workflow (workflow run)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/satnav/serve.mjs:1-3 · blob e2f9ff4a027de11b9bcfa18a3ccad1938fe026f1 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: unknown · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
import {createPreviewServer} from '../journey/serve.mjs';
const server=await createPreviewServer(Number(process.argv[2]||8768));
console.log(`Native M1 candidate http://127.0.0.1:${server.address().port}/atlas/v/satnav-native-m1/`);