GLOBALGRID2050 / EXPLORE CODE

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

Kuiper Tests and 1 more file (part 1)

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.

700 lines of JavaScript from globalgrid2050, in 2 files. Topic: Kuiper, cosmos and drawing engines. Section 1244 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 Card render · globalgrid2050 / kuiper-grid/i0073/cartridges/004000000000-kuiper-card.js lines 1–283
  2. Kuiper Tests test · globalgrid2050 / kuiper-grid/i0073/cartridges/004100000000-kuiper-tests.js lines 1–417

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: 96% of its lines are the same as kuiper-grid/drawing/kuiper-card.js (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 95% of lines shared with Kuiper Card; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9559 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 kuiper-grid/drawing/kuiper-card.js:1-277 d76a0c3635a858e4e087db51aa46d419c325cd72
  • sha256 704370dd2bf1fd85a14e0b4b5793f6482e9ce6e754436e34177226633922e70d
  • target sha256 5e632857c5a3501aae563f61ef2bb44cef03923c020066caa35b64e7fe88bad8
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

renderglobalgrid2050 / kuiper-grid/i0073/cartridges/004000000000-kuiper-card.js · lines 1–283 of 283 · Not reached from any entry point (candidate for review) · pattern revealUnderHead (shared by 3 files)

What it does
It draws its content. Defines 19 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, revealUnderHead, 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/004000000000-kuiper-card.js:1-283 · blob c33bbf6a9f09c3d0a7723cfb05ed81dff295443c · 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); }
// THE SAME WINDOW, ASKED FOR BY PLACE. A runner holds this page's code window against the wafer's own card on
// the same lines of the same public files and fails unless the text is the same. This is not a second way of
// showing code: it is the one way (the same file reader, the same window) with the place given from outside.
window.__kuiperCode = async (owner, repo, commit, path, line) => { const lines = await rawFile(owner, repo, commit, path);
  const at = Math.min(Math.max(1, line | 0), lines.length), from = Math.max(1, at - CONTEXT), to = Math.min(lines.length, at + CONTEXT);
  const rows = codeWindow(lines, from, to, at).node.textContent.split(String.fromCharCode(10));
  return { from, to, at, rows:rows.map((t, i) => ({ n:from + i, text:t.slice(8) })) }; };
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()) revealUnderHead(); }); revealUnderHead(); 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);
  });
}
// THE CODE IS BROUGHT IN UNDER THE HEAD, never over it: the window's top is put just below the head's foot,
// and then the marked line is brought to the middle of the window.
function revealUnderHead(){ const w = cardShown && cardShown.window; if (!w) return;
  const head = card.querySelector('.cc-head'), floor = head ? head.getBoundingClientRect().bottom : card.getBoundingClientRect().top;
  card.scrollTop += w.node.getBoundingClientRect().top - (floor + 4);
  w.scrollToTarget(); }
{ const st = document.createElement('style');
  st.textContent = '#card .cc-head{position:sticky;top:-8px;z-index:2;background:#000;padding-top:8px;margin-top:-8px}'
    + '#card.codeopen .cc-tile-what,#card.codeopen .scada-brand,#card.codeopen .cc-plain,#card.codeopen .cc-links{display:none}'
    + '#card.codeopen .cc-tile{padding:8px 12px;margin:2px 0 6px}#card.codeopen .cc-tile-name{font-size:16px;margin-bottom:.35rem}'
    + '#card.codeopen .cc-tile-open{padding:.4rem 0}#card.codeopen .cc-tile-part{margin-bottom:.15rem}'
    + '@media (max-width:640px){#card.codeopen .cc-code{max-height:24vh}}';
  document.head.appendChild(st); }
function show(a){
  card.classList.remove('codeopen');
  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) + '.');
    // THE HEADER IS THE HEADER. It stays at the top of the card whatever is opened under it.
    const head = el('div', 'cc-head'); head.append(top, links, brand, plain);
    card.append(head, det);
    det.open = codeOpen; card.classList.toggle('codeopen', det.open);
    det.addEventListener('toggle', () => { card.classList.toggle('codeopen', det.open); });
    // 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) revealUnderHead(); 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()) revealUnderHead(); });
    revealUnderHead();
    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.

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: 92% 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). 91% of lines shared with Kuiper Tests; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9194 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 kuiper-grid/i0073/releases/003100000000-kuiper-shell/kuiper-tests.js:1-844 ad24a37445c54d4bffe4fa63a649d1f4292a151c
  • sha256 fefa0a309b92da778bc2c92fcc837ecf2521826d189a666019b8c2a470f82693
  • 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/004100000000-kuiper-tests.js · lines 1–417 of 897 · 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
