"""Extract only synthetic runtime records, excluding paths, environment and credentials.
Usage: python extract-proof.py <worktree> <thread-id> <proxy-log>
"""
import json,pathlib,sqlite3,subprocess,sys
root=pathlib.Path(sys.argv[1]);tid=sys.argv[2]
db=sqlite3.connect('file:'+str(root/'.t3/userdata/statev2.sqlite')+'?mode=ro',uri=True);db.row_factory=sqlite3.Row
runs=[dict(r) for r in db.execute('select ordinal,status,requested_at,completed_at from orchestration_v2_projection_runs where thread_id=? order by ordinal',(tid,))]
events=[]
p=root/'.t3/userdata/logs/provider'/('events.'+tid.replace(':','-')+'.log')
for line in p.read_text().splitlines():
 if 'NTIVE: ' not in line: continue
 obj=json.loads(line.split('NTIVE: ',1)[1]); event=obj.get('event',{}); data=event.get('payload',{});kind=data.get('type')
 if kind not in ['query.open','query.close','prompt.offer','command_lifecycle','result']:continue
 clean={k:data[k] for k in ['type','subtype','command_uuid','state','is_error','num_turns'] if k in data}
 if kind=='prompt.offer':
  msg=data['message'];clean['message']={'uuid':msg.get('uuid'),'content':msg.get('message',{}).get('content')}
 if kind=='query.open': clean['options']={k:data['options'][k] for k in ['model','resume','resumeSessionAt','sessionId'] if k in data['options']}
 events.append({'time':line[1:25],'direction':event['direction'],'payload':clean})
requests=[json.loads(l) for l in pathlib.Path(sys.argv[3]).read_text().splitlines()]
windows=[]
for r in runs:
 if r["ordinal"]!=2: continue
 windows.append({'ordinal':r['ordinal'],'requests':[q for q in requests if r['requested_at']<=q['time'] and (r['completed_at'] is None or q['time']<=r['completed_at'])]})
print(json.dumps({'commit':subprocess.check_output(['git','-C',str(root),'rev-parse','HEAD'],text=True).strip(),
 'cliVersion':subprocess.check_output(['claude','--version'],text=True).strip(),
 'threadId':tid,'runs':runs,'nativeProtocol':events,'httpRequestsDuringResumeWindow':windows},indent=2))
