GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Websites and apps / seed-data / experiments/economical-seeds

Link Targets and 3 more files

A JavaScript module in the drivers folder of Testcode that reads receivers. It is built from the check step (`check`), the note step (`note`) and the strip step (`strip`).

692 lines of JavaScript and Python from seed-data, testcode, in 4 files. Topic: Websites and apps. Section 2013 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. Teleprint Index render · seed-data / experiments/economical-seeds/teleprint_index.py lines 1–118
  2. Link Targets storage · testcode / drivers/link-targets.mjs lines 1–431
  3. Power State Counterexample electrical · testcode / examples/power_state_counterexample.py lines 1–46
  4. Published Surfaces ingest · testcode / lib/published-surfaces.mjs lines 1–97

Teleprint Index

A Python command-line tool in the economical seeds folder of Seed Data that indexes a local GridAtlas teleprint and join exact text sections to Modular Star, using SHA-256.

renderseed-data / experiments/economical-seeds/teleprint_index.py · lines 1–118 of 118 · Entry point

What it does
It lists and searches its content. Defines index, retrieve. Uses libraries argparse, hashlib, json, re, contextlib. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage experimental (path word 'experiments'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: command-line arguments. Out: JSON file.
Downstream impact
Used directly by 3 files: Experiment A (seed-data); Experiment B (seed-data); State Compare (seed-data). Reached from 2 other entry points, including Bench State Compare (seed-data); Test State Compare (seed-data).
What it achieves
Defines `index` and `retrieve`. It accepts `--index`, `--from-index` and `--extract`.
Why it matters
Imported by Experiment A, Experiment B and State Compare.
Application
seed-data · experiments/economical-seeds · Python CLI
Uses
History (import), Magnets (import), argparse, hashlib, json, re, contextlib, pathlib
Used by
imported by Experiment A (import), imported by Experiment B (import), imported by State Compare (sys.path import)
Produces
index, retrieve
Defines here
index, retrieve
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
seed-data@e4af7ee340a38d94f21ddbba147395b569ccce11 experiments/economical-seeds/teleprint_index.py:1-118 · blob 90f12c840103310afa97423542925ab87d65cb35 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: experimental · users: none · canonical: supporting_data
"""Index a local GridAtlas teleprint and join exact text sections to Modular Star."""
import argparse
import hashlib
import json
import re
from contextlib import closing
from pathlib import Path

from history import git_blob
from magnets import DB, connect, file_sha, read_json

RULE = r"={78}\n"
CONTENTS = re.compile(RULE + r"CONTENTS -- (\d+) file\(s\), (\d+) characters\n" + RULE)
ITEM = re.compile(r"^ *(\d+)\. (.+)\n +(\d+) chars · (.+)$", re.M)
SECTION = re.compile(RULE + r"FILE: (.+)\n(\d+) chars · (.+)\n" + RULE)
MISSING = re.compile(RULE + r"NOT READ -- (\d+) resource\(s\)\n" + RULE)
LIVE = RULE + r"THE LIVE PAGE AS IT STOOD \(document.documentElement.outerHTML\)\n"
END = RULE + r"END OF TELEPRINT\n={78}(?:\n|$)"


def index(path, database):
    raw = path.read_bytes()
    text = raw.decode("utf-8-sig")
    contents = CONTENTS.search(text)
    if not contents:
        raise ValueError("Missing contents index")
    first = SECTION.search(text, contents.end())
    if not first:
        raise ValueError("Missing file sections")
    expected = [(url, int(size), kind) for _, url, size, kind in ITEM.findall(
        text[contents.end():first.start()])]
    matches = list(SECTION.finditer(text, first.start()))
    end = re.search(END, text[matches[-1].end():])
    if not end or len(expected) != len(matches) or len(matches) != int(contents[1]):
        raise ValueError("Incomplete capture or unexpected framing")
    if sum(x[1] for x in expected) != int(contents[2]):
        raise ValueError("Index character total mismatch")
    end_offset = matches[-1].end() + end.start()
    missing = MISSING.search(text, contents.end(), first.start())
    missing_items = []
    if missing:
        live = re.search(LIVE, text[missing.end():first.start()])
        boundary = missing.end() + live.start() if live else first.start()
        missing_items = re.findall(r"^- (.+)\n +(.*)$", text[missing.end():boundary], re.M)
        if len(missing_items) != int(missing[1]):
            raise ValueError("Omission list count mismatch")
    state_block = re.search(RULE + r"THE SCREEN THIS CAME FROM\n" + RULE, text)
    state, _ = json.JSONDecoder().raw_decode(text[state_block.end():].lstrip())
    records = []
    previous_end = 0
    byte_end = 3 if raw.startswith(bytes.fromhex("efbbbf")) else 0
    with closing(connect(database)) as connection:
        for i, match in enumerate(matches):
            url, size, role = match.groups()
            finish = matches[i+1].start() if i+1 < len(matches) else end_offset
            section = text[match.end():finish]
            if (url, int(size), role.replace("shown in full", "in full")) != expected[i] or not section.endswith("\n\n"):
                raise ValueError(f"Index or boundary mismatch in section {i+1}")
            body = section[:-2]
            if len(body.encode("utf-16-le"))//2 != int(size):
                raise ValueError(f"Character count mismatch in section {i+1}")
            data = body.encode("utf-8")
            byte_start = byte_end + len(text[previous_end:match.end()].encode("utf-8"))
            byte_end = byte_start + len(data)
            previous_end = finish-2
            blob = git_blob(data)
            tablet = connection.execute("select n from tablet where git_blob=?", (blob,)).fetchone()
            records.append(dict(section=i+1, url=url, kind=role, utf16_units=int(size),
                                byte_start=byte_start, byte_length=len(data),
                                text_sha256=hashlib.sha256(data).hexdigest(), git_blob=blob,
                                tablet=tablet[0] if tablet else None))
    return dict(input=str(path), input_sha256=hashlib.sha256(raw).hexdigest(), bytes=len(raw),
                newline_count=text.count("\n"), database_sha256=file_sha(database),
                screen={k: state.get(k) for k in ("generation", "capturedAt", "viewport")},
                records=records, not_read=missing_items)


def retrieve(path, record):
    with path.open("rb") as stream:
        stream.seek(record["byte_start"])
        raw = stream.read(record["byte_length"])
    if hashlib.sha256(raw).hexdigest() != record["text_sha256"]:
        raise ValueError("Selected section content differs from the index")
    return raw


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("capture", type=Path)
    modes = parser.add_mutually_exclusive_group(required=True)
    modes.add_argument("--index", type=Path)
    modes.add_argument("--from-index", type=Path)
    parser.add_argument("--extract", help="Exact resource URL or a unique URL suffix")
    parser.add_argument("--output", type=Path, help="Destination for verified resource bytes")
    parser.add_argument("--find", default="rail|metro|tram")
    args = parser.parse_args()
    if args.from_index:
        if not args.extract or not args.output:
            parser.error("--from-index requires --extract and --output")
        receipt = read_json(args.from_index)
        selected = [r for r in receipt["records"] if r["url"].endswith(args.extract)]
        if len(selected) != 1:
            parser.error(f"Expected one resource match, found {len(selected)}")
        payload = retrieve(args.capture, selected[0])
        with args.output.open("xb") as stream:
            stream.write(payload)
        print(json.dumps(selected[0], indent=2))
        raise SystemExit(0)
    before = file_sha(DB)
    result = index(args.capture, DB)
    if result["database_sha256"] != before:
        raise ValueError("Database changed during indexing")
    with args.index.open("x", encoding="utf-8") as stream:
        json.dump(result, stream, indent=2)
    hits = [r for r in result["records"] if re.search(args.find, r["url"], re.I)]
    print(json.dumps(dict(bytes=result["bytes"], sections=len(result["records"]),
                          exact_tablets=sum(r["tablet"] is not None for r in result["records"]),
                          omissions=len(result["not_read"]), query=args.find, hits=hits), indent=2))

Link Targets

A JavaScript module in the drivers folder of Testcode that reads receivers. It is built from the check step (`check`), the note step (`note`) and the strip step (`strip`).

storagetestcode / drivers/link-targets.mjs · lines 1–431 of 431 · Not reached from any entry point (candidate for review) · pattern posix (shared by 2 files)

What it does
It loads receivers. Defines 7 functions or classes, including check, note, strip, walk, posix. Uses libraries node:fs, node:path, node:url. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage experimental (repository name word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. README: "Every run saves all six immutable checkout SHAs in `estate-inputs.json` alongside `testcode-run.json`, `link-targets.json` and `repd-rows.json`."
Inputs & outputs
In: JSON file receivers.json; command-line arguments. Out: JSON file link-targets.json.
What it achieves
Every deep link this estate builds, and where it lands.
Why it matters
No other file in the estate was found to import it.
Application
testcode · drivers · JavaScript module
Uses
Published Surfaces (import), node:fs, node:path, node:url
Used by
none found
Produces
check, note, strip, walk, posix, isAssertion, classify
Defines here
check, note, strip, walk, posix, isAssertion, classify
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 drivers/link-targets.mjs:1-431 · blob 57697a7f89249e1892b7ac06ed76287f5669daae · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: experimental · users: none · canonical: unreached_review
/* link-targets.mjs — every deep link this estate builds, and where it lands.
 *
 * "make the testcode engine clever so that you can use it as a driver to
 *  automate links updates in map button" — the architect, 2026-09-05.
 *
 * The fault: the MAP button in Pipeline News built every link against
 * https://globalgrid2050.com/repd_grid_atlasv8/ — a page that answers with HTTP
 * 200 and carries no engine at all. 21,045 bytes, zero cartridges, zero
 * current.json, zero nearest-substation path, against 20 cartridge references
 * in the v9 shell. Every MAP click landed somewhere inert, and no monitor
 * complained, because a link checker calls that green.
 *
 * This driver reads the estate's SOURCE — offline, from local clones — finds
 * every place a deep link is constructed, and reports which receiver each one
 * targets. A consumer building against a retired receiver is a FAILURE here,
 * not a note, because the whole point is that this must never again be
 * something a person had to notice.
 *
 * The list of retired receivers is not written here. It is read from the
 * engine's published contract, ventus-grid-engine/deeplink/receivers.json, so
 * retiring a route is done once, in the place that knows, rather than in every
 * checker that ever copied it.
 *
 * TWO WAYS THIS GATE WAS GREEN WHILE THE FAULT WAS LIVE, both measured
 * 2026-09-05, both fixed below:
 *
 *   1. It could not see HTML. SCAN accepted only .js and .mjs. The page served
 *      at https://globalgrid2050.com/uk_renewables_pipeline/v9.7/ carries
 *          <a href="../../repd_grid_atlasv8/">MAP ATLAS</a>
 *      in its nav bar, and that URL answers HTTP 200. This driver printed "no
 *      LIVE consumer builds a deep link against a retired receiver" while a
 *      reader could click it. "0 live sites" was true of the JavaScript and
 *      false of the HTML. It now reads .html, and resolves every anchor
 *      against the URL the file is published at, because the fault was written
 *      as a RELATIVE href and no amount of searching for the absolute string
 *      would ever have found it.
 *
 *   2. It decided what was live from a directory-name regex. See the block on
 *      classification below: nine directories the homepage links right now
 *      were being excluded from the verdict as superseded history, and the
 *      build cut that morning was counted live only by falling off the end of
 *      the function.
 *
 * Run: node drivers/link-targets.mjs
 *      node drivers/link-targets.mjs --estate DIR   read a different estate
 *          root. This is how the gate is shown going red and then green on a
 *          controlled input; a check nobody has watched fail is a claim.
 */
import { existsSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { homepageSurfaces } from '../lib/published-surfaces.mjs';

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const estateFlag = process.argv.indexOf('--estate');
const PARENT = estateFlag >= 0 && process.argv[estateFlag + 1]
    ? path.resolve(process.cwd(), process.argv[estateFlag + 1])
    : path.resolve(ROOT, '..');
const checks = [];
const check = (name, ok, detail = '') => checks.push({ name, ok: Boolean(ok), detail });
/* A line that is always true is a measurement, not a check, and counting it in
   "N/N checks passed" is how a suite inflates its own denominator with things
   that could never have gone red. These are printed separately and excluded
   from the total. */
const notes = [];
const note = (name, detail) => notes.push({ name, detail });

/* ---- The contract, read from the engine rather than restated ------------- */
const contractPath = path.join(PARENT, 'ventus-grid-engine', 'deeplink', 'receivers.json');
if (!existsSync(contractPath)) {
    console.error('ventus-grid-engine/deeplink/receivers.json is not present.');
    console.error('This driver has nothing to check against, which is a failure, not a pass:');
    console.error('a check that cannot find its own contract has checked nothing.');
    process.exit(1);
}
const contract = JSON.parse(readFileSync(contractPath, 'utf8'));
const canonical = contract.canonical.route;
const retired = (contract.retired || []).map((r) => r.route);

const strip = (value) => String(value).split('?')[0].split('#')[0].replace(/\/+$/, '');
const retiredStripped = retired.map(strip);

/* ---- Which surfaces the estate actually publishes -------------------------
   This used to be a directory-name regex, /^v9(\.\d+)*$/, with the highest
   name declared live and every other name declared "superseded history" and
   excluded from the verdict. Two things that regex got wrong, both measured:

     - uk_renewables_pipeline/202609051156/ — the build cut that morning and
       the FIRST pipeline link on the homepage — matches no version pattern at
       all, so it reached 'live' only by falling off the end of the function.
       A timestamped release directory being treated correctly by accident is
       not the same as being treated correctly.

     - v7, v9, v9.4, v9.5, v9.5.1, v9.6, v9.6.1, v9.6.2 and v9.7 are all linked
       from https://globalgrid2050.com/ right now, and every one of their index
       pages served <a href="../../repd_grid_atlasv8/">MAP ATLAS</a>. They were
       excluded from the verdict as history WHILE THE HOMEPAGE PUBLISHED THEM.

   A directory name is not a publication decision; the homepage is. So the set
   of supported surfaces is read from globalgrid2050/index.html — the same
   bytes served at the root of the site. A surface the homepage links has to be
   right. A directory it does not link is reported with its count and left
   alone, which is still the estate's rule about dated publications: an erratum,
   not a rewrite. The difference is that "left alone" is now a decision the
   homepage made, and it can be changed by unlinking the page. */
const published = homepageSurfaces(PARENT);

/* ---- Where the estate builds links --------------------------------------- */
/* Only the surfaces that emit project deep links. Kept explicit rather than
   scanning everything: a driver that greps the whole estate finds every URL
   ever written in a comment and drowns the real finding.

   `servedAt` is the URL a file is read at, and it is what makes a relative
   href checkable. Without it a `../../repd_grid_atlasv8/` cannot be resolved
   to a route at all, and this driver records the href as unresolved rather
   than passing over it.

   pipelinenews is a build repo, not a site, so most of its markup has no
   address. Its TEMPLATES do: ui/templates/*.html is what a published version
   shell is generated from, and it is served at
   uk_renewables_pipeline/<version>/index.html. That depth is all a relative
   href needs, and it matters — the template that generates every future shell
   was carrying <a href="../../repd_grid_atlasv8/">MAP ATLAS</a> itself, which
   is the difference between fixing the output and fixing the thing that makes
   the output. */
const SCAN = [
    {
        repo: 'globalgrid2050',
        repoRoot: path.join(PARENT, 'globalgrid2050'),
        dir: path.join(PARENT, 'globalgrid2050', 'uk_renewables_pipeline'),
        exts: ['.js', '.mjs', '.html'],
        servedAt: (rel) => new URL(rel, 'https://globalgrid2050.com/').href
    },
    {
        repo: 'pipelinenews',
        repoRoot: path.join(PARENT, 'pipelinenews'),
        dir: path.join(PARENT, 'pipelinenews'),
        exts: ['.js', '.mjs', '.html'],
        skip: ['node_modules', '.git', 'releases', 'build'],
        servedAt: (rel) => (rel.startsWith('ui/templates/')
            ? 'https://globalgrid2050.com/uk_renewables_pipeline/{version}/index.html'
            : null)
    }
];

function walk(dir, exts, skip, out, depth = 0) {
    if (depth > 8 || !existsSync(dir)) return out;
    for (const name of readdirSync(dir)) {
        if ((skip || []).includes(name) || name === 'node_modules' || name === '.git') continue;
        const full = path.join(dir, name);
        let s;
        try { s = statSync(full); } catch { continue; }
        if (s.isDirectory()) walk(full, exts, skip, out, depth + 1);
        else if (exts.includes(path.extname(name))) out.push(full);
    }
    return out;
}

const posix = (p) => p.replace(/\\/g, '/');
const findings = [];
const unresolved = [];

for (const target of SCAN) {
    const files = walk(target.dir, target.exts, target.skip, []);
    for (const file of files) {
        let source;
        try { source = readFileSync(file, 'utf8'); } catch { continue; }
        const rel = posix(path.relative(PARENT, file));

        if (path.extname(file) === '.html') {
            /* ---- HTML: an anchor is a link, and it is usually relative ------
               No guard on repd_ref/atlasUrl here: those names belong to the
               JavaScript that builds a per-row link. A nav button is a plain
               <a href> and carries none of them, which is the second reason
               this gate could not see the fault it was written for.

               Comments are removed before anything is read, so the note in
               202609051156/index.html explaining what the button USED to open
               is not counted as the thing it stopped doing. A mention is not a
               link, in HTML too. */
            const markup = source.replace(/<!--[\s\S]*?-->/g, '');
            const base = target.servedAt(posix(path.relative(target.repoRoot, file)));
            const byRoute = new Map();
            for (const m of markup.matchAll(/<a\b[^>]*?\bhref\s*=\s*["']([^"']+)["']/gi)) {
                const href = m[1].trim();
                if (!href || href.startsWith('#') || /^(mailto|tel|javascript):/i.test(href)) continue;
                let resolved = null;
                if (/^https?:\/\//i.test(href)) resolved = href;
                else if (base) { try { resolved = new URL(href, base).href; } catch { resolved = null; } }
                if (!resolved) {
                    /* A relative href in a repo with no declared origin cannot
                       be resolved to a receiver. Recorded with its file, never
                       just dropped: an unreadable href is not a clean one, and
                       one on a LIVE surface is a hole in this gate's coverage
                       that has to be visible as a failure rather than as a
                       silent zero. */
                    unresolved.push({ repo: target.repo, file: rel, href });
                    continue;
                }
                const bare = strip(resolved);
                for (const route of [canonical, ...retired]) {
                    if (bare !== strip(route)) continue;
                    const key = strip(route);
                    byRoute.set(key, (byRoute.get(key) || 0) + 1);
                }
            }
            for (const [route, count] of byRoute) {
                findings.push({
                    repo: target.repo,
                    file: rel,
                    kind_of_site: 'html anchor',
                    route,
                    retired: retiredStripped.includes(route),
                    builds: count,
                    mentions_only: 0
                });
            }
            continue;
        }

        /* A deep link is a URL that carries the identity parameter, or a
           builder named for the atlas. Both shapes, because the estate has
           written it both ways. */
        if (!/repd_ref|atlasUrl|buildDeepLink|atlasLink/.test(source)) continue;
        for (const route of [canonical, ...retired]) {
            const bare = strip(route);
            if (!source.includes(bare)) continue;
            /* A MENTION IS NOT A LINK.
               Lane B caught this on the first real use: this driver flagged
               three files that name the retired route in order to ASSERT ITS
               ABSENCE. A proof saying "this must never appear" was being
               reported as the very thing it prevents, which is how a gate
               teaches people to ignore it.

               So classify the line the route sits on. Assigned, concatenated
               or handed to new URL() is a link; inside an assertion, a
               negation or a comment it is a statement ABOUT a link, counted
               separately and reported rather than judged. */
            /* A REFUSAL LIST IS NOT A LINK EITHER.
               Second time this driver has had to learn the distinction. A
               consumer that compiles in the engine's contract necessarily
               carries the RETIRED routes too -- that is what lets it refuse
               one before the live document has been read, and dropping them
               would make the compiled copy less safe, not more. Those entries
               sit inside the `retired:` array of a COMPILED_CONTRACT block and
               are already checked against the published contract, entry for
               entry, further down this file. Counting them as links would fail
               a consumer for holding the very list that protects it. */
            const compiledBlock = (source.match(/const COMPILED_CONTRACT[\s\S]*?\n\}\);/) || [""])[0];
            const compiledRetired = compiledBlock
                ? new Set([...compiledBlock.matchAll(/route:\s*"([^"]+)"/g)].map((m) => strip(m[1])).slice(1))
                : new Set();
            const lines = source.split('\n').filter((l) => l.includes(bare));
            const isAssertion = (line) =>
                /assert|expect|doesNotMatch|toBe|!==|===|must not|never|retired|forbidden|\bnot\b/i.test(line)
                || /^\s*(\/\/|\*|\/\*)/.test(line)
                || (compiledRetired.has(bare) && compiledBlock.includes(line.trim()));
            const buildLines = lines.filter((l) => !isAssertion(l));
            findings.push({
                repo: target.repo,
                file: rel,
                kind_of_site: 'script',
                route: bare,
                retired: retiredStripped.includes(bare),
                builds: buildLines.length,
                mentions_only: lines.length - buildLines.length
            });
        }
    }
}

/* ---- Live, or history? ---------------------------------------------------
   The first run of this driver reported 65 sites on the retired receiver and
   would have stayed red for ever. Some of them are IMMUTABLE: an archive tree
   and superseded published bundles that the homepage no longer offers. A
   published version is a dated record and must not be rewritten — the estate's
   own rule is that a dated publication gets an erratum, not a rewrite — so a
   gate that demands they change is a gate that can never go green, which is
   precisely how a check decays into an alarm nobody reads.

   So they are classified, not filtered. What changed is WHO decides: the
   homepage, by linking a surface, rather than a regex over directory names. */
function classify(file) {
    const rel = posix(file);
    if (/(^|\/)archive\//.test(rel)) return 'archived';
    if (!rel.startsWith('globalgrid2050/')) return 'live';
    if (!published.ok) return 'unknown';
    return published.publishes(rel.slice('globalgrid2050/'.length)) ? 'live' : 'not-published';
}

for (const f of findings) f.kind = classify(f.file);

const onRetiredAll = findings.filter((f) => f.retired && f.builds > 0);
const retiredMentionsOnly = findings.filter((f) => f.retired && f.builds === 0);
const onRetired = onRetiredAll.filter((f) => f.kind === 'live');
const retiredHistory = onRetiredAll.filter((f) => f.kind !== 'live');
const onCanonical = findings.filter((f) => !f.retired);

check('the engine publishes a canonical receiver for consumers to read',
    Boolean(canonical), canonical);

/* The surface list is itself a measurement, and a wrong one silences this
   gate, so it is checked rather than assumed. */
check('the set of supported surfaces was read from the homepage the estate serves',
    published.ok,
    `${published.source}: ${published.why}; pipeline surfaces published: ${published.pipelineDirs.join(', ') || 'none'}`);

const unresolvedLive = unresolved.filter((u) => classify(u.file) === 'live');
check('every relative href on a LIVE surface could be resolved to a URL',
    unresolvedLive.length === 0,
    unresolvedLive.length === 0
        ? `every anchor on a published surface resolved against its origin; ${unresolved.length} unresolvable href(s) remain, all in the archive or in unpublished directories, because their repo declares no publish origin`
        : `${unresolvedLive.length} relative href(s) on a published surface could not be resolved — unreadable, therefore unchecked: ${[...new Set(unresolvedLive.map((u) => u.file))].slice(0, 6).join('; ')}`);

/* ---- THE COMPILED COPY, AND THE GATE THAT MAKES IT SAFE ------------------
 *
 * On 2026-09-05 the live consumer was measured unable to paint a single one of
 * its 7,680 rows until a cross-origin fetch of receivers.json completed, because
 * it held no route of its own and its link builder is synchronous. It now
 * compiles the engine's contract in and fetches the published one to verify it.
 *
 * That is only defensible with THIS check. A hard-coded route the estate cannot
 * notice drifting is the original fault -- seven plugins each holding a route
 * that had quietly stopped being true. A hard-coded route compared against the
 * engine's published document on every offline run is a cache with an expiry
 * the estate can see. The difference is entirely this block, so it fails hard
 * rather than warning: if the compiled copy and the published document ever
 * disagree, the consumer must be corrected before anything ships.
 *
 * It reads the consumer's SOURCE rather than trusting a declaration in it, and
 * it locates the module by name rather than by a path list, so cutting v9.8
 * does not leave the check pointing at a file nobody serves. */
const compiledConsumers = walk(
    path.join(PARENT, 'globalgrid2050', 'uk_renewables_pipeline'), ['.js'], [], [],
).filter((file) => path.basename(file).startsWith('atlas-receiver-')
    && classify(posix(path.relative(PARENT, file))) === 'live');

const compiled = compiledConsumers.map((file) => {
    const source = readFileSync(file, 'utf8');
    const block = source.match(/const COMPILED_CONTRACT\s*=\s*Object\.freeze\(([\s\S]*?)\n\}\);/);
    const routes = block ? [...block[1].matchAll(/route:\s*"([^"]+)"/g)].map((m) => strip(m[1])) : [];
    return {
        file: posix(path.relative(PARENT, file)),
        present: Boolean(block),
        canonical: routes[0] || null,
        retired: routes.slice(1),
    };
});

check('the live consumer compiles in the contract rather than waiting on a fetch to build a link',
    compiled.length > 0 && compiled.every((c) => c.present),
    compiled.length
        ? compiled.map((c) => `${c.file} ${c.present ? 'has' : 'MISSING'} COMPILED_CONTRACT`).join('; ')
        : 'no live atlas-receiver module found, so this check measured nothing');

check("the compiled-in canonical receiver equals the engine's published one",
    compiled.length > 0 && compiled.every((c) => c.canonical === strip(canonical)),
    compiled.map((c) => `${c.file}: ${c.canonical} vs published ${strip(canonical)}`).join('; '));

check('the compiled-in contract carries every route the engine has retired',
    compiled.length > 0 && compiled.every((c) => retiredStripped.every((r) => c.retired.includes(r))),
    compiled.map((c) => `${c.file}: retired [${c.retired.join(', ')}] vs published [${retiredStripped.join(', ')}]`).join('; '));

check('the compiled-in canonical receiver is not itself a retired route',
    compiled.length > 0 && compiled.every((c) => !retiredStripped.includes(c.canonical)),
    'a compiled contract naming a dead receiver is the original defect, cached');
check('at least one consumer was found, so this driver is measuring something',
    findings.length > 0,
    `${findings.length} link-building sites across ${new Set(findings.map((f) => f.repo)).size} repo(s)`);

/* The scanner has to be able to see the file type the fault was written in.
   It could not, for a day and a half, and reported green the whole time. */
const htmlFindings = findings.filter((f) => f.kind_of_site === 'html anchor');
check('the scanner reads the markup as well as the scripts',
    SCAN.every((t) => t.exts.includes('.html')),
    `${htmlFindings.length} receiver anchor(s) found in HTML, which the .js/.mjs-only scanner could not see at all`);

check('no LIVE consumer builds a deep link against a retired receiver',
    onRetired.length === 0,
    onRetired.length
        ? onRetired.map((f) => `${f.file} (${f.kind_of_site})`).join('; ')
        : 'every live consumer targets the canonical receiver');
/* Reported, never counted against the verdict, and never hidden either: a
   count that quietly disappears is how the estate loses track of what it is
   carrying. */
note('a route named only to assert its absence is not counted as a link',
    `${retiredMentionsOnly.length} file(s) name the retired route only in an assertion or a comment`);
note('history is recorded rather than rewritten',
    `${retiredHistory.length} site(s) in the archive or in directories the homepage does not link still name the retired receiver, correctly left alone`);

const report = {
    schema: 'globalgrid2050.testcode.link-targets.v2',
    generated_utc: new Date().toISOString(),
    estate_root: posix(PARENT),
    canonical_receiver: canonical,
    retired_receivers: retired,
    contract_source: 'ventus-grid-engine/deeplink/receivers.json',
    published_surfaces_source: published.source,
    published_pipeline_surfaces: published.pipelineDirs,
    unresolved_relative_hrefs: unresolved.length,
    unresolved_relative_hrefs_on_live_surfaces: unresolvedLive.length,
    on_canonical: onCanonical,
    on_retired: onRetired,
    on_retired_not_published: retiredHistory
};
writeFileSync(path.join(process.cwd(), 'link-targets.json'), JSON.stringify(report, null, 2) + '\n');

console.log(`canonical receiver   ${canonical}`);
console.log(`retired              ${retired.join(', ') || 'none'}`);
console.log(`surfaces published   ${published.pipelineDirs.join(', ') || 'none'} (from ${published.source})`);
console.log(`link-building sites  ${findings.length}  (${htmlFindings.length} in HTML)\n`);
for (const f of findings) {
    if (f.retired && f.builds > 0 && f.kind === 'live') {
        console.log(`RETIRED  ${f.file}  [${f.kind_of_site}, LIVE]`);
        console.log(`         -> ${f.route}`);
    }
}
console.log(`(${findings.length - onRetired.length} further site(s) on the canonical receiver, in the archive, or in unpublished directories — see link-targets.json)`);

let failed = 0;
console.log('');
for (const c of checks) {
    if (!c.ok) failed += 1;
    console.log(`${c.ok ? 'ok  ' : 'FAIL'}  ${c.name}${c.detail ? '  -- ' + c.detail : ''}`);
}
console.log('');
for (const n of notes) console.log(`note  ${n.name}  -- ${n.detail}`);
console.log(`(a note is a measurement with no pass or fail. It is not counted below,`);
console.log(` because a line that could not have gone red is not evidence that it did not.)`);
console.log(`\n${checks.length - failed}/${checks.length} checks passed`);
if (failed) { console.error(`${failed} FAILED`); process.exit(1); }

Power State Counterexample

A Python command-line tool in the examples folder of Testcode that works with feeder observation (`FeederObservation`) and upstream voltage only (`upstream_voltage_only`).

electricaltestcode / examples/power_state_counterexample.py · lines 1–46 of 46 · Entry point

What it does
It calculates its inputs. Defines FeederObservation, upstream_voltage_only, continuity_evidence, mismatch. Uses libraries dataclasses.
Why it exists in the grid workflow
Domain stage experimental (repository name word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. README: "examples/power_state_counterexample.py and its offline tests demonstrate one narrow but falsifiable principle: a live upstream feeder voltage can coexist with an open breaker and no verified power at the load."
Downstream impact
Used directly by 1 file: Test Power State Counterexample (testcode).
What it achieves
It is built from the feeder observation class (`FeederObservation`), the continuity evidence helper (`continuity_evidence`) and the mismatch step (`mismatch`). Illustrative feeder-state counterexample, not operational control logic.
Why it matters
Checked by Test Power State Counterexample.
Application
testcode · examples · Python CLI
Uses
dataclasses
Used by
imported by Test Power State Counterexample (import)
Produces
FeederObservation, upstream_voltage_only, continuity_evidence, mismatch
Defines here
FeederObservation, upstream_voltage_only, continuity_evidence, mismatch
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 examples/power_state_counterexample.py:1-46 · blob 23b8e5c827fbc64e45bd263b2efb5291048bf909 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: unknown
"""Illustrative feeder-state counterexample, not operational control logic.

Context: Google Cloud europe-west2-b outage 20 Oct 2026:
https://status.cloud.google.com/incidents/Xs2XTHzAVC9YnafnPyzj

This model is NOT Google's PLC code, a safe generator-start algorithm,
an engineering design, or a complete electrical topology.
"""

from dataclasses import dataclass


@dataclass(frozen=True)
class FeederObservation:
    line_side_energised: bool
    breaker_closed: bool
    load_side_energised: bool


def upstream_voltage_only(a: FeederObservation, b: FeederObservation) -> bool:
    """Flawed indicator: voltage visible on either line-side meter."""
    return a.line_side_energised or b.line_side_energised


def continuity_evidence(feeder: FeederObservation) -> bool:
    """Illustrative evidence predicate ONLY; not sufficient for real safety logic."""
    return (
        feeder.line_side_energised
        and feeder.breaker_closed
        and feeder.load_side_energised
    )


def mismatch(a: FeederObservation, b: FeederObservation) -> bool:
    """True if upstream voltage falsely suggests a healthy load source."""
    return upstream_voltage_only(a, b) and not (
        continuity_evidence(a) or continuity_evidence(b)
    )


if __name__ == "__main__":
    a = FeederObservation(False, True, False)   # Failed active feeder
    b = FeederObservation(True, False, False)   # Live line side, open breaker
    assert upstream_voltage_only(a, b)
    assert mismatch(a, b)
    print("PASS: upstream voltage can be true while neither feeder delivers power")

Published Surfaces

A JavaScript module in Testcode that converts to repo path (`toRepoPath`).

ingesttestcode / lib/published-surfaces.mjs · lines 1–97 of 97 · Not reached from any entry point (candidate for review) · pattern clean (shared by 37 files)

What it does
It loads data. Defines clean, toRepoPath, homepageSurfaces, publishes. Uses libraries node:fs, node:path. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage experimental (repository name word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Downstream impact
Used directly by 2 files: Renewable Energy Planning Database (REPD) Rows (testcode); Link Targets (testcode).
What it achieves
It is built from the clean step (`clean`), the to repo path helper (`toRepoPath`) and the homepage surfaces helper (`homepageSurfaces`). What the estate publishes, read from the page that publishes it.
Why it matters
Imported by Renewable Energy Planning Database (REPD) Rows and Link Targets.
Application
testcode · lib · JavaScript module
Uses
node:fs, node:path
Used by
imported by Renewable Energy Planning Database (REPD) Rows (import), imported by Link Targets (import)
Produces
homepageSurfaces
Defines here
clean, toRepoPath, homepageSurfaces, publishes
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 lib/published-surfaces.mjs:1-97 · blob 279e109550cc5350c7b8eda3e9e9b5e7b6307f57 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: experimental · users: none · canonical: unreached_review
/* published-surfaces.mjs — what the estate publishes, read from the page that
 * publishes it.
 *
 * Two gates used to decide which surfaces they were responsible for from a
 * directory-name regex:
 *
 *     /^v9(\.\d+)*$/          and then: newest name wins, the rest is history
 *
 * Both consequences were measured on 2026-09-05:
 *
 *   - `uk_renewables_pipeline/202609051156/` — the build that was cut that day
 *     and is the first link on the homepage — matches no version pattern at
 *     all. link-targets classified it 'live' only by falling off the end of
 *     the function, and repd-rows could not see it: its 10/10 was a statement
 *     about v9.7, the control, and about no candidate.
 *   - Nine directories the homepage links RIGHT NOW (v7, v9, v9.4, v9.5,
 *     v9.5.1, v9.6, v9.6.1, v9.6.2, v9.7) were excluded from the verdict as
 *     "superseded history" while every one of them serves
 *     <a href="../../repd_grid_atlasv8/">MAP ATLAS</a> to a real reader.
 *
 * A directory name is not a publication decision. The homepage is. So this
 * reads globalgrid2050/index.html — the same bytes served at
 * https://globalgrid2050.com/ — and returns the set of paths it links. A
 * surface the homepage links is supported and has to be right; a directory it
 * does not link is reported with its count and left alone.
 *
 * Offline by construction: the local clone's index.html, never a fetch. If the
 * clone and the live site ever disagree, that is a different gate's job, and
 * this one names the file it read so the disagreement is visible.
 */
import { existsSync, readFileSync } from 'node:fs';
import path from 'node:path';

const clean = (href) => href.split('?')[0].split('#')[0];

/* A repo-relative path with no './' and no trailing slash, or null if the href
   points off-site, at a fragment, or above the repo root. */
function toRepoPath(href) {
    const value = clean(String(href).trim());
    if (!value || /^[a-z]+:/i.test(value) || value.startsWith('//') || value.startsWith('#')) return null;
    const stripped = value.replace(/^\.\//, '').replace(/^\//, '').replace(/\/+$/, '');
    if (!stripped || stripped.startsWith('..')) return null;
    return stripped;
}

export function homepageSurfaces(parent, repo = 'globalgrid2050') {
    const homepage = path.join(parent, repo, 'index.html');
    if (!existsSync(homepage)) {
        return {
            ok: false,
            repo,
            homepage,
            source: `${repo}/index.html`,
            paths: new Set(),
            why: `${repo}/index.html is not present, so nothing can be said about which surfaces the estate publishes`,
            publishes: () => false,
            pipelineDirs: []
        };
    }
    const source = readFileSync(homepage, 'utf8');
    const paths = new Set(['index.html']);
    for (const m of source.matchAll(/<a\b[^>]*?\bhref\s*=\s*["']([^"']+)["']/gi)) {
        const p = toRepoPath(m[1]);
        if (p) paths.add(p);
    }

    /* A file is published if the homepage links it, or links a directory it
       sits under. index.html of a linked directory is the page that directory
       serves. */
    const publishes = (repoRelPath) => {
        const norm = String(repoRelPath).replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/+$/, '');
        if (paths.has(norm)) return true;
        const parts = norm.split('/');
        for (let i = parts.length - 1; i > 0; i -= 1) {
            if (paths.has(parts.slice(0, i).join('/'))) return true;
        }
        return false;
    };

    const pipelineDirs = [...paths]
        .map((p) => p.match(/^uk_renewables_pipeline\/([^/]+)$/))
        .filter(Boolean)
        .map((m) => m[1])
        .filter((n) => !n.endsWith('.html'))
        .sort();

    return {
        ok: paths.size > 1,
        repo,
        homepage,
        source: `${repo}/index.html`,
        paths,
        why: `${paths.size - 1} link target(s) on ${repo}/index.html`,
        publishes,
        pipelineDirs
    };
}