finishSelftest, pathSelftest, inWindow, on, buttonsSelftest, settle, litPixels, isolateSelftest, onScreen, census, ring, ev, ask, cardSelftest, esc1, box
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/004100000000-kuiper-tests.js:1-417 · blob 1311e354804310ceb4fe6738baf3d828e54ef121 · 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
'use strict';
// kuiper-tests.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.
function finishSelftest(c, n, lines){
  let maxOld = 0; for (let i = 0; i < newFrom; i++) maxOld = Math.max(maxOld, commits[i].k1);
  const a = address(c.k0), nb = selftest.newBandPixel || [0,0,0], pp = selftest.pupilPixel || [0,0,0];
  const T = { T1_new_is_one_band_beyond_everything_older: c.k0 >= maxOld,
              T2_boundary_key_resolves_to_a_new_commit: !!(a && !a.silent && a.i >= newFrom && a.m === 0),
              T3_flash_is_amber_on_the_new_band: nb[0] > 150 && nb[0] > nb[2] + 40,
              T3_no_flash_on_the_silent_centre: pp[0] < 40 && pp[1] < 40,
              new_commits: n, new_lines: lines, boundary_key: c.k0, newBandPixel: nb, pupilPixel: pp };
  T.PASS = T.T1_new_is_one_band_beyond_everything_older && T.T2_boundary_key_resolves_to_a_new_commit && T.T3_flash_is_amber_on_the_new_band && T.T3_no_flash_on_the_silent_centre;
  window.__selftest = T; document.title = 'selftest ' + (T.PASS ? 'PASS' : 'FAIL');
}
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)); };

