GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / claude / scripts

Claude Clean Clone Byte Survey and 6 more files

A Python command-line tool in the scripts folder that works with sha256 published (`sha256_published`) and eol census (`eol_census`), using SHA-256.

683 lines of Python and JavaScript from claude, code-generator, compass, in 7 files. Topic: Maps, GIS and field navigation. Section 466 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. Claude Clean Clone Byte Survey storage · claude / scripts/clean_clone_byte_survey.py lines 1–330
  2. Routefactor storage · claude / sessions/202609021835-estate-and-corridor/scripts/routefactor.py lines 1–102
  3. Router ingest · claude / sessions/202609021835-estate-and-corridor/scripts/router.py lines 1–170
  4. Context other · code-generator / apps/geodesy/context.mjs lines 1–3
  5. Geodesy geodesy · code-generator / apps/geodesy/geodesy.mjs lines 1–25
  6. Position Overlay transform · compass / upstream/tools/satnav/line/position-overlay.mjs lines 1–32
  7. Route Follower transform · compass / upstream/tools/satnav/line/route-follower.mjs lines 1–21

Claude Clean Clone Byte Survey

A Python command-line tool in the scripts folder that works with sha256 published (`sha256_published`) and eol census (`eol_census`), using SHA-256.

storageclaude / scripts/clean_clone_byte_survey.py · lines 1–330 of 330 · Entry point · pattern attributes (shared by 2 files)

What it does
It loads data. Defines 9 functions or classes, including git, sha256_published, eol_census, attributes, renormalise. Uses libraries argparse, hashlib, json, os, re. 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: JSON file current.json; JSON file byte-survey.json; command-line arguments. Out: JSON file.
Downstream impact
Used directly by 1 file: Claude Clean Clone Byte Survey Workflow (claude).
What it achieves
It is built from the git step (`git`), the attributes step (`attributes`) and the renormalise step (`renormalise`). What the bytes are, measured where the bytes are true. It accepts `--root`, `--repos` and `--out`.
Why it matters
Run by Claude Clean Clone Byte Survey Workflow.
Application
claude · scripts · Python CLI
Uses
argparse, hashlib, json, os, re, subprocess, sys, time
Used by
run by Claude Clean Clone Byte Survey Workflow (workflow run)
Produces
git, sha256_published, eol_census, attributes, renormalise, cartridges, survey_repo, board, main
Defines here
git, sha256_published, eol_census, attributes, renormalise, cartridges, survey_repo, board, 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 scripts/clean_clone_byte_survey.py:1-330 · blob 12b7fbbb8363ebf34a0bc0753e98510546241e9b · 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
"""clean_clone_byte_survey.py - what the bytes are, measured where the bytes are true.

WHY THIS CANNOT RUN ON THE LAPTOP

`git status` compares THROUGH `.gitattributes` normalisation. It reports a tree clean while
the disk holds CRLF and the blob holds LF. Fifteen of eighteen repositories here are in that
state. So every measurement that depends on file bytes - a digest, a checksum manifest, a
character ceiling - reads a different number on this Windows working tree than it will read
anywhere the artefact is actually served. A ceiling check run on the laptop is not wrong by
a rounding error; it is measuring a different file.

A GitHub runner checks out from the blob. It is the cheapest clean clone in the estate, it
is free on a public repository, and it can hold several repositories side by side. That is
why this survey belongs in the cloud and not here.

WHAT IT MEASURES

1. LINE ENDINGS, per repository, from `git ls-files --eol` on a fresh checkout:
   `i/crlf` (the blob itself is CRLF) is a different fact from `w/crlf` (only the disk is),
   and they are counted separately. One repository legitimately ships CRLF in the blob, so a
   single combined number would report a correct repository as broken.

   AND THE TRAP IN RUNNING THIS IN THE CLOUD AT ALL: on a Linux runner `w/crlf` is 0 for
   every repository BY CONSTRUCTION, because git only writes CRLF into a checkout on a
   platform that asks for it. Reading that as "the CRLF problem is fixed" would be a wrong
   conclusion delivered by this instrument. The runner answers what the repository SHIPS
   (`i/crlf`, and whether renormalising changes anything); the laptop answers what its own
   disk HOLDS. The board says so in as many words so the two are never confused.

2. `.gitattributes` CLASSIFICATION. The canonical line is `* text=auto eol=lf`. GitHub's
   default template is the bare `* text=auto`, which normalises on commit but lets the
   checkout be CRLF - the exact trap the estate's own note names. Bare is reported as `bare`,
   not as `present`, because "has a .gitattributes" is the answer that hides the problem.

3. RENORMALISATION. `git add --renormalize .` on a clean checkout must change nothing. Files
   it changes are stored differently from what `.gitattributes` requires.

4. THE CHARACTER CEILING, measured three ways, because THREE DIFFERENT NUMBERS ARE ENFORCED
   in this estate and they are not the same:

       368640   characters  the ceiling the cartridge proof ASSERTS (0.9 x 409600)
       400000   bytes       the ceiling tools/scope/loop.mjs lint GATES
       409600   bytes       the composer boundary, reported but not enforced

   and because characters are not bytes. The proof measures `source.length` - UTF-16 code
   units - while the lint measures `statSync().size`. Cartridges contain non-ASCII, so the
   two diverge, and a file can pass one and fail the other. Both are reported per cartridge
   with the divergence named, so nobody has to remember which gauge they were reading.

5. MANIFEST IDENTITY. Every cartridge `sha256` in `atlas/current.json` recomputed with the
   estate's own publication rule: text extensions are LF-normalised before hashing, binaries
   are hashed raw. A mismatch here is a manifest that describes a file the repository does
   not contain.

THIS IS AN INFORMATIONAL SURVEY. IT EXITS 0 ON EVERY FINDING, ALWAYS.

The gates that must block already exist and already fail loudly - `202608312212-cartridge-proof.yml`
in gridatlas is the model. This is not one of them, and a non-zero exit here would both mail
the actor and misrepresent what the job is. Findings live in the JSON and the board. If you
are about to "fix" this into a gate: don't. The gate is elsewhere and it is already red when
it needs to be.

    python scripts/clean_clone_byte_survey.py --root /path/holding/clones \
        --out survey.json --board docs/boards/bytes.md
"""

