#!/usr/bin/env bash
# ~/.kimi-code/hooks/verify.sh — Stop hook body for Kimi Code CLI.
#
# Fires when the model is about to end its turn. Runs the project's test suite;
# on failure, exits 2 with the summary on stderr, which Kimi appends to context
# and the model keeps working. On success (or no detectable runner) exits 0.
#
# Register in config.toml:
#   [[hooks]]
#   event = "Stop"
#   command = "bash ~/.kimi-code/hooks/verify.sh"
#   timeout = 300
#
# Remember: hooks fail open. If this script crashes or times out the turn ends
# normally. It is a quality loop, not a security barrier — deny rules are that.

set -u
cd "${KIMI_CWD:-.}" 2>/dev/null || true
# The event JSON arrives on stdin; we don't need it, but drain it so the CLI
# never blocks on a full pipe.
cat >/dev/null

run() {            # run a command, capture output, return its status
  out=$("$@" 2>&1); st=$?
  return $st
}

if   [ -f package.json ] && command -v npm   >/dev/null; then run npm test --silent
elif ls ./*.sln ./*.csproj >/dev/null 2>&1 && command -v dotnet >/dev/null; then run dotnet test --nologo -v q
elif [ -f pyproject.toml ] && command -v uv  >/dev/null; then run uv run pytest -q
elif [ -f Cargo.toml ]     && command -v cargo >/dev/null; then run cargo test -q
elif [ -f go.mod ]         && command -v go  >/dev/null; then run go test ./...
else
  echo "verify.sh: no test runner detected; nothing checked" >&2
  exit 0
fi

if [ "$st" -ne 0 ]; then
  {
    echo "Verification failed (exit $st). The turn is not done. Fix the failures, then re-run the suite:"
    echo "$out" | tail -n 40
  } >&2
  exit 2
fi
echo "verify.sh: suite green"
exit 0
