import subprocess,sys,json,sqlite3,time,pathlib,datetime
worktree,project,prompt_file,out=sys.argv[1:]
folder=pathlib.Path(out)/datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')
folder.mkdir(parents=True)
prompt=pathlib.Path(prompt_file).read_text()
cli=['node','apps/server/src/bin.ts','thread','start',project,prompt,'--provider','claudeAgent','--model','claude-haiku-5-5','--title','Delegation final wake proof','--base-dir','.t3','--json']
r=subprocess.run(cli,cwd=worktree,capture_output=True,text=True,check=True)
launched=json.loads(r.stdout)
parent=launched['threadId']
print(json.dumps({'threadId':parent,'output':str(folder)}),flush=True)
db=sqlite3.connect('file:'+worktree+'/.t3/userdata/statev2.sqlite?mode=ro',uri=True)
seen=set(); child=None
with (folder/'transcript.txt').open('w') as log:
 def emit(s):
  print(s,flush=True);log.write(s+'\n');log.flush()
 sha=subprocess.check_output(['git','rev-parse','HEAD'],cwd=worktree,text=True).strip()
 emit('Commit: '+sha)
 emit('Real server, fresh isolated T3 home; Claude Haiku 5.5 parent and child; shared async delegation.')
 deadline=time.monotonic()+240
 while time.monotonic()<deadline:
  subs=[json.loads(x[0]) for x in db.execute('select payload_json from orchestration_v2_projection_subagents where thread_id=?',(parent,))]
  if subs: child=subs[0]['childThreadId']
  for row in db.execute('select thread_id,created_at,role,run_id,payload_json from orchestration_v2_projection_messages where thread_id in (?,?) order by created_at',(parent,child or '')):
   tid,ts,role,run,payload=row; m=json.loads(payload)
   if role=='assistant' and not m.get('streaming') or m.get('notification'):
    text=m.get('text','');note=m.get('notification')
    if note: text=json.dumps(note)
    key=(tid,run,text)
    if key not in seen and text:
     seen.add(key)
     ordinal=db.execute('select ordinal from orchestration_v2_projection_runs where run_id=?',(run,)).fetchone()
     emit(ts+' '+('PARENT' if tid==parent else 'CHILD')+' run '+str(ordinal[0] if ordinal else '?')+' '+role+': '+text)
  if subs and subs[0]['status']=='completed':
   result=subs[0].get('result');key=('result',result)
   if key not in seen:seen.add(key);emit('TASK completed result: '+str(result))
   messages=[json.loads(x[0]) for x in db.execute("select payload_json from orchestration_v2_projection_messages where thread_id=? and role='assistant'",(parent,))]
   if any('GOT:' in x.get('text','') and not x.get('streaming') for x in messages):break
  time.sleep(1)
 else: emit('Stopped after 240 seconds without final parent reply')
