GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / kuiper-belt / /

Scale Logic and 5 more files

A JavaScript module in the learn the kuiper folder of Kuiper Belt that converts to fraction (`toFraction`), sets position (`setPosition`) and polar (`setPolar`) and calculates planar distances and angles.

700 lines of JavaScript and HTML from kuiper-belt, in 6 files. Topic: Kuiper, cosmos and drawing engines. Section 1524 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. Kuiper Belt — Index Page render · kuiper-belt / index.html lines 491–595
  2. Kuiper Law render · kuiper-belt / learn-the-kuiper/202610042225/kuiper-law.js lines 1–119
  3. Grid Test test · kuiper-belt / learn-the-kuiper/202610042346/modules/grid-test.html lines 1–17
  4. Strings Test test · kuiper-belt / learn-the-kuiper/202610042346/modules/strings-test.html lines 1–51
  5. Zoom Test test · kuiper-belt / learn-the-kuiper/202610042346/modules/zoom-test.html lines 1–16
  6. Scale Logic render · kuiper-belt / learn-the-kuiper/202610042346/scale-logic.js lines 1–392

Kuiper Belt — Index Page

A web page that converts to world (`toWorld`), steps anim (`stepAnim`), calculates planar distances and draws on a canvas. Published at https://ventusltd.github.io/kuiper-belt/.

