#!/usr/bin/env python3
"""Real-server driver. Run inside a proof checkout; no direct database writes.
Start its dev server with T3CODE_DEV_SEED=0 and the trusted resume-confirm.ts
extension in Pi launchArgs: --no-extensions --no-mcp --no-skills --approve -e <extension>.
Set PI_PROOF_LOG to a fresh file. Use a fresh T3 home for each revision.
seed: completes initial turns. Restart the server, then restore: sends all messages
concurrently. Open each returned thread in the web client and click Approve.
state: captures the final real-server state, plus extension milestones.
"""
import argparse, concurrent.futures, json, pathlib, subprocess, datetime
p=argparse.ArgumentParser();p.add_argument('phase',choices=['seed','restore','state']);p.add_argument('--project',required=True);p.add_argument('--home',required=True);p.add_argument('--output',required=True);p.add_argument('--ids');p.add_argument('--count',type=int,default=4);a=p.parse_args()
out=pathlib.Path(a.output)/datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S');out.mkdir(parents=True)
def cli(args):
 r=subprocess.run(['node','apps/server/src/bin.ts','thread',*args,'--base-dir',a.home,'--json'],capture_output=True,text=True)
 if r.returncode: raise RuntimeError(r.stderr)
 return json.loads(r.stdout)
if a.phase=='seed':
 def initial(i): return cli(['start',a.project,'Reply exactly INITIAL_TURN_COMPLETE. Do not use tools.','--title',f'Concurrent restore {i+1}','--provider','pi','--model','openai/gpt-6-luna','--wait'])
 with concurrent.futures.ThreadPoolExecutor(max_workers=a.count) as pool: result=list(pool.map(initial,range(a.count)))
else:
 ids=json.loads(pathlib.Path(a.ids).read_text());ids=[x['threadId'] if isinstance(x,dict) else x for x in ids]
 def action(t): return cli(['send',t,'Reply exactly RESTORED_TURN_COMPLETE. Do not use tools.'] if a.phase=='restore' else ['show',t])
 with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool: result=list(pool.map(action,ids))
(out/(a.phase+'.json')).write_text(json.dumps(result,indent=2)); print(json.dumps(result,indent=2))
