GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / AI agents and coordination / data-grid-gb / chatgpt

ChatGPT Ingest ETYS and 6 more files

A Python command-line tool in Data Grid GB that reads sources and transformers, using SHA-256. It parses sites (`parse_sites`), parses equipment (`parse_equipment`) and parses faults (`parse_faults`).

531 lines of Python and CSS from data-grid-gb, gemini, in 7 files. Topic: AI agents and coordination. Section 1619 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. ChatGPT Ingest ETYS storage · data-grid-gb / chatgpt/ingest_etys.py lines 1–244
  2. Test Contract test · data-grid-gb / chatgpt/tests/test_contract.py lines 1–45
  3. ChatGPT Verify Product ingest · data-grid-gb / chatgpt/verify_product.py lines 1–40
  4. Gemini render · gemini / docs/assets/gemini.css lines 1–25
  5. Gemini Build Manifest storage · gemini / scripts/build_manifest.py lines 1–105
  6. UI Packets transform · gemini / scripts/ui/packets.py lines 1–40
  7. UI Render Home transform · gemini / scripts/ui/render_home.py lines 1–32

ChatGPT Ingest ETYS

A Python command-line tool in Data Grid GB that reads sources and transformers, using SHA-256. It parses sites (`parse_sites`), parses equipment (`parse_equipment`) and parses faults (`parse_faults`).

storagedata-grid-gb / chatgpt/ingest_etys.py · lines 1–244 of 244 · Entry point · pattern records (shared by 2 files)

What it does
It loads sources and transformers. Defines 12 functions or classes, including sha256, pinned, clean, records, sheet_to. Uses libraries __future__, argparse, hashlib, json, re. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'chatgpt'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). Domain terms in the code: transformers.
Inputs & outputs
In: JSON file sources.json; command-line arguments.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Deterministically normalise pinned National Energy System Operator (NESO) ETYS 2025 workbooks. Its code works with 100 MVA. It accepts `--appendix-b`, `--fault-peak` and `--fault-minimum`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
data-grid-gb · chatgpt · Python CLI
Uses
__future__, argparse, hashlib, json, re, pathlib, typing, openpyxl
Used by
none found
Produces
sha256, pinned, clean, records, sheet_to, has_header, parse_sites, parse_equipment, parse_faults, unique, build, main
Defines here
sha256, pinned, clean, records, sheet_to, has_header, parse_sites, parse_equipment, parse_faults, unique, build, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
data-grid-gb@4a9cef6c7c791f76d416c8b2fbafac8265f7a263 chatgpt/ingest_etys.py:1-244 · blob 9b6fa466d9b0cab4ff0fccaa19781e4e9265f2a2 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
#!/usr/bin/env python3
"""Deterministically normalise pinned NESO ETYS 2025 workbooks."""

from __future__ import annotations

import argparse
import hashlib
import json
import re
from pathlib import Path
from typing import Any, Iterable

import openpyxl

ROOT = Path(__file__).resolve().parent
TO_BY_SUFFIX = {"a": "SHET", "b": "SPT", "c": "NGET", "d": "OFTO"}
FAULT_COLUMNS = (
    "three_phase_initial_peak_current_ka",
    "three_phase_rms_break_current_ka",
    "three_phase_dc_break_current_ka",
    "three_phase_peak_break_current_ka",
    "single_phase_initial_peak_current_ka",
    "single_phase_rms_break_current_ka",
    "single_phase_dc_break_current_ka",
    "single_phase_peak_break_current_ka",
)
FAULT_HEADER_KEYS = {
    "Three Phase Initial Peak Current (kA)": "three_phase_initial_peak_current_ka",
    "Three Phase RMS Break Current (kA)": "three_phase_rms_break_current_ka",
    "Symmetrical Three Phase RMS Break Current (kA)": "three_phase_rms_break_current_ka",
    "Three Phase DC Break Current (kA)": "three_phase_dc_break_current_ka",
    "Three Phase Peak Break Current (kA)": "three_phase_peak_break_current_ka",
    "Asymmetrical Three Phase Peak Break Current (kA)": "three_phase_peak_break_current_ka",
    "Single Phase Initial Peak Current (kA)": "single_phase_initial_peak_current_ka",
    "Single Phase RMS Break Current (kA)": "single_phase_rms_break_current_ka",
    "Symmetrical Single Phase RMS Break Current (kA)": "single_phase_rms_break_current_ka",
    "Single Phase DC Break Current (kA)": "single_phase_dc_break_current_ka",
    "Single Phase Peak Break Current (kA)": "single_phase_peak_break_current_ka",
    "Asymmetrical Single Phase Peak Break Current (kA)": "single_phase_peak_break_current_ka",
}


def sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def pinned(path: Path, artifact: str, ledger: dict[str, Any]) -> dict[str, Any]:
    spec = ledger["artifacts"][artifact]
    actual = {"bytes": path.stat().st_size, "sha256": sha256(path)}
    if actual["bytes"] != spec["bytes"] or actual["sha256"] != spec["sha256"]:
        raise ValueError(f"{artifact}: source bytes do not match pinned ledger: {actual}")
    return {"artifact": artifact, "url": spec["url"], **actual}


def clean(value: Any) -> Any:
    if isinstance(value, str):
        return " ".join(value.split())
    return value


