import sqlite3,json,sys,pathlib
checkout,thread,commit,out=sys.argv[1:]
c=sqlite3.connect(f"file:{checkout}/.t3/userdata/statev2.sqlite?mode=ro",uri=True)
def items(t):
 return [json.loads(r[0]) for r in c.execute("select payload_json from orchestration_v2_projection_turn_items where thread_id=? order by rowid",(t,))]
parent=items(thread)
calls=[x for x in parent if x["type"]=="dynamic_tool"]
children=[]
for (cid,payload) in c.execute("select thread_id,payload_json from orchestration_v2_projection_threads"):
 d=json.loads(payload)
 if d.get("lineage",{}).get("parentThreadId")==thread: children.append(cid)
def readable(x):
 d={k:x[k] for k in ["type","status","title","text","message","toolName","input"] if k in x}
 if isinstance(x.get("output"),dict): d["output"]={k:x["output"][k] for k in ["status","workState","summary","waitTimedOut"] if k in x["output"]}
 return d
data={"commit":commit,"surface":"Real T3 server and web client; Codex CLI 0.171.0; gpt-6-luna", "childItems":[readable(x) for cid in children for x in items(cid) if x["type"] in ["assistant_message","system_notice","run_interrupt_result"]],"parentToolResults":[readable(x) for x in calls if "task_status" in str(x.get("toolName","")) or "delegate_task" in str(x.get("toolName",""))],"parentAssistantMessages":[x.get("text") for x in parent if x["type"]=="assistant_message"]}
pathlib.Path(out).write_text(json.dumps(data,indent=2))
print(json.dumps(data,indent=2))
