#!/usr/bin/env bash
# SIGKILL this worktree's dev server (port 13993 owner, cwd-checked) and its Codex descendants a few seconds into a new provider turn, then restart.
db=/home/ubuntu/wt/issue-26384/.t3/userdata/statev2.sqlite
before=$(sqlite3 -readonly "$db" "select count(*) from orchestration_v2_projection_provider_turns")
descendants() { for c in $(ps -o pid= --ppid "$1"); do echo "$c"; descendants "$c"; done; }
for i in $(seq 1 3000); do
  n=$(sqlite3 -readonly "$db" "select count(*) from orchestration_v2_projection_provider_turns" 2>/dev/null || echo "$before")
  if [ "$n" -gt "$before" ]; then
    sleep "${1:-3}"
    pid=$(ss -H -ltnp | grep ":13993 " | grep -o "pid=[0-9]*" | cut -d= -f2)
    [ "$(readlink /proc/$pid/cwd)" = /home/ubuntu/wt/issue-26384/apps/server ] || { echo "cwd mismatch"; exit 1; }
    tree="$pid $(descendants "$pid" | tr '\n' ' ')"
    ps -o pid,args -p "$(echo $tree | tr ' ' ',')" | cut -c1-120
    kill -9 $tree; echo "killed tree at $(date -u +%T.%N)"
    sleep 3; touch /home/ubuntu/wt/issue-26384/apps/server/package.json; echo "restart at $(date -u +%T.%N)"; exit 0
  fi
  sleep 0.01
done
echo timeout
