import sys,subprocess,pathlib,json,sqlite3
work=pathlib.Path(sys.argv[1]);out=pathlib.Path(sys.argv[2]);side=sys.argv[3]
thread=json.loads((out/'launch-result.json').read_text())['threadId']
db=sqlite3.connect(f'file:{work}/.t3/userdata/statev2.sqlite?mode=ro',uri=True)
def git(cwd,*args):return subprocess.check_output(['git',*args],cwd=cwd,text=True).strip()
parent=json.loads(db.execute('select payload_json from orchestration_v2_projection_threads where thread_id=?',(thread,)).fetchone()[0]);folder=pathlib.Path(parent['worktreePath']);markers={f'repo{n}':git(folder/f'repo{n}','rev-parse','HEAD') for n in [1,3]}
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',(thread,))]
delegate=[d for d in items if d.get('toolName','').endswith('delegate_task')]
children=[json.loads(row[0]) for row in db.execute('select payload_json from orchestration_v2_projection_threads') if json.loads(row[0]).get('lineage',{}).get('parentThreadId')==thread]
result={'side':side,'parent':{'branch':parent['branch'],'entries':sorted(p.name for p in folder.iterdir()),'markers':markers},'delegateCalls':[{'input':d.get('input'),'output':d.get('output')} for d in delegate],'children':[]}
for child in children:
 cwd=pathlib.Path(child['worktreePath']);repos={}
 for r in cwd.iterdir():
  if r.name.startswith('repo') and r.is_dir():
   repos[r.name]={'head':git(r,'rev-parse','HEAD'),'latestCommit':git(r,'log','-1','--format=%s'),'parentMarkerExists':(r/'PARENT_ONLY.txt').exists()}
 result['children'].append({'branch':child['branch'],'entries':sorted(p.name for p in cwd.iterdir()),'repositories':repos,'ls':subprocess.check_output(['ls','-la'],cwd=cwd,text=True)})
 childitems=[json.loads(row[0]) for row in db.execute('select payload_json from orchestration_v2_projection_turn_items where thread_id=? order by ordinal',(child['id'],))]
 result['children'][-1]['commands']=[{k:d[k] for k in ['input','output','exitCode'] if k in d} for d in childitems if d['type']=='command_execution' and d.get('input')!='Preparing workspace']
(out/'result.raw.json').write_text(json.dumps(result,indent=2));print(out,flush=True)
