#!/bin/bash
# Sandboxed AC verification for act:ca5ac156 (ensure_main_station pane-liveness
# hardening). The bug: ensure_main_station trusted the @mux_claude window
# marker as the ONLY Claude-liveness signal, so a live pre-v0.44 Claude with
# no marker got the qa_launch_fresh keystrokes (C-u + `cd … && claude` +
# Enter) typed INTO its input box.
#
# Everything runs under a mktemp dir with HOME overridden AND a private
# throwaway tmux server (tmux -L mux-stl-test-$$ -f /dev/null) — it never
# touches the real ~/.mux/worktrees, ~/.config/mux, or the operator's live
# tmux server. Fake Claudes are REAL node processes printing Claude Code's UI
# footer, so pane_current_command and the pane snapshot both look authentic.
# The test server is killed in cleanup even on assertion failure.
set -uo pipefail

REPO_ROOT="$(cd "$(dirname "$0")/../../.." && pwd)"
SANDBOX=$(mktemp -d /tmp/cc-mux-station-test.XXXXXX)
FAKE_HOME="$SANDBOX/home"
PROJ="$SANDBOX/proj"
WT_DIR="$FAKE_HOME/.mux/worktrees"
MUX="$REPO_ROOT/templates/mux/bin/mux"
NODE_BIN="$(command -v node)"

pass=0; fail=0
ok()  { echo "  PASS: $1"; pass=$((pass+1)); }
bad() { echo "  FAIL: $1"; fail=$((fail+1)); }
assert() { # assert <desc> <cmd...>
  local desc="$1"; shift
  if "$@" >/dev/null 2>&1; then ok "$desc"; else bad "$desc"; fi
}

# --- private throwaway tmux server -------------------------------------------
unset TMUX TMUX_PANE
SOCK="mux-stl-test-$$"
TMX() { tmux -L "$SOCK" -f /dev/null "$@"; }
cleanup() { TMX kill-server 2>/dev/null || true; rm -rf "$SANDBOX"; }
trap cleanup EXIT

# --- sandbox home -------------------------------------------------------------
mkdir -p "$FAKE_HOME/.config/mux" "$WT_DIR" "$FAKE_HOME/.local/share/mux/wt-health" \
         "$FAKE_HOME/.claude/projects" "$SANDBOX/bin"
cp "$REPO_ROOT/templates/mux/config/worktree-session-health.sh" "$FAKE_HOME/.config/mux/"
cp "$REPO_ROOT/templates/mux/config/worktree-dirty-check.sh" "$FAKE_HOME/.config/mux/"
chmod +x "$FAKE_HOME/.config/mux/"*.sh

# Stub claude FIRST in the panes' PATH so a relaunch never starts the real
# Claude Code inside the test server.
cat > "$SANDBOX/bin/claude" <<'SH'
#!/bin/bash
echo "stub-claude up — ? for shortcuts"
exec tail -f /dev/null
SH
chmod +x "$SANDBOX/bin/claude"

# Fake live Claude: a REAL node process whose visible pane shows Claude
# Code's footer — pane_current_command = "node", snapshot matches the
# pane_is_live_claude markers. No @mux_claude marker is ever set on it.
cat > "$SANDBOX/fake-claude.js" <<'JS'
console.log('╭──────────────────────────────╮');
console.log('│ >                            │');
console.log('╰──────────────────────────────╯');
console.log('  ? for shortcuts');
setInterval(() => {}, 1 << 30);
JS
# Noise process: also node, but with NO Claude UI markers — must classify
# as "other", never get the marker backfilled, never get keystrokes.
cat > "$SANDBOX/noise.js" <<'JS'
console.log('dev server listening on :3000');
setInterval(() => {}, 1 << 30);
JS

# Stub muxlib.py — answers only what cmd_new/cmd_qa/create_worktree ask.
cat > "$FAKE_HOME/.config/mux/muxlib.py" <<'PY'
import sys, os
cmd = sys.argv[1] if len(sys.argv) > 1 else ""
if cmd == "project-path":
    p = os.environ.get("STUB_PROJ_PATH", "")
    if p:
        print(p)
    else:
        sys.exit(1)
elif cmd == "project-names":
    print("live")
elif cmd in ("worktree-add", "worktree-remove", "narrate-mark"):
    pass
elif cmd == "worktree-is-active":
    print("yes")
elif cmd == "narrate-check":
    print("yes")
PY
echo '{"active":[]}' > "$FAKE_HOME/.config/mux/worktrees.json"
echo '{}' > "$FAKE_HOME/.config/mux/projects.json"

