#!/usr/bin/env bash
# Reference PreToolUse guard for Claude Code (and adaptable to other
# tools that pass the pending shell command on stdin as JSON, or via the
# $TOOL_INPUT / $CLAUDE_TOOL_INPUT env var depending on the tool version).
#
# Provided by @abblor/agent-os. Enforces constitution.md section 1 (Safety &
# Git Operations): no direct pushes to protected branches and no
# repo-local worktrees.
#
# Exit code 0 = allow, non-zero = block the tool call.
#
# ---------------------------------------------------------------------------
# Push safety
# ---------------------------------------------------------------------------
# Feature branch pushes are part of the authorized issue-to-live workflow.
# Feature branch pushes have no approval gates under the temporary policy.

set -euo pipefail

# Claude Code passes hook input as JSON on stdin. Fall back to $1 for
# manual/testing invocation.
INPUT="$(cat 2>/dev/null || true)"
COMMAND="${1:-}"
if [ -z "$COMMAND" ] && [ -n "$INPUT" ]; then
  COMMAND="$(echo "$INPUT" | grep -o '"command"[[:space:]]*:[[:space:]]*"[^"]*"' | head -1 | sed -E 's/.*"command"[[:space:]]*:[[:space:]]*"([^"]*)"/\1/' || true)"
fi

if [ -z "$COMMAND" ]; then
  exit 0
fi

PROTECTED_BRANCHES_REGEX='^(main|master)$'

deny() {
  echo "$1" >&2
  exit 1
}

# ------------------------------------------------------------------- push ---

if echo "$COMMAND" | grep -qE '\bgit\s+push\b'; then
  GIT_DIR="$(git rev-parse --absolute-git-dir 2>/dev/null || true)"
  if [ -z "$GIT_DIR" ]; then
    deny "BLOCKED by agent-os guard-bash.sh: push attempted outside a git repository."
  fi

  CURRENT_BRANCH="$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo '')"
  if printf '%s' "$CURRENT_BRANCH" | grep -qE "$PROTECTED_BRANCHES_REGEX" || \
    echo "$COMMAND" | grep -qE '(^|[[:space:]])(main|master)([[:space:]]|$)|:[[:space:]]*(refs/heads/)?(main|master)([[:space:]]|$)'; then
    deny "BLOCKED by agent-os guard-bash.sh: push targets protected branch main/master. Push a feature branch and merge through a pull request."
  fi

  exit 0
fi

# ------------------------------------------------------- repo-local worktrees

if echo "$COMMAND" | grep -qE '(^|[;&|]\s*)mkdir\s+(-p\s+)?(\./)?\.?worktrees?\b'; then
  deny "BLOCKED by agent-os guard-bash.sh: repo-local worktrees are forbidden (constitution.md section 1). Create the worktree outside the repo tree instead."
fi

exit 0
