#!/usr/bin/env bash
# Issue #31092: sending /clear on a stale Claude thread runs /compact first, then the clear.
# Claim: already fixed by #30325 (99e361e415), where /clear became T3's own command. Sent on its own,
# /clear now arms a fresh session and dispatches nothing, and the next message (freshContext) is never
# compacted first. Shows: before #30325 a stale "/clear" send plans compactBeforeSend=true; on main
# useComposerSend intercepts /clear before planning any turn, and a fresh-context send plans no compaction.
# Needs deps installed (`vp i`). Run from the root of a clean t3code checkout.
set -euo pipefail

ok=1
pass() { echo "PASS  $*"; }
fail() { echo "FAIL  $*"; ok=0; }

if [ -n "$(git status --porcelain)" ]; then
  echo "refusing to run on a dirty tree"
  exit 2
fi
ORIG=$(git symbolic-ref -q --short HEAD || git rev-parse HEAD)
TEST=apps/web/src/components/prove-issue-31092.test.ts
SEND=apps/web/src/components/chat/useComposerSend.ts
LOG=$(mktemp)
cleanup() {
  rm -f "$TEST" "$LOG"
  git checkout -q -f "$ORIG"
}
trap 'rc=$?; cleanup; [ "${PROOF_DONE:-0}" = 1 ] && exit 0; [ "$rc" -ne 0 ] && exit "$rc"; exit 1' EXIT

git fetch -q origin main
MAIN=$(git rev-parse FETCH_HEAD)
FIX=99e361e4153fdf9fd361c5c0df279a3e5f2c56c6
BEFORE=$(git rev-parse "$FIX^")
echo "main=$MAIN fix=$FIX before=$BEFORE"

subject=$(git log -1 --format=%s "$FIX")
if git merge-base --is-ancestor "$FIX" "$MAIN" \
  && [ "$subject" = "feat: /clear starts a fresh session in the same thread (#30325)" ]; then
  pass "#30325 ($(git rev-parse --short "$FIX")) is on main: $subject"
else
  fail "#30325 is not on main, or $FIX is a different commit ($subject)"
fi

# Static, on main: a lone /clear arms a fresh session and returns before planComposerTurn runs.
intercept=$(git show "$MAIN:$SEND" | grep -n 'isClearComposerCommand(trimmed)' | head -1 | cut -d: -f1)
arm=$(git show "$MAIN:$SEND" | grep -n 'armFreshSession(routeThreadKey);' | head -1 | cut -d: -f1)
plan=$(git show "$MAIN:$SEND" | grep -n '} = planComposerTurn({' | head -1 | cut -d: -f1)
if [ -n "$intercept" ] && [ -n "$arm" ] && [ -n "$plan" ] && [ "$intercept" -lt "$arm" ] && [ "$arm" -lt "$plan" ] \
  && git show "$MAIN:$SEND" | sed -n "${arm},$((arm + 5))p" | grep -q '^ *return;$'; then
  pass "main $SEND:$intercept: a lone /clear calls armFreshSession and returns (line $arm) before planComposerTurn (line $plan), so no /compact or /clear turn is sent"
else
  fail "main $SEND does not intercept /clear before planning a turn"
fi
if ! git show "$BEFORE:$SEND" | grep -q 'isClearComposerCommand'; then
  pass "before #30325 $SEND has no /clear intercept: /clear went through planComposerTurn like any message"
else
  fail "before #30325 $SEND already intercepted /clear"
fi

write_test() {
  cat > "$TEST" <<'EOF'
// prove-issue-31092: what the composer plans for /clear on a stale Claude thread.
import { assert, it } from "vite-plus/test";
import { planComposerTurn } from "./ChatView.logic";

// The issue's state: a server Claude thread idle past its cache TTL with 345K tokens to compact.
const stale = {
  sendQueuesBehindSetup: false, isServerThread: true, activeMessageCount: 12,
  sendEnvMode: "local" as const, worktreePath: null, activeThreadBranch: "main",
  isScratchProject: false, resumeCompactionTokens: 345_000, keepFullHistory: false,
  phase: "ready" as const, dispatchMode: "auto" as const,
};

it("prove-issue-31092", async () => {
  if (process.env.PROOF_EXPECT === "bug") {
    // Before #30325, "/clear" was planned like any message: compact first, then send it.
    assert.isTrue(planComposerTurn({ ...stale, messageText: "/clear" } as never).compactBeforeSend);
    return;
  }
  const { isClearComposerCommand } = await import("@t3tools/shared/composerTrigger");
  assert.isTrue(isClearComposerCommand("/clear"));
  // On main, /clear never reaches planComposerTurn; the next message is a fresh-context send.
  const next = planComposerTurn({ ...stale, messageText: "next task", freshContext: true });
  assert.isFalse(next.compactBeforeSend);
});
EOF
}

run_at() {
  git checkout -q --detach "$1"
  write_test
  local rc=0
  PROOF_EXPECT="$2" vp test run "$TEST" > "$LOG" 2>&1 || rc=$?
  rm -f "$TEST"
  if [ "$rc" -eq 0 ] && ! grep -Eq 'Tests +1 passed' "$LOG"; then rc=3; fi
  if [ "$rc" -ne 0 ]; then sed 's#'"$HOME"'#~#g' "$LOG" | tail -25; fi
  return "$rc"
}

if run_at "$BEFORE" bug; then
  pass "before #30325 ($(git rev-parse --short "$BEFORE")): \"/clear\" on a stale thread (345K tokens) plans compactBeforeSend=true"
else
  fail "before #30325: \"/clear\" on a stale thread did not plan a compaction"
fi
if run_at "$MAIN" fixed; then
  pass "main ($(git rev-parse --short "$MAIN")): /clear is T3's command, and the message after it plans compactBeforeSend=false"
else
  fail "main: the fresh-context send after /clear still plans a compaction"
fi

if [ "$ok" = 1 ]; then
  echo "VERDICT: #31092 is fixed on main by #30325"
  PROOF_DONE=1; exit 0
fi
echo "VERDICT: not shown"
exit 1
