GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / galaxies-wafers / /

Galaxies Wafers — App

A JavaScript module that draws lines meta, families, blocks and cables, using SHA-256, and uses data from the stars repository. Served with the page at https://ventusltd.github.io/galaxies-wafers/.

700 lines of JavaScript from galaxies-wafers, in 1 file. Topic: Kuiper, cosmos and drawing engines. Section 1176 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. Galaxies Wafers — App render · galaxies-wafers / app.mjs lines 388–1087

Galaxies Wafers — App

A JavaScript module that draws lines meta, families, blocks and cables, using SHA-256, and uses data from the stars repository. Served with the page at https://ventusltd.github.io/galaxies-wafers/.

rendergalaxies-wafers / app.mjs · lines 388–1087 of 1609 (continued from section 1175) · Entry point · pattern machineDetail (shared by 2 files)

What it does
It draws lines meta, families, blocks and cables. Defines 91 functions or classes, including $, snapshot, clearColour, motion, indexOfKey. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain terms in the code: cables. README: "The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/202609151339."
Inputs & outputs
In: data source: stars data; JSON file all-lines.meta.json; JSON file families.json; JSON file blocks.json; JSON file index.json. Out: WebGL/WebGPU drawing.
Downstream impact
Used directly by 1 file: Galaxies Wafers — Index Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/). Reached from 242 other entry points, including 404 (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/404.html); Galaxies Wafers — Iterations Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/); Galaxies Wafers — Proof Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/proof/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/.
What it achieves
It indexes key (`indexOfKey`), builds gl (`buildGL`) and draws marks (`drawMarks`). The Line Wafer. Its code works with 100 kW. It responds to pointerdown, pointermove and pointerup events.
Why it matters
Loaded by the page of the same name at https://ventusltd.github.io/galaxies-wafers/.
Application
galaxies-wafers · / · JavaScript module
Uses
Galaxies Wafers — Lib (import), Stars — Index Page (estate URL)
Used by
loaded by Galaxies Wafers — Index Page (script src), mentioned in Standalone (comment link)
Produces
$, snapshot, clearColour, motion, indexOfKey, bin, tier1, tier2, compile, initGL, fallback2d, buildGL
Defines here
cacheRect, rasterCache, blitCache, recordFrame, render, draw, home, flyTo, famsOf, paintPanel, family, connect, famLine, s, gestures, up, Queue, LRU, cached, rawURL, ghURL, register, familyRecord, readSource, el, link, row, btn, sheet, setTag
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 app.mjs:388-1087 · blob 925d89a774d1abc7cc7ad231b4f5a460a8d67c6f · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: unknown · users: none · canonical: unknown
    gl.bindFramebuffer(gl.FRAMEBUFFER, null);
    if (!ok) throw new Error('framebuffer incomplete');
    cache.w = w; cache.h = h; cache.valid = false;
    return true;
  } catch (e) {
    console.warn('moving-frame cache unavailable, drawing every frame in full:', e.message);
    gl.bindFramebuffer(gl.FRAMEBUFFER, null);
    cache.broken = true;
    return false;
  }
}

/* Where the cached texture lands on screen, in clip space: [x0, y0, x1, y1]. */
function cacheRect() {
  const hw = cache.w / (cache.zoom * view.dpr * 2), hh = cache.h / (cache.zoom * view.dpr * 2);   /* half extents, world units */
  const kx = view.zoom * view.dpr * 2 / stage.width, ky = view.zoom * view.dpr * 2 / stage.height;
  return [(cache.x - hw - view.x) * kx, (cache.y - hh - view.y) * ky,
          (cache.x + hw - view.x) * kx, (cache.y + hh - view.y) * ky];
}

function rasterCache() {
  gl.bindFramebuffer(gl.FRAMEBUFFER, cache.fbo);
  gl.viewport(0, 0, cache.w, cache.h);
  drawPoints(cache.w, cache.h, view.x, view.y);
  gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  gl.viewport(0, 0, stage.width, stage.height);
  cache.x = view.x; cache.y = view.y; cache.zoom = view.zoom; cache.valid = true; cache.rasters++;
}

function blitCache() {
  let r = cacheRect();
  const covers = r[0] <= -1 && r[1] <= -1 && r[2] >= 1 && r[3] >= 1 && view.zoom / cache.zoom <= CACHE_MAGNIFY;
  if (!cache.valid || !covers) { rasterCache(); r = cacheRect(); }
  gl.clearColor(...clearColour(), 1); gl.clear(gl.COLOR_BUFFER_BIT);
  gl.disable(gl.BLEND);
  gl.useProgram(cache.prog); gl.bindVertexArray(cache.vao);
  gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, cache.tex);
  gl.uniform4f(cache.rect, r[0], r[1], r[2], r[3]);
  gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  gl.enable(gl.BLEND);
}

/* ── the frame budget: measured, never typed ─────────────────────────────── */

/* The time between consecutive drawn frames while the camera is moving. It
   includes the GPU and compositor work that the draw calls themselves do not
   wait for. A gap longer than IDLE_GAP_MS is the camera resting, not a frame. */
