#!/usr/bin/env python3
"""Read only synthetic worktree events; never reads live userdata."""
import sqlite3,json,sys,pathlib
checkout,thread,out=sys.argv[1:]
c=sqlite3.connect(f'file:{checkout}/.t3/userdata/statev2.sqlite?mode=ro',uri=True)
events=[]
for seq,kind,at,payload,command in c.execute('select sequence,event_type,occurred_at,payload_json,command_id from orchestration_events where stream_id=? order by sequence',(thread,)):
 p=json.loads(payload)
 if kind in ('run.created','run.updated','message.updated','turn-item.updated','provider-turn.updated','runtime-request.updated'):
  entry={'sequence':seq,'event':kind,'at':at,**{k:p[k] for k in ('id','ordinal','status','runId','text','streaming','creationSource','createdBy','kind','output','title','toolCall','input','answers','resolvedAt','providerTurnId') if k in p}}
  if command and command.startswith('provider-continuation:'): entry['command']='provider-continuation:<synthetic-message-id>'
  events.append(entry)
pathlib.Path(out).write_text('\n'.join(json.dumps(x) for x in events)+'\n')
print('written',len(events),'synthetic persisted events')
