In this section
- Check Catalogue test · elements / tests/check_catalogue.py lines 1–254
- 404 render · galaxies-wafers / 404.html lines 1–59
- Galaxies Wafers — App render · galaxies-wafers / app.mjs lines 1–387
Check Catalogue
A Python command-line tool in the tests folder of Elements that tests provenance, families and lines meta, using SHA-256.
testelements / tests/check_catalogue.py · lines 1–254 of 254 · Entry point
- What it does
- It tests provenance, families and lines meta. Defines expected_rows, same, problems, main, set_field. Uses libraries copy, hashlib, json, struct, sys. Side effects: reads or writes files; makes network requests; starts processes.
- Inputs & outputs
- In: JSON file provenance.json; JSON file families.json; JSON file all-lines.meta.json.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It sets field (`set_field`) and is built from the expected rows helper (`expected_rows`) and the same step (`same`). Checks of the committed catalogue against its pinned inputs.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- elements · tests · Python CLI
- Uses
- copy, hashlib, json, struct, sys, urllib.request, collections, pathlib
- Used by
- none found
- Produces
- expected_rows, same, problems, main
- Defines here
- expected_rows, same, problems, main, set_field
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- elements@3179b0b8474ca395a949678d6f4d576dc33f3220 tests/check_catalogue.py:1-254 · blob 1b1cc61a1b3b614945baae1d2d1b1e8048f4321d · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, network, process · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
"""Checks of the committed catalogue against its pinned inputs.
Run from the repository root: python tests/check_catalogue.py
WHAT THIS PROVES. This file builds, independently of the builder, the complete row
for every entry from the pinned register copy and the pinned numbered database, and
requires each committed row to equal it exactly, field for field, with no extra and
no missing fields:
- functions: key, title, name, kind, lines, distinct_lines, first_line, last_line,
block, block_in_register, category, repos, files, standalone, first_written,
named_by_register_blocks, description (every value derived from families.json,
lines.bin and the register);
- elements: key, number, symbol, title, description, kind, category, category_title,
state, functions_inside, function_keys, functions_not_in_numbered_database, repos,
live, files, first_written, depends_on, used_by (from the register; membership
against families.json);
- apps: exactly the element rows of kind app, whole rows;
- surfaces: key, url, title, description, blocks;
- provenance: every count (elements, apps, surfaces, families_total,
functions_over_10_lines, numbered_lines, highest_line_key) and the register's
generated_utc and byte length, all with the same JSON types.
It also requires every line key of every catalogued function's sequence to be issued.
WHAT THIS DOES NOT PROVE. That the register or the numbered database are right;
that the register's depends_on and used_by edges are real (they are copied as the
register states them, and references to blocks the register does not hold are
counted and printed, not hidden); that keys were never reused historically; that
any surface is live or any function runs.
Before the real catalogue may pass, every deliberately broken copy below must fail,
including each unchecked-field case a peer review found.
"""
import copy, hashlib, json, struct, sys, urllib.request
from collections import defaultdict
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
load = lambda p: json.loads((ROOT / p).read_text(encoding="utf-8"))
def expected_rows(register, families, fam_lines):
blocks = register["blocks"]
by_sym = {b["symbol"]: b for b in blocks}
cat_title = {c.get("id"): c.get("title") or c.get("id") for c in register.get("categories", []) if isinstance(c, dict)}
named_by = defaultdict(list)
for b in blocks:
for fn in b.get("inside") or []:
named_by[fn["family"]].append(b["symbol"])
funcs = []
for fam in families:
if fam["lineCount"] <= 10:
continue
n, name = fam["n"], fam.get("name")
seq = fam_lines[fam["lineOffset"]: fam["lineOffset"] + fam["lineCount"]]
if fam["lineOffset"] < 0 or fam["lineOffset"] + fam["lineCount"] > len(fam_lines) or len(seq) != fam["lineCount"]:
raise SystemExit(f"family {n} points outside lines.bin")
blk = by_sym.get(fam["block"])
distinct = len(set(seq))
desc = (f"{fam['kind']} {name or '(name not yet known)'} · {fam['lineCount']} line occurrences, "
f"{distinct} distinct line keys · sequence starts at line {seq[0]} and ends at line {seq[-1]} "
f"(endpoints of the sequence, not a numeric range) · "
+ (f"in block {blk['symbol']} {blk['title']}" if blk else f"pack block {fam['block']} (not in the current register)")
+ f" · found in {fam['repos']} repositories and {fam['files']} files · "
+ ("self-contained" if fam.get("standalone") else "needs context")
+ (f" · first written {fam['first_written']}" if fam.get("first_written") else "")
+ " · description not yet written")
funcs.append({
"key": f"family:{n}", "title": f"#{n} {name}" if name else f"#{n} (name not yet known)", "name": name,
"kind": fam["kind"], "lines": fam["lineCount"], "distinct_lines": distinct,
"first_line": f"line:{seq[0]}", "last_line": f"line:{seq[-1]}",
"block": f"block:{fam['block']}", "block_in_register": bool(blk), "category": fam.get("category"),
"repos": fam["repos"], "files": fam["files"], "standalone": bool(fam.get("standalone")),
"first_written": fam.get("first_written"),
"named_by_register_blocks": [f"block:{s}" for s in named_by.get(n, [])], "description": desc,
"_sequence": seq,
})
pack_ids = {f["n"] for f in families}
sym = lambda d: d["symbol"] if isinstance(d, dict) else d
elems = []
for b in blocks:
inside = b.get("inside") or []
elems.append({
"key": f"block:{b['symbol']}", "number": b["number"], "symbol": b["symbol"], "title": b["title"],
"description": b.get("description") or "description not yet written", "kind": b["kind"],
"category": b["category"], "category_title": cat_title.get(b["category"], b["category"]),
"state": b.get("state"), "functions_inside": len(inside),
"function_keys": [f"family:{fn['family']}" for fn in inside],
"functions_not_in_numbered_database": [f"family:{fn['family']}" for fn in inside if fn["family"] not in pack_ids],
"repos": b.get("repos") or [], "live": b.get("live") or [],
"files": [{"repo": f["repo"], "path": f["path"], "commit": f.get("commit")} for f in b.get("files") or []],
"first_written": b.get("first_written"),
"depends_on": [f"block:{sym(d)}" for d in b.get("depends_on") or []],
"used_by": [f"block:{sym(d)}" for d in b.get("used_by") or []],
})
apps = [e for e in elems if e["kind"] == "app"]
surf = defaultdict(set)
for b in blocks:
for u in b.get("live") or []:
surf[u.rsplit("/", 1)[0] + "/"].add(b["symbol"])
surfs = [{"key": f"surface:{u}", "url": u, "title": u.split("://", 1)[-1],
"description": f"served folder recorded as the live address of {len(s)} register blocks",
"blocks": [f"block:{x}" for x in sorted(s)]} for u, s in sorted(surf.items())]
known = {x["key"] for x in elems}
refs = [(e["key"], field, r) for e in elems for field in ("depends_on", "used_by") for r in e[field] if r not in known]
dangling = {"references": len(refs), "source_blocks": len({s for s, _, _ in refs}),
"distinct_targets": sorted({r for _, _, r in refs}),
"by_field": {f: sum(1 for _, g, _ in refs if g == f) for f in ("depends_on", "used_by")}}
return {"functions": funcs, "elements": elems, "apps": apps, "surfaces": surfs}, dangling
def same(a, b):
"""Equality that also requires the same JSON type: True is not 1, 0 is not False."""
if type(a) is not type(b):
return False
if isinstance(a, dict):
return a.keys() == b.keys() and all(same(a[k], b[k]) for k in a)
if isinstance(a, list):
return len(a) == len(b) and all(same(x, y) for x, y in zip(a, b))
return a == b
def problems(cat, prov, exp, keyset):
bad = []
keys = [x["key"] for part in ("elements", "functions", "surfaces") for x in cat[part]]
if len(keys) != len(set(keys)):
bad.append("a key appears more than once")
for part in ("functions", "elements", "apps", "surfaces"):
want = {r["key"]: {k: v for k, v in r.items() if not k.startswith("_")} for r in exp[part]}
got_list = cat[part]
got = {}
for r in got_list:
if r.get("key") in got:
bad.append(f"{part}: {r.get('key')} listed twice")
got[r.get("key")] = r
if len(got_list) != len(exp[part]):
bad.append(f"{part}: {len(got_list)} rows, recomputed {len(exp[part])}")
extra, missing = set(got) - set(want), set(want) - set(got)
if extra or missing:
bad.append(f"{part}: {len(extra)} extra keys, {len(missing)} missing keys")
for k in set(got) & set(want):
if not same(got[k], want[k]):
fields = sorted(f for f in set(got[k]) | set(want[k]) if not same(got[k].get(f), want[k].get(f)) or (f in got[k]) != (f in want[k]))
bad.append(f"{part} {k}: fields differ from the recomputed row: {fields}")
for r in exp["functions"]:
if any(key not in keyset for key in r["_sequence"]):
bad.append(f"{r['key']}: a line key in its sequence is not issued")
c = dict(prov["counts"])
for field, want in exp["_counts"].items():
if not same(c.get(field), want):
bad.append(f"provenance counts.{field} is {c.get(field)!r}, recomputed {want!r}")
for field, want in exp["_register"].items():
if not same(prov["register"].get(field), want):
bad.append(f"provenance register.{field} is {prov['register'].get(field)!r}, recomputed {want!r}")
if "_apps_count" in cat:
c["apps"] = cat["_apps_count"]
if (c["elements"], c["apps"], c["surfaces"], c["functions_over_10_lines"]) != \
(len(cat["elements"]), len(cat["apps"]), len(cat["surfaces"]), len(cat["functions"])):
bad.append("provenance counts differ from the catalogue")
return bad
def main():
prov = load("catalogue/provenance.json")
reg_bytes = (ROOT / prov["register"]["copy"]).read_bytes()
if hashlib.sha256(reg_bytes).hexdigest() != prov["register"]["sha256"]:
sys.exit("register copy does not match its recorded sha256")
register = json.loads(reg_bytes)
pack = {}
for src in prov["numbered_database"]:
b = urllib.request.urlopen(src["url"], timeout=120).read()
if hashlib.sha256(b).hexdigest() != src["sha256"]:
sys.exit(f"served bytes changed since the build: {src['url']}")
pack[src["url"].rsplit("/", 1)[1]] = b
u32 = lambda b: list(struct.unpack(f"<{len(b)//4}I", b))
keyset = set(u32(pack["all-lines.bin"]))
families = json.loads(pack["families.json"])
meta = json.loads(pack["all-lines.meta.json"])
exp, dangling = expected_rows(register, families, u32(pack["lines.bin"]))
exp["_counts"] = {"elements": len(exp["elements"]), "apps": len(exp["apps"]), "surfaces": len(exp["surfaces"]),
"families_total": len(families), "functions_over_10_lines": len(exp["functions"]),
"numbered_lines": meta["lines"], "highest_line_key": meta["max"]}
if meta["lines"] != len(keyset) or meta["max"] != max(keyset):
sys.exit("all-lines.meta.json disagrees with all-lines.bin")
exp["_register"] = {"generated_utc": register.get("generated_utc"), "bytes": len(reg_bytes)}
cat = {k: load(f"catalogue/{k}.json") for k in ("elements", "apps", "surfaces", "functions")}
def set_field(part, i, field, value):
return lambda c: c[part][i].__setitem__(field, value)
ra = next(i for i, e in enumerate(cat["elements"]) if e["kind"] == "app")
mutations = [
("duplicate key", lambda c: c["functions"][1].__setitem__("key", c["functions"][0]["key"])),
("a foreign but issued first key", set_field("functions", 0, "first_line", "line:342795")),
("a false last key", set_field("functions", 0, "last_line", "line:27")),
("occurrences inflated", lambda c: c["functions"][0].__setitem__("lines", c["functions"][0]["lines"] + 100)),
("distinct lines changed", set_field("functions", 2, "distinct_lines", 1)),
("first key with a fake namespace", lambda c: c["functions"][0].__setitem__("first_line", "fake:" + c["functions"][0]["first_line"][5:])),
("function points at an unknown block", set_field("functions", 0, "block", "block:NOPE")),
("function description invented", set_field("functions", 0, "description", "invented")),
("function category invented", set_field("functions", 0, "category", "invented")),
("block_in_register inverted", lambda c: c["functions"][0].__setitem__("block_in_register", not c["functions"][0]["block_in_register"])),
("unknown family added", lambda c: c["functions"].append({**c["functions"][0], "key": "family:99999999"})),
("function dropped", lambda c: c["functions"].pop()),
("element lists family:0", set_field("elements", 0, "function_keys", ["family:0"])),
("element description changed", set_field("elements", 0, "description", "invented")),
("element depends_on invented", set_field("elements", 0, "depends_on", ["block:DOES-NOT-EXIST"])),
("element live invented", set_field("elements", 0, "live", ["https://example.invalid/"])),
("element files invented", set_field("elements", 0, "files", [{"repo": "example/invalid", "path": "invented.js", "commit": None}])),
("unknown block added", lambda c: c["elements"].append({**c["elements"][0], "key": "block:ZZZ"})),
("invented app prose", set_field("apps", 0, "description", "invented prose")),
("invented app title", set_field("apps", 0, "title", "invented title")),
("duplicate app with provenance count raised to match", lambda c: (c["apps"].append(c["apps"][0]), c.__setitem__("_apps_count", len(c["apps"])))),
("surface URL changed, key kept", set_field("surfaces", 0, "url", "https://example.invalid/")),
("surface description invented", set_field("surfaces", 0, "description", "invented")),
("surface key replaced by an unrelated URL", set_field("surfaces", 0, "key", "surface:https://example.test/other/")),
("fake key prefix", lambda c: c["surfaces"][0].__setitem__("key", "planet:" + c["surfaces"][0]["key"])),
("block_in_register True turned into 1", lambda c: c["functions"][0].__setitem__("block_in_register", int(c["functions"][0]["block_in_register"]))),
("standalone False turned into 0", lambda c: c["functions"][next(i for i, f in enumerate(c["functions"]) if f["standalone"] is False)].__setitem__("standalone", 0)),
("invented surface", lambda c: c["surfaces"].append({"key": "surface:https://example.invalid/", "url": "https://example.invalid/", "title": "x", "description": "x", "blocks": []})),
]
prov_mutations = [
("families_total raised", lambda p: p["counts"].__setitem__("families_total", p["counts"]["families_total"] + 1)),
("numbered_lines raised", lambda p: p["counts"].__setitem__("numbered_lines", p["counts"]["numbered_lines"] + 1)),
("highest_line_key raised", lambda p: p["counts"].__setitem__("highest_line_key", p["counts"]["highest_line_key"] + 1)),
("register generated_utc changed", lambda p: p["register"].__setitem__("generated_utc", "2000-01-01T00:00:00Z")),
("register bytes changed", lambda p: p["register"].__setitem__("bytes", p["register"]["bytes"] + 1)),
]
for name, mutate in mutations:
broken = copy.deepcopy(cat)
mutate(broken)
if not problems(broken, prov, exp, keyset):
sys.exit(f"a broken copy passed ({name}); the check proves nothing until it fails")
for name, mutate in prov_mutations:
broken_prov = copy.deepcopy(prov)
mutate(broken_prov)
if not problems(cat, broken_prov, exp, keyset):
sys.exit(f"a broken provenance passed ({name}); the check proves nothing until it fails")
print(f"{len(mutations) + len(prov_mutations)} broken copies each fail as required")
bad = problems(cat, prov, exp, keyset)
if bad:
sys.exit("catalogue check FAILED:\n- " + "\n- ".join(bad[:40]))
print(f"catalogue check PASS: complete rows equal the recomputed rows; {len(cat['elements'])} elements, "
f"{len(cat['apps'])} apps, {len(cat['surfaces'])} surfaces, {len(cat['functions'])} functions")
d = dangling
print(f"disclosed, not failed: {d['references']} register references from {d['source_blocks']} blocks name "
f"{len(d['distinct_targets'])} distinct targets absent from this register "
f"(depends_on {d['by_field']['depends_on']}, used_by {d['by_field']['used_by']})")
if __name__ == "__main__":
main()404
A web page in Galaxies Wafers. Published at https://ventusltd.github.io/galaxies-wafers/404.html.
rendergalaxies-wafers / 404.html · lines 1–59 of 59 · Entry point
- What it does
- It draws its content. Defines say, squash. Side effects: changes the web page (DOM); makes network requests.
- Inputs & outputs
- In: JSON file index.json. Out: web page.
- Downstream impact
- It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/404.html.
- What it achieves
- Defines `say` and `squash`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- galaxies-wafers · / · page
- Uses
- Galaxies Wafers — Iterations Page (link), Galaxies Wafers — Index Page (link)
- Used by
- none found
- Produces
- say, squash
- Defines here
- say, squash
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 404.html:1-59 · blob 23f68e6e2ac587ee24b21ec054598e8f029ff99a · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: unknown
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="color-scheme" content="dark">
<title>Galaxies Wafers — not found</title>
<style>
body{margin:0;background:#0b0d12;color:#d8dee9;font:14px/1.5 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
padding:calc(env(safe-area-inset-top,0px) + 1.25rem) 1rem 2rem}
main{max-width:40rem;margin:0 auto}
h1{font-size:13px;letter-spacing:.14em;margin:0 0 .5rem}
.dim{color:#8b93a7}
a{color:#5ec8f2}
code{overflow-wrap:anywhere}
</style>
</head>
<body>
<main>
<h1>NOT FOUND</h1>
<p id="msg" class="dim">Checking whether this address is a mistyped version…</p>
<p><a href="/galaxies-wafers/iterations/">Every version</a> · <a href="/galaxies-wafers/">The Line Wafer</a></p>
</main>
<script>
/* GitHub Pages serves this page for any missing address. A link copied from a
phone message often gains a space or loses a hyphen. If the address, with
spaces removed, names an iteration that exists, or its two-digit number
matches exactly one iteration, go there and keep the query (the layers the
link asked for). Otherwise say what was asked and link to every version.
Nothing is guessed when two iterations could match. */
(async () => {
const BASE = '/galaxies-wafers/';
const msg = document.getElementById('msg');
const raw = decodeURIComponent(location.pathname);
const rel = raw.startsWith(BASE) ? raw.slice(BASE.length) : raw.replace(/^\//, '');
const say = t => { msg.textContent = t; };
const m = rel.replace(/\s+/g, '').match(/^iterations\/([^/]+)/);
if (!m) { say(`Nothing is published at ${raw}.`); return; }
let dirs = [];
try {
const r = await fetch(BASE + 'iterations/index.json', { cache: 'no-cache' });
dirs = (await r.json()).iterations.map(x => x.dir);
} catch (e) { say(`Nothing is published at ${raw}, and the version list could not be read: ${e.message}`); return; }
const asked = m[1];
const squash = s => s.toLowerCase().replace(/[^a-z0-9]/g, '');
let hit = dirs.find(d => d === asked) || dirs.find(d => squash(d) === squash(asked));
if (!hit) {
const n = asked.match(/^(\d{2})/);
const byNumber = n ? dirs.filter(d => d.startsWith(n[1] + '-')) : [];
if (byNumber.length === 1) hit = byNumber[0];
}
if (!hit) { say(`Nothing is published at ${raw}, and it does not match exactly one version.`); return; }
const dest = `${BASE}iterations/${hit}/${location.search}${location.hash}`;
say(`Taking you to ${hit}…`);
location.replace(dest);
})();
</script>
</body>
</html>Galaxies Wafers — App
A JavaScript module that draws lines meta, families, blocks and cables, using SHA-256, and uses data from the stars repository. Served with the page at https://ventusltd.github.io/galaxies-wafers/.
rendergalaxies-wafers / app.mjs · lines 1–387 of 1609 · Entry point · pattern machineDetail (shared by 2 files)
- What it does
- It draws lines meta, families, blocks and cables. Defines 91 functions or classes, including $, snapshot, clearColour, motion, indexOfKey. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain terms in the code: cables. README: "The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/202609151339."
- Inputs & outputs
- In: data source: stars data; JSON file all-lines.meta.json; JSON file families.json; JSON file blocks.json; JSON file index.json. Out: WebGL/WebGPU drawing.
- Downstream impact
- Used directly by 1 file: Galaxies Wafers — Index Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/). Reached from 242 other entry points, including 404 (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/404.html); Galaxies Wafers — Iterations Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/); Galaxies Wafers — Proof Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/proof/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/.
- What it achieves
- It indexes key (`indexOfKey`), builds gl (`buildGL`) and draws marks (`drawMarks`). The Line Wafer. Its code works with 100 kW. It responds to pointerdown, pointermove and pointerup events.
- Why it matters
- Loaded by the page of the same name at https://ventusltd.github.io/galaxies-wafers/.
- Application
- galaxies-wafers · / · JavaScript module
- Uses
- Galaxies Wafers — Lib (import), Stars — Index Page (estate URL)
- Used by
- loaded by Galaxies Wafers — Index Page (script src), mentioned in Standalone (comment link)
- Produces
- $, snapshot, clearColour, motion, indexOfKey, bin, tier1, tier2, compile, initGL, fallback2d, buildGL
- Defines here
- $, snapshot, clearColour, motion, indexOfKey, bin, tier1, tier2, compile, initGL, fallback2d, buildGL, put, resize, ensureOverlay, drawMarks, toScreen, lowerBound, visibleRange, drawPoints, ensureCache
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 app.mjs:1-387 · blob 925d89a774d1abc7cc7ad231b4f5a460a8d67c6f · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: unknown · users: none · canonical: unknown
/* The Line Wafer.
*
* WHAT THIS IS. Every line of code in the estate that has been given a
* permanent number is one point on one surface. There are 250,174 of them and
* they are numbered 1 to 342,795: the number is the line's permanent key, it
* never changes and it is never reused, and numbers missing from the sequence
* were never issued. Those gaps are drawn as gaps.
*
* WHY THE NUMBER IS THE ADDRESS. A point's position here is a pure function of
* its own permanent key and of nothing else:
*
* r = SPACING * sqrt(key) theta = key * GOLDEN
*
* so line 8,285 is in the same place on every device, in every session, for
* ever, and the surface can be reconstituted from the numbers alone. Nothing
* about a position is stored, fetched or remembered. That is what makes the
* surface unbounded rather than large: the estate can issue line 400,000
* tomorrow and the wafer already has somewhere to put it.
*
* THE BEAM. The camera is a beam. It steers over the wafer and focuses, and
* where it focuses the structure resolves — one line, its length, whether any
* function family carries it, and which. Focus is the only instrument; there
* are no levels and nothing is pre-rendered.
*
* THE RULE THIS PAGE EXISTS TO MEET. It must be able to connect any two
* uniquely numbered lines in the estate. Type two numbers and it answers: the
* families that carry both, or a refusal naming which of the two no family
* carries.
*
* TWO RELATIONS, AND THE FIRST VERSION OF THIS PAGE CONFUSED THEM.
* FANOUT is one number appearing in several families: the same text sitting in
* several places, which is duplication. CO-MEMBERSHIP is two different numbers
* appearing in one family: two lines of the same function, which is
* neighbourhood and is NOT the same text. Connecting uses co-membership, so a
* line carried by exactly one family is perfectly connectable — to another line
* of that family. The page originally claimed the opposite and a reviewer was
* right to reject it. See lib.mjs.
*
* WHAT IS NOT CLAIMED. Neither relation is a dependency and neither means one
* line calls the other. Triviality is visible rather than hidden: a line's
* fanout is printed, so line 2, an empty line in 2,281 families, looks exactly
* as meaningless as it is.
*
* ROOT PROMOTION (iteration 38). What three merged iterations proved is carried
* into this root page, each section citing the file it was lifted from:
* iterations/22-fast-zoom/app.mjs — the moving-frame cache, culling by radius
* band, antialias off, the marks canvas resized only on a size change, the
* measured frame budget, and a finger lifting after a pinch is not a tap.
* iterations/31-code-card-everywhere/card.mjs and app.mjs — a tap on a line,
* a route or empty ground opens a code card (the "code card" section below).
* iterations/21-dark-pixels/app.mjs — the dark ground, here a toggle that is
* OFF by default, so the page looks exactly as it did until it is ticked.
* The placement law is untouched: every position still comes from lib.mjs.
*/
import { place, placeAll, parseKey, indexOfKey as findKey, ownersOf, fanoutCount,
connectAnswer, esc, fmt, SPACING } from './lib.mjs';
const DATA = 'https://globalgrid2050.com/testcode/202609142202/data/';
const $ = id => document.getElementById(id);
let stage = $("stage");
const U = {
fanout: null, /* lines carried by MORE THAN ONE family; counted, never typed */
keys: null, /* Uint32Array, sorted: every permanent line number issued */
lens: null, /* Uint16Array: characters in that line */
inFam: null, /* Uint8Array: 1 when at least one family carries it */
pos: null, /* Float32Array 2N: the pure function of the key */
n: 0,
families: null, /* tier 2 */
famLines: null,
ownerOf: null, /* Map<key, number[]> family indexes, built once on demand */
meta: null
};
const view = { x: 0, y: 0, zoom: 1, w: 0, h: 0, dpr: 1, focus: -1, link: null };
/* The one read-only hook for layers: the live camera, and listeners called after every frame. */
/* Listeners get a frozen scalar snapshot, never the live object: a listener that
mutates what it received cannot move the wafer's camera. (Codex review.) */
const snapshot = () => Object.freeze({ x: view.x, y: view.y, zoom: view.zoom, w: view.w, h: view.h, dpr: view.dpr, moving: MOTION.moving, dark: GROUND.dark });
/* DARK GROUND (iterations/21-dark-pixels/app.mjs), as a toggle, OFF by default.
When on, every line point is drawn near-black and the layers panel wakes only
the keys a ticked layer charts. The reader switches it with #darkGround; it
travels in the URL as ground=dark. Layers read it from the snapshot. */
const GROUND = { dark: false };
const CLEAR_LIT = [0.043, 0.051, 0.071], CLEAR_DARK = [0.012, 0.014, 0.020]; /* 21-dark-pixels render() */
const clearColour = () => GROUND.dark ? CLEAR_DARK : CLEAR_LIT;
/* FAST ZOOM (iteration 22). While a gesture is moving the camera the wafer is
not re-rasterised: its 250k points are drawn once into an offscreen texture
CACHE_SPAN times the screen in each direction, and each moving frame only
draws that texture as one transformed quad. The texture is redrawn when the
camera leaves it (panned past its margin, zoomed out past it, or magnified
more than CACHE_MAGNIFY times), and full detail returns SETTLE_MS after the
last gesture event. Layers read `moving` from the snapshot to thin their
drawing in the same frames. */
const SETTLE_MS = 150;
const CACHE_SPAN = 1.5;
const CACHE_MAGNIFY = 2;
const MOTION = { moving: false, timer: 0 };
function motion() {
MOTION.moving = true;
clearTimeout(MOTION.timer);
MOTION.timer = setTimeout(() => { MOTION.moving = false; draw(); }, SETTLE_MS);
}
window.__wafer = Object.freeze({ get view() { return snapshot(); }, onDraw: new Set(),
get moving() { return MOTION.moving; }, get settleMs() { return SETTLE_MS; }, get dark() { return GROUND.dark; },
get stats() { return Object.freeze({ drawn: frameStats.drawn, total: U.n, rasters: cache.rasters }); } });
/* ── the surface ─────────────────────────────────────────────────────────── */
const placeOne = place; /* where a number sits, issued or not */
const indexOfKey = key => findKey(U.keys, key);
/* ── loading ─────────────────────────────────────────────────────────────── */
async function bin(name, Kind) {
const r = await fetch(DATA + name, { cache: 'default' });
if (!r.ok) throw new Error(DATA + name + ' returned HTTP ' + r.status);
return new Kind(await r.arrayBuffer());
}
async function tier1() {
const [meta, keys, lens, inFam] = await Promise.all([
fetch(DATA + 'all-lines.meta.json').then(r => r.json()),
bin('all-lines.bin', Uint32Array),
bin('all-lines.len.bin', Uint16Array),
bin('all-lines.family.bin', Uint8Array)
]);
U.meta = meta; U.keys = keys; U.lens = lens; U.inFam = inFam; U.n = keys.length;
U.pos = placeAll(keys);
let carried = 0;
for (let i = 0; i < inFam.length; i++) carried += inFam[i];
$('count').textContent =
`${fmt(U.n)} numbered lines · 1 to ${fmt(meta.max)} · ${fmt(carried)} carried by a family`;
$('prov').textContent =
`numbered database built ${meta.built_utc.slice(0, 16).replace('T', ' ')} UTC · pack ${meta.source.sha256.slice(0, 12)}`;
}
async function tier2() {
const [families, famLines] = await Promise.all([
fetch(DATA + 'families.json').then(r => r.json()),
bin('lines.bin', Uint32Array)
]);
U.families = families; U.famLines = famLines;
const owner = ownersOf(families, famLines);
U.ownerOf = owner;
U.fanout = fanoutCount(owner);
if (view.focus >= 0) paintPanel(view.focus);
if (view.link) connect(view.link[0], view.link[1]);
if (waitingKey > 0) openLine(waitingKey); /* 31-code-card-everywhere: a card waiting on the index resumes */
}
/* ── drawing ─────────────────────────────────────────────────────────────── */
const VS = `#version 300 es
precision highp float;
in vec2 a_pos; in float a_len; in float a_fam;
uniform vec2 u_res; uniform vec2 u_cam; uniform float u_zoom; uniform float u_dpr;
uniform float u_focusKey;
out float v_fam; out float v_len; out float v_focus;
void main(){
vec2 p = (a_pos - u_cam) * u_zoom;
gl_Position = vec4(p / (u_res * 0.5), 0.0, 1.0);
float base = 1.0 + min(a_len, 120.0) * 0.012;
gl_PointSize = clamp(base * sqrt(u_zoom) * u_dpr, 1.0, 26.0 * u_dpr);
v_fam = a_fam; v_len = a_len; v_focus = 0.0;
}`;
const FS = `#version 300 es
precision highp float;
in float v_fam; in float v_len; in float v_focus;
uniform float u_dark;
out vec4 o;
void main(){
vec2 d = gl_PointCoord - 0.5;
float r = length(d);
if (r > 0.5) discard;
float edge = smoothstep(0.5, 0.42, r);
vec3 carried = vec3(0.84, 0.87, 0.94);
vec3 alone = vec3(0.30, 0.34, 0.44);
float a = 0.30 + 0.70 * v_fam;
if (u_dark > 0.5) {
/* iterations/21-dark-pixels/app.mjs: the ground is dead but still faintly there */
carried = vec3(0.16, 0.18, 0.23);
alone = vec3(0.09, 0.10, 0.13);
a = 0.45 + 0.30 * v_fam;
}
vec3 c = mix(alone, carried, v_fam);
o = vec4(c, edge * a);
}`;
let gl = null, prog = null, loc = {}, vao = null, ctx2d = null;
function compile(g, type, src) {
const s = g.createShader(type); g.shaderSource(s, src); g.compileShader(s);
if (!g.getShaderParameter(s, g.COMPILE_STATUS)) throw new Error(g.getShaderInfoLog(s));
return s;
}
/* If anything after acquiring the context fails — a shader that will not compile
on some driver, a program that will not link — the page must fall back, not
half-run. A canvas cannot hand out a 2D context once it has given out a WebGL
one, so the canvas itself is replaced. The first version left `gl` non-null on
failure and then asked the same canvas for a 2D context, which returns null:
the fallback it advertised did not exist. */
function initGL() {
/* Iteration 22: antialias off. Each point already fades its own edge in the
fragment shader, and multisampling a full-screen buffer was measured GPU cost. */
gl = stage.getContext('webgl2', { antialias: false, alpha: false });
if (!gl) { gl = null; return fallback2d(); }
try { return buildGL(); }
catch (e) { gl = null; console.warn('WebGL setup failed, falling back:', e.message); return fallback2d(); }
}
function fallback2d() {
const fresh = stage.cloneNode(false);
stage.replaceWith(fresh);
stage = fresh;
ctx2d = stage.getContext('2d');
$('hint').textContent = ctx2d
? 'drawn without the GPU: at low zoom one line in seven is plotted'
: 'this browser gave neither a GPU nor a 2D canvas; nothing can be drawn';
return false;
}
function buildGL() {
prog = gl.createProgram();
gl.attachShader(prog, compile(gl, gl.VERTEX_SHADER, VS));
gl.attachShader(prog, compile(gl, gl.FRAGMENT_SHADER, FS));
gl.linkProgram(prog);
if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(prog));
gl.useProgram(prog);
for (const u of ['u_res', 'u_cam', 'u_zoom', 'u_dpr', 'u_focusKey', 'u_dark']) loc[u] = gl.getUniformLocation(prog, u);
vao = gl.createVertexArray(); gl.bindVertexArray(vao);
const put = (data, name, size, Kind, norm) => {
const b = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, b);
gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
const l = gl.getAttribLocation(prog, name);
gl.enableVertexAttribArray(l);
gl.vertexAttribPointer(l, size, Kind, !!norm, 0, 0);
};
put(U.pos, 'a_pos', 2, gl.FLOAT, false);
put(U.lens, 'a_len', 1, gl.UNSIGNED_SHORT, false);
put(U.inFam, 'a_fam', 1, gl.UNSIGNED_BYTE, false);
gl.enable(gl.BLEND);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
return true;
}
function resize() {
view.dpr = Math.min(window.devicePixelRatio || 1, 2);
view.w = stage.clientWidth; view.h = stage.clientHeight;
stage.width = Math.round(view.w * view.dpr);
stage.height = Math.round(view.h * view.dpr);
if (gl) gl.viewport(0, 0, stage.width, stage.height);
}
let overlay = null;
function ensureOverlay() {
if (overlay) return overlay;
overlay = document.createElement('canvas');
overlay.style.cssText = 'position:fixed;inset:0;width:100%;height:100%;pointer-events:none;z-index:1';
document.body.appendChild(overlay);
return overlay;
}
/* The marks canvas is resized only when the stage changes size and cleared only
when it holds something: assigning canvas.width every frame reallocates a
full-screen backing store on every frame. */
let marksDirty = true;
function drawMarks() {
const o = ensureOverlay();
const has = !!view.link || view.focus >= 0;
if (o.width !== stage.width || o.height !== stage.height) { o.width = stage.width; o.height = stage.height; marksDirty = true; }
if (!has && !marksDirty) return;
const c = o.getContext('2d');
c.setTransform(view.dpr, 0, 0, view.dpr, 0, 0);
c.clearRect(0, 0, view.w, view.h);
marksDirty = has;
if (!has) return;
const toScreen = ([x, y]) => [
(x - view.x) * view.zoom + view.w / 2,
view.h / 2 - ((y - view.y) * view.zoom)
];
if (view.link) {
const [ka, kb] = view.link;
const A = toScreen(placeOne(ka)), B = toScreen(placeOne(kb));
c.strokeStyle = '#5ec8f2'; c.lineWidth = 1.2; c.setLineDash([5, 4]);
c.beginPath(); c.moveTo(A[0], A[1]);
c.quadraticCurveTo((A[0] + B[0]) / 2, (A[1] + B[1]) / 2 - 40, B[0], B[1]);
c.stroke(); c.setLineDash([]);
for (const P of [A, B]) {
c.strokeStyle = '#5ec8f2'; c.beginPath(); c.arc(P[0], P[1], 9, 0, 6.2832); c.stroke();
}
}
if (view.focus >= 0) {
const P = toScreen(placeOne(view.focus));
c.strokeStyle = '#ffd54a'; c.lineWidth = 1.4;
c.beginPath(); c.arc(P[0], P[1], 11, 0, 6.2832); c.stroke();
c.beginPath(); c.moveTo(P[0] - 18, P[1]); c.lineTo(P[0] - 13, P[1]);
c.moveTo(P[0] + 13, P[1]); c.lineTo(P[0] + 18, P[1]);
c.moveTo(P[0], P[1] - 18); c.lineTo(P[0], P[1] - 13);
c.moveTo(P[0], P[1] + 13); c.lineTo(P[0], P[1] + 18);
c.stroke();
}
}
/* ── the moving-frame cache ──────────────────────────────────────────────── */
const BLIT_VS = `#version 300 es
in vec2 a_q; uniform vec4 u_rect; out vec2 v_uv;
void main(){ v_uv = a_q; gl_Position = vec4(mix(u_rect.xy, u_rect.zw, a_q), 0.0, 1.0); }`;
const BLIT_FS = `#version 300 es
precision mediump float; in vec2 v_uv; uniform sampler2D u_tex; out vec4 o;
void main(){ o = texture(u_tex, v_uv); }`;
const cache = { fbo: null, tex: null, w: 0, h: 0, prog: null, vao: null, rect: null, valid: false, x: 0, y: 0, zoom: 1, rasters: 0, broken: false };
/* CULLING BY THE LAW. r = sqrt(key), so the keys that can appear in a world
rectangle are exactly those whose radius lies between the rectangle's nearest
and farthest distance from the origin: keys in [r0^2, r1^2]. U.keys is sorted,
so that is one contiguous index range, found by two binary searches, and one
drawArrays call over it. POINT_MARGIN_PX widens the rectangle by the largest
point radius so a point straddling the edge is not cut. */
const POINT_MARGIN_PX = 14;
const frameStats = { drawn: 0 };
function lowerBound(a, v) { let lo = 0, hi = a.length; while (lo < hi) { const m = (lo + hi) >>> 1; if (a[m] < v) lo = m + 1; else hi = m; } return lo; }
function visibleRange(halfWpx, halfHpx, cx, cy) {
const k = view.zoom * view.dpr;
const hw = halfWpx / k + POINT_MARGIN_PX / view.zoom, hh = halfHpx / k + POINT_MARGIN_PX / view.zoom;
const ax = Math.abs(cx), ay = Math.abs(cy);
const dx = Math.max(ax - hw, 0), dy = Math.max(ay - hh, 0);
const r0 = Math.hypot(dx, dy) / SPACING, r1 = Math.hypot(ax + hw, ay + hh) / SPACING;
return [lowerBound(U.keys, Math.floor(r0 * r0)), lowerBound(U.keys, Math.ceil(r1 * r1) + 1)];
}
function drawPoints(w, h, cx, cy) {
gl.clearColor(...clearColour(), 1); gl.clear(gl.COLOR_BUFFER_BIT);
gl.useProgram(prog); gl.bindVertexArray(vao);
gl.uniform2f(loc.u_res, w, h);
gl.uniform2f(loc.u_cam, cx, cy);
gl.uniform1f(loc.u_zoom, view.zoom * view.dpr);
gl.uniform1f(loc.u_dpr, view.dpr);
gl.uniform1f(loc.u_focusKey, view.focus);
gl.uniform1f(loc.u_dark, GROUND.dark ? 1 : 0);
const [lo, hi] = visibleRange(w / 2, h / 2, cx, cy);
if (hi > lo) gl.drawArrays(gl.POINTS, lo, hi - lo);
frameStats.drawn = hi - lo;
}
/* Returns false when this GPU cannot give a render target, and the page then
simply draws every moving frame in full, as the root page does. */
function ensureCache() {
if (cache.broken) return false;
const max = Math.min(gl.getParameter(gl.MAX_TEXTURE_SIZE), gl.getParameter(gl.MAX_RENDERBUFFER_SIZE));
const w = Math.min(max, Math.ceil(stage.width * CACHE_SPAN)), h = Math.min(max, Math.ceil(stage.height * CACHE_SPAN));
if (cache.tex && cache.w === w && cache.h === h) return true;
try {
if (!cache.prog) {
const p = gl.createProgram();
gl.attachShader(p, compile(gl, gl.VERTEX_SHADER, BLIT_VS));
gl.attachShader(p, compile(gl, gl.FRAGMENT_SHADER, BLIT_FS));
gl.linkProgram(p);
if (!gl.getProgramParameter(p, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(p));
cache.prog = p; cache.rect = gl.getUniformLocation(p, 'u_rect');
cache.vao = gl.createVertexArray(); gl.bindVertexArray(cache.vao);
const b = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, b);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]), gl.STATIC_DRAW);
const l = gl.getAttribLocation(p, 'a_q'); gl.enableVertexAttribArray(l); gl.vertexAttribPointer(l, 2, gl.FLOAT, false, 0, 0);
}
if (cache.tex) { gl.deleteTexture(cache.tex); gl.deleteFramebuffer(cache.fbo); }
cache.tex = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, cache.tex);
gl.texStorage2D(gl.TEXTURE_2D, 1, gl.RGBA8, w, h);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
cache.fbo = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, cache.fbo);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, cache.tex, 0);
const ok = gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE;