"""Drive the real T3 CLI and record the real remote server's activity output.
Run in either checkout after two fresh servers have been linked and B signed into
T3 Connect staging with publishing enabled. No provider or relay is substituted.
Usage: python3 drive.py ROOT SIDE ENVIRONMENT_B PROJECT_B
ROOT holds SIDE/a and SIDE/b server homes and SIDE-b.log server stdout.
"""
import datetime,json,os,pathlib,re,selectors,subprocess,sys,time
root=pathlib.Path(sys.argv[1]);side,env,project=sys.argv[2:5]
out=root/(side+'-'+datetime.datetime.now(datetime.timezone.utc).strftime('%H%M%S'));out.mkdir()
cli=['node','apps/server/src/bin.ts']
prompt=f'Use delegate_task in wait mode to run a remote child on environment {env} in its existing project {project}. Use OpenCode provider opencode model anthropic/claude-haiku-5-5 for the child. The child task is exactly: Reply with the single word DONE. Wait for the child and report its result. Do not run the child locally. Use the linked environment tools to discover the proper project and capabilities if needed.'
(out/'prompt.txt').write_text(prompt)
start=time.monotonic();events=[]
def emit(text):
 elapsed=round(time.monotonic()-start,3)
 events.append([elapsed,'o',text+'\r\n'])
 print(text,flush=True)
with open(root/(side+'-b.log')) as log:
 log.seek(0,2)
 emit('Real T3 server / OpenCode / T3 Connect staging')
 emit('Commit: '+subprocess.check_output(['git','rev-parse','HEAD'],text=True).strip())
 emit('Action: delegate_task remote child, wait mode; child replies DONE')
 p=subprocess.Popen(cli+['thread','start',str(root/side/'a/project'),prompt,'--title','Remote delegation proof','--provider','opencode','--model','anthropic/claude-haiku-5-5','--wait','--json','--base-dir',str(root/side/'a')],stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True)
 doneAt=None;buffer='';child=None
 while time.monotonic()-start<180:
  chunk=log.read()
  if chunk:
   buffer+=chunk
   while '\n' in buffer:
    line,buffer=buffer.split('\n',1)
    # Only activity publisher blocks are public evidence; other logs may hold local paths.
    if re.match(r'^\[.*\] ',line): active='agent activity' in line
    if locals().get('active',False):
     emit(line)
     m=re.search(r"threadId: '([^']+)'",line)
     if m: child=m[1]
  if p.poll() is not None and doneAt is None:
   stdout,stderr=p.communicate();(out/'parent.json').write_text(stdout)
   emit('Parent CLI result: '+stdout.strip());doneAt=time.monotonic()
  if doneAt is not None and time.monotonic()-doneAt>18: break
  time.sleep(.1)
 else:
  p.terminate();emit('Timed out before the real run finished')
 if child:
  result=subprocess.run(cli+['thread','show',child,'--json','--base-dir',str(root/side/'b')],capture_output=True,text=True)
  d=json.loads(result.stdout);(out/'child.json').write_text(json.dumps(d,indent=2))
  emit('Child CLI result: '+json.dumps({'status':d['thread']['status'],'delegatedFrom':d['thread']['delegatedFrom'],'parentThreadId':d['thread']['parentThreadId'],'messages':d['messages']}))
 emit('Capture ended after observing the completed run and activity clearing.')
(out/'recording.cast').write_text(json.dumps({'version':2,'width':140,'height':45,'timestamp':int(time.time())})+'\n'+''.join(json.dumps(e)+'\n' for e in events))
(out/'server-output.txt').write_text('\n'.join(e[2].rstrip() for e in events)+'\n')
print('OUTPUT_DIRECTORY='+str(out))
