GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / AI agents and coordination / spiders / tools

Codex Audit Runtime Source and 6 more files

A Python command-line tool in the drivers folder of Teleprinter that uses SHA-256. It is built from the digest step (`digest`), the frame step (`frame`) and the inspect step (`inspect`).

520 lines of JavaScript and Python and HTML from spiders, teleprinter, in 7 files. Topic: AI agents and coordination. Section 1653 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. Validate 60x Program storage · spiders / tools/validate-60x-program.mjs lines 1–94
  2. Demo render · teleprinter / demo.html lines 1–100
  3. Codex App Outcomes storage · teleprinter / drivers/codex/app-outcomes.mjs lines 1–56
  4. Codex App Print Browser interaction · teleprinter / drivers/codex/app-print.browser.mjs lines 1–40
  5. Codex Audit Runtime Source storage · teleprinter / drivers/codex/audit-runtime-source.py lines 1–123
  6. Codex Audit Source Print storage · teleprinter / drivers/codex/audit-source-print.py lines 1–87
  7. Codex Capture Geometry Test test · teleprinter / drivers/codex/capture-geometry.test.mjs lines 1–20

Validate 60x Program

A JavaScript module in the tools folder of Spiders that uses SHA-256. It is built from the value after helper (`valueAfter`).

storagespiders / tools/validate-60x-program.mjs · lines 1–94 of 94 · Entry point · pattern valueAfter (shared by 3 files)

What it does
It loads data. Defines valueAfter, oid. Uses libraries node:crypto, node:fs, node:path. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'spiders'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file 20260904-60x-program.json; command-line arguments.
Downstream impact
Used directly by 2 files: 60x Program Proof Workflow (spiders); Llama Advisory Workflow (spiders).
What it achieves
Its name says it validates 60x program. Defines `valueAfter` and `oid`.
Why it matters
Run by 60x Program Proof Workflow and Llama Advisory Workflow.
Application
spiders · tools · JavaScript module
Uses
node:crypto, node:fs, node:path
Used by
run by 60x Program Proof Workflow (workflow run), run by Llama Advisory Workflow (workflow run)
Produces
valueAfter, oid
Defines here
valueAfter, oid
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
spiders@78fc0f90bd5ca73f3d5d7c0e0b7b5712cfe781e5 tools/validate-60x-program.mjs:1-94 · blob f48bfe02e7f0b42631c061653e8c69ea775a6018 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
#!/usr/bin/env node
import { createHash } from 'node:crypto';
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, relative, resolve } from 'node:path';

const args = process.argv.slice(2);
const valueAfter = flag => {
  const index = args.indexOf(flag);
  return index < 0 ? null : args[index + 1];
};
const programPath = resolve(valueAfter('--program') || 'control/20260904-60x-program.json');
const receiptPath = valueAfter('--receipt');
const bytes = readFileSync(programPath);
const sha256 = createHash('sha256').update(bytes).digest('hex');
let program;
const errors = [];
const findings = [];
try { program = JSON.parse(bytes); }
catch (error) { errors.push(`program JSON does not parse: ${error.message}`); program = {}; }

const oid = value => /^[0-9a-f]{40}$/.test(String(value || ''));
if (program.schema !== 'spiders.autonomous-build-program.v1') errors.push('unknown schema');
if (program.total_slots !== 60) errors.push('total_slots must be 60');
if (program.promotion?.authority !== 'CEO' || program.promotion?.candidate_may_promote !== false)
  errors.push('promotion must remain CEO-only and unavailable to candidate branches');
if (program.execution?.order !== 'discovery-author-serial-cutter')
  errors.push('execution order must be discovery-author-serial-cutter');
if (program.execution?.serial_cutter?.no_op !== 'reject'
    || program.execution?.serial_cutter?.same_input_replay !== 'same-release')
  errors.push('serial cutter lacks no-op or idempotence protection');

const delivery = program.state_delivery || {};
for (const key of ['identity_from_state', 'receiver_acceptance_required', 'delivered_state_readback_required', 'fallback_distinguished'])
  if (delivery[key] !== true) errors.push(`state_delivery.${key} must be true`);

const lanes = Array.isArray(program.lanes) ? program.lanes : [];
if (lanes.length !== 2) errors.push('exactly two isolated build lanes are required');
for (const lane of lanes) {
  if (!lane || typeof lane.id !== 'string' || typeof lane.repository !== 'string') errors.push('lane identity is incomplete');
  if (!lane?.isolated_branch || lane.isolated_branch === 'main') errors.push(`${lane?.id || 'lane'} is not isolated from main`);
  if (!oid(lane?.base_commit) || !oid(lane?.observed_head)) errors.push(`${lane?.id || 'lane'} lacks exact base/head identity`);
  if (lane?.target_slots !== 30) errors.push(`${lane?.id || 'lane'} must own 30 slots`);
}

