#!/usr/bin/env python3
"""Real T3 server A/B driver. Usage: python3 measure.py CHECKOUT OUTPUT_ROOT SIDE.
Requires dependencies installed and `vp run --filter t3 build:bundle` in CHECKOUT.
Seeds exclusively through project CLI and HTTP MCP, using repository Replay (dev).
No database writes or copied state; SQLite below is read-only verification.
"""
import concurrent.futures,datetime,json,os,pathlib,socket,sqlite3,statistics,subprocess,sys,time,urllib.request
wt=pathlib.Path(sys.argv[1]).resolve(); output=pathlib.Path(sys.argv[2]).resolve()/f'{sys.argv[3]}-{datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%dT%H%M%SZ")}';output.mkdir(parents=True)
home=output/'home';state=home/'userdata';state.mkdir(parents=True)
node=subprocess.check_output(['which','node'],text=True).strip()
replay={'driver':'acpRegistry','displayName':'Replay (dev)','config':{'source':'local','commandPath':node,'commandArgs':[str(wt/'apps/server/scripts/dev-replay-agent.ts')]}}
(state/'settings.json').write_text(json.dumps({'providerInstances':{**{k:{'driver':k,'enabled':False} for k in ['codex','claudeAgent','cursor','grok','opencode','antigravity','kiro','pi','muse','fx']},'devReplay':replay},'compactIdleThreads':False}))
workspace=output/'workspace';workspace.mkdir();(workspace/'README.md').write_text('Synthetic command projection performance proof\n')
for args in [['init','--quiet','--initial-branch=main'],['add','.'],['-c','user.name=Proof','-c','user.email=proof@example.invalid','commit','--quiet','-m','Synthetic workspace']]:subprocess.run(['git',*args],cwd=workspace,check=True)
with socket.socket() as sock:sock.bind(('127.0.0.1',0));port=sock.getsockname()[1]
serverlog=open(output/'server-private.log','w')
env={**os.environ,'T3CODE_DEV_SEED':'0','T3CODE_TRACE_MIN_LEVEL':'Debug','T3CODE_TRACE_MAX_BYTES':'50000000','T3CODE_TRACE_MAX_FILES':'4','T3CODE_TRACE_BATCH_WINDOW_MS':'100'}
p=subprocess.Popen([node,'apps/server/src/bin.ts','serve','--base-dir',str(home),'--port',str(port),'--host','127.0.0.1'],cwd=wt,env=env,stdout=serverlog,stderr=serverlog)
(output/'server.pid').write_text(str(p.pid))
def cli(*args):return subprocess.check_output([node,str(wt/'apps/server/dist/bin.mjs'),*args,'--base-dir',str(home)],text=True,stderr=subprocess.PIPE)
report={'side':sys.argv[3],'commit':subprocess.check_output(['git','rev-parse','HEAD'],cwd=wt,text=True).strip(),'environment':{'os':'Linux x86_64','node':subprocess.check_output([node,'--version'],text=True).strip(),'surface':'real Node server; HTTP MCP and project CLI; repository Replay multi-turn','tracing':'Debug, timing enabled, identical on both sides','data':'fresh synthetic git project and fresh server-created database; no compaction'},'checkpoints':[]}
sid=None;token=None;tid=None

def rpc(method,params):
 global sid
 headers={'Content-Type':'application/json','Accept':'application/json, text/event-stream','Authorization':'Bearer '+token,'MCP-Protocol-Version':'2025-06-18'}
 if sid:headers['Mcp-Session-Id']=sid
 request_id=str(time.time_ns())
 req=urllib.request.Request(f'http://127.0.0.1:{port}/mcp',json.dumps({'jsonrpc':'2.0','id':request_id,'method':method,'params':params}).encode(),headers)
 with urllib.request.urlopen(req,timeout=180) as r:
  sid=r.headers.get('Mcp-Session-Id',sid);text=r.read().decode()
 data=json.loads(text) if text.startswith('{') else next(json.loads(x[6:]) for x in text.splitlines() if x.startswith('data: ') and json.loads(x[6:]).get('id')==request_id)
 if 'error' in data:raise RuntimeError(data)
 return data['result']
def tool(name,args):
 r=rpc('tools/call',{'name':name,'arguments':args})
 if r.get('isError'):raise RuntimeError(r)
 return r.get('structuredContent') or json.loads(r['content'][0]['text'])
def wait_idle():
 while True:
  r=tool('t3_thread_wait',{'threadId':tid,'timeoutMs':60000,'untilDelegatedWorkSettled':True})
  if not r['timedOut']:
   assert r['status']=='completed',r
   return r

def counts():
 with sqlite3.connect(f'file:{state}/statev2.sqlite?mode=ro',uri=True) as db:
  out={}
  for label,query in {
   'runs':"select count(*) from orchestration_v2_projection_runs where thread_id=?",
   'completedRuns':"select count(*) from orchestration_v2_projection_runs where thread_id=? and status='completed'",
   'compactions':"select count(*) from orchestration_v2_projection_turn_items where thread_id=? and type='compaction'",
   'userMessages':"select count(*) from orchestration_v2_projection_messages where thread_id=? and role='user'",
   'assistantMessages':"select count(*) from orchestration_v2_projection_messages where thread_id=? and role='assistant'",
   'providerTurns':"select count(*) from orchestration_v2_projection_provider_turns where thread_id=?",
  }.items():out[label]=db.execute(query,(tid,)).fetchone()[0]
  out['assistantTexts']=[list(row) for row in db.execute("select json_extract(payload_json,'$.text'),count(*) from orchestration_v2_projection_messages where thread_id=? and role='assistant' group by 1",(tid,))]
 return out

