GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Websites and apps / grid-distance-maths / src

Verify Derived and 4 more files

A JavaScript module in the rig kit folder of Gridmachine1 that fetches vnd apache.

476 lines of JavaScript and Python from grid-distance-maths, gridmachine1, in 5 files. Topic: Websites and apps. Section 1996 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. Placement transform · grid-distance-maths / src/placement.py lines 1–108
  2. CD Trace ingest · gridmachine1 / 202609071322-linux-handover/probes/cd-trace.mjs lines 1–70
  3. Range storage · gridmachine1 / 202609071322-linux-handover/rig-kit/range.mjs lines 1–82
  4. Validity ingest · gridmachine1 / 202609071322-linux-handover/rig-kit/validity.mjs lines 1–88
  5. Verify Derived render · gridmachine1 / 202609071322-linux-handover/rig-kit/verify-derived.mjs lines 1–128

Placement

A Python module in Grid Distance Maths that works with hilbert order (`hilbert_order`). It is built from the golden step (`golden`), the hilbert step (`hilbert`) and the lattice step (`lattice`).

transformgrid-distance-maths / src/placement.py · lines 1–108 of 108 · Not reached from any entry point (candidate for review) · pattern golden (shared by 2 files)

What it does
It calculates its inputs. Defines golden, hilbert_order, hilbert, lattice, morph. Uses libraries math.
What it achieves
Where a thing goes on a plane, and what "near" means there.
Why it matters
No other file in the estate was found to import it.
Application
grid-distance-maths · src · Python module
Uses
math
Used by
none found
Produces
golden, hilbert_order, hilbert, lattice, morph
Defines here
golden, hilbert_order, hilbert, lattice, morph
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
grid-distance-maths@8e91b07d8312acca5bcaef43e839f06a3b1d642a src/placement.py:1-108 · blob fc91899073b3bf6cc44839e93840fb12f5233116 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unreached_review
"""Placement: where a thing goes on a plane, and what "near" means there.

The companion to geodesy.py. Geodesy answers where something IS; placement
answers where to PUT it when you are drawing a space that has no map.

Three arrangements, because three different questions need three different
meanings of "near". Choosing an arrangement is choosing what adjacency means,
and getting that wrong makes a boundary invisible.

  golden(key)   an archive. Adjacency is ORDER. r = spacing*sqrt(key),
                theta = key*GOLDEN. Area grows linearly with count, so density
                is constant forever; the golden angle never aligns, so no rows,
                spokes or gaps appear however many are added; and place j never
                moves when place j+1 arrives. This is the Kuiper arrangement.

  hilbert(d)    a swept space. Adjacency is ONE PARAMETER DIFFERING BY ONE
                STEP. Consecutive indices land adjacent at every zoom, so a
                boundary between two verdicts appears as a coherent edge
                rather than scattered dust. The golden spiral deliberately
                destroys this locality, which is exactly why it is wrong here.

  lattice(i)    the raw mixed-radix decode: index -> one value per axis. The
                thing both of the above are arranging.

And morph(), because an arrangement is not a still: the same points moved from
one arrangement to another is how one becomes legible as the descendant of the
other.

Held to placement.mjs by test/verify_placement.mjs. Neither is authoritative;
they must agree.
"""
import math

__all__ = ["GOLDEN", "golden", "hilbert", "lattice", "morph", "hilbert_order"]

# the golden angle, pi*(3-sqrt(5)) = 2.39996... rad. The most irrational angle
# there is, which is the whole point: a rational one eventually makes spokes.
GOLDEN = math.pi * (3.0 - math.sqrt(5.0))


def golden(key, spacing=1.0):
    """Archive placement. Point `key` of an unbounded, append-only sequence."""
    if key < 0:
        raise ValueError("key must be >= 0")
    r = spacing * math.sqrt(key)
    t = key * GOLDEN
    return (r * math.cos(t), r * math.sin(t))


def hilbert_order(n):
    """The smallest order whose curve holds n points: side 2**order."""
    if n <= 0:
        raise ValueError("n must be > 0")
    order = 0
    while (1 << order) * (1 << order) < n:
        order += 1
    return order


