#!/usr/bin/env bash
# CLI driver used for both real-app runs, expressed with portable arguments.
# From the chosen checkout, first run: T3CODE_DEV_SEED=0 vp run dev
# Requires real Claude Code 2.1.336 with access to claude-haiku-5-5.
# Usage: bash reproduction.sh seed|trigger|next PROJECT OUTPUT_DIR [THREAD_ID]
set -eu
phase=$1
project=$2
output=$3
thread=${4:-}
mkdir -p "$output"
cli() { node apps/server/src/bin.ts "$@" --base-dir .t3; }
case "$phase" in
 seed)
  cli project add --title "Conversation recovery proof" "$project"
  cli thread start --provider claudeAgent --model claude-haiku-5-5 --wait --json "$project" "Reply with FIRST_OK and nothing else" > "$output/first.json"
  cat "$output/first.json"
  # Stop the dev server using its retained terminal session, then move ONLY
  # this throwaway session's transcript out of Claude's project directory.
  # Obtain nativeId read-only from this checkout's database:
  sqlite3 .t3/userdata/statev2.sqlite "select json_extract(payload_json,'$.nativeThreadRef.nativeId') from orchestration_v2_projection_provider_threads;"
  # Restart with T3CODE_DEV_SEED=0 vp run dev, then run the trigger phase.
  ;;
 trigger)
  cli thread send --wait --json "$thread" "Reply with FALLBACK_ORIGINAL and nothing else" > "$output/trigger.json" 2> "$output/trigger-error.txt" || true
  cat "$output/trigger.json"
  # Observe without sending anything: base adds an empty completed run;
  # head remains failed. Record the real web conversation during this step.
  cli thread show --json "$thread" > "$output/after-trigger.json"
  sqlite3 -json .t3/userdata/statev2.sqlite "select ordinal,status,requested_at,completed_at from orchestration_v2_projection_runs order by ordinal;" > "$output/runs-trigger.json"
  ;;
 next)
  cli thread send --wait --json "$thread" "Reply with FALLBACK_NEXT and nothing else" > "$output/next.json"
  cat "$output/next.json"
  ;;
 *) exit 2 ;;
esac