const IDLE_GAP_MS = 250;
const budget = { last: 0, ring: new Float64Array(60), n: 0, i: 0, shown: 0 };
function recordFrame() {
  const t = performance.now(), dt = t - budget.last;
  budget.last = t;
  if (dt <= 0 || dt > IDLE_GAP_MS) return;
  budget.ring[budget.i] = dt; budget.i = (budget.i + 1) % 60; budget.n = Math.min(60, budget.n + 1);
  if (t - budget.shown < 250) return;
  budget.shown = t;
  const s = Array.from(budget.ring.subarray(0, budget.n)).sort((x, y) => x - y);
  const el = $('budget');
  if (el) el.textContent = `frame ${s[s.length >> 1].toFixed(1)} ms · median of the last ${budget.n} frames`;
}

function render() {
  recordFrame();
  if (gl) {
    if (MOTION.moving && ensureCache()) blitCache();
    else { cache.valid = false; drawPoints(stage.width, stage.height, view.x, view.y); }
  } else if (ctx2d) {
    const c = ctx2d;
    c.setTransform(1, 0, 0, 1, 0, 0);
    c.fillStyle = GROUND.dark ? '#030406' : '#0b0d12'; c.fillRect(0, 0, stage.width, stage.height);
    c.fillStyle = GROUND.dark ? '#1e222c' : '#7d8598';   /* dark values: 21-dark-pixels */
    const step = view.zoom < 0.5 ? 7 : 1;
    for (let i = 0; i < U.n; i += step) {
      const x = (U.pos[i * 2] - view.x) * view.zoom * view.dpr + stage.width / 2;
      const y = stage.height / 2 - (U.pos[i * 2 + 1] - view.y) * view.zoom * view.dpr;
      if (x < 0 || y < 0 || x > stage.width || y > stage.height) continue;
      c.fillRect(x, y, view.dpr, view.dpr);
    }
  }
  drawMarks();
  { const snap = snapshot(); for (const f of window.__wafer.onDraw) { try { f(snap); } catch (e) { console.warn('onDraw listener failed:', e); } } }
}

let pending = false;
function draw() { if (!pending) { pending = true; requestAnimationFrame(() => { pending = false; render(); }); } }

/* ── the beam: steering and focusing ─────────────────────────────────────── */

function home() {
  const maxR = SPACING * Math.sqrt(U.meta.max);
  view.x = 0; view.y = 0;
  view.zoom = Math.min(view.w, view.h) / (maxR * 2.15);
  draw();
}

function flyTo(key, zoom) {
  const [x, y] = placeOne(key);
  const z0 = view.zoom, x0 = view.x, y0 = view.y;
  const z1 = zoom ?? Math.max(view.zoom, 9);
  const t0 = performance.now(), ms = 620;
  (function step(t) {
    const u = Math.min(1, (t - t0) / ms);
    const e = u < .5 ? 4 * u * u * u : 1 - Math.pow(-2 * u + 2, 3) / 2;
    view.x = x0 + (x - x0) * e; view.y = y0 + (y - y0) * e;
    view.zoom = Math.exp(Math.log(z0) + (Math.log(z1) - Math.log(z0)) * e);
    motion(); render();
    if (u < 1) requestAnimationFrame(step);
  })(t0);
}

/* ── the panel: what the beam found ──────────────────────────────────────── */

function famsOf(key) {
  if (!U.ownerOf) return null;
  return U.ownerOf.get(key) || [];
}

function paintPanel(key) {
  const i = indexOfKey(key);
  const p = $('panelbody');
  if (i < 0) {
    p.innerHTML =
      `<h2>Line <span class="n">${fmt(key)}</span></h2>
       <p class="refuse">This number was never issued. The numbering runs 1 to ${fmt(U.meta.max)} and
       ${fmt(U.meta.max - U.n)} of those numbers were skipped, so a gap is a real answer rather than a
       missing record. The surface still has a place for it, and the beam is pointing at it.</p>`;
    $('panel').hidden = false; return;
  }
  const chars = U.lens[i], carried = U.inFam[i] === 1;
  const fams = famsOf(key);
  let body =
    `<h2>Line <span class="n">${fmt(key)}</span></h2>
     <dl>
       <dt>characters</dt><dd>${chars === 65535
          ? 'at least 65,535 — the pack stores this in sixteen bits and this line reaches the ceiling, so its true length is not known here'
          : fmt(chars) + (chars === 0 ? ' (an empty line)' : '')}</dd>
       <dt>permanent</dt><dd>this number is never reused, so it means this line for ever</dd>
       <dt>carried by</dt><dd>${carried ? 'at least one function family' : 'no function family'}</dd>
     </dl>`;
  if (!carried) {
    body += `<p class="refuse">Nothing can be connected to this line. It is numbered and it exists, but no
      function family in the estate carries it, so it has no partner to join it to.</p>`;
  } else if (fams === null) {
    body += `<p class="dim">The family index is still loading; the families carrying this line will appear here.</p>`;
  } else if (fams.length === 0) {
    body += `<p class="refuse">The pack marks this line as carried, but no family range in this build
      contains it. That disagreement is shown rather than smoothed over.</p>`;
  } else {
    const show = fams.slice(0, 12);
    body += `<p>Carried by <span class="fam">${fmt(fams.length)}</span> ${fams.length === 1 ? 'family' : 'families'}${fams.length > 12 ? ', first twelve' : ''}:</p><ul>` +
      show.map(f => {
        const fa = U.families[f];
        const cat = fa.category ?? 'no category recorded';
        return `<li><span class="fam">${esc(fa.name)}</span> <span class="dim">#${fmt(fa.n)} · ${esc(fa.kind)} · ${esc(cat)} · ${fmt(fa.lineCount)} lines</span></li>`;
      }).join('') + `</ul>`;
    if (fams.length > 60) {
      body += `<p class="dim">A line carried by this many families is almost certainly trivial: a brace, a
        blank, an import. Its connection count is drawn here rather than hidden, so you can see that for
        yourself.</p>`;
    }
  }
  p.innerHTML = body;
  $('panel').hidden = false;
}

