#!/usr/bin/env bash # Hook: UserPromptSubmit # # Fires on every user message. Instead of pre-searching mem0 with the # raw prompt, this injects a decision rubric telling the agent when # and how to search itself. The agent has more context than this # script does -- let it decide. # # Input: JSON on stdin (prompt, session_id, cwd, transcript_path) # Output: Decision rubric injected into Claude's context (exit 0) # Intentionally omit -e so the script always exits 0 even if jq fails -- # must never block the user's prompt. set -uo pipefail if [ -n "${MEM0_DEBUG:-}" ]; then mkdir -p "$HOME/.mem0" && exec 2>>"$HOME/.mem0/hooks.log" fi INPUT=$(cat) PROMPT=$(echo "$INPUT" | jq -r '.prompt // ""' 2>/dev/null || echo "") # Acknowledgements and short replies don't warrant memory context if [ ${#PROMPT} -lt 20 ]; then exit 0 fi SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" # shellcheck source=_identity.sh . "$SCRIPT_DIR/_identity.sh" # Detect stack traces and error patterns in the prompt (no API needed) HAS_ERROR="" if echo "$PROMPT" | grep -qiE '(Traceback|Error:|Exception:|panic:|FAILED|fatal:| at .+\.[a-z]+:[0-9]+)'; then HAS_ERROR="true" fi # Detect file paths in the prompt (no API needed) FILE_PATHS=$(echo "$PROMPT" | grep -oE '([a-zA-Z0-9_./-]+\.(py|ts|tsx|js|jsx|rs|go|rb|java|sh|yaml|yml|json|toml|md|sql|css|html))\b' 2>/dev/null | head -5 || echo "") # Telemetry (background, fire-and-forget) _TELEM_ARGS="" [ -n "$HAS_ERROR" ] && _TELEM_ARGS="$_TELEM_ARGS --error_detected" [ -n "$FILE_PATHS" ] && _TELEM_ARGS="$_TELEM_ARGS --file_paths_detected" python3 "$SCRIPT_DIR/telemetry.py" user_prompt $_TELEM_ARGS 2>/dev/null & # No API key — emit detections only, skip search rubric if [ -z "${MEM0_API_KEY:-}" ]; then if [ -n "$HAS_ERROR" ]; then echo "**ERROR DETECTED in prompt.** Set MEM0_API_KEY to search past debugging context." fi if [ -n "$FILE_PATHS" ]; then echo "**FILE PATHS detected:** \`$FILE_PATHS\`" fi exit 0 fi USER_ID="$MEM0_RESOLVED_USER_ID" cat <"}}]})\` - Also run a broader text search without the files filter as fallback: - \`search_memories(query="", filters={"AND": [{"user_id": "$USER_ID"}, {"app_id": "$MEM0_PROJECT_ID"}]})\` EOF fi cat <"}}\`. Skip recency for durable facts (conventions, decisions). - Empty results are normal -- proceed without context. EOF exit 0