#!/usr/bin/env bash
# Proof for the #21611 comment. Runs one launch test on three revisions, all on the same origin/main:
#   test-only        launch test alone (main's code)              -> expected to fail
#   patch            test + #23796's namespace line + doc fixes   -> expected to pass
#   ns-instance      test + #21611's thread:<id>:<instance> line  -> comparison only
# Then runs the related server suites on the patch, and writes the patch with git format-patch.
set -u
WT="${WT:?set WT to the jr-comment-21611 worktree}"
OUT="$(cd "$(dirname "$0")" && pwd)"
cd "$WT"
git fetch -q origin main
BASE=$(git rev-parse --short origin/main)
PATCH_BASE=$(git rev-parse --short jr/comment-21611~2)
echo "origin/main=$BASE patch-base=$PATCH_BASE"
[ "$BASE" = "$PATCH_BASE" ] || { echo "patch is not on latest origin/main; rebase first"; exit 1; }
[ "$(git rev-parse jr/comment-21611-ns-instance~1)" = "$(git rev-parse jr/comment-21611~1)" ] ||
  { echo "ns-instance branch is not on the test commit"; exit 1; }

run_one() { # name rev
  local name=$1 rev=$2 log="$OUT/launch-test-$1.log"
  git switch -q --detach "$rev" || exit 1
  (cd apps/server && vp test run src/orchestration-v2/ThreadLaunchService.test.ts -t "reissued") >"$log" 2>&1
  local code=$?
  echo "$name ($(git rev-parse --short HEAD)) exit=$code :$(grep -E '^ +Tests ' "$log" | tr -s ' ') $(grep -m1 -oE 'AssertionError: .*' "$log")"
}
run_one test-only jr/comment-21611~1
run_one patch jr/comment-21611
run_one ns-instance jr/comment-21611-ns-instance

git switch -q --detach jr/comment-21611
SUITES=$(cd apps/server && git grep -l "McpSessionRegistry\|requestNamespace" -- 'src/**/*.test.ts' | tr '\n' ' ')
(cd apps/server && vp test run $SUITES) >"$OUT/suites-with-patch.log" 2>&1
echo "related suites on patch exit=$? :$(grep -E '^ +(Test Files|Tests) ' "$OUT/suites-with-patch.log" | tr -s ' ' | tr '\n' ' ')$(grep -oE 'FAIL +src/[^ ]+ > .*' "$OUT/suites-with-patch.log" | sort -u | tr '\n' ' ')"
# Any failing file also runs on plain origin/main, to separate local environment failures from the patch.
for file in $(grep -oE 'FAIL +src/[^ ]+' "$OUT/suites-with-patch.log" | awk '{print $2}' | sort -u); do
  git switch -q --detach origin/main
  log="$OUT/main-$(basename "$file" .ts).log"
  (cd apps/server && vp test run "$file") >"$log" 2>&1
  echo "  $file on origin/main exit=$? :$(grep -E '^ +Tests ' "$log" | tr -s ' ') $(grep -m1 -oE "Executable doesn't exist" "$log")"
done
git switch -q jr/comment-21611

git format-patch -q --stdout origin/main..jr/comment-21611 >"$OUT/mcp-thread-namespace-launch-test.patch"
echo "patch: $(git rev-list --count origin/main..jr/comment-21611) commits, $(git diff --shortstat origin/main jr/comment-21611)"
