"""Real ACP recovery proof. GOOGLE_GEMINI_BASE_URL must point to the API gateway.
Usage: python3 driver.py CHECKOUT OUTPUT_DIRECTORY PORT
Requires agy 1.5.20 and Node. Uses only fresh synthetic data.
"""
import os,sys,pathlib,json,subprocess,time,sqlite3,shlex
work=pathlib.Path(sys.argv[1]);out=pathlib.Path(sys.argv[2]);out.mkdir(parents=True,exist_ok=False);data=out/'data';settings=data/'userdata';settings.mkdir(parents=True)
wrapper=out/'agy'
wrapper.write_text('#!/bin/sh\nexec strace -f -e trace=read -e trace-fds=0 -e inject=read:delay_exit=100ms -s 65536 -o '+shlex.quote(str(out/'agy-trace'))+'.$$ agy "$@"\n');wrapper.chmod(0o755)
(settings/'settings.json').write_text(json.dumps({'providerInstances':{'antigravity':{'driver':'antigravity','enabled':True,'config':{'authMethod':'gemini-api-key','apiKey':'synthetic-proof-key','binaryPath':str(wrapper)}}}}))
cli=['node','apps/server/src/bin.ts'];env=dict(os.environ,T3CODE_DEV_SEED='0')
log=(out/'server.log').open('w');server=subprocess.Popen(cli+['serve','--base-dir',str(data),'--port',sys.argv[3]],cwd=work,env=env,stdout=log,stderr=log)
def call(args):
 p=subprocess.run(cli+args+['--base-dir',str(data)],cwd=work,env=env,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,timeout=180)
 return p

def agents():
 result=[]
 for p in pathlib.Path('/proc').iterdir():
  if not p.name.isdigit():continue
  try:
   argv=(p/'cmdline').read_bytes().split(b'\0')
   if len(argv)>2 and argv[1]==b'acp' and str(data).encode() in b' '.join(argv):result.append(int(p.name))
  except OSError:pass
 return result
try:
 print('Starting real T3 server on a fresh database.',flush=True)
 deadline=time.monotonic()+60
 while not (data/'userdata/server-runtime.json').exists():
  assert server.poll() is None,'Server exited'
  assert time.monotonic()<deadline,'Server startup timeout'
  time.sleep(.1)
 p=call(['project','add',str(out),'--title','ACP recovery proof']);assert p.returncode==0,p.stdout
 p=call(['thread','start',str(out),'Remember the word ORCHARD. Reply READY only.','--provider','antigravity','--model','gemini-3.8-flash','--wait','--json']);(out/'turn1.json').write_text(p.stdout);v=json.loads(p.stdout);assert v['status']=='completed',p.stdout;tid=v['threadId']
 print('Turn 1: Remember ORCHARD. Result: '+v['reply'],flush=True)
 for pid in agents():os.kill(pid,9)
 p=call(['thread','send',tid,'Reply READY only.','--wait','--json']);(out/'warm.json').write_text(p.stdout);v=json.loads(p.stdout);assert v['status']=='completed',p.stdout
 print('Warm-up: stopped owned agy; next turn loaded the saved session and completed.',flush=True)
 db=sqlite3.connect('file:'+str(data/'userdata/statev2.sqlite')+'?mode=ro',uri=True);native=None
 for row in db.execute('select * from orchestration_v2_projection_provider_threads'):
  for c in row:
   if isinstance(c,str) and c.startswith('{'):
    v=json.loads(c)
    if v.get('appThreadId')==tid:native=v['nativeThreadRef']['nativeId']
 db.close();assert native
 seen=set(out.glob('agy-trace.*'))
 eventlog=next((data/'userdata/logs/provider').glob('events.'+tid.replace(':','-')+'.log'));offset=eventlog.stat().st_size
 for pid in agents():os.kill(pid,9)
 print('Stopped owned agy again. Sending: Reply KIWI, then the word I asked you to remember.',flush=True)
 p=subprocess.Popen(cli+['thread','send',tid,'Reply KIWI, then the word I asked you to remember.','--wait','--json','--base-dir',str(data)],cwd=work,env=env,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)
 killed=False;deadline=time.monotonic()+180
 while p.poll() is None:
  recent=b''.join(f.read_bytes() for f in set(out.glob('agy-trace.*'))-seen)
  if not killed and b'session/load' in recent:
   tracer=next(f for f in set(out.glob('agy-trace.*'))-seen if b'session/load' in f.read_bytes())
   children=pathlib.Path('/proc/'+tracer.name.split('.')[-1]+'/task/'+tracer.name.split('.')[-1]+'/children').read_text().split()
   for child in children:
    pid=int(child)
    assert str(data).encode() in pathlib.Path(f'/proc/{pid}/cmdline').read_bytes()
    os.kill(pid,9);killed=True;print('SIGKILL: real replacement agy had session/load in flight (strace of real stdin read).',flush=True)
  if time.monotonic()>deadline:p.terminate();raise RuntimeError('Turn timeout')
  time.sleep(.0001)
 raw=p.communicate()[0];(out/'turn3.txt').write_text(raw)
 v=json.loads(raw.splitlines()[0]);print('Result: '+v['status']+' | reply: '+str(v['reply']),flush=True)
 if v['error']:print('Error: '+v['error'],flush=True)
 print('CLI exit: '+str(p.returncode),flush=True)
 deadline=time.monotonic()+10
 while b'"method":"session/load","status":"failed"' not in eventlog.read_bytes()[offset:] and time.monotonic()<deadline:time.sleep(.05)
 events=[]
 for line in eventlog.read_bytes()[offset:].decode().splitlines():
  event=json.loads(line[line.index('{'):])['event'];payload=event.get('payload',{})
  if event.get('kind')=='request':events.append({k:payload[k] for k in ('method','status','errorTag') if k in payload})
 (out/'protocol.json').write_text(json.dumps(events,indent=2))
 load=[e for e in events if e.get('method')=='session/load'];assert any(e['status']=='failed' for e in load),'Not a failed session/load'
 print('Protocol confirmed: session/load failed with AcpProcessExitedError before prompt.',flush=True)
 recovered='Recovering provider context in a fresh native session' in (out/'server.log').read_text()
 print('Fresh-session recovery logged: '+str(recovered),flush=True)
 (out/'result.json').write_text(json.dumps({'result':v,'crashInjected':killed,'recovered':recovered,'protocol':events},indent=2))
finally:
 for pid in agents():
  try:os.kill(pid,15)
  except ProcessLookupError:pass
 server.terminate()
 try:server.wait(timeout=15)
 except subprocess.TimeoutExpired:server.kill();server.wait()
 log.close()
