#!/usr/bin/env bash
# PreToolUse hook: best-effort protection for the gate's own files.
# Its deny is evaluated before permission mode, so it holds even under bypassPermissions.
# NOT a security boundary: a shell-capable worker has other paths (symlinks, wrappers).
set -uo pipefail

# (1) inert unless this session opted in — matches verify-goal.sh, so "registered but off"
# is literally true. Without this the protector would deny .claude edits in every session.
[ "${GOAL_GATE_ACTIVE:-0}" = "1" ] || exit 0

command -v jq >/dev/null 2>&1 || exit 0

INPUT=$(cat)
tool=$(jq -r '.tool_name // empty' <<<"$INPUT" 2>/dev/null)
PROTECTED_RE='(^|/)\.claude/hooks/(verify-goal|protect-gate)\.sh$|(^|/)\.claude/settings(\.local)?\.json$|(^|/)\.claude/goal-base$'
deny() { jq -nc --arg r "$1" '{hookSpecificOutput:{hookEventName:"PreToolUse", permissionDecision:"deny", permissionDecisionReason:$r}}'; exit 0; }

case "$tool" in
  Edit|Write|MultiEdit|NotebookEdit)
    fp=$(jq -r '.tool_input.file_path // .tool_input.notebook_path // empty' <<<"$INPUT" 2>/dev/null)
    [[ "$fp" =~ $PROTECTED_RE ]] && deny "Editing the completion gate ($fp) is not allowed while a goal is active." ;;
  Bash)
    cmd=$(jq -r '.tool_input.command // empty' <<<"$INPUT" 2>/dev/null)
    grep -qE '\.claude/(hooks/(verify-goal|protect-gate)\.sh|settings(\.local)?\.json|goal-base)' <<<"$cmd" \
      && deny "Command touches the gate's files; denied."
    grep -qE '\b(rm|rmdir|mv)\b[^|;&]*\.claude(/|\b)' <<<"$cmd" \
      && deny "Command removes or moves .claude; denied." ;;
esac
exit 0
