In this section
- Geodesy Proof geodesy · ventus-grid-engine / proofs/geodesy.proof.mjs lines 1–201
- Route Obstacles Proof other · ventus-grid-engine / proofs/route-obstacles.proof.mjs lines 1–178
- Atlas Pointer Deep Link transform · ventus-grid-engine / sources/deeplink-extracts/emitter/atlas-pointer-deep-link.mjs lines 1–261
Geodesy Proof
A JavaScript module in the proofs folder of Ventus Grid Engine that uses haversine. It is built from the check step (`check`) and the near step (`near`).
geodesyventus-grid-engine / proofs/geodesy.proof.mjs · lines 1–201 of 201 · Not reached from any entry point (candidate for review)
- What it does
- Defines check, near. Side effects: starts processes.
- Why it exists in the grid workflow
- Domain stage site_feasibility (topic 'maps-gis'): substation-to-site feasibility (terrain, LiDAR and connection evidence before design), a journey named in Ventus Ltd's brief.
- What it achieves
- The maths this repo isolated must keep answering the same numbers, and must keep disagreeing where it is right to disagree.
- 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), Geo Area (import), Geo Shapes (import), Geo GeoJSON (import)
- Used by
- none found
- Produces
- check, near
- Defines here
- check, near
- 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/geodesy.proof.mjs:1-201 · blob 8985e941bf4c773f7ad8f720273e3529f976f64e · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: site_feasibility · users: IPP_developer, landowner_planner · canonical: unreached_review
/* geodesy.proof.mjs — the maths this repo isolated must keep answering the
* same numbers, and must keep disagreeing where it is right to disagree.
*
* Every check below names a property of the real system in plain English.
* A check is not "test 7 passed"; it is a sentence worth reading in a failure
* report at 2am.
*
* Run: node proofs/geodesy.proof.mjs
*/
import {
EARTH_RADIUS_KM, R_ATLAS, R_UK, R_MEAN, MAX_RADIUS_KM,
haversine, haversineUK
} from '../engine/geo-core.js';
import { polygonAreaKm2, polylinePerimeterKm, circleCapAreaKm2 } from '../engine/geo-area.js';
import { destinationCirclePoints, circleVertexCount, ZONE_DRAW_VERTICES } from '../engine/geo-shapes.js';
import { circleFeatureCollection } from '../engine/geo-geojson.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;
/* ── The earth model ─────────────────────────────────────────────────────── */
check('the default radius is the estate default R_ATLAS = 6378.137, unchanged, '
+ 'so an extracted function reproduces V8 numbers exactly and a regression '
+ 'looks like a regression',
EARTH_RADIUS_KM === 6378.137 && R_ATLAS === EARTH_RADIUS_KM);
check('R_UK is the Gaussian mean radius of curvature at 54N, the accurate '
+ 'option for new work, and it is LARGER than the default — both deployed '
+ 'constants are too small at GB latitudes, which is the fact that makes '
+ '"swap to the mean radius" the wrong instinct',
R_UK === 6384.7272 && R_UK > R_ATLAS && R_ATLAS > R_MEAN);
check('R_MEAN is exported only to reproduce existing Turf-based results, and '
+ 'is the least accurate of the three here: switching the default to it '
+ 'would roughly double the error rather than remove it',
R_MEAN === 6371.0088
&& Math.abs(R_MEAN - R_UK) > Math.abs(R_ATLAS - R_UK));
check('the default is within about one part in a thousand of the UK-accurate '
+ 'radius — smaller than the uncertainty in a REPD site centroid, so the '
+ 'radius is not the dominant error in any grid distance this repo reports',
Math.abs(R_ATLAS - R_UK) / R_UK < 1.5e-3);
check('MAX_RADIUS_KM is the antipodal distance on the model actually in use',
near(MAX_RADIUS_KM, Math.PI * EARTH_RADIUS_KM, 1e-9));
/* ── haversine: argument order is (lon, lat), and getting it backwards is
* silent, so it is asserted rather than trusted ─────────────────────────── */
// One degree of latitude is about 111.3 km anywhere. One degree of LONGITUDE
// at 60N is about half that. If the argument order were (lat, lon) these two
// would come out swapped, and nothing else in the system would complain.
const oneDegLat = haversine(0, 0, 0, 1);
const oneDegLonAt60 = haversine(0, 60, 1, 60);
check('haversine takes (lon, lat) pairs in GeoJSON order, not (lat, lon): one '
+ 'degree of latitude is about 111.3 km and one degree of longitude at 60N '
+ 'is about half that, which only holds if the order is as documented',
near(oneDegLat, 111.32, 0.05) && near(oneDegLonAt60, 55.66, 0.1));
check('a zero-length leg is 0 km and not NaN',
haversine(-2.35, 56.05, -2.35, 56.05) === 0);
check('distance is symmetric',
near(haversine(-2.35, 56.05, -0.1, 51.5), haversine(-0.1, 51.5, -2.35, 56.05), 1e-12));
check('haversineUK returns the same leg LONGER than the default, by exactly the '
+ 'radius ratio — the UK-accurate sphere is bigger, so the accurate answer '
+ 'is bigger, which is the opposite of what the naming instinct suggests',
near(haversineUK(-2.35, 56.05, -0.1, 51.5) / haversine(-2.35, 56.05, -0.1, 51.5),
R_UK / R_ATLAS, 1e-12)
&& haversineUK(-2.35, 56.05, -0.1, 51.5) > haversine(-2.35, 56.05, -0.1, 51.5));
/* ── Polygon area: the collapsed A/B implementations ─────────────────────── */
// The reference polygon, measured independently against BOTH original V8
// implementations before extraction. If this number moves, the extraction
// changed the maths.
const LONDON = [[-0.1000, 51.5000], [-0.0950, 51.5020], [-0.0900, 51.4995],
[-0.0930, 51.4960], [-0.0990, 51.4965]];
const london = polygonAreaKm2(LONDON);
check('the collapsed polygon area reproduces both original V8 implementations to '
+ '8 decimal places on the reference London polygon (0.30664823 km2) — this '
+ 'is the check that proves the extraction did not rewrite the maths',
near(london.areaKm2, 0.30664823, 5e-9));
// A 1 km x 1 km square at 55N, constructed on the SAME spherical model the
// formula integrates over. Building it from the usual ellipsoidal constants
// (110.574 km/deg lat, 111.320 km/deg lon) instead leaves a 0.44% residual
// that is the ellipsoid-vs-sphere difference, not an error in this code — a
// distinction worth keeping, because a test that blames the wrong component
// is worse than no test.
const D = Math.PI / 180, lat0 = 55;
const kmPerDegLat = EARTH_RADIUS_KM * D;
const dLat = 1 / kmPerDegLat;
const dLon = 1 / (EARTH_RADIUS_KM * D * Math.cos((lat0 + dLat / 2) * D));
const SQUARE = [[0, lat0], [dLon, lat0], [dLon, lat0 + dLat], [0, lat0 + dLat]];
// Measured residual is 1.02e-9 km2, about a thousandth of a square metre per
// square kilometre. That is the second-order term in the small-angle
// construction of the square, not slack in the formula, so the tolerance is
// set just above it rather than rounded up to something comfortable.
check('a 1 km by 1 km square at 55N, built on the same sphere the formula '
+ 'integrates over, measures 1 km2 to within five parts in a billion',
near(polygonAreaKm2(SQUARE).areaKm2, 1.0, 5e-9));
check('area is orientation-independent: reversing the winding does not flip the sign',
near(polygonAreaKm2([...LONDON].reverse()).areaKm2, london.areaKm2, 1e-12));
check('fewer than three points encloses zero area and returns zeros, not NaN',
polygonAreaKm2([[0, 0], [1, 1]]).areaKm2 === 0
&& polygonAreaKm2([]).areaKm2 === 0
&& !Number.isNaN(polygonAreaKm2([[0, 0]]).areaHa));
/* ── The acre drift that the collapse was supposed to remove ────────────── */
check('acres come from the exact 4046.85642 m2 per acre constant, not the rounded '
+ '247.105 acres per km2 that the Measure tool used — on the reference polygon '
+ 'that is 75.774428 ac, where the old rounded path gave 75.774311',
near(london.areaAc, 75.774428, 5e-6)
&& !near(london.areaAc, london.areaKm2 * 247.105, 1e-6));
check('every area result carries the same conversion family, so no caller has to '
+ 'convert for itself and drift again',
near(london.areaHa, london.areaM2 / 10000, 1e-12)
&& near(london.areaM2, london.areaKm2 * 1e6, 1e-6)
&& near(london.pitches, london.areaM2 / 7140, 1e-12));
/* ── The cap area that was deliberately NOT merged ───────────────────────── */
check('the spherical cap reduces to pi r squared at 1 km, where the earth is flat enough',
near(circleCapAreaKm2(1).areaKm2, Math.PI, 1e-5));
check('the spherical cap departs from pi r squared at 5000 km, to 0.9498 of the '
+ 'planar answer — the sphere behaving like a sphere, and exactly why this '
+ 'function was not merged into the polygon one',
near(circleCapAreaKm2(5000).areaKm2 / (Math.PI * 5000 * 5000), 0.94983, 1e-4));
check('cap area and polygon area remain different functions with different names, '
+ 'neither silently substitutable for the other',
circleCapAreaKm2 !== polygonAreaKm2);
/* ── Perimeter ───────────────────────────────────────────────────────────── */
check('a closed perimeter includes the closing leg and an open one does not',
polylinePerimeterKm(LONDON, true) > polylinePerimeterKm(LONDON, false));
check('the closing leg is exactly the last-to-first haversine',
near(polylinePerimeterKm(LONDON, true) - polylinePerimeterKm(LONDON, false),
haversine(LONDON[4][0], LONDON[4][1], LONDON[0][0], LONDON[0][1]), 1e-12));
check('a single point has no length', polylinePerimeterKm([[0, 0]], true) === 0);
/* ── Circle points: the fourth duplication, now one function ─────────────── */
const ring24 = destinationCirclePoints(-2.35, 56.05, 10, 24);
check('the circle generator returns exactly the requested number of points, '
+ 'unclosed, so one function serves both the 24-vertex zone-draw path and the '
+ '64/96/128-vertex render path that used to keep their own copies',
ring24.length === 24
&& !(ring24[0][0] === ring24[23][0] && ring24[0][1] === ring24[23][1]));
check('every generated point is the requested geodesic radius from the centre',
ring24.every(p => near(haversine(-2.35, 56.05, p[0], p[1]), 10, 1e-6)));
check('the first point is due north of the centre, as bearing zero requires',
near(ring24[0][0], -2.35, 1e-9) && ring24[0][1] > 56.05);
check('V8 vertex counts are preserved exactly, so a rendered ring stays comparable '
+ 'with what V8 drew',
circleVertexCount(10) === 64 && circleVertexCount(600) === 96
&& circleVertexCount(6000) === 128 && ZONE_DRAW_VERTICES === 24);
/* ── GeoJSON shaping stays out of the maths ─────────────────────────────── */
const fc = circleFeatureCollection(-2.35, 56.05, 10);
const ring = fc.features[0].geometry.coordinates[0];
check('the GeoJSON ring is explicitly closed, as the spec requires, while the raw '
+ 'generator leaves it open',
ring.length === 65 && ring[0][0] === ring[64][0] && ring[0][1] === ring[64][1]);
check('the FeatureCollection records the radius and centre it was built from, so a '
+ 'rendered circle can be traced back to the query that made it',
fc.features[0].properties.radius_km === 10
&& fc.features[0].properties.centre[0] === -2.35);
/* ── Report ─────────────────────────────────────────────────────────────── */
if (failures.length) {
console.error('geodesy proof FAILED (' + failures.length + ' of '
+ (failures.length + passed) + '):\n- ' + failures.join('\n- '));
process.exit(1);
}
console.log('geodesy proof PASS — ' + passed + ' checks');
export default { status: 'PASS', checks: passed };Route Obstacles Proof
A JavaScript module in the proofs folder of Ventus Grid Engine that calculates planar distances, covering motorways.
otherventus-grid-engine / proofs/route-obstacles.proof.mjs · lines 1–178 of 178 · Not reached from any entry point (candidate for review) · pattern throws (shared by 12 files)
- What it does
- It lists and searches motorways. Defines check, near, throws. Side effects: starts processes.
- 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. Domain terms in the code: motorways.
- What it achieves
- It is built from the check step (`check`), the near step (`near`) and the throws step (`throws`). The check a scalar corridor function could not make.
- Why it matters
- No other file in the estate was found to import it.
- Application
- ventus-grid-engine · proofs · JavaScript module
- Uses
- Route Obstacles (import), Corridor Estimate (import)
- Used by
- none found
- Produces
- check, near, throws
- Defines here
- check, near, throws
- 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/route-obstacles.proof.mjs:1-178 · blob 3919542c2aaab00433434b5520f5c985afd761a0 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: duplicate_candidate
/* route-obstacles.proof.mjs — the check a scalar corridor function could not
* make.
*
* The defect this module was written against, measured and named: South Antrim
* to the Western HVDC converter is 142.21 km, almost all of it Irish Sea, and
* corridor-estimate printed 177.05 km of "highway corridor" because it receives
* one scalar kilometre and never sees the coordinates. Every check below that
* matters is a check that could not exist inside a function taking a scalar.
*
* Run: node proofs/route-obstacles.proof.mjs
*/
import * as mod from '../engine/route-obstacles.js';
import { forCable, CABLE_FACTOR } from '../engine/corridor-estimate.js';
const { schema, OBSTACLES, NOT_COMPUTED, crossingLengthM, crossingSchedule, routeEstimate } = mod;
const failures = [];
let passed = 0;
const check = (n, c) => { c ? passed += 1 : failures.push(n); };
const near = (a, b, tol) => Math.abs(a - b) <= tol;
const throws = (fn, p) => { try { fn(); return false; } catch (e) { return p.test(e.message); } };
check('schema is declared', schema === 'ventus-grid-engine.route-obstacles.v1');
/* ── THE DEFECT. The Irish Sea route. ───────────────────────────────────── */
{
const SOUTH_ANTRIM_TO_WESTERN_HVDC_KM = 142.21;
/* What the scalar function does today, unchanged and still correct for what
it is: it has no way to know. This is not a criticism of forCable, it is
a demonstration that the check has to live somewhere else. */
const scalar = forCable(SOUTH_ANTRIM_TO_WESTERN_HVDC_KM);
check('the existing scalar corridor estimate still returns its calibrated 177.05 km, unchanged',
near(scalar.km, 177.05, 0.05));
/* What this module does once the crossing is declared. */
const sea = routeEstimate({
straightLineKm: SOUTH_ANTRIM_TO_WESTERN_HVDC_KM,
crossings: [{ type: 'open_water' }],
corridorFactor: CABLE_FACTOR
});
check('a route crossing open water returns NO corridor estimate — null, not a number',
sea.value === null && sea.corridorApplicable === false);
check('the refusal names open water as the blocker',
sea.schedule.blockedBy.includes('Open water / sea'));
check('the straight line is preserved unchanged, because it is a real measurement',
sea.straightLineKm === SOUTH_ANTRIM_TO_WESTERN_HVDC_KM);
check('the basis says plainly that a road factor would describe a route that does not exist',
/route that does not exist/i.test(sea.basis));
check('the basis names the structural reason: a scalar-only function never saw the coordinates',
/never saw the coordinates/i.test(sea.basis));
/* And the same distance over land, where the factor IS applicable. */
const land = routeEstimate({
straightLineKm: SOUTH_ANTRIM_TO_WESTERN_HVDC_KM, crossings: [], corridorFactor: CABLE_FACTOR
});
check('the same distance over land still returns the calibrated corridor estimate',
near(land.value, 177.05, 0.05) && land.corridorApplicable === true);
check('so the module changes the answer ONLY where the route crosses something that blocks it',
near(land.value, scalar.km, 1e-9));
}
/* ── Crossing method: what cannot be open-cut. ──────────────────────────── */
check('a motorway is trenchless', OBSTACLES.motorway.trenchless === true);
check('a railway is trenchless', OBSTACLES.railway.trenchless === true);
check('a navigable river is trenchless', OBSTACLES.navigable_river.trenchless === true);
check('a minor road is not — open-cut with traffic management is normal',
OBSTACLES.minor_road.trenchless === false);
check('only open water blocks a highway-corridor estimate; a motorway is crossed, not a blocker',
OBSTACLES.open_water.blocksCorridor === true && OBSTACLES.motorway.blocksCorridor === false);
check('every obstacle carries a reason a reader can act on',
Object.values(OBSTACLES).every(o => typeof o.why === 'string' && o.why.length > 50));
check('the railway reason names the approval that usually governs the programme',
/asset protection/i.test(OBSTACLES.railway.why));
/* ── Crossing length: the setback dominates. ────────────────────────────── */
{
const m = crossingLengthM({ widthM: 30, setbackM: 15 });
check('a 30 m motorway with 15 m setbacks is a 60 m span, not a 30 m drill', m.value === 60);
check('the span is double the obstacle width once setbacks are counted',
m.value / 30 === 2);
const deep = crossingLengthM({ widthM: 30, setbackM: 15, depthM: 8 });
check('declaring a depth lengthens the bore, because it dips and returns',
deep.value > m.value && near(deep.value, Math.hypot(30, 8) * 2, 1e-9));
check('with no depth declared the bore is the flat span, not a silently invented curve',
crossingLengthM({ widthM: 30, setbackM: 15, depthM: 0 }).value === 60);
check('the basis says a drill is never the width of the thing it passes under',
/never the width of the thing it passes under/i.test(m.basis));
check('the basis says widths and setbacks are the owner\'s requirements, hence inputs',
/inputs here and not constants/i.test(m.basis));
}
/* ── The schedule. ──────────────────────────────────────────────────────── */
{
const s = crossingSchedule({ crossings: [
{ type: 'motorway', widthM: 30, setbackM: 15 },
{ type: 'railway', count: 2, widthM: 12, setbackM: 20 },
{ type: 'minor_road', count: 3, widthM: 7, setbackM: 2 }
] });
check('crossings are counted including multiples', s.crossingCount === 6);
check('trenchless and open-cut are counted separately',
s.trenchlessCount === 3 && s.openCutCount === 3);
check('added length totals every crossing including multiples: 60 + 2x52 + 3x11',
near(s.addedLengthM, 60 + 2 * 52 + 3 * 11, 1e-9));
check('a route with no blocking crossing keeps the corridor factor applicable',
s.corridorApplicable === true);
check('each item reports the method a contractor would price',
s.items[0].method === 'trenchless' && s.items[2].method === 'open-cut');
}
/* A crossing counted but not costed must say so rather than contribute zero
silently — a zero that looks like an answer is the failure mode here. */
{
const s = crossingSchedule({ crossings: [{ type: 'motorway' }, { type: 'railway', widthM: 12, setbackM: 20 }] });
check('a crossing with no width declared contributes no length and is named as undeclared',
s.undeclaredLengths.includes('Motorway') && near(s.addedLengthM, 52, 1e-9));
check('the basis says undeclared crossings are counted, not costed',
/counted, not costed/i.test(s.basis));
}
/* ── Route estimate arithmetic. ─────────────────────────────────────────── */
{
const r = routeEstimate({
straightLineKm: 10,
crossings: [{ type: 'motorway', widthM: 30, setbackM: 15 }],
corridorFactor: 1.245
});
check('corridor is the straight line times the factor', near(r.corridorKm, 12.45, 1e-9));
check('the crossing allowance is added in kilometres', near(r.crossingAllowanceKm, 0.06, 1e-9));
check('the total is corridor plus crossings', near(r.value, 12.51, 1e-9));
check('the basis states how many crossings cannot be open-cut',
/1 cannot be open-cut|of which 1/i.test(r.basis));
check('the basis keeps the screening caveat',
/not a route, not a constructability assessment/i.test(r.basis));
}
/* ── Input discipline. ──────────────────────────────────────────────────── */
check('an unknown obstacle type is refused and the known list is named',
throws(() => crossingSchedule({ crossings: [{ type: 'moat' }] }), /not a known obstacle.*motorway/s));
check('a corridor factor below 1 is refused — a route cannot be shorter than the straight line',
throws(() => routeEstimate({ straightLineKm: 10, crossings: [], corridorFactor: 0.9 }), /at least 1/));
check('a fractional crossing count is refused',
throws(() => crossingSchedule({ crossings: [{ type: 'motorway', count: 1.5 }] }), /whole number/));
check('crossings must be an array, and an empty one is the way to say "crosses nothing"',
throws(() => crossingSchedule({ crossings: 'motorway' }), /must be an array/)
&& crossingSchedule({ crossings: [] }).crossingCount === 0);
check('a zero or negative width is refused',
throws(() => crossingLengthM({ widthM: 0, setbackM: 15 }), /greater than zero/));
/* ── Refusals, and the boundary with the module it protects. ────────────── */
{
const callable = Object.keys(mod).filter(k => typeof mod[k] === 'function');
check('no function finds or optimises a route',
callable.every(n => !/find|search|optimi[sz]e|path|shortest/i.test(n)));
check('no function prices a crossing or asserts consent',
callable.every(n => !/cost|price|consent|permit|approv/i.test(n)));
check('the refusals name the route itself, cost, consent and ground conditions',
['theRouteItself', 'crossingCost', 'crossingConsent', 'groundConditions'].every(k => k in NOT_COMPUTED));
check('the refusal on routing says crossings are declared by the user, not discovered',
/declared by the user, not discovered/i.test(NOT_COMPUTED.theRouteItself));
check('the straight-line first pass is untouched: corridor-estimate still exports its calibrated factor',
CABLE_FACTOR === 1.245);
}
if (failures.length) {
console.error('route-obstacles proof FAILED (' + failures.length + ' of '
+ (failures.length + passed) + '):\n- ' + failures.join('\n- '));
process.exit(1);
}
console.log('route-obstacles proof PASS — ' + passed + ' checks');
export default { status: 'PASS', checks: passed };Atlas Pointer Deep Link
A JavaScript module in the emitter folder of Ventus Grid Engine that works with solar and uses data from the GridAtlas repository.
Set aside from the main view: 93% of its lines are the same as releases/202608312018-pipelinenews/assets/202608312018-atlas-pointer-deep-link.mjs (pipelinenews), which stays. (near-copy-of, proposed by families.py). 92% of lines shared with PipelineNews Atlas Pointer Deep Link; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9296 to pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 releases/202608312018-pipelinenews/assets/202608312018-atlas-pointer-deep-link.mjs:1-249 cb85109f99373755ba2a868bff9b65ea78265f2d
- sha256 000c06b68b9a5faf6ffbb20c283604e27267d5fd93c2cf9285de21a6bac5383e
- target sha256 6f83fe433380d19e0946aa4f66177a20c40a39013e2024faaef62e4a76c795e9
- group of 2 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
transformventus-grid-engine / sources/deeplink-extracts/emitter/atlas-pointer-deep-link.mjs · lines 1–261 of 261 · Not reached from any entry point (candidate for review) · pattern finiteInRange (shared by 4 files)
- What it does
- It calculates solar. Defines invariant, finiteInRange, buildAtlasV9DeepLink, selfTest, add.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'atlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: solar.
- Inputs & outputs
- In: JSON file live-set.json.
- What it achieves
- It builds atlas v9 deep link (`buildAtlasV9DeepLink`) and is built from the invariant step (`invariant`) and the finite in range helper (`finiteInRange`). `head_sha` (PipelineNews): lines: 1-249 (whole file) NOTE: this is the file `app.mjs` actually imports (import line 1 of `app.mjs`).
- Why it matters
- No other file in the estate was found to import it.
- Application
- ventus-grid-engine · sources/deeplink-extracts/emitter · JavaScript module
- Uses
- GridAtlas — Atlas Page (estate URL), GlobalGrid2050 — Renewable Energy Planning Database (REPD) Grid Atlas v8 Page (estate URL)
- Used by
- mentioned in Standalone (comment link)
- Produces
- ATLAS_DEEP_LINK_CONTRACT, buildAtlasV9DeepLink, selfTest
- Defines here
- invariant, finiteInRange, buildAtlasV9DeepLink, selfTest, add
- 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/atlas-pointer-deep-link.mjs:1-261 · blob 18c84ab3ec2163aebbc54d981fc6960720b3a0de · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
/*
* PROVENANCE
* source_repo: pipelinenews
* source_path: releases/202609032329-pipelinenews/assets/202608312037-atlas-pointer-deep-link.mjs
* head_sha (pipelinenews): ade103ae2a2eec4f334e159b479f20b857d63515
* lines: 1-249 (whole file)
* NOTE: this is the file app.mjs actually imports (import line 1 of app.mjs).
* ACTIVE_TARGET here is "ported" -> https://ventusltd.github.io/gridatlas/atlas/
* -- this is the live, in-service emitter, not the sibling 202608311343 file
* (identical code, ACTIVE_TARGET="legacy") which exists in the same releases/
* tree but is NOT the file imported by app.mjs.
*/
/**
* PipelineNews -> GridAtlas deep-link cartridge.
*
* Generation 202608312037. Successor to 202608291447-atlas-pointer-deep-link.mjs.
* DRAFT - deployment: not-authorised. Review before promoting.
*
* ---------------------------------------------------------------------------
* WHAT CHANGED AND WHY
* ---------------------------------------------------------------------------
* The predecessor emitted /gridatlas/<release_id>/?repd_ref=<n>
* which fails twice:
*
* FAULT 1 - wrong path. The release is served at
* /gridatlas/atlas/releases/<release_id>/ and GridAtlas'
* atlas/current.json declares the stable route as /gridatlas/atlas/.
* The "atlas/" segment was missing, so every link 404s.
*
* Note the predecessor's own invariant ASSERTED the broken shape:
* receiverUrl.pathname === `/gridatlas/${release_id}/`
* so correcting base_url alone would have thrown. Both had to move
* together, which is why this is a new cartridge and not an edit.
*
* FAULT 2 - stripped payload. The link carried the reference alone, so the
* atlas had to resolve it by booting a 35.7 MB query engine before
* it could move the map. The known-good legacy link carries
* repd_ref + project + technology + capacity_mw + latitude +
* longitude + zoom and flies straight there, resolving nothing.
*
* Every one of those fields is ALREADY in the compact project index
* (fields: repd_ref, gg_project_id, name, technology, status,
* capacity_mw, county, region, operator, repd_record_updated,
* geometry_status, latitude, longitude) and is ALREADY passed to
* this function by app.mjs. The predecessor simply ignored them.
* No data change, no schema change, no GridAtlas change.
*
* The eligibility gate already requires geometry_status === "valid", which is
* exactly the guarantee that latitude and longitude are present. The contract
* that makes the full payload safe was there all along.
*
* ---------------------------------------------------------------------------
* THE OPEN DECISION (priority item L-04)
* ---------------------------------------------------------------------------
* Two receivers accept the same parameters:
* "legacy" - globalgrid2050.com/repd_grid_atlasv8/ - proven, in use today
* "ported" - ventusltd.github.io/gridatlas/atlas/ - the migration target
*
* Change ACTIVE_TARGET below. That is the entire switch. Both are validated by
* the same invariants, so neither can be selected in a broken state.
*/
const ATLAS_TARGETS = Object.freeze({
ported: Object.freeze({
id: "ported",
schema: "pipelinenews.gridatlas-live-pointer-receipt.v4",
classification: "VERIFIED_PROMOTION_ELIGIBLE_GRIDATLAS_V9",
generation: "202608300453",
release_id: "202608300453-atlas-v9",
// The STABLE route. GridAtlas atlas/current.json -> "live_route".
// Using the stable route rather than the pinned release means a GridAtlas
// release promotion does not silently break every PipelineNews link.
base_url: "https://ventusltd.github.io/gridatlas/atlas/",
pinned_release_url:
"https://ventusltd.github.io/gridatlas/atlas/releases/202608300453-atlas-v9/",
hostname: "ventusltd.github.io",
pathname: "/gridatlas/atlas/",
state_url: "https://ventusltd.github.io/gridatlas/state/live-set.json",
source_commit: "4f3e8fc5c7ea28edf83dbac9b231024723bcf231",
}),
legacy: Object.freeze({
id: "legacy",
schema: "pipelinenews.gridatlas-live-pointer-receipt.v4",
classification: "VERIFIED_LEGACY_ATLAS_V8_IN_SERVICE",
generation: "legacy",
release_id: "repd_grid_atlasv8",
base_url: "https://globalgrid2050.com/repd_grid_atlasv8/",
pinned_release_url: "https://globalgrid2050.com/repd_grid_atlasv8/",
hostname: "globalgrid2050.com",
pathname: "/repd_grid_atlasv8/",
state_url: null,
source_commit: null,
}),
});
/** L-04. One line. Both branches are invariant-checked below. */
const ACTIVE_TARGET = "ported";
const RECEIVER = ATLAS_TARGETS[ACTIVE_TARGET];
function invariant(condition, message) {
if (!condition) throw new Error(`Atlas receiver contract: ${message}`);
}
invariant(Boolean(RECEIVER), `ACTIVE_TARGET "${ACTIVE_TARGET}" is not a known receiver`);
const receiverUrl = new URL(RECEIVER.base_url);
invariant(receiverUrl.protocol === "https:", "receiver is not HTTPS");
invariant(receiverUrl.hostname === RECEIVER.hostname, "receiver hostname changed");
// Validate against the receiver's OWN declared pathname. The predecessor
// hardcoded a template here, which is what pinned the broken shape in place.
invariant(receiverUrl.pathname === RECEIVER.pathname, "receiver route mismatch");
invariant(receiverUrl.pathname.endsWith("/"), "receiver route must end in a slash");
/** Emitted in this order, matching the known-good legacy link exactly. */
const QUERY_PARAMETER_ORDER = Object.freeze([
"repd_ref", "project", "technology", "capacity_mw", "latitude", "longitude", "zoom",
]);
const DEFAULT_ZOOM = 12;
export const ATLAS_DEEP_LINK_CONTRACT = Object.freeze({
schema: "pipelinenews.atlas-current-deep-link-cartridge.v2",
generation: "202608312037",
supersedes: "pipelinenews.atlas-current-deep-link-cartridge.v1",
supersede_reason:
"v1 emitted a 404 path and carried repd_ref alone, forcing a 35.7 MB engine boot to resolve it",
deployment: "not-authorised",
active_target: ACTIVE_TARGET,
receiver: RECEIVER,
available_targets: Object.freeze(Object.keys(ATLAS_TARGETS)),
eligibility: Object.freeze({
field: "geometry_status",
equals: "valid",
ineligible_result: "",
presentation: "NO MAP",
}),
identity_anchor: "repd_ref",
query_parameter_order: QUERY_PARAMETER_ORDER,
inbound_match_semantics: "EXACT_PROJECT_REPD_REF",
context_parameters_are_advisory: true,
lifecycle:
"timestamped PipelineNews release; receiver authenticated at build and public readback",
});
/** Finite, in-range coordinate. Anything else means we do not emit one. */
function finiteInRange(value, limit) {
// Number(null) and Number("") are both 0, which is finite and in range. Without
// this guard a project with a missing longitude is emitted at longitude 0 - the
// Greenwich meridian - instead of having its coordinates dropped. Caught by
// selfTest case "drops both coordinates when only one is present".
if (value === null || value === undefined || value === "") return null;
const n = Number(value);
return Number.isFinite(n) && Math.abs(n) <= limit ? n : null;
}
/**
* Build the atlas deep link for a project.
*
* Identity (repd_ref) is REQUIRED and remains the only field the receiver
* matches on - EXACT_PROJECT_REPD_REF is unchanged. Everything else is
* advisory context that lets the map position itself without a lookup, and any
* field that is missing or malformed is simply omitted rather than guessed.
*
* @param {object} project compact project index row
* @returns {string} absolute URL, or "" when the project has no valid geometry
*/
export function buildAtlasV9DeepLink(project) {
if (project?.[ATLAS_DEEP_LINK_CONTRACT.eligibility.field]
!== ATLAS_DEEP_LINK_CONTRACT.eligibility.equals) return "";
const repdRef = String(project?.repd_ref ?? "").trim();
if (!/^\d+$/u.test(repdRef)) return "";
const url = new URL(RECEIVER.base_url);
url.searchParams.set("repd_ref", repdRef);
const name = String(project?.name ?? "").trim();
if (name) url.searchParams.set("project", name);
const technology = String(project?.technology ?? "").trim();
if (technology) url.searchParams.set("technology", technology);
const capacity = Number(project?.capacity_mw);
if (Number.isFinite(capacity) && capacity > 0) {
url.searchParams.set("capacity_mw", String(capacity));
}
// Emitted as a pair or not at all. Half a coordinate is worse than none.
const latitude = finiteInRange(project?.latitude, 90);
const longitude = finiteInRange(project?.longitude, 180);
if (latitude !== null && longitude !== null) {
url.searchParams.set("latitude", String(latitude));
url.searchParams.set("longitude", String(longitude));
url.searchParams.set("zoom", String(DEFAULT_ZOOM));
}
return url.href;
}
/**
* Self-test. Pure, no IO, no network. Callable from a build step or a verifier.
* Returns {ok, checks:[{name, ok, detail}]}.
*/
export function selfTest() {
const checks = [];
const add = (name, ok, detail) => checks.push({ name, ok: Boolean(ok), detail: detail ?? null });
const cleveHill = {
repd_ref: "6502", name: "Cleve Hill Solar Project", technology: "solar",
capacity_mw: 373, latitude: 51.338767, longitude: 0.913885,
geometry_status: "valid",
};
const href = buildAtlasV9DeepLink(cleveHill);
const u = href ? new URL(href) : null;
add("emits a link for a valid-geometry project", Boolean(href), href);
add("path ends in a slash and is the declared route",
u && u.pathname === RECEIVER.pathname, u && u.pathname);
add("carries repd_ref", u && u.searchParams.get("repd_ref") === "6502");
add("carries project name", u && u.searchParams.get("project") === "Cleve Hill Solar Project");
add("carries technology", u && u.searchParams.get("technology") === "solar");
add("carries capacity_mw", u && u.searchParams.get("capacity_mw") === "373");
add("carries latitude", u && u.searchParams.get("latitude") === "51.338767");
add("carries longitude", u && u.searchParams.get("longitude") === "0.913885");
add("carries zoom", u && u.searchParams.get("zoom") === String(DEFAULT_ZOOM));
// The regression that started this: a ref-only link is no longer produced
// for a project that has coordinates.
add("does NOT emit a ref-only link when coordinates exist",
u && [...u.searchParams.keys()].length > 1,
u && [...u.searchParams.keys()].join(","));
// Eligibility gate still closes.
add("no link when geometry is not valid",
buildAtlasV9DeepLink({ ...cleveHill, geometry_status: "missing" }) === "");
add("no link when repd_ref is not numeric",
buildAtlasV9DeepLink({ ...cleveHill, repd_ref: "B0850" }) === "");
// Partial coordinates must be dropped as a pair, not emitted half.
const half = new URL(buildAtlasV9DeepLink({ ...cleveHill, longitude: null }));
add("drops both coordinates when only one is present",
!half.searchParams.has("latitude") && !half.searchParams.has("longitude"),
half.search);
add("still carries identity when coordinates are dropped",
half.searchParams.get("repd_ref") === "6502");
// Out-of-range coordinates are treated as absent, not clamped.
const bad = new URL(buildAtlasV9DeepLink({ ...cleveHill, latitude: 999 }));
add("rejects out-of-range latitude rather than clamping it",
!bad.searchParams.has("latitude"));
// Golden ref from the predecessor contract must still resolve.
const golden = buildAtlasV9DeepLink({
repd_ref: "13599", name: "Golden", technology: "solar",
capacity_mw: 1, latitude: 52, longitude: -1, geometry_status: "valid",
});
add("golden repd_ref 13599 still emits", golden.includes("repd_ref=13599"));
return { ok: checks.every((c) => c.ok), target: ACTIVE_TARGET, checks };
}