import os, sys, json, time, subprocess, urllib.request, pathlib, re, signal, sqlite3
ROOT=pathlib.Path(__file__).parent
checkout=pathlib.Path(sys.argv[1]); side=sys.argv[2]
run=ROOT/(side+'-'+time.strftime('%Y%m%d-%H%M%S')); run.mkdir()
env=dict(os.environ,T3CODE_DEV_SEED='0',T3CODE_DISABLE_ANALYTICS='1')
servers=[]
def cli(home,*args,timeout=180):
 p=subprocess.run(['node',str(checkout/'apps/server/src/bin.ts'),*args,'--base-dir',str(home)],cwd=checkout,env=env,capture_output=True,text=True,timeout=timeout)
 if p.returncode: raise RuntimeError(f'CLI {args[0:2]} failed: {p.stdout}\n{p.stderr}')
 return p.stdout
class MCP:
 def __init__(self,port,token):
  self.url=f'http://127.0.0.1:{port}/mcp'; self.headers={'Authorization':'Bearer '+token,'Content-Type':'application/json','Accept':'application/json, text/event-stream'}; self.n=0
  self.rpc('initialize',{'protocolVersion':'2025-06-18','capabilities':{},'clientInfo':{'name':'issue-36956-proof','version':'1'}})
  self.rpc('notifications/initialized',{},notify=True)
 def rpc(self,method,params,notify=False):
  self.n+=1; body={'jsonrpc':'2.0','method':method,'params':params}
  if not notify: body['id']=self.n
  req=urllib.request.Request(self.url,json.dumps(body).encode(),self.headers)
  try: r=urllib.request.urlopen(req,timeout=180)
  except urllib.error.HTTPError as e: raise RuntimeError(str(e)+' '+e.read().decode())
  with r:
   if r.headers.get('mcp-session-id'): self.headers['mcp-session-id']=r.headers['mcp-session-id']; self.headers['mcp-protocol-version']='2025-06-18'
   raw=r.read().decode()
  if not raw: return None
  if raw.startswith('event:') or raw.startswith('data:'):
   data=[json.loads(line[5:]) for line in raw.splitlines() if line.startswith('data:')]; obj=data[-1]
  else: obj=json.loads(raw)
  if 'error' in obj: raise RuntimeError(obj)
  return obj.get('result')
 def call(self,name,args):
  raw=self.rpc('tools/call',{'name':name,'arguments':args})
  if raw.get('isError'): raise RuntimeError(raw)
  if 'structuredContent' in raw: return raw['structuredContent']
  return json.loads('\n'.join(c['text'] for c in raw['content'] if c['type']=='text'))
