GLOBALGRID2050 / EXPLORE CODE

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

Codex Fifty Prints and 5 more files

A JavaScript module in the drivers folder of Teleprinter that draws fifty prints results, campaign results and the Renewable Energy Planning Database (REPD) register, using SHA-256.

556 lines of JavaScript and Python from teleprinter, in 6 files. Topic: AI agents and coordination. Section 1656 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Codex Fifty Prints render · teleprinter / drivers/codex/fifty-prints.mjs lines 1–344
  2. Codex File Print Compatibility storage · teleprinter / drivers/codex/file-print-compatibility.mjs lines 1–116
  3. Codex Inspect App PDF ingest · teleprinter / drivers/codex/inspect-app-pdf.py lines 1–23
  4. Codex Inspect PDF ingest · teleprinter / drivers/codex/inspect-pdf.py lines 1–50
  5. Codex Layer Quick Controls Test test · teleprinter / drivers/codex/layer-quick-controls.test.mjs lines 1–15
  6. Codex Layout Command Test test · teleprinter / drivers/codex/layout-command.test.mjs lines 1–8

Codex Fifty Prints

A JavaScript module in the drivers folder of Teleprinter that draws fifty prints results, campaign results and the Renewable Energy Planning Database (REPD) register, using SHA-256.

renderteleprinter / drivers/codex/fifty-prints.mjs · lines 1–344 of 344 · Not reached from any entry point (candidate for review) · pattern progress (shared by 7 files)

What it does
It draws fifty prints results, campaign results and the REPD register. Defines 9 functions or classes, including readCandidateJSON, sha256, saveReceipt, readAtlasState, rect. Uses libraries node:fs/promises, node:path, node:url, node:crypto, node:child_process. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'codex'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). Domain terms in the code: the REPD register.
Inputs & outputs
In: JSON file release.json; JSON file fifty-prints-results.json; JSON file -manifest.json; command-line arguments. Out: JSON file campaign-results.json.
What it achieves
It reads candidate JSON (`readCandidateJSON`), saves receipt (`saveReceipt`) and reads atlas state (`readAtlasState`). 25 scenarios, two fresh installed-Chrome visits each; all binary evidence stays offline. It reads `release.json`. It responds to teleprint events.
Why it matters
No other file in the estate was found to import it.
Application
teleprinter · drivers/codex · JavaScript module
Uses
Codex Driver (script call), node:fs/promises, node:path, node:url, node:crypto, node:child_process, node:assert/strict
Used by
none found
Produces
readCandidateJSON, sha256, saveReceipt, readAtlasState, rect, onscreen, assertAtlasState, prepare, progress
Defines here
readCandidateJSON, sha256, saveReceipt, readAtlasState, rect, onscreen, assertAtlasState, prepare, progress
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/fifty-prints.mjs:1-344 · blob 2d4e8a27ffaa325edc72e274280ce736531eebe1 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, process · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
/** 25 scenarios, two fresh installed-Chrome visits each; all binary evidence stays offline. */
import fs from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { createHash } from 'node:crypto';
import { spawnSync } from 'node:child_process';
import assert from 'node:assert/strict';
import { attachScreenCapture, clickAndReadDownload } from './driver.mjs';

const appRender = process.argv.includes('--app-render');
const here = path.dirname(fileURLToPath(import.meta.url));
const base = process.argv[2];
assert.ok(base, 'Usage: node fifty-prints.mjs BASE_URL [OFFLINE_ROOT] [--limit=25]');
const root = path.resolve(process.argv[3]?.startsWith('--') || !process.argv[3]
  ? 'C:/Users/vikra/OneDrive/Desktop/offline-screenshots' : process.argv[3]);
assert.ok(!root.toLowerCase().startsWith(path.resolve(here, '../..').toLowerCase()), 'Print artifacts must stay outside Git.');
const limit = Number(process.argv.find(arg => arg.startsWith('--limit='))?.split('=')[1] || 25);
assert.ok(Number.isInteger(limit) && limit >= 1 && limit <= 25);
const offset = Number(process.argv.find(arg => arg.startsWith('--offset='))?.split('=')[1] || 0);
assert.ok(Number.isInteger(offset) && offset >= 0 && offset + limit <= 25);
const buildSha256 = process.argv.find(arg => arg.startsWith('--build-sha256='))?.split('=')[1];
assert.match(buildSha256 || '', /^[a-f0-9]{64}$/i, 'Supply --build-sha256=HASH for the frozen candidate build.');
async function readCandidateJSON(relative) {
  const response = await fetch(new URL(relative, base), { signal: AbortSignal.timeout(30000), cache: 'no-store' });
  assert.ok(response.ok, `${relative}: HTTP ${response.status}`);
  return response.json();
}
const release = await readCandidateJSON('release.json');
const pins = Object.fromEntries(await Promise.all(['atlas', 'pipeline', 'landing'].map(async app => [app, await readCandidateJSON(`teleprinter/${app}-source-pin.json`)])));
const sourceCommit = pins.atlas.commit;
assert.ok(Object.values(pins).every(pin => pin.commit === sourceCommit && pin.generation === release.generation), 'Source pins do not identify one frozen generation/commit.');
const candidate = { url: base, generation: release.generation, sourceCommit, engineCommit: release.teleprinter.commit, buildSha256 };
const output = path.join(root, `teleprinter-${new Date().toISOString().replace(/[:.]/g, '-')}-${process.pid}`);
await fs.mkdir(output, { recursive: true });
const { chromium } = await import(pathToFileURL(process.env.PLAYWRIGHT_MODULE || 'C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright/index.mjs').href);
const sha256 = bytes => createHash('sha256').update(bytes).digest('hex');
const geometries = [
  { name: 'desktop-wide', width: 1440, height: 900, dpr: 1 },
  { name: 'desktop-portrait', width: 900, height: 1200, dpr: 1 },
  { name: 'iPad-emulation', width: 1024, height: 768, dpr: 2 },
  { name: 'iPhone-emulation', width: 393, height: 852, dpr: 2 },
  { name: 'mobile-landscape', width: 852, height: 393, dpr: 2 }
];
const projects = [
  { ref: '2484', query: 'repd_ref=2484&technology=wind_offshore&latitude=52.6199968&longitude=2.5499934' },
  { ref: '18790', query: 'repd_ref=18790&technology=bess' },
  { ref: '11613', query: 'repd_ref=11613&technology=wind_offshore' }
];
const pipelineSearches = ['Berwick', 'Ossian', 'Hornsea', 'Dogger', 'Norfolk', 'RWE', 'SSE', 'Orsted'];
const layerSets = [['400', '275'], ['220', '132', '66'], ['400', '220', '132'], ['275', '66'], ['400', '132', '66']];
const scenarios = Array.from({ length: 25 }, (_, i) => {
  const kind = i < 15 ? 'atlas' : i < 23 ? 'pipeline' : 'landing';
  const project = projects[i % projects.length];
  return { id: String(i + 1).padStart(2, '0'), kind, geometry: geometries[i % 5],
    route: kind === 'atlas' ? `atlas/?${project.query}` : kind === 'pipeline' ? 'pipeline/' : '',
    project: kind === 'atlas' ? project.ref : null, layers: kind === 'atlas' ? layerSets[i % 5] : [],
    search: kind === 'pipeline' ? pipelineSearches[i - 15] : null,
    pdfRoute: 'File > Print PDF' };
});
const receipt = { createdAt: new Date().toISOString(), base, candidate, output, browser: 'installed Chrome', printRoute:appRender?'app-render, no host capture':'host screenshot', physicalDevices: false,
  requestedScenarios: limit, expectedVisits: limit * 2, expectedDownloads: limit * 2, scenarios: [] };
