GLOBALGRID2050 / EXPLORE CODE

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

Scan GridAtlas Versions and 9 more files

A Python command-line tool in the history folder that scans repo (`scan_repo`). It is built from the run step (`run`).

669 lines of JavaScript and Python from gridatlas, in 10 files. Topic: Maps, GIS and field navigation. Section 631 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. CI Unified Preservation Gate automation · gridatlas / tools/ci/unified-preservation-gate.py lines 1–69
  2. Scan GridAtlas Versions storage · gridatlas / tools/history/scan_gridatlas_versions.py lines 1–211
  3. Browser Test test · gridatlas / tools/journey/browser.test.mjs lines 1–152
  4. Build Module storage · gridatlas / tools/journey/build-module.mjs lines 1–13
  5. Build storage · gridatlas / tools/journey/build.mjs lines 1–39
  6. Contract Test test · gridatlas / tools/journey/contract.test.mjs lines 1–30
  7. Controller Test test · gridatlas / tools/journey/controller.test.mjs lines 1–75
  8. GridAtlas — Journey ingest · gridatlas / tools/journey/module.mjs lines 1–40
  9. Serve ingest · gridatlas / tools/journey/serve.mjs lines 1–20
  10. Bootstrap render · gridatlas / tools/journey/src/bootstrap.js lines 1–20

CI Unified Preservation Gate

A Python command-line tool in the tools folder of GridAtlas covering unified authorised changes, using SHA-256.

automationgridatlas / tools/ci/unified-preservation-gate.py · lines 1–69 of 69 · Entry point

