#!/usr/bin/env bash
# prevent-memory-write.sh — PreToolUse hook
#
# Blocks Write/Edit/MultiEdit calls targeting Claude Code's native auto-memory
# files (~/.claude/projects/*/memory/*.md).
#
# These files are runtime-specific silos that no other agent harness can read.
# All agent learnings MUST go to OpenBrain (capture MCP tool or REST API).
# MEMORY.md files may only contain load-path behavioral guardrails — not knowledge.
#
# Exit codes (Claude Code PreToolUse):
#   0 = allow
#   2 = block with message shown to agent

set -euo pipefail

INPUT="$(cat)"

FILE_PATH="$(echo "$INPUT" | jq -r '.tool_input.file_path // empty' 2>/dev/null || true)"

[[ -z "$FILE_PATH" ]] && exit 0

# Resolve ~ to HOME
FILE_PATH="${FILE_PATH/#\~/$HOME}"

# Block writes to Claude Code auto-memory files
if [[ "$FILE_PATH" =~ /.claude/projects/.+/memory/.*\.md$ ]]; then
  echo "BLOCKED: Do not write agent learnings to ~/.claude/projects/*/memory/ — this is a runtime-specific silo."
  if [[ -n "${OPENBRAIN_URL:-}" ]]; then
    echo "Use OpenBrain instead: MCP 'capture' tool or REST POST ${OPENBRAIN_URL%/}/v1/thoughts"
  else
    echo "Use OpenBrain instead: the 'capture' MCP tool (set OPENBRAIN_URL for the REST endpoint)."
  fi
  echo "File blocked: $FILE_PATH"
  exit 2
fi

exit 0
