main
John Lauer Corrected Astra ESC routing: native zero-open result, full accounting and voiceover handoff a80479d 23d ago
from bridge import *
import csv,math,collections,re
rows=[json.loads(l) for l in open(D/'evidence/calls.jsonl')]
rid=json.load(open(D/'evidence/final-recording-start.json'))['recordingId'];idx=next(i for i,x in enumerate(rows) if x['result'].get('recordingId')==rid)
comm=[x for x in rows[idx:] if x['verb']=='kicad_route_net' and not x['args'].get('dryRun') and x['result'].get('success')]
first=next(x for x in rows if x['verb']=='kicad_routing_state');routefirst=next(x for x in rows if x['verb']=='kicad_route_net')
v=json.load(open(D/'evidence/final-validate.json'));st=json.load(open(D/'evidence/final-state.json'));base=json.load(open(D/'evidence/token-baseline.json'));prompt=base['promptTimestamp'];u0=base['baseline']['payload']['info']['total_token_usage'];last=None;model=None;usages=[];usage_records=[];lasttotal=u0
roll='/home/adom/.codex/sessions/2026/09/12/rollout-2026-09-12T12-08-00-01a09697-1b14-7111-9897-63815e098b24.jsonl'
for l in open(roll):
 x=json.loads(l);p=x.get('payload',{})
 if x['type']=='turn_context':model=p.get('model')
 if p.get('type')=='token_count' and p.get('info') and x['timestamp']>=prompt:
  tot=p['info']['total_token_usage']
  if tot!=lasttotal:
   usages.append(p['info']['last_token_usage']);usage_records.append(dict(timestamp=x['timestamp'],usage=p['info']['last_token_usage']))
  last=x;lasttotal=tot
