GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / AI agents and coordination / teleprinter / drivers/codex

Codex Native Display Proof and 6 more files

A JavaScript module in the drivers folder of Teleprinter that fetches native display results, using SHA-256.

601 lines of JavaScript and Python from teleprinter, in 7 files. Topic: AI agents and coordination. Section 1657 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. Codex Native Display Proof interaction · teleprinter / drivers/codex/native-display-proof.mjs lines 1–178
  2. Codex Offline Evidence Inventory storage · teleprinter / drivers/codex/offline-evidence-inventory.py lines 1–64
  3. Codex Offline PDF Sweep storage · teleprinter / drivers/codex/offline-pdf-sweep.py lines 1–81
  4. Codex Offline Source Batch storage · teleprinter / drivers/codex/offline-source-batch.py lines 1–53
  5. Codex Outcome Test test · teleprinter / drivers/codex/outcome.test.mjs lines 1–112
  6. Codex Png Pixels Test test · teleprinter / drivers/codex/png-pixels.test.mjs lines 1–105
  7. Codex Prepare Demo other · teleprinter / drivers/codex/prepare-demo.mjs lines 1–8

Codex Native Display Proof

A JavaScript module in the drivers folder of Teleprinter that fetches native display results, using SHA-256.

interactionteleprinter / drivers/codex/native-display-proof.mjs · lines 1–178 of 178 · Not reached from any entry point (candidate for review)

What it does
It fetches native display results. Uses libraries node:fs/promises, node:path, node:url, node:child_process, node:crypto. Side effects: changes the web page (DOM); reads or writes files; makes network requests; 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 results.json; JSON file native-display-results.json.
What it achieves
Real Chrome display-capture flow. No host screenshot provider or replacement pixels. 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 (script call), node:fs/promises, node:path, node:url, node:child_process, node:crypto, 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/native-display-proof.mjs:1-178 · blob f96c5ca9c8d81cd76ef64a95d6ca46d8128e20a8 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, process · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
/** Real Chrome display-capture flow. No host screenshot provider or replacement pixels. */
import fs from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { spawnSync } from 'node:child_process';
import { randomBytes, createHash } from 'node:crypto';
import assert from 'node:assert/strict';
import { clickAndReadDownload } from './driver.mjs';

