GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / stars / modular-star

Register and 5 more files

A Python module in the spider folder of Stars that registers the graphs this repository publishes for the Spider dashboard.

622 lines of HTML and JavaScript and Python from stars, in 6 files. Topic: Kuiper, cosmos and drawing engines. Section 1584 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. Wandering other · stars / modular-star/wandering.mjs lines 1–83
  2. Why storage · stars / modular-star/why.mjs lines 1–107
  3. Features docs-config · stars / spider/features.yml lines 1–77
  4. Register energy-data · stars / spider/register.py lines 1–123
  5. Start render · stars / start.html lines 1–114
  6. Table render · stars / table.html lines 1–118

Wandering

A JavaScript module in the modular star folder of Stars. It is built from the arg step (`arg`).

otherstars / modular-star/wandering.mjs · lines 1–83 of 83 · Entry point

What it does
It lists and searches its content. Defines arg, sh. Uses libraries node:child_process, node:fs, node:path. Side effects: reads or writes files; starts processes.
Inputs & outputs
In: command-line arguments.
Downstream impact
Used directly by 1 file: Modular Star Workflow (stars).
What it achieves
Wandering star — walk the full commit history of every public Ventusltd repository and add every version of every code file ever written to the numbered database, with the date it was written.
Why it matters
Run by Modular Star Workflow.
Application
stars · modular-star · JavaScript module
Uses
Stars — Modular Star (script call), node:child_process, node:fs, node:path
Used by
run by Modular Star Workflow (workflow run)
Produces
arg, sh
Defines here
arg, sh
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
stars@030ebc202d35959fecd162327892f671d1d9a0cc modular-star/wandering.mjs:1-83 · blob cee4533c684fa7356619c5ded7e959c848c0aa3b · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: unknown · users: none · canonical: unknown
// Wandering star — walk the full commit history of every public Ventusltd repository and add every version of
// every code file ever written to the numbered database, with the date it was written. It resumes where the last
// run stopped, so the whole history builds up over successive runs without renumbering anything.
// Usage: node modular-star/wandering.mjs --db modular.sqlite --work /tmp/wander --minutes 45
import { execFileSync } from 'node:child_process';
import { rmSync } from 'node:fs';
import path from 'node:path';
import { openDb, ingestFile, langOf, gitBlobId } from './lib.mjs';

const arg = (k, d) => { const i = process.argv.indexOf('--' + k); return i > 0 ? process.argv[i + 1] : d; };
const DB = arg('db', 'modular.sqlite'), WORK = arg('work', '/tmp/wander');
const deadline = Date.now() + Number(arg('minutes', '45')) * 60000;
const OWNER = 'Ventusltd', SKIP = /(^|\/)(node_modules|vendor|dist|build|\.git)\/|\.min\.(js|mjs)$/i;
const sh = (args, opts = {}) => execFileSync('git', args, { encoding: 'utf8', maxBuffer: 1024 * 1024 * 1024, ...opts });

const ctx = openDb(DB);
ctx.db.exec(`
CREATE TABLE IF NOT EXISTS commit_info(repo TEXT NOT NULL, sha TEXT NOT NULL, date TEXT NOT NULL, PRIMARY KEY(repo, sha));
CREATE TABLE IF NOT EXISTS wander(repo TEXT PRIMARY KEY, commits_total INTEGER, commits_done INTEGER, updated_utc TEXT);`);
const done = ctx.db.prepare('SELECT 1 FROM commit_info WHERE repo = ? AND sha = ?');
const insCommit = ctx.db.prepare('INSERT OR IGNORE INTO commit_info(repo, sha, date) VALUES(?, ?, ?)');

const repos = execFileSync('gh', ['api', '--paginate', `users/${OWNER}/repos?type=public&per_page=100`, '--jq', '.[] | select(.private == false and .fork == false) | .full_name'], { encoding: 'utf8' })
  .split('\n').filter(r => r && r !== `${OWNER}/stars`);
// Least-finished repositories first, so every repository makes progress.
const progress = new Map(ctx.db.prepare('SELECT repo, commits_total, commits_done FROM wander').all().map(w => [w.repo, w]));
repos.sort((a, b) => ((progress.get(a)?.commits_done ?? 0) / (progress.get(a)?.commits_total || 1)) - ((progress.get(b)?.commits_done ?? 0) / (progress.get(b)?.commits_total || 1)));

let versions = 0;
for (const repo of repos) {
  if (Date.now() > deadline) break;
  const w = progress.get(repo);
  if (w && w.commits_total && w.commits_done >= w.commits_total) continue;
  const dir = path.join(WORK, repo.replace('/', '__'));
  try {
    rmSync(dir, { recursive: true, force: true });
    execFileSync('git', ['clone', '--quiet', '--bare', '--filter=blob:limit=1m', `https://github.com/${repo}.git`, dir], { stdio: 'pipe' });
    // Oldest first. For each commit, the files it added or changed, with their new blob ids.
    const log = sh(['-C', dir, '-c', 'core.quotepath=false', 'log', '--all', '--reverse', '--no-renames', '--raw', '--no-abbrev', '--format=@@%H %cI']);
    const commits = [];
    for (const line of log.split('\n')) {
      if (line.startsWith('@@')) { const [sha, date] = line.slice(2).split(' '); commits.push({ sha, date, files: [] }); }
      else if (line.startsWith(':')) {
        const [meta, p] = line.split('\t'); const f = meta.split(' ');
        if (['A', 'M'].includes(f[4]?.[0]) && langOf(p) && !SKIP.test(p)) commits.at(-1)?.files.push({ oid: f[3], path: p });
      }
    }
    let n = 0, stopped = false;
    for (const c of commits) {
      if (done.get(repo, c.sha)) { n++; continue; }
      if (Date.now() > deadline) { stopped = true; break; }
      ctx.db.exec('BEGIN');
      if (c.files.length) {
        const input = c.files.map(f => f.oid).join('\n') + '\n';
        const buf = execFileSync('git', ['-C', dir, 'cat-file', '--batch'], { input, maxBuffer: 512 * 1024 * 1024, env: { ...process.env, GIT_NO_LAZY_FETCH: '1' } });
        let pos = 0;
        for (const f of c.files) {
          const nl = buf.indexOf(0x0a, pos);
          const [got, type, size] = buf.subarray(pos, nl).toString().split(' ');
          if (type === 'missing' || got !== f.oid) { pos = nl + 1; continue; }
          const bytes = buf.subarray(nl + 1, nl + 1 + Number(size));
          pos = nl + 1 + Number(size) + 1;
          if (gitBlobId(bytes) !== f.oid) continue;
          ingestFile(ctx, { repo, commit: c.sha, path: f.path, bytes, oid: f.oid, seen: c.date });
          versions++;
        }
      }
      insCommit.run(repo, c.sha, c.date);
      ctx.db.exec('COMMIT');
      n++;
    }
    ctx.db.prepare('INSERT OR REPLACE INTO wander(repo, commits_total, commits_done, updated_utc) VALUES(?, ?, ?, ?)').run(repo, commits.length, n, new Date().toISOString());
    console.log(`${repo}: ${n}/${commits.length} commits walked${stopped ? ' (time budget reached; continues next run)' : ''}`);
  } catch (e) {
    try { ctx.db.exec('ROLLBACK'); } catch {}
    console.log(`${repo}: not walked — ${String(e.message).split('\n')[0].slice(0, 200)}`);
  } finally {
    rmSync(dir, { recursive: true, force: true });
  }
}
const t = ctx.db.prepare('SELECT count(*) repos, sum(commits_done) done, sum(commits_total) total FROM wander').get();
console.log(`History: ${t.done}/${t.total} commits across ${t.repos} repositories; ${versions} file versions read this run.`);
ctx.db.close();

