#!/usr/bin/env bash
# Evidence for "a child's question no longer waits behind another coordinator's busy lock".
#
# Usage: reproduce.sh <t3code clone> [runs]
#   Run it from the extracted evidence folder; it reads ./tla and ./proof-only-tests.patch.
#   FIX      commit to test (default: the clone's fix/keyed-stream-reactions branch;
#            fetch it with `git fetch <fork> fix/keyed-stream-reactions:fix/keyed-stream-reactions`)
#   TLA_JAR  path to tla2tools.jar (https://github.com/tlaplus/tlaplus/releases); TLC is skipped if unset
#
# It adds a detached worktree next to the clone, installs it, and applies proof-only-tests.patch
# (WorktreeBranchSync and PullRequestSyncReactor cases that stay out of the PR). Each test then
# runs `runs` times with the production files from main, and again with the fix. Logs go to ./out.
set -uo pipefail
REPO=$(cd "${1:?usage: reproduce.sh <t3code clone> [runs]}" && pwd)
RUNS=${2:-10}
HERE=$(cd "$(dirname "$0")" && pwd)
OUT="$HERE/out"
FIX=$(git -C "$REPO" rev-parse "${FIX:-fix/keyed-stream-reactions}")
BASE=$(git -C "$REPO" rev-parse "$FIX^") # main the one-commit fix sits on
WT="$(dirname "$REPO")/keyed-runner-proof"
PROD=(
  apps/server/src/orchestration-v2/DelegatedTaskQuestionReactor.ts
  apps/server/src/orchestration-v2/Orchestrator.ts
  apps/server/src/orchestration-v2/ProviderContinuationService.ts
  apps/server/src/orchestration-v2/PullRequestSyncReactor.ts
  apps/server/src/orchestration-v2/WorktreeBranchSync.ts
  packages/shared/src/KeyedLock.ts
)
# label | package dir | test file | -t filter
TESTS=(
  "question-wake|apps/server|src/orchestration-v2/runtimeLayer.test.ts|wakes an idle coordinator for its task's question"
  "worktree-branch|apps/server|src/orchestration-v2/WorktreeBranchSync.test.ts|updates an idle worktree's branch"
  "pr-created-link|apps/server|src/orchestration-v2/PullRequestSyncReactor.test.ts|links an idle thread's created pull request"
  "pr37417-queued-run|apps/server|src/orchestration-v2/runtimeLayer.test.ts|starts an idle thread's queued run"
  "pr37416-continuation|apps/server|src/orchestration-v2/ProviderContinuationService.test.ts|does not delay other threads' wakes"
)

rm -rf "$OUT" && mkdir -p "$OUT"
[ -d "$WT" ] || git -C "$REPO" worktree add -q --detach "$WT" "$FIX"
cd "$WT"
git checkout -q --detach "$FIX" && git checkout -q -- .
vp i >"$OUT/install.log" 2>&1 || { echo "vp i failed, see $OUT/install.log"; exit 1; }
git apply "$HERE/proof-only-tests.patch"

echo "base $BASE" | tee "$OUT/summary.txt"
echo "fix  $FIX" | tee -a "$OUT/summary.txt"
for side in main fix; do
  [ "$side" = main ] && rev=$BASE || rev=$FIX
  git checkout -q "$rev" -- "${PROD[@]}"
  for entry in "${TESTS[@]}"; do
    IFS='|' read -r label dir file filter <<<"$entry"
    pass=0 fail=0
    for i in $(seq "$RUNS"); do
      if (cd "$dir" && vp test run "$file" -t "$filter") >"$OUT/$side-$label-$i.log" 2>&1; then
        pass=$((pass + 1))
      else
        fail=$((fail + 1))
      fi
    done
    echo "$side $label: pass=$pass fail=$fail" | tee -a "$OUT/summary.txt"
  done
done
(cd packages/shared && vp test run src/KeyedLock.test.ts) >"$OUT/fix-keyed-lock.log" 2>&1 &&
  echo "fix KeyedLock.test.ts: pass" | tee -a "$OUT/summary.txt" ||
  echo "fix KeyedLock.test.ts: FAIL" | tee -a "$OUT/summary.txt"
git checkout -q -- .

[ -n "${TLA_JAR:-}" ] || { echo "TLA_JAR unset; skipping TLC"; exit 0; }
cd "$HERE/tla"
rm -f ./*_TTrace_*
tlc() { java -XX:+UseParallelGC -cp "$TLA_JAR" tlc2.TLC -workers 4 -cleanup -metadir "$OUT/states-$1" "${@:2}"; }
for m in Sequential KeyedFork KeyedForkNonFifoLock KeyedForkLateJoin SequentialLarge SequentialNoBusyLarge KeyedForkLarge; do
  tlc "$m" -deadlock -config "$m.cfg" ReactorLocks.tla >"$OUT/tlc-$m.out" 2>&1
  echo "tlc $m: $(grep -E 'is violated|was violated|No error has been found' "$OUT/tlc-$m.out" | head -1) ($(grep -oE '[0-9,]+ distinct states found, 0 states left' "$OUT/tlc-$m.out" | tail -1 | cut -d' ' -f1) distinct states)" | tee -a "$OUT/summary.txt"
done
for m in Sequential ByParent ByChild; do
  tlc "qw-$m" -config "qw-$m.cfg" QuestionWakeKeys.tla >"$OUT/tlc-qw-$m.out" 2>&1
  echo "tlc qw-$m: $(grep -E 'is violated|was violated|No error has been found' "$OUT/tlc-qw-$m.out" | head -1)" | tee -a "$OUT/summary.txt"
done
rm -rf "$OUT"/states-*