import argparse
import hashlib
import json
import os
import re
import subprocess
import sys
import time

# The estate's publication rule, from gridatlas tools/scope/lib.mjs sha256PublishedFile().
LF_NORMALISED = {'.js', '.mjs', '.cjs', '.css', '.html', '.htm', '.json', '.geojson',
                 '.txt', '.md', '.yml', '.yaml', '.svg'}

CARTRIDGE_CEILING_CHARS = 368640     # what the proof asserts
LOOP_GATE_BYTES = 400000             # what the lint gates
COMPOSER_BOUNDARY_BYTES = 409600     # what is reported

CANONICAL_ATTR = re.compile(r'^\s*\*\s+text=auto\s+eol=lf\s*$', re.M)
BARE_ATTR = re.compile(r'^\s*\*\s+text=auto\s*$', re.M)


def git(repo, *args, timeout=180):
    p = subprocess.run(['git', '-C', repo, *args], capture_output=True, text=True,
                       timeout=timeout, errors='replace')
    return p.returncode, p.stdout, p.stderr


def sha256_published(path):
    """Bytes as published: LF-normalised for text, raw for everything else."""
    with open(path, 'rb') as f:
        b = f.read()
    if os.path.splitext(path)[1].lower() in LF_NORMALISED:
        b = b.replace(b'\r\n', b'\n')
    return hashlib.sha256(b).hexdigest()


def eol_census(repo):
    rc, out, _ = git(repo, 'ls-files', '--eol')
    if rc != 0:
        return {'error': 'ls-files --eol failed'}
    c = {'files': 0, 'i_crlf': 0, 'i_mixed': 0, 'w_crlf': 0, 'w_mixed': 0}
    for line in out.splitlines():
        c['files'] += 1
        if 'i/crlf' in line:
            c['i_crlf'] += 1
        if 'i/mixed' in line:
            c['i_mixed'] += 1
        if 'w/crlf' in line:
            c['w_crlf'] += 1
        if 'w/mixed' in line:
            c['w_mixed'] += 1
    return c


def attributes(repo):
    p = os.path.join(repo, '.gitattributes')
    if not os.path.exists(p):
        return {'state': 'absent'}
    with open(p, 'rb') as f:
        raw = f.read()
    txt = raw.decode('utf-8', 'replace')
    if CANONICAL_ATTR.search(txt):
        state = 'canonical'
    elif BARE_ATTR.search(txt):
        # Normalises on commit, permits a CRLF checkout. The named trap.
        state = 'bare'
    else:
        state = 'other'
    return {'state': state, 'bytes': len(raw)}


def renormalise(repo):
    """On a clean checkout this must change nothing. Names the files if it does.

    The index is restored with `git reset` afterwards, which is safe ONLY because this runs
    on a fresh clone. On a working tree it would unstage whatever someone else had staged,
    so a dirty index is refused rather than surveyed - a measurement is never worth another
    lane's work in progress.
    """
    rc, staged, _ = git(repo, 'diff', '--cached', '--name-only')
    if rc != 0 or staged.strip():
        return {'skipped': 'index is not empty; this is not a fresh clone',
                'staged': len(staged.split())}
    rc, _, _ = git(repo, 'add', '--renormalize', '.')
    if rc != 0:
        return {'error': 'renormalize failed'}
    rc, out, _ = git(repo, 'diff', '--cached', '--name-only')
    files = [f for f in out.splitlines() if f]
    git(repo, 'reset', '-q')
    return {'changed': len(files), 'files': files[:40]}