Why

A JavaScript module in the modular star folder of Stars that reads decays, engine join, reactions and blocks.

storagestars / modular-star/why.mjs · lines 1–107 of 107 · Entry point · pattern plural (shared by 9 files)

What it does
It loads decays, engine join, reactions and blocks. Defines 11 functions or classes, including readJson, maybe, esc, plural, blockName. Uses libraries node:fs, node:path. Side effects: reads or writes files.
Inputs & outputs
In: JSON file decays.json; JSON file engine-join.json; JSON file reactions.json; JSON file blocks.json; JSON file families.json; JSON file graph.json; command-line arguments.
Downstream impact
Used directly by 1 file: Modular Star Workflow (stars).
What it achieves
It reads JSON (`readJson`) and is built from the plural step (`plural`) and the block name helper (`blockName`). Defines `readJson`, `maybe`, `esc` and 8 more.
Why it matters
Run by Modular Star Workflow.
Application
stars · modular-star · JavaScript module
Uses
Stars — Index Page (estate URL), node:fs, node:path
Used by
run by Modular Star Workflow (workflow run)
Produces
readJson, maybe, esc, plural, blockName, lineList, whyDecay, whyFamily, whyBlock, why, withWhy
Defines here
readJson, maybe, esc, plural, blockName, lineList, whyDecay, whyFamily, whyBlock, why, withWhy
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
stars@030ebc202d35959fecd162327892f671d1d9a0cc modular-star/why.mjs:1-107 · blob ce93abbbc1072d2456d32ae276d5e127985fdb28 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: supporting_data
#!/usr/bin/env node
// why.mjs — one plain sentence on every red card, tracing the cause.
//
// For each red node in modular/graph.json and blocks/graph.json, walks the evidence this repository already holds
// (modular/decays.json, modular/engine-join.json, blocks/reactions.json, a block's needs in blocks/blocks.json) and
// writes the walk down as one sentence in the card's reason, wrapped in <!--why--> … <!--/why--> so a second run
// replaces it. Honest by rule: when the walk finds nothing, the sentence is "cause not yet traced".
// Also writes relationships/WHY.md, the same sentences as a list.
//
// Usage: node modular-star/why.mjs --out .      (node 24, no dependencies)
import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
import { join } from 'node:path';

const args = process.argv.slice(2);
const outIdx = args.indexOf('--out');
const ROOT = outIdx >= 0 && args[outIdx + 1] ? args[outIdx + 1] : '.';
const STARS = 'https://ventusltd.github.io/stars/';
const readJson = (p) => JSON.parse(readFileSync(join(ROOT, p), 'utf8').replace(/^/, ''));
const maybe = (p) => (existsSync(join(ROOT, p)) ? readJson(p) : null);
const esc = (s) => String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
const plural = (n, w, ws = w + 's') => `${n} ${n === 1 ? w : ws}`;
const NOT_TRACED = 'cause not yet traced';

// ---------- evidence ----------
const decays = maybe('modular/decays.json')?.decays || [];
const engineJoin = maybe('modular/engine-join.json')?.families || {};
const reactions = maybe('blocks/reactions.json')?.reactions || [];
const blocks = maybe('blocks/blocks.json')?.blocks || [];
const familiesOf = maybe('blocks/families.json') || {};
const blockOfFamily = new Map();
for (const [sym, fams] of Object.entries(familiesOf)) for (const n of fams) blockOfFamily.set(String(n), sym);
const bySymbol = new Map(blocks.map((b) => [b.symbol, b]));
const blockName = (sym) => { const b = bySymbol.get(sym); return b ? `block ${b.symbol} · ${b.title}` : `block ${sym}`; };
const lineList = (lines) => lines.slice(0, 3).join(', ') + (lines.length > 3 ? ` and ${lines.length - 3} more` : '');

function whyDecay(needle) {
  const d = decays.find((x) => x.needle === needle || x.message === needle);
  if (!d) return NOT_TRACED;
  const first = d.families?.[0];
  const sym = first ? blockOfFamily.get(String(first.family)) : null;
  let s = `Red because ${d.red_stars.toLocaleString()} red composition tests throw "${d.needle}"`;
  s += d.lines?.length ? `, carried at ${d.lines.length === 1 ? 'numbered line' : `${d.lines.length} numbered lines`} ${lineList(d.lines)}` : ', not found in any numbered line';
  s += d.families?.length ? ` in ${plural(d.families.length, 'function')}` + (first ? ` (for example family ${first.family}, ${first.name}${sym ? `, ${blockName(sym)}` : ''})` : '') : ' and in no function this star has numbered';
  s += '.';
  const m = d.needle.match(/requires the (\S+) module/);
  if (m) s += ` The message names a module that was absent when the compound was assembled: ${m[1]}.`;
  return s;
}

function whyFamily(n) {
  const thrown = decays.filter((d) => (d.families || []).some((f) => String(f.family) === String(n)));
  if (thrown.length) { const d = thrown[0]; return `Red because this function carries the error "${d.needle}", thrown in ${d.red_stars.toLocaleString()} red composition tests${thrown.length > 1 ? `, and ${plural(thrown.length - 1, 'other error')}` : ''}.`; }
  const j = engineJoin[String(n)];
  const frag = j?.joins?.find((x) => x.type === 'fragment');
  const canon = j?.joins?.find((x) => x.type === 'canonical');
  if (frag) return `Red because this copy of ${j.name} is ${frag.relation || 'a fragment'} (${frag.label})${canon ? `; its canonical home is ${canon.label}` : ''}.`;
  return NOT_TRACED;
}