function connect(ka, kb) {
  view.link = [ka, kb];
  const p = $('panelbody');
  const head = `<h2>Connect <span class="n">${fmt(ka)}</span> to <span class="n">${fmt(kb)}</span></h2>`;

  /* The index is the only thing that can be missing; everything else is decided
     by lib.mjs so the page cannot disagree with the proofs. */
  if (!U.ownerOf) {
    p.innerHTML = head + `<p class="dim">The family index is still loading. The answer will appear here
      without another tap.</p>`;
    $('panel').hidden = false; draw(); return;
  }

  const a = connectAnswer(ka, kb, { keys: U.keys, owner: U.ownerOf });
  const famLine = f => {
    const fa = U.families[f];
    return `<li><span class="fam">${esc(fa.name)}</span> <span class="dim">#${fmt(fa.n)} · ${esc(fa.category ?? 'no category recorded')}</span></li>`;
  };
  let body = head;

  if (a.verdict === 'absent') {
    body += `<p class="refuse">${a.absent.map(fmt).join(' and ')} ${a.absent.length > 1 ? 'were' : 'was'}
      never issued in this numbering, so there is nothing at that address to connect.</p>`;

  } else if (a.verdict === 'same-line') {
    body += `<p class="refuse">Those are the same line. A line is not connected to itself, and reporting
      that it is would be the page agreeing with you rather than answering you.</p>` +
      (a.both.length
        ? `<p>Line ${fmt(ka)} is carried by ${fmt(a.both.length)} ${a.both.length === 1 ? 'family' : 'families'}.</p>`
        : `<p>No family carries line ${fmt(ka)}.</p>`);

  } else if (a.verdict === 'no-family') {
    body += `<p class="refuse">${a.without.map(fmt).join(' and ')} ${a.without.length > 1 ? 'are' : 'is'}
      carried by no function family at all, so ${a.without.length > 1 ? 'they have' : 'it has'} nothing to be
      joined through.</p>`;

  } else if (a.verdict === 'joined') {
    body += `<p>Joined by <span class="fam">${fmt(a.both.length)}</span>
      ${a.both.length === 1 ? 'family that carries' : 'families that carry'} both lines${a.both.length > 12 ? ', first twelve' : ''}:</p>
      <ul>${a.both.slice(0, 12).map(famLine).join('')}</ul>
      <p class="dim">This is co-membership: two different lines sitting in one function. It is not the same
      text in two places, and it is not a dependency. Either line may be carried by only that one family and
      still connect perfectly well through it.</p>`;

  } else {
    body += `<p class="refuse">No family carries both lines, so these two are not joined.</p>
      <dl><dt>${fmt(ka)}</dt><dd>${a.A.length ? fmt(a.A.length) + ' ' + (a.A.length === 1 ? 'family' : 'families') : 'no family'}</dd>
          <dt>${fmt(kb)}</dt><dd>${a.B.length ? fmt(a.B.length) + ' ' + (a.B.length === 1 ? 'family' : 'families') : 'no family'}</dd></dl>
      <p class="dim">An unjoined pair is the ordinary case: most lines of the estate sit in unrelated
      functions. This is not about fanout. ${fmt(U.fanout)} of the ${fmt(U.n)} numbered lines appear in more
      than one family, which is duplication; joining two numbers asks the different question of whether one
      family holds them both.</p>`;
  }

  p.innerHTML = body;
  $('panel').hidden = false;

  /* Frame both ends. */
  const [ax, ay] = placeOne(ka), [bx, by] = placeOne(kb);
  view.x = (ax + bx) / 2; view.y = (ay + by) / 2;
  const span = Math.max(Math.hypot(bx - ax, by - ay), 4);
  view.zoom = Math.min(view.w, view.h) / (span * 1.8);
  draw();
}

/* ── gestures ────────────────────────────────────────────────────────────── */

