In this section
- Solar Battery Energy Storage System (BESS) Topology V7 — Cable Geometry Visualiser Page render · cable-trench-or-drill / releases/202609052001/solar-bess-topology-v7/cable-geometry-visualiser/index.html lines 1–280
- Render Readiness interaction · cable-trench-or-drill / releases/202609052001/solar-bess-topology-v7/cable-geometry-visualiser/render-readiness.js lines 1–32
- Route Constraints ingest · cable-trench-or-drill / src/route-constraints/route-constraints.js lines 1–190
- Derive Cable electrical · cable-trench-or-drill / tools/derive_cable.py lines 1–47
- Import Original storage · cable-trench-or-drill / tools/import_original.py lines 1–83
- Render Readiness Test test · cable-trench-or-drill / tools/render-readiness.test.mjs lines 1–62
Solar Battery Energy Storage System (BESS) Topology V7 — Cable Geometry Visualiser Page
A web page in Cable Trench or Drill covering cables, 132kV, 33kV and solar, using BS EN 50618 and BS 7671, and uses data from UK Power Networks open data.
rendercable-trench-or-drill / releases/202609052001/solar-bess-topology-v7/cable-geometry-visualiser/index.html · lines 1–280 of 280 · version 2026-09-05 20:01 · Entry point
- What it does
- It draws cables, 132kV, 33kV and solar. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'bess'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: cables, 132kV, 33kV, solar, 110kV, 66kV.
- Inputs & outputs
- In: form fields (user input). Out: web page. Voltage levels named: 132kV, 110kV, 66kV, 33kV, 20kV, 15kV, 10kV, 6kV.
- Downstream impact
- Used directly by 4 files: GlobalGrid2050 — Solar Battery Energy Storage System (BESS) Topology V7 Page (globalgrid2050, https://globalgrid2050.com/solar-bess-topology-v7/); Solar Battery Energy Storage System (BESS) Topology V7 — Module Layout Page (globalgrid2050, https://globalgrid2050.com/solar-bess-topology-v7/module-layout/); Solar Battery Energy Storage System (BESS) Topology V7 — Module Layout Page (globalgrid2050, https://globalgrid2050.com/testcode/202609051958/layer-apps/solar-bess-topology-v7/module-layout/); Spider Maya — V1 Page (spiders, https://ventusltd.github.io/spiders/spider_maya/v1/). Reached from 137 other entry points, including Iterations — 43 Registry Growth Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/43-registry-growth/); Iterations — 47 Federation Honesty Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/47-federation-honesty/); Demonstration Videos (globalgrid2050, https://globalgrid2050.com/solar-bess-topology-v7/docs/demonstration-videos.html).
- What it achieves
- Its code works with 1 kV, 132 kV and 33 kV.
- Why it matters
- Loaded by the Solar Battery Energy Storage System (BESS) Topology V7 page in GlobalGrid2050 at https://globalgrid2050.com/solar-bess-topology-v7/ and 3 other pages.
- Application
- cable-trench-or-drill · releases/202609052001/solar-bess-topology-v7/cable-geometry-visualiser · page
- Uses
- Solar Battery Energy Storage System (BESS) Topology V7 — Cable Geometry Visualiser Style Sheet (stylesheet), Solar Battery Energy Storage System (BESS) Topology V7 — Cable Geometry Visualiser (script src), Calculations (script src), Rendering (script src), Export (script src), UI (script src), Render Readiness (script src)
- Used by
- linked from GlobalGrid2050 — Solar Battery Energy Storage System (BESS) Topology V7 Page (link), linked from Solar Battery Energy Storage System (BESS) Topology V7 — Module Layout Page (link), linked from Solar Battery Energy Storage System (BESS) Topology V7 — Module Layout Page (link), named by URL in Spider Maya — V1 Page (estate URL)
- 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
- cable-trench-or-drill@bf00f9503ff7a662933775a022557c4ca9d9880a releases/202609052001/solar-bess-topology-v7/cable-geometry-visualiser/index.html:1-280 · blob 21fc7a76fb8d36c17b1d632f43e5cfcb4fb84d26 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unknown
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Cable Geometry Visualiser V7 | GlobalGrid2050</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<div class="dashboard">
<div class="panel panel-left">
<h2>Cable Geometry Visualiser V7</h2>
<div class="guidance-box"><strong>GlobalGrid2050 V7 migration</strong><br>This page is migrated from the original cable geometry visualiser into the V5 toolset. It remains a geometry capture and visual review tool only. It does not perform electrical rating, thermal rating, cable sizing, protection grading or construction design.</div>
<div class="button-row">
<button id="cg_print_report" class="btn print-btn" type="button" onclick="window.print()">Print</button><a class="btn" href="../module-layout/index.html" style="text-align:center;text-decoration:none;">Module Layout V7</a><a class="btn btn-alt" href="../dc-ac-lv-topology-review/index.html" style="text-align:center;text-decoration:none;">DC AC LV Topology Review</a></div>
<h3 class="section-title">Geometry Inputs</h3>
<div class="warning-box">
This tool produces indicative geometry records only and must not be used for trench design, duct sizing, burial depth specification, electrical design or any construction document without independent verification by a competent engineer with responsibility for the project.<br>
No electrical calculation is performed.<br>
No thermal rating is performed.<br>
No compliance verdict is produced.<br>
No burial depth design advice is produced.<br>
The user must verify safety, installation depth, protection, rating and utility compliance with a competent person in accordance with local law, site conditions and the relevant power utility or infrastructure owner requirements.
</div>
<div id="status_box" class="status-box ok" aria-live="polite">Geometry only. Ready for capture.</div>
<h3>Route Identity</h3>
<div class="input-group">
<label for="route_name">Route ID</label>
<input type="text" id="route_name" value="M_W3_BESS_to_PCS" />
</div>
<div class="input-group">
<label for="section_length">Worst Case Section Length m</label>
<input type="text" inputmode="decimal" enterkeyhint="done" autocomplete="off" autocorrect="off" spellcheck="false" data-numeric="true" id="section_length" value="30" />
</div>
<h3 class="section-title">Installation Basis</h3>
<div class="input-group">
<label for="installation_condition">Installation Condition</label>
<select id="installation_condition">
<option value="buried_duct">Buried Duct</option>
<option value="direct_buried">Direct Buried</option>
<option value="open_trough">Open Trough</option>
<option value="free_air">Free Air on Cleats</option>
<option value="metallic_enclosure">Metallic Enclosure</option>
</select>
</div>
<div class="input-group">
<label for="service_type">Service Type</label>
<select id="service_type">
<option value="lv" selected>LV AC</option>
<option value="mv">33kV AC</option>
<option value="ehv">132kV AC</option>
<option value="dc">DC</option>
</select>
</div>
<div class="input-group">
<label for="grouping_basis">Grouping Basis</label>
<select id="grouping_basis">
<option value="same_circuit">Same Circuit</option>
<option value="same_service">Same Service</option>
<option value="mixed_service">Mixed Service</option>
</select>
</div>
<div class="input-group">
<label for="burial_depth">Burial Depth mm</label>
<input type="text" inputmode="decimal" enterkeyhint="done" autocomplete="off" autocorrect="off" spellcheck="false" data-numeric="true" id="burial_depth" value="900" />
</div>
<div class="inline-note" id="burial_note">Indicative cover or depth input only. Verify with competent person and utility standard.</div>
<h3 class="section-title">Cable OD Lookup</h3>
<div class="input-group">
<label for="lookup_cores">Cores</label>
<select id="lookup_cores">
<option value="single">Single Core</option>
<option value="three">Three Core</option>
</select>
</div>
<div class="input-group">
<label for="lookup_voltage">Voltage Class</label>
<select id="lookup_voltage">
<option value="">— manual OD entry —</option>
<optgroup label="LV Power — 0.6/1kV XLPE, Cu conductor">
<option value="lv_cu_sc">0.6/1kV Cu XLPE single core (AWA)</option>
<option value="lv_cu_2c">0.6/1kV Cu XLPE 2-core SWA</option>
<option value="lv_cu_3c">0.6/1kV Cu XLPE 3-core SWA</option>
<option value="lv_cu_4c">0.6/1kV Cu XLPE 4-core SWA</option>
<option value="lv_cu_5c">0.6/1kV Cu XLPE 5-core SWA</option>
</optgroup>
<optgroup label="LV Power — 0.6/1kV XLPE, Al conductor">
<option value="lv_al_sc">0.6/1kV Al XLPE single core (AWA)</option>
<option value="lv_al_3c">0.6/1kV Al XLPE 3-core SWA</option>
<option value="lv_al_4c">0.6/1kV Al XLPE 4-core SWA</option>
<option value="lv_al_5c">0.6/1kV Al XLPE 5-core SWA</option>
</optgroup>
<optgroup label="LV — Multicore, fixed installation">
<option value="lv3">LV 0.6/1kV 3-core</option>
</optgroup>
<optgroup label="Solar PV — DC string (flexible Cu, 1500V DC only)">
<option value="pv_string">1500V DC string — BS EN 50618 Class II</option>
</optgroup>
<optgroup label="Solar PV — Flexible screened (Cu screened, fixed/occasional)">
<option value="flex_hv_ac">1000/1000V AC — IT system (Uo=1000V ≥ inverter Vac)</option>
<option value="flex_hv_dc">1500V DC — flexible screened</option>
</optgroup>
<optgroup label="Solar PV — Rigid Al, Al tube armour (non-magnetic, fixed only)">
<option value="al_ata_ac">1000/1000V AC — Al tube armour, IT system</option>
<option value="al_ata_dc">1500/1500V DC — Al tube armour</option>
</optgroup>
<optgroup label="MV XLPE — fixed installation">
<option value="6">6 kV (3.6/6 kV)</option>
<option value="10">10 kV (5.8/10 kV)</option>
<option value="15">15 kV (8.7/15 kV)</option>
<option value="20">20 kV (12/20 kV)</option>
<option value="33">33 kV (19/33 kV) — Al</option>
<option value="33cu">33 kV (19/33 kV) — Cu 3-core</option>
</optgroup>
<optgroup label="HV XLPE — fixed installation ★ confirmed datasheets">
<option value="66">66 kV (38/66 kV) ★</option>
<option value="110">110 kV (64/110 kV) ★</option>
<option value="132">132 kV (76/132 kV) ★</option>
</optgroup>
</select>
</div>
<div class="input-group">
<label for="lookup_csa">Conductor CSA mm²</label>
<select id="lookup_csa">
<option value="">— select voltage first —</option>
</select>
</div>
<div class="inline-note" id="lookup_note">Select voltage and CSA to auto-populate OD and bend factor. All values are for <strong>fixed installation</strong> only. Flexible applications, very tight bend radii, cleats and terminations must be verified with the cable manufacturer. ★ = anchored on confirmed datasheets. Others from catalogue model. Indicative only.</div>
<h3 class="section-title">Formation</h3>
<div class="input-group">
<label for="formation_type">Formation Type</label>
<select id="formation_type"></select>
</div>
<div class="input-group">
<label for="circuit_qty">Number of Circuit Groups</label>
<input type="text" inputmode="decimal" enterkeyhint="done" autocomplete="off" autocorrect="off" spellcheck="false" data-numeric="true" id="circuit_qty" value="4" />
</div>
<div class="input-group">
<label for="max_per_row">Max Groups per Row</label>
<input type="text" inputmode="decimal" enterkeyhint="done" autocomplete="off" autocorrect="off" spellcheck="false" data-numeric="true" id="max_per_row" value="2" />
</div>
<div class="input-group">
<label for="cable_od">Cable Outer Diameter mm</label>
<input type="text" inputmode="decimal" enterkeyhint="done" autocomplete="off" autocorrect="off" spellcheck="false" data-numeric="true" id="cable_od" value="45" />
</div>
<div class="inline-note" id="od_source_note">OD entered manually.</div>
<div class="input-group">
<label for="spacing_basis">Spacing Basis</label>
<select id="spacing_basis">
<option value="clear_gap">Clear Gap</option>
<option value="touching">Touching</option>
<option value="centre_to_centre">Centre to Centre</option>
</select>
</div>
<div class="input-group">
<label for="spacing_h">Horizontal Spacing mm</label>
<input type="text" inputmode="decimal" enterkeyhint="done" autocomplete="off" autocorrect="off" spellcheck="false" data-numeric="true" id="spacing_h" value="150" />
</div>
<div class="input-group">
<label for="spacing_v">Vertical Spacing mm</label>
<input type="text" inputmode="decimal" enterkeyhint="done" autocomplete="off" autocorrect="off" spellcheck="false" data-numeric="true" id="spacing_v" value="150" />
</div>
<div class="inline-note" id="spacing_note">Spacing inputs are active.</div>
<h3 class="section-title">Bend Geometry</h3>
<div class="input-group">
<label for="bend_factor">Bend Radius x OD</label>
<input type="text" inputmode="decimal" enterkeyhint="done" autocomplete="off" autocorrect="off" spellcheck="false" data-numeric="true" id="bend_factor" value="15" />
</div>
<div class="stat-block">
<div class="stat-row"><span>Formation Width</span><span class="stat-val" id="out_width">0 mm</span></div>
<div class="stat-row"><span>Formation Depth</span><span class="stat-val" id="out_depth">0 mm</span></div>
<div class="stat-row"><span>Burial Depth Input</span><span class="stat-val" id="out_burial">0 mm</span></div>
<div class="stat-row"><span>Indicative Trench Width</span><span class="stat-val" id="out_trench_width">0 mm</span></div>
<div class="stat-row"><span>Indicative Trench Depth</span><span class="stat-val" id="out_trench_depth">0 mm</span></div>
<div class="stat-row"><span>Applied Bend Radius</span><span class="stat-val" id="out_mbr" style="color: var(--accent-2);">0 mm</span></div>
<div class="stat-row"><span>Rows</span><span class="stat-val" id="out_rows">0</span></div>
<div class="stat-row"><span>Clear Gap Horizontal</span><span class="stat-val" id="out_gap_h">0 mm</span></div>
<div class="stat-row"><span>Clear Gap Vertical</span><span class="stat-val" id="out_gap_v">0 mm</span></div>
<div class="stat-row"><span>Approx Group CTC Horizontal</span><span class="stat-val" id="out_ctc_h">0 mm</span></div>
<div class="stat-row"><span>Approx Group CTC Vertical</span><span class="stat-val" id="out_ctc_v">0 mm</span></div>
<div class="stat-row"><span>Review Status</span><span class="stat-val" id="out_note" style="color: var(--ok);">OK</span></div>
</div>
<div class="button-row">
<button class="btn" id="export_btn" type="button">Export JSON</button>
<button class="btn btn-alt" id="copy_btn" type="button">Copy Snapshot</button>
<button class="btn" id="drawing_view_btn" type="button">Drawing View</button>
</div>
<div class="conflict-box" id="conflict_box" aria-live="polite" hidden>
<strong>Input conflicts</strong>
<ul id="conflict_list"></ul>
</div>
<div class="review-box" id="review_box" aria-live="polite" hidden>
<strong>Review points</strong>
<ul id="review_list"></ul>
</div>
<div class="assumption-box">
<strong>Standing assumptions</strong>
<ul>
<li>Within group cable spacing is assumed touching unless separately modelled.</li>
<li>Mixed service visual uses one worst case OD for all shown services and is schematic only.</li>
<li>Bend visual shows a single cable body sweep only and does not model full multi cable sweep, trench profile, duct entry, pull path or installation forces.</li>
<li>Burial depth is recorded as an indicative input only and is not design advice.</li>
<li>4-core and 5-core multicore formations are drawn as a single cable OD. Within-cable core arrangement is not modelled.</li>
</ul>
</div>
<div class="snapshot-box" id="snapshot_box"></div>
<div class="guidance-box">
<strong>Indicative burial depth guidance only</strong><br>
Use this for early geometry capture only, not final design advice.
<ul>
<li>Primary source for LV to 132kV burial depth guidance in this tool is <a href="https://g81.ukpowernetworks.co.uk/library/installation/cables/ecs-02-0019-installation-of-underground-cables-lv-to-132kv" target="_blank" rel="noopener noreferrer">UKPN ECS 02 0019 Installation of Underground Cables LV to 132kV v14.2</a>.</li>
<li>For this tool, burial depth should be read as depth to the top of duct or cable as applicable and then verified for the actual installation basis.</li>
<li>BS 7671 and ERA 69 30 give thermal rating reference depths, not utility minimum cover requirements. See the official <a href="https://electrical.theiet.org/bs-7671-18th-edition-wiring-regulations/" target="_blank" rel="noopener noreferrer">IET BS 7671 page</a>.</li>
<li>Street authority and underground apparatus context should be checked at the official <a href="https://www.gov.uk/government/publications/recording-of-underground-apparatus-in-streets-code-of-practice" target="_blank" rel="noopener noreferrer">GOV.UK underground apparatus code page</a>.</li>
<li>Street Works UK should be used as coordination context only, not as the source of the burial depth figures in this tool. See the official <a href="https://streetworks.org.uk/resources/publications/" target="_blank" rel="noopener noreferrer">Street Works UK publications page</a>.</li>
<li>DC minimum burial depth in this tool is a project default assumption only and has no normative source embedded in this release.</li>
</ul>
The user must verify safety, cover, backfill, duct arrangement, rating, separation, highway loading and protection with a competent person in accordance with the appropriate local regulation and the relevant power utility, infrastructure owner, highway authority or site designer requirements before use.
</div>
</div>
<div class="panel panel-right">
<div class="canvas-container">
<h3 style="align-self:flex-start; color: var(--accent);">Worst Case Formation Cross Section</h3>
<p class="subtle-note" style="align-self:flex-start;">
Cable group box only. Envelope width = the horizontal size of the cable group shown. Envelope depth = the vertical size of the cable group shown.
</p>
<div class="legend">
<span class="legend-item"><span class="legend-swatch" style="background:#666; border-color:#00ffff;"></span>LV AC</span>
<span class="legend-item"><span class="legend-swatch" style="background:#b87333; border-color:#ff5555;"></span>33kV AC</span>
<span class="legend-item"><span class="legend-swatch" style="background:#ffd700; border-color:#ff8800;"></span>132kV AC</span>
<span class="legend-item"><span class="legend-swatch" style="background:#777; border-color: var(--accent-2);"></span>DC</span>
</div>
<canvas id="formation_canvas" width="900" height="420" aria-label="Formation cross section visual"></canvas>
</div>
<div class="canvas-container">
<h3 style="align-self:flex-start; color: #8fd3ff;">Indicative Trench Cross Section</h3>
<p class="subtle-note" style="align-self:flex-start;">
Indicative trench size only. Trench width shown = worst case formation envelope width only. Trench depth shown = burial depth input to the top of duct or cable, plus cable formation depth. No bedding, side clearance, cover boards, duct OD, shoring or civil design is modelled.
</p>
<canvas id="trench_canvas" width="900" height="500" aria-label="Indicative trench cross section visual"></canvas>
</div>
<div class="canvas-container">
<h3 style="align-self:flex-start; color: var(--accent-2);">Single Cable Bend Sweep</h3>
<p class="subtle-note" style="align-self:flex-start;">
Single cable body sweep only. Not multi cable sweep, trench profile, duct entry or civil detail.
</p>
<canvas id="bend_canvas" width="900" height="380" aria-label="Single cable bend sweep visual"></canvas>
</div>
</div>
</div>
<script src="./data.js"></script>
<script src="./calculations.js"></script>
<script src="./rendering.js"></script>
<script src="./export.js"></script>
<script src="./ui.js"></script>
<script src="./render-readiness.js"></script>
</body>
</html>Render Readiness
A JavaScript file in the cable geometry visualiser folder of Cable Trench or Drill covering cables, using SHA-256.
interactioncable-trench-or-drill / releases/202609052001/solar-bess-topology-v7/cable-geometry-visualiser/render-readiness.js · lines 1–32 of 32 · version 2026-09-05 20:01 · Entry point · pattern pending (shared by 2 files)
- What it does
- Defines publish, pending, onInput, onChange, completed. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'bess'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: cables. README: "`src/cable-geometry/render-readiness.js` observes the original snapshot after the three geometry canvases are drawn."
- Downstream impact
- Used directly by 2 files: Solar Battery Energy Storage System (BESS) Topology V7 — Cable Geometry Visualiser Page (cable-trench-or-drill); Render Readiness Test (cable-trench-or-drill). Reached from 142 other entry points, including Iterations — 43 Registry Growth Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/43-registry-growth/); Iterations — 47 Federation Honesty Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/47-federation-honesty/); Demonstration Videos (globalgrid2050, https://globalgrid2050.com/solar-bess-topology-v7/docs/demonstration-videos.html).
- What it achieves
- It is built from the publish step (`publish`), the pending step (`pending`) and the on input helper (`onInput`). Observe completed original render snapshots; never invoke or replace calculations. It responds to input, change and resize events.
- Why it matters
- Loaded by the Cable Geometry Visualiser page. Checked by Render Readiness Test.
- Application
- cable-trench-or-drill · releases/202609052001/solar-bess-topology-v7/cable-geometry-visualiser · script
- Uses
- none found
- Used by
- loaded by Solar Battery Energy Storage System (BESS) Topology V7 — Cable Geometry Visualiser Page (script src), referenced by Render Readiness Test (new URL import.meta.url)
- Produces
- publish, pending, onInput, onChange, completed
- Defines here
- publish, pending, onInput, onChange, completed
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cable-trench-or-drill@bf00f9503ff7a662933775a022557c4ca9d9880a releases/202609052001/solar-bess-topology-v7/cable-geometry-visualiser/render-readiness.js:1-32 · blob 47be5dc1a580a1ddec96d536fb4c04eb33ff43b3 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unknown
/* Observe completed original render snapshots; never invoke or replace calculations. */
(() => {
'use strict';
const box=document.getElementById('snapshot_box');if(!box)return;
let epoch=0, revision=0, disposed=false;
let state=Object.freeze({schema:'ventus.cable-render.v1',state:'pending',revision:0});
const publish=value=>{state=Object.freeze(value);document.dispatchEvent(new CustomEvent('ventus:cable-render-state',{detail:state}));};
const pending=()=>{epoch++;publish({schema:'ventus.cable-render.v1',state:'pending',revision});};
const inputIds=new Set(['route_name','section_length','burial_depth','circuit_qty','max_per_row','cable_od','spacing_h','spacing_v','bend_factor']);
const changeIds=new Set(['installation_condition','service_type','grouping_basis','formation_type','spacing_basis','lookup_cores','lookup_voltage','lookup_csa']);
const onInput=event=>{if(inputIds.has(event.target.id))pending();};
const onChange=event=>{if(changeIds.has(event.target.id))pending();};
const completed=async()=>{
const token=++epoch,text=box.textContent;
try {
const snapshot=JSON.parse(text);
if(!snapshot.inputs || !snapshot.derived_geometry)throw Error('Snapshot fields missing');
const canvases=['formation_canvas','trench_canvas','bend_canvas'].map(id=>document.getElementById(id));
if(canvases.some(c=>!c || !c.width || !c.height))throw Error('Drawing canvas missing');
const digest=await crypto.subtle.digest('SHA-256',new TextEncoder().encode(text));
if(disposed || token!==epoch)return;
revision++;
publish({schema:'ventus.cable-render.v1',state:'ready',revision,snapshotSha256:[...new Uint8Array(digest)].map(x=>x.toString(16).padStart(2,'0')).join(''),
capturedAt:snapshot.captured_at,canvases:Object.freeze(canvases.map(c=>Object.freeze({id:c.id,width:c.width,height:c.height}))),scope:'Original geometry render completed; no electrical or construction acceptance.'});
} catch(error) {if(!disposed && token===epoch)publish({schema:'ventus.cable-render.v1',state:'failed',revision,error:String(error)});}
};
Object.defineProperty(window,'CableGeometryRender',{value:Object.freeze({getState:()=>state}),writable:false,configurable:false});
const observer=new MutationObserver(completed);observer.observe(box,{childList:true,characterData:true,subtree:true});
document.addEventListener('input',onInput,true);document.addEventListener('change',onChange,true);window.addEventListener('resize',pending);
window.addEventListener('pagehide',event=>{if(event.persisted)return;disposed=true;epoch++;observer.disconnect();document.removeEventListener('input',onInput,true);document.removeEventListener('change',onChange,true);window.removeEventListener('resize',pending);});
completed();
})();Route Constraints
A JavaScript module in Cable Trench or Drill that works with sha256 hex (`sha256Hex`) and direct first pass (`directFirstPass`), covering engine pin, using SHA-256.
ingestcable-trench-or-drill / src/route-constraints/route-constraints.js · lines 1–190 of 190 · pattern assess (shared by 5 files)
- What it does
- Defines sha256Hex, load, reset, directFirstPass, assess.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'route'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
- Inputs & outputs
- In: JSON file engine-pin.json.
- Downstream impact
- Used directly by 1 file: Route Constraints Test (cable-trench-or-drill). Reached from 1 other entry point, including Verify Route Constraints Workflow (cable-trench-or-drill).
- What it achieves
- It is built from the sha256 hex helper (`sha256Hex`), the load step (`load`) and the reset step (`reset`). The constraint-aware SECOND result.
- Why it matters
- Checked by Route Constraints Test.
- Application
- cable-trench-or-drill · src/route-constraints · JavaScript module
- Uses
- none found
- Used by
- imported by Route Constraints Test (import)
- Produces
- load, reset, directFirstPass, assess, NOT_IMPLEMENTED
- Defines here
- sha256Hex, load, reset, directFirstPass, assess
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cable-trench-or-drill@bf00f9503ff7a662933775a022557c4ca9d9880a src/route-constraints/route-constraints.js:1-190 · blob fecdf498f8daf20f437ef68c33e2ca1947a92a85 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unknown
/**
* route-constraints — the constraint-aware SECOND result.
*
* DEVELOPMENT-PLAN.md stage 3 says it plainly: "Keep direct connection/distance
* as the first pass, always available. Manual or optional constraint-aware
* routing remains a second result, not a replacement." This cartridge is that
* second result, and it is built so it cannot become the first one — `assess()`
* always returns the direct distance, unmodified, alongside whatever the
* constraint assessment concludes, and the direct figure is present even when
* the constrained one refuses.
*
* WHERE THE MATHEMATICS LIVES, AND WHY NOT HERE.
* The crossing classification and geometry are `engine/route-obstacles.js` in
* ventus-grid-engine. This cartridge carries no copy of them. A copy would
* drift: the engine's proofs would go on passing against the engine while this
* repository quietly computed something else, and the divergence would be
* invisible because both would still look right.
*
* WHY THE BYTES ARE PINNED AND VERIFIED, NOT JUST FETCHED.
* Reading a live URL trades one risk for another: no drift, but no control
* either — an engine change would alter a route assessment here with nothing
* recording that it had. So `engine-pin.json` records the exact commit, git
* blob and SHA-256 this cartridge was proven against, and `load()` hashes what
* it actually receives and refuses to proceed if it differs. That is this
* repository's own discipline — it pins bytes, not URLs — applied to a
* dependency it does not own.
*
* FAIL CLOSED, VISIBLY.
* Every failure path returns a state and a reason. There is no silent fallback
* to a local copy, no default corridor factor, and no partial answer dressed up
* as a complete one. `unknown coverage` is a real state here, per stage 4:
* a crossing declared without a width is counted and named, never costed at
* zero, because a zero that looks like an answer is worse than no answer.
*/
const PIN_URL = new URL('./engine-pin.json', import.meta.url);
let cached = null;
async function sha256Hex(text) {
const bytes = new TextEncoder().encode(text);
const digest = await crypto.subtle.digest('SHA-256', bytes);
return [...new Uint8Array(digest)].map(b => b.toString(16).padStart(2, '0')).join('');
}
/**
* Load and verify the pinned engine module.
*
* Resolves to { state: 'ready', engine, pin } or { state: 'refused', reason }.
* It never throws for an integrity failure: a refusal is a result the caller
* has to render, not an exception to swallow.
*/
export async function load({ fetchImpl = fetch, importImpl } = {}) {
if (cached) return cached;
let pin;
try {
pin = await (await fetchImpl(PIN_URL)).json();
} catch (e) {
return { state: 'refused', reason: `the engine pin could not be read: ${e.message}` };
}
const { servedUrl, contentSha256, schemaExpected, commit, module } = pin.engine;
let text;
try {
const response = await fetchImpl(servedUrl, { cache: 'no-store' });
if (!response.ok) {
return { state: 'refused', reason: `the engine module returned HTTP ${response.status} from ${servedUrl}` };
}
text = await response.text();
} catch (e) {
return { state: 'refused', reason: `the engine module could not be fetched: ${e.message}` };
}
const actual = await sha256Hex(text);
if (actual !== contentSha256) {
return {
state: 'refused',
reason:
`the engine module served from ${servedUrl} does not match the pinned bytes. ` +
`Pinned ${contentSha256.slice(0, 12)}… at commit ${commit.slice(0, 7)}, received ${actual.slice(0, 12)}…. ` +
`The engine has moved since this cartridge was proven against it. Re-verify ${module} ` +
`and update engine-pin.json deliberately — a route assessment must not change because a ` +
`dependency changed underneath it.`
};
}
let engine;
try {
engine = importImpl ? await importImpl(servedUrl) : await import(/* @vite-ignore */ servedUrl);
} catch (e) {
return { state: 'refused', reason: `the engine module hashed correctly but did not import: ${e.message}` };
}
if (engine.schema !== schemaExpected) {
return {
state: 'refused',
reason: `the engine module declares schema "${engine.schema}", the pin expects "${schemaExpected}"`
};
}
cached = { state: 'ready', engine, pin };
return cached;
}
/** Discard the cached module. Used by tests and after a pin change. */
export function reset() { cached = null; }
/**
* The first pass, preserved.
*
* Returned by `assess()` unconditionally, including when the constrained
* assessment refuses. It is a measurement and it does not stop being one
* because a route is difficult.
*/
export function directFirstPass({ straightLineKm }) {
return {
quantity: 'direct_distance_km',
value: straightLineKm,
unit: 'km',
basis:
'The direct point-to-point distance. This is the first pass and is always available. ' +
'It is not a route and does not claim to be; it is the measurement every other figure ' +
'here is derived from.'
};
}
/**
* The second result: direct first pass, plus a constraint-aware assessment.
*
* `crossings` are DECLARED by the user, per stage 3's "manual or optional
* constraint-aware routing". Nothing here discovers a constraint from a map.
*/
export async function assess({ straightLineKm, crossings = [], corridorFactor, loaded = null }) {
const first = directFirstPass({ straightLineKm });
const mod = loaded || await load();
if (mod.state !== 'ready') {
return {
state: 'refused',
firstPass: first,
constrained: null,
reason: mod.reason,
note:
'The direct first pass above is unaffected and remains valid. Only the constraint-aware ' +
'second result is unavailable.'
};
}
let estimate;
try {
estimate = mod.engine.routeEstimate({ straightLineKm, crossings, corridorFactor });
} catch (e) {
return {
state: 'refused', firstPass: first, constrained: null,
reason: `the engine refused these inputs: ${e.message}`,
note: 'The direct first pass above is unaffected and remains valid.'
};
}
const undeclared = estimate.schedule.undeclaredLengths;
return {
state: estimate.value === null ? 'no-result' : 'assessed',
firstPass: first,
constrained: estimate,
coverage: undeclared.length
? { state: 'unknown', undeclared,
note: `${undeclared.length} declared crossing(s) carry no width or setback and contribute ` +
`no length: ${undeclared.join(', ')}. They are counted as present and explicitly not ` +
`costed. Unknown coverage is a state, not a zero.` }
: { state: 'declared', undeclared: [], note: 'Every declared crossing carries a width and a setback.' },
engineCommit: mod.pin.engine.commit,
note:
estimate.value === null
? 'No constrained result: the engine refused to apply a corridor factor to this route. ' +
'The direct first pass above stands and is unchanged.'
: 'A screening estimate, presented beside the first pass and never in place of it. ' +
'Not a route, not a constructability assessment, not a consenting design.'
};
}
export const NOT_IMPLEMENTED = Object.freeze({
automatedRouting:
'This cartridge does not find a route. Crossings are declared by the user. An automated router needs the route graph, land ownership, ground conditions and consenting constraints described in DEVELOPMENT-PLAN.md stage 4, none of which are present yet.',
cost:
'Stage 5 compares trenching and drilling alternatives including costs. No cost model exists here, and a length is not a price.',
permission:
'Whether a crossing is permitted is the asset owner\'s and regulator\'s answer. Network Rail asset protection alone commonly governs the programme regardless of engineering feasibility.'
});Derive Cable
A Python command-line tool in the tools folder of Cable Trench or Drill covering cables, using SHA-256. It is built from the blob step (`blob`) and the sha step (`sha`).
electricalcable-trench-or-drill / tools/derive_cable.py · lines 1–47 of 47 · Entry point
- What it does
- Defines blob, sha, main. Uses libraries pathlib, argparse, datetime, hashlib, json. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'cable'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: cables. README: "`tools/derive_cable.py` composes a fresh, unique UTC-minute release from the committed baseline"
- Inputs & outputs
- In: command-line arguments. Out: JSON file derived-latest.json.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- Compose one immutable Cable render-readiness release from committed original bytes. It accepts `--generation`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- cable-trench-or-drill · tools · Python CLI
- Uses
- pathlib, argparse, datetime, hashlib, json, re, subprocess
- Used by
- none found
- Produces
- blob, sha, main
- Defines here
- blob, sha, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cable-trench-or-drill@bf00f9503ff7a662933775a022557c4ca9d9880a tools/derive_cable.py:1-47 · blob 52ba6d75c36f7abba28bb285ae86e8ebb311b59d · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unknown
"""Compose one immutable Cable render-readiness release from committed original bytes."""
from pathlib import Path
import argparse, datetime, hashlib, json, re, subprocess
ROOT=Path(__file__).resolve().parents[1]
BASELINE='76396fd3639dd86cddd21e392f29f43ab6d22f2d'
GENERATION='202609051921'
PREFIX='solar-bess-topology-v7/cable-geometry-visualiser/'
def blob(path):
return subprocess.check_output(['git','-C',str(ROOT),'show',BASELINE+':'+path])
def sha(raw): return hashlib.sha256(raw).hexdigest()
def main():
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--generation',default=datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%d%H%M'));args=parser.parse_args()
if not re.fullmatch(r'\d{12}',args.generation): raise SystemExit('Unique UTC timestamp required')
release=ROOT/'releases'/args.generation
if release.exists(): raise SystemExit('Immutable release already exists')
baseline_raw=blob('releases/'+GENERATION+'/manifest.json');baseline=json.loads(baseline_raw)
entry=PREFIX+'index.html';cartridge=PREFIX+'render-readiness.js'
insertion='<script src="./render-readiness.js"></script>\n'
files=[];prepared=[]
for member in baseline['files']:
if not member['path'].startswith(PREFIX):continue
raw=blob('releases/'+GENERATION+'/'+member['path'])
if sha(raw)!=member['sha256']:raise SystemExit('Baseline manifest mismatch')
role='original'
if member['path']==entry:
if raw.count(b'</body>')!=1:raise SystemExit('Ambiguous entry insertion')
raw=raw.replace(b'</body>',insertion.encode()+b'</body>');role='composed-entry'
prepared.append((member['path'],raw,role))
source='src/cable-geometry/render-readiness.js';raw=(ROOT/source).read_bytes().replace(b'\r\n',b'\n')
prepared.append((cartridge,raw,'cartridge'))
release.mkdir(parents=True)
for name,raw,role in prepared:
target=release/name;target.parent.mkdir(parents=True,exist_ok=True);target.write_bytes(raw)
files.append(dict(path=name,bytes=len(raw),sha256=sha(raw),role=role))
siblings=baseline.get('crossOwnerNavigation',[])
manifest=dict(schema='globalgrid.derived-runtime.v1',generation=args.generation,createdAt=datetime.datetime.now(datetime.timezone.utc).isoformat(),
baseline=dict(commit=BASELINE,generation=GENERATION,manifestSha256=sha(baseline_raw)),
applications=[dict(id='cable-geometry-visualiser',entry=entry)],files=files,
composition=dict(entry=entry,insertBefore='</body>',insertion=insertion),cartridge=dict(path=cartridge,sourcePath=source),
crossOwnerNavigation=siblings,rootOriginDependencies=baseline.get('rootOriginDependencies',[]),
scope='Original formulas and runtime files preserved. Only entry composition and independent render-readiness observer are new. No engineering acceptance claim.')
raw=(json.dumps(manifest,indent=2)+'\n').encode();(release/'manifest.json').write_bytes(raw)
pointer=dict(schema='globalgrid.derived-runtime-pointer.v1',generation=args.generation,manifest='releases/'+args.generation+'/manifest.json',manifestSha256=sha(raw))
(ROOT/'derived-latest.json').write_text(json.dumps(pointer,indent=2)+'\n',encoding='utf8',newline='\n');print(json.dumps(pointer))
if __name__=='__main__':main()Import Original
A Python command-line tool in the tools folder of Cable Trench or Drill covering grid substations, Renewable Energy Planning Database (REPD) master, cables and solar, using SHA-256.
storagecable-trench-or-drill / tools/import_original.py · lines 1–83 of 83 · Entry point
- What it does
- Defines git, main. Uses libraries argparse, datetime, hashlib, json, re. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (repository name word 'cable'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: cables, solar.
- Inputs & outputs
- In: GeoJSON file grid_substations.geojson; JSON file repd_master.json; command-line arguments. Out: JSON file latest.json.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It is built from the git step (`git`). Import an immutable original runtime from an explicit GlobalGrid Git revision. It accepts `--source`, `--commit` and `--generation`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- cable-trench-or-drill · tools · Python CLI
- Uses
- argparse, datetime, hashlib, json, re, subprocess, pathlib
- Used by
- none found
- Produces
- git, main
- Defines here
- git, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cable-trench-or-drill@bf00f9503ff7a662933775a022557c4ca9d9880a tools/import_original.py:1-83 · blob 1ebac1b98858969345cffb415067e624e53a5ede · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: supporting_data
"""Import an immutable original runtime from an explicit GlobalGrid Git revision."""
import argparse
import datetime
import hashlib
import json
import re
import subprocess
from pathlib import Path
def git(repo, *args):
return subprocess.check_output(['git', '-C', str(repo), *args])
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--source', type=Path, required=True)
parser.add_argument('--commit', required=True)
parser.add_argument('--generation', required=True)
parser.add_argument('--apps', nargs='+', default=['cable-geometry-visualiser'])
parser.add_argument('--layout-producer-commit', required=True)
args = parser.parse_args()
if not re.fullmatch(r'[0-9a-f]{40}', args.commit) or not re.fullmatch(r'\d{12}', args.generation):
parser.error('full source SHA and 12-digit generation required')
base = Path(__file__).resolve().parents[1]
target = base / 'releases' / args.generation
if target.exists():
parser.error('immutable generation already exists')
prefixes = ['solar-bess-topology-v7/' + app for app in args.apps]
paths = git(args.source, 'ls-tree', '-r', '--name-only', args.commit, '--', *prefixes).decode().splitlines()
paths = [p for p in paths if Path(p).suffix in {'.html', '.js', '.css'}]
if not paths:
parser.error('no original runtime files')
contents = {p: git(args.source, 'show', args.commit + ':' + p) for p in paths}
required = set()
external = set()
for raw in contents.values():
text = raw.decode('utf8')
required.update(re.findall(r'\.\./\.\./(repd_grid_atlasv8/data/[\w.-]+)', text))
external.update(re.findall(r'https?://[^\s\"\'<>`]+', text))
for relative in sorted(required):
contents[relative] = git(args.source, 'show', args.commit + ':' + relative)
manifest = {
'schema': 'globalgrid.original-runtime.v1', 'generation': args.generation,
'createdAt': datetime.datetime.now(datetime.timezone.utc).isoformat(),
'origin': {'repository': 'Ventusltd/globalgrid2050', 'commit': args.commit},
'applications': [{'id': app, 'entry': 'solar-bess-topology-v7/' + app + '/index.html'} for app in args.apps],
'policy': 'Original runtime and required relative data bytes copied unchanged; no generated full-code reports.',
'rootOriginDependencies': ['/grid_substations.geojson', '/dist/repd_master.json'],
'externalLiteralUrls': sorted(external),
'externalScope': 'Literal URL inventory, not exhaustive dynamic dependency closure. External libraries, styles, tiles and geocoding remain external. Root-absolute data requires the GlobalGrid origin or an explicit hosting adapter.',
'files': []}
if not re.fullmatch(r'[0-9a-f]{40}', args.layout_producer_commit):
parser.error('full Layout producer commit required for sibling navigation')
if args.apps != ['cable-geometry-visualiser']:
parser.error('This producer owns only Cable Geometry; other apps remain with their owners')
manifest['rootOriginDependencies'] = []
manifest['crossOwnerNavigation'] = [{
'path': 'solar-bess-topology-v7/' + app + '/index.html',
'repository': 'Ventusltd/layout-tool', 'commit': args.layout_producer_commit,
'entry': 'releases/202609051858/solar-bess-topology-v7/' + app + '/index.html',
'manifestSha256': 'bb6d0a5cf4cf63d68b3d5cb02e55c27f1ccc0646135d7e39cdedbbe3da262796',
'rule': 'Consumer composes the separately owned sibling route; this producer includes only Cable Geometry.'}
for app in ['module-layout', 'dc-ac-lv-topology-review']]
for relative, raw in sorted(contents.items()):
path = target / relative
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(raw)
manifest['files'].append({'path': relative, 'bytes': len(raw),
'sha256': hashlib.sha256(raw).hexdigest(),
'gitBlob': hashlib.sha1(b'blob ' + str(len(raw)).encode() + b'\0' + raw).hexdigest(),
'role': 'relative-data' if relative in required else 'runtime'})
raw_manifest = (json.dumps(manifest, indent=2) + '\n').encode()
(target / 'manifest.json').write_bytes(raw_manifest)
latest = {'schema': 'globalgrid.original-runtime-pointer.v1', 'generation': args.generation,
'manifest': 'releases/' + args.generation + '/manifest.json',
'manifestSha256': hashlib.sha256(raw_manifest).hexdigest()}
(base / 'latest.json').write_text(json.dumps(latest, indent=2) + '\n', encoding='utf8')
print(json.dumps({'generation': args.generation, 'files': len(contents), 'bytes': sum(map(len, contents.values())), 'manifestSha256': latest['manifestSha256']}))
if __name__ == '__main__':
main()Render Readiness Test
A test in the tools folder of Cable Trench or Drill that checks Render Readiness.
testcable-trench-or-drill / tools/render-readiness.test.mjs · lines 1–62 of 62 · Entry point · pattern Target (shared by 3 files)
- What it does
- It tests its inputs. Defines settle, fixture, Target, Observer, event. Uses libraries node:test, node:assert/strict, node:fs, node:vm. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (repository name word 'cable'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. README: "`src/cable-geometry/render-readiness.js` observes the original snapshot after the three geometry canvases are drawn."
- Downstream impact
- Used directly by 1 file: Verify Derived Workflow (cable-trench-or-drill).
- What it achieves
- It is built from the settle step (`settle`), the fixture step (`fixture`) and the target class (`Target`). The README says: `src/cable-geometry/render-readiness.js` observes the original snapshot after the three geometry canvases are drawn.
- Why it matters
- Run by Verify Derived Workflow.
- Application
- cable-trench-or-drill · tools · test
- Uses
- Render Readiness (new URL import.meta.url), node:test, node:assert/strict, node:fs, node:vm
- Used by
- run by Verify Derived Workflow (workflow run)
- Produces
- settle, fixture, Target, Observer, event
- Defines here
- settle, fixture, Target, Observer, event
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cable-trench-or-drill@bf00f9503ff7a662933775a022557c4ca9d9880a tools/render-readiness.test.mjs:1-62 · blob 236cb4b77cb526f59e9a1238c3811e6e0b66934a · GitHub at these lines
- State
- achieves: readme · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unknown
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import vm from 'node:vm';
const source=fs.readFileSync(new URL('../src/cable-geometry/render-readiness.js',import.meta.url),'utf8');
const settle=()=>new Promise(resolve=>setImmediate(resolve));
function fixture() {
// Node's EventTarget does not remove a boolean-capture registration consistently;
// normalize the equivalent options object to model browser listener matching.
class Target extends EventTarget {
addEventListener(type,listener,options){super.addEventListener(type,listener,typeof options==='boolean'?{capture:options}:options);}
removeEventListener(type,listener,options){super.removeEventListener(type,listener,typeof options==='boolean'?{capture:options}:options);}
}
const doc=new Target(),win=new Target(),digests=[];
const box={textContent:JSON.stringify({inputs:{quantity:4},derived_geometry:{rows:2},captured_at:'fixture'})};
const canvases=Object.fromEntries(['formation_canvas','trench_canvas','bend_canvas'].map(id=>[id,{id,width:900,height:400}]));
doc.getElementById=id=>id==='snapshot_box'?box:canvases[id];
let callback,disconnected=false;
class Observer {constructor(fn){callback=fn;}observe(){}disconnect(){disconnected=true;}}
const crypto={subtle:{digest:()=>new Promise((resolve,reject)=>digests.push({resolve,reject}))}};
vm.runInNewContext(source,{document:doc,window:win,MutationObserver:Observer,CustomEvent,TextEncoder,crypto});
function event(type,id) {const e=new Event(type);Object.defineProperty(e,'target',{value:{id}});doc.dispatchEvent(e);}
return {win,box,digests,event,getState:()=>win.CableGeometryRender.getState(),
mutate:()=>callback(),resolve:(n,byte=1)=>digests[n].resolve(new Uint8Array(32).fill(byte).buffer),
get disconnected(){return disconnected;}};
}
test('a stale digest cannot mark a newer pending input ready',async()=>{
const f=fixture();assert.equal(f.digests.length,1);
f.event('input','circuit_qty');f.resolve(0);await settle();
assert.equal(f.getState().state,'pending');assert.equal(f.getState().revision,0);
f.mutate();f.resolve(1,2);await settle();
assert.equal(f.getState().state,'ready');assert.equal(f.getState().revision,1);
assert.equal(f.getState().snapshotSha256,'02'.repeat(32));
});
test('out-of-order completion and failure cannot overwrite the latest render',async()=>{
const f=fixture();f.mutate();f.resolve(1,3);await settle();
const latest=f.getState();f.digests[0].reject(Error('old digest failed'));await settle();
assert.equal(f.getState(),latest);assert.equal(latest.state,'ready');
f.mutate();f.mutate();f.resolve(3,4);await settle();f.resolve(2,5);await settle();
assert.equal(f.getState().snapshotSha256,'04'.repeat(32));assert.equal(f.getState().revision,2);
});
test('unrelated changes and route-name blur change preserve ready state',async()=>{
const f=fixture();f.resolve(0);await settle();const ready=f.getState();
f.event('change','route_name');f.event('change','unrelated');f.event('input','unrelated');
assert.equal(f.getState(),ready);
f.event('change','formation_type');assert.equal(f.getState().state,'pending');
// An actual snapshot DOM write completes even when its content is identical.
f.mutate();f.resolve(1);await settle();assert.equal(f.getState().state,'ready');
assert.equal(f.getState().revision,2);assert.equal(f.getState().snapshotSha256,ready.snapshotSha256);
});
test('disposing invalidates pending work while bfcache suspension preserves observation',async()=>{
const f=fixture();const cached=new Event('pagehide');Object.defineProperty(cached,'persisted',{value:true});f.win.dispatchEvent(cached);
assert.equal(f.disconnected,false);f.resolve(0);await settle();assert.equal(f.getState().state,'ready');
f.event('input','route_name');f.mutate();f.win.dispatchEvent(new Event('pagehide'));f.resolve(1);await settle();
assert.equal(f.disconnected,true);assert.equal(f.getState().state,'pending');
const last=f.getState();f.event('input','circuit_qty');f.win.dispatchEvent(new Event('resize'));assert.equal(f.getState(),last);
});