GLOBALGRID2050 / EXPLORE CODE

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

Advance and 2 more files

A JavaScript module in the scope folder of GridAtlas that fetches grid 400kV and CVAA ratchets, using SHA-256 from postcodes.io.

700 lines of JavaScript and Python from gridatlas, in 3 files. Topic: Maps, GIS and field navigation. Section 688 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. SatNav Waypoint Browser render · gridatlas / tools/satnav/waypoint-browser.py lines 1–256
  2. State Test test · gridatlas / tools/satnav/waypoints/state.test.mjs lines 1–21
  3. Advance interaction · gridatlas / tools/scope/advance.mjs lines 1–423

SatNav Waypoint Browser

A Python command-line tool in the tools folder of GridAtlas that emits fix (`emit_fix`), checks bearing (`check_bearing`) and map gestures (`check_map_gestures`) and calculates planar distances and angles.

rendergridatlas / tools/satnav/waypoint-browser.py · lines 1–256 of 256 · Entry point · pattern check_browser (shared by 6 files)

What it does
It lists and searches its content. Defines 8 functions or classes, including pins, clear_map_pixel, place, emit_fix, measured. Uses libraries math, os, re, pathlib, runpy. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It is built from the pins step (`pins`), the clear map pixel helper (`clear_map_pixel`) and the place step (`place`). Touch and GPS regression for the composed GridAtlas waypoint map.
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, pathlib, runpy, playwright.sync_api
Used by
none found
Produces
pins, clear_map_pixel, place, emit_fix, measured, check_bearing, check_map_gestures, check_browser
Defines here
pins, clear_map_pixel, place, emit_fix, measured, check_bearing, check_map_gestures, check_browser
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/waypoint-browser.py:1-256 · blob 8425b267a7ce5acbc7023fe5e943cddef2ad6681 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
"""Touch and GPS regression for the composed GridAtlas waypoint map."""

import math
import os
import re
from pathlib import Path
from runpy import run_path

from playwright.sync_api import TimeoutError as PlaywrightTimeout, expect, sync_playwright


# V1 and V2 use the same geolocation contract and independent distance oracle.
compact = run_path(str(Path(__file__).with_name('compact-browser.py')))
GPS_SPY = compact['GPS_SPY'] + ''';
(() => {
  const gps = navigator.geolocation;
  const watch = gps.watchPosition.bind(gps);
  let lastHandler;
  gps.watchPosition = (success, error, options) => {
    lastHandler = success;
    return watch(success, error, options);
  };
  // A browser may deliver an already-queued callback after clearWatch.
  window.__waypointSample = ([longitude, latitude], heading, speed) => lastHandler({
    coords:{longitude, latitude, accuracy:5, heading, speed}, timestamp:Date.now()
  });
})()'''
surface_distance = compact['surface_distance']
SITE = os.environ.get('LINE_TEST_URL', 'http://127.0.0.1:8873/atlas/v/satnav-waypoints-202611281300/')
PLANNED = 'gridatlas-satnav-waypoints'
POSITION = 'gridatlas-satnav-position'

READ_PINS = '''({source, count, previous}) => {
  const data = window.__GRIDATLAS_V9_MAP__.getSource(source)?.serialize()?.data;
  if (!Array.isArray(data?.features)) return null;
  const points = data.features.filter(f => f.geometry.type === 'Point' &&
    ['start-point', 'waypoint', 'destination-point'].includes(f.properties.role));
  const pins = points.map(f => ({id:f.properties.pinId, role:f.properties.role, at:f.geometry.coordinates}));
  if (count != null && pins.length !== count) return null;
  if (previous && JSON.stringify(previous) === JSON.stringify(pins)) return null;
  return pins;
}'''


def pins(page, count=None, previous=None):
    try:
        return page.wait_for_function(READ_PINS, arg={'source': PLANNED, 'count': count,
                                      'previous': previous}, timeout=10000).json_value()
    except PlaywrightTimeout as error:
        observed = page.evaluate(READ_PINS, {'source': PLANNED})
        status = page.locator('#satnav-status').inner_text()
        raise AssertionError(f'Expected {count} pins, saw {observed}. Map status {status!r}') from error


def clear_map_pixel(page, cell, used=()):
    """Find a visible canvas pixel near the chosen grid cell, outside controls."""
    return page.wait_for_function('''({cell,used}) => {
      const map = window.__GRIDATLAS_V9_MAP__;
      if (map.isMoving()) return null;
      const canvas = map.getCanvas(), rect = canvas.getBoundingClientRect();
      const xs = [.22, .32, .42, .52, .62, .72, .82, .91], ys = [.48, .58, .68, .78, .88];
      const preferred = [xs[cell % xs.length], ys[Math.floor(cell / xs.length) % ys.length]];
      const candidates = xs.flatMap(x => ys.map(y => [x,y]));
      candidates.sort((a,b) => Math.hypot(a[0]-preferred[0],a[1]-preferred[1]) -
                                  Math.hypot(b[0]-preferred[0],b[1]-preferred[1]));
      for (const [fx,fy] of candidates) {
        const x = Math.round(rect.left + rect.width*fx), y = Math.round(rect.top + rect.height*fy);
        if (used.some(([px,py]) => Math.hypot(px-x,py-y) < 8)) continue;
        const previous = used[used.length-1];
        if (previous && Math.hypot(previous[0]-x,previous[1]-y) < 90) continue;
        if (document.elementFromPoint(x,y) === canvas) {
          return {x,y,at:map.unproject([x-rect.left,y-rect.top]).toArray()};
        }
      }
      return null;
    }''', arg={'cell':cell, 'used':used}, timeout=15000).json_value()


def place(page, control, cell, used=None):
    page.locator('#satnav-' + control).tap()
    pixel = clear_map_pixel(page, cell, used or ())
    page.touchscreen.tap(pixel['x'], pixel['y'])
    if used is not None:
        used.append([pixel['x'], pixel['y']])
    return pixel['at']