def records(ws: Any, required: tuple[str, ...]) -> Iterable[dict[str, Any]]:
    header = None
    for row in ws.iter_rows(values_only=True):
        values = tuple(clean(v) for v in row)
        if header is None:
            if all(name in values for name in required):
                header = values
            continue
        if not any(v not in (None, "") for v in values):
            continue
        yield {str(key): value for key, value in zip(header, values) if key not in (None, "")}
    if header is None:
        raise ValueError(f"{ws.title}: required header not found: {required}")


def sheet_to(ws: Any) -> str:
    match = re.fullmatch(r"B-[1234]-[12]([abcd])", ws.title)
    if not match:
        raise ValueError(f"cannot derive transmission owner from {ws.title}")
    return TO_BY_SUFFIX[match.group(1)]


def has_header(ws: Any, required: tuple[str, ...]) -> bool:
    for row in ws.iter_rows(min_row=1, max_row=8, values_only=True):
        values = tuple(clean(v) for v in row)
        if all(name in values for name in required):
            return True
    return False


def parse_sites(wb: Any) -> list[dict[str, Any]]:
    output = []
    for suffix, owner in TO_BY_SUFFIX.items():
        ws = wb[f"B-1-1{suffix}"]
        for row in records(ws, ("Site Code", "Site Name", "Voltage (kV)")):
            code, name, kv = row["Site Code"], row["Site Name"], row["Voltage (kV)"]
            if not isinstance(code, str) or not isinstance(name, str) or not isinstance(kv, (int, float)):
                continue
            output.append({"owner": owner, "site_code": code.strip().upper(),
                           "site_name": name.strip(), "voltage_kv": float(kv)})
    return sorted(output, key=lambda x: (x["owner"], x["site_code"], x["voltage_kv"], x["site_name"]))


def parse_equipment(wb: Any, prefix: str, kind: str, changed: bool) -> list[dict[str, Any]]:
    output = []
    for suffix in TO_BY_SUFFIX:
        ws = wb[f"{prefix}{suffix}"]
        if has_header(ws, ("Node1", "Node2")):
            iterator = records(ws, ("Node1", "Node2"))
            n1, n2 = "Node1", "Node2"
        else:
            iterator = records(ws, ("Node 1", "Node 2"))
            n1, n2 = "Node 1", "Node 2"
        for row in iterator:
            a, b = row.get(n1), row.get(n2)
            if not isinstance(a, str) or not isinstance(b, str):
                continue
            item = {"owner": TO_BY_SUFFIX[suffix], "kind": kind,
                    "node_1": a.strip().upper(), "node_2": b.strip().upper(),
                    "source_sheet": ws.title}
            for source, target in (
                ("Year", "year"), ("Status", "status"),
                ("OHL Length (km)", "ohl_length_km"),
                ("Cable Length (km)", "cable_length_km"),
                ("Circuit Type", "circuit_type"),
                ("R (% on 100 MVA)", "r_percent_100mva"),
                ("R (% on 100MVA)", "r_percent_100mva"),
                ("X (% on 100 MVA)", "x_percent_100mva"),
                ("X (% on 100MVA)", "x_percent_100mva"),
                ("B (% on 100 MVA)", "b_percent_100mva"),
                ("B (% on 100MVA)", "b_percent_100mva"),
                ("Rating (MVA)", "rating_mva"),
                ("Winter Rating (MVA)", "winter_rating_mva"),
                ("Spring Rating (MVA)", "spring_rating_mva"),
                ("Summer Rating (MVA)", "summer_rating_mva"),
                ("Autumn Rating (MVA)", "autumn_rating_mva"),
            ):
                if source in row and row[source] not in (None, ""):
                    item[target] = clean(row[source])
            if changed and ("year" not in item or "status" not in item):
                raise ValueError(f"{ws.title}: planned equipment lacks Year/Status")
            output.append(item)
    return sorted(output, key=lambda x: (x["owner"], x["node_1"], x["node_2"], str(x.get("year", ""))))


def parse_faults(path: Path, demand_case: str) -> list[dict[str, Any]]:
    wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
    output = []
    for ws in wb.worksheets:
        if not re.fullmatch(r"D[123]\.\d", ws.title):
            continue
        title = clean(ws.cell(1, 1).value)
        header = tuple(clean(ws.cell(2, col).value) for col in range(1, 11))
        metric_keys = tuple(FAULT_HEADER_KEYS.get(name) for name in header[2:])
        if (header[:2] != ("Location", "Voltage (kV)") or None in metric_keys
                or metric_keys != FAULT_COLUMNS):
            raise ValueError(f"{ws.title}: fault schema drift: {header}")
        year_index = re.search(r"\b(?:Yr|Year)\s*(\d+)\b", str(title), re.I)
        winter = re.search(r"\b(\d{4}/\d{2})\b", str(title))
        if not year_index or not winter:
            raise ValueError(f"{ws.title}: scenario not found in {title!r}")
        owner = {"1": "SHET", "2": "SPT", "3": "NGET"}[ws.title[1]]
        for source_row, row in enumerate(
                ws.iter_rows(min_row=3, max_col=10, values_only=True), start=3):
            if not isinstance(row[0], str) or not isinstance(row[1], (int, float)):
                continue
            item = {"demand_case": demand_case, "owner": owner,
                    "scenario_year_index": int(year_index.group(1)),
                    "winter": winter.group(1), "node": clean(row[0]).upper(),
                    "voltage_kv": float(row[1]), "source_sheet": ws.title,
                    "source_row": source_row}
            item["published_metric_labels"] = list(header[2:])
            for key, value in zip(metric_keys, row[2:]):
                if not isinstance(value, (int, float)):
                    raise ValueError(f"{ws.title}/{row[0]}: nonnumeric {key}")
                item[key] = float(value)
            output.append(item)
    wb.close()
    return sorted(output, key=lambda x: (x["demand_case"], x["owner"], x["winter"], x["node"]))


