In this section
- Test Slope test · lidar / tests/test_slope.py lines 1–119
- Measure GridAtlas render · neural-link-between-agents / FIXES/NL-010/tools/evidence/nl010/team-1/measure-gridatlas.cjs lines 1–123
- Build Kuiper Map storage · neural-link-between-agents / FIXES/NL-011/build_kuiper_map.py lines 1–342
- GridAtlas A3 Map Links storage · neural-link-between-agents / FIXES/NL-016/gridatlas/tools/a3_map_links.py lines 1–101
- GridAtlas Clockshift transform · neural-link-between-agents / FIXES/NL-016/gridatlas/tools/clockshift.mjs lines 1–5
Test Slope
A test in the tests folder of LiDAR that checks LiDAR Slope Tiles, using SHA-256. It is built from the plane step (`plane`).
testlidar / tests/test_slope.py · lines 1–119 of 119 · Entry point · pattern plane (shared by 2 files)
- What it does
- It tests its inputs. Defines 8 functions or classes, including plane, test_plane_has_no_photons_and_right_slope, test_class_edges, test_aspect_octants_point_downslope, test_crease_makes_photons_beside_the_crease_only. Uses libraries hashlib, inspect, json, os, pathlib. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage site_feasibility (repository name word 'lidar'): substation-to-site feasibility (terrain, LiDAR and connection evidence before design), a journey named in Ventus Ltd's brief.
- Downstream impact
- It is itself an entry point (test); no other file was found loading it.
- What it achieves
- Tests for `src/slope_tiles.py` on synthetic ground.
- Why it matters
- Guards the behaviour of LiDAR Slope Tiles.
- Application
- lidar · tests · test
- Uses
- LiDAR Slope Tiles (sys.path import), hashlib, inspect, json, os, pathlib, sys, tempfile, traceback
- Used by
- none found
- Produces
- plane, test_plane_has_no_photons_and_right_slope, test_class_edges, test_aspect_octants_point_downslope, test_crease_makes_photons_beside_the_crease_only, test_nan_marks_neighbours_nodata, test_tiles_roundtrip_and_index, test_decode_refuses_damage
- Defines here
- plane, test_plane_has_no_photons_and_right_slope, test_class_edges, test_aspect_octants_point_downslope, test_crease_makes_photons_beside_the_crease_only, test_nan_marks_neighbours_nodata, test_tiles_roundtrip_and_index, test_decode_refuses_damage
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- lidar@2ddf7257e4847e5f387e03aaecbc1cc425c4e387 tests/test_slope.py:1-119 · blob 68b44596325a5dca71c1699477461a68827019b4 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: site_feasibility · users: IPP_developer, landowner_planner · canonical: unknown
"""Tests for src/slope_tiles.py on synthetic ground.
A plane must annihilate (Horn and Zevenbergen-Thorne agree exactly, zero photons); a crease
(break of slope) must make photons on the crease and nowhere else; classes, aspect octants and
the .gst tiles must say what the maths says.
E:/swarm/gpu-bench/venv/Scripts/python.exe lidar/tests/test_slope.py
"""
import hashlib, inspect, json, os, pathlib, sys, tempfile, traceback
import numpy as np
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
import slope_tiles as st # noqa: E402
GPU = [False] + ([True] if st.cp is not None else [])
def plane(pe, pn, n=65):
"""South-up grid with dz/de = pe, dz/dn = pn (1 m spacing)."""
y, x = np.mgrid[0:n, 0:n].astype(np.float64)
return 100.0 + pe * x + pn * y
def test_plane_has_no_photons_and_right_slope():
for gpu in GPU:
rec, cls, asp, ph = st.run(plane(0.072, 0.096), use_gpu=gpu) # 12 %
assert rec["photons"] == 0 and rec["max_diff_pp"] < 1e-9
assert abs(rec["electron"]["mean_pct"] - 12.0) < 1e-9
assert rec["witness"]["photons"] == 0
inner = cls[1:-1, 1:-1]
assert (inner == 3).all() # 12 % falls in 10-15
assert (cls[0] == st.NODATA).all() and (cls[:, -1] == st.NODATA).all()
def test_class_edges():
for s_pct, k in [(0.0, 0), (1.99, 0), (2.001, 1), (4.9, 1), (5.001, 2), (9.99, 2), (15.001, 4), (24.9, 4), (25.001, 5), (80, 5)]:
_, cls, _, _ = st.run(plane(s_pct / 100, 0.0, 9), use_gpu=False, witness_on=False)
assert cls[4, 4] == k, (s_pct, cls[4, 4], k)
def test_aspect_octants_point_downslope():
# (dz/de, dz/dn) -> downslope octant. Rising to the east means the ground falls to the WEST (6).
cases = [((0, -0.1), 0), ((-0.1, -0.1), 1), ((-0.1, 0), 2), ((-0.1, 0.1), 3),
((0, 0.1), 4), ((0.1, 0.1), 5), ((0.1, 0), 6), ((0.1, -0.1), 7), ((0.001, 0), st.FLAT)]
for gpu in GPU:
for (pe, pn), o in cases:
_, _, asp, _ = st.run(plane(pe, pn, 9), use_gpu=gpu, witness_on=False)
assert asp[4, 4] == o, ((pe, pn), asp[4, 4], o)
assert asp[0, 0] == st.NODATA
def test_crease_makes_photons_beside_the_crease_only():
n = 65
y, x = np.mgrid[0:n, 0:n].astype(np.float64)
# flat to the south-west of the diagonal x + y = 64, a 20 % (per axis) bank rising beyond it.
# Horn smooths across the crease and ZT does not: they differ on the nodes either side of it.
g = 50.0 + 0.2 * np.maximum(x + y - 64, 0)
for gpu in GPU:
rec, _, _, ph = st.run(g, use_gpu=gpu)
r, c = np.nonzero(ph)
band = set(((r + 1) + (c + 1) - 64).tolist())
assert rec["photons"] > 0 and band == {-1, 1}, band
assert rec["breaks"]["share_on_breaks"] == 1.0 and rec["breaks"]["by_chance"] < 0.1
assert rec["witness"]["photons"] == 0 and rec["witness"]["photons_cpu"] == rec["photons"]
def test_nan_marks_neighbours_nodata():
g = plane(0.05, 0.0)
g[20, 20] = np.nan
_, cls, asp, _ = st.run(g, use_gpu=False)
assert cls[20, 21] == st.NODATA and cls[19, 19] == st.NODATA and asp[21, 21] == st.NODATA
assert cls[20, 23] != st.NODATA
def test_tiles_roundtrip_and_index(tmp):
n = 2 * st.TILE_M + 1
y, x = np.mgrid[0:n, 0:n].astype(np.float64)
g = 100 + 10 * np.sin(x / 40.0) * np.cos(y / 55.0)
rec, cls, asp, _ = st.run(g, 400000, 300000, use_gpu=False, witness_on=False)
idx = st.write_tiles(str(tmp), cls, asp, 400000, 300000, "synth")
assert len(idx["tiles"]) == 4 and idx["tile_m"] == 256
again = json.load(open(tmp / st.INDEX))
assert again["tiles"] == idx["tiles"]
for t in idx["tiles"]:
blob = open(tmp / t["file"], "rb").read()
assert hashlib.sha256(blob).hexdigest() == t["sha256"] and len(blob) == t["bytes"]
head, c, a = st.decode(blob)
r0, c0 = t["n0"] - 300000, t["e0"] - 400000
assert (c == cls[r0:r0 + st.N, c0:c0 + st.N]).all() and (a == asp[r0:r0 + st.N, c0:c0 + st.N]).all()
assert head["steep_count"] == t["steep"] == int(((c >= 3) & (c != 255)).sum())
assert abs(sum(t["share"]) - 1) < 1e-4
# shared edges agree between neighbours
a = st.decode(open(tmp / "tiles/0_0.gst", "rb").read())[1]
b = st.decode(open(tmp / "tiles/1_0.gst", "rb").read())[1]
assert (a[:, -1] == b[:, 0]).all()
def test_decode_refuses_damage():
blob = st.encode(np.zeros((st.N, st.N), np.uint8), np.zeros((st.N, st.N), np.uint8), 0, 0)
for bad in (b"XXXX" + blob[4:], blob[:-1], blob[:10]):
try:
st.decode(bad)
except ValueError:
continue
raise AssertionError("damaged tile accepted")
if __name__ == "__main__":
fails = 0
for name, fn in sorted((n, f) for n, f in globals().items() if n.startswith("test_") and callable(f)):
with tempfile.TemporaryDirectory() as d:
try:
fn(*([pathlib.Path(d)] if inspect.signature(fn).parameters else []))
print("ok ", name)
except Exception:
fails += 1
print("FAIL", name); traceback.print_exc()
print(f"{fails} failed")
sys.exit(1 if fails else 0)Measure GridAtlas
A JavaScript module in the evidence folder of Neural Link Between Agents.
renderneural-link-between-agents / FIXES/NL-010/tools/evidence/nl010/team-1/measure-gridatlas.cjs · lines 1–123 of 123 · Not reached from any entry point (candidate for review) · pattern measure (shared by 35 files)
- What it does
- It draws its content. Defines wire, measure, r, cs. Uses libraries playwright, fs. Side effects: changes the web page (DOM); 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: JSON file style.json.
- What it achieves
- Its name says it measures GridAtlas. Defines `wire` and `measure`.
- Why it matters
- No other file in the estate was found to import it.
- Application
- neural-link-between-agents · FIXES/NL-010/tools/evidence/nl010/team-1 · JavaScript module
- Uses
- playwright, fs
- Used by
- none found
- Produces
- wire, measure, r, cs
- Defines here
- wire, measure, r, cs
- 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-010/tools/evidence/nl010/team-1/measure-gridatlas.cjs:1-123 · blob 2b956faa6654969eddcd1d9436dfe3221d68529b · GitHub at these lines
- State
- achieves: name · context: auto · stage: output · effects: dom, filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer, ai_agent · canonical: unreached_review
const { chromium, devices } = require('playwright');
const fs = require('fs');
const OUT = '/tmp/nl010/team-1';
const URL = 'http://127.0.0.1:8201/atlas/';
const args = ['--use-gl=angle','--use-angle=swiftshader','--enable-unsafe-swiftshader','--ignore-gpu-blocklist'];
const VENDOR = '/home/user/estate/kuiper-belt/see-through/202610050513/vendor/';
const BLOCKED = [];
async function wire(page, tag) {
await page.route('**/*', async (route) => {
const u = route.request().url();
if (u.startsWith('http://127.0.0.1:8201/')) return route.continue();
if (u.includes('maplibre-gl@3.6.2/dist/maplibre-gl.js')) return route.fulfill({ status: 200, contentType: 'application/javascript', body: fs.readFileSync(VENDOR + 'maplibre-gl.js') });
if (u.includes('maplibre-gl@3.6.2/dist/maplibre-gl.css')) return route.fulfill({ status: 200, contentType: 'text/css', body: fs.readFileSync(VENDOR + 'maplibre-gl.css') });
if (u.includes('basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json')) return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ version: 8, name: 'stub-dark', sources: {}, layers: [{ id: 'bg', type: 'background', paint: { 'background-color': '#0b0e14' } }] }) });
BLOCKED.push(tag + ' ' + u.slice(0, 140));
return route.abort('blockedbyclient');
});
}
async function measure(page, tag) {
// wait for the menu bar to install (max 60 s)
let installed = false;
for (let i = 0; i < 60; i++) {
installed = await page.evaluate(() => !!document.getElementById('gridatlas-menu-bar'));
if (installed) break;
await page.waitForTimeout(1000);
}
await page.waitForTimeout(4000);
const data = await page.evaluate(() => {
const r = (el) => { if (!el) return null; const b = el.getBoundingClientRect(); return { x: +b.x.toFixed(1), y: +b.y.toFixed(1), w: +b.width.toFixed(1), h: +b.height.toFixed(1) }; };
const cs = (el, props) => { if (!el) return null; const s = getComputedStyle(el); const o = {}; props.forEach(p => o[p] = s.getPropertyValue(p)); return o; };
const bar = document.getElementById('gridatlas-menu-bar');
const out = { viewport: { w: innerWidth, h: innerHeight, dpr: devicePixelRatio }, title: document.title, href: location.href };
out.menuBarState = window.__GRIDATLAS_MODULES__ && window.__GRIDATLAS_MODULES__.menuBar ? JSON.parse(JSON.stringify(window.__GRIDATLAS_MODULES__.menuBar, (k, v) => typeof v === 'function' ? undefined : v)) : null;
out.bar = { rect: r(bar), style: cs(bar, ['position','top','left','right','height','z-index','background-color','border-bottom','font-family','font-size','line-height','backdrop-filter','display']) };
out.titles = bar ? Array.from(bar.querySelectorAll('.gm-title')).map(t => ({ text: t.textContent, rect: r(t), side: t.closest('.gm-side') ? t.closest('.gm-side').className : null, style: cs(t, ['font-family','font-size','letter-spacing','text-transform','color','padding','min-height','background-color']) })) : [];
const brand = bar ? bar.querySelector('.gm-brand-slot') : null;
out.brandSlot = brand ? { rect: r(brand), style: cs(brand, ['max-width','padding','display','justify-content']), html: brand.innerHTML.slice(0, 3000) } : null;
const hh = document.querySelector('.hud-header');
out.hudHeader = hh ? { rect: r(hh), parent: hh.parentElement && hh.parentElement.className, children: Array.from(hh.children).map(c => ({ tag: c.tagName, cls: c.className, text: c.textContent.replace(/\s+/g,' ').trim(), rect: r(c), display: getComputedStyle(c).display })), style: cs(hh, ['display','gap','font-family']) } : null;
const vm = document.querySelector('.ventus-main');
const vs = document.querySelector('.ventus-sub');
out.ventusMain = vm ? { tag: vm.tagName, text: vm.textContent.trim(), rect: r(vm), style: cs(vm, ['font-family','font-size','font-weight','letter-spacing','color','text-shadow','line-height','margin']), link: (vm.closest('a') || {}).href || null, parentTag: vm.parentElement.tagName, parentCls: vm.parentElement.className } : null;
out.ventusSub = vs ? { tag: vs.tagName, text: vs.textContent.trim(), rect: r(vs), style: cs(vs, ['font-family','font-size','font-weight','letter-spacing','color','text-transform']) } : null;
out.images = Array.from(document.querySelectorAll('img, svg, [style*="background-image"]')).filter(e => /ventus|logo|brand/i.test((e.outerHTML||'').slice(0,400)) || (e.closest && e.closest('#gridatlas-menu-bar'))).slice(0,20).map(e => ({ tag: e.tagName, src: e.currentSrc || e.src || null, natural: e.naturalWidth ? { w: e.naturalWidth, h: e.naturalHeight } : null, rect: r(e), cls: e.className & … [line shortened here: 517 characters; full line on GitHub]
out.anchorsInBar = bar ? Array.from(bar.querySelectorAll('a')).slice(0, 30).map(a => ({ text: a.textContent.replace(/\s+/g,' ').trim().slice(0,60), href: a.href, target: a.target, hidden: a.offsetParent === null })) : [];
const sel = {
mapContainer: '.map-container', map: '#map, .maplibregl-map', mapControls: '.map-controls', search: '.search-bar-wrapper', attrib: '.custom-map-attrib', scada: '#scada-ui-container', scadaBrand: '.scada-brand', statusLegend: '.status-legend', fsLetterhead: '#fs-letterhead', btnExport: '#btn-export', btnStatus: '#btn-status', btnFullscreen: '#btn-fullscreen', btnRadius: '#btn-radius', btnZone … [line shortened here: 694 characters; full line on GitHub]
};
out.landmarks = {};
for (const k in sel) { const el = document.querySelector(sel[k]); out.landmarks[k] = el ? { rect: r(el), visible: !!(el.offsetParent || el.getClientRects().length), inBar: !!el.closest('#gridatlas-menu-bar'), parentCls: el.parentElement && (el.parentElement.className || el.parentElement.id), display: getComputedStyle(el).display, position: getComputedStyle(el).position, zIndex: getComputedStyl … [line shortened here: 424 characters; full line on GitHub]
// visible elements that sit over the map outside the bar: anything absolutely/fixed positioned with text, top-level
out.overlays = Array.from(document.body.querySelectorAll('*')).filter(e => { const s = getComputedStyle(e); if (!(s.position === 'absolute' || s.position === 'fixed')) return false; if (e.closest('#gridatlas-menu-bar')) return false; if (e.closest('.maplibregl-canvas-container')) return false; const b = e.getBoundingClientRect(); return b.width > 0 && b.height > 0 && s.visibility !== 'hidden' … [line shortened here: 652 characters; full line on GitHub]
out.brandChain = (function(){ const vm = document.querySelector('#gridatlas-menu-bar .ventus-main'); const chain = []; let e = vm; while (e && e.id !== 'gridatlas-menu-bar') { chain.push(e.tagName + (e.id ? '#' + e.id : '') + (e.className ? '.' + String(e.className).split(' ').join('.') : '')); e = e.parentElement; } return chain; })();
out.rootVars = { clear: getComputedStyle(document.documentElement).getPropertyValue('--gridatlas-menu-bar-clear') };
out.bodyFont = cs(document.body, ['font-family','font-size','background-color','color']);
return out;
});
fs.writeFileSync(`${OUT}/measure-${tag}.json`, JSON.stringify(data, null, 1));
await page.screenshot({ path: `${OUT}/shell-${tag}.png`, timeout: 180000 });
// open each menu and measure its panel
const names = ['File','Edit','View','Scope','Grid','About'];
const panels = {};
for (const n of names) {
try {
const t = page.locator(`#gridatlas-menu-bar .gm-title:has-text("${n}")`).first();
await t.click({ timeout: 5000 });
await page.waitForTimeout(600);
panels[n] = await page.evaluate((n) => {
const bar = document.getElementById('gridatlas-menu-bar');
const p = Array.from(bar.querySelectorAll('.gm-panel')).find(p => !p.hidden);
if (!p) return null;
const b = p.getBoundingClientRect();
const items = Array.from(p.querySelectorAll('button,[role="button"],a,.gm-layer-group,label')).filter(e => e.getClientRects().length).slice(0, 80).map(e => ({ tag: e.tagName, text: e.textContent.replace(/\s+/g,' ').trim().slice(0, 70), href: e.href || null, h: +e.getBoundingClientRect().height.toFixed(0) }));
return { rect: { x: +b.x.toFixed(1), y: +b.y.toFixed(1), w: +b.width.toFixed(1), h: +b.height.toFixed(1) }, position: getComputedStyle(p).position, count: items.length, items };
}, n);
await page.screenshot({ path: `${OUT}/menu-${n.toLowerCase()}-${tag}.png`, timeout: 180000 });
await page.keyboard.press('Escape');
await page.waitForTimeout(300);
} catch (e) { panels[n] = { error: String(e).slice(0, 200) }; }
}
fs.writeFileSync(`${OUT}/panels-${tag}.json`, JSON.stringify(panels, null, 1));
console.log(tag, 'installed', installed, 'bar', JSON.stringify(data.bar.rect), 'titles', data.titles.map(t => t.text + '@' + t.rect.x + ',' + t.rect.y + ' ' + t.rect.w + 'x' + t.rect.h).join(' | '));
}
(async () => {
const browser = await chromium.launch({ args });
const consoleLog = [];
// desktop
{
const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 } });
const page = await ctx.newPage(); await wire(page, 'desk');
page.on('console', m => consoleLog.push('[desk] ' + m.type() + ' ' + m.text().slice(0, 200)));
page.on('requestfailed', rq => consoleLog.push('[desk] FAIL ' + rq.url().slice(0, 160)));
await page.goto(URL, { waitUntil: 'load', timeout: 120000 });
await page.waitForTimeout(8000);
await measure(page, 'desktop-1280x800');
await ctx.close();
}
{
const ctx = await browser.newContext({ ...devices['Pixel 7'] });
const page = await ctx.newPage(); await wire(page, 'px7');
page.on('console', m => consoleLog.push('[px7] ' + m.type() + ' ' + m.text().slice(0, 200)));
page.on('requestfailed', rq => consoleLog.push('[px7] FAIL ' + rq.url().slice(0, 160)));
await page.goto(URL, { waitUntil: 'load', timeout: 120000 });
await page.waitForTimeout(8000);
await measure(page, 'pixel7');
await ctx.close();
}
{
const ctx = await browser.newContext({ ...devices['Pixel 7'], viewport: { width: 360, height: 740 } });
const page = await ctx.newPage(); await wire(page, '360');
await page.goto(URL, { waitUntil: 'load', timeout: 120000 });
await page.waitForTimeout(8000);
await measure(page, '360x740');
await ctx.close();
}
fs.writeFileSync(`${OUT}/console.log`, consoleLog.join('\n'));
fs.writeFileSync(`${OUT}/blocked-requests.log`, Array.from(new Set(BLOCKED)).join('\n'));
await browser.close();
})().catch(e => { console.error(e); process.exit(1); });Build Kuiper Map
A Python command-line tool in Neural Link Between Agents that selects lines (`select_lines`), loads comments (`load_comments`) and parses comment (`parse_comment`) (units: kV).
storageneural-link-between-agents / FIXES/NL-011/build_kuiper_map.py · lines 1–342 of 342 · Entry point · pattern norm_label (shared by 2 files)
- What it does
- It loads data. Defines 16 functions or classes, including sh, utc, overnight_type, overnight_who, decisions_row. Uses libraries argparse, glob, json, os, re. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage agent_infra (path word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- 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
- It is built from the utc step (`utc`), the overnight type helper (`overnight_type`) and the overnight who helper (`overnight_who`). Build `FIXES/NL-011/KUIPER-MAP.md`: the neural link keyed the way the Kuiper keys lines. It accepts `--comments-dir` and `--out`.
- 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-011 · Python CLI
- Uses
- argparse, glob, json, os, re, subprocess, sys, datetime
- Used by
- none found
- Produces
- sh, utc, overnight_type, overnight_who, decisions_row, blame, line_at, select_lines, file_rows, load_comments, parse_comment, comment_rows
- Defines here
- sh, utc, overnight_type, overnight_who, decisions_row, blame, line_at, select_lines, file_rows, load_comments, parse_comment, comment_rows, model_of, norm_label, esc, main
- 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-011/build_kuiper_map.py:1-342 · blob a30862f927df99a2be83bdcdeca5fc4dfe93e0ea · GitHub at these lines
- State
- achieves: comment · context: auto · stage: output · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
#!/usr/bin/env python3
"""Build FIXES/NL-011/KUIPER-MAP.md: the neural link keyed the way the Kuiper keys lines.
One row per key. A file key is `nl@<commit> <path>:<line>`: the commit is the one that wrote the line (git blame),
the line number is the line's number in that commit's version of the file, and the text is re-read from that commit
with `git show` and compared to the working tree before the row is written (a row whose text differs is marked).
A comment key is `#<issue>/c<id>` (GitHub issue comment id); its time is GitHub's created_at.
Usage (from the repository root):
python3 FIXES/NL-011/build_kuiper_map.py --comments-dir <dir with c9.json c10-*.json c11.json> [--out FIXES/NL-011/KUIPER-MAP.md]
Without --comments-dir the comments are fetched with `gh api` (REST, paged by &page=N).
Written by FABLE-FIN-3, 2 Nov 2026. Types: RULE, RULING, DECISION, HANDOFF, REVISION, REVIEW, FINDING, and the
envelope's own REQUEST, ACK, BLOCKER where a comment carries them (DECISION-PROPOSAL is written DECISION).
"""
import argparse, glob, json, os, re, subprocess, sys, datetime, collections
REPO = 'Ventusltd/neural-link-between-agents'
ISSUES = (9, 10, 11)
def sh(*cmd, text=True):
return subprocess.run(cmd, check=True, capture_output=True, text=text).stdout
def utc(ts):
return datetime.datetime.fromtimestamp(int(ts), datetime.timezone.utc).strftime('%Y-%m-%d %H:%M:%SZ')
# ---------------------------------------------------------------------------------------------------------------
# 1. File rows: which lines of which files are keys, and how they are typed.
# (path, selector, type, who, note). selector: list of line numbers, or a regex matched against the line text,
# or ('range', a, b). type may be a callable(line_text) -> type.
# ---------------------------------------------------------------------------------------------------------------
def overnight_type(t):
s = t.lower()
if 'correction' in s: return 'REVISION'
if 'rule from now' in s or 'ruling' in s or 'rulings' in s: return 'RULING'
if re.search(r'shipped|published|merged|done\.|merge|moved to', s): return 'HANDOFF'
return 'FINDING'
def overnight_who(t):
if 'Watcher A' in t: return 'WATCHER-A (Fable)'
if t.startswith('- 2026-11-01 23:3') or t.startswith('- 2026-11-01 23:5') or t.startswith('- 2026-11-02 00:05 UTC · (Watcher A') or t.startswith('- 2026-11-02 00:07 UTC · Watcher A'):
return 'WATCHER-A (Fable)'
return 'HARNESS'
def decisions_row(t):
# | D001 | time | who | authority | what | key | link | status |
cells = [c.strip() for c in t.strip().strip('|').split('|')]
if len(cells) < 8: return None
what = cells[4]
w = what.lower()
typ = 'DECISION'
if w.startswith('ruling') or 'ruling:' in w[:40]: typ = 'RULING'
elif w.startswith('refuses') or w.startswith('"verdict: fail') or w.startswith('fail:'): typ = 'REVIEW'
elif w.startswith('hands off') or w.startswith('handoff'): typ = 'HANDOFF'
elif w.startswith('revision'): typ = 'REVISION'
elif w.startswith('admits'): typ = 'REVIEW'
elif w.startswith('discloses') or w.startswith('finding'): typ = 'FINDING'
status = cells[7]
sup = ''
m = re.search(r'(superseded by|resolved by|overrides|supersedes|replaces) (D\d+[a-z]?(?:[,/ ]+D\d+[a-z]?)*)', status + ' ' + what, re.I)
if m: sup = m.group(0)
return dict(id=cells[0], when=cells[1], who=cells[2], typ=typ, summary=what[:160], superseded=sup)
FILE_SPECS = [
('LINK-RULE.md', re.compile(r'^\d\. '), 'RULE', 'OWNER (relayed by HARNESS)', 'the link is the medium of exchange'),
('LINK-RULE.md', [1], 'RULE', 'OWNER (relayed by HARNESS)', 'title and date of the rule'),
('PROTOCOL.md', [5, 7, 15, 16, 20, 25, 30, 31, 33, 37, 41, 45, 47], 'RULE', 'Agent F (protocol v1 author)', 'protocol v1'),
('AGENTS.md', re.compile(r'^(\d\. |- )'), 'RULE', 'Agent F (protocol v1 author)', 'mailbox rules'),
('SESSIONS/202611012145-kuiper-edition-harness-notes.md', ('range', 39, 66, re.compile(r'^- ')), 'RULE', 'HARNESS', 'rules that bind every edition'),
('FIXES/NL-010/BRIEF.md', [5, 72], 'DECISION', 'OWNER (quoted by HARNESS)', "owner's words: the roadmap brief and Addendum 1"),
('FIXES/NL-010/OVERNIGHT.md', [3], 'DECISION', 'OWNER (quoted by HARNESS)', "owner's ACCEPT and overnight instruction"),
('FIXES/NL-010/OVERNIGHT.md', ('range', 13, 22, re.compile(r'^- R')), 'DECISION', 'HARNESS', 'the small steps R0-R4'),
('FIXES/NL-010/OVERNIGHT.md', ('range', 36, 400, re.compile(r'^- ')), overnight_type, overnight_who, 'overnight log entry'),
('FIXES/NL-010/ROADMAP.md', ('range', 27, 39, re.compile(r'^\d\. ')), 'RULE', 'FABLE-T5B (consolidator)', 'the law the roadmap is written under'),
('FIXES/NL-010/ROADMAP.md', re.compile(r'^### Step \d+\.'), 'DECISION', 'FABLE-T5B (consolidator)', 'a roadmap step'),
('FIXES/NL-010/ROADMAP.md', re.compile(r'^- \*\*Q\d '), 'DECISION', 'FABLE-T5B (consolidator) to OWNER', 'open question for the owner (OPEN)'),
('FIXES/NL-010/ROADMAP.md', re.compile(r'^## Phase 2'), 'DECISION', 'FABLE-T5B (consolidator)', 'Phase 2 gated on owner acceptance of steps 1-10'),
('FIXES/NL-010/OPUS-BRIEF.md', re.compile(r'ACCEPT|-F body=@file|may touch|REQUEST comment'), 'RULE', 'HARNESS', 'Opus team rule'),
('FIXES/NL-011/DECISIONS.md', re.compile(r'^\| D\d'), None, None, 'NL-011 decision log row (LINK-09)'),
('FIXES/NL-011/PROTOCOL-v2-proposal.md', re.compile(r'^\| \d+ \| \*\*'), 'DECISION', 'NL-011 STUDY-06 (proposal to OWNER, NOT ADOPTED)', 'protocol v2 hunk (OPEN)'),
('FIXES/NL-011/LEDGER.md', re.compile(r'^\| (Q\d|OW-)'), 'DECISION', 'OPUS LINK-08 (ledger) to OWNER', 'owner ask in the ledger'),
('FIXES/NL-011/SYNTHESIS.md', ('range', 11, 15, re.compile(r'^\d\. ')), 'FINDING', 'NL-011 STUDY-06', 'the synthesis answer, five sentences'),
]
def blame(path):
"""Return {final_line: (sha, orig_line, author, committer_time)}."""
out = sh('git', 'blame', '--line-porcelain', '--', path)
res = {}
sha = orig = final = None; author = ''; ctime = 0
for ln in out.splitlines():
m = re.match(r'^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$', ln)
if m:
sha, orig, final = m.group(1), int(m.group(2)), int(m.group(3)); continue
if ln.startswith('author '): author = ln[7:]
elif ln.startswith('committer-time '): ctime = int(ln[15:])
elif ln.startswith('\t'):
res[final] = (sha, orig, author, ctime)
return res
_show_cache = {}
def line_at(sha, path, n):
key = (sha, path)
if key not in _show_cache:
_show_cache[key] = sh('git', 'show', f'{sha}:{path}').splitlines()
lines = _show_cache[key]
return lines[n - 1] if 0 < n <= len(lines) else None
def select_lines(lines, selector):
if isinstance(selector, list): return [n for n in selector if n <= len(lines)]
if isinstance(selector, tuple):
_, a, b, rx = selector
return [n for n in range(a, min(b, len(lines)) + 1) if rx.search(lines[n - 1])]
return [n for n, t in enumerate(lines, 1) if selector.search(t)]
def file_rows():
rows = []
for path, selector, typ, who, note in FILE_SPECS:
if not os.path.exists(path): continue
lines = open(path, encoding='utf-8').read().split('\n')
bl = blame(path)
for n in select_lines(lines, selector):
text = lines[n - 1]
sha, orig, author, ctime = bl[n]
at_commit = line_at(sha, path, orig)
verified = (at_commit is not None and at_commit.rstrip() == text.rstrip())
row_typ = typ(text) if callable(typ) else typ
row_who = who(text) if callable(who) else who
summary = re.sub(r'\s+', ' ', text.strip())[:170]
sup = ''
if path.endswith('DECISIONS.md'):
d = decisions_row(text)
if d is None: continue
row_typ, row_who, summary, sup = d['typ'], d['who'], f"{d['id']} ({d['when']}): {d['summary']}", d['superseded']
if 'CORRECTION of times' in text: sup = 'corrects the three log stamps above it (01:05Z, 01:12Z, 01:25Z)'
if 'CORRECTION SHIPPED' in text: sup = 'supersedes the Edition 5 release a432b43 (OVERNIGHT.md R2 entry)'
rows.append(dict(key=f'nl@{sha[:7]} {path}:{orig}', when=utc(ctime), who=row_who, typ=row_typ, note=note,
summary=summary, superseded=sup, verified=verified, cur_line=n, path=path, sha=sha[:7]))
return rows
# ---------------------------------------------------------------------------------------------------------------
# 2. Comment rows.
# ---------------------------------------------------------------------------------------------------------------
# Curated supersession: new comment id -> (old comment id, why). Everything else is derived from TYPE/IN-REPLY-TO.
SUPERSEDES = {
6567437030: (6566796733, 'delegation renewed and widened to See Through folders'),
6567953002: (6567194090, 'Edition 5 manifest corrected: be99c8a1 restored in place of 4e6b4031'),
6568373074: (6567953002, 'the pointer moved from Edition 5 to Edition 6'),
6569312507: (6568373074, 'the pointer moved from Edition 6 to Edition 7'),
6569860419: (6569312507, 'the pointer moved from Edition 7 to Edition 8'),
6570717660: (6569860419, 'the pointer moved from Edition 8 to Edition 9'),
6572568222: (6570717660, 'the pointer moved from Edition 9 to Edition 10'),
6574744989: (6572568222, 'the pointer moved from Edition 10 to Edition 11'),
6566485658: (6565195261, 'kuiper-shell rev 2 replaces rev 1 (refused 6565858587)'),
6568299280: (6566485658, 'kuiper-shell rev 3 (2045c51a) replaces rev 2 (withdrawn 6567109868)'),
6567112212: (6565667126, 'layers re-handed off with the four behaviours'),
6568555984: (6567112212, 'layers revision 202611020304 (b16716bd)'),
6571928537: (6568555984, 'layers revision 202611020637 (c8fccccf) after b16716bd was refused 6569024455'),
6566504289: (6565879640, 'drift revision 49/49'),
6568883224: (6566504289, 'drift revision 202611020240 (f03b7835) after the withdrawal 6567584787'),
6573876435: (6568231803, 'File revision 202611020832 (5fc4e307) replaces 3ae05df7'),
6567574981: (6565550370, 'line-card landscape revision 8ec117f9 replaces e2baeaaa'),
6566812411: (6565556866, 'POINTER-READY redefined without layers; admission order 5, 8, 6, 7, 3, 9'),
6566977283: (6566873489, 'D020 answered on the link: K1 blobs stay in branch history, main never carried them'),
6568437190: (6568425579, 'whole-wafer HARNESS-LIMITED ruling; controller 2 takes over from controller 1'),
6570675769: (6568425579, 'controller 2 hands over the queue; controller 1 handover superseded'),
6568425579: (6566567995, 'controller 1 end-of-run handover replaces its running REVIEW state'),
}
ADMIT_WORDS = re.compile(r'\bADMITTED\b|\badmitted\b', re.I)
REFUSE_WORDS = re.compile(r'\bREFUSED\b|\bwithdrawn\b|\bwithdraws\b', re.I)
def load_comments(cdir):
rows = []
if cdir:
files = sorted(glob.glob(os.path.join(cdir, 'c*.json')))
for f in files:
n = int(re.search(r'c(\d+)', os.path.basename(f)).group(1))
for r in json.load(open(f)):
r['_issue'] = n; rows.append(r)
else:
for n in ISSUES:
page = 1
while True:
data = json.loads(sh('gh', 'api', f'repos/{REPO}/issues/{n}/comments?per_page=100&page={page}'))
for r in data: r['_issue'] = n; rows.append(r)
if len(data) < 100: break
page += 1
seen = set(); out = []
for r in rows:
if r['id'] in seen: continue
seen.add(r['id']); out.append(r)
return sorted(out, key=lambda r: (r['_issue'], r['created_at']))
def parse_comment(r):
body = r['body'] or ''
first = body.strip().splitlines()[0] if body.strip() else ''
m = re.match(r'\s*\[([^\]]+?)\s*(?:→|->)\s*([^\]]*)\]\s*\[([^\]]*)\]\s*\[([^\]]*)\]', body)
if m:
frm, to, stamp = m.group(1).strip(), m.group(2).strip(), m.group(4).strip()
else:
m2 = re.match(r'\s*(\w[\w\-]*) · (\w+) · (\S+) ·', body)
frm = (m2.group(2).upper() if m2 else 'unknown'); to = 'ALL'; stamp = (m2.group(3) if m2 else '')
t = re.search(r'TYPE:\s*([A-Z][A-Z\-]+)', body)
typ = t.group(1) if t else (re.match(r'\s*([A-Z]+) ·', body).group(1) if re.match(r'\s*([A-Z]+) ·', body) else '?')
if typ == 'DECISION-PROPOSAL': typ = 'DECISION'
irt = re.search(r'IN-REPLY-TO:\s*(\S+)', body)
irt_id = None
if irt:
mm = re.search(r'issuecomment-(\d+)', irt.group(1))
irt_id = int(mm.group(1)) if mm else None
scope = re.search(r'SCOPE:\s*(.+)', body)
status = re.search(r'STATUS:\s*(.+)', body)
summary = (scope.group(1) if scope else first.split('·', 3)[-1] if '·' in first else first)
summary = re.sub(r'\s+', ' ', summary.strip())[:150]
corrected = 'time corrected' in first
return dict(id=r['id'], issue=r['_issue'], when=r['created_at'].replace('T', ' ').replace('Z', 'Z'), who=frm, to=to,
typ=typ, irt=irt_id, status=(status.group(1).strip()[:60] if status else ''), summary=summary,
stamp=stamp, corrected=corrected, updated=r['updated_at'] != r['created_at'], body=body)
def comment_rows(raw):
parsed = [parse_comment(r) for r in raw]
by = {p['id']: p for p in parsed}
for p in parsed:
sup = ''
if p['id'] in SUPERSEDES:
old, why = SUPERSEDES[p['id']]
sup = f'#{by[old]["issue"] if old in by else "?"}/c{old}: {why}'
elif p['typ'] == 'REVISION' and p['irt'] in by:
sup = f'#{by[p["irt"]]["issue"]}/c{p["irt"]}: revision of that hand-off'
if p['corrected']:
sup = (sup + '; ' if sup else '') + 'its own envelope time, corrected in place to GitHub\'s'
p['superseded'] = sup
rel = ''
if p['typ'] == 'REVIEW' and p['irt'] in by:
if REFUSE_WORDS.search(p['status']) or REFUSE_WORDS.search(p['body'][:600]): rel = 'refused'
if ADMIT_WORDS.search(p['status']): rel = 'admitted'
p['relation'] = rel
return parsed
# ---------------------------------------------------------------------------------------------------------------
# 3. Write the map.
# ---------------------------------------------------------------------------------------------------------------
def model_of(label):
u = label.upper()
if u.startswith('FABLE') or u.startswith('WATCHER'): return 'Fable'
if u.startswith('OPUS') or 'LINK-' in u: return 'Opus'
if u.startswith('HARNESS'): return 'harness (Fable session)'
if u.startswith('NL-011'): return 'Opus'
return 'unstated'
def norm_label(label):
s = re.sub(r'\s*\(.*?\)\s*', ' ', label).strip()
s = re.sub(r'\s+(lead|builder|tester|evidence|architect|consolidator|integrator).*$', '', s, flags=re.I)
s = re.sub(r'\s+(shell/evidence|layers|law-and-proof|bar|card|camera|touch|lines|seethrough|perf|type|robust|journey|index|persistence|decision log|resume kit|live reviewer|integration controller)$', '', s, flags=re.I)
return s.strip() or label
def esc(s):
return str(s).replace('|', '\\|')
def main():
ap = argparse.ArgumentParser()
ap.add_argument('--comments-dir')
ap.add_argument('--out', default='FIXES/NL-011/KUIPER-MAP.md')
a = ap.parse_args()
head = sh('git', 'rev-parse', '--short', 'HEAD').strip()
now = datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%d %H:%M UTC')
frows = file_rows()
crows = comment_rows(load_comments(a.comments_dir))
unverified = [r for r in frows if not r['verified']]
agents = collections.OrderedDict()
for p in crows:
k = norm_label(p['who'])
a_ = agents.setdefault(k, dict(model=model_of(k), n=0, roles=set(), first=p['when'], last=p['when'], issues=set()))
a_['n'] += 1; a_['last'] = max(a_['last'], p['when']); a_['first'] = min(a_['first'], p['when']); a_['issues'].add(p['issue'])
role = re.search(r'\b(lead|builder|tester|evidence|architect|consolidator)\b', p['who'], re.I)
if role: a_['roles'].add(role.group(1).lower())
L = []
L.append('# KUIPER-MAP: the neural link keyed the way the Kuiper keys lines')
L.append('')
L.append(f'Built by FIXES/NL-011/build_kuiper_map.py at {now} (clock read with `date -u`) on neural-link-between-agents '
f'`{head}`. One row per key. A file key `nl@<commit> <path>:<line>` names the commit that wrote the line '
f'(git blame) and the line number in that commit\'s version of the file; each line was re-read from that commit '
f'with `git show` and compared with the working tree ({len(frows) - len(unverified)} of {len(frows)} equal; '
f'a row marked `~` differs in whitespace only or has moved). A comment key `#<issue>/c<id>` is the GitHub issue '
f'comment; its time is GitHub\'s `created_at`, never the self-written stamp. "Supersedes" names the key a row '
f'replaced, from the envelope (REVISION, IN-REPLY-TO) or the builder\'s curated list, which is itself in the script.')
L.append('')
L.append('Types: RULE (binds agents), RULING (a harness or controller decision on a case), DECISION (a proposal, a plan or an '
'owner question; DECISION-PROPOSAL envelopes are written DECISION), HANDOFF, REVISION, REVIEW, FINDING; the envelope\'s '
'REQUEST, ACK and BLOCKER are kept where a comment carries them.')
L.append('')
L.append(f'Counts: {len(frows)} file keys, {len(crows)} comment keys (#9 {sum(1 for p in crows if p["issue"]==9)}, '
f'#10 {sum(1 for p in crows if p["issue"]==10)}, #11 {sum(1 for p in crows if p["issue"]==11)}), {len(agents)} agent labels.')
L.append('')
# agents
L.append('## A. Agents (every FROM label on #9, #10, #11, normalised to the agent; role words kept in the comment rows)')
L.append('')
L.append('| agent | model | comments | issues | first (UTC) | last (UTC) |')
L.append('|---|---|---|---|---|---|')
for k, v in sorted(agents.items(), key=lambda kv: (kv[1]['model'], kv[0])):
L.append(f'| {esc(k)} | {v["model"]} | {v["n"]} | {", ".join("#"+str(i) for i in sorted(v["issues"]))} | {v["first"]} | {v["last"]} |')
by_model = collections.Counter(v['model'] for v in agents.values())
L.append('')
L.append('Distinct labels by model: ' + ', '.join(f'{m} {n}' for m, n in sorted(by_model.items())) + '.')
L.append('')
# file rows
L.append('## B. Rules, rulings and decisions written in this repository (keyed by the commit that wrote the line)')
L.append('')
L.append('| key | written (UTC, commit time) | who | type | supersedes | text (first 170 chars) |')
L.append('|---|---|---|---|---|---|')
for r in frows:
mark = '' if r['verified'] else ' ~'
L.append(f'| `{r["key"]}`{mark} | {r["when"]} | {esc(r["who"])} | {r["typ"]} | {esc(r["superseded"])} | {esc(r["summary"])} |')
L.append('')
# comments
for n in ISSUES:
L.append(f'## C{n}. Issue #{n} comments')
L.append('')
L.append('| key | created (UTC) | from | to | type | in reply to | supersedes | relation | scope / first line |')
L.append('|---|---|---|---|---|---|---|---|---|')
for p in crows:
if p['issue'] != n: continue
irt = f'c{p["irt"]}' if p['irt'] else ('NEW' if 'IN-REPLY-TO: NEW' in p['body'] else '')
L.append(f'| `#{n}/c{p["id"]}` | {p["when"]} | {esc(p["who"])} | {esc(p["to"][:60])} | {p["typ"]} | {irt} | {esc(p["superseded"])} | {p["relation"]} | {esc(p["summary"])} |')
L.append('')
L.append('## Limits')
L.append('')
L.append('- A file key is only as fine as a line: a decision spread over several lines is keyed by its first line.')
L.append('- The "supersedes" column is complete for the chains the builder lists (editions, delegation, module revisions, '
'controller handovers) and for REVISION envelopes; other supersessions live in the DECISIONS.md rows\' status column.')
L.append('- "relation" is read from a REVIEW\'s STATUS line and first 600 characters (admitted / refused); a REVIEW that '
'both refuses one module and admits another is written by its STATUS word.')
L.append('- Comment bodies are not copied; the row keeps the SCOPE line (or the first line) only, so the K1 check runs on less text.')
L.append('')
L.append('---')
L.append('_Generated by [Claude Code](https://claude.ai/code)_')
open(a.out, 'w', encoding='utf-8').write('\n'.join(L) + '\n')
print(f'wrote {a.out}: {len(frows)} file keys ({len(unverified)} unverified), {len(crows)} comment keys, {len(agents)} agents')
if __name__ == '__main__':
main()GridAtlas A3 Map Links
A Python command-line tool in the tools folder of Neural Link Between Agents that reads offshore coordinates.
storageneural-link-between-agents / FIXES/NL-016/gridatlas/tools/a3_map_links.py · lines 1–101 of 101 · Entry point · pattern rows_of (shared by 2 files)
- What it does
- It loads offshore coordinates. Defines safe, km, rows_of, main. Uses libraries glob, json, math, sys, collections. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
- 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: JSON file offshore-coordinates.json; DuckDB queries; command-line arguments. Out: JSON file. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It is built from the safe step (`safe`) and the rows of helper (`rows_of`). A3: what GridAtlas returns for each MAP link of the operative Pipeline News page (`uk_renewables_pipeline`/), live (records Parquet, Q2) versus the October preview .
- 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-016/gridatlas/tools · Python CLI
- Uses
- glob, json, math, sys, collections, duckdb
- Used by
- none found
- Produces
- safe, km, rows_of, main
- Defines here
- safe, km, rows_of, main
- 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/gridatlas/tools/a3_map_links.py:1-101 · blob 7578836e99351274fc5592be423e30d9c2845546 · GitHub at these lines
- State
- achieves: comment · context: auto · stage: output · effects: filesystem, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer, ai_agent · canonical: supporting_data
"""A3: what GridAtlas returns for each MAP link of the operative Pipeline News page (uk_renewables_pipeline/202611132345),
live generation 202610312138 (records parquet 202608290716, Q2) versus the October preview 202611132345.
Offline replica of two receivers, read from the shipped code (not run in a browser):
- identity card: place-global-search receiveExactRepdDeepLink (atlas/cartridges/202611132345-place-global-search-v9-5.js
:695-850; the live 202609071213 cartridge has the same branch structure): exact repd_ref in the records parquet ->
RESOLVED (register point; else Crown Estate lease point from atlas/data/offshore-coordinates.json; else the link's point)
or RESOLVED_UNMAPPED; no exact ref -> NOT_IN_ACTIVE_REGISTER (no card; link fields kept). hasSafeMapPoint rejects 0,0 and
the BNG false origin (-7.55716, 49.766807).
- point and grid maths: sld-sandbox arrival (atlas/cartridges/202609241334-sld-sandbox-v9-8.js :6362-6620) measures from the
link's latitude/longitude whenever they are usable, independent of the register; refuses the false origin.
Usage: python3 -I a3_map_links.py <pipeline release dir> <gridatlas work dir> <previous operative release dir> <out.json>
"""
import glob, json, math, sys
from collections import Counter
import duckdb
FO = (-7.55716, 49.766807)
def safe(lon, lat):
if lon is None or lat is None or not (math.isfinite(lon) and math.isfinite(lat)):
return False
if abs(lon) < 1e-12 and abs(lat) < 1e-12:
return False
if abs(lat - FO[1]) < 1e-9 and abs(lon - FO[0]) < 1e-9:
return False
return -180 <= lon <= 180 and -90 <= lat <= 90
def km(a, b):
R = 6378.137; d = math.pi / 180
dl, dp = (b[0] - a[0]) * d, (b[1] - a[1]) * d
h = math.sin(dp / 2) ** 2 + math.cos(a[1] * d) * math.cos(b[1] * d) * math.sin(dl / 2) ** 2
return 2 * R * math.atan2(math.sqrt(h), math.sqrt(1 - h))
def rows_of(rel):
out = []
for f in sorted(glob.glob(f'{rel}/data/v9.1/projects/part-*.json')):
out += json.load(open(f, encoding='utf-8'))['projects']
return out
def main(rel, work, prev, outp):
proj = rows_of(rel)
prev_refs = {p['repd_ref'] for p in rows_of(prev)} if prev else set()
lease = {str(c['repd_ref']): c for c in json.load(open(f'{work}/atlas/data/offshore-coordinates.json'))['coordinates']
if c.get('longitude') is not None}
regs = {}
for g, pq in (('live_202610312138', '202608290716'), ('preview_202611132345', '202611132345')):
regs[g] = {r[0]: r for r in duckdb.connect().execute(
f"SELECT repd_ref, name, longitude, latitude, capacity_mw, technology FROM read_parquet('{work}/data/repd_projects_{pq}.parquet')").fetchall()}
res = []
for p in proj:
ref = str(p['repd_ref']); lon, lat = p.get('longitude'), p.get('latitude')
link_ok = safe(lon, lat)
row = {'repd_ref': ref, 'name': p['name'], 'technology': p.get('technology'), 'new_vs_202609082224': ref not in prev_refs,
'link_has_point': link_ok, 'arrival_point_and_grid_maths': 'MEASURED_FROM_LINK_POINT' if link_ok else 'NOT_MEASURED'}
for g, reg in regs.items():
r = reg.get(ref)
if r is None:
st = 'NOT_IN_ACTIVE_REGISTER (no identity card; map point from link only)' if link_ok else 'NOT_IN_ACTIVE_REGISTER and no link point (lands nowhere)'
extra = None
else:
if safe(r[2], r[3]):
src = 'register'
pt = (r[2], r[3])
elif ref in lease:
src = 'crown_estate_lease'; pt = (lease[ref]['longitude'], lease[ref]['latitude'])
elif link_ok:
src = 'link'; pt = (lon, lat)
else:
src = None; pt = None
st = f'RESOLVED ({src} point)' if src else 'RESOLVED_UNMAPPED (identity, map not moved)'
extra = {'register_name_differs': r[1].strip() != (p['name'] or '').strip(),
'card_point_vs_link_point_km': round(km(pt, (lon, lat)), 3) if (pt and link_ok) else None}
row[g] = st
row[g + '_detail'] = extra
res.append(row)
summ = {}
for subset, flt in (('all_rows', lambda r: True), ('new_vs_202609082224', lambda r: r['new_vs_202609082224'])):
s = [r for r in res if flt(r)]
summ[subset] = {'rows': len(s)}
for g in regs:
summ[subset][g] = dict(Counter(r[g] for r in s).most_common())
summ[subset][g + '_card_point_over_1km_from_link'] = sum(1 for r in s if (r[g + '_detail'] or {}).get('card_point_vs_link_point_km') and r[g + '_detail']['card_point_vs_link_point_km'] > 1)
summ[subset][g + '_register_name_differs'] = sum(1 for r in s if (r[g + '_detail'] or {}).get('register_name_differs'))
summ[subset]['arrival'] = dict(Counter(r['arrival_point_and_grid_maths'] for r in s))
gap = [r for r in res if r['live_202610312138'].startswith('NOT_IN') and not r['preview_202611132345'].startswith('NOT_IN')]
summ['closed_by_preview'] = len(gap)
summ['still_not_in_preview'] = Counter(r['preview_202611132345'] for r in res if r['preview_202611132345'].startswith('NOT_IN'))
far = sorted([r for r in res if ((r['preview_202611132345_detail'] or {}).get('card_point_vs_link_point_km') or 0) > 1],
key=lambda r: -r['preview_202611132345_detail']['card_point_vs_link_point_km'])
summ['preview_card_vs_link_over_1km_examples'] = [f"{r['repd_ref']} {r['name']} {r['preview_202611132345_detail']['card_point_vs_link_point_km']} km" for r in far[:10]]
json.dump({'summary': summ, 'rows': res}, open(outp, 'w'), indent=0, ensure_ascii=False, default=list)
print(json.dumps(summ, indent=1, default=dict))
if __name__ == '__main__':
main(*sys.argv[1:5])GridAtlas Clockshift
A JavaScript module in the tools folder of Neural Link Between Agents.
transformneural-link-between-agents / FIXES/NL-016/gridatlas/tools/clockshift.mjs · lines 1–5 of 5 · Not reached from any entry point (candidate for review)
- What it does
- It calculates its inputs. Defines FD.
- 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.
- What it achieves
- Preload: shift the JS clock to `FAKE_NOW` (ISO) while letting it tick.
- Why it matters
- No other file in the estate was found to import it.
- Application
- neural-link-between-agents · FIXES/NL-016/gridatlas/tools · JavaScript module
- Uses
- none found
- Used by
- none found
- Produces
- FD
- Defines here
- FD
- 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/gridatlas/tools/clockshift.mjs:1-5 · blob e0a4fe2be1f46eab2a804ddd2a59e458d2358b3b · GitHub at these lines
- State
- achieves: comment · context: auto · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer, ai_agent · canonical: unreached_review
// Preload: shift the JS clock to FAKE_NOW (ISO) while letting it tick. Test-only evidence tool.
const target = Date.parse(process.env.FAKE_NOW), real = Date.now, off = target - real();
const R = Date;
class FD extends R { constructor(...a) { if (a.length === 0) super(real() + off); else super(...a); } static now() { return real() + off; } }
globalThis.Date = FD;