GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / AI agents and coordination / gpu-drivers-for-global-grid / claude

Claude Bench GPU and 6 more files

A JavaScript module in GPU Drivers for Global Grid that resolves artefact (`resolveArtefact`) and reads count (`readCount`). It resolves artefact (`resolveArtefact`) and reads count (`readCount`).

660 lines of JavaScript and Python and HTML from gpu-drivers-for-global-grid, in 7 files. Topic: AI agents and coordination. Section 1624 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. Claude Bench GPU ingest · gpu-drivers-for-global-grid / claude/bench-gpu.mjs lines 1–344
  2. Claude Make Sample Artefact other · gpu-drivers-for-global-grid / claude/make-sample-artefact.mjs lines 1–68
  3. Codex Corpus Review storage · gpu-drivers-for-global-grid / codex/corpus-review.py lines 1–47
  4. Codex Learn Repo storage · gpu-drivers-for-global-grid / codex/learn-repo.py lines 1–106
  5. Codex Learn Repo Test test · gpu-drivers-for-global-grid / codex/learn-repo.test.py lines 1–11
  6. Codex Learning Night storage · gpu-drivers-for-global-grid / codex/learning-night.py lines 1–60
  7. Codex Monitor Local render · gpu-drivers-for-global-grid / codex/monitor-local.html lines 1–24

Claude Bench GPU

A JavaScript module in GPU Drivers for Global Grid that resolves artefact (`resolveArtefact`) and reads count (`readCount`). It resolves artefact (`resolveArtefact`) and reads count (`readCount`).

ingestgpu-drivers-for-global-grid / claude/bench-gpu.mjs · lines 1–344 of 344 · Entry point · pattern resolveArtefact (shared by 2 files)

What it does
It fetches data. Defines 8 functions or classes, including resolveArtefact, pipe, newSrcWriteBuffer, newSrcMapped, readCount. Uses libraries node:fs, node:url, node:path, playwright. 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: command-line arguments. Out: WebGL/WebGPU drawing.
Downstream impact
Used directly by 1 file: Claude Bench Workflow (gpu-drivers-for-global-grid).
What it achieves
THE TELEPRINT ON THE RTX 5070, WITH THE CUDA BEST-PRACTICE RULES APPLIED. --------------------------------------------------------------------------- The same ~27.5 MB artefact the CPU bench ate, uploaded to the discrete GPU and reduced by a compute shader.
Why it matters
Run by Claude Bench Workflow.
Application
gpu-drivers-for-global-grid · claude · JavaScript module
Uses
node:fs, node:url, node:path, playwright
Used by
run by Claude Bench Workflow (workflow run)
Produces
resolveArtefact, pipe, newSrcWriteBuffer, newSrcMapped, readCount, dispatch, measure, mean
Defines here
resolveArtefact, pipe, newSrcWriteBuffer, newSrcMapped, readCount, dispatch, measure, mean
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-gpu.mjs:1-344 · blob 79f516ccc32f83dbf7520f6bd9b82378a5f255fb · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, network, process · domain stage: agent_infra · users: ai_agent · canonical: unknown
/**
 * THE TELEPRINT ON THE RTX 5070, WITH THE CUDA BEST-PRACTICE RULES APPLIED.
 * ---------------------------------------------------------------------------
 * The same ~27.5 MB artefact the CPU bench ate, uploaded to the discrete GPU and
 * reduced by a compute shader. Offline: a Chromium already installed for
 * Playwright, WebGPU on, and NOTHING fetched from the network -- the bytes are
 * served to the page from disk through a route interceptor.
 *
 * WHY FIVE VARIANTS AND NOT ONE. the CUDA C++ Best Practices Guide gives
 * specific, testable rules. Each variant below turns ONE of them on, so the
 * cost of each is a measured delta rather than a belief:
 *
 *   A baseline      writeBuffer upload, one u32 (4 bytes) per thread, wg 256
 *   B mapped        upload via mappedAtCreation -- the WebGPU analogue of
 *                   the guide's "page-locked/pinned memory transfers attain the
 *                   highest bandwidth", because it writes into driver-owned
 *                   memory once instead of staging a pageable copy
 *   C vectorized    one vec4<u32> (16 bytes) per thread. Guide: coalesced,
 *                   128-bit loads maximise global memory throughput
 *   D gridstride    fewer workgroups, each thread looping. Guide: occupancy
 *                   and instruction-level parallelism hide memory latency
 *   E resident      upload ONCE, run the kernel N times. Guide, High Priority:
 *                   "Minimize data transfer between the host and the device"
 *
 * WHICH GPU ANSWERED is printed, never assumed: this laptop has an Intel iGPU
 * and the 5070, and silently getting the iGPU is the classic false result.
 * Chrome also ignores powerPreference on Windows (crbug.com/369219127), so the
 * printed adapter is the only evidence of which device did the work.
 *
 * EVERY VARIANT MUST AGREE WITH THE CPU. The work is counting bytes equal to
 * '=' (0x3D) -- not arbitrary, since the teleprint's section boundaries are
 * runs of '=', so this is the first pass of a real parse expressed as the
 * embarrassingly-parallel reduction a GPU exists for. A fast wrong answer is
 * not a result, so the CPU count is computed first and every run is checked.
 *
 *   node bench-gpu.mjs [artefact.txt] [--iters 5] [--headed=0]
 *
 * The artefact path is optional: argv[2], else $BENCH_ARTEFACT, else
 * ./sample-artefact.txt next to this file (make-sample-artefact.mjs writes one).
 */
import { readFileSync, existsSync } from 'node:fs';
import { pathToFileURL, fileURLToPath } from 'node:url';
import path from 'node:path';

/* 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 HERE = path.dirname(fileURLToPath(import.meta.url));
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;

function resolveArtefact() {
  const argvPath = process.argv[2] && !process.argv[2].startsWith('--') ? process.argv[2] : undefined;
  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);
}
const file = resolveArtefact();
const ii = process.argv.indexOf('--iters');
const ITERS = ii > 0 ? Number(process.argv[ii + 1]) : 5;

const buf = readFileSync(file);
const MB = buf.length / 1048576;
console.log(`file  ${file}`);
console.log(`bytes ${buf.length} (${MB.toFixed(2)} MB)`);

/* CPU ground truth, twice: scalar, then the same count via indexOf, which is
   the fair comparison because it is what a real parser would use. */
let cpuCount = 0;
let t0 = process.hrtime.bigint();
for (let i = 0; i < buf.length; i++) if (buf[i] === 0x3d) cpuCount += 1;
const cpuScalarMs = Number(process.hrtime.bigint() - t0) / 1e6;
t0 = process.hrtime.bigint();
let n = 0, at = -1;
while ((at = buf.indexOf(0x3d, at + 1)) !== -1) n += 1;
const cpuIndexOfMs = Number(process.hrtime.bigint() - t0) / 1e6;
console.log(`CPU scalar  count '=' : ${cpuCount} in ${cpuScalarMs.toFixed(1)}ms (${(MB / (cpuScalarMs / 1000)).toFixed(0)} MB/s)`);
console.log(`CPU indexOf count '=' : ${n} in ${cpuIndexOfMs.toFixed(1)}ms (${(MB / (cpuIndexOfMs / 1000)).toFixed(0)} MB/s)`);

