#!/usr/bin/env bash
# agent-guard.sh  -  PreToolUse Bash guard for the multi-agent pipeline.
#
# Turns two prompt-level rules into deterministic, OS-enforced gates:
#   1. No AI/assistant attribution in git commit messages (Co-Authored-By: Claude,
#      "Generated with Claude Code", robot emoji, Anthropic no-reply address).
#   2. No force-push to a protected branch (main / master / develop).
#
# Contract (Claude Code PreToolUse hook):
#   - Reads the tool-call JSON on stdin: {"tool_input":{"command":"..."}, ...}.
#   - Exit 2  -> BLOCK the tool call (reason on stderr, shown to the model).
#   - Exit 0  -> allow.
#
# Safety design (fail-OPEN):
#   - The command string is ONLY parsed/pattern-matched, NEVER executed or eval'd
#     (the decision core is agent-guard.py; shlex tokenizes without running).
#   - Any internal error (bad JSON, missing python3/helper, empty input) -> exit 0.
#     A guard bug must never break a legitimate tool call.
#   - No network, no file writes, no secret values printed.
#   - The single exec is a read-only `git rev-parse` to learn the current branch.

set -u

HERE="$(cd "$(dirname "$0")" 2>/dev/null && pwd || true)"
HELPER="$HERE/agent-guard.py"
[ -f "$HELPER" ] || exit 0
command -v python3 >/dev/null 2>&1 || exit 0

PAYLOAD="$(cat 2>/dev/null || true)"
[ -z "$PAYLOAD" ] && exit 0

CUR_BRANCH="$(git rev-parse --abbrev-ref HEAD 2>/dev/null || true)"

DECISION="$(printf '%s' "$PAYLOAD" | CUR_BRANCH="$CUR_BRANCH" python3 "$HELPER" 2>/dev/null || true)"

case "$DECISION" in
  BLOCK_ATTRIB)
    echo "BLOCKED by agent-guard: the commit message carries AI/assistant attribution." >&2
    echo "Remove any 'Co-Authored-By: Claude', 'Generated with Claude Code', robot-emoji, or" >&2
    echo "anthropic no-reply trailer. Commits are authored solely as the user's git identity." >&2
    exit 2 ;;
  BLOCK_FORCE)
    echo "BLOCKED by agent-guard: force-push to a protected branch (main/master/develop) is not allowed." >&2
    echo "Rewriting shared history is a data-loss risk. Push a normal commit, or force-push a feature branch." >&2
    exit 2 ;;
  *)
    exit 0 ;;
esac
