#!/usr/bin/env bash
# pr-write-guard.sh  -  PreToolUse on Bash: a pr-threads.mjs apply (a GitHub
# write by /multi-agent:address-review) asks the person first, and is denied
# with MULTI_AGENT_UNATTENDED=1. The decision is in pr-write-guard.mjs.
#
# Contract (Claude Code PreToolUse hook): reads the tool-call JSON on stdin,
# prints the hook JSON or nothing, exits 0. A call that mentions none of
# pr*threads, --action and --confirm ends here without starting node. Without
# node, a call that mentions pr*threads and apply still gets an ask (deny
# unattended).

set -u

HERE="$(cd "$(dirname "$0")" 2>/dev/null && pwd || true)"
CORE="$HERE/pr-write-guard.mjs"
INPUT="$(cat)"

case "$INPUT" in
  *pr*threads* | *--action* | *--confirm*) ;;
  *) exit 0 ;;
esac

if [ -f "$CORE" ] && command -v node >/dev/null 2>&1; then
  printf '%s' "$INPUT" | node "$CORE" 2>/dev/null && exit 0
fi

case "$INPUT" in
  *pr*threads*apply* | *apply*pr*threads*)
    decision=ask
    [ "${MULTI_AGENT_UNATTENDED:-}" = "1" ] && decision=deny
    printf '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"%s","permissionDecisionReason":"pr-write-guard: pr-threads apply writes to GitHub; approve this one write"}}\n' "$decision"
    ;;
esac
exit 0
