GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / energy-transition-simulator / tests

Iterations — 43 Registry Growth and 5 more files

A JavaScript module in Galaxies Wafers using data from GitHub API. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/43-registry-growth/. It fetches queue (`FetchQueue`), fetches once (`fetchOnce`) and paints machine (`paintMachine`).

700 lines of JavaScript from energy-transition-simulator, galaxies-wafers, in 6 files. Topic: Electricity markets and data pipelines. Section 768 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. UI test · energy-transition-simulator / tests/ui.cjs lines 1–161
  2. Iterations — 15 Price Spread interaction · galaxies-wafers / iterations/15-price-spread/app.mjs lines 1–37
  3. Browser Check render · galaxies-wafers / iterations/15-price-spread/browser-check.mjs lines 1–27
  4. Model ingest · galaxies-wafers / iterations/15-price-spread/model.mjs lines 1–21
  5. Model Test test · galaxies-wafers / iterations/15-price-spread/model.test.mjs lines 1–14
  6. Iterations — 43 Registry Growth render · galaxies-wafers / iterations/43-registry-growth/app.mjs lines 1–440

UI

A JavaScript module in the tests folder of Energy Transition Simulator that draws on a canvas.

testenergy-transition-simulator / tests/ui.cjs · lines 1–161 of 161 · Entry point · pattern modList (shared by 3 files)