def send(label):return tool('t3_thread_send',{'threadId':tid,'message':label,'mode':'queue'})
def spans_since(start_ns,end_ns):
 result={}
 for f in (state/'logs').glob('server.trace*'):
  if not f.is_file():continue
  for line in f.open():
   try:s=json.loads(line)
   except ValueError:continue
   if s.get('name') not in ['Orchestrator.dispatchMessage','Orchestrator.startNextQueuedRun']:continue
   if start_ns <= int(s.get('startTimeUnixNano','0')) <= end_ns:
    # Deliberately omit attributes, which can contain local paths or identifiers.
    result[s['spanId']]={k:s[k] for k in ['name','startTimeUnixNano','durationMs','exit']}
 return list(result.values())
def summary(values):
 return {'n':len(values),'medianMs':statistics.median(values),'minMs':min(values),'maxMs':max(values),'spreadMs':max(values)-min(values),'samplesMs':values} if values else {'n':0}
def checkpoint(target):
 before=counts();print(json.dumps({'phase':'measure','side':sys.argv[3],'at':before}),flush=True)
 start=time.time_ns();deliveries=[]
 # Reproduction block repeated three times for stable medians: 21 idle sends, 9 bursts of four.
 for repetition in range(3):
  for i in range(7):deliveries.append(send(f'measure {target} idle {repetition} {i}')['delivery']);wait_idle()
  for burst in range(3):
   with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool:deliveries.extend(r['delivery'] for r in pool.map(send,[f'measure {target} burst {repetition} {burst} {i}' for i in range(4)]))
   wait_idle()
 end=time.time_ns()
 # Trace exporter flush, outside measured window.
 time.sleep(0.5)
 spans=spans_since(start,end);after=counts()
 dispatch=[s['durationMs'] for s in spans if s['name']=='Orchestrator.dispatchMessage']
 queued=[s['durationMs'] for s in spans if s['name']=='Orchestrator.startNextQueuedRun' and s['durationMs']>=2]
 block={'seedRuns':target,'before':before,'after':after,'idleAndBurstDeliveries':{d:deliveries.count(d) for d in set(deliveries)},'dispatchMessage':summary(dispatch),'queuedStartAtLeast2ms':summary(queued),'spans':spans}
 assert after['completedRuns']==after['runs']==before['runs']+57,block
 assert after['userMessages']==after['runs'] and after['assistantMessages']==after['runs'] and after['compactions']==0,block
 assert len(dispatch)==57,(len(dispatch),block)
 report['checkpoints'].append(block);(output/'measurement.json').write_text(json.dumps(report,indent=2))
 print(json.dumps({'phase':'measured','side':sys.argv[3],'seedRuns':target,'dispatch':summary(dispatch),'queued':summary(queued)}),flush=True)
try:
 deadline=time.monotonic()+90
 while not (state/'server-runtime.json').exists():
  if p.poll() is not None:raise RuntimeError('server exited; inspect private log')
  if time.monotonic()>deadline:raise TimeoutError('server startup')
  time.sleep(.2)
 cli('project','add',str(workspace),'--title','Command projection proof')
 token=cli('auth','session','issue','--subject','mcp-client','--token-only').strip()
 rpc('initialize',{'protocolVersion':'2025-06-18','capabilities':{},'clientInfo':{'name':'projection-proof','version':'1'}})
 projects=tool('t3_project_list',{}) if False else None
 # project list is a public CLI surface; get the id from project add output by listing MCP projects.
 tools=rpc('tools/list',{})['tools'];project_tool=next(x for x in tools if x['name']=='t3_project_list')
 projects=tool(project_tool['name'],{});(output/'project-result-private.json').write_text(json.dumps(projects))
 project_id=projects['projects'][0]['id']
 deadline=time.monotonic()+60
 while True:
  try:
   launched=tool('t3_thread_launch',{'projectId':project_id,'title':'Command projection proof','message':'seed 1','runtimeMode':'approval-required','modelSelection':{'instanceId':'devReplay','model':'multi-turn'}})
   break
  except RuntimeError as error:
   if 'model_unavailable' not in str(error) or time.monotonic()>deadline:raise
   time.sleep(1)
 tid=launched['threadId'];wait_idle()
 for target in [78,1015,2523]:
  while (n:=counts()['runs'])<target:
   batch=min(16,target-n)
   for i in range(batch):send(f'seed {n+i+1}')
   wait_idle()
   if (n+batch)%128<16:print(json.dumps({'phase':'seed','side':sys.argv[3],'runs':n+batch}),flush=True)
  checkpoint(target)
 report['final']=counts();(output/'measurement.json').write_text(json.dumps(report,indent=2));print('COMPLETE',output.name,flush=True)
finally:
 p.terminate()
 try:p.wait(timeout=30)
 except subprocess.TimeoutExpired:p.kill();p.wait()
 serverlog.close()
