GLOBALGRID2050 / EXPLORE CODE

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

Published Fault Level Proof and 3 more files

A JavaScript module in the proofs folder of Ventus Grid Engine covering 132kV, using SHA-256 and uses data from National Energy System Operator (NESO) data portal.

591 lines of JavaScript from ventus-grid-engine, in 4 files. Topic: Automation and CI. Section 1874 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. Power Factor Proof other · ventus-grid-engine / proofs/power-factor.proof.mjs lines 1–143
  2. Published Fault Level Proof electrical · ventus-grid-engine / proofs/published-fault-level.proof.mjs lines 1–209
  3. Rating Envelope Proof electrical · ventus-grid-engine / proofs/rating-envelope.proof.mjs lines 1–156
  4. Receiver Focus Param Proof ingest · ventus-grid-engine / proofs/receiver-focus-param.proof.mjs lines 1–83

Power Factor Proof

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

otherventus-grid-engine / proofs/power-factor.proof.mjs · lines 1–143 of 143 · Not reached from any entry point (candidate for review) · pattern throws (shared by 12 files)

What it does
It lists and searches its content. Defines check, near, throws. Side effects: starts processes.
What it achieves
The cheapest capacity anybody ever buys, checked. Its code works with 156.1 kVA.
Why it matters
No other file in the estate was found to import it.
Application
ventus-grid-engine · proofs · JavaScript module
Uses
Power Factor (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/power-factor.proof.mjs:1-143 · blob 3caec593a1a7ef4d7525a0504f3a6eb97f5a2230 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: unknown · users: none · canonical: unreached_review
/* power-factor.proof.mjs — the cheapest capacity anybody ever buys, checked.
 *
 * The worked case throughout: 1,000 kW at 0.85, corrected to 0.98. It is the
 * ordinary industrial one, and the numbers are round enough that an error is
 * obvious rather than plausible.
 *
 * Run: node proofs/power-factor.proof.mjs
 */

import * as mod from '../engine/power-factor.js';
const { schema, NOT_COMPUTED, reactivePowerKvar, apparentPowerKva,
    correctionKvar, againstAgreedCapacity } = 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.power-factor.v1');

/* ── The triangle. These are identities and must be exact. ──────────────── */

check('1,000 kW at 0.85 is 1,176.5 kVA',
    near(apparentPowerKva({ kw: 1000, powerFactor: 0.85 }).value, 1176.47, 0.01));

check('1,000 kW at 0.85 draws 619.7 kVAr',
    near(reactivePowerKvar({ kw: 1000, powerFactor: 0.85 }).value, 619.75, 0.01));

/* S^2 = P^2 + Q^2 must hold exactly, or the trigonometry is wrong. */
{
    const P = 1000, pf = 0.85;
    const S = apparentPowerKva({ kw: P, powerFactor: pf }).value;
    const Q = reactivePowerKvar({ kw: P, powerFactor: pf }).value;
    check('the power triangle closes: S squared equals P squared plus Q squared',
        near(S * S, P * P + Q * Q, 1e-6));
    check('and the power factor is P over S, by definition', near(P / S, pf, 1e-12));
}

/* At unity there is no reactive power at all. Written from the identity
   rather than through arccos/tan, so this is exactly zero and not 6e-9. */
check('at unity power factor the reactive power is EXACTLY zero, not nearly zero',
    reactivePowerKvar({ kw: 1000, powerFactor: 1 }).value === 0);

check('at unity, apparent power equals real power',
    apparentPowerKva({ kw: 1000, powerFactor: 1 }).value === 1000);

/* ── The correction, and the capacity it releases. ──────────────────────── */
{
    const c = correctionKvar({ kw: 1000, fromPowerFactor: 0.85, toPowerFactor: 0.98 });
    check('correcting 1,000 kW from 0.85 to 0.98 needs 416.7 kVAr',
        near(c.value, 416.70, 0.02));
    check('reactive power falls from 619.7 to 203.0 kVAr',
        near(c.reactiveBeforeKvar, 619.75, 0.01) && near(c.reactiveAfterKvar, 203.05, 0.01));
    check('apparent power falls from 1,176.5 to 1,020.4 kVA',
        near(c.apparentBeforeKva, 1176.47, 0.01) && near(c.apparentAfterKva, 1020.41, 0.01));
    check('156.1 kVA of connection capacity is released',
        near(c.capacityReleasedKva, 156.06, 0.02));
    check('that is 13.3% of the site demand on its connection',
        near(c.capacityReleasedPercent, 13.27, 0.02));
    check('the correction equals the difference in reactive power, which is the whole method',
        near(c.value, c.reactiveBeforeKvar - c.reactiveAfterKvar, 1e-9));
    check('the basis says the released capacity comes with no reduction in consumption',
        /no reduction in consumption/i.test(c.basis));
    check('the basis warns that unity is usually the wrong target and why',
        /unity is usually the\s+wrong target/i.test(c.basis.replace(/\s+/g, ' '))
        || /unity is usually the wrong target/i.test(c.basis.replace(/\s+/g, ' ')));
    check('the basis warns a fixed bank over-corrects at part load',
        /over-correct at part load/i.test(c.basis));
}

/* A worse target is not a correction. */
check('correcting to a WORSE power factor is refused',
    throws(() => correctionKvar({ kw: 1000, fromPowerFactor: 0.95, toPowerFactor: 0.85 }),
        /must be better than/));

check('correcting to the same power factor is refused, because it is not a correction',
    throws(() => correctionKvar({ kw: 1000, fromPowerFactor: 0.9, toPowerFactor: 0.9 }),
        /must be better than/));

/* The relationship that makes this worth doing: the worse the starting point,
   the more capacity correction returns. */
{
    const poor = correctionKvar({ kw: 1000, fromPowerFactor: 0.70, toPowerFactor: 0.95 });
    const fair = correctionKvar({ kw: 1000, fromPowerFactor: 0.90, toPowerFactor: 0.95 });
    check('a site at 0.70 releases far more capacity than one already at 0.90',
        poor.capacityReleasedKva > fair.capacityReleasedKva * 4);
    check('a site at 0.70 releases over a quarter of its connection demand',
        poor.capacityReleasedPercent > 25);
}

/* ── Against an agreed capacity. ────────────────────────────────────────── */
{
    const over = againstAgreedCapacity({ kw: 1000, powerFactor: 0.85, agreedKva: 1100 });
    check('1,000 kW at 0.85 exceeds an agreed 1,100 kVA', over.exceeds === true);
    check('the excess is quantified', /EXCEEDS the agreed capacity by 76\.5 kVA/.test(over.basis));

    const under = againstAgreedCapacity({ kw: 1000, powerFactor: 0.98, agreedKva: 1100 });
    check('the same load corrected to 0.98 fits inside the same agreed capacity',
        under.exceeds === false);
    check('which is the point: the connection stopped being the constraint without any '
        + 'reduction in consumption',
        over.exceeds && !under.exceeds && over.from.kw === under.from.kw);
    check('the basis says the agreed capacity is commercial and this is not a connection assessment',
        /commercial figure from a connection agreement/i.test(under.basis)
        && /not a connection assessment/i.test(under.basis));
}

/* ── Input discipline. ──────────────────────────────────────────────────── */

check('a power factor of 95 is refused, and the message says to pass 0.95',
    throws(() => apparentPowerKva({ kw: 1000, powerFactor: 95 }), /fraction.*0\.95/s));

check('a power factor above 1 is refused even just above',
    throws(() => apparentPowerKva({ kw: 1000, powerFactor: 1.01 }), /fraction/));

check('a zero or negative load is refused',
    throws(() => apparentPowerKva({ kw: 0, powerFactor: 0.9 }), /greater than zero/));

check('a non-numeric input is refused by type rather than coerced',
    throws(() => apparentPowerKva({ kw: '1000', powerFactor: 0.9 }), /finite number/));

/* ── Refusals. ──────────────────────────────────────────────────────────── */
{
    const callable = Object.keys(mod).filter(k => typeof mod[k] === 'function');
    check('no function designs equipment or prices anything',
        callable.every(n => !/design|bank|cost|price|charge|payback|tariff/i.test(n)));
    check('the refusals name bank design, charges, payback and varying load',
        ['capacitorBankDesign', 'reactiveCharges', 'payback', 'varyingLoad'].every(k => k in NOT_COMPUTED));
    check('the bank-design refusal names harmonic resonance as the reason, not vagueness',
        /harmonic resonance/i.test(NOT_COMPUTED.capacitorBankDesign)
        && /supply impedance/i.test(NOT_COMPUTED.capacitorBankDesign));
    check('each refusal is a readable reason rather than a label',
        Object.values(NOT_COMPUTED).every(v => typeof v === 'string' && v.length > 60));
}

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

Published Fault Level Proof

A JavaScript module in the proofs folder of Ventus Grid Engine covering 132kV, using SHA-256 and uses data from National Energy System Operator (NESO) data portal.

electricalventus-grid-engine / proofs/published-fault-level.proof.mjs · lines 1–209 of 209 · pattern clone (shared by 15 files)

What it does
It lists and searches 132kV. Defines check, clone. Side effects: starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (voltage levels 132kV (all 132kV or above)): 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: 132kV.
Inputs & outputs
Voltage levels named: 132kV.
Downstream impact
Used directly by 1 file: Papers — Published Fault Level Page (globalgrid2050, https://globalgrid2050.com/papers/202609060045-published-fault-level/). Reached from 48 other entry points, including Grid Engine — Compute Against Charging Page (globalgrid2050, https://globalgrid2050.com/grid_engine/202609060324-compute-against-charging/); Grid Engine — Connection Cap Page (globalgrid2050, https://globalgrid2050.com/grid_engine/202609060212-connection-cap/); Grid Engine — Corridor Estimate Page (globalgrid2050, https://globalgrid2050.com/grid_engine/202609060237-corridor-estimate/).
What it achieves
It is built from the check step (`check`) and the clone step (`clone`). A fault-level figure on an open map is allowed to be exactly one thing: what a publisher said, on a date, under a stated basis, by exact metric name. Its code works with 132 kV and 14.52 kA.
Why it matters
Loaded by the Published Fault Level page in GlobalGrid2050 at https://globalgrid2050.com/papers/202609060045-published-fault-level/.
Application
ventus-grid-engine · proofs · JavaScript module
Uses
Published Fault Level (import)
Used by
linked from Papers — Published Fault Level Page (link)
Produces
check, clone
Defines here
check, clone
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/published-fault-level.proof.mjs:1-209 · blob 72f93c037e044be4b5f5643b201d92c37067b757 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/* published-fault-level.proof.mjs — a fault-level figure on an open map is
 * allowed to be exactly one thing: what a publisher said, on a date, under a
 * stated basis, by exact metric name. This proof holds the module to that,
 * and — more importantly — holds it to what it must NOT do.
 *
 * Run: node proofs/published-fault-level.proof.mjs
 */

import * as mod from '../engine/published-fault-level.js';
const { schema, ETYS_METRICS, LTDS_METRICS, METRIC_LABELS, REFUSED_GENERIC_NAMES,
    CAVEAT, NOT_COMPUTED, NO_HEADROOM, record, quote } = mod;

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

/* A complete, honest record: the ETYS 2025 peak-demand figure for Abham
   132 kV, exactly as data-grid-gb normalises it, with the pinned artefact
   NESO publishes (fault_peak, sha256 from data-grid-gb/chatgpt/sources.json). */
const GOOD = {
    provenance: {
        publisher: 'NESO',
        publication: 'Electricity Ten Year Statement 2025, Appendix D',
        source_url: 'https://www.neso.energy/document/383951/download',
        sha256: 'ad8b54fa0b0562c34295514c150f33913a92fc756ff140e0154d53c181363440',
        /* The date NESO's ETYS documents page shows against "ETYS 2025
           Appendix D - Fault Levels Peak": 30 Jun 2026 (read 2026-09-05).
           The first version of this fixture carried 2025-11-27, a date that
           was never read anywhere - invented as a plausible fixture value in
           a proof whose subject is that a figure must be dated. Corrected. */
        published_date: '2026-06-30',
        study_basis: 'peak demand, winters 2025/26 to 2033/34',
        licence: 'as published by NESO'
    },
    site: { name: 'ABHAM', voltage_kv: 132, busbar: 'ABHA1 M2', operator: 'NGET' },
    metrics: {
        three_phase_rms_break_current_ka: { min: 12.78, max: 14.52 },
        three_phase_initial_peak_current_ka: { min: 31.28, max: 35.54 }
    }
};
const clone = () => JSON.parse(JSON.stringify(GOOD));

/* ── Identity and vocabulary ─────────────────────────────────────────────── */

check('the module identifies itself with a stable schema string',
    schema === 'ventus-grid-engine.published-fault-level.v1');

check('the ETYS vocabulary is the eight currents Appendix D publishes, named '
    + 'exactly as data-grid-gb normalises them — no more, no fewer',
    ETYS_METRICS.length === 8
    && ETYS_METRICS.includes('three_phase_rms_break_current_ka')
    && ETYS_METRICS.includes('single_phase_peak_break_current_ka')
    && ETYS_METRICS.every(n => METRIC_LABELS[n] && METRIC_LABELS[n].unit === 'kA'));

check('the LTDS vocabulary is kept separate from the ETYS eight, so a reader '
    + 'can see which publisher a name belongs to',
    LTDS_METRICS.length > 0
    && LTDS_METRICS.every(n => !ETYS_METRICS.includes(n) && METRIC_LABELS[n]));

check('every label a card may print names WHICH current it is — none of them '
    + 'is the bare phrase "fault level"',
    Object.values(METRIC_LABELS).every(m => m.label.toLowerCase() !== 'fault level'
        && m.label.toLowerCase() !== 'maximum fault level'));

check('generic names are refused by the vocabulary itself',
    REFUSED_GENERIC_NAMES.includes('fault_level')
    && REFUSED_GENERIC_NAMES.includes('short_circuit_level'));

/* ── A good record is accepted, frozen, and says it was not computed ─────── */

const good = record(clone());
check('a complete published record is accepted', good.ok === true && good.record !== null);
check('the accepted record is frozen — nothing downstream can quietly edit a '
    + 'published figure', good.ok && Object.isFrozen(good.record)
    && Object.isFrozen(good.record.metrics) && Object.isFrozen(good.record.provenance));
check('the accepted record states computed:false, so no consumer can mistake '
    + 'it for a study result', good.ok && good.record.computed === false);
check('the record carries the caveat text verbatim', good.ok && good.record.caveat === CAVEAT);
check('the record keeps the metric names exactly as given and attaches the unit '
    + 'and label from the vocabulary',
    good.ok && good.record.metrics.three_phase_rms_break_current_ka.unit === 'kA'
    && good.record.metrics.three_phase_rms_break_current_ka.label === 'three-phase RMS break current');

/* ── Provenance is not optional: each missing field is its own refusal ───── */

for (const key of ['publisher', 'publication', 'source_url', 'sha256', 'published_date', 'study_basis']) {
    const bad = clone(); delete bad.provenance[key];
    const r = record(bad);
    check('a record without provenance.' + key + ' is refused, and the refusal names the field',
        r.ok === false && typeof r.refused === 'string' && r.refused.includes(key));
}

{
    const bad = clone(); bad.provenance.sha256 = 'not-a-hash';
    check('a provenance hash that is not a 64-hex SHA-256 is refused',
        record(bad).ok === false);
}
{
    const bad = clone(); bad.provenance.published_date = '27/11/2025';
    check('a date that is not YYYY-MM-DD is refused — a figure with an '
        + 'ambiguous date is a figure with no date', record(bad).ok === false);
}
{
    const bad = clone(); bad.provenance.source_url = 'Appendix D';
    check('a source that is not a URL is refused — the reader must be able to '
        + 'go and read the same page', record(bad).ok === false);
}

/* ── The collapse the contract forbids ───────────────────────────────────── */

{
    const bad = clone(); bad.metrics = { fault_level: { min: 12, max: 14, unit: 'kA' } };
    const r = record(bad);
    check('a metric called "fault_level" is refused even with a unit — a '
        + 'number that does not say which current it is is not a measurement',
        r.ok === false && /generic/.test(r.refused));
}
{
    const bad = clone(); bad.metrics = { Maximum_Fault_Level: { min: 12, max: 14, unit: 'kA' } };
    check('the generic-name refusal is case-insensitive', record(bad).ok === false);
}
{
    const bad = clone(); bad.metrics = { some_new_metric: { min: 1, max: 2 } };
    check('an unknown metric with no declared unit and label is refused',
        record(bad).ok === false);
}
{
    const ok = clone(); ok.metrics = { some_new_metric: { min: 1, max: 2, unit: 'kA', label: 'a declared current' } };
    const r = record(ok);
    check('an unknown metric IS accepted when it declares its own unit and label, '
        + 'and is marked as declared rather than vocabulary',
        r.ok === true && r.record.metrics.some_new_metric.declared === true);
}
{
    const bad = clone(); bad.metrics.three_phase_rms_break_current_ka.unit = 'MVA';
    check('a vocabulary metric carrying the wrong unit is refused rather than '
        + 'silently relabelled', record(bad).ok === false);
}
{
    const bad = clone(); bad.metrics.three_phase_rms_break_current_ka = { min: 14.52, max: 12.78 };
    check('min above max is refused', record(bad).ok === false);
}
{
    const bad = clone(); bad.metrics.three_phase_rms_break_current_ka = { min: -1, max: 12 };
    check('a negative current is refused', record(bad).ok === false);
}
{
    const bad = clone(); bad.metrics = {};
    check('a record with no metrics at all is refused', record(bad).ok === false);
}
{
    const bad = clone(); delete bad.site.voltage_kv;
    check('a record that does not say which voltage level is refused',
        record(bad).ok === false);
}

/* ── quote(): the only line a card may print ─────────────────────────────── */

const line = good.ok ? quote(good.record, 'three_phase_rms_break_current_ka') : null;
check('quote() prints the metric label, the range and the unit',
    typeof line === 'string' && line.includes('three-phase RMS break current')
    && line.includes('12.78–14.52 kA'));
check('quote() prints the site, busbar and voltage the figure is for',
    typeof line === 'string' && line.includes('ABHAM ABHA1 M2 132 kV'));
check('quote() prints the publisher, publication, study basis and date',
    typeof line === 'string' && line.includes('NESO')
    && line.includes('Appendix D') && line.includes('peak demand')
    && line.includes('published 2026-06-30'));
check('quote() never prints the bare words "fault level" for a named current',
    typeof line === 'string' && !/\bfault level\b/i.test(line));
check('quote() has no default metric — asking for none returns null rather '
    + 'than a silently chosen figure',
    good.ok && quote(good.record) === null && quote(good.record, 'fault_level') === null);
check('quote() of a metric the record does not carry returns null, not a '
    + 'number from a different metric',
    good.ok && quote(good.record, 'single_phase_rms_break_current_ka') === null);

/* ── What the module must NOT be able to do ──────────────────────────────── */

/* CALLABLE exports only. The first version of this tested every export
   NAME and caught NOT_COMPUTED and NO_HEADROOM -- the two string constants
   that exist precisely to SAY these things are refused. The constraint is
   about capability a caller can reach, so it is asserted over functions. */
const callable = Object.keys(mod).filter(n => typeof mod[n] === 'function');
check('the module exports exactly two functions, record and quote -- validate '
    + 'and print, nothing else',
    callable.length === 2 && callable.includes('record') && callable.includes('quote'));
check('no callable computes, calculates, estimates or solves anything -- a '
    + 'fault current is the operator model, not this module arithmetic',
    callable.every(n => !/compute|calculat|estimat|solve|derive/i.test(n)));
check('no callable offers headroom against a rating -- matching a published '
    + 'metric to the right switchgear rating is engineering, not screening',
    callable.every(n => !/headroom|margin|capacity/i.test(n)));
check('the refusals are stated as text a card can print, not left implicit',
    typeof NOT_COMPUTED === 'string' && NOT_COMPUTED.length > 40
    && typeof NO_HEADROOM === 'string' && NO_HEADROOM.length > 40);

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

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

Rating Envelope Proof

A JavaScript module in the proofs folder of Ventus Grid Engine covering overhead lines (OHL) and transformers. It is built from the check step (`check`).

electricalventus-grid-engine / proofs/rating-envelope.proof.mjs · lines 1–156 of 156 · Not reached from any entry point (candidate for review)

What it does
Defines check. Side effects: starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (voltage levels 400kV, 132kV (all 132kV or above)): 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: overhead lines (OHL), transformers, 400kV, 132kV.
Inputs & outputs
Voltage levels named: 400kV, 132kV.
What it achieves
What a circuit is published to carry, season by season, and a structural refusal to add those numbers up. Its code works with 132 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
Network Topology (import), Rating Envelope (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/rating-envelope.proof.mjs:1-156 · blob 1fb178492d6d3d114ffb8dde2b8b0fcb5c46162f · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/* rating-envelope.proof.mjs — what a circuit is published to carry, season
 * by season, and a structural refusal to add those numbers up. Two claims
 * matter:
 *
 *   1. The per-season figure is a RANGE (lowest/highest across qualifying
 *      circuits), never a sum and never a mean.
 *   2. A placeholder value (>= IMPLAUSIBLE_MVA) is flagged and excluded
 *      from the range, without dropping the circuit itself or its other
 *      seasons.
 *
 * Uses the same COWL/DIDC/STRA/ISLE/PLCH fixture as
 * network-topology.proof.mjs and electrical-distance.proof.mjs.
 *
 * Run: node proofs/rating-envelope.proof.mjs
 */

import { ACCEPTS, index } from '../engine/network-topology.js';
import { at, schema, requires, IMPLAUSIBLE_MVA, SEASONS, NEVER_SUMMED, NOT_A_CAPACITY }
    from '../engine/rating-envelope.js';

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

const PRODUCT = {
    schema: ACCEPTS,
    sites: [
        { code: 'COWL', name: 'Cowley', transmission_owner: 'NGET', voltages_kv: [400, 132] },
        { code: 'DIDC', name: 'Didcot', transmission_owner: 'NGET', voltages_kv: [400] },
        { code: 'STRA', name: 'Strand', transmission_owner: 'NGET', voltages_kv: [400] },
        { code: 'ISLE', name: 'Isolated', transmission_owner: 'NGET', voltages_kv: [132] },
        { code: 'PLCH', name: 'Placeholder', transmission_owner: 'NGET', voltages_kv: [400] }
    ],
    nodes: [
        { node: 'COWL4', site_code: 'COWL', voltage_kv: 400, voltage_consistent_with_site: true },
        { node: 'COWL1', site_code: 'COWL', voltage_kv: 132, voltage_consistent_with_site: true },
        { node: 'DIDC4', site_code: 'DIDC', voltage_kv: 400, voltage_consistent_with_site: true },
        { node: 'STRA4', site_code: 'STRA', voltage_kv: 400, voltage_consistent_with_site: true },
        { node: 'ISLE1', site_code: 'ISLE', voltage_kv: 132, voltage_consistent_with_site: true },
        { node: 'PLCH4', site_code: 'PLCH', voltage_kv: 400, voltage_consistent_with_site: true }
    ],
    circuits: [
        { node_1: 'COWL4', node_2: 'DIDC4', circuit_type: 'OHL', transmission_owner: 'NGET',
          winter_mva: 1200, spring_mva: 1100, summer_mva: 900, autumn_mva: 1150,
          r_pct_100mva: 0.5, x_pct_100mva: 5, b_pct_100mva: 10, ohl_km: 20 },
        { node_1: 'DIDC4', node_2: 'STRA4', circuit_type: 'OHL', transmission_owner: 'NGET',
          winter_mva: 800, spring_mva: 750, summer_mva: 600, autumn_mva: 700, ohl_km: 15 },
        { node_1: 'COWL4', node_2: 'ISLE1', circuit_type: 'OHL', transmission_owner: 'NGET',
          winter_mva: 500, spring_mva: 480, summer_mva: 400, autumn_mva: 450 },
        // The implausible-value fixture: a placeholder winter figure that
        // must be flagged and excluded from the winter range, without
        // touching this circuit's spring/summer/autumn figures.
        { node_1: 'COWL4', node_2: 'PLCH4', circuit_type: 'OHL', transmission_owner: 'NGET',
          winter_mva: 9999, spring_mva: 100, summer_mva: 90, autumn_mva: 95 }
    ],
    transformers: [
        { node_1: 'COWL4', node_2: 'COWL1', rating_mva: 240, transmission_owner: 'NGET' }
    ],
    planned_changes: []
};

const idx = index(PRODUCT);

/* ── Contract gates ───────────────────────────────────────────────────── */

check('at() refuses an index that exposes no graph(), rather than throwing',
    at({}, 'COWL') === null && at(null, 'COWL') === null);

check('at() refuses an unknown site',
    at(idx, 'NOWHERE') === null);

check('the module identifies itself and the graph schema it requires, and '
    + 'SEASONS is the fixed four-season vocabulary every result is built from',
    schema === 'gridatlas.module.rating-envelope.v1'
    && requires === 'gridatlas.module.network-topology.graph.v1'
    && SEASONS.length === 4 && SEASONS.includes('winter') && SEASONS.includes('summer'));

/* ── The three circuits at Cowley, and the RANGE they produce ────────────── */

const cowl = at(idx, 'COWL');

check('only circuits are considered — the internal transformer landing at '
    + 'COWL4/COWL1 contributes no rating row, because a transformer has no '
    + 'seasonal MVA rating in this fixture',
    cowl.circuits.length === 3
    && cowl.circuits.every(c => ['DIDC4', 'ISLE1', 'PLCH4'].includes(c.to_node)));

check('spring is untouched by the winter placeholder: all three circuits '
    + 'qualify, and the range is a real lowest/highest across them — '
    + '100 (Placeholder) to 1100 (Didcot)',
    cowl.by_season.spring.circuits === 3
    && cowl.by_season.spring.lowest_circuit_mva === 100
    && cowl.by_season.spring.highest_circuit_mva === 1100
    && cowl.by_season.spring.excluded_as_implausible === 0);

check('the range is never a sum: the winter total of the two legitimate '
    + 'circuits (1200 + 500 = 1700) does not appear anywhere as '
    + 'highest_circuit_mva, and it is not the mean either (850)',
    cowl.by_season.winter.highest_circuit_mva !== 1700
    && cowl.by_season.winter.highest_circuit_mva !== 850);

/* ── The implausible-value flag ──────────────────────────────────────────── */

check('a value at or above IMPLAUSIBLE_MVA (9999) is EXCLUDED from the '
    + 'winter range — the range is 500 to 1200, the two real circuits, not '
    + '9999',
    IMPLAUSIBLE_MVA === 9999
    && cowl.by_season.winter.lowest_circuit_mva === 500
    && cowl.by_season.winter.highest_circuit_mva === 1200
    && cowl.by_season.winter.circuits === 2
    && cowl.by_season.winter.excluded_as_implausible === 1);

check('the flagged circuit is not dropped from the result set — its '
    + 'spring/summer/autumn figures are still reported, only its winter '
    + 'value is flagged',
    cowl.circuits.find(c => c.to_node === 'PLCH4').ratings_mva.spring === 100
    && cowl.circuits.find(c => c.to_node === 'PLCH4').flags.length === 1
    && cowl.circuits.find(c => c.to_node === 'PLCH4').flags[0].season === 'winter');

check('exactly one circuit across the site carries a flagged value, and '
    + 'the site-level count agrees',
    cowl.counts.with_a_flagged_value === 1);

/* ── A season with nothing qualifying reports so honestly, not as zero ──── */

const isleOnly = at(idx, 'COWL', { voltageKv: 132 });
check('restricted to the 132kV node, no circuit lands there (the only '
    + 'circuits at Cowley are on the 400kV node) — every season reports '
    + 'published: false rather than a range of nothing',
    isleOnly.circuits.length === 0
    && Object.values(isleOnly.by_season).every(s => s.published === false && s.circuits === 0));

/* ── The module never claims a total or a spare capacity ─────────────────── */

check('the module states plainly, in its own exported strings, that a '
    + 'rating is not additive and not a spare-capacity claim',
    /not additive/i.test(NEVER_SUMMED) && /not.*free|spare/i.test(NOT_A_CAPACITY));

check('a caller-visible check: no field anywhere in a returned result is '
    + 'named a site total or a summed rating — the refusal to sum is '
    + 'structural, not just documented',
    !JSON.stringify(cowl).toLowerCase().includes('total_mva')
    && !JSON.stringify(cowl).toLowerCase().includes('site_rating'));

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

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

Receiver Focus Param Proof

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

ingestventus-grid-engine / proofs/receiver-focus-param.proof.mjs · lines 1–83 of 83 · Not reached from any entry point (candidate for review)

What it does
It loads engine graph. Defines check. Uses libraries node:fs, node:path, node:url. Side effects: reads or writes files; starts processes.
Inputs & outputs
In: JSON file engine-graph.json.
What it achieves
?focus= centres the graph on one module.
Why it matters
No other file in the estate was found to import it.
Application
ventus-grid-engine · proofs · JavaScript module
Uses
node:fs, node:path, node:url
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/receiver-focus-param.proof.mjs:1-83 · blob 3f480e0720a5864ecfa168698fab2dbc20536fb3 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: unknown · users: none · canonical: unreached_review
/* receiver-focus-param.proof.mjs — ?focus= centres the graph on one module.
 *
 * Written 202609050300. The dashboards are being given menus that link INTO
 * the maths: a File menu in GridAtlas names an engine module and the reader
 * lands on that node with its dependencies already drawn. Before this, the
 * receiver read only ?graph=, so every such link would have opened the same
 * default node and the menu would have been decoration.
 *
 * What is asserted, and why each one earns its place:
 *
 *   - the parameter is read at all;
 *   - it matches on the node's OWN label, so a link is written with the same
 *     string the graph publishes and there is no second naming scheme to
 *     drift out of step with the first;
 *   - an unknown value is ignored rather than thrown, because a reader
 *     following a link to a module that has since been renamed should still
 *     get the graph, not a blank page;
 *   - every label this proof claims is linkable is actually present in
 *     genome/engine-graph.json, read from the file rather than restated here.
 *
 * Run: node proofs/receiver-focus-param.proof.mjs
 */
import { readFileSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const checks = [];
const check = (name, ok, detail = '') => checks.push({ name, ok: Boolean(ok), detail });

const page = readFileSync(path.join(ROOT, 'spider-sandbox.html'), 'utf8');

check('the receiver reads a focus parameter', /qp\.get\("focus"\)/.test(page), 'qp.get("focus")');
check(
  'it matches the node label exactly before anything else',
  /ns\.findIndex\(n=>n\.label===wantFocus\)/.test(page),
  'exact label match first'
);
check(
  'it falls back to a case-insensitive label match',
  /toLowerCase\(\)===lc/.test(page),
  'case-insensitive second pass'
);
check(
  'an unknown focus is ignored, never thrown',
  /if\(i>=0\)current=i;/.test(page),
  'current is only reassigned on a hit'
);
check(
  'focus is applied after the graph is chosen, so it indexes the right scope',
  page.indexOf('qp.get("focus")') > page.indexOf('qp.get("graph")'),
  'focus is read after graph'
);

/* The labels the menus will link to must exist in the published graph. Read
   them; do not restate them. A menu that names a module the graph has dropped
   is a broken link that no assertion about the page's own source would catch. */
const graph = JSON.parse(readFileSync(path.join(ROOT, 'genome', 'engine-graph.json'), 'utf8'));
const labels = new Set((graph.nodes || []).map(n => n.label));
check('the engine graph publishes nodes to focus on', labels.size > 0, `${labels.size} labelled nodes`);

const canonical = (graph.nodes || []).filter(n => n.type === 'canonical').map(n => n.label);
check(
  'the canonical engine modules are all labelled and linkable',
  canonical.length > 0 && canonical.every(l => typeof l === 'string' && l.length > 0),
  `${canonical.length} canonical modules: ${canonical.slice(0, 3).join(', ')}${canonical.length > 3 ? ' …' : ''}`
);
check(
  'the graph names a default focus, so a link without ?focus still lands somewhere',
  typeof graph.focus_default === 'string' || Number.isInteger(graph.focus_default),
  String(graph.focus_default)
);

let failed = 0;
for (const c of checks) {
  if (!c.ok) failed += 1;
  console.log(`${c.ok ? 'ok  ' : 'FAIL'}  ${c.name}${c.detail ? '  -- ' + c.detail : ''}`);
}
console.log(`\n${checks.length - failed}/${checks.length} checks passed`);
if (failed) {
  console.error(`${failed} FAILED`);
  process.exit(1);
}