GLOBALGRID2050 / EXPLORE CODE

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

Estate and 6 more files

A Python module in the scripts folder of Claude using data from GitHub API.

667 lines of Python and JavaScript from claude, in 7 files. Topic: AI agents and coordination. Section 1612 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. Dupcheck other · claude / sessions/202609021835-estate-and-corridor/scripts/dupcheck.py lines 1–53
  2. Edge Rail ingest · claude / sessions/202609021835-estate-and-corridor/scripts/edge_rail.py lines 1–61
  3. Estate storage · claude / sessions/202609021835-estate-and-corridor/scripts/estate.py lines 1–210
  4. Extra Count storage · claude / sessions/202609021835-estate-and-corridor/scripts/extra_count.py lines 1–79
  5. Growth storage · claude / sessions/202609021835-estate-and-corridor/scripts/growth.py lines 1–98
  6. Headless render · claude / sessions/202609021835-estate-and-corridor/scripts/headless.mjs lines 1–46
  7. Loc storage · claude / sessions/202609021835-estate-and-corridor/scripts/loc.py lines 1–120

Dupcheck

A Python command-line tool in the scripts folder of Claude.

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

What it does
Defines main. Uses libraries subprocess, collections, os, sys, concurrent.futures. 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).
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
No statement of purpose was found in the file, a README line naming it, or its name. 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; it is an entry point.
Application
claude · sessions/202609021835-estate-and-corridor/scripts · Python CLI
Uses
Datapoints (import), subprocess, collections, os, sys, concurrent.futures
Used by
none found
Produces
main
Defines here
main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
claude@df9da02425fdf0c65d11a84f32cd9b3ef927b309 sessions/202609021835-estate-and-corridor/scripts/dupcheck.py:1-53 · blob eb78bab06bf1be348540d3f9ca8dda11a0a5d12c · GitHub at these lines
State
achieves: name · context: readme_derived · stage: unknown · effects: process · domain stage: agent_infra · users: ai_agent · canonical: unknown
import subprocess, collections, os, sys
sys.argv = ['dupcheck', '../clones']
import datapoints as DP
from concurrent.futures import ProcessPoolExecutor

ROOT = '../clones'
copies, meta = collections.Counter(), {}

def main():
    for r in DP.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:
                m, path = line.split('\t', 1)
                p = m.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 DP.DATA:
                continue
            copies[sha] += 1
            meta.setdefault(sha, (r, sha, path, ext, size))

    jobs = [meta[s] for s in copies]
    jobs.sort(key=lambda j: -j[4])
    with ProcessPoolExecutor(max_workers=10) as ex:
        res = list(ex.map(DP.work, jobs))
    per = {j[1]: r['dp'] for j, r in zip(jobs, res)}
    uniq = sum(per.values())
    allc = sum(per[s] * copies[s] for s in per)
    print('datapoints, unique content only : %16s' % f'{uniq:,}')
    print('datapoints, counting every copy : %16s' % f'{allc:,}')
    print('inflation from duplicate copies : %16s   (x%.2f)' % (f'{allc - uniq:,}', allc / uniq))
    worst = sorted(copies.items(), key=lambda kv: -per.get(kv[0], 0) * (kv[1] - 1))[:5]
    print('\nmost-duplicated content by datapoint impact:')
    for sha, c in worst:
        if c > 1:
            print('   %3d copies  x %12s dp  = %14s inflated' %
                  (c, f'{per[sha]:,}', f'{per[sha] * (c - 1):,}'))

if __name__ == '__main__':
    main()

Edge Rail

A Python command-line tool in the scripts folder of Claude.

ingestclaude / sessions/202609021835-estate-and-corridor/scripts/edge_rail.py · lines 1–61 of 61 · version 2026-09-02 18:35 · Entry point · pattern _chunk (shared by 2 files)

What it does
It loads data. Defines _init, _chunk, main. Uses libraries os, json, array, time, 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: command-line arguments.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Precompute, for every road edge, how many railway segments it crosses.
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), os, json, array, time, sys, concurrent.futures
Used by
none found
Produces
main
Defines here
_init, _chunk, 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/edge_rail.py:1-61 · blob 6691153fb2e7bcb296a3d59c521c31fb033dbc9b · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
"""Precompute, for every road edge, how many railway segments it crosses.

Windows-safe multiprocessing: worker lives in a real module with a __main__ guard.
"""
import os, json, array, time, sys
from concurrent.futures import ProcessPoolExecutor
from common import HERE

