GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Websites and apps / globalgrid2050 / testcode/202609151413

Layers and 2 more files

A JavaScript module in the testcode folder of GlobalGrid2050 that fetches families and blocks from the stars repository.

680 lines of JavaScript from globalgrid2050, in 3 files. Topic: Websites and apps. Section 1977 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. Physics transform · globalgrid2050 / testcode/202609151413/physics.mjs lines 1–260
  2. Layers render · globalgrid2050 / testcode/202609151500/layers.mjs lines 1–279
  3. Pick transform · globalgrid2050 / testcode/202609160151/pick.mjs lines 1–141

Physics

A JavaScript module in the testcode folder of GlobalGrid2050. It is built from the phase step (`phase`).

transformglobalgrid2050 / testcode/202609151413/physics.mjs · lines 1–260 of 260 · version 2026-09-15 14:13 · pattern phase (shared by 6 files)

What it does
It calculates its inputs. Defines phase.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Downstream impact
Used directly by 3 files: Engines (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/06-stars-as-engines/); Questions (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/06-stars-as-engines/); Laws (globalgrid2050). Reached from 3 other entry points, including Iterations — 06 Stars As Engines (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/06-stars-as-engines/); Iterations — 06 Stars As Engines Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/06-stars-as-engines/); Layers Panel (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/06-stars-as-engines/).
What it achieves
Ten placement laws for one estate.
Why it matters
Imported by Engines, Questions and Laws, from Galaxies Wafers.
Application
globalgrid2050 · testcode/202609151413 · JavaScript module
Uses
none found
Used by
named by URL in Engines (estate URL), named by URL in Questions (estate URL), imported by Laws (import)
Produces
TAU, GOLDEN_ANGLE, phase, wafer, orbit, shells, collapse, accretion, spectrum, lattice, field, condensation
Defines here
phase
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609151413/physics.mjs:1-260 · blob d873de43487eae43567e77fd5c80815fe72d3af4 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: production_core
/* physics.mjs — ten placement laws for one estate.
 *
 * WHAT THIS IS. The estate has 250,174 permanently numbered lines and 10,985
 * function families. This file holds ten different ways of deciding where a
 * thing goes, each taken from a real physical law, and nothing else. No drawing,
 * no DOM, no fetch. Give it the numbers and it returns positions.
 *
 * WHY TEN LAWS AND NOT ONE PICTURE. A layout is an argument about what matters.
 * Sort by number and you see history. Sort by mass and you see weight. Sort by
 * charge and you see conflict. The same data under ten laws is ten readings of
 * the same estate, and a reading that survives several laws is telling you
 * something about the code rather than about the layout.
 *
 * THE RULE EVERY LAW OBEYS. A position is a pure function of the entity's own
 * permanent key and of published facts about it. No randomness, no simulation
 * state, no iteration to convergence, no memory between frames. Give the same
 * key to the same law and you get the same point, on every device, for ever.
 * That is what makes any of these surfaces shareable by a link and unbounded
 * rather than merely large: a key that does not exist yet already has a place.
 *
 * WHAT IS NOT CLAIMED. These are analogies, drawn honestly. Code is not matter.
 * A function family has no mass in kilograms and a duplicated line exerts no
 * force. Each law says in its own note what it is borrowing and what it is not
 * asserting. Where a law needs a constant it is written down and named, never
 * tuned until the picture looked nice.
 */

export const TAU = Math.PI * 2;
export const GOLDEN_ANGLE = Math.PI * (3 - Math.sqrt(5));   /* 2.39996… rad */

/* A deterministic angle from a key. Not random: a fixed integer hash, so the
   same key is the same angle for ever. Written out rather than imported so the
   arithmetic can be read. */
export function phase(key) {
  let h = key >>> 0;
  h = Math.imul(h ^ (h >>> 16), 0x45d9f3b) >>> 0;
  h = Math.imul(h ^ (h >>> 16), 0x45d9f3b) >>> 0;
  h = (h ^ (h >>> 16)) >>> 0;
  return (h / 4294967296) * TAU;
}

/* ── 1. WAFER — the number is the address ────────────────────────────────── */
export const wafer = {
  id: 'wafer',
  title: 'Wafer',
  borrows: 'phyllotaxis, the spiral a sunflower uses to pack seeds without gaps',
  reads: 'the permanent number, and nothing else',
  note:
    'Radius is the square root of the number and angle is the number times the '
    + 'golden angle, so equal area holds equal count and no two numbers stack. '
    + 'Numbers were issued in order, so a ring is a period of the estate history '
    + 'and a gap is a number never issued.',
  place: (e) => {
    const r = Math.sqrt(e.key), t = e.key * GOLDEN_ANGLE;
    return [r * Math.cos(t), r * Math.sin(t)];
  }
};

