GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / sld / scripts

Single-Line Diagram (SLD) Fetch Sources and 5 more files

A Python command-line tool in the scripts folder that draws components and metadata, using SHA-256. It extracts text zip (`extract_text_zip`), verifies lock (`verify_lock`) and checks offline (`check_offline`).

665 lines of Python and PowerShell and YAML from sld, in 6 files. Topic: Grid network and substations. Section 451 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. Single-Line Diagram (SLD) Fetch Sources render · sld / scripts/fetch_sources.py lines 1–270
  2. Single-Line Diagram (SLD) Furnace storage · sld / scripts/furnace.py lines 1–146
  3. Single-Line Diagram (SLD) Refresh Local automation · sld / scripts/refresh_local.ps1 lines 1–67
  4. Single-Line Diagram (SLD) Verify Furnace ingest · sld / scripts/verify_furnace.py lines 1–75
  5. Single-Line Diagram (SLD) Sources docs-config · sld / sources.yaml lines 1–60
  6. Browser test · sld / tests/browser.cjs lines 1–47

Single-Line Diagram (SLD) Fetch Sources

A Python command-line tool in the scripts folder that draws components and metadata, using SHA-256. It extracts text zip (`extract_text_zip`), verifies lock (`verify_lock`) and checks offline (`check_offline`).

rendersld / scripts/fetch_sources.py · lines 1–270 of 270 · Entry point · pattern check_offline (shared by 2 files)

