#!/usr/bin/env bash
set -euo pipefail

# bash >= 4.2 per associative arrays e [[ -v arr[key] ]]
if ((BASH_VERSINFO[0] < 4 || (BASH_VERSINFO[0] == 4 && BASH_VERSINFO[1] < 2))); then
  if command -v tmux >/dev/null 2>&1; then
    tmux display-message 'tmux-picker: serve bash >= 4.2'
  else
    printf 'tmux-picker: serve bash >= 4.2\n' >&2
  fi
  exit 1
fi

self="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/$(basename -- "${BASH_SOURCE[0]}")"
mode="${TMUX_PICKER_MODE:-default}"
git_status_script="$HOME/.tmux/scripts/git-pane-status.sh"

cache_dir() {
  REPLY="${TMPDIR:-/tmp}/tmux-picker-cache-${UID:-$(id -u)}"
}

clear_cache() {
  cache_dir
  rm -rf -- "$REPLY"
}

install_tmux_hooks() {
  local picker="${1:-$HOME/.local/bin/tmux-session-picker}"
  local cmd

  command -v tmux >/dev/null 2>&1 || { printf 'tmux-picker: tmux non trovato\n' >&2; return 1; }
  cmd="$picker clear-cache"

  # Use fixed hook array indexes so repeated installs replace xtmux's hooks
  # without clobbering unrelated user hooks on the same events.
  tmux set-hook -g 'session-created[90]' "run-shell '$cmd'"
  tmux set-hook -g 'session-closed[90]' "run-shell '$cmd'"
  tmux set-hook -g 'window-linked[90]' "run-shell '$cmd'"
  tmux set-hook -g 'window-unlinked[90]' "run-shell '$cmd'"
}

c_reset=$'\033[0m'
c_dim=$'\033[38;5;244m'
c_session=$'\033[38;5;255m'
c_repo=$'\033[38;5;81m'
c_pane=$'\033[38;5;246m'
c_sp=$'\033[38;5;141m'      # specialist (sp-*) badge: violet
c_stale=$'\033[38;5;130m'   # orphan/finished-but-open specialist: dark amber

run_git() {
  if command -v timeout >/dev/null 2>&1; then
    timeout 0.7 git "$@" 2>/dev/null
  else
    git "$@" 2>/dev/null
  fi
}

paint() {
  REPLY="$1${*:2}$c_reset"
}

sanitize_osc() {
  sed -E $'s/\x1b\][^\x1b\x07]*(\x07|\x1b\\\\)//g'
}

capture_pane_safe() {
  local target="$1"
  local start="$2"
  local out
  out="$(tmux capture-pane -p -e -t "$target" -S "$start" 2>/dev/null)" || {
    printf '(pane non leggibile)\n'
    return 0
  }
  printf '%s\n' "$out" | sanitize_osc
}

# Stati normalizzati: needs-input | done | running | idle | ""
# Sorgente primaria: @agent_state scritto dagli hook agent. Questo include anche pi.
normalize_agent_state() {
  local pane_id="$1"
  local opt="$2"
  local cmd="$3"
  local tail

  case "$opt" in
    needs-input|permission|waiting|input) REPLY='needs-input'; return 0 ;;
    done|finished|stop|complete)          REPLY='done';        return 0 ;;
    running|working|thinking|busy|tool)
      if agent_state_is_stale "${4:-}"; then REPLY='stale'; else REPLY='running'; fi
      return 0 ;;
    idle)                                  REPLY='idle';        return 0 ;;
    ''|-|off|none) ;;
    *) REPLY="$opt"; return 0 ;;
  esac

  [ "${TMUX_PICKER_AGENT:-0}" = '1' ] || { REPLY=''; return 0; }

  case "$cmd" in
    claude|codex|aider|cursor|node|python|python3|ollama|llm|opencode|pi) ;;
    *) REPLY=''; return 0 ;;
  esac

  tail="$(tmux capture-pane -p -t "$pane_id" -S -3 2>/dev/null | tr -d '\r')"
  [ -n "$tail" ] || { REPLY='idle'; return 0; }

  if printf '%s' "$tail" | grep -qiE 'do you want|allow|approve|\(y/n\)|permission|press enter|waiting for|\? '; then
    REPLY='needs-input'
  elif printf '%s' "$tail" | grep -qiE 'esc to interrupt|thinking|working|running|generating|compiling|[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏]'; then
    REPLY='running'
  else
    REPLY='idle'
  fi
}

# xtmux-dvs defect 2: @agent_state is a last-write-wins pane option, so a pane
# that died mid-turn keeps advertising `running` forever. On 2026-08-05 five
# panes reported running with @agent_last_transition frozen for over eight hours
# after a usage limit killed them mid-request, and every consumer that read the
# state alone concluded the lanes were healthy.
#
# Only `running` is falsifiable by age. `needs-input`, `done` and `idle` are
# legitimately durable — a pane can sit at a permission prompt for a day and the
# state is still true.
#
# Fails OPEN: a pane with no @agent_last_transition, or an unparseable value, is
# never called stale. The option is genuinely unset on some panes, and an
# aggressive default there would be the mirror image of the bug.
#
# Threshold: XTMUX_AGENT_STALE_AFTER (`45m`, `90s`, `2h`), default 45m, 0 disables.
# The same default and variable are honoured by src/tmux.ts.
agent_stale_after_s() {
  if [ -z "${_XTMUX_STALE_AFTER_S:-}" ]; then
    if [ -n "${XTMUX_AGENT_STALE_AFTER:-}" ] && parse_wait_duration "${XTMUX_AGENT_STALE_AFTER}"; then
      _XTMUX_STALE_AFTER_S="$REPLY"
    else
      _XTMUX_STALE_AFTER_S=2700
    fi
  fi
  REPLY="$_XTMUX_STALE_AFTER_S"
}

# agent_state_is_stale <last_transition> -> 0 when stale
#
# The timestamp is supplied by the caller, never fetched here. Every bulk caller
# already enumerates panes with `tmux list-panes -F`, so carrying
# @agent_last_transition in that same format costs no extra tmux call. An earlier
# revision fell back to one `show-options` per running pane; that read is
# invisible in normal use but is counted by the monitor_run poll-tick contracts
# in test/contract.sh, which stub `tmux` and assert an exact call count. Reading
# only what the caller already has keeps the probe count untouched and the hot
# list path free.
#
# Callers with no timestamp to hand pass nothing and get the fail-open answer.
agent_state_is_stale() {
  local lt="${1:-}" after ts now
  [ -n "$lt" ] && [ "$lt" != '-' ] || return 1
  agent_stale_after_s; after="$REPLY"
  [ "$after" -gt 0 ] || return 1
  ts="$(date -d "$lt" +%s 2>/dev/null)" || return 1
  [ -n "$ts" ] || return 1
  now="$(date +%s)"
  [ "$(( now - ts ))" -gt "$after" ]
}

agent_rank() {
  case "$1" in
    stale)       REPLY=0 ;;
    needs-input) REPLY=1 ;;
    done)        REPLY=2 ;;
    running)     REPLY=3 ;;
    *)           REPLY=4 ;;
  esac
}

agent_state_is_working() {
  case "${1:-}" in
    running|working|busy|thinking|tool) return 0 ;;
    *) return 1 ;;
  esac
}

state_badge() {
  case "$1" in
    stale)       REPLY=$'\033[38;5;203m[stale]'"$c_reset" ;;
    needs-input) REPLY=$'\033[38;5;214m[wait]'"$c_reset" ;;
    done)        REPLY=$'\033[38;5;78m[done]'"$c_reset" ;;
    running)     REPLY=$'\033[38;5;81m[run]'"$c_reset" ;;
    idle)        REPLY="${c_dim}[idle]${c_reset}" ;;
    *) REPLY='' ;;
  esac
}

idle_badge() {
  local activity="${1:-}" now="${2:-}" threshold_mins="${TMUX_PICKER_STALE_MINS:-60}"
  local age mins label color
  IDLE_STALE=0

  [[ "$activity" =~ ^[0-9]+$ ]] || { REPLY=''; return 0; }
  [[ "$now" =~ ^[0-9]+$ ]] || now="$(date +%s)"
  [[ "$threshold_mins" =~ ^[0-9]+$ ]] || threshold_mins=60

  age=$(( now - activity ))
  [ "$age" -lt 0 ] && age=0
  mins=$(( age / 60 ))

  if [ "$age" -lt 60 ]; then
    label='idle <1m'
  elif [ "$age" -lt 3600 ]; then
    label="idle ${mins}m"
  elif [ "$age" -lt 86400 ]; then
    label="idle $(( age / 3600 ))h"
  else
    label="idle $(( age / 86400 ))d"
  fi

  color="$c_dim"
  if [ "$mins" -ge "$threshold_mins" ]; then
    IDLE_STALE=1
    color="$c_stale"
  fi
  REPLY="${color}[$label]${c_reset}"
}

# --- specialist (sp-*) + role (role-*) awareness (xtmux-rib.4, xtmux-2i5) ----
# detection is name + pane_pid based (no capture-pane cost). a pane is a
# specialist / interactive role if its session name matches one of:
#   ^sp-<role>-<hex>$        managed sp job
#   ^role-<role>[-<slug>]$   interactive role session (xt pi --role)
# and the pane_pid is alive.
#
# hot list path never calls sp/jq/ps/pgrep: it only checks session name + pane
# pid. preview may inspect the pane process tree to extract --bead, but the picker
# does not call `sp ps` or read specialists job db in normal operation.
# a live sp-* pane is treated as [stale] unless an explicit @agent_state says
# otherwise (e.g. needs-input -> [wait]).

# sp_role_from_name <session_name> -> REPLY=role (or empty)
sp_role_from_name() {
  local name="$1"
  REPLY=''
  if [[ "$name" =~ ^sp-([a-z][a-z0-9-]*)-[0-9a-f]+$ ]]; then
    REPLY="${BASH_REMATCH[1]}"
  elif [[ "$name" =~ ^role-([a-z][a-z0-9-]*[a-z0-9])-[0-9a-f]{4,}$ ]]; then
    REPLY="${BASH_REMATCH[1]}"
  elif [[ "$name" =~ ^role-([a-z][a-z0-9-]*[a-z0-9])$ ]]; then
    REPLY="${BASH_REMATCH[1]}"
  fi
}

# sp_hash_from_name <session_name> -> REPLY=6-ish suffix hash (or empty)
sp_hash_from_name() {
  local name="$1"
  REPLY=''
  if [[ "$name" =~ ^sp-[a-z][a-z0-9-]*-([0-9a-f]+)$ ]]; then
    REPLY="${BASH_REMATCH[1]}"
  elif [[ "$name" =~ ^role-[a-z][a-z0-9-]*[a-z0-9]-([0-9a-f]{4,})$ ]]; then
    REPLY="${BASH_REMATCH[1]}"
  fi
}

# sp_is_specialist <session_name> <pane_pid> -> REPLY=role if specialist else empty
sp_is_specialist() {
  local name="$1" pid="$2"
  sp_role_from_name "$name"
  [ -n "$REPLY" ] || return 0
  # pane must be alive. -0 kills with signal 0 (no-op test).
  [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null || REPLY=''
}

# sp_bead_from_pane <pane_pid> -> REPLY=bead id (or empty), via child cmdline.
# the specialists bun process is a child of the pane shell; its cmdline carries
# --bead <id>. tolerant: returns empty if not found.
sp_bead_from_pane() {
  local pid="$1" proc cmdline
  REPLY=''
  [ -n "$pid" ] || return 0
  for proc in "$pid" $(pgrep -P "$pid" 2>/dev/null || true); do
    [ -n "$proc" ] || continue
    cmdline="$(ps -o args= -p "$proc" 2>/dev/null | head -1 || true)"
    if [[ "$cmdline" =~ --bead[[:space:]]+([^[:space:]]+) ]]; then
      REPLY="${BASH_REMATCH[1]}"
      return 0
    fi
  done
}

# sp_proc_state_from_pane <pane_pid> -> REPLY=running|'' via process tree.
# preview-only. detects a live specialists runner/feed process without calling sp.
sp_proc_state_from_pane() {
  local pid="$1" proc cmdline
  REPLY=''
  [ -n "$pid" ] || return 0
  for proc in "$pid" $(pgrep -P "$pid" 2>/dev/null || true); do
    [ -n "$proc" ] || continue
    cmdline="$(ps -o args= -p "$proc" 2>/dev/null | head -1 || true)"
    case "$cmdline" in
      *'/specialists/dist/index.js run '*|*'/specialists/dist/index.js feed '*|*' specialists/dist/index.js run '*|*' specialists/dist/index.js feed '*)
        REPLY='running'
        return 0
        ;;
    esac
  done
}

# sp_meta <session_name> <pane_pid> -> sets globals sp_role sp_bead sp_state sp_stale
# one-stop resolution for a specialist pane. sp_stale=1 means the pane is alive
# but there is no explicit live specialist state, so it is a cleanup target.
sp_role=''; sp_bead=''; sp_state=''; sp_stale=''
sp_meta() {
  sp_role=''; sp_bead=''; sp_state=''; sp_stale=''
  sp_is_specialist "$1" "$2"
  sp_role="$REPLY"
  [ -n "$sp_role" ] || return 0
  sp_bead_from_pane "$2"; sp_bead="$REPLY"
  sp_proc_state_from_pane "$2"; sp_state="$REPLY"
  # no `sp ps` integration by design: it was too slow/unreliable for the picker.
  # preview can inspect process tree: if no runner/feed is alive, mark stale.
  [ -z "$sp_state" ] && sp_stale=1 || sp_stale='' 
}

# sp_badge -> REPLY = colored [sp] + optional [stale]. used in render_pane_line.
sp_badge() {
  local out
  paint "$c_sp" '[sp]'; out="$REPLY"
  if [ "${sp_stale:-0}" = 1 ]; then
    out+=" "
    paint "$c_stale" '[stale]'; out+="$REPLY"
  fi
  REPLY="$out"
}

short_path() {
  local p="${1:-}"
  [ -n "$p" ] || { REPLY=''; return 0; }
  if [[ "$p" == "$HOME"* ]]; then
    p="~${p#$HOME}"
  fi

  local parts
  IFS='/' read -r -a parts <<< "$p"
  local n=${#parts[@]}
  if [ "$n" -le 4 ]; then
    REPLY="$p"
    return
  fi

  REPLY="…/${parts[$((n-3))]}/${parts[$((n-2))]}/${parts[$((n-1))]}"
}

short_rel_path() {
  local rel="${1:-}"
  [ -n "$rel" ] || { REPLY=''; return 0; }

  local parts
  IFS='/' read -r -a parts <<< "$rel"
  local n=${#parts[@]}
  if [ "$n" -le 2 ]; then
    REPLY="$rel"
    return
  fi

  REPLY="…/${parts[$((n-2))]}/${parts[$((n-1))]}"
}

relative_hint() {
  local pane_path="${1:-}"
  local root="${2:-}"
  [ -n "$pane_path" ] || { REPLY=''; return 0; }
  [ -n "$root" ] || { REPLY=''; return 0; }
  [ "$pane_path" != "$root" ] || { REPLY=''; return 0; }

  local rel="${pane_path#"$root"/}"
  [ "$rel" != "$pane_path" ] || { REPLY=''; return 0; }
  short_rel_path "$rel"   # sets REPLY
}

git_root_for_path() {
  local p="${1:-}"
  [ -n "$p" ] || { REPLY=''; return 0; }
  REPLY="$(run_git -C "$p" rev-parse --show-toplevel 2>/dev/null || true)"
}

# group_root_for_path <pane_path> <git_root> -> REPLY=sort/group key
# keep git status/display tied to the actual worktree, but group known xtrm/tmux
# worktree layouts under their parent repo so sp-* jobs don't float as separate
# top-level repos in the picker.
group_root_for_path() {
  local pane_path="${1:-}"
  local root="${2:-}"
  local base=''

  case "$pane_path" in
    */.xtrm/worktrees/*) base="${pane_path%%/.xtrm/worktrees/*}" ;;
    */.worktrees/*)      base="${pane_path%%/.worktrees/*}" ;;
  esac

  if [ -n "$base" ] && { [ -d "$base/.git" ] || [ -f "$base/.git" ]; }; then
    REPLY="$base"
    return 0
  fi

  REPLY="${root:-$pane_path}"
}

status_for_path() {
  local pane_id="${1:-}"
  local pane_path="${2:-}"

  if [ -x "$git_status_script" ]; then
    if [ -z "$pane_id" ] && [ -n "$pane_path" ]; then
      # path is already the resolved repo toplevel (build_list resolves it
      # first); tell the status script so it skips a redundant rev-parse.
      REPLY="$(TMUX_GIT_TOPLEVEL="$pane_path" "$git_status_script" "" "$pane_path" 2>/dev/null)" || short_path "$pane_path"
    else
      REPLY="$("$git_status_script" "$pane_id" "$pane_path" 2>/dev/null)" || short_path "$pane_path"
    fi
  else
    short_path "$pane_path"
  fi
}

status_meta_from_root_status() {
  local raw="${1:-}"
  local rest meta

  [ -n "$raw" ] || { REPLY=''; return 0; }
  rest="${raw#* }"
  if [ "$rest" = "$raw" ]; then
    REPLY="$raw"
    return 0
  fi

  case "$rest" in
    *'  '*) meta="${rest%%  *}" ;;
    *' path '*) meta="${rest%% path *}" ;;
    *) meta="$rest" ;;
  esac

  REPLY="$meta"
}

render_list_status() {
  local pane_path="${1:-}"
  local root="${2:-}"
  local root_status="${3:-}"
  local repo meta rel out

  if [ -z "$root" ]; then
    short_path "$pane_path"
    paint "$c_dim" "$REPLY"   # sets REPLY
    return 0
  fi

  repo="${root##*/}"
  status_meta_from_root_status "$root_status"; meta="$REPLY"
  relative_hint "$pane_path" "$root"; rel="$REPLY"

  paint "$c_repo" "$repo"; out="$REPLY"
  [ -n "$meta" ] && out+=" $meta"
  if [ -n "$rel" ]; then paint "$c_dim" "· $rel"; out+=" $REPLY"; fi
  REPLY="$out"
}

pane_location_hint() {
  local pane_path="${1:-}"
  local root="${2:-}"
  local repo rel out

  if [ -z "$root" ]; then
    short_path "$pane_path"
    paint "$c_dim" "$REPLY"   # sets REPLY
    return 0
  fi

  repo="${root##*/}"
  relative_hint "$pane_path" "$root"; rel="$REPLY"

  paint "$c_repo" "$repo"; out="$REPLY"
  if [ -n "$rel" ]; then paint "$c_dim" "· $rel"; out+=" $REPLY"; fi
  REPLY="$out"
}

session_meta() {
  # Replace record delimiters before tmux emits TSV. Sanitizing after read is
  # too late because an embedded newline has already become another record.
  tmux list-sessions -F $'#{session_id}\t#{s/\n/ /:#{s/\t/ /:session_name}}\t#{pane_id}\t#{s/\n/ /:#{s/\t/ /:pane_current_path}}\t#{session_activity}'
}

pane_meta() {
  tmux list-panes -a -F $'#{session_id}\t#{window_index}\t#{s/\n/ /:#{s/\t/ /:window_name}}\t#{pane_id}\t#{pane_index}\t#{pane_active}\t#{s/\n/ /:#{s/\t/ /:pane_current_command}}\t#{s/\n/ /:#{s/\t/ /:pane_current_path}}\t#{?@agent_state,#{s/\n/ /:#{s/\t/ /:@agent_state}},-}\t#{pane_pid}\t#{?@agent_bead,#{s/\n/ /:#{s/\t/ /:@agent_bead}},-}\t#{?@agent_task,#{s/\n/ /:#{s/\t/ /:@agent_task}},-}\t#{?@agent_parent_session,#{s/\n/ /:#{s/\t/ /:@agent_parent_session}},-}\t#{?@agent_last_transition,#{s/\n/ /:#{s/\t/ /:@agent_last_transition}},-}'
}

agent_meta_value() {
  case "${1:-}" in ''|-) REPLY='' ;; *) REPLY="${1//$'\t'/ }"; REPLY="${REPLY//$'\n'/ }" ;; esac
}

agent_meta_label() {
  local bead task parent out=''
  agent_meta_value "${1:-}"; bead="$REPLY"
  agent_meta_value "${2:-}"; task="$REPLY"
  agent_meta_value "${3:-}"; parent="$REPLY"
  [ "${#task}" -gt 36 ] && task="${task:0:33}..."
  [ -n "$bead" ] && out+=" bead:$bead"
  [ -n "$task" ] && out+=" task:$task"
  [ -n "$parent" ] && out+=" from:$parent"
  if [ -n "$out" ]; then
    paint "$c_dim" "$out"; REPLY="$REPLY"
  else
    REPLY=''
  fi
}

bead_preview_summary() {
  local cwd="${1:-$PWD}" bead="${2:-}" out
  agent_meta_value "$bead"; bead="$REPLY"
  [ -n "$bead" ] || return 0
  command -v bd >/dev/null 2>&1 || { printf 'bead-context %s (bd unavailable)\n' "$bead"; return 0; }
  out="$(cd "$cwd" 2>/dev/null && bd show "$bead" 2>/dev/null | sed -n '1,18p' || true)"
  if [ -n "$out" ]; then
    printf '\nbead-context %s\n' "$bead"
    printf '%s\n' "$out"
  else
    printf '\nbead-context %s (not found from %s)\n' "$bead" "$cwd"
  fi
}

extract_bead_id() {
  local text="${1:-}" line
  # Conservative: require a dot-number child id (e.g. xtmux-rib.16). This avoids
  # treating arbitrary worktree slugs such as feature-123 as bead ids.
  #
  # The DASH is load-bearing, and it is not cosmetic. This is run over whole
  # filesystem paths, and without it the pattern also matches `tmp.9` inside
  # /tmp/tmp.9aBcDeFg — mktemp's suffix begins with a digit roughly one time in
  # six. A pane whose cwd was a temp dir would then be labelled with the bead
  # `tmp.9`, which exists nowhere and which nobody can look up. Every real bead id
  # is <prefix>-<slug>.<n>, so requiring the dash rejects the false positive and
  # accepts every genuine id. (It also made the contract suite flake ~1 run in 3,
  # dependent on nothing but the random name mktemp handed it.)
  line="$(printf '%s\n' "$text" | grep -Eo '[A-Za-z][A-Za-z0-9]*-[A-Za-z0-9.-]*[A-Za-z0-9]\.[0-9]+' | head -1 || true)"
  REPLY="$line"
}

refine_derived_bead_id() {
  local candidate="${1:-}" cur
  [ -n "$candidate" ] || { REPLY=''; return 0; }
  if command -v bd >/dev/null 2>&1; then
    cur="$candidate"
    while [ -n "$cur" ]; do
      if bd show "$cur" >/dev/null 2>&1; then REPLY="$cur"; return 0; fi
      case "$cur" in *-*) cur="${cur#*-}" ;; *) break ;; esac
    done
    REPLY=''
  else
    REPLY="$candidate"
  fi
}

derive_bead_id() {
  local session_name="${1:-}" pane_path="${2:-}" root="${3:-}" rel candidate
  extract_bead_id "$session_name"; candidate="$REPLY"
  refine_derived_bead_id "$candidate"; [ -n "$REPLY" ] && return 0

  rel=''
  if [ -n "$root" ]; then
    case "$pane_path" in "$root"/*) rel="${pane_path#"$root"/}" ;; esac
  fi
  if [ -z "$rel" ]; then
    case "$pane_path" in
      */.xtrm/worktrees/*) rel="${pane_path#*/.xtrm/worktrees/}" ;;
      */.worktrees/*) rel="${pane_path#*/.worktrees/}" ;;
      *) rel="${pane_path##*/}" ;;
    esac
  fi
  extract_bead_id "$rel"; candidate="$REPLY"
  refine_derived_bead_id "$candidate"; [ -n "$REPLY" ] && return 0
  REPLY=''
}

git_worktree_preview() {
  local root="${1:-}" branch dirty stat
  [ -n "$root" ] || return 0
  [ -d "$root/.git" ] || git -C "$root" rev-parse --is-inside-work-tree >/dev/null 2>&1 || return 0
  branch="$(git -C "$root" rev-parse --abbrev-ref HEAD 2>/dev/null || true)"
  dirty="$(git -C "$root" status --short 2>/dev/null | wc -l | tr -d ' ')"
  [ -n "$dirty" ] || dirty=0
  printf '\ngit-worktree'
  [ -n "$branch" ] && printf ' branch=%s' "$branch"
  printf ' dirty=%s\n' "$dirty"
  if [ "$dirty" -gt 0 ]; then
    stat="$( { git -C "$root" diff --stat 2>/dev/null; git -C "$root" diff --cached --stat 2>/dev/null; } | sed -n '1,12p' || true)"
    [ -n "$stat" ] && { printf 'diff-stat\n'; printf '%s\n' "$stat"; }
  fi
}

preview_enrichment() {
  local cwd="${1:-$PWD}" root="${2:-}" session_name="${3:-}" explicit_bead="${4:-}" bead
  agent_meta_value "$explicit_bead"; bead="$REPLY"
  if [ -z "$bead" ]; then
    derive_bead_id "$session_name" "$cwd" "$root"; bead="$REPLY"
    [ -n "$bead" ] && printf 'derived-bead=%s\n' "$bead"
  fi
  bead_preview_summary "$cwd" "$bead"
  git_worktree_preview "$root"
}

_worktree_collisions_tsv() {
  local sid sname pane_id path root key sessions panes n names pair
  declare -A root_sessions=()
  declare -A root_panes=()
  while IFS=$'\t' read -r sid sname pane_id path; do
    [ -n "$sid" ] || continue
    path="${path:-$HOME}"
    git_root_for_path "$path"; root="$REPLY"
    [ -n "$root" ] || continue
    key="$sid:$sname"
    case "|${root_sessions[$root]:-}|" in *"|$key|"*) ;; *) root_sessions[$root]+="${root_sessions[$root]:+|}$key" ;; esac
    root_panes[$root]="$(( ${root_panes[$root]:-0} + 1 ))"
  done < <(tmux list-panes -a -F $'#{session_id}\t#{session_name}\t#{pane_id}\t#{pane_current_path}' 2>/dev/null || true)

  for root in "${!root_sessions[@]}"; do
    sessions="${root_sessions[$root]}"
    IFS='|' read -ra _pairs <<< "$sessions"
    n="${#_pairs[@]}"
    [ "$n" -gt 1 ] || continue
    names=''
    for pair in "${_pairs[@]}"; do
      names+="${names:+,}${pair#*:}"
    done
    printf 'shared-worktree\t%s\t%s\t%s\t%s\n' "$root" "$n" "${root_panes[$root]:-0}" "$names"
  done | sort -t $'\t' -k2,2nr -k1,1
}

worktree_collisions() {
  local json=0 line type path sessions panes names first=1 name name_first count=0 started_ms="$(date +%s%3N)"
  [ "${1:-}" = '--json' ] && json=1
  if [ "$json" != 1 ]; then _worktree_collisions_tsv; return; fi
  printf '['
  while IFS=$'\t' read -r type path sessions panes names; do
    [ "$type" = shared-worktree ] || continue
    count=$(( count + 1 ))
    [ "$first" = 1 ] || printf ','; first=0
    printf '{"path":"%s","sessionCount":%s,"paneCount":%s,"sessionNames":[' "$(json_escape "$path")" "$sessions" "$panes"
    name_first=1
    IFS=',' read -ra _collision_names <<< "$names"
    for name in "${_collision_names[@]}"; do
      [ "$name_first" = 1 ] || printf ','; name_first=0
      printf '"%s"' "$(json_escape "$name")"
    done
    printf ']}'
  done < <(_worktree_collisions_tsv)
  printf ']\n'
  log_cli_emit query.completed command=worktree-collisions count="$count" duration_ms="$(( $(date +%s%3N) - started_ms ))" outcome=ok
}

tsv_clean() {
  local value="${1:-}"
  value="${value//$'\t'/ }"
  value="${value//$'\r'/ }"
  value="${value//$'\n'/ }"
  printf '%s' "$value"
}


xtmux_state_dir() {
  REPLY="${XDG_STATE_HOME:-$HOME/.local/state}/xtmux"
}

event_log_file() {
  if [ -n "${XTMUX_EVENT_LOG_FILE:-}" ]; then
    REPLY="$XTMUX_EVENT_LOG_FILE"
  else
    xtmux_state_dir
    REPLY="$REPLY/events.jsonl"
  fi
}

json_escape() {
  local s="${1:-}"
  s="${s//\\/\\\\}"
  s="${s//\"/\\\"}"
  s="${s//$'\t'/\\t}"
  s="${s//$'\r'/\\r}"
  s="${s//$'\n'/\\n}"
  printf '%s' "$s"
}

json_nullable() {
  case "${1:-}" in ''|-) printf 'null' ;; *) printf '"%s"' "$(json_escape "$1")" ;; esac
}

topology_number() {
  case "${1:-}" in
    ''|-) printf 'null' ;;
    *[!0-9]*) printf 'null' ;;
    *) printf '%s' "$1" ;;
  esac
}

topology_milliseconds() {
  case "${1:-}" in
    ''|-) printf 'null' ;;
    *[!0-9]*) printf 'null' ;;
    *) printf '%s000' "$1" ;;
  esac
}

topology_boolean() {
  case "${1:-}" in
    1|true|yes|on) printf 'true' ;;
    *) printf 'false' ;;
  esac
}

topology_agent_json() {
  local first=1 key value index
  # role/worktree/branch/parent_pane_id are named for xtrm.topology.projection.v1
  # (@xtrm/contracts), which is what Core's aggregation viewer joins this snapshot
  # into. Appended, never reordered: the earlier keys are a published contract.
  local -a keys=(instance_id state bead_id task prompt_file parent_session_id last_transition role worktree branch parent_pane_id)
  local -a values=("$@")
  for index in "${!keys[@]}"; do
    value="${values[$index]:-}"
    case "$value" in ''|-) continue ;; esac
    [ "$first" = 1 ] || printf ','
    first=0
    key="${keys[$index]}"
    printf '"%s":"%s"' "$key" "$(json_escape "$value")"
  done
}

# V1 deliberately retains its historical best-effort default-server lookup.
# V2 durable writes must not infer identity outside a tmux client: a bare shell
# can otherwise be attributed to whichever pane is current.
tmux_identity_available() {
  [ -n "${TMUX:-}" ] && return 0
  case "${XTMUX_OBS_V2:-}" in
    shadow|1) return 1 ;;
    *) return 0 ;;
  esac
}

current_tmux_session() {
  tmux_identity_available || { REPLY=''; return 0; }
  REPLY="$(tmux display-message -p '#S' 2>/dev/null || true)"
}

current_tmux_session_id() {
  tmux_identity_available || { REPLY=''; return 0; }
  REPLY="$(tmux display-message -p '#{session_id}' 2>/dev/null || true)"
}

current_tmux_pane() {
  tmux_identity_available || { REPLY=''; return 0; }
  REPLY="$(tmux display-message -p '#{pane_id}' 2>/dev/null || true)"
}

# Normalize any tmux target (session_id $N, pane_id %N, window_id @N, session
# name, or session:window.pane shorthand) to a stable #{session_id}. Sets REPLY
# to the session_id on success, empty on failure. Used by message-* to
# canonicalize the address space — writers and readers must agree on the same
# key for --for/--to matching to work.
resolve_to_session_id() {
  local target="${1:-}" out
  REPLY=''
  [ -n "$target" ] || return 1
  # tmux display-message returns 0 with empty output for a non-existent $N/%N
  # target instead of erroring, so we validate by checking the returned id.
  out="$(tmux display-message -p -t "$target" '#{session_id}' 2>/dev/null || true)"
  [ -n "$out" ] || return 1
  REPLY="$out"
  return 0
}

# Resolve a tmux target to a pane id. tmux does NOT accept a pane id (%N) as
# the window specifier in the `session:%N` shorthand: `spfix:%875` is parsed as
# session:window, the %875 window lookup fails, and tmux silently falls back to
# the session's CURRENT window — so `#{pane_id}` returns the active pane, not
# %875. Extract the %N suffix ourselves when the target carries one
# (session:%N or session:window.%N) and verify it is a live pane; otherwise ask
# tmux directly (a bare %N is server-global and resolves correctly). Sets REPLY
# to the pane id, empty on failure.
target_pane_id() {
  local target="${1:-}"
  REPLY=''
  [ -n "$target" ] || return 1
  case "$target" in
    *:%[0-9]*) REPLY="${target##*:}" ;;   # session:%N
    *.%[0-9]*) REPLY="${target##*.}" ;;   # session:window.%N
  esac
  if [ -n "$REPLY" ]; then
    # The extracted id must be a live pane; a stale %N would route to nothing.
    tmux display-message -p -t "$REPLY" '#{pane_id}' 2>/dev/null | grep -qx "$REPLY" || { REPLY=''; return 1; }
  else
    REPLY="$(tmux display-message -p -t "$target" '#{pane_id}' 2>/dev/null || true)"
  fi
  [ -n "$REPLY" ]
}

# human-friendly age from an epoch seconds value: 3s, 12m, 4h, 2d
format_age_short() {
  local epoch="${1:-0}" now diff
  now="$(date +%s 2>/dev/null || printf '0')"
  diff=$(( now - epoch ))
  (( diff < 0 )) && diff=0
  if (( diff < 60 ));      then REPLY="${diff}s"
  elif (( diff < 3600 ));  then REPLY="$(( diff / 60 ))m"
  elif (( diff < 86400 )); then REPLY="$(( diff / 3600 ))h"
  else                          REPLY="$(( diff / 86400 ))d"
  fi
}

# Best-effort size-triggered rotation. Keeps events.jsonl bounded so grep-based
# message-list stays fast. Rotation is opportunistic (checked at write time),
# not scheduled — no cron, no daemon.
XTMUX_EVENT_LOG_MAX_BYTES="${XTMUX_EVENT_LOG_MAX_BYTES:-10485760}" # 10 MB
XTMUX_EVENT_LOG_KEEP="${XTMUX_EVENT_LOG_KEEP:-3}"

rotate_event_log_if_needed() {
  local file="${1:-}" size i src dst
  [ -n "$file" ] && [ -f "$file" ] || return 0
  size="$(stat -c '%s' -- "$file" 2>/dev/null || stat -f '%z' -- "$file" 2>/dev/null || printf '0')"
  [ "$size" -ge "$XTMUX_EVENT_LOG_MAX_BYTES" ] || return 0
  # shift .N-1 -> .N (drop oldest), then file -> .1
  for ((i=XTMUX_EVENT_LOG_KEEP; i>=1; i--)); do
    src="${file}.$((i-1))"; dst="${file}.$i"
    [ "$i" = 1 ] && src="$file"
    if [ "$i" = "$XTMUX_EVENT_LOG_KEEP" ] && [ -f "$dst" ]; then
      rm -f -- "$dst" 2>/dev/null || true
    fi
    [ -f "$src" ] && mv -f -- "$src" "$dst" 2>/dev/null || true
  done
  : > "$file" 2>/dev/null || true
}

