import os,sys,time,json,subprocess,socket,threading,datetime
from pathlib import Path
from PIL import Image,ImageDraw,ImageFont
side,checkout,run,project,port=sys.argv[1:];run=Path(run);port=int(port)
run.mkdir(parents=True,exist_ok=True);frames=run/'frames';frames.mkdir()
sha=subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip()
phase='Starting real T3 server'; apppid=None; done=False; observations=[]; history=[]; last=None; started=time.monotonic()
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',20)
small=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',17)
def utc():return datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='seconds')
def proc():
 rows={}
 for p in Path('/proc').iterdir():
  if not p.name.isdigit():continue
  try:rows[int(p.name)]=(int((p/'stat').read_text().split()[3]),(p/'cmdline').read_bytes().split(b'\0'))
  except (OSError,ValueError,IndexError):pass
 return rows
def census():
 rows=proc();return sorted(pid for pid,(pp,args) in rows.items() if pp==apppid and any(b'server-filesystem/dist/index.js' in a for a in args))
def record():
 global last
 with (run/'census.ndjson').open('w',buffering=1) as f:
  n=0
  while not done:
   pids=census() if apppid else [];stamp=utc();alive=apppid is not None and Path('/proc/'+str(apppid)).exists()
   row=dict(utc=stamp,elapsed=round(time.monotonic()-started,1),phase=phase,appServerPid=apppid,appServerAlive=alive,mcpPids=pids);f.write(json.dumps(row)+'\n')
   key=(phase,tuple(pids))
   if key!=last:history.append(stamp[11:19]+' '+phase+' | MCP '+str(pids));last=key
   im=Image.new('RGB',(1280,720),'#101722');d=ImageDraw.Draw(im)
   lines=[f'{side.upper()} | T3 {sha[:10]} | Codex CLI 0.174.0',f'UTC {stamp} | elapsed {row["elapsed"]}s',f'Phase: {phase}',f'Shared app-server: {apppid} | alive: {alive}',f'Live stdio MCP processes: {len(pids)} | PIDs: {pids}','','Observed transitions:']
   for i,l in enumerate(lines):d.text((28,24+i*32),l,font=font,fill='#e7edf6')
   for i,l in enumerate(history[-10:]):d.text((28,256+i*30),l[:115],font=small,fill='#bcd1ea')
   d.text((28,632),'Linux | real T3 CLI/server | gpt-6.1-sol through hub',font=small,fill='#a8bfd8')
   d.text((28,664),'Real filesystem MCP server. Live /proc capture, 1 frame/second.',font=small,fill='#a8bfd8')
   im.save(frames/f'{n:05d}.png');n+=1;time.sleep(1)
def cli(*args):
 p=subprocess.run(['node','apps/server/src/bin.ts',*args,'--base-dir',str(run/'t3')],cwd=checkout,capture_output=True,text=True,timeout=180)
 # Commands use synthetic prompts; paths are omitted from the public command log.
 with (run/'commands.ndjson').open('a') as f:f.write(json.dumps(dict(utc=utc(),command=list(args[:2]),exit=p.returncode,stdout=p.stdout if args[0]=='thread' else 'project added',stderr=p.stderr.replace(str(run),'$RUN').replace(project,'$PROJECT')))+'\n')
 if p.returncode:raise RuntimeError('CLI failed: '+p.stderr)
 return p.stdout
def protocol():
 events=[]
 for f in (run/'t3/userdata/logs/provider').glob('*.log'):
  for l in f.read_text().splitlines():
   try:j=json.loads(l.split('NTIVE: ',1)[1]);e=j.get('event',{});p=e.get('payload',{});par=p.get('params',{});m=p.get('method');item=par.get('item',{})
   except:continue
   if m=='thread/unsubscribe':events.append(dict(utc=l[1:25],direction=e.get('direction'),method=m,threadId=par.get('threadId')))
   elif item.get('type')=='subAgentActivity':events.append(dict(utc=l[1:25],direction=e.get('direction'),method=m,kind=item.get('kind'),threadId=par.get('threadId'),agentThreadId=item.get('agentThreadId')))
 return sorted(events,key=lambda x:x['utc'])
