#!/usr/bin/env bash
# Resolve the tmux pane that the CURRENT process actually runs in.
#
# Why this exists: Claude Code's Bash tool strips $TMUX and $TMUX_PANE, so a
# bare `tmux display-message -p '#{pane_id}'` does NOT return the caller's pane
# — it returns the pane of the most-recently-active tmux *client*, which (when
# the user has several attached sessions) is frequently a DIFFERENT session
# than the one the okstra run lives in. Earlier trace-pane fixes all trusted
# `display-message` and therefore mis-placed (or dropped) the tail pane.
#
# This resolver instead walks the process's own ancestor PIDs and matches them
# against the tmux server's pane_pids. That is deterministic and correct
# regardless of $TMUX/$TMUX_PANE or which client is active: when the process is
# a descendant of a tmux pane's shell it finds exactly that pane; when it is not
# inside any tmux pane (e.g. Claude launched from the macOS GUI app) no ancestor
# matches and the function prints nothing.
#
# Usage: pane="$(okstra_resolve_caller_pane)"   # empty => not in a tmux pane
# Optional arg: a starting PID (defaults to $$) — used by the regression test.
# bash 3.2 safe (no associative arrays).
okstra_resolve_caller_pane() {
  command -v tmux >/dev/null 2>&1 || return 0
  local panes
  panes="$(tmux list-panes -a -F '#{pane_pid} #{pane_id}' 2>/dev/null)" || return 0
  [ -n "$panes" ] || return 0

  local pid="${1:-$$}"
  local depth=0
  local hit
  while [ -n "$pid" ] && [ "$pid" != "0" ] && [ "$depth" -lt 16 ]; do
    hit="$(printf '%s\n' "$panes" | awk -v p="$pid" '$1==p {print $2; exit}')"
    if [ -n "$hit" ]; then
      printf '%s\n' "$hit"
      return 0
    fi
    pid="$(ps -o ppid= -p "$pid" 2>/dev/null | tr -d ' ')"
    depth=$((depth + 1))
  done
  return 0
}
