GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / graphics-engines-open-source / web/versions/202609262227-site-world/world

Substrate and 5 more files

A JavaScript module in the world folder of Graphics Engines Open Source that sets origin, writes readout, opens panel and calculates planar distances, covering projects, attribution and substations.

655 lines of JavaScript and HTML and Python from graphics-engines-open-source, kuiper-belt, in 6 files. Topic: Kuiper, cosmos and drawing engines. Section 1503 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. Substrate geodesy · graphics-engines-open-source / web/versions/202609262227-site-world/world/substrate.mjs lines 1–339
  2. Graphics Engines Open Source — Versions Page render · graphics-engines-open-source / web/versions/index.html lines 1–45
  3. Notify Kuiper docs-config · kuiper-belt / agents/examples/notify-kuiper.yml lines 1–21
  4. Kuiper Belt — Diary Page render · kuiper-belt / diary/20261005.html lines 1–70
  5. Editions — Belt Page render · kuiper-belt / editions/202610311905/belt/index.html lines 1–53
  6. Edition Belt storage · kuiper-belt / editions/202610311905/tools/edition_belt.py lines 1–127

Substrate

A JavaScript module in the world folder of Graphics Engines Open Source that sets origin, writes readout, opens panel and calculates planar distances, covering projects, attribution and substations.

geodesygraphics-engines-open-source / web/versions/202609262227-site-world/world/substrate.mjs · lines 1–339 of 339 · version 2026-09-26 22:27 · Entry point · pattern dismissStart (shared by 3 files)

What it does
It draws projects, attribution and substations. Defines 29 functions or classes, including $, live, guarded, baseHeight, measuredAt. Side effects: changes the web page (DOM); reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain terms in the code: substations.
Inputs & outputs
In: JSON file projects.json; JSON file attribution.json; browser storage (getItem). Out: browser storage (setItem). Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
Downstream impact
Used directly by 1 file: Versions — Site World Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/202609262227-site-world/). Reached from 1 other entry point, including Graphics Engines Open Source — Versions Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/).
What it achieves
It sets origin (`setOrigin`), writes readout (`writeReadout`) and opens panel (`openPanel`). The substrate: an empty world you can move around in. It reads `./world/data/projects.json`. It responds to click, pointerdown and resize events.
Why it matters
Loaded by the Site World page at https://ventusltd.github.io/graphics-engines-open-source/web/versions/202609262227-site-world/.
Application
graphics-engines-open-source · web/versions/202609262227-site-world/world · JavaScript module
VEDIC
HEIGHT (GG2050-VEDIC-000011): Solar Design Studio / LiDAR · Mathematics / Raster sampling. bng_easting_m, bng_northing_m → height_receipt_or_null
Uses
Links (import), Camera (import), Views (import), Frame Gate (import), Device Budget (import), Lines (import), Input (import), Layers (import), and 7 more
Used by
loaded by Versions — Site World Page (script src), mentioned in Standalone (comment link)
Produces
$, live, guarded, baseHeight, measuredAt, heightAt, solids, invalidate, gridAssets, setOrigin, target, moving
Defines here
$, live, guarded, baseHeight, measuredAt, heightAt, solids, invalidate, gridAssets, setOrigin, target, moving, flyTo, draw, pin, chooseView, writeReadout, openPanel, hold, release, remembered, dismissStart, nearestSubstation, near, showPlace, writeCredits, mountFind, siteNear, loadIndex
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
graphics-engines-open-source@79e0bd8ee33844835e553fc84d552b6aa1521152 web/versions/202609262227-site-world/world/substrate.mjs:1-339 · blob b7492cfaf9ebaf8f57b633ae339dd248ed7d6a45 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: unknown · users: none · canonical: unknown
// The substrate: an empty world you can move around in. It owns the loop, the camera and the views;
// everything you see comes from layers listed in manifest.json, plus the design being drawn (trenches and cables).
// Positions are local metres from the site origin, which is held in float64 British National Grid metres
// (0, 0 until a site is chosen). setOrigin moves the origin and shifts the viewer so they stay put in the world;
// walking more than 600 m from the origin moves it to the nearest whole kilometre (origin.mjs).
// The design is kept in memory in national-grid metres, so it survives every move of the origin.

import { gridAtlasUrl } from './links.mjs';
import { perspective, view, multiply } from './camera.mjs';
import { VIEWS, fpsOf, step, look, setView, toggle, blocked, AERIAL_MIN_CLEARANCE } from './views.mjs';
import { createFrameGate } from './frame-gate.mjs';
import { initialBudget, adjust } from './device-budget.mjs';
import { createLines } from './lines.mjs';
import { attachInput } from './input.mjs';
import { loadLayers } from './layers.mjs';
import { rebaseIfNeeded, toBng, toLocal } from './origin.mjs';
import { arrive } from './arrival.mjs';
import { gridRef, wgs84ToBng } from './bng.mjs';
import { createDesign } from './design-ui.mjs';
import { createSearchPanel, NO_TERRAIN } from './search-ui.mjs';
import { distanceLabel } from './labels.mjs';
import { footerText, aboutList } from './attribution.mjs';

const $ = id => document.getElementById(id);
const canvas = $('view'), where = $('where'), status = $('status');
const FADE_M = 450, FOV = 70 * Math.PI / 180, MAX_DT = 0.1, ARRIVAL_FPS = 30, ARRIVAL = { height: 80, seconds: 3 };
const JUMP_M = 3000;      // further than this, Find moves the origin and drops in from above instead of flying across
const SITE_HALF_M = 1024; // half the staged site's side: terrain tiles exist within this of its centre
// Arriving at a found place: an oblique look at it, about 35 degrees down from 150 m out, not straight down on it.
const OBLIQUE = { pitch: -35 * Math.PI / 180, back: 150 };
const SUBSTATION_REACH_M = 5000; // further than this, the grid data here is not the grid near the place

let state = { view: 'standing', pos: [0, -25, 0], yaw: 0, pitch: -0.12 };
let budget = initialBudget(devicePixelRatio);
let loaded = { generation: '', layers: [] }, vertices = 0;
let origin = { e: 0, n: 0, id: 0 };
let groundVersion = 0; // bumped whenever a layer says new ground has arrived, or the origin moves
let lastGround = 0;    // the last ground height found near the viewer; used where no layer knows the height
let arrival = null;    // { pose, t0 } while the drone flies itself somewhere
let place = null;      // the place last found: { label, e, n } in national-grid metres; a pin marks it
const GROUND_MEMORY_M = 20;