const receiptPath = path.join(here, 'fifty-prints-results.json');
async function saveReceipt() { const text = JSON.stringify(receipt, null, 2) + '\n'; await fs.writeFile(receiptPath, text); await fs.writeFile(path.join(output, 'campaign-results.json'), text); }

async function readAtlasState(page) {
  return page.evaluate(() => {
    const rect = node => { const r = node?.getBoundingClientRect(); return r ? { x: r.x, y: r.y, width: r.width, height: r.height } : null; };
    const onscreen = r => !!r && r.width > 0 && r.height > 0 && r.x < innerWidth && r.y < innerHeight && r.x + r.width > 0 && r.y + r.height > 0;
    const forms = [...document.querySelectorAll('input,textarea,select')];
    const controls = [...document.querySelectorAll('input[data-gridatlas-layer-proxy],input[data-layer-id]')]
      .filter(input => { const r = input.getBoundingClientRect(); return r.width > 0 && r.height > 0 && getComputedStyle(input).visibility !== 'hidden'; })
      .map(input => { const label = input.closest('label'); const bounds = rect(label); return {
        index: forms.indexOf(input), key: input.dataset.gridatlasLayerProxy || `engine:${input.dataset.layerId}`,
        checked: input.checked, label: (label?.textContent || input.getAttribute('aria-label') || '').trim(),
        bounds, intersectsViewport: onscreen(bounds)
      }; });
    const panel = ['scada-ui-container', 'fs-curtain-keys', 'gridatlas-dash'].map(id => document.getElementById(id)).find(node => onscreen(rect(node)));
    const panelBounds = rect(panel);
    const map = window.__GRIDATLAS_V9_MAP__;
    return { url: location.href, visibleText: document.body.innerText, controls,
      selectedLayerKeys: [...new Set(controls.filter(input => input.checked).map(input => input.key))].sort(),
      panel: { present: !!panel, bounds: panelBounds, intersectsViewport: onscreen(panelBounds) },
      mapLayers: (map?.getStyle?.()?.layers || []).map(layer => ({ id: layer.id, visibility: layer.layout?.visibility || 'visible' })) };
  });
}
function assertAtlasState(snapshot, scenario, expectedKeys) {
  assert.match(snapshot.visibleText, new RegExp(`TEST CODE repd-${scenario.project} \\| ENGINE COMPLETED`), 'Captured project engine status differs from the requested project.');
  assert.match(snapshot.visibleText, new RegExp(`REPD\\s+${scenario.project}\\b`), 'Captured project identity missing.');
  assert.deepEqual(snapshot.selectedLayerKeys, [...new Set(expectedKeys)].sort(), 'Layer selection changed before capture.');
  const selected = snapshot.controls.filter(input => input.checked);
  assert.ok(selected.length && selected.every(input => input.label), 'Selected layer legend labels must be nonempty.');
  assert.ok(snapshot.panel.intersectsViewport, 'Open Layers panel does not intersect the captured viewport.');
  assert.ok(selected.some(input => input.intersectsViewport), 'No selected layer legend label intersects the captured viewport.');
  for (const layer of scenario.layers) {
    const rendered = snapshot.mapLayers.find(item => item.id === `l-${layer}`);
    assert.ok(rendered, `Expected map layer l-${layer} is unavailable.`);
    assert.equal(rendered.visibility !== 'none', snapshot.selectedLayerKeys.includes(`engine:${layer}`), `Map layer ${layer} does not match its checkbox.`);
  }
}

