GLOBALGRID2050 / EXPLORE CODE

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

Log Tpl and 3 more files

A map page in the artifacts folder of Claude. It is built from the esc step (`esc`), the pad step (`pad`) and the rpad step (`rpad`).

623 lines of Python and HTML from claude, in 4 files. Topic: AI agents and coordination. Section 1610 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. Corridor render · claude / sessions/202609021835-estate-and-corridor/artifacts/corridor.html lines 535–595
  2. Log Tpl render · claude / sessions/202609021835-estate-and-corridor/artifacts/log.tpl.html lines 1–242
  3. Analyze storage · claude / sessions/202609021835-estate-and-corridor/scripts/analyze.py lines 1–107
  4. Build Graph storage · claude / sessions/202609021835-estate-and-corridor/scripts/build_graph.py lines 1–213

Corridor

A web page in the artifacts folder of Claude covering cables, substations, 400kV and motorways, using SHA-256 and Douglas-Peucker.

renderclaude / sessions/202609021835-estate-and-corridor/artifacts/corridor.html · lines 535–595 of 595 · version 2026-09-02 18:35 (continued from section 1609) · Entry point

What it does
It draws cables, substations, 400kV and motorways. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'claude'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). Domain terms in the code: cables, substations, 400kV, motorways, 33kV.
Inputs & outputs
Out: web page. Voltage levels named: 400kV, 33kV.
Downstream impact
It is itself an entry point (page); no other file was found loading it.
What it achieves
Grid Corridor Engine. Its code works with 400 kV and 33 kV.
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/artifacts · page
Uses
https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500;600&family=IBM+Plex+Sans:wght@400;500;600&display=swap
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/artifacts/corridor.html:535-595 · blob 34c11e42414f0f49c2ee941a55f18678e4827065 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: agent_infra · users: ai_agent · canonical: unknown
</section>

<section>
  <h2><span class="n">10</span> The corridor tracer &mdash; a second feature, not a replacement</h2>
  <p>The straight line stays exactly as it is. The tracer is additive, behind a deliberate action, and drawn
    only when asked for.</p>

  <h3>The gesture</h3>
  <p>The v8 engine binds <code>click</code>, <code>dblclick</code>, <code>mousemove</code>, <code>mousedown</code>,
    <code>mouseup</code> and <code>keydown</code>. It binds <strong>no <code>contextmenu</code> and no long-press</strong>
    &mdash; both slots are free, on desktop and on touch.</p>
  <div class="scroll"><table>
    <thead><tr><th>surface</th><th>gesture</th><th>why it is safe</th></tr></thead>
    <tbody>
      <tr><td class="k">desktop</td><td>right-click on the map or on a substation</td>
        <td class="d">Nothing binds <code>contextmenu</code> today, so no existing behaviour is displaced.</td></tr>
      <tr><td class="k">touch</td><td>long-press, about 500 ms, with a movement threshold so a pan never fires it</td>
        <td class="d">No <code>touchstart</code> handler exists; pan and pinch stay untouched.</td></tr>
      <tr><td class="k">both</td><td>a <span class="cy">&#10230; TRACE</span> tile beside Zone Draw and the radius tool</td>
        <td class="d">Follows the collapsible-panel pattern already in the engine, so it is discoverable without a gesture.</td></tr>
    </tbody>
  </table></div>

  <h3>What it draws</h3>
  <p>A stream of neon corridors from the chosen point to the nearest connection points, <strong>coloured by the
    voltage class of the target</strong>, reusing the palette already carrying the 400 / 275 / 132 / 66 / 33 kV layers.
    Anyone who knows the map knows instantly that a blue corridor lands at 400 kV.</p>
  <ul>
    <li>Animated dash offset flowing toward the substation &mdash; direction carried by motion, not an arrowhead</li>
    <li>Each corridor labelled: routed km, straight km, factor, crossings by class</li>
    <li>Corridors failing the swathe-width test drawn dashed and dimmed, with the reason on hover</li>
    <li>Snap distance drawn as a distinct stub at each end, never silently absorbed into the route</li>
    <li>Click a corridor to open the substation card that already exists</li>
    <li><code>prefers-reduced-motion</code> stops the flow and leaves the corridors static</li>
  </ul>

  <h3>Exploration mode &mdash; where this gets interesting</h3>
  <p>The card already names the sites a circuit reaches: <em>CULHAM JET, DIDCOT, EAST CLAYDON, LEIGHTON
    BUZZARD, MINETY, WALHAM</em>. Trace from a substation rather than from a project and those become traceable
    onward &mdash; a second press walks the published network one hop further, each circuit drawn in its own
    voltage colour. The result is a user pulling the grid graph outward by hand, which is the thing no other
    public tool lets anyone do.</p>

  <div class="measured">
    <div class="lbl">The line this feature must not cross</div>
    <p>A drawn corridor will be read as a route someone could build. It is a <strong>corridor length along public
      road geometry</strong> &mdash; not a wayleave, not a consent, not a design, not a cost. The label has to carry
      that as firmly as the panel already carries <em>a rating is not what is free on the circuit</em>. Drawing it
      beautifully raises that risk rather than lowering it.</p>
  </div>