What it does
Defines git, paths, check, workflows, main. Uses libraries json, subprocess, pathlib. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage field_execution (path word 'gate'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Inputs & outputs
In: JSON file unified-authorised-changes.json; JSON file current.json.
Downstream impact
Used directly by 1 file: GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
It is built from the git step (`git`), the paths step (`paths`) and the check step (`check`). V9.201 additive change gate. Run from a full Git checkout of the exact candidate.
Why it matters
Run by GridAtlas PR File Size Guard Workflow.
Application
gridatlas · tools/ci · Python CLI
Uses
json, subprocess, pathlib
Used by
run by GridAtlas PR File Size Guard Workflow (workflow run)
Produces
git, paths, check, main
Defines here
git, paths, check, workflows, main
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/ci/unified-preservation-gate.py:1-69 · blob c36d0864494c050f83f04d38df889b88072ab863 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
"""V9.201 additive change gate. Run from a full Git checkout of the exact candidate.
Complements (does not replace) tools/twin/preserve.mjs and browser regressions.
"""
import json
import subprocess
from pathlib import Path

BASE = 'a31234b180c991509e81621dc12d67c051ac6a59'
REGISTER = 'tools/ci/unified-authorised-changes.json'
PROTECTED = ('atlas/v/', 'atlas/releases/', 'atlas/cartridges/', 'data/')
POINTERS = {'atlas/current.json', 'atlas/index.html'}


def git(root, *args):
    return subprocess.check_output(['git', '-C', str(root), *args])


def paths(root, rev):
    return set(git(root, 'ls-tree', '-r', '--name-only', '-z', rev).decode().split('\0')[:-1])


def check(root, base, head, register):
    errors = []
    if register.get('baseline') != base:
        raise ValueError('register baseline mismatch')
    rules = register['paths']
    for path, rule in rules.items():
        if rule.get('status') not in ('A', 'M') or not rule.get('purpose', '').strip():
            raise ValueError(f'invalid authorisation: {path}')
    git(root, 'merge-base', '--is-ancestor', base, head)
    raw = git(root, 'diff', '--name-status', '--no-renames', '-z', base, head).decode().split('\0')[:-1]
    if len(raw) % 2:
        raise ValueError('malformed diff')
    changed = list(zip(raw[::2], raw[1::2]))
    for status, path in changed:
        print(f'{status}\t{path}')
        if path in POINTERS or (status != 'A' and path.startswith(PROTECTED)):
            errors.append(f'protected path: {path}')
        if status not in ('A', 'M') or rules.get(path, {}).get('status') != status:
            errors.append(f'unauthorised {status}: {path}')
    before, after = paths(root, base), paths(root, head)
    def workflows(items):
        return {p for p in items if p.startswith('.github/workflows/') and p.endswith(('.yml', '.yaml'))}
    if len(workflows(before)) != 9 or workflows(before) != workflows(after):
        errors.append('nine-workflow identity not preserved')
    # Mode changes to existing files are not authorised by text edits.
    summary = git(root, 'diff', '--summary', '--no-renames', base, head).decode()
    if any(line.lstrip().startswith('mode change ') for line in summary.splitlines()):
        errors.append('existing file mode changed')
    return changed, errors


def main():
    root = Path(git(Path.cwd(), 'rev-parse', '--show-toplevel').decode().strip())
    head = git(root, 'rev-parse', 'HEAD').decode().strip()
    register = json.loads(git(root, 'show', f'{head}:{REGISTER}'))
    changed, errors = check(root, BASE, head, register)
    print(f'Baseline {BASE}; candidate {head}; {len(changed)} changed paths')
    for error in errors:
        print('FAIL:', error)
    if errors:
        return 1
    print('PASS: authorised path delta, protected pointers, nine workflow identities')
    print('Historical SHA-256 and behavioural checks remain separate mandatory gates.')
    return 0


if __name__ == '__main__':
    raise SystemExit(main())

Scan GridAtlas Versions

A Python command-line tool in the history folder that scans repo (`scan_repo`). It is built from the run step (`run`).

storagegridatlas / tools/history/scan_gridatlas_versions.py · lines 1–211 of 211 · Entry point

What it does
It lists and searches its content. Defines run, scan_repo, main. Uses libraries __future__, argparse, json, os, re. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (path 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: command-line arguments.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Bounded Git-history scanner for GridAtlas release and workflow pattern recognition. It accepts `--repo`, `--reference-repo` and `--output`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
gridatlas · tools/history · Python CLI
Uses
__future__, argparse, json, os, re, subprocess, time, collections
Used by
none found
Produces
run, scan_repo, main
Defines here
run, scan_repo, main
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/history/scan_gridatlas_versions.py:1-211 · blob 0d496c61630672af2398013489f1cf9eeadb437d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Bounded Git-history scanner for GridAtlas release and workflow pattern recognition.

The scanner is intentionally mechanical: GitHub Actions checks out the complete
repository and this program reads Git history directly. It never edits history and
stops at the requested wall-clock budget (30 seconds by default).
"""

from __future__ import annotations

import argparse
import json
import os
import re
import subprocess
import time
from collections import Counter, defaultdict
from datetime import datetime, timezone
from pathlib import Path
from typing import Any

RELEASE_RE = re.compile(r"(?:^|/)(20\d{10,12}-atlas-v\d+(?:\.\d+)?)($|/)", re.I)
SCANNER_RE = re.compile(r"(?:scan|scanner).*(?:version|history)|(?:version|history).*(?:scan|scanner)", re.I)
TIMESTAMP_RE = re.compile(r"(?:^|/)(20\d{10,12})[-_/]")
WORKFLOW_RE = re.compile(r"^\.github/(?:workflows|workflow-archive)/(.+\.ya?ml)$")
SEARCH_RE = re.compile(r"(?:place|postcode|gazetteer|geocod|flyto|fly-to|address)", re.I)
COMPARATOR_RE = re.compile(r"(?:compare|comparator|audit|verify|proof|readback)", re.I)


def run(repo: Path, args: list[str], deadline: float, *, allow_fail: bool = False) -> str:
    remaining = max(0.2, deadline - time.monotonic())
    try:
        proc = subprocess.run(
            ["git", "-C", str(repo), *args],
            check=not allow_fail,
            text=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            timeout=remaining,
        )
    except subprocess.TimeoutExpired as exc:
        raise TimeoutError(f"git {' '.join(args)} exceeded bounded scanner budget") from exc
    if proc.returncode and not allow_fail:
        raise RuntimeError(proc.stderr.strip() or f"git {' '.join(args)} failed")
    return proc.stdout


def scan_repo(repo: Path, deadline: float, *, include_parent_duplicate_check: bool) -> dict[str, Any]:
    head = run(repo, ["rev-parse", "HEAD"], deadline).strip()
    branch = run(repo, ["rev-parse", "--abbrev-ref", "HEAD"], deadline).strip()
    commit_count = int(run(repo, ["rev-list", "--all", "--count"], deadline).strip() or "0")
    tree_paths = [p for p in run(repo, ["ls-tree", "-r", "--name-only", "HEAD"], deadline).splitlines() if p]

    previous_paths: list[str] = []
    if include_parent_duplicate_check:
        parent = run(repo, ["rev-parse", "HEAD^"], deadline, allow_fail=True).strip()
        if parent:
            previous_paths = [
                p for p in run(repo, ["ls-tree", "-r", "--name-only", parent], deadline).splitlines() if p
            ]

    # One bounded Git command scans all commit metadata and touched paths. Record separators
    # make parsing deterministic and avoid a subprocess per commit/version.
    history_text = run(
        repo,
        [
            "log",
            "--all",
            "--date=iso-strict",
            "--pretty=format:@@COMMIT@@%H%x09%ad%x09%s",
            "--name-only",
        ],
        deadline,
    )

    commits: list[dict[str, Any]] = []
    current: dict[str, Any] | None = None
    for line in history_text.splitlines():
        if line.startswith("@@COMMIT@@"):
            if current is not None:
                commits.append(current)
            payload = line.removeprefix("@@COMMIT@@")
            sha, committed_at, subject = (payload.split("\t", 2) + ["", ""])[:3]
            current = {"sha": sha, "committed_at": committed_at, "subject": subject, "paths": []}
        elif current is not None and line.strip():
            current["paths"].append(line.strip())
    if current is not None:
        commits.append(current)

    release_first_seen: dict[str, dict[str, str]] = {}
    path_change_counts: Counter[str] = Counter()
    workflow_counts: Counter[str] = Counter()
    search_changes: list[dict[str, str]] = []
    comparator_changes: list[dict[str, str]] = []
    timestamp_groups: defaultdict[str, set[str]] = defaultdict(set)

    for commit in commits:
        for item in commit["paths"]:
            path_change_counts[item] += 1
            release_match = RELEASE_RE.search(item)
            if release_match:
                release_id = release_match.group(1)
                release_first_seen.setdefault(
                    release_id,
                    {
                        "commit": commit["sha"],
                        "committed_at": commit["committed_at"],
                        "subject": commit["subject"],
                    },
                )
            workflow_match = WORKFLOW_RE.match(item)
            if workflow_match:
                workflow_counts[workflow_match.group(1)] += 1
            if SEARCH_RE.search(item) or SEARCH_RE.search(commit["subject"]):
                search_changes.append({"commit": commit["sha"], "subject": commit["subject"], "path": item})
            if COMPARATOR_RE.search(item) or COMPARATOR_RE.search(commit["subject"]):
                comparator_changes.append({"commit": commit["sha"], "subject": commit["subject"], "path": item})
            timestamp_match = TIMESTAMP_RE.search(item)
            if timestamp_match:
                timestamp_groups[timestamp_match.group(1)].add(item)

    self_path = 'tools/history/scan_gridatlas_versions.py'
    current_scanners = sorted(p for p in tree_paths if SCANNER_RE.search(p))
    previous_scanners = sorted(p for p in previous_paths if SCANNER_RE.search(p) and p != self_path)
    releases_in_head = sorted({m.group(1) for p in tree_paths if (m := RELEASE_RE.search(p))})

    return {
        "path": str(repo),
        "head": head,
        "branch": branch,
        "commit_count": commit_count,
        "commits_scanned": len(commits),
        "files_in_head": len(tree_paths),
        "scanner_candidates_before_this_change": previous_scanners,
        "scanner_candidates_now": current_scanners,
        "scanner_was_already_present": bool(previous_scanners),
        "releases_in_head": releases_in_head,
        "release_first_seen": dict(sorted(release_first_seen.items())),
        "workflow_files_touched": dict(workflow_counts.most_common()),
        "most_changed_paths": path_change_counts.most_common(30),
        "search_pattern_changes": search_changes[:100],
        "comparator_pattern_changes": comparator_changes[:100],
        "timestamp_groups": {key: sorted(value)[:40] for key, value in sorted(timestamp_groups.items())},
    }


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--repo", default=".")
    parser.add_argument("--reference-repo")
    parser.add_argument("--output", required=True)
    parser.add_argument("--max-seconds", type=float, default=30.0)
    args = parser.parse_args()

    started = time.monotonic()
    deadline = started + max(1.0, min(args.max_seconds, 30.0))
    output: dict[str, Any] = {
        "schema": "gridatlas.history-pattern-scan.v1",
        "generated_at": datetime.now(timezone.utc).isoformat(),
        "max_seconds": max(1.0, min(args.max_seconds, 30.0)),
        "status": "RUNNING",
        "truncated": False,
        "repositories": {},
        "findings": [],
    }

    try:
        primary = scan_repo(Path(args.repo).resolve(), deadline, include_parent_duplicate_check=True)
        output["repositories"]["gridatlas"] = primary
        if args.reference_repo and Path(args.reference_repo).exists() and time.monotonic() < deadline:
            output["repositories"]["cvaa_reference"] = scan_repo(
                Path(args.reference_repo).resolve(), deadline, include_parent_duplicate_check=False
            )

        output["findings"] = [
            {
                "id": "scanner-duplication-check",
                "status": "REUSE" if primary["scanner_was_already_present"] else "CREATE_ONCE",
                "evidence": primary["scanner_candidates_before_this_change"],
            },
            {
                "id": "immutable-release-lineage",
                "status": "OBSERVED",
                "release_count": len(primary["release_first_seen"]),
                "head_release_count": len(primary["releases_in_head"]),
            },
            {
                "id": "cartridge-not-app-copy",
                "status": "REQUIRED",
                "rule": "v9.5 changes one hashed cartridge and current composition; no new full application folder",
            },
        ]
        output["status"] = "PASS"
    except TimeoutError as exc:
        output["status"] = "PASS_BOUNDED"
        output["truncated"] = True
        output["warning"] = str(exc)
    except Exception as exc:  # fail closed in CI, but always leave a useful report
        output["status"] = "FAIL"
        output["error"] = repr(exc)

    output["elapsed_seconds"] = round(time.monotonic() - started, 3)
    target = Path(args.output)
    target.parent.mkdir(parents=True, exist_ok=True)
    target.write_text(json.dumps(output, indent=2, sort_keys=True) + "\n", encoding="utf-8")
    print(json.dumps({"status": output["status"], "elapsed_seconds": output["elapsed_seconds"], "output": str(target)}))
    return 0 if output["status"].startswith("PASS") else 1


if __name__ == "__main__":
    raise SystemExit(main())

Browser Test

A test in the journey folder of GridAtlas that checks Build and Serve, using SHA-256.

testgridatlas / tools/journey/browser.test.mjs · lines 1–152 of 152 · Entry point

What it does
It tests its inputs. Uses libraries node:fs, node:path, node:os, node:assert/strict, node:crypto. Side effects: changes the web page (DOM); reads or writes files.
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. README: "browser.test.mjs uses the actual Atlas composer and native MapLibre, with the local fixture composition generated by build.mjs (not committed or published by this source change)."
Inputs & outputs
In: JSON file receipt.json. Out: JSON file receipt.json; JSON file failure.json; interactive map; WebGL/WebGPU drawing.
Downstream impact
Used directly by 1 file: GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
Real native GridAtlas composer acceptance; local HTTP serves Git-published LF text bytes.
Why it matters
Run by GridAtlas PR File Size Guard Workflow.
Application
gridatlas · tools/journey · test
Uses
Build (import), Serve (import), node:fs, node:path, node:os, node:assert/strict, node:crypto, node:url
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/journey/browser.test.mjs:1-152 · blob 839bf3adf047a8e4bb92573cded5c1a0519c1b21 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/** Real native GridAtlas composer acceptance; local HTTP serves Git-published LF text bytes. */
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import assert from 'node:assert/strict';
import {createHash} from 'node:crypto';
import {pathToFileURL} from 'node:url';
import {ROOT, G as FIXTURE_GENERATION} from './build.mjs';
const G = process.env.JOURNEY_BROWSER_GENERATION || FIXTURE_GENERATION;
import {createPreviewServer} from './serve.mjs';
const pwModule = process.env.PLAYWRIGHT_MODULE;
const pw = await import(pwModule && path.isAbsolute(pwModule) ? pathToFileURL(pwModule).href : pwModule || 'playwright');
const runStartedUTC=new Date().toISOString();
const out = process.env.JOURNEY_BROWSER_OUTPUT || path.join(os.tmpdir(), 'gridatlas-gj03-browser-' + G + '-' + runStartedUTC.replace(/[:.]/g,'-'));
fs.mkdirSync(out, {recursive: true});
fs.rmSync(path.join(out,'receipt.json'),{force:true});
console.log(JSON.stringify({browserOutput:out,runStartedUTC}));
const server = await createPreviewServer();
const origin = `http://127.0.0.1:${server.address().port}`;
let browser;
const receipts = [], errors = [], failed = [], assets = [], assetReads=[];
try {
  browser = await pw.chromium.launch({headless:true,args:['--use-gl=angle','--use-angle=swiftshader','--enable-webgl','--ignore-gpu-blocklist']});
  const context = await browser.newContext({...pw.devices['Pixel 7'], viewport:{width:390,height:844}});
  const page = await context.newPage();
  page.on('pageerror', e => errors.push(e.message));
  page.on('requestfailed', r => failed.push({url:r.url(),error:r.failure()?.errorText}));
  page.on('response',r=>{if(r.url()==='https://cdn.jsdelivr.net/npm/maplibre-gl@3.6.2/dist/maplibre-gl.js')assetReads.push(r.body().then(b=>assets.push({url:r.url(),status:r.status(),bytes:b.length,sha256:createHash('sha256').update(b).digest('hex')})));});
  await page.goto(`${origin}/atlas/v/${G}/`, {waitUntil:'domcontentloaded', timeout:90000});
  await page.waitForFunction(() => window.__GRIDATLAS_V9_MAP__ && document.querySelector('#gridatlas-gj03 .gj-launch'), null, {timeout:90000});
  await page.waitForFunction(() => window.__GRIDATLAS_V9_MAP__?.getStyle()?.layers?.length > 0, null, {timeout:90000});
  const native = await page.evaluate(() => {const m=window.__GRIDATLAS_V9_MAP__; return {constructor:m.constructor.name,version:window.maplibregl?.version,canvas:!!m.getCanvas().getContext('webgl2') || !!m.getCanvas().getContext('webgl'),container:m.getContainer().id,existingLayers:m.getStyle().layers.length,existingLayerIds:m.getStyle().layers.map(l=>l.id)};});
  assert.equal(native.version, '3.6.2'); assert.ok(native.canvas); assert.ok(native.existingLayers > 0);
  await page.waitForFunction(() => {const s=window.__GRIDATLAS_MODULES__?.menuBar; return s?.installed || s?.failure;}, null, {timeout:90000});
  const menuState = await page.evaluate(()=>window.__GRIDATLAS_MODULES__.menuBar);
  assert.equal(menuState.installed,true,JSON.stringify(menuState));
  assert.equal(menuState.layer_controls,63);
  const nativeGrid = page.locator('#gridatlas-menu-bar-title-4');
  await nativeGrid.tap();
  const nativeJourney = page.locator('[data-journey-group="native-grid-menu"] button');
  await nativeJourney.tap();
  assert.equal(await page.evaluate(()=>window.__GRIDATLAS_MODULES__.gridJourneyPreview.snapshot().opened),true);
  await page.getByRole('button',{name:'Close Grid Journey',exact:true}).tap();
  assert.equal(await nativeGrid.evaluate(e => e === document.activeElement && e.getClientRects().length > 0),true,'Close returns focus to the visible native Grid title');
  await nativeGrid.tap();
  await nativeJourney.tap();
  await page.getByRole('button',{name:'Explore real grid nearby',exact:true}).tap();
  assert.equal(await nativeGrid.getAttribute('aria-expanded'),'true');
  assert.equal(await page.evaluate(()=>window.__GRIDATLAS_MODULES__.gridJourneyPreview.snapshot().opened),false);
  await nativeGrid.click();
  await page.locator('.gj-launch').click();
  await assert.match(await page.locator('.gj-status').textContent(),/Explore the physical grid/);
  assert.equal(await page.evaluate(()=>!!window.__GRIDATLAS_V9_MAP__.getSource('gridatlas-gj03-route')), false);
  await page.getByRole('button',{name:'Load SYNTHETIC demonstration',exact:true}).click();
  assert.equal(await page.evaluate(()=>!!window.__GRIDATLAS_V9_MAP__.getSource('gridatlas-gj03-route')), false);
  await page.getByRole('combobox',{name:'Explicit starting node'}).selectOption('A1');
  await page.waitForFunction(()=>window.__GRIDATLAS_MODULES__.gridJourneyPreview.snapshot().steps===8);
  await page.waitForFunction(()=>!!window.__GRIDATLAS_V9_MAP__.getLayer('gridatlas-gj03-schematic'),null,{timeout:60000});
  await page.getByRole('button',{name:'Next',exact:true}).click();
  assert.equal(await page.evaluate(()=>window.__GRIDATLAS_MODULES__.gridJourneyPreview.snapshot().step),1);
  await page.getByRole('button',{name:'Reset',exact:true}).click();
  for(let i=0;i<8;i++) await page.getByRole('button',{name:'Next',exact:true}).click();
  assert.match(await page.locator('.gj-status').textContent(), /backtrack/);
  for(const [width,height] of [[390,844],[393,852],[1440,1000],[844,390]]) {
    const stepBefore=await page.evaluate(()=>window.__GRIDATLAS_MODULES__.gridJourneyPreview.snapshot().step);
    await page.setViewportSize({width,height});
    await page.waitForFunction(()=>{const m=window.__GRIDATLAS_V9_MAP__,c=m.getCanvas(),d=m.getSource('gridatlas-gj03-route').serialize().data;return d.features.every(f=>f.geometry.coordinates.every(x=>{const p=m.project(x);return p.x>=0&&p.x<=c.clientWidth&&p.y>=0&&p.y<=c.clientHeight;}));});
    await page.waitForFunction(()=>{const m=window.__GRIDATLAS_V9_MAP__;return m.isSourceLoaded('gridatlas-gj03-route')&&m.isSourceLoaded('gridatlas-gj03-cursor');});
    await page.evaluate(()=>new Promise(resolve=>{const m=window.__GRIDATLAS_V9_MAP__;m.once('render',resolve);m.triggerRepaint();}));
    const renderedEdges=await page.evaluate(()=>{const m=window.__GRIDATLAS_V9_MAP__,c=m.getCanvas();return [...new Set(m.queryRenderedFeatures([[0,0],[c.clientWidth,c.clientHeight]],{layers:['gridatlas-gj03-verified','gridatlas-gj03-schematic']}).map(f=>f.properties.edgeUid))];});
    assert.equal(renderedEdges.length,3,'actual MapLibre rendered all three located synthetic edges');
    const layout=await page.evaluate(()=>{const p=document.querySelector('.gj-panel').getBoundingClientRect(),m=window.__GRIDATLAS_V9_MAP__,r=m.getContainer().getBoundingClientRect(),points=m.getSource('gridatlas-gj03-route').serialize().data.features.flatMap(f=>f.geometry.coordinates.map(c=>{const q=m.project(c);return{x:q.x+r.left,y:q.y+r.top};}));return {panel:{x:p.x,y:p.y,width:p.width,height:  … [line shortened here: 656 characters; full line on GitHub]
    assert.ok(layout.panel.x>=0 && layout.panel.y>=0 && layout.panel.x+layout.panel.width<=width+1 && layout.panel.y+layout.panel.height<=height+1);
    assert.ok(layout.controls.every(e=>e.h>=44)); assert.equal(layout.overflow,false);
    assert.ok(layout.points.every(q=>q.x<layout.panel.x||q.x>layout.panel.x+layout.panel.width||q.y<layout.panel.y||q.y>layout.panel.y+layout.panel.height),'route remains visible outside the panel: '+JSON.stringify(layout));
    assert.equal(await page.evaluate(()=>window.__GRIDATLAS_MODULES__.gridJourneyPreview.snapshot().step),stepBefore,'orientation retains step');
    const closeButton=page.getByRole('button',{name:'Close Grid Journey',exact:true});
    await closeButton.scrollIntoViewIfNeeded();
    assert.equal(await closeButton.evaluate(e=>{const r=e.getBoundingClientRect(),p=document.elementFromPoint(r.x+r.width/2,r.y+r.height/2);return p===e||e.contains(p);}),true,'Close remains hittable after rotation');
    await page.screenshot({path:path.join(out,`native-${width}x${height}.png`)});
    await closeButton.click();
    await page.keyboard.press('Enter'); // Close restored opener; keyboard reopens.
    assert.equal(await page.evaluate(()=>window.__GRIDATLAS_MODULES__.gridJourneyPreview.snapshot().step),stepBefore);
    receipts.push({viewport:{width,height},layout,renderedEdges,result:'PASS'});
  }
  await page.getByRole('button',{name:'Close Grid Journey',exact:true}).focus();
  await page.keyboard.press('Tab');
  assert.equal(await page.getByRole('button',{name:'Explore real grid nearby',exact:true}).evaluate(e=>e===document.activeElement),true);
  await page.keyboard.press('Shift+Tab'); await page.keyboard.press('Enter'); await page.keyboard.press('Enter');
  await page.emulateMedia({reducedMotion:'reduce'});
  await page.getByRole('button',{name:'Reset',exact:true}).click();
  await page.getByRole('button',{name:'Start · manual',exact:true}).focus(); await page.keyboard.press('Enter');
  await page.waitForTimeout(1200);
  assert.deepEqual(await page.evaluate(()=>{const s=window.__GRIDATLAS_MODULES__.gridJourneyPreview.snapshot();return {step:s.step,playing:s.playing};}),{step:1,playing:false});
  await page.getByRole('button',{name:'Close Grid Journey',exact:true}).focus(); await page.keyboard.press('Escape');
  assert.equal(await page.locator('.gj-launch').evaluate(e=>e===document.activeElement),true);
  assert.equal(await page.evaluate(()=>!!window.__GRIDATLAS_V9_MAP__.getSource('gridatlas-gj03-route')),false);
  await page.locator('.gj-launch').click();
  await page.waitForFunction(()=>!!window.__GRIDATLAS_V9_MAP__.getLayer('gridatlas-gj03-schematic'));
  await page.evaluate(()=>window.dispatchEvent(new CustomEvent('gridatlas:card-open',{detail:{owner:'offtakers'}})));
  assert.equal(await page.evaluate(()=>!!window.__GRIDATLAS_V9_MAP__.getSource('gridatlas-gj03-route')),false);
  assert.match(await page.locator('.gj-status').textContent(),/surrounding grid/);
  const foreign = {type:'FeatureCollection',features:[{type:'Feature',properties:{owner:'external-preserve'},geometry:{type:'Point',coordinates:[0,50]}}]};
  await page.evaluate(data=>window.__GRIDATLAS_V9_MAP__.addSource('gridatlas-gj03-cursor',{type:'geojson',data}),foreign);
  await page.getByRole('button',{name:'Load SYNTHETIC demonstration',exact:true}).click();
  await page.getByRole('combobox',{name:'Explicit starting node'}).selectOption('A1');
  await page.waitForFunction(()=>document.querySelector('.gj-status').textContent.includes('collision'));
  assert.match(await page.locator('.gj-status').textContent(),/^WITHHELD:/);
  assert.equal(await page.getByRole('button',{name:'Next',exact:true}).isDisabled(),true);
  assert.deepEqual(await page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.getSource('gridatlas-gj03-cursor').serialize().data),foreign);
  await page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.removeSource('gridatlas-gj03-cursor'));
  await page.evaluate(data=>{const m=window.__GRIDATLAS_V9_MAP__;m.addSource('journey-external',{type:'geojson',data});m.addLayer({id:'gridatlas-gj03-schematic',type:'circle',source:'journey-external'});},foreign);
  await page.getByRole('button',{name:'Load SYNTHETIC demonstration',exact:true}).click();
  await page.getByRole('combobox',{name:'Explicit starting node'}).selectOption('A1');
  await page.waitForFunction(()=>document.querySelector('.gj-status').textContent.includes('layer collision'));
  assert.equal(await page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.getLayer('gridatlas-gj03-schematic').source),'journey-external');
  await page.evaluate(()=>{const m=window.__GRIDATLAS_V9_MAP__;m.removeLayer('gridatlas-gj03-schematic');m.removeSource('journey-external');});
  await page.getByRole('button',{name:'Load SYNTHETIC demonstration',exact:true}).click();
  await page.getByRole('combobox',{name:'Explicit starting node'}).selectOption('A1');
  await page.waitForFunction(()=>!!window.__GRIDATLAS_V9_MAP__.getLayer('gridatlas-gj03-schematic'));
  // Real style reload retains the map instance and restores exactly one owned source/layer set.
  await page.evaluate(()=>{const m=window.__GRIDATLAS_V9_MAP__,s=m.getStyle();s.layers=s.layers.filter(l=>!l.id.startsWith('gridatlas-gj03-'));for(const k of Object.keys(s.sources))if(k.startsWith('gridatlas-gj03-'))delete s.sources[k];m.setStyle(s,{diff:false});});
  await page.waitForFunction(()=>!!window.__GRIDATLAS_V9_MAP__.getLayer('gridatlas-gj03-schematic'));
  assert.equal(await page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.getStyle().layers.filter(l=>l.id.startsWith('gridatlas-gj03-')).length),3);
  await page.emulateMedia({reducedMotion:'no-preference'});
  await page.getByRole('button',{name:'Start',exact:true}).click();
  await page.waitForTimeout(250);
  await page.getByRole('button',{name:'Pause',exact:true}).click();
  const stoppedAt=await page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.getSource('gridatlas-gj03-cursor').serialize().data);
  await page.waitForTimeout(1100);
  assert.deepEqual(await page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.getSource('gridatlas-gj03-cursor').serialize().data),stoppedAt);
  // Actual MapLibre repeated mount/destroy, no replacement map instance.
  for(let i=0;i<3;i++) {await page.evaluate(()=>window.__GRIDATLAS_MODULES__.gridJourneyPreview.destroy());assert.equal(await page.locator('#gridatlas-gj03').count(),0);await page.evaluate(()=>window.__GRIDATLAS_MODULES__.gridJourneyPreview.mount());assert.equal(await page.locator('#gridatlas-gj03').count(),1);}
  const finalMap = await page.evaluate(()=>({version:maplibregl.version,canvasCount:document.querySelectorAll('canvas.maplibregl-canvas').length,layers:window.__GRIDATLAS_V9_MAP__.getStyle().layers.length,layerIds:window.__GRIDATLAS_V9_MAP__.getStyle().layers.map(l=>l.id)}));
  assert.equal(finalMap.canvasCount,1);
  assert.ok(native.existingLayerIds.every(id=>finalMap.layerIds.includes(id)),'all initial Atlas layers preserved; existing asynchronous Atlas layers may arrive later');
  assert.ok(!finalMap.layerIds.some(id=>id.startsWith('gridatlas-gj03-')));
  await page.locator('.gj-launch').click();
  await page.getByRole('button',{name:'Load SYNTHETIC demonstration',exact:true}).click();
  await page.getByRole('combobox',{name:'Explicit starting node'}).selectOption('A1');
  await page.waitForFunction(()=>window.__GRIDATLAS_MODULES__.gridJourneyPreview.snapshot().steps===8);
  await page.getByRole('button',{name:'Start',exact:true}).click();
  await page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.remove());
  assert.equal(await page.locator('#gridatlas-gj03').count(),0);
  assert.equal(await page.evaluate(()=>window.__GRIDATLAS_MODULES__.gridJourneyPreview.snapshot().alive),false);
  assert.deepEqual(errors,[],'native page errors must be zero');
  await Promise.all(assetReads);assert.equal(assets.length,1);assert.equal(assets[0].status,200);
  const cartridgeSha256=createHash('sha256').update(fs.readFileSync(path.join(ROOT,`atlas/modules/${G}-grid-journey-preview.js`),'utf8').replace(/\r\n/g,'\n')).digest('hex');
  fs.writeFileSync(path.join(out,'receipt.json'),JSON.stringify({result:'PASS',runStartedUTC,runCompletedUTC:new Date().toISOString(),generation:G,cartridgeSha256,transport:'local read-only HTTP; LF published text bytes; actual existing composer and native MapLibre',assets,native,receipts,reducedMotion:'manual one step; no automatic progress after1200ms',keyboard:'Tab/ShiftTab and Enter operate co  … [line shortened here: 874 characters; full line on GitHub]
  console.log(JSON.stringify({result:'PASS',out,nativeVersion:native.version,existingLayers:native.existingLayers,viewports:receipts.length,errors,requestFailures:failed.length}));
} catch(e) {fs.writeFileSync(path.join(out,'failure.json'),JSON.stringify({message:e.message,stack:e.stack,errors,failed},null,2));throw e;}
finally {await browser?.close();await new Promise(r=>server.close(r));}

Build Module

A JavaScript module in the journey folder of GridAtlas that uses SHA-256. It is built from the option step (`option`).

storagegridatlas / tools/journey/build-module.mjs · lines 1–13 of 13 · Not reached from any entry point (candidate for review) · pattern option (shared by 6 files)

What it does
Defines option. Uses libraries node:fs, node:path, node:crypto. Side effects: reads or writes files.
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: command-line arguments.
What it achieves
Assemble the reusable Journey cartridge only; never writes compositions or pointers.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · tools/journey · JavaScript module
Uses
GridAtlas — Journey (import), node:fs, node:path, node:crypto
Used by
none found
Produces
option
Defines here
option
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/journey/build-module.mjs:1-13 · blob 6e03a696628bc624c3599f6fd929cdb9dbf383a4 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/** Assemble the reusable Journey cartridge only; never writes compositions or pointers. */
import fs from 'node:fs';
import path from 'node:path';
import {createHash} from 'node:crypto';
import {assembleModule} from './module.mjs';
const args=process.argv.slice(2);
function option(name){const i=args.indexOf(name);return i<0?undefined:args[i+1];}
const generation=option('--generation'),out=option('--out');
if(!generation||!out||args.length!==4)throw new Error('Usage: node tools/journey/build-module.mjs --generation YYYYMMDDHHMM --out FILE');
const {body}=assembleModule({generation});
fs.mkdirSync(path.dirname(path.resolve(out)),{recursive:true});
fs.writeFileSync(out,body);
console.log(JSON.stringify({generation,path:out,bytes:Buffer.byteLength(body),sha256:createHash('sha256').update(body).digest('hex')}));

Build

A JavaScript module in the journey folder of GridAtlas that reads synthetic branch, using SHA-256.

storagegridatlas / tools/journey/build.mjs · lines 1–39 of 39 · pattern assemble (shared by 13 files)

What it does
It loads synthetic branch. Defines read, hash, assemble, build. Uses libraries node:fs, node:path, node:url, node:crypto, node:assert/strict. Side effects: reads or writes files.
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. README: "assembleModule({generation}) from build.mjs returns {body,pin,fixture}"
Inputs & outputs
In: JSON file synthetic-branch.v1.json; JSON file current.json; command-line arguments.
Downstream impact
Used directly by 4 files: Browser Test (gridatlas); Serve (gridatlas); Cut Grid Explorer (gridatlas); Grid Explorer Proof (gridatlas). Reached from 11 other entry points, including GridAtlas Cartridge Proof Workflow (gridatlas); GridAtlas PR File Size Guard Workflow (gridatlas); Browser Test (gridatlas).
What it achieves
It is built from the read step (`read`), the hash step (`hash`) and the assemble step (`assemble`). Deterministic, pinned-source preview assembly. Never modifies a live pointer. It reads `tools/journey/fixtures/synthetic-branch.v1.json`.
Why it matters
Imported by Serve. Run by Cut Grid Explorer and Grid Explorer Proof. Checked by Browser Test.
Application
gridatlas · tools/journey · JavaScript module
Uses
GridAtlas — Release (import), GridAtlas — Journey (import), node:fs, node:path, node:url, node:crypto, node:assert/strict
Used by
imported by Browser Test (import), imported by Serve (import), run by Cut Grid Explorer (script call), run by Grid Explorer Proof (script call)
Produces
ROOT, G, assemble, build
Defines here
read, hash, assemble, build
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/journey/build.mjs:1-39 · blob 2bbdc7bcf0c9eceeb0ae3ded66a4cafb82acddb9 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/** Deterministic, pinned-source preview assembly. Never modifies a live pointer. */
import fs from 'node:fs';
import path from 'node:path';
import {fileURLToPath} from 'node:url';
import {createHash} from 'node:crypto';
import assert from 'node:assert/strict';
import {deriveCurrent, rerootForPreview} from '../release/lib.mjs';
export const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
export const G = '202611171525', PARENT = '202611161720', BUDGET = 72000;
const read = p => fs.readFileSync(path.join(ROOT, p), 'utf8').replace(/\r\n/g, '\n');
const hash = b => createHash('sha256').update(b).digest('hex');
import {assembleModule} from './module.mjs';
export {assembleModule} from './module.mjs';
export function assemble() {
  const {body, pin, fixture} = assembleModule();
  const parentText = read(`atlas/manifests/${PARENT}-composition.json`), parent = JSON.parse(parentText);
  const composition = JSON.parse(deriveCurrent(parentText));
  Object.assign(composition, {generation: G, previous_generation: PARENT, superseded_generation: PARENT, candidate_predecessor: PARENT, composition_version: 'GJ-03-preview-1', composition_id: 'native-grid-journey-preview', composition_manifest: `./manifests/${G}-composition.json`, composition_note: 'Isolated native GJ-03 preview; real routes withheld. No operative release change.'});
  composition.cartridge_order.push('grid-journey-preview');
  composition.cartridges.push({id: 'grid-journey-preview', generation: G, version: 'GJ-03-preview-1', type: 'script', slot: 'after-cartridge', after: 'uk-offtakers-overlay', path: `./modules/${G}-grid-journey-preview.js`, sha256: hash(body), bytes: Buffer.byteLength(body), byte_budget: BUDGET, budget_status: 'PROPOSED_PREVIEW_ONLY_NOT_OWNER_RELEASE_APPROVAL', preview_only: true, real_routes_accept  … [line shortened here: 560 characters; full line on GitHub]
  const manifest = {...composition, parent_generation: PARENT, version: 'GJ-03-preview-1', cut_at_utc: '2026-11-17T15:25:00.000Z', note: 'GJ milestone preview, separate from Pipeline News editions. No owner promotion requested or assumed.', candidate_status: 'PREVIEW_ONLY_REAL_ROUTES_WITHHELD', acceptance: {full_application_copies_created: 0, immutable_shell_modified: false, owner_release_acceptan  … [line shortened here: 511 characters; full line on GitHub]
  manifest.acceptance.synthetic_fixture = {path: 'tools/journey/fixtures/synthetic-branch.v1.json', sha256: hash(read('tools/journey/fixtures/synthetic-branch.v1.json')), sourceBundleSha: fixture.ledger.sourceBundleSha, synthetic: true};
  assert.equal(parent.generation, PARENT);
  return new Map([
    [`atlas/modules/${G}-grid-journey-preview.js`, body],
    [`atlas/manifests/${G}-composition.json`, JSON.stringify(manifest, null, 1) + '\n'],
    [`atlas/v/${G}/current.json`, rerootForPreview(deriveCurrent(JSON.stringify(manifest)))],
    [`atlas/v/${G}/index.html`, read('atlas/index.html')]
  ]);
}
export function build(check = false) {
  const outputs = assemble();
  for (const [p, bytes] of outputs) {
    if (check) assert.equal(read(p), bytes, `Rebuild drift: ${p}`);
    else { fs.mkdirSync(path.dirname(path.join(ROOT, p)), {recursive: true}); fs.writeFileSync(path.join(ROOT, p), bytes); }
  }
  return {generation: G, cartridgeBytes: Buffer.byteLength(outputs.get(`atlas/modules/${G}-grid-journey-preview.js`)), proposedBudgetBytes: BUDGET, files: [...outputs.keys()]};
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) console.log(JSON.stringify(build(process.argv.includes('--check'))));

Contract Test

A test in the journey folder of GridAtlas that uses SHA-256.

testgridatlas / tools/journey/contract.test.mjs · lines 1–30 of 30 · Entry point · pattern clone (shared by 15 files)

What it does
It tests its inputs. Defines read, clone, 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 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: JSON file synthetic-branch.v1.json; JSON file reviewed-pair.v1.json.
Downstream impact
Used directly by 1 file: GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
Defines `read`, `clone` and `make`. It reads `./fixtures/synthetic-branch.v1.json`.
Why it matters
Run by GridAtlas PR File Size Guard Workflow.
Application
gridatlas · tools/journey · test
Uses
node:assert/strict, node:fs, node:crypto, ./vendor/65d48a851fc2ac74b13f939a0184e11298e7e5bd/edge-cover-journey.js
Used by
run by GridAtlas PR File Size Guard Workflow (workflow run)
Produces
read, clone, make
Defines here
read, clone, 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/journey/contract.test.mjs:1-30 · blob da3521b41556b0b849c57bf6deb22c0c4b581be3 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import assert from 'node:assert/strict';
import fs from 'node:fs';
import {createHash} from 'node:crypto';
import {planJourney} from './vendor/65d48a851fc2ac74b13f939a0184e11298e7e5bd/edge-cover-journey.js';
const read = p => JSON.parse(fs.readFileSync(new URL(p, import.meta.url)));
const fixture = read('./fixtures/synthetic-branch.v1.json'), pair = read('./fixtures/reviewed-pair.v1.json');
const clone = x => JSON.parse(JSON.stringify(x));
const make = (f, chosenNode) => planJourney({sourceBytes: f.networkText, ledger: f.ledger, query: {seed: {chosenNode}, bounds: {maxNodes: 25, maxEdges: 30, maxMoves: 60, maxGeometryBytes: 16000}}});
const p = await make(fixture, 'A1');
assert.equal(p.status, 'complete'); assert.equal(p.edgeCatalog.length, 4); assert.equal(p.steps.length, 8);
assert.ok(p.steps.some(s => s.traversal === 'backtrack'));
assert.ok(p.edgeCatalog.some(e => e.geometryStatus === 'verified_circuit_and_polyline'));
assert.equal(p.edgeCatalog.filter(e => e.schematic).length, 2);
assert.equal(p.edgeCatalog.filter(e => !e.coordinates).length, 1);
assert.equal(p.physicalUnits, null); assert.equal(p.planSha256, (await make(fixture, 'A1')).planSha256);
assert.equal((await make(fixture, '')).refusal, 'chosen_node_required');
assert.equal((await make(fixture, 'nearest')).refusal, 'seed_not_in_source');
const blocked = clone(fixture); blocked.ledger.nodes[0].rights = {status: 'blocked'};
assert.equal((await make(blocked, 'A1')).refusal, 'seed_rights_withheld');
const edgeBlocked = clone(fixture); for (const e of edgeBlocked.ledger.edges) e.rights = {status: 'blocked'};
assert.equal((await make(edgeBlocked, 'A1')).steps.length, 0);
const emptyLedger = clone(fixture); emptyLedger.ledger.nodes = []; emptyLedger.ledger.edges = [];
assert.equal((await make(emptyLedger, 'A1')).refusal, 'seed_identity_unreviewed');
const unsupported = clone(fixture); unsupported.ledger.edges[0].geometryStatus = 'invented';
await assert.rejects(make(unsupported, 'A1'), /unknown geometry evidence/);
const digestMismatch = clone(fixture); digestMismatch.networkText += ' ';
await assert.rejects(make(digestMismatch, 'A1'), /digest does not match/);
assert.equal((await make(pair, 'A1')).eligibleEdges, 1);
assert.equal(createHash('sha256').update(fs.readFileSync(new URL('./fixtures/reviewed-pair.v1.json', import.meta.url))).digest('hex'), '174ac6824c5a8fa5d161d6529840211d7d94472e2b2a172abdc25643b0230087');
console.log('Journey UI input contract: canonical shared fixture, deterministic branch/backtrack, polyline/schematic/unlocated, no-seed/nearest/rights/identity/geometry/digest refusals PASS');

Controller Test

A test in the journey folder of GridAtlas that checks Controller and Bootstrap. It is built from the clone step (`clone`), the target class (`Target`) and the harness step (`harness`).

testgridatlas / tools/journey/controller.test.mjs · lines 1–75 of 75 · Entry point · pattern harness (shared by 3 files)

What it does
It tests the REPD register. Defines 8 functions or classes, including clone, Target, harness, E, all. Uses libraries node:test, node:assert/strict, node:fs, node:vm. Side effects: changes the web page (DOM); reads or writes files.
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. Domain terms in the code: the REPD register.
Inputs & outputs
In: JSON file synthetic-branch.v1.json.
Downstream impact
Used directly by 1 file: GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
Lifecycle negatives use a small DOM/map stub. It reads `./fixtures/synthetic-branch.v1.json`.
Why it matters
Run by GridAtlas PR File Size Guard Workflow.
Application
gridatlas · tools/journey · test
Uses
Controller (import), Bootstrap (new URL import.meta.url), node:test, node:assert/strict, node:fs, node:vm, ./vendor/65d48a851fc2ac74b13f939a0184e11298e7e5bd/edge-cover-journey.js
Used by
run by GridAtlas PR File Size Guard Workflow (workflow run)
Produces
clone, Target, harness, E, all, button, choose, settled
Defines here
clone, Target, harness, E, all, button, choose, settled
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/journey/controller.test.mjs:1-75 · blob ceced37c9e952f53e59e78bf00a2de2ee8eefa83 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/** Lifecycle negatives use a small DOM/map stub. Native GIS acceptance is browser.test.mjs. */
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import vm from 'node:vm';
import {createJourneyController} from './src/controller.mjs';
import {planJourney} from './vendor/65d48a851fc2ac74b13f939a0184e11298e7e5bd/edge-cover-journey.js';
const fixture=JSON.parse(fs.readFileSync(new URL('./fixtures/synthetic-branch.v1.json',import.meta.url)));
const clone=x=>JSON.parse(JSON.stringify(x));
class Target {
  events=new Map();
  addEventListener(t,f){if(!this.events.has(t))this.events.set(t,new Set());this.events.get(t).add(f);}
  removeEventListener(t,f){this.events.get(t)?.delete(f);}
  emit(t,e={}){for(const f of [...(this.events.get(t)||[])])f({type:t,preventDefault(){},...e});}
  listeners(){return [...this.events.values()].reduce((n,s)=>n+s.size,0);}
}
function harness({planner=planJourney,input=fixture,reduced=false,ready=true,layerHosts=false,layerReady=true}={}) {
  const D={activeElement:null}, W=new Target(), media=new Target(); media.matches=reduced;
  let nextRaf=0;const rafs=new Map();W.matchMedia=()=>media;W.requestAnimationFrame=f=>{rafs.set(++nextRaf,f);return nextRaf;};W.cancelAnimationFrame=id=>rafs.delete(id);
  class E extends Target {
    constructor(tag){super();this.tag=tag;this.children=[];this.attrs={};this.style={};this.textContent='';this.disabled=false;this.hidden=false;}
    setAttribute(k,v){this.attrs[k]=v;if(k==='disabled')this.disabled=true;if(k==='hidden')this.hidden=true;}
    appendChild(e){e.parent=this;this.children.push(e);return e;}
    replaceChildren(){this.children=[];}
    remove(){if(this.parent)this.parent.children=this.parent.children.filter(e=>e!==this);}
    focus(){D.activeElement=this;}
  }
  const container=new E('div');container.attrs.id='map-container';
  if(layerHosts)for(const id of ['scada-ui-container','fs-curtain-keys']){const h=new E('div');h.attrs.id=id;h.querySelector=selector=>selector==='input[data-layer-id]'&&layerReady?{focus(){}}:null;container.appendChild(h);}
  const all=(e=container)=>[e,...e.children.flatMap(c=>all(c))];
  D.createElement=t=>new E(t);D.getElementById=id=>all().find(e=>e.attrs.id===id)||null;
  const map=new Target(), sources=new Map(),layers=new Map();map.on=map.addEventListener;map.off=map.removeEventListener;
  map.getContainer=()=>container;map.getStyle=()=>ready?{layers:[...layers.values()]}:undefined;
  map.addSource=(id,v)=>{assert.ok(!sources.has(id));sources.set(id,{data:clone(v.data),writes:0,setData(d){this.data=clone(d);this.writes++;}});};
  map.getSource=id=>sources.get(id);map.removeSource=id=>sources.delete(id);
  map.addLayer=l=>{assert.ok(!layers.has(l.id));layers.set(l.id,clone(l));};map.getLayer=id=>layers.get(id);map.removeLayer=id=>layers.delete(id);map.fitBounds=()=>{};
  const c=createJourneyController({map,document:D,window:W,planner,fixture:clone(input),css:'',generation:'test'});
  const button=s=>all().find(e=>e.tag==='button'&&e.textContent===s),select=()=>all().find(e=>e.tag==='select');
  function choose(){c.open();button('Load SYNTHETIC demonstration').emit('click');select().value='A1';select().emit('change');}
  return {D,W,map,media,rafs,sources,layers,c,all,button,choose,ready(v){ready=v;},status:()=>all().find(e=>e.attrs.role==='status')?.textContent,tick(t){const active=[...rafs.values()];rafs.clear();active.forEach(f=>f(t));}};
}
async function settled(h){for(let i=0;i<250;i++){if(h.c.snapshot().status!=='withheld'||h.status()?.startsWith('WITHHELD:'))return;await new Promise(r=>setTimeout(r,2));}throw new Error('Planner did not settle');}
test('missing map refuses before DOM mount',()=>assert.throws(()=>createJourneyController({map:null}),/Native MapLibre/));
test('explicit demo/seed, branch/backtrack, reset and owned cleanup',async()=>{const h=harness();h.c.open();assert.equal(h.sources.size,0);h.choose();await settled(h);assert.equal(h.layers.size,3);assert.equal(h.sources.size,2);assert.equal(h.c.snapshot().steps,8);for(let i=0;i<8;i++)h.button('Next').emit('click');assert.equal(h.c.snapshot().step,8);assert.match(h.status(),/backtrack B1 → A1/);h.b  … [line shortened here: 699 characters; full line on GitHub]
for(const kind of ['source','layer'])test(`${kind} collision is terminal and never mutates external content`,async()=>{const h=harness();let external;if(kind==='source'){h.map.addSource('gridatlas-gj03-cursor',{data:{owner:'external'}});external=h.sources.get('gridatlas-gj03-cursor');}else{h.map.addLayer({id:'gridatlas-gj03-schematic',source:'external'});external=h.layers.get('gridatlas-gj03-schem  … [line shortened here: 844 characters; full line on GitHub]
test('style reload installs exactly one owned set without listener growth',async()=>{const h=harness();h.choose();await settled(h);for(let i=0;i<4;i++){h.sources.clear();h.layers.clear();h.map.emit('style.load');assert.equal(h.sources.size,2);assert.equal(h.layers.size,3);assert.equal(h.map.listeners(),3);}let frames=0;h.map.fitBounds=()=>frames++;h.map.emit('resize');assert.equal(frames,1);h.c.de  … [line shortened here: 411 characters; full line on GitHub]
test('replacement source with the same ID after style reload remains foreign',async()=>{const h=harness();h.choose();await settled(h);h.sources.clear();h.layers.clear();h.map.addSource('gridatlas-gj03-cursor',{data:{owner:'external-new-style'}});const foreign=h.sources.get('gridatlas-gj03-cursor');h.map.emit('style.load');assert.match(h.status(),/collision/);assert.equal(h.c.snapshot().status,'wit  … [line shortened here: 517 characters; full line on GitHub]
test('reduced motion is manual; preference changes cancel playback RAF',async()=>{const h=harness({reduced:true});h.choose();await settled(h);h.button('Start · manual').emit('click');assert.equal(h.c.snapshot().step,1);assert.equal(h.rafs.size,0);h.media.matches=false;h.media.emit('change');h.button('Start').emit('click');assert.equal(h.rafs.size,1);h.tick(0);h.tick(400);assert.equal(h.sources.get  … [line shortened here: 582 characters; full line on GitHub]
test('map removal cancels RAF/listeners and stale callback cannot resurrect UI',async()=>{const h=harness();h.choose();await settled(h);h.button('Start').emit('click');const stale=[...h.rafs.values()][0];h.sources.clear();h.layers.clear();h.map.getLayer=()=>{throw new Error('style already destroyed');};h.map.emit('remove');assert.equal(h.c.snapshot().alive,false);assert.equal(h.rafs.size,0);assert  … [line shortened here: 576 characters; full line on GitHub]
test('late asynchronous planning after close/destroy cannot add map resources',async()=>{let resolve;const h=harness({planner:()=>new Promise(r=>{resolve=r;})});h.choose();h.c.close();h.c.destroy();resolve(await planJourney({sourceBytes:fixture.networkText,ledger:fixture.ledger,query:{seed:{chosenNode:'A1'}}}));await new Promise(r=>setTimeout(r,0));assert.equal(h.sources.size,0);assert.equal(h.all  … [line shortened here: 416 characters; full line on GitHub]
test('blocked seed rights draws nothing',async()=>{const input=clone(fixture);input.ledger.nodes[0].rights={status:'blocked'};const h=harness({input});h.choose();await settled(h);assert.match(h.status(),/seed_rights_withheld/);assert.equal(h.sources.size,0);h.c.destroy();});
test('unsupported geometry output is refused by presentation',async()=>{const h=harness({planner:async()=>({status:'complete',steps:[{}],edgeCatalog:[{geometryStatus:'invented'}]})});h.choose();await settled(h);assert.match(h.status(),/Unsupported geometry/);assert.equal(h.sources.size,0);h.c.destroy();});
test('stylesheet arriving late and real card selection while closed',async()=>{const h=harness({ready:false});h.choose();await settled(h);assert.equal(h.sources.size,0);h.ready(true);h.map.emit('style.load');assert.equal(h.sources.size,2);h.c.close();h.W.emit('gridatlas:card-open');h.c.open();assert.equal(h.c.snapshot().status,'withheld');assert.equal(h.sources.size,0);assert.match(h.status(),/sur  … [line shortened here: 433 characters; full line on GitHub]
test('public bootstrap replaces a controller destroyed by native map.remove',()=>{const instances=[], firstMap={},nextMap={}, W={__GRIDATLAS_V9_MAP__:firstMap};const context={window:W,document:{},JourneyEngine:{},JourneyFixture:{},JourneyCSS:'',JourneyGeneration:'test',console,setTimeout,clearTimeout,createJourneyController(options){let alive=true;const c={options,snapshot:()=>({alive}),destroy(){  … [line shortened here: 802 characters; full line on GitHub]
test('missing-map bounded attachment timer is removed by public destroy',()=>{let timer,cleared=false,created=0;const W={};const context={window:W,document:{},JourneyEngine:{},JourneyFixture:{},JourneyCSS:'',JourneyGeneration:'test',console,setTimeout(f){timer=f;return 7;},clearTimeout(id){assert.equal(id,7);cleared=true;},createJourneyController(){created++;}};vm.runInNewContext(fs.readFileSync(n  … [line shortened here: 615 characters; full line on GitHub]

// Native launchers all target one controller; real selections must never reuse a demo plan.
test('Layers groups open the existing controller and are removed with it',()=>{const h=harness({layerHosts:true});assert.equal(h.c.snapshot().layerControls,2);const launchers=h.all().filter(e=>e.textContent==='Open Grid Journey');assert.equal(launchers.length,2);launchers[1].emit('click');assert.equal(h.c.snapshot().opened,true);assert.equal(launchers[0].attrs['aria-expanded'],'true');h.c.close();  … [line shortened here: 592 characters; full line on GitHub]
test('public Journey event carries labelled context and clears demonstration resources',async()=>{const h=harness();h.choose();await settled(h);h.W.emit('gridatlas:journey-open',{detail:{origin:{name:'<script>unsafe</script>',id:'REPD2470'}}});assert.equal(h.c.snapshot().opened,true);assert.deepEqual(h.c.snapshot().origin,{name:'<script>unsafe</script>',id:'REPD2470'});assert.equal(h.c.snapshot().  … [line shortened here: 652 characters; full line on GitHub]
test('public origin update handles malformed context without planning or network',()=>{let calls=0;const h=harness({planner:()=>{calls++;}});h.c.setOrigin({name:{untrusted:'object'},id:{bad:true}});assert.equal(h.c.snapshot().origin,null);assert.equal(h.c.snapshot().synthetic,false);assert.equal(calls,0);h.c.destroy();});

test('real-grid action delegates exact selected coordinates to the existing vicinity controller',()=>{const h=harness();let args;h.W.__GRIDATLAS_MODULES__={gridVicinity:{open(o){args=o;}}};h.c.open({origin:{id:'REPD2470',name:'Known record',at:[-0.5,52],type:'repd'}});h.button('Explore real grid nearby').emit('click');assert.deepEqual(args,{origin:{name:'Known record',id:'REPD2470',at:[-0.5,52],ty  … [line shortened here: 515 characters; full line on GitHub]
test('real-grid action does not forward null-island context or invent a route',()=>{const h=harness();let args;h.W.__GRIDATLAS_MODULES__={gridVicinity:{open(o){args=o;}}};h.c.open({origin:{id:'opaque',at:[0,0]}});h.button('Explore real grid nearby').emit('click');assert.equal(args.origin,undefined);assert.equal(h.sources.size,0);h.c.destroy();});

test('a real card event without explicit context clears the prior origin',()=>{const h=harness();h.c.open({origin:{id:'old',name:'Old asset',at:[-1,52],type:'repd'}});h.W.emit('gridatlas:card-open',{detail:{owner:'offtakers'}});assert.equal(h.c.snapshot().origin,null);let args;h.W.__GRIDATLAS_MODULES__={gridVicinity:{open(o){args=o;}}};h.button('Explore real grid nearby').emit('click');assert.equa  … [line shortened here: 442 characters; full line on GitHub]

test('without vicinity the primary action opens real native Grid controls and preserves selected coordinates',()=>{const h=harness();const grid=h.D.createElement('button');grid.attrs.id='gridatlas-menu-bar-title-4';grid.getAttribute=k=>grid.attrs[k];let clicks=0,center;grid.click=()=>{clicks++;grid.attrs['aria-expanded']='true';};h.map.getContainer().appendChild(grid);h.map.flyTo=o=>{center=o.cent  … [line shortened here: 689 characters; full line on GitHub]

test('before native menu readiness primary action reveals original real layer controls',()=>{const h=harness({layerHosts:true});const host=h.D.getElementById('scada-ui-container');let scrolled=false;host.scrollIntoView=()=>{scrolled=true;};h.c.open();h.button('Explore real grid nearby').emit('click');assert.equal(scrolled,true);assert.equal(h.c.snapshot().opened,false);assert.equal(h.sources.size,  … [line shortened here: 420 characters; full line on GitHub]

test('empty native hosts are not falsely marked engine-ready by a Journey key-group',()=>{const h=harness({layerHosts:true,layerReady:false});assert.equal(h.c.snapshot().layerControls,0);assert.equal(h.all().some(e=>e.attrs['data-journey-group']),false);h.c.destroy();});

test('Close restores visible Grid title when the native menu launcher is hidden',()=>{const h=harness({layerHosts:true});const grid=h.D.createElement('button');grid.attrs.id='gridatlas-menu-bar-title-4';h.map.getContainer().appendChild(grid);const button=h.all().find(e=>e.textContent==='Open Grid Journey');button.getClientRects=()=>[];button.emit('click');h.c.close();assert.equal(h.D.activeElement  … [line shortened here: 424 characters; full line on GitHub]

test('real-grid action stops its original event from closing the native menu it opens',()=>{const h=harness({layerHosts:true});const host=h.D.getElementById('scada-ui-container');host.scrollIntoView=()=>{};let stopped=false;h.c.open();h.button('Explore real grid nearby').emit('click',{stopPropagation(){stopped=true;}});assert.equal(stopped,true);h.c.destroy();});

GridAtlas — Journey

A JavaScript module in the tools folder that reads vendor pin, reviewed pair and synthetic branch, using SHA-256.

ingestgridatlas / tools/journey/module.mjs · lines 1–40 of 40

What it does
It loads vendor pin, reviewed pair and synthetic branch. Defines read, hash, assembleModule. Uses libraries node:fs, node:path, node:url, node:crypto, node:assert/strict. Side effects: reads or writes files.
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: JSON file vendor-pin.json; JSON file reviewed-pair.v1.json; JSON file synthetic-branch.v1.json.
Downstream impact
Used directly by 2 files: Build Module (gridatlas); Build (gridatlas). Reached from 12 other entry points, including GridAtlas Cartridge Proof Workflow (gridatlas); GridAtlas PR File Size Guard Workflow (gridatlas); Browser Test (gridatlas).
What it achieves
It is built from the read step (`read`), the hash step (`hash`) and the assemble module helper (`assembleModule`). Deterministic, pinned-source preview assembly. Never modifies a live pointer. It reads `tools/journey/vendor-pin.json`.
Why it matters
Imported by Build Module and Build.
Application
gridatlas · tools/journey · JavaScript module
Uses
node:fs, node:path, node:url, node:crypto, node:assert/strict
Used by
imported by Build Module (import), imported by Build (import)
Produces
ROOT, G, assembleModule
Defines here
read, hash, assembleModule
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/journey/module.mjs:1-40 · blob 3e7bf5c9790b29d7ddfc145687b0169294414377 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/** Deterministic, pinned-source preview assembly. Never modifies a live pointer. */
import fs from 'node:fs';
import path from 'node:path';
import {fileURLToPath} from 'node:url';
import {createHash} from 'node:crypto';
import assert from 'node:assert/strict';
export const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
export const G = '202611171525', PARENT = '202611161720', BUDGET = 72000;
const read = p => fs.readFileSync(path.join(ROOT, p), 'utf8').replace(/\r\n/g, '\n');
const hash = b => createHash('sha256').update(b).digest('hex');
export function assembleModule({generation = G} = {}) {
  assert.match(generation, /^\d{12}$/, "Generation must be a UTC minute identifier");
  const pin = JSON.parse(read('tools/journey/vendor-pin.json'));
  assert.equal(pin.commit, '65d48a851fc2ac74b13f939a0184e11298e7e5bd');
  const wrappers = [];
  const imports = {
    'network-topology.js': '',
    'journey-evidence.js': "import {index as topologyIndex} from './network-topology.js';",
    'edge-cover-journey.js': "import {canonicalJson, ordinal, prepareJourneyEvidence, sha256} from './journey-evidence.js';"
  };
  const aliases = {'network-topology.js': '', 'journey-evidence.js': 'const topologyIndex = JourneyTopology.index;', 'edge-cover-journey.js': 'const {canonicalJson, ordinal, prepareJourneyEvidence, sha256} = JourneyEvidence;'};
  const names = ['JourneyTopology', 'JourneyEvidence', 'JourneyEngine'];
  for (const [i, p] of pin.files.entries()) {
    const raw = fs.readFileSync(path.join(ROOT, 'tools/journey', p.vendorPath));
    assert.equal(raw.length, p.bytes, p.path); assert.equal(hash(raw), p.sha256, p.path);
    let text = raw.toString('utf8'); const file = path.basename(p.path);
    if (imports[file]) { assert.ok(text.includes(imports[file])); text = text.replace(imports[file], aliases[file]); }
    const exports = [...text.matchAll(/^export (?:async )?(?:function|const) ([A-Za-z_$][\w$]*)/gm)].map(m => m[1]);
    text = text.replace(/^export (?=(?:async )?(?:function|const) )/gm, '');
    assert.ok(!/^\s*(?:import|export) /m.test(text), 'Unexpected ESM syntax in pinned module');
    wrappers.push(`const ${names[i]} = (() => {\n${text}\nreturn Object.freeze({${exports.join(',')}});\n})();`);
  }
  assert.equal(hash(fs.readFileSync(path.join(ROOT, 'tools/journey/fixtures/reviewed-pair.v1.json'))), pin.sharedFixture.sha256);
  const fixture = JSON.parse(read('tools/journey/fixtures/synthetic-branch.v1.json'));
  assert.equal(fixture.synthetic, true);
  const controller = read('tools/journey/src/controller.mjs').replace('export function createJourneyController', 'function createJourneyController');
  const body = `/* GJ-03 PREVIEW ONLY. Canonical engine ${pin.repository}@${pin.commit}. No live pointer writes. */\n(() => {\n'use strict';\n${wrappers.join('\n')}\nconst JourneyFixture = ${JSON.stringify(fixture)};\nconst JourneyCSS = ${JSON.stringify(read('tools/journey/src/journey.css'))};\nconst JourneyGeneration = '${generation}';\n${controller}\n${read('tools/journey/src/bootstrap.js')}\n})  … [line shortened here: 407 characters; full line on GitHub]
  assert.ok(Buffer.byteLength(body) <= BUDGET, `Preview exceeds proposed ${BUDGET}B budget: ${Buffer.byteLength(body)}`);
  return {body, pin, fixture};
}

Serve

A JavaScript module in the journey folder of GridAtlas. It creates preview server (`createPreviewServer`).

ingestgridatlas / tools/journey/serve.mjs · lines 1–20 of 20

What it does
It loads data. Defines createPreviewServer. Uses libraries node:fs, node:path, node:http, node:url. Side effects: reads or writes files; starts processes.
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: command-line arguments.
Downstream impact
Used directly by 10 files: UKPN Paired Browser (gridatlas); UKPN Secondary Browser (gridatlas); Browser Test (gridatlas); Vicinity Entry Browser (gridatlas); and 6 more. Reached from 2 other entry points, including GridAtlas Cartridge Proof Workflow (gridatlas); GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
Read-only local preview server, serving the same LF text bytes as GitHub Pages.
Why it matters
Imported by 8 files, including UKPN Paired Browser, UKPN Secondary Browser and Vicinity Entry Browser. Checked by 2 tests, including Browser Test.
Application
gridatlas · tools/journey · JavaScript module
Uses
Build (import), node:fs, node:path, node:http, node:url
Used by
imported by UKPN Paired Browser (import), imported by UKPN Secondary Browser (import), imported by Browser Test (import), imported by Vicinity Entry Browser (import), imported by Vicinity Focus Browser (import), imported by Vicinity A4 Browser (import), imported by Layers Visible Browser (import), imported by Regional Interface Browser (import), and 2 more
Produces
createPreviewServer
Defines here
createPreviewServer
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/journey/serve.mjs:1-20 · blob 53b25846529fc739213fa38600fc19b13d85efbc · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/** Read-only local preview server, serving the same LF text bytes as GitHub Pages. */
import fs from 'node:fs';
import path from 'node:path';
import http from 'node:http';
import {fileURLToPath} from 'node:url';
import {ROOT, G} from './build.mjs';
const types={'.html':'text/html','.json':'application/json','.js':'text/javascript','.mjs':'text/javascript','.css':'text/css','.svg':'image/svg+xml','.geojson':'application/json','.png':'image/png','.wasm':'application/wasm','.pbf':'application/x-protobuf','.woff2':'font/woff2'};
export async function createPreviewServer(port=0) {
  const server=http.createServer((req,res)=>{
    let p;try{p=decodeURIComponent(new URL(req.url,'http://localhost').pathname);}catch{res.writeHead(400).end();return;}
    p=path.resolve(ROOT,'.'+p);if(!(p===ROOT||p.startsWith(ROOT+path.sep))){res.writeHead(403).end();return;}
    try{if(fs.statSync(p).isDirectory())p=path.join(p,'index.html');let bytes=fs.readFileSync(p);const ext=path.extname(p);if(['.html','.json','.js','.mjs','.css','.geojson'].includes(ext))bytes=Buffer.from(bytes.toString('utf8').replace(/\r\n/g,'\n'));res.writeHead(200,{'content-type':types[ext]||'application/octet-stream','cache-control':'no-store'}).end(bytes);}catch{res.writeHead(404).end();}
  });
  await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(port,'127.0.0.1',resolve);});return server;
}
if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)){
  const port=Number(process.argv[2]||8084);if(!Number.isInteger(port)||port<1||port>65535)throw new Error('Port must be1..65535');
  const server=await createPreviewServer(port);console.log(`GJ-03 PREVIEW ONLY http://127.0.0.1:${server.address().port}/atlas/v/${G}/`);
  process.once('SIGINT',()=>server.close(()=>process.exit(0)));
}

Bootstrap

A JavaScript file in the journey folder of GridAtlas. It is built from the mount step (`mount`) and the attach step (`attach`).

rendergridatlas / tools/journey/src/bootstrap.js · lines 1–20 of 20 · pattern attach (shared by 32 files)

What it does
It loads data. Defines mount, attach. Side effects: changes the web page (DOM); reads or writes files.
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.
Downstream impact
Used directly by 1 file: Controller Test (gridatlas). Reached from 1 other entry point, including GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
Bounded public-map attachment. No private card closures, new map or network fetch.
Why it matters
Checked by Controller Test.
Application
gridatlas · tools/journey/src · script
Uses
none found
Used by
referenced by Controller Test (new URL import.meta.url)
Produces
mount, attach
Defines here
mount, attach
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/journey/src/bootstrap.js:1-20 · blob c51816bdc7c5060f494b9103e3846bce6782c9aa · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
// Bounded public-map attachment. No private card closures, new map or network fetch.
const registry = window.__GRIDATLAS_MODULES__ = window.__GRIDATLAS_MODULES__ || {};
if (!registry.gridJourneyPreview) {
  let controller = null, timer = null, attempts = 0, stopped = false;
  function mount(map = window.__GRIDATLAS_V9_MAP__) {
    stopped = false;
    if (controller?.snapshot().alive) return controller;
    controller = null;
    controller = createJourneyController({map, document, window, planner: JourneyEngine.planJourney, fixture: JourneyFixture, css: JourneyCSS, generation: JourneyGeneration});
    return controller;
  }
  function attach() {
    if (stopped) return;
    if (window.__GRIDATLAS_V9_MAP__) { try { mount(); } catch (e) { console.warn('[Grid Journey preview]', e.message); } return; }
    if (++attempts < 120) timer = setTimeout(attach, 250);
    else console.warn('[Grid Journey preview] native map unavailable; no replacement map created');
  }
  registry.gridJourneyPreview = Object.freeze({schema: 'gridatlas.journey.preview.v1', generation: JourneyGeneration, mount, open(options) { return mount().open(options); }, setOrigin(origin) { return mount().setOrigin(origin); }, snapshot: () => controller?.snapshot() || {status: 'map-unavailable'}, destroy() { stopped = true; clearTimeout(timer); controller?.destroy(); controller = null; }});
  attach();
}