/* ── 2. ORBIT — Kepler's third law ───────────────────────────────────────── */
export const orbit = {
  id: 'orbit',
  title: 'Orbits',
  borrows: "Kepler's third law: the square of a period is the cube of the semi-major axis",
  reads: 'the family a line belongs to, and how many lines that family holds',
  note:
    'Each family is a primary and its lines are bodies around it. A line sits at '
    + 'a radius set by its position within the family, so an early line orbits '
    + 'close and a late line far out. The family primary is itself placed by the '
    + 'wafer law, so the systems do not collide. Nothing here is a real period: '
    + 'no line moves and no time passes.',
  place: (e) => {
    const [fx, fy] = wafer.place({ key: (e.family ?? 0) * 31 + 1 });
    if (e.family == null) return [fx, fy];
    const n = Math.max(e.famCount || 1, 1);
    const a = 2 + 9 * Math.cbrt((e.inFamily + 1) / n);       /* semi-major axis */
    const t = phase(e.key) + (e.inFamily / n) * TAU;
    return [fx + a * Math.cos(t), fy + a * 0.62 * Math.sin(t)];   /* an inclined ellipse */
  }
};

/* ── 3. SHELLS — electron shells, 2n² per shell ──────────────────────────── */
export const shells = {
  id: 'shells',
  title: 'Shells',
  borrows: 'the electron shell, which holds 2n squared states at principal number n',
  reads: 'the family, and how many lines it holds',
  note:
    'A family is an atom and its lines fill shells: two in the first, eight in '
    + 'the second, eighteen in the third. A family of six lines is complete in '
    + 'two shells; a family of four hundred has an absurd number of them, and '
    + 'that absurdity is the point. The outermost shell is the valence, and a '
    + 'line in an unfilled outer shell is the one most likely to be changed.',
  place: (e) => {
    const [fx, fy] = wafer.place({ key: (e.family ?? 0) * 31 + 1 });
    if (e.family == null) return [fx, fy];
    let i = e.inFamily, n = 1;
    while (i >= 2 * n * n) { i -= 2 * n * n; n++; }             /* which shell, which seat */
    const seats = 2 * n * n;
    const t = (i / seats) * TAU + phase(e.family) ;
    const r = 1.6 + n * 1.5;
    return [fx + r * Math.cos(t), fy + r * Math.sin(t)];
  }
};

/* ── 4. COLLAPSE — mass concentrates, as in a degenerate star ────────────── */
export const collapse = {
  id: 'collapse',
  title: 'Collapse',
  borrows: 'gravitational collapse: what is heavy falls inward and what is light is left in the halo',
  reads: 'fanout, meaning how many families carry this exact line',
  note:
    'Fanout is the analogue of mass. A line written once sits far out; a line '
    + 'copied into a thousand families falls to the centre. The core of this '
    + 'picture is therefore the estate duplication, and it is mostly braces, '
    + 'blanks and imports. That is the honest result: the densest thing in the '
    + 'code is the least meaningful, and a collapse picture makes it impossible '
    + 'to miss. Radius falls as the inverse square root of fanout, the same '
    + 'exponent that relates orbital radius to binding, borrowed for its shape '
    + 'and not as a claim about force.',
  place: (e) => {
    const m = Math.max(e.fanout || 1, 1);
    const r = 60 / Math.sqrt(m);
    const t = phase(e.key);
    return [r * Math.cos(t), r * Math.sin(t)];
  }
};

/* ── 5. ACCRETION — a disk with an inner edge ────────────────────────────── */
export const accretion = {
  id: 'accretion',
  title: 'Accretion',
  borrows: 'an accretion disk: material spirals inward, and there is a radius inside which nothing stable orbits',
  reads: 'the line length in characters',
  note:
    'Long lines carry angular momentum and stay out; short lines spiral in. The '
    + 'innermost stable orbit here is the empty line, which cannot spiral further '
    + 'because it has nothing left to lose. The spiral arm is logarithmic, which '
    + 'is the shape a real disk takes, and the pitch is fixed at one radian per '
    + 'e-fold rather than fitted.',
  place: (e) => {
    const L = Math.max(e.chars || 0, 0);
    const r = 3 + 26 * Math.log1p(L) / Math.log1p(200);
    const t = Math.log1p(L) * 3.4 + phase(e.key) * 0.25;
    return [r * Math.cos(t), r * Math.sin(t)];
  }
};

/* ── 6. SPECTRUM — emission lines ────────────────────────────────────────── */
export const spectrum = {
  id: 'spectrum',
  title: 'Spectrum',
  borrows: 'an emission spectrum: each element emits at its own fixed wavelengths',
  reads: 'the category of the family, and the line length',
  note:
    'Each category is an element and occupies one band of the horizontal axis; '
    + 'within its band a line is placed by length. A category with a wide smear '
    + 'holds lines of every size; a category with a sharp line is uniform. '
    + 'Unlike a real spectrum the bands are assigned by name order, not by '
    + 'energy, because code categories have no energy.',
  place: (e) => {
    const c = e.cat ?? 0, n = Math.max(e.catCount || 1, 1);
    const x = ((c + 0.5) / n - 0.5) * 108;
    const L = Math.max(e.chars || 0, 0);
    const y = (Math.log1p(L) / Math.log1p(400) - 0.5) * 70;
    const jitter = (phase(e.key) / TAU - 0.5) * (108 / n) * 0.82;
    return [x + jitter, y];
  }
};

