GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / AI agents and coordination / testcode / sandbox/capsules/teleprinter

Build and 7 more files

A JavaScript module in the teleprinter folder of Testcode that draws cartridges, tool layers and scopes, using SHA-256.

550 lines of JavaScript and Python from testcode, in 8 files. Topic: AI agents and coordination. Section 1661 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. Build render · testcode / sandbox/capsules/teleprinter/build.mjs lines 1–174
  2. Homepage storage · testcode / sandbox/capsules/teleprinter/homepage.py lines 1–29
  3. Serve other · testcode / sandbox/capsules/teleprinter/serve.py lines 1–65
  4. Serve Test test · testcode / sandbox/capsules/teleprinter/serve.test.py lines 1–66
  5. Verify Candidate storage · testcode / sandbox/capsules/teleprinter/verify-candidate.mjs lines 1–74
  6. Verify Candidate Test test · testcode / sandbox/capsules/teleprinter/verify-candidate.test.mjs lines 1–34
  7. Verify Live storage · testcode / sandbox/capsules/teleprinter/verify-live.py lines 1–32
  8. Session Restart Test test · testcode / sandbox/capsules/tool-layers/session-restart.test.mjs lines 1–76

Build

A JavaScript module in the teleprinter folder of Testcode that draws cartridges, tool layers and scopes, using SHA-256.

rendertestcode / sandbox/capsules/teleprinter/build.mjs · lines 1–174 of 174 · Entry point

What it does
It draws cartridges, tool layers and scopes. Defines git, sha256, requireCandidateSyntax, write, walk. Uses libraries node:child_process, node:fs/promises, node:crypto, node:path, node:url. 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 experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: JSON file cartridges.json; JSON file results.json; JSON file tool-layers.json; JSON file layer-source-scopes.json; JSON file current.json; JSON file release.json; JSON file inherited-release.json; JSON file cases.json.
Downstream impact
Used directly by 1 file: Codex Cartridges Workflow (testcode).
What it achieves
It is built from the git step (`git`), the sha256 step (`sha256`) and the require candidate syntax helper (`requireCandidateSyntax`). Codex: prepare a new immutable Test Code generation; finish source bundles after committing code. It writes `atlas/tool-layers.json`.
Why it matters
Run by Codex Cartridges Workflow.
Application
testcode · sandbox/capsules/teleprinter · JavaScript module
Uses
Verify Candidate (script call), Compose (script call), Ownership (script call), Registry (script call), Source Scopes (script call), node:child_process, node:fs/promises, node:crypto, node:path, node:url
Used by
run by Codex Cartridges Workflow (workflow run)
Produces
git, sha256, requireCandidateSyntax, write, walk
Defines here
git, sha256, requireCandidateSyntax, write, walk
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/capsules/teleprinter/build.mjs:1-174 · blob aed6c674fabeab808acda999072e98f952356b59 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, process · domain stage: experimental · users: none · canonical: unknown
/** Codex: prepare a new immutable Test Code generation; finish source bundles after committing code. */
import { execFileSync } from 'node:child_process';
import { cp, mkdir, readFile, writeFile, readdir, rename, access } from 'node:fs/promises';
import { createHash } from 'node:crypto';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { verifyCandidate } from './verify-candidate.mjs';
import { composeToolOwner } from '../tool-layers/compose.mjs';
import { mergeToolOwnership } from '../tool-layers/ownership.mjs';
import { buildNavigationRegistry } from '../tool-layers/registry.mjs';
import { buildToolSourceScopes } from '../tool-layers/source-scopes.mjs';

