GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Automation and CI / ventus-grid-engine / proofs

V9 Engine Proof and 8 more files

A JavaScript module in the proofs folder of Ventus Grid Engine covering substations, 33kV and 400kV, using haversine.

694 lines of JavaScript and Python and YAML from ventus-grid-engine, wire-frame-scanner, in 9 files. Topic: Automation and CI. Section 1875 of 2044.

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

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

In this section

  1. Site Tile Proof other · ventus-grid-engine / proofs/site-tile.proof.mjs lines 1–130
  2. V9 Engine Proof other · ventus-grid-engine / proofs/v9-engine.proof.mjs lines 1–188
  3. Wider Fleet Build Payload Excerpt other · ventus-grid-engine / sources/deeplink-extracts/emitter/wider-fleet-build_payload.excerpt.py lines 1–25
  4. Audit Receivers storage · ventus-grid-engine / tools/audit-receivers.mjs lines 1–94
  5. Build Browser Observer storage · ventus-grid-engine / tools/build-browser-observer.mjs lines 1–19
  6. Geometry Audit Workflow automation · wire-frame-scanner / .github/workflows/geometry-audit.yml lines 1–38
  7. Scanner Workflow automation · wire-frame-scanner / .github/workflows/scanner.yml lines 1–22
  8. Test Fictional test · wire-frame-scanner / tests/test_fictional.py lines 1–98
  9. Test Fictional Loop test · wire-frame-scanner / tests/test_fictional_loop.py lines 1–80

Site Tile Proof

A JavaScript module in the proofs folder of Ventus Grid Engine. It is built from the check step (`check`).

otherventus-grid-engine / proofs/site-tile.proof.mjs · lines 1–130 of 130 · Not reached from any entry point (candidate for review)

What it does
Defines check. Side effects: starts processes.
What it achieves
Wireframe rule R5, the site tile: stream the measured ground where you arrive, never download in bulk.
Why it matters
No other file in the estate was found to import it.
Application
ventus-grid-engine · proofs · JavaScript module
Uses
Site Tile (import)
Used by
none found
Produces
check
Defines here
check
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
ventus-grid-engine@ad566356a44e006682e956483d569f31ddbb9630 proofs/site-tile.proof.mjs:1-130 · blob 085a64ca0e9acf3799ce63d4d3866bd85d3d9637 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: unknown · users: none · canonical: unreached_review
/* site-tile.proof.mjs — wireframe rule R5, the site tile: stream the measured
 * ground where you arrive, never download in bulk. These checks hold the
 * tile maths to the rule's own words, so the rule and its code cannot drift.
 *
 * Run: node proofs/site-tile.proof.mjs
 */

import { schema, TILE_M, PRODUCTS, GAP_S, DAILY_CAP, BACKOFF_FIRST_S, BACKOFF_MAX_S, BASIS,
    tileOf, tilesForBox, tilesForRoute, cellCentre, tileKey, RECEIPT_FIELDS, missingReceiptFields,
    schedule, backoff, groundUse, noMeasuredGround } from '../engine/site-tile.js';

const failures = [];
let passed = 0;
const check = (name, condition) => {
    if (condition) passed += 1;
    else failures.push(name);
};

/* ── The constants and where they come from ─────────────────────────────── */

check('tiles are a fixed 2,048 m on a 2,048 m lattice (rule 1)', TILE_M === 2048);
check('two products, the terrain and the surface, and nothing else (rule 2)',
    PRODUCTS.length === 2 && PRODUCTS[0] === 'dtm' && PRODUCTS[1] === 'dsm');
check('the pace is more than twice the spacing at which the service refused a client (rule 3)',
    GAP_S === 40 && GAP_S / BASIS.refusal.mean_spacing_s > 2);
check('the daily cap is 16 and says it was chosen, not measured (rule 3)',
    DAILY_CAP === 16 && BASIS.daily_cap === 'chosen, not measured');
check('the refusal back-off starts at 5 minutes and tops out at 1 hour (rule 3)',
    BACKOFF_FIRST_S === 300 && BACKOFF_MAX_S === 3600);
check('a 2,048 m tile of 1 m cells is 4,194,304 cells, as measured',
    TILE_M * TILE_M === BASIS.measured.dtm_2048_cells);
check('the surface product has not been measured yet, and the basis says so rather than guessing',
    BASIS.measured.dsm_bytes === null);

/* ── Rule 1: tiles, like a map ──────────────────────────────────────────── */

const t = tileOf(530624.4, 178388.9);
check('a point lands in the tile whose corner is the lattice point below and to the west of it',
    t.e0 === 530432 && t.n0 === 178176 && t.size === 2048);
check('a point exactly on a lattice line belongs to the tile that starts there',
    tileOf(4096, 6144).e0 === 4096 && tileOf(4096, 6144).n0 === 6144);
check('a small site inside one tile takes exactly one tile',
    tilesForBox(530500, 178200, 530900, 178900).length === 1);
check('a site straddling a tile corner takes the four tiles it touches, and no more',
    tilesForBox(532400, 180200, 532600, 180300).length === 4);
const route = tilesForRoute([[500000, 200000], [520000, 200000]]);
check('a 20 km straight route east, from 500,000 to 520,000 m, takes the ten tiles its line crosses (lattice columns 244 to 253)',
    route.length === 10 && route[0].e0 === 244 * 2048 && route[9].e0 === 253 * 2048 && route.every(r => r.n0 === 198656));
check('a route never skips a tile between two far points (sampled at a quarter tile or finer)',
    route.map(r => r.e0).every((e, i, a) => i === 0 || e - a[i - 1] === TILE_M));
check('a route with a half-width takes the tiles its corridor touches as well',
    tilesForRoute([[500000, 198700]], 100).length === 2);
check('an empty route takes no tiles', tilesForRoute([]).length === 0);
check('the tile corner is a cell corner: cell (0, 0) has its centre half a metre in',
    cellCentre({ e0: 1000, n0: 2000 }, 0, 0)[0] === 1000.5 && cellCentre({ e0: 1000, n0: 2000 }, 0, 0)[1] === 2000.5);

