import json, sqlite3, pathlib, sys, re
root = pathlib.Path(sys.argv[1])
conn = sqlite3.connect(f"file:{root / '.t3/userdata/statev2.sqlite'}?mode=ro", uri=True)
threads = [r[0] for r in conn.execute("select distinct thread_id from orchestration_v2_projection_turn_items where thread_id like 'thread:delegated%'")]
for thread in threads:
    print("DELEGATED CHILD")
    for (raw,) in conn.execute("select payload_json from orchestration_v2_projection_turn_items where thread_id=? order by ordinal", (thread,)):
        d=json.loads(raw)
        if d['type'] in ['command_execution','assistant_message']:
            print(json.dumps({k:d.get(k) for k in ['type','status','startedAt','completedAt','input','output','text']}, ensure_ascii=False))
    print("Run count:", conn.execute("select count(*) from orchestration_v2_projection_runs where thread_id=?",(thread,)).fetchone()[0])

def fields(b):
    pos=0
    def varint():
        nonlocal pos
        n=0;shift=0
        while True:
            x=b[pos];pos+=1;n|=(x&127)<<shift
            if x<128:return n
            shift+=7
    while pos<len(b):
        key=varint();typ=key&7;num=key>>3
        if typ==0:varint()
        elif typ==1:pos+=8
        elif typ==5:pos+=4
        elif typ==2:
            n=varint();value=b[pos:pos+n];pos+=n;yield num,value
        else:raise ValueError(typ)

def field(b,n):return next((v for k,v in fields(b) if k==n),b'')
for db in (root/'.t3/userdata/providers/antigravity').glob('*/antigravity-acp/conversations/*.db'):
    c=sqlite3.connect(f"file:{db}?mode=ro",uri=True)
    steps=list(c.execute('select idx,step_type,status,step_payload from steps order by idx'))
    if not any(b'./job.sh A 20' in row[3] for row in steps):continue
    # Parent prompts mention job.sh too; identify the session that ran the commands.
    if not any(typ==132 and field(field(field(payload,5),4),2)==b'run_command' for _,typ,_,payload in steps):continue
    print("NATIVE CHILD TRANSCRIPT")
    for idx,typ,status,payload in steps:
        if typ==15:
            text=field(field(payload,20),1).decode('utf-8')
            print(json.dumps({'step':idx,'type':'PLANNER_RESPONSE','status':status,'text':text}))
        elif typ==101:
            text=field(field(payload,114),1).decode('utf-8')
            # Keep notification output, omit session identifiers and file locations.
            match=re.search(r'timestamp=([^ ]+).*?Command exited with code (\d+)\.\s+Command output:\s+([AB] finished: result-[AB])',text,re.S)
            print(json.dumps({'step':idx,'type':'SYSTEM_MESSAGE','status':status,'notification':match.groups() if match else 'background wake'}))