# V2 backend mode: unset defaults to on (cutover, xtmux-3xs.31); 0 opts out;
# shadow -> mirror writes to observability.db for divergence comparison while
# V1 stays authoritative; 1 -> V2 authoritative (same as unset default now).
# Domain phases (3-8, epic xtmux-3xs) wire the actual delegation; this function
# only surfaces the mode so shell callers can branch without re-parsing the env.
obs_v2_mode() {
  case "${XTMUX_OBS_V2:-}" in
    '0')       REPLY='off' ;;
    shadow)    REPLY='shadow' ;;
    '' | '1')  REPLY='on' ;;
    *)         REPLY='off' ;;
  esac
}

# Delegate a durable operation to the Bun runtime (epic xtmux-3xs).
#
# Two callers, two needs:
#   obs_call  — best-effort. Used on the shadow path and for additive writes.
#               A V2 failure must never change V1's stdout or exit status, so
#               everything is swallowed. Returns 1 if the call did not run.
#   obs_call_strict — stdout/exit pass through. Used when V2 is authoritative
#               (XTMUX_OBS_V2=1), where a silent failure would mean silently
#               losing the operation.
# obs_runtime_argv — populate the global OBS_ARGV array with the invocation
# prefix for the V2 backend: compiled binary if present (fastest), else
# `bun run src/cli.ts`. Callers do "${OBS_ARGV[@]}" <subcommand> [args...].
obs_runtime_argv() {
  local root binary
  root="${self%/bin/*}"
  binary="$root/bin/xtmux-obs"
  if [ -x "$binary" ]; then
    # cd-then-exec wrapper: Bun (compiled or not) refuses to start from a
    # deleted directory (xt end worktree teardown), and exec preserves the PID
    # so monitor ownership/liveness (owner_pid) and signal delivery stay intact.
    OBS_ARGV=("bash" "-c" 'cd "$1" || exit 1; shift; exec "$@"' "xtmux-obs" "$root" "$binary")
  elif command -v bun >/dev/null 2>&1; then
    OBS_ARGV=("bash" "-c" 'cd "$1" || exit 1; shift; exec "$@"' "xtmux-obs" "$root" "bun" "run" "$root/src/cli.ts")
  else
    # An npm install ships neither: bin/xtmux-obs is not in package.json `files:`
    # (a compiled 100MB binary per platform is not a tarball), and bun is not a
    # system dependency of a node user. scripts/xtmux-obs.mjs is the launcher for
    # exactly that case — it resolves the VENDORED bun from the npm dependency
    # and restores a valid cwd before spawning it. Without this rung the entire
    # agent-JSON surface is unavailable on the one install path most users take.
    OBS_ARGV=("node" "$root/scripts/xtmux-obs.mjs")
  fi
}
# Bound each obs subprocess call from safe_send_pointer by wall-clock time so a
# stuck coordination-DB call cannot silently hang the picker forever
# (xtrm-wiy5n.4.17). The DB layer already sets busy_timeout (default 3s, see
# src/db/connection.ts), but the shell caller previously wrapped every obs call
# with `2>/dev/null || true`: any hang past busy_timeout — a stuck bun subprocess,
# a WAL recovery stall, a fuse-backed disk syscall — became an invisible pane
# freeze. This wrapper caps the call at $XTMUX_OBS_CALL_TIMEOUT_SEC (default 5s)
# and, on timeout, emits a diagnostic that names the DB path AND the fuser-
# reported holder pids so operators can find the process to kill instead of
# guessing. It returns 124 on timeout so the caller can propagate (--reply-to
# fulfilment) or swallow (best-effort delivery-record / handoff attempt).
#
# Notes on the timeout invocation (reported by Codex on PR #84):
# - `-k` sends SIGKILL $XTMUX_OBS_CALL_KILL_AFTER_SEC (default 2) after SIGTERM
#   so a subprocess that traps or ignores SIGTERM (the actual case the task's
#   evidence caught: "survived SIGTERM, needed SIGKILL") is still bounded.
# - `command -v timeout` gates the wrap: on systems without GNU coreutils
#   (macOS default), fall through to a raw call so best-effort delivery-record
#   and --reply-to fulfilment don't return 127. A one-shot warning to stderr
#   surfaces the degradation instead of silently dropping the protection.
# - The DB fallback path mirrors the runtime's own resolution:
#   ${XTMUX_OBS_DB_PATH:-${XDG_STATE_HOME:-$HOME/.local/state}/xtmux/observability.db}
#   so a customized XDG_STATE_HOME still names the right DB in the diagnostic.
_XTMUX_OBS_TIMEOUT_WARNED=0
safe_pointer_obs_call() {
  local state_home="${XDG_STATE_HOME:-$HOME/.local/state}"
  local db="${XTMUX_OBS_DB_PATH:-$state_home/xtmux/observability.db}"
  local subcmd="${1:-<none>}"
  local cap="${XTMUX_OBS_CALL_TIMEOUT_SEC:-5}"
  local kill_after="${XTMUX_OBS_CALL_KILL_AFTER_SEC:-2}"
  local rc holders
  # _XTMUX_OBS_CALL_TIMEOUT_UNAVAILABLE=1 is a test-only escape hatch that
  # simulates the macOS-without-coreutils path from a Linux CI runner. Not for
  # operator use — production degradation must come from a real `timeout`
  # absence so operators see the fallback warning.
  if [ "${_XTMUX_OBS_CALL_TIMEOUT_UNAVAILABLE:-}" != 1 ] && command -v timeout >/dev/null 2>&1; then
    timeout -k "$kill_after" "$cap" "${OBS_ARGV[@]}" "$@"
    rc=$?
  else
    if [ "$_XTMUX_OBS_TIMEOUT_WARNED" != 1 ]; then
      printf 'safe-send-pointer: warning: `timeout` not on PATH; obs subprocess is unbounded — install GNU coreutils (macOS: `brew install coreutils` for gtimeout, then symlink) to restore the wall-clock cap.\n' >&2
      _XTMUX_OBS_TIMEOUT_WARNED=1
    fi
    "${OBS_ARGV[@]}" "$@"
    rc=$?
  fi
  if [ "$rc" = 124 ] || [ "$rc" = 137 ]; then
    holders="$(fuser "$db" 2>/dev/null | tr -s ' ' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//' || true)"
    printf 'safe-send-pointer: obs subprocess "%s" hit %ss wall-clock cap (XTMUX_OBS_CALL_TIMEOUT_SEC, kill-after %ss); likely lock contention on coordination DB %s; holders (pids from fuser): %s\n' \
      "$subcmd" "$cap" "$kill_after" "$db" "${holders:-<none>}" >&2
  fi
  return "$rc"
}

obs_available() {
  local root binary
  root="${self%/bin/*}"
  binary="$root/bin/xtmux-obs"
  # Binary path: standalone. Otherwise we need cli.ts plus something to run it:
  # system bun, or node + the vendored-bun launcher.
  [ -x "$binary" ] && return 0
  [ -f "$root/src/cli.ts" ] || return 1
  command -v bun >/dev/null 2>&1 && return 0
  [ -f "$root/scripts/xtmux-obs.mjs" ] && command -v node >/dev/null 2>&1
}

json_error() {
  local code="$1" message="$2" command="$3"
  printf '{"code":"%s","message":"%s","detail":{"command":"%s"}}\n' \
    "$(json_escape "$code")" "$(json_escape "$message")" "$(json_escape "$command")" >&2
}

command_error() {
  local json="$1" code="$2" message="$3" command="$4" exit_code="$5"
  if [ "$json" = 1 ]; then json_error "$code" "$message" "$command"; else printf '%s\n' "$message" >&2; fi
  return "$exit_code"
}

json_requested() {
  local arg
  for arg in "$@"; do [ "$arg" = '--json' ] && return 0; done
  return 1
}

json_command_state() {
  local command="$1" subcommand="${2:-}"
  case "$command:$subcommand" in
    message-list:*|message-status:*|message-get:*|unread-count:*|obligations:list|wait-agent:*|monitor-agent:*|monitor-list:*|monitor-kill:*|monitors:*|safe-send-pointer:*|handoff:*|message-send:*|message-reply:*|message-cancel:*|message-ack:*|worktree-collisions:*|dashboard:*|topology:*|audit:*|log:tail|log:query|log:follow|context:--current|pane:capture|bridge:--stdio|agent-last:*|agent-episode:*|instance-get:*) REPLY='ready' ;;
    # Everything else, including the interactive-only nav family and picker
    # internals, is refused with XTMUX_JSON_UNSUPPORTED by
    # json_request_preflight — never classified as JSON-ready.
    *) REPLY='unsupported' ;;
  esac
}

json_request_preflight() {
  local command="$1" subcommand="${2:-}"
  json_command_state "$command" "$subcommand"
  case "$REPLY" in
    unsupported)
      json_error XTMUX_JSON_UNSUPPORTED "$command does not support --json" "$command"
      return 2
      ;;
    planned)
      json_error XTMUX_JSON_NOT_READY "$command --json is classified but not implemented" "$command"
      return 2
      ;;
  esac
  # Read-only identity/topology/content commands are exempt from the V2-mode gate.
  # XTMUX_OBS_V2 selects the observability STORE (SQLite vs legacy JSONL);
  # these commands read only live tmux and the host-id file. Gating them on
  # that flag would make a valid graph depend on an unrelated event store.
  case "$command" in
    context|topology|pane) : ;;
    *)
      obs_v2_mode; local mode="$REPLY"
      if [ "$mode" != 'on' ]; then
        json_error XTMUX_JSON_REQUIRES_V2 "$command --json requires the V2 runtime" "$command"
        return 2
      fi
      ;;
  esac
  if [ "$command" != topology ] && ! obs_available; then
    json_error XTMUX_JSON_BACKEND_UNAVAILABLE "$command --json backend is unavailable" "$command"
    return 1
  fi
}

obs_call() {
  obs_available || return 1
  obs_runtime_argv
  "${OBS_ARGV[@]}" "$@" >/dev/null 2>&1 || true
}
obs_call_strict() {
  obs_runtime_argv
  "${OBS_ARGV[@]}" "$@"
}

# obs_shadow_diff <domain> <command> <diff_kind> <v1_output> <v2_output>
# Byte-compare V1 vs V2. On mismatch, best-effort record via `obs_call
# shadow-record` with snippets truncated to 512 chars each. Silent — cannot
# fail the wrapped V1 command. Skipped entirely when V2 runtime unavailable.
obs_shadow_diff() {
  local domain="$1" command="$2" kind="$3" v1="$4" v2="$5"
  [ "$v1" = "$v2" ] && return 0
  obs_available || return 0
  local v1s="${v1:0:512}" v2s="${v2:0:512}"
  obs_call shadow-record \
    --domain "$domain" \
    --command "$command" \
    --diff-kind "$kind" \
    --v1-snippet "$v1s" \
    --v2-snippet "$v2s"
}

log_event() {
  local type="${1:-}" file dir ts epoch first=1 kv key val
  [ -n "$type" ] || return 0
  event_log_file; file="$REPLY"; dir="${file%/*}"
  mkdir -p "$dir" 2>/dev/null || true
  rotate_event_log_if_needed "$file"
  ts="$(date -Is 2>/dev/null || date '+%Y-%m-%dT%H:%M:%S%z')"
  epoch="$(date +%s 2>/dev/null || printf '0')"
  {
    printf '{"ts":"%s","ts_epoch":%s,"type":"%s"' "$(json_escape "$ts")" "$epoch" "$(json_escape "$type")"
    for kv in "$@"; do
      [ "$first" = 1 ] && { first=0; continue; }
      key="${kv%%=*}"; val="${kv#*=}"
      [ -n "$key" ] || continue
      case "$key" in *[!A-Za-z0-9_.-]* ) key="field" ;; esac
      printf ',"%s":"%s"' "$key" "$(json_escape "$val")"
    done
    printf '}\n'
  } >> "$file" 2>/dev/null || true
}

log_cli_emit() {
  local type="${1:-}"; shift || true
  [ -n "$type" ] || { printf 'usage: log emit <type> [key=value...]\n' >&2; return 2; }
  obs_v2_mode; local _mode="$REPLY"
  if [ "$_mode" = 'on' ]; then
    obs_runtime_argv
    exec "${OBS_ARGV[@]}" log-emit "$type" "$@"
  fi
  log_event "$type" "$@"
  # Shadow-tee: also insert into V2 event_journal for parity. log_event above
  # clobbers $REPLY (via event_log_file), so we snapshot mode up-front.
  if [ "$_mode" = 'shadow' ] && obs_available; then
    obs_call log-emit "$type" "$@"
  fi
}

log_cli_tail() {
  local n=50 json=0 arg file
  for arg in "$@"; do
    case "$arg" in --json) json=1 ;; *[!0-9]*) return 2 ;; *) n="$arg" ;; esac
  done
  obs_v2_mode
  if [ "$REPLY" = 'on' ]; then
    obs_runtime_argv
    local args=(log-tail "$n")
    [ "$json" = 1 ] && args+=(--json)
    exec "${OBS_ARGV[@]}" "${args[@]}"
  fi
  event_log_file; file="$REPLY"
  [ -f "$file" ] || return 0
  tail -n "$n" "$file"
}

_log_json_field_match() {
  local field="$1" value="$2"
  printf '"%s":"%s"' "$field" "$(json_escape "$value")"
}

# _log_cli_query_v1_body — V1 JSONL scan for log-query; extracted so the
# shadow-tee path can capture stdout before diffing. Args:
# <type> <pane> <session> <bead> <since_secs> <limit>.
_log_cli_query_v1_body() {
  local type="$1" pane="$2" session="$3" bead="$4" since="$5" limit="$6"
  local file now since_epoch
  event_log_file; file="$REPLY"
  [ -f "$file" ] || return 0
  now="$(date +%s)"; since_epoch=0
  [ -n "$since" ] && since_epoch=$(( now - since ))
  awk -v since="$since_epoch" 'since<=0 {print; next} { if (match($0, /"ts_epoch":[0-9]+/)) { v=substr($0, RSTART+11, RLENGTH-11); if (v >= since) print } }' "$file" |
    { [ -n "$type" ] && grep -F -- "$(_log_json_field_match type "$type")" || cat; } |
    { [ -n "$pane" ] && grep -F -- "$(_log_json_field_match pane "$pane")" || cat; } |
    { [ -n "$session" ] && grep -F -- "$(_log_json_field_match session "$session")" || cat; } |
    { [ -n "$bead" ] && grep -F -- "$(_log_json_field_match bead "$bead")" || cat; } |
    tail -n "$limit"
}

log_cli_query() {
  local type='' pane='' session='' bead='' since='' limit=100 json=0 after_id='' arg
  while [ "$#" -gt 0 ]; do
    arg="$1"; shift
    case "$arg" in
      # The cursor. Only meaningful under V2 (it IS the committed SQLite rowid),
      # so V1 refuses it rather than ignoring it — silently dropping a cursor
      # would hand the caller a full unpaged dump it would mistake for its page.
      --after-id) [ "$#" -gt 0 ] || return 2; after_id="$1"; shift ;;
      --after-id=*) after_id="${arg#--after-id=}" ;;
      --type) [ "$#" -gt 0 ] || return 2; type="$1"; shift ;;
      --type=*) type="${arg#--type=}" ;;
      --pane) [ "$#" -gt 0 ] || return 2; pane="$1"; shift ;;
      --pane=*) pane="${arg#--pane=}" ;;
      --session|--for) [ "$#" -gt 0 ] || return 2; session="$1"; shift ;;
      --session=*|--for=*) session="${arg#*=}" ;;
      --bead) [ "$#" -gt 0 ] || return 2; bead="$1"; shift ;;
      --bead=*) bead="${arg#--bead=}" ;;
      --since) [ "$#" -gt 0 ] || return 2; parse_wait_duration "$1" || return 2; since="$REPLY"; shift ;;
      --since=*) parse_wait_duration "${arg#--since=}" || return 2; since="$REPLY" ;;
      --limit) [ "$#" -gt 0 ] || return 2; limit="$1"; shift ;;
      --limit=*) limit="${arg#--limit=}" ;;
      --json) json=1 ;;
      *) command_error "$json" XTMUX_INVALID_ARGUMENT "log query: unknown arg: $arg" log 2; return $? ;;
    esac
  done
  obs_v2_mode; local mode="$REPLY"
  if [ -n "$after_id" ] && [ "$mode" != 'on' ]; then
    command_error "$json" XTMUX_JSON_REQUIRES_V2 "log query --after-id requires the V2 runtime: the cursor is the committed SQLite journal id, which the legacy JSONL store does not have" log 2
    return $?
  fi
  if [ "$mode" = 'on' ]; then
    obs_runtime_argv
    local cli_args=(log-query --limit "$limit")
    [ -n "$after_id" ] && cli_args+=(--after-id "$after_id")
    [ "$json" = 1 ]   && cli_args+=(--json)
    [ -n "$type" ]    && cli_args+=(--type    "$type")
    [ -n "$session" ] && cli_args+=(--session "$session")
    [ -n "$pane" ]    && cli_args+=(--pane    "$pane")
    [ -n "$bead" ]    && cli_args+=(--bead    "$bead")
    [ -n "$since" ]   && cli_args+=(--since   "$(( ( $(date +%s) - since ) * 1000 ))")
    exec "${OBS_ARGV[@]}" "${cli_args[@]}"
  fi
  if [ "$mode" = 'shadow' ]; then
    local v1_out v2_out=''
    v1_out="$(_log_cli_query_v1_body "$type" "$pane" "$session" "$bead" "$since" "$limit")"
    if obs_available; then
      obs_runtime_argv
      local v2_args=(log-query --limit "$limit")
      [ -n "$type" ]    && v2_args+=(--type    "$type")
      [ -n "$session" ] && v2_args+=(--session "$session")
      [ -n "$pane" ]    && v2_args+=(--pane    "$pane")
      [ -n "$bead" ]    && v2_args+=(--bead    "$bead")
      [ -n "$since" ]   && v2_args+=(--since   "$(( ( $(date +%s) - since ) * 1000 ))")
      v2_out="$("${OBS_ARGV[@]}" "${v2_args[@]}" 2>/dev/null || true)"
    fi
    obs_shadow_diff log log-query content "$v1_out" "$v2_out"
    [ -n "$v1_out" ] && printf '%s\n' "$v1_out"
    return 0
  fi
  _log_cli_query_v1_body "$type" "$pane" "$session" "$bead" "$since" "$limit"
}

log_cli() {
  local sub="${1:-}"; shift || true
  case "$sub" in
    emit) log_cli_emit "$@" ;;
    tail) log_cli_tail "$@" ;;
    query) log_cli_query "$@" ;;
    follow) log_cli_follow "$@" ;;
    *) printf 'usage: log <emit|tail|query|follow> ...\n' >&2; return 2 ;;
  esac
}

# log follow --after-id N — the committed-event stream (gaps doc 6.4).
#
# V2-only, for the same reason as the cursor: the id being followed IS the
# committed SQLite rowid. exec into the runtime rather than capturing it — this is
# an unbounded stream, and a command substitution would buffer it forever and
# swallow the SIGINT/SIGTERM that is the normal way a follower ends.
log_cli_follow() {
  local json=0 arg
  for arg in "$@"; do [ "$arg" = '--json' ] && json=1; done
  obs_v2_mode
  if [ "$REPLY" != 'on' ]; then
    command_error "$json" XTMUX_JSON_REQUIRES_V2 "log follow requires the V2 runtime: the stream cursor is the committed SQLite journal id, which the legacy JSONL store does not have" log 2
    return $?
  fi
  if ! obs_available; then
    command_error "$json" XTMUX_JSON_BACKEND_UNAVAILABLE "log follow backend is unavailable" log 1
    return $?
  fi
  obs_runtime_argv
  exec "${OBS_ARGV[@]}" log-follow "$@"
}

# bridge --stdio — the read-only NDJSON surface a remote viewer reaches through
# `ssh <host> xtmux bridge --stdio` (xtmux-j46.9). exec, never capture: this is an
# unbounded bidirectional stream, and a command substitution would both buffer it
# forever and swallow the signals that are supposed to end it.
#
# XTMUX_PICKER is how the runtime calls BACK into this script for topology, which
# is implemented here in bash. Relaying the existing command is the whole point —
# a second implementation of xtrm.xtmux.topology.v1 inside the runtime would be a
# second thing to keep in sync, and drift between them is invisible to both.
bridge_cli() {
  local json=0 arg
  for arg in "$@"; do [ "$arg" = '--json' ] && json=1; done
  obs_v2_mode
  if [ "$REPLY" != 'on' ]; then
    command_error "$json" XTMUX_JSON_REQUIRES_V2 "bridge requires the V2 runtime: it serves the SQLite journal cursor, which the legacy JSONL store does not have" bridge 2
    return $?
  fi
  if ! obs_available; then
    command_error "$json" XTMUX_JSON_BACKEND_UNAVAILABLE "bridge backend is unavailable" bridge 1
    return $?
  fi
  obs_runtime_argv
  XTMUX_PICKER="$self" exec "${OBS_ARGV[@]}" bridge "$@"
}

# context --current [--json] — the runtime-origin DTO Specialists reads on every
# `sp run` to record which pane/agent spawned a job (xtrm.runtime-origin.v1).
# Strict, never best-effort: a swallowed failure here would let the caller bind a
# job to a pane we never actually verified.
context_cli() {
  if ! obs_available; then
    json_error XTMUX_RUNTIME_UNAVAILABLE "xtmux context requires the V2 runtime (bin/xtmux-obs or bun + src/cli.ts)" "context"
    return 1
  fi
  obs_call_strict context "$@"
}

# pane capture --pane %N [--lines N] [--json] — bounded, read-only terminal
# preview for a Console viewer. Kept out of `topology` on purpose: topology is
# identity and must stay cheap enough to poll; pane content is unbounded and is
# fetched on demand, one pane at a time.
pane_cli() {
  local sub="${1:-}"; shift || true
  case "$sub" in
    capture)
      if ! obs_available; then
        json_error XTMUX_RUNTIME_UNAVAILABLE "xtmux pane capture requires the V2 runtime (bin/xtmux-obs or bun + src/cli.ts)" "pane"
        return 1
      fi
      obs_call_strict pane capture "$@"
      ;;
    *) printf 'usage: pane capture --pane <%%id> [--lines N] [--json]\n' >&2; return 2 ;;
  esac
}

message_send() {
  local to='' from='' bead='' text='' id='' expects_reply='' reply_to='' to_pane='' from_pane='' json=0 arg
  while [ "$#" -gt 0 ]; do
    arg="$1"; shift
    case "$arg" in
      --to) [ "$#" -gt 0 ] || return 2; to="$1"; shift ;;
      --to=*) to="${arg#--to=}" ;;
      --from) [ "$#" -gt 0 ] || return 2; from="$1"; shift ;;
      --from=*) from="${arg#--from=}" ;;
      --to-pane) [ "$#" -gt 0 ] || return 2; to_pane="$1"; shift ;;
      --to-pane=*) to_pane="${arg#--to-pane=}" ;;
      --from-pane) [ "$#" -gt 0 ] || return 2; from_pane="$1"; shift ;;
      --from-pane=*) from_pane="${arg#--from-pane=}" ;;
      --reply-to) [ "$#" -gt 0 ] || return 2; reply_to="$1"; shift ;;
      --reply-to=*) reply_to="${arg#--reply-to=}" ;;
      --bead) [ "$#" -gt 0 ] || return 2; bead="$1"; shift ;;
      --bead=*) bead="${arg#--bead=}" ;;
      --text) [ "$#" -gt 0 ] || return 2; text="$1"; shift ;;
      --text=*) text="${arg#--text=}" ;;
      --id) [ "$#" -gt 0 ] || return 2; id="$1"; shift ;;
      --id=*) id="${arg#--id=}" ;;
      --expects-reply)
        case "${1:-}" in
          true|false|1|0) expects_reply="$1"; shift ;;
          *) expects_reply=true ;;
        esac
        ;;
      --expects-reply=*) expects_reply="${arg#--expects-reply=}" ;;
      --json) json=1 ;;
      *) text+="${text:+ }$arg" ;;
    esac
  done
  [ -n "$to" ] && [ -n "$text" ] || { command_error "$json" XTMUX_INVALID_ARGUMENT 'usage: message-send --to <session|pane> [--from x] [--bead id] [--reply-to key] [--expects-reply[=true|false]] --text <text>' message-send 2; return $?; }
  case "$expects_reply" in ''|true|false|1|0) ;; *) command_error "$json" XTMUX_INVALID_ARGUMENT 'message-send: --expects-reply must be true or false' message-send 2; return $? ;; esac
  # Canonicalize target to session_id so message-list --for finds it regardless
  # of which alias (name/pane_id/session_id/shorthand) the recipient uses. For
  # $N/%N ids we require resolution (those are meaningful only as live tmux
  # objects; a stale $99999 is a routing bug). For plain names we fall through
  # to the raw target so offline unit tests and legacy callers keep working.
  local to_sid=''
  if resolve_to_session_id "$to"; then
    to_sid="$REPLY"
  else
    case "$to" in
      '$'*|'%'*|'@'*)
        command_error "$json" XTMUX_TARGET_NOT_FOUND "message-send: target does not exist: $to" message-send 1
        log_event message.failed to="$to" reason=target_missing
        return 1
        ;;
      *)
        to_sid="$to"
        ;;
    esac
  fi
  # Normalize sender to session_id too. Fall back to raw --from if unresolvable
  # (e.g. tests outside tmux), then to current session_id.
  local from_sid=''
  if [ -n "$from" ]; then
    resolve_to_session_id "$from" && from_sid="$REPLY" || from_sid="$from"
  else
    current_tmux_session_id; from_sid="$REPLY"
  fi
  [ -n "$from_sid" ] || from_sid='unknown'
  [ -n "$id" ] || id="msg-$(date +%s)-$$"
  # V2 authoritative delegation: skip legacy events.jsonl + unread projection
  # writes, delegate to the Bun runtime which owns messages/receipts/deliveries
  # and reconciliation. Best-effort tmux display-message note still fires so
  # the UI signal is unchanged.
  obs_v2_mode; local _mode="$REPLY"
  if [ "$_mode" = 'on' ]; then
    # pane-hint extraction — reproduce Phase 3's same-session ambiguity fix.
    # Uses target_pane_id (not a raw tmux #{pane_id} lookup): tmux misparses
    # the `session:%N` shorthand and returns the session's active pane, which
    # silently dropped the pane suffix on delivery.
    local to_pid='' from_pid=''
    target_pane_id "$to" && to_pid="$REPLY"
    [ -n "$from" ] && target_pane_id "$from" && from_pid="$REPLY"
    obs_runtime_argv
    local cli_args=(message-send --to "$to_sid" --from "$from_sid" --id "$id" --text "$text")
    [ "$json" = 1 ]         && cli_args+=(--json)
    [ -n "$bead" ]          && cli_args+=(--bead "$bead")
    [ -n "$expects_reply" ] && cli_args+=(--expects-reply "$expects_reply")
    [ -n "$reply_to" ]      && cli_args+=(--reply-to "$reply_to")
    [ -n "$to_pane" ]       && cli_args+=(--to-pane "$to_pane")
    [ -n "$from_pane" ]     && cli_args+=(--from-pane "$from_pane")
    [ -n "$to_pid" ]         && cli_args+=(--to-pane "$to_pid")
    [ -z "$reply_to" ] && [ -n "$from_pid" ] && cli_args+=(--from-pane "$from_pid")
    "${OBS_ARGV[@]}" "${cli_args[@]}" || return $?
    tmux display-message -t "$to_sid" "msg from ${from_sid}${bead:+ [$bead]}: ${text:0:80}" 2>/dev/null || true
    return 0
  fi
  log_event message.sent id="$id" from="$from_sid" to="$to_sid" bead="$bead" text="$text"
  # Shadow-tee: under XTMUX_OBS_V2=shadow, mirror the write into SQLite so
  # subsequent shadow-mode reads can meaningfully diff V1 vs V2 state. V1
  # remains authoritative; V2 failure is silent. log_event above clobbers
  # $REPLY (event_log_file), so we snapshot mode up-front.
  if [ "$_mode" = 'shadow' ] && obs_available; then
    local to_pid_s='' from_pid_s=''
    target_pane_id "$to" && to_pid_s="$REPLY"
    [ -n "$from" ] && target_pane_id "$from" && from_pid_s="$REPLY"
    local shadow_args=(message-send --to "$to_sid" --from "$from_sid" --id "$id" --text "$text")
    [ -n "$bead" ]          && shadow_args+=(--bead "$bead")
    [ -n "$expects_reply" ] && shadow_args+=(--expects-reply "$expects_reply")
    [ -n "$reply_to" ]      && shadow_args+=(--reply-to "$reply_to")
    [ -n "$to_pid_s" ]      && shadow_args+=(--to-pane "$to_pid_s")
    [ -z "$reply_to" ] && [ -n "$from_pid_s" ] && shadow_args+=(--from-pane "$from_pid_s")
    obs_call "${shadow_args[@]}"
  fi
  # Delivery signal — best-effort. Bumps a session-scoped counter recipients
  # can watch (@agent_unread_count) and stamps @agent_unread_since; also emits
  # a status-line notice for any attached client. Failures are silent because
  # the message is already durably logged.
  local prev now_epoch
  prev="$(tmux show-options -t "$to_sid" -qv @agent_unread_count 2>/dev/null || printf '0')"
  case "$prev" in ''|*[!0-9]*) prev=0 ;; esac
  now_epoch="$(date +%s 2>/dev/null || printf '0')"
  tmux set-option -t "$to_sid" -q @agent_unread_count "$(( prev + 1 ))" 2>/dev/null || true
  tmux set-option -t "$to_sid" -q @agent_unread_since "$now_epoch" 2>/dev/null || true
  tmux display-message -t "$to_sid" "msg from ${from_sid}${bead:+ [$bead]}: ${text:0:80}" 2>/dev/null || true
  printf 'message\t%s\t%s\t%s\t%s\t%s\n' "$id" "$from_sid" "$to_sid" "$bead" "$text"
}

message_reply() {
  local key='' text='' message_key='' json=0 arg
  while [ "$#" -gt 0 ]; do
    arg="$1"; shift
    case "$arg" in
      --in-reply-to) [ "$#" -gt 0 ] || return 2; key="$1"; shift ;;
      --in-reply-to=*) key="${arg#--in-reply-to=}" ;;
      --text) [ "$#" -gt 0 ] || return 2; text="$1"; shift ;;
      --text=*) text="${arg#--text=}" ;;
      --message-key) [ "$#" -gt 0 ] || return 2; message_key="$1"; shift ;;
      --message-key=*) message_key="${arg#--message-key=}" ;;
      --json) json=1 ;;
      *) printf 'message-reply: unknown arg: %s\n' "$arg" >&2; return 2 ;;
    esac
  done
  [ -n "$key" ] && [ -n "$text" ] || { command_error "$json" XTMUX_INVALID_ARGUMENT 'usage: message-reply --in-reply-to <messageKey> --text <text> [--message-key K]' message-reply 2; return $?; }
  obs_v2_mode; [ "$REPLY" = on ] || { command_error "$json" XTMUX_JSON_REQUIRES_V2 'message-reply requires XTMUX_OBS_V2=1' message-reply 2; return $?; }
  obs_runtime_argv
  local args=(message-reply --in-reply-to "$key" --text "$text")
  [ -n "$message_key" ] && args+=(--message-key "$message_key")
  [ "$json" = 1 ] && args+=(--json)
  exec "${OBS_ARGV[@]}" "${args[@]}"
}

message_cancel() {
  local key='' json=0 arg
  while [ "$#" -gt 0 ]; do
    arg="$1"; shift
    case "$arg" in
      --message-key) [ "$#" -gt 0 ] || return 2; key="$1"; shift ;;
      --message-key=*) key="${arg#--message-key=}" ;;
      --json) json=1 ;;
      *) printf 'message-cancel: unknown arg: %s\n' "$arg" >&2; return 2 ;;
    esac
  done
  [ -n "$key" ] || { command_error "$json" XTMUX_INVALID_ARGUMENT 'usage: message-cancel --message-key <messageKey>' message-cancel 2; return $?; }
  obs_v2_mode; [ "$REPLY" = on ] || { command_error "$json" XTMUX_JSON_REQUIRES_V2 'message-cancel requires XTMUX_OBS_V2=1' message-cancel 2; return $?; }
  obs_runtime_argv
  local args=(message-cancel --message-key "$key")
  [ "$json" = 1 ] && args+=(--json)
  exec "${OBS_ARGV[@]}" "${args[@]}"
}

message_ack() {
  local id="${1:-}" by='' json=0
  shift || true
  while [ "$#" -gt 0 ]; do
    case "$1" in --by) shift; by="${1:-}" ;; --by=*) by="${1#--by=}" ;; --json) json=1 ;; esac
    shift || true
  done
  [ -n "$id" ] || { command_error "$json" XTMUX_INVALID_ARGUMENT 'usage: message-ack <message-id> [--by session]' message-ack 2; return $?; }
  if [ -n "$by" ]; then
    resolve_to_session_id "$by" && by="$REPLY"
  else
    current_tmux_session_id; by="$REPLY"
  fi
  [ -n "$by" ] || by='unknown'
  obs_v2_mode; local _mode="$REPLY"
  if [ "$_mode" = 'on' ]; then
    obs_runtime_argv
    local ack_args=(message-ack "$id" --by "$by")
    [ "$json" = 1 ] && ack_args+=(--json)
    "${OBS_ARGV[@]}" "${ack_args[@]}" || return $?
    if [ "$by" != unknown ]; then
      local prev
      prev="$(tmux show-options -t "$by" -qv @agent_unread_count 2>/dev/null || printf '0')"
      case "$prev" in ''|*[!0-9]*) prev=0 ;; esac
      if [ "$prev" -gt 0 ]; then
        local next=$(( prev - 1 ))
        tmux set-option -t "$by" -q @agent_unread_count "$next" 2>/dev/null || true
        [ "$next" -eq 0 ] && tmux set-option -u -t "$by" -q @agent_unread_since 2>/dev/null || true
      fi
    fi
    return 0
  fi
  log_event message.ack id="$id" by="$by"
  # Shadow-tee: mirror ack into SQLite for parity. Best-effort; V1 keeps authority.
  # log_event clobbers $REPLY (event_log_file) so we snapshot mode up-front.
  if [ "$_mode" = 'shadow' ] && obs_available; then
    obs_call message-ack "$id" --by "$by"
  fi
  # Decrement recipient's unread counter. If it hits zero, clear the stamp too.
  # Best-effort: acking outside a tmux session (tests) just no-ops.
  if [ -n "${by:-}" ] && [ "$by" != unknown ]; then
    local prev
    prev="$(tmux show-options -t "$by" -qv @agent_unread_count 2>/dev/null || printf '0')"
    case "$prev" in ''|*[!0-9]*) prev=0 ;; esac
    if [ "$prev" -gt 0 ]; then
      local next=$(( prev - 1 ))
      tmux set-option -t "$by" -q @agent_unread_count "$next" 2>/dev/null || true
      [ "$next" = 0 ] && tmux set-option -t "$by" -qu @agent_unread_since 2>/dev/null || true
    fi
  fi
  printf 'ack\t%s\t%s\n' "$id" "$by"
}

message_status() {
  local key="${1:-}" json=0
  [ -n "$key" ] || { printf 'usage: message-status <message_key> [--json]\n' >&2; return 2; }
  shift || true
  [ "${1:-}" = '--json' ] && json=1
  obs_v2_mode
  [ "$REPLY" = on ] || { printf 'message-status: requires XTMUX_OBS_V2=1\n' >&2; return 2; }
  obs_runtime_argv
  local args=(message-status "$key")
  [ "$json" = 1 ] && args+=(--json)
  exec "${OBS_ARGV[@]}" "${args[@]}"
}

