GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Automation and CI / globalgrid2050 / testcode/202609150502/proof

Build and 8 more files (part 1)

A JavaScript module in the testcode folder of GlobalGrid2050 that reads surfaces and laws. It reads stamp (`readStamp`), reads title (`readTitle`) and reads law (`readLaw`).

627 lines of JavaScript and Python from globalgrid2050, in 9 files. Topic: Automation and CI. Section 1797 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Publication storage · globalgrid2050 / testcode/202609150502/proof/publication.py lines 1–55
  2. Self Test test · globalgrid2050 / testcode/202609150502/proof/self-test.mjs lines 1–28
  3. Snapshot storage · globalgrid2050 / testcode/202609150502/proof/snapshot.py lines 1–36
  4. Page Check render · globalgrid2050 / testcode/202609151339/proof/page.check.mjs lines 1–36
  5. Build All Lines storage · globalgrid2050 / testcode/202609152203/build_all_lines.mjs lines 1–29
  6. Add All Lines storage · globalgrid2050 / testcode/202609152203/proof/add_all_lines.mjs lines 1–40
  7. Key Permanence storage · globalgrid2050 / testcode/202609152203/proof/key_permanence.mjs lines 1–53
  8. Pack Check storage · globalgrid2050 / testcode/202609152203/proof/pack_check.mjs lines 1–58
  9. Build storage · globalgrid2050 / testcode/202609160224/build.mjs lines 1–292

Publication

A Python command-line tool in the proof folder of GlobalGrid2050 that uses SHA-256. It is built from the digest step (`digest`).

storageglobalgrid2050 / testcode/202609150502/proof/publication.py · lines 1–55 of 55 · version 2026-09-15 05:02 · Entry point · pattern digest (shared by 56 files)

What it does
It fetches data. Defines digest, main. Uses libraries argparse, hashlib, json, pathlib, urllib.request. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: JSON file publication.json; command-line arguments. Out: JSON file publication.json.
Downstream impact
Used directly by 1 file: GlobalGrid2050 UK Solar Lens Workflow (globalgrid2050).
What it achieves
Build or verify a byte manifest, including the shared Generator runtime. It accepts `--verify`, `--base` and `--report`.
Why it matters
Run by GlobalGrid2050 UK Solar Lens Workflow.
Application
globalgrid2050 · testcode/202609150502/proof · Python CLI
Uses
argparse, hashlib, json, pathlib, urllib.request
Used by
run by GlobalGrid2050 UK Solar Lens Workflow (workflow run)
Produces
digest, main
Defines here
digest, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609150502/proof/publication.py:1-55 · blob 98ab024c0846a0ca27ca7db335df7db327160930 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: experimental · users: none · canonical: production_core
"""Build or verify a byte manifest, including the shared Generator runtime."""
import argparse
import hashlib
import json
from pathlib import Path
import urllib.request

ROOT = Path(__file__).resolve().parents[1]
DEPENDENCIES = ['../202609142225/core.js', '../202609142225/gl.js', '../202609142225/GRAMMAR.md']

def digest(data):
    return {'bytes': len(data), 'sha256': hashlib.sha256(data).hexdigest()}

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--verify', action='store_true')
    parser.add_argument('--base', help='Served URL of this stamped folder')
    parser.add_argument('--report')
    args = parser.parse_args()
    if not args.verify:
        files = {p.relative_to(ROOT).as_posix(): digest(p.read_bytes()) for p in sorted(ROOT.rglob('*'))
                 if p.is_file() and p.name != 'publication.json' and '__pycache__' not in p.parts}
        result = {'schema': 'public-byte-manifest-v1', 'files': files,
                  'dependencies': {name: digest((ROOT / name).read_bytes()) for name in DEPENDENCIES}}
        (ROOT / 'publication.json').write_text(json.dumps(result, indent=2)+'\n', encoding='utf-8', newline='\n')
        print(json.dumps({'pass': True, 'files': len(files), 'dependencies': len(DEPENDENCIES)}))
        return
    manifest_bytes = (ROOT / 'publication.json').read_bytes()
    manifest = json.loads(manifest_bytes)
    report = {'pass': False, 'checked': []}
    try:
        if args.base:
            with urllib.request.urlopen(args.base.rstrip('/')+'/publication.json', timeout=60) as r:
                if r.read() != manifest_bytes:
                    raise ValueError('Served manifest differs from the committed manifest')
        for name, expected in {**manifest['files'], **manifest['dependencies']}.items():
            data = (ROOT / name).read_bytes()
            if digest(data) != expected:
                raise ValueError(f'Committed bytes differ: {name}')
            if args.base:
                with urllib.request.urlopen(args.base.rstrip('/')+'/'+name, timeout=60) as r:
                    if r.read() != data:
                        raise ValueError(f'Served bytes differ: {name}')
            report['checked'].append({'file': name, **expected})
        report['pass'] = True
    except Exception as error:
        report['error'] = str(error)
    if args.report:
        Path(args.report).write_text(json.dumps(report, indent=2)+'\n', encoding='utf-8')
    print(json.dumps(report, indent=2))
    if not report['pass']:
        raise SystemExit(1)

if __name__ == '__main__':
    main()

Self Test

A JavaScript module in the proof folder of GlobalGrid2050 that tests UK solar, today and provenance, using SHA-256.

testglobalgrid2050 / testcode/202609150502/proof/self-test.mjs · lines 1–28 of 28 · version 2026-09-15 05:02 · Entry point

