import os,sys,json,time,subprocess,pathlib,urllib.request,signal,datetime
# Usage: python3 reproduce.py <before|after> <checkout> <scratch-directory>
ROOT=pathlib.Path(sys.argv[3]).resolve(); ROOT.mkdir(parents=True, exist_ok=True)
side=sys.argv[1]; checkout=pathlib.Path(sys.argv[2]).resolve()
run=ROOT/(side+'-'+datetime.datetime.now().strftime('%H%M%S')); run.mkdir(); print(run,flush=True)
agent=checkout/'apps/server/scripts/dev-replay-agent.ts'; original=agent.read_text()
# Export only credentials issued to our synthetic replay agents; never upload this private file.
agent.write_text(original.replace('mcp: t3McpServer(params.mcpServers),','mcp: t3McpServer(params.mcpServers),').replace('        return {\n          ...(message.method === "session/new"',f'        NodeFS.appendFileSync({json.dumps(str(run/"credentials.private"))}, JSON.stringify({{cwd, mcp: t3McpServer(params.mcpServers)}})+"\\n");\n        return {{\n          ...(message.method === "session/new"'))
procs=[]
def cli(home,*args):
 p=subprocess.run(['node','apps/server/src/bin.ts',*args,'--base-dir',str(home)],cwd=checkout,capture_output=True,text=True)
 if p.returncode: raise RuntimeError(str(args)+p.stderr+p.stdout)
 return p.stdout

def call(cred,name,args):
 endpoint=cred['endpoint']; headers={'authorization':cred['authorization'],'accept':'application/json, text/event-stream','content-type':'application/json'}
 def post(body):
  req=urllib.request.Request(endpoint,json.dumps({'jsonrpc':'2.0',**body}).encode(),headers)
  with urllib.request.urlopen(req,timeout=120) as r:
   if r.headers.get('mcp-session-id'): headers['mcp-session-id']=r.headers['mcp-session-id']
   t=r.read().decode()
  if not t: return None
  data=next((l[5:] for l in t.splitlines() if l.startswith('data:')),t)
  return json.loads(data)
 post({'id':1,'method':'initialize','params':{'protocolVersion':'2025-06-18','capabilities':{},'clientInfo':{'name':'paging-evidence','version':'1'}}})
 post({'method':'notifications/initialized'})
 r=post({'id':2,'method':'tools/call','params':{'name':name,'arguments':args}})
 if 'error' in r or r.get('result',{}).get('isError'): raise RuntimeError(json.dumps(r))
 return r['result'].get('structuredContent',r['result'])
try:
 homes=[]; workspaces=[]
 for i in range(2):
  home=run/('source' if i==0 else 'peer'); (home/'userdata').mkdir(parents=True)
  settings={'linkedEnvironmentsEnabled':True,'providerInstances':{x:{'driver':x,'enabled':False} for x in ['codex','claudeAgent','cursor','grok','muse','pi','opencode','antigravity']},'defaultModelSelection':{'instanceId':'devReplay','model':'multi-turn'}}
  (home/'userdata/settings.json').write_text(json.dumps(settings))
  port=18741+i+(10 if side=='after' else 0)
  log=open(run/f'server-{i}.private.log','w')
  p=subprocess.Popen(['node','apps/server/src/bin.ts','--port',str(port),'--host','127.0.0.1','--no-browser','--base-dir',str(home),'--dev-url',f'http://127.0.0.1:{port+100}'],cwd=checkout,env={**os.environ,'T3CODE_DEV_SEED':'0','T3CODE_ENVIRONMENT_LABEL':('Source' if i==0 else 'Peer')},stdout=log,stderr=log); procs.append(p)
  for attempt in range(120):
   if (home/'userdata/server-runtime.json').exists(): break
   if p.poll()!=None: raise RuntimeError('server exited '+str(p.returncode))
   time.sleep(1)
  else: raise RuntimeError('server startup timeout')
  workspace=run/('workspace-source' if i==0 else 'workspace-peer'); workspace.mkdir()
  subprocess.run(['git','init','-q',str(workspace)],check=True)
  (workspace/'README.md').write_text('Synthetic pagination evidence\n')
  subprocess.run(['git','-C',str(workspace),'add','.'],check=True)
  subprocess.run(['git','-C',str(workspace),'-c','user.name=Evidence','-c','user.email=evidence@example.invalid','commit','-qm','seed'],check=True)
  print(cli(home,'project','add',str(workspace),'--title',('Source' if i==0 else 'Long history')).strip(),flush=True)
  homes.append(home); workspaces.append(workspace)
 # pair using a freshly minted credential, private to this driver
 pairing=json.loads(cli(homes[1],'auth','pairing','create','--json'))
 (run/'pairing.private.json').write_text(json.dumps(pairing))
 print('pair fields',list(pairing),flush=True)
 token=pairing['credential']
 print(cli(homes[0],'environment','link',f'http://127.0.0.1:{18742+(10 if side=="after" else 0)}','--pairing-code',token,'--access','full-access'),flush=True)
 peer=json.loads(cli(homes[1],'thread','start',str(workspaces[1]),'Synthetic message 01','--provider','devReplay','--model','multi-turn','--title','Pagination history','--wait','--json'))
 thread=peer['threadId']; print('seeded peer',flush=True)
 for n in range(2,26):
  cli(homes[1],'thread','send',thread,f'Synthetic message {n:02d}','--wait','--json')
  print('turn',n,flush=True)
 source=json.loads(cli(homes[0],'thread','start',str(workspaces[0]),'Read linked history','--provider','devReplay','--model','multi-turn','--title','Reader','--wait','--json'))
 creds=[json.loads(l) for l in (run/'credentials.private').read_text().splitlines()]
 cred=next(x['mcp'] for x in creds if x['cwd']==str(workspaces[0]))
 links=call(cred,'t3_environment_links',{})
 (run/'links.private.json').write_text(json.dumps(links))
 print('links shape',str(links)[:600],flush=True)
 env=links['links'][0]['environmentId']
 listed=call(cred,'t3_thread_list',{'environmentId':env,'allProjects':True})
 implicit=call(cred,'t3_thread_read',{'environmentId':env,'threadId':thread,'limit':35})
 explicit=call(cred,'t3_thread_read',{'environmentId':env,'threadId':thread,'limit':35,'beforePosition':9007199254740991})
 result={'side':side,'sha':subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip(),'cursorless':implicit,'explicitNewest':explicit}
 (run/'raw.private.json').write_text(json.dumps(result,indent=2))
 print('READS CAPTURED',run,flush=True)
finally:
 agent.write_text(original)
 # Discover descendants strictly from the processes this driver spawned.
 def descendants(pid):
  found=[]
  try: children=pathlib.Path(f'/proc/{pid}/task/{pid}/children').read_text().split()
  except: children=[]
  for c in children: found+=descendants(int(c))+[int(c)]
  return found
 for p in procs:
  children=descendants(p.pid)
  for pid in children:
   try: os.kill(pid,signal.SIGTERM)
   except ProcessLookupError: pass
  p.terminate()
 for p in procs:
  try:p.wait(timeout=15)
  except subprocess.TimeoutExpired:p.kill();p.wait()