def emit_fix(page, at, accuracy=5, age=0):
    page.evaluate('args => window.__lineGpsTest.emit(...args)', [at, accuracy, age])


def measured(page, at):
    page.wait_for_function('''({source,at,missing}) => {
      const features = window.__GRIDATLAS_V9_MAP__.getSource(source)?.serialize()?.data?.features;
      if (!Array.isArray(features)) return false;
      const fix = features.find(f => f.properties.role === 'measured-gps');
      const ring = features.some(f => f.properties.role === 'gps-accuracy');
      return missing ? !fix && !ring : ring && JSON.stringify(fix?.geometry.coordinates) === JSON.stringify(at);
    }''', arg={'source': POSITION, 'at': at, 'missing': at is None}, timeout=10000)


def check_bearing(page, planned, at):
    page.evaluate('at => window.__waypointSample(at, 77, 1.3)', at)
    expect(page.locator('#satnav-status')).to_contain_text('GPS course 77°')
    guide = page.locator('#satnav-guide')
    expect(guide).to_contain_text('remaining')
    match = re.search(r'Pin (\d+) · (\d+) m · (\d+)° true', guide.inner_text())
    assert match, guide.inner_text()
    index, metres, degrees = map(int, match.groups())
    end = planned[index - 1]['at']
    lon1, lat1, lon2, lat2 = map(math.radians, [*at, *end])
    east = math.sin(lon2 - lon1) * math.cos(lat2)
    north = math.cos(lat1) * math.sin(lat2) - math.sin(lat1) * math.cos(lat2) * math.cos(lon2 - lon1)
    expected = math.degrees(math.atan2(east, north)) % 360
    assert abs((degrees - expected + 180) % 360 - 180) <= 1
    assert abs(surface_distance(at, end) - metres) < 2
    page.evaluate('at => window.__waypointSample(at, 77, 0)', at)
    expect(page.locator('#satnav-status')).not_to_contain_text('GPS course')


def check_map_gestures(page, expected):
    map_object = 'window.__GRIDATLAS_V9_MAP__'
    assert page.evaluate(f'{map_object}.dragPan.isEnabled() && {map_object}.touchZoomRotate.isEnabled()')
    pixel = clear_map_pixel(page, 13)
    centre = page.evaluate(f'{map_object}.getCenter().toArray()')
    page.mouse.move(pixel['x'], pixel['y'])
    page.mouse.down()
    page.mouse.move(pixel['x'] - 40, pixel['y'] - 16, steps=5)
    page.mouse.up()
    page.wait_for_function('at => !window.__GRIDATLAS_V9_MAP__.isMoving() && Math.abs(window.__GRIDATLAS_V9_MAP__.getCenter().lng-at[0])>1e-6', arg=centre)
    assert pins(page, len(expected)) == expected


def check_browser(browser, name, width, height):
    with browser.new_context(viewport={'width': width, 'height': height},
                             is_mobile=True, has_touch=True) as context:
        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=60000)
        expect(page.locator('#satnav-from')).to_be_enabled(timeout=45000)
        assert page.evaluate('window.__lineGpsTest.records.starts') == []
        canvas = page.locator('#map canvas.maplibregl-canvas').first.bounding_box()
        assert canvas and canvas['width'] * canvas['height'] >= width * height * .85
        page.evaluate('() => { window.__GRIDATLAS_V9_MAP__.jumpTo({center:[-1.50,51.50],zoom:17}); }')

        first = place(page, 'from', 16)
        last = place(page, 'to', 9)
        original = pins(page, 2)
        assert [p['role'] for p in original] == ['start-point', 'destination-point']
        assert surface_distance(first, original[0]['at']) < 2
        assert surface_distance(last, original[-1]['at']) < 2

        page.locator('#satnav-location').tap()
        page.evaluate('window.__lineGpsTest.deny()')
        assert pins(page, 2) == original
        page.locator('#satnav-location').tap()
        gps_start = [first[0] + .0003, first[1] + .0002]
        emit_fix(page, gps_start)
        measured(page, gps_start)
        assert pins(page, 2) == original, 'Start GPS replaced the planned FROM'
        manual = place(page, 'from', 14)
        current = pins(page, 2)
        assert surface_distance(manual, current[0]['at']) < 2
        assert current[-1] == original[-1]
        check_bearing(page, current, [manual[0] + .001, manual[1] + .001])

        # Each point uses an actual tap on the canvas. TO must stay at the end.
        tapped = []
        for i in range(12):
            before = current
            coordinate = place(page, 'add', i, tapped)
            current = pins(page, len(before) + 1)
            assert current[:-2] == before[:-1] and current[-1] == before[-1]
            assert current[-2]['role'] == 'waypoint'
            assert surface_distance(coordinate, current[-2]['at']) < 2
        assert len({p['id'] for p in current}) == len(current)
        page.locator('#satnav-undo').tap()
        assert pins(page, len(before)) == before

        # A pin dropped at the measured fix remains fixed when the walker moves.
        at = [first[0] + .00013, first[1] + .00011]
        emit_fix(page, at)
        measured(page, at)
        page.locator('#satnav-add').tap()
        page.locator('#satnav-use-fix').tap()
        current = pins(page, len(before) + 1)
        assert current[-2]['at'] == at
        moved = [at[0] + .00018, at[1]]
        emit_fix(page, moved)
        measured(page, moved)
        assert pins(page, len(current)) == current

        # Replacing an endpoint preserves the IDs and positions of all other pins.
        previous = current
        endpoint = place(page, 'to', 17)
        current = pins(page, len(previous), previous)
        assert current[:-1] == previous[:-1] and current[-1]['id'] == previous[-1]['id']
        assert surface_distance(endpoint, current[-1]['at']) < 2
        page.locator('#satnav-undo').tap()
        assert pins(page, len(previous), current) == previous

        # Editing, reordering and removing are exercised through the on-map editor.
        current = previous
        page.locator('#satnav-edit').tap()
        selected = page.locator('#satnav-selected')
        number = int(re.search(r'Pin (\d+) of', selected.inner_text()).group(1))
        for _ in range(abs(5 - number)):
            page.locator('#satnav-next' if number < 5 else '#satnav-prev').tap()
        expect(selected).to_contain_text('Pin 5 of')
        expect(page.locator('#satnav-earlier')).to_be_enabled()
        before_ids = [p['id'] for p in current]
        page.locator('#satnav-earlier').tap()
        reordered = pins(page, len(current), current)
        after_ids = [p['id'] for p in reordered]
        assert sorted(after_ids) == sorted(before_ids)
        assert sum(a != b for a, b in zip(before_ids, after_ids)) == 2
        page.locator('#satnav-undo').tap()
        assert pins(page, len(current), reordered) == current
        if not page.locator('#satnav-remove').is_visible():
            page.locator('#satnav-edit').tap()
        page.locator('#satnav-remove').tap()
        removed = pins(page, len(current) - 1)
        assert len(set(before_ids) - {p['id'] for p in removed}) == 1
        page.locator('#satnav-undo').tap()
        assert pins(page, len(current)) == current
        if page.locator('#satnav-remove').is_visible():
            page.locator('#satnav-edit').tap()
        check_map_gestures(page, current)

        assert page.evaluate('window.__lineGpsTest.records') == {'starts':[1, 2], 'stops':[1]}
        emit_fix(page, moved, age=15000)
        measured(page, None)
        assert pins(page, len(current)) == current
        page.locator('#satnav-stop').tap()
        assert page.evaluate('window.__lineGpsTest.records.stops') == [1, 2]
        page.evaluate('at => window.__waypointSample(at, 77, 1.3)', at)
        measured(page, None)
        assert not errors, errors
        print(f'{name} {width}x{height}: 14 ordered map pins, undo, edit, GPS, pan and Stop passed', flush=True)


