import subprocess, pathlib, os, time, json, sqlite3, signal, sys
ROOT=pathlib.Path(__file__).parent
side=sys.argv[1]; checkout=pathlib.Path(sys.argv[2]); port=sys.argv[3]
out=ROOT/(side+'-'+time.strftime('%Y%m%d-%H%M%S')); out.mkdir()
data=out/'data'; start=time.monotonic(); frames=[]
def emit(s):
 print(s,flush=True); frames.append([round(time.monotonic()-start,2),s])
def cli(*args):
 p=subprocess.run(['node','apps/server/src/bin.ts',*args,'--base-dir',str(data)],cwd=checkout,text=True,capture_output=True)
 if p.returncode: raise RuntimeError(p.stderr or p.stdout)
 return p.stdout.strip()
server=None
log=open(out/'private-server.log','w')
def boot():
 global server
 server=subprocess.Popen(['node','apps/server/src/bin.ts','serve','--base-dir',str(data),'--port',port,'--host','127.0.0.1'],cwd=checkout,env={**os.environ,'T3CODE_DEV_SEED':'0'},stdout=log,stderr=log)
 deadline=time.monotonic()+90
 while time.monotonic()<deadline:
  if (data/'userdata/server-runtime.json').exists():
   try:
    r=json.loads((data/'userdata/server-runtime.json').read_text())
    if r['pid']==server.pid: return
   except Exception: pass
  if server.poll() is not None: raise RuntimeError('Server exited')
  time.sleep(.25)
 raise RuntimeError('Server startup timeout')
def stop():
 server.send_signal(signal.SIGTERM); server.wait(timeout=45)
def show(t): return json.loads(cli('thread','show',t,'--json'))
def ready(t):
 deadline=time.monotonic()+100
 while time.monotonic()<deadline:
  s=show(t)
  if s['thread']['status'] in ('failed','completed','waiting') and any(m['role']=='assistant' for m in s['messages']): return s
  time.sleep(1)
 raise RuntimeError('Thread did not finish initial response')
def snapshot(label,ids):
 result={}
 db=sqlite3.connect('file:'+str(data/'userdata/statev2.sqlite')+'?mode=ro',uri=True)
 for name,t in ids.items():
  s=show(t); th=s['thread']
  tasks=[json.loads(r[0]).get('pendingBackgroundTasks',[]) for r in db.execute('select payload_json from orchestration_v2_projection_provider_threads where thread_id=?',(t,))]
  commands=[]
  for row in db.execute("select payload_json from orchestration_v2_projection_turn_items where thread_id=? and type='command_execution' order by ordinal",(t,)):
   p=json.loads(row[0]); commands.append(p)
  result[name]={'status':th['status'],'runCount':th['runCount'],'messages':[{'role':m['role'],'text':m['text']} for m in s['messages']],'persistedTasks':tasks,'commandItems':commands}
  emit(name+': status='+th['status']+' runs='+str(th['runCount']))
  emit('  persisted pendingBackgroundTasks: '+json.dumps(tasks))
  for m in s['messages']:
   if m['role']=='assistant': emit('  Claude: '+m['text'])
 db.close()
 (out/(label+'.json')).write_text(json.dumps(result,indent=2))
 return result
try:
 sha=subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip()
 emit(side.upper()+' '+sha+' | Linux, real T3 server CLI, Claude haiku')
 boot(); cli('project','add',str(ROOT))
 ids={}
 for name,cmd in [('A multi-operand','sleep 10m 30s && printf done'),('B single-operand control','sleep 630s && printf done')]:
  prompt='Run exactly '+cmd+' using Bash with run_in_background:true. Reply started and end your turn immediately without waiting or checking the task.'
  emit('Start '+name+': '+cmd+' (Bash run_in_background:true)')
  ids[name]=json.loads(cli('thread','start',str(ROOT),prompt,'--provider','claudeAgent','--model','haiku','--title',name,'--json'))['threadId']
 for t in ids.values(): ready(t)
 emit('BEFORE RESTART'); snapshot('before-restart',ids)
 emit('SIGTERM server; wait for exit; restart with same data. No user messages sent.')
 stop(); boot()
 deadline=time.monotonic()+100
 while time.monotonic()<deadline:
  ss=[show(t) for t in ids.values()]
  control=ss[1]
  if control['thread']['runCount']>=2 and control['thread']['status'] in ('completed','failed'):
   if side=='base' or (ss[0]['thread']['runCount']>=2 and ss[0]['thread']['status'] in ('completed','failed')): break
  time.sleep(1)
 emit('AFTER RESTART'); snapshot('after-restart',ids)
 emit('Observed for another 20 seconds without user input.')
 time.sleep(20); snapshot('final',ids)
finally:
 if server is not None and server.poll() is None: stop()
 log.close(); (out/'terminal-recording.json').write_text(json.dumps(frames,indent=2))
 print('ARTIFACT_DIR='+str(out),flush=True)