/* ── Rules 4 and 8: stream, and keep a receipt ──────────────────────────── */

check('a tile key names the product, the corner and the size',
    tileKey('dtm', t) === 'dtm/530432/178176/2048');
let threw = false;
try { tileKey('imagery', t); } catch { threw = true; }
check('a key for anything but measured ground is refused (rule 11: imagery follows the map\'s rules)', threw);
check('the receipt hashes the decoded cells, not the file bytes',
    RECEIPT_FIELDS.includes('sha256_cells') && !RECEIPT_FIELDS.includes('sha256_bytes'));
check('the receipt carries the licence and the attribution',
    RECEIPT_FIELDS.includes('licence') && RECEIPT_FIELDS.includes('attribution'));
const full = Object.fromEntries(RECEIPT_FIELDS.map(f => [f, 'x']));
full.survey_year = null;
check('a receipt may say the survey year is unknown, but must say it',
    missingReceiptFields(full).length === 0);
const noYear = { ...full }; delete noYear.survey_year;
check('a receipt that leaves the survey year out altogether is incomplete',
    missingReceiptFields(noYear).includes('survey_year'));

/* ── Rules 2, 3 and 5: the schedule ─────────────────────────────────────── */

const one = schedule([t]);
check('one tile is two requests, the terrain first, 40 s apart',
    one.requests.length === 2 && one.requests[0].product === 'dtm' && one.requests[1].at_s - one.requests[0].at_s === 40);
check('the same tile asked twice in one visit is asked once',
    schedule([t, t]).requests.length === 2);
check('a tile with a stored wireframe or live receipt is drawn from that, not asked again (rule 5)',
    schedule([t], { have: new Set(['dtm/530432/178176/2048']) }).requests.length === 1);
const long = schedule(route);
check('past the daily cap the plan stops and names every tile it could not fetch',
    long.requests.length === DAILY_CAP && long.stopped_at_cap && long.missing.length === route.length * 2 - DAILY_CAP);
check('requests already made today count against the cap',
    schedule([t], { usedToday: 15 }).requests.length === 1);

/* ── Rule 3: refusals ───────────────────────────────────────────────────── */

check('no refusal, no pause', backoff(0) === 0);
check('the pause doubles: 5, 10, 20 and 40 minutes',
    backoff(1) === 300 && backoff(2) === 600 && backoff(3) === 1200 && backoff(4) === 2400);
check('the pause tops out at one hour', backoff(5) === 3600);
check('a refusal after the one-hour pause stops the fetcher until a person restarts it',
    backoff(6) === 'stop' && backoff(9) === 'stop');

/* ── Rule 9: survey year before scanning ────────────────────────────────── */

check('a survey after the build may be scanned for the asset',
    groundUse({ surveyYear: 2024, buildYear: 2021 }) === 'as built');
check('a survey in the build year is the ground before the asset (the flight may predate the build)',
    groundUse({ surveyYear: 2022, buildYear: 2022 }) === 'pre-construction ground');
check('a survey before the build is the ground before the asset',
    groundUse({ surveyYear: 2022, buildYear: 2025 }) === 'pre-construction ground');
check('an unknown year on either side never permits a scan',
    groundUse({ surveyYear: null, buildYear: 2020 }) === 'pre-construction ground'
    && groundUse({ surveyYear: 2022 }) === 'pre-construction ground');

/* ── Rule 10: say it, do not fill it ────────────────────────────────────── */

check('an error is no measured ground', noMeasuredGround({ http: 500 }));
check('untagged all-zero cells are no measured ground, never 0 m', noMeasuredGround({ allZeroUntagged: true }));
check('a run of exact zeros is no measured ground', noMeasuredGround({ zeroRun: true }));
check('a good tile is measured ground', noMeasuredGround({}) === false);

check('the module identifies itself with a stable schema string',
    schema === 'gridatlas.module.site-tile.v1');

/* ── Report ─────────────────────────────────────────────────────────────── */

if (failures.length) {
    console.error('site-tile proof FAILED (' + failures.length + ' of '
        + (failures.length + passed) + '):\n- ' + failures.join('\n- '));
    process.exit(1);
}
console.log('site-tile proof PASS — ' + passed + ' checks');
export default { status: 'PASS', checks: passed };

V9 Engine Proof

A JavaScript module in the proofs folder of Ventus Grid Engine covering substations, 33kV and 400kV, using haversine.

otherventus-grid-engine / proofs/v9-engine.proof.mjs · lines 1–188 of 188 · Not reached from any entry point (candidate for review)

What it does
Defines check, near, EARTH_RADIUS_KM_FROM_V8. Side effects: starts processes.
Why it exists in the grid workflow
Domain terms in the code: substations, 33kV, 400kV.
Inputs & outputs
Voltage levels named: 400kV, 33kV.
What it achieves
It is built from the check step (`check`) and the near step (`near`). The V9 geodesy and nearest-search, held to the two. Its code works with 33 kV and 400 kV.
Why it matters
No other file in the estate was found to import it.
Application
ventus-grid-engine · proofs · JavaScript module
Uses
Geo Core (import), V9 Geodesy (import), V9 Nearest Search (import)
Used by
none found
Produces
check, near, EARTH_RADIUS_KM_FROM_V8
Defines here
check, near, EARTH_RADIUS_KM_FROM_V8
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
ventus-grid-engine@ad566356a44e006682e956483d569f31ddbb9630 proofs/v9-engine.proof.mjs:1-188 · blob d824198bbc3e6a8f4160e64199b1eb7242b286f9 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: unknown · users: none · canonical: unreached_review
/* v9-engine.proof.mjs — the V9 geodesy and nearest-search, held to the two
 * claims that matter about them:
 *
 *   1. PARITY. The V9 module claims to return exactly what the V8 incumbent
 *      returns. "Nearly the incumbent" is not a claim, it is an argument
 *      waiting to happen every time a digit differs — so parity is asserted
 *      to the last bit, not to a tolerance.
 *
 *   2. NO RING-SEARCH BUG. The nearest-search is an exhaustive scan, so it
 *      cannot exclude the true nearest node. That is easy to say and easy to
 *      lose in a later "optimisation", so there is a fixture here whose true
 *      nearest node is deliberately placed where a naive bounding-box or ring
 *      pre-filter would drop it. If someone adds such a filter, this fails.
 *
 * Run: node proofs/v9-engine.proof.mjs
 */

