In this section
- GPU Check storage · soil / gpu_check.py lines 1–49
- Import Environment storage · soil / import_environment.py lines 1–112
- Import Soil storage · soil / import_soil.py lines 1–42
- Test Thermal test · soil / test_thermal.py lines 1–43
- Thermal transform · soil / thermal.py lines 1–70
- Estate Survey storage · spiders / tools/estate-survey.mjs lines 1–384
GPU Check
A Python module in Soil that reads sssi and provenance, using SHA-256. It is built from the classify step (`classify`) and the polygon step (`polygon`).
storagesoil / gpu_check.py · lines 1–49 of 49 · Not reached from any entry point (candidate for review) · pattern polygon (shared by 2 files)
- What it does
- It loads sssi and provenance. Defines classify, polygon. Uses libraries json, hashlib, time, pathlib, numpy. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (repository name word 'soil'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. README: "`gpu_check.py`: CuPy polygon membership checked against an independent CPU winding-angle calculation, plus labelled thermal-unit fixtures."
- Inputs & outputs
- In: GeoJSON file sssi.geojson; JSON file provenance.json. Out: JSON file checks.json.
- What it achieves
- Bounded double-precision GPU screening of imported conservation polygons.
- Why it matters
- No other file in the estate was found to import it.
- Application
- soil · / · Python module
- Uses
- Thermal (import), json, hashlib, time, pathlib, numpy, cupy
- Used by
- none found
- Produces
- classify, polygon
- Defines here
- classify, polygon
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- soil@d26288ed03df533507739b9f218358fc7aa36a01 gpu_check.py:1-49 · blob c7336986dd385454124e24d7c01f4e21815d1b84 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
"""Bounded double-precision GPU screening of imported conservation polygons.
Independent CPU winding-angle witness; no restoration score or land judgement.
"""
import json,hashlib,time
from pathlib import Path
import numpy as np
import cupy as cp
from thermal import conductivity_to_resistivity
ROOT=Path(__file__).parent;OUT=ROOT/'.local'/'gpu';OUT.mkdir(parents=True,exist_ok=True)
kernel=cp.RawKernel(r'''extern "C" __global__ void ring(const double* p,int n,const double* r,int m,unsigned char* result){int i=blockDim.x*blockIdx.x+threadIdx.x;if(i>=n)return;double x=p[2*i],y=p[2*i+1];bool in=false;for(int k=0,j=m-1;k<m;j=k++){double ax=r[2*j],ay=r[2*j+1],bx=r[2*k],by=r[2*k+1];double cr=(bx-ax)*(y-ay)-(by-ay)*(x-ax);if(fabs(cr)<1e-12&&x>=fmin(ax,bx)-1e-12&&x<=fmax(ax,bx)+1e-12 … [line shortened here: 567 characters; full line on GitHub]
def classify(points,ring):
r=np.asarray(ring,dtype=np.float64)[:,:2]
if np.array_equal(r[0],r[-1]):r=r[:-1]
if len(r)<3 or not np.isfinite(r).all():raise ValueError('Invalid ring')
gp=cp.asarray(points);gr=cp.asarray(r);out=cp.empty(len(points),cp.uint8)
kernel(((len(points)+255)//256,),(256,),(gp,np.int32(len(points)),gr,np.int32(len(r)),out))
angles=np.zeros(len(points));boundary=np.zeros(len(points),bool)
for a,b in zip(r,np.roll(r,-1,axis=0)):
u=a-points;v=b-points;angles+=np.arctan2(u[:,0]*v[:,1]-u[:,1]*v[:,0],np.sum(u*v,axis=1))
cross=(b[0]-a[0])*(points[:,1]-a[1])-(b[1]-a[1])*(points[:,0]-a[0])
boundary|=(np.abs(cross)<1e-12)&np.all(points>=np.minimum(a,b)-1e-12,axis=1)&np.all(points<=np.maximum(a,b)+1e-12,axis=1)
witness=np.where(boundary,2,(np.abs(angles)>np.pi).astype(np.uint8))
actual=cp.asnumpy(out);assert np.array_equal(actual,witness),int(np.sum(actual!=witness))
return actual
def polygon(points,rings):
inside=np.zeros(len(points),bool);boundary=np.zeros(len(points),bool)
for ring in rings:
c=classify(points,ring);inside^=c==1;boundary|=c==2
return np.where(boundary,2,inside.astype(np.uint8))
started=time.perf_counter()
fixture=polygon(np.array([[.5,.5],[2,2],[0,1],[5,5]],dtype=float),[[[0,0],[4,0],[4,4],[0,4],[0,0]],[[1,1],[3,1],[3,3],[1,3],[1,1]]])
assert fixture.tolist()==[1,0,2,0]
path=ROOT/'.local'/'environment'/'sssi.geojson';raw=path.read_bytes();geo=json.loads(raw)
provenance=json.loads((path.parent/'provenance.json').read_text());west,south,east,north=provenance['bbox_wgs84']
x=np.linspace(west,east,256);y=np.linspace(south,north,256);xx,yy=np.meshgrid(x,y);points=np.c_[xx.ravel(),yy.ravel()]
records=[];masks=[]
for f in geo['features']:
geom=f['geometry'];polys=[geom['coordinates']] if geom['type']=='Polygon' else geom['coordinates'] if geom['type']=='MultiPolygon' else None
if polys is None:raise ValueError('Unsupported geometry')
interior=np.zeros(len(points),bool);boundary=np.zeros(len(points),bool)
for poly in polys:
c=polygon(points,poly);interior|=c==1;boundary|=c==2
mask=np.where(boundary,2,interior.astype(np.uint8));masks.append(mask)
records.append({'feature_id':f.get('id'),'inside_points':int(np.sum(mask==1)),'boundary_points':int(np.sum(mask==2)),'polygons':len(polys)})
k=[.25,.5,1,2,4];gpu_rho=cp.asnumpy(1/cp.asarray(k,dtype=cp.float64));assert np.array_equal(gpu_rho,np.array(conductivity_to_resistivity(k)))
cp.cuda.Stream.null.synchronize()
result={'device':cp.cuda.runtime.getDeviceProperties(0)['name'].decode(),'source_sha256':hashlib.sha256(raw).hexdigest(),'bbox_wgs84':provenance['bbox_wgs84'],'points_per_feature':len(points),'feature_point_checks':len(points)*len(records),'features':records,'gpu_cpu_disagreements':0,'thermal_reciprocal_fixture':'5 synthetic unit checks only; not site thermal measurements','elapsed_s':time.perf_co … [line shortened here: 575 characters; full line on GitHub]
np.savez_compressed(OUT/'environment-mask.npz',longitude=x,latitude=y,classifications=np.array(masks))
(OUT/'checks.json').write_text(json.dumps(result,indent=2));print(json.dumps(result))Import Environment
A Python command-line tool in Soil that fetches environment sources, service, count and sssi, using EPSG:4326 and SHA-256 from arcgis.com. It is built from the fetch step (`fetch`).
storagesoil / import_environment.py · lines 1–112 of 112 · Entry point
- What it does
- It fetches environment sources, service, count and sssi. Defines main, fetch. Uses libraries argparse, hashlib, json, math, datetime. Side effects: reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (repository name word 'soil'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. README: "`import_environment.py`: bounded Natural England SSSI polygon import for conservation context."
- Inputs & outputs
- In: data source: arcgis.com; JSON file environment_sources.json; JSON file service.json; JSON file item.json; JSON file layer.json; JSON file count.json; GeoJSON file sssi.geojson; command-line arguments. Out: JSON file provenance.json. Coordinate systems named: WGS84 / EPSG:4326.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- Download a bounded, provenance-preserving Natural England SSSI polygon sample. It accepts `--bbox` and `--output`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- soil · / · Python CLI
- Uses
- argparse, hashlib, json, math, datetime, pathlib, urllib.parse, urllib.request
- Used by
- none found
- Produces
- main
- Defines here
- main, fetch
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- soil@d26288ed03df533507739b9f218358fc7aa36a01 import_environment.py:1-112 · blob ed5c83483307af8218ab3cdbdd7ed870da5442ba · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: supporting_data
"""Download a bounded, provenance-preserving Natural England SSSI polygon sample.
Standard library only. Coordinates are actual source polygon vertices reprojected
by ArcGIS to WGS84 longitude/latitude; no bounding-box geometry is fabricated.
"""
import argparse
import hashlib
import json
import math
from datetime import datetime, timezone
from pathlib import Path
from urllib.parse import urlencode
from urllib.request import Request, urlopen
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--bbox', nargs=4, type=float, metavar=('WEST', 'SOUTH', 'EAST', 'NORTH'))
parser.add_argument('--output', type=Path, default=Path('.local/environment'))
args = parser.parse_args()
config = json.loads(Path(__file__).with_name('environment_sources.json').read_text())
bbox = args.bbox or config['default_bbox_wgs84']
west, south, east, north = bbox
if not (all(math.isfinite(v) for v in bbox) and -180 <= west < east <= 180
and -90 <= south < north <= 90 and east-west <= .25 and north-south <= .25):
parser.error('bbox must be ordered WGS84 coordinates, at most 0.25 degrees on either axis')
output = args.output
output.mkdir(parents=True, exist_ok=True)
downloaded = 0
records = []
def fetch(url, filename, params=None):
nonlocal downloaded
if params:
url += '?' + urlencode(params)
remaining = config['maximum_total_download_bytes'] - downloaded
if remaining <= 0:
raise RuntimeError('10 MiB aggregate download cap reached')
with urlopen(Request(url, headers={'User-Agent': 'soil-public-environment-import/1.0'}), timeout=45) as response:
raw = response.read(remaining + 1)
if len(raw) > remaining:
raise RuntimeError('Response exceeds aggregate 10 MiB download cap; narrow the bbox')
downloaded += len(raw)
data = json.loads(raw)
if 'error' in data:
raise RuntimeError(f'ArcGIS error: {data["error"]}')
(output / filename).write_bytes(raw)
records.append({'url': url, 'file': filename, 'bytes': len(raw),
'sha256': hashlib.sha256(raw).hexdigest(),
'retrieved_at_utc': datetime.now(timezone.utc).isoformat()})
return data
service = fetch(config['service_url'], 'service.json', {'f': 'json'})
if service.get('serviceItemId') != config['item_id']:
raise RuntimeError('Service item changed; source ownership/licence requires review')
item = fetch('https://www.arcgis.com/sharing/rest/content/items/' + config['item_id'],
'item.json', {'f': 'json'})
licence_text = item.get('licenseInfo', '')
if not ('open government licence' in licence_text.lower()
or 'open-government-licence' in licence_text.lower()):
raise RuntimeError('Source item does not confirm Open Government Licence; inspect item.json')
layer_url = config['service_url'] + '/' + str(config['layer_id'])
layer = fetch(layer_url, 'layer.json', {'f': 'json'})
if layer.get('geometryType') != 'esriGeometryPolygon':
raise RuntimeError('Expected polygon source layer')
params = {'where': '1=1', 'geometry': ','.join(map(str, bbox)),
'geometryType': 'esriGeometryEnvelope', 'inSR': 4326,
'spatialRel': 'esriSpatialRelIntersects'}
count = fetch(layer_url + '/query', 'count.json',
dict(params, f='json', returnCountOnly='true'))['count']
features = fetch(layer_url + '/query', 'sssi.geojson',
dict(params, f='geojson', outFields='*', outSR=4326,
returnGeometry='true', resultRecordCount=config['maximum_features'],
orderByFields=layer['objectIdField']))
if features.get('type') != 'FeatureCollection':
raise RuntimeError('Expected GeoJSON FeatureCollection')
rows = features['features']
if len(rows) > config['maximum_features']:
raise RuntimeError('Server ignored feature limit')
for row in rows:
geometry = row.get('geometry') or {}
if geometry.get('type') not in ('Polygon', 'MultiPolygon') or not geometry.get('coordinates'):
raise RuntimeError('Null or nonpolygon geometry returned')
exceeded = bool(features.get('exceededTransferLimit') or
features.get('properties', {}).get('exceededTransferLimit'))
complete = not exceeded and len(rows) == count
provenance = {
'schema_version': 1, 'dataset': config['dataset'], 'publisher': config['publisher'],
'source': config, 'source_item_owner': item.get('owner'),
'licence_as_recorded': licence_text,
'copyright_as_recorded': layer.get('copyrightText') or service.get('copyrightText'),
'bbox_wgs84': bbox, 'selection': 'full source geometries intersecting bbox; not clipped',
'input_crs_as_recorded': layer.get('extent', {}).get('spatialReference'),
'output_crs': 'EPSG:4326', 'coordinate_order': ['longitude', 'latitude'],
'coordinate_units': 'degrees', 'attribute_units': 'as recorded in source field metadata; not inferred',
'fields_as_recorded': layer.get('fields', []),
'source_editing_info_as_recorded': layer.get('editingInfo'),
'query_count': count, 'feature_count': len(rows),
'exceeded_transfer_limit': exceeded, 'complete_for_bbox_query': complete,
'completeness_note': 'Count and feature requests are separate snapshots; no dataset-wide completeness claim.',
'geometry': 'Actual source Polygon/MultiPolygon vertices; server reprojection to WGS84; no simplification requested.',
'files': records, 'downloaded_bytes': downloaded,
'limitations': config['scope']}
(output / 'provenance.json').write_text(json.dumps(provenance, indent=2) + '\n', encoding='utf-8')
print(json.dumps({'output': str(output), 'features': len(rows), 'query_count': count,
'complete_for_bbox_query': complete, 'downloaded_bytes': downloaded}))
if not complete:
raise SystemExit('Partial result retained with provenance; narrow bbox before using for screening')
if __name__ == '__main__':
main()Import Soil
A Python command-line tool that fetches soil sources, catalogue and provenance, using SHA-256.
storagesoil / import_soil.py · lines 1–42 of 42 · Entry point
- What it does
- It fetches soil sources, catalogue and provenance. Defines main. Uses libraries argparse, datetime, hashlib, json, pathlib. Side effects: reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'soil'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. README: "`import_soil.py`: bounded UKCEH metadata import."
- Inputs & outputs
- In: JSON file soil_sources.json; command-line arguments. Out: JSON file catalogue.json; JSON file provenance.json.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- Bounded UKCEH metadata import; measurements remain explicitly pending. It accepts `--output` and `--offline`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- soil · / · Python CLI
- Uses
- argparse, datetime, hashlib, json, pathlib, urllib.request
- Used by
- none found
- Produces
- main
- Defines here
- main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- soil@d26288ed03df533507739b9f218358fc7aa36a01 import_soil.py:1-42 · blob bdc1924a3c4e3756a41ffc03d31a0dd43697bcff · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: supporting_data
"""Bounded UKCEH metadata import; measurements remain explicitly pending.
Default output: .local/soil/provenance.json and catalogue.json.
No third-party dependencies. No fabricated geometry or thermal resistivity.
"""
import argparse
import datetime
import hashlib
import json
from pathlib import Path
import urllib.request
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output', type=Path, default=Path(__file__).parent / '.local/soil')
parser.add_argument('--offline', action='store_true', help='Record verified source manifest without a network request')
args = parser.parse_args()
source = json.loads(Path(__file__).with_name('soil_sources.json').read_text(encoding='utf-8'))
args.output.mkdir(parents=True, exist_ok=True)
result = {'source': source, 'retrieved_at_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(),
'status': 'blocked_measurements_not_downloaded', 'numeric_output': None, 'row_count': 0}
if not args.offline:
url = source['catalogue_url'] + '?format=json'
# Bound the read and reject truncation; the metadata is normally about 10 KB.
with urllib.request.urlopen(url, timeout=30) as response:
raw = response.read(262144)
if len(raw) == 262144:
raise RuntimeError('Metadata reaches 256 KiB cap; refusing a potentially truncated record')
metadata = json.loads(raw)
if metadata.get('id') != '8c87a397-a010-48a4-8ca5-0f3742c2d857':
raise RuntimeError('Unexpected UKCEH record')
(args.output / 'catalogue.json').write_bytes(raw)
result['metadata'] = {'url': url, 'bytes': len(raw), 'sha256': hashlib.sha256(raw).hexdigest()}
else:
result['status'] = 'offline_manifest_only_measurements_pending'
(args.output / 'provenance.json').write_text(json.dumps(result, indent=2) + '\n', encoding='utf-8')
print(json.dumps({'status': result['status'], 'output': str(args.output), 'numeric_output': None}))
if __name__ == '__main__':
main()Test Thermal
A test in Soil that checks Thermal. It is built from the thermal tests class (`ThermalTests`).
testsoil / test_thermal.py · lines 1–43 of 43 · Entry point
- What it does
- It tests its inputs. Defines ThermalTests, test_reciprocal_units_and_round_trip, test_reject_invalid_and_overflow, test_record_preserves_evidence_and_conditioning, test_reject_wrong_quantity_and_missing_provenance. Uses libraries math, unittest.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (repository name word 'soil'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
- Downstream impact
- It is itself an entry point (test); no other file was found loading it.
- What it achieves
- Unit and provenance checks; fixture values are arithmetic scenarios, not soils.
- Why it matters
- Guards the behaviour of Thermal.
- Application
- soil · / · test
- Uses
- Thermal (import), math, unittest
- Used by
- none found
- Produces
- ThermalTests
- Defines here
- ThermalTests, test_reciprocal_units_and_round_trip, test_reject_invalid_and_overflow, test_record_preserves_evidence_and_conditioning, test_reject_wrong_quantity_and_missing_provenance
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- soil@d26288ed03df533507739b9f218358fc7aa36a01 test_thermal.py:1-43 · blob cec39d047df29f33773312c741bddd1c1782ffb3 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unknown
"""Unit and provenance checks; fixture values are arithmetic scenarios, not soils."""
import math
import unittest
from thermal import conductivity_to_resistivity, convert_record
class ThermalTests(unittest.TestCase):
def test_reciprocal_units_and_round_trip(self):
values = [0.25, 0.5, 1.0, 2.0, 4.0]
self.assertEqual(conductivity_to_resistivity(values), [4.0, 2.0, 1.0, 0.5, 0.25])
self.assertEqual(conductivity_to_resistivity(conductivity_to_resistivity(values)), values)
def test_reject_invalid_and_overflow(self):
for value in [0, -1, math.inf, -math.inf, math.nan, None, True, "2", [2], 5e-324]:
with self.subTest(value=value), self.assertRaises(ValueError):
conductivity_to_resistivity([value])
def test_record_preserves_evidence_and_conditioning(self):
original = dict(conductivity=2, conductivity_unit="W/(m K)", status="scenario",
source="arithmetic fixture; not a site measurement",
conditions={"volumetric_water_content": None})
output = convert_record(original)
self.assertEqual(output["thermal_resistivity"], 0.5)
self.assertEqual(output["thermal_resistivity_unit"], "K m/W")
self.assertEqual(output["thermal_resistivity_evidence"], "derived_from_scenario")
self.assertFalse(output["ampacity_calculated"])
output["conditions"]["volumetric_water_content"] = 0.2
self.assertIsNone(original["conditions"]["volumetric_water_content"])
self.assertNotIn("thermal_resistivity", original)
def test_reject_wrong_quantity_and_missing_provenance(self):
valid = dict(conductivity=2, conductivity_unit="W/(m K)", status="measured", source="fixture")
for change in [dict(conductivity_unit="ohm m"), dict(conductivity_unit="m/s"),
dict(source=""), dict(status="approved"), dict(status="modelled")]:
with self.subTest(change=change), self.assertRaises(ValueError):
convert_record({**valid, **change})
self.assertEqual(convert_record({**valid, "status": "modelled", "model": "fixture-v1"})
["thermal_resistivity_evidence"], "derived_from_modelled")
if __name__ == "__main__":
unittest.main()Thermal
A Python module in Soil that works with cables. It converts record (`convert_record`) and is built from the conductivity to resistivity helper (`conductivity_to_resistivity`).
transformsoil / thermal.py · lines 1–70 of 70
- What it does
- It calculates cables. Defines _positive_finite, conductivity_to_resistivity, convert_record. Uses libraries copy, math, numbers.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (repository name word 'soil'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: cables.
- Downstream impact
- Used directly by 2 files: GPU Check (soil); Test Thermal (soil).
- What it achieves
- Scalar/isotropic soil thermal-property conversion; no cable ampacity model.
- Why it matters
- Imported by GPU Check. Checked by Test Thermal.
- Application
- soil · / · Python module
- Uses
- copy, math, numbers
- Used by
- imported by GPU Check (import), imported by Test Thermal (import)
- Produces
- conductivity_to_resistivity, convert_record
- Defines here
- _positive_finite, conductivity_to_resistivity, convert_record
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- soil@d26288ed03df533507739b9f218358fc7aa36a01 thermal.py:1-70 · blob 34fbeed4aebc3430b5c880a1c15b2744c1971169 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unknown
"""Scalar/isotropic soil thermal-property conversion; no cable ampacity model.
All numerical inputs to conductivity_to_resistivity are W/(m K). Outputs are
K m/W. Unknown/missing values must be retained separately, never changed to zero.
No site thermal property is inferred from soil texture or other covariates.
"""
from copy import deepcopy
import math
from numbers import Real
CONDUCTIVITY_UNIT = "W/(m K)"
RESISTIVITY_UNIT = "K m/W"
STATUSES = frozenset(("measured", "modelled", "scenario"))
def _positive_finite(value, name):
if isinstance(value, bool) or not isinstance(value, Real):
raise ValueError(f"{name} must be a finite positive number")
value = float(value)
if not math.isfinite(value) or value <= 0:
raise ValueError(f"{name} must be a finite positive number")
return value
def conductivity_to_resistivity(values):
"""Return a list of reciprocals for a 1-D iterable of positive conductivities.
This checks the arithmetic only. Use convert_record to retain property status,
source and conditioning information. A tensor requires a matrix inverse and
is outside this scalar API. Reject reciprocal overflow instead of emitting inf.
"""
result = []
for index, raw in enumerate(values):
conductivity = _positive_finite(raw, f"conductivity[{index}]")
resistivity = 1.0 / conductivity
if not math.isfinite(resistivity) or resistivity <= 0:
raise ValueError(f"conductivity[{index}] has an unrepresentable reciprocal")
result.append(resistivity)
return result
def convert_record(record):
"""Copy a sourced conductivity record and add derived thermal resistivity.
A 'measured' input remains measured-source evidence; its reciprocal is marked
derived, rather than represented as an independently measured resistivity.
Unknown conditioning fields can be null; they cannot imply suitability for
a particular cable burial depth, moisture state or temperature.
"""
if not isinstance(record, dict):
raise ValueError("record must be an object")
if record.get("conductivity_unit") != CONDUCTIVITY_UNIT:
raise ValueError(f"conductivity_unit must be {CONDUCTIVITY_UNIT}")
if record.get("status") not in STATUSES:
raise ValueError("status must be measured, modelled or scenario")
source = record.get("source")
if not isinstance(source, str) or not source.strip():
raise ValueError("a nonempty source citation or scenario identifier is required")
if record["status"] == "modelled":
model = record.get("model")
if not isinstance(model, str) or not model.strip():
raise ValueError("modelled conductivity requires a model identifier/version")
value = conductivity_to_resistivity([record.get("conductivity")])[0]
output = deepcopy(record)
output.update(thermal_resistivity=value, thermal_resistivity_unit=RESISTIVITY_UNIT,
thermal_resistivity_derivation="1 / conductivity",
thermal_resistivity_evidence="derived_from_" + record["status"],
ampacity_calculated=False)
return outputEstate Survey
A JavaScript module in the tools folder of Spiders that uses SHA-256 using data from GitHub API. It parses JSON (`parseJson`), validates registry (`validateRegistry`) and fetches JSON (`fetchJson`).
storagespiders / tools/estate-survey.mjs · lines 1–384 of 503 · Entry point · pattern validateRegistry (shared by 2 files)
- What it does
- It fetches data. Defines 17 functions or classes, including valueAfter, portable, sha256, byteCompare, shardFor. Uses libraries node:crypto, node:fs, node:path. Side effects: reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'spiders'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: data source: GitHub API; command-line arguments.
- Downstream impact
- Used directly by 1 file: Estate Survey Workflow (spiders).
- What it achieves
- Defines `valueAfter`, `portable`, `sha256` and 13 more.
- Why it matters
- Run by Estate Survey Workflow.
- Application
- spiders · tools · JavaScript module
- Uses
- node:crypto, node:fs, node:path
- Used by
- run by Estate Survey Workflow (workflow run)
- Produces
- valueAfter, portable, sha256, byteCompare, shardFor, stableWrite, parseJson, validateRegistry, localReceipt, fetchJson, fixtureReader, liveReader
- Defines here
- valueAfter, portable, sha256, byteCompare, shardFor, stableWrite, parseJson, validateRegistry, localReceipt, fetchJson, fixtureReader, liveReader, normaliseObservation, surveyShard, findingRows, aggregate
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- spiders@78fc0f90bd5ca73f3d5d7c0e0b7b5712cfe781e5 tools/estate-survey.mjs:1-384 · blob dfc85148e8c313cb2132af4c2580b4df93de59bd · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem, network · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
#!/usr/bin/env node
import { createHash } from 'node:crypto';
import {
mkdirSync,
readFileSync,
renameSync,
writeFileSync,
} from 'node:fs';
import { dirname, relative, resolve } from 'node:path';
const REGISTRY_SCHEMA = 'spiders.estate-survey-registry.v1';
const LOCAL_SCHEMA = 'spiders.estate-survey-local.v1';
const SHARD_SCHEMA = 'spiders.estate-survey-shard.v1';
const AGGREGATE_SCHEMA = 'spiders.estate-survey-aggregate.v1';
const REQUIRED_CHECKS = [
'repository-metadata',
'default-branch-head',
'workflow-inventory',
];
const MAX_REPOSITORIES = 64;
const REQUEST_TIMEOUT_MS = 20_000;
const args = process.argv.slice(2);
const mode = args.shift();
const valueAfter = flag => {
const index = args.indexOf(flag);
return index < 0 ? null : args[index + 1];
};
const portable = path => relative(process.cwd(), resolve(path)).replaceAll('\\', '/');
const sha256 = bytes => createHash('sha256').update(bytes).digest('hex');
const byteCompare = (left, right) => Buffer.compare(Buffer.from(left), Buffer.from(right));
const shardFor = (owner, name, count) =>
Number.parseInt(sha256(`${owner}/${name}`).slice(0, 8), 16) % count;
function stableWrite(path, value) {
const output = resolve(path);
mkdirSync(dirname(output), { recursive: true });
const temporary = `${output}.tmp-${process.pid}`;
writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
renameSync(temporary, output);
}
function parseJson(path, label) {
const bytes = readFileSync(path);
try {
return { bytes, value: JSON.parse(bytes.toString('utf8')) };
} catch (error) {
throw new Error(`${label} JSON does not parse: ${error.message}`);
}
}
function validateRegistry(path) {
const errors = [];
let parsed;
try {
parsed = parseJson(path, 'registry');
} catch (error) {
return { errors: [error.message], bytes: Buffer.alloc(0), registry: {} };
}
const registry = parsed.value;
if (parsed.bytes.length > 128 * 1024) errors.push('registry exceeds 128 KiB bound');
if (registry.schema !== REGISTRY_SCHEMA) errors.push('unknown registry schema');
if (!/^[A-Za-z0-9-]+$/.test(registry.owner || '')) errors.push('invalid registry owner');
if (registry.scope !== 'public-owner-repositories') errors.push('registry scope must be public-owner-repositories');
if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(registry.captured_utc || '')) {
errors.push('captured_utc must be an ISO-8601 UTC second');
}
if (registry.capture_method !== 'git ls-remote --symref <repository> HEAD') {
errors.push('capture_method is not the bounded registry capture command');
}
if (registry.shard_count !== 4) errors.push('shard_count must be exactly 4');
if (!Number.isInteger(registry.repository_count)
|| registry.repository_count < 1
|| registry.repository_count > MAX_REPOSITORIES) {
errors.push(`repository_count must be between 1 and ${MAX_REPOSITORIES}`);
}
if (JSON.stringify(registry.checks) !== JSON.stringify(REQUIRED_CHECKS)) {
errors.push(`checks must be exactly ${REQUIRED_CHECKS.join(', ')}`);
}
const repositories = Array.isArray(registry.repositories) ? registry.repositories : [];
if (!Array.isArray(registry.repositories)) errors.push('repositories must be an array');
if (repositories.length !== registry.repository_count) {
errors.push(`repository_count ${registry.repository_count} does not match ${repositories.length} entries`);
}
const names = new Set();
for (const [index, repository] of repositories.entries()) {
const prefix = `repositories[${index}]`;
const keys = repository && typeof repository === 'object'
? Object.keys(repository).sort().join(',') : '';
if (keys !== 'default_branch,head_sha,name') errors.push(`${prefix} has an unexpected shape`);
if (!/^[A-Za-z0-9._-]+$/.test(repository?.name || '')) errors.push(`${prefix} has an invalid name`);
if (!/^[A-Za-z0-9._/-]+$/.test(repository?.default_branch || '')) errors.push(`${prefix} has an invalid default branch`);
if (!/^[0-9a-f]{40}$/.test(repository?.head_sha || '')) errors.push(`${prefix} has an invalid head SHA`);
const folded = String(repository?.name || '').toLowerCase();
if (names.has(folded)) errors.push(`${prefix} duplicates repository ${repository?.name}`);
names.add(folded);
}
const sorted = [...repositories].sort((a, b) => byteCompare(a.name, b.name));
if (repositories.some((repository, index) => repository.name !== sorted[index]?.name)) {
errors.push('repositories must be sorted by UTF-8 name bytes');
}
const counts = Array.from({ length: registry.shard_count || 0 }, () => 0);
for (const repository of repositories) {
if (counts.length) counts[shardFor(registry.owner, repository.name, counts.length)] += 1;
}
if (counts.some(count => count < 1 || count > 12)) {
errors.push(`shard allocation is outside 1..12 repositories: ${counts.join(',')}`);
}
return { errors, bytes: parsed.bytes, registry, shardCounts: counts };
}
function localReceipt(path) {
const checked = validateRegistry(path);
const receipt = {
schema: LOCAL_SCHEMA,
registry: portable(path),
registry_sha256: sha256(checked.bytes),
owner: checked.registry.owner ?? null,
repository_count: checked.registry.repository_count ?? null,
shard_count: checked.registry.shard_count ?? null,
shard_repository_counts: checked.shardCounts || [],
checks: checked.registry.checks || [],
expectations: (checked.registry.repositories || []).map(repository => ({
name: repository.name,
default_branch: repository.default_branch,
head_sha: repository.head_sha,
shard: shardFor(checked.registry.owner, repository.name, checked.registry.shard_count),
})),
integrity_errors: checked.errors,
status: checked.errors.length ? 'fail' : 'pass',
};
return { receipt, registry: checked.registry };
}
async function fetchJson(url, token) {
const headers = {
Accept: 'application/vnd.github+json',
'User-Agent': 'spiders-bounded-estate-survey',
'X-GitHub-Api-Version': '2022-11-28',
};
if (token) headers.Authorization = `Bearer ${token}`;
let response;
try {
response = await fetch(url, { headers, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
} catch (error) {
throw new Error(`transport failure for ${url}: ${error.name}: ${error.message}`);
}
let body;
try {
body = await response.json();
} catch (error) {
throw new Error(`non-JSON response ${response.status} for ${url}: ${error.message}`);
}
if (response.status === 404) return { notFound: true, body };
if (!response.ok) {
throw new Error(`GitHub API ${response.status} for ${url}: ${body?.message || 'unknown response'}`);
}
return { notFound: false, body };
}
function fixtureReader(path) {
if (!path) return null;
const fixture = parseJson(path, 'fixture').value;
if (fixture.schema !== 'spiders.estate-survey-fixture.v1'
|| !fixture.repositories
|| typeof fixture.repositories !== 'object') {
throw new Error('fixture has unknown schema or no repository map');
}
return async name => {
if (!(name in fixture.repositories)) throw new Error(`fixture lacks repository ${name}`);
return fixture.repositories[name];
};
}
async function liveReader(owner, token, repository) {
const base = `https://api.github.com/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repository.name)}`;
const metadata = await fetchJson(base, token);
if (metadata.notFound) return { not_found: true };
if (typeof metadata.body?.default_branch !== 'string') {
throw new Error(`${repository.name} metadata lacks a default branch`);
}
const branch = encodeURIComponent(metadata.body.default_branch);
const commit = await fetchJson(`${base}/commits/${branch}`, token);
const workflowFiles = await fetchJson(`${base}/contents/.github/workflows?ref=${branch}`, token);
if (commit.notFound) throw new Error(`${repository.name} default branch returned 404`);
return {
metadata: metadata.body,
commit: commit.body,
workflow_files: workflowFiles.notFound ? [] : workflowFiles.body,
};
}
function normaliseObservation(repository, raw) {
const expected = {
default_branch: repository.default_branch,
head_sha: repository.head_sha,
};
if (raw?.not_found === true) {
return {
name: repository.name,
availability: 'not-found',
expected,
observed: null,
findings: ['repository-not-found'],
};
}
const metadata = raw?.metadata;
const commit = raw?.commit;
const workflowFiles = raw?.workflow_files;
if (!metadata || typeof metadata !== 'object') throw new Error(`${repository.name} metadata is missing`);
if (!commit || !/^[0-9a-f]{40}$/.test(commit.sha || '')) throw new Error(`${repository.name} commit response lacks a full SHA`);
if (!Array.isArray(workflowFiles)
|| workflowFiles.some(file => !file || typeof file.name !== 'string'
|| typeof file.type !== 'string' || !/^[0-9a-f]{40}$/.test(file.sha || '')
|| !Number.isInteger(file.size))) {
throw new Error(`${repository.name} workflow inventory is malformed`);
}
if (typeof metadata.default_branch !== 'string'
|| typeof metadata.private !== 'boolean'
|| typeof metadata.archived !== 'boolean'
|| typeof metadata.disabled !== 'boolean'
|| typeof metadata.fork !== 'boolean'
|| typeof metadata.has_pages !== 'boolean') {
throw new Error(`${repository.name} metadata response is malformed`);
}
const workflows = workflowFiles
.filter(file => file.type === 'file' && /\.ya?ml$/i.test(file.name))
.map(file => ({ name: file.name, sha: file.sha, size: file.size }))
.sort((left, right) => byteCompare(left.name, right.name));
const observed = {
default_branch: metadata.default_branch,
head_sha: commit.sha,
private: metadata.private,
archived: metadata.archived,
disabled: metadata.disabled,
fork: metadata.fork,
has_pages: metadata.has_pages,
workflow_files_total: workflows.length,
workflow_files: workflows,
};
const findings = [];
if (observed.private) findings.push('visibility-became-private');
if (observed.default_branch !== expected.default_branch) findings.push('default-branch-drift');
if (observed.head_sha !== expected.head_sha) findings.push('head-drift');
if (observed.archived) findings.push('repository-archived');
if (observed.disabled) findings.push('repository-disabled');
return { name: repository.name, availability: 'observed', expected, observed, findings };
}
async function surveyShard(registryPath, shardIndex, fixturePath) {
const local = localReceipt(registryPath);
if (local.receipt.status !== 'pass') {
return {
schema: SHARD_SCHEMA,
registry_sha256: local.receipt.registry_sha256,
shard_index: shardIndex,
shard_count: local.receipt.shard_count,
assigned_count: 0,
observations: [],
machinery_errors: local.receipt.integrity_errors,
status: 'fail',
};
}
if (!Number.isInteger(shardIndex) || shardIndex < 0 || shardIndex >= local.registry.shard_count) {
throw new Error(`shard must be an integer from 0 to ${local.registry.shard_count - 1}`);
}
const assigned = local.registry.repositories.filter(repository =>
shardFor(local.registry.owner, repository.name, local.registry.shard_count) === shardIndex);
const fixture = fixtureReader(fixturePath);
const observations = [];
const machinery = [];
for (const repository of assigned) {
try {
const raw = fixture
? await fixture(repository.name)
: await liveReader(local.registry.owner, process.env.GITHUB_TOKEN || '', repository);
observations.push(normaliseObservation(repository, raw));
} catch (error) {
machinery.push(`${repository.name}: ${error.message}`);
observations.push({
name: repository.name,
availability: 'unmeasured',
expected: {
default_branch: repository.default_branch,
head_sha: repository.head_sha,
},
observed: null,
findings: [],
});
}
}
return {
schema: SHARD_SCHEMA,
registry_sha256: local.receipt.registry_sha256,
shard_index: shardIndex,
shard_count: local.registry.shard_count,
assigned_count: assigned.length,
observations,
findings_count: observations.reduce((sum, observation) => sum + observation.findings.length, 0),
machinery_errors: machinery.sort(byteCompare),
status: machinery.length ? 'fail' : 'pass',
};
}
function findingRows(observation) {
return observation.findings.map(kind => ({
repository: observation.name,
kind,
expected: observation.expected,
observed: observation.observed,
}));
}
function aggregate(registryPath, localPath, shardPaths) {
const errors = [];
const localParsed = parseJson(localPath, 'local receipt');
const local = localParsed.value;
const expectedLocal = localReceipt(registryPath).receipt;
if (expectedLocal.status !== 'pass') {
errors.push(...expectedLocal.integrity_errors.map(error => `checked-in registry: ${error}`));
}
if (JSON.stringify(local) !== JSON.stringify(expectedLocal)) {
errors.push('local receipt differs from the checked-in registry receipt');
}
if (local.schema !== LOCAL_SCHEMA || local.status !== 'pass') errors.push('local registry receipt is not a passing receipt');
if (!/^[0-9a-f]{64}$/.test(local.registry_sha256 || '')) errors.push('local receipt lacks a registry digest');
if (!/^[A-Za-z0-9-]+$/.test(local.owner || '')) errors.push('local receipt lacks a valid owner');
if (!Array.isArray(local.expectations) || local.expectations.length !== local.repository_count) {
errors.push('local receipt expectation count is inconsistent');
}
if (shardPaths.length !== local.shard_count) errors.push(`expected ${local.shard_count} shard paths, received ${shardPaths.length}`);
const shardInputs = [];
const observations = [];
const seenShards = new Set();
const expectations = new Map((local.expectations || []).map(expectation => [expectation.name, expectation]));
for (const path of shardPaths) {
try {
const parsed = parseJson(path, 'shard receipt');
const shard = parsed.value;
shardInputs.push({ shard_index: shard.shard_index, sha256: sha256(parsed.bytes) });
if (shard.schema !== SHARD_SCHEMA) errors.push(`${portable(path)} has an unknown shard schema`);
if (shard.registry_sha256 !== local.registry_sha256) errors.push(`${portable(path)} registry digest differs from local receipt`);
if (shard.shard_count !== local.shard_count) errors.push(`${portable(path)} shard count differs from local receipt`);
if (!Number.isInteger(shard.shard_index) || shard.shard_index < 0 || shard.shard_index >= local.shard_count) {
errors.push(`${portable(path)} has invalid shard index`);
} else if (seenShards.has(shard.shard_index)) {
errors.push(`duplicate shard ${shard.shard_index}`);
} else {
seenShards.add(shard.shard_index);
}
if (shard.status !== 'pass' || (shard.machinery_errors || []).length) {
errors.push(...(shard.machinery_errors || [`shard ${shard.shard_index} did not pass`]));
}
if (!Array.isArray(shard.observations) || shard.observations.length !== shard.assigned_count) {
errors.push(`shard ${shard.shard_index} observation count is inconsistent`);
} else {
const expectedCount = [...expectations.values()].filter(expectation =>
expectation.shard === shard.shard_index).length;
if (shard.assigned_count !== expectedCount) {
errors.push(`shard ${shard.shard_index} assigned count differs from local receipt`);
}
for (const observation of shard.observations) {
const expectation = expectations.get(observation?.name);
if (expectation && expectation.shard !== shard.shard_index) {
errors.push(`${observation.name} appeared in the wrong shard`);
}
}
observations.push(...shard.observations);
const findingsCount = shard.observations.reduce((sum, observation) =>
sum + (Array.isArray(observation?.findings) ? observation.findings.length : 0), 0);
if (shard.findings_count !== findingsCount) {
errors.push(`shard ${shard.shard_index} findings count is inconsistent`);
}
}
} catch (error) {
errors.push(`${portable(path)}: ${error.message}`);
}
}
for (let index = 0; index < local.shard_count; index += 1) {
if (!seenShards.has(index)) errors.push(`missing shard ${index}`);
}
observations.sort((a, b) => byteCompare(a.name, b.name));
const seenRepositories = new Set();
for (const observation of observations) {