GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / AI agents and coordination / neural-link-between-agents / FIXES/NL-014/scripts

GlobalGrid2050 Render and 11 more files

A JavaScript module in the tools folder of Neural Link Between Agents that maps the Renewable Energy Planning Database (REPD) register.

638 lines of JavaScript and Python and Shell from neural-link-between-agents, in 12 files. Topic: AI agents and coordination. Section 1640 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. Indep Verify storage · neural-link-between-agents / FIXES/NL-014/scripts/indep_verify.py lines 1–48
  2. Rebuild Coords geodesy · neural-link-between-agents / FIXES/NL-014/scripts/rebuild_coords.py lines 1–14
  3. Rerun V6 ingest · neural-link-between-agents / FIXES/NL-014/scripts/rerun_v6.py lines 1–21
  4. Tech and Uncompared storage · neural-link-between-agents / FIXES/NL-014/scripts/tech_and_uncompared.py lines 1–101
  5. Interact render · neural-link-between-agents / FIXES/NL-015/scripts/interact.mjs lines 1–42
  6. Load render · neural-link-between-agents / FIXES/NL-015/scripts/load.mjs lines 1–40
  7. Recount ingest · neural-link-between-agents / FIXES/NL-015/scripts/recount.py lines 1–36
  8. Textdiff render · neural-link-between-agents / FIXES/NL-015/scripts/textdiff.mjs lines 1–24
  9. S1 Build automation · neural-link-between-agents / FIXES/NL-015/successor/S1-build.sh lines 1–14
  10. Drive storage · neural-link-between-agents / FIXES/NL-016/G1/drive.mjs lines 1–99
  11. GlobalGrid2050 Page Delta storage · neural-link-between-agents / FIXES/NL-016/globalgrid2050/tools/page_delta.mjs lines 1–73
  12. GlobalGrid2050 Render render · neural-link-between-agents / FIXES/NL-016/globalgrid2050/tools/render.mjs lines 1–126

Indep Verify

A Python module in the scripts folder of Neural Link Between Agents that reads the Renewable Energy Planning Database (REPD) register, using SHA-256.

storageneural-link-between-agents / FIXES/NL-014/scripts/indep_verify.py · lines 1–48 of 48 · Not reached from any entry point (candidate for review)

What it does
It loads the REPD register. Uses libraries csv, hashlib, io, json, sys. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'agents'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). Domain terms in the code: the REPD register.
Inputs & outputs
In: command-line arguments. Out: JSON file.
What it achieves
Independent structure check of a raw REPD CSV + XLSX (no automation/REPD code).
Why it matters
No other file in the estate was found to import it.
Application
neural-link-between-agents · FIXES/NL-014/scripts · Python module
Uses
csv, hashlib, io, json, sys, collections, datetime, openpyxl
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 FIXES/NL-014/scripts/indep_verify.py:1-48 · blob c4d6b0dc62812452253125ae68db82dca0b46301 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
"""Independent structure check of a raw REPD CSV + XLSX (no automation/repd code)."""
import csv, hashlib, io, json, sys, collections, datetime
import openpyxl
csvp, xlsxp, outp = sys.argv[1:4]
res = {}
raw = open(csvp, 'rb').read()
res['csv_bytes'] = len(raw); res['csv_sha256'] = hashlib.sha256(raw).hexdigest()
try: raw.decode('utf-8'); enc = 'utf-8'
except UnicodeDecodeError: enc = 'cp1252'
res['csv_encoding'] = enc
rows = list(csv.reader(io.StringIO(raw.decode(enc), newline='')))
hdr, body = rows[0], rows[1:]
res['csv_header'] = hdr; res['csv_columns'] = len(hdr); res['csv_records'] = len(body)
res['csv_field_counts'] = dict(collections.Counter(len(r) for r in body))
refs = [r[1].strip() for r in body]
res['csv_unique_refs'] = len(set(refs))
res['csv_dup_refs'] = sorted(k for k, v in collections.Counter(refs).items() if v > 1)
res['csv_blank_cells_total'] = sum(1 for r in body for c in r if c.strip() == '')
res['csv_NA_cells'] = {hdr[i]: n for i, n in collections.Counter(i for r in body for i, c in enumerate(r) if c.strip() == 'NA').items()}
# month-first / non dd/mm/yyyy date strings
datecols = [2] + list(range(37, 51))
odd = collections.defaultdict(list)
for r in body:
    for i in datecols:
        v = r[i].strip()
        if not v: continue
        try:
            d = datetime.datetime.strptime(v, '%d/%m/%Y')
            if len(v) != 10: odd[hdr[i]].append((r[1], v))
        except ValueError:
            odd[hdr[i]].append((r[1], v))
res['csv_nonconforming_dates'] = {k: v for k, v in odd.items()}
wb = openpyxl.load_workbook(xlsxp, read_only=True, data_only=True)
res['xlsx_sheets'] = wb.sheetnames
ws = wb['REPD']
xr = list(ws.iter_rows(values_only=True))
xh = [str(c) if c is not None else '' for c in xr[0]]
xb = [r for r in xr[1:] if any(c not in (None, '') for c in r)]
res['xlsx_header_equals_csv_header'] = xh == hdr
res['xlsx_records'] = len(xb)
xrefs = [str(int(r[1])) if isinstance(r[1], (int, float)) else str(r[1]).strip() for r in xb]
res['xlsx_unique_refs'] = len(set(xrefs))
res['ref_sets_equal'] = set(xrefs) == set(refs)
res['same_order'] = xrefs == refs
raw2 = open(xlsxp, 'rb').read()
res['xlsx_bytes'] = len(raw2); res['xlsx_sha256'] = hashlib.sha256(raw2).hexdigest()
json.dump(res, open(outp, 'w'), indent=1, default=str)
print(json.dumps({k: v for k, v in res.items() if k not in ('csv_header',)}, default=str, indent=1))

Rebuild Coords

A Python module in the scripts folder of Neural Link Between Agents.

geodesyneural-link-between-agents / FIXES/NL-014/scripts/rebuild_coords.py · lines 1–14 of 14 · Not reached from any entry point (candidate for review)

What it does
It loads data. Uses libraries importlib.util, json, sys, hashlib, pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'agents'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: command-line arguments.
What it achieves
Its name says it rebuilds coords.
Why it matters
No other file in the estate was found to import it.
Application
neural-link-between-agents · FIXES/NL-014/scripts · Python module
Uses
importlib.util, json, sys, hashlib, pathlib
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 FIXES/NL-014/scripts/rebuild_coords.py:1-14 · blob cc233788ad4a244040db90f13608c53fc7d19f47 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
import importlib.util, json, sys, hashlib
from pathlib import Path
mod_path, identity, xlsx, out, existing = sys.argv[1:6]
spec = importlib.util.spec_from_file_location('spine', mod_path); m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
ident = json.load(open(identity))['records']
p = m.build_coordinate_fixture(Path(xlsx), ident, Path(out))
e = json.load(open(existing))
print('rebuilt meta', {k: v for k, v in p.items() if k != 'records'})
print('existing meta', {k: v for k, v in e.items() if k != 'records'})
print('records equal:', p['records'] == e['records'])
diff = [(a, b) for a, b in zip(p['records'], e['records']) if a != b]
print('differing records', len(diff), diff[:5])
pe = dict(p); pe['source_workbook'] = e['source_workbook']; pe['source_workbook_sha256'] = e['source_workbook_sha256']
print('payload equal apart from workbook name/hash:', pe == e)

Rerun V6

A Python module in the scripts folder of Neural Link Between Agents.

ingestneural-link-between-agents / FIXES/NL-014/scripts/rerun_v6.py · lines 1–21 of 21 · Not reached from any entry point (candidate for review)