import { haversine } from '../engine/geo-core.js';
import {
    EARTH_RADIUS_KM as V9_RADIUS, distanceKm, representativePoint,
    voltagesKv, destinationPoint, initialBearingDeg
} from '../engine/v9-geodesy.js';
import { normalise, index } from '../engine/v9-nearest-search.js';

const failures = [];
let passed = 0;
const check = (name, condition) => {
    if (condition) passed += 1;
    else failures.push(name);
};
const near = (a, b, tol) => Math.abs(a - b) <= tol;

/* ── 1. Parity with the incumbent, to the last bit ──────────────────────── */

const LEGS = [
    [-2.35, 56.05, -0.10, 51.50],   // Berwick Bank to London
    [-0.75, 53.36, -0.78, 53.30],   // West Burton Solar to Cottam, a short leg
    [-5.00, 58.00,  1.70, 52.50],   // corner to corner of GB
    [ 0.00,  0.00,  0.00,  1.00],   // one degree at the equator
    [-3.00, 55.00, -3.00, 55.00]    // a zero-length leg
];

check('V9 distanceKm is bit-identical to the V8 haversine on every reference '
    + 'leg, including a zero-length one — the module claims parity, so parity '
    + 'is asserted exactly and not to a tolerance',
    LEGS.every(([a, b, c, d]) => distanceKm(a, b, c, d) === haversine(a, b, c, d)));

check('both stand on the same radius, so parity cannot be accidental',
    V9_RADIUS === EARTH_RADIUS_KM_FROM_V8());

function EARTH_RADIUS_KM_FROM_V8() { return 6378.137; }

/* ── 2. The nearest-search cannot exclude the true nearest node ─────────── */

// The trap. The query sits at (0, 55). The TRUE nearest node is 6 km away but
// almost due east, so it lies outside a naive square bounding box drawn in
// DEGREES (+/-0.06 deg), because 0.06 deg of longitude at 55N is only 3.8 km
// while 0.06 deg of latitude is 6.7 km. A degree-box pre-filter keeps the
// 6.6 km northern node and drops the 6.0 km eastern one — reporting a distance
// 10% too long, silently, with no error anywhere.
const QUERY = [0, 55];
const DECOY_NORTH = { name: 'Decoy North Grid Substation', voltages_kv: [400],
                      location: { lon: 0, lat: 55 + 6.6 / 111.32 } };
const TRUE_EAST = { name: 'True East Substation', voltages_kv: [400],
                    location: { lon: 6.0 / (111.32 * Math.cos(55 * Math.PI / 180)), lat: 55 } };
const FAR = { name: 'Far Away Substation', voltages_kv: [400],
              location: { lon: 1.5, lat: 56.2 } };
const LOW_VOLTAGE = { name: 'Local 33kV Point', voltages_kv: [33],
                      location: { lon: 0.001, lat: 55.001 } };

const idx = index([DECOY_NORTH, TRUE_EAST, FAR, LOW_VOLTAGE]);
const best = idx.nearest(QUERY[0], QUERY[1], { minimumKv: 100 });

const dEast = distanceKm(QUERY[0], QUERY[1], TRUE_EAST.location.lon, TRUE_EAST.location.lat);
const dNorth = distanceKm(QUERY[0], QUERY[1], DECOY_NORTH.location.lon, DECOY_NORTH.location.lat);

check('the fixture is actually a trap: the true nearest node is closer than '
    + 'the decoy, but sits outside a naive degree-square box that still '
    + 'contains the decoy — if this fails the test has stopped testing anything',
    dEast < dNorth
    && Math.abs(TRUE_EAST.location.lon - QUERY[0]) > 0.06
    && Math.abs(DECOY_NORTH.location.lat - QUERY[1]) < 0.06);

check('nearest() returns the TRUE nearest node, not the one a degree-box '
    + 'pre-filter would have left behind — this is the ring-search bug class, '
    + 'and it inflates a reported grid distance by kilometres when present',
    best && best.point.name === 'True East Substation');

check('the reported distance is the true one, roughly 6 km and not the decoy 6.6',
    best && near(best.km, 6.0, 0.05));

check('a node below the voltage floor is excluded even when it is nearest of '
    + 'all — a 33 kV point 130 m away is not a transmission connection',
    best && best.point.name !== 'Local 33kV Point');

check('with no voltage floor the search is free to return that nearest node, '
    + 'so the exclusion above is the filter working and not the node missing',
    idx.nearest(QUERY[0], QUERY[1], { minimumKv: 0 })?.point.name === 'Local 33kV Point');

check('a limit above 1 returns a list sorted by true distance, ascending',
    (() => { const list = idx.nearest(QUERY[0], QUERY[1], { minimumKv: 100, limit: 3 });
        return Array.isArray(list) && list.length === 3
            && list[0].km <= list[1].km && list[1].km <= list[2].km
            && list[0].point.name === 'True East Substation'; })());

check('an empty index returns null rather than throwing or inventing a node',
    index([]).nearest(0, 55, { minimumKv: 100 }) === null);

check('a node with no declared voltages is skipped rather than crashing the '
    + 'scan — the live cartridge duplicate of this module lacks exactly this '
    + 'default, which is why it can throw where this one cannot',
    (() => { const i = index([{ name: 'No Voltage', location: { lon: 0, lat: 55 } }, TRUE_EAST]);
        return i.nearest(0, 55, { minimumKv: 100 })?.point.name === 'True East Substation'; })());

/* ── Name normalisation ─────────────────────────────────────────────────── */