/* HEADLESS CHROMIUM HAS NO GPU ADAPTER ON THIS MACHINE. Measured: headless
   requestAdapter() returns null with "No available adapters", so a headless run
   would silently report "no GPU" on a laptop that has two. The window is
   therefore real. --headed=0 forces the headless path back on if you want to
   see that failure for yourself. */
const HEADLESS = process.argv.includes('--headed=0');
const CHANNEL = process.env.BENCH_CHANNEL || undefined; // e.g. 'chrome' for installed Chrome
const browser = await chromium.launch({
  headless: HEADLESS,
  channel: CHANNEL,
  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));

/* The bytes reach the page from DISK, not from the network and not marshalled
   through CDP as a 27-million-element array. */
await page.route('https://bench.local/**', route => {
  if (route.request().url().endsWith('/payload.bin')) {
    return route.fulfill({ status: 200, contentType: 'application/octet-stream', body: buf });
  }
  return route.fulfill({ status: 200, contentType: 'text/html', body: '<!doctype html><title>bench</title>' });
});
await page.goto('https://bench.local/index.html');

const result = await page.evaluate(async (iters) => {
  if (!navigator.gpu) return { error: 'navigator.gpu is undefined: WebGPU not exposed in this Chromium' };
  const adapter = await navigator.gpu.requestAdapter({ powerPreference: 'high-performance' });
  if (!adapter) return { error: 'requestAdapter returned null: no WebGPU adapter' };
  const info = adapter.info || (adapter.requestAdapterInfo ? await adapter.requestAdapterInfo() : {});
  const L = adapter.limits;
  const device = await adapter.requestDevice({ requiredLimits: {
    maxStorageBufferBindingSize: L.maxStorageBufferBindingSize,
    maxBufferSize: L.maxBufferSize } });
  device.addEventListener?.('uncapturederror', e => console.log('uncaptured: ' + e.error.message));

  const raw = new Uint8Array(await (await fetch('/payload.bin')).arrayBuffer());
  /* Guide: batch many small transfers into ONE larger transfer. The whole
     artefact goes across in a single copy, padded to a 16-byte boundary so the
     vec4 variant's loads stay aligned. Padding is zero, which is not '='. */
  const quads = Math.ceil(raw.length / 16);
  const padded = new Uint8Array(quads * 16);
  padded.set(raw);
  const words = padded.byteLength / 4;

  const WG = 256; // multiple of 32: guide, block sizes should be warp multiples

  const src = `
@group(0) @binding(0) var<storage, read> src : array<u32>;
@group(0) @binding(1) var<storage, read_write> total : atomic<u32>;
var<workgroup> partial : atomic<u32>;
fn hits(w : u32) -> u32 {
  var c : u32 = 0u;
  if ((w & 0xffu) == 0x3du) { c = c + 1u; }
  if (((w >> 8u) & 0xffu) == 0x3du) { c = c + 1u; }
  if (((w >> 16u) & 0xffu) == 0x3du) { c = c + 1u; }
  if (((w >> 24u) & 0xffu) == 0x3du) { c = c + 1u; }
  return c;
}
@compute @workgroup_size(${WG})
fn scalar(@builtin(global_invocation_id) g : vec3<u32>, @builtin(local_invocation_id) l : vec3<u32>) {
  if (l.x == 0u) { atomicStore(&partial, 0u); }
  workgroupBarrier();
  var c : u32 = 0u;
  if (g.x < arrayLength(&src)) { c = hits(src[g.x]); }
  atomicAdd(&partial, c);
  workgroupBarrier();
  if (l.x == 0u) { atomicAdd(&total, atomicLoad(&partial)); }
}`;

  const src4 = `
@group(0) @binding(0) var<storage, read> src : array<vec4<u32>>;
@group(0) @binding(1) var<storage, read_write> total : atomic<u32>;
var<workgroup> partial : atomic<u32>;
fn hits(w : u32) -> u32 {
  var c : u32 = 0u;
  if ((w & 0xffu) == 0x3du) { c = c + 1u; }
  if (((w >> 8u) & 0xffu) == 0x3du) { c = c + 1u; }
  if (((w >> 16u) & 0xffu) == 0x3du) { c = c + 1u; }
  if (((w >> 24u) & 0xffu) == 0x3du) { c = c + 1u; }
  return c;
}
/* Guide: 128-bit (vec4) loads maximise global memory throughput, and
   consecutive threads touch consecutive 16-byte lanes, so the warp coalesces. */
@compute @workgroup_size(${WG})
fn vectorized(@builtin(global_invocation_id) g : vec3<u32>, @builtin(local_invocation_id) l : vec3<u32>) {
  if (l.x == 0u) { atomicStore(&partial, 0u); }
  workgroupBarrier();
  var c : u32 = 0u;
  if (g.x < arrayLength(&src)) {
    let v = src[g.x];
    c = hits(v.x) + hits(v.y) + hits(v.z) + hits(v.w);
  }
  atomicAdd(&partial, c);
  workgroupBarrier();
  if (l.x == 0u) { atomicAdd(&total, atomicLoad(&partial)); }
}
/* Guide: fewer, fatter blocks with a grid-stride loop keep the SMs occupied
   and expose instruction-level parallelism to hide memory latency. */
@compute @workgroup_size(${WG})
fn gridstride(@builtin(global_invocation_id) g : vec3<u32>, @builtin(local_invocation_id) l : vec3<u32>,
              @builtin(num_workgroups) nw : vec3<u32>) {
  if (l.x == 0u) { atomicStore(&partial, 0u); }
  workgroupBarrier();
  let n = arrayLength(&src);
  let stride = nw.x * ${WG}u;
  var c : u32 = 0u;
  var i = g.x;
  loop {
    if (i >= n) { break; }
    let v = src[i];
    c = c + hits(v.x) + hits(v.y) + hits(v.z) + hits(v.w);
    i = i + stride;
  }
  atomicAdd(&partial, c);
  workgroupBarrier();
  if (l.x == 0u) { atomicAdd(&total, atomicLoad(&partial)); }
}`;

  const modScalar = device.createShaderModule({ code: src });
  const modVec = device.createShaderModule({ code: src4 });
  const pipe = (m, e) => device.createComputePipeline({ layout: 'auto', compute: { module: m, entryPoint: e } });
  const pScalar = pipe(modScalar, 'scalar');
  const pVec = pipe(modVec, 'vectorized');
  const pGrid = pipe(modVec, 'gridstride');

  const outBuf = device.createBuffer({ size: 4, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC });
  const readBuf = device.createBuffer({ size: 4, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ });

  const newSrcWriteBuffer = () => {
    const b = device.createBuffer({ size: padded.byteLength, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST });
    device.queue.writeBuffer(b, 0, padded);
    return b;
  };
  const newSrcMapped = () => {
    const b = device.createBuffer({ size: padded.byteLength, usage: GPUBufferUsage.STORAGE, mappedAtCreation: true });
    new Uint8Array(b.getMappedRange()).set(padded);
    b.unmap();
    return b;
  };

  async function readCount() {
    const e = device.createCommandEncoder();
    e.copyBufferToBuffer(outBuf, 0, readBuf, 0, 4);
    device.queue.submit([e.finish()]);
    await readBuf.mapAsync(GPUMapMode.READ);
    const v = new Uint32Array(readBuf.getMappedRange().slice(0))[0];
    readBuf.unmap();
    return v;
  }

  async function dispatch(pipeline, srcBuf, groups) {
    device.queue.writeBuffer(outBuf, 0, new Uint32Array([0]));
    await device.queue.onSubmittedWorkDone();
    const bind = device.createBindGroup({ layout: pipeline.getBindGroupLayout(0),
      entries: [{ binding: 0, resource: { buffer: srcBuf } }, { binding: 1, resource: { buffer: outBuf } }] });
    const t = performance.now();
    const enc = device.createCommandEncoder();
    const pass = enc.beginComputePass();
    pass.setPipeline(pipeline); pass.setBindGroup(0, bind);
    pass.dispatchWorkgroups(groups);
    pass.end();
    device.queue.submit([enc.finish()]);
    await device.queue.onSubmittedWorkDone();
    const ms = performance.now() - t;
    return { ms, count: await readCount() };
  }

  const variants = [];
  async function measure(name, note, make, pipeline, groups) {
    const runs = [];
    for (let i = 0; i < iters; i++) {
      const tu = performance.now();
      const b = make();
      await device.queue.onSubmittedWorkDone();
      const uploadMs = performance.now() - tu;
      const d = await dispatch(pipeline, b, groups);
      runs.push({ uploadMs, computeMs: d.ms, count: d.count });
      b.destroy?.();
    }
    variants.push({ name, note, groups, threads: groups * WG, runs });
  }

  await measure('A baseline  writeBuffer + u32/thread', 'guide rule: none applied beyond one batched transfer',
    newSrcWriteBuffer, pScalar, Math.ceil(words / WG));
  await measure('B mapped    mappedAtCreation + u32/thread', 'pinned-memory analogue: one write into driver memory',
    newSrcMapped, pScalar, Math.ceil(words / WG));
  await measure('C vector    mappedAtCreation + vec4/thread', '128-bit coalesced loads',
    newSrcMapped, pVec, Math.ceil(quads / WG));
  await measure('D gridstride mappedAtCreation + vec4 + loop', 'occupancy/ILP: 1024 fat workgroups',
    newSrcMapped, pGrid, 1024);

  /* E: Guide High Priority -- minimise host<->device transfer. Upload ONCE,
     then run the kernel `iters` times on the resident buffer. */
  const resident = newSrcMapped();
  await device.queue.onSubmittedWorkDone();
  const residentRuns = [];
  for (let i = 0; i < iters; i++) {
    const d = await dispatch(pVec, resident, Math.ceil(quads / WG));
    residentRuns.push({ uploadMs: 0, computeMs: d.ms, count: d.count });
  }
  variants.push({ name: 'E resident  upload once, N kernels', note: 'Guide High Priority: minimise host<->device transfer',
    groups: Math.ceil(quads / WG), threads: Math.ceil(quads / WG) * WG, runs: residentRuns });

  return {
    adapter: { vendor: info.vendor, architecture: info.architecture, device: info.device, description: info.description },
    limits: { maxBufferSize: L.maxBufferSize, maxStorageBufferBindingSize: L.maxStorageBufferBindingSize,
      maxComputeInvocationsPerWorkgroup: L.maxComputeInvocationsPerWorkgroup,
      maxComputeWorkgroupsPerDimension: L.maxComputeWorkgroupsPerDimension },
    bytes: raw.length, paddedBytes: padded.byteLength, workgroupSize: WG, variants
  };
}, ITERS);

