import sys, sqlite3, json, pathlib, datetime
checkout, parent, output = sys.argv[1:]
db = sqlite3.connect(f'file:{checkout}/.t3/userdata/statev2.sqlite?mode=ro', uri=True)
items = [json.loads(row[0]) for row in db.execute('select payload_json from orchestration_v2_projection_turn_items where thread_id=? order by ordinal', (parent,))]
tools=[]
for item in items:
    name=item.get('toolName','')
    if any(name.endswith(x) for x in ['delegate_task','t3_thread_send','t3_thread_wait','task_status']):
        tools.append({k:item.get(k) for k in ['toolName','input','output','startedAt','completedAt']})
children=[]
for tool in tools:
    if tool['toolName'].endswith('t3_thread_send'):
        result=tool['output']
        if isinstance(result,str): result=json.loads(result)
        children.append(result['threadId'])
requests=[]
work=[]
for child in children:
    requests.extend(json.loads(r[0]) for r in db.execute('select payload_json from orchestration_v2_projection_runtime_requests where thread_id=?',(child,)))
    work.extend(json.loads(r[0]) for r in db.execute("select payload_json from orchestration_v2_projection_turn_items where thread_id=? and type='command_execution'",(child,)))
record={'capturedAt':datetime.datetime.now(datetime.timezone.utc).isoformat(),'tools':tools,'childRuntimeRequests':requests,'childCommands':work}
pathlib.Path(output).write_text(json.dumps(record,indent=2)+'\n')
print(json.dumps({'toolCount':len(tools),'requests':[(r['kind'],r['status'],r['responseCapability']) for r in requests],'commands':[(x.get('input'),x['status']) for x in work]}))