function whyBlock(sym) {
  const b = bySymbol.get(sym);
  const fails = reactions.filter((r) => (r.a === sym || r.b === sym) && r.verdict === 'fails');
  if (fails.length) { const r = fails[0]; const other = r.a === sym ? r.b : r.a; return `Red because composition tests with ${blockName(other)} fail (${r.basis})${r.decay ? `, the error being "${r.decay}"` : ''}${fails.length > 1 ? `; ${plural(fails.length - 1, 'other pair')} also fail` : ''}.`; }
  if (b?.needs?.length) return `Red because the block needs ${plural(b.needs.length, 'name')} it does not define (${b.needs.slice(0, 4).map((x) => x.meaning || x.name).join(', ')}${b.needs.length > 4 ? ', …' : ''}).`;
  if (b && !b.functions) return 'Red because no function of the numbered code was placed in this block.';
  return NOT_TRACED;
}

function why(node) {
  const id = String(node.id ?? '');
  if (node.type === 'decay' || id.startsWith('decay:')) return whyDecay(id.replace(/^decay:/, ''));
  if (id.startsWith('family:')) return whyFamily(id.slice(7));
  if (id.startsWith('block:')) return whyBlock(id.slice(6));
  return NOT_TRACED;
}

// ---------- write ----------
const MARK = /<!--why-->[\s\S]*?<!--\/why-->/g;
function withWhy(reason, sentence) {
  const base = String(reason || '').replace(MARK, '');
  const piece = `<!--why--><br><b>Why.</b> ${esc(sentence)}<!--/why-->`;
  const pre = base.indexOf('<pre');
  return pre >= 0 ? base.slice(0, pre) + piece + base.slice(pre) : base + piece;
}

const md = ['# Why, on every red card', '', `Generated ${new Date().toISOString()}. One sentence per red card, walked from the evidence this repository holds`,
  '(decays, the engine join, the chemistry, a block\'s needs) by `modular-star/why.mjs`. "Cause not yet traced" means the walk found nothing; it is never invented.', ''];
let total = 0, traced = 0;
for (const file of ['modular/graph.json', 'blocks/graph.json']) {
  const graph = maybe(file);
  if (!graph) { md.push(`## ${file}`, '', 'Not present in this checkout.', ''); continue; }
  const red = (graph.nodes || []).filter((n) => n.rag === 'red');
  md.push(`## ${graph.label || file} (\`${file}\`)`, '');
  if (!red.length) { md.push(`No red cards at ${graph.generated_utc || 'this run'}.`, ''); continue; }
  for (const n of red) {
    const s = why(n);
    total++; if (s !== NOT_TRACED) traced++;
    n.reason = withWhy(n.reason, s);
    md.push(`- **${n.label}** (\`${n.id}\`): ${s}`);
  }
  md.push('');
  writeFileSync(join(ROOT, file), JSON.stringify(graph));
}
md.push(`${total} red cards, ${traced} traced, ${total - traced} not yet traced. Cards: ${STARS}spider/graphs/`);
mkdirSync(join(ROOT, 'relationships'), { recursive: true });
writeFileSync(join(ROOT, 'relationships/WHY.md'), md.join('\n') + '\n');
console.log(`why: ${total} red cards, ${traced} traced, ${total - traced} not yet traced → relationships/WHY.md`);

Features

A configuration file in the spider folder of Stars covering chemistry and VEDIC.

Set aside from the main view: A comment at the top of the file says a tool wrote it. (noise-generated, proposed by noise.py). All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line 2 comment: # Written by spider/register.py on every build. Each entry has the same fields as a manifest entry.

docs-configstars / spider/features.yml · lines 1–77 of 77 · Not reached from any entry point (candidate for review)

