#!/usr/bin/env python3
"""Read-only final inspection. Output synthetic replies and delivery states only."""
import json,pathlib,sqlite3,subprocess,sys
checkout,side=sys.argv[1:]
with sqlite3.connect('file:'+checkout+'/.t3/userdata/statev2.sqlite?mode=ro',uri=True) as db:
 threads=[json.loads(r[0]) for r in db.execute('select payload_json from orchestration_v2_projection_threads')]
 tasks=[json.loads(r[0]) for r in db.execute('select payload_json from orchestration_v2_projection_subagents')]
p=next(t for t in threads if t['title']=='Parent evidence')
c=next(t for t in threads if t['lineage']['parentThreadId']==p['id'])
result={'side':side,'environment':'Linux real development server and CLI; fresh isolated synthetic data','threads':[]}
for label,t in [('parent',p),('child',c)]:
 proc=subprocess.run(['node','apps/server/src/bin.ts','thread','show',t['id'],'--base-dir','.t3','--json'],cwd=checkout,capture_output=True,text=True,check=True)
 value=json.loads(proc.stdout)
 messages=[m['text'].strip() for m in value['messages'] if m['role']=='assistant' and any(m['text'].strip() in [marker,marker+' only'] for marker in ['CHILD FIRST COMPLETE','CHILD FOLLOWUP COMPLETE','PARENT IDLE','PARENT FOLLOWUP RECEIVED'])]
 result['threads'].append({'label':label,'status':value['thread']['status'],'runs':value['thread']['runCount'],'syntheticAssistantReplies':messages})
result['delegatedTasks']=[{'status':t['status'],'completionDeliveryState':t.get('completionDelivery',{}).get('state')} for t in tasks if t['threadId']==p['id']]
print(json.dumps(result,indent=2))
