"""Run from either installed checkout: python3 run-proof.py <fresh-home> <port>.
Place proof-agent.mjs beside this script. No live data or paid provider is used.
The home must not exist. Server is stopped after the CLI turn finishes.
"""
import json, os, pathlib, subprocess, sys, time, urllib.request
home=pathlib.Path(sys.argv[1]).resolve(); port=int(sys.argv[2]); home.mkdir()
agent=pathlib.Path(__file__).with_name('proof-agent.mjs').resolve()
node=subprocess.check_output(['node','-p','process.execPath'],text=True).strip()
(home/'userdata').mkdir(); (home/'workspace').mkdir()
settings={'defaultModelSelection':{'instanceId':'proofReplay','model':'proof-alpha'},'providerInstances':{key:{'driver':key,'enabled':False} for key in ['codex','claudeAgent','cursor','grok','muse','pi','opencode','antigravity']}}
settings['providerInstances']['proofReplay']={'driver':'acpRegistry','displayName':'Synthetic catalog proof','enabled':True,'config':{'source':'local','commandPath':node,'commandArgs':[str(agent),str(home/'runtime.ndjson')]}}
(home/'userdata/settings.json').write_text(json.dumps(settings))
subprocess.run(['git','init','--quiet','--initial-branch=main',str(home/'workspace')],check=True)
subprocess.run(['git','-C',str(home/'workspace'),'-c','user.name=Proof','-c','user.email=proof@example.invalid','commit','--quiet','--allow-empty','-m','Synthetic proof workspace'],check=True)
cli=[node,'apps/server/src/bin.ts']; env={**os.environ,'T3CODE_DEV_SEED':'0'}
with (home/'server.log').open('w') as output:
 server=subprocess.Popen(cli+['serve','--base-dir',str(home),'--port',str(port),'--host','127.0.0.1','--dev-url',f'http://127.0.0.1:{port+1}'],env=env,stdout=output,stderr=subprocess.STDOUT)
 try:
  for attempt in range(120):
   if server.poll() is not None: raise RuntimeError('Server exited; see server.log')
   if (home/'userdata/server-runtime.json').exists():
    try:
     urllib.request.urlopen(f'http://127.0.0.1:{port}/.well-known/t3/environment',timeout=1)
     break
    except Exception: pass
   time.sleep(.5)
  else: raise RuntimeError('Server did not become ready')
  subprocess.run(cli+['project','add',str(home/'workspace'),'--title','Catalog validation proof','--base-dir',str(home)],env=env,check=True,stdout=subprocess.DEVNULL)
  with (home/'cli.log').open('w') as output:
   subprocess.run(cli+['thread','start',str(home/'workspace'),'RUN_CATALOG_PROOF','--title','Catalog validation proof','--provider','proofReplay','--model','proof-alpha','--wait','--json','--base-dir',str(home)],env=env,check=True,stdout=output,stderr=subprocess.STDOUT,timeout=120)
 finally:
  server.terminate()
  try: server.wait(timeout=20)
  except subprocess.TimeoutExpired: server.kill(); server.wait()
print('Captured runtime.ndjson; keep server.log and cli.log private.')