function gestures() {
  let down = null, moved = 0, pinch = null, wasPinch = false;   /* a finger lifting after a pinch is not a tap */
  const pts = new Map();
  stage.addEventListener('pointerdown', e => {
    stage.setPointerCapture(e.pointerId);
    pts.set(e.pointerId, [e.clientX, e.clientY]);
    if (pts.size === 1) { down = [e.clientX, e.clientY]; moved = 0; }
    if (pts.size >= 2) wasPinch = true;
    if (pts.size === 2) {
      const [p, q] = [...pts.values()];
      pinch = { d: Math.hypot(p[0] - q[0], p[1] - q[1]), z: view.zoom };
    }
  });
  stage.addEventListener('pointermove', e => {
    if (!pts.has(e.pointerId)) return;
    const prev = pts.get(e.pointerId);
    pts.set(e.pointerId, [e.clientX, e.clientY]);
    if (pts.size === 2 && pinch) {
      const [p, q] = [...pts.values()];
      const d = Math.hypot(p[0] - q[0], p[1] - q[1]);
      if (pinch.d > 0) view.zoom = Math.max(0.02, Math.min(4000, pinch.z * (d / pinch.d)));
      motion(); draw(); return;
    }
    if (pts.size === 1) {
      const dx = e.clientX - prev[0], dy = e.clientY - prev[1];
      moved += Math.abs(dx) + Math.abs(dy);
      view.x -= dx / view.zoom; view.y += dy / view.zoom;
      motion(); draw();
    }
  });
  const up = e => {
    /* wasPinch: iterations/22-fast-zoom/app.mjs. The root treated the last finger
       of a pinch lifting as a tap and opened a panel under it. */
    if (pts.size === 1 && down && moved < 7 && !wasPinch) {
      /* iterations/31-code-card-everywhere/app.mjs: every tap opens a code card,
         on a line, a route or empty ground; the line panel stays for FLY and links */
      $('panel').hidden = true; view.focus = -1; view.link = null; draw();
      cardTap(e.clientX, e.clientY);
    }
    pts.delete(e.pointerId);
    if (pts.size < 2) pinch = null;
    if (pts.size === 0) { down = null; wasPinch = false; }
  };
  stage.addEventListener('pointerup', up);
  stage.addEventListener('pointercancel', e => { pts.delete(e.pointerId); pinch = null; down = null; if (pts.size === 0) wasPinch = false; });
  stage.addEventListener('wheel', e => {
    e.preventDefault();
    const f = Math.exp(-e.deltaY * 0.0016);
    view.zoom = Math.max(0.02, Math.min(4000, view.zoom * f));
    motion(); draw();
  }, { passive: false });
  stage.addEventListener('dblclick', () => { view.focus = -1; view.link = null; $('panel').hidden = true; home(); });
}

/* ── the code card ───────────────────────────────────────────────────────────
 *
 * Lifted from iterations/31-code-card-everywhere/card.mjs; its description
 * follows. Differences here: it reads U and draw() directly instead of through
 * bindWafer(); a card waiting on the family index is resumed by tier2(); the
 * tile band on empty ground comes from the layers panel's tile rule; a point
 * hit also lists that feature's properties; and the tap's click is swallowed on
 * anything that is not the wafer.
 *
 * Any tap on the wafer opens a card:
 *   on a line   — its key, the exact text of that line inside the function that
 *                 contains it, read from the file at the commit the numbered
 *                 database pins, with its family, block and app;
 *   on a route  — the module the route draws, its first and last line, its stops;
 *   on nothing  — the nearest issued line and the radius band the point sits in,
 *                 both computed from the placement law r = sqrt(key).
 *
 * Reused, not reinvented:
 *   iteration 03 (code-particle.mjs): the block register, a fetch queue, reading
 *     a file from raw.githubusercontent at its pinned commit, one writer for the
 *     WAIT / LOAD / OK / EMPTY / FAIL tag, and fetched text reaching the page only
 *     through textContent.
 *   iteration 07 (code-card.mjs): the Grid Atlas popup look — black ground, #444
 *     edge, monospace, an amber title, grey detail, the bordered cyan button.
 *
 * Where a line sits in its file. The modular star publishes one record per
 * function family (stars/code/f/<n div 500>.json). Each record lists the family's
 * permanent line keys in file order and every place the family lives
 * (repository, commit, path, first and last line). A key at position j of the
 * record is file line first + j. The page then checks the text it finds there
 * against the character count the numbered database holds for that key, and says
 * whether they agree.
 *
 * Changing a digit. Tap a line in the code window and each digit run on it is
 * an input. Edits exist
 * only in this page's memory: nothing is written to any repository, nothing is
 * stored in the browser. For a ventus-grid-engine module the page can run the
 * module twice in a Web Worker built from a Blob — once as published at the
 * commit the estate imports, once with the edit — calling one documented
 * function with the input its own proof uses first, and shows both answers.
 *
 * Loading, as Grid Atlas loads: nothing is fetched until a card opens; one
 * queue runs at most two fetches at once, each aborted after 15 s; one promise
 * per URL is shared, and a failed fetch leaves the cache so a retry can happen;
 * at most eight source files and four family buckets are held, the least
 * recently used evicted first. The card is one element, re-filled on every tap:
 * the code window is one text node however long the function, and only the one
 * selected line becomes editable fields.
 */


const STARS = 'https://ventusltd.github.io/stars/';
const REGISTER = STARS + 'blocks/blocks.json';
const RAW = 'https://raw.githubusercontent.com/';
const ENGINE_REPO = 'Ventusltd/ventus-grid-engine';
const PIN = 'd9cd18b0e2034325814924e6e4a0e958014f2748';   /* the engine commit the estate imports */
const BUCKET = 500;            /* stars/code/index.json bucket_size; checked when the index is read */
const WINDOW_MAX = 160;        /* lines shown when a function is longer than this */
const RUN_MS = 2000;
const FETCH_MS = 15000;        /* Grid Atlas: every fetch has a 15 s AbortController timeout */
const MAX_FIELDS = 40;         /* digit fields on one selected line */
const REACH = 22;              /* px: the wafer's own tap reach, as the root's nearestKeyAt had it */
const DISCLAIMER = 'Illustrative physics drawn by a computer from published data. Not an engineering design or certified calculation. Any real design above 100 kW needs study and approval by a qualified chartered electrical engineer under the applicable standards.';

