GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / kuiper-belt / editions/202611020825/modules

Layers

A JavaScript file in the editions folder of Kuiper Belt that fetches bytes (`fetchBytes`), loads source (`loadSource`), draws features (`drawFeatures`) and calculates planar distances (units: kV), using SHA-256.

700 lines of JavaScript from kuiper-belt, in 1 file. Topic: Kuiper, cosmos and drawing engines. Section 1519 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. Layers interaction · kuiper-belt / editions/202611020825/modules/202611020637-layers.js lines 1–700

Layers

A JavaScript file in the editions folder of Kuiper Belt that fetches bytes (`fetchBytes`), loads source (`loadSource`), draws features (`drawFeatures`) and calculates planar distances (units: kV), using SHA-256.

interactionkuiper-belt / editions/202611020825/modules/202611020637-layers.js · lines 1–700 of 823 · version 2026-11-02 06:37 · Not reached from any entry point (candidate for review) · pattern drawFeatures (shared by 2 files)

What it does
It draws its content. Defines 68 functions or classes, including edName, esc, fmt, rec, setState. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). README: "Edition 10 is the same page, keys and modules with one module added: the layers registry (`modules/202611020637-layers.js`, sha256 `c8fccccf212a66cf9c37e02a260eed212bd1ad2548c52b13fbf6024bd5d22486`, Opus team 3, NL-010 step 3, the GridAtlas lesson of layer management), with its data `data/layers.json` and `data/editions.json`."
Inputs & outputs
In: JSON file layers.json; JSON file editions.json; JSON file keys-min.json; JSON file keys.json; form fields (user input).
What it achieves
It sets state (`setState`), fetches bytes (`fetchBytes`) and loads source (`loadSource`). Kuiper module layers Revision of -layers.js (refused 04:24Z by the night controller, unchanged), built on Kuiper Edition 9 picker, e/E, the LINES panel the shell moves into WAFER). It responds to change, keydown and resize events.
Why it matters
No other file in the estate was found to import it.
Application
kuiper-belt · editions/202611020825/modules · script
VEDIC
FILTER (GG2050-VEDIC-000043): Kuiper / Code navigation · Computer science / Interactive visualisation. placed_records, visibility_state, query → filtered_line_panel
Uses
none found
Used by
none found
Produces
edName, esc, fmt, rec, setState, tagText, inspect, get, original, set, value, register
Defines here
edName, esc, fmt, rec, setState, tagText, inspect, get, original, set, value, register, moduleId, hex, fetchBytes, verified, verifiedOne, admissible, loadSource, scr, drawFeatures, loud, alertLine, buildPanel, closePanel, sizePanel, fillRows, paintRow, apply, engineLines
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
kuiper-belt@26fba12ab1b5bab8e71934ab86c58273e5f32682 editions/202611020825/modules/202611020637-layers.js:1-700 · blob ede8ea019a7e15738eabb91e01005a946d4f81fd · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
/* kuiper module layers, generation 202611020637 (UTC), Apache-2.0 (kuiper-belt code)
   Revision of 202611020304-layers.js (refused 04:24Z by the night controller, unchanged), built on Kuiper Edition 9
   (202611020629), whose page still draws the verified lines itself (index.html loadEdition, edCard, edFly, the spark
   picker, e/E, the LINES panel the shell moves into WAFER). Two changes:
   (1) THE SPARK TAP. The refused file kept its tap bookkeeping (down, moved) in a bubble-phase pointerup on window; the
       shell stops pointerup on its bar and strip (kuiper-shell.js, bar/strip pointerup stopPropagation), so after one tap
       on a menu title an entry stayed in `down` forever and every later pointerdown set moved = 99: a tap 1.6 px from
       line 323 never reached the picker and the engine's key card stayed (journey spark-tap, Pixel 7, 04:24Z). Now the
       bookkeeping runs in the capture phase (it always sees the up), a primary pointerdown starts a fresh gesture, and
       the pick itself still runs in the bubble phase, after the engine's key card, so the line's card wins.
   (2) ENGINE LINES. On a page whose engine owns the verified lines (#lyAll and #lineslist exist: Edition 9, uncut) the
       module does not draw, list, pick or step lines a second time: the engine's layer is the lines layer, its switch
       #lyAll follows the registry's lines row both ways, and the registry still verifies keys-min.json against its
       sha256 (a FAIL switches the engine's lines off). The rows sit inside the engine's LINES block, after its filter
       and before its list, and fold away while the filter is in use. On a cut page (no #lyAll) the module owns the
       lines as 202611020304 did.
   Earlier: revision of 202611012141-layers.js (unchanged; 202611020240 was cut, tested and never admitted): while the filter is in
   use the layer rows fold away so the list keeps room on a 360 x 780 phone with the keyboard up (journey lines-filter); and taps inside #card never reach the page's close-on-click
   (index.html:603), as Edition 4's card listener ensured before the cut (REVIEW issuecomment-6567442274).
   Opus team 3, NL-010 roadmap step 3 "the Kuiper layer registry" (neural-link FIXES/NL-010/ROADMAP.md step 3;
   FIXES/NL-010/team-2/STEPS.md 3.1-3.8). Reference layers are records in data/layers.json (kuiper.layers.v1); each
   layer has ONE original control, input[data-ky-layer="layer:<id>"] in the WAFER panel (#layers); every other surface
   (keys e/E, the readout, the URL, the File menu, SCOPE/EDIT, the apps) proxies it through KY.modules.layers.api.
   Folds in NL-009 round 1 patch 05-lines (FIXES/NL-009/round1/05-lines.md, findings 1-10): the Edition 4 LINES panel
   becomes the verified-lines layer's control inside the WAFER panel.
   Moved here from the page (Edition 4 copy, editions/202611012135/index.html at kuiper-belt@96736f5):
   :626-654 loadEdition/edScreen/drawEdition and the draw wrap, :655-674 edCard and its card listener (fallback only;
   the card is Opus team 2's line-card module when admitted), :676-692 edFly/edNext/pointerup/e-E, :705-709 the LINES
   panel, :718 fillLines on open, :728-749 the ly* switches, fillLines and the two wraps.
   GridAtlas lessons: one original, many proxies (gridatlas@5ec7f62 atlas/modules/202609031958-menu-bar.js:12-13,
   :419-432, :1451-1462); the live state in the label (:91-98); install-then-inventory (:107-139); the whole row is the
   hit target (:1414-1425); galaxies-wafers@fff6fc6 layers-panel.mjs:117-118 (states), :325-330 (refuse on the row).
   requires: wafer, keyPlace, address, describe, findBy, flyTo, safeBox, fmt, esc, cv, o2, hud, big, sub, card, gbox,
             repos, commits, N, SPACE, lightTime, cam, lit, sel, redraw, draw, panels, refuse
   optional (used when admitted earlier, never required): line-card (api.show), see-through/apps (api via register)
   provides: layers */
