GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / globalgrid2050 / testcode/wafer-development-environment/202609192047-proof-k0017

Wafer Development Environment — Proof K0017 Page (part 2)

A web page in the testcode folder of GlobalGrid2050 that draws link contract. Published at https://globalgrid2050.com/testcode/wafer-development-environment/202609192047-proof-k0017/. It builds link (`buildLink`), parses link (`parseLink`) and renders code (`renderCode`).

511 lines of HTML from globalgrid2050, in 1 file. Topic: Kuiper, cosmos and drawing engines. Section 1478 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. Wafer Development Environment — Proof K0017 Page render · globalgrid2050 / testcode/wafer-development-environment/202609192047-proof-k0017/index.html lines 701–1211

Wafer Development Environment — Proof K0017 Page

A web page in the testcode folder of GlobalGrid2050 that draws link contract. Published at https://globalgrid2050.com/testcode/wafer-development-environment/202609192047-proof-k0017/. It builds link (`buildLink`), parses link (`parseLink`) and renders code (`renderCode`).

renderglobalgrid2050 / testcode/wafer-development-environment/202609192047-proof-k0017/index.html · lines 701–1211 of 1211 · version 2026-09-19 20:47 (continued from section 1477) · Entry point · pattern renderCode (shared by 3 files)

What it does
It draws link contract. Defines 64 functions or classes, including buildLink, complaints, parseLink, fmt, day. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: JSON file link-contract.json; form fields (user input). Out: web page; WebGL/WebGPU drawing.
Downstream impact
Used directly by 5 files: GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); Homepage Versions — Before Refresh Page (globalgrid2050, https://globalgrid2050.com/homepage_versions/20260922-before-refresh/); Homepage V123 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v123.html); Homepage V124 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v124.html); and 1 more. Reached from 83 other entry points, including GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); Homepage V037 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v037.html); Homepage V038 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v038.html). It is itself an entry point, published at https://globalgrid2050.com/testcode/wafer-development-environment/202609192047-proof-k0017/.
What it achieves
Its `lightTime` function gives commit period summary or null from year, optional month and optional day (VEDIC: period). It reads `cosmos/link-contract.json`. It responds to webglcontextlost, resize and pointerdown events.
Why it matters
Loaded by the GlobalGrid2050 Homepage Before Four Nests page at https://globalgrid2050.com/homepage-before-four-nests-20260925.html and 4 other pages.
Application
globalgrid2050 · testcode/wafer-development-environment/202609192047-proof-k0017 · page
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 GlobalGrid2050 Homepage Before Four Nests (link), linked from Homepage Versions — Before Refresh Page (link), linked from Homepage V123 (link), linked from Homepage V124 (link), linked from Homepage V125 (link)
Produces
buildLink, complaints, parseLink, fmt, day, words, prog, U, tsv, narrow, resize, flyTo
Defines here
loadTracked, raiseFlags, lightPath, pathSelftest, inWindow, on, cardSelftest, esc1, box, same, repoSelftest, strip, check, phoneSelftest, ev, seen, walk, lightTime, pinchNow, pointerGone, goToKey
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/wafer-development-environment/202609192047-proof-k0017/index.html:701-1211 · blob 3ab451f5177af46b76125d44b12801d94e9f8c3d · GitHub at these lines
State
achieves: code · context: readme_derived · stage: output · effects: dom, network · domain stage: experimental · users: none · canonical: production_core
  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');
}
// ------------------------------------------------------------------ where a page is on the wafer
// A PAGE IS NOT A PLACE. tools/where.py asks git which commits touched a path and cosmos/wafer.tsv
// where each of those commits landed, and writes both files this reads. The page then does the same
// key arithmetic over its own commit table and the test is that the two agree exactly, commit by
// commit, key by key. Neither is trusted: they are made to contradict each other or agree.
async function loadTracked(){
  if (tracked) return tracked;
  const [tt, cc] = await Promise.all([tsv('cosmos/tracked.tsv'), tsv('cosmos/tracked-commits.tsv')]);
  tracked = { paths:tt.map(p => ({ repo:p[0], path:p[1], use:p[2], in_git:+p[3], on_wafer:+p[4],
                lines_in_those_commits:+p[5], k0:+p[6], k1:+p[7], first:p[8], last:p[9] })),
              commits:cc.map(p => ({ path:p[0], sha:p[1], unix:+p[2], lines:+p[3], k0:+p[4], k1:+p[5] })) };
  return tracked;
}
function raiseFlags(idx){
  pathFlags.fill(0); for (const i of idx) pathFlags[i] = 1;
  gl.activeTexture(gl.TEXTURE1); gl.bindTexture(gl.TEXTURE_2D, pathTex);
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.R32F, TW, pathRows, 0, gl.RED, gl.FLOAT, pathFlags);
  gl.activeTexture(gl.TEXTURE0);
}
async function lightPath(name, quiet){
  const T = await loadTracked();
  const row = T.paths.find(p => p.path.toLowerCase() === String(name).toLowerCase());
  if (!row) return { error:'no tracked page of that name: run tools/where.py --five', asked_for:name };
  const want = T.commits.filter(c => c.path === row.path);
  const idx = [], missing = [], disagreed = [];
  for (const c of want) { const i = bySha.get(c.sha);
    if (i === undefined) { missing.push(c.sha); continue; }
    if (commits[i].k0 !== c.k0 || commits[i].k1 !== c.k1) disagreed.push({ sha:c.sha, page:[commits[i].k0, commits[i].k1], tool:[c.k0, c.k1] });
    idx.push(i); }
  idx.sort((a, b) => a - b);
  litRepo = -1; litK = [-1,-1]; litCi = null; newFrom = -1; flash = 0; pulse = -1; target = null;
  litPath = { row, idx }; raiseFlags(idx);
  tween = null; cx = 0; cy = 0; zoom = (Math.min(cv.width, cv.height)/2)*0.80/Math.sqrt(SPACE); draw();
  if (!quiet) { card.style.display = 'block';
    card.classList.remove('sheet'), card.innerHTML = 'PATH:' + row.path + '\n' + row.repo + '\n\n' + fmt(row.on_wafer) + ' commits touched it, of ' + fmt(row.in_git)
      + ' git knows\nfirst ' + row.first + ', last ' + row.last
      + '\n\nkeys ' + fmt(row.k0) + ' .. ' + fmt(row.k1)
      + '\n' + fmt(row.lines_in_those_commits) + ' lines in those commits, which is the commits, not the page'
      + '\n\nuse: ' + row.use; }
  return { row, idx, want:want.length, missing, disagreed };
}
// THE TEST. ?selftest=path:<name>. The count the page lit must be the count the tool counted, every
// sha the tool named must be a commit this wafer holds, and every key must match to the digit. Then
// the picture: at a zoom where one of those commits is more than a pixel wide, that pixel must
// actually carry the path's light, or the page is lighting a set it never drew.
async function pathSelftest(name){
  const r = await lightPath(name, true);
  if (r.error) { window.__selftest = { PASS:false, asked_for:name, error:r.error }; document.title = 'selftest FAIL'; return; }
  let raised = 0; for (let i = 0; i < pathFlags.length; i++) if (pathFlags[i] > 0.5) raised++;
  const T = { page:r.row.path, repository:r.row.repo, use:r.row.use,
    commits_lit_by_the_page:r.idx.length, commits_counted_by_where_py:r.row.on_wafer, commits_git_knows:r.row.in_git,
    shas_the_wafer_does_not_hold:r.missing, keys_where_tool_and_page_disagree:r.disagreed, flags_raised_in_the_texture:raised,
    first_key:r.row.k0, last_key:r.row.k1,
    T1_the_page_lit_what_where_py_counted: r.idx.length === r.row.on_wafer && r.idx.length === r.want,
    T2_every_sha_the_tool_named_is_on_this_wafer: r.missing.length === 0,
    T3_tool_and_page_give_every_commit_the_same_keys: r.disagreed.length === 0,
    T4_the_light_was_actually_raised: raised === r.idx.length && r.idx.length > 0 };
  // the picture: the widest of its commits, at a zoom that makes it three pixels of radius
  let best = -1, bestW = 0;
  for (const i of r.idx) { const w = Math.sqrt(commits[i].k1) - Math.sqrt(commits[i].k0); if (w > bestW) { bestW = w; best = i; } }
  const zWant = 3/Math.max(bestW, 1e-12), z = Math.min(zWant, POINTS_FROM*0.9), wpx = bestW*z;
  T.widest_commit_px_at_the_zoom_used = +wpx.toFixed(3);
  if (best >= 0 && wpx >= 1) {
    const mid = (Math.sqrt(commits[best].k0) + Math.sqrt(commits[best].k1))/2, p = keyPlace(mid*mid);
    tween = null; cx = p[0]; cy = p[1]; zoom = z; dirty = true; draw();
    const px = new Uint8Array(4); gl.readPixels(Math.round(cv.width/2), Math.round(cv.height/2), 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, px);
    T.pixel_at_the_middle_of_its_widest_commit = [px[0], px[1], px[2]];
    T.T5_that_pixel_carries_the_paths_light = px[0] > 120 && px[2] > 100 && px[0] > px[1] + 40 && px[2] > px[1] + 30;
  } else { T.T5_that_pixel_carries_the_paths_light = null; T.why_no_pixel_was_read = 'every commit of this page is finer than one pixel at any zoom the field is drawn at'; }
  T.PASS = T.T1_the_page_lit_what_where_py_counted && T.T2_every_sha_the_tool_named_is_on_this_wafer
        && T.T3_tool_and_page_give_every_commit_the_same_keys && T.T4_the_light_was_actually_raised
        && T.T5_that_pixel_carries_the_paths_light !== false;
  window.__selftest = T; document.title = 'selftest ' + (T.PASS ? 'PASS' : 'FAIL');
}