const args = process.argv.slice(2);
const options = {};
while (args.length) { const key = args.shift(); if (!key.startsWith('--') || !args.length) throw new Error('Use --name value options.'); options[key.slice(2)] = args.shift(); }
const base = new URL(options.base || 'http://127.0.0.2:8887/testcode/202609051517/');
const folderName = `native-display-${new Date().toISOString().replace(/[:.]/g, '-')}-${randomBytes(3).toString('hex')}`;
const output = path.resolve(options.output || path.join(process.env.USERPROFILE || process.cwd(), 'OneDrive/Desktop/offline-screenshots', folderName));
const root = path.dirname(fileURLToPath(import.meta.url));
const repo = path.resolve(root, '../..');
if (output === repo || output.startsWith(repo + path.sep)) throw new Error('Native proof artifacts must be stored outside the Git repository.');
await fs.mkdir(output, { recursive: false });
const modulePath = options.playwright || process.env.PLAYWRIGHT_MODULE || path.join(process.env.USERPROFILE || '', 'OneDrive/Documents/GitHub/globalgrid2050/uk_renewables_pipeline/v9.7/node_modules/playwright/index.mjs');
const { chromium } = await import(pathToFileURL(modulePath).href);
const flags = ['--auto-select-desktop-capture-source=Entire screen', '--allow-http-screen-capture', '--auto-accept-this-tab-capture'];
const servedEngineUrl = new URL('teleprinter/print-screen.js', base).href;
const servedEngineResponse = await fetch(servedEngineUrl);
assert.ok(servedEngineResponse.ok, 'Cannot read served screen engine');
const servedEngineSha256 = createHash('sha256').update(Buffer.from(await servedEngineResponse.arrayBuffer())).digest('hex');
const cases = [
  { id: 'atlas-desktop', app: 'atlas', width: 1365, height: 900, dpr: 1, mobile: false },
  { id: 'atlas-mobile-portrait', app: 'atlas', width: 393, height: 852, dpr: 3, mobile: true },
  { id: 'pipeline-landscape', app: 'pipeline', width: 1200, height: 800, dpr: 1, mobile: false },
];
const inspector = `import sys,json,base64,io
from pypdf import PdfReader
import pymupdf
p=json.load(sys.stdin); data=base64.b64decode(p['pdf']); settings=p['settings']; initial=p['initial']; drawing=p['drawing']
r=PdfReader(io.BytesIO(data),strict=True); assert len(r.pages)==1, 'expected one page'
page=r.pages[0]; objects=page['/Resources']['/XObject']; assert len(objects)==1, 'expected one screen image'
ref=next(iter(objects.values())); image=ref.get_object(); width=int(image['/Width']); height=int(image['/Height'])
assert width==settings['width'] and height==settings['height'], 'PDF pixels differ from native track settings'
assert width==drawing['width'] and height==drawing['height'], 'PDF pixels differ from actual drawn source dimensions'
rgb=image.get_data(); assert len(rgb)==width*height*3, 'invalid RGB payload size'
assert any(rgb), 'native captured RGB is entirely zero'
assert float(page.mediabox.width)==width, 'page width changed image width'
doc=pymupdf.open(stream=data,filetype='pdf'); rectangles=doc[0].get_image_rects(ref.idnum); assert len(rectangles)==1
rect=rectangles[0]; assert rect.x0==0 and rect.width==width and rect.height==height, 'screen image scaled/cropped'
header=float(rect.y0); footer=float(page.mediabox.height)-float(rect.y1)
assert header>0 and footer>0, 'header/footer bands must be outside the screen image'
content=page.get_contents().get_data().decode('latin1'); assert f'{width} 0 0 {height} 0 ' in content
text=page.extract_text(); assert 'GLOBALGRID2050' in text and 'generation' in text, 'header/footer text missing'
print(json.dumps({'imageWidth':width,'imageHeight':height,'pageWidth':float(page.mediabox.width),'pageHeight':float(page.mediabox.height),'headerHeight':header,'footerHeight':footer,'rgbBytes':len(rgb),'nonzeroRgb':True,'imageUnscaled':True,'validPdf':True,'furnitureOutsideImage':True,'initialSettingsGeometryMatch':width==initial['width'] and height==initial['height'],'drawTimeSettingsGeometryMatc  … [line shortened here: 448 characters; full line on GitHub]
`;
const report = {
  startedAt: new Date().toISOString(), base: base.href, offlineArtifacts: output,
  scope: 'Real native getDisplayMedia call, initial and draw-time browser-provided track settings, actual drawn frame and PDF geometry, nonzero RGB, external header/footer bands, and stopped tracks.',
  limitations: ['Post-download screenshots are visual context only and are NOT pixel-equality references.', 'This does not prove original monitor physical resolution or exact source-frame color/pixel fidelity.', 'Mobile portrait is desktop Chrome emulation, not physical iPhone/Safari.', 'Writer byte/pixel retention is measured by separate unit and host-capture tests.'],
  originalGetDisplayMediaDelegated: true, hostScreenshotCaptureProvider: false, flags, cases: [],
  chooserAutomation: 'Chrome auto-select/auto-accept flags automate the native chooser only; getDisplayMedia and returned track/frame data remain original browser implementations.',
  temporaryEngineOverride: options['print-screen'] ? path.resolve(options['print-screen']) : null,
  servedEngineUrl, servedEngineSha256,
};
for (const specimen of cases) {
  let browser, context, page;
  const result = { ...specimen, ok: false };
  try {
    browser = await chromium.launch({ channel: 'chrome', headless: true, args: flags });
    result.browserVersion = browser.version();
    context = await browser.newContext({ viewport: { width: specimen.width, height: specimen.height }, deviceScaleFactor: specimen.dpr, isMobile: specimen.mobile, hasTouch: specimen.mobile, acceptDownloads: true });
    if (options['print-screen']) {
      const engineBytes = await fs.readFile(path.resolve(options['print-screen']));
      result.temporaryEngineSha256 = createHash('sha256').update(engineBytes).digest('hex');
      await context.route('**/teleprinter/print-screen.js', route => route.fulfill({ status: 200, contentType: 'text/javascript', body: engineBytes }));
    }
    await context.addInitScript(() => {
      const proof = { calls: [], tracks: [], draws: [], unavailable: false };
      window.__nativeDisplayProof = proof;
      const originalDraw = CanvasRenderingContext2D.prototype.drawImage;
      CanvasRenderingContext2D.prototype.drawImage = function(...args) {
        if (proof.tracks.some(track => track.kind === 'video' && track.readyState === 'live')) {
          const source = args[0];
          if (source instanceof HTMLVideoElement || source instanceof ImageBitmap) proof.draws.push({ instrument: source.constructor.name, width: source.videoWidth || source.width, height: source.videoHeight || source.height, arguments: args.slice(1), trackSettings: proof.tracks.filter(track => track.kind === 'video').map(track => track.getSettings()), delegatedToOriginal: true });
        }
        return originalDraw.apply(this, args);
      };
      const media = navigator.mediaDevices;
      if (!media?.getDisplayMedia) { proof.unavailable = true; return; }
      const original = media.getDisplayMedia.bind(media);
      media.getDisplayMedia = async (...args) => {
        const call = { startedAt: new Date().toISOString(), arguments: args, delegatedToOriginal: true };
        proof.calls.push(call);
        try {
          const stream = await original(...args);
          const videoTracks = stream.getVideoTracks();
          proof.tracks.push(...stream.getTracks());
          call.trackReceivedAt = new Date().toISOString();
          for (const track of stream.getTracks()) {
            const originalStop = track.stop.bind(track);
            track.stop = (...stopArgs) => {
              if (!call.firstTrackStoppedAt) call.firstTrackStoppedAt = new Date().toISOString();
              return originalStop(...stopArgs);
            };
          }
          call.videoTracks = videoTracks.map(track => ({ label: track.label, readyState: track.readyState, settings: track.getSettings() }));
          return stream;
        } catch (error) { call.error = String(error); throw error; }
      };
    });
    page = await context.newPage();
    const moduleResponse = page.waitForResponse(response => response.url() === servedEngineUrl, {timeout:60000})
      .then(async response => ({ sha256:createHash('sha256').update(await response.body()).digest('hex') })).catch(error => ({error:String(error)}));
    const url = new URL(`${specimen.app}/`, base);
    result.url = url.href;
    await page.goto(url.href, { waitUntil: 'domcontentloaded', timeout: 60000 });
    result.actualEngineResponse = await moduleResponse;
    assert.equal(result.actualEngineResponse.sha256, result.temporaryEngineSha256 || servedEngineSha256, 'Browser engine response does not match measured bytes');
    if (specimen.app === 'atlas') {
      await page.waitForFunction(() => window.__GRIDATLAS_V9_MAP__?.getStyle?.()?.layers?.length > 0, null, { timeout: 90000 });
      await page.locator('#codex-teleprinter').waitFor({ state: 'attached', timeout: 90000 });
    } else await page.locator('#codex-teleprinter #file-menu > summary').waitFor({ state: 'visible', timeout: 60000 });
    assert.equal(await page.evaluate(() => typeof window.__codexTeleprinterCapture), 'undefined', 'host screenshot provider must not be installed');
    await page.evaluate(() => document.querySelector('#codex-teleprinter').addEventListener('teleprint', event => { window.__nativeDisplayProof.receipt = event.detail; }));
    let locator;
    if (specimen.app === 'atlas') {
      const file = page.getByRole('button', { name: 'File', exact: true });
      await file.click();
      locator = page.locator('button[data-gm-export]').filter({ hasText: /\bPrint\b/i });
    } else {
      await page.locator('#codex-teleprinter #file-menu > summary').click();
      locator = page.locator('#codex-teleprinter [data-codex-print-command="pdf"]');
    }
    const download = await clickAndReadDownload(page, locator, { timeout: 45000 });
    const proof = await page.evaluate(() => {
      const proof = window.__nativeDisplayProof;
      return { unavailable: proof?.unavailable, calls: proof?.calls, draws: proof?.draws, receipt: proof?.receipt, tracks: proof?.tracks.map(track => ({ kind: track.kind, label: track.label, readyState: track.readyState, settings: track.getSettings() })), hostCaptureProvider: typeof window.__codexTeleprinterCapture };
    });
    result.nativeCapture = proof;
    assert.ok(download.ok, download.error);
    assert.equal(proof.calls.length, 1, 'expected exactly one native screen capture request');
    assert.equal(proof.calls[0].delegatedToOriginal, true);
    assert.ok(proof.tracks.length > 0 && proof.tracks.every(track => track.readyState === 'ended'), 'native capture tracks must stop after download');
    const initial = proof.calls[0].videoTracks[0]?.settings;
    const drawing = proof.draws.at(-1);
    assert.ok(drawing?.delegatedToOriginal, 'actual native frame draw must be observed without substitution');
    const settings = drawing.trackSettings[0];
    assert.ok(Number.isInteger(settings?.width) && settings.width > 0 && Number.isInteger(settings?.height) && settings.height > 0, 'native track must report actual dimensions');
    const pdfPath = path.join(output, `${specimen.id}.pdf`);
    await fs.writeFile(pdfPath, download.bytes, { flag: 'wx' });
    result.pdf = pdfPath;
    result.pdfBytes = download.bytes.length;
    result.sha256 = createHash('sha256').update(download.bytes).digest('hex');
    result.postDownloadScreenshot = path.join(output, `${specimen.id}-post-download.png`);
    await page.screenshot({ path: result.postDownloadScreenshot, fullPage: false, scale: 'device' });
    const inspected = spawnSync('python', ['-c', inspector], { input: JSON.stringify({ pdf: download.bytes.toString('base64'), settings, initial, drawing }), encoding: 'utf8', maxBuffer: 4 * 1024 * 1024, windowsHide: true });
    assert.equal(inspected.status, 0, inspected.stderr);
    result.pdfInspection = JSON.parse(inspected.stdout);
    result.initialSettingsGeometryAssertion = { passed: result.pdfInspection.initialSettingsGeometryMatch, initial: { width: initial.width, height: initial.height }, drawn: { width: drawing.width, height: drawing.height }, explanation: 'Initial settings can change before a frame arrives. A mismatch remains recorded; it is not evidence of physical screen-resolution preservation.' };
    result.requestedViewportGeometryMatch = settings.width === Math.round(specimen.width * specimen.dpr) && settings.height === Math.round(specimen.height * specimen.dpr);
    result.ok = true;
    console.log(`PASS ${specimen.id}: native ${settings.width}x${settings.height}; tracks ended; PDF geometry retained.`);
  } catch (error) {
    result.error = String(error.stack || error);
    if (page) result.failureState = await page.evaluate(() => ({ title: document.title, url: location.href, status: document.querySelector('#codex-teleprinter')?.shadowRoot?.querySelector('#status')?.textContent, calls: window.__nativeDisplayProof?.calls, tracks: window.__nativeDisplayProof?.tracks.map(track => ({ readyState: track.readyState, settings: track.getSettings() })) })).catch(() => null  … [line shortened here: 402 characters; full line on GitHub]
    console.log(`FAIL ${specimen.id}: ${error.message}`);
  } finally {
    if (page) await page.evaluate(() => window.__nativeDisplayProof?.tracks.forEach(track => track.stop())).catch(() => {});
    await context?.close().catch(error => { result.cleanupError = String(error); result.ok = false; });
    await browser?.close().catch(error => { result.cleanupError = String(error); result.ok = false; });
    report.cases.push(result);
    await fs.writeFile(path.join(output, `${specimen.id}-metadata.json`), JSON.stringify(result, null, 2) + '\n');
  }
}
report.finishedAt = new Date().toISOString();
report.passed = report.cases.filter(result => result.ok).length;
report.initialSettingsGeometryPassed = report.cases.filter(result => result.pdfInspection?.initialSettingsGeometryMatch).length;
report.requestedViewportGeometryPassed = report.cases.filter(result => result.requestedViewportGeometryMatch).length;
await fs.writeFile(path.join(output, 'results.json'), JSON.stringify(report, null, 2) + '\n');
await fs.writeFile(path.join(root, 'native-display-results.json'), JSON.stringify(report, null, 2) + '\n');
console.log(JSON.stringify({ passed: report.passed, tested: cases.length, offlineArtifacts: output }));
if (report.passed !== cases.length) process.exitCode = 1;

Codex Offline Evidence Inventory

A Python command-line tool in the drivers folder of Teleprinter that works with inspect PDF (`inspect_pdf`), covering teleprint evidence summary, campaign results and CI verdict, using SHA-256.

storageteleprinter / drivers/codex/offline-evidence-inventory.py · lines 1–64 of 64 · Entry point

What it does
Defines inspect_pdf, main. Uses libraries pathlib, collections, concurrent.futures, hashlib, json. 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).
Inputs & outputs
In: JSON file teleprint-evidence-summary.json; JSON file campaign-results.json; JSON file results.json; JSON file ci-verdict.json; JSON file ci-verdict-202609051556.json; command-line arguments. Out: JSON file inventory.json.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Read existing offline evidence; inspect actual PDFs, never execute captured code.
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, collections, concurrent.futures, hashlib, json, sys, time, pymupdf
Used by
none found
Produces
inspect_pdf, main
Defines here
inspect_pdf, 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/offline-evidence-inventory.py:1-64 · blob 64d3b72b62dfcfd83be81a8260b09b7745132631 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
"""Read existing offline evidence; inspect actual PDFs, never execute captured code."""
from pathlib import Path
import collections
import concurrent.futures
import hashlib
import json
import sys
import time