async function prepare(page, scenario, progress) {
  progress('navigate');
  await page.goto(new URL(scenario.route, base).href, { waitUntil: 'domcontentloaded', timeout: 60000 });
  progress('wait for app print menus');
  await page.locator('#codex-teleprinter').waitFor({state:'attached', timeout:90000});
  const state = { url: page.url(), project: scenario.project, layers: [] };
  if (scenario.kind === 'atlas') {
    progress('wait for visible engine completion');
    const badge = page.getByText(new RegExp(`TEST CODE repd-${scenario.project} \\| ENGINE COMPLETED`)).first();
    await badge.waitFor({ state: 'visible', timeout: 90000 });
    state.engineStatus = await badge.innerText();
    const body = await page.locator('body').innerText();
    assert.match(body, new RegExp(`REPD\\s+${scenario.project}\\b`), 'Project identity missing from visible body.');
    assert.match(body, /Nearest|substation|connection/i, 'Project calculation missing from visible body.');
    state.projectBody = body;
    progress('wait for File menu and layers panel');
    await page.locator('.gm-title').filter({ hasText: /^File$/i }).waitFor({ state: 'visible', timeout: 60000 });
    const toggle = page.locator('#gridatlas-dash-toggle');
    if (!/HIDE LAYERS/i.test(await toggle.innerText())) await toggle.click();
    for (const layer of scenario.layers) {
      progress(`toggle layer ${layer}`);
      const input = page.locator(`input[data-gridatlas-layer-proxy="engine:${layer}"]:visible, input[data-layer-id="${layer}"]:visible`).first();
      await input.waitFor({ state: 'visible', timeout: 60000 });
      const before = await input.isChecked();
      await input.locator('xpath=ancestor::label[1]').click();
      assert.equal(await input.isChecked(), !before, `Layer ${layer} failed to toggle.`);
    }
    state.layers = await page.locator('input[data-gridatlas-layer-proxy]:visible, input[data-layer-id]:visible').evaluateAll(inputs =>
      inputs.filter(input => input.checked).map(input => ({ key: input.dataset.gridatlasLayerProxy || `engine:${input.dataset.layerId}`,
        label: input.getAttribute('aria-label') || input.parentElement.textContent.trim() })).sort((a, b) => a.key.localeCompare(b.key)));
    state.selectedLayerKeys = state.layers.map(layer => layer.key);
  } else if (scenario.kind === 'pipeline') {
    progress(`wait for Pipeline rows, search ${scenario.search}`);
    await page.waitForFunction(() => document.querySelector('#tbody tr')?.children.length > 1, null, {timeout:90000});
    await page.locator('#tbody tr td').first().waitFor({ state: 'visible', timeout: 30000 });
    await page.locator('#search').fill(scenario.search);
    await page.waitForFunction(query => {
      const row = document.querySelector('#tbody tr');
      return row?.children.length > 1 && row.innerText.toLowerCase().includes(query.toLowerCase());
    }, scenario.search, { timeout: 30000 });
    state.search = await page.locator('#search').inputValue();
    assert.equal(state.search, scenario.search);
    state.firstRow = await page.locator('#tbody tr').first().innerText();
    state.visibleResultCount = await page.locator('#tbody tr').count();
    assert.ok(state.visibleResultCount > 0, 'Pipeline search returned no visible project rows.');
    await page.waitForFunction(query => new URL(location.href).searchParams.get('q') === query, scenario.search, {timeout:30000});
  } else {
    state.bodyExcerpt = (await page.locator('body').innerText()).slice(0, 3000);
    assert.ok(state.bodyExcerpt.trim().length > 50, 'Landing body is empty.');
  }
  state.url = page.url();
  return state;
}

