import os,pathlib,subprocess,time,json,tomllib,shutil,socket,sys
# Usage: python3 driver.py BASE_CHECKOUT HEAD_CHECKOUT
# Each checkout must have dependencies installed. Upload no auth or raw server logs.
ROOT=pathlib.Path(__file__).parent
run=ROOT/time.strftime('run-%Y%m%d-%H%M%S');run.mkdir()
cfg=tomllib.loads((pathlib.Path.home()/'.codex/config.toml').read_text())
home=run/'codex';home.mkdir()
text='model = "gpt-5.1-codex"\nmodel_reasoning_effort = "none"\n'
if cfg.get('openai_base_url'):text+='openai_base_url = '+json.dumps(cfg['openai_base_url'])+'\n'
(home/'config.toml').write_text(text)
shutil.copyfile(pathlib.Path.home()/'.codex/auth.json',home/'auth.json')
env=dict(os.environ,CODEX_HOME=str(home),T3CODE_DEV_SEED='0')
project=run/'project';project.mkdir();subprocess.run(['git','init','-q',str(project)],check=True)
for side,wt in [('before',pathlib.Path(sys.argv[1]).resolve()),('after',pathlib.Path(sys.argv[2]).resolve())]:
 data=run/side;data.mkdir()
 s=socket.socket();s.bind(('127.0.0.1',0));port=s.getsockname()[1];s.close()
 log=open(data/'server.log','w')
 p=subprocess.Popen(['node','apps/server/src/bin.ts','serve','--base-dir',str(data/'state'),'--port',str(port),'--host','127.0.0.1'],cwd=wt,env=env,stdout=log,stderr=subprocess.STDOUT)
 try:
  for i in range(120):
   if p.poll() is not None:raise RuntimeError('server stopped')
   try:
    with socket.create_connection(('127.0.0.1',port),timeout=1):
     if json.loads((data/'state/userdata/server-runtime.json').read_text()).get('port') == port:break
   except (OSError,ValueError):time.sleep(.5)
  commands=[['project','add','--base-dir',str(data/'state'),str(project)],['thread','start','--base-dir',str(data/'state'),'--provider','codex','--model','gpt-6.1-sol','--wait','--json',str(project),'Reply with OK']]
  for n,args in enumerate(commands):
   result=subprocess.run(['node',str(wt/'apps/server/src/bin.ts'),*args],cwd=project,env=env,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,timeout=240)
   (data/f'command-{n}.txt').write_text(result.stdout)
   print(side,n,'exit',result.returncode,result.stdout,flush=True)
 finally:
  p.terminate()
  try:p.wait(timeout=20)
  except subprocess.TimeoutExpired:p.kill();p.wait()
  log.close()
print('RUN',run,flush=True)
