import pathlib, subprocess, os, json, time, sys, socket
root=pathlib.Path(__file__).parent
run=root/time.strftime('%Y%m%d-%H%M%S'); run.mkdir()
fake=run/'codex-crash'; fake.write_text('''#!/bin/sh
if [ "$1" = "--version" ]; then
 echo 'codex-cli 0.172.0'
 exit 0
fi
read request
cat >&2 <<'EOF'
thread 'tokio-rt-worker' (51304) has overflowed its stack
memory allocation of 45408 bytes failed
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
EOF
exit 134
'''); fake.chmod(0o755)
for side,checkout in [('before',sys.argv[1]),('after',sys.argv[2])]:
 data=run/side; (data/'userdata').mkdir(parents=True)
 (data/'userdata/settings.json').write_text(json.dumps({'providerInstances':{'codex':{'driver':'codex','config':{'binaryPath':str(fake)}}}}))
 with socket.socket() as sock:
  sock.bind(('127.0.0.1',0)); port=sock.getsockname()[1]
 with (run/(side+'-stdout.log')).open('w') as out:
  p=subprocess.Popen(['node','apps/server/src/bin.ts','--base-dir',str(data),'--host','127.0.0.1','--port',str(port),'--no-browser'],cwd=checkout,env={**os.environ,'T3CODE_DEV_SEED':'0'},stdout=out,stderr=subprocess.STDOUT)
  try:
   trace=data/'userdata/logs/server.trace.ndjson'
   for i in range(120):
    if trace.exists() and 'CodexAppServerProcessExitedError' in trace.read_text(): break
    if p.poll() is not None: break
    time.sleep(.5)
  finally:
   p.terminate()
   try:p.wait(timeout=15)
   except subprocess.TimeoutExpired:p.kill();p.wait()
 lines=trace.read_text().splitlines() if trace.exists() else []
 errors=[l for l in lines if 'CodexAppServerProcessExitedError' in l]
 # Export only synthetic crash diagnostics; never publish unrelated environment logs.
 clean=[]
 for line in errors:
  obj=json.loads(line)
  def visit(x):
   if isinstance(x,dict):
    for k,v in x.items():
     if isinstance(v,str) and ('Codex App Server process exited with code 134' in v):clean.append(v.split("\n")[0])
     else:visit(v)
   elif isinstance(x,list):
    for v in x:visit(v)
  visit(obj)
 summary='\n'.join(dict.fromkeys(clean))
 (run/(side+'-capture.txt')).write_text(summary+'\n')
 print(side,summary,flush=True)
print('ARTIFACTS',run,flush=True)