if __name__ == '__main__':
    with sync_playwright() as playwright:
        for engine in os.environ.get('LINE_TEST_BROWSERS', 'chromium,webkit').split(','):
            engine = engine.strip()
            options = {'args': ['--enable-webgl', '--use-gl=angle', '--use-angle=swiftshader',
                                '--enable-unsafe-swiftshader']} if engine == 'chromium' else {}
            browser = getattr(playwright, engine).launch(**options)
            try:
                for size in [(390, 664), (664, 390)]:
                    check_browser(browser, engine, *size)
            finally:
                browser.close()

State Test

A test in the waypoints folder of GridAtlas. It runs tests (`runTests`).

testgridatlas / tools/satnav/waypoints/state.test.mjs · lines 1–21 of 21 · Entry point · pattern reject (shared by 5 files)

What it does
It tests its inputs. Defines runTests, eq, reject, test.
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`, `reject` and `test`.
Why it matters
Run by GridAtlas PR File Size Guard Workflow.
Application
gridatlas · tools/satnav/waypoints · test
Uses
./state.mjs
Used by
run by GridAtlas PR File Size Guard Workflow (workflow run)
Produces
runTests, eq, reject, test
Defines here
runTests, eq, reject, test
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/waypoints/state.test.mjs:1-21 · blob ad766d6c5c3f06f46057284f3c140db833b8277a · 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 { createWaypointState } from './state.mjs';
function runTests(createWaypointState) {
  let count=0;
  const eq=(a,b)=>{if(JSON.stringify(a)!==JSON.stringify(b))throw new Error('Expected '+JSON.stringify(b)+'; got '+JSON.stringify(a));};
  const reject=fn=>{let caught=false;try{fn();}catch(e){caught=e instanceof RangeError;}if(!caught)throw new Error('Expected RangeError');};
  const test=(name,fn)=>{fn();count++;};
  test('empty draft ready and ordered ids',()=>{const s=createWaypointState();eq(s.snapshot().status,'empty');s.add([0,0]);eq(s.snapshot().status,'draft');s.add([1,1]);eq(s.snapshot().status,'ready');eq(s.snapshot().pins.map(p=>p.id),['wp-1','wp-2']);});
  test('insert before destination',()=>{const s=createWaypointState();const a=s.add([0,0]),b=s.add([2,2]),c=s.add([1,1],1);eq(s.snapshot().pins.map(p=>p.id),[a,c,b]);s.undo();eq(s.snapshot().pins.map(p=>p.id),[a,b]);});
  test('replace stable identity and opposite endpoint',()=>{const s=createWaypointState();const a=s.add([0,0]),b=s.add([1,1]);s.replace(a,[2,2]);eq(s.snapshot().pins,[{id:a,coordinate:[2,2]},{id:b,coordinate:[1,1]}]);s.undo();eq(s.snapshot().pins[0].coordinate,[0,0]);});
  test('remove restore same id',()=>{const s=createWaypointState();const a=s.add([0,0]),b=s.add([1,1]);s.remove(a);eq(s.snapshot().status,'draft');s.undo();eq(s.snapshot().pins.map(p=>p.id),[a,b]);});
  test('move both directions and undo',()=>{const s=createWaypointState();const a=s.add([0,0]),b=s.add([1,1]),c=s.add([2,2]);s.move(a,2);eq(s.snapshot().pins.map(p=>p.id),[b,c,a]);s.move(a,0);eq(s.snapshot().pins.map(p=>p.id),[a,b,c]);s.undo();s.undo();eq(s.snapshot().pins.map(p=>p.id),[a,b,c]);});
  test('invalid edits atomic',()=>{const s=createWaypointState();const a=s.add([0,0]);const before=s.snapshot();for(const at of [[181,0],[0,91],[NaN,0],[0,0,0],null])reject(()=>s.add(at));reject(()=>s.replace(a,[0,Infinity]));reject(()=>s.move(a,1));reject(()=>s.remove('missing'));reject(()=>s.add([1,1],-1));eq(s.snapshot(),before);});
  test('snapshot immutable and no input alias',()=>{const s=createWaypointState(),at=[0,0];s.add(at);const snap=s.snapshot();at[0]=7;s.add([1,1]);eq(snap.pins.length,1);eq(snap.pins[0].coordinate,[0,0]);if(!Object.isFrozen(snap)||!Object.isFrozen(snap.pins)||!Object.isFrozen(snap.pins[0])||!Object.isFrozen(snap.pins[0].coordinate))throw Error('Not frozen');});
  test('no-op not recorded',()=>{const s=createWaypointState();const a=s.add([0,0]);eq(s.replace(a,[0,0]),false);eq(s.move(a,0),false);eq(s.undo(),true);eq(s.snapshot().status,'empty');eq(s.undo(),false);});
  test('ids never recycled on undo',()=>{const s=createWaypointState();const a=s.add([0,0]);s.undo();if(s.add([0,0])===a)throw Error('Recycled id');});
  test('capacity and undo bound',()=>{const s=createWaypointState({maxPins:2,maxUndo:1});s.add([0,0]);s.add([1,1]);reject(()=>s.add([2,2]));eq(s.undo(),true);eq(s.undo(),false);eq(s.snapshot().pins.length,1);});
  test('many pins and independent instances',()=>{const s=createWaypointState(),other=createWaypointState();for(let i=0;i<1000;i++)s.add([i/1000,51]);eq(s.snapshot().pins.length,1000);eq(other.snapshot().pins.length,0);for(let i=0;i<256;i++)eq(s.undo(),true);eq(s.snapshot().pins.length,744);eq(s.undo(),false);});
  test('mixed action undo',()=>{const s=createWaypointState();const a=s.add([0,0]),b=s.add([1,1]),c=s.add([2,2]);const before=s.snapshot().pins;s.move(c,0);s.replace(b,[3,3]);s.remove(a);s.add([4,4],1);for(let i=0;i<4;i++)eq(s.undo(),true);eq(s.snapshot().pins,before);});
  return count;
}
console.log(`${runTests(createWaypointState)} waypoint cases passed`);

Advance

A JavaScript module in the scope folder of GridAtlas that fetches grid 400kV and CVAA ratchets, using SHA-256 from postcodes.io.

interactiongridatlas / tools/scope/advance.mjs · lines 1–423 of 432 · Entry point · pattern replaceExactlyOnce (shared by 3 files)

What it does
It fetches grid 400kV and CVAA ratchets. Defines 18 functions or classes, including moveDirectory, removePath, runNodeCheck, finishScope, finishFinal. Uses libraries node:fs, node:path, node:child_process. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Inputs & outputs
In: data source: postcodes.io; JSON file current-v5.json; JSON file live-set.json; JSON file current.json; GeoJSON file grid_400kv.geojson; JSON file modules.json; JSON file cvaa-ratchets.json; DuckDB queries.
Downstream impact
Used directly by 1 file: GridAtlas Scope Loop Workflow (gridatlas).
What it achieves
It removes path (`removePath`), runs node check (`runNodeCheck`) and replaces exactly once (`replaceExactlyOnce`). Defines `moveDirectory`, `removePath`, `runNodeCheck` and 15 more. It reads `./current.json`.
Why it matters
Run by GridAtlas Scope Loop Workflow.
Application
gridatlas · tools/scope · JavaScript module
Uses
GridAtlas — Scope (script call), Verify Compose (script call), Loop (script call), GridAtlas — Atlas Page (estate URL), node:fs, node:path, node:child_process
Used by
run by GridAtlas Scope Loop Workflow (workflow run)
Produces
moveDirectory, removePath, runNodeCheck, finishScope, finishFinal, temporaryAtlasRouter, rootRouter, rewriteLivePointers, scope1, scope2, scope3, replaceExactlyOnce
Defines here
moveDirectory, removePath, runNodeCheck, finishScope, finishFinal, temporaryAtlasRouter, rootRouter, rewriteLivePointers, scope1, scope2, scope3, replaceExactlyOnce, buildLocationSearchCartridge, scope4, updateCompositionPointers, scope5, retireScopeLoopWorkflow, scope6
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/scope/advance.mjs:1-423 · blob 60f6981de167c45f5576217c6790d6ea9ddcd057 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, network, process, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import fs from 'node:fs';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import {
  ROOT, SCOPE_DIR, MASTER_NAME, CURRENT_RELEASE, SHARED_400KV_CARTRIDGE,
  EXPECTED_RELEASES, invariant, listScopeDocuments, activeScope, readJson,
  writeJson, writeText, writeFrontMatter, nextGeneration, scopeFileName,
  scopeMarkdown, sha256PublishedFile, githubOutput, relativePosix
} from './lib.mjs';

const MASTER_PATH = path.join(SCOPE_DIR, MASTER_NAME);
const LIVE_POINTERS = [
  path.join(ROOT, 'releases', 'current-v5.json'),
  path.join(ROOT, 'state', 'live-set.json')
];

function moveDirectory(from, to) {
  if (fs.existsSync(from) && fs.existsSync(to)) throw new Error(`both source and destination exist: ${relativePosix(from)} and ${relativePosix(to)}`);
  if (!fs.existsSync(from)) {
    invariant(fs.existsSync(to), `missing both source and destination for ${relativePosix(from)}`);
    return;
  }
  fs.mkdirSync(path.dirname(to), { recursive: true });
  fs.renameSync(from, to);
}

function removePath(target) {
  if (fs.existsSync(target)) fs.rmSync(target, { recursive: true, force: true });
}

function runNodeCheck(filePath) {
  const result = spawnSync(process.execPath, ['--check', filePath], { cwd: ROOT, encoding: 'utf8' });
  invariant(result.status === 0, `${relativePosix(filePath)} syntax check failed: ${result.stderr || result.stdout}`);
}

function finishScope(document, nextScope, slug, title, body) {
  const generation = nextGeneration(String(document.data.generation));
  const nextName = scopeFileName(generation, nextScope, slug);
  writeFrontMatter(document.filePath, { status: 'done', next: nextName });
  writeText(path.join(SCOPE_DIR, nextName), scopeMarkdown({
    generation,
    scope: nextScope,
    parent: document.name,
    title,
    body
  }));
  writeFrontMatter(MASTER_PATH, { active_scope: nextScope });
  return { nextName, generation };
}

function finishFinal(document) {
  const closureGeneration = nextGeneration(String(document.data.generation));
  writeFrontMatter(document.filePath, { status: 'done', next: null });
  writeFrontMatter(MASTER_PATH, { status: 'done', active_scope: null, closure_generation: closureGeneration });
  const closureName = `${closureGeneration}-closure.md`;
  writeText(path.join(SCOPE_DIR, closureName), `---\nschema: "gridatlas.scope-closure.v1"\ngeneration: "${closureGeneration}"\nstatus: "done"\nparent: "${document.name}"\n---\n# GridAtlas scope loop closed\n\nAll six bounded scopes are complete. The loop schedule is retired. The immutable shell remains \`${CURRENT_RELEASE}\`; future application changes must be SHA-256 cartridges ordered by \`atlas  … [line shortened here: 453 characters; full line on GitHub]
  return { nextName: '', generation: closureGeneration };
}

