#!/usr/bin/env bash
# Stop hook. Two deterministic checks on the session transcript; no LLM involved.
# 1. Open tasks: TaskCreate'd items whose last TaskUpdate is not completed/deleted -> keep working.
# (This is what "continue" prompts were doing by hand: 427 of them in 45 days.)
# 2. Code edited after the last verification command -> nudge once per session.
# Exit 2 = do not stop, stderr goes to Claude. stop_hook_active=true means we already nudged
# this turn: always allow then, so the hook can never loop.
set -u
input="$(cat)"
[ "$(printf '%s' "$input" | jq -r '.stop_hook_active // false')" = "true" ] && exit 0
t="$(printf '%s' "$input" | jq -r '.transcript_path // empty')"
[ -f "$t" ] || exit 0
sid="$(printf '%s' "$input" | jq -r '.session_id // "nosession"')"
# If the last assistant text ends with a question, Claude is asking the user: let it stop,
# unless he is away, where a chat question stalls the run exactly like AskUserQuestion would.
last_text="$(jq -r 'select(.type=="assistant") | .message.content[]? | select(.type=="text") | .text' "$t" 2>/dev/null | grep -v '^[[:space:]]*