def inspect_pdf(path):
    import pymupdf
    raw = path.read_bytes()
    result = {'path': str(path), 'bytes': len(raw), 'sha256': hashlib.sha256(raw).hexdigest()}
    try:
        with pymupdf.open(stream=raw, filetype='pdf') as doc:
            result['pages'] = len(doc)
            result['pageRecords'] = [{'page': i + 1, 'size': [page.rect.width, page.rect.height],
                                     'images': [[image[2], image[3]] for image in page.get_images()],
                                     'textCharacters': len(page.get_text())} for i, page in enumerate(doc)]
            result['ok'] = True
    except Exception as error:
        result.update(ok=False, error=str(error))
    return result


def main():
    root, output = map(lambda x: Path(x).resolve(), sys.argv[1:3])
    if not output.is_relative_to(root):
        raise ValueError('Write evidence only beneath the supplied offline folder')
    started = time.monotonic()
    files = [p for p in root.rglob('*') if p.is_file() and not p.is_relative_to(output)]
    inventory = collections.defaultdict(lambda: {'files': 0, 'bytes': 0})
    for p in files:
        entry = inventory[p.suffix.lower() or '(none)']
        entry['files'] += 1
        entry['bytes'] += p.stat().st_size
    with concurrent.futures.ProcessPoolExecutor(max_workers=4) as pool:
        pdfs = list(pool.map(inspect_pdf, [p for p in files if p.suffix.lower() == '.pdf']))
    reports = []
    names = {'teleprint-evidence-summary.json', 'campaign-results.json', 'results.json', 'ci-verdict.json', 'ci-verdict-202609051556.json'}
    for p in files:
        if p.name not in names or p.stat().st_size > 10000000:
            continue
        try:
            data = json.loads(p.read_bytes())
            if not isinstance(data, dict):
                continue
            reports.append({'path': str(p), 'sha256': hashlib.sha256(p.read_bytes()).hexdigest(),
                            'recordedClaims': {k: data[k] for k in ['generation', 'base', 'candidate', 'passed', 'failed', 'ok', 'actualVisits', 'savedDownloads', 'summary', 'scope'] if k in data}})
        except (ValueError, OSError):
            continue
    result = {'schema': 'codex-offline-evidence-inventory-v1', 'root': str(root),
              'fileTypes': dict(inventory), 'pdfFiles': len(pdfs), 'pdfReadable': sum(p.get('ok', False) for p in pdfs),
              'pdfPages': sum(p.get('pages', 0) for p in pdfs), 'seconds': round(time.monotonic() - started, 2),
              'pdfs': pdfs, 'priorReports': reports,
              'scope': 'Actual PDF bytes hashed and every page opened, text extracted, image dimensions read. Existing report claims inventoried, not promoted to independently verified passes. No visual fidelity or physical-device claim.'}
    output.mkdir(parents=True, exist_ok=True)
    (output / 'inventory.json').write_text(json.dumps(result, indent=2) + '\n', encoding='utf8')
    print(json.dumps({k: result[k] for k in ['pdfFiles', 'pdfReadable', 'pdfPages', 'seconds']}))


