GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / globalgrid2050 / kuiper-grid/i0073/cartridges

Kuiper Card and 2 more files

A JavaScript file in the cartridges folder of GlobalGrid2050 that converts to world (`toWorld`) and steps anim (`stepAnim`).

654 lines of JavaScript from globalgrid2050, in 3 files. Topic: Kuiper, cosmos and drawing engines. Section 1241 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 Tests test · globalgrid2050 / kuiper-grid/i0073/cartridges/003400000000-kuiper-tests.js lines 701–864
  2. Kuiper Programs interaction · globalgrid2050 / kuiper-grid/i0073/cartridges/003600000000-kuiper-programs.js lines 1–231
  3. Kuiper Card render · globalgrid2050 / kuiper-grid/i0073/cartridges/003700000000-kuiper-card.js lines 1–259

Kuiper Tests

A JavaScript file in the cartridges folder of GlobalGrid2050 that tests link contract, cables, solar and battery storage (BESS), and uses data from the GridAtlas repository.

Set aside from the main view: 97% of its lines are the same as kuiper-grid/i0073/releases/003100000000-kuiper-shell/kuiper-tests.js (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 96% of lines shared with Kuiper Tests; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9698 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 kuiper-grid/i0073/releases/003100000000-kuiper-shell/kuiper-tests.js:1-844 ad24a37445c54d4bffe4fa63a649d1f4292a151c
  • sha256 94f07e130ed676feba8595a89a4383455c3394b96111f09f52bb62119a79b373
  • target sha256 23f4df7ece0aa08ce698b7293a74719acca1ccb7f0c22f00a0f41686763337a4
  • group of 7 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

testglobalgrid2050 / kuiper-grid/i0073/cartridges/003400000000-kuiper-tests.js · lines 701–864 of 864 (continued from section 1240) · Not reached from any entry point (candidate for review) · pattern buttonsSelftest (shared by 8 files)

What it does
It tests link contract, cables, solar and battery storage (BESS). Defines 28 functions or classes, including finishSelftest, pathSelftest, inWindow, on, buttonsSelftest. Side effects: changes the web page (DOM); makes network requests.
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). Domain terms in the code: cables, solar, battery storage (BESS).
Inputs & outputs
In: data source: gridatlas data; JSON file link-contract.json.
What it achieves
It is built from the finish selftest helper (`finishSelftest`), the path selftest helper (`pathSelftest`) and the in window helper (`inWindow`). A cartridge of the Kuiper shell. It reads `cosmos/link-contract.json`. It responds to pointerdown and pointermove events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · kuiper-grid/i0073/cartridges · script
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
Cable Geometry Visualiser V5 (estate URL), GridAtlas — Atlas Page (estate URL), GlobalGrid2050 — Cable Geometry Page (estate URL)
Used by
none found
Produces
finishSelftest, pathSelftest, inWindow, on, buttonsSelftest, settle, litPixels, isolateSelftest, onScreen, census, ring, ev
Defines here
repoSelftest, strip, check, phoneSelftest, ev, seen, walk, 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
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 kuiper-grid/i0073/cartridges/003400000000-kuiper-tests.js:701-864 · blob 383e63f3d973988f3a67b01c28201dfa0c3e8900 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: agent_infra · users: ai_agent · canonical: duplicate_candidate
// 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(); }
  // THE PUBLIC FACE, CHECKED ON THE FACE ITSELF. Functions, use cases and disclaimers: what a person
  // can do here, what it is for, and what it is not. The placement law, the angle and the unresolved
  // pixels are engineering notes and belong in the repository, not in front of a reader.
  // PRESENT IS NOT THE SAME AS VISIBLE. textContent returns words that are set to display:none as
  // happily as words on the screen, so every check passed while a phone showed no disclaimer at all.
  // Ask the layout instead: a node with no client rectangles is not in front of anybody.
  const seen = el => { if (!el) return ''; let out = '';
    const walk = n => { if (n.nodeType === 3) { const r = document.createRange(); r.selectNodeContents(n);
        if (r.getClientRects().length) out += ' ' + n.nodeValue; return; }
      if (n.nodeType !== 1 || !n.getClientRects().length) return;
      for (const c of n.childNodes) walk(c); };
    walk(el); return out.replace(/\s+/g, ' ').trim().toLowerCase(); };
  const faceSeen = seen(document.getElementById('foot')) + ' ' + seen(document.getElementById('top'));
  // NOTHING MAY RUN OFF THE RIGHT EDGE. A box whose content is wider than the box itself is a box
  // with words hidden in it, which is how a cut disclaimer looks to everyone except a test.
  const overflows = [];
  for (const id of ['top','hud','foot','card']) { const el = document.getElementById(id);
    if (el && el.getClientRects().length && el.scrollWidth > el.clientWidth + 1)
      overflows.push({ panel:id, content_px:el.scrollWidth, box_px:el.clientWidth }); }
  const face = (document.getElementById('foot').textContent + ' ' + document.getElementById('top').textContent).toLowerCase();
  const T = { viewport:[W, H], narrow_layout:narrow(), wafer_centre_on_screen:[Math.round(scx), Math.round(scy)], wafer_radius_px:Math.round(Rpx),
    T7_the_face_carries_the_disclaimer: face.indexOf('without warranty of any kind') >= 0,
    T9_the_disclaimer_is_actually_on_the_screen: faceSeen.indexOf('without warranty of any kind') >= 0,
    T10_nothing_is_cut_off_at_the_right_edge: overflows.length === 0, panels_that_overflow: overflows,
    visible_face_words: faceSeen.length,
    T8_the_face_explains_no_machinery: !/golden|one law|√|sqrt|unresolved pixel/.test(face),
    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;
  T.PASS = T.PASS && T.T7_the_face_carries_the_disclaimer && T.T8_the_face_explains_no_machinery
        && T.T9_the_disclaimer_is_actually_on_the_screen && T.T10_nothing_is_cut_off_at_the_right_edge;
  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){
  endIsolate();
  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.classList.remove('sheet'), 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.classList.remove('sheet'), 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; }

