#!/usr/bin/env python3
"""Run from an installed T3 Code checkout: python3 run-proof.py OUTPUT_DIR PORT.
Keep agent.mjs beside this script. Each invocation needs a new OUTPUT_DIR.
No existing T3 home or provider credentials are used.
"""
import json,os,pathlib,subprocess,sys,time
out=pathlib.Path(sys.argv[1]).resolve();out.mkdir(parents=True,exist_ok=False)
port=int(sys.argv[2]);home=out/'home';(home/'userdata').mkdir(parents=True)
agent=pathlib.Path(__file__).with_name('agent.mjs')
node=subprocess.check_output(['which','node'],text=True).strip()
settings={'defaultModelSelection':{'instanceId':'proofAgent','model':'proof'},'providerInstances':{'proofAgent':{'driver':'acpRegistry','displayName':'Proof driver','enabled':True,'config':{'source':'local','customModels':['proof'],'commandPath':node,'commandArgs':[str(agent),str(out/'responses.json')]}}}}
for driver in ['codex','claudeAgent','cursor','grok','muse','pi','opencode','antigravity']:
 settings['providerInstances'][driver]={'driver':driver,'enabled':False}
settings['providerInstances']['devReplay']={'driver':'acpRegistry','enabled':True,'config':{'customModels':['multi-turn']}}
(home/'userdata/settings.json').write_text(json.dumps(settings))
cli=[node,'apps/server/src/bin.ts'];env={**os.environ,'T3CODE_DEV_SEED':'0'}
with open(out/'server.log','w') as log:
 server=subprocess.Popen(cli+['serve','--port',str(port),'--host','127.0.0.1','--base-dir',str(home),'--dev-url',f'http://127.0.0.1:{port+1}'],stdout=log,stderr=log,env=env)
 try:
  for _ in range(300):
   if (home/'userdata/server-runtime.json').exists():break
   if server.poll() is not None:raise RuntimeError('Server stopped; see server.log')
   time.sleep(.1)
  subprocess.run(cli+['project','add','.', '--title','Synthetic proof','--base-dir',str(home)],check=True,capture_output=True)
  run=subprocess.run(cli+['thread','start','.', 'Run the delegated task lookup proof.','--provider','proofAgent','--model','proof','--title','Delegated task lookup proof','--wait','--json','--base-dir',str(home)],capture_output=True,text=True,timeout=120)
  (out/'cli.json').write_text(run.stdout+run.stderr)
  if run.returncode:raise RuntimeError('Thread failed; see cli.json')
  # Only synthetic tool results are public; capabilities describe the local machine.
  records=json.loads((out/'responses.json').read_text())
  public=[r for r in records if r['tool']!='orchestrator_capabilities']
  (out/'public-responses.json').write_text(json.dumps(public,indent=2)+'\n')
  print('Recorded delegate_task and three task_status calls.')
 finally:
  server.terminate()
  try:server.wait(timeout=15)
  except subprocess.TimeoutExpired:server.kill();server.wait()
