#!/usr/bin/python3
"""Record a live, read-only transcript of the real T3 server and Codex.
Usage: headless-desktop python3 capture.py CHECKOUT SCRATCH SIDE PORT
The sibling driver.ts is temporarily copied into the checkout's CLI directory.
All databases are fresh; no production state or credentials are copied.
"""
import os, sys, time, subprocess as sp, sqlite3, json, threading, re
from pathlib import Path
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GLib
checkout, scratch, side, port = sys.argv[1:]
checkout=Path(checkout); scratch=Path(scratch)
out=scratch/(side+'-'+time.strftime('%Y%m%d-%H%M%S'));out.mkdir()
home=out/'home'; db=home/'userdata/statev2.sqlite'
sha=sp.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip()
window=Gtk.Window();window.set_default_size(1400,900);window.move(0,0)
view=Gtk.TextView();view.set_editable(False);view.set_cursor_visible(False);view.set_monospace(True)
view.set_left_margin(30);view.set_top_margin(25);view.set_wrap_mode(Gtk.WrapMode.WORD_CHAR)
css=Gtk.CssProvider();css.load_from_data(b'textview,textview text {background:#111827;color:#e5e7eb;font:18px monospace;}')
view.get_style_context().add_provider(css,600);window.add(view);window.show_all()
start=time.monotonic(); transcript=[]
def clean(s):
 s=str(s).replace(str(home),'<server-home>').replace(str(scratch/'repo'),'<project-root>').replace(str(scratch),'<scratch>').replace(str(checkout),'<checkout>')
 return s
def emit(s):
 line=f'{time.monotonic()-start:5.1f}s  '+clean(s)
 transcript.append(line)
 def add():
  b=view.get_buffer();b.insert(b.get_end_iter(),line+'\n');return False
 GLib.idle_add(add)
 (out/'transcript.txt').write_text('\n'.join(transcript)+'\n')
def command(args,**kw):return sp.run(args,cwd=checkout,check=True,capture_output=True,text=True,**kw)
def worker():
 server=None; rec=None; driver=None
 try:
  emit(f'{side.upper()} | commit {sha[:10]} | Linux | Codex CLI 0.172.0')
  emit('Real server / MCP runtime transcript (not a replay or a unit test)')
  emit('Fresh database; local bare origin; upload-pack delays fetch by 4 seconds.')
  env=os.environ.copy();env['T3CODE_DEV_SEED']='0'
  server=sp.Popen(['node','apps/server/src/bin.ts','serve','--base-dir',str(home),'--port',port,str(scratch/'repo')],cwd=checkout,env=env,stdout=open(out/'server-private.log','w'),stderr=sp.STDOUT)
  for _ in range(200):
   if (home/'userdata/server-runtime.json').exists():break
   if server.poll() is not None:raise RuntimeError('server stopped')
   time.sleep(.1)
  command(['node','apps/server/src/bin.ts','project','add',str(scratch/'repo'),'--base-dir',str(home)])
  target=checkout/'apps/server/src/cli/zzProof44106.ts';target.write_text((scratch/'driver.ts').read_text())
  rec=sp.Popen(['ffmpeg','-y','-loglevel','error','-f','x11grab','-video_size','1400x900','-framerate','5','-i',os.environ['DISPLAY'],'-c:v','libx264','-preset','ultrafast','-pix_fmt','yuv420p',str(out/'recording.mp4')],stdin=sp.PIPE)
  emit('Launch: worktree, baseRef=origin/main, startFromOrigin=true, no message')
  log=open(out/'driver-private.log','w')
  driver=sp.Popen(['node',str(target),'--base-dir',str(home),'--provider','codex','--model','gpt-6.1-sol','--message','Run `pwd`, then `sleep 20`, then reply with the pwd output','--polls','9'],cwd=checkout,stdout=log,stderr=sp.STDOUT)
  seen=set(); final_reply=False; status=None; worktree=None
  deadline=time.monotonic()+80
  while time.monotonic()<deadline:
   text=(out/'driver-private.log').read_text()
   for key,desc in [('launch ->','Launch returned: runId=null'),('worktreePath at send = null','Immediate send: worktreePath=null; request pwd, sleep 20, then reply'),('send ->','Send returned: run accepted')]:
    if key in text and key not in seen:seen.add(key);emit(desc)
   try:
    con=sqlite3.connect(f'file:{db}?mode=ro',uri=True)
    # The only thread is synthetic, created above by the real MCP launch tool.
    for row in con.execute("select json_extract(payload_json, '$.worktreePath') from orchestration_v2_projection_threads"):
     if row[0] and row[0]!=worktree:worktree=row[0];emit('Worktree bound: '+worktree)
    for row in con.execute('select status from orchestration_v2_projection_runs'):
     if row[0]!=status:status=row[0];emit('Run status: '+status)
    for id,typ,st,payload in con.execute("select turn_item_id,type,status,payload_json from orchestration_v2_projection_turn_items where type in ('command_execution','assistant_message') order by ordinal"):
     p=json.loads(payload); key=(id,st,p.get('text'),p.get('output'))
     if key in seen:continue
     seen.add(key)
     if typ=='command_execution':emit('Codex command ['+st+']: '+p.get('input','')+ (' → '+p['output'].strip() if p.get('output') else ''))
     elif p.get('phase')=='final_answer':final_reply=True;emit('RECORDED FINAL REPLY: '+p.get('text','').replace('```','').strip())
    for id,payload in con.execute("select effect_id,payload_json from orchestration_v2_effect_outbox where effect_type='provider-session.detach'"):
     if id not in seen:seen.add(id);emit('OUTBOX provider-session.detach: '+json.loads(payload).get('detail',str(json.loads(payload))))
    con.close()
   except sqlite3.OperationalError as e:
    emit('Monitor error: '+str(e));raise
   if driver.poll() is not None:break
   time.sleep(.2)
  emit('Observation complete. Final run status: '+str(status))
  emit('Recorded final assistant reply: '+('YES' if final_reply else 'NO'))
  emit('Paths above are aliases for the synthetic project and its server data.')
  (out/'result.json').write_text(json.dumps(dict(side=side,sha=sha,status=status,finalReply=final_reply,worktree=clean(worktree)),indent=2))
  time.sleep(2)
  for name in ['capture-a.png','capture.png']:
   sp.run(['import','-display',os.environ['DISPLAY'],'-window','root','-crop','1400x900+0+0',str(out/name)],check=True)
   time.sleep(.5)
  assert (out/'capture-a.png').read_bytes()==(out/'capture.png').read_bytes(), 'Final capture not stable'
 except Exception as e:
  emit('CAPTURE FAILED: '+str(e));time.sleep(2)
 finally:
  if rec:rec.communicate(b'q\n',timeout=10)
  if driver and driver.poll() is None:driver.terminate();driver.wait(timeout=10)
  if server:server.send_signal(2);server.wait(timeout=30)
  GLib.idle_add(Gtk.main_quit)
threading.Thread(target=worker,daemon=True).start();Gtk.main()
print(out)
