"""Manual real-app reproduction. Requires a fresh T3CODE_DEV_SEED=0 dev server.
Run: PROVIDER_MODEL=<configured inexpensive model> python3 driver.py CHECKOUT PROJECT
Start a browser recording on the delegated child's conversation before restart.
After this script restarts the server, reload that same conversation.
No database writes or synthetic provider events are used.
"""
import json, os, pathlib, re, signal, sqlite3, subprocess, sys, time
checkout, project = map(pathlib.Path, sys.argv[1:3])
prompt = ('Delegate a child using delegate_task with Claude and the cheapest available model. '
'Tell it: Start a background shell command sleep 25 without awaiting it, then end your turn. '
'When the background command completes and you are woken, start sleep 900 as a background command, '
'call t3_background_wait on it so it is awaited, and end your turn. Do not replace or cancel that task. '
'Parent: finish your turn after delegating, without waiting.')
def cli(*args):
    return subprocess.check_output(['node','apps/server/src/bin.ts',*args,'--base-dir','.t3'],cwd=checkout,text=True)
cli('project','add',str(project),'--title','Restart recovery')
started=json.loads(cli('thread','start',str(project),prompt,'--provider','claudeAgent','--model',os.environ['PROVIDER_MODEL'],'--title','Restart background work','--json'))
def connect():
    return sqlite3.connect(f'file:{checkout}/.t3/userdata/statev2.sqlite?mode=ro',uri=True)
for _ in range(180):
    with connect() as db:
        rows=[json.loads(r[0]) for r in db.execute('select payload_json from orchestration_v2_projection_subagents')]
        children=[r['childThreadId'] for r in rows if r['origin']=='app_owned' and r['threadId']==started['threadId']]
        pts=[json.loads(r[0]) for r in db.execute('select payload_json from orchestration_v2_projection_provider_threads')]
        ready=[p for p in pts if p['appThreadId'] in children and p['status']=='idle' and any(t.get('awaited') for t in p['pendingBackgroundTasks'])]
        completed=[r for r in rows if 'provider-continuation' in r['id'] and r['status']=='completed' and r.get('providerThreadId')]
    if ready and completed: break
    time.sleep(2)
else: raise SystemExit('Required reproduction state was not reached')
print('Precondition: child idle; awaited background command present; completed app-owned continuation references child.')
# Use the server port printed by this checkout's dev runner.
port=int(os.environ['SERVER_PORT'])
listing=subprocess.check_output(['ss','-H','-ltnp',f'sport = :{port}'],text=True)
pid=int(re.search(r'pid=(\d+)',listing)[1])
assert pathlib.Path(f'/proc/{pid}/cwd').resolve()==checkout/'apps/server'
os.kill(pid,signal.SIGTERM)
time.sleep(2)
(checkout/'apps/server/src/bin.ts').touch()
print('Graceful restart requested; reload the child conversation after recovery.')
