"""Real T3 server MCP performance proof. Usage: python3 drive.py CHECKOUT OUTPUT SIDE PORT
Install the identical scratch fixture hook using setup-hook.py before running.
The hook only issues an MCP credential and reactivates a synthetic replay run.
It does not change the measured production command handlers.
"""
import pathlib,sys,subprocess,os,signal,time,json,urllib.request,sqlite3,statistics,datetime
root=pathlib.Path(sys.argv[1]).resolve(); out=pathlib.Path(sys.argv[2]).resolve()/datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ'); out.mkdir(parents=True)
side=sys.argv[3];port=int(sys.argv[4]);origin=f'http://127.0.0.1:{port}';home=out/'home';db=home/'userdata/statev2.sqlite';trace=home/'userdata/logs/server.trace.ndjson';proc=None
# Never inherit the live server home or telemetry destinations.
env={k:v for k,v in os.environ.items() if not k.startswith('T3CODE_')};env['T3CODE_DEV_SEED']='0'
def cli(*args):
 p=subprocess.run(['node','apps/server/src/bin.ts',*args,'--base-dir',str(home)],cwd=root,env=env,text=True,capture_output=True,timeout=180)
 if p.returncode: raise RuntimeError(p.stderr+p.stdout)
 return p.stdout

def stop():
 global proc
 if proc:
  os.killpg(proc.pid,signal.SIGTERM)
  try:proc.wait(timeout=8)
  except subprocess.TimeoutExpired:os.killpg(proc.pid,signal.SIGKILL);proc.wait()
  proc=None

def start(label):
 global proc
 log=open(out/f'{label}-server.log','w')
 proc=subprocess.Popen(['node','scripts/dev-runner.ts','dev:server','--port',str(port),'--home-dir',str(home),'--no-seed'],cwd=root,env=env,stdout=log,stderr=subprocess.STDOUT,start_new_session=True)
 for _ in range(240):
  if proc.poll() is not None:raise RuntimeError('server exited; inspect local log')
  try:
   urllib.request.urlopen(origin+'/.well-known/t3/environment',timeout=1).read();return
  except Exception:time.sleep(.5)
 raise RuntimeError('server did not listen')

def post(path,body,headers={}):
 req=urllib.request.Request(origin+path,json.dumps(body).encode(),{'content-type':'application/json',**headers})
 with urllib.request.urlopen(req,timeout=180) as r:
  text=r.read().decode();heads=dict(r.headers)
  if text.startswith('event:') or text.startswith('data:'):
   data=[json.loads(l[6:]) for l in text.splitlines() if l.startswith('data: ')];obj=data[-1]
  else:obj=json.loads(text)
 return obj,heads

def connect(tid):
 fixture,_=post('/__card_proof_fixture',{'threadId':tid})
 headers={'authorization':fixture['config']['authorizationHeader'],'accept':'application/json, text/event-stream'}
 _,h=post('/mcp',{'jsonrpc':'2.0','id':1,'method':'initialize','params':{'protocolVersion':'2025-06-18','capabilities':{},'clientInfo':{'name':'synthetic-card-proof','version':'1'}}},headers)
 headers['mcp-session-id']=next(v for k,v in h.items() if k.lower()=='mcp-session-id');headers['mcp-protocol-version']='2025-06-18'
 return fixture,headers

def call(headers,name,args,id):
 result,_=post('/mcp',{'jsonrpc':'2.0','id':id,'method':'tools/call','params':{'name':name,'arguments':args}},headers)
 if 'error' in result or result.get('result',{}).get('isError'):raise RuntimeError(json.dumps(result))
 return result['result']

def read_cards(tid,run):
 with sqlite3.connect(f'file:{db}?mode=ro',uri=True) as c:
  vals=[json.loads(r[0]) for r in c.execute("SELECT payload_json FROM orchestration_v2_projection_turn_items WHERE thread_id=? AND type IN ('secret_request','link_request') ORDER BY ordinal",(tid,))]
  turns=[json.loads(r[0]) for r in c.execute('SELECT payload_json FROM orchestration_v2_projection_provider_turns WHERE run_attempt_id=?',(run['activeAttemptId'],))]
  expected=turns[-1]['id']
  normalized=[{'type':x['type'],'label':x.get('label'),'reason':x.get('reason'),'hint':x.get('hint'),'secretStatus':x.get('secretStatus'),'linkStatus':x.get('linkStatus'),'status':x['status'],'correctRun':x['runId']==run['id'],'correctNode':x['nodeId']==run['rootNodeId'],'correctProviderThread':x['providerThreadId']==run['providerThreadId'],'correctProviderTurn':x['providerTurnId']==expected} for x in vals]
  assert all(all(x[k] for k in ['correctRun','correctNode','correctProviderThread','correctProviderTurn']) for x in normalized)
  return normalized

