import argparse, datetime, json, pathlib, re, sqlite3, subprocess
p=argparse.ArgumentParser()
p.add_argument('--checkout', required=True)
p.add_argument('--output', required=True)
p.add_argument('--provider', choices=['codex','claudeAgent'], required=True)
a=p.parse_args()
checkout=pathlib.Path(a.checkout).resolve()
out=pathlib.Path(a.output).resolve()/datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')
out.mkdir(parents=True)
project=out/'project'
project.mkdir()
subprocess.run(['git','init','-q',str(project)],check=True)
cli=['node','apps/server/src/bin.ts']
def call(args):
 return subprocess.run(cli+args+['--base-dir','.t3'],cwd=checkout,text=True,capture_output=True,check=True).stdout
call(['project','add',str(project),'--title','Background wait proof'])
if a.provider=='codex':
 model='gpt-6-luna'
 prompt='Check your currently available tools. If t3_background_wait is available, call it exactly once with taskIds ["bg-test-1"]. Otherwise say TOOL_NOT_OFFERED. Report the exact result. Do not use any other tools.'
else:
 model='claude-haiku-5-5'
 prompt='Reproduce background wait recovery exactly. 1. Use Bash with run_in_background true for echo done-quick; save the returned task ID. 2. Use foreground Bash sleep 5. 3. Call t3_background_wait with that completed task ID and record the exact response. 4. Use Bash with run_in_background true for sleep 20; save its real task ID. 5. Call t3_background_wait with taskIds ["made-up-id-123"] and record the exact response. 6. Call t3_background_wait with the real sleep task ID. End your turn immediately after registering it; when woken report completion. In your final answer quote the task IDs and every background_wait response exactly. Do not delegate or use subagents.'
(out/'prompt.txt').write_text(prompt)
print(json.dumps({'provider':a.provider,'model':model,'prompt':prompt}),flush=True)
result=json.loads(call(['thread','start',str(project),prompt,'--title','Background wait recovery','--provider',a.provider,'--model',model,'--wait','--json']))
db=sqlite3.connect(f'file:{checkout}/.t3/userdata/statev2.sqlite?mode=ro',uri=True)
items=[]
for row in db.execute('select payload_json from orchestration_v2_projection_turn_items where thread_id=? order by ordinal',(result['threadId'],)):
 item=json.loads(row[0])
 if item['type']=='dynamic_tool' and 'background_wait' in item.get('toolName',''):
  items.append({k:item.get(k) for k in ['type','status','startedAt','completedAt','toolName','input','output']})
 elif item['type']=='command_execution':
  output=re.sub(r'/tmp/[^\s.]+(?:\.[^\s.]+)*', '<temporary-output-file>',item.get('output',''))
  items.append({'type':item['type'],'input':item.get('input'),'output':output,'startedAt':item.get('startedAt'),'completedAt':item.get('completedAt')})
 elif item['type']=='assistant_message':
  items.append({'type':item['type'],'text':item.get('text'),'startedAt':item.get('startedAt')})
report={'commit':subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip(),'provider':a.provider,'model':model,'prompt':prompt,'result':result,'items':items}
(out/'transcript.json').write_text(json.dumps(report,indent=2))
print(json.dumps(report,indent=2),flush=True)