def idle(root,previous):
 deadline=time.monotonic()+210
 while time.monotonic()<deadline:
  if sum(e.get('method')=='thread/unsubscribe' and e.get('threadId')==root for e in protocol())>previous:return
  time.sleep(1)
 raise RuntimeError('Root idle unsubscribe did not arrive')
def settle(label):
 global phase
 phase=label;time.sleep(20)
 observations.append(dict(phase=phase,utc=utc(),appServerPid=apppid,mcpPids=census(),protocol=protocol()))
env=os.environ.copy()
for k in ['ASCII_TOKEN','ASCII_API_URL','CODEX_SESSION_ID','CODEX_THREAD_ID']:env.pop(k,None)
env.update(CODEX_HOME=str(run/'codex'),T3CODE_DEV_SEED='0')
log=(run/'server.log').open('w')
server=subprocess.Popen(['node','apps/server/src/bin.ts','serve','--base-dir',str(run/'t3'),'--port',str(port),'--host','127.0.0.1'],cwd=checkout,env=env,stdout=log,stderr=subprocess.STDOUT)
t=threading.Thread(target=record);t.start()
try:
 for _ in range(120):
  try:
   with socket.create_connection(('127.0.0.1',port),timeout=1):break
  except OSError:time.sleep(1)
 else:raise RuntimeError('Server startup timeout')
 cli('project','add',project,'--title','MCP cleanup proof')
 phase='Starting keepalive thread'
 keep=json.loads(cli('thread','start',project,'Use exec_command to run sleep 1500 with yield_time_ms=1000, then wait for that command until it finishes. Do not finish your turn before it completes. This keeps the shared provider alive for a process cleanup reproduction.','--title','Keepalive','--provider','codex','--model','gpt-6.1-sol','--option','reasoningEffort=low','--json'))
 # Capture the app-server descended from the server PID that this driver spawned.
 for _ in range(60):
  rows=proc();desc={server.pid}
  for i in range(10):desc.update(pid for pid,(pp,args) in rows.items() if pp in desc)
  matches=list({pp for pid,(pp,args) in rows.items() if pid in desc and any(b'server-filesystem/dist/index.js' in a for a in args)})
  if matches:apppid=matches[0];break
  time.sleep(1)
 if apppid is None:raise RuntimeError('No real Codex app-server found')
 prompt='Spawn exactly one native subagent with fork_turns="none" (a fresh context). Ask it to read README.md using filesystem MCP and return its first line. Wait for its result, leave it open, and return that line. Do not use close_agent.'
 phase='Cycle 1: spawn one native child'
 result=json.loads(cli('thread','start',project,prompt,'--title','Subagent cleanup','--provider','codex','--model','gpt-6.1-sol','--option','reasoningEffort=low','--wait','--json'))
 thread=result['threadId'];events=protocol();root=next(e['threadId'] for e in events if e.get('kind')=='started')
 phase='Cycle 1: waiting for idle release';idle(root,0);settle('Cycle 1: 20s after idle release')
 phase='Cycle 2: resume and spawn one child'
 result=json.loads(cli('thread','send',thread,prompt,'--wait','--json'))
 phase='Cycle 2: waiting for idle release';idle(root,1);settle('Cycle 2: 20s after idle release')
 phase='Completed both idle-release cycles';time.sleep(5)
 (run/'result.json').write_text(json.dumps(dict(side=side,sha=sha,codexVersion='0.174.0',rootThreadId=root,keepaliveThreadId=keep['threadId'],observations=observations,protocol=protocol()),indent=2))
 print(json.dumps(dict(side=side,counts=[len(x['mcpPids']) for x in observations],result='completed')),flush=True)
finally:
 done=True;t.join();server.terminate()
 try:server.wait(timeout=20)
 except subprocess.TimeoutExpired:server.kill();server.wait()
 # apppid was captured from this spawned server, never a name-based kill.
 if apppid and Path('/proc/'+str(apppid)).exists():
  try:os.kill(apppid,15)
  except ProcessLookupError:pass
 log.close()
