migrate-sessions.sh 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #!/usr/bin/env bash
  2. #
  3. # Migrate sessions from ~/.pi/agent/*.jsonl to proper session directories.
  4. # This fixes sessions created by the bug in v0.30.0 where sessions were
  5. # saved to ~/.pi/agent/ instead of ~/.pi/agent/sessions/<encoded-cwd>/.
  6. #
  7. # Usage: ./migrate-sessions.sh [--dry-run]
  8. #
  9. set -e
  10. AGENT_DIR="${PI_AGENT_DIR:-$HOME/.pi/agent}"
  11. DRY_RUN=false
  12. if [[ "$1" == "--dry-run" ]]; then
  13. DRY_RUN=true
  14. echo "Dry run mode - no files will be moved"
  15. echo
  16. fi
  17. # Find all .jsonl files directly in agent dir (not in subdirectories)
  18. shopt -s nullglob
  19. files=("$AGENT_DIR"/*.jsonl)
  20. shopt -u nullglob
  21. if [[ ${#files[@]} -eq 0 ]]; then
  22. echo "No session files found in $AGENT_DIR"
  23. exit 0
  24. fi
  25. echo "Found ${#files[@]} session file(s) to migrate"
  26. echo
  27. migrated=0
  28. failed=0
  29. for file in "${files[@]}"; do
  30. filename=$(basename "$file")
  31. # Read first line and extract cwd using jq
  32. if ! first_line=$(head -1 "$file" 2>/dev/null); then
  33. echo "SKIP: $filename - cannot read file"
  34. ((failed++))
  35. continue
  36. fi
  37. # Parse JSON and extract cwd
  38. if ! cwd=$(echo "$first_line" | jq -r '.cwd // empty' 2>/dev/null); then
  39. echo "SKIP: $filename - invalid JSON"
  40. ((failed++))
  41. continue
  42. fi
  43. if [[ -z "$cwd" ]]; then
  44. echo "SKIP: $filename - no cwd in session header"
  45. ((failed++))
  46. continue
  47. fi
  48. # Encode cwd: remove leading slash, replace slashes with dashes, wrap with --
  49. encoded=$(echo "$cwd" | sed 's|^/||' | sed 's|[/:\\]|-|g')
  50. encoded="--${encoded}--"
  51. target_dir="$AGENT_DIR/sessions/$encoded"
  52. target_file="$target_dir/$filename"
  53. if [[ -e "$target_file" ]]; then
  54. echo "SKIP: $filename - target already exists"
  55. ((failed++))
  56. continue
  57. fi
  58. echo "MIGRATE: $filename"
  59. echo " cwd: $cwd"
  60. echo " to: $target_dir/"
  61. if [[ "$DRY_RUN" == false ]]; then
  62. mkdir -p "$target_dir"
  63. mv "$file" "$target_file"
  64. fi
  65. ((migrated++))
  66. echo
  67. done
  68. echo "---"
  69. echo "Migrated: $migrated"
  70. echo "Skipped: $failed"
  71. if [[ "$DRY_RUN" == true && $migrated -gt 0 ]]; then
  72. echo
  73. echo "Run without --dry-run to perform the migration"
  74. fi