import argparse, subprocess, json, time, pathlib, urllib.request, datetime
p=argparse.ArgumentParser(); p.add_argument('checkout'); p.add_argument('home'); p.add_argument('side'); p.add_argument('sha'); a=p.parse_args()
out=pathlib.Path(__file__).parent/(a.side+'-'+datetime.datetime.now().strftime('%Y%m%d-%H%M%S')); out.mkdir()
events=[]; start=time.monotonic()
def log(s):
    events.append([round(time.monotonic()-start,3),s]); print(s,flush=True)
def cli(*args):
    return subprocess.check_output(['node','apps/server/src/bin.ts',*args,'--base-dir',a.home],cwd=a.checkout,text=True)
origin=json.loads((pathlib.Path(a.home)/'userdata/server-runtime.json').read_text())['origin']
token=subprocess.check_output(['node','apps/server/evidence-token.ts',a.home],cwd=a.checkout,text=True).strip()
headers={'Authorization':'Bearer '+token,'Content-Type':'application/json','Accept':'application/json, text/event-stream'}; seq=0
def rpc(method,params=None,notify=False):
    global seq
    seq+=1; payload={'jsonrpc':'2.0','method':method,'params':params or {}}
    if not notify: payload['id']=seq
    req=urllib.request.Request(origin+'/mcp',data=json.dumps(payload).encode(),headers=headers)
    with urllib.request.urlopen(req,timeout=90) as r:
        if r.headers.get('mcp-session-id'): headers['mcp-session-id']=r.headers['mcp-session-id']
        raw=r.read().decode()
    if not raw:return
    packets=[json.loads(x[6:]) for x in raw.splitlines() if x.startswith('data: ')] if raw.startswith('event:') or raw.startswith('data:') else [json.loads(raw)]
    packet=next(x for x in packets if x.get('id')==seq)
    if 'error' in packet: raise RuntimeError(packet['error'])
    return packet['result']
rpc('initialize',{'protocolVersion':'2025-06-18','capabilities':{},'clientInfo':{'name':'wait-output-proof','version':'1'}}); rpc('notifications/initialized',notify=True)
def call(name,args):
    r=rpc('tools/call',{'name':name,'arguments':args})
    if r.get('isError'):raise RuntimeError(r)
    if 'structuredContent' in r:return r['structuredContent']
    return json.loads(next(c['text'] for c in r['content'] if c['type']=='text'))
log('REAL T3 SERVER / MCP - '+a.side.upper()+' '+a.sha[:10])
log('Linux; isolated fresh database; devReplay / showcase; output wait timeoutMs=5000')
# Each side uses its own checkout as the synthetic project, with identical prompts.
subprocess.run(['node','apps/server/src/bin.ts','project','add',a.checkout,'--title','Wait output proof','--base-dir',a.home],cwd=a.checkout,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
log('1. CLI thread start: "Short task: say done"; no output schema; --wait')
launched=json.loads(cli('thread','start',a.checkout,'Short task: say done','--provider','devReplay','--model','showcase','--wait','--json'))
thread=launched['threadId']; results=[]
def wait(run=None,until=False,label=''):
    args={'threadId':thread,'untilOutput':until,'timeoutMs':5000 if until else 45000}
    if run:args['runId']=run
    log(label+' t3_thread_wait untilOutput='+str(until).lower()+' ...')
    t=time.monotonic(); r=call('t3_thread_wait',args); elapsed=round(time.monotonic()-t,3)
    log('   status='+r['status']+' timedOut='+str(r['timedOut']).lower()+' elapsed='+str(elapsed)+'s')
    results.append({'label':label,'arguments':args,'response':r,'elapsedSeconds':elapsed});return r
first=wait(until=False,label='2. Run 1 baseline');wait(first['runId'],True,'3. Run 1 output wait')
log('4. t3_thread_send: "Short task: say done"; no output schema')
sent=call('t3_thread_send',{'threadId':thread,'message':'Short task: say done'})
wait(sent['runId'],False,'5. Run 2 baseline');wait(sent['runId'],True,'6. Run 2 output wait')
log('7. Send same prompt with requested JSON output schema; replay submits no output')
sent=call('t3_thread_send',{'threadId':thread,'message':'Short task: say done','outputSchema':{'type':'object','properties':{'done':{'type':'boolean'}},'required':['done'],'additionalProperties':False}})
wait(sent['runId'],False,'8. Run 3 baseline');wait(sent['runId'],True,'9. Run 3 missing output')
log('Capture complete')
(out/'responses.json').write_text(json.dumps({'side':a.side,'sha':a.sha,'results':results},indent=2))
(out/'events.json').write_text(json.dumps(events,indent=2))
(out/'transcript.txt').write_text('\n'.join(f'{t:7.3f}s {s}' for t,s in events)+'\n')
print('OUTPUT_DIRECTORY='+str(out))