/* ── 7. LATTICE — a crystal, and the shape a printed circuit takes ───────── */
export const lattice = {
  id: 'lattice',
  title: 'Lattice',
  borrows: 'a square crystal lattice, and the orthogonal routing of a printed circuit board',
  reads: 'the permanent number only',
  note:
    'Numbers fill a square lattice in Hilbert-curve order, so consecutive '
    + 'numbers stay near each other at every zoom. This is the layout a board '
    + 'or a floorplan uses, and it is the only one of the ten where locality on '
    + 'screen means locality in the numbering. It is also the one that shows how '
    + 'much of the estate is contiguous runs written in one sitting.',
  place: (e) => {
    /* Hilbert d2xy over a 512x512 grid, the standard iterative form. */
    const N = 512;
    let t = e.key % (N * N), x = 0, y = 0;
    for (let s = 1; s < N; s *= 2) {
      const rx = 1 & (t / 2), ry = 1 & (t ^ rx);
      if (ry === 0) { if (rx === 1) { x = s - 1 - x; y = s - 1 - y; } const tmp = x; x = y; y = tmp; }
      x += s * rx; y += s * ry;
      t = Math.floor(t / 4);
    }
    return [(x / N - 0.5) * 100, (y / N - 0.5) * 100];
  }
};

/* ── 8. FIELD — charge and potential ─────────────────────────────────────── */
export const field = {
  id: 'field',
  title: 'Field',
  borrows: 'an electrostatic field: like charges repel and the potential falls with distance',
  reads: 'fanout as charge, and the family as position',
  note:
    'A family sits where the wafer puts it and carries a charge equal to the '
    + 'total fanout of its lines. Lines are placed on the equipotential of their '
    + 'own family, at a radius that grows with their own charge, so a heavily '
    + 'copied line is pushed out of its own family rather than pulled in. This '
    + 'is the inverse of the collapse law on purpose: the same quantity read as '
    + 'repulsion instead of attraction, and the two pictures disagree about the '
    + 'same estate.',
  place: (e) => {
    const [fx, fy] = wafer.place({ key: (e.family ?? 0) * 31 + 1 });
    const q = Math.max(e.fanout || 1, 1);
    const r = 1.2 + 3.2 * Math.log1p(q);
    const t = phase(e.key);
    return [fx + r * Math.cos(t), fy + r * Math.sin(t)];
  }
};

/* ── 9. CONDENSATION — temperature and the forming of structure ──────────── */
export const condensation = {
  id: 'condensation',
  title: 'Condensation',
  borrows: 'a cooling cloud: hot material is diffuse, cold material condenses into structure',
  reads: 'when the family was first written',
  note:
    'Age is temperature inverted. The oldest code is coldest and has condensed '
    + 'into tight clumps; the newest is hot and fills the volume. A clump means '
    + 'code that has stopped moving, which is either settled or abandoned, and '
    + 'this law cannot tell you which. The scale height falls exponentially with '
    + 'age, the same form as an isothermal atmosphere.',
  place: (e) => {
    const age = e.ageDays == null ? 0 : Math.max(e.ageDays, 0);
    const T = Math.exp(-age / 120);                       /* 120 days: an e-fold */
    const [fx, fy] = wafer.place({ key: (e.family ?? 0) * 31 + 1 });
    const r = 0.6 + 16 * T;
    const t = phase(e.key);
    return [fx * (0.55 + 0.45 * T) + r * Math.cos(t), fy * (0.55 + 0.45 * T) + r * Math.sin(t)];
  }
};

/* ── 10. BEAM — what the beam has written ────────────────────────────────── */
export const beam = {
  id: 'beam',
  title: 'Beam',
  borrows: 'electron-beam lithography, which writes a pattern directly with no mask',
  reads: 'the permanent number, and where the beam has been',
  note:
    'The surface is blank until the beam passes. Position is the wafer law, but '
    + 'a point is only developed once the beam has visited its radius, so the '
    + 'picture is written outward from the centre as you sweep. This is the only '
    + 'law with a parameter that is not a property of the data: the beam radius '
    + 'is where you point it. It is here to make the point that a surface can be '
    + 'unbounded and still be written one place at a time.',
  place: (e) => wafer.place(e),
  /* A beam law also declares what is developed yet; the renderer dims the rest. */
  developed: (e, beamRadius) => Math.sqrt(e.key) <= beamRadius
};

export const LAWS = [wafer, orbit, shells, collapse, accretion, spectrum, lattice, field, condensation, beam];
export const byId = Object.fromEntries(LAWS.map(l => [l.id, l]));

