import sqlite3, json, sys
from pathlib import Path
root, thread, sha, side = sys.argv[1:]
c = sqlite3.connect('file:' + str(Path(root)/'.t3/userdata/statev2.sqlite') + '?mode=ro', uri=True)
c.row_factory = sqlite3.Row
rows = lambda q: [dict(r) for r in c.execute(q, (thread,))]
runs = rows('select status, completed_at from orchestration_v2_projection_runs where thread_id=?')
nodes = rows('select kind,status,started_at,completed_at from orchestration_v2_projection_nodes where thread_id=?')
items=[]
for r in rows('select type,status,payload_json from orchestration_v2_projection_turn_items where thread_id=? order by ordinal'):
 p=json.loads(r.pop('payload_json'))
 r.update({k:p[k] for k in ['startedAt','completedAt','steps','command','exitCode'] if k in p})
 if r['type'] in ['todo_list','command_execution']: items.append(r)
events=[]
for r in rows("select occurred_at,payload_json from orchestration_events where stream_id=? and event_type='turn-item.updated' order by sequence"):
 p=json.loads(r['payload_json'])
 if p.get('type')=='todo_list':events.append({'at':r['occurred_at'],'status':p['status'],'completedAt':p.get('completedAt'),'steps':p['steps']})
result={'side':side,'commit':sha,'environment':'Linux web dev app, fresh unseeded database; real Codex gpt-6-luna; 1280x800 CSS viewport; light theme','runs':runs,'nodes':nodes,'items':items,'planSnapshots':events}
# Keep public artifacts free of machine-local paths; command text, statuses and timestamps are retained.
for i in result['items']:
 if i.get('command','').startswith('git worktree'): i['command']='[workspace preparation]'
print(json.dumps(result,indent=2))