Kuiper Programs

A JavaScript file in the cartridges folder of GlobalGrid2050 that makes body (`makeBody`), sets tag (`setTag`), makes app buttons (`makeAppButtons`) and calculates planar distances.

interactionglobalgrid2050 / kuiper-grid/i0073/cartridges/003600000000-kuiper-programs.js · lines 1–231 of 231 · Not reached from any entry point (candidate for review) · pattern bodyDrawnDiameter (shared by 54 files)

What it does
Defines 27 functions or classes, including closestPair, blackSky, nameInLines, makeBody, bodyTo. 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).
What it achieves
It makes body (`makeBody`), sets tag (`setTag`) and makes app buttons (`makeAppButtons`). A cartridge of the Kuiper shell. It responds to click and keydown events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · kuiper-grid/i0073/cartridges · script
Uses
none found
Used by
none found
Produces
closestPair, blackSky, nameInLines, makeBody, bodyTo, labels, bodyJump, bodyMove, bodyDrawnDiameter, bodyDotPx, sheet, setTag
Defines here
closestPair, blackSky, nameInLines, makeBody, bodyTo, labels, bodyJump, bodyMove, bodyDrawnDiameter, bodyDotPx, sheet, setTag, revealCode, sparksTo, ensureGlow, makeAppButtons, isolateNow, isolate, raiseTile, endIsolate, unisolate, appCard, closeCard, codeWindow, lh, padTop, place
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 kuiper-grid/i0073/cartridges/003600000000-kuiper-programs.js:1-231 · blob 184adf2f5f171a549400904c755c6d72ce1143e0 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
'use strict';
// kuiper-programs.js - a cartridge of the Kuiper shell. Cut from the whole page with no change of behaviour;
// replaced, when it is, by a newer file the pointer names and the composer checks by its hash.
let ASM = null, gatherAnim = null, homeAnim = null;
// ===== THE BODY: a smaller Kuiper of one application's own work =====================================
let body = null, bodyAnim = null, BP = null, bodyBuf = null;
// THE PALETTE OF THE ONE PULSE. The ring that sweeps the disc is white and ice blue; what it leaves lit is
// the same light, at full brightness. No second look: the saturated green was one, and it is gone.
const FARADAY = [0.80, 0.96, 1.0];
// THE BODY FILLS THE INNER DISC, so a third of the gap is a bigger dot and the body reads from across a
// room without a single dot breaking the rule that makes it a population and not a patch.
const BODY_RADIUS = 0.55, BODY_RADIUS_MAX = 0.92, DOT_MAX_PX = 5, DOT_MIN_PX = 1.0;
const VS_BODY = `#version 300 es
precision highp float;
in vec2 a_pos; uniform float u_zoom, u_size; uniform vec2 u_center, u_res;
void main(){ gl_Position = vec4((a_pos - u_center) * u_zoom / (0.5*u_res), 0.0, 1.0); gl_PointSize = u_size; }`;
// A DOT IS A DISC WITH A HARD EDGE, AND IT IS NOT ADDED TO WHAT IS UNDER IT. Light that adds is how
// neighbours merge into a white patch; here a dot covers what it covers and nothing more.
const FS_BODY = `#version 300 es
precision highp float; uniform vec3 u_on; out vec4 o;
void main(){ if (length(gl_PointCoord - 0.5) > 0.5) discard; o = vec4(u_on, 1.0); }`;
// THE GAP, MEASURED. The nearest two centres among the places the module returned, found with a grid
// so a large application costs no more than a small one. Nothing here is judged by eye.
function closestPair(pos){
  const m = pos.length / 2; if (m < 2) return Infinity;
  let x0 = 1e300, x1 = -1e300, y0 = 1e300, y1 = -1e300;
  for (let q = 0; q < pos.length; q += 2) { x0 = Math.min(x0, pos[q]); x1 = Math.max(x1, pos[q]); y0 = Math.min(y0, pos[q+1]); y1 = Math.max(y1, pos[q+1]); }
  const cell = Math.max(1e-9, Math.sqrt(Math.max(1e-18, (x1 - x0) * (y1 - y0)) / m)), grid = new Map();
  let best = Infinity;
  for (let j = 0; j < m; j++) { const gx = Math.floor((pos[2*j] - x0) / cell), gy = Math.floor((pos[2*j+1] - y0) / cell);
    for (let dx = -1; dx <= 1; dx++) for (let dy = -1; dy <= 1; dy++) { const cellm = grid.get((gx + dx) + ':' + (gy + dy)); if (!cellm) continue;
      for (const k of cellm) { const d = Math.hypot(pos[2*j] - pos[2*k], pos[2*j+1] - pos[2*k+1]); if (d < best) best = d; } }
    const key = gx + ':' + gy; (grid.get(key) || grid.set(key, []).get(key)).push(j); }
  return best;
}
// THE BLACK SKY RULE, as one question any body can be asked: are all centres at least three dot radii
// apart? It is the same function the page obeys and the test plants a too tight body against.
function blackSky(pos, dotRadius){ const gap = closestPair(pos); return { gap, dotRadius, ok: gap >= 3 * dotRadius * (1 - 1e-4) }; }   // exactly a third is allowed; the margin is for rounding, not for squeezing
function nameInLines(words){ const w = String(words).split(' '); if (String(words).length <= 9 || w.length < 2) return String(words);
  const half = Math.ceil(w.length / 2); return w.slice(0, half).join(' ') + ' / ' + w.slice(half).join(' '); }