What it does
It loads data. Uses libraries os, runpy, sys, repd_sources_v6. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'agents'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: command-line arguments.
What it achieves
Re-run the historical V6 chain on local July bytes inside a scratch tree.
Why it matters
No other file in the estate was found to import it.
Application
neural-link-between-agents · FIXES/NL-014/scripts · Python module
Uses
os, runpy, sys, repd_sources_v6
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 FIXES/NL-014/scripts/rerun_v6.py:1-21 · blob 653a5f27c5c0328c18282edf9bec85d1cca0445a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
"""Re-run the historical V6 chain on local July bytes inside a scratch tree.
usage: rerun_v6.py TREE CSV XLSX VALIDATED_AT
Patches only: repd_sources_v6.fetch_bytes (local files by URL) and utc_now (frozen timestamp)."""
import os, runpy, sys
tree, csvp, xlsxp, ts = sys.argv[1:5]
os.environ.pop('REPD_RELEASE_DESCRIPTOR', None)
os.environ['REPD_VALIDATED_AT'] = ts
os.environ['REPD_SOURCE_CSV_FILE'] = os.path.abspath(csvp); os.environ['REPD_SOURCE_XLSX_FILE'] = os.path.abspath(xlsxp)
sys.path.insert(0, os.path.join(tree, 'scripts'))
import repd_sources_v6 as r
files = {r.CSV_URL: open(csvp, 'rb').read(), r.XLSX_URL: open(xlsxp, 'rb').read()}
r.fetch_bytes = lambda url, *a, **k: files[url]
r.utc_now = lambda: ts
os.chdir(tree)
for s in ['validate_repd_sources_v6.py', 'validate_v6_manifest_provenance.py', 'build_project_identity_v6.py', 'validate_project_identity_v6.py']:
    print('==', s, flush=True)
    sys.argv = [s]
    try:
        runpy.run_path(os.path.join(tree, 'scripts', s), run_name='__main__')
    except SystemExit as e:
        print('exit', e.code)

Tech and Uncompared

A Python module in the scripts folder of Neural Link Between Agents that reads tech tables, uncompared columns, wind and the Renewable Energy Planning Database (REPD) register.

storageneural-link-between-agents / FIXES/NL-014/scripts/tech_and_uncompared.py · lines 1–101 of 101 · Not reached from any entry point (candidate for review) · pattern detail (shared by 2 files)

What it does
It loads tech tables, uncompared columns, wind and the REPD register. Defines load, mw, agg, detail. Uses libraries csv, json, math, sys, collections. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'agents'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). Domain terms in the code: wind, the REPD register.
Inputs & outputs
In: command-line arguments. Out: JSON file tech_tables.json; JSON file uncompared_columns.json. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
What it achieves
It is built from the load step (`load`), the agg step (`agg`) and the detail step (`detail`). Blank capacity is unknown, never zero.
Why it matters
No other file in the estate was found to import it.
Application
neural-link-between-agents · FIXES/NL-014/scripts · Python module
Uses
csv, json, math, sys, collections, datetime
Used by
none found
Produces
load, mw, agg, detail
Defines here
load, mw, agg, detail
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 FIXES/NL-014/scripts/tech_and_uncompared.py:1-101 · blob 03e01ba14ce555ca2311d66e2357a8818d0503d8 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
"""Pieces 5 and 6. usage: tech_and_uncompared.py PREV_clean.csv NEW_clean.csv OLD_diff.json INDEP.json OUTDIR
Blank capacity is unknown, never zero."""
import csv, json, math, sys, collections, datetime
prevp, newp, olddiff, indep, out = sys.argv[1:6]
def load(p):
    rows = list(csv.DictReader(open(p, encoding='utf-8-sig', newline='')))
    return {r['Ref ID'].strip(): r for r in rows}
P, N = load(prevp), load(newp)
CAP, T, S = 'Installed Capacity (MWelec)', 'Technology Type', 'Development Status (short)'
def mw(r):
    try: return float(r[CAP])
    except (ValueError, TypeError): return None
def agg(recs):
    n = len(recs); k = [mw(r) for r in recs]
    return n, sum(x for x in k if x is not None), sum(1 for x in k if x is None)
techs = sorted(set(r[T] for r in P.values()) | set(r[T] for r in N.values()))
added = set(N) - set(P); removed = set(P) - set(N); kept = set(P) & set(N)
LIVE = ['Application Submitted', 'Awaiting Construction', 'Under Construction', 'Operational']
md = ['# Per-technology quarter-on-quarter tables: July 2026 (Q2) -> October 2026 (Q3)', '',
      f'Inputs: {prevp.split("/")[-1]} ({len(P)} refs), {newp.split("/")[-1]} ({len(N)} refs). MW sums known capacities only; blank capacity is unknown, never zero.', '',
      '## Records and capacity by technology', '',
      '| Technology | Jul n | Oct n | Added | Removed | Jul MW | Oct MW | Delta MW | Unknown cap. Jul | Unknown cap. Oct | Status changes |', '|---|---|---|---|---|---|---|---|---|---|---|']
res = {}
for t in techs:
    p = [r for r in P.values() if r[T] == t]; n = [r for r in N.values() if r[T] == t]
    pn, pm, pu = agg(p); nn, nm, nu = agg(n)
    a = sum(1 for x in added if N[x][T] == t); rm = sum(1 for x in removed if P[x][T] == t)
    sc = sum(1 for x in kept if N[x][T] == t and P[x][S] != N[x][S])
    res[t] = dict(jul_n=pn, oct_n=nn, added=a, removed=rm, jul_mw=round(pm, 3), oct_mw=round(nm, 3), jul_unknown=pu, oct_unknown=nu, status_changes=sc)
    md.append(f'| {t} | {pn:,} | {nn:,} | {a} | {rm} | {pm:,.1f} | {nm:,.1f} | {nm-pm:+,.1f} | {pu} | {nu} | {sc} |')
tot = lambda d, k: sum(v[k] for v in res.values())
md.append(f'| **All** | {tot(res,"jul_n"):,} | {tot(res,"oct_n"):,} | {tot(res,"added")} | {tot(res,"removed")} | {tot(res,"jul_mw"):,.1f} | {tot(res,"oct_mw"):,.1f} | {tot(res,"oct_mw")-tot(res,"jul_mw"):+,.1f} | {tot(res,"jul_unknown")} | {tot(res,"oct_unknown")} | {tot(res,"status_changes")} |')
md += ['', '## Pipeline stage by technology (count / known MW), July -> October', '',
       '| Technology | ' + ' | '.join(LIVE) + ' |', '|---|' + '---|' * len(LIVE)]
stage = {}
for t in ['Solar Photovoltaics', 'Battery', 'Wind Onshore', 'Wind Offshore', 'Hydrogen', 'Pumped Storage Hydroelectricity']:
    cells = []
    for s in LIVE:
        a = agg([r for r in P.values() if r[T] == t and r[S] == s]); b = agg([r for r in N.values() if r[T] == t and r[S] == s])
        stage[f'{t}|{s}'] = dict(jul=[a[0], round(a[1], 1)], oct=[b[0], round(b[1], 1)])
        cells.append(f'{a[0]:,} / {a[1]:,.0f} -> {b[0]:,} / {b[1]:,.0f}')
    md.append(f'| {t} | ' + ' | '.join(cells) + ' |')
md += ['', '## Status transitions on retained records, by technology (top transitions)', '', '| Technology | From | To | n | MW (Oct capacity) |', '|---|---|---|---|---|']
tr = collections.Counter(); trmw = collections.Counter()
for x in kept:
    if P[x][S] != N[x][S]:
        k = (N[x][T], P[x][S], N[x][S]); tr[k] += 1; trmw[k] += mw(N[x]) or 0
for k, v in tr.most_common(25):
    md.append(f'| {k[0]} | {k[1]} | {k[2]} | {v} | {trmw[k]:,.1f} |')
open(f'{out}/../w5/TECH_TABLES.md', 'w').write('\n'.join(md) + '\n')
json.dump({'by_technology': res, 'stage': stage, 'transitions': [[*k, v, round(trmw[k], 3)] for k, v in tr.most_common()]}, open(f'{out}/../w5/tech_tables.json', 'w'), indent=1)
# ---- piece 6
old = json.load(open(olddiff)); unc = old['conventions']['columns_only_in_new']
ind = json.load(open(indep))
md = ['# Changes in the columns the earlier July->October report never compared', '',
      f'The earlier report (docs/repd/2026q3/changes-jul-to-oct, previous = derived project_identity_v6.json) compared 19 columns; {len(unc)} official columns were not compared. Counts below are retained refs (14,648) whose value changed, from clean.py output July vs clean.py output October, classified by scripts/indep_diff.py.', '',
      '| Column | Real change | of which filled (blank->value) | blanked (value->blank) | Formatting only (whitespace/spacing/separator/numeric form) |', '|---|---|---|---|---|']