const queue = Array.isArray(program.queue) ? program.queue : [];
if (queue.length !== 60) errors.push(`queue has ${queue.length} entries, expected 60`);
const slots = new Set();
for (const item of queue) {
  if (!Number.isInteger(item?.slot) || item.slot < 1 || item.slot > 60 || slots.has(item.slot))
    errors.push(`invalid or duplicate slot ${String(item?.slot)}`);
  slots.add(item?.slot);
  if (!['pipeline', 'grid'].includes(item?.lane)) errors.push(`slot ${item?.slot} has unknown lane`);
  if (!Number.isInteger(item?.lane_iteration) || item.lane_iteration < 1 || item.lane_iteration > 30)
    errors.push(`slot ${item?.slot} has invalid lane_iteration`);
  if (item?.phases?.join('>') !== 'discovery>author>serial-cutter')
    errors.push(`slot ${item?.slot} breaks the phase order`);
  if (item?.commit !== null && !oid(item.commit)) errors.push(`slot ${item?.slot} has invalid commit`);
  if (item?.parent !== null && !oid(item.parent)) errors.push(`slot ${item?.slot} has invalid parent`);
  if (!Array.isArray(item?.tests)) errors.push(`slot ${item?.slot} has no test receipt list`);
  if (typeof item?.receipt_path !== 'string' || !item.receipt_path) errors.push(`slot ${item?.slot} has no receipt path`);
  const passing = item?.state === 'passed' && item.tests.length > 0 && item.tests.every(test => test.result === 'pass');
  if (item?.qualifies !== passing) errors.push(`slot ${item?.slot} qualification disagrees with its state/tests`);
  if (!passing) findings.push(`slot ${item?.slot} remains ${item?.state || 'unknown'} and is retained but not counted`);
}
for (const laneId of ['pipeline', 'grid']) {
  const items = queue.filter(item => item.lane === laneId);
  if (items.length !== 30) errors.push(`${laneId} has ${items.length} slots, expected 30`);
  const sequence = items.map(item => item.lane_iteration).sort((a, b) => a - b);
  if (sequence.join(',') !== Array.from({ length: 30 }, (_, index) => index + 1).join(','))
    errors.push(`${laneId} lane iterations are not exactly 1..30`);
}
for (const attempt of program.retained_attempts || []) {
  if (!['failed', 'superseded'].includes(attempt?.state)) errors.push('retained attempt must be failed or superseded');
  if (attempt?.qualifies !== false) errors.push('failed/superseded attempt must not count');
  if (!oid(attempt?.commit) || !Array.isArray(attempt?.tests)) errors.push('retained attempt lacks commit/test evidence');
}

const result = {
  schema: 'spiders.autonomous-build-receipt.v1',
  program: relative(process.cwd(), programPath).replaceAll('\\', '/'),
  program_sha256: sha256,
  slot_count: queue.length,
  qualifying_count: queue.filter(item => item.qualifies).length,
  structural_errors: errors,
  informational_findings: findings,
  status: errors.length ? 'fail' : 'pass',
};
if (receiptPath) {
  const output = resolve(receiptPath);
  mkdirSync(dirname(output), { recursive: true });
  writeFileSync(output, JSON.stringify(result, null, 2) + '\n');
}
console.log(JSON.stringify(result, null, 2));
process.exitCode = errors.length ? 1 : 0;

Demo

A web page in Teleprinter that renders with WebGL.

renderteleprinter / demo.html · lines 1–100 of 100 · Entry point