</section>

<footer>
  <p><strong>Provenance.</strong> Route factors from 815 ETYS circuits with coordinates at both ends, built length
    from <code>ohl_km + cable_km</code>. Coverage and collision counts from <code>connection-points.v3.json</code> and
    <code>gb-transmission-network.v1.json</code>. Graph sizes counted from the committed GeoJSON. NESO sources
    re-downloaded and confirmed against their pinned SHA-256 on 2026-09-03.</p>
  <p><strong>Not measured here.</strong> Consenting durations, wayleave costs, land ownership, and anything about
    whether a project can connect &mdash; none of which any published appendix contains.</p>
</footer>
</div>

Log Tpl

A map page in the artifacts folder of Claude. It is built from the esc step (`esc`), the pad step (`pad`) and the rpad step (`rpad`).

Set aside from the main view: 94% of its lines are the same as estate_scan/202609021952/index.html (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 93% of lines shared with GlobalGrid2050 — Estate Scan Page; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9352 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 estate_scan/202609021952/index.html:1-255 dd333982daeafe37ba619cbd4e798124714c0430
  • sha256 b51ffd87692e5a94f9227fe8be3b001559330ee4c0579067181e7403bae59ad2
  • target sha256 c98604637f1b3e9649b3e868acbf2da062978eab59ae66d5e069471fbbf99f2c
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

renderclaude / sessions/202609021835-estate-and-corridor/artifacts/log.tpl.html · lines 1–242 of 242 · version 2026-09-02 18:35 · Entry point

What it does
It maps its content. Defines 15 functions or classes, including esc, pad, rpad, num, bars. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'claude'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
Out: web page; interactive map.
Downstream impact
It is itself an entry point (page); no other file was found loading it.
What it achieves
Ventus Estate Log. It responds to keydown and click events.
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/artifacts · page
Uses
https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&display=swap
Used by
none found
Produces
esc, pad, rpad, num, bars, secs, ageD, line, kv, T, CT, LT
Defines here
esc, pad, rpad, num, bars, secs, ageD, line, kv, T, CT, LT, ORD, all, step
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/artifacts/log.tpl.html:1-242 · blob 4bcb2c5d3c2b93a829fda6bb86d489896e6690c1 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: agent_infra · users: ai_agent · canonical: unknown
<title>Ventus Estate Log</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&display=swap">
<style>
:root{
  color-scheme: dark;
  --bg:#04060a;
  --ink:#7d8f9c;
  --hi:#d7e3ec;
  --key:#4a5a66;
  --cy:#35c9d9;
  --ok:#3fbf5f;
  --bad:#e2564d;
  --am:#e8a33d;
}
*{box-sizing:border-box}
html,body{background:var(--bg)}
body{
  margin:0;
  color:var(--ink);
  font-family:"IBM Plex Mono", ui-monospace, "Cascadia Mono", Consolas, monospace;
  font-size:12.5px;
  line-height:1.5;
  font-variant-ligatures:none;
  -webkit-font-smoothing:antialiased;
}
#scan{
  padding:26px 20px 64px;
  max-width:1180px;
  margin:0 auto;
  white-space:pre;
  overflow-x:auto;
  tab-size:2;
}
.k{color:var(--key)}
.v{color:var(--hi)}
.c{color:var(--cy)}
.o{color:var(--ok)}
.b{color:var(--bad)}
.a{color:var(--am)}
.r{color:#2b3742}
.hdr{color:var(--hi)}
#cur{
  display:inline-block;width:7px;height:13px;background:var(--cy);
  vertical-align:-2px;animation:bl 1.05s steps(2,start) infinite
}
@keyframes bl{50%{opacity:0}}
@media (prefers-reduced-motion: reduce){#cur{animation:none}}
</style>

<div id="scan"></div>

<script>
const D = /*__DATA__*/;

/* ---------- formatting ---------- */
const esc = s => String(s).replace(/[&<>]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;'}[c]));
const pad  = (s,n) => { s = String(s); return s.length >= n ? s : s + ' '.repeat(n - s.length); };
const rpad = (s,n) => { s = String(s); return s.length >= n ? s : ' '.repeat(n - s.length) + s; };
const num  = n => (n === undefined || n === null) ? '-' : Number(n).toLocaleString('en-GB');
const BL   = ['·','▁','▂','▃','▅','▆','▇','█'];
const bars = arr => { const m = Math.max(1, ...arr);
  return arr.map(n => n ? BL[Math.min(7, 1 + Math.floor((n/m)*6))] : BL[0]).join(''); };
const secs = s => s >= 3600 ? (s/3600).toFixed(1)+'h' : s >= 60 ? (s/60).toFixed(1)+'m' : s+'s';
const ageD = iso => ((Date.now() - new Date(iso)) / 864e5).toFixed(1);

const L = [];                                     // {h: html, pause?: n}
const line = (h='', pause=0) => L.push({h, pause});
const kv = (k, v, cls='v') =>
  line('  <span class="k">' + pad(k,15) + '</span><span class="' + cls + '">' + v + '</span>');
const RULE = '─'.repeat(96);

/* ---------- header ---------- */
line('<span class="r">' + RULE + '</span>');
kv('scan', D.generated_utc.replace('T',' ').replace('Z','') + ' UTC', 'c');
kv('workers', D.workers);
kv('targets', D.repos.length + ' repositories');
kv('elapsed', D.elapsed_s + ' s');
line('', 260);

/* ---------- per repository ---------- */
let n = 0;
for (const r of D.repos) {
  n++;
  const idx = String(n).padStart(2,'0') + '/' + D.repos.length;
  line('');
  line('<span class="r">' + RULE + '</span>');
  line('<span class="c">' + idx + '</span>', 150);
  line('<span class="r">' + RULE + '</span>');

  if (r.error) { kv('error', esc(r.error), 'b'); continue; }

  kv('ref', r.ref);
  kv('head', r.head_iso.replace('T',' ').slice(0,19));
  kv('first', r.first_iso.replace('T',' ').slice(0,19) + '   span ' + r.span_days + ' d');
  kv('commits', num(r.commits) + '   merges ' + num(r.merges) + '   per day ' + r.per_day);
  kv('recent', '24h ' + num(r.c1) + '   7d ' + num(r.c7) + '   30d ' + num(r.c30));
  kv('lines', '+' + num(r.add_total) + '  −' + num(r.del_total));
  kv('touched', num(r.files_touched) + ' file changes   median ' + r.files_median + '   max ' + r.files_max);
  kv('interval', 'median ' + r.gap_med_h + ' h   longest ' + r.gap_max_h + ' h');
  kv('authors', num(r.authors_total));
  r.authors.slice(0,5).forEach((a,ai) =>
    line('    <span class="k">' + pad('author ' + String(ai+1).padStart(2,'0'), 36) + '</span>' + rpad(num(a.c), 6)));
  kv('tree', num(r.tracked_files) + ' files   ' + r.tracked_human +
             '   depth avg ' + r.depth_avg + ' max ' + r.depth_max);
  kv('types', r.exts.slice(0,6).map(e => e.e + ' ' + e.n).join('   '), 'k');
  r.biggest.slice(0,3).forEach((b,bi) =>
    line('    <span class="k">' + pad('object ' + String(bi+1).padStart(2,'0'), 60) + '</span>' + rpad(b.b, 9)));
  if (r.loc) {
    kv('text', num(r.loc.text_files) + ' files   ' + num(r.loc.lines_total) + ' lines');
    kv('code', num(r.loc.files_codeish) + ' files   ' + num(r.loc.lines_codeish) + ' lines   ' +
               (100 * r.loc.lines_codeish / Math.max(1, r.loc.lines_total)).toFixed(1) + '% of text');
    kv('languages', r.loc.by_lang.slice(0,6).map(x => x.l + ' ' + num(x.n)).join('   '), 'k');
  }
  kv('branches', num(r.branches) + '   worktrees ' + num(r.worktrees) +
                 '   workflow files ' + num(r.workflow_files));
  (r.branch_rows||[]).slice(0,5).forEach((b,bi) =>
    line('    <span class="k">' + pad('branch ' + String(bi+1).padStart(2,'0'), 48) + '</span>' + pad(b.d, 13) +
         '<span class="' + (Number(b.ahead) ? 'a' : 'k') + '">+' + b.ahead + '</span>'));

  const h = r.http || {};
  const hc = h.status === 200 ? 'o' : (h.status ? 'b' : 'k');
  kv('http', '<span class="' + hc + '">' + (h.status || 'ERR') + '</span>  ' +
             num(h.bytes || 0) + ' B   ' + (h.ms || 0) + ' ms   ' + esc(h.last_modified || '-'), 'k');

  const c = r.ci || {};
  if (c.sampled) {
    kv('runs', num(c.sampled) + ' sampled of ' + num(c.total_count) +
               '   <span class="o">ok ' + c.success + '</span>   <span class="' +
               (c.failure ? 'b' : 'k') + '">fail ' + c.failure + '</span>   cancel ' + c.cancelled);
    kv('duration', 'median ' + secs(c.dur_med) + '   max ' + secs(c.dur_max) + '   total ' + secs(c.dur_sum));
    kv('events', c.events.map(e => e.e + ' ' + e.n).join('   '), 'k');
    kv('window', c.window[0].replace('T',' ').slice(0,16) + '  →  ' + c.window[1].replace('T',' ').slice(0,16), 'k');
    if (c.deploy_consec_fail)
      kv('deploy', '<span class="b">JAMMED  ' + c.deploy_consec_fail + ' consecutive</span>   last ok ' +
                   (c.deploy_last_ok || '-').replace('T',' ').slice(0,16), 'k');
    c.workflows.slice(0, 10).forEach((w, wi) => {
      const st = w.lc === 'success' ? '<span class="o">OK  </span>'
               : w.lc === 'failure' ? '<span class="b">FAIL</span>'
               : '<span class="a">' + pad(String(w.lc || '?').slice(0,4),4) + '</span>';
      line('    ' + st + ' <span class="k">' + pad('workflow ' + String(wi+1).padStart(2,'0'), 56) + '</span>' +
           rpad(w.t,4) + ' run' + rpad(w.f,5) + ' fail' + rpad(secs(w.med),7) +
           '  <span class="k">' + w.last.replace('T',' ').slice(0,16) + '</span>');
    })
  } else {
    kv('runs', 'none sampled', 'k');
  }
  kv('hours', bars(r.hours) + '   00→23 UTC', 'c');
  kv('weekday', bars(r.dow) + '   Mon→Sun', 'c');
  kv('30 days', bars(r.days30.map(x => x.n)), 'c');
  line('', 120);
}

/* ---------- estate totals ---------- */
const T = k => D.repos.reduce((a,r) => a + (Number(r[k]) || 0), 0);
const CT = k => D.repos.reduce((a,r) => a + (Number(r.ci && r.ci[k]) || 0), 0);
line('');
line('<span class="r">' + RULE + '</span>');
line('<span class="hdr">E S T A T E   T O T A L S</span>', 260);
line('<span class="r">' + RULE + '</span>');
kv('commits', num(T('commits')) + '   merges ' + num(T('merges')));
kv('lines', '+' + num(T('add_total')) + '  −' + num(T('del_total')));
kv('file changes', num(T('files_touched')));
kv('tracked', num(T('tracked_files')) + ' files   ' +
              (T('tracked_bytes')/1073741824).toFixed(2) + ' GB');
kv('branches', num(T('branches')) + '   worktrees ' + num(T('worktrees')));
kv('workflows', num(T('workflow_files')) + ' files   ' + num(CT('total_count')) + ' lifetime runs');
kv('sampled', num(CT('sampled')) + ' runs   <span class="o">ok ' + CT('success') +
              '</span>   <span class="b">fail ' + CT('failure') + '</span>');
kv('runner time', secs(CT('dur_sum')));
const LT = k => D.repos.reduce((a,r) => a + (Number(r.loc && r.loc[k]) || 0), 0);
kv('text', num(LT('text_files')) + ' files   ' + num(LT('lines_total')) + ' lines');
kv('code', num(LT('files_codeish')) + ' files   ' + num(LT('lines_codeish')) + ' lines   ' +
           (100 * LT('lines_codeish') / Math.max(1, LT('lines_total'))).toFixed(1) + '% of text');
const AG = {}, AF = {};
for (const r of D.repos) for (const x of (r.loc?.by_lang || [])) {
  AG[x.l] = (AG[x.l] || 0) + x.n; AF[x.l] = (AF[x.l] || 0) + x.f;
}
line('');
for (const [l, n] of Object.entries(AG).sort((a,b) => b[1]-a[1]).slice(0,14))
  line('  <span class="k">' + pad(l, 15) + '</span>' + rpad(num(n), 13) + ' lines' +
       rpad(num(AF[l]), 9) + ' files');
const red = D.repos.flatMap(r => (r.ci?.workflows||[]).filter(w => w.lc === 'failure'));
kv('red now', '<span class="b">' + red.length + ' workflows failing</span>', 'k');
const ORD = r => String(D.repos.indexOf(r) + 1).padStart(2,'0');
const jam = D.repos.filter(r => r.ci?.deploy_consec_fail);
kv('jammed', jam.length ? '<span class="b">' + jam.map(r => ORD(r) + ' (' + r.ci.deploy_consec_fail + ')').join('   ') + '</span>' : 'none', 'k');
const p404 = D.repos.filter(r => r.http && r.http.status !== 200);
kv('http !200', p404.length ? '<span class="a">' + p404.map(r => ORD(r) + ' (' + r.http.status + ')').join('   ') + '</span>' : 'none', 'k');
line('', 200);

/* ---------- index ---------- */
line('');
line('<span class="r">' + RULE + '</span>');
line('<span class="hdr">I N D E X</span>');
line('<span class="r">' + RULE + '</span>');
const CW = [['id',6],['cmt',9],['30d',7],['files',9],['size',11],['code',10],['wf',6],['br',6],['ok',6],['fail',7],['runs',9],['http',6]];

line('  <span class="k">' + CW.map(([h,w]) => pad(h,w)).join('') + '</span>');
let IDX = '# estate-index v3  ' + D.generated_utc + '\n';
IDX += '# ' + CW.map(([h,w]) => pad(h,w)).join('') + '\n';
for (const r of D.repos) {
  const c = r.ci || {}, h = r.http || {};
  const cells = [pad(String(D.repos.indexOf(r)+1).padStart(2,'0'),6), pad(num(r.commits),9),
                 pad(num(r.c30),7), pad(num(r.tracked_files),9), pad(r.tracked_human||'-',11),
                 pad(num(r.loc?.lines_codeish),10),
                 pad(num(r.workflow_files),6), pad(num(r.branches),6), pad(num(c.success),6),
                 pad(num(c.failure),7), pad(num(c.total_count),9), pad(h.status||'-',6)];
  line('  ' + cells.join(''));
  IDX += '  ' + cells.join('') + '\n';
}
line('');
line('<span class="k">  EOF  ' + D.generated_utc + '</span>');
line('<span id="cur"></span>');

/* ---------- vertical reveal ---------- */
const box = document.getElementById('scan');
const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
let i = 0, done = false;

function all(){
  if (done) return; done = true;
  box.innerHTML = L.map(x => x.h).join('\n');
}
function step(){
  if (done) return;
  const t0 = performance.now();
  let held = 0, chunk = '';
  while (i < L.length && performance.now() - t0 < 7) {
    chunk += (i ? '\n' : '') + L[i].h;
    held = L[i].pause; i++;
    if (held) break;
  }
  box.insertAdjacentHTML('beforeend', chunk);
  if (i >= L.length) { done = true; return; }
  held ? setTimeout(step, held) : requestAnimationFrame(step);
}
if (reduced) all(); else requestAnimationFrame(step);
addEventListener('keydown', all);
addEventListener('click', all);
</script>

Analyze

A Python command-line tool in the scripts folder of Claude that reads routes and metrics.

storageclaude / sessions/202609021835-estate-and-corridor/scripts/analyze.py · lines 1–107 of 107 · version 2026-09-02 18:35 · Entry point · pattern summarize (shared by 5 files)

What it does
It loads routes and metrics. Defines pct, med, summarize, main. Uses libraries json, os, sys, collections. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'claude'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file out_routes.json; command-line arguments. Out: JSON file out_metrics.json.
Downstream impact
Used directly by 3 files: Calib (claude); Crossings (claude); Sweep (claude).
What it achieves
It is built from the pct step (`pct`), the med step (`med`) and the summarize step (`summarize`). Measure straight vs routed against published `cable_km`.
Why it matters
Imported by Calib, Crossings and Sweep.
Application
claude · sessions/202609021835-estate-and-corridor/scripts · Python CLI
Uses
Sessions — Estate and Corridor (import), json, os, sys, collections
Used by
imported by Calib (import), imported by Crossings (import), imported by Sweep (import)
Produces
pct, med, summarize, main
Defines here
pct, med, summarize, 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/analyze.py:1-107 · blob 8ca043bf540d356a877f2aa23a5b797e25085494 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
"""Measure straight vs routed against published cable_km."""
import json, os, sys
from common import HERE

def pct(xs, q):
    if not xs: return float("nan")
    s = sorted(xs); i = (len(s) - 1) * q
    lo = int(i); hi = min(lo + 1, len(s) - 1); f = i - lo
    return s[lo] * (1 - f) + s[hi] * f

def med(xs): return pct(xs, 0.5)

def summarize(rows, label, candidate_key="routed_total_km", truth_key="cable_km"):
    ok = [r for r in rows if r["status"] == "ok" and r.get(candidate_key) is not None]
    out = {"label": label, "n_total": len(rows), "n_scored": len(ok)}
    ape_s, ape_r, ratio_rs, ratio_rp, ratio_sp = [], [], [], [], []
    wins = 0
    for r in ok:
        pub = r[truth_key]; s = r["straight_km"]; c = r[candidate_key]
        es = abs(s - pub) / pub * 100.0
        er = abs(c - pub) / pub * 100.0
        r["ape_straight"] = es; r["ape_routed"] = er
        r["ratio_routed_straight"] = c / s
        r["ratio_routed_pub"] = c / pub
        r["ratio_straight_pub"] = s / pub
        ape_s.append(es); ape_r.append(er)
        ratio_rs.append(c / s); ratio_rp.append(c / pub); ratio_sp.append(s / pub)
        if er < es: wins += 1
    out["median_ape_straight"] = med(ape_s)
    out["median_ape_routed"] = med(ape_r)
    out["mean_ape_straight"] = sum(ape_s) / len(ape_s) if ape_s else None
    out["mean_ape_routed"] = sum(ape_r) / len(ape_r) if ape_r else None
    out["p25_ape_routed"] = pct(ape_r, .25); out["p75_ape_routed"] = pct(ape_r, .75)
    out["p25_ape_straight"] = pct(ape_s, .25); out["p75_ape_straight"] = pct(ape_s, .75)
    out["routed_beats_straight_n"] = wins
    out["routed_beats_straight_frac"] = wins / len(ok) if ok else 0.0
    out["median_ratio_routed_straight"] = med(ratio_rs)
    out["median_ratio_routed_published"] = med(ratio_rp)
    out["median_ratio_straight_published"] = med(ratio_sp)
    # gate, evaluated over ALL circuits in the validation set (failures count against)
    out["gate_median_ape_lt_15"] = out["median_ape_routed"] < 15.0
    out["gate_beat_frac_ge_80_scored"] = out["routed_beats_straight_frac"] >= 0.80
    out["beat_frac_of_all_95"] = wins / len(rows)
    out["gate_beat_frac_ge_80_all"] = (wins / len(rows)) >= 0.80
    out["gate_passes_scored_only"] = bool(out["gate_median_ape_lt_15"] and out["gate_beat_frac_ge_80_scored"])
    out["gate_passes_all_circuits"] = bool(out["gate_median_ape_lt_15"] and out["gate_beat_frac_ge_80_all"])
    return out, ok

def main(path="out_routes.json"):
    rows = json.load(open(os.path.join(HERE, path)))
    res = {}
    for key in ("routed_total_km", "routed_core_km"):
        s, ok = summarize(rows, key, candidate_key=key)
        res[key] = s

    # ---- invariant checks ----
    viol_site, viol_snap = [], []
    for r in rows:
        if r["status"] != "ok": continue
        if r["routed_total_km"] < r["straight_km"] - 1e-9:
            viol_site.append((r["site_1"], r["site_2"], r["routed_total_km"], r["straight_km"]))
        if r["routed_core_km"] < r["straight_snapped_km"] - 1e-9:
            viol_snap.append((r["site_1"], r["site_2"], r["routed_core_km"], r["straight_snapped_km"]))
    res["invariant_routed_total_ge_straight_site_violations"] = len(viol_site)
    res["invariant_routed_core_ge_straight_snapped_violations"] = len(viol_snap)
    res["invariant_violation_examples"] = viol_site[:5]

    # ---- snap distribution ----
    snaps = [r["snap1_km"] for r in rows] + [r["snap2_km"] for r in rows]
    res["snap_km"] = {"min": min(snaps), "p50": med(snaps), "p75": pct(snaps, .75),
                      "p90": pct(snaps, .90), "max": max(snaps),
                      "over_1km": sum(1 for x in snaps if x > 1.0),
                      "over_5km": sum(1 for x in snaps if x > 5.0),
                      "n": len(snaps)}
    from collections import Counter
    res["status"] = dict(Counter(r["status"] for r in rows))

    # ---- published length context ----
    pubs = [r["cable_km"] for r in rows]
    res["published_cable_km"] = {"min": min(pubs), "p50": med(pubs), "max": max(pubs),
                                 "under_5km": sum(1 for p in pubs if p < 5)}
    sl = [r["straight_km"] for r in rows]
    res["straight_km_dist"] = {"min": min(sl), "p50": med(sl), "max": max(sl)}

    # ---- worst 10 by routed error ----
    ok = [r for r in rows if r["status"] == "ok"]
    ok.sort(key=lambda r: -r["ape_routed"])
    res["worst10"] = [{
        "from": r["name_1"], "to": r["name_2"],
        "pub_cable_km": round(r["cable_km"], 2), "ohl_km": round(r["ohl_km"], 2),
        "straight_km": round(r["straight_km"], 2),
        "routed_total_km": round(r["routed_total_km"], 2),
        "routed_core_km": round(r["routed_core_km"], 2),
        "snap1": round(r["snap1_km"], 2), "snap2": round(r["snap2_km"], 2),
        "ape_routed": round(r["ape_routed"], 1), "ape_straight": round(r["ape_straight"], 1),
        "matched_1": r["matched_1"], "matched_2": r["matched_2"],
    } for r in ok[:10]]

    # circuits where straight line already EXCEEDS published (coordinate/rating problem)
    res["straight_exceeds_published_n"] = sum(1 for r in rows if r["straight_km"] > r["cable_km"])
    res["straight_exceeds_published_frac"] = res["straight_exceeds_published_n"] / len(rows)

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

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

Build Graph

A Python command-line tool in the scripts folder of Claude that reads meta, UK primary roads, UK trunk roads and UK motorways, using haversine.

storageclaude / sessions/202609021835-estate-and-corridor/scripts/build_graph.py · lines 1–213 of 213 · version 2026-09-02 18:35 · Entry point · pattern key_of (shared by 2 files)

What it does
It loads meta, UK primary roads, UK trunk roads and UK motorways. Defines read_blob, flatten_geojson, key_of, build, get_id. Uses libraries json, os, sys, time, array. 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: GeoJSON file uk_primary_roads.geojson; GeoJSON file uk_trunk_roads.geojson; GeoJSON file uk_motorways.geojson; command-line arguments. Out: JSON file .meta.json.
Downstream impact
Used directly by 1 file: Rail (claude). Reached from 2 other entry points, including Crossings (claude); Edge Rail (claude).
What it achieves
It reads blob (`read_blob`) and gets id (`get_id`). Build a routable road graph from OSM primary + trunk roads. It writes `.meta.json`.
Why it matters
Imported by Rail.
Application
claude · sessions/202609021835-estate-and-corridor/scripts · Python CLI
Uses
Sessions — Estate and Corridor (import), json, os, sys, time, array, gc, collections, subprocess
Used by
imported by Rail (import)
Produces
read_blob, flatten_geojson, key_of, build
Defines here
read_blob, flatten_geojson, key_of, build, get_id
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/build_graph.py:1-213 · blob 881aa3c8f22a81fa3fa5b6b2601d0a35cf7843c7 · 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
"""Build a routable road graph from OSM primary + trunk roads.

Strategy (memory-conscious, pure Python -- numpy is not installed):
  1. Parse each GeoJSON once, flatten every LineString into a flat array('d')
     of lon/lat pairs plus an array('l') of way start offsets. Drop properties
     and the parsed JSON immediately.
  2. Count how many times each rounded vertex (1e-6 deg, OSM native precision)
     is referenced. A vertex is a JUNCTION if referenced by >= 2 way-positions
     or if it is a way endpoint.
  3. Contract each way into edges between consecutive junctions, carrying the
     true geodesic length (haversine, R = 6371.0088 km) summed over every
     intermediate shape point.
  4. Emit CSR adjacency + node coordinate arrays to a binary file.
"""
import json, os, sys, time, array, gc
from collections import defaultdict
from common import haversine, HERE

CLONES = r"C:\Users\vikra\AppData\Local\Temp\claude\C--Users-vikra\5b94bee7-197b-4cfd-944b-d4cf3aa02d18\scratchpad\clones"
GG = os.path.join(CLONES, "globalgrid2050")
OUT = os.path.join(HERE, "graph")
SCALE = 1_000_000  # 1e-6 degree rounding


def read_blob(path):
    import subprocess
    p = subprocess.run(["git", "-C", GG, "show", "gh/main:" + path],
                       capture_output=True)
    if p.returncode != 0:
        raise RuntimeError(p.stderr[:500])
    return p.stdout


def flatten_geojson(paths):
    """Return (coords array('d') of lon,lat pairs, way_start array('l'))."""
    coords = array.array("d")
    starts = array.array("q")
    nfeat = 0
    for path in paths:
        t0 = time.time()
        raw = read_blob(path)
        gj = json.loads(raw)
        del raw
        feats = gj["features"]
        for f in feats:
            g = f.get("geometry")
            if not g:
                continue
            gt = g.get("type")
            if gt == "LineString":
                lines = [g["coordinates"]]
            elif gt == "MultiLineString":
                lines = g["coordinates"]
            else:
                continue
            for ln in lines:
                if len(ln) < 2:
                    continue
                starts.append(len(coords) // 2)
                for pt in ln:
                    coords.append(pt[0]); coords.append(pt[1])
                nfeat += 1
        del gj, feats
        gc.collect()
        print("  parsed %-32s ways=%d pts=%d  %.1fs" %
              (path, nfeat, len(coords) // 2, time.time() - t0), flush=True)
    starts.append(len(coords) // 2)  # sentinel
    return coords, starts


def key_of(lon, lat):
    return (int(round(lat * SCALE)) + 90_000_000) * 400_000_000 + \
           (int(round(lon * SCALE)) + 180_000_000)


def build(paths, out_prefix):
    t_all = time.time()
    print("[1/4] parsing geojson", flush=True)
    coords, starts = flatten_geojson(paths)
    nways = len(starts) - 1
    npts = len(coords) // 2
    print("  ways=%d shape-points=%d" % (nways, npts), flush=True)

    print("[2/4] counting vertex references", flush=True)
    t0 = time.time()
    cnt = defaultdict(int)
    keys = array.array("q", bytes(8 * npts))  # cache key per shape point
    for w in range(nways):
        a = starts[w]; b = starts[w + 1]
        for i in range(a, b):
            k = key_of(coords[2 * i], coords[2 * i + 1])
            keys[i] = k
            cnt[k] += 1
        # way endpoints are always junctions
        cnt[keys[a]] += 2
        cnt[keys[b - 1]] += 2
    print("  unique vertices=%d  %.1fs" % (len(cnt), time.time() - t0), flush=True)

    print("[3/4] assigning junction ids + contracting ways", flush=True)
    t0 = time.time()
    nid = {}
    nlat = array.array("d"); nlon = array.array("d")
    edges = {}   # (u,v) u<v -> min length km
    geoms = {}   # (u,v) -> array('d') of lon,lat pairs INCLUDING both junctions

    def get_id(k, lon, lat):
        j = nid.get(k)
        if j is None:
            j = len(nlat)
            nid[k] = j
            nlon.append(lon); nlat.append(lat)
        return j

    for w in range(nways):
        a = starts[w]; b = starts[w + 1]
        prev_j = None
        acc = 0.0
        seg = array.array("d")
        plon = coords[2 * a]; plat = coords[2 * a + 1]
        for i in range(a, b):
            lon = coords[2 * i]; lat = coords[2 * i + 1]
            if i > a:
                acc += haversine(plat, plon, lat, lon)
            plat = lat; plon = lon
            if prev_j is not None:
                seg.append(lon); seg.append(lat)
            k = keys[i]
            if cnt[k] >= 2:  # junction
                j = get_id(k, lon, lat)
                if prev_j is not None and j != prev_j and acc > 0.0:
                    e = (prev_j, j) if prev_j < j else (j, prev_j)
                    old = edges.get(e)
                    if old is None or acc < old:
                        edges[e] = acc
                        g = array.array("d", [nlon[prev_j], nlat[prev_j]])
                        g.extend(seg)
                        geoms[e] = g
                prev_j = j
                acc = 0.0
                seg = array.array("d")
    del cnt, keys, coords, starts
    gc.collect()
    nnodes = len(nlat)
    print("  nodes=%d edges=%d  %.1fs" % (nnodes, len(edges), time.time() - t0), flush=True)

    print("[4/4] building CSR + connected components", flush=True)
    t0 = time.time()
    deg = array.array("q", bytes(8 * (nnodes + 1)))
    for (u, v) in edges:
        deg[u + 1] += 1; deg[v + 1] += 1
    for i in range(nnodes):
        deg[i + 1] += deg[i]
    indptr = array.array("q", deg)
    fill = array.array("q", deg[:nnodes])
    m = len(edges)
    indices = array.array("q", bytes(8 * 2 * m))
    weights = array.array("d", bytes(8 * 2 * m))
    eids = array.array("q", bytes(8 * 2 * m))
    gptr = array.array("q", [0])
    gxy = array.array("d")
    for eid, ((u, v), wgt) in enumerate(edges.items()):
        p = fill[u]; indices[p] = v; weights[p] = wgt; eids[p] = eid; fill[u] = p + 1
        p = fill[v]; indices[p] = u; weights[p] = wgt; eids[p] = eid; fill[v] = p + 1
        gxy.extend(geoms[(u, v)])
        gptr.append(len(gxy) // 2)
    del edges, geoms, fill, deg
    gc.collect()

    # connected components (iterative BFS)
    comp = array.array("q", [-1]) * nnodes
    sizes = []
    for s in range(nnodes):
        if comp[s] != -1:
            continue
        cid = len(sizes)
        comp[s] = cid
        stack = [s]; n = 0
        while stack:
            u = stack.pop(); n += 1
            for p in range(indptr[u], indptr[u + 1]):
                v = indices[p]
                if comp[v] == -1:
                    comp[v] = cid; stack.append(v)
        sizes.append(n)
    giant = max(sizes)
    print("  components=%d giant=%d (%.2f%% of nodes)  %.1fs" %
          (len(sizes), giant, 100.0 * giant / nnodes, time.time() - t0), flush=True)

    os.makedirs(OUT, exist_ok=True)
    pre = os.path.join(OUT, out_prefix)
    for name, arr in (("nlat", nlat), ("nlon", nlon), ("indptr", indptr),
                      ("indices", indices), ("weights", weights), ("comp", comp),
                      ("eids", eids), ("gptr", gptr), ("gxy", gxy)):
        with open(pre + "." + name + ".bin", "wb") as fh:
            arr.tofile(fh)
    meta = {"nodes": nnodes, "edges": m, "components": len(sizes),
            "giant": giant, "giant_frac": giant / nnodes,
            "shape_points": npts, "ways": nways,
            "build_seconds": round(time.time() - t_all, 1),
            "sources": paths,
            "total_edge_km": round(sum(weights) / 2.0, 1)}
    json.dump(meta, open(pre + ".meta.json", "w"), indent=1)
    print(json.dumps(meta, indent=1))
    return meta


if __name__ == "__main__":
    which = sys.argv[1] if len(sys.argv) > 1 else "roads"
    if which == "roads":
        build(["uk_primary_roads.geojson", "uk_trunk_roads.geojson"], "roads")
    elif which == "roads_mw":
        build(["uk_primary_roads.geojson", "uk_trunk_roads.geojson",
               "uk_motorways.geojson"], "roads_mw")