GLOBALGRID2050 / EXPLORE CODE

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

Codex Runtime Source Test and 3 more files

A test in the drivers folder of Teleprinter that checks Runtime Source, using SHA-256 using data from the GridAtlas repository.

577 lines of JavaScript from teleprinter, in 4 files. Topic: AI agents and coordination. Section 1658 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 Runtime Source Test test · teleprinter / drivers/codex/runtime-source.test.mjs lines 1–294
  2. Codex Screen Capture Test test · teleprinter / drivers/codex/screen-capture.test.mjs lines 1–8
  3. Codex Screen PDF Test test · teleprinter / drivers/codex/screen-pdf.test.mjs lines 1–113
  4. Codex Source Code storage · teleprinter / drivers/codex/source-code.mjs lines 1–162

Codex Runtime Source Test

A test in the drivers folder of Teleprinter that checks Runtime Source, using SHA-256 using data from the GridAtlas repository.

testteleprinter / drivers/codex/runtime-source.test.mjs · lines 1–294 of 294 · Not reached from any entry point (candidate for review) · pattern install (shared by 42 files)

What it does
It tests its inputs. Defines install, installDirectTransport, DiagnosticXHR. Uses libraries node:test, node:assert/strict, node:crypto, node:fs/promises. Side effects: changes the web page (DOM); reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
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: "`runtime-source.js` collects current state and dependency responses for the source driver."
Inputs & outputs
In: data source: gridatlas data; Parquet file huge-unrequested.parquet; JSON file missing.json; JSON file atlas-source-code.manifest.json; JSON file atlas-source-pin.json; GeoJSON file grid_400kv.geojson; JSON file tilejson.json; JSON file metadata.json.
What it achieves
It is built from the install step (`install`), the install direct transport helper (`installDirectTransport`) and the diagnostic xhr class (`DiagnosticXHR`). The README says: `runtime-source.js` collects current state and dependency responses for the source driver.
Why it matters
Guards the behaviour of Runtime Source.
Application
teleprinter · drivers/codex · test
Uses
Runtime Source (new URL import.meta.url), node:test, node:assert/strict, node:crypto, node:fs/promises, ./dynamic.js
Used by
none found
Produces
install, installDirectTransport, DiagnosticXHR
Defines here
install, installDirectTransport, DiagnosticXHR
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/runtime-source.test.mjs:1-294 · blob 9e96306d3b8410071c7c4d9f18a9568875590094 · GitHub at these lines
State
achieves: readme · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
import test from 'node:test';
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { readFile } from 'node:fs/promises';
const source = await readFile(new URL('./runtime-source.js', import.meta.url), 'utf8');
const { captureRuntimeSource } = await import(`data:text/javascript;base64,${Buffer.from(source).toString('base64')}`);
const baseBytes = new TextEncoder().encode('PRINT SOURCE CODE\nPinned café source\n');
const baseManifest = { byteCount: baseBytes.length, sha256: createHash('sha256').update(baseBytes).digest('hex'), commit: 'a'.repeat(40) };

