"""Wait for a parent's own cleanup without waiting for descendant captures.
Usage: python3 wait-parent.py CHECKOUT PARENT_JSON
"""
import sqlite3,json,time,sys,pathlib
parent=json.loads(pathlib.Path(sys.argv[2]).read_text())['threadId']
db=pathlib.Path(sys.argv[1])/'.t3/userdata/statev2.sqlite'
connection=sqlite3.connect('file:'+str(db)+'?mode=ro',uri=True)
while True:
    rows=connection.execute("select effect_type,status from orchestration_v2_effect_outbox where thread_id=? and effect_type in ('checkpoint.capture','provider-turn.interrupt','delegated-tasks.stop')",(parent,)).fetchall()
    if len(rows)>=3 and all(status=='succeeded' for _,status in rows):
        print('Parent cleanup and checkpoint succeeded.');break
    time.sleep(.2)
