#!/bin/bash
# Repro driver for issue 33432: parent delegates a child, then `t3 thread send` from a shell
# targets the finished child. Prints runs and parent delegated tasks afterwards.
# Usage: driver.sh <worktree> <base-dir> <project-path> <provider> <model>
set -euo pipefail
WT=$1; B=$2; PROJ=$3; PROV=$4; MODEL=$5; OUT=$PWD
DB=$B/userdata/statev2.sqlite
cd "$WT/apps/server"
PID=$( (node src/bin.ts project add "$PROJ" --base-dir "$B" || true) | sed -n 's/^Added project \([^ ]*\).*/\1/p')
[ -n "$PID" ] || PID=$(sqlite3 -readonly "file:$DB?mode=ro" "select project_id from orchestration_v2_projection_threads where title like 'P parent%' limit 1")
echo "project $PID"
echo 'Call the delegate_task tool exactly once with mode "wait" and the task: "Reply with exactly the word PONG and nothing else. Do not use any tools." When it returns, reply with the child result and stop.' \
  | node src/bin.ts thread start --base-dir "$B" --title "P parent $PROV" --provider "$PROV" --model "$MODEL" --wait --json "$PID" - | tee "$OUT/start.json"
P=$(python3 -I -c 'import json,sys; print(json.load(open(sys.argv[1]))["threadId"])' "$OUT/start.json")
C=$(sqlite3 -readonly "file:$DB?mode=ro" "select child_thread_id from orchestration_v2_projection_subagents where thread_id='$P' order by started_at limit 1")
echo "parent $P"; echo "child  $C"
echo "$(date -u +%T) t3 thread send <child> -"
echo 'Reply with exactly the word SECOND and nothing else. Do not use any tools.' | node src/bin.ts thread send --base-dir "$B" "$C" -
sleep 60
echo "$(date -u +%T) state:"
sqlite3 -readonly -header -column "file:$DB?mode=ro" "
select case thread_id when '$P' then 'parent' else 'child' end as thread, ordinal, status, requested_at, completed_at from orchestration_v2_projection_runs where thread_id in ('$P','$C') order by thread desc, ordinal;
select status, completion_delivery_state, started_at, completed_at from orchestration_v2_projection_subagents where thread_id='$P' order by started_at;"
