GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / globalgrid2050 / testcode/202609142202

Star and 2 more files

A JavaScript file in the testcode folder of GlobalGrid2050 that draws map (`drawMap`) (units: kWh), covering postcodes, using SHA-256. It draws map (`drawMap`) and maps lens (`mapLens`).

624 lines of JavaScript from globalgrid2050, in 3 files. Topic: Kuiper, cosmos and drawing engines. Section 1456 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. Quantum render · globalgrid2050 / testcode/202609142202/quantum.js lines 701–976
  2. Particle transform · globalgrid2050 / testcode/202609142225/lenses/particle.js lines 1–51
  3. Star render · globalgrid2050 / testcode/202609150125/star.js lines 1–297

Quantum

A JavaScript file in the testcode folder of GlobalGrid2050 that draws families, blocks, electron and entangled, using SHA-256. It makes program (`makeProgram`), builds layout (`buildLayout`) and sets focus (`setFocus`).

renderglobalgrid2050 / testcode/202609142202/quantum.js · lines 701–976 of 976 · version 2026-09-14 22:02 (continued from section 1455) · Not reached from any entry point (candidate for review) · pattern renderRecord (shared by 2 files)

What it does
It draws families, blocks, electron and entangled. Defines 75 functions or classes, including $, fmt, phoneNow, fail, hex. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. README: "A read-only lab page: `index.html` + `quantum.js` (one ES module, WebGL2, no CDN, no framework, no build step)."
Inputs & outputs
In: JSON file families.json; JSON file blocks.json; JSON file electron.json; JSON file random.json; JSON file entangled.json; JSON file provenance.json. Out: WebGL/WebGPU drawing.
What it achieves
Quantum Twin Star — testcode/ — generation 2 — ES module, WebGL2 only, no CDN, no framework. It responds to keydown, click and pointerdown events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · testcode/202609142202 · script
VEDIC
SEARCH (GG2050-VEDIC-000030): See Through / Kuiper · Computer science / Interactive visualisation. query, substation_names → match_count_and_indices
Uses
none found
Used by
mentioned in Standalone (comment link)
Produces
$, fmt, phoneNow, fail, hex, hash32, mulberry32, stateNum, stateName, SEA_VS, UNIQ_VS, makeProgram
Defines here
focusLine, doSearch, pickAt, updateHUD, stateText, renderHUD, setSeaUniforms, setUniqUniforms, genUniforms, rotMat, frame, wireUI, up, walkBand, legend, aboutPanel, fallback2D
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609142202/quantum.js:701-976 · blob e1a1326a6328dbe845f9aa6352601573aa408390 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: experimental · users: none · canonical: unreached_review
function focusLine(n, u) {
  if (u.inFam) { const f = D.families[u.firstFam]; setFocus({ famIdx: u.firstFam, key: n }); S.msg = `line #${n} · unique line ${fmt(u.i + 1)} of ${fmt(D.uniqN)} in LINES.md · ${fmt(u.len)} bytes · inside a function family: appears in ${fmt(u.famCount)} famil${u.famCount === 1 ? 'y' : 'ies'}, showing #${f.n} ${f.name} (first by pack order) · lit in the unique band and in the family sea · search st  … [line shortened here: 429 characters; full line on GitHub]
  else { setFocus({ famIdx: -1, atom: null, key: n }); S.msg = `line #${n} · unique line ${fmt(u.i + 1)} of ${fmt(D.uniqN)} in LINES.md · ${fmt(u.len)} bytes · outside every function family (grey band) · no electron record: nothing to measure`; }
}
function doSearch(q) {
  q = q.trim(); if (!q) return; S.lastActivity = performance.now();
  const again = q === S.lastQuery; // lastQuery is set only by a search that steered to a focus (setFocus clears it; a no-match clears it), so "Enter again" measures only that focus
  if (again && S.atom) { measure(); return; }
  if (again) { S.msg = 'nothing to measure: this focus has no electron record (search steered, it did not collapse)'; updateHUD(true); return; }
  S.lastQuery = '';
  const lm = /^line\s*#?(\d+)$/i.exec(q); const m = /^#?(\d+)$/.exec(q);
  if (lm) { // "line N": the permanent line number, even when N is also a family key
    const n = +lm[1]; const u = uniqFacts(n);
    if (u) { focusLine(n, u); S.lastQuery = q; }
    else S.msg = `line #${n} is not in LINES.md (${fmt(D.uniqN)} unique lines, numbered ${fmt(D.uniq[0])} to ${fmt(D.uniq[D.uniqN - 1])}; numbers missing from the sequence were never issued or were withdrawn)`;
  } else if (m) {
    const n = +m[1]; const u = uniqFacts(n);
    if (D.famByN.has(n)) { const fi = D.famByN.get(n); const f = D.families[fi]; setFocus({ famIdx: fi }); S.lastQuery = q; S.msg = `family #${n} ${f.name} · block ${f.block} · ${fmt(f.lineCount)} entries · search steers, it does not measure: ${S.atom ? 'Enter again or tap the sphere to collapse' : 'no electron record for this family, nothing to measure'}${u ? ` · #${n} is also a permanent line nu  … [line shortened here: 446 characters; full line on GitHub]
    else if (u) { focusLine(n, u); S.lastQuery = q; }
    else if (D.atomByN.has(n)) { setFocus({ atom: D.atomByN.get(n) }); S.lastQuery = q; S.msg = `state #${n} ${D.atomByN.get(n).name} (electron census numbering) · search steers, it does not measure: Enter again or tap the sphere to collapse`; }
    else S.msg = `#${n} is neither a family key, a line number in LINES.md nor a shipped state number.`;
  } else {
    const fams = D.famByName.get(q), atoms = D.atomByName.get(q);
    if (fams) { setFocus({ famIdx: fams[0] }); S.lastQuery = q; S.msg = `${fams.length} famil${fams.length === 1 ? 'y' : 'ies'} named "${q}" · showing #${D.families[fams[0]].n} · search steers, it does not measure: ${S.atom ? 'Enter again or tap the sphere to collapse' : 'no electron record, nothing to measure'}`; }
    else if (atoms) { setFocus({ atom: atoms[0] }); S.lastQuery = q; S.msg = `${atoms.length} state${atoms.length === 1 ? '' : 's'} named "${q}" · search steers, it does not measure: Enter again or tap the sphere to collapse`; }
    else S.msg = `no family or shipped state is named "${q}"`;
  }
  updateHUD(true);
}

// ---------- pick ----------
function pickAt(cssX, cssY) {
  if (!pick.ok) { S.msg = 'pick framebuffer unavailable'; return; }
  const x = Math.round(cssX * DPR), y = Math.round(G.H - cssY * DPR); const sz = G.phone ? 8 : 1; const half = Math.floor(sz / 2);
  gl.bindFramebuffer(gl.FRAMEBUFFER, pick.fbo); gl.viewport(0, 0, G.W, G.H); gl.disable(gl.BLEND); gl.enable(gl.SCISSOR_TEST); gl.scissor(x - half, y - half, sz, sz);
  gl.clearBufferuiv(gl.COLOR, 0, new Uint32Array([0, 0, 0, 0]));
  gl.useProgram(P.pick.p); setSeaUniforms(P.pick, 1); gl.bindVertexArray(VAO.sea); gl.drawArraysInstanced(gl.POINTS, 0, S.seaDrawn, 2); // both stars are pickable
  const out = new Uint32Array(sz * sz * 4); gl.readPixels(x - half, y - half, sz, sz, gl.RGBA_INTEGER, gl.UNSIGNED_INT, out);
  gl.disable(gl.SCISSOR_TEST); gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.enable(gl.BLEND);
  let best = null, bd = 1e9; for (let j = 0; j < sz; j++) for (let i = 0; i < sz; i++) { const o = (j * sz + i) * 4; if (out[o]) { const d = (i - half) ** 2 + (j - half) ** 2; if (d < bd) { bd = d; best = [out[o], (out[o + 1] & 0xFFFF) - 1, out[o + 1] >>> 16]; } } }
  if (!best) { S.msg = 'tap hit no entry'; updateHUD(true); return; }
  const fi = best[1]; const f = D.families[fi]; setFocus({ famIdx: fi, key: best[0] }); // a pick steers only; it never measures
  const bi = D.famBlock[fi]; const bl = bi < D.NB ? D.blocks.blocks[bi] : null;
  S.msg = `${best[2] === 1 ? 'twin star: ' : ''}#${best[0]} · family #${f.n} ${f.name} · block ${bl ? bl.symbol + ' (' + bl.category + ')' : f.block + ' (off table)'} · line #${best[0]} appears in ${fmt(D.keyCount.get(best[0]))} families${best[2] === 1 ? ' (the twin is the same entry mirrored; the pick steers the principal)' : ''} · tap steers only: press measure, tap the sphere or Enter to collap  … [line shortened here: 421 characters; full line on GitHub]
}

// ---------- HUD ----------
let hudDirty = true, hudLast = 0;
function updateHUD(force) { if (force) hudDirty = true; }
function stateText() {
  const a = S.atom; if (!a) return S.famIdx >= 0 ? `shells not shipped for this state (${fmt(D.electron.totals.atoms_shipped)} of ${fmt(D.electron.totals.atoms_in_star)} atoms carry records): tap steers, nothing to measure` : S.key ? `focus: line #${S.key} (outside every function family): no atom, nothing to measure` : 'no focus';
  const T = a.shells.K + a.shells.L + a.shells.M; if (T === 0) return 'no electrons: nothing to measure';
  const th = S.hand ? S.hand.theta : S.theta, ph = S.hand ? S.hand.phi : S.phi; const c = Math.cos(th / 2), s = Math.sin(th / 2);
  const collapsed = S.outcome >= 0 && !!S.collapse; const atPole = th < 1e-6 || Math.abs(th - PI) < 1e-6;
  const st = collapsed ? (S.outcome ? 'collapsed |1> AWAY' : 'collapsed |0> HOME') : S.hand ? 'prepared by hand' : S.relaxFrom ? 'relaxing to the data state' : (th < 1e-6 ? 'pure |0>' : Math.abs(th - PI) < 1e-6 ? 'pure |1>' : 'superposition (data state)');
  // φ wording follows the actual condition in frame(): frozen after a collapse, set by hand during a drag, precessing only for an unpaired spin, else still
  const phiWord = collapsed ? 'φ frozen at the collapse' : S.hand ? 'φ set by hand' : a.spin === 'unpaired' ? 'φ precessing (decorative: precession marks "no test or proof calls this")' : 'φ still (paired)';
  return `state: ${st} · θ=${deg(th)}° ${atPole ? 'φ — (global phase at the pole, not a state parameter)' : 'φ=' + deg(ph) + '°'} · P(home)=${(c * c).toFixed(3)} P(away)=${(s * s).toFixed(3)} · |α|²+|β|²=1 by construction (Bloch angles)`
    + (collapsed ? ` · measured at θ=${deg(S.measuredTheta)}° (${S.measuredHow}) · data θ=${deg(S.dataTheta)}° · a repeat measurement now reproduces the outcome until re-prepared` : '')
    + ` · K${a.shells.K} L${a.shells.L} M${a.shells.M} → sin²(θ/2)=M/(K+L+M)=${(Math.sin(S.dataTheta / 2) ** 2).toFixed(3)}: the chance the next caller sits in another repository (M shell), whether or not that repository holds a copy · ${a.valence > 0 ? `a TUNNEL is possible only where valence ≥ 1 (a caller in a repository holding no copy): this atom has valence ${a.valence} (electron.json tunnell  … [line shortened here: 743 characters; full line on GitHub]
}
function renderHUD(now) {
  if (!hudDirty && now - hudLast < 250) return; hudLast = now; hudDirty = false;
  const L = []; const x = 'x';
  L.push(['', `renderer: ${S.renderer}`]);
  if (S.contextLost) { L.push(['', 'WebGL context lost: 0 entries on GPU, nothing drawn' + (S.contextRestoredNote ? ' · ' + S.contextRestoredNote : '') + ' · waiting for the browser to restore the context']); }
  else {
    L.push(['', `on GPU: ${fmt(S.uniqDrawn)} unique numbered lines (LINES.md ${D.linesMdStamp}) + ${fmt(S.seaDrawn)} family-line entries · ${fmt(D.uniqInFamily)} unique lines sit inside a function family, ${fmt(D.uniqOutside)} do not` + (S.uniqStride > 1 ? ` · unique band: ${fmt(S.uniqDrawn)} of ${fmt(D.uniqN)} drawn (1 in ${S.uniqStride})` : '') + (S.phoneMode ? ' · ' + S.phoneMode : '')]);
    if (S.contextRestoredNote) L.push([x, `context: ${S.contextRestoredNote}`]);
    L.push([x, `${fmt(D.distinct)} distinct permanent numbers in the family buckets (${D.distinct === D.uniqInFamily ? 'equal to' : 'NOT equal to'} the ${fmt(D.uniqInFamily)} in-family unique lines) · index.json states ${fmt(D.provenance.checks.index_lines)} unique lines, LINES.md carries ${fmt(D.uniqN)} (${D.provenance.checks.index_lines === D.uniqN ? 'equal' : 'differ'}; the buckets alone reprod  … [line shortened here: 575 characters; full line on GitHub]
    L.push([x, `fps ${(S.fps || 0).toFixed(0)} (1 s mean) · draw calls ${S.lastDrawCalls} · DPR ${DPR}`]);
  }
  L.push([x, `seed "${S.seedString}"${S.seedNote ? ' · ' + S.seedNote : ''} · PRNG mulberry32(hash(seed, state, measurementCount))`]);
  L.push([x, stateText()]);
  L.push([x, `last measurement (Born audit): ${S.born || 'no measurement yet'}`]);
  const tw = S.twin; if (tw) { const probs = tw.cands.map(c => `${c.label} q=${c.q.toFixed(3)}${c.p != null ? ' p=' + c.p : ''}`).join(' · '); L.push([x, `twin tier: ${tw.tierLabel}${tw.cands.length ? ' · ' + probs : ''}${tw.all.length > 8 ? ` · ${tw.all.length - 8} more candidates not drawn` : ''}${S.twinNote ? ' · ' + S.twinNote : ''}`]); }
  const rp = S.reprepareAt ? Math.max(0, (S.reprepareAt - now) / 1000) : 0;
  L.push([x, S.hold ? 'hold: no automatic re-preparation (θ stays where it is; φ still precesses for an unpaired spin)' : S.reprepareAt ? `re-prepare in ${rp.toFixed(1)} s` : 'prepared (data state)']);
  const t = D.electron.totals; L.push([x, `data caveats: atoms with records ${fmt(t.atoms_shipped)}/${fmt(t.atoms_in_star)} · entangled states listed ${D.entangled.soul_md.entanglements_listed}/${D.entangled.soul_md.entanglements_stated} · random p on ${D.random.edges.filter(e => e.p != null).length}/${D.random.edges.length} edges · shipped atoms with M>0: ${fmt(D.atomsWithM)}/${fmt(t.atoms_shippe  … [line shortened here: 1,257 characters; full line on GitHub]
  if (S.famJoinNote) L.push([x, `join: ${S.famJoinNote}`]);
  if (S.atom && S.atom.valence > 0) L.push([x, `valence repos (call #${S.atom.n} without holding a copy, electron.json valence_repos): ${S.atom.valence_repos.join(', ')}`]);
  L.push([x, `cable: ${S.cableOn ? 'on' : 'off'}${S.cableNote ? ' · ' + S.cableNote : ' · no automatic external request; line text only on demand'}`]);
  const a = S.atom; if (a) { const h = S.hist.get(a.n); if (h && h.n >= 20) { const c = Math.cos(S.dataTheta / 2) ** 2; L.push([x, `histogram #${a.n} (prepared data state only): HOME ${h.home}/${h.n}=${(h.home / h.n).toFixed(3)} vs cos²(θ/2)=${c.toFixed(3)} · AWAY ${h.tunnel}/${h.n}=${(h.tunnel / h.n).toFixed(3)} vs sin²=${(1 - c).toFixed(3)} · ${h.skipped} draws not counted (repeats on a collapse  … [line shortened here: 447 characters; full line on GitHub]
  if (G.phone || G.compact) { const ab = atomBadges(); if (ab) L.push([x, `atom: ${ab}`]); L.push([x, BANDS_TEXT()]); }
  if (now - S.lastActivity > 20000 && !S.collapse) L.push([x, 'unitary evolution, nothing measured']);
  if (S.msg) L.push(['', S.msg]);
  if (S.prove) L.push(['', S.prove]);
  const hud = $('#hud'); hud.textContent = ''; L.forEach(([cls, txt]) => { const d = document.createElement('div'); d.className = cls; d.textContent = txt; hud.appendChild(d); });
  if (G.phone || G.compact) { const t = document.createElement('div'); t.className = 'k'; t.textContent = hud.classList.contains('collapsed') ? '▸ tap to expand' : '▾ tap to collapse'; hud.appendChild(t); }
}

// ---------- draw ----------
function setSeaUniforms(prog, pickMode) {
  const U = prog.U; gl.uniform1i(U.u_fam, 0); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, B.famTex);
  gl.uniform2f(U.u_res, G.W, G.H); gl.uniform1f(U.u_dpr, DPR); gl.uniform1f(U.u_time, S.time); gl.uniform2f(U.u_c0, G.c0[0], G.c0[1]); gl.uniform2f(U.u_c1, G.c1[0], G.c1[1]);
  gl.uniform1f(U.u_R, G.R); gl.uniform3f(U.u_view, S.view.x, S.view.y, S.view.z); gl.uniform1f(U.u_spiral, G.spiral);
  gl.uniform1ui(U.u_focusKey, S.key >>> 0); gl.uniform1ui(U.u_focusFamily, S.famIdx >= 0 ? S.famIdx : 0xFFFF); gl.uniform1ui(U.u_twinKey, S.twinKey >>> 0); gl.uniform1ui(U.u_twinFamily, S.twinFamily);
  gl.uniform1i(U.u_focusBlock, S.focusBlock); gl.uniform1i(U.u_focusCat, S.focusCat); gl.uniform1f(U.u_collapseT, S.collapseT || 0);
  gl.uniform1f(U.u_size, G.phone ? 1.0 : 1.2); gl.uniform1f(U.u_alpha, G.phone ? 0.5 : 0.35); gl.uniform3fv(U.u_pal, G.palFlat); gl.uniform1i(U.u_pick, pickMode);
}
function setUniqUniforms() {
  const U = P.uniq.U; gl.uniform1i(U.u_fam, 0); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, B.famTex);
  gl.uniform2f(U.u_res, G.W, G.H); gl.uniform1f(U.u_dpr, DPR); gl.uniform1f(U.u_time, S.time); gl.uniform2f(U.u_c0, G.c0[0], G.c0[1]); gl.uniform2f(U.u_c1, G.c1[0], G.c1[1]);
  gl.uniform1f(U.u_R, G.R); gl.uniform3f(U.u_view, S.view.x, S.view.y, S.view.z); gl.uniform1f(U.u_n, S.uniqDrawn); gl.uniform1f(U.u_alpha, G.phone ? 0.5 : 0.4);
  gl.uniform1ui(U.u_focusKey, S.key >>> 0); gl.uniform1ui(U.u_focusFamily, S.famIdx >= 0 ? S.famIdx : 0xFFFF); gl.uniform1f(U.u_collapseT, S.collapseT || 0); gl.uniform3fv(U.u_pal, G.palFlat);
}
function genUniforms(space, opts = {}) {
  const U = P.gen.U; gl.useProgram(P.gen.p); gl.uniform2f(U.u_res, G.W, G.H); gl.uniform2f(U.u_org, G.c0[0], G.c0[1]); gl.uniform2f(U.u_c0, G.c0[0], G.c0[1]); gl.uniform2f(U.u_c1, G.c1[0], G.c1[1]);
  gl.uniform1f(U.u_R, G.R); gl.uniform3f(U.u_view, S.view.x, S.view.y, S.view.z); gl.uniform1i(U.u_space, space); gl.uniform1f(U.u_time, S.time); gl.uniform1f(U.u_dpr, DPR);
  gl.uniform1f(U.u_size, opts.size || 4); gl.uniform1i(U.u_orbit, opts.orbit ? 1 : 0); gl.uniform1i(U.u_dash, opts.dash ? 1 : 0); gl.uniform1i(U.u_round, opts.round ? 1 : 0); gl.uniform1f(U.u_cut, opts.cut != null ? opts.cut : 2);
}
function rotMat() { const t = -0.45; const c = Math.cos(t), s = Math.sin(t); // tilt about x so the pole leans toward the viewer
  return new Float32Array([1, 0, 0, 0, c, s, 0, -s, c]); }
let lastT = 0;
function frame(now) {
  requestAnimationFrame(frame);
  const dt = lastT ? (now - lastT) / 1000 : 0; lastT = now; S.time = now / 1000; S.drawCalls = 0;
  S.fpsSamples.push(now); while (S.fpsSamples.length && S.fpsSamples[0] < now - 1000) S.fpsSamples.shift();
  S.fps = S.fpsSamples.length > 1 ? (S.fpsSamples.length - 1) * 1000 / (now - S.fpsSamples[0]) : 0; void dt;
  if (S.contextLost || gl.isContextLost()) { if (!S.contextLost) onContextLost({ preventDefault() {} }); S.lastDrawCalls = 0; S.fps = 0; renderHUD(now); return; } // nothing is drawn while the context is lost; the HUD says so
  // qubit evolution
  const a = S.atom; if (a && a.spin === 'unpaired' && !S.hand && S.outcome < 0) S.phi = (2 * PI * S.time / 8) % (2 * PI);
  if (S.relaxFrom && !S.hand) { const k = Math.min(1, (now - S.relaxFrom.t0) / 2000); S.theta = S.relaxFrom.theta + (S.dataTheta - S.relaxFrom.theta) * k; if (!(a && a.spin === 'unpaired')) S.phi = S.relaxFrom.phi * (1 - k); if (k >= 1) S.relaxFrom = null; }
  if (S.collapse) { const k = Math.min(1, (now - S.collapse) / 120); S.collapseT = k; S.flash = Math.max(0, 1 - (now - (S.flashAt || S.collapse)) / 400); if (!S.hold && S.reprepareAt && now >= S.reprepareAt) reprepare(); }
  else S.collapseT = 0;
  if (S.hold && S.reprepareAt) S.reprepareAt = now + 8000;
  gl.viewport(0, 0, G.W, G.H); gl.clearColor(0.028, 0.035, 0.05, 1); gl.clear(gl.COLOR_BUFFER_BIT);
  // 1. the sea, both stars, one call; then the unique-lines band, both stars, one call
  gl.blendFunc(gl.ONE, gl.ONE); gl.useProgram(P.sea.p); setSeaUniforms(P.sea, 0); gl.bindVertexArray(VAO.sea); gl.drawArraysInstanced(gl.POINTS, 0, S.seaDrawn, 2);
  gl.useProgram(P.uniq.p); setUniqUniforms(); gl.bindVertexArray(VAO.uniq); gl.drawArraysInstanced(gl.POINTS, 0, S.uniqDrawn, 2);
  gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  // 2. journey (both stars, mirrored) as a dashed strip + beads
  if (B.journeyN > 1) { genUniforms(1, { dash: true }); gl.bindVertexArray(VAO.journey); gl.drawArraysInstanced(gl.LINE_STRIP, 0, B.journeyN, 2); }
  if (B.journeyN > 0) { genUniforms(1, { round: true, size: 5 }); gl.bindVertexArray(VAO.journey); gl.drawArraysInstanced(gl.POINTS, 0, B.journeyN, 2); }
  // 3. tether (dashed) principal → twin
  if (B.tetherN > 0 && !S.tetherDissolved) { genUniforms(1, { dash: true }); gl.bindVertexArray(VAO.tether); gl.drawArrays(gl.LINES, 0, B.tetherN); }
  // 4. twin cloud
  if (B.cloudN > 0) { genUniforms(1, { round: true, size: 7, orbit: !S.twin.chosen }); gl.bindVertexArray(VAO.cloud); gl.drawArrays(gl.POINTS, 0, B.cloudN); }
  // 5. atom lines (bonds, spin arrows, dials) and dots (repo ring, nucleus)
  if (B.atomLinesN > 0) { genUniforms(0); gl.bindVertexArray(VAO.atomLines); gl.drawArrays(gl.LINES, 0, B.atomLinesN); }
  if (B.atomDotsN > 0) { genUniforms(0, { round: true, size: 4 }); gl.bindVertexArray(VAO.atomDots); gl.drawArrays(gl.POINTS, 0, B.atomDotsN - (S.atom ? 1 : 0)); if (S.atom) { genUniforms(0, { round: true, size: S.nucleusSize }); gl.drawArrays(gl.POINTS, B.atomDotsN - 1, 1); } }
  // 6. electrons in K/L/M shells
  if (a) { const U = P.elec.U; gl.useProgram(P.elec.p); gl.uniform2f(U.u_res, G.W, G.H); gl.uniform2f(U.u_org, G.c0[0], G.c0[1]); gl.uniform1f(U.u_r, G.sphereR); gl.uniform3f(U.u_counts, a.shells.K, a.shells.L, a.shells.M); gl.uniform1f(U.u_stride, S.elecStride); gl.uniform1f(U.u_time, S.time); gl.uniform1f(U.u_dpr, DPR); gl.uniform1f(U.u_collapseT, S.collapseT || 0); gl.uniform1f(U.u_outcome, S.o  … [line shortened here: 642 characters; full line on GitHub]
  // 7. Bloch wireframe, state arrow and dot
  { const U = P.bloch.U; gl.useProgram(P.bloch.p); gl.uniformMatrix3fv(U.u_rot, false, rotMat()); gl.uniform2f(U.u_org, G.c0[0], G.c0[1]); gl.uniform1f(U.u_r, G.sphereR); gl.uniform2f(U.u_res, G.W, G.H); gl.uniform1i(U.u_mode, 0); gl.uniform1i(U.u_round, 0); gl.uniform1f(U.u_size, 1);
    const dark = a && (a.shells.K + a.shells.L + a.shells.M === 0); const empty = !a;
    gl.uniform4f(U.u_col, 0, .9, 1, dark ? 0.12 : empty ? 0.3 : 0.7); gl.bindVertexArray(VAO.wire); gl.drawArrays(gl.LINES, 0, B.wireN);
    if (a && a.class === 'ambiguous') { gl.uniform2f(U.u_org, G.c0[0] + 8 * DPR, G.c0[1] + 6 * DPR); gl.uniform4f(U.u_col, 1, .83, .29, 0.35); gl.drawArrays(gl.LINES, 0, B.wireN); gl.uniform2f(U.u_org, G.c0[0], G.c0[1]); }
    if (a && !dark) { const th = S.hand ? S.hand.theta : (S.collapse && S.measuredTheta != null ? S.measuredTheta : S.theta), ph = S.hand ? S.hand.phi : S.phi; gl.uniform1i(U.u_mode, 1); // while collapsing the shader mixes from the measured θ to the pole gl.uniform1f(U.u_theta, th); gl.uniform1f(U.u_phi, ph); gl.uniform1f(U.u_collapseT, S.collapseT || 0); gl.uniform1f(U.u_outcome, Math.max(0, S.o  … [line shortened here: 409 characters; full line on GitHub]
      gl.uniform4f(U.u_col, 1, 1, 1, 0.9); gl.bindVertexArray(VAO.state); gl.drawArrays(gl.LINES, 0, 2); gl.uniform1i(U.u_round, 1); gl.uniform1f(U.u_size, 9 * DPR); const oc = S.outcome === 1 ? [1, .83, .29] : [0, .9, 1]; gl.uniform4f(U.u_col, S.outcome >= 0 ? oc[0] : 1, S.outcome >= 0 ? oc[1] : 1, S.outcome >= 0 ? oc[2] : 1, 1); gl.drawArrays(gl.POINTS, 1, 1); }
  }
  // 8. re-preparation ring
  if (S.reprepareAt && !S.hold) { const frac = Math.max(0, (S.reprepareAt - now) / 8000); genUniforms(0, { cut: frac }); gl.bindVertexArray(VAO.ring); gl.bindBuffer(gl.ARRAY_BUFFER, B.ring); const rr = G.sphereR * 1.08;
    if (S.ringScale !== rr) { /* ring vertices are re-uploaded only when the sphere radius changes (resize) */ const arr = new Float32Array(128 * 8); for (let i = 0; i < 128; i++) { const t = Math.floor(i / 2) / 64 + (i % 2) / 64; const an = -PI / 2 + t * 2 * PI; arr.set([Math.cos(an) * rr, Math.sin(an) * rr, 0, .9, 1, .8, t, 0], i * 8); } gl.bufferSubData(gl.ARRAY_BUFFER, 0, arr); S.ringScale = r  … [line shortened here: 404 characters; full line on GitHub]
    gl.drawArrays(gl.LINES, 0, 128); }
  // 9. the classical cable: a bead travelling from the sea point to the sphere while a fetch is in flight
  if (S.cable && !S.cable.done && S.famIdx >= 0) { const p = familyPos(S.famIdx); const k = ((now - S.cable.t0) / 600) % 1; const arr = new Float32Array([p[0] * (1 - k), p[1] * (1 - k), .5, .6, .7, 1, 0, 0]); gl.bindBuffer(gl.ARRAY_BUFFER, B.cable); gl.bufferSubData(gl.ARRAY_BUFFER, 0, arr); genUniforms(1, { round: true, size: 6 }); gl.bindVertexArray(VAO.cable); gl.drawArrays(gl.POINTS, 0, 1); }
  gl.bindVertexArray(null);
  S.lastDrawCalls = S.drawCalls; renderHUD(now);
}

// ---------- interaction ----------
function wireUI() {
  const search = $('#search'); search.addEventListener('keydown', e => { if (e.key === 'Enter') doSearch(search.value); });
  $('#measure').onclick = () => measure();
  $('#reprepare').onclick = () => { if (S.outcome >= 0 || S.hand || S.relaxFrom) reprepare('re-prepared by the button: θ back to the data value'); else { S.msg = 'already in the prepared data state'; updateHUD(true); } };
  $('#cable').onclick = e => { S.cableOn = !S.cableOn; e.target.classList.toggle('on', S.cableOn); e.target.textContent = 'cable: ' + (S.cableOn ? 'on' : 'off'); S.cableNote = S.cableOn ? 'on: after a measurement the family record is fetched from the bucket URL in provenance.json (once per bucket, retried only after a failure; sha256 checked, a mismatching bucket is not used)' : 'off: no automatic  … [line shortened here: 439 characters; full line on GitHub]
  $('#hold').onclick = e => { S.hold = !S.hold; e.target.classList.toggle('on', S.hold); updateHUD(true); };
  $('#newseed').onclick = () => { S.seedString = new Date().toISOString().slice(0, 10); S.seedNote = 'this is not a finding'; updateHUD(true); };
  $('#about').onclick = () => { const p = $('#aboutPanel'); p.hidden = !p.hidden; };
  $('#prove').onclick = async () => {
    let sha = 'sha256 unavailable'; try { const h = await crypto.subtle.digest('SHA-256', D.lines); sha = Array.from(new Uint8Array(h)).map(b => b.toString(16).padStart(2, '0')).join(''); } catch (e) { sha = 'sha256 unavailable: ' + e.message; }
    const prov = D.provenance.outputs.find(o => o.file === 'lines.bin');
    let usha = 'sha256 unavailable'; try { const h = await crypto.subtle.digest('SHA-256', D.uniq.buffer); usha = Array.from(new Uint8Array(h)).map(b => b.toString(16).padStart(2, '0')).join(''); } catch (e) { usha = 'sha256 unavailable: ' + e.message; }
    const uprov = D.provenance.outputs.find(o => o.file === 'all-lines.bin');
    S.prove = `prove it: family VBO ${fmt(S.seaBytes)} bytes (${fmt(S.seaDrawn)} entries × 12) · drawArraysInstanced(POINTS, 0, ${fmt(S.seaDrawn)}, 2) each frame · unique-lines VBO ${fmt(S.uniqBytes)} bytes (${fmt(S.uniqDrawn)} lines × 8) · drawArraysInstanced(POINTS, 0, ${fmt(S.uniqDrawn)}, 2) each frame · CPU sum of keys ${fmt(S.keySum)} · sha256(lines.bin in memory) ${sha} vs provenance ${prov.  … [line shortened here: 632 characters; full line on GitHub]
  };
  { const hud = $('#hud'); hud.classList.toggle('collapsed', G.phone || G.compact); hud.addEventListener('click', () => { if (!(G.phone || G.compact)) return; hud.classList.toggle('collapsed'); updateHUD(true); }); } // the toggle acts in the phone and compact layouts (live: a resize re-evaluates them)
  // sphere handle: drag prepares by hand (unitary), tap measures
  const h = $('#sphereHandle'); let drag = null;
  h.addEventListener('pointerdown', e => { h.setPointerCapture(e.pointerId); drag = { x: e.clientX, y: e.clientY, moved: false, th: S.hand ? S.hand.theta : S.theta, ph: S.hand ? S.hand.phi : S.phi }; S.lastActivity = performance.now(); });
  h.addEventListener('pointermove', e => { if (!drag) return; const dx = e.clientX - drag.x, dy = e.clientY - drag.y; if (Math.hypot(dx, dy) > 3) drag.moved = true; if (drag.moved && S.atom) { S.hand = { theta: Math.min(PI, Math.max(0, drag.th - dy * 0.012)), phi: (drag.ph + dx * 0.012 + 4 * PI) % (2 * PI) }; if (S.outcome >= 0) { S.outcome = -1; S.collapse = null; S.collapseT = 0; S.reprepareAt =  … [line shortened here: 587 characters; full line on GitHub]
  const up = e => { if (!drag) return; if (!drag.moved) measure(); else if (S.hand && !S.hold) { S.relaxFrom = { t0: performance.now(), theta: S.hand.theta, phi: S.hand.phi }; S.theta = S.hand.theta; S.phi = S.hand.phi; S.hand = null; } drag = null; updateHUD(true); };
  h.addEventListener('pointerup', up); h.addEventListener('pointercancel', up);
  // canvas: tap picks an entry; horizontal swipe walks the conduction band; wheel zooms; mouse drag pans
  let cd = null; canvas.addEventListener('pointerdown', e => { cd = { x: e.clientX, y: e.clientY, moved: false, vx: S.view.x, vy: S.view.y, t: performance.now() }; });
  canvas.addEventListener('pointermove', e => { if (!cd) return; const dx = e.clientX - cd.x, dy = e.clientY - cd.y; if (Math.hypot(dx, dy) > 6) cd.moved = true; if (cd.moved && e.pointerType === 'mouse') { S.view.x = cd.vx + dx * DPR; S.view.y = cd.vy + dy * DPR; } });
  canvas.addEventListener('pointerup', e => { if (!cd) return; const dx = e.clientX - cd.x, dy = e.clientY - cd.y; const rect = canvas.getBoundingClientRect(); if (!cd.moved) pickAt(e.clientX - rect.left, e.clientY - rect.top); else if (e.pointerType !== 'mouse' && Math.abs(dx) > 40 && Math.abs(dx) > Math.abs(dy)) walkBand(dx < 0 ? 1 : -1); cd = null; });
  canvas.addEventListener('wheel', e => { e.preventDefault(); const f = Math.exp(-e.deltaY * 0.001); S.view.z = Math.min(8, Math.max(0.5, S.view.z * f)); }, { passive: false });
  // keyboard: arrows walk the conduction band, a bare Enter measures — only when no control has focus (a button, input, select or link keeps its own Enter)
  window.addEventListener('keydown', e => { const t = e.target; if (t === search) return; if (t && t !== document.body && t !== canvas && t.closest && t.closest('button,input,select,a,textarea,[contenteditable]')) return; if (e.key === 'ArrowRight') walkBand(1); else if (e.key === 'ArrowLeft') walkBand(-1); else if (e.key === 'Enter' && S.atom) measure(); });
  window.addEventListener('resize', () => { if (S.contextLost) return; resize(); buildAtomGeometry(); if (S.twin) { if (S.twin.chosen) buildTwinPost(); else buildTwin(); } updateHUD(true); }); // a resize (or rotation) during a collapse keeps the chosen twin
  canvas.addEventListener('webglcontextlost', onContextLost); canvas.addEventListener('webglcontextrestored', onContextRestored);
}
function walkBand(dir) { S.bandPos = (S.bandPos + dir + D.band.length) % D.band.length; const a = D.atomByN.get(D.band[S.bandPos]); setFocus({ atom: a }); S.msg = `conduction band ${S.bandPos + 1}/${D.band.length}: #${a.n} ${a.name} (${a.class})`; updateHUD(true); }

function legend() {
  const el = $('#legend'); el.textContent = '';
  const all = document.createElement('button'); all.className = 'u-chip on'; all.textContent = 'all'; all.onclick = () => { S.focusCat = -1; S.focusBlock = -1; sel.value = ''; el.querySelectorAll('.u-chip').forEach(c => c.classList.remove('on')); all.classList.add('on'); }; el.appendChild(all);
  D.blocks.categories.forEach((c, i) => { const b = document.createElement('button'); b.className = 'u-chip'; const sw = document.createElement('i'); sw.style.background = c.colour; b.appendChild(sw); b.appendChild(document.createTextNode(`${c.id} (${fmt(D.blocks.blocks.filter(x => x.category === c.id).reduce((s, x) => s + x.families, 0))})`)); b.title = c.title; b.onclick = () => { S.focusCat = i  … [line shortened here: 556 characters; full line on GitHub]
  const off = document.createElement('button'); off.className = 'u-chip'; const osw = document.createElement('i'); osw.style.background = '#8b93a7'; off.appendChild(osw); off.appendChild(document.createTextNode(`off table (${fmt(D.offTable)})`)); off.onclick = () => { S.focusCat = D.NC; S.focusBlock = -1; el.querySelectorAll('.u-chip').forEach(x => x.classList.remove('on')); off.classList.add('on'  … [line shortened here: 426 characters; full line on GitHub]
  const sel = document.createElement('select'); sel.setAttribute('aria-label', 'focus a block'); const o0 = document.createElement('option'); o0.value = ''; o0.textContent = 'focus a block…'; sel.appendChild(o0);
  D.blocks.blocks.forEach((b, i) => { const o = document.createElement('option'); o.value = i; o.textContent = `${b.symbol} ${b.title} (${b.families})`; sel.appendChild(o); });
  sel.onchange = () => { if (sel.value === '') { S.focusBlock = -1; return; } S.focusBlock = +sel.value; S.focusCat = -1; el.querySelectorAll('.u-chip').forEach(x => x.classList.remove('on')); }; el.appendChild(sel);
}
function aboutPanel() {
  const p = $('#aboutPanel'); const t = D.electron.totals; const sm = D.entangled.soul_md;
  const pWith = D.random.edges.filter(e => e.p != null).length;
  p.innerHTML = `<b>What is exact and what is a picture.</b>
<div class="u-sub" style="margin-top:6px">Exact</div>
<ul style="margin:4px 0 4px 18px;padding:0">
<li>One normalised qubit cos(θ/2)|0&gt; + e<sup>iφ</sup> sin(θ/2)|1&gt; built from one atom's shell census: θ from its K/L/M caller counts, sin²(θ/2) = M/(K+L+M), read from the shell counts recorded for this atom in ${D.shellSource} — this page does not recompute them. |0&gt; HOME = the next caller sits in the atom's own repository (K+L shells); |1&gt; AWAY = the next caller sits in another reposi  … [line shortened here: 895 characters; full line on GitHub]
<li>The twin is sampled from a stated, seeded distribution; the page prints its tier, the rule and every probability used, including the effective probability of an ENTANGLED_MAYBE partner. Random-star weights are published p renormalised to sum to 1 (classical weights, nothing squared); when an atom has both maker-draw and stars-draw edges only the maker edges (the ones with p) are used and the H  … [line shortened here: 453 characters; full line on GitHub]
<li>Every line entry the buckets publish (${fmt(D.N)}) and every unique numbered line in LINES.md (${fmt(D.uniqN)}, ${D.linesMdStamp}) is resident on the GPU, each in one buffer, and drawn every frame, twice (principal and twin). ${fmt(D.uniqInFamily)} of the unique lines sit inside a function family, ${fmt(D.uniqOutside)} do not.</li>
</ul>
<div class="u-sub">Picture</div>
<ul style="margin:4px 0 4px 18px;padding:0">
<li>The twin star is the same buffers drawn point-by-point reflected through the centre (angle + π, same radius): a mirror image, deterministic. It is a picture of the singlet's antipodal correlation (spin up along n on one particle means spin down along n on the other); no second qubit is modelled and no measurement is made on the twin, so no correlation is computed.</li>
<li>Entangled states are one definition called from other repositories (the state register, file SOUL.md, ${fmt(sm.entanglements_listed)} of ${fmt(sm.entanglements_stated)} listed). The twin rule is this page's choice — on AWAY the defining repository, on HOME one of the called_from repositories at 1/N — a lookup in the pack, not a correlation between two measurements. No signal is involved becaus  … [line shortened here: 430 characters; full line on GitHub]
<li>φ is decorative: precession only marks "no test or proof calls this" (unpaired spin); the census spin flag (paired = a test or proof calls it) only sets whether φ precesses, and φ never enters the Born probability. At a pole φ is a global phase and is not shown.</li>
<li>Shells are directory/repo layers (K same directory, L same repository, M other repositories). "Tunnelling" in electron.json is the valence subset — a caller in a repository holding no copy (BONDS_WITH): ${fmt(D.atomsTunnelling)} of the ${fmt(t.atoms_shipped)} shipped atoms have one, ${fmt(D.atomsValence0)} have valence 0. M counts callers; valence counts repositories. The word "tunnel" appears  … [line shortened here: 471 characters; full line on GitHub]
<li>The 8-second timer is re-preparation, not decoherence.</li>
<li>No Bell test exists here: one qubit, one measurement basis, no second party; nothing on this page tests quantum mechanics.</li>
<li>Every shipped atom has a caller outside its home directory and repository: ${fmt(D.atomsWithM)} of ${fmt(t.atoms_shipped)} have M&gt;0 and ${fmt(D.atomsNoHome)} have K+L=0, so no pure |0&gt; data state can appear. ${fmt(D.distinctTriples)} distinct K/L/M triples occur among the ${fmt(t.atoms_shipped)} atoms; how star-maker counts them is not verified here. Only families whose name matches a sh  … [line shortened here: 602 characters; full line on GitHub]
<li>Random Star edges are prompts, not findings; p exists on ${pWith} of ${D.random.edges.length} edges; ${fmt(D.atomsBothDraws)} shipped atoms have edges in both draws.</li>
<li>Only ${fmt(t.atoms_shipped)} of ${fmt(t.atoms_in_star)} atoms and ${fmt(sm.entanglements_listed)} of ${fmt(sm.entanglements_stated)} entanglements are shipped. State numbers (electron census) and family keys (code buckets) are different numberings; this page joins them by name only and says so in the HUD. Joins by "#N" between the state register (SOUL.md) / random.json and the census are check  … [line shortened here: 545 characters; full line on GitHub]
<li>index.json states ${fmt(D.provenance.checks.index_lines)} unique numbered lines and LINES.md carries ${fmt(D.uniqN)}; the published buckets carry ${fmt(D.N)} entries with ${fmt(D.distinct)} distinct numbers, which is the in-family part. All are printed; none is invented.</li>
<li>Line text is never shown unless fetched from GitHub at the pinned commit on demand (the classical cable); a line outside every family has no family record and therefore no known source place — nothing is fetched for it.</li>
<li>A tap on a sea point steers only (focus, highlight, lines panel); it never measures. Measurement is the measure button, a tap on the sphere, or Enter (a second Enter on the same search, or a bare Enter when no control has focus).</li>
</ul>`;
}

// ---------- no WebGL2: 2D fallback ----------
function fallback2D(reason) {
  const old = $('#gl'); const c = document.createElement('canvas'); c.id = 'fallback'; old.replaceWith(c); // a canvas that has given out a webgl2 context cannot give out a 2d one
  const ctx = c.getContext('2d'); const rect = c.getBoundingClientRect(); c.width = rect.width * DPR; c.height = rect.height * DPR;
  console.error('WebGL2 path failed:', reason);
  const cx = c.width / 2, cy = c.height / 2, r = 90 * DPR; ctx.fillStyle = '#07090d'; ctx.fillRect(0, 0, c.width, c.height);
  ctx.strokeStyle = '#00e5ff'; ctx.lineWidth = DPR; ctx.beginPath(); ctx.arc(cx, cy, r, 0, 2 * PI); ctx.stroke(); ctx.beginPath(); ctx.ellipse(cx, cy, r, r * 0.35, 0, 0, 2 * PI); ctx.stroke();
  const a = (D.focusDefault != null && D.atomByN.get(D.focusDefault)) || D.electron.atoms[0]; const th = atomTheta(a) || 0; ctx.fillStyle = '#fff'; ctx.beginPath(); ctx.arc(cx + Math.sin(th) * r, cy - Math.cos(th) * r, 5 * DPR, 0, 2 * PI); ctx.fill();
  [[0.55, a.shells.K], [0.85, a.shells.L], [1.25, a.shells.M]].forEach(([k, n]) => { ctx.strokeStyle = '#385464'; ctx.beginPath(); ctx.arc(cx, cy, r * k, 0, 2 * PI); ctx.stroke(); ctx.fillStyle = '#ffd54a'; for (let i = 0; i < Math.min(n, 512); i++) { const an = 2 * PI * i / n; ctx.beginPath(); ctx.arc(cx + Math.cos(an) * r * k, cy + Math.sin(an) * r * k, 2 * DPR, 0, 2 * PI); ctx.fill(); } });
  ctx.fillStyle = '#d8dee9'; ctx.font = `${12 * DPR}px ui-monospace,Menlo,Consolas,monospace`; ctx.textAlign = 'center';
  ctx.fillText(`#${a.n} ${a.name} · K${a.shells.K} L${a.shells.L} M${a.shells.M} · θ=${(th * 180 / PI).toFixed(1)}° · ${a.class} · spin ${a.spin}`, cx, cy + r * 1.5 + 20 * DPR);
  ctx.fillText(`The sea of ${fmt(D.N)} line entries and the ${fmt(D.uniqN)} unique lines need WebGL2 (${reason}). This 2D canvas shows only the focus atom.`, cx, cy + r * 1.5 + 40 * DPR);
  $('#hud').textContent = `renderer: none (WebGL2 unavailable: ${reason}) · on GPU: 0 unique numbered lines + 0 family-line entries · the sea needs WebGL2`;
  $('#sphereHandle').hidden = true;
}

// ---------- boot ----------
(async function main() {
  try {
    await loadData();
    D.maxLC = Math.max(...D.families.map(f => f.lineCount));
    $('#count').textContent = `${fmt(D.blocks.blocks.length)} named blocks · ${fmt(D.families.length)} function families · ${fmt(D.N)} line entries in ${fmt(D.provenance.checks.buckets_fetched)} buckets (${fmt(D.distinct)} distinct numbered lines) · ${fmt(D.uniqN)} unique numbered lines in LINES.md (${D.linesMdStamp}): ${fmt(D.uniqInFamily)} inside a function family, ${fmt(D.uniqOutside)} not · in  … [line shortened here: 457 characters; full line on GitHub]
    G.pal = D.blocks.categories.map(c => hex(c.colour)).concat([hex('#8b93a7')]); G.palFlat = new Float32Array(G.pal.flat());
    aboutPanel(); renderRecord();
    const am = D.provenance.amendments && D.provenance.amendments.length ? D.provenance.amendments[D.provenance.amendments.length - 1].utc : null;
    $('#foot').textContent = `202609142202 quantum-twin-star · pack built ${D.provenance.built_utc}${am ? ' · pack amended ' + am : ''} from ${D.provenance.stars_base} and raw.githubusercontent.com/Ventusltd/star-maker@${D.provenance.star_maker_commit.slice(0, 7)} · GLOBALGRID2050`;
    canvas = $('#gl');
    let ok = false, why = '';
    try { D.rin = 0.5; buildLayout(); legend(); ok = initGL(); if (!ok) why = 'getContext("webgl2") returned null'; } catch (e) { why = e.message; ok = false; }
    if (!ok) { fallback2D(why); return; }
    const dbg = gl.getExtension('WEBGL_debug_renderer_info');
    S.renderer = dbg ? gl.getParameter(dbg.UNMASKED_RENDERER_WEBGL) : (gl.getParameter(gl.RENDERER) || 'renderer masked by browser');
    S.lastDrawCalls = 0;
    resize(); wireUI();
    const def = D.focusDefault != null ? D.atomByN.get(D.focusDefault) : null;
    if (def) { setFocus({ atom: def }); S.bandPos = Math.max(0, D.band.indexOf(def.n)); S.msg = `default focus: state #${def.n} ${def.name} (electron/graph.json focus_default "${D.electron.focus_default}", shipped in electron.json) · band: ${D.bandNote}`; }
    else { setFocus({ famIdx: 0 }); S.msg = `no focus_default shipped in electron.json (${JSON.stringify(D.electron.focus_default)}): showing the first family`; }
    requestAnimationFrame(frame);
    window.__qts = { S, G, D, B, familyPos, DPR, gl, uniqIndex }; // lab handle for the headless proof script; reads only (gl is exposed so a proof can provoke a context loss)
    // deep link
    if (location.hash.startsWith('#family=')) doSearch('#' + location.hash.slice(8));
    else if (location.hash.startsWith('#line=')) doSearch('line ' + location.hash.slice(6));
  } catch (e) { fail(`Could not load live data: ${e.message}. Check the internet connection and reload.`); $('#count').textContent = 'pack could not be loaded'; console.error(e); }
})();

Particle

A JavaScript module in the lenses folder of GlobalGrid2050. It is built from the put step (`put`).

transformglobalgrid2050 / testcode/202609142225/lenses/particle.js · lines 1–51 of 51 · version 2026-09-14 22:25 · Not reached from any entry point (candidate for review)

What it does
It calculates its inputs. Defines put.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Downstream impact
Used directly by 1 file: UI (globalgrid2050).
What it achieves
Lens particle — from v03-particle-universe (GRAMMAR §7 particle).
Why it matters
Imported by UI.
Application
globalgrid2050 · testcode/202609142225/lenses · JavaScript module
Uses
none found
Used by
imported by UI (import)
Produces
put
Defines here
put
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609142225/lenses/particle.js:1-51 · blob aa90739dbfed02e51052186110b3cd13d7a45019 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: unreached_review
/* lens particle — from v03-particle-universe (GRAMMAR §7 particle). Stars in 12 sectors; families orbit the open block (u_orbit). */
const TAU = Math.PI * 2;

export default {
  id: 'particle',
  from: 'v03-particle-universe',
  wants: ['block', 'group', 'family', 'category', 'repo'],
  always: ['block', 'group', 'category', 'repo'],
  draws: ['depends on', 'uses', 'used by', 'shared line', 'random link', 'entangled'],
  curve: { mode: 'bow', bow: 0.2 },
  hint(core, view) { return view.open >= 0 ? 'Every block is a star in its category sector; the families of the open block orbit it.' : 'Every block is a star in its category sector; repositories sit on the rim. Tap a star to open it.'; },
  simplify(width) { return width <= 600 ? { rings: 2, tooltip: false } : { rings: 4, tooltip: true }; },
  camera() { return { pan: true, zoom: [0.5, 6], rotate: false }; },
  layout(core, view, out) {
    const { w, h } = view, S = Math.min(w, h), cx = w / 2, cy = h / 2, nc = core.range.cat[1] - core.range.cat[0], span = TAU / nc;
    const put = (i, r, a) => { out[2 * i] = cx + r * Math.cos(a); out[2 * i + 1] = cy + r * Math.sin(a); };
    const [b0, b1] = core.range.block; const perCat = new Map(); for (let i = b0; i < b1; i++) { const c = core.cat[i]; if (!perCat.has(c)) perCat.set(c, []); perCat.get(c).push(i); }
    for (const [c, list] of perCat) { const a0 = c * span - Math.PI / 2, n = list.length; list.forEach((i, k) => { const r = (0.12 + 0.36 * Math.pow((k + 1) / (n + 1), 0.8)) * 1.05 * S; const a = a0 + span * (0.15 + 0.7 * ((k * 0.618) % 1)); put(i, r, a); }); }
    for (let c = core.range.cat[0]; c < core.range.cat[1]; c++) put(c, 0.05 * S, (c - core.range.cat[0] + 0.5) * span - Math.PI / 2);
    const [g0, g1] = core.range.group; for (let i = g0; i < g1; i++) put(i, 0.52 * S, (i - g0 + 0.5) * TAU / (g1 - g0) - Math.PI / 2);
    const [r0, r1] = core.range.repo; for (let i = r0; i < r1; i++) put(i, 0.58 * S, (i - r0 + 0.5) * TAU / (r1 - r0) - Math.PI / 2);
    let orbit = null;
    if (view.open >= 0 && out[2 * view.open] === out[2 * view.open]) { for (const f of core.familiesOf(view.open)) { out[2 * f] = out[2 * view.open]; out[2 * f + 1] = out[2 * view.open + 1]; } orbit = { parent: view.open, rings: view.params.rings || 4 }; }
    else if (view.open >= 0) { for (const f of core.familiesOf(view.open)) { out[2 * f] = out[2 * view.open]; out[2 * f + 1] = out[2 * view.open + 1]; } orbit = { parent: view.open, rings: view.params.rings || 4 }; }
    return { bounds: [cx - 0.6 * S, cy - 0.6 * S, cx + 0.6 * S, cy + 0.6 * S], home: { pan: [0, 0], zoom: 1, rotate: 0 }, orbit };
  },
  edges(core, view) {
    const a = [], b = [], kind = [], cls = [], w = [], o = view.open, f = view.focus, E = core.edges;
    if (o >= 0) {
      for (const t of core.edgesOf(o, 1, 'out')) { a.push(o); b.push(t); kind.push(1); cls.push(2); w.push(1); }
      for (const s of core.edgesOf(o, 1, 'in')) { a.push(s); b.push(o); kind.push(3); cls.push(2); w.push(1); }
    }
    if (f >= 0 && core.cls[f] === 4) {
      // uses threads cross to the star that holds the used family
      for (const t of core.edgesOf(f, 2, 'out')) { const p = core.parent[t]; if (p >= 0 && p !== o) { a.push(f); b.push(p); kind.push(2); cls.push(2); w.push(1); } else if (p === o) { a.push(f); b.push(t); kind.push(2); cls.push(2); w.push(1); } }
      for (const s of core.edgesOf(f, 2, 'in')) { const p = core.parent[s]; if (p >= 0 && p !== o) { a.push(p); b.push(f); kind.push(3); cls.push(2); w.push(1); } else if (p === o) { a.push(s); b.push(f); kind.push(3); cls.push(2); w.push(1); } }
      for (const e of core.edgeIds(f, 4, 'both')) { const t = E.a[e] === f ? E.b[e] : E.a[e], p = core.parent[t]; a.push(f); b.push(p === o ? t : p); kind.push(4); cls.push(2); w.push(E.w[e]); }
      for (const e of core.edgeIds(f, 5, 'both')) { const t = E.a[e] === f ? E.b[e] : E.a[e], p = core.parent[t]; a.push(f); b.push(p === o ? t : p); kind.push(5); cls.push(2); w.push(E.w[e]); }
      for (const t of core.edgesOf(f, 6, 'out')) { a.push(f); b.push(t); kind.push(6); cls.push(2); w.push(1); }
    }
    for (const r of view.recipe) if (core.cls[r] === 2) for (const t of core.edgesOf(r, 1, 'out')) if (view.recipe.includes(t)) { a.push(r); b.push(t); kind.push(1); cls.push(2); w.push(1); }
    return { a: Uint32Array.from(a.slice(0, 4000)), b: Uint32Array.from(b.slice(0, 4000)), kind: Uint8Array.from(kind.slice(0, 4000)), cls: Uint8Array.from(cls.slice(0, 4000)), w: Float32Array.from(w.slice(0, 4000)) };
  },
  labels(core, view, max) {
    const out = [];
    for (let i = 0; i < core.N && out.length < max; i++) if ((view.lit[i] & 15) && core.cls[i] !== 4) out.push(i);
    for (let i = core.range.block[0]; i < core.range.block[1] && out.length < max; i++) if (2 + 0.55 * Math.sqrt(core.mass[i]) > 9 && !out.includes(i)) out.push(i);
    for (let c = core.range.cat[0]; c < core.range.cat[1] && out.length < max; c++) if (!out.includes(c)) out.push(c);
    return Uint32Array.from(out);
  },
};

Star

A JavaScript file in the testcode folder of GlobalGrid2050 that draws map (`drawMap`) (units: kWh), covering postcodes, using SHA-256. It draws map (`drawMap`) and maps lens (`mapLens`).

renderglobalgrid2050 / testcode/202609150125/star.js · lines 1–297 of 297 · version 2026-09-15 01:25 · Not reached from any entry point (candidate for review) · pattern catName (shared by 3 files)

What it does
It draws postcodes. Defines 22 functions or classes, including el, n, money, esc, withheld. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: postcodes. README: "`index.html` + `star.js` + `style.css` — three lenses (map, sector, energy) that compute every number from the JSON at run time."
Inputs & outputs
Out: canvas drawing.
What it achieves
Sector Star — testcode/. Every number on this page is read from `data/*.json` at run time; none is typed into the HTML. It responds to resize events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · testcode/202609150125 · script
Uses
none found
Used by
none found
Produces
el, n, money, esc, withheld, catName, catColour, q, setQ, lens, countsLine, drawMap
Defines here
el, n, money, esc, withheld, catName, catColour, q, setQ, lens, countsLine, drawMap, px, py, catRow, districtCard, mapLens, sectorLens, energyLens, footer, render, load
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609150125/star.js:1-297 · blob 2d004852af8751732d74c69707b32fbe2ea15c2a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: experimental · users: none · canonical: unreached_review
/* Sector Star — testcode/202609150125.
   Every number on this page is read from data/*.json at run time; none is typed into the HTML.
   No randomness: this file contains no Math.random and no other random source.
   URL keys are permanent: ?lens=map|sector|energy&district=<outcode>&sector=<SIC code>  */
'use strict';

var D = { sectors: null, geography: null, provenance: null };
var CATS = ['farmers', 'manufacturers', 'other_high_energy', 'rest'];
var LENSES = ['map', 'sector', 'energy'];
var el = function (id) { return document.getElementById(id); };
var nf = new Intl.NumberFormat('en-GB');
var n = function (v) { return v === null || v === undefined ? null : nf.format(Math.round(v)); };

function money(v) { return v === null || v === undefined ? null : '£' + nf.format(Math.round(v)); }
function esc(s) { return String(s === null || s === undefined ? '' : s).replace(/[&<>"]/g, function (c) { return ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]; }); }
function withheld(reason) { return '<span class="withheld">withheld (' + esc(reason) + ')</span>'; }
function catName(id) { var c = (D.sectors.categories || []).filter(function (x) { return x.id === id; })[0]; return c ? c.name : id; }
function catColour(id) { return (D.sectors.category_colours || {})[id] || '#8b93a7'; }

/* ---- URL state (permanent keys only) ---- */
function q() { return new URLSearchParams(location.search); }
function setQ(k, v) {
  var p = q();
  if (v === null || v === undefined || v === '') p.delete(k); else p.set(k, v);
  history.replaceState(null, '', location.pathname + (p.toString() ? '?' + p : ''));
  render();
}
function lens() { var l = q().get('lens'); return LENSES.indexOf(l) >= 0 ? l : 'map'; }

/* ---- the count sentence: one string, built from the JSON ---- */
function countsLine() {
  var s = D.sectors, g = D.geography, p = D.provenance;
  var dates = (p.sources[1] && p.sources[1].months) || [];
  var built = (p.built_utc || '').slice(0, 16).replace('T', ' ');
  return nf.format(s.population) + ' qualifying companies · ' +
    nf.format(s.sections.length) + ' SIC sections · ' +
    nf.format(s.divisions.length) + ' divisions · ' +
    nf.format(s.groups.length) + ' groups · ' +
    nf.format(g.districts.length) + ' postcode districts · ' +
    nf.format(g.regions.length) + ' regions · ' +
    nf.format(s.categories.filter(function (c) { return c.id === 'farmers'; })[0].count) + ' farmers · ' +
    nf.format(s.categories.filter(function (c) { return c.id === 'manufacturers'; })[0].count) + ' manufacturers · ' +
    nf.format(s.categories.filter(function (c) { return c.id === 'other_high_energy'; })[0].count) + ' other high energy · ' +
    'accounts ' + (dates.length ? dates.length + ' monthly files' : 'not stated') +
    ', register ' + esc(p.sources[0].snapshot) + ' · data ' + built + ' UTC';
}

/* ---- map lens: outcode centroids on a plain equirectangular canvas ---- */
function drawMap() {
  var c = el('map'); if (!c) return;
  var W = c.clientWidth, H = Math.round(W * 1.15), dpr = window.devicePixelRatio || 1;
  c.width = Math.round(W * dpr); c.height = Math.round(H * dpr);
  c.style.height = H + 'px';
  var x = c.getContext('2d'); x.setTransform(dpr, 0, 0, dpr, 0, 0);
  x.clearRect(0, 0, W, H);
  var pts = D.geography.districts.filter(function (d) { return d.lat !== null && d.lon !== null; });
  if (!pts.length) return;
  var la = pts.map(function (d) { return d.lat; }), lo = pts.map(function (d) { return d.lon; });
  var la0 = Math.min.apply(null, la), la1 = Math.max.apply(null, la);
  var lo0 = Math.min.apply(null, lo), lo1 = Math.max.apply(null, lo);
  var k = Math.cos((la0 + la1) / 2 * Math.PI / 180);
  var pad = 14;
  var sx = (W - 2 * pad) / ((lo1 - lo0) * k), sy = (H - 2 * pad) / (la1 - la0);
  var s = Math.min(sx, sy);
  var ox = pad + ((W - 2 * pad) - (lo1 - lo0) * k * s) / 2;
  var oy = pad + ((H - 2 * pad) - (la1 - la0) * s) / 2;
  var px = function (d) { return ox + (d.lon - lo0) * k * s; };
  var py = function (d) { return oy + (la1 - d.lat) * s; };
  var maxN = pts.reduce(function (a, d) { return Math.max(a, d.count); }, 1);
  window.__hit = [];
  pts.slice().sort(function (a, b) { return b.count - a.count; }).forEach(function (d) {
    var best = 'rest', bv = -1;
    CATS.forEach(function (cid) { var v = d.categories[cid]; if (v !== null && v > bv) { bv = v; best = cid; } });
    var r = Math.max(2.2, Math.sqrt(d.count / maxN) * 15);
    var X = px(d), Y = py(d);
    x.beginPath(); x.arc(X, Y, r, 0, Math.PI * 2);
    x.fillStyle = catColour(best); x.globalAlpha = 0.55; x.fill();
    x.globalAlpha = 1; x.lineWidth = 0.6; x.strokeStyle = catColour(best); x.stroke();
    window.__hit.push({ d: d, x: X, y: Y, r: Math.max(r, 11) });
  });
  var home = D.geography.home_centroid;
  if (home && home.lat !== null) {
    var hx = ox + (home.lon - lo0) * k * s, hy = oy + (la1 - home.lat) * s;
    x.globalAlpha = 1; x.strokeStyle = '#d8dee9'; x.lineWidth = 1;
    x.beginPath(); x.arc(hx, hy, 6, 0, Math.PI * 2); x.stroke();
    x.beginPath(); x.moveTo(hx - 10, hy); x.lineTo(hx + 10, hy); x.moveTo(hx, hy - 10); x.lineTo(hx, hy + 10); x.stroke();
  }
  c.onclick = function (ev) {
    var b = c.getBoundingClientRect(), mx = ev.clientX - b.left, my = ev.clientY - b.top, pick = null, pd = 1e9;
    window.__hit.forEach(function (h) {
      var dd = (h.x - mx) * (h.x - mx) + (h.y - my) * (h.y - my);
      if (dd <= h.r * h.r && dd < pd) { pd = dd; pick = h.d; }
    });
    if (pick) setQ('district', pick.outcode);
  };
}

function catRow(o) {
  return CATS.map(function (cid) {
    var v = o.categories[cid];
    return '<tr><td><span class="dot" style="background:' + catColour(cid) + '"></span> ' + esc(catName(cid)) +
      '</td><td class="n">' + (v === null ? withheld('n &lt; 5') : n(v)) + '</td></tr>';
  }).join('');
}

function districtCard(code) {
  var d = D.geography.districts.filter(function (x) { return x.outcode === code; })[0];
  if (!d) return '<div class="panel"><h2>District ' + esc(code) + '</h2><p class="k">Not published: ' +
    'either it is not in the qualifying population, or it holds fewer than 5 companies and is withheld.</p></div>';
  return '<div class="panel"><h2>Postcode district ' + esc(d.outcode) + '</h2>' +
    '<p class="k">' + esc(d.region || 'region not stated') + (d.county ? ' · ' + esc(d.county) : '') +
    (d.miles_from_ha4 === null || d.miles_from_ha4 === undefined ? '' : ' · ' + d.miles_from_ha4 + ' miles from HA4 (straight line) · ' + esc(d.band)) + '</p>' +
    '<table><tr><th>companies</th><td class="n">' + n(d.count) + '</td></tr>' + catRow(d) +
    (d.folded_into_other ? '<tr><td class="withheld">folded into other (n &lt; 5)</td><td class="n">' + n(d.folded_into_other) + '</td></tr>' : '') +
    '<tr><th>median net worth</th><td class="n">' + (d.median_net_worth_gbp === null ? withheld('n &lt; 5') : money(d.median_net_worth_gbp)) + '</td></tr>' +
    '<tr><th>median cash</th><td class="n">' + (d.median_cash_gbp === null ? withheld('n &lt; 5') : money(d.median_cash_gbp)) + '</td></tr>' +
    '<tr><th>filing SECR energy</th><td class="n">' + (d.n_filing_energy ? n(d.n_filing_energy) : 'not filed') + '</td></tr>' +
    '</table><p><button onclick="setQ(\'district\',\'\')" style="min-height:44px">close</button></p></div>';
}

function mapLens() {
  var g = D.geography, dcode = q().get('district');
  var bands = g.distance_bands.map(function (b) {
    return '<tr><td>' + esc(b.band) + '</td><td class="n">' + n(b.count) + '</td>' +
      CATS.map(function (c) { return '<td class="n">' + (b.categories[c] === null ? '&lt;5' : n(b.categories[c])) + '</td>'; }).join('') + '</tr>';
  }).join('');
  var regions = g.regions.map(function (r) {
    return '<tr><td>' + esc(r.region) + '</td><td class="n">' + n(r.count) + '</td>' +
      CATS.map(function (c) { return '<td class="n">' + (r.categories[c] === null ? '&lt;5' : n(r.categories[c])) + '</td>'; }).join('') + '</tr>';
  }).join('');
  var top = g.districts.slice(0, 40).map(function (d) {
    return '<tr class="row" onclick="setQ(\'district\',\'' + esc(d.outcode) + '\')"><td>' + esc(d.outcode) + '</td>' +
      '<td>' + esc(d.region || '—') + '</td><td class="n">' + n(d.count) + '</td>' +
      '<td class="n">' + (d.categories.farmers === null ? '&lt;5' : n(d.categories.farmers)) + '</td>' +
      '<td class="n">' + (d.categories.manufacturers === null ? '&lt;5' : n(d.categories.manufacturers)) + '</td>' +
      '<td class="n">' + (d.categories.other_high_energy === null ? '&lt;5' : n(d.categories.other_high_energy)) + '</td></tr>';
  }).join('');
  return '<canvas id="map" aria-label="postcode district centroids sized by company count"></canvas>' +
    '<p class="k">Each disc is one postcode district, area proportional to its company count, coloured by its largest ' +
    'category. The cross is HA4. Districts with fewer than 5 companies are not drawn: ' + n(g.districts_withheld_n_lt_5) +
    ' companies sit in those withheld districts. Tap a disc for the district card.</p>' +
    (dcode ? districtCard(dcode) : '') +
    '<div class="panel"><h2>By straight-line distance from HA4</h2><div class="wrap"><table>' +
    '<tr><th>band</th><th class="n">companies</th><th class="n">farm</th><th class="n">mfg</th><th class="n">high</th><th class="n">rest</th></tr>' +
    bands + '</table></div></div>' +
    '<div class="panel"><h2>By England region and Wales</h2><div class="wrap"><table>' +
    '<tr><th>region</th><th class="n">companies</th><th class="n">farm</th><th class="n">mfg</th><th class="n">high</th><th class="n">rest</th></tr>' +
    regions + '</table></div><p class="k">' + n(g.regions_withheld_n_lt_5) + ' companies sit in regions with fewer than 5 and are withheld.</p></div>' +
    '<div class="panel"><h2>Districts with the largest counts</h2><div class="wrap"><table>' +
    '<tr><th>district</th><th>region</th><th class="n">all</th><th class="n">farm</th><th class="n">mfg</th><th class="n">high</th></tr>' +
    top + '</table></div><p class="k">Counts only. No maximum and no top-N of any money figure is published anywhere on this page.</p></div>';
}

function sectorLens() {
  var s = D.sectors, code = q().get('sector');
  var max = s.divisions.reduce(function (a, d) { return Math.max(a, d.count); }, 1);
  var bars = s.divisions.map(function (d) {
    var w = (d.count / max * 100).toFixed(2);
    var med = d.net_worth_gbp && d.net_worth_gbp.median !== undefined ? money(d.net_worth_gbp.median) : withheld('n &lt; 5');
    return '<tr class="row" onclick="setQ(\'sector\',\'' + esc(d.code) + '\')"><td>' +
      '<b>' + esc(d.code) + '</b> ' + esc(d.name) +
      '<div class="bar" style="width:' + w + '%;background:' + catColour(d.category) + '"></div></td>' +
      '<td class="n">' + n(d.count) + '</td><td class="n">' + med + '</td></tr>';
  }).join('');
  var card = '';
  if (code) {
    var d = s.divisions.filter(function (x) { return x.code === code; })[0];
    if (d) {
      var gs = s.groups.filter(function (g) { return g.division === code; });
      card = '<div class="panel"><h2>' + esc(d.code) + ' ' + esc(d.name) + '</h2>' +
        '<p class="k">section ' + esc(d.section) + ' · ' + esc(catName(d.category)) + ' · ' +
        (d.share * 100).toFixed(2) + '% of the population</p><div class="wrap"><table>' +
        '<tr><th>companies</th><td class="n">' + n(d.count) + '</td></tr>' +
        ['profit_measure_gbp', 'net_worth_gbp', 'cash_gbp', 'wages_gbp', 'employees'].map(function (k) {
          var c = d[k]; if (!c) return '';
          var lbl = k.replace(/_gbp$/, '').replace(/_/g, ' ');
          var m = c.median === undefined ? withheld(c.withheld || 'n &lt; 5') : (k === 'employees' ? n(c.median) : money(c.median));
          var sum = c.sum === null || c.sum === undefined ? withheld(c.sum_withheld || 'n &lt; 10') : (k === 'employees' ? n(c.sum) : money(c.sum));
          return '<tr><th>median ' + esc(lbl) + '</th><td class="n">' + m + '</td></tr>' +
            '<tr><th>total ' + esc(lbl) + '</th><td class="n">' + sum + '</td></tr>';
        }).join('') +
        '<tr><th>filing SECR energy</th><td class="n">' + (d.secr.n_filing_energy || 'not filed') + '</td></tr>' +
        '</table></div><h2 style="margin-top:12px">Groups</h2><div class="wrap"><table>' +
        '<tr><th>group</th><th>classes</th><th class="n">companies</th></tr>' +
        gs.map(function (g) {
          return '<tr><td>' + esc(g.code) + '</td><td class="k">' +
            g.classes.slice(0, 6).map(function (c) { return esc(c.title || c.code) + ' (' + n(c.count) + ')'; }).join('; ') +
            (g.classes_withheld_n_lt_5 ? '; <span class="withheld">' + n(g.classes_withheld_n_lt_5) + ' in classes withheld (n &lt; 5)</span>' : '') +
            '</td><td class="n">' + n(g.count) + '</td></tr>';
        }).join('') + '</table></div>' +
        '<p><button onclick="setQ(\'sector\',\'\')" style="min-height:44px">close</button></p></div>';
    }
  }
  var cats = s.categories.map(function (c) {
    return '<tr><td><span class="dot" style="background:' + c.colour + '"></span> ' + esc(c.name) +
      '<div class="k">' + esc(c.rule) + '</div></td><td class="n">' + n(c.count) + '</td><td class="n">' +
      (c.share * 100).toFixed(1) + '%</td></tr>';
  }).join('');
  return '<div class="panel"><h2>Sector categories</h2><div class="wrap"><table>' +
    '<tr><th>category</th><th class="n">companies</th><th class="n">share</th></tr>' + cats + '</table></div></div>' +
    card +
    '<div class="panel"><h2>By SIC 2007 division</h2><div class="wrap"><table>' +
    '<tr><th>division</th><th class="n">companies</th><th class="n">median net worth</th></tr>' + bars + '</table></div>' +
    '<p class="k">' + n(s.divisions_withheld_or_unknown) + ' companies are in divisions with fewer than 5 or with no parsable SIC code and are withheld. Tap a division for its groups.</p></div>';
}

function energyLens() {
  var s = D.sectors;
  var rows = s.sections.map(function (x) {
    var e = x.secr;
    return '<tr><td>' + esc(x.code) + ' ' + esc(x.name) + '</td><td class="n">' + n(x.count) + '</td>' +
      '<td class="n">' + (e.n_filing_energy || 0) + '</td>' +
      '<td class="n">' + (e.energy_kwh.median === undefined ? withheld(e.energy_kwh.withheld || 'n &lt; 5') : n(e.energy_kwh.median)) + '</td>' +
      '<td class="n">' + (e.energy_kwh.sum === null || e.energy_kwh.sum === undefined ? withheld(e.energy_kwh.sum_withheld || 'not filed') : n(e.energy_kwh.sum)) + '</td></tr>';
  }).join('');
  var catrows = s.categories.map(function (c) {
    var e = c.secr;
    return '<tr><td><span class="dot" style="background:' + c.colour + '"></span> ' + esc(c.name) + '</td>' +
      '<td class="n">' + n(c.count) + '</td><td class="n">' + (e.n_filing_energy || 0) + '</td>' +
      '<td class="n">' + (e.energy_kwh.median === undefined ? withheld(e.energy_kwh.withheld || 'n &lt; 5') : n(e.energy_kwh.median)) + '</td>' +
      '<td class="n">' + (e.n_filing_co2 || 0) + '</td></tr>';
  }).join('');
  var total = s.sections.reduce(function (a, x) { return a + (x.secr.n_filing_energy || 0); }, 0);
  return '<div class="panel"><h2>Filed SECR energy — a filed subset, not the population</h2>' +
    '<p class="k">' + n(total) + ' of ' + n(s.population) + ' companies have a Streamlined Energy and Carbon ' +
    'Reporting energy figure in the filed accounts this build read. Overall median ' +
    (s.secr_overall_median_kwh === null ? 'not available' : n(s.secr_overall_median_kwh) + ' kWh') +
    '. Every figure below describes only the companies that filed one; it is not a population estimate, ' +
    'and it must not be scaled up.</p>' +
    '<div class="wrap"><table><tr><th>category</th><th class="n">companies</th><th class="n">filing kWh</th>' +
    '<th class="n">median kWh</th><th class="n">filing CO2</th></tr>' + catrows + '</table></div></div>' +
    '<div class="panel"><h2>By SIC 2007 section</h2><div class="wrap"><table>' +
    '<tr><th>section</th><th class="n">companies</th><th class="n">filing</th><th class="n">median kWh</th><th class="n">total kWh</th></tr>' +
    rows + '</table></div><p class="k">A total is published only where at least 10 companies filed and the largest ' +
    'single contributor is under half the sum; otherwise it says withheld.</p></div>' +
    '<div class="panel"><h2>Network regions</h2>' +
    (function () {
      var g = D.geography.grid_regions;
      if (!g || !g.dno || !g.dno.length) return '<p class="k">not available in this build</p>';
      return '<p class="k">' + esc(g.note) + '</p><div class="wrap"><table><tr><th>DNO / network region</th><th class="n">companies</th></tr>' +
        g.dno.map(function (r) { return '<tr><td>' + esc(r.dno) + '</td><td class="n">' + n(r.companies) + '</td></tr>'; }).join('') +
        '</table></div>';
    })() + '</div>';
}

function footer() {
  var p = D.provenance, s = D.sectors;
  var links = (p.links || []).map(function (l) {
    return '<div><b>' + esc(l.relation) + '</b> — <a href="' + esc(l.to) + '">' + esc(l.to) + '</a><br>' + esc(l.why) + '</div>';
  }).join('');
  return 'Sector Star · built ' + esc((p.built_utc || '').slice(0, 16).replace('T', ' ')) + ' UTC · ' +
    'sources: Companies House register snapshot ' + esc(p.sources[0].snapshot) + ' and ' +
    esc(String(p.sources[1].count_months)) + ' monthly accounts files; postcodes.io outcodes; UK SIC 2007.<br>' +
    'Qualifying rule: active England and Wales companies whose latest filed accounts show profit, ' +
    'balance sheet net worth or cash of £1,000,000 or more.<br>' +
    'Suppression: any group of fewer than 5 companies is withheld and folded into other; a sum is published only ' +
    'where at least 10 companies contribute and the largest single contributor is under 50% of it; no maximum and ' +
    'no top-N is ever published. Withheld cells this build: ' + n(p.suppression.tally.cells_withheld_n_lt_5) +
    '; withheld sums: ' + n(p.suppression.tally.sums_withheld_n_lt_10 + p.suppression.tally.sums_withheld_dominant_contributor + p.suppression.tally.sums_withheld_not_positive) + '.<br>' +
    'Energy: ' + n(p.counts.filing_secr_energy) + ' of ' + n(s.population) + ' companies filed a SECR energy figure, so every ' +
    'energy number here describes a filed subset, not the population, and must not be scaled up.<br>' +
    'No company name, registration number, address, full postcode or link appears in any file here. ' +
    'Data files: ' + p.outputs.map(function (o) { return esc(o.file) + ' ' + esc(o.sha256.slice(0, 12)); }).join(' · ') +
    '<div class="links"><b>links</b>' + links + '</div>';
}

function render() {
  var L = lens();
  el('tabs').innerHTML = LENSES.map(function (x) {
    return '<button role="tab" aria-selected="' + (x === L) + '" onclick="setQ(\'lens\',\'' + x + '\')">' + x + '</button>';
  }).join('');
  el('legend').innerHTML = (D.sectors.categories || []).map(function (c) {
    return '<span><i class="dot" style="background:' + c.colour + '"></i>' + esc(c.name) + '</span>';
  }).join('');
  el('counts').textContent = countsLine();
  el('view').innerHTML = L === 'sector' ? sectorLens() : L === 'energy' ? energyLens() : mapLens();
  el('foot').innerHTML = footer();
  if (L === 'map') drawMap();
}

function load(name) {
  return fetch('data/' + name + '.json', { cache: 'default' }).then(function (r) {
    if (!r.ok) throw new Error('data/' + name + '.json returned HTTP ' + r.status);
    return r.json();
  });
}

Promise.all([load('sectors'), load('geography'), load('provenance')]).then(function (r) {
  D.sectors = r[0]; D.geography = r[1]; D.provenance = r[2];
  window.SECTOR_STAR = D;
  render();
  var t = null;
  window.addEventListener('resize', function () { clearTimeout(t); t = setTimeout(function () { if (lens() === 'map') drawMap(); }, 150); });
}).catch(function (e) {
  el('counts').textContent = '';
  el('view').innerHTML = '<div class="fail">Could not load the data: ' + esc(e.message) + '. Check the connection and reload.</div>';
});