_G = None
_R = None


def _init(pre):
    global _G, _R
    from router import Graph
    from rail import RailIndex
    _G = Graph(pre)
    _R = RailIndex()


def _chunk(args):
    lo, hi = args
    G = _G; R = _R
    out = []
    for eid in range(lo, hi):
        gm = G.edge_geometry(eid)
        if len(gm) < 4:
            continue
        n = R.count_crossings(gm)
        if n:
            out.append((eid, n))
    return out


def main(pre="roads", workers=10):
    from router import Graph
    G = Graph(pre)
    m = G.meta["edges"]
    del G
    step = (m + workers * 4 - 1) // (workers * 4)
    tasks = [(i, min(i + step, m)) for i in range(0, m, step)]
    t0 = time.time()
    counts = array.array("i", bytes(4 * m))
    with ProcessPoolExecutor(max_workers=workers,
                             initializer=_init, initargs=(pre,)) as ex:
        done = 0
        for res in ex.map(_chunk, tasks):
            for eid, n in res:
                counts[eid] = n
            done += 1
            print("  chunk %d/%d  %.0fs" % (done, len(tasks), time.time() - t0), flush=True)
    nz = sum(1 for c in counts if c)
    tot = sum(counts)
    print("edges=%d crossing_edges=%d (%.2f%%) total_crossings=%d  %.0fs" %
          (m, nz, 100.0 * nz / m, tot, time.time() - t0))
    with open(os.path.join(HERE, "graph", pre + ".railcnt.bin"), "wb") as fh:
        counts.tofile(fh)


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

Estate

A Python module in the scripts folder of Claude using data from GitHub API.

storageclaude / sessions/202609021835-estate-and-corridor/scripts/estate.py · lines 1–210 of 210 · version 2026-09-02 18:35 · Not reached from any entry point (candidate for review) · pattern stats (shared by 6 files)

What it does
It fetches data. Defines 7 functions or classes, including run, prepare, default_ref, api, ci. 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 API step (`api`), the stats step (`stats`) and the since step (`since`). Defines `run`, `prepare`, `default_ref` and 3 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, prepare, default_ref, api, ci, stats
Defines here
run, prepare, default_ref, api, ci, stats, since
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/estate.py:1-210 · blob 18ee4debbc7189ea13c9e0b5c1be4f18b933cc13 · 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
from concurrent.futures import ThreadPoolExecutor, as_completed

GH   = pathlib.Path("C:/Users/vikra/OneDrive/Documents/GitHub")
WORK = pathlib.Path(sys.argv[1])
WORK.mkdir(parents=True, exist_ok=True)
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=300):
    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 prepare(name):
    dst = WORK / name
    if not (dst / ".git").exists():
        rc, _, e = run("git","clone","--shared","--no-checkout",
                       str(GH/name/".git"), str(dst), timeout=900)
        if rc:
            return ("prep", name, None, "clone: " + e.strip()[:160])
    run("git","remote","add","gh","https://github.com/Ventusltd/" + name + ".git", cwd=dst)
    rc, _, e = run("git","fetch","-q","--no-tags","gh",
                   "+refs/heads/*:refs/remotes/gh/*", cwd=dst, timeout=1200)
    if rc:
        return ("prep", name, str(dst), "fetch: " + e.strip()[:160])
    return ("prep", name, str(dst), None)

def default_ref(dst):
    for r in ("gh/main","gh/master"):
        if run("git","rev-parse","--verify","-q",r, cwd=dst)[0] == 0:
            return r
    return None

def api(url):
    req = urllib.request.Request(url, headers={"Accept":"application/vnd.github+json",
                                               "User-Agent":"estate-scan"})
    with urllib.request.urlopen(req, timeout=60) as r:
        return json.load(r)

def ci(name):
    try:
        d = api("https://api.github.com/repos/Ventusltd/" + name + "/actions/runs?per_page=100")
        return ("ci", name, d, None)
    except Exception as ex:
        return ("ci", name, None, str(ex)[:120])

