In this section
- GridAtlas M5 Precision Evidence storage · neural-link-between-agents / FIXES/NL-016/gridatlas/tools/m5_precision_evidence.py lines 1–133
- 03 Test test · neural-link-between-agents / SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS/03-test.mjs lines 1–50
- 04 Replay transform · neural-link-between-agents / SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS/04-replay.mjs lines 1–79
- 05 Estimator transform · neural-link-between-agents / SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS/05-estimator.mjs lines 1–54
- 06 Reference transform · neural-link-between-agents / SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS/06-reference.mjs lines 1–46
- 07 Lifecycle ingest · neural-link-between-agents / SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS/07-lifecycle.mjs lines 1–34
- 08 Relative transform · neural-link-between-agents / SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS/08-relative.mjs lines 1–30
- 09 Arrow render · neural-link-between-agents / SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS/09-arrow.html lines 1–11
- 09 Browser render · neural-link-between-agents / SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS/09-browser.py lines 1–55
- 10 Camera transform · neural-link-between-agents / SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS/10-camera.mjs lines 1–73
- 11 Modes Arrival transform · neural-link-between-agents / SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS/11-modes-arrival.mjs lines 1–97
GridAtlas M5 Precision Evidence
A Python command-line tool in the tools folder of Neural Link Between Agents that reads the Renewable Energy Planning Database (REPD) register.
storageneural-link-between-agents / FIXES/NL-016/gridatlas/tools/m5_precision_evidence.py · lines 1–133 of 133 · Entry point · pattern decimals (shared by 2 files)
- What it does
- It loads the REPD register. Defines 7 functions or classes, including rpz, n, load, cands_at, join. Uses libraries csv, json, re, sys, unicodedata. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register.
- Inputs & outputs
- In: DuckDB queries; command-line arguments. Out: JSON file.
- 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 rpz step (`rpz`), the load step (`load`) and the cands at helper (`cands_at`). Evidence for the capacity-precision question of the M5 REPD record join (offline replica of `tools/lightning/src/11b-repd-records.js` `RpQ/RpZ/RpJ`, same rules as `/auto/gridatlas/scripts/m5_join_rate.py`). Its code works with 100 MW and 50 MW.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- neural-link-between-agents · FIXES/NL-016/gridatlas/tools · Python CLI
- Uses
- csv, json, re, sys, unicodedata, collections, duckdb
- Used by
- none found
- Produces
- rpz, n, load, cands_at, join, decimals, main
- Defines here
- rpz, n, load, cands_at, join, decimals, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 FIXES/NL-016/gridatlas/tools/m5_precision_evidence.py:1-133 · blob 7de1456a5db87ae818c0b69a1103c4adc0327420 · GitHub at these lines
- State
- achieves: comment · context: auto · stage: output · effects: filesystem, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer, ai_agent · canonical: supporting_data
"""Evidence for the capacity-precision question of the M5 REPD record join (offline replica of
tools/lightning/src/11b-repd-records.js RpQ/RpZ/RpJ, same rules as <workspace>/auto/gridatlas/scripts/m5_join_rate.py).
For every drawn-register row (globalgrid2050 dist/repd_master.json, 10,784 rows, no ref) it records which record
it joins in Q2 (202608290716) and in the October preview (202611132345, CSV precision), then:
1. classifies the rows that joined in Q2 but not in October (why the 80 are lost: ref no longer active, MW,
name, point or technology changed in REPD, or a new same-point twin made it ambiguous);
2. measures what Excel full precision would do: for each October join, the ref's capacity in the staged file
(Q3_CANONICAL_STAGED.csv, XLSX precision) versus the CSV value; any difference breaks the exact MW match;
3. reports the register's own capacity precision (decimal places), which decides which source precision can match.
Usage: python3 -I m5_precision_evidence.py <register.json> <q2.parquet> <oct.parquet> <staged_xlsx_precision.csv> <out.json> <oct_csv_precision.csv>
Excel effect is measured raw-against-raw (staged XLSX value vs the CSV-precision input value for the same ref), because the
compiler rescales biomass >100 MW and solar_roof >50 MW by /1000 before writing capacity_mw.
"""
import csv, json, re, sys, unicodedata
from collections import defaultdict, Counter
import duckdb
EPS = 1.000001e-6
def rpz(s):
s = '' if s is None else str(s)
s = re.sub(r'[\x80-\x9f]', lambda m: bytes([ord(m.group())]).decode('cp1252', errors='replace'), s)
return ' '.join(unicodedata.normalize('NFC', s).split())
def n(v):
try:
v = float(v)
except (TypeError, ValueError):
return 0.0
return v if v > 0 else 0.0
def load(parquet):
rows = duckdb.connect().execute(
f"SELECT repd_ref, name, capacity_mw, repd_technology, longitude, latitude, status FROM read_parquet('{parquet}')").fetchall()
grid = defaultdict(list)
for r in rows:
grid[(round(r[4], 4), round(r[5], 4))].append(r)
return rows, grid
def cands_at(grid, x, y):
out = {}
for dx in (-1e-4, 0, 1e-4):
for dy in (-1e-4, 0, 1e-4):
for r in grid.get((round(x + dx, 4), round(y + dy, 4)), []):
if abs(r[4] - x) <= EPS and abs(r[5] - y) <= EPS:
out[r[0]] = r
return list(out.values())
def join(grid, f):
x, y = f['geometry']['coordinates'][:2]
p = f['properties']
c = [r for r in cands_at(grid, x, y)
if rpz(r[1]) == rpz(p.get('name')) and abs(n(r[2]) - n(p.get('capacity'))) < 1e-6 and r[3] == p.get('raw_tech')]
return c
def decimals(v):
s = repr(float(v)) if v not in (None, '') else ''
return len(s.split('.')[1].rstrip('0')) if '.' in s else 0
def main(reg, q2p, octp, staged, out, csvp):
feats = json.load(open(reg, encoding='utf-8'))['features']
q2rows, q2 = load(q2p)
octrows, oc = load(octp)
octby = {r[0]: r for r in octrows}
xl = {}
with open(staged, encoding='utf-8-sig', newline='') as fh:
for row in csv.DictReader(fh):
ref = (row.get('Ref ID') or '').strip()
xl[ref] = (row.get('Installed Capacity (MWelec)') or '').strip()
cs = {}
with open(csvp, encoding='utf-8-sig', newline='') as fh:
for row in csv.DictReader(fh):
cs[(row.get('Ref ID') or '').strip()] = (row.get('Installed Capacity (MWelec)') or '').strip()
res = Counter(); lost = Counter(); lost_ex = defaultdict(list)
xl_break = 0; xl_ex = []; reg_dec = Counter()
for f in feats:
p = f['properties']
reg_dec[decimals(p.get('capacity') or 0)] += 1
a, b = join(q2, f), join(oc, f)
ka = 'one' if len(a) == 1 else ('none' if not a else 'multi')
kb = 'one' if len(b) == 1 else ('none' if not b else 'multi')
res[(ka, kb)] += 1
if ka == 'one' and kb != 'one':
ref = a[0][0]; o = octby.get(ref)
if kb == 'multi':
why = 'ambiguous in October (a second record now shares point, name, MW and technology)'
elif o is None:
why = 'ref not in the October snapshot (left the active statuses, outside bbox or withdrawn)'
else:
d = []
if abs(o[4] - a[0][4]) > EPS or abs(o[5] - a[0][5]) > EPS: d.append('point')
if rpz(o[1]) != rpz(a[0][1]): d.append('name')
if abs(n(o[2]) - n(a[0][2])) >= 1e-6: d.append('MW')
if o[3] != a[0][3]: d.append('technology')
why = 'October record changed: ' + ('+'.join(d) or 'other')
lost[why] += 1
if len(lost_ex[why]) < 6:
lost_ex[why].append({'ref': ref, 'register_name': p.get('name'), 'q2': [a[0][1], a[0][2], a[0][6]],
'oct': None if o is None else [o[1], o[2], o[6], round(o[4], 6), round(o[5], 6)]})
if kb == 'one':
ref = b[0][0]; v = xl.get(ref, ''); c0 = cs.get(ref, '')
if v != c0 and abs(n(v) - n(c0)) >= 1e-6:
xl_break += 1
if len(xl_ex) < 10:
xl_ex.append({'ref': ref, 'name': b[0][1], 'csv_mw': c0, 'parquet_mw': b[0][2], 'xlsx_mw': v, 'register_mw': p.get('capacity')})
q2_one = sum(v for (a, b), v in res.items() if a == 'one')
oct_one = sum(v for (a, b), v in res.items() if b == 'one')
rep = {
'register_rows': len(feats),
'joined_q2_202608290716': q2_one,
'joined_oct_csv_precision_202611132345': oct_one,
'transition_q2_to_oct': {f'{a}->{b}': v for (a, b), v in sorted(res.items())},
'lost_q2_to_oct_by_reason': dict(lost.most_common()),
'lost_examples': lost_ex,
'oct_joins_broken_by_xlsx_precision': xl_break,
'oct_joined_with_xlsx_precision_upper_bound': oct_one - xl_break,
'xlsx_break_examples': xl_ex,
'register_capacity_decimal_places': dict(sorted(reg_dec.items())),
}
json.dump(rep, open(out, 'w'), indent=1, ensure_ascii=False)
print(json.dumps({k: v for k, v in rep.items() if not k.endswith('examples')}, indent=1))
if __name__ == '__main__':
main(*sys.argv[1:7])03 Test
A JavaScript module in Neural Link Between Agents that formats degrees (`formatDegrees`) and calculates planar distances and angles.
testneural-link-between-agents / SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS/03-test.mjs · lines 1–50 of 50 · Not reached from any entry point (candidate for review) · pattern deviceHeading (shared by 2 files)
- What it does
- It tests its inputs. Defines normalise, formatDegrees, deviceHeading. Uses libraries node:assert/strict.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
- What it achieves
- It formats degrees (`formatDegrees`) and is built from the normalise step (`normalise`) and the device heading helper (`deviceHeading`). Frozen source extract from blob.
- Why it matters
- No other file in the estate was found to import it.
- Application
- neural-link-between-agents · SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS · JavaScript module
- Uses
- node:assert/strict
- Used by
- none found
- Produces
- normalise, formatDegrees, deviceHeading
- Defines here
- normalise, formatDegrees, deviceHeading
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS/03-test.mjs:1-50 · blob 60d5c064c5a9c38d3daff1359b84c923df844abc · GitHub at these lines
- State
- achieves: comment · context: auto · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner, ai_agent · canonical: unreached_review
import assert from 'node:assert/strict';
// Frozen source extract from blob 4a72e94ee1fa07dc69650adafa25b6e3f9eddf2e
const radians = Math.PI / 180;
const normalise = degrees => (degrees % 360 + 360) % 360;
function formatDegrees(degrees) {
return String(Math.round(normalise(degrees)) % 360).padStart(3, '0') + '°';
}
// Project the screen's top edge onto the horizontal plane using the W3C
// intrinsic Z-X'-Y'' rotation. A vertical top edge has no horizontal heading.
function deviceHeading(event, screenAngle = 0) {
if (!Number.isFinite(screenAngle)) return null;
const beta = (Number.isFinite(event.beta) ? event.beta : 0) * radians;
const gamma = (Number.isFinite(event.gamma) ? event.gamma : 0) * radians;
const angle = screenAngle * radians;
const east = Math.cos(gamma) * Math.sin(angle);
const north = Math.sin(beta) * Math.sin(gamma) * Math.sin(angle) + Math.cos(beta) * Math.cos(angle);
if (Math.hypot(east, north) < 0.15) return null;
const screenOffset = Math.atan2(east, north) / radians;
if (typeof event.webkitCompassHeading === 'number') {
const heading = event.webkitCompassHeading;
const accuracy = event.webkitCompassAccuracy;
if (!Number.isFinite(heading) || heading < 0 || heading > 360) return null;
if (accuracy != null && (!Number.isFinite(accuracy) || accuracy < 0)) return null;
// WebKit reports the magnetic bearing of the device's top in portrait.
// The portrait edge points backwards if the phone is held upside down.
const portraitOffset = Math.cos(beta) < 0 ? 180 : 0;
return { degrees: normalise(heading + screenOffset - portraitOffset), reference: 'magnetic' };
}
if (!(event.absolute === true || event.type === 'deviceorientationabsolute')) return null;
if (!Number.isFinite(event.alpha) || event.alpha < 0 || event.alpha > 360) return null;
return { degrees: normalise(screenOffset - event.alpha), reference: 'sensor' };
}
let count=0, degenerate=0, maxError=0;
for(const alpha of [0,1,45,90,135,180,225,270,315,359]) for(const beta of [-170,-90,-60,-20,0,20,60,90,170]) for(const gamma of [-80,-45,0,45,80]) for(const angle of [0,90,180,270]) {
let x=Math.sin(angle*radians),y=Math.cos(angle*radians),z=0;
[x,z]=[x*Math.cos(gamma*radians)+z*Math.sin(gamma*radians),-x*Math.sin(gamma*radians)+z*Math.cos(gamma*radians)];
[y,z]=[y*Math.cos(beta*radians)-z*Math.sin(beta*radians),y*Math.sin(beta*radians)+z*Math.cos(beta*radians)];
[x,y]=[x*Math.cos(alpha*radians)-y*Math.sin(alpha*radians),x*Math.sin(alpha*radians)+y*Math.cos(alpha*radians)];
const result=deviceHeading({absolute:true,alpha,beta,gamma},angle);
if(Math.hypot(x,y)<0.15){assert.equal(result,null);degenerate++;}else{assert.equal(result.reference,'sensor');const oracle=normalise(Math.atan2(x,y)/radians);const error=Math.abs((result.degrees-oracle+540)%360-180);assert.ok(error<1e-9);maxError=Math.max(maxError,error);}
count++;
}
console.log({count,degenerate,maxError});
const cases=[['relative',{alpha:90,beta:0,gamma:0}],['missing tilt',{absolute:true,alpha:90}],['contradictory absolute',{absolute:false,type:'deviceorientationabsolute',alpha:90,beta:0,gamma:0}],['poor accuracy',{webkitCompassHeading:90,webkitCompassAccuracy:180,beta:0,gamma:0}],['missing accuracy',{webkitCompassHeading:90,beta:0,gamma:0}],['negative accuracy',{webkitCompassHeading:90,webkitCompas … [line shortened here: 676 characters; full line on GitHub]
for(const [name,event] of cases)console.log(name,JSON.stringify(deviceHeading(event)));04 Replay
A JavaScript module in Neural Link Between Agents. It is built from the run step (`run`), the fix step (`fix`) and the tick step (`tick`).
transformneural-link-between-agents / SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS/04-replay.mjs · lines 1–79 of 79 · Not reached from any entry point (candidate for review) · pattern replay (shared by 12 files)
- What it does
- It calculates its inputs. Defines 7 functions or classes, including replay, norm, angle, run, fix.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
- What it achieves
- Defines `replay`, `norm`, `angle` and 3 more.
- Why it matters
- No other file in the estate was found to import it.
- Application
- neural-link-between-agents · SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS · JavaScript module
- Uses
- none found
- Used by
- none found
- Produces
- replay, norm, angle, run, fix, h, tick
- Defines here
- replay, norm, angle, run, fix, h, tick
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS/04-replay.mjs:1-79 · blob 30e74b62b6b1b28016ad8b75b15eb6f674825679 · GitHub at these lines
- State
- achieves: name · context: auto · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner, ai_agent · canonical: unreached_review
function replay(events) {
let now=0, generation=0, active=false, permission="idle", screen=0, heading=null, fix=null, lastH=-1,lastF=-1,target=90;
const finite=Number.isFinite;
const norm=x=>((x%360)+360)%360;
const angle=x=>norm(x+180)-180;
return events.map(e=>{
if(!finite(e.at)||e.at<now)throw Error("nonmonotonic replay clock");
now=e.at;
if(e.type==="start"){generation++;active=false;permission="pending";heading=fix=null;lastH=lastF=-1;}
if(e.type==="grant"&&e.gen===generation&&permission==="pending"){active=true;permission="granted";}
if(e.type==="deny"&&e.gen===generation&&permission==="pending"){active=false;permission="denied";}
if(e.type==="stop"){generation++;active=false;permission="idle";heading=fix=null;lastH=lastF=-1;}
if(e.type==="screen"&&[0,90,180,270].includes(e.angle)&&screen!==e.angle){screen=e.angle;heading=null;}
if(e.type==="target"){target=e.bearing;}
if(active&&e.gen===generation&&e.type==="heading"&&finite(e.ts)&&e.ts>lastH&&e.ts<=now&&now-e.ts<=2000&&finite(e.deg)&&e.deg>=0&&e.deg<360&&finite(e.accuracy)&&e.accuracy>=0&&e.accuracy<=30&&e.screen===screen&&["true","magnetic","sensor"].includes(e.ref)&&e.tiltValid===true){
// A fresh true observation takes precedence over incompatible frames.
if(!(heading&&heading.ref==="true"&&now-heading.ts<=2000&&e.ref!=="true")){heading={deg:e.deg,ts:e.ts,ref:e.ref};lastH=e.ts;}
}
if(active&&e.gen===generation&&e.type==="fix"&&finite(e.ts)&&e.ts>lastF&&e.ts<=now&&now-e.ts<=5000&&finite(e.accuracy)&&e.accuracy>=0&&e.accuracy<=30&&finite(e.speed)&&e.speed>=0){
fix={ts:e.ts,course:e.speed>0&&finite(e.course)&&e.course>=0&&e.course<360?e.course:null};lastF=e.ts;
}
const h=active&&heading&&now-heading.ts<=2000?heading:null;
const f=active&&fix&&now-fix.ts<=5000?fix:null;
const state=!active?permission:!f?"no-fix":!h?"no-heading":h.ref!=="true"?"incompatible":!finite(target)||target<0||target>=360?"no-target":"ready";
return [state,state==="ready"?angle(target-h.deg):null,f?f.course:null];
});
}
function run(){
const start={type:"start",at:0},grant={type:"grant",at:0,gen:1};
const fix=(at=0,extras={})=>({type:"fix",at,ts:at,gen:1,accuracy:3,speed:0,course:90,...extras});
const h=(deg,at=0,extras={})=>({type:"heading",at,ts:at,gen:1,deg,accuracy:5,ref:"true",screen:0,tiltValid:true,...extras});
const tick=at=>({type:"tick",at});
const prefix=[start,grant,fix()];
const cases=[
["stationary north",[...prefix,h(0)],["ready",90,null]],
["stationary east",[...prefix,h(90)],["ready",0,null]],
["stationary south",[...prefix,h(180)],["ready",-90,null]],
["stationary west",[...prefix,h(270)],["ready",-180,null]],
["wrap 359",[...prefix,h(359)],["ready",91,null]],
["wrap 1",[...prefix,h(359),h(1,1)],["ready",89,null]],
["walking sideways",[...prefix,fix(1,{speed:1.5,course:90}),h(0,1)],["ready",90,90]],
["reverse course not heading",[...prefix,h(0),fix(1,{speed:1.5,course:270})],["ready",90,270]],
["reverse handset",[...prefix,h(90),h(270,1)],["ready",-180,null]],
["screen invalidates",[...prefix,h(90),{type:"screen",at:1,angle:90}],["no-heading",null,null]],
["screen new observation",[...prefix,h(90),{type:"screen",at:1,angle:90},h(180,2,{screen:90})],["ready",-90,null]],
["wrong screen",[...prefix,h(90),{type:"screen",at:1,angle:90},h(180,2)],["no-heading",null,null]],
["missing events",[...prefix,tick(1000)],["no-heading",null,null]],
["heading age boundary",[...prefix,h(90),tick(2000)],["ready",0,null]],
["heading expired",[...prefix,h(90),tick(2001)],["no-heading",null,null]],
["delayed heading",[...prefix,h(90,2500,{ts:0})],["no-heading",null,null]],
["out of order",[...prefix,h(90,10),h(180,11,{ts:9})],["ready",0,null]],
["duplicate",[...prefix,h(90,10),h(180,11,{ts:10})],["ready",0,null]],
["future timestamp",[...prefix,h(90,10,{ts:11})],["no-heading",null,null]],
["stale fix",[...prefix,h(90,5001)],["no-fix",null,null]],
["fix age boundary",[...prefix,h(90,5000)],["ready",0,null]],
["delayed fix",[start,grant,fix(5001,{ts:0}),h(90,5001)],["no-fix",null,null]],
["poor fix",[start,grant,fix(0,{accuracy:31}),h(90)],["no-fix",null,null]],
["magnetic only",[...prefix,h(90,0,{ref:"magnetic"})],["incompatible",null,null]],
["unknown sensor frame",[...prefix,h(90,0,{ref:"sensor"})],["incompatible",null,null]],
["dual stream",[...prefix,h(90),h(180,1,{ref:"magnetic"})],["ready",0,null]],
["fallback incompatible after expiry",[...prefix,h(90),h(180,2001,{ref:"magnetic"})],["incompatible",null,null]],
["missing tilt",[...prefix,h(90,0,{tiltValid:false})],["no-heading",null,null]],
["poor accuracy",[...prefix,h(90,0,{accuracy:180})],["no-heading",null,null]],
["missing accuracy",[...prefix,h(90,0,{accuracy:null})],["no-heading",null,null]],
["invalid angle",[...prefix,h(999)],["no-heading",null,null]],
["denied",[start,{type:"deny",at:1,gen:1},fix(2),h(90,2)],["denied",null,null]],
["stop pending",[start,{type:"stop",at:1},{type:"grant",at:2,gen:1},fix(2),h(90,2)],["idle",null,null]],
["stop live",[...prefix,h(90),{type:"stop",at:1},h(180,2)],["idle",null,null]],
["target removed",[...prefix,h(90),{type:"target",at:1,bearing:null}],["no-target",null,null]],
["target replaced",[...prefix,h(90),{type:"target",at:1,bearing:180}],["ready",90,null]]
];
let assertions=0;const eq=(a,b,label)=>{assertions++;if(JSON.stringify(a)!==JSON.stringify(b))throw Error(label+" "+JSON.stringify(a)+" expected "+JSON.stringify(b));};
for(const [name,events,expected] of cases){const first=replay(events);eq(first.at(-1),expected,name);eq(replay(events),first,name+" deterministic");}
for(let d=0;d<360;d++){const expected=d<=90?90-d:d<=270?90-d:450-d;eq(replay([...prefix,h(d)]).at(-1),["ready",expected===180?-180:expected,null],"circle "+d);}
return {scenarios:cases.length,assertions,circle:360,results:cases.map(([name,events,expected])=>({name,expected,actual:replay(events).at(-1)}))};
}
console.log(JSON.stringify(run(), null, 2));05 Estimator
A JavaScript module in Neural Link Between Agents that calculates planar distances and angles.
transformneural-link-between-agents / SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS/05-estimator.mjs · lines 1–54 of 54 · Not reached from any entry point (candidate for review) · pattern trace (shared by 3 files)
- What it does
- It calculates its inputs. Defines 6 functions or classes, including benchmark, norm, trace, estimator, label.
- Why it exists in the grid workflow
- Domain stage hv_procurement (path word 'estimator'): HV materials procurement, which Ventus Ltd states is within its commercial execution boundary.
- What it achieves
- It is built from the estimator step (`estimator`), the label step (`label`) and the metrics step (`metrics`). Defines `benchmark`, `norm`, `trace` and 3 more.
- Why it matters
- No other file in the estate was found to import it.
- Application
- neural-link-between-agents · SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS · JavaScript module
- Uses
- none found
- Used by
- none found
- Produces
- benchmark, norm, trace, estimator, label, metrics
- Defines here
- benchmark, norm, trace, estimator, label, metrics
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS/05-estimator.mjs:1-54 · blob c6663b5ea1ce1df428146baaf8798936231f53f5 · GitHub at these lines
- State
- achieves: name · context: auto · stage: transform · effects: none found · domain stage: hv_procurement · users: EPC_contractor, procurement_buyer, ai_agent · canonical: unreached_review
function benchmark(){
const norm=x=>((x%360)+360)%360,delta=(a,b)=>norm(a-b+180)-180,err=(a,b)=>Math.abs(delta(a,b));
const dt=100, N=120, noise=[-8,6,-4,9,-2,5,-7,3,1,-3];
const trace=(name,truth,observed,step=null)=>({name,step,rows:Array.from({length:N},(_,i)=>({t:i*dt,truth:norm(truth(i)),sample:norm(observed(i))}))});
const traces=[
trace("stationary-wrap",()=>0,i=>noise[i%10]),
trace("boundary",()=>25,i=>25+noise[i%10]),
trace("steady-turn",i=>350+i*2,i=>350+i*2+noise[i%10]),
trace("reversal-180",i=>i<40?0:180,i=>(i<40?0:180)+noise[i%10],40),
trace("reversal-90",i=>i<40?90:180,i=>(i<40?90:180)+noise[i%10],40),
trace("isolated-spike",()=>0,i=>i===40?165:noise[i%10]),
trace("constant-bias",()=>0,i=>20+noise[i%10]),
trace("persistent-disturbance",()=>0,i=>i<40?noise[i%10]:150+noise[i%10])
];
function estimator(kind){
let history=[],value=null,pending=null;
return {reset(){history=[];value=pending=null;},push(sample){
if(sample===null){this.reset();return null;}
if(kind==="raw")return sample;
if(kind==="mean5"){
history.push(sample);if(history.length>5)history.shift();
let x=0,y=0;for(const a of history){x+=Math.cos(a*Math.PI/180);y+=Math.sin(a*Math.PI/180);}
return Math.hypot(x,y)/history.length<0.15?null:norm(Math.atan2(y,x)*180/Math.PI);
}
if(value===null){value=sample;return value;}
if(kind==="adaptive"&&err(sample,value)>=60){
if(pending!==null&&err(sample,pending)<=25){value=sample;pending=null;return value;}
pending=sample;return null;
}
pending=null;
value=norm(value+(1-Math.exp(-dt/300))*delta(sample,value));return value;
}};
}
function label(h,previous,hyst){if(h===null)return null;const a=err(h,0);if(!hyst)return a<=25?"ahead":"turn";return previous==="ahead"?(a>30?"turn":"ahead"):previous==="turn"?(a<20?"ahead":"turn"):a<=25?"ahead":"turn";}
function metrics(kind,tr){
const e=estimator(kind);let prev=null,hprev=null,changes=0,hchanges=0,unavailable=0,wrong=0,updates=0,last=null,sum=0,sq=0,max=0,available=0;
const series=tr.rows.map(r=>{const v=e.push(r.sample),a=label(v,prev,false),b=label(v,hprev,true);
if(a!==null&&prev!==null&&a!==prev)changes++;if(b!==null&&hprev!==null&&b!==hprev)hchanges++;prev=a;hprev=b;
if(v===null){unavailable++;last=null;return null;}
const x=err(v,r.truth);sum+=x;sq+=x*x;max=Math.max(max,x);available++;if(x>45)wrong++;
if(last===null||err(last,v)>=1){updates++;last=v;}return x;
});
let settle=null;if(tr.step!==null){for(let i=tr.step;i<=series.length-5;i++){if(series.slice(i,i+5).every(x=>x!==null&&x<=10)){settle=(i-tr.step)*dt;break;}}}
return {mae:sum/available,rmse:Math.sqrt(sq/available),max,unavailable,wrong,changes,hchanges,updates,settle};
}
let assertions=0;const check=(ok,name)=>{assertions++;if(!ok)throw Error(name)};
const kinds=["raw","mean5","ema","adaptive"];
const results=traces.map(tr=>({name:tr.name,methods:Object.fromEntries(kinds.map(k=>[k,metrics(k,tr)]))}));
for(const k of kinds){let e=estimator(k);check(err(e.push(359),359)<1e-9,k+" initial");check(err(e.push(1),0)<=1.00000001,k+" wrap");check(e.push(null)===null,k+" reset");check(err(e.push(180),180)<1e-9,k+" restart");}
let e=estimator("adaptive");e.push(0);check(e.push(180)===null,"suspend reversal");check(e.push(179)===179,"confirm reversal");e.reset();e.push(0);check(e.push(165)===null,"spike");check(e.push(1)!==null,"spike recovery");
for(const tr of traces)for(const k of kinds){const m=metrics(k,tr);check(JSON.stringify(m)===JSON.stringify(metrics(k,tr)),tr.name+" "+k+" reproducible");check(Number.isFinite(m.mae)&&m.mae>=0&&m.mae<=180&&m.max<=180&&m.unavailable<=N,"bounded");}
return {assertions,scenarios:traces.length,samples:N*traces.length,evaluations:N*traces.length*kinds.length,dt,results};
}
console.log(JSON.stringify(benchmark(), null, 2));06 Reference
A JavaScript module in Neural Link Between Agents that calculates planar distances. It is built from the valid step (`valid`), the sigma step (`sigma`) and the convert step (`convert`).
transformneural-link-between-agents / SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS/06-reference.mjs · lines 1–46 of 46 · Not reached from any entry point (candidate for review) · pattern benchmark (shared by 6 files)
- What it does
- It calculates its inputs. Defines 7 functions or classes, including benchmark, norm, delta, valid, sigma.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
- What it achieves
- Defines `benchmark`, `norm`, `delta` and 4 more.
- Why it matters
- No other file in the estate was found to import it.
- Application
- neural-link-between-agents · SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS · JavaScript module
- Uses
- none found
- Used by
- none found
- Produces
- benchmark, norm, delta, valid, sigma, convert, fail
- Defines here
- benchmark, norm, delta, valid, sigma, convert, fail
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS/06-reference.mjs:1-46 · blob 7e06cdc66cc3302b3f5d0d08007e381cf071d024 · GitHub at these lines
- State
- achieves: name · context: auto · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner, ai_agent · canonical: unreached_review
function benchmark(){
const norm=x=>((x%360)+360)%360;
const delta=(a,b)=>norm(a-b+180)-180;
const valid=x=>Number.isFinite(x);
const sigma=h=>Math.hypot(.26,5417/h);
function convert(s,m){
const fail=reason=>({state:"unavailable",reason,heading:null,map:"north-up"});
if(!s||!valid(s.heading)||s.heading<0||s.heading>=360||!valid(s.accuracy)||s.accuracy<0||s.accuracy>30||s.fresh!==true)return fail("sensor");
if(s.disturbed===true)return fail("disturbance");
if(s.reference==="true"&&s.verifiedTrue===true)return {state:"available",heading:s.heading,budget:s.accuracy,map:"eligible"};
if(s.reference!=="magnetic")return fail("reference");
if(!m||m.model!=="WMM2025"||m.verified!==true||m.applicable!==true||!valid(m.year)||m.year<2025||m.year>=2030||!valid(m.D)||Math.abs(m.D)>180||!valid(m.H)||m.H<0||!valid(m.extra)||m.extra<0)return fail("model");
if(m.H<2000)return fail("blackout");
if(m.H<6000)return fail("caution");
const budget=s.accuracy+2*sigma(m.H)+m.extra;
if(budget>30)return fail("budget");
return {state:"available",heading:norm(s.heading+m.D),budget,map:"eligible"};
}
let passed=0;function check(v,label){if(!v)throw Error(label);passed++}
const s={heading:90,accuracy:5,reference:"magnetic",fresh:true};
const m={model:"WMM2025",verified:true,applicable:true,year:2026.92,D:0,H:20000,extra:1};
let maxCorrected=0,maxUncorrected=0,sumRaw=0,sweep=0;
for(let h=0;h<360;h++)for(const D of [-120,-30,-5,0,5,30,120]){
const out=convert({...s,heading:h},{...m,D});
let expected=h+D;if(expected<0)expected+=360;if(expected>=360)expected-=360;
check(out.state==="available","available");check(out.heading===expected,"sign/wrap");
let target=expected+90;if(target>=360)target-=360;
check(delta(target,out.heading)===90,"relative target");
const rawErr=Math.abs(delta(h,expected)),correctedErr=Math.abs(delta(out.heading,expected));
sumRaw+=rawErr;maxUncorrected=Math.max(maxUncorrected,rawErr);maxCorrected=Math.max(maxCorrected,correctedErr);sweep++;
}
const cases=[
["missing model",s,null,"model"],["unknown reference",{...s,reference:"sensor"},m,"reference"],["unverified true",{...s,reference:"true"},m,"reference"],["old epoch",s,{...m,year:2024.99},"model"],["expired",s,{...m,year:2030},"model"],["wrong model",s,{...m,model:"unknown"},"model"],["unverified coefficients",s,{...m,verified:false},"model"],["wrong location",s,{...m,applicable:false},"model"],[ … [line shortened here: 1,022 characters; full line on GitHub]
for(const [name,a,b,reason] of cases){const out=convert(a,b);check(out.reason===reason,name);check(out.heading===null&&out.map==="north-up",name+" fallback");}
const trueOut=convert({...s,reference:"true",verifiedTrue:true}, {...m,D:20});check(trueOut.heading===90,"no double correction");
check(convert(s,{...m,H:6000}).state==="available","6000 boundary");
check(convert(s,{...m,year:2025}).state==="available","2025 boundary");
check(convert(s,{...m,year:2029.999}).state==="available","2029 boundary");
let severe=0,suppressed=0;
for(let i=0;i<120;i++){const truth=0,D=12,bias=i>=40?150:0,heading=norm(truth-D+bias);const out=convert({...s,heading},{...m,D});if(Math.abs(delta(out.heading,truth))>45)severe++;const guarded=convert({...s,heading,disturbed:i>=40},{...m,D});if(guarded.heading===null)suppressed++;}
check(severe===80,"persistent bias survives");check(suppressed===80,"known bias suppressed");
const uncertainties=[2000,6000,10000,20000,40000].map(H=>({H,sigma:sigma(H)}));
check(uncertainties.every((v,i)=>i===0||v.sigma<uncertainties[i-1].sigma),"uncertainty decreases");
return {passed,sweep,gateCases:cases.length,maxCorrected,maxUncorrected,meanUncorrected:sumRaw/sweep,severe,suppressed,uncertainties};
}
console.log(JSON.stringify(benchmark(),null,2));07 Lifecycle
A JavaScript module in Neural Link Between Agents that works with lifecycle benchmark (`lifecycleBenchmark`).
ingestneural-link-between-agents / SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS/07-lifecycle.mjs · lines 1–34 of 34 · Not reached from any entry point (candidate for review) · pattern model (shared by 4 files)
- What it does
- Defines 13 functions or classes, including lifecycleBenchmark, eq, model, create, stop.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
- What it achieves
- It is built from the lifecycle benchmark helper (`lifecycleBenchmark`), the stop step (`stop`) and the start step (`start`). Defines `lifecycleBenchmark`, `model`, `create` and 9 more.
- Why it matters
- No other file in the estate was found to import it.
- Application
- neural-link-between-agents · SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS · JavaScript module
- Uses
- none found
- Used by
- none found
- Produces
- lifecycleBenchmark, eq, model, create, stop, start, sample, read, hide, show, leave, restore
- Defines here
- lifecycleBenchmark, eq, model, create, stop, start, sample, read, hide, show, leave, restore, scenario
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS/07-lifecycle.mjs:1-34 · blob d5e66e1084563977bbced06ba809e732359b049f · GitHub at these lines
- State
- achieves: name · context: auto · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner, ai_agent · canonical: unreached_review
function lifecycleBenchmark(){
const stats={assertions:0,passed:0,scenarios:0,cycles:0,maxCompassListeners:0,maxGpsWatches:0,lateCallbacksRejected:0};
function eq(a,b,label){stats.assertions++;if(a!==b)throw Error(label+": "+a+" != "+b);stats.passed++;}
function model(){
let now=10000,visible=true, page=true;
const create=()=>({gen:0,phase:"unavailable",active:0,last:null,seen:-Infinity,reason:"idle"});
const c=create(),g=create();
function stop(x,reason="stopped",phase="unavailable"){x.gen++;x.active=0;x.last=null;x.seen=-Infinity;x.phase=phase;x.reason=reason;}
function start(x,gesture,available=true){if(!gesture||!visible||!page)return null;if(x.active||x.phase==="pending")return null;if(!available){stop(x,"unsupported");return null;}stop(x,"requesting","pending");return x.gen;}
function resolve(x,token,result){if(token!==x.gen||x.phase!=="pending"||!visible||!page){stats.lateCallbacksRejected++;return false;}if(result!=="granted"&&result!=="implicit"){stop(x,result,result==="denied"?"denied":"unavailable");return false;}x.active=x===c?2:1;x.phase="unavailable";x.reason="awaiting sample";stats.maxCompassListeners=Math.max(stats.maxCompassListeners,c.active);stats.maxGps … [line shortened here: 460 characters; full line on GitHub]
function sample(x,token,t,value,quality=true){if(token!==x.gen||!x.active||!visible||!page){stats.lateCallbacksRejected++;return false;}if(!Number.isFinite(t)||t>now||t<=x.seen||now-t>2000)return false;x.seen=t;if(!quality||!Number.isFinite(value)){x.last=null;x.phase="degraded";x.reason="quality";return false;}x.last={t,value};x.phase="fresh";x.reason="valid";return true;}
function read(x){if(x.last&&now-x.last.t>2000){x.last=null;x.phase="degraded";x.reason="stale";}return {phase:x.phase,value:x.last?.value??null};}
function hide(){visible=false;stop(c,"hidden");stop(g,"hidden");}
function show(){visible=true;}
function leave(){hide();page=false;}
function restore(){page=true;show();}
return {c,g,start,resolve,sample,read,stop,hide,show,leave,restore,advance:n=>now+=n,clock:()=>now};
}
function scenario(fn){stats.scenarios++;fn(model());}
scenario(m=>{eq(m.start(m.c,false),null,"no gesture");eq(m.c.active,0,"no listeners");eq(m.g.active,0,"no watch");});
scenario(m=>{eq(m.start(m.c,true,false),null,"unsupported");eq(m.read(m.c).phase,"unavailable","unsupported state");});
for(const outcome of ["denied","rejected","error","timeout"]){scenario(m=>{const t=m.start(m.c,true);eq(m.c.active,0,"pending no listeners");eq(m.resolve(m.c,t,outcome),false,"failed permission");eq(m.c.active,0,"no listeners");eq(m.g.active,0,"no GPS");eq(m.read(m.c).phase,outcome==="denied"?"denied":"unavailable","failure state");});}
for(const action of ["stop","hide","leave"]){scenario(m=>{const t=m.start(m.c,true);if(action==="stop")m.stop(m.c);else m[action]();eq(m.resolve(m.c,t,"granted"),false,"late grant");eq(m.c.active,0,"late listener");eq(m.read(m.c).value,null,"no stale display");});}
scenario(m=>{const t=m.start(m.c,true);eq(m.start(m.c,true),null,"duplicate pending");eq(m.resolve(m.c,t,"granted"),true,"grant");eq(m.start(m.c,true),null,"duplicate active");eq(m.c.active,2,"one pair");eq(m.resolve(m.c,t,"granted"),false,"duplicate grant");eq(m.c.active,2,"one pair still");});
scenario(m=>{const g=m.start(m.g,true),c=m.start(m.c,true);m.resolve(m.g,g,"granted");m.resolve(m.c,c,"denied");eq(m.g.active,1,"GPS survives compass denial");eq(m.sample(m.g,g,m.clock(),25),true,"GPS usable");eq(m.read(m.g).value,25,"GPS value");eq(m.c.active,0,"compass off");});
scenario(m=>{const g=m.start(m.g,true),c=m.start(m.c,true);m.resolve(m.c,c,"implicit");m.resolve(m.g,g,"denied");eq(m.c.active,2,"compass survives GPS denial");eq(m.g.active,0,"GPS off");});
scenario(m=>{const t=m.start(m.c,true);m.resolve(m.c,t,"granted");eq(m.read(m.c).phase,"unavailable","grant not reading");eq(m.sample(m.c,t,m.clock(),0),true,"north valid");eq(m.read(m.c).value,0,"zero preserved");m.advance(2000);eq(m.read(m.c).phase,"fresh","inclusive boundary");m.advance(1);eq(m.read(m.c).phase,"degraded","stale without timer");eq(m.read(m.c).value,null,"stale suppressed");});
scenario(m=>{const t=m.start(m.c,true);m.resolve(m.c,t,"granted");eq(m.sample(m.c,t,m.clock()-2001,90),false,"late sample");eq(m.sample(m.c,t,m.clock()+1,90),false,"future");eq(m.sample(m.c,t,NaN,90),false,"unknown timestamp");eq(m.sample(m.c,t,m.clock(),90),true,"valid");eq(m.sample(m.c,t,m.clock(),180),false,"duplicate");eq(m.read(m.c).value,90,"unchanged");m.advance(10);eq(m.sample(m.c,t,m.clo … [line shortened here: 616 characters; full line on GitHub]
scenario(m=>{const t=m.start(m.c,true);m.resolve(m.c,t,"granted");m.sample(m.c,t,m.clock(),20);m.stop(m.c);const u=m.start(m.c,true);m.resolve(m.c,u,"granted");eq(m.sample(m.c,t,m.clock(),200),false,"old generation");eq(m.read(m.c).value,null,"not revived");eq(m.sample(m.c,u,m.clock(),80),true,"new generation");});
scenario(m=>{const t=m.start(m.c,true);m.resolve(m.c,t,"granted");const g=m.start(m.g,true);m.resolve(m.g,g,"implicit");m.stop(m.c);eq(m.g.active,1,"compass stop independent");m.stop(m.g);eq(m.c.active,0,"both stopped");eq(m.g.active,0,"watch cleared");});
scenario(m=>{for(let i=0;i<1000;i++){stats.cycles++;const c=m.start(m.c,true),g=m.start(m.g,true);eq(m.resolve(m.c,c,"granted"),true,"cycle grant");eq(m.resolve(m.g,g,"implicit"),true,"cycle watch");eq(m.c.active,2,"pair");eq(m.g.active,1,"watch");m.sample(m.c,c,m.clock(),i%360);m.sample(m.g,g,m.clock(),i);if(i%2)m.leave();else m.hide();eq(m.c.active,0,"cleanup compass");eq(m.g.active,0,"cleanup … [line shortened here: 699 characters; full line on GitHub]
return stats;
}
console.log(JSON.stringify(lifecycleBenchmark(),null,2));08 Relative
A JavaScript module in Neural Link Between Agents that works with valid angle (`validAngle`) and calculates angles.
transformneural-link-between-agents / SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS/08-relative.mjs · lines 1–30 of 30 · Not reached from any entry point (candidate for review) · pattern stable (shared by 3 files)
- What it does
- It calculates its inputs. Defines 7 functions or classes, including benchmark, norm, nominal, stable, validAngle.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
- What it achieves
- It is built from the stable step (`stable`), the valid angle helper (`validAngle`) and the model step (`model`). Defines `benchmark`, `norm`, `nominal` and 4 more.
- Why it matters
- No other file in the estate was found to import it.
- Application
- neural-link-between-agents · SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS · JavaScript module
- Uses
- none found
- Used by
- none found
- Produces
- benchmark, norm, nominal, stable, validAngle, model, fail
- Defines here
- benchmark, norm, nominal, stable, validAngle, model, fail
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS/08-relative.mjs:1-30 · blob 27646eb352f1f6d0ca720a64a184563427092357 · GitHub at these lines
- State
- achieves: name · context: auto · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner, ai_agent · canonical: unreached_review
function benchmark(){
const norm=x=>((x%360)+360)%360, delta=(b,h)=>norm(b-h+180)-180;
const labels=["ahead","right","behind","left"], centers={ahead:0,right:90,behind:180,left:270};
const nominal=d=>labels[Math.floor(norm(d+45)/90)];
const stable=(d,prev)=>prev&&Math.abs(delta(d,centers[prev]))<=50?prev:nominal(d);
const validAngle=x=>Number.isFinite(x)&&x>=0&&x<360;
function model(){let key=null,prev=null;return (h,t,now)=>{
const next=t?JSON.stringify([t.id,t.revision,t.generation,h?.generation]):null;
if(next!==key){prev=null;key=next;}
const fail=reason=>{prev=null;return {angle:null,label:null,reason};};
if(!t||!t.valid||!Number.isFinite(t.distance)||t.distance<0||!t.id||!Number.isInteger(t.revision)||!Number.isInteger(t.generation))return fail("target");
if(t.distance===0)return fail("coincident");
if(!h||h.state!=="fresh"||h.reference!=="true"||t.reference!=="true"||!validAngle(h.angle)||!validAngle(t.bearing)||!Number.isInteger(h.generation)||h.generation!==t.generation)return fail("reference-or-state");
if(!Number.isFinite(now)||!Number.isFinite(h.time)||!Number.isFinite(t.time)||now-h.time<0||now-h.time>2000||now-t.time<0||now-t.time>2000)return fail("age");
if(h.disturbed!==false||!Number.isFinite(h.uncertainty)||!Number.isFinite(t.uncertainty)||h.uncertainty<0||t.uncertainty<0||h.uncertainty+t.uncertainty>20)return fail("quality");
const angle=delta(t.bearing,h.angle),label=stable(angle,prev);prev=label;
const ambiguity=Math.min(...[45,135,-45,-135].map(b=>Math.abs(delta(angle,b))))<=h.uncertainty+t.uncertainty;
return {angle,label,ambiguity,reason:null};
};}
let n=0;const groups={};let g="geometry";function check(ok,msg){n++;groups[g]=(groups[g]||0)+1;if(!ok)throw Error(msg);}
let maxError=0;
for(let h=0;h<360;h++)for(let b=0;b<360;b++){const d=delta(b,h),r=Math.PI/180;const east=Math.sin(b*r)*Math.cos(h*r)-Math.cos(b*r)*Math.sin(h*r),north=Math.cos(b*r)*Math.cos(h*r)+Math.sin(b*r)*Math.sin(h*r);const oracle=Math.atan2(east,north)/r;const err=Math.abs(delta(d,oracle));maxError=Math.max(maxError,err);check(err<1e-9,"vector");check(d>=-180&&d<180,"range");check(delta(norm(b+137),norm(h+1 … [line shortened here: 492 characters; full line on GitHub]
g="fractional";for(let i=0;i<3600;i++){const h=i/10,b=norm(359.95-i/20);const d=delta(b,h);check(Math.abs(delta(norm(h+d),b))<1e-9,"reconstruct");check(d>=-180&&d<180,"range");}
g="boundary";let rawChanges=0,stableChanges=0;for(const edge of [45,135,225,315]){let p=nominal(edge-2),raw=p;for(let i=0;i<100;i++){const d=delta(edge+(i%2?2:-2),0),a=nominal(d),s=stable(d,p);rawChanges+=a!==raw;stableChanges+=s!==p;check(s===p,"jitter");raw=a;p=s;}check(stable(delta(edge+6,0),p)===nominal(edge+6),"forward");check(stable(delta(edge-6,0),nominal(edge+6))===nominal(edge-6),"reverse … [line shortened here: 404 characters; full line on GitHub]
g="validity";const h={angle:0,state:"fresh",reference:"true",time:1000,generation:1,uncertainty:3,disturbed:false},t={id:"neutral",revision:1,generation:1,valid:true,distance:100,bearing:45,reference:"true",time:1000,uncertainty:2};let m=model();check(m(h,t,1000).ambiguity,"ambiguity");check(m(h,{...t,bearing:90},3000).angle===90,"inclusive");check(m(h,t,3001).angle===null,"expiry");const badH=[nu … [line shortened here: 786 characters; full line on GitHub]
const badT=[null,{valid:false},{distance:0},{distance:-1},{distance:NaN},{bearing:null},{bearing:NaN},{reference:"magnetic"},{time:1001},{time:-1001},{revision:null},{id:""},{generation:2},{uncertainty:NaN}];for(const v of badT){const a=m(h,v===null?null:{...t,...v},1000);check(a.angle===null&&a.label===null,"bad target");}
g="reset";for(let i=0;i<1000;i++){m=model();check(m(h,{...t,bearing:44},1000).label==="ahead","seed");check(m(h,{...t,bearing:47},1000).label==="ahead","hold");check(m(h,{...t,bearing:47,revision:2},1000).label==="right","revision");check(m(h,{...t,bearing:44,revision:2},1000).label==="right","hold reverse");check(m({...h,state:"degraded"},t,1000).label===null,"clear");check(m(h,{...t,bearing:44,r … [line shortened here: 622 characters; full line on GitHub]
return {assertions:n,passed:n,groups,integerPairs:129600,fractionalPairs:3600,boundarySamples:400,rawChanges,stableChanges,resetCycles:1000,maxVectorErrorDeg:maxError,thresholds:{hysteresisDeg:5,maxCombinedUncertaintyDeg:20,maxAgeMs:2000},limitations:"synthetic model; no browser, field test or composition"};
}
console.log(JSON.stringify(benchmark(),null,2));09 Arrow
A web page in Neural Link Between Agents that draws SVG graphics.
renderneural-link-between-agents / SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS/09-arrow.html · lines 1–11 of 11 · Entry point
- What it does
- It draws its content. Defines $. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
- Inputs & outputs
- Out: web page; SVG drawing.
- Downstream impact
- It is itself an entry point (page); no other file was found loading it.
- What it achieves
- ORIENT-09 neutral study.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- neural-link-between-agents · SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS · page
- Uses
- none found
- Used by
- none found
- Produces
- $
- Defines here
- $
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS/09-arrow.html:1-11 · blob d6924092236472cc9c95f1a2fe8bc9e68690d260 · GitHub at these lines
- State
- achieves: comment · context: auto · stage: output · effects: dom · domain stage: field_execution · users: EPC_contractor, landowner_planner, ai_agent · canonical: unknown
<!doctype html>
<html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"><title>ORIENT-09 neutral study</title>
<style>
*{box-sizing:border-box}body{margin:0;font:16px system-ui,sans-serif;background:#b9b9b9;color:#fff}.map{min-height:100dvh;background:repeating-linear-gradient(37deg,#e7e7e7 0 20px,#24332b 20px 40px,#74634a 40px 60px)}.dock{position:fixed;z-index:2;top:calc(8px + var(--safe-top,env(safe-area-inset-top,0px)));left:calc(8px + var(--safe-left,env(safe-area-inset-left,0px)));right:calc(8px + var(--safe … [line shortened here: 1,575 characters; full line on GitHub]
</style><body><main class="map" aria-label="Synthetic map background"><section class="dock" aria-labelledby="title"><h1 id="title">Destination direction</h1><div class="visual"><svg id="arrow" viewBox="0 0 100 100" aria-hidden="true" hidden><path d="M50 3 88 48 63 48 63 96 37 96 37 48 12 48Z"/></svg></div><p class="instruction" id="instruction" role="status" aria-atomic="true">Direction unavailabl … [line shortened here: 736 characters; full line on GitHub]
<script>
const $=id=>document.getElementById(id);const arrow=$('arrow'),instruction=$('instruction'),distance=$('distance'),panel=$('panel'),toggle=$('toggle');
function render(s){const validDistance=s.distanceValid===true&&Number.isFinite(s.distance)&&s.distance>=0;const labels={ahead:'Straight ahead',right:'Turn right',left:'Turn left',behind:'Behind you'};const allowed=validDistance&&s.distance>0&&s.reason===null&&Number.isFinite(s.angle)&&s.angle>=-180&&s.angle<180&&Object.hasOwn(labels,s.label)&&typeof s.ambiguity==='boolean';const visible=allowed&&! … [line shortened here: 1,049 characters; full line on GitHub]
toggle.onclick=()=>{panel.hidden=!panel.hidden;toggle.setAttribute('aria-expanded',String(!panel.hidden));toggle.textContent=panel.hidden?'Show SatNav panel':'Hide SatNav panel';};
window.render=render;render({reason:'reference-or-state',distanceValid:false});
</script></body></html>09 Browser
A Python module in Neural Link Between Agents.
renderneural-link-between-agents / SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS/09-browser.py · lines 1–55 of 55 · Not reached from any entry point (candidate for review)
- What it does
- It loads data. Defines check, lum. Uses libraries pathlib, playwright.sync_api, json, math. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
- What it achieves
- Defines `check` and `lum`.
- Why it matters
- No other file in the estate was found to import it.
- Application
- neural-link-between-agents · SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS · Python module
- Uses
- pathlib, playwright.sync_api, json, math
- Used by
- none found
- Produces
- check, lum
- Defines here
- check, lum
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS/09-browser.py:1-55 · blob ad50577e4c57bcec46acf4726af83821b9e40d9f · GitHub at these lines
- State
- achieves: name · context: auto · stage: output · effects: dom, filesystem · domain stage: field_execution · users: EPC_contractor, landowner_planner, ai_agent · canonical: unreached_review
from pathlib import Path
from playwright.sync_api import sync_playwright
import json, math
root=Path(__file__).parent
counts={}
def check(group, ok):
assert ok, group
counts[group]=counts.get(group,0)+1
with sync_playwright() as p:
browser=p.chromium.launch(executable_path='/usr/bin/chromium',args=['--no-sandbox'])
for w,h in [(320,568),(390,844),(844,390),(1280,720)]:
page=browser.new_page(viewport={'width':w,'height':h})
page.set_content((root/'09-arrow.html').read_text())
for safe in [0,24]:
page.evaluate('(s)=>{for(const k of ["top","left","right","bottom"])document.documentElement.style.setProperty("--safe-"+k,s+"px")}',safe)
box=page.locator('.dock').bounding_box(); b=page.locator('#toggle').bounding_box()
check('geometry',box['x']>=safe+7 and box['y']>=safe+7)
check('geometry',box['x']+box['width']<=w-safe-7 and box['y']+box['height']<=h-safe-7)
check('geometry',b['width']>=44 and b['height']>=44)
check('geometry',page.evaluate('document.documentElement.scrollWidth===innerWidth'))
for angle in range(-180,180):
label=['ahead','right','behind','left'][((angle+45)%360)//90]
page.evaluate('(s)=>render(s)',dict(angle=angle,label=label,ambiguity=False,reason=None,distance=123,distanceValid=True))
check('angle',page.locator('#arrow').is_visible())
check('angle',page.locator('#arrow').evaluate('(e)=>e.style.transform')==f'rotate({angle}deg)')
check('angle',page.locator('#instruction').inner_text()==dict(ahead='Straight ahead',right='Turn right',behind='Behind you',left='Turn left')[label])
valid=dict(angle=90,label='right',ambiguity=False,reason=None,distance=123,distanceValid=True)
for change in [dict(reason='age'),dict(reason='quality'),dict(reason='denied'),dict(reason='stopped'),dict(reason='target'),dict(reason='reference-or-state'),dict(ambiguity=True),dict(angle=None),dict(angle=180),dict(label='invalid'),dict(distanceValid=False),dict(distance=0,reason='coincident')]:
page.evaluate('(s)=>render(s)',valid|change)
check('unavailable',not page.locator('#arrow').is_visible())
check('unavailable',page.locator('#arrow').evaluate('(e)=>e.style.transform')=='')
check('unavailable',page.locator('#instruction').inner_text()!='Turn right')
page.evaluate('(s)=>render(s)',valid)
check('distance',page.locator('#distance').inner_text()=='123 m straight line')
page.evaluate('(s)=>render(s)',valid|dict(distance=1000000,reason='age'))
check('distance',page.locator('#distance').inner_text()=='1000.00 km straight line')
page.evaluate('(s)=>render(s)',valid)
page.get_by_role('button',name='Show SatNav panel').click()
check('panel',page.locator('#panel').is_visible() and page.locator('#arrow').is_visible())
page.get_by_role('button',name='Hide SatNav panel').click()
check('panel',not page.locator('#panel').is_visible() and page.locator('#arrow').is_visible())
check('accessibility',page.get_by_role('status').inner_text()=='Turn right')
check('accessibility',page.locator('#arrow').get_attribute('aria-hidden')=='true')
check('accessibility',page.locator('#toggle').get_attribute('aria-expanded')=='false')
check('accessibility',page.locator('#toggle').get_attribute('aria-controls')=='panel')
page.keyboard.press('Tab'); page.keyboard.press('Shift+Tab')
check('accessibility',page.locator('#toggle').evaluate('(e)=>e===document.activeElement'))
if w==390: page.screenshot(path=str(root/'09-preview.png'))
page.close()
browser.close()
def lum(rgb):
x=[v/255 for v in rgb];return sum(k*(v/12.92 if v<=0.04045 else ((v+0.055)/1.055)**2.4) for k,v in zip([.2126,.7152,.0722],x))
ratio=(1.05)/(lum([16,24,32])+.05)
check('contrast',ratio>=4.5)
print(json.dumps(dict(assertions=sum(counts.values()),groups=counts,contrastRatio=ratio,viewports=4,safeAreaFixtures=8,engine='Chromium',limitations='synthetic background and safe-area overrides; no actual Safari, screen reader, or field test'),indent=2))10 Camera
A JavaScript module in Neural Link Between Agents that creates controller (`createController`). It creates controller (`createController`) and is built from the camera study helper (`cameraStudy`) and the finite step (`finite`).
transformneural-link-between-agents / SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS/10-camera.mjs · lines 1–73 of 73 · Not reached from any entry point (candidate for review) · pattern createController (shared by 3 files)
- What it does
- It calculates its inputs. Defines 15 functions or classes, including cameraStudy, norm, delta, finite, createController.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
- What it achieves
- Defines `cameraStudy`, `norm`, `delta` and 10 more.
- Why it matters
- No other file in the estate was found to import it.
- Application
- neural-link-between-agents · SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS · JavaScript module
- Uses
- none found
- Used by
- none found
- Produces
- cameraStudy, norm, delta, finite, createController, fresh, goodHeading, goodFix, tick, check, fixture, h
- Defines here
- cameraStudy, norm, delta, finite, createController, fresh, goodHeading, goodFix, tick, check, fixture, h, f, tick, invariant
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS/10-camera.mjs:1-73 · blob 4dabd49dff6319d1ae5408a2e3fd320fa27164de · GitHub at these lines
- State
- achieves: name · context: auto · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner, ai_agent · canonical: unreached_review
function cameraStudy(){
const norm=a=>((a%360)+360)%360;
const delta=(a,b)=>norm(a-b+180)-180;
const finite=n=>typeof n==="number"&&Number.isFinite(n);
function createController(map){
let mode="north",follow=false,suspended=false,heading=null,fix=null,epoch=0,now=0,zoomPending=false;
const fresh=(s,age)=>s&&s.epoch===epoch&&finite(s.t)&&s.t<=now&&now-s.t<=age;
const goodHeading=s=>fresh(s,2000)&&s.reference==="true"&&s.valid===true&&finite(s.deg)&&s.deg>=0&&s.deg<360;
const goodFix=s=>fresh(s,5000)&&s.valid===true&&Array.isArray(s.at)&&s.at.length===2&&s.at.every(finite)&&Math.abs(s.at[0])<=180&&Math.abs(s.at[1])<=90;
function tick(t){if(!finite(t)||t<now)throw Error("nonmonotonic clock");now=t;
if(!follow||suspended)return;
const target={};const b=mode==="heading"&&goodHeading(heading)?heading.deg:0;
if(Math.abs(delta(b,map.bearing))>0.000001)target.bearing=b;
if(goodFix(fix)){
if(fix.at.some((v,i)=>v!==map.center[i]))target.center=fix.at.slice();
if(zoomPending){const z=Math.min(map.maxZoom,Math.max(17,map.zoom));if(z!==map.zoom)target.zoom=z;zoomPending=false;}
}
if(Object.keys(target).length)map.write(target,"camera-controller");
}
return {
tick,epoch:()=>epoch,mode:()=>mode,following:()=>follow,
setMode:m=>{if(m!=="north"&&m!=="heading")throw Error("invalid mode");mode=m;},
start:()=>{if(!suspended){follow=true;zoomPending=true;}},
resume:()=>{if(!suspended){follow=true;zoomPending=false;}},
manual:()=>{follow=false;zoomPending=false;},
external:target=>{if(suspended)return;follow=false;zoomPending=false;map.write(target,"camera-controller");},
suspend:()=>{suspended=true;follow=false;zoomPending=false;epoch++;fix=heading=null;},
restore:()=>{suspended=false;},
stop:()=>{follow=false;zoomPending=false;epoch++;fix=heading=null;},
heading:s=>{if(s?.epoch===epoch&&!suspended&&finite(s.t)&&s.t<=now&&(!heading||s.t>heading.t))heading={...s};},
fix:s=>{if(s?.epoch===epoch&&!suspended&&finite(s.t)&&s.t<=now&&(!fix||s.t>fix.t))fix={...s,at:Array.isArray(s.at)?s.at.slice():null};},
};
}
let checks=0, cases=0, maxWrites=0, anglePairs=0, cycles=0;
const check=(v,m)=>{checks++;if(!v)throw Error(m+" at "+checks)};
function fixture(){
const map={center:[0,0],bearing:0,zoom:12,maxZoom:20,pitch:30,destination:"synthetic-destination",layers:["base","grid","route"],pins:["A","B"],writes:[],
write(p,owner){this.writes.push({owner,p});Object.assign(this,p);}};
const c=createController(map);
const h=(deg,t=0,extra={})=>c.heading({deg,t,epoch:c.epoch(),reference:"true",valid:true,...extra});
const f=(at,t=0,extra={})=>c.fix({at,t,epoch:c.epoch(),valid:true,...extra});
const tick=t=>{let n=map.writes.length;c.tick(t);let w=map.writes.length-n;maxWrites=Math.max(maxWrites,w);check(w<=1,"more than one write per tick");};
const invariant=()=>{check(map.destination==="synthetic-destination","destination");check(map.layers.join()==="base,grid,route","layers");check(map.pins.join()==="A,B","pins");check(map.pitch===30,"pitch");check(map.writes.every(w=>w.owner==="camera-controller"),"writer");};
return {map,c,h,f,tick,invariant};
}
for(let initial=0;initial<360;initial++)for(let heading=0;heading<360;heading++){
const {map,c,h,f,tick}=fixture();map.bearing=initial;map.zoom=18;c.resume();c.setMode("heading");h(heading);f([1,2]);tick(0);
check(map.bearing===heading,"heading");check(map.center[0]===1&&map.center[1]===2,"center");check(map.zoom===18,"zoom");anglePairs++;
}
for(let i=0;i<1000;i++){
const {map,c,h,f,tick,invariant}=fixture();c.start();c.setMode("heading");h(359);f([1,2]);tick(0);
check(map.zoom===17&&map.bearing===359,"first");tick(1);h(1,1);f([2,3],1);tick(1);check(map.bearing===1&&map.center[0]===2,"wrap");
c.manual();map.zoom=19;map.center=[4,5];map.bearing=42;tick(2);h(90,2);f([3,4],2);tick(2);check(map.bearing===42&&map.center[0]===4&&map.zoom===19,"manual");
c.resume();tick(2);check(map.bearing===90&&map.center[0]===3&&map.zoom===19,"resume");
tick(2003);check(map.bearing===0&&map.center[0]===3,"expiry fallback");c.suspend();const old=c.epoch()-1;c.restore();tick(2004);h(120,2004,{epoch:old});f([6,7],2004,{epoch:old});c.resume();tick(2004);check(map.bearing===0&&map.center[0]===3,"old epoch");
h(180,2004);f([7,8],2004);tick(2004);check(map.bearing===180&&map.center[0]===7,"new epoch");
c.external({center:[9,10],zoom:14,bearing:30});tick(2005);h(270,2005);f([8,9],2005);tick(2005);check(!c.following()&&map.center[0]===9&&map.bearing===30,"external");
c.setMode("north");tick(2005);check(map.bearing===30,"paused mode");c.resume();tick(2005);check(map.bearing===0&&map.zoom===14&&map.center[0]===8,"explicit north resume");
c.stop();tick(2006);check(!c.following(),"stop");invariant();cycles++;
}
for(const extra of [{reference:"magnetic"},{valid:false},{deg:NaN},{deg:360},{deg:-1},{t:1},{epoch:-1}]){
const {map,c,h,f,tick,invariant}=fixture();map.bearing=27;c.resume();c.setMode("heading");h(90,0,extra);f([1,2]);tick(0);
check(map.bearing===0&&map.center[0]===1,"invalid heading");invariant();cases++;
}
for(const extra of [{valid:false},{at:[181,1]},{at:[0,91]},{at:[NaN,0]},{at:null},{t:1},{epoch:-1}]){
const {map,c,h,f,tick,invariant}=fixture();c.start();c.setMode("heading");h(90);f([1,2],0,extra);tick(0);
check(map.bearing===90&&map.center[0]===0&&map.zoom===12,"invalid gps");invariant();cases++;
}
{const {map,c,h,f,tick,invariant}=fixture();map.maxZoom=16;c.start();f([1,2]);tick(0);check(map.zoom===16,"zoom cap");invariant();cases++;}
{const {map,c,h,f,tick,invariant}=fixture();c.resume();c.setMode("heading");h(90);f([1,2]);tick(0);tick(10);h(180,10);f([3,4],10);h(270,9);f([8,9],9);tick(10);check(map.bearing===180&&map.center[0]===3,"ordering");const n=map.writes.length;tick(11);check(map.writes.length===n,"no-op");tick(5011);check(map.bearing===0&&map.center[0]===3,"expiry");invariant();cases++;}
return {assertions:checks,passed:checks,anglePairs,cycles,additionalCases:cases,maxWritesPerTick:maxWrites,engine:"JavaScript deterministic fake camera, no browser or real MapLibre"};
}
console.log(JSON.stringify(cameraStudy(),null,2));11 Modes Arrival
A JavaScript module in Neural Link Between Agents. It is built from the invalidate step (`invalidate`), the identity step (`identity`) and the same step (`same`).
transformneural-link-between-agents / SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS/11-modes-arrival.mjs · lines 1–97 of 97 · Not reached from any entry point (candidate for review) · pattern quality (shared by 2 files)
- What it does
- It calculates its inputs. Defines 15 functions or classes, including study, norm, controller, invalidate, identity.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
- What it achieves
- Defines `study`, `norm`, `controller` and 12 more.
- Why it matters
- No other file in the estate was found to import it.
- Application
- neural-link-between-agents · SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS · JavaScript module
- Uses
- none found
- Used by
- none found
- Produces
- study, norm, controller, invalidate, identity, same, quality, hGood, eligible, view, check, setup
- Defines here
- study, norm, controller, invalidate, identity, same, quality, hGood, eligible, view, check, setup, route, sample, compass
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 SESSIONS/2026-12-02-SATNAV-ORIENT-20/FINDINGS/11-modes-arrival.mjs:1-97 · blob 8f77ddf188053455eb923724253da89e9edce96d · GitHub at these lines
- State
- achieves: name · context: auto · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner, ai_agent · canonical: unreached_review
function study(){
const modes=["walking","driving","manual"], finite=Number.isFinite;
const policies={walking:{radius:15,accuracy:10,remaining:15},driving:{radius:25,accuracy:15,remaining:25},manual:{radius:15,accuracy:10,remaining:0}};
const norm=x=>((x%360)+360)%360, rel=(b,h)=>norm(b-h+180)-180;
function controller(){
let mode="walking",journey=1,targetRev=1,leg=1,request=0,epoch=0,objective="shortest",destination="D",observation="O",verifiedStop=false,route=null,status="idle",fix=null,heading=null,now=0,lastTime=-Infinity,streak=[],arrived=false,match=null;
const layers=["base","grid"],pins=["P","D"],camera={zoom:18,owner:"shared"},gpsWatch=1;
const invalidate=()=>{request++;route=null;match=null;status="idle";streak=[];arrived=false;};
const identity=()=>({journey,targetRev,leg,request,mode,objective,epoch,destination,observation});
const same=k=>k&&Object.entries(identity()).every(([key,value])=>k[key]===value);
const quality=f=>!!f&&f.epoch===epoch&&finite(f.t)&&f.t<=now&&now-f.t<=5000&&finite(f.accuracy)&&f.accuracy>0&&f.accuracy<=30&&finite(f.d)&&f.d>=0&&finite(f.stopD)&&f.stopD>=0;
const hGood=()=>heading&&heading.epoch===epoch&&heading.valid===true&&heading.reference==="true"&&finite(heading.deg)&&heading.deg>=0&&heading.deg<360&&heading.t<=now&&now-heading.t<=2000;
const eligible=(f,m)=>{
const p=policies[mode];
return quality(f)&&verifiedStop&&f.accuracy<=p.accuracy&&f.stopD+f.accuracy<=p.radius&&(mode==="manual"||(route&&status==="ready"&&m?.routeId===route.id&&m?.t===f.t&&m?.unique===true&&m?.onRoute===true&&finite(m.remaining)&&m.remaining>=0&&m.remaining<=p.remaining&&route.endpoint===observation))&&(mode!=="driving"||(finite(f.speed)&&f.speed>=0&&f.speed<=0.5));
};
function view(){
const usable=quality(fix), p=policies[mode];
const matched=usable&&status==="ready"&&route&&match?.routeId===route.id&&match?.t===fix.t&&match.unique===true&&match.onRoute===true&&finite(match.remaining)&&match.remaining>=0&&finite(match.nextBearing)&&match.nextBearing>=0&&match.nextBearing<360;
const source=mode==="driving"?(usable&&finite(fix.speed)&&fix.speed>=2&&finite(fix.course)&&fix.course>=0&&fix.course<360&&fix.courseValid===true?fix.course:null):(hGood()?heading.deg:null);
const b=mode==="manual"?(usable&&fix.d>fix.accuracy&&finite(fix.bearing)&&fix.bearing>=0&&fix.bearing<360?fix.bearing:null):(matched?match.nextBearing:null);
return {mode,destination,observation,objective,routeId:route?.id??null,status,straight:usable?fix.d:null,remaining:matched?match.remaining:null,eta:matched&&finite(match.eta)&&match.eta>=0&&route.timeSupported?match.eta:null,arrow:source!==null&&b!==null?rel(b,source):null,orientation:source,arrived:arrived&&usable&&eligible(fix,match),streak:streak.length,layers:[...layers],pins:[...pins],z … [line shortened here: 451 characters; full line on GitHub]
}
return {
identity,view,
configureStop:(id,verified)=>{observation=id;verifiedStop=verified===true;leg++;invalidate();},
changeMode:(m,{confirmed=false,safelyStopped=false}={})=>{if(!modes.includes(m)||!confirmed||(mode==="driving"&&!safelyStopped))return false;if(m===mode)return true;mode=m;objective="shortest";leg++;invalidate();return true;},
changeTarget:id=>{destination=id;targetRev++;leg++;observation=id;verifiedStop=false;invalidate();},
objective:o=>{if(!["shortest","fastest"].includes(o)||(o==="fastest"&&mode!=="driving"))return false;objective=o;invalidate();return true;},
begin:()=>{invalidate();status=mode==="manual"?"direct":"pending";return identity();},
accept:(k,r)=>{if(!same(k)||mode==="manual"||status!=="pending")return false;if(!r||r.eligible!==true||r.snapUnique!==true||r.graphFresh!==true||r.endpoint!==observation||r.objective!==objective||!r.id||(objective==="fastest"&&r.timeSupported!==true)){status="unavailable";return false;}route={...r};status="ready";return true;},
tick:t=>{if(!finite(t)||t<now)throw Error("clock");now=t;if(!quality(fix)){streak=[];arrived=false;}else if(streak.length&&now-streak.at(-1)>2500){streak=[];arrived=false;}},
gps:(f,m=null)=>{if(f?.epoch!==epoch||!finite(f.t)||f.t<=lastTime||f.t>now)return false;lastTime=f.t;fix={...f};match=m?{...m}:null;if(!eligible(fix,match)){streak=[];arrived=false;return true;}if(streak.length&&f.t-streak.at(-1)>2500){streak=[];arrived=false;}streak.push(f.t);if(streak.length>3)streak.shift();arrived=streak.length===3&&streak[2]-streak[0]>=2000;return true;},
heading:h=>{if(h?.epoch===epoch&&finite(h.t)&&h.t<=now&&(!heading||h.t>heading.t))heading={...h};},
loss:()=>{epoch++;fix=heading=match=null;lastTime=-Infinity;invalidate();},
epoch:()=>epoch
};
}
let assertions=0,boundaryCases=0,raceCases=0,lifecycleCycles=0,naiveFalse=0,conservativeFalse=0,blocked=0;
const check=(x,m)=>{assertions++;if(!x)throw Error(m+" #"+assertions);};
function setup(mode="walking",verified=true){
const c=controller();c.changeMode(mode,{confirmed:true,safelyStopped:true});c.configureStop("O",verified);return c;
}
function route(c,extra={}){let k=c.begin();return c.accept(k,{id:"R"+k.request,eligible:true,snapUnique:true,graphFresh:true,endpoint:"O",objective:k.objective,timeSupported:true,...extra});}
function sample(c,t,extra={},mextra={}){
c.tick(t);const f={epoch:c.epoch(),t,accuracy:3,d:120,stopD:3,bearing:90,speed:0,course:180,courseValid:true,...extra};
const m={routeId:c.view().routeId,t,unique:true,onRoute:true,remaining:4,nextBearing:0,eta:10,...mextra};
return c.gps(f,m);
}
function compass(c,t,extra={}){c.heading({epoch:c.epoch(),t,deg:90,valid:true,reference:"true",...extra});}
for(const mode of modes)for(let d=0;d<=40;d++)for(let a=0;a<=35;a++)for(const verified of [false,true]){
const c=setup(mode,verified);if(mode!=="manual")check(route(c),"valid route");
for(const t of [0,1000,2000])sample(c,t,{stopD:d,accuracy:a});
const p=policies[mode],expected=verified&&a>0&&a<=p.accuracy&&d+a<=p.radius;
check(c.view().arrived===expected,"arrival boundary "+mode+" "+d+" "+a);
check(c.view().straight===(a>0&&a<=30?120:null),"distance independence");
if(!expected&&d<=p.radius){naiveFalse++;if(c.view().arrived)conservativeFalse++;}
boundaryCases++;
}
for(let i=0;i<1000;i++){
const c=setup("driving");check(route(c),"drive route");sample(c,0,{speed:10});compass(c,0);check(c.view().arrow===-180,"course not compass");
sample(c,1000,{speed:0});compass(c,1000,{deg:270});check(c.view().arrow===null,"stationary vehicle");
sample(c,2000);sample(c,3000);check(c.view().arrived,"drive arrival");
const old=c.identity();check(!c.changeMode("walking",{confirmed:true}),"unsafe switch");check(c.view().arrived,"failed switch leaves state");
check(c.changeMode("walking",{confirmed:true,safelyStopped:true}),"confirmed switch");check(c.view().destination==="D"&&c.view().routeId===null&&!c.view().arrived&&c.view().straight===120,"reset preserve");
let current=c.begin();check(!c.accept(old,{id:"OLD"}),"obsolete request");check(c.accept(current,{id:"W",eligible:true,snapUnique:true,graphFresh:true,endpoint:"O",objective:"shortest"}),"walking route");
sample(c,4000);compass(c,4000,{deg:90});check(c.view().arrow===-90&&c.view().remaining===4,"next manoeuvre not direct");
check(!c.gps({epoch:c.epoch(),t:4000,accuracy:3,d:0,stopD:0}),"duplicate");check(c.view().streak===1,"duplicate not arrival");
sample(c,5000,{}, {unique:false});check(c.view().arrow===null&&!c.view().arrived&&c.view().streak===0,"ambiguous snap");
check(c.changeMode("manual",{confirmed:true}),"manual transition");sample(c,6000);compass(c,6000);check(c.view().arrow===0&&c.view().remaining===null&&c.view().straight===120,"manual direct");
c.tick(8001);check(c.view().arrow===null&&c.view().straight===120,"heading expiry");c.tick(11001);check(c.view().straight===null&&!c.view().arrived,"gps expiry");
const v=c.view();check(v.layers.join()==="base,grid"&&v.pins.join()==="P,D"&&v.zoom===18&&v.cameraOwner==="shared"&&v.gpsWatch===1,"shared invariants");
const e=c.epoch();c.loss();check(!c.gps({epoch:e,t:11001}),"old epoch");check(c.view().routeId===null&&c.view().arrow===null,"loss cleared");
lifecycleCycles++;
}
for(const before of modes)for(const after of modes)for(const change of ["mode","target","leg","objective","loss","retry"]){
const c=setup(before);let old=c.begin();
if(change==="mode"){if(before===after)continue;c.changeMode(after,{confirmed:true,safelyStopped:true});}
if(change==="target")c.changeTarget("D2");
if(change==="leg")c.configureStop("O2",true);
if(change==="objective"){if(before!=="driving")continue;c.objective("fastest");}
if(change==="loss")c.loss();
if(change==="retry")c.begin();
check(!c.accept(old,{id:"OLD",eligible:true,snapUnique:true,graphFresh:true,endpoint:"O",objective:"shortest"}),"stale route token");
check(c.view().routeId===null&&c.view().arrow===null&&c.view().eta===null&&!c.view().arrived,"stale no output");
raceCases++;
}
for(const mode of ["walking","driving"])for(const extra of [{eligible:false},{snapUnique:false},{graphFresh:false},{endpoint:"wrong"},{objective:"fastest"},{id:""}]){
const c=setup(mode);check(!route(c,extra),"unavailable route");sample(c,0);compass(c,0);check(c.view().status==="unavailable"&&c.view().arrow===null&&c.view().remaining===null,"no direct fallback");blocked++;
}
{const c=setup("driving");check(c.objective("fastest"),"fastest select");check(!route(c,{timeSupported:false}),"fastest missing data");blocked++;}
{const c=setup("walking");check(!c.objective("fastest"),"walking fastest not supported");check(route(c),"route");sample(c,0);sample(c,1000);sample(c,4000);check(!c.view().arrived&&c.view().streak===1,"gap resets");sample(c,5000);sample(c,6000);check(c.view().arrived,"recovered dwell");c.tick(8501);check(!c.view().arrived,"arrival expires");}
{const c=setup("manual",false);sample(c,0,{d:0,stopD:0});sample(c,1000,{d:0,stopD:0});sample(c,2000,{d:0,stopD:0});check(!c.view().arrived,"mapped point not access");}
{const c=setup("manual");sample(c,0);compass(c,0,{valid:false});check(c.view().arrow===null&&c.view().straight===120,"flagged disturbance");}
return {assertions,passed:assertions,boundaryCases,raceCases,lifecycleCycles,blockedRouteCases:blocked,naiveUnsafeAcceptances:naiveFalse,conservativeUnsafeAcceptances:conservativeFalse,engine:"deterministic JavaScript model; no live GPS, graph or browser"};
}
console.log(JSON.stringify(study(),null,2));