for (const scenario of scenarios.slice(offset, offset + limit)) {
  const result = { ...scenario, visits: [], pairStateMatches: false };
  receipt.scenarios.push(result);
  for (const mode of ['pdf', 'source']) {
    let browser, context, page, captured, captureStatePromise;
    const visit = { visitId: `${path.basename(output)}-${scenario.id}-${mode}`, browser: 'installed Chrome', candidate,
      mode, startedAt: new Date().toISOString(), ok: false, console: [], networkFailures: [] };
    result.visits.push(visit);
    let currentStep = 'launch Chrome';
    const progress = step => { currentStep = step; console.log(`STEP ${scenario.id} ${mode}: ${step}`); };
    const heartbeat = setInterval(() => console.log(`WAIT ${scenario.id} ${mode}: ${currentStep}`), 30000);
    try {
      progress('launch Chrome');
      browser = await chromium.launch({ channel: 'chrome', headless: true });
      const { width, height, dpr } = scenario.geometry;
      context = await browser.newContext({ viewport: { width, height }, deviceScaleFactor: dpr, acceptDownloads: true });
      page = await context.newPage();
      page.on('console', message => { if (['error', 'warning'].includes(message.type()) && visit.console.length < 150) visit.console.push({ type: message.type(), text: message.text() }); });
      page.on('pageerror', error => visit.console.push({ type: 'pageerror', text: String(error) }));
      page.on('requestfailed', request => { if (visit.networkFailures.length < 150) visit.networkFailures.push({ url: request.url(), error: request.failure()?.errorText }); });
      if (!appRender) await attachScreenCapture(page, { onCapture: png => {
        captured = png;
        // driver.mjs does not await onCapture: observe rejection immediately, await below.
        if (scenario.kind === 'atlas') captureStatePromise = readAtlasState(page).then(value => ({ value }), error => ({ error }));
      } });
      if(appRender) await page.addInitScript(()=>{window.__forbiddenPrintCalls=0;const forbid=()=>{window.__forbiddenPrintCalls++;throw Error('Forbidden screen/browser capture');};if(navigator.mediaDevices)navigator.mediaDevices.getDisplayMedia=forbid;window.print=forbid;window.__codexTeleprinterCapture=forbid;});
      visit.state = await prepare(page, scenario, progress);
      if(appRender && mode==='pdf' && scenario.kind==='pipeline') {
        await page.evaluate(()=>document.fonts.ready);
        let previous='', stableSince=0, settled=false;
        const started=Date.now();
        while(Date.now()-started<15000) {
          const snapshot=await page.evaluate(()=>JSON.stringify({
            canvases:[...document.querySelectorAll('canvas')].map(c=>c.toDataURL()),
            scroll:[...document.querySelectorAll('*')].filter(e=>e.scrollTop||e.scrollLeft).map(e=>[e.id,e.scrollTop,e.scrollLeft])
          }));
          if(snapshot!==previous){previous=snapshot;stableSince=Date.now();}
          else if(Date.now()-stableSince>=600){settled=true;break;}
          await page.waitForTimeout(150);
        }
        assert.ok(settled,'Pipeline chart/scroll state did not settle before the visual comparison');
        visit.visualReadiness={method:'unchanged canvas bytes and scroll positions',stableMs:600};
      }
      if(appRender)await page.evaluate(()=>document.querySelector('#codex-teleprinter').addEventListener('teleprint',e=>window.__appPrintReceipt=e.detail));
      let downloaded;
      if (mode === 'pdf') {
        progress(`download PDF via ${scenario.pdfRoute}`);
        if (scenario.kind === 'atlas') {
          await page.locator('.gm-title').filter({ hasText: /^File$/i }).click();
          downloaded = await clickAndReadDownload(page, page.locator('button[data-gm-export]').filter({ hasText: /Print/i }).first(), { timeout: 60000 });
        } else {
          await page.locator('#codex-teleprinter #file-menu > summary').click();
          downloaded = await clickAndReadDownload(page, page.locator('#codex-teleprinter [data-codex-print-command="pdf"]'), { timeout:60000 });
        }
        assert.ok(downloaded.ok, downloaded.error);
        visit.bytes = downloaded.bytes.length;
        visit.sha256 = sha256(downloaded.bytes);
        visit.suggestedFilename = downloaded.filename;
        if(appRender){
          visit.appReceipt=await page.evaluate(()=>window.__appPrintReceipt);
          assert.equal(visit.appReceipt.method,'app-render');
          assert.equal(await page.evaluate(()=>window.__forbiddenPrintCalls),0);
          captured=await page.screenshot({type:'png',scale:'device'});
          if(scenario.kind==='atlas')captureStatePromise=readAtlasState(page).then(value=>({value}));
        }
        assert.ok(captured, 'Missing independent viewport comparison.');
        if (scenario.kind === 'atlas') {
          assert.ok(captureStatePromise, 'Capture-time layer snapshot was not scheduled.');
          const snapshot = await captureStatePromise;
          if (snapshot.error) throw snapshot.error;
          visit.captureState = snapshot.value;
          assertAtlasState(visit.captureState, scenario, visit.state.selectedLayerKeys);
        }
        visit.path = path.join(output, `${scenario.id}-${scenario.kind}-${scenario.geometry.name}.pdf`);
        await fs.writeFile(visit.path, downloaded.bytes, { flag: 'wx' });
        visit.pngPath = visit.path.replace(/\.pdf$/, '.png');
        visit.pngSha256 = sha256(captured);
        await fs.writeFile(visit.pngPath, captured, { flag: 'wx' });
        progress('inspect embedded and rendered PDF pixels');
        const inspected = spawnSync('python', [path.join(here, appRender ? 'inspect-app-pdf.py' : 'inspect-pdf.py')], {
          input: JSON.stringify({ pdf: downloaded.bytes.toString('base64'), png: captured.toString('base64') }), encoding: 'utf8', maxBuffer: 2000000, timeout: 60000
        });
        assert.equal(inspected.status, 0, inspected.stderr || String(inspected.error));
        visit.inspection = JSON.parse(inspected.stdout);
      } else {
        progress('prepare source download through the app File menu');
        if (scenario.kind === 'atlas') {
          progress('download source through File > Print source code');
          await page.locator('.gm-title').filter({hasText:/^File$/i}).click();
          visit.sourceCommandState = await readAtlasState(page);
          assertAtlasState(visit.sourceCommandState, scenario, visit.state.selectedLayerKeys);
          downloaded = await clickAndReadDownload(page, page.locator('button[data-codex-print-source]'), { timeout: 120000 });
        } else {
          await page.locator('#codex-teleprinter #file-menu > summary').click();
          downloaded = await clickAndReadDownload(page, page.locator('#codex-teleprinter [data-codex-print-command="source"]'), { timeout:120000 });
        }
        assert.ok(downloaded.ok, downloaded.error);
        visit.bytes = downloaded.bytes.length;
        visit.sha256 = sha256(downloaded.bytes);
        visit.suggestedFilename = downloaded.filename;
        const source = downloaded.bytes.toString('utf8');
        visit.path = path.join(output, `${scenario.id}-${scenario.kind}-${scenario.geometry.name}-source.txt`);
        await fs.writeFile(visit.path, downloaded.bytes, { flag: 'wx' });
        assert.match(source, /PRINT SOURCE CODE/);
        assert.ok(source.length > 10000, 'Source print coverage unexpectedly small.');
        const framed = source.match(/===== BEGIN DIAGNOSTIC MANIFEST =====\r?\n([\s\S]*?)\r?\n===== END DIAGNOSTIC MANIFEST =====/);
        assert.ok(framed, 'Source print has no runtime diagnostic manifest.');
        const manifest = JSON.parse(framed[1]);
        progress(`verify runtime manifest (${manifest.counts?.resources ?? '?'} resources)`);
        visit.runtimeManifestPath = visit.path.replace(/\.txt$/, '-manifest.json');
        await fs.writeFile(visit.runtimeManifestPath, JSON.stringify(manifest, null, 2) + '\n', { flag: 'wx' });
        visit.runtimeManifest = { format: manifest.format, complete: manifest.complete,
          observedResourcesComplete: manifest.observedResourcesComplete, counts: manifest.counts,
          failures: manifest.failures, discoveryWarnings: manifest.discoveryWarnings,
          state: { url: manifest.state?.url, viewport: manifest.state?.viewport },
          baseManifest: { commit: manifest.baseManifest?.commit, sha256: manifest.baseManifest?.sha256 } };
        assert.equal(manifest.state?.url, visit.state.url, 'Source capture URL differs from the actual app view.');
        if (scenario.kind === 'atlas') {
          const snapshot = visit.sourceCommandState;
          assert.match(manifest.state.visibleText, new RegExp(`TEST CODE repd-${scenario.project} \\| ENGINE COMPLETED`));
          assert.match(manifest.state.visibleText, new RegExp(`REPD\\s+${scenario.project}\\b`));
          for (const control of snapshot.controls) {
            const form = manifest.state.forms.find(form => form.root === 'document' && form.index === control.index);
            assert.ok(form && form.type === 'checkbox', `Source manifest missing layer form ${control.key}.`);
            assert.equal(form.checked, control.checked, `Source manifest layer ${control.key} differs from the printed view.`);
          }
          for (const layer of scenario.layers) {
            const mapLayer = manifest.state.map?.layers?.find(item => item.id === `l-${layer}`);
            assert.ok(mapLayer, `Source map is missing layer l-${layer}.`);
            assert.equal(mapLayer.layout?.visibility !== 'none', snapshot.selectedLayerKeys.includes(`engine:${layer}`));
          }
          for (const control of snapshot.controls.filter(input => input.checked && input.intersectsViewport)) {
            const legendName = control.label.replace(/\s*\[(?:OK|LOAD|WAIT|ERROR)\]/g, '').trim();
            assert.ok(manifest.state.visibleText.includes(legendName), `Source visible text is missing selected legend ${legendName}.`);
          }
          visit.sourceCapturedLayerKeys = [...new Set(snapshot.controls.filter(control => manifest.state.forms.find(form => form.root === 'document' && form.index === control.index)?.checked).map(control => control.key))].sort();
        }
        assert.equal(manifest.baseManifest?.commit, candidate.sourceCommit, 'Source capture commit differs from frozen candidate.');
        assert.equal(manifest.baseManifest?.sha256, pins[scenario.kind].sha256, 'Source capture bytes differ from the app source pin.');
        assert.equal(manifest.failures?.length, 0, 'Runtime source capture reports unavailable or failed resources; see saved manifest.');
      }
      visit.bytes = downloaded.bytes.length;
      visit.sha256 = sha256(downloaded.bytes);
      visit.suggestedFilename = downloaded.filename;
      visit.status = await page.locator('#codex-teleprinter #status').innerText().catch(() => '');
      visit.ok = true;
      console.log(`PASS ${scenario.id} ${mode} ${visit.bytes} bytes`);
    } catch (error) {
      visit.error = String(error);
      if (page) {
        const failure = { url: page.url(), body: await page.locator('body').innerText().catch(() => ''),
          dom: await page.content().catch(() => ''), console: visit.console, networkFailures: visit.networkFailures };
        const failureBytes = Buffer.from(JSON.stringify(failure, null, 2) + '\n');
        visit.failureEvidencePath = path.join(output, `${scenario.id}-${mode}-failure.json`);
        visit.failureEvidenceSha256 = sha256(failureBytes);
        await fs.writeFile(visit.failureEvidencePath, failureBytes, { flag: 'wx' });
        visit.status = await page.locator('#codex-teleprinter #status').innerText().catch(() => '');
      }
      console.log(`FAIL ${scenario.id} ${mode}: ${error.message}`);
    } finally {
      clearInterval(heartbeat);
      captured = undefined;
      await context?.close().catch(() => {});
      await browser?.close().catch(() => {});
      if (visit.failureEvidencePath) {
        visit.consoleCount = visit.console.length;
        visit.networkFailureCount = visit.networkFailures.length;
        delete visit.console;
        delete visit.networkFailures;
      }
      visit.closedAt = new Date().toISOString();
      visit.finishedAt = visit.closedAt;
      await saveReceipt();
    }
  }
  const [pdf, source] = result.visits;
  result.pairStateMatches = !!(pdf.state && source.state && pdf.state.url === source.state.url &&
    JSON.stringify(pdf.state.selectedLayerKeys || []) === JSON.stringify(source.state.selectedLayerKeys || []) &&
    pdf.state.project === source.state.project && pdf.state.search === source.state.search &&
    pdf.state.firstRow === source.state.firstRow && (scenario.kind !== 'atlas' ||
      JSON.stringify(pdf.captureState?.selectedLayerKeys) === JSON.stringify(source.sourceCapturedLayerKeys)));
  await saveReceipt();
}
receipt.finishedAt = new Date().toISOString();
receipt.actualVisits = receipt.scenarios.reduce((sum, scenario) => sum + scenario.visits.length, 0);
receipt.savedDownloads = receipt.scenarios.flatMap(scenario => scenario.visits).filter(visit => visit.path).length;
receipt.ok = receipt.scenarios.every(scenario => scenario.pairStateMatches && scenario.visits.every(visit => visit.ok));
await saveReceipt();
console.log(JSON.stringify({ ok: receipt.ok, visits: receipt.actualVisits, savedDownloads: receipt.savedDownloads, output, receiptPath }));
if (!receipt.ok) process.exitCode = 1;