Why it exists in the grid workflow
Domain stage agent_infra (path word 'spider'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file graph.json; JSON file chemistry.json; JSON file vedic.json; JSON file random.json.
Downstream impact
Used directly by 1 file: Sources (ventus-grid-engine).
What it achieves
Graphs this repository publishes for the Spider dashboard (ventus-grid-engine `spider/manifest.json`).
Why it matters
Imported by Sources, from Ventus Grid Engine.
Application
stars · spider · configuration
Uses
Stars — Index Page (estate URL)
Used by
named by URL in Sources (estate URL)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
stars@030ebc202d35959fecd162327892f671d1d9a0cc spider/features.yml:1-77 · blob 75a3fb9c3073fa36aa72ba3beffcc8800abc7307 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: none found · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
# Graphs this repository publishes for the Spider dashboard (ventus-grid-engine spider/manifest.json).
# Written by spider/register.py on every build. Each entry has the same fields as a manifest entry.
schema_version: spider-features-v1
site: "https://ventusltd.github.io/stars/"
graphs:
  - id: "modular"
    title: "Reuse"
    path: "https://ventusltd.github.io/stars/modular/graph.json"
    edges_path: null
    source_spider: "stars/modular-star (build.mjs)"
    description: "Functions and classes found in two or more different files across the public Ventusltd repositories, wired to the repositories they live in and to other families sharing their name. Node ids are permanent numbers (family:N); GitHub opens the exact lines; External opens the code report (every place it is used, the live page, the numbered lines, copy). Rebuilt hourly on GitHub Acti  … [line shortened here: 405 characters; full line on GitHub]
    nodes: 303
    edges: 1025
    graph_generated_utc: "2026-12-05T23:26:43.596Z"
  - id: "sense"
    title: "Assessment"
    path: "https://ventusltd.github.io/stars/sense/graph.json"
    edges_path: null
    source_spider: "stars/modular-star (sense.mjs)"
    description: "The code universe charted into sense: what is canonical and what is a copy, what depends on what, what is proven together and what is untested, what is a decision rather than a fact. Ordered from the whole to the parts."
    nodes: 142
    edges: 628
    graph_generated_utc: "2026-12-05T23:28:34.597Z"
  - id: "proof-of-work"
    title: "Audit"
    path: "https://ventusltd.github.io/stars/proof/graph.json"
    edges_path: null
    source_spider: "stars/modular-star (proof.mjs)"
    description: "What ran, when, what it produced and which checks it passed: the workflows, their latest runs and their artefacts."
    nodes: 40
    edges: 68
    graph_generated_utc: "2026-12-05T23:28:34.711Z"
  - id: "structure"
    title: "Structure"
    path: "https://ventusltd.github.io/stars/structure/graph.json"
    edges_path: null
    source_spider: "stars/modular-star (structure.mjs)"
    description: "globalgrid2050 architecture development, top-down: repositories, the blocks in each, and the engine modules in their canonical order."
    nodes: 141
    edges: 455
    graph_generated_utc: "2026-12-05T23:28:43.980Z"
  - id: "decisions"
    title: "Decisions"
    path: "https://ventusltd.github.io/stars/decisions/graph.json"
    edges_path: null
    source_spider: "stars/modular-star (decisions.mjs)"
    description: "The judgements attached to the maps' permanent keys: one card per decision record, open (amber), decided (green) or superseded (grey), wired to the block, constant or function family it concerns. A decided record is permission; an open record is a question. Records are made by clicks from the Decision issue form."
    nodes: 37
    edges: 39
    graph_generated_utc: "2026-12-05T23:28:18.315Z"
  - id: "chemistry"
    title: "Compatibility"
    path: "https://ventusltd.github.io/stars/spider/graphs/chemistry.json"
    edges_path: null
    source_spider: "star-maker (chemistry.mjs), rebuilt by stars"
    description: "Which combinations of GridAtlas components always work, which fail, and the error each failure produces. Arithmetic over every recorded composition test."
    nodes: 125
    edges: 129
    graph_generated_utc: "2026-12-05T23:30:29.164Z"
  - id: "vedic"
    title: "Classification"
    path: "https://ventusltd.github.io/stars/spider/graphs/vedic.json"
    edges_path: null
    source_spider: "star-maker (vedic.mjs), rebuilt by stars"
    description: "The five classes of the code (structure, movement, computation, flow, data), what is never used, and whether each test loaded the map's parts in the declared order."
    nodes: 305
    edges: 300
    graph_generated_utc: "2026-12-05T23:30:29.626Z"
  - id: "random"
    title: "Sampling"
    path: "https://ventusltd.github.io/stars/spider/graphs/random.json"
    edges_path: null
    source_spider: "star-maker (random.mjs), rebuilt by stars"
    description: "Randomly chosen links between components, for tripping over dependencies nobody wrote down. Prompts to look, not findings."
    nodes: 168
    edges: 150
    graph_generated_utc: "2026-12-05T23:30:30.032Z"

Register

A Python module in the spider folder of Stars that registers the graphs this repository publishes for the Spider dashboard.

energy-datastars / spider/register.py · lines 1–123 of 123 · Entry point · pattern adapt (shared by 2 files)

What it does
It loads data. Defines adapt, yaml_str. Uses libraries json, pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'spider'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file graph.json.
Downstream impact
Used directly by 2 files: Modular Star Workflow (stars); Refresh Workflow (stars).
What it achieves
Defines `adapt` and `yaml_str`.
Why it matters
Run by Modular Star Workflow and Refresh Workflow.
Application
stars · spider · Python module
Uses
Stars — Index Page (estate URL), json, pathlib
Used by
run by Modular Star Workflow (workflow run), run by Refresh Workflow (workflow run)
Produces
adapt, yaml_str
Defines here
adapt, yaml_str
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
stars@030ebc202d35959fecd162327892f671d1d9a0cc spider/register.py:1-123 · blob 96d328ee9328e2a75da9541db59e1550fe710536 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
"""Register the graphs this repository publishes for the Spider dashboard.

Writes spider/features.yml, a list of graphs in the same shape as the entries of the dashboard's own
spider/manifest.json (ventus-grid-engine), and adapts any graph that is not yet in the dashboard's format
into spider/graphs/<id>.json. The dashboard's update workflow reads features.yml, checks each graph is
reachable, and adds it. Standard library only; no model involved.
"""
import json
import pathlib

ROOT = pathlib.Path(__file__).resolve().parents[1]
SITE = "https://ventusltd.github.io/stars/"
OUT = ROOT / "spider" / "graphs"

# id, title, source file, who makes it, what it shows. Ids match the local Spider copies where they exist.
GRAPHS = [
    ("modular", "Reuse", "modular/graph.json", "stars/modular-star (build.mjs)",
     "Functions and classes found in two or more different files across the public Ventusltd repositories, wired to the "
     "repositories they live in and to other families sharing their name. Node ids are permanent numbers (family:N); "
     "GitHub opens the exact lines; External opens the code report (every place it is used, the live page, the numbered lines, copy). Rebuilt hourly on GitHub Actions."),
    ("periodic-table", "Inventory", "blocks/graph.json", "stars/modular-star (blocks.mjs)",
     "Every block of globalgrid2050 architecture development with a permanent number and a plain-language description, grouped by category and wired to the "
     "repositories it lives in. Underneath each block are its numbered functions. External opens the table page."),
    ("sense", "Assessment", "sense/graph.json", "stars/modular-star (sense.mjs)",
     "The code universe charted into sense: what is canonical and what is a copy, what depends on what, what is proven together and "
     "what is untested, what is a decision rather than a fact. Ordered from the whole to the parts."),
    ("proof-of-work", "Audit", "proof/graph.json", "stars/modular-star (proof.mjs)",
     "What ran, when, what it produced and which checks it passed: the workflows, their latest runs and their artefacts."),
    ("structure", "Structure", "structure/graph.json", "stars/modular-star (structure.mjs)",
     "globalgrid2050 architecture development, top-down: repositories, the blocks in each, and the engine modules in their canonical order."),
    ("decisions", "Decisions", "decisions/graph.json", "stars/modular-star (decisions.mjs)",
     "The judgements attached to the maps' permanent keys: one card per decision record, open (amber), decided (green) or "
     "superseded (grey), wired to the block, constant or function family it concerns. A decided record is permission; an open "
     "record is a question. Records are made by clicks from the Decision issue form."),
    ("chemistry", "Compatibility", "reports/chemistry/graph.json", "star-maker (chemistry.mjs), rebuilt by stars",
     "Which combinations of GridAtlas components always work, which fail, and the error each failure produces. "
     "Arithmetic over every recorded composition test."),
    ("vedic", "Classification", "reports/vedic/graph.json", "star-maker (vedic.mjs), rebuilt by stars",
     "The five classes of the code (structure, movement, computation, flow, data), what is never used, and whether each "
     "test loaded the map's parts in the declared order."),
    ("random", "Sampling", "reports/random/graph.json", "star-maker (random.mjs), rebuilt by stars",
     "Randomly chosen links between components, for tripping over dependencies nobody wrote down. Prompts to look, "
     "not findings."),
]


def adapt(graph):
    """Bring a graph into the dashboard's generic shape: nodes with ids, edges by id with a type."""
    nodes = graph.get("nodes") or []
    if nodes and all("id" in n for n in nodes):
        return graph, False
    seen = set()
    out_nodes = []
    for n in nodes:
        label = str(n.get("label", ""))
        if not label or label in seen:
            continue
        seen.add(label)
        node = {"id": label, "label": label, "type": n.get("type", "unknown"), "rag": str(n.get("rag", "grey")).lower(),
                "reason": n.get("reason", "")}
        for k in ("gh", "ext"):
            if n.get(k):
                node[k] = n[k]
        out_nodes.append(node)
    index = {n["id"]: i for i, n in enumerate(out_nodes)}
    out_edges = []  # index arrays, the receiver's compact edge form (as genome-spider publishes)
    for e in graph.get("edges") or []:
        a, b = e.get("from"), e.get("to")
        if a in index and b in index:
            out_edges.append([index[a], index[b], e.get("type") or e.get("kind") or "repo"])
    adapted = {k: v for k, v in graph.items() if k not in ("nodes", "edges")}
    adapted["adapted_for"] = "ventus-grid-engine Spider receiver (ids = labels, edge kind = type)"
    adapted["nodes"], adapted["edges"] = out_nodes, out_edges
    return adapted, True


def yaml_str(s):
    return json.dumps(s, ensure_ascii=False)  # a JSON string is a valid YAML double-quoted scalar


features = []
OUT.mkdir(parents=True, exist_ok=True)
for gid, title, src, spider, description in GRAPHS:
    path = ROOT / src
    if not path.exists():
        continue
    graph = json.loads(path.read_text(encoding="utf-8-sig"))
    graph, changed = adapt(graph)
    if not graph["nodes"]:
        continue
    if changed:
        target = OUT / f"{gid}.json"
        target.write_text(json.dumps(graph, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
        url = SITE + "spider/graphs/" + gid + ".json"
    else:
        target, url = path, SITE + src
    if target.stat().st_size > 600 * 1024:  # the dashboard fetches every registered graph on load; Pages gzips, so 600 KB raw is ~90 KB on the wire
        print(f"{gid}: {target.stat().st_size // 1024} KB is over the 600 KB limit, not registered")
        continue
    features.append((gid, title, url, spider, description, len(graph["nodes"]), len(graph["edges"]),
                     graph.get("generated_utc", "")))

lines = [
    "# Graphs this repository publishes for the Spider dashboard (ventus-grid-engine spider/manifest.json).",
    "# Written by spider/register.py on every build. Each entry has the same fields as a manifest entry.",
    "schema_version: spider-features-v1",
    "site: " + yaml_str(SITE),
    "graphs:",
]
for gid, title, url, spider, description, n, e, gen in features:
    lines += [
        f"  - id: {yaml_str(gid)}",
        f"    title: {yaml_str(title)}",
        f"    path: {yaml_str(url)}",
        "    edges_path: null",
        f"    source_spider: {yaml_str(spider)}",
        f"    description: {yaml_str(description)}",
        f"    nodes: {n}",
        f"    edges: {e}",
        f"    graph_generated_utc: {yaml_str(gen)}",
    ]
(ROOT / "spider" / "features.yml").write_text("\n".join(lines) + "\n", encoding="utf-8")
print(f"{len(features)} graphs registered: " + ", ".join(f"{f[0]} ({f[5]} nodes / {f[6]} edges)" for f in features))

Start

A web page in Stars covering solar, substations and cables, and uses data from the ventus-grid-engine and code-generator repositories. Published at https://ventusltd.github.io/stars/start.html.

renderstars / start.html · lines 1–114 of 114 · Entry point

What it does
It draws solar, substations and cables. Defines go. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain terms in the code: solar, substations, cables.
Inputs & outputs
Out: web page.
Downstream impact
Used directly by 4 files: Code (stars, https://ventusltd.github.io/stars/code.html); Stars — Index Page (stars, https://ventusltd.github.io/stars/); Table (stars, https://ventusltd.github.io/stars/table.html); Table — Block Page Rnd Page (testcode). Reached from 382 other entry points, including Code Generator — Index Page (code-generator, https://ventusltd.github.io/code-generator/); Generate (code-generator, https://ventusltd.github.io/code-generator/); 404 (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/404.html). It is itself an entry point, published at https://ventusltd.github.io/stars/start.html.
What it achieves
GlobalGrid2050 architecture development.
Why it matters
Loaded by the Code page at https://ventusltd.github.io/stars/code.html and 3 other pages.
Application
stars · / · page
Uses
Table (link), Code (link), Code Generator — Index Page (link)
Used by
linked from Code (link), linked from Stars — Index Page (link), linked from Table (link), linked from Table — Block Page Rnd Page (link)
Produces
go
Defines here
go
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
stars@030ebc202d35959fecd162327892f671d1d9a0cc start.html:1-114 · blob 23bc23c3ab9b8d5d17c1ab59640e9c0392c658c8 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Start here · globalgrid2050 architecture development</title>
<style>
  :root{color-scheme:dark}
  body{margin:0;padding:16px 18px 40px;background:#0b0d12;color:#d8dee9;font:15px/1.55 ui-monospace,Menlo,Consolas,monospace;max-width:720px}
  a{color:#00e5ff}
  h1{font-size:22px;margin:0 0 4px}
  h2{font-size:17px;margin:0 0 10px;color:#eef2fb}
  .ey{color:#7da0c8;text-transform:uppercase;letter-spacing:.08em;font-size:11px}
  .nav{display:flex;flex-wrap:wrap;gap:6px 14px;margin:10px 0 18px;font-size:13px}
  .muted{color:#8b93a7}
  .step{border:1px solid #2a3140;border-radius:10px;padding:14px;margin:14px 0;background:#0f1218}
  .choice{display:block;width:100%;box-sizing:border-box;text-align:left;background:#12151c;border:1px solid #385464;color:#eef2fb;padding:12px 14px;border-radius:8px;font:inherit;cursor:pointer;margin:8px 0;text-decoration:none}
  .choice:hover,.choice:focus{border-color:#00e5ff;outline:none}
  .choice small{display:block;color:#8b93a7;font-size:12.5px;margin-top:2px}
  .choice .go{color:#00e5ff;font-size:12px}
  .back{background:none;border:none;color:#8b93a7;font:inherit;font-size:13px;cursor:pointer;padding:0;margin:0 0 8px}
  .back:hover{color:#00e5ff}
  .cats a.choice{padding:9px 12px}
  @media(max-width:600px){body{padding:12px 12px 40px}}
</style>
<div class="ey">Ventus · Global Grid 2050</div>
<h1>Start here</h1>
<nav class="nav"><a href="https://globalgrid2050.com/">Home</a><a href="https://ventusltd.github.io/ventus-grid-engine/?graph=periodic-table">Map</a><a href="./table.html">Blocks</a><a href="./code.html">Code report</a></nav>
<p class="muted">Three questions, in plain words, lead you to the right page. No code is shown until you ask for it.</p>

<section class="step" id="s-what">
  <h2>What do you want to do?</h2>
  <button class="choice" data-next="s-built">See what has been built<small>The blocks, the repositories, the whole picture</small></button>
  <button class="choice" data-next="s-find">Find one piece of code<small>By its name, by its subject, or by its number</small></button>
  <button class="choice" data-next="s-check">Check that things work<small>What ran, what passed, what works together</small></button>
  <button class="choice" data-next="s-build">Put blocks together into a new app<small>Choose blocks from the table and generate an app</small></button>
</section>

<section class="step" id="s-built" hidden>
  <button class="back" data-back>← Back</button>
  <h2>How do you want to see it?</h2>
  <a class="choice" href="./table.html">As a table of blocks, by subject<small>63 named blocks, each with a permanent number and a plain description. The best first view.</small><span class="go">Blocks page →</span></a>
  <a class="choice" href="https://ventusltd.github.io/ventus-grid-engine/?graph=structure">Top-down: which repository holds what<small>Repositories, the blocks in each, and the engine modules in order</small><span class="go">Structure map →</span></a>
  <a class="choice" href="https://ventusltd.github.io/ventus-grid-engine/?graph=federation">As the list of repositories<small>The repositories and how they relate</small><span class="go">Repositories map →</span></a>
  <a class="choice" href="https://ventusltd.github.io/ventus-grid-engine/?graph=gridatlas-lineage">How the current map was composed<small>The map's ancestry, version by version</small><span class="go">Lineage map →</span></a>
</section>

<section class="step" id="s-find" hidden>
  <button class="back" data-back>← Back</button>
  <h2>Do you know its name?</h2>
  <a class="choice" href="./code.html">Yes, roughly<small>Type part of the name; matches appear as you type. Code is shown only when you open one.</small><span class="go">Code report →</span></a>
  <button class="choice" data-next="s-subject">No, but I know the subject<small>Distance, grid network, capacity, map layers, news, solar…</small></button>
  <button class="choice" data-next="s-number">I have a number<small>A block number (1 to 63 and up) or a function number (#511 and up)</small></button>
</section>

<section class="step" id="s-subject" hidden>
  <button class="back" data-back>← Back</button>
  <h2>Which subject?</h2>
  <div class="cats">
    <a class="choice" href="./table.html?category=geodesy">Distances on the earth<small>Distance, bearing, area, circles, GeoJSON</small></a>
    <a class="choice" href="./table.html?category=network">The grid network<small>Topology, electrical distance, ratings, fault level, voltage</small></a>
    <a class="choice" href="./table.html?category=connections">Connections and capacity<small>Can a site connect, how much, and what it costs</small></a>
    <a class="choice" href="./table.html?category=layers">Data drawn on the map<small>Substations, lines by voltage, power plants, data centres, railways</small></a>
    <a class="choice" href="./table.html?category=cartridges">Plug-in parts of the map<small>Search, substation intelligence, the single-line sandbox</small></a>
    <a class="choice" href="./table.html?category=arrival">Links that land on the right place<small>The MAP button and place search</small></a>
    <a class="choice" href="./table.html?category=news">Pipeline News<small>The news site and its panels</small></a>
    <a class="choice" href="./table.html?category=solar">Solar, batteries and cables<small>Site layout, single-line diagrams, cable trenches</small></a>
    <a class="choice" href="./table.html?category=interface">Menus and page controls<small>Menu bars, teleprinter controls, page shells</small></a>
    <a class="choice" href="./table.html?category=constants">Numbers everyone must agree on<small>Earth radius, allowed technologies, statuses: some not yet agreed</small></a>
    <a class="choice" href="./table.html?category=proofs">Checks on the other code<small>Proofs, verifiers, the spiders that draw these maps</small></a>
    <a class="choice" href="./table.html?category=other">Everything else<small>Blocks found automatically from source files</small></a>
  </div>
</section>

<section class="step" id="s-number" hidden>
  <button class="back" data-back>← Back</button>
  <h2>What kind of number is it?</h2>
  <a class="choice" href="./table.html">A block number, for example 13<small>Blocks are numbered from 1. Open the table and tap the tile with that number.</small><span class="go">Blocks page →</span></a>
  <a class="choice" href="./code.html">A function number, for example #511<small>Type the number into the search box on the code report.</small><span class="go">Code report →</span></a>
</section>

<section class="step" id="s-check" hidden>
  <button class="back" data-back>← Back</button>
  <h2>What do you want to check?</h2>
  <a class="choice" href="https://ventusltd.github.io/ventus-grid-engine/?graph=proof-of-work">That the hourly build ran and passed<small>What ran, when, what it produced, which checks passed</small><span class="go">Audit map →</span></a>
  <a class="choice" href="https://ventusltd.github.io/ventus-grid-engine/?graph=chemistry">Which parts of the map work together<small>Combinations that always work, combinations that fail, and the error each gives</small><span class="go">Compatibility map →</span></a>
  <a class="choice" href="https://ventusltd.github.io/ventus-grid-engine/?graph=sense">What is the original and what is a copy<small>What is proven, what is untested, what is still a decision</small><span class="go">Assessment map →</span></a>
  <a class="choice" href="https://ventusltd.github.io/ventus-grid-engine/?graph=modular">Which functions are written more than once<small>The same logic in two or more files, and where</small><span class="go">Reuse map →</span></a>
</section>

<section class="step" id="s-build" hidden>
  <button class="back" data-back>← Back</button>
  <h2>Build a new app</h2>
  <a class="choice" href="./table.html">1. Choose blocks from the table<small>Open a block and tap "Add to an app". Blocks with no code of their own cannot be added.</small><span class="go">Blocks page →</span></a>
  <a class="choice" href="https://ventusltd.github.io/ventus-grid-engine/?graph=generated-apps">2. See the apps already built<small>Each app and the blocks it is made of</small><span class="go">Applications map →</span></a>
  <a class="choice" href="https://ventusltd.github.io/code-generator/">3. Go straight to the generator<small>Generating an app needs a GitHub account with access to the code-generator repository.</small><span class="go">Code generator →</span></a>
</section>

<p class="muted" style="margin-top:22px">On the map pages, "Tap does" sets what a tap on a card does: Explore shows its links; External opens its page here. <a href="https://github.com/Ventusltd/stars/blob/main/MODULAR-STAR.md">What this is</a></p>
<script>
const steps = [...document.querySelectorAll('.step')];
const trail = [];
function go(id, push) {
  if (!document.getElementById(id)) id = 's-what';
  steps.forEach(s => s.hidden = s.id !== id);
  if (push) trail.push(id);
  if (location.hash !== '#' + id) history.replaceState(null, '', id === 's-what' ? location.pathname : '#' + id);
  window.scrollTo(0, 0);
}
document.querySelectorAll('[data-next]').forEach(b => b.onclick = () => go(b.dataset.next, true));
document.querySelectorAll('[data-back]').forEach(b => b.onclick = () => { trail.pop(); go(trail[trail.length - 1] || 's-what', false); });
window.onhashchange = () => go(location.hash.slice(1) || 's-what', true);
go(location.hash.slice(1) || 's-what', true);
</script>
</html>

Table

A web page in Stars that draws blocks and uses data from the ventus-grid-engine and Code Generator repositories. Published at https://ventusltd.github.io/stars/table.html. It closes panel (`closePanel`) and shows category (`showCategory`).

renderstars / table.html · lines 1–118 of 118 · Entry point · pattern showCategory (shared by 3 files)

What it does
It draws blocks. Defines 7 functions or classes, including $, esc, byName, closePanel, show. Side effects: changes the web page (DOM); makes network requests.
Inputs & outputs
In: data source: ventus-grid-engine data; data source: code-generator data; JSON file blocks.json. Out: web page.
Downstream impact
Used directly by 28 files: Table (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/05-periodic-table/); Code (stars, https://ventusltd.github.io/stars/code.html); Stars — Index Page (stars, https://ventusltd.github.io/stars/); Start (stars, https://ventusltd.github.io/stars/start.html); and 24 more. Reached from 359 other entry points, including 404 (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/404.html); Galaxies Wafers — App (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/); Galaxies Wafers — Index Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/). It is itself an entry point, published at https://ventusltd.github.io/stars/table.html.
What it achieves
Periodic table of GlobalGrid2050 architecture development. It reads `./blocks/blocks.json`.
Why it matters
Loaded by the Code page at https://ventusltd.github.io/stars/code.html and 24 other pages. Also imported by a file of the same name, Lens Grammar Proof and Generate, from Code Generator, Galaxies Wafers and GlobalGrid2050.
Application
stars · / · page
Uses
Start (link), Code (link), Code Generator — Index Page (link)
Used by
named by URL in Table (estate URL), linked from Code (link), linked from Stars — Index Page (link), linked from Start (link), linked from Spiders — Index Page (link), linked from Species — Estate Activity Page (link), named by URL in Lens Grammar Proof (estate URL), named by URL in Generate (estate URL), and 20 more
Produces
$, esc, byName, closePanel, show, showCategory, tile
Defines here
$, esc, byName, closePanel, show, showCategory, tile
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
stars@030ebc202d35959fecd162327892f671d1d9a0cc table.html:1-118 · blob 10090e0f73120f5bf19b9604ab6812d7f338fe06 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: unknown
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Periodic table of globalgrid2050 architecture development</title>
<style>
  :root{color-scheme:dark}
  body{margin:0;padding:16px 18px 40px;background:#0b0d12;color:#eef2fb;font:14px/1.5 Inter,ui-sans-serif,system-ui,sans-serif}
  a{color:#00e5ff}
  h1{font-size:22px;margin:0 0 4px}
  .ey{font-family:ui-monospace,monospace;font-size:11px;letter-spacing:.2em;text-transform:uppercase;color:#00e5ff}
  .nav{display:flex;flex-wrap:wrap;gap:6px 14px;margin:8px 0 10px;font-size:13px;font-family:ui-monospace,monospace}
  .muted{color:#9aa3b5}
  .cat{margin:18px 0 6px;display:flex;align-items:baseline;gap:10px;flex-wrap:wrap;scroll-margin-top:8px}
  .cat h2{font-size:14px;margin:0;letter-spacing:.06em;text-transform:uppercase}
  .cat.on h2{text-decoration:underline;text-underline-offset:4px}
  .grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(112px,1fr));gap:8px}
  .tile{border:1px solid #262b36;border-radius:10px;padding:8px 9px;background:linear-gradient(160deg,rgba(255,255,255,.055),rgba(255,255,255,.014));cursor:pointer;min-height:78px;display:flex;flex-direction:column;gap:2px}
  .tile:hover,.tile.on{border-color:#00e5ff;box-shadow:0 0 0 1px rgba(0,229,255,.22)}
  .tile .sym{font-family:ui-monospace,monospace;font-size:20px;font-weight:700;line-height:1}
  .tile .num{font-family:ui-monospace,monospace;font-size:10px;color:#9aa3b5}
  .tile .t{font-size:11.5px;line-height:1.2;color:#dfe6f3}
  .tile .n{font-family:ui-monospace,monospace;font-size:10px;color:#9aa3b5;margin-top:auto}
  .panel{position:sticky;bottom:0;border:1px solid #00e5ff;border-radius:14px;background:#12151c;padding:14px;margin-top:18px;box-shadow:0 -10px 40px rgba(0,0,0,.4);max-height:70vh;overflow:auto}
  .panel h3{margin:0 0 4px;font-size:18px;padding-right:36px}
  .close{position:absolute;top:8px;right:10px;background:none;border:1px solid #385464;color:#9aa3b5;border-radius:999px;width:28px;height:28px;font:inherit;cursor:pointer}
  .close:hover{border-color:#00e5ff;color:#eef2fb}
  .btn{display:inline-block;background:#0f1218;border:1px solid #385464;color:#eef2fb;padding:7px 12px;border-radius:999px;font:inherit;font-size:13px;cursor:pointer;margin:6px 6px 0 0;text-decoration:none}
  .btn:hover{border-color:#00e5ff}
  .btn.first{border-color:#00e5ff}
  details{margin-top:8px}summary{cursor:pointer;color:#9aa3b5;font-size:13px}
  .inside{font-family:ui-monospace,monospace;font-size:12px;columns:2;column-gap:20px}
  .filter{margin:8px 0 0;font-size:13px}
  @media(max-width:600px){.inside{columns:1}.grid{grid-template-columns:repeat(auto-fill,minmax(96px,1fr))}body{padding:12px 12px 40px}}
</style>
<div class="ey">Ventus · Global Grid 2050</div>
<h1>Periodic table of globalgrid2050 architecture development</h1>
<nav class="nav"><a href="https://ventusltd.github.io/ventus-grid-engine/?graph=periodic-table">← Map</a><a href="https://globalgrid2050.com/">Home</a><a href="./start.html">Start here</a><a href="./code.html">Code report</a></nav>
<div class="muted" id="status">Loading…</div>
<div class="muted">Tap a block to see what it does, where it runs and what it needs.</div>
<div class="filter" id="filter" hidden></div>
<div id="table"></div>
<div class="panel" id="panel" hidden></div>
<p class="muted" style="margin-top:20px">Every block has a permanent number. Numbers 1 to 47 are the original elements; later numbers are blocks added as the code is read. Underneath each block are its functions, each with its own permanent number; they are the parts list, kept in the background. <a href="https://github.com/Ventusltd/stars/blob/main/MODULAR-STAR.md">What this is</a> · <a href="./s  … [line shortened here: 514 characters; full line on GitHub]
<script>
const $ = s => document.querySelector(s);
const esc = s => String(s).replace(/[&<>"]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
const byName = (a, b) => String(a).localeCompare(String(b), 'en');
let data;
function closePanel() {
  $('#panel').hidden = true;
  document.querySelectorAll('.tile.on').forEach(t => t.classList.remove('on'));
  const q = new URLSearchParams(location.search); q.delete('block');
  history.replaceState(null, '', q.toString() ? '?' + q : location.pathname);
}
function show(sym) {
  const b = data.blocks.find(x => x.symbol === sym); if (!b) return;
  document.querySelectorAll('.tile').forEach(t => t.classList.toggle('on', t.dataset.sym === sym));
  const autos = $('#autos'); if (autos && b.kind === 'auto') autos.open = true;
  const cat = data.categories.find(c => c.id === b.category) || { title: 'Other tools', colour: '#9aa3b5' };
  const p = $('#panel'); p.hidden = false;
  const kind = { constant: 'a value everyone must agree on', engine: 'an engine module', cartridge: 'a plug-in part of the map', layer: 'a map layer', deeplink: 'a link contract', app: 'an app', tool: 'a tool', auto: 'found automatically from one source file' }[b.kind] || b.kind;
  const state = b.state === 'UNSETTLED' ? ' · value not yet agreed' : b.state === 'SETTLED' ? ' · agreed' : '';
  const deps = (b.depends_on || []).slice().sort((x, y) => byName(x.title, y.title));
  const usedBy = (b.used_by || []).slice().sort(byName);
  const inside = (b.inside || []).slice().sort((x, y) => (y.places - x.places) || byName(x.name, y.name));
  const buttons = [
    b.live[0] ? `<a class="btn first" href="${esc(b.live[0])}" target="_blank" rel="noopener">Open the live page</a>` : '',
    `<a class="btn" href="https://ventusltd.github.io/ventus-grid-engine/?graph=periodic-table&focus=${encodeURIComponent(b.symbol + ' · ' + b.title)}">See it on the map</a>`,
    b.functions ? `<a class="btn" href="https://ventusltd.github.io/code-generator/?blocks=${encodeURIComponent(b.symbol)}">Add to an app</a>` : '',
    b.files[0] ? `<a class="btn" href="https://github.com/${esc(b.files[0].repo)}/blob/${esc(b.files[0].commit)}/${esc(b.files[0].path)}" target="_blank" rel="noopener">Source on GitHub</a>` : ''
  ].join('');
  p.innerHTML = `<button class="close" id="close" title="Close" aria-label="Close">×</button>
    <div class="ey" style="color:${cat.colour}">${esc(cat.title)} · block ${b.number}</div>
    <h3><span style="font-family:ui-monospace,monospace">${esc(b.symbol)}</span> ${esc(b.title)}</h3>
    <div>${esc(b.description)}</div>
    <div class="muted" style="margin-top:6px">${esc(kind)}${state}${b.functions ? ` · ${b.functions} functions inside (${b.named_functions} named)` : ' · no code of its own'}${b.repos.length ? ' · lives in ' + b.repos.map(r => esc(r.split('/')[1])).sort(byName).join(', ') : ''}${b.first_written ? ' · first written ' + b.first_written.slice(0, 10) : ''}</div>
    <div>${buttons}</div>
    ${deps.length ? `<div style="margin-top:8px"><span class="muted">Depends on:</span> ${deps.map(d => `<a href="?block=${esc(d.symbol)}">${esc(d.symbol)} ${esc(d.title)}</a> <span class="muted">(through ${d.via.map(esc).join(", ")})</span>`).join("; ")}</div>` : ""}${usedBy.length ? `<div><span class="muted">Used by:</span> ${usedBy.map(s => `<a href="?block=${esc(s)}">${esc(s)}</a>`).join(", ")  … [line shortened here: 414 characters; full line on GitHub]
    ${b.needs.length ? `<div style="margin-top:6px"><span style="color:#ffd54a">Needs from elsewhere:</span> ${b.needs.slice(0, 8).map(n => esc(n.meaning)).join('; ')}</div>` : ''}
    ${inside.length ? `<details><summary>Inside: the parts list (${inside.length} of ${b.named_functions} named functions, most used first)</summary><div class="inside">${inside.map(f => `<div><a href="./code.html?family=${f.family}">#${f.family}</a> ${esc(f.name)} <span class="muted">×${f.places}</span></div>`).join('')}</div></details>` : ''}`;
  $('#close').onclick = closePanel;
  document.querySelectorAll('#panel a[href^="?block="]').forEach(a => a.onclick = e => { e.preventDefault(); show(new URLSearchParams(a.getAttribute('href')).get('block')); });
  const q = new URLSearchParams(location.search); q.set('block', sym);
  history.replaceState(null, '', '?' + q);
}
function showCategory(id) {
  const cat = data.categories.find(c => c.id === id); const f = $('#filter');
  document.querySelectorAll('.cat').forEach(el => el.classList.toggle('on', el.dataset.cat === id));
  if (!cat) { f.hidden = true; return; }
  f.hidden = false;
  f.innerHTML = `Showing the subject <b style="color:${cat.colour}">${esc(cat.title)}</b> · <a href="./table.html">show every subject</a>`;
  const h = document.getElementById('h-' + id); if (h) h.scrollIntoView({ block: 'start' });
}
(async () => {
  try {
    data = await (await fetch('./blocks/blocks.json', {cache: 'no-cache'})).json();
    const named = data.blocks.filter(b => b.kind !== 'auto'), autos = data.blocks.filter(b => b.kind === 'auto');
    $('#status').textContent = `${named.length} named blocks and ${autos.length} blocks found automatically from source files · ${data.blocks.reduce((s, b) => s + b.functions, 0).toLocaleString('en-GB')} functions underneath · updated ${data.generated_utc.slice(0, 16).replace('T', ' ')} UTC`;
    const t = $('#table');
    const tile = (b, c) => `<div class="tile" data-sym="${esc(b.symbol)}" style="border-top:3px solid ${c.colour}"><div class="num">${b.number}</div><div class="sym">${esc(b.symbol)}</div><div class="t">${esc(b.title)}</div><div class="n">${b.functions ? b.functions + ' functions' : 'data only'}${b.state === 'UNSETTLED' ? ' · not agreed' : ''}</div></div>`;
    for (const c of data.categories) {
      const all = data.blocks.filter(b => b.category === c.id && (b.kind !== 'auto' || b.functions >= 8)).sort((a, b) => a.number - b.number);
      if (!all.length) continue;
      const bs = all.filter(b => b.kind !== 'auto'), as = all.filter(b => b.kind === 'auto');
      t.insertAdjacentHTML('beforeend', `<div class="cat" id="h-${esc(c.id)}" data-cat="${esc(c.id)}"><h2 style="color:${c.colour}"><a href="?category=${esc(c.id)}" style="color:inherit;text-decoration:none">${esc(c.title)}</a></h2><span class="muted">${esc(c.blurb)}</span></div>`);
      if (bs.length) t.insertAdjacentHTML('beforeend', `<div class="grid">${bs.map(b => tile(b, c)).join('')}</div>`);
      if (as.length) t.insertAdjacentHTML('beforeend', `<details id="autos"><summary>${as.length} blocks found automatically from source files, in number order (tap to show)</summary><div class="grid" style="margin-top:8px">${as.map(b => tile(b, c)).join('')}</div></details>`);
    }
    document.querySelectorAll('.tile').forEach(el => el.onclick = () => show(el.dataset.sym));
    document.querySelectorAll('.cat h2 a').forEach(a => a.onclick = e => { e.preventDefault(); const id = new URLSearchParams(a.getAttribute('href')).get('category'); history.replaceState(null, '', '?category=' + id); showCategory(id); });
    const q = new URLSearchParams(location.search);
    if (q.get('category')) showCategory(q.get('category'));
    if (q.get('block')) show(q.get('block'));
  } catch (e) { $('#status').textContent = 'The table is not published yet: ' + e.message; }
})();
</script>
</html>