def seed_history(n,tid):
 # Server is stopped. Clone only this fixture's four settled records, with distinct IDs and consistent references.
 with sqlite3.connect(db) as c:
  c.row_factory=sqlite3.Row
  tables=['runs','run_attempts','nodes','provider_turns']
  originals={t:dict(c.execute('SELECT * FROM orchestration_v2_projection_'+t+' WHERE thread_id=? ORDER BY rowid LIMIT 1',(tid,)).fetchone()) for t in tables}
  payloads={t:json.loads(r['payload_json']) for t,r in originals.items()}
  ids={p['id'] for p in payloads.values()}
  def rewrite(v,i):
   if isinstance(v,str):return f'{v}:history:{i}' if v in ids else v
   if isinstance(v,list):return [rewrite(x,i) for x in v]
   if isinstance(v,dict):return {k:rewrite(x,i) for k,x in v.items()}
   return v
  old=c.execute('SELECT count(*) FROM orchestration_v2_projection_runs WHERE thread_id=?',(tid,)).fetchone()[0]-1
  for i in range(old+1,n+1):
   for t,row in originals.items():
    r={k:rewrite(v,i) for k,v in row.items()};p=rewrite(payloads[t],i)
    if 'ordinal' in r:r['ordinal']=i+1 if t=='provider_turns' else i
    if 'ordinal' in p:p['ordinal']=i+1 if t=='provider_turns' else i
    if 'status' in r:r['status']='completed'
    p['status']='completed';r['payload_json']=json.dumps(p)
    c.execute('INSERT INTO orchestration_v2_projection_'+t+' ('+','.join(r)+') VALUES ('+','.join('?' for _ in r)+')',list(r.values()))
  # The measured current run is newer than all synthetic history.
  live=payloads['runs'];live['ordinal']=15001;live['status']='completed'
  c.execute("UPDATE orchestration_v2_projection_runs SET ordinal=15001,status='completed',payload_json=? WHERE run_id=?",(json.dumps(live),live['id']))
  return {t:c.execute('SELECT count(*) FROM orchestration_v2_projection_'+t+' WHERE thread_id=?',(tid,)).fetchone()[0] for t in tables}

try:
 start('initial')
 # Make the normal project and completed run through the real CLI and replay provider.
 workspace=out/'workspace';workspace.mkdir();subprocess.run(['git','init','-q',str(workspace)],check=True)
 subprocess.run(['git','-C',str(workspace),'-c','user.name=Proof','-c','user.email=proof@example.invalid','commit','--allow-empty','-qm','initial'],check=True)
 cli('project','add',str(workspace),'--title','Synthetic card proof')
 launched=json.loads(cli('thread','start',str(workspace),'Prepare synthetic card proof','--title','Synthetic card proof','--provider','devReplay','--model','multi-turn','--wait','--json'))
 tid=launched['threadId'];stop()
 settings=home/'userdata/settings.json';s=json.loads(settings.read_text());s['linkedEnvironmentsEnabled']=True;settings.write_text(json.dumps(s))
 results=[]
 for n in [0,2000,15000]:
  counts=seed_history(n,tid);start(f'history-{n}');fixture,headers=connect(tid);run=json.loads(fixture['run']['payload_json'])
  offset=trace.stat().st_size;responses=[]
  # Three repetitions, each matching triage: five pending/cancelled secrets and five pending links.
  for batch in range(3):
   for i in range(5):
    tag=f'proof-{n}-{batch}-{i}'
    responses.append(call(headers,'request_secret',{'label':f'Token {tag}','reason':'Synthetic performance proof','timeoutMs':1000,'clientRequestId':tag},100+batch*20+i))
   for i in range(5):
    tag=f'proof-link-{n}-{batch}-{i}'
    responses.append(call(headers,'t3_environment_link',{'hint':f'Synthetic target {tag}','reason':'Synthetic performance proof','clientRequestId':tag},110+batch*20+i))
  cards=read_cards(tid,run)
  stop() # flush trace, and stop before the next history insertion
  with open(trace) as f:f.seek(offset);spans=[json.loads(l) for l in f if l.strip()]
  spans=[{'name':x['name'],'durationMs':x['durationMs'],'exit':x.get('exit',{}).get('_tag')} for x in spans if x.get('name') in ['orchestrationV2.dispatch.secretRequestRecord','orchestrationV2.dispatch.linkRequestRecord']]
  stats={}
  for kind in ['secret','link']:
   name='orchestrationV2.dispatch.'+('secretRequestRecord' if kind=='secret' else 'linkRequestRecord')
   v=[x['durationMs'] for x in spans if x['name']==name];assert len(v)==(30 if kind=='secret' else 15),(kind,len(v))
   assert all(x['exit']=='Success' for x in spans)
   stats[kind]={'n':len(v),'medianMs':statistics.median(v),'minMs':min(v),'maxMs':max(v),'samplesMs':v}
  phase={'olderRuns':n,'tableCounts':counts,'stats':stats,'cards':cards,'spans':spans,'toolResponses':responses}
  results.append(phase);(out/f'{side}-results.json').write_text(json.dumps({'side':side,'sha':subprocess.check_output(['git','rev-parse','HEAD'],cwd=root,text=True).strip(),'platform':'Linux x86_64, Node 26.13.1; same VM; real development server; synthetic replay-owned run; HTTP MCP tools','phases':results},indent=2))
  print(side,n,json.dumps(stats),flush=True)
 print('RESULT',out/f'{side}-results.json',flush=True)
finally:stop()