// THE CARD, TESTED. A key in the middle of a carried file is tapped by the page itself; the line the
// card shows must be the line that file holds at that number, the marked line must be that one and no
// other, and the panel must be on the screen. A key with no card must say so and show no code at all.
// A RECTANGLE IS NOT A SIGHTING. The link's box was inside the window and the sheet's own overflow
// was hiding it, so the check passed and the photograph showed no link. Ask what is actually at the
// point, which is the question a thumb asks.
const inWindow = r => !!r && r.width > 4 && r.height > 4 && r.top >= -0.5 && r.bottom <= innerHeight + 0.5
                && r.left >= -0.5 && r.right <= innerWidth + 0.5;
const on = el => { if (!el) return false; const r = el.getBoundingClientRect(); if (!inWindow(r)) return false;
  const hit = document.elementFromPoint(Math.round(r.left + r.width / 2), Math.round(r.top + r.height / 2));
  return !!hit && (hit === el || el.contains(hit) || hit.contains(el)); };

async function cardSelftest(){
  const T = { cards_carried: cards.length };
  if (!cards.length) { T.PASS = false; T.error = 'no file carries its keys on this page';
    window.__selftest = T; document.title = 'selftest FAIL'; return; }
  const c = cards[0], j = Math.floor(c.lines / 2), k = c.k0 + j;
  T.file = c.path; T.line_asked_for = j + 1; T.key = k;
  show(address(k));
  for (let i = 0; i < 60 && !cardShown; i++) await new Promise(r => setTimeout(r, 100));
  const d = cardShown && cardShown.data;
  T.T1_the_card_opened_for_that_key = !!cardShown && cardShown.line === j;
  T.T2_the_line_shown_is_the_line_that_file_holds = !!d && typeof d.text[j] === 'string';
  const html = card.innerHTML;
  const want = d ? d.text[j] : null;
  const esc1 = t => String(t).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  T.T3_that_exact_text_is_on_the_screen = !!want && (want.trim() === '' || html.indexOf(esc1(want)) >= 0);
  // THE MARKED ROW IS THE ONE THE KEY ASKED FOR, and the text in it is that file's line. Marking the
  // wrong row is the one failure a reader could not catch: the code would be real and the answer wrong.
  { const hit = card.querySelector('.cl.hit'), tx = hit && hit.querySelector('.tx');
    T.marked_line = hit ? hit.getAttribute('data-line') : null;
    T.T4_it_is_the_marked_line = !!hit && hit.getAttribute('data-line') === String(j + 1)
      && !!tx && tx.textContent === String(want); }
  const r = card.getBoundingClientRect();
  T.T5_the_card_is_on_the_screen = r.width > 40 && r.height > 20 && r.left >= -0.5 && r.right <= innerWidth + 0.5;
  // and a key that no file carries must say so, and show no code
  const far = cards.reduce((m, x) => Math.max(m, x.k0 + x.lines), 0) + 1000;
  show(address(far));
  await new Promise(r => setTimeout(r, 150));
  T.T6_a_key_with_no_card_shows_no_code = card.innerHTML.indexOf('<pre') < 0 && card.innerHTML.indexOf('class="cl"') < 0;
  // AND IT SAYS THE THREE THINGS A PERSON ASKED. Almost every tap a stranger makes lands here, so
  // this is the card that matters most: what the work was, the day it was done, one link to it.
  const seenText = card.textContent.replace(/\s+/g, ' ');
  T.the_plain_card = seenText.slice(0, 160);
  const lnk = card.querySelector('a[href*="github.com/"]');
  const priv = seenText.indexOf('This work is not public.') >= 0;
  T.T11_it_says_the_work_the_day_and_where_to_see_it =
       /\bwork of \d{1,2} [A-Z][a-z]{2} \d{4}\b/.test(seenText)
    && seenText.indexOf('The code for this line is not carried here yet.') >= 0
    && (priv ? !lnk : !!lnk && /\/commit\/[0-9a-f]{7,40}$/.test(lnk.getAttribute('href')) && on(lnk));
  // NO ARITHMETIC AND NO INSTRUCTIONS ANYWHERE ON THE PAGE, not in a card and not in the markup a
  // reader can read. The words are listed once so they cannot come back by accident.
  // WRITTEN IN PIECES ON PURPOSE. Spelled out, the list of forbidden words IS three forbidden words
  // in the page, and the check fails on itself. It did, on its first run.
  const BANNED = ['pyth' + 'on ', 'key' + '.py', 'ever ' + 'issued'];
  const whole = document.documentElement.outerHTML.toLowerCase();
  T.banned_words_found = BANNED.filter(w => whole.indexOf(w) >= 0 || seenText.toLowerCase().indexOf(w) >= 0);
  T.T12_no_arithmetic_and_no_command_anywhere_on_the_page = T.banned_words_found.length === 0;
  // THE LINK AND THE LINES BELOW IT, MEASURED. The 0012 review found the card cut off after the
  // marked line on a phone: the ten lines below and the link to GitHub were behind the button bar.
  // Being in the markup is not being on the screen, so this asks the layout where they really are.
  show(address(k));
  for (let i = 0; i < 60 && !cardShown; i++) await new Promise(r => setTimeout(r, 100));
  await new Promise(r => setTimeout(r, 120));
  const lk = card.querySelector('a[href*="github.com"]');
  T.T7_the_github_link_is_on_the_screen = on(lk);
  T.link_rect = lk ? [lk.getBoundingClientRect().left, lk.getBoundingClientRect().top,
                      lk.getBoundingClientRect().right, lk.getBoundingClientRect().bottom].map(Math.round) : null;
  const rws = Array.prototype.slice.call(card.querySelectorAll('.cl'));
  const mk = rws.map(el => el.getAttribute('data-line')).indexOf(String(j + 1));
  let below = 0, belowOn = 0;
  for (let i = mk + 1; mk >= 0 && i < rws.length; i++) { below++; if (on(rws[i])) belowOn++; }
  T.lines_below_the_marked_line = below; T.lines_below_it_on_the_screen = belowOn;
  T.T8_ten_lines_below_are_there_and_five_are_on_the_screen = below >= CONTEXT && belowOn >= 5;
  const bdy = card.querySelector('.cb');
  T.T9_no_code_line_runs_off_the_right_edge = !!bdy && bdy.scrollWidth <= bdy.clientWidth + 1;
  const box = el => { if (!el) return null; const r = el.getBoundingClientRect();
    return [r.left, r.top, r.right, r.bottom].map(Math.round); };
  T.sheet_rects = { card:box(card), head:box(card.querySelector('.ch')), body:box(bdy), foot:box(card.querySelector('.cf')) };
  const hdr = card.querySelector('.ch');
  T.header = hdr ? hdr.textContent.replace(/\s+/g, ' ').trim() : null;
  T.T10_the_header_says_what_day_the_work_was_done = !!T.header && /\b\d{1,2} [A-Z][a-z]{2} \d{4}\b/.test(T.header);
  // A TAP IN A DARK GAP MUST LEAD SOMEWHERE. A key between two pieces of work is a real place on
  // this picture and a reader lands on one often; it named the next piece of work and then left them
  // holding a sentence with nothing to press.
  let silent = null;
  for (const c of commits) { const g = address(c.k1); if (g && g.silent && g.next) { silent = c.k1; break; } }
  T.a_key_in_a_gap = silent;
  if (silent !== null) {
    show(address(silent));
    await new Promise(r => setTimeout(r, 120));
    const way = card.querySelector('a[data-key]');
    T.the_gap_card = card.textContent.replace(/\s+/g, ' ').slice(0, 120);
    T.T13_a_gap_leads_to_the_next_work = !!way && on(way);
    if (way) { way.click(); await new Promise(r => setTimeout(r, 250));
      T.after_following_it = card.textContent.replace(/\s+/g, ' ').slice(0, 90);
      T.T13_a_gap_leads_to_the_next_work = /work of \d{1,2} [A-Z][a-z]{2} \d{4}/.test(card.textContent); }
  } else { T.T13_a_gap_leads_to_the_next_work = true; T.a_key_in_a_gap = 'this wafer has no gaps'; }
  // AND NO PANEL IS DRAWN FOR WORDS THAT ARE NOT THERE.
  litRepo = -1; litK = [-1, -1]; litCi = null; target = null; card.style.display = 'none'; draw();
  await new Promise(r => setTimeout(r, 60));
  { const hr = hud.getBoundingClientRect();
    T.readout_when_nothing_is_highlighted = [hud.textContent.trim().length, Math.round(hr.width), Math.round(hr.height)];
    T.T14_an_empty_readout_draws_no_box = hud.textContent.trim().length > 0 || hr.width < 1 || hr.height < 1; }
  // THE LINK CONTRACT, PROVED ON ITSELF AND AGAINST THE PUBLISHED TABLE. Parsing a link this page
  // built must give back exactly what it was asked for; and the address this page builds must be
  // the address the tools build, character for character, or the two have quietly drifted apart.
  try {
    const ct = await fetch('cosmos/link-contract.json').then(r => r.json());
    const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
    const wrong = [];
    for (const ex of ct.examples) {
      const built = buildLink(ex.asked);
      const want = {}; for (const k of Object.keys(LINK.params)) {
        const v = ex.asked[k]; want[k] = (v === undefined || v === null || v === '') ? null : v; }
      if (built !== ex.built) wrong.push({ asked:ex.asked, this_page:built, the_table:ex.built });
      else if (!same(parseLink(built), want)) wrong.push({ asked:ex.asked, came_back:parseLink(built) });
    }
    T.examples_checked = ct.examples.length;
    T.links_that_disagree = wrong;
    T.T15_a_link_this_page_built_parses_back_to_what_it_asked_for = ct.examples.length > 0 && wrong.length === 0;
  } catch (e) {
    // A TEST THAT CANNOT RUN MUST FAIL, NOT GO QUIET.
    T.T15_a_link_this_page_built_parses_back_to_what_it_asked_for = false;
    T.links_that_disagree = 'the published table could not be read: ' + (e && e.message || e);
  }
  // AND NOBODY TYPES AN ADDRESS. One function makes them; a hand written one is how the two halves
  // of a link stop agreeing without anybody noticing.
  try {
    const src = await fetch(location.pathname).then(r => r.text());
    const typed = [];
    for (const k of Object.keys(LINK.params)) {
      const needle = '?' + k + '=';
      let at = -1;
      while ((at = src.indexOf(needle, at + 1)) >= 0) {
        // A SENTENCE THAT MENTIONS AN ADDRESS IS NOT AN ADDRESS. A typed one begins a string, so
        // the character before the question mark is a quote. This sentence may not show you an
        // example, because an example would be the very thing it is looking for, and this check
        // failed on its own explanation the first time it ran.
        const before = at > 0 ? src[at - 1] : ' ';
        if (before === '"' || before === "'" || before === '`') typed.push(src.slice(Math.max(0, at - 30), at + 14));
      }
    }
    T.addresses_typed_by_hand = typed;
    T.T16_no_address_is_typed_by_hand_in_this_page = typed.length === 0;
  } catch (e) {
    T.T16_no_address_is_typed_by_hand_in_this_page = false;
    T.addresses_typed_by_hand = 'the page could not read its own source: ' + (e && e.message || e);
  }
  // ARRIVING BY A LINK. The view flies, an arrow is shot from the centre of the record to the work
  // the address names, and only then does the card open. The arrow must END ON THE DOT the card
  // describes: an arrow that points near the answer is worse than none, because it is believed.
  { const ka = c.k0 + Math.floor(c.lines / 3);
    home(); card.style.display = 'none'; target = null; arrow = null; arrowTip = null; draw();
    arriveAt(ka);
    // THE CLOCK IS NOT WHAT IS BEING CHECKED. Under a headless time budget this page gets about seven
    // animation frames in eight seconds, so waiting for the flight to finish measures the browser's
    // throttle. Put the camera where the flight was going, tell the arrow its time is up, draw once.
    for (let i = 0; i < 60 && !arrow; i++) await new Promise(r => setTimeout(r, 100));
    if (tween) { cx = tween.x1; cy = tween.y1; zoom = tween.z1; tween = null; }
    if (arrow) arrow.t0 = performance.now() - ARROW_MS;
    draw();
    const p = keyPlace(ka);
    const wx = (p[0] - cx) * zoom + ov.width / 2, wy = ov.height / 2 - (p[1] - cy) * zoom;
    T.arrow_tip = arrowTip ? [Math.round(arrowTip.x), Math.round(arrowTip.y)] : null;
    T.arrow_still_flying = !!arrow;
    T.camera = [Math.round(cx), Math.round(cy), +zoom.toFixed(3)];
    T.draws_seen = drawCount;
    T.the_dot_it_should_end_on = [Math.round(wx), Math.round(wy)];
    T.T17_the_arrow_ends_on_the_dot = !!arrowTip && arrowTip.done
      && Math.hypot(arrowTip.x - wx, arrowTip.y - wy) < 2;
    // and it is shot from the centre of the record, not from wherever the camera happened to be
    // IT COMES ALONG THE LINE FROM THE BEGINNING OF THE RECORD. After the camera flies, that point
    // is far off the screen, so what can be checked is not where the drawing starts but that the
    // drawing lies on the line: the direction is the meaning.
    { const c0x = (0 - cx) * zoom + ov.width / 2, c0y = ov.height / 2 + cy * zoom;
      const ux = wx - c0x, uy = wy - c0y, vx = (arrowTip ? arrowTip.x0 : 0) - c0x, vy = (arrowTip ? arrowTip.y0 : 0) - c0y;
      const cross = Math.abs(ux * vy - uy * vx) / Math.max(1, Math.hypot(ux, uy));
      T.arrow_starts_at = arrowTip ? [Math.round(arrowTip.x0), Math.round(arrowTip.y0)] : null;
      T.the_centre_of_the_record_is_at = [Math.round(c0x), Math.round(c0y)];
      T.how_far_the_arrow_is_off_that_line_px = arrowTip ? +cross.toFixed(2) : null;
      T.T18_it_is_shot_from_the_centre_of_the_record = !!arrowTip && cross < 2
        && arrowTip.x0 >= -1 && arrowTip.x0 <= ov.width + 1 && arrowTip.y0 >= -1 && arrowTip.y0 <= ov.height + 1; }
    for (let i = 0; i < 40 && card.style.display === 'none'; i++) await new Promise(r => setTimeout(r, 100));
    T.T19_and_then_the_card_opens = card.style.display !== 'none'
      && card.textContent.replace(/\s+/g, ' ').length > 20;
    T.the_card_after_arriving = card.textContent.replace(/\s+/g, ' ').slice(0, 90); }
  // AN ADDRESS THIS PAGE CANNOT ANSWER MUST SAY SO. The note claimed it already did; building such
  // a link was refused, but ARRIVING with one said nothing at all, which is the half a reader meets.
  { const A = window.__arrival || { said:[], shown:null };
    T.what_the_address_asked_for_that_this_page_cannot_answer = A.said;
    T.what_the_page_said_about_it = A.shown ? A.shown.replace(/\s+/g, ' ').slice(0, 150) : null;
    const said_it = A.said.length === 0 || (!!A.shown && A.said.every(x => A.shown.indexOf(x) >= 0));
    // and the sentences themselves, on addresses chosen here rather than on whatever this one was
    const one = complaints('https://x/?colour=red'), two = complaints('https://x/?key=abc'),
          none = complaints('https://x/?key=12&path=a');
    T.T20_an_address_it_cannot_answer_is_answered_in_words =
         said_it && one.length === 1 && one[0].indexOf('colour') >= 0
      && two.length === 1 && two[0].indexOf('whole number') >= 0 && none.length === 0; }
  T.sample_line = want === null ? null : String(want).slice(0, 80);
  T.PASS = T.T1_the_card_opened_for_that_key && T.T2_the_line_shown_is_the_line_that_file_holds
        && T.T3_that_exact_text_is_on_the_screen && T.T4_it_is_the_marked_line
        && T.T5_the_card_is_on_the_screen && T.T6_a_key_with_no_card_shows_no_code
        && T.T7_the_github_link_is_on_the_screen && T.T8_ten_lines_below_are_there_and_five_are_on_the_screen
        && T.T9_no_code_line_runs_off_the_right_edge && T.T10_the_header_says_what_day_the_work_was_done
        && T.T11_it_says_the_work_the_day_and_where_to_see_it
        && T.T12_no_arithmetic_and_no_command_anywhere_on_the_page
        && T.T13_a_gap_leads_to_the_next_work && T.T14_an_empty_readout_draws_no_box
        && T.T15_a_link_this_page_built_parses_back_to_what_it_asked_for
        && T.T16_no_address_is_typed_by_hand_in_this_page
        && T.T17_the_arrow_ends_on_the_dot && T.T18_it_is_shot_from_the_centre_of_the_record
        && T.T19_and_then_the_card_opens && T.T20_an_address_it_cannot_answer_is_answered_in_words;
  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(); }
  // 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){
  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; }
