In this section
- Layout Command render · globalgrid2050 / testcode/202609051850/teleprinter/layout-command.js lines 1–24
- Session Restart render · globalgrid2050 / testcode/202609052015/tool-layers/session-restart.js lines 1–23
- Teleprinter Bootstrap render · globalgrid2050 / testcode/202609052023/teleprinter-bootstrap.js lines 1–11
- Test VEDIC Entry test · globalgrid2050-homepage / tests/test_vedic_entry.py lines 1–30
- Claude Analyse Corpus GPU storage · gpu-drivers-for-global-grid / claude/analyse-corpus-gpu.mjs lines 1–343
- Claude Bench Cpu Ram ingest · gpu-drivers-for-global-grid / claude/bench-cpu-ram.mjs lines 1–162
Layout Command
A JavaScript module in the teleprinter folder of GlobalGrid2050 that works with selected layout control (`selectedLayoutControl`).
renderglobalgrid2050 / testcode/202609051850/teleprinter/layout-command.js · lines 1–24 of 24 · version 2026-09-05 18:50 · Not reached from any entry point (candidate for review)
- What it does
- It draws its content. Defines selectedLayoutControl, mountLayoutCommand. Side effects: changes the web page (DOM).
- 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.
- Downstream impact
- Used directly by 2 files: Teleprinter Bootstrap (globalgrid2050); Codex Layout Command Test (teleprinter).
- What it achieves
- It is built from the selected layout control helper (`selectedLayoutControl`) and the mount layout command helper (`mountLayoutCommand`). Separate Layout entry point. Reuses the selected project's existing layout command. It responds to click events.
- Why it matters
- Imported by Teleprinter Bootstrap. Checked by Codex Layout Command Test.
- Application
- globalgrid2050 · testcode/202609051850/teleprinter · JavaScript module
- Uses
- none found
- Used by
- imported by Teleprinter Bootstrap (import), imported by Codex Layout Command Test (import)
- Produces
- selectedLayoutControl, mountLayoutCommand
- Defines here
- selectedLayoutControl, mountLayoutCommand
- 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/202609051850/teleprinter/layout-command.js:1-24 · blob 8297f6abefe55aa3e993ef0a74b495ff0d633861 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: unreached_review
/** Separate Layout entry point. Reuses the selected project's existing layout command. */
export function selectedLayoutControl(doc = document) {
return [...doc.querySelectorAll('.neon-layout')].find(control => control.isConnected && !control.disabled) || null;
}
export function mountLayoutCommand(doc = document) {
const root = doc.getElementById('map-container');
if (!root || doc.getElementById('codex-layout-command')) return () => {};
const wrapper = doc.createElement('div'); wrapper.id = 'codex-layout-command';
const button = doc.createElement('button'); button.type = 'button'; button.textContent = '▦ Layout';
button.title = 'Open the selected project’s layout';
const status = doc.createElement('span'); status.setAttribute('role','status');
const style = doc.createElement('style');
style.textContent = '#codex-layout-command{position:absolute;right:12px;top:68px;z-index:1001;display:flex;align-items:flex-end;flex-direction:column;gap:4px;max-width:230px}#codex-layout-command button{min-height:44px;padding:8px 14px;color:#d9f5ff;background:#11252eee;border:1px solid #56838c;border-radius:3px;font:12px monospace;cursor:pointer}#codex-layout-command span:not(:empty){padding:6p … [line shortened here: 459 characters; full line on GitHub]
button.addEventListener('click', event => {
event.stopPropagation();
const command = selectedLayoutControl(doc);
if (!command) { status.textContent = 'Select a project with a nearby grid connection to open its layout.'; return; }
status.textContent = '';
command.click();
});
wrapper.addEventListener('click',event=>event.stopPropagation());
wrapper.append(button,status); root.append(style,wrapper);
return () => { wrapper.remove(); style.remove(); };
}Session Restart
A JavaScript module in the tool layers folder of GlobalGrid2050 that works with request confirmation (`requestConfirmation`) and cancel restart (`cancelRestart`).
renderglobalgrid2050 / testcode/202609052015/tool-layers/session-restart.js · lines 1–23 of 23 · version 2026-09-05 20:15 · pattern activate (shared by 9 files)
- What it does
- It draws its content. Defines mountSessionRestart, reset, requestConfirmation, activate, cancelRestart. Side effects: changes the web page (DOM).
- 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.
- Downstream impact
- Used directly by 2 files: Session Restart Test (testcode); Host (globalgrid2050). Reached from 3 other entry points, including Codex Cartridges Workflow (testcode); Controls Layout Workflow (testcode); Offshore Route Workflow (testcode).
- What it achieves
- It is built from the mount session restart helper (`mountSessionRestart`), the reset step (`reset`) and the request confirmation helper (`requestConfirmation`). Restart only this iframe after an explicit two-step user action. It responds to click and tool events.
- Why it matters
- Imported by Host. Checked by Session Restart Test.
- Application
- globalgrid2050 · testcode/202609052015/tool-layers · JavaScript module
- Uses
- none found
- Used by
- imported by Session Restart Test (import), imported by Host (import)
- Produces
- mountSessionRestart
- Defines here
- mountSessionRestart, reset, requestConfirmation, activate, cancelRestart
- 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/202609052015/tool-layers/session-restart.js:1-23 · blob aaaddefbf05ac44fe43ee9c722dc0aa49449d9ba · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: production_core
/** Restart only this iframe after an explicit two-step user action. */
export function mountSessionRestart(layer, bar, frame, entry) {
const doc=bar.ownerDocument, row=doc.createElement('div');
row.dataset.toolSessionActions='';Object.assign(row.style,{gridColumn:'1 / -1',display:'flex',gap:'8px',alignItems:'center',flexWrap:'wrap'});
const restart=doc.createElement('button'), cancel=doc.createElement('button'), note=doc.createElement('span');
restart.textContent='Restart tool';cancel.textContent='Keep working';cancel.hidden=true;note.setAttribute('role','status');
for(const button of [restart,cancel])Object.assign(button.style,{minHeight:'44px',cursor:'pointer'});
let armed=false;
const reset=()=>{armed=false;restart.textContent='Restart tool';cancel.hidden=true;note.textContent='';};
const requestConfirmation=()=>{armed=true;restart.textContent='Confirm restart';cancel.hidden=false;note.textContent='Unsaved work in this tool will be lost. Other tools stay open.';restart.focus();};
const activate=()=>{
if(!armed){requestConfirmation();return;}
const target=typeof entry==='function'?entry():entry;
reset();if(!target){note.textContent='This linked page cannot be restarted here.';return;}
frame.dispatchEvent(new Event('tool-navigation-start'));frame.src=target;
};
restart.addEventListener('click',activate);
const cancelRestart=()=>{reset();restart.focus();};
cancel.addEventListener('click',cancelRestart);
layer.addEventListener('tool-layer-dismissed',reset);layer.addEventListener('tool-document-changed',reset);
row.append(restart,cancel,note);bar.append(row);
return {requestConfirmation,dispose:()=>{restart.removeEventListener('click',activate);cancel.removeEventListener('click',cancelRestart);layer.removeEventListener('tool-layer-dismissed',reset);layer.removeEventListener('tool-document-changed',reset);row.remove();}};
}Teleprinter Bootstrap
A JavaScript module in the testcode folder of GlobalGrid2050 that draws landing pin and landing code.
renderglobalgrid2050 / testcode/202609052023/teleprinter-bootstrap.js · lines 1–11 of 11 · version 2026-09-05 20:23 · Not reached from any entry point (candidate for review)
- What it does
- It draws landing pin and landing code. Side effects: changes the web page (DOM); 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 landing-source-pin.json; JSON file landing-source-code.manifest.json.
- What it achieves
- No statement of purpose was found in the file, a README line naming it, or its name.
- Why it matters
- No other file in the estate was found to import it.
- Application
- globalgrid2050 · testcode/202609052023 · JavaScript module
- Uses
- Controls (import)
- 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/202609052023/teleprinter-bootstrap.js:1-11 · blob 8dc388d280a85d72975880ac4eeed1109f45f4b7 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: experimental · users: none · canonical: unreached_review
import { mountTeleprinter } from './teleprinter/controls.js';
const base = new URL('./teleprinter/', import.meta.url);
try {
const response = await fetch(new URL('landing-source-pin.json', base), { cache: 'no-store', credentials: 'same-origin', redirect: 'error' });
if (!response.ok) throw new Error('Source code is still being prepared.');
const pin = await response.json();
if (pin.generation !== '202609052023' || pin.app !== 'landing' || !/^[a-f0-9]{40}$/.test(pin.commit) || pin.repository !== 'https://github.com/Ventusltd/testcode') throw new Error('The source code version could not be checked.');
mountTeleprinter({ printButtons: undefined, appName: "Test Code", manifestUrl: new URL('landing-source-code.manifest.json', base), textUrl: new URL('landing-source-code.txt', base), expectedCommit: pin.commit, expectedRepository: pin.repository });
} catch (error) {
const note = document.createElement('p'); note.setAttribute('role', 'status'); note.textContent = 'Print options: ' + error.message; document.body.append(note);
}Test VEDIC Entry
A test in the tests folder of GlobalGrid2050 Homepage that checks VEDIC — Index Page using data from the vedic- repository.
testglobalgrid2050-homepage / tests/test_vedic_entry.py · lines 1–30 of 30 · Entry point
- What it does
- It tests its inputs. Defines VedicEntryTests, test_vedic_section. Uses libraries json, unittest, pathlib. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage agent_infra (path word 'vedic'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: data source: vedic- data; JSON file homepage.json; JSON file entity-types.json.
- Downstream impact
- Used directly by 3 files: Build Homepage Release Candidate Workflow (globalgrid2050-homepage); Pages Workflow (globalgrid2050-homepage); PR Checks Workflow (globalgrid2050-homepage).
- What it achieves
- It is built from the vedic entry tests class (`VedicEntryTests`). Defines `VedicEntryTests` and `test_vedic_section`.
- Why it matters
- Run by Build Homepage Release Candidate Workflow, Pages Workflow and PR Checks Workflow.
- Application
- globalgrid2050-homepage · tests · test
- Uses
- VEDIC — Index Page (estate URL), json, unittest, pathlib
- Used by
- run by Build Homepage Release Candidate Workflow (workflow run), run by Pages Workflow (workflow run), run by PR Checks Workflow (workflow run)
- Produces
- VedicEntryTests
- Defines here
- VedicEntryTests, test_vedic_section
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050-homepage@551a7625b02ddb7b3e6e0181cc643b8114c7fc06 tests/test_vedic_entry.py:1-30 · blob 1065403a878eb83c629757849019c5d4d8bfb9d4 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
import json
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
class VedicEntryTests(unittest.TestCase):
def test_vedic_section(self):
d = json.loads((ROOT/"data/homepage.json").read_text())
m = json.loads((ROOT/"data/entity-types.json").read_text())
h = (ROOT/"index.html").read_text()
e = [e for e in d["entities"] if e["id"] == "vedic"]
self.assertEqual(len(e),1)
self.assertEqual(d["view"]["items"][10], {"entity_id":"vedic","open":False})
releases = {r["id"]: r for r in e[0]["releases"]}
self.assertEqual(len(releases), len(e[0]["releases"]))
self.assertEqual(releases["v1"]["url"],"https://ventusltd.github.io/vedic-/")
self.assertEqual(releases["v1"]["archive_url"],"https://ventusltd.github.io/vedic-/releases/202611260135-v1/")
self.assertEqual(releases["v1"]["archive_kind"],"app")
v2 = releases["202611261351"]
self.assertEqual(v2["url"],"https://ventusltd.github.io/vedic-/releases/202611261351/")
self.assertEqual(v2["source_ref"],"https://github.com/Ventusltd/vedic-/tree/55ff568b378acff4adae02fb5c758b4f4f8c6bcd")
self.assertEqual(v2["status"],"available")
promotions = [p for p in d["promotions"] if p["entity_id"] == "vedic"]
self.assertEqual((promotions[0]["from_release_id"], promotions[0]["to_release_id"]),("v1","202611261351"))
self.assertEqual(promotions[-1]["to_release_id"],e[0]["operative_release_id"])
operative = releases[e[0]["operative_release_id"]]
self.assertEqual(operative["status"],"available")
self.assertEqual(m["records"]["vedic"]["type"],"catalogue")
self.assertEqual(h.count('<details id="vedic">'),1)
self.assertIn(f'href="{operative["url"]}">Open VEDIC',h)
self.assertIn('id="satnav-concept"',h)Claude Analyse Corpus GPU
A JavaScript module in GPU Drivers for Global Grid that fetches corpus GPU analysis, using SHA-256.
storagegpu-drivers-for-global-grid / claude/analyse-corpus-gpu.mjs · lines 1–343 of 343 · Entry point · pattern collect (shared by 23 files)
- What it does
- It fetches corpus GPU analysis. Defines resolveRoot, collect, read. Uses libraries node:fs, node:crypto, node:url, node:path, node:os. Side effects: reads or writes files; makes network requests; starts processes.
- Why it exists in the grid workflow
- Domain stage agent_infra (path word 'claude'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). README: "The script demonstrates its own caveat when run on its fallback corpus, the `claude/` directory itself: `analyse-corpus-gpu.mjs` and `bench-gpu.mjs` score 0.99224 against each other."
- Inputs & outputs
- In: JSON file corpus-gpu-analysis.json; command-line arguments. Out: JSON file corpus-gpu-analysis.json; WebGL/WebGPU drawing.
- Downstream impact
- Used directly by 1 file: Claude Bench Workflow (gpu-drivers-for-global-grid).
- What it achieves
- It resolves root (`resolveRoot`) and is built from the collect step (`collect`) and the read step (`read`). This asks a question whose answer changes what ships.
- Why it matters
- Run by Claude Bench Workflow.
- Application
- gpu-drivers-for-global-grid · claude · JavaScript module
- Uses
- node:fs, node:crypto, node:url, node:path, node:os, playwright
- Used by
- run by Claude Bench Workflow (workflow run)
- Produces
- resolveRoot, collect, read
- Defines here
- resolveRoot, collect, read
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gpu-drivers-for-global-grid@6c47912a8dde251ffebd92ff129e6a0c11c4ebfe claude/analyse-corpus-gpu.mjs:1-343 · blob 03f9f0c914afad776654d71c88f2eb2dd62cf1cb · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
/**
* WHAT IS ACTUALLY IN THE SERVED PAYLOAD — ANALYSED ON THE GPU.
* ---------------------------------------------------------------------------
* Not a benchmark. This asks a question whose answer changes what ships:
*
* HOW MUCH OF THE CORPUS THE CLIENT DOWNLOADS IS THE SAME CODE AGAIN?
*
* GridAtlas keeps every generation of every cartridge, which is the right rule
* for provenance -- a pinned generation must stay byte-identical forever. But
* it means the directory the world can reach holds many near-copies, and on an
* ARM phone the thing that matters is bytes over the wire. Knowing WHICH files
* are near-duplicates of each other, and how near, is what lets a release drop
* payload without breaking the immutability rule.
*
* ALL THE ANALYSIS RUNS ON THE GPU. Two compute passes, no CPU fallback in the
* measurement path:
*
* pass 1 per-file 256-bin byte histogram. One workgroup per file, a
* grid-stride loop over that file's byte range, 256 atomic bins in
* workgroup memory so the hot atomics stay on-chip, one global write
* per bin at the end.
* pass 2 pairwise cosine similarity over the N x 256 histogram matrix.
* One thread per (i,j) pair. N^2 threads, which is exactly the shape
* a GPU is for and exactly the shape that makes a CPU quadratic.
*
* WHAT THE CPU STILL DOES, STATED HONESTLY: reads the files off disk, and
* verifies pass 1 against a CPU histogram so a wrong answer cannot pass as a
* fast one. Orchestration and I/O are not "analysis" and cannot be moved onto
* the GPU; every metric reported below is computed by a shader.
*
* COSINE SIMILARITY ON BYTE HISTOGRAMS IS A SCREEN, NOT A PROOF. Two files with
* identical byte distributions are not necessarily identical files. It is a
* cheap upper bound on similarity: a LOW score proves difference, a HIGH score
* says "look here". Exact duplicates are confirmed separately by SHA-256 on the
* host, and the two are reported separately rather than conflated.
*
* node analyse-corpus-gpu.mjs [corpus-root] [--out <dir>] [--top 25]
*
* The corpus root is optional: argv[2], else $CORPUS_ROOT, else the directory
* this script lives in -- which is a small but real corpus, so the harness runs
* on any machine without the GridAtlas tree present. Numbers from that fallback
* are a smoke test of the harness, not the measurements in results/.
*/
import { readFileSync, readdirSync, writeFileSync, mkdirSync, existsSync, statSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { pathToFileURL, fileURLToPath } from 'node:url';
import path from 'node:path';
import os from 'node:os';
const HERE = path.dirname(fileURLToPath(import.meta.url));
function resolveRoot() {
const argvPath = process.argv[2] && !process.argv[2].startsWith('--') ? process.argv[2] : undefined;
const candidates = [argvPath, process.env.CORPUS_ROOT, HERE];
for (const c of candidates) if (c && existsSync(c) && statSync(c).isDirectory()) return c;
console.error('usage: node analyse-corpus-gpu.mjs [corpus-root] [--out dir] [--top N]');
console.error('no corpus root found. Pass a directory or set $CORPUS_ROOT.');
process.exit(2);
}
const root = resolveRoot();
const oi = process.argv.indexOf('--out');
const OUT = oi > 0 ? process.argv[oi + 1] : null;
const ti = process.argv.indexOf('--top');
const TOP = ti > 0 ? Number(process.argv[ti + 1]) : 25;
const EXT = new Set(['.js', '.mjs', '.html', '.css']);
function collect(d, out = []) {
for (const e of readdirSync(d, { withFileTypes: true })) {
if (e.name === 'node_modules' || e.name === '.git') continue;
const p = path.join(d, e.name);
if (e.isDirectory()) collect(p, out);
else if (EXT.has(path.extname(e.name))) out.push(p);
}
return out;
}
console.log('=== CORPUS ===');
const files = collect(root);
if (files.length === 0) {
console.error(`no .js/.mjs/.html/.css files under ${root} -- nothing to analyse.`);
process.exit(2);
}
const bufs = files.map(f => readFileSync(f));
const sizes = bufs.map(b => b.length);
const total = sizes.reduce((a, b) => a + b, 0);
const offsets = [];
let acc = 0;
for (const s of sizes) { offsets.push(acc); acc += s; }
const corpus = Buffer.concat(bufs);
console.log(`root ${root}`);
console.log(`files ${files.length}`);
console.log(`bytes ${total.toLocaleString()} (${(total / 1048576).toFixed(2)} MB)`);
console.log(`machine ${os.cpus()[0].model.trim()}, ${(os.totalmem() / 1073741824).toFixed(2)} GB RAM`);
/* Exact duplicates are a host-side SHA-256 fact, reported separately from the
GPU's similarity screen so the two are never conflated. */
const byHash = new Map();
bufs.forEach((b, i) => {
const h = createHash('sha256').update(b).digest('hex');
if (!byHash.has(h)) byHash.set(h, []);
byHash.get(h).push(i);
});
const dupGroups = [...byHash.values()].filter(g => g.length > 1);
const dupBytes = dupGroups.reduce((a, g) => a + sizes[g[0]] * (g.length - 1), 0);
/* CPU ground truth for pass 1, so a wrong GPU histogram cannot pass. */
const cpuHist = new Uint32Array(files.length * 256);
for (let f = 0; f < files.length; f++) {
const b = bufs[f];
for (let i = 0; i < b.length; i++) cpuHist[f * 256 + b[i]] += 1;
}
/* Playwright may live in another project's node_modules rather than next to
this file, so an absolute path is tried first and the bare specifier is the
fallback. Override with PLAYWRIGHT_PATH. */
const PW = process.env.PLAYWRIGHT_PATH
|| 'C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright/index.js';
/* playwright's entry is CommonJS, so its exports arrive on .default. */
const pwMod = existsSync(PW) ? await import(pathToFileURL(PW).href) : await import('playwright');
const chromium = (pwMod.default || pwMod).chromium;
/* Headless Chromium exposes no WebGPU adapter on this machine (measured), so
the window is real. */
const browser = await chromium.launch({ headless: false, args: [
'--enable-unsafe-webgpu', '--enable-features=Vulkan', '--ignore-gpu-blocklist',
'--enable-gpu', '--disable-gpu-sandbox', '--force_high_performance_gpu',
'--enable-webgpu-developer-features'] });
const page = await browser.newPage();
page.on('console', m => console.log(' [page] ' + m.text()));
page.on('pageerror', e => console.log(' [pageerror] ' + e.message));
await page.route('https://analyse.local/**', r => r.request().url().endsWith('/corpus.bin')
? r.fulfill({ status: 200, contentType: 'application/octet-stream', body: corpus })
: r.fulfill({ status: 200, contentType: 'text/html', body: '<!doctype html><title>corpus analysis</title>' }));
await page.goto('https://analyse.local/index.html');
const gpu = await page.evaluate(async ({ offsets, sizes, n }) => {
if (!navigator.gpu) return { error: 'WebGPU not exposed' };
const adapter = await navigator.gpu.requestAdapter({ powerPreference: 'high-performance' });
if (!adapter) return { error: 'no WebGPU adapter' };
const info = adapter.info || {};
const L = adapter.limits;
const device = await adapter.requestDevice({ requiredLimits: {
maxStorageBufferBindingSize: L.maxStorageBufferBindingSize, maxBufferSize: L.maxBufferSize } });
const raw = new Uint8Array(await (await fetch('/corpus.bin')).arrayBuffer());
const words = Math.ceil(raw.length / 4);
const padded = new Uint8Array(words * 4);
padded.set(raw);
/* CUDA Best Practices Guide, High Priority: the corpus crosses PCIe once and stays resident for
both passes. */
const tUp = performance.now();
const srcBuf = device.createBuffer({ size: padded.byteLength, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST });
device.queue.writeBuffer(srcBuf, 0, padded);
const rangeBuf = device.createBuffer({ size: n * 8, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST });
const ranges = new Uint32Array(n * 2);
for (let i = 0; i < n; i++) { ranges[i * 2] = offsets[i]; ranges[i * 2 + 1] = sizes[i]; }
device.queue.writeBuffer(rangeBuf, 0, ranges);
await device.queue.onSubmittedWorkDone();
const uploadMs = performance.now() - tUp;
const histBuf = device.createBuffer({ size: n * 256 * 4,
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC });
const simBuf = device.createBuffer({ size: n * n * 4,
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC });
/* PASS 1 -- one workgroup per file, 256 on-chip bins, grid-stride over the
file's byte range. Bytes are pulled out of the u32 array by shifting, so
the loads stay word-aligned and coalesce across the warp. */
const m1 = device.createShaderModule({ code: `
@group(0) @binding(0) var<storage, read> src : array<u32>;
@group(0) @binding(1) var<storage, read> ranges : array<vec2<u32>>;
@group(0) @binding(2) var<storage, read_write> hist : array<atomic<u32>>;
var<workgroup> bins : array<atomic<u32>, 256>;
@compute @workgroup_size(256)
fn main(@builtin(workgroup_id) wg : vec3<u32>, @builtin(local_invocation_id) l : vec3<u32>) {
atomicStore(&bins[l.x], 0u);
workgroupBarrier();
let r = ranges[wg.x];
let start = r.x;
let len = r.y;
var i = l.x;
loop {
if (i >= len) { break; }
let abs = start + i;
let w = src[abs >> 2u];
let b = (w >> ((abs & 3u) * 8u)) & 0xffu;
atomicAdd(&bins[b], 1u);
i = i + 256u;
}
workgroupBarrier();
let c = atomicLoad(&bins[l.x]);
if (c > 0u) { atomicAdd(&hist[wg.x * 256u + l.x], c); }
}` });
const p1 = device.createComputePipeline({ layout: 'auto', compute: { module: m1, entryPoint: 'main' } });
const bind1 = device.createBindGroup({ layout: p1.getBindGroupLayout(0), entries: [
{ binding: 0, resource: { buffer: srcBuf } },
{ binding: 1, resource: { buffer: rangeBuf } },
{ binding: 2, resource: { buffer: histBuf } }] });
device.queue.writeBuffer(histBuf, 0, new Uint32Array(n * 256));
await device.queue.onSubmittedWorkDone();
let t = performance.now();
let enc = device.createCommandEncoder();
let pass = enc.beginComputePass();
pass.setPipeline(p1); pass.setBindGroup(0, bind1);
pass.dispatchWorkgroups(n);
pass.end();
device.queue.submit([enc.finish()]);
await device.queue.onSubmittedWorkDone();
const histMs = performance.now() - t;
/* PASS 2 -- N^2 cosine similarities, one thread per pair. Each thread reads
two 256-entry rows and reduces them; this is the quadratic step that makes
a CPU crawl and a GPU shrug. */
const m2 = device.createShaderModule({ code: `
@group(0) @binding(0) var<storage, read> hist : array<u32>;
@group(0) @binding(1) var<storage, read_write> sim : array<f32>;
override N : u32 = 1u;
@compute @workgroup_size(16, 16)
fn main(@builtin(global_invocation_id) g : vec3<u32>) {
let i = g.x; let j = g.y;
if (i >= N || j >= N) { return; }
if (j < i) { sim[i * N + j] = 0.0; return; }
var dot : f32 = 0.0; var na : f32 = 0.0; var nb : f32 = 0.0;
for (var k : u32 = 0u; k < 256u; k = k + 1u) {
let a = f32(hist[i * 256u + k]);
let b = f32(hist[j * 256u + k]);
dot = dot + a * b; na = na + a * a; nb = nb + b * b;
}
let d = sqrt(na) * sqrt(nb);
sim[i * N + j] = select(0.0, dot / d, d > 0.0);
}` });
const p2 = device.createComputePipeline({ layout: 'auto',
compute: { module: m2, entryPoint: 'main', constants: { N: n } } });
const bind2 = device.createBindGroup({ layout: p2.getBindGroupLayout(0), entries: [
{ binding: 0, resource: { buffer: histBuf } }, { binding: 1, resource: { buffer: simBuf } }] });
t = performance.now();
enc = device.createCommandEncoder();
pass = enc.beginComputePass();
pass.setPipeline(p2); pass.setBindGroup(0, bind2);
pass.dispatchWorkgroups(Math.ceil(n / 16), Math.ceil(n / 16));
pass.end();
device.queue.submit([enc.finish()]);
await device.queue.onSubmittedWorkDone();
const simMs = performance.now() - t;
async function read(buf, size) {
const r = device.createBuffer({ size, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ });
const e = device.createCommandEncoder();
e.copyBufferToBuffer(buf, 0, r, 0, size);
device.queue.submit([e.finish()]);
await r.mapAsync(GPUMapMode.READ);
const copy = r.getMappedRange().slice(0);
r.unmap(); r.destroy();
return copy;
}
const histOut = new Uint32Array(await read(histBuf, n * 256 * 4));
const simOut = new Float32Array(await read(simBuf, n * n * 4));
return {
adapter: { vendor: info.vendor, architecture: info.architecture, description: info.description },
uploadMs, histMs, simMs, pairs: (n * (n - 1)) / 2,
hist: Array.from(histOut), sim: Array.from(simOut)
};
}, { offsets, sizes, n: files.length });
await browser.close();
if (gpu.error) { console.log('GPU UNAVAILABLE: ' + gpu.error); process.exit(1); }
/* VERIFY pass 1 against the CPU. A fast wrong histogram is not a result. */
let histAgrees = true;
for (let i = 0; i < cpuHist.length; i++) if (cpuHist[i] !== gpu.hist[i]) { histAgrees = false; break; }
const N = files.length;
const MB = total / 1048576;
console.log('\n=== GPU (MEASURED) ===');
console.log(`adapter ${JSON.stringify(gpu.adapter)}`);
console.log(`upload (once) ${gpu.uploadMs.toFixed(1)} ms (${(MB / (gpu.uploadMs / 1000)).toFixed(0)} MB/s)`);
console.log(`pass 1 histograms ${gpu.histMs.toFixed(2)} ms (${(MB / (gpu.histMs / 1000)).toFixed(0)} MB/s over ${N} files)`);
console.log(`pass 2 similarity ${gpu.simMs.toFixed(2)} ms (${gpu.pairs.toLocaleString()} pairs)`);
console.log(`histogram verification vs CPU: ${histAgrees ? 'MATCHES bin for bin' : '*** DISAGREES ***'}`);
console.log('\n=== EXACT DUPLICATES (host SHA-256, reported separately) ===');
console.log(`duplicate groups ${dupGroups.length}`);
console.log(`redundant bytes ${dupBytes.toLocaleString()} (${(dupBytes / 1048576).toFixed(2)} MB, ${(dupBytes / total * 100).toFixed(1)}% of corpus)`);
for (const g of dupGroups.sort((a, b) => sizes[b[0]] - sizes[a[0]]).slice(0, 8)) {
console.log(` ${(sizes[g[0]] / 1024).toFixed(0).padStart(7)} KB x${g.length} ${g.map(i => path.relative(root, files[i])).join(' == ')}`);
}
console.log(`\n=== GPU SIMILARITY SCREEN: top ${TOP} near-duplicate pairs (not byte-identical) ===`);
const rel = files.map(f => path.relative(root, f).split(path.sep).join('/'));
const pairs = [];
for (let i = 0; i < N; i++) {
for (let j = i + 1; j < N; j++) {
const s = gpu.sim[i * N + j];
if (s >= 0.99) pairs.push({ i, j, s });
}
}
const exactSet = new Set(dupGroups.flatMap(g => g.flatMap(a => g.map(b => `${Math.min(a, b)}:${Math.max(a, b)}`))));
const near = pairs.filter(p => !exactSet.has(`${p.i}:${p.j}`)).sort((a, b) => b.s - a.s);
console.log(`pairs at cosine >= 0.99 : ${pairs.length.toLocaleString()} of ${gpu.pairs.toLocaleString()}`);
console.log(` of which byte-identical: ${(pairs.length - near.length).toLocaleString()}`);
/* NOT "the reducible payload" -- that would be reading the screen as a proof.
These are the pairs a real byte-exact diff should be pointed at next. */
console.log(` near-duplicate, NOT identical: ${near.length.toLocaleString()} <- candidates to diff, NOT proven redundancy`);
for (const p of near.slice(0, TOP)) {
console.log(` ${p.s.toFixed(5)} ${(sizes[p.i] / 1024).toFixed(0)}KB ${rel[p.i]}`);
console.log(` ${(sizes[p.j] / 1024).toFixed(0)}KB ${rel[p.j]}`);
}
/* NOT a payload saving, and must never be read as one. Pairs overlap heavily --
one file appearing in fifty pairs is counted fifty times -- so this sum can
and does exceed the size of the whole corpus. It is printed only to show the
screen's fan-out, and it is deliberately kept out of the JSON report so it
cannot be picked up as a number. */
const nearBytes = near.reduce((a, p) => a + Math.min(sizes[p.i], sizes[p.j]), 0);
console.log(`\nbytes sitting in near-duplicate pairs: ${(nearBytes / 1048576).toFixed(2)} MB`);
console.log(' ^ NOT a payload saving. Pairs overlap, so files are counted many');
console.log(' times over; this figure can exceed the corpus itself. The only');
console.log(' defensible redundancy number above is the SHA-256 one.');
if (OUT) {
mkdirSync(OUT, { recursive: true });
const report = {
measuredAt: new Date().toISOString(),
machine: { cpu: os.cpus()[0].model.trim(), logicalCores: os.cpus().length,
ramGB: +(os.totalmem() / 1073741824).toFixed(2), gpu: gpu.adapter },
corpus: { root, files: N, bytes: total },
gpuTiming: { uploadMs: gpu.uploadMs, histMs: gpu.histMs, simMs: gpu.simMs, pairs: gpu.pairs },
verification: { histogramMatchesCpu: histAgrees },
exactDuplicates: { groups: dupGroups.length, redundantBytes: dupBytes,
pctOfCorpus: +(dupBytes / total * 100).toFixed(2),
examples: dupGroups.slice(0, 20).map(g => ({ bytes: sizes[g[0]], files: g.map(i => rel[i]) })) },
nearDuplicates: { threshold: 0.99, pairsAtThreshold: pairs.length,
byteIdentical: pairs.length - near.length, nearNotIdentical: near.length,
top: near.slice(0, 100).map(p => ({ cosine: +p.s.toFixed(6), a: rel[p.i], b: rel[p.j],
bytesA: sizes[p.i], bytesB: sizes[p.j] })) }
};
writeFileSync(path.join(OUT, 'corpus-gpu-analysis.json'), JSON.stringify(report, null, 2));
console.log(`\nwrote ${path.join(OUT, 'corpus-gpu-analysis.json')}`);
}Claude Bench Cpu Ram
A JavaScript module in GPU Drivers for Global Grid that resolves artefact (`resolveArtefact`), using SHA-256. It resolves artefact (`resolveArtefact`) and is built from the work step (`work`).
ingestgpu-drivers-for-global-grid / claude/bench-cpu-ram.mjs · lines 1–162 of 162 · Entry point · pattern resolveArtefact (shared by 2 files)
- What it does
- It loads data. Defines work, resolveArtefact. Uses libraries node:worker_threads, node:fs, node:crypto, node:url, node:path. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage agent_infra (path word 'claude'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: command-line arguments.
- Downstream impact
- Used directly by 1 file: Claude Bench Workflow (gpu-drivers-for-global-grid).
- What it achieves
- No network, no model. It loads a large text artefact (the original run used the real 27.5 MB GridAtlas teleprint the architect produced on ) and measures several different things, each of which stresses a…
- Why it matters
- Run by Claude Bench Workflow.
- Application
- gpu-drivers-for-global-grid · claude · JavaScript module
- Uses
- node:worker_threads, node:fs, node:crypto, node:url, node:path, node:os
- Used by
- run by Claude Bench Workflow (workflow run)
- Produces
- work, resolveArtefact
- Defines here
- work, resolveArtefact
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gpu-drivers-for-global-grid@6c47912a8dde251ffebd92ff129e6a0c11c4ebfe claude/bench-cpu-ram.mjs:1-162 · blob cc36153bdf8507be006fce39a950fb027dc79bf8 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: unknown
/**
* HOW FAST CAN THIS MACHINE ACTUALLY EAT A TELEPRINT?
* ---------------------------------------------------------------------------
* Offline. No network, no model. It loads a large text artefact (the original
* run used the real 27.5 MB GridAtlas teleprint the architect produced on
* 2026-09-05) and measures several different things, each of which stresses a
* different part of the box:
*
* read cold-ish file read -> storage + page cache
* memcpy buffer copy in RAM -> DDR5 bandwidth, one core
* sha256 hash the whole file -> CPU, compute bound
* parse find every BEGIN/END section -> CPU, branch + string bound
*
* Then it runs the SAME work on 1..N worker threads, each worker holding its
* OWN copy of the file, because "load it x several threads" means N resident
* copies, not one shared buffer sliced N ways. That is the honest test of what
* a DC machine does when N readers each open the artefact.
*
* MEASURED, not asserted: every number below is a timing this process took.
*
* node bench-cpu-ram.mjs [artefact.txt] [--threads 1,2,4,8,16,20]
*
* The artefact path is optional. Resolution order:
* 1. argv[2]
* 2. $BENCH_ARTEFACT
* 3. ./sample-artefact.txt next to this file (make it with make-sample-artefact.mjs)
* The 27.5 MB teleprint itself is deliberately NOT committed: it is evidence,
* not source.
*/
import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
import { readFileSync, statSync, existsSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import os from 'node:os';
const MB = 1024 * 1024;
/* The unit of work. Deliberately three separate phases so a slow one is
visible rather than averaged into the others. */
function work(buf) {
const t = {};
let m0 = process.hrtime.bigint();
const copy = Buffer.allocUnsafe(buf.length);
buf.copy(copy);
t.memcpyMs = Number(process.hrtime.bigint() - m0) / 1e6;
m0 = process.hrtime.bigint();
const digest = createHash('sha256').update(buf).digest('hex');
t.sha256Ms = Number(process.hrtime.bigint() - m0) / 1e6;
m0 = process.hrtime.bigint();
const text = buf.toString('utf8');
t.decodeMs = Number(process.hrtime.bigint() - m0) / 1e6;
m0 = process.hrtime.bigint();
let sections = 0;
const re = /^=+ (BEGIN|END) /gm;
while (re.exec(text) !== null) sections += 1;
t.parseMs = Number(process.hrtime.bigint() - m0) / 1e6;
t.sections = sections;
t.digest16 = digest.slice(0, 16);
return t;
}
/* Path with a sensible fallback, so the bench is runnable on a machine that
does not have the (uncommitted) teleprint. */
function resolveArtefact(argvPath) {
const here = path.dirname(fileURLToPath(import.meta.url));
const candidates = [argvPath, process.env.BENCH_ARTEFACT, path.join(here, 'sample-artefact.txt')];
for (const c of candidates) if (c && existsSync(c)) return c;
console.error('no artefact found. Pass a path, set $BENCH_ARTEFACT, or generate one:');
console.error(' node make-sample-artefact.mjs sample-artefact.txt 26');
process.exit(2);
}
if (!isMainThread) {
/* Each worker reads the file ITSELF. No shared buffer, no transfer: this is
N independent readers, which is the case being measured. */
const t0 = process.hrtime.bigint();
const buf = readFileSync(workerData.file);
const readMs = Number(process.hrtime.bigint() - t0) / 1e6;
const r = work(buf);
r.readMs = readMs;
r.rssMB = process.memoryUsage().rss / MB;
parentPort.postMessage(r);
} else {
const argvPath = process.argv[2] && !process.argv[2].startsWith('--') ? process.argv[2] : undefined;
const file = resolveArtefact(argvPath);
const ti = process.argv.indexOf('--threads');
const LADDER = ti > 0 ? process.argv[ti + 1].split(',').map(Number) : [1, 2, 4, 8, 16, 20];
const bytes = statSync(file).size;
const machine = {
cpu: os.cpus()[0].model.trim(),
logicalCores: os.cpus().length,
totalRamGB: +(os.totalmem() / 1024 / 1024 / 1024).toFixed(2),
freeRamGB: +(os.freemem() / 1024 / 1024 / 1024).toFixed(2),
node: process.version,
file,
fileBytes: bytes,
fileMB: +(bytes / MB).toFixed(2)
};
console.log(JSON.stringify(machine, null, 1));
/* Single-threaded baseline, run three times: the first is cold, the later
two are warm. Reporting only the fastest would flatter the page cache. */
console.log('\n=== SINGLE THREAD, 3 passes (MEASURED) ===');
const single = [];
for (let i = 0; i < 3; i++) {
const t0 = process.hrtime.bigint();
const buf = readFileSync(file);
const readMs = Number(process.hrtime.bigint() - t0) / 1e6;
const r = work(buf);
r.readMs = readMs;
single.push(r);
console.log(`pass ${i + 1} read ${readMs.toFixed(1)}ms (${(bytes / MB / (readMs / 1000)).toFixed(0)} MB/s)`
+ ` memcpy ${r.memcpyMs.toFixed(1)}ms (${(bytes / MB / (r.memcpyMs / 1000)).toFixed(0)} MB/s)`
+ ` sha256 ${r.sha256Ms.toFixed(1)}ms (${(bytes / MB / (r.sha256Ms / 1000)).toFixed(0)} MB/s)`
+ ` utf8-decode ${r.decodeMs.toFixed(1)}ms parse ${r.parseMs.toFixed(1)}ms sections ${r.sections}`);
}
console.log('\n=== THREAD LADDER: N independent readers, each with its own copy (MEASURED) ===');
const ladder = [];
for (const n of LADDER) {
const t0 = process.hrtime.bigint();
const results = await Promise.all(Array.from({ length: n }, () => new Promise((res, rej) => {
const w = new Worker(new URL(import.meta.url), { workerData: { file } });
w.on('message', m => { res(m); w.terminate(); });
w.on('error', rej);
})));
const wallMs = Number(process.hrtime.bigint() - t0) / 1e6;
const totalMB = (bytes * n) / MB;
const row = {
threads: n,
wallMs: +wallMs.toFixed(1),
totalMBProcessed: +totalMB.toFixed(1),
aggregateMBps: +(totalMB / (wallMs / 1000)).toFixed(0),
perThreadMeanSha256Ms: +(results.reduce((a, r) => a + r.sha256Ms, 0) / n).toFixed(1),
perThreadMeanMemcpyMs: +(results.reduce((a, r) => a + r.memcpyMs, 0) / n).toFixed(1),
peakWorkerRssMB: +Math.max(...results.map(r => r.rssMB)).toFixed(0),
sectionsAgree: new Set(results.map(r => r.sections)).size === 1,
digestsAgree: new Set(results.map(r => r.digest16)).size === 1
};
ladder.push(row);
console.log(`${String(n).padStart(3)} threads wall ${row.wallMs.toFixed(0).padStart(6)}ms`
+ ` aggregate ${String(row.aggregateMBps).padStart(5)} MB/s`
+ ` mean sha256 ${String(row.perThreadMeanSha256Ms).padStart(7)}ms`
+ ` mean memcpy ${String(row.perThreadMeanMemcpyMs).padStart(6)}ms`
+ ` peak worker RSS ${String(row.peakWorkerRssMB).padStart(4)} MB`
+ ` identical: sections=${row.sectionsAgree} digest=${row.digestsAgree}`);
}
const base = ladder.find(r => r.threads === 1) || ladder[0];
console.log('\n=== SCALING vs 1 thread (MEASURED) ===');
for (const r of ladder) {
console.log(`${String(r.threads).padStart(3)} threads speedup x${(r.aggregateMBps / base.aggregateMBps).toFixed(2)}`
+ ` efficiency ${((r.aggregateMBps / base.aggregateMBps) / r.threads * 100).toFixed(0)}%`);
}
console.log('\nJSON ' + JSON.stringify({ machine, single, ladder }));
}