What it does
It draws its content. Defines say, run. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'teleprinter'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
Out: web page; WebGL/WebGPU drawing.
Downstream impact
It is itself an entry point (page); no other file was found loading it.
What it achieves
Defines `say` and `run`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
teleprinter · / · page
Uses
Teleprinter (import)
Used by
none found
Produces
say, run
Defines here
say, run
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
teleprinter@e45bfe38c3040b0f36f7df94ce262b63db8d0b60 demo.html:1-100 · blob ed5697cf8da7d109f7f2a43058adb9cff75d1ed4 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: agent_infra · users: ai_agent · canonical: unknown
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Teleprinter</title>
<style>
  :root { color-scheme: dark; }
  body { margin:0; background:#08151c; color:#eaf4f6;
         font:14px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace; }
  header { padding:18px 20px; border-bottom:1px solid #1d3b46; }
  h1 { margin:0; font-size:16px; letter-spacing:.22em; text-transform:uppercase; }
  p.lede { margin:6px 0 0; color:#8fb3bd; }
  main { padding:20px; display:grid; gap:16px; max-width:860px; }
  button { font:inherit; min-height:48px; padding:12px 18px; cursor:pointer;
           color:#bdfaff; background:#0f2833; border:1px solid #37656b; }
  button:hover { background:#164152; }
  .row { display:flex; gap:10px; flex-wrap:wrap; }
  pre { background:#0b1e27; border:1px solid #1d3b46; padding:12px;
        overflow:auto; margin:0; white-space:pre-wrap; }
  .swatch { display:grid; grid-template-columns:repeat(6,1fr); gap:6px; }
  .swatch div { height:54px; display:grid; place-items:center; font-size:11px; color:#04121a; }
  canvas { width:100%; max-width:420px; border:1px solid #1d3b46; display:block; }
  .note { color:#8fb3bd; }
</style>
</head>
<body>
<header>
  <h1>Teleprinter</h1>
  <p class="lede">Emit the record exactly as it was. No paper, no reflow, no clever processing.</p>
</header>
<main>
  <div class="row">
    <button id="pdf">Teleprint this screen &rarr; PDF</button>
    <button id="png">&rarr; PNG</button>
    <button id="compose">Force the compose fallback</button>
  </div>

  <p class="note">Everything below is here so a record can be checked against
  what was on screen: a WebGL canvas, a 2D canvas, colour, and live text.</p>

  <div class="swatch" id="swatch"></div>
  <canvas id="gl" width="420" height="150"></canvas>
  <pre id="out">Nothing emitted yet.</pre>
</main>

<script type="module">
import { teleprint, canDisplayCapture } from './teleprinter.js';

const out = document.getElementById('out');
const say = (text) => { out.textContent = text; };

/* Colour, so a record that has silently lost backgrounds is obvious. */
const swatch = document.getElementById('swatch');
['#ff4400','#ffb000','#39d353','#22b8cf','#7c6bff','#ff5ea8'].forEach((c) => {
  const cell = document.createElement('div');
  cell.style.background = c;
  cell.textContent = c;
  swatch.appendChild(cell);
});

/* A WebGL canvas WITHOUT preserveDrawingBuffer - the exact case that prints
   blank through a browser print pipeline, and the reason the compose path
   re-reads every canvas rather than trusting it. */
const gl = document.getElementById('gl').getContext('webgl');
if (gl) {
  gl.clearColor(0.05, 0.35, 0.42, 1);
  gl.clear(gl.COLOR_BUFFER_BIT);
}

const run = async (options, label) => {
  say(`${label}…`);
  try {
    const r = await teleprint(options);
    say([
      `method       ${r.method}${r.note ? '  (' + r.note + ')' : ''}`,
      `size         ${r.width} x ${r.height}  ${r.orientation}`,
      `file         ${r.filename}  ${r.bytes.toLocaleString()} bytes`,
      `devicePixelRatio ${window.devicePixelRatio}`,
      `viewport     ${innerWidth} x ${innerHeight}`,
      '',
      r.method === 'display'
        ? 'This is the compositor output: what was on the screen, at screen resolution.'
        : 'This is a RECONSTRUCTION, not a screen grab. See README, Path B.'
    ].join('\n'));
  } catch (error) {
    say(`failed: ${error}`);
  }
};

document.getElementById('pdf').onclick = () => run({}, 'Capturing');
document.getElementById('png').onclick = () => run({ format: 'png' }, 'Capturing');
document.getElementById('compose').onclick = () => run({ method: 'compose' }, 'Composing');

say(canDisplayCapture()
  ? 'Display capture is available: the PDF and PNG buttons will take a real screen grab.\nYou will be asked which tab or window to share.'
  : 'Display capture is NOT available in this browser (iOS Safari has no getDisplayMedia).\nEvery button will use the compose fallback, which is a reconstruction.');
</script>
</body>
</html>

Codex App Outcomes

A JavaScript module in the drivers folder of Teleprinter.

storageteleprinter / drivers/codex/app-outcomes.mjs · lines 1–56 of 56 · Not reached from any entry point (candidate for review)

What it does
Uses libraries node:url, node:fs/promises, node:path, node:assert/strict, node:child_process. 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). README: "`drivers/codex/app-outcomes.json` records nine additional Pipeline/Atlas/Test Code checks in Chrome, Firefox and mobile WebKit emulation."
Inputs & outputs
In: command-line arguments. Out: JSON file app-outcomes.json.
What it achieves
Historical launcher check for . New menu-only builds use `file-print-compatibility.mjs` and `fifty-prints.mjs`.
Why it matters
No other file in the estate was found to import it.
Application
teleprinter · drivers/codex · JavaScript module
Uses
Codex Driver (script call), node:url, node:fs/promises, node:path, node:assert/strict, node:child_process
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
teleprinter@e45bfe38c3040b0f36f7df94ce262b63db8d0b60 drivers/codex/app-outcomes.mjs:1-56 · blob 4d555e16363ef0e071ffd0d3326651d99862c331 · 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
/** Historical launcher check for 202609051419. New menu-only builds use
 * file-print-compatibility.mjs and fifty-prints.mjs. Downloads are deleted. */
import {pathToFileURL,fileURLToPath} from 'node:url';
import fs from 'node:fs/promises';
import path from 'node:path';
import assert from 'node:assert/strict';
import {spawnSync} from 'node:child_process';
import {attachScreenCapture,clickAndReadDownload} from './driver.mjs';
const {chromium,firefox,webkit}=await import(pathToFileURL(process.env.PLAYWRIGHT_MODULE).href);
const base=process.argv[2];
if(!base) throw new Error('Supply the served generation URL.');
const here=path.dirname(fileURLToPath(import.meta.url));
const results=[];
for(const [name,type,options,viewport] of [
 ['Chrome',chromium,{channel:'chrome'},{width:1400,height:900}],
 ['Firefox',firefox,{},{width:1200,height:800}],
 ['WebKit mobile emulation',webkit,{},{width:393,height:852}]
]) {
 if(process.env.TELEPRINTER_BROWSER && name!==process.env.TELEPRINTER_BROWSER) continue;
 const browser=await type.launch({headless:true,...options});
 try {
  for(const route of ['','pipeline/','atlas/?repd_ref=2484&technology=wind_offshore']) {
   const context=await browser.newContext({viewport,acceptDownloads:true});
   const page=await context.newPage(); let captured;
   try {
    await attachScreenCapture(page,{onCapture:png=>{captured=png;}});
    await page.goto(new URL(route,base).href,{waitUntil:'domcontentloaded',timeout:60000});
    await page.getByRole('button',{name:'Teleprinter',exact:true}).waitFor({timeout:90000});
    if(route.startsWith('pipeline')) await page.locator('#tbody tr').first().waitFor({timeout:60000});
    if(route.startsWith('atlas')) {
     await page.locator('canvas').first().waitFor({timeout:60000});
     await page.getByText(/TEST CODE repd-2484 \| ENGINE COMPLETED/).waitFor({timeout:60000});
    }
    await page.getByRole('button',{name:'Teleprinter',exact:true}).click();
    const downloaded=await clickAndReadDownload(page,page.getByRole('button',{name:'Print source code',exact:true}),{timeout:60000});
    assert.ok(downloaded.ok,downloaded.error);
    const source=downloaded.bytes.toString('utf8');
    assert.match(source,/PRINT SOURCE CODE/);
    assert.match(source,/https:\/\/github.com\/Ventusltd\/testcode/);
    assert.match(source,/drivers|teleprinter/);
    assert.ok(source.length>10000,'source coverage unexpectedly small');
    await page.getByRole('button',{name:'Copy source code',exact:true}).click();
    const pdf=await clickAndReadDownload(page,page.getByRole('button',{name:'Print',exact:true}),{timeout:60000});
    assert.ok(pdf.ok,pdf.error);
    assert.ok(captured);
    const inspected=spawnSync('python',[path.join(here,'inspect-pdf.py')],{input:JSON.stringify({pdf:pdf.bytes.toString('base64'),png:captured.toString('base64')}),encoding:'utf8',maxBuffer:1000000});
    assert.equal(inspected.status,0,inspected.stderr);
    results.push({browser:name,route,ok:true,...(route.startsWith('atlas')?{gridEngineCompleted:true}:{}),sourceBytes:downloaded.bytes.length,pdf:JSON.parse(inspected.stdout)});
    console.log(`PASS ${name} ${route||'landing'}: ${downloaded.bytes.length} source bytes, screen pixels preserved`);
   } catch(error) {results.push({browser:name,route,ok:false,error:String(error)}); console.log(`FAIL ${name} ${route}: ${error.message}`);}
   finally {captured=undefined;await context.close().catch(()=>{});}
  }
 } finally {await browser.close();}
}
await fs.writeFile(path.join(here,'app-outcomes.json'),JSON.stringify({createdAt:new Date().toISOString(),base,physicalDevices:false,results},null,2)+'\n');
if(results.some(result=>!result.ok))process.exitCode=1;

Codex App Print Browser

A JavaScript module in the drivers folder of Teleprinter.

interactionteleprinter / drivers/codex/app-print.browser.mjs · lines 1–40 of 40 · Not reached from any entry point (candidate for review)

What it does
It loads data. Uses libraries node:fs/promises, node:path, node:url, node:assert/strict. Side effects: changes the web page (DOM); 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).
Inputs & outputs
In: command-line arguments. Out: JSON file results.json.
What it achieves
It responds to teleprint events.
Why it matters
No other file in the estate was found to import it.
Application
teleprinter · drivers/codex · JavaScript module
Uses
Codex Driver (import), node:fs/promises, node:path, node:url, node:assert/strict
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
teleprinter@e45bfe38c3040b0f36f7df94ce262b63db8d0b60 drivers/codex/app-print.browser.mjs:1-40 · blob a7047dbfed4d440bcd2adc6a02f5a188eafd764f · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
import fs from 'node:fs/promises';
import path from 'node:path';
import {fileURLToPath,pathToFileURL} from 'node:url';
import assert from 'node:assert/strict';
import {clickAndReadDownload} from './driver.mjs';
const here=path.dirname(fileURLToPath(import.meta.url));
const {chromium,firefox,webkit}=await import(pathToFileURL('C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright/index.mjs'));
const base=process.argv[2] || 'https://globalgrid2050.com/testcode/202609051623/';
const output=path.join('C:/Users/vikra/OneDrive/Desktop/offline-screenshots','app-print-'+new Date().toISOString().replace(/[:.]/g,'-'));
await fs.mkdir(output,{recursive:true});
const count=Number(process.env.PRINT_CASES||6), records=[];
for(let i=0;i<count;i++){
 const engine=[chromium,firefox,webkit][Math.floor(i/2)%3], name=['chrome','firefox','webkit'][Math.floor(i/2)%3];
 const viewport=i%2?{width:393,height:852}:{width:1365,height:900};
 const record={name,viewport};let browser;
 try{
  browser=await engine.launch({headless:true,...(name==='chrome'?{channel:'chrome'}:{})});
  const context=await browser.newContext({viewport,deviceScaleFactor:i%2?2:1,acceptDownloads:true});
  await context.addInitScript(()=>{window.__forbiddenPrintCalls=0;window.print=()=>{window.__forbiddenPrintCalls++;throw Error('Browser print forbidden');};if(navigator.mediaDevices)navigator.mediaDevices.getDisplayMedia=()=>{window.__forbiddenPrintCalls++;throw Error('Screen sharing forbidden');};window.__codexTeleprinterCapture=()=>{window.__forbiddenPrintCalls++;throw Error('Host screenshot inj  … [line shortened here: 424 characters; full line on GitHub]
  if(process.env.LOCAL_DRIVERS==='1')await context.route('**/teleprinter/**',async route=>{
    const rel=new URL(route.request().url()).pathname.split('/teleprinter/')[1];
    if(['controls.js','print-screen.js','app-frame.js','vendor/html2canvas-1.4.1.mjs'].includes(rel))return route.fulfill({body:await fs.readFile(path.join(here,rel)),contentType:'text/javascript'});
    return route.continue();
  });
  const page=await context.newPage();record.errors=[];page.on('pageerror',e=>record.errors.push(String(e)));
  await page.goto(new URL('atlas/?repd_ref=2470&technology=wind_offshore&latitude=52.1374391&longitude=2.1708996&zoom=12&project=East+Anglia+3+(EA+3)&capacity_mw=1400',base).href,{waitUntil:'domcontentloaded'});
  await page.getByText(/TEST CODE repd-2470 \| ENGINE COMPLETED/).first().waitFor({timeout:90000});
  const toggle=page.locator('#gridatlas-dash-toggle');if(!/HIDE LAYERS/.test(await toggle.innerText()))await toggle.click();
  await page.locator('.gm-title').filter({hasText:/^File$/i}).click();
  await page.evaluate(()=>document.querySelector('#codex-teleprinter').addEventListener('teleprint',e=>window.__printReceipt=e.detail));
  const downloaded=await clickAndReadDownload(page,page.locator('button[data-gm-export]').filter({hasText:/Print/i}).first(),{timeout:60000});
  assert.ok(downloaded.ok,downloaded.error);
  await page.screenshot({path:path.join(output,`${i}-${name}-reference.png`),scale:'device'});
  await fs.writeFile(path.join(output,`${i}-${name}.pdf`),downloaded.bytes);
  record.receipt=await page.evaluate(()=>window.__printReceipt);record.forbiddenCalls=await page.evaluate(()=>window.__forbiddenPrintCalls);
  assert.equal(record.forbiddenCalls,0);assert.equal(record.receipt.method,'app-render');assert.equal(record.receipt.width,viewport.width*(i%2?2:1));assert.equal(record.receipt.height,viewport.height*(i%2?2:1));
  record.ok=true;
 }catch(error){record.ok=false;record.error=String(error);}finally{await browser?.close();records.push(record);await fs.writeFile(path.join(output,'results.json'),JSON.stringify(records,null,2));console.log(JSON.stringify(record));}
}
console.log(output);if(records.some(r=>!r.ok))process.exitCode=1;

Codex Audit Runtime Source

A Python command-line tool in the drivers folder of Teleprinter that uses SHA-256. It is built from the digest step (`digest`), the frame step (`frame`) and the inspect step (`inspect`).

storageteleprinter / drivers/codex/audit-runtime-source.py · lines 1–123 of 123 · Entry point · pattern inspect (shared by 40 files)

What it does
It lists and searches its content. Defines digest, main, frame, inspect. Uses libraries argparse, base64, concurrent.futures, hashlib, json. 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: command-line arguments. Out: JSON file audit.json.
Downstream impact
Used directly by 1 file: Codex Offline Source Batch (teleprinter).
What it achieves
Offline verification of original Codex source TXT frames and JS/JSON syntax. It accepts `--report`, `--repo` and `--no-extract`.
Why it matters
Run by Codex Offline Source Batch.
Application
teleprinter · drivers/codex · Python CLI
Uses
argparse, base64, concurrent.futures, hashlib, json, os, pathlib, re
Used by
run by Codex Offline Source Batch (script call)
Produces
digest, main
Defines here
digest, main, frame, inspect
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
teleprinter@e45bfe38c3040b0f36f7df94ce262b63db8d0b60 drivers/codex/audit-runtime-source.py:1-123 · blob 73ded80e9c915c9d19d852c363739c43776410f3 · 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
"""Offline verification of original Codex source TXT frames and JS/JSON syntax.
No extracted JavaScript is executed; node --check performs parsing only.
"""
import argparse
import base64
import concurrent.futures
import hashlib
import json
import os
from pathlib import Path
import re
import subprocess
import time
from urllib.parse import urlparse


def digest(data): return hashlib.sha256(data).hexdigest()


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("source", type=Path)
    parser.add_argument("output", type=Path)
    parser.add_argument("--report", type=Path)
    parser.add_argument("--repo", type=Path, help="Optional local Git repository for independent pinned-source byte comparison")
    parser.add_argument("--no-extract", action="store_true", help="Keep only audit reports, avoiding duplicate source-body files")
    args = parser.parse_args()
    if args.output.resolve().is_relative_to(Path(__file__).resolve().parents[2]):
        parser.error("Extracted source belongs outside Git.")
    args.output.mkdir(parents=True, exist_ok=True)
    raw = args.source.read_bytes()
    started = time.monotonic()
    errors = []
    bodies = []

    def frame(prefix, suffix, count, expected, encoding="utf-8"):
        start = raw.find(prefix.encode())
        if start < 0: raise ValueError("Missing frame: " + prefix[:120])
        start += len(prefix.encode())
        end = raw.find(suffix.encode(), start)
        if end < 0: raise ValueError("Missing frame end")
        encoded = raw[start:end]
        data = base64.b64decode(encoded, validate=True) if encoding == "base64" else encoded
        if len(data) != count or digest(data) != expected: raise ValueError("Frame byte count or SHA256 mismatch")
        return data

    marker = b"===== BEGIN DIAGNOSTIC MANIFEST =====\n"
    begin = raw.index(marker) + len(marker)
    manifest = json.loads(raw[begin:raw.index(b"\n===== END DIAGNOSTIC MANIFEST =====", begin)])
    base = manifest["baseManifest"]
    if not re.fullmatch(r"[a-f0-9]{40}", base["commit"]): raise ValueError("Invalid pinned Git commit")
    pinned = frame(f"===== BEGIN PINNED SOURCE | bytes={base['byteCount']} | sha256={base['sha256']} =====\n", "\n===== END PINNED SOURCE =====", base["byteCount"], base["sha256"])
    for item in base.get("files", []):
        if item.get("status") == "omitted" or "startByte" not in item: continue
        data = pinned[item["startByte"]:item["startByte"] + item["byteCount"]]
        if len(data) != item["byteCount"] or digest(data) != item["sha256"]:
            errors.append("Pinned file integrity: " + item["path"])
        if args.repo:
            committed = subprocess.run(["git", "-C", str(args.repo), "show", base["commit"] + ":" + item["path"]], stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=30, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
            if committed.returncode or committed.stdout != data:
                errors.append("Pinned source differs from local Git commit: " + item["path"])
        bodies.append(("pinned:" + item["path"], data))
    current = re.search(rb"===== BEGIN CURRENT DOCUMENT \| bytes=(\d+) \| sha256=([a-f0-9]{64}) =====\n", raw)
    if not current: raise ValueError("Missing current document")
    frame(current[0].decode(), "\n===== END CURRENT DOCUMENT =====", int(current[1]), current[2].decode())
    represented = []
    for resource in manifest["resources"]:
        if resource["status"] == "already-represented":
            represented.append(resource["url"])
            continue
        if resource["status"] != "included":
            errors.append("Unavailable resource: " + resource["url"])
            continue
        name = json.dumps(resource["url"], ensure_ascii=False, separators=(",", ":"))
        data = frame(f"===== BEGIN RESOURCE {name} | originalBytes={resource['byteCount']} | encoding={resource['encoding']} | sha256={resource['sha256']} =====\n", f"\n===== END RESOURCE {name} =====", resource["byteCount"], resource["sha256"], resource["encoding"])
        bodies.append((resource["url"], data))
    errors.extend(str(error) for error in manifest.get("failures", []))
    unique = {}
    for name, data in bodies: unique.setdefault((name, digest(data)), data)

    def inspect(item):
        (name, sha), data = item
        result = {"name": name, "bytes": len(data), "sha256": sha, "ok": True, "syntax": "not-applicable"}
        pathname = urlparse(name).path
        javascript = pathname.endswith((".js", ".mjs", "/+esm"))
        json_data = pathname.endswith((".json", ".geojson"))
        if javascript:
            run = subprocess.run(["node", "--check", "--input-type=module"], input=data, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=30, cwd=args.output, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
            result.update(syntax="javascript-parse-only", ok=run.returncode == 0)
            if run.returncode: result["error"] = run.stderr.decode("utf8", "replace")[:2000]
        elif json_data:
            result["syntax"] = "json"
            try: json.loads(data)
            except Exception as error: result.update(ok=False, error=str(error))
        if not args.no_extract:
            (args.output / (sha + (".mjs" if javascript else ".json" if json_data else ".bin"))).write_bytes(data)
        return result

    workers = min(8, max(1, (os.cpu_count() or 2) // 2))
    with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:
        results = list(pool.map(inspect, unique.items()))
    errors.extend(result["name"] + ": " + result["error"] for result in results if not result["ok"])
    state = manifest["state"]
    badge = re.search(r"TEST CODE [^\n]+ENGINE COMPLETED[^\n]*", state.get("visibleText", ""))
    report = {"schema": "codex-offline-runtime-source-audit-v1", "artifact": {"filename": args.source.name, "bytes": len(raw), "sha256": digest(raw)},
              "url": state.get("url"), "capturedAt": state.get("capturedAt"), "sourceCommit": base.get("commit"),
              "viewport": state.get("viewport"), "printedEngineBadge": badge[0] if badge else None,
              "workers": workers, "seconds": round(time.monotonic() - started, 2), "pinnedGitBytesChecked": bool(args.repo),
              "counts": {"verifiedBodies": len(bodies), "javascriptChecks": sum(r["syntax"] == "javascript-parse-only" for r in results), "jsonChecks": sum(r["syntax"] == "json" for r in results), "failures": len(errors)},
              "representedSourceTransport": represented, "ok": not errors, "errors": errors, "results": results,
              "limitations": manifest.get("limitations", []) + ["Offline syntax parsing does not execute code or validate grid mathematics.", "Self-consistent hashes do not independently authenticate a GitHub deployment.", "Browser discovery cannot prove universal dependency completeness."]}
    encoded = json.dumps(report, indent=2, ensure_ascii=True) + "\n"
    (args.output / "audit.json").write_text(encoded, encoding="utf8")
    if args.report: args.report.write_text(encoded, encoding="utf8")
    print(json.dumps({key: report[key] for key in ["counts", "workers", "seconds", "ok", "printedEngineBadge"]}))
    return 0 if report["ok"] else 1


if __name__ == "__main__":
    try: raise SystemExit(main())
    except Exception as error:
        print(json.dumps({"ok": False, "error": str(error)}))
        raise SystemExit(1)

Codex Audit Source Print

A Python command-line tool in the drivers folder of Teleprinter that uses SHA-256. It is built from the inspect step (`inspect`).

storageteleprinter / drivers/codex/audit-source-print.py · lines 1–87 of 87 · Entry point · pattern inspect (shared by 40 files)

What it does
It lists and searches its content. Defines inspect, main. Uses libraries pathlib, argparse, datetime, hashlib, json. 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: command-line arguments. Out: JSON file audit.json.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Offline structural audit of a source-print PDF; never executes extracted code. It accepts `--report`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
teleprinter · drivers/codex · Python CLI
Uses
pathlib, argparse, datetime, hashlib, json, re, sys, pymupdf
Used by
none found
Produces
inspect, main
Defines here
inspect, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
teleprinter@e45bfe38c3040b0f36f7df94ce262b63db8d0b60 drivers/codex/audit-source-print.py:1-87 · blob 90513b83d571e9e8881482b252be0d9f44fcd288 · 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
"""Offline structural audit of a source-print PDF; never executes extracted code.

Usage: python audit-source-print.py INPUT.pdf OFFLINE_OUTPUT_DIR [--report REPORT.json]
Exit 0: no detected structural failures (not proof of full dependency completeness).
Exit 1: missing/truncated resources or an unsupported/unreadable inventory.
"""
from pathlib import Path
import argparse
import datetime
import hashlib
import json
import re
import sys
import pymupdf


def inspect(filename, output):
    raw = filename.read_bytes()
    with pymupdf.open(stream=raw, filetype="pdf") as pdf:
        pages = [page.get_text() for page in pdf]
        metadata = pdf.metadata
    output.mkdir(parents=True, exist_ok=True)
    text = "\n".join(pages)
    (output / "extracted-text.txt").write_text(text, encoding="utf8")
    # Remove PDF furniture only in the parser's copy; retain original extraction.
    clean = re.sub(r"(?m)^(?:blob:https?://.*|Page \d+ of \d+|\d{2}/\d{2}/\d{4}, \d{2}:\d{2})\s*$", "", text)
    prefix = clean.split("THE LIVE PAGE AS IT STOOD", 1)[0]
    entries = []
    pattern = r"(?m)^\s*(\d+)\.\s+(https?://[\s\S]+?)\s+(\d+)\s+chars\s*\u00b7([\s\S]*?)(?=^\s*\d+\.\s+https?://|^={8,}|\Z)"
    for match in re.finditer(pattern, prefix):
        number, url, size, detail = match.groups()
        url = re.sub(r"\s+", "", url)
        detail = " ".join(detail.split())
        truncated = re.search(r"TRUNCATED to first (\d+)", detail)
        script = "browser (script)" in detail or "+esm" in url or bool(re.search(r"\.(?:m?js)(?:[?#]|$)", url))
        entries.append({"index": int(number), "url": url, "printedOriginalCharacters": int(size),
                        "truncated": bool(truncated), "printedRetainedCharacters": int(truncated[1]) if truncated else None,
                        "script": script, "printedDescription": detail})
    failures = [{"url": url, "printedFailure": failure.strip()} for url, failure in
                re.findall(r"(?m)^-\s+(https?://\S+)\s*\n\s*(HTTP\s+\d+[^\n]*)", prefix)]
    reasons = []
    if not entries or [item["index"] for item in entries] != list(range(1, len(entries) + 1)):
        reasons.append("Inventory missing, non-contiguous, or unsupported: completeness cannot be assessed.")
    declared = re.search(r"NOT READ\s*--\s*(\d+)\s+resource", prefix)
    if declared and int(declared[1]) != len(failures):
        reasons.append("Unread-resource count does not match parsed failure entries.")
    truncated = [item for item in entries if item["truncated"]]
    scripts = [item for item in truncated if item["script"]]
    if failures: reasons.append(f"{len(failures)} dependency failures are printed in the record.")
    if truncated: reasons.append(f"{len(truncated)} resource bodies are explicitly truncated, including {len(scripts)} scripts.")
    generation = re.search(r'"generation"\s*:\s*"(\d+)"', prefix)
    report = {"schema": "codex-offline-source-print-audit-v1", "checkedAt": datetime.datetime.now(datetime.timezone.utc).isoformat(),
              "artifact": {"filename": filename.name, "bytes": len(raw), "sha256": hashlib.sha256(raw).hexdigest(), "pages": len(pages)},
              "generation": generation[1] if generation else None, "pdfMetadata": metadata,
              "counts": {"inventoryEntries": len(entries), "truncatedResources": len(truncated), "truncatedScripts": len(scripts), "failedResources": len(failures)},
              "ok": not reasons, "reasons": reasons, "resources": entries, "failures": failures,
              "limits": ["Offline only: HTTP failures are what the artifact reports; no live network request is made.",
                         "PDF text is a paginated representation, not original source bytes; no byte-integrity or JavaScript syntax pass is claimed.",
                         "No extracted source is executed. A clean structural audit cannot prove every browser dependency is present."]}
    return report


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("input", type=Path)
    parser.add_argument("output", type=Path)
    parser.add_argument("--report", type=Path)
    args = parser.parse_args()
    repo = Path(__file__).resolve().parents[2]
    if args.output.resolve().is_relative_to(repo):
        parser.error("Extracted source must stay outside the Git repository.")
    try:
        report = inspect(args.input.resolve(), args.output.resolve())
        encoded = json.dumps(report, indent=2, ensure_ascii=True) + "\n"
        (args.output / "audit.json").write_text(encoded, encoding="utf8")
        if args.report:
            args.report.parent.mkdir(parents=True, exist_ok=True)
            args.report.write_text(encoded, encoding="utf8")
        print(json.dumps({key: report[key] for key in ["generation", "counts", "ok", "reasons"]}))
        return 0 if report["ok"] else 1
    except Exception as error:
        print(json.dumps({"ok": False, "error": str(error)}))
        return 1


if __name__ == "__main__":
    sys.exit(main())

Codex Capture Geometry Test

A test in the drivers folder of Teleprinter that checks Capture Geometry.

testteleprinter / drivers/codex/capture-geometry.test.mjs · lines 1–20 of 20 · Not reached from any entry point (candidate for review)

What it does
It tests its inputs. Uses libraries node:test, node:assert/strict.
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).
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
Guards the behaviour of Capture Geometry.
Application
teleprinter · drivers/codex · test
Uses
Capture Geometry (import), node:test, node:assert/strict
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
teleprinter@e45bfe38c3040b0f36f7df94ce262b63db8d0b60 drivers/codex/capture-geometry.test.mjs:1-20 · blob 0a78c11c7a06b0c108d39dd416c77add48b2700d · GitHub at these lines
State
achieves: name · context: readme_derived · stage: unknown · effects: none found · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
import test from 'node:test';
import assert from 'node:assert/strict';
import {captureGeometry, assertStableGeometry} from './capture-geometry.mjs';
test('fractional display scaling retains the renderer backing size', () => {
  const g = captureGeometry(2048, 972, 1.875);
  assert.equal(g.pixelWidth,3840); assert.equal(g.pixelHeight,1822);
  assert.doesNotThrow(()=>assertStableGeometry(g,g,{width:3840,height:1822}));
});
test('odd viewport sizes and common scaling factors agree with canvas floor semantics',()=>{
  for(const ratio of [1,1.25,1.5,1.875,2,3]) {
    const g=captureGeometry(393,853,ratio);
    assert.equal(g.pixelWidth,Math.floor(393*ratio)); assert.equal(g.pixelHeight,Math.floor(853*ratio));
  }
});
test('real resize and wrong frame remain failures',()=>{
  const g=captureGeometry(393,853,2);
  assert.throws(()=>assertStableGeometry(g,captureGeometry(394,853,2),{width:786,height:1706}),/resized/);
  assert.throws(()=>assertStableGeometry(g,g,{width:785,height:1706}),/unexpected/);
  assert.throws(()=>captureGeometry(10000,10000,3),/large/);
});