def hilbert(d, order):
    """Locality-preserving placement. Distance `d` along a Hilbert curve of
    side 2**order, as integer (x, y). Consecutive d are always adjacent."""
    side = 1 << order
    if d < 0 or d >= side * side:
        raise ValueError("d out of range for order %d" % order)
    x = y = 0
    t = d
    s = 1
    while s < side:
        rx = 1 if (t // 2) % 2 else 0
        ry = 1 if (t ^ rx) % 2 else 0
        # rotate the quadrant so the curve stays continuous
        if ry == 0:
            if rx == 1:
                x, y = s - 1 - x, s - 1 - y
            x, y = y, x
        x += s * rx
        y += s * ry
        t //= 4
        s <<= 1
    return (x, y)


def lattice(index, radices):
    """Mixed-radix decode: a linear index to one value per axis, least
    significant axis first. The space every arrangement is arranging."""
    if index < 0:
        raise ValueError("index must be >= 0")
    out, r = [], index
    for radix in radices:
        if radix < 1:
            raise ValueError("every radix must be >= 1")
        out.append(r % radix)
        r //= radix
    return out


def morph(a, b, t, ease=True):
    """One point on its way from arrangement a to arrangement b.

    An arrangement is not a still. Moving the SAME points from one to another
    is what shows that one descends from the other: nothing is created or
    destroyed, only rearranged.
    """
    if not 0.0 <= t <= 1.0:
        raise ValueError("t must be in [0, 1]")
    k = t * t * (3.0 - 2.0 * t) if ease else t      # smoothstep
    return (a[0] + (b[0] - a[0]) * k, a[1] + (b[1] - a[1]) * k)

CD Trace

A JavaScript module in the probes folder of Gridmachine1 that fetches composition, interconnectors, interconnector endpoints and homepage catalogue, using SHA-256 from the GridAtlas and ventus-grid-engine repositories.

ingestgridmachine1 / 202609071322-linux-handover/probes/cd-trace.mjs · lines 1–70 of 70 · version 2026-09-07 13:22 · Not reached from any entry point (candidate for review)

What it does
It fetches composition, interconnectors, interconnector endpoints and homepage catalogue. Defines sha, blob, head, n. Uses libraries node:child_process, node:crypto. Side effects: makes network requests; starts processes.
Why it exists in the grid workflow
Domain terms in the code: interconnectors.
Inputs & outputs
In: data source: gridatlas data; data source: ventus-grid-engine data; JSON file current.json; JSON file 202609071232-composition.json; GeoJSON file interconnectors.geojson; JSON file interconnector-endpoints.json; JSON file interconnectors.config.json; JSON file interconnectors.json.
What it achieves
It is built from the sha step (`sha`), the blob step (`blob`) and the head step (`head`). For each artefact a commit produced, is the live origin serving exactly the bytes git holds?
Why it matters
No other file in the estate was found to import it.
Application
gridmachine1 · 202609071322-linux-handover/probes · JavaScript module
Uses
GridAtlas — Index Page (estate URL), node:child_process, node:crypto
Used by
none found
Produces
sha, blob, head, n
Defines here
sha, blob, head, n
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridmachine1@16cd3db49d03e6faa0e4e24f06f08184422049be 202609071322-linux-handover/probes/cd-trace.mjs:1-70 · blob 6303de534aaccdbce5ce5bc08f4a8a5f113c5c76 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: network, process · domain stage: unknown · users: none · canonical: unreached_review
// CD trace: for each artefact a commit produced, is the live origin serving
// exactly the bytes git holds? MATCH means CD has completed for that file;
// STALE means the push landed but Pages has not (or a different composition
// is being served); 404 means the path never deployed. Hashes are of the LF
// git blob, which is what Pages serves - a working-copy hash on Windows is
// CRLF and would report false STALE for every text file.
import { execFileSync } from "node:child_process";
import { createHash } from "node:crypto";

const sha = (b) => createHash("sha256").update(b).digest("hex");
const blob = (repo, rev, path) => execFileSync("git", ["-C", repo, "cat-file", "blob", `${rev}:${path}`], { maxBuffer: 64 << 20 });
const head = (repo) => execFileSync("git", ["-C", repo, "rev-parse", "--short", "HEAD"], { encoding: "utf8" }).trim();

const REPOS = {
  gridatlas: { dir: "C:/Users/vikra/gapub", origin: "https://ventusltd.github.io/gridatlas/" },
  globalgrid2050: { dir: "C:/Users/vikra/OneDrive/Documents/GitHub/globalgrid2050", origin: "https://globalgrid2050.com/" },
  engine: { dir: "C:/Users/vikra/OneDrive/Documents/GitHub/ventus-grid-engine", origin: "https://ventusltd.github.io/ventus-grid-engine/" },
};

// what each repo's CD is, as read from its workflows and Pages settings
const CD = {
  gridatlas: "Pages serves main directly; no deploy workflow. Push == deploy, subject to Pages build latency. verify-live.yml and the overnight builders can request a Pages build via the API.",
  globalgrid2050: "deploy-pages.yml on push to main with path filters (uk_renewables_pipeline/**, catalogue/**, index.html, testcode/**, ...). A release outside those paths does not deploy.",
  engine: "Pages serves main directly; verify.yml runs the proofs on push; genome.yml regenerates the graph and commits it back; deeplink-receiver-audit.yml audits the canonical receiver daily at 04:17 UTC.",
};

const ARTEFACTS = [
  ["gridatlas", "atlas/v/202609071232/current.json"],
  ["gridatlas", "atlas/cartridges/202609071232-sld-sandbox-v9-8.js"],
  ["gridatlas", "atlas/manifests/202609071232-composition.json"],
  ["gridatlas", "atlas/cartridges/202609071213-place-global-search-v9-5.js"],
  ["gridatlas", "atlas/data/interconnectors.geojson"],
  ["gridatlas", "atlas/data/interconnector-endpoints.json"],
  ["gridatlas", "atlas/interconnectors.config.json"],
  ["gridatlas", "atlas/current.json"],
  ["globalgrid2050", "uk_renewables_pipeline/202609071221/index.html"],
  ["globalgrid2050", "uk_renewables_pipeline/202609071221/data/v9.8/interconnectors.json"],
  ["globalgrid2050", "uk_renewables_pipeline/202609071221/data/v9.8/interconnectors_manifest.json"],
  ["globalgrid2050", "uk_renewables_pipeline/202609071221/scripts/core/atlas-interconnector-link-v9-8.js"],
  ["globalgrid2050", "catalogue/homepage-catalogue.json"],
  ["engine", "deeplink/receivers.json"],
  ["engine", "index.html"],
  ["engine", "genome/engine-graph.json"],
];

const rows = [];
for (const [repo, path] of ARTEFACTS) {
  const { dir, origin } = REPOS[repo];
  let gitHash = null;
  try { gitHash = sha(blob(dir, "HEAD", path)); } catch { gitHash = "not-in-HEAD"; }
  const url = origin + path;
  let status = 0, liveHash = null;
  try {
    const r = await fetch(url, { cache: "no-store", signal: AbortSignal.timeout(20000) });
    status = r.status;
    if (r.ok) liveHash = sha(Buffer.from(await r.arrayBuffer()));
  } catch (e) { status = "ERR " + String(e.message).slice(0, 30); }
  const verdict = status !== 200 ? String(status) : liveHash === gitHash ? "MATCH" : "STALE";
  rows.push({ repo, head: head(dir), path, verdict, git: gitHash.slice(0, 12), live: liveHash ? liveHash.slice(0, 12) : "-" });
}

console.log("CD TRACE  " + new Date().toISOString());
for (const [k, v] of Object.entries(CD)) console.log(`  ${k}: ${v}`);
console.log("");
console.log("  repo            HEAD     verdict  git-blob      live          path");
for (const r of rows) console.log(`  ${r.repo.padEnd(15)} ${r.head.padEnd(8)} ${r.verdict.padEnd(8)} ${r.git.padEnd(13)} ${r.live.padEnd(13)} ${r.path}`);
const n = (v) => rows.filter((r) => r.verdict === v).length;
console.log(`\n  MATCH ${n("MATCH")} · STALE ${n("STALE")} · 404 ${n("404")} · other ${rows.length - n("MATCH") - n("STALE") - n("404")}`);
const rootGen = JSON.parse(blob(REPOS.gridatlas.dir, "HEAD", "atlas/current.json").toString()).generation;
console.log(`  gridatlas root current.json generation in git: ${rootGen}  (root promotion is the owner's call)`);

Range

A JavaScript module in the rig kit folder of Gridmachine1 that reads vnd apache. It serves options (`serveOptions`) and is built from the mime for helper (`mimeFor`).

storagegridmachine1 / 202609071322-linux-handover/rig-kit/range.mjs · lines 1–82 of 82 · version 2026-09-07 13:22 · Not reached from any entry point (candidate for review)

What it does
It loads vnd apache. Defines serveWithRange, mimeFor, serveOptions. Uses libraries node:fs. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
Inputs & outputs
In: Parquet file vnd.apache.parquet; DuckDB queries.
Downstream impact
Used directly by 2 files: Verify Interconnector Arrival (gridmachine1); Verify Derived (gridmachine1).
What it achieves
Serve `target` honouring a Range header if present.
Why it matters
Imported by Verify Interconnector Arrival and Verify Derived.
Application
gridmachine1 · 202609071322-linux-handover/rig-kit · JavaScript module
Uses
node:fs
Used by
imported by Verify Interconnector Arrival (import), imported by Verify Derived (import)
Produces
serveWithRange, mimeFor, serveOptions
Defines here
serveWithRange, mimeFor, serveOptions
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridmachine1@16cd3db49d03e6faa0e4e24f06f08184422049be 202609071322-linux-handover/rig-kit/range.mjs:1-82 · blob de531a0ab10574d2f34c7d6d992fc082860223ee · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, storage · domain stage: unknown · users: none · canonical: unreached_review
// HTTP Range support for the mirror server.
//
// DuckDB-WASM reads a parquet file with `Range: bytes=start-end` requests, one
// per column chunk. A server that ignores the header and returns 200 with the
// whole 1.45 MB file either makes DuckDB throw an IO error or re-downloads the
// entire file for every chunk. Either way the identity path never completes,
// and the control case fails for a reason that has nothing to do with the
// cartridge under test. This is the missing piece that made the rig unable to
// run the identity path at all.
import fs from 'node:fs';

/* Serve `target` honouring a Range header if present. Returns true when it
   handled the response. Only single ranges are supported, which is all DuckDB
   sends. */
export function serveWithRange(req, res, target, contentType) {
  const size = fs.statSync(target).size;
  const range = req.headers.range;
  const base = {
    'Content-Type': contentType,
    'Accept-Ranges': 'bytes',
    'Cache-Control': 'no-store',
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Expose-Headers': 'Content-Range, Content-Length, Accept-Ranges',
  };

  if (!range) {
    res.writeHead(200, { ...base, 'Content-Length': size });
    fs.createReadStream(target).pipe(res);
    return true;
  }

  const m = /^bytes=(\d*)-(\d*)$/.exec(String(range).trim());
  if (!m) {
    res.writeHead(416, { ...base, 'Content-Range': `bytes */${size}` }).end();
    return true;
  }
  let start = m[1] === '' ? null : Number(m[1]);
  let end = m[2] === '' ? null : Number(m[2]);
  if (start === null && end === null) {
    res.writeHead(416, { ...base, 'Content-Range': `bytes */${size}` }).end();
    return true;
  }
  // suffix range: bytes=-N means the last N bytes
  if (start === null) { start = Math.max(0, size - end); end = size - 1; }
  if (end === null || end >= size) end = size - 1;
  if (start > end || start >= size) {
    res.writeHead(416, { ...base, 'Content-Range': `bytes */${size}` }).end();
    return true;
  }
  res.writeHead(206, {
    ...base,
    'Content-Range': `bytes ${start}-${end}/${size}`,
    'Content-Length': end - start + 1,
  });
  fs.createReadStream(target, { start, end }).pipe(res);
  return true;
}

export function mimeFor(file) {
  // jsdelivr's `+esm` bundles carry no extension. Served as octet-stream,
  // Chromium refuses them as module scripts and the identity path dies at the
  // DuckDB import - which is what the control case was reporting.
  if (file.endsWith('+esm') || /[\/]npm[\/].*[\/][^.\/]+$/.test(file)) return 'text/javascript; charset=utf-8';
  if (file.endsWith('.parquet')) return 'application/vnd.apache.parquet';
  if (file.endsWith('.wasm')) return 'application/wasm';
  if (file.endsWith('.js') || file.endsWith('.mjs')) return 'text/javascript; charset=utf-8';
  if (file.endsWith('.json') || file.endsWith('.geojson')) return 'application/json; charset=utf-8';
  if (file.endsWith('.html')) return 'text/html; charset=utf-8';
  if (file.endsWith('.css')) return 'text/css; charset=utf-8';
  if (file.endsWith('.png')) return 'image/png';
  return 'application/octet-stream';
}

/* Preflight for CORS on range requests from a worker. */
export function serveOptions(res) {
  res.writeHead(204, {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'GET, HEAD, OPTIONS',
    'Access-Control-Allow-Headers': 'Range, Content-Type',
    'Access-Control-Max-Age': '86400',
  }).end();
}

Validity

A JavaScript module in the rig kit folder of Gridmachine1 that classifies run (`classifyRun`), using SHA-256.

ingestgridmachine1 / 202609071322-linux-handover/rig-kit/validity.mjs · lines 1–88 of 88 · version 2026-09-07 13:22 · Not reached from any entry point (candidate for review) · pattern preflight (shared by 2 files)

What it does
It loads data. Defines preflight, classifyRun, steer. Uses libraries node:fs, node:path. Side effects: reads or writes files.
Inputs & outputs
In: JSON file current.json.
What it achieves
It classifies run (`classifyRun`) and is built from the preflight step (`preflight`) and the steer step (`steer`). Pre-flight: everything a version needs, checked for presence before a browser is launched.
Why it matters
No other file in the estate was found to import it.
Application
gridmachine1 · 202609071322-linux-handover/rig-kit · JavaScript module
Uses
node:fs, node:path
Used by
none found
Produces
preflight, classifyRun, steer
Defines here
preflight, classifyRun, steer
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridmachine1@16cd3db49d03e6faa0e4e24f06f08184422049be 202609071322-linux-handover/rig-kit/validity.mjs:1-88 · blob e39ebc8a8e3b78b7081cc59e01669c18188c663a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: unknown · users: none · canonical: unreached_review
// Harness validity: the runner's ability to tell whether it can be believed.
//
// Three times in one night a harness reported failures that were its own:
// candidates refused on a SHA-256 mismatch, a mirror missing MapLibre, a mirror
// missing the register payload. Each time the tell was the same, and each time
// it was noticed by a person: a case that is KNOWN to work also failed.
//
// So the rule is encoded. Every run carries a control. If the control fails,
// the run is HARNESS_INVALID and nothing it says about the product is counted.
// A run that cannot pass its own control has no standing to fail a candidate.
import fs from 'node:fs';
import path from 'node:path';

/* Pre-flight: everything a version needs, checked for presence before a browser
   is launched. A missing cartridge found here is a fact stated in one line; the
   same fact found mid-run costs a full pass and arrives disguised as a product
   failure. Reads current.json and resolves each cartridge path the way the
   loader will. */
export function preflight(mirrorRoot, versionDir) {
  const problems = [];
  const currentPath = path.join(mirrorRoot, versionDir, 'current.json');
  if (!fs.existsSync(currentPath)) return { ok: false, problems: [`no current.json at ${versionDir}`] };
  const current = JSON.parse(fs.readFileSync(currentPath, 'utf8'));
  for (const c of current.cartridges || []) {
    const abs = path.resolve(path.join(mirrorRoot, versionDir), c.path);
    if (!fs.existsSync(abs)) { problems.push(`cartridge missing from mirror: ${c.id} -> ${c.path}`); continue; }
    const bytes = fs.statSync(abs).size;
    if (c.bytes && bytes !== c.bytes) problems.push(`cartridge size differs: ${c.id} mirror=${bytes} manifest=${c.bytes}`);
  }
  // the shell the version boots from
  const shellIndex = path.join(mirrorRoot, versionDir, 'index.html');
  if (!fs.existsSync(shellIndex)) problems.push('version index.html missing');
  return { ok: problems.length === 0, problems, cartridges: (current.cartridges || []).length };
}

/* The control decision. `controlResult` is the outcome of driving a case that
   is known to work on the published version. If it did not pass here, the
   harness - mirror, translator, timing, hashing - is what failed. */
export function classifyRun(controlResult, results) {
  if (!controlResult) {
    return { validity: 'NO_CONTROL', reason: 'run carried no control case; its failures cannot be attributed', results };
  }
  if (!controlResult.pass) {
    return {
      validity: 'HARNESS_INVALID',
      reason: `control "${controlResult.name}" failed: ${controlResult.error || controlResult.signature || 'no detail'}. `
        + 'A harness that cannot pass a known-good case has no standing to fail a candidate. '
        + 'Nothing below is counted against any candidate.',
      results: results.map((r) => ({ ...r, counted: false, why_not_counted: 'harness invalid' })),
    };
  }
  return { validity: 'VALID', reason: `control "${controlResult.name}" passed`, results: results.map((r) => ({ ...r, counted: true })) };
}

/* What the next run should do differently, derived from this run's validity
   rather than from a person reading the log. This is the part that compounds. */
export function steer(classification, preflightResult) {
  const steps = [];
  if (!preflightResult.ok) {
    steps.push('Complete the mirror before running: ' + preflightResult.problems.join('; '));
    steps.push('Do not launch a browser until preflight is clean; a run against an incomplete mirror produces failures that are not the product\'s.');
    return { action: 'FIX_MIRROR', steps };
  }
  switch (classification.validity) {
    case 'HARNESS_INVALID':
      steps.push('The control failed, so vary the HARNESS not the candidates: mirror completeness, translator, cartridge re-signing, readiness signals.');
      steps.push('Re-run the control alone until it passes; only then re-admit candidates.');
      return { action: 'FIX_HARNESS', steps };
    case 'NO_CONTROL':
      steps.push('Add a control case before drawing any conclusion from this run.');
      return { action: 'ADD_CONTROL', steps };
    default: {
      const counted = classification.results.filter((r) => r.counted);
      const failed = counted.filter((r) => !r.pass);
      const sigs = new Set(failed.map((r) => r.signature || r.error || 'unsigned'));
      if (failed.length === counted.length && counted.length > 1 && sigs.size === 1) {
        steps.push('Every candidate failed with one signature, and the control passed - the fault is upstream of every edit but downstream of the harness. Instrument the path rather than varying the change.');
        return { action: 'INSTRUMENT', steps };
      }
      if (failed.length === 0) {
        steps.push('All candidates passed. The next useful run removes changes one at a time to find the smallest set that still passes.');
        return { action: 'MINIMISE', steps };
      }
      steps.push('Some passed, some failed, control valid: the difference between the nearest pass and the nearest fail is the smallest known statement of the fix.');
      return { action: 'DIFF_NEAREST_PAIR', steps };
    }
  }
}

Verify Derived

A JavaScript module in the rig kit folder of Gridmachine1 that fetches vnd apache.

rendergridmachine1 / 202609071322-linux-handover/rig-kit/verify-derived.mjs · lines 1–128 of 128 · version 2026-09-07 13:22 · Not reached from any entry point (candidate for review)

What it does
It fetches vnd apache. Uses libraries node:fs, node:path, node:http, file:///C:/Users/vikra/LocalCI/PipelineNews-GridAtlas/v004/node_modules/playwright/index.mjs. Side effects: changes the web page (DOM); reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
Inputs & outputs
In: data source: 127.0.0.1:${PORT}; Parquet file vnd.apache.parquet; DuckDB queries; command-line arguments.
What it achieves
Does v9.144 rescue the refs that were showing a failure card?
Why it matters
No other file in the estate was found to import it.
Application
gridmachine1 · 202609071322-linux-handover/rig-kit · JavaScript module
Uses
Range (import), node:fs, node:path, node:http, file:///C:/Users/vikra/LocalCI/PipelineNews-GridAtlas/v004/node_modules/playwright/index.mjs
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridmachine1@16cd3db49d03e6faa0e4e24f06f08184422049be 202609071322-linux-handover/rig-kit/verify-derived.mjs:1-128 · blob b9067f4dbd3d1cb0051ffb46c3cfe5ca75f62229 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: unknown · users: none · canonical: unreached_review
// Does v9.144 rescue the refs that were showing a failure card?
//
// Driven offline against the mirror, with the network cut, so the answer is
// about the cartridge and not about what happened to be reachable. Three cases:
// a ref the register cannot locate but the Crown Estate can, one it cannot
// locate and neither can, and one that always worked - the control that proves
// the change did not alter the normal path.
import fs from 'node:fs';
import path from 'node:path';
import http from 'node:http';
import { serveWithRange, serveOptions, mimeFor } from './range.mjs';
import { chromium } from 'file:///C:/Users/vikra/LocalCI/PipelineNews-GridAtlas/v004/node_modules/playwright/index.mjs';

const MIRROR = 'D:/gridatlas-ci/offline-sandbox/deps';
const PORT = 8907;
const VERSION = process.argv[2] || '202609071021';
const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8',
  '.json': 'application/json; charset=utf-8', '.geojson': 'application/json; charset=utf-8',
  '.css': 'text/css; charset=utf-8', '.png': 'image/png', '.wasm': 'application/wasm', '.parquet': 'application/vnd.apache.parquet' };