def unique(items: list[dict[str, Any]], fields: tuple[str, ...], label: str) -> None:
    seen = set()
    for item in items:
        key = tuple(item.get(field) for field in fields)
        if key in seen:
            raise ValueError(f"duplicate {label}: {key}")
        seen.add(key)


def build(args: argparse.Namespace) -> dict[str, Any]:
    ledger = json.loads((ROOT / "sources.json").read_text(encoding="utf-8"))
    paths = {"appendix_b": args.appendix_b, "fault_peak": args.fault_peak,
             "fault_minimum": args.fault_minimum}
    provenance = {key: pinned(path, key, ledger) for key, path in paths.items()}
    wb = openpyxl.load_workbook(args.appendix_b, read_only=True, data_only=True)
    sites = parse_sites(wb)
    circuits = parse_equipment(wb, "B-2-1", "circuit", False)
    circuit_changes = parse_equipment(wb, "B-2-2", "circuit_change", True)
    transformers = parse_equipment(wb, "B-3-1", "transformer", False)
    transformer_changes = parse_equipment(wb, "B-3-2", "transformer_change", True)
    wb.close()
    faults = parse_faults(args.fault_peak, "peak") + parse_faults(args.fault_minimum, "minimum")
    unique(sites, ("owner", "site_code", "voltage_kv"), "site voltage")
    unique(faults, ("demand_case", "owner", "source_sheet", "source_row"),
           "fault source row")
    return {
        "schema": "data-grid-gb.etys.normalized.v1",
        "edition": "ETYS 2025",
        "claim_boundary": "topology_and_equipment_parameters_not_a_solved_power_flow_case",
        "provenance": provenance,
        "counts": {"sites": len(sites), "circuits": len(circuits),
                   "circuit_changes": len(circuit_changes), "transformers": len(transformers),
                   "transformer_changes": len(transformer_changes), "fault_scenarios": len(faults)},
        "sites": sites, "circuits": circuits, "circuit_changes": circuit_changes,
        "transformers": transformers, "transformer_changes": transformer_changes,
        "fault_scenarios": faults,
    }


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--appendix-b", type=Path, required=True)
    parser.add_argument("--fault-peak", type=Path, required=True)
    parser.add_argument("--fault-minimum", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()
    product = build(args)
    payload = (json.dumps(product, ensure_ascii=False, sort_keys=True,
                          separators=(",", ":")) + "\n").encode("utf-8")
    args.output.parent.mkdir(parents=True, exist_ok=True)
    args.output.write_bytes(payload)
    args.output.with_suffix(args.output.suffix + ".sha256").write_text(
        hashlib.sha256(payload).hexdigest() + "  " + args.output.name + "\n", encoding="ascii", newline="\n")
    print(json.dumps({"output": str(args.output), "sha256": hashlib.sha256(payload).hexdigest(),
                      "counts": product["counts"]}, indent=2))


if __name__ == "__main__":
    main()

Test Contract

A test in the tests folder of Data Grid GB that uses SHA-256 using data from National Energy System Operator (NESO) data portal.

testdata-grid-gb / chatgpt/tests/test_contract.py · lines 1–45 of 45 · Entry point

What it does
It tests its inputs. Defines FeedContractTest, test_mobile_acceptance_words_are_exact, test_source_ledger_is_complete_and_hashes_are_well_formed, test_real_product_if_built. Uses libraries hashlib, json, unittest, pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'chatgpt'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: data source: NESO data portal; JSON file sources.json; JSON file etys-2025.normalized.json.
Downstream impact
It is itself an entry point (test); no other file was found loading it.
What it achieves
It is built from the feed contract test class (`FeedContractTest`). Defines `FeedContractTest`, `test_mobile_acceptance_words_are_exact`, `test_source_ledger_is_complete_and_hashes_are_well_formed` and 1 more.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
data-grid-gb · chatgpt/tests · test
Uses
hashlib, json, unittest, pathlib
Used by
none found
Produces
FeedContractTest
Defines here
FeedContractTest, test_mobile_acceptance_words_are_exact, test_source_ledger_is_complete_and_hashes_are_well_formed, test_real_product_if_built
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
data-grid-gb@4a9cef6c7c791f76d416c8b2fbafac8265f7a263 chatgpt/tests/test_contract.py:1-45 · blob 86550f0be292a5319cd06f0e2a25a2f6e703ce45 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
import hashlib
import json
import unittest
from pathlib import Path


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


class FeedContractTest(unittest.TestCase):
    def test_mobile_acceptance_words_are_exact(self):
        contract = (ROOT / "PRODUCT_CONTRACT.md").read_text(encoding="utf-8")
        self.assertIn("Mobile is the sales surface; it must answer immediately.", contract)

    def test_source_ledger_is_complete_and_hashes_are_well_formed(self):
        ledger = json.loads((ROOT / "sources.json").read_text(encoding="utf-8"))
        self.assertEqual(
            set(ledger["artifacts"]),
            {"appendix_a", "appendix_b", "appendix_c", "fault_minimum", "fault_peak"},
        )
        for artifact in ledger["artifacts"].values():
            self.assertRegex(artifact["sha256"], r"^[0-9a-f]{64}$")
            self.assertGreater(artifact["bytes"], 0)
            self.assertTrue(artifact["url"].startswith("https://www.neso.energy/document/"))

    def test_real_product_if_built(self):
        path = ROOT / "derived" / "etys-2025.normalized.json"
        if not path.exists():
            self.skipTest("derived product has not been built")
        raw = path.read_bytes()
        data = json.loads(raw)
        self.assertEqual(data["counts"]["sites"], len(data["sites"]))
        self.assertEqual(data["counts"]["fault_scenarios"], len(data["fault_scenarios"]))
        sidecar = path.with_suffix(path.suffix + ".sha256").read_text().split()[0]
        self.assertEqual(sidecar, hashlib.sha256(raw).hexdigest())
        cottam = [r for r in data["fault_scenarios"] if r["demand_case"] == "peak"
                  and r["winter"] == "2025/26" and r["node"] == "COTT4 M1"]
        self.assertEqual(len(cottam), 1)
        self.assertAlmostEqual(cottam[0]["three_phase_initial_peak_current_ka"],
                               109.219270174868, places=10)
        self.assertIn("three_phase_rms_break_current_ka", cottam[0])


if __name__ == "__main__":
    unittest.main()

ChatGPT Verify Product

A Python command-line tool in Data Grid GB that uses SHA-256.

ingestdata-grid-gb / chatgpt/verify_product.py · lines 1–40 of 40 · Entry point · pattern require (shared by 53 files)

What it does
It loads data. Defines require, main. Uses libraries __future__, hashlib, json, sys, pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'chatgpt'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: command-line arguments.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Defines `require`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
data-grid-gb · chatgpt · Python CLI
Uses
__future__, hashlib, json, sys, pathlib
Used by
none found
Produces
require, main
Defines here
require, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
data-grid-gb@4a9cef6c7c791f76d416c8b2fbafac8265f7a263 chatgpt/verify_product.py:1-40 · blob e1332f7f388cd750a417bc37e463943d03bfeb15 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
#!/usr/bin/env python3
from __future__ import annotations

import hashlib
import json
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent


def require(condition: bool, message: str) -> None:
    if not condition:
        raise AssertionError(message)


def main() -> None:
    path = Path(sys.argv[1])
    raw = path.read_bytes()
    data = json.loads(raw)
    require(raw.endswith(b"\n"), "canonical product must end LF")
    require(data["schema"] == "data-grid-gb.etys.normalized.v1", "schema")
    require(data["claim_boundary"] == "topology_and_equipment_parameters_not_a_solved_power_flow_case", "claim boundary")
    require("Mobile is the sales surface; it must answer immediately." in
            (ROOT / "PRODUCT_CONTRACT.md").read_text(encoding="utf-8"), "mobile acceptance phrase")
    require(data["counts"]["sites"] == len(data["sites"]), "site count")
    require(data["counts"]["fault_scenarios"] == len(data["fault_scenarios"]), "fault count")
    cottam = [x for x in data["fault_scenarios"] if x["demand_case"] == "peak"
              and x["winter"] == "2025/26" and x["node"] == "COTT4 M1"]
    require(len(cottam) == 1, "exact Cottam peak scenario")
    require(abs(cottam[0]["three_phase_initial_peak_current_ka"] - 109.219270174868) < 1e-10,
            "Cottam exact metric semantics")
    require("three_phase_rms_break_current_ka" in cottam[0], "separate RMS metric")
    sidecar = path.with_suffix(path.suffix + ".sha256").read_text(encoding="ascii").split()[0]
    require(sidecar == hashlib.sha256(raw).hexdigest(), "sidecar hash")
    print(f"PASS {path} {sidecar} counts={data['counts']}")


if __name__ == "__main__":
    main()

Gemini

A style sheet in the assets folder covering solar.

rendergemini / docs/assets/gemini.css · lines 1–25 of 25 · Not reached from any entry point (candidate for review)

What it does
Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage agent_infra (path word 'gemini'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). Domain terms in the code: solar.
What it achieves
Adapted Pipeline News newspaper components; provenance in `UI-SOURCES.md`.
Why it matters
No other file in the estate was found to import it.
Application
gemini · docs/assets · style sheet
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
gemini@bf5d9f7de72c07ce57ec64864ac5181cc46c8381 docs/assets/gemini.css:1-25 · blob 7f8096a96a6c3b15a35c668f5312df4b638741a6 · GitHub at these lines
State
achieves: comment · context: auto · stage: output · effects: dom · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
/* Adapted Pipeline News newspaper components; provenance in UI-SOURCES.md. */
:root{--solar:#66ccff;--accent:#00ffff;--ok:#00ff88;--panel:#0b0e14;--soft:#222}
.meta{display:flex;gap:12px;flex-wrap:wrap;margin-bottom:18px;padding:9px 12px;border:1px solid #24323a;background:#071018;color:var(--muted);font-size:11px}
.meta strong{color:var(--accent)}
.meta a{color:#66ccff}
.newspaper{border:1px solid #424b55;background:#06080b;margin-bottom:28px;box-shadow:0 0 22px rgba(0,255,255,.04)}
.masthead{padding:16px 18px 12px;border-bottom:1px solid #424b55}
.masthead h2{font-size:24px;line-height:1;color:#fff;letter-spacing:2px}
.masthead h2 span{color:var(--solar)}
.strap{display:flex;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-top:8px;color:#8e98a5;font-size:10px;text-transform:uppercase}
.stories{display:grid;grid-template-columns:repeat(3,minmax(280px,1fr));align-items:stretch}
.story{display:block;padding:18px;border-right:1px solid #252a31;border-bottom:1px solid #252a31;text-decoration:none;min-height:180px;background:#07090c}
.story:hover{background:#0b0f14}
.story .kicker{font-size:10px;font-weight:bold;letter-spacing:.5px}
.story h3{color:#fff;font-size:17px;line-height:1.28;margin:9px 0 12px}
.story p{color:#aeb6c1;font-size:11px;line-height:1.55}
.story .source{display:block;color:#7f8996;margin-top:12px;font-size:10px}
.section-title{font-size:14px;color:var(--accent);letter-spacing:1px;margin:0 0 12px}
.signal{display:inline-block;padding:4px 6px;border:1px solid #3b444f;background:#090b0f;color:#9aa3af;font-size:9px;font-weight:bold;white-space:nowrap}
.stories{grid-template-columns:repeat(2,minmax(280px,1fr))}
.masthead h2{font-size:20px}
.stories{grid-template-columns:1fr}
.newspaper{margin:0 0 24px}.masthead h2{font-size:20px;line-height:1.3}.strap{line-height:1.5}
.stories{grid-template-columns:repeat(2,minmax(0,1fr))}.story{min-height:0;padding:16px;overflow-wrap:anywhere}.story .kicker{color:var(--green)}.story h3{font-size:16px}.story p{font-size:13px}.story .source{color:var(--muted)}.story:hover h3{color:var(--cyan)}
.meta{overflow-wrap:anywhere;display:block;line-height:1.8}.meta strong{display:block}.bridge-nav{display:flex;flex-wrap:wrap;gap:8px 20px;margin:0 0 24px;font-size:13px}.bridge-nav a{padding:8px 0}.bridge-status{font-size:12px;color:var(--muted)}.inside .launch{margin:0 6px 8px 0}.source-key{overflow-wrap:anywhere}.manifest-list{margin:0;padding:0;list-style:none}.manifest-list li{padding:10px 0;  … [line shortened here: 913 characters; full line on GitHub]

Gemini Build Manifest

A Python command-line tool in the scripts folder that reads sources and packets, using SHA-256.

storagegemini / scripts/build_manifest.py · lines 1–105 of 105 · Entry point · pattern publish (shared by 21 files)

What it does
It loads sources and packets. Defines esc, write, build, publish. Uses libraries os, json, hashlib, datetime, pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'gemini'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file SOURCES.json; JSON file PACKETS.json.
Downstream impact
Used directly by 1 file: Publish Gemini Bridge Workflow (gemini).
What it achieves
It is built from the esc step (`esc`), the write step (`write`) and the build step (`build`). Deterministic static publication; Python 3.11+, standard library. It writes `robots.txt`.
Why it matters
Run by Publish Gemini Bridge Workflow.
Application
gemini · scripts · Python CLI
Uses
UI Render Home (import), UI Packets (import), os, json, hashlib, datetime, pathlib
Used by
run by Publish Gemini Bridge Workflow (workflow run)
Produces
esc, write, build
Defines here
esc, write, build, publish
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gemini@bf5d9f7de72c07ce57ec64864ac5181cc46c8381 scripts/build_manifest.py:1-105 · blob 4c9049ddf13fec325af84aeb3ef5f97a90c0fa72 · GitHub at these lines
State
achieves: comment · context: auto · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
"""Deterministic static publication; Python 3.11+, standard library."""
import os
import json
import hashlib
import datetime
import pathlib
from ui.render_home import render_home
from ui.packets import packet_documents, sitemap

ROOT = pathlib.Path(__file__).resolve().parents[1]
DOCS = ROOT / "docs"
BASE = "https://ventusltd.github.io/gemini/"
RAW = "https://raw.githubusercontent.com/Ventusltd/gemini/main/"
ALLOWED = {".md", ".json", ".py", ".sql"}
LIMIT = 512 * 1024

def esc(s):
    return str(s).replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace('"', "&quot;")

def write(path, data):
    p = DOCS / path
    p.parent.mkdir(parents=True, exist_ok=True)
    p.write_bytes(data if isinstance(data, bytes) else data.encode("utf-8"))

def build():
    sha = os.environ["BRIDGE_SOURCE_SHA"]
    stamp = datetime.datetime.fromisoformat(os.environ["BRIDGE_SOURCE_DATE"].replace("Z", "+00:00")).astimezone(datetime.timezone.utc).isoformat()
    if len(sha) != 40 or any(c not in "0123456789abcdef" for c in sha):
        raise ValueError("invalid source SHA")
    artifacts = []
    expected = set()
    def publish(repo_path, dest, data, category, summary):
        write(dest, data)
        expected.add(dest)
        artifacts.append(dict(id=dest, title=pathlib.Path(repo_path).stem.replace("_", " "), category=category, repo_path=repo_path, pages_url=BASE+dest, raw_url=RAW+repo_path, sha256=hashlib.sha256(data).hexdigest(), summary=summary))
    for folder in ("context", "handoff"):
        for p in sorted((ROOT / folder).rglob("*")):
            if p.is_symlink():
                raise ValueError("symlinks not permitted")
            if not p.is_file() or p.suffix.lower() not in ALLOWED:
                continue
            rel = p.relative_to(ROOT).as_posix()
            if any(not (c.isascii() and (c.isalnum() or c in "/._-")) for c in rel):
                raise ValueError("unsafe path: "+rel)
            data = p.read_bytes()
            if len(data) > LIMIT:
                raise ValueError("artifact exceeds limit: "+rel)
            content = data.decode("utf-8")
            category = "handoff" if folder == "handoff" else "satnav" if "SATNAV" in rel else "grid_data" if "SCHEMAS" in rel else "architecture"
            summary = next((line.strip("# ").strip() for line in content.splitlines() if line.strip()), rel)[:180]
            publish(rel, "files/"+rel, data, category, summary)
    bundle = []
    for name in ("ACTIVE_TASKS.md", "SATNAV_ARCHITECTURE.md", "SCHEMAS_AND_PROFILES.md", "AGENT_PROTOCOL.md", "SOURCES.json"):
        rel = "context/"+name
        bundle.append("=== FILE: "+rel+" ===\n"+(ROOT / rel).read_text(encoding="utf-8"))
    publish("docs/CONTEXT_BUNDLE.md", "CONTEXT_BUNDLE.md", "\n\n".join(bundle).encode("utf-8"), "architecture", "Compact entry point for independent AI review")
    publish("context/ACTIVE_TASKS.md", "ACTIVE_TASKS.md", (ROOT/"context/ACTIVE_TASKS.md").read_bytes(), "architecture", "Current review assignment")
    for p in sorted((DOCS/"files").rglob("*")):
        if p.is_file() and p.relative_to(DOCS).as_posix() not in expected:
            p.unlink()
    packet_index = json.loads((ROOT/"context/PACKETS.json").read_text(encoding="utf-8"))
    for dest, data, summary in packet_documents(packet_index["packets"], esc, BASE):
        publish("docs/"+dest, dest, data, "packet", summary)
    receipt = (ROOT/"handoff/GEMINI_INC_001.md").read_bytes()
    publish("handoff/GEMINI_INC_001.md", "handoff/GEMINI_INC_001.md", receipt, "handoff", "Gemini report digest")
    for p in (DOCS/"packets").glob("*"):
        if p.is_file() and p.relative_to(DOCS).as_posix() not in expected:
            p.unlink()
    write("sitemap.xml", sitemap(BASE, stamp, ["", "index.html", "MANIFEST.json"]+list(expected)))
    write("robots.txt", "User-agent: *\nAllow: /\nSitemap: "+BASE+"sitemap.xml\n")
    manifest = dict(schema="ventus.gemini.bridge.v1", generated_at_utc=stamp, source_commit=sha, repo="Ventusltd/gemini", pages_base_url=BASE, raw_base_url=RAW, artifacts=artifacts)
    write("MANIFEST.json", json.dumps(manifest, indent=2, sort_keys=True)+"\n")
    # Keep machine-readable artifacts identical; render the directory from the same manifest.
    source_index = json.loads((ROOT / "context/SOURCES.json").read_text(encoding="utf-8"))
    source_rows = []
    for source in source_index["sources"]:
        name = source["repository"].split("/")[-1]
        public_url = "https://ventusltd.github.io/" + name + "/"
        if name == "globalgrid2050":
            public_url = "https://www.globalgrid2050.com/"
        links = '<a href="' + esc(source["tree_url"]) + '">Pinned source</a>'
        if name in ("spiders", "kuiper-belt", "vedic-", "gridatlas", "satnav", "globalgrid2050"):
            links += '<a href="' + esc(public_url) + '">Public website</a>'
        if name == "spiders":
            links += '<a href="' + esc(source["tree_url"] + "/species/genome-spider") + '">Genome Spider</a>'
        source_rows.append('<li><strong>' + esc(name) + '</strong><small>' + esc(source["commit"]) + '</small>' + links + '</li>')
    cards = []
    for label, title, desc, href in (
        ("Assignment", "Active tasks", "Read the current independent engineering review.", "ACTIVE_TASKS.md"),
        ("Context", "Context bundle", "One compact document for AI retrieval.", "CONTEXT_BUNDLE.md"),
        ("Evidence", "Source index", "Immutable repository revisions and source links.", "files/context/SOURCES.json"),
        ("Protocol", "Agent coordination", "Reuse existing work; return evidence and bounded patches.", "files/context/AGENT_PROTOCOL.md"),
    ):
        cards.append('<a class="story" href="' + esc(href) + '"><span class="kicker">' + esc(label) + '</span><h3>' + esc(title) + '</h3><p>' + esc(desc) + '</p><span class="source">Open document</span></a>')
    sources = json.loads((ROOT/"context/SOURCES.json").read_text(encoding="utf-8"))["sources"]
    write("index.html", render_home(sha, stamp, artifacts, sources, esc, BASE))
    for name in ("globalgrid2050.css", "gemini.css"):
        write("assets/"+name, (ROOT/"scripts/ui"/name).read_bytes())
    for name in ("UI-SOURCES.md", "PIPELINE-LICENSE.txt", "PIPELINE-NOTICE.txt"):
        write(name, (ROOT/"scripts/ui"/name).read_bytes())
    write(".nojekyll", b"")
    print("Published", len(artifacts), "artifacts from", sha)

if __name__ == "__main__":
    build()

UI Packets

A Python module in the scripts folder of Gemini that works with packet documents (`packet_documents`), using SHA-256. It is built from the sitemap step (`sitemap`).

transformgemini / scripts/ui/packets.py · lines 1–40 of 40

What it does
It calculates its inputs. Defines packet_documents, sitemap. Uses libraries xml.etree.ElementTree.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'gemini'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Downstream impact
Used directly by 1 file: Gemini Build Manifest (gemini). Reached from 1 other entry point, including Publish Gemini Bridge Workflow (gemini).
What it achieves
Bounded static packets from curated immutable source evidence.
Why it matters
Imported by Gemini Build Manifest.
Application
gemini · scripts/ui · Python module
Uses
xml.etree.ElementTree
Used by
imported by Gemini Build Manifest (import)
Produces
packet_documents, sitemap
Defines here
packet_documents, sitemap
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gemini@bf5d9f7de72c07ce57ec64864ac5181cc46c8381 scripts/ui/packets.py:1-40 · blob dc6dae7111cfda1f722bab2951fc5118ed2cc037 · GitHub at these lines
State
achieves: comment · context: auto · stage: transform · effects: none found · domain stage: agent_infra · users: ai_agent · canonical: unknown
"""Bounded static packets from curated immutable source evidence."""
from xml.etree.ElementTree import Element, SubElement, tostring

def packet_documents(packets, esc, base):
    for p in packets:
        title=p["title"]
        lines=["# "+title,*p["sections"]]
        body="".join("<p>"+esc(x)+"</p>" for x in p["sections"])
        for s in p["sources"]:
            url="https://github.com/"+s["repository"]+"/tree/"+s["commit"]
            lines.append("## "+s["repository"]+" | "+s["branch"]+" | "+s["commit"]+"\n"+url)
            body+='<h2>'+esc(s["repository"])+'</h2><p>Branch: '+esc(s["branch"])+' · <a href="'+esc(url)+'">Commit '+esc(s["commit"])+'</a></p>'
            if s.get("public_url"):
                lines.append("Discovery target: "+s["public_url"])
                body+='<p><a href="'+esc(s["public_url"])+'">Public discovery target</a></p>'
            body+="<ul>"
            for f in s["files"]:
                url="https://github.com/"+s["repository"]+"/blob/"+s["commit"]+"/"+f
                lines.append("- "+f+" | "+url)
                body+='<li><a href="'+esc(url)+'">'+esc(f)+'</a></li>'
            body+="</ul>"
        for c in p.get("commands",[]):
            entry=[c["word"],c["signature"] or c["symbol"],"Inputs: "+"; ".join(c["inputs"]),"Output: "+c["output"],"Limits: "+c["limits"],"Evidence: "+c["receipt"],"Source SHA-256: "+c["source_sha256"]]
            lines.extend(entry)
            body+="<h2>"+esc(entry[0])+"</h2><p><code>"+esc(entry[1])+"</code></p>"+"".join("<p>"+esc(x)+"</p>" for x in entry[2:5])+'<p><a href="'+esc(c["receipt"])+'">Pinned source span</a> · SHA-256 '+esc(c["source_sha256"])+'</p>'
        slug=p["id"]
        md=("\n\n".join(lines)+"\n").encode()
        html=('<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="description" content="'+esc(title)+'"><link rel="canonical" href="'+base+'packets/'+slug+'.html"><link rel="stylesheet" href="../assets/globalgrid2050.css"><title>'+esc(title)+' | GlobalGrid2050 Gemini</title></head><body><header><p class="brand">  … [line shortened here: 710 characters; full line on GitHub]
        for ext,data in (("md",md),("html",html)):
            if len(data)>15000:
                raise ValueError("packet exceeds 15 KB: "+slug+"."+ext)
            yield "packets/"+slug+"."+ext,data,title

def sitemap(base, stamp, paths):
    root=Element("urlset",xmlns="http://www.sitemaps.org/schemas/sitemap/0.9")
    for path in sorted(set(paths)):
        entry=SubElement(root,"url")
        SubElement(entry,"loc").text=base+path
        SubElement(entry,"lastmod").text=stamp
    return tostring(root,encoding="utf-8",xml_declaration=True)+b"\n"

UI Render Home

A Python module in the scripts folder of Gemini covering sources, using SHA-256 and uses data from the kuiper-belt repository.

transformgemini / scripts/ui/render_home.py · lines 1–32 of 32 · pattern section (shared by 12 files)

What it does
It calculates sources. Defines render_home, link, section.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'gemini'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file SOURCES.json.
Downstream impact
Used directly by 1 file: Gemini Build Manifest (gemini). Reached from 1 other entry point, including Publish Gemini Bridge Workflow (gemini).
What it achieves
It renders home (`render_home`) and is built from the link step (`link`) and the section step (`section`). Static presentation, independent of manifest data and API endpoints.
Why it matters
Imported by Gemini Build Manifest.
Application
gemini · scripts/ui · Python module
Uses
none found
Used by
imported by Gemini Build Manifest (import)
Produces
render_home
Defines here
render_home, link, section
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gemini@bf5d9f7de72c07ce57ec64864ac5181cc46c8381 scripts/ui/render_home.py:1-32 · blob a8521cf8e5c379d4ecd8df5619bde3a22a6afe38 · GitHub at these lines
State
achieves: comment · context: auto · stage: transform · effects: none found · domain stage: agent_infra · users: ai_agent · canonical: unknown
"""Static presentation, independent of manifest data and API endpoints."""
def render_home(sha, stamp, artifacts, sources, esc, base):
    def link(path, label, cls=""):
        return '<a class="'+cls+'" href="'+esc(path)+'">'+esc(label)+'</a>'
    def section(n, title, subtitle, body, id):
        return '<details id="'+id+'"><summary><span class="number">'+n+'</span><span class="title">'+title+'<small>'+subtitle+'</small></span></summary><div class="inside">'+body+'</div></details>'
    cards = [
        ("START HERE", "Kuiper modular agent start", "Canonical source keys and selective lookup for all agents.", "https://ventusltd.github.io/kuiper-belt/agents/"),
        ("MACHINE READABLE", "Manifest", "Artifact catalogue, source revision and SHA-256 checksums.", "MANIFEST.json"),
        ("ASSIGNMENT 003", "Active tasks", "Current scope, evidence and next engineering contribution.", "ACTIVE_TASKS.md"),
        ("HANDOVER", "Gemini notes", "Review inbox; patches require authorised integration.", "files/handoff/GEMINI_NOTES.md"),
    ]
    stories = "".join('<a class="story" href="'+esc(path)+'"><span class="kicker">'+esc(tag)+'</span><h3>'+esc(title)+'</h3><p>'+esc(desc)+'</p><span class="source">OPEN RESOURCE</span></a>' for tag,title,desc,path in cards)
    names = {"spiders":"Spider and Genome Spider","kuiper-belt":"Kuiper","vedic-":"Vedic","gridatlas":"GridAtlas","satnav":"SatNav","globalgrid2050":"GlobalGrid2050","neural-link-between-agents":"Neural Link"}
    source_rows = []
    for s in sources:
        name = s["repository"].split("/")[-1]
        source_rows.append('<li><strong>'+esc(names.get(name,name))+'</strong><small class="source-key">'+esc(s["commit"])+'</small>'+link(s["tree_url"],"Pinned source")+'</li>')
    source_body = '<p>Historical Increment 001–002 source pins. For current default-branch keys use Kuiper modular agent start. The snapshots below are not live acceptance.</p>'+link("files/context/SOURCES.json","Source index (JSON)","launch")+'<ul class="manifest-list">'+''.join(source_rows)+'</ul>'
    rows = ''.join('<li>'+link(a["pages_url"].removeprefix(base),a["title"])+link(a["raw_url"],"Raw GitHub")+'<small>'+esc(a["summary"])+'</small></li>' for a in artifacts)
    return ('<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="description" content="Public Gemini engineering context, source manifests and agent handovers for Ventus GlobalGrid2050."><title>GlobalGrid2050 | Gemini</title><link rel="stylesheet" href="assets/globalgrid2050.css"><link rel="stylesheet" href="asse  … [line shortened here: 429 characters; full line on GitHub]
        '<header><h1 class="brand">GLOBALGRID2050 / GEMINI</h1><p class="mission">Gemini Engineering Bridge</p><p class="bridge-intro">Gemini is an adapter into Kuiper: one shared engineering address space, not a separate estate database.</p></header>'
        '<main><nav class="bridge-nav" aria-label="Primary resources">'+link("https://globalgrid2050.com/","GlobalGrid2050")+link("https://ventusltd.github.io/kuiper-belt/agents/","Kuiper start")+link("MANIFEST.json","Manifest")+link("CONTEXT_BUNDLE.md","Context bundle")+link("ACTIVE_TASKS.md","Active tasks")+'</nav>'
        '<div class="meta"><strong>PUBLIC READ-ONLY · INCREMENT 003</strong>Source timestamp UTC: '+esc(stamp)+'<br>Source revision: <code>'+esc(sha)+'</code><br>'+str(len(artifacts))+' published artifacts · '+str(len(sources))+' source repositories</div>'
        '<section class="newspaper" aria-label="Engineering resources"><div class="masthead"><h2>GEMINI <span>INTELLIGENCE</span></h2><div class="strap"><span>Shared engineering context</span><span>Evidence before claims</span></div></div><div class="stories">'+stories+'</div></section>'
        '<h2 class="sections-heading">Browse sections</h2><section aria-label="Engineering directory">'
        +section("01","Engineering instruments","Spider · Genome Spider · Kuiper · Vedic",source_body,"instruments")
        +section("02","SatNav and GridAtlas","Architecture · schemas · routing profiles",'<p>Review verified sources before proposing new designs.</p>'+link("files/context/SATNAV_ARCHITECTURE.md","SatNav architecture","launch")+link("files/context/SCHEMAS_AND_PROFILES.md","Schemas and profiles","launch"),"satnav")
        +section("03","Agent coordination","Protocol · tasks · handovers",link("files/context/AGENT_PROTOCOL.md","Agent protocol","launch")+link("ACTIVE_TASKS.md","Active tasks","launch")+link("files/handoff/GEMINI_NOTES.md","Handoff inbox","launch"),"coordination")
        +'<section aria-label="Intelligence packets"><h2 class="sections-heading">Engineering intelligence packets</h2><ul class="manifest-list">'+''.join('<li>'+link(a["pages_url"].removeprefix(base),a["summary"])+'</li>' for a in artifacts if a["id"].startswith("packets/") and a["id"].endswith(".html"))+'</ul></section>'
        +section("04","Published catalogue","All artifacts · source and raw links",'<ul class="manifest-list">'+rows+'</ul>',"catalogue")
        +'</section></main><footer><p>Ventus Ltd · GlobalGrid2050 · Read-only AI interoperability.</p><p>Source timestamps are not live acceptance. No automatic engineering patch execution.</p><p>'+link("UI-SOURCES.md","UI provenance and licence")+'</p></footer></body></html>\n')