import subprocess,os,time,json,pathlib,signal,sys
root=pathlib.Path(__file__).parent
run=root/time.strftime('run-%Y%m%d-%H%M%S');run.mkdir()
providers=['claudeAgent','codex']
def snapshot(home):
 out={}
 for name in providers:
  try:
   d=json.loads((home/'caches'/f'{name}.json').read_text())
   out[name]={k:d[k] for k in ['status','installed','checkedAt']};out[name]['auth']=d['auth']['status']
  except (FileNotFoundError,json.JSONDecodeError):out[name]=None
 return out
for side,worktree,sha,port in [('before',sys.argv[1],'fd64128014',16881),('after',sys.argv[2],'5b5a0dd0d1',16882)]:
 home=run/side;home.mkdir()
 def boot():
  log=open(home/'private-server.log','a')
  return subprocess.Popen(['node','apps/server/src/bin.ts','serve','--base-dir',str(home),'--no-browser','--port',str(port)],cwd=worktree,env={**os.environ,'T3CODE_DEV_SEED':'0'},stdout=log,stderr=log,start_new_session=True)
 def stop(p):
  os.kill(p.pid,signal.SIGTERM)
  try:p.wait(timeout=20)
  except subprocess.TimeoutExpired:os.killpg(p.pid,signal.SIGKILL);p.wait()
 p=boot()
 try:
  deadline=time.monotonic()+90
  while time.monotonic()<deadline:
   seed=snapshot(home)
   if all(v and v['status']=='ready' and v['installed'] and v['auth']=='authenticated' for v in seed.values()):break
   if p.poll() is not None:raise RuntimeError('server exited')
   time.sleep(.1)
  else:raise RuntimeError('ready cache not obtained')
 finally:stop(p)
 time.sleep(.5)
 initial=snapshot(home);p=boot();start=time.monotonic();samples=[];events=[];last=None
 try:
  while time.monotonic()-start<15:
   now=round(time.monotonic()-start,3);state=snapshot(home)
   samples.append({'seconds':now,'providers':state})
   if state!=last:
    events.append(samples[-1]);print(side,json.dumps(samples[-1]),flush=True);last=state
   time.sleep(.02)
 finally:stop(p)
 report={'side':side,'commit':sha,'environment':'Linux; real Node server; fresh isolated data; no copied database','pollIntervalMs':20,'initial':initial,'events':events,'samples':samples}
 (run/f'{side}.json').write_text(json.dumps(report,indent=2))
print('OUTPUT',run,flush=True)
