In this section
- Verify Bundle ingest · galaxies-wafers / iterations/11-the-bond/verify_bundle.py lines 1–258
- Wafer transform · galaxies-wafers / iterations/11-the-bond/wafer.mjs lines 1–78
- Iterations — 12 Visibility Lab render · galaxies-wafers / iterations/12-visibility-lab/app.mjs lines 1–113
- Browser Check render · galaxies-wafers / iterations/12-visibility-lab/browser-check.mjs lines 1–52
- Export Style storage · galaxies-wafers / iterations/12-visibility-lab/export-style.mjs lines 1–13
- Iterations — 12 Visibility Lab Page render · galaxies-wafers / iterations/12-visibility-lab/index.html lines 1–31
- Model transform · galaxies-wafers / iterations/12-visibility-lab/model.mjs lines 1–32
- Model Test test · galaxies-wafers / iterations/12-visibility-lab/model.test.mjs lines 1–19
Verify Bundle
A Python command-line tool in the iterations folder of Galaxies Wafers that runs process (`run_process`), using SHA-256.
ingestgalaxies-wafers / iterations/11-the-bond/verify_bundle.py · lines 1–258 of 258 · Entry point · pattern _check (shared by 4 files)
- What it does
- It loads data. Defines 11 functions or classes, including digest, _integer, _hex, _check, run_process. Uses libraries __future__, argparse, collections, hashlib, json. Side effects: reads or writes files; starts processes.
- Inputs & outputs
- In: JSON file report.json; command-line arguments.
- Downstream impact
- Used directly by 1 file: Test Verify Bundle (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/11-the-bond/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/11-the-bond/.
- What it achieves
- It verifies bundle (`verify_bundle`) and is built from the digest step (`digest`) and the inspect report helper (`inspect_report`). Portable offline verification of one explicitly selected public Bond bundle. It reads `report.json`. It accepts `--version-dir`, `--output` and `--timeout-seconds`.
- Why it matters
- Checked by Test Verify Bundle.
- Application
- galaxies-wafers · iterations/11-the-bond · Python CLI
- Uses
- Bond Validator (script call), __future__, argparse, collections, hashlib, json, pathlib, re, shutil
- Used by
- imported by Test Verify Bundle (import)
- Produces
- digest, run_process, inspect_report, verify_bundle, main
- Defines here
- digest, _integer, _hex, _check, run_process, _public_process, _predicate_valid, inspect_report, _inventory, verify_bundle, main
- 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 iterations/11-the-bond/verify_bundle.py:1-258 · blob 2f497d272eaab2338000f4765a76c55eb21e9b82 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: unknown · users: none · canonical: unknown
"""Portable offline verification of one explicitly selected public Bond bundle."""
from __future__ import annotations
import argparse
from collections import Counter
import hashlib
import json
from pathlib import Path
import re
import shutil
import subprocess
import sys
import time
VERSION = "1.0.0"
CANONICAL_WAFER_LF_SHA256 = "3f7a57344a804fbc7e7352155b40fe0d3cae42c8f6d1fd50a7dfc4b6234c0809"
SOURCE_REPO = "Ventusltd/galaxies-wafers"
STATUSES = ("CONTRADICTED", "PARTIALLY EVALUATED", "NOT EVALUATED", "HONOURED")
PREDICATE_STATUSES = ("PASSED", "FAILED", "NOT EVALUATED")
ARTIFACT_SUFFIXES = frozenset({".py", ".mjs", ".js", ".json", ".html", ".css", ".md"})
REQUIRED_FILES = ("index.html", "style.css", "app.mjs", "wafer.mjs", "model.mjs", "model.test.mjs", "report.json", "bond_validator.py")
MODEL_SCRIPT = """import { readFileSync } from 'node:fs';
import { validateReport, summarise } from './model.mjs';
const report = JSON.parse(readFileSync('report.json', 'utf8'));
validateReport(report);
process.stdout.write(JSON.stringify(summarise(report.rows)));
"""
SCOPE = "Bundle consistency and executable checks; partial or unevaluated claim rows are permitted. Honest CONTRADICTED rows are permitted unless the optional contradiction gate is enabled. Source identities are checked offline; no source repository is fetched."
def digest(data):
return hashlib.sha256(data).hexdigest()
def _integer(n):
return type(n) is int and 0 <= n <= 9007199254740991
def _hex(value, size):
return isinstance(value, str) and re.fullmatch(r"[0-9a-f]{" + str(size) + "}", value) is not None
def _check(ident, ok, **facts):
return {"id": ident, "status": "PASSED" if ok else "FAILED", **facts}
def run_process(argv, cwd, timeout):
"""Run without a shell; retain output privately for parsing, never receipt text."""
started = time.monotonic()
try:
completed = subprocess.run(argv, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout, check=False)
result = {"exit_code": completed.returncode, "timed_out": False, "available": True, "stdout": completed.stdout, "stderr": completed.stderr}
except subprocess.TimeoutExpired as error:
result = {"exit_code": None, "timed_out": True, "available": True, "stdout": error.stdout or b"", "stderr": error.stderr or b""}
except OSError:
result = {"exit_code": None, "timed_out": False, "available": False, "stdout": b"", "stderr": b""}
result["duration_ms"] = round((time.monotonic() - started) * 1000)
return result
def _public_process(result):
return {"exit_code": result["exit_code"], "timed_out": result["timed_out"], "available": result["available"], "duration_ms": result["duration_ms"], "stdout_sha256": digest(result["stdout"]), "stderr_sha256": digest(result["stderr"])}
def _predicate_valid(p):
if not isinstance(p, dict) or p.get("status") not in PREDICATE_STATUSES:
return False
if not all(_integer(p.get(k)) for k in ("checked", "total", "passed", "failed")):
return False
if p["checked"] > p["total"] or p["passed"] + p["failed"] != p["checked"]:
return False
if p["status"] == "PASSED":
return p["failed"] == 0 and p["checked"] == p["total"]
if p["status"] == "FAILED":
return p["failed"] > 0
return p["failed"] == 0 and p["checked"] < p["total"]
def inspect_report(report):
"""Independently recount advertised totals; never copy source prose to receipts."""
checks, summary, source = [], None, {}
if not isinstance(report, dict):
return [_check("report.format", False)], summary, source
rows, inputs = report.get("rows"), report.get("input_checks")
format_ok = report.get("schema") == "bond.v1" and isinstance(rows, list) and isinstance(inputs, list)
checks.append(_check("report.format", format_ok))
provenance = report.get("provenance")
provenance_ok = isinstance(provenance, dict) and provenance.get("repo") == SOURCE_REPO and _hex(provenance.get("commit"), 40) and _hex(provenance.get("manifest_sha256"), 64)
if provenance_ok:
source = {"repo": SOURCE_REPO, "commit": provenance["commit"], "manifest_sha256": provenance["manifest_sha256"]}
checks.append(_check("report.provenance", bool(provenance_ok)))
sources = provenance.get("sources") if isinstance(provenance, dict) else None
source_records_ok = isinstance(sources, list) and bool(sources) and all(isinstance(s, dict) and _hex(s.get("commit"), 40) and _hex(s.get("sha256"), 64) and _hex(s.get("git_blob"), 40) and _integer(s.get("bytes")) for s in sources)
checks.append(_check("report.source_identities", source_records_ok, source_records=len(sources) if isinstance(sources, list) else 0))
all_inputs_passed = isinstance(inputs, list) and bool(inputs) and all(_predicate_valid(p) and p["status"] == "PASSED" and p["checked"] > 0 for p in inputs)
checks.append(_check("report.source_input_checks", all_inputs_passed, source_input_checks=len(inputs) if isinstance(inputs, list) else 0))
input_details = report.get("inputs")
issues_clear = isinstance(input_details, dict) and input_details.get("family_input_issues") == [] and input_details.get("optional_input_issues", []) == []
checks.append(_check("report.source_input_issues", issues_clear))
if not format_ok:
return checks, summary, source
ids, row_valid, row_totals_valid = set(), True, True
summary = {"layers": len(rows), "statements": 0, "gapRecords": 0, "checked": 0, "total": 0, "statuses": {s: 0 for s in STATUSES}}
features, references = 0, 0
for r in rows:
if not isinstance(r, dict):
row_valid = False
continue
ident, status = r.get("layer_id"), r.get("status")
ps, not_evaluated, disclosed = r.get("predicates"), r.get("not_evaluated"), r.get("disclosed")
if not isinstance(ident, str) or not ident or ident in ids:
row_valid = False
else:
ids.add(ident)
if status not in STATUSES or not isinstance(ps, list) or not isinstance(not_evaluated, list) or not isinstance(disclosed, list) or not all(_predicate_valid(p) for p in ps):
row_valid = False
continue
failed = any(p["failed"] > 0 for p in ps)
if failed != (status == "CONTRADICTED") or (status == "HONOURED" and (not_evaluated or any(p["status"] != "PASSED" for p in ps))):
row_valid = False
checked, total = sum(p["checked"] for p in ps), sum(p["total"] for p in ps)
summary["statuses"][status] += 1
summary["checked"] += checked
summary["total"] += total
summary["statements"] += len(not_evaluated)
summary["gapRecords"] += len(disclosed)
cov = r.get("coverage")
expected = {"checks_evaluated": checked, "checks_total": total, "predicates": len(ps), "predicates_passed": sum(p["status"] == "PASSED" for p in ps), "predicates_failed": sum(p["status"] == "FAILED" for p in ps), "not_evaluated_items": len(not_evaluated), "disclosure_items": len(disclosed)}
if not isinstance(cov, dict) or any(not _integer(cov.get(k)) or cov[k] != value for k, value in expected.items()) or not _integer(cov.get("features")) or not _integer(cov.get("key_references")):
row_totals_valid = False
else:
features += cov["features"]
references += cov["key_references"]
checks.append(_check("report.row_consistency", row_valid))
checks.append(_check("report.row_totals", row_totals_valid))
coverage = report.get("coverage")
expected = {"manifest_entries": len(rows), "layers_reported": len(rows), "features": features, "key_references": references, "checks_evaluated": summary["checked"], "checks_total": summary["total"]}
counts = coverage.get("status_counts") if isinstance(coverage, dict) else None
totals_ok = isinstance(coverage, dict) and all(_integer(coverage.get(k)) and coverage[k] == value for k, value in expected.items()) and isinstance(counts, dict) and set(counts) == set(STATUSES) and all(_integer(counts[s]) and counts[s] == summary["statuses"][s] for s in STATUSES)
checks.append(_check("report.aggregate_totals", totals_ok))
return checks, summary, source
def _inventory(root, excluded):
"""Only this directory's public artifact suffixes; never recursively enumerate."""
artifacts, issues = [], []
for path in sorted(root.iterdir(), key=lambda p: p.name):
if path.suffix.lower() not in ARTIFACT_SUFFIXES or path.resolve() in excluded:
continue
if path.is_dir():
continue
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,119}", path.name):
issues.append("unsupported artifact filename")
continue
if path.resolve().parent != root:
issues.append("artifact resolves outside the selected directory")
continue
try:
raw = path.read_bytes()
artifacts.append({"file": path.name, "bytes": len(raw), "sha256": digest(raw)})
except OSError:
issues.append("artifact could not be read")
return artifacts, issues
def verify_bundle(version_dir, *, timeout_seconds=60, fail_on_contradiction=False, excluded_paths=(), runner=run_process):
if not _integer(timeout_seconds) or not 1 <= timeout_seconds <= 120:
raise ValueError("timeout must be between 1 and 120 seconds")
root = Path(version_dir).resolve()
receipt = {"schema": "bond.bundle-verification.v1", "verifier_version": VERSION, "bundle_scope": SCOPE, "status": "FAILED", "fail_on_contradiction": bool(fail_on_contradiction), "source": {}, "runtime_counts": None, "artifacts": [], "checks": []}
checks = receipt["checks"]
if not root.is_dir():
checks.append(_check("bundle.directory", False))
return receipt
excluded = {Path(p).resolve() for p in excluded_paths}
artifacts, inventory_issues = _inventory(root, excluded)
receipt["artifacts"] = artifacts
checks.append(_check("bundle.inventory", not inventory_issues, files=len(artifacts), issue_count=len(inventory_issues)))
filenames = {a["file"] for a in artifacts}
checks.append(_check("bundle.required_files", all(name in filenames for name in REQUIRED_FILES), required_files=len(REQUIRED_FILES), present_required_files=sum(name in filenames for name in REQUIRED_FILES)))
python_tests = sorted(name for name in filenames if name.startswith("test_") and name.endswith(".py"))
checks.append(_check("bundle.python_test_files", bool(python_tests), files=len(python_tests)))
if "wafer.mjs" in filenames:
raw = (root / "wafer.mjs").read_bytes()
actual = digest(raw.replace(b"\r\n", b"\n"))
receipt["canonical_wafer"] = {"file": "wafer.mjs", "normalization": "CRLF to LF only", "expected_sha256": CANONICAL_WAFER_LF_SHA256, "actual_sha256": actual}
checks.append(_check("bundle.canonical_wafer", actual == CANONICAL_WAFER_LF_SHA256))
summary = None
if "report.json" in filenames:
try:
report = json.loads((root / "report.json").read_bytes())
report_checks, summary, source = inspect_report(report)
checks.extend(report_checks)
receipt["source"] = source
receipt["runtime_counts"] = summary
except (ValueError, UnicodeError, OSError):
checks.append(_check("report.decode", False))
if fail_on_contradiction:
count = summary["statuses"]["CONTRADICTED"] if summary else None
checks.append(_check("report.optional_contradiction_gate", count == 0, contradicted_rows=count))
if python_tests:
result = runner([sys.executable, "-B", "-m", "unittest", "discover", "-s", ".", "-p", "test_*.py", "-v"], root, timeout_seconds)
text = (result["stdout"] + result["stderr"]).decode("utf-8", errors="replace")
matched = re.findall(r"\bRan (\d+) tests?\b", text)
count = int(matched[-1]) if matched else 0
skipped_matches = re.findall(r"\bskipped=(\d+)", text)
expected_failure_matches = re.findall(r"\bexpected failures=(\d+)", text)
skipped = int(skipped_matches[-1]) if skipped_matches else 0
expected_failures = int(expected_failure_matches[-1]) if expected_failure_matches else 0
checks.append(_check("python.unittest", result["exit_code"] == 0 and count > skipped, tests=count, skipped=skipped, expected_failures=expected_failures, **_public_process(result)))
node = shutil.which("node") or "node"
if "model.test.mjs" in filenames:
result = runner([node, "--test", "--test-reporter=tap", "model.test.mjs"], root, timeout_seconds)
text = result["stdout"].decode("utf-8", errors="replace")
counts = {key: int(matches[-1]) if (matches := re.findall(r"(?m)^# " + key + r" (\d+)\s*$", text)) else None for key in ("tests", "pass", "fail", "cancelled", "skipped", "todo")}
ok = result["exit_code"] == 0 and counts["tests"] is not None and counts["tests"] > 0 and counts["pass"] is not None and counts["pass"] > 0 and counts["fail"] == 0 and counts["cancelled"] == 0
checks.append(_check("node.model_tests", ok, counts=counts, **_public_process(result)))
for filename in sorted(filenames):
if filename.endswith((".mjs", ".js")):
result = runner([node, "--check", filename], root, timeout_seconds)
checks.append(_check("javascript.syntax", result["exit_code"] == 0, file=filename, **_public_process(result)))
if "model.mjs" in filenames and "report.json" in filenames:
result = runner([node, "--input-type=module", "-e", MODEL_SCRIPT], root, timeout_seconds)
try:
runtime = json.loads(result["stdout"])
agrees = summary is not None and json.dumps(runtime, sort_keys=True) == json.dumps(summary, sort_keys=True)
except (ValueError, UnicodeError):
agrees = False
checks.append(_check("node.runtime_report_totals", result["exit_code"] == 0 and agrees, **_public_process(result)))
after, after_issues = _inventory(root, excluded)
checks.append(_check("bundle.unchanged_during_verification", not after_issues and artifacts == after))
receipt["status"] = "PASSED" if checks and all(c["status"] == "PASSED" for c in checks) else "FAILED"
receipt["check_counts"] = {"total": len(checks), "passed": sum(c["status"] == "PASSED" for c in checks), "failed": sum(c["status"] == "FAILED" for c in checks)}
return receipt
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--version-dir", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True, help="new public receipt path; existing files are never replaced")
parser.add_argument("--timeout-seconds", type=int, default=60)
parser.add_argument("--fail-on-contradiction", action="store_true")
args = parser.parse_args(argv)
if args.output.exists():
parser.exit(2, "Receipt output already exists; choose a new file.\n")
try:
receipt = verify_bundle(args.version_dir, timeout_seconds=args.timeout_seconds, fail_on_contradiction=args.fail_on_contradiction, excluded_paths=[args.output])
encoded = (json.dumps(receipt, ensure_ascii=True, indent=2, allow_nan=False) + "\n").encode()
with args.output.open("xb") as output:
output.write(encoded)
except (OSError, ValueError, TypeError):
parser.exit(2, "The selected bundle could not be verified or the new receipt could not be written.\n")
print(json.dumps({"status": receipt["status"], "receipt_sha256": digest(encoded), "check_counts": receipt.get("check_counts", {})}))
return 0 if receipt["status"] == "PASSED" else 1
if __name__ == "__main__":
raise SystemExit(main())Wafer
A JavaScript module in the iterations folder of Galaxies Wafers. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/11-the-bond/.
transformgalaxies-wafers / iterations/11-the-bond/wafer.mjs · lines 1–78 of 78 · pattern placeAll (shared by 2 files)
- What it does
- It calculates its inputs. Defines place, placeAll, extent, phase.
- Why it exists in the grid workflow
- README: "Required browser files: `index.html`, `style.css`, `app.mjs`, `model.mjs`, `report.json`, and unchanged `wafer.mjs`."
- Downstream impact
- Used directly by 5 files: Iterations — 11 the Bond (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/11-the-bond/); Model (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/12-visibility-lab/); Model Test (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/12-visibility-lab/); Iterations — 41 Golden Angle (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/41-golden-angle/); and 1 more. Reached from 5 other entry points, including Iterations — 11 the Bond Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/11-the-bond/); Iterations — 12 Visibility Lab (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/12-visibility-lab/); Iterations — 12 Visibility Lab Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/12-visibility-lab/).
- What it achieves
- It is built from the place step (`place`), the place all helper (`placeAll`) and the extent step (`extent`). This file is the ground the galaxy is drawn on, and it is the one file here that must not change.
- Why it matters
- Imported by 4 files, including Iterations — 11 the Bond, Model and Iterations — 41 Golden Angle, from Testcode. Checked by Model Test.
- Application
- galaxies-wafers · iterations/11-the-bond · JavaScript module
- Uses
- none found
- Used by
- imported by Iterations — 11 the Bond (import), imported by Model (import), referenced by Model Test (new URL import.meta.url), imported by Iterations — 41 Golden Angle (import), imported by Sandbox — Galaxy Bond (import), mentioned in Standalone (comment link)
- Produces
- GOLDEN_ANGLE, SUBSTRATE, place, placeAll, extent, phase
- Defines here
- place, placeAll, extent, phase
- 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 iterations/11-the-bond/wafer.mjs:1-78 · blob 56514b6fa9cbfa61b0944ae18bcb7d599628f22b · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unknown
/* wafer.mjs — THE SUBSTRATE. FROZEN.
*
* This file is the ground the galaxy is drawn on, and it is the one file here
* that must not change. Grid Atlas never redraws its Carto basemap to suit a
* layer; neither does this. Every link ever shared, every layer ever built and
* every screenshot ever taken depends on a number landing in the same place
* for ever.
*
* THE LAW, in full, and it is the whole file:
*
* r = sqrt(key)
* theta = key x 2.39996322972865332... (the golden angle)
* x = r cos(theta)
* y = r sin(theta)
*
* A point's place is a pure function of its own permanent number and of nothing
* else. Not of what else exists, not of how many there are, not of the order
* they were loaded, not of the viewport, not of a random seed. Give it 8,285
* and you get the same two numbers on every device, in every browser, in every
* year.
*
* WHY THIS ARRANGEMENT AND NOT ANOTHER. It is phyllotaxis, the spiral a
* sunflower uses. The golden angle is the irrational that packs worst-case
* best: no two points fall on a common ray, so nothing occludes anything, and
* the square root of the key means equal area holds equal count, so density on
* screen is density in the numbering rather than an artefact of the projection.
*
* WHY IT IS UNBOUNDED. The estate's line numbers run to 342,795 today. This
* function is defined for every positive integer, so line 400,000 and line
* 40,000,000 already have places, and issuing them moves nothing. That is what
* lets layers accumulate for years over a ground that never shifts beneath
* them.
*
* WHAT A GAP MEANS. Numbers that were never issued leave holes, and the holes
* are drawn. They are not missing data; they are numbers the estate chose not
* to give out, and on a frozen substrate a hole is as much a fact as a point.
*
* TO CHANGE THIS FILE is to invalidate every layer, link and record that has
* ever pointed at the galaxy. If a different arrangement is wanted, it is a new
* substrate with a new name beside this one, never an edit to this one.
*/
export const GOLDEN_ANGLE = Math.PI * (3 - Math.sqrt(5));
export const SUBSTRATE = Object.freeze({
id: 'wafer.v1',
law: 'r = sqrt(key); theta = key * goldenAngle',
frozen_utc: '2026-09-15T15:00:00Z',
note: 'The basemap of the code galaxy. Never changes. New arrangements are new substrates.'
});
/** Where a permanent key sits. Defined for every positive integer, issued or not. */
export function place(key) {
const r = Math.sqrt(key), t = key * GOLDEN_ANGLE;
return [r * Math.cos(t), r * Math.sin(t)];
}
/** The same law over a whole column of keys, as a flat xy array for the GPU. */
export function placeAll(keys) {
const n = keys.length, p = new Float32Array(n * 2);
for (let i = 0; i < n; i++) {
const k = keys[i], r = Math.sqrt(k), t = k * GOLDEN_ANGLE;
p[i * 2] = r * Math.cos(t);
p[i * 2 + 1] = r * Math.sin(t);
}
return p;
}
/** The radius that contains every key up to max: what the camera must frame. */
export const extent = max => Math.sqrt(max);
/** A deterministic angle from a key, for layers that need to fan several marks
* off one point without ever calling a random number generator. */
export function phase(key) {
let h = key >>> 0;
h = Math.imul(h ^ (h >>> 16), 0x45d9f3b) >>> 0;
h = Math.imul(h ^ (h >>> 16), 0x45d9f3b) >>> 0;
return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
}Iterations — 12 Visibility Lab
A JavaScript module in Galaxies Wafers that draws visibility style and catalog, using SHA-256. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/12-visibility-lab/.
rendergalaxies-wafers / iterations/12-visibility-lab/app.mjs · lines 1–113 of 113 · Entry point · pattern clearError (shared by 2 files)
- What it does
- It draws visibility style and catalog. Defines 14 functions or classes, including $, options, error, clearError, readChecked. Side effects: changes the web page (DOM); makes network requests.
- Why it exists in the grid workflow
- README: "The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/202609151339."
- Inputs & outputs
- In: JSON file catalog.json. Out: JSON file visibility-style.json; downloaded file visibility-style.json; canvas drawing.
- Downstream impact
- Used directly by 1 file: Iterations — 12 Visibility Lab Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/12-visibility-lab/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/12-visibility-lab/.
- What it achieves
- It reads checked (`readChecked`), builds table (`buildTable`) and registers page tools (`registerPageTools`). The README says: The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/. It reads `catalog.json`. It responds to pagehide, click and change events.
- Why it matters
- Loaded by the page of the same name at https://ventusltd.github.io/galaxies-wafers/iterations/12-visibility-lab/.
- Application
- galaxies-wafers · iterations/12-visibility-lab · JavaScript module
- Uses
- Visibility Style (import), Model (import)
- Used by
- loaded by Iterations — 12 Visibility Lab Page (script src)
- Produces
- $, options, error, clearError, readChecked, styles, styleReadings, draw, choose, buildTable, registerPageTools, snapshot
- Defines here
- $, options, error, clearError, readChecked, styles, styleReadings, draw, choose, buildTable, registerPageTools, snapshot, register, init
- 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 iterations/12-visibility-lab/app.mjs:1-113 · blob 5b01f30b34ca50ede257c120bc56d72ee51de80f · GitHub at these lines
- State
- achieves: readme · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: unknown
import {exportVisibility,sourceContexts,currentStyle,proposedStyle,measureStyle} from './visibility-style.mjs';
import {CATALOG_SHA256,validateCatalog,prepareGeometry,cameraFor} from './model.mjs';
const $=id=>document.getElementById(id), canvases=[$('current'),$('proposed')];
let catalog=null,selected=null,geometry=null,epoch=0,controller=null,queue=Promise.resolve(),tableBuilt=false;
const cache=new Map(), views=new Map();
const sourceRoot='https://github.com/Ventusltd/galaxies-wafers/blob/be62c82b9ffebeaa9b1152a7e7fae1658b585d4b/';
const options=()=>({casing:$('casing').value,pointRadiusCssPx:4,strokeCssPx:2});
function error(message){$('failure').textContent=message;$('failure').hidden=false;}
function clearError(){$('failure').hidden=true;}
async function readChecked(path,expected,bytes,signal){
const response=await fetch(new URL(path,import.meta.url),{signal});if(!response.ok)throw Error(`Input unavailable: HTTP ${response.status}`);
const raw=await response.arrayBuffer();if(bytes!==undefined&&raw.byteLength!==bytes)throw Error('Input byte length refused');
const digest=[...new Uint8Array(await crypto.subtle.digest('SHA-256',raw))].map(x=>x.toString(16).padStart(2,'0')).join('');
if(digest!==expected)throw Error('Input digest refused');return JSON.parse(new TextDecoder().decode(raw));
}
function styles(){return[currentStyle(selected),proposedStyle(selected,options())];}
function styleReadings(){
if(!selected)return;
const values=styles().map(s=>measureStyle(s,sourceContexts())[0]);
$('current-ratio').textContent=selected.features?values[0].core_to_context_ratio.toFixed(2)+':1':'EMPTY';
$('proposed-ratio').textContent=selected.features?values[1].core_to_context_ratio.toFixed(2)+':1':'EMPTY';
$('boundary-ratio').textContent=selected.features?values[1].boundary_ratio.toFixed(2)+':1':'EMPTY';
$('style-limit').textContent=!selected.features?'EMPTY: no geometry or contrast claim.':options().casing==='dark'?'Black casing separates a mark from bright points, but its outer boundary has low contrast against dark ground. The coloured core is measured separately.':options().casing==='light'?'White casing separates from dark ground, but can disappear against bright substrate points. This is n … [line shortened here: 545 characters; full line on GitHub]
const report=exportVisibility(catalog,options());
const ground=report.counts.contexts.find(x=>x.context_id==='webgl_ground');
$('counts').textContent=`${catalog.layers.length} layers · ${catalog.counts.features.toLocaleString()} source features · ${catalog.counts.empty_layers} EMPTY · ${ground.current_meets_3_to_1}/${ground.evaluated_layers} current cores reach 3:1 against source ground`;
$('table-count').textContent=`(${catalog.layers.length})`;
if(tableBuilt){for(const row of report.rows){const tr=$('row-'+row.layer_id);tr.cells[2].textContent=row.status==='EMPTY'?'EMPTY':row.current_measurements[0].core_to_context_ratio.toFixed(2)+':1';tr.cells[3].textContent=row.status==='EMPTY'?'EMPTY':row.proposed_measurements[0].core_to_context_ratio.toFixed(2)+':1';}}
}
function draw(){
if(!catalog||!selected)return;
const pair=styles();
canvases.forEach((canvas,i)=>{
const width=canvas.clientWidth,height=canvas.clientHeight,dpr=Math.min(devicePixelRatio||1,3);
const wantedW=Math.round(width*dpr),wantedH=Math.round(height*dpr);
if(canvas.width!==wantedW)canvas.width=wantedW;if(canvas.height!==wantedH)canvas.height=wantedH;
const ctx=canvas.getContext('2d');ctx.setTransform(dpr,0,0,dpr,0,0);ctx.globalAlpha=1;ctx.fillStyle='#0b0d12';ctx.fillRect(0,0,width,height);
const view=cameraFor($('camera').value,geometry,width,height,catalog.max_issued_key);views.set(canvas,{...view,width,height});
if(!geometry?.features.length){ctx.fillStyle='#b5c1d1';ctx.font='14px system-ui';ctx.textAlign='center';ctx.fillText(geometry?'EMPTY · no marks':'Load a layer to see its issued keys',width/2,height/2);return;}
const s=pair[i],position=p=>[(p.x-view.x)*view.zoom+width/2,height/2-(p.y-view.y)*view.zoom];
for(const f of geometry.features){
if(f.type==='Point'){
const [x,y]=position(f.xy[0]);if(x<-8||x>width+8||y<-8||y>height+8)continue;
if(s.point_shape==='square'){ctx.globalAlpha=s.alpha;ctx.fillStyle=s.base_colour;ctx.fillRect(x-1,y-1,2,2);}
else{if(s.casing){ctx.globalAlpha=s.casing.alpha;ctx.fillStyle=s.casing.colour;ctx.beginPath();ctx.arc(x,y,s.casing.point_radius_css_px,0,2*Math.PI);ctx.fill();}ctx.globalAlpha=s.alpha;ctx.fillStyle=s.base_colour;ctx.beginPath();ctx.arc(x,y,s.point_radius_css_px,0,2*Math.PI);ctx.fill();}
}else{
ctx.beginPath();f.xy.forEach((p,j)=>{const [x,y]=position(p);j?ctx.lineTo(x,y):ctx.moveTo(x,y);});
if(s.casing){ctx.globalAlpha=s.casing.alpha;ctx.strokeStyle=s.casing.colour;ctx.lineWidth=s.casing.line_width_css_px;ctx.stroke();}
ctx.globalAlpha=s.alpha;ctx.strokeStyle=s.base_colour;ctx.lineWidth=s.line_width_css_px;ctx.stroke();
}
}
ctx.globalAlpha=1;
});
}
async function choose(id,load=true){
if(!catalog)return;const next=catalog.layers.find(l=>l.id===id);if(!next)throw Error('Unknown layer refused');
selected=next;$('layer').value=id;geometry=null;clearError();controller?.abort();const ticket=++epoch;
$('feature-detail').textContent='Tap a charted point to inspect its key and source feature. This view does not contain source-code bodies.';
$('geometry-status').textContent=`${id}: WAIT · ${next.features} source features`;styleReadings();draw();
if(!load)return;
queue=queue.catch(()=>{}).then(async()=>{
if(ticket!==epoch)return;
$('geometry-status').textContent=`${id}: LOAD`;
try{
let prepared=cache.get(id);
if(!prepared){controller=new AbortController();const doc=await readChecked(next.file,next.sha256,next.bytes,controller.signal);if(ticket!==epoch)return;prepared=prepareGeometry(doc,next,catalog.max_issued_key);cache.set(id,prepared);while(cache.size>2)cache.delete(cache.keys().next().value);}
if(ticket!==epoch)return;geometry=prepared;
$('geometry-status').textContent=`${id}: ${geometry.features.length?'OK':'EMPTY'} · ${geometry.features.length.toLocaleString()} features · ${geometry.keys.length.toLocaleString()} unique charted keys · unselected keys dark`;
draw();
}catch(e){if(ticket===epoch&&e.name!=='AbortError'){$('geometry-status').textContent=`${id}: REFUSED`;error(e.message);geometry=null;draw();}}
});return queue;
}
function buildTable(){
if(tableBuilt||!catalog)return;tableBuilt=true;const frag=document.createDocumentFragment();
for(const l of catalog.layers){const tr=document.createElement('tr');tr.id='row-'+l.id;for(const value of [l.label,l.features,'','']){const td=document.createElement('td');td.textContent=value;tr.append(td);}frag.append(tr);}
$('rows').append(frag);styleReadings();
}
function registerPageTools(){
const context=document.modelContext;if(!context?.registerTool)return;
const lifecycle=new AbortController();addEventListener('pagehide',()=>lifecycle.abort(),{once:true});
const snapshot=()=>({layer_id:selected?.id??null,geometry_status:$('geometry-status').textContent,features:geometry?.features.length??0,keys:geometry?.keys.length??0,casing:$('casing').value});
const register=tool=>{try{Promise.resolve(context.registerTool(tool,{signal:lifecycle.signal})).catch(()=>{});}catch{}};
register({name:'read_visibility',description:'Read the currently selected layer, geometry counts and casing.',inputSchema:{type:'object',properties:{},additionalProperties:false},annotations:{readOnlyHint:true},execute:input=>{if(!input||typeof input!=='object'||Array.isArray(input)||Object.keys(input).length)throw Error('Expected empty input');return snapshot();}});
register({name:'select_visibility_layer',description:'Select and load one catalogue layer in the visible comparison.',inputSchema:{type:'object',properties:{layerId:{type:'string'}},required:['layerId'],additionalProperties:false},annotations:{readOnlyHint:false},execute:async input=>{if(!input||typeof input!=='object'||Array.isArray(input)||Object.keys(input).length!==1||typeof input.layerId!== … [line shortened here: 543 characters; full line on GitHub]
}
canvases.forEach(canvas=>canvas.addEventListener('click',event=>{
if(!geometry?.keys.length)return;const rect=canvas.getBoundingClientRect(),v=views.get(canvas),x=event.clientX-rect.left,y=event.clientY-rect.top;
let nearest=null,best=100;
for(const p of geometry.keys){const dx=(p.x-v.x)*v.zoom+v.width/2-x,dy=v.height/2-(p.y-v.y)*v.zoom-y,d=dx*dx+dy*dy;if(d<best){best=d;nearest=p;}}
if(!nearest)return;$('feature-card').open=true;
$('feature-detail').textContent=JSON.stringify({layer_id:selected.id,key:nearest.key,feature_index_zero_based:nearest.feature_index,geometry_source:sourceRoot+selected.source_file,source_sha256:selected.source_sha256,note:'Code address, not an electrical coordinate. Exact source-code body is not included in this geometry projection.'},null,2);
}));
$('layer').addEventListener('change',()=>choose($('layer').value).catch(e=>error(e.message)));
$('load').addEventListener('click',()=>choose($('layer').value).catch(e=>error(e.message)));
$('camera').addEventListener('change',draw);$('casing').addEventListener('change',()=>{styleReadings();draw();});
$('table-panel').addEventListener('toggle',()=>{if($('table-panel').open)buildTable();});
$('export').addEventListener('click',()=>{
const report=exportVisibility(catalog,options());report.provenance=catalog.source;report.geometry_projection='catalog.json; feature counts independently checked during export; geometry fetched only on selection';
const blob=new Blob([JSON.stringify(report,null,2)+'\n'],{type:'application/json'}),url=URL.createObjectURL(blob),a=document.createElement('a');a.href=url;a.download='visibility-style.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);
});
new ResizeObserver(draw).observe($('current'));
async function init(){
try{
catalog=validateCatalog(await readChecked('catalog.json',CATALOG_SHA256));
$('layer').replaceChildren(...catalog.layers.map(l=>{const option=document.createElement('option');option.value=l.id;option.textContent=`${l.id} · ${l.label}`;return option;}));
for(const id of ['grid-engine-shell','learned','module-Ga','crossname','spider','module-Gg']){const button=document.createElement('button');button.textContent=id;button.addEventListener('click',()=>choose(id).catch(e=>error(e.message)));$('priorities').append(button);}
$('layer').disabled=false;$('load').disabled=false;$('export').disabled=false;
$('overlay-source').href=sourceRoot+'layers-panel.mjs';$('wafer-source').href=sourceRoot+'wafer.mjs';
$('machine').textContent=`Inputs: ${catalog.layers.length} pinned layer entries, colour in sRGB, opacity in [0,1], dimensions in CSS px, positive integer issued keys. Outputs: unitless contrast ratios and code-space geometry. Source commit ${catalog.source.commit}. Placement is unchanged; inferred electrical quantities: none.`;
await choose('module-Ga',false);registerPageTools();
}catch(e){error(e.message);$('counts').textContent='Catalogue REFUSED';}
}
init();Browser Check
A JavaScript module in the iterations folder of Galaxies Wafers that fetches visibility style and catalog. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/12-visibility-lab/.
rendergalaxies-wafers / iterations/12-visibility-lab/browser-check.mjs · lines 1–52 of 52 · Not reached from any entry point (candidate for review)
- What it does
- It fetches visibility style and catalog. Uses libraries node:fs/promises, node:url, node:path, node:child_process, node:assert/strict. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes.
- Why it exists in the grid workflow
- README: "`browser-check.mjs` exercises this exact page at390x844 and1400x900 in Chromium and WebKit."
- Inputs & outputs
- In: JSON file catalog.json. Out: JSON file visibility-style.json; JSON file receipt.json.
- What it achieves
- The README says: `browser-check.mjs` exercises this exact page at390x844 and1400x900 in Chromium and WebKit.
- Why it matters
- No other file in the estate was found to import it.
- Application
- galaxies-wafers · iterations/12-visibility-lab · JavaScript module
- Uses
- node:fs/promises, node:url, node:path, node:child_process, node:assert/strict
- Used by
- none found
- 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
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/12-visibility-lab/browser-check.mjs:1-52 · blob 13d190c1747c8ddf4c09ee85666a4518f637bc0c · GitHub at these lines
- State
- achieves: readme · context: readme_derived · stage: output · effects: dom, filesystem, network, process · domain stage: unknown · users: none · canonical: unreached_review
import {mkdir,writeFile,readFile} from 'node:fs/promises';
import {fileURLToPath} from 'node:url';
import {dirname,resolve} from 'node:path';
import {spawn} from 'node:child_process';
import assert from 'node:assert/strict';
const {chromium,webkit}=await import(process.env.PLAYWRIGHT_MODULE||'playwright');
const directory=dirname(fileURLToPath(import.meta.url));
const output=resolve(process.env.PROOF_OUTPUT||'browser-evidence');await mkdir(output,{recursive:true});
let server=null;const base=process.env.PAGE_URL||'http://127.0.0.1:8779/';
if(!process.env.PAGE_URL){server=spawn('python',['-m','http.server','8779','--bind','127.0.0.1','--directory',directory],{stdio:'ignore',windowsHide:true});for(let i=0;i<40;i++){try{if((await fetch(base)).ok)break;}catch{}await new Promise(r=>setTimeout(r,100));}}
const results=[];let failed=false;
try{
for(const engineName of (process.env.BROWSER_ENGINES||'chromium,webkit').split(',')){
const engine={chromium,webkit}[engineName];if(!engine)throw Error('Unsupported test browser');
const launchOptions=engineName==='chromium'&&process.env.CHROME_PATH?{executablePath:process.env.CHROME_PATH}:{};
const browser=await engine.launch({headless:true,...launchOptions});
try{
for(const viewport of [{width:390,height:844},{width:1400,height:900}]){
const started=new Date().toISOString(),errors=[],failedRequests=[],geometryRequests=[];
const context=await browser.newContext({viewport,deviceScaleFactor:viewport.width===390?3:1,isMobile:viewport.width===390,hasTouch:viewport.width===390});
const page=await context.newPage();page.on('pageerror',e=>errors.push(e.message));page.on('console',m=>{if(m.type()==='error')errors.push(m.text());});page.on('requestfailed',r=>{if(!/ABORTED|cancelled/i.test(r.failure()?.errorText||''))failedRequests.push(r.url());});page.on('request',r=>{if(r.url().includes('/geometry/'))geometryRequests.push(r.url());});
let result={engine:engineName,version:browser.version(),viewport,dpr:viewport.width===390?3:1,started,pass:false};
try{
const response=await page.goto(base,{waitUntil:'networkidle'});assert.equal(response.status(),200);
await page.waitForFunction(()=>!document.querySelector('#layer').disabled);
assert.equal(await page.locator('#layer option').count(),201);assert.equal(geometryRequests.length,0);
await page.getByRole('button',{name:'Load selected layer',exact:true}).click();
await page.waitForFunction(()=>document.querySelector('#geometry-status').textContent.includes('module-Ga: OK'));
assert.equal(geometryRequests.length,1);
await page.locator('#camera').selectOption('fit');
await page.screenshot({path:resolve(output,`${engineName}-${viewport.width}-fit.png`),fullPage:true});
await page.locator('#camera').selectOption('near');
await page.screenshot({path:resolve(output,`${engineName}-${viewport.width}-near.png`),fullPage:true});
const rect=await page.locator('#proposed').boundingBox();await page.locator('#proposed').click({position:{x:rect.width/2,y:rect.height/2}});
assert.match(await page.locator('#feature-detail').textContent(),/"key":/);
await page.getByRole('button',{name:'spider',exact:true}).click();await page.waitForFunction(()=>document.querySelector('#geometry-status').textContent.includes('spider: EMPTY'));
assert.equal(await page.locator('#current-ratio').textContent(),'EMPTY');
await page.locator('#table-panel summary').click();await page.waitForFunction(()=>document.querySelectorAll('#rows tr').length===201);assert.equal(await page.locator('#rows tr').count(),201);assert.equal(geometryRequests.length,2);
await page.getByRole('button',{name:'learned',exact:true}).click();await page.waitForFunction(()=>document.querySelector('#geometry-status').textContent.includes('learned: OK'));
await page.locator('#casing').selectOption('light');assert.match(await page.locator('#style-limit').textContent(),/bright substrate/);
const downloadPromise=page.waitForEvent('download');await page.getByRole('button',{name:'Download style JSON'}).click();const download=await downloadPromise;assert.equal(download.suggestedFilename(),'visibility-style.json');
const downloadPath=resolve(output,`${engineName}-${viewport.width}-style.json`);await download.saveAs(downloadPath);const exported=JSON.parse(await readFile(downloadPath,'utf8'));assert.equal(exported.rows.length,201);assert.equal(exported.counts.empty_layers,3);assert.equal(exported.rows[0].proposed.point_radius_css_px,4);
const overflow=await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+1);assert.equal(overflow,false);assert.deepEqual(errors,[]);assert.deepEqual(failedRequests,[]);
result={...result,pass:true,geometry_fetches:geometryRequests.length,overflow,errors,failed_requests:failedRequests,webmcp_validation:'Not exercised by this harness; optional support is not claimed verified.'};
await page.route('**/catalog.json',route=>route.fulfill({status:200,contentType:'application/json',body:'{}'}));await page.reload({waitUntil:'networkidle'});assert.match(await page.locator('#failure').textContent(),/digest refused/);assert.equal(await page.locator('#layer').isDisabled(),true);result.tampered_catalog_refused=true;
}catch(e){failed=true;result={...result,pass:false,error:e.message,errors,failed_requests:failedRequests};}
result.finished=new Date().toISOString();results.push(result);await context.close();
}
}finally{await browser.close();}
}
}finally{server?.kill();await writeFile(resolve(output,'receipt.json'),JSON.stringify({source_commit:process.env.GITHUB_SHA||null,url:base,results},null,2)+'\n');}
console.log(JSON.stringify({cases:results.length,passed:results.filter(x=>x.pass).length}));if(failed)process.exitCode=1;Export Style
A JavaScript module in the iterations folder of Galaxies Wafers that reads catalog and visibility style, using SHA-256. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/12-visibility-lab/.
storagegalaxies-wafers / iterations/12-visibility-lab/export-style.mjs · lines 1–13 of 13 · Not reached from any entry point (candidate for review)
- What it does
- It loads catalog and visibility style. Uses libraries node:fs/promises, node:crypto. Side effects: reads or writes files.
- Inputs & outputs
- In: JSON file catalog.json; command-line arguments. Out: JSON file visibility-style.json.
- What it achieves
- Its name says it exports style. It reads `./catalog.json` and writes `./visibility-style.json`.
- Why it matters
- No other file in the estate was found to import it.
- Application
- galaxies-wafers · iterations/12-visibility-lab · JavaScript module
- Uses
- Visibility Style (import), Model (import), node:fs/promises, node:crypto
- Used by
- none found
- 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
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/12-visibility-lab/export-style.mjs:1-13 · blob 3b4330e06db872b365ad8362cc6e6e597004bdbe · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: unreached_review
import {readFile,writeFile} from 'node:fs/promises';
import {createHash} from 'node:crypto';
import {exportVisibility} from './visibility-style.mjs';
import {validateCatalog,CATALOG_SHA256} from './model.mjs';
const raw=await readFile(new URL('./catalog.json',import.meta.url));
if(createHash('sha256').update(raw).digest('hex')!==CATALOG_SHA256)throw Error('Catalogue pin mismatch');
const catalog=validateCatalog(JSON.parse(raw));
const output=exportVisibility(catalog,{casing:'dark',pointRadiusCssPx:4,strokeCssPx:2});
output.provenance=catalog.source;
output.geometry_projection='catalog.json; feature counts independently checked during export; geometry fetched only on selection';
const bytes=JSON.stringify(output,null,2)+'\n';
await writeFile(process.argv[2]||new URL('./visibility-style.json',import.meta.url),bytes,{flag:'wx'});
console.log(JSON.stringify({layers:output.rows.length,bytes:Buffer.byteLength(bytes),sha256:createHash('sha256').update(bytes).digest('hex')}));Iterations — 12 Visibility Lab Page
A web page in Galaxies Wafers that draws visibility style and catalog. Published at https://ventusltd.github.io/galaxies-wafers/iterations/12-visibility-lab/.
rendergalaxies-wafers / iterations/12-visibility-lab/index.html · lines 1–31 of 31 · Entry point
- What it does
- It draws visibility style and catalog. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- README: "The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/202609151339."
- Inputs & outputs
- In: JSON file visibility-style.json; JSON file catalog.json; form fields (user input). Out: web page.
- Downstream impact
- It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/12-visibility-lab/.
- What it achieves
- Compare pinned code-layer geometry, stroke sizes and contrast on a dark substrate.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- galaxies-wafers · iterations/12-visibility-lab · page
- Uses
- Galaxies Wafers — Style Sheet (stylesheet), Iterations — 12 Visibility Lab (script src)
- Used by
- none found
- 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
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/12-visibility-lab/index.html:1-31 · blob 19be7ced5f121437233d24918ac61d936f187183 · 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">
<meta name="description" content="Compare pinned code-layer geometry, stroke sizes and contrast on a dark substrate.">
<title>Layer visibility · Code geometry</title>
<link rel="stylesheet" href="style.css">
<header><span class="eyebrow">CODE GEOMETRY / VISIBILITY</span><h1>Make a layer legible.</h1><p>Same issued keys. Same colours. Compare the marks, not a new layout.</p></header>
<main>
<p id="failure" role="alert" hidden></p>
<section class="controls" aria-label="Layer and view controls">
<label>Layer<select id="layer" disabled><option>Reading catalogue…</option></select></label>
<div id="priorities" class="chips"></div>
<button id="load" disabled>Load selected layer</button>
<div class="settings"><label>Camera<select id="camera"><option value="home">All issued space</option><option value="fit">Fit this layer</option><option value="near">First key · zoom 9</option></select></label><label>Proposed casing<select id="casing"><option value="dark">Black outline</option><option value="light">White comparison</option><option value="none">No casing</option></select></label></d … [line shortened here: 403 characters; full line on GitHub]
<p id="counts" role="status">Reading catalogue…</p>
</section>
<section class="plots" aria-label="Current and proposed geometry">
<figure><figcaption><strong>Current</strong><span>1 px lines · 2 × 2 px points</span></figcaption><canvas id="current" aria-label="Current layer geometry"></canvas></figure>
<figure><figcaption><strong>Proposed</strong><span>2 px lines · 4 px point radius</span></figcaption><canvas id="proposed" aria-label="Proposed layer geometry"></canvas></figure>
</section>
<p id="geometry-status" role="status">Choose a layer to load its geometry. Unselected keys stay dark.</p>
<div class="readings"><div><span>Current core / ground</span><strong id="current-ratio">—</strong></div><div><span>Proposed core / ground</span><strong id="proposed-ratio">—</strong></div><div><span>Proposed outer boundary / ground</span><strong id="boundary-ratio">—</strong></div></div>
<p id="style-limit" class="note"></p>
<p class="note">Sizes are a project policy in CSS pixels. The 3:1 comparison is a full-coverage pixel model—not a readability guarantee or a WCAG conformance claim. Zoom changes placement, not mark sizes. Colours encode source layers, never verdicts.</p>
<details id="feature-card"><summary>Selected geometry</summary><pre id="feature-detail">Tap a charted point to inspect its key and source feature. This view does not contain source-code bodies.</pre></details>
<details id="table-panel"><summary>All-layer style table <span id="table-count"></span></summary><p>Metadata only: opening this table does not load layer geometry.</p><div class="table-scroll"><table><thead><tr><th>Layer</th><th>Features</th><th>Current core / ground</th><th>Proposed core / ground</th></tr></thead><tbody id="rows"></tbody></table></div></details>
<p><button id="export" disabled>Download style JSON</button> <a href="visibility-style.json">Default style JSON</a> · <a href="catalog.json">Geometry catalogue</a></p>
<details><summary>Questions</summary><h2>How does this help draw a system or an SLD?</h2><p>It tests whether a code-layer point or route can be distinguished. It draws no busbar, feeder, transformer, protection or earthing element. <code>features[].keys</code> feeds frozen <code>place(key)</code>; these are code addresses, not electrical coordinates.</p><h2>What is this code used for?</h2><p><code … [line shortened here: 1,124 characters; full line on GitHub]
<details><summary>Machine detail</summary><p id="machine">Loading source identity…</p><p>Refusals: unknown layer, malformed geometry, unissued keys during export, mismatched file digest or feature count. Empty layers create no marks. Geometry is loaded only on selection, one request at a time; obsolete requests are cancelled. No all-layer geometry preload.</p><p><a href="README.md">Method and limi … [line shortened here: 532 characters; full line on GitHub]
</main><script type="module" src="app.mjs"></script>
</html>Model
A JavaScript module in the iterations folder of Galaxies Wafers that validates catalog (`validateCatalog`) and prepares geometry (`prepareGeometry`), using SHA-256. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/12-visibility-lab/.
transformgalaxies-wafers / iterations/12-visibility-lab/model.mjs · lines 1–32 of 32 · pattern cameraFor (shared by 2 files)
- What it does
- It calculates its inputs. Defines validateCatalog, prepareGeometry, cameraFor.
- Downstream impact
- Used directly by 3 files: Iterations — 12 Visibility Lab (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/12-visibility-lab/); Export Style (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/12-visibility-lab/); Model Test (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/12-visibility-lab/). Reached from 1 other entry point, including Iterations — 12 Visibility Lab Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/12-visibility-lab/).
- What it achieves
- It validates catalog (`validateCatalog`) and prepares geometry (`prepareGeometry`). Defines `validateCatalog`, `prepareGeometry` and `cameraFor`.
- Why it matters
- Imported by Iterations — 12 Visibility Lab and Export Style. Checked by Model Test.
- Application
- galaxies-wafers · iterations/12-visibility-lab · JavaScript module
- Uses
- Wafer (import)
- Used by
- imported by Iterations — 12 Visibility Lab (import), imported by Export Style (import), imported by Model Test (import), mentioned in Standalone (comment link)
- Produces
- CATALOG_SHA256, validateCatalog, prepareGeometry, cameraFor
- Defines here
- validateCatalog, prepareGeometry, cameraFor
- 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 iterations/12-visibility-lab/model.mjs:1-32 · blob 46979a0c8e613e6745f8ee5e5a8c05fee0421adf · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unknown
import {place} from './wafer.mjs';
export const CATALOG_SHA256='89dbaa88310ab87e1b4caa6e16efdaa3473bd50e1b942a9564fa4f12f2ab2cd7';
export function validateCatalog(c){
if(c?.schema!=='code.visibility-catalog.v1'||c.substrate!=='wafer.v1'||!Array.isArray(c.layers))throw Error('Catalogue contract refused');
const ids=new Set();let total=0,empty=0;
for(const l of c.layers){
if(!/^[\w-]+$/.test(l.id)||ids.has(l.id)||!/^#[0-9a-f]{6}$/i.test(l.colour)||!Number.isSafeInteger(l.features)||l.features<0||l.file!==`geometry/${l.id}.json`||!Number.isSafeInteger(l.bytes)||l.bytes<0||!/^[a-f0-9]{64}$/.test(l.sha256))throw Error('Layer metadata refused');
ids.add(l.id);total+=l.features;empty+=Number(l.features===0);
}
if(c.counts?.layers!==ids.size||c.counts.features!==total||c.counts.empty_layers!==empty)throw Error('Catalogue count mismatch');
return c;
}
export function prepareGeometry(doc,layer,maxKey){
if(doc?.schema!=='code.geometry.v1'||doc.layer_id!==layer.id||!Array.isArray(doc.features)||doc.features.length!==layer.features)throw Error('Geometry identity or count refused');
const keys=new Map(),features=[];
let minX=Infinity,maxX=-Infinity,minY=Infinity,maxY=-Infinity;
doc.features.forEach((feature,index)=>{
if(!['Point','LineString'].includes(feature.type)||!Array.isArray(feature.keys)||!feature.keys.length||(feature.type==='Point'&&feature.keys.length!==1)||(feature.type==='LineString'&&feature.keys.length<2))throw Error('Geometry shape refused');
const xy=feature.keys.map(key=>{
if(!Number.isSafeInteger(key)||key<=0||key>maxKey)throw Error('Geometry key range refused');
if(!keys.has(key)){const [x,y]=place(key);keys.set(key,{key,x,y,feature_index:index});minX=Math.min(minX,x);maxX=Math.max(maxX,x);minY=Math.min(minY,y);maxY=Math.max(maxY,y);}
return keys.get(key);
});features.push({type:feature.type,xy});
});
return {features,keys:[...keys.values()],bounds:keys.size?{minX,maxX,minY,maxY}:null};
}
export function cameraFor(mode,geometry,width,height,maxKey){
if(mode==='home'||!geometry?.keys.length)return{x:0,y:0,zoom:Math.min(width,height)/(Math.sqrt(maxKey)*2.15)};
if(mode==='near'){const p=geometry.keys[0];return{x:p.x,y:p.y,zoom:9};}
if(mode!=='fit')throw Error('Unknown camera');
const b=geometry.bounds;return{x:(b.minX+b.maxX)/2,y:(b.minY+b.maxY)/2,zoom:Math.min(20,(width-36)/Math.max(1,b.maxX-b.minX),(height-36)/Math.max(1,b.maxY-b.minY))};
}Model Test
A test in the iterations folder of Galaxies Wafers that checks Model and Visibility Style, using SHA-256. It is built from the sha step (`sha`).
testgalaxies-wafers / iterations/12-visibility-lab/model.test.mjs · lines 1–19 of 19 · Not reached from any entry point (candidate for review)
- What it does
- It tests its inputs. Defines sha. Uses libraries node:test, node:assert/strict, node:fs/promises, node:crypto. Side effects: reads or writes files.
- Why it exists in the grid workflow
- README: "`model.test.mjs` checks the pure model and all geometry identities/hashes"
- Inputs & outputs
- In: JSON file catalog.json.
- What it achieves
- The README says: `model.test.mjs` checks the pure model and all geometry identities/hashes. It reads `./catalog.json`.
- Why it matters
- Guards the behaviour of Model, Visibility Style and Wafer.
- Application
- galaxies-wafers · iterations/12-visibility-lab · test
- Uses
- Model (import), Visibility Style (import), Wafer (new URL import.meta.url), node:test, node:assert/strict, node:fs/promises, node:crypto
- Used by
- none found
- Produces
- sha
- Defines here
- sha
- 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 iterations/12-visibility-lab/model.test.mjs:1-19 · blob 324357b9615a9395c466ec41e335bce4391cbbee · GitHub at these lines
- State
- achieves: readme · context: readme_derived · stage: ingest · effects: filesystem · domain stage: unknown · users: none · canonical: unreached_review
import test from 'node:test';
import assert from 'node:assert/strict';
import {readFile} from 'node:fs/promises';
import {createHash} from 'node:crypto';
import {validateCatalog,prepareGeometry,cameraFor,CATALOG_SHA256} from './model.mjs';
import {currentStyle,proposedStyle,measureStyle,sourceContexts,exportVisibility,contrast,composite,luminance} from './visibility-style.mjs';
const bytes=await readFile(new URL('./catalog.json',import.meta.url));
const catalog=validateCatalog(JSON.parse(bytes));
const sha=b=>createHash('sha256').update(b).digest('hex');
test('catalogue and frozen placement retain exact pins',async()=>{assert.equal(sha(bytes),CATALOG_SHA256);const wafer=await readFile(new URL('./wafer.mjs',import.meta.url));assert.equal(sha(wafer.toString('utf8').replaceAll('\r\n','\n')),'3f7a57344a804fbc7e7352155b40fe0d3cae42c8f6d1fd50a7dfc4b6234c0809');});
test('all 201 geometry files retain digest, identity and actual feature totals',async()=>{let features=0,empty=0;for(const layer of catalog.layers){const raw=await readFile(new URL(layer.file,import.meta.url));assert.equal(raw.length,layer.bytes);assert.equal(sha(raw),layer.sha256);const prepared=prepareGeometry(JSON.parse(raw),layer,catalog.max_issued_key);features+=prepared.features.length;empty … [line shortened here: 534 characters; full line on GitHub]
test('all styles preserve palette and current baseline counts',()=>{const report=exportVisibility(catalog,{casing:'dark',pointRadiusCssPx:4});assert.equal(report.counts.evaluated_layers,198);assert.equal(report.counts.contexts[0].current_meets_3_to_1,25);report.rows.forEach((row,i)=>{assert.equal(row.base_colour,catalog.layers[i].colour);assert.equal(row.proposed.point_radius_css_px,4);assert.equa … [line shortened here: 493 characters; full line on GitHub]
test('source line opacity and square sizes are not upgraded in current view',()=>{const source=currentStyle({colour:'#0054ff',draws:'lines'});assert.equal(source.alpha,.55);assert.equal(source.line_width_css_px,1);assert.equal(source.point_width_css_px,2);assert.equal(source.point_shape,'square');});
test('black and white casing limits remain visible',()=>{const layer={colour:'#0054ff',draws:'lines'},contexts=sourceContexts();const black=measureStyle(proposedStyle(layer,{casing:'dark'}),contexts);const white=measureStyle(proposedStyle(layer,{casing:'light'}),contexts);assert.ok(black[0].boundary_ratio<3);assert.ok(white[1].boundary_ratio<3);assert.ok(white[0].boundary_ratio>3);});
test('contrast/compositing uses unrounded sRGB channels',()=>{assert.equal(contrast('#ffffff','#000000'),21);assert.deepEqual(composite('#ffffff',.5,'#000000'),[.5,.5,.5]);assert.ok(Math.abs(luminance([.5,.5,.5])-.21404114048223255)<1e-12);});
test('empty geometry cannot manufacture marks or zoom focus',()=>{const l=catalog.layers.find(x=>x.id==='spider');const g=prepareGeometry({schema:'code.geometry.v1',layer_id:l.id,features:[]},l,catalog.max_issued_key);assert.deepEqual(g.keys,[]);assert.equal(g.bounds,null);assert.deepEqual(cameraFor('near',g,390,255,342795),cameraFor('home',g,390,255,342795));});
test('malformed catalogues fail closed',()=>{const duplicate=structuredClone(catalog);duplicate.layers.push(duplicate.layers[0]);assert.throws(()=>validateCatalog(duplicate));const count=structuredClone(catalog);count.counts.features++;assert.throws(()=>validateCatalog(count));});
test('wrong geometry identity, missing features and bad keys are refused',()=>{const l={id:'fixture',features:1};for(const doc of [{schema:'code.geometry.v1',layer_id:'wrong',features:[]},{schema:'code.geometry.v1',layer_id:l.id,features:[]},{schema:'code.geometry.v1',layer_id:l.id,features:[{type:'Point',keys:[0]}]},{schema:'code.geometry.v1',layer_id:l.id,features:[{type:'Point',keys:[999999]}]} … [line shortened here: 454 characters; full line on GitHub]
test('pure model is repeatable without input mutation',()=>{const before=JSON.stringify(catalog);assert.deepEqual(exportVisibility(catalog,{casing:'dark'}),exportVisibility(catalog,{casing:'dark'}));assert.equal(JSON.stringify(catalog),before);});