#!/bin/bash
# GateGuard — block first edit to a file until it has been read.
#
# PreToolUse hook: tracks which files have been Read in this session.
# If an Edit/Write targets a file that hasn't been Read yet, rejects
# the tool use with a message demanding investigation.
#
# This prevents the class of bug where the agent edits a file without
# understanding its imports, callers, or data schemas first.

TOOL_NAME="$CLAUDE_TOOL_NAME"
TOOL_INPUT="$CLAUDE_TOOL_INPUT"
SESSION_DIR="${CLAUDE_SESSION_DIR:-/tmp/cody-gateguard-$$}"

# Only gate Edit and Write tools
case "$TOOL_NAME" in
  Edit|Write|MultiEdit)
    ;;
  Read)
    # Track reads — extract file path and record it
    FILE_PATH=$(echo "$TOOL_INPUT" | grep -o '"file_path"[[:space:]]*:[[:space:]]*"[^"]*"' | head -1 | sed 's/.*"file_path"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/')
    if [ -n "$FILE_PATH" ]; then
      mkdir -p "$SESSION_DIR"
      echo "$FILE_PATH" >> "$SESSION_DIR/read_files.txt"
    fi
    exit 0
    ;;
  *)
    exit 0
    ;;
esac

# Extract the target file path from the tool input
FILE_PATH=$(echo "$TOOL_INPUT" | grep -o '"file_path"[[:space:]]*:[[:space:]]*"[^"]*"' | head -1 | sed 's/.*"file_path"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/')

if [ -z "$FILE_PATH" ]; then
  exit 0  # Can't determine file — allow
fi

# Check if this file has been read in this session
mkdir -p "$SESSION_DIR"
if [ -f "$SESSION_DIR/read_files.txt" ] && grep -qF "$FILE_PATH" "$SESSION_DIR/read_files.txt"; then
  exit 0  # File has been read — allow edit
fi

# Block the edit
echo "BLOCK: Read $FILE_PATH first before editing. Check imports, callers, and data schemas to avoid breaking dependencies."
exit 1