function makeBody(st){
  if (!ASM || !st.idx.length) return null;
  const seq = (st.prog.on.sequence && st.prog.on.sequence.length) ? st.prog.on.sequence : (st.prog.on.shape ? [{ shape:st.prog.on.shape }] : []);
  if (!seq.length) return null;
  const m = st.idx.length, R = Math.sqrt(SPACE), from = new Float32Array(2 * m);
  // ONE DOT FOR EVERY PIECE OF WORK, IN ORDER OF KEY: the module puts dot j at place j, and place 0 is
  // the middle, so the oldest work is the middle of the small Kuiper and the newest is its rim.
  st.idx.forEach((ci, j) => { const c0 = commits[ci], p = keyPlace(c0.k0 + Math.floor((c0.k1 - c0.k0) / 2)); from[2*j] = p[0]; from[2*j+1] = p[1]; });
  // THE SIZE THE SHOW WILL REALLY BE SEEN AT. On a phone the short tile rises under the picture and the
  // disc is refitted smaller above it, so what resolves is decided for THAT size, not for the empty screen.
  const zHome = homeCamera().z * (narrow() ? 0.62 : 1), states = [];
  for (const step of seq) { const shape = step.shape === 'text' ? 'text:' + nameInLines(st.app.button) : step.shape;
    // A NAME NEEDS ENOUGH DOTS TO BE A NAME: about six to a letter. Nine pieces of work cannot spell
    // two words, and a scatter that means nothing is worse than the small Kuiper it would replace.
    // A NAME ONLY WHEN IT CAN BE READ. A letter is a shape of squares and needs a dot for every one of them;
    // with fewer, letters lose strokes (85 pieces of work spelt CABL S). Counted from the module's own
    // lettering, not estimated.
    if (step.shape === 'text') { const ink = ASM.raster ? ASM.raster(nameInLines(st.app.button)) : null;
      const squares = ink ? ink.on.reduce((t, v) => t + v, 0) : 1e9; if (m < squares) continue; }
    let unit; try { unit = ASM.targets(shape, m); } catch (e) { continue; }
    const unitGap = closestPair(unit);
    // large enough that a dot a third of the gap wide is at least a pixel; never larger than the disc
    let frac = BODY_RADIUS; const need = DOT_MIN_PX * 3 / Math.max(1e-12, unitGap * R * zHome);
    if (need > frac) frac = Math.min(BODY_RADIUS_MAX, need);
    const to = new Float32Array(unit.length); for (let q = 0; q < unit.length; q++) to[q] = unit[q] * R * frac;
    const gap = unitGap * R * frac;
    const unresolved = gap * zHome / 3 < DOT_MIN_PX * 0.999;
    // WHAT CANNOT BE RESOLVED IS NOT SHOWN AS IF IT COULD. A state that would need dots under a pixel is
    // left out, and the show ends on the last state that does resolve: the work gathers and STAYS, it
    // is never simply gone from the middle of the disc, which is what a phone showed.
    if (unresolved && states.length) continue;
    states.push({ shape, to, gap, frac, hold:step.hold_ms || 0, unresolved }); }
  if (!states.length) return null;
  return { n:m, from, pos:new Float32Array(from), states, k:-1, gap:0, shown:false };
}
function bodyTo(arr){ if (body) body.live = closestPair(arr);
  if (!BP) { BP = prog(VS_BODY, FS_BODY); bodyBuf = gl.createBuffer(); }
  gl.bindBuffer(gl.ARRAY_BUFFER, bodyBuf); gl.bufferData(gl.ARRAY_BUFFER, arr, gl.DYNAMIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER, null); }
function labels(show){ const o = document.getElementById('o'); if (o) o.style.visibility = show ? 'visible' : 'hidden'; }
function bodyJump(k){ if (!body) return; labels(false); const stt = body.states[k]; body.pos.set(stt.to); body.k = k; body.gap = stt.gap; body.shown = true; bodyAnim = null; bodyTo(body.pos); dirty = true; }
function bodyMove(k){ if (!body) return; labels(false); bodyAnim = { k, t0:performance.now(), from:new Float32Array(body.pos), gap0:body.shown ? body.gap : body.states[k].gap, phase:'move' };
  body.shown = true; dirty = true; }
// the dot's radius ON THE SCREEN, from the measured gap and the zoom of this moment: a third of the
// gap, never more, however the visitor zooms
// THE SIZE FOLLOWS THE CANVAS, NOT THE SCREEN. This canvas is as many pixels as the window is wide, so a
// point size is already in the units the gap is measured in. Multiplying by the screen's pixel ratio
// drew every dot at twice its size on a real screen and at its right size in every test.
function bodyDrawnDiameter(){ return Math.max(1, 2 * bodyDotPx() * (cv.width / Math.max(1, innerWidth))); }
// A THIRD OF THE GAP AS THE DOTS ARE NOW. At rest the gap is the state's own; in flight it is measured
// from where the dots are at that frame, because leaving the rim they are almost on top of one another
// and no resting spacing describes them.
function bodyDotPx(){ const gap = body.live !== undefined ? body.live : body.gap;      // measured every time the dots are placed
  return Math.max(0.5, Math.min(DOT_MAX_PX, gap * zoom / 3)); }
// BESIDE THE SHELL, NOT BESIDE THIS FILE. Released, this part lives in a folder of parts and the module lives
// beside the shell; a script asks for a module relative to its own address, so './assemble.mjs' asked for a
// file that is not there. The page's base address is the shell's folder, with the composer or without it.
// AND A FAILED LOAD SAYS SO. The catch used to swallow it, and on the live address the dots simply never
// gathered, with nothing on the page or in the console to say why.
let asmWhy = null;
const asmReady = import(new URL('assemble.mjs', document.baseURI).href).then(m => { ASM = m; })
  .catch(e => { ASM = null; asmWhy = String(e && e.message || e); console.error('[kuiper] the gathering animation could not be loaded:', asmWhy); });