function install({ blocked = false, many = false, mapStyle, documentBase } = {}) {
  const base = 'https://app.test/view/';
  const binary = Uint8Array.from([0, 255, 3, 128]);
  const responses = new Map([
    [base, ['<html>original network document</html>', 'text/html']],
    [base + 'app.js', ['import "./child.js"; import( "./dynamic.js" ); export { x } from "./child.js";', 'text/javascript']],
    [base + 'child.js', ['export const x = 1; const inactive = new URL("./huge-unrequested.parquet", import.meta.url);', 'text/javascript']],
    [base + 'dynamic.js', ['export default 7;', 'text/javascript']],
    [base + 'inline.js', ['export const inline = true;', 'text/javascript']],
    [base + 'style.css', ['@import "./nested.css"; body{background:url("./asset.bin")}', 'text/css']],
    [base + 'nested.css', ['p{color:red}', 'text/css']],
    [base + 'asset.bin', [binary, 'application/octet-stream']],
    [base + 'missing.json', ['{"error":"not found"}', 'application/json', 404]],
    ['https://cdn.test/library.js', ['export const remote = true;', 'text/javascript']],
    ['blob:https://app.test/example', ['globalThis.neverExecuteThis = true;', 'text/javascript']],
  ]);
  const calls = [];
  const form = [
    { tagName: 'INPUT', id: 'layer', name: 'layer', type: 'checkbox', value: 'grid', checked: true, disabled: false },
    { tagName: 'SELECT', id: 'choice', name: 'choice', type: 'select-one', value: 'solar', options: [{ value: 'solar', text: 'Solar', selected: true }], disabled: false },
    { tagName: 'TEXTAREA', id: 'notes', name: 'notes', type: 'textarea', value: 'Live unsaved notes', disabled: false },
  ];
  const lists = {
    'input,textarea,select': form,
    script: [{ src: base + 'app.js', type: 'module' }, { src: '', type: 'module', textContent: 'import "./inline.js";' }, { src: 'blob:https://app.test/example' }],
    'link[rel="stylesheet"]': [{ href: base + 'style.css' }],
    img: [{ src: base + 'asset.bin', currentSrc: base + 'asset.bin' }], style: [], '[style]': [], iframe: [],
  };
  const globals = {
    location: { href: base, origin: 'https://app.test' }, innerWidth: 393, innerHeight: 852, devicePixelRatio: 3, scrollX: 0, scrollY: 21,
    performance: { getEntriesByType: () => many ? Array.from({ length: 1501 }, (_, i) => ({ name: base + i + '.js' })) : [{ name: base + 'app.js', initiatorType: 'script' }, { name: base + 'style.css' }, { name: 'https://cdn.test/library.js' }, { name: base + 'atlas-source-code.txt' }, { name: base + 'atlas-source-code.manifest.json' }, { name: base + 'atlas-source-pin.json' }, ...(blocked ? [{ na  … [line shortened here: 479 characters; full line on GitHub]
    document: { title: 'Live Grid Atlas', baseURI: documentBase || base, documentElement: { outerHTML: '<html><body>Current DOM + inline source</body></html>' }, body: { innerText: 'Current visible layers' }, querySelectorAll: selector => lists[selector] ?? [] },
    window: { __GRIDATLAS_V9_MAP__: { getCenter: () => ({ lng: -2.5, lat: 52 }), getZoom: () => 10, getBearing: () => 20, getPitch: () => 30, getStyle: () => mapStyle || ({ layers: [{ id: 'grid', layout: { visibility: 'visible' } }], sources: { substations: { type: 'geojson' } } }) } },
  };
  const saved = new Map(Object.keys(globals).map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)]));
  for (const [key, value] of Object.entries(globals)) Object.defineProperty(globalThis, key, { configurable: true, value });
  return {
    calls, binary, lists, responses,
    fetchImpl: async (url, options) => {
      calls.push({ url, options });
      if (url.startsWith('https://blocked.test')) throw new TypeError('CORS blocked');
      const response = responses.get(url);
      assert.ok(response, 'unexpected fetch: ' + url);
      return new Response(response[0], { status: response[2] ?? 200, headers: { 'content-type': response[1] } });
    },
    restore() { for (const [key, descriptor] of saved) { if (descriptor) Object.defineProperty(globalThis, key, descriptor); else delete globalThis[key]; } },
  };
}

test('captures pinned source, current DOM/forms/map, recursive scripts/CSS, blobs and complete binary bytes', async () => {
  const env = install();
  try {
    const { bytes, manifest } = await captureRuntimeSource({ baseBytes, baseManifest, fetchImpl: env.fetchImpl });
    const text = new TextDecoder().decode(bytes);
    assert.ok(text.includes(new TextDecoder().decode(baseBytes)));
    assert.ok(text.includes('<html><body>Current DOM + inline source</body></html>'));
    assert.equal(manifest.state.forms[0].checked, true);
    assert.equal(manifest.state.forms[1].selected[0].value, 'solar');
    assert.equal(manifest.state.forms[2].value, 'Live unsaved notes');
    assert.equal(manifest.state.map.layers[0].id, 'grid');
    assert.equal(manifest.state.viewport.devicePixelRatio, 3);
    assert.equal(manifest.complete, false, 'browser discovery must not claim all dependencies proven');
    assert.equal(manifest.observedResourcesComplete, true);
    assert.equal(manifest.failures.length, 0);
    assert.equal(manifest.exclusions.length, 3);
    assert.equal(env.calls.filter(call => call.url.endsWith('/child.js')).length, 1);
    assert.ok(env.calls.some(call => call.url.endsWith('/dynamic.js')));
    assert.ok(env.calls.some(call => call.url.endsWith('/nested.css')));
    assert.ok(env.calls.some(call => call.url.endsWith('/inline.js')));
    assert.ok(env.calls.some(call => call.url.startsWith('blob:')));
    assert.equal(globalThis.neverExecuteThis, undefined);
    assert.equal(env.calls.find(call => call.url.startsWith('https://cdn.test')).options.credentials, 'omit');
    assert.equal(env.calls.find(call => call.url.endsWith('/app.js')).options.credentials, 'same-origin');
    assert.ok(env.calls.every(call => call.options.cache === 'force-cache'));
    const binary = manifest.resources.find(resource => resource.url.endsWith('/asset.bin'));
    assert.equal(binary.encoding, 'base64');
    assert.equal(binary.byteCount, 4);
    assert.equal(binary.sha256, createHash('sha256').update(env.binary).digest('hex'));
    assert.ok(text.includes(Buffer.from(env.binary).toString('base64')));
    assert.equal(manifest.byteCount, bytes.length);
    assert.equal(manifest.sha256, createHash('sha256').update(bytes).digest('hex'));
  } finally { env.restore(); }
});

test('CORS failure and HTTP error remain visible, with complete error response body', async () => {
  const env = install({ blocked: true });
  try {
    const result = await captureRuntimeSource({ baseBytes, baseManifest, fetchImpl: env.fetchImpl });
    assert.equal(result.manifest.complete, false);
    assert.equal(result.manifest.observedResourcesComplete, false);
    assert.equal(result.manifest.failures.length, 2);
    assert.ok(new TextDecoder().decode(result.bytes).includes('CORS blocked'));
    assert.ok(new TextDecoder().decode(result.bytes).includes('{"error":"not found"}'));
    assert.equal(result.manifest.resources.find(resource => resource.url.endsWith('/missing.json')).status, 'included-http-error');
  } finally { env.restore(); }
});

test('tampered pinned bytes and an excessive dependency graph fail explicitly', async () => {
  const env = install({ many: true });
  try {
    await assert.rejects(captureRuntimeSource({ baseBytes: new Uint8Array(baseBytes.length), baseManifest, fetchImpl: env.fetchImpl }), /SHA256 check/);
    await assert.rejects(captureRuntimeSource({ baseBytes, baseManifest, fetchImpl: env.fetchImpl }), /1,500-resource limit/);
    assert.equal(env.calls.length, 0);
  } finally { env.restore(); }
});

test('worker-only live GeoJSON resolves against the remote document base and is included completely', async () => {
  const documentBase = 'https://ventusltd.github.io/gridatlas/atlas/releases/202608300453-atlas-v9/';
  const data = '../cartridges/5f5fbec83f9ce307b47ddc6e7277743f0bba1a2445b0f3ca50a9a1806146e993/grid_400kv.geojson';
  const full = new URL(data, documentBase).href;
  const geojson = JSON.stringify({ type: 'FeatureCollection', features: [{ type: 'Feature', properties: { voltage: 400000 }, geometry: { type: 'LineString', coordinates: [[1, 2], [3, 4]] } }] });
  const env = install({ documentBase, mapStyle: { layers: [{ id: 'l-400', source: 'src-400', layout: { visibility: 'visible' } }], sources: { 'src-400': { type: 'geojson', data }, inline: { type: 'geojson', data: { type: 'FeatureCollection', features: [] } } } } });
  env.lists.script = env.lists.script.filter(script => script.src);
  env.responses.set(full, [geojson, 'application/geo+json']);
  try {
    const result = await captureRuntimeSource({ baseBytes, baseManifest, fetchImpl: env.fetchImpl });
    const resource = result.manifest.resources.find(resource => resource.url === full);
    assert.equal(resource.status, 'included');
    assert.deepEqual(resource.expectedKinds, ['geojson']);
    assert.ok(resource.discoveredBy.some(item => item.reason.includes('src-400') && item.reason.includes('l-400')));
    assert.equal(resource.byteCount, Buffer.byteLength(geojson));
    assert.equal(resource.sha256, createHash('sha256').update(geojson).digest('hex'));
    assert.ok(new TextDecoder().decode(result.bytes).includes(geojson));
    assert.equal(env.calls.filter(call => call.url === full).length, 1);
    assert.ok(result.manifest.mapDependencies.some(item => item.status === 'embedded-state'));
    assert.deepEqual(result.manifest.state.map.sources.inline.data.features, []);
    assert.equal(result.manifest.state.resourceTiming.historyComplete, false);
    assert.equal(result.manifest.complete, false);
    assert.equal(result.manifest.failures.length, 0);
  } finally { env.restore(); }
});

test('TileJSON advertised URLs and DPR sprite pair are fetched; tile/glyph templates are explicit gaps', async () => {
  const env = install({ mapStyle: {
    layers: [{ id: 'roads', source: 'vector', layout: { visibility: 'visible' } }],
    sources: { vector: { type: 'vector', url: './tiles/tilejson.json' }, raster: { type: 'raster', tiles: ['https://tiles.test/{z}/{x}/{y}.png'] } },
    glyphs: './fonts/{fontstack}/{range}.pbf', sprite: './sprites/default?key=public',
  } });
  env.responses.set('https://app.test/view/tiles/tilejson.json', [JSON.stringify({ tilejson: '3.0.0', tiles: ['./7/2/3.pbf', './{z}/{x}/{y}.pbf'], data: ['./metadata.json'] }), 'application/json']);
  env.responses.set('https://app.test/view/tiles/7/2/3.pbf', [env.binary, 'application/x-protobuf']);
  env.responses.set('https://app.test/view/tiles/metadata.json', ['{"source":"roads"}', 'application/json']);
  env.responses.set('https://app.test/view/sprites/default@2x.json?key=public', ['{"marker":{"x":0,"y":0,"width":1,"height":1}}', 'application/json']);
  env.responses.set('https://app.test/view/sprites/default@2x.png?key=public', [Uint8Array.from([137, 80, 78, 71, 13, 10, 26, 10]), 'image/png']);
  try {
    const result = await captureRuntimeSource({ baseBytes, baseManifest, fetchImpl: env.fetchImpl });
    assert.ok(env.calls.some(call => call.url.endsWith('/tiles/7/2/3.pbf')));
    assert.ok(env.calls.some(call => call.url.endsWith('/tiles/metadata.json')));
    assert.ok(env.calls.some(call => call.url.endsWith('/default@2x.png?key=public')));
    assert.ok(env.calls.every(call => !/[{}]|%7B|%7D/i.test(call.url)), 'templates must never be fetched as invented coordinates');
    assert.equal(result.manifest.mapDependencies.filter(item => item.status === 'unresolved-template').length, 3);
    assert.ok(result.manifest.discoveryWarnings.some(item => item.reason.includes('Exact rendered worker tile set')));
    assert.equal(result.manifest.observedResourcesComplete, false);
    assert.equal(result.manifest.failures.length, 0);
  } finally { env.restore(); }
});

test('HTML or invalid JSON masquerading as live GeoJSON/TileJSON is retained but fails validation', async () => {
  const env = install({ mapStyle: { layers: [], sources: { bad: { type: 'geojson', data: './bad.geojson' }, vector: { type: 'vector', url: './bad-tilejson.json' } } } });
  env.responses.set('https://app.test/view/bad.geojson', ['<html>error page returned with status 200</html>', 'text/html']);
  env.responses.set('https://app.test/view/bad-tilejson.json', ['{"message":"missing tiles"}', 'application/json']);
  try {
    const result = await captureRuntimeSource({ baseBytes, baseManifest, fetchImpl: env.fetchImpl });
    assert.equal(result.manifest.failures.length, 2);
    assert.equal(result.manifest.resources.filter(resource => resource.status === 'included-invalid-map-data').length, 2);
    assert.ok(new TextDecoder().decode(result.bytes).includes('<html>error page returned with status 200</html>'));
    assert.equal(result.manifest.observedResourcesComplete, false);
  } finally { env.restore(); }
});

test('nested open shadow roots retain HTML, live forms, and stylesheet dependencies', async () => {
  const env = install();
  const inner = { innerHTML: '<textarea>default</textarea>', textContent: 'default', querySelectorAll: selector => selector === 'input,textarea,select' ? [{ tagName: 'TEXTAREA', id: 'shadow-notes', value: 'Edited in shadow', type: 'textarea' }] : [] };
  const outer = { innerHTML: '<style>.x{background:url("./shadow.png")}</style><nested-widget></nested-widget>', textContent: 'shadow content', querySelectorAll: selector => selector === '*' ? [{ tagName: 'NESTED-WIDGET', shadowRoot: inner }] : selector === 'style' ? [{ textContent: '.x{background:url("./shadow.png")}' }] : [] };
  env.lists['*'] = [{ tagName: 'TELEPRINTER-TOOLS', id: 'tools', shadowRoot: outer }];
  env.responses.set('https://app.test/view/shadow.png', [env.binary, 'image/png']);
  try {
    const result = await captureRuntimeSource({ baseBytes, baseManifest, fetchImpl: env.fetchImpl });
    assert.equal(result.manifest.state.openShadowRoots.length, 2);
    assert.ok(result.manifest.state.openShadowRoots[0].html.includes('nested-widget'));
    const form = result.manifest.state.forms.find(control => control.id === 'shadow-notes');
    assert.equal(form.value, 'Edited in shadow');
    assert.ok(form.root.includes('NESTED-WIDGET'));
    assert.ok(env.calls.some(call => call.url.endsWith('/shadow.png')));
    assert.ok(new TextDecoder().decode(result.bytes).includes('Edited in shadow'));
  } finally { env.restore(); }
});

test('global inline map geometry remains complete while public rendered features are clearly derived', async () => {
  const inlineData = { type: 'FeatureCollection', features: [{ type: 'Feature', properties: { onlyGlobal: 'not copied' }, geometry: { type: 'Point', coordinates: [12, 34] } }] };
  const env = install({ mapStyle: { layers: [{ id: 'visible', source: 'inline' }], sources: { inline: { type: 'geojson', data: inlineData } } } });
  window.__GRIDATLAS_V9_MAP__.queryRenderedFeatures = () => [{ type: 'Feature', id: 7, source: 'inline', layer: { id: 'visible' }, properties: { voltage: 275000 }, geometry: { type: 'Point', coordinates: [1, 2] } }];
  try {
    const { manifest, bytes } = await captureRuntimeSource({ baseBytes, baseManifest, fetchImpl: env.fetchImpl });
    assert.deepEqual(manifest.state.map.sources.inline.data, inlineData);
    const serialized = new TextDecoder().decode(bytes).split('===== BEGIN DIAGNOSTIC MANIFEST =====\n')[1].split('\n===== END DIAGNOSTIC MANIFEST =====')[0];
    assert.deepEqual(JSON.parse(serialized).state.map.sources.inline.data, inlineData);
    assert.equal(manifest.state.map.renderedFeatures.count, 1);
    assert.equal(manifest.state.map.renderedFeatures.features[0].properties.voltage, 275000);
    assert.match(manifest.state.map.renderedFeatures.provenance, /NOT original worker tile bytes/);
    assert.equal(inlineData.features[0].properties.onlyGlobal, 'not copied', 'capture must not mutate live map source');
  } finally { env.restore(); }
});

function installDirectTransport(env, { oversized = false, timedOut = false } = {}) {
  const savedFetch = globalThis.fetch;
  const savedXHR = Object.getOwnPropertyDescriptor(globalThis, 'XMLHttpRequest');
  let overriddenFetchCalls = 0;
  globalThis.fetch = async () => { overriddenFetchCalls++; throw new Error('DuckDB: No magic bytes found at end of parquet file'); };
  env.lists.script = env.lists.script.filter(script => !script.src?.startsWith('blob:'));
  class DiagnosticXHR {
    open(method, url, async) { assert.equal(method, 'GET'); assert.equal(async, true); this.url = url; }
    send() {
      assert.equal(this.responseType, 'arraybuffer');
      assert.equal(this.withCredentials, false);
      assert.equal(this.timeout, 30000);
      queueMicrotask(() => {
        if (timedOut) { this.ontimeout?.(); return; }
        if (this.url.startsWith('https://blocked.test')) { this.onerror?.(); return; }
        if (oversized) { this.onprogress?.({ loaded: 257 * 1024 * 1024 }); return; }
        const response = env.responses.get(this.url);
        assert.ok(response, `unexpected direct request ${this.url}`);
        const bytes = typeof response[0] === 'string' ? new TextEncoder().encode(response[0]) : response[0];
        this.status = response[2] ?? 200;
        this.responseURL = this.url;
        this.contentType = response[1];
        this.response = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
        this.onprogress?.({ loaded: bytes.length });
        this.onload?.();
      });
    }
    getResponseHeader(name) { return name === 'content-type' ? this.contentType : null; }
    abort() { this.aborted = true; this.onabort?.(); }
  }
  globalThis.XMLHttpRequest = DiagnosticXHR;
  return { calls: () => overriddenFetchCalls, restore() {
    globalThis.fetch = savedFetch;
    if (savedXHR) Object.defineProperty(globalThis, 'XMLHttpRequest', savedXHR);
    else delete globalThis.XMLHttpRequest;
  } };
}

test('default HTTP capture bypasses overridden Atlas fetch and preserves actual GeoJSON bytes', async () => {
  const env = install({ mapStyle: { layers: [{ id: 'grid400', source: 'grid400' }], sources: { grid400: { type: 'geojson', data: './grid_400kv.geojson' } } } });
  const geojson = JSON.stringify({ type: 'FeatureCollection', features: [{ type: 'Feature', properties: { name: 'café ⚡' }, geometry: { type: 'Point', coordinates: [1, 2] } }] });
  env.responses.set('https://app.test/view/grid_400kv.geojson', [geojson, 'application/geo+json']);
  const transport = installDirectTransport(env);
  try {
    const { bytes, manifest } = await captureRuntimeSource({ baseBytes, baseManifest });
    assert.equal(transport.calls(), 0, 'application fetch override must never service HTTP diagnostic requests');
    assert.equal(manifest.failures.length, 0);
    const resource = manifest.resources.find(item => item.url.endsWith('/grid_400kv.geojson'));
    assert.match(resource.transport, /XMLHttpRequest/);
    assert.equal(resource.status, 'included');
    assert.equal(resource.sha256, createHash('sha256').update(geojson).digest('hex'));
    assert.ok(new TextDecoder().decode(bytes).includes(geojson));
    const binary = manifest.resources.find(item => item.url.endsWith('/asset.bin'));
    assert.equal(binary.sha256, createHash('sha256').update(env.binary).digest('hex'));
  } finally { transport.restore(); env.restore(); }
});

test('direct HTTP preserves error bodies, reports CORS, and aborts excessive byte growth', async () => {
  const env = install({ blocked: true });
  const transport = installDirectTransport(env);
  try {
    const { bytes, manifest } = await captureRuntimeSource({ baseBytes, baseManifest });
    assert.equal(transport.calls(), 0);
    assert.equal(manifest.failures.length, 2);
    assert.match(new TextDecoder().decode(bytes), /\{"error":"not found"\}/);
    assert.ok(manifest.failures.some(failure => /network\/CORS/.test(failure.reason)));
  } finally { transport.restore(); env.restore(); }
  const largeEnv = install();
  const largeTransport = installDirectTransport(largeEnv, { oversized: true });
  try {
    await assert.rejects(captureRuntimeSource({ baseBytes, baseManifest }), /explicit 256 MiB resource limit/);
    assert.equal(largeTransport.calls(), 0);
  } finally { largeTransport.restore(); largeEnv.restore(); }
  const timeoutEnv = install();
  const timeoutTransport = installDirectTransport(timeoutEnv, { timedOut: true });
  try {
    const { manifest } = await captureRuntimeSource({ baseBytes, baseManifest });
    assert.ok(manifest.failures.length > 0);
    assert.ok(manifest.failures.every(failure => /30-second timeout/.test(failure.reason)));
    assert.equal(timeoutTransport.calls(), 0, 'timeouts must never silently fall back to the application fetch override');
  } finally { timeoutTransport.restore(); timeoutEnv.restore(); }
});

Codex Screen Capture Test

A test in the drivers folder of Teleprinter that checks App Frame.

testteleprinter / drivers/codex/screen-capture.test.mjs · lines 1–8 of 8 · 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 App Frame.
Application
teleprinter · drivers/codex · test
Uses
App Frame (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/screen-capture.test.mjs:1-8 · blob 8b7de8bfd4e7e5fc4fb7661d4c91998bd1cd1d37 · 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 { captureAppFrame } from './app-frame.js';
test('oversized app views refuse before any capture or sharing',async t=>{
 const names=['document','innerWidth','innerHeight','devicePixelRatio'];const saved=Object.fromEntries(names.map(n=>[n,Object.getOwnPropertyDescriptor(globalThis,n)]));t.after(()=>names.forEach(n=>saved[n]?Object.defineProperty(globalThis,n,saved[n]):delete globalThis[n]));
 for(const [n,v] of Object.entries({document:{fonts:{ready:Promise.resolve()}},innerWidth:20000,innerHeight:20000,devicePixelRatio:2}))Object.defineProperty(globalThis,n,{configurable:true,value:v});
 await assert.rejects(captureAppFrame(),/too large/);
});

Codex Screen PDF Test

A test in the drivers folder of Teleprinter that checks Screen PDF. It is built from the frame step (`frame`) and the inspect step (`inspect`).

testteleprinter / drivers/codex/screen-pdf.test.mjs · lines 1–113 of 113 · Not reached from any entry point (candidate for review) · pattern inspect (shared by 40 files)

What it does
It tests its inputs. Defines frame, inspect. Uses libraries node:test, 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: "`screen-pdf.mjs` embeds losslessly compressed RGB pixels (and an alpha mask when required), without JPEG encoding, reflow or scaling."
What it achieves
The README says: `screen-pdf.mjs` embeds losslessly compressed RGB pixels (and an alpha mask when required), without JPEG encoding, reflow or scaling.
Why it matters
Guards the behaviour of Screen PDF.
Application
teleprinter · drivers/codex · test
Uses
Screen PDF (import), node:test, node:assert/strict, node:child_process
Used by
none found
Produces
frame, inspect
Defines here
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/screen-pdf.test.mjs:1-113 · blob 9814436923d30e2f16ea1a475340fc7a8910b23c · GitHub at these lines
State
achieves: readme · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
import test from 'node:test';
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { screenPdf, getScreenPdfLayout } from './screen-pdf.mjs';

function frame(width = 320, height = 90, transparent = false) {
  const rgba = new Uint8Array(width * height * 4);
  for (let i = 0; i < width * height; i++) rgba.set([i % 251, (i * 7) % 253, (i * 13) % 255, transparent ? i % 256 : 255], i * 4);
  return { width, height, rgba };
}
const furniture = {
  brand: 'VENTUS  GLOBALGRID2050 · GRID ATLAS',
  title: 'Grid Atlas (layer view) \\ full screen',
  credit: 'Data © OpenStreetMap contributors | © CARTO | EV data © Open Charge Map',
  generation: '202609051419',
  capturedAt: '2026-09-05 15:00 UTC',
  url: 'https://example.test/atlas/?project=123&layers=grid,substations',
};
function inspect(pdf, source, layout, { render = true } = {}) {
  const code = `import sys,json,base64,io
from pypdf import PdfReader
import pymupdf
p=json.load(sys.stdin)
data=base64.b64decode(p['pdf']); rgba=base64.b64decode(p['rgba']); layout=p['layout']
r=PdfReader(io.BytesIO(data),strict=True); assert len(r.pages)==1
page=r.pages[0]; image=page['/Resources']['/XObject']['/Screen'].get_object()
rgb=bytes(value for index,value in enumerate(rgba) if index%4!=3)
assert image.get_data()==rgb, 'embedded RGB changed'
assert (image['/Width'],image['/Height'])==(p['width'],p['height'])
assert tuple(map(float,page.mediabox))==(0,0,layout['width'],layout['height'])
if '/SMask' in image: assert image['/SMask'].get_object().get_data()==rgba[3::4]
if isinstance(image['/ColorSpace'],list): assert image['/ColorSpace'][1].get_object()['/N']==3
fonts=page['/Resources'].get('/Font',{})
for name in fonts: assert fonts[name].get_object()['/Subtype']=='/Type1'
doc=pymupdf.open(stream=data,filetype='pdf'); rects=doc[0].get_image_rects(4)
assert len(rects)==1
rect=rects[0]; assert tuple(rect)==(0,layout['headerHeight'],p['width'],layout['headerHeight']+p['height'])
if p['render']:
 pix=doc[0].get_pixmap(matrix=pymupdf.Matrix(1,1),clip=rect,alpha=False)
 assert pix.samples==rgb, 'rendered image crop changed'
 full=doc[0].get_pixmap(matrix=pymupdf.Matrix(1,1),alpha=False)
 if layout['headerHeight']: assert full.samples[:3]==bytes([255,255,255]), 'header is not white'
 if layout['footerHeight']: assert full.samples[-3:]==bytes([255,255,255]), 'footer is not white'
print(json.dumps({'text':page.extract_text(),'fonts':len(fonts),'imageRect':list(rect),'pageHeight':float(page.mediabox.height)}))
`;
  return JSON.parse(execFileSync('python', ['-c', code], { input: JSON.stringify({ pdf: Buffer.from(pdf).toString('base64'), rgba: Buffer.from(source.rgba).toString('base64'), width: source.width, height: source.height, layout, render }), encoding: 'utf8', windowsHide: true, maxBuffer: 4 * 1024 * 1024 }));
}

test('default remains a single exact image with no furniture or fonts', async () => {
  const source = frame();
  const layout = getScreenPdfLayout(source.width, source.height);
  assert.deepEqual(layout.image, { x: 0, y: 0, width: source.width, height: source.height });
  assert.equal(layout.height, source.height);
  const result = inspect(await screenPdf(source), source, layout);
  assert.equal(result.fonts, 0);
  assert.equal(result.text, '');
});

test('white bands contain correctly encoded text outside byte-identical, rendered-identical screen', async () => {
  const source = frame();
  const layout = getScreenPdfLayout(source.width, source.height, furniture);
  const pdf = await screenPdf({ ...source, furniture });
  const raw = Buffer.from(pdf).toString('latin1');
  assert.ok(raw.includes('\\251'), 'copyright must be WinAnsi octal');
  assert.ok(raw.includes('\\267'), 'middle dot must be WinAnsi octal');
  assert.ok(raw.includes('\\(layer view\\)'), 'PDF parentheses must be escaped');
  const result = inspect(pdf, source, layout);
  assert.equal(result.fonts, 2);
  assert.ok(result.text.includes('© OpenStreetMap contributors'));
  assert.ok(result.text.includes('GLOBALGRID2050 · GRID ATLAS'));
  assert.ok(result.text.includes('generation 202609051419'));
  assert.ok(result.text.includes('2026-09-05 15:00 UTC'));
  assert.equal(layout.image.y, layout.footerHeight);
  assert.equal(layout.height, layout.headerHeight + source.height + layout.footerHeight);
});

test('long unbroken URLs and titles wrap without truncation, overlap or horizontal clipping', () => {
  const title = 'A long title (including details) '.repeat(8);
  const url = 'https://example.test/atlas/?long=' + 'abcdefgh0123456789'.repeat(35);
  const settings = { brand: 'VENTUS', title, url, credit: '', generation: '', capturedAt: '' };
  const layout = getScreenPdfLayout(220, 100, settings);
  assert.equal(layout.lines.filter(line => line.band === 'header' && line.font === 'regular').map(line => line.text).join(''), title);
  assert.equal(layout.lines.filter(line => line.band === 'footer').map(line => line.text).join(''), url);
  for (const line of layout.lines) {
    assert.ok(line.x >= 0 && line.x + line.width <= 220);
    if (line.band === 'footer') assert.ok(line.y - line.size * .25 > 0 && line.y + line.size < layout.footerHeight);
    else assert.ok(line.y - line.size * .25 > layout.footerHeight + 100 && line.y + line.size < layout.height);
  }
  const doubled = getScreenPdfLayout(440, 100, { ...settings, scale: 2 });
  const capped = getScreenPdfLayout(440, 100, { ...settings, scale: 4 });
  assert.deepEqual(doubled, capped);
  assert.equal(doubled.lines[0].size, 24);
});

test('ICC and alpha references remain correct when font objects follow them', async () => {
  const profile = new Uint8Array(132);
  new DataView(profile.buffer).setUint32(0, 132);
  profile.set(new TextEncoder().encode('RGB '), 16);
  profile.set(new TextEncoder().encode('acsp'), 36);
  for (const transparent of [false, true]) for (const withProfile of [false, true]) {
    const source = frame(160, 30, transparent);
    const pdf = await screenPdf({ ...source, furniture, ...(withProfile ? { iccProfile: profile } : {}) });
    const result = inspect(pdf, source, getScreenPdfLayout(160, 30, furniture), { render: !transparent && !withProfile });
    assert.equal(result.fonts, 2);
  }
});

test('invalid dimensions, excessive page height, and unusable furniture scale fail', async () => {
  assert.throws(() => getScreenPdfLayout(10, 20, furniture), /too narrow/);
  assert.throws(() => getScreenPdfLayout(320, 14400, furniture), /height limit/);
  assert.throws(() => getScreenPdfLayout(320, 100, { ...furniture, scale: NaN }), /scale/);
  await assert.rejects(screenPdf({ width: 1, height: 1, rgba: new Uint8Array(3), furniture }), /dimensions or pixels/);
});

Codex Source Code

A JavaScript module in the drivers folder of Teleprinter that creates source code bundle (`createSourceCodeBundle`), verifies source code bundle (`verifySourceCodeBundle`) and writes source code bundle (`writeSourceCodeBundle`), using SHA-256.

storageteleprinter / drivers/codex/source-code.mjs · lines 1–162 of 162 · Not reached from any entry point (candidate for review) · pattern header (shared by 3 files)

What it does
It lists and searches its content. Defines 13 functions or classes, including digest, fail, git, scopesOf, githubIdentity. Uses libraries node:child_process, node:util, node:crypto, node:fs/promises, node:path. 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.
Downstream impact
Used directly by 3 files: Codex Outcome Test (teleprinter); Codex Prepare Demo (teleprinter); Codex Source Code Test (teleprinter).
What it achieves
It creates source code bundle (`createSourceCodeBundle`), verifies source code bundle (`verifySourceCodeBundle`) and writes source code bundle (`writeSourceCodeBundle`). Print source code from committed Git objects.
Why it matters
Imported by Codex Prepare Demo. Checked by 2 tests, including Codex Outcome Test.
Application
teleprinter · drivers/codex · JavaScript module
Uses
node:child_process, node:util, node:crypto, node:fs/promises, node:path, node:url
Used by
run by Codex Outcome Test (script call), imported by Codex Prepare Demo (import), run by Codex Source Code Test (script call)
Produces
createSourceCodeBundle, verifySourceCodeBundle, verifySourceCodeBundleAgainstRepository, writeSourceCodeBundle
Defines here
digest, fail, git, scopesOf, githubIdentity, header, begin, end, createSourceCodeBundle, matches, verifySourceCodeBundle, verifySourceCodeBundleAgainstRepository, writeSourceCodeBundle
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/source-code.mjs:1-162 · blob 62f8d81f3edeb53d6ddba44fbc436aac9c557791 · 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
/** Print source code from committed Git objects. No working-tree files are read. */
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { createHash } from 'node:crypto';
import { writeFile, mkdir } from 'node:fs/promises';
import { dirname, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';

const exec = promisify(execFile);
const FORMAT = 'codex-print-source-code-v1';
const POLICY = Object.freeze({
  source: 'Committed Git blobs only; working-tree changes are never substituted.',
  inclusion: 'All regular files and symlink target blobs under each literal scope, including dotfiles and generated files, if valid UTF-8 text.',
  omission: 'NUL-containing or non-UTF-8 blobs and Git submodules are explicitly listed as omitted. No truncation.',
  boundaries: 'File startByte and byteCount identify exact original UTF-8 bytes in the bundle; offsets are zero-based. No newline normalization.',
});
const digest = bytes => createHash('sha256').update(bytes).digest('hex');
const utf8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
function fail(message) { throw new Error(`Print source code: ${message}`); }
async function git(repoDir, args) {
  try {
    return (await exec('git', ['-C', repoDir, ...args], {
      encoding: 'buffer', maxBuffer: 256 * 1024 * 1024, windowsHide: true,
    })).stdout;
  } catch (error) {
    fail(`Git command failed (${args[0]}): ${String(error.stderr || error.message).trim()}`);
  }
}
function scopesOf(paths) {
  if (!Array.isArray(paths) || paths.length === 0) fail('at least one path scope is required');
  return [...new Set(paths.map(path => {
    if (typeof path !== 'string' || !path || path.includes('\\') || path.includes('\0') || path.startsWith('/') || /^[A-Za-z]:/.test(path)) fail('invalid path scope');
    if (path === '.') return path;
    if (path.split('/').some(part => !part || part === '.' || part === '..')) fail(`unsafe path scope: ${path}`);
    return path;
  }))].sort();
}
function githubIdentity(value) {
  const match = /^(?:https:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([\w.-]+\/[\w.-]+?)(?:\.git)?\/?$/.exec(value.trim());
  if (!match) fail('repository identity must be a GitHub HTTPS or SSH repository URL');
  return `https://github.com/${match[1]}`;
}
function header(manifest) {
  return `PRINT SOURCE CODE\nFormat: ${FORMAT}\nRepository: ${manifest.repository}\nCommit: ${manifest.commit}\nTree: ${manifest.tree}\nScopes: ${JSON.stringify(manifest.scopes)}\nPolicy: ${JSON.stringify(POLICY)}\nInventory: ${JSON.stringify(manifest.files.map(({ startByte, ...entry }) => entry))}\n\n`;
}
function begin(file) { return `===== BEGIN FILE ${JSON.stringify(file.path)} | bytes=${file.byteCount} | sha256=${file.sha256} =====\n`; }
function end(file) { return `\n===== END FILE ${JSON.stringify(file.path)} =====\n\n`; }

/** revision is required and resolved once to a full immutable commit SHA. */
export async function createSourceCodeBundle({ repoDir, revision, paths = ['.'], repository } = {}) {
  if (!repoDir || typeof revision !== 'string' || !revision.trim() || revision.startsWith('-')) fail('repoDir and an explicit revision are required');
  const scopes = scopesOf(paths);
  const commit = (await git(repoDir, ['rev-parse', '--verify', '--end-of-options', `${revision}^{commit}`])).toString('utf8').trim();
  const tree = (await git(repoDir, ['rev-parse', '--verify', `${commit}^{tree}`])).toString('utf8').trim();
  const identity = githubIdentity(repository ?? (await git(repoDir, ['remote', 'get-url', 'origin'])).toString('utf8').trim());
  const listing = await git(repoDir, ['ls-tree', '-r', '-z', '--full-tree', commit]);
  let records;
  try { records = utf8.decode(listing).split('\0').filter(Boolean); } catch { fail('Git paths must be valid UTF-8'); }
  const entries = records.map(record => {
    const match = /^(\d+) (blob|commit) ([a-f0-9]+)\t([\s\S]+)$/.exec(record);
    if (!match) fail('unsupported Git tree entry');
    return { mode: match[1], type: match[2], blobOid: match[3], path: match[4] };
  });
  const matches = (entry, scope) => scope === '.' || entry.path === scope || entry.path.startsWith(`${scope}/`);
  for (const scope of scopes) if (!entries.some(entry => matches(entry, scope))) fail(`scope not found at ${commit}: ${scope}`);
  const selected = entries.filter(entry => scopes.some(scope => matches(entry, scope)));
  const bodies = new Map();
  const files = [];
  for (const { type, ...entry } of selected) {
    if (type === 'commit') { files.push({ ...entry, status: 'omitted', reason: 'Git submodule; contents belong to another repository' }); continue; }
    const bytes = await git(repoDir, ['cat-file', 'blob', entry.blobOid]);
    const metadata = { ...entry, byteCount: bytes.length, sha256: digest(bytes) };
    let reason;
    if (bytes.includes(0)) reason = 'Binary blob (contains NUL)';
    else { try { utf8.decode(bytes); } catch { reason = 'Non-UTF-8 blob'; } }
    if (reason) files.push({ ...metadata, status: 'omitted', reason });
    else { files.push({ ...metadata, status: 'included' }); bodies.set(entry.path, bytes); }
  }
  if (!bodies.size) fail('zero text-file coverage for the requested scopes');
  const manifest = { format: FORMAT, repository: identity, commit, tree, scopes, policy: POLICY, files };
  const parts = [Buffer.from(header(manifest))];
  let offset = parts[0].length;
  for (const file of files.filter(file => file.status === 'included')) {
    const prefix = Buffer.from(begin(file));
    const suffix = Buffer.from(end(file));
    file.startByte = offset + prefix.length;
    const bytes = bodies.get(file.path);
    parts.push(prefix, bytes, suffix);
    offset += prefix.length + bytes.length + suffix.length;
  }
  parts.push(Buffer.from('===== END PRINT SOURCE CODE =====\n'));
  const bytes = Buffer.concat(parts);
  manifest.byteCount = bytes.length;
  manifest.sha256 = digest(bytes);
  manifest.includedCount = bodies.size;
  manifest.omittedCount = files.length - bodies.size;
  const text = bytes.toString('utf8');
  verifySourceCodeBundle(text, manifest);
  return { text, manifest };
}

/** Integrity validation; repository-backed validation below also proves inventory coverage. */
export function verifySourceCodeBundle(text, manifest, { expectedRepository, expectedCommit } = {}) {
  if (!manifest || manifest.format !== FORMAT || typeof text !== 'string') fail('unsupported bundle');
  if (expectedRepository && manifest.repository !== expectedRepository) fail('repository mismatch');
  if (expectedCommit && manifest.commit !== expectedCommit) fail('commit mismatch');
  if (!/^[a-f0-9]{40,64}$/.test(manifest.commit) || !/^[a-f0-9]{40,64}$/.test(manifest.tree)) fail('invalid commit/tree identity');
  if (JSON.stringify(manifest.policy) !== JSON.stringify(POLICY)) fail('policy mismatch');
  if (!Array.isArray(manifest.files) || !manifest.files.length) fail('missing inventory');
  const bytes = Buffer.from(text, 'utf8');
  if (bytes.length !== manifest.byteCount || digest(bytes) !== manifest.sha256) fail('bundle byte count or SHA256 mismatch');
  const chunks = [Buffer.from(header(manifest))];
  let offset = chunks[0].length;
  let included = 0;
  let omitted = 0;
  const seen = new Set();
  for (const file of manifest.files) {
    if (typeof file.path !== 'string' || seen.has(file.path)) fail('invalid or duplicate inventory path');
    seen.add(file.path);
    if (file.status === 'omitted') { if (!file.reason) fail('omission without reason'); omitted++; continue; }
    if (file.status !== 'included') fail('invalid inventory status');
    included++;
    const prefix = Buffer.from(begin(file));
    if (!Number.isSafeInteger(file.byteCount) || file.byteCount < 0 || file.startByte !== offset + prefix.length) fail(`invalid boundary: ${file.path}`);
    const body = bytes.subarray(file.startByte, file.startByte + file.byteCount);
    if (body.length !== file.byteCount || digest(body) !== file.sha256) fail(`file integrity mismatch: ${file.path}`);
    const suffix = Buffer.from(end(file));
    chunks.push(prefix, body, suffix);
    offset += prefix.length + body.length + suffix.length;
  }
  chunks.push(Buffer.from('===== END PRINT SOURCE CODE =====\n'));
  if (!included || included !== manifest.includedCount || omitted !== manifest.omittedCount || !Buffer.concat(chunks).equals(bytes)) fail('inventory, framing, or coverage mismatch');
  return true;
}

/** Re-read Git objects and require the entire canonical bundle, including omissions, to match. */
export async function verifySourceCodeBundleAgainstRepository(text, manifest, options) {
  verifySourceCodeBundle(text, manifest, { expectedCommit: options.expectedCommit, expectedRepository: options.expectedRepository });
  const expected = await createSourceCodeBundle({ repoDir: options.repoDir, revision: options.expectedCommit ?? manifest.commit, repository: options.expectedRepository ?? manifest.repository, paths: options.paths ?? manifest.scopes });
  if (text !== expected.text || JSON.stringify(manifest) !== JSON.stringify(expected.manifest)) fail('bundle does not match committed repository inventory');
  return true;
}

/** Explicit output locations; text and manifest should be hosted together on one origin. */
export async function writeSourceCodeBundle(options) {
  const { textPath, manifestPath } = options;
  if (!textPath || !manifestPath || resolve(textPath) === resolve(manifestPath)) fail('distinct textPath and manifestPath are required');
  const bundle = await createSourceCodeBundle(options);
  await mkdir(dirname(resolve(textPath)), { recursive: true });
  await mkdir(dirname(resolve(manifestPath)), { recursive: true });
  await writeFile(textPath, bundle.text, 'utf8');
  await writeFile(manifestPath, `${JSON.stringify(bundle.manifest, null, 2)}\n`, 'utf8');
  return bundle.manifest;
}

if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
  const [repoDir, revision, textPath, manifestPath, ...paths] = process.argv.slice(2);
  try {
    const result = await writeSourceCodeBundle({ repoDir, revision, textPath, manifestPath, paths: paths.length ? paths : ['.'] });
    process.stdout.write(`Print source code: ${result.includedCount} included, ${result.omittedCount} omitted; commit ${result.commit}\n`);
  } catch (error) { process.stderr.write(`${error.message}\n`); process.exitCode = 1; }
}