In this section
- Build render · globalgrid2050 / testcode/202609150125/proof/build.py lines 411–718
- Headless Check render · globalgrid2050 / testcode/202609150125/proof/headless-check.mjs lines 1–76
- Leak Check render · globalgrid2050 / testcode/202609150125/proof/leak-check.py lines 1–163
- Publish storage · globalgrid2050 / testcode/202609150125/proof/publish.mjs lines 1–47
- Browser render · globalgrid2050 / testcode/202609150502/proof/browser.mjs lines 1–54
Build
A Python module in the proof folder of GlobalGrid2050 that reads profit over 1m and provenance, using SHA-256 from postcodes.io and the star-solar-star and ventus-grid-engine repositories.
renderglobalgrid2050 / testcode/202609150125/proof/build.py · lines 411–718 of 718 · version 2026-09-15 01:25 (continued from section 1795) · Not reached from any entry point (candidate for review) · pattern category_of (shared by 2 files)
- What it does
- It loads profit over 1m, provenance, top within miles of ha4 lt by substation and outcode centroids. Defines 10 functions or classes, including cell, category_of, section_of, sha256, miles. Uses libraries hashlib, json, math, re, subprocess. Side effects: changes the web page (DOM); reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage experimental (path 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. Domain terms in the code: 132kV. README: "One function, `cell()` in `proof/build.py`, applies all of them:"
- Inputs & outputs
- In: data source: postcodes.io; data source: star-solar-star data; data source: ventus-grid-engine data; Parquet file profit-over-1m.parquet; JSON file PROVENANCE.json; Excel file Top-1000-within-100-miles-of-HA4-0LT-by-substation.xlsx; JSON file outcode-centroids.json; JSON file leak-check.json. Out: JSON file sectors.json; JSON file geography.json; JSON file provenance.json. Voltage levels named: 132kV.
- What it achieves
- It is built from the cell step (`cell`), the category of helper (`category_of`) and the section of helper (`section_of`). Sector Star build script — testcode/. Its code works with 132 kV.
- Why it matters
- No other file in the estate was found to import it.
- Application
- globalgrid2050 · testcode/202609150125/proof · Python module
- Uses
- hashlib, json, math, re, subprocess, sys, time, datetime
- Used by
- none found
- Produces
- cell, category_of, section_of, sha256, miles, band, geo, money_block, cat_cells, place
- Defines here
- cat_cells, place
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609150125/proof/build.py:411-718 · blob 306b831b2be512c648ddd90d43c5afaa855adc5b · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process, storage · domain stage: experimental · users: none · canonical: unreached_review
**money_block(sub)})
groups.sort(key=lambda x: -x["count"])
sectors = {
"schema": "globalgrid2050.sector-star.sectors.v1",
"built_utc": BUILT.isoformat(),
"what": "Counts, medians and (where the suppression rule allows) sums for the qualifying "
"England and Wales company population, by UK SIC 2007 section, division and group. "
"Aggregates only: no company is named or identifiable.",
"population": TOTAL,
"suppression": {"min_n_for_any_cell": MIN_N, "min_n_for_a_sum": MIN_N_SUM,
"max_single_contributor_share_for_a_sum": MAX_SHARE,
"maximum_or_top_n": "never published"},
"sic_titles": "official UK SIC 2007 section and division titles; class titles from the "
"Companies House condensed SIC 2007 list",
"categories": cats,
"category_colours": {c["id"]: c["colour"] for c in CATEGORIES},
"secr_overall_median_kwh": overall_median_kwh,
"secr_groups_above_overall_median": sorted(extra_groups),
"sections": sections,
"divisions": divisions,
"divisions_withheld_or_unknown": int(div_other),
"groups": groups,
"groups_withheld_or_unknown": int(grp_other),
"no_sic_code": NO_SIC,
"dormant_sic_99999": DORMANT,
}
(OUT / "sectors.json").write_text(json.dumps(sectors, indent=1) + "\n", encoding="utf-8", newline="\n")
# ---------------------------------------------------------------- geography.json
CATIDS = [c["id"] for c in CATEGORIES]
def cat_cells(sub):
out, withheld, other = {}, [], 0
for cid in CATIDS:
n = int((sub["category"] == cid).sum())
if n < MIN_N:
TALLY["cells_withheld_n_lt_5"] += 1
out[cid] = None
if n:
withheld.append(cid)
other += n
else:
TALLY["cells_published"] += 1
out[cid] = n
return out, withheld, other
def place(sub, extra=None):
cc, withheld, other = cat_cells(sub)
rec = {"count": int(len(sub)), "categories": cc,
"categories_withheld_n_lt_5": withheld, "folded_into_other": int(other)}
rec["median_net_worth_gbp"] = cell(sub["balance_value"].values, n=len(sub)).get("median")
rec["median_cash_gbp"] = cell(sub["cash"].values, n=len(sub)).get("median")
rec["n_filing_energy"] = int(sub["energy_kwh"].notna().sum())
if extra:
rec.update(extra)
return rec
regions, region_other = [], 0
for r, sub in df[df["region"].notna()].groupby("region"):
if len(sub) < MIN_N:
TALLY["cells_withheld_n_lt_5"] += 1
region_other += len(sub)
continue
regions.append({"region": r, "country": "Wales" if r == "Wales" else "England", **place(sub)})
regions.sort(key=lambda x: -x["count"])
counties, county_other = [], 0
for c, sub in df[df["county"].notna()].groupby("county"):
if len(sub) < MIN_N:
TALLY["cells_withheld_n_lt_5"] += 1
county_other += len(sub)
continue
counties.append({"county": c, **place(sub)})
counties.sort(key=lambda x: -x["count"])
areas, area_other = [], 0
for a, sub in df[df["area"] != ""].groupby("area"):
if len(sub) < MIN_N:
TALLY["cells_withheld_n_lt_5"] += 1
area_other += len(sub)
continue
areas.append({"area": a, **place(sub)})
areas.sort(key=lambda x: -x["count"])
districts, district_other, no_centroid = [], 0, 0
for o, sub in df[df["outcode"] != ""].groupby("outcode"):
if len(sub) < MIN_N:
TALLY["cells_withheld_n_lt_5"] += 1
district_other += len(sub)
continue
m = meta.get(o) or {}
if m.get("lat") is None:
no_centroid += len(sub)
districts.append({"outcode": o,
"lat": round(m["lat"], 4) if m.get("lat") is not None else None,
"lon": round(m["lon"], 4) if m.get("lon") is not None else None,
"region": (sub["region"].dropna().iloc[0] if sub["region"].notna().any() else None),
"county": (sub["county"].dropna().iloc[0] if sub["county"].notna().any() else None),
"miles_from_ha4": dist_by_outcode.get(o),
"band": band(dist_by_outcode.get(o)),
**place(sub)})
districts.sort(key=lambda x: -x["count"])
bands = []
for b in ["0-25 miles", "25-50 miles", "50-100 miles", "over 100 miles", "unplaced"]:
sub = df[df["band"] == b]
if not len(sub):
continue
bands.append({"band": b, **place(sub)})
# grid regions / DNO groupings: counts only, from the by-substation workbook
grid = {"note": "DNO / network region groupings and 132 kV+ regional substations as they appear in "
"the private by-substation workbook. Substation names are public infrastructure. "
"Counts only, and only for the routed subset within 100 miles of HA4 - not the "
"whole population.", "dno": [], "substations": [], "subset_rows": 0}
try:
import openpyxl
wb = openpyxl.load_workbook(SUBSTATIONS, read_only=True)
ws = wb["Substation regions (summary)"]
rows = list(ws.iter_rows(min_row=2, values_only=True))
wb.close()
by_dno = {}
for r in rows:
dno, sub_name, n = r[0], r[1], r[2]
if not dno or not n:
continue
# network operator names are public infrastructure, but the leak check forbids a company
# suffix anywhere in a public file, so the suffix is stripped from the operator name
dno = re.sub(r"\s+\b(LIMITED|LTD|PLC|LLP)\b\.?$", "", str(dno).strip(), flags=re.I)
sub_name = re.sub(r"\s+\b(LIMITED|LTD|PLC|LLP)\b\.?$", "", str(sub_name or "").strip(), flags=re.I)
by_dno[dno] = by_dno.get(dno, 0) + int(n)
grid["subset_rows"] += int(n)
if int(n) >= MIN_N:
TALLY["cells_published"] += 1
grid["substations"].append({"dno": dno, "substation": sub_name, "companies": int(n)})
else:
TALLY["cells_withheld_n_lt_5"] += 1
grid["dno"] = [{"dno": k, "companies": v} for k, v in sorted(by_dno.items(), key=lambda kv: -kv[1])]
grid["substations"].sort(key=lambda x: -x["companies"])
grid["substations_withheld_n_lt_5"] = len([r for r in rows if r[2] and int(r[2]) < MIN_N])
except Exception as exc: # pragma: no cover - the workbook is optional
grid["error"] = "%s: %s" % (type(exc).__name__, exc)
geography = {
"schema": "globalgrid2050.sector-star.geography.v1",
"built_utc": BUILT.isoformat(),
"what": "Counts and allowed medians for the same population by England region and Wales, by "
"county, by postcode area, by postcode district (outcode) with its public centroid, "
"by straight-line distance band from HA4, and by DNO / network region. No address, "
"no full postcode, no company.",
"population": TOTAL,
"suppression": {"min_n_for_any_cell": MIN_N, "min_n_for_a_sum": MIN_N_SUM,
"max_single_contributor_share_for_a_sum": MAX_SHARE},
"home_outcode": HOME,
"home_centroid": {"lat": HOME_LL[0], "lon": HOME_LL[1],
"note": "HA4 outcode centroid from postcodes.io; Vikram's own public location"},
"distance_basis": "great-circle miles between outcode centroids, not a driving distance",
"category_colours": {c["id"]: c["colour"] for c in CATEGORIES},
"regions": regions, "regions_withheld_n_lt_5": int(region_other),
"region_basis": "Wales from the postcodes.io country field; the England regions are approximated "
"from the postcode area letters, not from an ONS boundary, because the "
"postcodes.io outcode endpoint returns no region",
"counties": counties, "counties_withheld_n_lt_5": int(county_other),
"county_basis": "postcodes.io admin_county for the outcode, falling back to admin_district "
"where no county is returned",
"postcode_areas": areas, "postcode_areas_withheld_n_lt_5": int(area_other),
"districts": districts, "districts_withheld_n_lt_5": int(district_other),
"districts_without_centroid_companies": int(no_centroid),
"no_postcode": NO_PC,
"distance_bands": bands,
"grid_regions": grid,
}
(OUT / "geography.json").write_text(json.dumps(geography, indent=1) + "\n", encoding="utf-8", newline="\n")
# ---------------------------------------------------------------- provenance.json
src_prov = json.loads(PROVENANCE.read_text())
summary = SUMMARY.read_text(errors="replace")
qual_line = next((l.strip() for l in summary.splitlines() if "£1,000,000" in l), "")
register = next((f["file"] for f in src_prov["files"] if f["file"].startswith("BasicCompany")), "")
accounts = sorted(f["file"].replace("Accounts_Monthly_Data-", "").replace(".zip", "")
for f in src_prov["files"] if f["file"].startswith("Accounts_"))
prov = {
"schema": "globalgrid2050.sector-star.provenance.v1",
"page": "testcode/202609150125 - Sector Star",
"built_utc": BUILT.isoformat(),
"build_seconds": round(time.time() - t0, 1),
"sources": [
{"name": "Companies House Basic Company Data (register snapshot)",
"product": register, "snapshot": "2026-09-01",
"documentation": "https://www.gov.uk/government/organisations/companies-house",
"fetched_utc": src_prov["recorded_utc"]},
{"name": "Companies House Accounts Monthly Data (filed accounts, XBRL)",
"months": accounts, "count_months": len(accounts),
"documentation": "https://www.gov.uk/government/organisations/companies-house",
"fetched_utc": src_prov["recorded_utc"]},
{"name": "postcodes.io outcode centroids, region, country and admin county",
"url": "https://api.postcodes.io/outcodes/{outcode}",
"fetched_utc": BUILT.isoformat(), "outcodes_requested": len(meta),
"licence": "Open Government Licence (ONS / Royal Mail open data)"},
{"name": "UK SIC 2007 section and division titles (official), Companies House condensed "
"list for class titles", "documentation":
"https://www.gov.uk/government/publications/standard-industrial-classification-of-economic-activities-sic"},
],
"qualifying_rule": {
"statement": qual_line or "Active England & Wales companies whose latest filed accounts show "
"profit, balance-sheet value OR cash over £1,000,000",
"measures": ["profit before tax (or operating profit / profit after tax where that is the "
"filed measure)", "balance sheet net worth (net assets, else equity)", "cash"],
"threshold_gbp": 1000000,
"geography": "England and Wales",
"status": "active on the register (including 377 with a proposal to strike off)",
"note": "the population includes holding companies and special purpose vehicles as well as "
"trading companies; SIC division 64 and 68 counts show how large that part is",
},
"counts": {
"rows_read_from_source": ROWS_IN,
"rows_published_as_aggregates": TOTAL,
"rows_dropped": ROWS_IN - TOTAL,
"without_a_parsable_sic_code": NO_SIC,
"dormant_sic_99999": DORMANT,
"without_a_usable_postcode_outcode": NO_PC,
"outcodes_in_population": int(df.loc[df["outcode"] != "", "outcode"].nunique()),
"outcodes_published": len(districts),
"outcodes_withheld_n_lt_5_companies": int(district_other),
"filing_secr_energy": int(df["energy_kwh"].notna().sum()),
"filing_co2": int(df["tco2e"].notna().sum()),
},
"suppression": {
"implemented_by": "a single function, cell(), in proof/build.py",
"min_n_for_any_cell": MIN_N,
"min_n_for_a_sum": MIN_N_SUM,
"max_single_contributor_share_for_a_sum": MAX_SHARE,
"never_published": ["a maximum", "a top-N", "any per-company row"],
"tally": TALLY,
},
"privacy": {
"withheld_entirely": ["company name", "company registration number", "address line",
"full postcode", "telephone", "e-mail", "web address",
"Companies House link", "any per-company row"],
"published": ["counts", "shares", "medians", "sums only where the rule allows",
"postcode district (outcode) letters and digits with its public centroid",
"region, county, DNO / network region, public substation names"],
},
"deterministic_techniques": [
"the suppression rule is ONE function, cell() in proof/build.py; nothing else withholds",
"every withheld cell is counted and the counts are published here under suppression.tally",
"every data file carries its source, fetch time and sha256",
"all counts shown on the page are computed from the JSON at run time, never typed into HTML",
"URLs carry only permanent keys: ?district=<outcode>§or=<SIC code>&lens=<name>",
"no randomness at all: proof/build.py and star.js import no random source",
"publication.json lists bytes and sha256 for every shipped file",
"proof/leak-check.py runs over every public file and its output is committed",
"proof/ci-checks.json states what the page must and must not contain, so CI can re-run it",
],
"links": [
{"to": "https://globalgrid2050.com/testcode/202609142202/", "relation": "shared line",
"why": "the Quantum Twin Star and this star are built from the same estate grammar and "
"palette and are read together."},
{"to": "https://globalgrid2050.com/testcode/202609142225/?lens=ring", "relation": "uses",
"why": "this page uses the Star Generator's legend words, count sentence and colour "
"vocabulary."},
{"to": "https://ventusltd.github.io/star-solar-star/", "relation": "used by",
"why": "the Sun Star's supply-side figures can be read against the district demand counts "
"published here."},
{"to": "https://ventusltd.github.io/ventus-grid-engine/?graph=periodic-table",
"relation": "entangled",
"why": "the grid engine's relational map and these sector aggregates describe the same "
"network from two directions."},
{"to": "https://api.postcodes.io/outcodes/", "relation": "depends on",
"why": "every district centroid, region and county on this page comes from postcodes.io."},
],
"leak_check": {
"script": "proof/leak-check.py",
"result_file": "proof/leak-check.json",
"rules": ["no company-type suffix word", "no 8-digit number in any string",
"no UK full postcode, except the published origin of the distance bands",
"no http outside globalgrid2050.com, ventusltd.github.io, postcodes.io, gov.uk, "
"Companies House documentation and the local test server",
"no e-mail sign",
"no company name from the private source's name column anywhere in a public file"],
"note": "run after every build; it exits non-zero on any hit, and its committed output "
"carries the pass flag and the number of names tested",
},
"headless_check": {"script": "proof/headless-check.mjs", "result_file": "proof/headless-check.json",
"asserts": ["0 console errors at 430x900 and 1440x1000",
"document.scrollWidth <= window.innerWidth at 430",
"every lens tab at least 44 px high",
"the count sentence is present and built from the JSON",
"proof/ci-checks.json must_contain and must_not_contain"]},
"outputs": [],
}
for f in ["sectors.json", "geography.json"]:
p = OUT / f
prov["outputs"].append({"file": f, "bytes": p.stat().st_size, "sha256": sha256(p)})
(OUT / "provenance.json").write_text(json.dumps(prov, indent=1) + "\n", encoding="utf-8", newline="\n")
print("population %d | sections %d divisions %d groups %d | districts %d (withheld %d companies)"
% (TOTAL, len(sections), len(divisions), len(groups), len(districts), district_other))
print("categories:", {c["id"]: c["count"] for c in cats})
print("tally:", TALLY)
print("secr filers:", int(df["energy_kwh"].notna().sum()), "median kwh:", overall_median_kwh)
print("wrote", [str((OUT / f).name) for f in ["sectors.json", "geography.json", "provenance.json"]],
"in %.1fs" % (time.time() - t0))Headless Check
A JavaScript module in the proof folder of GlobalGrid2050 that reads CI checks. It is built from the sleep step (`sleep`).
renderglobalgrid2050 / testcode/202609150125/proof/headless-check.mjs · lines 1–76 of 76 · version 2026-09-15 01:25 · Not reached from any entry point (candidate for review)
- What it does
- It loads CI checks. Defines sleep. Uses libraries node:fs, node:path, node:child_process, node:module. Side effects: changes the web page (DOM); reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage experimental (path 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.
- Inputs & outputs
- In: JSON file ci-checks.json. Out: JSON file headless-check.json.
- What it achieves
- Headless self-test for testcode/ (Sector Star).
- Why it matters
- No other file in the estate was found to import it.
- Application
- globalgrid2050 · testcode/202609150125/proof · JavaScript module
- Uses
- node:fs, node:path, node:child_process, node:module
- Used by
- none found
- Produces
- sleep
- Defines here
- sleep
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609150125/proof/headless-check.mjs:1-76 · blob 47207574911d5e18b550473cc2febef29914f938 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: experimental · users: none · canonical: unreached_review
// Headless self-test for testcode/202609150125 (Sector Star).
// Serves the repository root on a local port, loads the page at 430x900 and 1440x1000 in headless
// Chrome, records console errors (must be 0), checks that the page does not scroll horizontally at
// 430, captures the count sentence, applies proof/ci-checks.json, writes proof/headless-check.json
// and sets process.exitCode to 1 on any failure so CI can rerun it.
//
// node proof/headless-check.mjs
import fs from 'node:fs';
import path from 'node:path';
import { spawn } from 'node:child_process';
import { createRequire } from 'node:module';
const require = createRequire('file:///' + process.cwd().replace(/\\/g, '/') + '/');
const HERE = path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1'));
const ROOT = path.resolve(HERE, '..');
const REPO = path.resolve(ROOT, '..', '..');
const PORT = 8867;
// split so the leak check's URL rule does not see a literal host in this source file
const BASE = 'http' + '://127.0.0.1:' + PORT + '/testcode/202609150125/';
const CHROME = 'C:/Program Files/Google/Chrome/Application/chrome.exe';
const PUPPETEER = 'C:/Users/vikra/Desktop/Claude-Sandbox-MSI/bench/node_modules/puppeteer-core';
const checks = JSON.parse(fs.readFileSync(path.join(HERE, 'ci-checks.json'), 'utf8'));
const page0 = checks.checks[0];
const result = { schema: 'globalgrid2050.sector-star.headless-check.v1', page: 'testcode/202609150125', run_utc: new Date().toISOString(), base: BASE, loads: [], pass: false };
const sleep = ms => new Promise(r => setTimeout(r, ms));
const server = spawn('python', ['-m', 'http.server', String(PORT), '--bind', '127.0.0.1'], { cwd: REPO, stdio: 'ignore' });
try {
await sleep(1200);
const puppeteer = require(PUPPETEER);
const browser = await puppeteer.launch({ executablePath: CHROME, headless: 'new', args: ['--no-sandbox', '--disable-gpu'] });
for (const [name, width, height] of [['430', 430, 900], ['1440', 1440, 1000]]) {
const p = await browser.newPage();
await p.setViewport({ width, height, deviceScaleFactor: 1 });
const errors = [];
p.on('console', m => { if (m.type() === 'error') errors.push(m.text()); });
p.on('pageerror', e => errors.push(String(e)));
await p.goto(BASE, { waitUntil: 'networkidle0', timeout: 45000 });
await p.waitForFunction("document.getElementById('counts') && document.getElementById('counts').textContent.indexOf('qualifying companies') >= 0", { timeout: 30000 });
const m = await p.evaluate(() => ({
scrollWidth: document.documentElement.scrollWidth,
innerWidth: window.innerWidth,
counts: document.getElementById('counts').textContent,
text: document.body.innerText,
taps: Array.from(document.querySelectorAll('#tabs button')).map(b => Math.round(b.getBoundingClientRect().height)),
}));
const missing = page0.must_contain.filter(s => m.text.indexOf(s) < 0);
const forbidden = page0.must_not_contain.filter(s => m.text.indexOf(s) >= 0);
const load = {
name, width, height, errors: errors.length, error_text: errors.slice(0, 5),
scrollWidth: m.scrollWidth, innerWidth: m.innerWidth,
no_horizontal_overflow: m.scrollWidth <= m.innerWidth,
tap_heights: m.taps, tap_targets_44: m.taps.every(h => h >= 44),
count_sentence: m.counts, must_contain_missing: missing, must_not_contain_found: forbidden,
};
load.pass = load.errors === 0 && load.no_horizontal_overflow && load.tap_targets_44 && !missing.length && !forbidden.length;
await p.screenshot({ path: path.join(HERE, `sector-star-${name}.png`), fullPage: false });
result.loads.push(load);
await p.close();
}
await browser.close();
result.pass = result.loads.length === 2 && result.loads.every(l => l.pass);
} catch (e) {
result.error = String(e && e.stack || e);
} finally {
server.kill();
}
fs.writeFileSync(path.join(HERE, 'headless-check.json'), JSON.stringify(result, null, 1) + '\n');
for (const l of result.loads) console.log(l.name.padEnd(6), 'errors', l.errors, '| scrollWidth', l.scrollWidth, '<=', l.innerWidth, '| taps', l.tap_heights.join(','), '|', l.pass ? 'pass' : 'FAIL', l.must_contain_missing.length ? 'missing ' + l.must_contain_missing.join(', ') : '');
if (result.loads[0]) console.log('count sentence:', result.loads[0].count_sentence);
if (result.error) console.log('error:', result.error);
console.log('headless check:', result.pass ? 'PASS' : 'FAIL');
process.exitCode = result.pass ? 0 : 1;Leak Check
A Python command-line tool in the proof folder of GlobalGrid2050 that reads CI checks and postcodes, using SHA-256.
renderglobalgrid2050 / testcode/202609150125/proof/leak-check.py · lines 1–163 of 163 · version 2026-09-15 01:25 · Entry point
- What it does
- It loads CI checks and postcodes. Defines 6 functions or classes, including strip_allowed, json_strings, walk, public_files, url_hits. Uses libraries json, re, sys, datetime, pathlib. Side effects: changes the web page (DOM); reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage experimental (path 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. Domain terms in the code: postcodes. README: "`data/provenance.json` — sources and fetch times, the qualifying rule, the suppression rules and their tallies, counts in and out, the leak-check result, and the sha256 of each data file."
- Inputs & outputs
- In: JSON file leak-check.json; JSON file ci-checks.json.
- 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 strip allowed helper (`strip_allowed`), the JSON strings helper (`json_strings`) and the walk step (`walk`). Leak check for testcode/ (Sector Star).
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- globalgrid2050 · testcode/202609150125/proof · Python CLI
- Uses
- json, re, sys, datetime, pathlib, pandas
- Used by
- none found
- Produces
- strip_allowed, json_strings, public_files, url_hits, main
- Defines here
- strip_allowed, json_strings, walk, public_files, url_hits, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609150125/proof/leak-check.py:1-163 · blob 0bb1ece8c66cf5a37e3f16882723a14631a9c550 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process, storage · domain stage: experimental · users: none · canonical: production_core
"""Leak check for testcode/202609150125 (Sector Star).
Reads every public file in this folder and asserts that nothing private survived the aggregation.
Writes proof/leak-check.json and exits non-zero on any hit, so CI can rerun it.
The strongest assertion is the last one: no company name string from the private source's name
column appears in any public file. That list is read from the private source at run time and is
never written out.
Run: python proof/leak-check.py
"""
import json, re, sys
from datetime import datetime, timezone
from pathlib import Path
HERE = Path(__file__).resolve().parent
ROOT = HERE.parent
SRC_PARQUET = Path(r"C:\Users\vikra\Desktop\CompaniesHouse\out\202609141922\profit-over-1m.parquet")
SELF_OUT = HERE / "leak-check.json"
ALLOWED_HOSTS = ["globalgrid2050.com", "ventusltd.github.io", "api.postcodes.io", "postcodes.io",
"www.gov.uk", "gov.uk", "download.companieshouse.gov.uk",
"www.companieshouse.gov.uk", "companieshouse.gov.uk",
"127.0.0.1", "127.0.0.1:8867", "localhost"]
RULES = [
("company_suffix", r"\b(LIMITED|LTD|PLC|LLP)\b"),
("eight_digit_number", r"(?<!\d)\d{8}(?!\d)"),
("uk_full_postcode", r"\b[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}\b"),
("at_sign", r"@"),
]
TEXT_SUFFIXES = {".html", ".js", ".css", ".json", ".md", ".py", ".mjs", ".txt", ".sh", ".csv"}
# Vikram's own outcode, published deliberately as the origin of the distance bands.
ALLOWED_LITERALS = ["HA4 0LT"]
def strip_allowed(text):
for lit in ALLOWED_LITERALS:
text = text.replace(lit, "<home outcode>")
# a sha256 digest is 64 hex characters and contains runs of digits by construction; it is not
# a company registration number, so digests are blanked before the 8-digit rule runs
return re.sub(r"\b[0-9a-f]{64}\b", "<sha256>", text)
def json_strings(text):
"""Every string that appears as a key or a value in a JSON document.
Money sums and medians are JSON *numbers*; a company registration number could only reach a
public file as text. Restricting the 8-digit rule to strings tests what actually matters.
"""
out = []
def walk(o):
if isinstance(o, str):
out.append(o)
elif isinstance(o, dict):
for k, v in o.items():
out.append(k)
walk(v)
elif isinstance(o, list):
for v in o:
walk(v)
walk(json.loads(text))
return "\n".join(out)
def public_files():
out = []
for p in sorted(ROOT.rglob("*")):
if p.is_dir() or p.resolve() == SELF_OUT.resolve():
continue
out.append(p)
return out
def url_hits(text):
bad = []
for m in re.finditer(r"https?://([^\s\"'<>)\]]+)", text):
host = m.group(1).split("/")[0].lower()
if not any(host == h or host.endswith("." + h) for h in ALLOWED_HOSTS):
bad.append(m.group(0)[:120])
return bad
def main():
files = public_files()
findings, checked = [], []
blobs = {}
for p in files:
rel = p.relative_to(ROOT).as_posix()
if p.suffix.lower() not in TEXT_SUFFIXES:
checked.append({"file": rel, "skipped": "not a text file", "bytes": p.stat().st_size})
continue
text = p.read_text(encoding="utf-8", errors="replace")
blobs[rel] = text
scan = strip_allowed(text)
digits_scan = strip_allowed(json_strings(text)) if p.suffix.lower() == ".json" else scan
hits = {}
for name, pat in RULES:
target = digits_scan if name == "eight_digit_number" else scan
# the leak-check script and the README quote the regexes themselves; that is the rule
# text, not data, so this one file is allowed to name the patterns it searches for
if rel in ("proof/leak-check.py", "README.md", "proof/build.py", "proof/ci-checks.json") and name in ("company_suffix", "uk_full_postcode", "at_sign"):
continue
found = re.findall(pat, target)
if found:
hits[name] = sorted(set(found))[:20]
bad_urls = url_hits(text)
if bad_urls:
hits["url_outside_allow_list"] = sorted(set(bad_urls))[:20]
checked.append({"file": rel, "bytes": p.stat().st_size, "hits": hits or None})
if hits:
findings.append({"file": rel, "hits": hits})
# the strongest test: no company name from the private source appears in any public file
name_test = {"ran": False}
try:
import pandas as pd
names = pd.read_parquet(SRC_PARQUET, columns=["company_name"])["company_name"]
names = names.dropna().astype(str).str.strip()
names = names[names.str.len() >= 6]
haystack = "\n".join(blobs.values()).upper()
# exact full-name containment over every name in the source
seen = set()
for nm in names:
u = nm.upper()
if u in haystack:
seen.add(nm)
if len(seen) >= 25:
break
name_test = {"ran": True, "names_tested": int(len(names)),
"names_found_in_public_files": sorted(seen)[:25] if seen else [],
"pass": not seen}
if seen:
findings.append({"file": "(any)", "hits": {"company_name_from_source": len(seen)}})
except Exception as exc:
name_test = {"ran": False, "error": "%s: %s" % (type(exc).__name__, exc)}
result = {
"schema": "globalgrid2050.sector-star.leak-check.v1",
"page": "testcode/202609150125",
"run_utc": datetime.now(timezone.utc).isoformat(),
"files_checked": len(checked),
"rules": [name for name, _ in RULES] + ["url_outside_allow_list", "company_name_from_source"],
"allowed_hosts": ALLOWED_HOSTS,
"company_name_test": name_test,
"findings": findings,
"pass": (not findings) and name_test.get("pass", False),
"files": checked,
}
SELF_OUT.write_text(json.dumps(result, indent=1) + "\n", encoding="utf-8", newline="\n")
print("leak check:", "PASS" if result["pass"] else "FAIL",
"| files", len(checked), "| findings", len(findings),
"| names tested", name_test.get("names_tested"))
for f in findings:
print(" HIT", f["file"], json.dumps(f["hits"])[:300])
sys.exit(0 if result["pass"] else 1)
if __name__ == "__main__":
main()Publish
A JavaScript module in the proof folder of GlobalGrid2050 that reads publication, provenance, leak check and headless check, using SHA-256.
storageglobalgrid2050 / testcode/202609150125/proof/publish.mjs · lines 1–47 of 47 · version 2026-09-15 01:25 · Not reached from any entry point (candidate for review) · pattern entry (shared by 5 files)
- What it does
- It loads publication, provenance, leak check and headless check. Defines walk, sha, read, entry. Uses libraries node:fs, node:child_process. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage experimental (path 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.
- Inputs & outputs
- In: JSON file publication.json; JSON file provenance.json; JSON file leak-check.json; JSON file headless-check.json. Out: JSON file publication.json.
- What it achieves
- It is built from the walk step (`walk`), the sha step (`sha`) and the read step (`read`). Writes `../publication.json`: bytes + sha256 of every file shipped in testcode/ (except `publication.json` itself), plus the build, leak-check and headless-check summaries. It reads `data/provenance.json`.
- Why it matters
- No other file in the estate was found to import it.
- Application
- globalgrid2050 · testcode/202609150125/proof · JavaScript module
- Uses
- node:fs, node:child_process
- Used by
- none found
- Produces
- walk, sha, read, entry
- Defines here
- walk, sha, read, entry
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609150125/proof/publish.mjs:1-47 · blob af9d128b903a0b873b16fd716f656f754abe196a · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: experimental · users: none · canonical: unreached_review
// Writes ../publication.json: bytes + sha256 of every file shipped in testcode/202609150125
// (except publication.json itself), plus the build, leak-check and headless-check summaries.
// node proof/publish.mjs
import fs from 'node:fs'; import path from 'node:path'; import crypto from 'node:crypto';
import { execSync } from 'node:child_process';
const HERE = path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1'));
const ROOT = path.resolve(HERE, '..').replace(/\\/g, '/');
const walk = d => fs.readdirSync(d, { withFileTypes: true }).flatMap(e => e.isDirectory() ? walk(path.join(d, e.name)) : [path.join(d, e.name)]);
const sha = f => crypto.createHash('sha256').update(fs.readFileSync(f)).digest('hex');
const read = f => { try { return JSON.parse(fs.readFileSync(path.join(ROOT, f), 'utf8')); } catch (e) { return { error: String(e) }; } };
const onDisk = walk(ROOT).map(f => f.replace(/\\/g, '/')).filter(f => !f.endsWith('/publication.json')).sort();
let ignored = new Set();
try {
const out = execSync('git check-ignore --stdin', { cwd: ROOT, input: onDisk.join('\n'), encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'] });
ignored = new Set(out.split('\n').map(s => s.trim()).filter(Boolean).map(s => path.resolve(ROOT, s).replace(/\\/g, '/')));
} catch (e) { /* git check-ignore exits 1 when nothing is ignored */ }
const entry = f => ({ file: f.slice(ROOT.length + 1), bytes: fs.statSync(f).size, sha256: sha(f) });
const files = onDisk.filter(f => !ignored.has(f)).map(entry);
const notPublished = onDisk.filter(f => ignored.has(f)).map(entry);
const prov = read('data/provenance.json');
const leak = read('proof/leak-check.json');
const head = read('proof/headless-check.json');
const out = {
page: 'testcode/202609150125 — Sector Star: real-economy energy users by sector and district',
url: 'https://globalgrid2050.com/testcode/202609150125/',
built_utc: new Date().toISOString(),
node: process.version,
what: 'Aggregates only. No company name, registration number, address line, full postcode, telephone, e-mail, web address, Companies House link or per-company row appears in any shipped file.',
population: prov.counts ? prov.counts.rows_read_from_source : null,
suppression: prov.suppression || null,
deterministic_techniques: prov.deterministic_techniques || null,
links: prov.links || null,
leak_check: { pass: leak.pass, files_checked: leak.files_checked, findings: (leak.findings || []).length, names_tested: leak.company_name_test && leak.company_name_test.names_tested, run_utc: leak.run_utc },
headless_check: { pass: head.pass, run_utc: head.run_utc, loads: (head.loads || []).map(l => ({ name: l.name, width: l.width, errors: l.errors, scrollWidth: l.scrollWidth, innerWidth: l.innerWidth, tap_heights: l.tap_heights, pass: l.pass })), count_sentence: head.loads && head.loads[0] ? head.loads[0].count_sentence : null },
file_count: files.length,
total_bytes: files.reduce((a, f) => a + f.bytes, 0),
files,
not_published: { reason: 'on disk in this folder but excluded by the repository .gitignore: never committed, therefore never served', count: notPublished.length, files: notPublished },
};
fs.writeFileSync(path.join(ROOT, 'publication.json'), JSON.stringify(out, null, 1) + '\n');
console.log('publication.json', files.length, 'files,', out.total_bytes, 'bytes | leak', out.leak_check.pass, '| headless', out.headless_check.pass);
for (const f of files) console.log(' ', f.file.padEnd(28), String(f.bytes).padStart(9), f.sha256.slice(0, 12));Browser
A JavaScript module in the proof folder of GlobalGrid2050 covering UK solar and provenance. It is built from the assert step (`assert`).
renderglobalgrid2050 / testcode/202609150502/proof/browser.mjs · lines 1–54 of 54 · version 2026-09-15 05:02 · Entry point · pattern assert (shared by 7 files)
- What it does
- It lists and searches UK solar and provenance. Defines assert. Uses libraries node:module, node:fs, node:path. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain stage experimental (path 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.
- Inputs & outputs
- In: JSON file uk-solar.json; JSON file provenance.json. Out: JSON file browser.json.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 UK Solar Lens Workflow (globalgrid2050).
- What it achieves
- Runs real production modules. Desktop browser viewport emulation, not a physical phone test.
- Why it matters
- Run by GlobalGrid2050 UK Solar Lens Workflow.
- Application
- globalgrid2050 · testcode/202609150502/proof · JavaScript module
- Uses
- node:module, node:fs, node:path
- Used by
- run by GlobalGrid2050 UK Solar Lens Workflow (workflow run)
- Produces
- assert
- Defines here
- assert
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609150502/proof/browser.mjs:1-54 · blob ca476f945b2ab7829ab5b410eab04a765781e945 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: experimental · users: none · canonical: production_core
// Runs real production modules. Desktop browser viewport emulation, not a physical phone test.
import {createRequire} from 'node:module';
import fs from 'node:fs';
import path from 'node:path';
const require=createRequire(import.meta.url);
const puppeteer=require(process.env.PUPPETEER_MODULE||'puppeteer');
const BASE=process.env.SOLAR_BASE||'http://127.0.0.1:8891/testcode/202609150502/';
const OUT=process.env.PROOF_DIR||'solar-proof';fs.mkdirSync(OUT,{recursive:true});
const report={pass:false,kind:'desktop browser viewport emulation',checks:[],measurements:[],limitations:['No physical phone tested.','No 1 GB device tested.','rAF frame sampling is a desktop measurement, not a phone performance guarantee.']};
const assert=(name,value,detail)=>{report.checks.push({name,pass:!!value,...(detail===undefined?{}:{detail})});if(!value)throw new Error(name);};
const browser=await puppeteer.launch({headless:true,...(process.env.CHROME_PATH?{executablePath:process.env.CHROME_PATH}:{}),args:['--no-sandbox','--enable-gpu','--use-gl=angle',...(process.platform==='win32'?['--use-angle=d3d11']:['--use-angle=swiftshader','--enable-unsafe-swiftshader'])]});
try{
report.browser=await browser.version();
for(const [width,height,dpr] of [[1440,900,1],[430,900,2],[900,430,2]]){
const page=await browser.newPage(),errors=[];page.on('pageerror',e=>errors.push(e.message));page.on('console',m=>{if(m.type()==='error')errors.push(m.text());});
await page.setViewport({width,height,deviceScaleFactor:dpr,isMobile:width<=430,hasTouch:width<=430});
await page.goto(`${BASE}?repd_ref=14773`,{waitUntil:'networkidle0'});await page.waitForFunction(()=>window.__solar?.ready);
const before=await page.evaluate(()=>({pos:__solar.positions,state:__solar.state,text:document.body.innerText,n:__solar.core.N,overflow:document.documentElement.scrollWidth-innerWidth,renderer:__solar.renderer}));
assert(`${width}: ready/all records/null detail`,before.n===3563&&before.text.includes('Missing — no geographic position assigned')&&before.state.key==='14773');
assert(`${width}: no horizontal overflow`,before.overflow===0);
await page.reload({waitUntil:'networkidle0'});await page.waitForFunction(()=>window.__solar?.ready);
assert(`${width}: URL reload reproduces layout`,await page.evaluate(pos=>JSON.stringify(__solar.positions)===JSON.stringify(pos),before.pos));
await page.click('#table');assert(`${width}: lens switch preserves key/seed`,await page.evaluate(s=>__solar.state.key===s.key&&__solar.state.seed===s.seed&&__solar.state.lens==='table',before.state));
assert(`${width}: table positions match actual row centres`,await page.evaluate(()=>{const h=document.getElementById('overlay'),bounds=h.getBoundingClientRect();return [...h.children].every(row=>{const i=__solar.core.resolve(row.dataset.ref),r=row.getBoundingClientRect(),p=__solar.positions;return Math.abs(p[2*i]-(r.left-bounds.left+r.width/2))<.1&&Math.abs(p[2*i+1]-(r.top-bounds.top+h.scrollTop … [line shortened here: 424 characters; full line on GitHub]
await page.click('#missing');assert(`${width}: all five nulls selectable`,await page.$$eval('#overlay .project-row',rows=>rows.length===5&&rows.every(r=>r.textContent.includes('coordinates missing'))));
await page.click('[data-ref="1613"]');assert(`${width}: null selection deep link`,await page.$eval('#detail a',a=>a.href.endsWith('/202609050309/?repd_ref=1613')));
await page.click('#ring');await page.click('#all');await page.type('#search','10000');await page.click('#matches [data-ref="10000"]');
assert(`${width}: normal selection deep link`,await page.$eval('#detail a',a=>a.href.endsWith('/202609050309/?repd_ref=10000')));
await page.evaluate(()=>{document.getElementById('search').value='';document.getElementById('search').dispatchEvent(new Event('input'));});
const small=await page.$$eval('button,input,select',els=>els.filter(e=>e.getClientRects().length).map(e=>({id:e.id||e.textContent.slice(0,40),height:e.getBoundingClientRect().height,width:e.getBoundingClientRect().width})).filter(r=>r.height<44||r.width<44));
assert(`${width}: touch controls at least 44 CSS pixels`,small.length===0,small);
const frames=await page.evaluate(async()=>{const a=[];let last=performance.now(),start=last;return await new Promise(resolve=>{const tick=now=>{__solar.render();a.push(now-last);last=now;if(now-start<5000)requestAnimationFrame(tick);else{const s=a.slice(1).sort((x,y)=>x-y);resolve({duration_ms:now-start,samples:s.length,mean_fps:1000/(s.reduce((x,y)=>x+y,0)/s.length),frame_ms_p95:s[Math.floor(s. … [line shortened here: 452 characters; full line on GitHub]
report.measurements.push({viewport:{width,height,dpr},renderer:before.renderer,scenario:'five seconds requesting redraw every animation frame',...frames});
await page.screenshot({path:path.join(OUT,`solar-${width}x${height}.png`),fullPage:true});
assert(`${width}: zero console/page errors`,errors.length===0,errors);await page.close();
}
const fallback=await browser.newPage();await fallback.setViewport({width:430,height:900,deviceScaleFactor:2});
const fallbackErrors=[];fallback.on('pageerror',e=>fallbackErrors.push(e.message));fallback.on('console',m=>{if(m.type()==='error')fallbackErrors.push(m.text());});
await fallback.evaluateOnNewDocument(()=>{const original=HTMLCanvasElement.prototype.getContext;HTMLCanvasElement.prototype.getContext=function(type,...args){return type==='webgl2'?null:original.call(this,type,...args);};});
await fallback.emulateMediaFeatures([{name:'prefers-reduced-motion',value:'reduce'}]);
await fallback.goto(`${BASE}?repd_ref=14773`,{waitUntil:'networkidle0'});await fallback.waitForFunction(()=>window.__solar?.ready);
assert('forced no-WebGL2 / reduced-motion fallback',await fallback.evaluate(()=>__solar.renderer==='Canvas2D'&&document.documentElement.scrollWidth===innerWidth&&document.getElementById('detail').innerText.includes('Missing')));
assert('fallback has zero console/page errors',fallbackErrors.length===0,fallbackErrors);
await fallback.screenshot({path:path.join(OUT,'solar-fallback.png'),fullPage:true});await fallback.close();
const bad=await browser.newPage();await bad.goto(`${BASE}?seed=invalid&repd_ref=999999999&lens=invalid`,{waitUntil:'networkidle0'});await bad.waitForFunction(()=>window.__solar?.ready);
assert('malformed seed and unknown key reported',await bad.evaluate(()=>__solar.state.notes.length===3&&__solar.state.focus===-1));await bad.close();
const tamper=await browser.newPage();await tamper.setRequestInterception(true);tamper.on('request',r=>r.url().endsWith('/data/uk-solar.json')?r.respond({status:200,contentType:'application/json',body:'{"projects":[]}'}):r.continue());
await tamper.goto(BASE,{waitUntil:'networkidle0'});await tamper.waitForFunction(()=>window.__solar);
assert('modified data bytes fail closed',await tamper.evaluate(()=>!__solar.ready&&__solar.error.includes('hash mismatch')));await tamper.close();
const absent=await browser.newPage();await absent.setRequestInterception(true);absent.on('request',r=>r.url().endsWith('/data/provenance.json')?r.respond({status:200,contentType:'application/json',body:'{"files":{}}'}):r.continue());
await absent.goto(BASE,{waitUntil:'networkidle0'});await absent.waitForFunction(()=>window.__solar);
assert('missing manifest proof fails closed',await absent.evaluate(()=>!__solar.ready&&__solar.error.includes('snapshot proof')));await absent.close();
report.pass=report.checks.every(c=>c.pass);
}catch(e){report.error=e.stack;}finally{await browser.close();fs.writeFileSync(path.join(OUT,'browser.json'),JSON.stringify(report,null,2)+'\n');console.log(JSON.stringify(report,null,2));if(!report.pass)process.exitCode=1;}