function temporaryAtlasRouter() {
  return `<!doctype html>\n<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Grid Atlas</title></head><body><p><a id="open" href="./releases/${CURRENT_RELEASE}/">Open Grid Atlas</a></p><script type="module">const current=await fetch('./current.json',{cache:'no-store'}).then(response=>{if(!response.ok)throw new Error('current.json   … [line shortened here: 650 characters; full line on GitHub]
}

function rootRouter() {
  return `<!doctype html>\n<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="gridatlas-current-route" content="atlas"><title>Grid Atlas</title><script>(()=>{const target='./atlas/';window.location.replace(target+window.location.search+window.location.hash);})();</script></head><body data-gridatlas-current-route="atlas"><main>  … [line shortened here: 484 characters; full line on GitHub]
}

function rewriteLivePointers(routerGeneration) {
  const pointer = readJson(LIVE_POINTERS[0]);
  pointer.current.live_url = 'https://ventusltd.github.io/gridatlas/atlas/';
  pointer.current.route = '/gridatlas/atlas/';
  pointer.current.release_route = `/gridatlas/atlas/releases/${CURRENT_RELEASE}/`;
  pointer.current.runtime.shared_cartridge_path = `atlas/releases/cartridges/${SHARED_400KV_CARTRIDGE}/grid_400kv.geojson`;
  pointer.current.atlas_router_generation = routerGeneration;
  pointer.predecessor.live_url = `https://ventusltd.github.io/gridatlas/atlas/releases/${pointer.predecessor.release_id}/`;
  pointer.predecessor.route = `/gridatlas/atlas/releases/${pointer.predecessor.release_id}/`;
  pointer.rollback.route = `/gridatlas/atlas/releases/${pointer.rollback.release_id}/`;
  pointer.atlas = {
    schema: 'gridatlas.router.v1',
    generation: routerGeneration,
    stable_route: '/gridatlas/atlas/',
    immutable_release_route: `/gridatlas/atlas/releases/${CURRENT_RELEASE}/`,
    no_new_application_copy: true
  };
  for (const filePath of LIVE_POINTERS) writeJson(filePath, pointer);
}