if __name__ == '__main__':
    main()

Codex Offline PDF Sweep

A Python command-line tool in the drivers folder of Teleprinter that works with inspect page (`inspect_page`) and memory budget (`memory_budget`), covering page results and summary, using SHA-256.

storageteleprinter / drivers/codex/offline-pdf-sweep.py · lines 1–81 of 81 · Entry point · pattern initialize (shared by 2 files)

What it does
Defines initialize, inspect_page, memory_budget, Status, main. Uses libraries argparse, concurrent.futures, ctypes, hashlib, json. 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).
Inputs & outputs
In: command-line arguments. Out: JSON file page-results.json; JSON file summary.json.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It is built from the initialize step (`initialize`) and the status class (`Status`). Parallel CPU-only PDF page decoding/rendering. No network, browser, or AI calls. It accepts `--summary`.
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
argparse, concurrent.futures, ctypes, hashlib, json, os, pathlib, time
Used by
none found
Produces
initialize, inspect_page, memory_budget, main
Defines here
initialize, inspect_page, memory_budget, Status, 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/offline-pdf-sweep.py:1-81 · blob ddf6a6f463756de657660441f1e71a06ae0b99b7 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
"""Parallel CPU-only PDF page decoding/rendering. No network, browser, or AI calls."""
import argparse
import concurrent.futures
import ctypes
import hashlib
import json
import os
from pathlib import Path
import time
import pymupdf

DOCUMENT = None


def initialize(filename):
    global DOCUMENT
    DOCUMENT = pymupdf.open(filename)


def inspect_page(index):
    try:
        page = DOCUMENT[index]
        text = page.get_text().encode("utf8")
        pixmap = page.get_pixmap(matrix=pymupdf.Matrix(96 / 72, 96 / 72), alpha=False)
        pixels = pixmap.samples
        return {"page": index + 1, "textBytes": len(text), "textSha256": hashlib.sha256(text).hexdigest(),
                "width": pixmap.width, "height": pixmap.height, "renderSha256": hashlib.sha256(pixels).hexdigest(),
                "nonuniformPixels": min(pixels) != max(pixels), "ok": bool(text.strip()) and min(pixels) != max(pixels)}
    except Exception as error:
        return {"page": index + 1, "ok": False, "error": str(error)}