Layers

A JavaScript module in the testcode folder of GlobalGrid2050 that fetches families and blocks from the stars repository.

renderglobalgrid2050 / testcode/202609151500/layers.mjs · lines 1–279 of 279 · version 2026-09-15 15:00 · Not reached from any entry point (candidate for review) · pattern anchor (shared by 16 files)

What it does
It fetches families and blocks. Defines 7 functions or classes, including json, bin, familyIndex, rowOf, anchor. Side effects: makes network requests.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: data source: stars data; JSON file families.json; JSON file blocks.json.
What it achieves
It is built from the JSON step (`json`), the bin step (`bin`) and the family index helper (`familyIndex`). The layer registry for the wafer, in Grid Atlas's own grammar.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · testcode/202609151500 · JavaScript module
Uses
Stars — Index Page (estate URL)
Used by
none found
Produces
STATES, familyIndex, LAYERS, GROUPS, byId
Defines here
json, bin, familyIndex, rowOf, anchor, anchor, find
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609151500/layers.mjs:1-279 · blob 9e7d6d8f989153f21fd102b20c89a090664436d2 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: network · domain stage: experimental · users: none · canonical: unreached_review
/* layers.mjs — the layer registry for the wafer, in Grid Atlas's own grammar.
 *
 * THE SUBSTRATE IS FROZEN. The wafer is the basemap. A numbered line sits at
 * r = sqrt(key), theta = key x the golden angle, and that never changes, in the
 * same way the Atlas never changes its Carto ground. Every link ever made stays
 * true, and a key issued tomorrow already has a place. Nothing in this file
 * moves a point; a layer only decides what is drawn on top and in what colour.
 *
 * THE GRAMMAR IS THE ATLAS'S. Each layer declares an id, a label, a group and a
 * state, and the state vocabulary is the Atlas's own:
 *
 *   WAIT   nothing fetched, the source is empty, waiting for you to tick it
 *   LOAD   fetching now
 *   OK     loaded and drawn
 *   EMPTY  loaded and there was nothing in it, which is an answer
 *   FAIL   the fetch or the build failed, with the reason kept
 *
 * Twelve of the Atlas's sixty layers preload and forty-eight do not. The same
 * split is used here: the layers that need only the base pack are marked
 * preload, and everything that needs the family index or a remote register waits
 * until it is asked for. That is what makes the surface hold more than a phone
 * can carry.
 *
 * WHAT A LAYER MAY AND MAY NOT DO. A layer returns marks: points to tint, or
 * pairs of keys to join with a line. It may not move a point, add a point that
 * has no number, or invent a relationship. Every layer names its evidence, and
 * a layer whose evidence is a recorded failure says so differently from one
 * whose evidence is a declaration.
 */

export const STATES = ['WAIT', 'LOAD', 'OK', 'EMPTY', 'FAIL'];

const STARS = 'https://ventusltd.github.io/stars/';
const PACK = '../202609142202/data/';

/* ── helpers shared by the layers ────────────────────────────────────────── */

async function json(url) {
  const r = await fetch(url, { cache: 'default' });
  if (!r.ok) throw new Error(url.split('/').pop() + ' returned HTTP ' + r.status);
  return r.json();
}
async function bin(url, K) {
  const r = await fetch(url, { cache: 'default' });
  if (!r.ok) throw new Error(url.split('/').pop() + ' returned HTTP ' + r.status);
  return new K(await r.arrayBuffer());
}

/* The family index is needed by several layers, so it is built once and shared
   rather than fetched per layer. This is the Atlas's fan-out pattern: one
   source, several layers drawn from it. */
let familyIndexPromise = null;
export function familyIndex(U) {
  if (!familyIndexPromise) familyIndexPromise = (async () => {
    const [families, famLines] = await Promise.all([
      json(PACK + 'families.json'),
      bin(PACK + 'lines.bin', Uint32Array)
    ]);
    const owner = new Map();
    for (let f = 0; f < families.length; f++) {
      const o = families[f].lineOffset, c = families[f].lineCount;
      for (let i = o; i < o + c; i++) {
        const k = famLines[i], cur = owner.get(k);
        if (cur === undefined) owner.set(k, [f]);
        else if (cur[cur.length - 1] !== f) cur.push(f);
      }
    }
    return { families, famLines, owner };
  })();
  return familyIndexPromise;
}

const rowOf = U => {
  if (!U._row) { U._row = new Map(); for (let i = 0; i < U.n; i++) U._row.set(U.keys[i], i); }
  return U._row;
};

/* ── the layers ──────────────────────────────────────────────────────────── */