function scope1(document) {
  const releaseRoot = path.join(ROOT, 'atlas', 'releases');
  fs.mkdirSync(releaseRoot, { recursive: true });
  for (const release of EXPECTED_RELEASES) moveDirectory(path.join(ROOT, release), path.join(releaseRoot, release));
  moveDirectory(
    path.join(ROOT, 'cartridges', SHARED_400KV_CARTRIDGE),
    path.join(releaseRoot, 'cartridges', SHARED_400KV_CARTRIDGE)
  );

  const generation = String(document.data.generation);
  writeJson(path.join(ROOT, 'atlas', 'current.json'), {
    schema: 'gridatlas.current.v1',
    generation,
    architecture: 'MOVED_RELEASE_BASELINE',
    live_route: '/gridatlas/atlas/',
    release_id: CURRENT_RELEASE,
    release_route: `/gridatlas/atlas/releases/${CURRENT_RELEASE}/`,
    shell_index: `./releases/${CURRENT_RELEASE}/index.html`,
    last_known_green: `/gridatlas/atlas/releases/${CURRENT_RELEASE}/`,
    cartridge_order: [],
    cartridges: []
  });
  writeText(path.join(ROOT, 'atlas', 'index.html'), temporaryAtlasRouter());
  writeText(path.join(ROOT, 'index.html'), rootRouter());
  rewriteLivePointers(generation);

  return finishScope(document, 2, 'modularise-immutable-shell-and-cartridges', 'Scope 2 — modularise the Atlas shell and cartridges', `Do only this scope.\n\n## Changes\n\n- Replace the temporary Atlas redirect with the stable SHA-verifying composer in \`atlas/index.html\`.\n- Keep \`${CURRENT_RELEASE}\` byte-identical as the immutable shell.\n- Define ordered cartridges in \`atlas/current.json\`;  … [line shortened here: 1,036 characters; full line on GitHub]
}

function scope2(document) {
  const loaderSource = fs.readFileSync(path.join(ROOT, 'tools', 'scope', 'payloads', 'atlas-loader.html'), 'utf8');
  writeText(path.join(ROOT, 'atlas', 'index.html'), loaderSource);
  const previous = readJson(path.join(ROOT, 'atlas', 'current.json'));
  const generation = String(document.data.generation);
  writeJson(path.join(ROOT, 'atlas', 'current.json'), {
    schema: 'gridatlas.current.v2',
    generation,
    previous_generation: previous.generation,
    architecture: 'IMMUTABLE_SHELL_PLUS_HASHED_CARTRIDGES',
    live_route: '/gridatlas/atlas/',
    release_id: CURRENT_RELEASE,
    release_route: `/gridatlas/atlas/releases/${CURRENT_RELEASE}/`,
    shell: {
      release_id: CURRENT_RELEASE,
      index: `./releases/${CURRENT_RELEASE}/index.html`,
      base: `./releases/${CURRENT_RELEASE}/`
    },
    cartridge_order: [],
    cartridges: [],
    last_known_green: {
      release_id: CURRENT_RELEASE,
      route: `/gridatlas/atlas/releases/${CURRENT_RELEASE}/`
    },
    contracts: {
      new_full_application_folders: 0,
      cartridge_sha256_required: true,
      cartridge_order_explicit: true,
      shell_mutation_forbidden: true
    }
  });

  for (const obsolete of ['successor', 'successor-202608291239', 'successor-202608291430', 'v8-mirror']) {
    removePath(path.join(ROOT, 'ui', obsolete));
  }
  removePath(path.join(ROOT, 'assets'));
  removePath(path.join(ROOT, 'cartridges'));
  writeText(path.join(ROOT, 'atlas', 'README.md'), `# Atlas runtime\n\n\`atlas/index.html\` is the stable composer. It fetches one immutable shell from \`atlas/releases/\`, verifies each listed cartridge with SHA-256, replaces only named cartridge slots, and writes the composed document.\n\nThe only mutable application pointer is \`atlas/current.json\`. New features must be bounded cartridges; do   … [line shortened here: 436 characters; full line on GitHub]

  return finishScope(document, 3, 'apply-pipelinenews-lessons', 'Scope 3 — apply PipelineNews repository lessons', `Do only this scope.\n\n## Changes\n\n- Record the inspected PipelineNews tree and the patterns adopted by GridAtlas.\n- Define stable module namespaces for cartridges, manifests, state, and UI source.\n- Preserve the archived one-off workflows as evidence; do not reactivate them.\n\n  … [line shortened here: 665 characters; full line on GitHub]
}

function scope3(document) {
  const generation = String(document.data.generation);
  writeText(path.join(ROOT, 'atlas', 'architecture', `${generation}-pipelinenews-lessons.md`), `# PipelineNews lessons applied to GridAtlas\n\nSource repository: https://github.com/Ventusltd/pipelinenews  \nInspected tree: \`83d9c430b283f8beaa8c0a05e42b14d4a4784623\`\n\n## Adopted\n\n- Stable source areas for UI, cartridges, manifests, state and automation.\n- Timestamped scope records and compile  … [line shortened here: 887 characters; full line on GitHub]
  writeJson(path.join(ROOT, 'atlas', 'modules.json'), {
    schema: 'gridatlas.modules.v1',
    generation,
    source_patterns_from: {
      repository: 'Ventusltd/pipelinenews',
      tree: '83d9c430b283f8beaa8c0a05e42b14d4a4784623'
    },
    modules: {
      composer: './index.html',
      cartridges: './cartridges/',
      manifests: './manifests/',
      state: './state/',
      immutable_releases: './releases/',
      ui_source: '../ui/'
    },
    timestamp_policy: 'TIMESTAMPS_FOR_SCOPES_MANIFESTS_AND_OUTPUTS_NOT_STABLE_MODULE_NAMES'
  });
  const currentPath = path.join(ROOT, 'atlas', 'current.json');
  const current = readJson(currentPath);
  current.generation = generation;
  current.previous_generation = current.previous_generation || '202608301321';
  current.provenance = {
    ...(current.provenance || {}),
    pipelinenews_repository: 'https://github.com/Ventusltd/pipelinenews',
    pipelinenews_tree: '83d9c430b283f8beaa8c0a05e42b14d4a4784623',
    cvaa_guide: 'https://github.com/Ventusltd/cvaa/blob/main/202608301321-gridatlas-amnesia-vaccine.txt'
  };
  writeJson(currentPath, current);

  return finishScope(document, 4, 'add-uk-location-search-cartridge', 'Scope 4 — add UK postcode and town location search', `Do only this scope.\n\n## Changes\n\n- Derive \`atlas/cartridges/202608301136-place-postcode-search.js\` from the immutable shell search script.\n- Add the postcodes.io postcode, outcode and OS Open Names place lane.\n- Keep REPD results first and exact REPD identity/deep-li  … [line shortened here: 971 characters; full line on GitHub]
}

function replaceExactlyOnce(source, search, replacement, label) {
  const first = source.indexOf(search);
  invariant(first >= 0, `search patch missing ${label}`);
  invariant(source.indexOf(search, first + search.length) < 0, `search patch ${label} is not unique`);
  return source.slice(0, first) + replacement + source.slice(first + search.length);
}

function buildLocationSearchCartridge(source) {
  let output = source;
  output = replaceExactlyOnce(
    output,
    "  const DUCKDB_MODULE = 'https://cdn.jsdelivr.net/npm/@duckdb/duckdb-wasm@1.29.0/+esm';",
    "  const GEOCODER_BASE = 'https://api.postcodes.io';\n  const DUCKDB_MODULE = 'https://cdn.jsdelivr.net/npm/@duckdb/duckdb-wasm@1.29.0/+esm';",
    'GEOCODER_BASE insertion'
  );
  output = replaceExactlyOnce(output, "    schema: 'gridatlas.v9-place-postcode-search.v1',", "    schema: 'gridatlas.v9-place-postcode-search.v2',", 'schema bump');
  output = replaceExactlyOnce(output, "    generation: '202608300453',", "    generation: '202608301136',", 'generation bump');
  output = replaceExactlyOnce(
    output,
    '    parquet_url: PARQUET_URL,',
    "    geocoder: GEOCODER_BASE,\n    geocoder_requests: 0,\n    geocoder_failures: [],\n    last_location_selection: null,\n    parquet_url: PARQUET_URL,",
    'geocoder state'
  );
  output = replaceExactlyOnce(output, '  async function queryOfficialRepd(query) {', '  async function queryOfficialRepd(query, serial = null) {', 'queryOfficialRepd signature');
  output = replaceExactlyOnce(output, '    const serial = ++activeQuerySerial;\n', '', 'old serial increment');
  output = replaceExactlyOnce(output, '    if (serial !== activeQuerySerial) return [];\n', '    if (serial !== null && serial !== activeQuerySerial) return [];\n', 'serial guard');

  const renderStart = output.indexOf('  function renderResults(');
  const waitStart = output.indexOf('  async function waitForCapturedMap');
  invariant(renderStart >= 0 && waitStart > renderStart, 'render/execute replacement markers missing');
  const gazetteer = fs.readFileSync(path.join(ROOT, 'tools', 'scope', 'patches', '202608301136-gazetteer.jsfrag'), 'utf8');
  const renderExecute = fs.readFileSync(path.join(ROOT, 'tools', 'scope', 'patches', '202608301136-render-execute.jsfrag'), 'utf8');
  output = `${output.slice(0, renderStart)}${gazetteer}\n${renderExecute}${output.slice(waitStart)}`;

  output = output.replace(/input\.setAttribute\('placeholder',\s*'[^']*'\);/, "input.setAttribute('placeholder', 'Search project, UK postcode or town...');");
  output = output.replace(/input\.setAttribute\('aria-label',\s*'[^']*'\);/, "input.setAttribute('aria-label', 'Search project, UK postcode or town');");

  for (const required of [
    "const GEOCODER_BASE = 'https://api.postcodes.io'",
    "kind: 'postcode'",
    "kind: 'postcode_district'",
    "kind: 'place'",
    'Promise.all([',
    "url.searchParams.delete('repd_ref')",
    'fly to only, not a REPD project',
    'No REPD project, UK postcode or place match'
  ]) invariant(output.includes(required), `generated location cartridge missing ${required}`);
  return output;
}

function scope4(document) {
  const sourcePath = path.join(ROOT, 'atlas', 'releases', CURRENT_RELEASE, '202608291818-place-postcode-search.js');
  const cartridgePath = path.join(ROOT, 'atlas', 'cartridges', '202608301136-place-postcode-search.js');
  const cartridge = buildLocationSearchCartridge(fs.readFileSync(sourcePath, 'utf8'));
  writeText(cartridgePath, cartridge);
  runNodeCheck(cartridgePath);

  const contractPath = path.join(ROOT, 'ui', 'cartridges', '202608301136-uk-gazetteer-flyto.mjs');
  writeText(contractPath, `export const ATLAS_V9_UK_GAZETTEER_FLYTO_CONTRACT = Object.freeze({\n  schema: 'gridatlas.cartridge.v1',\n  generation: '202608301136',\n  activation: 'explicit-user-query-only',\n  externalGeocoderRequests: 2,\n  provider: 'postcodes.io',\n  resultClass: 'LOCATION_ONLY',\n  proximityEstablishesIdentity: false,\n  setsDeepLink: false\n});\n`);
  runNodeCheck(contractPath);

  const currentPath = path.join(ROOT, 'atlas', 'current.json');
  const current = readJson(currentPath);
  const generation = String(document.data.generation);
  current.previous_generation = current.generation;
  current.generation = generation;
  current.cartridge_order = ['uk-gazetteer-flyto'];
  current.cartridges = [{
    id: 'uk-gazetteer-flyto',
    generation: '202608301136',
    type: 'script',
    slot: 'replace-script',
    replace_script: '202608291818-place-postcode-search.js',
    path: './cartridges/202608301136-place-postcode-search.js',
    sha256: sha256PublishedFile(cartridgePath),
    contract: '../ui/cartridges/202608301136-uk-gazetteer-flyto.mjs',
    result_class: 'LOCATION_ONLY',
    sets_deep_link: false
  }];
  current.search_lanes = {
    repd: { external_requests: 0, identity_claims: 'EXACT_REPD_REF_ONLY', first: true },
    uk_gazetteer: {
      provider: 'postcodes.io',
      endpoints: ['postcodes', 'outcodes', 'places'],
      identity_claims: 'none',
      external_requests_per_query_max: 2,
      result_class: 'LOCATION_ONLY'
    }
  };
  writeJson(currentPath, current);

  return finishScope(document, 5, 'compile-and-attest-cartridge-composition', 'Scope 5 — compile and attest the cartridge composition', `Do only this scope.\n\n## Changes\n\n- Create one timestamped composition manifest from the immutable shell and ordered cartridge hashes.\n- Update \`atlas/current.json\`, \`atlas/state/live-set.json\`, and the existing repository live pointers.\n- Run the struct  … [line shortened here: 822 characters; full line on GitHub]
}

function updateCompositionPointers(current, manifestPath) {
  const pointer = readJson(LIVE_POINTERS[0]);
  pointer.current.atlas_composition = {
    schema: 'gridatlas.composition-pointer.v1',
    generation: current.generation,
    route: current.live_route,
    shell_release_id: current.shell.release_id,
    cartridge_order: current.cartridge_order,
    manifest: manifestPath.replace(/^\.\//, 'atlas/')
  };
  for (const filePath of LIVE_POINTERS) writeJson(filePath, pointer);
}

function scope5(document) {
  const currentPath = path.join(ROOT, 'atlas', 'current.json');
  const current = readJson(currentPath);
  const generation = String(document.data.generation);
  const previousGeneration = current.generation;
  current.previous_generation = previousGeneration;
  current.generation = generation;

  const releaseDirectory = path.join(ROOT, 'atlas', 'releases', CURRENT_RELEASE);
  const manifestRelative = `./manifests/${generation}-composition.json`;
  const manifestPath = path.join(ROOT, 'atlas', 'manifests', `${generation}-composition.json`);
  const manifest = {
    schema: 'gridatlas.composition-manifest.v1',
    generation,
    parent_generation: previousGeneration,
    live_route: current.live_route,
    shell: {
      release_id: CURRENT_RELEASE,
      index: current.shell.index,
      base: current.shell.base,
      hashes: {
        index_html: sha256PublishedFile(path.join(releaseDirectory, 'index.html')),
        css: sha256PublishedFile(path.join(releaseDirectory, 'ventusv8.css')),
        engine: sha256PublishedFile(path.join(releaseDirectory, 'ventus-corev8engine.js')),
        maplibre_worker_bridge: sha256PublishedFile(path.join(releaseDirectory, '202608292311-maplibre-worker-bridge.js')),
        pre_snapped_adapter: sha256PublishedFile(path.join(releaseDirectory, '202608292126-pre-snapped-config-adapter.js'))
      }
    },
    shared_runtime: {
      path: `./releases/cartridges/${SHARED_400KV_CARTRIDGE}/grid_400kv.geojson`,
      sha256: sha256PublishedFile(path.join(ROOT, 'atlas', 'releases', 'cartridges', SHARED_400KV_CARTRIDGE, 'grid_400kv.geojson'))
    },
    cartridge_order: current.cartridge_order,
    cartridges: current.cartridges,
    acceptance: {
      full_application_copies_created: 0,
      immutable_shell_modified: false,
      exact_repd_identity_lane_preserved: true,
      uk_location_lane_result_class: 'LOCATION_ONLY',
      external_location_failure_isolated: true,
      runtime_browser_verification: 'REQUIRED_BY_202608301321-verify-live.yml'
    },
    scope_file: document.name
  };
  writeJson(manifestPath, manifest);
  current.composition_manifest = manifestRelative;
  writeJson(currentPath, current);
  writeJson(path.join(ROOT, 'atlas', 'state', 'live-set.json'), {
    schema: 'gridatlas.atlas-live-set.v1',
    generation,
    live_route: current.live_route,
    release_id: current.release_id,
    shell: current.shell,
    cartridge_order: current.cartridge_order,
    composition_manifest: manifestRelative,
    last_known_green: current.last_known_green
  });
  updateCompositionPointers(current, manifestRelative);

  const verification = spawnSync(process.execPath, ['tools/scope/verify-compose.mjs'], { cwd: ROOT, encoding: 'utf8' });
  invariant(verification.status === 0, `composition verification failed: ${verification.stderr || verification.stdout}`);

  return finishScope(document, 6, 'close-and-harden-cicd-loop', 'Scope 6 — close and harden the CI/CD loop', `Do only this scope.\n\n## Changes\n\n- Write the CVAA application and ratchet record.\n- Confirm only the scope loop and live verifier remain active; all 21 prior workflows remain archived.\n- Retire the scope loop schedule after closure.\n- Write the timestamped closure record and dispatc  … [line shortened here: 785 characters; full line on GitHub]
}

function retireScopeLoopWorkflow() {
  const workflowPath = path.join(ROOT, '.github', 'workflows', '202608301321-scope-loop.yml');
  let workflow = fs.readFileSync(workflowPath, 'utf8');
  workflow = replaceExactlyOnce(workflow, '# scope-loop-mode: active', '# scope-loop-mode: retired', 'scope loop mode marker');
  const start = workflow.indexOf('# BEGIN ACTIVE TRIGGERS');
  const endMarker = '# END ACTIVE TRIGGERS';
  const end = workflow.indexOf(endMarker);
  invariant(start >= 0 && end > start, 'scope loop trigger markers missing');
  const retired = `# BEGIN ACTIVE TRIGGERS\non:\n  workflow_dispatch:\n# END ACTIVE TRIGGERS`;
  workflow = `${workflow.slice(0, start)}${retired}${workflow.slice(end + endMarker.length)}`;
  writeText(workflowPath, workflow);
}

function scope6(document) {
  const generation = String(document.data.generation);
  writeText(path.join(ROOT, 'governance', `${generation}-cvaa-gridatlas-application.md`), `# CVAA applied to GridAtlas\n\nGuide: https://github.com/Ventusltd/cvaa/blob/main/202608301321-gridatlas-amnesia-vaccine.txt\n\n## Active antibodies\n\n- One active numbered scope at a time.\n- One deterministic scope per workflow run.\n- Zero top-level full Atlas release directories.\n- Exactly eight immuta  … [line shortened here: 829 characters; full line on GitHub]
  writeJson(path.join(ROOT, 'state', 'cvaa-ratchets.json'), {
    schema: 'gridatlas.cvaa-ratchets.v1',
    generation,
    maximums: {
      top_level_full_release_directories: 0,
      active_workflows: 2,
      active_numbered_scopes: 0,
      future_full_application_copies: 0,
      mutable_application_pointers: 1
    },
    exact: {
      immutable_release_baseline: 8,
      archived_legacy_workflows: 21
    },
    enforcement: 'tools/scope/loop.mjs'
  });
  retireScopeLoopWorkflow();
  const currentPath = path.join(ROOT, 'atlas', 'current.json');
  const current = readJson(currentPath);
  current.scope_closure = { generation, status: 'DONE', scopes: 6, schedule_retired: true };
  writeJson(currentPath, current);

  const verification = spawnSync(process.execPath, ['tools/scope/verify-compose.mjs'], { cwd: ROOT, encoding: 'utf8' });
  invariant(verification.status === 0, `final composition verification failed: ${verification.stderr || verification.stdout}`);
  return finishFinal(document);
}

const handlers = new Map([
  [1, scope1], [2, scope2], [3, scope3], [4, scope4], [5, scope5], [6, scope6]
]);

try {
  const documents = listScopeDocuments();
  const document = activeScope(documents);
  invariant(document, 'no active scope to advance');
  const handler = handlers.get(Number(document.data.scope));
  invariant(handler, `no deterministic handler for scope ${document.data.scope}`);
  const result = handler(document);
  const commitMessage = `${document.data.generation}-gridatlas-scope-${String(document.data.scope).padStart(2, '0')}: ${document.body.split('\n')[0].replace(/^#\s*/, '')}`;
  githubOutput({
    completed_scope: document.data.scope,
    completed_scope_file: document.name,