import os, pathlib, subprocess, json, time, socket, shutil, sys
ROOT=pathlib.Path(__file__).parent
side=sys.argv[1]; checkout=pathlib.Path(sys.argv[2]); port=int(sys.argv[3])
run=ROOT/(side+'-'+str(time.time_ns()));run.mkdir()
home=run/'home'; (home/'userdata').mkdir(parents=True)
appdir=run/'AppDir';(appdir/'usr/bin').mkdir(parents=True)
(appdir/'usr/bin/python3').symlink_to('/usr/bin/python3')
real_codex=shutil.which('codex'); node=shutil.which('node')
probe=run/'codex-launch'; result=run/'launch.jsonl'
probe.write_text('''#!/usr/bin/python3
import os,sys,json,subprocess
keys=['APPIMAGE','APPDIR','ARGV0','OWD','ELECTRON_RUN_AS_NODE','PROOF_HOST_VALUE','PROOF_CONFIG_VALUE']
entry={'args':sys.argv[1:],'environment':{k:os.environ.get(k) for k in keys},'python':subprocess.check_output(['/usr/bin/zsh','-c',"python3 -c 'import sys; print(sys.executable)'"],text=True).strip()}
with open('''+repr(str(result))+''','a') as f:f.write(json.dumps(entry)+'\\n')
os.execv('''+repr(real_codex)+''',['codex',*sys.argv[1:]])
''');probe.chmod(0o755)
settings={'providerInstances':{'codex':{'driver':'codex','enabled':True,'config':{'binaryPath':str(probe)},'environment':[{'name':'PROOF_CONFIG_VALUE','value':'configured-kept','sensitive':False}]}},'defaultModelSelection':{'instanceId':'codex','model':os.environ['PROOF_MODEL']}}
(home/'userdata/settings.json').write_text(json.dumps(settings))
env=dict(os.environ,T3CODE_DEV_SEED='0',T3CODE_TELEMETRY_ENABLED='false',SHELL='/usr/bin/zsh',APPIMAGE=str(run/'T3.AppImage'),APPDIR=str(appdir),ARGV0='T3.AppImage',OWD=str(run),ELECTRON_RUN_AS_NODE='1',PROOF_HOST_VALUE='host-kept')
env['PATH']=str(appdir/'usr/bin')+':'+env['PATH']
serverlog=open(run/'server-private.log','w')
server=subprocess.Popen([node,'apps/server/src/bin.ts','serve','--base-dir',str(home),'--host','127.0.0.1','--port',str(port),'--no-browser'],cwd=checkout,env=env,stdout=serverlog,stderr=subprocess.STDOUT)
(run/'pid').write_text(str(server.pid)); print('Real T3 Code server / Linux / '+side+' / synthetic AppImage runtime',flush=True)
print('Fresh isolated database; starting server and creating project...',flush=True)
try:
 for i in range(120):
  if server.poll() is not None: raise RuntimeError('server exited: '+str(server.returncode))
  try:
   with socket.create_connection(('127.0.0.1',port),timeout=1):
    if (home/'userdata/server-runtime.json').exists():break
    time.sleep(1)
  except OSError:time.sleep(1)
 else:raise RuntimeError('server did not bind')
 workspace=run/'workspace';workspace.mkdir();subprocess.run(['git','init','-q',str(workspace)],check=True)
 (workspace/'README.md').write_text('Synthetic environment proof workspace.\n')
 subprocess.run(['git','-C',str(workspace),'add','.'],check=True)
 subprocess.run(['git','-C',str(workspace),'-c','user.name=Proof','-c','user.email=proof@example.invalid','commit','-qm','Initial'],check=True)
 def cli(args,timeout=120):
  p=subprocess.run([node,'apps/server/src/bin.ts',*args,'--base-dir',str(home)],cwd=checkout,text=True,capture_output=True,timeout=timeout)
  with open(run/'cli-private.log','a') as f:f.write(p.stdout+p.stderr)
  print('CLI',args[:2],'exit',p.returncode,flush=True)
  return p
 added=cli(['project','add',str(workspace),'--title','Environment proof'])
 if added.returncode:raise RuntimeError('project creation failed; see private log')
 command='/usr/bin/zsh -c \'for name in APPIMAGE APPDIR ARGV0 OWD ELECTRON_RUN_AS_NODE PROOF_HOST_VALUE PROOF_CONFIG_VALUE; do printf "%s=" "$name"; printenv "$name" || printf "<absent>\\n"; done; printf "python3 sys.executable="; python3 -c "import sys; print(sys.executable)"\''
 prompt='Use exec_command with login=false. Execute exactly this command once, without changing or unsetting environment values. Do not run other commands. Report its output verbatim. Command: '+command
 print('Starting fresh Codex thread; asking agent to inspect environment and Python...',flush=True)
 p=cli(['thread','start',str(workspace),prompt,'--title','Environment proof','--provider','codex','--model',os.environ['PROOF_MODEL'],'--wait','--json'],timeout=180)
 import sqlite3
 def sanitize(value):return value.replace(str(appdir),'<AppDir>').replace(str(run),'<Run>')
 print('\nPROVIDER PROCESS ENVIRONMENT (launch wrapper; no environment changes)',flush=True)
 entries=[json.loads(line) for line in result.read_text().splitlines()]
 for entry in entries:
  if entry['args']==['app-server']:
   for k,v in entry['environment'].items():print(k+'='+sanitize(v if v is not None else '<absent>'),flush=True)
   print('python3 sys.executable='+sanitize(entry['python']),flush=True)
   break
 print('\nREAL AGENT SHELL OUTPUT (persisted command event)',flush=True)
 db=sqlite3.connect('file:'+str(home/'userdata/statev2.sqlite')+'?mode=ro',uri=True)
 events=[]
 for (payload,) in db.execute("select payload_json from orchestration_v2_projection_turn_items where type='command_execution' order by ordinal"):
  item=json.loads(payload)
  if item.get('input')=='Preparing workspace':continue
  events.append({k:item.get(k) for k in ['input','output','exitCode']})
  print(sanitize(item.get('output','')),flush=True)
  print('Command exit code: '+str(item.get('exitCode')),flush=True)
 db.close()
 print('Turn status: '+str(json.loads(p.stdout).get('status')),flush=True)
 (run/'public-observations.json').write_text(sanitize(json.dumps({'launch':entries,'commands':events,'turnStatus':json.loads(p.stdout).get('status')},indent=2)))
 print('Paths normalized: <AppDir> is the synthetic AppImage directory; <Run> is the isolated run directory.',flush=True)
 print('AI-assisted; verified with the tests and tools listed above.',flush=True)
finally:
 server.terminate()
 try:server.wait(timeout=20)
 except subprocess.TimeoutExpired:server.kill();server.wait()
 serverlog.close()
