GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / cosmic / tools/explore/visual

Explore — Visual

A JavaScript file in the tools folder of Cosmic that builds wafer and grid, fits cam, calculates planar distances and draws on a canvas, using SHA-256 and Louvain.

700 lines of JavaScript from cosmic, in 1 file. Topic: Kuiper, cosmos and drawing engines. Section 1171 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. Explore — Visual render · cosmic / tools/explore/visual/app.js lines 1–700

Explore — Visual

A JavaScript file in the tools folder of Cosmic that builds wafer and grid, fits cam, calculates planar distances and draws on a canvas, using SHA-256 and Louvain.

rendercosmic / tools/explore/visual/app.js · lines 1–700 of 971 · Not reached from any entry point (candidate for review) · pattern renderLegend (shared by 2 files)

What it does
It draws its content. Defines 83 functions or classes, including $, narrow, mapLike, esc, path. Side effects: changes the web page (DOM); makes network requests.
Inputs & outputs
In: JSON file graph.json. Out: canvas drawing.
What it achieves
It maps like (`mapLike`), builds wafer (`buildWafer`) and builds grid (`buildGrid`). Explore Code visualiser. Vanilla canvas; reads `graph.json` (coordinates precomputed by `visualise.py`). It responds to resize, hashchange and input events.
Why it matters
No other file in the estate was found to import it.
Application
cosmic · tools/explore/visual · script
Uses
none found
Used by
none found
Produces
$, narrow, mapLike, esc, path, title, human, repoName, secUrl, isOv, cat, catColour
Defines here
$, narrow, mapLike, esc, path, title, human, repoName, secUrl, isOv, cat, catColour, catTitle, colour, shown, lit, load, progress, init, ensureOv, prepOv, sha256word0, ro, hexCell, buildWafer, buildGrid, cam, fitCam, freeArea, fitTo
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/visual/app.js:1-700 · blob 613252f7083767a8e4ab2b0da34e537da8b7d10e · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: unreached_review
/* Explore Code visualiser. Vanilla canvas; reads graph.json (coordinates precomputed by visualise.py). */
(function () {
  'use strict';
  document.documentElement.className += ' js';
  var $ = function (id) { return document.getElementById(id); };
  var cv = $('cv'), ctx = cv.getContext('2d'), stageEl = $('stage'), tip = $('tip'), info = $('info');
  var flowEl = $('flow'), legend = $('legend'), q = $('q'), sug = $('sug'), toastEl = $('toast');
  var D = null, N = 0, P = null, uses = [], usedBy = [], gridIx = {}, dpr = 1, W = 0, H = 0;
  var V = { view: 'pipeline', colour: 'role', topic: -1, repo: -1, sel: -1, hov: -1, edges: false,
            reach: false, only: false, hidden: {}, q: '', cell: null, drift: false, safe: false, pulse: false };
  var cams = {}, matchSet = null, dirty = false, lower = null, sugItems = [], sugOn = 0, lastHash = '';
  var BASE_MODES = ['role', 'topic', 'stage', 'pattern'], OV_MODES = ['community', 'clarity', 'periodic', 'laws'];
  var MODES = BASE_MODES.slice(), VIEWS = ['pipeline', 'map', 'flow'];
  var OV = {}, ovWait = {}, WL = null; // loaded overlays (lazy), wafer layout
  var narrow = function () { return window.matchMedia ? window.matchMedia('(max-width:760px)').matches : window.innerWidth <= 760; };
  var mapLike = function (v) { return v === 'map' || v === 'wafer'; };
  var SEL = '#0066ff', ACC = '#00ffff', LINE = '#2f343d', PANEL = '#0b0e14', DIM = '#161a20';

  function esc(s) { return String(s).replace(/[&<>"']/g, function (c) { return '&#' + c.charCodeAt(0) + ';'; }); }
  function path(i) { var d = D.dirs[P.d[i]]; return d ? d + '/' + P.b[i] : P.b[i]; }
  function title(i) { return P.ti[i] || human(P.b[i]); }
  function human(b) {
    var s = b.replace(/\.[^.]+$/, '').replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').trim();
    return s ? s.charAt(0).toUpperCase() + s.slice(1) : b;
  }
  function repoName(i) { return D.repos[P.r[i]][0]; }
  function secUrl(i) {
    var s = String(P.sec[i]); while (s.length < D.sw) s = '0' + s;
    return '../s/' + s + '.html#f' + P.blk[i];
  }

  // ------------------------------------------------------------ colour
  function isOv(mode) { return OV_MODES.indexOf(mode) >= 0; }
  function cat(i, mode) {
    mode = mode || V.colour;
    if (mode === 'role') return P.o[i];
    if (mode === 'topic') return P.t[i];
    if (mode === 'stage') return P.s[i];
    if (isOv(mode)) return OV[mode] ? OV[mode].c[i] : -1;
    return P.p[i];
  }
  function catColour(c, mode) {
    mode = mode || V.colour;
    if (mode === 'role') return D.roles[c][2];
    if (mode === 'topic') return D.topics[c][3];
    if (mode === 'stage') return D.stages[c][2];
    if (isOv(mode)) return OV[mode] && c >= 0 ? OV[mode].cats[c][1] : D.grey;
    return c >= 0 ? D.pats[c][1] : D.grey;
  }
  function catTitle(c, mode) {
    mode = mode || V.colour;
    if (mode === 'role') return D.roles[c][1];
    if (mode === 'topic') return D.topics[c][1];
    if (mode === 'stage') return D.stages[c][1];
    if (isOv(mode)) return OV[mode] && c >= 0 ? OV[mode].cats[c][0] : (mode === 'community' ? 'no community (no resolved references)' : 'no value');
    return c >= 0 ? D.pats[c][0] : 'unique (no shared pattern)';
  }
  function colour(i) { return catColour(cat(i)); }
  function shown(i) { // passes filters
    if (V.topic >= 0 && P.t[i] !== V.topic) return false;
    if (V.repo >= 0 && P.r[i] !== V.repo) return false;
    if (V.hidden[cat(i)]) return false;
    if (V.only && P.re[i] !== 0) return false;
    if (V.safe && !(OV.drift && OV.drift.safeSet[i])) return false;
    return true;
  }
  function lit(i) { return shown(i) && (!matchSet || matchSet[i]); }

  // ------------------------------------------------------------ load
  function load() {
    var box = $('load'), total = +box.getAttribute('data-bytes') || 0;
    function progress(got) {
      var pc = total ? Math.min(100, Math.round(got * 100 / total)) : 0;
      $('loadbar').style.width = pc + '%'; box.setAttribute('aria-valuenow', pc);
      $('loadtxt').textContent = 'Loading map: ' + (got / 1048576).toFixed(1) + ' of ' + (total / 1048576).toFixed(1) + ' MB (' + pc + '%)';
    }
    fetch('graph.json').then(function (r) {
      if (!r.ok) throw new Error(r.status);
      if (!r.body || !r.body.getReader || !window.TextDecoder) return r.json();
      var rd = r.body.getReader(), parts = [], got = 0;
      return (function pump() {
        return rd.read().then(function (x) {
          if (x.done) {
            var all = new Uint8Array(got), o = 0;
            parts.forEach(function (p) { all.set(p, o); o += p.length; });
            return JSON.parse(new TextDecoder('utf-8').decode(all));
          }
          parts.push(x.value); got += x.value.length; progress(got); return pump();
        });
      })();
    }).then(init).catch(function (e) {
      box.hidden = true;
      $('status').textContent = 'Could not load graph.json (' + e.message + '). Serve this folder over http, or use the plain list below.';
      document.documentElement.className = document.documentElement.className.replace(' js', '');
    });
  }
  function init(data) {
    D = data; P = D.n; N = P.r.length; D.ov = D.ov || {};
    for (var i = 0; i < N; i++) { uses.push([]); usedBy.push([]); }
    for (var k = 0; k < D.e.length; k += 2) { uses[D.e[k]].push(D.e[k + 1]); usedBy[D.e[k + 1]].push(D.e[k]); }
    buildGrid('pipeline', P.px, P.py, 22); buildGrid('map', P.mx, P.my, 10);
    OV_MODES.forEach(function (m) { if (D.ov[m]) MODES.push(m); });
    if (D.ov.wafer) VIEWS.push('wafer');
    var ft = $('ftopic'), fr = $('frepo');
    D.topics.forEach(function (t) { ft.add(new Option(t[1] || 'no topic', t[0])); });
    D.repos.slice().sort(function (a, b) { return a[0].toLowerCase() < b[0].toLowerCase() ? -1 : 1; })
      .forEach(function (r) { fr.add(new Option(r[0] + ' (' + r[3] + ')', r[0])); });
    $('load').hidden = true;
    $('status').textContent = N + ' files · ' + D.repos.length + ' repos · ' + (D.e.length / 2) + ' imports · cut ' + D.cut;
    bind(); readHash(); setLegend(!narrow()); resize(); applyAll(true); lastHash = location.hash;
    if (!location.hash || location.hash === '#') writeHash();
  }

  // ------------------------------------------------------------ lazy overlays (ov-<name>.json, id -> value)
  function ensureOv(name, cb) {
    if (OV[name]) { if (cb) cb(); return; }
    if (!D.ov[name]) return;
    if (ovWait[name]) { if (cb) ovWait[name].push(cb); return; }
    ovWait[name] = cb ? [cb] : [];
    toast('Loading ' + name + ' (' + Math.max(1, Math.round(D.ov[name] / 1024)) + ' KB)…', 0);
    fetch('ov-' + name + '.json').then(function (r) { if (!r.ok) throw new Error(r.status); return r.json(); })
      .then(function (d) {
        prepOv(name, d); OV[name] = d; toast('');
        var w = ovWait[name]; delete ovWait[name]; w.forEach(function (f) { f(); });
      }).catch(function (e) { delete ovWait[name]; toast('Could not load ' + name + ' (' + e.message + ')', 4000); });
  }
  function prepOv(name, d) {
    if (name === 'periodic') {
      var pix = {}; d.cats.forEach(function (c, k) { pix[c[2]] = k; });
      d.c = d.v.map(function (e) { return e < 0 ? -1 : pix[d.els[e][3]]; });
    } else if (name === 'drift') {
      d.safeSet = new Uint8Array(N); d.safe.forEach(function (i) { d.safeSet[i] = 1; });
      d.canon = {}; for (var k = 0; k < d.e.length; k += 3) d.canon[d.e[k]] = [d.e[k + 1], d.e[k + 2]];
    } else if (name === 'wafer') { buildWafer(d); }
    else d.c = d.v;
  }

  // ------------------------------------------------------------ wafer: positions from permanent keys
  // Same law as tools/explore/lab/wafer.py wafer_dies(): u = first 32 bits of sha256("repo/path"),
  // die per repo on a hex spiral by its permanent number, r = rad*sqrt(u/2^32), theta = 2pi frac(u*phi32/2^32).
  var SHA_K = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
    0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
    0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
    0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];
  function sha256word0(str) { // first 32 bits of SHA-256 of the UTF-8 bytes of str
    var b = unescape(encodeURIComponent(str)), n = b.length, L = ((n + 9 + 63) >> 6) << 4, m = new Array(L), i;
    for (i = 0; i < L; i++) m[i] = 0;
    for (i = 0; i < n; i++) m[i >> 2] |= b.charCodeAt(i) << (24 - (i & 3) * 8);
    m[n >> 2] |= 0x80 << (24 - (n & 3) * 8); m[L - 1] = n * 8;
    var h = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19], w = new Array(64);
    function ro(x, k) { return (x >>> k) | (x << (32 - k)); }
    for (var o = 0; o < L; o += 16) {
      var a = h[0], bb = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7];
      for (i = 0; i < 64; i++) {
        if (i < 16) w[i] = m[o + i] | 0;
        else {
          var s0 = ro(w[i - 15], 7) ^ ro(w[i - 15], 18) ^ (w[i - 15] >>> 3), s1 = ro(w[i - 2], 17) ^ ro(w[i - 2], 19) ^ (w[i - 2] >>> 10);
          w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0;
        }
        var t1 = (hh + (ro(e, 6) ^ ro(e, 11) ^ ro(e, 25)) + ((e & f) ^ (~e & g)) + SHA_K[i] + w[i]) | 0;
        var t2 = ((ro(a, 2) ^ ro(a, 13) ^ ro(a, 22)) + ((a & bb) ^ (a & c) ^ (bb & c))) | 0;
        hh = g; g = f; f = e; e = (d + t1) | 0; d = c; c = bb; bb = a; a = (t1 + t2) | 0;
      }
      h[0] = (h[0] + a) | 0; h[1] = (h[1] + bb) | 0; h[2] = (h[2] + c) | 0; h[3] = (h[3] + d) | 0;
      h[4] = (h[4] + e) | 0; h[5] = (h[5] + f) | 0; h[6] = (h[6] + g) | 0; h[7] = (h[7] + hh) | 0;
    }
    return h[0] >>> 0;
  }
  function hexCell(i) {
    if (i === 0) return [0, 0];
    var ring = 1; while (1 + 3 * ring * (ring + 1) <= i) ring++;
    var j = i - (1 + 3 * ring * (ring - 1)), side = Math.floor(j / ring), off = j % ring;
    var dirs = [[1, 0], [1, -1], [0, -1], [-1, 0], [-1, 1], [0, 1]], qq = dirs[4][0] * ring, rr = dirs[4][1] * ring;
    for (var s = 0; s < side; s++) { qq += dirs[s][0] * ring; rr += dirs[s][1] * ring; }
    qq += dirs[side][0] * off; rr += dirs[side][1] * off;
    return [qq + rr / 2, rr * Math.sqrt(3) / 2];
  }
  function buildWafer(d) {
    var S = 1000, PHI32 = 2654435769, cnt = {}, i, r;
    for (i = 0; i < N; i++) cnt[P.r[i]] = (cnt[P.r[i]] || 0) + 1;
    var cap = {}, maxcap = 1;
    Object.keys(cnt).forEach(function (k) { var c = 1; while (c < cnt[k]) c *= 2; cap[k] = c; if (c > maxcap) maxcap = c; });
    var dies = {}, x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9;
    Object.keys(cnt).forEach(function (k) {
      var num = d.numbers[D.repos[k][0]], hc = hexCell(num), rad = Math.max(0.14, 0.49 * Math.sqrt(cap[k] / maxcap));
      dies[k] = [hc[0], hc[1], rad];
      x0 = Math.min(x0, hc[0] - rad); x1 = Math.max(x1, hc[0] + rad); y0 = Math.min(y0, hc[1] - rad); y1 = Math.max(y1, hc[1] + rad);
    });
    var M = 0.2, xs = new Float64Array(N), ys = new Float64Array(N), raw = new Float64Array(2 * N);
    for (i = 0; i < N; i++) {
      var dd = dies[P.r[i]], u = sha256word0(repoName(i) + '/' + path(i));
      r = dd[2] * Math.sqrt(u / 4294967296);
      var th = 2 * Math.PI * (Math.imul(u, PHI32) >>> 0) / 4294967296;
      raw[2 * i] = dd[0] + r * Math.cos(th); raw[2 * i + 1] = dd[1] + r * Math.sin(th);
      xs[i] = (raw[2 * i] - x0 + M) * S; ys[i] = (raw[2 * i + 1] - y0 + M) * S;
    }
    WL = { W: (x1 - x0 + 2 * M) * S, H: (y1 - y0 + 2 * M) * S, raw: raw, dies: Object.keys(dies).map(function (k) {
      var q = dies[k]; return [(q[0] - x0 + M) * S, (q[1] - y0 + M) * S, q[2] * S, +k]; }) };
    buildGrid('wafer', xs, ys, 8);
  }
  function buildGrid(view, xs, ys, cell) {
    var g = {}, c = cell * 2;
    for (var i = 0; i < N; i++) {
      var key = Math.floor(xs[i] / c) + ',' + Math.floor(ys[i] / c);
      (g[key] || (g[key] = [])).push(i);
    }
    gridIx[view] = { g: g, c: c, xs: xs, ys: ys, r: cell * 0.4 };
  }

  // ------------------------------------------------------------ camera
  function cam() { return cams[V.view] || (cams[V.view] = fitCam(V.view)); }
  function fitCam(view) {
    var L = view === 'map' ? D.map : view === 'wafer' ? (WL || D.map) : D.pipe, m = mapLike(view);
    var k = m ? Math.min(W / L.W, H / L.H) * 0.95 : Math.min(W / L.W, (H * 2.2) / L.H);
    return { k: k, x: (W - L.W * k) / 2, y: m ? (H - L.H * k) / 2 : 6 };
  }
  function freeArea() { // the part of the stage not covered by the info panel: [x0, y0, x1, y1]
    if (info.hidden) return [0, 0, W, H];
    if (info.offsetTop > 10) return [0, 0, W, info.offsetTop];
    return [0, 0, Math.max(W * 0.4, info.offsetLeft), H];
  }
  function fitTo(ids, why) {
    if (!ids.length) { toast(why ? 'No files ' + why + ' with the current filters' : 'Nothing matches', 3500); return; }
    if (V.view === 'flow' || !gridIx[V.view]) { toast(ids.length + ' files ' + (why || 'match'), 3000); return; }
    var g = gridIx[V.view], x0 = 1e15, y0 = 1e15, x1 = -1e15, y1 = -1e15;
    ids.forEach(function (i) { x0 = Math.min(x0, g.xs[i]); x1 = Math.max(x1, g.xs[i]); y0 = Math.min(y0, g.ys[i]); y1 = Math.max(y1, g.ys[i]); });
    var A = freeArea(), aw = A[2] - A[0], ah = A[3] - A[1] - 40, pad = g.c * 3;
    var c = cam(), k = Math.min(aw / (x1 - x0 + 2 * pad), ah / (y1 - y0 + 2 * pad), mapLike(V.view) ? 3 : 2.5);
    c.k = Math.max(0.01, k); c.x = A[0] + aw / 2 - (x0 + x1) / 2 * c.k; c.y = A[1] + 40 + ah / 2 - (y0 + y1) / 2 * c.k;
    toast(ids.length + ' file' + (ids.length === 1 ? '' : 's') + ' ' + (why || 'match') + ': tap one', 3000); redraw();
  }
  var toastT = 0;
  function toast(msg, ms) {
    clearTimeout(toastT); toastEl.textContent = msg || ''; toastEl.hidden = !msg;
    if (msg && ms) toastT = setTimeout(function () { toastEl.hidden = true; }, ms);
  }
  function toWorld(sx, sy) { var c = cam(); return [(sx - c.x) / c.k, (sy - c.y) / c.k]; }
  function zoomAt(sx, sy, f) {
    var c = cam(), nk = Math.max(0.01, Math.min(40, c.k * f));
    c.x = sx - (sx - c.x) * nk / c.k; c.y = sy - (sy - c.y) * nk / c.k; c.k = nk; redraw();
  }
  function centreOn(i, minK) {
    if (V.view === 'flow' || i < 0 || !gridIx[V.view]) return;
    var c = cam(), g = gridIx[V.view];
    if (minK && c.k < minK) c.k = minK;
    var A = freeArea();
    c.x = (A[0] + A[2]) / 2 - g.xs[i] * c.k; c.y = (A[1] + A[3]) * 0.5 - g.ys[i] * c.k; redraw();
  }
  function hit(sx, sy) {
    if (V.view === 'flow' || !gridIx[V.view]) return -1;
    var g = gridIx[V.view], w = toWorld(sx, sy), c = cam();
    var rad = Math.max(g.r * 1.3, 7 / c.k), best = -1, bd = rad * rad;
    var cx = Math.floor(w[0] / g.c), cy = Math.floor(w[1] / g.c), span = Math.ceil(rad / g.c);
    for (var a = cx - span; a <= cx + span; a++) for (var b = cy - span; b <= cy + span; b++) {
      var arr = g.g[a + ',' + b]; if (!arr) continue;
      for (var j = 0; j < arr.length; j++) {
        var i = arr[j]; if (!shown(i)) continue;
        var dx = g.xs[i] - w[0], dy = g.ys[i] - w[1], d = dx * dx + dy * dy;
        if (d < bd) { bd = d; best = i; }
      }
    }
    return best;
  }

  // ------------------------------------------------------------ drawing
  function redraw() { if (!dirty) { dirty = true; requestAnimationFrame(draw); } }
  function resize() {
    stageEl.style.height = (window.innerHeight - $('bar').offsetHeight) + 'px';
    dpr = window.devicePixelRatio || 1; W = stageEl.clientWidth; H = stageEl.clientHeight;
    cv.width = Math.round(W * dpr); cv.height = Math.round(H * dpr); redraw();
  }
  function draw() {
    dirty = false;
    if (!D || V.view === 'flow' || !gridIx[V.view]) return;
    var c = cam(), g = gridIx[V.view], xs = g.xs, ys = g.ys;
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.fillStyle = '#000'; ctx.fillRect(0, 0, W, H);
    ctx.save(); ctx.translate(c.x, c.y); ctx.scale(c.k, c.k);
    if (V.view === 'pipeline') drawPipeFrame(c); else if (V.view === 'wafer') drawWaferFrame(c); else drawMapFrame(c);
    if (V.edges) drawAllEdges(c);
    if (V.drift && OV.drift) drawDrift(c);
    var focus = V.hov >= 0 ? V.hov : V.sel;
    if (V.colour === 'pattern') { drawPatternLinks(V.sel, c); if (V.hov !== V.sel) drawPatternLinks(V.hov, c); }
    if (V.sel >= 0) drawNeighbourEdges(V.sel, c);
    if (V.pulse && OV.faraday && V.sel >= 0) drawPulse(V.sel, c);
    if (V.hov >= 0 && V.hov !== V.sel) drawNeighbourEdges(V.hov, c);
    // dots, batched by colour, culled to the viewport
    var x0 = -c.x / c.k, y0 = -c.y / c.k, x1 = x0 + W / c.k, y1 = y0 + H / c.k;
    var rw = g.r, pad = rw * 3, buckets = {}, dimmed = [], hollow = [], rings = [];
    for (var i = 0; i < N; i++) {
      var x = xs[i], y = ys[i];
      if (x < x0 - pad || x > x1 + pad || y < y0 - pad || y > y1 + pad) continue;
      if (!lit(i)) { if (!V.only || shown(i)) dimmed.push(i); continue; }
      if (V.reach && P.re[i] === 0) { hollow.push(i); continue; }
      var col = colour(i); (buckets[col] || (buckets[col] = [])).push(i);
      if (V.reach && P.en[i] === 1) rings.push(i);
    }
    var minR = 1.1 / c.k, R = Math.max(rw, minR);
    var pat = V.colour === 'pattern';
    dots(dimmed, DIM, R * 0.8);
    Object.keys(buckets).sort().forEach(function (col) {
      var arr = buckets[col], r = R;
      if (pat) r = P.p[arr[0]] >= 0 ? Math.max(rw * 1.35, minR * 1.6) : R * 0.6;
      if (pat && P.p[arr[0]] >= 0 && c.k * r > 1.5) { ctx.globalAlpha = 0.22; dots(arr, col, r * 2.1); ctx.globalAlpha = 1; }
      dots(arr, col, r);
    });
    if (hollow.length) { // unreached: hollow, hatched rings
      ctx.lineWidth = Math.max(0.8 / c.k, rw * 0.25);
      for (var h = 0; h < hollow.length; h++) {
        var j = hollow[h]; ctx.strokeStyle = colour(j); ctx.globalAlpha = 0.75;
        ctx.beginPath(); ctx.arc(xs[j], ys[j], R * 0.9, 0, 6.2832); ctx.stroke();
        ctx.beginPath(); ctx.moveTo(xs[j] - R * 0.6, ys[j] + R * 0.6); ctx.lineTo(xs[j] + R * 0.6, ys[j] - R * 0.6); ctx.stroke();
      }
      ctx.globalAlpha = 1;
    }
    if (rings.length) {
      ctx.strokeStyle = '#ffffff'; ctx.lineWidth = Math.max(0.7 / c.k, rw * 0.22); ctx.globalAlpha = 0.85;
      ctx.beginPath();
      rings.forEach(function (j) { var rr = Math.max(R * 1.7, 2.2 / c.k); ctx.moveTo(xs[j] + rr, ys[j]); ctx.arc(xs[j], ys[j], rr, 0, 6.2832); });
      ctx.stroke(); ctx.globalAlpha = 1;
    }
    if (matchSet) {
      ctx.strokeStyle = ACC; ctx.lineWidth = 1.2 / c.k;
      for (var m = 0; m < N; m++) if (matchSet[m] && shown(m)) { ctx.beginPath(); ctx.arc(xs[m], ys[m], R + 3 / c.k, 0, 6.2832); ctx.stroke(); }
    }
    ring(V.hov, '#ffffff', R + 3 / c.k, 1.5 / c.k);
    ring(V.sel, SEL, R + 5 / c.k, 3 / c.k); ring(V.sel, '#ffffff', R + 2 / c.k, 1 / c.k);
    ctx.restore();
    if (V.view === 'pipeline') drawPipeHeader(c);
    function dots(arr, col, r) {
      ctx.fillStyle = col;
      if (c.k * r < 2.2) { var s = r * 2; for (var a = 0; a < arr.length; a++) ctx.fillRect(xs[arr[a]] - r, ys[arr[a]] - r, s, s); return; }
      ctx.beginPath();
      for (var b = 0; b < arr.length; b++) { ctx.moveTo(xs[arr[b]] + r, ys[arr[b]]); ctx.arc(xs[arr[b]], ys[arr[b]], r, 0, 6.2832); }
      ctx.fill();
    }
    function ring(i, col, r, lw) {
      if (i < 0) return; ctx.strokeStyle = col; ctx.lineWidth = lw;
      ctx.beginPath(); ctx.arc(xs[i], ys[i], r, 0, 6.2832); ctx.stroke();
    }
  }
  function label(text, x, y, px, col, c, align) {
    ctx.font = (px / c.k) + 'px ui-monospace,Menlo,Consolas,monospace'; ctx.fillStyle = col;
    ctx.textAlign = align || 'left'; ctx.fillText(text, x, y);
  }
  function drawPipeFrame(c) {
    var pp = D.pipe;
    ctx.lineWidth = 1 / c.k;
    pp.cols.forEach(function (col, si) {
      ctx.fillStyle = PANEL; ctx.fillRect(col[0] - 14, 20, col[1] - col[0] + 28, pp.H - 30);
    });
    pp.groups.forEach(function (gp) {
      var on = (V.repo < 0 || V.repo === gp[5]);
      ctx.strokeStyle = on ? LINE : '#15181d'; ctx.strokeRect(gp[1] - 4, gp[2], gp[3] + 8, gp[4]);
      var px = Math.min(12, 34 * c.k * 0.8);
      if (px < 7) return;
      ctx.font = (px / c.k) + 'px ui-monospace,Menlo,Consolas,monospace';
      var t = D.repos[gp[5]][0] + ' · ' + gp[6], maxw = gp[3];
      if (ctx.measureText(t).width > maxw) {
        var name = D.repos[gp[5]][0], tail = '… · ' + gp[6];
        while (name.length > 1 && ctx.measureText(name + tail).width > maxw) name = name.slice(0, -1);
        t = name + tail;
      }
      ctx.fillStyle = on ? '#a6adbb' : '#333'; ctx.textAlign = 'left'; ctx.fillText(t, gp[1], gp[2] + 25);
    });
  }
  function drawPipeHeader(c) {
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    ctx.fillStyle = 'rgba(0,0,0,.85)'; ctx.fillRect(0, 0, W, 22);
    ctx.font = '12px ui-monospace,Menlo,Consolas,monospace'; ctx.textAlign = 'left';
    D.pipe.cols.forEach(function (col, si) {
      var x = col[0] * c.k + c.x;
      if (x > W || (col[1] * c.k + c.x) < 0) return;
      var t = col[2] + ' · ' + col[3] + (si < 3 ? '  →' : ''), room = (col[1] - col[0]) * c.k + (D.pipe.cols[1][0] - col[1]) * c.k * 0.8;
      if (ctx.measureText(t).width > room) t = ['Ingest', 'Transform', 'Output', '?'][si] + ' ' + col[3];
      ctx.fillStyle = D.stages[si][2]; ctx.fillText(t, Math.max(4, x), 15);
    });
  }
  function drawMapFrame(c) {
    var m = D.map;
    ctx.lineWidth = 1 / c.k;
    m.repos.forEach(function (rc) {
      var on = V.repo < 0 || V.repo === rc[3];
      ctx.beginPath(); ctx.arc(rc[0], rc[1], rc[2], 0, 6.2832);
      ctx.fillStyle = PANEL; ctx.fill(); ctx.strokeStyle = on ? LINE : '#15181d'; ctx.stroke();
    });
    ctx.strokeStyle = '#1b2028';
    m.dirs.forEach(function (d) { if (d[2] * c.k > 4) { ctx.beginPath(); ctx.arc(d[0], d[1], d[2], 0, 6.2832); ctx.stroke(); } });
    m.dirs.forEach(function (d) {
      if (d[2] * c.k > 45) label(d[3], d[0], d[1] - d[2] - 3 / c.k, 11, '#6f7785', c, 'center');
    });
    m.repos.forEach(function (rc) {
      if (rc[2] * c.k > 34) label(D.repos[rc[3]][0], rc[0], rc[1] - rc[2] - 4 / c.k, rc[2] * c.k > 90 ? 13 : 11, V.repo < 0 || V.repo === rc[3] ? '#a6adbb' : '#333', c, 'center');
    });
  }
  function drawWaferFrame(c) {
    ctx.lineWidth = 1 / c.k;
    WL.dies.forEach(function (d) {
      var on = V.repo < 0 || V.repo === d[3];
      ctx.beginPath(); ctx.arc(d[0], d[1], d[2], 0, 6.2832); ctx.fillStyle = PANEL; ctx.fill(); ctx.strokeStyle = on ? LINE : '#15181d'; ctx.stroke();
    });
    WL.dies.forEach(function (d) {
      if (d[2] * c.k > 30) label(D.repos[d[3]][0], d[0], d[1] - d[2] - 4 / c.k, 11, V.repo < 0 || V.repo === d[3] ? '#a6adbb' : '#333', c, 'center');
    });
  }
  function drawDrift(c) { // near-copy edges: copy -> canonical, dashed
    var g = gridIx[V.view], xs = g.xs, ys = g.ys, e = OV.drift.e;
    ctx.strokeStyle = '#ffae00'; ctx.lineWidth = 1.2 / c.k; ctx.globalAlpha = 0.55; ctx.setLineDash([5 / c.k, 3 / c.k]); ctx.beginPath();
    for (var k = 0; k < e.length; k += 3) if (shown(e[k]) || shown(e[k + 1])) { ctx.moveTo(xs[e[k]], ys[e[k]]); ctx.lineTo(xs[e[k + 1]], ys[e[k + 1]]); }
    ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1;
  }
  function curve(x1, y1, x2, y2) {
    ctx.moveTo(x1, y1);
    if (V.view === 'pipeline') {
      var dx = Math.abs(x2 - x1), bend = Math.max(60, dx * 0.45);
      if (dx < 400) { var off = 220 + Math.abs(y2 - y1) * 0.08; ctx.bezierCurveTo(x1 + off, y1, x2 + off, y2, x2, y2); }
      else ctx.bezierCurveTo(x1 + (x2 > x1 ? bend : -bend), y1, x2 - (x2 > x1 ? bend : -bend), y2, x2, y2);
    } else {
      var mx = (x1 + x2) / 2, my = (y1 + y2) / 2, nx = -(y2 - y1) * 0.15, ny = (x2 - x1) * 0.15;
      ctx.quadraticCurveTo(mx + nx, my + ny, x2, y2);
    }
  }
  function drawNeighbourEdges(i, c) {
    var g = gridIx[V.view], xs = g.xs, ys = g.ys;
    ctx.lineWidth = 1.4 / c.k;
    ctx.globalAlpha = 0.9; ctx.strokeStyle = ACC; ctx.beginPath();
    uses[i].forEach(function (j) { if (shown(j)) curve(xs[i], ys[i], xs[j], ys[j]); }); ctx.stroke();
    ctx.strokeStyle = '#ffae00'; ctx.beginPath();
    usedBy[i].forEach(function (j) { if (shown(j)) curve(xs[j], ys[j], xs[i], ys[i]); }); ctx.stroke();
    // second ring: neighbours' own edges, faint
    ctx.globalAlpha = 0.18; ctx.lineWidth = 1 / c.k; ctx.strokeStyle = '#ffffff'; ctx.beginPath();
    uses[i].concat(usedBy[i]).slice(0, 60).forEach(function (j) {
      uses[j].forEach(function (k) { if (k !== i && shown(k)) curve(xs[j], ys[j], xs[k], ys[k]); });
    });
    ctx.stroke(); ctx.globalAlpha = 1;
  }
  // Faraday pulse (laws FA): the users of the selected file light with the measured rate p, users of users with p*p.
  var pulseT0 = 0, pulseFor = -1;
  function pulseRings(i) {
    var r1 = usedBy[i].filter(shown), seen = {}, r2 = [];
    seen[i] = 1; r1.forEach(function (j) { seen[j] = 1; });
    for (var a = 0; a < r1.length && r2.length < 400; a++)
      usedBy[r1[a]].forEach(function (k) { if (!seen[k] && shown(k)) { seen[k] = 1; r2.push(k); } });
    return [r1, r2];
  }
  function drawPulse(i, c) {
    var g = gridIx[V.view], xs = g.xs, ys = g.ys, f = OV.faraday, rings = pulseRings(i);
    var reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (pulseFor !== i) { pulseFor = i; pulseT0 = performance.now(); }
    var t = reduce ? 1 : Math.min(1, (performance.now() - pulseT0) / 900), R = Math.max(g.r, 1.1 / c.k);
    [[rings[0], f.p, 0], [rings[1], f.p * f.p, 0.5]].forEach(function (rg) {
      var lt = Math.max(0, Math.min(1, (t - rg[2]) * 2)); if (!lt || !rg[0].length) return;
      ctx.globalAlpha = rg[1] * lt; ctx.strokeStyle = '#ffe14d'; ctx.lineWidth = 2.2 / c.k; ctx.beginPath();
      rg[0].forEach(function (j) { var rr = R * (1.6 + 1.4 * (1 - lt)); ctx.moveTo(xs[j] + rr, ys[j]); ctx.arc(xs[j], ys[j], rr, 0, 6.2832); });
      ctx.stroke();
    });
    ctx.globalAlpha = 1;
    if (t < 1) redraw();
  }
  function pulseInfo(i) {
    var f = OV.faraday; if (!V.pulse || !f) return '';
    var rg = pulseRings(i), pc = Math.round(f.p * 100);
    return '<h3>Faraday pulse</h3><p class="m">' + rg[0].length + ' file' + (rg[0].length === 1 ? '' : 's') + ' use this one, and ' +
      rg[1].length + ' more use those. Across the estate\'s copies, when a used file changed its users changed too in ' +
      f.k + ' of ' + f.n + ' cases (' + pc + '%), so these are the files to check when it changes. Rings: users at ' + pc +
      '%, their users at ' + Math.round(f.p * f.p * 100) + '%. Source: ' + esc(f.source) + (f.cut ? ', cut ' + esc(f.cut) : '') + '.</p>';
  }
  function drawPatternLinks(i, c) {
    if (i < 0 || P.p[i] < 0) return;
    var g = gridIx[V.view], xs = g.xs, ys = g.ys, p = P.p[i];
    ctx.strokeStyle = D.pats[p][1]; ctx.lineWidth = 1.2 / c.k; ctx.globalAlpha = 0.7;
    ctx.setLineDash([6 / c.k, 4 / c.k]); ctx.beginPath();
    for (var j = 0; j < N; j++) if (j !== i && P.p[j] === p && shown(j)) { ctx.moveTo(xs[i], ys[i]); ctx.lineTo(xs[j], ys[j]); }
    ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1;
  }
  var bundleCache = null;
  function drawAllEdges(c) {
    var g = gridIx[V.view], xs = g.xs, ys = g.ys, e = D.e;
    if (mapLike(V.view)) {
      ctx.lineWidth = 0.8 / c.k; ctx.globalAlpha = 0.07; ctx.strokeStyle = '#66ccff'; ctx.beginPath();
      for (var k = 0; k < e.length; k += 2) if (shown(e[k]) && shown(e[k + 1])) curve(xs[e[k]], ys[e[k]], xs[e[k + 1]], ys[e[k + 1]]);
      ctx.stroke(); ctx.globalAlpha = 1; return;
    }
    // Pipeline: bundle repo-group to repo-group (one curve per pair, width by count)
    var key = V.topic + '|' + V.repo + '|' + V.only + '|' + V.colour + '|' + JSON.stringify(V.hidden);
    if (!bundleCache || bundleCache.key !== key) {
      var grpOf = groupIndex(), agg = {};
      for (var a = 0; a < e.length; a += 2) {
        var s = e[a], t = e[a + 1]; if (!shown(s) || !shown(t)) continue;
        var kk = grpOf[s] + ',' + grpOf[t]; agg[kk] = (agg[kk] || 0) + 1;
      }
      bundleCache = { key: key, agg: agg };
    }
    var gs = D.pipe.groups, agg2 = bundleCache.agg;
    ctx.strokeStyle = '#66ccff';
    Object.keys(agg2).sort().forEach(function (kk) {
      var p = kk.split(','), A = gs[+p[0]], B = gs[+p[1]], n = agg2[kk];
      ctx.globalAlpha = Math.min(0.55, 0.12 + Math.log(1 + n) * 0.08);
      ctx.lineWidth = Math.max(1 / c.k, Math.min(14, 1 + Math.log(1 + n) * 2.2));
      ctx.beginPath();
      var ax = A[1] + A[3] + 6, ay = A[2] + A[4] / 2, bx = B[1] - 6, by = B[2] + B[4] / 2;
      if (A === B) { ax = A[1] + A[3] + 6; bx = ax; by = ay + 1; }
      if (B[1] <= A[1]) { bx = B[1] + B[3] + 6; }
      curve(ax, ay, bx, by); ctx.stroke();
    });
    ctx.globalAlpha = 1;
  }
  var grpCache = null;
  function groupIndex() {
    if (grpCache) return grpCache;
    grpCache = new Int32Array(N);
    var gs = D.pipe.groups;
    for (var i = 0; i < N; i++) {
      for (var j = 0; j < gs.length; j++) {
        var gp = gs[j];
        if (P.s[i] === gp[0] && P.r[i] === gp[5] && P.py[i] >= gp[2] && P.py[i] <= gp[2] + gp[4]) { grpCache[i] = j; break; }
      }
    }
    return grpCache;
  }

  // ------------------------------------------------------------ legend
  function counts(mode) {
    var m = {};
    for (var i = 0; i < N; i++) {
      if (V.topic >= 0 && P.t[i] !== V.topic) continue;
      if (V.repo >= 0 && P.r[i] !== V.repo) continue;
      var c = cat(i, mode); m[c] = (m[c] || 0) + 1;
    }
    return m;
  }
  function renderLegend() {
    var mode = V.colour, cnt = counts(mode), keys;
    if (mode === 'role') keys = D.roles.map(function (_, i) { return i; });
    else if (mode === 'topic') keys = D.topics.map(function (_, i) { return i; });
    else if (mode === 'stage') keys = [0, 1, 2, 3];
    else if (isOv(mode) && mode !== 'community') {
      keys = OV[mode] ? OV[mode].cats.map(function (_, i) { return i; }) : [];
      if (cnt[-1]) keys.push(-1);
    } else {
      keys = Object.keys(cnt).map(Number).filter(function (k) { return k >= 0; })
        .sort(function (a, b) { return (cnt[b] - cnt[a]) || (a - b); }).slice(0, 18);
      keys.push(-1);
    }
    $('legtitle').textContent = mode === 'pattern' ? 'pattern: same colour = same shared logic' : mode === 'community' ? 'community: files that reference each other' :
      mode === 'periodic' ? 'periodic element, by period' : mode === 'clarity' ? 'clarity group' : mode;
    legend.innerHTML = keys.map(function (k) {
      return '<li data-k="' + k + '" class="' + (V.hidden[k] ? 'off' : '') + '" title="click to hide/show, double-click to show only this">' +
        '<i style="background:' + catColour(k) + '"></i>' + esc(catTitle(k)) + ' <small>' + (cnt[k] || 0) + '</small></li>';
    }).join('') + (Object.keys(V.hidden).length ? '<li data-k="all"><small>show all</small></li>' : '');
    var note = [];
    if (mode === 'pattern') {
      var shared = 0; for (var i = 0; i < N; i++) if (P.p[i] >= 0) shared++;
      note.push(D.pats.length + ' shared patterns cover ' + shared + ' files; unique files are grey.' + (D.adapter === 'parquet' ? ' (Approximation: shared file names.)' : ''));
    }
    if (isOv(mode) && !OV[mode]) note.push('Loading…');
    if (mode === 'community' && OV.community) note.push(OV.community.cats.length + ' communities (Louvain on resolved references); grey files have none.');
    if (mode === 'periodic' && OV.periodic) note.push(OV.periodic.els.length + ' elements; tap a file for its symbol. Candidates have no number.');
    if (V.drift && OV.drift) note.push((OV.drift.e.length / 3) + ' near-copy edges (dashed, copy → canonical). ' + OV.drift.safe.length + ' safe-review candidates: unreached, with a reachable near copy.');
    if (V.view === 'wafer') note.push('Wafer: one die per repository by its permanent number; each file sits where its own repo/path key puts it, computed in your browser, so unchanged files never move.');
    if (mode === 'role' && D.adapter === 'parquet') note.push('Roles approximated from path words until build_graph.json lands.');
    if (V.reach) {
      var en = 0, un = 0, known = 0;
      for (var j = 0; j < N; j++) { if (P.en[j] === 1) en++; if (P.re[j] === 0) un++; if (P.re[j] !== 2) known++; }
      note.push(known ? en + ' entry points (white rings) · ' + un + ' files not reached from any entry point: candidates for review (hollow, struck).' :
        'Reachability is not available in this build.');
    }
    $('legnote').textContent = note.join(' ');
  }

  // ------------------------------------------------------------ info panel and tooltip
  function fileItem(j) {
    return '<li data-f="' + j + '"><span class="sw" style="background:' + colour(j) + '"></span>' +
      esc(repoName(j) + ' / ' + path(j)) + '</li>';
  }
  function showInfo() {
    var i = V.sel;
    if (i < 0 && !V.cell) { info.hidden = true; return; }
    info.hidden = false;
    if (i < 0) return showCell();
    var r = D.repos[P.r[i]], t = D.topics[P.t[i]];
    var reach = P.re[i] === 2 ? 'not computed' : P.re[i] ? 'reached from an entry point' : 'not reached from any entry point (candidate for review)';
    var lead = esc(title(i)) + ' is ' + (/^[aeiou]/i.test(D.roles[P.o[i]][1]) ? 'an ' : 'a ') + esc(D.roles[P.o[i]][1].split(/[:(]/)[0].trim().toLowerCase()) +
      ' file in ' + esc(r[0]) + (t[0] ? ', topic ' + esc(t[1]) : '') + '.';
    var h = '<button class="x" data-act="close" aria-label="Close">×</button><h2 tabindex="-1">' + esc(title(i)) + '</h2>' +
      '<p class="lead">' + lead + '</p><div class="m">' + esc(r[0] + ' / ' + path(i)) + '</div>' +
      '<a class="open" href="' + secUrl(i) + '">Open section ' + P.sec[i] + ' →</a>' +
      '<a class="open" href="../repos/' + esc(r[1]) + '.html">Repository</a>' +
      '<dl>' + (P.a[i] ? '<dt>Achieves</dt><dd>' + esc(P.a[i]) + '</dd>' : '') +
      (P.w[i] ? '<dt>Why</dt><dd>' + esc(P.w[i]) + '</dd>' : '') +
      '<dt>Role</dt><dd><span class="sw" style="background:' + D.roles[P.o[i]][2] + '"></span>' + esc(D.roles[P.o[i]][1]) + '</dd>' +
      '<dt>Stage</dt><dd>' + esc(D.stages[P.s[i]][1]) + '</dd>' +
      (t[0] ? '<dt>Topic</dt><dd><a href="../topics/' + esc(t[0]) + '.html">' + esc(t[1]) + '</a></dd>' : '') +
      ovRows(i) +
      '<dt>Lines</dt><dd>' + P.l[i] + '</dd>' +
      (P.p[i] >= 0 ? '<dt>Pattern</dt><dd><span class="sw" style="background:' + D.pats[P.p[i]][1] + '"></span>' + esc(D.pats[P.p[i]][0]) + ' (' + D.pats[P.p[i]][2] + ' files)</dd>' : '') +
      '<dt>Entry</dt><dd>' + (P.en[i] === 2 ? 'not computed' : P.en[i] ? 'yes' : 'no') + '</dd>' +
      '<dt>Reach</dt><dd>' + reach + '</dd>' +
      (P.df[i] ? '<dt>Defines</dt><dd>' + esc(P.df[i].split(' ').join(', ')) + '</dd>' : '') + '</dl>' +
      '<h3>Uses (' + uses[i].length + ')</h3><ul>' + (uses[i].slice(0, 80).map(fileItem).join('') || '<li class="m">none resolved in the estate</li>') + '</ul>' +
      '<h3>Used by (' + usedBy[i].length + ')</h3><ul>' + (usedBy[i].slice(0, 80).map(fileItem).join('') || '<li class="m">none found</li>') + '</ul>' +
      pulseInfo(i);
    var dr = OV.drift;
    if (dr && dr.fam[i] >= 0) {
      var fam = []; for (var f = 0; f < N && fam.length < 40; f++) if (f !== i && dr.fam[f] === dr.fam[i]) fam.push(f);
      var cn = dr.canon[i];
      h += '<h3>Near copies (' + fam.length + ')' + (dr.safeSet[i] ? ' · safe review candidate' : '') + '</h3>' +
        (cn ? '<div class="m">canonical copy (similarity ' + (cn[1] / 10).toFixed(0) + '%):</div><ul>' + fileItem(cn[0]) + '</ul>' : '<div class="m">this is the canonical copy</div>') +
        '<ul>' + fam.filter(function (x) { return !cn || x !== cn[0]; }).map(fileItem).join('') + '</ul>';
    }
    if (P.p[i] >= 0) {
      var same = []; for (var j = 0; j < N && same.length < 40; j++) if (j !== i && P.p[j] === P.p[i]) same.push(j);
      h += '<h3>Same pattern (' + (D.pats[P.p[i]][2] - 1) + ')</h3><ul>' + same.map(fileItem).join('') + '</ul>';
    }
    info.innerHTML = h; info.scrollTop = 0;
  }
  function ovRows(i) {
    var h = '', o;
    if ((o = OV.community) && o.c[i] >= 0) h += '<dt>Community</dt><dd><span class="sw" style="background:' + o.cats[o.c[i]][1] + '"></span>' + esc(o.cats[o.c[i]][0]) + '</dd>';
    if ((o = OV.clarity) && o.c[i] >= 0) h += '<dt>Clarity</dt><dd><span class="sw" style="background:' + o.cats[o.c[i]][1] + '"></span>' + esc(o.cats[o.c[i]][0]) + '</dd>';
    if ((o = OV.periodic) && o.v[i] >= 0) {
      var e = o.els[o.v[i]];
      h += '<dt>Element</dt><dd>' + (e[0] ? '<b>' + esc(e[0]) + '</b> ' : '') + (e[1] != null ? '#' + e[1] + ' ' : '(candidate) ') + esc(e[2]) +
        ' · period ' + e[3] + (e[5] ? ' · like ' + esc(e[6] || e[5]) : '') + '</dd>';
    }
    if ((o = OV.laws) && o.c[i] >= 0) h += '<dt>Law</dt><dd>' + esc(o.cats[o.c[i]][0]) + '</dd>';
    return h;
  }
  function showCell() {
    var cl = V.cell, mode = flowMode(), list = [];
    for (var k = 0; k < D.e.length && list.length < 60; k += 2) {
      var a = D.e[k], b = D.e[k + 1];
      if (!shown(a) || !shown(b)) continue;
      if (cl.stage ? (P.s[a] === cl.a && P.s[b] === cl.b) : (cat(a, mode) === cl.a && cat(b, mode) === cl.b)) list.push([a, b]);
    }
    var nm = cl.stage ? function (x) { return D.stages[x][1]; } : function (x) { return catTitle(x, mode); };
    info.innerHTML = '<button class="x" data-act="close" aria-label="Close">×</button><h2>' + esc(nm(cl.a)) + ' → ' + esc(nm(cl.b)) + '</h2>' +
      '<div class="m">' + cl.n + ' imports; first ' + list.length + ' shown (importer, then imported)</div><ul>' +
      list.map(function (p) { return fileItem(p[0]) + '<li class="m" style="cursor:default;padding-left:14px">↳ uses</li>' + fileItem(p[1]); }).join('') + '</ul>';
  }
  function showTip(i, sx, sy) {
    if (i < 0) { tip.hidden = true; return; }
    tip.innerHTML = '<b>' + esc(title(i)) + '</b>' + (P.a[i] ? '<div>' + esc(P.a[i]) + '</div>' : '') +
      (P.w[i] ? '<div class="m">why: ' + esc(P.w[i]) + '</div>' : '') +
      '<div class="m">' + esc(repoName(i) + ' / ' + path(i)) + '</div>' +
      '<div><span class="sw" style="background:' + D.roles[P.o[i]][2] + '"></span>' + esc(D.roles[P.o[i]][0]) + ' · ' + esc(D.stages[P.s[i]][0]) +
      ' · ' + P.l[i] + ' lines · uses ' + uses[i].length + ' · used by ' + usedBy[i].length + '</div>';
    tip.hidden = false;
    var tw = tip.offsetWidth, th = tip.offsetHeight, A = freeArea(); // never over the info panel
    var x = Math.max(4, Math.min(A[2] - tw - 4, sx + 14)), y = sy + 16 + th > A[3] ? sy - th - 10 : sy + 16;
    if (x + tw > A[2] || y < 0 || y + th > A[3] || sx > A[2] || sy > A[3]) { tip.hidden = true; return; }
    tip.style.left = x + 'px'; tip.style.top = Math.max(4, y) + 'px';
  }

  // ------------------------------------------------------------ flow view
  function flowMode() { return V.colour === 'pattern' || V.colour === 'community' || (isOv(V.colour) && !OV[V.colour]) ? 'role' : V.colour; }
  function renderFlow() {
    var mode = flowMode(), K = mode === 'role' ? D.roles.length : mode === 'topic' ? D.topics.length : isOv(mode) ? OV[mode].cats.length : 4;
    var m = [], st = [], tot = 0, i, j;
    for (i = 0; i < K; i++) { m.push([]); for (j = 0; j < K; j++) m[i].push(0); }
    for (i = 0; i < 4; i++) st.push([0, 0, 0, 0]);
    for (var k = 0; k < D.e.length; k += 2) {
      var a = D.e[k], b = D.e[k + 1]; if (!shown(a) || !shown(b)) continue;
      var ca = cat(a, mode), cb = cat(b, mode); if (ca >= 0 && cb >= 0) m[ca][cb]++; st[P.s[a]][P.s[b]]++; tot++;
    }
    function table(mat, n, nameOf, colOf, stage) {
      var mx = 1; mat.forEach(function (r) { r.forEach(function (v) { if (v > mx) mx = v; }); });
      var h = '<table><tr><th class="row">importer ↓ · imported →</th>';
      for (var c = 0; c < n; c++) h += '<th title="' + esc(nameOf(c)) + '"><span class="sw" style="background:' + colOf(c) + '"></span>' + esc(nameOf(c).split(/[ :,]/)[0]) + '</th>';
      h += '<th>total</th></tr>';
      for (var r = 0; r < n; r++) {
        var rs = 0; h += '<tr><th class="row"><span class="sw" style="background:' + colOf(r) + '"></span>' + esc(nameOf(r)) + '</th>';
        for (c = 0; c < n; c++) {
          var v = mat[r][c]; rs += v;
          var al = v ? (0.15 + 0.85 * Math.log(1 + v) / Math.log(1 + mx)).toFixed(2) : 0;
          h += v ? '<td class="c" data-a="' + r + '" data-b="' + c + '" data-n="' + v + '" data-st="' + (stage ? 1 : 0) + '" style="background:' + hexA(colOf(r), al) + ';color:' + (al > 0.55 ? '#000' : '#fff') + '">' + v + '</td>' : '<td style="color:#333">·</td>';
        }
        h += '<th>' + rs + '</th></tr>';
      }
      return h + '</table>';
    }
    flowEl.innerHTML = '<h2>Flow by ' + mode + '</h2><p>' + tot + ' resolved imports between files that pass the current filters. Rows import columns; ' +
      'click a cell to list the files.' + (tot ? '' : ' No imports are resolved in this data yet.') + '</p>' +
      table(m, K, function (c) { return catTitle(c, mode); }, function (c) { return catColour(c, mode); }, false) +
      '<h2>Ingest → Transform → Engineering output</h2><p>Imports between stages (the build\'s stage rule).</p>' +
      table(st, 4, function (c) { return D.stages[c][1]; }, function (c) { return D.stages[c][2]; }, true);
  }
  function hexA(hex, a) {
    var n = parseInt(hex.slice(1), 16);
    return 'rgba(' + (n >> 16 & 255) + ',' + (n >> 8 & 255) + ',' + (n & 255) + ',' + a + ')';
  }

  // ------------------------------------------------------------ search / commands
  function searchIndex() {
    if (lower) return lower;
    lower = [];
    for (var i = 0; i < N; i++) lower.push((P.b[i] + '\u0001' + repoName(i) + '/' + path(i) + '\u0001' + P.df[i] + '\u0001' + title(i)).toLowerCase());
    return lower;
  }