const repo = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../..');
const args = process.argv.slice(2);
const mode = args.shift();
const options = {};
while (args.length) { const key = args.shift(); if (!key.startsWith('--') || !args.length) throw new Error('Use --name value options.'); options[key.slice(2)] = args.shift(); }
const engineDir = options['engine-dir'] || process.env.TELEPRINTER_REPO;
if (!engineDir) throw new Error('Provide --engine-dir PATH_TO_TELEPRINTER_REPOSITORY.');
const git = (dir, ...args) => execFileSync('git', ['-C', dir, ...args], { maxBuffer: 256 * 1024 * 1024, windowsHide: true });
const sha256 = value => createHash('sha256').update(value).digest('hex');
const generation = options.generation || (mode === 'prepare' ? new Date().toISOString().replace(/\D/g, '').slice(0, 12) : '');
if (!/^\d{12}$/.test(generation)) throw new Error('A 12-digit --generation UTC timestamp is required.');
const generationRoot = path.join(repo, 'sandbox', generation);
async function requireCandidateSyntax() {
  const result = await verifyCandidate(generationRoot);
  if (!result.ok) throw new Error('Candidate refused: ' + JSON.stringify(result.checks.filter(check => !check.ok)));
  console.log(`Offline candidate gate: ${result.scripts} scripts, ${result.checks.length} checks passed.`);
}
const prefix = `sandbox/${generation}`;
const modules = ['controls.js', 'print-screen.js', 'screen-pdf.mjs', 'png-pixels.mjs', 'print-source-code.js', 'runtime-source.js', 'app-frame.js', 'capture-geometry.mjs', 'clone-visible-ui.js', 'layer-quick-controls.js', 'layers-panel-policy.js', 'layout-command.js', 'cartridges.json', 'vendor/html2canvas-1.4.1.mjs', 'vendor/html2canvas-LICENSE.txt'];
async function write(relative, contents) {
  const target = path.join(generationRoot, relative);
  await mkdir(path.dirname(target), { recursive: true });
  await writeFile(target, contents);
}
async function walk(dir, base = dir) {
  const output = [];
  for (const entry of await readdir(dir, { withFileTypes: true })) {
    const full = path.join(dir, entry.name);
    if (entry.isDirectory()) output.push(...await walk(full, base));
    else if (entry.isFile()) output.push(path.relative(base, full).replaceAll('\\', '/'));
    else throw new Error(`Unsupported file type: ${full}`);
  }
  return output.sort();
}
const sourceScopeNote = `# Print source code scope\n\nThis generation adds the Codex-authored Teleprinter controls. Each app's text includes the committed HTML, JavaScript, ESM and CSS in its app directory, its bootstrap, the Teleprinter browser modules and vendored renderer license, and this scope note. Atlas includes current.json, which identifies the immutable remote shell and hashed cartridges  … [line shortened here: 2,147 characters; full line on GitHub]

if (mode === 'prepare') {
  const predecessor = options.from || '202609051344';
  if (!/^\d{12}$/.test(predecessor) || predecessor === generation) throw new Error('Invalid predecessor generation.');
  const predecessorRoot = path.join(repo, 'sandbox', predecessor);
  await access(predecessorRoot);
  const evidenceGeneration = JSON.parse(await readFile(path.join(predecessorRoot, 'results.json'), 'utf8')).generation || predecessor;
  // mkdir without recursive refuses an existing generation; never repair an old timestamp in place.
  await mkdir(generationRoot);
  for (const entry of await readdir(predecessorRoot)) await cp(path.join(predecessorRoot, entry), path.join(generationRoot, entry), { recursive: true, force: false, errorOnExist: true });
  const engineCommit = git(engineDir, 'rev-parse', '--verify', '--end-of-options', `${options['engine-revision'] || 'HEAD'}^{commit}`).toString().trim();
  for (const filename of modules) await write(`teleprinter/${filename}`, git(engineDir, 'show', `${engineCommit}:drivers/codex/${filename}`));
  const originals = await walk(generationRoot);
  for (const relative of originals) {
    if (!/\.(?:html|js|mjs|css)$/.test(relative) || relative === 'results.html' || relative.startsWith('teleprinter/') || relative.startsWith('layer-apps/')) continue;
    const full = path.join(generationRoot, relative);
    let text = (await readFile(full, 'utf8')).replace(/\r\n/g, '\n');
    text = text.replaceAll(predecessor, generation);
    if (relative === 'atlas/index.html') text = text.replace(/<title>[^<]*<\/title>/, `<title>Test Code Atlas ${generation}</title>`);
    await writeFile(full, text);
    if (path.basename(relative).includes(predecessor)) await rename(full, path.join(generationRoot, relative.replaceAll(predecessor, generation)));
  }
  let toolLayerBootstrap = '';
  if (options['tool-owner']) {
    const owner = await composeToolOwner(generationRoot, options['tool-owner'], options['tool-revision'], options['tool-release']);
    let previous = {owners:[],tools:[]};
    try { previous = JSON.parse(await readFile(path.join(generationRoot,'atlas/tool-layers.json'),'utf8')); } catch(error) { if(error.code!=='ENOENT') throw error; }
    const names = {'gis-sld-financial-sandbox':'GIS SLD Financial Sandbox','module-layout':'Module Layout','cable-geometry-visualiser':'Cable Geometry','dc-ac-coupled-bess':'DC / AC BESS'};
    const apps = owner.applications.filter(app=>!options['tool-id'] || app.id===options['tool-id']);
    if(!apps.length) throw Error('Requested tool is absent from pinned owner manifest');
    await write('atlas/tool-layers.json', JSON.stringify(mergeToolOwnership(previous,owner,apps,names),null,2)+'\n');
  }
  try {
    const config = JSON.parse(await readFile(path.join(generationRoot,'atlas/tool-layers.json'),'utf8'));
    config.navigation=buildNavigationRegistry(config);
    const toolSources=await buildToolSourceScopes(config.navigation,owner=>{
      const name=owner.repository.match(/^https:\/\/github\.com\/Ventusltd\/([a-zA-Z0-9_-]+)(?:\.git)?$/)?.[1];
      if(!name)throw Error('Unsupported local tool owner repository');
      return git(path.join(path.dirname(engineDir),name),'show',`${owner.commit}:releases/${owner.release}/manifest.json`);
    },file=>readFile(path.join(generationRoot,file)));
    await write('layer-source-scopes.json',JSON.stringify(toolSources,null,2)+'\n');
    for(const file of ['index.html','source-browser.css','source-browser.mjs'])await write('source-browser/'+file,(await readFile(new URL('../tool-layers/source-browser/'+file,import.meta.url),'utf8')).replace(/\r\n/g,'\n'));
    await write('atlas/tool-layers.json',JSON.stringify(config,null,2)+'\n');
    for (const file of ['navigation.js','host.js','dismissal.js','focus-boundary.js','readiness.js','viewport.js','session-restart.js','recovery.js']) await write('tool-layers/'+file, (await readFile(new URL('../tool-layers/'+file,import.meta.url),'utf8')).replace(/\r\n/g,'\n'));
    toolLayerBootstrap = `import { mountToolLayers } from '../tool-layers/host.js';\nmountToolLayers(${JSON.stringify(config.tools)}, import.meta.url, ${JSON.stringify(config.navigation)});\n`;
  } catch (error) { if (error.code !== 'ENOENT') throw error; }
  const current = JSON.parse((await readFile(path.join(generationRoot, 'atlas/current.json'), 'utf8')).replaceAll(predecessor, generation));
  current.generation = generation;
  current.previous_generation = predecessor;
  current.composition_id = `${generation}-teleprinter`;
  for (const cartridge of current.cartridges) {
    const relative = path.posix.normalize(`atlas/${cartridge.path}`);
    if (!relative.startsWith('atlas/cartridges/') || relative.includes('..')) throw new Error('Unsafe cartridge path.');
    cartridge.sha256 = sha256(await readFile(path.join(generationRoot, relative)));
  }
  await write('atlas/current.json', JSON.stringify(current, null, 2) + '\n');
  for (const [app, appName] of [['landing', 'Test Code'], ['pipeline', 'Pipeline News'], ['atlas', 'GridAtlas']]) {
    const appDir = app === 'landing' ? '' : `${app}/`;
    const parent = app === 'landing' ? './' : '../';
    await write(`${appDir}teleprinter-bootstrap.js`, `import { mountTeleprinter } from '${parent}teleprinter/controls.js';\n${app === 'atlas' ? `import { mountLayerQuickControls } from '${parent}teleprinter/layer-quick-controls.js';\nmountLayerQuickControls();\nimport { mountLayersPanelPolicy } from '${parent}teleprinter/layers-panel-policy.js';\nmountLayersPanelPolicy();\nimport { mountLayoutComm  … [line shortened here: 1,582 characters; full line on GitHub]
    let html = await readFile(path.join(generationRoot, `${appDir}index.html`), 'utf8');
    // A predecessor can already have Teleprinter. Replace its mount, never stack it.
    html = html.replace(/      const teleprinterUrl =[^\n]*\n      const teleprinterScript =[^\n]*\n      html =[^\n]*\n\s*\n/g, '');
    html = html.replace(/<script type="module" src="\.\/teleprinter-bootstrap\.js"><\/script>\s*/g, '');
    html = html.replace(/      html = html\.replace\(\/<head>\/i, '<head><link rel="icon" href="data:,">'\);\n/g, '');
    if (!/<link\b[^>]*rel=["']icon["']/i.test(html)) html = /<head>/i.test(html) ? html.replace(/<head>/i, '<head><link rel="icon" href="data:,">') : html.replace(/<!doctype html>/i, '<!doctype html><link rel="icon" href="data:,">');
    if (app === 'atlas') {
      const marker = '      document.open();';
      if (!html.includes(marker)) throw new Error('Atlas composer insertion point missing.');
      html = html.replace(marker, `      html = html.replace(/<head>/i, '<head><link rel="icon" href="data:,">');\n${marker}`);
      html = html.replace(marker, () => `      const teleprinterUrl = new URL('./teleprinter-bootstrap.js', window.location.href).href;\n      const teleprinterScript = '<script type="module" src="' + escapeAttribute(teleprinterUrl) + '">' + SCRIPT_CLOSE;\n      html = /<\\/body>/i.test(html) ? html.replace(/<\\/body>/i, teleprinterScript + '$&') : html + teleprinterScript;\n\n${marker}`);
    } else {
      const mount = '<script type="module" src="./teleprinter-bootstrap.js"></script>';
      html = /<\/body>/i.test(html) ? html.replace(/<\/body>/i, mount + '\n</body>') : html + '\n' + mount + '\n';
      if (app === 'landing') {
        html = html.replace(/<p><strong>Inherited detector evidence from \d{12}\.<\/strong>[^<]*<\/p>/g, '');
        html = html.replace(/(<h1>[^<]*<\/h1>)/, `$1<p><strong>Inherited detector evidence from ${evidenceGeneration}.</strong> The grid measurements below were not rerun for this print-test generation.</p>`);
      }
    }
    await write(`${appDir}index.html`, html);
  }
  const predecessorRelease = JSON.parse(await readFile(path.join(predecessorRoot, 'release.json'), 'utf8'));
  await write('inherited-release.json', JSON.stringify(predecessorRelease, null, 2) + '\n');
  await write('release.json', JSON.stringify({ generation, predecessor, built_utc: new Date().toISOString(), purpose: 'Full rendered screen through File Print, retained header/footer, and current-view source with runtime dependencies.', teleprinter: { repository: 'https://github.com/Ventusltd/teleprinter', commit: engineCommit }, inherited_detector_evidence: { generation: evidenceGeneration, rerun  … [line shortened here: 650 characters; full line on GitHub]
  await write('teleprinter/SOURCE-SCOPE.md', sourceScopeNote);
  await write('teleprinter/.gitattributes', '# Source bundle SHA256 applies to these exact bytes on every platform.\n*-source-code.txt -text\n');
  const files = await walk(generationRoot);
  for (const relative of files.filter(file => file.startsWith('pipeline/contracts/') && file.endsWith('.json'))) await write(relative, (await readFile(path.join(generationRoot, relative), 'utf8')).replace(/\r\n/g, '\n'));
  const common = modules.map(name => `teleprinter/${name}`).concat('teleprinter/SOURCE-SCOPE.md');
  const scopes = {};
  for (const app of ['landing', 'pipeline', 'atlas']) {
    const selected = app === 'landing' ? ['index.html', 'capsule-launch.js', 'teleprinter-bootstrap.js'] : files.filter(file => file.startsWith(`${app}/`) && !file.startsWith(`${app}/data/`) && /\.(?:html|js|mjs|css)$/.test(file));
    if (app === 'atlas') { selected.push('atlas/current.json'); if(toolLayerBootstrap) selected.push('atlas/tool-layers.json','tool-layers/host.js','tool-layers/dismissal.js','tool-layers/focus-boundary.js','tool-layers/readiness.js','tool-layers/viewport.js','tool-layers/session-restart.js','tool-layers/recovery.js','tool-layers/navigation.js'); }
    if (app === 'pipeline') selected.push(...files.filter(file => file.startsWith('pipeline/contracts/') && file.endsWith('.json')));
    scopes[app] = [...new Set([...selected, ...common])].sort().map(file => `${prefix}/${file}`);
  }
  await write('teleprinter/source-scopes.json', JSON.stringify({ generation, predecessor, engineCommit, scopes, excluded: ['atlas/data/**', 'pipeline/data/**', '**/results*', '**/cases*', '**/receipts*', 'inherited detector evidence', 'generated source text, manifests, and pins', 'external runtime dependencies'] }, null, 2) + '\n');
  await requireCandidateSyntax();
  console.log(JSON.stringify({ generation, codeReady: true, launchPaths: [`/testcode/${generation}/`, `/testcode/${generation}/pipeline/`, `/testcode/${generation}/atlas/`], finish: `node sandbox/capsules/teleprinter/build.mjs finish --generation ${generation} --revision FULL_CODE_COMMIT --engine-dir "${engineDir}"` }, null, 2));
} else if (mode === 'finish') {
  if (!options.revision) throw new Error('Finish requires --revision FULL_CODE_COMMIT after source is committed.');
  const commit = git(repo, 'rev-parse', '--verify', '--end-of-options', `${options.revision}^{commit}`).toString().trim();
  const scopePath = `${prefix}/teleprinter/source-scopes.json`;
  const plan = JSON.parse(git(repo, 'show', `${commit}:${scopePath}`).toString('utf8'));
  if (plan.generation !== generation) throw new Error('Source scope generation mismatch.');
  const engineSource = git(engineDir, 'show', `${plan.engineCommit}:drivers/codex/source-code.mjs`);
  const { writeSourceCodeBundle, verifySourceCodeBundleAgainstRepository } = await import(`data:text/javascript;base64,${engineSource.toString('base64')}`);
  const results = [];
  for (const [app, scopes] of Object.entries(plan.scopes)) {
    if (!['landing', 'pipeline', 'atlas'].includes(app) || !Array.isArray(scopes) || !scopes.length || scopes.some(scope => !scope.startsWith(`${prefix}/`) || scope.split('/').includes('..'))) throw new Error('Invalid committed source scopes.');
    // Deployment files must match the pinned code, including uncommitted worktree changes.
    for (const scope of scopes) {
      const committed = git(repo, 'show', `${commit}:${scope}`);
      const present = await readFile(path.join(repo, scope));
      if (!committed.equals(present)) throw new Error(`Source must be committed before finish: ${scope}`);
    }
    const textPath = path.join(generationRoot, `teleprinter/${app}-source-code.txt`);
    const manifestPath = path.join(generationRoot, `teleprinter/${app}-source-code.manifest.json`);
    const repository = 'https://github.com/Ventusltd/testcode';
    const manifest = await writeSourceCodeBundle({ repoDir: repo, revision: commit, repository, paths: scopes, textPath, manifestPath });
    await verifySourceCodeBundleAgainstRepository(await readFile(textPath, 'utf8'), manifest, { repoDir: repo, expectedCommit: commit, expectedRepository: repository, paths: scopes });
    await write(`teleprinter/${app}-source-pin.json`, JSON.stringify({ generation, app, repository, commit, sha256: manifest.sha256, byteCount: manifest.byteCount }, null, 2) + '\n');
    results.push({ app, commit, included: manifest.includedCount, omitted: manifest.omittedCount, bytes: manifest.byteCount });
  }
  await requireCandidateSyntax();
  console.log(JSON.stringify({ generation, sourceReady: true, results }, null, 2));
} else throw new Error('Use prepare or finish.');

Homepage

A Python module in the teleprinter folder of Testcode that prepares one measured homepage restore point and append the new Test Code link, using SHA-256.

storagetestcode / sandbox/capsules/teleprinter/homepage.py · lines 1–29 of 29 · Not reached from any entry point (candidate for review)

What it does
It lists and searches its content. Uses libraries pathlib, subprocess, hashlib, json, re. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. README: "`homepage.py WEB_REPO GENERATION` creates a measured restore point before adding the new Test Code link and retaining its predecessor."
Inputs & outputs
In: command-line arguments.
What it achieves
The README says: `homepage.py WEB_REPO GENERATION` creates a measured restore point before adding the new Test Code link and retaining its predecessor.
Why it matters
No other file in the estate was found to import it.
Application
testcode · sandbox/capsules/teleprinter · Python module
Uses
pathlib, subprocess, hashlib, json, re, datetime, 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
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/capsules/teleprinter/homepage.py:1-29 · blob 5db818ec02a5e0d71a260de8d45b7a9ffd9227f8 · GitHub at these lines
State
achieves: readme · context: readme_derived · stage: output · effects: filesystem, process · domain stage: experimental · users: none · canonical: unreached_review
"""Prepare one measured homepage restore point and append the new Test Code link."""
import pathlib, subprocess, hashlib, json, re, datetime, sys
root=pathlib.Path(sys.argv[1]).resolve()
generation=sys.argv[2]
assert re.fullmatch(r'\d{12}',generation)
index=root/'index.html'
data=index.read_bytes()
text=data.decode('utf8')
folder=root/'homepage_versions'
versions=list(folder.glob('homepage_v*.html'))
number=max(int(re.search(r'v(\d+)',p.name).group(1)) for p in versions)+1
snapshot=folder/f'homepage_v{number:03}.html'
assert not snapshot.exists()
source=subprocess.check_output(['git','-C',str(root),'rev-parse','HEAD'],text=True).strip()
measurement={'created_utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'folder_file_count_before':sum(p.is_file() for p in folder.iterdir()),'html_version':snapshot.name,'line_count':len(text.splitlines()),'word_count':len(text.split()),'character_count':len(text),'bytes':len(data),'sha256':hashlib.sha256(data).hexdigest(),'source_commit':source,'intention':f'Add Test Code {generation  … [line shortened here: 489 characters; full line on GitHub]
snapshot.write_bytes(data)
(folder/f'homepage_v{number:03}-measurement.json').write_text(json.dumps(measurement,indent=2)+'\n',encoding='utf8')
assert f'./testcode/{generation}/' not in text, 'generation already linked'
previous=re.search(r'<p><a href="\./testcode/(\d{12})/">([^<]*)</a>',text)
assert previous, 'expected prior Test Code link'
anchor=f'<p><a href="./testcode/{previous.group(1)}/">'
assert text.count(anchor)==1,'expected previous Test Code row'
new=f'<p><a href="./testcode/{generation}/">Print test candidate — {generation} UTC</a>: <strong>File → Print</strong> keeps the full screen and its layers, with a header and footer. <strong>Print source code</strong> includes the current view and fetched dependencies for attaching in AI chat. Testing is in progress; this is not a Design Freeze.</p>\n'
text=text.replace(anchor,new+anchor,1)
prior_label=previous.group(2)
if not prior_label.startswith('Previous '):
    text=text.replace(anchor+prior_label+'</a>',anchor+'Previous '+prior_label+'</a>',1)
index.write_text(text,encoding='utf8',newline='\n')
print(json.dumps(measurement,indent=2))

Serve

A Python command-line tool in the teleprinter folder of Testcode that works with do get (`do_GET`) and do post (`do_POST`).

othertestcode / sandbox/capsules/teleprinter/serve.py · lines 1–65 of 65 · Entry point · pattern do_POST (shared by 2 files)

What it does
Defines 6 functions or classes, including handler, Handler, __init__, reply, do_GET. Uses libraries argparse, json, threading, datetime, http.server. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: command-line arguments.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It is built from the handler step (`handler`), the handler class (`Handler`) and the reply step (`reply`). Local static app server with an offline diagnostic receipt endpoint. It accepts `--root`, `--output` and `--port`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
testcode · sandbox/capsules/teleprinter · Python CLI
Uses
argparse, json, threading, datetime, http.server, pathlib, urllib.parse
Used by
none found
Produces
handler
Defines here
handler, Handler, __init__, reply, do_GET, do_POST
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/capsules/teleprinter/serve.py:1-65 · blob af9a014f784b217726cdeb7a2402e3322cfc637f · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: experimental · users: none · canonical: unknown
"""Local static app server with an offline diagnostic receipt endpoint."""
import argparse
import json
import threading
from datetime import datetime, timezone
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import urlsplit

MAX_BODY = 1048576

def handler(root, output):
    output = Path(output).resolve()
    if any((parent / ".git").exists() for parent in (output, *output.parents)):
        raise ValueError("Receipt output must be outside Git")
    output.mkdir(parents=True, exist_ok=True)
    log = output / "diagnostic-receipts.jsonl"
    lock = threading.Lock()
    class Handler(SimpleHTTPRequestHandler):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, directory=str(Path(root).resolve()), **kwargs)
        def reply(self, status, payload):
            data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
            self.send_response(status)
            self.send_header("Content-Type", "application/json; charset=utf-8")
            self.send_header("Cache-Control", "no-store")
            self.send_header("Content-Length", str(len(data)))
            self.end_headers()
            self.wfile.write(data)
        def do_GET(self):
            if urlsplit(self.path).path != "/__testcode/receipt":
                return super().do_GET()
            self.reply(200, {"schema": "testcode.receipt-endpoint.v1", "method": "POST",
                             "storage": "offline", "maxBytes": MAX_BODY})
        def do_POST(self):
            if urlsplit(self.path).path != "/__testcode/receipt":
                return self.reply(404, {"error": "Unknown endpoint"})
            try:
                size = int(self.headers.get("Content-Length", "-1"))
            except ValueError:
                size = -1
            if size < 0:
                return self.reply(411, {"error": "Content-Length required"})
            if size > MAX_BODY:
                return self.reply(413, {"error": "Receipt too large"})
            try:
                payload = json.loads(self.rfile.read(size).decode("utf-8"))
                if not isinstance(payload, dict):
                    raise ValueError("Receipt must be an object")
            except (ValueError, UnicodeError):
                return self.reply(400, {"error": "JSON object required"})
            record = {"receivedAt": datetime.now(timezone.utc).isoformat(), "receipt": payload}
            with lock:
                with log.open("a", encoding="utf-8") as stream:
                    stream.write(json.dumps(record, ensure_ascii=False) + "\n")
            self.reply(201, {"ok": True, "receivedAt": record["receivedAt"]})
    return Handler

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--root", required=True)
    parser.add_argument("--output", required=True, help="Offline evidence directory, outside Git")
    parser.add_argument("--port", type=int, default=8894)
    args = parser.parse_args()
    ThreadingHTTPServer(("127.0.0.1", args.port), handler(args.root, args.output)).serve_forever()

Serve Test

A test in the teleprinter folder of Testcode. It is built from the receipt tests class (`ReceiptTests`).

testtestcode / sandbox/capsules/teleprinter/serve.test.py · lines 1–66 of 66 · Entry point · pattern request (shared by 18 files)

What it does
It tests its inputs. Defines ReceiptTests, test_real_server_and_static_negative_control, request. Uses libraries importlib.util, json, tempfile, threading, unittest. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Downstream impact
It is itself an entry point (test); no other file was found loading it.
What it achieves
Defines `ReceiptTests`, `test_real_server_and_static_negative_control` and `request`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
testcode · sandbox/capsules/teleprinter · test
Uses
importlib.util, json, tempfile, threading, unittest, urllib.request, urllib.error, pathlib
Used by
none found
Produces
ReceiptTests
Defines here
ReceiptTests, test_real_server_and_static_negative_control, request
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/capsules/teleprinter/serve.test.py:1-66 · blob 2ba788a116c621bf7fc90cee52f4ab308dc5142d · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, network · domain stage: experimental · users: none · canonical: unknown
import importlib.util
import json
import tempfile
import threading
import unittest
import urllib.request
import urllib.error
from pathlib import Path
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
spec = importlib.util.spec_from_file_location("receipt_server", Path(__file__).with_name("serve.py"))
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)

class ReceiptTests(unittest.TestCase):
    def test_real_server_and_static_negative_control(self):
        with tempfile.TemporaryDirectory() as temp:
            root = Path(temp) / "site"
            root.mkdir()
            (root / "index.html").write_text("<h1>test app</h1>")
            evidence = Path(temp) / "offline"
            def request(server, path, data=None):
                url = "http://127.0.0.1:%s%s" % (server.server_port, path)
                try:
                    with urllib.request.urlopen(urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"}), timeout=5) as response:
                        return response.status, response.read()
                except urllib.error.HTTPError as error:
                    return error.code, error.read()
            server = ThreadingHTTPServer(("127.0.0.1", 0), module.handler(root, evidence))
            worker = threading.Thread(target=server.serve_forever, daemon=True)
            worker.start()
            try:
                self.assertEqual(request(server, "/")[0], 200)
                status, body = request(server, "/__testcode/receipt")
                self.assertEqual(status, 200)
                self.assertEqual(json.loads(body)["schema"], "testcode.receipt-endpoint.v1")
                self.assertEqual(request(server, "/__testcode/receipt", b'{"case":"measured"}')[0], 201)
                record = json.loads((evidence / "diagnostic-receipts.jsonl").read_text())
                self.assertEqual(record["receipt"]["case"], "measured")
                self.assertEqual(request(server, "/__testcode/receipt", b'bad')[0], 400)
                self.assertEqual(request(server, "/__testcode/receipt", b'[]')[0], 400)
                import http.client
                connection = http.client.HTTPConnection("127.0.0.1", server.server_port, timeout=5)
                connection.putrequest("POST", "/__testcode/receipt")
                connection.putheader("Content-Length", str(module.MAX_BODY+1))
                connection.endheaders()
                self.assertEqual(connection.getresponse().status, 413)
                connection.close()
                self.assertEqual(request(server, "/unknown", b'{}')[0], 404)
                self.assertEqual(len((evidence / "diagnostic-receipts.jsonl").read_text().splitlines()), 1)
            finally:
                server.shutdown()
                server.server_close()
                worker.join()
            from functools import partial
            static = ThreadingHTTPServer(("127.0.0.1", 0), partial(SimpleHTTPRequestHandler, directory=str(root)))
            worker = threading.Thread(target=static.serve_forever, daemon=True)
            worker.start()
            try:
                self.assertEqual(request(static, "/__testcode/receipt")[0], 404)
                self.assertEqual(request(static, "/__testcode/receipt", b'{}')[0], 501)
            finally:
                static.shutdown()
                static.server_close()
                worker.join()
if __name__ == "__main__":
    unittest.main()

Verify Candidate

A JavaScript module in the teleprinter folder of Testcode that uses SHA-256. It verifies candidate (`verifyCandidate`) and is built from the sha step (`sha`) and the check step (`check`).

storagetestcode / sandbox/capsules/teleprinter/verify-candidate.mjs · lines 1–74 of 74

What it does
It loads data. Defines sha, verifyCandidate, check, parse, walk. Uses libraries node:fs/promises, node:path, node:vm, node:child_process, node:crypto. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: JSON file current.json; command-line arguments.
Downstream impact
Used directly by 2 files: Build (testcode); Verify Candidate Test (testcode). Reached from 1 other entry point, including Codex Cartridges Workflow (testcode).
What it achieves
Offline gate for the exact candidate bytes, including generated cartridges.
Why it matters
Run by Build. Checked by Verify Candidate Test.
Application
testcode · sandbox/capsules/teleprinter · JavaScript module
Uses
node:fs/promises, node:path, node:vm, node:child_process, node:crypto, node:url
Used by
run by Build (script call), run by Verify Candidate Test (script call)
Produces
verifyCandidate
Defines here
sha, verifyCandidate, check, parse, walk
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/capsules/teleprinter/verify-candidate.mjs:1-74 · blob c56a98ff7e021de92c6d09dc024f7e819671d4b2 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: experimental · users: none · canonical: supporting_data
/** Offline gate for the exact candidate bytes, including generated cartridges. */
import fs from 'node:fs/promises';
import path from 'node:path';
import vm from 'node:vm';
import {spawnSync} from 'node:child_process';
import {createHash} from 'node:crypto';
import {pathToFileURL} from 'node:url';

const sha = bytes => createHash('sha256').update(bytes).digest('hex');
export async function verifyCandidate(root) {
  root = path.resolve(root);
  const checks = [];
  const check = (name, ok, detail) => checks.push({name, ok, detail});
  async function parse(name, code, module) {
    try {
      if (module) {
        const r = spawnSync(process.execPath, ['--check','--input-type=module'], {input:code,encoding:'utf8',windowsHide:true,timeout:15000});
        if (r.status !== 0) throw new Error((r.stderr || String(r.error)).slice(0,1000));
      } else new vm.Script(code, {filename:name});
      check(`parse:${name}`,true,'syntax only; code not executed');
    } catch (error) { check(`parse:${name}`,false,String(error.message)); }
  }
  const files = [];
  async function walk(dir) {
    for (const entry of await fs.readdir(dir,{withFileTypes:true})) {
      if (entry.name === '.git') continue;
      const p = path.join(dir,entry.name);
      if (entry.isDirectory()) await walk(p);
      else if (entry.isFile()) files.push(p);
      else check('file-type',false,p);
    }
  }
  await walk(root);
  const current = JSON.parse(await fs.readFile(path.join(root,'atlas/current.json'),'utf8'));
  check('cartridges-nonempty',Array.isArray(current.cartridges) && current.cartridges.length>0,'Zero runtime cartridges cannot pass');
  for (const entry of current.cartridges || []) {
    const p = path.resolve(root,'atlas',entry.path);
    const relative = path.relative(root,p);
    if (relative.startsWith('..') || path.isAbsolute(relative)) { check('cartridge-path',false,entry.path); continue; }
    try { check(`cartridge-hash:${entry.id}`,sha(await fs.readFile(p))===entry.sha256,entry.path); }
    catch(error) { check(`cartridge-hash:${entry.id}`,false,error.message); }
  }
  let scripts = 0;
  for (const p of files) {
    const name = path.relative(root,p);
    if (/\.(?:m?js|html)$/.test(p)) {
      const code = await fs.readFile(p,'utf8');
      if (/\.m?js$/.test(p)) {
        scripts++;
        await parse(name,code,p.endsWith('.mjs') || /^\s*(?:export\b|import\s+(?!\())/m.test(code));
      } else {
        let index=0;
        for(const [,attrs,body] of code.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi)) {
          if (/\bsrc\s*=/.test(attrs) || !body.trim()) continue;
          const type=attrs.match(/\btype\s*=\s*["']([^"']+)/i)?.[1];
          if(type && !['module','text/javascript','application/javascript'].includes(type)) continue;
          scripts++;
          await parse(`${name}:inline-${++index}`,body,type==='module');
        }
      }
    }
  }
  check('scripts-nonempty',scripts>0,`${scripts} scripts inspected`);
  return {generation:current.generation,files:files.length,scripts,checks,ok:checks.every(x=>x.ok),scope:'Offline syntax and declared cartridge hash checks; no browser, GPU shader compilation or runtime outcome claim.'};
}

if (process.argv[1] && import.meta.url===pathToFileURL(path.resolve(process.argv[1])).href) {
  try {
    const result=await verifyCandidate(process.argv[2]);
    if(process.argv[3]) await fs.writeFile(process.argv[3],JSON.stringify(result,null,2)+'\n');
    console.log(JSON.stringify({generation:result.generation,scripts:result.scripts,passed:result.checks.filter(x=>x.ok).length,failed:result.checks.filter(x=>!x.ok)}));
    if(!result.ok)process.exitCode=1;
  } catch(error) { console.error(String(error));process.exitCode=1; }
}

Verify Candidate Test

A test in the teleprinter folder of Testcode that checks Verify Candidate, using SHA-256.

testtestcode / sandbox/capsules/teleprinter/verify-candidate.test.mjs · lines 1–34 of 34 · Not reached from any entry point (candidate for review) · pattern fixture (shared by 30 files)

What it does
It tests its inputs. Defines fixture. Uses libraries node:test, node:assert/strict, node:fs/promises, node:path, node:crypto. Side effects: changes the web page (DOM); reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
Out: JSON file current.json.
What it achieves
Its name says it verifies candidate test. Defines `fixture`.
Why it matters
Guards the behaviour of Verify Candidate.
Application
testcode · sandbox/capsules/teleprinter · test
Uses
Verify Candidate (script call), node:test, node:assert/strict, node:fs/promises, node:path, node:crypto, node:child_process, node:url
Used by
none found
Produces
fixture
Defines here
fixture
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/capsules/teleprinter/verify-candidate.test.mjs:1-34 · blob 67fbcba682b33653a1be8f14a1db38bd6b651431 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: experimental · users: none · 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 {createHash} from 'node:crypto';
import {spawnSync} from 'node:child_process';
import {fileURLToPath} from 'node:url';
import {verifyCandidate} from './verify-candidate.mjs';
const offline='C:/Users/vikra/OneDrive/Desktop/offline-screenshots/codex-next-print-tests';
await fs.mkdir(offline,{recursive:true});
async function fixture(code,empty=false) {
  const root=await fs.mkdtemp(path.join(offline,'negative-control-'));
  await fs.mkdir(path.join(root,'atlas'));
  await fs.writeFile(path.join(root,'atlas/main.js'),code);
  await fs.writeFile(path.join(root,'atlas/current.json'),JSON.stringify({generation:'fixture',cartridges:empty?[]:[{id:'main',path:'main.js',sha256:createHash('sha256').update(code).digest('hex')}]}));
  await fs.writeFile(path.join(root,'index.html'),'<script>window.ready = true;</script>');
  return root;
}
test('valid generated code and inline script pass',async()=>assert.equal((await verifyCandidate(await fixture('window.ready = true;'))).ok,true));
test('corrupted generated code refuses despite an updated matching hash',async()=>{
  const root=await fixture("window.ready = 'broken\nstring';");
  const r=await verifyCandidate(root);
  assert.equal(r.checks.find(x=>x.name==='cartridge-hash:main').ok,true);
  assert.equal(r.checks.find(x=>x.name==='parse:atlas\\main.js').ok,false);
  const cli=spawnSync(process.execPath,[fileURLToPath(new URL('./verify-candidate.mjs',import.meta.url)),root],{encoding:'utf8',windowsHide:true});
  assert.equal(cli.status,1);
  await fs.writeFile(path.join(root,'refusal.txt'),cli.stdout+cli.stderr);
});
test('zero runtime cartridges cannot report green',async()=>assert.equal((await verifyCandidate(await fixture('window.ready=true;',true))).ok,false));
test('invalid inline script is rejected',async()=>{
  const root=await fixture('window.ready=true;');
  await fs.writeFile(path.join(root,'index.html'),'<script>const broken = ;</script>');
  assert.equal((await verifyCandidate(root)).ok,false);
});

Verify Live

A Python module in the teleprinter folder of Testcode that verifies published Test Code bytes and homepage, using SHA-256. It is built from the check step (`check`).

storagetestcode / sandbox/capsules/teleprinter/verify-live.py · lines 1–32 of 32 · Not reached from any entry point (candidate for review)

What it does
It fetches data. Defines check. Uses libraries pathlib, sys, subprocess, urllib.request, hashlib. Side effects: reads or writes files; makes network requests; starts processes.
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. README: "`verify-live.py WEB_REPO GENERATION OUTPUT_JSON` compares published bytes against Git, including the homepage."
Inputs & outputs
In: command-line arguments.
What it achieves
The README says: `verify-live.py WEB_REPO GENERATION OUTPUT_JSON` compares published bytes against Git, including the homepage.
Why it matters
No other file in the estate was found to import it.
Application
testcode · sandbox/capsules/teleprinter · Python module
Uses
pathlib, sys, subprocess, urllib.request, hashlib, json, datetime, time
Used by
none found
Produces
check
Defines here
check
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/capsules/teleprinter/verify-live.py:1-32 · blob a771baa6d182f47c7ccbe70ca3a3651df80f8621 · GitHub at these lines
State
achieves: readme · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: experimental · users: none · canonical: unreached_review
"""Verify published Test Code bytes and homepage. No screenshot/PDF artifacts."""
from pathlib import Path
import sys,subprocess,urllib.request,hashlib,json,datetime,time,concurrent.futures
repo=Path(sys.argv[1]);generation=sys.argv[2];output=Path(sys.argv[3]);base='https://www.globalgrid2050.com/'
commit=subprocess.check_output(['git','-C',str(repo),'rev-parse','HEAD'],text=True).strip()
prefix='testcode/'+generation+'/'
paths=subprocess.check_output(['git','-C',str(repo),'ls-tree','-r','--name-only',commit,'--',prefix],text=True).splitlines()
paths=[p for p in paths if not any(part.startswith('.') for part in p.split('/'))]
assert len(paths)>100
expected_index=subprocess.check_output(['git','-C',str(repo),'show',commit+':'+prefix+'index.html'])
for attempt in range(45):
    try:
        actual=urllib.request.urlopen(base+prefix+'index.html',timeout=15).read()
        if actual==expected_index:break
    except Exception:pass
    if attempt%3==0:print('Waiting for published Teleprinter '+generation,flush=True)
    time.sleep(20)
else:raise SystemExit('Committed generation not yet served after 15 minutes.')
def check(p):
    expected=subprocess.check_output(['git','-C',str(repo),'show',commit+':'+p])
    try:
        response=urllib.request.urlopen(urllib.request.Request(base+p,headers={'Cache-Control':'no-cache'}),timeout=45)
        actual=response.read()
        return {'path':p,'bytes':len(actual),'matches_commit':actual==expected,'sha256':hashlib.sha256(actual).hexdigest()}
    except Exception as error:return {'path':p,'matches_commit':False,'error':str(error)}
with concurrent.futures.ThreadPoolExecutor(max_workers=6) as pool:results=list(pool.map(check,paths+['index.html']))
record={'checked_utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'commit':commit,'generation':generation,'files':len(results),'matching':sum(x['matches_commit'] for x in results),'results':results}
output.parent.mkdir(parents=True,exist_ok=True);output.write_text(json.dumps(record,indent=2)+'\n',encoding='utf8')
print(json.dumps({k:v for k,v in record.items() if k!='results'}),flush=True)
if any(not x['matches_commit'] for x in results):
    print(json.dumps([x for x in results if not x['matches_commit']]),flush=True)
    raise SystemExit(1)

Session Restart Test

A test in the tool layers folder of Testcode that checks Session Restart. It is built from the element class (`Element`).

testtestcode / sandbox/capsules/tool-layers/session-restart.test.mjs · lines 1–76 of 76 · Entry point · pattern fixture (shared by 30 files)

What it does
It tests its inputs. Defines fixture, Element. Uses libraries node:test, node:assert/strict.
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Downstream impact
Used directly by 3 files: Codex Cartridges Workflow (testcode); Controls Layout Workflow (testcode); Offshore Route Workflow (testcode).
What it achieves
Defines `fixture` and `Element`.
Why it matters
Run by Codex Cartridges Workflow, Controls Layout Workflow and Offshore Route Workflow.
Application
testcode · sandbox/capsules/tool-layers · test
Uses
Session Restart (import), node:test, node:assert/strict
Used by
run by Codex Cartridges Workflow (workflow run), run by Controls Layout Workflow (workflow run), run by Offshore Route Workflow (workflow run)
Produces
fixture, Element
Defines here
fixture, Element
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/capsules/tool-layers/session-restart.test.mjs:1-76 · blob ab7a9ec8aa231381d5ceedc16106c030e30fc373 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: unknown
import test from 'node:test';
import assert from 'node:assert/strict';
import {mountSessionRestart} from './session-restart.js';

function fixture(entry='pinned-tool-entry') {
  let focused;
  class Element extends EventTarget {
    constructor(tag, doc) {super();this.tagName=tag;this.ownerDocument=doc;this.children=[];this.style={};this.dataset={};this.hidden=false;}
    setAttribute(name,value) {this[name]=value;}
    append(...nodes) {for(const node of nodes){node.parent=this;this.children.push(node);}}
    remove() {if(this.parent)this.parent.children=this.parent.children.filter(x=>x!==this);}
    focus() {focused=this;}
    click() {this.dispatchEvent(new Event('click'));}
  }
  const doc={createElement:tag=>new Element(tag,doc)};
  const layer=new Element('section',doc),bar=new Element('header',doc);
  const frame=new EventTarget(),otherFrame={src:'other-tool',state:{drawn:665}};
  let navigations=0,current='original-tool',starts=0;
  Object.defineProperty(frame,'src',{get:()=>current,set:value=>{current=value;navigations++;}});
  frame.addEventListener('tool-navigation-start',()=>starts++);
  const api=mountSessionRestart(layer,bar,frame,entry);
  const row=bar.children[0], [restart,cancel,note]=row.children;
  return {layer,bar,frame,otherFrame,api,restart,cancel,note,
    get navigations(){return navigations;},get starts(){return starts;},get focused(){return focused;}};
}

test('confirmation is explicit and reloads only the selected iframe once',()=>{
  const f=fixture();f.restart.click();
  assert.equal(f.navigations,0);assert.equal(f.restart.textContent,'Confirm restart');assert.equal(f.cancel.hidden,false);
  f.restart.click();assert.equal(f.navigations,1);assert.equal(f.starts,1);assert.equal(f.frame.src,'pinned-tool-entry');
  assert.deepEqual(f.otherFrame,{src:'other-tool',state:{drawn:665}});
  assert.equal(f.restart.textContent,'Restart tool');assert.equal(f.cancel.hidden,true);
  f.api.dispose();
});

test('cancel and layer dismissal disarm confirmation without navigation',()=>{
  const f=fixture();f.restart.click();f.cancel.click();
  assert.equal(f.navigations,0);assert.equal(f.focused,f.restart);assert.equal(f.cancel.hidden,true);
  f.restart.click();f.layer.dispatchEvent(new Event('tool-layer-dismissed'));
  assert.equal(f.restart.textContent,'Restart tool');assert.equal(f.note.textContent,'');
  f.restart.click();assert.equal(f.navigations,0);assert.equal(f.restart.textContent,'Confirm restart');
  f.api.dispose();
});

test('repeated recovery requests only arm confirmation and never reload',()=>{
  const f=fixture();f.api.requestConfirmation();f.api.requestConfirmation();
  assert.equal(f.navigations,0);assert.equal(f.starts,0);assert.equal(f.restart.textContent,'Confirm restart');
  f.cancel.click();f.api.requestConfirmation();assert.equal(f.navigations,0);
  f.restart.click();assert.equal(f.navigations,1);assert.equal(f.starts,1);
  f.api.dispose();
});

test('disposal removes session controls and detaches the layer listener',()=>{
  const f=fixture();f.api.requestConfirmation();f.api.dispose();
  assert.equal(f.bar.children.length,0);
  // A detached control is retained only by this fixture: no layer event may mutate it.
  const label=f.restart.textContent;f.layer.dispatchEvent(new Event('tool-layer-dismissed'));
  assert.equal(f.restart.textContent,label);assert.equal(f.navigations,0);
  f.restart.click();f.restart.click();f.cancel.click();
  assert.equal(f.navigations,0);assert.equal(f.starts,0);
});

test('restart resolves the current document only after confirmation and retains query/hash',()=>{
  let current='https://example.test/original';const f=fixture(()=>current);
  f.restart.click();current='https://example.test/linked?project=7#detail';f.restart.click();
  assert.equal(f.frame.src,current);assert.equal(f.navigations,1);
  f.api.requestConfirmation();f.layer.dispatchEvent(new Event('tool-document-changed'));
  f.restart.click();assert.equal(f.navigations,1);assert.equal(f.restart.textContent,'Confirm restart');
  f.api.dispose();
});

test('inaccessible linked page cannot fall back to restarting the original document',()=>{
  const f=fixture(()=>null);f.restart.click();f.restart.click();
  assert.equal(f.navigations,0);assert.equal(f.starts,0);assert.match(f.note.textContent,/cannot be restarted/);
  f.api.dispose();
});