#!/bin/bash
# MC Delegation Guard - Prevents Master Control from directly executing tools
# This enforces the Prime Directive: MC orchestrates, never executes
#
# Claude Code Hook: PreToolUse
# Exit codes:
#   0 = Allow tool use
#   2 = Block tool use (with feedback message)

set -e

# Read hook input from stdin (JSON format)
INPUT=$(cat)

# Parse the tool name from input
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name // empty')

# MC session tracking file
SESSION_FILE="$HOME/.grid/mc_session_id"

# Only enforce when MC is active (session file exists)
if [[ ! -f "$SESSION_FILE" ]]; then
    # Not an MC session, allow all tools
    exit 0
fi

# Read the MC session ID
MC_SESSION=$(cat "$SESSION_FILE" 2>/dev/null || echo "")

# If session file is empty or unreadable, allow (safety fallback)
if [[ -z "$MC_SESSION" ]]; then
    exit 0
fi

# Blocked tools for MC - these require spawning a Program
BLOCKED_TOOLS=("Write" "Edit" "Bash" "NotebookEdit")

# Check if current tool is in blocked list
for blocked in "${BLOCKED_TOOLS[@]}"; do
    if [[ "$TOOL_NAME" == "$blocked" ]]; then
        # Return feedback to Claude (exit code 2 sends message back)
        cat << 'EOF'
DELEGATION VIOLATION DETECTED

Master Control cannot use the tool directly.

THE PRIME DIRECTIVE:
  "MC orchestrates, never executes."

RESOLUTION:
  Spawn an Executor Program via Task() tool to perform this operation.

  Example:
    Task(
      description="Execute the file operation",
      prompt="[specific instructions for the Program]"
    )

All Write, Edit, Bash, and NotebookEdit operations must be delegated.

End of Line.
EOF
        exit 2
    fi
done

# Tool is allowed
exit 0
