"""Run against each checkout: python reproduce.py CHECKOUT OUTPUT PORT.
Set PRIVATE_RUNTIME_MODEL to the configured provider's inexpensive model slug.
Requires node, git, installed checkout dependencies, and configured provider access.
"""
import datetime, json, os, pathlib, subprocess, sys, time, urllib.request
checkout=pathlib.Path(sys.argv[1]).resolve()
run=pathlib.Path(sys.argv[2]).resolve()/datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S%fZ')
run.mkdir(parents=True)
home=run/'home'; repo=run/'repo'; repo.mkdir()
subprocess.run(['git','init','-q',str(repo)],check=True)
def cli(*args):
    return subprocess.run(['node',str(checkout/'apps/server/src/bin.ts'),*args,'--base-dir',str(home)],cwd=checkout,text=True,capture_output=True,check=True).stdout
log=(run/'private-server.log').open('w')
server=subprocess.Popen(['node',str(checkout/'apps/server/src/bin.ts'),'serve','--base-dir',str(home),'--port',sys.argv[3]],cwd=checkout,env={**os.environ,'T3CODE_DEV_SEED':'0'},stdout=log,stderr=log)
try:
    for attempt in range(120):
        if server.poll() is not None: raise RuntimeError('Server exited; inspect private log')
        try:
            urllib.request.urlopen('http://127.0.0.1:'+sys.argv[3],timeout=1)
            break
        except Exception: time.sleep(0.5)
    cli('project','add',str(repo))
    prompt="Use the Task tool exactly once to launch a general-purpose subagent with the prompt 'Reply with the word pong and nothing else.' Then reply done."
    result=cli('thread','start','--provider','claudeAgent','--model',os.environ['PRIVATE_RUNTIME_MODEL'],'--wait','--json',str(repo),prompt)
    (run/'parent-result.json').write_text(result)
    # Discover the child in this isolated database, then read it through the real CLI.
    import sqlite3
    db=sqlite3.connect(f'file:{home}/userdata/statev2.sqlite?mode=ro',uri=True)
    rows=db.execute('select child_thread_id,payload_json from orchestration_v2_projection_subagents').fetchall()
    for child,payload in rows:
        read=json.loads(cli('thread','show',child,'--json'))
        task=json.loads(payload)
        public={'childThreadId':child,'idLength':len(child),'link':read['thread']['link'],'linkLength':len(read['thread']['link']),'subagentResult':task.get('result'),'messages':read['messages']}
        print(json.dumps(public,indent=2))
finally:
    server.terminate()
    try: server.wait(timeout=15)
    except subprocess.TimeoutExpired: server.kill(); server.wait()
    log.close()
