#!/usr/bin/env bash
# PreToolUse hook — enforces agent tool boundaries.
# Usage: pre-tool-use.sh <agent-type>
# Receives tool call JSON on stdin (from Claude Code hook protocol).
# Exit 0 = allow, exit 2 = block.

AGENT_TYPE="${1:-public}"

# Read stdin — fail closed if unavailable
if [ -t 0 ]; then
  echo "Blocked: Cannot determine tool call (no stdin). Failing closed." >&2
  exit 2
fi
INPUT=$(cat)
TOOL_NAME=$(echo "$INPUT" | grep -o '"tool_name":"[^"]*"' | head -1 | cut -d'"' -f4)

# ---------------------------------------------------------------------------
# Admin agent — allow all tools EXCEPT writes/commands to protected code directories.
# The agent must never modify app source, platform code, or its own hooks.
# ---------------------------------------------------------------------------
if [ "$AGENT_TYPE" = "admin" ]; then
  case "$TOOL_NAME" in
    Write|Edit)
      FILE_PATH=$(echo "$INPUT" | grep -o '"file_path":"[^"]*"' | head -1 | cut -d'"' -f4)
      case "$FILE_PATH" in
        # Platform UI source (platform/ui/) — source lives here, not on device
        */platform/ui/app/*|*/platform/ui/lib/*|*/platform/ui/*.ts|*/platform/ui/*.tsx|*/platform/ui/*.mjs)
          echo "Blocked: Admin agent cannot modify platform UI source at $FILE_PATH" >&2
          exit 2
          ;;
        # Compiled MCP servers, hooks, and scripts — what actually ships to device
        */platform/plugins/*/mcp/dist/*|*/platform/plugins/*/hooks/*|*/platform/scripts/*)
          echo "Blocked: Admin agent cannot modify platform code at $FILE_PATH" >&2
          exit 2
          ;;
      esac
      ;;
    Bash)
      # Block shell commands referencing protected code directories
      case "$INPUT" in
        *"platform/ui/app/"*|*"platform/ui/lib/"*|*"platform/plugins/"*"hooks/"*|*"platform/scripts/"*)
          echo "Blocked: Admin agent cannot run shell commands against code directories" >&2
          exit 2
          ;;
      esac
      ;;
  esac
  exit 0
fi