Codex File Print Compatibility

A JavaScript module in the drivers folder of Teleprinter that reads print compatibility results, using SHA-256. It is built from the sha256 step (`sha256`) and the progress step (`progress`).

storageteleprinter / drivers/codex/file-print-compatibility.mjs · lines 1–116 of 116 · Not reached from any entry point (candidate for review) · pattern progress (shared by 7 files)

What it does
It loads print compatibility results. Defines sha256, progress. Uses libraries node:fs/promises, node:path, node:url, node:crypto, node:child_process. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'codex'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file file-print-compatibility-results.json; command-line arguments.
What it achieves
Six fresh non-Chrome visits, actual separate File print commands.
Why it matters
No other file in the estate was found to import it.
Application
teleprinter · drivers/codex · JavaScript module
Uses
Codex Driver (script call), node:fs/promises, node:path, node:url, node:crypto, node:child_process, node:assert/strict
Used by
none found
Produces
sha256, progress
Defines here
sha256, progress
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/file-print-compatibility.mjs:1-116 · blob f56fa300e0d7eae58601be0a44a94ad40937f0c8 · 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
/** Six fresh non-Chrome visits, actual separate File print commands. Offline artifacts only. */
import fs from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { createHash } from 'node:crypto';
import { spawnSync } from 'node:child_process';
import assert from 'node:assert/strict';
import { attachScreenCapture, clickAndReadDownload } from './driver.mjs';
const here = path.dirname(fileURLToPath(import.meta.url));
const base = process.argv[2] || 'https://globalgrid2050.com/testcode/202609051457/';
const output = path.join('C:/Users/vikra/OneDrive/Desktop/offline-screenshots', `file-print-compatibility-${new Date().toISOString().replace(/[:.]/g, '-')}`);
await fs.mkdir(output, { recursive: true });
const { chromium, firefox, webkit } = await import(pathToFileURL(process.env.PLAYWRIGHT_MODULE || 'C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright/index.mjs').href);
const sha256 = value => createHash('sha256').update(value).digest('hex');
const report = { base, output, startedAt: new Date().toISOString(), physicalSafariOrIPhoneTested: false,
  screenshotChooserCovered: false, captureMethod: 'Playwright viewport capture binding', visits: [] };
