#!/usr/bin/env bash
# openroar pre-commit hook — drift-stop guardrails per STANDING_RUN_DIRECTIVE §15.
#
# Install via: ln -sf ../../scripts/git-hooks/pre-commit .git/hooks/pre-commit
#
# Refuses commits that:
#   (a) Touch openroar/manifest/** but don't reference an eval result in the
#       commit message (the cadence requires re-running the eval after any
#       manifest change).
#   (b) Touch openroar/tools/** (Phase 3 security-critical) without a `panel:`
#       record in the commit body.
#
# To override for a genuine exception (docs-only, hotfix):
#   git commit --no-verify    # explicit, audited via reflog
#
# The hook is INTENTIONALLY soft on docs-only / non-safety-bearing changes —
# it only blocks commits where the cadence is structurally violated.
set -e

# Skip on amend / merge — those have their own semantics
case "${1:-}" in
    "")  ;; # normal commit, run checks
    *amend*|merge*) exit 0 ;;
esac

# Files staged for commit
STAGED="$(git diff --cached --name-only)"

# Read commit message (passed via .git/COMMIT_EDITMSG)
MSG_FILE=".git/COMMIT_EDITMSG"
if [ ! -f "$MSG_FILE" ]; then
    # Hook invoked without a message file (rare path) — let it through.
    exit 0
fi
MSG="$(cat "$MSG_FILE")"

# Lowercase the message for case-insensitive matching
MSG_LOWER="$(echo "$MSG" | tr '[:upper:]' '[:lower:]')"

# (a) Manifest-touching commits must reference an eval result
if echo "$STAGED" | grep -qE "^openroar/manifest/"; then
    if ! echo "$MSG_LOWER" | grep -qE "bypass-rate|eval|t-087|over-refusal|hard-gate|numbers panel|measured"; then
        echo "ERROR: commit touches openroar/manifest/** but the message has no eval reference."
        echo "       Run \`python -m openroar.eval.cli --judge fixed-allow\` (or with a real judge),"
        echo "       then include the bypass-rate / over-refusal-rate / hard-gate numbers in the commit body."
        echo "       Override with: git commit --no-verify  (and write down WHY in the message)."
        exit 1
    fi
fi

# (b) Tools-touching commits must have a panel record (security-critical)
if echo "$STAGED" | grep -qE "^openroar/tools/"; then
    if ! echo "$MSG_LOWER" | grep -qE "panel:|review record|families:|risk-class:"; then
        echo "ERROR: commit touches openroar/tools/** (security-critical) without a panel record."
        echo "       Run the multi-review panel and include its review-record block in the commit body."
        echo "       Override with: git commit --no-verify  (and write down WHY in the message)."
        exit 1
    fi
fi

exit 0
