#!/usr/bin/env bash
# gstack-session-kind — classify the current agent session so skills know whether
# a human can answer an interactive prompt (AskUserQuestion).
#
# Usage: gstack-session-kind            → prints one of: unattended | spawned | headless | interactive
#
# Used by the preamble (generate-preamble-bash.ts) which echoes
#   SESSION_KIND: <value>
# so the AskUserQuestion-failure fallback rule can branch without a shell-out at
# failure time:
#   spawned     → orchestrator session (OpenClaw). Auto-choose recommended option
#                 per the skill's SPAWNED_SESSION block. Never prose, never BLOCKED.
#   headless    → no human present (claude -p evals / CI / codex exec). BLOCK on AUQ failure.
#   interactive → a human is present. Prose-fallback on AUQ failure.
#   unattended  → a parent agent drives this run and reads its artifacts, not
#                 its prose (plan B1). Recommended options are auto-decided and
#                 logged; the final approval gate is written, never approved;
#                 no prompts, no publishing, no sync. Honored ONLY as the
#                 explicit GSTACK_SESSION_KIND=unattended override, which
#                 outranks GSTACK_HEADLESS so a parent can drive a run inside
#                 CI; the eval harness never sets it, so `headless` keeps its
#                 BLOCK semantics and no eval case changes meaning.
#
# Detection is best-effort. On ANY ambiguity it prints `interactive` — BLOCK only on
# a positive headless signal, since a stray prose message in an unmarked one-shot
# `-p` run just ends the turn (harmless), whereas wrongly BLOCKING a real human is not.
#
# GSTACK_SESSION_KIND=spawned|unattended is the explicit per-command override (step 0
# below), outranking every ambient marker. Deliberately narrow — only those two are honored:
# Claude Code subagents inherit the parent env byte-for-byte (#2733), so a
# dispatching skill marks its subagent by prefixing the gstack-skill-start
# invocation. "headless" already has GSTACK_HEADLESS; other values are reserved
# and ignored (fall through to detection).
#
# Why env vars and not TTY/entrypoint: an interactive Conductor session reports
# CLAUDE_CODE_ENTRYPOINT=sdk-ts with no TTY — identical to a headless SDK eval. The
# signals that actually discriminate are the host/orchestrator/CI env markers below.
set -euo pipefail

# 0. Explicit spawned / unattended marker — full rationale and contract in the header above.
case "${GSTACK_SESSION_KIND:-}" in
  spawned|unattended)
    echo "$GSTACK_SESSION_KIND"
    exit 0
    ;;
esac

# 1. Orchestrator-spawned session (OpenClaw). Authoritative block lives in the skill;
#    we only surface the classification.
if [ -n "${OPENCLAW_SESSION:-}" ]; then
  echo "spawned"
  exit 0
fi

# 2. Explicit headless override (set by the eval/E2E harness for determinism).
if [ -n "${GSTACK_HEADLESS:-}" ]; then
  echo "headless"
  exit 0
fi

# 3. Positive interactive-host signals: a human-driven host is present.
#    - Conductor app sets CONDUCTOR_* workspace vars.
#    - Plain interactive `claude` CLI sets CLAUDE_CODE_ENTRYPOINT=cli.
if [ -n "${CONDUCTOR_WORKSPACE_PATH:-}" ] || [ -n "${CONDUCTOR_PORT:-}" ] || [ "${CLAUDE_CODE_ENTRYPOINT:-}" = "cli" ]; then
  echo "interactive"
  exit 0
fi

# 4. Codex non-interactive run: `codex exec` (alias `e`) or `codex review`. Codex
#    0.170 gives every tool shell CODEX_THREAD_ID and CODEX_CI=1, and no TTY, in
#    its interactive TUI and in exec alike, so the env cannot tell them apart.
#    The process tree can: exec runs tool shells under its own `codex exec`
#    process, while the TUI runs them under its `codex app-server` daemon. Walk
#    up to the nearest codex process (argv[0], or argv[1] under node or a script
#    interpreter) and read its subcommand. Linux's /proc keeps argv boundaries;
#    elsewhere ps joins argv with spaces, so a TUI started with --no-daemon and a
#    prompt whose first word is "exec" would read as exec there. Linux also reads
#    parent pids from /proc, so a slim image without ps still works. Elsewhere
#    any read failure (no ps, as in Git Bash) means no signal.
_codex_argv() {
  if [ -r "/proc/$1/cmdline" ]; then tr '\0' '\n' < "/proc/$1/cmdline"; else ps -o args= -p "$1" 2>/dev/null | tr ' ' '\n'; fi
}
_codex_noninteractive_ancestor() {
  local pid=$PPID depth=0 tok i found skip sub
  while [ "$depth" -lt 12 ] && [ "${pid:-0}" -gt 1 ] 2>/dev/null; do
    i=0 found=0 skip=0 sub=""
    while IFS= read -r tok; do
      i=$((i + 1))
      if [ "$found" -eq 0 ]; then
        [ "$i" -le 2 ] || break
        case "${tok##*/}" in codex|codex.js|codex.exe) found=1 ;; esac
        continue
      fi
      if [ "$skip" -eq 1 ]; then skip=0; continue; fi
      case "$tok" in
        -c|--config|-m|--model|-p|--profile|-s|--sandbox|-a|--ask-for-approval|-C|--cd|-i|--image|--add-dir|--enable|--disable|--local-provider|--remote|--remote-auth-token-env) skip=1 ;;
        -*|'') ;;
        *) sub=$tok; break ;;
      esac
    done < <(_codex_argv "$pid")
    if [ "$found" -eq 1 ]; then
      case "$sub" in exec|e|review) return 0 ;; *) return 1 ;; esac
    fi
    if [ -r "/proc/$pid/status" ]; then
      pid=$(while read -r tok sub; do [ "$tok" = "PPid:" ] && { echo "$sub"; break; }; done < "/proc/$pid/status")
    else
      pid=$(ps -o ppid= -p "$pid" 2>/dev/null | tr -d ' ') || return 1
    fi
    depth=$((depth + 1))
  done
  return 1
}
if [ -n "${CODEX_THREAD_ID:-}" ] && _codex_noninteractive_ancestor; then
  echo "headless"
  exit 0
fi

# 5. CI / automation markers with no interactive host → headless.
if [ -n "${CI:-}" ] || [ -n "${GITHUB_ACTIONS:-}" ]; then
  echo "headless"
  exit 0
fi

# 6. No positive headless signal → assume a human is present (degrade-safe default).
echo "interactive"