message_get() {
  local target="${1:-}" json=0
  [ -n "$target" ] || { printf 'usage: message-get <message_key|message_id> [--json]\n' >&2; return 2; }
  shift || true
  [ "${1:-}" = '--json' ] && json=1
  obs_v2_mode
  [ "$REPLY" = on ] || { printf 'message-get: requires XTMUX_OBS_V2=1\n' >&2; return 2; }
  obs_runtime_argv
  local args=(message-get "$target")
  [ "$json" = 1 ] && args+=(--json)
  exec "${OBS_ARGV[@]}" "${args[@]}"
}

instance_get() {
  # K4 (xtmux-s96.4). agent-state.sh calls this through the `xtmux` name on
  # PATH, which is THIS dispatcher — an unrouted subcommand would fall through
  # to the interactive picker and the pane-metadata rehydration would silently
  # no-op on every real install while passing every test that stubs `xtmux`.
  local target="${1:-}" json=0
  [ -n "$target" ] || { printf 'usage: instance-get <instance-id> [--json]\n' >&2; return 2; }
  shift || true
  [ "${1:-}" = '--json' ] && json=1
  obs_v2_mode
  [ "$REPLY" = on ] || { printf 'instance-get: requires XTMUX_OBS_V2=1\n' >&2; return 2; }
  obs_runtime_argv
  local args=(instance-get "$target")
  [ "$json" = 1 ] && args+=(--json)
  exec "${OBS_ARGV[@]}" "${args[@]}"
}

agent_last() {
  local target="${1:-}" json=0
  [ -n "$target" ] || { printf 'usage: agent-last <pane-id|session-id> [--json]\n' >&2; return 2; }
  shift || true
  [ "${1:-}" = '--json' ] && json=1
  obs_v2_mode
  [ "$REPLY" = on ] || { printf 'agent-last: requires XTMUX_OBS_V2=1\n' >&2; return 2; }
  obs_runtime_argv
  local args=(agent-last "$target")
  [ "$json" = 1 ] && args+=(--json)
  exec "${OBS_ARGV[@]}" "${args[@]}"
}

# xtmux-gdk: the viewer-facing episode projection — one user prompt plus all
# continuations until control returns to the operator. The latest agent_turns
# row is never the response; the episode is.
agent_episode() {
  local target="${1:-}" json=0
  [ -n "$target" ] || { printf 'usage: agent-episode <pane-id|session-id> [--json]\n' >&2; return 2; }
  shift || true
  [ "${1:-}" = '--json' ] && json=1
  obs_v2_mode
  [ "$REPLY" = on ] || { printf 'agent-episode: requires XTMUX_OBS_V2=1\n' >&2; return 2; }
  obs_runtime_argv
  local args=(agent-episode "$target")
  [ "$json" = 1 ] && args+=(--json)
  exec "${OBS_ARGV[@]}" "${args[@]}"
}

unread_count() {
  local recipient="" pane="" arg
  while [ "$#" -gt 0 ]; do
    arg="$1"; shift
    case "$arg" in
      --for) [ "$#" -gt 0 ] || return 2; recipient="$1"; shift ;;
      --for=*) recipient="${arg#--for=}" ;;
      --pane) [ "$#" -gt 0 ] || return 2; pane="$1"; shift ;;
      --pane=*) pane="${arg#--pane=}" ;;
      *) printf 'unread-count: unknown arg: %s\n' "$arg" >&2; return 2 ;;
    esac
  done
  # xtrm-wiy5n.4.24: --for is optional. The underlying CLI resolves the missing
  # value through liveTmuxRequester when running under tmux, so a Claude hook
  # can call `unread-count --pane $TMUX_PANE` without a prior session-id lookup.
  obs_v2_mode
  [ "$REPLY" = on ] || { printf 'unread-count: requires XTMUX_OBS_V2=1\n' >&2; return 2; }
  if [ -n "$recipient" ] && resolve_to_session_id "$recipient"; then recipient="$REPLY"; fi
  obs_runtime_argv
  local args=(unread-count)
  [ -n "$recipient" ] && args+=(--for "$recipient")
  [ -n "$pane" ] && args+=(--pane "$pane")
  exec "${OBS_ARGV[@]}" "${args[@]}"
}

message_json_field() {
  local name="$1" line="$2"
  printf '%s\n' "$line" | sed -n "s/.*\"$name\":\"\([^\"\\]*\)\".*/\1/p"
}

# _message_list_v1_body — V1 JSONL scan producing message-list stdout.
# Shared between the mode=off direct path and the mode=shadow capture-then-diff
# path (xtmux-3xs.12). Args: <for> <since_secs> <limit> <unacked_bool> <message_key>.
_message_list_v1_body() {
  local to="$1" since="$2" limit="$3" unacked="$4" message_key="${5:-}"
  local file files=() now since_epoch ack_tmp line ts_epoch id from target bead text ts to_sid=''
  event_log_file; file="$REPLY"
  if [ -n "$to" ]; then
    if resolve_to_session_id "$to"; then to_sid="$REPLY"; else to_sid=''; fi
  fi
  local i
  [ -f "$file" ] && files+=("$file")
  for ((i=1; i<=XTMUX_EVENT_LOG_KEEP; i++)); do
    [ -f "${file}.$i" ] && files+=("${file}.$i")
  done
  [ ${#files[@]} -gt 0 ] || return 0
  now="$(date +%s)"; since_epoch=0
  [ -n "$since" ] && since_epoch=$(( now - since ))
  ack_tmp="$(mktemp)"
  trap 'rm -f "${ack_tmp:-}"' RETURN EXIT INT TERM
  grep -hF '"type":"message.ack"' "${files[@]}" 2>/dev/null | sed -n 's/.*"id":"\([^"\\]*\)".*/\1/p' > "$ack_tmp" || true
  while IFS= read -r line; do
    case "$line" in *'"type":"message.sent"'*) ;; *) continue ;; esac
    ts_epoch="$(printf '%s\n' "$line" | sed -n 's/.*"ts_epoch":\([0-9][0-9]*\).*/\1/p')"
    if [ "$since_epoch" -gt 0 ]; then
      [ -n "$ts_epoch" ] && [ "$ts_epoch" -lt "$since_epoch" ] && continue
    fi
    id="$(message_json_field id "$line")"
    from="$(message_json_field from "$line")"
    target="$(message_json_field to "$line")"
    bead="$(message_json_field bead "$line")"
    text="$(message_json_field text "$line")"
    ts="$(message_json_field ts "$line")"
    if [ -n "$to" ] && [ "$target" != "$to" ] && { [ -z "$to_sid" ] || [ "$target" != "$to_sid" ]; }; then
      continue
    fi
    [ -z "$message_key" ] || [ "$id" = "$message_key" ] || continue
    if [ "$unacked" = 1 ] && grep -Fx -- "$id" "$ack_tmp" >/dev/null 2>&1; then continue; fi
    if [ "$unacked" = 1 ]; then
      format_age_short "${ts_epoch:-0}"
      printf 'message\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$id" "$ts" "$REPLY" "$from" "$target" "$bead" "$text"
    else
      printf 'message\t%s\t%s\t%s\t%s\t%s\t%s\n' "$id" "$ts" "$from" "$target" "$bead" "$text"
    fi
  done < <(grep -hF '"type":"message.sent"' "${files[@]}" 2>/dev/null) | tail -n "$limit"
}

message_list() {
  local to='' pane='' from='' since='' message_key='' limit=100 unacked=0 expects_reply=0 json=0 arg
  while [ "$#" -gt 0 ]; do
    arg="$1"; shift
    case "$arg" in
      --for|--to) [ "$#" -gt 0 ] || return 2; to="$1"; shift ;;
      --for=*|--to=*) to="${arg#*=}" ;;
      --from) [ "$#" -gt 0 ] || return 2; from="$1"; shift ;;
      --from=*) from="${arg#--from=}" ;;
      --message-key) [ "$#" -gt 0 ] || return 2; message_key="$1"; shift ;;
      --message-key=*) message_key="${arg#--message-key=}" ;;
      --since) [ "$#" -gt 0 ] || return 2; parse_wait_duration "$1" || return 2; since="$REPLY"; shift ;;
      --since=*) parse_wait_duration "${arg#--since=}" || return 2; since="$REPLY" ;;
      --limit) [ "$#" -gt 0 ] || return 2; limit="$1"; shift ;;
      --limit=*) limit="${arg#--limit=}" ;;
      --pane) [ "$#" -gt 0 ] || return 2; pane="$1"; shift ;;
      --pane=*) pane="${arg#--pane=}" ;;
      --unacked) unacked=1 ;;
      --expects-reply) expects_reply=1 ;;
      --json) json=1 ;;
      *) printf 'message-list: unknown arg: %s\n' "$arg" >&2; return 2 ;;
    esac
  done
  obs_v2_mode; local mode="$REPLY"
  if [ "$mode" != 'on' ] && { [ "$expects_reply" = 1 ] || [ "$json" = 1 ] || [ -n "$pane" ]; }; then
    printf 'message-list: --pane/--expects-reply/--json require V2\n' >&2
    return 2
  fi
  # xtrm-wiy5n.4.24 (Codex #87): the no---for form is V2-only. The legacy
  # v1/shadow scanners (_message_list_v1_body) receive `to` verbatim and, when
  # it is empty, skip the recipient predicate — returning messages for every
  # recipient in the events log. That is an information-disclosure shape,
  # not a cosmetic gap, so refuse it here loudly instead of silently
  # widening the query. V2 mode still resolves the implicit recipient through
  # liveTmuxRequester in the underlying CLI (see cliMessageList).
  if [ "$mode" != 'on' ] && [ -z "$to" ]; then
    printf 'message-list: --for is required in XTMUX_OBS_V2=%s mode (implicit live-tmux fallback is V2-only)\n' "$mode" >&2
    return 2
  fi
  if [ "$mode" = 'on' ]; then
    # xtrm-wiy5n.4.24: --for is optional; the CLI resolves it through
    # liveTmuxRequester when running under tmux (Claude hook use case).
    # V1/shadow paths still need a name/id up front — they scan events.jsonl.
    local to_sid_v2=''
    if [ -n "$to" ] && resolve_to_session_id "$to"; then to_sid_v2="$REPLY"; else to_sid_v2="$to"; fi
    obs_runtime_argv
    local cli_args=(message-list --limit "$limit")
    [ -n "$to_sid_v2" ]      && cli_args+=(--for "$to_sid_v2")
    [ "$unacked" = 1 ]       && cli_args+=(--unacked)
    [ "$expects_reply" = 1 ] && cli_args+=(--expects-reply)
    [ "$json" = 1 ]          && cli_args+=(--json)
    [ -n "$pane" ]           && cli_args+=(--pane "$pane")
    [ -n "$from" ]           && cli_args+=(--from "$from")
    [ -n "$message_key" ]    && cli_args+=(--message-key "$message_key")
    [ -n "$since" ]          && cli_args+=(--since "$since")
    exec "${OBS_ARGV[@]}" "${cli_args[@]}"
  fi
  if [ "$mode" = 'shadow' ]; then
    local v1_out v2_out=''
    v1_out="$(_message_list_v1_body "$to" "$since" "$limit" "$unacked" "$message_key")"
    if obs_available; then
      local to_sid_v2=''
      if [ -n "$to" ] && resolve_to_session_id "$to"; then to_sid_v2="$REPLY"; else to_sid_v2="$to"; fi
      if [ -n "$to_sid_v2" ]; then
        obs_runtime_argv
        local v2_args=(message-list --for "$to_sid_v2" --limit "$limit")
        [ "$unacked" = 1 ] && v2_args+=(--unacked)
        [ "$expects_reply" = 1 ] && v2_args+=(--expects-reply)
        [ -n "$from" ] && v2_args+=(--from "$from")
        [ -n "$message_key" ] && v2_args+=(--message-key "$message_key")
        [ -n "$since" ] && v2_args+=(--since "$since")
        v2_out="$("${OBS_ARGV[@]}" "${v2_args[@]}" 2>/dev/null || true)"
      fi
    fi
    obs_shadow_diff messages message-list content "$v1_out" "$v2_out"
    [ -n "$v1_out" ] && printf '%s\n' "$v1_out"
    return 0
  fi
  _message_list_v1_body "$to" "$since" "$limit" "$unacked" "$message_key"
}

join_args_for_log() {
  local out='' arg
  for arg in "$@"; do
    out+="${out:+ }$arg"
  done
  printf '%s' "$out"
}

git_repo_root() {
  REPLY="$(git rev-parse --show-toplevel 2>/dev/null || true)"
}

git_current_branch() {
  REPLY="$(git branch --show-current 2>/dev/null || git rev-parse --abbrev-ref HEAD 2>/dev/null || true)"
}

git_head_hash() {
  REPLY="$(git rev-parse --short HEAD 2>/dev/null || true)"
}

# One command_runs row per invocation (xtmux-3xs.7): insert on start, UPDATE the
# same row on finish. The wrapped command still runs here in the shell, so its
# stdout/stderr/exit pass through untouched (PRD §20).
obs_run_start() {
  local tool="$1" mode="$2" session="$3" pane="$4" bead="$5" cwd="$6" repo="$7" branch="$8" head="$9"; shift 9
  [ "$mode" = 'off' ] && return 0
  obs_available || return 0
  obs_runtime_argv
  local args=(telemetry start --tool "$tool" --pid "$$")
  [ -n "$session" ] && args+=(--session "$session")
  [ -n "$pane" ] && args+=(--pane "$pane")
  [ -n "$bead" ] && args+=(--bead "$bead")
  [ -n "$cwd" ] && args+=(--cwd "$cwd")
  [ -n "$repo" ] && args+=(--repo "$repo")
  [ -n "$branch" ] && args+=(--branch "$branch")
  [ -n "$head" ] && args+=(--head "$head")
  args+=(-- "$@")
  "${OBS_ARGV[@]}" "${args[@]}" 2>/dev/null || true
}
obs_run_finish() {
  local run_id="$1" rc="$2" branch="$3" head="$4"
  [ -n "$run_id" ] || return 0
  obs_call telemetry finish --id "$run_id" --exit "$rc" --branch "$branch" --head "$head"
}

telemetry_run() {
  local tool="${1:-}"; shift || true
  [ -n "$tool" ] || { printf 'usage: telemetry <git|bd|gh> -- <args...>\n' >&2; return 2; }
  [ "${1:-}" = -- ] && shift
  [ "$#" -gt 0 ] || { printf 'usage: telemetry %s -- <args...>\n' "$tool" >&2; return 2; }
  local event args pane session bead cwd rc repo branch head sub mode run_id session_id
  args="$(join_args_for_log "$@")"
  obs_v2_mode; mode="$REPLY"
  pane=''; session=''; session_id=''; bead=''
  # In V2, a missing TMUX context means identity is unknown. Do not let tmux
  # resolve its default server and credit a bystander pane. V1 keeps its
  # historical lookup for byte-identity compatibility.
  if tmux_identity_available; then
    current_tmux_pane; pane="$REPLY"
    current_tmux_session; session="$REPLY"
    current_tmux_session_id; session_id="$REPLY"
    [ -n "$pane" ] && bead="$(tmux show-options -p -t "$pane" -qv @agent_bead 2>/dev/null || true)"
  fi
  cwd="$(pwd -P 2>/dev/null || pwd)"
  run_id=''
  case "$tool" in
    git)
      case "${1:-}" in
        commit) event='git.commit' ;;
        push) event='git.push' ;;
        merge) event='git.merge' ;;
        *) event='git.command' ;;
      esac
      git_repo_root; repo="$REPLY"; git_current_branch; branch="$REPLY"; git_head_hash; head="$REPLY"
      log_event telemetry.command.started tool=git event="$event" pane="$pane" session="$session" bead="$bead" cwd="$cwd" repo="$repo" branch="$branch" head="$head" argv="$args"
      run_id="$(obs_run_start git "$mode" "$session_id" "$pane" "$bead" "$cwd" "$repo" "$branch" "$head" "$@")"
      set +e
      git "$@"
      rc=$?
      set -e
      git_head_hash; head="$REPLY"; git_current_branch; branch="$REPLY"
      log_event "$event" tool=git exit="$rc" pane="$pane" session="$session" bead="$bead" cwd="$cwd" repo="$repo" branch="$branch" head="$head" argv="$args"
      obs_run_finish "$run_id" "$rc" "$branch" "$head"
      return "$rc"
      ;;
    bd)
      sub="${1:-}"
      case "$sub" in
        create) event='bd.create' ;;
        close) event='bd.close' ;;
        remember) event='bd.remember' ;;
        update)
          if printf '%s
' "$@" | grep -Eq '^--claim$|^--claim='; then event='bd.claim'; else event='bd.update'; fi
          ;;
        *) event='bd.command' ;;
      esac
      log_event telemetry.command.started tool=bd event="$event" pane="$pane" session="$session" bead="$bead" cwd="$cwd" argv="$args"
      run_id="$(obs_run_start bd "$mode" "$session_id" "$pane" "$bead" "$cwd" '' '' '' "$@")"
      set +e
      bd "$@"
      rc=$?
      set -e
      log_event "$event" tool=bd exit="$rc" pane="$pane" session="$session" bead="$bead" cwd="$cwd" argv="$args"
      obs_run_finish "$run_id" "$rc" '' ''
      return "$rc"
      ;;
    gh)
      if [ "${1:-}" = pr ] && [ "${2:-}" = create ]; then
        event='git.pr.create'
      elif [ "${1:-}" = pr ] && [ "${2:-}" = merge ]; then
        event='git.pr.merge'
      else
        event='gh.command'
      fi
      git_repo_root; repo="$REPLY"; git_current_branch; branch="$REPLY"; git_head_hash; head="$REPLY"
      log_event telemetry.command.started tool=gh event="$event" pane="$pane" session="$session" bead="$bead" cwd="$cwd" repo="$repo" branch="$branch" head="$head" argv="$args"
      run_id="$(obs_run_start gh "$mode" "$session_id" "$pane" "$bead" "$cwd" "$repo" "$branch" "$head" "$@")"
      set +e
      gh "$@"
      rc=$?
      set -e
      git_head_hash; head="$REPLY"; git_current_branch; branch="$REPLY"
      log_event "$event" tool=gh exit="$rc" pane="$pane" session="$session" bead="$bead" cwd="$cwd" repo="$repo" branch="$branch" head="$head" argv="$args"
      obs_run_finish "$run_id" "$rc" "$branch" "$head"
      return "$rc"
      ;;
    *) printf 'telemetry: unknown tool: %s\n' "$tool" >&2; return 2 ;;
  esac
}


git_branch_name() {
  local root="${1:-}"
  [ -n "$root" ] || { REPLY=''; return 0; }
  REPLY="$(git -C "$root" rev-parse --abbrev-ref HEAD 2>/dev/null || true)"
}

git_dirty_count() {
  local root="${1:-}"
  [ -n "$root" ] || { REPLY=0; return 0; }
  REPLY="$(git -C "$root" status --short 2>/dev/null | wc -l | tr -d ' ' || true)"
  [ -n "$REPLY" ] || REPLY=0
}

idle_label_plain() {
  local activity="${1:-}" now="${2:-}" age mins threshold_mins="${TMUX_PICKER_STALE_MINS:-60}"
  IDLE_STALE=0
  [[ "$activity" =~ ^[0-9]+$ ]] || { REPLY=''; return 0; }
  [[ "$now" =~ ^[0-9]+$ ]] || now="$(date +%s)"
  [[ "$threshold_mins" =~ ^[0-9]+$ ]] || threshold_mins=60
  age=$(( now - activity )); [ "$age" -lt 0 ] && age=0
  mins=$(( age / 60 ))
  [ "$mins" -ge "$threshold_mins" ] && IDLE_STALE=1
  if [ "$age" -lt 60 ]; then REPLY='<1m'
  elif [ "$age" -lt 3600 ]; then REPLY="${mins}m"
  elif [ "$age" -lt 86400 ]; then REPLY="$(( age / 3600 ))h"
  else REPLY="$(( age / 86400 ))d"; fi
}

# `stale` outranks everything: it is the one state that means the tooling has
# lost sight of a lane. A session rollup that let a healthy sibling pane hide a
# stale one would reproduce exactly the blindness of xtmux-dvs.
dashboard_state_rank() {
  case "${1:-}" in
    stale) REPLY=0 ;;
    needs-input) REPLY=1 ;;
    running) REPLY=2 ;;
    done) REPLY=3 ;;
    idle) REPLY=4 ;;
    *) REPLY=5 ;;
  esac
}

dashboard_choose_state() {
  local current="${1:-}" candidate="${2:-}" cr nr
  [ -n "$candidate" ] || { REPLY="$current"; return 0; }
  [ -n "$current" ] || { REPLY="$candidate"; return 0; }
  dashboard_state_rank "$current"; cr="$REPLY"
  dashboard_state_rank "$candidate"; nr="$REPLY"
  if [ "$nr" -lt "$cr" ]; then REPLY="$candidate"; else REPLY="$current"; fi
}

_dashboard_tsv() {
  local mode="${1:-sessions-only}" json_internal="${2:-0}" now sid sname pane_id path activity root repo branch dirty idle idle_ms shared state bead task
  local pane_sid pane_sname pane_cmd pane_path pane_state pane_bead pane_task pane_parent pane_pid pane_root pane_state_norm
  local tmp_panes _sid_list _sid
  case "$mode" in expanded|sessions-only) ;; *) mode='sessions-only' ;; esac
  now="$(date +%s)"
  tmp_panes="$(mktemp)"
  trap 'rm -f "${tmp_panes:-}"' RETURN EXIT INT TERM
  declare -A sess_name=()
  declare -A sess_path=()
  declare -A sess_activity=()
  declare -A sess_root=()
  declare -A sess_state=()
  declare -A sess_bead=()
  declare -A sess_task=()
  declare -A root_sids=()
  declare -A sess_shared=()

  while IFS=$'\t' read -r sid sname pane_id path activity; do
    [ -n "$sid" ] || continue
    path="${path:-$HOME}"
    git_root_for_path "$path"; root="$REPLY"
    sess_name["$sid"]="$sname"
    sess_path["$sid"]="$path"
    sess_activity["$sid"]="${activity:-0}"
    sess_root["$sid"]="$root"
    if [ -n "$root" ]; then
      case " ${root_sids[$root]:-} " in *" $sid "*) ;; *) root_sids[$root]+=" $sid" ;; esac
    fi
  done < <(session_meta)

  while IFS=$'\t' read -r pane_sid pane_sname pane_id pane_cmd pane_path pane_state pane_pid pane_bead pane_task pane_parent pane_transition; do
    [ -n "$pane_sid" ] || continue
    normalize_agent_state "$pane_id" "$pane_state" "$pane_cmd" "$pane_transition"; pane_state_norm="$REPLY"
    dashboard_choose_state "${sess_state[$pane_sid]:-}" "$pane_state_norm"; sess_state["$pane_sid"]="$REPLY"
    agent_meta_value "$pane_bead"; pane_bead="$REPLY"
    agent_meta_value "$pane_task"; pane_task="$REPLY"
    [ -z "${sess_bead[$pane_sid]:-}" ] && [ -n "$pane_bead" ] && sess_bead["$pane_sid"]="$pane_bead"
    [ -z "${sess_task[$pane_sid]:-}" ] && [ -n "$pane_task" ] && sess_task["$pane_sid"]="$pane_task"
    if [ "$mode" = expanded ]; then
      printf 'pane\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' \
        "$pane_sid" "$(tsv_clean "$pane_sname")" "$pane_id" "${pane_state_norm:-}" "$(tsv_clean "$pane_bead")" "$(tsv_clean "$pane_task")" "$(tsv_clean "$pane_cmd")" "$(tsv_clean "$pane_path")" >> "$tmp_panes"
    fi
  done < <(tmux list-panes -a -F $'#{session_id}\t#{session_name}\t#{pane_id}\t#{pane_current_command}\t#{pane_current_path}\t#{?@agent_state,#{@agent_state},-}\t#{pane_pid}\t#{?@agent_bead,#{@agent_bead},-}\t#{?@agent_task,#{@agent_task},-}\t#{?@agent_parent_session,#{@agent_parent_session},-}\t#{?@agent_last_transition,#{@agent_last_transition},-}' 2>/dev/null || true)

  for root in "${!root_sids[@]}"; do
    _sid_list="${root_sids[$root]}"; set -- $_sid_list
    if [ "$#" -gt 1 ]; then for _sid in "$@"; do sess_shared["$_sid"]=1; done; fi
  done

  printf 'dashboard\tmode\t%s\n' "$mode"
  for sid in "${!sess_name[@]}"; do
    sname="${sess_name[$sid]}"; path="${sess_path[$sid]:-$HOME}"; root="${sess_root[$sid]:-}"
    repo="${root##*/}"; [ -n "$root" ] || repo=''
    git_branch_name "$root"; branch="$REPLY"
    git_dirty_count "$root"; dirty="$REPLY"
    idle_label_plain "${sess_activity[$sid]:-}" "$now"; idle="$REPLY"
    if [[ "${sess_activity[$sid]:-}" =~ ^[0-9]+$ ]]; then idle_ms="$(( (now - sess_activity[$sid]) * 1000 ))"; [ "$idle_ms" -lt 0 ] && idle_ms=0; else idle_ms=0; fi
    state="${sess_state[$sid]:-}"
    bead="${sess_bead[$sid]:-}"
    if [ -z "$bead" ]; then derive_bead_id "$sname" "$path" "$root"; bead="$REPLY"; fi
    task="${sess_task[$sid]:-}"
    shared="${sess_shared[$sid]:-0}"
    printf 'session\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s' \
      "$sid" "$(tsv_clean "$sname")" "${state:-}" "$(tsv_clean "$bead")" "$(tsv_clean "$task")" "$(tsv_clean "$repo")" "$(tsv_clean "$branch")" "$dirty" "$shared" "$idle" "$(tsv_clean "$path")"
    [ "$json_internal" = 1 ] && printf '\t%s' "$idle_ms"
    printf '\n'
    if [ "$mode" = expanded ]; then
      awk -F '\t' -v s="$sid" '$1=="pane" && $2==s {print}' "$tmp_panes"
    fi
  done | sort -t $'\t' -k1,1 -k2,2
}

dashboard() {
  local mode='sessions-only' json=0 arg out line type first sid name state bead task repo branch dirty shared idle path idle_ms
  local pane_id command session_count=0 pane_count=0 started_ms="$(date +%s%3N)"
  for arg in "$@"; do
    case "$arg" in expanded|sessions-only) mode="$arg" ;; --json) json=1 ;; *) return 2 ;; esac
  done
  if [ "$json" != 1 ]; then _dashboard_tsv "$mode"; return; fi
  out="$(_dashboard_tsv "$mode" 1)"
  printf '{"mode":"%s","sessions":[' "$mode"
  first=1
  while IFS= read -r line; do
    type="$(audit_tsv_field "$line" 1)"; [ "$type" = session ] || continue
    session_count=$(( session_count + 1 ))
    sid="$(audit_tsv_field "$line" 2)"; name="$(audit_tsv_field "$line" 3)"; state="$(audit_tsv_field "$line" 4)"
    bead="$(audit_tsv_field "$line" 5)"; task="$(audit_tsv_field "$line" 6)"; repo="$(audit_tsv_field "$line" 7)"
    branch="$(audit_tsv_field "$line" 8)"; dirty="$(audit_tsv_field "$line" 9)"; shared="$(audit_tsv_field "$line" 10)"
    idle="$(audit_tsv_field "$line" 11)"; path="$(audit_tsv_field "$line" 12)"; idle_ms="$(audit_tsv_field "$line" 13)"
    [ "$first" = 1 ] || printf ','; first=0
    printf '{"sessionId":"%s","sessionName":"%s","state":%s,"beadId":%s,"task":%s,"repo":%s,"branch":%s,"dirtyCount":%s,"sharedWorktree":%s,"idleMs":%s,"path":"%s"}' \
      "$(json_escape "$sid")" "$(json_escape "$name")" "$(json_nullable "$state")" "$(json_nullable "$bead")" "$(json_nullable "$task")" \
      "$(json_nullable "$repo")" "$(json_nullable "$branch")" "${dirty:-0}" "$([ "${shared:-0}" = 1 ] && printf true || printf false)" "${idle_ms:-0}" "$(json_escape "$path")"
  done <<< "$out"
  printf '],"panes":['
  first=1
  while IFS= read -r line; do
    type="$(audit_tsv_field "$line" 1)"; [ "$type" = pane ] || continue
    pane_count=$(( pane_count + 1 ))
    sid="$(audit_tsv_field "$line" 2)"; name="$(audit_tsv_field "$line" 3)"; pane_id="$(audit_tsv_field "$line" 4)"
    state="$(audit_tsv_field "$line" 5)"; bead="$(audit_tsv_field "$line" 6)"; task="$(audit_tsv_field "$line" 7)"
    command="$(audit_tsv_field "$line" 8)"; path="$(audit_tsv_field "$line" 9)"
    [ "$first" = 1 ] || printf ','; first=0
    printf '{"sessionId":"%s","sessionName":"%s","paneId":"%s","state":%s,"beadId":%s,"task":%s,"command":%s,"path":"%s"}' \
      "$(json_escape "$sid")" "$(json_escape "$name")" "$(json_escape "$pane_id")" "$(json_nullable "$state")" "$(json_nullable "$bead")" \
      "$(json_nullable "$task")" "$(json_nullable "$command")" "$(json_escape "$path")"
  done <<< "$out"
  printf ']}\n'
  log_cli_emit query.completed command=dashboard session_count="$session_count" pane_count="$pane_count" duration_ms="$(( $(date +%s%3N) - started_ms ))" outcome=ok
}

topology_json() {
  local json=0 arg rows row sid sname created activity attached wid windex wname wactive
  local pane_id pindex pactive width height left top pid command path instance state bead task prompt parent transition role worktree branch parent_pane
  local key session_first window_first pane_first agent
  for arg in "$@"; do
    case "$arg" in
      --json) json=1 ;;
      *) command_error "$json" XTMUX_INVALID_ARGUMENT "topology: unknown arg: $arg" topology 2; return $? ;;
    esac
  done
  [ "$json" = 1 ] || { printf 'usage: topology --json\n' >&2; return 2; }

  local picker_source host_id_source
  picker_source="$(readlink -f -- "${BASH_SOURCE[0]}" 2>/dev/null || printf '%s' "${BASH_SOURCE[0]}")"
  host_id_source="$(cd -- "$(dirname -- "$picker_source")/../scripts" && pwd)/xtmux-host-id.sh"
  source "$host_id_source"
  unset host_id_source picker_source

  host_id
  local host_id="$REPLY" generated_at_ms="$(date +%s%3N)"
  # One list-panes pass supplies every session, window and pane field. Do not
  # add display-message/show-options calls here: Console needs one coherent
  # snapshot, not independently sampled hierarchy levels.
  rows="$(tmux list-panes -a -F $'#{session_id}\t#{session_name}\t#{session_created}\t#{session_activity}\t#{session_attached}\t#{window_id}\t#{window_index}\t#{window_name}\t#{window_active}\t#{pane_id}\t#{pane_index}\t#{pane_active}\t#{pane_width}\t#{pane_height}\t#{pane_left}\t#{pane_top}\t#{pane_pid}\t#{pane_current_command}\t#{pane_current_path}\t#{?@agent_instance_id,#{@agent_instance_id},-}\t#{?@agent_state,#{@agent_state},-}\t#{?@agent_bead,#{@agent_bead},-}\t#{?@agent_task,#{@agent_task},-}\t#{?@agent_prompt_file,#{@agent_prompt_file},-}\t#{?@agent_parent_session,#{@agent_parent_session},-}\t#{?@agent_last_transition,#{@agent_last_transition},-}\t#{?@agent_role,#{@agent_role},-}\t#{?@agent_worktree,#{@agent_worktree},-}\t#{?@agent_branch,#{@agent_branch},-}\t#{?@agent_parent_pane,#{@agent_parent_pane},-}' 2>/dev/null || true)"

  local -a sessions=() pane_rows=()
  declare -A session_seen=() session_name=() session_created=() session_activity=() session_attached=()
  declare -A session_windows=() window_seen=() window_index=() window_name=() window_active=()
  while IFS=$'\t' read -r sid sname created activity attached wid windex wname wactive pane_id pindex pactive width height left top pid command path instance state bead task prompt parent transition role worktree branch parent_pane; do
    [ -n "$sid" ] || continue
    sname="$(tsv_clean "$sname")"
    created="$(tsv_clean "$created")"; activity="$(tsv_clean "$activity")"; attached="$(tsv_clean "$attached")"
    windex="$(tsv_clean "$windex")"; wname="$(tsv_clean "$wname")"; wactive="$(tsv_clean "$wactive")"
    pindex="$(tsv_clean "$pindex")"; pactive="$(tsv_clean "$pactive")"; width="$(tsv_clean "$width")"
    height="$(tsv_clean "$height")"; left="$(tsv_clean "$left")"; top="$(tsv_clean "$top")"; pid="$(tsv_clean "$pid")"
    command="$(tsv_clean "$command")"; path="$(tsv_clean "$path")"
    instance="$(tsv_clean "$instance")"; state="$(tsv_clean "$state")"; bead="$(tsv_clean "$bead")"
    task="$(tsv_clean "$task")"; prompt="$(tsv_clean "$prompt")"; parent="$(tsv_clean "$parent")"
    transition="$(tsv_clean "$transition")"
    role="$(tsv_clean "$role")"; worktree="$(tsv_clean "$worktree")"
    branch="$(tsv_clean "$branch")"; parent_pane="$(tsv_clean "$parent_pane")"
    if [ -z "${session_seen[$sid]:-}" ]; then
      session_seen["$sid"]=1; sessions+=("$sid")
      session_name["$sid"]="$sname"; session_created["$sid"]="$created"
      session_activity["$sid"]="$activity"; session_attached["$sid"]="$attached"
    fi
    key="$sid|$wid"
    if [ -z "${window_seen[$key]:-}" ]; then
      window_seen["$key"]=1; session_windows["$sid"]+="${session_windows[$sid]:+ }$wid"
      window_index["$key"]="$windex"; window_name["$key"]="$wname"; window_active["$key"]="$wactive"
    fi
    pane_rows+=("$sid"$'\t'"$wid"$'\t'"$pane_id"$'\t'"$pindex"$'\t'"$pactive"$'\t'"$width"$'\t'"$height"$'\t'"$left"$'\t'"$top"$'\t'"$pid"$'\t'"$command"$'\t'"$path"$'\t'"$instance"$'\t'"$state"$'\t'"$bead"$'\t'"$task"$'\t'"$prompt"$'\t'"$parent"$'\t'"$transition"$'\t'"$role"$'\t'"$worktree"$'\t'"$branch"$'\t'"$parent_pane")
  done <<< "$rows"

  printf '{"schema_version":"xtrm.xtmux.topology.v1","generated_at_ms":%s,"host":{"host_id":"%s"},"sessions":[' \
    "$(topology_number "$generated_at_ms")" "$(json_escape "$host_id")"
  session_first=1
  for sid in "${sessions[@]}"; do
    [ "$session_first" = 1 ] || printf ','; session_first=0
    printf '{"session_id":"%s","name":"%s","created_at_ms":%s,"activity_at_ms":%s,"attached":%s,"active":%s,"windows":[' \
      "$(json_escape "$sid")" "$(json_escape "${session_name[$sid]}")" \
      "$(topology_milliseconds "${session_created[$sid]}")" "$(topology_milliseconds "${session_activity[$sid]}")" \
      "$(topology_boolean "${session_attached[$sid]}")" "$(topology_boolean "${session_attached[$sid]}")"
    window_first=1
    read -ra _topology_windows <<< "${session_windows[$sid]:-}"
    for wid in "${_topology_windows[@]}"; do
      key="$sid|$wid"
      [ "$window_first" = 1 ] || printf ','; window_first=0
      printf '{"window_id":"%s","window_index":%s,"name":"%s","active":%s,"panes":[' \
        "$(json_escape "$wid")" "$(topology_number "${window_index[$key]}")" "$(json_escape "${window_name[$key]}")" "$(topology_boolean "${window_active[$key]}")"
      pane_first=1
      for row in "${pane_rows[@]}"; do
        IFS=$'\t' read -r row_sid row_wid pane_id pindex pactive width height left top pid command path instance state bead task prompt parent transition role worktree branch parent_pane <<< "$row"
        [ "$row_sid" = "$sid" ] && [ "$row_wid" = "$wid" ] || continue
        [ "$pane_first" = 1 ] || printf ','; pane_first=0
        printf '{"pane_id":"%s","pane_index":%s,"active":%s,"width":%s,"height":%s,"left":%s,"top":%s,"pid":%s,"current_command":"%s","current_path":"%s"' \
          "$(json_escape "$pane_id")" "$(topology_number "$pindex")" "$(topology_boolean "$pactive")" \
          "$(topology_number "$width")" "$(topology_number "$height")" "$(topology_number "$left")" "$(topology_number "$top")" \
          "$(topology_number "$pid")" "$(json_escape "$command")" "$(json_escape "$path")"
        agent="$(topology_agent_json "$instance" "$state" "$bead" "$task" "$prompt" "$parent" "$transition" "$role" "$worktree" "$branch" "$parent_pane")"
        [ -n "$agent" ] && printf ',"agent":{%s}' "$agent"
        printf '}'
      done
      printf ']}'
    done
    printf ']}'
  done
  printf ']}\n'
}