const GATHER_RADIUS = 0.30;                      // of the record's own radius: a body, with the dark disc still around it
function sheet(title, sub){
  const mine = ++cardToken;
  card.classList.remove('short');
  card.replaceChildren();
  card.style.display = 'block';
  card.scrollTop = 0;
  const x = el('button', 'cc-x', '\u00d7'); x.type = 'button'; x.setAttribute('aria-label', 'close');
  x.addEventListener('click', closeCard);
  card.append(x, el('span', 'cc-title', title));
  if (sub) card.append(el('span', 'cc-grey', sub));
  const tagLine = el('div', 'cc-tagline'), tag = el('span', 'cc-tag'), msg = el('span', 'cc-grey');
  tagLine.append(tag, msg); card.append(tagLine);
  const body = el('div', 'cc-body'); card.append(body);
  // THE SINGLE WRITER OF THE STATE. Nothing else touches the chip, and a writer for a card that has
  // been replaced does nothing at all.
  const setTag = (st, text) => { if (mine !== cardToken) return false;
    tag.dataset.s = st; tag.textContent = st; if (text != null) msg.textContent = text; return true; };
  dirty = true;
  return { mine, body, setTag, live: () => mine === cardToken };
}
function revealCode(){
  const w = cardShown && cardShown.window; if (!w) return;
  const cr = card.getBoundingClientRect(), pr = w.node.getBoundingClientRect();
  if (pr.bottom > cr.bottom - 4) card.scrollTop += pr.bottom - cr.bottom + 8;
  else if (pr.top < cr.top) card.scrollTop -= cr.top - pr.top + 8;
  w.scrollToTarget();
}
function sparksTo(arr){ ensureGlow(); gl.bindBuffer(gl.ARRAY_BUFFER, glowBuf);
  gl.bufferData(gl.ARRAY_BUFFER, arr, gl.DYNAMIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER, null); }
function ensureGlow(){ if (!PG) { PG = prog(VS_GLOW, FS_GLOW); glowBuf = gl.createBuffer(); } }
// ===== ISOLATE AN APPLICATION =================================================================
function makeAppButtons(){
  const bar = document.getElementById('apps'); bar.replaceChildren();
  for (const pr of programs) { const ap = apps.find(x => x.app === pr.select.app);
    if (!ap || !(appWork[ap.app] || []).length) continue;        // nothing of it on this record: no button
    const b = el('button', null, pr.button); b.type = 'button'; b.setAttribute('data-app', pr.name);
    b.addEventListener('click', e => { e.stopPropagation(); isolate(pr.name); }); bar.append(b); }
  if (typeof layout === 'function') layout();
}
// THE STATE ITSELF, with no animation, so it can be arrived at by a link and asked for by a test.
function isolateNow(name, front){
  const asData = programs.find(x => x.name === name); if (!asData) return null;
  const prog = Object.assign({}, asData, { on:Object.assign({}, asData.on, { colour:FARADAY }) });
  const ap = apps.find(x => x.app === prog.select.app); if (!ap) return null;
  name = ap.app;
  const idx = []; for (const sha of (appWork[name] || [])) { const i = bySha.get(sha); if (i !== undefined) idx.push(i); }
  idx.sort((x, y) => x - y);
  litRepo = -1; litK = [-1,-1]; litCi = null; newFrom = -1; flash = 0; litPath = null; target = null; arrow = null;
  iso = { app:ap, prog, front:front === undefined ? 1e30 : front, idx, set:new Set(idx), lit:idx.length, dark:commits.length - idx.length,
          first:idx.length ? commits[idx[0]].unix : 0, last:idx.length ? commits[idx[idx.length - 1]].unix : 0 };
  raiseFlags(idx);
  { // A FEW SPARKS FOR EVERY PIECE OF WORK, spread through its own lines so a big piece of work is a
    // scatter around its ring and a small one a point or two. Never more than the program allows.
    const per = Math.max(1, Math.min(24, (prog.on.sparks | 0) || 8)), pts = [];
    for (const i of idx) { const c0 = commits[i], len = Math.max(1, c0.k1 - c0.k0), take = Math.min(per, len);
      for (let j = 0; j < take; j++) { const p = keyPlace(c0.k0 + Math.floor((j + 0.5) * len / take)); pts.push(p[0], p[1]); } }
    ensureGlow();
    iso.from = new Float32Array(pts); iso.pos = iso.from; iso.to = null;
    glowCount = pts.length / 2; iso.sparks = glowCount; sparksTo(iso.from); }
  body = makeBody(iso);
  // arrived at by a link, or asked for outright: the END of the program, with no waiting
  if (front === undefined && body) bodyJump(body.states.length - 1);
  for (const b of document.querySelectorAll('#apps button')) b.classList.toggle('on', b.getAttribute('data-app') === prog.name);
  if (front === undefined) raiseTile();
  dirty = true;
  return iso;
}
// PRESS: the pulse runs out through the record, which on this picture is forward through time, and
// where it has passed the rest goes dark. The pulse is the page's own; nothing new is animated.
function isolate(name){
  const prog = programs.find(x => x.name === name); if (!prog) return;
  closeCard(); unisolate(true); anim = null; flash = 0; newFrom = -1; target = null; arrow = null;
  { const h = homeCamera(); cx = h.x; cy = h.y; zoom = h.z; tween = null; atHome = true; }
  // the selection is made at once and the FRONT starts at the origin with nothing switched; each dot
  // switches when the front reaches it, so the darkening is seen to travel
  if (!isolateNow(name, 0)) return;
  bodyAnim = null; if (body) body.shown = false;
  isoAnim = { name, t0:performance.now(), R:Math.sqrt(SPACE), ms:Math.max(200, (prog.pulse.seconds || 1.5) * 1000) }; dirty = true;
}
function raiseTile(){ if (!iso || !(iso.prog.end && iso.prog.end.tile)) return;
  appCard(iso); if (atHome) { const h = homeCamera(); flyTo(h.x, h.y, h.z); } dirty = true; }
// ANY OTHER ACTION FIRST ENDS THE ISOLATE. Called by everything that shows something else, before it
// does anything, so the darkening can never outlive the thing it was for.
function endIsolate(){ if (iso || isoAnim || bodyAnim) { unisolate(true); closeCard(); } }
function unisolate(quiet){ labels(true); iso = null; isoAnim = null; gatherAnim = null; homeAnim = null; body = null; bodyAnim = null; pulse = -1;
  for (const b of document.querySelectorAll('#apps button')) b.classList.remove('on');
  if (!quiet) dirty = true; }
