"""Extract only synthetic reproduction facts; omit paths, credentials, host IDs."""
import pathlib,json,sqlite3,sys
root=pathlib.Path(sys.argv[1]);out={}
for side in ['base','head']:
 db=sqlite3.connect(f'file:{root}/{side}-final/userdata/statev2.sqlite?mode=ro',uri=True)
 out[side]={'runs':[{'status':s,'requestedAt':r,'completedAt':c} for s,r,c in db.execute('select status,requested_at,completed_at from orchestration_v2_projection_runs order by requested_at')], 'subagents':[{'status':s,'startedAt':a,'completedAt':b,'updatedAt':u} for s,a,b,u in db.execute('select status,started_at,completed_at,updated_at from orchestration_v2_projection_subagents')]}
children=[]
for p in sorted((root/'subagent-temp/async-subagent-runs').glob('*/status.json')):
 d=json.loads(p.read_text());child={'state':d['state'],'startedAt':d['startedAt'],'steps':[]}
 for st in d.get('steps',[]):
  child['steps'].append({k:st[k] for k in ['agent','status','startedAt','completedAt','exitCode'] if k in st})
  transcript=pathlib.Path(st['sessionFile']);events=[]
  if transcript.exists():
   for line in transcript.read_text().splitlines():
    x=json.loads(line);m=x.get('message',{});role=m.get('role');cs=m.get('content',[])
    if not isinstance(cs,list):continue
    for c in cs:
     if c.get('type')=='toolCall' and c.get('name')=='bash':events.append({'timestamp':x.get('timestamp'),'event':'bash','command':c.get('arguments',{}).get('command')})
     elif c.get('type')=='text' and c.get('text','').strip()=='SCOUT_OK':events.append({'timestamp':x.get('timestamp'),'event':role,'text':'SCOUT_OK'})
  child['events']=events
 children.append(child)
out['piChildren']=children
(root/'evidence-facts.json').write_text(json.dumps(out,indent=2))
print(json.dumps(out,indent=2))