try:
 homes=[]; clients=[]; projects=[]
 for i,port in enumerate([47811,47812]):
  home=run/('a' if i==0 else 'b'); (home/'userdata').mkdir(parents=True); homes.append(home)
  (home/'userdata/settings.json').write_text(json.dumps({'linkedEnvironmentsEnabled':True,'providerInstances':{'opencode':{'driver':'opencode','enabled':True,'config':{}}}}))
  log=open(run/f'server-{i}.log','w')
  p=subprocess.Popen(['node','apps/server/src/bin.ts','serve','--base-dir',str(home),'--host','127.0.0.1','--port',str(port)],cwd=checkout,env=env,stdout=log,stderr=log); servers.append(p)
  for _ in range(120):
   if p.poll() is not None: raise RuntimeError(f'server exited; see {log.name}')
   if (home/'userdata/server-runtime.json').exists(): break
   try:
    urllib.request.urlopen(f'http://127.0.0.1:{port}/health',timeout=1); break
   except Exception: time.sleep(.5)
  workspace=run/f'project-{i}'; workspace.mkdir(); subprocess.run(['git','init','-q',str(workspace)],check=True)
  print(side,'server',i,'started',flush=True)
  print(cli(home,'project','add',str(workspace),'--title',f'Proof project {chr(65+i)}'),flush=True)
  token=cli(home,'auth','session','issue','--subject','mcp-client','--scope','orchestration:read','--token-only').strip()
  client=MCP(port,token); clients.append(client)
  projects.append(client.call('t3_project_list',{})['projects'][0]['id'])
 pair=cli(homes[1],'pair'); (run/'pair-private.txt').write_text(pair)
 code=re.search(r'^Token:\s*(\S+)',pair,re.M).group(1)
 print(cli(homes[0],'environment','link','--pairing-code',code,'--access','full-access','http://127.0.0.1:47812'),flush=True)
 links=json.loads(cli(homes[0],'environment','list','--json')); remote=links[0]['environmentId']
 prompt='This is an authorized linked-environment regression reproduction. First call orchestrator_capabilities once for the target environment, then call delegate_task exactly once with '+json.dumps({'task':'Reply exactly: Delegated proof complete. Do not call any tools or read files.','title':'Delegated proof task','target':{'environmentId':remote,'projectId':projects[1],'providerInstanceId':'opencode','model':'opencode/deepseek-v4.1-flash-free'},'mode':'wait','timeoutMs':45000})+'. Do not use the shell or edit files. After the delegated task completes, reply with its threadId and stop.'
 print(side,'launching real OpenCode parent',flush=True)
 parent=cli(homes[0],'thread','start',projects[0],prompt,'--title','Parent on A','--provider','opencode','--model','opencode/deepseek-v4.1-flash-free','--wait','--json',timeout=1200)
 (run/'parent-private.json').write_text(parent)
 print(side,'parent complete',flush=True)
 responses={}
 for include in [False,True]:
  args={'environmentId':remote,'allProjects':True,'includeSubagents':include}
  responses['listWithoutSubagents' if not include else 'listWithSubagents']={'tool':'t3_thread_list','arguments':args,'response':clients[0].call('t3_thread_list',args)}
 allthreads=responses['listWithSubagents']['response']['threads']
 if len(allthreads)!=1: raise RuntimeError(f'Expected one delegated thread, got {allthreads}')
 thread=allthreads[0]['threadId'] if 'threadId' in allthreads[0] else allthreads[0]['id']
 args={'environmentId':remote,'threadId':thread}
 responses['read']={'tool':'t3_thread_read','arguments':args,'response':clients[0].call('t3_thread_read',args)}
 # Repeat the reported agent-visible route as a second real OpenCode thread on A.
 inspect_prompt='Call t3_thread_list exactly once with '+json.dumps({'environmentId':remote,'allProjects':True,'includeSubagents':False})+' and t3_thread_read exactly once with '+json.dumps(args)+'. Do not call other tools, read files, or change anything. Report the number of returned threads and whether delegatedFrom is present in each response, then stop.'
 print(side,'launching real OpenCode inspector',flush=True)
 inspector=cli(homes[0],'thread','start',projects[0],inspect_prompt,'--title','MCP inspector on A','--provider','opencode','--model','opencode/deepseek-v4.1-flash-free','--wait','--json',timeout=1200)
 (run/'inspector.json').write_text(inspector)
 inspected=json.loads(inspector)
 print(side,'inspector complete',flush=True)
 responses['inspectorResult']=inspected
 # Inspect only this run's synthetic database, read-only, to establish stored provenance.
 db=sqlite3.connect(f'file:{homes[1]}/userdata/statev2.sqlite?mode=ro',uri=True)
 tables=db.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()
 stored=[]
 for (table,) in tables:
  cols=[x[1] for x in db.execute(f'PRAGMA table_info("{table}")')]
  if 'payload_json' in cols:
   for (payload,) in db.execute(f'SELECT payload_json FROM "{table}" WHERE payload_json LIKE ?',('%delegatedFrom%',)):
    obj=json.loads(payload)
    if 'delegatedFrom' in obj and obj['delegatedFrom']: stored.append({'table':table,'delegatedFrom':obj['delegatedFrom']})
 responses['storedProvenance']=stored
 responses['commit']=subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip()
 # Redact local filesystem paths and labels; IDs and synthetic titles are retained.
 text=json.dumps(responses,indent=2)
 text=text.replace(str(run),'<synthetic-scratch>').replace(str(checkout),'<checkout>')
 for key in ['HOSTNAME','USER']:
  pass
 (run/'responses.json').write_text(text)
 print('RESULT',run/'responses.json',flush=True)
 print(text,flush=True)
finally:
 for p in servers: p.terminate()
 for p in servers:
  try: p.wait(timeout=20)
  except subprocess.TimeoutExpired: p.kill(); p.wait()