What it does
It tests its inputs. Defines 6 functions or classes, including modList, launch, BLUE_SCAN, ready, state. Uses libraries http, fs, path, playwright. Side effects: changes the web page (DOM); reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (voltage levels 400kV (all 132kV or above)): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: 400kV.
Inputs & outputs
In: JSON file index.json; command-line arguments. Out: canvas drawing. Voltage levels named: 400kV.
Downstream impact
Used directly by 1 file: Overlay Workflow (energy-transition-simulator).
What it achieves
It is built from the mod list helper (`modList`), the launch step (`launch`) and the ready step (`ready`). UI check for the menu bar, the site-world tokens and the wire look (`mod/menu-style.js`, `menu-bar.js`, `wire-look.js`). Its code works with 400 kV.
Why it matters
Run by Overlay Workflow.
Application
energy-transition-simulator · tests · JavaScript module
Uses
http, fs, path, playwright
Used by
run by Overlay Workflow (workflow run)
Produces
modList, launch, BLUE_SCAN, ready, state, band
Defines here
modList, launch, BLUE_SCAN, ready, state, band
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a tests/ui.cjs:1-161 · blob dcf1f85a83f943eeca0aec7042bcf0f98bf4874d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
// UI check for the menu bar, the site-world tokens and the wire look (mod/menu-style.js, menu-bar.js, wire-look.js).
// Serves prototype/ on a local port. mod/index.json is NOT edited: the server answers it with the shipped list plus the
// UI mods for the chosen stage, so the check runs whether or not the captain has switched them on.
//   node tests/ui.cjs [stage] [outDir]     stage: before | style | menu | wire (default wire)
// Env: UI_LAT, UI_LON (start point; default a 400 kV line), UI_LAUNCHER (a module exporting launch(); default playwright
// Chrome with ANGLE d3d11). Every check prints PASS or FAIL with evidence; exit code 1 on any FAIL.
const http = require('http'), fs = require('fs'), path = require('path');
const ROOT = path.join(__dirname, '..', 'prototype');
const STAGE = process.argv[2] || 'wire', OUT = process.argv[3] || path.join(__dirname, '..', 'test-output', 'ui');
const LAT = process.env.UI_LAT || '52.2441634', LON = process.env.UI_LON || '-1.0453368';
const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript', '.json': 'application/json' };
fs.mkdirSync(OUT, { recursive: true });
function modList() {
  const shipped = JSON.parse(fs.readFileSync(path.join(ROOT, 'mod', 'index.json'), 'utf8')).filter(n => !/^(menu-style|menu-bar|wire-look)$/.test(n));
  if (STAGE === 'before') return shipped;
  const list = ['menu-style', ...shipped];
  if (STAGE === 'menu' || STAGE === 'wire') { if (!list.includes('gpu-rows')) list.push('gpu-rows'); }   // all 22 controls
  if (STAGE === 'wire') list.push('wire-look');
  if (STAGE === 'menu' || STAGE === 'wire') list.push('menu-bar');
  return list;
}
const server = http.createServer((q, s) => {
  const u = decodeURIComponent(q.url.split('?')[0]).replace(/^\/+/, '') || 'overlay.html';
  if (u === 'mod/index.json') { s.writeHead(200, { 'Content-Type': 'application/json' }); return s.end(JSON.stringify(modList())); }
  const f = path.join(ROOT, u);
  if (!f.startsWith(ROOT) || !fs.existsSync(f) || fs.statSync(f).isDirectory()) { s.writeHead(404); return s.end(); }
  s.writeHead(200, { 'Content-Type': TYPES[path.extname(f)] || 'application/octet-stream' }); fs.createReadStream(f).pipe(s);
});
const results = []; const check = (name, ok, evidence) => { results.push({ name, ok: !!ok }); console.log(`${ok ? 'PASS' : 'FAIL'} ${name} :: ${String(evidence).slice(0, 300)}`); };
async function launch() {
  if (process.env.UI_LAUNCHER) return require(process.env.UI_LAUNCHER).launch();
  const { chromium } = require('playwright');
  return chromium.launch({ channel: process.env.CI ? undefined : 'chrome', args: process.env.CI ? ['--use-angle=swiftshader', '--enable-unsafe-swiftshader'] : ['--use-angle=d3d11', '--enable-gpu', '--ignore-gpu-blocklist'] });
}
// Filled blue anywhere in the page chrome: a background whose blue beats red by 80+ and is not the pale line colour.
const BLUE_SCAN = () => {
  const bad = [];
  for (const el of document.querySelectorAll('body *')) {
    if (el.closest('.maplibregl-canvas-container') || el.tagName === 'CANVAS') continue;
    const cs = getComputedStyle(el); if (cs.display === 'none' || cs.visibility === 'hidden') continue;
    const r = el.getBoundingClientRect(); if (!r.width || !r.height) continue;
    const m = cs.backgroundColor.match(/rgba?\(([\d.]+),\s*([\d.]+),\s*([\d.]+)(?:,\s*([\d.]+))?/); if (!m) continue;
    const [R, G, B, A] = [+m[1], +m[2], +m[3], m[4] === undefined ? 1 : +m[4]];
    if (A > 0.3 && B - R > 80 && B > 120 && R < 120) bad.push((el.id || el.tagName) + ' ' + cs.backgroundColor);
  }
  return bad;
};
async function ready(p) {
  await p.waitForFunction(() => window.SIM && document.querySelector('canvas.maplibregl-canvas'), null, { timeout: 30000 });
  await p.waitForTimeout(7000);
}
(async () => {
  await new Promise(r => server.listen(0, '127.0.0.1', r));
  const base = `http://127.0.0.1:${server.address().port}/overlay.html?lat=${LAT}&lon=${LON}`;
  const b = await launch();
  const errs = [];
  // ---- desktop 1920 ----
  const p = await b.newPage({ viewport: { width: 1920, height: 1080 } }); p.on('pageerror', e => errs.push(e.message));
  await p.goto(base, { waitUntil: 'load' }); await ready(p);
  check('window.SIM and the map canvas', await p.evaluate(() => !!window.SIM && !!document.querySelector('canvas.maplibregl-canvas')), 'SIM + canvas');
  await p.screenshot({ path: path.join(OUT, `${STAGE}-1920.png`) });
  if (STAGE !== 'before') {
    const blue = await p.evaluate(BLUE_SCAN); check('no blue filled controls (1920)', blue.length === 0, blue.join(' | ') || 'none');
    check('#bar hidden', await p.evaluate(() => getComputedStyle(document.getElementById('bar')).display === 'none'), 'display none');
  }
  if (STAGE === 'menu' || STAGE === 'wire') {
    await p.waitForTimeout(3000);
    const ctl = await p.evaluate(() => window.SIM.menu ? window.SIM.menu.controls() : []);
    const ok = ctl.filter(c => c.found && c.inMenu);
    check('22 controls found, each inside its menu', ok.length === 22, `${ok.length}/22 ` + ctl.filter(c => !c.inMenu).map(c => c.key).join(',') + ' | ' + ctl.map(c => c.menu[0] + ':' + c.label).join(', '));
    // One panel at a time; Escape closes; an outside click closes; Controls opens the help.
    const titles = await p.evaluate(() => window.SIM.menu.titles);
    let one = true, seen = [];
    for (const t of titles) {
      await p.click(`#sim-menu .gm-title[data-menu="${t}"]`); await p.waitForTimeout(120);
      const n = await p.evaluate(() => Array.from(document.querySelectorAll('.gm-panel')).filter(x => !x.hidden).map(x => x.dataset.menu));
      seen.push(t + '=' + n.join('+')); if (n.length !== 1 || n[0] !== t) one = false;
    }
    check('one panel open at a time', one, seen.join(' '));
    await p.keyboard.press('Escape'); await p.waitForTimeout(100);
    check('Escape closes', await p.evaluate(() => window.SIM.menu.openName() === ''), 'open: none');
    await p.click('#sim-menu .gm-title[data-menu="Grid"]'); await p.mouse.click(960, 600); await p.waitForTimeout(100);
    check('outside click closes', await p.evaluate(() => window.SIM.menu.openName() === ''), 'open: none');
    await p.click('#help-toggle'); await p.waitForTimeout(100);
    const help = await p.evaluate(() => ({ open: window.SIM.menu.openName(), text: (document.querySelector('#help #info') || {}).textContent || '' }));
    check('Controls opens the help', help.open === 'Help' && help.text.length > 40, help.open + ' ' + help.text.slice(0, 60));
    await p.keyboard.press('Escape');
    const where = await p.textContent('#where'); check('#where shows the grid reference line', /^[A-Z]{2} \d{4} \d{4} · -?\d+\.\d{6}, -?\d+\.\d{6}/.test(where), where);
    const attr = await p.textContent('#attribution'); check('attribution strip filled', attr.length > 20, attr);
    // Click every control from its menu and record what changed.
    const state = () => p.evaluate(() => ({ blocks: window.SIM.blocks.length, pitch: Math.round(window.SIM.map.getPitch()), zoom: +window.SIM.map.getZoom().toFixed(2),
      layers: (window.SIM.map.getStyle().layers || []).length, c: window.SIM.map.getCenter().lng.toFixed(5) }));
    const clicked = [];
    for (const c of ctl) {
      await p.evaluate(m => window.SIM.menu.open(m), c.menu); await p.waitForTimeout(100);
      const vis = await p.evaluate(k => { const e = window.SIM.menu.element(k); const r = e && e.getBoundingClientRect(); return !!(r && r.width && r.height); }, c.key);
      const s0 = await state(), l0 = await p.evaluate(k => { const e = window.SIM.menu.element(k); return (e.textContent || '').trim() + (e.classList.contains('on') ? '[on]' : ''); }, c.key);
      let how = 'click';
      if (c.key === 'sub-input') { await p.evaluate(k => window.SIM.menu.element(k).focus(), c.key); await p.keyboard.type('go substation 400'); await p.keyboard.press('Enter'); how = 'typed'; }
      else await p.evaluate(k => window.SIM.menu.element(k).click(), c.key);
      await p.waitForTimeout(c.key === 'sat' || c.key === 'dark' || c.key === 'wire' ? 1500 : 900);
      const s1 = await state(), l1 = await p.evaluate(k => { const e = window.SIM.menu.element(k); return (e.textContent || '').trim() + (e.classList.contains('on') ? '[on]' : ''); }, c.key);
      if (c.key === 'fps') { await p.evaluate(() => window.SIM.menu.element('fps').click()); await p.waitForTimeout(300); }   // back out of first person
      const diff = Object.keys(s0).filter(k => s0[k] !== s1[k]).map(k => `${k} ${s0[k]}->${s1[k]}`);
      const changed = l0 !== l1 || diff.length > 0;
      clicked.push({ key: c.key, vis, changed, how, label: `${l0} -> ${l1}`, diff: diff.join(', ') });
    }
    fs.writeFileSync(path.join(OUT, `${STAGE}-clicks.json`), JSON.stringify(clicked, null, 1));
    const reach = clicked.filter(x => x.vis), eff = clicked.filter(x => x.changed);
    check('every control reachable (visible when its menu is open)', reach.length === 22, `${reach.length}/22 ` + clicked.filter(x => !x.vis).map(x => x.key).join(','));
    check('every control shows an effect or label change', eff.length >= 20, `${eff.length}/22; none: ` + clicked.filter(x => !x.changed).map(x => x.key).join(','));
    await p.evaluate(() => window.SIM.menu.close());
    await p.screenshot({ path: path.join(OUT, `${STAGE}-1920-after-clicks.png`) });
  }
  // The two views the owner looks at, for every stage (before and after): the farm by drone, and walking in Wire.
  await p.goto(base, { waitUntil: 'load' }); await ready(p);
  await p.evaluate(() => document.getElementById('drone').click()); await p.waitForTimeout(4000);
  await p.screenshot({ path: path.join(OUT, `${STAGE}-drone-1920.png`) });
  await p.evaluate(() => { document.getElementById('wire').click(); }); await p.waitForTimeout(1500);
  await p.evaluate(() => { const b = document.getElementById('pylons'); if (!b.classList.contains('on')) b.click(); document.getElementById('walk').click(); });
  await p.waitForTimeout(7000);
  await p.screenshot({ path: path.join(OUT, `${STAGE}-walk-wire-1920.png`) });
  if (STAGE === 'wire') {
    const wl = await p.evaluate(() => window.SIM.wireLook ? window.SIM.wireLook.stats() : null);
    check('wire look active with a fade distance', wl && wl.fadeM > 0 && wl.frames > 0 && !wl.err, JSON.stringify(wl));
    check('1 m grid drawn within 30 m', wl && wl.gridOn && wl.minorSegments > 0 && wl.minorRadiusM <= 30, wl && `${wl.minorSegments} minor, ${wl.majorSegments} major segments, radius ${wl.minorRadiusM} m`);
    // The fade, measured: the band just under the horizon with the fade off (1e7 m) against on (the default).
    const band = async () => {
      const png = (await p.screenshot({ clip: { x: 0, y: 324, width: 1920, height: 130 } })).toString('base64');
      return p.evaluate(async b64 => {
        const img = await new Promise(r => { const i = new Image(); i.onload = () => r(i); i.src = 'data:image/png;base64,' + b64; });
        const cv = document.createElement('canvas'); cv.width = img.width; cv.height = img.height; const g = cv.getContext('2d'); g.drawImage(img, 0, 0);
        const d = g.getImageData(0, 0, img.width, img.height).data; let s = 0;
        for (let i = 0; i < d.length; i += 4) s += d[i] + d[i + 1] + d[i + 2]; return +(s / (d.length / 4) / 3).toFixed(2);
      }, png);
    };
    await p.evaluate(() => window.SIM.wireLook.set({ fadeM: 1e7 })); await p.waitForTimeout(800); const off = await band();
    await p.screenshot({ path: path.join(OUT, `${STAGE}-walk-wire-nofade-1920.png`) });
    await p.evaluate(() => window.SIM.wireLook.set({ fadeM: 0 })); await p.waitForTimeout(800); const onF = await band();
    const lum = { far_band_no_fade: off, far_band_fade: onF };
    check('far lines fade (band under the horizon darker with the fade on)', onF < off * 0.8, JSON.stringify(lum));
  }
  // ---- phone 390 ----
  const q = await b.newPage({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true, deviceScaleFactor: 2 }); q.on('pageerror', e => errs.push(e.message));
  await q.goto(base, { waitUntil: 'load' }); await ready(q);
  await q.screenshot({ path: path.join(OUT, `${STAGE}-390.png`) });
  if (STAGE !== 'before') {
    const blue = await q.evaluate(BLUE_SCAN); check('no blue filled controls (390)', blue.length === 0, blue.join(' | ') || 'none');
    const over = await q.evaluate(() => document.documentElement.scrollWidth <= innerWidth); check('no sideways scroll at 390', over, 'scrollWidth');
  }
  if (STAGE === 'menu' || STAGE === 'wire') {
    const fit = await q.evaluate(() => { const r = document.querySelector('#sim-menu .gm-views').getBoundingClientRect(); return r.right <= innerWidth + 0.5; });
    check('menu bar fits 390 px', fit, 'views end inside the screen');
    await q.tap('#sim-menu .gm-title[data-menu="Scope"]'); await q.waitForTimeout(200);
    await q.screenshot({ path: path.join(OUT, `${STAGE}-390-scope.png`) });
  }
  check('no page errors', errs.length === 0, errs.slice(0, 3).join(' | ') || 'none');
  await b.close(); server.close();
  const bad = results.filter(r => !r.ok).length; console.log(`${results.length - bad}/${results.length} PASS (${STAGE})`);
  process.exit(bad ? 1 : 0);
})().catch(e => { console.error(e); process.exit(1); });

Iterations — 15 Price Spread

A JavaScript module in Galaxies Wafers that draws spread calculation, using SHA-256. It is built from the draw step (`draw`) and the refresh step (`refresh`).

interactiongalaxies-wafers / iterations/15-price-spread/app.mjs · lines 1–37 of 37 · Not reached from any entry point (candidate for review)

What it does
It draws spread calculation. Defines $, draw, refresh. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage hv_procurement (path word 'price'): HV materials procurement, which Ventus Ltd states is within its commercial execution boundary. README: "The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/202609151339."
Inputs & outputs
Out: JSON file spread-calculation.json; downloaded file spread-calculation.json.
What it achieves
The README says: The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/. It responds to submit, input and click events.
Why it matters
No other file in the estate was found to import it.
Application
galaxies-wafers · iterations/15-price-spread · JavaScript module
Uses
none found
Used by
none found
Produces
$, draw, refresh
Defines here
$, draw, refresh
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/15-price-spread/app.mjs:1-37 · blob 82dc3d1ac3249fc2372f59cb58347707dfc68ec6 · GitHub at these lines
State
achieves: readme · context: readme_derived · stage: output · effects: dom · domain stage: hv_procurement · users: EPC_contractor, procurement_buyer · canonical: unreached_review
import{SOURCE,URL,FIELDS,parse,calculate}from'./model.mjs';
const $=id=>document.getElementById(id),fmt=n=>n!==0 && Math.abs(n)<.000001?n.toExponential(4):n.toLocaleString('en-GB',{maximumFractionDigits:3});
let engine,current;
$('code').href=`https://github.com/${SOURCE.repository}/blob/${SOURCE.commit}/${SOURCE.file}`;$('proof').href=`https://github.com/${SOURCE.repository}/blob/${SOURCE.commit}/proofs/interconnector-economics.proof.mjs`;
$('provenance').textContent=`${SOURCE.repository} / ${SOURCE.commit} / ${SOURCE.file}\nSHA256 ${SOURCE.sha256}`;
const NS='http://www.w3.org/2000/svg';function svg(tag,attrs){const e=document.createElementNS(NS,tag);for(const[k,v]of Object.entries(attrs))e.setAttribute(k,String(v));$('curve').append(e);return e;}
function draw(){
  $('curve').replaceChildren();$('rows').replaceChildren();if(!current?.rent)return;
  const max=current.series.at(-1).grossGbp,x=u=>50+(u-.1)/.9*435,y=value=>225-value/max*190;
  svg('path',{d:'M50 25 V225 H490',class:'axis'});
  for(const[px,py,label]of[[50,255,'0.1'],[243,255,'0.5'],[485,255,'1.0'],[50,19,`GBP ${fmt(max)}`]]){const e=svg('text',{x:px,y:py});e.textContent=label;}
  svg('polyline',{points:current.series.map(p=>`${x(p.utilisation)},${y(p.grossGbp)}`).join(' '),class:'curve',pathLength:1});
  for(const point of current.series){svg('circle',{cx:x(point.utilisation),cy:y(point.grossGbp),r:3,class:'point'});const tr=document.createElement('tr');for(const value of [fmt(point.utilisation),fmt(point.grossGbp)]){const td=document.createElement('td');td.textContent=value;tr.append(td);}$('rows').append(tr);}
  if(current.inputs.utilisation>=.1)svg('circle',{cx:x(current.inputs.utilisation),cy:y(current.rent.value),r:6,class:'selected'});
}
function refresh(){
  current=null;$('download').disabled=true;$('error').hidden=true;
  if(!engine)return;
  try{
    current=calculate(engine,Object.fromEntries(FIELDS.map(id=>[id,parse($(id).value)])));
    $('energy').textContent=fmt(current.energy.value);$('gross').textContent=current.rent?`£${fmt(current.rent.value)}`:'Not computed';
    $('direction').textContent=`Commercial incentive: ${current.direction.direction}`;
    $('spread').textContent=`Signed GB-minus-neighbour spread: ${fmt(current.direction.signedSpreadGbpPerMwh)} GBP/MWh. Absolute spread: ${fmt(current.direction.spreadGbpPerMwh)} GBP/MWh.`;
    $('quick').textContent=`${fmt(current.energy.value)} GWh · ${current.rent?`£${fmt(current.rent.value)} gross, not profit`:'gross value refused at zero spread'}`;
    $('refusal').hidden=!current.refusal;$('refusal').textContent=current.refusal?`${current.refusal.function} REFUSED · ${current.refusal.name}: ${current.refusal.message}`:'';
    $('chart').hidden=!current.rent;$('result').hidden=false;$('record').textContent=JSON.stringify(current,null,2);$('download').disabled=false;$('status').textContent=current.refusal?'Partial result: energy and incentive only; gross-value refusal retained.':'Calculated by the pinned module under the stated assumptions.';draw();
  }catch(error){current=null;$('result').hidden=true;$('quick').textContent='Input refused; previous result cleared.';$('status').textContent='No current calculation.';$('error').hidden=false;$('error').textContent=`${error.name}: ${error.message}`;$('record').textContent='No current result.';$('curve').replaceChildren();$('rows').replaceChildren();}
}
$('controls').addEventListener('submit',event=>{event.preventDefault();refresh();});$('controls').addEventListener('input',refresh);
$('swap').addEventListener('click',()=>{const value=$('gbPriceGbpPerMwh').value;$('gbPriceGbpPerMwh').value=$('neighbourPriceGbpPerMwh').value;$('neighbourPriceGbpPerMwh').value=value;refresh();});
for(const[id,reason]of Object.entries({wafer:'No numbered line established for this element: the pinned module has not been matched to an issued line and manifest layer in this lab.',application:'No registered application URL established for this calculation. The lab does not invent a register entry.',tools:'No manifest layer established for this calculation. A tool handoff requires a verified lay  … [line shortened here: 489 characters; full line on GitHub]
$('download').addEventListener('click',()=>{if(!current)return;const blob=globalThis.URL.createObjectURL(new Blob([JSON.stringify(current,null,2)+'\n'],{type:'application/json'}));const a=document.createElement('a');a.href=blob;a.download='spread-calculation.json';a.click();setTimeout(()=>globalThis.URL.revokeObjectURL(blob),1000);});
try{engine=await import(URL);refresh();}catch(error){$('quick').textContent='Calculation module unavailable.';$('status').textContent='No substitute calculation.';$('error').hidden=false;$('error').textContent=error.message;}
if(document.modelContext?.registerTool){const lifecycle=new AbortController();addEventListener('pagehide',()=>lifecycle.abort(),{once:true});const register=tool=>{try{Promise.resolve(document.modelContext.registerTool(tool,{signal:lifecycle.signal})).catch(()=>{});}catch{}};
  register({name:'read_spread_calculation',description:'Read this synthetic price-spread result without changing state.',inputSchema:{type:'object',properties:{},additionalProperties:false},annotations:{readOnlyHint:true,untrustedContentHint:false},execute(input){if(!input || typeof input!=='object' || Array.isArray(input) || Object.keys(input).length)throw new TypeError('Expected empty object');r  … [line shortened here: 503 characters; full line on GitHub]
  register({name:'configure_spread_calculation',description:'Set synthetic assumptions and run the visible calculation; no price forecast, dispatch or financial transaction.',inputSchema:{type:'object',properties:Object.fromEntries(FIELDS.map(key=>[key,{type:'number'}])),required:FIELDS,additionalProperties:false},annotations:{readOnlyHint:false,untrustedContentHint:false},execute(input){if(!engin  … [line shortened here: 843 characters; full line on GitHub]
}

Browser Check

A JavaScript module in the iterations folder of Galaxies Wafers that uses SHA-256.

rendergalaxies-wafers / iterations/15-price-spread/browser-check.mjs · lines 1–27 of 27 · Not reached from any entry point (candidate for review)

What it does
It draws its content. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes.
Why it exists in the grid workflow
Domain stage hv_procurement (path word 'price'): HV materials procurement, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
Out: JSON file receipt.json.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
No other file in the estate was found to import it.
Application
galaxies-wafers · iterations/15-price-spread · JavaScript module
Uses
Model (script call)
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
galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/15-price-spread/browser-check.mjs:1-27 · blob 08a01bbdd412b0cc85297e0fcc1fc24e7c10b189 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, network, process · domain stage: hv_procurement · users: EPC_contractor, procurement_buyer · canonical: unreached_review
import{spawn}from'node:child_process';import{mkdir,writeFile,readFile}from'node:fs/promises';import path from'node:path';import{createHash}from'node:crypto';import assert from'node:assert/strict';import{SOURCE,URL as MODULE_URL}from'./model.mjs';
const playwright=await import(process.env.PLAYWRIGHT_MODULE || 'playwright');const output=process.env.PROOF_OUTPUT || path.resolve('browser-evidence');await mkdir(output,{recursive:true});const url=process.env.PAGE_URL || 'http://127.0.0.1:8779/';const server=process.env.PAGE_URL?null:spawn(process.platform==='win32'?'python':'python3',['-m','http.server','8779','--bind','127.0.0.1'],{stdio:'ignor  … [line shortened here: 422 characters; full line on GitHub]
try{
  for(let n=0;n<30;n++){try{if((await fetch(url)).ok)break;}catch{}if(n===29)throw Error('Preview unavailable');await new Promise(r=>setTimeout(r,100));}
  for(const name of(process.env.BROWSER_ENGINES || 'chromium,webkit').split(',')){
    const browser=await playwright[name].launch({headless:true,...(name==='chromium' && process.env.CHROME_PATH?{executablePath:process.env.CHROME_PATH}:{})});
    try{for(const width of[390,1400]){
      const context=await browser.newContext({viewport:{width,height:width===390?844:900},deviceScaleFactor:width===390?3:1,isMobile:width===390,hasTouch:width===390,acceptDownloads:true});const page=await context.newPage();page.setDefaultTimeout(12000);const errors=[],failed=[],responses=[];let negative=false;const receipt={engine:name,version:browser.version(),width,dpr:width===390?3:1,started:n  … [line shortened here: 466 characters; full line on GitHub]
      page.on('pageerror',e=>{if(!negative)errors.push(e.message);});page.on('console',m=>{if(!negative && m.type()==='error')errors.push(m.text());});page.on('requestfailed',r=>{if(!negative)failed.push(r.url());});page.on('response',r=>{if(negative)return;if(r.status()>=400)failed.push(r.url());if(r.url()===MODULE_URL)responses.push(r.body().then(bytes=>({status:r.status(),sha256:createHash('sha  … [line shortened here: 441 characters; full line on GitHub]
      try{
        await page.goto(url);await page.waitForFunction(()=>document.querySelector('#gross').textContent==='£30,000');assert.equal(await page.locator('#energy').innerText(),'1');assert.match(await page.locator('#direction').innerText(),/import to GB/);
        await page.waitForFunction(()=>parseFloat(getComputedStyle(document.querySelector('.curve')).strokeDashoffset)===0);assert.equal(await page.locator('.axis').evaluate(e=>getComputedStyle(e).fill),'none');await page.screenshot({path:path.join(output,`${name}-${width}-spread.png`),fullPage:true});
        await page.locator('#swap').click();assert.match(await page.locator('#direction').innerText(),/export from GB/);assert.equal(await page.locator('#gross').innerText(),'£30,000');
        await page.locator('#gbPriceGbpPerMwh').fill('90');assert.equal(await page.locator('#gross').innerText(),'Not computed');assert.match(await page.locator('#refusal').innerText(),/greater than zero/);assert.equal(await page.locator('#chart').isVisible(),false);
        await page.locator('#gbPriceGbpPerMwh').fill('-15');assert.match(await page.locator('#direction').innerText(),/export from GB/);await page.locator('#utilisation').fill('0');assert.equal(await page.locator('#result').isVisible(),false);assert.equal(await page.locator('#download').isDisabled(),true);
        await page.locator('#utilisation').fill('');assert.match(await page.locator('#error').innerText(),/finite number/);await page.locator('#utilisation').fill('.5');await page.locator('#gbPriceGbpPerMwh').fill('90');await page.locator('#neighbourPriceGbpPerMwh').fill('60');await page.locator('#run').click();assert.equal(await page.locator('#gross').innerText(),'£15,000');
        await page.locator('#wafer').click();assert.match(await page.locator('#handoff').innerText(),/No numbered line established/);await page.locator('#application').click();assert.match(await page.locator('#handoff').innerText(),/No registered application URL/);await page.locator('#tools').click();assert.match(await page.locator('#handoff').innerText(),/No manifest layer/);
        assert.equal(await page.locator('#code').getAttribute('href'),`https://github.com/${SOURCE.repository}/blob/${SOURCE.commit}/${SOURCE.file}`);
        await page.getByText('Machine detail',{exact:true}).click();assert.equal(await page.locator('#rows tr').count(),10);const promise=page.waitForEvent('download');await page.locator('#download').click();const download=await promise;const filename=path.join(output,`${name}-${width}-record.json`);await download.saveAs(filename);const record=JSON.parse(await readFile(filename,'utf8'));assert.equ  … [line shortened here: 477 characters; full line on GitHub]
        await page.emulateMedia({reducedMotion:'reduce'});assert.equal(await page.locator('.curve').evaluate(e=>getComputedStyle(e).animationName),'none');receipt.overflow=await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+1);assert.equal(receipt.overflow,false);await page.screenshot({path:path.join(output,`${name}-${width}-details.png`),fullPage:true});
        receipt.source_responses=await Promise.all(responses);assert.ok(receipt.source_responses.length);for(const r of receipt.source_responses){assert.equal(r.status,200);assert.equal(r.sha256,SOURCE.sha256);}assert.deepEqual(errors,[]);assert.deepEqual(failed,[]);
        negative=true;await page.route(MODULE_URL,r=>r.abort('failed'));await page.reload();await page.waitForFunction(()=>document.querySelector('#quick').textContent.includes('module unavailable'));assert.equal(await page.locator('#result').isVisible(),false);assert.equal(await page.locator('#download').isDisabled(),true);receipt.module_unavailable_refused=true;receipt.native_webmcp='Not exercis  … [line shortened here: 453 characters; full line on GitHub]
      }catch(error){receipt.pass=false;receipt.error=error.stack;}finally{receipt.finished=new Date().toISOString();results.push(receipt);await context.close();}
    }}finally{await browser.close();}
  }
}finally{server?.kill();await writeFile(path.join(output,'receipt.json'),JSON.stringify({source_commit:process.env.GITHUB_SHA || null,url,results},null,2)+'\n');}
console.log(JSON.stringify({cases:results.length,passed:results.filter(r=>r.pass).length}));if(!results.length || results.some(r=>!r.pass))process.exitCode=1;

Model

A JavaScript module in the iterations folder of Galaxies Wafers that uses SHA-256.

ingestgalaxies-wafers / iterations/15-price-spread/model.mjs · lines 1–21 of 21 · Not reached from any entry point (candidate for review) · pattern compact (shared by 10 files)

What it does
Defines parse, calculate, compact.
Why it exists in the grid workflow
Domain stage hv_procurement (path word 'price'): HV materials procurement, which Ventus Ltd states is within its commercial execution boundary.
Downstream impact
Used directly by 1 file: Browser Check (galaxies-wafers).
What it achieves
Defines `parse`, `calculate` and `compact`. Its code works with 100 GW.
Why it matters
Run by Browser Check.
Application
galaxies-wafers · iterations/15-price-spread · JavaScript module
Uses
none found
Used by
run by Browser Check (script call)
Produces
PIN, SOURCE, URL, FIELDS, parse, calculate
Defines here
parse, calculate, compact
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/15-price-spread/model.mjs:1-21 · blob c4a98bcb7ea1891eb4bc3d21bc795e1ea38c3d34 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: hv_procurement · users: EPC_contractor, procurement_buyer · canonical: unreached_review
export const PIN='d9cd18b0e2034325814924e6e4a0e958014f2748';
export const SOURCE={repository:'Ventusltd/ventus-grid-engine',commit:PIN,file:'engine/interconnector-economics.js',sha256:'e6c4b9de5bc2bf6a8900ef776b3d5005ca358a3f73b38ba002205a37f7ca41f8'};
export const URL=`https://cdn.jsdelivr.net/gh/${SOURCE.repository}@${PIN}/${SOURCE.file}`;
export const FIELDS=['capacityGw','hours','utilisation','gbPriceGbpPerMwh','neighbourPriceGbpPerMwh'];
export const parse=text=>text.trim()===''?undefined:Number(text);
export function calculate(engine,input){
  if(input.capacityGw>100 || input.hours>8760 || Math.abs(input.gbPriceGbpPerMwh)>10000 || Math.abs(input.neighbourPriceGbpPerMwh)>10000)throw new RangeError('Interface policy: at most 100 GW, 8760 hours and absolute price 10000 GBP/MWh');
  const common={capacityGw:input.capacityGw,hours:input.hours,utilisation:input.utilisation};
  const direction=engine.flowDirection({gbPriceGbpPerMwh:input.gbPriceGbpPerMwh,neighbourPriceGbpPerMwh:input.neighbourPriceGbpPerMwh});
  const energy=engine.energyTransferredGwh(common);
  if(![energy.value,direction.spreadGbpPerMwh,direction.signedSpreadGbpPerMwh].every(Number.isFinite) || energy.value<=0)throw new RangeError('Interface policy: nonfinite or underflowed arithmetic refused');
  let rent=null,refusal=null,series=[];
  try{rent=engine.congestionRentGbp({...common,spreadGbpPerMwh:direction.spreadGbpPerMwh});}
  catch(error){if(direction.spreadGbpPerMwh!==0)throw error;refusal={function:'congestionRentGbp',name:error.name,message:error.message};}
  if(rent){
    if(!Number.isFinite(rent.value) || rent.value<=0)throw new RangeError('Interface policy: nonfinite or underflowed gross value refused');
    series=Array.from({length:10},(_,i)=>{const utilisation=(i+1)/10;const result=engine.congestionRentGbp({...common,utilisation,spreadGbpPerMwh:direction.spreadGbpPerMwh});if(!Number.isFinite(result.value) || result.value<=0)throw new RangeError('Interface policy: nonfinite or underflowed sensitivity point');return{utilisation,grossGbp:result.value};});
  }
  const compact=r=>r?{quantity:r.quantity,value:r.value,unit:r.unit,from:r.from}:null;
  return{schema:'galaxy-spread-lab.v1',source:SOURCE,fixture:'Synthetic caller-supplied prices, capacity, hours and utilisation; not a forecast or scheduled flow.',inputs:Object.fromEntries(FIELDS.map(key=>[key,input[key]])),direction:{direction:direction.direction,signedSpreadGbpPerMwh:direction.signedSpreadGbpPerMwh,spreadGbpPerMwh:direction.spreadGbpPerMwh,from:direction.from},energy:compact(en  … [line shortened here: 541 characters; full line on GitHub]
}

Model Test

A test in the iterations folder of Galaxies Wafers that uses SHA-256.

testgalaxies-wafers / iterations/15-price-spread/model.test.mjs · lines 1–14 of 14 · Not reached from any entry point (candidate for review)

What it does
It tests its inputs. Uses libraries node:test. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage hv_procurement (path word 'price'): HV materials procurement, which Ventus Ltd states is within its commercial execution boundary.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
No other file in the estate was found to import it.
Application
galaxies-wafers · iterations/15-price-spread · test
Uses
node:test
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
galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/15-price-spread/model.test.mjs:1-14 · blob f2b40842b639088ab36bedb6238de1486c83275b · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem, network · domain stage: hv_procurement · users: EPC_contractor, procurement_buyer · canonical: unreached_review
import test from'node:test';import assert from'node:assert/strict';import{createHash}from'node:crypto';import{readFile}from'node:fs/promises';import{SOURCE,URL,parse,calculate}from'./model.mjs';
const bytes=process.env.ENGINE_FILE?await readFile(process.env.ENGINE_FILE):await(async()=>{const r=await fetch(URL,{signal:AbortSignal.timeout(15000)});assert.equal(r.status,200);return Buffer.from(await r.arrayBuffer());})();assert.equal(createHash('sha256').update(bytes).digest('hex'),SOURCE.sha256);const engine=await import(`data:text/javascript;base64,${bytes.toString('base64')}`);
const base={capacityGw:1,hours:1,utilisation:1,gbPriceGbpPerMwh:90,neighbourPriceGbpPerMwh:60};const run=patch=>calculate(engine,{...base,...patch});
test('oneGWh at30GBP perMWh yields30000grossGBP',()=>{const r=run({});assert.equal(r.energy.value,1);assert.equal(r.energy.unit,'GWh');assert.equal(r.rent.value,30000);assert.equal(r.rent.unit,'GBP');assert.equal(r.direction.direction,'import to GB');});
test('swapping prices reverses incentive, not absolute spread',()=>{const r=run({gbPriceGbpPerMwh:60,neighbourPriceGbpPerMwh:90});assert.equal(r.direction.direction,'export from GB');assert.equal(r.direction.signedSpreadGbpPerMwh,-30);assert.equal(r.rent.value,30000);});
test('equal prices preserve partial result and exact zero-spread refusal',()=>{const r=run({gbPriceGbpPerMwh:60});assert.equal(r.direction.direction,'no commercial incentive');assert.equal(r.energy.value,1);assert.equal(r.rent,null);assert.deepEqual(r.series,[]);assert.match(r.refusal.message,/greater than zero/);});
test('negative stated prices are valid source inputs',()=>assert.equal(run({gbPriceGbpPerMwh:-15,neighbourPriceGbpPerMwh:40}).direction.signedSpreadGbpPerMwh,-55));
test('ten source-computed sensitivity values',()=>{const r=run({utilisation:.5});assert.equal(r.rent.value,15000);assert.equal(r.series.length,10);assert.equal(r.series[0].grossGbp,3000);assert.equal(r.series.at(-1).grossGbp,30000);});
test('zero capacity, hours and utilisation refused',()=>{for(const field of['capacityGw','hours','utilisation'])assert.throws(()=>run({[field]:0}),/greater than zero/);});
test('percentage-as-fraction refused',()=>assert.throws(()=>run({utilisation:70}),/fraction/));
test('blank remains missing',()=>{assert.equal(parse(' '),undefined);assert.throws(()=>run({hours:parse('')}),/finite number/);});
test('explicit interface bounds',()=>{assert.throws(()=>run({capacityGw:101}),/Interface policy/);assert.throws(()=>run({gbPriceGbpPerMwh:10001}),/Interface policy/);});
test('underflow removed instead of drawingNaNchart',()=>assert.throws(()=>run({capacityGw:Number.MIN_VALUE,hours:Number.MIN_VALUE}),/underflowed/));
test('result is finite serializable with exclusions',()=>{const r=run({});assert.deepEqual(JSON.parse(JSON.stringify(r)),r);assert.ok(r.notComputed.includes('profit'));assert.equal(r.source.sha256,SOURCE.sha256);});

Iterations — 43 Registry Growth

A JavaScript module in Galaxies Wafers using data from GitHub API. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/43-registry-growth/. It fetches queue (`FetchQueue`), fetches once (`fetchOnce`) and paints machine (`paintMachine`).

rendergalaxies-wafers / iterations/43-registry-growth/app.mjs · lines 1–440 of 555 · Entry point · pattern fillQuestions (shared by 2 files)

What it does
It draws its content. Defines 41 functions or classes, including $, el, fmt, when, FetchQueue. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. README: "The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/202609151339."
Inputs & outputs
In: data source: GitHub API; JSON file latest.json; JSON file graph_latest.json. Out: canvas drawing.
Downstream impact
Used directly by 1 file: Iterations — 43 Registry Growth Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/43-registry-growth/). Reached from 1 other entry point, including Iterations — 47 Federation Honesty Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/47-federation-honesty/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/43-registry-growth/.
What it achieves
How the Estate Grew: the page. It responds to click, pointerdown and pointermove events.
Why it matters
Loaded by the page of the same name at https://ventusltd.github.io/galaxies-wafers/iterations/43-registry-growth/.
Application
galaxies-wafers · iterations/43-registry-growth · JavaScript module
Uses
./registry.mjs
Used by
loaded by Iterations — 43 Registry Growth Page (script src)
Produces
$, el, fmt, when, FetchQueue, fetchOnce, label, paintMachine, hydrateListing, hydrateSnapshot, missingTop, openTimeline
Defines here
$, el, fmt, when, FetchQueue, fetchOnce, label, paintMachine, hydrateListing, hydrateSnapshot, missingTop, openTimeline, tlState, loadRow, fillRow, part, countTimeline, buildDiffLists, paintList, openDiff, runDiff, put, hydrateGraph, bounds, fit, requestDraw, drawGraph, X, on, inView
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/43-registry-growth/app.mjs:1-440 · blob 1dc7911810af8a6659b97d4c1a5d29a5635513c9 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
/* How the Estate Grew: the page. Loading in Grid Atlas grammar: every section
   exists from the start, nothing is fetched until the reader opens it, one
   queue of 4 carries every request with a 15 s timeout, one promise per URL
   (removed on failure so a retry is possible), and only the changed row or
   label is touched. The counting rules live in registry.mjs. */
import * as G from './registry.mjs';

const OWNER = 'Ventusltd';
const REPO = 'registry_of_all_content_in_repos_and_dependencies';
/* origin/main of the registry repository when this page was built (git fetch) */
const PIN = '4088117acd2c2d1ea3596779e13373fbb709c696';
const RAW = `https://raw.githubusercontent.com/${OWNER}/${REPO}/${PIN}/`;
const API = `https://api.github.com/repos/${OWNER}/${REPO}/`;
const TIMEOUT = 15000, CONCURRENCY = 4, PAGE = 12;

const $ = id => document.getElementById(id);
const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
const fmt = n => (n == null ? 'not yet known' : Number(n).toLocaleString('en-GB'));
const when = s => (s ? s.replace('T', ' ').replace(/:\d\dZ$/, 'Z') : null);
$('sha').textContent = PIN.slice(0, 12);
$('sha').title = PIN;

/* ── loading, as Grid Atlas does it ─────────────────────────────────────── */
class FetchQueue {
  constructor(n) { this.n = n; this.active = 0; this.wait = []; this.peak = 0; }
  async add(task) {
    if (this.active >= this.n) await new Promise(r => this.wait.push(r));
    this.active++; this.peak = Math.max(this.peak, this.active);
    try { return await task(); } finally { this.active--; if (this.wait.length) this.wait.shift()(); }
  }
}
const queue = new FetchQueue(CONCURRENCY);
const urlCache = new Map();
const M = { fetches: 0, failed: 0, bytes: 0, timeouts: 0 };

function fetchOnce(url, onBytes) {
  if (urlCache.has(url)) return urlCache.get(url);
  const p = queue.add(async () => {
    const ctl = new AbortController();
    const timer = setTimeout(() => ctl.abort(), TIMEOUT);
    M.fetches++; paintMachine();
    try {
      const res = await fetch(url, { signal: ctl.signal, headers: url.startsWith(API) ? { Accept: 'application/vnd.github+json' } : undefined });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      let t;
      if (res.body && res.body.getReader && onBytes) {
        const reader = res.body.getReader(); const dec = new TextDecoder(); const parts = []; let got = 0;
        for (;;) { const { done, value } = await reader.read(); if (done) break; got += value.length; M.bytes += value.length; parts.push(dec.decode(value, { stream: true })); onBytes(got); }
        parts.push(dec.decode()); t = parts.join('');
      } else { t = await res.text(); M.bytes += t.length; }
      try { return JSON.parse(t); } catch (_) { throw new Error('not valid JSON'); }
    } catch (err) {
      M.failed++;
      if (err && err.name === 'AbortError') { M.timeouts++; throw new Error('timed out after 15 s'); }
      throw new Error((err && err.message) || String(err));
    } finally { clearTimeout(timer); paintMachine(); }
  }).catch(err => { urlCache.delete(url); throw err; });
  urlCache.set(url, p);
  return p;
}

/* the label of one section: only its text changes */
function label(sec, state, stats) {
  const s = $('lbl-' + sec);
  s.textContent = `${s.dataset.baseLabel} [${state}${stats ? ': ' + stats : ''}]`;
}
function paintMachine() {
  const newest = listing.value ? listing.value.versions[listing.value.versions.length - 1] : null;
  const s = newest != null && SNAP.get(newest) && SNAP.get(newest).sum;
  $('machine').textContent = 'Machine detail · inputs: registry/registry_vNNNN.json (repos[].files[] entries, integers counted), registry/latest.json (pointer: authoritative_version integer, json_path, updated_at UTC), registry/graph_latest.json (nodes with x, y in its own drawing units, edges from/to/type), the registry/ directory listing from the GitHub contents API; all at commit ' + PIN +
    ' · outputs: per snapshot repos and files counted (entries), repos and files added and removed between two snapshots (entries), file-count growth per repo (entries), MATCH / DIFFERS / NOT YET KNOWN per check · refusals: edges EMPTY for a snapshot with no edges field; NOT YET KNOWN when a file cannot be read; withheld entries counted, not displayed' +
    ` · this visit: ${M.fetches} requests, ${M.failed} failed, ${M.timeouts} timed out, ${fmt(M.bytes)} characters read, peak concurrency ${queue.peak} of ${CONCURRENCY}, snapshots held ${[...SNAP.values()].filter(x => x.sum).length}` +
    (s ? ` · newest read: v${G.pad4(newest)} with ${fmt(s.repoCount)} repos and ${fmt(s.fileCount)} files` : '');
}

/* ── the numbered files: listing, then one snapshot at a time ─────────────── */
const listing = { value: null, loading: null };
function hydrateListing() {
  if (listing.value) return Promise.resolve(listing.value);
  if (listing.loading) return listing.loading;
  listing.loading = (async () => {
    try {
      const dir = await fetchOnce(`${API}contents/registry?ref=${PIN}`);
      if (!Array.isArray(dir)) throw new Error('listing is not an array');
      const versions = dir.map(f => G.versionOfName(f.name)).filter(v => v != null).sort((a, b) => a - b);
      const sizes = new Map(dir.filter(f => G.versionOfName(f.name) != null).map(f => [G.versionOfName(f.name), f.size]));
      listing.value = { versions, sizes, method: 'the GitHub contents API listing of registry/ at the pinned commit', fromListing: true };
    } catch (e) {
      /* declared fallback: the pointer's authoritative_version, stated as such */
      const latest = await fetchOnce(RAW + 'registry/latest.json');
      const n = latest && Number.isInteger(latest.authoritative_version) ? latest.authoritative_version : null;
      if (n == null) throw new Error(`directory listing failed (${e.message}) and latest.json has no authoritative_version`);
      listing.value = { versions: Array.from({ length: n }, (_, i) => i + 1), sizes: new Map(), method: `v0001 to the authoritative_version in latest.json, because the directory listing failed (${e.message})`, fromListing: false };
    } finally { listing.loading = null; }
    return listing.value;
  })();
  return listing.loading;
}

const SNAP = new Map();   // version -> { sum, loading, err }
function hydrateSnapshot(v, onBytes) {
  let s = SNAP.get(v);
  if (!s) { s = { sum: null, loading: null, err: null }; SNAP.set(v, s); }
  if (s.sum) return Promise.resolve(s.sum);
  if (s.loading) return s.loading;
  s.err = null;
  s.loading = fetchOnce(RAW + 'registry/' + G.snapshotName(v), onBytes)
    .then(json => {
      s.sum = G.summarise(json, v);
      urlCache.delete(RAW + 'registry/' + G.snapshotName(v));   // the parsed file is dropped; the summary stays
      return s.sum;
    })
    .catch(e => { s.err = e.message; throw e; })
    .finally(() => { s.loading = null; paintMachine(); });
  return s.loading;
}
const SCHEMA_TOP = ['boot_sequence', 'generated_at', 'registry_version', 'repos', 'schema_version', 'totals'];
const missingTop = sum => SCHEMA_TOP.filter(k => !sum.topKeys.includes(k));

/* ── 1. timeline ─────────────────────────────────────────────────────────── */
const TL = new Map();  // version -> { li, head, nums, bar }
let tlMax = 0;
async function openTimeline() {
  if (TL.size) return;
  label('timeline', 'LOAD', 'listing registry/');
  let L;
  try { L = await hydrateListing(); }
  catch (e) { label('timeline', 'FAIL', e.message); return; }
  if (!L.versions.length) { label('timeline', 'EMPTY', 'no numbered snapshot files in registry/'); return; }
  const ol = $('rows-timeline');
  const frag = document.createDocumentFragment();
  for (const v of L.versions) {
    const li = el('li', 'row wait');
    const head = el('p', 'rhead'); const nums = el('p', 'nums small'); const bar = el('div', 'bar'); const i = el('i');
    bar.appendChild(i); li.append(head, nums, bar);
    head.append(el('span', 'st', 'WAIT'), el('b', null, `v${G.pad4(v)}`));
    nums.textContent = L.sizes.get(v) ? `${fmt(L.sizes.get(v))} bytes, queued` : 'queued';
    li.addEventListener('click', () => { if (li.classList.contains('fail')) loadRow(v); });
    TL.set(v, { li, head, nums, bar: i });
    frag.appendChild(li);
  }
  ol.appendChild(frag);
  ol.insertBefore(el('li', 'small dim', `${L.versions.length} numbered snapshots, found from ${L.method}.`), ol.firstChild);
  fillSummary();
  await Promise.all(L.versions.map(v => loadRow(v)));
}
function tlState(v, cls, st) {
  const r = TL.get(v); if (!r) return;
  r.li.className = 'row ' + cls;
  r.head.firstChild.textContent = st;
}
async function loadRow(v) {
  const r = TL.get(v);
  tlState(v, 'wait', 'WAIT');
  const size = listing.value && listing.value.sizes.get(v);
  let lastPaint = 0;
  try {
    const sum = await hydrateSnapshot(v, got => {
      const now = performance.now(); if (now - lastPaint < 150) return; lastPaint = now;
      if (r) { tlState(v, 'load', 'LOAD'); r.nums.textContent = size ? `${Math.round(100 * got / size)}% of ${fmt(size)} bytes` : `${fmt(got)} bytes`; }
    });
    fillRow(v, sum);
  } catch (e) {
    if (r) { tlState(v, 'fail', 'FAIL'); r.nums.textContent = `${e.message}. Tap to try again.`; }
  }
  countTimeline();
}
function fillRow(v, sum) {
  const r = TL.get(v); if (!r) return;
  tlState(v, 'ok', 'OK');
  const h = r.head;
  while (h.childNodes.length > 1) h.removeChild(h.lastChild);
  h.append(el('b', null, sum.generated_at ? when(sum.generated_at) : `v${G.pad4(v)}`), el('span', 'dim', sum.generated_at ? `v${G.pad4(v)} · generated_at` : 'no generated_at: version number'));
  const n = r.nums; n.textContent = '';
  const part = (b, t) => { n.append(el('b', null, b), document.createTextNode(' ' + t + '  ')); };
  part(fmt(sum.repoCount), 'repos');
  part(fmt(sum.fileCount), 'files');
  const types = Object.keys(sum.types).length;
  n.append(document.createTextNode(`· ${types} file types · states ${Object.entries(sum.states).map(([k, c]) => `${k} ${fmt(c)}`).join(', ') || 'none'} · edges ${sum.edges == null ? 'EMPTY (no edges field)' : fmt(sum.edges)}`));
  const d = sum.declared;
  if (d) {
    const agree = d.repo_count === sum.repoCount && d.file_count === sum.fileCount;
    n.append(document.createTextNode(` · totals written in the file ${agree ? 'equal these counts' : `say ${fmt(d.repo_count)} repos, ${fmt(d.file_count)} files`}; reachable ${fmt(d.reachable_count)}, unreachable ${fmt(d.unreachable_count)}`));
  } else n.append(document.createTextNode(' · no totals field'));
  if (sum.registry_version !== v) n.append(document.createTextNode(` · registry_version inside says ${sum.registry_version == null ? 'nothing' : sum.registry_version}`));
  const miss = missingTop(sum);
  if (miss.length) n.append(document.createTextNode(` · fields named above but absent: ${miss.join(', ')}`));
  if (sum.withheldRepos || sum.withheldFiles) n.append(document.createTextNode(` · ${sum.withheldRepos} repos and ${sum.withheldFiles} files withheld, ${G.WITHHELD_REASON}`));
  if (sum.fileCount > tlMax) { tlMax = sum.fileCount; for (const [vv, rr] of TL) { const s = SNAP.get(vv); if (s && s.sum) rr.bar.style.width = (100 * s.sum.fileCount / tlMax).toFixed(1) + '%'; } }
  else r.bar.style.width = (100 * sum.fileCount / tlMax).toFixed(1) + '%';
}
function countTimeline() {
  const vs = listing.value ? listing.value.versions : [];
  let ok = 0, fail = 0;
  for (const v of vs) { const s = SNAP.get(v); if (s && s.sum) ok++; else if (s && s.err) fail++; }
  if (ok + fail < vs.length) label('timeline', 'LOAD', `${ok} of ${vs.length} read`);
  else if (fail) label('timeline', 'FAIL', `${ok} of ${vs.length} read, ${fail} failed: tap a failed row`);
  else label('timeline', 'OK', `${ok} snapshots read`);
  fillSummary(); fillQuestions();
}

/* ── 2. diff ─────────────────────────────────────────────────────────────── */
const LISTS = [
  ['added', 'Repositories added', x => [el('b', null, x.name), document.createTextNode(` · ${fmt(x.files)} files`)]],
  ['removed', 'Repositories removed', x => [el('b', null, x.name), document.createTextNode(` · had ${fmt(x.files)} files`)]],
  ['growth', 'Largest growth in files counted (largest first; shrinkage at the end)', x => [el('b', null, `${x.delta > 0 ? '+' : ''}${fmt(x.delta)}`), document.createTextNode(` ${x.name} · ${x.from == null ? 'absent' : fmt(x.from)} to ${x.to == null ? 'absent' : fmt(x.to)}`)]],
  ['filesAdded', 'Files added', x => [el('b', null, x.name), document.createTextNode(' / ' + x.path)]],
  ['filesRemoved', 'Files removed', x => [el('b', null, x.name), document.createTextNode(' / ' + x.path)]],
  ['edgesAdded', 'Edges added', x => [document.createTextNode(x)]],
  ['edgesRemoved', 'Edges removed', x => [document.createTextNode(x)]],
];
const DL = new Map();   // key -> { h, ol, info, prev, next, items, page, render }
function buildDiffLists() {
  const box = $('d-lists');
  for (const [key, title, render] of LISTS) {
    const wrap = el('div', 'list'); const h = el('h3', null, title); const info = el('p', 'small dim', 'not yet known');
    const ol = el('ol'); const pager = el('div', 'pager');
    const prev = el('button', null, 'previous'); const next = el('button', null, 'next'); prev.type = next.type = 'button';
    const where = el('span', 'small dim');
    pager.append(prev, next, where); wrap.append(h, info, ol, pager); box.appendChild(wrap);
    const L = { h, ol, info, prev, next, where, items: [], page: 0, render, empty: null };
    prev.addEventListener('click', () => { if (L.page > 0) { L.page--; paintList(L); } });
    next.addEventListener('click', () => { if ((L.page + 1) * PAGE < L.items.length) { L.page++; paintList(L); } });
    DL.set(key, L); paintList(L);
  }
}
function paintList(L) {
  L.ol.textContent = '';
  const start = L.page * PAGE, slice = L.items.slice(start, start + PAGE);
  for (const x of slice) { const li = el('li'); li.append(...L.render(x)); L.ol.appendChild(li); }
  const pages = Math.max(1, Math.ceil(L.items.length / PAGE));
  L.where.textContent = L.items.length ? `${start + 1} to ${start + slice.length} of ${fmt(L.items.length)} · page ${L.page + 1} of ${pages}` : '';
  L.prev.disabled = L.page === 0; L.next.disabled = (L.page + 1) * PAGE >= L.items.length;
}
async function openDiff() {
  if (DL.size) return;
  buildDiffLists();
  label('diff', 'LOAD', 'listing registry/');
  let L;
  try { L = await hydrateListing(); } catch (e) { label('diff', 'FAIL', e.message); $('d-status').textContent = 'FAIL: ' + e.message; return; }
  if (L.versions.length < 2) { label('diff', 'EMPTY', 'fewer than two numbered snapshots'); return; }
  for (const id of ['d-from', 'd-to']) {
    const s = $(id); s.textContent = '';
    for (const v of L.versions) { const o = el('option', null, `v${G.pad4(v)}`); o.value = v; s.appendChild(o); }
  }
  $('d-from').value = L.versions[L.versions.length - 2];
  $('d-to').value = L.versions[L.versions.length - 1];
  $('d-go').disabled = false;
  label('diff', 'OK', `${L.versions.length} snapshots to choose from`);
  $('d-status').textContent = 'WAIT: choose two snapshots and tap compare.';
}
let diffToken = 0;
async function runDiff() {
  const a = Number($('d-from').value), b = Number($('d-to').value);
  const token = ++diffToken;
  $('d-status').textContent = `LOAD: reading v${G.pad4(a)} and v${G.pad4(b)}`;
  label('diff', 'LOAD', `v${G.pad4(a)} to v${G.pad4(b)}`);
  let sa, sb;
  try { [sa, sb] = await Promise.all([hydrateSnapshot(a), hydrateSnapshot(b)]); if (TL.size) { fillRow(a, sa); fillRow(b, sb); countTimeline(); } }
  catch (e) { if (token === diffToken) { $('d-status').textContent = 'FAIL: ' + e.message + '. Tap compare to try again.'; label('diff', 'FAIL', e.message); } return; }
  if (token !== diffToken) return;
  const d = G.diff(sa, sb);
  const put = (key, items, empty) => { const L = DL.get(key); L.items = items; L.page = 0; L.info.textContent = items.length ? `${fmt(items.length)} entries` : `EMPTY: ${empty}`; paintList(L); };
  put('added', d.added, `no repository in v${G.pad4(b)} is absent from v${G.pad4(a)}`);
  put('removed', d.removed, `no repository in v${G.pad4(a)} is absent from v${G.pad4(b)}`);
  put('growth', d.growth, 'no repositories in either snapshot');
  put('filesAdded', d.filesAdded, `no file path in v${G.pad4(b)} is absent from v${G.pad4(a)}`);
  put('filesRemoved', d.filesRemoved, `no file path in v${G.pad4(a)} is absent from v${G.pad4(b)}`);
  if (d.edges.empty) { put('edgesAdded', [], d.edges.empty); put('edgesRemoved', [], d.edges.empty); }
  else { put('edgesAdded', d.edges.added, 'no edge added'); put('edgesRemoved', d.edges.removed, 'no edge removed'); }
  const direction = a === b ? ' (the same snapshot on both sides)' : a > b ? ' (from a newer to an older snapshot)' : '';
  $('d-status').textContent = `OK: v${G.pad4(a)} (${fmt(sa.repoCount)} repos, ${fmt(sa.fileCount)} files) to v${G.pad4(b)} (${fmt(sb.repoCount)} repos, ${fmt(sb.fileCount)} files)${direction}. Withheld, ${G.WITHHELD_REASON}: ${d.withheldRepos} repos, ${d.withheldFiles} file changes.`;
  label('diff', 'OK', `v${G.pad4(a)} to v${G.pad4(b)}: ${d.added.length} repos added, ${d.removed.length} removed, ${fmt(d.filesAdded.length)} files added, ${fmt(d.filesRemoved.length)} removed`);
}

/* ── 3. graph ────────────────────────────────────────────────────────────── */
const graph = { value: null, loading: null, facts: null, view: null, sel: null, showFiles: true, drawn: { nodes: 0, edges: 0 }, frames: 0 };
function hydrateGraph() {
  if (graph.value) return Promise.resolve(graph.value);
  if (graph.loading) return graph.loading;
  graph.loading = fetchOnce(RAW + 'registry/graph_latest.json').then(g => {
    graph.value = g; graph.facts = G.graphFacts(g);
    const nodes = (g.nodes || []).filter(n => Number.isFinite(n.x) && Number.isFinite(n.y));
    graph.withheld = nodes.filter(n => { const p = G.parseNodeId(n.id); return G.isWithheld(p.repo, p.path); }).length;
    graph.nodes = nodes.filter(n => { const p = G.parseNodeId(n.id); return !G.isWithheld(p.repo, p.path); });
    graph.byId = new Map(graph.nodes.map(n => [n.id, n]));
    graph.noXY = (g.nodes || []).length - nodes.length;
    return g;
  }).finally(() => { graph.loading = null; paintMachine(); });
  return graph.loading;
}
const cv = $('g-canvas'); const ctx = cv.getContext('2d');
function bounds() {
  let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
  for (const n of graph.nodes) { x0 = Math.min(x0, n.x); y0 = Math.min(y0, n.y); x1 = Math.max(x1, n.x); y1 = Math.max(y1, n.y); }
  return { x0, y0, x1, y1 };
}
function fit() {
  if (!graph.nodes || !graph.nodes.length) return;
  const r = cv.getBoundingClientRect(); const b = bounds(); const padPx = 36;
  const s = Math.min((r.width - 2 * padPx) / Math.max(1, b.x1 - b.x0), (r.height - 2 * padPx) / Math.max(1, b.y1 - b.y0));
  graph.view = { s, cx: (b.x0 + b.x1) / 2, cy: (b.y0 + b.y1) / 2 };
  requestDraw();
}
let drawQueued = false;
function requestDraw() { if (!drawQueued) { drawQueued = true; requestAnimationFrame(() => { drawQueued = false; drawGraph(); }); } }
function drawGraph() {
  if (!graph.nodes || !graph.view) return;
  const t0 = performance.now();
  const r = cv.getBoundingClientRect(); const dpr = Math.min(2, window.devicePixelRatio || 1);
  const W = Math.max(1, Math.round(r.width * dpr)), H = Math.max(1, Math.round(r.height * dpr));
  if (cv.width !== W || cv.height !== H) { cv.width = W; cv.height = H; }
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  ctx.fillStyle = '#05060a'; ctx.fillRect(0, 0, r.width, r.height);
  const { s, cx, cy } = graph.view;
  const X = x => (x - cx) * s + r.width / 2, Y = y => (y - cy) * s + r.height / 2;
  const on = n => graph.showFiles || !String(n.id).startsWith('file::');
  const inView = (x, y, m) => x > -m && y > -m && x < r.width + m && y < r.height + m;
  const types = graph.value.edgeTypes || {};
  let ne = 0, nn = 0;
  const edges = graph.value.edges || [];
  for (const pass of [0, 1]) {
    for (const e of edges) {
      const a = graph.byId.get(e.from), b = graph.byId.get(e.to);
      if (!a || !b || !on(a) || !on(b)) continue;               // both ends must exist and be shown
      const ax = X(a.x), ay = Y(a.y), bx = X(b.x), by = Y(b.y);
      if (Math.max(ax, bx) < 0 || Math.min(ax, bx) > r.width || Math.max(ay, by) < 0 || Math.min(ay, by) > r.height) continue;
      const t = types[e.type] || {};
      const dash = String(t.dash || '').trim().split(/\s+/).filter(Boolean).map(Number).filter(Number.isFinite);
      ctx.beginPath(); ctx.moveTo(ax, ay); ctx.lineTo(bx, by);
      if (pass === 0) { ctx.setLineDash([]); ctx.strokeStyle = 'rgba(0,0,0,.85)'; ctx.lineWidth = 4.5; ctx.stroke(); }
      else { ctx.setLineDash(dash.map(d => Math.max(2, d * Math.min(1, s * 4)))); ctx.strokeStyle = /^#[0-9a-f]{6}$/i.test(t.colour || '') ? t.colour : '#8b93a7'; ctx.lineWidth = 1.6; ctx.stroke(); ne++; }
    }
  }
  ctx.setLineDash([]);
  const zoomR = Math.max(0.6, Math.min(2.2, s * 12));
  for (const n of graph.nodes) {
    if (!on(n)) continue;
    const x = X(n.x), y = Y(n.y); if (!inView(x, y, 20)) continue;
    const repo = String(n.id).startsWith('repo::');
    const rad = (repo ? 5.5 : 2.6) * zoomR;
    ctx.beginPath(); ctx.arc(x, y, rad + 2.5, 0, Math.PI * 2); ctx.fillStyle = 'rgba(0,0,0,.9)'; ctx.fill();
    ctx.beginPath(); ctx.arc(x, y, rad, 0, Math.PI * 2); ctx.fillStyle = repo ? '#ffffff' : '#9aa6bd'; ctx.fill();
    if (repo) { ctx.beginPath(); ctx.arc(x, y, rad + 4, 0, Math.PI * 2); ctx.strokeStyle = 'rgba(94,200,242,.55)'; ctx.lineWidth = 1.5; ctx.stroke(); }
    if (graph.sel === n) { ctx.beginPath(); ctx.arc(x, y, rad + 7, 0, Math.PI * 2); ctx.strokeStyle = '#ffd54a'; ctx.lineWidth = 2; ctx.stroke(); }
    nn++;
  }
  /* labels only where there is room: repository spacing on screen decides */
  const gap = 420 * s;
  ctx.font = '11px ui-monospace, Menlo, Consolas, monospace'; ctx.textBaseline = 'middle';
  for (const n of graph.nodes) {
    const repo = String(n.id).startsWith('repo::');
    if (!on(n) || !(repo ? gap > 70 : s > 0.5) && graph.sel !== n) continue;
    const x = X(n.x), y = Y(n.y); if (!inView(x, y, 0)) continue;
    const text = String(n.label || n.id); const max = repo ? Math.max(8, Math.floor(gap / 7.5)) : 28;
    const t = text.length > max ? text.slice(0, max - 1) + '…' : text;
    const tx = x + 9, ty = repo ? y - 14 : y;
    ctx.lineWidth = 3; ctx.strokeStyle = '#05060a'; ctx.strokeText(t, tx, ty);
    ctx.fillStyle = graph.sel === n ? '#ffd54a' : repo ? '#ffffff' : '#c5cddc'; ctx.fillText(t, tx, ty);
  }
  graph.drawn = { nodes: nn, edges: ne }; graph.frames++; graph.lastMs = performance.now() - t0;
  graph.maxMs = Math.max(graph.maxMs || 0, graph.lastMs);
  $('g-stats').textContent = graphStats();
}
function graphStats() {
  const f = graph.facts; if (!f) return 'WAIT';
  const edges = graph.value.edges || [];
  const bothEnds = edges.filter(e => graph.byId.has(e.from) && graph.byId.has(e.to)).length;
  return `OK: ${fmt(f.nodes)} nodes (${f.repoNodes.length} repositories, ${f.fileNodes.length} files), ${fmt(f.edges)} edges (${Object.entries(f.byType).map(([k, c]) => `${k} ${c}`).join(', ')}); ${bothEnds} have both ends in the file, ${f.edges - bothEnds} do not and are never drawn. In view now: ${graph.drawn.nodes} nodes, ${graph.drawn.edges} edges. ${graph.withheld} nodes withheld, ${G.WITHHEL  … [line shortened here: 483 characters; full line on GitHub]
}
async function openGraph() {
  if (graph.opened) { fit(); return; }
  label('graph', 'LOAD', 'graph_latest.json');
  try { await hydrateGraph(); }
  catch (e) { label('graph', 'FAIL', e.message + ': close and reopen to try again'); $('g-stats').textContent = 'FAIL: ' + e.message; return; }
  if (!graph.nodes.length) { label('graph', 'EMPTY', 'graph_latest.json has no nodes with x, y'); return; }
  const legend = el('div', 'legend');
  for (const [k, c] of Object.entries(graph.facts.byType)) {
    const t = (graph.value.edgeTypes || {})[k] || {};
    const sp = el('span'); const i = el('i'); i.style.borderTopColor = /^#[0-9a-f]{6}$/i.test(t.colour || '') ? t.colour : '#8b93a7';
    if (String(t.dash || '').trim()) i.style.borderTopStyle = 'dashed';
    sp.append(i, document.createTextNode(`${t.label || k} (${c})`)); legend.appendChild(sp);
  }
  $('g-stats').before(legend);
  graph.opened = true;
  fit();
  label('graph', 'OK', `${fmt(graph.facts.nodes)} nodes, ${fmt(graph.facts.edges)} edges`);
  fillQuestions();
}
/* pan, pinch, wheel, tap */
const ptrs = new Map(); let gesture = null;
cv.addEventListener('pointerdown', e => {
  if (!graph.view) return;
  cv.setPointerCapture(e.pointerId);
  ptrs.set(e.pointerId, { x: e.clientX, y: e.clientY });
  gesture = { moved: 0, t: performance.now(), start: { ...graph.view }, pts: new Map([...ptrs].map(([k, v]) => [k, { ...v }])) };
});
cv.addEventListener('pointermove', e => {
  if (!ptrs.has(e.pointerId) || !gesture) return;
  const prev = ptrs.get(e.pointerId); ptrs.set(e.pointerId, { x: e.clientX, y: e.clientY });
  gesture.moved += Math.hypot(e.clientX - prev.x, e.clientY - prev.y);
  const v = graph.view;
  if (ptrs.size === 1) { v.cx -= (e.clientX - prev.x) / v.s; v.cy -= (e.clientY - prev.y) / v.s; }
  else if (ptrs.size === 2) {
    const [a, b] = [...ptrs.values()]; const [a0, b0] = [...gesture.pts.values()];
    if (a0 && b0) {
      const d0 = Math.hypot(a0.x - b0.x, a0.y - b0.y) || 1, d1 = Math.hypot(a.x - b.x, a.y - b.y) || 1;
      zoomAt((a.x + b.x) / 2, (a.y + b.y) / 2, gesture.start.s * d1 / d0 / v.s);
    }
  }
  requestDraw();
});
const endPtr = e => {
  if (!ptrs.has(e.pointerId)) return;
  ptrs.delete(e.pointerId);
  if (gesture && ptrs.size === 0 && gesture.moved < 10 && e.type === 'pointerup') pick(e.clientX, e.clientY);
  if (ptrs.size === 0) gesture = null;
  else gesture = { moved: 99, t: performance.now(), start: { ...graph.view }, pts: new Map([...ptrs].map(([k, v]) => [k, { ...v }])) };
};
cv.addEventListener('pointerup', endPtr); cv.addEventListener('pointercancel', endPtr);
cv.addEventListener('wheel', e => { if (!graph.view) return; e.preventDefault(); zoomAt(e.clientX, e.clientY, Math.exp(-e.deltaY * 0.0015)); requestDraw(); }, { passive: false });
function zoomAt(px, py, k) {
  const v = graph.view; const r = cv.getBoundingClientRect();
  const wx = (px - r.left - r.width / 2) / v.s + v.cx, wy = (py - r.top - r.height / 2) / v.s + v.cy;
  v.s = Math.max(0.01, Math.min(4, v.s * k));
  v.cx = wx - (px - r.left - r.width / 2) / v.s; v.cy = wy - (py - r.top - r.height / 2) / v.s;
}
function pick(px, py) {
  const r = cv.getBoundingClientRect(); const v = graph.view;
  let best = null, bd = 24;
  for (const n of graph.nodes) {
    if (!graph.showFiles && String(n.id).startsWith('file::')) continue;
    const d = Math.hypot((n.x - v.cx) * v.s + r.width / 2 - (px - r.left), (n.y - v.cy) * v.s + r.height / 2 - (py - r.top));
    if (d < bd) { bd = d; best = n; }
  }
  graph.sel = best; showCard(best); requestDraw();
}
function showCard(n) {
  const card = $('g-card');
  if (!n) { card.hidden = true; return; }