import json,pathlib,sqlite3,sys
# Usage: python extract-native.py DATABASE CODEX_SESSIONS COMMIT OUTPUT
# Read only this proof's database; export only native permissions and command I/O.
db,sessions,sha,out=sys.argv[1:]
c=sqlite3.connect('file:'+db+'?mode=ro',uri=True)
records=[]
for tid,mode in c.execute("select thread_id,runtime_mode from orchestration_v2_projection_threads where runtime_mode in ('auto','auto-accept-edits') order by created_at"):
 for (s,) in c.execute('select payload_json from orchestration_v2_projection_provider_threads where thread_id=?',(tid,)):
  native=json.loads(s)['nativeThreadRef']['nativeId']
  for p in pathlib.Path(sessions).glob('**/*'+native+'*.jsonl'):
   record={'commit':sha,'runtimeMode':mode,'contexts':[],'commandIO':[]}
   for line in p.read_text().splitlines():
    v=json.loads(line); d=v.get('payload',{})
    if v['type']=='turn_context': record['contexts'].append({k:d.get(k) for k in ['approval_policy','sandbox_policy']})
    if v['type']=='response_item' and d.get('type')=='custom_tool_call' and 'gh api user' in d.get('input',''): record['commandIO'].append({k:d.get(k) for k in ['type','name','input']})
    if v['type']=='response_item' and d.get('type')=='custom_tool_call_output': record['commandIO'].append({'type':d['type'],'output':d.get('output')})
   records.append(record)
pathlib.Path(out).write_text(json.dumps(records,indent=2)+'\n')