/* The first input each engine module's own proof calls it with. `evidence` must
   appear, whitespace collapsed, in the proof file at PIN or the run is refused. */
const FIXTURES = {
  'engine/voltage-drop.js': {
    fn: 'voltageDropVolts',
    input: { currentA: 200, lengthM: 250, resistanceOhmPerKm: 0.1, reactanceOhmPerKm: 0.08, powerFactor: 0.9, phases: 'three' },
    proof: 'proofs/voltage-drop.proof.mjs',
    evidence: "currentA: 200, lengthM: 250, resistanceOhmPerKm: 0.1, reactanceOhmPerKm: 0.08, powerFactor: 0.9, phases: 'three'"
  },
  'engine/current-from-power.js': {
    fn: 'currentFromMvaAtKv',
    input: { mva: 1200, kv: 400 },
    proof: 'proofs/current-from-power.proof.mjs',
    evidence: 'currentFromMvaAtKv({ mva: 1200, kv: 400 })'
  }
};

/* Which single-line-diagram element an engine module feeds, and through which
   function. The function must exist in the fetched source or the answer is
   withheld; the field it returns (quantity, unit) is read from that source. */
const SLD = {
  'engine/voltage-drop.js': { element: 'cable route (the feeder cable between two busbars)', fn: 'voltageDropVolts' },
  'engine/current-from-power.js': { element: 'feeder (the current a circuit rating implies)', fn: 'currentFromMvaAtKv' },
  'engine/firm-capacity.js': { element: 'transformer (firm capacity of a substation\'s units)', fn: 'firmCapacityMva' },
  'engine/power-factor.js': { element: 'feeder (reactive power and its correction)', fn: 'correctionKvar' },
  'engine/route-obstacles.js': { element: 'cable route (length with crossings)', fn: 'routeEstimate' },
  'engine/published-fault-level.js': { element: 'protection (a published fault level at a busbar)', fn: 'quote' }
};

/* ── fetching: one queue of two, bounded caches ─────────────────────────────── */

class Queue {
  constructor(n) { this.n = n; this.active = 0; this.waiting = []; }
  async add(task, onWait) {
    if (this.active >= this.n) { onWait?.(); await new Promise(r => this.waiting.push(r)); }
    this.active++;
    try { return await task(); }
    finally { this.active--; this.waiting.shift()?.(); }
  }
}
class LRU {
  constructor(n) { this.n = n; this.m = new Map(); }
  get(k) { const v = this.m.get(k); if (v !== undefined) { this.m.delete(k); this.m.set(k, v); } return v; }
  set(k, v) { this.m.delete(k); this.m.set(k, v); while (this.m.size > this.n) this.m.delete(this.m.keys().next().value); }
  delete(k) { this.m.delete(k); }
  get size() { return this.m.size; }
}
const queue = new Queue(2);
const sources = new LRU(8);
const buckets = new LRU(4);
const once = new Map();
let fetchCount = 0;

function cached(cache, url, parse, onWait) {
  let p = cache.get(url);
  if (!p) {
    p = queue.add(async () => {
      fetchCount++;
      const ac = new AbortController();
      const t = setTimeout(() => ac.abort(), FETCH_MS);
      try {
        const r = await fetch(url, { signal: ac.signal });
        if (!r.ok) throw new Error(url + ' returned HTTP ' + r.status);
        return await (parse === 'json' ? r.json() : r.text());
      } catch (e) {
        throw e.name === 'AbortError' ? new Error(url + ` gave no answer within ${FETCH_MS / 1000} s`) : e;
      } finally { clearTimeout(t); }
    }, onWait);
    p.catch(() => cache.delete(url));
    cache.set(url, p);
  }
  return p;
}
const onceMap = { get: k => once.get(k), set: (k, v) => once.set(k, v), delete: k => once.delete(k) };
const rawURL = (repo, commit, path) => `${RAW}${repo}/${commit}/${path}`;
const ghURL = (repo, commit, path, a, b) => `https://github.com/${repo}/blob/${commit}/${path}` + (a ? `#L${a}` + (b && b !== a ? `-L${b}` : '') : '');

function register() {
  return cached(onceMap, REGISTER, 'json').then(j => {
    if (!j._bySymbol) {
      const m = new Map();
      for (const b of j.blocks || []) if (!m.has(b.symbol)) m.set(b.symbol, b);
      Object.defineProperty(j, '_bySymbol', { value: m });
    }
    return j._bySymbol;
  });
}
async function familyRecord(n, onWait) {
  const idx = await cached(onceMap, STARS + 'code/index.json', 'json', onWait);
  const size = idx.bucket_size ?? BUCKET;
  const b = Math.floor(n / size);
  if (Array.isArray(idx.buckets) && !idx.buckets.includes(b)) return { missing: `bucket ${b} is not listed in stars/code/index.json` };
  const j = await cached(buckets, `${STARS}code/f/${b}.json`, 'json', onWait);
  const rec = j[String(n)];
  return rec ? { rec, bucket: b } : { missing: `family #${n} is not in bucket ${b}` };
}
const readSource = (repo, commit, path, onWait) => cached(sources, rawURL(repo, commit, path), 'text', onWait)
  .then(t => t.split('\n').map(l => l.replace(/\r$/, '')));