Set aside from the main view: 100% of its lines are the same as testcode/wafer-development-environment/202609191345-proof-7/index.html (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 99% of lines shared with Wafer Development Environment — Proof 7 Page; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9982 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/wafer-development-environment/202609191345-proof-7/index.html:1-594 8f615def7fea7bab74c8921d09a47e9df280e481
  • sha256 82594c70efe2ba615ac50166594d3384e155872ca3350d91fa8060b42550e4e2
  • target sha256 425a03d53f4a5d77743f8c1cf67cfaa1b2bf47ffcf39be2d7e52339d3271bccb
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

renderkuiper-belt / index.html · lines 491–595 of 595 (continued from section 1523) · Entry point · pattern linesByRunningTotals (shared by 21 files)

What it does
It draws its content. Defines 39 functions or classes, including fmt, words, prog, U, tsv. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: form fields (user input). Out: web page; WebGL/WebGPU drawing.
Downstream impact
Used directly by 12 files: Apps Registry (kuiper-belt); Registry of All Content in Repos and Dependencies — Index Page (registry_of_all_content_in_repos_and_dependencies, https://ventusltd.github.io/registry_of_all_content_in_repos_and_dependencies/); Kuiper Law (kuiper-belt); Deep (kuiper-belt); and 8 more. Reached from 278 other entry points, including Iterations — 43 Registry Growth Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/43-registry-growth/); Iterations — 47 Federation Honesty Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/47-federation-honesty/); GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html). It is itself an entry point, published at https://ventusltd.github.io/kuiper-belt/.
What it achieves
It shows new (`showNew`) and is built from the fmt step (`fmt`) and the words step (`words`). Its `describe` function gives human readable address description from resolved address and repository metadata (VEDIC: explain). It responds to webglcontextlost, resize and pointerdown events.
Why it matters
Loaded by the Registry of All Content in Repos and Dependencies page in Registry of All Content in Repos and Dependencies at https://ventusltd.github.io/registry_of_all_content_in_repos_and_dependencies/ and 4 other pages. Also imported by 6 files, including Apps Registry, Kuiper Law and Deep. Checked by VEDIC Browser Smoke.
Application
kuiper-belt · / · page
VEDIC
EXPLAIN (GG2050-VEDIC-000040): Kuiper / Code navigation · Computer science / Interactive visualisation. resolved_address, repository_metadata → human_readable_address_description
VEDIC
RECENT (GG2050-VEDIC-000041): Kuiper / Code navigation · Computer science / Interactive visualisation. hours, ordered_commits → recent_band_animation_state
VEDIC
PERIOD (GG2050-VEDIC-000042): Kuiper / Code navigation · Computer science / Interactive visualisation. year, month_optional, day_optional, ordered_commits → commit_period_summary_or_null
Uses
none found
Used by
named by URL in Apps Registry (estate URL), linked from Registry of All Content in Repos and Dependencies — Index Page (link), named by URL in Kuiper Law (estate URL), named by URL in Deep (estate URL), named by URL in Radar (estate URL), named by URL in Start Here (estate URL), linked from Learn the Kuiper — Astra Codex Page (link), named by URL in Kuiper Law (estate URL), and 4 more
Produces
fmt, words, prog, U, tsv, narrow, resize, flyTo, layout, safeBox, homeCamera, home
Defines here
ev, lightTime, pinchNow, pointerGone
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
kuiper-belt@26fba12ab1b5bab8e71934ab86c58273e5f32682 index.html:491-595 · blob 57539a88d3df548c43e15a151b6935d406c5a158 · GitHub at these lines
State
achieves: code · context: readme_derived · stage: output · effects: dom, network · domain stage: agent_infra · users: ai_agent · canonical: duplicate_candidate
  const W = innerWidth, H = innerHeight, Rpx = Math.sqrt(SPACE)*zoom;
  const scx = (0 - cx)*zoom + W/2, scy = H/2 + cy*zoom;          // where the wafer's centre really is on screen
  const panels = []; let worst = 1e9;
  for (const id of ['top','hud','foot']) { const r = document.getElementById(id).getBoundingClientRect();
    const qx = Math.max(r.left, Math.min(scx, r.right)), qy = Math.max(r.top, Math.min(scy, r.bottom));
    const clear = Math.hypot(qx - scx, qy - scy) - Rpx;          // nearest point of the panel, less the rim radius
    panels.push({ panel:id, rect:[r.left, r.top, r.right, r.bottom].map(Math.round), clear_of_the_rim_px:Math.round(clear) });
    worst = Math.min(worst, clear); }
  const onScreen = scx - Rpx >= -0.5 && scx + Rpx <= W + 0.5 && scy - Rpx >= -0.5 && scy + Rpx <= H + 0.5;
  show(address(Math.floor(N/2))); layout();
  const cr = card.getBoundingClientRect();
  const cardFits = cr.left >= -0.5 && cr.top >= -0.5 && cr.right <= W + 0.5 && cr.bottom <= H + 0.5 && cr.width > 40 && cr.height > 20;
  const ev = (t, id, x, y) => cv.dispatchEvent(new PointerEvent(t, { pointerId:id, clientX:x, clientY:y, bubbles:true, pointerType:'touch' }));
  const z0 = zoom, cx0 = cx;                                     // one finger: the world must follow it
  ev('pointerdown', 11, Math.round(W*0.5), Math.round(H*0.5)); ev('pointermove', 11, Math.round(W*0.5) + 60, Math.round(H*0.5));
  const dragged = cx0 - cx; ev('pointerup', 11, Math.round(W*0.5) + 60, Math.round(H*0.5));
  const zA = zoom;                                               // two fingers: the distance between them must set the zoom
  ev('pointerdown', 21, Math.round(W*0.35), Math.round(H*0.5)); ev('pointerdown', 22, Math.round(W*0.65), Math.round(H*0.5));
  const spread = Math.round(W*0.65) - Math.round(W*0.35);
  ev('pointermove', 22, Math.round(W*0.35) + 2*spread, Math.round(H*0.5));
  const zB = zoom; ev('pointerup', 21, 0, 0); ev('pointerup', 22, 0, 0);
  // put the wafer back the way it was found: the test's own light is not part of the record
  { const h = homeCamera(); cx = h.x; cy = h.y; zoom = h.z; atHome = true; litRepo = -1; target = null;
    card.style.display = 'none'; dirty = true; draw(); }
  const T = { viewport:[W, H], narrow_layout:narrow(), wafer_centre_on_screen:[Math.round(scx), Math.round(scy)], wafer_radius_px:Math.round(Rpx),
    T1_no_permanent_panel_covers_the_wafer: worst >= 0, panels,
    T2_the_whole_wafer_is_on_the_screen: onScreen,
    T3_the_card_fits: cardFits, card_rect:[cr.left, cr.top, cr.right, cr.bottom].map(Math.round),
    T4_one_finger_drags: Math.abs(dragged - 60/z0) < 1e-6, dragged_world_units:+dragged.toFixed(6), expected_world_units:+(60/z0).toFixed(6),
    T5_two_fingers_pinch: zB > zA*1.8 && zB <= ZMAX + 1e-9, zoom_before_pinch:+zA.toFixed(6), zoom_after_pinch:+zB.toFixed(6) };
  T.PASS = T.T1_no_permanent_panel_covers_the_wafer && T.T2_the_whole_wafer_is_on_the_screen && T.T3_the_card_fits
        && T.T4_one_finger_drags && T.T5_two_fingers_pinch;
  window.__selftest = T; document.title = 'selftest ' + (T.PASS ? 'PASS' : 'FAIL');
}
// LIGHT A PERIOD. "2026-07" or "2026-07-14". Time order makes it one band, so the count is a
// difference of two running totals and the light is one annulus.
function lightTime(y, m, d){
  const t0 = Date.UTC(y, m ? m-1 : 0, d || 1)/1000, t1 = d ? t0 + 86400 : Date.UTC(m ? y : y+1, m ? m : 0, 1)/1000;
  const i0 = (commits[0].unix >= t0) ? 0 : findBy('unix', t0 - 1) + 1, i1 = (commits[0].unix >= t1) ? 0 : findBy('unix', t1 - 1) + 1;
  const label = y + (m ? '-' + String(m).padStart(2,'0') : '') + (d ? '-' + String(d).padStart(2,'0') : '');
  litRepo = -1; newFrom = -1; flash = 0; target = null; card.style.display = 'block';
  if (i1 <= i0) { litK = [-1,-1]; litCi = null; card.innerHTML = label + '\nsilence: no commit carries that date'; home(); dirty = true; return null; }
  const last = commits[i1-1], lines = last.cum + last.lines - commits[i0].cum, rs = new Set(); for (let i = i0; i < i1; i++) rs.add(commits[i].repo);
  litK = [Math.sqrt(commits[i0].k0), Math.sqrt(last.k1)]; litCi = [i0, i1];
  card.innerHTML = 'ENERGISED · ' + label + '\n<b>' + fmt(lines) + '</b> lines in <b>' + fmt(i1 - i0) + '</b> commits across ' + rs.size + ' repositories'
    + '\nkeys ' + fmt(commits[i0].k0) + ' to ' + fmt(last.k1) + ' · one band, because keys run in time order';
  home(); dirty = true; return { i0, i1, lines };
}
// TOUCH. Every pointer that is down is held in one map, so one finger drags and two pinch, and a
// mouse is just a pointer with one finger. The pinch keeps the world point between the fingers
// under the fingers, which is the same rule the wheel already obeys, so zooming in on a phone and
// on a desktop land on the same key.
const ZMAX = 60;
let drag = null, moved = 0, pinch = null;
const pts = new Map();
function pinchNow(){ const v = [...pts.values()], a = v[0], b = v[1];
  return { d:Math.hypot(a.x-b.x, a.y-b.y), mx:(a.x+b.x)/2, my:(a.y+b.y)/2 }; }
cv.addEventListener('pointerdown', e => {
  pts.set(e.pointerId, { x:e.clientX, y:e.clientY });
  if (pts.size === 2) { const s = pinchNow(), w = toWorld(s.mx, s.my); pinch = { d0:s.d, z0:zoom, wx:w[0], wy:w[1] }; drag = null; moved = 99; }
  else if (pts.size === 1) { drag = [e.clientX, e.clientY]; moved = 0; }
});
addEventListener('pointermove', e => {
  if (pts.has(e.pointerId)) pts.set(e.pointerId, { x:e.clientX, y:e.clientY });
  if (pinch && pts.size >= 2) { const s = pinchNow(); if (pinch.d0 > 1) {
      zoom = Math.max(1e-4, Math.min(ZMAX, pinch.z0 * s.d / pinch.d0));
      cx = pinch.wx - (s.mx - innerWidth/2)/zoom; cy = pinch.wy + (s.my - innerHeight/2)/zoom;
      atHome = false; tween = null; dirty = true; } return; }
  if (!drag) return; moved += Math.abs(e.clientX-drag[0]) + Math.abs(e.clientY-drag[1]);
  cx -= (e.clientX-drag[0])/zoom; cy += (e.clientY-drag[1])/zoom; drag = [e.clientX, e.clientY];
  atHome = false; tween = null; dirty = true; });
function pointerGone(e){ pts.delete(e.pointerId); if (pts.size < 2) pinch = null; if (pts.size === 0) drag = null; }
addEventListener('pointerup', e => {
  if (drag && moved < 4 && N) { const [wx, wy] = toWorld(e.clientX, e.clientY), r = Math.hypot(wx, wy);
    if (r*r < SPACE) { let k = zoom >= POINTS_FROM ? keyAt(wx, wy) : -1; const exact = k >= 0; if (!exact) k = Math.floor(r*r);
      target = exact ? { x:keyPlace(k)[0], y:keyPlace(k)[1] } : null; show(address(k)); } }
  pointerGone(e); });
addEventListener('pointercancel', pointerGone);
addEventListener('wheel', e => { const [wx, wy] = toWorld(e.clientX, e.clientY), f = e.deltaY < 0 ? 1.18 : 1/1.18;
  zoom = Math.max(1e-4, Math.min(ZMAX, zoom*f)); cx = wx - (e.clientX - innerWidth/2)/zoom; cy = wy + (e.clientY - innerHeight/2)/zoom;
  atHome = false; tween = null; dirty = true; }, { passive:true });
// the tap targets, so a phone can do everything the keyboard can
document.getElementById('keys').addEventListener('click', e => { const k = e.target.getAttribute('data-k'); if (!k) return;
  e.stopPropagation(); dispatchEvent(new KeyboardEvent('keydown', { key:k })); });
elTop.addEventListener('click', () => elTop.classList.toggle('open'));       // the long subtitle, collapsed by default
card.addEventListener('click', () => { card.style.display = 'none'; dirty = true; });
const gbox = document.getElementById('goto'), gin = document.getElementById('gotoin');
gin.addEventListener('keydown', e => { e.stopPropagation(); if (e.key === 'Escape') { gbox.style.display = 'none'; return; }
  if (e.key !== 'Enter') return; gbox.style.display = 'none'; const raw = gin.value.trim(), q = raw.replace(/[ ,_]/g,'');
  const mt = raw.match(/^(20\d\d)(?:-(\d\d))?(?:-(\d\d))?$/);
  if (mt) { lightTime(+mt[1], mt[2] ? +mt[2] : 0, mt[3] ? +mt[3] : 0); return; }
  const mnew = raw.toLowerCase().match(/^(?:show\s+)?new(?:\s+code)?(?:\s+(\d+)\s*h?)?$/);
  if (mnew) { showNew(mnew[1] ? Number(mnew[1]) : 24); return; }
  if (/^\d+$/.test(q)) goKey(Math.min(SPACE-1, Number(q)));
  else { const r = repos.find(x => x.name.toLowerCase() === raw.toLowerCase()) || repos.find(x => x.name.toLowerCase().includes(raw.toLowerCase()));
    if (r) { litRepo = r.i; target = null; card.style.display = 'none'; home(); dirty = true; } } });
addEventListener('keydown', e => { if (gbox.style.display === 'block') return;
  if (e.key === 'r' && N) { const j = Math.floor(Math.random()*N), c = commits[findBy('cum', j)]; goKey(c.k0 + (j - c.cum)); }   // uniform over issued lines
  else if (e.key === 'n' && N) showNew(24);
  else if (e.key === '/') { e.preventDefault(); gbox.style.display = 'block'; gin.value = ''; gin.focus(); }
  else if (e.key === 'Backspace') { e.preventDefault(); target = null; litRepo = -1; newFrom = -1; flash = 0; pulse = -1; litK = [-1,-1]; litCi = null; card.style.display = 'none'; home(); } });
requestAnimationFrame(frame);
</script>
</body>
</html>

Kuiper Law

A JavaScript module in the learn the kuiper folder of Kuiper Belt that places many (`placeMany`) and converts to screen (`toScreen`).

Set aside from the main view: 92% of its lines are the same as see-through/202611020012/kuiper-law.js (kuiper-belt), which stays. (near-copy-of, proposed by families.py). 92% of lines shared with Kuiper Law; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9238 to kuiper-belt@26fba12ab1b5bab8e71934ab86c58273e5f32682 see-through/202611020012/kuiper-law.js:1-123 180da0cc157440e01b5f5a14fb22b71e4faea910
  • sha256 2c7512ea1bfdc65f646684655338fa9e2e0564fa89ba38b42577cbc1ceb564ea
  • target sha256 ae995d1f6b4388633b1dd4eefe0bd1e56a76824c28a1db066148781868abbb5d
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

renderkuiper-belt / learn-the-kuiper/202610042225/kuiper-law.js · lines 1–119 of 119 · version 2026-10-04 22:25 · Entry point · pattern placeMany (shared by 2 files)

What it does
It draws its content. Defines 6 functions or classes, including keyPlace, place, placeMany, shader, toScreen. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage agent_infra (path word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Downstream impact
Used directly by 11 files: Grid Test (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610042346/modules/grid-test.html); Strings Test (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610042346/modules/strings-test.html); Zoom Test (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610042346/modules/zoom-test.html); Sheet (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610042346/sheet.html); and 7 more. Reached from 3 other entry points, including Menu (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050354/menu.html); Play (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/play.html); Solid (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/solid.html).
What it achieves
It places many (`placeMany`) and is built from the key place helper (`keyPlace`) and the place step (`place`). `kuiper-law.js` THE ONE LAW OF THE REAL KUIPER, lifted VERBATIM from the live page.
Why it matters
Loaded by the Sheet page at https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610042346/sheet.html and 3 other pages. Also imported by Logic. Checked by 6 tests, including Grid Test.
Application
kuiper-belt · learn-the-kuiper/202610042225 · JavaScript module
Uses
Kuiper Belt — Index Page (estate URL)
Used by
loaded by Grid Test (script src), loaded by Strings Test (script src), loaded by Zoom Test (script src), loaded by Sheet (script src), loaded by Deep Test (script src), loaded by Radar Test (script src), loaded by Realgame Test (script src), loaded by Lesson (script src), and 3 more, mentioned in Standalone (comment link)
Produces
keyPlace, place, placeMany, shader, toScreen, homeZoom
Defines here
keyPlace, place, placeMany, shader, toScreen, homeZoom
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
kuiper-belt@26fba12ab1b5bab8e71934ab86c58273e5f32682 learn-the-kuiper/202610042225/kuiper-law.js:1-119 · blob c506a252f27fa8b80e849eb63bbb6699eaf674f0 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: agent_infra · users: ai_agent · canonical: unknown
// kuiper-law.js  THE ONE LAW OF THE REAL KUIPER, lifted VERBATIM from the live page.
// Source: github.com/Ventusltd/kuiper-belt  index.html @ commit 7a65dd315b0c60b1baf9a7090206c900b2cfd0a1
//         (2026-10-04 16:08 +0100, "docs: add What is the Kuiper page"), live at https://ventusltd.github.io/kuiper-belt/
// Every screen of LEARN THE KUIPER GAME that places a real-wafer particle must go through window.KuiperLaw.
// Nothing in here is invented: every formula below is quoted with the live line number it came from.
//
// index.html:79      //     key k  ->  r = sqrt(k),  theta = 2 pi frac(k G / 2^32),  G = 2654435769
// index.html:92      const G32 = 2654435769, TW = 4096;
// index.html:250     function keyPlace(k){ const m = Math.imul((k % 4294967296) >>> 0, G32) >>> 0, th = 2*Math.PI*m/4294967296, r = Math.sqrt(k + 0.5);
// index.html:251       return [r*Math.cos(th), r*Math.sin(th)]; }
// index.html:143       float d = float(gl_VertexID);
// index.html:144       float r = u_R0 + (d + 0.5) / (u_R0 + sqrt(u_R0*u_R0 + d + 0.5) + 1e-9);      // sqrt(k0+d+.5), kept precise
// index.html:145       uint m = (u_k0lo + uint(gl_VertexID)) * ${G32}u;
// index.html:146       float A = 6.283185307179586 * float(m >> 16) / 65536.0, B = 6.283185307179586 * float(m & 0xFFFFu) / 4294967296.0;
// index.html:147       vec2 cs = vec2(cos(A)*cos(B) - sin(A)*sin(B), sin(A)*cos(B) + cos(A)*sin(B));
// index.html:148       gl_Position = vec4((r*cs - u_center) * u_zoom / (0.5*u_res), 0.0, 1.0);
// index.html:333         for (let off = s0; off < s1; off += 4000000) {                       // bounded calls; the driver watchdog is real
// index.html:334           gl.uniform1ui(U(PK,'u_k0lo'), (off % 4294967296) >>> 0); gl.uniform1f(U(PK,'u_R0'), Math.sqrt(off));
// index.html:335           gl.drawArrays(gl.POINTS, 0, Math.min(4000000, s1 - off)); } }
// index.html:357     { const x0 = (0 - cx)*zoom + ov.width/2, y0 = ov.height/2 + cy*zoom, ...   (the 2D overlay: world y is UP on screen)
//
// WHAT THE LAW SAYS, in words that match the code exactly:
//   keys start at 0.  m = (key * 2654435769) mod 2^32, an unsigned 32-bit integer product (Math.imul, wrapping).
//   turns = m / 2^32           the angle as a fraction of one full turn, in [0, 1)
//   theta = 2 pi turns         radians, anticlockwise from +x, with world y UP on screen (WebGL clip space, :148; overlay :357)
//   r     = sqrt(key + 0.5)    the radius; NOT sqrt(key). The half is in the live code at :250 and :144.
//   Successive keys turn by G32/2^32 = 0.6180339887 of a turn = 222.4922 degrees anticlockwise on screen, which is the
//   same point as 137.5078 degrees CLOCKWISE. The Excel "137.5 anticlockwise" spiral is the MIRROR IMAGE of the Kuiper.
//   Keys beyond 2^32 wrap: key % 4294967296 first (:250), and the shader gets the low 32 bits of the batch offset (:334).
(function (root) {
  'use strict';
  // index.html:92      const G32 = 2654435769, TW = 4096;
  const G32 = 2654435769, TW = 4096;
  const TWO32 = 4294967296;
  // the whole wafer as of this commit: sum of every gap_before and lines in cosmos/wafer.tsv (index.html:180  N = issued; SPACE = k;)
  const SPACE = 59637070538;

  // index.html:250-251, VERBATIM. This is the electron. Do not edit it; edit the live page and re-lift.
  function keyPlace(k){ const m = Math.imul((k % 4294967296) >>> 0, G32) >>> 0, th = 2*Math.PI*m/4294967296, r = Math.sqrt(k + 0.5);
    return [r*Math.cos(th), r*Math.sin(th)]; }

  // The same law, opened up so the game can show each part: m, turns, degrees, r, x, y.
  // Every expression here is the one in keyPlace at :250, nothing added.
  function place(key){
    const k = +key;
    const m = Math.imul((k % 4294967296) >>> 0, G32) >>> 0;        // :250
    const turns = m / 4294967296;                                   // :250  th = 2*Math.PI*m/4294967296
    const th = 2*Math.PI*m/4294967296;                              // :250
    const r = Math.sqrt(k + 0.5);                                   // :250
    return { key: k, m: m, turns: turns, deg: turns * 360, theta: th, r: r, x: r*Math.cos(th), y: r*Math.sin(th) };
  }

  // n keys from k0, x,y interleaved, exactly as the live batch does it (:333-335): u_k0lo is the low 32 bits of the
  // batch offset and the shader adds gl_VertexID in uint32. Written here with keyPlace so the result is identical to :250.
  function placeMany(k0, n, out){
    out = out || new Float64Array(2*n);
    for (let d = 0; d < n; d++) { const p = keyPlace(k0 + d); out[2*d] = p[0]; out[2*d+1] = p[1]; }
    return out;
  }

  // The vertex shader at :143-148 reproduced in float32, as the GPU computes it. The live view itself has these float32
  // differences from keyPlace; they are reported separately in kuiper-law.receipt.json and are not photons.
  const f = Math.fround;
  function shader(k0, d){
    // :334  gl.uniform1ui(U(PK,'u_k0lo'), (off % 4294967296) >>> 0); gl.uniform1f(U(PK,'u_R0'), Math.sqrt(off));
    const u_k0lo = (k0 % 4294967296) >>> 0, u_R0 = f(Math.sqrt(k0));
    // :143  float d = float(gl_VertexID);
    const fd = f(d);
    // :144  float r = u_R0 + (d + 0.5) / (u_R0 + sqrt(u_R0*u_R0 + d + 0.5) + 1e-9);
    const r = f(u_R0 + f(f(fd + 0.5) / f(f(u_R0 + f(Math.sqrt(f(f(f(u_R0*u_R0) + fd) + 0.5)))) + f(1e-9))));
    // :145  uint m = (u_k0lo + uint(gl_VertexID)) * ${G32}u;
    const m = Math.imul((u_k0lo + d) >>> 0, G32) >>> 0;
    // :146  float A = 6.283185307179586 * float(m >> 16) / 65536.0, B = 6.283185307179586 * float(m & 0xFFFFu) / 4294967296.0;
    const A = f(f(f(6.283185307179586) * f(m >>> 16)) / 65536.0), B = f(f(f(6.283185307179586) * f(m & 0xFFFF)) / 4294967296.0);
    // :147  vec2 cs = vec2(cos(A)*cos(B) - sin(A)*sin(B), sin(A)*cos(B) + cos(A)*sin(B));
    const cA = f(Math.cos(A)), sA = f(Math.sin(A)), cB = f(Math.cos(B)), sB = f(Math.sin(B));
    const cs = [f(f(cA*cB) - f(sA*sB)), f(f(sA*cB) + f(cA*sB))];
    return { key: k0 + d, m: m, turns: m / TWO32, r: r, x: f(r*cs[0]), y: f(r*cs[1]) };
  }

  // World to screen, as the live page does it. :148 puts world y UP (WebGL clip space); the 2D overlay at :357 agrees
  // (y0 = ov.height/2 + cy*zoom). A 2D canvas is y-down, so the game must FLIP y when it draws KuiperLaw points.
  function toScreen(x, y, cam, W, H){
    return [ W/2 + (x - cam.cx) * cam.zoom, H/2 - (y - cam.cy) * cam.zoom ];
  }

  // index.html:244-248, how the live home camera frames the whole wafer: radius = 80% of half the clear box.
  function homeZoom(boxW, boxH, space){ return Math.min(boxW, boxH) / 2 * 0.80 / Math.sqrt(space == null ? SPACE : space); }

  const constants = {
    G32: G32, TW: TW, TWO32: TWO32, SPACE: SPACE, KEYS_FROM: 0, RADIUS_OFFSET: 0.5,
    TURN_PER_KEY: G32 / TWO32,                       // 0.6180339887 of a turn per key
    DEG_PER_KEY_ANTICLOCKWISE: 360 * G32 / TWO32,    // 222.4922359 degrees anticlockwise, y up
    DEG_PER_KEY_CLOCKWISE: 360 - 360 * G32 / TWO32,  // 137.5077641 degrees clockwise, the same point
    Y_UP_ON_SCREEN: true, BATCH: 4000000, MAX_CALLS: 3000, POINTS_FROM: 1.0
  };

  // TEACHING VARIANT, clearly NOT THE REAL KUIPER. The spreadsheet spiral: theta = key x 137.507764 degrees anticlockwise,
  // r = sqrt(key) (no half). Its angle runs the OTHER WAY round and its radius is off by sqrt(k+0.5)-sqrt(k). Show it only
  // beside the real one, labelled. It exists so a learner can see why the Kuiper is not it.
  const teach = {
    excel: function (key) {
      const k = +key, deg = (k * 137.507764) % 360, th = deg * Math.PI / 180, r = Math.sqrt(k);
      return { key: k, deg: deg, turns: deg / 360, theta: th, r: r, x: r*Math.cos(th), y: r*Math.sin(th),
               label: 'NOT THE REAL KUIPER: Excel spiral, 137.507764 deg per key anticlockwise, r = sqrt(key)' };
    },
    label: 'NOT THE REAL KUIPER'
  };

  const KuiperLaw = {
    place: place, placeMany: placeMany, keyPlace: keyPlace, shader: shader, toScreen: toScreen, homeZoom: homeZoom,
    constants: constants, teach: teach,
    source: 'kuiper-belt@7a65dd315b0c60b1baf9a7090206c900b2cfd0a1 index.html:92,143-148,250-251,333-335,357',
    live: 'https://ventusltd.github.io/kuiper-belt/'
  };
  Object.freeze(constants); Object.freeze(KuiperLaw);
  root.KuiperLaw = KuiperLaw;
  if (typeof module !== 'undefined' && module.exports) module.exports = KuiperLaw;
})(typeof window !== 'undefined' ? window : globalThis);

Grid Test

A web page in the learn the kuiper folder of Kuiper Belt. Published at https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610042346/modules/grid-test.html.

testkuiper-belt / learn-the-kuiper/202610042346/modules/grid-test.html · lines 1–17 of 17 · version 2026-10-04 23:46 · Entry point

What it does
It tests its inputs. Uses libraries grid-data.js. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage agent_infra (path word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
Out: web page.
Downstream impact
It is itself an entry point, published at https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610042346/modules/grid-test.html.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
kuiper-belt · learn-the-kuiper/202610042346/modules · page
Uses
Kuiper Law (script src), Scale Logic (script src), Grid (script src), grid-data.js
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
kuiper-belt@26fba12ab1b5bab8e71934ab86c58273e5f32682 learn-the-kuiper/202610042346/modules/grid-test.html:1-17 · blob 5d68558259155a42903972de6c45a3c67ff3579b · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: agent_infra · users: ai_agent · canonical: unknown
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>Draw the grid test</title>
<style>html,body{margin:0;height:100%;background:#000;overflow:hidden}#host{position:fixed;inset:0;background:#000}
#closed{color:#ffb000;font:bold 32px "Segoe UI",Arial,sans-serif;padding:40px;display:none}</style></head>
<body><div id="host"></div><div id="closed">DRAW THE GRID CLOSED. Reload to open again.</div>
<script src="../kuiper-law.js"></script>
<script src="../scale-logic.js"></script>
<script src="grid-data.js"></script>
<script src="grid.js"></script>
<script>
(function(){
  var m=(window.KGModules||[]).filter(function(x){return x.id==='grid'})[0], host=document.getElementById('host');
  var close=m.close; m.close=function(){close.call(m); host.style.display='none'; document.getElementById('closed').style.display='block'; window.__closed=true;};
  m.open(host);
})();
</script></body></html>

Strings Test

A web page in the learn the kuiper folder of Kuiper Belt. Published at https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610042346/modules/strings-test.html.

testkuiper-belt / learn-the-kuiper/202610042346/modules/strings-test.html · lines 1–51 of 51 · version 2026-10-04 23:46 · Entry point

What it does
It tests its inputs. Defines btn, ptr, st, log. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage agent_infra (path word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
Out: web page.
Downstream impact
It is itself an entry point, published at https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610042346/modules/strings-test.html.
What it achieves
Defines `btn`, `ptr` and `log`. It responds to kgclose events.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
kuiper-belt · learn-the-kuiper/202610042346/modules · page
Uses
Kuiper Law (script src), Scale Logic (script src), Strings (script src)
Used by
none found
Produces
btn, ptr, st, log
Defines here
btn, ptr, st, log
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
kuiper-belt@26fba12ab1b5bab8e71934ab86c58273e5f32682 learn-the-kuiper/202610042346/modules/strings-test.html:1-51 · blob 569f5253ab5a72ee11a9b7f64da9e5bc09f81efd · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: agent_infra · users: ai_agent · canonical: unknown
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="color-scheme" content="dark">
<title>Solar Strings test</title>
<style>html,body{margin:0;height:100%;background:#000;color:#fff;overflow:hidden}#host{position:fixed;inset:0}</style>
</head>
<body>
<div id="host"></div>
<pre id="report" style="display:none"></pre>
<script src="../kuiper-law.js"></script>
<script src="../scale-logic.js"></script>
<script src="strings.js"></script>
<script>
  var mod = window.KGModules.filter(function (m) { return m.id === 'strings'; })[0];
  var host = document.getElementById('host');
  host.addEventListener('kgclose', function () { host.textContent = 'closed'; });
  mod.open(host);
  // ?act=a,b,c runs real dispatched events (clicks, pointer, keys) for the self-test; results go into #report
  var q = new URLSearchParams(location.search), acts = (q.get('act') || '').split(',').filter(Boolean), out = [];
  function btn(k, d) { return host.querySelector('button[data-k="' + k + '"][data-d="' + d + '"]'); }
  function ptr(cv, x, y) { var r = cv.getBoundingClientRect(); cv.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, clientX: r.left + x, clientY: r.top + y, pointerType: 'touch' })); }
  function st() { return mod._state(); }
  function log(s) { out.push(s); }
  setTimeout(function () {
    acts.forEach(function (a) {
      var m = a.split(':');
      if (m[0] === 'plus' || m[0] === 'minus') { var n = +(m[2] || 1); for (var i = 0; i < n; i++) btn(m[1], m[0] === 'plus' ? 1 : -1).click(); }
      else if (m[0] === 'type') { var inp = host.querySelector('input[data-k="' + m[1] + '"]'); inp.focus(); inp.value = m[2]; inp.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })); }
      else if (m[0] === 'tapstring') { var S = st(), G = S.geom; ptr(S.cvL, (G.colS0 + G.colS1) / 2, G.sy[+m[1]]); }
      else if (m[0] === 'tapinv') { var S2 = st(), G2 = S2.geom; ptr(S2.cvL, G2.colI, G2.iy[+m[1]]); }
      else if (m[0] === 'tapkey') { var S3 = st(), c = S3.waferCamDrawn, o = S3.plan.byKey[+m[1]]; ptr(S3.cvW, c.ox + o.pos.x * c.z, c.oy - o.pos.y * c.z); }
      else if (m[0] === 'why') { st().whyBtn.click(); }
      else if (m[0] === 'esc') { window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })); }
      var s = st();
      if (!s) { log(a + ' -> CLOSED, host: ' + host.textContent); return; }
      var P = s.plan, sel = s.sel;
      // check every position against the law
      var bad = 0; P.items.forEach(function (o) { var k = KuiperLaw.keyPlace(o.key); if (k[0] !== o.pos.x || k[1] !== o.pos.y) bad++; });
      log(a + ' -> p=' + JSON.stringify(s.p) + ' panels=' + P.panels + ' strings=' + P.strs.length + ' combs=' + P.combs.length + ' invs=' + P.invs.length +
          ' keys=' + P.keysUsed + ' maxKey=' + P.maxKey + ' sel=' + (sel ? sel.label + '@' + sel.key : 'none') + ' lawMismatch=' + bad + ' cap="' + s.cap.textContent + '"');
    });
    out.push('viewport -> ' + innerWidth + 'x' + innerHeight + ' scrollW=' + document.documentElement.scrollWidth);
    document.getElementById('report').textContent = out.join('\n');
    document.title = 'DONE';
  }, 300);