u={k:lasttotal.get(k,0)-u0.get(k,0) for k in lasttotal}
cost=sum(((x['input_tokens']-x.get('cached_input_tokens',0))*10+x.get('cached_input_tokens',0))* (2 if x['input_tokens']>272000 else 1)/1e6+x['output_tokens']*50*(1.5 if x['input_tokens']>272000 else 1)/1e6 for x in usages)
length=sum(math.hypot(s['end']['x']-s['start']['x'],s['end']['y']-s['start']['y']) for s in st['segments'])
initial=json.load(open('evidence/baseline-validate.json'))
def sig(v):return (v['type'],tuple(sorted(i['uuid'] for i in v.get('items',[]))))
a={sig(x) for x in initial['violations'] if x['severity']=='error'};b={sig(x) for x in v['violations'] if x['severity']=='error'}
remaining=v.get('unconnectedItems',v.get('unconnected_items',[]));types=collections.Counter(x['type'] for x in v['violations'] if x['severity']=='error')
counts=collections.Counter(round(s['width'],3) for s in st['segments'])
remainingNets=sorted({re.search(r'\[([^]]+)\]',i['description']).group(1) for x in remaining for i in x['items'] if re.search(r'\[([^]]+)\]',i['description'])})
stats=dict(engine='GPT-6 Astra',model=model,board='ESC G431, shared Fable placement, 149 footprints, 4 copper layers, initial GND and +3V3 planes',desktop='arav-rog, Windows user arav, KiCad 10.0.3, kicad-bridge 1.0.3',window=[prompt,last['timestamp']],windowNote='Whole routing task through the stated accounting cutoff, including rejected planning candidates, first discarded recording, display/capture diagnostics, replay, the previously published incomplete take, the subsequent corrective routing work and publication preparation. Earlier placement and six-net tasks excluded.',planning=dict(wallSeconds=round(routefirst['start']-first['start'],3),definition='First kicad_routing_state request to first kicad_route_net request, a dry run',toAcceptedTakeFirstCommitSeconds=round(comm[0]['start']-first['start'],3)),routing=dict(commits=len(comm),wallSeconds=round(comm[-1]['end']-comm[0]['start'],3),firstToLastCompletionSeconds=round(comm[-1]['end']-comm[0]['end'],3),netsTouched=len(set(x['args']['net'] for x in comm)),segments=len(st['segments']),vias=len(st['vias']),copperLengthMm=round(length,3),lengthDefinition='Sum of native track centerline lengths, excluding pads, planes and vertical via barrels',trackWidths=counts,netsFullyConnected=59-len(remainingNets),netsRemaining=remainingNets,liveUnfilledNetsRemaining=st['netsRemaining'],drcErrors=v['errors'],newDrcErrors=len(b-a),inheritedDrcErrors=len(a&b),unconnected=v['unconnected'],violationTypes=types,zonesRefilled=v['zonesRefilled'],violationReportMayBeTruncated=v['violationReportMayBeTruncated']),tokens=dict(thread=u,uncachedInputTokens=u['input_tokens']-u['cached_input_tokens'],threadTurns=len(usages),agentLaunches=0,agents=0,workerThreads=max(0,sum(x['verb']=='desktop_record_start' and bool(x['result'].get('recordingId')) for x in rows)-1),acceptedTakeWorkerThreads=1,maxConcurrentWorkerThreads=1,displayAwakeHelperProcesses=1,displayAwakeHelperNote='One temporary hidden PowerShell process holds a display/system-awake lease for the final recording; released at cleanup, with a 20-minute automatic timeout. Power settings unchanged.',workerNote='One elapsed-time-caption Python worker per take after the first take. The count is cumulative across those takes; one ran in the accepted take. Routing and C++ path search are serial. No AI sub-agents.',withAgents=u,accountingSource=roll,accountingCutoff=last['timestamp'],accountingNote='input_tokens includes cached_input_tokens. Reasoning output is included in output_tokens. No cache writes reported. Reporting after cutoff excluded.',maxRequestInputTokens=max(x['input_tokens'] for x in usages)),usdApiEquivalent=dict(thread=round(cost,6),withAgents=round(cost,6),priceBasis='OpenAI GPT-6 Astra model page checked 2026-09-13: $10 uncached input, $1 cached input, $50 output, $12.50 cache writes per million tokens (no writes reported). Standard API equivalent. Requests above 272K input use 2x input/cache and 1.5x output prices.',priceUrl='https://developers.openai.com/api/docs/models/gpt-6-astra'),planShare=dict(planUsdPerMonth=200,threadPercent=round(cost/2,6),withAgentsPercent=round(cost/2,6),note='API-equivalent cost divided by $200, not actual subscription billing or quota consumption'))
allcomm=[x for x in rows if x['verb']=='kicad_route_net' and not x['args'].get('dryRun') and x['result'].get('success')]
stats['routing']['wholeTaskSuccessfulCommits']=len(allcomm)
stats['routing']['wholeTaskFirstCommitToLastWallSeconds']=round(allcomm[-1]['end']-allcomm[0]['start'],3)
stats['planning']['firstStateThroughFinalCommitWallSeconds']=round(allcomm[-1]['end']-first['start'],3)
stats['recordings']=[]
for i,x in enumerate(rows):
 if x['verb']!='desktop_record_start' or not x['result'].get('recordingId'):continue
 ident=x['result']['recordingId'];end=next((j for j,y in enumerate(rows[i+1:],i+1) if y['verb']=='desktop_record_stop' and y['args'].get('recordingId')==ident),None)
 if end is None:continue
 span=rows[i:end+1];val=next((y['result'] for y in reversed(span) if y['verb']=='kicad_routing_validate'),{})
 stats['recordings'].append(dict(recordingId=ident,startUTC=x['utc'],wallSeconds=rows[end]['result'].get('elapsedMs',0)/1000,bytes=rows[end]['result'].get('bytes'),path=rows[end]['result'].get('path'),accepted=ident==rid,successfulCommits=sum(y['verb']=='kicad_route_net' and not y['args'].get('dryRun') and bool(y['result'].get('success')) for y in span),errors=val.get('errors'),unconnected=val.get('unconnected')))
(D/'evidence/token-accounting.json').write_text(json.dumps(dict(baseline=u0,cutoff=last['timestamp'],cumulative=lasttotal,delta=u,requests=usage_records),indent=2))
(D/'evidence/astra-stats.json').write_text(json.dumps(stats,indent=2));(D/'evidence/unconnected.json').write_text(json.dumps(remaining,indent=2))
with (D/'evidence/bridge-calls.csv').open('w') as f:
 w=csv.writer(f);w.writerow(['startUTC','endUTC','durationSeconds','verb','net','success','errorCode','items','revision','drcErrors','unconnected','command'])
 for x in rows:
  r=x['result'];d=r.get('drc',r);w.writerow([x['utc'],datetime.datetime.fromtimestamp(x['end'],datetime.timezone.utc).isoformat(),round(x['end']-x['start'],4),x['verb'],x['args'].get('net'),r.get('success'),r.get('errorCode'),len(r.get('itemIds',[])),r.get('revision'),d.get('errors'),d.get('unconnected'),x['command']])
(D/'evidence/bridge-commands.txt').write_text('\n'.join(x['command'] for x in rows)+'\n')
print(json.dumps(stats,indent=2))