audit_tsv_field() {
  local line="$1" n="$2"
  awk -F '\t' -v n="$n" '{print $n}' <<< "$line"
}

mux_help() {
  cat <<'EOF'
multiplexing-safe delegation

communication contract
  1. beads first: durable task contract (`bd show <id>`)
  2. /tmp prompt-file second: ephemeral constraints/meta-protocol
  3. send-keys third: single-line pointer only

never send while working
  wait-agent <pane> [--wait-for-transition] --timeout 30m --interval 30s
  monitor-agent <pane> [--wait-for-transition] --timeout 30m --interval 30s
  monitor-list --json / monitor-kill <id>

safe handoff
  handoff --target <pane> --bead <id> --note 'NO push'   [--prompt-file X --wait-ready 2m --monitor]
  safe-send-pointer [--reply-to <messageKey>] <pane> 'leggi /tmp/file.txt e seguilo'
  add --yes only after inspecting the printed command

message replies
  message-reply --in-reply-to <messageKey> --text <text> [--message-key K] [--json]
  message-cancel --message-key <messageKey> [--json]
  message-ack means receipt, not reply

inventory / dashboard
  dashboard sessions-only    compact orchestrator TSV
  dashboard expanded         pane-level detail
  audit                      read-only hygiene report
  worktree-collisions        shared checkout warnings

picker keys
  Tab      toggle nesting (expanded / sessions-only)
  Space    mark row for Alt-X bulk kill
  Ctrl-f   filters: repo / branch / cmd:agent / grep
  Ctrl-r   refresh active filter/mode
  Alt-i    interrupt pane micro-action
  Ctrl-Y   approve/waiting-agent micro-action
  Ctrl-O   one-line message micro-action
  ?        show this cheatsheet

cleanup rule of thumb
  cleanup rows are candidates; warning rows need operator judgment.
  dirty, shared, or working sessions are not safe to kill blindly.
EOF
}

# The command reference. Two rules when editing this:
#   1. Every command in the top-level dispatch must appear here, and nothing that
#      is not a command may appear as one. test/contract.sh fails otherwise.
#   2. The `json output:` field lists must match what the commands actually emit.
#      contract.sh compares them against live --json output, not against a doc —
#      a wrong INPUT flag fails loudly (exit 2), but a wrong OUTPUT field name
#      returns null silently, which is how `id`/`text` got guessed for messages.
# Full JSON contract (envelope, ordering, error codes): docs/json-command-api.md.
help_text() {
  cat <<'EOF'
xtmux — tmux session/pane picker and agent-orchestration CLI

usage:  xtmux <command> [args]
        xtmux help              this reference
        xtmux mux-help          delegation safety protocol (beads > /tmp > send-keys)

`tmux-session-picker` is the same program under its legacy name; every command
below works under either. <angled> args are REQUIRED, [bracketed] are optional.
[json] marks commands that accept --json and print machine-readable output.

MESSAGES — short status/escalation between panes.
Durable task content belongs in beads (`bd`), not here.
  message-send   --to <target> --text <text> [--from <id>] [--bead <id>]
                 [--to-pane <%id>] [--from-pane <%id>] [--message-key <key>]
                 [--expects-reply[=true|false]] [--reply-to <messageKey>] [json]
                 --bead implies --expects-reply=true; opt out explicitly.
  message-list   [--for <target>] [--pane <%id>] [--from <id>] [--message-key <key>]
                 [--unacked] [--expects-reply] [--limit <n>] [--since <dur>] [json]
                 --expects-reply adds correlated reply fields; --for is REQUIRED
                 outside tmux, else it defaults to the live session.
  message-get   <messageKey|messageId> [json]   read one message; never acks it
  message-reply  --in-reply-to <messageKey> --text <text> [--message-key <key>] [json]
  message-cancel --message-key <messageKey> [json]
  message-ack    <message-id> [--by <target>] [json] (receipt, not reply)
  message-status <message-key> [--json] (add --json for correlated reply state)
  unread-count   [--for <recipient>] [--pane <%id>] [json]  --for defaults to live tmux.
  obligations list [--pane <%id>] [json]   active reply obligations owned by this live pane.
  json output:
    message        messageKey, senderId, senderPaneId, senderKind, recipientId,
                   targetPaneId, recipientKind, beadId, summary, createdAtMs,
                   expectsReply, acked, ackedAtMs, ackedBy
    message-send   messageKey, messageId, duplicate, senderId, senderPaneId,
                   senderKind, recipientId, recipientKind, targetPaneId, beadId,
                   expectsReply, createdAtMs
    message-ack    messageKey, acked, ackedAtMs, ackedBy, status
    message-reply  messageKey, messageId, duplicate, replyToMessageKey,
                   fulfilledMessageKey, fulfilled, senderId, senderPaneId,
                   recipientId, targetPaneId, createdAtMs
    message-cancel messageKey, cancelled, cancelledAtMs
    message-list   correlated opt-in adds replyStatus, fulfilledAtMs,
                   fulfilledByMessageKey, correlatedReply
    message-status --json adds replyStatus, fulfilledAtMs,
                   fulfilledByMessageKey, correlatedReply
    unread-count   recipientId, unreadCount, oldestUnackedAtMs
    obligations    messageKey, messageId, senderId, senderPaneId, recipientId,
                   targetPaneId, summary, createdAtMs, acked, ackedAtMs, replyStatus

    TRAP: the message body is `summary` and its id is `messageKey`. There is
    no `text` field and no `id` field — reading those yields null.

  A target is a session id ($1732), a pane id (%2635), or a session name. Quote
    Pane/session ids in shells: '$1732' unquoted expands to nothing and acts under the WRONG identity.

MONITORS — never prompt a pane that is working; wait for it instead.
  wait-agent    <target> [--wait-for-transition] [--consume] [--timeout <dur>]
                [--interval <dur>] [json]        blocks until the pane leaves
                                                 working/running/busy/thinking (--consume claims its wake once)
  monitor-agent <target> [--wait-for-transition] [--timeout <dur>]
                [--interval <dur>] [json]        same, but registered + background
  monitor-list  [json]                             monitors [--all] [json] pretty view
  monitor-kill  <id> [json]                        monitor-run <internal>: do not call

  json output:
    wait-agent    waitId, target, requesterSessionId, requesterPaneId,
                  targetSessionId, targetPaneId, state, monitorId,
                  terminalStatus, wakeDelivered, wakeConsumed, replayed,
                  startedAtMs, completedAtMs, timeoutMs, intervalMs
    monitor-agent monitorId, waitId, target, requesterSessionId, requesterPaneId,
                  sessionId, paneId, state, paneState, startedAtMs, timeoutMs,
                  intervalMs, terminalStatus, wakeDelivered
    monitor-list  monitorId, waitId, target, requesterSessionId, requesterPaneId,
                  sessionId, paneId, state (terminal-overlaid), paneState,
                  startedAtMs, updatedAtMs, timeoutMs, intervalMs,
                  terminalStatus, terminalAtMs, wakeDelivered, wakeConsumed, orphan
    monitor-kill  monitorId, status

DELEGATION — hand work to another pane without fragmenting its prompt.
  handoff          --target <target> --bead <id> [--note <text>] [--file <path>]
                   [--yes] [json]   writes the /tmp prompt file, keeps the bead as
                                    the contract, prints the exact send command
  handoff          --target <t> --prompt-file <path> [--wait-ready <dur>] [--monitor]
                   [--handoff-key <k>] [--yes] [json]   durable, readiness-aware
                                    path over an existing file; send-keys success
                                    is an ATTEMPT, never acceptance
  safe-send-pointer [--yes] [--double-enter|--no-double-enter]
                   [--force-freeform] [--reply-to <messageKey>]
                   <target> <slash-command | /tmp pointer> [json]
                   --reply-to fulfils only after successful tmux injection; injection failure never fulfils.
                   Refuses working targets, multiline payloads and $(...); dry-runs
                   unless --yes; adds the second Enter Claude panes eat (pi/Codex do not).

  json output:
    handoff        target, paneId, beadId, promptFile, handoffKey, monitorId, sent,
                   durable, createdAtMs

IDENTITY & LAST TURN — who a pane is, and what it last said.
  context --current [--json]   the runtime origin of the INVOKING pane, as
                               xtrm.runtime-origin.v1. Read-only; outside tmux, or
                               unverifiable, exits non-zero — never a guessed binding.
  agent-last <pane-id|session-id> [--json]   full text of the target's most recent agent turn (pi+claude); plain falls back to summary; exit 5 XTMUX_NOT_FOUND.  agent-episode <pane-id|session-id> [--json]  latest response episode: primary + follow-ups, acks collapsed.
  instance-get <instance-id> [--json]        one durable agent occupation by id; plain output is field<TAB>value so a hook can read one field without a JSON parser; exit 5 XTMUX_NOT_FOUND.

  json output:
    context        schema_version, kind, host_id, tmux_session_id/window_id/
                   pane_id (stable $N/@N/%N ids, never names or indexes),
                   agent_instance_id?, bead_id?, parent_session_id?,
                   captured_at_ms, capture_source, verified
    agent-last/agent-episode  turnId, ..., completedAt (OMITTED when absent); episode:
                   episodeId, openedAtMs, closedAtMs, primary, followUps[], collapsed[]

SESSIONS & DASHBOARD — inventory for orchestrators. — inventory for orchestrators.
  dashboard [sessions-only|expanded] [json]   agent-readable inventory
  topology --json                            complete host/session/window/pane snapshot
  list [all|waiting|running|repo:<x>|branch:<x>|cmd:<x>|grep:<x>]
  list-active                                 list under the active filter

NAVIGATION — operator traversal over sessions and attention targets.
  nav [next|prev|attention-next|attention-prev|back|help]
                   `nav` opens the navigator; next/prev follow tmux session order,
                   attention-* cycle the attention ordering, back returns.

  json output:
    dashboard      mode, sessions, panes
                   sessions/panes rows: sessionId, sessionName, paneId, state,
                   beadId, task, repo, branch, dirtyCount, sharedWorktree,
                   idleMs, path
    topology       schema_version, generated_at_ms, host, sessions
                   host: host_id
                   session: session_id, name, created_at_ms, activity_at_ms,
                   attached, active, windows
                   window: window_id, window_index, name, active, panes
                   pane: pane_id, pane_index, active, width, height, left, top,
                   pid, current_command, current_path, agent?
                   agent: instance_id, state, bead_id, task, prompt_file,
                   parent_session_id, last_transition, role, worktree, branch, parent_pane_id
                   topology uses stable $/@/% ids, omits absent agent metadata,
                   and never includes pane content.

PANE CONTENT — bounded, on-demand terminal preview.
  pane capture --pane <%id> [--lines N] [--json]
                   the last N lines of one pane, ANSI escapes intact

  json output:
    pane capture   schema_version, pane_id, captured_at_ms, requested_lines,
                   returned_lines, max_lines, truncated, content

    --lines above max_lines is CLAMPED, never silently honored. truncated means
    only "there is more above what you were given"; never journalled.

REMOTE — read-only observation of another host, over your own ssh.
  bridge --stdio   NDJSON request/response on stdin/stdout, meant to be run as
                   `ssh <host> xtmux bridge --stdio`: OpenSSH owns transport and
                   auth; this stores no keys and listens on no socket.

    methods:       bridge.hello, bridge.cancel, topology.snapshot, journal.query,
                   journal.follow, pane.capture, health.get
    read-only:     anything that would MUTATE is refused (XTMUX_BRIDGE_READ_ONLY),
                   and anything not on that list is refused too. Frames are
                   size-capped; malformed input is answered and the stream keeps serving.

OBSERVABILITY — the local event log and command telemetry (see also the standalone `xtmux-events` live tail).
  log emit  <type> [key=value ...]
  log tail  [n]
  log query [--type <t>] [--session <s>] [--pane <%id>] [--bead <id>]
            [--since <dur>] [--limit <n>] [--after-id <n>] [json]
  log follow --after-id <n> [--interval <ms>] [--once] [json]
            NDJSON stream of committed journal items — same envelope as the
            log query page items, not a second schema. SIGINT/SIGTERM exit 0.
  telemetry <git|bd|gh> -- <args ...>          run a command and record it

  json output:
    log query      createdAtMs, type, domain, eventKey, sessionId, paneId,
                   beadId, correlationId, plus type-specific detail keys

    --after-id <n> cursor-paged envelope (xtrm.xtmux.journal-page.v1): journal_id
                   per item, plus next_after_id / oldest_available_id /
                   latest_available_id / has_more. Cursor = committed SQLite
                   journal id; EXCLUSIVE, ascending; never page by timestamp; a
                   cursor older than retained history returns XTMUX_CURSOR_EXPIRED
                   (oldest_available_id re-anchors the next page).

HYGIENE — end-of-session cleanup.
  audit                [json]   read-only report: `warning` rows need judgment,
                                `cleanup` rows are safe candidates
  worktree-collisions  [json]   sessions sharing one git checkout
  clear-cache                   drop the picker's git cache
  install-hooks [picker-path]   tmux cache-invalidation hooks

  json output:
    audit                severity, kind, sessionId, sessionName, paneId,
                         paneIndex, path, repo, detail
    worktree-collisions  path, sessionCount, paneCount, sessionNames

PICKER INTERNALS — invoked by the fzf UI. Agents do not normally call these.
  preview, popup, jump, kill, act, attn-jump, jump-back, kill-confirm, bulk-kill, bulk-kill-targets
  bulk-kill-confirm, rename, rename-apply, mode-toggle, filter-menu, filter-clear, filter-preset, prompt-label, border-label, nav-go, nav-act
  nav-border-label, nav-key-help, list-nav, list-nav-single, list-active-nav, list-active-nav-single

Errors are `exit 2` with a usage line; under --json they are
{"code":"XTMUX_...","message":...}. See docs/json-command-api.md.
EOF
}

audit_json() {
  local input="$1" line severity kind sid name pane path repo state cmd dirty first=1 field
  printf '['
  while IFS= read -r line; do
    IFS=$'\t' read -r severity kind sid name field _ <<< "$line"
    case "$severity" in warning|cleanup) ;; *) continue ;; esac
    pane=''; path=''; repo=''; state=''; cmd=''; dirty=''
    IFS=$'\t' read -ra _audit_fields <<< "$line"
    for field in "${_audit_fields[@]:4}"; do
      case "$field" in %*) pane="$field" ;; path=*) path="${field#path=}" ;; repo=*) repo="${field#repo=}" ;; state=*) state="${field#state=}" ;; cmd=*) cmd="${field#cmd=}" ;; dirty=*) dirty="${field#dirty=}" ;; *) [ "$kind" = missing-path ] && [ -z "$path" ] && path="$field" ;; esac
    done
    [ "$first" = 1 ] || printf ','; first=0
    printf '{"severity":"%s","kind":"%s","sessionId":%s,"sessionName":"%s","paneId":%s,"paneIndex":null,"path":%s,"repo":%s,"detail":{' \
      "$severity" "$(json_escape "$kind")" "$(json_nullable "$sid")" "$(json_escape "$name")" "$(json_nullable "$pane")" "$(json_nullable "$path")" "$(json_nullable "$repo")"
    local detail_first=1
    if [ -n "$state" ]; then printf '"state":"%s"' "$(json_escape "$state")"; detail_first=0; fi
    if [ -n "$cmd" ]; then [ "$detail_first" = 1 ] || printf ','; printf '"command":"%s"' "$(json_escape "$cmd")"; detail_first=0; fi
    if [ -n "$dirty" ]; then [ "$detail_first" = 1 ] || printf ','; printf '"dirtyCount":%s' "$dirty"; fi
    printf '}}'
  done <<< "$input"
  printf ']\n'
}

# audit_walk emits V1's human TSV. audit() wraps it so persistence is purely
# additive: stdout is whatever the walk printed, byte for byte (PRD §20), and a
# copy is piped to the runtime (xtmux-3xs.8).
audit() {
  local mode out display_out rc session stable=0 json=0 arg finding_count=0 started_ms="$(date +%s%3N)"
  while [ "$#" -gt 0 ]; do
    arg="$1"; shift
    case "$arg" in
      --stable) stable=1 ;;
      --json) json=1 ;;
      *) command_error "$json" XTMUX_INVALID_ARGUMENT "audit: unknown arg: $arg" audit 2; return $? ;;
    esac
  done
  obs_v2_mode; mode="$REPLY"
  if [ "$mode" = 'off' ] || ! obs_available; then
    audit_walk
    return "$?"
  fi
  out="$(audit_walk)"; rc=$?
  display_out="$out"
  if [ "$stable" = 1 ] && [[ "$out" == *$'\n'* ]]; then
    local header="${out%%$'\n'*}" body="${out#*$'\n'}"
    display_out="$header"$'\n'"$(printf '%s\n' "$body" | sort -t $'\t' -k1,1 -k2,2 -k4,4 -k5,5)"
  fi
  if [ "$json" = 1 ]; then
    audit_json "$display_out"
    finding_count="$(printf '%s\n' "$display_out" | grep -Ec $'^(warning|cleanup)\t' || true)"
    log_cli_emit query.completed command=audit count="$finding_count" duration_ms="$(( $(date +%s%3N) - started_ms ))" outcome="$([ "$rc" -eq 0 ] && printf ok || printf error)"
  elif [ -n "$display_out" ]; then printf '%s\n' "$display_out"; fi
  current_tmux_session_id; session="$REPLY"
  # A walk that failed halfway is a PARTIAL run: it records what it saw but must
  # never resolve findings it simply never reached. Omit unknown optional
  # identity so SQLite stores NULL rather than an empty sentinel.
  local ingest_args=(audit ingest)
  [ -n "$session" ] && ingest_args+=(--session "$session")
  [ "$rc" -eq 0 ] || ingest_args+=(--partial)
  printf '%s\n' "$out" | obs_call "${ingest_args[@]}"
  # Shadow diff for audit is a follow-up: audit_walk reads live tmux state
  # which drifts between two walks, so a live V1-vs-V2 comparison would
  # produce racy false positives. xtmux-3xs.17's --stable makes ORDER
  # comparable; a stable input-fixture harness would make CONTENT comparable.
  return "$rc"
}

audit_walk() {
  local line type sid name state bead task repo branch dirty shared idle path pane cmd
  current_tmux_session; log_event audit.run session="${REPLY:-unknown}"
  dashboard expanded | while IFS= read -r line; do
    [ -n "$line" ] || continue
    type="$(audit_tsv_field "$line" 1)"
    case "$type" in
      dashboard) printf 'audit\tread-only\twarnings-and-cleanup-candidates\n' ;;
      session)
        sid="$(audit_tsv_field "$line" 2)"
        name="$(audit_tsv_field "$line" 3)"
        state="$(audit_tsv_field "$line" 4)"
        bead="$(audit_tsv_field "$line" 5)"
        task="$(audit_tsv_field "$line" 6)"
        repo="$(audit_tsv_field "$line" 7)"
        branch="$(audit_tsv_field "$line" 8)"
        dirty="$(audit_tsv_field "$line" 9)"
        shared="$(audit_tsv_field "$line" 10)"
        idle="$(audit_tsv_field "$line" 11)"
        path="$(audit_tsv_field "$line" 12)"
        [ -n "$sid" ] || continue
        if [ -n "$path" ] && [ ! -d "$path" ]; then
          printf 'cleanup\tmissing-path\t%s\t%s\t%s\n' "$sid" "$(tsv_clean "$name")" "$(tsv_clean "$path")"
        fi
        if [[ "$name" == sp-* ]] && { [ "$state" = done ] || [ -z "$state" ]; }; then
          printf 'cleanup\tstale-specialist\t%s\t%s\tstate=%s\n' "$sid" "$(tsv_clean "$name")" "$(tsv_clean "$state")"
        fi
        if [ "${dirty:-0}" -gt 0 ] 2>/dev/null; then
          printf 'warning\tdirty-worktree\t%s\t%s\tdirty=%s\trepo=%s\tpath=%s\n' "$sid" "$(tsv_clean "$name")" "$dirty" "$(tsv_clean "$repo")" "$(tsv_clean "$path")"
        fi
        if [ "${shared:-0}" = 1 ]; then
          printf 'warning\tshared-worktree\t%s\t%s\trepo=%s\tpath=%s\n' "$sid" "$(tsv_clean "$name")" "$(tsv_clean "$repo")" "$(tsv_clean "$path")"
        fi
        if agent_state_is_working "$state"; then
          printf 'warning\tworking-do-not-kill\t%s\t%s\tstate=%s\n' "$sid" "$(tsv_clean "$name")" "$state"
        fi
        case "$name" in
          tmp-*|test-*|*-tmp|*-test|*' '*) printf 'warning\tnaming-convention\t%s\t%s\n' "$sid" "$(tsv_clean "$name")" ;;
        esac
        ;;
      pane)
        sid="$(audit_tsv_field "$line" 2)"
        name="$(audit_tsv_field "$line" 3)"
        pane="$(audit_tsv_field "$line" 4)"
        state="$(audit_tsv_field "$line" 5)"
        bead="$(audit_tsv_field "$line" 6)"
        task="$(audit_tsv_field "$line" 7)"
        cmd="$(audit_tsv_field "$line" 8)"
        path="$(audit_tsv_field "$line" 9)"
        if [ -n "$state" ] && [ -z "$bead" ]; then
          printf 'warning\tagent-pane-without-bead\t%s\t%s\t%s\tstate=%s\tcmd=%s\n' "$sid" "$(tsv_clean "$name")" "$(tsv_clean "$pane")" "$state" "$(tsv_clean "$cmd")"
        fi
        ;;
    esac
  done
}

render_pane_line() {
  local window_index="$1"
  local window_name="$2"
  local pane_id="$3"
  local pane_active="$4"
  local pane_cmd="$5"
  local pane_path="$6"
  local root="$7"
  local state="${8:-}"
  local session_name="${9:-}"
  local pane_pid="${10:-}"
  local meta_bead="${11:-}"
  local meta_task="${12:-}"
  local meta_parent="${13:-}"
  local marker cmd badge loc out sp_badge_str role_str meta_label

  marker=' '
  [ "$pane_active" = '1' ] && marker='*'
  cmd="${pane_cmd:-shell}"
  state_badge "$state"; badge="$REPLY"
  pane_location_hint "$pane_path" "$root"; loc="$REPLY"

  # specialist awareness (xtmux-rib.4): fast list path uses session name + live
  # pane pid only. bead/job details are resolved in preview to keep list warm fast.
  sp_is_specialist "$session_name" "$pane_pid"; sp_role="$REPLY"
  sp_bead=''; sp_state=''; sp_stale='' 

  paint "$c_pane" "    ↳ $marker $window_index:$window_name $pane_id"; out="$REPLY"
  if [ -n "$sp_role" ]; then
    sp_badge; sp_badge_str="$REPLY"
    out+=" $sp_badge_str"
    # show real state badges for specialists too (e.g. [wait] in the waiting
    # filter). do not show the synthetic [done] used only to rank stale cleanup.
    if [ -n "$badge" ] && ! { [ "${sp_stale:-0}" = 1 ] && [ -z "$sp_state" ] && [ "$state" = 'done' ]; }; then
      out+=" $badge"
    fi
    paint "$c_sp" "$sp_role"; role_str="$REPLY"
    [ -n "$sp_bead" ] && role_str+=" $c_dim· $sp_bead$c_reset"
    out+=" $role_str"
  else
    [ -n "$badge" ] && out+=" $badge"
    paint "$c_dim" "$cmd"; out+=" $REPLY"
  fi
  agent_meta_label "$meta_bead" "$meta_task" "$meta_parent"; meta_label="$REPLY"
  [ -n "$meta_label" ] && out+="$meta_label"
  [ -n "$loc" ] && out+="  $loc"
  REPLY="$out"
}

# ── richer filters: ctrl-f submenu + spec language (xtmux-rib.11) ────────────
# one active filter at a time, carried in a state file so the ctrl-f submenu
# can hand the chosen spec to the main fzf's reload. ctrl-a/w/e reset the slot
# (they stay pure attention filters); ctrl-f sets a content filter.
picker_state_dir() {
  local dir="${TMPDIR:-/tmp}/tmux-picker-state-${UID:-$(id -u)}"
  REPLY=''
  [ ! -L "$dir" ] || return 1
  if [ ! -e "$dir" ]; then
    (umask 077; mkdir -p "$dir") 2>/dev/null || return 1
    chmod 700 "$dir" 2>/dev/null || return 1
  fi
  [ -d "$dir" ] && [ -O "$dir" ] || return 1
  REPLY="$dir"
}

picker_state_file() {
  local name="$1" dir file
  picker_state_dir || { REPLY=''; return 1; }; dir="$REPLY"; file="$dir/$name"
  if [ -e "$file" ] || [ -L "$file" ]; then
    [ -f "$file" ] && [ ! -L "$file" ] && [ -O "$file" ] \
      || { REPLY=''; return 1; }
  fi
  REPLY="$file"
}

picker_state_read() {
  local file
  picker_state_file "$1" || { REPLY=''; return 1; }; file="$REPLY"
  REPLY="$(<"$file")"
}

picker_state_write() {
  local name="$1" value="${2:-}" file dir tmp
  picker_state_file "$name" || return 1; file="$REPLY"; dir="${file%/*}"
  tmp="$(mktemp "$dir/.${name}.XXXXXX")" || return 1
  if printf '%s' "$value" > "$tmp" && mv -f -- "$tmp" "$file"; then return 0; fi
  rm -f -- "$tmp"; return 1
}

filter_state_file() { picker_state_file filter; }
list_mode_file() { picker_state_file list-mode; }

read_list_mode() {
  picker_state_read list-mode || true
  case "$REPLY" in sessions-only) ;; *) REPLY='expanded' ;; esac
}

write_list_mode() {
  picker_state_write list-mode "${1:-expanded}"
}

toggle_list_mode() {
  read_list_mode
  case "$REPLY" in
    sessions-only) write_list_mode 'expanded' ;;
    *) write_list_mode 'sessions-only' ;;
  esac
}

# ── nav record + renderer helpers (xtmux-rib.23/.27) ───────────────────
# NAV-1 record: type<TAB>sid<TAB>name<TAB>target<TAB>token<TAB>display<NUL>.
# Field 6 is presentation-only and may contain anything (spaces, newlines,
# shell metacharacters); only the first five fields are machine identity.
#
# nav_row_fields <row> -> REPLY='type\tsid\ttarget\ttoken'. The display
# text is never parsed. A NUL-delimited read (`read -r -d ''`) returns 1 at
# EOF with no NUL; the parser tolerates that so the CLI does not abort
# mid-row under set -euo pipefail.
nav_row_fields() {
  local row="$1" type sid target token
  IFS=$'\t' read -r -d '' type sid _ target token _ <<< "$row" || true
  REPLY="$type"$'\t'"$sid"$'\t'"$target"$'\t'"$token"
}

# display_fallback <text> -> REPLY: newlines collapsed to one line. Used when
# the installed fzf cannot safely render multi-line records.
display_fallback() {
  REPLY="${1//$'\n'/ }"
}

# fit_width <text> <width> -> REPLY: unchanged when it fits, otherwise
# truncated to exactly <width> characters ending in a single ellipsis.
# Character-safe: bash substring indexing counts characters, so a multi-byte
# UTF-8 char is never split.
fit_width() {
  local text="$1" width="$2"
  if [ "$width" -le 0 ]; then
    REPLY=''
  elif [ "${#text}" -le "$width" ]; then
    REPLY="$text"
  else
    REPLY="${text:0:$((width - 1))}…"
  fi
}