const live = () => loaded.layers.filter(l => l.layer);
// A layer that throws is switched off and named; it never takes the rest of the world down with it.
const guarded = (l, fn, fallback) => {
  try { return fn(); } catch (e) { l.layer = null; l.status = 'failed and switched off: ' + e.message; return fallback; }
};
// The ground the layers know, before any design cuts it.
const baseHeight = (x, y) => {
  for (const l of live()) {
    if (typeof l.layer.heightAt !== 'function') continue;
    const h = guarded(l, () => l.layer.heightAt(x, y), NaN);
    if (Number.isFinite(h)) {
      if (Math.hypot(x - state.pos[0], y - state.pos[1]) <= GROUND_MEMORY_M) lastGround = h;
      return h;
    }
  }
  return lastGround; // the empty world is flat at 0 m; past the edge of known ground, keep the last height
};
// Ground actually measured by a layer at (x, y), or NaN: engineering checks use this, never a guess.
const measuredAt = (x, y) => {
  for (const l of live()) {
    if (typeof l.layer.heightAt !== 'function') continue;
    const h = guarded(l, () => l.layer.heightAt(x, y), NaN);
    if (Number.isFinite(h)) return h;
  }
  return NaN;
};
// The ground everyone stands on: the layers' ground with every finished trench cut into it (design-ui.mjs).
const heightAt = (x, y) => design.heightAt(x, y);
// Solids are what a person or drone cannot pass through; layers declare them as boxes in local metres.
const solids = () => live().flatMap(l => (typeof l.layer.solids === 'function' ? guarded(l, () => l.layer.solids({ pos: state.pos }), []) : []));

const lines = createLines(canvas, { onRestore: () => gate.invalidate() });
const gate = createFrameGate(draw);
// A layer asks for a redraw; { ground: true } (the default) also says new ground has arrived.
const invalidate = ({ ground = true } = {}) => { if (ground) groundVersion++; gate.invalidate(); };

// Grid equipment the design measures its routes against: substations and towers from the grid layer, if loaded.
function gridAssets() {
  const model = live().find(l => l.id === 'grid')?.layer?.debug?.()?.model;
  if (!model) return [];
  const subs = (model.substations || []).map(s => ({ kind: 'substation', label: `${s.cls} substation`, e: s.e, n: s.n }));
  const towers = (model.lines || []).flatMap(l => l.towers.map(t => ({ kind: 'tower', label: `${l.cls} pylon`, e: t.e, n: t.n })));
  return [...subs, ...towers];
}
const design = createDesign({ doc: document, canvas, fov: FOV, baseHeight, measured: measuredAt, origin: () => origin, viewer: () => state,
  invalidate, redraw: () => gate.invalidate(), assets: gridAssets });
design.setGroundVersion(() => groundVersion);

// ---- moving -----------------------------------------------------------------------------------------
// Moves the site origin to (e, n) national-grid metres. The viewer and the route being drawn are shifted by the
// same amount the other way, so they stay in the same place in the world; layers read it via api.origin().
function setOrigin(e, n) {
  if (!Number.isFinite(e) || !Number.isFinite(n)) throw Error('setOrigin needs finite easting and northing');
  const dx = e - origin.e, dy = n - origin.n;
  state = { ...state, pos: [state.pos[0] - dx, state.pos[1] - dy, state.pos[2]] };
  origin = { e, n, id: origin.id + 1 };
  design.shift(dx, dy);
  invalidate();
  return { ...origin };
}

const target = () => (arrival ? ARRIVAL_FPS : fpsOf(VIEWS[state.view], input.get().slow));
const moving = () => input.active() || !!arrival;
const input = attachInput(canvas, $('pad'), {
  onChange: () => { if (input.active()) arrival = null; gate.setMoving(moving(), target()); gate.invalidate(); },
  onLook: (dy, dp) => { arrival = null; state = look(state, dy, dp); gate.invalidate(); },
  onView: v => chooseView(toggle(state.view, v)),
  onClick: (x, y) => design.pickAt(x, y)
});

// Flies the drone smoothly to hover above local [x, y], looking down; any movement key takes over.
function flyTo(x, y, opts = {}) {
  if (state.view !== 'aerial') chooseView('aerial', { arrive: false });
  if (Math.hypot(x - state.pos[0], y - state.pos[1]) > JUMP_M) { // a far place: move the origin there, drop in from above
    const p = toBng(origin, x, y);
    setOrigin(Math.round(p.e / 1000) * 1000, Math.round(p.n / 1000) * 1000);
    [x, y] = toLocal(origin, p.e, p.n);
    state = { ...state, pos: [x, y, heightAt(x, y) + 400] };
  }
  // back: stand off this far behind the point (along the current heading), so a pitch above straight down still sees it.
  const { back = 0, ...rest } = opts, yaw = rest.yaw ?? state.yaw, g = heightAt(x, y);
  const at = [x - back * Math.sin(yaw), y - back * Math.cos(yaw), g];
  const height = back && rest.pitch ? back * Math.tan(-rest.pitch) : (rest.height ?? ARRIVAL.height);
  arrival = { pose: arrive(state, at, { ...ARRIVAL, ...rest, yaw, height }), t0: performance.now() };
  gate.setMoving(true, ARRIVAL_FPS);
}

function draw(now, intervalMs) {
  if (arrival) {
    const t = (now - arrival.t0) / 1000;
    state = { ...state, ...arrival.pose(t) };
    if (arrival.pose.done(t)) { arrival = null; gate.setMoving(moving(), target()); }
  } else if (input.active()) {
    const i = input.get(), dt = Math.min(intervalMs / 1000, MAX_DT);
    if (i.turn) state = look(state, i.turn * dt, 0);
    state = step(state, i, dt, heightAt, solids());
    budget = adjust(budget, intervalMs, 1000 / target());
  }
  const r = arrival ? null : rebaseIfNeeded(origin, state.pos);
  if (r) setOrigin(r.e, r.n);
  // Ground can arrive after the viewer does (tiles stream in): a walker's eye follows it, a drone keeps clear.
  const v = VIEWS[state.view], g = heightAt(state.pos[0], state.pos[1]);
  if (v.eye !== null && Math.abs(state.pos[2] - (g + v.eye)) > 1e-6) state = { ...state, pos: [state.pos[0], state.pos[1], g + v.eye] };
  if (v.eye === null && state.pos[2] < g + AERIAL_MIN_CLEARANCE) state = { ...state, pos: [state.pos[0], state.pos[1], g + AERIAL_MIN_CLEARANCE] };
  lines.resize(budget.scale);
  // The view is built at the eye; lines.draw moves each batch by (its origin - eye) in doubles.
  const mat = multiply(perspective(FOV, canvas.width / canvas.height, 0.05, 5000), view([0, 0, 0], state.yaw, state.pitch));
  const ctx = { pos: state.pos, heightAt, measuredAt, groundVersion, origin: { ...origin } };
  const batches = live().flatMap(l => (typeof l.layer.lines === 'function' ? guarded(l, () => l.layer.lines(ctx), []) : []));
  vertices = lines.draw(mat, state.pos, FADE_M, batches.concat(design.batches(), pin()));
  writeReadout();
}