/* ── DOM helpers: fetched text only ever meets textContent ─────────────────── */

const el = (tag, cls, text) => {
  const e = document.createElement(tag);
  if (cls) e.className = cls;
  if (text != null) e.textContent = String(text);
  return e;
};
const link = (href, text) => { const a = el('a', 'cc-link', text); a.href = href; a.target = '_blank'; a.rel = 'noopener noreferrer'; return a; };
const row = (dl, k, ...v) => { dl.append(el('dt', null, k)); const dd = el('dd'); dd.append(...v.map(x => typeof x === 'string' ? document.createTextNode(x) : x)); dl.append(dd); return dd; };
const btn = (text, cls, on) => { const b = el('button', cls || 'popup-btn', text); b.type = 'button'; b.addEventListener('click', on); return b; };

let token = 0;         /* the card belongs to the latest open only */
let mark = null;       /* {kind:'key', key} | {kind:'point', x, y, key} | {kind:'route', keys} */
let waitingKey = -1;

/* the card's mark follows the camera like any layer (registered where markCanvas is made, below) */

/* ── the sheet ─────────────────────────────────────────────────────────────── */

function sheet(title, sub) {
  const mine = ++token;
  const card = $('card');
  card.replaceChildren();
  card.hidden = false;
  card.scrollTop = 0;
  const x = btn('×', 'cc-x', closeCard); x.setAttribute('aria-label', 'close');
  const t = el('span', 'cc-title', title);
  card.append(x, t);
  if (sub) card.append(el('span', 'cc-grey', sub));
  const tagLine = el('div', 'cc-tagline');
  const tag = el('span', 'cc-tag'), msg = el('span', 'cc-grey');
  tagLine.append(tag, msg);
  card.append(tagLine);
  const body = el('div', 'cc-body');
  card.append(body);
  const setTag = (s, text) => {                 /* the single writer of the state */
    if (mine !== token) return false;
    tag.dataset.s = s; tag.textContent = s;
    if (text != null) msg.textContent = text;
    return true;
  };
  return { mine, card, body, setTag, live: () => mine === token };
}

function closeCard() { token++; $('card').hidden = true; $('card').replaceChildren(); mark = null; waitingKey = -1; draw(); }
document.addEventListener('keydown', e => { if (e.key === 'Escape' && !$('card').hidden) closeCard(); });

/* A card opening under a finger must not take that same tap's click. Widened
   from card.mjs (which guarded #card only) to anything that is not the wafer:
   the defect noted in iterations/21-dark-pixels/layers-panel.mjs was the same
   click landing on a layers checkbox that had just appeared under the finger. */
let swallowUntil = 0;
document.addEventListener('click', e => {
  if (performance.now() < swallowUntil && e.target instanceof Element && e.target.id !== 'stage') { e.preventDefault(); e.stopPropagation(); }
  swallowUntil = 0;
}, true);

/* ── the tap ───────────────────────────────────────────────────────────────── */

function cardTap(cx, cy) {
  if (!U.pos) return;
  swallowUntil = performance.now() + 450;
  const hit = window.__layers?.pickAt?.(cx, cy);
  if (hit?.feature?.geometry?.type === 'LineString') {
    /* on one of the route's own stops: that line's card; on the stroke between stops: the route's */
    const v = window.__wafer.view, fam = hit.feature.properties?.family;
    let stop = -1, bestD = 14 * 14;
    for (const k of hit.feature.geometry.keys) {
      const [x, y] = place(k), dx = (x - v.x) * v.zoom + v.w / 2 - cx, dy = v.h / 2 - (y - v.y) * v.zoom - cy, d = dx * dx + dy * dy;
      if (d < bestD) { bestD = d; stop = k; }
    }
    if (stop > 0) return openLine(stop, { layer: hit.layer, family: fam });
    return openRoute(hit.layer, hit.feature);
  }
  if (hit?.feature?.geometry?.type === 'Point') return openLine(hit.feature.geometry.key, { layer: hit.layer, props: hit.feature.properties });
  const v = window.__wafer.view;
  const wx = (cx - v.w / 2) / v.zoom + v.x, wy = (v.h / 2 - cy) / v.zoom + v.y;
  const near = nearestIssued(wx, wy);
  if (near && near.d * v.zoom <= REACH) return openLine(near.key);
  return openArea(wx, wy, near, v.zoom);
}

function nearestIssued(wx, wy) {
  const { pos, keys, n } = U;
  let best = -1, bestD = Infinity;
  for (let i = 0; i < n; i++) {
    const dx = pos[i * 2] - wx, dy = pos[i * 2 + 1] - wy, d = dx * dx + dy * dy;
    if (d < bestD) { bestD = d; best = i; }
  }
  return best < 0 ? null : { key: keys[best], d: Math.sqrt(bestD) };
}
const issuedIn = (a, b) => lowerBound(U.keys, b) - lowerBound(U.keys, a);   /* keys in [a, b) */

/* ── marks on the wafer ─────────────────────────────────────────────────────── */

