#!/usr/bin/env bash
# Usage: orphan-quit.sh <worktree> <label>
# Plants a live agent-device daemon in the worktree's T3 state dir (what a server killed after
# the quit grace leaves behind), starts the T3 server without touching devices, sends it SIGTERM
# (graceful quit), and reports whether the daemon survived.
set -u
WT=$1; LABEL=$2
VER=$(node -p "require('$WT/apps/server/src/device/deviceToolVersions.json')['agent-device']")
TOOL=$WT/.t3/tools/agent-device/$VER
STATE=$WT/.t3/userdata/device/agent-device
echo "== $LABEL: $(git -C "$WT" rev-parse --short HEAD) + $(git -C "$WT" status --short apps/server/src/device | tr '\n' ' ')"
if [ ! -f "$TOOL/.install-complete" ]; then
  npm install --prefix "$TOOL" --no-fund --no-audit "agent-device@$VER" >/dev/null 2>&1 && printf '%s' "$VER" > "$TOOL/.install-complete"
fi
mkdir -p "$STATE"
AGENT_DEVICE_STATE_DIR=$STATE AGENT_DEVICE_DAEMON_SERVER_MODE=http AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS=0 \
  AGENT_DEVICE_NO_UPDATE_NOTIFIER=1 NO_COLOR=1 node "$TOOL/node_modules/agent-device/bin/agent-device.mjs" devices --json >/dev/null 2>&1
DPID=$(node -p "require('$STATE/daemon.json').pid")
echo "planted daemon pid=$DPID: $(ps -o args= -p "$DPID" | cut -c1-160)"
cd "$WT/apps/server"
T3CODE_DEV_SEED=0 node src/bin.ts --base-dir "$WT/.t3" --port 15099 --no-browser > "$OUT/server-$LABEL.log" 2>&1 &
SPID=$!
for i in $(seq 1 120); do grep -q "Listening on" "$OUT/server-$LABEL.log" && break; sleep 1; done
echo "server pid=$SPID cwd=$(readlink /proc/$SPID/cwd) $(grep -o 'Listening on .*' "$OUT/server-$LABEL.log")"
T0=$(date +%s%N); kill -TERM "$SPID"; wait "$SPID"; T1=$(date +%s%N)
echo "server exited after SIGTERM in $(( (T1 - T0) / 1000000 )) ms"
sleep 1
if kill -0 "$DPID" 2>/dev/null; then echo "RESULT $LABEL: daemon $DPID STILL RUNNING after graceful quit"; else echo "RESULT $LABEL: daemon $DPID stopped"; fi
ls "$STATE"