const reportPath = path.join(here, 'file-print-compatibility-results.json');
const retryFirefoxSource = process.argv.includes('--retry-firefox-source');
if (retryFirefoxSource) {
  const original = JSON.parse(await fs.readFile(reportPath, 'utf8'));
  assert.equal(original.base, base, 'Retry must use the original candidate.');
  report.visits = original.visits;
  report.initialStartedAt = original.startedAt;
  report.originalOutput = original.output;
  report.retry = 'One bounded Firefox source retry; original failures retained.';
}
for (const [name, type, options, viewport, deviceScaleFactor] of [
  ['Edge', chromium, { channel: 'msedge' }, { width: 1440, height: 900 }, 1],
  ['Firefox', firefox, {}, { width: 393, height: 852 }, 2],
  ['WebKit', webkit, {}, { width: 1024, height: 768 }, 2]
]) {
  for (const mode of ['pdf', 'source']) {
    if (retryFirefoxSource && (name !== 'Firefox' || mode !== 'source')) continue;
    const visit = { browser: name, mode, viewport, deviceScaleFactor, startedAt: new Date().toISOString(), ok: false };
    report.visits.push(visit);
    let browser, context, page, png, step = 'launch';
    const errors = [];
    const progress = value => { step = value; console.log(`STEP ${name} ${mode}: ${step}`); };
    const heartbeat = setInterval(() => console.log(`WAIT ${name} ${mode}: ${step}`), 30000);
    try {
      browser = await type.launch({ headless: true, ...options });
      context = await browser.newContext({ viewport, deviceScaleFactor, acceptDownloads: true });
      page = await context.newPage();
      page.on('pageerror', error => errors.push({ type: 'pageerror', text: String(error) }));
      page.on('requestfailed', request => { if (errors.length < 150) errors.push({ type: 'requestfailed', url: request.url(), reason: request.failure()?.errorText }); });
      await attachScreenCapture(page, { onCapture: captured => { png = captured; } });
      progress('navigate and await computed project');
      await page.goto(new URL('atlas/?repd_ref=2484&technology=wind_offshore&latitude=52.6199968&longitude=2.5499934', base).href, { waitUntil: 'domcontentloaded', timeout: 60000 });
      await page.getByText(/TEST CODE .*\| ENGINE COMPLETED/).first().waitFor({ state: 'visible', timeout: 90000 });
      assert.match(await page.locator('body').innerText(), /REPD\s+2484\b/);
      visit.url = page.url();
      visit.engineStatus = await page.getByText(/TEST CODE .*\| ENGINE COMPLETED/).first().innerText();
      const fileMenu = page.locator('.gm-title').filter({ hasText: /^File$/i });
      await fileMenu.waitFor({ state: 'visible', timeout: 60000 });
      const toggle = page.locator('#gridatlas-dash-toggle');
      if (!/HIDE LAYERS/i.test(await toggle.innerText())) await toggle.click();
      for (const layer of ['400', '275']) {
        progress(`select layer ${layer}`);
        const input = page.locator(`input[data-gridatlas-layer-proxy="engine:${layer}"]:visible, input[data-layer-id="${layer}"]:visible`).first();
        await input.waitFor({ state: 'visible', timeout: 60000 });
        await input.locator('xpath=ancestor::label[1]').click();
        assert.equal(await input.isChecked(), true);
      }
      visit.selectedLayerKeys = await page.locator('input[data-layer-id]:visible, input[data-gridatlas-layer-proxy]:visible').evaluateAll(inputs => inputs.filter(input => input.checked).map(input => input.dataset.gridatlasLayerProxy || `engine:${input.dataset.layerId}`).sort());
      await fileMenu.click();
      progress(`File > ${mode === 'pdf' ? 'Print' : 'Print source code'}`);
      const command = mode === 'pdf'
        ? page.locator('button[data-gm-export]').filter({ hasText: /Print/i }).first()
        : page.locator('button[data-codex-print-source]').first();
      const download = await clickAndReadDownload(page, command, { timeout: mode === 'pdf' ? 60000 : 120000 });
      assert.ok(download.ok, download.error);
      visit.path = path.join(output, `${name}-${mode}.${mode === 'pdf' ? 'pdf' : 'txt'}`);
      visit.bytes = download.bytes.length;
      visit.sha256 = sha256(download.bytes);
      await fs.writeFile(visit.path, download.bytes, { flag: 'wx' });
      if (mode === 'pdf') {
        assert.ok(png, 'App File Print did not invoke host capture.');
        visit.pngPath = path.join(output, `${name}-pdf.png`);
        visit.pngSha256 = sha256(png);
        await fs.writeFile(visit.pngPath, png, { flag: 'wx' });
        progress('inspect PDF image pixels and furniture');
        const inspected = spawnSync('python', [path.join(here, 'inspect-pdf.py')], { input: JSON.stringify({ pdf: download.bytes.toString('base64'), png: png.toString('base64') }), encoding: 'utf8', maxBuffer: 2000000, timeout: 60000 });
        assert.equal(inspected.status, 0, inspected.stderr);
        visit.inspection = JSON.parse(inspected.stdout);
        assert.ok(visit.inspection.headersFootersPresent);
      } else {
        const match = download.bytes.toString('utf8').match(/===== BEGIN DIAGNOSTIC MANIFEST =====\r?\n([\s\S]*?)\r?\n===== END DIAGNOSTIC MANIFEST =====/);
        assert.ok(match, 'No runtime diagnostic manifest in File source download.');
        const manifest = JSON.parse(match[1]);
        visit.manifest = { format: manifest.format, counts: manifest.counts, complete: manifest.complete, observedResourcesComplete: manifest.observedResourcesComplete, failures: manifest.failures, sourceCommit: manifest.baseManifest?.commit, stateUrl: manifest.state?.url };
        assert.equal(manifest.state?.url, visit.url);
        assert.equal(manifest.failures?.length, 0, 'Source capture has failed resources.');
      }
      visit.ok = true;
      console.log(`PASS ${name} ${mode}: ${visit.bytes} bytes`);
    } catch (error) {
      visit.error = String(error);
      const evidence = Buffer.from(JSON.stringify({ errors, body: await page?.locator('body').innerText().catch(() => ''), dom: await page?.content().catch(() => '') }, null, 2));
      visit.failurePath = path.join(output, `${name}-${mode}-failure.json`);
      visit.failureSha256 = sha256(evidence);
      await fs.writeFile(visit.failurePath, evidence, { flag: 'wx' });
      console.log(`FAIL ${name} ${mode}: ${error.message}`);
    } finally {
      clearInterval(heartbeat); png = undefined;
      await context?.close().catch(() => {});
      await browser?.close().catch(() => {});
      visit.finishedAt = new Date().toISOString();
      await fs.writeFile(reportPath, JSON.stringify(report, null, 2) + '\n');
    }
  }
}
report.finishedAt = new Date().toISOString();
report.ok = report.visits.length === 6 && report.visits.every(visit => visit.ok);
await fs.writeFile(reportPath, JSON.stringify(report, null, 2) + '\n');
console.log(JSON.stringify({ ok: report.ok, reportPath, output }));
if (!report.ok) process.exitCode = 1;

