import sqlite3, json, sys
# Only synthetic proof threads and model selections; never export the database.
db, parent, side, out = sys.argv[1:]
c=sqlite3.connect('file:'+db+'?mode=ro',uri=True)
threads=[json.loads(r[0]) for r in c.execute('select payload_json from orchestration_v2_projection_threads')]
selected=[t for t in threads if t['id']==parent or t.get('lineage',{}).get('parentThreadId')==parent or t.get('title')=='Created suffix control']
ids={t['id'] for t in selected}
result={'side':side,'threads':[{'id':t['id'],'title':t['title'],'modelSelection':t.get('modelSelection'),'lineage':t.get('lineage')} for t in selected]}
result['runs']=[{'threadId':p['threadId'],'ordinal':p['ordinal'],'status':p['status'],'modelSelection':p.get('modelSelection')} for (s,) in c.execute('select payload_json from orchestration_v2_projection_runs') if (p:=json.loads(s))['threadId'] in ids]
result['toolCalls']=[{'toolName':p.get('toolName'),'input':p.get('input'),'status':p['status']} for (s,) in c.execute('select payload_json from orchestration_v2_projection_turn_items where thread_id=? and type="dynamic_tool" order by ordinal',(parent,)) if (p:=json.loads(s))]
json.dump(result,open(out,'w'),indent=2)