await browser.close();

if (result.error) { console.log('\nGPU UNAVAILABLE: ' + result.error); process.exit(1); }

console.log('\n=== THE ADAPTER THAT ACTUALLY ANSWERED (MEASURED) ===');
console.log(JSON.stringify(result.adapter, null, 1));
console.log('limits ' + JSON.stringify(result.limits));
console.log(`payload ${result.bytes} B padded to ${result.paddedBytes} B, workgroup size ${result.workgroupSize}`);

console.log('\n=== VARIANTS (warm means, iteration 1 discarded) ===');
const rows = [];
for (const v of result.variants) {
  const warm = v.runs.slice(1);
  const mean = k => warm.reduce((a, r) => a + r[k], 0) / warm.length;
  const up = mean('uploadMs'), co = mean('computeMs');
  const ok = v.runs.every(r => r.count === cpuCount);
  rows.push({ name: v.name, note: v.note, threads: v.threads, uploadMs: +up.toFixed(2), computeMs: +co.toFixed(3),
    uploadMBps: up ? Math.round(MB / (up / 1000)) : null, computeMBps: Math.round(MB / (co / 1000)),
    endToEndMs: +(up + co).toFixed(2), correct: ok, count: v.runs[0].count });
  console.log(`${v.name.padEnd(38)} threads ${String(v.threads).padStart(8)}`
    + `  upload ${up.toFixed(2).padStart(7)}ms ${up ? String(Math.round(MB / (up / 1000))).padStart(6) + ' MB/s' : '     -     '}`
    + `  compute ${co.toFixed(3).padStart(7)}ms ${String(Math.round(MB / (co / 1000))).padStart(6)} MB/s`
    + `  ${ok ? 'count MATCHES CPU' : 'COUNT WRONG (' + v.runs[0].count + ' vs ' + cpuCount + ')'}`);
}

console.log('\n=== WHAT EACH RULE BOUGHT (MEASURED DELTA) ===');
const base = rows[0];
for (const r of rows.slice(1)) {
  console.log(`${r.name.padEnd(38)} compute x${(base.computeMs / r.computeMs).toFixed(2)} vs baseline`
    + `  end-to-end x${(base.endToEndMs / r.endToEndMs).toFixed(2)}`);
}

console.log('\n=== GPU vs CPU ON THE SAME ARTEFACT (MEASURED) ===');
const best = rows.reduce((a, b) => (b.computeMs < a.computeMs ? b : a));
console.log(`CPU scalar loop           ${cpuScalarMs.toFixed(1)}ms  (${(MB / (cpuScalarMs / 1000)).toFixed(0)} MB/s)`);
console.log(`CPU Buffer.indexOf        ${cpuIndexOfMs.toFixed(1)}ms  (${(MB / (cpuIndexOfMs / 1000)).toFixed(0)} MB/s)`);
console.log(`GPU best compute-only     ${best.computeMs.toFixed(3)}ms  (${best.computeMBps} MB/s)  [${best.name.trim()}]`);
console.log(`GPU best end-to-end       ${best.endToEndMs.toFixed(2)}ms  (upload included)`);
console.log(`\ncompute-only  GPU vs CPU scalar   x${(cpuScalarMs / best.computeMs).toFixed(1)}`);
console.log(`compute-only  GPU vs CPU indexOf  x${(cpuIndexOfMs / best.computeMs).toFixed(1)}`);
console.log(`end-to-end    GPU vs CPU scalar   x${(cpuScalarMs / best.endToEndMs).toFixed(2)}`);
console.log(`end-to-end    GPU vs CPU indexOf  x${(cpuIndexOfMs / best.endToEndMs).toFixed(2)}`);

