#!/usr/bin/env python3
"""Real T3 dev-server process-lifetime reproduction; synthetic data only.
Usage: python3 prove.py WORKTREE OUTPUT_DIR LABEL SHA
"""
import os, sys, time, json, signal, subprocess, pathlib, datetime
root, out, label, sha = sys.argv[1:]
out = pathlib.Path(out); out.mkdir(parents=True, exist_ok=False)
start = time.monotonic(); records=[]
def emit(message):
    event={'t':round(time.monotonic()-start,3),'message':message}
    records.append(event); print(f"{event['t']:7.3f}s  {message}",flush=True)
    (out/'timeline.json').write_text(json.dumps(records,indent=2))
    (out/'transcript.txt').write_text('\n'.join(f"{e['t']:7.3f}s  {e['message']}" for e in records)+'\n')
fixture=out/'fixture'; fixture.mkdir(); (fixture/'codex').mkdir()
(fixture/'codex'/'config.toml').write_text('[marketplaces.example]\nsource = "git@github.com:example-owner/example-repo.git"\nsource_type = "git"\n')
ssh=fixture/'ssh'; ssh.write_text('''#!/usr/bin/env python3
import os,sys,time,json,signal
if '-G' in sys.argv:
 os.execv('/usr/bin/ssh',['ssh']+sys.argv[1:])
def log(kind, **kw):
 with open(os.environ['PROOF_SSH_LOG'],'a') as f:
  f.write(json.dumps(dict(time=time.monotonic(),kind=kind,pid=os.getpid(),ppid=os.getppid(),pgid=os.getpgrp(),**kw))+'\\n')
def stop(sig,frame):
 log('signal',signal=signal.Signals(sig).name)
 sys.exit(128+sig)
for sig in [signal.SIGTERM,signal.SIGHUP,signal.SIGINT,signal.SIGPIPE]: signal.signal(sig,stop)
log('start',args=sys.argv[1:])
for i in range(20):
 time.sleep(.5)
 log('waiting',elapsed=(i+1)*.5)
log('completed-wait',elapsed=10)
sys.exit(1)
'''); ssh.chmod(0o755)
(fixture/'gitconfig').write_text('[core]\n sshCommand = '+str(ssh)+'\n')
env=os.environ.copy(); env.update(T3CODE_DEV_SEED='0',CODEX_HOME=str(fixture/'codex'),GIT_CONFIG_GLOBAL=str(fixture/'gitconfig'),PROOF_SSH_LOG=str(out/'ssh.jsonl'))
# Do not inherit the hosting T3 instance's credentials or data path.
for key in ['T3CODE_HOME','T3CODE_BASE_DIR','T3CODE_DEV_AUTH_TOKEN','VITE_HTTP_URL','VITE_WS_URL']:
 env.pop(key,None)
log=open(out/'private-server.log','w')
emit(f'{label} | commit {sha[:10]} | Linux | codex-cli 0.169.0')
emit('Fresh T3 state; synthetic SSH marketplace; fake ssh waits 10 seconds.')
emit('Command: T3CODE_DEV_SEED=0 CODEX_HOME=<fixture> GIT_CONFIG_GLOBAL=<fixture> vp run dev')
p=subprocess.Popen(['vp','run','dev'],cwd=root,env=env,stdout=log,stderr=subprocess.STDOUT,start_new_session=True)
tracked={p.pid}; seen=0; first=None; last_state=None; leader=None; sshpid=None

def proc(pid):
 try:
  stat=pathlib.Path(f'/proc/{pid}/stat').read_text(); fields=stat[stat.rfind(')')+2:].split()
  return dict(state=fields[0],ppid=int(fields[1]),pgid=int(fields[2]))
 except (FileNotFoundError,ProcessLookupError): return None
try:
 while time.monotonic()-start<150:
  # Capture descendants of our spawned process before they can be reparented.
  for path in pathlib.Path('/proc').iterdir():
   if path.name.isdigit():
    info=proc(int(path.name))
    if info and info['ppid'] in tracked: tracked.add(int(path.name))
  events=[]
  if (out/'ssh.jsonl').exists():
   for line in (out/'ssh.jsonl').read_text().splitlines():
    try: events.append(json.loads(line))
    except json.JSONDecodeError: pass
  for e in events[seen:]:
   tracked.add(e['pid'])
   if e['kind']=='start':
    first=first or time.monotonic(); leader=e['pgid']; sshpid=e['pid']; tracked.add(leader)
    emit(f"ssh START pid={e['pid']} parent git={e['ppid']} process-group={leader}")
    emit('ssh argv: '+' '.join(e['args']))
   elif e['kind']=='signal': emit(f"ssh RECEIVED {e['signal']}; parent now={e['ppid']} (reparented if git is gone)")
   elif e['kind']=='completed-wait': emit('ssh COMPLETED full 10-second simulated agent wait, without interruption')
  seen=len(events)
  if leader:
   c=proc(leader); s=proc(sshpid)
   state=(c['state'] if c else 'gone',s['state'] if s else 'gone',s['ppid'] if s else None)
   if state!=last_state:
    emit(f'Observed process state: codex={state[0]}, ssh={state[1]}, ssh-parent={state[2]}'); last_state=state
  if first and time.monotonic()-first>14: break
  if p.poll() is not None: emit(f'Dev runner exited unexpectedly: {p.returncode}'); break
  time.sleep(.025)
 if not first: emit('NO SSH START OBSERVED within 150 seconds')
 else: emit('Observation finished before stopping the dev server.')
finally:
 # Stop only the process tree spawned by this driver, including captured detached groups.
 emit('Cleanup: stop captured dev-server process tree.')
 for pid in sorted(tracked,reverse=True):
  if pid==os.getpid(): continue
  try: os.kill(pid,signal.SIGTERM)
  except ProcessLookupError: pass
 try: p.wait(timeout=10)
 except subprocess.TimeoutExpired:
  for pid in tracked:
   try: os.kill(pid,signal.SIGKILL)
   except ProcessLookupError: pass
 log.close()