// THE TILE OF AN ISOLATED APPLICATION: its name, what it does for a project, OPEN. Then how much of
// the record is lit and how much has gone dark, because the two must make the whole.
function appCard(st){
  cardToken++; cardShown = null; card.replaceChildren(); card.style.display = 'block'; card.scrollTop = 0;
  card.classList.add('short');
  const x = el('button', 'cc-x', '\u00d7'); x.type = 'button'; x.setAttribute('aria-label', 'close');
  x.addEventListener('click', () => { card.style.display = 'none'; dirty = true; });
  const t = el('a', 'cc-tile cc-app'); t.href = st.app.live; t.target = '_blank'; t.rel = 'noopener'; t.setAttribute('data-app', st.app.app);
  t.append(el('div', 'cc-tile-name', st.app.button));
  if (whatItDoes[st.app.live]) t.append(el('div', 'cc-tile-what', whatItDoes[st.app.live] + '.'));
  t.append(el('span', 'cc-tile-open', 'OPEN ' + st.app.button));
  const brand = el('div', 'scada-brand'), inner = el('div');
  inner.append(el('div', 'scada-brand-main', 'Ventus'), el('div', 'scada-brand-sub', 'Cables & Connectivity\u00ae')); brand.append(inner);
  const plain = el('div', 'cc-plain cc-count', fmt(st.lit) + ' pieces of work lit, ' + fmt(st.dark) + ' gone dark, '
    + fmt(st.lit + st.dark) + ' in all \u00b7 ' + day(st.first) + ' to ' + day(st.last));
  card.append(x, t, brand, plain);
  if (!ASM && asmWhy) card.append(el('div', 'cc-refuse', 'The gathering could not be loaded, so this work stays where it is: ' + asmWhy));
  if (typeof layout === 'function') layout();
}
function closeCard(){ cardToken++; card.style.display = 'none'; card.replaceChildren();
  target = null; cardShown = null; dirty = true; }
addEventListener('keydown', e => {
  if (e.key === 'Escape' && card.style.display !== 'none') { e.preventDefault(); closeCard(); } });

function codeWindow(lines, a, b, at){
  const pre = el('pre', 'cc-code');
  pre.setAttribute('aria-label', 'the code around this line');
  const bar = el('div', 'cc-hi cc-hi-target');
  const out = [];
  for (let i = a; i <= b; i++) out.push(String(i).padStart(6) + '  ' + lines[i - 1]);
  pre.append(bar, document.createTextNode(out.join('\n')));
  const lh = () => parseFloat(getComputedStyle(pre).lineHeight) || 16;
  const padTop = () => parseFloat(getComputedStyle(pre).paddingTop) || 0;
  const place = () => { bar.style.top = (padTop() + (at - a) * lh()) + 'px'; bar.style.height = lh() + 'px'; };
  return { node:pre, bar, place, first:a, last:b, at,
    scrollToTarget(){ place(); pre.scrollTop = Math.max(0, (at - a) * lh() - pre.clientHeight/2 + lh()/2); } };
}

// WHAT A TAP OPENS. One way in for every kind of answer: the work and the day it was done, a state
// chip saying how much of it is proved, and, where the code for that line is carried on this site,
// the code itself with the tapped line marked. Nothing here sends a reader to GitHub to READ code;
// the link is there for the detail and the history, which is what GitHub is good for.

Kuiper Card

A JavaScript file in the cartridges folder of GlobalGrid2050 that converts to world (`toWorld`) and steps anim (`stepAnim`).

Set aside from the main view: 97% of its lines are the same as kuiper-grid/i0073/cartridges/003900000000-kuiper-card.js (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 97% of lines shared with Kuiper Card; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9723 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 kuiper-grid/i0073/cartridges/003900000000-kuiper-card.js:1-266 106c5ececcf47fa4541455c56ff482f2b2a509e2
  • sha256 688255b8e029dc7fcf3cb2b47abab8b3af1d1b07e2cde2dda3a2947a9552a7d9
  • target sha256 f0f6e017cd77cc235bc3e19ba877969c84c29d55b45322d2337a7e4d25310663
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

renderglobalgrid2050 / kuiper-grid/i0073/cartridges/003700000000-kuiper-card.js · lines 1–259 of 259 · Not reached from any entry point (candidate for review) · pattern workTable (shared by 5 files)

What it does
It draws its content. Defines 18 functions or classes, including toWorld, cardFor, esc, gh, ghLink. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
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).
What it achieves
It shows new (`showNew`) and is built from the to world helper (`toWorld`) and the card for helper (`cardFor`). A cartridge of the Kuiper shell. It responds to toggle and click events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · kuiper-grid/i0073/cartridges · script
VEDIC
RECENT (GG2050-VEDIC-000041): Kuiper / Code navigation · Computer science / Interactive visualisation. hours, ordered_commits → recent_band_animation_state
Uses
none found
Used by
none found
Produces
toWorld, cardFor, esc, gh, ghLink, el, drow, linkTo, workTable, rawFile, workCode, open
Defines here
toWorld, cardFor, esc, gh, ghLink, el, drow, linkTo, workTable, rawFile, workCode, open, show, put, goKey, arriveAt, showNew, stepAnim
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 kuiper-grid/i0073/cartridges/003700000000-kuiper-card.js:1-259 · blob 745f265007d312ae35479d273fe5181532419237 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: agent_infra · users: ai_agent · canonical: duplicate_candidate
'use strict';
// kuiper-card.js - a cartridge of the Kuiper shell. Cut from the whole page with no change of behaviour;
// replaced, when it is, by a newer file the pointer names and the composer checks by its hash.
// ------------------------------------------------------------------------------ the controls
function toWorld(px, py){ return [cx + (px - innerWidth/2)/zoom, cy - (py - innerHeight/2)/zoom]; }
// A KEY THAT LANDS IN A CARRIED FILE SHOWS THE CODE. Until every commit's file list is published a
// browser cannot work out which file a key belongs to, so the answer is worked out beforehand, one
// public file at a time, and the page simply looks it up. Where there is no card the page says what
// it knows and does not pretend otherwise.
function cardFor(k){ return cards.find(c => k >= c.k0 && k < c.k0 + c.lines) || null; }
function esc(t){ return String(t).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); }
const CONTEXT = 10;
// THE ONE RULE THAT MAKES THE ADDRESS OF A LINE ON GITHUB, the same rule tools/cards.py writes
// down, so a change of commit ids can be answered by making every link again from the fields.
// The owner used to be written in here by hand: correct by luck, and wrong the first time a
// carried file came from anywhere else.
// ONE RULE, TWO SHAPES. A whole piece of work is a commit; a line is a path inside it. Nothing in
// this page types a GitHub address: every one of them comes out of here, from data, so when the
// commit ids change they can all be made again by rebuilding the data.
function gh(o){
  if (!o || !o.owner || !o.repo || !o.commit) return null;
  const base = 'https://github.com/' + o.owner + '/' + o.repo;
  if (!o.path) return base + '/commit/' + o.commit;
  return base + '/blob/' + o.commit + '/' + o.path + (o.line ? '#L' + o.line : '');
}
function ghLink(c, line){
  return gh({ owner:c.owner, repo:c.repo, commit:c.commit, path:c.path, line:line });
}
// ===== THE POP CARD =========================================================================
// The card this estate refined over many iterations, brought over rather than approximated again.
// Grid Atlas's popup look, a state chip with ONE writer, and a code window that is one <pre> with
// one text node: the numbers are part of the text, so copying the code copies what is on the
// screen, and the tapped line is marked by a bar placed from the line height.
function el(tag, cls, text){ const e = document.createElement(tag); if (cls) e.className = cls;
  if (text != null) e.textContent = text; return e; }