// The pin at the place last found: a 40 m mast with a diamond on the ground, so it can be seen from the drone.
function pin() {
  if (!place) return [];
  const [x, y] = toLocal(origin, place.e, place.n), z = heightAt(x, y), r = 6, h = 40;
  const v = [0, 0, 0, 0, 0, h, -r, 0, 0, 0, r, 0, 0, r, 0, r, 0, 0, r, 0, 0, 0, -r, 0, 0, -r, 0, -r, 0, 0,
    0, 0, h, -3, 0, h - 6, 0, 0, h, 3, 0, h - 6];
  return [{ key: 'place-pin', version: `${origin.id}:${groundVersion}:${place.e}:${place.n}`, positions: new Float32Array(v),
    color: [1, 0.45, 0.85, 1], origin: [x, y, z] }];
}

function chooseView(v, { arrive: fly = true } = {}) {
  const next = setView(state, v, heightAt);
  if (blocked(next.pos, VIEWS[v].body, solids())) return; // e.g. no standing up under a table
  const from = state.view;
  state = next; arrival = null;
  for (const b of document.querySelectorAll('[data-view]')) b.setAttribute('aria-pressed', String(b.dataset.view === v));
  $('lift').hidden = v !== 'aerial';
  if (v !== 'aerial') input.setLift(0);
  if (fly && v === 'aerial' && from !== 'aerial') flyTo(state.pos[0], state.pos[1]);
  gate.setMoving(moving(), target());
  gate.invalidate();
}

function writeReadout() {
  const [x, y, z] = state.pos, g = heightAt(x, y), v = VIEWS[state.view], p = toBng(origin, x, y);
  // On screen: a grid reference and the height of the ground above sea level. The exact numbers are under Controls.
  let ref = '';
  try { ref = gridRef(p.e, p.n, 8); } catch { /* off the national grid */ }
  const up = v.eye === null ? ` · ${Math.round(z - g)} m up` : '';
  const known = Number.isFinite(measuredAt(x, y)); // only measured ground is given a height above sea level
  where.textContent = `${ref ? ref + ' · ' : ''}${known ? `ground ${Math.round(g)} m above sea level` : 'ground height not measured here'}${up}`;
  $('where-detail').textContent = `${v.label} · easting ${p.e.toFixed(1)} m, northing ${p.n.toFixed(1)} m · ` +
    `eye ${(z - g).toFixed(2)} m above the ground${known ? ` · ground ${g.toFixed(2)} m above sea level` : ''}`;
  // When still, no frame is drawn, so the rate is 0 whatever the last second's counter still holds.
  status.textContent = `${moving() ? gate.fps() : 0} fps now (moving ${v.fps}, precise ${v.slowFps}, still 0) · ${budget.scale}× resolution · ` +
    `${vertices / 2} lines · ${loaded.layers.map(l => l.id + ': ' + l.status).join('; ') || 'no layers'}`;
}

// ---- page controls ----------------------------------------------------------------------------------
for (const b of document.querySelectorAll('[data-view]')) b.addEventListener('click', () => { chooseView(b.dataset.view); canvas.focus(); });
// One panel at a time: Find, Design and Controls share the space under the dash on a phone.
let search = null;
const panels = { 'help-toggle': 'help', 'design-toggle': 'design', 'find-toggle': 'find' };
// GridAtlas opens at the spot you are standing on (latitude, longitude and zoom only; no project reference).
$('to-gridatlas').addEventListener('click', () => {
  const url = gridAtlasUrl({ origin, pos: state.pos });
  if (url) open(url, '_blank', 'noopener');
});
function openPanel(btn, open) {
  if (btn === 'find-toggle') { if (search) (open ? search.open() : search.close()); }
  else $(panels[btn]).hidden = !open;
  $(btn).setAttribute('aria-expanded', String(open));
  if (btn === 'design-toggle' && !open) design.putDown(); // closing Design puts the tool down
  const shown = Object.keys(panels).find(b => $(b).getAttribute('aria-expanded') === 'true');
  if (shown) document.body.dataset.panel = panels[shown]; else delete document.body.dataset.panel;
  if (btn === 'find-toggle' && open) dismissStart();
}
for (const btn of Object.keys(panels)) {
  $(btn).addEventListener('click', () => {
    const open = $(btn).getAttribute('aria-expanded') !== 'true';
    for (const o of Object.keys(panels)) if (o !== btn && $(o).getAttribute('aria-expanded') === 'true') openPanel(o, false);
    openPanel(btn, open);
  });
}
// Up and Down: hold to climb or sink; a quick tap moves 10 m, so a tap is never lost.
const TAP_MS = 250, TAP_M = 10;
for (const b of document.querySelectorAll('[data-lift]')) {
  let down = 0;
  const hold = e => {
    e.preventDefault(); down = performance.now();
    try { b.setPointerCapture(e.pointerId); } catch { /* synthetic or finished pointer */ }
    input.setLift(Number(b.dataset.lift));
  };
  const release = e => {
    if (!down) return;
    const tap = e.type === 'pointerup' && performance.now() - down < TAP_MS;
    down = 0; input.setLift(0);
    if (tap && state.view === 'aerial') {
      const [x, y, z] = state.pos, floor = heightAt(x, y) + AERIAL_MIN_CLEARANCE;
      state = { ...state, pos: [x, y, Math.max(floor, z + Number(b.dataset.lift) * TAP_M)] };
      gate.invalidate();
    }
  };
  b.addEventListener('pointerdown', hold);
  for (const t of ['pointerup', 'pointercancel', 'pointerleave']) b.addEventListener(t, release);
}

// The first step, offered once: a small card that opens Find. Dismissed for good with × or by using Find.
const START_KEY = 'world.start.dismissed';
const remembered = () => { try { return localStorage.getItem(START_KEY) === '1'; } catch { return false; } };
function dismissStart() {
  $('start').hidden = true;
  try { localStorage.setItem(START_KEY, '1'); } catch { /* private window: it just shows again next time */ }
}
$('start').hidden = remembered();
$('start-close').addEventListener('click', () => { dismissStart(); canvas.focus(); });
$('start-go').addEventListener('click', () => { if ($('find-toggle').getAttribute('aria-expanded') !== 'true') $('find-toggle').click(); });
$('place-close').addEventListener('click', () => { $('place').hidden = true; canvas.focus(); });