for c in unc:
    d = ind['columns'].get(c, {})
    m = sum(v for k, v in d.items() if k.startswith('material'))
    f = sum(v for k, v in d.items() if not k.startswith('material'))
    md.append(f'| {c} | {m} | {d.get("material_filled",0)} | {d.get("material_blanked",0)} | {f} |')
# coordinates
X, Y = 'X-coordinate', 'Y-coordinate'
moves = []
for x in kept:
    a, b = P[x], N[x]
    if (a[X].strip(), a[Y].strip()) != (b[X].strip(), b[Y].strip()):
        try: d = math.hypot(float(b[X]) - float(a[X]), float(b[Y]) - float(a[Y]))
        except ValueError: d = None
        moves.append((x, a[T], a[X], a[Y], b[X], b[Y], d))
bands = collections.Counter()
for m in moves:
    d = m[6]
    bands['unparseable/blank' if d is None else '<100 m' if d < 100 else '100 m-1 km' if d < 1000 else '1-10 km' if d < 10000 else '10-100 km' if d < 100000 else '>100 km'] += 1
md += ['', f'## Coordinates (British National Grid easting/northing)', '', f'{len(moves)} retained records changed X and/or Y. Distance moved:', '']
for k in ['<100 m', '100 m-1 km', '1-10 km', '10-100 km', '>100 km', 'unparseable/blank']:
    md.append(f'- {k}: {bands[k]}')
big = [m for m in moves if m[6] and m[6] >= 10000]
md += ['', 'Moves of 10 km or more (open REPD data; likely corrections of misplaced points):', '', '| Ref | Technology | Jul X,Y | Oct X,Y | km |', '|---|---|---|---|---|']
for m in sorted(big, key=lambda m: -m[6]):
    md.append(f'| {m[0]} | {m[1]} | {m[2]},{m[3]} | {m[4]},{m[5]} | {m[6]/1000:,.1f} |')
# dates & refs detail
def detail(col):
    rows = [(x, P[x][col], N[x][col]) for x in sorted(kept, key=int) if P[x][col].strip() != N[x][col].strip()]
    return rows
for col in ['Appeal Lodged', 'Appeal Withdrawn', 'Appeal Refused', 'Appeal Granted', 'Secretary of State - Intervened', 'Secretary of State - Refusal', 'Secretary of State - Granted', 'Judicial Review', 'Appeal Reference', 'Secretary of State Reference', 'Type of Secretary of State Intervention']:
    r = detail(col)
    md += ['', f'### {col}: {len(r)} changed', '']
    for x, a, b in r[:20]:
        md.append(f'- ref {x}: "{a}" -> "{b}"')
md += ['', '### Planning Application Reference (compared earlier too; listed for completeness)', '']
for x, a, b in detail('Planning Application Reference'):
    if ' '.join(a.split()) != ' '.join(b.split()): md.append(f'- ref {x}: "{a.strip()}" -> "{b.strip()}"')
md += ['', '### Address: real changes after removing line breaks and spacing', '']
ad = [(x, a, b) for x, a, b in detail('Address') if ''.join(a.split()).casefold() != ''.join(b.split()).casefold()]
md.append(f'{len(ad)} retained records have a substantive address change (all other address differences are line-break/spacing removal by DESNZ).')
for x, a, b in ad[:20]: md.append(f'- ref {x}: "{" ".join(a.split())}" -> "{" ".join(b.split())}"')
open(f'{out}/UNCOMPARED_COLUMNS.md', 'w').write('\n'.join(md) + '\n')
json.dump({'uncompared_columns': unc, 'coordinate_moves': moves, 'bands': bands}, open(f'{out}/uncompared_columns.json', 'w'), indent=1)
print('ok', len(moves), dict(bands))

Interact

A JavaScript module in the scripts folder of Neural Link Between Agents covering battery storage (BESS).

renderneural-link-between-agents / FIXES/NL-015/scripts/interact.mjs · lines 1–42 of 42 · Not reached from any entry point (candidate for review) · pattern ready (shared by 44 files)

What it does
It draws battery storage (BESS). Defines ready, meta, grab. Uses libraries fs. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'agents'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). Domain terms in the code: battery storage (BESS).
Inputs & outputs
In: command-line arguments.
What it achieves
Defines `ready`, `meta` and `grab`.
Why it matters
No other file in the estate was found to import it.
Application
neural-link-between-agents · FIXES/NL-015/scripts · JavaScript module
Uses
/opt/npm-tools/node_modules/playwright/index.mjs, fs
Used by
none found
Produces
ready, meta, grab
Defines here
ready, meta, grab
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 FIXES/NL-015/scripts/interact.mjs:1-42 · blob c60f02eb1c6d1a832409019f31f0c12306b05667 · GitHub at these lines
State
achieves: name · context: auto · stage: output · effects: dom, filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
import { chromium } from '/opt/npm-tools/node_modules/playwright/index.mjs';
import fs from 'fs';
const [,, release, outdir, port = '8731'] = process.argv;
const base = `http://127.0.0.1:${port}/uk_renewables_pipeline/${release}/`;
const browser = await chromium.launch({ executablePath: '/usr/bin/google-chrome', headless: true, args: ['--proxy-server=https=127.0.0.1:9', '--proxy-bypass-list=<-loopback>'] });
const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 }, acceptDownloads: true });
const page = await ctx.newPage();
const errs = []; page.on('pageerror', e => errs.push(e.message));
const ready = async () => page.waitForFunction(() => document.querySelector('#tbody')?.dataset.complete === 'true' && !/Loading/.test(document.querySelector('#resultsMeta').textContent), null, { timeout: 60000 });
const meta = () => page.evaluate(() => ({ r: document.querySelector('#resultsMeta').textContent, f: document.querySelector('#resultsMeta').dataset.filteredCount, rows: document.querySelectorAll('#tbody tr').length, pager: document.querySelector('#projectPager')?.textContent.trim(), url: location.search }));
const out = {};
await page.goto(base); await ready();
out.initial = await meta();
out.tech = {};
for (const t of ['solar', 'bess', 'wind_onshore', 'wind_offshore', 'interconnector', 'all']) { await page.click(`#tech [data-technology="${t}"]`); await page.waitForTimeout(300); out.tech[t] = await meta(); }
out.status = {};
for (const s of ['Operational', 'Under Construction', 'Awaiting Construction', 'Application Submitted', 'All']) { await page.click(`#status [data-official-status="${s}"]`); await page.waitForTimeout(300); out.status[s] = await meta(); }
out.search = {};
for (const q of ['18561', 'Salters Lane', 'Berwick Bank', 'GG2050-REPD-19459', 'Forsinain', 'zzznotfound']) { await page.fill('#search', q); await page.waitForTimeout(700); out.search[q] = await meta(); out.search[q].first = await page.evaluate(() => document.querySelector('#tbody tr .site')?.childNodes[0]?.textContent || null); }
await page.click('#clearFilters'); await page.waitForTimeout(300);
// pagination: go to page 2 and to last page via repeated next? use dataset: click next once, then jump by evaluating clicks
await page.click('#projectPager [data-page-step="1"]'); await page.waitForTimeout(200); out.page2 = await meta();
const pages = Number(await page.evaluate(() => document.querySelector('#projectPager').dataset.pages));
for (let i = 2; i < pages; i++) await page.evaluate(() => document.querySelector('#projectPager [data-page-step="1"]').click());
await page.waitForTimeout(300); out.lastPage = await meta();
await page.click('#clearFilters'); await page.waitForTimeout(300);
// URL hydration
await page.goto(base + '?status=No%20Application%20Made'); await ready(); out.urlNoAppMade = await meta();
await page.goto(base + '?technology=bess&status=Under%20Construction'); await ready(); out.urlBessUC = await meta();
// county
await page.goto(base); await ready();
await page.selectOption('#county', { index: 5 }); await page.waitForTimeout(300); out.county = { value: await page.$eval('#county', s => s.value), ...(await meta()) };
await page.click('#clearFilters'); await page.waitForTimeout(300);
// exports
async function grab(label, sel) { const [d] = await Promise.all([page.waitForEvent('download'), page.click(sel)]); const p = `${outdir}/${release}_${label}.csv`; await d.saveAs(p); return { file: p, name: d.suggestedFilename(), exportMeta: await page.$eval('#exportMeta', e => e.textContent) }; }
out.exportAll = await grab('export_all', '#exportInline');
await page.click('#status [data-official-status="Under Construction"]'); await page.waitForTimeout(300);
out.exportUC = await grab('export_under_construction', '#export');
out.pageErrors = errs;
fs.writeFileSync(`${outdir}/${release}_interact.json`, JSON.stringify(out, null, 1));
console.log(JSON.stringify(out, null, 1));
await browser.close();