function drow(dl, k, v){ dl.append(el('dt', null, k)); const d = el('dd', null, v); dl.append(d); return d; }
function linkTo(href, text){ const a = el('a', 'cc-link', text); a.href = href; a.target = '_blank'; a.rel = 'noopener'; return a; }
let cardToken = 0, cardSource = null, PG = null, glowBuf = null, glowCount = 0, glowOff = false;
// THE ESTATE'S ONE GATHERING ANIMATION, used as it stands. If it cannot be read the sparks simply stay
// where the work is: the page is quieter, and nothing is pretended.
// THE CODE A PIECE OF WORK CHANGED, THE WAFER'S WAY. The table of what each piece of work changed is one
// small module, asked for the first time a dot is tapped. The file is read from the public repository at
// that exact commit. Nothing is fetched for a repository that is not provably public.
let WORK = null, workWhy = null; const rawCache = new Map();
{ const st = document.createElement('style');          // the look of the other-files buttons travels with this part
  st.textContent = '#card .cc-nav{display:flex;gap:.35rem;flex-wrap:wrap;margin:.3rem 0}'
    + '#card .cc-mini{background:#0a0a0a;color:#00ffff;border:1px solid #444;border-radius:3px;font:inherit;font-size:11px;padding:.3rem .5rem;cursor:pointer}'
    + '#card .cc-mini.cc-on{border-color:#00ffff;color:#fff}';
  document.head.appendChild(st); }
function workTable(){ if (WORK || workWhy) return Promise.resolve(WORK);
  // beside the shell, not beside this file (see the programs part for how the other way failed on the live address)
  return import(new URL('kuiper-work.mjs', document.baseURI).href).then(m => { WORK = m.WORK; return WORK; })
    .catch(e => { workWhy = String(e && e.message || e); console.error('[kuiper] what each piece of work changed could not be loaded:', workWhy); return null; }); }
function rawFile(owner, repo, sha, path){ const u = 'https://raw.githubusercontent.com/' + owner + '/' + repo + '/' + sha + '/' + path.split('/').map(encodeURIComponent).join('/');
  if (!rawCache.has(u)) { rawCache.set(u, fetch(u).then(x => { if (!x.ok) throw new Error('the file answered ' + x.status); return x.text(); })
      .then(t => t.split('\n').map(l => l.replace(/\r$/, ''))).catch(e => { rawCache.delete(u); throw e; }));
    if (rawCache.size > 8) rawCache.delete(rawCache.keys().next().value); }
  return rawCache.get(u); }