const markCanvas = document.createElement('canvas');
markCanvas.style.cssText = 'position:fixed;inset:0;width:100%;height:100%;pointer-events:none;z-index:2';
document.body.appendChild(markCanvas);
const mctx = markCanvas.getContext('2d');
window.__wafer.onDraw.add(drawMark);
let drawnMark = false;

function drawMark(v) {
  if (!mark && !drawnMark) return;
  const dpr = v.dpr || 1, Wd = Math.round(v.w * dpr), H = Math.round(v.h * dpr);
  if (markCanvas.width !== Wd || markCanvas.height !== H) { markCanvas.width = Wd; markCanvas.height = H; }
  mctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  mctx.clearRect(0, 0, v.w, v.h);
  drawnMark = !!mark;
  if (!mark) return;
  const S = ([x, y]) => [(x - v.x) * v.zoom + v.w / 2, v.h / 2 - (y - v.y) * v.zoom];
  mctx.lineWidth = 1.6; mctx.strokeStyle = '#00ffff';
  if (mark.kind === 'route') {
    mctx.beginPath();
    mark.keys.forEach((k, i) => { const [x, y] = S(place(k)); i ? mctx.lineTo(x, y) : mctx.moveTo(x, y); });
    mctx.setLineDash([6, 4]); mctx.stroke(); mctx.setLineDash([]);
    for (const k of [mark.keys[0], mark.keys[mark.keys.length - 1]]) { const [x, y] = S(place(k)); mctx.beginPath(); mctx.arc(x, y, 10, 0, 6.2832); mctx.stroke(); }
    return;
  }
  if (mark.kind === 'point') {
    const [px, py] = S([mark.x, mark.y]);
    mctx.beginPath(); mctx.moveTo(px - 8, py); mctx.lineTo(px + 8, py); mctx.moveTo(px, py - 8); mctx.lineTo(px, py + 8); mctx.stroke();
    if (mark.key > 0) {
      const [kx, ky] = S(place(mark.key));
      mctx.setLineDash([3, 3]); mctx.beginPath(); mctx.moveTo(px, py); mctx.lineTo(kx, ky); mctx.stroke(); mctx.setLineDash([]);
      mctx.beginPath(); mctx.arc(kx, ky, 9, 0, 6.2832); mctx.stroke();
    }
    return;
  }
  const [x, y] = S(place(mark.key));
  mctx.strokeStyle = '#ffd54a';
  mctx.beginPath(); mctx.arc(x, y, 11, 0, 6.2832); mctx.stroke();
}

/* ── a line ────────────────────────────────────────────────────────────────── */

