#!/usr/bin/env python3
"""Export only this synthetic proof thread's relevant persisted tool records."""
import argparse,json,sqlite3,pathlib
p=argparse.ArgumentParser()
p.add_argument('database',type=pathlib.Path)
p.add_argument('thread')
p.add_argument('output',type=pathlib.Path)
a=p.parse_args()
db=sqlite3.connect(a.database.resolve().as_uri()+'?mode=ro',uri=True)
rows=[json.loads(x[0]) for x in db.execute("select payload_json from orchestration_v2_projection_turn_items where thread_id=? and type='dynamic_tool' order by ordinal",(a.thread,))]
caps=next(r for r in rows if r['toolName'].endswith('orchestrator_capabilities'))['output']['structuredContent']
delegate=next(r for r in rows if r['toolName'].endswith('delegate_task'))
result={'piAdvertisedAtDelegation':next(p for p in caps['providers'] if p['providerInstanceId']=='pi'),'delegateTool':{k:delegate[k] for k in ['toolName','input','output','startedAt','completedAt']}}
a.output.write_text(json.dumps(result,indent=2)+'\n')