function workCode(a, r, s){
  if (!r.pub) { s.setTag('EMPTY', 'This work is not public, so its code is not shown.'); return; }
  const det = card.querySelector('details.cc-q');
  if (det && !det.open && !s.asked) { s.asked = true; s.setTag('WAIT', 'open this to read the code this piece of work changed');
    det.addEventListener('toggle', () => { if (det.open && s.live()) workCode(a, r, s); }, { once:true }); return; }
  s.setTag('LOAD', 'finding what this piece of work changed\u2026');
  workTable().then(table => { if (!s.live()) return;
    if (!table) { s.setTag('FAIL', 'The list of what each piece of work changed could not be read: ' + workWhy); return; }
    const row = table[a.c.sha];
    if (!row) { s.setTag('EMPTY', 'This piece of work changed no code a card can show: data, pictures, or files that were only removed.'); return; }
    const full = row[0], count = row[1], files = row.slice(2);
    const pick = el('div', 'cc-nav'), head = el('div', 'cc-codehead'), holder = el('div');
    s.body.append(head, pick, holder);
    const open = i => { const path = files[i][0], line = files[i][1], name = path.split('/').pop();
      for (const b of pick.children) b.classList.toggle('cc-on', b.getAttribute('data-i') === String(i));
      head.textContent = 'This piece of work changed ' + fmt(count) + (count === 1 ? ' file' : ' files') + '. Showing ' + path + '.';
      holder.replaceChildren(); cardShown = null;
      s.setTag('LOAD', 'reading ' + name + ' as it stood that day\u2026');
      rawFile(r.owner, r.name, full, path).then(lines => { if (!s.live()) return;
        const at = Math.min(Math.max(1, line), lines.length), from = Math.max(1, at - CONTEXT), to = Math.min(lines.length, at + CONTEXT);
        const w = codeWindow(lines, from, to, at); holder.append(w.node);
        const src = el('div', 'cc-source'), g = linkTo(gh({ owner:r.owner, repo:r.name, commit:full, path:path, line:at }), 'GitHub'); g.classList.add('cc-gh');
        src.append(g); holder.append(src);
        cardShown = { work:true, path, line:at, lines, window:w, sheet:s, from, to };
        s.setTag('OK', 'lines ' + fmt(from) + ' to ' + fmt(to) + ' of ' + fmt(lines.length) + ', around the first line this work changed (line ' + fmt(at) + ')');
        requestAnimationFrame(() => { if (s.live()) revealCode(); }); revealCode(); dirty = true;
      }).catch(e => { if (s.live()) s.setTag('FAIL', name + ' could not be read from the public repository: ' + (e && e.message || e) + '. Nothing is shown in its place.'); }); };
    files.forEach((f, i) => { const b = el('button', 'cc-mini', f[0].split('/').pop()); b.type = 'button'; b.setAttribute('data-i', i); b.title = f[0];
      b.addEventListener('click', e => { e.stopPropagation(); open(i); }); pick.append(b); });
    if (count > files.length) pick.append(el('span', 'cc-small', ' and ' + fmt(count - files.length) + ' more'));
    if (files.length < 2) pick.style.display = 'none';
    open(0);
  });
}
function show(a){
  cardShown = null;
  if (!a) { closeCard(); return; }
  if (a.silent) {
    const x = a.next, s = sheet('Nothing was recorded here', '');
    s.setTag('EMPTY', 'This point falls between two pieces of work, so no line of code has this address.');
    if (x) { const p = el('div', 'cc-row');
      const go = el('a', 'cc-link', 'Go to the next work: ' + repos[x.repo].name + ', ' + day(x.unix));
      // BESIDE THE ADDRESS BAR, NOT BESIDE THE SHELL. Under the composer the page's base is the shell's own
      // folder, and a bare ?key= would lead there instead of to the one address that never changes.
      go.href = location.pathname + buildLink({ key:x.k0 }); go.setAttribute('data-key', x.k0);
      p.append(go); s.body.append(p); }
    return;
  }
  const r = repos[a.c.repo], c = cardFor(a.k);
  litRepo = a.c.repo;
  const s = sheet('Line ' + fmt(a.k), c ? ' \u00b7 ' + c.path.split('/').pop() : ' \u00b7 ' + r.name);
  // THE ORDER OF THE CARD IS THE ORDER OF THE QUESTIONS A PERSON WHO SIGNS ASKS. What is this for,
  // and where do I open it; whose is it; what was done and when. How it is made comes last and
  // closed, one tap further in, for the engineer who is in the room but does not sign.
  { const found = r.pub ? appFor(r.owner, r.name, c ? c.path : null) : null;
    const det = el('details', 'cc-q'); det.append(el('summary', null, 'See the code behind this'));
    for (const kid of Array.from(card.children)) if (!kid.classList.contains('cc-x')) det.append(kid);
    let top;
    // WHERE TO PUT THE VISITOR. A carried file knows its own page; any other piece of work has the
    // page its files agreed on. Where that page is the application's own front door, the tile is the
    // application's, as before.
    const near = r.pub ? ((c && c.page) || pageOfWork[a.c.sha] || null) : null;
    const theApp = found && found.app ? found.app : null;
    if (near && !(theApp && theApp.live === near.address)) {
      top = el('a', 'cc-tile cc-app cc-page'); top.href = near.address; top.target = '_blank'; top.rel = 'noopener';
      top.setAttribute('data-app', theApp ? theApp.app : ''); top.setAttribute('data-page', near.address);
      if (theApp) top.append(el('div', 'cc-tile-part', 'part of ' + theApp.button));
      top.append(el('div', 'cc-tile-name', near.title || near.address.replace(/^https?:\/\//, '')));
      top.append(el('span', 'cc-tile-open', 'OPEN THIS PAGE'));
    } else if (found && found.app) {
      top = el('a', 'cc-tile cc-app'); top.href = found.app.live; top.target = '_blank'; top.rel = 'noopener';
      top.setAttribute('data-app', found.app.app);
      top.append(el('div', 'cc-tile-name', found.app.button));
      if (whatItDoes[found.app.live]) top.append(el('div', 'cc-tile-what', whatItDoes[found.app.live] + '.'));
      top.append(el('span', 'cc-tile-open', 'OPEN ' + found.app.button));
    } else {
      top = el('div', 'cc-notile cc-app');
      top.setAttribute('data-app', found && found.unproved ? '?' : '');
      top.append(el('div', null, 'This work has no page of its own yet.'));
    }
    // THE LINKS A CARD CARRIES, IN THE OPEN AND IN AS FEW WORDS AS THEY NEED: the application (above),
    // GitHub as one quiet word for those who know what it is, and the site itself whenever there is
    // nothing else to offer, so that no card is ever a dead end.
    const links = el('div', 'cc-row cc-links');
    { const gu = r.pub ? gh({ owner:r.owner, repo:r.name, commit:a.c.sha }) : null;
      if (!near && !(found && found.app)) {
        // the front door of the site this work is served from, where it has one; else the main site
        const door = (r.pub && frontOfWork[a.c.sha]) || 'https://www.globalgrid2050.com/';
        const hl = linkTo(door, door.replace(/^https?:\/\//, '').replace(/\/$/, ''));
        hl.classList.add('cc-home'); links.append(hl); }
      // GITHUB IS HUMBLE: one small grey word at the very bottom of the code fold, for those who know
      // what it is. Never a sentence, and never in the way of a visitor who does not.
      if (gu) { const src = el('div', 'cc-source'); const gl = linkTo(gu, 'source'); gl.classList.add('cc-gh');
        src.append(gl); det.append(src); cardSource = src; } }
    const brand = el('div', 'scada-brand'), inner = el('div');
    inner.append(el('div', 'scada-brand-main', 'Ventus'), el('div', 'scada-brand-sub', 'Cables & Connectivity\u00ae'));
    brand.append(inner);
    const plain = el('div', 'cc-plain', 'Engineering work in ' + r.name + ', done on ' + day(a.c.unix) + '.');
    card.append(top, links, brand, plain, det);
    det.open = codeOpen;
    // ASKED FOR MUST MEAN SEEN. With the tile, the brand and the plain line above it, the code opened
    // below the fold of the card on a phone. Opening it brings the window into view, then the line.
    det.addEventListener('toggle', () => { if (det.open && cardShown && cardShown.window) revealCode(); dirty = true; }); }
  const meta = el('dl', 'cc-dl');
  drow(meta, 'work', r.name + ' \u00b7 ' + day(a.c.unix));
  const u = r.pub ? gh({ owner:r.owner, repo:r.name, commit:a.c.sha }) : null;
  const d = drow(meta, 'history', '');
  if (u) { d.append(linkTo(u, 'source')); d.append(' \u00b7 commit ' + a.c.sha.slice(0, 7)); }
  else d.textContent = 'not public, so there is no link';
  s.body.append(meta);
  if (!c) { workCode(a, r, s); return; }
  const j = a.k - c.k0;
  s.setTag('LOAD', 'reading the lines around it from this site\u2026');
  const put = data => {
    if (!s.live()) return;
    cardShown = { card:c, line:j, data, sheet:s };
    const short = c.commit.slice(0, 7), fileName = c.path.split('/').pop();
    // THE ARITHMETIC THIS CARD IS ABOUT TO RELY ON, CHECKED BEFORE IT IS RELIED ON. The pack was
    // built from git and every line proved against it when it was built; what can still go wrong
    // here is the pack and the list disagreeing about the length of the file, and then every number
    // below would be a guess.
    if (!c.here || data.lines !== c.lines || data.text.length !== c.lines || !(j >= 0 && j < c.lines)) {
      s.setTag('FAIL', !c.here
        ? 'This file is no longer in the repository, so its neighbours today would not be this line\u2019s neighbours. Nothing around it is shown.'
        : 'The record says this file has ' + fmt(c.lines) + ' lines and the text carried for it has '
          + fmt(data.text.length) + ', so the numbering cannot be trusted. Nothing around it is shown.');
      const h = el('div', 'cc-codehead');
      h.append(c.path + ' \u00b7 ' + c.repo + ' @ ' + short + ' \u00b7 line ' + fmt(j + 1) + ' \u00b7 ');
      h.append(linkTo(ghLink(c, j + 1), 'source'));
      s.body.append(h);
      dirty = true; return;
    }
    const from = Math.max(1, j + 1 - CONTEXT), to = Math.min(data.text.length, j + 1 + CONTEXT);
    const head = el('div', 'cc-codehead');
    head.append(c.path + ' \u00b7 ' + c.repo + ' @ ' + short + ' \u00b7 line ' + fmt(j + 1)
              + ' \u00b7 showing ' + fmt(from) + '\u2013' + fmt(to) + ' of ' + fmt(data.text.length) + ' \u00b7 ');
    head.append(linkTo(ghLink(c, j + 1), 'source'));
    s.body.append(head);
    s.body.append(el('div', 'cc-check',
      'These lines are carried on this site, read from ' + c.repo + ' at commit ' + short
      + ' when this page was built and checked line for line against it then \u00b7 '
      + fmt(j + 1 - from) + ' above, ' + fmt(to - j - 1) + ' below. Scroll inside the window to see them all;'
      + ' a long line scrolls sideways.'));
    const w = codeWindow(data.text, from, to, j + 1);
    s.body.append(w.node);
    cardShown.window = w;
    s.setTag('OK', 'the line and the lines around it, as the file stood that day');
    s.body.append(el('div', 'cc-disclaimer',
      'Provided as is, without warranty of any kind; a chart, not a design.'));
    if (cardSource && cardSource.parentNode) cardSource.parentNode.append(cardSource);
    requestAnimationFrame(() => { if (s.live()) revealCode(); });
    revealCode();
    dirty = true;
  };
  if (cardCache[c.file]) { put(cardCache[c.file]); return; }
  fetch('cosmos/cards/' + c.file).then(x => x.json()).then(dd => { cardCache[c.file] = dd; put(dd); })
    .catch(e => s.setTag('FAIL', 'the lines around this one could not be read from this site: ' + (e && e.message || e)));
}
function goKey(k){ endIsolate(); const p = keyPlace(k); target = { x:p[0], y:p[1] }; show(address(k)); flyTo(p[0], p[1], 14); }
// ARRIVING BY SOMEBODY ELSE'S LINK. The view flies, the arrow is shot, the card opens: three things
// in that order, because a card that appears over a picture of nine thousand pieces of work asks to
// be taken on trust, and an arrow from the middle of the record to one dot does not.
function arriveAt(k){
  endIsolate();
  const a = address(k);
  if (!a) return;
  const p = keyPlace(k);
  target = null; arrow = null; arrowTip = null; card.style.display = 'none';
  flyTo(p[0], p[1], Math.max(14, zoom));
  setTimeout(() => { arrow = { k, t0:performance.now() }; dirty = true; }, 920);
  setTimeout(() => { target = { x:p[0], y:p[1] }; show(a); dirty = true; }, 920 + ARROW_MS);
}
// SHOW NEW CODE. "New" is measured from the newest commit, not from the wall clock, so the same
// page gives the same answer tomorrow. Keys run in time order, so what is new is always one
// contiguous band at the rim: the boundary is a single circle, and that circle is drawn.
function showNew(hours){
  endIsolate();
  const last = commits[commits.length-1].unix, cut = last - hours*3600;
  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';
    { const r0 = repos[c.repo], u0 = r0.pub ? gh({ owner:r0.owner, repo:r0.name, commit:c.sha }) : null;
      card.classList.remove('sheet');
      card.innerHTML = 'NEW CODE · the last ' + anim_hours + ' hours of work, as a band at the rim'
        + '\n<b>' + fmt(n) + '</b> pieces of work, <b>' + fmt(lines) + '</b> lines added'
        + '\nbegins with <b>' + r0.name + '</b>, ' + day(c.unix)
        + (u0 ? '\n<a class="cc-gh" style="color:#666;font-size:10.5px" href="' + u0 + '" target="_blank" rel="noopener">GitHub</a>' : ''); }
    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.