# nav_wrap_text <text> <width> -> REPLY: newline-joined lines, each <= width.
# Greedy word wrap; words longer than width are hard-split (bash substring is
# character-safe). Every character of <text> is preserved, none is cut.
nav_wrap_text() {
  local text="$1" width="$2" line='' word out=''
  local -a words=() lines=()
  if [ "$width" -le 0 ]; then REPLY="$text"; return 0; fi
  # Fast path: text already fits and needs no splitting.
  if [ "${#text}" -le "$width" ] && [[ "$text" != *$'\n'* ]]; then REPLY="$text"; return 0; fi
  read -r -a words <<< "$text"
  for word in "${words[@]}"; do
    while [ "${#word}" -gt "$width" ]; do
      [ -n "$line" ] && { lines+=("$line"); line=''; }
      lines+=("${word:0:$width}")
      word="${word:$width}"
    done
    if [ -z "$line" ]; then line="$word"
    elif [ $(( ${#line} + 1 + ${#word} )) -le "$width" ]; then line+=" $word"
    else lines+=("$line"); line="$word"; fi
  done
  [ -n "$line" ] && lines+=("$line")
  [ "${#lines[@]}" -eq 0 ] && { REPLY=''; return 0; }
  printf -v out '%s
' "${lines[@]}"
  REPLY="${out%$'
'}"
}

# nav_wrap_styled <text> <width> <role> <indent> -> REPLY: wrapped, then styled
# per line with the indent prepended. Styling stays after all width math.
nav_wrap_styled() {
  local text="$1" width="$2" role="$3" indent="$4" line out=''
  nav_wrap_text "$text" "$width"
  if [[ "$REPLY" != *$'
'* ]]; then
    nav_style "$role" "$REPLY"
    REPLY="$indent$REPLY"
    return 0
  fi
  while IFS= read -r line; do
    nav_style "$role" "$line"
    out+="${out:+$'
'}$indent$REPLY"
  done <<< "$REPLY"
  REPLY="$out"
}

# current_marker <row-id> <current-id> -> REPLY='▶' when the row IS the
# current session/pane, else a single space (keeps columns aligned).
current_marker() {
  if [ "$1" = "$2" ]; then REPLY='▶'; else REPLY=' '; fi
}

# _fzf_multiline_probe_run <fzf-bin> -> on|off|classic
# Runs in command substitution, so its EXIT trap cannot affect caller traps.
# Machine-field action safety is verified FIRST (single {5}, multi {+5},
# reload-sync+track-current {5}) against single-line records; any failure is
# `classic` because a token architecture that cannot be proven must not be
# used. Only then is multi-line display integrity checked: `on` when two NUL
# records with newline displays stay distinct and round-trip, `off` when they
# do not (bounded one-line nav keeps the same proven token architecture).
_fzf_multiline_probe_run() {
  local bin="$1" work capture records expected runner actual rc
  command -v timeout >/dev/null 2>&1 || { printf 'classic\n'; return; }
  work="$(mktemp -d "${TMPDIR:-/tmp}/xtmux-fzf-probe.XXXXXX" 2>/dev/null)" || { printf 'classic\n'; return; }
  trap "rm -rf -- '$work'" EXIT INT TERM
  capture="$work/capture"
  records="$work/records"
  cat > "$capture" <<'CAPEOF'
#!/bin/sh
printf '%s\0' "$@" > "$CAPTURE"
CAPEOF
  chmod +x "$capture"
  # Machine-field records use single-line displays so token resolution is
  # tested independently of multi-line rendering.
  printf 'pane\t$42\talpha\t%%17\tp:$42:%%17\tline one\0session\t$43\tbeta\t$43\ts:$43\tsecond\0' > "$records"

  # Single highlight: {5} must resolve the hidden action token and {} must be
  # the complete machine record, never a parsed display fragment.
  runner="$work/single"
  cat > "$runner" <<EOF
#!/bin/sh
exec env -u FZF_DEFAULT_OPTS -u FZF_DEFAULT_OPTS_FILE -u FZF_DEFAULT_COMMAND \
  '$bin' --read0 --sync --no-sort --delimiter='$(printf '\t')' --with-nth=6 \
  --bind='load:become($capture {5} {})' < '$records'
EOF
  chmod +x "$runner"
  actual="$work/single.actual"
  CAPTURE="$actual" timeout --foreground --kill-after=1s 3s script -qfec "$runner" /dev/null >/dev/null 2>&1 || { printf 'classic\n'; return; }
  expected="$work/single.expected"
  printf 'p:$42:%%17\0pane\t$42\talpha\t%%17\tp:$42:%%17\tline one\0' > "$expected"
  cmp -s "$actual" "$expected" || { printf 'classic\n'; return; }

  # Multi-select must pass only field-5 machine tokens as separate arguments.
  runner="$work/multi"
  cat > "$runner" <<EOF
#!/bin/sh
exec env -u FZF_DEFAULT_OPTS -u FZF_DEFAULT_OPTS_FILE -u FZF_DEFAULT_COMMAND \
  '$bin' --read0 --sync --no-sort --multi --delimiter='$(printf '\t')' --with-nth=6 \
  --bind='load:select-all+become($capture {+5})' < '$records'
EOF
  chmod +x "$runner"
  actual="$work/multi.actual"
  CAPTURE="$actual" timeout --foreground --kill-after=1s 3s script -qfec "$runner" /dev/null >/dev/null 2>&1 || { printf 'classic\n'; return; }
  expected="$work/multi.expected"
  printf 'p:$42:%%17\0s:$43\0' > "$expected"
  cmp -s "$actual" "$expected" || { printf 'classic\n'; return; }

  # The exact reload/track/execute-silent actions used by nav must resolve the token.
  runner="$work/reload"
  cat > "$runner" <<EOF
#!/bin/sh
exec env -u FZF_DEFAULT_OPTS -u FZF_DEFAULT_OPTS_FILE -u FZF_DEFAULT_COMMAND \
  '$bin' --read0 --sync --track --delimiter='$(printf '\t')' --with-nth=6 \
  --bind='load:reload-sync(cat $records)+track-current+execute-silent($capture {5})+abort' < '$records'
EOF
  chmod +x "$runner"
  actual="$work/reload.actual"
  set +e
  CAPTURE="$actual" timeout --foreground --kill-after=1s 3s script -qfec "$runner" /dev/null >/dev/null 2>&1
  rc=$?
  set -e
  [ "$rc" -eq 130 ] || { printf 'classic\n'; return; }
  expected="$work/reload.expected"
  printf 'p:$42:%%17\0' > "$expected"
  cmp -s "$actual" "$expected" || { printf 'classic\n'; return; }

  # Multi-line integrity: two NUL records whose displays contain newlines must
  # remain exactly two selectable records with intact field-5 tokens, and the
  # complete record must round-trip through {} byte-for-byte.
  records="$work/multi-records"
  printf 'pane\t$42\talpha\t%%17\tp:$42:%%17\tline one\nline two\0session\t$43\tbeta\t$43\ts:$43\tsecond\0' > "$records"
  runner="$work/multiline"
  cat > "$runner" <<EOF
#!/bin/sh
exec env -u FZF_DEFAULT_OPTS -u FZF_DEFAULT_OPTS_FILE -u FZF_DEFAULT_COMMAND \
  '$bin' --read0 --sync --no-sort --multi --delimiter='$(printf '\t')' --with-nth=6 \
  --bind='load:select-all+become($capture {+5})' < '$records'
EOF
  chmod +x "$runner"
  actual="$work/multiline.actual"
  CAPTURE="$actual" timeout --foreground --kill-after=1s 3s script -qfec "$runner" /dev/null >/dev/null 2>&1 || { printf 'off\n'; return; }
  expected="$work/multiline.expected"
  printf 'p:$42:%%17\0s:$43\0' > "$expected"
  cmp -s "$actual" "$expected" || { printf 'off\n'; return; }
  runner="$work/multiline-full"
  cat > "$runner" <<EOF
#!/bin/sh
exec env -u FZF_DEFAULT_OPTS -u FZF_DEFAULT_OPTS_FILE -u FZF_DEFAULT_COMMAND \
  '$bin' --read0 --sync --no-sort --delimiter='$(printf '\t')' --with-nth=6 \
  --bind='load:become($capture {5} {})' < '$records'
EOF
  chmod +x "$runner"
  actual="$work/multiline-full.actual"
  CAPTURE="$actual" timeout --foreground --kill-after=1s 3s script -qfec "$runner" /dev/null >/dev/null 2>&1 || { printf 'off\n'; return; }
  expected="$work/multiline-full.expected"
  printf 'p:$42:%%17\0pane\t$42\talpha\t%%17\tp:$42:%%17\tline one\nline two\0' > "$expected"
  cmp -s "$actual" "$expected" || { printf 'off\n'; return; }
  printf 'on\n'
}

# fzf_multiline_probe -> REPLY=on|off|classic. on = NUL multi-line nav is
# proven; off = machine-field actions are proven but multi-line display is not
# (bounded one-line nav); classic = machine-field action safety cannot be
# proven, so nav must route to the classic launcher. Cached by fzf path+version
# in UI state (not the lifecycle-cleared git cache); the probe itself never
# runs fzf's search engine (--filter) — it verifies explicit action payloads.
fzf_multiline_probe() {
  REPLY='classic'
  command -v fzf >/dev/null 2>&1 || return 0
  command -v script >/dev/null 2>&1 || return 0
  command -v cmp >/dev/null 2>&1 || return 0
  command -v timeout >/dev/null 2>&1 || return 0
  local bin ver identity key cache cached_key cached_value verdict cache_ok=0
  bin="$(command -v fzf)"
  ver="$(fzf --version 2>/dev/null | head -1)"
  identity="$(stat -Lc '%d:%i:%s:%Y' "$bin" 2>/dev/null || printf unknown)"
  key="probe-v2 $bin $ver $identity"
  if picker_state_file fzf-multiline; then cache="$REPLY"; cache_ok=1; else cache=''; fi
  if [ "$cache_ok" = 1 ] && [ "${TMUX_PICKER_NO_CACHE:-0}" != '1' ] && [ -f "$cache" ]; then
    { IFS= read -r cached_key || true; IFS= read -r cached_value || true; } < "$cache"
    if [ "$cached_key" = "$key" ]; then
      case "$cached_value" in on|off|classic) REPLY="$cached_value"; return 0 ;; esac
    fi
  fi
  verdict="$(_fzf_multiline_probe_run "$bin")"
  case "$verdict" in on|off|classic) REPLY="$verdict" ;; *) REPLY='classic' ;; esac
  if [ "$cache_ok" = 1 ] && [ "${TMUX_PICKER_NO_CACHE:-0}" != '1' ]; then
    picker_state_write fzf-multiline "$(printf '%s\n%s\n' "$key" "$REPLY")" || true
  fi
}

# ── NAV-2/5: bounded hierarchy cards + launcher routing ─────────────────
# Cards are built from the SAME inventory build_list already collected: no new
# git/tmux/process queries. Free-text fields are sanitized at tmux emission, so
# the only newline a display can contain is the structural card break below.

# nav_card_width -> REPLY: bounded card width. XTMUX_NAV_WIDTH pins it for
# tests (32/44/60); otherwise the invoking client's columns (52 default).
nav_card_width() {
  local w="${XTMUX_NAV_WIDTH:-${COLUMNS:-52}}"
  case "$w" in ''|*[!0-9]*) w=52 ;; esac
  [ "$w" -gt 0 ] || w=52
  REPLY="$w"
}

# nav_text_clean removes control bytes that could alter record framing or ANSI
# presentation. Structural newlines are added only by the card renderers.
nav_text_clean() {
  local text="${1:-}"
  while [[ "$text" == *[[:cntrl:]]* ]]; do text="${text/[[:cntrl:]]/ }"; done
  REPLY="$text"
}

# nav_state_tag <normalized-state> -> REPLY=plain badge text ('' if none).
nav_state_tag() {
  case "$1" in
    stale) REPLY='stale' ;;
    needs-input) REPLY='wait' ;;
    done) REPLY='done' ;;
    running) REPLY='run' ;;
    idle) REPLY='idle' ;;
    *) REPLY='' ;;
  esac
}

# attn_state_name <rank> -> REPLY=stale|needs-input|done|running|idle
attn_state_name() {
  case "$1" in
    0) REPLY='stale' ;;
    1) REPLY='needs-input' ;;
    2) REPLY='done' ;;
    3) REPLY='running' ;;
    *) REPLY='idle' ;;
  esac
}

# nav_branch_label <branch> -> REPLY. Humanize common branch naming syntax and
# cap it before the complete context line is fitted to the drawer width.
nav_branch_label() {
  local branch="${1:-}"
  branch="${branch#refs/heads/}"
  case "$branch" in
    feature/*|feat/*|fix/*|bugfix/*|hotfix/*|chore/*|docs/*|refactor/*|test/*|release/*|xt/*) branch="${branch#*/}" ;;
  esac
  branch="${branch//\// }"; branch="${branch//_/ }"; branch="${branch//-/ }"
  while [[ "$branch" == *'  '* ]]; do branch="${branch//  / }"; done
  REPLY="$branch"
}

# nav_session_context <group-root> <root-status> <age> <shared-wt> -> REPLY
# The default row keeps only repo, concise branch, terse flags, and shared state.
nav_session_context() {
  local root="${1:-}" root_status="${2:-}" shared="${4:-}"
  local repo branch flags rest out=''
  if [ -n "$root" ]; then
    repo="${root##*/}"
    branch_from_root_status "$root_status"; branch="$REPLY"
    nav_branch_label "$branch"; branch="$REPLY"
    rest="${root_status#* }"; rest="${rest#* }"; rest="${rest#* }"
    flags=''
    case "$rest" in *'  '*) flags="${rest%%  *}" ;; esac
    out="$repo"
    [ -n "$branch" ] && out+=" · $branch"
    [ -n "$flags" ] && out+=" · $flags"
  fi
  if [ "$shared" = 1 ]; then
    [ -n "$out" ] && out+=" · "
    out+='shared'
  fi
  REPLY="$out"
}

# nav_pane_context <bead> <task> <pane-path> <root> -> REPLY
# Prefer the human task, then the bead id. Paths are details-only.
nav_pane_context() {
  local bead="${1:-}" task="${2:-}"
  agent_meta_value "$bead"; bead="$REPLY"
  agent_meta_value "$task"; task="$REPLY"
  if [[ "$task" == session:* ]]; then
    nav_branch_label "${task#session:}"; task="$REPLY"
  fi
  REPLY="${task:-$bead}"
}

nav_state_label() {
  case "$1" in
    stale) REPLY='stale' ;;
    needs-input|wait) REPLY='wait' ;;
    running|run) REPLY='run' ;;
    done) REPLY='done' ;;
    idle) REPLY='idle' ;;
    *) REPLY='' ;;
  esac
}

# nav_style <role> <text> -> REPLY. Truecolor is presentation-only and is
# applied after width calculation so ANSI bytes never affect truncation.
nav_style() {
  local role="$1" text="${2:-}" code
  case "$role" in
    session) code='38;2;240;242;243' ;;
    pane-id) code='38;2;215;219;221' ;;
    runtime) code='38;2;159;168;171' ;;
    context|task) code='38;2;133;141;145' ;;
    section) code='38;2;101;112;117' ;;
    age) code='38;2;133;141;145' ;;
    stale) code='38;2;216;141;141' ;;
    needs-input|wait) code='38;2;232;200;120' ;;
    running|run) code='38;2;143;205;160' ;;
    done) code='38;2;141;169;199' ;;
    idle) code='38;2;120;130;135' ;;
    current) code='38;2;240;242;243' ;;
    *) REPLY="$text"; return 0 ;;
  esac
  REPLY=$'\033['"$code"'m'"$text"$'\033[0m'
}

nav_group_label() {
  case "$1" in
    stale|needs-input|wait) REPLY='attn' ;;
    running|run) REPLY='active' ;;
    *) REPLY='other' ;;
  esac
}

# nav_session_card <marker> <name> <state> <age> <context> <lines>
# Every session carries its compact group label, so fuzzy filtering cannot remove
# the only heading for retained rows. Pane rows retain the precise state label.
nav_session_card() {
  local marker="${1:- }" name="$2" state="$3" age="$4" context="$5" lines="${6:-multi}" w
  local label group exact suffix prefix name_budget head body marker_styled name_styled age_styled state_styled context_styled
  nav_text_clean "$name"; name="$REPLY"
  nav_text_clean "$age"; age="$REPLY"
  nav_text_clean "$context"; context="$REPLY"
  nav_group_label "$state"; group="$REPLY"
  nav_state_label "$state"; exact="$REPLY"
  nav_card_width; w="$REPLY"
  if [ "$w" -lt 32 ]; then
    case "$group" in attn) group='a' ;; active) group='r' ;; *) group='o' ;; esac
    label="$group${exact:+/$exact}"
  else
    label="$group${exact:+ $exact}"
  fi
  suffix=''
  [ -n "$age" ] && suffix="$age"
  [ -n "$label" ] && suffix+="${suffix:+  }$label"
  prefix="$marker "
  name_budget=$(( w - ${#prefix} - ${#suffix} - 2 ))
  [ "$name_budget" -lt 1 ] && name_budget=1

  if [ "$lines" = single ]; then
    fit_width "$name" "$name_budget"; name="$REPLY"
    head="$prefix$name${suffix:+  $suffix}"
    local rest=$(( w - ${#head} - 3 ))
    if [ -n "$context" ] && [ "$rest" -ge 4 ]; then
      fit_width "$context" "$rest"; context="$REPLY"
      head+=" · $context"
    fi
    fit_width "$head" "$w"; REPLY="$REPLY"
    return 0
  fi

  # Multi: wrap instead of cut. Continuation lines align under the name.
  nav_wrap_text "$name" "$name_budget"
  local -a _name_lines=()
  if [[ "$REPLY" == *$'\n'* ]]; then
    while IFS= read -r _nl; do _name_lines+=("$_nl"); done <<< "$REPLY"
  else
    _name_lines=("$REPLY")
  fi
  local _first="${_name_lines[0]}"
  nav_style current "$marker"; marker_styled="$REPLY"
  nav_style session "$_first"; name_styled="$REPLY"
  nav_style age "$age"; age_styled="$REPLY"
  nav_style "$state" "$label"; state_styled="$REPLY"
  head="$marker_styled $name_styled"
  [ -n "$age" ] && head+="  $age_styled"
  [ -n "$age" ] && [ -n "$label" ] && head+='  '
  [ -n "$label" ] && head+="$state_styled"
  local _i
  for _i in "${_name_lines[@]:1}"; do
    [ -n "$_i" ] || continue
    nav_style session "$_i"; head+=$'\n'"  $REPLY"
  done

  body="$head"
  if [ -n "$context" ]; then
    nav_wrap_styled "$context" $(( w - 4 )) context '    '
    body+=$'\n'"$REPLY"
  fi
  REPLY="$body"
  return 0
}

# nav_pane_card <branch> <pane-id> <runtime> <state> <task> <session-state> <lines>
# Multi: pane id, group and exact state anchor line 1; runtime and task wrap
# onto continuation lines rather than being cut. Single keeps deterministic
# truncation (one physical line cannot hold more than the width).
nav_pane_card() {
  local branch="$1" pane="$2" runtime="$3" state="$4" task="$5" session_state="$6" lines="${7:-multi}" w label group indent runtime_sep base prefix suffix sep runtime_budget task_budget
  local branch_styled pane_styled runtime_styled task_styled group_styled state_styled
  nav_text_clean "$runtime"; runtime="$REPLY"
  nav_text_clean "$task"; task="$REPLY"
  nav_state_label "$state"; label="$REPLY"
  nav_group_label "$session_state"; group="$REPLY"
  nav_card_width; w="$REPLY"
  if [ "$w" -lt 32 ]; then
    case "$group" in attn) group='a' ;; active) group='r' ;; *) group='o' ;; esac
    group="$group${label:+/$label}"; label=''; indent=''; runtime_sep=' '; sep=' '
    suffix="$sep$group"
    base="$indent$branch $pane$runtime_sep"
  else
    indent='    '; runtime_sep='  '; sep='  '
    suffix="$sep$group${label:+  $label}"
    base="$indent$branch $pane$runtime_sep"
  fi

  if [ "$lines" = single ]; then
    runtime_budget=$(( w - ${#base} - ${#suffix} ))
    if [ "$w" -lt 32 ] && [ "$runtime_budget" -gt 4 ]; then runtime_budget=4; fi
    [ "$runtime_budget" -gt 11 ] && runtime_budget=11
    [ "$runtime_budget" -lt 1 ] && runtime_budget=1
    fit_width "$runtime" "$runtime_budget"; runtime="$REPLY"
    prefix="$base$runtime"
    task_budget=$(( w - ${#prefix} - ${#suffix} - 2 ))
    [ "$task_budget" -gt 24 ] && task_budget=24
    [ "$task_budget" -lt 0 ] && task_budget=0
    fit_width "$task" "$task_budget"; task="$REPLY"
    nav_style section "$branch"; branch_styled="$REPLY"
    nav_style pane-id "$pane"; pane_styled="$REPLY"
    nav_style runtime "$runtime"; runtime_styled="$REPLY"
    nav_style task "$task"; task_styled="$REPLY"
    nav_style "$session_state" "$group"; group_styled="$REPLY"
    nav_style "$state" "$label"; state_styled="$REPLY"
    REPLY="$indent$branch_styled $pane_styled$runtime_sep$runtime_styled"
    [ -n "$task" ] && REPLY+="  $task_styled"
    REPLY+="$sep$group_styled"
    [ -n "$label" ] && REPLY+="  $state_styled"
    return 0
  fi

  # Multi: line 1 = id + runtime + group/state; task and long runtimes wrap.
  runtime_budget=$(( w - ${#base} - ${#suffix} ))
  nav_wrap_text "$runtime" "$runtime_budget"
  local -a _rt=()
  if [[ "$REPLY" == *$'\n'* ]]; then
    while IFS= read -r _rl; do _rt+=("$_rl"); done <<< "$REPLY"
  else
    _rt=("$REPLY")
  fi
  nav_style section "$branch"; branch_styled="$REPLY"
  nav_style pane-id "$pane"; pane_styled="$REPLY"
  nav_style "$session_state" "$group"; group_styled="$REPLY"
  nav_style "$state" "$label"; state_styled="$REPLY"
  local _first="${_rt[0]}" _card="" _r _task_inline=0
  nav_style runtime "$_first"; runtime_styled="$REPLY"
  [ -n "$task" ] && [ $(( ${#base} + ${#_first} + 2 + ${#task} + ${#suffix} )) -le "$w" ] && _task_inline=1
  _card="$indent$branch_styled $pane_styled$runtime_sep$runtime_styled"
  if [ "$_task_inline" = 1 ]; then
    nav_style task "$task"; task_styled="$REPLY"
    _card+="  $task_styled"
  fi
  for _r in "${_rt[@]:1}"; do
    [ -n "$_r" ] || continue
    nav_style runtime "$_r"; _card+=$'\n'"$indent  $REPLY"
  done
  _card+="$sep$group_styled"
  [ -n "$label" ] && _card+="  $state_styled"
  if [ -n "$task" ] && [ "$_task_inline" = 0 ]; then
    local _ti="$indent  "
    [ "$w" -lt 32 ] && _ti=' '
    nav_wrap_styled "$task" $(( w - ${#_ti} )) task "$_ti"
    _card+=$'\n'"$REPLY"
  fi
  REPLY="$_card"
  return 0
}

# nav_route -> REPLY=classic|multiline|oneline. Maps the capability probe onto
# the three ADR fallback levels (NAV-2): on -> multiline, off -> one-line nav
# (same token architecture), classic -> classic launcher.
nav_route() {
  fzf_multiline_probe
  case "$REPLY" in
    on) REPLY='multiline' ;;
    off) REPLY='oneline' ;;
    *) REPLY='classic' ;;
  esac
}

# nav_act <token> <action> — the single strict dispatcher for every nav
# single-row action (Enter uses nav_go; popup/kill/rename/approve/interrupt/
# message use nav_act). The hidden action token is the ONLY input; display text
# never reaches any tmux command. The nav renderer never emits header records,
# and an empty/malformed token is rejected here, so no fzf row is a dead,
# closable selection.
nav_act() {
  local token="${1:-}" action="${2:-}" parsed type sid pane
  if [ -z "$token" ] || ! parse_nav_token "$token"; then
    tmux display-message 'tmux-picker: riga non azionabile' 2>/dev/null || true
    return 1
  fi
  parsed="$REPLY"
  IFS=$'\t' read -r type sid pane <<< "$parsed"
  [ "$sid" = - ] && sid=''
  case "$type" in
    session)
      case "$action" in
        popup)  open_popup_client session "$sid" "$sid" ;;
        kill)   kill_target session "$sid" "$sid" ;;
        rename) rename_target session "$sid" "$sid" ;;
        *)
          tmux display-message "tmux-picker: azione non valida su riga sessione: $action" 2>/dev/null || true
          return 1
          ;;
      esac
      ;;
    pane)
      resolve_nav_pane_session "$sid" "$pane" || return 1
      sid="$REPLY"
      case "$action" in
        popup)  open_popup_client pane "$sid" "$pane" ;;
        kill)   kill_target pane "$sid" "$pane" ;;
        rename) rename_target pane "$sid" "$pane" ;;
        approve|interrupt|message) act_on_target pane "$sid" "$pane" "$action" ;;
        *)
          tmux display-message "tmux-picker: azione sconosciuta: $action" 2>/dev/null || true
          return 1
          ;;
      esac
      ;;
  esac
}

# nav_border_label — fzf transform-border-label source for the nav launcher.
nav_border_label() {
  read_list_mode
  case "$REPLY" in
    sessions-only) printf '%s' ' ↵ open · Tab panes · ^/ details · ? help · compact ' ;;
    *) printf '%s' ' ↵ open · Tab panes · ^/ details · ? help · expanded ' ;;
  esac
}

# nav_key_help — the `?` panel for nav: the full action list stays here, never
# in the persistent footer (ADR Decision 8 / section 17).
nav_key_help() {
  cat <<'EOF'
xtmux nav — keys

  Enter          go to the highlighted session/pane
  Alt-Enter      open it in a popup (detached client)
  Tab            compact <-> expanded list
  Space          mark rows (multi-select)
  Alt-X          bulk-kill marked rows (multi-select only)
  Alt-x          kill the highlighted row
  Alt-r          rename the highlighted row
  ^Y             approve a waiting agent pane
  Alt-i          interrupt the highlighted agent pane
  ^O             message the highlighted agent pane
  ^A all · ^W wait · ^E run     attention presets
  ^F             structured filter (repo:/branch:/cmd:/grep:)
  Ctrl-r         refresh list (bypasses the git cache)
  ^/             toggle the bottom inspector
  Alt-p          inspector compact <-> large
  ?              this help

Every action resolves the hidden action token; displayed text is never parsed.
EOF
}

# pick_classic — the original newline-TSV launcher, byte-compatible with the
# legacy picker. Used by bare `xtmux`/`tmux-session-picker`, by
# XTMUX_NAV_LAYOUT=classic, and as the nav fallback when machine-field action
# safety cannot be proven. fzf receives five-field TSV rows; every action reads
# machine fields {1} {2} {4} and the Enter flow parses the row like the
# original picker.
pick_classic() {
  if ! command -v fzf >/dev/null 2>&1; then
    tmux display-message 'fzf non trovato'
    exit 1
  fi
  local preview_window='right,62%,border-left,wrap,follow'
  local preview_window_max='right,94%,border-left,wrap,follow'
  local border_label=' Enter switch · Tab mark · Alt-R rename · Alt-X bulk kill · Alt-x kill · ^Y ok · Alt-I int · ^O msg · ^A all ^W wait ^E run · ^F filter · Ctrl-r refresh · ? help · Ctrl-/ preview '
  local choice type sid name target _
  case "$mode" in
    compact-wrap)
      preview_window='right,68%,border-left,wrap,follow'
      preview_window_max='right,94%,border-left,wrap,follow'
      border_label=' compact wrap · Enter switch · Alt-Enter popup · Alt-x kill · ^Y approve · Alt-I interrupt · ^O msg · ^A/^W/^E filtri · ^F filter · Ctrl-r refresh · ? help '
      ;;
    compact-nowrap)
      preview_window='right,68%,border-left,follow'
      preview_window_max='right,94%,border-left,follow'
      border_label=' compact no-wrap · Enter switch · Alt-Enter popup · Alt-x kill · ^Y approve · Alt-I interrupt · ^O msg · ^A/^W/^E filtri · ^F filter · Ctrl-r refresh · ? help '
      ;;
  esac
  choice="$({
    "$self" list all
  } | fzf \
    --ansi \
    --delimiter=$'\t' \
    --with-nth=5 \
    --layout=reverse-list \
    --height=100% \
    --border=sharp \
    --border-label "$border_label" \
    --border-label-pos='3:bottom' \
    --no-scrollbar \
    --cycle \
    --no-bold \
    --multi \
    --prompt='all> ' \
    --pointer='>' \
    --marker='✓ ' \
    --info=inline-right \
    --color='fg:#b8bcc0,bg:-1,hl:#ffffff,fg+:#ffffff,bg+:#222222,hl+:#ffffff,info:#8a8f94,prompt:#8a8f94,pointer:#c6cacf,marker:#c6cacf,label:#8a8f94,border:#303030,gutter:-1' \
    --preview-window="$preview_window" \
    --bind="load:transform-prompt($self prompt-label)+transform-border-label($self border-label)" \
    --bind="ctrl-/:toggle-preview" \
    --bind="?:change-preview($self mux-help)" \
    --bind="ctrl-r:reload(TMUX_PICKER_NO_CACHE=1 $self list-active)" \
    --bind="ctrl-a:execute-silent($self filter-preset all)+change-prompt(all> )+reload($self list all)" \
    --bind="ctrl-w:execute-silent($self filter-preset waiting)+change-prompt(wait> )+reload($self list waiting)" \
    --bind="ctrl-e:execute-silent($self filter-preset running)+change-prompt(run> )+reload($self list running)" \
    --bind="ctrl-f:execute($self filter-menu)+reload($self list-active)+transform-prompt($self prompt-label)" \
    --bind="tab:execute($self mode-toggle)+reload($self list-active)+transform-prompt($self prompt-label)+transform-border-label($self border-label)" \
    --bind="space:toggle+down" \
    --bind="alt-p:change-preview-window($preview_window_max|$preview_window)" \
    --bind="alt-x:execute-silent($self kill {1} {2} {4})+reload($self list-active)" \
    --bind="alt-X:execute-silent($self bulk-kill-targets {+4})+reload($self list-active)" \
    --bind="alt-r:execute($self rename {1} {2} {4})+reload($self list-active)" \
    --bind="ctrl-y:execute-silent($self act {1} {2} {4} approve)+reload($self list-active)" \
    --bind="alt-i:execute-silent($self act {1} {2} {4} interrupt)+reload($self list-active)" \
    --bind="ctrl-o:execute($self act {1} {2} {4} message)+reload($self list-active)" \
    --bind="alt-enter:become($self popup {1} {2} {4})" \
    --preview "$self preview {1} {2} {3} {4}"
  )" || true
  [ -n "${choice:-}" ] || exit 0
  IFS=$'\t' read -r type sid name target _ <<< "$choice"
  jump_to_target "$type" "$sid" "$target"
}

# nav_reserve_fzf_width — convert popup columns into usable row columns. fzf's
# border plus multi-select pointer/marker gutter consume eight terminal cells.
nav_reserve_fzf_width() {
  local w="${XTMUX_NAV_WIDTH:-${COLUMNS:-52}}"
  case "$w" in ''|*[!0-9]*) w=52 ;; esac
  w=$(( w - 8 ))
  [ "$w" -lt 1 ] && w=1
  XTMUX_NAV_WIDTH="$w"
  export XTMUX_NAV_WIDTH
}

# pick_nav — the drawer launcher for bare `xtmux nav`. Routes on the capability
# probe: multiline -> NUL hierarchy cards; oneline -> NUL one-line cards (same
# hidden token architecture); classic -> the classic launcher.
# XTMUX_NAV_LAYOUT=classic forces the classic launcher. fzf runs --track with
# reload-sync+track-current binds (probe-proven); the footer is the short ADR
# string only; the inspector sits at the bottom, initially compact, ^/ toggles.
pick_nav() {
  if ! command -v fzf >/dev/null 2>&1; then
    tmux display-message 'fzf non trovato'
    exit 1
  fi
  local layout navmode
  layout="${XTMUX_NAV_LAYOUT:-}"
  if [ "$layout" = classic ]; then
    pick_classic
    return $?
  fi
  nav_route; navmode="$REPLY"
  case "$navmode" in
    classic)
      pick_classic
      return $?
      ;;
  esac
  nav_reserve_fzf_width
  local footer=' ↵ open · Tab panes · ^/ details · ? help '
  local inspector='hidden,bottom,7,border-top,wrap,follow'
  local inspector_max='bottom,50%,border-top,wrap,follow'
  local lall lwait lrun lactive self_q
  printf -v self_q '%q' "$self"
  if [ "$navmode" = oneline ]; then
    lall="$self_q list-nav-single all"
    lwait="$self_q list-nav-single waiting"
    lrun="$self_q list-nav-single running"
    lactive="$self_q list-active-nav-single"
  else
    lall="$self_q list-nav all"
    lwait="$self_q list-nav waiting"
    lrun="$self_q list-nav running"
    lactive="$self_q list-active-nav"
  fi
  local -a initial_list
  if [ "$navmode" = oneline ]; then
    initial_list=("$self" list-active-nav-single)
  else
    initial_list=("$self" list-active-nav)
  fi
  (
    local initial_file record type sid name target token display prefix pos=1 index=0
    initial_file="$(mktemp "${TMPDIR:-/tmp}/xtmux-nav.XXXXXX")" || exit 1
    trap 'rm -f "$initial_file"' EXIT INT TERM
    "${initial_list[@]}" > "$initial_file"
    while IFS= read -r -d '' record; do
      index=$((index + 1))
      IFS=$'\t' read -r type sid name target token _ <<< "$record"
      prefix="$type"$'\t'"$sid"$'\t'"$name"$'\t'"$target"$'\t'"$token"$'\t'
      display="${record#"$prefix"}"
      case "$display" in '▎ '*|*$'\n''▎ '*) pos="$index"; break ;; esac
    done < "$initial_file"
    fzf \
    --ansi \
    --read0 \
    --track \
    --delimiter=$'\t' \
    --with-nth=6 \
    --layout=reverse-list \
    --height=100% \
    --border=sharp \
    --border-label "$footer" \
    --border-label-pos='3:bottom' \
    --no-scrollbar \
    --cycle \
    --no-bold \
    --multi \
    --header=' xtmux nav · state groups · type to filter ' \
    --header-first \
    --prompt='all> ' \
    --pointer='>' \
    --marker='✓ ' \
    --info=inline-right \
    --color='fg:#b8bcc0,bg:-1,hl:#ffffff,fg+:#ffffff,bg+:#222222,hl+:#ffffff,info:#8a8f94,prompt:#8a8f94,pointer:#c6cacf,marker:#c6cacf,label:#8a8f94,border:#303030,gutter:-1' \
    --preview-window="$inspector" \
    --bind="load:pos($pos)+transform-prompt($self_q prompt-label nav)+transform-border-label($self_q nav-border-label)" \
    --bind="ctrl-/:toggle-preview" \
    --bind="?:change-preview($self_q nav-key-help)+show-preview" \
    --bind="ctrl-r:reload-sync(TMUX_PICKER_NO_CACHE=1 $lactive)+track-current" \
    --bind="ctrl-a:execute-silent($self_q filter-preset all)+change-prompt(all> )+reload-sync($lall)+track-current" \
    --bind="ctrl-w:execute-silent($self_q filter-preset waiting)+change-prompt(wait> )+reload-sync($lwait)+track-current" \
    --bind="ctrl-e:execute-silent($self_q filter-preset running)+change-prompt(run> )+reload-sync($lrun)+track-current" \
    --bind="ctrl-f:execute($self_q filter-menu)+reload-sync($lactive)+track-current+transform-prompt($self_q prompt-label nav)" \
    --bind="tab:execute($self_q mode-toggle)+reload-sync($lactive)+track-current+transform-prompt($self_q prompt-label nav)+transform-border-label($self_q nav-border-label)" \
    --bind="space:toggle+down" \
    --bind="alt-p:change-preview-window($inspector_max|$inspector)" \
    --bind="enter:become($self_q nav-go {5})" \
    --bind="alt-enter:become($self_q nav-act {5} popup)" \
    --bind="alt-x:execute-silent($self_q nav-act {5} kill)+reload-sync($lactive)+track-current" \
    --bind="alt-X:execute-silent($self_q bulk-kill {+5})+reload-sync($lactive)+track-current" \
    --bind="alt-r:execute($self_q nav-act {5} rename)+reload-sync($lactive)+track-current" \
    --bind="ctrl-y:execute-silent($self_q nav-act {5} approve)+reload-sync($lactive)+track-current" \
    --bind="alt-i:execute-silent($self_q nav-act {5} interrupt)+reload-sync($lactive)+track-current" \
    --bind="ctrl-o:execute($self_q nav-act {5} message)+reload-sync($lactive)+track-current" \
    --preview "$self_q preview {1} {2} {3} {4}" < "$initial_file" || true
  )
  return 0
}

# parse_filter <spec> -> sets FF_ATTN FF_REPO FF_BRANCH FF_CMD FF_GREP
# grammar (comma-separated clauses, ANDed):
#   all | waiting | running          attention presets
#   repo:<substr>                    substring match on repo basename
#   branch:<name>                    exact branch match
#   cmd:<agent|shell|bun>            session has a pane of that class
#   grep:<text>                      case-insensitive fixed text in pane capture
parse_filter() {
  FF_ATTN='all'; FF_REPO=''; FF_BRANCH=''; FF_CMD=''; FF_GREP=''
  local spec="${1:-}" clause
  [ -n "$spec" ] || return 0
  local _clauses=()
  IFS=',' read -ra _clauses <<< "$spec"
  for clause in "${_clauses[@]}"; do
    clause="${clause## }"; clause="${clause%% }"
    [ -n "$clause" ] || continue
    case "$clause" in
      all|waiting|running) FF_ATTN="$clause" ;;
      repo:*)   FF_REPO="${clause#repo:}" ;;
      branch:*) FF_BRANCH="${clause#branch:}" ;;
      cmd:*)    FF_CMD="${clause#cmd:}" ;;
      grep:*)   FF_GREP="${clause#grep:}" ;;
      *) ;;  # unknown clause ignored (defensive: never break the list)
    esac
  done
}

# classify_pane_cmd <pane_cmd> <normalized_state> -> REPLY=agent|shell|bun|other
# truthful source for "agent" is @agent_state (xtmux-rib.2); specialists run bun.
classify_pane_cmd() {
  local cmd="${1:-}" state="${2:-}"
  case "$cmd" in
    bun) REPLY='bun'; return 0 ;;
  esac
  if [ -n "$state" ] && [ "$state" != '-' ]; then REPLY='agent'; return 0; fi
  case "$cmd" in
    bash|zsh|sh|fish|dash|ksh|tcsh|csh|osh) REPLY='shell' ;;
    *) REPLY='other' ;;
  esac
}

# __repo_matches <root> <name-substr> -> return 0 if root basename contains name
__repo_matches() {
  local root="${1:-}" name="${2:-}" base lbase lname
  [ -n "$root" ] && [ -n "$name" ] || return 1
  base="${root##*/}"; lbase="${base,,}"; lname="${name,,}"
  case "$lbase" in *"$lname"*) return 0 ;; esac
  lbase="${root,,}"
  case "$lbase" in *"$lname"*) return 0 ;; esac
  return 1
}

# branch_from_root_status <root_status> -> REPLY=branch ('' if unparseable)
# root_status format: "REPO <icon> BRANCH [flags] <icon> <path>"
branch_from_root_status() {
  local raw="${1:-}" rest
  [ -n "$raw" ] || { REPLY=''; return 0; }
  rest="${raw#* }"            # drop REPO token
  [ "$rest" = "$raw" ] && { REPLY=''; return 0; }
  rest="${rest#* }"           # drop icon token
  REPLY="${rest%% *}"         # first token of remainder == BRANCH
}

# __filter_distinct <repo|branch> -> print distinct values across live sessions
__filter_distinct() {
  local kind="$1" p root val
  local -A seen=()
  while IFS= read -r p; do
    [ -n "$p" ] || continue
    git_root_for_path "$p"; root="$REPLY"
    [ -n "$root" ] || continue
    if [ "$kind" = repo ]; then
      val="${root##*/}"
    else
      val="$(run_git -C "$root" rev-parse --abbrev-ref HEAD 2>/dev/null || true)"
    fi
    [ -n "$val" ] || continue
    [[ -v seen["$val"] ]] && continue
    seen["$val"]=1
    printf '%s\n' "$val"
  done < <(tmux list-sessions -F '#{pane_current_path}' 2>/dev/null)
  return 0
}

