In this section
- Visibility Style transform · galaxies-wafers / iterations/12-visibility-lab/visibility-style.mjs lines 1–108
- Iterations — 13 Diversified Demand energy-data · galaxies-wafers / iterations/13-diversified-demand/app.mjs lines 1–61
- Browser Check render · galaxies-wafers / iterations/13-diversified-demand/browser-check.mjs lines 1–58
- Iterations — 13 Diversified Demand Page render · galaxies-wafers / iterations/13-diversified-demand/index.html lines 1–26
- Model transform · galaxies-wafers / iterations/13-diversified-demand/model.mjs lines 1–21
- Model Test test · galaxies-wafers / iterations/13-diversified-demand/model.test.mjs lines 1–21
- Iterations — 14 Electrical Hops render · galaxies-wafers / iterations/14-electrical-hops/app.mjs lines 1–60
- Browser Check render · galaxies-wafers / iterations/14-electrical-hops/browser-check.mjs lines 1–33
- Fixture other · galaxies-wafers / iterations/14-electrical-hops/fixture.mjs lines 1–10
- Model transform · galaxies-wafers / iterations/14-electrical-hops/model.mjs lines 1–13
- Model Test test · galaxies-wafers / iterations/14-electrical-hops/model.test.mjs lines 1–17
- Browser Check render · galaxies-wafers / iterations/16-firm-capacity/browser-check.mjs lines 1–25
- Model ingest · galaxies-wafers / iterations/16-firm-capacity/model.mjs lines 1–15
- Model Test test · galaxies-wafers / iterations/16-firm-capacity/model.test.mjs lines 1–13
Visibility Style
A JavaScript module in the iterations folder of Galaxies Wafers that works with linear channel (`linearChannel`) and source contexts (`sourceContexts`). Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/12-visibility-lab/.
transformgalaxies-wafers / iterations/12-visibility-lab/visibility-style.mjs · lines 1–108 of 108 · pattern composite (shared by 2 files)
- What it does
- It calculates its inputs. Defines 16 functions or classes, including finite, unit, rgb, hex, composite.
- Why it exists in the grid workflow
- README: "The exported `bond.visibility-style.v1` JSON preserves layer IDs and colours and records all named comparison contexts."
- Downstream impact
- Used directly by 3 files: Iterations — 12 Visibility Lab (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/12-visibility-lab/); Export Style (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/12-visibility-lab/); Model Test (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/12-visibility-lab/). Reached from 1 other entry point, including Iterations — 12 Visibility Lab Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/12-visibility-lab/).
- What it achieves
- It measures style (`measureStyle`) and exports visibility (`exportVisibility`). Pure `sRGB` visibility model. No DOM, geometry keys, network or source changes.
- Why it matters
- Imported by Iterations — 12 Visibility Lab and Export Style. Checked by Model Test.
- Application
- galaxies-wafers · iterations/12-visibility-lab · JavaScript module
- Uses
- none found
- Used by
- imported by Iterations — 12 Visibility Lab (import), imported by Export Style (import), imported by Model Test (import), mentioned in Standalone (comment link)
- Produces
- STYLE_VERSION, GRAPHICS_COMPARATOR, PROJECT_POLICY, SOURCE_BASELINE, W3C_REFERENCE, rgb, hex, composite, linearChannel, luminance, contrast, brightness
- Defines here
- finite, unit, rgb, hex, composite, linearChannel, luminance, contrast, brightness, sourceContexts, contextsChecked, chooseCasing, currentStyle, proposedStyle, measureStyle, exportVisibility
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/12-visibility-lab/visibility-style.mjs:1-108 · blob e606ceda314f500f1c249fe503fa44dd88baf030 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unknown
/* Pure sRGB visibility model. No DOM, geometry keys, network or source changes. */
export const STYLE_VERSION = '1.0.0';
export const GRAPHICS_COMPARATOR = 3;
export const PROJECT_POLICY = Object.freeze({ minimum_stroke_css_px: 2, minimum_point_radius_css_px: 3, casing_band_css_px: 1, source: 'PROJECT POLICY; size values are not WCAG requirements' });
export const SOURCE_BASELINE = Object.freeze({ line_layer_alpha: 0.55, other_layer_alpha: 0.8, line_width_css_px: 1, point_shape: 'square', point_width_css_px: 2, point_height_css_px: 2, casing: null, zoom_changes_css_size: false, zoom_changes_alpha: false });
export const W3C_REFERENCE = 'https://www.w3.org/WAI/WCAG22/understanding/non-text-contrast.html';
function finite(value, label) {
if (typeof value !== 'number' || !Number.isFinite(value)) throw new TypeError(`${label} must be finite`);
return value;
}
function unit(value, label) {
finite(value, label);
if (value < 0 || value > 1) throw new RangeError(`${label} must be between 0 and 1`);
return value;
}
export function rgb(value) {
if (typeof value === 'string' && /^#[0-9a-f]{6}$/i.test(value)) return [1, 3, 5].map(i => parseInt(value.slice(i, i + 2), 16) / 255);
if (!Array.isArray(value) || value.length !== 3) throw new TypeError('colour must be #rrggbb or three sRGB channels');
return value.map(channel => unit(channel, 'sRGB channel'));
}
export function hex(value) { return '#' + rgb(value).map(c => Math.round(c * 255).toString(16).padStart(2, '0')).join(''); }
export function composite(foreground, alpha, background) {
const f = rgb(foreground), b = rgb(background); unit(alpha, 'alpha');
return f.map((c, i) => c * alpha + b[i] * (1 - alpha));
}
export function linearChannel(value) { unit(value, 'sRGB channel'); return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4; }
export function luminance(value) { const c = rgb(value).map(linearChannel); return c[0] * 0.2126 + c[1] * 0.7152 + c[2] * 0.0722; }
export function contrast(a, b) { const x = luminance(a), y = luminance(b); return (Math.max(x, y) + 0.05) / (Math.min(x, y) + 0.05); }
export function brightness(value, factor = 1) {
finite(factor, 'brightness'); if (factor < 0) throw new RangeError('brightness must be nonnegative');
return rgb(value).map(c => Math.min(1, c * factor));
}
export function sourceContexts({ ground = [0.043, 0.051, 0.071] } = {}) {
const g = rgb(ground);
return [
{ id: 'webgl_ground', label: 'WebGL bare ground', rgb: g, source: 'app.mjs clearColor(0.043,0.051,0.071,1); configurable scenario ground' },
{ id: 'carried_centre', label: 'Carried-family point opaque centre', rgb: [0.84, 0.87, 0.94], source: 'app.mjs shader carried vec3; opaque centre only' },
{ id: 'alone_centre', label: 'Uncarried point centre over WebGL ground', rgb: composite([0.30, 0.34, 0.44], 0.30, g), source: 'app.mjs shader alone vec3 at alpha 0.30; edge attenuation excluded' },
{ id: 'fallback_ground', label: 'Canvas fallback bare ground', rgb: rgb('#0b0d12'), source: 'app.mjs fallback fill #0b0d12' },
{ id: 'fallback_point', label: 'Canvas fallback opaque point', rgb: rgb('#7d8598'), source: 'app.mjs fallback point fill #7d8598' }
];
}
function contextsChecked(contexts) {
if (!Array.isArray(contexts) || !contexts.length) throw new TypeError('at least one explicit comparison context is required');
const ids = new Set();
return contexts.map(c => {
if (!c || typeof c.id !== 'string' || !c.id || ids.has(c.id)) throw new TypeError('context ids must be unique nonempty strings');
ids.add(c.id); return { ...c, rgb: rgb(c.rgb) };
});
}
export function chooseCasing(contexts, { alpha = 1, threshold = GRAPHICS_COMPARATOR } = {}) {
const checked = contextsChecked(contexts); unit(alpha, 'casing alpha');
finite(threshold, 'contrast threshold'); if (threshold < 1) throw new RangeError('contrast threshold must be at least 1');
const candidates = ['#ffffff', '#000000'].map(colour => {
const ratios = checked.map(c => ({ context_id: c.id, ratio: contrast(composite(colour, alpha, c.rgb), c.rgb) }));
return { colour, alpha, ratios, minimum_ratio: Math.min(...ratios.map(r => r.ratio)), meets_all: ratios.every(r => r.ratio >= threshold) };
});
candidates.sort((a, b) => b.minimum_ratio - a.minimum_ratio || a.colour.localeCompare(b.colour));
return { ...candidates[0], status: candidates[0].meets_all ? 'MEETS_SELECTED_CONTEXTS' : 'SELECTED_CONTEXTS_LIMIT', candidates };
}
export function currentStyle(layer) {
rgb(layer.colour);
return { base_colour: layer.colour, alpha: layer.draws === 'lines' ? 0.55 : 0.8, brightness: 1, line_width_css_px: 1, point_shape: 'square', point_width_css_px: 2, point_height_css_px: 2, casing: null };
}
export function proposedStyle(layer, options = {}) {
const base = rgb(layer.colour), contexts = contextsChecked(options.contexts ?? sourceContexts());
const zoom = options.zoom ?? 1; finite(zoom, 'zoom'); if (zoom <= 0) throw new RangeError('zoom must be positive');
const alpha = unit(options.alpha ?? 1, 'core alpha'), factor = options.brightness ?? 1;
const lineWidth = Math.max(PROJECT_POLICY.minimum_stroke_css_px, finite(options.strokeCssPx ?? 2, 'stroke size'));
const radius = Math.max(PROJECT_POLICY.minimum_point_radius_css_px, finite(options.pointRadiusCssPx ?? 3, 'point radius'));
const mode = options.casing ?? 'auto';
if (!['auto', 'none', 'light', 'dark'].includes(mode)) throw new TypeError('casing must be auto, none, light or dark');
const chosenIds = options.casingContextIds ?? ['webgl_ground'];
if (!Array.isArray(chosenIds) || !chosenIds.length || new Set(chosenIds).size !== chosenIds.length || chosenIds.some(id => !contexts.some(c => c.id === id))) throw new TypeError('casing contexts must name available unique contexts');
const selected = contexts.filter(c => chosenIds.includes(c.id));
const choice = chooseCasing(selected, { alpha: options.casingAlpha ?? 1 });
let casing = null;
if (mode !== 'none') {
const colour = mode === 'auto' ? choice.colour : mode === 'light' ? '#ffffff' : '#000000';
const selectedChoice = choice.candidates.find(candidate => candidate.colour === colour);
casing = { mode, colour, alpha: unit(options.casingAlpha ?? 1, 'casing alpha'), band_css_px: PROJECT_POLICY.casing_band_css_px, line_width_css_px: lineWidth + 2 * PROJECT_POLICY.casing_band_css_px, point_radius_css_px: radius + PROJECT_POLICY.casing_band_css_px, selection_context_ids: chosenIds.slice(), selection: { ...selectedChoice, status: selectedChoice.meets_all ? 'MEETS_SELECTED_CONTEXTS … [line shortened here: 465 characters; full line on GitHub]
}
return { base_colour: layer.colour, render_rgb: brightness(base, factor), alpha, brightness: factor, line_width_css_px: lineWidth, point_shape: 'circle', point_radius_css_px: radius, casing, zoom, zoom_changes_css_size: false, zoom_changes_alpha: false, policy: PROJECT_POLICY.source };
}
export function measureStyle(style, contexts) {
return contextsChecked(contexts).map(c => {
const outer = style.casing ? composite(style.casing.colour, style.casing.alpha, c.rgb) : c.rgb;
const core = composite(style.render_rgb ?? brightness(style.base_colour, style.brightness ?? 1), style.alpha, outer);
const boundary = style.casing ? contrast(outer, c.rgb) : contrast(core, c.rgb);
return { context_id: c.id, context_rgb: c.rgb, context_display_hex: hex(c.rgb), core_composite_rgb: core, core_display_hex: hex(core), core_to_context_ratio: contrast(core, c.rgb), core_to_casing_ratio: style.casing ? contrast(core, outer) : null, casing_to_context_ratio: style.casing ? contrast(outer, c.rgb) : null, boundary_ratio: boundary, meets_graphics_comparator: boundary >= GRAPHICS_COM … [line shortened here: 410 characters; full line on GitHub]
});
}
export function exportVisibility(manifest, options = {}) {
if (manifest?.substrate !== 'wafer.v1' || !Array.isArray(manifest.layers)) throw new TypeError('a wafer.v1 manifest is required');
const contexts = contextsChecked(options.contexts ?? sourceContexts({ ground: options.ground }));
const ids = new Set();
const rows = manifest.layers.map((layer, index) => {
if (!layer || typeof layer.id !== 'string' || !layer.id || ids.has(layer.id)) throw new TypeError('layer identifiers must be unique nonempty strings');
if (!Number.isSafeInteger(layer.features) || layer.features < 0) throw new TypeError('manifest feature counts must be nonnegative integers');
ids.add(layer.id); rgb(layer.colour);
const empty = layer.features === 0, current = currentStyle(layer), proposed = proposedStyle(layer, { ...options, contexts });
return { manifest_index: index, layer_id: layer.id, label: layer.label ?? layer.id, group: layer.group ?? '', manifest_features: layer.features, status: empty ? 'EMPTY' : 'STYLE_MODEL', draws: layer.draws ?? 'unspecified', base_colour: layer.colour, current, proposed, current_measurements: empty ? [] : measureStyle(current, contexts), proposed_measurements: empty ? [] : measureStyle(proposed, … [line shortened here: 590 characters; full line on GitHub]
});
const nonempty = rows.filter(r => r.status !== 'EMPTY');
const perContext = contexts.map(c => ({ context_id: c.id, evaluated_layers: nonempty.length, current_meets_3_to_1: nonempty.filter(r => r.current_measurements.find(m => m.context_id === c.id).meets_graphics_comparator).length, proposed_boundary_meets_3_to_1: nonempty.filter(r => r.proposed_measurements.find(m => m.context_id === c.id).meets_graphics_comparator).length }));
return { schema: 'bond.visibility-style.v1', style_version: STYLE_VERSION, source_baseline: SOURCE_BASELINE, project_policy: PROJECT_POLICY, comparator: { ratio: GRAPHICS_COMPARATOR, reference: W3C_REFERENCE, scope: '3:1 graphical adjacency comparator only; not full WCAG conformance, not a minimum-size standard' }, colour_model: 'Source-over compositing in encoded sRGB; relative luminance is com … [line shortened here: 1,174 characters; full line on GitHub]
}Iterations — 13 Diversified Demand
A JavaScript module in Galaxies Wafers covering group demand, using SHA-256. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/13-diversified-demand/.
energy-datagalaxies-wafers / iterations/13-diversified-demand/app.mjs · lines 1–61 of 61 · Entry point · pattern register (shared by 59 files)
- What it does
- It draws group demand. Defines $, fmt, refresh, register. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- README: "The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/202609151339."
- Inputs & outputs
- Out: JSON file group-demand.json; downloaded file group-demand.json.
- Downstream impact
- Used directly by 1 file: Iterations — 13 Diversified Demand Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/13-diversified-demand/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/13-diversified-demand/.
- What it achieves
- It is built from the fmt step (`fmt`), the refresh step (`refresh`) and the register step (`register`). The README says: The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/. It responds to submit, input and change events.
- Why it matters
- Loaded by the page of the same name at https://ventusltd.github.io/galaxies-wafers/iterations/13-diversified-demand/.
- Application
- galaxies-wafers · iterations/13-diversified-demand · JavaScript module
- Uses
- Model (import)
- Used by
- loaded by Iterations — 13 Diversified Demand Page (script src)
- Produces
- $, fmt, refresh, register
- Defines here
- $, fmt, refresh, register
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/13-diversified-demand/app.mjs:1-61 · blob aa77289c519a8fa1655a5c9f08a3ba6980f0fb85 · GitHub at these lines
- State
- achieves: readme · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: supporting_data
import {SOURCE,MODULE_URL,numberInput,calculate} from './model.mjs';
const $ = id => document.getElementById(id);
const fields = ['unitCount','perUnitKw','coincidenceFactor','measuredGroupPeakKw'];
const fmt = n => n!==0 && Math.abs(n)<0.000001 ? n.toExponential(4) : n.toLocaleString('en-GB',{maximumFractionDigits:6});
let engine, current;
$('source').href=`https://github.com/${SOURCE.repository}/blob/${SOURCE.commit}/${SOURCE.file}`;
$('sourcePin').textContent=`${SOURCE.repository} / ${SOURCE.commit} / ${SOURCE.file}\nSHA256 ${SOURCE.sha256}`;
function refresh() {
current=null; $('download').disabled=true;
const mode=$('mode').value;
$('factorFields').hidden=mode!=='assumed'; $('peakFields').hidden=mode!=='implied';
if(!engine)return;
try {
const inputs=Object.fromEntries(fields.map(id=>[id,numberInput($(id).value)]));
current=calculate(engine,mode,inputs);
$('resultLabel').textContent=mode==='assumed'?'Aggregate group demand · under the stated assumption':'Coincidence factor · implied by the supplied peak';
$('answer').textContent=fmt(current.value); $('answerUnit').textContent=current.unit==='kW'?'kW':'fraction';
$('equation').textContent=mode==='assumed'?`${fmt(inputs.unitCount)} units × ${fmt(inputs.perUnitKw)} kW × ${fmt(current.factor)}`:`${fmt(current.groupKw)} kW ÷ ${fmt(current.from.unrestrictedKw)} kW`;
$('unrestricted').textContent=`${fmt(current.from.unrestrictedKw)} kW`;
$('group').textContent=`${fmt(current.groupKw)} kW`;
$('groupLabel').textContent=mode==='assumed'?'With the assumed factor':'Supplied group peak';
$('fraction').textContent=`${fmt(current.factor*100)}% of this group's unrestricted total. This is aggregate kW, not kW per unit.`;
$('loadLabel').textContent=`${fmt(current.groupKw)} kW`;
$('groupBar').style.width=`${current.factor*100}%`;
$('record').textContent=JSON.stringify(current,null,2);
$('result').hidden=false; $('error').hidden=true; $('status').textContent='Calculated by the pinned module · illustrative inputs'; $('download').disabled=false;
} catch(error) {
$('result').hidden=true; $('error').hidden=false; $('error').textContent=`REFUSED · ${error.name}: ${error.message}`;
$('record').textContent='No current result. Correct the refused input.'; $('status').textContent='Input refused; previous result cleared.';
}
}
$('controls').addEventListener('submit',event=>event.preventDefault());
$('controls').addEventListener('input',event=>{if(event.target.id==='factorSlide')$('coincidenceFactor').value=$('factorSlide').value;else if(event.target.id==='coincidenceFactor' && Number($('coincidenceFactor').value)>0 && Number($('coincidenceFactor').value)<=1)$('factorSlide').value=$('coincidenceFactor').value;refresh();});
$('mode').addEventListener('change',refresh);
$('reset').addEventListener('click',()=>{$('mode').value='assumed';$('unitCount').value='100';$('perUnitKw').value='7';$('coincidenceFactor').value='0.3';$('factorSlide').value='0.3';$('measuredGroupPeakKw').value='210';refresh();});
$('download').addEventListener('click',()=>{if(!current)return;const url=URL.createObjectURL(new Blob([JSON.stringify(current,null,2)+'\n'],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download='group-demand.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);});
try {
engine=await import(MODULE_URL);
for(const [name,reason] of Object.entries(engine.NOT_COMPUTED)) {const term=document.createElement('dt');term.textContent=name;const desc=document.createElement('dd');desc.textContent=reason;$('exclusions').append(term,desc);}
refresh();
} catch(error) {
$('status').textContent='Calculation module unavailable. No substitute result is calculated.';
$('error').hidden=false;$('error').textContent=`Source import failed: ${error.message}`;
}
const context=document.modelContext;
if(context?.registerTool) {
const lifecycle=new AbortController();
addEventListener('pagehide',()=>lifecycle.abort(),{once:true});
const register=tool=>{try{Promise.resolve(context.registerTool(tool,{signal:lifecycle.signal})).catch(()=>{});}catch{}};
register({name:'read_group_demand',description:'Read the current illustrative group-demand record without changing the page.',inputSchema:{type:'object',properties:{},additionalProperties:false},annotations:{readOnlyHint:true,untrustedContentHint:false},execute(input){if(!input || typeof input!=='object' || Array.isArray(input) || Object.keys(input).length)throw new TypeError('Expected an empty … [line shortened here: 513 characters; full line on GitHub]
register({name:'configure_group_demand',description:'Set illustrative group inputs and recalculate the visible comparison. Does not approve a connection or publish data.',inputSchema:{type:'object',properties:{mode:{type:'string',enum:['assumed','implied']},unitCount:{type:'integer',minimum:1,maximum:10000000},perUnitKw:{type:'number',exclusiveMinimum:0,maximum:1000},coincidenceFactor:{type:'num … [line shortened here: 636 characters; full line on GitHub]
if(!engine)throw new Error('Calculation module unavailable');
if(!input || typeof input!=='object' || Array.isArray(input) || Object.keys(input).some(key=>!['mode',...fields].includes(key)))throw new TypeError('Unexpected configuration fields');
const needed=['unitCount','perUnitKw',input.mode==='assumed'?'coincidenceFactor':'measuredGroupPeakKw'];
if(needed.some(key=>typeof input[key]!=='number' || !Number.isFinite(input[key])))throw new TypeError('Required inputs must be finite numbers');
calculate(engine,input.mode,input);
$('mode').value=input.mode;for(const key of needed)$(key).value=String(input[key]);
if(input.mode==='assumed')$('factorSlide').value=String(input.coincidenceFactor);
refresh();return JSON.parse(JSON.stringify(current));
}});
}Browser Check
A JavaScript module in the iterations folder of Galaxies Wafers that uses SHA-256. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/13-diversified-demand/.
rendergalaxies-wafers / iterations/13-diversified-demand/browser-check.mjs · lines 1–58 of 58 · Not reached from any entry point (candidate for review)
- What it does
- It draws its content. Defines hash. Uses libraries node:child_process, node:fs/promises, node:path, node:crypto, node:assert/strict. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes.
- Inputs & outputs
- Out: JSON file receipt.json.
- What it achieves
- Defines `hash`. Its code works with 700 kW.
- Why it matters
- No other file in the estate was found to import it.
- Application
- galaxies-wafers · iterations/13-diversified-demand · JavaScript module
- Uses
- Model (script call), node:child_process, node:fs/promises, node:path, node:crypto, node:assert/strict
- Used by
- none found
- Produces
- hash
- Defines here
- hash
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/13-diversified-demand/browser-check.mjs:1-58 · blob 5a01c6282c2e2af7dd8d6d5ad0cda97edee6a2df · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, network, process · domain stage: unknown · users: none · canonical: unreached_review
import {spawn} from 'node:child_process';
import {mkdir,writeFile,readFile} from 'node:fs/promises';
import path from 'node:path';
import {createHash} from 'node:crypto';
import assert from 'node:assert/strict';
import {SOURCE,MODULE_URL} from './model.mjs';
const playwright=await import(process.env.PLAYWRIGHT_MODULE || 'playwright');
const output=process.env.PROOF_OUTPUT || path.resolve('browser-evidence');
await mkdir(output,{recursive:true});
const url=process.env.PAGE_URL || 'http://127.0.0.1:8779/';
const server=process.env.PAGE_URL?null:spawn(process.platform==='win32'?'python':'python3',['-m','http.server','8779','--bind','127.0.0.1'],{stdio:'ignore'});
const results=[];
const hash=bytes=>createHash('sha256').update(bytes).digest('hex');
try {
for(let attempt=0;attempt<30;attempt++){try{const response=await fetch(url);if(response.ok)break;}catch{}if(attempt===29)throw Error('Preview server unavailable');await new Promise(resolve=>setTimeout(resolve,100));}
for(const name of(process.env.BROWSER_ENGINES || 'chromium,webkit').split(',')) {
const browser=await playwright[name].launch({headless:true,...(name==='chromium' && process.env.CHROME_PATH?{executablePath:process.env.CHROME_PATH}:{})});
try {for(const width of[390,1400]) {
const context=await browser.newContext({viewport:{width,height:width===390?844:900},deviceScaleFactor:width===390?3:1,isMobile:width===390,hasTouch:width===390,acceptDownloads:true});
const page=await context.newPage();page.setDefaultTimeout(12000);
const errors=[],failures=[],sources=[];
const receipt={engine:name,version:browser.version(),width,dpr:width===390?3:1,started:new Date().toISOString(),pass:false,errors,failed_requests:failures};
let negative=false;
page.on('pageerror',e=>{if(!negative)errors.push(e.message);});
page.on('console',message=>{if(!negative && message.type()==='error')errors.push(message.text());});
page.on('requestfailed',request=>{if(!negative)failures.push({url:request.url(),error:request.failure()?.errorText});});
page.on('response',response=>{if(negative)return;if(response.status()>=400)failures.push({url:response.url(),status:response.status()});if(response.url()===MODULE_URL)sources.push(response.body().then(bytes=>({status:response.status(),sha256:hash(bytes)})));});
try {
await page.goto(url);await page.waitForFunction(()=>document.querySelector('#answer').textContent==='210');
assert.equal(await page.locator('#unrestricted').innerText(),'700 kW');
await page.screenshot({path:path.join(output,`${name}-${width}-assumed.png`),fullPage:true});
await page.locator('#coincidenceFactor').fill('0.6');assert.equal(await page.locator('#answer').innerText(),'420');
await page.locator('#coincidenceFactor').fill('0');assert.match(await page.locator('#error').innerText(),/greater than zero/);assert.equal(await page.locator('#result').isVisible(),false);assert.equal(await page.locator('#download').isDisabled(),true);
await page.locator('#coincidenceFactor').fill('');assert.match(await page.locator('#error').innerText(),/finite number/);
await page.locator('#reset').click();await page.locator('#mode').selectOption('implied');assert.equal(await page.locator('#answer').innerText(),'0.3');
await page.locator('#measuredGroupPeakKw').fill('701');assert.match(await page.locator('#error').innerText(),/exceeds the unrestricted total/);
await page.locator('#measuredGroupPeakKw').fill('350');assert.equal(await page.locator('#answer').innerText(),'0.5');
await page.locator('#unitCount').fill('1.5');assert.match(await page.locator('#error').innerText(),/whole number/);
await page.locator('#unitCount').fill('10000001');assert.match(await page.locator('#error').innerText(),/Interface policy/);
await page.locator('#reset').click();await page.locator('#mode').selectOption('implied');await page.locator('#measuredGroupPeakKw').fill('350');
await page.getByText('Machine detail',{exact:true}).click();
assert.equal(await page.locator('#exclusions dt').count(),4);
const downloadPromise=page.waitForEvent('download');await page.locator('#download').click();const download=await downloadPromise;
const filename=path.join(output,`${name}-${width}-result.json`);await download.saveAs(filename);
const record=JSON.parse(await readFile(filename,'utf8'));assert.equal(record.value,0.5);assert.equal(record.groupKw,350);assert.equal(record.source.sha256,SOURCE.sha256);
receipt.overflow=await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+1);assert.equal(receipt.overflow,false);
await page.emulateMedia({reducedMotion:'reduce'});assert.equal(await page.locator('#groupBar').evaluate(e=>getComputedStyle(e).transitionDuration),'0s');
receipt.source_responses=await Promise.all(sources);assert.ok(receipt.source_responses.length>=1);for(const source of receipt.source_responses){assert.equal(source.status,200);assert.equal(source.sha256,SOURCE.sha256);}
assert.deepEqual(errors,[]);assert.deepEqual(failures,[]);
negative=true;await page.route(MODULE_URL,route=>route.abort('failed'));await page.reload();await page.waitForFunction(()=>document.querySelector('#status').textContent.includes('module unavailable'));
assert.equal(await page.locator('#result').isVisible(),false);assert.equal(await page.locator('#download').isDisabled(),true);receipt.module_unavailable_refused=true;
receipt.native_webmcp='Not exercised; no native support is claimed verified.';receipt.pass=true;
}catch(error){receipt.pass=false;receipt.error=error.stack;}finally{receipt.finished=new Date().toISOString();results.push(receipt);await context.close();}
}}finally{await browser.close();}
}
}finally{server?.kill();await writeFile(path.join(output,'receipt.json'),JSON.stringify({source_commit:process.env.GITHUB_SHA || null,url,results},null,2)+'\n');}
console.log(JSON.stringify({cases:results.length,passed:results.filter(r=>r.pass).length}));
if(!results.length || results.some(r=>!r.pass))process.exitCode=1;Iterations — 13 Diversified Demand Page
A web page in Galaxies Wafers that reads inputs for mode, unit count and per unit kW (units: kW). Published at https://ventusltd.github.io/galaxies-wafers/iterations/13-diversified-demand/.
rendergalaxies-wafers / iterations/13-diversified-demand/index.html · lines 1–26 of 26 · Entry point
- What it does
- It draws its content. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- README: "The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/202609151339."
- Inputs & outputs
- In: form fields (user input). Out: web page.
- Downstream impact
- It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/13-diversified-demand/.
- What it achieves
- Explore aggregate group demand with an explicit coincidence factor and a pinned calculation module. Its code works with 100 kW.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- galaxies-wafers · iterations/13-diversified-demand · page
- Uses
- Galaxies Wafers — Style Sheet (stylesheet), Iterations — 13 Diversified Demand (script src)
- 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
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/13-diversified-demand/index.html:1-26 · blob e2d219a9a917999abe9dbc262ff5845a9f7341bd · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>One group, one assumption · Demand lab</title><meta name="description" content="Explore aggregate group demand with an explicit coincidence factor and a pinned calculation module."><link rel="icon" href="data:,"><link rel="stylesheet" href="style.css"></head>
<body><main>
<header><p class="eyebrow">SYSTEM SKETCH / GROUP DEMAND</p><h1>One group. One assumption.</h1><p>What changes when the units do not all draw their full rating together?</p></header>
<section class="workspace" aria-label="Group demand calculator">
<form id="controls" novalidate><p class="tag">Synthetic example · not a measured network</p>
<label for="mode">Direction</label><select id="mode"><option value="assumed">Assume a factor → calculate group kW</option><option value="implied">Supply a group peak → derive a factor</option></select>
<div class="pair"><label>Number of units<input id="unitCount" type="number" inputmode="numeric" value="100" min="1" max="10000000" step="1"></label><label>Each unit · kW<input id="perUnitKw" type="number" inputmode="decimal" value="7" min="0" max="1000" step="any"></label></div>
<div id="factorFields"><label>Assumed coincidence · fraction<input id="coincidenceFactor" type="number" inputmode="decimal" value="0.3" min="0" max="1" step="any"></label><label class="range-label" for="factorSlide">Explore the assumption · 0.01 to 1</label><input id="factorSlide" type="range" min="0.01" max="1" step="0.01" value="0.3"></div>
<div id="peakFields" hidden><label>Supplied group peak · kW<input id="measuredGroupPeakKw" type="number" inputmode="decimal" value="210" min="0" step="any"></label><p class="hint">This example is synthetic. A value typed here is not evidence of a measurement.</p></div>
<button type="button" id="reset">Reset the 100 × 7 example</button><p class="hint">The engine has no default factor. The starting 0.3 is an explicit illustrative assumption, not a recommendation.</p>
</form>
<section class="drawing" aria-label="Demand comparison"><p id="status" role="status" aria-live="polite">Loading the pinned calculation module…</p>
<div id="result" hidden><p class="result-label" id="resultLabel"></p><p class="big"><output id="answer"></output> <span id="answerUnit"></span></p><p id="equation" class="mono"></p>
<figure><figcaption>Same group · bars share the unrestricted-total scale</figcaption><div class="bar-heading"><span>All units at full rating</span><output id="unrestricted"></output></div><div class="track"><div class="bar total"></div></div><div class="bar-heading"><span id="groupLabel"></span><output id="group"></output></div><div class="track"><div class="bar group" id="groupBar"></div></div><p … [line shortened here: 441 characters; full line on GitHub]
<div class="connection"><span>Group load annotation<br><strong id="loadLabel"></strong></span><span class="linkline" aria-hidden="true"></span><span class="unknown">Upstream capacity<br><strong>Not established</strong></span></div>
<p class="hint">The animation interpolates a bar length when an input changes. It is not a load curve, clock, power-flow solution or equipment-sizing result.</p>
</div><p id="error" role="alert" hidden></p></section></section>
<details><summary>Questions</summary><dl>
<dt>How does this help draw a system or a single-line diagram?</dt><dd>It supplies an illustrative aggregate load label in kW. In assumed mode, <code>diversifiedDemandKw(...).value</code> supplies that label; in inverse mode, the label is the supplied peak. No bus, feeder, transformer or real connection is selected.</dd>
<dt>Which function is doing the work?</dt><dd><code>diversifiedDemandKw</code> or <code>impliedCoincidence</code> in <code>engine/diversified-demand.js</code>, at the full source revision below. These are direct imported calls, not a local formula implementation. The module's own proof is a verified static caller at that pin; cross-repository callers have not been exhaustively audited.</dd>
<dt>Where does the factor come from?</dt><dd>From an explicit assumption, or the ratio implied by a supplied group peak. Neither direction determines whether the inputs represent this group, its control regime or its future behaviour.</dd>
<dt>What is connected next?</dt><dd>Nothing has been established. A load label alone does not identify a connection point or establish firm capacity, security, voltage, thermal limits or protection suitability.</dd></dl></details>
<details><summary>Machine detail</summary><p><a id="source" target="_blank" rel="noreferrer">Pinned calculation source</a> · <a href="README.md">Lab contract</a></p><p class="mono" id="sourcePin"></p><p>Inputs: positive integer units, positive kW per unit, and either a fraction in (0, 1] or a positive group peak no greater than the unrestricted total. This lab adds explicit bounds: at most 10,000, … [line shortened here: 1,030 characters; full line on GitHub]
<footer>Illustrative physics drawn by a computer from published data. Not an engineering design or certified calculation. Any real design above 100 kW needs study and approval by a qualified chartered electrical engineer under the applicable standards. The 100 kW threshold is this project's review policy.</footer>
</main><script type="module" src="app.mjs"></script></body></html>Model
A JavaScript module in the iterations folder of Galaxies Wafers that uses SHA-256. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/13-diversified-demand/. It is built from the number input helper (`numberInput`).
transformgalaxies-wafers / iterations/13-diversified-demand/model.mjs · lines 1–21 of 21
- What it does
- It calculates its inputs. Defines numberInput, calculate.
- Downstream impact
- Used directly by 3 files: Iterations — 13 Diversified Demand (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/13-diversified-demand/); Browser Check (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/13-diversified-demand/); Model Test (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/13-diversified-demand/). Reached from 1 other entry point, including Iterations — 13 Diversified Demand Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/13-diversified-demand/).
- What it achieves
- Defines `numberInput` and `calculate`. Its code works with 1000 kW.
- Why it matters
- Imported by Iterations — 13 Diversified Demand. Run by Browser Check. Checked by Model Test.
- Application
- galaxies-wafers · iterations/13-diversified-demand · JavaScript module
- Uses
- none found
- Used by
- imported by Iterations — 13 Diversified Demand (import), run by Browser Check (script call), imported by Model Test (import), mentioned in Standalone (comment link)
- Produces
- SOURCE, MODULE_URL, numberInput, calculate
- Defines here
- numberInput, calculate
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/13-diversified-demand/model.mjs:1-21 · blob b73791ba7e767a4dff49dbd82647d15049915899 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unknown
export const SOURCE = Object.freeze({repository:'Ventusltd/ventus-grid-engine',commit:'d9cd18b0e2034325814924e6e4a0e958014f2748',file:'engine/diversified-demand.js',sha256:'d3fa87733b1131a4b3f44fe9ab45b7304aae7168e31403dc1fddbc032e14043f'});
export const MODULE_URL = `https://cdn.jsdelivr.net/gh/${SOURCE.repository}@${SOURCE.commit}/${SOURCE.file}`;
export function numberInput(text) {
if (typeof text !== 'string') throw new TypeError('Interface input must be text');
return text.trim() === '' ? undefined : Number(text);
}
export function calculate(engine, mode, inputs) {
if (!['assumed','implied'].includes(mode)) throw new RangeError('Unknown calculation direction');
if (inputs.unitCount > 10000000 || (Number.isInteger(inputs.unitCount) && !Number.isSafeInteger(inputs.unitCount))) throw new RangeError('Interface policy: unitCount must be a safe integer no greater than 10000000');
if (inputs.perUnitKw > 1000) throw new RangeError('Interface policy: perUnitKw must not exceed 1000 kW');
const args = {unitCount:inputs.unitCount,perUnitKw:inputs.perUnitKw};
const name = mode === 'assumed' ? 'diversifiedDemandKw' : 'impliedCoincidence';
const field = mode === 'assumed' ? 'coincidenceFactor' : 'measuredGroupPeakKw';
args[field] = inputs[field];
const result = engine[name](args);
const groupKw = mode === 'assumed' ? result.value : result.from.measuredGroupPeakKw;
const factor = mode === 'assumed' ? result.from.coincidenceFactor : result.value;
if (![result.value,result.from.unrestrictedKw,groupKw,factor].every(Number.isFinite)) throw new RangeError('Interface policy: nonfinite result refused');
if (result.from.unrestrictedKw <= 0 || groupKw <= 0 || factor <= 0 || factor > 1) throw new RangeError('Interface policy: inconsistent result refused');
return {schema:'galaxy-demand-lab.v1',source:SOURCE,mode,assumption:'Synthetic illustration; supplied values are not verified measurements.',function:name,inputs:args,quantity:result.quantity,value:result.value,unit:result.unit,from:result.from,groupKw,factor,notEstablished:['connection point','firm capacity','future coincidence','time series','equipment sizing']};
}Model Test
A test in the iterations folder of Galaxies Wafers that checks Model, using SHA-256.
testgalaxies-wafers / iterations/13-diversified-demand/model.test.mjs · lines 1–21 of 21 · Not reached from any entry point (candidate for review)
- What it does
- It tests its inputs. Uses libraries node:test, node:assert/strict, node:crypto, node:fs/promises. Side effects: reads or writes files; makes network requests.
- What it achieves
- The engine remains external. Only the reviewed, hash-matching source may execute.
- Why it matters
- Guards the behaviour of Model.
- Application
- galaxies-wafers · iterations/13-diversified-demand · test
- Uses
- Model (import), node:test, node:assert/strict, node:crypto, node:fs/promises
- 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
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/13-diversified-demand/model.test.mjs:1-21 · blob f7472f6bde022503cbfb5044598aa2946182667d · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, network · domain stage: unknown · users: none · canonical: unreached_review
import test from 'node:test';
import assert from 'node:assert/strict';
import {createHash} from 'node:crypto';
import {readFile} from 'node:fs/promises';
import {SOURCE,MODULE_URL,numberInput,calculate} from './model.mjs';
// The engine remains external. Only the reviewed, hash-matching source may execute.
const bytes=process.env.ENGINE_FILE?await readFile(process.env.ENGINE_FILE):await(async()=>{const response=await fetch(MODULE_URL,{signal:AbortSignal.timeout(15000)});assert.equal(response.status,200);return Buffer.from(await response.arrayBuffer());})();
assert.equal(createHash('sha256').update(bytes).digest('hex'),SOURCE.sha256);
const engine=await import(`data:text/javascript;base64,${bytes.toString('base64')}`);
const base={unitCount:100,perUnitKw:7,coincidenceFactor:0.3};
test('explicit assumption yields aggregate210kW,700kW unrestricted',()=>{const r=calculate(engine,'assumed',base);assert.equal(r.value,210);assert.equal(r.groupKw,210);assert.equal(r.from.unrestrictedKw,700);assert.equal(r.unit,'kW');assert.equal(r.source.commit,SOURCE.commit);});
test('supplied210kW implies0.3, not a verified measurement',()=>{const r=calculate(engine,'implied',{unitCount:100,perUnitKw:7,measuredGroupPeakKw:210});assert.equal(r.value,0.3);assert.equal(r.groupKw,210);assert.equal(r.unit,'dimensionless');assert.match(r.assumption,/not verified/);});
test('unity reaches unrestricted total',()=>assert.equal(calculate(engine,'assumed',{...base,coincidenceFactor:1}).value,700));
test('blank stays missing and engine supplies refusal, no factor default',()=>{assert.equal(numberInput(' '),undefined);assert.throws(()=>calculate(engine,'assumed',{...base,coincidenceFactor:undefined}),/coincidenceFactor must be a finite number/);});
test('zero and percentage-as-fraction are refused by source',()=>{for(const value of[0,-0.1,20])assert.throws(()=>calculate(engine,'assumed',{...base,coincidenceFactor:value}),RangeError);});
test('fractional count and nonfinite inputs refused',()=>{assert.throws(()=>calculate(engine,'assumed',{...base,unitCount:1.5}),/whole number/);assert.throws(()=>calculate(engine,'assumed',{...base,coincidenceFactor:NaN}),TypeError);assert.throws(()=>calculate(engine,'assumed',{...base,perUnitKw:0}),/greater than zero/);});
test('peak above total refused',()=>assert.throws(()=>calculate(engine,'implied',{unitCount:100,perUnitKw:7,measuredGroupPeakKw:701}),/exceeds the unrestricted total/));
test('interface bounds are identified as policy',()=>{assert.throws(()=>calculate(engine,'assumed',{...base,unitCount:10000001}),/Interface policy/);assert.throws(()=>calculate(engine,'assumed',{...base,perUnitKw:1001}),/Interface policy/);});
test('direction validated',()=>assert.throws(()=>calculate(engine,'other',base),/Unknown calculation direction/));
test('finite output guard does not trust arbitrary injected result',()=>{assert.throws(()=>calculate({diversifiedDemandKw:()=>({value:Infinity,from:{unrestrictedKw:700,coincidenceFactor:0.3}})},'assumed',base),/nonfinite result/);});
test('record is finite serializable and names what remains unestablished',()=>{const r=calculate(engine,'assumed',base);assert.deepEqual(JSON.parse(JSON.stringify(r)),r);assert.ok(r.notEstablished.includes('firm capacity'));assert.equal(Object.keys(engine.NOT_COMPUTED).length,4);});Iterations — 14 Electrical Hops
A JavaScript module in Galaxies Wafers that draws topology query and transformers, using SHA-256.
rendergalaxies-wafers / iterations/14-electrical-hops/app.mjs · lines 1–60 of 60 · Not reached from any entry point (candidate for review) · pattern register (shared by 59 files)
- What it does
- It draws topology query and transformers. Defines 7 functions or classes, including $, svg, text, draw, clear. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain terms in the code: transformers. README: "The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/202609151339."
- Inputs & outputs
- Out: JSON file topology-query.json; downloaded file topology-query.json.
- What it achieves
- It is built from the SVG step (`svg`), the text step (`text`) and the draw step (`draw`). The README says: The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/. Its code works with 9999 MVA. It responds to submit, input and change events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- galaxies-wafers · iterations/14-electrical-hops · JavaScript module
- Uses
- Fixture (import), Model (import)
- Used by
- none found
- Produces
- $, svg, text, draw, clear, refresh, register
- Defines here
- $, svg, text, draw, clear, refresh, register
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/14-electrical-hops/app.mjs:1-60 · blob 22de94a0fead8e4c7f4616772bc1aea2812bff07 · GitHub at these lines
- State
- achieves: readme · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unreached_review
import {product} from './fixture.mjs';
import {PIN,BASE,SOURCES,query,edgeKey} from './model.mjs';
const $=id=>document.getElementById(id);
const wideCoords={COWL1:[95,70],COWL4:[95,225],DIDC4:[390,225],STRA4:[700,225],ISLE1:[390,375],PLCH4:[390,70]};
const narrowCoords={COWL1:[65,65],COWL4:[65,270],DIDC4:[265,270],STRA4:[265,480],ISLE1:[65,480],PLCH4:[265,65]};
const narrow=matchMedia('(max-width:760px)');
const NS='http://www.w3.org/2000/svg';
let engine,index,current;
function svg(tag,attrs,parent=$('network')){const element=document.createElementNS(NS,tag);for(const[key,value]of Object.entries(attrs))element.setAttribute(key,String(value));parent.append(element);return element;}
function text(x,y,value,cls){const element=svg('text',{x,y,'text-anchor':'middle',class:cls||''});element.textContent=value;}
function draw(){
const coords=narrow.matches?narrowCoords:wideCoords;
$('network').setAttribute('viewBox',narrow.matches?'0 0 400 550':'0 0 820 420');
$('network').replaceChildren();
const refused=new Set((current?.route?.refusals||[]).map(row=>edgeKey(row.at_node,row.to_node)));
for(const row of [...product.circuits,...product.transformers]){const[a,b]=[coords[row.node_1],coords[row.node_2]];svg('line',{x1:a[0],y1:a[1],x2:b[0],y2:b[1],class:`edge${refused.has(edgeKey(row.node_1,row.node_2))?' refused':''}`});}
for(const[step,row]of(current?.route?.path||[]).entries()){const[a,b]=[coords[row.from_node],coords[row.to_node]];svg('line',{x1:a[0],y1:a[1],x2:b[0],y2:b[1],pathLength:1,class:'route',style:`--delay:${step*0.65}s`});}
const tx=narrow.matches?65:95,ty=narrow.matches?156:139;
svg('circle',{cx:tx,cy:ty,r:17,class:'transformer'});svg('circle',{cx:tx,cy:ty+19,r:17,class:'transformer'});
for(const row of product.nodes){const[x,y]=coords[row.node];svg('circle',{cx:x,cy:y,r:10,class:'node'});text(x,y-23,row.node);text(x,y+33,`${row.voltage_consistent_with_site?row.voltage_kv:'undeclared'}${row.voltage_consistent_with_site?' kV':''}`,'kv');}
}
for(const id of ['from','to'])for(const site of product.sites){const option=document.createElement('option');option.value=site.code;option.textContent=`${site.code} · ${site.name}`;$(id).append(option);}
$('to').value='STRA';
$('provenance').textContent=`Ventusltd/ventus-grid-engine @ ${PIN}`;
for(const source of [...SOURCES,{file:'proofs/electrical-distance.proof.mjs'}]){const li=document.createElement('li');const link=document.createElement('a');link.href=`https://github.com/Ventusltd/ventus-grid-engine/blob/${PIN}/${source.file}`;link.textContent=source.file;li.append(link);if(source.sha256)li.append(` · SHA256 ${source.sha256}`);$('sources').append(li);}
function clear(){current=null;$('path').replaceChildren();$('refusals').replaceChildren();$('download').disabled=true;$('replay').disabled=true;$('headline').textContent='No result';$('neighbours').textContent='No current result.';$('record').textContent='No current result.';}
function refresh(){
clear();if(!engine){draw();return;}
try{
const budget=$('budget').value.trim()===''?NaN:Number($('budget').value);
current=query(engine,index,{from:$('from').value,to:$('to').value,budget,voltage:$('voltage').value==='all'?null:Number($('voltage').value)});
const route=current.route;
$('status').textContent=route?'Computed by the pinned search modules':'Unknown site or unavailable compatible graph';
$('headline').textContent=route?.reached?`${route.hops} ${route.hops===1?'hop':'hops'}`:'Not reached';
$('reason').textContent=route?.reason || (route?.reached?'Fewest-hop path in this fixture and query. This is not available capacity.':'The module returned no route object.');
for(const[step,row]of(route?.path||[]).entries()){const li=document.createElement('li');li.textContent=`${row.from_node} → ${row.to_node} · ${row.kind} · ${row.from_voltage_kv??'undeclared'} → ${row.to_voltage_kv??'undeclared'} kV`;if(row.ratings_mva?.winter===9999)li.append(' · 9999 MVA fixture placeholder carried unchanged, not headroom');$('path').append(li);}
for(const refusal of route?.refusals||[]){const li=document.createElement('li');li.textContent=`${refusal.at_node} → ${refusal.to_node}: ${refusal.reason}`;$('refusals').append(li);}
if(!$('refusals').children.length){const li=document.createElement('li');li.textContent='None reported by this bounded search. This is not validation of all fixture edges.';$('refusals').append(li);}
$('neighbours').textContent=current.neighbourhood?.sites.length?current.neighbourhood.sites.map(site=>`${site.code}: ${site.hops} ${site.hops===1?'hop':'hops'}`).join(' · '):'No other sites returned within this origin/budget query.';
$('record').textContent=JSON.stringify(current,null,2);$('download').disabled=false;$('replay').disabled=!route?.path?.length;
}catch(error){current=null;$('status').textContent=`REFUSED · ${error.name}`;$('reason').textContent=error.message;}
draw();
}
$('controls').addEventListener('submit',event=>event.preventDefault());$('controls').addEventListener('input',refresh);$('controls').addEventListener('change',refresh);
$('replay').addEventListener('click',draw);
narrow.addEventListener('change',draw);
$('download').addEventListener('click',()=>{if(!current)return;const url=URL.createObjectURL(new Blob([JSON.stringify(current,null,2)+'\n'],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download='topology-query.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);});
draw();
try{const[search,topology]=await Promise.all(SOURCES.map(source=>import(BASE+source.file)));engine=search;index=topology.index(product);if(!index)throw new Error('Fixture schema refused');refresh();}catch(error){clear();draw();$('status').textContent='Pinned module unavailable. No substitute search.';$('reason').textContent=error.message;}
if(document.modelContext?.registerTool){
const lifecycle=new AbortController();addEventListener('pagehide',()=>lifecycle.abort(),{once:true});
const register=tool=>{try{Promise.resolve(document.modelContext.registerTool(tool,{signal:lifecycle.signal})).catch(()=>{});}catch{}};
register({name:'read_hop_query',description:'Read the current synthetic topology query without changing it.',inputSchema:{type:'object',properties:{},additionalProperties:false},annotations:{readOnlyHint:true,untrustedContentHint:false},execute(input){if(!input || typeof input!=='object' || Array.isArray(input) || Object.keys(input).length)throw new TypeError('Expected empty object');return curr … [line shortened here: 493 characters; full line on GitHub]
register({name:'configure_hop_query',description:'Set origin, destination and hop budget, then update the visible schematic. This does not establish real connectivity or capacity.',inputSchema:{type:'object',properties:{from:{type:'string',enum:product.sites.map(s=>s.code)},to:{type:'string',enum:product.sites.map(s=>s.code)},budget:{type:'integer',minimum:0,maximum:6},voltage:{enum:[null,33,132 … [line shortened here: 553 characters; full line on GitHub]
if(!engine || !index)throw new Error('Pinned modules unavailable');
if(!input || typeof input!=='object' || Array.isArray(input) || Object.keys(input).some(key=>!['from','to','budget','voltage'].includes(key)))throw new TypeError('Unexpected query fields');
if(![input.from,input.to].every(code=>product.sites.some(site=>site.code===code)) || ![null,33,132,400].includes(input.voltage))throw new RangeError('Select available fixture sites and origin voltage');
query(engine,index,input);$('from').value=input.from;$('to').value=input.to;$('budget').value=String(input.budget);$('voltage').value=input.voltage===null?'all':String(input.voltage);refresh();return JSON.parse(JSON.stringify(current));
}});
}Browser Check
A JavaScript module in the iterations folder of Galaxies Wafers that uses SHA-256.
rendergalaxies-wafers / iterations/14-electrical-hops/browser-check.mjs · lines 1–33 of 33 · Not reached from any entry point (candidate for review)
- What it does
- It draws its content. 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 sub33kv_design (voltage levels 33kV (all 33kV or below)): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: 33kV.
- Inputs & outputs
- Out: JSON file receipt.json. Voltage levels named: 33kV.
- What it achieves
- Its code works with 33 kV and 9999 MVA.
- Why it matters
- No other file in the estate was found to import it.
- Application
- galaxies-wafers · iterations/14-electrical-hops · JavaScript module
- Uses
- Model (script call)
- 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
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/14-electrical-hops/browser-check.mjs:1-33 · blob 58572941dc0c360a79c4bf04b14675d632f0983b · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, network, process · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
import{spawn}from'node:child_process';import{mkdir,writeFile,readFile}from'node:fs/promises';import path from'node:path';import{createHash}from'node:crypto';import assert from'node:assert/strict';import{BASE,SOURCES}from'./model.mjs';
const playwright=await import(process.env.PLAYWRIGHT_MODULE || 'playwright');const output=process.env.PROOF_OUTPUT || path.resolve('browser-evidence');await mkdir(output,{recursive:true});
const url=process.env.PAGE_URL || 'http://127.0.0.1:8779/';const server=process.env.PAGE_URL?null:spawn(process.platform==='win32'?'python':'python3',['-m','http.server','8779','--bind','127.0.0.1'],{stdio:'ignore'});const results=[];
try{
for(let n=0;n<30;n++){try{if((await fetch(url)).ok)break;}catch{}if(n===29)throw Error('Preview unavailable');await new Promise(r=>setTimeout(r,100));}
for(const name of(process.env.BROWSER_ENGINES || 'chromium,webkit').split(',')){
const browser=await playwright[name].launch({headless:true,...(name==='chromium' && process.env.CHROME_PATH?{executablePath:process.env.CHROME_PATH}:{})});
try{for(const width of[390,1400]){
const context=await browser.newContext({viewport:{width,height:width===390?844:900},deviceScaleFactor:width===390?3:1,isMobile:width===390,hasTouch:width===390,acceptDownloads:true});const page=await context.newPage();page.setDefaultTimeout(12000);
const errors=[],failed=[],sourceResponses=[];let negative=false;const receipt={engine:name,version:browser.version(),width,dpr:width===390?3:1,started:new Date().toISOString(),pass:false,errors,failed_requests:failed};
page.on('pageerror',e=>{if(!negative)errors.push(e.message);});page.on('console',m=>{if(!negative && m.type()==='error')errors.push(m.text());});page.on('requestfailed',r=>{if(!negative)failed.push(r.url());});
page.on('response',r=>{if(negative)return;if(r.status()>=400)failed.push(r.url());const source=SOURCES.find(s=>BASE+s.file===r.url());if(source)sourceResponses.push(r.body().then(bytes=>({file:source.file,status:r.status(),sha256:createHash('sha256').update(bytes).digest('hex')})));});
try{
await page.goto(url);await page.waitForFunction(()=>document.querySelector('#headline').textContent==='2 hops');assert.equal(await page.locator('#path li').count(),2);assert.equal(await page.locator('.route').count(),2);assert.equal(await page.locator('.edge.refused').count(),1);
await page.waitForFunction(()=>[...document.querySelectorAll('.route')].every(e=>Number.parseFloat(getComputedStyle(e).strokeDashoffset)===0));
await page.screenshot({path:path.join(output,`${name}-${width}-route.png`),fullPage:true});
await page.locator('#to').selectOption('DIDC');await page.locator('#voltage').selectOption('132');assert.equal(await page.locator('#headline').innerText(),'2 hops');assert.match(await page.locator('#path li').first().innerText(),/transformer/);
await page.locator('#budget').fill('1');assert.equal(await page.locator('#headline').innerText(),'Not reached');assert.equal(await page.locator('.route').count(),0);
await page.locator('#budget').fill('1.5');assert.match(await page.locator('#status').innerText(),/REFUSED/);assert.equal(await page.locator('#download').isDisabled(),true);
await page.locator('#budget').fill('6');await page.locator('#voltage').selectOption('33');assert.match(await page.locator('#reason').innerText(),/no node at 33 kV/);
await page.locator('#voltage').selectOption('all');await page.locator('#to').selectOption('ISLE');assert.equal(await page.locator('#headline').innerText(),'Not reached');assert.match(await page.locator('#refusals').innerText(),/different declared voltages/);
await page.locator('#to').selectOption('COWL');assert.equal(await page.locator('#headline').innerText(),'0 hops');assert.equal(await page.locator('#path li').count(),0);
await page.locator('#to').selectOption('PLCH');assert.match(await page.locator('#path').innerText(),/9999 MVA fixture placeholder/);
await page.getByText('Machine detail',{exact:true}).click();const promise=page.waitForEvent('download');await page.locator('#download').click();const download=await promise;const filename=path.join(output,`${name}-${width}-query.json`);await download.saveAs(filename);const record=JSON.parse(await readFile(filename,'utf8'));assert.equal(record.route.path[0].ratings_mva.winter,9999);assert.e … [line shortened here: 426 characters; full line on GitHub]
await page.emulateMedia({reducedMotion:'reduce'});assert.equal(await page.locator('.route').first().evaluate(e=>getComputedStyle(e).animationName),'none');
receipt.layout=await page.evaluate(()=>({width:innerWidth,scrollWidth:document.documentElement.scrollWidth,overflowing:[...document.querySelectorAll('main *')].filter(e=>e.getBoundingClientRect().right>innerWidth+1).slice(0,12).map(e=>({tag:e.tagName,id:e.id,right:e.getBoundingClientRect().right}))}));
receipt.overflow=receipt.layout.scrollWidth>receipt.layout.width+1;await page.screenshot({path:path.join(output,`${name}-${width}-details.png`),fullPage:true});assert.equal(receipt.overflow,false);receipt.source_responses=await Promise.all(sourceResponses);for(const source of SOURCES){const observed=receipt.source_responses.filter(r=>r.file===source.file);assert.ok(observed.length);for(con … [line shortened here: 484 characters; full line on GitHub]
assert.deepEqual(errors,[]);assert.deepEqual(failed,[]);negative=true;await page.route(BASE+SOURCES[0].file,r=>r.abort('failed'));await page.reload();await page.waitForFunction(()=>document.querySelector('#status').textContent.includes('module unavailable'));assert.equal(await page.locator('.route').count(),0);assert.equal(await page.locator('#download').isDisabled(),true);receipt.module_u … [line shortened here: 511 characters; full line on GitHub]
}catch(error){receipt.error=error.stack;receipt.pass=false;}finally{receipt.finished=new Date().toISOString();results.push(receipt);await context.close();}
}}finally{await browser.close();}
}
}finally{server?.kill();await writeFile(path.join(output,'receipt.json'),JSON.stringify({source_commit:process.env.GITHUB_SHA || null,url,results},null,2)+'\n');}
console.log(JSON.stringify({cases:results.length,passed:results.filter(r=>r.pass).length}));if(!results.length || results.some(r=>!r.pass))process.exitCode=1;Fixture
A JavaScript module in the iterations folder of Galaxies Wafers covering overhead lines (OHL).
othergalaxies-wafers / iterations/14-electrical-hops/fixture.mjs · lines 1–10 of 10 · Not reached from any entry point (candidate for review)
- Why it exists in the grid workflow
- Domain terms in the code: overhead lines (OHL).
- Downstream impact
- Used directly by 1 file: Iterations — 14 Electrical Hops (galaxies-wafers).
- What it achieves
- Data-only transcription of PRODUCT in the pinned electrical-distance proof.
- Why it matters
- Imported by Iterations — 14 Electrical Hops.
- Application
- galaxies-wafers · iterations/14-electrical-hops · JavaScript module
- Uses
- none found
- Used by
- imported by Iterations — 14 Electrical Hops (import)
- Produces
- product
- 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
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/14-electrical-hops/fixture.mjs:1-10 · blob ec67129542ada78ad3b690eacb754fc3835b663e · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: unknown · effects: none found · domain stage: unknown · users: none · canonical: unreached_review
// Data-only transcription of PRODUCT in the pinned electrical-distance proof.
// Synthetic identifiers; this is not a map of the real network.
export const product={
schema:'data-grid-gb.transmission-network.v1',
sites:[{code:'COWL',name:'Cowley',transmission_owner:'NGET',voltages_kv:[400,132]},{code:'DIDC',name:'Didcot',transmission_owner:'NGET',voltages_kv:[400]},{code:'STRA',name:'Strand',transmission_owner:'NGET',voltages_kv:[400]},{code:'ISLE',name:'Isolated',transmission_owner:'NGET',voltages_kv:[132]},{code:'PLCH',name:'Placeholder',transmission_owner:'NGET',voltages_kv:[400]}],
nodes:[{node:'COWL4',site_code:'COWL',voltage_kv:400,voltage_consistent_with_site:true},{node:'COWL1',site_code:'COWL',voltage_kv:132,voltage_consistent_with_site:true},{node:'DIDC4',site_code:'DIDC',voltage_kv:400,voltage_consistent_with_site:true},{node:'STRA4',site_code:'STRA',voltage_kv:400,voltage_consistent_with_site:true},{node:'ISLE1',site_code:'ISLE',voltage_kv:132,voltage_consistent_wi … [line shortened here: 496 characters; full line on GitHub]
circuits:[{node_1:'COWL4',node_2:'DIDC4',circuit_type:'OHL',transmission_owner:'NGET',winter_mva:1200,spring_mva:1100,summer_mva:900,autumn_mva:1150,r_pct_100mva:0.5,x_pct_100mva:5,b_pct_100mva:10,ohl_km:20},{node_1:'DIDC4',node_2:'STRA4',circuit_type:'OHL',transmission_owner:'NGET',winter_mva:800,spring_mva:750,summer_mva:600,autumn_mva:700,ohl_km:15},{node_1:'COWL4',node_2:'ISLE1',circuit_type … [line shortened here: 631 characters; full line on GitHub]
transformers:[{node_1:'COWL4',node_2:'COWL1',rating_mva:240,transmission_owner:'NGET'}],
planned_changes:[{node_1:'STRA4',node_2:'FUTR1',year:2029,status:'proposed',asset:'new circuit'}]
};Model
A JavaScript module in the iterations folder of Galaxies Wafers that uses SHA-256. It is built from the edge key helper (`edgeKey`).
transformgalaxies-wafers / iterations/14-electrical-hops/model.mjs · lines 1–13 of 13 · Not reached from any entry point (candidate for review) · pattern query (shared by 6 files)
- What it does
- It calculates its inputs. Defines query, edgeKey.
- Downstream impact
- Used directly by 2 files: Iterations — 14 Electrical Hops (galaxies-wafers); Browser Check (galaxies-wafers).
- What it achieves
- Defines `query` and `edgeKey`.
- Why it matters
- Imported by Iterations — 14 Electrical Hops. Run by Browser Check.
- Application
- galaxies-wafers · iterations/14-electrical-hops · JavaScript module
- Uses
- none found
- Used by
- imported by Iterations — 14 Electrical Hops (import), run by Browser Check (script call)
- Produces
- PIN, BASE, SOURCES, query, edgeKey
- Defines here
- query, edgeKey
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/14-electrical-hops/model.mjs:1-13 · blob fffd6ee60a708cfc571f9d7269dc3934b0068435 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unreached_review
export const PIN='d9cd18b0e2034325814924e6e4a0e958014f2748';
export const BASE=`https://cdn.jsdelivr.net/gh/Ventusltd/ventus-grid-engine@${PIN}/`;
export const SOURCES=[{file:'engine/electrical-distance.js',sha256:'b6b55e2207e29a7078f0ab9a1ee0575125a0252386907e93434b78aeead2c4a3'},{file:'engine/network-topology.js',sha256:'cf04c754e550e594ddd09096ec2b2c04c0082058126897c6e7afdeee92f7561c'}];
export function query(engine,index,{from,to,budget,voltage}) {
if(typeof from!=='string' || typeof to!=='string' || !from || !to)throw new TypeError('Interface policy: supply origin and destination identifiers');
if(!Number.isInteger(budget) || budget<0 || budget>6)throw new RangeError('Interface policy: hop budget must be an integer from 0 to 6');
if(voltage!==null && (!Number.isFinite(voltage) || voltage<=0))throw new RangeError('Interface policy: origin voltage must be positive kV or unfiltered');
const options={maxHops:budget,...(voltage===null?{}:{voltageKv:voltage})};
const route=engine.between(index,from,to,options);
const neighbourhood=engine.within(index,from,{hops:budget,...(voltage===null?{}:{voltageKv:voltage})});
return {schema:'galaxy-hop-lab.v1',source:{repository:'Ventusltd/ventus-grid-engine',commit:PIN,files:SOURCES},fixture:'Synthetic PRODUCT from proofs/electrical-distance.proof.mjs at the same pin; not an actual network map.',inputs:{from,to,budget,voltage},route,neighbourhood};
}
export const edgeKey=(a,b)=>[a,b].sort().join('|');Model Test
A test in the iterations folder of Galaxies Wafers that uses SHA-256.
testgalaxies-wafers / iterations/14-electrical-hops/model.test.mjs · lines 1–17 of 17 · Not reached from any entry point (candidate for review)
- What it does
- It tests its inputs. Uses libraries node:test. Side effects: reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain terms in the code: 132kV, 33kV.
- Inputs & outputs
- Voltage levels named: 132kV, 33kV.
- What it achieves
- Its code works with 132 kV and 33 kV.
- Why it matters
- No other file in the estate was found to import it.
- Application
- galaxies-wafers · iterations/14-electrical-hops · test
- Uses
- node:test
- 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
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/14-electrical-hops/model.test.mjs:1-17 · blob 35e1c3a5c618e9320de71b662a736054fc45efe4 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem, network · domain stage: unknown · users: none · canonical: unreached_review
import test from 'node:test';import assert from 'node:assert/strict';import {createHash}from'node:crypto';import{readFile}from'node:fs/promises';import path from'node:path';
import {product}from'./fixture.mjs';import{BASE,SOURCES,query}from'./model.mjs';
const modules=await Promise.all(SOURCES.map(async source=>{const bytes=process.env.ENGINE_DIRECTORY?await readFile(path.join(process.env.ENGINE_DIRECTORY,source.file)):await(async()=>{const r=await fetch(BASE+source.file,{signal:AbortSignal.timeout(15000)});assert.equal(r.status,200);return Buffer.from(await r.arrayBuffer());})();assert.equal(createHash('sha256').update(bytes).digest('hex'),source … [line shortened here: 486 characters; full line on GitHub]
const[engine,topology]=modules;const index=topology.index(product);const input={from:'COWL',to:'STRA',budget:6,voltage:null};const run=patch=>query(engine,index,{...input,...patch});
test('two-hop source search and ordered nodes',()=>{const r=run({}).route;assert.equal(r.hops,2);assert.equal(r.reached,true);assert.deepEqual(r.path.map(p=>p.to_node),['DIDC4','STRA4']);});
test('132kV origin crosses one transformer then a circuit',()=>{const r=run({to:'DIDC',voltage:132}).route;assert.equal(r.hops,2);assert.equal(r.transformers_crossed,1);assert.equal(r.voltage_changes,1);assert.equal(r.path[0].from_node,'COWL1');});
test('mixed-declared-voltage circuit refused',()=>{const r=run({to:'ISLE'}).route;assert.equal(r.reached,false);assert.equal(r.hops,null);assert.match(r.refusals[0].reason,/different declared voltages/);});
test('one-hop budget excludes STRA',()=>{const r=run({budget:1});assert.equal(r.route.reached,false);assert.deepEqual(r.neighbourhood.sites.map(s=>s.code),['DIDC','PLCH']);});
test('same site has zero hops and no path',()=>{const r=run({to:'COWL'}).route;assert.equal(r.reached,true);assert.equal(r.hops,0);assert.deepEqual(r.path,[]);});
test('absent origin voltage distinct from unknown site',()=>{assert.match(run({voltage:33}).route.reason,/no node at33 kV|no node at 33 kV/);assert.equal(run({to:'NOWHERE'}).route,null);});
test('planned change not in current graph',()=>{assert.equal(index.graph().has('FUTR1'),false);assert.ok(index.graph().edgesAt('STRA4').every(e=>e.kind!=='planned_change'));});
test('placeholder MVA preserved, no headroom inferred',()=>{assert.equal(run({to:'PLCH'}).route.path[0].ratings_mva.winter,9999);});
test('source carries unsummed per-hop impedance',()=>{assert.deepEqual(run({}).route.path[0].parameters_pct_100mva,{r_pct:.5,x_pct:5,b_pct:10});assert.equal(run({}).route.path[1].parameters_pct_100mva,null);});
test('two-hop neighbourhood has three sites',()=>assert.equal(run({budget:2}).neighbourhood.counts.sites,3));
test('strict interface budget, no silent type fallback',()=>{for(const budget of[-1,1.5,7,NaN,'2'])assert.throws(()=>run({budget}),/Interface policy/);});
test('strict voltage type',()=>assert.throws(()=>run({voltage:'132'}),/Interface policy/));
if(process.env.TRUSTED_FIXTURE)test('fixture equals separately captured proof PRODUCT',async()=>assert.deepEqual(product,JSON.parse(await readFile(process.env.TRUSTED_FIXTURE,'utf8')).c1_product));Browser Check
A JavaScript module in the iterations folder of Galaxies Wafers that uses SHA-256.
rendergalaxies-wafers / iterations/16-firm-capacity/browser-check.mjs · lines 1–25 of 25 · Not reached from any entry point (candidate for review)
- What it does
- It draws its content. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes.
- Inputs & outputs
- Out: JSON file receipt.json.
- What it achieves
- Its code works with 30 MVA, 0 MVA and 120 MVA.
- Why it matters
- No other file in the estate was found to import it.
- Application
- galaxies-wafers · iterations/16-firm-capacity · JavaScript module
- Uses
- Model (script call)
- 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
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/16-firm-capacity/browser-check.mjs:1-25 · blob 7a09c7074c33eb19f3d2cb27ebd38c8756020bc4 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, network, process · domain stage: unknown · users: none · canonical: unreached_review
import{spawn}from'node:child_process';import{mkdir,writeFile,readFile}from'node:fs/promises';import path from'node:path';import{createHash}from'node:crypto';import assert from'node:assert/strict';import{SOURCE,MODULE_URL}from'./model.mjs';
const playwright=await import(process.env.PLAYWRIGHT_MODULE || 'playwright');const output=process.env.PROOF_OUTPUT || path.resolve('browser-evidence');await mkdir(output,{recursive:true});const url=process.env.PAGE_URL || 'http://127.0.0.1:8779/';const server=process.env.PAGE_URL?null:spawn(process.platform==='win32'?'python':'python3',['-m','http.server','8779','--bind','127.0.0.1'],{stdio:'ignor … [line shortened here: 422 characters; full line on GitHub]
try{
for(let n=0;n<30;n++){try{if((await fetch(url)).ok)break;}catch{}if(n===29)throw Error('Preview unavailable');await new Promise(r=>setTimeout(r,100));}
for(const name of(process.env.BROWSER_ENGINES || 'chromium,webkit').split(',')){
const browser=await playwright[name].launch({headless:true,...(name==='chromium' && process.env.CHROME_PATH?{executablePath:process.env.CHROME_PATH}:{})});
try{for(const width of[390,1400]){
const context=await browser.newContext({viewport:{width,height:width===390?844:900},deviceScaleFactor:width===390?3:1,isMobile:width===390,hasTouch:width===390,acceptDownloads:true});const page=await context.newPage();page.setDefaultTimeout(12000);const errors=[],failed=[],responses=[];let negative=false;const receipt={engine:name,version:browser.version(),width,dpr:width===390?3:1,started:n … [line shortened here: 466 characters; full line on GitHub]
page.on('pageerror',e=>{if(!negative)errors.push(e.message);});page.on('console',m=>{if(!negative && m.type()==='error')errors.push(m.text());});page.on('requestfailed',r=>{if(!negative)failed.push(r.url());});page.on('response',r=>{if(negative)return;if(r.status()>=400)failed.push(r.url());if(r.url()===MODULE_URL)responses.push(r.body().then(bytes=>({status:r.status(),sha256:createHash('sha … [line shortened here: 441 characters; full line on GitHub]
try{
await page.goto(url);await page.waitForFunction(()=>document.querySelector('#firm').textContent==='30MVA');assert.equal(await page.locator('#installed').innerText(),'60MVA');assert.match(await page.locator('#utilisation').innerText(),/140%/);await page.waitForFunction(()=>Number(getComputedStyle(document.querySelector('.removed')).opacity)<=.251);await page.screenshot({path:path.join(outpu … [line shortened here: 447 characters; full line on GitHub]
await page.getByRole('button',{name:'Unequal units',exact:true}).click();assert.equal(await page.locator('#installed').innerText(),'120MVA');assert.equal(await page.locator('#firm').innerText(),'30MVA');assert.match(await page.locator('#comparison').innerText(),/does not say every possible unit outage/);
await page.getByRole('button',{name:'One unit',exact:true}).click();assert.equal(await page.locator('#firm').innerText(),'0MVA');assert.match(await page.locator('#utilisation').innerText(),/No finite firm-utilisation/);
await page.getByText('Machine detail',{exact:true}).click();const promise=page.waitForEvent('download');await page.locator('#download').click();const download=await promise;const filename=path.join(output,`${name}-${width}-single.json`);await download.saveAs(filename);const record=JSON.parse(await readFile(filename,'utf8'));assert.equal(record.assessment.utilisationOfFirm.value,'Infinity') … [line shortened here: 443 characters; full line on GitHub]
await page.locator('#units').fill('30,,30');assert.match(await page.locator('#error').innerText(),/finite number/);assert.equal(await page.locator('#result').isVisible(),false);assert.equal(await page.locator('#download').isDisabled(),true);await page.locator('#units').fill('30,30');await page.locator('#demand').fill('0');assert.match(await page.locator('#error').innerText(),/greater than … [line shortened here: 407 characters; full line on GitHub]
await page.locator('#demand').fill('24');assert.match(await page.locator('#comparison').innerText(),/within the largest-unit-loss/);await page.getByRole('button',{name:'RUN · largest-unit loss',exact:true}).click();
await page.locator('#wafer').click();assert.match(await page.locator('#handoff').innerText(),/No numbered line established/);assert.equal(await page.locator('#code').getAttribute('href'),`https://github.com/${SOURCE.repository}/blob/${SOURCE.commit}/${SOURCE.file}`);
await page.emulateMedia({reducedMotion:'reduce'});assert.equal(await page.locator('.removed').evaluate(e=>getComputedStyle(e).animationName),'none');receipt.overflow=await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+1);assert.equal(receipt.overflow,false);await page.screenshot({path:path.join(output,`${name}-${width}-details.png`),fullPage:true});
receipt.source_responses=await Promise.all(responses);assert.ok(receipt.source_responses.length);for(const r of receipt.source_responses){assert.equal(r.status,200);assert.equal(r.sha256,SOURCE.sha256);}assert.deepEqual(errors,[]);assert.deepEqual(failed,[]);
negative=true;await page.route(MODULE_URL,r=>r.abort('failed'));await page.reload();await page.waitForFunction(()=>document.querySelector('#quick').textContent.includes('module unavailable'));assert.equal(await page.locator('#result').isVisible(),false);assert.equal(await page.locator('#download').isDisabled(),true);receipt.module_unavailable_refused=true;receipt.native_webmcp='Not exercis … [line shortened here: 453 characters; full line on GitHub]
}catch(error){receipt.pass=false;receipt.error=error.stack;}finally{receipt.finished=new Date().toISOString();results.push(receipt);await context.close();}
}}finally{await browser.close();}
}
}finally{server?.kill();await writeFile(path.join(output,'receipt.json'),JSON.stringify({source_commit:process.env.GITHUB_SHA || null,url,results},null,2)+'\n');}
console.log(JSON.stringify({cases:results.length,passed:results.filter(r=>r.pass).length}));if(!results.length || results.some(r=>!r.pass))process.exitCode=1;Model
A JavaScript module in the iterations folder of Galaxies Wafers that parses units (`parseUnits`) (units: MVA), using SHA-256. It parses number (`parseNumber`) and parses units (`parseUnits`).
ingestgalaxies-wafers / iterations/16-firm-capacity/model.mjs · lines 1–15 of 15 · Not reached from any entry point (candidate for review) · pattern parseNumber (shared by 2 files)
- What it does
- Defines parseNumber, parseUnits, calculate.
- Downstream impact
- Used directly by 1 file: Browser Check (galaxies-wafers).
- What it achieves
- Defines `parseNumber`, `parseUnits` and `calculate`. Its code works with 1000 MVA.
- Why it matters
- Run by Browser Check.
- Application
- galaxies-wafers · iterations/16-firm-capacity · JavaScript module
- Uses
- none found
- Used by
- run by Browser Check (script call)
- Produces
- SOURCE, MODULE_URL, parseNumber, parseUnits, calculate
- Defines here
- parseNumber, parseUnits, calculate
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/16-firm-capacity/model.mjs:1-15 · blob 34054122acbb014cd76e0b7231f5023f8e36ca50 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unreached_review
export const SOURCE={repository:'Ventusltd/ventus-grid-engine',commit:'d9cd18b0e2034325814924e6e4a0e958014f2748',file:'engine/firm-capacity.js',sha256:'2e855b2e829bb65d033b86330cf43bee6733ffaaa0eee696cbbd36f20cc4c54a'};
export const MODULE_URL=`https://cdn.jsdelivr.net/gh/${SOURCE.repository}@${SOURCE.commit}/${SOURCE.file}`;
export const parseNumber=text=>text.trim()===''?undefined:Number(text);
export const parseUnits=text=>text.split(',').map(parseNumber);
export function calculate(engine,{units,demandMva}){
if(!Array.isArray(units) || units.length<1 || units.length>6 || Array.from({length:units.length},(_,i)=>i).some(i=>!Object.hasOwn(units,i)))throw new TypeError('Interface policy: one to six dense unit ratings required');
if(units.some(n=>typeof n==='number' && Number.isFinite(n) && (n<0.001 || n>1000)) || demandMva>5000)throw new RangeError('Interface policy: each unit0.001–1000MVA; demand at most5000MVA');
const firm=engine.firmCapacityMva({units});
const assessment=engine.assessAgainstFirm({units,demandMva});
const{basis,...values}=assessment;
for(const key of ['firmMva','installedMva','demandMva','shortfallMva','utilisationOfInstalled'])if(!Number.isFinite(values[key]))throw new RangeError('Interface policy: nonfinite arithmetic refused');
if(values.firmMva===0 && values.utilisationOfFirm===Infinity)values.utilisationOfFirm={kind:'nonfinite',value:'Infinity',reason:'Positive demand divided by zero arithmetic firm capacity; not a finite percentage.'};
else if(!Number.isFinite(values.utilisationOfFirm))throw new RangeError('Interface policy: unexpected nonfinite firm utilisation');
return{schema:'galaxy-firm-lab.v1',source:SOURCE,fixture:'Synthetic caller-supplied ratings and demand, not an actual substation or connection assessment.',inputs:{units:[...units],demandMva},largestUnitMva:firm.from.largestUnitMva,assessment:values,notComputed:['spare capacity','connection availability','cyclic and emergency rating','security compliance'],sourceBasisOmitted:'The lab reports num … [line shortened here: 538 characters; full line on GitHub]
}Model Test
A test in the iterations folder of Galaxies Wafers that uses SHA-256.
testgalaxies-wafers / iterations/16-firm-capacity/model.test.mjs · lines 1–13 of 13 · Not reached from any entry point (candidate for review)
- What it does
- It tests its inputs. Uses libraries node:test. Side effects: reads or writes files; makes network requests.
- 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
- galaxies-wafers · iterations/16-firm-capacity · test
- Uses
- node:test
- 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
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/16-firm-capacity/model.test.mjs:1-13 · blob 005d08ebb44010d566ff11c3b879bcdd59d19095 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem, network · domain stage: unknown · users: none · canonical: unreached_review
import test from'node:test';import assert from'node:assert/strict';import{createHash}from'node:crypto';import{readFile}from'node:fs/promises';import{SOURCE,MODULE_URL,parseUnits,calculate}from'./model.mjs';
const bytes=process.env.ENGINE_FILE?await readFile(process.env.ENGINE_FILE):await(async()=>{const r=await fetch(MODULE_URL,{signal:AbortSignal.timeout(15000)});assert.equal(r.status,200);return Buffer.from(await r.arrayBuffer());})();assert.equal(createHash('sha256').update(bytes).digest('hex'),SOURCE.sha256);const engine=await import(`data:text/javascript;base64,${bytes.toString('base64')}`);cons … [line shortened here: 472 characters; full line on GitHub]
test('equal-unit arithmetic retains installed60/firm30/shortfall12',()=>{const r=run();assert.equal(r.assessment.installedMva,60);assert.equal(r.assessment.firmMva,30);assert.equal(r.assessment.shortfallMva,12);assert.equal(r.assessment.utilisationOfFirm,1.4);assert.equal(r.assessment.utilisationOfInstalled,.7);});
test('unequal units do not repeat overbroad source narrative',()=>{const r=run([90,30]);assert.equal(r.assessment.installedMva,120);assert.equal(r.assessment.firmMva,30);assert.ok(!('basis'in r.assessment));assert.match(r.sourceBasisOmitted,/overstate/);});
test('single unit preserves taggedInfinity, not silentnull',()=>{const r=run([30],10);assert.equal(r.assessment.firmMva,0);assert.equal(r.assessment.utilisationOfFirm.value,'Infinity');assert.equal(r.assessment.utilisationOfFirm.kind,'nonfinite');assert.deepEqual(JSON.parse(JSON.stringify(r)),r);});
test('three units and within-firm limit',()=>{const r=run([30,30,30],60);assert.equal(r.assessment.firmMva,60);assert.equal(r.assessment.withinFirm,true);});
test('demand above installed remains a comparison, not approval',()=>{const r=run([30],42);assert.equal(r.assessment.withinInstalled,false);assert.ok(r.notComputed.includes('connection availability'));});
test('sparse array refused before source checker skips holes',()=>assert.throws(()=>run(Array(1)),/dense unit/));
test('empty component is missing, not zero',()=>{assert.deepEqual(parseUnits('30,,30'),[30,undefined,30]);assert.throws(()=>run(parseUnits('30,,30')),/finite number/);});
test('zero or missing demand refused by source',()=>{assert.throws(()=>run([30,30],0),/greater than zero/);assert.throws(()=>calculate(engine,{units:[30,30],demandMva:undefined}),/finite number/);});
test('array/upper/lower interface bounds',()=>{assert.throws(()=>run([]),/Interface policy/);assert.throws(()=>run(Array(7).fill(30)),/Interface policy/);assert.throws(()=>run([1001]),/Interface policy/);assert.throws(()=>run([.0001]),/Interface policy/);});
test('input array not mutated',()=>{const units=[30,20,10];run(units);assert.deepEqual(units,[30,20,10]);});
test('serializable source provenance and exact largest',()=>{const r=run([10,20,30]);assert.equal(r.largestUnitMva,30);assert.equal(r.source.sha256,SOURCE.sha256);assert.deepEqual(JSON.parse(JSON.stringify(r)),r);});