GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / AI agents and coordination / claude / sessions/202609021835-estate-and-corridor/scripts

Rail and 9 more files

A Python command-line tool in the scripts folder of Claude that builds index (`build_index`) and counts crossings (`count_crossings`), covering UK mainline railways, using haversine.

658 lines of Python and Shell from claude, in 10 files. Topic: AI agents and coordination. Section 1613 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. Parquet Count storage · claude / sessions/202609021835-estate-and-corridor/scripts/parquet_count.py lines 1–70
  2. Rail ingest · claude / sessions/202609021835-estate-and-corridor/scripts/rail.py lines 1–100
  3. Run Study storage · claude / sessions/202609021835-estate-and-corridor/scripts/run_study.py lines 1–66
  4. Sanitise storage · claude / sessions/202609021835-estate-and-corridor/scripts/sanitise.py lines 1–61
  5. Sanity storage · claude / sessions/202609021835-estate-and-corridor/scripts/sanity.py lines 1–88
  6. Sweep storage · claude / sessions/202609021835-estate-and-corridor/scripts/sweep.py lines 1–80
  7. Verify Cowley other · claude / sessions/202609021835-estate-and-corridor/scripts/verify_cowley.py lines 1–99
  8. Verify Homepage other · claude / sessions/202609021835-estate-and-corridor/scripts/verify_homepage.py lines 1–43
  9. Census storage · claude / sessions/202609030120-cicd-spider/census.py lines 1–36
  10. CI Log automation · claude / sessions/202609030120-cicd-spider/ci-log.sh lines 1–15

Parquet Count

A Python module in the scripts folder of Claude.

storageclaude / sessions/202609021835-estate-and-corridor/scripts/parquet_count.py · lines 1–70 of 70 · version 2026-09-02 18:35 · Not reached from any entry point (candidate for review)

What it does
It loads data. Uses libraries subprocess, collections, os, io, sys. Side effects: reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'claude'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
Out: JSON file parquet.json.
What it achieves
Count datapoints held in Parquet, which the text-based count could not see. It writes `parquet.json`.
Why it matters
No other file in the estate was found to import it.
Application
claude · sessions/202609021835-estate-and-corridor/scripts · Python module
Uses
subprocess, collections, os, io, sys, json, pyarrow.parquet
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
claude@df9da02425fdf0c65d11a84f32cd9b3ef927b309 sessions/202609021835-estate-and-corridor/scripts/parquet_count.py:1-70 · blob f40933ab8213c616714aced033371f82e134d39d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process, storage · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
"""Count datapoints held in parquet, which the text-based count could not see.

One datapoint = one cell = rows x columns, read from the parquet footer
metadata (no full decompression). Counted once per unique git blob.
"""
import subprocess, collections, os, io, sys, json
import pyarrow.parquet as pq

ROOT  = '../clones'
REPOS = ["chatgpt-audits","companies","cvaa","data-centres-gb",
         "data-federation-map-for-globalgrid2050-all-repos","data-gb-electricity",
         "data-grid-gb","data-gridatlas","data-interconnectors","gb-electricity-ui",
         "globalgrid2050","grid-distance-maths","gridatlas","pipelinenews","spiders"]

seen, jobs, copies = set(), [], 0
for r in REPOS:
    ref = None
    for c in ('gh/main', 'gh/master'):
        if subprocess.run(['git', '-C', os.path.join(ROOT, r), 'rev-parse', '--verify', '-q', c],
                          capture_output=True).returncode == 0:
            ref = c
            break
    if not ref:
        continue
    out = subprocess.run(['git', '-C', os.path.join(ROOT, r), 'ls-tree', '-r', '-l', ref],
                         capture_output=True, text=True, errors='replace').stdout
    for line in out.splitlines():
        try:
            meta, path = line.split('\t', 1)
            p = meta.split()
            sha, size = p[2], (int(p[3]) if p[3].isdigit() else 0)
        except Exception:
            continue
        if not path.lower().endswith('.parquet'):
            continue
        copies += 1
        if sha in seen:
            continue
        seen.add(sha)
        jobs.append((r, sha, path, size))

rows = cells = ok = bad = 0
cols_seen = collections.Counter()
byrepo = collections.Counter()
for r, sha, path, size in jobs:
    try:
        blob = subprocess.run(['git', '-C', os.path.join(ROOT, r), 'cat-file', 'blob', sha],
                              capture_output=True, timeout=300).stdout
        f = pq.ParquetFile(io.BytesIO(blob))
        nr = f.metadata.num_rows
        nc = f.metadata.num_columns
        rows += nr
        cells += nr * nc
        cols_seen[nc] += 1
        byrepo[r] += nr * nc
        ok += 1
    except Exception:
        bad += 1

print('unique parquet blobs : %s   (of %s copies on disk)' % (f'{len(jobs):,}', f'{copies:,}'))
print('read successfully    : %s   unreadable %d' % (f'{ok:,}', bad))
print('rows                 : %s' % f'{rows:,}')
print('cells (datapoints)   : %s' % f'{cells:,}')
print('typical column counts: %s' % ', '.join(f'{c} cols x{n}' for c, n in cols_seen.most_common(5)))
print()
print('by repository (ordinal order withheld):')
for r, n in byrepo.most_common():
    print('   %-52s %14s' % (r, f'{n:,}'))
json.dump({'unique_blobs': len(jobs), 'copies': copies, 'rows': rows, 'cells': cells},
          open('parquet.json', 'w'), indent=1)

