"""Real Codex lifecycle reproduction. Requires an isolated running dev server.
Usage: python prove.py WORKTREE BROWSER_CLI SESSION SERVER_PID CASE OUTPUT
CASE is command or subagent. Pair that browser with the dev app before running.
"""
import json, os, pathlib, signal, sqlite3, subprocess, sys, time
root, browser, session, server_pid, case, output = sys.argv[1:]
root = pathlib.Path(root).resolve()
out = pathlib.Path(output) / (case + '-' + time.strftime('%Y%m%d-%H%M%S'))
out.mkdir(parents=True)
def run(args):
    return subprocess.check_output(args, cwd=root, text=True).strip()
def ab(*args):
    return run([browser, '--session', session, *args])
def cli(*args):
    return run(['node','apps/server/src/bin.ts',*args,'--base-dir',str(root / '.t3')])
def query(sql, params=()):
    with sqlite3.connect('file:' + str(root / '.t3/userdata/statev2.sqlite') + '?mode=ro', uri=True) as db:
        return db.execute(sql, params).fetchall()
prompt = ('Run sleep 90 in a foreground shell command now. Wait for it to finish. Do not background it.' if case == 'command' else 'Use your native spawn_agent tool to spawn exactly one child. Its task: run sleep 120 in a foreground shell command, then say done. Immediately after spawn_agent returns, end your own turn with the final answer "Child started; root finished." Do not wait for the child. Do not use MCP delegation. Do not inspect any files. This is a controlled lifecycle reproduction.')
thread = os.environ.get('PROOF_THREAD') or cli('thread','start','--provider','codex','--model','gpt-6-luna','--title', 'Foreground command proof' if case == 'command' else 'Subagent lifecycle proof',str(root),prompt).splitlines()[-1]
def state():
    runs = query('select status from orchestration_v2_projection_runs where thread_id=?',(thread,))
    items = query('select type,status,json_extract(payload_json,\'$.input\') from orchestration_v2_projection_turn_items where thread_id=? or thread_id in (select child_thread_id from orchestration_v2_projection_subagents where thread_id=?)',(thread,thread))
    subs = query('select status from orchestration_v2_projection_subagents where thread_id=?',(thread,))
    return dict(runs=runs,items=items,subagents=subs)
for _ in range(180):
    before = state()
    cmds = [i for i in before['items'] if i[0]=='command_execution' and i[1]=='running' and i[2] and 'sleep' in i[2]]
    if cmds and (case=='command' or (before['runs']==[('completed',)] and before['subagents'])):
        break
    time.sleep(1)
else:
    raise RuntimeError('Required live state was not reached: '+json.dumps(before))
ab('eval','location.href = location.origin + "/" + location.pathname.split("/")[1] + "/" + encodeURIComponent('+json.dumps(thread)+')')
ab('wait','--text','Foreground command proof' if case=='command' else 'Subagent lifecycle proof')
# Use the actual UI control to close workspace details before recording.
ab('eval','document.querySelector("[aria-label=\\\"Thread details\\\"]") && document.querySelector("button[aria-label=\\\"Toggle thread details panel\\\"]")?.click()')
time.sleep(1)
ab('record','start',str(out/'lifecycle.mp4'))
time.sleep(2)
children = pathlib.Path('/proc/'+server_pid+'/task/'+server_pid+'/children').read_text().split()
candidates=[]
for child in children:
    try:
        cmd=pathlib.Path('/proc/'+child+'/cmdline').read_bytes().split(b'\0')
        if len(cmd)>1 and cmd[1]==b'app-server' and pathlib.Path(cmd[0].decode()).name=='codex':
            candidates.append(int(child))
    except FileNotFoundError:
        pass
assert pathlib.Path('/proc/'+server_pid+'/cwd').resolve()==root/'apps/server'
assert candidates, candidates
for pid in candidates:
    os.kill(pid,signal.SIGKILL)
# Observation interval matches the triage reproduction; this is a runtime driver, not a test.
time.sleep(25)
after=state()
(out/'state.json').write_text(json.dumps(dict(case=case,model='gpt-6-luna',before=before,after=after,observationSecondsAfterKill=25),indent=2))
ab('snapshot')
# Dismiss the error toast so it does not cover the result.
ab('eval','document.querySelector("button[aria-label=\\\"Dismiss error\\\"]")?.click()')
if case=='subagent':
    ab('eval','Array.from(document.querySelectorAll("button")).find(b=>b.textContent.startsWith("Worked for") && b.getAttribute("aria-expanded")==="false")?.click()')
time.sleep(2)
ab('record','stop')
# Keep two captures half a second apart and report whether the final view is stable.
from PIL import Image, ImageChops
stable=False
for n in range(12):
    ab('screenshot',str(out/'stability-a.png'))
    time.sleep(.5)
    ab('screenshot',str(out/'final.png'))
    if ImageChops.difference(Image.open(out/'stability-a.png').convert('RGB'),Image.open(out/'final.png').convert('RGB')).getbbox() is None:
        stable=True
        break
(out/'capture.json').write_text(json.dumps(dict(stable=stable,attempts=n+1)))
print(out)
