import pathlib,json,sys,datetime
root=pathlib.Path(sys.argv[1])
for side in ['before','after']:
 run=pathlib.Path((root/(side+'-recorded-latest')).read_text());out={'side':side,'parent':json.loads(json.loads((run/'parent-result.json').read_text())['stdout']),'delegateCalls':[],'childProtocol':[],'autoSettle':[],'databaseObservations':[]}
 for p in (run/'t3/userdata/logs/provider').glob('*'):
  child='thread-delegated-task' in p.name
  for raw in p.read_text().splitlines():
   if '] NTIVE: ' not in raw:continue
   try:e=json.loads(raw.split('] NTIVE: ',1)[1])['event'];q=e['payload']
   except (ValueError,KeyError):continue
   method=q.get('method');params=q.get('params',{});item=params.get('item',{})
   if not child and method=='item/completed' and item.get('tool')=='delegate_task':
    result=item.get('result',{}).get('structuredContent',{});out['delegateCalls'].append({'utc':raw[1:25],'arguments':item.get('arguments'),'status':item.get('status'),'result':{k:result.get(k) for k in ['status','workState','latestTerminalStatus','providerInstanceId','model','executedModel','summary','hasPendingChildRuns','waitTimedOut']}})
   if child:
    event={'utc':raw[1:25],'direction':e['direction'],'method':method}
    if method=='thread/started':event['nativeThreadId']=params['thread']['id'];out['childNativeThreadId']=event['nativeThreadId']
    elif method=='turn/completed':event['status']=params.get('turn',{}).get('status')
    elif method not in ['thread/archive','thread/unsubscribe','thread/closed','thread/archived']:continue
    out['childProtocol'].append(event)
 for raw in (run/'t3/userdata/logs/server.trace.ndjson').read_text().splitlines():
  x=json.loads(raw);a=x.get('attributes',{})
  if a.get('orchestration_v2.command_type')=='thread.auto-settle':
   out['autoSettle'].append({'name':x.get('name'),'utc':datetime.datetime.fromtimestamp(int(x['startTimeUnixNano'])/1e9,datetime.UTC).isoformat(),'commandType':a['orchestration_v2.command_type'],'exit':x.get('exit')})
 for raw in (run/'observations.jsonl').read_text().splitlines():
  x=json.loads(raw);row=next((r for r in x['threads'] if r[0]==out.get('childNativeThreadId')),None);out['databaseObservations'].append({'utc':x['utc'],'secondsAfterParent':x['secondsAfterParent'],'childArchived':row[1] if row else None})
 (root/(side+'-evidence.json')).write_text(json.dumps(out,indent=2)+'\n')
 print(side,'delegates',len(out['delegateCalls']),'protocol',out['childProtocol'],'last',out['databaseObservations'][-1])