Rail

A Python command-line tool in the scripts folder of Claude that builds index (`build_index`) and counts crossings (`count_crossings`), covering UK mainline railways, using haversine.

ingestclaude / sessions/202609021835-estate-and-corridor/scripts/rail.py · lines 1–100 of 100 · version 2026-09-02 18:35 · Entry point · pattern build_index (shared by 3 files)

What it does
Defines 7 functions or classes, including load_rail_segments, build_index, _orient, seg_intersect, RailIndex. Uses libraries json, os, array, math, time.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'claude'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Downstream impact
Used directly by 2 files: Crossings (claude); Edge Rail (claude).
What it achieves
It loads rail segments (`load_rail_segments`) and is built from the seg intersect helper (`seg_intersect`) and the rail index class (`RailIndex`). Railway crossing counting: spatial index over mainline railway segments. It reads `uk_mainline_railways.geojson`.
Why it matters
Imported by Crossings and Edge Rail.
Application
claude · sessions/202609021835-estate-and-corridor/scripts · Python CLI
Uses
Sessions — Estate and Corridor (import), Build Graph (import), json, os, array, math, time, gc
Used by
imported by Crossings (import), imported by Edge Rail (import)
Produces
load_rail_segments, build_index, seg_intersect, RailIndex
Defines here
load_rail_segments, build_index, _orient, seg_intersect, RailIndex, __init__, count_crossings
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
claude@df9da02425fdf0c65d11a84f32cd9b3ef927b309 sessions/202609021835-estate-and-corridor/scripts/rail.py:1-100 · blob 880c3eee4f9b760b43e0fdbded18fbe733b99637 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: agent_infra · users: ai_agent · canonical: unknown
"""Railway crossing counting: spatial index over mainline railway segments."""
import json, os, array, math, time, gc
from common import haversine, HERE
from build_graph import read_blob

CELL = 0.01  # ~1.1 km lat


def load_rail_segments():
    """Flat arrays of segment endpoints (lon1,lat1,lon2,lat2)."""
    raw = read_blob("uk_mainline_railways.geojson")
    gj = json.loads(raw); del raw
    seg = array.array("d")
    nl = 0
    for f in gj["features"]:
        g = f.get("geometry")
        if not g: continue
        gt = g.get("type")
        if gt == "LineString": lines = [g["coordinates"]]
        elif gt == "MultiLineString": lines = g["coordinates"]
        else: continue
        for ln in lines:
            if len(ln) < 2: continue
            nl += 1
            for i in range(len(ln) - 1):
                seg.append(ln[i][0]); seg.append(ln[i][1])
                seg.append(ln[i + 1][0]); seg.append(ln[i + 1][1])
    del gj; gc.collect()
    return seg, nl


def build_index(seg, cell=CELL):
    """Grid hash: cell -> list of segment indices."""
    idx = {}
    n = len(seg) // 4
    for s in range(n):
        x1 = seg[4 * s]; y1 = seg[4 * s + 1]
        x2 = seg[4 * s + 2]; y2 = seg[4 * s + 3]
        i1 = int(math.floor(y1 / cell)); j1 = int(math.floor(x1 / cell))
        i2 = int(math.floor(y2 / cell)); j2 = int(math.floor(x2 / cell))
        for i in range(min(i1, i2), max(i1, i2) + 1):
            for j in range(min(j1, j2), max(j1, j2) + 1):
                b = idx.get((i, j))
                if b is None: idx[(i, j)] = [s]
                else: b.append(s)
    return idx


def _orient(ax, ay, bx, by, cx, cy):
    v = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax)
    if v > 1e-14: return 1
    if v < -1e-14: return -1
    return 0


def seg_intersect(ax, ay, bx, by, cx, cy, dx, dy):
    """Proper segment intersection in lon/lat plane (fine at GB scale)."""
    d1 = _orient(cx, cy, dx, dy, ax, ay)
    d2 = _orient(cx, cy, dx, dy, bx, by)
    d3 = _orient(ax, ay, bx, by, cx, cy)
    d4 = _orient(ax, ay, bx, by, dx, dy)
    return d1 != d2 and d3 != d4 and d1 != 0 and d2 != 0 and d3 != 0 and d4 != 0


class RailIndex:
    def __init__(self, cell=CELL):
        t0 = time.time()
        self.seg, self.nlines = load_rail_segments()
        self.nseg = len(self.seg) // 4
        self.idx = build_index(self.seg, cell)
        self.cell = cell
        self.build_seconds = time.time() - t0

    def count_crossings(self, poly, dedup=True):
        """poly: flat [lon,lat,...]. Returns number of railway segments crossed."""
        seg = self.seg; idx = self.idx; cell = self.cell
        hits = set()
        npts = len(poly) // 2
        for k in range(npts - 1):
            ax = poly[2 * k]; ay = poly[2 * k + 1]
            bx = poly[2 * k + 2]; by = poly[2 * k + 3]
            i1 = int(math.floor(ay / cell)); j1 = int(math.floor(ax / cell))
            i2 = int(math.floor(by / cell)); j2 = int(math.floor(bx / cell))
            cand = set()
            for i in range(min(i1, i2), max(i1, i2) + 1):
                for j in range(min(j1, j2), max(j1, j2) + 1):
                    b = idx.get((i, j))
                    if b: cand.update(b)
            for s in cand:
                if seg_intersect(ax, ay, bx, by,
                                 seg[4 * s], seg[4 * s + 1],
                                 seg[4 * s + 2], seg[4 * s + 3]):
                    hits.add(s if dedup else (k, s))
        return len(hits)


