#!/bin/bash
# Protect scaffold-synced agents and skills from accidental modification.
# Used by PreToolUse hook for Edit|Write|MultiEdit tools.
# Uses permissionDecision: "ask" to prompt user for confirmation.
#
# Opt-in: defaults OFF. Enable by setting "protectAgentsSkills": true in
# ~/.claude/evolv-coder-kit/global-state.json. Master "protectionsEnabled": false
# overrides this and disables all protections (parity with protect-files.sh).
#
# Rationale: agents and skills are scaffold-synced from the global catalog.
# Direct edits in a managed project are overwritten on the next
# /eck:pull-from-global-catalog. This hook surfaces the canonical edit path
# (the upstream scaffold) before edits happen.

. "$(dirname "$0")/_common.sh"

STATE_FILE="$HOME/.claude/evolv-coder-kit/global-state.json"

# Master kill-switch: NOOP if all protections disabled (parity with protect-files.sh).
if [ -f "$STATE_FILE" ]; then
  ENABLED=$(cat "$STATE_FILE" | grep -o '"protectionsEnabled":[^,}]*' | grep -o '[^:]*$' | tr -d ' ')
  if [ "$ENABLED" = "false" ]; then exit 0; fi
fi

# Opt-in: default off. Hook is a NOOP unless protectAgentsSkills is explicitly true.
OPTIN="false"
if [ -f "$STATE_FILE" ]; then
  OPTIN=$(cat "$STATE_FILE" | grep -o '"protectAgentsSkills":[^,}]*' | grep -o '[^:]*$' | tr -d ' ')
fi
if [ "$OPTIN" != "true" ]; then exit 0; fi

INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')

if [ -z "$FILE_PATH" ]; then
  exit 0
fi

FILE_PATH_NORM=$(_normalize_path "$FILE_PATH")

# Match anywhere in the path (the .claude/ tree may be nested under a project root).
case "$FILE_PATH_NORM" in
  */.claude/agents/*|*/.claude/skills/*)
    jq -n --arg file "$FILE_PATH" '{
      "hookSpecificOutput": {
        "hookEventName": "PreToolUse",
        "permissionDecision": "ask",
        "permissionDecisionReason": ("Scaffold-synced file: " + $file + " — direct edits are overwritten on next /eck:pull-from-global-catalog. Edit the canonical version in scaffold/ upstream, or confirm to proceed.")
      }
    }'
    exit 0
    ;;
esac

exit 0