// The nearest substation in the grid data to national-grid (e, n), or a plain line saying there is none to hand.
function nearestSubstation(e, n) {
  const all = gridAssets();
  if (!all.length) return 'Grid data not loaded for this area';
  const near = kind => all.filter(a => a.kind === kind).map(a => ({ ...a, d: Math.hypot(a.e - e, a.n - n) })).sort((a, b) => a.d - b.d)[0];
  const s = near('substation'), t = near('tower');
  if (s && s.d <= SUBSTATION_REACH_M) return `Nearest ${s.label}: ${distanceLabel(s.d)}`;
  const none = `No substation within ${SUBSTATION_REACH_M / 1000} km in the grid data loaded`;
  return t ? `${none} · nearest ${t.label} ${distanceLabel(t.d)}` : none;
}
// Names the place just found, pins it, and says what is known there.
function showPlace(label, e, n, terrain) {
  place = { label, e, n };
  $('place-name').textContent = label;
  let ref = '';
  try { ref = gridRef(e, n, 8) + ' · '; } catch { /* off the national grid */ }
  $('place-grid').textContent = ref + nearestSubstation(e, n);
  $('place-terrain').textContent = terrain ? '' : NO_TERRAIN;
  $('place').hidden = false;
  gate.invalidate();
}
addEventListener('resize', () => gate.invalidate());
setInterval(() => { if (!moving()) writeReadout(); }, 1000); // text only: no frame is drawn

// Small print for exactly the layers that are on: one line along the bottom, the full lines under Controls.
let attribution = null;
function writeCredits() {
  if (!attribution) return;
  const ids = live().map(l => l.id), full = footerText(ids, attribution);
  $('credit-full').textContent = full;
  $('credit-short').textContent = full.replace(/ copyright and\/or database right/g, '').replace(/ All rights reserved\./g, '');
  $('credits').replaceChildren(...aboutList(ids, attribution).map(c => {
    const li = document.createElement('li'), a = document.createElement('a');
    a.href = c.link || c.licence_url || '#'; a.target = '_blank'; a.rel = 'noopener';
    a.textContent = `${c.line} (${c.licence})`; li.append(a); return li;
  }));
}

// Find: a REPD project, postcode or "lat, lon"; the drone flies there. Near the staged site there is terrain.
function mountFind() {
  const siteNear = (lat, lon) => {
    if (!loaded.site) return false;
    const p = wgs84ToBng(lat, lon);
    return Math.abs(p.e - loaded.site.centre_e) <= SITE_HALF_M && Math.abs(p.n - loaded.site.centre_n) <= SITE_HALF_M;
  };
  const loadIndex = () => fetch('./world/data/projects.json', { cache: 'no-cache' })
    .then(r => { if (!r.ok) throw Error(`HTTP ${r.status}`); return r.json(); });
  search = createSearchPanel(document.body, {
    loadIndex, attribution, hasTerrain: siteNear,
    onChoose: ({ lat, lon, label }) => {
      const p = wgs84ToBng(lat, lon), [x, y] = toLocal(origin, p.e, p.n);
      openPanel('find-toggle', false);
      flyTo(x, y, OBLIQUE);
      showPlace(label || `${lat.toFixed(5)}, ${lon.toFixed(5)}`, p.e, p.n, siteNear(lat, lon));
      canvas.focus();
    }
  });
  search.element.id = 'find';
  // Escape inside the box closes it; keep the Find button in step.
  search.element.addEventListener('keydown', e => { if (e.key === 'Escape') { $('find-toggle').setAttribute('aria-expanded', 'false'); delete document.body.dataset.panel; } });
}

try {
  loaded = await loadLayers('./world/manifest.json', { invalidate, origin: () => origin });
} catch (e) {
  loaded = { generation: '', layers: [{ id: 'manifest', status: 'failed: ' + e.message }] };
}
await design.loadCatalogue();
try { attribution = await (await fetch('./world/data/attribution.json', { cache: 'no-cache' })).json(); } catch { /* the fixed footer stays */ }
writeCredits();
mountFind();
// A site places the world: its centre becomes the origin, so the viewer starts in the middle of the land.
if (loaded.site) origin = { e: loaded.site.centre_e, n: loaded.site.centre_n, id: origin.id + 1 };
chooseView('standing');

// For tests and the console. Read-only views of the live state, and the origin and arrival hooks.
window.world = Object.freeze({
  origin: () => ({ ...origin }), groundVersion: () => groundVersion, setOrigin, heightAt,
  state: () => state, budget: () => budget, fps: () => gate.fps(), generation: () => loaded.generation,
  layers: () => loaded.layers.map(({ id, status, layer }) => ({ id, status, detail: layer?.status ?? null })), // detail: the layer's own word
  // Flies the drone to national-grid (e, n): the arrival is smooth and capped at 30 fps.
  flyTo: (e, n, opts) => { const [x, y] = toLocal(origin, e, n); flyTo(x, y, opts); },
  place: () => (place ? { ...place } : null), // the place last found and pinned
  design: design.snapshot // the design in memory, in national-grid metres (export and import come later)
});

Graphics Engines Open Source — Versions Page

A web page. Published at https://ventusltd.github.io/graphics-engines-open-source/web/versions/.

rendergraphics-engines-open-source / web/versions/index.html · lines 1–45 of 45 · Entry point