const installed = [];
const rangeLog = [];
const missed = [];
const server = http.createServer((req, res) => {
  const url = decodeURIComponent(req.url.split('?')[0]);
  let target = path.join(MIRROR, url.replace(/^\/+/, ''));
  if (fs.existsSync(target) && fs.statSync(target).isDirectory()) target = path.join(target, 'index.html');
  if (!fs.existsSync(target)) {
    // RECORD=1 installs a missing dependency once, into the same shape the URL
    // already has, so the next run is pure offline replay. The register payload
    // the identity path needs was never mirrored, which is why the control
    // failed too - a fact about the mirror, not about the cartridge.
    const seg = url.replace(/^\/+/, '').split('/');
    if (process.env.RECORD === '1' && /\./.test(seg[0])) {
      const remote = 'https://' + seg[0] + '/' + seg.slice(1).join('/');
      fetch(remote).then(async (r) => {
        if (!r.ok) throw new Error('HTTP ' + r.status);
        const buf = Buffer.from(await r.arrayBuffer());
        fs.mkdirSync(path.dirname(target), { recursive: true });
        fs.writeFileSync(target, buf);
        installed.push(remote.slice(0, 96) + '  ' + buf.length + 'B');
        res.writeHead(200, { 'Content-Type': TYPES[path.extname(target)] || 'application/octet-stream' }).end(buf);
      }).catch(() => { missed.push(remote.slice(0, 96)); res.writeHead(404).end('x'); });
      return;
    }
    missed.push(url);
    res.writeHead(404).end('not in mirror');
    return;
  }
  if (req.method === 'OPTIONS') return serveOptions(res);
  rangeLog.push(req.method + ' ' + (req.headers.range || '-') + ' ' + path.basename(target));
  serveWithRange(req, res, target, TYPES[path.extname(target)] || mimeFor(target));
}).listen(PORT);