def memory_budget():
    if os.name != "nt":
        return 4 * 1024**3
    class Status(ctypes.Structure):
        _fields_ = [("length", ctypes.c_ulong), ("load", ctypes.c_ulong)] + [(name, ctypes.c_ulonglong) for name in
                     ["totalPhys", "availPhys", "totalPage", "availPage", "totalVirtual", "availVirtual", "extended"]]
    status = Status()
    status.length = ctypes.sizeof(status)
    if not ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(status)):
        return 2 * 1024**3
    return status.availPhys


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("pdf", type=Path)
    parser.add_argument("output", type=Path)
    parser.add_argument("--summary", type=Path)
    args = parser.parse_args()
    if args.output.resolve().is_relative_to(Path(__file__).resolve().parents[2]):
        parser.error("Per-page evidence belongs outside Git.")
    available = memory_budget()
    # Leave memory for the user's apps and concurrent browser campaigns.
    workers = max(1, min((os.cpu_count() or 2) - 2, int(max(0, available - 1536 * 1024**2) / (256 * 1024**2))))
    raw = args.pdf.read_bytes()
    with pymupdf.open(args.pdf) as doc:
        count = len(doc)
    started = time.monotonic()
    with concurrent.futures.ProcessPoolExecutor(max_workers=workers, initializer=initialize, initargs=(str(args.pdf.resolve()),)) as pool:
        pages = list(pool.map(inspect_page, range(count), chunksize=4))
    args.output.mkdir(parents=True, exist_ok=True)
    page_bytes = (json.dumps(pages, indent=2) + "\n").encode()
    (args.output / "page-results.json").write_bytes(page_bytes)
    summary = {"schema": "codex-offline-pdf-sweep-v1", "file": args.pdf.name, "artifactSha256": hashlib.sha256(raw).hexdigest(),
               "workers": workers, "logicalProcessors": os.cpu_count(), "availableMemoryBytesAtStart": available,
               "pages": count, "passed": sum(page["ok"] for page in pages), "failed": [page for page in pages if not page["ok"]],
               "pageResultsSha256": hashlib.sha256(page_bytes).hexdigest(), "seconds": round(time.monotonic() - started, 2),
               "scope": "All PDF pages decoded, text extracted and rasterized at96DPI; no source execution or completeness claim.",
               "ok": all(page["ok"] for page in pages)}
    encoded = json.dumps(summary, indent=2) + "\n"
    (args.output / "summary.json").write_text(encoded, encoding="utf8")
    if args.summary:
        args.summary.write_text(encoded, encoding="utf8")
    print(json.dumps(summary))
    return 0 if summary["ok"] else 1


if __name__ == "__main__":
    raise SystemExit(main())

Codex Offline Source Batch

A Python command-line tool in the drivers folder of Teleprinter covering audit, summary and offline batch results, using SHA-256. It is built from the audit step (`audit`).

storageteleprinter / drivers/codex/offline-source-batch.py · lines 1–53 of 53 · Entry point · pattern audit (shared by 7 files)

What it does
Defines main, audit. Uses libraries concurrent.futures, json, pathlib, subprocess, sys. 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 audit.json; command-line arguments. Out: JSON file summary.json; JSON file offline-source-batch-results.json.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Verify every downloaded source print from a browser campaign using offline subprocesses.
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
Codex Audit Runtime Source (script call), concurrent.futures, json, pathlib, subprocess, sys, time
Used by
none found
Produces
main
Defines here
main, audit
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/offline-source-batch.py:1-53 · blob 85a479073381679f6d21c5dc3d1b1fda9ea7672a · 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
"""Verify every downloaded source print from a browser campaign using offline subprocesses."""
import concurrent.futures
import json
from pathlib import Path
import subprocess
import sys
import time

here = Path(__file__).resolve().parent


def main():
    receipt = json.loads(Path(sys.argv[1]).read_bytes())
    output = Path(sys.argv[2]).resolve()
    if output.is_relative_to(here.parents[1]): raise ValueError("Evidence output must be outside Git")
    output.mkdir(parents=True, exist_ok=True)
    repo = Path(sys.argv[3]).resolve()
    sources = [visit for scenario in receipt["scenarios"] for visit in scenario["visits"] if visit["mode"] == "source"]
    if not receipt.get("finishedAt") or len(sources) != 25: raise ValueError("Expected a finished25-source campaign")
    started = time.monotonic()

    def audit(visit):
        destination = output / visit["visitId"]
        command = [sys.executable, str(here / "audit-runtime-source.py"), visit["path"], str(destination), "--repo", str(repo), "--no-extract"]
        run = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=180, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
        result = {"visitId": visit["visitId"], "ok": run.returncode == 0, "exitCode": run.returncode}
        report_path = destination / "audit.json"
        if report_path.exists():
            report = json.loads(report_path.read_bytes())
            result.update(artifactSha256=report["artifact"]["sha256"], counts=report["counts"], pinnedGitBytesChecked=report["pinnedGitBytesChecked"])
            if report["artifact"]["sha256"] != visit["sha256"]: result.update(ok=False, error="Downloaded source hash differs from browser receipt")
        else: result["error"] = (run.stdout + run.stderr).decode("utf8", "replace")[-2000:]
        return result

    # Two memory-heavy source parsers; each fans out up to eight light syntax workers.
    with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
        results = list(pool.map(audit, sources))
    report = {"schema": "codex-offline-source-batch-v1", "candidate": receipt["candidate"], "sources": len(results),
              "passed": sum(item["ok"] for item in results), "seconds": round(time.monotonic() - started, 2), "outerWorkers": 2,
              "ok": all(item["ok"] for item in results), "results": results,
              "scope": "Every actual source download rehashed, framed bodies verified, pinned files compared to local Git, JS parsed without execution, JSON parsed. No network or AI calls."}
    encoded = json.dumps(report, indent=2) + "\n"
    (output / "summary.json").write_text(encoded, encoding="utf8")
    (here / "offline-source-batch-results.json").write_text(encoded, encoding="utf8")
    print(json.dumps({key: report[key] for key in ["sources", "passed", "seconds", "ok"]}))
    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 Outcome Test

A test in the drivers folder of Teleprinter that checks Codex Source Code and Codex Driver.

testteleprinter / drivers/codex/outcome.test.mjs · lines 1–112 of 112 · Not reached from any entry point (candidate for review)