export const LAYERS = [

  /* GROUP: the ground itself */
  { id: 'carried', label: 'Carried by a family', group: 'THE NUMBERED GROUND', preload: true,
    colour: '#d8dee9',
    evidence: 'the pack\'s own flag: 128,369 of 250,174 numbered lines are inside at least one function family',
    note: 'The base tint. A line the estate has organised into a function is lit; a line that exists and '
        + 'belongs to no function is left dim. The dark rings are stretches of numbering where almost '
        + 'nothing was ever gathered into a named function.',
    async build(U) {
      const tint = new Float32Array(U.n);
      for (let i = 0; i < U.n; i++) tint[i] = U.inFam[i] ? 1 : 0.12;
      return { kind: 'tint', tint, lit: U.n };
    } },

  { id: 'length', label: 'Line length', group: 'THE NUMBERED GROUND', preload: true,
    colour: '#80cbc4',
    evidence: 'the pack\'s length column, one unsigned 16-bit value per line',
    note: 'Brightness is the character count. The empty lines vanish and the long ones stand out, which is '
        + 'the quickest way to see where the estate writes densely. Exactly one line reaches the ceiling of '
        + 'the sixteen-bit field, so its true length is not known and it is drawn at the ceiling.',
    async build(U) {
      const tint = new Float32Array(U.n);
      for (let i = 0; i < U.n; i++) tint[i] = 0.08 + 0.92 * Math.min(1, Math.log1p(U.lens[i]) / Math.log1p(160));
      return { kind: 'tint', tint };
    } },

  /* GROUP: duplication, from the family index */
  { id: 'fanout', label: 'Duplication', group: 'WHAT IS WRITTEN TWICE', preload: false,
    colour: '#ffd54a',
    evidence: 'counted from families.json and lines.bin: how many function families carry each line',
    note: 'The estate was numbered so that nothing is written twice without knowing it. This is that answer. '
        + 'Brightness is how many families carry the same line. The brightest points are not the most '
        + 'important code; they are braces, blanks and imports. That is the honest result and the reason '
        + 'the next layer exists.',
    async build(U) {
      const { owner } = await familyIndex(U);
      const row = rowOf(U);
      const tint = new Float32Array(U.n).fill(0.05);
      let shared = 0, max = 0;
      for (const [k, fs] of owner) {
        const i = row.get(k); if (i === undefined) continue;
        if (fs.length > 1) shared++;
        if (fs.length > max) max = fs.length;
        tint[i] = 0.12 + 0.88 * Math.min(1, Math.log(fs.length) / Math.log(60));
      }
      return { kind: 'tint', tint, stat: `${shared.toLocaleString('en-GB')} lines in more than one family, the most in ${max.toLocaleString('en-GB')}` };
    } },

  { id: 'copying', label: 'Real copying only', group: 'WHAT IS WRITTEN TWICE', preload: false,
    colour: '#ff8a65',
    evidence: 'lines in 2 to 40 families and at least 12 characters long; the rest discarded as structural',
    note: 'The same measurement with the noise removed. A line in more than forty families is structure, not '
        + 'copying, and a line under twelve characters carries too little to be evidence. What is left is '
        + 'where the estate genuinely repeats itself, and it is a small fraction of the previous layer.',
    async build(U) {
      const { owner } = await familyIndex(U);
      const row = rowOf(U);
      const tint = new Float32Array(U.n).fill(0.04);
      let usable = 0;
      for (const [k, fs] of owner) {
        if (fs.length < 2 || fs.length > 40) continue;
        const i = row.get(k); if (i === undefined || U.lens[i] < 12) continue;
        usable++;
        tint[i] = 0.35 + 0.65 * Math.min(1, fs.length / 12);
      }
      return { kind: 'tint', tint, stat: `${usable.toLocaleString('en-GB')} lines are usable evidence of copying` };
    } },

  /* GROUP: the blocks, from the live register */
  { id: 'blocks', label: 'Inside a numbered block', group: 'THE WORKING MODULES', preload: false,
    colour: '#5ec8f2',
    evidence: 'the live block register at ventusltd.github.io/stars/blocks/blocks.json',
    note: 'Which numbered lines sit inside a block the estate has named, numbered and proved. These are the '
        + 'modules with a repository, a pinned commit and a path. Everything lit here is code somebody can '
        + 'point at; everything dark is code that works but that no module claims.',
    async build(U) {
      const doc = await json(STARS + 'blocks/blocks.json');
      const { families, famLines } = await familyIndex(U);
      const row = rowOf(U);
      const wanted = new Set();
      for (const b of doc.blocks) for (const f of b.inside || []) wanted.add(f.family);
      const byN = new Map(families.map((f, i) => [f.n, i]));
      const tint = new Float32Array(U.n).fill(0.05);
      let lit = 0;
      for (const n of wanted) {
        const fi = byN.get(n); if (fi === undefined) continue;
        const f = families[fi];
        for (let j = f.lineOffset; j < f.lineOffset + f.lineCount; j++) {
          const i = row.get(famLines[j]); if (i === undefined) continue;
          if (tint[i] < 0.9) { tint[i] = 0.95; lit++; }
        }
      }
      return { kind: 'tint', tint,
        stat: `${lit.toLocaleString('en-GB')} lines lie inside ${wanted.size.toLocaleString('en-GB')} named function families across ${doc.blocks.length} blocks` };
    } },

  { id: 'engine', label: 'The grid engine', group: 'THE WORKING MODULES', preload: false,
    colour: '#7fd6a2',
    evidence: 'blocks whose repository is Ventusltd/ventus-grid-engine in the live register',
    note: 'The lines that are the grid mathematics itself: distance and bearing, voltage drop, firm capacity, '
        + 'connection capacity, ratings, route obstacles. This is the smallest layer on the wafer and it is '
        + 'the one the whole estate exists to serve.',
    async build(U) {
      const doc = await json(STARS + 'blocks/blocks.json');
      const { families, famLines } = await familyIndex(U);
      const row = rowOf(U);
      const byN = new Map(families.map((f, i) => [f.n, i]));
      const tint = new Float32Array(U.n).fill(0.04);
      let lit = 0, blocks = 0;
      for (const b of doc.blocks) {
        if (!(b.repos || []).some(r => /ventus-grid-engine/.test(r))) continue;
        blocks++;
        for (const fn of b.inside || []) {
          const fi = byN.get(fn.family); if (fi === undefined) continue;
          const f = families[fi];
          for (let j = f.lineOffset; j < f.lineOffset + f.lineCount; j++) {
            const i = row.get(famLines[j]); if (i === undefined) continue;
            if (tint[i] < 0.9) { tint[i] = 1; lit++; }
          }
        }
      }
      return { kind: 'tint', tint,
        stat: `${lit.toLocaleString('en-GB')} lines across ${blocks} engine blocks` };
    } },

  /* GROUP: joins drawn as lines */
  { id: 'declared', label: 'Declared dependencies', group: 'WHAT FITS WITH WHAT', preload: false,
    colour: '#8ea8ff', draws: 'lines',
    evidence: 'depends_on in the live block register: only 48 of 205 blocks with code declare anything',
    note: 'A line between two blocks that the register says depend on each other, drawn between the first '
        + 'numbered line of each. This is what the authors wrote down, and it is thin: most of the estate '
        + 'declares nothing at all.',
    async build(U) {
      const doc = await json(STARS + 'blocks/blocks.json');
      const { families, famLines } = await familyIndex(U);
      const row = rowOf(U);
      const byN = new Map(families.map((f, i) => [f.n, i]));
      const anchor = b => {
        for (const fn of b.inside || []) {
          const fi = byN.get(fn.family);
          if (fi !== undefined && families[fi].lineCount) return famLines[families[fi].lineOffset];
        }
        return null;
      };
      const bySym = new Map(doc.blocks.map(b => [b.symbol, b]));
      const joins = [];
      for (const b of doc.blocks) {
        const a = anchor(b); if (a === null) continue;
        for (const d of b.depends_on || []) {
          const t = bySym.get(d.symbol); if (!t) continue;
          const z = anchor(t); if (z === null) continue;
          joins.push({ a, b: z, label: `${b.symbol} depends on ${d.symbol}`, kind: 'declared' });
        }
      }
      return joins.length ? { kind: 'joins', joins, stat: `${joins.length} declared dependencies drawable` }
                          : { kind: 'empty', why: 'no declared dependency could be anchored to a numbered line' };
    } },

  { id: 'learned', label: 'Learned by failure', group: 'WHAT FITS WITH WHAT', preload: false,
    colour: '#ffd54a', draws: 'lines',
    evidence: 'the chemistry star: 3,319 tested compositions, 913 failures, two of them rules',
    note: 'Two rules nobody declared and the estate learned by trying: sld-sandbox will not run without '
        + 'sld-styles, recorded in 702 failed compositions, and grid-scope will not run without geodesy, '
        + 'recorded in 211. Drawn differently from a declaration because the evidence is of a different '
        + 'kind. If there are only two of these, it is because only the cartridges have been composed at '
        + 'scale, not because the rest fit together.',
    async build(U) {
      const doc = await json(STARS + 'blocks/blocks.json');
      const { families, famLines } = await familyIndex(U);
      const row = rowOf(U);
      const byN = new Map(families.map((f, i) => [f.n, i]));
      const anchor = b => {
        for (const fn of b.inside || []) {
          const fi = byN.get(fn.family);
          if (fi !== undefined && families[fi].lineCount) return famLines[families[fi].lineOffset];
        }
        return null;
      };
      const find = word => doc.blocks.find(b =>
        (b.title || '').toLowerCase().includes(word) || (b.description || '').toLowerCase().includes(word));
      const RULES = [
        ['sld-sandbox', 'sld-styles', 702], ['grid-scope', 'geodesy', 211]
      ];
      const joins = [];
      for (const [from, to, n] of RULES) {
        const A = find(from), B = find(to);
        if (!A || !B) continue;
        const a = anchor(A), z = anchor(B);
        if (a === null || z === null) continue;
        joins.push({ a, b: z, kind: 'learned',
          label: `${from} will not run without ${to} — ${n} failed compositions` });
      }
      return joins.length ? { kind: 'joins', joins, stat: `${joins.length} rules learned by failure` }
                          : { kind: 'empty', why: 'neither rule could be anchored: the register names no line for one of the blocks' };
    } }
];