console.log('\nJSON ' + JSON.stringify({ cpuScalarMs, cpuIndexOfMs, cpuCount, adapter: result.adapter, rows }));

Claude Make Sample Artefact

A JavaScript module in GPU Drivers for Global Grid. It is built from the rnd step (`rnd`) and the write step (`write`).

othergpu-drivers-for-global-grid / claude/make-sample-artefact.mjs · lines 1–68 of 68 · Entry point

What it does
Defines rnd, write. Uses libraries node:fs, node:events. Side effects: reads or writes files.
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: "`make-sample-artefact.mjs` writes a same-shaped stand-in so the harness runs on any machine, including CI."
Inputs & outputs
In: command-line arguments.
Downstream impact
Used directly by 1 file: Claude Bench Workflow (gpu-drivers-for-global-grid).
What it achieves
The artefact the measured numbers came from is a 27,568,130-byte GridAtlas teleprint source dump.
Why it matters
Run by Claude Bench Workflow.
Application
gpu-drivers-for-global-grid · claude · JavaScript module
Uses
node:fs, node:events
Used by
run by Claude Bench Workflow (workflow run)
Produces
rnd, write
Defines here
rnd, write
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/make-sample-artefact.mjs:1-68 · blob 36caaf04886cfcbb7d1cbec1cc274f0aef0af1d2 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
/**
 * A STAND-IN FOR THE TELEPRINT.
 * ---------------------------------------------------------------------------
 * The artefact the measured numbers came from is a 27,568,130-byte GridAtlas
 * teleprint source dump. It is evidence, not source, so it is NOT committed
 * here. This writes a same-shaped synthetic artefact so the benches -- and the
 * CI workflow, which has no teleprint -- are runnable anywhere:
 *
 *   - "===== BEGIN <name> =====" / "===== END <name> =====" section markers,
 *     which is what the CPU bench's /^=+ (BEGIN|END) /gm counts
 *   - runs of '=' between sections, which is what the GPU bench reduces over
 *   - deterministic (seeded), so two runs on the same machine are comparable
 *
 * It is a SHAPE match, not the artefact. Numbers produced from it are not the
 * numbers in claude/results/ -- those name the real teleprint and this machine.
 *
 *   node make-sample-artefact.mjs [out.txt] [sizeMB]
 */
import { createWriteStream } from 'node:fs';
import { once } from 'node:events';

const out = process.argv[2] || 'sample-artefact.txt';
const targetBytes = Math.round((Number(process.argv[3]) || 26) * 1024 * 1024);

/* mulberry32: tiny, seeded, so the file is byte-identical run to run. */
let seed = 0x9e3779b9;
const rnd = () => {
  seed |= 0; seed = (seed + 0x6D2B79F5) | 0;
  let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
  t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
  return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};

const WORDS = ['grid', 'atlas', 'node', 'substation', 'feeder', 'export', 'capacity',
  'circuit', 'transformer', 'headroom', 'REPD', 'geodesy', 'bearing', 'radius',
  'polyline', 'cartridge', 'sentinel', 'teleprint', 'lane', 'manifest'];

const ws = createWriteStream(out);
const write = async s => { if (!ws.write(s)) await once(ws, 'drain'); };

let written = 0;
let section = 0;
while (written < targetBytes) {
  const name = `SECTION-${String(section).padStart(4, '0')}-${WORDS[section % WORDS.length].toUpperCase()}`;
  const begin = `===== BEGIN ${name} =====\n`;
  await write(begin); written += begin.length;

  /* A body of plausible source-dump lines, plus the occasional rule line of
     '=' so the byte histogram is not degenerate. */
  const lines = 400 + Math.floor(rnd() * 800);
  let body = '';
  for (let i = 0; i < lines; i++) {
    if (i % 37 === 0) { body += '='.repeat(60) + '\n'; continue; }
    const n = 4 + Math.floor(rnd() * 10);
    const parts = [];
    for (let j = 0; j < n; j++) parts.push(WORDS[Math.floor(rnd() * WORDS.length)]);
    body += `${String(i).padStart(5, ' ')}  ${parts.join(' ')} = ${(rnd() * 1000).toFixed(3)}\n`;
  }
  await write(body); written += body.length;

  const end = `===== END ${name} =====\n`;
  await write(end); written += end.length;
  section += 1;
}
ws.end();
await once(ws, 'finish');
console.log(`wrote ${out}  ${written} bytes (${(written / 1048576).toFixed(2)} MB)  ${section} sections `
  + `(${section * 2} BEGIN/END markers)`);

Codex Corpus Review

A Python module in GPU Drivers for Global Grid that reads cartridge, provenance and corpus GPU analysis, using SHA-256.

storagegpu-drivers-for-global-grid / codex/corpus-review.py · lines 1–47 of 47

What it does
It loads cartridge, provenance and corpus GPU analysis. Uses libraries argparse, hashlib, json, pathlib, subprocess. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'codex'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file cartridge.json; JSON file corpus-gpu-analysis.json; command-line arguments. Out: JSON file provenance.json.
Downstream impact
Used directly by 1 file: Codex Overnight (gpu-drivers-for-global-grid).
What it achieves
Bounded cross-repository GPU similarity screening using the attributed Claude harness. It accepts `--reviews` and `--out`.
Why it matters
Run by Codex Overnight.
Application
gpu-drivers-for-global-grid · codex · Python module
Uses
argparse, hashlib, json, pathlib, subprocess
Used by
run by Codex Overnight (script call)
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
gpu-drivers-for-global-grid@6c47912a8dde251ffebd92ff129e6a0c11c4ebfe codex/corpus-review.py:1-47 · blob 5152d058422adb238ebf1124e8ff743df5ab4305 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
"""Bounded cross-repository GPU similarity screening using the attributed Claude harness."""
import argparse
import hashlib
import json
from pathlib import Path
import subprocess

p = argparse.ArgumentParser()
p.add_argument('--reviews', type=Path, required=True)
p.add_argument('--out', type=Path, required=True)
a = p.parse_args(); a.out.mkdir(parents=True, exist_ok=True)
repo = Path(__file__).resolve().parents[1]
corpus = a.out / 'source-sample'; corpus.mkdir(exist_ok=True)
reports = [json.loads(x.read_text(encoding='utf8')) for x in sorted(a.reviews.glob('*/cartridge.json'))]
selected = []; total = 0
# Fair round-robin sampling: no one monolith consumes the whole budget.
for index in range(40):
    for r in reports:
        candidates = [f for f in r['files'] if Path(f['path']).suffix in ('.js', '.mjs', '.cjs')]
        if index >= len(candidates): continue
        f = candidates[index]
        if total + f['bytes'] > 64_000_000 or len(selected) >= 1000: continue
        raw = subprocess.check_output(['git', '-C', str(repo.parent / r['repository']), 'cat-file', 'blob', f['blob']], timeout=30)
        assert hashlib.sha256(raw).hexdigest() == f['sha256']
        name = f'{len(selected):04d}-{r["repository"]}.mjs'
        (corpus / name).write_bytes(raw)
        selected.append({'sample': name, 'repository': r['repository'], 'commit': r['commit'], **f})
        total += len(raw)
