#!/usr/bin/env bash
#
# okstra-compact-reminder.sh — SessionStart(matcher: compact) 훅.
#
# 컴팩션(/compact 또는 자동) 후 배치/게이트 정리 의무가 리드의 working context
# 에서 사라질 수 있다. 이 훅은 SessionStart stdin JSON 의 cwd 로 이 프로젝트의
# 진행 중 okstra run 을 찾아, 완료 pane/task 가 어떻게 회수되는지 사실 서술
# 리마인더를 stdout 으로 낸다(SessionStart 는 평문 stdout 이 컨텍스트로 주입됨).
# 활성 run 이 없으면 무출력. 세션 진행을 절대 막지 않는다 — 실패는 삼키고 exit 0.
set -u

_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
home="${OKSTRA_HOME:-$HOME/.okstra}"
# pane_reclaim 패키지는 repo(scripts/okstra_ctl)·설치($OKSTRA_HOME/lib/python)
# 양쪽에 있을 수 있으므로 둘 다 PYTHONPATH 에 둔다.
export PYTHONPATH="${_dir}:${home}/lib/python${PYTHONPATH:+:$PYTHONPATH}"

_stdin="$(cat 2>/dev/null || true)"
cwd="$(printf '%s' "$_stdin" | python3 -c 'import json,sys
try:
    print(json.load(sys.stdin).get("cwd","") or "")
except Exception:
    pass' 2>/dev/null || true)"
[ -n "$cwd" ] || cwd="$PWD"

while IFS= read -r run_dir; do
  [ -n "$run_dir" ] || continue
  cat <<EOF
An okstra run is in progress for this project: ${run_dir}
For this run, the panes of dispatches that have finished are closed at every worker round/phase boundary and immediately before the lead asks the user for any approval, clarification, or decision. Count them first with \`okstra team reclaim --project-root <PROJECT_ROOT> --run-manifest <RUN_MANIFEST> --dry-run\`, report that count as \`PROGRESS: phase-batch-cleanup panes=<n>\`, then run the same command without --dry-run to close them. In-progress dispatches keep their panes. The completed workers' background tasks are then stopped with TaskStop; TaskStop alone idles the roster task and closes no pane, so it is not cleanup on its own.
EOF
done < <(python3 -m okstra_ctl.pane_reclaim --in-flight-run-dirs-for "$cwd" 2>/dev/null || true)

exit 0
