GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / testcode / tools

To Kuiper and 1 more file

A Python command-line tool in Worlds covering solar, using SHA-256. It is built from the grid step (`grid`).

241 lines of Python and JavaScript from testcode, worlds-, in 2 files. Topic: Kuiper, cosmos and drawing engines. Section 1587 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. Spider Universe Served render · testcode / tools/spider-universe-served.mjs lines 1–90
  2. To Kuiper other · worlds- / src/to_kuiper.py lines 1–151

Spider Universe Served

A JavaScript module in the tools folder of Testcode using data from the stars repository. It is built from the act step (`act`).

rendertestcode / tools/spider-universe-served.mjs · lines 1–90 of 90 · Entry point

What it does
It draws its content. Defines act. Uses libraries playwright. Side effects: changes the web page (DOM); makes network requests; starts processes.
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: data source: stars data; JSON file index.json.
Downstream impact
Used directly by 1 file: Spider Universe Served Workflow (testcode).
What it achieves
Served-page proof for a GlobalGrid2050 Spider universe generation on `globalgrid2050.com/testcode/` /.
Why it matters
Run by Spider Universe Served Workflow.
Application
testcode · tools · JavaScript module
Uses
playwright
Used by
run by Spider Universe Served Workflow (workflow run)
Produces
act
Defines here
act
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 tools/spider-universe-served.mjs:1-90 · blob ef02dc33376db144bf0aa0f88b83ee79009e62f7 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network, process · domain stage: agent_infra · users: ai_agent · canonical: unknown
// Served-page proof for a GLOBALGRID2050 Spider universe generation on globalgrid2050.com/testcode/<generation>/.
// For each of the ten read-only versions, at phone (430) and desktop (1280) width, in Chromium:
//   1. the page reaches the live counts (10,811 function families) with no page error;
//   2. its own picture renders (a version-specific selector and minimum count, measured, printed);
//   3. the family journey: search "effectiveGap" -> open #2 -> numbered line 9 carries its code;
//   4. "contained in" opens that family's block without a page error, and the trail grows.
// A missing browser, page or data is a FAIL, never a skip. Usage: GENERATION=202609141350 node tools/spider-universe-served.mjs
import { chromium } from 'playwright';
const GEN = process.env.GENERATION;
if (!/^\d{12}$/.test(GEN || '')) { console.error('FAIL: GENERATION must be a 12-digit UTC stamp'); process.exit(1); }
const BASE = `https://globalgrid2050.com/testcode/${GEN}/`;
const PICTURE = {
  'v01-spider-drill': ['#left .card, #right .card', 12],
  'v02-radial-sunburst': ['#sun path.seg', 200],
  'v03-particle-universe': ['canvas#sky', 1],
  'v04-periodic-arrows': ['.tile', 207],
  'v05-chord-dependencies': ['path.chord', 50],
  'v06-treemap-lines': ['#map .cell', 12],
  'v07-flow-repos': ['path.band', 50],
  'v08-ring-journey': ['circle.b', 207],
  'v09-line-river': ['.mini button', 207],
  'v10-ide-search': ['#nav details', 12],
};
const results = []; const check = (v, w, name, ok, detail = '') => { results.push(ok); console.log(`${ok ? 'PASS' : 'FAIL'} [${v} @${w}] ${name}${detail ? ' — ' + detail : ''}`); };
const browser = await chromium.launch();
for (const [v, [sel, min]] of Object.entries(PICTURE)) for (const width of [430, 1280]) {
  // 430 px is driven as a touch phone (Codex's headless run timed out v01/v03/v04 under emulated touch at the live-page step)
  const touch = width === 430;
  const context = await browser.newContext({ viewport: { width, height: 900 }, hasTouch: touch, isMobile: touch });
  const page = await context.newPage();
  const act = async loc => { if (touch) await loc.tap(); else await loc.click(); };
  const errors = []; page.on('pageerror', e => errors.push(String(e).slice(0, 160)));
  
  try {
    const t0 = Date.now();
    const resp = await page.goto(`${BASE}${v}/index.html`, { waitUntil: 'domcontentloaded' });
    check(v, width, 'page served', resp && resp.status() === 200, `HTTP ${resp && resp.status()}`);
    // the counts are live data and move with every Modular star run (10,811 families at 13:50 UTC, 10,912 at 15:25 UTC): require the shape, then compare with index.json
    await page.waitForFunction(() => /[\d,]{5,} function families · [\d,]{6,} unique numbered lines/.test(document.body.innerText), null, { timeout: 45000 });
    const idx = await fetch('https://ventusltd.github.io/stars/code/index.json').then(r => r.json());
    const shown = await page.evaluate(() => document.body.innerText.match(/([\d,]+) function families · ([\d,]+) unique numbered lines/));
    check(v, width, 'live counts shown and equal to index.json', !!shown && shown[1] === idx.families.toLocaleString('en-GB') && shown[2] === idx.lines.toLocaleString('en-GB'), `${Date.now() - t0} ms; page ${shown && shown[1]}/${shown && shown[2]}, index ${idx.families}/${idx.lines}`);
    await page.waitForTimeout(1200);
    const n = await page.locator(sel).count();
    check(v, width, `picture renders (${sel} >= ${min})`, n >= min, `${n}`);
    await page.fill('.u-search', 'effectiveGap');
    const hit = page.locator('.u-hits button', { hasText: '#2 effectiveGap' }).first();
    await hit.waitFor({ timeout: 10000 }); await act(hit);
    await page.waitForFunction(() => [...document.querySelectorAll('.u-line, .ln')].some(e => /(^|\s)9\s*│.*effectiveGap/.test(e.textContent)), null, { timeout: 30000 });
    check(v, width, 'search -> family #2 -> numbered line 9 carries its code', true);
    // relationship hop: #2 is used by #9 — follow that arrow, then check the new family's source link and step back
    const usedBy = page.locator('button', { hasText: /^#9\b/ }).first();
    const hadUsedBy = await usedBy.count();
    if (hadUsedBy) await act(usedBy);
    const hopped = hadUsedBy ? await page.waitForFunction(() => /#9 /.test(document.body.innerText) && [...document.querySelectorAll('#trail a')].some(a => /^#9 /.test(a.textContent)), null, { timeout: 30000 }).then(() => true, () => false) : false;
    check(v, width, 'used-by arrow #2 -> #9 opens that family and adds it to the trail', hopped, hadUsedBy ? '' : 'no #9 control');
    const src = await page.locator('a', { hasText: 'File at commit' }).last().getAttribute('href').catch(() => null);
    check(v, width, 'the hop target links to its file at the pinned commit with a line anchor', /^https:\/\/github\.com\/Ventusltd\/[^/]+\/blob\/[0-9a-f]{40}\/.+#L\d+-L\d+$/.test(src || ''), src || 'no link');
    const back = page.locator('#trail a', { hasText: /^#2 / }).first();
    const hadBack = await back.count();
    if (hadBack) { await act(back); await page.waitForTimeout(1500); }
    const trailAfterBack = await page.locator('#trail a').allTextContents();
    check(v, width, 'the trail steps back to #2', hadBack > 0 && /^#2 /.test(trailAfterBack[trailAfterBack.length - 1] || ''), trailAfterBack.slice(-2).join(' › '));
    if (hadBack) { // re-open #2 so the containing-block step below starts from the family panel, whichever way the version handles "back"
      await page.fill('.u-search', 'effectiveGap'); await act(page.locator('.u-hits button', { hasText: '#2 effectiveGap' }).first());
      await page.waitForFunction(() => [...document.querySelectorAll('.u-line, .ln')].some(e => /(^|\s)9\s*│/.test(e.textContent)), null, { timeout: 30000 });
    }
    const trail0 = await page.locator('#trail a').count();
    const up = page.locator('button', { hasText: 'contained in' }).first();
    // count the control BEFORE clicking: versions that replace the panel when the block opens remove it
    const had = await up.count();
    if (had) { await act(up); await page.waitForTimeout(1500); }
    const trail1 = await page.locator('#trail a').count();
    check(v, width, '"contained in" opens the block and the trail grows', had > 0 && trail1 > trail0, `control ${had ? 'present' : 'absent'}; trail ${trail0} -> ${trail1}`);
    // the live page must open from the family panel by tap or click (a new tab), the last step of the journey
    await page.fill('.u-search', 'effectiveGap'); await act(page.locator('.u-hits button', { hasText: '#2 effectiveGap' }).first());
    const live = page.locator('a.u-chip.live').first(); await live.waitFor({ timeout: 15000 });
    const [popup] = await Promise.all([page.waitForEvent('popup', { timeout: 15000 }).catch(() => null), act(live)]);
    check(v, width, `live page opens in a new tab by ${touch ? 'tap' : 'click'}`, !!popup, popup ? await popup.url() : 'no popup');
    if (popup) await popup.close();
    check(v, width, 'no page errors', errors.length === 0, errors.join(' | '));
  } catch (e) {
    check(v, width, 'journey ran to the end', false, String(e).split('\n')[0].slice(0, 200));
    if (errors.length) console.log(`   page errors: ${errors.join(' | ')}`);
  } finally { await context.close(); }
}
await browser.close();
const failed = results.filter(r => !r).length;
console.log(`${results.length - failed}/${results.length} checks passed for generation ${GEN}`);
process.exit(failed ? 1 : 0);

To Kuiper

A Python command-line tool in Worlds covering solar, using SHA-256. It is built from the grid step (`grid`).

otherworlds- / src/to_kuiper.py · lines 1–151 of 151 · Entry point

What it does
Defines grid, main. Uses libraries io, json, os, sys, time. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). Domain terms in the code: solar.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Turn the enumeration into numbers the Kuiper can draw.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
worlds- · src · Python CLI
Uses
Hundred Billion (import), io, json, os, sys, time, numpy, cupy, hashlib
Used by
none found
Produces
grid, main
Defines here
grid, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
worlds-@83817c34790800d4af5057629121d83d0d67a332 src/to_kuiper.py:1-151 · blob 424d7915097edee6aee702e38759e578c7ccce3a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: unknown
"""Turn the enumeration into numbers the Kuiper can draw.

The shape is the estate's own, copied not invented: a data cartridge is a
single const assignment between sentinel comments, carrying its attribution
inside itself, with the payload as integer arrays. TUBE-DATA.js is the
precedent and this follows it exactly.

WHAT IS SHIPPED, AND WHAT IS NOT
Not the space. A billion verdicts regenerate in under a second, so shipping
them would be shipping what a function already gives. What ships is a
PROJECTION: the verdict for every combination of the five axes a reader can
actually turn, held at nominal tolerance, plus the marginal counts from the
full run behind it. 8,100 verdicts is 8 kB; the space behind it is 125 billion.

NO NAMES. No maker, model, project, client or site appears here or in the
output. Module classes are described by their electrical character and power
bin, which is what the arithmetic uses anyway.

    python to_kuiper.py
"""
import io
import json
import os
import sys
import time

import numpy as np

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import hundred_billion as HB   # noqa: E402  the verified kernel and its bins

OUT = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
                   "night-results", "SOLAR-DATA.js")

# the five axes a reader can turn; tolerances held at nominal
AX = [("module_bin", len(HB.B)), ("series", len(HB.SERIES)),
      ("strings", len(HB.STRINGS)), ("site_tmin", len(HB.TMIN)),
      ("ambient", len(HB.INV_KVA))]


def grid():
    """One verdict per turnable combination, at nominal tolerance."""
    n = int(np.prod([c for _k, c in AX]))
    idx = np.zeros(n, dtype=np.int64)
    # rebuild a full-space index with tolerance axes pinned to their middle
    vm, bm, gm = HB.N_VOC // 2, HB.N_BETA // 2, HB.N_GAMMA // 2
    k = 0
    for bi in range(len(HB.B)):
        for si in range(len(HB.SERIES)):
            for ni in range(len(HB.STRINGS)):
                for ti in range(len(HB.TMIN)):
                    for ii in range(len(HB.INV_KVA)):
                        v = [bi, si, ni, ti, 1, ii, vm, bm, gm, 0, 1]
                        lin, mul = 0, 1
                        for val, rad in zip(v, HB.RAD):
                            lin += val * mul
                            mul *= rad
                        idx[k] = lin
                        k += 1
    return idx


def main():
    idx = grid()
    print("projection: %s turnable combinations out of a space of %s"
          % ("{:,}".format(len(idx)), "{:,}".format(HB.SIZE)))

    cpu = HB.reference(idx[:4000])
    try:
        import cupy as cp
        K = cp.ElementwiseKernel(
            "int64 idx, raw float64 tvoc, raw float64 tisc, raw float64 tvmp, "
            "raw float64 twp, raw float64 tbeta, raw float64 tgamma, "
            "raw float64 tk, raw float64 ser, raw float64 strs, "
            "raw float64 tmin, raw float64 thot, raw float64 inv",
            "int64 code", HB.SRC, "ventus_100b")
        cols = list(zip(*HB.B))
        T = tuple(cp.asarray(np.array(c, float)) for c in cols) + (
            cp.asarray(np.array(HB.SERIES, float)),
            cp.asarray(np.array(HB.STRINGS, float)),
            cp.asarray(np.array(HB.TMIN, float)),
            cp.asarray(np.array(HB.THOT, float)),
            cp.asarray(np.array(HB.INV_KVA, float)))
        t0 = time.perf_counter()
        codes = cp.asnumpy(K(cp.asarray(idx), *T))
        sec = time.perf_counter() - t0
        backend = "cupy"
    except Exception as exc:
        print("  cupy unavailable (%r) - the processor did it" % (exc,))
        t0 = time.perf_counter()
        codes = HB.reference(idx)
        sec = time.perf_counter() - t0
        backend = "numpy"

    differ = int((codes[:4000] != cpu).sum())
    print("  verified: processor vs %s on 4,000 of %s cells, %d differ"
          % (backend, "{:,}".format(len(idx)), differ))
    if differ:
        print("  FAIL: nothing is written for arithmetic that differs.")
        return 1

    counts = [int((codes == k).sum()) for k in range(len(HB.LABEL))]
    bins = [{"bin_w": int(b[3]), "voc": b[0], "isc": b[1], "vmp": b[2],
             "beta_pct_per_K": b[4], "gamma_pct_per_K": b[5],
             "bifacial_k": b[6]} for b in HB.B]

    payload = {
        "attribution": "Module electrical characteristics read from published "
                       "manufacturer datasheets; inverter limits and ambient "
                       "derating read from a published inverter datasheet. No "
                       "maker, model, project or site is named, by rule. "
                       "Sizing rules are Ventus Ltd's own, reproduced against "
                       "brute force in 2520 of 2520 design cells.",
        "made": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
        "what_this_is": "DC sizing verdicts. Not a design, not a study, not a "
                        "connection assessment. Both readings of the "
                        "cold-voltage clause are kept and neither is collapsed.",
        "space_behind_it": HB.SIZE,
        "verdicts": {"labels": HB.LABEL, "counts_in_projection": counts},
        "axes": [{"name": k, "steps": c} for k, c in AX],
        "values": {"module_bin_w": [int(b[3]) for b in HB.B],
                   "series": HB.SERIES, "strings": HB.STRINGS,
                   "site_tmin_c": HB.TMIN,
                   "ambient_c": HB.AMBIENT,
                   "inverter_kva": HB.INV_KVA},
        "module_bins": bins,
        "order": "row-major over axes as listed; index = ((((b*S+s)*N+n)*T+t)*A+a)",
        "verdict_codes": {str(i): HB.LABEL[i] for i in range(len(HB.LABEL))},
        "grid": [int(c) for c in codes],
    }
    js = ("/* SOLAR-DATA:START */ const SOLAR_DATA = "
          + json.dumps(payload, separators=(",", ":"))
          + "; /* SOLAR-DATA:END */\n")
    os.makedirs(os.path.dirname(OUT), exist_ok=True)
    io.open(OUT, "w", encoding="utf-8", newline="\n").write(js)

    import hashlib
    sha = hashlib.sha256(io.open(OUT, "rb").read()).hexdigest()
    print("  computed on %s in %.4f s" % (backend, sec))
    for i, lab in enumerate(HB.LABEL):
        print("    %-32s %7s  %6.2f%%"
              % (lab, "{:,}".format(counts[i]), 100.0 * counts[i] / len(idx)))
    print("\n  wrote %s" % os.path.basename(OUT))
    print("  %s bytes, sha256 %s" % ("{:,}".format(os.path.getsize(OUT)), sha[:40]))
    print("  cartridge shape matches TUBE-DATA.js: one const between sentinels,")
    print("  attribution inside the payload, integers for the grid.")
    return 0


if __name__ == "__main__":
    sys.exit(main())