check('normalisation strips the noise words that make two names for one site '
    + 'look like two sites',
    normalise('Cowley 400kV Grid Substation') === 'COWLEY'
    && normalise('COWLEY SUBSTATION') === 'COWLEY');

check('normalisation is stable enough to key a map: punctuation and case do '
    + 'not create a second entry for the same site',
    normalise('St. Johns Wood Substation') === normalise('ST JOHNS WOOD substation'));

check('the index keys by normalised name and finds a site under either spelling',
    (() => { const i = index([{ name: 'Cowley 400kV Grid Substation',
                                location: { lon: 0, lat: 55 }, voltages_kv: [400] }]);
        return i.byName('COWLEY SUBSTATION')?.name === 'Cowley 400kV Grid Substation'
            && i.byName('nothing here at all') === null; })());

/* ── Representative point ───────────────────────────────────────────────── */

check('a polygon reduces to the mean of its outer ring, not to whichever '
    + 'corner the mapper happened to start at',
    (() => { const p = representativePoint({ type: 'Polygon',
        coordinates: [[[0, 55], [1, 55], [1, 56], [0, 56]]] });
        return near(p[0], 0.5, 1e-12) && near(p[1], 55.5, 1e-12); })());

check('a Point passes through unchanged',
    (() => { const p = representativePoint({ type: 'Point', coordinates: [-2.35, 56.05] });
        return p[0] === -2.35 && p[1] === 56.05; })());

check('an unsupported geometry returns null rather than a plausible-looking '
    + 'mean — the incumbent returns null for a LineString and so does this',
    representativePoint({ type: 'LineString', coordinates: [[0, 55], [1, 56]] }) === null
    && representativePoint(null) === null
    && representativePoint({ type: 'Point', coordinates: [] }) === null);

/* ── Voltage parsing: the unit trap ─────────────────────────────────────── */

check('OpenStreetMap `voltage` is volts at every magnitude, so 400000 is 400 kV',
    voltagesKv({ voltage: '400000' }).includes(400));

check('a semicolon-separated voltage list yields every voltage present',
    (() => { const v = voltagesKv({ voltage: '400000;275000' });
        return v.includes(400) && v.includes(275); })());

check('an explicit kv property is already kilovolts and is not divided again',
    voltagesKv({ kv: '132' }).includes(132));

check('absent voltage data is an empty list, never a guess and never a throw',
    Array.isArray(voltagesKv(null)) && voltagesKv(null).length === 0
    && voltagesKv({}).length === 0);

/* ── Destination point and bearing round-trip ───────────────────────────── */

check('walking 10 km on a bearing and measuring back gives 10 km again',
    (() => { const d = destinationPoint(-2.35, 56.05, 10, 47);
        return near(distanceKm(-2.35, 56.05, d[0], d[1]), 10, 1e-9); })());

check('the bearing measured to that destination is the bearing walked',
    (() => { const d = destinationPoint(-2.35, 56.05, 10, 47);
        return near(initialBearingDeg(-2.35, 56.05, d[0], d[1]), 47, 1e-6); })());

check('due north is bearing 0 and due east is bearing 90',
    near(initialBearingDeg(0, 55, 0, 56), 0, 1e-9)
    && near(initialBearingDeg(0, 55, 0.001, 55), 90, 1e-3));

/* ── Report ─────────────────────────────────────────────────────────────── */

if (failures.length) {
    console.error('v9-engine proof FAILED (' + failures.length + ' of '
        + (failures.length + passed) + '):\n- ' + failures.join('\n- '));
    process.exit(1);
}
console.log('v9-engine proof PASS — ' + passed + ' checks');
export default { status: 'PASS', checks: passed };

Wider Fleet Build Payload Excerpt

A Python module in the emitter folder of Ventus Grid Engine.

otherventus-grid-engine / sources/deeplink-extracts/emitter/wider-fleet-build_payload.excerpt.py · lines 1–25 of 25 · Not reached from any entry point (candidate for review)