# --- fixture project ------------------------------------------------------------
git init -q "$PROJ"
git -C "$PROJ" config user.email t@t.t; git -C "$PROJ" config user.name t
echo code > "$PROJ/file.txt"
git -C "$PROJ" add -A && git -C "$PROJ" commit -qm init
MAIN_SLUG=$(echo "$PROJ" | sed 's|[/.]|-|g')
mkdir -p "$FAKE_HOME/.claude/projects/$MAIN_SLUG"

# --- desks on the private server -------------------------------------------------
# One session per scenario so marker backfill in one test can't leak into the
# next. Window 0 is the main-station candidate (lowest-index non-worktree).
#   live     → unmarked fake Claude (the act:ca5ac156 victim)
#   noise    → unmarked node WITHOUT Claude markers ("other")
#   dead     → bare shell (window 1's Claude died — relaunch is correct)
#   marked   → fake Claude WITH @mux_claude=1 (pre-fix happy path, no-op)
#   dispatch → unmarked idle fake Claude for the `mux qa dispatch` path
HOME="$FAKE_HOME" PATH="$SANDBOX/bin:$PATH" \
  TMX new-session -d -s live -x 200 -y 50 -c "$PROJ" "$NODE_BIN $SANDBOX/fake-claude.js" \
  || { echo "FATAL: could not start private tmux server"; exit 1; }
TMX new-session -d -s noise -x 200 -y 50 -c "$PROJ" "$NODE_BIN $SANDBOX/noise.js"
TMX new-session -d -s dead -x 200 -y 50 -c "$PROJ"
TMX new-session -d -s marked -x 200 -y 50 -c "$PROJ" "$NODE_BIN $SANDBOX/fake-claude.js"
TMX set-window-option -t "marked:0" @mux_claude 1
TMX new-session -d -s dispatch -x 200 -y 50 -c "$PROJ" "$NODE_BIN $SANDBOX/fake-claude.js"
# verstr → unmarked fake Claude whose EXECUTABLE is named like a bare version
# string ("2.1.169"): the macOS native installer execs a versioned binary, so
# a real Claude pane reports pane_current_command as the version (live
# finding, dec-c1dbcd8b QA). Symlinked node keeps the process authentic.
mkdir -p "$SANDBOX/bin"
ln -sf "$NODE_BIN" "$SANDBOX/bin/2.1.169"
TMX new-session -d -s verstr -x 200 -y 50 -c "$PROJ" "$SANDBOX/bin/2.1.169 $SANDBOX/fake-claude.js"
sleep 1  # let the fake-Claude footers render before any pane classification

SOCKET_PATH=$(TMX display-message -p -t live '#{socket_path}')
SERVER_PID=$(TMX display-message -p -t live '#{pid}')

# Run mux "inside" a given desk: TMUX points at the test socket, TMUX_PANE at
# that desk's window-0 pane so session resolution lands on the right desk.
run_mux_in() { # run_mux_in <session> <args...>
  local sess="$1"; shift
  local pane; pane=$(TMX display-message -p -t "${sess}:0" '#{pane_id}')
  env HOME="$FAKE_HOME" STUB_PROJ_PATH="$PROJ" \
      TMUX="${SOCKET_PATH},${SERVER_PID},0" TMUX_PANE="$pane" \
      bash "$MUX" "$@"
}
win_count() { TMX list-windows -t "$1" 2>/dev/null | wc -l | tr -d ' '; }
win_opt()   { TMX show-options -wv -t "$1" "$2" 2>/dev/null; }
# Pane snapshots and command output go through files — pane content contains
# single quotes (`cd '…'`), which inline <<<'…' interpolation can't survive.
SNAP="$SANDBOX/snap.txt"; OUT="$SANDBOX/out.txt"
pane_snap() { TMX capture-pane -t "$1" -p -S -50 >"$SNAP" 2>/dev/null; }

echo "== T1: live UNMARKED Claude => no keystroke injection + marker backfill (the act:ca5ac156 bug)"
before=$(win_count live)
run_mux_in live new "review the parser" >"$OUT" 2>&1; rc=$?
sleep 0.5
assert "mux new exits 0 ($rc)" test "$rc" -eq 0
pane_snap "live:0"
assert "NO launch keystrokes typed into the live Claude's input box" \
  bash -c "! grep -qF \"cd '\" '$SNAP'"
assert "@mux_claude=1 BACKFILLED on the unmarked live Claude" \
  test "$(win_opt live:0 @mux_claude)" = "1"