What it does
It tests its inputs. Uses libraries node:http, node:fs/promises, node:path, node:url, node:child_process. Side effects: changes the web page (DOM); 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 source-code.manifest.json. Out: JSON file outcome-results.json.
What it achieves
Actual controls, download bytes and rendered pixel comparison.
Why it matters
Guards the behaviour of Codex Source Code, Codex Driver and Print Screen.
Application
teleprinter · drivers/codex · test
Uses
Codex Source Code (script call), Codex Driver (script call), Print Screen (dynamic import), node:http, node:fs/promises, node:path, node:url, node:child_process, node:assert/strict, playwright
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/outcome.test.mjs:1-112 · blob 92bc544603dba509f7ce5abfec3d1592d8550af7 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
/** Actual controls, download bytes and rendered pixel comparison. No retained screenshots/PDFs. */
import http from 'node:http';
import fs from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { spawnSync } from 'node:child_process';
import assert from 'node:assert/strict';
import { createSourceCodeBundle } from './source-code.mjs';
import { attachScreenCapture, clickAndReadDownload } from './driver.mjs';
const root = path.dirname(fileURLToPath(import.meta.url));
const repo = path.resolve(root,'../..');
const modulePath = process.env.PLAYWRIGHT_MODULE;
const { chromium, firefox, webkit } = modulePath ? await import(pathToFileURL(modulePath).href) : await import('playwright');
const bundle = await createSourceCodeBundle({ repoDir: repo, revision: 'HEAD', paths: ['README.md','pdf.js'] });
const sourceBytes = Buffer.from(bundle.text);
const server = http.createServer(async (req,res) => {
  try {
    const url = new URL(req.url,'http://localhost');
    if (url.pathname.endsWith('/source-code.txt')) { res.setHeader('Content-Type','text/plain;charset=utf-8'); res.end(sourceBytes); return; }
    if (url.pathname.endsWith('/source-code.manifest.json')) { res.setHeader('Content-Type','application/json'); res.end(JSON.stringify(bundle.manifest)); return; }
    const filename = path.resolve(root, '.'+decodeURIComponent(url.pathname));
    if (!filename.startsWith(root+path.sep)) throw new Error('outside root');
    res.setHeader('Content-Type', filename.endsWith('.html') ? 'text/html;charset=utf-8' : 'text/javascript');
    res.end(await fs.readFile(filename));
  } catch { res.writeHead(404); res.end('Not found'); }
});
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
const base = `http://127.0.0.1:${server.address().port}/demo.html`;
const reports = [];
const engines = [['Chrome',chromium,{channel:'chrome'}],['Edge',chromium,{channel:'msedge'}],['Firefox',firefox,{}],['WebKit',webkit,{}]];
const viewports = [
  {name:'desktop landscape',width:1200,height:800,dpr:1},
  {name:'desktop portrait',width:800,height:1100,dpr:1},
  {name:'mobile portrait emulation',width:393,height:852,dpr:2},
  {name:'mobile landscape emulation',width:852,height:393,dpr:2}
];
try {
  for (const [name, engine, options] of engines) {
    let browser;
    try { browser = await engine.launch({headless:true,...options}); }
    catch(error) { reports.push({browser:name,ok:false,error:String(error)}); console.log(`FAIL ${name}: ${error.message}`); continue; }
    try {
      for (const viewport of viewports) {
        const context = await browser.newContext({viewport:{width:viewport.width,height:viewport.height},deviceScaleFactor:viewport.dpr,acceptDownloads:true});
        const page = await context.newPage();
        let captured;
        try {
          await attachScreenCapture(page,{onCapture:png=>{captured=png;}});
          await page.goto(base);
          await page.getByLabel('Show grid layer').check();
          assert.equal(await page.locator('#layer-state').textContent(),'Grid layer visible');
          const pdf = await clickAndReadDownload(page,page.getByRole('button',{name:'Print',exact:true}));
          assert.ok(pdf.ok,pdf.error);
          assert.ok(captured,'no browser capture');
          const inspected = spawnSync('python',[path.join(root,'inspect-pdf.py')],{input:JSON.stringify({pdf:pdf.bytes.toString('base64'),png:captured.toString('base64')}),encoding:'utf8',maxBuffer:4000000});
          assert.equal(inspected.status,0,inspected.stderr);
          const pixels = JSON.parse(inspected.stdout);
          assert.equal(pixels.width,viewport.width*viewport.dpr);
          assert.equal(pixels.height,viewport.height*viewport.dpr);
          await page.locator('details').evaluate(node=>{node.open=true;});
          await page.locator('#screenshot').setInputFiles({name:'device-screenshot.png',mimeType:'image/png',buffer:captured});
          const uploaded = await clickAndReadDownload(page,page.getByRole('button',{name:'Print selected screenshot',exact:true}));
          assert.ok(uploaded.ok,uploaded.error);
          const uploadedCheck = spawnSync('python',[path.join(root,'inspect-pdf.py')],{input:JSON.stringify({pdf:uploaded.bytes.toString('base64'),png:captured.toString('base64')}),encoding:'utf8',maxBuffer:4000000});
          assert.equal(uploadedCheck.status,0,uploadedCheck.stderr);
          const text = await clickAndReadDownload(page,page.getByRole('button',{name:'Print source code',exact:true}));
          assert.ok(text.ok,text.error);
          assert.deepEqual(text.bytes,sourceBytes,'downloaded source differs from committed bundle');
          assert.match(text.filename,/\.txt$/);
          // Force the real manual fallback rather than letting clipboard privileges mask it.
          await page.evaluate(()=>{Object.defineProperty(navigator,'clipboard',{value:{writeText:async()=>{throw new DOMException('Denied','NotAllowedError');}},configurable:true});});
          await page.getByRole('button',{name:'Copy source code',exact:true}).click();
          await page.waitForFunction(()=>document.querySelector('textarea')?.value.length>0);
          assert.equal(await page.locator('textarea').inputValue(),sourceBytes.toString('utf8'));
          reports.push({browser:name,version:browser.version(),viewport:viewport.name,ok:true,...pixels,uploadedScreenshotPixelsIdentical:true,sourceBytes:text.bytes.length,sourceDownloadIdentical:true,copyFallbackComplete:true});
          console.log(`PASS ${name} ${viewport.name}: PDF ${pixels.width}x${pixels.height}, source ${text.bytes.length} bytes, complete copy fallback`);
        } catch(error) { reports.push({browser:name,viewport:viewport.name,ok:false,error:String(error)}); console.log(`FAIL ${name} ${viewport.name}: ${error.message}`); }
        finally { captured=undefined; await context.close().catch(error=>{reports.push({browser:name,case:'context cleanup',ok:false,error:String(error)});}); }
      }
      const context=await browser.newContext({acceptDownloads:true});
      try {
        const page=await context.newPage(); await page.goto(base);
        if (name === 'Chrome') {
          const timeoutCleanup = await page.evaluate(async()=>{
            const {printScreen}=await import('./print-screen.js');
            let stopped=0;
            Object.defineProperty(navigator.mediaDevices,'getDisplayMedia',{configurable:true,value:async()=>({getTracks:()=>[{stop(){stopped++;}}]})});
            const original=document.createElement.bind(document);
            document.createElement=(tag,...args)=>tag==='video'?{play:()=>new Promise(()=>{}),pause(){}}:original(tag,...args);
            try { await printScreen(); return {stopped,error:null}; }
            catch(error) { return {stopped,error:error.message}; }
            finally { document.createElement=original; }
          });
          assert.equal(timeoutCleanup.stopped,1,'stalled playback must stop capture');
          assert.match(timeoutCleanup.error,/No screen frame/);
          reports.push({browser:name,case:'stalled display playback stops capture',ok:true});
        }
        const absent=await clickAndReadDownload(page,page.locator('#nonexistent'),{timeout:500});
        assert.equal(absent.ok,false,'missing control must fail');
        await page.route('**/source-code.txt',route=>route.fulfill({body:'corrupt source',contentType:'text/plain'}));
        await page.reload();
        const corrupt=await clickAndReadDownload(page,page.getByRole('button',{name:'Print source code',exact:true}),{timeout:1500});
        assert.equal(corrupt.ok,false,'corrupt source must never download');
        reports.push({browser:name,case:'missing-control and corrupt-source fail without crashing',ok:true});
        console.log(`PASS ${name}: missing control and corrupt source rejected`);
      } catch(error) { reports.push({browser:name,case:'negative controls',ok:false,error:String(error)}); }
      finally { await context.close().catch(error=>{reports.push({browser:name,case:'context cleanup',ok:false,error:String(error)});}); }
    } finally { await browser.close().catch(error=>{reports.push({browser:name,case:'browser cleanup',ok:false,error:String(error)});}); }
  }
} finally { await new Promise(resolve=>server.close(resolve)); }
await fs.writeFile(path.join(root,'outcome-results.json'),JSON.stringify({createdAt:new Date().toISOString(),capture:'Playwright browser compositor screenshot; pixels in memory only',physicalDeviceTests:false,reports},null,2)+'\n');
if (reports.some(r=>!r.ok)) process.exitCode=1;