# cmd_filter_menu: the ctrl-f submenu. picks dimension+value, writes spec to the
# state file. two-level for repo/branch (live sessions), one-level for cmd,
# free text for grep.
cmd_filter_menu() {
  command -v fzf >/dev/null 2>&1 || return 0
  local dim spec=''
  dim="$(printf '%s\n' 'repo' 'branch' 'cmd' 'grep' '' 'clear' \
    | fzf --prompt='filter by> ' --height=40% --no-sort --tiebreak=index --cycle 2>/dev/null)" || return 0
  case "$dim" in
    repo)
      spec="$(__filter_distinct repo | fzf --prompt='repo> ' --height=50% --no-sort 2>/dev/null)" || spec=''
      [ -n "$spec" ] && spec="repo:$spec"
      ;;
    branch)
      spec="$(__filter_distinct branch | fzf --prompt='branch> ' --height=50% --no-sort 2>/dev/null)" || spec=''
      [ -n "$spec" ] && spec="branch:$spec"
      ;;
    cmd)
      spec="$(printf '%s\n' agent shell bun | fzf --prompt='cmd> ' --height=30% --no-sort 2>/dev/null)" || spec=''
      [ -n "$spec" ] && spec="cmd:$spec"
      ;;
    grep)
      local _q
      _q="$(printf '%s\n' 'type text, then Enter' | fzf --prompt='grep> ' --print-query --height=30% --no-sort 2>/dev/null)" \
        && spec="grep:$(printf '%s\n' "$_q" | head -1)" || spec=''
      ;;
    clear) spec='' ;;
    *) spec='' ;;
  esac
  picker_state_write filter "$spec" || true
}

# build_list <spec> [<mode>] [<emit>] [<lines>]
# spec: all|waiting|running, or comma clauses repo:/branch:/cmd:/grep:
# mode: expanded (default) | sessions-only (suppress pane rows)
# emit: tsv (default, public five-field newline TSV) | nav (private
# six-field NUL-delimited records: type<TAB>sid<TAB>name<TAB>target
# <TAB>token<TAB>display<NUL>; token is s:$N / p:$N:%N)
# lines: multi (session primary/context plus one-line panes) | single (bounded one-line cards,
# the fzf-multiline off fallback; same token architecture)
build_list() (
  local filter="${1:-all}" list_mode="${2:-expanded}" emit="${3:-tsv}" lines="${4:-multi}"
  local tmp_sessions tmp_panes sid sname pane_id pane_path session_activity root sort_key group_key display root_status name_width=12 session_col
  local window_index window_name pane_index pane_active pane_cmd pane_row_path pane_col pane_state pane_pid pane_bead pane_task pane_parent pane_rank cur_rank _cls
  local psid pwi ppi ppid pcol attn idle stale_bucket section last_section=-1 header_label now
  local cur_pane='' cur_sid='' _sstate _stag _marker _sctx _scard _pblock _pline
  local pcmd pstate pbead ptask ppath proot pctx pstate_tag pdisp _nav_group _nav_state _branch _seen
  local -a _prow=()
  declare -A root_cache=()
  declare -A root_status_cache=()
  declare -A sess_name=()
  declare -A sess_attn=()
  declare -A sess_stale=()
  declare -A sess_section=()
  declare -A pane_block=()
  declare -A sess_root=()
  declare -A sess_group_root=()
  declare -A sess_root_status=()
  declare -A sess_nav_rank=()
  declare -A sess_nav_state=()
  declare -A sess_pane_count=()
  declare -A sess_pane_seen=()
  declare -A sess_classes=()
  declare -A sess_grep_hit=()
  declare -A root_sids=()
  declare -A sess_shared_wt=()
  declare -A sess_idle_plain=()
  parse_filter "$filter"

  # Persistent git cache (path -> root, root -> status). The expensive, near-static
  # half of the list. Agent state (@agent_state) and the attention sort derived
  # from it are NEVER cached — they're read fresh every call (see xtmux-rib.17).
  local _gcd _gcf _gnow _gmt _ghit=0 _gp _gr _gs
  cache_dir; _gcd="$REPLY"
  _gcf="$_gcd/git-table"
  if [ "${TMUX_PICKER_NO_CACHE:-0}" != '1' ] && [ -f "$_gcf" ]; then
    _gnow=$(date +%s)
    _gmt=$(stat -c %Y "$_gcf" 2>/dev/null || echo 0)
    if [ "$_gmt" -gt 0 ] && (( _gnow - _gmt < ${TMUX_PICKER_GIT_CACHE_TTL:-30} )); then
      while IFS=$'\t' read -r _gp _gr _gs; do
        [ -n "$_gp" ] || continue
        root_cache["$_gp"]="$_gr"
        [ -n "$_gr" ] && root_status_cache["$_gr"]="$_gs"
      done < "$_gcf"
      _ghit=1
    fi
  fi

  tmp_sessions="$(mktemp)"
  tmp_panes="$(mktemp)"
  now="$(date +%s)"
  trap 'rm -f "${tmp_sessions:-}" "${tmp_panes:-}" "${_gtmp:-}"' EXIT INT TERM

  while IFS=$'\t' read -r sid sname pane_id pane_path session_activity; do
    [ -n "$sid" ] || continue
    pane_path="${pane_path:-$HOME}"

    if [[ -v root_cache["$pane_path"] ]]; then
      root="${root_cache[$pane_path]}"
    else
      git_root_for_path "$pane_path"; root="$REPLY"
      root_cache["$pane_path"]="$root"
    fi

    if [ -n "$root" ]; then
      if [[ -v root_status_cache["$root"] ]]; then
        root_status="${root_status_cache[$root]}"
      else
        status_for_path "" "$root"; root_status="$REPLY"
        root_status_cache["$root"]="$root_status"
      fi
    else
      root_status=''
    fi

    group_root_for_path "$pane_path" "$root"; group_key="$REPLY"
    sort_key="$group_key"
    if [ "$emit" = nav ]; then
      display=''
      idle_label_plain "$session_activity" "$now"; sess_idle_plain["$sid"]="$REPLY"; stale_bucket="$IDLE_STALE"
    else
      render_list_status "$pane_path" "$root" "$root_status"; display="$REPLY"
      idle_badge "$session_activity" "$now"; idle="$REPLY"; stale_bucket="$IDLE_STALE"
      [ -n "$idle" ] && display+=" $idle"
    fi
    section=0
    [[ "$sname" == sp-* ]] && section=1
    if [ "$emit" = nav ]; then nav_text_clean "$sname"; sname="$REPLY"; fi
    sess_name["$sid"]="$sname"
    sess_stale["$sid"]="$stale_bucket"
    sess_section["$sid"]="$section"
    sess_root["$sid"]="$root"
    sess_group_root["$sid"]="${root:+$group_key}"
    sess_root_status["$sid"]="$root_status"
    [ "${#sname}" -gt "$name_width" ] && name_width="${#sname}"

    printf '%s\t%s\t%s\t%s\t%s\t%s\n' "$section" "$sort_key" "$stale_bucket" "$sid" "$sname" "$display" >> "$tmp_sessions"
  done < <(session_meta)

  while IFS=$'\t' read -r sid window_index window_name pane_id pane_index pane_active pane_cmd pane_row_path pane_state pane_pid pane_bead pane_task pane_parent pane_transition; do
    [ -n "$sid" ] || continue
    pane_row_path="${pane_row_path:-$HOME}"

    # NAV-2 current target: TMUX_PANE is honoured ONLY when it exactly matches an
    # enumerated pane; the current session is derived from that same inventory.
    # No extra tmux query (ADR Decision 9).
    if [ "$emit" = nav ] && [ -n "${TMUX_PANE:-}" ] && [ "$pane_id" = "$TMUX_PANE" ]; then
      cur_pane="$pane_id"; cur_sid="$sid"
    fi

    if [[ -v root_cache["$pane_row_path"] ]]; then
      root="${root_cache[$pane_row_path]}"
    else
      git_root_for_path "$pane_row_path"; root="$REPLY"
      root_cache["$pane_row_path"]="$root"
    fi

    if [ -n "$root" ]; then
      case " ${root_sids[$root]:-} " in *" $sid "*) ;; *) root_sids[$root]+=" $sid" ;; esac
    fi

    normalize_agent_state "$pane_id" "$pane_state" "$pane_cmd" "$pane_transition"; pane_state="$REPLY"
    if [ "$emit" = nav ]; then
      sess_pane_count["$sid"]=$(( ${sess_pane_count[$sid]:-0} + 1 ))
      case "$pane_state" in
        stale) _nav_group=0 ;;
        needs-input) _nav_group=1 ;;
        running) _nav_group=2 ;;
        done) _nav_group=3 ;;
        *) _nav_group=4 ;;
      esac
      if [ "$_nav_group" -lt "${sess_nav_rank[$sid]:-5}" ]; then
        sess_nav_rank["$sid"]="$_nav_group"
        sess_nav_state["$sid"]="$pane_state"
      fi
    fi
    # specialist state takes precedence when tracked: a waiting specialist should
    # rank for attention like a waiting agent pane (xtmux-rib.4).
    # fast specialist detection for list hot path: session name + live pane pid.
    # no pgrep/ps/sp here; bead/details are resolved in preview only. do not
    # synthesize stale/running state without process-tree evidence; explicit
    # @agent_state is the only state source in the hot list path.
    sp_is_specialist "${sess_name[$sid]:-}" "$pane_pid"; sp_role="$REPLY"
    agent_rank "$pane_state"; pane_rank="$REPLY"
    cur_rank="${sess_attn[$sid]:-4}"
    [ "$pane_rank" -lt "$cur_rank" ] && sess_attn["$sid"]="$pane_rank"

    # richer filters (xtmux-rib.11): collect per-session cmd classes + grep hits.
    # only the work for an active clause is done (free-text grep is lazy here).
    if [ -n "$FF_CMD" ]; then
      classify_pane_cmd "$pane_cmd" "$pane_state"; _cls="$REPLY"
      case " ${sess_classes[$sid]:-} " in *" $_cls "*) ;; *) sess_classes["$sid"]+=" $_cls";; esac
    fi
    if [ -n "$FF_GREP" ] && [ "${sess_grep_hit[$sid]:-0}" != 1 ]; then
      if capture_pane_safe "$pane_id" -50 | sed -E $'s/\x1b\\[[0-9;]*m//g' | grep -qiF -- "$FF_GREP"; then
        sess_grep_hit["$sid"]=1
      fi
    fi

    if [ "$emit" = nav ]; then
      # NAV-2 card inputs ride in the temp row (never used by the tsv path).
      printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$sid" "$window_index" "$pane_index" "$pane_id" "$pane_cmd" "${pane_state:--}" "${pane_bead:--}" "${pane_task:--}" "$pane_row_path" "$root" >> "$tmp_panes"
    else
      render_pane_line "$window_index" "$window_name" "$pane_id" "$pane_active" "$pane_cmd" "$pane_row_path" "$root" "$pane_state" "${sess_name[$sid]:-}" "$pane_pid" "$pane_bead" "$pane_task" "$pane_parent"; pane_col="$REPLY"
      printf '%s\t%s\t%s\t%s\t%s\n' "$sid" "$window_index" "$pane_index" "$pane_id" "$pane_col" >> "$tmp_panes"
    fi
  done < <(pane_meta)

  if [ -s "$tmp_panes" ]; then
    if [ "$emit" = nav ]; then
      while IFS=$'\t' read -r -a _prow; do
        [ -n "${_prow[0]:-}" ] || continue
        psid="${_prow[0]}"; ppid="${_prow[3]}"
        pcmd="${_prow[4]:-}"; pstate="${_prow[5]:-}"; pbead="${_prow[6]:-}"; ptask="${_prow[7]:-}"; ppath="${_prow[8]:-}"; proot="${_prow[9]:-}"
        nav_pane_context "$pbead" "$ptask" "$ppath" "$proot"; pctx="$REPLY"
        nav_state_tag "$pstate"; pstate_tag="$REPLY"
        _seen=$(( ${sess_pane_seen[$psid]:-0} + 1 )); sess_pane_seen["$psid"]="$_seen"
        if [ "$_seen" -eq "${sess_pane_count[$psid]:-1}" ]; then _branch='└'; else _branch='├'; fi
        nav_pane_card "$_branch" "$ppid" "${pcmd:-shell}" "$pstate_tag" "$pctx" "${sess_nav_state[$psid]:-idle}" "$lines"; pdisp="$REPLY"
        pane_block["$psid"]+="$(printf 'pane\t%s\t%s\t%s\tp:%s:%s\t%s' "$psid" "${sess_name[$psid]:-}" "$ppid" "$psid" "$ppid" "$pdisp")"$'\x1f'
      done < <(sort -t $'\t' -k1,1 -k2,2n -k3,3n "$tmp_panes")
    else
      while IFS=$'\t' read -r psid pwi ppi ppid pcol; do
        [ -n "$psid" ] || continue
        pane_block["$psid"]+="$(printf 'pane\t%s\t%s\t%s\t%s' "$psid" "${sess_name[$psid]:-}" "$ppid" "$pcol")"$'\n'
      done < <(sort -t $'\t' -k1,1 -k2,2n -k3,3n "$tmp_panes")
    fi
  fi

  for root in "${!root_sids[@]}"; do
    _sid_list="${root_sids[$root]}"
    # Count words in the sid list; more than one session in the same git
    # worktree is a multiplexing collision warning, not a hard error.
    set -- $_sid_list
    if [ "$#" -gt 1 ]; then
      for _sid in "$@"; do sess_shared_wt["$_sid"]=1; done
    fi
  done

  # Persist the git cache if this call was a miss. Agent state is deliberately
  # excluded — only path/root/status (near-static, expensive) is stored.
  if [ "$_ghit" = '0' ] && [ "${TMUX_PICKER_NO_CACHE:-0}" != '1' ]; then
    mkdir -p "$_gcd"
    local _gtmp="$_gcf.tmp.$$"
    if {
      for _gp in "${!root_cache[@]}"; do
        _gr="${root_cache[$_gp]}"
        _gs=""
        [ -n "$_gr" ] && _gs="${root_status_cache[$_gr]:-}"
        printf '%s\t%s\t%s\n' "$_gp" "$_gr" "$_gs"
      done
    } > "$_gtmp" 2>/dev/null; then
      mv -f "$_gtmp" "$_gcf" || rm -f "$_gtmp"
    else
      rm -f "$_gtmp"
    fi
  fi

  [ "$name_width" -gt 22 ] && name_width=22

  while IFS=$'\t' read -r section sort_key stale_bucket sid sname display; do
    if [ "$emit" = nav ]; then
      _nav_state="${sess_nav_state[$sid]:-idle}"
      case "$_nav_state" in stale|needs-input) _nav_group=0 ;; running) _nav_group=1 ;; *) _nav_group=2 ;; esac
      section="$_nav_group"
    else
      section="${sess_section[$sid]:-$section}"
    fi
    printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$section" "${sess_attn[$sid]:-4}" "${sess_stale[$sid]:-$stale_bucket}" "$sort_key" "$sid" "$sname" "$display"
  done < "$tmp_sessions" |
    sort -t $'\t' -k1,1n -k2,2n -k3,3n -k4,4 -k6,6 |
    while IFS=$'\t' read -r section attn stale_bucket _ sid sname display; do
      # attention preset (xtmux-rib.23/.25): waiting = stale + needs-input
      # (rank<=1), running = any actually-running pane (rank<=3). The old
      # guards (rank==0 / rank<=2) silently dropped needs-input panes from
      # waiting and running panes from running.
      case "$FF_ATTN" in
        waiting) [ "$attn" -le 1 ] || continue ;;
        running) [ "$attn" -le 3 ] || continue ;;
      esac
      # content filters (xtmux-rib.11): AND of repo/branch/cmd/grep clauses
      if [ -n "$FF_REPO" ]; then
        __repo_matches "${sess_root[$sid]:-}" "$FF_REPO" || continue
      fi
      if [ -n "$FF_BRANCH" ]; then
        branch_from_root_status "${sess_root_status[$sid]:-}"
        [ "$REPLY" = "$FF_BRANCH" ] || continue
      fi
      if [ -n "$FF_CMD" ]; then
        case " ${sess_classes[$sid]:-} " in *" $FF_CMD "*) ;; *) continue ;; esac
      fi
      if [ -n "$FF_GREP" ]; then
        [ "${sess_grep_hit[$sid]:-0}" = 1 ] || continue
      fi
      if [ "$emit" != nav ] && [ "${section:-0}" = 1 ] && [ "$last_section" != 1 ]; then
        paint "$c_sp" "── specialists (sp-*) ──"; header_label="$REPLY"
        printf 'header\t\tspecialists\t\t  %s\n' "$header_label"
        last_section=1
      fi
      printf -v session_col '%-*s' "$name_width" "$sname"
      if [ "${stale_bucket:-0}" = 1 ] && [ "$attn" -gt 1 ]; then
        paint "$c_dim" "$session_col"
      else
        paint "$c_session" "$session_col"
      fi
      session_col="$REPLY"
      if [ "$emit" = nav ]; then
        # NAV-2 transport: field 5 is the session action token (s:$sid); field 6
        # is the bounded card (presentation-only). The ▎ marker comes from
        # TMUX_PANE and is independent of fzf's › pointer.
        _sstate="${sess_nav_state[$sid]:-idle}"
        nav_state_tag "$_sstate"; _stag="$REPLY"
        _marker=' '
        [ -n "$cur_sid" ] && [ "$sid" = "$cur_sid" ] && _marker='▎'
        nav_session_context "${sess_group_root[$sid]:-${sess_root[$sid]:-}}" "${sess_root_status[$sid]:-}" "${sess_idle_plain[$sid]:-}" "${sess_shared_wt[$sid]:-0}"; _sctx="$REPLY"
        nav_session_card "$_marker" "$sname" "$_stag" "${sess_idle_plain[$sid]:-}" "$_sctx" "$lines"; _scard="$REPLY"
        printf 'session\t%s\t%s\t%s\ts:%s\t%s\0' "$sid" "$sname" "$sid" "$sid" "$_scard"
      else
        if [ "${sess_shared_wt[$sid]:-0}" = 1 ]; then
          paint "$c_stale" "[shared-wt]"; display+=" $REPLY"
        fi
        printf 'session\t%s\t%s\t%s\t  %s  %s\n' "$sid" "$sname" "$sid" "$session_col" "$display"
      fi
      if [ "$list_mode" != 'sessions-only' ]; then
        if [ "$emit" = nav ]; then
          # bash strings cannot hold NUL, so the block is \x1f-separated
          # internally and each row is re-terminated with NUL at emit time.
          _pblock="${pane_block[$sid]:-}"
          if [ -n "$_pblock" ]; then
            while IFS= read -r -d $'\x1f' _pline; do
              [ -n "$_pline" ] || continue
              printf '%s\0' "$_pline"
            done <<< "$_pblock"
          fi
        else
          printf '%s' "${pane_block[$sid]:-}"
        fi
      fi
    done
)

attn_list() {
  local sid sname pane_id pane_cmd activity pane_state pane_pid pane_transition rank
  while IFS=$'\t' read -r sid sname pane_id pane_cmd activity pane_state pane_pid pane_transition; do
    [ -n "$pane_id" ] || continue
    normalize_agent_state "$pane_id" "$pane_state" "$pane_cmd" "$pane_transition"; pane_state="$REPLY"
    sp_is_specialist "$sname" "$pane_pid"; sp_role="$REPLY"
    # no synthetic specialist state here: attn-jump/waiting use explicit
    # @agent_state only for sp panes, keeping the hot path truthful.
    agent_rank "$pane_state"; rank="$REPLY"
    # stale/needs-input/done. The bound tracks agent_rank: inserting `stale` at 0
    # shifted done from 1 to 2, and leaving the bound at 1 would have silently
    # dropped finished panes out of attn-jump.
    [ "$rank" -le 2 ] || continue
    printf '%s\t%s\t%s\t%s
' "$rank" "${activity:-0}" "$sid" "$pane_id"
  done < <(tmux list-panes -a -F $'#{session_id}\t#{session_name}\t#{pane_id}\t#{pane_current_command}\t#{window_activity}\t#{?@agent_state,#{@agent_state},-}\t#{pane_pid}\t#{?@agent_last_transition,#{@agent_last_transition},-}') |
    sort -t $'\t' -k1,1n -k2,2nr
}

# attn_cycle_target <next|prev> <current_pane>
# Prints 'sid<TAB>pane' of the attention-cycle target in attn_list order
# (rank asc, activity desc), wrapping at the boundaries. When the current
# pane is not in the list, next picks the first row and prev the last. An
# empty attention list prints nothing and exits 0 (non-error). Reuses
# attn_list; never enriches git/preview (xtmux-rib.25).
attn_cycle_target() {
  local dir="${1:-next}" current="${2:-}"
  local line n=0 i idx=-1 sid pane
  local -a rows=()
  while IFS= read -r line; do
    [ -n "$line" ] || continue
    rows+=("$line")
  done < <(attn_list)
  n="${#rows[@]}"
  [ "$n" -gt 0 ] || return 0
  for ((i = 0; i < n; i++)); do
    IFS=$'\t' read -r _ _ _ pane <<< "${rows[$i]}"
    if [ "$pane" = "$current" ]; then idx=$i; break; fi
  done
  if [ "$idx" -ge 0 ]; then
    if [ "$dir" = prev ]; then
      idx=$(( (idx - 1 + n) % n ))
    else
      idx=$(( (idx + 1) % n ))
    fi
  elif [ "$dir" = prev ]; then
    idx=$(( n - 1 ))
  else
    idx=0
  fi
  IFS=$'\t' read -r _ _ sid pane <<< "${rows[$idx]}"
  printf '%s\t%s\n' "$sid" "$pane"
}

record_prev() {
  local cur_sid="${1:-}" cur_pane="${2:-}" current
  if [ -z "$cur_sid" ] || [ -z "$cur_pane" ]; then
    current="$(tmux display-message -p $'#{session_id}\t#{pane_id}' 2>/dev/null || true)"
    IFS=$'\t' read -r cur_sid cur_pane <<< "$current"
  fi
  [ -n "$cur_sid" ] && [ -n "$cur_pane" ] && tmux set -g @picker_prev "$cur_sid:$cur_pane" 2>/dev/null || true
}

attn_jump() {
  local n="${1:-1}" line sid pane
  line="$(attn_list | sed -n "${n}p")"
  if [ -z "$line" ]; then
    tmux display-message "tmux-picker: nessun agente in attesa #$n"
    return 0
  fi
  IFS=$'\t' read -r _ _ sid pane <<< "$line"
  jump_to_target pane "$sid" "$pane"
}

jump_back() {
  local prev sid pane
  prev="$(tmux show -gv @picker_prev 2>/dev/null || true)"
  if [ -z "$prev" ]; then
    tmux display-message 'tmux-picker: nessun pane precedente'
    return 0
  fi
  sid="${prev%%:*}"
  pane="${prev#*:}"
  jump_to_target pane "$sid" "$pane"
}

# ── nav verb family (xtmux-rib.25) ────────────────────────────────────────
# Direct commands: never build inventory, never call git/fzf. Session cycling
# uses tmux's OWN session order (switch-client -n/-p); attention cycling
# reuses attn_list; back reuses the previous-target mechanism.

# nav_session_cycle <next|prev> — record the current target, then switch to
# the next/previous tmux session in tmux's own order.
nav_session_cycle() {
  local dir="${1:-next}"
  record_prev
  case "$dir" in
    next) tmux switch-client -n ;;
    prev) tmux switch-client -p ;;
  esac
}

# nav_attention_cycle <next|prev> — record the current target, then jump to
# the adjacent row in the authoritative attention ordering (wrap, current
# pane absent, and empty list are all non-errors).
nav_attention_cycle() {
  local dir="${1:-next}"
  local current cur_sid cur target sid pane
  current="$(tmux display-message -p $'#{session_id}\t#{pane_id}' 2>/dev/null || true)"
  IFS=$'\t' read -r cur_sid cur <<< "$current"
  target="$(attn_cycle_target "$dir" "$cur")"
  if [ -z "$target" ]; then
    tmux display-message 'tmux-picker: nessun target di attenzione' 2>/dev/null || true
    return 0
  fi
  record_prev "$cur_sid" "$cur"
  IFS=$'\t' read -r sid pane <<< "$target"
  jump_to_target pane "$sid" "$pane"
}

# parse_nav_token <token> -> REPLY='type<TAB>sid<TAB>pane'. IDs use tmux's
# immutable machine forms only; names and general tmux target syntax are rejected.
parse_nav_token() {
  local tok="${1:-}"
  REPLY=''
  if [[ "$tok" =~ ^s:(\$[0-9]+)$ ]]; then
    REPLY="session"$'\t'"${BASH_REMATCH[1]}"$'\t'
  elif [[ "$tok" =~ ^p:(\$[0-9]+):(%[0-9]+)$ ]]; then
    REPLY="pane"$'\t'"${BASH_REMATCH[1]}"$'\t'"${BASH_REMATCH[2]}"
  elif [[ "$tok" =~ ^p:(%[0-9]+)$ ]]; then
    REPLY="pane"$'\t-\t'"${BASH_REMATCH[1]}"
  else
    return 1
  fi
}

# resolve_nav_pane_session <encoded-sid-or-empty> <pane> -> REPLY=live sid.
# A paired token is rejected if the pane no longer belongs to that session.
resolve_nav_pane_session() {
  local encoded="${1:-}" pane="$2" live
  live="$(tmux display-message -p -t "$pane" '#{session_id}' 2>/dev/null || true)"
  [ -n "$live" ] || return 1
  [ -z "$encoded" ] || [ "$encoded" = "$live" ] || return 1
  REPLY="$live"
}

# nav_go <token> acts on hidden machine identity and records the previous target.
nav_go() {
  local parsed type sid pane
  parse_nav_token "${1:-}" || return 1
  parsed="$REPLY"
  IFS=$'\t' read -r type sid pane <<< "$parsed"
  [ "$sid" = - ] && sid=''
  case "$type" in
    session)
      record_prev
      jump_to_target session "$sid" "$sid"
      ;;
    pane)
      resolve_nav_pane_session "$sid" "$pane" || return 1
      sid="$REPLY"
      record_prev
      jump_to_target pane "$sid" "$pane"
      ;;
  esac
}

nav_help() {
  cat <<'EOF'
xtmux nav — operator navigation over tmux sessions and attention targets.

usage:  xtmux nav                      open the interactive navigator (fzf)
        xtmux nav next                 switch to the next tmux session
        xtmux nav prev                 switch to the previous tmux session
        xtmux nav attention-next       cycle to the next attention target
        xtmux nav attention-prev       cycle to the previous attention target
        xtmux nav back                 return to the target recorded before the last jump
        xtmux nav help                 this reference

next/prev follow tmux's own session order (switch-client -n / -p) and
record the previous target so `back` can return. attention-next/prev cycle
the authoritative attention ordering (stale, needs-input, done); an empty
attention list is a non-error. back reuses the existing @picker_prev
mechanism. The nav family is interactive-only: --json is refused.
EOF
}

parse_wait_duration() {
  local raw="${1:-}" n unit
  [ -n "$raw" ] || { REPLY=0; return 0; }
  if [[ "$raw" =~ ^([0-9]+)([smhd]?)$ ]]; then
    n="${BASH_REMATCH[1]}"; unit="${BASH_REMATCH[2]}"
    case "$unit" in
      h) REPLY=$(( n * 3600 )) ;;
      m) REPLY=$(( n * 60 )) ;;
      d) REPLY=$(( n * 86400 )) ;;
      *) REPLY="$n" ;;
    esac
    return 0
  fi
  return 1
}

resolve_tmux_pane() {
  local target="${1:-}"
  [ -n "$target" ] || return 1
  REPLY="$(tmux display-message -p -t "$target" '#{pane_id}' 2>/dev/null || true)"
  [ -n "$REPLY" ]
}

observe_agent_state() {
  local pane="$1" raw cmd state
  raw="$(tmux show-options -p -t "$pane" -qv @agent_state 2>/dev/null || true)"
  if [ -n "$raw" ]; then
    normalize_agent_state "$pane" "$raw" ""; REPLY="$REPLY"; return 0
  fi
  # Fallback for panes without @agent_state: use the same opt-in inference as the
  # picker, scoped to this call. This is intentionally secondary because UI
  # markers are brittle across agent harnesses.
  cmd="$(tmux display-message -p -t "$pane" '#{pane_current_command}' 2>/dev/null || true)"
  if [ -n "$cmd" ]; then
    TMUX_PICKER_AGENT=1 normalize_agent_state "$pane" "" "$cmd"
    state="$REPLY"
    [ -n "$state" ] || state='unknown'
    REPLY="$state"
  else
    REPLY='unknown'
  fi
}

wait_agent() {
  local target='' timeout=0 interval=30 wait_for_transition=0 json=0 arg pane state start started_ms now elapsed armed=1
  while [ "$#" -gt 0 ]; do
    arg="$1"; shift
    case "$arg" in
      --wait-for-transition) wait_for_transition=1 ;;
      --timeout=*) parse_wait_duration "${arg#--timeout=}" || return 2; timeout="$REPLY" ;;
      --timeout) [ "$#" -gt 0 ] || return 2; parse_wait_duration "$1" || return 2; timeout="$REPLY"; shift ;;
      --interval=*) parse_wait_duration "${arg#--interval=}" || return 2; interval="$REPLY" ;;
      --interval) [ "$#" -gt 0 ] || return 2; parse_wait_duration "$1" || return 2; interval="$REPLY"; shift ;;
      --json) json=1 ;;
      -h|--help) return 2 ;;
      *) [ -z "$target" ] || return 2; target="$arg" ;;
    esac
  done
  [ -n "$target" ] || { command_error "$json" XTMUX_INVALID_ARGUMENT 'wait-agent: target required' wait-agent 2; return $?; }
  resolve_tmux_pane "$target" || { command_error "$json" XTMUX_TARGET_NOT_FOUND "wait-agent: target not found: $target" wait-agent 1; return $?; }
  pane="$REPLY"
  start="$(date +%s)"
  started_ms="$(date +%s%3N)"
  if [ "$wait_for_transition" = 1 ]; then
    observe_agent_state "$pane"
    agent_state_is_working "$REPLY" || armed=0
  fi
  while :; do
    observe_agent_state "$pane"; state="$REPLY"
    if [ "$armed" = 0 ]; then
      agent_state_is_working "$state" && armed=1
    elif ! agent_state_is_working "$state"; then
      if [ "$json" = 1 ]; then
        printf '{"target":"%s","sessionId":null,"paneId":"%s","state":"%s","status":"done","startedAtMs":%s,"completedAtMs":%s,"timeoutMs":%s,"intervalMs":%s}\n' \
          "$(json_escape "$target")" "$(json_escape "$pane")" "$(json_escape "$state")" "$started_ms" "$(date +%s%3N)" "$(( timeout * 1000 ))" "$(( interval * 1000 ))"
      else
        printf 'target=%s pane=%s state=%s\n' "$target" "$pane" "$state"
      fi
      return 0
    fi
    if [ "$timeout" -gt 0 ]; then
      now="$(date +%s)"; elapsed=$(( now - start ))
      if [ "$elapsed" -ge "$timeout" ]; then
        if [ "$json" = 1 ]; then
          json_error XTMUX_WAIT_TIMEOUT "wait-agent: timeout target=$target pane=$pane state=$state elapsed=${elapsed}s" wait-agent
        else
          printf 'wait-agent: timeout target=%s pane=%s state=%s elapsed=%ss\n' "$target" "$pane" "$state" "$elapsed" >&2
        fi
        return 124
      fi
    fi
    sleep "$interval"
  done
}

monitor_dir() {
  REPLY="${TMPDIR:-/tmp}/tmux-picker-state-${UID:-$(id -u)}/monitors"
}

monitor_file() {
  local id="${1:-}"
  monitor_dir
  REPLY="$REPLY/$id.tsv"
}

monitor_write_record() {
  local id="$1" pid="$2" target="$3" pane="$4" state="$5" start="$6" timeout="$7" interval="$8" updated="$9"
  local file tmp dir mode
  # Under XTMUX_OBS_V2=1 the monitors table is authoritative and the /tmp registry
  # is not written at all (xtmux-3xs.4: "no /tmp writes from the V2 monitor path").
  obs_v2_mode; mode="$REPLY"
  [ "$mode" = 'on' ] && return 0
  monitor_file "$id"; file="$REPLY"; dir="${file%/*}"
  mkdir -p "$dir" 2>/dev/null || true
  tmp="$file.tmp.$$"
  printf 'monitor\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' \
    "$(tsv_clean "$id")" "$(tsv_clean "$pid")" "$(tsv_clean "$target")" "$(tsv_clean "$pane")" \
    "$(tsv_clean "$state")" "$(tsv_clean "$start")" "$(tsv_clean "$timeout")" "$(tsv_clean "$interval")" "$(tsv_clean "$updated")" \
    > "$tmp" && mv -f "$tmp" "$file"
}

monitor_run() {
  local id="$1" target="$2" pane="$3" timeout="$4" interval="$5" start="$6" wait_for_transition="${7:-0}" initial_state="${8:-}"
  local state now elapsed mode armed=1
  [ "$wait_for_transition" = 1 ] && ! agent_state_is_working "$initial_state" && armed=0
  obs_v2_mode; mode="$REPLY"
  cleanup_monitor() {
    local cleanup_id="$1" cleanup_mode="$2"
    # V2 keeps the row (it carries the terminal history); only the TSV goes.
    [ "$cleanup_mode" = 'on' ] || { monitor_file "$cleanup_id"; rm -f "$REPLY" 2>/dev/null || true; }
  }
  trap "cleanup_monitor '$id' '$mode'" EXIT INT TERM
  while :; do
    observe_agent_state "$pane"; state="$REPLY"
    now="$(date +%s)"
    monitor_write_record "$id" "$$" "$target" "$pane" "$state" "$start" "$timeout" "$interval" "$now"
    # A tick updates the row in place. It does not append a historical event —
    # that is the whole point of the phase.
    [ "$mode" = 'off' ] || obs_call monitor heartbeat --id "$id" --state "$state"
    if [ "$armed" = 0 ]; then
      agent_state_is_working "$state" && armed=1
    elif ! agent_state_is_working "$state"; then
      log_event monitor.done id="$id" target="$target" pane="$pane" state="$state"
      [ "$mode" = 'off' ] || obs_call monitor terminate --id "$id" --status done
      return 0
    fi
    if [ "$timeout" -gt 0 ]; then
      elapsed=$(( now - start ))
      if [ "$elapsed" -ge "$timeout" ]; then
        log_event monitor.timeout id="$id" target="$target" pane="$pane" state="$state" elapsed="$elapsed"
        [ "$mode" = 'off' ] || obs_call monitor terminate --id "$id" --status timeout
        return 124
      fi
    fi
    sleep "$interval"
  done
}

