In this section
- Codex Cartridge Outcomes Browser render · teleprinter / drivers/codex/cartridge-outcomes.browser.mjs lines 1–297
- Codex Compact Campaign Report storage · teleprinter / drivers/codex/compact-campaign-report.py lines 1–21
- Codex Demo render · teleprinter / drivers/codex/demo.html lines 1–42
- Codex Design Freeze Publish storage · teleprinter / drivers/codex/design-freeze-publish.mjs lines 1–153
- Codex Design Freeze Publish Test test · teleprinter / drivers/codex/design-freeze-publish.test.mjs lines 1–20
Codex Cartridge Outcomes Browser
A JavaScript module in the drivers folder of Teleprinter that draws tool layers, using SHA-256.
renderteleprinter / drivers/codex/cartridge-outcomes.browser.mjs · lines 1–297 of 297 · Not reached from any entry point (candidate for review) · pattern state (shared by 17 files)
- What it does
- It draws tool layers. Defines states, state, ready. Uses libraries node:fs/promises, node:path, node:url, node:assert/strict. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain stage agent_infra (path word 'codex'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: JSON file release.json; JSON file tool-layers.json; JSON file derived-latest.json; JSON file style.json; command-line arguments. Out: JSON file results.json; canvas drawing.
- What it achieves
- It is built from the states step (`states`), the state step (`state`) and the ready step (`ready`). Actual installed-Chrome UI proof for the extracted controls.
- Why it matters
- No other file in the estate was found to import it.
- Application
- teleprinter · drivers/codex · JavaScript module
- Uses
- node:fs/promises, node:path, node:url, node:assert/strict
- Used by
- none found
- Produces
- states, state, ready
- Defines here
- states, state, ready
- 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/cartridge-outcomes.browser.mjs:1-297 · blob 4339d1e9b2b1275dc6a44d06bf5d62daedaf83ee · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
/** Actual installed-Chrome UI proof for the extracted controls. Artifacts stay offline. */
import fs from 'node:fs/promises';
import path from 'node:path';
import {pathToFileURL} from 'node:url';
import assert from 'node:assert/strict';
const base=process.argv[2], output=process.argv[3];
assert.ok(base && output && output.replaceAll('\\','/').includes('/offline-screenshots/'));
const {chromium}=await import(pathToFileURL(process.env.PLAYWRIGHT_MODULE || 'C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright/index.mjs'));
const release=await (await fetch(new URL('release.json',base))).json();
const toolsResponse=await fetch(new URL('atlas/tool-layers.json',base));
const toolConfig=toolsResponse.ok && toolsResponse.headers.get('content-type')?.includes('json') ? await toolsResponse.json() : null;
const records=[];await fs.mkdir(output,{recursive:true});
for(const viewport of [{width:1400,height:900},{width:393,height:852}]) {
let browser,page;const record={viewport,generation:release.generation,engineCommit:release.teleprinter.commit};
try {
browser=await chromium.launch({channel:'chrome',headless:true});
page=await browser.newPage({viewport,deviceScaleFactor:viewport.width===393?2:1});
if(process.argv.includes('--map-frame'))await page.addInitScript(()=>{window.__capturePermissionCalls=0;if(navigator.mediaDevices)navigator.mediaDevices.getDisplayMedia=()=>{window.__capturePermissionCalls++;throw Error('Screen sharing forbidden');};});
if(process.argv.includes('--local-tool-capsules')) {
record.localToolCapsules=true;
await page.route('**/tool-layers/*.js',async route=>{
const name=new URL(route.request().url()).pathname.split('/').at(-1);
if(!['host.js','dismissal.js','focus-boundary.js','readiness.js','viewport.js','session-restart.js','recovery.js','navigation.js'].includes(name))return route.continue();
await route.fulfill({body:await fs.readFile(path.join('C:/Users/vikra/testcode-source-publication/sandbox/capsules/tool-layers',name)),contentType:'text/javascript'});
});
}
if(process.argv.includes('--navigation-preview')) {
record.navigationPreview=true;
const {buildNavigationRegistry}=await import(pathToFileURL('C:/Users/vikra/testcode-source-publication/sandbox/capsules/tool-layers/registry.mjs'));
toolConfig.navigation=buildNavigationRegistry(toolConfig);
await page.route('**/atlas/teleprinter-bootstrap.js',async route=>{const response=await route.fetch();const body=(await response.text()).replace(/mountToolLayers\([^\n]+/,`mountToolLayers(${JSON.stringify(toolConfig.tools)}, import.meta.url, ${JSON.stringify(toolConfig.navigation)});`);await route.fulfill({response,body});});
}
if(process.argv.includes('--recover')) {
record.recoveryFaultInjection=true;let injected=false;
await page.route('**/module-layout/index.html',route=>{
if(injected)return route.continue();injected=true;return route.fulfill({status:404,contentType:'text/html',body:'<!doctype html><html><body>Injected missing tool</body></html>'});
});
}
let releaseModuleStyle;
if(process.argv.includes('--module-preview')) {
record.moduleProducerPreview=true;
const root='C:/Users/vikra/OneDrive/Documents/GitHub/layout-tool';
const pointer=JSON.parse(await fs.readFile(path.join(root,'derived-latest.json'),'utf8'));
const producer=path.join(root,'releases',pointer.generation,'solar-bess-topology-v7/module-layout');
await page.route('**/module-layout/*',async route=>{
const name=new URL(route.request().url()).pathname.split('/').at(-1);
if(!/^[a-zA-Z0-9_.-]+$/.test(name))return route.continue();
try {await route.fulfill({body:await fs.readFile(path.join(producer,name)),contentType:name.endsWith('.html')?'text/html':name.endsWith('.css')?'text/css':'text/javascript'});}catch{return route.continue();}
});
}
if(process.argv.includes('--cable-preview')) {
record.cableProducerPreview=true;
const root='C:/Users/vikra/OneDrive/Documents/GitHub/cable-trench-or-drill';
const pointer=JSON.parse(await fs.readFile(path.join(root,'derived-latest.json'),'utf8'));
const producer=path.join(root,'releases',pointer.generation,'solar-bess-topology-v7/cable-geometry-visualiser');
await page.route('**/cable-geometry-visualiser/*',async route=>{
const name=new URL(route.request().url()).pathname.split('/').at(-1);
if(!/^[a-zA-Z0-9_.-]+$/.test(name))return route.continue();
try {await route.fulfill({body:await fs.readFile(path.join(producer,name)),contentType:name.endsWith('.html')?'text/html':name.endsWith('.css')?'text/css':'text/javascript'});}catch{return route.continue();}
});
}
if(process.argv.includes('--gis-preview')) {
record.gisProducerPreview=true;
const root='C:/Users/vikra/OneDrive/Documents/GitHub/unnamed-01';
const pointer=JSON.parse(await fs.readFile(path.join(root,'derived-latest.json'),'utf8'));
const producer=path.join(root,'releases',pointer.generation,'solar-bess-topology-v7/gis-sld-financial-sandbox');
await page.route('**/gis-sld-financial-sandbox/*',async route=>{
const name=new URL(route.request().url()).pathname.split('/').at(-1);
if(!/^[a-zA-Z0-9_.-]+$/.test(name))return route.continue();
try {await route.fulfill({body:await fs.readFile(path.join(producer,name)),contentType:name.endsWith('.html')?'text/html':name.endsWith('.css')?'text/css':'text/javascript'});}catch{return route.continue();}
});
}
if(process.argv.includes('--guard')) {
record.moduleStyleGate=true;const gate=new Promise(resolve=>releaseModuleStyle=resolve);
await page.route('https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json',async route=>{
if(route.request().frame().url().includes('/module-layout/'))await gate;
await route.continue();
});
}
await page.goto(new URL('atlas/?repd_ref=1938&technology=solar',base).href,{waitUntil:'domcontentloaded'});
await page.getByText(/TEST CODE repd-1938 \| ENGINE COMPLETED/).first().waitFor({timeout:90000});
const grid=page.locator('#codex-layer-quick-controls [data-layer-command="grid"]');
const subs=page.locator('#codex-layer-quick-controls [data-layer-command="subs"]');
await grid.waitFor({state:'visible',timeout:60000});
await page.waitForFunction(()=>!document.querySelector('[data-layer-command="grid"]')?.disabled,null,{timeout:60000});
const states=()=>page.evaluate(()=>Object.fromEntries(['400','275','220','132','66','subs'].map(id=>[id,document.querySelector('#scada-ui-container input[data-layer-id="'+id+'"]')?.checked])));
const panel=page.locator('.scada-wrapper');
if(Number(release.generation)>=202609051848) assert.equal(await panel.getAttribute('data-gridatlas-collapsed'),'1','Layers must start collapsed');
await page.waitForFunction(()=>{const value=JSON.stringify([...document.querySelectorAll('#scada-ui-container input[data-layer-id]')].map(n=>[n.dataset.layerId,n.checked]));const now=performance.now();const previous=window.__controlReadiness;if(!previous||previous.value!==value){window.__controlReadiness={value,since:now};return false;}return now-previous.since>=500;},null,{timeout:15000,polling … [line shortened here: 407 characters; full line on GitHub]
const first=await states();
// Normalise through the real group button, then prove both directions.
if(['400','275','220','132','66'].every(id=>first[id])) await grid.click();
await grid.click();const enabled=await states();
assert.ok(['400','275','220','132','66'].every(id=>enabled[id]));
await grid.click();const disabled=await states();
assert.ok(['400','275','220','132','66'].every(id=>!disabled[id]));
record.beforeSubs=disabled;await subs.click();await page.waitForFunction(expected=>document.querySelector('#scada-ui-container input[data-layer-id="subs"]')?.checked===expected,!disabled.subs,{timeout:5000});const subChanged=await states();assert.notEqual(subChanged.subs,disabled.subs);
assert.ok(['400','275','220','132','66'].every(id=>subChanged[id]===disabled[id]));
await grid.click();
const beforePanel=await states();
const toggle=page.locator('#gridatlas-dash-toggle');await toggle.click();await toggle.click();
assert.deepEqual(await states(),beforePanel,'Panel visibility changed enabled layers');
const bounds=await page.locator('#codex-layer-quick-controls').boundingBox(),map=await page.locator('#map-container').boundingBox();
assert.ok(bounds.x>=map.x && bounds.x<map.x+40 && bounds.y+bounds.height<=map.y+map.height+2,'Quick controls must stay bottom-left within map');
assert.ok(bounds.y>map.y+map.height/2);record.quickControlBounds=bounds;
if(toolConfig) {
record.tools=[];
for(const tool of toolConfig.tools) {
await page.locator('#codex-tool-layers').getByRole('button',{name:tool.title,exact:true}).click();
const dialog=page.getByRole('dialog',{name:tool.title,exact:true});
await dialog.waitFor({state:'visible'});
const frame=dialog.frameLocator('iframe');
if(process.argv.includes('--recover') && tool.id==='module-layout') {
const retry=dialog.getByRole('button',{name:'Retry tool loading',exact:true});await retry.waitFor({state:'visible',timeout:10000});
await page.screenshot({path:path.join(output,`${viewport.width}-injected-load-failure.png`)});
await retry.click();assert.equal(await frame.getByText('Injected missing tool',{exact:true}).count(),1,'Retry must request confirmation before navigation');
await Promise.all([page.waitForEvent('framenavigated',{predicate:f=>f.url().includes('/module-layout/index.html')}),dialog.getByRole('button',{name:'Confirm restart',exact:true}).click()]);
await retry.waitFor({state:'hidden',timeout:10000});
}
if(tool.id==='gis-sld-financial-sandbox') {
await frame.locator('#btn_draw').waitFor({state:'attached',timeout:60000});
if(process.argv.includes('--route-state')) {
const realm=page.frames().find(f=>f.url().includes('/gis-sld-financial-sandbox/index.html'));
await realm.waitForFunction(()=>typeof map!=='undefined'&&map?.isStyleLoaded()&&map.getSource('topology'),null,{timeout:60000});
assert.equal(await realm.evaluate(()=>GisSldRoute.getSnapshot().status),'empty');
await frame.locator('#btn_draw').click();
await realm.waitForFunction(()=>GisSldRoute.getSnapshot().status==='available',null,{timeout:15000});
const direct=await realm.evaluate(()=>GisSldRoute.getSnapshot());assert.equal(direct.route.geometry.coordinates.length,2);
await frame.locator('#btn_map_drop_pins').click();
assert.equal(await realm.evaluate(()=>GisSldRoute.getSnapshot().status),'editing');
assert.equal(await realm.evaluate(()=>GisSldRoute.getSnapshot().route),null);
const canvas=frame.locator('#map canvas');await canvas.scrollIntoViewIfNeeded();
const points=await canvas.evaluate(canvas=>{const r=canvas.getBoundingClientRect(),hits=[];for(let y=Math.max(r.top+20,20);y<Math.min(r.bottom-20,innerHeight-20);y+=30)for(let x=Math.max(r.left+20,20);x<Math.min(r.right-20,innerWidth-20);x+=30)if(document.elementFromPoint(x,y)===canvas)hits.push({x:x-r.left,y:y-r.top});return hits;});
assert.ok(points.length>=2,'The original map must expose space for route drawing');
await canvas.click({position:points[Math.floor(points.length*.3)]});
await canvas.click({position:points[Math.floor(points.length*.7)]});
await frame.locator('#btn_map_draw_route').click();
const manual=await realm.evaluate(()=>GisSldRoute.getSnapshot());
assert.equal(manual.status,'available');assert.equal(manual.pins.length,2);assert.equal(manual.route.geometry.coordinates.length,4);assert.equal(manual.committed,true);
assert.equal(await realm.evaluate(()=>{const snapshot=GisSldRoute.getSnapshot();const original=JSON.stringify(state.currentGeoJSON);try{snapshot.route.geometry.coordinates[0][0]=0;}catch{}return Object.isFrozen(snapshot.route.geometry.coordinates[0])&&original===JSON.stringify(state.currentGeoJSON);}),true,'Read-only adapter must not expose mutable original state');
await page.screenshot({path:path.join(output,`${viewport.width}-manual-route.png`)});
if(process.argv.includes('--map-frame')) {
await realm.waitForFunction(()=>map.isStyleLoaded()&&map.getSource('topology')&&!map.isMoving(),null,{timeout:15000});
const captured=await realm.evaluate(()=>GisSldMapFrame.capture());
await fs.writeFile(path.join(output,`${viewport.width}-gis-map.png`),Buffer.from(captured.png.split(',')[1],'base64'));
await frame.locator('#map canvas').screenshot({path:path.join(output,`${viewport.width}-gis-map-reference.png`)});
assert.ok(captured.width>0&&captured.height>0);assert.equal(captured.route.committed,true);assert.equal(captured.route.pins.length,2);
assert.equal(await realm.evaluate(()=>window.__capturePermissionCalls),0);
assert.equal(await realm.evaluate(async()=>{const controller=new AbortController();controller.abort();try{await GisSldMapFrame.capture({signal:controller.signal});return 'unexpected';}catch(e){return e.name;}}),'AbortError');
delete captured.png;record.gisMapFrame={...captured,permissionCalls:0,preAbortedRefused:true};
}
await frame.locator('#btn_map_clear_route').click();const cleared=await realm.evaluate(()=>GisSldRoute.getSnapshot());assert.equal(cleared.pins.length,0);assert.equal(cleared.route.geometry.coordinates.length,2);
record.gisRoute={direct,manual,clearRestoresDirect:true,immutableCopy:true};
}
await frame.locator('#mod_wp').fill('665');
await frame.locator('#mod_wp').press('Tab');
await page.screenshot({path:path.join(output,`${viewport.width}-${tool.id}-open.png`)});
await dialog.getByRole('button',{name:/Close.*return to GridAtlas/}).click();
assert.deepEqual(await states(),beforePanel,'Closing tool altered Atlas layers');
await page.locator('#codex-tool-layers').getByRole('button',{name:tool.title,exact:true}).click();
assert.equal(await frame.locator('#mod_wp').inputValue(),'665','Reopening lost standalone app state');
}
if(tool.id==='module-layout') {
if(process.argv.includes('--guard')) {
await frame.locator('#ml-draw-readiness[data-ready="false"]').waitFor({timeout:15000});
assert.equal(await frame.locator('#ml_draw_center').isDisabled(),true);
assert.equal(await frame.locator('#ml_pick_site').isDisabled(),true);
const realm=page.frames().find(f=>f.url().includes('/module-layout/index.html'));
const state=()=>realm.evaluate(()=>({centre:mlState.centre,pickMode:mlState.pickMode,features:mlState.currentGeoJSON.features.length}));
const before=await state();await frame.locator('#ml_draw_center').dispatchEvent('click');await frame.locator('#ml_pick_site').dispatchEvent('click');
assert.deepEqual(await state(),before,'Blocked draw or pick changed original state');
await page.screenshot({path:path.join(output,`${viewport.width}-guard-pending.png`)});
releaseModuleStyle();await frame.locator('#ml-draw-readiness[data-ready="true"]').waitFor({timeout:60000});
assert.equal(await frame.locator('#ml_draw_center').isDisabled(),false);record.moduleGuard={blockedEarly:true,originalStatePreserved:true,enabledAfterMap:true};
}
await frame.locator('#ml_status').filter({hasText:'Ready. Draw at map centre or pick a site.'}).waitFor({timeout:60000});
await frame.locator('#ml_total_modules').fill('120');
await frame.locator('#ml_modules_per_row').fill('20');
await frame.locator('#ml_draw_center').click();
await frame.locator('#ml_out_rows').filter({hasText:/^6$/}).waitFor({timeout:15000});
assert.equal((await frame.locator('#ml_out_rows').innerText()).trim(),'6');
assert.equal((await frame.locator('#ml_out_rendered').innerText()).trim(),'120');
await page.screenshot({path:path.join(output,`${viewport.width}-${tool.id}-open.png`)});
}
if(tool.id==='cable-geometry-visualiser') {
await frame.locator('#route_name').fill('Chrome integration test');
await frame.locator('#route_name').press('Tab');
assert.ok((await frame.locator('#status_box').innerText()).length>0);
const drawingFrame=page.frames().find(f=>f.url().includes('/cable-geometry-visualiser/index.html'));
await drawingFrame.waitForFunction(()=>{const canvases=[...document.querySelectorAll('canvas')];return canvases.length===3&&canvases.every(c=>{const data=c.getContext('2d').getImageData(0,0,c.width,c.height).data;for(let i=3;i<data.length;i+=4)if(data[i])return true;return false;});},null,{timeout:15000,polling:200});
if(process.argv.includes('--cable-signal')) {
const ready=()=>drawingFrame.waitForFunction(()=>window.CableGeometryRender?.getState().state==='ready',null,{timeout:15000});
await ready();
await frame.locator('#route_name').fill('Route readiness regression');await ready();
const beforeBlur=await drawingFrame.evaluate(()=>CableGeometryRender.getState());
await frame.locator('#route_name').press('Tab');
assert.equal(await drawingFrame.evaluate(()=>CableGeometryRender.getState().state),'ready','Route-name blur must not invent a pending render');
const revision=beforeBlur.revision;
const pending=await drawingFrame.evaluate(()=>{const el=document.getElementById('circuit_qty');el.value='8';el.dispatchEvent(new Event('input',{bubbles:true}));return CableGeometryRender.getState().state;});
assert.equal(pending,'pending');await ready();
const signal=await drawingFrame.evaluate(async()=>{const text=document.getElementById('snapshot_box').textContent;const hash=[...new Uint8Array(await crypto.subtle.digest('SHA-256',new TextEncoder().encode(text)))].map(x=>x.toString(16).padStart(2,'0')).join('');return {state:CableGeometryRender.getState(),hash,input:document.getElementById('circuit_qty').value};});
assert.equal(signal.state.snapshotSha256,signal.hash);assert.ok(signal.state.revision>revision);assert.equal(signal.input,'8');
await frame.locator('#circuit_qty').dispatchEvent('input');await ready();
assert.ok(await drawingFrame.evaluate(previous=>CableGeometryRender.getState().revision>previous,signal.state.revision),'An identical-value redraw still advances the render revision');
record.cableSignal={routeNameBlurStable:true,pendingBeforeRender:true,snapshotHashMatched:true,repeatRenderAdvanced:true,receipt:signal.state};
}
record.cableCanvases=await frame.locator('canvas').evaluateAll(nodes=>nodes.map(canvas=>{const p=canvas.getContext('2d').getImageData(0,0,canvas.width,canvas.height).data;let opaque=0;const colors=new Set();for(let i=0;i<p.length;i+=4){if(p[i+3])opaque++;colors.add(p[i]+','+p[i+1]+','+p[i+2]);}return {id:canvas.id,width:canvas.width,height:canvas.height,opaque,colors:colors.size};}));
assert.equal(record.cableCanvases.length,3);
assert.ok(record.cableCanvases.every(c=>c.opaque>100&&c.colors>4),'Cable canvases must contain drawn geometry');
await page.screenshot({path:path.join(output,`${viewport.width}-${tool.id}-open.png`)});
}
if(process.argv.includes('--viewport')) {
const boxes=await dialog.evaluate(layer=>Object.fromEntries(['header','strong','[data-tool-readiness]','header button','iframe'].map(selector=>{const r=layer.querySelector(selector).getBoundingClientRect();return [selector,{x:r.x,y:r.y,width:r.width,height:r.height,right:r.right,bottom:r.bottom}];})));
for(const box of Object.values(boxes))assert.ok(box.x>=0&&box.right<=viewport.width+1,'Tool header or frame overflows horizontally');
assert.ok(boxes.iframe.height>100&&boxes.iframe.bottom<=viewport.height+1,'Tool iframe must fit viewport');
assert.ok(boxes['header button'].height>=44,'Close target must stay touch sized');
assert.ok(boxes.strong.right<=boxes['header button'].x,'Title and close must not overlap');
}
if(process.argv.includes('--readiness')) {
const ready=dialog.locator('[data-tool-readiness]');
await ready.locator('xpath=self::*[@data-interface="loaded"]').waitFor({timeout:35000});
const expected=tool.id==='gis-sld-financial-sandbox'?'unreported':'ready';
await page.waitForFunction(({id,expected})=>document.querySelector('[data-tool-readiness="'+id+'"]')?.dataset.drawing===expected,{id:tool.id,expected},{timeout:35000});
}
if(process.argv.includes('--focus')) {
const close=dialog.getByRole('button',{name:/Close.*return to GridAtlas/});
const lastHeader=dialog.locator('header button:visible').last();
await lastHeader.focus();await page.keyboard.press('Tab');
const toolFrame=page.frames().find(f=>f.url().includes(tool.id+'/index.html'));
assert.ok(await toolFrame.evaluate(()=>document.activeElement!==document.body),'Tab must enter tool');
await page.keyboard.press('Shift+Tab');
assert.equal(await lastHeader.evaluate(n=>n===document.activeElement),true,'Shift Tab must return to last header control');
await close.focus();await page.keyboard.press('Shift+Tab');
assert.ok(await toolFrame.evaluate(()=>document.activeElement!==document.body),'Reverse Tab must enter end of tool');
await page.keyboard.press('Tab');
assert.equal(await close.evaluate(n=>n===document.activeElement),true,'Last tool control must wrap to close');
}
if(process.argv.includes('--restart') && tool.id==='module-layout') {
await dialog.getByRole('button',{name:'Restart tool',exact:true}).click();
await dialog.getByRole('button',{name:/Close.*return to GridAtlas/}).click();
await page.locator('#codex-tool-layers').getByRole('button',{name:tool.title,exact:true}).click();
assert.equal(await dialog.getByRole('button',{name:'Confirm restart',exact:true}).count(),0,'Reopening must clear armed restart');
await dialog.getByRole('button',{name:'Restart tool',exact:true}).click();
await dialog.getByRole('button',{name:'Keep working',exact:true}).click();
assert.equal(await frame.locator('#ml_total_modules').inputValue(),'120','Cancel restart must keep work');
await dialog.getByRole('button',{name:'Restart tool',exact:true}).click();
await Promise.all([page.waitForEvent('framenavigated',{predicate:f=>f.url().includes('/module-layout/index.html')}),dialog.getByRole('button',{name:'Confirm restart',exact:true}).click()]);
await frame.locator('#ml_status').filter({hasText:'Ready. Draw at map centre or pick a site.'}).waitFor({timeout:60000});
assert.equal(await frame.locator('#ml_total_modules').inputValue(),'1200','Confirmed restart must restore original session');
const gis=page.frames().find(f=>f.url().includes('/gis-sld-financial-sandbox/index.html'));
assert.equal(await gis.locator('#mod_wp').inputValue(),'665','Restarting Module must retain GIS work');
assert.deepEqual(await states(),beforePanel,'Restarting tool changed Atlas');
}
if(process.argv.includes('--source-browser')) {
const opened=page.context().waitForEvent('page');await dialog.getByRole('button',{name:'Source code',exact:true}).click();const sourcePage=await opened;
try{await sourcePage.waitForLoadState('domcontentloaded');await sourcePage.locator('#status').filter({hasText:'Choose a file'}).waitFor();assert.equal(await sourcePage.locator('#tool').inputValue(),tool.id);await sourcePage.locator('#open').click();await sourcePage.locator('#status').filter({hasText:/^Verified /}).waitFor();}finally{await sourcePage.close();}
}
if(process.argv.includes('--escape')) {
await frame.locator('body').press('Escape');
await dialog.waitFor({state:'hidden'});
assert.equal(await page.locator('#codex-tool-layers').getByRole('button',{name:tool.title,exact:true}).evaluate(n=>n===document.activeElement),true,'Escape must return focus');
assert.deepEqual(await states(),beforePanel,'Escape changed Atlas layers');
} else await dialog.getByRole('button',{name:/Close.*return to GridAtlas/}).click();
record.tools.push({id:tool.id,opened:true,closed:true,escape:process.argv.includes('--escape'),focusBoundary:process.argv.includes('--focus'),readiness:process.argv.includes('--readiness'),viewport:process.argv.includes('--viewport'),restart:process.argv.includes('--restart')&&tool.id==='module-layout',recovery:process.argv.includes('--recover')&&tool.id==='module-layout'});
}
} else if(Number(release.generation)>=202609051850) {
await page.locator('.neon-layout').first().waitFor({state:'attached',timeout:30000});
await page.locator('#codex-layout-command button').click();
await page.getByText('Layout sandbox',{exact:false}).first().waitFor({state:'visible',timeout:30000});
record.layoutOpened=true;
}
if(process.argv.includes('--navigation')) {
const navigationLayers=await states();
await page.locator('#codex-tool-layers').getByRole('button',{name:'Cable Geometry',exact:true}).click();
const cableDialog=page.getByRole('dialog',{name:'Cable Geometry',exact:true});
await cableDialog.frameLocator('iframe').getByRole('link',{name:/^Module Layout V7$/i}).click();
const linked=page.getByRole('dialog',{name:'Module Layout',exact:true}).filter({visible:true});
await linked.waitFor({state:'visible'});const linkedFrame=linked.frameLocator('iframe');
const owner=JSON.parse(await linked.getAttribute('data-current-owner'));assert.equal(owner.commit,toolConfig.tools.find(t=>t.id==='module-layout').owner.commit);
await linkedFrame.locator('#ml_total_modules').fill('321');
await linked.getByRole('button',{name:'Restart tool',exact:true}).click();await linked.getByRole('button',{name:'Confirm restart',exact:true}).click();
await linkedFrame.locator('#ml_total_modules').waitFor();assert.equal(await linkedFrame.locator('#ml_total_modules').inputValue(),'1200','Restart must stay on navigated Module');
await linkedFrame.getByRole('link',{name:'DC AC LV Topology Review',exact:true}).click();
const dc=page.getByRole('dialog',{name:'DC/AC LV Topology Review',exact:true});await dc.waitFor({state:'visible'});
assert.equal(JSON.parse(await dc.getAttribute('data-current-owner')).commit,toolConfig.navigation.find(t=>t.id==='dc-ac-lv-topology-review').owner.commit);
assert.equal(await dc.locator('[data-tool-readiness]').getAttribute('data-drawing'),'unreported');
await page.screenshot({path:path.join(output,`${viewport.width}-sibling-navigation.png`)});
await dc.getByRole('button',{name:/Close.*return to GridAtlas/}).click();assert.deepEqual(await states(),navigationLayers);
record.siblingNavigation={moduleOwner:owner,currentDocumentRestart:true,dcOwnerResolved:true,atlasRetained:true};
}
record.layerStates=await states();record.ok=true;
await page.screenshot({path:path.join(output,`${viewport.width}-controls.png`),fullPage:false});
} catch(error) {record.ok=false;record.error=String(error);if(page){record.failureControls=await page.locator('input[data-layer-id="subs"]').evaluateAll(nodes=>nodes.map(n=>({parent:n.closest('[id]')?.id,checked:n.checked,connected:n.isConnected}))).catch(()=>null);await page.screenshot({path:path.join(output,`${viewport.width}-failure.png`)}).catch(()=>{});}}
finally {await browser?.close();records.push(record);await fs.writeFile(path.join(output,'results.json'),JSON.stringify({base,records},null,2));console.log(JSON.stringify(record));}
}
if(records.some(r=>!r.ok))process.exitCode=1;Codex Compact Campaign Report
A Python module in the drivers folder of Teleprinter covering campaign results, using SHA-256.
storageteleprinter / drivers/codex/compact-campaign-report.py · lines 1–21 of 21 · Not reached from any entry point (candidate for review)
- What it does
- Uses libraries pathlib, hashlib, json, sys. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage agent_infra (path word 'codex'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: JSON file campaign-results.json; command-line arguments.
- What it achieves
- Publish small measured findings while preserving the full receipt offline.
- Why it matters
- No other file in the estate was found to import it.
- Application
- teleprinter · drivers/codex · Python module
- Uses
- pathlib, hashlib, json, sys
- 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/compact-campaign-report.py:1-21 · blob 46031ed256e4be5a5682e8359f48792a88599a86 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
"""Publish small measured findings while preserving the full receipt offline."""
from pathlib import Path
import hashlib
import json
import sys
source = Path(sys.argv[1])
raw = source.read_bytes()
report = json.loads(raw)
offline = Path(report['output']) / 'campaign-results.json'
offline.write_bytes(raw)
summary = {key: report.get(key) for key in ['candidate', 'createdAt', 'finishedAt', 'ok', 'browser', 'physicalDevices', 'actualVisits', 'savedDownloads']}
summary['fullReceiptSha256'] = hashlib.sha256(raw).hexdigest()
summary['offlineReceipt'] = str(offline)
summary['scenarios'] = []
for scenario in report['scenarios']:
item = {key: scenario.get(key) for key in ['id', 'kind', 'geometry', 'project', 'layers', 'search', 'pairStateMatches']}
item['visits'] = [{key: visit.get(key) for key in ['visitId', 'mode', 'ok', 'closedAt', 'bytes', 'sha256', 'pngSha256', 'inspection', 'error']} for visit in scenario['visits']]
summary['scenarios'].append(item)
Path(sys.argv[2]).write_text(json.dumps(summary, indent=2) + '\n', encoding='utf8')
print(json.dumps({'fullReceiptBytes': len(raw), 'publishedSummaryBytes': Path(sys.argv[2]).stat().st_size, 'ok': report['ok']}))Codex Demo
A web page in the drivers folder of Teleprinter that renders with WebGL and reads inputs for layer and screenshot. It is built from the draw step (`draw`).
renderteleprinter / drivers/codex/demo.html · lines 1–42 of 42 · Entry point
- What it does
- It draws its content. Defines draw. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage agent_infra (path word 'codex'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: JSON file source-code.manifest.json; user-supplied file (file picker); form fields (user input). Out: web page; WebGL/WebGPU drawing.
- Downstream impact
- It is itself an entry point (page); no other file was found loading it.
- What it achieves
- Print and Print source code. It responds to change, resize and click events.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- teleprinter · drivers/codex · page
- Uses
- Print Screen (import), Print Source Code (import)
- Used by
- none found
- Produces
- draw
- Defines here
- draw
- 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/demo.html:1-42 · blob 155ebbdd12383aeca19033f7b77b71c517a522f8 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: agent_infra · users: ai_agent · canonical: unknown
<!doctype html>
<html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Teleprinter — Print and Print source code</title>
<style>
*{box-sizing:border-box}body{margin:0;background:#071820;color:#edf9ff;font:17px system-ui}main{padding:20px;max-width:850px;margin:auto}button,label{font:inherit}button{min-height:44px;padding:10px 14px;background:#d7ffff;color:#102632;border:1px solid #71a7b2;border-radius:5px;cursor:pointer}button:disabled{opacity:.6}nav{display:flex;flex-wrap:wrap;gap:10px}#scene{position:relative;height:170px … [line shortened here: 685 characters; full line on GitHub]
</style>
<main><h1>Teleprinter</h1><p>Print keeps what you see as a digital PDF. Print source code gives you a text file to attach in ChatGPT.</p>
<label><input id="layer" type="checkbox"> Show grid layer</label>
<div id="scene"><canvas id="map"></canvas><div class="card">Current view<br><strong id="layer-state">Grid layer hidden</strong></div></div>
<nav><button id="print">Print</button><button id="print-source">Print source code</button><button id="copy-source">Copy source code</button><button id="share-source" hidden>Share source code</button></nav>
<p id="status" role="status" aria-live="polite">Choose Print, or take the source code with you.</p>
<details><summary>Print a screenshot</summary><p>If this browser cannot capture its screen, take a screenshot on your device, then choose it here. Its pixels will be kept at their original size.</p><input id="screenshot" type="file" accept="image/png,image/jpeg,image/webp"><button id="print-image">Print selected screenshot</button></details>
<div id="source-text"></div>
</main><script type="module">
import { printScreen } from './print-screen.js';
import { attachPrintSourceCode } from './print-source-code.js';
const status = document.querySelector('#status');
const canvas = document.querySelector('#map');
const draw = () => {
canvas.width = Math.round(canvas.clientWidth * devicePixelRatio); canvas.height = Math.round(canvas.clientHeight * devicePixelRatio);
const gl = canvas.getContext('webgl', { preserveDrawingBuffer: true });
if (gl) { gl.clearColor(.09,.29,.35,1); gl.clear(gl.COLOR_BUFFER_BIT); gl.enable(gl.SCISSOR_TEST); gl.scissor(canvas.width/2,0,canvas.width/2,canvas.height); gl.clearColor(...(document.querySelector('#layer').checked ? [.85,.6,.07,1] : [.12,.19,.25,1])); gl.clear(gl.COLOR_BUFFER_BIT); gl.disable(gl.SCISSOR_TEST); }
document.querySelector('#layer-state').textContent = document.querySelector('#layer').checked ? 'Grid layer visible' : 'Grid layer hidden';
};
draw(); document.querySelector('#layer').addEventListener('change', draw); addEventListener('resize', draw);
const capture = window.__codexTeleprinterCapture ? async () => {
const encoded = await window.__codexTeleprinterCapture();
return new Blob([Uint8Array.from(atob(encoded), c => c.charCodeAt(0))], { type: 'image/png' });
} : undefined;
for (const [id, useImage] of [['#print',false],['#print-image',true]]) {
document.querySelector(id).addEventListener('click', async () => {
try {
const image = useImage ? document.querySelector('#screenshot').files[0] : undefined;
if (useImage && !image) throw new Error('Choose a screenshot first.');
const result = await printScreen({ capture, image });
status.textContent = `PDF ready: ${result.width} × ${result.height} pixels. Check your downloads.`;
window.lastPrintReceipt = result;
} catch (error) { status.textContent = error.message; }
});
}
attachPrintSourceCode({ button: document.querySelector('#print-source'), copyButton: document.querySelector('#copy-source'), shareButton: document.querySelector('#share-source'), status, fallbackContainer: document.querySelector('#source-text'), manifestUrl: './source-code.manifest.json', textUrl: './source-code.txt', filename: 'teleprinter-source-code.txt', onError: e => { status.textContent=e.me … [line shortened here: 412 characters; full line on GitHub]
</script></html>Codex Design Freeze Publish
A JavaScript module in the drivers folder of Teleprinter that prepares homepage (`prepareHomepage`) and verifies candidate tree (`verifyCandidateTree`) and external audit (`verifyExternalAudit`), using SHA-256.
storageteleprinter / drivers/codex/design-freeze-publish.mjs · lines 1–153 of 153 · Not reached from any entry point (candidate for review) · pattern requireThat (shared by 2 files)
- What it does
- It loads data. Defines 10 functions or classes, including stable, requireThat, escape, git, prepareHomepage. Uses libraries node:fs/promises, node:path, 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).
- Inputs & outputs
- In: command-line arguments.
- Downstream impact
- Used directly by 1 file: Codex Design Freeze Publish Test (teleprinter).
- What it achieves
- It prepares homepage (`prepareHomepage`), verifies candidate tree (`verifyCandidateTree`) and verifies external audit (`verifyExternalAudit`). Prepare or explicitly publish one accepted design freeze.
- Why it matters
- Checked by Codex Design Freeze Publish Test.
- Application
- teleprinter · drivers/codex · JavaScript module
- Uses
- Codex Design Freeze (script call), node:fs/promises, node:path, node:child_process, node:url
- Used by
- imported by Codex Design Freeze Publish Test (import)
- Produces
- prepareHomepage, snapshotMetrics, verifyCandidateTree, verifyExternalAudit, publishFreeze
- Defines here
- stable, requireThat, escape, git, prepareHomepage, snapshotMetrics, inventory, verifyCandidateTree, verifyExternalAudit, publishFreeze
- 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-publish.mjs:1-153 · blob fde7f4823f62a086f8615d76d392436d89227faf · 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
/** Prepare or explicitly publish one accepted design freeze. No unattended agent loop. */
import fs from 'node:fs/promises';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { digest, OFFLINE_ROOT } from './design-freeze.mjs';
const here = path.dirname(fileURLToPath(import.meta.url));
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 requireThat = (value,message) => { if (!value) throw new Error(message); };
const escape = value => String(value).replace(/[&<>"']/g, char => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[char]));
function git(worktree,args) {
const result = spawnSync('git',['-C',worktree,...args],{encoding:'utf8',maxBuffer:4000000});
requireThat(result.status === 0, `git ${args[0]} failed: ${result.stderr || result.error || result.stdout}`); return result.stdout.trim();
}
export function prepareHomepage(html, record) {
requireThat(record.status === 'DESIGN FREEZE' && /^[a-f0-9]{64}$/.test(record.proofSha256 || ''), 'An accepted freeze record is required');
const c = record.candidate;
requireThat(/^\d{12,14}$/.test(c?.generation || ''), 'Generation must be an immutable timestamp');
const url = new URL(c.url); requireThat(url.protocol === 'https:' && url.pathname.endsWith(`/testcode/${c.generation}/`) && !url.search && !url.hash, 'Candidate must have an immutable HTTPS testcode generation URL');
requireThat(record.counts?.visits === 50 && record.counts?.pdf === 25 && record.counts?.source === 25 && record.counts?.png === 25, 'Freeze counts are incomplete');
const marker = `<!-- DESIGN FREEZE ${c.generation} ${record.proofSha256} -->`;
if (html.includes(marker)) return {html,changed:false};
requireThat(!html.includes(`<!-- DESIGN FREEZE ${c.generation} `), 'This generation already has a different freeze proof');
const row = `${marker}\n<p><a href="${escape(c.url)}">DESIGN FREEZE � ${escape(c.generation)} UTC</a>: 50 installed Chrome visits; 25 PDF and 25 source downloads. Captured screen pixels match; headers and footers remain outside the image. Browser emulation; source capture limitations are recorded. <a href="./design-freeze/${c.generation}-${record.proofSha256}.json">Proof ${record.proofSha256}</a> … [line shortened here: 409 characters; full line on GitHub]
const end = '<!-- DESIGN FREEZE APPEND HERE -->';
if (html.includes(end)) {
requireThat(html.indexOf(end) === html.lastIndexOf(end), 'Ambiguous freeze append marker');
return {html:html.replace(end,row+end),changed:true};
}
requireThat((html.match(/<\/body>/g) || []).length === 1, 'Expected exactly one HTML body end');
const section = `<section id="design-freeze">\n<h2>Design Freeze versions</h2>\n${row}${end}\n</section>\n`;
return {html:html.replace('</body>',section+'</body>'),changed:true};
}
export function snapshotMetrics(html, names, sourceCommit) {
const next = 1 + names.reduce((max,name)=>Math.max(max,Number(name.match(/^homepage_v(\d+)\.html$/)?.[1] || 0)),0);
return {filename:`homepage_v${String(next).padStart(3,'0')}.html`,fileCountBefore:names.length,lineCount:html.split('\n').length-(html.endsWith('\n')?1:0),wordCount:html.trim().split(/\s+/).filter(Boolean).length,characterCount:[...html].length,bytes:Buffer.byteLength(html),sha256:digest(html),sourceCommit,intention:'Append an accepted immutable Design Freeze version while preserving every existi … [line shortened here: 432 characters; full line on GitHub]
}
async function inventory(directory) {
const files=[];
for(const entry of await fs.readdir(directory,{withFileTypes:true})) {
if(entry.name === '.git') continue;
const filename=path.join(directory,entry.name);
requireThat(!entry.isSymbolicLink(),`Candidate symlink rejected: ${filename}`);
if(entry.isDirectory()) files.push(...await inventory(filename)); else if(entry.isFile()) files.push(filename);
}
return files;
}
export async function verifyCandidateTree(pins, worktree, generation) {
const directory=path.resolve(worktree,'testcode',generation);
requireThat(await fs.realpath(directory) === directory, 'Candidate directory may not be a symlink');
const manifest=JSON.parse(await fs.readFile(pins.buildManifestPath,'utf8'));
const expected=[];
for(const entry of manifest.files || []) {
const relative=path.relative(path.resolve(pins.buildRoot),path.resolve(entry.path));
requireThat(relative && !relative.startsWith('..') && !path.isAbsolute(relative),'Build entry outside candidate root');
const filename=path.resolve(directory,relative);
requireThat(digest(await fs.readFile(filename)) === entry.sha256,`Candidate bytes differ: ${relative}`);
expected.push(filename);
}
requireThat(expected.length && stable(expected.sort()) === stable((await inventory(directory)).sort()),'Candidate tree differs from build inventory');
return directory;
}
/** Re-read the exact audited registries and original files immediately before staging publication. */
export async function verifyExternalAudit(record, pins) {
requireThat(Array.isArray(record.externalReviews) && record.externalReviews.length > 0, 'Accepted record has no external review audit');
for (const audit of record.externalReviews) {
const pin=pins.inputs?.find(input=>input.path===audit.path);
const bytes=await fs.readFile(audit.path);
requireThat(pin && digest(bytes) === pin.sha256 && digest(bytes) === audit.sha256, `External registry changed before publication: ${audit.path}`);
const review=JSON.parse(bytes);
const artifacts=(review.runs || []).flatMap(run=>(run.artifacts || []).map(item=>({...item,path:path.resolve(run.directory,item.filename)})));
for (const resolution of audit.resolutionProofs || []) {
const proofBytes=await fs.readFile(resolution.path);
requireThat(digest(proofBytes) === resolution.sha256,'External resolution proof changed before publication');
artifacts.push(...JSON.parse(proofBytes).evidence);
}
const offline=await fs.realpath(OFFLINE_ROOT);
for (const artifact of artifacts) {
const real=await fs.realpath(artifact.path), relative=path.relative(offline,real);
requireThat(relative && !relative.startsWith('..') && !path.isAbsolute(relative),'External artifact escapes offline root');
const data=await fs.readFile(artifact.path);
requireThat(data.length === artifact.bytes && digest(data) === artifact.sha256,`External artifact changed before publication: ${artifact.path}`);
}
}
}
export async function publishFreeze({recordPath,reportPath,pinsPath,worktree,publish=false}) {
worktree=await fs.realpath(path.resolve(worktree));
const record=JSON.parse(await fs.readFile(recordPath,'utf8'));
const report=JSON.parse(await fs.readFile(reportPath,'utf8'));
const pins=JSON.parse(await fs.readFile(pinsPath,'utf8'));
requireThat(stable(record.candidate) === stable(pins.candidate) && stable(report.candidate) === stable(pins.candidate),'Candidate identities differ');
requireThat(record.proofSha256 === digest(stable({report,evidence:record.evidence,inputs:pins.inputs,heads:pins.heads})),'Freeze report or pinned inputs differ from accepted proof');
const gate=spawnSync(process.execPath,[path.join(here,'design-freeze.mjs'),path.resolve(reportPath),path.resolve(pinsPath)],{encoding:'utf8',maxBuffer:4000000,timeout:3600000});
requireThat(gate.status === 0,`Freeze recheck rejected: ${gate.stderr || gate.error || gate.stdout}`);
const accepted=JSON.parse(await fs.readFile(path.join(OFFLINE_ROOT,'design-freeze',record.proofSha256+'.json'),'utf8'));
requireThat(stable(record) === stable(accepted),'Supplied record differs from gate-produced record');
await verifyCandidateTree(pins,worktree,record.candidate.generation);
const homepage=path.join(worktree,'index.html');
const original=await fs.readFile(homepage,'utf8');
const prepared=prepareHomepage(original,record);
if(!prepared.changed) return {status:'ALREADY PREPARED',generation:record.candidate.generation,proofSha256:record.proofSha256};
const beforeHead=git(worktree,['rev-parse','HEAD']);
requireThat(!git(worktree,['diff','--cached','--name-only']),'Unrelated staged changes exist');
const targeted=['index.html','homepage_versions/README.md'];
requireThat(!git(worktree,['status','--porcelain','--',...targeted]),'Homepage or snapshot README has uncommitted changes');
if(publish) {
requireThat(!git(worktree,['status','--porcelain']),'Publish requires a clean worktree');
requireThat(git(worktree,['branch','--show-current']),'Detached HEAD cannot publish');
const candidateFiles = await inventory(path.join(worktree,'testcode',record.candidate.generation));
for (const filename of candidateFiles) git(worktree,['ls-files','--error-unmatch','--',path.relative(worktree,filename)]);
git(worktree,['fetch','origin','main']);
const remote=git(worktree,['rev-parse','refs/remotes/origin/main']);
git(worktree,['merge-base','--is-ancestor',remote,'HEAD']);
requireThat(remote === beforeHead,'Publish requires HEAD equal fetched origin/main; root must review any existing outgoing commits');
}
const snapshotDir=path.join(worktree,'homepage_versions');
const entries=await fs.readdir(snapshotDir,{withFileTypes:true});
const names=entries.filter(entry=>entry.isFile()).map(entry=>entry.name);
const metrics=snapshotMetrics(original,names,beforeHead);
const readmePath=path.join(snapshotDir,'README.md');
const oldReadme=await fs.readFile(readmePath,'utf8');
requireThat(oldReadme.includes('Before creating a new homepage version'),'Homepage snapshot rules missing');
const annotation=`\n\n## ${metrics.filename} � Design Freeze\n\nSource commit: ${beforeHead}\nFolder file count before: ${metrics.fileCountBefore}\nHTML snapshot: ${metrics.filename}\nLines: ${metrics.lineCount}; words: ${metrics.wordCount}; characters: ${metrics.characterCount}; bytes: ${metrics.bytes}.\nSHA-256: ${metrics.sha256}\nIntention: ${metrics.intention}\nGeneration: ${record.candidate. … [line shortened here: 446 characters; full line on GitHub]
const finding={status:record.status,candidate:record.candidate,proofSha256:record.proofSha256,counts:record.counts,scope:record.scope,homepageRestorePoint:metrics};
const relativeFinding=`design-freeze/${record.candidate.generation}-${record.proofSha256}.json`;
const relativeSnapshot=`homepage_versions/${metrics.filename}`;
const paths=['index.html','homepage_versions/README.md',relativeSnapshot,relativeFinding];
// Record the restore-point metrics and exact old HTML before touching the homepage.
await fs.writeFile(path.join(snapshotDir,metrics.filename),original,{flag:'wx'});
await fs.writeFile(readmePath,oldReadme+annotation);
await fs.mkdir(path.join(worktree,'design-freeze'),{recursive:true});
await fs.writeFile(path.join(worktree,relativeFinding),JSON.stringify(finding,null,2)+'\n',{flag:'wx'});
requireThat(await fs.readFile(homepage,'utf8') === original,'Homepage changed while preparation ran');
await fs.writeFile(homepage,prepared.html);
if(!publish) return {status:'PREPARED',paths,metrics,generation:record.candidate.generation,proofSha256:record.proofSha256};
requireThat(git(worktree,['rev-parse','HEAD']) === beforeHead,'HEAD changed while preparing');
requireThat(!git(worktree,['diff','--cached','--name-only']),'Index changed while preparing');
await verifyCandidateTree(pins,worktree,record.candidate.generation);
await verifyExternalAudit(record,pins);
git(worktree,['add','--',...paths]);
requireThat(stable(git(worktree,['diff','--cached','--name-only']).split('\n').sort()) === stable([...paths].sort()),'Staged paths differ from intended publication');
git(worktree,['commit','-m',`Append Design Freeze ${record.candidate.generation} (${record.proofSha256.slice(0,12)})`]);
const commit=git(worktree,['rev-parse','HEAD']);
git(worktree,['push','origin','HEAD:refs/heads/main']);
return {status:'PUBLISHED',commit,paths,generation:record.candidate.generation,proofSha256:record.proofSha256};
}
if(process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
const [recordPath,reportPath,pinsPath,worktree,...options]=process.argv.slice(2);
try {
requireThat(recordPath && reportPath && pinsPath && worktree && options.every(option=>option==='--publish'),'Usage: node design-freeze-publish.mjs RECORD REPORT PINS WEB_WORKTREE [--publish]');
console.log(JSON.stringify(await publishFreeze({recordPath,reportPath,pinsPath,worktree,publish:options.includes('--publish')}),null,2));
} catch(error) { console.error(JSON.stringify({status:'REJECTED',error:String(error)}));process.exitCode=1; }
}Codex Design Freeze Publish Test
A test in the drivers folder of Teleprinter that checks Codex Design Freeze Publish and Codex Design Freeze, using SHA-256.
testteleprinter / drivers/codex/design-freeze-publish.test.mjs · lines 1–20 of 20 · Not reached from any entry point (candidate for review) · pattern record (shared by 46 files)
- What it does
- It tests its inputs. Defines record. Uses libraries node:test, node:assert/strict, node:fs/promises, node:path, node:os. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage agent_infra (path word 'codex'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- Out: JSON file review.json.
- What it achieves
- Defines `record`.
- Why it matters
- Guards the behaviour of Codex Design Freeze Publish and Codex Design Freeze.
- Application
- teleprinter · drivers/codex · test
- Uses
- Codex Design Freeze Publish (import), Codex Design Freeze (import), node:test, node:assert/strict, node:fs/promises, node:path, node:os
- Used by
- none found
- Produces
- record
- Defines here
- record
- 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-publish.test.mjs:1-20 · blob 3923dac4e8e1b583f92b87585d37ec84d760a784 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import { prepareHomepage, snapshotMetrics, verifyCandidateTree, verifyExternalAudit } from './design-freeze-publish.mjs';
import { digest } from './design-freeze.mjs';
const record = () => ({status:'DESIGN FREEZE',candidate:{generation:'202609051800',url:'https://example.org/testcode/202609051800/'},proofSha256:'a'.repeat(64),counts:{visits:50,pdf:25,source:25,png:25}});
const html='<!doctype html><html><body>\n<a href="./old/">Old working version</a>\n<script>const original = "untouched";</script>\n</body></html>\n';
test('append preserves every pre-existing byte around inserted section',()=>{const result=prepareHomepage(html,record());assert.equal(result.changed,true);assert.equal(result.html.slice(0,html.indexOf('</body>')),html.slice(0,html.indexOf('</body>')));assert.ok(result.html.endsWith('</body></html>\n'));assert.match(result.html,/50 installed Chrome visits; 25 PDF and 25 source/);});
test('identical generation/proof is idempotent',()=>{const first=prepareHomepage(html,record());assert.deepEqual(prepareHomepage(first.html,record()),{html:first.html,changed:false});});
test('successor appends after predecessor without modifying its row',()=>{const first=prepareHomepage(html,record()).html;const second=record();second.candidate={generation:'202609051900',url:'https://example.org/testcode/202609051900/'};second.proofSha256='b'.repeat(64);const next=prepareHomepage(first,second).html;const marker='<!-- DESIGN FREEZE APPEND HERE -->';assert.equal(next.slice(0,first. … [line shortened here: 458 characters; full line on GitHub]
test('same generation with different proof is rejected',()=>{const first=prepareHomepage(html,record()).html;const next=record();next.proofSha256='b'.repeat(64);assert.throws(()=>prepareHomepage(first,next),/different freeze proof/);});
test('partial evidence and unsafe candidate URL are rejected',()=>{const r=record();r.counts.pdf=24;assert.throws(()=>prepareHomepage(html,r),/incomplete/);r.counts.pdf=25;r.candidate.url='javascript:alert(1)';assert.throws(()=>prepareHomepage(html,r),/immutable HTTPS/);});
test('missing or ambiguous placement is rejected',()=>{assert.throws(()=>prepareHomepage('<html/>',record()),/body end/);assert.throws(()=>prepareHomepage(html+'<!-- DESIGN FREEZE APPEND HERE --><!-- DESIGN FREEZE APPEND HERE -->',record()),/Ambiguous/);});
test('restore-point metrics and monotonically increasing name are computed before edit',()=>{const m=snapshotMetrics('one two\nthree\n',['README.md','homepage_v009.html','homepage_v011.html'],'head');assert.equal(m.filename,'homepage_v012.html');assert.equal(m.fileCountBefore,3);assert.equal(m.lineCount,2);assert.equal(m.wordCount,3);assert.equal(m.characterCount,14);assert.equal(m.sha256,digest(' … [line shortened here: 423 characters; full line on GitHub]
test('candidate copy must exactly match pinned build inventory and bytes',async t=>{const root=await fs.mkdtemp(path.join(os.tmpdir(),'freeze-publisher-'));t.after(()=>{assert.equal(path.dirname(path.resolve(root)),path.resolve(os.tmpdir()));assert.match(path.basename(root),/^freeze-publisher-/);return fs.rm(root,{recursive:true,force:true});});const build=path.join(root,'build');const web=path.jo … [line shortened here: 1,358 characters; full line on GitHub]
test('publication requires the exact accepted registry bytes again',async t=>{const root=await fs.mkdtemp(path.join(os.tmpdir(),'freeze-publisher-'));t.after(()=>{assert.equal(path.dirname(path.resolve(root)),path.resolve(os.tmpdir()));assert.match(path.basename(root),/^freeze-publisher-/);return fs.rm(root,{recursive:true,force:true});});const filename=path.join(root,'review.json');const bytes=Bu … [line shortened here: 783 characters; full line on GitHub]
test('publication cannot use an old record without its external review audit',async()=>{await assert.rejects(verifyExternalAudit({},{}),/no external review audit/);});