In this section
- Rail Browser interaction · seed-data / experiments/economical-seeds/next-rail/rail-browser.mjs lines 1–183
- Rail Source render · seed-data / experiments/economical-seeds/next-rail/rail-source.mjs lines 1–148
- Seed Discover storage · seed-data / experiments/economical-seeds/seed_discover.py lines 1–192
- Seed Plan storage · seed-data / experiments/economical-seeds/seed_plan.py lines 1–95
Rail Browser
A JavaScript module in the next rail folder of Seed Data that fetches UK mainline railways, using SHA-256 from the GridAtlas repository. It is built from the query step (`query`).
interactionseed-data / experiments/economical-seeds/next-rail/rail-browser.mjs · lines 1–183 of 183 · Not reached from any entry point (candidate for review) · pattern until (shared by 3 files)
- What it does
- It fetches UK mainline railways. Defines until, call, run, query. Uses libraries node:assert/strict, node:child_process, node:fs/promises, node:os, node:path. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage experimental (path word 'experiments'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
- Inputs & outputs
- In: data source: gridatlas data; JSON file rail-browser.json; Parquet file uk_mainline_railways.parquet; GeoJSON file uk_mainline_railways.geojson; command-line arguments.
- What it achieves
- Defines `until`, `call`, `run` and 1 more. It responds to message, open and error events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- seed-data · experiments/economical-seeds/next-rail · JavaScript module
- Uses
- GridAtlas — Atlas Page (estate URL), node:assert/strict, node:child_process, node:fs/promises, node:os, node:path, node:timers/promises
- Used by
- none found
- Produces
- until, call, run, query
- Defines here
- until, call, run, query
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- seed-data@e4af7ee340a38d94f21ddbba147395b569ccce11 experiments/economical-seeds/next-rail/rail-browser.mjs:1-183 · blob 88b11504429f68744ede82a0a0f4941eb2f6def3 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, network, process, storage · domain stage: experimental · users: none · canonical: unreached_review
import assert from 'node:assert/strict';
import {spawn} from 'node:child_process';
import {mkdtemp, readFile, rm, writeFile} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import {join} from 'node:path';
import {setTimeout as sleep} from 'node:timers/promises';
const [chrome, outfile = 'rail-browser.json', url = 'https://ventusltd.github.io/gridatlas/atlas/'] = process.argv.slice(2);
if (!chrome) throw Error('usage: node rail-browser.mjs CHROME [RECEIPT] [ATLAS_URL]');
const expected = {
generation: '202611222343',
bridge: '60be8215ba873ac2886786bf6e3fd51e5764e7c5e26684fde71ebe9974a329a2',
partition: 'partitions/uk_mainline_railways.parquet',
sha256: '4cbd1a2b59a33e5e7d8416301cbe357941c94d70db5ca1410a04a9da2a1884cc',
rows: 89933,
};
const profile = await mkdtemp(join(tmpdir(), 'seed-rail-chrome-'));
const browser = spawn(chrome, ['--headless=new','--no-first-run','--no-default-browser-check',
'--disable-background-networking','--remote-debugging-port=0','--window-size=1400,900',
'--use-angle=swiftshader','--enable-unsafe-swiftshader', '--user-data-dir=' + profile, 'about:blank'],
{windowsHide:true, stdio:'ignore'});
let socket, sequence = 0, session;
const awaiting = new Map();
const requests = new Set();
const checks = {};
const started=Date.now();
let stage = 'chrome';
function until(fn, timeout, description) {
const start = Date.now();
return (async () => {
while (Date.now() - start < timeout) {
const result = await fn();
if (result) return result;
await sleep(200);
}
throw new Error('Timeout: ' + description);
})();
}
function call(method, params = {}, scoped = true) {
const id = ++sequence;
return new Promise((resolve,reject) => {
const timeout = setTimeout(() => {
awaiting.delete(id);
reject(new Error('CDP timeout: ' + method));
}, 12_000);
awaiting.set(id, {resolve,reject,timeout});
socket.send(JSON.stringify({id, method, params, ...(scoped && session ? {sessionId:session} : {})}));
});
}
async function run(expression) {
const response = await call('Runtime.evaluate', {expression,returnByValue:true,awaitPromise:true});
if (response.exceptionDetails) throw new Error(response.exceptionDetails.exception?.description || expression);
return response.result.value;
}
const query = (expression, timeout = 30_000) => until(() => run(expression), timeout, expression);
const state = String.raw`(() => {
const map = window.__GRIDATLAS_V9_MAP__;
const bridge = window.__GRIDATLAS_MAP_READY__;
const atlas = window.__GRIDATLAS_ATLAS__;
if (!map || !map.getLayer('l-mainline_rail') || !bridge || !atlas) return null;
const selected = Object.entries(bridge.loaded_on_demand).find(([key]) => key.endsWith('/uk_mainline_railways.geojson'));
return { generation: atlas.generation, bridgeDigest: atlas.loaded_cartridges.find(row => row.id === 'streaming-parquet-bridge')?.sha256,
layer:map.getLayer('l-mainline_rail').type, source:map.getLayer('l-mainline_rail').source,
visibility:map.getLayoutProperty('l-mainline_rail','visibility'),
paint:{color:map.getPaintProperty('l-mainline_rail','line-color'),width:map.getPaintProperty('l-mainline_rail','line-width')},
checkbox: Boolean(document.querySelector('input[data-layer-id=mainline_rail]')),
rail: selected?.[1] || null, parquetRequests:bridge.parquet_requests, releasedPayloads:bridge.released_payloads,
railFailure:bridge.stream_failures.find(x => x.pathname?.endsWith('/uk_mainline_railways.geojson'))?.message };
})()`;
const rendered = String.raw`(() => {
const m=window.__GRIDATLAS_V9_MAP__, layer='l-mainline_rail';
if (!m.isSourceLoaded('src-mainline_rail')) return null;
const features=m.queryRenderedFeatures({layers:[layer]});
if (!features.length) return null;
const bounds=m.getCanvas().getBoundingClientRect();
let click;
outer: for(const f of features.slice(0,240)) {
const sequences=f.geometry.type==='LineString'?[f.geometry.coordinates]:f.geometry.coordinates;
for(const seq of sequences) {
for(let i=1;i<Math.min(seq.length,12);i++) {
const a=m.project(seq[i-1]),b=m.project(seq[i]);
const p=[(a.x+b.x)/2,(a.y+b.y)/2];
if (p[0] < bounds.width*0.27 || p[0]>bounds.width*0.85 || p[1]<150 || p[1]>bounds.height-100) continue;
const x=p[0]+bounds.x,y=p[1]+bounds.y;
if(document.elementFromPoint(x,y)!==m.getCanvas()) continue;
const picked=m.queryRenderedFeatures(p,{layers:[layer]})[0];
if (picked) { click={x,y,id:picked.id ?? null, name:picked.properties?.name ?? null}; break outer; }
}
}
}
return {zoom:m.getZoom(),hits:features.length,geometry:[...new Set(features.map(f=>f.geometry.type))],
identities:[...new Set(features.map(f=>f.id).filter(v=>v!=null))].slice(0,8), click};
})()`;
try {
const port = await until(async () => {
try {return (await readFile(join(profile,'DevToolsActivePort'),'utf8')).trim().split(/\r?\n/);} catch {return null;}
}, 10_000, 'Chrome DevTools port');
socket = new WebSocket('ws://127.0.0.1:' + port[0] + port[1]);
socket.addEventListener('message', event => {
const message = JSON.parse(event.data);
if (message.id && awaiting.has(message.id)) {
const work = awaiting.get(message.id); awaiting.delete(message.id); clearTimeout(work.timeout);
message.error ? work.reject(new Error(message.error.message)) : work.resolve(message.result);
}
if (message.method === 'Network.requestWillBeSent' && /uk_mainline_railways\.(geojson|parquet)/.test(message.params.request.url)) {
requests.add(message.params.request.url);
}
});
await new Promise((resolve,reject) => {
socket.addEventListener('open',resolve,{once:true});
socket.addEventListener('error',reject,{once:true});
});
checks.browser = (await call('Browser.getVersion',{},false)).product;
const {targetId} = await call('Target.createTarget',{url:'about:blank'},false);
session = (await call('Target.attachToTarget',{targetId,flatten:true},false)).sessionId;
await call('Page.enable'); await call('Runtime.enable'); await call('Network.enable');
await call('Emulation.setDeviceMetricsOverride',{width:1400,height:900,deviceScaleFactor:1,mobile:false});
stage='bootstrap';
const nav = await call('Page.navigate',{url});
assert(!nav.errorText, nav.errorText);
checks.before=await query(state,55_000);
assert.equal(checks.before.generation, expected.generation);
assert.equal(checks.before.bridgeDigest,expected.bridge);
assert.equal(checks.before.layer,'line');
assert.equal(checks.before.source,'src-mainline_rail');
assert.equal(checks.before.visibility,'none');
assert.equal(checks.before.rail,null);
assert(checks.before.checkbox);
stage='activate UK mainline layer';
await run("document.querySelector('input[data-layer-id=mainline_rail]').click(); true");
checks.hydrated=await query('(() => { const s='+state+'; return (s?.rail && s.releasedPayloads > '+checks.before.releasedPayloads+' || s?.railFailure) ? s : null; })()', 95_000);
assert(!checks.hydrated.railFailure, checks.hydrated.railFailure);
assert.deepEqual(checks.hydrated.rail,{parquet:expected.partition,rows:expected.rows,sha256:expected.sha256});
assert.equal(checks.hydrated.visibility,'visible');
stage='national viewport';
await run("window.__GRIDATLAS_V9_MAP__.jumpTo({center:[-3.5,54],zoom:5});true");
checks.national=await query(rendered);
assert.equal(checks.national.zoom,5);
assert(checks.national.geometry.every(type => /LineString$/.test(type)));
stage='detailed viewport';
await run("window.__GRIDATLAS_V9_MAP__.jumpTo({center:[-0.125,51.515],zoom:12});true");
checks.detail=await query('(() => { const r='+rendered+'; return r?.click ? r : null; })()');
assert.equal(checks.detail.zoom,12);
assert(checks.detail.geometry.every(type => /LineString$/.test(type)));
stage='feature click';
const {x,y}=checks.detail.click;
await call('Input.dispatchMouseEvent',{type:'mousePressed',x,y,button:'left',clickCount:1});
await call('Input.dispatchMouseEvent',{type:'mouseReleased',x,y,button:'left',clickCount:1});
checks.popup=await query("document.querySelector('.maplibregl-popup-content')?.innerText?.trim()",8_000);
assert(checks.detail.click.name);
assert(checks.popup.includes(checks.detail.click.name));
stage='visibility toggle and reuse';
const settledBeforeToggle=await query(state);
const toggle="document.querySelector('input[data-layer-id=mainline_rail]').click();true";
await run(toggle);
checks.hidden=await query("window.__GRIDATLAS_V9_MAP__.queryRenderedFeatures({layers:['l-mainline_rail']}).length === 0");
await run(toggle);
checks.restored=await query(rendered);
checks.after=await query(state);
assert.equal(checks.after.parquetRequests,settledBeforeToggle.parquetRequests);
assert.equal(checks.after.releasedPayloads,settledBeforeToggle.releasedPayloads);
stage='pass';
} catch (error) {
checks.error = String(error.message).replaceAll(profile,'<browser-profile>');
try {
checks.diagnostic=await run("({title:document.title,generation:window.__GRIDATLAS_ATLAS__?.generation ?? null, map:!!window.__GRIDATLAS_V9_MAP__, bridge:!!window.__GRIDATLAS_MAP_READY__, railwayFailures:window.__GRIDATLAS_MAP_READY__?.stream_failures?.filter(x=>x.pathname?.includes('mainline')) ?? []})");
} catch {}
process.exitCode=1;
} finally {
if (socket?.readyState === WebSocket.OPEN) {
try { await Promise.race([call('Browser.close',{},false),sleep(1500)]); } catch {}
}
socket?.close();
browser.kill();
for (const entry of awaiting.values()) clearTimeout(entry.timeout);
await rm(profile,{recursive:true,force:true,maxRetries:4,retryDelay:100}).catch(()=>{});
const receipt={status:stage==='pass'?'passed':'bounded failure',stage,scope:'Pinned live composition and desktop viewport; no complete coverage or timing guarantee.',url,expected,checks,elapsedMs:Date.now()-started,documentNetworkRequests:[...requests]};
await writeFile(outfile,JSON.stringify(receipt,null,2)+'\n',{flag:'wx'});
console.log(JSON.stringify({status:receipt.status,stage,error:checks.error}));
}
Rail Source
A JavaScript module in the next rail folder of Seed Data that fetches rail receipt and UK mainline railways, using SHA-256 from the data-GridAtlas and GridAtlas repositories.
renderseed-data / experiments/economical-seeds/next-rail/rail-source.mjs · lines 1–148 of 148 · Not reached from any entry point (candidate for review) · pattern layer (shared by 2 files)
- What it does
- It fetches rail receipt and UK mainline railways. Defines sha256, gitBlob, request, grid, layer. Uses libraries node:crypto, node:child_process, node:fs/promises, node:vm. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage experimental (path word 'experiments'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
- Inputs & outputs
- In: data source: data-gridatlas data; data source: gridatlas data; JSON file rail-source-receipt.json; Parquet file uk_mainline_railways.parquet; Parquet file railways.parquet; GeoJSON file uk_mainline_railways.geojson; GeoJSON file railways.geojson; DuckDB queries.
- What it achieves
- It is built from the git blob helper (`gitBlob`), the grid step (`grid`) and the layer step (`layer`). Defines `sha256`, `gitBlob`, `request` and 2 more.
- Why it matters
- No other file in the estate was found to import it.
- Application
- seed-data · experiments/economical-seeds/next-rail · JavaScript module
- Uses
- GridAtlas — Atlas Page (estate URL), node:crypto, node:child_process, node:fs/promises, node:vm
- Used by
- none found
- Produces
- sha256, gitBlob, request, grid, layer
- Defines here
- sha256, gitBlob, request, grid, layer
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- seed-data@e4af7ee340a38d94f21ddbba147395b569ccce11 experiments/economical-seeds/next-rail/rail-source.mjs:1-148 · blob 8876a6836f0274e46ce13405977915e761516184 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, network, process, storage · domain stage: experimental · users: none · canonical: unreached_review
import assert from 'node:assert/strict';
import {createHash} from 'node:crypto';
import {execFileSync} from 'node:child_process';
import {writeFile} from 'node:fs/promises';
import vm from 'node:vm';
const GRIDATLAS = 'afffa9781f6130529ae93052604cd3d98d172a35';
const R = 'atlas/releases/202608300453-atlas-v9/';
const BRIDGE = 'atlas/cartridges/202609241251-streaming-parquet-bridge-v9-5.js';
const DATA = 'https://ventusltd.github.io/data-gridatlas/202608291237-data-gridatlas/data/';
const [outfile = 'rail-source-receipt.json', repo] = process.argv.slice(2);
const sha256 = bytes => createHash('sha256').update(bytes).digest('hex');
const gitBlob = bytes => createHash('sha1').update('blob '+bytes.length+'\0').update(bytes).digest('hex');
async function request(url) {
const result = await fetch(url, {signal:AbortSignal.timeout(20000)});
assert(result.ok, 'HTTP '+result.status+' at '+url);
return Buffer.from(await result.arrayBuffer());
}
async function grid(path, pin) {
const raw = repo ? execFileSync('git',['--no-lazy-fetch','-C',repo,'show',GRIDATLAS+':'+path])
: await request('https://raw.githubusercontent.com/Ventusltd/gridatlas/'+GRIDATLAS+'/'+path);
assert.equal(gitBlob(raw),pin, path);
return raw.toString('utf8');
}
const [engine,shell,bridge,manifestBytes] = await Promise.all([
grid(R+'ventus-corev8engine.js','c53342c2cab7086cbd26be90f5524647165f76aa'),
grid(R+'index.html','0b27ff625f14a5dcccaca4901f481d06cf58e56c'),
grid(BRIDGE,'62a6ade186de4ed6848d017b3b3b410b028efa87'),
request(DATA+'manifest.json'),
]);
assert.equal(sha256(manifestBytes),'3246dbdaa042ae8352ec9b7128cb6c2fe65e4f1aba0534302510661828df2526');
const manifest = JSON.parse(manifestBytes);
const partition = manifest.artifacts.find(row => row.path==='partitions/uk_mainline_railways.parquet');
assert.equal(partition.rows,89933);
assert.equal(partition.bytes,16109232);
assert.equal(partition.sha256,'4cbd1a2b59a33e5e7d8416301cbe357941c94d70db5ca1410a04a9da2a1884cc');
assert.equal(manifest.artifacts.find(row=>row.path==='partitions/railways.parquet').rows,3596);
function layer(id) {
const source = shell.match(new RegExp(String.raw`\{ id: "\$\{id\}"[^\n]+\}`.replace('\\$\\{id\\}',id)));
assert(source,id);
return vm.runInNewContext('('+source[0]+')',{});
}
const line = layer('mainline_rail'), points = layer('rail');
assert.equal(line.url,'/uk_mainline_railways.geojson');
assert.equal(line.type,'line');
assert.equal(line.preload,false);
assert.equal(line.color,'#ff8800');
assert.equal(line.width,1.5);
assert.equal(points.type,'point');
assert.equal(points.preload,true);
assert.equal(points.url,'data/railways.geojson');
assert(shell.includes('maplibre-gl@3.6.2/dist/maplibre-gl.js'));
const fetches = [], queries = [], closed = [];
const sample = {
type:'LineString',
coordinates:[[-0.12,51.51],[-0.11,51.52]],
};
const fixture = {source_id:'mainline',feature_index:12, feature_id:'sample', geometry_json:JSON.stringify(sample),properties_json:'{"name":"fixture rail"}'};
const context = vm.createContext({
window:{location:{href:'https://ventusltd.github.io/gridatlas/atlas/'}},
URL,TextDecoder,TextEncoder,Response,ReadableStream,DOMException,crypto:globalThis.crypto,
performance,queueMicrotask:()=>{},console,
});
context.window.fetch = async (url, options) => {
fetches.push({url,cache:options?.cache});
assert.equal(url,DATA+'manifest.json');
return new Response(manifestBytes);
};
context.window.__GRIDATLAS_DUCKDB_RUNTIME__ = {
module_url:'https://cdn.jsdelivr.net/npm/@duckdb/duckdb-wasm@1.29.0/+esm',
promise:Promise.resolve({database:{connect:async()=>({
query: async sql => { queries.push(sql); return {toArray:()=>[fixture]}; },
close: async () => closed.push(true),
})}}),
};
vm.runInContext(bridge,context,{filename:BRIDGE});
const state = context.window.__GRIDATLAS_MAP_READY__;
assert.equal(state.parquet_requests,0);
assert.equal(state.duckdb_runtime_started,false);
assert.equal(fetches.length,0);
const response = await context.window.fetch(line.url);
const hydrated = await response.json();
assert.equal(queries.length,1);
assert.equal(response.headers.get('X-GridAtlas-Data-Plane'),'V9-PARQUET-DUCKDB-STREAMED-RESPONSE');
assert(queries[0].includes(DATA+partition.path));
assert(queries[0].includes('ORDER BY feature_index'));
assert.equal(hydrated.features[0].id,'sample');
assert.deepEqual(hydrated.features[0].geometry,sample);
assert.equal(hydrated.features[0].properties.name,'fixture rail');
assert.equal(closed.length,1);
assert.equal(state.released_payloads,1);
assert.equal(state.loaded_on_demand[line.url].parquet,partition.path);
const shellFrom = engine.indexOf('function handleLayerToggle');
const shellTo = engine.indexOf('map.on(\'load\',',shellFrom);
assert(shellFrom >= 0 && shellTo > shellFrom);
const requests=[], layout=[], geometry=[];
const shellContext = {
map:{
getLayer:id => id==='l-mainline_rail',
setLayoutProperty: (_,key,value) => layout.push({key,value}),
getSource:id => { assert.equal(id,'src-mainline_rail'); return {setData:value => geometry.push(value)}; },
},
statusMode:false,
_visibleInteractiveIds:[],
_visibleHoverIds:[],
layerConfigById:new Map([[line.id,line]]),
RUNTIME_STATE:{[line.id]:{loaded:false,loading:false}},
REPD_IDS:[], TRANSIT_IDS:[],
networkQueue:{add:fn=>fn()},
fetchAndParseGeoJSON:async url => {requests.push(url); return hydrated.features;},
updateUIState:()=>{},
};
vm.createContext(shellContext);
vm.runInContext(engine.slice(shellFrom,shellTo),shellContext,{filename:R+'ventus-corev8engine.js'});
shellContext.handleLayerToggle(line.id,true);
await new Promise(setImmediate);
shellContext.handleLayerToggle(line.id,false);
shellContext.handleLayerToggle(line.id,true);
await new Promise(setImmediate);
assert.equal(requests.length,1);
assert.equal(requests[0],line.url);
assert.equal(geometry.length,1);
assert.equal(geometry[0].features[0].geometry.type,'LineString');
assert.deepEqual(layout.map(x=>x.value),['visible','none','visible']);
assert(engine.includes('queryRenderedFeatures(e.point, { layers: _visibleInteractiveIds })'));
const summary = {
status:'passed',
scope:'Exact source and declared dataset identity; one controlled DuckDB row and mock MapLibre source for mechanism checks.',
source:{
gridatlasCommit:GRIDATLAS,
engine:{path:R+'ventus-corev8engine.js',blob:'c53342c2cab7086cbd26be90f5524647165f76aa',tablet:1732,elementIds:{fetchAndParseGeoJSON:5647,hydrateLayer:5804,selectRenderedFeature:5811,handleLayerToggle:8736}},
shell:{path:R+'index.html',blob:'0b27ff625f14a5dcccaca4901f481d06cf58e56c',tablet:1731},
bridge:{path:BRIDGE,blob:'62a6ade186de4ed6848d017b3b3b410b028efa87',tablet:6504,elementIds:{queryOnDemand:8351,resolvePartition:143597}},
maplibreVersion:'3.6.2',
},
data:{root:DATA,manifestSha256:sha256(manifestBytes),partition},
layers:{line,points},fixture:{queries:queries.length,connectionClose:closed.length,releasedPayloads:state.released_payloads,
initialParquetRequests:0,sourceUpdates:geometry.length,renderVisibility:layout.map(x=>x.value)},
};
await writeFile(outfile,JSON.stringify(summary,null,2)+'\n',{flag:'wx'});
console.log(JSON.stringify({status:summary.status, partition:partition.path, documentedRows:partition.rows}));
Seed Discover
A Python command-line tool in the economical seeds folder of Seed Data that reads catalogue, using SHA-256.
storageseed-data / experiments/economical-seeds/seed_discover.py · lines 1–192 of 192 · Entry point · pattern initialize (shared by 2 files)
- What it does
- It loads catalogue. Defines 10 functions or classes, including canonical, available_record, base_catalogue, validate_record, install. Uses libraries argparse, hashlib, json, re, sqlite3. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage experimental (path word 'experiments'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
- Inputs & outputs
- In: JSON file catalogue.json; SQLite database; command-line arguments.
- Downstream impact
- Used directly by 3 files: Test VEDIC Candidate (seed-data); VEDIC Candidate (seed-data); Seed Plan (seed-data). Reached from 1 other entry point, including Seed Regressions Workflow (seed-data).
- What it achieves
- It validates record (`validate_record`) and is built from the canonical step (`canonical`) and the available record helper (`available_record`). Index demonstrated instrument contracts and retrieve evidence only on request. It reads `catalogue.json`. It accepts `--catalogue`, `--record` and `--top`.
- Why it matters
- Imported by VEDIC Candidate and Seed Plan. Checked by Test VEDIC Candidate.
- Application
- seed-data · experiments/economical-seeds · Python CLI
- Uses
- Magnets (import), argparse, hashlib, json, re, sqlite3, time, collections, contextlib
- Used by
- imported by Test VEDIC Candidate (import), imported by VEDIC Candidate (import), imported by Seed Plan (import)
- Produces
- canonical, available_record, base_catalogue, validate_record, install, initialize, obj_terms, expand, discover, main
- Defines here
- canonical, available_record, base_catalogue, validate_record, install, initialize, obj_terms, expand, discover, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- seed-data@e4af7ee340a38d94f21ddbba147395b569ccce11 experiments/economical-seeds/seed_discover.py:1-192 · blob 34ba1b77b2a143c00ee2cac4491925747136976d · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, storage · domain stage: experimental · users: none · canonical: supporting_data
"""Index demonstrated instrument contracts and retrieve evidence only on request."""
import argparse
import hashlib
import json
import re
import sqlite3
import time
from collections import deque
from contextlib import closing
from pathlib import Path
from magnets import ROOT, read_json
BASE = ROOT / "economy"
DEFAULT = BASE / "discovery.sqlite"
STOP_WORDS = set("""
a about all also an and any are as at be by can could do does find for from get give
have how i in into is it me of on or our please show so some tell than that the their
them there these this through to use want was we what when where which who will with would you
""".split())
SCHEMA = """
create table record(
id text primary key,
title text not null,
status text not null,
observable text not null,
locator text not null,
contract text not null
);
create table dependency(
owner text not null references record(id),
component text not null references record(id),
primary key(owner,component),
check(owner<>component)
);
create virtual table objective_fts using fts5(id unindexed,title, observable, terms, status unindexed,
tokenize='porter unicode61');
"""
def canonical(value):
return json.dumps(value, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
def available_record(key, title, status, observable, locator, terms="", components=(), **details):
return dict(id=key, title=title, status=status, observable=observable, locator=locator,
terms=terms, components=list(components), **details)
def base_catalogue():
return read_json(BASE / "catalogue.json")
def validate_record(record, workspace):
required = ("id", "title", "status", "observable", "locator")
if any(not isinstance(record.get(key), str) or not record[key].strip() for key in required):
raise ValueError("An instrument needs an id, title, status, observable and evidence locator")
locator = (workspace / record["locator"]).resolve()
if not locator.is_relative_to(workspace.resolve()) or not locator.is_file():
raise ValueError(f"Missing or outside-workspace evidence locator: {record['locator']}")
stored = dict(record)
stored.pop("digest", None)
return dict(stored, digest=hashlib.sha256(canonical(stored).encode()).hexdigest())
def install(db, records, workspace=ROOT):
records = [validate_record(record, workspace) for record in records]
with db:
for record in records:
values = tuple(record[name] for name in ("id", "title", "status", "observable", "locator"))
db.execute("insert into record values(?,?,?,?,?,?)", (*values, canonical(record)))
db.execute("insert into objective_fts values(?,?,?,?,?)",
(record["id"], record["title"], record["observable"], record.get("terms", ""),
record["status"]))
for record in records:
db.executemany("insert into dependency values(?,?)",
((record["id"], child) for child in record.get("components", [])))
for record in records:
cycle = db.execute("""with recursive inputs(id) as (
select component from dependency where owner = ?
union
select dependency.component from dependency join inputs on dependency.owner=inputs.id
) select 1 from inputs where id=?""", (record["id"], record["id"])).fetchone()
if cycle:
raise ValueError(f"Recursive dependency cycle at {record['id']}")
def initialize(path, inputs):
with path.open("xb"):
pass
try:
with closing(sqlite3.connect(path)) as db:
db.execute("pragma foreign_keys=on")
db.executescript(SCHEMA)
install(db, inputs)
except Exception:
path.unlink()
raise
def obj_terms(objective):
return sorted(set(re.findall(r"[^\W_]+", objective.casefold())) - STOP_WORDS)
def expand(db, roots, depth, cap):
scheduled = deque((item, 0) for item in roots)
visited = set()
details = []
while scheduled and len(details) < cap:
key, level = scheduled.popleft()
if key in visited:
continue
visited.add(key)
contract, = db.execute("select contract from record where id=?", (key,)).fetchone()
details.append(dict(level=level, instrument=json.loads(contract)))
if level < depth:
scheduled.extend((child, level+1) for child, in db.execute(
"select component from dependency where owner=? order by component", (key,)))
return details, any(k not in visited for k, _ in scheduled)
def discover(path, objective, top, depth=None, cap=10, verified_only=False):
start = time.perf_counter_ns()
cpu_start = time.process_time_ns()
terms = obj_terms(objective)
result = dict(objective=objective, terms=terms, hits=[], expanded=[], expansion_budget_exhausted=False)
if terms:
query = " OR ".join(f'"{term}"' for term in terms)
with closing(sqlite3.connect(path.resolve().as_uri()+"?mode=ro", uri=True)) as db:
db.execute("pragma query_only=on")
rows = db.execute("""
select r.id,r.title,r.status,r.observable,r.locator
from objective_fts join record r on objective_fts.id=r.id
where objective_fts match ? and (not ? or r.status like 'demonstrated%')
order by bm25(objective_fts,0,5,2,1,0),
case when r.status like 'demonstrated%' then 0 else 1 end, r.id
limit ?
""", (query, verified_only, top)).fetchall()
names = ("id", "title", "status", "observable", "locator")
result["hits"] = [dict(zip(names, row)) for row in rows]
if depth is not None:
details, remaining = expand(db, [r[0] for r in rows], depth, cap)
result.update(expanded=details, expansion_budget_exhausted=remaining)
result["status"] = "candidate_matches" if result["hits"] else "no_indexed_match"
result["metrics"] = dict(summary_rows=len(result["hits"]), detail_rows=len(result["expanded"]),
record_json_utf8_bytes=sum(len(canonical(row).encode())
for row in result["hits"] + result["expanded"]),
estate_source_bytes_read=0, evidence_payload_bytes_read=0,
inference_calls=0, cpu_ms=(time.process_time_ns()-cpu_start)/1e6,
wall_ms=(time.perf_counter_ns()-start)/1e6)
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--catalogue", type=Path, default=DEFAULT)
command = parser.add_subparsers(dest="command", required=True)
build = command.add_parser("build", help="Read the existing small instrument receipts once")
build.add_argument("--record", type=Path, action="append", default=[])
register = command.add_parser("register", help="Append a new revision and its existing inputs")
register.add_argument("record", type=Path, nargs="+")
query = command.add_parser("find", help="Retrieve a few summaries for a human objective")
query.add_argument("objective")
query.add_argument("--top", type=int, default=3)
query.add_argument("--expand-depth", type=int)
query.add_argument("--max-details", type=int, default=8)
query.add_argument("--demonstrated", action="store_true")
args = parser.parse_args()
if args.command == "build":
start = time.perf_counter_ns()
cpu_start = time.process_time_ns()
records = list(base_catalogue()) + [read_json(path) for path in args.record]
initialize(args.catalogue, records)
print(json.dumps(dict(indexed=len(records), index_file_bytes=args.catalogue.stat().st_size,
wall_ms=(time.perf_counter_ns()-start)/1e6,
cpu_ms=(time.process_time_ns()-cpu_start)/1e6, inference_calls=0)))
elif args.command == "register":
with closing(sqlite3.connect(args.catalogue.resolve().as_uri()+"?mode=rw", uri=True)) as db:
db.execute("pragma foreign_keys=on")
install(db, [read_json(path) for path in args.record])
print(json.dumps(dict(registered=len(args.record))))
else:
if args.top < 1 or args.max_details < 1 or (args.expand_depth is not None and args.expand_depth < 0):
parser.error("Limits must be positive and expansion depth must be non-negative")
result = discover(args.catalogue, args.objective, args.top, args.expand_depth, args.max_details,
args.demonstrated)
print(json.dumps(result, indent=2))
if __name__ == "__main__":
main()Seed Plan
A Python command-line tool in the economical seeds folder of Seed Data that reads wafer and routes.
storageseed-data / experiments/economical-seeds/seed_plan.py · lines 1–95 of 95 · Entry point
- What it does
- It loads wafer and routes. Defines safe_url, supplied_values, valid_input, plan. Uses libraries argparse, json, re, sqlite3, contextlib. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage experimental (path word 'experiments'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. README: "`seed_plan.py` uses narrow declared contracts to identify a bounded invocation, list missing inputs or mark an objective for investigation."
- Inputs & outputs
- In: JSON file universe.json; JSON file wafer.json; JSON file routes.json; SQLite database; command-line arguments.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It is built from the safe URL helper (`safe_url`), the supplied values helper (`supplied_values`) and the valid input helper (`valid_input`). The README says: `seed_plan.py` uses narrow declared contracts to identify a bounded invocation, list missing inputs or mark an objective for investigation. It accepts `--instrument`, `--catalogue` and `--routes`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- seed-data · experiments/economical-seeds · Python CLI
- Uses
- Magnets (import), Seed Discover (import), argparse, json, re, sqlite3, contextlib, pathlib, urllib.parse
- Used by
- none found
- Produces
- safe_url, supplied_values, valid_input, plan
- Defines here
- safe_url, supplied_values, valid_input, plan
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- seed-data@e4af7ee340a38d94f21ddbba147395b569ccce11 experiments/economical-seeds/seed_plan.py:1-95 · blob c76c6f3567e5209435b57872b4cc322f088f4432 · GitHub at these lines
- State
- achieves: readme · context: readme_derived · stage: ingest · effects: filesystem, storage · domain stage: experimental · users: none · canonical: supporting_data
"""Choose a verified, bounded invocation contract or return what is missing."""
import argparse
import json
import re
import sqlite3
from contextlib import closing
from pathlib import Path
from urllib.parse import urlsplit
from magnets import read_json
from seed_discover import BASE, DEFAULT, discover
def safe_url(value):
try:
parsed = urlsplit(value)
except ValueError:
return False
return parsed.scheme in {"http", "https"} and bool(parsed.hostname) and not parsed.username
def supplied_values(values):
result = {}
for value in values:
key, separator, provided = value.partition("=")
if not separator or not key or not provided or key in result:
raise ValueError("Inputs must be unique NAME=VALUE pairs")
result[key] = provided
return result
def valid_input(kind, value):
if kind == "file":
return Path(value).is_file()
if kind == "ordinal":
return bool(re.fullmatch(r"[0-9]{1,15}", value))
if kind == "resource_url":
return safe_url(value)
if kind == "cartridge":
return value in {"universe.json", "wafer.json"}
raise ValueError(f"Unsupported contract input type: {kind}")
def plan(catalogue, routes, objective, supplied, explicit=None):
text = objective.casefold()
matched = [
route for route in routes if (
route["id"] == explicit if explicit is not None else
all(any(re.search(r"(?<!\w)" + re.escape(phrase) + r"(?!\w)", text) for phrase in group)
for group in route["match"])
)
]
result = dict(objective=objective, ai_inference_calls=0, estate_payload_opened=False)
if len(matched) != 1:
result.update(status="ambiguous" if len(matched) > 1 else "investigate",
known_contracts=[route["id"] for route in matched])
if not matched:
result["candidates"] = discover(catalogue, objective, 3)["hits"]
result["reason"] = "Catalogued similarity alone cannot establish a sufficient executable contract."
return result
route, = matched
with closing(sqlite3.connect(catalogue.resolve().as_uri() + "?mode=ro", uri=True)) as database:
record = database.execute("select title,status,locator from record where id=?", (route["id"],)).fetchone()
if not record or not record[1].startswith("demonstrated"):
result.update(status="investigate", reason="The route lacks a demonstrated record.")
return result
missing = [key for key in route["inputs"] if key not in supplied]
invalid = [key for key, kind in route["inputs"].items()
if key in supplied and not valid_input(kind, supplied[key])]
extra = sorted(set(supplied) - set(route["inputs"]))
result.update(instrument=route["id"], title=record[0], scope=route["scope"],
prior_evidence=record[2], missing=missing, invalid=invalid, unexpected=extra)
if missing or invalid or extra:
result["status"] = "supply_inputs"
else:
result.update(status="ready_for_checked_invocation", argv=[word.format(**supplied) for word in route["argv"]],
evidence_status="Execution still needs to verify this input and output.")
return result
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("objective")
parser.add_argument("--instrument", help="Explicit route ID when the wording is unfamiliar")
parser.add_argument("--catalogue", type=Path, default=DEFAULT)
parser.add_argument("--routes", type=Path, default=BASE / "routes.json")
parser.add_argument("--provide", action="append", default=[])
args = parser.parse_args()
try:
result = plan(args.catalogue, read_json(args.routes), args.objective, supplied_values(args.provide), args.instrument)
except (ValueError, OSError, sqlite3.Error) as error:
parser.error(str(error))
print(json.dumps(result, indent=2))