import argparse, datetime, json, sqlite3, time
from pathlib import Path
p=argparse.ArgumentParser()
p.add_argument("home")
p.add_argument("side")
p.add_argument("output")
a=p.parse_args()
out=Path(a.output)
out.mkdir(parents=True,exist_ok=True)
log=(out/(a.side+"-observations.jsonl")).open("a",buffering=1)
while True:
 c=sqlite3.connect("file:"+str(Path(a.home)/"userdata/statev2.sqlite")+"?mode=ro",uri=True)
 def rows(t):
  return [json.loads(r[0]) for r in c.execute("select payload_json from orchestration_v2_projection_"+t)]
 threads=rows("threads")
 parent=next(t for t in threads if t.get("title")=="Idle compaction with delegated child")
 tid=parent["id"]
 runs=[r for r in rows("runs") if r["threadId"]==tid]
 turns=[json.loads(r[0]) for r in c.execute("select payload_json from orchestration_v2_projection_provider_turns where thread_id=?",(tid,))]
 items=[r for r in rows("turn_items") if r["threadId"]==tid and r["type"]=="subagent"]
 messages=[r for r in rows("messages") if r["threadId"]==tid]
 state={"observedAt":datetime.datetime.now(datetime.timezone.utc).isoformat(),"side":a.side,"parentRuns":[{k:r.get(k) for k in ["ordinal","status","startedAt","completedAt"]} for r in runs],"usage":[r.get("tokenUsage") for r in turns],"delegates":[{k:r.get(k) for k in ["title","status","origin"]} for r in items],"compactMessages":[{k:m.get(k) for k in ["text","createdAt","idleCompaction"]} for m in messages if m.get("text","").strip().lower()=="/compact"]}
 line=json.dumps(state)
 log.write(line+"\n")
 print(line,flush=True)
 c.close()
 time.sleep(30)