async function openLine(key, opts = {}) {
  mark = { kind: 'key', key }; draw();
  const i = findKey(U.keys, key);
  const chars = i >= 0 ? U.lens[i] : null;
  const { body, setTag, live } = sheet('Line ' + fmt(key),
    i < 0 ? ' number never issued' : ' ' + (chars === 65535 ? 'at least 65,535 characters' : fmt(chars) + (chars === 1 ? ' character' : ' characters')));
  if (opts.layer) { const s = el('div', 'cc-small', 'tapped on the layer ' + opts.layer.label); body.append(s); }
  if (opts.props && Object.keys(opts.props).length) {
    /* root promotion: the layer feature's own properties, which the root's inspect box used to show */
    const pd = el('dl', 'cc-dl');
    for (const [k, v] of Object.entries(opts.props)) row(pd, k, v !== null && typeof v === 'object' ? JSON.stringify(v) : String(v));
    body.append(pd);
  }
  const q = { sld: null, use: null, next: null, machine: null };

  if (i < 0) {
    setTag('EMPTY', `This number was never issued (the numbering runs 1 to ${fmt(U.meta.max)}), so no file holds a line with this key.`);
    return questions(body, { sld: 'none yet: no line has this key.', use: 'nothing: the key was never issued.', next: 'not established: there is no line to follow.', machine: `input: key ${key} · output: none · source: numbered database ${U.meta.built_utc}` });
  }
  if (!U.ownerOf) {
    waitingKey = key;
    setTag('WAIT', 'the family index is still loading; this card fills in when it lands');
    return;
  }
  waitingKey = -1;
  const famIdx = U.ownerOf.get(key) || [];
  if (!famIdx.length) {
    setTag('EMPTY', 'No function family carries this line, so the numbered database records no file and commit for it and its text cannot be read from a pinned place.');
    return questions(body, {
      sld: 'none yet: the line belongs to no function family.',
      use: 'not established: no family, block or file is recorded for this line.',
      next: 'not established: with no family there is no recorded use or dependency.',
      machine: `input: key ${key} · output: none · ${fmt(chars)} characters in the numbered database (built ${U.meta.built_utc})`
    });
  }
  const fams = famIdx.map(f => U.families[f]);
  let chosen = opts.family != null ? fams.find(f => f.n === opts.family) : null;
  chosen ||= fams.find(f => f.block) || fams[0];

  /* family chooser */
  const famRow = el('div', 'cc-row');
  famRow.append(el('span', 'cc-grey', `${fmt(fams.length)} ${fams.length === 1 ? 'family carries' : 'families carry'} it · `));
  if (fams.length > 1) {
    const sel = el('select', 'cc-select'); sel.setAttribute('aria-label', 'family');
    for (const f of fams.slice(0, 60)) { const o = el('option', null, `#${f.n} ${f.name}${f.block ? ' · ' + f.block : ''}`); o.value = f.n; if (f === chosen) o.selected = true; sel.append(o); }
    sel.addEventListener('change', () => openLine(key, { ...opts, family: Number(sel.value), place: 0 }));
    famRow.append(sel);
    if (fams.length > 60) famRow.append(el('span', 'cc-small', ` first 60 of ${fmt(fams.length)}`));
  } else famRow.append(el('span', 'cc-amber', `#${chosen.n} ${chosen.name}`));
  body.append(famRow);

  const onWait = () => setTag('WAIT', 'queued behind other fetches (two at a time)…');
  setTag('LOAD', `reading family #${chosen.n}'s record from the modular star…`);
  let fr, reg = null;
  try { [fr, reg] = await Promise.all([familyRecord(chosen.n, onWait), register().catch(() => null)]); }
  catch (e) { setTag('FAIL', 'Could not read the family record: ' + e.message); return; }
  if (!live()) return;
  if (fr.missing) { setTag('EMPTY', 'No place is recorded: ' + fr.missing + '.'); return; }
  const rec = fr.rec;
  const block = chosen.block && reg ? reg.get(chosen.block) : null;
  const places = rec.places || [];
  if (!places.length) { setTag('EMPTY', `Family #${chosen.n} records no place in any file.`); return; }
  const pi = Math.min(opts.place ?? 0, places.length - 1);
  const pl = places[pi];
  const at = [];
  rec.lines.forEach((k, j) => { if (k === key) at.push(j); });

  const meta = el('dl', 'cc-dl');
  row(meta, 'family', `#${chosen.n} ${(rec.names || [chosen.name]).join(', ')} · ${chosen.kind}${chosen.category ? ' · ' + chosen.category : ''}`);
  row(meta, 'block', chosen.block ? `${chosen.block}${block ? ' · ' + block.title : ' · not found in the live register'}` : 'none: no block in the register names this family');
  const app = row(meta, 'app', pl.repo);
  if (pl.live) { app.append(' · '); app.append(link(pl.live, 'live page')); }
  if (places.length > 1) {
    const sel = el('select', 'cc-select'); sel.setAttribute('aria-label', 'place');
    places.slice(0, 40).forEach((p, j) => { const o = el('option', null, `${j + 1}. ${p.repo.split('/')[1]} · ${p.path}`); o.value = j; if (j === pi) o.selected = true; sel.append(o); });
    sel.addEventListener('change', () => openLine(key, { ...opts, family: chosen.n, place: Number(sel.value) }));
    row(meta, 'place', sel, places.length > 40 ? ` first 40 of ${places.length}` : ` ${places.length} places`);
  }
  body.append(meta);

  if (!at.length) {
    setTag('EMPTY', `Family #${chosen.n}'s record does not list line ${key} among its ${rec.lines.length} lines, although the family pack says it carries it. That disagreement is shown, not smoothed over.`);
    return;
  }
  const fileLine = pl.first + at[0];
  setTag('LOAD', `fetching ${pl.path} at ${pl.commit.slice(0, 7)}…`);
  let lines;
  try { lines = await readSource(pl.repo, pl.commit, pl.path, onWait); }
  catch (e) { setTag('FAIL', 'Could not read the source: ' + e.message); return; }
  if (!live()) return;
  if (pl.last > lines.length) { setTag('FAIL', `The place record says lines ${pl.first}–${pl.last}, but the file at ${pl.commit.slice(0, 7)} has ${lines.length} lines.`); return; }

  const text = lines[fileLine - 1];
  const agree = chars === 65535 ? null : text.length === chars;
  let a = pl.first, b = pl.last;
  if (b - a + 1 > WINDOW_MAX) { a = Math.max(pl.first, fileLine - WINDOW_MAX / 2); b = Math.min(pl.last, a + WINDOW_MAX - 1); }

  const head = el('div', 'cc-codehead');
  head.append(`${pl.path} · ${pl.repo} @ ${pl.commit.slice(0, 7)} · line ${fileLine}` +
    (at.length > 1 ? ` (also at ${at.slice(1, 6).map(j => pl.first + j).join(', ')})` : '') +
    ` · function lines ${pl.first}–${pl.last}${a !== pl.first || b !== pl.last ? `, showing ${a}–${b}` : ''} · `);
  head.append(link(ghURL(pl.repo, pl.commit, pl.path, pl.first, pl.last), 'file at this commit on GitHub'));
  body.append(head);
  body.append(el('div', 'cc-check', agree === null
    ? `This line reaches the database's 16-bit length ceiling, so its length cannot confirm the match.`
    : agree ? `The text at line ${fileLine} is ${fmt(text.length)} characters, the length the numbered database holds for key ${key}.`
            : `Not confirmed: line ${fileLine} is ${fmt(text.length)} characters but the numbered database holds ${fmt(chars)} for key ${key}. Shown as read.`));

  const editor = codeWindow(lines, a, b, fileLine);
  body.append(editor.node);
  setTag('OK', `family #${chosen.n}, place ${pi + 1} of ${places.length}, at the commit the modular star pins`);
  requestAnimationFrame(() => editor.scrollToTarget());

  const engineModule = pl.repo === ENGINE_REPO && /^engine\/[A-Za-z0-9._-]+\.js$/.test(pl.path) ? pl.path : null;