monitor_agent() {
  local target='' timeout=0 interval=30 wait_for_transition=0 json=0 arg pane state start id pid mode session
  while [ "$#" -gt 0 ]; do
    arg="$1"; shift
    case "$arg" in
      --wait-for-transition) wait_for_transition=1 ;;
      --timeout=*) parse_wait_duration "${arg#--timeout=}" || return 2; timeout="$REPLY" ;;
      --timeout) [ "$#" -gt 0 ] || return 2; parse_wait_duration "$1" || return 2; timeout="$REPLY"; shift ;;
      --interval=*) parse_wait_duration "${arg#--interval=}" || return 2; interval="$REPLY" ;;
      --interval) [ "$#" -gt 0 ] || return 2; parse_wait_duration "$1" || return 2; interval="$REPLY"; shift ;;
      --json) json=1 ;;
      -h|--help) return 2 ;;
      *) [ -z "$target" ] || return 2; target="$arg" ;;
    esac
  done
  [ -n "$target" ] || { command_error "$json" XTMUX_INVALID_ARGUMENT 'usage: monitor-agent <target> [--wait-for-transition] [--timeout 30m] [--interval 30s]' monitor-agent 2; return $?; }
  resolve_tmux_pane "$target" || { command_error "$json" XTMUX_TARGET_NOT_FOUND "monitor-agent: target not found: $target" monitor-agent 1; return $?; }
  pane="$REPLY"
  observe_agent_state "$pane"; state="$REPLY"
  start="$(date +%s)"
  id="m${start}-$(printf '%s' "$pane" | tr -cd '0-9A-Za-z')-$$"
  obs_v2_mode; mode="$REPLY"
  monitor_write_record "$id" "starting" "$target" "$pane" "$state" "$start" "$timeout" "$interval" "$start"
  current_tmux_session_id; session="$REPLY"
  if [ "$mode" != 'off' ]; then
    local register_args=(monitor register --id "$id" --target "$target" --pane "$pane" \
      --state "$state" --timeout "$timeout" --interval "$interval")
    [ -n "$session" ] && register_args+=(--session "$session")
    obs_call "${register_args[@]}"
  fi
  "$self" monitor-run "$id" "$target" "$pane" "$timeout" "$interval" "$start" "$wait_for_transition" "$state" >/dev/null 2>&1 &
  pid="$!"
  monitor_write_record "$id" "$pid" "$target" "$pane" "$state" "$start" "$timeout" "$interval" "$start"
  # The poller now has a PID: adopt it, so reconciliation can tell a crashed
  # monitor from one that simply has not ticked yet.
  [ "$mode" = 'off' ] || obs_call monitor adopt --id "$id" --pid "$pid"
  log_event monitor.started id="$id" pid="$pid" target="$target" pane="$pane" state="$state" timeout="$timeout" interval="$interval"
  if [ "$json" = 1 ]; then
    printf '{"monitorId":"%s","target":"%s","sessionId":%s,"paneId":"%s","state":"%s","startedAtMs":%s,"timeoutMs":%s,"intervalMs":%s}\n' \
      "$(json_escape "$id")" "$(json_escape "$target")" "$([ -n "$session" ] && printf '"%s"' "$(json_escape "$session")" || printf 'null')" \
      "$(json_escape "$pane")" "$(json_escape "$state")" "$(( start * 1000 ))" "$(( timeout * 1000 ))" "$(( interval * 1000 ))"
  else
    printf 'monitor\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$id" "$pid" "$target" "$pane" "$state" "$start" "$timeout" "$interval" "$start"
  fi
}

# _monitor_list_v1_body — V1 TSV scan of the monitor state dir; extracted so
# the shadow-tee path can capture stdout before diffing.
_monitor_list_v1_body() {
  local dir file line type id pid target pane state start timeout interval updated now
  monitor_dir; dir="$REPLY"
  [ -d "$dir" ] || return 0
  now="$(date +%s)"
  for file in "$dir"/*.tsv; do
    [ -e "$file" ] || continue
    IFS=$'\t' read -r type id pid target pane state start timeout interval updated < "$file" || continue
    if [ -n "$pid" ] && [ "$pid" != starting ] && ! kill -0 "$pid" 2>/dev/null; then
      rm -f "$file" 2>/dev/null || true
      continue
    fi
    if [ -n "$pane" ]; then
      observe_agent_state "$pane"; state="$REPLY"
      monitor_write_record "$id" "$pid" "$target" "$pane" "$state" "$start" "$timeout" "$interval" "$now"
    fi
    printf 'monitor\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$id" "$pid" "$target" "$pane" "$state" "$start" "$timeout" "$interval" "$now"
  done | sort -t $'\t' -k6,6 -k2,2
}

monitor_list() {
  local json=0
  [ "${1:-}" = '--json' ] && json=1
  obs_v2_mode; local mode="$REPLY"
  # V2 authoritative: the table is the registry, and reconciliation of crashed
  # pollers happens inside the scan.
  if [ "$mode" = 'on' ]; then
    local args=(monitor list)
    [ "$json" = 1 ] && args+=(--json)
    obs_call_strict "${args[@]}"
    return "$?"
  fi
  if [ "$mode" = 'shadow' ]; then
    local v1_out v2_out=''
    v1_out="$(_monitor_list_v1_body)"
    if obs_available; then
      v2_out="$(obs_call_strict monitor list 2>/dev/null || true)"
    fi
    obs_shadow_diff monitors monitor-list content "$v1_out" "$v2_out"
    [ -n "$v1_out" ] && printf '%s\n' "$v1_out"
    return 0
  fi
  _monitor_list_v1_body
}

monitor_kill() {
  local id='' json=0 arg file type rid pid rest mode
  for arg in "$@"; do
    case "$arg" in --json) json=1 ;; --*) return 2 ;; *) [ -z "$id" ] || return 2; id="$arg" ;; esac
  done
  [ -n "$id" ] || { printf 'usage: monitor-kill <id>\n' >&2; return 2; }
  obs_v2_mode; mode="$REPLY"
  # V2 authoritative: the row is preserved with terminal_status=killed. V1 deleted
  # the TSV here, which is why a killed monitor left no history at all.
  if [ "$mode" = 'on' ]; then
    local args=(monitor kill --id "$id")
    [ "$json" = 1 ] && args+=(--json)
    obs_call_strict "${args[@]}"
    return "$?"
  fi
  monitor_file "$id"; file="$REPLY"
  [ -f "$file" ] || { printf 'monitor-kill: not found: %s\n' "$id" >&2; return 1; }
  IFS=$'\t' read -r type rid pid rest < "$file" || true
  if [ -n "${pid:-}" ] && [ "$pid" != starting ]; then kill "$pid" 2>/dev/null || true; fi
  rm -f "$file" 2>/dev/null || true
  log_event monitor.killed id="$id" pid="${pid:-}"
  [ "$mode" = 'off' ] || obs_call monitor terminate --id "$id" --status killed
  printf 'killed\t%s\n' "$id"
}

# monitors_view — human-scannable projection of monitor-list + obligations.
# Reads monitor-list --json (authoritative under V2), filters to non-terminal
# rows by default (`--all` shows everything), and prints one row per monitor as
# aligned columns so an operator can glance and see who is waiting on whom,
# how long, and how close to timeout each one is.
#
# ponytail: leans on the existing --json projection and jq; no new schema, no
# per-domain re-implementation. If jq is missing, we fall back to plain
# `monitor-list` TSV so the alias never blows up on minimal boxes.
monitors_view() {
  local show_all=0 json=0 from_file='' arg
  while [ $# -gt 0 ]; do
    case "$1" in
      --all) show_all=1 ;;
      --json) json=1 ;;
      # test hook: read monitor-list JSON from a file instead of shelling to
      # $self. Undocumented on purpose — only the formatter test uses it.
      --from-json) shift; from_file="${1:-}" ;;
      --from-json=*) from_file="${1#*=}" ;;
      -h|--help)
        cat <<'EOF'
usage: xtmux monitors [--all] [--json]
  Operator-scannable view of active monitors (target pane state, timeout progress,
  requester pane). By default hides monitors that have reached a terminal state;
  --all shows every row. --json passes through monitor-list --json unchanged.
EOF
        return 0
        ;;
      *) printf 'monitors: unknown flag: %s\n' "$1" >&2; return 2 ;;
    esac
    shift
  done
  # Reuse the picker's own `monitor-list` dispatch so we hit the same runtime
  # (compiled binary / bun / node launcher) and the same authoritative
  # projection as `xtmux monitor-list --json`. `--from-json` short-circuits
  # for tests.
  if [ "$json" = 1 ]; then
    if [ -n "$from_file" ]; then
      cat -- "$from_file"
      return $?
    fi
    # `exec` so stdout/stderr/exit propagate unaltered — this is a pure
    # passthrough over monitor-list --json.
    exec "$self" monitor-list --json
  fi
  if ! command -v jq >/dev/null 2>&1; then
    printf 'monitors: jq not found; falling back to `monitor-list`. install jq for the pretty view.\n' >&2
    "$self" monitor-list
    return $?
  fi
  local raw raw_err raw_rc
  if [ -n "$from_file" ]; then
    if ! raw="$(cat -- "$from_file" 2>/dev/null)"; then
      printf 'monitors: --from-json cannot read %s\n' "$from_file" >&2
      return 2
    fi
  else
    # Capture stderr and exit status separately so a backend failure surfaces
    # instead of masquerading as "no monitors" (Codex P2).
    raw_err="$(mktemp)"
    raw="$("$self" monitor-list --json 2>"$raw_err")" || raw_rc=$?
    raw_rc=${raw_rc:-0}
    if [ "$raw_rc" != 0 ]; then
      printf 'monitors: monitor-list failed (exit %s):\n' "$raw_rc" >&2
      cat "$raw_err" >&2
      rm -f "$raw_err"
      return "$raw_rc"
    fi
    rm -f "$raw_err"
  fi
  case "$raw" in ''|'[]') printf 'no monitors registered.\n'; return 0 ;; esac
  if [ "$show_all" = 0 ]; then
    local active_count
    active_count="$(printf '%s\n' "$raw" | jq -r '[.[] | select(.terminalStatus == null)] | length' 2>/dev/null || echo 0)"
    if [ "$active_count" = 0 ]; then
      printf 'no active monitors. add --all to see terminal rows.\n'
      return 0
    fi
  fi
  # Resolve session-name for target/requester on the fly. Names are best-effort
  # (a dead sid resolves to empty and we print the raw $sid). We build a
  # sid->name map from tmux once so we avoid a display-message call per row.
  local sidmap=''
  if command -v tmux >/dev/null 2>&1; then
    sidmap="$(tmux list-sessions -F '#{session_id}\t#{session_name}' 2>/dev/null || true)"
  fi
  local now_ms
  now_ms="$(date +%s%3N 2>/dev/null || printf '%s000' "$(date +%s)")"
  {
    printf 'STATE\tAGE\tTIMEOUT\tTARGET\tREQUESTER\tID\n'
    printf '%s\n' "$raw" | jq -r --arg all "$show_all" --arg now "$now_ms" --arg sidmap "$sidmap" '
      def fmt_dur(ms):
        (ms / 1000) as $s
        | if $s < 60 then "\($s|floor)s"
          elif $s < 3600 then "\(($s/60)|floor)m"
          elif $s < 86400 then "\(($s/3600)|floor)h"
          else "\(($s/86400)|floor)d" end;
      def name_of(sid):
        if sid == null or sid == "" then "-"
        else
          ($sidmap | split("\n")
           | map(select(length > 0) | split("\t") | {(.[0]): .[1]})
           | add // {}) as $m
          | ($m[sid] // sid)
        end;
      def target_label(row):
        (row.target // "-") as $t
        | (name_of($t)) as $tn
        | if row.paneId then "\($tn) (\(row.paneId))" else $tn end;
      def requester_label(row):
        if row.requesterSessionId == null then "-"
        else
          (name_of(row.requesterSessionId)) as $rn
          | if row.requesterPaneId then "\($rn) (\(row.requesterPaneId))" else $rn end
        end;
      def state_label(row):
        if row.terminalStatus != null then row.terminalStatus else (row.state // "?") end;
      def is_active(row): row.terminalStatus == null;
      map(select(($all == "1") or is_active(.)))
      | sort_by(-.startedAtMs)
      | .[]
      | [
          state_label(.),
          fmt_dur(($now|tonumber) - .startedAtMs),
          "\(fmt_dur(($now|tonumber) - .startedAtMs))/\(fmt_dur(.timeoutMs))",
          target_label(.),
          requester_label(.),
          (.monitorId // "?")
        ]
      | @tsv
    '
  } | awk -F '\t' '
    { for (i=1;i<=NF;i++) { if (length($i) > w[i]) w[i] = length($i); rows[NR,i] = $i }
      cols = NF; n = NR }
    END { for (r=1; r<=n; r++) {
            line = ""
            for (i=1; i<=cols; i++) {
              cell = rows[r,i]
              if (i < cols) line = line sprintf("%-*s  ", w[i], cell)
              else          line = line cell
            }
            print line
          } }
  '
}

handoff_default_file() {
  local target="${1:-target}" bead="${2:-bead}" safe
  safe="$(printf '%s-%s' "$target" "$bead" | tr -cs 'A-Za-z0-9._-' '-')"
  REPLY="${TMPDIR:-/tmp}/xtmux-handoff-${safe}.txt"
}

handoff_prompt_file_allowed() {
  local file="$1" real root
  case "$file" in /*) ;; *) return 1 ;; esac
  [ -f "$file" ] && [ -r "$file" ] || return 1
  real="$(realpath -e -- "$file" 2>/dev/null || readlink -f -- "$file" 2>/dev/null || true)"
  [ -n "$real" ] || return 1
  for root in "${TMPDIR:-/tmp}" "$PWD" "${XDG_STATE_HOME:-$HOME/.local/state}"; do
    root="$(realpath -m -- "$root" 2>/dev/null || printf '%s' "$root")"
    case "$real" in "$root"/*) return 0 ;; esac
  done
  return 1
}

# Readiness is a property of the AGENT INSTANCE, not of the pane.
#
# `log query` is a history query, so asking "does this pane have an agent.ready
# row?" answers yes for a pane whose PREVIOUS occupant readied and exited — and
# --wait-ready would then stop waiting and inject the pointer into a pane whose
# current agent has not finished initializing, which is precisely the failure
# readiness exists to prevent. Match the ready event against the pane's CURRENT
# @agent_instance_id (rotated on --new-instance by scripts/agent-state.sh).
#
# No instance id means no agent has claimed this pane at all: not ready, and never
# "ready by default".
handoff_ready_seen() {
  local pane="$1" out instance
  obs_available || return 1
  instance="$(tmux show-options -p -t "$pane" -qv @agent_instance_id 2>/dev/null || true)"
  [ -n "$instance" ] || return 1
  obs_runtime_argv
  out="$("${OBS_ARGV[@]}" log-query --type agent.ready --pane "$pane" --limit 50 --json 2>/dev/null || true)"
  printf '%s\n' "$out" | grep -F "\"instanceId\":\"$instance\"" >/dev/null 2>&1
}

handoff_wait_ready() {
  local target="$1" pane="$2" timeout="$3" json="$4" start now elapsed
  start="$(date +%s)"
  while :; do
    handoff_ready_seen "$pane" && return 0
    now="$(date +%s)"; elapsed=$(( now - start ))
    if [ "$timeout" -gt 0 ] && [ "$elapsed" -ge "$timeout" ]; then
      if [ "$json" = 1 ]; then
        json_error XTMUX_READY_TIMEOUT "handoff: agent.ready timeout target=$target pane=$pane elapsed=${elapsed}s" handoff
      else
        printf 'handoff: agent.ready timeout target=%s pane=%s elapsed=%ss\n' "$target" "$pane" "$elapsed" >&2
      fi
      return 124
    fi
    sleep 1
  done
}

handoff_v2() {
  local execute="$1" json="$2" target="$3" bead="$4" prompt_file="$5" wait_ready="$6" monitor="$7" handoff_key="$8" parent="$9" pane="${10}"; shift 10
  local target_session source_session monitor_id safe_key state create_out ready_timeout pointer
  handoff_prompt_file_allowed "$prompt_file" || {
    command_error "$json" XTMUX_PROMPT_FILE_REJECTED "handoff: prompt file must be readable existing file under local allowed path: $prompt_file" handoff 2
    return $?
  }
  current_tmux_session_id; source_session="$REPLY"
  resolve_to_session_id "$target" && target_session="$REPLY" || target_session=''
  # NOT a default. This used to substitute the literal string 'prompt-file' for a
  # missing --bead, which then landed in the durable handoff row AND in the journal
  # envelope's bead_id — a fabricated reference to a bead that does not exist,
  # indistinguishable downstream from a real one. A handoff whose contract nobody
  # can look up is not a handoff; the bead IS the contract, in both modes.
  [ -n "$bead" ] || { command_error "$json" XTMUX_INVALID_ARGUMENT 'handoff: --bead is required — the bead is the durable contract the target reads' handoff 2; return $?; }
  # Build and validate the pointer BEFORE anything durable is written.
  # handoff_prompt_file_allowed accepts a file under $PWD or XDG_STATE_HOME, but
  # safe_pointer_payload only accepts a payload referencing /tmp — so such a path
  # used to pass validation, create the durable handoff row, and only THEN have its
  # pointer rejected, leaving a handoff that claims a delegation nobody ever
  # attempted. Whatever we cannot deliver, we must not first record as delegated.
  pointer="leggi $prompt_file e seguilo. contratto durevole: bd show $bead. report finale nel bead."
  safe_pointer_payload "$pointer" >/dev/null 2>&1 || {
    command_error "$json" XTMUX_PROMPT_FILE_REJECTED "handoff: prompt file must live where a pointer may reference it (see safe-send-pointer rules): $prompt_file" handoff 2
    return $?
  }
  # Preflight target resolution and state before registering the durable handoff.
  # The actual send records a delivery_failed attempt if the target changes after
  # this check; failures before an attempt must not leave a created row behind.
  safe_send_pointer --dry-run "$target" "$pointer" >/dev/null 2>&1 || {
    command_error "$json" XTMUX_HANDOFF_DELIVERY_FAILED "handoff: pointer is not deliverable target=$target pane=$pane" handoff 1
    return $?
  }
  [ -n "$handoff_key" ] || handoff_key="ho-$(date +%s)-$$-${RANDOM}"
  safe_key="$(printf '%s' "$handoff_key" | tr -cs 'A-Za-z0-9._-' '-')"
  [ -n "$safe_key" ] || safe_key="ho-$(date +%s)-$$"
  monitor_id="hm-$safe_key"
  if [ "$execute" != 1 ]; then
    if [ "$json" = 1 ]; then
      printf '{"target":"%s","paneId":"%s","beadId":"%s","promptFile":"%s","handoffKey":"%s","monitorId":%s,"sent":false,"dryRun":true}\n' \
        "$(json_escape "$target")" "$(json_escape "$pane")" "$(json_escape "$bead")" "$(json_escape "$prompt_file")" "$(json_escape "$handoff_key")" \
        "$([ "$monitor" = 1 ] && printf '"%s"' "$(json_escape "$monitor_id")" || printf null)"
    else
      printf 'prompt-file\t%s\n' "$prompt_file"
      printf 'handoff-key\t%s\n' "$handoff_key"
      printf 'dry-run\tno durable writes or delivery\n'
    fi
    return 0
  fi
  obs_available || { command_error "$json" XTMUX_RUNTIME_UNAVAILABLE 'handoff: durable handoff requires V2 runtime' handoff 1; return $?; }
  obs_runtime_argv
  local create_args=(handoff create --id "$handoff_key" --key "$handoff_key" --target "$target" --target-pane "$pane" --bead "$bead" --prompt-file "$prompt_file")
  [ -n "$target_session" ] && create_args+=(--target-session "$target_session")
  [ -n "$source_session" ] && create_args+=(--source-session "$source_session")
  [ -n "$parent" ] && create_args+=(--parent-session "$parent")
  if [ "$monitor" = 1 ]; then
    create_args+=(--monitor-id "$monitor_id" --monitor-state waiting-ready --monitor-interval-ms 1000)
    [ "$wait_ready" -gt 0 ] && create_args+=(--monitor-timeout-ms "$((wait_ready * 1000))")
  fi
  # Keep the runtime's OWN structured error when it has one. Collapsing every
  # failure into XTMUX_HANDOFF_CREATE_FAILED throws away the only thing the caller
  # can act on: a reused idempotency key that names a different delegation
  # (XTMUX_HANDOFF_KEY_CONFLICT, exit 4) needs a new key, while a storage failure
  # needs a retry — and "durable registration failed" cannot tell them apart.
  local create_err
  create_err="$(mktemp)"
  create_out="$("${OBS_ARGV[@]}" "${create_args[@]}" 2>"$create_err")" || {
    local rc=$? err_body
    err_body="$(cat "$create_err" 2>/dev/null || true)"
    rm -f "$create_err"
    case "$err_body" in
      *'"code"'*) [ "$json" = 1 ] && printf '%s\n' "$err_body" >&2 || printf '%s\n' "$err_body" >&2 ;;
      *) if [ "$json" = 1 ]; then json_error XTMUX_HANDOFF_CREATE_FAILED 'handoff: durable registration failed' handoff; else printf '%s\n' "$err_body" >&2; fi ;;
    esac
    return "$rc"
  }
  rm -f "$create_err"
  if [ "$wait_ready" -gt 0 ]; then
    handoff_wait_ready "$target" "$pane" "$wait_ready" "$json" || {
      local ready_rc=$?
      if [ "$monitor" = 1 ]; then
        "${OBS_ARGV[@]}" monitor terminate --id "$monitor_id" --status timeout >/dev/null 2>&1 || true
      fi
      return "$ready_rc"
    }
  fi
  tmux set-option -p -t "$pane" -q @agent_bead "$bead" 2>/dev/null || true
  tmux set-option -p -t "$pane" -q @agent_prompt_file "$prompt_file" 2>/dev/null || true
  [ -n "$parent" ] && tmux set-option -p -t "$pane" -q @agent_parent_session "$parent" 2>/dev/null || true
  local delivery_rc=0
  set +e
  XTMUX_HANDOFF_ID="$handoff_key" safe_send_pointer --yes "$target" "$pointer" >/dev/null
  delivery_rc=$?
  set -e
  if [ "$delivery_rc" -ne 0 ]; then
    if [ "$json" = 1 ]; then
      json_error XTMUX_HANDOFF_DELIVERY_FAILED "handoff: pointer injection failed target=$target pane=$pane" handoff
    fi
    return "$delivery_rc"
  fi
  if [ "$json" = 1 ]; then
    printf '{"target":"%s","paneId":"%s","beadId":"%s","promptFile":"%s","handoffKey":"%s","monitorId":%s,"sent":true,"durable":true}\n' \
      "$(json_escape "$target")" "$(json_escape "$pane")" "$(json_escape "$bead")" "$(json_escape "$prompt_file")" "$(json_escape "$handoff_key")" \
      "$([ "$monitor" = 1 ] && printf '"%s"' "$(json_escape "$monitor_id")" || printf null)"
  fi
}

handoff() {
  local execute=0 json=0 target='' bead='' note='' file='' prompt_file='' wait_ready=0 monitor=0 handoff_key='' parent='' arg pane state bead_line pointer qtarget qpointer new_mode=0
  while [ "$#" -gt 0 ]; do
    arg="$1"; shift
    case "$arg" in
      --yes|--send) execute=1 ;;
      --dry-run) execute=0 ;;
      --json) json=1 ;;
      --target) [ "$#" -gt 0 ] || return 2; target="$1"; shift ;;
      --target=*) target="${arg#--target=}" ;;
      --bead) [ "$#" -gt 0 ] || return 2; bead="$1"; shift ;;
      --bead=*) bead="${arg#--bead=}" ;;
      --note) [ "$#" -gt 0 ] || return 2; note="$1"; shift ;;
      --note=*) note="${arg#--note=}" ;;
      --file) [ "$#" -gt 0 ] || return 2; file="$1"; shift ;;
      --file=*) file="${arg#--file=}" ;;
      --prompt-file) [ "$#" -gt 0 ] || return 2; prompt_file="$1"; shift; new_mode=1 ;;
      --prompt-file=*) prompt_file="${arg#--prompt-file=}"; new_mode=1 ;;
      --wait-ready) [ "$#" -gt 0 ] || return 2; parse_wait_duration "$1" || return 2; wait_ready="$REPLY"; new_mode=1; shift ;;
      --wait-ready=*) parse_wait_duration "${arg#--wait-ready=}" || return 2; wait_ready="$REPLY"; new_mode=1 ;;
      --monitor) monitor=1; new_mode=1 ;;
      --handoff-key) [ "$#" -gt 0 ] || return 2; handoff_key="$1"; new_mode=1; shift ;;
      --handoff-key=*) handoff_key="${arg#--handoff-key=}"; new_mode=1 ;;
      --parent) [ "$#" -gt 0 ] || return 2; parent="$1"; shift ;;
      --parent=*) parent="${arg#--parent=}" ;;
      -h|--help) return 2 ;;
      *) printf 'handoff: unknown arg: %s\n' "$arg" >&2; return 2 ;;
    esac
  done
  if [ "$new_mode" = 1 ]; then
    [ -n "$target" ] || { command_error "$json" XTMUX_INVALID_ARGUMENT 'usage: handoff --target <target> --prompt-file <path> [--wait-ready <dur>] [--monitor] [--yes]' handoff 2; return $?; }
    [ -n "$prompt_file" ] || { command_error "$json" XTMUX_INVALID_ARGUMENT 'handoff: --prompt-file required with readiness-aware flags' handoff 2; return $?; }
    resolve_tmux_pane "$target" || { command_error "$json" XTMUX_TARGET_NOT_FOUND "handoff: target not found: $target" handoff 1; return $?; }
    pane="$REPLY"
    handoff_v2 "$execute" "$json" "$target" "$bead" "$prompt_file" "$wait_ready" "$monitor" "$handoff_key" "$parent" "$pane"
    return $?
  fi
  [ -n "$target" ] && [ -n "$bead" ] || { command_error "$json" XTMUX_INVALID_ARGUMENT 'usage: handoff --target <pane/session> --bead <id> [--note text] [--file /tmp/x] [--yes]' handoff 2; return $?; }
  resolve_tmux_pane "$target" || { command_error "$json" XTMUX_TARGET_NOT_FOUND "handoff: target not found: $target" handoff 1; return $?; }
  pane="$REPLY"
  observe_agent_state "$pane"; state="$REPLY"
  if agent_state_is_working "$state"; then
    if [ "$json" = 1 ]; then
      json_error XTMUX_TARGET_WORKING "handoff: refused target=$target pane=$pane state=$state" handoff
    else
      printf 'handoff: refused target=%s pane=%s state=%s\n' "$target" "$pane" "$state" >&2
    fi
    return 75
  fi
  if command -v bd >/dev/null 2>&1; then
    bead_line="$(bd show "$bead" 2>/dev/null | head -1 || true)"
    [ -n "$bead_line" ] || { command_error "$json" XTMUX_BEAD_NOT_FOUND "handoff: bead not found: $bead" handoff 1; return $?; }
  else
    bead_line="$bead"
  fi
  [ -n "$file" ] || { handoff_default_file "$pane" "$bead"; file="$REPLY"; }
  mkdir -p "$(dirname "$file")" 2>/dev/null || true
  {
    printf 'bead: %s\n' "$bead"
    printf 'contract: bd show %s\n' "$bead"
    printf 'summary: %s\n' "$bead_line"
    [ -n "$parent" ] && printf 'parent-session: %s\n' "$parent"
    [ -n "$note" ] && { printf '\nmeta-protocol:\n'; printf '%s\n' "$note"; }
    printf '\nexpected-report:\n'
    printf '%s\n' '- read the bead as the durable task contract'
    printf '%s\n' '- update bead notes with findings/results'
    printf '%s\n' '- do not send multiline payloads over tmux; use this file as context'
  } > "$file"
  pointer="leggi $file e seguilo. contratto durevole: bd show $bead. report finale nel bead."
  safe_pointer_payload "$pointer" || return 2
  printf -v qtarget '%q' "$target"
  printf -v qpointer '%q' "$pointer"
  log_event handoff.created target="$target" pane="$pane" bead="$bead" prompt_file="$file" parent="$parent" state="$state"
  if [ "$json" != 1 ]; then
    printf 'prompt-file\t%s\n' "$file"
    printf 'bead\t%s\n' "$bead"
    printf 'pointer\t%s\n' "$pointer"
    printf 'command\t%s safe-send-pointer --yes %s %s\n' "$self" "$qtarget" "$qpointer"
  fi
  if [ "$execute" = 1 ]; then
    tmux set-option -p -t "$pane" -q @agent_bead "$bead" 2>/dev/null || true
    tmux set-option -p -t "$pane" -q @agent_prompt_file "$file" 2>/dev/null || true
    [ -n "$parent" ] && tmux set-option -p -t "$pane" -q @agent_parent_session "$parent" 2>/dev/null || true
    [ -n "$bead_line" ] && tmux set-option -p -t "$pane" -q @agent_task "$(tsv_clean "$bead_line")" 2>/dev/null || true
    log_event handoff.sent target="$target" pane="$pane" bead="$bead" prompt_file="$file" parent="$parent"
    safe_send_pointer --yes "$target" "$pointer" >/dev/null
  fi
  if [ "$json" = 1 ]; then
    printf '{"target":"%s","paneId":"%s","beadId":"%s","promptFile":"%s","sent":%s,"createdAtMs":%s}\n' \
      "$(json_escape "$target")" "$(json_escape "$pane")" "$(json_escape "$bead")" "$(json_escape "$file")" \
      "$([ "$execute" = 1 ] && printf true || printf false)" "$(date +%s%3N)"
  fi
}

safe_pointer_payload() {
  local payload="${1:-}"
  local force_freeform="${2:-0}"
  [ -n "$payload" ] || { printf 'safe-send-pointer: empty payload\n' >&2; return 1; }
  case "$payload" in *$'\n'*|*$'\r'*) printf 'safe-send-pointer: multiline payload rejected\n' >&2; return 1 ;; esac
  case "$payload" in *'`'*|*'$('*) printf 'safe-send-pointer: command substitution/backticks rejected\n' >&2; return 1 ;; esac
  if [ "$force_freeform" = 1 ]; then
    return 0                                # multi-line + shell-substitution guards still enforced above
  fi
  case "$payload" in
    /*) return 0 ;;                         # slash command, e.g. /compact
    *'/tmp/'*) return 0 ;;                  # pointer to prompt-file
    *) printf 'safe-send-pointer: payload must be a slash command or reference /tmp/<file> (use --force-freeform to bypass)\n' >&2; return 1 ;;
  esac
}

# Return 0 if the given pane is running a Claude Code process, 1 otherwise.
# Claude Code deterministically consumes the first Enter as paste-detection;
# other agents (pi, codex, raw shell) do not. Auto-detected here so
# safe-send-pointer / handoff callers do not need to know pane type.
# Is `claude` running anywhere in this process subtree? Bounded depth, first match
# wins — we are answering a yes/no question, not building an inventory.
pane_has_claude_descendant() {
  local pid="${1:-}" depth="${2:-0}" child comm
  [ -n "$pid" ] || return 1
  [ "$depth" -gt 0 ] || return 1
  for child in $(pgrep -P "$pid" 2>/dev/null || true); do
    comm="$(ps -o comm= -p "$child" 2>/dev/null || true)"
    case "${comm##*/}" in
      claude|claude-*) return 0 ;;
    esac
    pane_has_claude_descendant "$child" "$((depth - 1))" && return 0
  done
  return 1
}

pane_is_claude_code() {
  local pane="${1:-}" cmd='' pid=''
  [ -n "$pane" ] || return 1
  cmd="$(tmux display-message -p -t "$pane" '#{pane_current_command}' 2>/dev/null || true)"
  case "$cmd" in
    claude|claude-*|*/claude|*/claude-*) return 0 ;;
  esac
  # pane_current_command names only the FOREGROUND process. A pane launched with
  # `xt claude` runs a node wrapper (`node .../bin/xt claude`) which spawns claude
  # underneath it, so the pane reports `node` and this check used to miss — the
  # pane got double_enter=0, Claude Code's paste-detection ate the single Enter,
  # and the pointer sat in the input box, never submitted, while the sender was
  # told `sent`. A silent non-delivery is the worst failure this command can have,
  # so when the command name is inconclusive, look for claude in the subtree.
  #
  # Depth 3 covers the shapes we have: `claude` direct (1), `xt claude` wrapper
  # (2), and one extra level of shell nesting.
  pid="$(tmux display-message -p -t "$pane" '#{pane_pid}' 2>/dev/null || true)"
  pane_has_claude_descendant "$pid" 3
}

