In this section
- Codex Design Freeze storage · teleprinter / drivers/codex/design-freeze.mjs lines 1–284
- Codex Design Freeze Test test · teleprinter / drivers/codex/design-freeze.test.mjs lines 1–88
- Codex Driver transform · teleprinter / drivers/codex/driver.mjs lines 1–49
- Codex Driver Test test · teleprinter / drivers/codex/driver.test.mjs lines 1–103
Codex Design Freeze
A JavaScript module in the drivers folder of Teleprinter that reads pin, external evidence and the Renewable Energy Planning Database (REPD) register, using SHA-256.
storageteleprinter / drivers/codex/design-freeze.mjs · lines 1–284 of 284 · Not reached from any entry point (candidate for review) · pattern requireThat (shared by 2 files)
- What it does
- It loads pin, external evidence and the REPD register. Defines 14 functions or classes, including digest, stable, same, inside, representedTransportUrls. Uses libraries node:fs/promises, node:path, node:crypto, node:child_process, node:url. 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). Domain terms in the code: the REPD register.
- Inputs & outputs
- In: JSON file source-pin.json; JSON file source-code.manifest.json; JSON file external-evidence.json; command-line arguments.
- Downstream impact
- Used directly by 3 files: Codex Design Freeze Publish (teleprinter); Codex Design Freeze Publish Test (teleprinter); Codex Design Freeze Test (teleprinter).
- What it achieves
- It loads external artifact (`loadExternalArtifact`) and is built from the digest step (`digest`) and the stable step (`stable`). Fail-closed, offline design freeze gate. No publishing or Git mutation.
- Why it matters
- Run by Codex Design Freeze Publish. Checked by 2 tests, including Codex Design Freeze Publish Test.
- Application
- teleprinter · drivers/codex · JavaScript module
- Uses
- node:fs/promises, node:path, node:crypto, node:child_process, node:url
- Used by
- run by Codex Design Freeze Publish (script call), imported by Codex Design Freeze Publish Test (import), imported by Codex Design Freeze Test (import)
- Produces
- OFFLINE_ROOT, digest, representedTransportUrls, DEFAULT_EXTERNAL_REVIEW, evaluateFreeze
- Defines here
- digest, stable, same, inside, representedTransportUrls, requireThat, inspectExternalReviews, evaluateFreeze, check, artifact, framed, inventory, run, loadExternalArtifact
- 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/design-freeze.mjs:1-284 · blob db012409ae558906c8dda78bd7e44a21aa271fd2 · 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
/** Fail-closed, offline design freeze gate. No publishing or Git mutation. */
import fs from 'node:fs/promises';
import path from 'node:path';
import { createHash } from 'node:crypto';
import { spawnSync } from 'node:child_process';
import { fileURLToPath, pathToFileURL } from 'node:url';
export const OFFLINE_ROOT = 'C:/Users/vikra/OneDrive/Desktop/offline-screenshots';
export const digest = data => createHash('sha256').update(data).digest('hex');
const stable = value => JSON.stringify(value, (_, v) => v && !Array.isArray(v) && typeof v === 'object' ? Object.fromEntries(Object.entries(v).sort(([a],[b]) => a.localeCompare(b))) : v);
const identityKeys = ['url','generation','sourceCommit','engineCommit','buildSha256'];
const same = (a,b) => stable(a) === stable(b);
const inside = (file, root) => { const relative = path.relative(path.resolve(root), path.resolve(file)); return relative && !relative.startsWith('..') && !path.isAbsolute(relative); };
const recursionReason = 'Source transport/pin excluded to prevent recursive capture. The selected verified pinned source and its original manifest are included below; sibling app bundles are references only.';
/** Only selected-app source transport may be represented by the verified embedded base. */
export function representedTransportUrls({ diagnostic, candidate, files, buildRoot }) {
const resources = diagnostic.resources || [];
const represented = resources.filter(resource => resource.status === 'already-represented');
const exclusions = diagnostic.exclusions || [];
if (!represented.length && !exclusions.length) return new Set();
const requireThat = (value, message) => { if (!value) throw new Error(message); };
const current = new URL(diagnostic.state.url), baseUrl = new URL(candidate.url);
const app = ['atlas','pipeline','landing'].find(name => {
const appUrl = new URL(name === 'landing' ? './' : name + '/', baseUrl);
return current.origin === appUrl.origin && [appUrl.pathname, appUrl.pathname+'index.html'].includes(current.pathname);
});
requireThat(app, 'Cannot identify selected app for source transport');
const suffixes = ['source-pin.json','source-code.manifest.json','source-code.txt'];
const allowed = new Set(suffixes.map(suffix => new URL(`teleprinter/${app}-${suffix}`, baseUrl).href));
for (const resource of represented) {
requireThat(allowed.has(resource.url), `Unrepresented source transport: ${resource.url}`);
const matches = exclusions.filter(exclusion => exclusion.url === resource.url && exclusion.status === 'already-represented' && exclusion.reason === recursionReason);
requireThat(matches.length === 1, `Missing exact recursion exclusion: ${resource.url}`);
}
for (const exclusion of exclusions) requireThat(allowed.has(exclusion.url) && represented.some(resource => resource.url === exclusion.url) && exclusion.reason === recursionReason, `Arbitrary source exclusion: ${exclusion.url}`);
requireThat(new Set(represented.map(resource=>resource.url)).size === represented.length, 'Duplicate represented source transport');
const transport = suffixes.map(suffix => files[path.resolve(buildRoot, 'teleprinter', `${app}-${suffix}`)]);
requireThat(transport.every(Boolean), 'Selected source transport missing from pinned build');
const pin = JSON.parse(transport[0].toString('utf8')), manifest = JSON.parse(transport[1].toString('utf8'));
const base = diagnostic.baseManifest;
requireThat(pin.app === app && pin.generation === candidate.generation && pin.commit === candidate.sourceCommit && pin.repository === base.repository && pin.sha256 === base.sha256 && pin.byteCount === base.byteCount, 'Selected source pin does not represent embedded base');
requireThat(same(manifest,base) && digest(transport[2]) === base.sha256 && transport[2].length === base.byteCount, 'Selected source transport does not match embedded manifest/source');
return new Set(represented.map(resource=>resource.url));
}
export const DEFAULT_EXTERNAL_REVIEW = path.resolve(path.dirname(fileURLToPath(import.meta.url)), 'external-evidence.json');
const testedConditions = ['fifty-chrome-visits','pdf-frame-pixel-equality','source-selected-repd','source-complete-resource-frames','source-pinned-build-identity'];
function inspectExternalReviews({pins,candidate,buildManifest,files,checkedPaths,offlineRoot,check}) {
const audits = [];
const paths = pins.externalReviewPaths ?? [DEFAULT_EXTERNAL_REVIEW];
if (!check(Array.isArray(paths) && paths.length > 0 && new Set(paths).size === paths.length, 'Missing or invalid external review paths')) return audits;
for (const filename of paths) {
const bytes = files[filename], pin = pins.inputs?.find(input => input.path === filename);
if (!check(bytes && pin && digest(bytes) === pin.sha256, `Missing or changed pinned external review: ${filename}`)) continue;
let review; try { review = JSON.parse(bytes.toString('utf8')); } catch { check(false, `Malformed external review: ${filename}`); continue; }
if (!check(review.schema === 'codex-external-evidence-review-v1' && Array.isArray(review.runs) && Array.isArray(review.findings), `Invalid external review schema: ${filename}`)) continue;
const audit = {path:filename,sha256:digest(bytes),applicableFindingIds:[],resolutionProofs:[]}; audits.push(audit);
for (const run of review.runs) {
if (!check(typeof run.generation === 'string' && Array.isArray(run.artifacts), `Malformed audited run: ${filename}`)) continue;
for (const artifact of run.artifacts) {
const file = path.resolve(run.directory || '',artifact.filename || '');
check(inside(file,offlineRoot) && checkedPaths[file] === true && files[file] && files[file].length === artifact.bytes && digest(files[file]) === artifact.sha256, `External evidence missing or mutated: ${file}`);
}
}
const codeHashes = new Set((buildManifest?.files || []).map(entry => entry.sha256));
const ids = new Set();
for (const finding of review.findings) {
if (!check(typeof finding.id === 'string' && !ids.has(finding.id) && typeof finding.finding === 'string' && ['blocker','limitation','unsupported-claim'].includes(finding.severity), `Malformed external finding in ${filename}`)) continue;
ids.add(finding.id);
const generations = finding.appliesTo || [];
const buildHashes = finding.buildSha256 || [];
const shared = finding.sharedCodeSha256 || [];
if (!check(Array.isArray(generations) && Array.isArray(buildHashes) && Array.isArray(shared) && generations.every(value=>typeof value === 'string') && [...buildHashes,...shared].every(value=>/^[a-f0-9]{64}$/.test(value)), `Invalid finding applicability: ${finding.id}`)) continue;
// Explicitly assigned requirements apply before a test exists. Missing
// runtime evidence must not silently turn an open blocker into acceptance.
const applicable = generations.includes(candidate.generation) || buildHashes.includes(candidate.buildSha256) || shared.some(hash => codeHashes.has(hash));
if (!applicable || finding.severity !== 'blocker') continue;
audit.applicableFindingIds.push(finding.id);
let resolved = false;
const resolution = finding.resolution;
if (resolution) {
const proofBytes = files[resolution.proofPath], proofPin = pins.inputs?.find(input => input.path === resolution.proofPath);
let proof; try { proof = JSON.parse(proofBytes?.toString('utf8')); } catch {}
const artifactProof = proof?.evidence?.length > 0 && proof.evidence.every(item => inside(item.path,offlineRoot) && checkedPaths[item.path] === true && files[item.path] && files[item.path].length === item.bytes && digest(files[item.path]) === item.sha256);
const latestAudit = Math.max(0,...review.runs.map(run => Date.parse(run.summaryCreatedAt || '') || 0));
resolved = !!(proofBytes && proofPin && digest(proofBytes) === proofPin.sha256 && proof?.status === 'DESIGN FREEZE' && path.resolve(resolution.proofPath) === path.resolve(offlineRoot,'design-freeze',`${proof.proofSha256}.json`) && proof.counts?.visits === 50 && proof.counts?.pdf === 25 && proof.counts?.source === 25 && proof.counts?.png === 25 && proof.errors?.length === 0 && proof.proofSh … [line shortened here: 766 characters; full line on GitHub]
if (resolved) audit.resolutionProofs.push({findingId:finding.id,path:resolution.proofPath,sha256:digest(proofBytes),proofSha256:resolution.proofSha256,condition:resolution.condition});
}
check(resolved, `External blocking finding ${finding.id}: ${finding.finding}`);
}
}
return audits;
}
export function evaluateFreeze({ report, pins, files = {}, inspections = {}, currentHeads = {}, reachableCommits = {}, buildPaths = [], checkedPaths = {}, offlineRoot = OFFLINE_ROOT }) {
const errors = [], evidence = [];
const check = (condition, message) => { if (!condition) errors.push(message); return condition; };
const candidate = pins?.candidate;
if (!check(candidate && report, 'Missing report or pinned candidate')) return { status: 'REJECTED', errors };
for (const key of identityKeys) check(typeof candidate[key] === 'string' && candidate[key].length > 0, `Missing candidate ${key}`);
check(/^[a-f0-9]{40,64}$/.test(candidate.sourceCommit || ''), 'Source commit must be full SHA');
check(/^[a-f0-9]{40,64}$/.test(candidate.engineCommit || ''), 'Engine commit must be full SHA');
check(/^[a-f0-9]{64}$/.test(candidate.buildSha256 || ''), 'Missing build digest');
check(pins.expectedFurniture?.header?.length > 0 && pins.expectedFurniture?.footer?.some(text => text.includes(candidate.generation)), 'Expected footer must identify the candidate generation');
check(same(report.candidate, candidate), 'Report candidate differs from pinned candidate');
check(report.finishedAt && report.ok === true, 'Report not completed successfully');
check(report.browser === 'installed Chrome' && report.actualVisits === 50 && report.savedDownloads === 50 && report.expectedVisits === 50 && report.requestedScenarios === 25, 'Expected exactly fifty installed Chrome visits');
check(Array.isArray(pins.heads) && pins.heads.length > 0, 'Missing repository HEAD pins');
for (const commit of [candidate.sourceCommit,candidate.engineCommit]) check(reachableCommits[commit] === true, `Pinned commit absent or not an ancestor of captured HEAD: ${commit}`);
for (const head of pins.heads || []) check(currentHeads[head.repo] === head.commit, `Stale HEAD: ${head.repo}`);
check(Array.isArray(pins.inputs) && pins.inputs.length > 0, 'Missing source/build input pins');
check(pins.inputs?.some(input => input.sha256 === candidate.buildSha256), 'Build digest is not a pinned input');
for (const input of pins.inputs || []) check(files[input.path] && digest(files[input.path]) === input.sha256, `Changed or missing pinned input: ${input.path}`);
let buildManifest;
try { buildManifest = JSON.parse(files[pins.buildManifestPath]?.toString('utf8')); } catch { check(false, 'Missing or invalid build manifest'); }
check(files[pins.buildManifestPath] && digest(files[pins.buildManifestPath]) === candidate.buildSha256, 'Build manifest hash mismatch');
check(Array.isArray(buildManifest?.files) && buildManifest.files.length > 0, 'Empty build inventory');
check(pins.buildRoot && buildPaths.length > 0 && same([...buildPaths].sort(), (buildManifest?.files || []).map(entry => entry.path).sort()), 'Served directory inventory differs from build manifest');
for (const entry of buildManifest?.files || []) check(inside(entry.path, pins.buildRoot || '.') && files[entry.path] && digest(files[entry.path]) === entry.sha256, `Changed or missing served build file: ${entry.path}`);
const externalReviews = inspectExternalReviews({pins,candidate,buildManifest,files,checkedPaths,offlineRoot,check});
const scenarios = report.scenarios || [];
check(scenarios.length === 25 && new Set(scenarios.map(s => s.id)).size === 25, 'Expected twenty-five unique scenarios');
const visits = scenarios.flatMap(s => s.visits || []);
check(visits.length === 50 && visits.filter(v => v.mode === 'pdf').length === 25 && visits.filter(v => v.mode === 'source').length === 25, 'Expected 25 PDF and 25 source visits');
const ids = new Set(), paths = new Set();
function artifact(file, hash, kind) {
if (!check(typeof file === 'string' && inside(file, offlineRoot) && checkedPaths[file] === true, `${kind} path must resolve under offline root: ${file}`)) return null;
check(!paths.has(file), `Artifact reused: ${file}`); paths.add(file);
const bytes = files[file];
if (!check(bytes && /^[a-f0-9]{64}$/.test(hash || '') && digest(bytes) === hash, `Missing or mutated ${kind}: ${file}`)) return null;
evidence.push({ path:file, sha256:hash, bytes:bytes.length, kind }); return bytes;
}
for (const scenario of scenarios) {
check(scenario.pairStateMatches === true && scenario.visits?.length === 2, `Incomplete pair ${scenario.id}`);
const [pdf,source] = scenario.visits || [];
check(pdf?.mode === 'pdf' && source?.mode === 'source' && pdf?.state?.url === source?.state?.url && same(pdf?.state?.selectedLayerKeys || [], source?.state?.selectedLayerKeys || []) && pdf?.state?.project === source?.state?.project, `State mismatch ${scenario.id}`);
for (const visit of scenario.visits || []) {
const label = `${scenario.id}/${visit.mode}`;
check(visit.ok === true && !visit.error && !!visit.closedAt && visit.browser === 'installed Chrome', `Failed or incomplete Chrome visit ${label}`);
check(visit.visitId && !ids.has(visit.visitId), `Missing or reused visit ID ${label}`); ids.add(visit.visitId);
check(same(visit.candidate, candidate), `Candidate mismatch ${label}`);
try { check(new URL(visit.state?.url).href.startsWith(new URL(candidate.url).href.replace(/\/?$/, '/')), `URL outside candidate ${label}`); } catch { check(false, `Invalid URL ${label}`); }
const bytes = artifact(visit.path, visit.sha256, visit.mode);
check(bytes?.length === visit.bytes, `Byte count mismatch ${label}`);
if (visit.mode === 'pdf') {
artifact(visit.pngPath, visit.pngSha256, 'png');
const proof = inspections[visit.path];
check(proof?.sha256 === visit.sha256 && proof?.embeddedPixelsIdentical === true && proof?.renderedPixelsIdentical === true, `Pixel proof missing or failed ${label}`);
check(proof?.headersFootersPresent === true && proof?.imageRect?.[1] > 0 && proof?.imageRect?.[3] < proof?.pageHeight, `Header/footer must be outside image ${label}`);
check(proof?.expectedFurnitureMatched === true, `Expected header/footer text mismatch ${label}`);
} else if (visit.mode === 'source' && bytes) {
const text = bytes.toString('utf8');
const match = text.match(/===== BEGIN DIAGNOSTIC MANIFEST =====\n([\s\S]*?)\n===== END DIAGNOSTIC MANIFEST =====/);
let diagnostic; try { diagnostic = JSON.parse(match?.[1]); } catch { check(false, `Missing source diagnostic ${label}`); }
if (diagnostic) {
check(diagnostic.format === 'codex-runtime-source-v1' && diagnostic.baseManifest?.commit === candidate.sourceCommit && diagnostic.state?.url === visit.state?.url, `Source identity mismatch ${label}`);
if (scenario.project) check(/^\d+$/.test(String(scenario.project)) && new RegExp(`REPD\\s+${scenario.project}\\b`, 'i').test(diagnostic.state?.visibleText || ''), `Printed selected REPD project missing or wrong ${label}`);
check(typeof diagnostic.state?.visibleText === 'string' && diagnostic.state.visibleText.length > 0 && Array.isArray(diagnostic.state.forms) && diagnostic.state.viewport, `Missing current runtime state ${label}`);
check(Array.isArray(diagnostic.failures) && diagnostic.failures.length === 0, `Unavailable runtime source dependencies ${label}`);
check(Array.isArray(diagnostic.limitations) && diagnostic.limitations.length > 0 && Array.isArray(diagnostic.discoveryWarnings), `Source limitations not stated ${label}`);
check(Array.isArray(diagnostic.resources) && diagnostic.resources.length > 0, `Missing runtime dependency inventory ${label}`);
function framed(prefix, suffix, expectedBytes, expectedHash, encoding = 'utf-8') {
const start = bytes.indexOf(Buffer.from(prefix));
if (!check(start >= 0, `Missing source frame ${label}: ${prefix.slice(0,80)}`)) return;
const bodyStart = start + Buffer.byteLength(prefix);
const size = encoding === 'base64' ? 4 * Math.ceil(expectedBytes / 3) : expectedBytes;
const body = bytes.subarray(bodyStart, bodyStart + size);
const decoded = encoding === 'base64' ? Buffer.from(body.toString('ascii'),'base64') : body;
check(Number.isSafeInteger(expectedBytes) && expectedBytes >= 0 && decoded.length === expectedBytes && digest(decoded) === expectedHash && bytes.subarray(bodyStart+size,bodyStart+size+Buffer.byteLength(suffix)).equals(Buffer.from(suffix)), `Corrupt source frame ${label}`);
}
const base = diagnostic.baseManifest || {};
framed(`===== BEGIN PINNED SOURCE | bytes=${base.byteCount} | sha256=${base.sha256} =====\n`, '\n===== END PINNED SOURCE =====', base.byteCount, base.sha256);
const document = text.match(/===== BEGIN CURRENT DOCUMENT \| bytes=(\d+) \| sha256=([a-f0-9]{64}) =====\n/);
check(!!document, `Current document missing ${label}`);
if (document) framed(document[0], '\n===== END CURRENT DOCUMENT =====', Number(document[1]), document[2]);
let represented = new Set();
try { represented = representedTransportUrls({diagnostic,candidate,files,buildRoot:pins.buildRoot}); } catch (error) { check(false, `Invalid source exclusion ${label}: ${error.message}`); }
for (const resource of diagnostic.resources || []) {
if (resource.status === 'already-represented' && represented.has(resource.url)) continue;
check(resource.status === 'included' && ['utf-8','base64'].includes(resource.encoding), `Unavailable runtime dependency ${label}: ${resource.url}`);
framed(`===== BEGIN RESOURCE ${JSON.stringify(resource.url)} | originalBytes=${resource.byteCount} | encoding=${resource.encoding} | sha256=${resource.sha256} =====\n`, `\n===== END RESOURCE ${JSON.stringify(resource.url)} =====`, resource.byteCount, resource.sha256, resource.encoding);
}
}
}
}
}
const proofSha256 = digest(stable({ report, evidence, inputs:pins.inputs, heads:pins.heads }));
return { status:errors.length ? 'REJECTED' : 'DESIGN FREEZE', candidate, proofSha256, externalReviews, testedConditions:testedConditions.filter(condition=>condition !== 'source-selected-repd' || scenarios.some(scenario=>scenario.project)), reportFinishedAt:report.finishedAt, counts:{visits:visits.length,pdf:visits.filter(v=>v.mode==='pdf').length,source:visits.filter(v=>v.mode==='source').length … [line shortened here: 659 characters; full line on GitHub]
}
const here = path.dirname(fileURLToPath(import.meta.url));
async function inventory(directory) {
const output = [];
for (const entry of await fs.readdir(directory, {withFileTypes:true})) {
if (entry.name === '.git') continue;
const filename = path.resolve(directory, entry.name);
if (entry.isSymbolicLink()) throw new Error(`Build symlink is not accepted: ${filename}`);
if (entry.isDirectory()) output.push(...await inventory(filename));
else if (entry.isFile()) output.push(filename);
}
return output.sort();
}
async function run(reportPath, pinsPath) {
const [report,pins] = await Promise.all([fs.readFile(reportPath,'utf8').then(JSON.parse),fs.readFile(pinsPath,'utf8').then(JSON.parse)]);
const files = {}, checkedPaths = {}, currentHeads = {}, reachableCommits = {}, inspections = {};
let buildPaths = [];
try { buildPaths = await inventory(pins.buildRoot); } catch {}
const visits = (report.scenarios || []).flatMap(s => s.visits || []);
for (const filename of [...(pins.inputs || []).map(v=>v.path), ...visits.flatMap(v=>[v.path,v.pngPath]).filter(Boolean)]) {
try { const real = await fs.realpath(filename); checkedPaths[filename] = !!inside(real, await fs.realpath(OFFLINE_ROOT)); files[filename] = await fs.readFile(filename); } catch { /* Missing evidence is rejected below. */ }
}
let buildManifest;
try { files[pins.buildManifestPath] = await fs.readFile(pins.buildManifestPath); buildManifest = JSON.parse(files[pins.buildManifestPath]);
for (const entry of buildManifest.files || []) { try { files[entry.path] = await fs.readFile(entry.path); } catch {} }
} catch {}
const externalArtifactPaths = [];
async function loadExternalArtifact(filename) {
externalArtifactPaths.push(filename);
try { checkedPaths[filename] = !!inside(await fs.realpath(filename), await fs.realpath(OFFLINE_ROOT)); if (checkedPaths[filename]) files[filename] = await fs.readFile(filename); } catch {}
}
for (const filename of pins.externalReviewPaths ?? [DEFAULT_EXTERNAL_REVIEW]) {
try {
files[filename] = await fs.readFile(filename);
const review = JSON.parse(files[filename]);
for (const run of review.runs || []) for (const artifact of run.artifacts || []) await loadExternalArtifact(path.resolve(run.directory || '',artifact.filename || ''));
for (const finding of review.findings || []) if (finding.resolution?.proofPath) {
const proofPath = finding.resolution.proofPath;
files[proofPath] = await fs.readFile(proofPath);
const proof = JSON.parse(files[proofPath]);
for (const artifact of proof.evidence || []) await loadExternalArtifact(artifact.path);
}
} catch { /* Evaluation rejects missing, malformed or changed registries/proofs. */ }
}
for (const head of pins.heads || []) {
const result = spawnSync('git',['-C',head.repo,'rev-parse','HEAD'],{encoding:'utf8'});
if (result.status === 0) currentHeads[head.repo] = result.stdout.trim();
for (const commit of [pins.candidate.sourceCommit,pins.candidate.engineCommit]) {
const ancestor = spawnSync('git',['-C',head.repo,'merge-base','--is-ancestor',commit,head.commit],{encoding:'utf8'});
if (ancestor.status === 0) reachableCommits[commit] = true;
}
}
for (const visit of visits.filter(v => v.mode === 'pdf')) {
if (!files[visit.path] || !files[visit.pngPath] || !checkedPaths[visit.path] || !checkedPaths[visit.pngPath]) continue;
const result = spawnSync('python',[path.join(here,'inspect-pdf.py')],{input:JSON.stringify({pdf:files[visit.path].toString('base64'),png:files[visit.pngPath].toString('base64')}),encoding:'utf8',maxBuffer:2000000,timeout:60000});
if (result.status !== 0) continue;
try {
const proof = JSON.parse(result.stdout);
const expected = pins.expectedFurniture;
if (Array.isArray(expected?.header) && expected.header.length && Array.isArray(expected?.footer) && expected.footer.length) {
const script = 'import sys,json,base64,pymupdf\np=json.load(sys.stdin); d=pymupdf.open(stream=base64.b64decode(p["pdf"]),filetype="pdf"); r=p["rect"]; page=d[0]; h=page.get_text(clip=pymupdf.Rect(0,0,page.rect.width,r[1])); f=page.get_text(clip=pymupdf.Rect(0,r[3],page.rect.width,page.rect.height)); print(json.dumps(all(s in h for s in p["header"]) and all(s in f for s in p["footer"])))';
const textProof = spawnSync('python',['-c',script],{input:JSON.stringify({pdf:files[visit.path].toString('base64'),rect:proof.imageRect,...expected}),encoding:'utf8',timeout:60000});
proof.expectedFurnitureMatched = textProof.status === 0 && textProof.stdout.trim() === 'true';
}
inspections[visit.path] = proof;
} catch { /* Invalid inspection cannot qualify. */ }
}
// Re-read all inputs and HEADs after expensive PDF inspection to catch changes during verification.
for (const input of [...(pins.inputs || []), ...(buildManifest?.files || []), ...externalArtifactPaths.map(path => ({path})), ...visits.flatMap(visit => [visit.path,visit.pngPath].filter(Boolean).map(path => ({path}))), {path:pins.buildManifestPath}]) { try { files[input.path] = await fs.readFile(input.path); } catch { delete files[input.path]; } }
for (const head of pins.heads || []) {
const result = spawnSync('git',['-C',head.repo,'rev-parse','HEAD'],{encoding:'utf8'});
if (result.status !== 0 || result.stdout.trim() !== currentHeads[head.repo]) currentHeads[head.repo] = 'CHANGED';
}
try { if (!same(buildPaths, await inventory(pins.buildRoot))) buildPaths = []; } catch { buildPaths = []; }
const freeze = evaluateFreeze({report,pins,files,inspections,currentHeads,reachableCommits,buildPaths,checkedPaths});
if (freeze.status !== 'DESIGN FREEZE') { console.error(JSON.stringify(freeze)); return false; }
const directory = path.join(OFFLINE_ROOT,'design-freeze'); await fs.mkdir(directory,{recursive:true});
const stem = path.join(directory,freeze.proofSha256);
try { await fs.writeFile(stem+'.json',JSON.stringify(freeze,null,2)+'\n',{flag:'wx'}); }
catch (error) { if (error.code === 'EEXIST') return true; throw error; }
await fs.writeFile(stem+'.md',`# DESIGN FREEZE\n\nCandidate: ${freeze.candidate.url}\n\nGeneration: ${freeze.candidate.generation}\n\nSource commit: ${freeze.candidate.sourceCommit}\n\nEngine commit: ${freeze.candidate.engineCommit}\n\nBuild SHA-256: ${freeze.candidate.buildSha256}\n\nProof SHA-256: ${freeze.proofSha256}\n\n50 Chrome visits; 25 PDF + 25 source + 25 PNG.\n\n${freeze.scope}\n\nEvi … [line shortened here: 450 characters; full line on GitHub]
console.log(JSON.stringify({status:'READY',record:stem+'.json',candidate:freeze.candidate,proofSha256:freeze.proofSha256})); return true;
}
if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
const [report,pins,...options] = process.argv.slice(2);
if (!report || !pins) { console.error('Usage: node design-freeze.mjs REPORT.json PINS.json [--watch=SECONDS]'); process.exitCode = 2; }
else {
const option = options.find(v=>v.startsWith('--watch=')); const interval = option ? Number(option.split('=')[1]) : 0;
if (option && (!Number.isFinite(interval) || interval < 5)) throw new Error('Watch interval must be at least 5 seconds');
let previous;
do {
try {
const signature = digest(await fs.readFile(report)) + digest(await fs.readFile(pins));
if (signature !== previous) { const ok = await run(report,pins); previous = signature; if (!interval && !ok) process.exitCode = 1; }
} catch (error) { console.error(JSON.stringify({status:'REJECTED',error:String(error)})); if (!interval) process.exitCode = 1; }
if (interval) await new Promise(resolve=>setTimeout(resolve,interval*1000));
} while (interval);
}
}Codex Design Freeze Test
A test in the drivers folder of Teleprinter that checks Codex Design Freeze, using SHA-256 using data from the GridAtlas repository. It saves manifest (`saveManifest`) and sets review (`setReview`).
testteleprinter / drivers/codex/design-freeze.test.mjs · lines 1–88 of 88 · Not reached from any entry point (candidate for review) · pattern fixture (shared by 30 files)
- What it does
- It tests the REPD register. Defines fixture, withRepresentedTransport, saveManifest, setReview, blockingReview. Uses libraries node:test, node:path, 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). Domain terms in the code: the REPD register.
- Inputs & outputs
- In: JSON file source-pin.json; JSON file source-code.manifest.json.
- What it achieves
- Defines `fixture`, `withRepresentedTransport`, `saveManifest` and 2 more.
- Why it matters
- Guards the behaviour of Codex Design Freeze.
- Application
- teleprinter · drivers/codex · test
- Uses
- Codex Design Freeze (import), node:test, node:path, node:assert/strict
- Used by
- none found
- Produces
- fixture, withRepresentedTransport, saveManifest, setReview, blockingReview
- Defines here
- fixture, withRepresentedTransport, saveManifest, setReview, blockingReview
- 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/design-freeze.test.mjs:1-88 · blob bb3b1893593d30f3058db42beaef18222d45923f · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
import test from 'node:test';
import path from 'node:path';
import assert from 'node:assert/strict';
import { evaluateFreeze, digest, OFFLINE_ROOT, DEFAULT_EXTERNAL_REVIEW } from './design-freeze.mjs';
function fixture() {
const candidate={url:'https://example.org/20260905/',generation:'20260905',sourceCommit:'a'.repeat(40),engineCommit:'b'.repeat(40),buildSha256:digest(JSON.stringify({files:[{path:'served/code.js',sha256:digest('code')}]}))};
const external=Buffer.from(JSON.stringify({schema:'codex-external-evidence-review-v1',runs:[],findings:[]}));
const pins={externalReviewPaths:['external-review'],candidate,expectedFurniture:{header:['GLOBALGRID2050'],footer:[candidate.generation]},buildManifestPath:'build',buildRoot:'served',heads:[{repo:'source',commit:candidate.sourceCommit},{repo:'engine',commit:candidate.engineCommit}],inputs:[{path:'build',sha256:candidate.buildSha256},{path:'external-review',sha256:digest(external)}]};
const report={candidate,browser:'installed Chrome',finishedAt:'2026-09-05',ok:true,actualVisits:50,savedDownloads:50,expectedVisits:50,requestedScenarios:25,scenarios:[]};
const input={pins,report,files:{'external-review':external,build:Buffer.from(JSON.stringify({files:[{path:'served/code.js',sha256:digest('code')}]})), 'served/code.js':Buffer.from('code')},buildPaths:['served/code.js'],reachableCommits:{[candidate.sourceCommit]:true,[candidate.engineCommit]:true},checkedPaths:{},inspections:{},currentHeads:{source:candidate.sourceCommit,engine:candidate.engineCom … [line shortened here: 406 characters; full line on GitHub]
for(let i=0;i<25;i++) {
const state={url:candidate.url+'atlas/',project:'1',selectedLayerKeys:['400']};
const base=Buffer.from('PRINT SOURCE CODE\n'), doc=Buffer.from('<html>Current state</html>'), body=Buffer.from('export const current = true;');
const resource={url:candidate.url+'code.js',status:'included',byteCount:body.length,sha256:digest(body),encoding:'utf-8'};
const manifest={format:'codex-runtime-source-v1',baseManifest:{commit:candidate.sourceCommit,byteCount:base.length,sha256:digest(base)},state:{url:state.url,visibleText:'Current state REPD 1',forms:[],viewport:{width:100,height:100}},failures:[],limitations:['Computed unloaded references cannot be proven complete.'],discoveryWarnings:[],resources:[resource]};
const source=Buffer.from('PRINT SOURCE CODE\n===== BEGIN DIAGNOSTIC MANIFEST =====\n'+JSON.stringify(manifest)+'\n===== END DIAGNOSTIC MANIFEST =====\n'+`===== BEGIN PINNED SOURCE | bytes=${base.length} | sha256=${digest(base)} =====\n`+base+'\n===== END PINNED SOURCE =====\n'+`===== BEGIN CURRENT DOCUMENT | bytes=${doc.length} | sha256=${digest(doc)} =====\n`+doc+'\n===== END CURRENT DOCUMENT = … [line shortened here: 611 characters; full line on GitHub]
const visits=['pdf','source'].map(mode=>{const bytes=mode==='source'?source:Buffer.from('PDF fixture '+i);const file=OFFLINE_ROOT+`/case-${i}.${mode}`;input.files[file]=bytes;input.checkedPaths[file]=true;return {mode,state,candidate,visitId:`${i}-${mode}`,browser:'installed Chrome',ok:true,closedAt:'done',path:file,sha256:digest(bytes),bytes:bytes.length};});
const pdf=visits[0];pdf.pngPath=OFFLINE_ROOT+`/case-${i}.png`;input.files[pdf.pngPath]=Buffer.from('PNG fixture '+i);input.checkedPaths[pdf.pngPath]=true;pdf.pngSha256=digest(input.files[pdf.pngPath]);
input.inspections[pdf.path]={sha256:pdf.sha256,embeddedPixelsIdentical:true,renderedPixelsIdentical:true,headersFootersPresent:true,imageRect:[0,10,100,110],pageHeight:120,expectedFurnitureMatched:true};
report.scenarios.push({id:String(i),project:'1',pairStateMatches:true,visits});
}
return input;
}
test('complete, matching offline evidence qualifies with explicit limited scope',()=>{const result=evaluateFreeze(fixture());assert.equal(result.status,'DESIGN FREEZE',result.errors.join('\n'));assert.deepEqual(result.counts,{visits:50,pdf:25,source:25,png:25});});
for(const [name,mutate] of Object.entries({
'one missing visit':x=>x.report.scenarios[0].visits.pop(),
'mutated PDF':x=>x.files[x.report.scenarios[0].visits[0].path]=Buffer.from('changed'),
'bad PNG hash':x=>x.report.scenarios[0].visits[0].pngSha256='0'.repeat(64),
'missing PNG':x=>delete x.files[x.report.scenarios[0].visits[0].pngPath],
'stale HEAD':x=>x.currentHeads.source='c'.repeat(40),
'changed served file with unchanged manifest':x=>x.files['served/code.js']=Buffer.from('mutated'),
'unlisted served file':x=>x.buildPaths.push('served/unlisted.js'),
'unreachable source commit':x=>delete x.reachableCommits[x.pins.candidate.sourceCommit],
'changed build':x=>x.files.build=Buffer.from('changed'),
'failed visit':x=>x.report.scenarios[0].visits[0].ok=false,
'missing completion':x=>delete x.report.finishedAt,
'wrong candidate':x=>x.report.scenarios[0].visits[0].candidate={...x.pins.candidate,generation:'other'},
'reused visit':x=>x.report.scenarios[0].visits[0].visitId='1-pdf',
'PNG link outside root':x=>x.checkedPaths[x.report.scenarios[0].visits[0].pngPath]=false,
'pixel difference':x=>x.inspections[x.report.scenarios[0].visits[0].path].renderedPixelsIdentical=false,
'header covers image':x=>x.inspections[x.report.scenarios[0].visits[0].path].imageRect[1]=0,
'wrong header text':x=>x.inspections[x.report.scenarios[0].visits[0].path].expectedFurnitureMatched=false,
'source frame altered but outer hash updated':x=>{const v=x.report.scenarios[0].visits[1];x.files[v.path]=Buffer.from(x.files[v.path].toString().replace('export const current = true;','export const current = fake;'));v.sha256=digest(x.files[v.path]);v.bytes=x.files[v.path].length;},
'source dependency unavailable':x=>{const v=x.report.scenarios[0].visits[1];x.files[v.path]=Buffer.from(x.files[v.path].toString().replace('"status":"included"','"status":"unavailable"'));v.sha256=digest(x.files[v.path]);v.bytes=x.files[v.path].length;}
})) test(name+' rejects',()=>{const input=fixture();mutate(input);assert.equal(evaluateFreeze(input).status,'REJECTED');});
// Shape copied from the real 2026-09-05T14-52-04-724Z-7712 runtime diagnostic:
// resources retain discoveredBy/status; exclusions add the explicit recursion reason.
function withRepresentedTransport() {
const input=fixture(), visit=input.report.scenarios[0].visits[1];
const source=input.files[visit.path].toString('utf8');
const marker=/===== BEGIN DIAGNOSTIC MANIFEST =====\n([\s\S]*?)\n===== END DIAGNOSTIC MANIFEST =====/;
const manifest=JSON.parse(source.match(marker)[1]);
const reason='Source transport/pin excluded to prevent recursive capture. The selected verified pinned source and its original manifest are included below; sibling app bundles are references only.';
const records=['source-pin.json','source-code.manifest.json','source-code.txt'].map(suffix=>({url:new URL(`teleprinter/atlas-${suffix}`,input.pins.candidate.url).href,discoveredBy:[{from:'https://ventusltd.github.io/gridatlas/atlas/releases/202608300453-atlas-v9/',reason:'observed resource (fetch)'}],status:'already-represented'}));
manifest.resources.push(...records);manifest.exclusions=records.map(resource=>({...resource,reason}));
const pin={generation:input.pins.candidate.generation,app:'atlas',commit:input.pins.candidate.sourceCommit,sha256:manifest.baseManifest.sha256,byteCount:manifest.baseManifest.byteCount};
const transport=[JSON.stringify(pin),JSON.stringify(manifest.baseManifest),'PRINT SOURCE CODE\n'];
const build=JSON.parse(input.files.build.toString('utf8'));
records.forEach((record,index)=>{const filename=path.resolve(input.pins.buildRoot,'teleprinter',new URL(record.url).pathname.split('/').at(-1));input.files[filename]=Buffer.from(transport[index]);input.buildPaths.push(filename);build.files.push({path:filename,sha256:digest(input.files[filename])});});
input.files.build=Buffer.from(JSON.stringify(build));input.pins.candidate.buildSha256=digest(input.files.build);input.pins.inputs[0].sha256=input.pins.candidate.buildSha256;
function saveManifest() {input.files[visit.path]=Buffer.from(source.replace(marker,`===== BEGIN DIAGNOSTIC MANIFEST =====\n${JSON.stringify(manifest)}\n===== END DIAGNOSTIC MANIFEST =====`));visit.sha256=digest(input.files[visit.path]);visit.bytes=input.files[visit.path].length;}
saveManifest();return {input,manifest,saveManifest};
}
test('selected app transports represented by matching pinned source are accepted',()=>{const {input}=withRepresentedTransport();const result=evaluateFreeze(input);assert.equal(result.status,'DESIGN FREEZE',result.errors.join('\n'));});
test('arbitrary already-represented source file is rejected',()=>{const {input,manifest,saveManifest}=withRepresentedTransport();manifest.resources.at(-1).url=input.pins.candidate.url+'secret-source-code.txt';manifest.exclusions.at(-1).url=manifest.resources.at(-1).url;saveManifest();assert.equal(evaluateFreeze(input).status,'REJECTED');});
test('sibling app transport does not represent selected app',()=>{const {input,manifest,saveManifest}=withRepresentedTransport();manifest.resources.at(-1).url=manifest.resources.at(-1).url.replace('atlas-source','pipeline-source');manifest.exclusions.at(-1).url=manifest.resources.at(-1).url;saveManifest();assert.equal(evaluateFreeze(input).status,'REJECTED');});
test('missing recursion reason rejects represented transport',()=>{const {input,manifest,saveManifest}=withRepresentedTransport();manifest.exclusions[0].reason='Ignore this resource';saveManifest();assert.equal(evaluateFreeze(input).status,'REJECTED');});
test('transport exception never accepts actual unavailable dependency',()=>{const {input,manifest,saveManifest}=withRepresentedTransport();manifest.resources[0].status='unavailable';manifest.failures=[{url:manifest.resources[0].url,reason:'CORS unavailable'}];saveManifest();assert.equal(evaluateFreeze(input).status,'REJECTED');});
test('represented base must match pinned build transport bytes',()=>{const {input}=withRepresentedTransport();const file=input.buildPaths.find(file=>file.endsWith('atlas-source-code.txt'));input.files[file]=Buffer.from('wrong transport');assert.equal(evaluateFreeze(input).status,'REJECTED');});
function setReview(input,review) {input.files['external-review']=Buffer.from(JSON.stringify(review));input.pins.inputs.find(pin=>pin.path==='external-review').sha256=digest(input.files['external-review']);}
function blockingReview(input,overrides={}) {return {schema:'codex-external-evidence-review-v1',runs:[{generation:input.pins.candidate.generation,summaryCreatedAt:'2026-09-01',artifacts:[]}],findings:[{id:'EXT-REGRESSION',severity:'blocker',finding:'The specific printed condition failed',appliesTo:[input.pins.candidate.generation],...overrides}]};}
test('matching audited generation external blocker vetoes an otherwise passing run',()=>{const input=fixture();setReview(input,blockingReview(input));assert.ok(evaluateFreeze(input).errors.some(error=>error.includes('External blocking finding EXT-REGRESSION')));});
test('unrelated lane generation is audited but does not veto candidate',()=>{const input=fixture();const review=blockingReview(input,{appliesTo:['different-generation']});review.runs[0].generation='different-generation';setReview(input,review);const result=evaluateFreeze(input);assert.equal(result.status,'DESIGN FREEZE');assert.deepEqual(result.externalReviews,[{path:'external-review',sha256:diges … [line shortened here: 484 characters; full line on GitHub]
test('shared exact executable hash can veto a different generation',()=>{const input=fixture();const review=blockingReview(input,{appliesTo:['other'],sharedCodeSha256:[digest('code')]});review.runs[0].generation='other';setReview(input,review);assert.equal(evaluateFreeze(input).status,'REJECTED');});
test('exact audited build hash can veto despite different generation label',()=>{const input=fixture();const review=blockingReview(input,{appliesTo:['other'],buildSha256:[input.pins.candidate.buildSha256]});review.runs[0].generation='other';review.runs[0].buildSha256=input.pins.candidate.buildSha256;setReview(input,review);assert.equal(evaluateFreeze(input).status,'REJECTED');});
test('tampered registry hash is rejected',()=>{const input=fixture();input.files['external-review']=Buffer.from('{}');assert.equal(evaluateFreeze(input).status,'REJECTED');});
test('missing pinned registry is rejected',()=>{const input=fixture();delete input.files['external-review'];assert.equal(evaluateFreeze(input).status,'REJECTED');});
test('well-hashed but malformed registry is rejected',()=>{const input=fixture();setReview(input,{schema:'not-a-review',findings:[]});assert.equal(evaluateFreeze(input).status,'REJECTED');});
test('empty explicit registry list cannot disable review',()=>{const input=fixture();input.pins.externalReviewPaths=[];assert.equal(evaluateFreeze(input).status,'REJECTED');});
test('mutation of audited offline artifact fails even for unrelated generation',()=>{const input=fixture();const filename=path.resolve(OFFLINE_ROOT,'external-original.pdf');const review={schema:'codex-external-evidence-review-v1',runs:[{generation:'other',directory:OFFLINE_ROOT,artifacts:[{filename:'external-original.pdf',bytes:8,sha256:digest('original')}]}],findings:[]};input.checkedPaths[filena … [line shortened here: 535 characters; full line on GitHub]
test('manual resolved status and pass claim cannot clear external blocker',()=>{const input=fixture();setReview(input,blockingReview(input,{status:'resolved',resolution:{ok:true,reason:'Manually passed'}}));assert.equal(evaluateFreeze(input).status,'REJECTED');});
test('an exact pinned newer condition proof can resolve only its named condition',()=>{const input=fixture();const proofInput=fixture();proofInput.report.finishedAt='2026-09-06';const proof=evaluateFreeze(proofInput);const proofPath=path.resolve(OFFLINE_ROOT,'design-freeze',proof.proofSha256+'.json');input.files[proofPath]=Buffer.from(JSON.stringify(proof));input.pins.inputs.push({path:proofPath,s … [line shortened here: 955 characters; full line on GitHub]
test('printed selected project must be present in actual diagnostic text',()=>{const input=fixture();const visit=input.report.scenarios[0].visits[1];input.files[visit.path]=Buffer.from(input.files[visit.path].toString().replace('Current state REPD 1','Current state REPD 999'));visit.sha256=digest(input.files[visit.path]);visit.bytes=input.files[visit.path].length;assert.ok(evaluateFreeze(input).er … [line shortened here: 487 characters; full line on GitHub]
test('default tracked registry path is used when explicit paths are omitted',()=>{const input=fixture();delete input.pins.externalReviewPaths;input.files[DEFAULT_EXTERNAL_REVIEW]=input.files['external-review'];input.pins.inputs.find(pin=>pin.path==='external-review').path=DEFAULT_EXTERNAL_REVIEW;assert.equal(evaluateFreeze(input).status,'DESIGN FREEZE');delete input.files[DEFAULT_EXTERNAL_REVIEW]; … [line shortened here: 457 characters; full line on GitHub]
test('explicit candidate blocker applies even before a matching run exists',()=>{const input=fixture();const review=blockingReview(input);review.runs=[];setReview(input,review);assert.ok(evaluateFreeze(input).errors.some(error=>error.includes('External blocking finding EXT-REGRESSION')));});Codex Driver
A JavaScript module in the drivers folder of Teleprinter that attaches screen capture (`attachScreenCapture`).
transformteleprinter / drivers/codex/driver.mjs · lines 1–49 of 49 · Not reached from any entry point (candidate for review) · pattern diagnostic (shared by 2 files)
- What it does
- It calculates its inputs. Defines attachScreenCapture, clickAndReadDownload, diagnostic.
- 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: "`driver.mjs` attaches an in-memory Playwright screenshot provider."
- Downstream impact
- Used directly by 7 files: Codex App Outcomes (teleprinter); Codex App Print Browser (teleprinter); Codex Driver Test (teleprinter); Codex Fifty Prints (teleprinter); and 3 more.
- What it achieves
- It attaches screen capture (`attachScreenCapture`) and is built from the click and read download helper (`clickAndReadDownload`) and the diagnostic step (`diagnostic`). Playwright host: capture current compositor pixels in memory, never a screenshot file.
- Why it matters
- Imported by Codex App Print Browser. Run by 4 workflows and scripts, including Codex App Outcomes, Codex Fifty Prints and Codex File Print Compatibility. Checked by 2 tests, including Codex Driver Test.
- Application
- teleprinter · drivers/codex · JavaScript module
- Uses
- none found
- Used by
- run by Codex App Outcomes (script call), imported by Codex App Print Browser (import), imported by Codex Driver Test (import), run by Codex Fifty Prints (script call), run by Codex File Print Compatibility (script call), run by Codex Native Display Proof (script call), run by Codex Outcome Test (script call)
- Produces
- attachScreenCapture, clickAndReadDownload
- Defines here
- attachScreenCapture, clickAndReadDownload, diagnostic
- 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/driver.mjs:1-49 · blob d6340971887782328b1a00cac6302c0f0da0287f · 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
/** Playwright host: capture current compositor pixels in memory, never a screenshot file. */
export async function attachScreenCapture(page, { onCapture } = {}) {
await page.exposeBinding('__codexTeleprinterCapture', async ({ frame }) => {
if (frame !== page.mainFrame()) throw new Error('Only the main page can print this screen.');
const png = await page.screenshot({ type: 'png', fullPage: false, scale: 'device' });
onCapture?.(png);
return png.toString('base64');
});
}
/** Every rejection is observed immediately, including when clicking fails first. */
export async function clickAndReadDownload(page, locator, { timeout = 15000 } = {}) {
const diagnostic = async error => {
let appStatus = [];
try { appStatus = await page.locator('#codex-teleprinter #status, #gridatlas-teleprint-status').allTextContents(); } catch { /* Preserve the original error if the page closed. */ }
return { ok: false, error: String(error) + (appStatus.length ? ` | App: ${appStatus.join(' | ')}` : ''), appStatus };
};
const downloadPromise = page.waitForEvent('download', { timeout });
const results = await Promise.allSettled([downloadPromise, locator.click({ timeout })]);
const failed = results.find(result => result.status === 'rejected');
if (failed) {
if (results[0].status === 'fulfilled') {
await results[0].value.cancel().catch(() => {});
await results[0].value.delete().catch(() => {});
}
return diagnostic(failed.reason);
}
const download = results[0].value;
let timer, stream;
try {
return await Promise.race([
(async () => {
const failure = await download.failure();
if (failure) throw new Error(failure);
stream = await download.createReadStream();
if (!stream) throw new Error('The browser did not provide the downloaded file.');
const chunks = [];
for await (const chunk of stream) chunks.push(chunk);
return { ok: true, filename: download.suggestedFilename(), bytes: Buffer.concat(chunks) };
})(),
new Promise((_,reject) => { timer=setTimeout(()=>reject(new Error('The downloaded file did not finish in time.')),timeout); })
]);
} catch (error) { return diagnostic(error); }
finally {
clearTimeout(timer); stream?.destroy();
await download.cancel().catch(() => {});
await download.delete().catch(() => {});
}
}Codex Driver Test
A test in the drivers folder of Teleprinter that checks Codex Driver. It is built from the fixture step (`fixture`) and the bounded step (`bounded`).
testteleprinter / drivers/codex/driver.test.mjs · lines 1–103 of 103 · Not reached from any entry point (candidate for review) · pattern bounded (shared by 4 files)
- What it does
- It tests its inputs. Defines fixture, bounded. Uses libraries node:test, node:assert/strict, node:stream.
- 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
- Deterministic lifecycle checks complement the real-browser download outcomes.
- Why it matters
- Guards the behaviour of Codex Driver.
- Application
- teleprinter · drivers/codex · test
- Uses
- Codex Driver (import), node:test, node:assert/strict, node:stream
- Used by
- none found
- Produces
- fixture, bounded
- Defines here
- fixture, bounded
- 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/driver.test.mjs:1-103 · blob 1e975e2a1cf80a477661c7709c0cc598ff3360e2 · 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
/** Deterministic lifecycle checks complement the real-browser download outcomes. */
import test from 'node:test';
import assert from 'node:assert/strict';
import { Readable } from 'node:stream';
import { clickAndReadDownload } from './driver.mjs';
function fixture(overrides = {}) {
const state = { deleted: 0, cancelled: 0 };
const download = {
failure: async () => null,
createReadStream: async () => Readable.from([Buffer.from('complete '), Buffer.from('bytes\0\xff', 'latin1')]),
suggestedFilename: () => 'source.txt',
cancel: async () => { state.cancelled++; },
delete: async () => { state.deleted++; },
...overrides,
};
return { state, download, page: { waitForEvent: async () => download }, locator: { click: async () => {} } };
}
// A broken driver must fail this test instead of hanging the whole test process.
async function bounded(promise) {
let timer;
try {
return await Promise.race([
promise,
new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('Driver did not settle within the 1-second test watchdog.')), 1000); }),
]);
} finally { clearTimeout(timer); }
}
test('acquired download is deleted when its originating click rejects', async () => {
const { state, page } = fixture();
const result = await bounded(clickAndReadDownload(page, { click: async () => { throw new Error('click rejected after download started'); } }, { timeout: 40 }));
assert.equal(result.ok, false);
assert.match(result.error, /click rejected/);
assert.equal(state.deleted, 1, 'the acquired download must be deleted on the failed-click branch');
});
test('missing download and click timeout both reject without an unhandled promise', async () => {
let eventSettled = false;
let clickSettled = false;
const page = { waitForEvent(event, options) {
assert.equal(event, 'download');
assert.equal(options.timeout, 40);
return new Promise((_, reject) => setTimeout(() => { eventSettled = true; reject(new Error('download event timed out')); }, 15));
} };
const locator = { click(options) {
assert.equal(options.timeout, 40);
return new Promise((_, reject) => setTimeout(() => { clickSettled = true; reject(new Error('click timed out')); }, 5));
} };
const result = await bounded(clickAndReadDownload(page, locator, { timeout: 40 }));
assert.equal(result.ok, false);
assert.match(result.error, /timed out/);
assert.equal(eventSettled, true);
assert.equal(clickSettled, true);
});
test('download completion that never settles is bounded and cleaned up', async () => {
const { page, locator, state } = fixture({ failure: () => new Promise(() => {}) });
const result = await bounded(clickAndReadDownload(page, locator, { timeout: 40 }));
assert.equal(result.ok, false);
assert.match(result.error, /timed?\s*out|timeout|did not finish in time/i);
assert.equal(state.deleted, 1);
});
test('readback that never produces EOF is bounded, destroyed, and deleted', async () => {
const stream = new Readable({ read() {} });
const { page, locator, state } = fixture({ createReadStream: async () => stream });
try {
const result = await bounded(clickAndReadDownload(page, locator, { timeout: 40 }));
assert.equal(result.ok, false);
assert.match(result.error, /timed?\s*out|timeout|did not finish in time/i);
assert.equal(state.deleted, 1);
assert.equal(stream.destroyed, true, 'a timed-out read must not leave its stream open');
} finally { stream.destroy(); }
});
test('readback errors return a failed result and delete the download', async () => {
const stream = Readable.from((async function* () {
yield Buffer.from('partial content');
throw new Error('readback disconnected');
})());
const { page, locator, state } = fixture({ createReadStream: async () => stream });
const result = await bounded(clickAndReadDownload(page, locator, { timeout: 40 }));
assert.equal(result.ok, false);
assert.match(result.error, /readback disconnected/);
assert.equal(state.deleted, 1);
});
test('successful readback returns every original byte and deletes the download', async () => {
const { page, locator, state } = fixture();
const result = await bounded(clickAndReadDownload(page, locator, { timeout: 40 }));
assert.equal(result.ok, true);
assert.equal(result.filename, 'source.txt');
assert.deepEqual(result.bytes, Buffer.from('complete bytes\0\xff', 'latin1'));
assert.equal(state.deleted, 1);
});
test('download timeout retains the app error for diagnosis', async()=>{
const page={waitForEvent:async()=>{throw new Error('download timeout');},locator:()=>({allTextContents:async()=>['Source could not be prepared: headerLines is not defined']})};
const result=await clickAndReadDownload(page,{click:async()=>{}});
assert.equal(result.ok,false);assert.match(result.error,/headerLines is not defined/);assert.match(result.error,/download timeout/);
});