if __name__ == "__main__":
    R = RailIndex()
    print("rail lines=%d segments=%d cells=%d build=%.1fs" %
          (R.nlines, R.nseg, len(R.idx), R.build_seconds))

Run Study

A Python command-line tool in the scripts folder of Claude that reads routes and validation set, using haversine. It is built from the run step (`run`).

storageclaude / sessions/202609021835-estate-and-corridor/scripts/run_study.py · lines 1–66 of 66 · version 2026-09-02 18:35 · Entry point

What it does
It loads routes and validation set. Defines run. Uses libraries json, os, sys, time, collections. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'claude'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file out_routes.json; JSON file validation_set.json; command-line arguments. Out: JSON file.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Route the 95 cable circuits and measure routed vs straight vs published.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
claude · sessions/202609021835-estate-and-corridor/scripts · Python CLI
Uses
Sessions — Estate and Corridor (import), Router (import), json, os, sys, time, collections
Used by
none found
Produces
run
Defines here
run
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
claude@df9da02425fdf0c65d11a84f32cd9b3ef927b309 sessions/202609021835-estate-and-corridor/scripts/run_study.py:1-66 · blob 77d3ec72ffbd9227a560fe57b9028b72bf01ff89 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
"""Route the 95 cable circuits and measure routed vs straight vs published.

Definitions (kept explicit because the snap distance must never be hidden):
  straight_km      great-circle between the two SITE coordinates          [baseline]
  snap1/snap2      site -> nearest routable road junction                 [reported]
  routed_core_km   A* road distance between the two SNAPPED junctions
  routed_total_km  snap1 + routed_core_km + snap2                         [candidate]
  published_km     NESO cable_km for the circuit                          [truth]
"""
import json, os, sys, time
from common import haversine, HERE
from router import Graph

MAX_SNAP_KM = 5.0


def run(pre="roads", out="out_routes.json"):
    G = Graph(pre)
    G.build_snap_index()
    V = json.load(open(os.path.join(HERE, "data", "validation_set.json")))
    rows = []
    t0 = time.time()
    for c in V:
        r = dict(c)
        a, da = G.snap(c["lat1"], c["lon1"])
        b, db = G.snap(c["lat2"], c["lon2"])
        r["snap1_km"] = da; r["snap2_km"] = db
        r["snap_node_1"] = a; r["snap_node_2"] = b
        r["snap_max_km"] = max(da, db)
        # straight line between the SNAPPED nodes -- the correct invariant target
        r["straight_snapped_km"] = haversine(G.nlat[a], G.nlon[a], G.nlat[b], G.nlon[b])
        if da > MAX_SNAP_KM or db > MAX_SNAP_KM:
            r["status"] = "snap_too_far"
            r["routed_core_km"] = None; r["routed_total_km"] = None
            rows.append(r); continue
        if a == b:
            r["status"] = "same_snap_node"
            r["routed_core_km"] = 0.0
            r["routed_total_km"] = da + db
            r["path_hops"] = 1
            rows.append(r); continue
        d, path = G.astar(a, b)
        if d is None:
            r["status"] = "no_path"
            r["routed_core_km"] = None; r["routed_total_km"] = None
            rows.append(r); continue
        r["status"] = "ok"
        r["routed_core_km"] = d
        r["routed_total_km"] = da + d + db
        r["path_hops"] = len(path)
        r["path"] = path
        rows.append(r)
    print("routed %d circuits in %.1fs" % (len(rows), time.time() - t0))
    json.dump(rows, open(os.path.join(HERE, out), "w"))
    return rows


