In this section
- Test Power State Counterexample test · testcode / examples/test_power_state_counterexample.py lines 1–54
- Checkout other · testcode / lib/checkout.mjs lines 1–99
- Detector Proof other · testcode / sandbox/capsules/grid-compute/detector.proof.mjs lines 1–16
- Remove Test Screenshots test · testcode / sandbox/capsules/grid-compute/remove-test-screenshots.ps1 lines 1–28
- Compose Test test · testcode / sandbox/capsules/tool-layers/compose.test.mjs lines 1–83
- Dismissal Test test · testcode / sandbox/capsules/tool-layers/dismissal.test.mjs lines 1–21
- Focus Boundary Test test · testcode / sandbox/capsules/tool-layers/focus-boundary.test.mjs lines 1–33
- Navigation Test test · testcode / sandbox/capsules/tool-layers/navigation.test.mjs lines 1–53
- Ownership Test test · testcode / sandbox/capsules/tool-layers/ownership.test.mjs lines 1–33
- Readiness Test test · testcode / sandbox/capsules/tool-layers/readiness.test.mjs lines 1–50
- Recovery Test test · testcode / sandbox/capsules/tool-layers/recovery.test.mjs lines 1–10
- Source Scopes Test test · testcode / sandbox/capsules/tool-layers/source-scopes.test.mjs lines 1–90
- App Print Browser render · testcode / sandbox/tools/app-print.browser.cjs lines 1–50
- Arrival Diagnostic render · testcode / sandbox/tools/arrival-diagnostic.cjs lines 1–52
Test Power State Counterexample
A test in the examples folder of Testcode that checks Power State Counterexample. It is built from the source state counterexample tests class (`SourceStateCounterexampleTests`).
testtestcode / examples/test_power_state_counterexample.py · lines 1–54 of 54 · Entry point
- What it does
- It tests its inputs. Defines 6 functions or classes, including SourceStateCounterexampleTests, test_external_fault_while_other_feeder_is_locked_open, test_available_healthy_a_cannot_be_falsely_called_unavailable, test_no_upstream_voltage_has_no_specific_mismatch, test_open_breaker_blocks_simple_continuity_inference. Uses libraries unittest.
- Why it exists in the grid workflow
- Domain stage experimental (repository name word 'testcode'): 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
- Offline tests of a *conceptual* false-positive, not a PLC acceptance test.
- Why it matters
- Guards the behaviour of Power State Counterexample.
- Application
- testcode · examples · test
- Uses
- Power State Counterexample (import), unittest
- Used by
- none found
- Produces
- SourceStateCounterexampleTests
- Defines here
- SourceStateCounterexampleTests, test_external_fault_while_other_feeder_is_locked_open, test_available_healthy_a_cannot_be_falsely_called_unavailable, test_no_upstream_voltage_has_no_specific_mismatch, test_open_breaker_blocks_simple_continuity_inference, test_a_single_counterexample_invalidates_upstream_only_sufficiency
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 examples/test_power_state_counterexample.py:1-54 · blob ef9e0962a34d81c45afe328e2ff788b804c9d51a · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: unknown
"""Offline tests of a *conceptual* false-positive, not a PLC acceptance test.
Run: python -m unittest discover -s examples -p 'test_power_state_counterexample.py' -v
No network, dependencies, switchgear interfaces, or generators are accessed.
"""
import unittest
from power_state_counterexample import (
FeederObservation,
continuity_evidence,
mismatch,
upstream_voltage_only,
)
class SourceStateCounterexampleTests(unittest.TestCase):
def test_external_fault_while_other_feeder_is_locked_open(self):
active_a = FeederObservation(False, True, False)
disconnected_b = FeederObservation(True, False, False)
self.assertTrue(upstream_voltage_only(active_a, disconnected_b))
self.assertFalse(continuity_evidence(active_a))
self.assertFalse(continuity_evidence(disconnected_b))
self.assertTrue(mismatch(active_a, disconnected_b))
def test_available_healthy_a_cannot_be_falsely_called_unavailable(self):
healthy_a = FeederObservation(True, True, True)
isolated_b = FeederObservation(True, False, False)
self.assertTrue(upstream_voltage_only(healthy_a, isolated_b))
self.assertTrue(continuity_evidence(healthy_a))
self.assertFalse(mismatch(healthy_a, isolated_b))
def test_no_upstream_voltage_has_no_specific_mismatch(self):
dead_a = FeederObservation(False, True, False)
dead_b = FeederObservation(False, False, False)
self.assertFalse(upstream_voltage_only(dead_a, dead_b))
self.assertFalse(mismatch(dead_a, dead_b))
def test_open_breaker_blocks_simple_continuity_inference(self):
isolated = FeederObservation(True, False, False)
self.assertFalse(continuity_evidence(isolated))
def test_a_single_counterexample_invalidates_upstream_only_sufficiency(self):
# Counterexample to: "voltage upstream implies usable power at load".
a = FeederObservation(False, True, False)
b = FeederObservation(True, False, False)
self.assertTrue(upstream_voltage_only(a, b))
self.assertFalse(
continuity_evidence(a) or continuity_evidence(b)
)
if __name__ == "__main__":
unittest.main()Checkout
A JavaScript module in Testcode. It is built from the branch of helper (`branchOf`) and the has step (`has`).
othertestcode / lib/checkout.mjs · lines 1–99 of 99
- What it does
- It lists and searches its content. Defines branchOf, resolveCheckout, has. Uses libraries node:fs, node:child_process, node:path. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage experimental (repository name word 'testcode'): 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 2 files: Menu Map (testcode); Testcode — Run (testcode). Reached from 1 other entry point, including Testcode Workflow (testcode).
- What it achieves
- WHICH clone a gate read, decided explicitly and out loud.
- Why it matters
- Imported by Menu Map. Run by Testcode — Run.
- Application
- testcode · lib · JavaScript module
- Uses
- node:fs, node:child_process, node:path
- Used by
- imported by Menu Map (import), run by Testcode — Run (script call)
- Produces
- branchOf, resolveCheckout
- Defines here
- branchOf, resolveCheckout, has
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 lib/checkout.mjs:1-99 · blob 03209edb472fb8404a4ff0ad79ac38aea971d750 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: experimental · users: none · canonical: unknown
/* checkout.mjs — WHICH clone a gate read, decided explicitly and out loud.
*
* The defect this replaces, measured 2026-09-05: `node drivers/menu-map.mjs`
* run twice, twenty minutes apart, with nothing changed on disk, reported
*
* groups: 5 5/5 checks passed exit 0
* groups: 1 4/5 checks passed exit 1
*
* Both runs printed the surface as `gridatlas` and neither named the directory
* it had actually read. The cause was this line, in two files:
*
* candidates.find((c) => c.branch === 'main') || candidates[0]
*
* When no candidate answers `main` — because no clone is on main, or because
* `git branch --show-current` did not answer at all — the `||` silently takes
* `candidates[0]`, which is whatever `readdirSync` happened to return first.
* readdirSync order is not part of any contract, so the gate's verdict was not
* a property of the estate. Reproduced by making `git` unanswerable: identical
* command, identical bytes, exit 0 became exit 1.
*
* The rule here instead:
*
* 1. An explicitly declared path wins, and if it is not there that is a
* failure, not a search.
* 2. Otherwise candidates are enumerated in SORTED order and matched against
* a declared branch. Exactly one match is a result. Zero is a failure.
* More than one is a failure, because the gate cannot know which was meant.
* 3. A clone whose branch git would not tell us is UNKNOWN, never "not main".
* 4. There is no fallback. A gate that cannot say which bytes it read has
* not measured anything, and must say so rather than pick one.
*
* Every path out of here carries `dir`, `branch` and `why`, so the caller can
* print the bytes it read next to the verdict it reached.
*/
import { existsSync, readdirSync } from 'node:fs';
import { spawnSync } from 'node:child_process';
import path from 'node:path';
/* null means "git would not say", which is not the same as "not on main".
No `shell: true`: on Node 24 that raises DEP0190 on stderr, and this
runner's summary of a gate is the last line the gate printed — so a
deprecation warning from the runner's own plumbing was overwriting the
gate's verdict in the report. Measured: the `menus` row read
"(Use `node --trace-deprecation ...` to show where the warning was
created)" instead of "6/6 checks passed". */
export function branchOf(dir) {
const result = spawnSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'],
{ cwd: dir, encoding: 'utf8' });
if (result.error || result.status !== 0) return null;
const name = (result.stdout || '').trim();
return name && name !== 'HEAD' ? name : null;
}
/* parent directory the clones sit in
base clone name, e.g. 'gridatlas'; siblings are `${base}-*`
declared an explicit path that ends the search when present
branch the branch a candidate must be on to be selected
mustContain relative paths a candidate must actually have, so an empty
directory of the right name cannot be chosen */
export function resolveCheckout({ parent, base, declared = null, branch = 'main', mustContain = [] }) {
const has = (dir) => mustContain.every((rel) => existsSync(path.join(dir, ...rel.split('/'))));
if (declared) {
const dir = path.resolve(parent, declared);
if (!existsSync(dir)) {
return { ok: false, dir, branch: null, candidates: [], why: `declared checkout ${declared} is not present` };
}
if (!has(dir)) {
return { ok: false, dir, branch: branchOf(dir), candidates: [], why: `declared checkout ${declared} does not carry ${mustContain.join(', ')}` };
}
return { ok: true, dir, branch: branchOf(dir), candidates: [], why: `declared in the registry as ${declared}` };
}
let names = [];
try { names = readdirSync(parent); } catch { names = []; }
const candidates = names
.filter((n) => n === base || n.startsWith(`${base}-`))
.sort() /* deterministic, unlike readdir order */
.map((n) => path.join(parent, n))
.filter((dir) => has(dir))
.map((dir) => ({ dir, branch: branchOf(dir) }));
const shown = candidates.map((c) => `${path.basename(c.dir)}=${c.branch || 'UNKNOWN'}`);
const onBranch = candidates.filter((c) => c.branch === branch);
if (onBranch.length === 1) {
return { ok: true, dir: onBranch[0].dir, branch, candidates: shown, why: `the one ${base} checkout on ${branch}` };
}
if (onBranch.length === 0) {
return {
ok: false, dir: null, branch: null, candidates: shown,
why: `no ${base} checkout is on ${branch} — candidates: ${shown.join(', ') || 'none'}`
};
}
return {
ok: false, dir: null, branch: null, candidates: shown,
why: `${onBranch.length} ${base} checkouts are on ${branch}, so which bytes to read is ambiguous: ${onBranch.map((c) => path.basename(c.dir)).join(', ')}`
};
}Detector Proof
A JavaScript module in the grid compute folder of Testcode covering the Renewable Energy Planning Database (REPD) register.
othertestcode / sandbox/capsules/grid-compute/detector.proof.mjs · lines 1–16 of 16 · Not reached from any entry point (candidate for review)
- What it does
- Uses libraries 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. Domain terms in the code: the REPD register.
- 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
- testcode · sandbox/capsules/grid-compute · JavaScript module
- Uses
- Detector (import), 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
- testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/capsules/grid-compute/detector.proof.mjs:1-16 · blob 410eff37cf86a20e4729d1c9535c108c670d7d8a · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: unknown · effects: none found · domain stage: experimental · users: none · canonical: unreached_review
import assert from 'node:assert/strict';
import { assess } from './detector.mjs';
const c={kind:'repd',entity_id:'2484',has_location:true,longitude:2.55,latitude:52.62};
const row={node_id:'grid',lon:1.6,lat:52.2,km:77};
const r={record:{entity:{kind:'repd',id:'2484'},location:{lon:2.55,lat:52.62},operation:'Atlas selectAt / nearest-grid',status:'completed',events:[{status:'started'},{status:'completed'}],measurements:[row]}};
const shown={sourceLineCount:1,renderedLineCount:1};const backend={status:'completed',measurements:[row]};
assert.equal(assess(c,[r],shown,backend).outcome,'PASS');
assert.equal(assess(c,[],shown,backend).outcome,'NO_RECEIPT');
assert.equal(assess(c,[{record:{...r.record,events:[],status:'requested'}}],shown,backend).outcome,'ENGINE_NOT_FIRED');
assert.equal(assess(c,[r],{sourceLineCount:0,renderedLineCount:0},backend).outcome,'COMPUTED_BUT_NOT_DRAWN');
assert.equal(assess(c,[r],{sourceLineCount:1,renderedLineCount:0},backend).outcome,'COMPUTED_BUT_NOT_DRAWN');
assert.equal(assess(c,[{record:{...r.record,entity:{kind:'repd',id:'different'}}}],shown,backend).outcome,'WRONG_ENTITY');
assert.equal(assess(c,[{record:{...r.record,location:{lon:0,lat:0}}}],shown,backend).outcome,'WRONG_OR_UNVERIFIED_LOCATION');
assert.equal(assess(c,[{record:{...r.record,measurements:[{...row,km:99}]}}],shown,backend).outcome,'BACKEND_RESULT_MISMATCH');
assert.equal(assess(c,[r,{record:{...r.record,status:'requested',events:[]}}],shown,backend).outcome,'ENGINE_NOT_FIRED');
console.log('9 detector checks passed: never invoked, stale, wrong entity/location/distance, and computed-but-invisible cases rejected.');Remove Test Screenshots
A PowerShell script in the grid compute folder of Testcode.
testtestcode / sandbox/capsules/grid-compute/remove-test-screenshots.ps1 · lines 1–28 of 28 · Not reached from any entry point (candidate for review)
- What it does
- It tests its inputs. Side effects: 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.
- 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
- testcode · sandbox/capsules/grid-compute · PowerShell script
- Uses
- none found
- 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/grid-compute/remove-test-screenshots.ps1:1-28 · blob 959922a6de87082c6137c58ab22dd557229c0320 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: unknown · effects: process · domain stage: experimental · users: none · canonical: unreached_review
param([switch]$Delete)
$testImageRoots = @(
'C:\Users\vikra\OneDrive\Documents\GitHub\testcode\sandbox',
'C:\Users\vikra\testcode-source-publication\sandbox',
'C:\Users\vikra\globalgrid-testcode-publication\testcode'
)
$inventoryFile = 'C:\Users\vikra\OneDrive\Documents\GitHub\testcode\screenshots\DELETE-BUILD-IMAGE-INVENTORY.json'
if (-not $Delete) {
$testImages = foreach ($testImageRoot in $testImageRoots) {
Get-ChildItem -LiteralPath $testImageRoot -File -Recurse | Where-Object {
$_.Extension -in '.png','.jpg','.jpeg','.webp' -and $_.FullName -match '\\(evidence[^\\]*|compatibility[^\\]*|screenshots)\\'
} | Select-Object FullName,Length
}
$testImages | ConvertTo-Json | Set-Content -LiteralPath $inventoryFile
Write-Output ('Inventoried ' + @($testImages).Count + ' generated test images')
exit
}
$testImages = Get-Content -LiteralPath $inventoryFile -Raw | ConvertFrom-Json
foreach ($testImage in $testImages) {
$testImagePath = [IO.Path]::GetFullPath($testImage.FullName)
$insideApprovedRoot = $false
foreach ($testImageRoot in $testImageRoots) {
if ($testImagePath.StartsWith($testImageRoot + '\',[StringComparison]::OrdinalIgnoreCase)) { $insideApprovedRoot = $true }
}
if (-not $insideApprovedRoot -or [IO.Path]::GetExtension($testImagePath) -notin '.png','.jpg','.jpeg','.webp' -or $testImagePath -notmatch '\\(evidence[^\\]*|compatibility[^\\]*|screenshots)\\') { throw 'Invalid screenshot target' }
Remove-Item -LiteralPath $testImagePath
}
Write-Output ('Deleted ' + @($testImages).Count + ' generated test images')Compose Test
A test in the tool layers folder of Testcode that checks Compose, using SHA-256. It is built from the commit step (`commit`).
testtestcode / sandbox/capsules/tool-layers/compose.test.mjs · lines 1–83 of 83 · Entry point · pattern commit (shared by 8 files)
- What it does
- It tests its inputs. Defines digest, fixture, git, commit. Uses libraries node:test, node:assert/strict, node:fs/promises, 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.
- Downstream impact
- Used directly by 3 files: Codex Cartridges Workflow (testcode); Controls Layout Workflow (testcode); Offshore Route Workflow (testcode).
- What it achieves
- Defines `digest`, `fixture`, `git` and 1 more.
- Why it matters
- Run by Codex Cartridges Workflow, Controls Layout Workflow and Offshore Route Workflow.
- Application
- testcode · sandbox/capsules/tool-layers · test
- Uses
- Compose (script call), node:test, node:assert/strict, node:fs/promises, node:child_process, node:crypto, node:path, node:os
- Used by
- run by Codex Cartridges Workflow (workflow run), run by Controls Layout Workflow (workflow run), run by Offshore Route Workflow (workflow run)
- Produces
- digest, fixture, git, commit
- Defines here
- digest, fixture, git, commit
- 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/compose.test.mjs:1-83 · blob 6ec71b7ab045b35fa1a3b205f14f52115a54dac7 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem, process · domain stage: experimental · users: none · canonical: unknown
import test from 'node:test';
import assert from 'node:assert/strict';
import {mkdtemp, mkdir, writeFile, readFile, rm, readdir} from 'node:fs/promises';
import {execFileSync} from 'node:child_process';
import {createHash} from 'node:crypto';
import path from 'node:path';
import os from 'node:os';
import {composeToolOwner} from './compose.mjs';
const RELEASE = '202609051855';
const digest = bytes => createHash('sha256').update(bytes).digest('hex');
async function fixture(t, entries = [['index.html', '<h1>Original GIS</h1>']]) {
const temp = await mkdtemp(path.join(os.tmpdir(), 'tool-owner-proof-'));
t.after(async () => {
const resolved = path.resolve(temp);
if (path.dirname(resolved) !== path.resolve(os.tmpdir()) || !path.basename(resolved).startsWith('tool-owner-proof-')) throw Error('Refusing cleanup outside the owned fixture');
await rm(resolved, {recursive: true, force: true});
});
const owner = path.join(temp, 'owner'), target = path.join(temp, 'candidate');
await mkdir(owner); await mkdir(target);
const git = (...args) => execFileSync('git', ['-C', owner, ...args], {encoding:'utf8', windowsHide:true, stdio:['ignore','pipe','pipe']}).trim();
git('init', '--quiet'); git('remote', 'add', 'origin', 'https://github.com/example/fixture-owner.git');
await writeFile(path.join(owner, '.gitattributes'), '* -text\n');
const release = path.join(owner, 'releases', RELEASE);
const files = [];
for (const [name, text] of entries) {
const bytes = Buffer.from(text);
const file = path.join(release, name);
await mkdir(path.dirname(file), {recursive:true}); await writeFile(file, bytes);
files.push({path:name, bytes:bytes.length, sha256:digest(bytes)});
}
const manifest = {schema:'globalgrid.original-runtime.v1',generation:RELEASE,
applications:[{id:'fixture',entry:entries[0][0]}],files};
const commit = async () => {
await writeFile(path.join(release, 'manifest.json'), JSON.stringify(manifest));
git('add', '--', '.');
git('-c','user.name=Fixture','-c','user.email=fixture@example.invalid','commit','--quiet','-m','fixture');
return git('rev-parse', 'HEAD');
};
return {owner,target,release,manifest,commit};
}
test('only the pinned committed bytes are copied despite a dirty producer worktree', async t => {
const f = await fixture(t); const revision = await f.commit();
await writeFile(path.join(f.release, 'index.html'), '<h1>Uncommitted change</h1>');
const receipt = await composeToolOwner(f.target, f.owner, revision, RELEASE);
assert.equal(await readFile(path.join(f.target,'layer-apps','index.html'),'utf8'), '<h1>Original GIS</h1>');
assert.equal(receipt.commit, revision);
assert.equal(receipt.manifestSha256.length, 64);
});
test('short revisions and floating branch references are refused', async t => {
const f = await fixture(t); await f.commit();
await assert.rejects(composeToolOwner(f.target,f.owner,'main',RELEASE), /Full owner commit/);
await assert.rejects(composeToolOwner(f.target,f.owner,'abc1234',RELEASE), /Full owner commit/);
});
test('wrong generation in a committed manifest is refused', async t => {
const f = await fixture(t); f.manifest.generation='202609051623';
const revision=await f.commit();
await assert.rejects(composeToolOwner(f.target,f.owner,revision,RELEASE), /Invalid producer manifest/);
});
test('a committed hash mismatch is refused', async t => {
const f = await fixture(t); f.manifest.files[0].sha256='0'.repeat(64);
const revision=await f.commit();
await assert.rejects(composeToolOwner(f.target,f.owner,revision,RELEASE), /Producer mismatch/);
});
test('parent traversal cannot escape the candidate', async t => {
const f = await fixture(t); f.manifest.files[0].path='../escape.html';
const revision=await f.commit();
await assert.rejects(composeToolOwner(f.target,f.owner,revision,RELEASE), /Unsafe producer path/);
assert.deepEqual(await readdir(f.target), []);
});
test('a bad later member is rejected before any candidate file is written', async t => {
const f = await fixture(t, [['first.html','<p>First</p>'],['second.js','const second = 2;']]);
f.manifest.files[1].sha256='0'.repeat(64); const revision=await f.commit();
await assert.rejects(composeToolOwner(f.target,f.owner,revision,RELEASE), /Producer mismatch/);
assert.deepEqual(await readdir(f.target), [], 'Preflight all producer members before creating a partial candidate');
});Dismissal Test
A test in the tool layers folder of Testcode that checks Dismissal.
testtestcode / sandbox/capsules/tool-layers/dismissal.test.mjs · lines 1–21 of 21 · Entry point
- What it does
- It tests its inputs. Defines key. 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 `key`.
- Why it matters
- Run by Codex Cartridges Workflow, Controls Layout Workflow and Offshore Route Workflow.
- Application
- testcode · sandbox/capsules/tool-layers · test
- Uses
- Dismissal (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
- key
- Defines here
- key
- 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/dismissal.test.mjs:1-21 · blob 1908c8b3619f990472f0dcf43de5bdec71d9ef69 · 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 {bindLayerDismissal} from './dismissal.js';
const key = (name='Escape') => {const event=new Event('keydown',{cancelable:true});Object.defineProperty(event,'key',{value:name});return event;};
test('parent and child Escape close only visible layers and cleanup removes listeners',()=>{
const layer=new EventTarget();layer.style={display:'flex'};
const frame=new EventTarget();frame.contentDocument=new EventTarget();let count=0;
const dispose=bindLayerDismissal(layer,frame,()=>count++);
frame.dispatchEvent(new Event('load'));layer.dispatchEvent(key('Enter'));assert.equal(count,0);
frame.contentDocument.dispatchEvent(key());assert.equal(count,1);
layer.style.display='none';layer.dispatchEvent(key());assert.equal(count,1);
layer.style.display='flex';const consumed=key();consumed.preventDefault();layer.dispatchEvent(consumed);assert.equal(count,1);
dispose();layer.dispatchEvent(key());frame.contentDocument.dispatchEvent(key());assert.equal(count,1);
});
test('iframe reload detaches its previous document',()=>{
const layer=new EventTarget();layer.style={display:'flex'};const frame=new EventTarget();
const old=new EventTarget();frame.contentDocument=old;let count=0;
const dispose=bindLayerDismissal(layer,frame,()=>count++);frame.dispatchEvent(new Event('load'));
frame.contentDocument=new EventTarget();frame.dispatchEvent(new Event('load'));old.dispatchEvent(key());assert.equal(count,0);
frame.contentDocument.dispatchEvent(key());assert.equal(count,1);dispose();
});Focus Boundary Test
A test in the tool layers folder of Testcode that checks Focus Boundary.
testtestcode / sandbox/capsules/tool-layers/focus-boundary.test.mjs · lines 1–33 of 33 · Entry point · pattern press (shared by 6 files)
- What it does
- It tests its inputs. Defines node, press, node, press. Uses libraries node:test, node:assert/strict. Side effects: changes the web page (DOM).
- 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 `node`, `press`, `node` and 1 more.
- Why it matters
- Run by Codex Cartridges Workflow, Controls Layout Workflow and Offshore Route Workflow.
- Application
- testcode · sandbox/capsules/tool-layers · test
- Uses
- Focus Boundary (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
- node, press, node, press
- Defines here
- node, press, node, press
- 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/focus-boundary.test.mjs:1-33 · blob 30a72e94eb86e6feb70324aa178274c9cfae3c57 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: unknown
import test from 'node:test';
import assert from 'node:assert/strict';
import {bindFocusBoundary} from './focus-boundary.js';
test('Tab wraps at iframe boundaries and leaves internal traversal alone',()=>{
let focused;
const node=()=>({tabIndex:0,disabled:false,closest:()=>null,getClientRects:()=>[{}],focus(){focused=this;}});
const close=node(), first=node(), middle=node(), last=node(), hidden={...node(),getClientRects:()=>[]};
const child=new EventTarget();child.querySelectorAll=()=>[first,middle,last,hidden];child.defaultView={getComputedStyle:()=>({visibility:'visible'})};
const layer=new EventTarget();layer.style={display:'flex'};const frame=new EventTarget();frame.contentDocument=child;
const dispose=bindFocusBoundary(layer,frame,close);frame.dispatchEvent(new Event('load'));
const press=(target,shiftKey=false)=>{const e=new Event('keydown',{cancelable:true});Object.defineProperties(e,{key:{value:'Tab'},target:{value:target},shiftKey:{value:shiftKey}});layer.dispatchEvent(e);return e;};
assert.ok(press(close).defaultPrevented);assert.equal(focused,first);
press(close,true);assert.equal(focused,last);
press(last);assert.equal(focused,close);
press(first,true);assert.equal(focused,close);
assert.equal(press(middle).defaultPrevented,false);
layer.style.display='none';assert.equal(press(close).defaultPrevented,false);
dispose();layer.style.display='flex';assert.equal(press(close).defaultPrevented,false);
});
test('multiple header actions retain native order and wrap through currently visible buttons',()=>{
let focused;const doc={defaultView:{getComputedStyle:()=>({visibility:'visible'})}};
const node=()=>({tabIndex:0,disabled:false,hidden:false,ownerDocument:doc,closest:()=>null,getClientRects(){return this.hidden?[]:[{}];},focus(){focused=this;}});
const close=node(),restart=node(),cancel=node(),first=node(),last=node();
const child=new EventTarget();child.querySelectorAll=()=>[first,last];child.defaultView=doc.defaultView;
const layer=new EventTarget();layer.style={display:'flex'};layer.querySelectorAll=()=>[close,restart,cancel];
const frame=new EventTarget();frame.contentDocument=child;const dispose=bindFocusBoundary(layer,frame,close);frame.dispatchEvent(new Event('load'));
const press=(target,shiftKey=false)=>{const e=new Event('keydown',{cancelable:true});Object.defineProperties(e,{key:{value:'Tab'},target:{value:target},shiftKey:{value:shiftKey}});layer.dispatchEvent(e);return e;};
assert.equal(press(close).defaultPrevented,false);assert.equal(press(restart).defaultPrevented,false);
press(cancel);assert.equal(focused,first);press(first,true);assert.equal(focused,cancel);
cancel.hidden=true;press(first,true);assert.equal(focused,restart);press(restart);assert.equal(focused,first);
press(last);assert.equal(focused,close);dispose();
});Navigation Test
A test in the tool layers folder of Testcode that checks Navigation using data from globalgrid2050.com. It is built from the load step (`load`).
testtestcode / sandbox/capsules/tool-layers/navigation.test.mjs · lines 1–53 of 53 · Entry point · pattern entry (shared by 5 files)
- What it does
- It tests its inputs. Defines entry, href, fixture, load. Uses libraries node:test, node:assert/strict. Side effects: changes the web page (DOM).
- 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 tool-layers.json.
- Downstream impact
- Used directly by 3 files: Codex Cartridges Workflow (testcode); Controls Layout Workflow (testcode); Offshore Route Workflow (testcode).
- What it achieves
- Defines `entry`, `href`, `fixture` and 1 more.
- Why it matters
- Run by Codex Cartridges Workflow, Controls Layout Workflow and Offshore Route Workflow.
- Application
- testcode · sandbox/capsules/tool-layers · test
- Uses
- Navigation (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
- entry, href, fixture, load
- Defines here
- entry, href, fixture, load
- 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/navigation.test.mjs:1-53 · blob 44e0df52b741fbc1214204caf6c51aa7adba86ba · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: unknown
import test from 'node:test';
import assert from 'node:assert/strict';
import {resolveToolDestination,bindToolNavigation} from './navigation.js';
const base='https://globalgrid2050.com/testcode/202609052011/atlas/tool-layers.json';
const entry=(id,title,char)=>({id,title,entry:'../layer-apps/solar-bess-topology-v7/'+id+'/index.html',owner:{repository:'Ventusltd/'+id,commit:char.repeat(40),release:'202609052008',manifestSha256:char.repeat(64)}});
const registry=[entry('gis-sld-financial-sandbox','GIS SLD','a'),entry('module-layout','Module Layout','b'),entry('dc-ac-lv-topology-review','DC/AC LV Topology Review','c')];
const href=tool=>new URL(tool.entry,base).href;
function fixture() {
const layer=new EventTarget();layer.dataset={};layer.setAttribute=(k,v)=>{layer[k]=v;};
const frame=new EventTarget();frame.src=href(registry[0]);frame.contentWindow={location:{href:frame.src}};
frame.contentDocument={readyState:'complete',querySelector:s=>s==='#btn_draw'?{}:null};
const title={textContent:''},status={dataset:{},setAttribute(){},textContent:''};
let changed=0;layer.addEventListener('tool-document-changed',()=>changed++);
const dispose=bindToolNavigation(layer,frame,title,status,registry,base,registry[0]);
const load=(url,doc=frame.contentDocument)=>{frame.contentWindow={location:{href:url}};frame.contentDocument=doc;frame.dispatchEvent(new Event('load'));};
return {layer,frame,title,status,dispose,load,get changed(){return changed;}};
}
test('resolution preserves query/hash semantics and rejects a different origin or unknown path',()=>{
assert.equal(resolveToolDestination(href(registry[1])+'?project=5#layout',registry,base),registry[1]);
assert.equal(resolveToolDestination(href(registry[1]).replace('globalgrid2050.com','other.example'),registry,base),null);
assert.equal(resolveToolDestination('https://globalgrid2050.com/unknown',registry,base),null);
});
test('actual child location replaces stale frame src and rebinds title, owner and readiness',()=>{
const f=fixture();try {
f.load(href(registry[0]));assert.equal(f.layer.dataset.currentTool,registry[0].id);
const target=href(registry[1])+'?same=1#layout';
f.load(target,{readyState:'complete',querySelector:s=>s==='#ml_status'?{textContent:'Ready. Draw at map centre or pick a site.'}:null});
assert.equal(f.frame.src,href(registry[0]));assert.equal(f.frame.contentWindow.location.href,target);
assert.equal(f.title.textContent,'Module Layout');assert.equal(f.frame.title,'Module Layout');assert.equal(f.layer['aria-label'],'Module Layout');
assert.equal(f.layer.dataset.currentOwner,JSON.stringify(registry[1].owner));assert.equal(f.status.dataset.toolReadiness,'module-layout');
assert.equal(f.status.dataset.drawing,'ready');assert.equal(f.changed,2);
f.load(href(registry[2]));assert.equal(f.title.textContent,'DC/AC LV Topology Review');assert.equal(f.status.dataset.drawing,'unreported');
assert.equal(f.status.dataset.interface,'unreported');assert.equal(f.status.textContent,'Page loaded; drawing readiness unreported');
} finally {f.dispose();}
});
test('unknown and inaccessible documents clear stale pins without being labelled ready',()=>{
const f=fixture();try {
f.load(href(registry[0]));f.status.dataset.timedOut='true';
f.load('https://globalgrid2050.com/linked-page');
assert.equal(f.title.textContent,'Linked page');assert.equal(f.layer.dataset.currentOwner,undefined);assert.equal(f.status.dataset.toolReadiness,undefined);assert.equal(f.status.dataset.interface,'unbound');assert.equal(f.status.dataset.timedOut,undefined);
Object.defineProperty(f.frame,'contentWindow',{configurable:true,get(){throw Error('cross-origin');}});
f.frame.dispatchEvent(new Event('load'));assert.equal(f.status.dataset.interface,'unbound');assert.equal(f.layer.dataset.currentTool,undefined);
} finally {f.dispose();}
});
test('disposal removes navigation listener and leaves later load events untouched',()=>{
const f=fixture();f.load(href(registry[0]));const title=f.title.textContent,count=f.changed;f.dispose();
f.load(href(registry[2]));assert.equal(f.title.textContent,title);assert.equal(f.changed,count);
});Ownership Test
A test in the tool layers folder of Testcode that checks Ownership.
testtestcode / sandbox/capsules/tool-layers/ownership.test.mjs · lines 1–33 of 33 · Entry point
- What it does
- It tests cables. 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. Domain terms in the code: cables.
- Downstream impact
- Used directly by 3 files: Codex Cartridges Workflow (testcode); Controls Layout Workflow (testcode); Offshore Route Workflow (testcode).
- What it achieves
- No statement of purpose was found in the file, a README line naming it, or its name.
- Why it matters
- Run by Codex Cartridges Workflow, Controls Layout Workflow and Offshore Route Workflow.
- Application
- testcode · sandbox/capsules/tool-layers · test
- Uses
- Ownership (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
- 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/tool-layers/ownership.test.mjs:1-33 · blob 4b7a50a9e7476934166a14c4b99c937f20884599 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: unknown · effects: none found · domain stage: experimental · users: none · canonical: unknown
import test from 'node:test';
import assert from 'node:assert/strict';
import {mergeToolOwnership} from './ownership.mjs';
const old={repository:'layout',commit:'old',release:'1',manifestSha256:'a',applications:[{id:'cable',entry:'cable/index.html'},{id:'module',entry:'module/index.html'}]};
const next={repository:'cable',commit:'new',release:'2',manifestSha256:'b',applications:[{id:'cable',entry:'cable/index.html'}]};
const previous={owners:[old],tools:old.applications.map(app=>({...app,title:app.id}))};
test('migrate cable only; preserve module owner and historical bundle',()=>{
const result=mergeToolOwnership(previous,next,next.applications);
assert.equal(result.tools.find(x=>x.id==='cable').owner.repository,'cable');
assert.equal(result.tools.find(x=>x.id==='module').owner.repository,'layout');
assert.equal(result.owners.length,2);assert.equal(previous.tools[0].owner,undefined);
});
test('explicit provenance survives subsequent releases',()=>{
const first=mergeToolOwnership(previous,next,next.applications);
const second=mergeToolOwnership(first,{...next,commit:'newer'},next.applications);
assert.equal(second.tools.find(x=>x.id==='cable').owner.commit,'newer');
assert.equal(second.tools.find(x=>x.id==='module').owner.commit,'old');
});
test('ambiguous unpinned historical ownership is rejected',()=>{
assert.throws(()=>mergeToolOwnership({...previous,owners:[old,next]},next,next.applications),/Ambiguous/);
});
test('partial update of one producer retains the older manifest for untouched tools',()=>{
const historical={...old,applications:[...old.applications,{id:'dc',entry:'dc/index.html'}]};
const seed={owners:[historical],tools:historical.applications.map(app=>({...app,title:app.id}))};
const first=mergeToolOwnership(seed,next,next.applications);
const updated={...old,commit:'layout-new',release:'3',manifestSha256:'c',applications:[old.applications[1]]};
const result=mergeToolOwnership(first,updated,updated.applications);
assert.equal(result.tools.find(x=>x.id==='module').owner.commit,'layout-new');
assert.equal(result.tools.find(x=>x.id==='dc').owner.commit,'old');
assert.ok(result.owners.some(x=>x.repository==='layout' && x.commit==='old'));
assert.ok(result.owners.some(x=>x.repository==='layout' && x.commit==='layout-new'));
assert.equal(result.tools.find(x=>x.id==='cable').owner.commit,'new');
});Readiness Test
A test in the tool layers folder of Testcode that checks Readiness.
testtestcode / sandbox/capsules/tool-layers/readiness.test.mjs · lines 1–50 of 50 · Entry point
- What it does
- It tests cables. Uses libraries node:test, node:assert/strict. Side effects: changes the web page (DOM).
- 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. Domain terms in the code: cables.
- Downstream impact
- Used directly by 3 files: Codex Cartridges Workflow (testcode); Controls Layout Workflow (testcode); Offshore Route Workflow (testcode).
- What it achieves
- No statement of purpose was found in the file, a README line naming it, or its name.
- Why it matters
- Run by Codex Cartridges Workflow, Controls Layout Workflow and Offshore Route Workflow.
- Application
- testcode · sandbox/capsules/tool-layers · test
- Uses
- Readiness (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
- 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/tool-layers/readiness.test.mjs:1-50 · blob 1d36ea927460c20623c5d856bda7553f7e7895ca · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: unknown
import test from 'node:test';
import assert from 'node:assert/strict';
import {inspectToolReadiness,observeToolReadiness} from './readiness.js';
test('module DOM completion does not masquerade as map readiness',()=>{
const doc={readyState:'complete',querySelector:()=>({textContent:'Loading'})};
assert.equal(inspectToolReadiness('module-layout',doc).drawing,'pending');
doc.querySelector=()=>({textContent:'Ready. Draw at map centre or pick a site.'});
assert.equal(inspectToolReadiness('module-layout',doc).drawing,'ready');
});
test('prefilled Cable text is insufficient until all three canvases draw',()=>{
let alpha=0;const canvas={width:64,height:8,getContext:()=>({getImageData:()=>({data:Array.from({length:2048},(_,i)=>i%4===3?alpha:(i%4===0?Math.floor(i/64)%2*255:0))})})};
const doc={readyState:'complete',querySelector:()=>({}),querySelectorAll:()=>['formation_canvas','trench_canvas','bend_canvas'].map(id=>({...canvas,id}))};
assert.equal(inspectToolReadiness('cable-geometry-visualiser',doc).drawing,'pending');
alpha=255;assert.equal(inspectToolReadiness('cable-geometry-visualiser',doc).drawing,'ready');
});
test('GIS reports interface separately and never infers map readiness',()=>{
assert.deepEqual(inspectToolReadiness('gis-sld-financial-sandbox',{readyState:'complete',querySelector:()=>({})}),{interface:'loaded',drawing:'unreported',label:'Interface loaded'});
assert.equal(inspectToolReadiness('module-layout',{readyState:'loading'}).interface,'loading');
});
test('never-loading iframe times out and a later successful load clears stale timeout',async()=>{
const frame=new EventTarget();frame.contentDocument={readyState:'complete',querySelector:()=>({})};
const status={dataset:{},setAttribute(){},textContent:''};
const dispose=observeToolReadiness({id:'gis-sld-financial-sandbox'},frame,status,{timeout:5,interval:1});
await new Promise(resolve=>setTimeout(resolve,20));assert.equal(status.dataset.timedOut,'true');
frame.dispatchEvent(new Event('load'));assert.equal(status.dataset.timedOut,undefined);assert.equal(status.dataset.interface,'loaded');dispose();
});
for(const mode of ['null','throw'])test('external iframe '+mode+' access never becomes a loading timeout',async()=>{
const frame=new EventTarget();Object.defineProperty(frame,'contentDocument',{get(){if(mode==='throw')throw Error('cross origin');return null;}});
const status={dataset:{},setAttribute(){},textContent:''};
const dispose=observeToolReadiness({id:'module-layout'},frame,status,{timeout:5,interval:1});frame.dispatchEvent(new Event('load'));
await new Promise(resolve=>setTimeout(resolve,20));assert.equal(status.dataset.interface,'unavailable');assert.equal(status.dataset.timedOut,undefined);dispose();
});
test('observed Ready transition is retained when a subsequent draw changes the status',()=>{
const original=globalThis.MutationObserver;let observer;
globalThis.MutationObserver=class {constructor(callback){this.callback=callback;observer=this;}observe(){}disconnect(){this.disconnected=true;}notify(){if(!this.disconnected)this.callback();}};
try {
const marker={textContent:'Loading'};const frame=new EventTarget();frame.contentDocument={readyState:'complete',querySelector:()=>marker};
const status={dataset:{},setAttribute(){},textContent:''};const dispose=observeToolReadiness({id:'module-layout'},frame,status,{timeout:500,interval:200});frame.dispatchEvent(new Event('load'));
assert.equal(status.dataset.drawing,'pending');marker.textContent='Ready. Draw at map centre or pick a site.';observer.notify();assert.equal(status.dataset.drawing,'ready');
marker.textContent='Rendered120 physical modules';observer.notify();assert.equal(status.dataset.drawing,'ready');dispose();
} finally {globalThis.MutationObserver=original;}
});
test('a module that never reports Ready cannot gain readiness from rendered text',async()=>{
const frame=new EventTarget();frame.contentDocument={readyState:'complete',querySelector:()=>({textContent:'Rendered120 physical modules'})};
const status={dataset:{},setAttribute(){},textContent:''};const dispose=observeToolReadiness({id:'module-layout'},frame,status,{timeout:5,interval:1});frame.dispatchEvent(new Event('load'));
await new Promise(resolve=>setTimeout(resolve,20));assert.equal(status.dataset.drawing,'pending');assert.equal(status.dataset.timedOut,'true');dispose();
});Recovery Test
A test in the tool layers folder of Testcode that checks Recovery.
testtestcode / sandbox/capsules/tool-layers/recovery.test.mjs · lines 1–10 of 10 · Entry point
- What it does
- It tests its inputs. 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
- No statement of purpose was found in the file, a README line naming it, or its name.
- Why it matters
- Run by Codex Cartridges Workflow, Controls Layout Workflow and Offshore Route Workflow.
- Application
- testcode · sandbox/capsules/tool-layers · test
- Uses
- Recovery (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
- 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/tool-layers/recovery.test.mjs:1-10 · blob 67244615c3e25d605b92d4959d9b7b3be471db1d · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: unknown · effects: none found · domain stage: experimental · users: none · canonical: unknown
import test from 'node:test';
import assert from 'node:assert/strict';
import {shouldOfferRecovery} from './recovery.js';
test('missing app and explicit timeout offer retry; external navigation and unknown map do not',()=>{
assert.equal(shouldOfferRecovery({interface:'unrecognised'}),true);
assert.equal(shouldOfferRecovery({interface:'loading',timedOut:'true'}),true);
assert.equal(shouldOfferRecovery({interface:'loaded',drawing:'unreported'}),false);
assert.equal(shouldOfferRecovery({interface:'unavailable',drawing:'unreported'}),false);
assert.equal(shouldOfferRecovery({interface:'loaded',drawing:'ready'}),false);
});Source Scopes Test
A test in the tool layers folder of Testcode that checks Source Scopes, using SHA-256.
testtestcode / sandbox/capsules/tool-layers/source-scopes.test.mjs · lines 1–90 of 90 · Entry point · pattern fixture (shared by 30 files)
- What it does
- It tests its inputs. Defines 7 functions or classes, including sha, fixture, pin, readCandidate, run. Uses libraries node:test, node:assert/strict, node:crypto.
- 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: "`source-scopes.mjs` builds `layer-source-scopes.json` as a separate per-tool inventory."
- Inputs & outputs
- In: GeoJSON file grid.geojson; JSON file shared.json.
- Downstream impact
- Used directly by 3 files: Codex Cartridges Workflow (testcode); Controls Layout Workflow (testcode); Offshore Route Workflow (testcode).
- What it achieves
- It reads candidate (`readCandidate`) and is built from the sha step (`sha`) and the fixture step (`fixture`). The README says: `source-scopes.mjs` builds `layer-source-scopes.json` as a separate per-tool inventory.
- Why it matters
- Run by Codex Cartridges Workflow, Controls Layout Workflow and Offshore Route Workflow.
- Application
- testcode · sandbox/capsules/tool-layers · test
- Uses
- Source Scopes (import), node:test, node:assert/strict, node:crypto
- Used by
- run by Codex Cartridges Workflow (workflow run), run by Controls Layout Workflow (workflow run), run by Offshore Route Workflow (workflow run)
- Produces
- sha, fixture, pin, readCandidate, run, derivedFixture, run
- Defines here
- sha, fixture, pin, readCandidate, run, derivedFixture, run
- 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/source-scopes.test.mjs:1-90 · blob 968f2e9451200c6e44957df4eb6b0a4a557304c1 · GitHub at these lines
- State
- achieves: readme · 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 {createHash} from 'node:crypto';
import {buildToolSourceScopes} from './source-scopes.mjs';
const sha=raw=>createHash('sha256').update(raw).digest('hex');
function fixture() {
const bodies=new Map([['apps/one/index.html',Buffer.from('<script src="app.js"></script>')],['apps/one/app.js',Buffer.from('const original=1;')],['apps/two/index.html',Buffer.from('<p>Sibling</p>')],['shared/grid.geojson',Buffer.from('{"type":"FeatureCollection","features":[]}')]]);
const manifest={schema:'globalgrid.original-runtime.v1',generation:'202609051858',applications:[{id:'one',entry:'apps/one/index.html'},{id:'two',entry:'apps/two/index.html'}],files:[...bodies].map(([path,bytes])=>({path,bytes:bytes.length,sha256:sha(bytes)})),externalLiteralUrls:['https://example.test/library.js'],rootOriginDependencies:['/shared.json'],crossOwnerNavigation:[{path:'sibling/index … [line shortened here: 432 characters; full line on GitHub]
const reads=[];const owner={repository:'Ventusltd/fixture',commit:'a'.repeat(40),release:manifest.generation,manifestSha256:''};
const tool={id:'one',title:'One',entry:'../layer-apps/apps/one/index.html',owner};
const pin=()=>{const raw=Buffer.from(JSON.stringify(manifest));owner.manifestSha256=sha(raw);return raw;};
const readCandidate=async path=>{reads.push(path);const b=bodies.get(path.replace(/^layer-apps\//,''));if(!b)throw Error('Missing fixture candidate');return b;};
const run=()=>{const raw=pin();return buildToolSourceScopes([tool],async()=>raw,readCandidate);};
return {bodies,manifest,reads,owner,tool,pin,readCandidate,run};
}
test('own source and shared data are included while sibling runtime remains separate',async()=>{
const f=fixture(),before=JSON.stringify(f.manifest),out=await f.run();
assert.equal(out.apps.length,1);assert.deepEqual(out.apps[0].files.map(x=>x.path),['layer-apps/apps/one/index.html','layer-apps/apps/one/app.js','layer-apps/shared/grid.geojson']);
assert.equal(out.apps[0].files.at(-1).kind,'data');assert.equal(out.apps[0].files[1].kind,'source');
assert.equal(f.reads.includes('layer-apps/apps/two/index.html'),false);
assert.deepEqual(out.apps[0].baselineNavigation,f.manifest.crossOwnerNavigation);assert.deepEqual(out.apps[0].externalDependencies,f.manifest.externalLiteralUrls);
assert.equal(JSON.stringify(f.manifest),before);assert.equal(JSON.stringify(out).includes('const original=1'),false);
});
test('manifest pin, release identity and entry binding are mandatory',async()=>{
const f=fixture();const raw=f.pin();
await assert.rejects(buildToolSourceScopes([f.tool],async()=>Buffer.concat([raw,Buffer.from(' ')]),f.readCandidate),/manifest pin mismatch/);
f.owner.release='202609051859';await assert.rejects(f.run(),/release identity/);
f.owner.release=f.manifest.generation;f.tool.entry='../layer-apps/apps/two/index.html';await assert.rejects(f.run(),/entry mismatch/);
});
test('composed byte tampering and missing entry are refused',async()=>{
const f=fixture();f.bodies.set('apps/one/app.js',Buffer.from('const altered=2;'));
await assert.rejects(f.run(),/differs from owner/);
const absent=fixture();absent.manifest.files=absent.manifest.files.filter(x=>x.path!=='apps/one/index.html');
await assert.rejects(absent.run(),/entry absent/);
});
test('unknown schema and malformed manifest arrays cannot become scopes',async()=>{
for(const mutate of [m=>m.schema='unverified.v1',m=>m.applications={},m=>m.files=null,m=>m.applications[0].entry=null]) {
const f=fixture();mutate(f.manifest);await assert.rejects(f.run());assert.equal(f.reads.length,0);
}
});
test('excluded siblings cannot hide unsafe paths or duplicate manifest identities',async()=>{
for(const mutate of [
m=>m.files.push({...m.files[2],path:'apps/two/../../escape.js'}),
m=>m.files.push({...m.files[2]}),
m=>m.applications.push({...m.applications[0]}),
m=>m.files[2].sha256='not-a-hash',
m=>m.files[2].bytes=-1
]) {
const f=fixture();mutate(f.manifest);await assert.rejects(f.run());assert.equal(f.reads.length,0);
}
});
test('encoded traversal and an unmanifested entry cannot escape their declared scope',async()=>{
const f=fixture();f.manifest.files[1].path='apps/one/%2e%2e/escape.js';await assert.rejects(f.run());
const empty=fixture();empty.manifest.applications=[];await assert.rejects(empty.run());
});
function derivedFixture(mutateBaseline=()=>{},mutatePin=()=>{}) {
const f=fixture(),baseline=structuredClone(f.manifest);
baseline.generation='202609051857';mutateBaseline(baseline);
const original=Buffer.from(JSON.stringify(baseline));
f.manifest.schema='globalgrid.derived-runtime.v1';delete f.manifest.externalLiteralUrls;
f.manifest.baseline={commit:'b'.repeat(40),generation:'202609051857',manifestSha256:sha(original)};mutatePin(f.manifest.baseline);
const current=f.pin();
const run=()=>buildToolSourceScopes([f.tool],async owner=>owner.commit===f.owner.commit?current:original,f.readCandidate);
return {...f,baseline,run};
}
test('derived external declarations come from a separately hash-bound original baseline',async()=>{
const f=derivedFixture(),out=await f.run();
assert.deepEqual(out.apps[0].externalDependencies,['https://example.test/library.js']);
});
test('baseline dependency metadata cannot bypass identity, schema or array checks',async()=>{
for(const [mutate,pin] of [
[m=>m.generation='202609051856',()=>{}],
[m=>m.schema='unknown.v1',()=>{}],
[m=>m.externalLiteralUrls='not-an-array',()=>{}],
[()=>{},p=>p.commit='main'],
[()=>{},p=>p.manifestSha256='0'.repeat(64)]
]) {
const f=derivedFixture(mutate,pin);await assert.rejects(f.run());assert.equal(f.reads.length,0);
}
});App Print Browser
A JavaScript module in the tools folder of Testcode.
rendertestcode / sandbox/tools/app-print.browser.cjs · lines 1–50 of 50 · Entry point
- What it does
- It draws its content. Defines check. Uses libraries node:fs, node:path, playwright, C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright. Side effects: changes the web page (DOM); 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. Out: JSON file results.json.
- Downstream impact
- Used directly by 6 files: Composition Guard Workflow (testcode); Measurement Clearance Workflow (testcode); Measurement Readouts Workflow (testcode); Polygon Distance Workflow (testcode); and 2 more.
- What it achieves
- Defines `check`. It responds to teleprint events.
- Why it matters
- Run by 6 workflows and scripts, including Composition Guard Workflow, Measurement Clearance Workflow and Measurement Readouts Workflow.
- Application
- testcode · sandbox/tools · JavaScript module
- Uses
- node:fs, node:path, playwright, C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright
- Used by
- run by Composition Guard Workflow (workflow run), run by Measurement Clearance Workflow (workflow run), run by Measurement Readouts Workflow (workflow run), run by Polygon Distance Workflow (workflow run), run by Tool Recovery Workflow (workflow run), run by Vertex Limit Workflow (workflow run)
- 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/tools/app-print.browser.cjs:1-50 · blob a6108f99bd33047455e099587f7fc59b5cc8a383 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: experimental · users: none · canonical: unknown
const fs=require('node:fs'),path=require('node:path');
let pw;try{pw=require('playwright');}catch{pw=require('C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright');}
const base=process.argv[2],out=path.resolve(process.env.TEST_OUTPUT||'app-print-artifacts');
fs.mkdirSync(out,{recursive:true});
const results=[];
(async()=>{
const browser=await pw[process.env.TEST_ENGINE||'chromium'].launch();
try{for(const viewport of [{width:393,height:852},{width:1440,height:900}]){
const ratio=Number(process.env.TEST_DPR||1);
const context=await browser.newContext({viewport,deviceScaleFactor:ratio}),page=await context.newPage();
const receipt={viewport,checks:[],errors:[]};results.push(receipt);
const check=(name,pass,detail)=>{receipt.checks.push({name,pass:!!pass,detail});console.log(pass?'PASS':'FAIL',viewport.width,name);};
page.on('pageerror',e=>receipt.errors.push(e.message));
try{
await page.goto(base,{waitUntil:'domcontentloaded'});
await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__?.getSource('src-zonedraw-points'));
await page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.jumpTo({center:[0.935,51.339],zoom:14}));
await page.locator('.gm-title').filter({hasText:/^Scope$/}).click();
await page.locator('#btn-zonedraw').click();
await page.locator('#zonedraw-radius-input').fill('0.337');
const canvas=page.locator('#map canvas.maplibregl-canvas'),box=await canvas.boundingBox();
await canvas.click({position:{x:box.width/2,y:box.height/2}});
await page.waitForFunction(()=>document.querySelector('.measurement-dock-values')?.textContent.includes('Hectares'));
await page.waitForFunction(()=>!window.__GRIDATLAS_V9_MAP__.isMoving());
receipt.visibleMeasurements=await page.locator('.measurement-dock-values').innerText();
receipt.screenCanvas=await canvas.boundingBox();
receipt.geometry=await page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.getSource('src-zonedraw-fill')._data);
await page.screenshot({path:path.join(out,viewport.width+'-screen.png')});
await page.evaluate(()=>{window.__teleprint=null;document.querySelector('#codex-teleprinter').addEventListener('teleprint',event=>window.__teleprint=event.detail);});
const downloadPromise=page.waitForEvent('download',{timeout:60000}).catch(error=>({failed:error.message}));
const menu=page.locator('#gridatlas-menu-bar .gm-menu').filter({has:page.locator('[data-gm-export]')}).first();
await menu.locator('.gm-title').click();
const print=page.locator('#gridatlas-export-print');
if(await print.count())await print.click();else await page.locator('button[data-gm-export]').filter({hasText:/Print/}).first().click();
const download=await downloadPromise;
if(download.failed)throw Error(download.failed+' '+await page.locator('#codex-teleprinter #status').innerText());
await download.saveAs(path.join(out,viewport.width+'-print.pdf'));
receipt.teleprint=await page.evaluate(()=>window.__teleprint);
check('Actual Print downloads the app record without screen sharing',receipt.teleprint?.method==='app-render'&&receipt.teleprint?.capture?.screenSharing===false,receipt.teleprint);
check('Print records original viewport at device resolution',receipt.teleprint?.width===viewport.width*ratio&&receipt.teleprint?.height===viewport.height*ratio);
check('Print retains visible measurement panel after capture',await page.locator('.measurement-dock-values').isVisible());
check('Print leaves exact polygon geometry unchanged',JSON.stringify(await page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.getSource('src-zonedraw-fill')._data))===JSON.stringify(receipt.geometry));
check('Print causes no script errors',receipt.errors.length===0,receipt.errors);
}catch(error){receipt.error=error.stack;check('Print action completes',false,error.message);}
finally{await context.close();}
}}finally{await browser.close();}
})().catch(error=>{results.push({error:error.stack});process.exitCode=1;}).finally(()=>{
fs.writeFileSync(path.join(out,'results.json'),JSON.stringify({base,results},null,2)+'\n');
if(results.some(r=>r.error||r.checks?.some(c=>!c.pass)))process.exitCode=1;
});Arrival Diagnostic
A JavaScript module in the tools folder of Testcode.
rendertestcode / sandbox/tools/arrival-diagnostic.cjs · lines 1–52 of 52 · Not reached from any entry point (candidate for review)
- What it does
- It loads data. Defines save. Uses libraries node:fs, node:path, node:http, node:child_process, C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright. 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 results.json.
- What it achieves
- Defines `save`.
- Why it matters
- No other file in the estate was found to import it.
- Application
- testcode · sandbox/tools · JavaScript module
- Uses
- node:fs, node:path, node:http, node:child_process, C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright
- Used by
- none found
- Produces
- save
- Defines here
- save
- 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/tools/arrival-diagnostic.cjs:1-52 · blob cbf7cc6a2ad1047465ee1d17410bed44f21fc0e9 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: experimental · users: none · canonical: unreached_review
const fs = require('node:fs');
const path = require('node:path');
const http = require('node:http');
const {execFileSync} = require('node:child_process');
let playwright;
try {playwright = require(process.env.PLAYWRIGHT_MODULE || 'playwright');}
catch (error) {
if (process.env.PLAYWRIGHT_MODULE) throw error;
playwright = require('C:/Users/vikra/OneDrive/Documents/GitHub/gridatlas-main-202609050200/node_modules/playwright');
}
const root = path.resolve(__dirname, '../..');
const generation = process.env.TEST_GENERATION;
if (!/^\d{12}$/.test(generation || '')) throw Error('TEST_GENERATION must identify an immutable candidate');
const output = path.resolve(process.env.TEST_OUTPUT || 'offshore-route-artifacts');
fs.mkdirSync(output, {recursive:true});
const report = {generation, profiles:[], sourceMode:'Actual composed files; no request interception or source substitution', limitations:['Chrome phone emulation is not physical-device evidence.','Straight lines are mapped measurements, not surveyed export routes.']};
const server = http.createServer((req,res) => {
const pathname = decodeURIComponent(new URL(req.url,'http://localhost').pathname);
const relative = pathname.startsWith('/testcode/') ? '/sandbox/' + pathname.slice(10) : pathname;
let file = path.resolve(root, '.' + relative);
if (!file.startsWith(root + path.sep)) return res.writeHead(403).end();
try {
if (fs.statSync(file).isDirectory()) file=path.join(file,'index.html');
const repoPath=path.relative(root,file).split(path.sep).join('/');
const bytes=repoPath.startsWith('sandbox/202609051906/')
? execFileSync('git',['show','HEAD:'+repoPath],{cwd:root,maxBuffer:64*1024*1024}) : fs.readFileSync(file);
res.writeHead(200,{'Content-Type':({'.html':'text/html','.js':'text/javascript','.mjs':'text/javascript','.json':'application/json','.css':'text/css'})[path.extname(file)]||'application/octet-stream'}).end(bytes);
} catch {res.writeHead(404).end();}
});
function save(){fs.writeFileSync(path.join(output,'results.json'),JSON.stringify(report,null,2)+'\n');}
(async()=>{
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
const base=process.env.TEST_BASE||`http://127.0.0.1:${server.address().port}/testcode/${generation}/atlas/`;report.base=base;
const browser=await playwright.chromium.launch({headless:true,...(process.env.CHROME_CHANNEL==='chromium'?{}:{channel:'chrome'})});
try{
for(const ref of (process.env.TEST_REFS||'13419,9873,14926').split(',')){
const context=await browser.newContext({viewport:{width:1440,height:900}}),page=await context.newPage(),entry={ref,errors:[],failed:[],observations:[]};report.profiles.push(entry);
await context.addInitScript(()=>Object.defineProperty(window,'maplibregl',{configurable:true,set(value){Object.defineProperty(window,'maplibregl',{configurable:true,writable:true,value});value.Map=new Proxy(value.Map,{construct(target,args,newTarget){const m=Reflect.construct(target,args,newTarget);window.__DIAGNOSTIC_MAP__=m;return m;}});}}));
page.on('pageerror',e=>entry.errors.push(e.message));page.on('requestfailed',r=>entry.failed.push({url:r.url(),error:r.failure()}));
const query=ref==='13419'?'repd_ref=13419&technology=wind_offshore&latitude=56.5545&longitude=-0.1183&zoom=12':ref==='9873'?'repd_ref=9873&technology=wind_offshore&latitude=56.4431397&longitude=-1.4664021&zoom=12':'repd_ref=14926&technology=solar&latitude=51.779&longitude=-1.337&zoom=12';
await page.goto(base+'?'+query,{waitUntil:'domcontentloaded',timeout:60000});await page.bringToFront();
await page.waitForFunction(()=>window.__DIAGNOSTIC_MAP__&&window.__GRIDATLAS_NEON_LINKS__,null,{timeout:60000});
for(const seconds of [3,10,20]){
await page.waitForTimeout((seconds-(entry.observations.at(-1)?.seconds||0))*1000);
await page.screenshot({path:path.join(output,ref+'-'+seconds+'.png')});
const observation=await page.evaluate(()=>{const m=window.__DIAGNOSTIC_MAP__,n=window.__GRIDATLAS_NEON_LINKS__;return {visible:document.visibilityState,loaded:m.isStyleLoaded(),center:m.getCenter().toArray(),zoom:m.getZoom(),sources:Object.fromEntries(['gridatlas-neon-links','gridatlas-neon-nodes','gridatlas-sld'].map(id=>[id,m.getSource(id)?._data?.features?.length??null])),card:document.query … [line shortened here: 658 characters; full line on GitHub]
entry.observations.push({seconds,...observation});save();
}
console.log(JSON.stringify({ref,errors:entry.errors,observations:entry.observations.map(o=>({seconds:o.seconds,visible:o.visible,loaded:o.loaded,sources:o.sources,answer:o.answer,owner:o.owner,failures:o.neon.failures}))}));await context.close();
}
}finally{await browser.close();}
})().catch(error=>{report.error=error.stack;process.exitCode=1;}).finally(()=>{save();server.close();});