In this section
- Build V9 5 storage · gridatlas / tools/v9_5/build_v9_5.py lines 1–200
- Compiler render · gridatlas / tools/v9_5/compiler.py lines 1–276
- Release Stream Payload Cache automation · gridatlas / tools/v9_5/release_stream_payload_cache.py lines 1–108
- VEDIC OSM Pilot storage · gridatlas / tools/vedic/osm-pilot.py lines 1–44
Build V9 5
A Python command-line tool in the tools folder of GridAtlas that reads request, postcodes and the Renewable Energy Planning Database (REPD) register, using SHA-256.
storagegridatlas / tools/v9_5/build_v9_5.py · lines 1–200 of 200 · Entry point
- What it does
- It loads request, postcodes and the REPD register. Defines main. Uses libraries __future__, argparse, copy, json, re. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: postcodes, the REPD register.
- Inputs & outputs
- In: JSON file current.json; JSON file v9-5-request.json; JSON file v9-5-build.json; command-line arguments.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- Build GridAtlas v9.5 as one immutable-shell search cartridge. It accepts `--request` and `--report`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- gridatlas · tools/v9_5 · Python CLI
- Uses
- Compiler (import), __future__, argparse, copy, json, re, pathlib, typing
- Used by
- none found
- Produces
- main
- Defines here
- main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/v9_5/build_v9_5.py:1-200 · blob aa81df8ac696a163b654a0a0393072775785be39 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Build GridAtlas v9.5 as one immutable-shell search cartridge.
This is deliberately a compiler, not a hand-written application copy. It takes the
last accepted search cartridge, applies asserted transformations, writes one new
content-addressed cartridge, and advances atlas/current.json plus its manifest.
"""
from __future__ import annotations
import argparse
import copy
import json
import re
from pathlib import Path
from typing import Any
from compiler import compile_cartridge, dump_json, load_json, sha256_bytes
ROOT = Path(__file__).resolve().parents[2]
SOURCE = ROOT / "atlas/cartridges/202608301136-place-postcode-search.js"
SOURCE_SHA256 = "7f8e91c5ed54152f5ae4cd999ec501caed8d6625fdf0df20cc418805dec3e1fa"
CURRENT = ROOT / "atlas/current.json"
OLD_CONTRACT = ROOT / "ui/cartridges/202608301136-uk-gazetteer-flyto.mjs"
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--request", default="state/v9-5-request.json")
parser.add_argument("--report", default="work/v9-5-build.json")
args = parser.parse_args()
request_path = ROOT / args.request
request = load_json(request_path)
generation = str(request.get("generation", ""))
if not re.fullmatch(r"20\d{10}", generation):
raise RuntimeError(f"invalid 12-digit generation: {generation!r}")
if request.get("version") != "v9.5":
raise RuntimeError("request version must be v9.5")
source_bytes = SOURCE.read_bytes()
have_source_sha = sha256_bytes(source_bytes)
if have_source_sha != SOURCE_SHA256:
raise RuntimeError(f"source cartridge changed: {have_source_sha} != {SOURCE_SHA256}")
current = load_json(CURRENT)
if current.get("generation") == generation and current.get("composition_version") == "v9.5":
report = {
"schema": "gridatlas.v9-5-build.v1",
"status": "ALREADY_BUILT",
"generation": generation,
"current": str(CURRENT.relative_to(ROOT)),
}
dump_json(ROOT / args.report, report)
print(json.dumps(report))
return 0
previous_generation = str(current["generation"])
source_text = source_bytes.decode("utf-8")
compiled = compile_cartridge(source_text, generation)
compiled_bytes = compiled.encode("utf-8")
cartridge_sha = sha256_bytes(compiled_bytes)
cartridge_rel = Path(f"atlas/cartridges/{generation}-place-global-search-v9-5.js")
cartridge_path = ROOT / cartridge_rel
if cartridge_path.exists() and cartridge_path.read_bytes() != compiled_bytes:
raise RuntimeError(f"immutable target already exists with different bytes: {cartridge_rel}")
cartridge_path.parent.mkdir(parents=True, exist_ok=True)
cartridge_path.write_bytes(compiled_bytes)
contract_rel = Path(f"ui/cartridges/{generation}-global-gazetteer-flyto-v9-5.mjs")
contract_path = ROOT / contract_rel
contract = f"""export const ATLAS_V9_5_GLOBAL_GAZETTEER_FLYTO_CONTRACT = Object.freeze({{\n schema: 'gridatlas.cartridge.v1',\n generation: '{generation}',\n version: 'v9.5',\n activation: 'explicit-user-query',\n providers: ['postcodes.io', 'Nominatim / OpenStreetMap'],\n repdResultsFirst: true,\n staleResponseGuard: true,\n resultClass: 'LOCATION_ONLY',\n proximityEstablishesIdentit … [line shortened here: 443 characters; full line on GitHub]
if contract_path.exists() and contract_path.read_text(encoding="utf-8") != contract:
raise RuntimeError(f"immutable target already exists with different bytes: {contract_rel}")
contract_path.parent.mkdir(parents=True, exist_ok=True)
contract_path.write_text(contract, encoding="utf-8")
previous_manifest_path = (ROOT / "atlas" / str(current["composition_manifest"])).resolve()
previous_manifest = load_json(previous_manifest_path)
cartridge = {
"id": "uk-gazetteer-flyto",
"generation": generation,
"version": "v9.5",
"type": "script",
"slot": "replace-script",
"replace_script": "202608291818-place-postcode-search.js",
"path": f"./cartridges/{cartridge_rel.name}",
"sha256": cartridge_sha,
"contract": f"../{contract_rel.as_posix()}",
"capabilities": ["exact-repd-first", "uk-postcode", "uk-place", "global-address", "global-place"],
"result_class": "LOCATION_ONLY",
"sets_deep_link": False,
}
new_current = copy.deepcopy(current)
new_current.update(
{
"generation": generation,
"previous_generation": previous_generation,
"composition_version": "v9.5",
"composition_id": f"{generation}-gridatlas-v9.5",
"cartridge_order": ["uk-gazetteer-flyto"],
"cartridges": [cartridge],
"composition_manifest": f"./manifests/{generation}-composition.json",
}
)
new_current["search_lanes"] = {
"repd": {"external_requests": 0, "identity_claims": "EXACT_REPD_REF_ONLY", "first": True},
"uk_gazetteer": {
"provider": "postcodes.io",
"endpoints": ["postcodes", "outcodes", "places"],
"identity_claims": "none",
"result_class": "LOCATION_ONLY",
},
"global_gazetteer": {
"provider": "Nominatim / OpenStreetMap",
"endpoint": "search",
"activation": "Enter or search button",
"identity_claims": "none",
"result_class": "LOCATION_ONLY",
},
}
new_current["scope_closure"] = {
"generation": generation,
"status": "DONE",
"scope": "GridAtlas v9.5 global address fly-to",
"schedule_retired": True,
}
new_current.setdefault("provenance", {})["sandbox_source"] = (
"https://github.com/Ventusltd/globalgrid2050/blob/main/"
"solar-bess-topology-v7/gis-sld-financial-sandbox/gis-sld-v5-ui.js"
)
new_current["provenance"]["cvaa_commit"] = str(request.get("cvaa_commit", ""))
manifest = copy.deepcopy(previous_manifest)
manifest.update(
{
"schema": "gridatlas.composition-manifest.v1",
"generation": generation,
"parent_generation": previous_generation,
"version": "v9.5",
"composition_id": f"{generation}-gridatlas-v9.5",
"cartridge_order": ["uk-gazetteer-flyto"],
"cartridges": [cartridge],
"source_pattern": {
"repository": "Ventusltd/globalgrid2050",
"path": "solar-bess-topology-v7/gis-sld-financial-sandbox/gis-sld-v5-ui.js",
"behaviour": "Nominatim search then MapLibre flyTo",
},
"acceptance": {
"full_application_copies_created": 0,
"immutable_shell_modified": False,
"exact_repd_identity_lane_preserved": True,
"repd_results_first": True,
"postcode_stale_response_guard": True,
"uk_location_result_class": "LOCATION_ONLY",
"global_location_result_class": "LOCATION_ONLY",
"external_location_failure_isolated": True,
"golden_browser_verification": "REQUIRED",
},
}
)
manifest.pop("scope_file", None)
manifest_path = ROOT / f"atlas/manifests/{generation}-composition.json"
dump_json(manifest_path, manifest)
dump_json(CURRENT, new_current)
# Existing durable verifier should wait for this exact generation, not merely an old closed scope.
verifier_path = ROOT / "tools/scope/verify-live.mjs"
verifier = verifier_path.read_text(encoding="utf-8")
old_wait = "current?.schema === 'gridatlas.current.v2' && current?.scope_closure?.status === 'DONE' && current?.cartridge_order?.includes('uk-gazetteer-flyto')"
new_wait = f"current?.schema === 'gridatlas.current.v2' && current?.generation === '{generation}' && current?.composition_version === 'v9.5' && current?.scope_closure?.status === 'DONE' && current?.cartridge_order?.includes('uk-gazetteer-flyto')"
if old_wait in verifier:
verifier = verifier.replace(old_wait, new_wait, 1)
elif new_wait not in verifier:
raise RuntimeError("durable live verifier wait marker changed unexpectedly")
verifier_path.write_text(verifier, encoding="utf-8")
report = {
"schema": "gridatlas.v9-5-build.v1",
"status": "BUILT",
"generation": generation,
"version": "v9.5",
"previous_generation": previous_generation,
"source_cartridge": str(SOURCE.relative_to(ROOT)),
"source_sha256": have_source_sha,
"cartridge": str(cartridge_rel),
"cartridge_sha256": cartridge_sha,
"contract": str(contract_rel),
"manifest": str(manifest_path.relative_to(ROOT)),
"full_application_copies_created": 0,
}
dump_json(ROOT / args.report, report)
print(json.dumps(report, sort_keys=True))
return 0
if __name__ == "__main__":
raise SystemExit(main())Compiler
A Python module in the tools folder of GridAtlas covering postcodes and the Renewable Energy Planning Database (REPD) register, using SHA-256, and uses data from postcodes.io and OpenStreetMap Nominatim.
rendergridatlas / tools/v9_5/compiler.py · lines 1–276 of 276 · pattern dump_json (shared by 2 files)
- What it does
- It draws postcodes and the REPD register. Defines 6 functions or classes, including sha256_bytes, replace_once, regex_replace_once, load_json, dump_json. Uses libraries __future__, hashlib, json, re, pathlib. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: postcodes, the REPD register.
- Inputs & outputs
- In: data source: postcodes.io; data source: OpenStreetMap Nominatim.
- Downstream impact
- Used directly by 1 file: Build V9 5 (gridatlas).
- What it achieves
- It replaces once (`replace_once`), loads JSON (`load_json`) and dumps JSON (`dump_json`). Deterministic source transformations for GridAtlas v9.5.
- Why it matters
- Imported by Build V9 5.
- Application
- gridatlas · tools/v9_5 · Python module
- Uses
- __future__, hashlib, json, re, pathlib, typing
- Used by
- imported by Build V9 5 (import)
- Produces
- sha256_bytes, replace_once, regex_replace_once, load_json, dump_json, compile_cartridge
- Defines here
- sha256_bytes, replace_once, regex_replace_once, load_json, dump_json, compile_cartridge
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/v9_5/compiler.py:1-276 · blob f7a49f4aa792f6460e6009453e9c0e99e983916f · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Deterministic source transformations for GridAtlas v9.5."""
from __future__ import annotations
import hashlib
import json
import re
from pathlib import Path
from typing import Any
def sha256_bytes(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def replace_once(text: str, old: str, new: str, label: str) -> str:
count = text.count(old)
if count != 1:
raise RuntimeError(f"{label}: expected exactly one source marker, found {count}")
return text.replace(old, new, 1)
def regex_replace_once(text: str, pattern: str, replacement: str, label: str) -> str:
changed, count = re.subn(pattern, lambda _match: replacement, text, count=1, flags=re.S)
if count != 1:
raise RuntimeError(f"{label}: expected exactly one source region, found {count}")
return changed
def load_json(path: Path) -> dict[str, Any]:
return json.loads(path.read_text(encoding="utf-8"))
def dump_json(path: Path, value: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(value, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
def compile_cartridge(source: str, generation: str) -> str:
source = replace_once(
source,
" const GEOCODER_BASE = 'https://api.postcodes.io';\n",
" const GEOCODER_BASE = 'https://api.postcodes.io';\n"
" const GLOBAL_GEOCODER_URL = 'https://nominatim.openstreetmap.org/search';\n",
"global geocoder constant",
)
source = replace_once(
source,
" schema: 'gridatlas.v9-place-postcode-search.v2',\n"
" generation: '202608301136',\n"
" geocoder: GEOCODER_BASE,\n"
" geocoder_requests: 0,\n"
" geocoder_failures: [],\n",
" schema: 'gridatlas.v9-place-global-search.v3',\n"
f" generation: '{generation}',\n"
" version: 'v9.5',\n"
" geocoder: GEOCODER_BASE,\n"
" global_geocoder: GLOBAL_GEOCODER_URL,\n"
" geocoder_providers: ['postcodes.io', 'Nominatim / OpenStreetMap'],\n"
" geocoder_requests: 0,\n"
" global_geocoder_requests: 0,\n"
" geocoder_failures: [],\n",
"search state identity",
)
source = replace_once(
source,
" ORDER BY search_score DESC, capacity_mw DESC NULLS LAST, name ASC\n",
" ORDER BY search_score DESC, TRY_CAST(repd_ref AS BIGINT) ASC NULLS LAST, capacity_mw DESC NULLS LAST, name ASC\n",
"deterministic REPD tie-break",
)
source = replace_once(source, " kind: 'postcode',\n", " kind: 'postcode',\n provider: 'postcodes.io',\n", "postcode provider")
source = replace_once(source, " kind: 'postcode_district',\n", " kind: 'postcode_district',\n provider: 'postcodes.io',\n", "outcode provider")
source = replace_once(source, " kind: 'place',\n", " kind: 'place',\n provider: 'postcodes.io',\n", "UK place provider")
global_lane = r'''
async function queryGlobalGazetteer(query) {
const raw = String(query ?? '').trim();
if (raw.length < 2) return [];
const compact = normaliseCompact(raw);
if (FULL_POSTCODE.test(compact) || OUTCODE.test(compact)) return [];
state.global_geocoder_requests += 1;
try {
const url = new URL(GLOBAL_GEOCODER_URL);
url.searchParams.set('format', 'jsonv2');
url.searchParams.set('limit', '8');
url.searchParams.set('addressdetails', '1');
url.searchParams.set('accept-language', 'en');
url.searchParams.set('q', raw);
const response = await fetch(url, {
cache: 'default',
headers: { Accept: 'application/json' }
});
if (!response.ok) throw new Error(`Nominatim ${response.status}`);
const body = await response.json();
const out = [];
for (const row of Array.isArray(body) ? body : []) {
const longitude = Number(row.lon);
const latitude = Number(row.lat);
if (!Number.isFinite(longitude) || !Number.isFinite(latitude)) continue;
const display = String(row.display_name || '').trim();
const label = String(row.name || row.address?.city || row.address?.town || row.address?.village || display.split(',')[0] || raw).trim();
out.push({
kind: 'global_place',
provider: 'Nominatim / OpenStreetMap',
label,
sublabel: display || raw,
longitude,
latitude
});
}
return out;
} catch (error) {
state.geocoder_failures.push({
query: raw,
path: GLOBAL_GEOCODER_URL,
provider: 'Nominatim / OpenStreetMap',
message: String(error?.message || error)
});
console.warn('[V9.5 GLOBAL GAZETTEER]', error);
return [];
}
}
function dedupeGlobalLocations(ukResults, globalResults) {
return globalResults.filter(globalResult => !ukResults.some(ukResult => {
const sameLabel = String(globalResult.label).trim().toLowerCase() === String(ukResult.label).trim().toLowerCase();
const close = Math.abs(globalResult.longitude - ukResult.longitude) < 0.03 && Math.abs(globalResult.latitude - ukResult.latitude) < 0.03;
return sameLabel && close;
}));
}
'''
source = replace_once(
source,
"\n function selectLocation(result) {\n",
global_lane + "\n function selectLocation(result) {\n",
"global gazetteer lane",
)
source = replace_once(
source,
" const zoom = result.kind === 'postcode' ? 13 : result.kind === 'postcode_district' ? 11 : 12;\n",
" const zoom = result.kind === 'postcode' ? 13 : result.kind === 'postcode_district' ? 11 : result.kind === 'global_place' ? 12 : 12;\n"
" const provider = result.provider || 'postcodes.io';\n",
"location provider and zoom",
)
source = replace_once(
source,
"<span style=\"color:#555;font-size:9px\">Location only · postcodes.io · no project identity claimed</span>",
"<span style=\"color:#555;font-size:9px\">Location only · ${escapeHtml(provider)} · no project identity claimed</span>",
"provider-aware popup",
)
render_and_execute = r''' function renderResults(repdResults, resultsEl, ukResults = [], globalResults = []) {
resultsEl.innerHTML = '';
if (!repdResults.length && !ukResults.length && !globalResults.length) {
const empty = document.createElement('div');
empty.className = 'search-no-results';
empty.textContent = 'No REPD project, postcode, address or place match';
resultsEl.appendChild(empty);
resultsEl.style.display = 'block';
return;
}
for (const result of repdResults) {
const item = document.createElement('div');
item.className = 'search-result-item';
item.dataset.repdRef = result.repd_ref;
const location = [result.address, result.postcode, result.county].filter(Boolean).join(' · ');
const capacity = Number.isFinite(result.capacity_mw) ? `${result.capacity_mw.toLocaleString('en-GB')} MW` : '';
item.innerHTML = `<b>${escapeHtml(result.name)}</b><br><span>${escapeHtml(location)}</span>${capacity ? `<br><span style="color:#ffae00">${escapeHtml(capacity)}</span>` : ''}<span style="color:#555"> · REPD ${escapeHtml(result.repd_ref)}</span>`;
item.addEventListener('click', event => {
event.preventDefault();
event.stopPropagation();
resultsEl.style.display = 'none';
selectResult(result);
});
resultsEl.appendChild(item);
}
function renderLocationLane(title, locations) {
if (!locations.length) return;
const divider = document.createElement('div');
divider.className = 'search-no-results';
divider.textContent = title;
resultsEl.appendChild(divider);
for (const result of locations) {
const item = document.createElement('div');
item.className = 'search-result-item';
item.dataset.locationKind = result.kind;
item.dataset.locationProvider = result.provider || '';
item.innerHTML = `<b>${escapeHtml(result.label)}</b><br><span>${escapeHtml(result.sublabel)}</span><span style="color:#555"> · fly to only, not a REPD project</span>`;
item.addEventListener('click', event => {
event.preventDefault();
event.stopPropagation();
resultsEl.style.display = 'none';
selectLocation(result);
});
resultsEl.appendChild(item);
}
}
renderLocationLane('UK location', ukResults);
renderLocationLane('Global location', globalResults);
resultsEl.style.display = 'block';
}
async function executeSearch(input, resultsEl, includeGlobal = false) {
const serial = ++activeQuerySerial;
const query = input.value.trim();
if (query.length < 2) {
resultsEl.innerHTML = '';
resultsEl.style.display = 'none';
return;
}
resultsEl.style.display = 'block';
resultsEl.innerHTML = '<div class="search-no-results">Searching REPD projects, postcodes, addresses and places…</div>';
try {
const [results, ukLocations, rawGlobalLocations] = await Promise.all([
queryOfficialRepd(query, serial),
queryUkGazetteer(query),
includeGlobal ? queryGlobalGazetteer(query) : Promise.resolve([])
]);
if (serial !== activeQuerySerial) return;
const globalLocations = dedupeGlobalLocations(ukLocations, rawGlobalLocations);
renderResults(results, resultsEl, ukLocations, globalLocations);
} catch (error) {
if (serial !== activeQuerySerial) return;
state.failures.push({ query, message: String(error?.message || error) });
resultsEl.innerHTML = '<div class="search-no-results">Search unavailable — V8 map remains usable</div>';
resultsEl.style.display = 'block';
console.error('[V9.5 PLACE SEARCH]', error);
}
}
'''
source = regex_replace_once(
source,
r" function renderResults\([\s\S]*?\n async function waitForCapturedMap",
render_and_execute + " async function waitForCapturedMap",
"results and serialised execution",
)
source = replace_once(
source,
" input.setAttribute('placeholder', 'Search project, UK postcode or town...');\n"
" input.setAttribute('aria-label', 'Search project, UK postcode or town');\n",
" input.setAttribute('placeholder', 'Search project, address, postcode or place...');\n"
" input.setAttribute('aria-label', 'Search project, address, postcode or place');\n",
"search discoverability",
)
source = replace_once(
source,
" debounceTimer = setTimeout(() => executeSearch(input, resultsEl), 180);\n",
" debounceTimer = setTimeout(() => executeSearch(input, resultsEl, false), 180);\n",
"debounced local lanes",
)
# Enter is nested inside an if (8 spaces); button click is one level shallower (6 spaces).
for indent, label in [(" ", "Enter submission"), (" ", "button submission")]:
source = replace_once(
source,
f"{indent}executeSearch(input, resultsEl);\n",
f"{indent}executeSearch(input, resultsEl, true);\n",
label,
)
for marker in [
"const serial = ++activeQuerySerial",
"if (serial !== activeQuerySerial) return",
"GLOBAL_GEOCODER_URL",
"Nominatim / OpenStreetMap",
"kind: 'global_place'",
"TRY_CAST(repd_ref AS BIGINT) ASC",
"url.searchParams.delete('repd_ref')",
"Location only · ${escapeHtml(provider)} · no project identity claimed",
]:
if marker not in source:
raise RuntimeError(f"compiled cartridge missing invariant: {marker}")
return source
Release Stream Payload Cache
A Python command-line tool in the tools folder of GridAtlas that reads streaming road build, using SHA-256.
automationgridatlas / tools/v9_5/release_stream_payload_cache.py · lines 1–108 of 108 · Entry point
- What it does
- It loads streaming road build. Defines load, dump, main, patch_registry. Uses libraries __future__, argparse, hashlib, json, pathlib. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- In: JSON file streaming-road-build.json; JSON file current.json; command-line arguments.
- Downstream impact
- Used directly by 1 file: GridAtlas Verify Live Workflow (gridatlas).
- What it achieves
- It patches registry (`patch_registry`) and is built from the load step (`load`) and the dump step (`dump`). Release the bridge's reconstructed payload after serialisation and re-pin the cartridge. It accepts `--generation` and `--report`.
- Why it matters
- Run by GridAtlas Verify Live Workflow.
- Application
- gridatlas · tools/v9_5 · Python CLI
- Uses
- __future__, argparse, hashlib, json, pathlib
- Used by
- run by GridAtlas Verify Live Workflow (workflow run)
- Produces
- load, dump, main
- Defines here
- load, dump, main, patch_registry
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/v9_5/release_stream_payload_cache.py:1-108 · blob 87cc4e43a88cb0176100f1f3f74668d7fd8410f1 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Release the bridge's reconstructed payload after serialisation and re-pin the cartridge.
This is a deterministic post-compiler pass. It changes only the generated transport
cartridge, its generated contract, current.json, the composition manifest and build report.
"""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
def load(path: Path):
return json.loads(path.read_text(encoding="utf-8"))
def dump(path: Path, value) -> None:
path.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8")
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--generation", required=True)
parser.add_argument("--report", default="work/streaming-road-build.json")
args = parser.parse_args()
generation = args.generation
cartridge = ROOT / f"atlas/cartridges/{generation}-streaming-parquet-bridge-v9-5.js"
contract = ROOT / f"ui/cartridges/{generation}-streaming-parquet-bridge-v9-5.mjs"
current_path = ROOT / "atlas/current.json"
report_path = ROOT / args.report
current = load(current_path)
manifest_path = (ROOT / "atlas" / current["composition_manifest"]).resolve()
manifest = load(manifest_path)
report = load(report_path)
text = cartridge.read_text(encoding="utf-8")
state_old = " streamed_responses: 0,\n stream_failures: [],"
state_new = " streamed_responses: 0,\n released_payloads: 0,\n stream_failures: [],"
if state_new not in text:
if text.count(state_old) != 1:
raise RuntimeError("stream state marker changed")
text = text.replace(state_old, state_new, 1)
body_old = """ controller.enqueue(encoder.encode(JSON.stringify(payload)));
controller.close();
}).catch(error => {
state.stream_failures.push({ pathname, message: String(error?.message || error) });"""
body_new = """ const serialised = JSON.stringify(payload);
sourceCache.delete(pathname);
state.released_payloads += 1;
controller.enqueue(encoder.encode(serialised));
controller.close();
}).catch(error => {
sourceCache.delete(pathname);
state.stream_failures.push({ pathname, message: String(error?.message || error) });"""
if body_new not in text:
if text.count(body_old) != 1:
raise RuntimeError("stream serialisation marker changed")
text = text.replace(body_old, body_new, 1)
cartridge.write_text(text, encoding="utf-8")
digest = hashlib.sha256(cartridge.read_bytes()).hexdigest()
contract_text = contract.read_text(encoding="utf-8")
marker = " responseEstablishedBeforeBodyReconstruction: true,\n"
addition = marker + " payloadCacheReleasedAfterSerialisation: true,\n"
if addition not in contract_text:
if contract_text.count(marker) != 1:
raise RuntimeError("transport contract marker changed")
contract_text = contract_text.replace(marker, addition, 1)
contract.write_text(contract_text, encoding="utf-8")
def patch_registry(document: dict) -> None:
rows = document.get("cartridges", [])
transport = next((row for row in rows if row.get("id") == "streaming-parquet-bridge"), None)
if transport is None:
raise RuntimeError("transport cartridge missing from registry")
transport["sha256"] = digest
capabilities = transport.setdefault("capabilities", [])
if "payload-cache-release-after-serialisation" not in capabilities:
capabilities.append("payload-cache-release-after-serialisation")
patch_registry(current)
patch_registry(manifest)
manifest.setdefault("acceptance", {})["bridge_payload_cache_released_after_serialisation"] = True
current.setdefault("transport", {})["payload_cache"] = "RELEASE_AFTER_SERIALISATION"
report["transport_sha256"] = digest
report["payload_cache_released_after_serialisation"] = True
dump(current_path, current)
dump(manifest_path, manifest)
dump(report_path, report)
print(json.dumps({
"schema": "gridatlas.streaming-payload-release.v1",
"generation": generation,
"cartridge": str(cartridge.relative_to(ROOT)),
"sha256": digest,
"status": "PATCHED",
}, sort_keys=True))
return 0
if __name__ == "__main__":
raise SystemExit(main())VEDIC OSM Pilot
A Python module in the tools folder of GridAtlas that fetches topology, using SHA-256. It is built from the attrs step (`attrs`).
storagegridatlas / tools/vedic/osm-pilot.py · lines 1–44 of 44 · Not reached from any entry point (candidate for review)
- What it does
- It fetches topology. Defines attrs. Uses libraries hashlib, json, pathlib, sys, urllib.request. Side effects: reads or writes files; makes network requests; starts processes.
- Why it exists in the grid workflow
- Domain stage agent_infra (path word 'vedic'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: command-line arguments. Out: JSON file topology.json; JSON file receipt.json.
- What it achieves
- Bounded one-shot OSM source acquisition. Do not run from movement or a browser.
- Why it matters
- No other file in the estate was found to import it.
- Application
- gridatlas · tools/vedic · Python module
- Uses
- hashlib, json, pathlib, sys, urllib.request, xml.etree.ElementTree, datetime
- Used by
- none found
- Produces
- none declared
- Defines here
- attrs
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/vedic/osm-pilot.py:1-44 · blob 67845706532a7206cec009a3f1261884a3f79c8a · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
"""Bounded one-shot OSM source acquisition. Do not run from movement or a browser."""
import hashlib, json, pathlib, sys, urllib.request, xml.etree.ElementTree as ET
from datetime import datetime, timezone
OUT = pathlib.Path(sys.argv[1])
OUT.mkdir(parents=True, exist_ok=True)
URL = "https://api.openstreetmap.org/api/0.6/map?bbox=-1.2600,51.7510,-1.2580,51.7530"
LIMIT = 2 * 1024 * 1024
receipt = {"url": URL, "attribution": "© OpenStreetMap contributors", "licence": "ODbL-1.0", "licence_url": "https://www.openstreetmap.org/copyright", "attempted_utc": datetime.now(timezone.utc).isoformat(), "limit_bytes": LIMIT, "status": "unavailable"}
try:
request = urllib.request.Request(URL, headers={"User-Agent":"Ventus-GridAtlas-RegionalPilot/1.0 (+https://github.com/Ventusltd/gridatlas)", "Accept-Encoding":"identity"})
with urllib.request.urlopen(request, timeout=25) as response:
if response.geturl() != URL:
raise ValueError("unexpected redirect")
raw = response.read(LIMIT + 1)
if len(raw) > LIMIT:
raise ValueError("source exceeds byte cap")
if b"<!DOCTYPE" in raw.upper() or b"<!ENTITY" in raw.upper():
raise ValueError("unsafe XML")
root = ET.fromstring(raw)
if root.tag != "osm" or root.get("version") != "0.6":
raise ValueError("unexpected OSM document")
def attrs(e):
return {"id":e.attrib["id"], "version":e.get("version"), "timestamp":e.get("timestamp"), "tags":{t.attrib["k"]:t.attrib["v"] for t in e.findall("tag")}}
data = {"nodes":[], "ways":[], "relations":[]}
for e in root:
if e.tag == "node":
data["nodes"].append({**attrs(e),"lat":float(e.attrib["lat"]),"lon":float(e.attrib["lon"])})
elif e.tag == "way":
data["ways"].append({**attrs(e),"nodes":[n.attrib["ref"] for n in e.findall("nd")]})
elif e.tag == "relation":
data["relations"].append({**attrs(e),"members":[{k:m.attrib[k] for k in ("type","ref","role")} for m in e.findall("member")]})
if not data["nodes"] or not data["ways"]:
raise ValueError("empty source graph")
encoded = json.dumps(data, sort_keys=True, separators=(",",":"), ensure_ascii=False).encode()
(OUT/"source.osm").write_bytes(raw)
(OUT/"topology.json").write_bytes(encoded)
receipt.update(status="acquired", acquired_utc=datetime.now(timezone.utc).isoformat(), source_bytes=len(raw), source_sha256=hashlib.sha256(raw).hexdigest(), topology_sha256=hashlib.sha256(encoded).hexdigest(), counts={k:len(v) for k,v in data.items()})
except Exception as e:
receipt["error"] = f"{type(e).__name__}: {e}"
finally:
(OUT/"receipt.json").write_text(json.dumps(receipt,indent=2)+"\n")
print(json.dumps(receipt))
# Network failures are explicit evidence, not a successful live-source gate.
sys.exit(0 if receipt["status"]=="acquired" else 2)