import subprocess, json, sys, pathlib, datetime
checkout, home, project, output = sys.argv[1:]
out=pathlib.Path(output)/datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ'); out.mkdir(parents=True)
def cli(*args):
 p=subprocess.run(['node','apps/server/src/bin.ts',*args,'--base-dir',home],cwd=checkout,text=True,capture_output=True,timeout=300)
 if p.returncode: raise RuntimeError(p.stderr)
 return p.stdout
cli('project','add',project,'--title','Auth review proof')
prompt='Review the auth flow\n\nPay special attention to token renewal.'
instruction='Call create_threads exactly once with exactly one thread, omit title, and set prompt to this exact string: '+json.dumps(prompt)+'. Use the current checkout and provider. Do not call t3_thread_launch or delegate_task. After the tool succeeds, reply only with the child thread ID.'
started=json.loads(cli('thread','start',project,instruction,'--provider','opencode','--model','anthropic/claude-haiku-5-5','--title','Create auth review','--wait','--json'))
(out/'parent-start.json').write_text(json.dumps(started,indent=2))
parent=json.loads(cli('thread','show',started['threadId'],'--json'))
(out/'parent.json').write_text(json.dumps(parent,indent=2))
print(json.dumps(parent,indent=2))
print('OUTPUT_DIR',out)
import sqlite3
conn=sqlite3.connect(f'file:{home}/userdata/statev2.sqlite?mode=ro',uri=True)
items=[json.loads(row[0]) for row in conn.execute('select payload_json from orchestration_v2_projection_turn_items where thread_id=? and type=? order by ordinal',(started['threadId'],'dynamic_tool'))]
call=next(x for x in items if '.create_threads({' in x.get('input',{}).get('code',''))
result=json.loads(call['output'])
child=json.loads(cli('thread','show',result['threads'][0]['threadId'],'--json'))
proof={'toolInput':call['input'],'toolResult':result,'cliReadBack':{'thread':{k:child['thread'][k] for k in ['threadId','title','status','providerInstanceId','model']},'initialMessage':child['messages'][0]}}
(out/'proof.json').write_text(json.dumps(proof,indent=2))
print(json.dumps(proof,indent=2))