addEventListener('pointerup', e => {
  if (drag && moved < 4 && N) { const [wx, wy] = toWorld(e.clientX, e.clientY), r = Math.hypot(wx, wy);
    if (r*r < SPACE) { let k = zoom >= POINTS_FROM ? keyAt(wx, wy) : -1; const exact = k >= 0; if (!exact) k = Math.floor(r*r);
      target = exact ? { x:keyPlace(k)[0], y:keyPlace(k)[1] } : null; show(address(k)); } }
  pointerGone(e); });
addEventListener('pointercancel', pointerGone);
addEventListener('wheel', e => { const [wx, wy] = toWorld(e.clientX, e.clientY), f = e.deltaY < 0 ? 1.18 : 1/1.18;
  zoom = Math.max(1e-4, Math.min(ZMAX, zoom*f)); cx = wx - (e.clientX - innerWidth/2)/zoom; cy = wy + (e.clientY - innerHeight/2)/zoom;
  atHome = false; tween = null; dirty = true; }, { passive:true });
// the tap targets, so a phone can do everything the keyboard can
document.getElementById('keys').addEventListener('click', e => { const k = e.target.getAttribute('data-k'); if (!k) return;
  e.stopPropagation(); dispatchEvent(new KeyboardEvent('keydown', { key:k })); });
elTop.addEventListener('click', () => elTop.classList.toggle('open'));       // the long subtitle, collapsed by default
card.addEventListener('click', e => {
  // A LINK IN THE CARD IS NOT A DISMISSAL. Anywhere else in it closes the card, as before.
  const a = e.target.closest ? e.target.closest('a') : null;
  if (a && a.hasAttribute('data-key')) { e.preventDefault(); goToKey(+a.getAttribute('data-key')); return; }
  if (a) return;                                        // an address that leaves this page: let it
  card.style.display = 'none'; dirty = true; });
// GOING TO A KEY, from a link inside a card or from an address a reader arrived with. The camera
// flies, the dot is marked and its card opens: one way of arriving, however the reader got here.
function goToKey(k){
  const a = address(k);
  if (!a) return;
  const p = keyPlace(k);
  litK = [k, k + 1]; litCi = null; target = { x:p[0], y:p[1] };
  show(a); flyTo(p[0], p[1], Math.max(zoom, 14)); 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 === 'd') { detail = !detail; dirty = true; }
  else 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; litPath = null; card.style.display = 'none'; home(); } });
requestAnimationFrame(frame);
</script>
</body>
</html>