// EVERY CONTROL AFTER EVERY OTHER CONTROL. The black screen that reached a visitor was two presses
// long, and every check this page had pressed one. Each press is run to its END (every animation
// driven past its finish), then the picture is asked whether anything is lit and the state line is
// asked whether it says what is shown.
async function buttonsSelftest(){
  await asmReady;
  const T = { viewport:[innerWidth, innerHeight] }, R = Math.sqrt(SPACE);
  const controls = Array.from(document.querySelectorAll('#apps button, #keys button')).filter(b => b.getAttribute('data-k') !== '/');
  T.controls = controls.map(b => b.textContent);
  const settle = async () => { for (let i = 0; i < 60; i++) {
      if (isoAnim) isoAnim.t0 = performance.now() - 60000; if (bodyAnim) bodyAnim.t0 = performance.now() - 60000;
      if (anim) anim.t0 = performance.now() - 60000; if (tween) tween.t0 = performance.now() - 60000;
      frameOnce(); await new Promise(r => setTimeout(r, 5));
      if (!isoAnim && !bodyAnim && !anim && !tween) break; } draw(); };
  // EVERY PIXEL OF THE PICTURE, READ ONCE. Lit means plainly brighter than the dimmed record, which is
  // about a tenth of full and sums to under sixty.
  const litPixels = () => { draw(); const w = cv.width, h = cv.height, buf = new Uint8Array(w * h * 4);
    gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, buf); let lit = 0;
    for (let q = 0; q < buf.length; q += 4) if (buf[q] + buf[q+1] + buf[q+2] > 150) lit++;
    return { lit, of:w * h }; };
  const bad = []; let pairs = 0;
  for (const a of controls) for (const b of controls) {
    dispatchEvent(new KeyboardEvent('keydown', { key:'Backspace' })); await settle(); unisolate(true); anim = null; home(); tween = null; draw();
    a.click(); await settle(); b.click(); await settle(); pairs++;
    const p = litPixels(), says = hud.textContent.indexOf('ISOLATED') >= 0;
    if (p.lit < 60) bad.push([a.textContent, b.textContent, 'the screen is blank: ' + p.lit + ' of ' + p.of + ' samples lit']);
    if (says !== !!iso) bad.push([a.textContent, b.textContent, 'the state line says ' + (says ? 'ISOLATED' : 'nothing') + ' and the picture is ' + (iso ? 'isolated' : 'not')]);
    if (iso && b.getAttribute('data-app') === null && b.getAttribute('data-k') !== null) bad.push([a.textContent, b.textContent, 'still isolated after a control that is not an application']); }
  T.pairs_pressed = pairs; T.what_went_wrong = bad.slice(0, 12); T.how_many_went_wrong = bad.length;
  T.T1_every_control_after_every_other_never_blanks_the_screen = pairs >= 16 && !bad.some(x => /blank/.test(x[2]));
  T.T2_the_state_line_always_says_what_is_shown = !bad.some(x => /state line|still isolated/.test(x[2]));
  T.PASS = T.T1_every_control_after_every_other_never_blanks_the_screen && T.T2_the_state_line_always_says_what_is_shown;
  window.__selftest = T; document.title = 'selftest ' + (T.PASS ? 'PASS' : 'FAIL');
}
// P1, TESTED: "isolate every app with the faraday pulse and then be able to visit those apps".
async function isolateSelftest(){
  await asmReady;
  const T = { viewport:[innerWidth, innerHeight], programs:programs.length }, R = Math.sqrt(SPACE);
  const onScreen = el => { if (!el) return false; const r = el.getBoundingClientRect();
    if (!(r.width > 4 && r.height > 4 && r.top >= -0.5 && r.bottom <= innerHeight + 0.5 && r.left >= -0.5 && r.right <= innerWidth + 0.5)) return false;
    const h = document.elementFromPoint(Math.round(r.left + r.width/2), Math.round(r.top + r.height/2)); return !!h && (h === el || el.contains(h) || h.contains(el)); };
  // one button for every program, all of them on the screen with nothing to scroll or type
  const btns = Array.from(document.querySelectorAll('#apps button'));
  T.buttons = btns.map(b => b.textContent);
  // ON A PHONE THE ROW IS BEHIND ONE CHIP, so the disc has the screen: the chip is on the screen, one tap
  // opens the row, and then every button is. On a desktop they are simply all there.
  { const chip = document.getElementById('appschip');
    if (narrow() && chip) { T.the_chip_is_on_the_screen = onScreen(chip); T.buttons_hidden_until_asked_for = !btns.some(onScreen);
      chip.click(); await new Promise(r => setTimeout(r, 80)); }
    T.T1_a_button_for_every_application_all_on_the_screen = programs.length > 0 && btns.length === programs.length && btns.every(onScreen)
      && (!narrow() || !chip || (T.the_chip_is_on_the_screen && T.buttons_hidden_until_asked_for));
    if (narrow() && chip) { chip.click(); await new Promise(r => setTimeout(r, 80)); } }
  // a brightness census of the picture: how much of the disc is lit, along eight spokes
  const census = () => { draw(); const px = new Uint8Array(4); let bright = 0, green = 0, seen = 0;
    const x0 = (0 - cx)*zoom + cv.width/2, y0 = cv.height/2 + cy*zoom, Rp = R*zoom;
    for (let a = 0; a < 8; a++) for (let t = 0.06; t < 0.98; t += 0.004) {
      const x = Math.round(x0 + Math.cos(a*0.785)*Rp*t), y = Math.round(y0 + Math.sin(a*0.785)*Rp*t);
      if (x < 0 || y < 0 || x >= cv.width || y >= cv.height) continue;
      gl.readPixels(x, cv.height - 1 - y, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, px); seen++;
      if (px[1] > 215 && px[2] >= px[1] - 12 && px[0] > px[1] * 0.6) green++; else if (px[0] + px[1] + px[2] > 240) bright++; }
    return { seen, bright, green }; };
  unisolate(true); closeCard(); { const h = homeCamera(); cx = h.x; cy = h.y; zoom = h.z; tween = null; }
  const before = census();
  // every program, by the numbers
  const per = [], wrong = [];
  for (const pr of programs) { const st = isolateNow(pr.name); draw(); await new Promise(r => setTimeout(r, 30));
    const want = (appWork[pr.select.app] || []).filter(sha => bySha.get(sha) !== undefined).length;
    const tile = card.querySelector('a.cc-tile'), count = card.querySelector('.cc-count');
    const row = { program:pr.name, lit:st && st.lit, dark:st && st.dark, git_named:want, tile:tile && tile.href };
    per.push(row);
    if (!st || st.lit !== want || st.lit + st.dark !== commits.length || st.lit === 0) wrong.push([pr.name, 'count']);
    if (!tile || tile.href !== pr.end.tile || !onScreen(tile)) wrong.push([pr.name, 'tile']);
    if (!count || count.textContent.indexOf(fmt(st.lit)) < 0 || count.textContent.indexOf(fmt(st.dark)) < 0) wrong.push([pr.name, 'numbers not shown']);
    if (hud.textContent.indexOf('ISOLATED') < 0 || hud.textContent.indexOf(fmt(st.dark) + ' dark') < 0) wrong.push([pr.name, 'readout']); }
  T.every_program = per; T.what_was_wrong = wrong;
  T.T2_the_work_lit_is_exactly_the_work_git_named_and_lit_plus_dark_is_the_whole = programs.length > 0 && !wrong.some(w => w[1] === 'count');
  T.T3_every_tile_opens_its_application_and_is_on_the_screen = !wrong.some(w => w[1] === 'tile');
  T.T4_the_numbers_are_shown_on_the_tile_and_in_the_readout = !wrong.some(w => w[1] === 'numbers not shown' || w[1] === 'readout');
  // the picture: with the biggest application isolated the rest really is dark
  const big = programs.slice().sort((a, b) => (appWork[b.select.app] || []).length - (appWork[a.select.app] || []).length)[0];
  isolateNow(big.name); card.style.display = 'none'; if (body) body.shown = false; glowOff = true; const after = census(); glowOff = false;
  T.the_picture = { before, after, isolated:big.name };
  T.T5_what_is_not_the_application_goes_dark_in_the_picture = before.bright > 50 && after.bright < before.bright * 0.15;
  // the front: with it half way out, inside has switched and outside has not (the sparks at the work, not gathered)
  if (body) body.shown = false; iso.front = R * 0.5; draw();
  const ring = (t0, t1) => { const px = new Uint8Array(4); let b = 0, k = 0; const x0 = (0 - cx)*zoom + cv.width/2, y0 = cv.height/2 + cy*zoom, Rp = R*zoom;
    for (let a = 0; a < 8; a++) for (let t = t0; t < t1; t += 0.004) { const x = Math.round(x0 + Math.cos(a*0.785)*Rp*t), y = Math.round(y0 + Math.sin(a*0.785)*Rp*t);
      if (x < 0 || y < 0 || x >= cv.width || y >= cv.height) continue; gl.readPixels(x, cv.height - 1 - y, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, px); k++;
      if (px[0] + px[1] + px[2] > 240 && !(px[1] > 140 && px[1] > px[0] + 50)) b++; } return k ? b / k : 0; };
  const inside = ring(0.10, 0.45), outside = ring(0.55, 0.95);
  T.bright_share_inside_and_outside_the_front = [+inside.toFixed(3), +outside.toFixed(3)];
  T.T6_each_dot_switches_when_the_front_reaches_it = outside > 0.05 && inside < outside * 0.3;
  // GROW AND GLOW: with the program's glow the lit work covers many times the pixels it covered as
  // pin points, measured in the picture itself by switching the glow off and on again.
  isolateNow(programs[0].name); card.style.display = 'none'; if (body) body.shown = false;
  glowOff = true; const pins = census(); glowOff = false; const glow = census();
  T.lit_pixels_as_pin_points_and_with_the_glow = [pins.green, glow.green]; T.sparks = iso.sparks;
  // NOTHING IS DRAWN ADDITIVELY ANY MORE: switching the old glow off and on changes nothing in the picture
  T.T11_nothing_is_drawn_additively = glow.green === pins.green;
  // the glow arrives WITH the front: half way out there is glow inside and none outside
  iso.front = Math.sqrt(commits[iso.idx[0]].k0) * 0.97; const notYet = census(); iso.front = 1e30;
  T.glow_before_the_front_reaches_the_work = notYet.green;
  T.T12_before_the_front_reaches_the_work_none_of_it_is_lit = notYet.green === 0;
  // ON A PHONE THE CARD MUST NOT HIDE THE SHOW: a short tile, the middle of the disc above it
  isolateNow(programs[0].name); tween = null; layout(); { const h = homeCamera(); cx = h.x; cy = h.y; zoom = h.z; } draw();
  { const cr = card.getBoundingClientRect(), yMid = cv.height/2 + cy*zoom, Rp = R*zoom;
    const tile = card.querySelector('a.cc-tile'), open = tile && tile.querySelector('.cc-tile-open');
    T.card_top_and_disc = { card_top:Math.round(cr.top), disc_middle:Math.round(yMid), disc_radius:Math.round(Rp), card_height:Math.round(cr.height) };
    T.T13_the_tile_is_short_and_the_disc_stays_in_view = !narrow() || (cr.top >= yMid + Rp - 1 && Rp >= 70 && cr.height <= innerHeight * 0.30 && onScreen(open));
    T.T14_the_numbers_and_the_brand_are_lower_in_the_same_card = !!card.querySelector('.cc-count') && !!card.querySelector('.scada-brand')
      && card.querySelector('.scada-brand-sub').textContent === 'Cables & Connectivity\u00ae'; }
  // THE BODY. A smaller Kuiper of the application's own work, under the black sky rule, then its name.
  { const st = isolateNow(programs[0].name); card.style.display = 'none';
    // A MISSING MODULE MUST FAIL, NOT FALL BACK QUIETLY: without it there is no body at all.
    T.T14b_the_shared_gathering_module_was_read = !!ASM && !!body; T.states = body ? body.states.map(x => x.shape) : null;
    // ONE DOT FOR EVERY PIECE OF WORK, IN ORDER OF KEY, so the oldest work is the middle
    let ordered = !!body; if (body) for (let j = 1; j < st.idx.length; j++) if (commits[st.idx[j]].k0 < commits[st.idx[j-1]].k0) ordered = false;
    T.T15_one_dot_for_every_piece_of_work_in_order_of_key = !!body && body.n === st.lit && ordered;
    // every dot ends exactly where the SHARED module says, in every state
    let off = 0; if (body) for (const x of body.states) { const unit = ASM.targets(x.shape, body.n), Rw = R * x.frac;
      for (let q = 0; q < unit.length; q++) if (Math.abs(x.to[q] - unit[q] * Rw) > Rw * 1e-5) off++; }
    // a screen too small to resolve the name keeps the small Kuiper alone: one state there, two where the name can be read
    T.T16_every_dot_ends_exactly_where_the_shared_module_says = !!body && off === 0 && body.states.length >= (narrow() ? 1 : 2);
    // oldest in the middle, newest at the rim: the first dot is nearer the middle than the last
    const c0 = body && body.states[0].to; T.T17_it_is_a_smaller_kuiper_oldest_in_the_middle = !!c0
      && Math.hypot(c0[0], c0[1]) < Math.hypot(c0[c0.length - 2], c0[c0.length - 1]) * 0.25
      && Math.hypot(c0[c0.length - 2], c0[c0.length - 1]) <= R * body.states[0].frac * 1.0001;
    // THE BLACK SKY RULE, in every state and for EVERY application: no two centres closer than three
    // dot radii, the radius being what is drawn at this zoom. And a planted too tight body must FAIL.
    tween = null; { const h = homeCamera(); cx = h.x; cy = h.y; zoom = h.z; }
    const sky = [], broke = [];
    for (const pr of programs) { isolateNow(pr.name); card.style.display = 'none'; if (!body) { broke.push([pr.name, 'no body']); continue; }
      body.states.forEach((x, k) => { bodyJump(k); const rWorld = bodyDotPx() / zoom, v = blackSky(body.pos, rWorld);
        sky.push([pr.name, x.shape.slice(0, 12), body.n, +(v.gap * zoom).toFixed(2), +bodyDotPx().toFixed(2), +x.frac.toFixed(2)]);
        if (!v.ok && !x.unresolved) broke.push([pr.name, x.shape, 'centres closer than three radii']);
        if (bodyDotPx() < DOT_MIN_PX * 0.999 && !x.unresolved) broke.push([pr.name, x.shape, 'a dot under a pixel, not said to be unresolved']); }); }
    T.app_shape_dots_gap_px_dot_px_body_share = sky; T.black_sky_faults = broke;
    T.T18_the_black_sky_rule_holds_for_every_application_in_every_state = sky.length > 0 && broke.length === 0;
    const tight = new Float32Array(200); for (let q = 0; q < 200; q++) tight[q] = (q % 7) * 0.5;      // centres half a unit apart
    T.T19_a_planted_too_tight_body_is_failed_by_the_same_rule = blackSky(tight, 1).ok === false && blackSky(new Float32Array([0,0, 10,0, 0,10]), 1).ok === true;
    // IN THE PICTURE: the body is a population, not a patch. Lit share inside it is well under the
    // point where a field turns to mush (about 63 per cent), there is black between, and no white.
    isolateNow(programs[0].name); card.style.display = 'none'; bodyJump(0); draw();
    { const px = new Uint8Array(4), x0 = (0 - cx)*zoom + cv.width/2, y0 = cv.height/2 + cy*zoom, Rp = R*zoom*body.states[0].frac; let lit = 0, white = 0, k = 0;
      for (let yy = -Rp; yy <= Rp; yy += 2) for (let xx = -Rp; xx <= Rp; xx += 2) { if (xx*xx + yy*yy > Rp*Rp) continue;
        gl.readPixels(Math.round(x0 + xx), cv.height - 1 - Math.round(y0 + yy), 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, px); k++;
        if (px[1] > 215 && px[2] >= px[1] - 12) lit++; if (px[0] > 250 && px[1] > 250 && px[2] > 250) white++; }
      T.inside_the_body = { samples:k, lit_share:+(lit / k).toFixed(3), white_pixels:white };
      T.T20_the_body_is_a_population_not_a_patch = k > 50 && lit > 0 && lit / k < 0.45 && white === 0; }
    // a tap on a dot of the body opens that piece of work
    { const j = Math.floor(body.n / 2), x = (body.pos[2*j] - cx) * zoom + innerWidth / 2, y = innerHeight / 2 - (body.pos[2*j+1] - cy) * zoom;
      const ev = (t, px2, py2) => cv.dispatchEvent(new PointerEvent(t, { pointerId:31, clientX:px2, clientY:py2, bubbles:true, pointerType:'touch' }));
      ev('pointerdown', x, y); ev('pointerup', x, y); await new Promise(r => setTimeout(r, 150));
      const want = commits[iso.idx[j]];
      T.T21_a_tap_on_a_dot_of_the_body_opens_that_piece_of_work = card.style.display !== 'none' && card.textContent.indexOf(day(want.unix)) >= 0; } }
  // THE RULE, ASKED OF WHAT IS ACTUALLY DRAWN, ON A SCREEN LIKE A VISITOR'S. A real screen has a pixel
  // ratio of 1.5 or 2 and a headless one has 1, which is how a blob reached a reviewer past every
  // photograph. The diameter below is the very number handed to the GPU, in the canvas's own pixels.
  { const realRatio = window.devicePixelRatio;
    try { Object.defineProperty(window, 'devicePixelRatio', { value:2, configurable:true }); } catch (e) {}
    const perCss = cv.width / innerWidth, tooBig = [];
    for (const pr of programs) { isolateNow(pr.name); card.style.display = 'none'; tween = null; { const h = homeCamera(); cx = h.x; cy = h.y; zoom = h.z; }
      if (!body) continue;
      const ask = (label) => { const gapPx = closestPair(body.pos) * zoom * perCss, d = bodyDrawnDiameter();
        if (d / 2 * 3 > gapPx * 1.0001 && d > 1.0001) tooBig.push([pr.name, label, 'drawn radius ' + (d / 2).toFixed(2) + ' px, gap ' + gapPx.toFixed(2) + ' px']); };
      body.states.forEach((x, k) => { bodyJump(k); ask(x.shape.slice(0, 10)); });
      // in flight: from the rim to the small Kuiper, and from the small Kuiper to the name
      const legs = [[body.from, body.states[0].to, 'rim to cluster']]; if (body.states.length > 1) legs.push([body.states[0].to, body.states[1].to, 'cluster to name']);
      for (const [a0, b0, what] of legs) for (const t of [0.25, 0.5, 0.75]) { ASM.step(a0, b0, t, body.pos); bodyTo(body.pos); body.shown = true; ask(what + ' at ' + t); } }
    try { Object.defineProperty(window, 'devicePixelRatio', { value:realRatio, configurable:true }); } catch (e) {}
    T.dots_drawn_wider_than_a_third_of_their_gap = tooBig.slice(0, 10); T.how_many = tooBig.length;
    T.T27_no_dot_is_ever_drawn_wider_than_a_third_of_its_gap_at_rest_or_in_flight = programs.length > 0 && tooBig.length === 0; }
  // ONE PALETTE: what is lit is the pulse's own white and ice blue, never the saturated green. Asked of the
  // picture: inside a gathered body the lit pixels are blue-white (blue at least as strong as green, red not
  // far behind), and none is the old green.
  { isolateNow(programs[0].name); card.style.display = 'none'; tween = null; { const h = homeCamera(); cx = h.x; cy = h.y; zoom = h.z; } bodyJump(0); draw();
    const w = cv.width, h2 = cv.height, buf = new Uint8Array(w * h2 * 4); gl.readPixels(0, 0, w, h2, gl.RGBA, gl.UNSIGNED_BYTE, buf);
    let ice = 0, green = 0; for (let q = 0; q < buf.length; q += 4) { const r0 = buf[q], g0 = buf[q+1], b0 = buf[q+2];
      if (g0 > 215 && b0 >= g0 - 12 && r0 > g0 * 0.6) ice++; else if (g0 > 150 && g0 > b0 + 60 && g0 > r0 + 60) green++; }
    T.lit_pixels_ice_blue_and_old_green = [ice, green];
    T.T28_what_is_lit_is_the_pulses_white_and_ice_blue_not_green = ice > 50 && green === 0;
    const o = document.getElementById('o');
    T.T29_the_month_labels_are_put_away_while_work_is_gathered = !!o && o.style.visibility === 'hidden';
    unisolate(true); T.T30_and_come_back_when_it_is_over = !!o && o.style.visibility !== 'hidden'; }
  // A NAME ONLY WHEN IT CAN BE READ: every application that spells its name has a dot for every square of it
  { const thin = [];
    for (const pr of programs) { isolateNow(pr.name); card.style.display = 'none'; if (!body) continue;
      const named = body.states.find(x => x.shape.indexOf('text:') === 0); if (!named) continue;
      const ink = ASM.raster(named.shape.slice(5)).on.reduce((t, v) => t + v, 0); if (body.n < ink) thin.push([pr.name, body.n, ink]); }
    T.names_spelt_with_too_few_dots = thin;
    T.which_applications_spell_their_name = programs.filter(pr => { isolateNow(pr.name); card.style.display = 'none'; return body && body.states.some(x => x.shape.indexOf('text:') === 0); }).map(pr => pr.name);
    T.T31_a_name_is_spelt_only_when_there_are_enough_pieces_to_read_it = thin.length === 0; }
  // THE END STATE ON THE SCREEN THE PERSON IS HOLDING. A phone showed the tile and an empty centre: the
  // work gathered, flew, and was gone. At the end of every program the dots are inside the disc, and
  // they are IN THE PICTURE, not only in the arithmetic.
  { const empty = [];
    for (const pr of programs) { isolateNow(pr.name); layout(); tween = null; { const h = homeCamera(); cx = h.x; cy = h.y; zoom = h.z; } draw();
      if (!body || !body.shown) { empty.push([pr.name, 'no body']); continue; }
      let far = 0; for (let q = 0; q < body.pos.length; q += 2) if (Math.hypot(body.pos[q], body.pos[q+1]) > R * 1.0001) far++;
      const w = cv.width, h2 = cv.height, buf = new Uint8Array(w * h2 * 4); gl.readPixels(0, 0, w, h2, gl.RGBA, gl.UNSIGNED_BYTE, buf);
      const x0 = (0 - cx)*zoom + w/2, y0 = h2/2 + cy*zoom, Rp = R*zoom*body.states[body.k].frac + 3; let lit = 0;
      for (let yy = Math.max(0, Math.floor(y0 - Rp)); yy < Math.min(h2, y0 + Rp); yy++) for (let xx = Math.max(0, Math.floor(x0 - Rp)); xx < Math.min(w, x0 + Rp); xx++) {
        const q = ((h2 - 1 - yy) * w + xx) * 4; if (buf[q+1] > 215 && buf[q+2] >= buf[q+1] - 12) lit++; }
      if (far || lit < body.n) empty.push([pr.name, body.states[body.k].shape, 'dots outside the disc: ' + far + ', lit pixels in the body: ' + lit + ' for ' + body.n + ' dots']); }
    T.end_states_that_showed_nothing = empty;
    T.T23_at_the_end_of_every_program_the_work_is_in_the_picture = programs.length > 0 && empty.length === 0; }
  // every tile has its one plain sentence
  { const silent = programs.filter(pr => { const ap = apps.find(x => x.app === pr.select.app); return !ap || !(whatItDoes[ap.live] || '').length; }).map(pr => pr.name);
    T.tiles_without_a_sentence = silent; T.T24_every_tile_has_its_one_plain_sentence = silent.length === 0; }
  // the row holds applications a person acts in, in the order given, and nothing else
  T.the_row = Array.from(document.querySelectorAll('#apps button')).map(x => x.textContent);
  T.T25_the_row_is_the_seven_applications_in_order = T.the_row.join('|') === 'GRIDATLAS|PIPELINE NEWS|CABLES|REAL SYSTEMS|SPIDER SANDBOX|GRID ENGINE|PERIODIC TABLE';
  // the top box says KUIPER and one short line; the warranty line is on the screen; the hints are folded
  { const topText = document.getElementById('top').textContent.replace(/\s+/g, ' ').trim(), lg = document.querySelector('#foot .long'), sh = document.querySelector('#foot .short');
    T.the_top_box_says = topText;
    T.T26_the_top_box_is_kuiper_and_one_short_line = /^Kuiper/i.test(topText) && topText.length < 40 && !/pieces of work|20\d\d/.test(topText)
      && (!lg || lg.getClientRects().length === 0) && !!sh && sh.getClientRects().length > 0 && /without warranty of any kind/.test(sh.textContent); }
  // pressing a button runs the program to its end; whole view puts everything back
  btns[0].click(); await new Promise(r => setTimeout(r, 60));
  T.T7_a_press_starts_the_front_at_the_origin = !!iso && !!isoAnim && iso.front < R * 0.2;
  if (isoAnim) isoAnim.t0 = performance.now() - isoAnim.ms - 5;
  for (let i = 0; i < 40 && isoAnim; i++) { frameOnce(); await new Promise(r => setTimeout(r, 50)); }
  T.after_the_front_the_work_is_gathering = !!bodyAnim && bodyAnim.k === 0 && card.style.display !== 'none' && !!card.querySelector('a.cc-tile');
  const seen = [];
  for (let i = 0; i < 80 && bodyAnim; i++) { seen.push(bodyAnim.k + bodyAnim.phase); bodyAnim.t0 = performance.now() - 60000; frameOnce(); await new Promise(r => setTimeout(r, 20)); }
  T.the_show_went = seen.filter((v, i) => v !== seen[i - 1]);
  T.T8_and_ends_with_the_tile_open = !isoAnim && !bodyAnim && !!iso && iso.front > R && T.after_the_front_the_work_is_gathering
    && T.the_show_went.join(',') === body.states.map((x, k) => k + 'move,' + k + 'hold').join(',') && !!body && body.k === body.states.length - 1
    && card.style.display !== 'none' && !!card.querySelector('a.cc-tile');
  dispatchEvent(new KeyboardEvent('keydown', { key:'Backspace' })); await new Promise(r => setTimeout(r, 60));
  T.T22_whole_view_sends_the_work_home_first = !!bodyAnim && bodyAnim.home === true && !!iso;
  for (let i = 0; i < 40 && bodyAnim; i++) { bodyAnim.t0 = performance.now() - 60000; frameOnce(); await new Promise(r => setTimeout(r, 20)); }
  draw();
  T.T9_whole_view_puts_everything_back = iso === null && !document.querySelector('#apps button.on') && hud.textContent.indexOf('ISOLATED') < 0;
  // the link: built by the contract, read back by the contract, and it names a program
  const href = buildLink({ isolate:'gridatlas' });
  T.the_link = href;
  T.T10_a_link_arrives_already_isolated = parseLink(href).isolate === 'gridatlas' && !!programs.find(p => p.name === 'gridatlas');
  T.PASS = Object.keys(T).filter(k => /^T\d+_/.test(k)).every(k => T[k] === true);
  window.__selftest = T; document.title = 'selftest ' + (T.PASS ? 'PASS' : 'FAIL');
}
async function cardSelftest(){
  codeOpen = true;                       // the engineer's questions first, asked with the code opened
  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() === '' || card.textContent.indexOf(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 w = cardShown && cardShown.window, pre = w && w.node;
    const lh = pre ? parseFloat(getComputedStyle(pre).lineHeight) || 16 : 16;
    const pad = pre ? parseFloat(getComputedStyle(pre).paddingTop) || 0 : 0;
    if (w) w.place();
    T.marked_line = w ? w.at : null;
    T.T4_it_is_the_marked_line = !!w && w.at === j + 1
      && Math.abs(parseFloat(w.bar.style.top) - (pad + (w.at - w.first) * lh)) < 0.6
      && pre.textContent.split('\n')[w.at - w.first] === String(w.at).padStart(6) + '  ' + 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
  // A DOT WHOSE FILE IS NOT CARRIED HERE SHOWS THE CODE ITS PIECE OF WORK CHANGED, read from the public
  // repository at that exact commit. Asked of a piece of work the table names, with the code opened.
  const table = await workTable();
  T.the_table_of_changed_code_was_read = !!table; T.pieces_of_work_in_it = table ? Object.keys(table).length : 0;
  const wc = table && commits.find(q => table[q.sha] && !cardFor(q.k0) && repos[q.repo].pub);
  const far = wc ? wc.k0 : cards.reduce((m, x) => Math.max(m, x.k0 + x.lines), 0) + 1000;
  show(address(far));
  for (let i = 0; i < 120 && !(cardShown && cardShown.work) && !/FAIL|EMPTY/.test((card.querySelector('.cc-tag') || {}).textContent || ''); i++) await new Promise(r => setTimeout(r, 100));
  { const w = cardShown && cardShown.work ? cardShown : null, row = wc && table[wc.sha];
    T.a_piece_of_work_shows = w ? [w.path, 'line ' + w.line, (w.lines[w.line - 1] || '').slice(0, 60)] : (card.querySelector('.cc-tagline') || {}).textContent;
    T.T6_a_dot_with_no_carried_file_shows_the_code_its_work_changed = !!w && !!row && w.path === row[2][0] && w.line === Math.min(Math.max(1, row[2][1]), w.lines.length)
      && w.window.node.textContent.split('\n')[w.line - w.from] === String(w.line).padStart(6) + '  ' + w.lines[w.line - 1]
      && /This piece of work changed [\d,]+ files?\. Showing /.test(card.textContent) && (card.querySelector('.cc-tag') || {}).textContent === 'OK'; }
  // 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 chip = card.querySelector('.cc-tag');
  T.the_state_it_shows = chip ? chip.getAttribute('data-s') : null;
  T.T11_it_says_the_work_the_day_and_where_to_see_it =
       /(?<!\d)\d{1,2} [A-Z][a-z]{2} \d{4}(?!\d)/.test(seenText)
    && T.the_state_it_shows === 'OK'
    && (seenText.indexOf('not public') >= 0 ? !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*="#L"]');
  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 w = cardShown && cardShown.window, pre = w && w.node;
    const lh = pre ? parseFloat(getComputedStyle(pre).lineHeight) || 16 : 16;
    if (w) w.scrollToTarget();
    const below = w ? w.last - w.at : 0;
    const roomBelow = pre ? Math.floor((pre.scrollTop + pre.clientHeight - ((w.at - w.first + 1) * lh)) / lh) : 0;
    T.lines_below_the_marked_line = below; T.lines_below_it_on_the_screen = Math.min(below, roomBelow);
    T.T8_ten_lines_below_are_there_and_five_are_on_the_screen = below >= CONTEXT && roomBelow >= 5 && on(pre);
    // A LONG LINE MAY RUN PAST THE EDGE ONLY IF THE WINDOW CAN BE SCROLLED TO IT. The wafer's window
    // keeps code as code, unwrapped; what would be a fault is a line cut off with no way to reach it.
    const ox = pre ? getComputedStyle(pre).overflowX : '';
    T.T9_no_code_line_runs_off_the_right_edge = !!pre && (pre.scrollWidth <= pre.clientWidth + 1 || ox === 'auto' || ox === 'scroll');
    const chip2 = card.querySelector('.cc-tag');
    T.the_state_of_a_carried_line = chip2 ? chip2.getAttribute('data-s') : null;
    T.T21_the_state_chip_says_OK_and_only_one_thing = !!chip2 && T.the_state_of_a_carried_line === 'OK'
      && card.querySelectorAll('.cc-tag').length === 1; }
  const bdy = card.querySelector('.cc-body');
  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), body:box(bdy), window:box(card.querySelector('.cc-code')) };
  T.header = (card.querySelector('.cc-dl') || card).textContent.replace(/\s+/g, ' ').trim().slice(0, 120);
  T.T10_the_header_says_what_day_the_work_was_done = /(?<!\d)\d{1,2} [A-Z][a-z]{2} \d{4}(?!\d)/.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 = /(?<!\d)\d{1,2} [A-Z][a-z]{2} \d{4}(?!\d)/.test(card.textContent) && !!card.querySelector('.cc-tag'); }
  } 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());