GLOBALGRID2050 / EXPLORE CODE

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

Kuiper Belt — Editions Page

A web page that converts to world (`toWorld`), steps anim (`stepAnim`), places panels (`placePanels`) and calculates planar distances, using SHA-256. Published at https://ventusltd.github.io/kuiper-belt/editions/202611021201/.

524 lines of HTML from kuiper-belt, in 1 file. Topic: Kuiper, cosmos and drawing engines. Section 1522 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 — Editions Page render · kuiper-belt / editions/202611021201/index.html lines 438–961

Kuiper Belt — Editions Page

A web page that converts to world (`toWorld`), steps anim (`stepAnim`), places panels (`placePanels`) and calculates planar distances, using SHA-256. Published at https://ventusltd.github.io/kuiper-belt/editions/202611021201/.

renderkuiper-belt / editions/202611021201/index.html · lines 438–961 of 961 · version 2026-11-02 12:01 (continued from section 1521) · Entry point · pattern loadEdition (shared by 2 files)

What it does
It draws its content. Defines 62 functions or classes, including fmt, words, refuse, prog, U. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). README: "the stamp is written in three places in `index.html` (meta refresh, the link, `location.replace`), as `learn-the-kuiper/index.html` does."
Inputs & outputs
In: JSON file keys-min.json; JSON file keys.json; JSON file modules.json; form fields (user input). Out: web page; WebGL/WebGPU drawing.
Downstream impact
Used directly by 2 files: Kuiper Belt — Editions Page (kuiper-belt, https://ventusltd.github.io/kuiper-belt/editions/); After (neural-link-between-agents). Reached from 1 other entry point, including GlobalGrid2050 — Kuiper Editions Page (globalgrid2050, https://globalgrid2050.com/kuiper-editions/). It is itself an entry point, published at https://ventusltd.github.io/kuiper-belt/editions/202611021201/.
What it achieves
It shows new (`showNew`), loads edition (`loadEdition`) and draws edition (`drawEdition`). Its `describe` function gives human readable address description from resolved address and repository metadata (VEDIC: explain). It reads `modules.json`. It responds to webglcontextlost, resize and pointerdown events.
Why it matters
Loaded by the page of the same name at https://ventusltd.github.io/kuiper-belt/editions/. Also imported by After, from Neural Link Between Agents.
Application
kuiper-belt · editions/202611021201 · 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
linked from Kuiper Belt — Editions Page (link), named by URL in After (estate URL)
Produces
fmt, words, refuse, prog, U, tsv, narrow, resize, flyTo, layout, safeBox, homeCamera
Defines here
stepAnim, finishSelftest, repoSelftest, strip, check, phoneSelftest, ev, lightTime, isTap, pinchNow, pointerGone, loadEdition, edScreen, drawEdition, edCard, edBand, edAim, edFly, edKeep, esc, edNext, placePanels, setPanel, edSync, visibleLine, fillLines, kyLine, kyRefuse, kyHex, kyInject
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
kuiper-belt@26fba12ab1b5bab8e71934ab86c58273e5f32682 editions/202611021201/index.html:438-961 · blob b12bd24b2d6a250aa1467229dc056db51b8df943 · GitHub at these lines
State
achieves: code · context: readme_derived · stage: output · effects: dom, network · domain stage: agent_infra · users: ai_agent · canonical: unknown
  newFrom = findBy('unix', cut - 1) + (commits[0].unix >= cut ? 0 : 1); if (newFrom >= commits.length) newFrom = commits.length - 1;
  litRepo = -1; target = null; card.style.display = 'none'; tween = null;
  const R = Math.sqrt(SPACE); cx = 0; cy = 0; zoom = (Math.min(cv.width, cv.height)/2) * 0.80 / R;
  anim_hours = hours; anim = { t0:performance.now(), hours, R }; dirty = true;
}
function stepAnim(){
  const t = (performance.now() - anim.t0) / 1000; dirty = true;
  if (t < 1.6) { const u = t/1.6; pulse = anim.R * (u*u*(3-2*u)); flash = 0; }
  else if (t < 2.5) { pulse = -1; flash = 1 - 0.45*((t-1.6)/0.9); if (selftest && selftest.wantPixels === undefined) selftest.wantPixels = true; }
  else { const c = commits[newFrom], n = commits.length - newFrom; let lines = 0; for (let i = newFrom; i < commits.length; i++) lines += commits[i].lines;
    flash = 0.35; anim = null; const p = keyPlace(c.k0); target = { x:p[0], y:p[1], boundary:true };
    card.style.display = 'block';
    card.innerHTML = 'NEW CODE · the last ' + anim_hours + ' hours before the newest commit\n<b>' + fmt(lines) + '</b> lines in <b>' + fmt(n) + '</b> commits, one band at the rim'
      + '\nbegins at key <b>' + fmt(c.k0) + '</b> · ' + repos[c.repo].name + ' / ' + c.sha + ' · ' + new Date(c.unix*1000).toISOString().slice(0,16) + 'Z'
      + '\nthe text itself:  python tools/key.py ' + c.k0;
    flyTo(p[0], p[1], 14);
    if (selftest) finishSelftest(c, n, lines); }
}
let anim_hours = 24;
// THE TESTS, run by the page on itself with ?selftest=new, so the verdict is not an opinion.
function finishSelftest(c, n, lines){
  let maxOld = 0; for (let i = 0; i < newFrom; i++) maxOld = Math.max(maxOld, commits[i].k1);
  const a = address(c.k0), nb = selftest.newBandPixel || [0,0,0], pp = selftest.pupilPixel || [0,0,0];
  const T = { T1_new_is_one_band_beyond_everything_older: c.k0 >= maxOld,
              T2_boundary_key_resolves_to_a_new_commit: !!(a && !a.silent && a.i >= newFrom && a.m === 0),
              T3_flash_is_amber_on_the_new_band: nb[0] > 150 && nb[0] > nb[2] + 40,
              T3_no_flash_on_the_silent_centre: pp[0] < 40 && pp[1] < 40,
              new_commits: n, new_lines: lines, boundary_key: c.k0, newBandPixel: nb, pupilPixel: pp };
  T.PASS = T.T1_new_is_one_band_beyond_everything_older && T.T2_boundary_key_resolves_to_a_new_commit && T.T3_flash_is_amber_on_the_new_band && T.T3_no_flash_on_the_silent_centre;
  window.__selftest = T; document.title = 'selftest ' + (T.PASS ? 'PASS' : 'FAIL');
}
// LIGHT A REPOSITORY, TESTED. ?selftest=repo:<name>, or repo:* for the largest one. Two questions.
// ONE, the picture: walking outward from the centre, a pixel is green if and only if the key at
// that pixel's centre belongs to that repository. A pixel whose radial span straddles a change of
// owner is excluded and counted separately, because at this zoom one pixel covers hundreds of
// millions of addresses and the shader and this loop need not agree on which side of the line it
// falls. Every other pixel must agree exactly.
// TWO, the number: the repository's line total added up through the running totals, which is the
// arithmetic the shading itself is made of, must equal the direct sum of its commits, and both
// must equal what cosmos/repos.tsv declared before any of this was drawn. Three sources, one
// number, or the test fails.
function repoSelftest(name){
  const rp = (name === '*') ? repos.reduce((a, b) => b.lines > a.lines ? b : a)
                            : repos.find(x => x.name.toLowerCase() === name.toLowerCase());
  if (!rp) { window.__selftest = { PASS:false, asked_for:name, error:'no repository of that name is on this wafer' };
    document.title = 'selftest FAIL'; return; }
  let byRunning = 0, directly = 0, n = 0;
  for (const c of commits) if (c.repo === rp.i) { byRunning += issuedBelow(c.k1) - issuedBelow(c.k0); directly += c.lines; n++; }
  litRepo = rp.i; litK = [-1,-1]; litCi = null; newFrom = -1; flash = 0; pulse = -1; target = null; card.style.display = 'none';
  tween = null; { const h = homeCamera(); cx = h.x; cy = h.y; zoom = h.z; } draw();
  const W = cv.width, H = cv.height, Rpx = Math.sqrt(SPACE)*zoom;
  const col0 = Math.round(W/2 - cx*zoom), row0 = Math.round(H/2 - cy*zoom);   // the wafer's own centre, in GL pixels
  const span = Math.max(4, Math.floor(Rpx) - 1);
  const strip = (x, y, w, h) => { const b = new Uint8Array(w*h*4); gl.readPixels(x, y, w, h, gl.RGBA, gl.UNSIGNED_BYTE, b); return b; };
  const east = strip(col0, row0, span, 1), north = strip(col0, row0, 1, span);
  let lit = 0, dark = 0, wrong = 0, straddled = 0; const wrongAt = [];
  function check(buf, i, wx, wy, hx, hy, where){
    const own = ownerAt(Math.hypot(wx, wy));
    if (ownerAt(Math.hypot(wx-hx, wy-hy)) !== own || ownerAt(Math.hypot(wx+hx, wy+hy)) !== own) { straddled++; return; }
    const r0 = buf[i*4], g0 = buf[i*4+1], b0 = buf[i*4+2];
    const green = g0 > 120 && g0 > r0 + 40 && g0 > b0 + 30;
    if (green === (own === rp.i)) { green ? lit++ : dark++; }
    else { wrong++; if (wrongAt.length < 8) wrongAt.push({ strip:where, pixel_from_centre:i,
      key_belongs_to: own === -1 ? 'silence' : (own === -2 ? 'beyond the rim' : repos[own].name),
      drawn: green ? 'green' : 'not green', rgb:[r0, g0, b0] }); }
  }
  const hudWhenLit = hud.textContent;                 // what the page told the reader while it was lit
  const wy0 = cy + (row0 + 0.5 - H/2)/zoom, wx0 = cx + (col0 + 0.5 - W/2)/zoom, h = 0.5/zoom;
  for (let i = 0; i < span; i++) check(east, i, cx + (col0 + i + 0.5 - W/2)/zoom, wy0, h, 0, 'east');
  for (let i = 0; i < span; i++) check(north, i, wx0, cy + (row0 + i + 0.5 - H/2)/zoom, 0, h, 'north');
  { const hm = homeCamera(); cx = hm.x; cy = hm.y; zoom = hm.z; litRepo = -1; dirty = true; draw(); }
  const wpx = widestRunPx(rp.i, Rpx/Math.sqrt(SPACE));
  const tooSmall = wpx < 1;
  const said = /FINER THAN ONE PIXEL/.test(hudWhenLit);
  const T = { repository: rp.name, commits: n, viewport:[W, H], wafer_radius_px: Math.round(Rpx), pixels_walked: 2*span,
    // A pixel is green if and only if the key at its centre belongs to this repository. Nothing
    // else is asserted: a repository under a pixel wide lights nothing, and the second test is
    // that the page says that out loud instead of showing an empty wafer and letting it pass.
    T1_no_pixel_disagrees_with_the_keys: wrong === 0,
    T2_it_lights_pixels_or_the_page_says_it_is_too_small: lit > 0 || (tooSmall && said),
    widest_unbroken_run_px_at_this_zoom: +wpx.toFixed(4), finer_than_one_pixel: tooSmall, the_page_said_so: said,
    pixels: { green_and_owned_by_it: lit, not_green_and_not_owned_by_it: dark, disagreed: wrong, straddled_a_boundary_and_excluded: straddled },
    first_disagreements: wrongAt,
    T3_running_totals_equal_the_direct_sum: byRunning === directly,
    T4_and_equal_what_the_belt_declared: directly === rp.lines,
    lines_by_running_totals: byRunning, lines_added_directly: directly, lines_declared_by_the_belt: rp.lines };
  T.PASS = T.T1_no_pixel_disagrees_with_the_keys && T.T2_it_lights_pixels_or_the_page_says_it_is_too_small
        && T.T3_running_totals_equal_the_direct_sum && T.T4_and_equal_what_the_belt_declared;
  window.__selftest = T; document.title = 'selftest ' + (T.PASS ? 'PASS' : 'FAIL');
}
// THE PHONE TEST, run by the page on itself with ?selftest=phone at whatever size the window is.
// It states that size, so the verdict is about a real viewport and not about a claim. Three
// mechanical questions: does any permanent panel cover the wafer, does the card fit on the screen,
// and do a drag and a two finger pinch actually move the camera when the events are dispatched.
function phoneSelftest(){
  tween = null; { const h = homeCamera(); cx = h.x; cy = h.y; zoom = h.z; } draw();
  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;
// TAP OR DRAG (Edition 5): a finger jitters, so a tap is movement under a slop (10 px for touch, Android's
// own, 4 px for a mouse) measured from the point it went down, and for touch a press shorter than 700 ms, so
// a long press is not a tap. tapUp is the verdict of the last pointerup, read by the edition layer.
let down = null, slop = 4, tapUp = false;
function isTap(e){ return !!down && moved < slop && (e.pointerType !== 'touch' || e.timeStamp - down[2] < 700); }
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]; down = [e.clientX, e.clientY, e.timeStamp]; slop = e.pointerType === 'touch' ? 10 : 4; 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.max(moved, Math.hypot(e.clientX-down[0], e.clientY-down[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 => {
  tapUp = !!drag && isTap(e);
  if (tapUp && 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(); } });

// ============================================================ KUIPER EDITION 2: the verified lines
// Edition 1 (../202610311905/) verified 354 keyed findings of the estate and placed 346 distinct lines
// on a belt of their own. Edition 2 draws the same lines where they already are on THIS wafer: each
// line's key was computed by tools/edition_keys.py with key.py's walk (ls-tree order, lines_of), so a
// spark here is a key that python tools/key.py would resolve to that very line. Lines whose commit is
// not on the wafer are counted and named, never placed: the seventh law.
let ED = [], edPlaced = [], edSel = -1, edMeta = null;
const EDPATH = 'keys-min.json', EDFULL = 'keys.json';
// EDITION 5 (perf, NL-009 07): the page draws 17 of the 36 fields of each record, so it loads keys-min.json
// (1,558,451 bytes, written from keys.json by tools/edition_min.py, which records the sha256 of its source). The
// card law keeps line_text whole, so 07's 233 kB is not reached: one record's line_text is 1,240,449 bytes.
// keys.json (1,709,129 bytes) stays in the folder as the evidence. Without the compact file the full one loads.
async function loadEdition(){
  try { let r = await fetch(EDPATH); if (!r.ok) r = await fetch(EDFULL); if (!r.ok) throw new Error(EDFULL); const j = await r.json();
    edMeta = j.summary || {}; ED = j.bodies || j; }
  catch (e) { ED = []; edMeta = { error: 'keys.json did not load' }; }
  edPlaced = ED.filter(b => b.on_wafer && b.verified && Number.isFinite(b.key) && b.key >= 0 && b.key < SPACE)
               .map(b => { const p = keyPlace(b.key); return Object.assign({}, b, { x:p[0], y:p[1] }); });
  big.textContent = 'Kuiper Edition 12 · ' + (edMeta && edMeta.error ? edMeta.error + ' · no verified lines lit' : fmt(edPlaced.length) + ' verified lines lit');
  sub.textContent = 'Edition 1 verified ' + fmt(ED.length) + ' lines of the estate (354 keyed findings, 495 keys re-resolved; see ../202610311905/). '
    + 'Here each is a green spark at its own key on the one wafer: ' + sub.textContent;
  dirty = true;
}
function edScreen(b){ return [(b.x - cx)*zoom + ov.width/2, ov.height/2 - (b.y - cy)*zoom]; }
function drawEdition(){
  if (!edPlaced.length) { if (edMeta) hud.textContent += '\nEDITION 5 · ' + (edMeta.error || 'no lines placed'); return; }
  let onScreen = 0;
  for (let i = 0; i < edPlaced.length; i++) { const b = edPlaced[i], [x, y] = edScreen(b);
    if (x < -8 || y < -8 || x > ov.width + 8 || y > ov.height + 8) continue; onScreen++;
    const sel = i === edSel, focus = b.class === 'focus';
    o2.beginPath(); o2.arc(x, y, sel ? 6 : (focus ? 3.2 : 2.6), 0, 6.2832);
    o2.fillStyle = sel ? 'rgba(255,43,214,.95)' : (focus ? 'rgba(34,238,119,.95)' : 'rgba(34,238,119,.70)'); o2.fill();
    if (sel) { o2.strokeStyle = 'rgba(255,43,214,.9)'; o2.lineWidth = 1.5; o2.beginPath(); o2.arc(x, y, 14, 0, 6.2832); o2.stroke(); } }
  const notOn = ED.length - edPlaced.length;
  hud.textContent += '\nEDITION 5 · ' + fmt(edPlaced.length) + ' verified lines on this wafer, ' + fmt(onScreen) + ' in view'
    + (notOn ? ' · ' + fmt(notOn) + ' not on the wafer (named in keys.json), counted, not placed' : '')
    + ' · bright green: gridatlas and the data-centre repositories · green: the rest of the estate';
}
{ const _draw = draw; draw = function(){ _draw(); drawEdition(); }; }
function edCard(i){
  const b = edPlaced[i], a = address(b.key);
  // EDITION 5, the card law (Opus 2, step 2): the line-card module renders the card; the line of code is the header
  const LC = window.KY && KY.modules && KY.modules['line-card'];
  if (LC) { edSel = i; LC.api.show(b, { index:i, of:edPlaced.length, onclose: () => { edSel = -1; dirty = true; } }); return; }
  card.style.display = 'block'; card.classList.remove('open');
  card.setAttribute('role', 'region'); card.setAttribute('aria-label', 'verified line'); card.setAttribute('aria-live', 'polite');
  card.innerHTML = '<button class="cx" aria-label="close">×</button>'
    + '<b>' + esc(b.title) + '</b>  <span style="color:var(--dim)">' + fmt(i + 1) + ' of ' + fmt(edPlaced.length) + '</span>'
    + '\n' + esc(b.repo) + '  ' + esc(b.path) + ':' + b.line
    + (b.quote ? '<div class="cq">' + esc(b.quote) + '</div>' : '')
    + '<a href="' + esc(b.destination) + '" target="_blank" rel="noopener">open on GitHub at ' + esc(String(b.commit).slice(0,7)) + '</a>'
    + '  ·  <button class="ct" aria-expanded="false">details</button>'
    + '<div class="cd">' + (b.pattern ? 'pattern: ' + esc(b.pattern) + '\n' : '') + 'found by ' + esc(b.worker) + ' ' + esc(b.finding) + ', verified by a controller\n' + describe(a) + '</div>';
  if (a && !a.silent) litRepo = a.c.repo;
  target = { x:b.x, y:b.y }; edSel = i; dirty = true;
}
// the card toggles its details, closes on ×, and never swallows the link
card.addEventListener('click', e => {
  if (e.target.closest('.cx')) { card.style.display = 'none'; edSel = -1; target = null; dirty = true; e.stopPropagation(); return; }
  if (e.target.closest('.ct')) { const on = card.classList.toggle('open'); e.target.closest('.ct').setAttribute('aria-expanded', on ? 'true' : 'false'); e.stopPropagation(); return; }
  if (e.target.closest('a')) { e.stopPropagation(); return; }
  e.stopImmediatePropagation();                                  // a tap on the card body keeps it open (also from the engine's own close-on-click)
}, true);
// fly so that the spark lands in the clear band: under the bar and any open panel, above the card. The band is
// measured from the live rectangles, measured again on the next frame (the card has been laid out and painted by
// then) and whenever the card changes height (details, a long quote, a turned phone), so the spark never ends under
// the card or the bar. A panel that would cover the band is closed by the pick, as a LINES row already does.
const ED_Z = 14, ED_MARGIN = 8, ED_MINBAND = 96;
function edBand(){
  const s = safeBox(); let top = s.y0, bot = innerHeight - ED_MARGIN;
  for (const el of document.querySelectorAll('.gm-open')) { const r = el.getBoundingClientRect(); if (r.height > 0 && r.top < innerHeight/2) top = Math.max(top, r.bottom + ED_MARGIN); }
  if (card.style.display === 'block') { const r = card.getBoundingClientRect(); if (r.height > 0) bot = Math.min(bot, r.top - ED_MARGIN); }
  if (bot < top + 24) bot = top + 24;
  return { x0:s.x0, x1:s.x1, y0:top, y1:bot };
}
function edAim(b, z){ const a = edBand(), mx = (a.x0 + a.x1)/2, my = (a.y0 + a.y1)/2;
  return { x:b.x - (mx - innerWidth/2)/z, y:b.y + (my - innerHeight/2)/z, z }; }
let edFlown = null;
function edFly(b){
  const g = edBand(); if (openPanel && g.y1 - g.y0 < ED_MINBAND) setPanel(openPanel);
  const z = ED_Z, [sx, sy] = edScreen(b), far = Math.hypot(sx - innerWidth/2, sy - innerHeight/2) + Math.abs(Math.log2(z/zoom))*120;
  const t = edAim(b, z); atHome = false; edFlown = b; flyTo(t.x, t.y, z);
  tween.dur = matchMedia('(prefers-reduced-motion: reduce)').matches ? 1 : Math.max(300, Math.min(900, 300 + far*0.6));   // a short hop is quick, home to spark takes the full 900 ms
  requestAnimationFrame(() => { if (edFlown !== b || !tween) return; const u = edAim(b, z); tween.x1 = u.x; tween.y1 = u.y; });   // aim again once the card is laid out
}
// the card grew or shrank, or the phone was turned, after the fly: keep the spark inside the band
function edKeep(){ if (tween || edSel < 0 || !edFlown || card.style.display !== 'block' || document.querySelector('.gm-open')) return;
  const b = edPlaced[edSel]; if (!b) return; const a = edBand(), [sx, sy] = edScreen(b);
  if (sx >= a.x0 + 12 && sx <= a.x1 - 12 && sy >= a.y0 + 12 && sy <= a.y1 - 12) return;
  const t = edAim(b, zoom); flyTo(t.x, t.y, zoom); tween.dur = 350; }
if (typeof ResizeObserver === 'function') new ResizeObserver(() => edKeep()).observe(card);
addEventListener('resize', () => requestAnimationFrame(edKeep));
function esc(v){ return String(v == null ? '' : v).replace(/[&<>"]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c])); }
function edNext(step){ if (!edPlaced.length) return; edSel = (edSel + step + edPlaced.length) % edPlaced.length;
  const b = edPlaced[edSel]; edCard(edSel); edFly(b); }
// a tap on the wafer opens the nearest spark within reach: 24 px for a finger (Android's touch target), 9 px for a
// mouse. A tap is one pointer that went down on the canvas and came up within 10 px of where it went down, however
// long it stayed (a finger's wobble is not a drag, a slow press is still a tap); a drag, a pinch, or a tap on the
// bar, the card or a panel never picks a spark, and sparks of a layer that is switched off are not hit. Runs after
// the engine's own tap handler.
const ED_TAP_TOUCH = 24, ED_TAP_MOUSE = 9, ED_SLOP = 10;
let edDown = null;
cv.addEventListener('pointerdown', e => { edDown = pts.size === 1 ? { id:e.pointerId, x:e.clientX, y:e.clientY } : null; });
addEventListener('pointercancel', () => { edDown = null; });
addEventListener('pointerup', e => {
  const d = edDown; edDown = null;
  if (!d || d.id !== e.pointerId || e.target !== cv || !tapUp || !edPlaced.length || pts.size > 0) return;   // tapUp: NL-009 04-touch's verdict (10 px slop, 700 ms)
  if (Math.hypot(e.clientX - d.x, e.clientY - d.y) > ED_SLOP) return;
  const R = e.pointerType === 'mouse' ? ED_TAP_MOUSE : ED_TAP_TOUCH; let best = -1, bd = R*R;
  for (let i = 0; i < edPlaced.length; i++) { if (!visibleLine(edPlaced[i])) continue; const [x, y] = edScreen(edPlaced[i]); const q = (x - e.clientX)**2 + (y - e.clientY)**2; if (q < bd) { bd = q; best = i; } }
  if (best >= 0) { edCard(best); edFly(edPlaced[best]); }
});
addEventListener('keydown', e => { if (gbox.style.display === 'block') return;
  if (e.key === 'e') edNext(1); else if (e.key === 'E') edNext(-1); else if (e.key === 'Backspace') edSel = -1; });

// ============================================================ EDITION 3: the menu bar, panels at rest hidden
// Borrowed in spirit from gridatlas atlas/modules/202609031958-menu-bar.js: one row of titles, every panel
// hidden until its title is tapped, one open at a time, closed by the same tap, by Escape, or by a tap on the
// wafer. The wafer gets the whole screen; the readout, the commands and the edition's own text are layers.
const bar = document.createElement('div'); bar.id = 'bar'; bar.setAttribute('role', 'toolbar'); bar.setAttribute('aria-label', 'Kuiper Edition menu');
bar.innerHTML = '<span id="barname">KUIPER EDITION 6</span>'
  + '<button class="gm-title" data-panel="top" aria-controls="top" aria-expanded="false">edition</button>'
  + '<button class="gm-title" data-panel="hud" aria-controls="hud" aria-expanded="false">readout</button>'
  + '<button class="gm-title" data-panel="lines" aria-controls="lines" aria-expanded="false">lines</button>'
  + '<button class="gm-title" data-panel="foot" aria-controls="foot" aria-expanded="false">commands</button>';
document.body.prepend(bar);
const linesPanel = document.createElement('div'); linesPanel.id = 'lines'; linesPanel.className = 'gm-panel';
linesPanel.innerHTML = '<div id="linesctl"><label><input type="checkbox" id="lyAll" checked> verified lines layer</label>'
  + '<label><input type="checkbox" id="lyFocus"> gridatlas + data centres only</label>'
  + '<button data-k="e">next</button><button data-k="E">previous</button><input id="lyFind" aria-label="filter lines" placeholder="filter: repository, file or title"></div><div id="lineslist"></div>';
document.body.appendChild(linesPanel);
const PANELS = { top: elTop, hud: hud, lines: linesPanel, foot: elFoot };
for (const [k, el] of Object.entries(PANELS)) { el.setAttribute('role', 'region'); el.setAttribute('aria-label', { top:'edition', hud:'readout', lines:'lines', foot:'commands' }[k]); }
let openPanel = null;
function placePanels(){ const h = bar.getBoundingClientRect().height; for (const el of Object.values(PANELS)) el.style.top = (h + 2) + 'px'; }
addEventListener('resize', placePanels);
function setPanel(name){ placePanels();
  openPanel = (openPanel === name) ? null : name;
  for (const [k, el] of Object.entries(PANELS)) el.classList.toggle('gm-open', k === openPanel);
  for (const b of bar.querySelectorAll('.gm-title')) { const on = b.dataset.panel === openPanel; b.classList.toggle('gm-on', on); b.setAttribute('aria-expanded', on ? 'true' : 'false'); }
  if (openPanel === 'lines') fillLines();
  dirty = true;
}
bar.addEventListener('click', e => { const b = e.target.closest('.gm-title'); if (b) { e.stopPropagation(); setPanel(b.dataset.panel); } });
addEventListener('keydown', e => { if (e.key !== 'Escape' || gbox.style.display === 'block') return;
  if (openPanel) setPanel(openPanel); else if (card.style.display === 'block') { card.style.display = 'none'; edSel = -1; target = null; dirty = true; } });
cv.addEventListener('pointerdown', () => { if (openPanel) { setPanel(openPanel); moved = 99; } });   // the dismissing tap does nothing else
for (const el of [cv, ov, bar]) el.addEventListener('contextmenu', e => e.preventDefault());        // a long press on the wafer or the bar is not a menu
// ANDROID BACK (Edition 5). While a panel or the card is open the page holds one extra history entry, so the
// back gesture closes the layer instead of leaving the page; with nothing open, back leaves as it should. The
// entry follows the state on every redraw (every open or close sets dirty), so no close path is forgotten.
let edHist = false, edPopping = false;
function edSync(){ const open = !!openPanel || card.style.display === 'block';
  if (open && !edHist) { try { history.pushState({ kuiper:1 }, ''); } catch (e) {} edHist = true; }
  else if (!open && edHist) { edHist = false; if (history.state && history.state.kuiper) { edPopping = true; history.back(); } } }
addEventListener('popstate', () => {
  if (edPopping) { edPopping = false; edHist = !!(history.state && history.state.kuiper); edSync(); return; }   // our own back(): close nothing, re-arm if a layer opened meanwhile
  edHist = false; if (openPanel) setPanel(openPanel); if (card.style.display === 'block') { card.style.display = 'none'; edSel = -1; target = null; dirty = true; } });
{ const _draw = draw; draw = function(){ _draw(); edSync(); }; }
elTop.classList.add('open');                                   // the long subtitle is readable once the panel is open
// the safe rectangle now starts under the bar, and the hidden panels take no room
{ const _safe = safeBox; safeBox = function(){ const s = _safe(); placePanels(); s.y0 = Math.max(s.y0, bar.getBoundingClientRect().bottom + 8); s.y1 = Math.max(s.y0 + 24, innerHeight - 8); return s; }; }
// prefers-reduced-motion: the camera lands at once instead of flying for 900 ms
{ const _fly = flyTo, rm = matchMedia('(prefers-reduced-motion: reduce)'); flyTo = function(x, y, z){ _fly(x, y, z); if (rm.matches && tween) tween.t0 -= tween.dur; }; }
// the lines layer: on/off and focus-only, the list, the filter
let lyOn = true, lyFocus = false, lyQuery = '';
document.getElementById('lyAll').addEventListener('change', e => { lyOn = e.target.checked; dirty = true; });
document.getElementById('lyFocus').addEventListener('change', e => { lyFocus = e.target.checked; dirty = true; fillLines(); });
document.getElementById('lyFind').addEventListener('input', e => { lyQuery = e.target.value.trim().toLowerCase(); fillLines(); });
document.getElementById('lyFind').addEventListener('keydown', e => e.stopPropagation());
linesPanel.addEventListener('keydown', e => { const row = e.target.closest('[data-i]'); if (row && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); e.stopPropagation(); row.click(); } });
linesPanel.addEventListener('click', e => { const k = e.target.getAttribute('data-k'); if (k) { e.stopPropagation(); dispatchEvent(new KeyboardEvent('keydown', { key:k })); return; }
  const row = e.target.closest('[data-i]'); if (row) { e.stopPropagation(); const i = +row.dataset.i; const b = edPlaced[i]; if (openPanel) setPanel(openPanel); edCard(i); edFly(b); } });
function visibleLine(b){ return lyOn && (!lyFocus || b.class === 'focus'); }
function fillLines(){
  const list = document.getElementById('lineslist'); if (!list) return;
  const rows = [], LC = window.KY && KY.modules && KY.modules['line-card'];   // EDITION 5: a row reads line, key, title (step 2 K6)
  edPlaced.forEach((b, i) => { if (!visibleLine(b)) return;
    const hay = (b.repo + ' ' + b.path + ' ' + b.title).toLowerCase(); if (lyQuery && !hay.includes(lyQuery)) return;
    if (LC) { rows.push(LC.api.row(b, i, (i === edSel ? 'sel' : '') + (b.class === 'focus' ? ' focus' : ''))); return; }
    rows.push('<div class="ln' + (i === edSel ? ' sel' : '') + (b.class === 'focus' ? ' focus' : '') + '" data-i="' + i + '" role="button" tabindex="0"><b>' + esc(b.repo) + '</b> ' + esc(b.path) + ':' + b.line + '<br>' + esc(b.title) + '</div>'); });
  list.innerHTML = rows.join('') || '<div class="ln">' + (edMeta && edMeta.error ? esc(edMeta.error) : 'no line matches') + '</div>';
}
// the sparks obey the layer switches
{ const _drawEd = drawEdition; drawEdition = function(){ if (!lyOn) { hud.textContent += '\nEDITION 5 · verified lines layer off'; return; }
    const keep = edPlaced; if (lyFocus) edPlaced = keep.filter(b => b.class === 'focus'); try { _drawEd(); } finally { edPlaced = keep; } }; }
{ const _edNext = edNext; edNext = function(step){ if (!edPlaced.length) return; let i = edSel, n = edPlaced.length;
    for (let t = 0; t < n; t++) { i = (i + step + n) % n; if (visibleLine(edPlaced[i])) break; }
    edSel = i; const b = edPlaced[edSel]; edCard(edSel); edFly(b); }; }
// ======================================== KUIPER HOOK TABLE AND LOADER kuiper.hooks.v1 · begin (Opus team 4, step 4)
// Engine lines this patch changes: the wafer promise (one line after `let N = 0`, and kyWaferOk/kyWaferNo at the belt
// check, after `N = issued` and in the wafer.tsv catch), and the NL-009 round-1 fixes folded in by team 4: 09-robust
// (refuse() for the WebGL, context-lost, belt and wafer.tsv refusals, given slots here) and 04-touch (viewport, tap slop
// and tapUp). Nothing else above is changed. Everything a module
// may reach is in window.KY, built here after every wrap of the edition layer and frozen; the loader admits the
// modules of modules.json in `order`, each only when its bytes hash as recorded and every hook it requires exists,
// and refuses in words while the rest runs. Apache-2.0 (kuiper-belt). The same bytes, between the same two marker
// lines, are modules/202611012145-loader.js (the reviewable reference; it is never fetched). Lessons, cited:
// gridatlas@5ec7f62 atlas/index.html:39-44 (no-store, schema), :65-67 (missing id refused), :78-81 (hash in the
// browser), :82-83 (one blob script per cartridge), :104-114 (one published state); menu-bar.js:37-38 (never twice);
// atlas/modules/202610291043-uk-lightning-overlay.js:393-400 (one frozen API). The anti-lesson: learn-the-kuiper
// modes.html:16-24 skips a missing module silently; this loader says why, on screen.
const KY_EDITION = '202611021201';
const KY_NAMES = Object.freeze(['keyPlace', 'address', 'describe', 'findBy', 'flyTo', 'home', 'homeCamera', 'safeBox',
  'lightTime', 'showNew', 'goKey', 'fmt', 'words', 'esc', 'cv', 'ov', 'o2', 'hud', 'big', 'sub', 'card', 'gbox', 'gin',
  'SPACE', 'N', 'repos', 'commits', 'wafer', 'cam', 'lit', 'sel', 'redraw', 'draw', 'panels', 'refuse']);
const kyDraw = [], kyLines = [];
let kyAdmitting = null, kyInstalling = null;
function kyLine(t){ kyLines.push(t); if (!N) hud.textContent += '\n' + t; dirty = true; }
// the one wrap of draw: module painters run after the engine's and the edition's overlay, in ascending order;
// a painter that throws is taken out and named, the frame goes on
{ const _draw = draw; draw = function(){ _draw();
    if (kyLines.length) hud.textContent += '\nMODULES · ' + kyLines.join('\n');
    for (const d of kyDraw.slice()) { try { d.fn(o2, KY); }
      catch (e) { kyDraw.splice(kyDraw.indexOf(d), 1); kyLine(d.id + ' draw threw ' + (e && e.message || e) + ' · painter removed'); } } }; }
const KY_STATE = { schema: 'kuiper.modules.v1', edition: KY_EDITION, hooks: 'kuiper.hooks.v1', order: [], admitted: [],
  refused: [], failures: [], done: false, timings: { loader_start_ms: Math.round(performance.now()) } };
const KY_MODULES = {};
const KY = Object.freeze({
  schema: 'kuiper.hooks.v1', edition: KY_EDITION,
  hooks: Object.freeze({
    keyPlace, address, describe, findBy, flyTo, home, homeCamera, safeBox, lightTime, showNew, goKey, fmt, words, esc,
    cv, ov, o2, hud, big, sub, card, gbox, gin,
    get SPACE(){ return SPACE; }, get N(){ return N; }, get repos(){ return repos; }, get commits(){ return commits; },
    wafer: kyWafer }),
  cam: Object.freeze({ get x(){ return cx; }, get y(){ return cy; }, get zoom(){ return zoom; }, get atHome(){ return atHome; }, set atHome(v){ atHome = !!v; } }),
  lit: Object.freeze({ get repo(){ return litRepo; }, set repo(v){ litRepo = v; dirty = true; },
    get K(){ return litK; }, get Ci(){ return litCi; },
    set period(p){ if (p == null) { litK = [-1, -1]; litCi = null; dirty = true; } else lightTime(+p.y, +p.m || 0, +p.d || 0); } }),
  sel: Object.freeze({ get target(){ return target; }, set target(t){ target = t; dirty = true; } }),
  redraw(){ dirty = true; },
  draw: Object.freeze({ add(fn, order){ if (typeof fn !== 'function') throw new TypeError('KY.draw.add needs a function');
    kyDraw.push({ fn, order: +order || 0, id: kyInstalling || 'module' }); kyDraw.sort((a, b) => a.order - b.order); dirty = true; } }),
  // once the shell (team 1, id kuiper-shell) is admitted the bar and its panels are its own: add() forwards into the
  // shell's panel of that name (handoff/01-shell/REQUESTS.md item 2); a name the shell does not have falls back here
  panels: Object.freeze({ add(name, el, title){ const sh = KY_MODULES['kuiper-shell'], sp = sh && sh.api && typeof sh.api.panel === 'function' ? sh.api.panel(name) : null;
      if (sp) { sp.appendChild(el); KY.redraw(); return el; }
      if (PANELS[name]) throw new Error('panel ' + name + ' exists');
      el.classList.add('gm-panel'); el.setAttribute('role', 'region'); el.setAttribute('aria-label', String(title || name));
      if (!el.isConnected) document.body.appendChild(el); PANELS[name] = el; placePanels(); return el; },
    set: setPanel, place: placePanels }),
  refuse(text, slot){ if (typeof slot !== 'string' || !/^[a-z0-9-]+$/.test(slot) || slot === 'engine' || slot === 'modules')
      throw new TypeError('KY.refuse(text, slot): slot is the module id; engine and modules are the page\'s'); refuse(String(text || ''), slot); },
  names: KY_NAMES,
  register(m){ if (!kyAdmitting) { kyLine('a registration outside admission ignored: ' + (m && m.id)); return false; }
    if (kyAdmitting.reg) { kyAdmitting.twice = true; return false; } kyAdmitting.reg = m; return true; },
  modules: KY_MODULES,
  inspect(){ return JSON.parse(JSON.stringify(KY_STATE)); } });
window.KY = KY; window.__KUIPER_MODULES__ = KY_MODULES; window.__KUIPER_EDITION__ = KY_STATE;
// one strip, role=alert, for refused modules; the engine's own refusals keep their slot in the same strip
function kyRefuse(t){ refuse(t, 'modules'); }
const kyHex = b => [...new Uint8Array(b)].map(x => x.toString(16).padStart(2, '0')).join('');
function kyInject(id, buf){ return new Promise(ok => { const s = document.createElement('script'), u = URL.createObjectURL(new Blob([buf], { type: 'text/javascript' })), st = { loaded: false, error: null };
  const se = e => { if (e.filename === u) { st.error = st.error || String(e.message || 'error').replace(/^Uncaught /, ''); e.preventDefault(); } }, fin = l => { removeEventListener('error', se, true); URL.revokeObjectURL(u); st.loaded = l; ok(st); };
  addEventListener('error', se, true); s.dataset.kyModule = id; s.src = u; s.onload = () => fin(true); s.onerror = () => fin(false); document.head.appendChild(s); }); }   // a module's own script error is its refusal, not the page's error
async function kyAdmit(id, rec, provided){
  if (!rec) return 'in order but not in modules';
  const path = String(rec.path || ''), file = path.split('/').pop();
  if (!/^modules\/[a-z0-9][a-z0-9.-]*\.js$/.test(path) || path.includes('..')) return 'bad path ' + path;
  if (!/^\d{12}$/.test(rec.generation || '')) return 'generation ' + rec.generation + ' is not twelve digits';
  const fd = file.match(/^(\d{12})-/); if (fd && fd[1] !== rec.generation) return 'stamp mismatch: generation ' + rec.generation + ', file name ' + fd[1];
  if (!/^[0-9a-f]{64}$/.test(rec.sha256 || '')) return 'sha256 is not 64 hex';
  if (!String(rec.licence || '').trim()) return 'no licence'; for (const f of ['requires', 'provides']) if (rec[f] != null && !Array.isArray(rec[f])) return f + ' is not a list';
  for (const r of rec.requires || []) if (!provided.has(r)) return 'missing hook ' + r;
  let res; try { res = await fetch(path, { cache: 'no-store' }); } catch (e) { return 'fetch failed ' + (e && e.message || e); }
  if (!res.ok) return 'HTTP ' + res.status;
  const buf = await res.arrayBuffer(), sha = kyHex(await crypto.subtle.digest('SHA-256', buf));
  if (sha !== rec.sha256) return 'sha256 mismatch';
  if (buf.byteLength !== rec.bytes) return 'bytes ' + buf.byteLength + ' ≠ manifest ' + rec.bytes;
  if (rec.byte_budget && buf.byteLength > rec.byte_budget) return 'over byte_budget ' + buf.byteLength + ' > ' + rec.byte_budget;
  const head = new TextDecoder().decode(buf.slice(0, 200)).split('\n')[0].match(/^\/\* kuiper module ([a-z0-9-]+), generation (\d{12}) \(UTC\),/);
  if (!head) return 'no header line'; if (head[1] !== id) return 'header names ' + head[1] + ' ≠ ' + id;
  if (head[2] !== rec.generation) return 'stamp mismatch: generation ' + rec.generation + ', header ' + head[2];
  kyAdmitting = { id }; let reg, twice;
  let inj; try { inj = await kyInject(id, buf); } finally { reg = kyAdmitting.reg; twice = kyAdmitting.twice; kyAdmitting = null; } if (!inj.loaded) return 'script did not load'; if (inj.error) return 'script error: ' + inj.error;
  if (!reg) return 'no registration';
  if (twice) return 'registered twice';
  if (reg.schema !== 'kuiper.module.v1') return 'schema ' + reg.schema;
  if (reg.id !== id) return 'id ' + reg.id + ' ≠ ' + id; for (const f of ['requires', 'provides']) if (reg[f] != null && !Array.isArray(reg[f])) return 'registration ' + f + ' is not a list';
  if (reg.generation !== rec.generation) return 'stamp mismatch: generation ' + rec.generation + ', registration ' + reg.generation;
  for (const r of reg.requires || []) { if (!(rec.requires || []).includes(r)) return 'requires ' + r + ' not in the manifest'; if (!provided.has(r)) return 'missing hook ' + r; }
  if (typeof reg.install !== 'function') return 'no install';
  let api; kyInstalling = id;
  try { api = reg.install(KY); } catch (e) { return 'install threw ' + (e && e.message || e); } finally { kyInstalling = null; }
  const ready = Promise.resolve(api);
  ready.catch(e => { KY_STATE.failures.push({ id, why: 'install rejected ' + (e && e.message || e) }); kyLine(id + ' install rejected: ' + (e && e.message || e)); });
  Object.defineProperty(KY_MODULES, id, { enumerable: true, value: Object.freeze({ id, generation: rec.generation, sha256: sha,
    api: (api && typeof api.then === 'function') ? undefined : api, ready, inspect: typeof reg.inspect === 'function' ? reg.inspect : () => ({}) }) });
  for (const p of [id, ...(reg.provides || []), ...(rec.provides || [])]) provided.add(p);
  return null;
}
(async function kyLoad(){
  let m;
  try { const r = await fetch('modules.json', { cache: 'no-store' }); if (!r.ok) throw new Error('modules.json HTTP ' + r.status); m = await r.json(); if (!m || typeof m !== 'object') throw new Error('modules.json is not an object'); }
  catch (e) { m = { error: e && e.message || String(e) }; }
  const shape = m.error ? m.error : m.schema !== 'kuiper.modules.v1' ? 'schema ' + m.schema : m.hooks !== 'kuiper.hooks.v1' ? 'hooks ' + m.hooks
    : m.edition !== KY_EDITION ? 'edition ' + m.edition + ' ≠ page ' + KY_EDITION : !Array.isArray(m.order) || !Array.isArray(m.modules) ? 'order and modules must be lists'
    : !crypto.subtle ? 'no crypto.subtle (not a secure context)' : null;
  if (shape) { KY_STATE.whole = shape; KY_STATE.done = true; kyRefuse('MODULES NOT ADMITTED: ' + shape + ' · the wafer is unchanged'); kyLine('modules not admitted: ' + shape); return; }
  KY_STATE.order = m.order.slice();
  const provided = new Set(KY_NAMES), seen = new Set();
  for (const id of m.order) {
    let why; try { why = seen.has(id) ? 'in order twice' : await kyAdmit(id, m.modules.find(x => x && x.id === id), provided); } catch (e) { kyAdmitting = kyInstalling = null; why = 'loader error ' + (e && e.message || e); }
    const t = Math.round(performance.now()); seen.add(id);
    if (why) { KY_STATE.refused.push({ id, why, t_ms: t }); kyLine(id + ' refused: ' + why); }
    else { KY_STATE.admitted.push({ id, sha256: KY_MODULES[id].sha256, t_ms: t }); kyLine(id + ' admitted · ' + KY_MODULES[id].sha256.slice(0, 12)); }
  }
  KY_STATE.timings.last_admitted_ms = KY_STATE.admitted.length ? KY_STATE.admitted[KY_STATE.admitted.length - 1].t_ms : null;
  KY_STATE.timings.loader_end_ms = Math.round(performance.now());
  KY_STATE.bytes = m.modules.filter(x => x && KY_MODULES[x.id]).reduce((a, x) => a + (x.bytes || 0), 0);
  KY_STATE.byte_budget = m.modules.filter(x => x && KY_MODULES[x.id]).reduce((a, x) => a + (x.byte_budget || 0), 0);
  KY_STATE.done = true; for (const k of ['order', 'admitted', 'refused', 'timings']) Object.freeze(KY_STATE[k]);   // KY.modules stays open: the shell publishes .menuBar there (01-shell REQUESTS 2)
  if (KY_STATE.refused.length) kyRefuse(KY_STATE.refused.length + ' module' + (KY_STATE.refused.length > 1 ? 's' : '') + ' refused: '
    + KY_STATE.refused.map(x => x.id + ' (' + x.why + ')').join('; ') + ' · the wafer, the bar and every admitted module keep working');
})();
// ======================================== KUIPER HOOK TABLE AND LOADER kuiper.hooks.v1 · end
requestAnimationFrame(frame);
</script>
</body>
</html>