Codex Png Pixels Test

A test in the drivers folder of Teleprinter that checks Png Pixels. It is built from the chunk step (`chunk`) and the png step (`png`).

testteleprinter / drivers/codex/png-pixels.test.mjs · lines 1–105 of 105 · Not reached from any entry point (candidate for review) · pattern chunk (shared by 3 files)

What it does
It tests its inputs. Defines chunk, png. Uses libraries node:test, node:assert/strict, node:zlib.
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: "`png-pixels.mjs` decodes RGB/RGBA 8-bit PNG screenshots without the browser image decoder changing their colour values."
What it achieves
Deliberately separate bit-at-a-time CRC implementation from the decoder's table.
Why it matters
Guards the behaviour of Png Pixels.
Application
teleprinter · drivers/codex · test
Uses
Png Pixels (import), node:test, node:assert/strict, node:zlib
Used by
none found
Produces
chunk, png
Defines here
chunk, png
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/png-pixels.test.mjs:1-105 · blob d85b8ac37ef2fa7ea0ba0f184af03e77af865353 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · 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 { deflateSync } from 'node:zlib';
import { decodePngPixels } from './png-pixels.mjs';

// Deliberately separate bit-at-a-time CRC implementation from the decoder's table.
function chunk(type, data = Buffer.alloc(0)) {
  const body = Buffer.concat([Buffer.from(type), data]);
  let crc = 0xffffffff;
  for (const value of body) {
    crc ^= value;
    for (let bit = 0; bit < 8; bit++) crc = crc & 1 ? (crc >>> 1) ^ 0xedb88320 : crc >>> 1;
  }
  const length = Buffer.alloc(4), checksum = Buffer.alloc(4);
  length.writeUInt32BE(data.length); checksum.writeUInt32BE((crc ^ 0xffffffff) >>> 0);
  return Buffer.concat([length, body, checksum]);
}
function png({ width = 2, height = 2, color = 2, depth = 8, interlace = 0, raw, before = [], after = [], compressed, split = false } = {}) {
  const header = Buffer.alloc(13);
  header.writeUInt32BE(width, 0); header.writeUInt32BE(height, 4);
  header[8] = depth; header[9] = color; header[12] = interlace;
  const encoded = compressed ?? deflateSync(Buffer.from(raw));
  const data = split ? [chunk('IDAT', encoded.subarray(0, 3)), chunk('IDAT'), chunk('IDAT', encoded.subarray(3))] : [chunk('IDAT', encoded)];
  return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk('IHDR', header), ...before, ...data, ...after, chunk('IEND')]);
}
const row0 = [10, 20, 30, 50, 60, 70];
const expected = Uint8Array.from([10, 20, 30, 255, 50, 60, 70, 255, 15, 25, 35, 255, 80, 90, 100, 255]);
// These are hand-calculated encoded bytes, not output from a copy of the unfilter code.
const encodedRows = [
  [15, 25, 35, 80, 90, 100],
  [15, 25, 35, 65, 65, 65],
  [5, 5, 5, 30, 30, 30],
  [10, 15, 20, 48, 48, 48],
  [5, 5, 5, 30, 30, 30],
];
for (let filter = 0; filter < 5; filter++) test(`filter ${filter} restores exact RGB samples and opaque alpha`, async () => {
  const result = await decodePngPixels(png({ raw: [0, ...row0, filter, ...encodedRows[filter]], split: true }));
  assert.deepEqual(result, { width: 2, height: 2, rgba: expected });
});

