In this section
- Calib storage · claude / sessions/202609021835-estate-and-corridor/scripts/calib.py lines 1–85
- Sessions — Estate and Corridor geodesy · claude / sessions/202609021835-estate-and-corridor/scripts/common.py lines 1–97
- Crossings storage · claude / sessions/202609021835-estate-and-corridor/scripts/crossings.py lines 1–74
- Datapoints storage · claude / sessions/202609021835-estate-and-corridor/scripts/datapoints.py lines 1–134
- Deep storage · claude / sessions/202609021835-estate-and-corridor/scripts/deep.py lines 1–293
Calib
A Python command-line tool in the scripts folder of Claude that reads routes.
storageclaude / sessions/202609021835-estate-and-corridor/scripts/calib.py · lines 1–85 of 85 · version 2026-09-02 18:35 · Entry point · pattern report (shared by 21 files)
- What it does
- It loads routes. Defines best_k, loo_median_ape, report, main. Uses libraries json, 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
- In: JSON file out_routes.json. Out: JSON file out_calib.json.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It is built from the best k helper (`best_k`), the loo median ape helper (`loo_median_ape`) and the report step (`report`). Is a scalar detour factor on the straight line as good as routing?
- 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), Analyze (import), json, os
- Used by
- none found
- Produces
- best_k, loo_median_ape, report, main
- Defines here
- best_k, loo_median_ape, report, 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/calib.py:1-85 · blob ffbed95704aed93c6da64c4a010330f492ba7246 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
"""Is a scalar detour factor on the straight line as good as routing?
Fits a single multiplier k minimising median absolute percentage error against
published cable_km, for (a) straight line and (b) routed distance. Also reports
leave-one-out (honest, no in-sample fitting advantage) and a de-duplicated view
over distinct site pairs, since 95 circuits cover only 59 unique pairs.
"""
import json, os
from common import HERE
from analyze import med, pct
def best_k(vals, pubs, lo=0.5, hi=3.0, steps=2501):
best = (None, 1e18)
for i in range(steps):
k = lo + (hi - lo) * i / (steps - 1)
e = med([abs(k * v - p) / p * 100.0 for v, p in zip(vals, pubs)])
if e < best[1]:
best = (k, e)
return best
def loo_median_ape(vals, pubs):
"""Leave-one-out: fit k on all but i, score i."""
out = []
for i in range(len(vals)):
v2 = vals[:i] + vals[i + 1:]; p2 = pubs[:i] + pubs[i + 1:]
k, _ = best_k(v2, p2, steps=601)
out.append(abs(k * vals[i] - pubs[i]) / pubs[i] * 100.0)
return med(out), out
def report(rows, tag):
s = [r["straight_km"] for r in rows]
t = [r["routed_total_km"] for r in rows]
p = [r["cable_km"] for r in rows]
res = {"tag": tag, "n": len(rows)}
res["raw_median_ape_straight"] = med([abs(a - b) / b * 100 for a, b in zip(s, p)])
res["raw_median_ape_routed"] = med([abs(a - b) / b * 100 for a, b in zip(t, p)])
ks, es = best_k(s, p); kt, et = best_k(t, p)
res["best_k_straight"] = ks; res["calibrated_median_ape_straight"] = es
res["best_k_routed"] = kt; res["calibrated_median_ape_routed"] = et
lo_s, _ = loo_median_ape(s, p); lo_t, _ = loo_median_ape(t, p)
res["loo_median_ape_straight"] = lo_s
res["loo_median_ape_routed"] = lo_t
# head-to-head after calibration
wins = sum(1 for a, b, q in zip(s, t, p)
if abs(kt * b - q) / q < abs(ks * a - q) / q)
res["calibrated_routed_beats_calibrated_straight_frac"] = wins / len(rows)
return res
def main():
rows = [r for r in json.load(open(os.path.join(HERE, "out_routes.json")))
if r["status"] == "ok"]
out = {"all_scored_circuits": report(rows, "81 scored circuits")}
# de-duplicated: one record per distinct site pair (mean of published lengths)
byp = {}
for r in rows:
k = tuple(sorted((r["site_1"], r["site_2"])))
byp.setdefault(k, []).append(r)
ded = []
for k, g in byp.items():
r0 = dict(g[0])
r0["cable_km"] = sum(x["cable_km"] for x in g) / len(g)
ded.append(r0)
out["distinct_site_pairs"] = report(ded, "%d distinct site pairs" % len(ded))
json.dump(out, open(os.path.join(HERE, "out_calib.json"), "w"), indent=1)
for k, v in out.items():
print("--", v["tag"])
print(" raw : straight %.1f%% routed %.1f%%"
% (v["raw_median_ape_straight"], v["raw_median_ape_routed"]))
print(" calibrat: straight x%.3f -> %.1f%% routed x%.3f -> %.1f%%"
% (v["best_k_straight"], v["calibrated_median_ape_straight"],
v["best_k_routed"], v["calibrated_median_ape_routed"]))
print(" LOO : straight %.1f%% routed %.1f%%"
% (v["loo_median_ape_straight"], v["loo_median_ape_routed"]))
print(" calibrated routed beats calibrated straight: %.1f%%"
% (100 * v["calibrated_routed_beats_calibrated_straight_frac"]))
if __name__ == "__main__":
main()Sessions — Estate and Corridor
A Python command-line tool in the scripts folder of Claude that reads network and validation set, using haversine and Vincenty. It loads sites coords (`load_sites_with_coords`) and loads validation set (`load_validation_set`).
geodesyclaude / sessions/202609021835-estate-and-corridor/scripts/common.py · lines 1–97 of 97 · version 2026-09-02 18:35 · Entry point · pattern haversine (shared by 24 files)
- What it does
- It loads network and validation set. Defines haversine, spherical_law_of_cosines, vincenty_sphere, load_sites_with_coords, load_validation_set. Uses libraries json, math, 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
- In: JSON file cp.json; JSON file network.json. Out: JSON file validation_set.json.
- Downstream impact
- Used directly by 10 files: Router (claude); Analyze (claude); Build Graph (claude); Calib (claude); and 6 more.
- What it achieves
- Shared geodesy + IO for the road-routing feasibility study.
- Why it matters
- Imported by 10 files, including Router, Analyze and Build Graph.
- Application
- claude · sessions/202609021835-estate-and-corridor/scripts · Python CLI
- Uses
- json, math, os
- Used by
- imported by Router (import), imported by Analyze (import), imported by Build Graph (import), imported by Calib (import), imported by Crossings (import), imported by Edge Rail (import), imported by Rail (import), imported by Run Study (import), and 2 more
- Produces
- haversine, spherical_law_of_cosines, vincenty_sphere, load_sites_with_coords, load_validation_set
- Defines here
- haversine, spherical_law_of_cosines, vincenty_sphere, load_sites_with_coords, load_validation_set
- 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/common.py:1-97 · blob 59e792bfa6fe1a8c2f87513199274b167a3a5da5 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
"""Shared geodesy + IO for the road-routing feasibility study."""
import json, math, os
R_KM = 6371.0088
HERE = os.path.dirname(os.path.abspath(__file__))
DATA = os.path.join(HERE, "data")
def haversine(lat1, lon1, lat2, lon2):
p1 = math.radians(lat1); p2 = math.radians(lat2)
dp = p2 - p1
dl = math.radians(lon2 - lon1)
a = math.sin(dp / 2.0) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2.0) ** 2
return 2.0 * R_KM * math.asin(math.sqrt(a))
def spherical_law_of_cosines(lat1, lon1, lat2, lon2):
"""Independent formula for cross-checking haversine."""
p1 = math.radians(lat1); p2 = math.radians(lat2)
dl = math.radians(lon2 - lon1)
x = math.sin(p1) * math.sin(p2) + math.cos(p1) * math.cos(p2) * math.cos(dl)
x = max(-1.0, min(1.0, x))
return R_KM * math.acos(x)
def vincenty_sphere(lat1, lon1, lat2, lon2):
"""Second independent formula (special case of Vincenty on a sphere)."""
p1 = math.radians(lat1); p2 = math.radians(lat2)
dl = math.radians(lon2 - lon1)
num = math.sqrt((math.cos(p2) * math.sin(dl)) ** 2 +
(math.cos(p1) * math.sin(p2) - math.sin(p1) * math.cos(p2) * math.cos(dl)) ** 2)
den = math.sin(p1) * math.sin(p2) + math.cos(p1) * math.cos(p2) * math.cos(dl)
return R_KM * math.atan2(num, den)
def load_sites_with_coords():
cp = json.load(open(os.path.join(DATA, "cp.json"), encoding="utf-8"))
out = {}
for p in cp["connection_points"]:
loc = p.get("location")
if loc and loc.get("lat") is not None and loc.get("lon") is not None:
out[p["site_code"]] = (float(loc["lat"]), float(loc["lon"]),
p.get("name"), loc.get("matched_by"))
return out
def load_validation_set(min_sep_km=1.0):
net = json.load(open(os.path.join(DATA, "network.json"), encoding="utf-8"))
node2site = {n["node"]: n["site_code"] for n in net["nodes"]}
coords = load_sites_with_coords()
stats = {"cable_circuits": 0, "no_node_map": 0, "no_coords": 0,
"zero_len": 0, "too_close": 0, "kept": 0}
kept = []
for c in net["circuits"]:
if c.get("circuit_type") != "Cable":
continue
stats["cable_circuits"] += 1
s1 = node2site.get(c["node_1"]); s2 = node2site.get(c["node_2"])
if not s1 or not s2:
stats["no_node_map"] += 1; continue
if s1 not in coords or s2 not in coords:
stats["no_coords"] += 1; continue
pub = (c.get("cable_km") or 0.0) + (c.get("ohl_km") or 0.0)
cab = c.get("cable_km") or 0.0
if cab <= 0:
stats["zero_len"] += 1; continue
a = coords[s1]; b = coords[s2]
sl = haversine(a[0], a[1], b[0], b[1])
if sl <= min_sep_km:
stats["too_close"] += 1; continue
stats["kept"] += 1
kept.append({
"node_1": c["node_1"], "node_2": c["node_2"],
"site_1": s1, "site_2": s2,
"name_1": a[2], "name_2": b[2],
"matched_1": a[3], "matched_2": b[3],
"lat1": a[0], "lon1": a[1], "lat2": b[0], "lon2": b[1],
"cable_km": cab, "ohl_km": c.get("ohl_km") or 0.0,
"published_km": pub,
"straight_km": sl,
"owner": c.get("transmission_owner"),
"winter_mva": c.get("winter_mva"),
})
return kept, stats
if __name__ == "__main__":
kept, stats = load_validation_set()
print(json.dumps(stats, indent=1))
# dedupe view: how many distinct site pairs
pairs = set()
for k in kept:
pairs.add(tuple(sorted((k["site_1"], k["site_2"]))))
print("distinct site pairs:", len(pairs))
json.dump(kept, open(os.path.join(DATA, "validation_set.json"), "w"), indent=1)
print("wrote", len(kept), "circuits")Crossings
A Python command-line tool in the scripts folder of Claude that reads routes. It is built from the pearson step (`pearson`), the spearman step (`spearman`) and the rank step (`rank`).
storageclaude / sessions/202609021835-estate-and-corridor/scripts/crossings.py · lines 1–74 of 74 · version 2026-09-02 18:35 · Entry point · pattern pearson (shared by 2 files)
- What it does
- It loads routes. Defines pearson, spearman, rank, main. Uses libraries json, os, math. 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 out_crossings.json. Out: JSON file.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- Count railway crossings on each routed path and test correlation with error.
- 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), Rail (import), Analyze (import), json, os, math
- Used by
- none found
- Produces
- pearson, spearman, main
- Defines here
- pearson, spearman, rank, 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/crossings.py:1-74 · blob 9133bd6f5fb50fcc95fa12c7ac58f820cc822dec · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
"""Count railway crossings on each routed path and test correlation with error."""
import json, os, math
from common import HERE
from router import Graph
from rail import RailIndex
from analyze import med, pct
def pearson(xs, ys):
n = len(xs)
if n < 3: return float("nan")
mx = sum(xs) / n; my = sum(ys) / n
sxy = sum((a - mx) * (b - my) for a, b in zip(xs, ys))
sxx = sum((a - mx) ** 2 for a in xs); syy = sum((b - my) ** 2 for b in ys)
if sxx <= 0 or syy <= 0: return float("nan")
return sxy / math.sqrt(sxx * syy)
def spearman(xs, ys):
def rank(v):
order = sorted(range(len(v)), key=lambda i: v[i])
r = [0.0] * len(v); i = 0
while i < len(order):
j = i
while j + 1 < len(order) and v[order[j + 1]] == v[order[i]]: j += 1
avg = (i + j) / 2.0 + 1
for k in range(i, j + 1): r[order[k]] = avg
i = j + 1
return r
return pearson(rank(xs), rank(ys))
def main():
G = Graph("roads"); G.build_snap_index()
R = RailIndex()
rows = json.load(open(os.path.join(HERE, "out_routes.json")))
out = []
for r in rows:
if r["status"] != "ok" or "path" not in r:
continue
poly = G.path_geometry(r["path"])
nx = R.count_crossings(poly)
pub = r["cable_km"]
rec = {"from": r["name_1"], "to": r["name_2"], "crossings": nx,
"routed_total_km": r["routed_total_km"], "cable_km": pub,
"straight_km": r["straight_km"],
"ape_routed": abs(r["routed_total_km"] - pub) / pub * 100.0,
"detour_ratio": r["routed_total_km"] / r["straight_km"],
"crossings_per_km": nx / r["routed_total_km"]}
out.append(rec)
xs = [r["crossings"] for r in out]
ys = [r["ape_routed"] for r in out]
res = {
"n": len(out),
"crossings": {"min": min(xs), "p25": pct(xs, .25), "p50": med(xs),
"p75": pct(xs, .75), "p90": pct(xs, .90), "max": max(xs),
"mean": sum(xs) / len(xs), "zero_crossing_routes": xs.count(0)},
"crossings_per_km_median": med([r["crossings_per_km"] for r in out]),
"pearson_crossings_vs_ape": pearson(xs, ys),
"spearman_crossings_vs_ape": spearman(xs, ys),
"pearson_crossings_vs_detour": pearson(xs, [r["detour_ratio"] for r in out]),
"spearman_crossings_vs_detour": spearman(xs, [r["detour_ratio"] for r in out]),
"pearson_crossings_vs_routedkm": pearson(xs, [r["routed_total_km"] for r in out]),
}
json.dump({"summary": res, "rows": out},
open(os.path.join(HERE, "out_crossings.json"), "w"), indent=1)
print(json.dumps(res, indent=1))
hist = {}
for x in xs: hist[x] = hist.get(x, 0) + 1
print("crossing histogram:", dict(sorted(hist.items())))
if __name__ == "__main__":
main()Datapoints
A Python command-line tool in the scripts folder of Claude that counts CSV (`count_csv`). It counts JSON (`count_json`) and is built from the work step (`work`).
storageclaude / sessions/202609021835-estate-and-corridor/scripts/datapoints.py · lines 1–134 of 134 · version 2026-09-02 18:35 · Entry point
- What it does
- It loads data. Defines count_json, count_csv, work, main. Uses libraries subprocess, collections, os, re, sys. Side effects: reads or writes files; 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).
- Inputs & outputs
- In: command-line arguments. Out: JSON file datapoints.json.
- Downstream impact
- Used directly by 3 files: Dupcheck (claude); Extra Count (claude); Growth (claude).
- What it achieves
- Count datapoints across the estate under an explicit, stated definition. It writes `datapoints.json`.
- Why it matters
- Imported by Dupcheck, Extra Count and Growth.
- Application
- claude · sessions/202609021835-estate-and-corridor/scripts · Python CLI
- Uses
- subprocess, collections, os, re, sys, json, datetime, concurrent.futures
- Used by
- imported by Dupcheck (import), imported by Extra Count (import), imported by Growth (import)
- Produces
- count_json, count_csv, work, main
- Defines here
- count_json, count_csv, work, 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/datapoints.py:1-134 · blob c4d659710bb3fb9e039ab68ebe3eb275fd03154b · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
"""Count datapoints across the estate under an explicit, stated definition.
DEFINITION USED
CSV / TSV : one datapoint = one non-empty cell in a non-header row.
JSON / GeoJSON / NDJSON : one datapoint = one scalar VALUE leaf
(string, number, true, false, null).
Object KEYS are not counted.
Counted once per unique git blob, so the same file copied into many
immutable release folders is counted once, not once per copy.
"""
import subprocess, collections, os, re, sys, json, datetime
from concurrent.futures import ProcessPoolExecutor, as_completed
ROOT = sys.argv[1]
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"]
DATA = {'.csv', '.tsv', '.json', '.geojson', '.ndjson'}
TOK = re.compile(rb'"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null|:')
def count_json(buf):
"""Scalar value leaves. A string immediately followed by ':' is a key."""
toks = TOK.findall(buf)
n = 0
for i, t in enumerate(toks):
if t == b':':
continue
if t.startswith(b'"') and i + 1 < len(toks) and toks[i + 1] == b':':
continue # object key
n += 1
return n
def count_csv(buf, sep):
n = rows = 0
for i, line in enumerate(buf.split(b'\n')):
line = line.strip(b'\r')
if not line.strip():
continue
if i == 0:
continue # header
rows += 1
n += sum(1 for c in line.split(sep) if c.strip())
return n, rows
def work(job):
repo, sha, path, ext, size = job
try:
buf = subprocess.run(['git', '-C', os.path.join(ROOT, repo), 'cat-file', 'blob', sha],
capture_output=True, timeout=900).stdout
except Exception:
return {'ext': ext, 'dp': 0, 'rows': 0, 'bytes': 0, 'skipped': 1}
if ext in ('.csv', '.tsv'):
dp, rows = count_csv(buf, b'\t' if ext == '.tsv' else b',')
else:
dp, rows = count_json(buf), 0
return {'ext': ext, 'dp': dp, 'rows': rows, 'bytes': len(buf), 'skipped': 0}
def main():
seen, jobs = {}, []
copies = 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
base = path.rsplit('/', 1)[-1]
ext = ('.' + base.rsplit('.', 1)[1].lower()) if '.' in base[1:] else ''
if ext not in DATA:
continue
copies += 1
if sha not in seen:
seen[sha] = True
jobs.append((r, sha, path, ext, size))
jobs.sort(key=lambda j: -j[4]) # biggest first, better packing
by = collections.defaultdict(lambda: {'dp': 0, 'rows': 0, 'files': 0, 'bytes': 0})
skipped = 0
with ProcessPoolExecutor(max_workers=min(10, os.cpu_count() or 4)) as ex:
futs = [ex.submit(work, j) for j in jobs]
for i, f in enumerate(as_completed(futs)):
r = f.result()
b = by[r['ext']]
b['dp'] += r['dp']; b['rows'] += r['rows']
b['files'] += 1; b['bytes'] += r['bytes']
skipped += r['skipped']
if (i + 1) % 200 == 0:
print(' ... %d/%d' % (i + 1, len(jobs)), file=sys.stderr)
total = sum(v['dp'] for v in by.values())
print()
print('%-10s %10s %16s %14s' % ('type', 'files', 'datapoints', 'bytes'))
print('-' * 54)
for e in sorted(by, key=lambda k: -by[k]['dp']):
v = by[e]
print('%-10s %10s %16s %13.1f MB' %
(e, f"{v['files']:,}", f"{v['dp']:,}", v['bytes'] / 2**20))
print('-' * 54)
print('%-10s %10s %16s' % ('TOTAL', f"{sum(v['files'] for v in by.values()):,}", f"{total:,}"))
print()
print('unique data blobs counted : %s' % f"{len(jobs):,}")
print('file copies on disk : %s (%s duplicates not double-counted)'
% (f"{copies:,}", f"{copies - len(jobs):,}"))
print('csv/tsv data rows : %s' % f"{sum(by[e]['rows'] for e in ('.csv', '.tsv')):,}")
print('skipped (unreadable) : %d' % skipped)
json.dump({'generated_utc': datetime.datetime.now(datetime.UTC).strftime('%Y-%m-%dT%H:%M:%SZ'),
'total_datapoints': total,
'unique_blobs': len(jobs), 'file_copies': copies,
'by_type': {e: dict(v) for e, v in by.items()}},
open('datapoints.json', 'w'), indent=1)
if __name__ == '__main__':
main()Deep
A Python module in the scripts folder of Claude using data from GitHub API.
storageclaude / sessions/202609021835-estate-and-corridor/scripts/deep.py · lines 1–293 of 293 · version 2026-09-02 18:35 · Not reached from any entry point (candidate for review) · pattern human (shared by 2 files)
- What it does
- It fetches data. Defines 9 functions or classes, including run, fetch, api, ci, probe. Uses libraries json, subprocess, collections, datetime, os. Side effects: reads or writes files; makes network requests; 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).
- Inputs & outputs
- In: data source: GitHub API; command-line arguments. Out: JSON file.
- What it achieves
- It is built from the probe step (`probe`), the ref of helper (`ref_of`) and the human step (`human`). Defines `run`, `fetch`, `api` and 5 more.
- 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, datetime, os, sys, pathlib, urllib.request
- Used by
- none found
- Produces
- run, fetch, api, ci, probe, ref_of, human, deep
- Defines here
- run, fetch, api, ci, probe, ref_of, human, deep, dur
- 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/deep.py:1-293 · blob ea873d731bd981c87d223457b9b297fe44aa9c8e · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
import json, subprocess, collections, datetime, os, sys, pathlib, urllib.request, time, statistics
from concurrent.futures import ThreadPoolExecutor, as_completed
GH = pathlib.Path("C:/Users/vikra/OneDrive/Documents/GitHub")
WORK = pathlib.Path(sys.argv[1])
OUT = sys.argv[2]
NPROC = os.cpu_count() or 8
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"]
def run(*a, cwd=None, timeout=600):
try:
r = subprocess.run(a, cwd=cwd, capture_output=True, text=True,
errors="replace", timeout=timeout)
return r.returncode, r.stdout, r.stderr
except Exception as ex:
return 1, "", str(ex)[:160]
def fetch(name):
dst = WORK / name
if not (dst / ".git").exists():
run("git", "clone", "--shared", "--no-checkout", str(GH/name/".git"), str(dst), timeout=900)
run("git", "remote", "add", "gh", "https://github.com/Ventusltd/" + name + ".git", cwd=dst)
run("git", "fetch", "-q", "--no-tags", "gh", "+refs/heads/*:refs/remotes/gh/*", cwd=dst, timeout=1200)
return name, str(dst)
def api(url):
req = urllib.request.Request(url, headers={"Accept": "application/vnd.github+json",
"User-Agent": "estate-scan"})
with urllib.request.urlopen(req, timeout=90) as r:
return json.load(r)
def ci(name):
try:
return name, api("https://api.github.com/repos/Ventusltd/%s/actions/runs?per_page=100" % name)
except Exception as ex:
return name, {"error": str(ex)[:100]}
def probe(name):
url = "https://ventusltd.github.io/%s/" % name
try:
req = urllib.request.Request(url, method="GET", headers={"User-Agent": "estate-scan"})
t0 = time.time()
with urllib.request.urlopen(req, timeout=25) as r:
body = r.read()
return name, {"url": url, "status": r.status, "bytes": len(body),
"ms": int((time.time() - t0) * 1000),
"last_modified": r.headers.get("Last-Modified", "-"),
"server": r.headers.get("Server", "-")}
except urllib.error.HTTPError as e:
return name, {"url": url, "status": e.code, "bytes": 0, "ms": 0,
"last_modified": "-", "server": "-"}
except Exception as ex:
return name, {"url": url, "status": 0, "error": str(ex)[:60]}
def ref_of(dst):
for r in ("gh/main", "gh/master"):
if run("git", "rev-parse", "--verify", "-q", r, cwd=dst)[0] == 0:
return r
return None
SIZE_UNITS = ["B", "KB", "MB", "GB"]
def human(n):
f = float(n)
for u in SIZE_UNITS:
if f < 1024 or u == "GB":
return ("%.0f %s" % (f, u)) if u == "B" else ("%.1f %s" % (f, u))
f /= 1024
def deep(name, dst):
ref = ref_of(dst)
if not ref:
return {"name": name, "error": "no default branch"}
o = {"name": name, "ref": ref.split("/")[-1]}
_, log, _ = run("git", "log", ref, "--date=iso-strict",
"--pretty=format:\x01%H|%ad|%an|%ae|%P|%s", "--numstat", cwd=dst)
commits, cur = [], None
for line in log.splitlines():
if line.startswith("\x01"):
p = line[1:].split("|", 5)
cur = {"sha": p[0], "iso": p[1], "an": p[2], "ae": p[3],
"parents": p[4].split(), "subj": p[5] if len(p) > 5 else "",
"add": 0, "del": 0, "files": 0, "paths": []}
commits.append(cur)
continue
if cur and line.strip():
f = line.split("\t")
if len(f) == 3:
a, d, pth = f
cur["add"] += int(a) if a.isdigit() else 0
cur["del"] += int(d) if d.isdigit() else 0
cur["files"] += 1
cur["paths"].append(pth)
if not commits:
return {"name": name, "error": "empty history"}
dt = [datetime.datetime.fromisoformat(c["iso"]) for c in commits]
first, last = dt[-1], dt[0]
span_days = max(1, (last - first).days)
o["head"] = commits[0]["sha"]
o["head_iso"] = commits[0]["iso"]
o["head_subj"] = commits[0]["subj"][:88]
o["first_iso"] = commits[-1]["iso"]
o["span_days"] = span_days
o["commits"] = len(commits)
o["merges"] = sum(1 for c in commits if len(c["parents"]) > 1)
o["add_total"] = sum(c["add"] for c in commits)
o["del_total"] = sum(c["del"] for c in commits)
o["files_touched"] = sum(c["files"] for c in commits)
o["per_day"] = round(len(commits) / span_days, 2)
sizes = sorted(c["files"] for c in commits)
o["files_median"] = sizes[len(sizes)//2]
o["files_max"] = sizes[-1]
gaps = [(dt[i-1] - dt[i]).total_seconds()/3600 for i in range(1, len(dt))]
o["gap_max_h"] = round(max(gaps), 1) if gaps else 0
o["gap_med_h"] = round(statistics.median(gaps), 2) if gaps else 0
o["authors"] = [{"n": a, "c": c} for a, c in
collections.Counter(x["an"] for x in commits).most_common(8)]
o["authors_total"] = len({x["an"] for x in commits})
hod = collections.Counter(d.hour for d in dt)
o["hours"] = [hod.get(h, 0) for h in range(24)]
dow = collections.Counter(d.weekday() for d in dt)
o["dow"] = [dow.get(i, 0) for i in range(7)]
today = datetime.date.today()
per = collections.Counter(d.date().isoformat() for d in dt)
o["days30"] = [{"d": (today - datetime.timedelta(days=i)).isoformat(),
"n": per.get((today - datetime.timedelta(days=i)).isoformat(), 0)}
for i in range(29, -1, -1)]
o["c1"] = sum(1 for d in dt if (datetime.datetime.now(d.tzinfo) - d).days < 1)
o["c7"] = sum(1 for d in dt if (datetime.datetime.now(d.tzinfo) - d).days < 7)
o["c30"] = sum(1 for d in dt if (datetime.datetime.now(d.tzinfo) - d).days < 30)
dirs = collections.Counter()
for c in commits[:400]:
for p in c["paths"]:
dirs[p.split("/")[0] if "/" in p else "(root)"] += 1
o["areas"] = [{"d": k, "n": v} for k, v in dirs.most_common(8)]
_, tree, _ = run("git", "ls-tree", "-r", "-l", ref, cwd=dst)
exts, total_bytes, depths, biggest = collections.Counter(), 0, [], []
nfiles = 0
for line in tree.splitlines():
try:
meta, path = line.split("\t", 1)
parts = meta.split()
size = int(parts[3]) if parts[3].isdigit() else 0
except Exception:
continue
nfiles += 1
total_bytes += size
depths.append(path.count("/"))
base = path.rsplit("/", 1)[-1]
ext = ("." + base.rsplit(".", 1)[1].lower()) if "." in base else "(none)"
exts[ext] += 1
biggest.append((size, path))
biggest.sort(reverse=True)
o["tracked_files"] = nfiles
o["tracked_bytes"] = total_bytes
o["tracked_human"] = human(total_bytes)
o["depth_max"] = max(depths) if depths else 0
o["depth_avg"] = round(sum(depths)/len(depths), 2) if depths else 0
o["exts"] = [{"e": e, "n": n} for e, n in exts.most_common(10)]
o["biggest"] = [{"p": p[:56], "b": human(s)} for s, p in biggest[:5]]
_, br, _ = run("git", "branch", "-r", "--list", "gh/*", "--format=%(refname:short)|%(committerdate:short)", cwd=dst)
brs = []
for line in br.splitlines():
if not line.strip() or "->" in line:
continue
nm, _, dd = line.partition("|")
nm = nm.strip()[3:]
if nm and nm != o["ref"]:
_, cnt, _ = run("git", "rev-list", "--count", "%s..gh/%s" % (ref, nm), cwd=dst)
brs.append({"b": nm[:46], "d": dd, "ahead": cnt.strip() or "?"})
o["branch_rows"] = sorted(brs, key=lambda x: x["d"], reverse=True)[:8]
o["branches"] = len(brs) + 1
canon = GH / name
_, wt, _ = run("git", "worktree", "list", cwd=canon)
o["worktrees"] = len([l for l in wt.splitlines() if l.strip()])
wf = canon / ".github" / "workflows"
o["workflow_files"] = (len(list(wf.glob("*.yml"))) + len(list(wf.glob("*.yaml")))) if wf.exists() else 0
return o
t0 = time.time()
prep, ciraw, probes = {}, {}, {}
with ThreadPoolExecutor(max_workers=NPROC * 3) as ex:
fs = ([ex.submit(fetch, n) for n in REPOS] +
[ex.submit(ci, n) for n in REPOS] +
[ex.submit(probe, n) for n in REPOS])
for f in as_completed(fs):
n, v = f.result()
if isinstance(v, str):
prep[n] = v
elif "workflow_runs" in v or "error" in v and "status" not in v:
ciraw[n] = v
else:
probes[n] = v
print("[fetch+api+probe %.1fs]" % (time.time() - t0), file=sys.stderr)
t1 = time.time()
out = {}
with ThreadPoolExecutor(max_workers=NPROC) as ex:
fs = {ex.submit(deep, n, d): n for n, d in prep.items()}
for f in as_completed(fs):
n = fs[f]
try:
out[n] = f.result()
except Exception as ex2:
out[n] = {"name": n, "error": str(ex2)[:120]}
print("[deep %.1fs]" % (time.time() - t1), file=sys.stderr)
for n, d in ciraw.items():
o = out.setdefault(n, {"name": n})
runs = d.get("workflow_runs", [])
if not runs:
o["ci"] = {"sampled": 0, "total_count": d.get("total_count", 0)}
continue
def dur(r):
try:
a = datetime.datetime.fromisoformat(r["run_started_at"].replace("Z", "+00:00"))
b = datetime.datetime.fromisoformat(r["updated_at"].replace("Z", "+00:00"))
return max(0, int((b - a).total_seconds()))
except Exception:
return 0
byw = collections.defaultdict(lambda: {"t": 0, "f": 0, "s": 0, "d": [], "last": None, "lc": None})
for r in runs:
w = byw[r["name"]]
w["t"] += 1
if r["conclusion"] == "failure": w["f"] += 1
if r["conclusion"] == "success": w["s"] += 1
w["d"].append(dur(r))
if w["last"] is None or r["created_at"] > w["last"]:
w["last"], w["lc"] = r["created_at"], r["conclusion"]
wfs = []
for k, v in byw.items():
ds = sorted(x for x in v["d"] if x)
wfs.append({"n": k[:60], "t": v["t"], "f": v["f"], "s": v["s"],
"med": ds[len(ds)//2] if ds else 0,
"max": ds[-1] if ds else 0,
"last": v["last"], "lc": v["lc"]})
wfs.sort(key=lambda x: (-x["f"], -x["t"]))
alld = sorted(x for x in (dur(r) for r in runs) if x)
dep = [r for r in runs if ("ages" in r["name"] or "eploy" in r["name"])]
okd = [r for r in dep if r["conclusion"] == "success"]
consec = 0
for r in dep:
if r["conclusion"] == "failure": consec += 1
else: break
ev = collections.Counter(r["event"] for r in runs)
o["ci"] = {
"sampled": len(runs), "total_count": d.get("total_count", 0),
"success": sum(1 for r in runs if r["conclusion"] == "success"),
"failure": sum(1 for r in runs if r["conclusion"] == "failure"),
"cancelled": sum(1 for r in runs if r["conclusion"] == "cancelled"),
"window": [runs[-1]["created_at"], runs[0]["created_at"]],
"last_run": runs[0]["created_at"], "last_conclusion": runs[0]["conclusion"],
"dur_med": alld[len(alld)//2] if alld else 0,
"dur_max": alld[-1] if alld else 0,
"dur_sum": sum(alld),
"events": [{"e": k, "n": v} for k, v in ev.most_common(5)],
"deploy_consec_fail": consec,
"deploy_last_ok": okd[0]["created_at"] if okd else None,
"workflows": wfs,
}
for n, p in probes.items():
out.setdefault(n, {"name": n})["http"] = p
res = {"generated_utc": datetime.datetime.now(datetime.UTC).strftime("%Y-%m-%dT%H:%M:%SZ"),
"workers": NPROC, "elapsed_s": round(time.time() - t0, 1),
"repos": [out[n] for n in REPOS if n in out]}
json.dump(res, open(OUT, "w"), indent=1)
print("[total %.1fs] repos=%d bytes=%d" % (time.time() - t0, len(res["repos"]),
os.path.getsize(OUT)), file=sys.stderr)