What it does
It draws components and metadata. Defines 15 functions or classes, including EvidencePage, __init__, handle_starttag, handle_endtag, handle_data. Uses libraries argparse, hashlib, io, json, html.parser. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage sub33kv_design (repository name word 'sld'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: JSON file source-lock.json; JSON file components.json; JSON file metadata.json; command-line arguments. Out: SVG drawing.
Downstream impact
Used directly by 4 files: Single-Line Diagram (SLD) Build Catalogue (sld); Single-Line Diagram (SLD) Verify Furnace (sld); Test Sources (sld); Single-Line Diagram (SLD) Pages Workflow (sld). Reached from 1 other entry point, including Test Furnace Gate (sld).
What it achieves
Bounded, pinned acquisition; never executes remote content. It accepts `--output`, `--config` and `--accept-first-fetch`.
Why it matters
Imported by Single-Line Diagram (SLD) Build Catalogue and Single-Line Diagram (SLD) Verify Furnace. Run by Single-Line Diagram (SLD) Pages Workflow. Checked by Test Sources.
Application
sld · scripts · Python CLI
Uses
argparse, hashlib, io, json, html.parser, pathlib, re, stat
Used by
imported by Single-Line Diagram (SLD) Build Catalogue (import), imported by Single-Line Diagram (SLD) Verify Furnace (import), imported by Test Sources (sys.path import), run by Single-Line Diagram (SLD) Pages Workflow (workflow run)
Produces
EvidencePage, decc_licence_evidence, digest, safe_name, download, extract_text_zip, verify_lock, check_offline, acquire, main
Defines here
EvidencePage, __init__, handle_starttag, handle_endtag, handle_data, decc_licence_evidence, digest, safe_name, download, extract_text_zip, verify_lock, check_offline, acquire, add, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
sld@1205aa0d1f80d8e05a2cbb19f363939174b50002 scripts/fetch_sources.py:1-270 · blob 56d3ccc9df149c9cb432ee821fe0aa489c2c7762 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unknown
"""Bounded, pinned acquisition; never executes remote content.

sources.yaml deliberately uses the JSON subset of YAML (stdlib json parser).
First reviewed fetch: python scripts/fetch_sources.py --accept-first-fetch
Subsequent runs verify the existing hash lock and fail on any upstream change.
--output selects a data directory, e.g. an external drive. No dependencies.
"""
import argparse
import hashlib
import io
import json
from html.parser import HTMLParser
from pathlib import Path, PurePosixPath
import re
import stat
import urllib.request
import zipfile

ROOT = Path(__file__).resolve().parents[1]


class EvidencePage(HTMLParser):
    """Read only document heading, links and visible footer licence statement."""
    def __init__(self):
        super().__init__(convert_charrefs=True)
        self.links = []
        self.headings = []
        self.footer = []
        self.in_heading = False
        self.in_footer = False
        self.hidden = 0

    def handle_starttag(self, tag, attrs):
        attrs = dict(attrs)
        if tag in {"script", "style"}:
            self.hidden += 1
        if tag == "h1":
            self.in_heading = True
        if tag == "footer":
            self.in_footer = True
        if tag == "a":
            self.links.append((attrs.get("href", ""), attrs.get("rel", "").split()))

    def handle_endtag(self, tag):
        if tag in {"script", "style"}:
            self.hidden = max(0, self.hidden - 1)
        if tag == "h1":
            self.in_heading = False
        if tag == "footer":
            self.in_footer = False

    def handle_data(self, data):
        if not self.hidden:
            if self.in_heading:
                self.headings.append(data)
            if self.in_footer:
                self.footer.append(data)


def decc_licence_evidence(data, source):
    """Distil reviewed evidence, excluding changing nonces/navigation/analytics.

    This is a provenance record, not a licence grant or a mirrored source page.
    The actual PDF bytes remain independently and immutably SHA-256 locked.
    """
    page = EvidencePage()
    page.feed(data.decode("utf-8"))
    heading = " ".join(" ".join(page.headings).split())
    footer = " ".join(" ".join(page.footer).split())
    expected = "All content is available under the Open Government Licence v3.0 , except where otherwise stated"
    licence_url = source["licence_url"]
    pdf_url = next(item["url"] for item in source["files"] if item["name"].endswith(".pdf"))
    if heading != source["title"]:
        raise ValueError("DECC source title changed")
    license_links = [url for url, rel in page.links if "license" in rel]
    if license_links != [licence_url] or expected not in footer or "Crown copyright" not in footer:
        raise ValueError("DECC source page lacks expected OGL v3.0 / Crown copyright evidence")
    if pdf_url not in [url for url, _ in page.links]:
        raise ValueError("DECC source page lacks expected PDF link")
    evidence = {
        "schema_version": "1.0", "extractor": "decc-licence-evidence-v1",
        "title": heading, "source_url": source["url"], "pdf_url": pdf_url,
        "licence": "OGL-UK-3.0", "licence_url": licence_url,
        "scope": "All content is available under the Open Government Licence v3.0, except where otherwise stated",
        "copyright": "Crown copyright",
        "attribution": "Department of Energy & Climate Change, Illustrative example of a sample single line diagram (1 August 2014). Contains public sector information licensed under the Open Government Licence v3.0."
    }
    return (json.dumps(evidence, indent=2, sort_keys=True) + "\n").encode("utf-8")


def digest(data):
    return hashlib.sha256(data).hexdigest()


def safe_name(name):
    if not isinstance(name, str) or not re.fullmatch(r"[A-Za-z0-9_.-]+", name) or name in {".", ".."}:
        raise ValueError(f"Unsafe filename: {name!r}")
    return name


def download(url, limit):
    if not url.startswith("https://"):
        raise ValueError("Only HTTPS sources are accepted")
    request = urllib.request.Request(url, headers={"User-Agent": "SLD-library-research/1.0"})
    with urllib.request.urlopen(request, timeout=45) as response:
        if not response.geturl().startswith("https://"):
            raise ValueError("Non-HTTPS redirect")
        length = response.headers.get("Content-Length")
        if length and int(length) > limit:
            raise ValueError(f"Source exceeds byte limit: {url}")
        data = response.read(limit + 1)
    if len(data) > limit:
        raise ValueError(f"Source exceeds byte limit: {url}")
    return data


def extract_text_zip(data, allowed, limit=1000000):
    """Return exact allowlisted text members, rejecting traversal/symlinks/bombs."""
    expected = set(allowed)
    result = {}
    total = 0
    with zipfile.ZipFile(io.BytesIO(data)) as archive:
        seen = set()
        for info in archive.infolist():
            name = info.filename
            path = PurePosixPath(name)
            if name in seen or path.is_absolute() or ".." in path.parts or "\\" in name or ":" in name:
                raise ValueError(f"Unsafe or duplicate ZIP member: {name}")
            seen.add(name)
            if stat.S_ISLNK(info.external_attr >> 16):
                raise ValueError("ZIP symlink rejected")
            if info.is_dir():
                if name != "send_network_dsse/":
                    raise ValueError("Unexpected ZIP directory")
                continue
            if name not in expected or path.suffix.lower() not in {".dss", ".csv", ".txt"}:
                raise ValueError(f"ZIP member is not allowlisted text: {name}")
            total += info.file_size
            if total > limit:
                raise ValueError("ZIP expanded-size limit exceeded")
            content = archive.read(info)
            content.decode("utf-8-sig")
            if b"\x00" in content:
                raise ValueError("Binary ZIP member rejected")
            result[name] = content
    if set(result) != expected:
        raise ValueError("ZIP is missing expected members")
    return result


def verify_lock(records, previous):
    old = {entry["path"]: entry for entry in previous["files"]}
    new = {entry["path"]: entry for entry in records}
    if set(old) != set(new):
        raise ValueError("Source file set changed; review required")
    for path, entry in new.items():
        for field in ("sha256", "url", "licence", "source_id"):
            if entry[field] != old[path][field]:
                raise ValueError(f"Locked source changed ({field}): {path}")


def check_offline(config, output):
    """Verify locked local bytes and source attribution without making requests."""
    output = Path(output).resolve()
    lock = json.loads((output / "source-lock.json").read_text(encoding="utf-8"))
    sources = {source["id"]: source for source in config["sources"]}
    seen = set()
    for entry in lock["files"]:
        name = entry["path"]
        path = (output / name).resolve()
        if name in seen or not path.is_relative_to(output):
            raise ValueError(f"Unsafe or duplicate locked path: {name}")
        seen.add(name)
        source = sources.get(entry["source_id"])
        if source is None or source["licence"] != entry["licence"]:
            raise ValueError(f"Locked source attribution mismatch: {name}")
        data = path.read_bytes()
        if len(data) != entry["bytes"] or digest(data) != entry["sha256"]:
            raise ValueError(f"Local source integrity failure: {name}")
    for source in config["sources"]:
        for item in source["files"]:
            name = f"upstream/{source['id']}/{item['name']}"
            matching = [entry for entry in lock["files"] if entry["path"] == name]
            if len(matching) != 1 or matching[0]["url"] != item["url"]:
                raise ValueError(f"Missing or changed configured source: {name}")
    return lock


def acquire(config, output, accept_first=False):
    output = Path(output)
    lock_path = output / "source-lock.json"
    previous = json.loads(lock_path.read_text(encoding="utf-8")) if lock_path.exists() else None
    if previous is None and not accept_first:
        raise ValueError("No hash lock: review sources.yaml then pass --accept-first-fetch")
    payloads, records = {}, []

    def add(source, name, url, data, origin=None):
        relative = f"upstream/{source['id']}/{name}"
        if relative in payloads:
            raise ValueError(f"Duplicate output: {relative}")
        payloads[relative] = data
        entry = {"path": relative, "source_id": source["id"], "url": url,
                 "sha256": digest(data), "bytes": len(data), "licence": source["licence"]}
        if origin:
            entry["archive_member"] = origin
        records.append(entry)

    for source in config["sources"]:
        safe_name(source["id"])
        fetched = {}
        for item in source["files"]:
            name = safe_name(item["name"])
            data = download(item["url"], source["max_bytes"])
            if item.get("transform"):
                if item["transform"] != "decc-licence-evidence-v1" or source["id"] != "decc":
                    raise ValueError("Unreviewed source transformation")
                data = decc_licence_evidence(data, source)
            if item.get("md5") and hashlib.md5(data).hexdigest() != item["md5"]:
                raise ValueError(f"Pinned archive MD5 mismatch: {name}")
            if name.endswith(".pdf") and not data.startswith(b"%PDF-"):
                raise ValueError("Expected PDF signature")
            fetched[name] = data
            add(source, name, item["url"], data)
        if source["id"] == "powsybl":
            components = json.loads(fetched["components.json"])
            names = {safe_name(part["fileName"]) for component in components for part in component.get("subComponents", [])}
            if len(components) != source["expected_components"] or len(names) != source["expected_svgs"]:
                raise ValueError("Unexpected PowSyBl component/SVG counts")
            for name in sorted(names):
                if not name.endswith(".svg"):
                    raise ValueError("Unexpected component format")
                url = source["base_url"] + name
                data = download(url, source["max_bytes"])
                if b"<svg" not in data:
                    raise ValueError("Expected SVG content")
                add(source, name, url, data)
        if source["id"] == "send":
            metadata = json.loads(fetched["metadata.json"])
            if metadata.get("doi") != source["revision"] or metadata.get("license", {}).get("name") != "CC BY 4.0":
                raise ValueError("SEND version/licence mismatch")
            for name, data in extract_text_zip(fetched["send_network_dsse.zip"], source["zip_members"]).items():
                add(source, name, source["files"][1]["url"], data, origin=name)
    records.sort(key=lambda item: item["path"])
    if previous:
        verify_lock(records, previous)
    # No writes before every download, licence and existing lock check succeeds.
    for relative, data in payloads.items():
        path = output / relative
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_bytes(data)
    lock = {"schema_version": "1.0", "files": records}
    output.mkdir(parents=True, exist_ok=True)
    lock_path.write_text(json.dumps(lock, indent=2) + "\n", encoding="utf-8", newline="\n")
    return lock


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output", type=Path, default=ROOT / "data")
    parser.add_argument("--config", type=Path, default=ROOT / "sources.yaml")
    parser.add_argument("--accept-first-fetch", action="store_true")
    parser.add_argument("--check-offline", action="store_true", help="Verify existing locked local bytes without HTTP")
    args = parser.parse_args()
    config = json.loads(args.config.read_text(encoding="utf-8"))
    lock = check_offline(config, args.output) if args.check_offline else acquire(config, args.output, args.accept_first_fetch)
    print(f"Verified {len(lock['files'])} files in {args.output}")


if __name__ == "__main__":
    main()

Single-Line Diagram (SLD) Furnace

A Python command-line tool in the scripts folder that reads photon library and photon evidence, using SHA-256.

storagesld / scripts/furnace.py · lines 1–146 of 146 · Entry point · pattern electron (shared by 3 files)

What it does
It loads photon library and photon evidence. Defines digest, reference, main, electron. Uses libraries argparse, hashlib, json, math, os. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage sub33kv_design (repository name word 'sld'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: JSON file library.json; JSON file photon-evidence.json; JSON file photon-library.json; JSON file source-lock.json; command-line arguments.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It is built from the digest step (`digest`), the reference step (`reference`) and the electron step (`electron`). Bounded GPU layout furnace: independent CUDA and CuPy rectangle tests. It accepts `--library`, `--out` and `--grid`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
sld · scripts · Python CLI
Uses
argparse, hashlib, json, math, os, pathlib, time, numpy
Used by
none found
Produces
digest, reference, main
Defines here
digest, reference, main, electron
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
sld@1205aa0d1f80d8e05a2cbb19f363939174b50002 scripts/furnace.py:1-146 · blob eb5854d1152eeb6e4e45a066401ff862169fa174 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: supporting_data
"""Bounded GPU layout furnace: independent CUDA and CuPy rectangle tests.

Reuses the paired-kernel/reference pattern from Ventusltd/worlds-/src/furnace.py.
This checks declared symbol bounding boxes, not electrical safety or SVG ink.
"""
import argparse
import hashlib
import json
import math
import os
from pathlib import Path
import time

KERNEL = r'''
extern "C" __global__ void boxes(const double* w, const double* h,
 unsigned long long start, unsigned long long count, int symbols, int grid,
 double gap, unsigned char* out) {
 unsigned long long k = (unsigned long long)blockDim.x*blockIdx.x+threadIdx.x;
 if(k>=count)return;
 unsigned long long id=start+k, plane=(unsigned long long)grid*grid;
 int a=(id/plane)/symbols, b=(id/plane)%symbols;
 double x=((long long)(id%grid)-grid/2)*0.5;
 double y=((long long)((id/grid)%grid)-grid/2)*0.5;
 double left=x-w[b]/2-gap, right=x+w[b]/2+gap;
 double bottom=y-h[b]/2-gap, top=y+h[b]/2+gap;
 bool strict=(left<w[a]/2 && right>-w[a]/2 && bottom<h[a]/2 && top>-h[a]/2);
 bool inclusive=(left<=w[a]/2 && right>=-w[a]/2 && bottom<=h[a]/2 && top>=-h[a]/2);
 out[k]=strict?2:(inclusive?1:0);
}
'''

def digest(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()

def reference(xp, ids, w, h, n, grid, gap):
    pair = ids // (grid * grid)
    a, b = pair // n, pair % n
    x = (ids % grid - grid // 2) * .5
    y = (ids // grid % grid - grid // 2) * .5
    dx = xp.abs(x) - (w[a] + w[b]) / 2 - gap
    dy = xp.abs(y) - (h[a] + h[b]) / 2 - gap
    return xp.where((dx < 0) & (dy < 0), 2,
                    xp.where((dx <= 0) & (dy <= 0), 1, 0)).astype(xp.uint8)

def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--library', type=Path, default=Path('data/library.json'))
    parser.add_argument('--out', type=Path, required=True)
    parser.add_argument('--grid', type=int, default=1024)
    parser.add_argument('--batch', type=int, default=4_194_304)
    parser.add_argument('--gaps', type=float, nargs='+', default=[0, 2, 4])
    args = parser.parse_args()
    if not 2 <= args.grid <= 2048 or not 1 <= args.batch <= 16_777_216:
        parser.error('grid must be 2..2048; batch 1..16777216')
    if len(set(args.gaps)) != len(args.gaps) or any(not math.isfinite(g) or g < 0 or g > 100 for g in args.gaps):
        parser.error('gaps must be distinct finite values in 0..100')
    args.out.mkdir(parents=True, exist_ok=True)
    # Invalidate old acceptance before any imports or checks that may fail.
    receipt_path = args.out / 'photon-evidence.json'
    receipt_path.write_text(json.dumps({'accepted': False, 'status': 'running'}))
    started = time.perf_counter()
    import numpy as np
    import cupy as cp
    library = json.loads(args.library.read_text(encoding='utf-8'))
    components = library['components']
    eligible = []
    for item in components:
        size = item.get('size', {})
        w, h = size.get('width', 0), size.get('height', 0)
        if isinstance(w, (int, float)) and isinstance(h, (int, float)) and np.isfinite(w+h) and w > 0 and h > 0:
            eligible.append((item['id'], float(w), float(h)))
    if not eligible:
        raise ValueError('No finite positive declared component sizes')
    width = np.array([e[1] for e in eligible], dtype=np.float64)
    height = np.array([e[2] for e in eligible], dtype=np.float64)
    w, h = cp.asarray(width), cp.asarray(height)
    n = len(eligible)
    total = n * n * args.grid * args.grid
    kernel = cp.RawKernel(KERNEL, 'boxes')
    def electron(start, count, gap):
        out = cp.empty(count, dtype=cp.uint8)
        kernel(((count+255)//256,), (256,), (w, h, np.uint64(start), np.uint64(count), np.int32(n), np.int32(args.grid), np.float64(gap), out))
        return out
    # Separate hand-calculated threshold fixtures for inclusive/strict semantics.
    fixtures = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8], dtype=np.int64)
    # Two identical unit boxes, y=0, x from -2 to +2 in half-unit steps.
    fixture_ids = fixtures + 4*9
    expected = np.array([0,0,1,2,2,2,1,0,0], dtype=np.uint8)
    assert np.array_equal(reference(np, fixture_ids, np.array([1.]), np.array([1.]), 1, 9, 0), expected)
    sample_ids = np.unique(np.linspace(0, total-1, min(total, 8192), dtype=np.int64))
    cpu = reference(np, sample_ids, width, height, n, args.grid, args.gaps[0])
    assert np.array_equal(cp.asnumpy(reference(cp, cp.asarray(sample_ids), w, h, n, args.grid, args.gaps[0])), cpu)
    warm = electron(0, min(total, args.batch), args.gaps[0])
    warm_ref = reference(cp, cp.arange(len(warm), dtype=cp.int64), w, h, n, args.grid, args.gaps[0])
    assert int(cp.count_nonzero(warm != warm_ref).get()) == 0
    broken = warm.copy(); broken[0] = (broken[0] + 1) % 3
    assert int(cp.count_nonzero(broken != warm_ref).get()) == 1
    cp.cuda.Stream.null.synchronize()
    setup_seconds = time.perf_counter() - started
    rows = []
    for gap in args.gaps:
        begin = time.perf_counter()
        last_progress = begin
        counts = np.zeros(3, dtype=np.int64)
        mismatches = 0
        for start in range(0, total, args.batch):
            count = min(args.batch, total-start)
            ids = cp.arange(start, start+count, dtype=cp.int64)
            actual = electron(start, count, gap)
            other = reference(cp, ids, w, h, n, args.grid, gap)
            summary = cp.stack([cp.count_nonzero(actual != other)] + [cp.count_nonzero(actual == i) for i in range(3)])
            values = cp.asnumpy(summary)
            mismatches += int(values[0]); counts += values[1:]
            if mismatches:
                raise AssertionError(f'Channels disagree at batch {start}; refusing photon acceptance')
            if time.perf_counter() - last_progress >= 5:
                print(json.dumps({'gap':gap,'checked':start+count,'total':total,'mismatches':mismatches}),flush=True)
                last_progress = time.perf_counter()
        cp.cuda.Stream.null.synchronize()
        row = dict(gap=gap, unique_cases=total, mismatches=mismatches,
                   separated=int(counts[0]), touching=int(counts[1]), overlapping=int(counts[2]),
                   seconds=time.perf_counter()-begin)
        assert sum(counts) == total
        rows.append(row)
        print(json.dumps(row), flush=True)
    photon = dict(schema_version=1, kind='declared-bounding-box-layout-input',
                  library_sha256=digest(args.library), components=[dict(id=i,width=w,height=h) for i,w,h in eligible],
                  statuses={'0':'separated','1':'touching','2':'overlapping'},
                  production_enabled=False,
                  scope='Declared bounding boxes only; no electrical approval, routing, SVG ink or label collision certification.')
    photon_path = args.out / 'photon-library.json'
    photon_path.write_text(json.dumps(photon,indent=2)+'\n',encoding='utf-8', newline='\n')
    receipt = dict(accepted=True, scope=photon['scope'], device=cp.cuda.runtime.getDeviceProperties(0)['name'].decode(),
                   cupy_version=cp.__version__, cuda_runtime=cp.cuda.runtime.runtimeGetVersion(),
                   library_sha256=digest(args.library), script_sha256=digest(Path(__file__)),
                   photon_library_sha256=digest(photon_path), source_lock_sha256=digest(args.library.parent/'source-lock.json'),
                   channels=['raw CUDA interval intersection','CuPy centre-distance separation'],
                   cpu_reference_cases=len(sample_ids), threshold_fixtures=9, injected_error_detected=True,
                   grid=args.grid, pitch=.5, component_count=n, excluded_component_count=len(components)-n,
                   unique_cases=total*len(rows), iterations=rows, setup_seconds=setup_seconds,
                   whole_seconds=time.perf_counter()-started)
    receipt_path.write_text(json.dumps(receipt,indent=2)+'\n',encoding='utf-8', newline='\n')
    print(json.dumps({'accepted':True,'unique_cases':receipt['unique_cases'],'whole_seconds':receipt['whole_seconds']}),flush=True)

if __name__ == '__main__':
    main()

Single-Line Diagram (SLD) Refresh Local

A PowerShell script in the scripts folder covering photon library and photon evidence.

automationsld / scripts/refresh_local.ps1 · lines 1–67 of 67 · Not reached from any entry point (candidate for review)

What it does
Side effects: starts processes.
Why it exists in the grid workflow
Domain stage sub33kv_design (repository name word 'sld'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: JSON file photon-library.json; JSON file photon-evidence.json; JSON file library.json; JSON file source-lock.json.
What it achieves
Trusted main only. Schedule this controller with the existing logged-on user.
Why it matters
No other file in the estate was found to import it.
Application
sld · scripts · PowerShell script
Uses
none found
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
sld@1205aa0d1f80d8e05a2cbb19f363939174b50002 scripts/refresh_local.ps1:1-67 · blob 26d9d049b1f7fbc018bd0a20a437afd018ff1ac6 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
# Trusted main only. Schedule this controller with the existing logged-on user.
param(
    [Parameter(Mandatory=$true)][string]$Repository,
    [Parameter(Mandatory=$true)][string]$OutputRoot,
    [Parameter(Mandatory=$true)][string]$Python,
    [switch]$ForceFurnace
)
$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest
function Run([string]$Program, [string[]]$Arguments) {
    & $Program @Arguments
    if ($LASTEXITCODE -ne 0) { throw "$Program failed ($LASTEXITCODE): $Arguments" }
}
$repoPath = (Resolve-Path -LiteralPath $Repository).Path
$outputPath = [IO.Path]::GetFullPath($OutputRoot)
New-Item -ItemType Directory -Path $outputPath -Force | Out-Null
# A file lock also prevents overlap between manual and scheduled runs.
$lock = $null
$candidate = Join-Path $outputPath 'candidate'
$created = $false
try {
    $lock = [IO.File]::Open((Join-Path $outputPath 'refresh.lock'), 'OpenOrCreate', 'ReadWrite', 'None')
    Set-Location -LiteralPath $repoPath
    $remote = (& git remote get-url origin).Trim()
    if ($LASTEXITCODE -ne 0 -or $remote -notin @('https://github.com/Ventusltd/sld.git','git@github.com:Ventusltd/sld.git')) { throw 'Unexpected repository origin' }
    if ((& git branch --show-current).Trim() -ne 'main') { throw 'Controller requires main' }
    if (@(& git status --porcelain).Count -ne 0) { throw 'Working tree is dirty; refusing to overwrite changes' }
    Run git @('pull','--ff-only','origin','main')
    $base = (& git rev-parse HEAD).Trim()
    if (Test-Path -LiteralPath $candidate) { throw 'Candidate path already exists; inspect it before retrying' }
    Run git @('worktree','add','--detach',$candidate,$base)
    $created = $true
    Set-Location -LiteralPath $candidate
    Run $Python @('scripts/fetch_sources.py')
    Run $Python @('scripts/build_catalogue.py')
    Run $Python @('-m','unittest','discover','-s','tests','-p','test_*.py')
    & $Python scripts/verify_furnace.py
    $needsFurnace = $LASTEXITCODE -ne 0
    if ($needsFurnace -or $ForceFurnace) {
        $furnaceOut = Join-Path $outputPath 'furnace'
        Run $Python @('scripts/furnace.py','--out',$furnaceOut)
        Run $Python @('scripts/verify_furnace.py','--evidence-dir',$furnaceOut)
        New-Item -ItemType Directory -Path 'data/furnace' -Force | Out-Null
        Copy-Item -LiteralPath (Join-Path $furnaceOut 'photon-library.json') -Destination 'data/furnace/photon-library.json'
        Copy-Item -LiteralPath (Join-Path $furnaceOut 'photon-evidence.json') -Destination 'data/furnace/photon-evidence.json'
    }
    Run $Python @('scripts/verify_furnace.py')
    Run $Python @('scripts/build_site.py')
    # Only generated, reviewed-source outputs may enter the autonomous commit.
    Run git @('add','--','data/library.json','data/source-lock.json','data/upstream','data/furnace','assets/previews')
    & git diff --cached --quiet
    if ($LASTEXITCODE -eq 0) { Write-Output 'Pinned sources and accepted furnace inputs unchanged'; return }
    if ($LASTEXITCODE -ne 1) { throw 'Cannot inspect candidate diff' }
    Run git @('-c','user.name=SLD automation','-c','user.email=sld-automation@users.noreply.github.com','commit','-m','Refresh validated SLD catalogue and furnace evidence')
    # Ordinary fast-forward push rejects a concurrently advanced main.
    Run git @('push','origin','HEAD:refs/heads/main')
    Set-Location -LiteralPath $repoPath
    Run git @('pull','--ff-only','origin','main')
} finally {
    Set-Location -LiteralPath $repoPath
    if ($created) {
        $resolvedCandidate = [IO.Path]::GetFullPath($candidate)
        if ($resolvedCandidate -ne (Join-Path $outputPath 'candidate')) { throw 'Candidate cleanup escaped output directory' }
        & git worktree remove --force -- $resolvedCandidate
    }
    if ($null -ne $lock) { $lock.Dispose() }
}

Single-Line Diagram (SLD) Verify Furnace

A Python command-line tool in the scripts folder that reads photon evidence and photon library, using SHA-256.

ingestsld / scripts/verify_furnace.py · lines 1–75 of 75 · Entry point · pattern verify (shared by 34 files)

What it does
It loads photon evidence and photon library. Defines digest, require, verify. Uses libraries argparse, hashlib, json, math, pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage sub33kv_design (repository name word 'sld'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: JSON file photon-evidence.json; JSON file photon-library.json; JSON file library.json; JSON file source-lock.json; command-line arguments.
Downstream impact
Used directly by 2 files: Test Furnace Gate (sld); Single-Line Diagram (SLD) Pages Workflow (sld).
What it achieves
It is built from the digest step (`digest`), the require step (`require`) and the verify step (`verify`). Fail closed when a furnace receipt does not bind the exact published inputs. It accepts `--root` and `--evidence-dir`.
Why it matters
Run by Single-Line Diagram (SLD) Pages Workflow. Checked by Test Furnace Gate.
Application
sld · scripts · Python CLI
Uses
Single-Line Diagram (SLD) Fetch Sources (import), argparse, hashlib, json, math, pathlib
Used by
imported by Test Furnace Gate (sys.path import), run by Single-Line Diagram (SLD) Pages Workflow (workflow run)
Produces
digest, require, verify
Defines here
digest, require, verify
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
sld@1205aa0d1f80d8e05a2cbb19f363939174b50002 scripts/verify_furnace.py:1-75 · blob be40764ef3c526ac602e74f878f5c3bf784bfd91 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unknown
"""Fail closed when a furnace receipt does not bind the exact published inputs."""
import argparse
import hashlib
import json
import math
from pathlib import Path
from fetch_sources import check_offline


def digest(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()


def require(condition, message):
    if not condition:
        raise ValueError(message)


def verify(root, evidence_dir=None):
    root = Path(root)
    check_offline(json.loads((root / 'sources.yaml').read_text(encoding='utf-8')), root / 'data')
    evidence_dir = Path(evidence_dir) if evidence_dir else root / 'data/furnace'
    receipt = json.loads((evidence_dir / 'photon-evidence.json').read_text(encoding='utf-8'))
    photon_path = evidence_dir / 'photon-library.json'
    photon = json.loads(photon_path.read_text(encoding='utf-8'))
    library = json.loads((root / 'data/library.json').read_text(encoding='utf-8'))
    require(receipt.get('accepted') is True, 'Furnace has not accepted this candidate')
    for key, path in [('library_sha256', root / 'data/library.json'),
                      ('source_lock_sha256', root / 'data/source-lock.json'),
                      ('script_sha256', root / 'scripts/furnace.py'),
                      ('photon_library_sha256', photon_path)]:
        require(receipt.get(key) == digest(path), f'Stale or altered {key}')
    require(photon.get('library_sha256') == receipt['library_sha256'], 'Photon library binding differs')
    require(photon.get('production_enabled') is False, 'Photon must not claim production approval')
    eligible = []
    for item in library['components']:
        w, h = item.get('size', {}).get('width', 0), item.get('size', {}).get('height', 0)
        if all(isinstance(v, (int, float)) and math.isfinite(v) and v > 0 for v in [w, h]):
            eligible.append(dict(id=item['id'], width=float(w), height=float(h)))
    require(bool(eligible) and len({c['id'] for c in eligible}) == len(eligible), 'Invalid component IDs')
    require(photon.get('components') == eligible, 'Photon component inputs differ')
    n = len(eligible)
    require(receipt.get('component_count') == n, 'Component count differs')
    require(receipt.get('excluded_component_count') == len(library['components']) - n, 'Excluded count differs')
    grid = receipt.get('grid')
    require(type(grid) is int and 2 <= grid <= 2048, 'Invalid grid')
    require(receipt.get('pitch') == .5, 'Invalid grid pitch')
    total = n * n * grid * grid
    require(receipt.get('cpu_reference_cases') == min(total, 8192), 'Incomplete CPU reference')
    require(receipt.get('threshold_fixtures') == 9, 'Missing threshold fixtures')
    require(receipt.get('injected_error_detected') is True, 'Missing injected-error detection')
    require(receipt.get('channels') == ['raw CUDA interval intersection', 'CuPy centre-distance separation'], 'Missing independent channels')
    rows = receipt.get('iterations')
    require(isinstance(rows, list) and bool(rows), 'Missing iterations')
    gaps = []
    for row in rows:
        gap = row.get('gap')
        require(type(gap) in (float, int) and math.isfinite(gap) and 0 <= gap <= 100, 'Invalid gap')
        gaps.append(gap)
        require(row.get('unique_cases') == total and row.get('mismatches') == 0, 'Incomplete or mismatched cases')
        counts = [row.get(k) for k in ['separated', 'touching', 'overlapping']]
        require(all(type(v) is int and v >= 0 for v in counts), 'Invalid classification counts')
        require(sum(counts) == total, 'Classification count sum differs')
    require(len(set(gaps)) == len(gaps), 'Duplicate gap domains inflate unique cases')
    require(receipt.get('unique_cases') == total * len(rows), 'Unique case total differs')
    return receipt


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--root', type=Path, default=Path(__file__).resolve().parents[1])
    parser.add_argument('--evidence-dir', type=Path)
    args = parser.parse_args()
    receipt = verify(args.root, args.evidence_dir)
    print(f"Accepted exact furnace inputs: {receipt['unique_cases']:,} unique cases")

Single-Line Diagram (SLD) Sources

A configuration file covering components, metadata, buscoords and licence evidence, and uses data from UK Power Networks open data.

docs-configsld / sources.yaml · lines 1–60 of 60 · Not reached from any entry point (candidate for review)

Why it exists in the grid workflow
Domain stage sub33kv_design (repository name word 'sld'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. README: "Edit `sources.yaml` (JSON-compatible YAML), preserving immutable revisions and explicit licence evidence."
Inputs & outputs
In: JSON file components.json; JSON file metadata.json; CSV file buscoords.csv; JSON file licence-evidence.json.
What it achieves
The README says: Edit `sources.yaml` (JSON-compatible YAML), preserving immutable revisions and explicit licence evidence.
Why it matters
No other file in the estate was found to import it.
Application
sld · / · configuration
Uses
none found
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
sld@1205aa0d1f80d8e05a2cbb19f363939174b50002 sources.yaml:1-60 · blob 17ad8d5df6fac7bcb26efe726db81c22ca2574fd · GitHub at these lines
State
achieves: readme · context: readme_derived · stage: unknown · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
{
  "schema_version": "1.0",
  "format_note": "JSON-compatible YAML; parsed with Python standard-library json, no YAML dependency.",
  "sources": [
    {
      "id": "powsybl",
      "title": "PowSyBl ConvergenceLibrary",
      "kind": "component_library",
      "revision": "952186b5b34d1e4e472a04fb663b3654b54e3022",
      "licence": "MPL-2.0",
      "url": "https://github.com/powsybl/powsybl-diagram/tree/952186b5b34d1e4e472a04fb663b3654b54e3022/single-line-diagram/single-line-diagram-core/src/main/resources/ConvergenceLibrary",
      "base_url": "https://raw.githubusercontent.com/powsybl/powsybl-diagram/952186b5b34d1e4e472a04fb663b3654b54e3022/single-line-diagram/single-line-diagram-core/src/main/resources/ConvergenceLibrary/",
      "expected_components": 35,
      "expected_svgs": 37,
      "max_bytes": 2000000,
      "files": [
        {"name": "components.json", "url": "https://raw.githubusercontent.com/powsybl/powsybl-diagram/952186b5b34d1e4e472a04fb663b3654b54e3022/single-line-diagram/single-line-diagram-core/src/main/resources/ConvergenceLibrary/components.json"},
        {"name": "components.css", "url": "https://raw.githubusercontent.com/powsybl/powsybl-diagram/952186b5b34d1e4e472a04fb663b3654b54e3022/single-line-diagram/single-line-diagram-core/src/main/resources/ConvergenceLibrary/components.css"},
        {"name": "LICENSE", "url": "https://raw.githubusercontent.com/powsybl/powsybl-diagram/952186b5b34d1e4e472a04fb663b3654b54e3022/LICENSE"}
      ]
    },
    {
      "id": "send",
      "title": "Network Model for a Smart Energy Network Digital Twin",
      "kind": "network_model",
      "revision": "10.25405/data.ncl.21618342.v1",
      "licence": "CC-BY-4.0",
      "licence_url": "https://creativecommons.org/licenses/by/4.0/",
      "url": "https://data.ncl.ac.uk/articles/model/Network_Model_for_a_Smart_Energy_Network_Digital_Twin/21618342/1",
      "max_bytes": 1000000,
      "files": [
        {"name": "metadata.json", "url": "https://api.figshare.com/v2/articles/21618342/versions/1"},
        {"name": "send_network_dsse.zip", "url": "https://api.figshare.com/v2/file/download/38313285", "md5": "48d8483d91b68b8b6f6d43b829558368"}
      ],
      "zip_members": ["send_network_dsse/buscoords.csv", "send_network_dsse/generators_dsse.dss", "send_network_dsse/linecodes.dss", "send_network_dsse/lines_dsse.dss", "send_network_dsse/loads_dsse.dss", "send_network_dsse/master_dsse.dss", "send_network_dsse/xfmrs_dsse.dss"]
    },
    {
      "id": "decc",
      "title": "Illustrative example of a sample single line diagram",
      "kind": "illustrative_drawing",
      "revision": "2014-08-01",
      "licence": "OGL-UK-3.0",
      "licence_url": "https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/",
      "url": "https://www.gov.uk/government/publications/illustrative-example-of-a-sample-single-line-diagram",
      "max_bytes": 2000000,
      "files": [
        {"name": "licence-evidence.json", "transform": "decc-licence-evidence-v1", "url": "https://www.gov.uk/government/publications/illustrative-example-of-a-sample-single-line-diagram"},
        {"name": "line_diagram_illustrative_example.pdf", "url": "https://assets.publishing.service.gov.uk/media/5a7e2036ed915d74e6224444/line_diagram_illustrative_example.pdf"}
      ]
    }
  ],
  "references": [
    {"id": "enwl-lvns", "title": "ENWL / Manchester Low Voltage Network Solutions", "url": "https://www.enwl.co.uk/lvns", "status": "reference_only", "licence": "unresolved", "note": "25 real LV models dated 2015; public availability does not establish redistribution rights.", "rights_url": "https://www.enwl.co.uk/about-us/terms-and-conditions/"},
    {"id": "southampton-cad", "title": "Southampton CAD protocol", "url": "https://www.southampton.ac.uk/~assets/doc/estates-and-facilities/import/cadprotocol.pdf", "status": "reference_only", "licence": "unresolved", "note": "Revision B dated 2006-02-02, outside post-2012 drawing subset; current standards under review."},
    {"id": "uk-mvlv", "title": "Hybrid UK MV/LV models", "url": "https://github.com/deakinmt/uk-mvlv-models", "status": "reference_only", "licence": "unresolved", "note": "No repository licence established; upstream LVNS rights unresolved."},
    {"id": "ukpn", "title": "UKPN open-data catalogue", "url": "https://www.ukpowernetworks.co.uk/our-company/open-data-portal", "status": "reference_only", "licence": "per_dataset", "note": "Dataset-specific licence and registration requirements must be checked."},
    {"id": "catapult-dsi", "title": "Catapult Data Sharing Infrastructure", "url": "https://es.catapult.org.uk/project/data-sharing-infrastructure/", "status": "reference_only", "licence": "unresolved", "note": "Data infrastructure context, not a drawing corpus."},
    {"id": "catapult-guidance", "title": "Catapult Data Best Practice Guidance", "url": "https://es.catapult.org.uk/guide/data-best-practice-guidance/", "status": "reference_only", "licence": "unresolved", "note": "Metadata and rights guidance; no drawing assets acquired."}
  ]
}

Browser

A JavaScript module in the tests folder of Single-Line Diagram (SLD) that tests draft, bad and extra.

testsld / tests/browser.cjs · lines 1–47 of 47 · Entry point

What it does
It tests draft, bad and extra. Uses libraries playwright, node:assert/strict, node:fs/promises, node:path. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage sub33kv_design (repository name word 'sld'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: JSON file draft.json; JSON file bad.json; JSON file extra.json.
Downstream impact
Used directly by 1 file: Single-Line Diagram (SLD) Pages Workflow (sld).
What it achieves
Run in Linux CI against the packaged site.
Why it matters
Run by Single-Line Diagram (SLD) Pages Workflow.
Application
sld · tests · JavaScript module
Uses
playwright, node:assert/strict, node:fs/promises, node:path
Used by
run by Single-Line Diagram (SLD) Pages Workflow (workflow run)
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
sld@1205aa0d1f80d8e05a2cbb19f363939174b50002 tests/browser.cjs:1-47 · blob a9699a65806d524363e1eeeb323f4cdda4f2c76e · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unknown
/* Run in Linux CI against the packaged site. Do not launch local Windows Chromium. */
'use strict';
const {chromium}=require('playwright');
const assert=require('node:assert/strict');
const fs=require('node:fs/promises');
const path=require('node:path');
const base=process.env.BASE_URL||'http://127.0.0.1:8765';
(async()=>{
  if(process.platform==='win32'&&!process.env.ALLOW_LOCAL_BROWSER)throw Error('Use remote Linux CI; local Windows browser launch is disabled.');
  const browser=await chromium.launch({headless:true});
  const errors=[];
  try{
    const page=await browser.newPage({viewport:{width:1440,height:1000}});
    page.on('pageerror',e=>errors.push(e.message));page.on('console',m=>{if(m.type()==='error')errors.push(m.text());});
    const requests=[];page.on('request',request=>requests.push(request.url()));
    await page.goto(base);await page.waitForFunction(()=>document.querySelectorAll('.card').length===35);
    assert.match(await page.locator('.notice').innerText(),/disabled for production/);
    assert.equal(await page.locator('#furnace').count(),0);
    assert.doesNotMatch(await page.locator('body').innerText(),/furnace|GPU|photon|receipt/i);
    assert.equal(requests.some(url=>url.includes('/data/furnace/')),false,'The public UI must not fetch receipts');
    assert.equal(await page.getByRole('link',{name:'Source code',exact:true}).getAttribute('href'),'https://github.com/Ventusltd/sld');
    const palette=await page.evaluate(()=>{const body=getComputedStyle(document.body),link=getComputedStyle(document.querySelector('nav a')),button=getComputedStyle(document.querySelector('button'));return {background:body.backgroundColor,text:body.color,link:link.color,font:body.fontFamily,buttonFont:button.fontFamily,highlight:getComputedStyle(document.documentElement).getPropertyValue('--highli  … [line shortened here: 417 characters; full line on GitHub]
    assert.equal(palette.background,'rgb(0, 0, 0)');assert.equal(palette.text,'rgb(255, 255, 255)');assert.equal(palette.link,'rgb(102, 204, 255)');assert.equal(palette.highlight,'#00ffff');
    assert.equal(palette.font,'ui-monospace, SFMono-Regular, Consolas, monospace');assert.equal(palette.buttonFont,'ui-monospace, monospace');
    await page.locator('.card').first().locator('summary').click();assert.match(await page.locator('.card').first().innerText(),/MPL-2.0/);
    // Each generated SVG is fetched independently, including lazy images below the fold.
    for(const src of await page.locator('.preview').evaluateAll(imgs=>imgs.map(i=>i.getAttribute('src'))))assert.equal((await page.request.get(new URL(src,base+'/').href)).status(),200,src);
    await page.locator('#search').fill('breaker');assert.equal(await page.locator('.card').count(),1);
    await page.getByRole('button',{name:'+ Add to draft',exact:true}).click();
    await page.locator('#search').fill('not-a-part-xyz');assert.equal(await page.locator('.card').count(),0);assert.equal(await page.locator('#empty').isVisible(),true);
    await page.locator('#search').fill('two_windings');assert.equal(await page.locator('.card').count(),1);await page.getByRole('button',{name:'+ Add to draft',exact:true}).click();
    assert.equal(await page.locator('.instance').count(),2);
    const before=await page.locator('.instance.selected').getAttribute('transform');await page.locator('#move-right').click();assert.notEqual(await page.locator('.instance.selected').getAttribute('transform'),before);
    await page.locator('#connect').click();await page.locator('.instance').nth(0).click();await page.locator('.instance').nth(1).click();assert.equal(await page.locator('#canvas>line').count(),1);
    const exported=page.waitForEvent('download');await page.locator('#export').click();const file=await exported;const json=JSON.parse(await fs.readFile(await file.path(),'utf8'));assert.equal(json.instances.length,2);assert.equal(json.connections[0].kind,'illustrative-centre-link');
    await page.locator('#clear').click();assert.equal(await page.locator('.instance').count(),0);
    await page.locator('#import').setInputFiles({name:'draft.json',mimeType:'application/json',buffer:Buffer.from(JSON.stringify(json))});await page.waitForFunction(()=>document.querySelectorAll('.instance').length===2);
    const invalid={...json,instances:[{...json.instances[0],component_id:'<img src=x onerror=alert(1)>'}]};await page.locator('#import').setInputFiles({name:'bad.json',mimeType:'application/json',buffer:Buffer.from(JSON.stringify(invalid))});await page.waitForFunction(()=>document.getElementById('status').textContent.startsWith('Import rejected'));assert.equal(await page.locator('.instance').count  … [line shortened here: 406 characters; full line on GitHub]
    const polluted={...json,html:'<script>window.injected=true</script>'};await page.locator('#import').setInputFiles({name:'extra.json',mimeType:'application/json',buffer:Buffer.from(JSON.stringify(polluted))});await page.waitForFunction(()=>document.getElementById('status').textContent.startsWith('Imported'));assert.equal(await page.evaluate(()=>window.injected),undefined);
    const svgDownload=page.waitForEvent('download');await page.locator('#export-svg').click();const svgText=await fs.readFile(await (await svgDownload).path(),'utf8');assert.match(svgText,/EDUCATIONAL DRAFT/);assert.match(svgText,/data:image\/svg\+xml;base64,/);assert.doesNotMatch(svgText,/href="assets\//);
    await page.locator('.instance').first().click();await page.locator('#delete').click();assert.equal(await page.locator('.instance').count(),1);assert.equal(await page.locator('#canvas>line').count(),0);
    await page.locator('#search').fill('');await page.evaluate(()=>scrollTo(0,0));
    await fs.mkdir('artifacts',{recursive:true});await page.screenshot({path:path.join('artifacts','desktop.png'),fullPage:true});
    await page.setViewportSize({width:390,height:844});await page.locator('#search').fill('ground');assert.equal(await page.locator('.card').count(),2);assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true,'mobile page must not overflow horizontally');await page.locator('#search').fill('');await page.evaluate(()=>scrollTo(0,0));await page.screenshot({path:path  … [line shortened here: 448 characters; full line on GitHub]
    assert.deepEqual(errors,[]);console.log('PASS: 35 previews, provenance, search, draft edits, links, safe import/export, standalone SVG, desktop/mobile and console.');
  }finally{await browser.close();}
})().catch(e=>{console.error(e);process.exitCode=1;});