</script>
</body>
</html>

Zoom Test

A web page in the learn the kuiper folder of Kuiper Belt. Published at https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610042346/modules/zoom-test.html.

testkuiper-belt / learn-the-kuiper/202610042346/modules/zoom-test.html · lines 1–16 of 16 · version 2026-10-04 23:46 · Entry point

What it does
It tests its inputs. Uses libraries realgame-data.js. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage agent_infra (path word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
Out: web page.
Downstream impact
It is itself an entry point, published at https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610042346/modules/zoom-test.html.
What it achieves
It responds to kgclose events.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
kuiper-belt · learn-the-kuiper/202610042346/modules · page
Uses
Kuiper Law (script src), Scale Logic (script src), Zoom (script src), realgame-data.js
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
kuiper-belt@26fba12ab1b5bab8e71934ab86c58273e5f32682 learn-the-kuiper/202610042346/modules/zoom-test.html:1-16 · blob 8811b05ed18e25d72754c32a2474357bce10a364 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: agent_infra · users: ai_agent · canonical: unknown
<!doctype html>
<html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>ZOOM test harness</title>
<style>html,body{margin:0;height:100%;background:#000;color:#fff;font:bold 28px "Segoe UI",Arial,sans-serif;overflow:hidden}
#host{position:fixed;inset:0}#closed{display:none;padding:40px}</style></head>
<body><div id="host"></div><div id="closed">ZOOM CLOSED</div>
<script src="../kuiper-law.js"></script>
<script src="../scale-logic.js"></script>
<script src="realgame-data.js"></script>
<script src="zoom.js"></script>
<script>
var mod = (window.KGModules || []).filter(function (m) { return m.id === 'zoom'; })[0];
var host = document.getElementById('host');
host.addEventListener('kgclose', function () { host.style.display = 'none'; document.getElementById('closed').style.display = 'block'; window.__closed = true; });
mod.open(host);
</script></body></html>

Scale Logic

A JavaScript module in the learn the kuiper folder of Kuiper Belt that converts to fraction (`toFraction`), sets position (`setPosition`) and polar (`setPolar`) and calculates planar distances and angles.

renderkuiper-belt / learn-the-kuiper/202610042346/scale-logic.js · lines 1–392 of 491 · version 2026-10-04 23:46 · Entry point · pattern consider (shared by 5 files)

What it does
Defines 38 functions or classes, including fin, clamp, hash32, rng, toFraction. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage agent_infra (path word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Downstream impact
Used directly by 9 files: Grid Test (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610042346/modules/grid-test.html); Strings Test (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610042346/modules/strings-test.html); Zoom Test (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610042346/modules/zoom-test.html); Sheet (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610042346/sheet.html); and 5 more. Reached from 3 other entry points, including Menu (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050354/menu.html); Play (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/play.html); Solid (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/solid.html).
What it achieves
It sets position (`setPosition`), sets polar (`setPolar`) and gets moves (`getMoves`). `scale-logic.js` SCALE LOGIC for LEARN THE KUIPER: quadrillions of particles down to one, any one of them movable.
Why it matters
Loaded by the Sheet page at https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610042346/sheet.html and 2 other pages. Checked by 6 tests, including Grid Test.
Application
kuiper-belt · learn-the-kuiper/202610042346 · JavaScript module
Uses
none found
Used by
loaded by Grid Test (script src), loaded by Strings Test (script src), loaded by Zoom Test (script src), loaded by Sheet (script src), loaded by Deep Test (script src), loaded by Radar Test (script src), loaded by Realgame Test (script src), loaded by Lesson (script src), and 1 more
Produces
fin, clamp, hash32, rng, toFraction, prepare, mOf, lapsOf, radiusOf, keyAtRadius, setPosition, setPolar
Defines here
fin, clamp, hash32, rng, toFraction, prepare, mOf, lapsOf, radiusOf, keyAtRadius, setPosition, setPolar, clearMove, clearMoves, getMoves, degOf, truePlace, place, placeInner, rectOfView, inRect, bandOfRect, keysInRect, accept, n2, dot, jRange, tryKey, visibleKeys, sample
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
kuiper-belt@26fba12ab1b5bab8e71934ab86c58273e5f32682 learn-the-kuiper/202610042346/scale-logic.js:1-392 · blob 95d6858a765b4cb0b9a6568a8f85ab4912d29701 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: agent_infra · users: ai_agent · canonical: unknown
// scale-logic.js  SCALE LOGIC for LEARN THE KUIPER: quadrillions of particles down to one, any one of them movable.
// Pure logic: no DOM, runs in the browser (window.KuiperScale) and in Node (module.exports).
//
// The real law (kuiper-law.js, lifted from the live page) is:  r = sqrt(key + 0.5),
// angle = ((key mod 2^32) x 2654435769 mod 2^32) / 2^32 turns anticlockwise, world y UP.
// Here the same law is written with every number as a lever, so practice mode can bend it, and REAL puts it back:
//   params = { first: 0, count: N, turnNumber: 2654435769, wrap: 4294967296, degreesPerKey: null,
//              power: 0.5, offset: 0.5, skipPerSecond: 600, capSeconds: 1209600, workRest: null }
// With the real params, place(key) equals KuiperLaw.place(key) to the last bit for every key up to 2^53
// (same Math.imul path). Any other params go through exact modular arithmetic (Number when it fits, BigInt
// otherwise), so even ridiculous values compute and never throw; broken cases carry a 'note' string instead.
(function (root) {
  'use strict';

  var TWO32 = 4294967296, TWO53 = 9007199254740992, TAU = 2 * Math.PI;
  var hasBig = typeof BigInt === 'function';

  var REAL = Object.freeze({
    first: 0, count: 1000, turnNumber: 2654435769, wrap: TWO32, degreesPerKey: null,
    power: 0.5, offset: 0.5, skipPerSecond: 600, capSeconds: 1209600, workRest: null
  });

  var LIMITS = Object.freeze({
    scanCap: 8192,         // key bands at or below this are scanned one by one (exact, simple)
    candidateCap: 400000,  // lattice enumeration above this many expected hits switches to seeded random picks
    gapRangesCap: 20000    // the quiet-time allocator never emits more ranges than this
  });

  // ------------------------------------------------------------------ small helpers
  function fin(v, d) { v = +v; return (typeof v === 'number' && isFinite(v)) ? v : d; }
  function clamp(v, lo, hi) { return v < lo ? lo : (v > hi ? hi : v); }
  function hash32(a) { // one round of a 32-bit integer hash; deterministic picks come from this
    a = (a ^ 0x9E3779B9) >>> 0;
    a = Math.imul(a ^ (a >>> 16), 0x85EBCA6B) >>> 0;
    a = Math.imul(a ^ (a >>> 13), 0xC2B2AE35) >>> 0;
    return (a ^ (a >>> 16)) >>> 0;
  }
  function rng(seed) { // mulberry32, seeded, in [0, 1)
    var s = seed >>> 0;
    return function () {
      s = (s + 0x6D2B79F5) >>> 0;
      var t = Math.imul(s ^ (s >>> 15), 1 | s);
      t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
      return ((t ^ (t >>> 14)) >>> 0) / TWO32;
    };
  }
  // a non-negative real as an exact fraction num/den with den = base x 10^dec, dec <= 9
  function toFraction(x, base) {
    var dec = 0, scale = 1;
    while (dec < 9 && Math.abs(x * scale - Math.round(x * scale)) > 1e-9 * Math.max(1, Math.abs(x * scale))) { dec++; scale *= 10; }
    return { num: Math.round(x * scale), den: base * scale };
  }

  // ------------------------------------------------------------------ prepare(params): fill, repair, note
  function prepare(params) {
    if (params && params.__prepared === true) return params;
    var q = params || {}, notes = [];
    var first = fin(q.first, REAL.first); if (first !== Math.floor(first)) { first = Math.floor(first); notes.push('first rounded down to a whole key'); }
    var exactLimitReached = false;
    // every key must stay below 2^53, where k + 1 stops being exact (a loop there would never end)
    if (first > TWO53 - 1) { notes.push('first above 2^53: clamped to the exact limit'); first = TWO53 - 1; exactLimitReached = true; }
    if (first < -TWO53) { notes.push('first below -2^53: clamped'); first = -TWO53; exactLimitReached = true; }
    var count = fin(q.count, REAL.count); if (count < 1) { notes.push('count below 1: showing 1 particle'); count = 1; }
    if (count !== Math.floor(count)) count = Math.floor(count);
    if (count > TWO53) { notes.push('count above 2^53: the computer cannot count these keys exactly, clamped'); count = TWO53; exactLimitReached = true; }
    if (first + count > TWO53) { notes.push('first + count above 2^53: the last keys are not exact, clamped'); count = Math.max(1, TWO53 - first); exactLimitReached = true; }

    var power = fin(q.power, REAL.power), offset = fin(q.offset, REAL.offset);
    if (power === 0) notes.push('power 0: every particle sits on the same circle, radius 1');
    if (power < 0) notes.push('power negative: particles rush OUT at the centre and crowd IN at the rim; the real law is 0.5');
    if (power > 0 && Math.abs(power - 0.5) > 1e-12) notes.push('power ' + power + ': spacing changes with radius (only 0.5 keeps it constant)');

    // the angle: G/W turns per key, exact integers
    var G, W, angleSource;
    var dpk = q.degreesPerKey;
    if (dpk !== null && dpk !== undefined && dpk !== '' && isFinite(+dpk)) {
      var d = +dpk; var sign = d < 0 ? -1 : 1; d = Math.abs(d) % 360;
      var f = toFraction(d, 360); G = f.num; W = f.den; if (sign < 0) G = (W - G) % W;
      angleSource = 'degreesPerKey';
      if (G === 0) notes.push('degreesPerKey is a multiple of 360: every particle on one ray');
    } else {
      var tn = fin(q.turnNumber, REAL.turnNumber), wr = fin(q.wrap, REAL.wrap);
      if (wr < 1) { notes.push('wrap below 1: every particle on one ray (angle always 0)'); wr = 1; }
      if (wr !== Math.floor(wr) || tn !== Math.floor(tn)) {
        var fw = toFraction(wr, 1), ft = toFraction(Math.abs(tn), 1); // bring both to integers with a common scale
        var scale = Math.max(fw.den, ft.den);
        wr = Math.round(wr * scale); tn = Math.round(Math.abs(tn) * scale) * (tn < 0 ? -1 : 1);
        notes.push('turnNumber/wrap were not whole numbers: scaled to a whole fraction');
        if (!isFinite(wr) || !isFinite(tn)) { notes.push('turnNumber/wrap too large to scale: using the real 2654435769 / 2^32'); wr = REAL.wrap; tn = REAL.turnNumber; }
        if (wr < 1) { notes.push('wrap rounds to 0: every particle on one ray'); wr = 1; }
      }
      if (wr > TWO53) { notes.push('wrap above 2^53: angles still computed but with BigInt, slowly'); }
      G = tn; W = wr;
      if (G < 0) { G = ((G % W) + W) % W; notes.push('turnNumber negative: read as turning the other way'); }
      else if (G >= W) { G = G % W; }
      if (G === 0) notes.push('turn number 0 (or a multiple of wrap): every particle on one ray');
      angleSource = 'turnNumber/wrap';
    }
    var mode = (W === TWO32 && G < TWO32) ? 'imul' : ((W * G < TWO53 && W <= TWO53) ? 'num' : (hasBig ? 'big' : 'float'));
    if (mode === 'float') notes.push('no BigInt in this runtime: huge wraps are approximate');

    var skipPerSecond = Math.max(0, fin(q.skipPerSecond, REAL.skipPerSecond));
    var capSeconds = Math.max(0, fin(q.capSeconds, REAL.capSeconds));
    var p = {
      __prepared: true, first: first, count: count, last: first + count - 1,
      G: G, W: W, mode: mode, alpha: G / W, degreesPerKey: 360 * G / W, angleSource: angleSource,
      power: power, offset: offset, skipPerSecond: skipPerSecond, capSeconds: capSeconds,
      workRest: q.workRest || null, exactLimitReached: exactLimitReached, notes: notes, note: notes.join('; '),
      gaps: null
    };
    if (p.workRest) p.gaps = gaps(p);
    return p;
  }

  // ------------------------------------------------------------------ the angle, exact
  // m(key) = (key x G) mod W, as an integer in [0, W). Real params: Math.imul path, identical to kuiper-law.js:250.
  function mOf(p, k) {
    if (!isFinite(k)) return 0;
    if (p.mode === 'imul') return Math.imul((k % TWO32) >>> 0, p.G) >>> 0;
    var km = k % p.W; if (km < 0) km += p.W;
    if (p.mode === 'num') return (km * p.G) % p.W;
    if (p.mode === 'big') return Number((BigInt(km) * BigInt(p.G)) % BigInt(p.W));
    return ((km * p.alpha) % 1) * p.W; // float fallback, approximate
  }
  function lapsOf(p, k, m) { // full turns thrown away by the MOD: floor(key x G / W)
    var prod = k * p.G;
    if (!isFinite(prod) || !isFinite(m) || !isFinite(p.W) || m !== Math.floor(m)) return Math.floor((k * p.alpha)); // approximate when the exact path cannot run
    if (prod < TWO53 || !hasBig) return Math.floor((prod - m) / p.W);
    return Number((BigInt(k) * BigInt(p.G) - BigInt(m)) / BigInt(p.W));
  }
  function radiusOf(p, k) { return Math.pow(k + p.offset, p.power); }
  function keyAtRadius(p, r) { // the real-valued key whose radius is r (inverse of radiusOf); NaN when not invertible
    if (!(p.power > 0) || !(r >= 0)) return NaN;
    return Math.pow(r, 1 / p.power) - p.offset;
  }

  // ------------------------------------------------------------------ the movable layer (practice mode)
  var moves = new Map(); // key -> {x, y}
  function setPosition(key, x, y) {
    var k = Math.floor(fin(key, 0)); x = fin(x, 0); y = fin(y, 0);
    moves.set(k, { x: x, y: y });
    return { key: k, x: x, y: y, r: Math.hypot(x, y), deg: degOf(x, y) };
  }
  function setPolar(key, r, deg) {
    r = fin(r, 0); deg = fin(deg, 0); var th = deg * Math.PI / 180;
    return setPosition(key, r * Math.cos(th), r * Math.sin(th));
  }
  function clearMove(key) { return moves.delete(Math.floor(fin(key, 0))); }
  function clearMoves() { moves.clear(); }
  function getMoves() { var out = []; moves.forEach(function (v, k) { out.push({ key: k, x: v.x, y: v.y }); }); return out; }
  function degOf(x, y) { var d = Math.atan2(y, x) * 180 / Math.PI; return d < 0 ? d + 360 : d; }

  // ------------------------------------------------------------------ 1. place(key, params)
  function truePlace(p, k) {
    var m = mOf(p, k), turns = m / p.W, th = TAU * m / p.W, r = radiusOf(p, k);
    var note = null;
    if (!isFinite(r) || r !== r) { note = 'radius undefined for key ' + k + ' with power ' + p.power + ' and offset ' + p.offset; r = 0; }
    return { key: k, m: m, turns: turns, deg: turns * 360, theta: th, r: r, x: r * Math.cos(th), y: r * Math.sin(th), note: note };
  }
  function place(key, params) {
    try { return placeInner(key, params); }
    catch (e) { return { key: +key, x: 0, y: 0, r: 0, deg: 0, turns: 0, m: 0, laps: 0, moved: false, issued: true, note: 'could not place: ' + (e && e.message || e) }; }
  }
  function placeInner(key, params) {
    var p = prepare(params);
    var k = +key, keyNote = null;
    if (!isFinite(k)) { keyNote = 'key ' + String(key) + ' is not a number: showing the first key'; k = p.first; }
    var kf = Math.floor(k); // whole keys only; the real law truncates the same way
    if (Math.abs(kf) > TWO53) { keyNote = 'key beyond 2^53: clamped to the exact limit'; kf = clamp(kf, -TWO53, TWO53); }
    var t = truePlace(p, kf);
    var out = { key: kf, x: t.x, y: t.y, r: t.r, deg: t.deg, turns: t.turns, m: t.m, laps: lapsOf(p, kf, t.m), moved: false };
    var notes = [];
    if (keyNote) notes.push(keyNote);
    if (t.note) notes.push(t.note);
    if (kf < p.first || kf > p.last) notes.push('key ' + kf + ' is outside first..last (' + p.first + '..' + p.last + ')');
    if (kf > TWO53) notes.push('key above 2^53: not exact');
    if (p.gaps && !isIssued(kf, p.gaps)) { out.issued = false; notes.push('key skipped for time: no particle here (dark ring)'); } else out.issued = true;
    if (moves.has(kf)) {
      var mv = moves.get(kf);
      out.moved = true; out.truePlace = { x: t.x, y: t.y, r: t.r, deg: t.deg };
      out.x = mv.x; out.y = mv.y; out.r = Math.hypot(mv.x, mv.y); out.deg = degOf(mv.x, mv.y);
      out.leader = { fromX: t.x, fromY: t.y, toX: mv.x, toY: mv.y, label: 'MOVED FROM ITS TRUE PLACE' };
    }
    if (p.note) notes.push(p.note);
    if (notes.length) out.note = notes.join('; ');
    return out;
  }

  // ------------------------------------------------------------------ geometry of a window
  function rectOfView(view) {
    var zoom = Math.max(1e-300, fin(view && view.zoom, 1));
    var cx = fin(view && view.cx, 0), cy = fin(view && view.cy, 0);
    var hw = Math.abs(fin(view && view.w, 800)) / (2 * zoom), hh = Math.abs(fin(view && view.h, 600)) / (2 * zoom);
    return { x0: cx - hw, x1: cx + hw, y0: cy - hh, y1: cy + hh, zoom: zoom };
  }
  function inRect(rc, x, y) { return x >= rc.x0 && x <= rc.x1 && y >= rc.y0 && y <= rc.y1; }
  function bandOfRect(rc) { // radii and turn-interval covered by a rectangle, seen from the origin
    var dx = Math.max(rc.x0, 0, -rc.x1), dy = Math.max(rc.y0, 0, -rc.y1);
    var rmin = Math.hypot(dx, dy);
    var rmax = Math.max(Math.hypot(rc.x0, rc.y0), Math.hypot(rc.x1, rc.y0), Math.hypot(rc.x0, rc.y1), Math.hypot(rc.x1, rc.y1));
    var inside = rc.x0 <= 0 && 0 <= rc.x1 && rc.y0 <= 0 && 0 <= rc.y1;
    if (inside) return { rmin: 0, rmax: rmax, full: true, tLo: 0, tHi: 1 };
    var cs = [[rc.x0, rc.y0], [rc.x1, rc.y0], [rc.x1, rc.y1], [rc.x0, rc.y1]];
    var ref = Math.atan2(cs[0][1], cs[0][0]) / TAU, lo = 0, hi = 0;
    for (var i = 1; i < 4; i++) { var d = Math.atan2(cs[i][1], cs[i][0]) / TAU - ref; d -= Math.round(d); if (d < lo) lo = d; if (d > hi) hi = d; }
    var tLo = ref + lo, tHi = ref + hi; // a convex box without the origin spans under half a turn
    tLo -= Math.floor(tLo); tHi = tLo + (hi - lo);
    return { rmin: rmin, rmax: rmax, full: false, tLo: tLo, tHi: tHi };
  }

  // Core: every key of params whose TRUE place lies in rect (exact), capped at maxOut (seeded picks when more).
  // Works at 9e15 because the keys at a given radius and angle form a 2-D lattice {(k, kG - wW)}; a reduced basis
  // lets us enumerate only the candidates inside the box [kLo,kHi] x [yLo,yHi), then test each exactly.
  function keysInRect(p, rc, maxOut, seed) {
    maxOut = Math.max(1, Math.floor(fin(maxOut, 4000)));
    var out = [], info = { exact: true, scanned: 0, candidates: 0, expected: 0, method: 'scan', note: null };
    var band = bandOfRect(rc);
    var kLo = p.first, kHi = p.last;
    var inv = p.power > 0;
    if (inv) {
      var a = keyAtRadius(p, band.rmin), b = keyAtRadius(p, band.rmax);
      if (a === a) kLo = Math.max(p.first, Math.floor(a) - 1);
      if (b === b) kHi = Math.min(p.last, Math.ceil(b) + 1);
    }
    if (kHi < kLo) return { keys: out, info: info };
    var count = kHi - kLo + 1;
    var width = band.full ? 1 : Math.min(1, band.tHi - band.tLo);
    info.expected = count * width;

    function accept(k) {
      if (p.gaps && !isIssued(k, p.gaps)) return;
      var t = truePlace(p, k); info.scanned++;
      if (inRect(rc, t.x, t.y)) out.push(k);
    }

    if (count <= LIMITS.scanCap || p.mode === 'float' || p.W > TWO53) {
      // plain scan (exact when count small; for the float/huge-wrap fallback, a seeded sample of the band)
      if (count <= LIMITS.scanCap) { for (var k = kLo; k <= kHi; k++) accept(k); }
      else { var rn = rng(seed || 1); info.method = 'band-sample'; info.exact = false; for (var i = 0; i < 8 * maxOut && out.length < maxOut; i++) accept(kLo + Math.floor(rn() * count)); }
    } else {
      // lattice enumeration in (k, y) with y = kG - wW in [yLo, yHi), yHi - yLo <= W
      info.method = 'lattice';
      var Gb = BigInt(p.G), Wb = BigInt(p.W);
      var yLo = band.full ? 0 : band.tLo * p.W, yHi = band.full ? p.W : band.tHi * p.W;
      var Sx = 1 / Math.max(1, count), Sy = 1 / Math.max(1e-300, yHi - yLo);
      var u1 = [BigInt(1), Gb], u2 = [BigInt(0), Wb];
      function n2(u) { var ax = Number(u[0]) * Sx, ay = Number(u[1]) * Sy; return ax * ax + ay * ay; }
      function dot(u, v) { return Number(u[0]) * Number(v[0]) * Sx * Sx + Number(u[1]) * Number(v[1]) * Sy * Sy; }
      if (n2(u1) > n2(u2)) { var tmp = u1; u1 = u2; u2 = tmp; }
      for (var it = 0; it < 200; it++) {
        var qf = Math.round(dot(u1, u2) / n2(u1)); if (qf === 0 || !isFinite(qf)) break;
        var qb = BigInt(qf); u2 = [u2[0] - qb * u1[0], u2[1] - qb * u1[1]];
        if (n2(u2) < n2(u1)) { var t2 = u1; u1 = u2; u2 = t2; } else break;
      }
      var a1 = Number(u1[0]), y1 = Number(u1[1]), a2 = Number(u2[0]), y2 = Number(u2[1]);
      var det = Number(u1[0] * u2[1] - u2[0] * u1[1]); // = +-W exactly
      if (det === 0) { info.note = 'degenerate lattice'; return { keys: out, info: info }; }
      // Anchor at the band's middle key k0: work in k' = k - k0 and y' = y - m(k0) brought near 0, so the lattice
      // coordinates (i, j) of every candidate are small and their products stay exact even when k is near 9e15.
      // The lattice basis is unchanged by the translation.
      var cnt = kHi - kLo, h0 = Math.floor(cnt / 2), k0 = kLo + h0, y0 = mOf(p, k0);
      var kkLo = -h0, kkHi = cnt - h0;
      var yLoA = yLo - y0, yHiA = yHi - y0, shift = Math.round(yLoA / p.W) * p.W; yLoA -= shift; yHiA -= shift;
      var iMin = Infinity, iMax = -Infinity;
      var corners = [[kkLo, yLoA], [kkHi, yLoA], [kkLo, yHiA], [kkHi, yHiA]];
      for (var c = 0; c < 4; c++) { var iv = (y2 * corners[c][0] - a2 * corners[c][1]) / det; if (iv < iMin) iMin = iv; if (iv > iMax) iMax = iv; }
      var iLo = Math.floor(iMin) - 1, iHi = Math.ceil(iMax) + 1;
      info.lattice = { a1: a1, y1: y1, a2: a2, y2: y2, det: det, iLo: iLo, iHi: iHi, kLo: kLo, kHi: kHi, k0: k0, y0: y0, yLo: yLo, yHi: yHi };
      function jRange(i) {
        var lo = -Infinity, hi = Infinity, A, B;
        if (a2 !== 0) { A = (kkLo - i * a1) / a2; B = (kkHi - i * a1) / a2; if (A > B) { var s = A; A = B; B = s; } lo = Math.max(lo, A); hi = Math.min(hi, B); }
        else if (i * a1 < kkLo || i * a1 > kkHi) return null;
        if (y2 !== 0) { A = (yLoA - i * y1) / y2; B = (yHiA - i * y1) / y2; if (A > B) { var s2 = A; A = B; B = s2; } lo = Math.max(lo, A); hi = Math.min(hi, B); }
        else if (i * y1 < yLoA || i * y1 >= yHiA) return null;
        var jl = Math.ceil(lo) - 1, jh = Math.floor(hi) + 1;
        return jh < jl ? null : [jl, jh];
      }
      var hardCap = 8 * LIMITS.candidateCap, BIG = 4503599627370496; // 2^52: above this a product may be inexact
      function tryKey(i, j) {
        var pa = i * a1, pb = j * a2, kk; info.candidates++;
        if (Math.abs(pa) > BIG || Math.abs(pb) > BIG) kk = Number(BigInt(i) * BigInt(a1) + BigInt(j) * BigInt(a2)); else kk = pa + pb;
        if (kk < kkLo || kk > kkHi) return;
        var k = k0 + kk, yk = mOf(p, k);
        if (!((yk >= yLo && yk < yHi) || (yk + p.W >= yLo && yk + p.W < yHi) || (yk - p.W >= yLo && yk - p.W < yHi))) return;
        accept(k);
      }
      if (info.expected <= LIMITS.candidateCap && (iHi - iLo) <= 4 * LIMITS.candidateCap) {
        enumerate: for (var ii = iLo; ii <= iHi; ii++) {
          var jr = jRange(ii); if (!jr) continue;
          for (var jj = jr[0]; jj <= jr[1]; jj++) { tryKey(ii, jj); if (info.candidates > hardCap) { info.exact = false; info.note = 'candidate cap reached'; break enumerate; } }
        }
        if (out.length > maxOut) { // too many for the screen: deterministic thinning keeps the picture fair
          info.exact = false; info.note = 'thinned from ' + out.length + ' to ' + maxOut;
          out.sort(function (x, y) { return x - y; });
          var thin = [], step = out.length / maxOut, r0 = rng(seed || 1);
          for (var s3 = 0; s3 < maxOut; s3++) thin.push(out[Math.min(out.length - 1, Math.floor(s3 * step + r0() * step))]);
          out = thin;
        }
      } else {
        info.exact = false; info.method = 'lattice-sample';
        var rn2 = rng(seed || 1), seen = new Set(), span = iHi - iLo + 1;
        for (var at = 0; at < 6 * maxOut && out.length < maxOut; at++) {
          var i2 = iLo + Math.floor(rn2() * span), jr2 = jRange(i2); if (!jr2) continue;
          var j2 = jr2[0] + Math.floor(rn2() * (jr2[1] - jr2[0] + 1));
          var k2 = i2 * a1 + j2 * a2; if (seen.has(k2)) continue; seen.add(k2);
          tryKey(i2, j2);
          if (info.candidates > hardCap) { info.note = 'candidate cap reached'; break; }
        }
      }
    }
    return { keys: out, info: info };
  }

  // ------------------------------------------------------------------ 3. visibleKeys(params, view, maxDots)
  function visibleKeys(params, view, maxDots) {
    var p = prepare(params), rc = rectOfView(view);
    var res = keysInRect(p, rc, maxDots, 7);
    var keys = res.keys;
    moves.forEach(function (v, k) { if (inRect(rc, v.x, v.y) && keys.indexOf(k) < 0) keys.push(k); });
    keys.info = res.info; keys.note = res.info.note || p.note || null;
    return keys;
  }

  // ------------------------------------------------------------------ 2. sample(params, maxDots, viewport)
  // A fair picture of N particles: all of them when N <= maxDots; otherwise one deterministic pick from each of
  // maxDots equal-count key bands [first + N i/m, first + N (i+1)/m) (equal count = equal area for the real law),
  // plus every true neighbour inside the viewport when one is given, so the magnifier is honest.
  function sample(params, maxDots, viewport) {
    var p = prepare(params);
    var m = Math.max(1, Math.floor(fin(maxDots, 4000))), N = p.count, keys = [];
    if (N <= m) {
      for (var k = p.first; k <= p.last; k++) if (!p.gaps || isIssued(k, p.gaps)) keys.push(k);
      keys.exact = true;
    } else {
      var seedBase = hash32((N % TWO32) >>> 0) ^ hash32(Math.floor(N / TWO32) >>> 0);
      for (var i = 0; i < m; i++) {
        var lo = p.first + Math.floor(N * i / m), hi = p.first + Math.floor(N * (i + 1) / m); // [lo, hi)
        if (hi <= lo) hi = lo + 1;
        var span = hi - lo, h = hash32(seedBase ^ i), pick = lo + Math.floor(h / TWO32 * span);
        if (pick >= hi) pick = hi - 1;
        if (p.gaps && !isIssued(pick, p.gaps)) { // try a few more spots in the band before giving the band up as dark
          var ok = false; for (var t = 1; t <= 4 && !ok; t++) { var h2 = hash32(h + t); var p2 = lo + Math.floor(h2 / TWO32 * span); if (isIssued(p2, p.gaps)) { pick = p2; ok = true; } }
          if (!ok) continue;
        }
        keys.push(pick);
      }
      if (p.first <= p.last && keys.indexOf(p.first) < 0 && (!p.gaps || isIssued(p.first, p.gaps))) keys.unshift(p.first); // the first particle is always there
      keys.exact = false;
    }
    if (viewport) {
      var vis = visibleKeys(p, viewport, m);
      var set = new Set(keys); for (var v = 0; v < vis.length; v++) if (!set.has(vis[v])) { set.add(vis[v]); keys.push(vis[v]); }
      keys.visible = vis.length;
    }
    keys.represents = N / Math.max(1, keys.length);
    keys.note = p.note || null;
    return keys;
  }

  // ------------------------------------------------------------------ 4. pick(params, x, y, view)
  // Nearest particle to a world point: candidates from the radius band around r^power inverse (both sides),
  // through the exact lattice enumeration in a square that grows until something is found. Moved particles count
  // at their moved place. Returns {key, distance, place, screenDistance} or null when there is nothing at all.
  function pick(params, x, y, view) {
    var p = prepare(params); x = fin(x, 0); y = fin(y, 0);
    var zoom = view && isFinite(+view.zoom) && +view.zoom > 0 ? +view.zoom : 1;
    var rim = radiusOf(p, p.last); if (!isFinite(rim)) rim = 1e6;
    var s = Math.max(24 / zoom, 1.5), best = null, bestD = Infinity;
    function consider(k, px, py) { var d = Math.hypot(px - x, py - y); if (d < bestD) { bestD = d; best = k; } }
    moves.forEach(function (v, k) { consider(k, v.x, v.y); });
    for (var round = 0; round < 40; round++) {
      var rc = { x0: x - s, x1: x + s, y0: y - s, y1: y + s };
      var res = keysInRect(p, rc, 1024, 11);
      for (var i = 0; i < res.keys.length; i++) { var k = res.keys[i]; if (moves.has(k)) continue; var t = truePlace(p, k); consider(k, t.x, t.y); }
      if (best !== null && bestD <= s) break; // the nearest found is inside the searched square, so it is the nearest
      if (s > rim + Math.hypot(x, y) + 2) break;
      s *= 4;
    }
    if (best === null) return null;
    var pl = place(best, p);
    return { key: best, distance: bestD, screenDistance: bestD * zoom, place: pl, moved: pl.moved };
  }

  // A free particle (not a key) placed anywhere: its own polar reading and its nearest real neighbour.
  function freeDot(x, y, params) {
    x = fin(x, 0); y = fin(y, 0);
    var near = params === undefined && !moves.size ? null : pick(params || REAL, x, y, null);
    return { x: x, y: y, r: Math.hypot(x, y), deg: degOf(x, y), turns: degOf(x, y) / 360,
             keyAtThisRadius: keyAtRadius(prepare(params || REAL), Math.hypot(x, y)),
             nearestKey: near ? near.key : null, nearestDistance: near ? near.distance : null, nearest: near ? near.place : null };
  }