def stats(name, dst):
    ref = default_ref(dst)
    if not ref:
        return {"name": name, "error": "no main/master branch on remote"}
    o = {"name": name, "ref": ref.split("/")[-1]}

    _, log, _ = run("git","log",ref,"--date=short",
                    "--pretty=format:%H|%ad|%aI|%an|%s","--numstat", cwd=dst, timeout=900)
    commits, cur = [], None
    for line in log.splitlines():
        if len(line) > 41 and line[40] == "|":
            p = line.split("|", 4)
            cur = {"sha":p[0], "date":p[1], "iso":p[2], "author":p[3],
                   "subject":p[4] if len(p) > 4 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"}

    today = datetime.date.today()
    def since(days):
        c = (today - datetime.timedelta(days=days)).isoformat()
        return [x for x in commits if x["date"] >= c]
    d1, d7, d30 = since(1), since(7), since(30)

    o.update({
        "commits_total": len(commits),
        "first": commits[-1]["date"],
        "head_sha": commits[0]["sha"][:7],
        "head_iso": commits[0]["iso"],
        "head_subject": commits[0]["subject"][:96],
        "head_author": commits[0]["author"],
        "c24h": len(d1), "c7d": len(d7), "c30d": len(d30),
        "add30": sum(x["add"] for x in d30),
        "del30": sum(x["del"] for x in d30),
        "files30": sum(x["files"] for x in d30),
        "active_days_30": len({x["date"] for x in d30}),
        "authors_30": len({x["author"] for x in d30}),
    })

    days = [(today - datetime.timedelta(days=i)).isoformat() for i in range(13, -1, -1)]
    per = collections.Counter(x["date"] for x in commits)
    o["spark"] = [{"d": d, "n": per.get(d, 0)} for d in days]

    dirs = collections.Counter()
    for c in d30:
        for p in c["paths"]:
            dirs[p.split("/")[0] if "/" in p else "(root)"] += 1
    o["areas"] = [{"dir": k, "n": v} for k, v in dirs.most_common(5)]

    _, br, _ = run("git","branch","-r","--list","gh/*","--format=%(refname:short)", cwd=dst)
    o["branches"] = len([b for b in br.splitlines() if b.strip() and "->" not in b])

    canon = GH / name
    _, wt, _ = run("git","worktree","list", cwd=canon)
    o["worktrees"] = len([l for l in wt.splitlines() if l.strip()])

    _, lh, _ = run("git","rev-parse","--short","HEAD", cwd=canon)
    lh = lh.strip()
    o["local_head"] = lh
    if lh:
        _, ct, _ = run("git","rev-list","--left-right","--count", lh + "..." + ref, cwd=dst)
        parts = ct.split()
        o["local_ahead"], o["local_behind"] = (parts + ["?","?"])[:2]

    wf = canon / ".github" / "workflows"
    o["workflow_files"] = (len(list(wf.glob("*.yml"))) + len(list(wf.glob("*.yaml")))) if wf.exists() else 0

    _, tree, _ = run("git","ls-tree","-r",ref,"--name-only", cwd=dst, timeout=600)
    o["tracked_files"] = len(tree.splitlines())
    return o


t0 = time.time()
prepared, ci_raw = {}, {}
with ThreadPoolExecutor(max_workers=NPROC * 2) as ex:
    futs = [ex.submit(prepare, n) for n in REPOS] + [ex.submit(ci, n) for n in REPOS]
    for f in as_completed(futs):
        kind, n, a, b = f.result()
        if kind == "prep":
            prepared[n] = (a, b)
        else:
            ci_raw[n] = (a, b)
print("[prep+api %.1fs]" % (time.time() - t0), file=sys.stderr)

t1 = time.time()
out = {}
with ThreadPoolExecutor(max_workers=NPROC) as ex:
    futs = {ex.submit(stats, n, dst): n for n, (dst, err) in prepared.items() if dst}
    for f in as_completed(futs):
        n = futs[f]
        try:
            out[n] = f.result()
        except Exception as ex2:
            out[n] = {"name": n, "error": str(ex2)[:140]}
print("[stats %.1fs]" % (time.time() - t1), file=sys.stderr)

for n, (dst, err) in prepared.items():
    if err:
        out.setdefault(n, {"name": n})["prep_error"] = err

for n, (d, err) in ci_raw.items():
    o = out.setdefault(n, {"name": n})
    if err or not d:
        o["ci"] = {"error": err or "no data"}
        continue
    runs = d.get("workflow_runs", [])
    if not runs:
        o["ci"] = {"total_count": d.get("total_count", 0), "sampled": 0}
        continue
    s  = sum(1 for r in runs if r["conclusion"] == "success")
    fl = sum(1 for r in runs if r["conclusion"] == "failure")
    byw = collections.defaultdict(lambda: {"total":0, "fail":0, "last":None, "last_c":None})
    for r in runs:
        w = byw[r["name"]]
        w["total"] += 1
        if r["conclusion"] == "failure":
            w["fail"] += 1
        if w["last"] is None or r["created_at"] > w["last"]:
            w["last"], w["last_c"] = r["created_at"], r["conclusion"]
    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
    o["ci"] = {
        "total_count": d.get("total_count", 0),
        "sampled": len(runs),
        "success": s, "failure": fl,
        "window": [runs[-1]["created_at"], runs[0]["created_at"]],
        "last_run": runs[0]["created_at"],
        "last_conclusion": runs[0]["conclusion"],
        "deploy_wf": dep[0]["name"] if dep else None,
        "deploy_last_ok": okd[0]["created_at"] if okd else None,
        "deploy_consec_fail": consec,
        "workflows": sorted([dict(name=k, **v) for k, v in byw.items()],
                            key=lambda x: (-x["fail"], -x["total"]))[:10],
    }

res = {"generated_utc": datetime.datetime.now(datetime.UTC).strftime("%Y-%m-%dT%H:%M:%SZ"),
       "workers": NPROC,
       "repos": [out[n] for n in REPOS if n in out]}
json.dump(res, open(sys.argv[2], "w"), indent=1)
print("[total %.1fs] repos=%d" % (time.time() - t0, len(res["repos"])), file=sys.stderr)

Extra Count

A Python module in the scripts folder of Claude.

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

What it does
It loads data. Uses libraries subprocess, os, sys, io, json. 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
In: command-line arguments. Out: JSON file extra.json.
What it achieves
It writes `extra.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
Datapoints (import), subprocess, os, sys, io, json, collections, 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/extra_count.py:1-79 · blob a6a272614c205faef018375e9549c3b7b68efa10 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, process, storage · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
import subprocess, os, sys, io, json, collections
sys.argv = ['extra', '../clones']
import datapoints as DP
import pyarrow.parquet as pq

ROOT = '../extra'
DATA = DP.DATA | {'.parquet'}
CODE = {'.py','.mjs','.js','.cjs','.ts','.tsx','.jsx','.sh','.bash','.ps1','.awk','.sql',
        '.rb','.go','.rs','.java','.c','.h','.cpp','.html','.htm','.svg','.css','.scss',
        '.xml','.yml','.yaml','.toml','.ini','.cfg'}

repos = sorted(d[:-4] for d in os.listdir(ROOT) if d.endswith('.git'))
tot_dp = tot_loc = tot_files = 0
rows = []

for r in repos:
    g = os.path.join(ROOT, r + '.git')
    ref = subprocess.run(['git', '-C', g, 'for-each-ref', '--format=%(refname:short)', 'refs/heads'],
                         capture_output=True, text=True).stdout.split('\n')[0].strip()
    if not ref:
        rows.append((r, 0, 0, 0)); continue

    # lines of code / markup / config
    out = subprocess.run(['git', '-C', g, 'grep', '-I', '-c', '', ref, '--', '.'],
                         capture_output=True, text=True, errors='replace').stdout
    loc = 0
    prefix = ref + ':'
    for line in out.splitlines():
        if not line.startswith(prefix):
            continue
        path, _, n = line[len(prefix):].rpartition(':')
        if not n.isdigit():
            continue
        base = path.rsplit('/', 1)[-1]
        ext = ('.' + base.rsplit('.', 1)[1].lower()) if '.' in base[1:] else ''
        if ext in CODE:
            loc += int(n)

    # datapoints
    tree = subprocess.run(['git', '-C', g, 'ls-tree', '-r', ref],
                          capture_output=True, text=True, errors='replace').stdout
    dp = nf = 0
    for line in tree.splitlines():
        try:
            meta, path = line.split('\t', 1)
            sha = meta.split()[2]
        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
        nf += 1
        try:
            buf = subprocess.run(['git', '-C', g, 'cat-file', 'blob', sha],
                                 capture_output=True, timeout=300).stdout
        except Exception:
            continue
        if ext in ('.csv', '.tsv'):
            dp += DP.count_csv(buf, b'\t' if ext == '.tsv' else b',')[0]
        elif ext == '.parquet':
            try:
                f = pq.ParquetFile(io.BytesIO(buf))
                dp += f.metadata.num_rows * f.metadata.num_columns
            except Exception:
                pass
        else:
            dp += DP.count_json(buf)
    rows.append((r, loc, dp, nf))
    tot_loc += loc; tot_dp += dp; tot_files += nf

print('%-52s %10s %14s %7s' % ('repo', 'code lines', 'datapoints', 'files'))
print('-' * 88)
for r, loc, dp, nf in sorted(rows, key=lambda x: -x[2]):
    print('%-52s %10s %14s %7d' % (r[:52], f'{loc:,}', f'{dp:,}', nf))
print('-' * 88)
print('%-52s %10s %14s %7d' % ('TOTAL (14 repos, fork excluded)',
                               f'{tot_loc:,}', f'{tot_dp:,}', tot_files))
json.dump({'loc': tot_loc, 'datapoints': tot_dp, 'rows': rows}, open('extra.json', 'w'), indent=1)

Growth

A Python command-line tool in the scripts folder of Claude that works with first added (`first_added`) and blob points (`blob_points`).

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

What it does
It loads data. Defines first_added, blob_points, main. 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
In: command-line arguments. Out: JSON file growth.json.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
When did the datapoints actually arrive? It writes `growth.json`.
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
Datapoints (import), subprocess, collections, os, io, sys, json, pyarrow.parquet
Used by
none found
Produces
first_added, blob_points, main
Defines here
first_added, blob_points, 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/growth.py:1-98 · blob 5898820122d907c3d2e95b82c9405a6149cedc61 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process, storage · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
"""When did the datapoints actually arrive?

For every unique data blob, find the date its path first appeared in history,
then bucket datapoints by month. Answers whether growth is steady or lumpy.
"""
import subprocess, collections, os, io, sys, json
import pyarrow.parquet as pq
sys.argv = ['growth', '../clones']
import datapoints as DP

ROOT  = '../clones'
REPOS = DP.REPOS
TEXT  = DP.DATA


def first_added(repo, ref):
    """path -> earliest date the path was added."""
    out = subprocess.run(
        ['git', '-C', os.path.join(ROOT, repo), 'log', ref, '--reverse',
         '--diff-filter=A', '--name-only', '--date=short', '--format=%x01%ad'],
        capture_output=True, text=True, errors='replace').stdout
    date, m = None, {}
    for line in out.splitlines():
        if line.startswith('\x01'):
            date = line[1:].strip()
        elif line.strip() and date:
            m.setdefault(line.strip(), date)
    return m


def blob_points(repo, sha, path):
    ext = ('.' + path.rsplit('.', 1)[1].lower()) if '.' in path.rsplit('/', 1)[-1][1:] else ''
    try:
        buf = subprocess.run(['git', '-C', os.path.join(ROOT, repo), 'cat-file', 'blob', sha],
                             capture_output=True, timeout=600).stdout
    except Exception:
        return 0
    if ext in ('.csv', '.tsv'):
        return DP.count_csv(buf, b'\t' if ext == '.tsv' else b',')[0]
    if ext == '.parquet':
        try:
            f = pq.ParquetFile(io.BytesIO(buf))
            return f.metadata.num_rows * f.metadata.num_columns
        except Exception:
            return 0
    return DP.count_json(buf)


def main():
    seen = {}
    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
        added = first_added(r, ref)
        out = subprocess.run(['git', '-C', os.path.join(ROOT, r), 'ls-tree', '-r', ref],
                             capture_output=True, text=True, errors='replace').stdout
        for line in out.splitlines():
            try:
                meta, path = line.split('\t', 1)
                sha = meta.split()[2]
            except Exception:
                continue
            base = path.rsplit('/', 1)[-1]
            ext = ('.' + base.rsplit('.', 1)[1].lower()) if '.' in base[1:] else ''
            if ext not in TEXT and ext != '.parquet':
                continue
            d = added.get(path, '9999-99-99')
            if sha not in seen or d < seen[sha][2]:
                seen[sha] = (r, path, d)

    by_month = collections.Counter()
    files_month = collections.Counter()
    for sha, (r, path, d) in seen.items():
        n = blob_points(r, sha, path)
        by_month[d[:7]] += n
        files_month[d[:7]] += 1

    total = sum(by_month.values())
    print('%-9s %16s %16s %8s' % ('month', 'datapoints', 'cumulative', 'files'))
    print('-' * 54)
    run = 0
    for m in sorted(by_month):
        run += by_month[m]
        print('%-9s %16s %16s %8d' % (m, f'{by_month[m]:,}', f'{run:,}', files_month[m]))
    print('-' * 54)
    print('%-9s %16s' % ('TOTAL', f'{total:,}'))
    json.dump({'by_month': dict(by_month), 'files_month': dict(files_month), 'total': total},
              open('growth.json', 'w'), indent=1)


if __name__ == '__main__':
    main()

Headless

A JavaScript module in the scripts folder of Claude.

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

What it does
It draws its content. Uses libraries node:fs, node:vm. Side effects: changes the web page (DOM); 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).
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/202609021835-estate-and-corridor/scripts · JavaScript module
Uses
node:fs, node:vm
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/headless.mjs:1-46 · blob adaa2a712ad095f7286a0772281d69f339f99bb1 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
import fs from 'node:fs';
import vm from 'node:vm';

const html = fs.readFileSync('log.html', 'utf8');
const js = html.split('<script>')[1].split('</script>')[0];

const box = { html: '', innerHTML: '', insertAdjacentHTML(_, s) { this.html += s; } };
const sandbox = {
  console,
  performance,
  document: {
    getElementById: id => (id === 'scan' ? box : null),
    body: { scrollHeight: 0 },
  },
  window: { scrollTo() {} },
  matchMedia: () => ({ matches: true }),   // reduced motion -> render all at once
  addEventListener() {},
  requestAnimationFrame() {},
  setTimeout() {},
  Date, Number, String, Math, JSON, Object, Array,
};
sandbox.globalThis = sandbox;

try {
  vm.createContext(sandbox);
  vm.runInContext(js, sandbox, { timeout: 20000 });
} catch (e) {
  console.error('THREW:', e.message);
  process.exit(1);
}

const out = box.innerHTML || box.html;
const lines = out.split('\n');
const plain = lines.map(l => l.replace(/<[^>]*>/g, ''));
console.log('RENDER OK');
console.log('lines        :', lines.length);
console.log('chars        :', out.length);
console.log('max line len :', Math.max(...plain.map(l => l.length)));
console.log('empty lines  :', plain.filter(l => !l.trim()).length);
console.log('undefined?   :', out.includes('undefined'));
console.log('NaN?         :', out.includes('NaN'));
console.log('[object      :', out.includes('[object'));
console.log('\n--- first 34 rendered lines ---');
console.log(plain.slice(0, 34).join('\n'));
console.log('\n--- last 26 rendered lines ---');
console.log(plain.slice(-26).join('\n'));

Loc

A Python module in the scripts folder of Claude.

storageclaude / sessions/202609021835-estate-and-corridor/scripts/loc.py · lines 1–120 of 120 · version 2026-09-02 18:35 · Not reached from any entry point (candidate for review) · pattern count (shared by 27 files)

What it does
It loads data. Defines count. Uses libraries json, subprocess, collections, os, 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.
What it achieves
Defines `count`.
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, os, sys, pathlib, datetime, time
Used by
none found
Produces
count
Defines here
count
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/loc.py:1-120 · blob 162b2005524a38434e8231ea0813577ddcdf6048 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
import json, subprocess, collections, os, sys, pathlib, datetime, time
from concurrent.futures import ThreadPoolExecutor, as_completed

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"]

# extension -> (language, class)  class: code | markup | config | data | docs
LANG = {
    '.py':('Python','code'), '.mjs':('JavaScript','code'), '.js':('JavaScript','code'),
    '.cjs':('JavaScript','code'), '.ts':('TypeScript','code'), '.tsx':('TypeScript','code'),
    '.jsx':('JavaScript','code'), '.sh':('Shell','code'), '.bash':('Shell','code'),
    '.ps1':('PowerShell','code'), '.awk':('Awk','code'), '.sql':('SQL','code'),
    '.r':('R','code'), '.rb':('Ruby','code'), '.go':('Go','code'), '.rs':('Rust','code'),
    '.java':('Java','code'), '.c':('C','code'), '.h':('C','code'), '.cpp':('C++','code'),
    '.html':('HTML','markup'), '.htm':('HTML','markup'), '.svg':('SVG','markup'),
    '.css':('CSS','markup'), '.scss':('CSS','markup'), '.xml':('XML','markup'),
    '.yml':('YAML','config'), '.yaml':('YAML','config'), '.toml':('TOML','config'),
    '.ini':('INI','config'), '.cfg':('INI','config'), '.gitattributes':('Git','config'),
    '.gitignore':('Git','config'), '.json':('JSON','data'), '.geojson':('GeoJSON','data'),
    '.csv':('CSV','data'), '.tsv':('TSV','data'), '.ndjson':('NDJSON','data'),
    '.md':('Markdown','docs'), '.txt':('Text','docs'), '.rst':('Text','docs'),
}
CODEISH = {'code', 'markup', 'config'}


def count(name):
    dst = WORK / name
    ref = None
    for r in ('gh/main', 'gh/master'):
        if subprocess.run(['git', '-C', str(dst), 'rev-parse', '--verify', '-q', r],
                          capture_output=True).returncode == 0:
            ref = r
            break
    if not ref:
        return {'name': name, 'error': 'no default branch'}

    r = subprocess.run(['git', '-C', str(dst), 'grep', '-I', '-c', '', ref, '--', '.'],
                       capture_output=True, text=True, errors='replace', timeout=1800)
    by_lang  = collections.Counter()
    by_files = collections.Counter()
    by_class = collections.Counter()
    cls_files = collections.Counter()
    total = files = 0
    prefix = ref + ':'
    for line in r.stdout.splitlines():
        if not line.startswith(prefix):
            continue
        rest = line[len(prefix):]
        path, _, n = rest.rpartition(':')
        if not n.isdigit():
            continue
        n = int(n)
        base = path.rsplit('/', 1)[-1]
        ext = ('.' + base.rsplit('.', 1)[1].lower()) if '.' in base[1:] else \
              (base.lower() if base.startswith('.') else '(none)')
        lang, cls = LANG.get(ext, ('Other', 'data' if ext == '(none)' else 'other'))
        by_lang[lang] += n
        by_files[lang] += 1
        by_class[cls] += n
        cls_files[cls] += 1
        total += n
        files += 1
    return {
        'name': name,
        'text_files': files,
        'lines_total': total,
        'lines_codeish': sum(by_class[c] for c in CODEISH),
        'files_codeish': sum(cls_files[c] for c in CODEISH),
        'by_class': [{'c': k, 'n': v, 'f': cls_files[k]} for k, v in by_class.most_common()],
        'by_lang': [{'l': k, 'n': v, 'f': by_files[k]} for k, v in by_lang.most_common(12)],
    }


t0 = time.time()
out = {}
with ThreadPoolExecutor(max_workers=NPROC) as ex:
    fs = {ex.submit(count, n): n for n in REPOS}
    for f in as_completed(fs):
        n = fs[f]
        try:
            out[n] = f.result()
        except Exception as e:
            out[n] = {'name': n, 'error': str(e)[:120]}

res = {'generated_utc': datetime.datetime.now(datetime.UTC).strftime('%Y-%m-%dT%H:%M:%SZ'),
       'elapsed_s': round(time.time() - t0, 1),
       'workers': NPROC,
       'repos': [out[n] for n in REPOS if n in out]}
json.dump(res, open(OUT, 'w'), indent=1)

W = 52
print('%-*s %10s %10s %10s' % (W, 'repository', 'text files', 'lines', 'code-ish'))
print('-' * (W + 33))
for r in res['repos']:
    if 'error' in r:
        print('%-*s %10s' % (W, r['name'], r['error']))
        continue
    print('%-*s %10s %10s %10s' % (W, r['name'], f"{r['text_files']:,}",
                                   f"{r['lines_total']:,}", f"{r['lines_codeish']:,}"))
print('-' * (W + 33))
print('%-*s %10s %10s %10s' % (W, 'TOTAL',
      f"{sum(r.get('text_files',0) for r in res['repos']):,}",
      f"{sum(r.get('lines_total',0) for r in res['repos']):,}",
      f"{sum(r.get('lines_codeish',0) for r in res['repos']):,}"))
print()
agg = collections.Counter()
aggf = collections.Counter()
for r in res['repos']:
    for e in r.get('by_lang', []):
        agg[e['l']] += e['n']; aggf[e['l']] += e['f']
print('%-16s %12s %10s' % ('language', 'lines', 'files'))
for l, n in agg.most_common(16):
    print('%-16s %12s %10s' % (l, f'{n:,}', f'{aggf[l]:,}'))
print('\nelapsed %.1fs  workers %d' % (res['elapsed_s'], NPROC), file=sys.stderr)