(function () {
  'use strict';
  var ID = 'layers', GEN = '202611020637';
  var SCHEMA = 'kuiper.layers.v1', MANIFEST = 'data/layers.json', TIMEOUT_MS = 60000;
  // every file this module may fetch (its MODULE.json `reads`, edition_check E7); a record naming any other is refused
  var READS = ['data/layers.json', 'data/editions.json', 'keys-min.json', 'keys.json'];
  var ENGINE = false;           // true when the page's engine owns the verified lines (#lyAll, #lineslist): see the header
  var REQUIRES = ['wafer', 'keyPlace', 'address', 'describe', 'findBy', 'flyTo', 'safeBox', 'fmt', 'esc', 'cv', 'o2',
    'hud', 'big', 'sub', 'card', 'gbox', 'repos', 'commits', 'N', 'SPACE', 'lightTime', 'cam', 'lit', 'sel', 'redraw', 'draw', 'panels', 'refuse'];
  var STATES = ['WAIT', 'LOAD', 'OK', 'EMPTY', 'FAIL', 'REFUSED'];
  // kuiper-belt PALETTE.md:9-14, one colour one meaning; a layer may not invent a sixth (PALETTE.md:19)
  var PALETTE = { '#c9d3e6': 'the record', '#ffffff': 'the record', '#2ee6e6': 'the instrument', '#22ee77': 'energised',
    '#ffb000': 'attention', '#ff2bd6': 'selected' };
  var FORMATS = ['edition-keys.v1', 'code-feature-collection.v1', 'kuiper.editions.v1', 'engine'];

  var KY = null, H = null;
  var M = null;                 // the manifest, data/layers.json
  var rt = {};                  // id -> runtime { rec, on, value, status, why, placed, total, loaded_sha256, draw, ... }
  var panel = null, panelName = '', manifestWhy = 'WAIT · data/layers.json';
  var lines = { ED: [], placed: [], sel: -1, meta: null, focus: false, query: '', folded: {} };
  var lastRepo = -1, lastK0 = -1, booting = true;

  function edName() { return 'Kuiper edition ' + (KY && KY.edition ? KY.edition : '?'); }
  function esc(v) { return H ? H.esc(v) : String(v == null ? '' : v); }
  function fmt(n) { return H.fmt(n); }

  // ======================================================================== SECTION 1: the registry
  function rec(id) { return rt[id] ? rt[id].rec : null; }
  // THE STATE MACHINE of a row (team-2/STEPS.md 3.4; the state is the label's suffix, menu-bar.js:91-98): the legal
  // moves below and nothing else; REFUSED is terminal (only a later refusal, the wafer's, may restate its reason);
  // EMPTY, FAIL and REFUSED never carry an empty why; each move is kept (last 24) so a test can prove the path
  // WAIT -> LOAD -> OK | FAIL, not only the end. An illegal move changes nothing and returns false. (builder)
  var MOVES = { WAIT: STATES, LOAD: STATES, OK: STATES, EMPTY: STATES,
    FAIL: ['WAIT', 'LOAD', 'FAIL', 'REFUSED'], REFUSED: ['REFUSED'] };
  function setState(id, status, why) {
    var r = rt[id]; if (!r) return false;
    if (STATES.indexOf(status) < 0) { why = 'unknown state ' + status; status = 'FAIL'; }
    if (MOVES[r.status] && MOVES[r.status].indexOf(status) < 0) return false;
    why = why == null ? '' : String(why);
    if (!why && (status === 'EMPTY' || status === 'FAIL' || status === 'REFUSED')) why = 'no reason given';
    r.status = status; r.why = why;
    (r.history = r.history || []).push([status, why, Math.round(performance.now())]); if (r.history.length > 24) r.history.shift();
    paintRow(id);
    if (r.rec.preload && (status === 'FAIL' || status === 'REFUSED')) loud(id);
    return true;
  }
  function tagText(id) {
    var r = rt[id]; if (!r) return '';
    return r.status + (r.why ? ' · ' + r.why : '');
  }
  function inspect() {
    var inputs = panel ? panel.querySelectorAll('input[data-ky-layer]') : [];
    var vals = {}, keyless = 0;
    for (var i = 0; i < inputs.length; i++) { var v = inputs[i].getAttribute('data-ky-layer');
      if (!v || !/^layer:[a-z0-9-]+$/.test(v)) keyless++; vals[v] = 1; }
    var n = inputs.length, u = Object.keys(vals).length, want = M ? M.layers.length : -1;
    var states = {}, on = [];
    (M ? M.order : []).forEach(function (id) { if (!rt[id]) return; states[id] = rt[id].status; if (rt[id].on) on.push(id); });
    return { schema: SCHEMA, generation: GEN, layers: n, unique: u, complete: n === u && n === want && keyless === 0,
      on: on, states: states, tags: (M ? M.order : []).reduce(function (o, id) { o[id] = tagText(id); return o; }, {}),
      manifest: manifestWhy, lines_owner: ENGINE ? 'engine' : 'module' };
  }
  function get(id) {
    var r = rt[id]; if (!r) return null;
    var out = JSON.parse(JSON.stringify(r.rec));
    out.on = r.on; out.value = r.value; out.status = r.status; out.why = r.why; out.placed = r.placed; out.total = r.total;
    out.loaded_sha256 = r.loaded_sha256; out.tag = tagText(id); out.history = (r.history || []).slice();
    return out;
  }
  function original(id) { return panel ? panel.querySelector('input[data-ky-layer="layer:' + id + '"]') : null; }
  // the ONLY way a layer flips: click its original (menu-bar.js:1451-1462); the delegated change listener does the rest
  function set(id, on) {
    var el = original(id); if (!el) return false;
    if (el.disabled) return false;
    if (el.checked !== !!on) el.click();
    return true;
  }
  function value(id, v) {
    var r = rt[id]; if (!r) return false;
    if (id === 'lines') {
      if (v && typeof v === 'object') { if ('focus' in v) lines.focus = !!v.focus; if ('query' in v) lines.query = String(v.query || '').trim().toLowerCase(); }
      r.value = { focus: lines.focus, query: lines.query };
      var f = document.getElementById('lyFocus'), q = document.getElementById('lyFind');
      if (ENGINE) {                                                  // the engine's own controls, through their own events
        if (f && f.checked !== lines.focus) { f.checked = lines.focus; f.dispatchEvent(new Event('change', { bubbles: true })); }
        if (q && q.value.trim().toLowerCase() !== lines.query) { q.value = lines.query; q.dispatchEvent(new Event('input', { bubbles: true })); }
      } else {
        if (f) f.checked = lines.focus;
        if (q && q.value.trim().toLowerCase() !== lines.query) q.value = lines.query;
        fillLines();
      }
    } else if (id === 'repos') {
      var ri = -1;
      if (typeof v === 'number') ri = v;
      else if (v) { var s = String(v).toLowerCase(), rs = H.repos;
        var hit = rs.find(function (x) { return x.name.toLowerCase() === s; }) || rs.find(function (x) { return x.name.toLowerCase().indexOf(s) >= 0; });
        ri = hit ? hit.i : -1; }
      r.value = ri >= 0 ? H.repos[ri].name : null;
      if (r.on) { KY.lit.repo = ri; lastRepo = ri; }
    } else if (id === 'periods') {
      r.value = v ? String(v) : null;
      if (r.on) applyPeriod(r.value);
    } else {
      r.value = v == null ? null : v;
    }
    paintRow(id); KY.redraw();
    return true;
  }
  // a layer that arrives with a later module (See Through step 5, elements and spider step 7)
  function register(layer) {
    if (!layer || !layer.id) throw new Error('layers.register: no id');
    var r = rt[layer.id];
    if (!r) throw new Error('layer ' + layer.id + ' not in layers.json');
    var want = moduleId(r.rec.module);
    if (layer.module && want && layer.module !== want) throw new Error('layer ' + layer.id + ' belongs to module ' + want + ', not ' + layer.module);
    if (r.registered) throw new Error('layer ' + layer.id + ' registered twice');
    r.registered = true;
    if (typeof layer.draw === 'function') r.draw = layer.draw;
    if (r.status === 'REFUSED') return api;          // a refusal (licence, format, colour) is never lifted by registering
    if (typeof layer.load === 'function') {
      setState(layer.id, 'LOAD', 'module ' + (layer.module || want));
      Promise.resolve().then(function () { return layer.load(KY); }).then(function (res) {
        res = res || {}; r.placed = res.placed || 0; r.total = res.total || 0;
        if (r.placed) setState(layer.id, 'OK', fmt(r.placed) + ' of ' + fmt(r.total)); else setState(layer.id, 'EMPTY', res.why || 'nothing to place');
        KY.redraw();
      }, function (e) { setState(layer.id, 'FAIL', String(e && e.message || e)); });
    } else if (r.rec.source && r.rec.source.file) { loadSource(layer.id); }
    return api;
  }
  function moduleId(file) { if (!file) return ''; var m = String(file).match(/^(?:\d{12}-)?([a-z0-9-]+?)(?:\.js)?$/); return m ? m[1] : ''; }

  // ======================================================================== SECTION 2: loading, hashing, refusing
  function hex(buf) { var b = new Uint8Array(buf), s = ''; for (var i = 0; i < b.length; i++) s += (b[i] < 16 ? '0' : '') + b[i].toString(16); return s; }
  function fetchBytes(file) {
    var ctl = typeof AbortController === 'function' ? new AbortController() : null;
    var t = setTimeout(function () { if (ctl) ctl.abort(); }, TIMEOUT_MS);
    return fetch(file, { cache: 'no-store', signal: ctl ? ctl.signal : undefined }).then(function (res) {
      if (!res.ok) { var e = new Error(file + ' HTTP ' + res.status); e.http = res.status; throw e; }
      return res.arrayBuffer();
    }).catch(function (e) { if (e && e.http) throw e;
      var x = new Error(file + (e && e.name === 'AbortError' ? ' timed out after ' + (TIMEOUT_MS / 1000) + ' s' : ' did not load (network)')); x.http = 0; throw x; })
      .finally(function () { clearTimeout(t); });
  }
  // fetch, then hash, bytes and feature count against the record (gridatlas@5ec7f62 atlas/index.html:75-81 for data)
  // A recorded hash nobody checks is decoration (team-2/STEPS.md 3.1, galaxies-wafers@fff6fc6: a sha256 per layer file
  // that no root module verifies): a record without a 64-hex sha256, or a browser without crypto.subtle (an insecure
  // origin), is FAIL before a byte is fetched, never an unchecked admission. The digest is compared first, so one
  // changed byte reads "sha256 mismatch" whatever the length; then bytes; then the parse. (builder)
  // A record may name a fallback (the lines record: keys-min.json, NL-009 07 perf, then keys.json, as the base page
  // loads them, index.html loadEdition at kuiper-belt@a72c175). The fallback is tried only when the first file did not
  // load (HTTP, network); a file that loaded and hashed wrong is refused, never replaced by another.
  function verified(id) {
    var r = rt[id], src = r.rec.source;
    return verifiedOne(id, src).catch(function (e) {
      if (!src.fallback || e.http === undefined) throw e;
      return verifiedOne(id, src.fallback).catch(function (e2) { var x = new Error(e2.message + ' (' + e.message + ')'); x.http = e2.http; throw x; });
    });
  }
  function verifiedOne(id, src) {
    var r = rt[id], file = src.file, want = String(src.sha256 || '').toLowerCase();
    r.lastFile = file;
    setState(id, 'LOAD', file);
    if (READS.indexOf(file) < 0) return Promise.reject(new Error(file + ' is not in the module\'s reads, refused'));
    if (!/^[0-9a-f]{64}$/.test(want)) return Promise.reject(new Error('record has no sha256 for ' + file + ', unhashed data refused'));
    if (!(window.crypto && crypto.subtle && typeof crypto.subtle.digest === 'function'))
      return Promise.reject(new Error('crypto.subtle unavailable (not a secure context), unhashed data refused'));
    return fetchBytes(file).then(function (buf) {
      return crypto.subtle.digest('SHA-256', buf).then(function (d) {
        var sha = hex(d); r.loaded_sha256 = sha;
        if (sha !== want) throw new Error('sha256 mismatch');
        if (typeof src.bytes === 'number' && buf.byteLength !== src.bytes) throw new Error('bytes ' + buf.byteLength + ' ≠ record ' + src.bytes);
        var j; try { j = JSON.parse(new TextDecoder('utf-8').decode(buf)); } catch (e) { throw new Error(file + ' is not JSON'); }
        return j;
      });
    });
  }
  function admissible(k) { return Number.isFinite(k) && k >= 0 && k < H.SPACE; }   // index.html:632, the edition's predicate
  // a generic code-feature-collection.v1 layer: geometry carries keys, never coordinates (galaxies-wafers README.md:11-18)
  function loadSource(id) {
    var r = rt[id];
    return verified(id).then(function (j) {
      var fs = (j && j.features) || [];
      if (r.rec.source.features && fs.length !== r.rec.source.features) throw new Error('features ' + fs.length + ' ≠ record ' + r.rec.source.features);
      var pts = [], segs = [], bad = 0;
      fs.forEach(function (f) { var g = f && f.geometry; if (!g) { bad++; return; }
        if (g.type === 'Point' && admissible(g.key)) pts.push(H.keyPlace(g.key));
        else if (g.type === 'LineString' && g.keys && g.keys.length === 2 && admissible(g.keys[0]) && admissible(g.keys[1])) segs.push([H.keyPlace(g.keys[0]), H.keyPlace(g.keys[1])]);
        else bad++; });
      r.placed = pts.length + segs.length; r.total = fs.length;
      if (!r.draw) r.draw = function (o2) { drawFeatures(o2, r.rec.colour, pts, segs); };
      if (r.placed) setState(id, 'OK', fmt(r.placed) + ' of ' + fmt(r.total) + (bad ? ', ' + fmt(bad) + ' outside SPACE, counted, not placed' : ''));
      else setState(id, 'EMPTY', fs.length ? 'no feature admitted (' + fmt(bad) + ' outside SPACE)' : 'the file holds no features');
      KY.redraw();
    }).catch(function (e) { setState(id, 'FAIL', String(e.message || e)); });
  }
  function scr(p) { var c = KY.cam, o = H.o2.canvas; return [(p[0] - c.x) * c.zoom + o.width / 2, o.height / 2 - (p[1] - c.y) * c.zoom]; }
  function drawFeatures(o2, colour, pts, segs) {
    o2.strokeStyle = colour; o2.fillStyle = colour; o2.lineWidth = 1; o2.globalAlpha = 0.8;
    segs.forEach(function (s) { var a = scr(s[0]), b = scr(s[1]); o2.beginPath(); o2.moveTo(a[0], a[1]); o2.lineTo(b[0], b[1]); o2.stroke(); });
    pts.forEach(function (p) { var x = scr(p); o2.beginPath(); o2.arc(x[0], x[1], 2.6, 0, 6.2832); o2.fill(); });
    o2.globalAlpha = 1;
  }
  // a preload layer that fails says so in the row, the heading and an alert (09-robust.md:25-29); the wafer draws on
  function loud(id) {
    var r = rt[id], file = r.lastFile || (r.rec.source && r.rec.source.file) || r.rec.label;
    var http = r.status === 'FAIL' && /HTTP \d+|did not load|timed out/.test(r.why);   // a refusal is not a failed load
    H.big.textContent = String(file).toUpperCase() + (http ? ' DID NOT LOAD' : ' REFUSED') + ' · ' + r.status + ' · ' + r.why;
    alertLine(r.rec.label + ' layer ' + r.status + ' · ' + r.why + ' · the wafer still draws; nothing of this layer is placed');
  }
  // the shared #refuse[role=alert] strip, one line under our own slot (KY.refuse, hook table rev 3, HOOKS.md)
  function alertLine(text) { KY.refuse('LAYERS · ' + text, ID); }

  // ======================================================================== SECTION 3: the WAFER panel
  var CSS = ''
    + '#layers{display:none;position:fixed;left:0;right:0;width:auto;max-width:none;z-index:11;background:#090c13f2;border:1px solid #1d6470;'
    + 'border-radius:0 0 6px 6px;padding:6px 10px 8px;pointer-events:auto;text-align:left;overscroll-behavior:contain;'
    + 'max-height:var(--ky-layers-max,80vh);overflow:hidden;flex-direction:column}'
    + '#layers.gm-open,#layers.ky-in-shell{display:flex}'
    + '#layers.ky-typing .ky-ly-rows{display:none}'
    + '#layers.ky-engine{display:flex;position:static;border:0;padding:0;margin:4px 0;background:transparent;max-height:none;height:auto;min-height:0}'
    + '#layers.ky-engine .ky-ly-rows{overflow:visible;min-height:0}#layers.ky-engine.ky-typing{display:none}'
    + '#layers.ky-in-shell{position:static;border:0;padding:0;background:transparent;max-height:none;height:var(--ky-layers-fit,auto);min-height:240px}'
    + '@media (min-width:641px){#layers{right:auto;width:min(720px,96vw)}}'
    + '#layers .ky-ly-rows{flex:none;min-height:88px;overflow-y:auto;overscroll-behavior:contain}'
    + '#layers .ky-ly-g{color:#2ee6e6;letter-spacing:.12em;text-transform:uppercase;font-size:10px;padding:4px 2px 0;line-height:16px}'
    + '#layers label.ky-ly{position:relative;display:flex;align-items:center;gap:8px;min-height:44px;padding:0 4px;border:0;box-shadow:inset 0 1px #121a26;'
    + 'color:#8fb3bd;cursor:pointer;-webkit-tap-highlight-color:transparent;user-select:none}'
    + '#layers label.ky-ly input[data-ky-layer]{position:absolute;inset:0;width:100%;height:100%;margin:0;opacity:0;cursor:pointer;z-index:1}'
    + '#layers label.ky-ly .bx{flex:none;width:20px;height:20px;border:1px solid #12414a;border-radius:3px;background:#090c13}'
    + '#layers label.ky-ly input:checked ~ .bx{background:#22ee77;border-color:#22ee77;box-shadow:inset 0 0 0 3px #090c13}'
    + '#layers label.ky-ly input:disabled ~ .bx{border-style:dashed;opacity:.5}'
    + '#layers label.ky-ly:has(input:checked){color:#d5dcea}'
    + '#layers label.ky-ly .sw{flex:none;width:10px;height:10px;border-radius:50%}'
    + '#layers label.ky-ly .tx{flex:1 1 auto;min-width:0;display:flex;flex-direction:column;padding:4px 0;line-height:1.3}'
    + '#layers label.ky-ly .nm{white-space:normal;overflow-wrap:anywhere}'
    + '#layers label.ky-ly .st{color:#7d8799;font-size:11px;white-space:normal;overflow-wrap:anywhere}'
    + '#layers label.ky-ly .st[data-s=OK]{color:#22ee77}#layers label.ky-ly .st[data-s=FAIL],#layers label.ky-ly .st[data-s=REFUSED]{color:#ffb000}'
    + '#layers label.ky-ly .st[data-s=LOAD],#layers label.ky-ly .st[data-s=WAIT]{color:#2ee6e6}'
    + '#layers label.ky-ly.star .nm{font-size:16px;letter-spacing:.06em;color:#2ee6e6;text-transform:uppercase}'
    + '#layers .ky-ly-why{color:#ffb000;padding:6px 2px;white-space:pre-wrap}'
    // NL-009 05-lines: the controls stay put, only the list scrolls inside itself (finding 1); 44 px targets (2);
    // 16 px filter (3); a clear control and Escape (4); a count line (6); grouped by repository, sticky, foldable (7)
    + '#linesctl{flex:none;display:flex;flex-direction:column;gap:2px;margin-top:4px;border-top:1px solid #12414a;padding-top:4px}'
    + '#linesctl .lyrow{display:flex;gap:6px;align-items:center;flex-wrap:nowrap}'
    + '#linesctl label{display:flex;align-items:center;gap:6px;min-height:44px;padding:0 4px 0 2px;color:#8fb3bd;cursor:pointer;user-select:none;flex:1 1 auto;min-width:0}'
    + '#linesctl label:has(input:checked){color:#d5dcea}'
    + '#linesctl input[type=checkbox]{width:20px;height:20px;margin:0;accent-color:#22ee77;flex:none}'
    + '#linesctl #lyFind{flex:1 1 120px;min-width:0;min-height:44px;background:#090c13;color:#d5dcea;border:1px solid #12414a;padding:8px 10px;font:inherit;font-size:16px;border-radius:0;appearance:none}'
    + '#linesctl #lyFind:focus{outline:none;border-color:#2ee6e6}'
    + '#linesctl button{min-height:44px;min-width:44px;background:#0b1a20;color:#8fb3bd;border:1px solid #12414a;padding:0 10px;font:inherit;text-transform:uppercase;cursor:pointer;touch-action:manipulation;flex:none}'
    + '#linesctl button:active{border-color:#2ee6e6;color:#2ee6e6}'
    + '#lyClear{display:none!important;font-size:20px;line-height:1;padding:0}#lyClear.on{display:inline-block!important}'
    + '#lycount{color:#7d8799;padding:2px 2px 0;line-height:1.4}'
    // a short screen (landscape, 360 px tall): the rows shrink and scroll themselves so every row stays reachable (builder)
    + '@media (max-height:600px){#layers .ky-ly-rows{flex:0 1 auto}#layers #lineslist{flex:1 1 0;min-height:44px}}'
    + '#lineslist{flex:1 1 auto;min-height:88px;overflow-y:auto;overscroll-behavior:contain;-webkit-overflow-scrolling:touch}'
    + '#lineslist .lg{position:sticky;top:0;z-index:1;display:flex;align-items:center;gap:8px;min-height:44px;padding:4px 8px;background:#0b1a20;color:#2ee6e6;'
    + 'border-top:1px solid #12414a;cursor:pointer;text-transform:uppercase;letter-spacing:.06em;touch-action:manipulation;user-select:none}'
    + '#lineslist .lg .n{color:#7d8799;letter-spacing:0;text-transform:none}#lineslist .lg.focus{color:#22ee77}#lineslist .lg .ch{width:12px;color:#7d8799}'
    + '#lineslist .ln{content-visibility:auto;contain-intrinsic-size:auto 62px;min-height:44px;padding:5px 8px;border-top:1px solid #121a26;cursor:pointer;color:#7d8799;font-size:12px;overflow-wrap:anywhere}'
    + '#lineslist .ln code{display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden;color:#ffffff;white-space:pre-wrap;font:inherit;font-weight:600}'
    + '#lineslist .ln b{color:#d5dcea;font-weight:600}#lineslist .ln.focus b{color:#22ee77}#lineslist .ln.sel{background:rgba(255,43,214,.12)}'
    + '#lineslist .ln .t{display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}';

  function buildPanel() {
    panel = document.createElement('div'); panel.id = 'layers'; panel.className = 'gm-panel ky-layers';
    panel.setAttribute('aria-label', 'WAFER: the layer registry');
    var st = document.createElement('style'); st.id = 'ky-layers-style';
    // scoped above the shell's own '#kuiper-menu-bar .gm-panel #linesctl…' rules (kuiper-shell.js:156-160), so ours win
    st.textContent = CSS.replace(/(^|[},])(#linesctl|#lineslist|#lyClear|#lycount)/g, '$1body #layers.ky-layers $2'); panel.appendChild(st);
    var rows = document.createElement('div'); rows.className = 'ky-ly-rows'; rows.innerHTML = '<div class="ky-ly-why">' + esc(manifestWhy) + '</div>';
    panel.appendChild(rows);
    var host = document.querySelector('.gm-group[data-group="layers"]');   // team 1's shell: WAFER > layers group
    var elist = ENGINE ? document.getElementById('lineslist') : null;
    if (elist) {                                                     // the engine's LINES block: after its filter, before its list
      panel.classList.remove('gm-panel'); panel.classList.add('ky-engine'); elist.parentNode.insertBefore(panel, elist); panelName = 'engine';
    } else if (host) { panel.classList.remove('gm-panel'); panel.classList.add('ky-in-shell'); host.appendChild(panel); panelName = 'shell'; }   // never gm-open itself: an open panel is the shell's, and line-card hides the card only while one is open
    else {
      document.body.appendChild(panel);
      // without the shell, the Edition 4 LINES title (index.html:702) opens the WAFER panel once the page's #lines is
      // deleted (handoff/03-layers patch); the title's words stay team 1's (R2). No such title: a panel named wafer.
      var t = document.querySelector('#bar .gm-title[data-panel="lines"]');
      try { if (!t) throw 0; KY.panels.add('lines', panel, 'WAFER'); panelName = 'lines'; }
      catch (e) { KY.panels.add('wafer', panel, 'WAFER'); panelName = 'wafer'; }
    }
    // one delegated change listener: the single implementation of on/off (menu-bar.js:1451-1462, :1723-1726)
    panel.addEventListener('change', function (e) {
      var t = e.target; if (!t || !t.matches('input[data-ky-layer]')) return;
      apply(t.getAttribute('data-ky-layer').slice(6), t.checked);
    });
    panel.addEventListener('keydown', function (e) { if (e.target && e.target.id !== 'lyFind') return; e.stopPropagation(); });
    if (panelName === 'engine') return;                              // the engine's block sizes itself; its rows are its own
    // the panel height comes from the real viewport, keyboard included (05-lines finding 5)
    sizePanel(); addEventListener('resize', sizePanel);
    if (window.visualViewport) visualViewport.addEventListener('resize', sizePanel);
    // when the panel opens, show where you are (05-lines finding 7); no wrap of setPanel (ROADMAP 4.8)
    var opener = panelName === 'shell' ? (panel.closest('.gm-panel') || panel) : panel;   // the element whose gm-open means "shown"
    new MutationObserver(function () { if (opener.classList.contains('gm-open')) { sizePanel(); requestAnimationFrame(sizePanel); fillLines(true); } })
      .observe(opener, { attributes: true, attributeFilter: ['class'] });
    // the shell shows its panel by its own rule (not always a gm-open on the panel itself): watch it being laid out
    if (panelName === 'shell' && typeof ResizeObserver === 'function') {
      var shown = false;
      new ResizeObserver(function () { var h = opener.getBoundingClientRect().height;
        if (h && !shown) { sizePanel(); requestAnimationFrame(sizePanel); fillLines(true); } shown = !!h; }).observe(opener);
    }
    // rows answer Enter and Space as a button does (NL-009 04 touch, as team 4's patch gave the Edition 4 rows)
    panel.addEventListener('keydown', function (e) { var row = e.target.closest && e.target.closest('#lineslist [data-i], #lineslist [data-g]');
      if (row && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); e.stopPropagation(); row.click(); } });
  }
  function closePanel() {
    if (panelName === 'shell') { var sh = (KY.modules['kuiper-shell'] && KY.modules['kuiper-shell'].api) || window.__KUIPER_SHELL__; if (sh && typeof sh.close === 'function') sh.close(); return; }
    if (panel.classList.contains('gm-open')) KY.panels.set(panelName);
  }
  function sizePanel() {
    if (!panel) return;
    if (panelName === 'shell') {                 // the shell's panel must not scroll as well: fill exactly what it has left
      var sp = panel.closest('.gm-panel'); if (!sp) return;
      var pr = sp.getBoundingClientRect(), lr = panel.getBoundingClientRect();
      if (!pr.height) return;                                        // measured only while the shell panel is shown
      var pad = parseFloat(getComputedStyle(sp).paddingBottom) || 0;
      var vh0 = Math.min(innerHeight, window.visualViewport ? visualViewport.height : innerHeight);
      var maxH = Math.min(parseFloat(getComputedStyle(sp).maxHeight) || vh0, vh0 - pr.top);
      var fit = Math.max(240, Math.floor(maxH - (lr.top - pr.top + sp.scrollTop) - pad - 2));
      panel.style.setProperty('--ky-layers-fit', fit + 'px');
      var over = sp.scrollHeight - sp.clientHeight;                 // borders, margins, rounding: measured, then taken off
      if (over > 0) panel.style.setProperty('--ky-layers-fit', Math.max(240, fit - over) + 'px');
      return;
    }
    var vh = Math.min(innerHeight, window.visualViewport ? visualViewport.height : innerHeight);
    var top = parseFloat(panel.style.top) || 46, avail = Math.max(160, vh - top - 4);
    panel.style.setProperty('--ky-layers-max', Math.round(innerWidth <= 640 ? avail : Math.min(avail, vh * 0.8)) + 'px');
  }
  function fillRows() {
    var host = panel.querySelector('.ky-ly-rows'), html = [], group = null;
    M.order.forEach(function (id) {
      var r = rt[id].rec;
      if (r.group !== group) { group = r.group; html.push('<div class="ky-ly-g">' + esc(group) + '</div>'); }
      html.push('<label class="ky-ly' + (r.star ? ' star' : '') + '" data-id="' + esc(id) + '">'
        + '<input type="checkbox" data-ky-layer="' + esc(r.key) + '" aria-label="' + esc(r.label) + '">'
        + '<span class="bx" aria-hidden="true"></span><span class="sw" style="background:' + esc(r.colour) + '" title="' + esc(r.meaning) + '"></span>'
        + '<span class="tx"><span class="nm">' + esc(r.label) + '</span><span class="st" data-s="WAIT">WAIT</span></span></label>');
      if (id === 'lines' && !ENGINE) html.push(LINES_CTL);
    });
    host.innerHTML = html.join('');
    M.order.forEach(function (id) { var el = original(id); el.checked = !!rt[id].on; paintRow(id); });
    if (ENGINE) wireEngineLines(); else wireLines();
  }
  function paintRow(id) {
    var r = rt[id]; if (!panel || !r) return;
    var lab = panel.querySelector('label.ky-ly[data-id="' + id + '"]'); if (!lab) return;
    var st = lab.querySelector('.st'); st.setAttribute('data-s', r.status);
    st.textContent = tagText(id);
    var inp = lab.querySelector('input'); inp.checked = !!r.on; inp.disabled = r.status === 'REFUSED';
    lab.setAttribute('aria-label', r.rec.label + ' · ' + tagText(id));
  }

  // apply an on/off that came through the original
  function apply(id, on) {
    var r = rt[id]; if (!r) return;
    r.on = !!on;
    if (id === 'repos') { if (!on) { KY.lit.repo = -1; lastRepo = -1; } else if (r.value) value('repos', r.value); }
    if (id === 'periods') { if (!on) { KY.lit.period = null; lastK0 = -1; } else if (r.value) applyPeriod(r.value); }
    if (id === 'lines') { if (ENGINE) engineLines(on); else { if (!on) { lines.sel = -1; } fillLines(); } }
    if (on && !r.loaded && !r.rec.preload && r.status !== 'REFUSED') load(id);
    refreshWaferTags(); paintRow(id); writeURL(); KY.redraw();
  }

  // ======================================================================== SECTION 4: the verified-lines layer
  // ENGINE LINES (Edition 9): the page's #lyAll is the engine's switch of the same layer; the row and it follow each
  // other, and a layer whose data failed its sha256 is not drawn by the engine either
  function engineLines(on) {
    var all = document.getElementById('lyAll'); if (!all) return;
    var want = !!on && !(rt.lines && rt.lines.status === 'FAIL');
    if (all.checked !== want) { all.checked = want; all.dispatchEvent(new Event('change', { bubbles: true })); }
  }
  function wireEngineLines() {
    var all = document.getElementById('lyAll'), q = document.getElementById('lyFind');
    if (all) all.addEventListener('change', function () {
      var r = rt.lines; if (!r) return;
      if (all.checked && r.status === 'FAIL') { engineLines(false); return; }
      if (r.on === all.checked) return;
      r.on = all.checked; paintRow('lines'); writeURL();
    });
    // the filter is the engine's: while it has the focus (the keyboard is up) the rows fold away so the list keeps the
    // room it has in Edition 9; they return 350 ms after it loses the focus, so a row tapped after typing does not move
    // under the finger before its click (05-lines F5), and a query left in the field never hides the rows
    if (q) {
      var typing = function () { panel.classList.toggle('ky-typing', document.activeElement === q); };
      q.addEventListener('focus', typing);
      q.addEventListener('blur', function () { setTimeout(typing, 350); });
    }
  }
  var LINES_CTL = '<div id="linesctl">'
    + '<div class="lyrow"><label><input type="checkbox" id="lyFocus"> gridatlas + data centres only</label>'
    + '<button type="button" data-ky-step="1" aria-label="next verified line">next</button><button type="button" data-ky-step="-1" aria-label="previous verified line">prev</button></div>'
    + '<div class="lyrow"><input id="lyFind" type="text" inputmode="search" enterkeyhint="search" autocomplete="off" autocapitalize="off" autocorrect="off" spellcheck="false" placeholder="filter: repository, file or title" aria-label="filter the verified lines">'
    + '<button type="button" id="lyClear" aria-label="clear the filter">×</button></div>'
    + '<div id="lycount" aria-live="polite"></div></div><div id="lineslist"></div>';
  function wireLines() {
    var f = document.getElementById('lyFocus'), q = document.getElementById('lyFind'), c = document.getElementById('lyClear');
    var ctl = document.getElementById('linesctl'), list = document.getElementById('lineslist');
    // the controls and the list are inside .ky-ly-rows, but the list must be the one scroller: move them after it
    panel.appendChild(ctl); panel.appendChild(list);
    f.addEventListener('change', function () { value('lines', { focus: f.checked }); KY.redraw(); });
    // while the filter is in use (focused, or holding a query) the seven layer rows fold away, so the controls and the list
    // have the panel; they return when the field is empty and left. No reflow under a finger: a row tapped after typing
    // keeps the fold, because the query is still there (05-lines F5; journey lines-filter at 360 x 780)
    function typing() { panel.classList.toggle('ky-typing', document.activeElement === q || !!q.value.trim()); }
    q.addEventListener('focus', typing); q.addEventListener('blur', function () { setTimeout(typing, 0); });
    q.addEventListener('input', function () { lines.query = q.value.trim().toLowerCase(); rt.lines.value = { focus: lines.focus, query: lines.query }; typing(); fillLines(); });
    q.addEventListener('keydown', function (e) { e.stopPropagation();
      if (e.key === 'Escape') { if (q.value) { q.value = ''; lines.query = ''; typing(); fillLines(); } else q.blur(); e.preventDefault(); }
      else if (e.key === 'Enter') q.blur(); });
    c.addEventListener('click', function (e) { e.stopPropagation(); q.value = ''; lines.query = ''; rt.lines.value = { focus: lines.focus, query: '' }; q.blur(); typing(); fillLines(); });
    ctl.addEventListener('click', function (e) { var b = e.target.closest('[data-ky-step]'); if (!b) return; e.stopPropagation(); step(+b.getAttribute('data-ky-step')); });
    list.addEventListener('click', function (e) {
      var g = e.target.closest('[data-g]');
      if (g) { e.stopPropagation(); if (!lines.query) { var n = g.getAttribute('data-g'); lines.folded[n] = !lines.folded[n]; fillLines(); } return; }
      var row = e.target.closest('[data-i]'); if (!row) return;
      e.stopPropagation(); var i = +row.getAttribute('data-i');
      closePanel();                                                     // LINES closes on pick (Edition 4)
      openLine(i); fly(lines.placed[i]);
    });
  }
  // the list row shows the line's first 600 characters verbatim and says how many follow: one keys.json line is
  // 1,240,449 characters (a minified JSON line), which rendered whole made a 723,252 px row on a Galaxy S24 and 1.2 MB of
  // DOM text on every filter keystroke; the card keeps the whole line (builder, measured 22:05 UTC)
  function clipLine(t) { t = t == null ? '' : String(t); return t.length > 600 ? t.slice(0, 600) + ' … (+' + fmt(t.length - 600) + ' characters, the whole line is on its card)' : t; }
  function visibleLine(b) { return rt.lines.on && (!lines.focus || b.class === 'focus'); }
  function fillLines(scrollSel) {
    var list = document.getElementById('lineslist'), cnt = document.getElementById('lycount'), clr = document.getElementById('lyClear');
    if (!list || !rt.lines) return;
    if (clr) clr.classList.toggle('on', !!lines.query);
    var P = lines.placed, total = P.length, groups = {}, shown = 0, repos = {};
    P.forEach(function (b, i) { repos[b.repo] = 1; if (!visibleLine(b)) return;
      var hay = (b.repo + ' ' + b.path + ' ' + b.title + ' ' + (b.line_text || '')).toLowerCase();
      if (lines.query && hay.indexOf(lines.query) < 0) return;
      (groups[b.repo] = groups[b.repo] || []).push(i); shown++; });
    var names = Object.keys(groups).sort(function (a, b) { return groups[b].length - groups[a].length || (a < b ? -1 : 1); });
    var card = KY.modules && KY.modules['line-card'] && KY.modules['line-card'].api, html = [];
    names.forEach(function (n) {
      var idx = groups[n].sort(function (a, b) { var x = P[a], y = P[b]; return x.path < y.path ? -1 : x.path > y.path ? 1 : x.line - y.line; });
      var focus = P[idx[0]].class === 'focus', folded = !lines.query && lines.folded[n] && !(scrollSel && idx.indexOf(lines.sel) >= 0);
      if (scrollSel && idx.indexOf(lines.sel) >= 0) lines.folded[n] = false;
      html.push('<div class="lg' + (focus ? ' focus' : '') + '" data-g="' + esc(n) + '" role="button" tabindex="0" aria-expanded="' + (folded ? 'false' : 'true') + '"><span class="ch">' + (folded ? '▸' : '▾') + '</span>' + esc(n) + ' <span class="n">' + idx.length + '</span></div>');
      if (folded) return;
      idx.forEach(function (i) { var b = P[i], cls = 'ln' + (i === lines.sel ? ' sel' : '') + (b.class === 'focus' ? ' focus' : '');
        if (card && typeof card.rowInner === 'function') { html.push('<div class="' + cls + ' lc-row" data-i="' + i + '" role="button" tabindex="0">' + card.rowInner(b) + '</div>'); return; }   // Opus 2's row content, our .ln[data-i]
        // the line of code is the header (ROADMAP law 2): line_text first, verbatim; the key follows; the names after
        html.push('<div class="' + cls + '" data-i="' + i + '" role="button" tabindex="0"><code>' + esc(clipLine(b.line_text)) + '</code><b>' + esc(b.path) + ':' + b.line + '</b> · key ' + fmt(b.key)
          + '<div class="t">' + esc(b.title) + '</div></div>'); });
    });
    list.innerHTML = html.join('') || '<div class="ln">' + (rt.lines.on ? (total ? 'no line matches' : esc(tagText('lines'))) : 'layer off') + '</div>';
    if (cnt) cnt.textContent = !rt.lines.on ? '0 of ' + fmt(total) + ' rows · layer off · ' + fmt(total) + ' lines hidden'
      : fmt(shown) + ' of ' + fmt(total) + ' rows' + (lines.query ? ' match "' + lines.query + '"' : '') + (lines.focus ? ' · gridatlas + data centres only' : '')
        + (!lines.query && !lines.focus ? ' · ' + Object.keys(repos).length + ' repositories' : '');
    if (scrollSel && lines.sel >= 0) { var s = list.querySelector('[data-i="' + lines.sel + '"]'); if (s) s.scrollIntoView({ block: 'center' }); }
  }
  function loadLines() {
    var r = rt.lines;
    return verified('lines').then(function (j) {
      var bodies = j.bodies || j, summary = j.summary || {};
      if (!Array.isArray(bodies)) throw new Error('keys.json has no bodies');
      if (r.rec.source.features && bodies.length !== r.rec.source.features) throw new Error('features ' + bodies.length + ' ≠ record ' + r.rec.source.features);
      lines.ED = bodies; lines.meta = summary;
      // the edition's admission predicate, unchanged (index.html:632-633); placed by keyPlace and nothing else
      lines.placed = bodies.filter(function (b) { return b.on_wafer && b.verified && admissible(b.key); })
        .map(function (b) { var p = H.keyPlace(b.key); return Object.assign({}, b, { x: p[0], y: p[1] }); });
      r.placed = lines.placed.length; r.total = bodies.length; r.loaded = true;
      if (!r.placed) setState('lines', 'EMPTY', 'no body admitted of ' + fmt(bodies.length));
      else setState('lines', 'OK', fmt(r.placed) + ' of ' + fmt(r.total));
      if (ENGINE) { engineLines(r.on); KY.redraw(); return; }       // the engine names and draws them (index.html loadEdition)
      H.big.textContent = edName() + ' · ' + fmt(r.placed) + ' verified lines lit';
      H.sub.textContent = 'Edition 1 verified ' + fmt(bodies.length) + ' lines of the estate (354 keyed findings, 495 keys re-resolved; see ../202610311905/). '
        + 'Here each is a green spark at its own key on the one wafer: ' + H.sub.textContent;
      fillLines(); KY.redraw();
    }).catch(function (e) { lines.ED = []; lines.placed = []; r.loaded = true; setState('lines', 'FAIL', String(e.message || e));
      if (ENGINE) engineLines(false); else fillLines(); KY.redraw(); });
  }
  function edScreen(b) { return scr([b.x, b.y]); }
  function drawLines(o2) {
    var hud = H.hud, P = lines.placed;
    if (!rt.lines.on) { hud.textContent += '\n' + edName() + ' · verified lines layer off'; return; }
    if (!P.length) { hud.textContent += '\n' + edName() + ' · ' + tagText('lines'); return; }
    var on = 0, W = o2.canvas.width, Hh = o2.canvas.height;
    for (var i = 0; i < P.length; i++) { var b = P[i]; if (lines.focus && b.class !== 'focus') continue;
      var p = edScreen(b), x = p[0], y = p[1];
      if (x < -8 || y < -8 || x > W + 8 || y > Hh + 8) continue; on++;
      var sel = i === lines.sel, focus = b.class === 'focus';
      o2.beginPath(); o2.arc(x, y, sel ? 6 : (focus ? 3.2 : 2.6), 0, 6.2832);
      o2.fillStyle = sel ? 'rgba(255,43,214,.95)' : (focus ? 'rgba(34,238,119,.95)' : 'rgba(34,238,119,.70)'); o2.fill();
      if (sel) { o2.strokeStyle = 'rgba(255,43,214,.9)'; o2.lineWidth = 1.5; o2.beginPath(); o2.arc(x, y, 14, 0, 6.2832); o2.stroke(); } }
    var notOn = lines.ED.length - P.length;
    hud.textContent += '\n' + edName() + ' · ' + fmt(P.length) + ' verified lines on this wafer, ' + fmt(on) + ' in view'
      + (notOn ? ' · ' + fmt(notOn) + ' not on the wafer (named in keys.json), counted, not placed' : '')
      + ' · bright green: gridatlas and the data-centre repositories · green: the rest of the estate';
  }
  // the card is Opus team 2's (line-card); the Edition 4 card (index.html:655-674) is the fallback when it is absent
  function openLine(i) {
    var b = lines.placed[i]; if (!b) return;
    var a = H.address(b.key), lc = KY.modules && KY.modules['line-card'] && KY.modules['line-card'].api;
    lines.sel = i;
    if (lc && typeof lc.show === 'function') lc.show(b, { index: i, of: lines.placed.length, onclose: function () { lines.sel = -1; KY.sel.target = null; } });
    else fallbackCard(b, i, a);
    if (a && !a.silent && rt.repos && rt.repos.on) { KY.lit.repo = a.c.repo; lastRepo = a.c.repo; }
    else if (a && !a.silent) KY.lit.repo = a.c.repo;
    KY.sel.target = { x: b.x, y: b.y }; KY.redraw();
  }
  var cardWired = false;
  function fallbackCard(b, i, a) {
    var card = H.card;
    card.style.display = 'block'; card.classList.remove('open');
    card.setAttribute('role', 'region'); card.setAttribute('aria-label', 'verified line'); card.setAttribute('aria-live', 'polite');
    card.innerHTML = '<button class="cx" aria-label="close">×</button>'
      + (b.line_text != null ? '<code style="display:block;color:#fff;white-space:pre-wrap;font-weight:600">' + esc(b.line_text) + '</code>' : '')
      + esc(b.repo) + '@' + esc(String(b.commit).slice(0, 7)) + ' ' + esc(b.path) + ':' + b.line + ' · key ' + fmt(b.key)
      + '\n<b>' + esc(b.title) + '</b>  <span style="color:var(--dim)">' + fmt(i + 1) + ' of ' + fmt(lines.placed.length) + '</span>'
      + (b.quote ? '<div class="cq">' + esc(b.quote) + '</div>' : '')
      + '<a href="' + esc(b.destination) + '" target="_blank" rel="noopener">open on GitHub at ' + esc(String(b.commit).slice(0, 7)) + '</a>'
      + '  ·  <button class="ct" aria-expanded="false">details</button>'
      + '<div class="cd">' + (b.pattern ? 'pattern: ' + esc(b.pattern) + '\n' : '') + 'found by ' + esc(b.worker) + ' ' + esc(b.finding) + ', verified by a controller\n' + H.describe(a) + '</div>';
    // its controls are answered by guardCard()
  }
  // fly so the spark lands in the clear space: under the bar, above the card (index.html:676-680)
  // NL-009 03 camera, as the integrator's base gives it (index.html edBand/edAim at kuiper-belt@a72c175): the clear band is
  // under the bar and any open panel in the top half, above the card; aimed again on the next frame, once the card is laid out
  function band() {
    var s = H.safeBox(), top = s.y0, bot = innerHeight - 8, card = H.card, open = document.querySelectorAll('.gm-open');
    for (var i = 0; i < open.length; i++) { var r = open[i].getBoundingClientRect(); if (r.height > 0 && r.top < innerHeight / 2) top = Math.max(top, r.bottom + 8); }
    if (card.style.display === 'block') { var c = card.getBoundingClientRect(); if (c.height > 0) bot = Math.min(bot, c.top - 8); }
    if (bot < top + 24) bot = top + 24;
    return { x0: s.x0, x1: s.x1, y0: top, y1: bot };
  }
  function aim(b, z) { var a = band(), mx = (a.x0 + a.x1) / 2, my = (a.y0 + a.y1) / 2; return [b.x - (mx - innerWidth / 2) / z, b.y + (my - innerHeight / 2) / z]; }
  // as the base page's edFly (kuiper-belt@a72c175 index.html, ED_MINBAND, tween.dur, edKeep): a panel that leaves a band
  // under 96 px is closed by the pick; a short hop is quick (300-900 ms by screen distance, 1 ms for reduced motion);
  // the spark is kept inside the band when the card resizes or the phone turns. The duration is passed as flyTo's
  // fourth argument: the engine's flyTo (index.html:269) takes three today, so until the hook table forwards it the fly
  // lasts the engine's 900 ms (REQUEST to Opus 4/10 on #10).
  var MINBAND = 96, flown = null, flyingUntil = 0;
  function hop(b, z) {
    var p = edScreen(b), far = Math.hypot(p[0] - innerWidth / 2, p[1] - innerHeight / 2) + Math.abs(Math.log2(z / KY.cam.zoom)) * 120;
    return matchMedia('(prefers-reduced-motion: reduce)').matches ? 1 : Math.max(300, Math.min(900, 300 + far * 0.6));
  }
  function go(x, y, z, dur) { KY.cam.atHome = false; flyingUntil = performance.now() + Math.max(dur, 900) + 50; H.flyTo(x, y, z, dur); }
  function fly(b) {
    if (!b) return;
    var g = band(); if (g.y1 - g.y0 < MINBAND && document.querySelector('.gm-open')) closePanel();
    var z = 14, t = aim(b, z), dur = hop(b, z); flown = b;
    go(t[0], t[1], z, dur);                                         // atHome false first: a resize must not re-home (IX:248, :679)
    requestAnimationFrame(function () { if (flown !== b) return; var u = aim(b, z); go(u[0], u[1], z, dur); });
  }
  function keep() {
    if (performance.now() < flyingUntil || lines.sel < 0 || !flown || H.card.style.display !== 'block' || document.querySelector('.gm-open')) return;
    var b = lines.placed[lines.sel]; if (!b) return; var a = band(), p = edScreen(b);
    if (p[0] >= a.x0 + 12 && p[0] <= a.x1 - 12 && p[1] >= a.y0 + 12 && p[1] <= a.y1 - 12) return;
    var z = KY.cam.zoom, t = aim(b, z); go(t[0], t[1], z, 350);
  }
  function step(dir) {
    if (ENGINE) { dispatchEvent(new KeyboardEvent('keydown', { key: dir < 0 ? 'E' : 'e' })); return; }   // the engine's e / E
    var P = lines.placed, n = P.length; if (!n || !rt.lines.on) return;
    var i = lines.sel;
    for (var t = 0; t < n; t++) { i = (i + dir + n) % n; if (visibleLine(P[i])) break; }
    openLine(i); fly(P[i]); fillLines();
  }
  // The page closes the card on any click on it (index.html:603 `card.addEventListener('click', () => { card.style.display =
  // 'none' …`). Edition 4's capture listener on #card (index.html:668-674, cut by delete-moved.py) stopped that; this is it,
  // moved: a click inside #card (line-card's .lc-* controls included) never reaches the page's close or any pick. Line-card
  // hears the click first (its listener is on window, capture phase) and does details, × and the link itself.
  function guardCard() {
    H.card.addEventListener('click', function (e) {
      if (!e.target || !H.card.contains(e.target)) return;
      var lc = KY.modules && KY.modules['line-card'];
      if (!lc) {                                                     // the Edition 4 fallback card: its own controls
        if (e.target.closest('.cx')) { H.card.style.display = 'none'; lines.sel = -1; KY.sel.target = null; KY.redraw(); e.stopImmediatePropagation(); return; }
        if (e.target.closest('.ct')) { var on = H.card.classList.toggle('open'); e.target.closest('.ct').setAttribute('aria-expanded', on ? 'true' : 'false'); }
      }
      e.stopImmediatePropagation();                                  // a link keeps its default (a new tab); nothing else closes the card
    }, true);
  }
  function wireInput() {
    guardCard();
    if (typeof ResizeObserver === 'function') new ResizeObserver(function () { keep(); }).observe(H.card);
    addEventListener('resize', function () { requestAnimationFrame(keep); });
    addEventListener('keydown', function (e) {
      if (H.gbox.style.display === 'block') return;
      if (e.target && e.target.id === 'lyFind') return;
      if (e.key === 'e') step(1); else if (e.key === 'E') step(-1); else if (e.key === 'Backspace') lines.sel = -1;
    });
    // a tap within 9 px of a spark opens that line; only a tap on the wafer itself (05-lines finding 9)
    // The bookkeeping is in the CAPTURE phase: the shell stops pointerup on its bar and strip, and a bubble-phase listener
    // never saw those ups, so their pointers stayed in `down` and every later tap counted as a drag (refusal 04:24Z,
    // spark-tap). A primary pointerdown begins a new gesture, so nothing left from an earlier one can count.
    var down = {}, moved = 0, tap = null;
    addEventListener('pointerdown', function (e) { if (e.isPrimary) down = {};
      if (Object.keys(down).length) moved = 99; else moved = e.target === H.cv ? 0 : 99;   // tapUp: began on the canvas
      down[e.pointerId] = [e.clientX, e.clientY]; tap = null; }, true);
    addEventListener('pointermove', function (e) { var d = down[e.pointerId]; if (d) moved = Math.max(moved, Math.hypot(e.clientX - d[0], e.clientY - d[1])); }, true);
    addEventListener('pointercancel', function (e) { delete down[e.pointerId]; tap = null; }, true);
    addEventListener('pointerup', function (e) {
      var was = down[e.pointerId]; delete down[e.pointerId];
      // a tap: one pointer, down on the canvas, up within 10 px; reach 24 px for a finger, 9 px for a mouse (NL-009 04, base a72c175)
      tap = was && e.target === H.cv && moved <= 10 && Object.keys(down).length === 0 ? e.pointerId : null;
    }, true);
    addEventListener('pointerup', function (e) {                       // bubble: after the engine's key card, so the line's card wins
      if (tap === null || tap !== e.pointerId) return; tap = null;
      var P = lines.placed; if (!P.length || !rt.lines.on) return;
      var R = e.pointerType === 'mouse' ? 9 : 24, best = -1, bd = R * R;
      for (var i = 0; i < P.length; i++) { if (!visibleLine(P[i])) continue; var p = edScreen(P[i]), d = (p[0] - e.clientX) * (p[0] - e.clientX) + (p[1] - e.clientY) * (p[1] - e.clientY); if (d < bd) { bd = d; best = i; } }
      if (best >= 0) { openLine(best); fly(P[best]); }
    });
  }

  // ======================================================================== SECTION 5: wafer layers and app rows
  function applyPeriod(v) {
    var m = v && String(v).match(/^(20\d\d)(?:-(\d\d))?(?:-(\d\d))?$/);
    if (!m) { KY.lit.period = null; return; }
    H.lightTime(+m[1], m[2] ? +m[2] : 0, m[3] ? +m[3] : 0);
    lastK0 = KY.lit.K ? KY.lit.K[0] : -1;
  }
  function day(u) { return new Date(u * 1000).toISOString().slice(0, 10); }
  // the engine's own controls (tap, /, keys) light a repository or a period; the original follows the engine, never back
  function refreshWaferTags() {
    if (!rt.repos || !N()) return;
    var lr = KY.lit.repo;
    if (lr >= 0 && lr !== lastRepo && !rt.repos.on && !booting) { lastRepo = lr; mirrorOn('repos'); }
    lastRepo = lr;
    if (rt.repos.status === 'OK' || rt.repos.status === 'WAIT' || rt.repos.status === 'LOAD') {
      var name = lr >= 0 && H.repos[lr] ? H.repos[lr].name : null; rt.repos.value = name || rt.repos.value;
      setQuiet('repos', 'OK', !rt.repos.on ? 'off' : (name ? name : 'none lit'));
    }
    var K = KY.lit.K, ci = KY.lit.Ci, k0 = K ? K[0] : -1;
    if (k0 >= 0 && k0 !== lastK0 && !rt.periods.on && !booting) { lastK0 = k0; mirrorOn('periods'); }
    lastK0 = k0;
    if (rt.periods.status === 'OK' || rt.periods.status === 'WAIT' || rt.periods.status === 'LOAD') {
      var c = H.commits, txt = 'none lit';
      if (k0 >= 0 && ci && c[ci[0]] && c[ci[1] - 1]) txt = (rt.periods.value ? rt.periods.value + ' · ' : '') + fmt(ci[1] - ci[0]) + ' commits, ' + day(c[ci[0]].unix) + ' to ' + day(c[ci[1] - 1].unix);
      setQuiet('periods', 'OK', !rt.periods.on ? 'off' : txt);
    }
  }
  function mirrorOn(id) { rt[id].on = true; var el = original(id); if (el) el.checked = true; writeURL(); }
  function setQuiet(id, s, why) { var r = rt[id]; if (r.status === s && r.why === why) return; r.status = s; r.why = why; paintRow(id); }
  function N() { return H.N > 0 && H.SPACE > 0; }
  // editions: one amber ring at the radius of the first commit at or after each cut stamp; beyond the rim, counted
  var eds = { placed: [], beyond: [] };
  function stampUnix(s) { return Date.UTC(+s.slice(0, 4), +s.slice(4, 6) - 1, +s.slice(6, 8), +s.slice(8, 10), +s.slice(10, 12)) / 1000; }
  function loadEditions() {
    var r = rt.editions;
    return verified('editions').then(function (j) {
      if (!j || j.schema !== 'kuiper.editions.v1' || !Array.isArray(j.editions)) throw new Error('editions.json schema is not kuiper.editions.v1');
      if (r.rec.source.features && j.editions.length !== r.rec.source.features) throw new Error('features ' + j.editions.length + ' ≠ record ' + r.rec.source.features);
      var c = H.commits, last = c[c.length - 1].unix;
      eds.placed = []; eds.beyond = [];
      j.editions.forEach(function (e) {
        var u = stampUnix(e.stamp);
        if (u > last) { eds.beyond.push(e); return; }
        var i = Math.min(c.length - 1, H.findBy('unix', u - 1) + 1);
        eds.placed.push({ e: e, k: c[i].k0, r: Math.sqrt(c[i].k0) });
      });
      r.placed = eds.placed.length; r.total = j.editions.length; r.loaded = true;
      setState('editions', 'OK', fmt(r.placed) + ' of ' + fmt(r.total) + ' placed' + (eds.beyond.length ? ', ' + fmt(eds.beyond.length) + ' beyond the rim' : ''));
      KY.redraw();
    }).catch(function (e) { r.loaded = true; setState('editions', 'FAIL', String(e.message || e)); });
  }