import subprocess,sqlite3,json,time,sys,pathlib,datetime
root=pathlib.Path(sys.argv[1]);side=sys.argv[2]
out=pathlib.Path(__file__).resolve().parent/(side+'-'+datetime.datetime.now().strftime('%Y%m%d-%H%M%S'));out.mkdir()
start=time.monotonic();events=[];labels={}
def say(s):
 t=round(time.monotonic()-start,3);events.append([t,'o',s+'\r\n']); print(f'{t:6.2f}s  {s}',flush=True)
def cli(*args):
 p=subprocess.run(['node','apps/server/src/bin.ts',*args],cwd=root,text=True,capture_output=True)
 if p.returncode: raise RuntimeError(p.stderr)
 return p.stdout.strip()
def runs():
 with sqlite3.connect(f'file:{root}/.t3/userdata/statev2.sqlite?mode=ro',uri=True) as db:
  return [json.loads(x[0]) for x in db.execute('select payload_json from orchestration_v2_projection_runs where thread_id=? order by ordinal',(tid,))]
def snapshot():
 rs=runs();say(' | '.join(f'{labels.get(r["userMessageId"], "UNKNOWN")}: {r["status"]}' for r in rs));return rs
def wait(pred):
 deadline=time.monotonic()+100
 while time.monotonic()<deadline:
  rs=runs()
  if pred(rs): return rs
  time.sleep(.1)
 raise RuntimeError('Timed out')
try:
 say('Queue ordering - '+side.upper())
 say('Environment: Linux; real development server + CLI / MCP; replay provider')
 say('Synthetic thread; identical driver; terminal capture 1200 x 720; dark theme')
 say('Timing control: run-end handler delayed 20s; replay prompts wait 3s, both sides')
 say('$ thread start ACTIVE')
 launch=json.loads(cli('thread','start','--base-dir','.t3','--provider','devReplay','--model','multi-turn','--title','Queue order evidence','.','ACTIVE','--json'));tid=launch['threadId'];labels[runs()[0]['userMessageId']]='ACTIVE'
 say('$ t3_thread_send QUEUED mode=queue (through CLI)')
 sent=json.loads(cli('thread','send','--base-dir','.t3',tid,'QUEUED','--json'));labels[next(r for r in runs() if r['id']==sent['runId'])['userMessageId']]='QUEUED';say('Delivery: '+sent['delivery']);snapshot()
 wait(lambda rs:rs[0]['status']=='completed')
 say('ACTIVE completed; queue release handler still delayed.');snapshot()
 say('$ t3_thread_send NEWER mode=auto (through CLI)')
 sent=json.loads(cli('thread','send','--base-dir','.t3',tid,'NEWER','--json'));labels[next(r for r in runs() if r['id']==sent['runId'])['userMessageId']]='NEWER';say('Delivery: '+sent['delivery']);snapshot()
 previous=None
 deadline=time.monotonic()+100
 while time.monotonic()<deadline:
  rs=runs();state=[r['status'] for r in rs]
  if state!=previous: snapshot();previous=state
  if len(rs)==3 and all(s=='completed' for s in state):break
  time.sleep(.2)
 ordered=sorted([r for r in rs if r.get('startedAt')],key=lambda r:r['startedAt'])
 order=['ACTIVE','QUEUED','NEWER'];say('Observed execution order: '+' -> '.join(labels[r['userMessageId']] for r in ordered))
 for r in rs:say(f'{labels[r["userMessageId"]]:6} started {r.get("startedAt")} finished {r.get("completedAt")}')
 say('All observations above read from the real server projection (read-only).')
 (out/'observations.json').write_text(json.dumps(rs,indent=2))
finally:
 with (out/'recording.cast').open('w') as f:
  f.write(json.dumps({'version':2,'width':120,'height':36,'timestamp':int(time.time()),'env':{'TERM':'xterm-256color'}})+'\n')
  for e in events:f.write(json.dumps(e)+'\n')
 (out/'terminal.txt').write_text('\n'.join(f'{e[0]:6.2f}s {e[2].strip()}' for e in events))
 print('OUTPUT '+str(out),flush=True)