export const GROUPS = [...new Set(LAYERS.map(l => l.group))];
export const byId = Object.fromEntries(LAYERS.map(l => [l.id, l]));

Pick

A JavaScript module in the testcode folder of GlobalGrid2050. It builds pick index (`buildPickIndex`) and is built from the cell of helper (`cellOf`) and the nearest at helper (`nearestAt`).

transformglobalgrid2050 / testcode/202609160151/pick.mjs · lines 1–141 of 141 · version 2026-09-16 01:51 · pattern cellOf (shared by 2 files)

What it does
It calculates its inputs. Defines buildPickIndex, cellOf, nearestAt.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Downstream impact
Used directly by 6 files: Wafer Development Environment — Cable Cross Sections (globalgrid2050, https://globalgrid2050.com/testcode/wafer-development-environment/202609190330-cable-cross-sections/); Testcode — Quantum Twin Flights (globalgrid2050); Wafer Development Environment — Estate (globalgrid2050); Wafer Development Environment — Underground (globalgrid2050, https://globalgrid2050.com/testcode/wafer-development-environment/202609180205-underground/); and 2 more. Reached from 190 other entry points, including GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); GlobalGrid2050 — Compute Page (globalgrid2050, https://globalgrid2050.com/compute/).
What it achieves
Which line is under the finger.
Why it matters
Imported by 6 files, including Wafer Development Environment — Cable Cross Sections, Testcode — Quantum Twin Flights and Wafer Development Environment — Estate, from Star Electron Star.
Application
globalgrid2050 · testcode/202609160151 · JavaScript module
Uses
none found
Used by
imported by Wafer Development Environment — Cable Cross Sections (import), imported by Testcode — Quantum Twin Flights (import), imported by Wafer Development Environment — Estate (import), imported by Wafer Development Environment — Underground (import), imported by Star Electron Star — App (import), imported by GlobalGrid2050 — Testcode (import), mentioned in Standalone (comment link)
Produces
buildPickIndex, nearestAt
Defines here
buildPickIndex, cellOf, nearestAt
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609160151/pick.mjs:1-141 · blob f2b895b207925e24e3e047abb7462c7530c8e162 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: production_core
/* Which line is under the finger.
 *
 * WHAT WAS WRONG. The first version compared the tap against every point in the
 * estate — 250,174 distance tests per tap, and 283,231 by the next build. It is
 * the one place in the design whose cost grew with the estate, and it grew on
 * the interaction the whole page exists for.
 *
 * WHY A PLAIN GRID IS THE RIGHT ANSWER HERE, and not a quadtree or a k-d tree.
 * The wafer places key k at r = SPACING * sqrt(k), so the area inside radius r
 * holds exactly r^2 / SPACING^2 keys: every key owns pi * SPACING^2 of the
 * plane, everywhere, at every radius. The points are UNIFORMLY dense. A uniform
 * grid is optimal for uniform density and degenerate for clustered data, and
 * this is the one dataset that is uniform by construction. So the structure
 * that is usually the naive choice is here the correct one.
 *
 * WHAT IT COSTS. Two typed arrays and no objects: a start offset per cell and
 * one entry per point, both Uint32. For 283,231 points that is about 2.3 MB and
 * one O(n) pass, built from the positions the wafer has already computed. It is
 * never fetched, never refreshed and never invalidated, because a key's place
 * is a pure function of the key.
 */

/* Roughly this many points per cell. A tap reaches 22 px, so the search visits
   the cells a disc of that radius touches; sixteen keeps that handful small
   without making the cell table longer than the data it indexes. */
const PER_CELL = 16;

export function buildPickIndex(pos, n, spacing = 1) {
  /* Each key owns pi * spacing^2 of area, so a cell of side `size` holds
     size^2 / (pi * spacing^2) points on average. Solve that for PER_CELL. */
  const size = Math.sqrt(PER_CELL * Math.PI) * spacing;

  let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
  for (let i = 0; i < n; i++) {
    const x = pos[i * 2], y = pos[i * 2 + 1];
    if (x < minX) minX = x; if (x > maxX) maxX = x;
    if (y < minY) minY = y; if (y > maxY) maxY = y;
  }
  const cols = Math.max(1, Math.ceil((maxX - minX) / size) + 1);
  const rows = Math.max(1, Math.ceil((maxY - minY) / size) + 1);

  /* Counting sort into cells: count, prefix-sum, place. Two passes, no objects,
     no allocation per point. */
  const counts = new Uint32Array(cols * rows + 1);
  const cellOf = i => {
    const cx = Math.min(cols - 1, Math.max(0, (pos[i * 2] - minX) / size | 0));
    const cy = Math.min(rows - 1, Math.max(0, (pos[i * 2 + 1] - minY) / size | 0));
    return cy * cols + cx;
  };
  for (let i = 0; i < n; i++) counts[cellOf(i) + 1]++;
  for (let c = 0; c < cols * rows; c++) counts[c + 1] += counts[c];
  const start = counts;                       /* now the start offset of each cell */
  const items = new Uint32Array(n);
  const fill = start.slice(0, cols * rows);
  for (let i = 0; i < n; i++) items[fill[cellOf(i)]++] = i;

  /* ── the index measures whether its own assumption held ──────────────────
   *
   * The cell size above is derived ANALYTICALLY from SPACING, on the assumption
   * that every key owns pi * SPACING^2 of the plane. That is true for the wafer
   * law and silently false for every other one. Iteration 49 was written when
   * the wafer law was the only law; by the same night the estate had `core`
   * (most-used code at the centre) and a gravity law with measured masses —
   * Pipeline News pulling 453 directories toward r = 0, Grid Atlas 382. Under
   * those the points are deliberately clustered, which is the one distribution a
   * uniform grid is worst at.
   *
   * The index would keep returning the RIGHT answer and quietly stop being fast,
   * and nothing anywhere would say so: it would surface months later as "the
   * middle feels slow", with nobody able to name the cause. A structure that
   * degrades silently is the same defect as a check that passes silently, and
   * this one was in my own file. So it now measures what it actually built —
   * from the positions it was handed, not from the assumption — and says so.
   *
   * `uniform` is not a promise that the law is the wafer law. It is the weaker,
   * checkable claim that the occupancy this index actually achieved is close
   * enough to the target for the O(1)-per-tap argument to hold. */
  let worst = 0, occupied = 0;
  const occ = [];
  for (let c = 0; c < cols * rows; c++) {
    const k = start[c + 1] - start[c];
    if (k > worst) worst = k;
    if (k > 0) { occupied++; occ.push(k); }
  }
  occ.sort((a, b) => a - b);
  const median = occ.length ? occ[occ.length >> 1] : 0;
  const p99 = occ.length ? occ[Math.min(occ.length - 1, Math.floor(occ.length * 0.99))] : 0;

  return { start, items, cols, rows, size, minX, minY, n, pos,
           bytes: start.byteLength + items.byteLength,
           occupancy: {
             target: PER_CELL, median, p99, worst,
             cells: cols * rows, occupied,
             /* Ten times the target in the worst cell means a tap there costs ten
                times what the design claims. Two hundred times means the grid has
                stopped being an index. */
             uniform: worst <= PER_CELL * 10,
             why: worst <= PER_CELL * 10
               ? `worst cell holds ${worst} of a target ${PER_CELL}`
               : `worst cell holds ${worst}, ${(worst / PER_CELL).toFixed(0)}x the target ${PER_CELL}: ` +
                 `these positions are not uniformly dense, so a tap in the crowded region costs ` +
                 `far more than this index claims. It is still CORRECT; it is no longer fast.`
           } };
}

/* The index of the nearest point within `reach` world units of (wx, wy), or -1.
 *
 * It widens a ring of cells at a time and stops as soon as the best distance
 * found is closer than the nearest edge of the next ring — the usual guarantee,
 * and the reason this returns the same answer the full scan returned rather
 * than merely a nearby one. */
export function nearestAt(ix, wx, wy, reach) {
  const { start, items, cols, rows, size, minX, minY } = ix;
  const cx = Math.min(cols - 1, Math.max(0, (wx - minX) / size | 0));
  const cy = Math.min(rows - 1, Math.max(0, (wy - minY) / size | 0));
  const maxRing = Math.ceil(reach / size);
  let best = -1, bestD = reach * reach;

  for (let ring = 0; ring <= maxRing; ring++) {
    /* Everything in an earlier ring is closer than anything this ring can hold,
       so a hit inside (ring - 1) * size is already the answer. */
    if (best >= 0 && bestD < Math.pow((ring - 1) * size, 2)) break;
    const x0 = cx - ring, x1 = cx + ring, y0 = cy - ring, y1 = cy + ring;
    for (let gy = y0; gy <= y1; gy++) {
      if (gy < 0 || gy >= rows) continue;
      /* Only the perimeter of the ring is new; its interior was ring - 1. */
      const edge = (gy === y0 || gy === y1);
      for (let gx = x0; gx <= x1; gx += (edge ? 1 : (x1 - x0 || 1))) {
        if (gx < 0 || gx >= cols) continue;
        const c = gy * cols + gx;
        for (let p = start[c], e = start[c + 1]; p < e; p++) {
          const i = items[p];
          const dx = ix.pos[i * 2] - wx, dy = ix.pos[i * 2 + 1] - wy;
          const d = dx * dx + dy * dy;
          if (d < bestD) { bestD = d; best = i; }
        }
      }
    }
  }
  return best;
}