const CASES = [
  { ref: '13429', name: 'Ossian', tech: 'wind_offshore', expect: 'derived point exists (Crown Estate lease)' },
  { ref: '13432', name: 'unknown offshore', tech: 'wind_offshore', expect: 'no derived point; should degrade, not throw' },
  { ref: '11386', name: 'Harbour Farm', tech: 'solar', expect: 'control: register locates it, path unchanged' },
];

const browser = await chromium.launch();
const rows = [];
for (const c of CASES) {
  const ctx = await browser.newContext({ viewport: { width: 1400, height: 900 }, serviceWorkers: 'allow' });
  await ctx.route('**/*', async (route) => {
    const u = new URL(route.request().url());
    if (u.hostname === '127.0.0.1') return route.continue();
    try {
      // Forward the method and the Range header, and return the mirror's real
      // status with the range headers intact. Before this every request was
      // fulfilled as a 200 with the whole body, so DuckDB's chunk reads were
      // flattened and the identity path could not run at all.
      const hdr = route.request().headers();
      const fwd = {};
      if (hdr.range) fwd.Range = hdr.range;
      const m = await fetch(`http://127.0.0.1:${PORT}/${u.hostname}${u.pathname}${u.search}`, { method: route.request().method(), headers: fwd });
      if (!m.ok) return route.abort();
      const headers = { 'content-type': m.headers.get('content-type') || 'application/octet-stream',
                        'access-control-allow-origin': '*',
                        'access-control-expose-headers': 'Content-Range, Content-Length, Accept-Ranges',
                        'accept-ranges': 'bytes' };
      for (const h of ['content-range', 'content-length']) { const v = m.headers.get(h); if (v) headers[h] = v; }
      const body = route.request().method() === 'HEAD' ? Buffer.alloc(0) : Buffer.from(await m.arrayBuffer());
      return route.fulfill({ status: m.status, headers, body });
    } catch { return route.abort(); }
  });
  const page = await ctx.newPage();
  const out = { ref: c.ref, expect: c.expect };
  try {
    // No latitude or longitude: exactly the shape of a dead MAP link.
    await page.goto(`http://127.0.0.1:${PORT}/ventusltd.github.io/gridatlas/atlas/v/${VERSION}/`
      + `?repd_ref=${c.ref}&technology=${c.tech}&project=${encodeURIComponent(c.name)}`,
      { waitUntil: 'domcontentloaded', timeout: 45000 });
    await page.waitForFunction(() => window.__GRIDATLAS_PLACE_SEARCH__, null, { timeout: 45000 }).catch(() => {});
    await page.waitForTimeout(9000);
    Object.assign(out, await page.evaluate(() => {
      const d = window.__GRIDATLAS_PLACE_SEARCH__ && window.__GRIDATLAS_PLACE_SEARCH__.deep_link;
      return {
        status: d ? d.status : null, name: d ? d.name : null,
        mapped: d ? d.mapped : null,
        derived: d ? d.coordinate_derived : null,
        source: d ? d.coordinate_source : null,
        lease: d ? d.coordinate_lease : null,
        lon: d ? d.longitude : null,
        lat: d ? d.latitude : null,
        failCard: /did not fly to a safe map point|identity check failed/i.test(document.body.innerText || ''),
      };
    }));
  } catch (e) { out.error = String(e).slice(0, 90); }
  rows.push(out);
  await ctx.close();
}
await browser.close();
server.close();

const ranged = rangeLog.filter((l) => !l.includes(' - '));
console.log('  range requests served: ' + ranged.length + (ranged.length ? '  e.g. ' + ranged.slice(0, 3).join(' | ') : ''));
if (installed.length) { console.log('  installed into the mirror: ' + new Set(installed).size); }
if (missed.length) { console.log('  still missing: ' + [...new Set(missed)].slice(0,4).join(' | ').slice(0,200)); }
console.log(`  version ${VERSION}, offline, no coordinates in any link`);
console.log('  ref     status                    mapped derived  source                          failCard');
for (const r of rows) {
  console.log('  ' + String(r.ref).padEnd(8) + String(r.status).padEnd(26)
    + String(r.mapped).padEnd(7) + String(r.derived).padEnd(9)
    + String(r.source).slice(0, 30).padEnd(32) + String(r.failCard));
  if (r.name) console.log('           name: ' + r.name); if (r.lease) console.log('           lease: ' + r.lease + '  at ' + r.lon + ', ' + r.lat);
  if (r.error) console.log('           ERROR ' + r.error);
}