Codex Inspect App PDF

A Python module in the drivers folder of Teleprinter that compares an app-render PDF with an independent browser screenshot; not exact pixel equivalence.

ingestteleprinter / drivers/codex/inspect-app-pdf.py · lines 1–23 of 23 · Not reached from any entry point (candidate for review)

What it does
It loads data. Uses libraries base64, io, json, sys, pymupdf. 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).
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
No other file in the estate was found to import it.
Application
teleprinter · drivers/codex · Python module
Uses
base64, io, json, sys, pymupdf, numpy, PIL
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/inspect-app-pdf.py:1-23 · blob 1789b4fbb8ec3e04041cb57c980db493debe4082 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
"""Compare an app-render PDF with an independent browser screenshot; not exact pixel equivalence."""
import base64,io,json,sys
import pymupdf
import numpy as np
from PIL import Image
p=json.load(sys.stdin)
d=pymupdf.open(stream=base64.b64decode(p['pdf']),filetype='pdf')
assert len(d)==1
images=d[0].get_images();assert len(images)==1
pix=pymupdf.Pixmap(d,images[0][0]);actual=np.asarray(Image.frombytes('RGB',[pix.width,pix.height],pix.samples)).astype('int16')
reference=np.asarray(Image.open(io.BytesIO(base64.b64decode(p['png']))).convert('RGB')).astype('int16')
assert actual.shape==reference.shape,(actual.shape,reference.shape)
rect=d[0].get_image_rects(images[0][0])[0]
assert rect.width==pix.width and rect.height==pix.height and rect.y0>0 and rect.y1<d[0].rect.height
assert 'GLOBALGRID2050' in d[0].get_text()
h,w=actual.shape[:2];regions={'whole':(0,0,w,h),'menu':(0,0,w,max(1,round(h*.06))),'left':(0,0,w//3,h),'middle':(w//3,0,w*2//3,h),'right':(w*2//3,0,w,h)}
scores={}
for name,(x,y,x2,y2) in regions.items():
 a,b=actual[y:y2,x:x2],reference[y:y2,x:x2]
 score=float(np.mean(np.max(np.abs(a-b),axis=2)<=32));scores[name]=score
 assert score>=.85,(name,score)
assert np.std(actual)>5,'Blank app image'
print(json.dumps({'width':w,'height':h,'imageUnscaled':True,'furnitureOutsideImage':True,'fractionWithin32PerChannel':scores,'scope':'Approximate app-render comparison, threshold85% per region; not browser compositor pixel equivalence.'}))

Codex Inspect PDF

A Python module in the drivers folder of Teleprinter that reads PDF structure AND render the page; no PDF/image retained by this check, using SHA-256.

ingestteleprinter / drivers/codex/inspect-pdf.py · lines 1–50 of 50 · Not reached from any entry point (candidate for review)

What it does
It loads data. Uses libraries sys, json, base64, io, hashlib. 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).
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
No other file in the estate was found to import it.
Application
teleprinter · drivers/codex · Python module
Uses
sys, json, base64, io, hashlib, pymupdf, PIL, pypdf
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/inspect-pdf.py:1-50 · blob 5e588721f0e84ba5e78474a60604f9258cbd65e6 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
"""Read PDF structure AND render the page; no PDF/image retained by this check."""
import sys, json, base64, io, hashlib
import pymupdf
from PIL import Image
from pypdf import PdfReader
payload = json.load(sys.stdin)
pdf = base64.b64decode(payload['pdf'])
png = base64.b64decode(payload['png'])
original = Image.open(io.BytesIO(png))
source = original.convert('RGB')
reader = PdfReader(io.BytesIO(pdf), strict=True)
assert len(reader.pages) == 1, 'expected one digital page'
page = reader.pages[0]
assert float(page.mediabox.width) == source.width, 'screen width changed'
assert float(page.mediabox.height) >= source.height, 'screen height cropped'
objects = page['/Resources']['/XObject'].get_object()
assert len(objects) == 1, 'expected only the captured screen'
image = next(iter(objects.values())).get_object()
assert (image['/Width'], image['/Height']) == source.size, 'image downsampled'
raw = image.get_data()
if raw != source.tobytes():
    expected=source.tobytes()
    differences=[(i,raw[i],expected[i]) for i in range(len(raw)) if raw[i]!=expected[i]]
    raise AssertionError(json.dumps({'problem':'embedded screen pixels changed','sourceMode':original.mode,'pngInfo':str(original.info)[:200],'differentChannels':len(differences),'firstDifferences':differences[:12],'maxDifference':max(abs(a-b) for _,a,b in differences),'alphaExtrema':original.getchannel('A').getextrema() if original.mode=='RGBA' else None}))
doc = pymupdf.open(stream=pdf, filetype='pdf')
image_ref=doc[0].get_images()[0][0]
rects=doc[0].get_image_rects(image_ref)
assert len(rects)==1,'screen must appear exactly once'
image_rect=rects[0]
assert (image_rect.width,image_rect.height)==source.size,'screen was scaled'
assert image_rect.x0==0,'unexpected side margin'
furniture=doc[0].rect.height>source.height
if furniture:
    text=doc[0].get_text()
    assert 'GLOBALGRID2050' in text,'approved header missing'
    assert 'generation' in text.lower(),'generation footer missing'
render = doc[0].get_pixmap(matrix=pymupdf.Matrix(1,1), clip=image_rect, alpha=False)
assert (render.width, render.height) == source.size, 'render size differs'
profile=original.info.get('icc_profile')
if profile:
    colour=image['/ColorSpace']
    assert colour[0]=='/ICCBased' and colour[1].get_object().get_data()==profile, 'original colour profile not preserved'
    reference_doc=pymupdf.open(stream=png,filetype='png')
    rect=reference_doc[0].rect
    reference=reference_doc[0].get_pixmap(matrix=pymupdf.Matrix(source.width/rect.width,source.height/rect.height),alpha=False)
    assert (reference.width,reference.height)==source.size
    assert render.samples==reference.samples, 'PDF rendering differs from colour-managed PNG rendering'
else:
    assert render.samples == source.tobytes(), 'rendered PDF differs from screen'
print(json.dumps({'width':source.width,'height':source.height,'pageWidth':doc[0].rect.width,'pageHeight':doc[0].rect.height,'imageRect':list(image_rect),'headersFootersPresent':furniture,'pixels':source.width*source.height,'embeddedPixelsIdentical':True,'colourProfilePreserved':bool(profile),'renderedPixelsIdentical':True,'renderReference':'original PNG through MuPDF colour management' if profile   … [line shortened here: 469 characters; full line on GitHub]

Codex Layer Quick Controls Test

A test in the drivers folder of Teleprinter that checks Layer Quick Controls. It is built from the box step (`box`).

testteleprinter / drivers/codex/layer-quick-controls.test.mjs · lines 1–15 of 15 · Not reached from any entry point (candidate for review)

What it does
It tests its inputs. Defines box. Uses libraries node:test, node:assert/strict.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'codex'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). README: "Maintained source cartridges are enumerated in `cartridges.json`: capture geometry, visible UI clone, Grid/Subs quick controls, Layers arrival policy, and the independent Layout command."
What it achieves
The README says: Maintained source cartridges are enumerated in `cartridges.json`: capture geometry, visible UI clone, Grid/Subs quick controls, Layers arrival policy, and the independent Layout command.
Why it matters
Guards the behaviour of Layer Quick Controls.
Application
teleprinter · drivers/codex · test
Uses
Layer Quick Controls (import), node:test, node:assert/strict
Used by
none found
Produces
box
Defines here
box
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/layer-quick-controls.test.mjs:1-15 · blob e0717154219e299ab7aee401924749c2d969976a · GitHub at these lines
State
achieves: readme · context: readme_derived · stage: transform · effects: none found · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
import test from 'node:test';
import assert from 'node:assert/strict';
import {GRID_LAYER_IDS, toggleLayerGroup} from './layer-quick-controls.js';
const box = checked => ({checked, clicks:0, click(){this.checked=!this.checked;this.clicks++;}});
test('grid contract contains all five actual voltages',()=>assert.deepEqual([...GRID_LAYER_IDS],['400','275','220','132','66']));
test('mixed state enables group through existing click handlers, then disables it',()=>{
  const boxes=[box(true),box(false),box(false)]; toggleLayerGroup(boxes);
  assert.ok(boxes.every(b=>b.checked)); assert.equal(boxes[0].clicks,0);
  toggleLayerGroup(boxes); assert.ok(boxes.every(b=>!b.checked));
});
test('independent substation toggle leaves grid state alone',()=>{
  const grid=[box(true)], subs=[box(false)]; toggleLayerGroup(subs);
  assert.equal(subs[0].checked,true); assert.equal(grid[0].clicks,0);
  assert.doesNotThrow(()=>toggleLayerGroup([]));
});

Codex Layout Command Test

A test in the drivers folder of Teleprinter that checks Layout Command.

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

What it does
It tests its inputs. Uses libraries node:test, node:assert/strict. 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).
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
Guards the behaviour of Layout Command.
Application
teleprinter · drivers/codex · test
Uses
Layout Command (import), node:test, node:assert/strict
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
teleprinter@e45bfe38c3040b0f36f7df94ce262b63db8d0b60 drivers/codex/layout-command.test.mjs:1-8 · blob 6adb388f744d7e62fbcab2740acdea34ddb340d8 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
import test from 'node:test';
import assert from 'node:assert/strict';
import {selectedLayoutControl} from './layout-command.js';
test('layout resolves an existing selected-project action, not a grid toggle',()=>{
  const dead={isConnected:false}, disabled={isConnected:true,disabled:true}, action={isConnected:true,disabled:false};
  assert.equal(selectedLayoutControl({querySelectorAll(selector){assert.equal(selector,'.neon-layout');return [dead,disabled,action];}}),action);
});
test('no selection has no implicit calculation or layer action',()=>assert.equal(selectedLayoutControl({querySelectorAll:()=>[]}),null));