"""Run against each independently started fresh T3 dev server with Cursor enabled.
Usage: python3 prove-cursor.py CHECKOUT PROJECT OUTPUT_DIRECTORY
Optional: append existing command.json reader.json to collect an already run pair.
The collector reads only that checkout's synthetic database, read-only.
"""
import sys, json, sqlite3, subprocess, pathlib, datetime
root, project, out = map(pathlib.Path, sys.argv[1:4])
out = out / datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S%fZ')
out.mkdir(parents=True)
def run(title, prompt):
    p = subprocess.run(['node','apps/server/src/bin.ts','thread','start','--base-dir','.t3','--provider','cursor','--model','auto','--title',title,'--wait','--json',str(project),prompt],cwd=root,text=True,capture_output=True,check=True)
    return json.loads(p.stdout)
command_prompt = 'Run exactly this shell command once: node -e "process.exit(1)" . Do not retry it. Reply only with the exit code.'
if len(sys.argv)>4:
    command=json.loads(pathlib.Path(sys.argv[4]).read_text())
    reader=json.loads(pathlib.Path(sys.argv[5]).read_text())
else:
    command=run('Nonzero shell command',command_prompt)
    reader=run('Read command status',f'Call t3_thread_read on thread {command["threadId"]}. Quote the command_execution timeline item for node -e "process.exit(1)" from the tool result. Return only a pretty-printed JSON object, one field per line, containing the exact type, status, and text values from that item. Do not run any shell commands.')
c=sqlite3.connect(f'file:{root}/.t3/userdata/statev2.sqlite?mode=ro',uri=True)
def items(tid):
    return [json.loads(r[0]) for r in c.execute('select payload_json from orchestration_v2_projection_turn_items where thread_id=? order by ordinal',(tid,))]
commands=[i for i in items(command['threadId']) if i['type']=='command_execution' and i.get('input')=='node -e "process.exit(1)"']
assert len(commands)==1
item=commands[0]
node=json.loads(c.execute('select payload_json from orchestration_v2_projection_nodes where node_id=?',(item['nodeId'],)).fetchone()[0])
read_tools=[i for i in items(reader['threadId']) if i['type']=='dynamic_tool' and 't3_thread_read' in i['toolName']]
mcp_items=[]
for tool in read_tools:
    for part in tool['output']['content']:
        if part['type']=='text':
            response=json.loads(part['text'])
            mcp_items += [i for i in response.get('items',[]) if i.get('type')=='command_execution' and 'process.exit(1)' in i.get('text','')]
assert mcp_items, 'Reader did not call t3_thread_read with the command timeline'
report={
 'commit':subprocess.check_output(['git','rev-parse','HEAD'],cwd=root,text=True).strip(),
 'environment':'Linux, isolated fresh T3 dev server; real Cursor SDK, model auto; web client 1280x800 CSS pixels (2x capture), light theme',
 'commandPrompt':command_prompt,
 'commandRun':command,
 'matchingShellCommandCount':len(commands),
 'storedCommand':{k:item.get(k) for k in ['type','status','input','output','exitCode']},
 'executionNode':{k:node[k] for k in ['kind','status']},
 'readerToolCalls':[{'toolName':t['toolName'],'input':t['input']} for t in read_tools],
 'actualMcpTimelineItems':mcp_items,
 'readerReply':reader['reply']
}
(out/'runtime-transcript.json').write_text(json.dumps(report,indent=2)+'\n')
print(out/'runtime-transcript.json')
print(json.dumps(report,indent=2))