Load

A JavaScript module in the scripts folder of Neural Link Between Agents.

renderneural-link-between-agents / FIXES/NL-015/scripts/load.mjs · lines 1–40 of 40 · Not reached from any entry point (candidate for review)

What it does
Defines t. Uses libraries fs. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'agents'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: command-line arguments.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name. Described from its file name only (a candidate, not yet checked against the code).
Why it matters
No other file in the estate was found to import it.
Application
neural-link-between-agents · FIXES/NL-015/scripts · JavaScript module
Uses
/opt/npm-tools/node_modules/playwright/index.mjs, fs
Used by
none found
Produces
t
Defines here
t
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 FIXES/NL-015/scripts/load.mjs:1-40 · blob 410fe2fa362338bced652d64ef9f0a0e5f4f4b01 · GitHub at these lines
State
achieves: name · context: auto · stage: output · effects: dom, filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
import { chromium } from '/opt/npm-tools/node_modules/playwright/index.mjs';
import fs from 'fs';
const [,, release, outdir] = process.argv;
const url = `http://127.0.0.1:8731/uk_renewables_pipeline/${release}/`;
const proxy = process.env.HTTPS_PROXY ? { server: process.env.HTTPS_PROXY, bypass: '<-loopback>' } : undefined;
const browser = await chromium.launch({ executablePath: '/usr/bin/google-chrome', headless: true, args: ['--ignore-certificate-errors', `--proxy-server=https=${process.env.HTTPS_PROXY.replace(/^https?:\/\//,'')}`, '--proxy-bypass-list=<-loopback>'] });
const result = {};
for (const [name, vp, mobile] of [['desktop', { width: 1440, height: 900 }, false], ['mobile', { width: 390, height: 844 }, true]]) {
  const ctx = await browser.newContext({ viewport: vp, isMobile: mobile, hasTouch: mobile, ignoreHTTPSErrors: true, acceptDownloads: true });
  const page = await ctx.newPage();
  const consoleMsgs = [], failed = [], bad = [], reqs = [];
  page.on('console', m => { if (['error', 'warning'].includes(m.type())) consoleMsgs.push(`${m.type()}: ${m.text()}`); });
  page.on('pageerror', e => consoleMsgs.push(`pageerror: ${e.message}`));
  page.on('requestfailed', r => failed.push(`${r.url()} :: ${r.failure()?.errorText}`));
  page.on('response', r => { reqs.push(`${r.status()} ${r.url()}`); if (r.status() >= 400) bad.push(`${r.status()} ${r.url()}`); });
  const t0 = Date.now();
  await page.goto(url, { waitUntil: 'load', timeout: 60000 });
  try { await page.waitForFunction(() => /\d/.test(document.querySelector('#resultsMeta')?.textContent || '') && !/Loading/i.test(document.querySelector('#resultsMeta').textContent), null, { timeout: 60000 }); } catch (e) { consoleMsgs.push('TIMEOUT waiting resultsMeta'); }
  await page.waitForTimeout(4000);
  const info = await page.evaluate(() => {
    const t = s => document.querySelector(s)?.textContent.trim().replace(/\s+/g, ' ');
    return { title: document.title, h1: t('h1'), status: t('.header .status'), meta: t('.meta strong'), metaSpan: t('.meta span'),
      releaseMeta: t('#releaseMeta'), newsMeta: t('#newsMeta'), resultsMeta: t('#resultsMeta'), v1: t('#v1'), v2: t('#v2'), v3: t('#v3'),
      rows: document.querySelectorAll('#tbody tr').length, stories: document.querySelectorAll('#stories > *').length,
      firstRow: t('#tbody tr'), mapNav: document.querySelector('#mapAtlasNav')?.href,
      statusButtons: [...document.querySelectorAll('#status button')].map(b => b.textContent.trim()),
      counties: document.querySelectorAll('#county option').length,
      scrollW: document.documentElement.scrollWidth, clientW: document.documentElement.clientWidth };
  });
  info.loadMs = Date.now() - t0;
  await page.screenshot({ path: `${outdir}/${release}_${name}_top.png` });
  await page.screenshot({ path: `${outdir}/${release}_${name}_full.png`, fullPage: false, clip: undefined });
  await page.evaluate(()=>document.querySelector('#tbody')?.scrollIntoView()); await page.waitForTimeout(500);
  await page.screenshot({ path: `${outdir}/${release}_${name}_table.png` });
  result[name] = { info, console: consoleMsgs, failed, bad, requestCount: reqs.length, requests: reqs };
  await ctx.close();
}
await browser.close();
fs.writeFileSync(`${outdir}/${release}_load.json`, JSON.stringify(result, null, 1));
for (const k of Object.keys(result)) { const r = result[k]; console.log(k, JSON.stringify(r.info), '\nconsole:', r.console.length, r.console.slice(0, 8), '\nfailed:', r.failed, '\nbad:', r.bad); }

Recount

A Python module in the scripts folder of Neural Link Between Agents that reads solar and wind. It is built from the load step (`load`) and the coord step (`coord`).

ingestneural-link-between-agents / FIXES/NL-015/scripts/recount.py · lines 1–36 of 36 · Not reached from any entry point (candidate for review)

What it does
It loads solar and wind. Defines load, coord. Uses libraries csv, collections, json, sys, hashlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'agents'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). Domain terms in the code: solar, wind.
Inputs & outputs
In: command-line arguments.
What it achieves
Independent recount of the pinned figures from the October CSV (`repd-2026q3.csv`) and the official CSV.
Why it matters
No other file in the estate was found to import it.
Application
neural-link-between-agents · FIXES/NL-015/scripts · Python module
Uses
csv, collections, json, sys, hashlib
Used by
none found
Produces
load, coord
Defines here
load, coord
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 FIXES/NL-015/scripts/recount.py:1-36 · blob 2962ab23129095a7d38fa2615ff6ad129183dcfb · GitHub at these lines
State
achieves: comment · context: auto · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
# Independent recount of the pinned figures from the October CSV (repd-2026q3.csv) and the official CSV.
import csv, collections, json, sys, hashlib
def load(p):
    return list(csv.DictReader(open(p, encoding='utf-8-sig', newline='')))
src = sys.argv[1]
R = load(src)
print('rows', len(R), 'unique refs', len({r['Ref ID'] for r in R}))
print('tech types', collections.Counter(r['Technology Type'] for r in R).most_common())
TECH = {'Solar Photovoltaics': 'solar', 'Battery': 'bess', 'Wind Onshore': 'wind_onshore', 'Wind Offshore': 'wind_offshore'}
seen = {}; 
for r in R: seen.setdefault(r['Ref ID'], r)
inscope = []; blank = collections.Counter(); sub1 = collections.Counter()
for ref, r in seen.items():
    t = TECH.get(r['Technology Type'].strip())
    if not t: continue
    c = r['Installed Capacity (MWelec)'].strip().replace(',', '')
    if c == '': blank[t] += 1; continue
    c = float(c)
    if c < 1.0: sub1[t] += 1; continue
    inscope.append((ref, t, c, r))
cnt = collections.Counter(t for _, t, _, _ in inscope)
cap = round(sum(c for _, _, c, _ in inscope), 2)
largest = max(c for _, _, c, _ in inscope)
def coord(r):
    try: x = float(r['X-coordinate']); y = float(r['Y-coordinate']); return x, y
    except: return None