What it does
It draws its content. Side effects: changes the web page (DOM); makes network requests.
Inputs & outputs
In: JSON file index.json. Out: web page.
Downstream impact
It is itself an entry point, published at https://ventusltd.github.io/graphics-engines-open-source/web/versions/.
What it achieves
Site world versions. It reads `index.json`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
graphics-engines-open-source · web/versions · page
Uses
Graphics Engines Open Source — Index Page (link), Versions — Site World Page (link)
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
graphics-engines-open-source@79e0bd8ee33844835e553fc84d552b6aa1521152 web/versions/index.html:1-45 · blob b3aca23c733d6b0d01ea92c119f3bd65905a3c7d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: unknown
<!doctype html>
<html lang="en-GB">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Site world versions</title>
<link rel="icon" href="data:,">
<style>
  :root { --bg: #0a0a0a; --line: #9cdbff; --text: #cfe9ff; --dim: #6f8ea6; --edge: #1c2c3a; }
  html, body { margin: 0; background: var(--bg); color: var(--text); font: 14px/1.5 system-ui, sans-serif; }
  main { max-width: 720px; margin: 0 auto; padding: 24px 16px 40px; }
  h1 { font-size: 18px; font-weight: 600; margin: 0 0 4px; }
  p { color: var(--dim); margin: 0 0 16px; }
  a { color: var(--line); }
  ol { list-style: none; margin: 0; padding: 0; border-top: 1px solid var(--edge); }
  li { padding: 12px 0; border-bottom: 1px solid var(--edge); display: grid; gap: 2px; }
  li time { color: var(--dim); font-size: 12px; font-variant-numeric: tabular-nums; }
  li span { color: var(--dim); }
</style>
</head>
<body>
<main>
  <h1>Site world versions</h1>
  <p>Each release is kept in its own dated folder, newest first. Earlier versions stay available. The
    <a href="../">electrical scene explorer</a> is separate and unchanged.</p>
  <ol id="list"><li>Loading the version list…</li></ol>
  <p style="margin-top:16px">Code: MIT. Terrain, grid and project data keep their own licences; each version lists them in
    <code>world/ATTRIBUTION.md</code>.</p>
</main>
<script>
fetch('index.json', { cache: 'no-cache' }).then(r => r.json()).then(j => {
  const list = document.getElementById('list');
  const items = (j.versions || []).slice().sort((a, b) => String(b.id).localeCompare(String(a.id)));
  list.replaceChildren(...items.map(v => {
    const li = document.createElement('li'), a = document.createElement('a'), t = document.createElement('time'), s = document.createElement('span');
    a.href = v.path; a.textContent = v.id;
    t.dateTime = v.date; t.textContent = v.date;
    s.textContent = v.label;
    li.append(a, s, t);
    return li;
  }));
}).catch(() => { document.getElementById('list').innerHTML = '<li><a href="202609262227-site-world/">202609262227-site-world</a></li>'; });
</script>
</body>
</html>

Notify Kuiper

A configuration file in the examples folder of Kuiper Belt. Runs on pull requests.

docs-configkuiper-belt / agents/examples/notify-kuiper.yml · lines 1–21 of 21 · Not reached from any entry point (candidate for review)

Why it exists in the grid workflow
Domain stage agent_infra (path word 'agents'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
What it achieves
Install in the source repository after approval and secret configuration.
Why it matters
No other file in the estate was found to import it.
Application
kuiper-belt · agents/examples · configuration
Uses
none found
Used by
none found
Produces
none declared
Defines here
Refresh Kuiper after merge
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
kuiper-belt@26fba12ab1b5bab8e71934ab86c58273e5f32682 agents/examples/notify-kuiper.yml:1-21 · blob 39df69768a82eed5ab81675a7efbe0895f5459c2 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: none found · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
# Example only: install in the source repository after approval and secret configuration.
name: Refresh Kuiper after merge
on:
  pull_request:
    types: [closed]
permissions:
  contents: read
jobs:
  notify:
    if: github.event.pull_request.merged == true && github.event.pull_request.base.ref == github.event.repository.default_branch
    runs-on: ubuntu-latest
    steps:
      - name: Dispatch if authorised
        env:
          GH_TOKEN: ${{ secrets.KUIPER_DISPATCH_TOKEN }}
        run: |
          if [ -z "$GH_TOKEN" ]; then
            echo "No cross-repository credential; hourly Kuiper refresh remains available."
            exit 0
          fi
          gh api repos/Ventusltd/kuiper-belt/dispatches -f event_type=kuiper-agent-refresh

Kuiper Belt — Diary Page

A web page covering substations and solar. Published at https://ventusltd.github.io/kuiper-belt/diary/20261005.html.

renderkuiper-belt / diary/20261005.html · lines 1–70 of 70 · version 2026-10-05 · Entry point

What it does
It draws substations and solar. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). Domain terms in the code: substations, solar.
Inputs & outputs
Out: web page.
Downstream impact
It is itself an entry point, published at https://ventusltd.github.io/kuiper-belt/diary/20261005.html.
What it achieves
What Learn the Kuiper and See Through are, what they could become, and how they may help with grid connection in the UK.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
kuiper-belt · diary · page
Uses
Kuiper Belt — Learn the Kuiper Page (link), Kuiper Belt — See Through Page (link)
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
kuiper-belt@26fba12ab1b5bab8e71934ab86c58273e5f32682 diary/20261005.html:1-70 · blob 1463e4a14fe085a7e4ab24620d0e55daecffaba2 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: agent_infra · users: ai_agent · canonical: unknown
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="dark">
<title>Kuiper diary, 5 October 2026</title>
<meta name="description" content="What Learn the Kuiper and See Through are, what they could become, and how they may help with grid connection in the UK.">
<style>
html,body{margin:0;background:#000;color:#fff}
body{font:400 20px/1.55 "Segoe UI",system-ui,-apple-system,Arial,sans-serif}
main{box-sizing:border-box;max-width:680px;margin:0 auto;padding:32px 22px 64px}
h1{font-weight:400;font-size:30px;line-height:1.25;margin:0 0 6px}
h2{font-weight:400;font-size:24px;line-height:1.3;margin:38px 0 10px}
p{margin:0 0 16px}
.date{color:rgba(255,255,255,.65);margin:0 0 28px}
ul{margin:0 0 16px;padding-left:22px}
li{margin:0 0 8px}
a{color:#fff}
.go{display:block;border:1px solid rgba(255,255,255,.55);padding:16px 18px;margin:0 0 12px;text-decoration:none;letter-spacing:.03em}
.go:focus,.go:hover{background:#fff;color:#000;outline:none}
.small{color:rgba(255,255,255,.65);font-size:17px}
</style>
</head>
<body>
<main>
<h1>Kuiper diary</h1>
<p class="date">5 October 2026</p>

<p>Two things are open to everyone today. Both are free to use on a phone or a computer.</p>

<a class="go" href="https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/">LEARN THE KUIPER</a>
<a class="go" href="https://ventusltd.github.io/kuiper-belt/see-through/">SEE THROUGH</a>

<h2>What the Kuiper is</h2>
<p>The Kuiper gives every item a whole number, called a key, and works out where that item belongs from the number alone. Nothing is placed by hand. Two short rules do the work:</p>
<ul>
<li>the square root of the key sets how far out the item sits (the live page adds a half before taking the root);</li>
<li>multiplying the key and keeping only the remainder (MOD) sets where round the circle it sits.</li>
</ul>
<p>The same two rules place one item or billions. Today they place the recorded lines of code across our repositories. The same rule could give a key to every substation, cable and solar panel on a grid.</p>

<h2>Learn the Kuiper</h2>
<p>One circle, one dot and two numbers. One number sets the distance, the other sets the angle. Slide them or type them, and steer the dot onto the targets. A link then ties the two numbers into one key, and you are doing by hand what the Kuiper does for everything it holds.</p>
<p>There is almost nothing to read. You learn the rule the way you learn to ride a bicycle. A copy button gives the two rules as spreadsheet formulas, so anyone can rebuild the Kuiper in Excel or Google Sheets.</p>

<h2>See Through</h2>
<p>Type the name of a UK substation and press GO. The stars gather into the grid, the real map and the satellite view appear inside the circle, and then a model of the substation rises in three dimensions on the real ground, with towers along the mapped line routes.</p>
<p>The model is illustrative. It is drawn by one rule from open map data: what is mapped is shown where it is mapped, and the rest is estimated from the voltage and labelled as drawn. The same code covers about 5,800 mapped substations. Try: cowley.</p>

<h2>What it could become</h2>
<ul>
<li><b>Travel the grid.</b> Light the published circuits that leave a substation and follow them from site to site.</li>
<li><b>Start from a project.</b> Point at a field, a roof or a factory and see the nearest substations, the voltages there and the likely route lengths, in seconds.</li>
<li><b>Narrow it down step by step.</b> Compare sites one step at a time, so a person can organise the published evidence and the right questions for a network operator. That is the aim behind "see to grid connection probabilities iteratively". No connection probability is calculated today.</li>
<li><b>Carry it anywhere.</b> Both run in a browser, Learn the Kuiper also works offline, and the rule fits in two lines of a spreadsheet.</li>
</ul>

<h2>Why this matters in the UK now</h2>
<p>The wars in Ukraine and Iran showed how exposed the country is to imported fuel and to its price. More home-grown electricity is the way out, and a large part of the difficulty is no longer building the solar farms, wind farms and batteries. It is connecting them. Projects can wait years for a grid connection, and many applications are made for places where connecting was always going to be har  … [line shortened here: 406 characters; full line on GitHub]
<p>A tool that lets anyone see the grid around a site, quickly and for free, will not replace the studies a network operator must do. It may help before them: better questions asked earlier, and more people who understand how the grid is laid out and why a connection is easy in one place and hard in another.</p>
<p>Our ambition is faster electrification, and 75 terawatts of peak solar capacity worldwide by 2050.</p>

<h2>What it does not do</h2>
<p>It does not say whether a project can connect, what it would cost or when. It combines published map features with estimates, clearly marked as drawn from open data, and does not calculate network capacity, connection probability or a connection offer. Decisions still belong to the network operators and to qualified people.</p>

<p class="small">Substation and line data: (c) OpenStreetMap contributors, ODbL. Map: CARTO. Imagery: Esri and its providers. The placement rule follows H. Vogel (1979); its multiplier is the golden-ratio constant of D. E. Knuth's Fibonacci hashing; the numbers behind both are Fibonacci's (1202).</p>
</main>
</body>
</html>

Editions — Belt Page

A web page in Kuiper Belt that draws bodies. Published at https://ventusltd.github.io/kuiper-belt/editions/202610311905/belt/. It is built from the load step (`load`), the resize step (`resize`) and the to screen helper (`toScreen`).

renderkuiper-belt / editions/202610311905/belt/index.html · lines 1–53 of 53 · version 2026-10-31 19:05 · Entry point · pattern toScreen (shared by 40 files)

What it does
It draws bodies. Defines 7 functions or classes, including load, resize, toScreen, draw, pick. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). README: "`gridatlas atlas/index.html:81` — no served byte runs unless its SHA-256 equals the pointer's."
Inputs & outputs
In: JSON file belt.json; JSON file bodies.json. Out: web page; canvas drawing.
Downstream impact
It is itself an entry point, published at https://ventusltd.github.io/kuiper-belt/editions/202610311905/belt/.
What it achieves
Kuiper edition : the estate's best lines on the belt. It reads `belt.json`. It responds to pointerdown, pointermove and pointerup events.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
kuiper-belt · editions/202610311905/belt · page
Uses
none found
Used by
none found
Produces
load, resize, toScreen, draw, pick, show, esc
Defines here
load, resize, toScreen, draw, pick, show, esc
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
kuiper-belt@26fba12ab1b5bab8e71934ab86c58273e5f32682 editions/202610311905/belt/index.html:1-53 · blob baaf242883bf3a6a4aff570391767530545ec91c · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: agent_infra · users: ai_agent · canonical: unknown
<!DOCTYPE html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Kuiper edition 202610311905: the estate's best lines on the belt</title>
<style>
html,body{margin:0;height:100%;background:#05060a;color:#e8e6df;font:14px/1.4 ui-monospace,Menlo,Consolas,monospace}
#c{display:block;width:100vw;height:100vh;touch-action:none}
#card{position:fixed;left:0;right:0;bottom:0;max-height:46vh;overflow:auto;background:rgba(10,12,18,.96);border-top:1px solid #2a2f3a;padding:10px 14px;display:none}
#card b{color:#ffd166}#card a{color:#8ecae6}#card pre{white-space:pre-wrap;color:#cde;margin:6px 0;border-left:2px solid #3a4150;padding-left:8px}
#hud{position:fixed;top:8px;left:10px;color:#9aa3b2;font-size:12px;pointer-events:none}
#hud b{color:#e8e6df}
</style></head><body>
<canvas id="c"></canvas><div id="hud">loading…</div><div id="card"></div>
<script>
// Viewer for belt/belt.json + belt/bodies.json. Stations are [x, y, key, copies] centred on zero, exactly
// as written by tools/edition_belt.py. The viewer computes no position of its own: a body's place
// is the file's, and the file is reproducible from the register and the law printed in rules.txt.
const cv=document.getElementById('c'),ctx=cv.getContext('2d'),hud=document.getElementById('hud'),card=document.getElementById('card');
let belt=null,bodies=[],byId={},view={z:1,ox:0,oy:0},sel=null,dpr=1;
const COL={focus:'#ffd166',estate:'#8ecae6',kuiper:'#c77dff',history:'#90be6d'};
async function load(){
  belt=await (await fetch('belt.json')).json();
  bodies=await (await fetch('bodies.json')).json();
  for(const b of bodies) byId[b.id]=b;
  hud.innerHTML=`<b>${belt.name}</b> · ${belt.counts.bodies} bodies (${belt.counts.focus} gridatlas/datacentre) · ${belt.counts.unresolved} unresolved · asof ${belt.asof}<br>${belt.law}`;
  resize(); draw();
}
function resize(){dpr=window.devicePixelRatio||1;cv.width=innerWidth*dpr;cv.height=innerHeight*dpr;cv.style.width=innerWidth+'px';cv.style.height=innerHeight+'px';}
function toScreen(x,y){const s=Math.min(innerWidth,innerHeight)*view.z*0.5;return[innerWidth/2+x*s+view.ox,innerHeight/2-y*s+view.oy];} // y up, as the wafer draws it
function draw(){
  ctx.setTransform(dpr,0,0,dpr,0,0);ctx.fillStyle='#05060a';ctx.fillRect(0,0,innerWidth,innerHeight);
  const [cx,cy]=toScreen(0,0),s=Math.min(innerWidth,innerHeight)*view.z*0.5;
  ctx.strokeStyle='#161a24';ctx.lineWidth=1;for(const r of [0.16,0.92]){ctx.beginPath();ctx.arc(cx,cy,r*s,0,7);ctx.stroke();}
  for(const st of belt.stations){const id=st[2],b=byId[id];const [x,y]=toScreen(st[0],st[1]);
    ctx.fillStyle=COL[b&&b.class]||'#aaa';ctx.globalAlpha=b&&b.open?1:.35;ctx.beginPath();ctx.arc(x,y,sel===id?6:3.2,0,7);ctx.fill();
    if(sel===id){ctx.strokeStyle='#fff';ctx.lineWidth=1.5;ctx.stroke();}}
  ctx.globalAlpha=1;
}
function pick(px,py){let best=null,bd=14*14;for(const st of belt.stations){const [x,y]=toScreen(st[0],st[1]);const d=(x-px)**2+(y-py)**2;if(d<bd){bd=d;best=st[2];}}return best;}
function show(id){const b=byId[id];if(!b){card.style.display='none';return;}
  card.style.display='block';
  card.innerHTML=`<b>${esc(b.title)}</b> <span style="color:#9aa3b2">[${esc(b.worker)} ${esc(b.finding)} · class ${esc(b.class)} · body k=${b.k}]</span><br>
  <code>${esc(b.repo)}@${b.commit.slice(0,12)} ${esc(b.path)}:${b.line}${b.line_end&&b.line_end!=String(b.line)?'-'+esc(b.line_end):''}</code><br>
  ${b.quote?`<pre>${esc(b.quote)}</pre>`:''}${b.pattern?`pattern: ${esc(b.pattern)}<br>`:''}
  key <code>${b.id}</code><br><a href="${b.destination}" target="_blank" rel="noopener">open the line on GitHub at that commit</a>`;}
function esc(s){return String(s??'').replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));}
let drag=null;
cv.addEventListener('pointerdown',e=>{drag={x:e.clientX,y:e.clientY,ox:view.ox,oy:view.oy,moved:false};cv.setPointerCapture(e.pointerId);});
cv.addEventListener('pointermove',e=>{if(!drag)return;const dx=e.clientX-drag.x,dy=e.clientY-drag.y;if(Math.hypot(dx,dy)>4)drag.moved=true;view.ox=drag.ox+dx;view.oy=drag.oy+dy;draw();});
cv.addEventListener('pointerup',e=>{if(drag&&!drag.moved){sel=pick(e.clientX,e.clientY);show(sel);draw();}drag=null;});
cv.addEventListener('wheel',e=>{e.preventDefault();view.z=Math.max(.5,Math.min(40,view.z*(e.deltaY<0?1.15:1/1.15)));draw();},{passive:false});
addEventListener('resize',()=>{resize();draw();});
load();
</script></body></html>

Edition Belt

A Python command-line tool in the tools folder of Kuiper Belt that reads bodies and unresolved, using SHA-256.

storagekuiper-belt / editions/202610311905/tools/edition_belt.py · lines 1–127 of 127 · version 2026-10-31 19:05 · Entry point

What it does
It loads bodies and unresolved. Defines is, sh, blob_sha, main, write. Uses libraries argparse, csv, hashlib, json, math. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file belt.json; JSON file bodies.json; JSON file unresolved.json; 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 blob sha helper (`blob_sha`) and the write step (`write`). Place the verified keyed findings of a Kuiper edition on the belt. It writes `belt/belt.json`. It accepts `--register`, `--roots` and `--out`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
kuiper-belt · editions/202610311905/tools · Python CLI
Uses
argparse, csv, hashlib, json, math, os, subprocess, sys
Used by
none found
Produces
is, sh, blob_sha, main
Defines here
is, sh, blob_sha, main, write
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
kuiper-belt@26fba12ab1b5bab8e71934ab86c58273e5f32682 editions/202610311905/tools/edition_belt.py:1-127 · blob 0fcd48a8cc35f8f8d023ef7e8b11ad0136985ad2 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
#!/usr/bin/env python3
"""edition_belt.py: place the verified keyed findings of a Kuiper edition on the belt.

Law (kuiper-belt/README.md, estate-network.json "law"): one body per key;
r = a_min + (a_max - a_min) * sqrt((k + 0.5) / n), k the body ordinal among sorted keys;
theta = 2*pi*((k*2654435769) mod 2^32)/2^32, the 32-bit odometer of the live wafer (+222.492236 deg per key);
class is a property and never a position; no edges, because an unmeasured edge would be a claim
without a key.

Input : register.tsv  (worker, finding, repo, commit, path, line_start, line_end, title, pattern, verified)
Output: belt/belt.json  {name, source, law, counts, stations:[[x,y,key,copies]], edges:[]} as the wafer reads it
        belt/bodies.json one record per body, key beside the human fields
        belt/rules.txt   every constant used
        proof/<run-id>-belt.json  SHA-256 of every output, counts, the exact command line

The key of a body is the git blob SHA of the file at the commit, joined with the line number:
"<blob-sha>:<line>". It is resolved with `git rev-parse <commit>:<path>` in the local clone named
by --roots. A finding whose blob cannot be resolved is not placed; it is counted as `unresolved`.
"""
import argparse, csv, hashlib, json, math, os, subprocess, sys, datetime

# The shipped law (kuiper-belt index.html:250, learn-the-kuiper/*/kuiper-law.js, maths/10): the angle is
# the exact 32-bit odometer, theta = 2*pi * ((k * 2654435769) mod 2**32) / 2**32, which turns +222.492236
# degrees per key (0.6180339887 of a turn). estate.py turns the mirror +137.5 as a float; this edition
# follows the live wafer, and prints which in rules.txt.
ESTATE_A_MIN, ESTATE_A_MAX = 0.16, 0.92   # kuiper-belt tools/estate.py:20 A_MIN, A_MAX
MULT = 2654435769                       # floor(2**32 / phi), hex 9E3779B9, Knuth TAOCP vol 3 s6.4
TWO32 = 2 ** 32
# Centred on zero, as estate.py:159-163 measured from the live files ("the renderer multiplies straight
# through with no centring"; SPEC.md's "unit square" was inferred from prose and was wrong). The annulus
# is estate.py's, so this belt draws at the same scale as the estate belt.
A_MIN, A_MAX = ESTATE_A_MIN, ESTATE_A_MAX

def sh(cmd, cwd=None):
    return subprocess.run(cmd, cwd=cwd, capture_output=True, text=True)

def blob_sha(roots, repo, commit, path):
    for root in roots:
        clone = os.path.join(root, repo)
        if os.path.isdir(os.path.join(clone, ".git")):
            r = sh(["git", "-C", clone, "rev-parse", "--verify", "-q", f"{commit}:{path}"])
            if r.returncode == 0:
                return r.stdout.strip(), clone
            return None, clone
    return None, None

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--register", required=True)
    ap.add_argument("--roots", required=True, help="comma separated clone roots")
    ap.add_argument("--out", required=True, help="edition folder")
    ap.add_argument("--run-id", required=True)
    ap.add_argument("--asof", default=None)
    args = ap.parse_args()
    asof = args.asof or datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds")
    roots = args.roots.split(",")
    rows = list(csv.DictReader(open(args.register, newline=""), delimiter="\t"))
    bodies, unresolved, skipped = [], [], 0
    for row in rows:
        if row.get("verified", "").strip().upper() not in ("CONFIRMED", "VERIFIED", "PASS"):
            skipped += 1
            continue
        repo, commit, path = row["repo"].strip(), row["commit"].strip(), row["path"].strip()
        try:
            line = int(str(row["line_start"]).strip())
        except ValueError:
            unresolved.append({**row, "reason": "line not an integer"}); continue
        b, clone = blob_sha(roots, repo, commit, path)
        if not b:
            unresolved.append({**row, "reason": "blob not resolvable in clone" if clone else "clone not found"}); continue
        key = f"{b}:{line}"
        bodies.append({
            "id": key, "blob": b, "line": line, "repo": repo, "commit": commit, "path": path,
            "line_end": row.get("line_end", "").strip() or str(line),
            "title": row.get("title", "").strip(), "pattern": row.get("pattern", "").strip(),
            "worker": row.get("worker", "").strip(), "finding": row.get("finding", "").strip(),
            "quote": row.get("quote", "").strip()[:160],
            "class": row.get("cls", "").strip() or ("focus" if repo in ("gridatlas", "data-grid-gb", "data-centres-gb") else "estate"),
            "destination": f"https://github.com/Ventusltd/{repo}/blob/{commit}/{path}#L{line}",
            "open": True,
        })
    # one body per key: a line cited twice is one body
    seen, uniq = set(), []
    for b in bodies:
        if b["id"] in seen: continue
        seen.add(b["id"]); uniq.append(b)
    uniq.sort(key=lambda b: b["id"])
    n = len(uniq)
    stations = []
    for k, b in enumerate(uniq):
        r = A_MIN + (A_MAX - A_MIN) * math.sqrt((k + 0.5) / n)
        th = 2 * math.pi * ((k * MULT) % TWO32) / TWO32
        x, y = round(r * math.cos(th), 6), round(r * math.sin(th), 6)
        b["k"], b["x"], b["y"], b["r"], b["theta"] = k, x, y, round(r, 6), round(th % (2 * math.pi), 6)
        # The renderer's contract (estate.py:167-168, pilot.mjs:285-288): stations are [x, y, key(, copies)].
        stations.append([x, y, b["id"], 1])
    belt = {
        "name": f"kuiper-edition-{args.run_id}",
        "source": "verified keyed findings of the swarm; key = git blob SHA of the file at the cited commit, joined with the line",
        "attribution": "content identifiers issued by git; quotes are the estate's own lines",
        "law": "one body per key; r = a_min + (a_max - a_min) * sqrt((k + 0.5) / n) with k the body ordinal among sorted keys; theta = 2*pi*((k*2654435769) mod 2^32)/2^32, the live wafer's 32-bit odometer, +222.492236 degrees per key; class is a property and never a position; no edges, because an unmeasured edge would be a claim without a key",
        "asof": asof,
        "counts": {"register_rows": len(rows), "not_verified_skipped": skipped, "unresolved": len(unresolved), "bodies": n,
                   "dim": 0, "focus": sum(1 for b in uniq if b["class"] == "focus")},
        "stations": stations, "edges": [],
    }
    os.makedirs(os.path.join(args.out, "belt"), exist_ok=True)
    os.makedirs(os.path.join(args.out, "proof"), exist_ok=True)
    outs = {}
    def write(rel, text):
        p = os.path.join(args.out, rel); open(p, "w").write(text); outs[rel] = hashlib.sha256(text.encode()).hexdigest()
    write("belt/belt.json", json.dumps(belt, separators=(",", ":")))
    write("belt/bodies.json", json.dumps(uniq, indent=0))
    write("belt/unresolved.json", json.dumps(unresolved, indent=1))
    git = sh(["git", "--version"]).stdout.strip()
    write("belt/rules.txt", "\n".join([
        f"asof {asof}", f"run-id {args.run_id}", f"a_min {A_MIN}", f"a_max {A_MAX}",
        f"theta_law 2*pi*((k*{MULT}) mod 2^32)/2^32  (+222.492236 deg per key; the mirror of estate.py's float +137.507764)", "radius_law sqrt((k+0.5)/n) scaled to the annulus",
        "order sorted key, key = <blob sha>:<line>", "frame centred on zero, as estate.py measured", "stations [x, y, key, copies]", "edges none (unmeasured)", f"n {n}", f"git {git}",
        "command " + " ".join(sys.argv), ""]))
    proof = {"run_id": args.run_id, "asof": asof, "sha256": outs, "counts": belt["counts"], "command": " ".join(sys.argv)}
    open(os.path.join(args.out, "proof", f"{args.run_id}-belt.json"), "w").write(json.dumps(proof, indent=1))
    print(json.dumps(belt["counts"]))
    print(json.dumps(outs, indent=1))

if __name__ == "__main__":
    main()