source = repo / 'claude/analyse-corpus-gpu.mjs'
raw = source.read_bytes(); code = raw.decode('utf8')
old = 'chromium.launch({ headless: false, args: ['
assert code.count(old) == 1
# Launch-only adapter: preserve the attributed shaders and all measured logic.
adapted = code.replace(old, "chromium.launch({ headless: true, channel: 'chrome', args: [")
harness = a.out / 'attributed-corpus-harness.mjs'; harness.write_text(adapted, encoding='utf8')
(a.out / 'provenance.json').write_text(json.dumps({'source': str(source), 'sourceSha256': hashlib.sha256(raw).hexdigest(), 'adapter': 'Headless installed Chrome only; no shader changes', 'files': selected, 'bytes': total, 'scope': 'Bounded committed-source sample; similarity selects candidates, not proven duplication'}, indent=2), encoding='utf8')
if len(selected) < 2: raise ValueError('At least two source files required')
subprocess.run(['node', str(harness), str(corpus), '--out', str(a.out), '--top', '20'], check=True, timeout=120)
r = json.loads((a.out / 'corpus-gpu-analysis.json').read_text(encoding='utf8'))
assert r['verification']['histogramMatchesCpu'] is True
lookup = {f['sample']: f for f in selected}
brief = '# GPU cross-repository review cartridge\n\n' + f'{len(selected)} sampled files, {total} bytes. GPU histograms verified against CPU.\n\n## Exact duplicates\n\n' + str(r['exactDuplicates']['groups']) + ' exact groups in this sample.\n\n## Candidates for review, NOT proven duplicate code\n\n'
for pair in r['nearDuplicates']['top'][:12]:
    left, right = lookup[pair['a']], lookup[pair['b']]
    brief += f'- {left["repository"]}/{left["path"]} ↔ {right["repository"]}/{right["path"]}: histogram cosine {pair["cosine"]}; verify semantics before any extraction.\n'
(a.out / 'REVIEW.md').write_text(brief, encoding='utf8')
print('JSON ' + json.dumps({'gpuCorpusVerified': True, 'files': len(selected), 'bytes': total, 'card': str(a.out / 'REVIEW.md')}))

Codex Learn Repo

A Python command-line tool in GPU Drivers for Global Grid that reads phase, vocabulary, unresolved imports and clusters, using SHA-256 and k-means.

storagegpu-drivers-for-global-grid / codex/learn-repo.py · lines 1–106 of 106 · Entry point · pattern cluster (shared by 5 files)

What it does
It loads phase, vocabulary, unresolved imports and clusters. Defines 7 functions or classes, including git, save, words, train, cluster. Uses libraries os, argparse, collections, datetime, hashlib. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'codex'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file phase.json; JSON file files.json; JSON file vocabulary.json; JSON file unresolved-imports.json; JSON file clusters.json; command-line arguments.
Downstream impact
Used directly by 1 file: Codex Learning Night (gpu-drivers-for-global-grid).
What it achieves
It is built from the git step (`git`), the save step (`save`) and the words step (`words`). Local unsupervised lexical model; proposals only, never executes target source. It accepts `--root`, `--out` and `--seed`.
Why it matters
Run by Codex Learning Night.
Application
gpu-drivers-for-global-grid · codex · Python CLI
Uses
os, argparse, collections, datetime, hashlib, json, math, posixpath
Used by
run by Codex Learning Night (script call)
Produces
git, save, words, train, cluster, main
Defines here
git, save, words, train, cluster, main, phase
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 codex/learn-repo.py:1-106 · blob 6f0032b10b4f397883bf1bc6e6e23b38e69d7336 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
"""Local unsupervised lexical model; proposals only, never executes target source."""
import os
os.environ.setdefault('OPENBLAS_NUM_THREADS','2')
os.environ.setdefault('OMP_NUM_THREADS','2')
import argparse, collections, datetime as dt, hashlib, json, math, posixpath, re, subprocess, time
from pathlib import Path
import numpy as np

def git(root,*args): return subprocess.check_output(['git','-C',str(root),*args],timeout=120)
def save(path,value):
    raw=json.dumps(value,indent=2).encode()
    if len(raw)>8_000_000: raise ValueError('JSON partition exceeds8MB')
    path.write_bytes(raw)
def words(text):
    # Remove quoted literals before feature extraction; this is lexical preprocessing,
    # not a language parser or a proof of secret removal. Models stay offline.
    text=re.sub(r'''"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`''',' ',text)
    return [w.lower() for w in re.findall(r'[A-Za-z_][A-Za-z_0-9]{2,79}',text) if w.lower() not in {'const','function','return','import','from','export','default','true','false','null','none','self','this','else','async','await','undefined','var','let','for','while','class','def','try','catch','with','new'}]
def train(counts):
    df=collections.Counter(t for row in counts for t in row)
    vocabulary=[t for t,n in df.most_common(2048) if n<max(3,len(counts)*.95)] or list(df)[:2048]
    lookup={t:i for i,t in enumerate(vocabulary)}
    x=np.zeros((len(counts),len(vocabulary)),dtype=np.float32)
    idf=np.array([math.log((1+len(counts))/(1+df[t]))+1 for t in vocabulary],dtype=np.float32)
    for i,row in enumerate(counts):
        for term,n in row.items():
            if term in lookup:x[i,lookup[term]]=1+math.log(n)
    x*=idf;x/=np.maximum(np.linalg.norm(x,axis=1,keepdims=True),1e-12)
    return x,vocabulary,idf
def cluster(x,seed):
    if len(x)==0 or x.shape[1]==0:return np.zeros(len(x),dtype=int),np.empty((0,x.shape[1])),0
    k=min(12,len(x),max(1,int(math.sqrt(len(x)/2))))
    rng=np.random.default_rng(seed);centres=x[rng.choice(len(x),k,replace=False)].copy();labels=np.zeros(len(x),dtype=int)
    for iteration in range(30):
        new=np.argmax(x@centres.T,axis=1)
        if iteration and np.array_equal(new,labels):break
        labels=new
        for j in range(k):
            subset=x[labels==j]
            if len(subset):centres[j]=subset.mean(axis=0)
        centres/=np.maximum(np.linalg.norm(centres,axis=1,keepdims=True),1e-12)
    return labels,centres,iteration+1
