GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Websites and apps / ventus-grid-engine / engine

Electrical Distance and 1 more file (part 1)

A JavaScript module in Ventus Grid Engine that starts nodes (`startNodes`) (units: kV, MVA), covering transformers.

502 lines of JavaScript from ventus-grid-engine, in 2 files. Topic: Websites and apps. Section 2017 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. Diversified Demand energy-data · ventus-grid-engine / engine/diversified-demand.js lines 1–187
  2. Electrical Distance geodesy · ventus-grid-engine / engine/electrical-distance.js lines 1–315

Diversified Demand

A JavaScript module in Ventus Grid Engine that averages over window GW (`averageOverWindowGw`) (units: kW, kWh), covering transformers.

energy-dataventus-grid-engine / engine/diversified-demand.js · lines 1–187 of 187 · pattern ratio (shared by 8 files)

What it does
Defines 7 functions or classes, including positive, ratio, count, diversifiedDemandKw, impliedCoincidence. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain terms in the code: transformers.
Downstream impact
Used directly by 7 files: Build Graph (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/); Diversified Demand Proof (ventus-grid-engine); Grid Engine — Diversity Page (globalgrid2050, https://globalgrid2050.com/grid_engine/202609060211-diversity/); Grid Engine — Data Centre Connection Page (globalgrid2050, https://globalgrid2050.com/grid_engine/202609060316-data-centre-connection/); and 3 more. Reached from 4 other entry points, including Homepage V090 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v090.html); Homepage V091 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v091.html); Homepage V093 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v093.html).
What it achieves
It is built from the positive step (`positive`), the ratio step (`ratio`) and the count step (`count`). What a group of loads actually draws together, which is never the sum of what each could draw alone. Its code works with 2.85 GW, 7 kW and 700 kW.
Why it matters
Loaded by the Diversity page in GlobalGrid2050 at https://globalgrid2050.com/grid_engine/202609060211-diversity/ and 4 other pages. Also imported by Build Graph and Diversified Demand Proof.
Application
ventus-grid-engine · engine · JavaScript module
VEDIC
DIVERSIFY (GG2050-VEDIC-000028): Ventus Grid Engine / diversified-demand · Electrical engineering / Applied mathematics. unit_count, per_unit_kw, coincidence_factor → diversified_demand_kw
VEDIC
COINCIDE (GG2050-VEDIC-000029): Ventus Grid Engine / diversified-demand · Electrical engineering / Applied mathematics. unit_count, per_unit_kw, measured_group_peak_kw → coincidence_factor
VEDIC
TOTAL ANNUAL ENERGY (GG2050-VEDIC-000058): Ventus Grid Engine · Energy and power calculation. unit_count, annual_energy_per_unit_kwh → annual_population_energy_twh_result
Uses
none found
Used by
named by URL in Build Graph (estate URL), imported by Diversified Demand Proof (import), linked from Grid Engine — Diversity Page (link), linked from Grid Engine — Data Centre Connection Page (link), linked from Grid Engine — EV Depot Page (link), linked from Grid Engine — Compute Against Charging Page (link), linked from Grid Engine — Every Home a Charger Page (link)
Produces
schema, diversifiedDemandKw, impliedCoincidence, averageOverWindowGw, populationEnergyTwh, NOT_COMPUTED
Defines here
positive, ratio, count, diversifiedDemandKw, impliedCoincidence, averageOverWindowGw, populationEnergyTwh
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 engine/diversified-demand.js:1-187 · blob 0c316d234984a1363d8a27ce28a8a5653784b7b6 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: production_core
/**
 * Module: diversified-demand
 *
 * APPLIED ENGINEERING. What a group of loads actually draws together, which is
 * never the sum of what each could draw alone.
 *
 * WHY DIVERSITY IS THE WHOLE PROBLEM.
 * A hundred homes with 7 kW chargers do not present 700 kW to the transformer,
 * because they do not all charge at once. The figure that sizes the plant is
 * the After Diversity Maximum Demand — the peak of the SUM, not the sum of the
 * peaks. The ratio between them is the coincidence factor, and it falls as the
 * group grows: two homes are highly correlated, ten thousand are not.
 *
 * This is the single most consequential number in distribution planning, and
 * the one most often assumed rather than measured. Assume it too low and the
 * transformer overheats; too high and a viable connection is refused, or a
 * network is built that nobody needs. This module therefore REQUIRES the
 * coincidence factor as an input and supplies no default. Where a network
 * operator publishes one for a load class, use theirs.
 *
 * WHY THE NUMBER OF UNITS MATTERS AND IS NOT A FREE PARAMETER.
 * Coincidence is not a property of the appliance, it is a property of the
 * group. A coincidence factor quoted for 1,000 homes applied to 10 homes will
 * badly under-size. So `diversifiedDemand` records the unit count alongside the
 * factor, and `impliedCoincidence` runs the calculation the honest way round:
 * where a measured group peak exists, derive the factor from it.
 *
 * THE CHARGING-WINDOW CASE, WHICH IS DIFFERENT AND OFTEN CONFLATED.
 * Energy delivered in a window sets an AVERAGE power over that window; it does
 * not set the peak. Ten million vehicles taking 25 TWh a year average 2.85 GW
 * across the year and 8.56 GW across an eight-hour nightly window — but their
 * unrestricted simultaneous draw is far higher, and the number that matters
 * depends entirely on whether the charging is managed. Both quantities are
 * offered here, separately named, because collapsing them is how a flexibility
 * assumption gets smuggled into a network study.
 *
 * WHAT THIS MODULE REFUSES.
 * No function returns a coincidence factor from first principles: there is no
 * closed form, only measurement and the operator's published figures. No
 * function decides whether a group fits — that is firm capacity, and it is a
 * different module with its own refusals.
 *
 * Schema: ventus-grid-engine.diversified-demand.v1
 */

export const schema = 'ventus-grid-engine.diversified-demand.v1';

const HOURS_PER_YEAR = 8760;

function positive(name, v) {
    if (typeof v !== 'number' || !Number.isFinite(v)) {
        throw new TypeError(`${name} must be a finite number, received ${v === null ? 'null' : typeof v}`);
    }
    if (v <= 0) throw new RangeError(`${name} must be greater than zero, received ${v}`);
    return v;
}

function ratio(name, v) {
    positive(name, v);
    if (v > 1) throw new RangeError(
        `${name} must be a fraction in (0, 1], received ${v}. A percentage such as 20 must be passed as 0.2.`);
    return v;
}

function count(name, v) {
    positive(name, v);
    if (!Number.isInteger(v)) throw new RangeError(`${name} must be a whole number, received ${v}`);
    return v;
}

/**
 * After Diversity Maximum Demand for a group of like units.
 *
 *   ADMD = n x P_unit x coincidence
 *
 * The coincidence factor is required and belongs to the group size, not to the
 * appliance — which is why the unit count travels back with the answer.
 */
export function diversifiedDemandKw({ unitCount, perUnitKw, coincidenceFactor }) {
    count('unitCount', unitCount);
    positive('perUnitKw', perUnitKw);
    ratio('coincidenceFactor', coincidenceFactor);
    const unrestricted = unitCount * perUnitKw;
    const value = unrestricted * coincidenceFactor;
    return {
        schema,
        quantity: 'after_diversity_maximum_demand_kw',
        value,
        unit: 'kW',
        from: { unitCount, perUnitKw, coincidenceFactor, unrestrictedKw: unrestricted },
        basis:
            `${unitCount.toLocaleString('en-GB')} units of ${perUnitKw} kW could draw ` +
            `${unrestricted.toLocaleString('en-GB')} kW between them if every one ran at once. At a ` +
            `coincidence factor of ${coincidenceFactor} the group presents ${value.toLocaleString('en-GB', { maximumFractionDigits: 1 })} kW — ` +
            `the peak of the sum, not the sum of the peaks. That factor belongs to a group of THIS ` +
            `size: one quoted for a thousand units will badly under-size ten. Where the network ` +
            `operator publishes a factor for this load class, use theirs.`
    };
}

/**
 * The honest direction: derive the coincidence factor from a measured group
 * peak rather than assuming one.
 */
export function impliedCoincidence({ unitCount, perUnitKw, measuredGroupPeakKw }) {
    count('unitCount', unitCount);
    positive('perUnitKw', perUnitKw);
    positive('measuredGroupPeakKw', measuredGroupPeakKw);
    const unrestricted = unitCount * perUnitKw;
    if (measuredGroupPeakKw > unrestricted) {
        throw new RangeError(
            `measuredGroupPeakKw (${measuredGroupPeakKw}) exceeds the unrestricted total ` +
            `(${unrestricted}); a group cannot draw more than all its units at full rating.`);
    }
    return {
        schema,
        quantity: 'coincidence_factor',
        value: measuredGroupPeakKw / unrestricted,
        unit: 'dimensionless',
        from: { unitCount, perUnitKw, measuredGroupPeakKw, unrestrictedKw: unrestricted },
        basis:
            `Measured, not assumed: a group peak of ${measuredGroupPeakKw} kW against an unrestricted ` +
            `${unrestricted} kW implies this coincidence factor for a group of ${unitCount}. Prefer ` +
            `this direction wherever a measurement exists.`
    };
}

/**
 * Average power over a delivery window. NOT a peak.
 *
 * Energy in a window sets an average across it. The peak inside that window
 * depends on whether the load is managed, and nothing here can tell you.
 */
export function averageOverWindowGw({ annualTwh, windowHoursPerDay }) {
    positive('annualTwh', annualTwh);
    positive('windowHoursPerDay', windowHoursPerDay);
    if (windowHoursPerDay > 24) {
        throw new RangeError(`windowHoursPerDay must be at most 24, received ${windowHoursPerDay}`);
    }
    const windowHoursPerYear = windowHoursPerDay * 365;
    return {
        schema,
        quantity: 'average_power_across_window_gw',
        value: (annualTwh * 1000) / windowHoursPerYear,
        unit: 'GW',
        from: { annualTwh, windowHoursPerDay, windowHoursPerYear, hoursPerYear: HOURS_PER_YEAR },
        basis:
            `${annualTwh} TWh delivered inside a ${windowHoursPerDay}-hour daily window averages the ` +
            `power stated across that window. This is an AVERAGE, not a peak: the peak inside the ` +
            `window depends on whether the load is managed, and this figure cannot tell you. Quoting ` +
            `it as a peak is how a flexibility assumption gets smuggled into a network study.`
    };
}

/**
 * Annual energy for a population of like units.
 *
 *   E = n x e_unit
 *
 * The paper's ten million vehicles at 2,500 kWh each.
 */
export function populationEnergyTwh({ unitCount, perUnitKwhPerYear }) {
    count('unitCount', unitCount);
    positive('perUnitKwhPerYear', perUnitKwhPerYear);
    const kwh = unitCount * perUnitKwhPerYear;
    return {
        schema,
        quantity: 'population_annual_energy_twh',
        value: kwh / 1e9,
        unit: 'TWh',
        from: { unitCount, perUnitKwhPerYear, totalKwh: kwh },
        basis:
            `${unitCount.toLocaleString('en-GB')} units at ${perUnitKwhPerYear.toLocaleString('en-GB')} kWh ` +
            `a year. Annual energy only — it says nothing about when any of it is drawn.`
    };
}

export const NOT_COMPUTED = Object.freeze({
    coincidenceFromFirstPrinciples:
        'There is no closed form for a coincidence factor. It comes from measurement of a group of that size and load class, or from the network operator\'s published figure. This module requires it as an input for that reason.',
    peakInsideAWindow:
        'Energy delivered in a window fixes the average across it, never the peak inside it. The peak depends on whether the load is managed, which is a control decision, not arithmetic.',
    whetherTheGroupFits:
        'Whether a diversified demand can be connected is a firm-capacity and security question, and the binding constraint is often upstream of the transformer entirely.',
    futureCoincidence:
        'Coincidence factors measured on today\'s appliances do not survive a change in control: smart charging, time-of-use tariffs and vehicle-to-grid all move the factor, in both directions.'
});

Electrical Distance

A JavaScript module in Ventus Grid Engine that starts nodes (`startNodes`) (units: kV, MVA), covering transformers.

geodesyventus-grid-engine / engine/electrical-distance.js · lines 1–315 of 315 · Entry point · pattern startNodes (shared by 10 files)

What it does
It lists and searches transformers. Defines 6 functions or classes, including crossing, describe, legality, startNodes, between. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain terms in the code: transformers.
Downstream impact
Used directly by 3 files: Build Graph (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/); Electrical Distance Proof (ventus-grid-engine); Ventus Grid Engine — Genome Page (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/). Reached from 1 other entry point, including Genome Workflow (ventus-grid-engine).
What it achieves
It starts nodes (`startNodes`) and is built from the crossing step (`crossing`) and the describe step (`describe`). PROMOTED from `sources/v9-extracts/electrical-distance.mjs` (itself extracted verbatim from `gridatlas/atlas/modules/202609012245-electrical-distance.js`). Its code works with 100 MVA.
Why it matters
Loaded by the Genome page at https://ventusltd.github.io/ventus-grid-engine/genome/. Also imported by Build Graph and Electrical Distance Proof.
Application
ventus-grid-engine · engine · JavaScript module
Uses
none found
Used by
named by URL in Build Graph (estate URL), imported by Electrical Distance Proof (import), named by URL in Ventus Grid Engine — Genome Page (estate URL)
Produces
NOT_A_DISTANCE, NOT_A_CAPACITY, IMPEDANCE_CARRIED, UNDECLARED, between, within, schema, requires
Defines here
crossing, describe, legality, startNodes, between, within
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 engine/electrical-distance.js:1-315 · blob 85060a0846aa07b9877ecb10d8fccf79a04d76d3 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: production_core
/**
 * Module: electrical-distance
 *
 * PROMOTED from sources/v9-extracts/electrical-distance.mjs (itself
 * extracted verbatim from gridatlas/atlas/modules/202609012245-electrical-distance.js).
 *
 * How far away a substation is, measured in the network operator's own
 * published circuits rather than in kilometres. Breadth-first shortest
 * path (in hop count, not km) over the graph produced by
 * network-topology.js's index(product).graph(). No impedance summation:
 * R, X, B are carried per-hop exactly as published and never combined.
 *
 * Depends on: a `network-topology` index exposing `.graph()` with schema
 * 'gridatlas.module.network-topology.graph.v1', and `.site(key)`.
 *
 * CHANGED FROM THE SOURCE: the IIFE and `window.__GRIDATLAS_MODULES__`
 * registration are removed. `between()` and `within()` are otherwise
 * unchanged — verified verbatim against
 * gridatlas/atlas/modules/202609012245-electrical-distance.js at HEAD
 * 64268fd06a0da54ddffbcdaaaee382e314e829f7 (see sources/provenance.json).
 */

const SCHEMA = 'gridatlas.module.electrical-distance.v1';
const REQUIRES = 'gridatlas.module.network-topology.graph.v1';

export const NOT_A_DISTANCE =
  'Hops are published circuits between two sites, not a distance. A site '
  + 'one hop away may be a hundred kilometres away, and a site ten '
  + 'kilometres away may be on no shared circuit at all.';

export const NOT_A_CAPACITY =
  'A path existing on the published network says nothing about whether '
  + 'anything can flow along it for a new project. Ratings are the '
  + 'circuit\'s, not a spare allowance, and queue position, committed '
  + 'connections, consent and commercial terms appear in no appendix.';

export const IMPEDANCE_CARRIED =
  'R, X and B are reproduced on each hop exactly as published, on a '
  + '100 MVA base. They are not added, scaled or combined anywhere in '
  + 'this module. A sum of them would be the beginning of a load flow, '
  + 'which needs a declared model this data does not contain.';

export const UNDECLARED = 'undeclared';

/* A traversal must not invent a voltage, so the two ends of an edge are
   compared only when BOTH are declared. */
function crossing(graph, nearNode, farNode) {
  const near = graph.nodeVoltageKv(nearNode);
  const far = graph.nodeVoltageKv(farNode);
  return {
    near_kv: near,
    far_kv: far,
    both_declared: near != null && far != null,
    changes: near != null && far != null && near !== far
  };
}

function describe(graph, entry, nearNode) {
  const farNode = entry.row[entry.far];
  const cross = crossing(graph, nearNode, farNode);
  return {
    kind: entry.kind,
    from_node: nearNode,
    to_node: farNode,
    from_site_code: graph.nodeSiteCode(nearNode) || null,
    to_site_code: graph.nodeSiteCode(farNode) || null,
    from_voltage_kv: cross.near_kv,
    to_voltage_kv: cross.far_kv,
    voltage_changed: cross.changes,
    voltage_ratio_kv: entry.kind === 'transformer'
      && typeof entry.row.voltage_ratio_kv === 'string'
      ? entry.row.voltage_ratio_kv : null,
    ratings_mva: graph.ratingsOf(entry.row),
    transformer_rating_mva: entry.kind === 'transformer'
      && Number.isFinite(entry.row.rating_mva) ? entry.row.rating_mva : null,
    parameters_pct_100mva: graph.parametersOf(entry.row)
  };
}

/**
 * Is this edge legal to walk? A transformer is the only thing that may
 * change voltage. A circuit that appears to change voltage is refused
 * and reported rather than traversed.
 */
function legality(kind, cross) {
  if (!cross.changes) return { legal: true, refusal: null };
  if (kind === 'transformer') return { legal: true, refusal: null };
  return {
    legal: false,
    refusal: 'a ' + kind + ' whose two ends carry different declared '
      + 'voltages (' + cross.near_kv + ' kV and ' + cross.far_kv + ' kV); '
      + 'only a transformer may change voltage, so this edge is not walked'
  };
}

function startNodes(graph, site, voltageKv) {
  const nodes = graph.nodesOfSite(site.code);
  if (voltageKv == null) return nodes;
  return nodes.filter((name) => graph.nodeVoltageKv(name) === voltageKv);
}

/**
 * The shortest published path between two sites, in circuits.
 * Breadth-first, so the first arrival is a fewest-hop path.
 *
 * @param index      a network-topology index (must expose graph())
 * @param fromKey    site code or exact site name
 * @param toKey      site code or exact site name
 * @param options    { voltageKv, maxHops }
 * @returns a result object, or null if either site is unknown
 */
export function between(index, fromKey, toKey, options) {
  if (!index || typeof index.graph !== 'function') return null;
  const graph = index.graph();
  if (!graph || graph.schema !== REQUIRES) return null;

  const from = index.site(fromKey);
  const to = index.site(toKey);
  if (!from || !to) return null;

  const opts = options || {};
  const voltageKv = Number.isFinite(opts.voltageKv) ? opts.voltageKv : null;
  const maxHops = Number.isFinite(opts.maxHops) ? opts.maxHops : 6;

  const targets = new Set(graph.nodesOfSite(to.code));
  const origins = startNodes(graph, from, voltageKv);

  const base = {
    schema: SCHEMA,
    from: { code: from.code, name: from.name },
    to: { code: to.code, name: to.name },
    requested_voltage_kv: voltageKv,
    max_hops: maxHops,
    not_a_distance: NOT_A_DISTANCE,
    not_a_capacity: NOT_A_CAPACITY,
    impedance_basis: IMPEDANCE_CARRIED
  };

  if (!origins.length) {
    return Object.assign({}, base, {
      reached: false,
      reason: voltageKv == null
        ? 'the origin site publishes no nodes in this product'
        : 'the origin site publishes no node at ' + voltageKv + ' kV',
      hops: null, path: [], refusals: [], ties: 0, explored_nodes: 0
    });
  }

  if (from.code === to.code) {
    return Object.assign({}, base, {
      reached: true, hops: 0, path: [], refusals: [], ties: 0,
      explored_nodes: origins.length,
      reason: 'the same site'
    });
  }

  const seen = new Map();
  const refusals = [];
  let frontier = [];
  for (const name of origins.slice().sort()) {
    if (targets.has(name)) {
      return Object.assign({}, base, {
        reached: true, hops: 0, path: [], refusals: [], ties: 0,
        explored_nodes: 1,
        reason: 'both site codes resolve to the same node'
      });
    }
    seen.set(name, null);
    frontier.push(name);
  }

  for (let depth = 1; depth <= maxHops; depth += 1) {
    const next = [];
    const arrivals = [];
    for (const nearNode of frontier) {
      for (const entry of graph.edgesAt(nearNode)) {
        const farNode = entry.row[entry.far];
        if (!farNode || !graph.has(farNode)) continue;
        const cross = crossing(graph, nearNode, farNode);
        const verdict = legality(entry.kind, cross);
        if (!verdict.legal) {
          refusals.push({
            at_node: nearNode, to_node: farNode,
            kind: entry.kind, reason: verdict.refusal
          });
          continue;
        }
        if (seen.has(farNode)) continue;
        seen.set(farNode, { via: entry, from: nearNode });
        if (targets.has(farNode)) arrivals.push(farNode);
        else next.push(farNode);
      }
    }

    if (arrivals.length) {
      arrivals.sort();
      const path = [];
      let cursor = arrivals[0];
      while (cursor) {
        const step = seen.get(cursor);
        if (!step) break;
        path.unshift(describe(graph, step.via, step.from));
        cursor = step.from;
      }
      return Object.assign({}, base, {
        reached: true,
        hops: path.length,
        path,
        transformers_crossed: path.filter((h) => h.kind === 'transformer').length,
        voltage_changes: path.filter((h) => h.voltage_changed).length,
        ties: arrivals.length - 1,
        refusals,
        explored_nodes: seen.size,
        arrival_node: arrivals[0]
      });
    }

    if (!next.length) break;
    frontier = next.sort();
  }

  return Object.assign({}, base, {
    reached: false,
    reason: 'no published path within ' + maxHops + ' hops'
      + (voltageKv == null ? '' : ' from a ' + voltageKv + ' kV node')
      + '; this is a statement about the published network, not about '
      + 'whether the two sites are connected in reality',
    hops: null, path: [], refusals, ties: 0, explored_nodes: seen.size
  });
}

/**
 * Every site reachable within N hops, with the hop count at which it was
 * first reached.
 *
 * @param index    a network-topology index
 * @param key      site code or exact site name
 * @param options  { hops, voltageKv }
 */
export function within(index, key, options) {
  if (!index || typeof index.graph !== 'function') return null;
  const graph = index.graph();
  if (!graph || graph.schema !== REQUIRES) return null;

  const site = index.site(key);
  if (!site) return null;

  const opts = options || {};
  const voltageKv = Number.isFinite(opts.voltageKv) ? opts.voltageKv : null;
  const limit = Number.isFinite(opts.hops) ? opts.hops : 2;

  const origins = startNodes(graph, site, voltageKv);
  const seen = new Set(origins);
  const bySite = new Map();
  const refusals = [];
  let frontier = origins.slice().sort();

  for (let depth = 1; depth <= limit; depth += 1) {
    const next = [];
    for (const nearNode of frontier) {
      for (const entry of graph.edgesAt(nearNode)) {
        const farNode = entry.row[entry.far];
        if (!farNode || !graph.has(farNode) || seen.has(farNode)) continue;
        const cross = crossing(graph, nearNode, farNode);
        const verdict = legality(entry.kind, cross);
        if (!verdict.legal) {
          refusals.push({ at_node: nearNode, to_node: farNode,
            kind: entry.kind, reason: verdict.refusal });
          continue;
        }
        seen.add(farNode);
        next.push(farNode);
        const code = graph.nodeSiteCode(farNode);
        if (!code || String(code).toUpperCase() === String(site.code).toUpperCase()) continue;
        if (bySite.has(code)) continue;
        const far = graph.siteByCode(code);
        bySite.set(code, {
          code,
          name: far ? far.name : null,
          hops: depth,
          first_node: farNode,
          voltage_kv: cross.far_kv,
          via: entry.kind
        });
      }
    }
    if (!next.length) break;
    frontier = next.sort();
  }

  const sites = [...bySite.values()].sort((a, b) =>
    a.hops - b.hops || String(a.code).localeCompare(String(b.code)));

  return {
    schema: SCHEMA,
    site: { code: site.code, name: site.name },
    requested_voltage_kv: voltageKv,
    hop_limit: limit,
    origin_nodes: origins.length,
    sites,
    counts: {
      sites: sites.length,
      by_hop: sites.reduce((acc, s) => {
        acc[s.hops] = (acc[s.hops] || 0) + 1;
        return acc;
      }, {})
    },
    refusals,
    not_a_distance: NOT_A_DISTANCE,
    not_a_capacity: NOT_A_CAPACITY
  };
}

export const schema = SCHEMA;
export const requires = REQUIRES;