"""Run built base/head CLI bundles in an isolated Linux network namespace.
Usage: PROOF_BIND_HOST=<address> python3 reproduce.py BASE_WORKTREE HEAD_WORKTREE OUTPUT_PARENT
Before running, bring up lo and assign PROOF_BIND_HOST to a dummy tailscale0 in
`sudo unshare --net`; no external network, credentials or existing data needed.
Build each checkout first with `vp i` and `vp run build:bundle` in apps/server.
Public transcript captures only CLI connection output; host is redacted.
"""
import os,sys,socket,subprocess,time,select,json,pathlib,re
out=pathlib.Path(sys.argv[3])/str(time.time_ns());out.mkdir()
host=os.environ['PROOF_BIND_HOST']
loop=socket.socket();loop.bind(('127.0.0.1',3773));loop.listen()
try:
 for side,tree in [('before',sys.argv[1]),('after',sys.argv[2])]:
  home=out/side;home.mkdir();start=time.monotonic();events=[]
  def emit(line):
   events.append([round(time.monotonic()-start,3),line]);print(side,line,flush=True)
  sha=subprocess.check_output(['git','rev-parse','HEAD'],cwd=tree,text=True).strip()
  emit('Linux x86_64 | isolated network namespace | Node '+subprocess.check_output(['node','--version'],text=True).strip())
  emit('Commit: '+sha)
  emit('Bind: local Tailscale numeric address on dummy tailscale0 (redacted)')
  emit('127.0.0.1:3773 occupied; <tailscale-ip>:3773 initially free')
  emit('Fresh T3CODE_HOME per commit; T3CODE_PORT unset; no seeded data')
  for run,extra in [('Automatic startup 1',[]),('Automatic restart',[]),('Explicit port control',['--port','3773'])]:
   env={k:v for k,v in os.environ.items() if not k.startswith(('T3CODE_','VITE_'))};env.update(T3CODE_HOME=str(home),T3CODE_DEV_SEED='0',NO_COLOR='1')
   emit('');emit(run+': t3 serve --host <tailscale-ip>'+(' --port 3773' if extra else ''))
   p=subprocess.Popen(['node',tree+'/apps/server/dist/bin.mjs','serve','--host',host,*extra],cwd=tree,env=env,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
   data=b'';end=time.monotonic()+90
   try:
    while time.monotonic()<end:
     if select.select([p.stdout],[],[],1)[0]:
      chunk=os.read(p.stdout.fileno(),65536)
      if not chunk:break
      data+=chunk
      if b'Connection string:' in data:break
    match=re.search(r'Connection string: http://[^\s]+:(\d+)',data.decode(errors='replace'))
    if not match:raise RuntimeError('CLI did not print connection string')
    port=int(match[1]);emit('CLI stdout: '+match[0].replace(host,'<tailscale-ip>'))
    with socket.create_connection((host,port),timeout=3):pass
    emit('TCP connection to announced address: accepted')
   finally:
    p.terminate()
    try:p.wait(timeout=15)
    except subprocess.TimeoutExpired:p.kill();p.wait()
    emit('Server stopped (tracked PID); loopback listener remains occupied')
  (out/(side+'.json')).write_text(json.dumps(events,indent=2))
  (out/(side+'.txt')).write_text('\n'.join(e[1] for e in events)+'\n')
finally:loop.close()
print('OUTPUT',out,flush=True)