nocoord = sum(1 for *_, r in inscope if coord(r) is None)
out = dict(project_count=len(inscope), capacity_mw=cap, displayed=round(cap), largest_mw=largest, by_tech=dict(cnt),
           blank_capacity_in_4_techs=dict(blank), blank_total=sum(blank.values()), below_1mw=dict(sub1),
           no_xy_in_scope=nocoord,
           statuses=collections.Counter(r['Development Status (short)'] for *_, r in inscope).most_common(),
           status_long=collections.Counter(r['Development Status'] for *_, r in inscope).most_common(),
           no_application_made_all=sum(1 for r in R if 'no application made' in (r['Development Status']+r['Development Status (short)']).lower()),
           no_application_made_by_tech=collections.Counter(r['Technology Type'] for r in R if 'no application made' in (r['Development Status']+r['Development Status (short)']).lower()),
           no_application_made_inscope=[(ref, t, c) for ref, t, c, r in inscope if 'no application made' in (r['Development Status']+r['Development Status (short)']).lower()])
print(json.dumps(out, indent=1, default=str))

Textdiff

A JavaScript module in the scripts folder of Neural Link Between Agents.

renderneural-link-between-agents / FIXES/NL-015/scripts/textdiff.mjs · lines 1–24 of 24 · Not reached from any entry point (candidate for review)

What it does
Uses libraries fs. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'agents'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: command-line arguments.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name. Described from its file name only (a candidate, not yet checked against the code).
Why it matters
No other file in the estate was found to import it.
Application
neural-link-between-agents · FIXES/NL-015/scripts · JavaScript module
Uses
/opt/npm-tools/node_modules/playwright/index.mjs, fs
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 FIXES/NL-015/scripts/textdiff.mjs:1-24 · blob 237f4e086d3a3b23d23867163d823907c61f9201 · GitHub at these lines
State
achieves: name · context: auto · stage: output · effects: dom, filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
import { chromium } from '/opt/npm-tools/node_modules/playwright/index.mjs';
import fs from 'fs';
const outdir = process.argv[2];
const browser = await chromium.launch({ executablePath: '/usr/bin/google-chrome', headless: true, args: ['--proxy-server=https=127.0.0.1:9', '--proxy-bypass-list=<-loopback>'] });
for (const rel of ['202609082224', '202611132345']) {
  const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
  await page.goto(`http://127.0.0.1:8731/uk_renewables_pipeline/${rel}/`);
  await page.waitForFunction(() => document.querySelector('#tbody')?.dataset.complete === 'true', null, { timeout: 60000 });
  await page.waitForTimeout(1500);
  const t = await page.evaluate(() => {
    const clone = document.body.cloneNode(true);
    clone.querySelector('#tbody')?.remove(); clone.querySelector('#stories')?.remove();
    clone.querySelectorAll('select#county option').forEach(o => o.remove());
    const chrome = clone.innerText;
    const rows = [...document.querySelectorAll('#tbody tr')].map(tr => [...tr.children].map((td,i)=> i===0 ? td.childNodes[0].textContent : td.innerText.replace(/\s+/g,' ')).join(' | '));
    const counties = [...document.querySelectorAll('#county option')].map(o => o.value);
    return { chrome, rows, counties };
  });
  fs.writeFileSync(`${outdir}/${rel}_chrome.txt`, t.chrome);
  fs.writeFileSync(`${outdir}/${rel}_page1_rows.txt`, t.rows.join('\n') + '\n');
  fs.writeFileSync(`${outdir}/${rel}_counties.txt`, t.counties.join('\n') + '\n');
  await page.close();
}
await browser.close();

S1 Build

A shell script in the successor folder of Neural Link Between Agents that uses SHA-256.

automationneural-link-between-agents / FIXES/NL-015/successor/S1-build.sh · lines 1–14 of 14 · Entry point

What it does
Side effects: starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'agents'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Downstream impact
It is itself an entry point (shell script); no other file was found loading it.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
neural-link-between-agents · FIXES/NL-015/successor · shell script
Uses
none found
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 FIXES/NL-015/successor/S1-build.sh:1-14 · blob d0642f97f32d62f074f15a697be502ea6b56bd63 · GitHub at these lines
State
achieves: name · context: auto · stage: unknown · effects: process · domain stage: agent_infra · users: ai_agent · canonical: unknown
#!/usr/bin/env bash
# S1-build.sh - recreate uk_renewables_pipeline/202611140058 (V9.13) in a globalgrid2050
# checkout whose 202611132345 folder has tree 0c7a4ed5 (main d5de5a03 or later, BEFORE S2).
# Equivalent to S1-successor-release.patch (the 47 MB full-folder patch).
set -euo pipefail
cd "$(git rev-parse --show-toplevel)"
P=uk_renewables_pipeline/202611132345; N=uk_renewables_pipeline/202611140058
test "$(git rev-parse HEAD:$P)" = 0c7a4ed5ea369e4a4e71a45cfa6fe9c186fae773
test ! -e "$N"
cp -a "$P" "$N"
rm -rf "$N/fixtures/2026q3" "$N/tests/run_v9_12.sh" "$N/tests/check_v9_12.mjs"
git apply -p1 "$(dirname "$0")/S1-delta.patch"
( cd "$N" && find . -type f | sed 's#^\./##' | sort | xargs sha256sum ) | diff - "$(dirname "$0")/S1-file-sha256.txt"
bash "$N/tests/run_v9_13.sh"

Drive

A JavaScript module in Neural Link Between Agents using data from the ... repository. It is built from the ctype step (`ctype`).

storageneural-link-between-agents / FIXES/NL-016/G1/drive.mjs · lines 1–99 of 99 · Not reached from any entry point (candidate for review)