if __name__ == "__main__":
    pre = sys.argv[1] if len(sys.argv) > 1 else "roads"
    out = sys.argv[2] if len(sys.argv) > 2 else "out_routes.json"
    rows = run(pre, out)
    from collections import Counter
    print(Counter(r["status"] for r in rows))
    snaps = sorted([r["snap1_km"] for r in rows] + [r["snap2_km"] for r in rows])
    print("snap distance km: min=%.2f p50=%.2f p90=%.2f max=%.2f" %
          (snaps[0], snaps[len(snaps) // 2], snaps[int(len(snaps) * .9)], snaps[-1]))

Sanitise

A Python module in the scripts folder of Claude that reads deep and payload.

storageclaude / sessions/202609021835-estate-and-corridor/scripts/sanitise.py · lines 1–61 of 61 · version 2026-09-02 18:35 · Not reached from any entry point (candidate for review)

What it does
It loads deep and payload. Uses libraries json, io, sys. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'claude'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file deep.json. Out: JSON file payload.json.
What it achieves
It reads `deep.json` and writes `payload.json`.
Why it matters
No other file in the estate was found to import it.
Application
claude · sessions/202609021835-estate-and-corridor/scripts · Python module
Uses
json, io, sys
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
claude@df9da02425fdf0c65d11a84f32cd9b3ef927b309 sessions/202609021835-estate-and-corridor/scripts/sanitise.py:1-61 · blob 614a267dc4b8d160d0a137e60fd8097b03b40da8 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
import json, io, sys

src = json.load(open('deep.json'))

KEEP = ['ref', 'head_iso', 'first_iso', 'span_days', 'commits', 'merges', 'per_day',
        'c1', 'c7', 'c30', 'add_total', 'del_total', 'files_touched', 'files_median',
        'files_max', 'gap_med_h', 'gap_max_h', 'authors_total', 'tracked_files',
        'tracked_human', 'depth_avg', 'depth_max', 'branches', 'worktrees',
        'workflow_files', 'hours', 'dow']

out = {'generated_utc': src['generated_utc'], 'workers': src['workers'],
       'elapsed_s': src['elapsed_s'], 'repos': []}

for r in src['repos']:
    o = {k: r[k] for k in KEEP if k in r}
    if 'error' in r:
        o['error'] = 'unavailable'
        out['repos'].append(o)
        continue

    o['authors']     = [{'c': a['c']} for a in r.get('authors', [])[:5]]
    o['exts']        = [{'e': e['e'], 'n': e['n']} for e in r.get('exts', [])[:6]]
    o['biggest']     = [{'b': b['b']} for b in r.get('biggest', [])[:3]]
    o['branch_rows'] = [{'d': b['d'], 'ahead': b['ahead']} for b in r.get('branch_rows', [])[:5]]
    o['days30']      = [{'n': d['n']} for d in r.get('days30', [])]

    h = r.get('http') or {}
    o['http'] = {'status': h.get('status'), 'bytes': h.get('bytes'),
                 'ms': h.get('ms'), 'last_modified': h.get('last_modified')}

    c = r.get('ci') or {}
    if c.get('sampled'):
        o['ci'] = {k: c.get(k) for k in
                   ('sampled', 'total_count', 'success', 'failure', 'cancelled',
                    'window', 'dur_med', 'dur_max', 'dur_sum', 'deploy_consec_fail')}
        o['ci']['events'] = [{'e': e['e'], 'n': e['n']} for e in c.get('events', [])]
        o['ci']['workflows'] = [{'t': w['t'], 'f': w['f'], 'med': w['med'],
                                 'last': w['last'], 'lc': w['lc']}
                                for w in c.get('workflows', [])[:10]]
    else:
        o['ci'] = {'sampled': 0, 'total_count': c.get('total_count', 0)}

    l = r.get('loc')
    if l:
        o['loc'] = {'text_files': l['text_files'], 'lines_total': l['lines_total'],
                    'lines_codeish': l['lines_codeish'], 'files_codeish': l['files_codeish'],
                    'by_lang': [{'l': x['l'], 'n': x['n'], 'f': x['f']} for x in l['by_lang'][:6]]}
    out['repos'].append(o)

json.dump(out, open('payload.json', 'w'), indent=1)

blob = json.dumps(out)
NAMES = ['chatgpt-audits', 'companies', 'cvaa', 'data-centres-gb', 'data-gb-electricity',
         'data-grid-gb', 'data-gridatlas', 'data-interconnectors', 'gb-electricity-ui',
         'globalgrid2050', 'grid-distance-maths', 'gridatlas', 'pipelinenews', 'spiders',
         'ventusltd', 'github.io', 'Ventusltd', 'Vikram', 'Claude', 'codex/', 'atlas/',
         'audit/', 'Deploy', 'GridBot', 'REPD', '.py', '/']
leak = {n: blob.count(n) for n in NAMES if blob.count(n)}
print('payload bytes:', len(blob))
print('source bytes :', len(json.dumps(src)))
print('leaks        :', leak or 'none')

Sanity

A Python module in the scripts folder of Claude that uses haversine.

storageclaude / sessions/202609021835-estate-and-corridor/scripts/sanity.py · lines 1–88 of 88 · version 2026-09-02 18:35 · Not reached from any entry point (candidate for review)

What it does
It loads data. Uses libraries random, math, json, time, os. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'claude'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
Out: JSON file out_sanity.json.
What it achieves
Sanity checks demanded by the study brief.
Why it matters
No other file in the estate was found to import it.
Application
claude · sessions/202609021835-estate-and-corridor/scripts · Python module
Uses
Sessions — Estate and Corridor (import), Router (import), random, math, json, time, os
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
claude@df9da02425fdf0c65d11a84f32cd9b3ef927b309 sessions/202609021835-estate-and-corridor/scripts/sanity.py:1-88 · blob 10271885fa4af9803cb50a2c0d451787f15d10ba · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
"""Sanity checks demanded by the study brief."""
import random, math, json, time, os
from common import haversine, spherical_law_of_cosines, vincenty_sphere, HERE
from router import Graph

random.seed(20260903)
res = {}

# ---- 1. haversine vs two independent formulas ----
worst_slc = 0.0; worst_vin = 0.0
for _ in range(200000):
    la1 = random.uniform(49.0, 61.0); lo1 = random.uniform(-8.0, 2.0)
    la2 = random.uniform(49.0, 61.0); lo2 = random.uniform(-8.0, 2.0)
    h = haversine(la1, lo1, la2, lo2)
    if h < 1e-6:
        continue
    worst_slc = max(worst_slc, abs(h - spherical_law_of_cosines(la1, lo1, la2, lo2)) / h)
    worst_vin = max(worst_vin, abs(h - vincenty_sphere(la1, lo1, la2, lo2)) / h)
# short distances too (where law-of-cosines is known to lose precision)
worst_short = 0.0
for _ in range(50000):
    la1 = random.uniform(49.0, 61.0); lo1 = random.uniform(-8.0, 2.0)
    la2 = la1 + random.uniform(-0.002, 0.002); lo2 = lo1 + random.uniform(-0.002, 0.002)
    h = haversine(la1, lo1, la2, lo2)
    if h < 1e-9:
        continue
    worst_short = max(worst_short, abs(h - vincenty_sphere(la1, lo1, la2, lo2)) / h)
res["haversine_vs_law_of_cosines_max_rel"] = worst_slc
res["haversine_vs_vincenty_max_rel"] = worst_vin
res["haversine_vs_vincenty_max_rel_short_links"] = worst_short
res["formula_agreement_1e-9"] = bool(worst_vin < 1e-9 and worst_short < 1e-9)

# ---- load graph ----
t0 = time.time()
G = Graph("roads")
ncells = G.build_snap_index()
res["graph_load_seconds"] = round(time.time() - t0, 2)
res["snap_cells"] = ncells
res["nodes"] = G.n
res["giant_frac"] = G.meta["giant_frac"]

# ---- 2. edge weight equals the sum of its own geometry legs (EXHAUSTIVE) ----
w_by_eid = {}
for p_ in range(len(G.eids)):
    w_by_eid[G.eids[p_]] = G.weights[p_]
worst_edge = 0.0; checked = 0; mism = 0; worst_abs = 0.0
for eid in range(G.meta["edges"]):
    gm = G.edge_geometry(eid); npts = len(gm) // 2
    if npts < 2: continue
    s_ = 0.0
    for i in range(npts - 1):
        s_ += haversine(gm[2*i+1], gm[2*i], gm[2*i+3], gm[2*i+2])
    if s_ <= 0: continue
    w = w_by_eid[eid]; checked += 1
    r = abs(w - s_) / s_
    if r > 1e-9:
        mism += 1; worst_abs = max(worst_abs, abs(w - s_))
    worst_edge = max(worst_edge, r)
res["edge_weight_vs_geometry_max_rel"] = worst_edge
res["edge_weight_vs_geometry_max_abs_km"] = worst_abs
res["edge_weight_checks"] = checked
res["edge_weight_mismatches_over_1e-9"] = mism

# ---- 3. zero-length route between identical points ----
nd, _ = G.snap(52.5, -1.9)
c, p = G.astar(nd, nd)
res["identical_point_route_km"] = c
res["identical_point_route_is_zero"] = (c == 0.0)

# ---- 4. route length equals the sum of its own leg lengths ----
worst_leg = 0.0; tested = 0; failed = 0
for _ in range(25):
    a, _ = G.snap(random.uniform(51.0, 55.0), random.uniform(-3.0, 0.5))
    b, _ = G.snap(random.uniform(51.0, 55.0), random.uniform(-3.0, 0.5))
    c, path = G.astar(a, b)
    if c is None:
        failed += 1; continue
    legs = G.path_legs(path)
    s = sum(w for w, _e in legs)
    tested += 1
    if c > 0:
        worst_leg = max(worst_leg, abs(c - s) / c)
res["route_vs_legsum_max_rel"] = worst_leg
res["route_legsum_routes_tested"] = tested
res["route_legsum_routes_failed"] = failed

print(json.dumps(res, indent=1))
json.dump(res, open(os.path.join(HERE, "out_sanity.json"), "w"), indent=1)

Sweep

A Python command-line tool in the scripts folder of Claude that reads validation set, using haversine. It is built from the true length helper (`true_length`).

storageclaude / sessions/202609021835-estate-and-corridor/scripts/sweep.py · lines 1–80 of 80 · version 2026-09-02 18:35 · Entry point

What it does
It loads validation set. Defines true_length, main. Uses libraries json, os, array, sys. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'claude'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file validation_set.json; JSON file out_sweep.json; command-line arguments. Out: JSON file.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Sweep a railway-crossing penalty (km-equivalent) added to edge weight.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
claude · sessions/202609021835-estate-and-corridor/scripts · Python CLI
Uses
Sessions — Estate and Corridor (import), Router (import), Analyze (import), json, os, array, sys
Used by
none found
Produces
true_length, main
Defines here
true_length, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
claude@df9da02425fdf0c65d11a84f32cd9b3ef927b309 sessions/202609021835-estate-and-corridor/scripts/sweep.py:1-80 · blob 5d8667096ce848715156a4937d49d97c3422eee2 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
"""Sweep a railway-crossing penalty (km-equivalent) added to edge weight.

The penalty is added to the SEARCH cost only; the REPORTED length of the chosen
route is always its true geodesic length, so the comparison against published
cable_km stays honest.
"""
import json, os, array, sys
from common import haversine, HERE
from router import Graph
from analyze import med, pct

MAX_SNAP_KM = 5.0


def true_length(G, path):
    s = 0.0
    for a, b in zip(path, path[1:]):
        e = G.edge_between(a, b)
        s += e[0]
    return s


def main(pre="roads", penalties=(0.0, 0.5, 1.0, 2.0, 3.0, 5.0, 8.0, 20.0)):
    G = Graph(pre); G.build_snap_index()
    m = G.meta["edges"]
    cnt = array.array("i")
    with open(os.path.join(HERE, "graph", pre + ".railcnt.bin"), "rb") as fh:
        cnt.fromfile(fh, m)
    V = json.load(open(os.path.join(HERE, "data", "validation_set.json")))

    # pre-snap once
    jobs = []
    for c in V:
        a, da = G.snap(c["lat1"], c["lon1"])
        b, db = G.snap(c["lat2"], c["lon2"])
        if da > MAX_SNAP_KM or db > MAX_SNAP_KM:
            continue
        jobs.append((c, a, b, da, db))

    results = []
    for pen in penalties:
        extra = [cnt[i] * pen for i in range(m)] if pen > 0 else None
        apes, wins, n = [], 0, 0
        for (c, a, b, da, db) in jobs:
            if a == b:
                L = 0.0
            else:
                d, path = G.astar(a, b, extra_cost=extra)
                if d is None:
                    continue
                L = true_length(G, path)   # TRUE length, penalty excluded
            tot = da + L + db
            pub = c["cable_km"]
            er = abs(tot - pub) / pub * 100.0
            es = abs(c["straight_km"] - pub) / pub * 100.0
            apes.append(er); n += 1
            if er < es: wins += 1
        results.append({
            "penalty_km_per_crossing": pen,
            "n_scored": n,
            "median_ape_routed": med(apes),
            "mean_ape_routed": sum(apes) / len(apes),
            "p75_ape_routed": pct(apes, .75),
            "beats_straight_frac_scored": wins / n,
            "beats_straight_frac_all95": wins / len(V),
        })
        print("pen=%5.1f km  n=%d  medAPE=%6.2f%%  meanAPE=%7.2f%%  beat=%.1f%% (scored) %.1f%% (all 95)"
              % (pen, n, results[-1]["median_ape_routed"], results[-1]["mean_ape_routed"],
                 100 * results[-1]["beats_straight_frac_scored"],
                 100 * results[-1]["beats_straight_frac_all95"]), flush=True)

    best = min(results, key=lambda r: r["median_ape_routed"])
    print("\nbest by median APE: penalty=%.1f km  medAPE=%.2f%%"
          % (best["penalty_km_per_crossing"], best["median_ape_routed"]))
    json.dump({"results": results, "best": best},
              open(os.path.join(HERE, "out_sweep.json"), "w"), indent=1)


if __name__ == "__main__":
    main(sys.argv[1] if len(sys.argv) > 1 else "roads")

Verify Cowley

A Python module in the scripts folder of Claude covering GB transmission network, transformers, 400kV and 132kV. It is built from the card step (`card`).

otherclaude / sessions/202609021835-estate-and-corridor/scripts/verify_cowley.py · lines 1–99 of 99 · version 2026-09-02 18:35 · Not reached from any entry point (candidate for review)

What it does
Defines card. Uses libraries json, subprocess, collections. Side effects: starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'claude'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). Domain terms in the code: transformers, 400kV, 132kV.
Inputs & outputs
In: JSON file gb-transmission-network.v1.json. Voltage levels named: 400kV, 132kV.
What it achieves
Independently recompute every figure the Botley West card states about COWLEY, straight from gb-transmission-network.v1.json. Its code works with 132 kV and 400 kV.
Why it matters
No other file in the estate was found to import it.
Application
claude · sessions/202609021835-estate-and-corridor/scripts · Python module
Uses
json, subprocess, collections
Used by
none found
Produces
card
Defines here
card
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
claude@df9da02425fdf0c65d11a84f32cd9b3ef927b309 sessions/202609021835-estate-and-corridor/scripts/verify_cowley.py:1-99 · blob 6984e18c12469838dfc759979a8f7721ca900062 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
"""Independently recompute every figure the Botley West card states about COWLEY,
straight from gb-transmission-network.v1.json. Nothing here reads the cartridge,
so an agreement is a real agreement and a divergence is a real divergence.
"""
import json, subprocess, collections

net = json.loads(subprocess.run(
    ['git', '-C', 'data-grid-gb', 'show', 'gh/main:derived/gb-transmission-network.v1.json'],
    capture_output=True).stdout)

SITE = 'COWL'
site = next(s for s in net['sites'] if s['code'] == SITE)
nodes = [n for n in net['nodes'] if n['site_code'] == SITE]
nset = {n['node'] for n in nodes}
kv_of = {n['node']: n.get('voltage_kv') for n in nodes}

def card(label, claimed, computed):
    ok = 'OK  ' if str(claimed) == str(computed) else 'DIFF'
    print('  [%s] %-42s card: %-26s computed: %s' % (ok, label, claimed, computed))

print('SITE %s  %s   TO %s   declared voltages %s' %
      (SITE, site['name'], site.get('transmission_owner'), site.get('voltages_kv')))
print('nodes at site: %d  ->  %s' % (len(nodes), ', '.join(sorted(nset))))
print()

# ---- circuits ----
circ = [c for c in net['circuits'] if c['node_1'] in nset or c['node_2'] in nset]
c_by_kv = collections.Counter()
for c in circ:
    end = c['node_1'] if c['node_1'] in nset else c['node_2']
    c_by_kv[kv_of.get(end)] += 1
card('circuits, site-wide', 6, len(circ))
card('circuits at 400 kV', 6, c_by_kv.get(400.0, 0) + c_by_kv.get(400, 0))
card('circuits at 132 kV', 0, c_by_kv.get(132.0, 0) + c_by_kv.get(132, 0))

w = [c['winter_mva'] for c in circ if c.get('winter_mva')]
s = [c['summer_mva'] for c in circ if c.get('summer_mva')]
card('winter rating range MVA', '1180-2779', '%g-%g' % (min(w), max(w)))
card('summer rating range MVA', '877-2219', '%g-%g' % (min(s), max(s)))

# ---- transformers ----
tx = [t for t in net['transformers'] if t['node_1'] in nset or t['node_2'] in nset]
both = [t for t in tx if t['node_1'] in nset and t['node_2'] in nset]
t_by_kv = collections.Counter()
for t in tx:
    for e in (t['node_1'], t['node_2']):
        if e in nset:
            t_by_kv[kv_of.get(e)] += 1
print()
card('transformers, site-wide', 10, len(tx))
card('transformers at 400 kV', 5, t_by_kv.get(400.0, 0) + t_by_kv.get(400, 0))
card('transformers at 132 kV', 5, t_by_kv.get(132.0, 0) + t_by_kv.get(132, 0))
print('       transformers with BOTH ends inside this site: %d' % len(both))
print('       -> physical units at the site: %d ; winding-ends counted: %d'
      % (len(tx), sum(t_by_kv.values())))

# ---- reactive compensation ----
rc = [r for r in net['reactive_compensation'] if r['node'] in nset or r.get('site_code') == SITE]
print()
card('reactive compensation units', 5, len(rc))

# ---- planned changes ----
pc = [p for p in net['planned_changes'] if p['node_1'] in nset or p['node_2'] in nset]
yrs = collections.Counter(p['year'] for p in pc)
print()
card('planned changes total', 14, len(pc))
card('planned change years', '2026, 2028, 2030', ', '.join(sorted(yrs)))
for y in sorted(yrs):
    st = collections.Counter(p['status'] for p in pc if p['year'] == y)
    print('       %s: %s' % (y, '  '.join('%s %s' % (v, k) for k, v in sorted(st.items()))))

# ---- fault current ----
fc = [f for f in net['fault_current_scenarios'] if f.get('site_code') == SITE]
brk = [f['three_phase_rms_break_current_ka'] for f in fc
       if f.get('three_phase_rms_break_current_ka') is not None]
buses = {f['location'] for f in fc}
years = {f['winter'] for f in fc}
print()
card('fault-current rows', 15, len(fc))
card('distinct buses', 3, len(buses))
card('3ph RMS break current kA', '12.4-49.4', '%g-%g' % (min(brk), max(brk)))
card('year span', '2025/26 to 2033/34', '%s to %s' % (min(years), max(years)))
print('       buses: %s' % ', '.join(sorted(buses)))
print('       demand cases: %s' % ', '.join(sorted({f['demand_case'] for f in fc})))

# ---- neighbours ----
adj = collections.defaultdict(set)
nsite = {n['node']: n['site_code'] for n in net['nodes']}
for c in net['circuits']:
    a, b = nsite.get(c['node_1']), nsite.get(c['node_2'])
    if a and b and a != b:
        adj[a].add(b); adj[b].add(a)
one = adj[SITE]
two = {x for h in one for x in adj[h]} - one - {SITE}
name = {s['code']: s['name'] for s in net['sites']}
print()
card('sites one circuit away', 6, len(one))
card('more sites at two hops', 9, len(two))
print('       reach: %s' % ', '.join(sorted(name.get(c, c) for c in one)))

Verify Homepage

A Python module in the scripts folder of Claude.

otherclaude / sessions/202609021835-estate-and-corridor/scripts/verify_homepage.py · lines 1–43 of 43 · version 2026-09-02 18:35 · Not reached from any entry point (candidate for review)

What it does
Uses libraries io, re, subprocess, sys. Side effects: starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'claude'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
What it achieves
Its name says it verifies homepage. Described from its file name only (a candidate, not yet checked against the code).
Why it matters
No other file in the estate was found to import it.
Application
claude · sessions/202609021835-estate-and-corridor/scripts · Python module
Uses
io, re, subprocess, sys
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
claude@df9da02425fdf0c65d11a84f32cd9b3ef927b309 sessions/202609021835-estate-and-corridor/scripts/verify_homepage.py:1-43 · blob cfd9370d984f0360bca898f1d95b9bfe2168bd5e · GitHub at these lines
State
achieves: name · context: readme_derived · stage: unknown · effects: process · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
import io, re, subprocess, sys

new = io.open('index.html', encoding='utf-8').read()
old = subprocess.run(['git', 'show', 'HEAD:index.html'],
                     capture_output=True, text=True, encoding='utf-8').stdout

V8 = '    { name:"UK Energy Atlas Grid Overlay V8", url:"./repd_grid_atlasv8/" },'
checks = [
    ("V8 sentinel occurs exactly once", new.count(V8) == 1),
    ("V8 route occurs exactly once",    new.count('./repd_grid_atlasv8/') == 1),
    ("AUTOMATION_START survives",       new.count('GRIDATLAS_V9_AUTOMATION_START') == 1),
    ("AUTOMATION_END survives",         new.count('GRIDATLAS_V9_AUTOMATION_END') == 1),
]

name_pat = re.compile('name:"([^"]*)"')
note_pat = re.compile('note:"([^"]*)"')
on, nn = name_pat.findall(old), name_pat.findall(new)
onote, nnote = note_pat.findall(old), note_pat.findall(new)

added_names   = [x for x in nn if x not in on]
removed_names = [x for x in on if x not in nn]
removed_notes = [x for x in onote if x not in nnote]

checks += [
    ("every pre-existing name: string unchanged", not removed_names),
    ("every pre-existing note: string unchanged", not removed_notes),
    ("exactly one name added",                    len(added_names) == 1),
    ("new route resolves to a real folder",       './estate_scan/202609021858/' in new),
]

print("name: strings  %d -> %d" % (len(on), len(nn)))
print("note: strings  %d -> %d" % (len(onote), len(nnote)))
print("added name   : %r" % (added_names,))
print("removed names: %r" % (removed_names,))
print("removed notes: %r" % ([x[:50] for x in removed_notes],))
print()
ok = True
for label, passed in checks:
    print(("  PASS  " if passed else "  FAIL  ") + label)
    ok = ok and passed
print()
print("RESULT:", "all checks pass" if ok else "FAILED")
sys.exit(0 if ok else 1)

Census

A Python module in the sessions folder of Claude that reads members.

storageclaude / sessions/202609030120-cicd-spider/census.py · lines 1–36 of 36 · version 2026-09-03 01:20 · Not reached from any entry point (candidate for review)

What it does
It loads members. Uses libraries json, glob, os, sys, collections. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'spider'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file _members.json; command-line arguments. Out: JSON file.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
No other file in the estate was found to import it.
Application
claude · sessions/202609030120-cicd-spider · Python module
Uses
json, glob, os, sys, collections
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
claude@df9da02425fdf0c65d11a84f32cd9b3ef927b309 sessions/202609030120-cicd-spider/census.py:1-36 · blob 5d0cafa5a400ea7e540dea49cb7718682417b47e · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
import json,glob,os,sys,collections
sys.stdout.reconfigure(encoding='utf-8',errors='replace')
d=sys.argv[1]; rows={}
for f in sorted(glob.glob(os.path.join(d,'*.json'))):
    n=os.path.basename(f)[:-5]; o=None
    for line in open(f,encoding='utf-8',errors='replace'):
        line=line.strip()
        if line.startswith('{') and '"schema"' in line:
            try: o=json.loads(line)
            except Exception: pass
    if o: rows[n]=o
N=len(rows)
by=collections.defaultdict(lambda: collections.defaultdict(list))
for repo,o in rows.items():
    for r in o['results']: by[r['vaccine']][r['state']].append(repo)
print('repos measured: %d   immune repos: %d'%(N,sum(1 for v in rows.values() if v['status']=='immune')))
print('\nFAILING RULES - members, not cardinality (RH29). Control = repos the rule is quiet on.')
for v,st in sorted(by.items(), key=lambda kv:-len(kv[1].get('fail',[]))):
    f=st.get('fail',[])
    if not f: continue
    ctl=len(st.get('immune',[]))
    flag='' if ctl else '   <-- NO CONTROL: fires everywhere, suspect the rule'
    print('\n  %s  %d of %d   quiet on %d%s'%(v,len(f),N,ctl,flag))
    for r in sorted(f): print('      %s'%r)
warn={v:st.get('warn',[]) for v,st in by.items() if st.get('warn')}
if warn:
    print('\nWARNINGS - level: warning in the vaccine, an accepted dated allowance, NOT failures')
    for v,rs in sorted(warn.items(), key=lambda kv:-len(kv[1])):
        print('  %-28s %d of %d: %s'%(v,len(rs),N,', '.join(sorted(rs))))
skip={v:st.get('skipped',[]) for v,st in by.items() if st.get('skipped')}
if skip:
    print('\nSKIPPED - the rule declined to decide. A skip is not a pass.')
    for v,rs in sorted(skip.items()): print('  %-28s %d of %d: %s'%(v,len(rs),N,', '.join(sorted(rs))))
json.dump({v:{s:sorted(r) for s,r in st.items()} for v,st in by.items()},
          open(os.path.join(d,'_members.json'),'w',encoding='utf-8'),indent=1)
print('\nmembers written to %s'%os.path.join(d,'_members.json'))

CI Log

A shell script in the sessions folder of Claude using data from GitHub API.

automationclaude / sessions/202609030120-cicd-spider/ci-log.sh · lines 1–15 of 15 · version 2026-09-03 01:20 · Entry point

What it does
It fetches data. Side effects: makes network requests; starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'spider'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: data source: GitHub API.
Downstream impact
It is itself an entry point (shell script); no other file was found loading it.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
claude · sessions/202609030120-cicd-spider · shell script
Uses
none found
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
claude@df9da02425fdf0c65d11a84f32cd9b3ef927b309 sessions/202609030120-cicd-spider/ci-log.sh:1-15 · blob 8501f62df39608cfc7bd2f8fcdc497b116812e79 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: network, process · domain stage: agent_infra · users: ai_agent · canonical: unknown
#!/bin/bash
# ci-log.sh <owner/repo> <run_id> [grep-pattern]
# Reads a GitHub Actions run log. RH24: this endpoint returns 200 with the
# stored credential; the estate believed it was 403 for an entire night.
set -euo pipefail
REPO="$1"; RUN="$2"; PAT="${3:-}"
TOK=$(printf 'protocol=https\nhost=github.com\n\n' | git credential fill 2>/dev/null | sed -n 's/^password=//p')
[ -n "$TOK" ] || { echo "no credential"; exit 1; }
TMP=$(mktemp -d)
curl -sL -H "Authorization: token $TOK" \
  "https://api.github.com/repos/$REPO/actions/runs/$RUN/logs" -o "$TMP/logs.zip"
unzip -qo "$TMP/logs.zip" -d "$TMP/x" 2>/dev/null || { echo "not a zip"; head -c 200 "$TMP/logs.zip"; exit 1; }
if [ -n "$PAT" ]; then grep -rniE "$PAT" "$TMP/x" | sed "s|$TMP/x/||"; else
  find "$TMP/x" -type f -name '*.txt' | sed "s|$TMP/x/||" | sort; fi
rm -rf "$TMP"