What it achieves
`head_sha` (PipelineNews): lines: 155-172 (the 'row["t"]' technology-bucket field the wider-fleet emitter above reads as its 'technology' query parameter).
Why it matters
No other file in the estate was found to import it.
Application
ventus-grid-engine · sources/deeplink-extracts/emitter · Python module
Uses
none found
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
ventus-grid-engine@ad566356a44e006682e956483d569f31ddbb9630 sources/deeplink-extracts/emitter/wider-fleet-build_payload.excerpt.py:1-25 · blob 9636d7e9194781b01f501e555c4f3cc373d74f8b · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: none found · domain stage: unknown · users: none · canonical: unreached_review
# PROVENANCE
# source_repo: pipelinenews
# source_path: tools/intelligence/cartridges/wider-fleet/build_payload.py
# head_sha (pipelinenews): bab117e4bff007939a9230079788b8643c650a4e
# lines: 155-172 (the 'row["t"]' technology-bucket field the wider-fleet emitter
# above reads as its 'technology' query parameter)
#
        if raw in SPINE_TYPES:
            continue
        coordinates = (feature.get("geometry") or {}).get("coordinates") or []
        if len(coordinates) < 2:
            skipped += 1
            continue

        match, reason = (resolve(index, props) if index else (None, "no csv supplied"))
        how[reason] += 1

        row = {
            "n": props.get("name") or "",
            "o": props.get("operator") or "",
            "t": props.get("tech") or "other",
            "rt": raw,
            "s": props.get("status") or "",
            "c": megawatts(props.get("capacity")) or 0.0,
            "ll": [round(float(coordinates[0]), 5), round(float(coordinates[1]), 5)],

Audit Receivers

A JavaScript module in the tools folder of Ventus Grid Engine that reads PipelineNews rows, projects and receiver audit. It is built from the arg step (`arg`).

storageventus-grid-engine / tools/audit-receivers.mjs · lines 1–94 of 94 · Entry point

What it does
It loads PipelineNews rows, projects and receiver audit. Defines arg. Uses libraries node:fs, node:path, node:url. Side effects: reads or writes files.
Inputs & outputs
In: JSON file pipelinenews-rows.json; JSON file projects.json; command-line arguments. Out: JSON file receiver-audit.json.
Downstream impact
Used directly by 1 file: Deeplink Receiver Audit Workflow (ventus-grid-engine).
What it achieves
Run the query over real project rows and report.
Why it matters
Run by Deeplink Receiver Audit Workflow.
Application
ventus-grid-engine · tools · JavaScript module
Uses
Contract (import), node:fs, node:path, node:url
Used by
run by Deeplink Receiver Audit Workflow (workflow run)
Produces
arg
Defines here
arg
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
ventus-grid-engine@ad566356a44e006682e956483d569f31ddbb9630 tools/audit-receivers.mjs:1-94 · blob 27c4f753d4b09215136cd7a6b66d99c6f57b8d2b · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: production_core
/* audit-receivers.mjs — run the query over real project rows and report.
 *
 * The query itself lives in deeplink/contract.js as auditProjectRows, so this
 * tool and the proof that gates it run the same code. An audit whose logic
 * differs from the fix it authorises is not a gate.
 *
 * READ-ONLY. It rewrites nothing, anywhere. The engine publishes the contract;
 * it does not edit its consumers. The fault this exists to prevent was a link
 * silently pointing at a receiver that carries no engine, and the cure must not
 * be a workflow that silently rewrites links across the estate.
 *
 *   node tools/audit-receivers.mjs --report
 *   node tools/audit-receivers.mjs --rows path/to/rows.json
 *
 * With no --rows it reads the published Pipeline News release contract if a
 * local copy is present, and otherwise audits nothing and says so — it does not
 * reach for the network, because this runs in the step that must work offline.
 */
import { readFileSync, writeFileSync, existsSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { auditProjectRows, CANONICAL_RECEIVER, RETIRED_RECEIVERS } from '../deeplink/contract.js';

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');

function arg(flag) {
    const i = process.argv.indexOf(flag);
    return i > -1 && process.argv[i + 1] && !process.argv[i + 1].startsWith('--')
        ? process.argv[i + 1] : null;
}

/* Rows come from a file, never from a socket. A gate that needs the network
   cannot gate anything when the network is what has changed. */
const rowsPath = arg('--rows');
let rows = [];
let source = 'none';

if (rowsPath && existsSync(rowsPath)) {
    const parsed = JSON.parse(readFileSync(rowsPath, 'utf8'));
    rows = Array.isArray(parsed) ? parsed : (parsed.rows || parsed.projects || []);
    source = rowsPath;
} else {
    /* Known local locations, in order. Absent is a reported state, not a
       silent skip: a check that quietly finds nothing to check is the failure
       mode this estate has paid for repeatedly. */
    const candidates = [
        path.join(ROOT, 'sources', 'pipelinenews-rows.json'),
        path.join(ROOT, '..', 'globalgrid2050', 'uk_renewables_pipeline', 'v9.7', 'data', 'projects.json')
    ];
    const found = candidates.find((p) => existsSync(p));
    if (found) {
        const parsed = JSON.parse(readFileSync(found, 'utf8'));
        rows = Array.isArray(parsed) ? parsed : (parsed.rows || parsed.projects || []);
        source = found;
    }
}

const audit = auditProjectRows(rows);

const report = {
    schema: 'ventus.grid-engine.receiver-audit.v1',
    generated_utc: new Date().toISOString(),
    canonical_receiver: CANONICAL_RECEIVER,
    retired_receivers: RETIRED_RECEIVERS,
    source,
    rows_read: audit.total,
    with_repd_identity: audit.with_identity,
    linkable: audit.linkable,
    identity_but_no_geometry: audit.no_geometry,
    currently_on_a_retired_receiver: audit.on_retired_receiver,
    needs_update: audit.needs_update,
    /* Sampled, not truncated silently: the count above is the whole truth and
       this is only what a reader needs to see the shape of it. */
    sample_needing_update: audit.entries
        .filter((e) => e.linkable && e.current_href && e.current_href !== e.expected_href)
        .slice(0, 20)
};

writeFileSync(path.join(process.cwd(), 'receiver-audit.json'),
    JSON.stringify(report, null, 2) + '\n');

console.log(`source                       ${report.source}`);
console.log(`rows read                    ${report.rows_read}`);
console.log(`with an REPD identity        ${report.with_repd_identity}`);
console.log(`linkable                     ${report.linkable}`);
console.log(`identity but no geometry     ${report.identity_but_no_geometry}`);
console.log(`on a retired receiver        ${report.currently_on_a_retired_receiver}`);
console.log(`needs update                 ${report.needs_update}`);

if (report.source === 'none') {
    console.log('\nNo rows were available locally, so nothing was audited. That is reported,');
    console.log('not passed: this step opens no socket by design, and a check that finds');
    console.log('nothing to check has not checked anything.');
}

Build Browser Observer

A JavaScript module in the tools folder of Ventus Grid Engine. It builds browser observer (`buildBrowserObserver`) and is built from the read step (`read`).

storageventus-grid-engine / tools/build-browser-observer.mjs · lines 1–19 of 19 · Not reached from any entry point (candidate for review)

What it does
It loads data. Defines buildBrowserObserver, read. Uses libraries node:fs, node:path, node:url. Side effects: reads or writes files.
Inputs & outputs
In: command-line arguments.
Downstream impact
Used directly by 1 file: Browser Observer Proof (ventus-grid-engine).
What it achieves
Deterministic browser bundle of the owned receipt and presentation code.
Why it matters
Imported by Browser Observer Proof.
Application
ventus-grid-engine · tools · JavaScript module
Uses
node:fs, node:path, node:url
Used by
imported by Browser Observer Proof (import)
Produces
buildBrowserObserver
Defines here
buildBrowserObserver, read
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
ventus-grid-engine@ad566356a44e006682e956483d569f31ddbb9630 tools/build-browser-observer.mjs:1-19 · blob cfb2fcb37a0f7eec57c5d4feb0a5da853b8b9faf · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: unreached_review
/** Deterministic browser bundle of the owned receipt and presentation code.
 * Usage: node tools/build-browser-observer.mjs <output-file>
 * This bundles observation only; the caller must supply its actual calculation.
 */
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
export function buildBrowserObserver() {
  const read = name => fs.readFileSync(path.join(root, 'engine', name), 'utf8').replace(/\r\n/g, '\n');
  const geodesy = read('v9-geodesy.js').replace(/^export /gm, '');
  const observer = read('compute-observer.js').replace(/^import .*;\n/m, '').replace(/^export /gm, '');
  const presentation = read('compute-presentation.js').replace(/^export /gm, '');
  return `/* Ventus Grid Engine: generated receipt observer; not a substitute nearest engine. */\n(() => {\n'use strict';\nconst distanceKm = (() => {\n${geodesy}\nreturn distanceKm;\n})();\n${observer}\n${presentation}\nglobalThis.VentusGridCompute = Object.freeze({ schema, distanceKm, createComputeObserver, describeComputeReceipt });\n})();\n`;
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
  if (!process.argv[2]) throw new Error('Output file is required');
  fs.writeFileSync(process.argv[2], buildBrowserObserver());
}

Geometry Audit Workflow

A GitHub Actions workflow in Wire Frame Scanner. Runs on push, on a schedule and by hand.

automationwire-frame-scanner / .github/workflows/geometry-audit.yml · lines 1–38 of 38 · Entry point

What it does
It runs automated jobs on GitHub Actions. Side effects: starts processes.
Downstream impact
It is itself an entry point (workflow); no other file was found loading it.
What it achieves
Runs Geometry Audit (`audit/geometry_audit.py`).
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
wire-frame-scanner · .github/workflows · workflow
Uses
Geometry Audit (workflow run)
Used by
none found
Produces
none declared
Defines here
geometry-audit
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
wire-frame-scanner@43b27be73afab3c2563701b9534bfc30959804ee .github/workflows/geometry-audit.yml:1-38 · blob 6801afd8444ab4fafa5f1c8b559c8152bf2698cd · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: unknown · users: none · canonical: unknown
name: geometry-audit
# The geometry CI audit (audit/geometry_audit.py) against the simulator's main: NumPy on hosted CI for every push and
# once a day; the CuPy path runs on the self-hosted GPU runner when it is started (workflow_dispatch, gpu: true).
on:
  push:
    branches: [main]
  schedule:
    - cron: '17 5 * * *'
  workflow_dispatch:
    inputs:
      gpu:
        description: 'Run on the self-hosted GPU runner (CuPy)'
        type: boolean
        default: false
jobs:
  audit:
    runs-on: ${{ inputs.gpu && 'self-hosted' || 'ubuntu-latest' }}
    timeout-minutes: 15
    steps:
      - uses: actions/checkout@v4
      - uses: actions/checkout@v4
        with:
          repository: Ventusltd/energy-transition-simulator
          path: sim
      - uses: actions/setup-node@v4
        with:
          node-version: '22'
      - uses: actions/setup-python@v5
        if: ${{ !inputs.gpu }}
        with:
          python-version: '3.12'
      - run: python -m pip install numpy
        if: ${{ !inputs.gpu }}
      - run: python audit/geometry_audit.py --repo sim --out audit-out
      - uses: actions/upload-artifact@v4
        with:
          name: geometry-audit
          path: audit-out

Scanner Workflow

A GitHub Actions workflow in Wire Frame Scanner. Runs on push, on pull requests and by hand.

automationwire-frame-scanner / .github/workflows/scanner.yml · lines 1–22 of 22 · Entry point

What it does
It runs automated jobs on GitHub Actions. Side effects: starts processes.
Downstream impact
It is itself an entry point (workflow); no other file was found loading it.
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; it is an entry point.
Application
wire-frame-scanner · .github/workflows · workflow
Uses
none found
Used by
none found
Produces
none declared
Defines here
scanner
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
wire-frame-scanner@43b27be73afab3c2563701b9534bfc30959804ee .github/workflows/scanner.yml:1-22 · blob 24821be3c9c17fd0057adfe25ec9b4592c612f3a · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: process · domain stage: unknown · users: none · canonical: unknown
name: scanner
on:
  push:
    branches: ['scanner/**', 'cloud/**', 'build/**']
  pull_request:
  workflow_dispatch:
jobs:
  cpu:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with: { python-version: '3.12' }
      - run: pip install numpy matplotlib
      # CuPy is absent on the runner: each test runs NumPy only and reports the GPU comparison as n/a.
      - name: Every tests/test_*.py script (exit 0 = pass)
        run: |
          set -e
          for t in tests/test_*.py; do echo "== $t"; python "$t"; done
      - uses: actions/upload-artifact@v4
        if: always()
        with: { name: scanner-png, path: '**/*.png', if-no-files-found: ignore }

Test Fictional

A test in the tests folder of Wire Frame Scanner that checks Fictional.

testwire-frame-scanner / tests/test_fictional.py · lines 1–98 of 98 · Not reached from any entry point (candidate for review)

What it does
It tests its inputs. Defines check, seglen, all_tagged. Uses libraries math, os, sys, numpy. Side effects: starts processes.
What it achieves
It is built from the check step (`check`), the seglen step (`seglen`) and the all tagged helper (`all_tagged`). Exact geometry of the fictional parametric design proposals (`scanner/fictional.py`).
Why it matters
Guards the behaviour of Fictional.
Application
wire-frame-scanner · tests · test
Uses
Fictional (import), math, os, sys, numpy
Used by
none found
Produces
check, seglen, all_tagged
Defines here
check, seglen, all_tagged
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
wire-frame-scanner@43b27be73afab3c2563701b9534bfc30959804ee tests/test_fictional.py:1-98 · blob 6f1a1edc98e149546efa7b74685ac9fab8546341 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: unknown · users: none · canonical: unreached_review
"""Exact geometry of the fictional parametric design proposals (scanner/fictional.py).
Run: python3 tests/test_fictional.py
"""
import math, os, sys
import numpy as np
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
from scanner import fictional as F

E = 1e-9
results = []


def check(name, ok):
    results.append((name, bool(ok)))


def seglen(s):
    return math.dist(s[0], s[1])


def all_tagged(obj):
    """Every number in the model sits in a {'value','unit','provenance'} dict with the design-proposal tag."""
    if isinstance(obj, dict):
        if 'value' in obj:
            return obj.get('provenance') == F.PROV and 'unit' in obj and isinstance(obj['value'], (int, float))
        return all(all_tagged(v) for v in obj.values())
    if isinstance(obj, (list, tuple)):
        return all(all_tagged(v) for v in obj)
    return not isinstance(obj, (int, float))  # a bare number anywhere fails


# box
m, s = F.box(3.0, 4.0, 5.0)
L = sorted(round(seglen(x), 12) for x in s)
check('box has 12 edges', len(s) == 12)
check('box edge lengths 4x3, 4x4, 4x5', L == [3.0] * 4 + [4.0] * 4 + [5.0] * 4)
check('box tagged', all_tagged(m))

# solar block, several cases
for (mw, wp, ml, mwid, mpt, p, tilt, az, tr) in [(5.0, 550, 2.278, 1.134, 28, 6.0, 20, 180, 2),
                                                 (12.3, 600, 2.384, 1.303, 26, 7.5, 25, 165, 2),
                                                 (1.0, 450, 1.9, 1.0, 36, 5.0, 15, 200, 3)]:
    m, s = F.solar_block(mw, wp, ml, mwid, mpt, p, tilt, az, table_rows=tr)
    t = m['tables']['value']
    cap = t * mpt * wp / 1e6
    one = mpt * wp / 1e6
    check(f'{mw} MW: tables x modules x Wp within one table of MW', cap >= mw - E and cap - mw < one)
    check(f'{mw} MW: rects == tables, 4 edges each', len(m['table_rects']) == t and len(s) == 4 * t)
    fx, fy = math.sin(math.radians(az)), math.cos(math.radians(az))
    fronts = {}
    for r in m['table_rects']:
        c0 = [q['value'] for q in r['corners'][0]]
        fronts.setdefault(r['row']['value'], c0)
    ok = all(abs(((fronts[k][0] - fronts[k + 1][0]) * fx + (fronts[k][1] - fronts[k + 1][1]) * fy) - p) < E
             for k in range(len(fronts) - 1))
    check(f'{mw} MW: row spacing equals pitch ({len(fronts)} rows)', ok and len(fronts) == m['rows']['value'])
    r0 = m['table_rects'][0]; c = [[q['value'] for q in pt] for pt in r0['corners']]
    slope = math.dist(c[0], c[3]); rise = c[3][2] - c[0][2]
    check(f'{mw} MW: table slope length and tilt exact', abs(slope - tr * ml) < E and
          abs(math.degrees(math.asin(rise / slope)) - tilt) < 1e-9 and abs(math.dist(c[0], c[1]) - mpt // tr * mwid) < E)
    check(f'{mw} MW: every value tagged', all_tagged(m))

# heights raster: table heights between front and back, zero elsewhere; tilt recoverable
m, _ = F.solar_block(0.5, 500, 2.0, 1.0, 20, 6.0, 20, 180, table_rows=2, origin=(90.0, 5.0))
H, xs, ys = F.solar_block_heights(m, (-10.0, -5.0, 110.0, 70.0), 0.25)
fh, bh = m['front_height']['value'], m['back_height']['value']
on = H > 0
check('heights raster: covered cells within front..back height', on.any() and H[on].min() >= fh - E and H[on].max() <= bh + E)
check('heights raster: covered area ~ tables x footprint', abs(on.sum() * 0.0625 - m['tables']['value'] *
      m['table_length']['value'] * m['table_depth_horizontal']['value']) / on.sum() / 0.0625 < 0.1)

# fenced compound
m, s = F.fenced_compound(40.0, 25.0, 2.4, 3.0)
rails = [x for x in s if x[0][2] == x[1][2] == 0.0]
check('compound perimeter 2(w+d)', abs(sum(seglen(x) for x in rails) - 130.0) < E and m['perimeter']['value'] == 130.0)
posts = [x for x in s if x[0][:2] == x[1][:2]]
check('compound posts spaced <= spacing, all fence height', len(posts) == m['posts']['value'] == 14 + 9 + 14 + 9
      and all(abs(seglen(x) - 2.4) < E for x in posts))
check('compound tagged', all_tagged(m))

# cable route
m, s = F.cable_route((0.0, 0.0), (300.0, 400.0), 0.9, 0.45)
check('route length exact', abs(m['length']['value'] - 500.0) < E and abs(seglen(s[0]) - 500.0) < E)
check('trench cross-section width and depth', abs(seglen(s[2]) - 0.45) < E and abs(seglen(s[1]) - 0.9) < E)
check('route tagged', all_tagged(m))

# pylon row
m, s = F.pylon_row((5.0, 5.0), 37.0, 350.0, 6)
wires = s[6:]
check('pylon spans exact', len(wires) == 5 and all(abs(seglen(x) - 350.0) < 1e-9 for x in wires))
check('pylon route length', abs(m['route_length']['value'] - 1750.0) < E)
check('pylon tagged', all_tagged(m))

for n, ok in results:
    print(f"{'PASS' if ok else 'FAIL'}  {n}")
npass = sum(ok for _, ok in results)
print(f"\n{npass}/{len(results)} pass")
sys.exit(0 if npass == len(results) else 1)

Test Fictional Loop

A test in the tests folder of Wire Frame Scanner that checks Wire Frame Scanner — Scanner and Vlidar.

testwire-frame-scanner / tests/test_fictional_loop.py · lines 1–80 of 80 · Entry point · pattern ground (shared by 13 files)

What it does
It tests its inputs. Defines ground, build, cdiff, run. Uses libraries math, os, sys, numpy. Side effects: starts processes.
Downstream impact
It is itself an entry point (test); no other file was found loading it.
What it achieves
It is built from the ground step (`ground`), the build step (`build`) and the cdiff step (`cdiff`). Closed loop on fictional designs: fictional.solar_block -> virtual LiDAR -> scanner core -> compare with DESIGN.
Why it matters
Guards the behaviour of Wire Frame Scanner — Scanner, Vlidar and Fictional.
Application
wire-frame-scanner · tests · test
Uses
Wire Frame Scanner — Scanner (import), Vlidar (import), Fictional (import), math, os, sys, numpy
Used by
none found
Produces
ground, build, cdiff, run
Defines here
ground, build, cdiff, run
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
wire-frame-scanner@43b27be73afab3c2563701b9534bfc30959804ee tests/test_fictional_loop.py:1-80 · blob e5039b972040e6b41616ef7cd21c01986b380ac0 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: unknown · users: none · canonical: unknown
"""Closed loop on fictional designs: fictional.solar_block -> virtual LiDAR -> scanner core -> compare with DESIGN.

For each fictional solar design, the design's tables are rasterised with fictional.solar_block_heights (0.25 m) and
used as the site model's object heights; vlidar surveys it over rolling ground; core reads only DSM minus DTM > 1 m.
Tolerances (same as tests/test_vlidar_loop.py): pitch +/- 0.25 m, row direction +/- 1 deg.

Direction convention. fictional uses compass bearings (0 = +y, 90 = +x, clockwise); tables face azimuth_deg and
rows run along compass azimuth_deg + 90. core.row_normal/refine_normal return the row NORMAL in image-x convention
(radians from +x toward +row index); vlidar.rasterise puts survey y on the row index, so that is the survey's math
angle (from +x, counter-clockwise). Recovered row direction (math deg, mod 180) = (deg(theta) - 90) mod 180,
converted to compass mod 180 as (90 - math) mod 180. Designed row direction compass mod 180 = (azimuth + 90) mod 180.

This proves consistency between our own generator and our own scanner, not truth about any real site.
Run: python tests/test_fictional_loop.py
"""
import math, os, sys
import numpy as np
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
from scanner import core, vlidar, fictional

CELL, HCELL, MARGIN = 0.5, 0.25, 12.0
# (MW, pitch m, tilt deg, azimuth deg) -- fictional designs, every value assumed
DESIGNS = [(0.6, 5.0, 15.0, 180.0), (0.8, 7.5, 25.0, 160.0), (1.0, 9.0, 30.0, 213.0),
           (0.7, 12.0, 35.0, 135.0), (0.9, 6.5, 20.0, 241.0)]
MOD = dict(module_w_wp=450.0, module_len_m=2.1, module_wid_m=1.1, modules_per_table=24)


def ground(xp, x, y):
    return 5.0 + 1.5 * xp.sin(x / 37.0) + 1.0 * xp.cos(y / 29.0)


def build(mw, pitch, tilt, az):
    m, _ = fictional.solar_block(mw, pitch_m=pitch, tilt_deg=tilt, azimuth_deg=az, **MOD)
    pts = np.array([[q['value'] for q in p][:2] for t in m['table_rects'] for p in t['corners']])
    lo, hi = pts.min(0), pts.max(0)
    m, _ = fictional.solar_block(mw, pitch_m=pitch, tilt_deg=tilt, azimuth_deg=az,
                                 origin=(MARGIN - lo[0], MARGIN - lo[1]), **MOD)
    extent = float(math.ceil((hi - lo).max() + 2 * MARGIN))
    return m, extent


def cdiff(a, b):
    d = abs(a - b) % 180
    return min(d, 180 - d)


def run():
    out = []
    for (mw, pitch, tilt, az) in DESIGNS:
        m, E = build(mw, pitch, tilt, az)
        H, xs, ys = fictional.solar_block_heights(m, E, HCELL)
        n = H.shape[0]
        obj = lambda xp, x, y: xp.asarray(H)[xp.clip((y / HCELL).astype(np.int32), 0, n - 1),
                                            xp.clip((x / HCELL).astype(np.int32), 0, n - 1)]
        x, y, first, last = vlidar.survey(np, E, ground, obj, ppsm=8.0, noise_m=0.05, seed=7)
        dsm = vlidar.rasterise(np, x, y, first, E, CELL)
        dtm = vlidar.rasterise(np, x, y, last, E, CELL)
        mask = (dsm - dtm) > 1.0
        th = core.refine_normal(np, mask, core.row_normal(np, mask), CELL)
        r = core.row_pitch(np, mask, th, CELL)
        got_math = (math.degrees(th) - 90) % 180
        got_dir = (90 - got_math) % 180
        des_dir = (az + 90) % 180
        got_p = r[0] * CELL if r else None
        dd = cdiff(got_dir, des_dir)
        ok = got_p is not None and dd <= 1.0 and abs(got_p - pitch) <= 0.25
        out.append((mw, tilt, az, des_dir, pitch, got_dir, got_p, dd, m['rows']['value'], int(x.size), E, ok))
    return out


if __name__ == '__main__':
    res = run()
    for (mw, tilt, az, dd_, p, gd, gp, dd, rows, npts, E, ok) in res:
        gps = f"{gp:.3f}" if gp is not None else "None"
        print(f"{'PASS' if ok else 'FAIL'}  design {mw} MW tilt {tilt:.0f} az {az:.0f}: rows {dd_:6.2f} deg, pitch {p:5.2f} m"
              f"  ->  recovered rows {gd:6.2f} deg (err {dd:.2f}), pitch {gps} m  ({rows} rows, {npts} pulses, {E:.0f} m)")
    k = sum(r[-1] for r in res)
    print(f"\n{k}/{len(res)} fictional designs recovered (row direction compass mod 180, +/-1 deg; pitch +/-0.25 m)")
    print("This proves consistency between our own generator (fictional.py) and our own scanner (vlidar + core), not truth.")
    sys.exit(0 if k == len(res) else 1)