import os, sys, subprocess, json, textwrap, time
from pathlib import Path
root=Path(__file__).parent
side=sys.argv[1]
run=root/(side+'-capture-'+time.strftime('%Y%m%d-%H%M%S'))
run.mkdir()
(root/(side+'-capture-dir')).write_text(str(run))
repo=os.environ['EVIDENCE_REPO_ROOT']
sha=subprocess.check_output(['git','-C',repo,'rev-parse','HEAD'],text=True).strip()
print('\033[2J\033[H\033[?25l',end='')
print('T3 Code | issue #44307 | REAL SERVER / WEBSOCKET RPC CAPTURE')
print(side.upper()+'  '+sha)
print('Linux / fresh database / Claude Haiku 5.5 via hub / same 150-file scratch repository')
print('Plan + Full access -> background Explore reads each file -> Default follow-up x3')
print('='*118,flush=True)
env={**os.environ,'T3CODE_DEV_SEED':'0'}
p=subprocess.Popen(['node',str(root/'repro-44307.ts'),str(run)],stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True,env=env)
with (run/'driver.log').open('w') as f:
 for line in p.stdout:
  f.write(line); f.flush()
  stamp=line[:12]; content=line[13:].strip()
  pos=content.find('{')
  if pos>=0:
   try:
    state=json.loads(content[pos:]); label=content[:pos].strip()
    print(stamp,label)
    print('  mode:',state['mode'],'| runs:',', '.join(r['status'] for r in state['runs']),'| subagents:',', '.join(state['subagents']))
    responses=[r.get('response') for r in state['runs'] if r.get('response')]
    if responses: print('  Latest Claude reply:',responses[-1])
    errors=[r.get('error') for r in state['runs'] if r.get('error')]
    if errors:
     for wrapped in textwrap.wrap('ERROR: '+errors[-1],112): print('  '+wrapped)
   except Exception: print(line.rstrip())
  else: print(line.rstrip())
  sys.stdout.flush()
rc=p.wait()
print('Driver exit:',rc,flush=True)
(run/'exit.txt').write_text(str(rc))
# Keep the completed real terminal output visible for the recorder.
time.sleep(4)