def cartridges(repo):
    """gridatlas only: the character ceiling on all three gauges, plus manifest identity."""
    cur = os.path.join(repo, 'atlas', 'current.json')
    if not os.path.exists(cur):
        return None
    with open(cur, 'rb') as f:
        doc = json.loads(f.read().decode('utf-8'))
    rows = []
    for c in doc.get('cartridges', []):
        rel = (c.get('path') or '').lstrip('./')
        path = os.path.join(repo, 'atlas', rel)
        row = {'id': c.get('id'), 'generation': c.get('generation'), 'path': c.get('path'),
               'declared_sha256': c.get('sha256')}
        if not os.path.exists(path):
            row['state'] = 'missing'
            rows.append(row)
            continue
        with open(path, 'rb') as f:
            raw = f.read()
        src = raw.decode('utf-8', 'replace')
        row.update({
            'bytes': len(raw),
            'chars': len(src),
            # Characters and bytes diverge on every non-ASCII glyph. Naming the gap stops
            # the two gauges being quoted interchangeably.
            'bytes_minus_chars': len(raw) - len(src),
            'crlf_pairs': raw.count(b'\r\n'),
            'chars_vs_proof_ceiling': len(src) - CARTRIDGE_CEILING_CHARS,
            'bytes_vs_lint_gate': len(raw) - LOOP_GATE_BYTES,
            'bytes_vs_composer_boundary': len(raw) - COMPOSER_BOUNDARY_BYTES,
            'over_proof_ceiling': len(src) >= CARTRIDGE_CEILING_CHARS,
            'over_lint_gate': len(raw) > LOOP_GATE_BYTES,
            'measured_sha256': sha256_published(path),
        })
        row['sha256_matches'] = (row['measured_sha256'] == row['declared_sha256'])
        row['state'] = 'ok' if row['sha256_matches'] and not row['over_lint_gate'] else 'check'
        rows.append(row)
    return {'generation': doc.get('generation'), 'architecture': doc.get('architecture'),
            'cartridge_order': doc.get('cartridge_order'), 'rows': rows}


def survey_repo(root, name):
    repo = os.path.join(root, name)
    if not os.path.isdir(os.path.join(repo, '.git')):
        return {'repo': name, 'state': 'not-a-clone'}
    rc, head, _ = git(repo, 'rev-parse', 'HEAD')
    out = {'repo': name, 'state': 'surveyed', 'head': head.strip()[:12],
           'eol': eol_census(repo), 'gitattributes': attributes(repo),
           'renormalize': renormalise(repo)}
    carts = cartridges(repo)
    if carts:
        out['cartridges'] = carts
    return out


def board(res):
    L = []
    A = L.append
    A('# Clean-clone byte survey')
    A('')
    A('Measured on GitHub runners, which check out from the blob. The laptop cannot answer')
    A('these questions: `git status` compares through `.gitattributes`, so it reports clean')
    A('while the disk holds CRLF and the blob holds LF.')
    A('')
    A('INFORMATIONAL: this job exits 0 on every finding. The gates that must block already')
    A('exist and already fail loudly. This is a report.')
    A('')
    A('- surveyed at: `%s`' % res['generated_at'])
    A('- repositories: %d' % len(res['repos']))
    A('')
    A('## Line endings and `.gitattributes`')
    A('')
    A('`i/crlf` means the BLOB is CRLF - **the bytes that ship**, and the column to read')
    A('here. `w/crlf` means only the checkout is.')
    A('')
    A('**Do not read `w/crlf` from a Linux runner as good news.** Git only writes CRLF into')
    A('a checkout on a platform configured to want it, so on `ubuntu-24.04` this column is')
    A('0 by construction and says nothing about the Windows working tree, where 15 of 18')
    A('repositories hold CRLF on disk. Two different machines answer two different')
    A('questions: the runner says what the repository SHIPS, the laptop says what its own')
    A('disk HOLDS. `renormalize changes` and the `.gitattributes` column are the ones that')
    A('carry across both.')
    A('')
    A('| repo | head | tracked | i/crlf | w/crlf | mixed | .gitattributes | renormalize changes |')
    A('|---|---|---:|---:|---:|---:|---|---:|')
    for r in res['repos']:
        if r['state'] != 'surveyed':
            A('| `%s` | - | - | - | - | - | %s | - |' % (r['repo'], r['state']))
            continue
        e = r['eol']
        A('| `%s` | `%s` | %d | %d | %d | %d | %s | %d |'
          % (r['repo'], r['head'], e.get('files', 0), e.get('i_crlf', 0), e.get('w_crlf', 0),
             e.get('i_mixed', 0) + e.get('w_mixed', 0),
             r['gitattributes']['state'], r['renormalize'].get('changed', -1)))
    A('')
    bare = [r['repo'] for r in res['repos']
            if r.get('gitattributes', {}).get('state') == 'bare']
    if bare:
        A('`bare` means the file carries GitHub\'s default `* text=auto` with no `eol=lf`.')
        A('It normalises on commit and permits a CRLF checkout, which is the trap: %s.'
          % ', '.join('`%s`' % b for b in bare))
        A('')

    carts = [r for r in res['repos'] if r.get('cartridges')]
    for r in carts:
        c = r['cartridges']
        A('## Cartridge ceilings in `%s` (generation `%s`)' % (r['repo'], c['generation']))
        A('')
        A('Three ceilings are enforced in this estate and they are three different numbers:')
        A('**%d characters** is what the proof asserts, **%d bytes** is what `loop.mjs lint`'
          % (CARTRIDGE_CEILING_CHARS, LOOP_GATE_BYTES))
        A('gates, **%d bytes** is the composer boundary that is reported but not enforced.'
          % COMPOSER_BOUNDARY_BYTES)
        A('Characters are UTF-16 code units and bytes are bytes; the `b-c` column is how far')
        A('apart the two gauges are for that file.')
        A('')
        A('| cartridge | chars | bytes | b-c | clear of %d chars | clear of %d bytes | sha256 |'
          % (CARTRIDGE_CEILING_CHARS, LOOP_GATE_BYTES))
        A('|---|---:|---:|---:|---:|---:|---|')
        for x in c['rows']:
            if x['state'] == 'missing':
                A('| `%s` | - | - | - | - | - | MISSING |' % x['id'])
                continue
            A('| `%s` | %d | %d | %d | %d | %d | %s |'
              % (x['id'], x['chars'], x['bytes'], x['bytes_minus_chars'],
                 -x['chars_vs_proof_ceiling'], -x['bytes_vs_lint_gate'],
                 'matches' if x['sha256_matches'] else '**MISMATCH**'))
        A('')
    return '\n'.join(L) + '\n'


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--root', required=True, help='directory holding the fresh clones')
    ap.add_argument('--repos', nargs='*', default=None)
    ap.add_argument('--out', default='byte-survey.json')
    ap.add_argument('--board', default='')
    a = ap.parse_args()

    names = a.repos or sorted(d for d in os.listdir(a.root)
                              if os.path.isdir(os.path.join(a.root, d, '.git')))
    res = {'schema': 'ventus.clean-clone-byte-survey.v1',
           'generated_at': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
           'ceilings': {'proof_chars': CARTRIDGE_CEILING_CHARS,
                        'lint_gate_bytes': LOOP_GATE_BYTES,
                        'composer_boundary_bytes': COMPOSER_BOUNDARY_BYTES},
           'repos': [survey_repo(a.root, n) for n in names]}

    with open(a.out, 'w', encoding='utf-8', newline='\n') as f:
        json.dump(res, f, indent=1)
        f.write('\n')
    if a.board:
        os.makedirs(os.path.dirname(a.board) or '.', exist_ok=True)
        with open(a.board, 'w', encoding='utf-8', newline='\n') as f:
            f.write(board(res))

    surveyed = [r for r in res['repos'] if r['state'] == 'surveyed']
    print('repos %d · blob-CRLF files %d · checkout-CRLF files %d · renormalize would change %d '
          '· bare .gitattributes %d'
          % (len(surveyed),
             sum(r['eol'].get('i_crlf', 0) for r in surveyed),
             sum(r['eol'].get('w_crlf', 0) for r in surveyed),
             sum(r['renormalize'].get('changed', 0) for r in surveyed),
             sum(1 for r in surveyed if r['gitattributes']['state'] == 'bare')),
          file=sys.stderr)

    # Informational. Always 0. See the module docstring before changing this.
    return 0