safe_send_pointer() {
  local execute=0 double_enter=-1 force_freeform=0 json=0 target='' payload='' reply_to='' fulfilment_json='' arg pane state qpane qpayload cmd
  while [ "$#" -gt 0 ]; do
    arg="$1"; shift
    case "$arg" in
      --yes|--send) execute=1 ;;
      --dry-run) execute=0 ;;
      --double-enter) double_enter=1 ;;
      --no-double-enter) double_enter=0 ;;
      --force-freeform) force_freeform=1 ;;
      --reply-to) [ "$#" -gt 0 ] || return 2; reply_to="$1"; shift ;;
      --reply-to=*) reply_to="${arg#--reply-to=}" ;;
      --json) json=1 ;;
      -h|--help) return 2 ;;
      --*) printf 'safe-send-pointer: unknown option: %s\n' "$arg" >&2; return 2 ;;
      *)
        if [ -z "$target" ]; then
          target="$arg"
        else
          payload+="${payload:+ }$arg"
        fi
        ;;
    esac
  done
  [ -n "$target" ] && [ -n "$payload" ] || { command_error "$json" XTMUX_INVALID_ARGUMENT 'usage: safe-send-pointer [--yes] [--double-enter|--no-double-enter] [--force-freeform] [--reply-to <messageKey>] <target> <slash-command|/tmp pointer>' safe-send-pointer 2; return $?; }
  if [ -n "$reply_to" ]; then
    obs_v2_mode
    [ "$REPLY" = on ] || { command_error "$json" XTMUX_JSON_REQUIRES_V2 'safe-send-pointer --reply-to requires XTMUX_OBS_V2=1' safe-send-pointer 2; return $?; }
  fi
  if [ "$json" = 1 ]; then
    safe_pointer_payload "$payload" "$force_freeform" 2>/dev/null || { command_error 1 XTMUX_POINTER_REJECTED 'safe-send-pointer: payload rejected' safe-send-pointer 2; return $?; }
  else
    safe_pointer_payload "$payload" "$force_freeform" || return 2
  fi
  resolve_tmux_pane "$target" || { command_error "$json" XTMUX_TARGET_NOT_FOUND "safe-send-pointer: target not found: $target" safe-send-pointer 1; return $?; }
  pane="$REPLY"
  observe_agent_state "$pane"; state="$REPLY"
  if agent_state_is_working "$state"; then
    if [ "$json" = 1 ]; then
      json_error XTMUX_TARGET_WORKING "safe-send-pointer: refused target=$target pane=$pane state=$state" safe-send-pointer
    else
      printf 'safe-send-pointer: refused target=%s pane=%s state=%s\n' "$target" "$pane" "$state" >&2
    fi
    return 75
  fi

  # Auto-double-Enter for Claude Code targets unless the caller explicitly opted out.
  # Codex/pi/raw-shell panes never get the auto second Enter.
  if [ "$double_enter" = -1 ]; then
    if pane_is_claude_code "$pane"; then double_enter=1; else double_enter=0; fi
  fi

  # --force-freeform without --yes prints a confirmation banner so the operator sees
  # exactly what is being bypassed before they re-run with --yes.
  if [ "$force_freeform" = 1 ] && [ "$execute" != 1 ] && [ "$json" != 1 ]; then
    printf 'safe-send-pointer: --force-freeform bypasses the slash/tmp payload check.\n'
    printf '  payload guards STILL enforced: no newlines, no `...`, no $(...).\n'
    printf '  Re-run with --yes to send. Target=%s state=%s double_enter=%s\n' "$target" "${state:-unknown}" "$double_enter"
  fi

  printf -v qpane '%q' "$pane"
  printf -v qpayload '%q' "$payload"
  if [ "$json" != 1 ]; then
    printf 'tmux send-keys -t %s %s Enter\n' "$qpane" "$qpayload"
    if [ "$double_enter" = 1 ]; then
      printf '# followed by second Enter after 2s (Claude Code paste-detection auto-double-Enter)\n'
    fi
  fi
  if [ "$execute" = 1 ]; then
    local send_rc=0 second_rc=0
    set +e
    tmux send-keys -t "$pane" "$payload" Enter
    send_rc=$?
    if [ "$send_rc" = 0 ] && [ "$double_enter" = 1 ]; then
      sleep 2
      tmux send-keys -t "$pane" Enter
      second_rc=$?
      [ "$second_rc" = 0 ] || send_rc="$second_rc"
    fi
    set -e
    current_tmux_session_id; _from_session="$REPLY"
    obs_v2_mode; local send_mode="$REPLY"
    local target_sid='' summary
    resolve_to_session_id "$target" && target_sid="$REPLY" || target_sid="$target"
    summary="$(printf '%s' "$payload" | head -c 80)"
    if [ -n "${XTMUX_HANDOFF_ID:-}" ] && [ "$send_mode" = 'on' ]; then
      obs_runtime_argv
      safe_pointer_obs_call handoff attempt --id "$XTMUX_HANDOFF_ID" --summary "$summary" \
        --succeeded "$([ "$send_rc" = 0 ] && printf true || printf false)" \
        $([ "$send_rc" = 0 ] || printf '%s' '--failure-code target_gone') >/dev/null || true
    elif [ "$send_mode" = 'on' ]; then
      # V2: pane pointer is a DELIVERY attempt, not a durable message.
      obs_runtime_argv
      safe_pointer_obs_call delivery-record \
        --kind pane_pointer --source-session "${_from_session:-unknown}" \
        --target-session "$target_sid" --target-pane "$pane" --summary "$summary" \
        --succeeded "$([ "$send_rc" = 0 ] && printf true || printf false)" >/dev/null || true
    else
      log_event message.sent via=safe-send-pointer from="${_from_session:-unknown}" to="$target" pane="$pane" text="$payload" state="${state:-unknown}" double_enter="$double_enter" force_freeform="$force_freeform"
    fi
    if [ "$send_rc" != 0 ]; then
      command_error "$json" XTMUX_DELIVERY_FAILED 'safe-send-pointer: tmux injection failed; reply not fulfilled' safe-send-pointer 1
      return $?
    fi
    if [ -n "$reply_to" ]; then
      obs_runtime_argv
      local reply_args=(message-reply --in-reply-to "$reply_to" --text "$payload")
      [ "$json" = 1 ] && reply_args+=(--json)
      fulfilment_json="$(safe_pointer_obs_call "${reply_args[@]}")" || return $?
      [ "$json" = 1 ] || printf '%s' "$fulfilment_json"
    fi
    [ "$json" = 1 ] || printf 'sent target=%s pane=%s state=%s double_enter=%s\n' "$target" "$pane" "${state:-unknown}" "$double_enter"
  fi
  if [ "$json" = 1 ]; then
    if [ -n "$reply_to" ] && [ "$execute" = 1 ]; then
      printf '{"injection":{"target":"%s","paneId":"%s","state":"%s","doubleEnter":%s,"sent":true},"fulfilment":%s}\n' \
        "$(json_escape "$target")" "$(json_escape "$pane")" "$(json_escape "${state:-unknown}")" \
        "$([ "$double_enter" = 1 ] && printf true || printf false)" "$fulfilment_json"
    else
      printf '{"target":"%s","paneId":"%s","state":"%s","doubleEnter":%s,"sent":%s}\n' \
        "$(json_escape "$target")" "$(json_escape "$pane")" "$(json_escape "${state:-unknown}")" \
        "$([ "$double_enter" = 1 ] && printf true || printf false)" "$([ "$execute" = 1 ] && printf true || printf false)"
    fi
  fi
}

preview_field() {
  local label="$1" value="${2:-}"
  [ -n "$value" ] || return 0
  printf '  %-9s %s\n' "$label" "$value"
}

preview_session_row() {
  local sid="$1" name="$2" pane_path root root_name hdr attached window_count panes_raw pane_count
  local line window_index window_name pane_id pane_index pane_active pane_cmd pane_row_path pane_width pane_height pane_left pane_top pane_state pane_pid
  local meta_bead meta_task meta_prompt meta_parent meta_last rank best=4 best_line='' session_state bead sp_view_state
  pane_path="$(tmux display-message -p -t "$sid" '#{pane_current_path}' 2>/dev/null || true)"
  pane_path="${pane_path:-$HOME}"
  hdr="$(tmux display-message -p -t "$sid" $'#{session_attached}\t#{session_windows}' 2>/dev/null || true)"
  IFS=$'\t' read -r attached window_count <<< "$hdr"
  panes_raw="$(tmux list-panes -s -t "$sid" -F $'#{window_index}\t#{window_name}\t#{pane_id}\t#{pane_index}\t#{pane_active}\t#{pane_current_command}\t#{pane_current_path}\t#{pane_width}\t#{pane_height}\t#{pane_left}\t#{pane_top}\t#{?@agent_state,#{@agent_state},-}\t#{pane_pid}\t#{?@agent_bead,#{@agent_bead},-}\t#{?@agent_task,#{@agent_task},-}\t#{?@agent_prompt_file,#{@agent_prompt_file},-}\t#{?@agent_parent_session,#{@agent_parent_session},-}\t#{?@agent_last_transition,#{@agent_last_transition},-}' 2>/dev/null || true)"
  pane_count=0
  while IFS= read -r line; do
    IFS=$'\t' read -r window_index window_name pane_id pane_index pane_active pane_cmd pane_row_path pane_width pane_height pane_left pane_top pane_state pane_pid meta_bead meta_task meta_prompt meta_parent meta_last <<< "$line"
    [ -n "$pane_id" ] || continue
    pane_count=$((pane_count + 1))
    normalize_agent_state "$pane_id" "$pane_state" "$pane_cmd" "$meta_last"; pane_state="$REPLY"
    agent_rank "$pane_state"; rank="$REPLY"
    if [ -z "$best_line" ] || [ "$rank" -lt "$best" ]; then best="$rank"; best_line="$line"; fi
  done <<< "$panes_raw"
  attn_state_name "$best"; session_state="$REPLY"
  git_root_for_path "$pane_path"; root="$REPLY"; root_name="${root:+${root##*/}}"

  line="$best_line"
  IFS=$'\t' read -r window_index window_name pane_id pane_index pane_active pane_cmd pane_row_path pane_width pane_height pane_left pane_top pane_state pane_pid meta_bead meta_task meta_prompt meta_parent meta_last <<< "$line"
  agent_meta_value "$meta_bead"; meta_bead="$REPLY"
  agent_meta_value "$meta_task"; meta_task="$REPLY"
  agent_meta_value "$meta_prompt"; meta_prompt="$REPLY"
  agent_meta_value "$meta_parent"; meta_parent="$REPLY"
  agent_meta_value "$meta_last"; meta_last="$REPLY"
  bead="$meta_bead"
  if [ -z "$bead" ]; then derive_bead_id "$name" "$pane_path" "$root"; bead="$REPLY"; fi

  printf 'SESSION\n'
  preview_field name "$name"
  preview_field state "$session_state"
  preview_field repo "$root_name"
  preview_field windows "${window_count:-?}"
  preview_field panes "$pane_count"
  preview_field attached "${attached:-0}"

  if [ -n "$pane_id" ]; then
    printf '\nAGENT\n'
    preview_field pane "$pane_id"
    preview_field window "$window_index:$window_name.$pane_index"
    preview_field geometry "${pane_width}x${pane_height}+${pane_left}+${pane_top}"
    preview_field runtime "${pane_cmd:-shell}"
    preview_field bead "$bead"
    preview_field task "$meta_task"
    preview_field prompt "$meta_prompt"
    preview_field parent "$meta_parent"
    preview_field last "$meta_last"
    sp_meta "$name" "$pane_pid"
    if [ -n "$sp_role" ]; then
      sp_view_state="${sp_state:-${sp_stale:+stale}}"
      preview_field specialist "$sp_role"
      preview_field sp-state "${sp_view_state:-unknown}"
    fi
    bead_preview_summary "$pane_path" "$bead"
  fi

  printf '\nWORKTREE\n'
  preview_field path "$pane_path"
  if [ -n "$root" ]; then
    printf '\nGIT\n'
    git_worktree_preview "$root"
  fi

  printf '\n──────────────────────────────────\n'
  while IFS=$'\t' read -r window_index window_name pane_id pane_index pane_active pane_cmd pane_row_path pane_width pane_height pane_left pane_top pane_state pane_pid meta_bead meta_task meta_prompt meta_parent meta_last; do
    [ -n "$pane_id" ] || continue
    printf 'PANE %s  %s:%s.%s\n' "$pane_id" "$window_index" "$window_name" "$pane_index"
    capture_pane_safe "$pane_id" -8
    printf '\n'
  done <<< "$panes_raw"
}

preview_pane_row() {
  local sid="$1" name="$2" target_pane="$3" pinfo pane_path pane_cmd window_line pane_state pane_pid pane_width pane_height pane_left pane_top
  local meta_bead meta_task meta_prompt meta_parent meta_last root root_name attached bead sp_view_state
  pinfo="$(tmux display-message -p -t "$target_pane" $'#{pane_current_path}\t#{pane_current_command}\t#I:#W\t#{pane_width}\t#{pane_height}\t#{pane_left}\t#{pane_top}\t#{?@agent_state,#{@agent_state},-}\t#{pane_pid}\t#{?@agent_bead,#{@agent_bead},-}\t#{?@agent_task,#{@agent_task},-}\t#{?@agent_prompt_file,#{@agent_prompt_file},-}\t#{?@agent_parent_session,#{@agent_parent_session},-}\t#{?@agent_last_transition,#{@agent_last_transition},-}' 2>/dev/null || true)"
  IFS=$'\t' read -r pane_path pane_cmd window_line pane_width pane_height pane_left pane_top pane_state pane_pid meta_bead meta_task meta_prompt meta_parent meta_last <<< "$pinfo"
  pane_path="${pane_path:-$HOME}"
  normalize_agent_state "$target_pane" "$pane_state" "$pane_cmd" "$meta_last"; pane_state="$REPLY"
  git_root_for_path "$pane_path"; root="$REPLY"; root_name="${root:+${root##*/}}"
  attached="$(tmux display-message -p -t "$sid" '#{session_attached}' 2>/dev/null || true)"
  agent_meta_value "$meta_bead"; meta_bead="$REPLY"
  agent_meta_value "$meta_task"; meta_task="$REPLY"
  agent_meta_value "$meta_prompt"; meta_prompt="$REPLY"
  agent_meta_value "$meta_parent"; meta_parent="$REPLY"
  agent_meta_value "$meta_last"; meta_last="$REPLY"
  bead="$meta_bead"
  if [ -z "$bead" ]; then derive_bead_id "$name" "$pane_path" "$root"; bead="$REPLY"; fi

  printf 'SESSION\n'
  preview_field name "$name"
  preview_field repo "$root_name"
  preview_field attached "${attached:-0}"

  printf '\nAGENT\n'
  preview_field pane "$target_pane"
  preview_field window "$window_line"
  preview_field geometry "${pane_width}x${pane_height}+${pane_left}+${pane_top}"
  preview_field runtime "${pane_cmd:-shell}"
  preview_field state "$pane_state"
  preview_field bead "$bead"
  preview_field task "$meta_task"
  preview_field prompt "$meta_prompt"
  preview_field parent "$meta_parent"
  preview_field last "$meta_last"
  sp_meta "$name" "$pane_pid"
  if [ -n "$sp_role" ]; then
    sp_view_state="${sp_state:-${sp_stale:+stale}}"
    preview_field specialist "$sp_role"
    preview_field sp-state "${sp_view_state:-unknown}"
  fi
  bead_preview_summary "$pane_path" "$bead"

  printf '\nWORKTREE\n'
  preview_field path "$pane_path"
  if [ -n "$root" ]; then
    printf '\nGIT\n'
    git_worktree_preview "$root"
  fi
  printf '\n──────────────────────────────────\n'
  capture_pane_safe "$target_pane" -48
}

preview_row() {
  local type="${1:-}"
  local sid="${2:-}"
  local name="${3:-}"
  local target="${4:-}"

  if [ "$type" = 'header' ]; then
    printf 'specialists (sp-*)\n\nreal tmux sessions from specialists are grouped here so normal interactive sessions stay at the top.\n'
    return 0
  fi
  [ -n "$sid" ] || return 0
  case "$type" in
    pane) preview_pane_row "$sid" "$name" "$target" ;;
    *) preview_session_row "$sid" "$name" ;;
  esac
}

open_popup_client() {
  local type="$1"
  local sid="$2"
  local target="$3"

  if [ "$type" = 'header' ] || [ -z "$sid" ]; then
    return 0
  fi

  if [ "$type" = 'pane' ] && [ -n "$target" ]; then
    exec env -u TMUX tmux attach-session -t "$sid" \; select-window -t "$target" \; select-pane -t "$target"
  fi

  exec env -u TMUX tmux attach-session -t "$sid"
}

jump_to_target() {
  local type="$1"
  local sid="$2"
  local target="$3"

  if [ "$type" = 'header' ] || [ -z "$sid" ]; then
    return 0
  fi

  if [ "$type" = 'pane' ] && [ -n "$target" ]; then
    exec tmux switch-client -t "$sid" \; select-window -t "$target" \; select-pane -t "$target"
  fi

  exec tmux switch-client -t "$sid"
}

kill_confirm() {
  local sid="${1:-}"
  local answer="${2:-}"

  [ -n "$sid" ] || return 1
  case "$answer" in
    y|Y|yes|YES|Yes)
      tmux kill-session -t "$sid"
      tmux display-message "tmux-picker: sessione uccisa $sid" 2>/dev/null || true
      ;;
    *)
      tmux display-message "tmux-picker: kill annullato" 2>/dev/null || true
      ;;
  esac
}

bulk_kill_confirm() {
  local answer="${1:-}" sid killed=0
  shift || true

  case "$answer" in
    y|Y|yes|YES|Yes) ;;
    *) tmux display-message "tmux-picker: bulk kill annullato" 2>/dev/null || true; return 0 ;;
  esac

  for sid in "$@"; do
    [ -n "$sid" ] || continue
    tmux kill-session -t "$sid" 2>/dev/null && killed=$((killed + 1))
  done
  tmux display-message "tmux-picker: sessioni uccise $killed" 2>/dev/null || true
}

bulk_kill() {
  local tok parsed type sid pane i panes=0
  local -a sessions=() pane_targets=() confirm_cmd=()

  # Validate the complete selection before any mutation. One malformed or stale
  # token rejects the request instead of producing a partial destructive action.
  for tok in "$@"; do
    parse_nav_token "$tok" || return 1
    parsed="$REPLY"
    IFS=$'\t' read -r type sid pane <<< "$parsed"
    [ "$sid" = - ] && sid=''
    case "$type" in
      session)
        tmux has-session -t "$sid" 2>/dev/null || return 1
        sessions+=("$sid")
        ;;
      pane)
        resolve_nav_pane_session "$sid" "$pane" || return 1
        pane_targets+=("$pane")
        ;;
    esac
  done

  for pane in "${pane_targets[@]}"; do
    tmux kill-pane -t "$pane" 2>/dev/null && panes=$((panes + 1))
  done
  if [ "${#sessions[@]}" -gt 0 ]; then
    # confirm-before executes tmux commands directly. Session IDs never cross a
    # shell or command-prompt substitution boundary.
    confirm_cmd=(confirm-before -p "kill ${#sessions[@]} session(s)? [y/N]")
    for ((i = 0; i < ${#sessions[@]}; i++)); do
      confirm_cmd+=(kill-session -t "${sessions[$i]}")
      [ "$i" -eq $(( ${#sessions[@]} - 1 )) ] || confirm_cmd+=(';')
    done
    tmux "${confirm_cmd[@]}"
  elif [ "$panes" -gt 0 ]; then
    tmux display-message "tmux-picker: pane uccisi $panes" 2>/dev/null || true
  fi
}

# bulk_kill_targets adapts classic hidden target field 4 to strict tokens.
# Rendered display text never enters this command.
bulk_kill_targets() {
  local target
  local -a tokens=()
  for target in "$@"; do
    if [[ "$target" =~ ^\$[0-9]+$ ]]; then
      tokens+=("s:$target")
    elif [[ "$target" =~ ^%[0-9]+$ ]]; then
      tokens+=("p:$target")
    else
      return 1
    fi
  done
  bulk_kill "${tokens[@]}"
}

kill_target() {
  local type="$1"
  local sid="$2"
  local target="$3"
  local sname

  if [ "$type" = 'pane' ] && [ -n "$target" ]; then
    tmux kill-pane -t "$target"
    return 0
  fi

  [ -n "$sid" ] || return 1
  sname="$(tmux display-message -p -t "$sid" '#S' 2>/dev/null || printf '%s' "$sid")"
  tmux confirm-before -p "kill session ${sname:-$sid}? [y/N]" kill-session -t "$sid"
}

# rename_target / rename_apply were called by the dispatcher and by the Alt-R
# fzf binding but never existed: both exited 127 ("command not found"), so the
# advertised inline rename has never worked. The contract tests for them failed
# on every run, in a subshell that swallowed the count (xtmux-d0a.19).
#
# rename_target prompts; rename_apply performs. Splitting them is what lets the
# tmux command-prompt hand the typed name back through `run-shell`.
rename_apply() {
  local type="${1:-}" handle="${2:-}" name="${3:-}"

  [ -n "$type" ] && [ -n "$handle" ] || return 1
  # An empty name is a cancelled prompt, not a request to blank the name.
  if [ -z "$name" ]; then
    tmux display-message 'tmux-picker: rename annullato' 2>/dev/null || true
    return 0
  fi

  case "$type" in
    session) tmux rename-session -t "$handle" "$name" ;;
    # a pane row renames the window that holds it — panes have no name of their own
    pane)    tmux rename-window -t "$handle" "$name" ;;
    *)       return 1 ;;
  esac
}

# The tmux command that command-prompt runs with %1 replaced by the typed name.
# Split out from rename_target so it can be tested without an attached client.
#
# It renames with tmux's OWN commands and never reaches /bin/sh. The obvious
# spelling routes the name through `run-shell '... rename-apply %1'`, and that is
# a free-text field going through an unquoted shell expansion: tmux substitutes
# the text, then sh word-splits it, so "new sprint board" arrives as "new" and a
# name containing `;` or `$(...)` is EXECUTED. Quoting %1 for sh would only move
# the hole (an apostrophe in the name reopens it). With no shell in the path,
# tmux performs no command substitution and the name is inert text.
#
# %1 is single-quoted at the tmux parse level so spaces stay in one argument.
# A typed apostrophe makes tmux fail to parse — it renames nothing and reports a
# parse error. That is a safe failure, not an executed one.
rename_prompt_command() {
  local type="${1:-}" handle="${2:-}"
  [ -n "$handle" ] || return 1
  case "$type" in
    # a pane row renames the window that holds it
    pane)    printf "rename-window -t '%s' '%%1'" "$handle" ;;
    session) printf "rename-session -t '%s' '%%1'" "$handle" ;;
    *) return 1 ;;
  esac
}

prompt_line() {
  local prompt="$1" initial="${2:-}" value
  [ -r /dev/tty ] || return 1
  IFS= read -e -i "$initial" -p "$prompt" value < /dev/tty > /dev/tty || return 1
  REPLY="$value"
}

rename_target() {
  local type="${1:-}" sid="${2:-}" target="${3:-}" handle current
  case "$type" in
    pane) handle="$target"; current="$(tmux display-message -p -t "$target" '#W' 2>/dev/null || true)" ;;
    session) handle="$sid"; current="$(tmux display-message -p -t "$sid" '#S' 2>/dev/null || true)" ;;
    *) return 1 ;;
  esac
  [ -n "$handle" ] || return 1
  prompt_line "rename $type: " "$current" || return 0
  rename_apply "$type" "$handle" "$REPLY"
}

# act_on_target <type> <sid> <target> <action>
# act on a pane from the list without attaching. no-op on session rows (only
# pane rows carry a usable target). cross-session safe: send-keys -t <pane>.
# actions:
#   approve   -> send 'y Enter'         (yes to a waiting agent permission)
#   interrupt -> send 'C-c'             (cancel the current turn)
#   message   -> prompt the operator for a one-line message, send it + Enter
act_on_target() {
  local type="$1"
  local sid="$2"
  local target="$3"
  local action="$4"
  local toast

  # session rows have no pane target to act on. this guard keeps the binds safe
  # when the highlight lands on a session line.
  if [ "$type" != 'pane' ] || [ -z "$target" ]; then
    tmux display-message "tmux-picker: nessun pane su cui agire (riga sessione)"
    return 0
  fi

  case "$action" in
    approve)
      tmux send-keys -t "$target" 'y' Enter
      toast="approvato $target"
      ;;
    interrupt)
      tmux send-keys -t "$target" C-c
      toast="interrotto $target"
      ;;
    message)
      prompt_line 'invia: ' '' || return 0
      tmux send-keys -t "$target" -l -- "$REPLY"
      tmux send-keys -t "$target" Enter
      return 0
      ;;
    *)
      tmux display-message "tmux-picker: azione sconosciuta: $action"
      return 1
      ;;
  esac

  [ -n "$toast" ] && tmux display-message "tmux-picker: $toast"
}

if json_requested "${@:2}"; then
  json_request_preflight "${1:-}" "${2:-}" || exit $?
  case "${1:-}" in
    message-status|unread-count)
      _json_args=("$1")
      shift
      for _json_arg in "$@"; do [ "$_json_arg" = '--json' ] || _json_args+=("$_json_arg"); done
      set -- "${_json_args[@]}"
      ;;
  esac
fi

case "${1:-}" in
  list)
    # Output cache removed (xtmux-rib.17): it froze agent-derived sort/badges
    # for the whole TTL. Only the git half is cached (in build_list); the list
    # is always rendered fresh so @agent_state changes are immediate.
    shift
    # xtmux-rib.12: accept mode as optional second arg (for CLI/test), else
    # read from the persisted state file (for reloads from inside fzf).
    if [ -n "${2:-}" ]; then
      _list_mode="$2"
    else
      read_list_mode; _list_mode="$REPLY"
    fi
    build_list "${1:-all}" "$_list_mode"
    exit 0
    ;;
  list-nav)
    # NAV-1 private transport: same inventory/filter/sort as `list`, emitted
    # as six-field NUL-delimited records (type/sid/name/target/token/display)
    # for the interactive fzf. Public `list` stays five-field newline TSV.
    shift
    if [ -n "${2:-}" ]; then
      _list_mode="$2"
    else
      read_list_mode; _list_mode="$REPLY"
    fi
    build_list "${1:-all}" "$_list_mode" nav multi
    exit 0
    ;;
  list-nav-single)
    # NAV-2 one-line fallback: same records and tokens as list-nav, but every
    # card is collapsed to one bounded line (fzf_multiline_probe=off).
    shift
    if [ -n "${2:-}" ]; then
      _list_mode="$2"
    else
      read_list_mode; _list_mode="$REPLY"
    fi
    build_list "${1:-all}" "$_list_mode" nav single
    exit 0
    ;;
  list-active)
    # richer filters (xtmux-rib.11): rebuild the list applying the active
    # content filter and the current sessions-only/expanded mode (xtmux-rib.12).
    shift
    picker_state_read filter || true; _spec="$REPLY"
    read_list_mode
    build_list "$_spec" "$REPLY"
    exit 0
    ;;
  list-active-nav)
    shift
    picker_state_read filter || true; _spec="$REPLY"
    read_list_mode
    build_list "$_spec" "$REPLY" nav multi
    exit 0
    ;;
  list-active-nav-single)
    shift
    picker_state_read filter || true; _spec="$REPLY"
    read_list_mode
    build_list "$_spec" "$REPLY" nav single
    exit 0
    ;;
  nav-go)
    # fzf Enter binding: act on the hidden action token {5} directly.
    shift
    nav_go "${1:-}"
    exit $?
    ;;
  nav-act)
    # NAV-2 single-row action dispatcher: the ONLY inputs are the hidden
    # action token {5} and a fixed action literal from the bind. Display text
    # never crosses the command line.
    shift
    nav_act "${1:-}" "${2:-}"
    exit $?
    ;;
  nav-border-label)
    shift
    nav_border_label
    exit 0
    ;;
  nav-key-help)
    shift
    nav_key_help
    exit 0
    ;;
  nav)
    # xtmux-rib.23/.25/.24: operator navigation family. Bare `nav` opens the
    # nav launcher (drawer; XTMUX_NAV_LAYOUT=classic or an unprovable fzf
    # routes it to the classic launcher). The verbs are direct tmux actions and
    # never build inventory or call git/fzf. Interactive-only: --json is
    # refused by the preflight above.
    shift
    case "${1:-}" in
      "") pick_nav; exit $? ;;
      help|-h|--help) [ "$#" -eq 1 ] || { printf 'usage: xtmux nav help\n' >&2; exit 2; }; nav_help; exit 0 ;;
      next) [ "$#" -eq 1 ] || { printf 'usage: xtmux nav next\n' >&2; exit 2; }; nav_session_cycle next; exit 0 ;;
      prev) [ "$#" -eq 1 ] || { printf 'usage: xtmux nav prev\n' >&2; exit 2; }; nav_session_cycle prev; exit 0 ;;
      attention-next) [ "$#" -eq 1 ] || { printf 'usage: xtmux nav attention-next\n' >&2; exit 2; }; nav_attention_cycle next; exit 0 ;;
      attention-prev) [ "$#" -eq 1 ] || { printf 'usage: xtmux nav attention-prev\n' >&2; exit 2; }; nav_attention_cycle prev; exit 0 ;;
      back) [ "$#" -eq 1 ] || { printf 'usage: xtmux nav back\n' >&2; exit 2; }; jump_back; exit 0 ;;
      *) printf 'xtmux nav: unknown subcommand: %s\n' "$1" >&2; exit 2 ;;
    esac
    ;;
  mode-toggle)
    # xtmux-rib.12: flip sessions-only <-> expanded; the bind then reloads
    # with the flipped mode so the list immediately reflects it.
    shift
    toggle_list_mode
    exit 0
    ;;
  obligations)
    shift
    obs_v2_mode
    [ "$REPLY" = on ] || { printf 'obligations: requires XTMUX_OBS_V2=1\n' >&2; exit 2; }
    obs_runtime_argv
    exec "${OBS_ARGV[@]}" obligations "$@"
    ;;
  wait-agent)
    shift
    obs_v2_mode
    if [ "$REPLY" = on ]; then
      obs_runtime_argv
      exec "${OBS_ARGV[@]}" wait-agent "$@"
    fi
    wait_agent "$@"
    exit $?
    ;;
  monitor-agent)
    shift
    obs_v2_mode
    if [ "$REPLY" = on ]; then
      obs_runtime_argv
      exec "${OBS_ARGV[@]}" monitor-agent "$@"
    fi
    monitor_agent "$@"
    exit $?
    ;;
  monitor-run)
    shift
    monitor_run "$@"
    exit $?
    ;;
  monitor-list)
    shift
    obs_v2_mode
    if [ "$REPLY" = on ]; then
      obs_runtime_argv
      exec "${OBS_ARGV[@]}" monitor-list "$@"
    fi
    monitor_list "$@"
    exit $?
    ;;
  monitor-kill)
    shift
    monitor_kill "$@"
    exit $?
    ;;
  monitors)
    # Human-scannable operator view. Alias for monitor-list --pretty.
    shift
    monitors_view "$@"
    exit $?
    ;;
  safe-send-pointer)
    shift
    safe_send_pointer "$@"
    exit $?
    ;;
  worktree-collisions)
    shift
    worktree_collisions "$@"
    exit $?
    ;;
  dashboard)
    shift
    dashboard "$@"
    exit $?
    ;;
  topology)
    shift
    topology_json "$@"
    exit $?
    ;;
  audit)
    shift
    audit "$@"
    exit $?
    ;;
  handoff)
    shift
    handoff "$@"
    exit $?
    ;;
  mux-help)
    shift
    mux_help
    exit 0
    ;;
  log)
    shift
    log_cli "$@"
    exit $?
    ;;
  context)
    shift
    context_cli "$@"
    exit $?
    ;;
  pane)
    shift
    pane_cli "$@"
    exit $?
    ;;
  bridge)
    shift
    bridge_cli "$@"
    exit $?
    ;;
  message-send)
    shift
    message_send "$@"
    exit $?
    ;;
  message-reply)
    shift
    message_reply "$@"
    exit $?
    ;;
  message-cancel)
    shift
    message_cancel "$@"
    exit $?
    ;;
  message-list)
    shift
    message_list "$@"
    exit $?
    ;;
  message-status)
    shift
    message_status "$@"
    exit $?
    ;;
  message-get)
    shift
    message_get "$@"
    exit $?
    ;;
  agent-last)
    shift
    agent_last "$@"
    exit $?
    ;;
  agent-episode)
    shift
    agent_episode "$@"
    exit $?
    ;;
  instance-get)
    shift
    instance_get "$@"
    exit $?
    ;;
  unread-count)
    shift
    unread_count "$@"
    exit $?
    ;;
  message-ack)
    shift
    message_ack "$@"
    exit $?
    ;;
  telemetry)
    shift
    telemetry_run "$@"
    exit $?
    ;;
  border-label)
    # xtmux-rib.12: fzf transform-border-label source — reads current nesting
    # mode and TMUX_PICKER_MODE so the border matches current UI state.
    shift
    read_list_mode
    case "$mode:$REPLY" in
      compact-wrap:sessions-only)
        printf '%s' ' compact wrap · sessions-only · Enter switch · Space mark · Tab expand · Alt-Enter popup · Alt-x kill · ^Y approve · Alt-I interrupt · ^O msg · ^A/^W/^E filtri · ^F filter · Ctrl-r refresh · ? help '
        ;;
      compact-wrap:*)
        printf '%s' ' compact wrap · expanded · Enter switch · Tab compact · Alt-Enter popup · Alt-x kill · ^Y approve · Alt-I interrupt · ^O msg · ^A/^W/^E filtri · ^F filter · Ctrl-r refresh · ? help '
        ;;
      compact-nowrap:sessions-only)
        printf '%s' ' compact no-wrap · sessions-only · Enter switch · Space mark · Tab expand · Alt-Enter popup · Alt-x kill · ^Y approve · Alt-I interrupt · ^O msg · ^A/^W/^E filtri · ^F filter · Ctrl-r refresh · ? help '
        ;;
      compact-nowrap:*)
        printf '%s' ' compact no-wrap · expanded · Enter switch · Tab compact · Alt-Enter popup · Alt-x kill · ^Y approve · Alt-I interrupt · ^O msg · ^A/^W/^E filtri · ^F filter · Ctrl-r refresh · ? help '
        ;;
      default:sessions-only|*:sessions-only)
        printf '%s' ' sessions-only · Enter switch · Space mark · Tab expand · Alt-R rename · Alt-X bulk kill · Alt-x kill · ^Y ok · Alt-I int · ^O msg · ^A all ^W wait ^E run · ^F filter · Ctrl-r refresh · ? help · Ctrl-/ preview '
        ;;
      *)
        printf '%s' ' expanded · Enter switch · Tab compact · Alt-R rename · Alt-X bulk kill · Alt-x kill · ^Y ok · Alt-I int · ^O msg · ^A all ^W wait ^E run · ^F filter · Ctrl-r refresh · ? help · Ctrl-/ preview '
        ;;
    esac
    exit 0
    ;;
  preview)
    shift
    preview_row "$@"
    exit 0
    ;;
  popup)
    shift
    open_popup_client "$@"
    ;;
  jump)
    shift
    jump_to_target "$@"
    ;;
  kill)
    shift
    kill_target "$@"
    exit 0
    ;;
  act)
    # act-on-preview (xtmux-rib.3): act on the highlighted pane without
    # attaching. actions: approve | interrupt | message. invoked by the fzf
    # binds ctrl-y / alt-i / ctrl-o.
    shift
    act_on_target "$@"
    exit 0
    ;;
  attn-jump)
    shift
    record_prev
    attn_jump "${1:-1}"
    exit 0
    ;;
  jump-back)
    jump_back
    exit 0
    ;;
  kill-confirm)
    shift
    kill_confirm "$@"
    exit 0
    ;;
  bulk-kill)
    shift
    bulk_kill "$@"
    exit $?
    ;;
  bulk-kill-targets)
    shift
    bulk_kill_targets "$@"
    exit $?
    ;;
  bulk-kill-confirm)
    shift
    bulk_kill_confirm "$@"
    exit 0
    ;;
  rename)
    shift
    rename_target "$@"
    exit 0
    ;;
  rename-apply)
    shift
    rename_apply "$@"
    exit 0
    ;;
  clear-cache)
    clear_cache
    exit 0
    ;;
  filter-menu)
    # ctrl-f submenu (xtmux-rib.11): writes the chosen spec to the state file.
    shift
    cmd_filter_menu
    exit 0
    ;;
  filter-clear)
    shift
    picker_state_write filter '' || true
    exit 0
    ;;
  filter-preset)
    shift
    [ "$#" -eq 1 ] || die_usage "filter-preset requires all, waiting, or running"
    case "$1" in all) _preset='' ;; waiting|running) _preset="$1" ;; *) die_usage "invalid filter preset: $1" ;; esac
    picker_state_write filter "$_preset" || true
    exit 0
    ;;
  prompt-label)
    # fzf transform-prompt source: reflects the active filter in the prompt.
    shift
    _style="${1:-classic}"
    picker_state_read filter || true
    _spec="$REPLY"
    if [ -n "$_spec" ]; then printf '%s> ' "$_spec"; else printf 'all> '; fi
    exit 0
    ;;
  install-hooks)
    shift
    install_tmux_hooks "${1:-}"
    exit 0
    ;;
  "")
    # Bare legacy picker: the original classic newline-TSV launcher and
    # interaction semantics, byte-compatible (NAV-2 split-launch invariant).
    pick_classic
    exit $?
    ;;
  help|--help|-h)
    help_text
    exit 0
    ;;
  *)
    # The old ~1,500-character usage blob lived here. It listed every flag and
    # was unreadable, so agents missed required args that were technically in it
    # (`message-list --for`). Point at the grouped reference instead.
    printf 'xtmux: unknown command: %s\n' "${1:-}" >&2
    printf 'run `xtmux help` for the command reference, `xtmux mux-help` for the delegation protocol.\n' >&2
    exit 2
    ;;
esac

# Every dispatch arm above exits. Bare `xtmux` routes to pick_classic and bare
# `xtmux nav` to pick_nav; nothing falls through to a second launcher.
exit 0