assert "work still routed to a new worktree window" \
  test "$(win_count live)" -eq $((before + 1))

echo "== T2: unmarked node WITHOUT Claude markers => 'other', refuse loudly, no backfill"
before=$(win_count noise)
run_mux_in noise new "tighten the linter" >"$OUT" 2>&1; rc=$?
sleep 0.5
assert "mux new exits 0 ($rc)" test "$rc" -eq 0
pane_snap "noise:0"
assert "NO launch keystrokes typed into the unknown program" \
  bash -c "! grep -qF \"cd '\" '$SNAP'"
assert "@mux_claude NOT backfilled on a non-Claude node process" \
  test -z "$(win_opt noise:0 @mux_claude)"
assert "refusal is loud and names the program" \
  bash -c "grep -qF \"running 'node'\" '$OUT'"
assert "work still routed to a new worktree window" \
  test "$(win_count noise)" -eq $((before + 1))

echo "== T3: bare shell (Claude died) => relaunch there (existing behavior preserved)"
run_mux_in dead new "polish the docs" >"$OUT" 2>&1; rc=$?
sleep 0.5
assert "mux new exits 0 ($rc)" test "$rc" -eq 0
pane_snap "dead:0"
assert "launch keystrokes typed into the bare shell" \
  bash -c "grep -qF \"cd '\" '$SNAP'"
assert "relaunched station marked @mux_claude=1" \
  test "$(win_opt dead:0 @mux_claude)" = "1"
# The station relaunch is an EMPTY-prompt queue_claude_start: it must take the
# plain `cd && claude` path and write NO initial-prompt seed file (a stray seed
# arg would auto-submit garbage into the fresh station). The work prompt
# ("polish the docs") rode a separate worktree window, which DOES get a seed.
assert "empty-prompt station relaunch writes NO seed file for dead:0" \
  test ! -f "$FAKE_HOME/.local/share/mux/seed-prompts/dead-0.txt"

echo "== T4: marked live Claude => untouched no-op (pre-fix happy path preserved)"
before=$(win_count marked)
run_mux_in marked new "harden the cache" >"$OUT" 2>&1; rc=$?
sleep 0.5
assert "mux new exits 0 ($rc)" test "$rc" -eq 0
pane_snap "marked:0"
assert "NO keystrokes typed into the marked Claude" \
  bash -c "! grep -qF \"cd '\" '$SNAP'"
assert "work still routed to a new worktree window" \
  test "$(win_count marked)" -eq $((before + 1))

echo "== T5: qa dispatch reaches an unmarked-but-live IDLE Claude (shared classifier heals it)"
DESC="$SANDBOX/handoff.json"
cat > "$DESC" <<JSON
{ "project": "dispatch", "project_path": "$PROJ", "item_id": "dec-test1234",
  "what": "test handoff", "pickup_prompt": "pickup the QA handoff dec-test1234" }
JSON
# Run from the `live` desk's pane so the self-dispatch guard doesn't trip.
run_mux_in live qa dispatch "$DESC" >"$OUT" 2>&1; rc=$?
sleep 0.5
assert "qa dispatch exits 0 ($rc)" test "$rc" -eq 0
assert "dispatch INJECTED instead of queueing (unmarked Claude now visible)" \
  bash -c "grep -qF 'injected into the idle main session' '$OUT'"
pane_snap "dispatch:0"
assert "pickup prompt landed in the Claude pane" \
  bash -c "grep -qF 'pickup the QA handoff dec-test1234' '$SNAP'"
assert "@mux_claude=1 backfilled by the dispatch path too" \
  test "$(win_opt dispatch:0 @mux_claude)" = "1"

echo "== T6: real-install process name is a bare version string => still positively verified (dec-c1dbcd8b live finding)"
before=$(win_count verstr)
run_mux_in verstr new "check version-named claude" >"$OUT" 2>&1; rc=$?
sleep 0.5
assert "mux new exits 0 ($rc)" test "$rc" -eq 0
pane_snap "verstr:0"
assert "NO launch keystrokes typed into the version-named live Claude" \
  bash -c "! grep -qF \"cd '\" '$SNAP'"
assert "@mux_claude=1 BACKFILLED despite digit-led process name" \
  test "$(win_opt verstr:0 @mux_claude)" = "1"
assert "work still routed to a new worktree window" \
  test "$(win_count verstr)" -eq $((before + 1))

echo ""
echo "RESULT: $pass passed, $fail failed (sandbox: $SANDBOX)"
exit $fail
