#!/usr/bin/env bash
# Stop-hook VERIFY GATE — the agent cannot end its turn on a red build.
# Runs the repo's verify command (.claude/verify.sh) if present, and BLOCKS the stop
# (decision:block) with the failure output until it passes. No-ops in any repo WITHOUT a
# .claude/verify.sh, so it's safe to install globally. Converges via the stop_hook_active
# guard + Claude Code's hard ceiling of 8 consecutive blocks.

input="$(cat)"

jget() { # $1 = key
  command -v python3 >/dev/null 2>&1 || return 0
  printf '%s' "$input" | python3 -c "import sys,json
try: print(json.load(sys.stdin).get('$1',''))
except Exception: pass" 2>/dev/null
}

# 1) Don't loop: if we already blocked this turn, allow the stop.
[ "$(jget stop_hook_active)" = "True" ] && exit 0

# 2) Locate the project verify command.
cwd="$(jget cwd)"; [ -z "$cwd" ] && cwd="$PWD"
verify="$cwd/.claude/verify.sh"
[ -f "$verify" ] || exit 0          # no verify.sh -> no-op (safe everywhere)

# 3) Run it. Green -> let the agent finish. Red -> block and feed back the failures.
out="$(bash "$verify" 2>&1)"; code=$?
[ "$code" -eq 0 ] && exit 0

if command -v python3 >/dev/null 2>&1; then
  printf '%s' "$out" | python3 -c "import sys,json
out=sys.stdin.read()[-4000:]
print(json.dumps({'decision':'block','reason':'Verify gate failed — fix before finishing:\n'+out}))"
else
  echo '{"decision":"block","reason":"Verify gate failed — run .claude/verify.sh, fix the failures, then finish."}'
fi
exit 0