def main():
    p=argparse.ArgumentParser();p.add_argument('--root',type=Path,required=True);p.add_argument('--out',type=Path,required=True);p.add_argument('--seed',type=int,default=0);p.add_argument('--reuse',type=Path);p.add_argument('--commit');a=p.parse_args();a.out.mkdir(parents=True,exist_ok=True);start=time.monotonic()
    def phase(name):save(a.out/'phase.json',{'phase':name,'at':dt.datetime.now(dt.timezone.utc).isoformat()})
    if a.reuse:
        phase('Load pinned learned model');meta=json.loads((a.reuse/'manifest.json').read_text());files=json.loads((a.reuse/'files.json').read_text());vocabulary=json.loads((a.reuse/'vocabulary.json').read_text());x=np.concatenate([np.load(a.reuse/f,allow_pickle=False)['x'] for f in meta['vectorShards']],axis=0)
    else:
        phase('Pin inventory');head=git(a.root,'rev-parse',a.commit or 'HEAD').decode().strip();entries=[]
        for row in git(a.root,'ls-tree','-rlz',head).split(b'\0'):
            if not row:continue
            info,name=row.split(b'\t',1);fields=info.decode().split();name=name.decode('utf-8',errors='replace')
            if len(fields)==4 and fields[1]=='blob':entries.append((fields[2],int(fields[3]),name))
        tracked={e[2] for e in entries};seen=set();eligible=[];excluded=collections.Counter()
        for sha,size,name in entries:
            reason=None
            if Path(name).suffix.lower() not in {'.js','.mjs','.cjs','.py','.ts','.tsx','.html','.css','.yml','.yaml'}:reason='not source type'
            elif any(part in {'node_modules','vendor','data','results','versions','receipts','homepage_versions'} for part in name.lower().split('/')) or re.search(r'(?:^|/)\d{12}(?:/|$)',name):reason='archived/vendor/data scope'
            elif size>2_000_000:reason='source blob over2MB'
            elif sha in seen:reason='exact duplicate blob'
            if reason:excluded[reason]+=1;continue
            seen.add(sha);eligible.append((sha,size,name))
        selected=eligible[:5000];phase('Learn lexical features and trace relative imports');files=[];counts=[];unresolved=[]
        for sha,size,name in selected:
            raw=git(a.root,'cat-file','blob',sha);text=raw.decode('utf-8',errors='replace');count=collections.Counter(words(text));counts.append(dict(count.most_common(500)))
            imports=sorted(set(re.findall(r'''(?:from\s*|require\(\s*|import\(\s*)['"]([^'"]+)''',text)))
            local=[]
            for ref in imports:
                if not ref.startswith('.'):continue
                target=posixpath.normpath(posixpath.join(posixpath.dirname(name),ref.split('?')[0]));options=[target]+[target+s for s in ['.js','.mjs','.ts','/index.js','/index.mjs']];resolved=next((q for q in options if q in tracked),None);local.append({'import':ref,'resolved':resolved})
                if resolved is None:unresolved.append({'path':name,'import':ref,'status':'static unresolved; bundler/runtime mapping may explain'})
            files.append({'path':name,'blob':sha,'sha256':hashlib.sha256(raw).hexdigest(),'bytes':len(raw),'lines':len(text.splitlines()),'relativeImports':local,'termsBeforeCap':len(count),'termsRetained':min(500,len(count))})
        x,vocabulary,idf=train(counts);del counts
        phase('Five-month commit history');churn=collections.Counter();commit_count=0
        proc=subprocess.Popen(['git','-C',str(a.root),'log',head,'--since=153 days ago','--format=COMMIT:%H','--numstat'],stdout=subprocess.PIPE,text=True,encoding='utf-8',errors='replace')
        for line in proc.stdout:
            if line.startswith('COMMIT:'):commit_count+=1
            else:
                parts=line.rstrip('\n').split('\t',2)
                if len(parts)==3:churn[parts[2]]+=1
        if proc.wait():raise RuntimeError('History scan failed')
        shards=[]
        for offset in range(0,len(x),512):
            name=f'vectors-{offset:05d}.npz';np.savez_compressed(a.out/name,x=x[offset:offset+512]);shards.append(name)
        # Empty owners still get a model shard so subsequent load remains explicit.
        if not shards:np.savez_compressed(a.out/'vectors-00000.npz',x=x);shards=['vectors-00000.npz']
        np.savez_compressed(a.out/'idf.npz',idf=idf)
        meta={'schema':'ventus.lexical-learning.v1','repository':a.root.name,'commit':head,'trackedFiles':len(entries),'eligible':len(eligible),'selected':len(selected),'unselected':max(0,len(eligible)-len(selected)),'exclusions':dict(excluded),'dimensions':len(vocabulary),'vectorShards':shards,'historyCommits':commit_count,'historyDays':153,'hotspots':[{'path':p,'touches':n} for p,n in churn.most  … [line shortened here: 653 characters; full line on GitHub]
        save(a.out/'manifest.json',meta);save(a.out/'files.json',files);save(a.out/'vocabulary.json',vocabulary);save(a.out/'unresolved-imports.json',unresolved)
    phase('Cluster and measure assignment stability');labels,centres,iterations=cluster(x,a.seed);groups=[]
    for j,c in enumerate(centres):
        ids=np.where(labels==j)[0];representatives=sorted(ids,key=lambda i:float(x[i]@c),reverse=True)[:8]
        groups.append({'cluster':j,'files':len(ids),'terms':[vocabulary[i] for i in np.argsort(c)[-8:][::-1]],'representatives':[files[i]['path'] for i in representatives]})
    # Compare neighbour co-membership rather than raw cluster IDs, which can permute.
    stability=None
    if a.reuse and (a.reuse/'labels.npz').exists():
        baseline=np.load(a.reuse/'labels.npz',allow_pickle=False)['labels'];rng=np.random.default_rng(42)
        if len(labels)>1:
            pairs=rng.integers(0,len(labels),size=(min(10000,len(labels)**2),2));valid=pairs[:,0]!=pairs[:,1];pairs=pairs[valid];same=baseline[pairs[:,0]]==baseline[pairs[:,1]];current=labels[pairs[:,0]]==labels[pairs[:,1]]
            stability={'samplePairs':len(pairs),'coMembershipAgreement':float(np.mean(same==current)),'baselineSameClusterPairs':int(same.sum()),'warning':'Agreement is dominated by different-cluster pairs; not semantic accuracy.'}
    np.savez_compressed(a.out/'labels.npz',labels=labels)
    result={'repository':meta['repository'],'commit':meta['commit'],'seed':a.seed,'iterations':iterations,'groups':groups,'stability':stability,'seconds':round(time.monotonic()-start,2),'status':'review candidates only'};save(a.out/'clusters.json',result)
    lines=[f'# {meta["repository"]}: lexical review card',f'Commit {meta["commit"]}; seed{a.seed}; {len(files)} source blobs. Not a correctness verdict.','']
    for g in groups:lines+=['- '+', '.join(g['terms'])+': '+str(g['files'])+' files; start at '+', '.join(g['representatives'][:3])]
    (a.out/'REVIEW.md').write_text('\n'.join(lines),encoding='utf-8');phase('Complete');print(json.dumps({'repository':meta['repository'],'files':len(files),'groups':len(groups),'seconds':result['seconds']}))
if __name__=='__main__':main()

Codex Learn Repo Test

A test in GPU Drivers for Global Grid. It is built from the model test class (`ModelTest`).

testgpu-drivers-for-global-grid / codex/learn-repo.test.py · lines 1–11 of 11 · Entry point

What it does
It tests its inputs. Defines ModelTest, test_known_terms, test_reproducible_seed, test_empty. Uses libraries importlib.util, unittest, numpy, pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'codex'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Downstream impact
It is itself an entry point (test); no other file was found loading it.
What it achieves
Defines `ModelTest`, `test_known_terms`, `test_reproducible_seed` and 1 more.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
gpu-drivers-for-global-grid · codex · test
Uses
importlib.util, unittest, numpy, pathlib
Used by
none found
Produces
ModelTest
Defines here
ModelTest, test_known_terms, test_reproducible_seed, test_empty
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 codex/learn-repo.test.py:1-11 · blob 98b773adddadae6790a86881f1093e5d1c7911c2 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
import importlib.util,unittest,numpy as np
from pathlib import Path
spec=importlib.util.spec_from_file_location('learner',Path(__file__).with_name('learn-repo.py'));m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m)
class ModelTest(unittest.TestCase):
 def test_known_terms(self):
  x,v,idf=m.train([{'capacitor':3,'voltage':2},{'capacitor':3,'voltage':2},{'pipeline':4,'news':2}]);self.assertTrue(np.allclose(x[0],x[1]));self.assertAlmostEqual(float(x[0]@x[2]),0);self.assertTrue(np.allclose(np.linalg.norm(x,axis=1),1))
 def test_reproducible_seed(self):
  x=np.eye(8,dtype=np.float32);a,_,_=m.cluster(x,5);b,_,_=m.cluster(x,5);self.assertTrue(np.array_equal(a,b))
 def test_empty(self):
  x,v,_=m.train([]);labels,_,_=m.cluster(x,0);self.assertEqual(len(labels),0)
if __name__=='__main__':unittest.main()

Codex Learning Night

A Python module in GPU Drivers for Global Grid that reads plan, budget stop, clusters and phase.

storagegpu-drivers-for-global-grid / codex/learning-night.py · lines 1–60 of 60 · Not reached from any entry point (candidate for review) · pattern phase (shared by 6 files)

What it does
It loads plan, budget stop, clusters and phase. Defines save, phase, end. Uses libraries argparse, datetime, json, os, shutil. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'codex'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file PLAN.json; JSON file BUDGET-STOP.json; JSON file clusters.json; JSON file STATUS.json; JSON file phase.json; JSON file FINAL.json; command-line arguments.
What it achieves
It is built from the save step (`save`), the phase step (`phase`) and the end step (`end`). Bounded local learning queue through a fixed deadline; no source mutations/deployments. It accepts `--out`, `--until` and `--roots`.
Why it matters
No other file in the estate was found to import it.
Application
gpu-drivers-for-global-grid · codex · Python module
Uses
Codex Learn Repo (script call), argparse, datetime, json, os, shutil, subprocess, sys, time
Used by
none found
Produces
save, phase, end
Defines here
save, phase, end
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 codex/learning-night.py:1-60 · blob eb7d3bf0bcbef0c2db2496864584df061c07f5a4 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
"""Bounded local learning queue through a fixed deadline; no source mutations/deployments."""
import argparse,datetime as dt,json,os,shutil,subprocess,sys,time
from pathlib import Path
import psutil
p=argparse.ArgumentParser();p.add_argument('--out',type=Path,required=True);p.add_argument('--until',required=True);p.add_argument('--roots',type=Path,required=True);a=p.parse_args();a.out.mkdir(parents=True,exist_ok=True)
deadline=dt.datetime.fromisoformat(a.until).timestamp()
if not time.time()<deadline<=time.time()+12*3600:raise ValueError('Deadline must be within12hours')
here=Path(__file__).parent;owners=json.loads(a.roots.read_text());roots=[Path(r) for r in owners if (Path(r)/'.git').exists()]
start=time.time();active={};jobs=[];queued=set();hour=-1;completed=0;failed=0
def save(name,value):
    target=a.out/name;tmp=target.with_suffix('.tmp');tmp.write_text(json.dumps(value,indent=2),encoding='utf-8');os.replace(tmp,target)
def phase(path):
    try:return json.loads(path.read_text()).get('phase')
    except (OSError,ValueError):return 'starting or writing checkpoint'
def end(proc):
    try:
        root=psutil.Process(proc.pid);children=root.children(recursive=True)
        for child in children:child.terminate()
        root.terminate();_,alive=psutil.wait_procs(children+[root],timeout=3)
        for child in alive:child.kill()
    except psutil.Error:pass
save('PLAN.json',{'deadlineUTC':a.until,'repositories':[str(r) for r in roots],'initialStages':['commit inventory','lexical TF-IDF learning','relative dependency scan','five-month history','spherical clustering','review card'],'initialStageCount':6*len(roots),'hourly':'Repeat clustering with independent seeds on pinned models; detect changed local HEADs and reindex. No fabricated work or automatic  … [line shortened here: 545 characters; full line on GitHub]
try:
    while time.time()<deadline and not (a.out/'STOP').exists():
        current=int((time.time()-start)//3600)
        if current!=hour:
            hour=current
            for root in roots:
                head=subprocess.check_output(['git','-C',str(root),'rev-parse','HEAD'],text=True,timeout=20).strip()
                base=a.out/'models'/root.name/head
                mode='stability' if (base/'manifest.json').exists() else 'learn'
                key=(str(root),head,hour)
                if key not in queued:jobs.append({'root':str(root),'head':head,'base':str(base),'hour':hour,'mode':mode});queued.add(key)
        ram=psutil.virtual_memory().available/1024**3;battery=psutil.sensors_battery();reason=None
        if ram<2.5:reason='RAM reserve'
        if battery and not battery.power_plugged:reason='AC power required'
        if shutil.disk_usage(a.out).free<5*1024**3:reason='Disk reserve'
        if sum(f.stat().st_size for f in a.out.rglob('*') if f.is_file())>350_000_000:reason='350MB evidence budget';save('BUDGET-STOP.json',{'at':time.time()});break
        for pid,record in list(active.items()):
            proc=record['process'];job=record['job'];expired=time.time()-record['started']>900
            if reason or expired:end(proc)
            code=proc.poll()
            if code is not None:
                record['log'].close();ok=code==0 and (record['out']/'clusters.json').exists();completed+=int(ok);failed+=int(not ok)
                receipt={**job,'exitCode':code,'ok':ok,'reason':reason or ('15minute job timeout' if expired else None),'output':str(record['out'])}
                save(f'job-{len(queued):04d}-{pid}.json',receipt);del active[pid]
        if not reason:
            while jobs and len(active)<2 and psutil.virtual_memory().available/1024**3>3.2:
                job=jobs.pop(0);base=Path(job['base']);out=base if job['mode']=='learn' else a.out/'stability'/Path(job['root']).name/f'hour-{hour:02d}'
                out.mkdir(parents=True,exist_ok=True);cmd=[sys.executable,str(here/'learn-repo.py'),'--root',job['root'],'--out',str(out),'--seed',str(job['hour']),'--commit',job['head']]
                if job['mode']=='stability':cmd+=['--reuse',str(base)]
                log=(out/'worker.log').open('w',encoding='utf-8');proc=subprocess.Popen(cmd,stdout=log,stderr=subprocess.STDOUT,creationflags=subprocess.CREATE_NO_WINDOW,env=dict(os.environ,OPENBLAS_NUM_THREADS='2',OMP_NUM_THREADS='2'))
                try:handle=psutil.Process(proc.pid);handle.cpu_affinity(list(range(min(8,psutil.cpu_count()))));handle.nice(psutil.BELOW_NORMAL_PRIORITY_CLASS)
                except psutil.Error:pass
                active[proc.pid]={'process':proc,'log':log,'job':job,'started':time.time(),'out':out}
        save('STATUS.json',{'at':dt.datetime.now(dt.timezone.utc).isoformat(),'pid':os.getpid(),'deadlineUTC':a.until,'hour':hour,'completedJobs':completed,'failedJobs':failed,'queuedNow':len(jobs),'active':[{'pid':pid,'repository':Path(r['job']['root']).name,'mode':r['job']['mode'],'phase':phase(r['out']/'phase.json')} for pid,r in active.items()],'availableGiB':ram,'state':reason or ('learning'   … [line shortened here: 525 characters; full line on GitHub]
        time.sleep(3 if active or jobs else 15)
finally:
    for r in active.values():end(r['process']);r['log'].close()
    save('FINAL.json',{'finishedUTC':dt.datetime.now(dt.timezone.utc).isoformat(),'completedJobs':completed,'failedJobs':failed,'remaining':jobs,'scope':'Review candidates only; no deployments performed.'})

Codex Monitor Local

A web page in GPU Drivers for Global Grid. It is built from the update step (`update`).

rendergpu-drivers-for-global-grid / codex/monitor-local.html · lines 1–24 of 24 · Entry point

What it does
It draws its content. Defines el, update. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'codex'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file status.json. Out: web page.
Downstream impact
It is itself an entry point (page); no other file was found loading it.
What it achieves
VENTUS overnight terminal. It reads `/status.json`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
gpu-drivers-for-global-grid · codex · page
Uses
none found
Used by
none found
Produces
el, update
Defines here
el, update
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 codex/monitor-local.html:1-24 · blob 2dbc6e085b6e43da16de63c0dfdb5c4d735da193 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: agent_infra · users: ai_agent · canonical: unknown
<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>VENTUS overnight terminal</title>
<style>body{background:#0b0d0f;color:#d0d0d0;font:16px/1.6 Consolas,monospace;max-width:820px;margin:24px auto;padding:16px}h1{font-size:20px}progress{appearance:none;width:100%;height:20px;border:1px solid #888;background:#303438}progress::-webkit-progress-bar{background:#303438}progress::-webkit-progress-value{background:#c4c9ce}progress::-moz-progress-bar{background:#c4c9ce}p{margin:18px 0}outp  … [line shortened here: 449 characters; full line on GitHub]
<h1>[ VENTUS / OVERNIGHT LOCAL RUNNERS ]</h1><p id="health">Checking heartbeat...</p><p id="mode"></p>
<p>Eight-hour observation window <progress id="time" max="28800" value="0"></progress><span id="elapsed"></span></p>
<p>Evidence-backed review checkpoints <progress id="review" max="96" value="0"></progress><span id="count"></span></p>
<p>CPU utilisation <progress id="cpu" max="100" value="0"></progress><span id="cpuLabel"></span></p>
<p>GPU utilisation <progress id="gpu" max="100" value="0"></progress><span id="gpuLabel"></span></p>
<p>Repository learning queue <progress id="learning" max="27" value="0"></progress><output id="learningLabel"></output></p>
<p><output id="detail"></output></p><small>Read-only local monitor. Refreshes every five seconds; independently records heartbeat health every thirty seconds. The existing supervisor handles resource limits and hourly measurements. Elapsed time is not review completion. No claim of CPU thermal protection: no validated CPU temperature sensor is configured.</small>
<script>
const el=id=>document.getElementById(id);
async function update(){try{const r=await fetch('/status.json',{cache:'no-store'});if(!r.ok)throw Error();const d=await r.json(),s=d.status,m=s.sample||{};
el('health').textContent=(d.alert?'ALERT: '+d.alert:'SUPERVISOR HEARTBEAT OK')+' / checked '+d.checkedAt;
el('mode').textContent=s.active?'Active: '+s.active:s.pauseReason||'No active job';
el('time').value=s.elapsedSeconds||0;el('elapsed').textContent=Math.floor((s.elapsedSeconds||0)/60)+' / 480 minutes; stops '+d.deadlineUTC;
el('review').value=d.verified;el('count').textContent=d.verified+' / '+d.scopeCount+' verified; pending checkpoints require engineering review';
el('cpu').value=m.cpuPercent||0;el('cpuLabel').textContent=(m.cpuPercent??'unknown')+'%';el('gpu').value=m.gpuPercent||0;el('gpuLabel').textContent=(m.gpuPercent??'unknown')+'%';
const l=d.learning||{},finished=d.learningFinal?.finishedUTC,queued=l.queuedNow||0,idle=!l.active?.length;
const learningState=finished?'Finished at '+finished:(queued&&idle&&l.availableGiB<=3.2?'Waiting for launch RAM reserve: '+Number(l.availableGiB).toFixed(2)+' GiB available; more than 3.2 GiB required. '+queued+' jobs queued.':l.state||'No learning status');
const total=(l.completedJobs||0)+(l.failedJobs||0)+(l.queuedNow||0)+(l.active?.length||0);el('learning').max=Math.max(1,total);el('learning').value=l.completedJobs||0;el('learningLabel').textContent='\n'+(l.completedJobs||0)+' jobs completed / '+total+' due so far; '+(l.failedJobs||0)+' failed. '+learningState+'\n'+(l.futureHourlySweeps||0)+' further hourly sweeps; deadline '+(l.deadlineUTC||'unkn  … [line shortened here: 574 characters; full line on GitHub]
el('detail').textContent='Available RAM: '+Number(m.availableGiB||0).toFixed(2)+' GiB\nGPU temperature: '+(m.gpuTemperature??'unknown')+' C\nGPU memory: '+(m.gpuMemoryUsedMiB??'?')+' / '+(m.gpuMemoryTotalMiB??'?')+' MiB\nCompleted runner jobs: '+s.completed+'; failed jobs: '+s.failed+'\nThese counts do not certify application correctness.';
}catch{el('health').textContent='MONITOR UNAVAILABLE — displayed values may be stale';}}
update();setInterval(update,5000);
</script></html>