What it does
It fetches data. Defines ctype. Uses libraries module, fs, path, child_process, playwright. Side effects: 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 agent_infra (repository name word 'agents'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: data source: ... data; DuckDB queries; command-line arguments. Out: JSON file results.json.
What it achieves
G1 headless-Chrome driver for a LOCAL COPY of GridAtlas (no live site reachable).
Why it matters
No other file in the estate was found to import it.
Application
neural-link-between-agents · FIXES/NL-016/G1 · JavaScript module
Uses
module, fs, path, child_process, playwright
Used by
none found
Produces
ctype
Defines here
ctype
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 FIXES/NL-016/G1/drive.mjs:1-99 · blob 418c0edff14d94070d7a5f660390a3c1002f020b · GitHub at these lines
State
achieves: comment · context: auto · stage: output · effects: filesystem, network, process, storage · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
// G1 headless-Chrome driver for a LOCAL COPY of GridAtlas (no live site reachable).
// Usage: node drive.mjs <scenarios.json> <outDir>
// The page is opened under its real origin (https://ventusltd.github.io/...) and every
// request is answered from local files:
//   ventusltd.github.io/<path>  -> http://127.0.0.1:8812/<path>  (site/ = gridatlas, data-gridatlas, dist copies)
//   globalgrid2050.com/<path>   -> http://127.0.0.1:8812/<path>
//   cdn.jsdelivr.net maplibre / duckdb -> local npm copies (same versions as pinned)
//   raw.githubusercontent.com   -> fetched for real with curl through the session proxy
//   basemap style / tiles / glyphs -> flat stub; everything else aborted and logged.
import { createRequire } from 'module';
import fs from 'fs';
import path from 'path';
import { execFileSync } from 'child_process';
const require = createRequire('/opt/npm-tools/node_modules/');
const { chromium } = require('playwright');

const [listFile, outDir] = process.argv.slice(2);
const scenarios = JSON.parse(fs.readFileSync(listFile, 'utf8'));
const LOCAL = 'http://127.0.0.1:8812';
const V3 = '<workspace>/teams/4/b/vendor/node_modules/maplibre-gl/dist';
const VD = '<workspace>/teams/12/vendor';
const TILE = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', 'base64');
const STYLE = JSON.stringify({ version: 8, name: 'stub-dark', sources: {}, glyphs: 'https://stub.invalid/fonts/{fontstack}/{range}.pbf', layers: [{ id: 'bg', type: 'background', paint: { 'background-color': '#101418' } }] });
const ctype = f => f.endsWith('.css') ? 'text/css' : f.endsWith('.wasm') ? 'application/wasm' : f.endsWith('.json') || f.endsWith('.geojson') ? 'application/json' : 'application/javascript';

fs.mkdirSync(outDir, { recursive: true });
const browser = await chromium.launch({ executablePath: '/usr/bin/google-chrome', headless: true,
  args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist'] });
const all = [];
for (const s of scenarios) {
  const [w, h] = s.viewport || [1400, 900];
  const ctx = await browser.newContext({ viewport: { width: w, height: h }, isMobile: !!s.mobile, hasTouch: !!s.mobile,
    deviceScaleFactor: s.mobile ? 2 : 1 });
  const page = await ctx.newPage();
  const rec = { name: s.name, url: s.url, viewport: [w, h], served: {}, missing: [], aborted: [], remote: [], errors: [], steps: [] };
  page.on('pageerror', e => rec.errors.push('pageerror: ' + String(e.message).slice(0, 240)));
  page.on('console', m => { if (m.type() === 'error' || m.type() === 'warning') rec.errors.push(m.type() + ': ' + m.text().slice(0, 240)); });
  await page.route('**/*', async route => {
    const u = route.request().url();
    let m;
    try {
      if ((m = u.match(/^https:\/\/stub\.invalid\/(harness\/[^?#]*)/))) { m[1] = '/' + m[1]; }
      if (m || (m = u.match(/^https:\/\/(?:ventusltd\.github\.io|globalgrid2050\.com)(\/[^?#]*)/))) {
        const local = LOCAL + m[1];
        const r = await fetch(local);
        const body = Buffer.from(await r.arrayBuffer());
        if (r.status >= 400) rec.missing.push(`${r.status} ${u.slice(0, 160)}`);
        else rec.served[m[1]] = body.length;
        return route.fulfill({ status: r.status, body, headers: { 'content-type': r.headers.get('content-type') || ctype(m[1]), 'access-control-allow-origin': '*' } });
      }
      if (/maplibre-gl@3\.6\.2\/dist\/maplibre-gl\.(js|css)/.test(u)) {
        const f = `${V3}/maplibre-gl.${u.endsWith('.css') ? 'css' : 'js'}`;
        return route.fulfill({ status: 200, body: fs.readFileSync(f), contentType: ctype(f) });
      }
      if (/duckdb-wasm@1\.29\.0\/\+esm/.test(u)) return route.fulfill({ status: 200, body: fs.readFileSync(`${VD}/duckdb-esm.js`), contentType: 'application/javascript', headers: { 'access-control-allow-origin': '*' } });
      if ((m = u.match(/duckdb-wasm@1\.29\.0\/(dist\/[^?#]+)/))) {
        const f = `${VD}/node_modules/@duckdb/duckdb-wasm/${m[1]}`;
        return route.fulfill({ status: 200, body: fs.readFileSync(f), contentType: ctype(f), headers: { 'access-control-allow-origin': '*' } });
      }
      if (/^https:\/\/raw\.githubusercontent\.com\//.test(u)) {
        const body = execFileSync('curl', ['-sS', '-m', '30', '-f', u], { maxBuffer: 1 << 28 });
        rec.remote.push(`${body.length} ${u.slice(0, 160)}`);
        return route.fulfill({ status: 200, body, contentType: ctype(u), headers: { 'access-control-allow-origin': '*' } });
      }
      if (/style\.json/.test(u)) return route.fulfill({ status: 200, contentType: 'application/json', body: STYLE });
      if (/\.pbf(\?|$)/.test(u) || /fonts\//.test(u)) return route.fulfill({ status: 200, body: Buffer.alloc(0), contentType: 'application/x-protobuf' });
      if (/arcgisonline|basemaps|\/tile\/|\{z\}|\/\d+\/\d+\/\d+(\.png|@2x)/.test(u)) return route.fulfill({ status: 200, body: TILE, contentType: 'image/png' });
    } catch (e) { rec.errors.push('route: ' + u.slice(0, 120) + ' ' + String(e).slice(0, 120)); return route.abort(); }
    if (u.startsWith('data:') || u.startsWith('blob:')) return route.continue();
    rec.aborted.push(u.slice(0, 160));
    return route.abort();
  });
  const t0 = Date.now();
  try { await page.goto(s.url, { waitUntil: 'load', timeout: 90000 }); } catch (e) { rec.errors.push('goto: ' + e.message.slice(0, 200)); }
  for (const [i, st] of (s.steps || [{ wait: 20000, shot: true }]).entries()) {
    if (st.wait) await page.waitForTimeout(st.wait);
    if (st.click) { try { await page.click(st.click, { timeout: 8000 }); } catch (e) { rec.steps.push({ i, clickErr: e.message.slice(0, 160) }); } }
    if (st.tapAt) { await page.mouse.click(st.tapAt[0], st.tapAt[1]); }
    if (st.eval) {
      let v; try { v = await page.evaluate(st.eval); } catch (e) { v = 'ERR ' + e.message.slice(0, 300); }
      rec.steps.push({ i, label: st.label || '', t: Date.now() - t0, value: v });
      if (st.tapResult && Array.isArray(v) && v.length === 2) { if (s.mobile) await page.touchscreen.tap(v[0], v[1]); else await page.mouse.click(v[0], v[1]); }
    }
    if (st.waitAfter) await page.waitForTimeout(st.waitAfter);
    if (st.shot) {
      const f = path.join(outDir, `${s.name}${typeof st.shot === 'string' ? '-' + st.shot : ''}.png`);
      await page.screenshot({ path: f, fullPage: !!st.full }).catch(e => rec.errors.push('shot ' + e.message));
      rec.steps.push({ i, shot: f });
    }
  }
  rec.ms = Date.now() - t0;
  rec.errors = [...new Set(rec.errors)].slice(0, 40);
  rec.aborted = [...new Set(rec.aborted)];
  all.push(rec);
  await ctx.close();
}
await browser.close();
fs.writeFileSync(path.join(outDir, 'results.json'), JSON.stringify(all, null, 1));
for (const r of all) console.log(JSON.stringify({ name: r.name, ms: r.ms, served: Object.keys(r.served).length, missing: r.missing.length, aborted: r.aborted.length, errors: r.errors.length }));

GlobalGrid2050 Page Delta

A JavaScript module in the tools folder of Neural Link Between Agents that works with cap blank (`capBlank`) and solar plan (`solarPlan`) (units: MW).

storageneural-link-between-agents / FIXES/NL-016/globalgrid2050/tools/page_delta.mjs · lines 1–73 of 73 · Not reached from any entry point (candidate for review)

What it does
It loads data. Defines 8 functions or classes, including read, ref, xy, capBlank, cap. Uses libraries module, fs, papaparse. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'agents'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: CSV file repd.csv; CSV file repd-2026q3.csv; CSV file repd-grid-batteries.csv; CSV file repd-grid-batteries-2026q3.csv; CSV file repd-solar-operational-over-4mw.csv; CSV file repd-solar-operational-over-4mw-2026q3.csv; CSV file repd-solar-operational.csv; CSV file repd-solar-operational-2026q3.csv.
What it achieves
It is built from the read step (`read`), the ref step (`ref`) and the cap blank helper (`capBlank`). Per-page gain/loss table, January files vs 2026q3 files, applying each page's own filter. Its code works with 0 MW.
Why it matters
No other file in the estate was found to import it.
Application
neural-link-between-agents · FIXES/NL-016/globalgrid2050/tools · JavaScript module
Uses
module, fs, papaparse
Used by
none found
Produces
read, ref, xy, capBlank, cap, all, solarPlan, get
Defines here
read, ref, xy, capBlank, cap, all, solarPlan, get
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 FIXES/NL-016/globalgrid2050/tools/page_delta.mjs:1-73 · blob cd101c555e0c36923a4bfbd38f63d87d005c97e0 · GitHub at these lines
State
achieves: comment · context: auto · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
// Per-page gain/loss table, January files vs 2026q3 files, applying each page's own filter.
// Decodes like a browser XHR (UTF-8, invalid bytes -> U+FFFD), parses with papaparse 5.4.1 (header, skipEmptyLines).
import { createRequire } from 'module';
import fs from 'fs';
const require = createRequire('<workspace>/teams/4/b/vendor/');
const Papa = require('papaparse');
const G = '<workspace>/gg-wt/';
const read = f => Papa.parse(new TextDecoder('utf-8').decode(fs.readFileSync(G + f)), { header: true, skipEmptyLines: true }).data;
const ref = r => (r['Ref ID'] || '').trim();
const xy = r => parseFloat(r['X-coordinate']) && parseFloat(r['Y-coordinate']);
const capBlank = r => (r['Installed Capacity (MWelec)'] || '').trim() === '';
const cap = r => parseFloat(r['Installed Capacity (MWelec)']) || 0;
const all = r => true;
const solarPlan = r => {
  const t = (r['Technology Type'] || '').toLowerCase(), s = (r['Development Status'] || '').toLowerCase();
  if (!t.includes('solar')) return false;
  if (['refused', 'abandoned', 'withdrawn', 'operational', 'decommissioned'].some(w => s.includes(w))) return false;
  const c = cap(r); return c >= 1 && c <= 50;
};
const pages = [
  ['repd-atlas.md (/atlas/)', 'repd.csv', 'repd-2026q3.csv', all],
  ['uk_grid-batteries.md', 'repd-grid-batteries.csv', 'repd-grid-batteries-2026q3.csv', all],
  ['uk_operating_large_solar_farms.md', 'repd-solar-operational-over-4mw.csv', 'repd-solar-operational-over-4mw-2026q3.csv', all],
  ['repd-uk-operational-solar.md', 'repd-solar-operational.csv', 'repd-solar-operational-2026q3.csv', all],
  ['uk_offshore_wind_atlas.md', 'repd.csv', 'repd-2026q3.csv', r => r['Technology Type'] === 'Wind Offshore'],
  ['uk_onshore_wind_atlas.md', 'repd.csv', 'repd-2026q3.csv', r => r['Technology Type'] === 'Wind Onshore'],
  ['uk_solar_in-planning-1-50mw.md', 'repd.csv', 'repd-2026q3.csv', solarPlan],
  ['repd_atlas_grid_model.md', 'repd.csv', 'repd-2026q3.csv', all],
];
const cache = {};
const get = f => (cache[f] ||= read(f));
const out = [];
for (const [name, jf, of, filt] of pages) {
  const o = { page: name };
  for (const [k, f] of [['jan', jf], ['oct', of]]) {
    const rows = get(f).filter(filt);
    const drawn = rows.filter(xy);
    o[k] = {
      file: f, rows: rows.length, drawn: drawn.length,
      noXY: rows.filter(r => !xy(r)).map(r => `${ref(r)} ${(r['Site Name'] || '').trim()} [${(r['Development Status (short)'] || r['Development Status'] || '').trim()}${capBlank(r) ? '' : ', ' + r['Installed Capacity (MWelec)'] + ' MW'}]`),
      blankCapDrawnAs0MW: drawn.filter(capBlank).length,
      fffdRowsDrawn: drawn.filter(r => JSON.stringify(r).includes('�')).length,
      mojibakeRowsDrawn: drawn.filter(r => /Ã|Â|â€/.test(JSON.stringify(r))).length,
      dupRefs: rows.length - new Set(rows.map(ref)).size,
      refs: new Set(drawn.map(ref)),
      salters: drawn.filter(r => ['18561', '18562'].includes(ref(r))).map(r => `${ref(r)} ${r['Site Name']} X=${r['X-coordinate']} Y=${r['Y-coordinate']} county=${r['County']}`),
    };
  }
  o.gainedDrawn = [...o.oct.refs].filter(x => !o.jan.refs.has(x)).length;
  o.lostDrawn = [...o.jan.refs].filter(x => !o.oct.refs.has(x)).length;
  o.lostDrawnExamples = [...o.jan.refs].filter(x => !o.oct.refs.has(x)).slice(0, 8);
  delete o.jan.refs; delete o.oct.refs;
  out.push(o);
}
// newly blank-coordinate offshore projects
const offJan = new Set(out[4].jan.noXY.map(s => s.split(' ')[0]));
out[4].newlyNoXY = out[4].oct.noXY.filter(s => !offJan.has(s.split(' ')[0]));
// atlas master json
for (const f of ['dist/repd_master.json', 'dist/repd_master_2026q3.json']) {
  const d = JSON.parse(fs.readFileSync(G + f, 'utf8'));
  const by = {}; let z = 0, nul = 0, sal = [];
  for (const ft of d.features) {
    const p = ft.properties; by[p.tech] = (by[p.tech] || 0) + 1;
    if (p.capacity === 0) z++; if (p.capacity === null || p.capacity === undefined || p.capacity === '') nul++;
    if (['18561', '18562'].includes(String(p.repd_ref))) sal.push(`${p.repd_ref} ${p.name} ${ft.geometry.coordinates}`);
  }
  out.push({ master: f, features: d.features.length, byTech: by, capacityZero: z, capacityNull: nul, salters: sal });
}
fs.writeFileSync(process.argv[2], JSON.stringify(out, null, 1));
for (const o of out) {
  if (o.page) console.log(`${o.page}: jan ${o.jan.rows}/${o.jan.drawn} oct ${o.oct.rows}/${o.oct.drawn} | noXY ${o.jan.noXY.length}->${o.oct.noXY.length} | 0MW ${o.jan.blankCapDrawnAs0MW}->${o.oct.blankCapDrawnAs0MW} | FFFD ${o.jan.fffdRowsDrawn}->${o.oct.fffdRowsDrawn} | mojibake ${o.jan.mojibakeRowsDrawn}->${o.oct.mojibakeRowsDrawn} | dup ${o.jan.dupRefs}->${o.oct.dupRefs} | +${o.gainedDrawn} -$  … [line shortened here: 450 characters; full line on GitHub]
  else console.log(JSON.stringify(o));
}

GlobalGrid2050 Render

A JavaScript module in the tools folder of Neural Link Between Agents that maps the Renewable Energy Planning Database (REPD) register.

renderneural-link-between-agents / FIXES/NL-016/globalgrid2050/tools/render.mjs · lines 1–126 of 126 · Not reached from any entry point (candidate for review)

What it does
It maps the REPD register. Uses libraries module, fs, path, playwright. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'agents'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). Domain terms in the code: the REPD register.
Inputs & outputs
In: command-line arguments. Out: JSON file results.json; interactive map.
What it achieves
Headless Chrome render check of legacy REPD pages on January vs October data.
Why it matters
No other file in the estate was found to import it.
Application
neural-link-between-agents · FIXES/NL-016/globalgrid2050/tools · JavaScript module
Uses
module, fs, path, playwright
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 FIXES/NL-016/globalgrid2050/tools/render.mjs:1-126 · blob d78f9b9e378be297495ba79d3b4bca62e8da6899 · GitHub at these lines
State
achieves: comment · context: auto · stage: output · effects: dom, filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
// Headless Chrome render check of legacy REPD pages on January vs October data.
// Usage: node render.mjs <baseUrl> <outDir> <pageList.json>
// All non-localhost requests are intercepted: CDN libraries are served from local npm copies
// (same versions as the pages pin), map tiles get a flat dark PNG, everything else is aborted.
import { createRequire } from 'module';
import fs from 'fs';
import path from 'path';
const require = createRequire('/opt/npm-tools/node_modules/');
const { chromium } = require('playwright');

const [base, outDir, listFile] = process.argv.slice(2);
const pages = JSON.parse(fs.readFileSync(listFile, 'utf8'));
const V = '<workspace>/teams/4/b/vendor/node_modules';
const LEAFLET_HOOK = `;(function(){var c=0,m=0;window.__leaf={get circle(){return c},get marker(){return m}};
var oc=L.circleMarker;L.circleMarker=function(){c++;return oc.apply(this,arguments)};
var om=L.marker;L.marker=function(){m++;return om.apply(this,arguments)};})();`;
const MAPLIBRE_HOOK = `;(function(){var M=maplibregl.Map;maplibregl.Map=class extends M{constructor(o){super(o);(window.__maps=window.__maps||[]).push(this);}};})();`;
const libs = [
  [/leaflet@1\.9\.4\/dist\/leaflet\.js/, `${V}/leaflet/dist/leaflet.js`, LEAFLET_HOOK],
  [/leaflet@1\.9\.4\/dist\/leaflet\.css/, `${V}/leaflet/dist/leaflet.css`],
  [/leaflet\.markercluster@1\.4\.1\/dist\/leaflet\.markercluster\.js/, `${V}/leaflet.markercluster/dist/leaflet.markercluster.js`],
  [/MarkerCluster\.Default\.css/, `${V}/leaflet.markercluster/dist/MarkerCluster.Default.css`],
  [/MarkerCluster\.css/, `${V}/leaflet.markercluster/dist/MarkerCluster.css`],
  [/maplibre-gl@3\.[0-9.]+\/dist\/maplibre-gl\.js/, `${V}/maplibre-gl/dist/maplibre-gl.js`, MAPLIBRE_HOOK],
  [/maplibre-gl@3\.[0-9.]+\/dist\/maplibre-gl\.css/, `${V}/maplibre-gl/dist/maplibre-gl.css`],
  [/PapaParse\/5\.4\.1\/papaparse\.min\.js/, `${V}/papaparse/papaparse.min.js`],
  [/proj4js\/2\.11\.0\/proj4\.js/, `${V}/proj4/dist/proj4.js`],
  [/jquery-3\.7\.0\.min\.js/, `${V}/jquery/dist/jquery.min.js`],
  [/jquery\.dataTables\.min\.js/, `${V}/datatables.net/js/jquery.dataTables.min.js`],
  [/jquery\.dataTables\.min\.css/, `${V}/datatables.net-dt/css/jquery.dataTables.min.css`],
  [/@turf\/turf@6\/turf\.min\.js/, `${V}/@turf/turf/turf.min.js`],
];
// 1x1 dark PNG
const TILE = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', 'base64');
const REPD_IDS = ['solar','solar_roof','wind','bess','biomass','tidal','hydrogen','hydro','flywheel','act','geothermal','caes',
  'solar_operational','wind_onshore_operational','wind_offshore_operational','bess_operational'];

fs.mkdirSync(outDir, { recursive: true });
const browser = await chromium.launch({ executablePath: '/usr/bin/google-chrome', headless: true,
  args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist'] });
const results = [];
for (const p of pages) {
  const ctx = await browser.newContext({ viewport: { width: 1400, height: 1000 } });
  const page = await ctx.newPage();
  const rec = { name: p.name, url: p.url, errors: [], failed: [], aborted: [], data: [] };
  page.on('pageerror', e => rec.errors.push(String(e.message).slice(0, 300)));
  page.on('console', m => { if (m.type() === 'error') rec.errors.push('console: ' + m.text().slice(0, 300)); });
  page.on('requestfailed', r => { const u = r.url(); if (u.startsWith(base)) rec.failed.push(u.replace(base, '')); });
  page.on('response', async r => {
    const u = r.url();
    if (!u.startsWith(base)) return;
    if (/repd[^/]*\.(csv|json)(\?|$)/.test(u)) rec.data.push({ url: u.replace(base, ''), status: r.status(), bytes: (await r.body().catch(() => Buffer.alloc(0))).length });
    else if (r.status() >= 400) rec.failed.push(`${r.status()} ${u.replace(base, '')}`);
  });
  await page.route('**/*', async route => {
    const u = route.request().url();
    if (u.startsWith(base)) return route.continue();
    for (const [re, file, hook] of libs) if (re.test(u)) {
      let body = fs.readFileSync(file, "utf8"); if (hook) body += "\n" + hook;
      return route.fulfill({ status: 200, body, contentType: file.endsWith('.css') ? 'text/css' : 'application/javascript' });
    }
    if (/style\.json/.test(u)) return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({
      version: 8, name: 'stub-dark', glyphs: 'https://stub.invalid/fonts/{fontstack}/{range}.pbf', sources: {},
      layers: [{ id: 'bg', type: 'background', paint: { 'background-color': '#1b1b1d' } }] }) });
    if (/\.pbf(\?|$)/.test(u)) return route.fulfill({ status: 200, body: Buffer.alloc(0), contentType: 'application/x-protobuf' });
    if (/\{?\d+\}?\/\d+\/\d+(@2x)?\.png|basemaps|tile|openstreetmap\.org\/\d/.test(u)) return route.fulfill({ status: 200, body: TILE, contentType: 'image/png' });
    rec.aborted.push(u.slice(0, 120)); return route.abort();
  });
  const t0 = Date.now();
  try { await page.goto(base + p.url, { waitUntil: 'load', timeout: 60000 }); } catch (e) { rec.errors.push('goto: ' + e.message.slice(0, 200)); }
  await page.waitForTimeout(p.wait || 8000);
  if (p.toggle) {
    // atlas pages: switch on every REPD layer checkbox
    rec.toggled = await page.evaluate(ids => {
      let n = 0;
      for (const id of ids) for (const el of document.querySelectorAll(`input[data-layer-id="${id}"], input#${id}, input#chk-${id}, input#toggle-${id}`)) {
        if (el.type === 'checkbox' && !el.checked) { el.click(); n++; }
      }
      return n;
    }, REPD_IDS);
    await page.waitForTimeout(p.wait2 || 15000);
  }
  if (p.evalAfter) {
    rec.evalAfter = await page.evaluate(p.evalAfter).catch(e => 'ERR ' + e.message);
    await page.waitForTimeout(p.wait2 || 10000);
  }
  rec.ms = Date.now() - t0;
  rec.counts = await page.evaluate(ids => {
    const o = {};
    if (window.__leaf) { o.leafletCircleMarkers = window.__leaf.circle; o.leafletMarkers = window.__leaf.marker; }
    if (window.jQuery && jQuery.fn.dataTable) {
      o.tables = [...document.querySelectorAll('table')].filter(t => jQuery.fn.dataTable.isDataTable(t)).map(t => jQuery(t).DataTable().rows().count());
    }
    if (window.__maps) {
      o.maps = window.__maps.map(m => {
        const src = {};
        try {
          for (const [id, s] of Object.entries(m.style.sourceCaches || {})) {
            const so = m.getSource(id);
            if (so && so.type === 'geojson' && so._data && typeof so._data === 'object' && so._data.features) src[id] = so._data.features.length;
            else if (so && so.type === 'geojson' && typeof so._data === 'string' && /repd/.test(so._data)) src[id] = 'url:' + so._data;
          }
        } catch (e) { src.err = String(e); }
        let rendered = null;
        try {
          const lyr = (m.getStyle().layers || []).filter(l => /repd/i.test(l.source || '') || ids.includes(l.id)).map(l => l.id);
          const vis = lyr.filter(id => m.getLayoutProperty(id, 'visibility') !== 'none');
          const per = {}; for (const id of vis) per[id] = m.queryRenderedFeatures({ layers: [id] }).length;
          rendered = { layers: lyr.length, visible: vis.length, features: vis.length ? m.queryRenderedFeatures({ layers: vis }).length : 0, perLayer: per };
        } catch (e) { rendered = String(e).slice(0, 120); }
        return { sources: src, rendered };
      });
    }
    o.bodyTextSample = document.body.innerText.replace(/\s+/g, ' ').slice(0, 300);
    o.replacementChars = (document.body.innerText.match(/�/g) || []).length;
    return o;
  }, REPD_IDS).catch(e => ({ err: String(e) }));
  const shot = path.join(outDir, p.name + '.png');
  await page.screenshot({ path: shot, fullPage: false }).catch(e => rec.errors.push('shot: ' + e.message));
  rec.screenshot = shot;
  results.push(rec);
  console.log(JSON.stringify({ name: rec.name, ms: rec.ms, data: rec.data, counts: { ...rec.counts, bodyTextSample: undefined }, errors: rec.errors.length, failed: rec.failed.length, aborted: rec.aborted.length }));
  await ctx.close();
}
await browser.close();
fs.writeFileSync(path.join(outDir, 'results.json'), JSON.stringify(results, null, 1));