if __name__ == '__main__':
    sys.exit(main())

Routefactor

A Python module in the scripts folder of Claude that reads GB transmission network and connection points.

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

What it does
It loads GB transmission network and connection points. Defines sh, gc, q. Uses libraries json, subprocess, math, statistics, collections. 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: JSON file gb-transmission-network.v1.json; JSON file connection-points.v3.json. Out: JSON file routefactor.json.
What it achieves
Measure the GB transmission route factor from published data. It writes `routefactor.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, subprocess, math, statistics, collections
Used by
none found
Produces
sh, gc, q
Defines here
sh, gc, q
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/routefactor.py:1-102 · blob 944c1a0811d26b710ba039ac90805b84b9b1cae5 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
"""Measure the GB transmission route factor from published data.

Every ETYS circuit publishes its real built length (ohl_km + cable_km) and
connects two named nodes whose sites have coordinates. So the ratio between
"straight line between the two sites" and "length actually built" can be
measured, not assumed. That ratio is what turns a crow-flies distance on a
project card into a defensible statement about a route.
"""
import json, subprocess, math, statistics, collections

def sh(*a):
    return subprocess.run(a, capture_output=True).stdout

net = json.loads(sh('git', '-C', 'data-grid-gb', 'show',
                    'gh/main:derived/gb-transmission-network.v1.json'))
cps = json.loads(sh('git', '-C', 'data-grid-gb', 'show',
                    'gh/main:derived/connection-points.v3.json'))['connection_points']

loc = {}
for p in cps:
    L = p.get('location')
    if L:
        lat = L.get('latitude', L.get('lat'))
        lon = L.get('longitude', L.get('lon', L.get('lng')))
        if lat is not None and lon is not None:
            loc[p['site_code']] = (float(lat), float(lon))

node_site = {n['node']: n['site_code'] for n in net['nodes']}
node_kv   = {n['node']: n.get('voltage_kv') for n in net['nodes']}

R = 6371.0088
def gc(a, b):
    (la1, lo1), (la2, lo2) = a, b
    p1, p2 = math.radians(la1), math.radians(la2)
    dp, dl = p2 - p1, math.radians(lo2 - lo1)
    h = math.sin(dp/2)**2 + math.cos(p1)*math.cos(p2)*math.sin(dl/2)**2
    return 2 * R * math.asin(min(1, math.sqrt(h)))

rows = []
skip = collections.Counter()
for c in net['circuits']:
    s1, s2 = node_site.get(c['node_1']), node_site.get(c['node_2'])
    if not s1 or not s2:
        skip['node has no site'] += 1; continue
    if s1 == s2:
        skip['both ends same site'] += 1; continue
    if s1 not in loc or s2 not in loc:
        skip['site has no coordinates'] += 1; continue
    built = (c.get('ohl_km') or 0) + (c.get('cable_km') or 0)
    if built <= 0:
        skip['no published length'] += 1; continue
    d = gc(loc[s1], loc[s2])
    if d < 1.0:
        skip['ends under 1 km apart'] += 1; continue
    kv = node_kv.get(c['node_1']) or node_kv.get(c['node_2'])
    rows.append({'ratio': built / d, 'straight': d, 'built': built, 'kv': kv,
                 'type': c.get('circuit_type'), 'cable': c.get('cable_km') or 0})

print('circuits published        : %6d' % len(net['circuits']))
print('usable for measurement    : %6d' % len(rows))
for k, v in skip.most_common():
    print('  skipped, %-24s %5d' % (k, v))

rs = sorted(r['ratio'] for r in rows)
def q(p): return rs[int(p * (len(rs) - 1))]
print()
print('ROUTE FACTOR  (built length / straight-line between site coordinates)')
print('  p10 %.2f   p25 %.2f   median %.2f   p75 %.2f   p90 %.2f' %
      (q(.10), q(.25), q(.50), q(.75), q(.90)))
print('  mean %.2f   n=%d' % (statistics.mean(rs), len(rs)))

print()
print('by voltage class:')
byk = collections.defaultdict(list)
for r in rows:
    if r['kv']:
        byk[r['kv']].append(r['ratio'])
for kv in sorted(byk, reverse=True):
    v = sorted(byk[kv])
    if len(v) >= 12:
        print('  %4s kV  n=%4d   median %.2f   p25 %.2f   p75 %.2f' %
              (kv, len(v), v[len(v)//2], v[len(v)//4], v[3*len(v)//4]))

print()
print('by circuit type:')
byt = collections.defaultdict(list)
for r in rows:
    byt[r['type'] or '?'].append(r['ratio'])
for t in sorted(byt, key=lambda k: -len(byt[k])):
    v = sorted(byt[t])
    if len(v) >= 10:
        print('  %-12s n=%4d   median %.2f' % (t, len(v), v[len(v)//2]))

sane = [r for r in rows if r['ratio'] < 5]
print()
print('sanity: %d circuits have built length > 5x straight line' % (len(rows) - len(sane)))
worst = sorted(rows, key=lambda r: -r['ratio'])[:5]
for w in worst:
    print('   ratio %6.1f  straight %6.2f km  built %7.2f km  %s' %
          (w['ratio'], w['straight'], w['built'], w['type']))
json.dump({'n': len(rs), 'median': q(.50), 'p25': q(.25), 'p75': q(.75),
           'p10': q(.10), 'p90': q(.90)}, open('routefactor.json', 'w'), indent=1)

Router

A Python module in the scripts folder of Claude that reads meta, using haversine.

ingestclaude / sessions/202609021835-estate-and-corridor/scripts/router.py · lines 1–170 of 170 · version 2026-09-02 18:35 · pattern Graph (shared by 3 files)

What it does
It loads meta. Defines 10 functions or classes, including _load, Graph, __init__, build_snap_index, snap. Uses libraries array, os, math, json, heapq. 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 .meta.json.
Downstream impact
Used directly by 5 files: Crossings (claude); Edge Rail (claude); Run Study (claude); Sanity (claude); and 1 more.
What it achieves
It builds snap index (`build_snap_index`) and is built from the graph class (`Graph`) and the snap step (`snap`). Graph loading, spatial snapping and A* routing over the OSM road graph.
Why it matters
Imported by 5 files, including Crossings, Edge Rail and Run Study.
Application
claude · sessions/202609021835-estate-and-corridor/scripts · Python module
Uses
Sessions — Estate and Corridor (import), array, os, math, json, heapq
Used by
imported by Crossings (import), imported by Edge Rail (import), imported by Run Study (import), imported by Sanity (import), imported by Sweep (import)
Produces
Graph
Defines here
_load, Graph, __init__, build_snap_index, snap, astar, edge_between, path_legs, edge_geometry, path_geometry
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/router.py:1-170 · blob 891c7cdd713598fd1d0140e3900f1bab01b232cb · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
"""Graph loading, spatial snapping and A* routing over the OSM road graph."""
import array, os, math, json
from heapq import heappush, heappop
from common import haversine, HERE

GRAPH = os.path.join(HERE, "graph")


def _load(pre, name, typecode):
    a = array.array(typecode)
    path = os.path.join(GRAPH, pre + "." + name + ".bin")
    n = os.path.getsize(path) // a.itemsize
    with open(path, "rb") as fh:
        a.fromfile(fh, n)
    return a


class Graph:
    def __init__(self, pre="roads"):
        self.pre = pre
        self.nlat = _load(pre, "nlat", "d")
        self.nlon = _load(pre, "nlon", "d")
        self.indptr = _load(pre, "indptr", "q")
        self.indices = _load(pre, "indices", "q")
        self.weights = _load(pre, "weights", "d")
        self.eids = _load(pre, "eids", "q")
        self.comp = _load(pre, "comp", "q")
        self.gptr = _load(pre, "gptr", "q")
        self.gxy = _load(pre, "gxy", "d")
        self.meta = json.load(open(os.path.join(GRAPH, pre + ".meta.json")))
        self.n = len(self.nlat)
        # dominant component id
        counts = {}
        for c in self.comp:
            counts[c] = counts.get(c, 0) + 1
        self.giant_id = max(counts, key=counts.get)
        self._grid = None

    # ---------- spatial snap index ----------
    def build_snap_index(self, cell=0.02, giant_only=True):
        g = {}
        lat = self.nlat; lon = self.nlon; comp = self.comp; gid = self.giant_id
        for i in range(self.n):
            if giant_only and comp[i] != gid:
                continue
            k = (int(lat[i] / cell), int(lon[i] / cell))
            b = g.get(k)
            if b is None:
                g[k] = [i]
            else:
                b.append(i)
        self._grid = g
        self._cell = cell
        return len(g)

    def snap(self, la, lo, max_rings=60):
        """Nearest indexed node. Returns (node_id, distance_km)."""
        cell = self._cell; g = self._grid
        ci = int(la / cell); cj = int(lo / cell)
        best = -1; bestd = float("inf")
        r = 0
        while r <= max_rings:
            found_any = False
            for i in range(ci - r, ci + r + 1):
                for j in range(cj - r, cj + r + 1):
                    # only the ring perimeter after r=0
                    if r > 0 and abs(i - ci) != r and abs(j - cj) != r:
                        continue
                    b = g.get((i, j))
                    if not b:
                        continue
                    found_any = True
                    for nd in b:
                        d = haversine(la, lo, self.nlat[nd], self.nlon[nd])
                        if d < bestd:
                            bestd = d; best = nd
            # once something is found, expand two more rings to be safe,
            # because cell distance is not the same as great-circle distance
            if best >= 0 and r >= 2 and bestd < (r - 1) * cell * 111.0:
                break
            r += 1
            if best < 0 and r > max_rings:
                break
        return best, bestd

    # ---------- routing ----------
    def astar(self, src, dst, extra_cost=None):
        """A* with admissible great-circle heuristic.

        extra_cost: optional dict/list mapping edge id -> additional km-equivalent
                    penalty. Penalties are >= 0 so the heuristic stays admissible.
        Returns (cost_km, node_path) or (None, None).
        """
        if src == dst:
            return 0.0, [src]
        nlat = self.nlat; nlon = self.nlon
        indptr = self.indptr; indices = self.indices
        weights = self.weights; eids = self.eids
        tlat = nlat[dst]; tlon = nlon[dst]

        g = {src: 0.0}
        parent = {src: -1}
        closed = set()
        h0 = haversine(nlat[src], nlon[src], tlat, tlon)
        pq = [(h0, 0.0, src)]
        pops = 0
        while pq:
            f, gu, u = heappop(pq)
            if u in closed:
                continue
            closed.add(u)
            pops += 1
            if u == dst:
                path = []
                while u != -1:
                    path.append(u); u = parent[u]
                path.reverse()
                return gu, path
            for p in range(indptr[u], indptr[u + 1]):
                v = indices[p]
                if v in closed:
                    continue
                w = weights[p]
                if extra_cost is not None:
                    w += extra_cost[eids[p]]
                ng = gu + w
                if ng < g.get(v, float("inf")):
                    g[v] = ng
                    parent[v] = u
                    heappush(pq, (ng + haversine(nlat[v], nlon[v], tlat, tlon), ng, v))
        return None, None

    # ---------- helpers ----------
    def edge_between(self, u, v):
        """Return (weight, eid) for the edge u-v, or None."""
        for p in range(self.indptr[u], self.indptr[u + 1]):
            if self.indices[p] == v:
                return self.weights[p], self.eids[p]
        return None

    def path_legs(self, path):
        """Per-leg (weight, eid). Used for the leg-sum sanity check."""
        out = []
        for a, b in zip(path, path[1:]):
            e = self.edge_between(a, b)
            if e is None:
                raise RuntimeError("path uses a non-existent edge %d-%d" % (a, b))
            out.append(e)
        return out

    def edge_geometry(self, eid):
        """Flat [lon,lat,...] for one edge."""
        a = self.gptr[eid]; b = self.gptr[eid + 1]
        return self.gxy[2 * a:2 * b]

    def path_geometry(self, path):
        """Flat [lon,lat,...] for the whole routed path, orientation-corrected."""
        out = array.array("d")
        for a, b in zip(path, path[1:]):
            e = self.edge_between(a, b)
            gm = self.edge_geometry(e[1])
            pts = [(gm[2 * i], gm[2 * i + 1]) for i in range(len(gm) // 2)]
            # orient so the polyline starts at node a
            d_start = haversine(self.nlat[a], self.nlon[a], pts[0][1], pts[0][0])
            d_end = haversine(self.nlat[a], self.nlon[a], pts[-1][1], pts[-1][0])
            if d_end < d_start:
                pts.reverse()
            for (lo, la) in pts:
                out.append(lo); out.append(la)
        return out

Context

A JavaScript module in the geodesy folder of Code Generator.

othercode-generator / apps/geodesy/context.mjs · lines 1–3 of 3 · Not reached from any entry point (candidate for review)

Why it exists in the grid workflow
Domain stage site_feasibility (topic 'maps-gis'): substation-to-site feasibility (terrain, LiDAR and connection evidence before design), a journey named in Ventus Ltd's brief.
Downstream impact
Used directly by 1 file: Geodesy (code-generator).
What it achieves
Values the parts of Geodesy helpers need from their surroundings.
Why it matters
Imported by Geodesy.
Application
code-generator · apps/geodesy · JavaScript module
Uses
none found
Used by
imported by Geodesy (import)
Produces
DEG, EARTH_RADIUS_KM
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
code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/geodesy/context.mjs:1-3 · blob 674fb4dd2baf253cbe963e058991ba7feacf8801 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: none found · domain stage: site_feasibility · users: IPP_developer, landowner_planner · canonical: unreached_review
// Values the parts of Geodesy helpers need from their surroundings. Decide each one; the generator does not guess.
export const DEG = undefined; // TODO decide
export const EARTH_RADIUS_KM = undefined; // TODO decide — see REPORT.md, open decision

Geodesy

A JavaScript module in Code Generator that works with distance km (`distanceKm`) and initial bearing deg (`initialBearingDeg`) and calculates great-circle distances.

geodesycode-generator / apps/geodesy/geodesy.mjs · lines 1–25 of 25 · Not reached from any entry point (candidate for review) · pattern initialBearingDeg (shared by 24 files)

What it does
It calculates its inputs. Defines distanceKm, initialBearingDeg.
Why it exists in the grid workflow
Domain stage site_feasibility (topic 'maps-gis'): substation-to-site feasibility (terrain, LiDAR and connection evidence before design), a journey named in Ventus Ltd's brief.
What it achieves
It is built from the distance km helper (`distanceKm`) and the initial bearing deg helper (`initialBearingDeg`). Geodesy helpers — generated .649Z by Ventusltd/code-generator from the modular star.
Why it matters
No other file in the estate was found to import it.
Application
code-generator · apps/geodesy · JavaScript module
VEDIC
MEASURE (GG2050-VEDIC-000001): GridAtlas / Geodesy · Mathematics / Spherical geometry. coordinate_pair, coordinate_pair → distance_km
VEDIC
BEARING (GG2050-VEDIC-000005): GridAtlas / Geodesy · Mathematics / Trigonometry. coordinate_pair, coordinate_pair → bearing_deg
Uses
Context (import)
Used by
none found
Produces
distanceKm, initialBearingDeg
Defines here
distanceKm, initialBearingDeg
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/geodesy/geodesy.mjs:1-25 · blob 10bc31fc3d1c84c89b985d970527961e67e4838f · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: site_feasibility · users: IPP_developer, landowner_planner · canonical: unreached_review
// Geodesy helpers — generated 2026-09-14T08:57:44.649Z by Ventusltd/code-generator from the modular star.
// Each part is copied exactly from GitHub at the recorded commit. Family numbers are permanent keys.
// Parts: #511 distanceKm, #8770 initialBearingDeg

// Still needed from the surroundings (supply in context.mjs): DEG, EARTH_RADIUS_KM
import { DEG, EARTH_RADIUS_KM } from './context.mjs';

// ── family #511 distanceKm · function · used in 40 place(s) across 5 repositories · https://github.com/Ventusltd/claude/blob/df9da02425fdf0c65d11a84f32cd9b3ef927b309/sessions/202609031559-skin-architecture/prototype/engine.js#L35-L41
export   function distanceKm(lon1, lat1, lon2, lat2) {
    const dLat = (lat2 - lat1) * DEG;
    const dLon = (lon2 - lon1) * DEG;
    const a = Math.sin(dLat / 2) ** 2
      + Math.cos(lat1 * DEG) * Math.cos(lat2 * DEG) * Math.sin(dLon / 2) ** 2;
    return EARTH_RADIUS_KM * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  }

// ── family #8770 initialBearingDeg · function · used in 40 place(s) across 5 repositories · https://github.com/Ventusltd/globalgrid2050/blob/a387cac3aa3f09b8cdd27d3ed8040d661303f127/testcode/202609051152/atlas/cartridges/202609051152-substation-intelligence.js#L1627-L1633
export   function initialBearingDeg(lon1, lat1, lon2, lat2) {
    const p1 = lat1 * DEG; const p2 = lat2 * DEG;
    const dl = (lon2 - lon1) * DEG;
    const y = Math.sin(dl) * Math.cos(p2);
    const x = Math.cos(p1) * Math.sin(p2) - Math.sin(p1) * Math.cos(p2) * Math.cos(dl);
    return (Math.atan2(y, x) / DEG + 360) % 360;
  }

Position Overlay

A JavaScript module in the line folder of Compass.

transformcompass / upstream/tools/satnav/line/position-overlay.mjs · lines 1–32 of 32 · pattern point (shared by 35 files)

What it does
It calculates its inputs. Defines point, createPositionOverlay.
Why it exists in the grid workflow
Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Downstream impact
Used directly by 1 file: Compass (compass). Reached from 2 other entry points, including Verify Workflow (compass); Compass Test (compass).
What it achieves
Defines `point` and `createPositionOverlay`.
Why it matters
Imported by Compass.
Application
compass · upstream/tools/satnav/line · JavaScript module
Uses
Route Follower (import)
Used by
imported by Compass (import), mentioned in Standalone (comment link)
Produces
point, createPositionOverlay
Defines here
point, createPositionOverlay
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
compass@e200c888acbcc7af59d7cc38b29806e90b0a50db upstream/tools/satnav/line/position-overlay.mjs:1-32 · blob ae24435866faf19baa071508d503ea3c0ab7d75d · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unknown
import { createRouteFollower } from './route-follower.mjs';

export const point = (role, coordinates) => ({
  type: 'Feature',
  properties: { role },
  geometry: { type: 'Point', coordinates },
});

export function createPositionOverlay(coordinates, maths) {
  const line = { type: 'LineString', coordinates: coordinates.map(at => at.slice()) };
  const locate = createRouteFollower(line, maths);
  return (fix, nowMs) => {
    const metrics = locate(fix, nowMs);
    const features = [
      { type: 'Feature', properties: { role: 'selected-section' }, geometry: line },
    ];
    if (metrics.status === 'ok' || metrics.status === 'uncertain') {
      const measured = [fix.longitude, fix.latitude];
      features.push(point('measured-gps', measured));
      if (fix.accuracyM > 0) {
        const ring = maths.geodesicCircle(...measured, fix.accuracyM / 1000, 64);
        features.push({
          type: 'Feature',
          properties: { role: 'gps-accuracy' },
          geometry: { type: 'Polygon', coordinates: [ring] },
        });
      }
      if (metrics.status === 'ok') features.push(point('nearest-on-section', metrics.nearest));
    }
    return { metrics, features };
  };
}

Route Follower

A JavaScript module in the line folder of Compass. It is built from the valid step (`valid`).

transformcompass / upstream/tools/satnav/line/route-follower.mjs · lines 1–21 of 21 · pattern valid (shared by 20 files)

What it does
It calculates its inputs. Defines createRouteFollower, valid.
Why it exists in the grid workflow
Domain stage field_execution (path word 'route'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Downstream impact
Used directly by 12 files: Position Overlay (compass); Ordered Convergence 2km (gridatlas); Ordered Convergence Unlimited (gridatlas); Ordered (gridatlas); and 8 more. Reached from 8 other entry points, including Verify Workflow (compass); GridAtlas PR File Size Guard Workflow (gridatlas); Compass Test (compass).
What it achieves
Tracking only, not routing or authorisation.
Why it matters
Imported by 12 files, including Position Overlay, Ordered Convergence 2km and Ordered Convergence Unlimited, from GridAtlas.
Application
compass · upstream/tools/satnav/line · JavaScript module
Uses
none found
Used by
imported by Position Overlay (import), imported by Ordered Convergence 2km (import), imported by Ordered Convergence Unlimited (import), imported by Ordered (import), imported by Orient17a Continuity Ordered (import), imported by Orient17a Ordered (import), imported by Orient17a V9212 Ordered (import), imported by Orient15 Recovery (import), and 4 more, mentioned in Standalone (comment link)
Produces
createRouteFollower
Defines here
createRouteFollower, valid
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
compass@e200c888acbcc7af59d7cc38b29806e90b0a50db upstream/tools/satnav/line/route-follower.mjs:1-21 · blob a0cdb4a6fb808b4b43f87d8bc3a9ac5d20daff8a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unknown
// SPDX-License-Identifier: Apache-2.0
// Tracking only, not routing or authorisation. Inject the pinned canonical maths.
export function createRouteFollower(geometry,maths){
  const valid=p=>Array.isArray(p)&&p.length===2&&p.every(Number.isFinite)&&Math.abs(p[0])<=180&&Math.abs(p[1])<=90;
  if(geometry?.type!=="LineString"||!Array.isArray(geometry.coordinates)||geometry.coordinates.length<2||geometry.coordinates.length>20000||!geometry.coordinates.every(valid))throw Error("INVALID_LINE");
  const {distanceKm,distanceToSegmentKm,initialBearingDeg}=maths;
  const coords=geometry.coordinates.map(p=>p.slice()),segments=[];let total=0;
  for(let i=0;i<coords.length-1;i++){const a=coords[i],b=coords[i+1],length=distanceKm(...a,...b)*1000;if(!Number.isFinite(length)||length>1000)throw Error("SEGMENT_REQUIRES_DENSIFICATION");if(length>0){segments.push({a,b,length,start:total,index:i});total+=length;}}
  if(!segments.length)throw Error("EMPTY_ROUTE");
  return function locate(fix,nowMs){
    if(!valid([fix?.longitude,fix?.latitude])||!Number.isFinite(fix?.accuracyM)||fix.accuracyM<0||!Number.isFinite(fix?.timestampMs)||!Number.isFinite(nowMs))return {status:"invalid"};
    const age=nowMs-fix.timestampMs;if(age<0||age>10000)return {status:"stale"};
    if(fix.accuracyM>30)return {status:"uncertain",reason:"GPS_ACCURACY"};
    const hits=segments.map(s=>{const h=distanceToSegmentKm(fix.longitude,fix.latitude,...s.a,...s.b);return {s,h,distance:h.km*1000,progress:s.start+h.t*s.length};}).sort((a,b)=>a.distance-b.distance||a.s.index-b.s.index);
    const best=hits[0];
    if(hits.some(h=>h.distance<=best.distance+Math.max(5,fix.accuracyM)&&Math.abs(h.progress-best.progress)>Math.max(30,2*fix.accuracyM)))return {status:"uncertain",reason:"AMBIGUOUS_ROUTE_POSITION"};
    let signedCrossTrackM=null;
    if(best.h.t>0&&best.h.t<1){const direction=initialBearingDeg(...best.s.a,...best.s.b),offset=initialBearingDeg(...best.h.foot,fix.longitude,fix.latitude);signedCrossTrackM=best.distance<1e-6?0:Math.sign(Math.sin((offset-direction)*Math.PI/180))*best.distance;}
    return {status:"ok",segmentIndex:best.s.index,nearest:best.h.foot,offsetM:best.distance,signedCrossTrackM,progressM:best.progress,remainingM:Math.max(0,total-best.progress),totalM:total,offRoute:best.distance-fix.accuracyM>25,accuracyM:fix.accuracyM,fixAgeMs:age,trackingOnly:true};
  };
}