stop-server.sh 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #!/usr/bin/env bash
  2. # Stop the brainstorm server and clean up
  3. # Usage: stop-server.sh <session_dir>
  4. #
  5. # Kills the server process. Only deletes session directory if it's
  6. # under /tmp (ephemeral). Persistent directories (.superpowers/) are
  7. # kept so mockups can be reviewed later.
  8. SESSION_DIR="$1"
  9. if [[ -z "$SESSION_DIR" ]]; then
  10. echo '{"error": "Usage: stop-server.sh <session_dir>"}'
  11. exit 1
  12. fi
  13. STATE_DIR="${SESSION_DIR}/state"
  14. PID_FILE="${STATE_DIR}/server.pid"
  15. # Confirm a PID is actually our brainstorm server (node running server.cjs),
  16. # not a reused/unrelated process whose PID was recycled into a stale pid file.
  17. is_brainstorm_server() {
  18. kill -0 "$1" 2>/dev/null || return 1
  19. case "$(ps -p "$1" -o command= 2>/dev/null)" in
  20. *node*server.cjs*) return 0 ;;
  21. *) return 1 ;;
  22. esac
  23. }
  24. if [[ -f "$PID_FILE" ]]; then
  25. pid=$(cat "$PID_FILE")
  26. # Refuse to signal a PID we can't prove is our server. A stale pid file may
  27. # point at an unrelated process after a reboot/PID wraparound.
  28. if ! is_brainstorm_server "$pid"; then
  29. rm -f "$PID_FILE"
  30. echo '{"status": "stale_pid"}'
  31. exit 0
  32. fi
  33. # Try to stop gracefully, fallback to force if still alive
  34. kill "$pid" 2>/dev/null || true
  35. # Wait for graceful shutdown (up to ~2s)
  36. for i in {1..20}; do
  37. if ! kill -0 "$pid" 2>/dev/null; then
  38. break
  39. fi
  40. sleep 0.1
  41. done
  42. # If still running, escalate to SIGKILL
  43. if kill -0 "$pid" 2>/dev/null; then
  44. kill -9 "$pid" 2>/dev/null || true
  45. # Give SIGKILL a moment to take effect
  46. sleep 0.1
  47. fi
  48. if kill -0 "$pid" 2>/dev/null; then
  49. echo '{"status": "failed", "error": "process still running"}'
  50. exit 1
  51. fi
  52. rm -f "$PID_FILE" "${STATE_DIR}/server.log"
  53. # Only delete ephemeral /tmp directories
  54. if [[ "$SESSION_DIR" == /tmp/* ]]; then
  55. rm -rf "$SESSION_DIR"
  56. fi
  57. echo '{"status": "stopped"}'
  58. else
  59. echo '{"status": "not_running"}'
  60. fi