test('RGBA retains hidden RGB, partial alpha, channel wraparound, and ICC bytes', async () => {
  const profile = Buffer.alloc(132);
  profile.writeUInt32BE(profile.length, 0); profile.write('mntr', 12); profile.write('RGB ', 16); profile.write('XYZ ', 20); profile.write('acsp', 36);
  const result = await decodePngPixels(new Blob([png({ width: 2, height: 1, color: 6,
    raw: [1, 250, 128, 9, 0, 16, 129, 248, 127],
    before: [chunk('iCCP', Buffer.concat([Buffer.from('Test profile\0\0'), deflateSync(profile)]))],
  })]));
  assert.deepEqual(result.rgba, Uint8Array.from([250, 128, 9, 0, 10, 1, 1, 127]));
  assert.deepEqual(result.iccProfile, new Uint8Array(profile));
});

test('RGB tRNS preserves transparent pixels without losing their RGB', async () => {
  const transparent = Buffer.from([0, 10, 0, 20, 0, 30]);
  const result = await decodePngPixels(png({ height: 1, raw: [0, ...row0], before: [chunk('tRNS', transparent)] }));
  assert.deepEqual(result.rgba, Uint8Array.from([10, 20, 30, 0, 50, 60, 70, 255]));
});

test('Paeth selects left, above and upper-left using exact tie rules', async () => {
  // Pixel one on row two is [50,30,60]; predictors for pixel two are [50,20,50].
  const result = await decodePngPixels(png({ raw: [0, 20, 50, 50, 50, 20, 40, 4, 30, 236, 10, 10, 20, 30] }));
  assert.deepEqual(result.rgba, Uint8Array.from([20, 50, 50, 255, 50, 20, 40, 255, 50, 30, 60, 255, 60, 40, 80, 255]));
});

test('valid unsupported grayscale, 16-bit RGB, indexed, and Adam7 images return null', async () => {
  const variants = [
    { width: 1, height: 1, color: 0, raw: [0, 31] },
    { width: 1, height: 1, depth: 16, raw: [0, 0, 1, 0, 2, 0, 3] },
    { width: 1, height: 1, color: 3, raw: [0, 0], before: [chunk('PLTE', Buffer.from([1, 2, 3]))] },
    { width: 1, height: 1, color: 6, interlace: 1, raw: [0, 1, 2, 3, 4] },
  ];
  for (const variant of variants) assert.equal(await decodePngPixels(png(variant)), null);
});

test('bad signature, CRC, truncation, missing end, and trailing bytes fail', async () => {
  const valid = png({ raw: [0, ...row0, 0, ...encodedRows[0]] });
  const badSignature = Buffer.from(valid); badSignature[0] = 0;
  const badCrc = Buffer.from(valid); badCrc[29] ^= 1;
  for (const bytes of [badSignature, badCrc, valid.subarray(0, 4), valid.subarray(0, 30), valid.subarray(0, -12), Buffer.concat([valid, Buffer.from([1])])]) await assert.rejects(decodePngPixels(bytes), /PNG screenshot:/);
});

test('corrupt deflate, wrong inflated length, and invalid scanline filters fail', async () => {
  const variants = [
    { compressed: Buffer.from([1, 2, 3]) },
    { raw: [0, ...row0] },
    { raw: [0, ...row0, 5, ...encodedRows[0]] },
    { raw: Buffer.alloc(128 * 1024) },
  ];
  for (const variant of variants) await assert.rejects(decodePngPixels(png(variant)), /PNG screenshot:/);
  await assert.rejects(decodePngPixels(png({ width: 1, height: 1, color: 0, raw: [7, 1] })), /unknown scanline filter/);
});

test('chunk ordering, forbidden transparency, invalid depth, and oversized dimensions fail', async () => {
  const variants = [
    { color: 6, raw: [0], before: [chunk('tRNS', Buffer.alloc(6))] },
    { color: 2, depth: 4, raw: [0] },
    { width: 40000001, height: 1, raw: [0] },
    { raw: [0, ...row0, 0, ...encodedRows[0]], after: [chunk('tEXt', Buffer.from('a\0b')), chunk('IDAT', deflateSync(Buffer.alloc(0)))] },
  ];
  for (const variant of variants) await assert.rejects(decodePngPixels(png(variant)), /PNG screenshot:/);
});

test('ICC decompression is bounded independently of the tiny image', async () => {
  const image = png({ height: 1, raw: [0, ...row0], before: [chunk('iCCP', Buffer.concat([Buffer.from('Test\0\0'), deflateSync(Buffer.alloc(4 * 1024 * 1024 + 1))]))] });
  await assert.rejects(decodePngPixels(image), /decompressed data exceeds/);
});

Codex Prepare Demo

A JavaScript module in the drivers folder of Teleprinter.

otherteleprinter / drivers/codex/prepare-demo.mjs · lines 1–8 of 8 · Not reached from any entry point (candidate for review)

What it does
Uses libraries node:path, node:url.
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 source-code.manifest.json; command-line arguments.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
No other file in the estate was found to import it.
Application
teleprinter · drivers/codex · JavaScript module
Uses
Codex Source Code (import), node:path, node:url
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/prepare-demo.mjs:1-8 · blob e88603e4b055afa2b925788ca7f667f9d9f60ec4 · 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 path from 'node:path';
import {fileURLToPath} from 'node:url';
import {writeSourceCodeBundle} from './source-code.mjs';
const here=path.dirname(fileURLToPath(import.meta.url));
const repoDir=path.resolve(here,'../..');
const names=['controls.js','print-screen.js','screen-pdf.mjs','png-pixels.mjs','print-source-code.js','source-code.mjs','driver.mjs','README.md','SOURCE-CODE.md','demo.html'];
const result=await writeSourceCodeBundle({repoDir,revision:process.argv[2]||'HEAD',paths:names.map(name=>'drivers/codex/'+name),textPath:path.join(here,'source-code.txt'),manifestPath:path.join(here,'source-code.manifest.json')});
console.log('Prepared the committed Teleprinter source for demo.html.');