#!/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 §1 (Safety & Git
# Operations): no unapproved `git push`, no repo-local worktrees.
#
# Exit code 0 = allow, non-zero = block the tool call.

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

if echo "$COMMAND" | grep -qE '\bgit\s+push\b'; then
  echo "BLOCKED by agent-os guard-bash.sh: 'git push' requires explicit user approval per push (constitution.md §1). Stage/commit locally, show the user 'git log', and ask for confirmation before pushing." >&2
  exit 1
fi

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

exit 0