What it does
It tests UK solar, today and provenance. Defines check. Uses libraries node:assert/strict, node:fs, node:crypto, node:url. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: JSON file uk-solar.json; JSON file today.json; JSON file provenance.json.
Downstream impact
Used directly by 1 file: GlobalGrid2050 UK Solar Lens Workflow (globalgrid2050).
What it achieves
Defines `check`.
Why it matters
Run by GlobalGrid2050 UK Solar Lens Workflow.
Application
globalgrid2050 · testcode/202609150502/proof · JavaScript module
Uses
Model (import), Ring (import), Table (import), node:assert/strict, node:fs, node:crypto, node:url
Used by
run by GlobalGrid2050 UK Solar Lens Workflow (workflow run)
Produces
check
Defines here
check
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609150502/proof/self-test.mjs:1-28 · blob bf735d01a06823ad5aea53737d651c7921116936 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: experimental · users: none · canonical: production_core
import assert from 'node:assert/strict';
import fs from 'node:fs';
import {createHash} from 'node:crypto';
import {fileURLToPath} from 'node:url';
import {makeCore,readState,queryFor,projectURL,seriesLight} from '../model.mjs';
import ring from '../ring.mjs';
import table from '../table.mjs';
const root=new URL('../',import.meta.url),json=p=>JSON.parse(fs.readFileSync(new URL(p,root),'utf8'));
const report={pass:false,checks:[]};
const check=(name,fn)=>{fn();report.checks.push({name,pass:true});};
try{
const pack=json('data/uk-solar.json'),today=json('data/today.json'),core=makeCore(pack),seed=today.seed;
check('public source hashes',()=>{for(const [name,proof] of Object.entries(json('data/provenance.json').files)){const b=fs.readFileSync(new URL(`data/${name}`,root));assert.equal(b.length,proof.bytes);assert.equal(createHash('sha256').update(b).digest('hex'),proof.sha256);}});
check('all permanent records and explicit null geometry',()=>{assert.equal(core.N,3563);assert.equal(core.byKey.size,3563);assert.deepEqual(core.rec.filter(p=>p.latitude===null).map(p=>p.repd_ref),['14773','1613','1616','17120','17260']);assert.equal(core.rec.filter(p=>p.latitude!==null).length,3558);});
check('declared totals are recomputed at source precision',()=>{assert.equal(core.N,pack.solar_projects);assert.equal(Number(core.rec.reduce((s,p)=>s+(p.capacity_mw??0),0).toFixed(3)),pack.solar_capacity_mw);for(const status of core.statuses)assert.equal(core.rec.filter(p=>p.status===status).length,pack.by_status[status]);});
const view={w:430,h:380,seed,focus:0};const a=new Float32Array(core.N*2),b=new Float32Array(core.N*2);
check('registered lens contracts and pure deterministic ring bounds',()=>{for(const L of [ring,table])for(const key of ['id','from','wants','draws','hint','layout','edges','labels'])assert.ok(key in L);ring.layout(core,view,a);ring.layout(core,view,b);assert.deepEqual(a,b);assert.ok(a.every(Number.isFinite));for(let i=0;i<core.N;i++){assert.ok(a[2*i]>=0&&a[2*i]<=view.w);assert.ok(a[2*i+1]>=0&&a[2*  … [line shortened here: 563 characters; full line on GitHub]
check('URL round trip preserves seed selection and lens',()=>{for(const key of ['10000','14773']){const s=readState(`?lens=table&seed=${seed}&repd_ref=${key}`,seed,core);assert.equal(s.focus,core.resolve(key));assert.deepEqual(readState(queryFor(s),seed,core),s);s.lens='ring';assert.equal(readState(queryFor(s),seed,core).key,key);assert.equal(new URL(projectURL(key)).searchParams.get('repd_ref'),k  … [line shortened here: 408 characters; full line on GitHub]
check('unknown and malformed input is explicit',()=>{assert.equal(readState('?seed=bad&lens=unknown&repd_ref=999999999',seed,core).notes.length,3);assert.equal(readState('?seed=bad',seed,core).seed,seed);assert.equal(readState(`?seed=${'f'.repeat(64)}`,seed,core).seed,'f'.repeat(64));});
check('different valid seed changes layout, key order does not',()=>{ring.layout(core,{...view,seed:'a'.repeat(64)},b);assert.notDeepEqual(a,b);const reversed=makeCore({...pack,projects:[...pack.projects].reverse()});ring.layout(reversed,view,b);assert.deepEqual(a,b);});
check('table layout is pure from measured view inputs',()=>{const v={...view,params:{tableRows:[{i:0,x:100,y:24,height:48},{i:23,x:100,y:76,height:56}]}};table.layout(core,v,a);table.layout(core,structuredClone(v),b);assert.deepEqual(a,b);assert.equal(a[0],100);assert.equal(a[47],76);assert.ok(Number.isNaN(a[2]));});
check('reject invented or partial coordinates and invalid capacity',()=>{for(const edit of [{latitude:0},{capacity_mw:-1},{capacity_mw:NaN}]){const p=structuredClone(pack);Object.assign(p.projects.find(x=>x.latitude===null),edit);assert.throws(()=>makeCore(p));}const p=structuredClone(pack);p.projects[0].capacity_mw=null;assert.equal(makeCore(p).mass[0],0);p.projects[0].capacity_mw=0;assert.equal(  … [line shortened here: 426 characters; full line on GitHub]
check('light uses measured series with finite bounded values',()=>{const light=seriesLight(today.pv_live.series);assert.equal(light.length,today.pv_live.intervals);assert.ok(light.every(x=>x>=0&&x<=1));assert.deepEqual(seriesLight([{generation_mw:0}]),[0]);assert.throws(()=>seriesLight([{generation_mw:NaN}]));});
check('no unseeded random calls in shipped production modules',()=>{for(const name of ['model.mjs','ring.mjs','table.mjs','app.mjs'])assert.ok(!/Math\.random\s*\(/.test(fs.readFileSync(new URL(name,root),'utf8')));});
report.pass=true;
}catch(e){report.error=e.stack;}
const out=process.env.REPORT_PATH;if(out)fs.writeFileSync(out,JSON.stringify(report,null,2)+'\n');
console.log(JSON.stringify(report,null,2));if(!report.pass)process.exitCode=1;

Snapshot

A Python command-line tool in the proof folder of GlobalGrid2050 that fetches UK solar, today and sun provenance, using SHA-256 from the star-solar-star repository.

storageglobalgrid2050 / testcode/202609150502/proof/snapshot.py · lines 1–36 of 36 · version 2026-09-15 05:02 · Entry point

What it does
It fetches UK solar, today and sun provenance. Defines main. Uses libraries argparse, hashlib, json, pathlib, urllib.request. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: data source: star-solar-star data; JSON file uk-solar.json; JSON file today.json; JSON file provenance.json; JSON file sun-provenance.json; command-line arguments. Out: JSON file provenance.json.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Pin already-public Sun owner files; no collectors or private inputs live here. It accepts `--commit`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
globalgrid2050 · testcode/202609150502/proof · Python CLI
Uses
argparse, hashlib, json, pathlib, urllib.request, datetime
Used by
none found
Produces
main
Defines here
main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609150502/proof/snapshot.py:1-36 · blob 0fd4e6eb040ebbb7c9e2658d6b9d298999cdda70 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: experimental · users: none · canonical: production_core
"""Pin already-public Sun owner files; no collectors or private inputs live here."""
import argparse
import hashlib
import json
import pathlib
import urllib.request
from datetime import datetime, timezone

ROOT = pathlib.Path(__file__).resolve().parents[1]

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--commit', required=True)
    args = parser.parse_args()
    if len(args.commit) != 40 or any(c not in '0123456789abcdef' for c in args.commit):
        raise ValueError('A full public source commit is required')
    files = {}
    (ROOT / 'data').mkdir(exist_ok=True)
    for name in ['uk-solar.json', 'today.json', 'provenance.json']:
        url = f'https://raw.githubusercontent.com/Ventusltd/star-solar-star/{args.commit}/sun/{name}'
        with urllib.request.urlopen(url, timeout=60) as response:
            data = response.read()
        json.loads(data)
        dest = 'sun-provenance.json' if name == 'provenance.json' else name
        (ROOT / 'data' / dest).write_bytes(data)
        files[dest] = {'url': url, 'bytes': len(data), 'sha256': hashlib.sha256(data).hexdigest()}
    result = {'schema': 'uk-solar-snapshot-v1', 'source_commit': args.commit,
              'fetched_utc': datetime.now(timezone.utc).isoformat(), 'files': files,
              'source_provenance': 'sun-provenance.json',
              'grammar_commit': '1e8424f947399c67f61836c51393b6cb73995d5b',
              'grammar_sha256': '53a290e62c1f47b5d621899623b0c048a29d45d77d6f7464bfc757900eb79ecb'}
    (ROOT / 'data/provenance.json').write_text(json.dumps(result, indent=2)+'\n', encoding='utf-8', newline='\n')
    print(json.dumps({'pass': True, 'source_commit': args.commit, 'files': files}, indent=2))

if __name__ == '__main__':
    main()

Page Check

A JavaScript module in the proof folder of GlobalGrid2050.

renderglobalgrid2050 / testcode/202609151339/proof/page.check.mjs · lines 1–36 of 36 · version 2026-09-15 13:39 · Not reached from any entry point (candidate for review)

What it does
Uses libraries puppeteer-core. Side effects: changes the web page (DOM); starts processes.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
What it achieves
Drives the published page, not its library.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · testcode/202609151339/proof · JavaScript module
Uses
puppeteer-core
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
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609151339/proof/page.check.mjs:1-36 · blob 0a35913c12ea438e63989205d563fd4e39ccbe2a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, process · domain stage: experimental · users: none · canonical: unreached_review
/* Drives the published page, not its library. Written because the library
   proofs passed while the page threw on load. */
import puppeteer from 'puppeteer-core';
const CHROME = process.env.CHROME || '/usr/bin/google-chrome';
const B = process.env.WAFER_BASE || 'http://127.0.0.1:8899/testcode/202609151339/';
const b=await puppeteer.launch({executablePath:CHROME,headless:true,args:['--no-sandbox','--use-angle=d3d11','--use-gl=angle','--enable-gpu','--ignore-gpu-blocklist']});
const cases=[
 ['boot',            B,                       t=>/250,174 numbered lines/.test(t.count)],
 ['self 3 to 3',     B+'?line=3&to=3',        t=>/same line/i.test(t.panel) && !/Joined by/.test(t.panel)],
 ['join 3 to 4',     B+'?line=3&to=4',        t=>/Joined by/.test(t.panel) && /clampInteger/.test(t.panel) && /co-membership/i.test(t.panel)],
 ['bad to=',         B+'?line=3&to=banana',   t=>/Refused/i.test(t.panel) && /banana/.test(t.panel)],
 ['bad line=',       B+'?line=12abc',         t=>/Refused/i.test(t.panel)],
 ['huge line=',      B+'?line=1e308',         t=>/Refused/i.test(t.panel)],
 ['never issued',    B+'?line=342794&to=3',   t=>/never issued/i.test(t.panel)],
 ['focus 2',         B+'?line=2',             t=>/empty line/.test(t.panel) && /2,281|families/.test(t.panel)],
];
let pass=0, fail=[];
for(const [name,url,ok] of cases){
  const p=await b.newPage(); const errs=[];
  p.on('pageerror',e=>errs.push(String(e).slice(0,140)));
  await p.setViewport({width:430,height:900,deviceScaleFactor:2});
  await p.goto(url,{waitUntil:'load',timeout:60000});
  await new Promise(r=>setTimeout(r,7000));
  const t=await p.evaluate(()=>({
    count:document.getElementById('count').textContent,
    panel:(document.getElementById('panelbody').innerText||''),
    hidden:document.getElementById('panel').hidden,
    overflowX:document.documentElement.scrollWidth>window.innerWidth }));
  const good = errs.length===0 && !t.overflowX && ok(t);
  good?pass++:fail.push(`${name}: ${errs.length?'PAGE ERROR '+errs[0]:''}${t.overflowX?' overflowX':''} panel="${t.panel.replace(/\s+/g,' ').slice(0,110)}"`);
  console.log(`[${good?'PASS':'FAIL'}] ${name}`);
  await p.close();
}
await b.close();
if(fail.length){console.error('\nPAGE CHECK FAILED '+fail.length+' of '+cases.length+':\n- '+fail.join('\n- '));process.exit(1);}
console.log(`\npage check PASS — ${pass} cases in a 430px browser`);

Build All Lines

A JavaScript module in the testcode folder of GlobalGrid2050 that fetches lines meta, using SHA-256 from the stars repository.

storageglobalgrid2050 / testcode/202609152203/build_all_lines.mjs · lines 1–29 of 29 · version 2026-09-15 22:03 · Not reached from any entry point (candidate for review)

What it does
It fetches lines meta. Uses libraries node:crypto, node:path. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: data source: stars data. Out: JSON file all-lines.meta.json.
What it achieves
Every unique numbered line of the estate, from stars `LINES.md` (the modular star's own export).
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · testcode/202609152203 · JavaScript module
Uses
node:crypto, node:path
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
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609152203/build_all_lines.mjs:1-29 · blob ac2d1eb0d18e4074bb19f73eede1d73843db4d7b · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: experimental · users: none · canonical: unreached_review
// Every unique numbered line of the estate, from stars LINES.md (the modular star's own export).
// Output: all-lines.bin (Uint32 LE permanent numbers, ascending), all-lines.len.bin (Uint16 LE code length in bytes, capped 65535),
//         all-lines.meta.json (counts, min/max, sha256 + bytes of LINES.md, generated line from its header, family membership counts).
import { createHash } from 'node:crypto'; import { writeFileSync, readFileSync, existsSync } from 'node:fs';
import path from 'node:path'; import { fileURLToPath } from 'node:url';
// Copied into this stamp from the builder that made testcode/202609142202's all-lines pack; the only change is that it reads and
// writes ./data next to this file (the original wrote to its working directory and read lines.bin from the old stamp). Run after build_state.mjs.
const DATA = path.join(path.dirname(fileURLToPath(import.meta.url)), 'data');
const url = 'https://ventusltd.github.io/stars/LINES.md';
const buf = Buffer.from(await (await fetch(url)).arrayBuffer());
const sha = createHash('sha256').update(buf).digest('hex');
const text = buf.toString('utf8');
const header = text.slice(0, text.indexOf('```'));
const body = text.slice(text.indexOf('```text') + 7, text.lastIndexOf('```'));
const nums = [], lens = [];
for (const row of body.split('\n')) { const t = row.indexOf('\t'); if (t <= 0) continue; const n = Number(row.slice(0, t)); if (!Number.isInteger(n) || n <= 0) continue; nums.push(n); lens.push(Math.min(65535, Buffer.byteLength(row.slice(t + 1)))); }
const order = nums.map((n, i) => i).sort((a, b) => nums[a] - nums[b]);
const u32 = new Uint32Array(order.map(i => nums[i])), u16 = new Uint16Array(order.map(i => lens[i]));
// family membership from the Quantum Twin Star pack (which lines sit inside a function family)
const packLines = path.join(DATA, 'lines.bin');
let inFamily = null, famDistinct = 0;
if (existsSync(packLines)) { const fb = readFileSync(packLines); const fam = new Uint32Array(fb.buffer, fb.byteOffset, fb.length / 4); const set = new Set(fam); famDistinct = set.size; inFamily = new Uint8Array(u32.length); for (let i = 0; i < u32.length; i++) inFamily[i] = set.has(u32[i]) ? 1 : 0; }
writeFileSync(path.join(DATA, 'all-lines.bin'), Buffer.from(u32.buffer)); writeFileSync(path.join(DATA, 'all-lines.len.bin'), Buffer.from(u16.buffer)); if (inFamily) writeFileSync(path.join(DATA, 'all-lines.family.bin'), Buffer.from(inFamily.buffer));
const uniq = new Set(u32).size, dup = u32.length - uniq;
const meta = { schema: 'all-lines.v0', source: { url, bytes: buf.length, sha256: sha, header: header.trim().split('\n').slice(2, 3)[0]?.slice(0, 300) }, built_utc: new Date().toISOString(),
  lines: u32.length, distinct: uniq, duplicate_rows: dup, min: u32[0], max: u32[u32.length - 1], in_a_family: inFamily ? inFamily.reduce((s, v) => s + v, 0) : null, family_pack_distinct: famDistinct || null,
  files: { 'all-lines.bin': u32.length * 4, 'all-lines.len.bin': u16.length * 2, 'all-lines.family.bin': inFamily ? inFamily.length : 0 } };
writeFileSync(path.join(DATA, 'all-lines.meta.json'), JSON.stringify(meta, null, 1));
console.log(JSON.stringify(meta, null, 1));

Add All Lines

A JavaScript module in the proof folder of GlobalGrid2050 that reads lines meta and provenance, using SHA-256. It is built from the sha step (`sha`).

storageglobalgrid2050 / testcode/202609152203/proof/add_all_lines.mjs · lines 1–40 of 40 · version 2026-09-15 22:03 · Not reached from any entry point (candidate for review)

What it does
It loads lines meta and provenance. Defines sha. Uses libraries node:crypto, node:fs, node:path. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: JSON file all-lines.meta.json; JSON file provenance.json. Out: JSON file provenance.json.
What it achieves
Change: `build_all_lines.mjs` now writes straight into this stamp's `data/`, so SRC is `data/` itself (the copy step rewrites the same bytes) and paths are relative to this file. It reads `all-lines.meta.json` and writes `data/provenance.json`.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · testcode/202609152203/proof · JavaScript module
Uses
node:crypto, node:fs, node:path
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
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609152203/proof/add_all_lines.mjs:1-40 · blob 24c4b3122da2df2b27c8602fda9bed049521f28c · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: experimental · users: none · canonical: unreached_review
// Copied from testcode/202609142202/proof/add_all_lines.mjs. Change: build_all_lines.mjs now writes straight into this stamp's data/, so SRC is data/
// itself (the copy step rewrites the same bytes) and paths are relative to this file. Otherwise unchanged.
// Generation 2 data step: copy the all-lines pack (built by build_all_lines.mjs from the public LINES.md) into data/
// and record it in data/provenance.json (sources: LINES.md; outputs: the three binaries + meta; checks: the counts; amendments: this step).
// Nothing is computed from private data; every number written here is read from the files themselves or from all-lines.meta.json.
import { createHash } from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path'; import { fileURLToPath } from 'node:url';
const DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..').split(path.sep).join('/') + '/';
const SRC = DIR + 'data/';
const sha = b => createHash('sha256').update(b).digest('hex');
const meta = JSON.parse(fs.readFileSync(SRC + 'all-lines.meta.json', 'utf8'));
const files = ['all-lines.bin', 'all-lines.len.bin', 'all-lines.family.bin', 'all-lines.meta.json'];
const prov = JSON.parse(fs.readFileSync(DIR + 'data/provenance.json', 'utf8'));
const out = [];
for (const f of files) {
  const b = fs.readFileSync(SRC + f); fs.writeFileSync(DIR + 'data/' + f, b);
  const rec = { file: f, bytes: b.length, sha256: sha(b) };
  if (f !== 'all-lines.meta.json' && meta.files[f] !== b.length) throw new Error(`${f}: ${b.length} bytes on disk, meta says ${meta.files[f]}`);
  out.push(rec);
}
// counts re-derived from the copied binaries (not typed)
const u32 = new Uint32Array(fs.readFileSync(DIR + 'data/all-lines.bin').buffer.slice(0));
const fam = fs.readFileSync(DIR + 'data/all-lines.family.bin');
let asc = true; for (let i = 1; i < u32.length; i++) if (u32[i] <= u32[i - 1]) { asc = false; break; }
let inFam = 0; for (const v of fam) inFam += v;
const gen = /Generated (\d{4}-\d{2}-\d{2}T[\d:.]+Z)/.exec(meta.source.header || '');
if (!asc || u32.length !== meta.lines || inFam !== meta.in_a_family || u32[0] !== meta.min || u32[u32.length - 1] !== meta.max) throw new Error('all-lines binaries disagree with all-lines.meta.json');
prov.sources = prov.sources.filter(s => s.url !== meta.source.url);
prov.sources.push({ url: meta.source.url, bytes: meta.source.bytes, sha256: meta.source.sha256, fetched_utc: meta.built_utc, http_status: 200, attempts: 1, fetched_by: 'build_all_lines.mjs', header: meta.source.header });
prov.outputs = prov.outputs.filter(o => !files.includes(o.file)).concat(out);
Object.assign(prov.checks, {
  all_lines: u32.length, all_lines_distinct: meta.distinct, all_lines_duplicate_rows: meta.duplicate_rows, all_lines_min: u32[0], all_lines_max: u32[u32.length - 1],
  all_lines_in_a_family: inFam, all_lines_outside_families: u32.length - inFam, all_lines_ascending: asc,
  lines_md_generated_utc: gen ? gen[1] : null, lines_md_bytes: meta.source.bytes, lines_md_sha256: meta.source.sha256
});
prov.amendments = (prov.amendments || []).filter(a => a.script !== 'proof/add_all_lines.mjs');
prov.amendments.push({ utc: new Date().toISOString(), script: 'proof/add_all_lines.mjs', added: ['sources: LINES.md', 'outputs: all-lines.bin, all-lines.len.bin, all-lines.family.bin, all-lines.meta.json', 'checks.all_lines*', 'checks.lines_md_*'], source_added: meta.source.url, generation: 'generation 2' });
fs.writeFileSync(DIR + 'data/provenance.json', JSON.stringify(prov, null, 1));
console.log(JSON.stringify({ outputs: out, checks: { all_lines: u32.length, in_a_family: inFam, outside: u32.length - inFam, min: u32[0], max: u32[u32.length - 1], ascending: asc, lines_md_generated_utc: gen && gen[1] } }, null, 1));

Key Permanence

A JavaScript module in the proof folder of GlobalGrid2050 that reads lines meta, families and provenance.

storageglobalgrid2050 / testcode/202609152203/proof/key_permanence.mjs · lines 1–53 of 53 · version 2026-09-15 22:03 · Not reached from any entry point (candidate for review)

What it does
It loads lines meta, families and provenance. Defines u32, u16, load. Uses libraries node:fs, node:path, node:url. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. README: "`proof/key_permanence.mjs` → PASS: all 250,174 old keys are present, all 250,174 shared keys have the same length in `all-lines.len.bin`"
Inputs & outputs
In: JSON file all-lines.meta.json; JSON file families.json; JSON file provenance.json. Out: JSON file key_permanence.json.
What it achieves
It is built from the u32 step (`u32`), the u16 step (`u16`) and the load step (`load`). The permanent-key rule, checked between the previous numbered pack (`testcode/202609142202/data`) and this one (./data).
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · testcode/202609152203/proof · JavaScript module
Uses
node:fs, node:path, node:url
Used by
none found
Produces
u32, u16, load
Defines here
u32, u16, load
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609152203/proof/key_permanence.mjs:1-53 · blob b34d3700f55dcba92aa9468b45930d04f5c42d78 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: experimental · users: none · canonical: unreached_review
// key_permanence.mjs — the permanent-key rule, checked between the previous numbered pack (testcode/202609142202/data) and this one (./data).
// A line's number is its permanent key: it never changes and is never reused. So (1) every key in the old all-lines.bin must be in the new
// all-lines.bin, and (2) every key present in both must carry the same code length in all-lines.len.bin (a reused key would almost surely
// carry a different line). Also prints old vs new counts (lines, max key, families) and writes proof/key_permanence.json.
// Formats: all-lines.bin Uint32 LE ascending; all-lines.len.bin Uint16 LE, same order. Run from anywhere:  node proof/key_permanence.mjs
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const HERE = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const OLD = path.resolve(HERE, '..', '202609142202', 'data');
const NEW = path.join(HERE, 'data');
const u32 = (b) => new Uint32Array(b.buffer, b.byteOffset, b.length / 4);
const u16 = (b) => new Uint16Array(b.buffer, b.byteOffset, b.length / 2);
const load = (dir) => {
  const keys = u32(Buffer.from(fs.readFileSync(path.join(dir, 'all-lines.bin'))));
  const lens = u16(Buffer.from(fs.readFileSync(path.join(dir, 'all-lines.len.bin'))));
  const fam = fs.readFileSync(path.join(dir, 'all-lines.family.bin'));
  const meta = JSON.parse(fs.readFileSync(path.join(dir, 'all-lines.meta.json'), 'utf8'));
  const families = JSON.parse(fs.readFileSync(path.join(dir, 'families.json'), 'utf8'));
  const prov = JSON.parse(fs.readFileSync(path.join(dir, 'provenance.json'), 'utf8'));
  if (keys.length !== lens.length || keys.length !== fam.length) throw new Error(`${dir}: file lengths disagree`);
  for (let i = 1; i < keys.length; i++) if (keys[i] <= keys[i - 1]) throw new Error(`${dir}: all-lines.bin not strictly ascending at ${i}`);
  let inFam = 0; for (const v of fam) inFam += v;
  return { keys, lens, inFam, meta, families, prov };
};
const O = load(OLD), N = load(NEW);

// merge walk over two ascending arrays
let i = 0, j = 0, missing = 0, lenChanged = 0, added = 0, addedBelowOldMax = 0;
const missingEx = [], lenEx = [], addedBelowEx = [];
const oldMax = O.keys[O.keys.length - 1];
while (i < O.keys.length || j < N.keys.length) {
  const a = i < O.keys.length ? O.keys[i] : Infinity, b = j < N.keys.length ? N.keys[j] : Infinity;
  if (a === b) { if (O.lens[i] !== N.lens[j]) { lenChanged++; if (lenEx.length < 20) lenEx.push({ key: a, old_len: O.lens[i], new_len: N.lens[j] }); } i++; j++; }
  else if (a < b) { missing++; if (missingEx.length < 20) missingEx.push(a); i++; }
  else { added++; if (b <= oldMax) { addedBelowOldMax++; if (addedBelowEx.length < 20) addedBelowEx.push(b); } j++; }
}
const shared = O.keys.length - missing;
const R = {
  old_pack: 'testcode/202609142202/data', new_pack: path.basename(HERE) ? `testcode/${path.basename(HERE)}/data` : null,
  old: { lines: O.keys.length, max_key: oldMax, families: O.families.length, family_line_entries: O.prov.checks.lines_bin_entries, in_a_family: O.inFam, lines_md_generated_utc: O.prov.checks.lines_md_generated_utc, index_generated_utc: O.prov.checks.index_generated_utc },
  new: { lines: N.keys.length, max_key: N.keys[N.keys.length - 1], families: N.families.length, family_line_entries: N.prov.checks.lines_bin_entries, in_a_family: N.inFam, lines_md_generated_utc: N.prov.checks.lines_md_generated_utc, index_generated_utc: N.prov.checks.index_generated_utc },
  old_keys_missing_from_new: missing, missing_examples: missingEx,
  keys_in_both: shared, keys_in_both_with_different_length: lenChanged, length_change_examples: lenEx,
  keys_new_only: added, keys_new_only_at_or_below_old_max: addedBelowOldMax, new_only_below_old_max_examples: addedBelowEx,
  note: 'A new key at or below the old max is not a violation by itself (a number issued after the old export can be lower only if numbering is not monotone); it is reported, not failed.',
};
R.pass = missing === 0 && lenChanged === 0;
fs.writeFileSync(path.join(HERE, 'proof', 'key_permanence.json'), JSON.stringify(R, null, 1) + '\n');
console.log(JSON.stringify(R, null, 1));
console.log(R.pass ? 'PASS: every old key is present and every shared key has the same line length' : 'FAIL: permanent-key rule broken');
process.exit(R.pass ? 0 : 1);

Pack Check

A JavaScript module in the proof folder of GlobalGrid2050 that reads provenance, lines meta and families, using SHA-256. It is built from the sha step (`sha`).

storageglobalgrid2050 / testcode/202609152203/proof/pack_check.mjs · lines 1–58 of 58 · version 2026-09-15 22:03 · Not reached from any entry point (candidate for review)

What it does
It loads provenance, lines meta and families. Defines D, sha, ok. Uses libraries node:crypto, node:fs, node:path, node:url. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. README: "`proof/pack_check.mjs` → PASS: the no-browser checks of the previous stamp's proofs (provenance hashes match disk, binaries agree with meta, bucket distinct numbers = in-family unique lines = 149,457, index.json lines = LINES.md count, families tile lines.bin)."
Inputs & outputs
In: JSON file provenance.json; JSON file all-lines.meta.json; JSON file families.json. Out: JSON file pack_check.json.
What it achieves
The self-contained (no browser) parts of testcode/'s proofs, adapted to this stamp's `data/`. It reads `provenance.json`.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · testcode/202609152203/proof · JavaScript module
Uses
node:crypto, node:fs, node:path, node:url
Used by
none found
Produces
D, sha, ok
Defines here
D, sha, ok
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609152203/proof/pack_check.mjs:1-58 · blob f1acbd7e04f39fb8cc79e8c75bd6df3ef48d3b53 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: experimental · users: none · canonical: unreached_review
// pack_check.mjs — the self-contained (no browser) parts of testcode/202609142202's proofs, adapted to this stamp's data/.
// From proof/gen2.mjs "ground truth from disk": lines.bin entries, all-lines count, in/outside a family, the HUD count line rebuilt from disk.
// From the page's "prove it" button: sha256 of every data file equals data/provenance.json → outputs.
// From proof/add_all_lines.mjs: all-lines binaries agree with all-lines.meta.json (ascending, min, max, in_a_family).
// From README generation 2: distinct numbers in the buckets (lines.bin) == in-family unique lines; index.json lines == LINES.md count;
// every lines.bin number is a key of all-lines.bin. Also families.json offsets tile lines.bin exactly. Writes proof/pack_check.json.
import { createHash } from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const D = (f) => path.join(DIR, 'data', f);
const sha = (b) => createHash('sha256').update(b).digest('hex');
const R = { checks: {} };
const ok = (name, cond, detail) => { R.checks[name] = { pass: !!cond, ...(detail !== undefined ? { detail } : {}) }; };

const prov = JSON.parse(fs.readFileSync(D('provenance.json'), 'utf8'));
const meta = JSON.parse(fs.readFileSync(D('all-lines.meta.json'), 'utf8'));
const families = JSON.parse(fs.readFileSync(D('families.json'), 'utf8'));
const linesBuf = fs.readFileSync(D('lines.bin')), uniqBuf = fs.readFileSync(D('all-lines.bin')), famBuf = fs.readFileSync(D('all-lines.family.bin'));
const lines = new Uint32Array(linesBuf.buffer, linesBuf.byteOffset, linesBuf.length / 4);
const uniq = new Uint32Array(uniqBuf.buffer, uniqBuf.byteOffset, uniqBuf.length / 4);
let inFam = 0; for (const v of famBuf) inFam += v;

// prove it: provenance outputs vs disk
const provMismatch = prov.outputs.filter((o) => { const b = fs.readFileSync(D(o.file)); return b.length !== o.bytes || sha(b) !== o.sha256; }).map((o) => o.file);
ok('provenance_outputs_match_disk', provMismatch.length === 0 && prov.outputs.length === 10, { outputs: prov.outputs.length, mismatched: provMismatch });

// add_all_lines consistency
let asc = true; for (let i = 1; i < uniq.length; i++) if (uniq[i] <= uniq[i - 1]) { asc = false; break; }
ok('all_lines_agree_with_meta', asc && uniq.length === meta.lines && inFam === meta.in_a_family && uniq[0] === meta.min && uniq[uniq.length - 1] === meta.max,
  { lines: uniq.length, ascending: asc, min: uniq[0], max: uniq[uniq.length - 1], in_a_family: inFam });

// gen2 README claims
const distinct = new Set(lines);
ok('bucket_distinct_equals_in_family_unique', distinct.size === inFam, { bucket_distinct: distinct.size, in_a_family: inFam });
ok('index_lines_equals_lines_md', prov.checks.index_lines === uniq.length, { index_lines: prov.checks.index_lines, lines_md: uniq.length });
const uniqSet = new Set(uniq); let notKey = 0; for (const x of distinct) if (!uniqSet.has(x)) notKey++;
ok('every_family_line_is_a_lines_md_key', notKey === 0, { not_a_key: notKey });
let flagWrong = 0; for (let i = 0; i < uniq.length; i++) if ((famBuf[i] === 1) !== distinct.has(uniq[i])) flagWrong++;
ok('family_flag_matches_lines_bin', flagWrong === 0, { wrong: flagWrong });

// families.json tiles lines.bin
let off = 0, tile = true; for (const f of families) { if (f.lineOffset !== off) { tile = false; break; } off += f.lineCount; }
ok('families_tile_lines_bin', tile && off === lines.length && families.length === prov.checks.index_families, { families: families.length, entries: lines.length });

// gen2 HUD count line, rebuilt from disk (as proof/gen2.mjs computes it)
const stamp = prov.checks.lines_md_generated_utc; const stampText = `${stamp.slice(0, 10)} ${stamp.slice(11, 16)} UTC`;
R.expected_count_line = `on GPU: ${uniq.length.toLocaleString('en-GB')} unique numbered lines (LINES.md ${stampText}) + ${(lines.length).toLocaleString('en-GB')} family-line entries · ${inFam.toLocaleString('en-GB')} unique lines sit inside a function family, ${(uniq.length - inFam).toLocaleString('en-GB')} do not`;

// family numbers of the previous pack (reported, not failed: family records are regrouped by the modular star)
const prevF = path.resolve(DIR, '..', '202609142202', 'data', 'families.json');
if (fs.existsSync(prevF)) { const nowN = new Set(families.map((f) => f.n)); const old = JSON.parse(fs.readFileSync(prevF, 'utf8')); R.previous_family_numbers = { old: old.length, still_present: old.filter((f) => nowN.has(f.n)).length }; }

R.pass = Object.values(R.checks).every((c) => c.pass);
fs.writeFileSync(path.join(DIR, 'proof', 'pack_check.json'), JSON.stringify(R, null, 1) + '\n');
console.log(JSON.stringify(R, null, 1));
process.exit(R.pass ? 0 : 1);

Build

A JavaScript module in the testcode folder of GlobalGrid2050 that reads surfaces and laws. It reads stamp (`readStamp`), reads title (`readTitle`) and reads law (`readLaw`).

storageglobalgrid2050 / testcode/202609160224/build.mjs · lines 1–292 of 292 · version 2026-09-16 02:24 · Not reached from any entry point (candidate for review)

What it does
It loads surfaces and laws. Defines 7 functions or classes, including readStamp, readTitle, readLaw, walk, readStarIndex. Uses libraries node:fs, node:path, node:child_process. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: JSON file index.json. Out: JSON file surfaces.json; JSON file laws-index.json.
What it achieves
The nest's manifest, generated from the directory, never typed.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · testcode/202609160224 · JavaScript module
Uses
node:fs, node:path, node:child_process
Used by
none found
Produces
readStamp, readTitle, readLaw, walk, readStarIndex, readTracked, esc
Defines here
readStamp, readTitle, readLaw, walk, readStarIndex, readTracked, esc
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609160224/build.mjs:1-292 · blob bbd891c4297ba636a58946ed2986ad1a90bdb252 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: experimental · users: none · canonical: unreached_review
/* build.mjs — the nest's manifest, generated from the directory, never typed.
 *
 * WHY THIS EXISTS. The old front door at testcode/index.html was 184 bytes and
 * named two surfaces out of ninety-six, the newest of them eleven days old. It
 * was hand-typed, so it went stale the moment the next surface landed. Every
 * stale map in this estate has the same cause: an artefact generated by a run,
 * and no run triggered by publication. This file is the run. It reads the
 * directory it sits beside and writes what is actually there.
 *
 * WHAT IT EMITS. surfaces.json: one record per timestamped surface directory,
 * carrying its key, its title read from its own README or <title>, the files it
 * holds and the bytes they weigh. Nothing is invented; a surface with no README
 * and no title says so rather than being given a name.
 *
 * Run: node build.mjs   (from this directory)
 */
import fs from 'node:fs';
import path from 'node:path';
import { execFileSync } from 'node:child_process';

const HERE = path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1'));
const ROOT = path.resolve(HERE, '..');            /* testcode/ */
const TS = /^(\d{12}|\d{10}|\d{14})$/;            /* the estate's three stamp widths */

/* A stamp is YYYYMMDDHHMM, sometimes YYYYMMDDHHMMSS, sometimes YYYYMMDDHH.
   Read only what is certainly there: the date, and the time when present. */
function readStamp(name) {
  const y = name.slice(0, 4), m = name.slice(4, 6), d = name.slice(6, 8);
  const hh = name.slice(8, 10) || null, mm = name.slice(10, 12) || null;
  return { date: `${y}-${m}-${d}`, time: hh && mm ? `${hh}:${mm}` : null };
}

/* The surface's own name for itself, in order of authority: the first heading of
   its README, then the <title> of its index.html, then nothing. Never a guess. */
function readTitle(dir) {
  const rd = path.join(dir, 'README.md');
  if (fs.existsSync(rd)) {
    const h = fs.readFileSync(rd, 'utf8').split(/\r?\n/).find(l => l.startsWith('# '));
    if (h) return { title: h.replace(/^#\s*/, '').trim(), from: 'README.md' };
  }
  const ix = path.join(dir, 'index.html');
  if (fs.existsSync(ix)) {
    const m = fs.readFileSync(ix, 'utf8').match(/<title>([^<]+)<\/title>/i);
    if (m) return { title: m[1].trim(), from: 'index.html' };
  }
  return { title: null, from: null };
}

/* THE LAW OF A SURFACE, read from the surface rather than assigned.
 *
 * The 22 generated variations are islands: each has exactly one href, its own
 * stylesheet. A visitor arriving at Density from the homepage can look at it and
 * then has nowhere to go — 22 dead ends, against Vikram's rule that the universe
 * is endless and there are none.
 *
 * They differ only by law, over the same pack, so the natural way out of any one of
 * them is the same lines under a different law. That needs an index, and the index
 * must be GENERATED from the surfaces or it goes stale the moment a law is renamed —
 * which six of them were, hours ago. So read each surface's declared law out of its
 * own source and emit the map. Both this surface and the generator's template can
 * consume it; neither has to hold a list. */
function readLaw(dir) {
  const f = path.join(dir, 'wafer.mjs');
  if (!fs.existsSync(f)) return null;
  const src = fs.readFileSync(f, 'utf8');
  const m = /law[:=]\s*['"]([a-z][a-z0-9-]*)['"]/i.exec(src)
    || /the ([a-z][a-z0-9-]*) law, generated/i.exec(src);
  return m ? m[1] : null;
}

function walk(dir) {
  let files = 0, bytes = 0;
  for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
    if (e.name === 'node_modules' || e.name === '.git') continue;
    const p = path.join(dir, e.name);
    if (e.isDirectory()) { const s = walk(p); files += s.files; bytes += s.bytes; }
    else { files++; bytes += fs.statSync(p).size; }
  }
  return { files, bytes };
}

/* THE ZOOM DOWN: which numbered code each surface actually carries.
 *
 * The published star index records, per function family, every place it lives as
 * (repo, commit, path, first, last). 25,600 of its 89,145 places sit under a
 * testcode/<stamp>/ directory, so the join from a surface to its families already
 * exists and does not need building - only reading. This is the die-to-block step:
 * the Nest draws surfaces, and each surface now knows how many families of numbered
 * code are recorded inside it.
 *
 * READ HONESTLY. The star index is generated by a run, and no run is triggered by
 * publication, so it is always behind the newest surfaces. A surface with 0
 * families is NOT a surface with no code - it is one the index has not reached.
 * The manifest therefore carries the index's own generated_utc next to the counts,
 * and the page says "not yet indexed" rather than "none". Making the frontier gap
 * visible in the product beats hiding it behind a zero.
 */
function readStarIndex() {
  const dir = path.resolve(ROOT, '..', '..', 'stars', 'code', 'f');
  if (!fs.existsSync(dir)) return null;
  const idxPath = path.resolve(ROOT, '..', '..', 'stars', 'code', 'index.json');
  const idx = fs.existsSync(idxPath) ? JSON.parse(fs.readFileSync(idxPath, 'utf8')) : {};
  const byStamp = new Map();                  /* stamp -> {families:Set, places:int} */
  for (const f of fs.readdirSync(dir)) {
    if (!f.endsWith('.json')) continue;
    const bucket = JSON.parse(fs.readFileSync(path.join(dir, f), 'utf8'));
    for (const rec of Object.values(bucket)) {
      for (const pl of rec.places || []) {
        const m = /testcode\/(\d{10,14})\//.exec(pl.path || '');
        if (!m) continue;
        let e = byStamp.get(m[1]);
        if (!e) { e = { families: new Set(), places: 0 }; byStamp.set(m[1], e); }
        e.families.add(rec.n);
        e.places++;
      }
    }
  }
  return { byStamp, generated_utc: idx.generated_utc || null, families_in_index: idx.families || null };
}

const stars = readStarIndex();

/* WHICH SURFACES A READER CAN ACTUALLY REACH.
 *
 * This manifest's guarantee was "generated from the directory rather than typed, so it
 * cannot name a surface that is not there or omit one that is". That is true and it is
 * scoped to the wrong space: "there" means ON DISK, and the reader's "there" means ON
 * THE SITE. Tonight those differed — vikra-ac's live sweep found 25 of 122 surfaces
 * unreachable, and five that existed on one machine's disk and nowhere else.
 *
 * It is the night's single cause applied to this file: every proof runs where the code
 * lives, not where the reader stands. A surface present but untracked is published
 * nowhere, and a front door that offers it is advertising a room in one building only.
 * So ask git, once, and record it. This still does not prove the surface is SERVED —
 * only the reader's proof fetching published URLs can do that — but it closes the gap
 * between "on this disk" and "in the repository", which is the half this file can know. */
function readTracked() {
  try {
    const out = execFileSync('git', ['ls-files', '--', '.'], { cwd: ROOT, encoding: 'utf8' });
    const dirs = new Set();
    for (const line of out.split(String.fromCharCode(10))) {
      const m = /^([0-9]{10,14})\//.exec(line.trim());
      if (m) dirs.add(m[1]);
    }
    return dirs;
  } catch {
    return null;        /* not a git checkout: record unknown rather than guess false */
  }
}
const tracked = readTracked();

const names = fs.readdirSync(ROOT, { withFileTypes: true })
  .filter(e => e.isDirectory() && TS.test(e.name))
  .map(e => e.name)
  .sort();

const surfaces = names.map((name, i) => {
  const dir = path.join(ROOT, name);
  const { title, from } = readTitle(dir);
  const { files, bytes } = walk(dir);
  return {
    key: i + 1,                 /* the nest's own ordinal: 1..n, in issue order */
    stamp: name,
    ...readStamp(name),
    title, title_from: from,
    files, bytes,
    has_readme: fs.existsSync(path.join(dir, 'README.md')),
    has_proof: fs.existsSync(path.join(dir, 'proof')),
    /* null = no star index available at build time; 0 = indexed and genuinely empty
       is indistinguishable from not-yet-reached, so the page says "not yet indexed". */
    families: stars ? (stars.byStamp.get(name)?.families.size ?? 0) : null,
    places: stars ? (stars.byStamp.get(name)?.places ?? 0) : null,
    entry: fs.existsSync(path.join(dir, 'index.html')) ? `${name}/` : null,
    /* null = could not ask git. false = on this disk and in no repository, so no
       reader will ever reach it however valid it is. */
    published: tracked ? tracked.has(name) : null,
    /* A DIRECTORY IS NOT A SURFACE. This manifest is generated from a directory
       listing, which is why it cannot omit a surface that exists — and equally why
       it could not tell a surface from a folder. testcode/202609151500 holds one
       file, layers.mjs, and no index.html: it is committed, it is served, and it
       404s, because there is nothing there to serve. Vikram reported that 404 hours
       ago and it was never a deploy problem.
       CLASSIFY, DON'T EXCLUDE — the estate's own rule, and it applies to itself. The
       folder stays in the record; it simply stops being counted as a surface. */
    kind: fs.existsSync(path.join(dir, 'index.html')) ? 'surface' : 'fragment',
    law: readLaw(dir),
  };
});

const out = {
  generated_utc: new Date().toISOString(),
  built_from: 'globalgrid2050/testcode',
  /* Counted honestly: a fragment is present and named, and is not a surface. */
  surfaces: surfaces.filter(s => s.kind === 'surface').length,
  fragments: surfaces.filter(s => s.kind === 'fragment').map(s => s.stamp),
  listed: surfaces.length,
  named: surfaces.filter(s => s.title).length,
  openable: surfaces.filter(s => s.entry).length,
  total_files: surfaces.reduce((a, s) => a + s.files, 0),
  total_bytes: surfaces.reduce((a, s) => a + s.bytes, 0),
  law: 'r = sqrt(key) · theta = key × 2.39996…  (the golden angle)',
  /* law -> the stamps that draw it, so any surface can offer the others. */
  laws: Object.fromEntries(
    [...new Set(surfaces.map(s => s.law).filter(Boolean))].sort()
      .map(l => [l, surfaces.filter(s => s.law === l && s.entry).map(s => s.stamp)])),
  unpublished: tracked ? surfaces.filter(s => s.published === false).map(s => s.stamp) : null,
  star_index: stars
    ? { generated_utc: stars.generated_utc, families_in_index: stars.families_in_index,
        surfaces_reached: surfaces.filter(x => x.families > 0).length }
    : null,
  list: surfaces,
};

fs.writeFileSync(path.join(HERE, 'surfaces.json'), JSON.stringify(out, null, 1));

/* A SMALL FILE FOR A SMALL QUESTION. surfaces.json is 122 records wide; a page that
   only wants "what other laws exist" should not pay for the whole manifest. Emitted
   from the same pass, so it cannot disagree with it. */
const lawIndex = {
  generated_utc: out.generated_utc,
  note: "law -> the surfaces that draw it. Read from each surface's own source, never typed.",
  laws: Object.entries(out.laws).map(([id, stamps]) => ({
    id,
    stamps,
    open: stamps[0] || null,
    title: (surfaces.find((s) => s.stamp === stamps[0]) || {}).title || null,
  })),
};
fs.writeFileSync(path.join(HERE, 'laws-index.json'), JSON.stringify(lawIndex, null, 1));

/* THE FRONT DOOR, GENERATED — because the chair replaced a hand-typed one with a
   hand-typed one and did not notice for five hours.
 *
 * testcode/index.html was 184 bytes naming two surfaces of ninety-six, the newest
 * eleven days stale. The Nest fixed that by generating its manifest from the
 * directory. The front door that LINKS to the Nest was then written by hand, and by
 * 06:50 it claimed "ninety-seven" surfaces when there were 119, named a "most recent"
 * list 22 surfaces out of date, and linked 202609151500 — a FRAGMENT with no
 * index.html, which the manifest had been correctly classifying as unopenable for
 * hours while the front door offered it as a link.
 *
 * Same defect, same file, by the seat that wrote the fix. So the front door is emitted
 * from the manifest and cannot disagree with it. No JavaScript: it is the plain-text
 * fallback, and a fallback that needs the thing it is a fallback for is not one. */
{
  const openable = surfaces.filter((s) => s.kind === 'surface' && s.entry);
  const recent = openable.slice(-6).reverse();
  const esc = (t) => String(t).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  const rows = recent.map((s) =>
    '<li><a href="' + s.stamp + '/">' + s.stamp + '</a>' +
    (s.title ? ' <span class="dim">— ' + esc(s.title.replace(/^CPU Wafer Galaxy - /, '')) + '</span>' : '') +
    '</li>').join(String.fromCharCode(10) + ' ');
  const doc = [
    '<!doctype html>',
    '<meta charset="utf-8">',
    '<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">',
    '<meta name="color-scheme" content="dark">',
    '<title>Test Code — the nest</title>',
    '<!-- GENERATED by testcode/202609160224/build.mjs. Do not hand-edit: the previous',
    '     two versions of this file were typed, and both went stale. -->',
    '<style>',
    ' body{margin:0;background:#0b0d12;color:#d8dee9;font:14px/1.6 ui-monospace,Menlo,Consolas,monospace;padding:2rem 1rem;max-width:44rem;margin-inline:auto}',
    ' h1{font-size:15px;letter-spacing:.14em;margin:0 0 .3rem}',
    ' .dim{color:#8b93a7} a{color:#5ec8f2}',
    ' .go{display:inline-block;margin:1.2rem 0;padding:.45rem 1rem;border:1px solid #5ec8f2;border-radius:.2rem;text-decoration:none}',
    ' ul{padding-left:1.1rem;margin:.6rem 0 0} li{margin:.15rem 0}',
    '</style>',
    '<h1>TEST CODE</h1>',
    '<p class="dim">' + openable.length + ' surfaces the estate has published, each one a page. ' +
      'This list is generated from the directory, so it cannot name a surface that is not ' +
      'there or omit one that is.</p>',
    '<a class="go" href="202609160224/">OPEN THE NEST &rarr;</a>',
    '<p class="dim">Most recent:</p>',
    '<ul>',
    ' ' + rows,
    '</ul>',
    '<p class="dim">' + surfaces.filter((s) => s.kind === 'fragment').length +
      ' directories hold code but no page, so they are listed in the nest and not linked here. ' +
      'Generated ' + out.generated_utc + '.</p>',
    '',
  ].join(String.fromCharCode(10));
  fs.writeFileSync(path.join(ROOT, 'index.html'), doc);
}
const unpub = out.unpublished || [];
if (unpub.length) console.log(`UNPUBLISHED (on disk, in no repository): ${unpub.join(', ')}`);
if (out.fragments.length) console.log(`FRAGMENTS (a directory, not a surface — no index.html): ${out.fragments.join(', ')}`);
console.log(`surfaces ${out.surfaces} · named ${out.named} · openable ${out.openable} · files ${out.total_files} · ${(out.total_bytes / 1048576).toFixed(1)} MB`);
if (out.star_index) {
  console.log(`star index ${out.star_index.generated_utc} · ${out.star_index.surfaces_reached}/${out.surfaces} surfaces reached · the rest are newer than the index`);
} else {
  console.log('star index not present at build time; families recorded as null');
}