resolve-plan-dir.sh 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #!/bin/sh
  2. # planning-with-files: resolve active plan directory.
  3. #
  4. # Resolution order:
  5. # 1. $PLAN_ID env var → ./.planning/$PLAN_ID/ if exists
  6. # 2. ./.planning/.active_plan content → matching dir if exists
  7. # 3. Newest ./.planning/<dir>/ by mtime
  8. # 4. Otherwise empty stdout (caller falls back to legacy ./task_plan.md)
  9. #
  10. # Always exits 0. Never errors out the agent loop.
  11. #
  12. # Usage:
  13. # PLAN_DIR="$(sh scripts/resolve-plan-dir.sh)"
  14. # PLAN_FILE="${PLAN_DIR:+$PLAN_DIR/}task_plan.md"
  15. set -u
  16. PLAN_ROOT="${1:-${PWD}/.planning}"
  17. ACTIVE_FILE="${PLAN_ROOT}/.active_plan"
  18. resolve_from_env() {
  19. plan_id="${PLAN_ID:-}"
  20. [ -z "${plan_id}" ] && return 1
  21. candidate="${PLAN_ROOT}/${plan_id}"
  22. if [ -d "${candidate}" ]; then
  23. printf "%s\n" "${candidate}"
  24. return 0
  25. fi
  26. return 1
  27. }
  28. resolve_from_active_file() {
  29. [ -f "${ACTIVE_FILE}" ] || return 1
  30. plan_id="$(tr -d '\r\n' < "${ACTIVE_FILE}")"
  31. [ -z "${plan_id}" ] && return 1
  32. candidate="${PLAN_ROOT}/${plan_id}"
  33. if [ -d "${candidate}" ]; then
  34. printf "%s\n" "${candidate}"
  35. return 0
  36. fi
  37. return 1
  38. }
  39. resolve_latest_dir() {
  40. [ -d "${PLAN_ROOT}" ] || return 1
  41. # Portable newest-mtime selector. Avoid `ls -t` BSD/GNU drift.
  42. # Only consider dirs that contain task_plan.md — skips system dirs like sessions/.
  43. latest=""
  44. latest_mtime=0
  45. for entry in "${PLAN_ROOT}"/*/; do
  46. [ -d "${entry}" ] || continue
  47. # Strip trailing slash
  48. clean="${entry%/}"
  49. # Skip hidden dirs
  50. case "$(basename "${clean}")" in
  51. .*) continue ;;
  52. esac
  53. # Skip dirs that are not plan dirs
  54. [ -f "${clean}/task_plan.md" ] || continue
  55. mtime="$(date -r "${clean}" +%s 2>/dev/null || stat -c '%Y' "${clean}" 2>/dev/null || echo 0)"
  56. if [ "${mtime}" -gt "${latest_mtime}" ] 2>/dev/null; then
  57. latest_mtime="${mtime}"
  58. latest="${clean}"
  59. fi
  60. done
  61. if [ -n "${latest}" ]; then
  62. printf "%s\n" "${latest}"
  63. return 0
  64. fi
  65. return 1
  66. }
  67. if resolve_from_env; then exit 0; fi
  68. if resolve_from_active_file; then exit 0; fi
  69. if resolve_latest_dir; then exit 0; fi
  70. exit 0