#!/bin/bash
# AutoMem SessionStart hook - prompts Claude to run two-phase recall.
# Claude executes the MCP tool calls; this script just injects the prompt.
# Generated by scripts/sync-memory-policy.ts. Do not edit by hand.

# Emit at most once per session: residual double-registration (legacy settings
# entry + plugin, or path-variant duplicates) must not inject the prompt twice.
# Hook stdin is JSON that includes session_id; no stdin/session_id -> always emit.
SESSION_ID=""
HOOK_SOURCE=""
if [ ! -t 0 ]; then
  HOOK_INPUT=$(cat 2>/dev/null || true)
  SESSION_ID=$(printf '%s' "$HOOK_INPUT" | sed -n 's/.*"session_id"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n 1 | tr -cd 'A-Za-z0-9_-')
  HOOK_SOURCE=$(printf '%s' "$HOOK_INPUT" | sed -n 's/.*"source"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n 1 | tr -cd 'A-Za-z0-9_-')
fi
if [ -n "$SESSION_ID" ]; then
  SENTINEL="${TMPDIR:-/tmp}/automem-session-start-${SESSION_ID}${HOOK_SOURCE:+-$HOOK_SOURCE}"
  if [ -e "$SENTINEL" ]; then
    exit 0
  fi
  : > "$SENTINEL" 2>/dev/null || true
fi

PROJECT=$(basename "$PWD")

cat << EOF
<automem_session_context>
MEMORY RECALL - run both recalls before your first substantive response. They are independent: issue them in parallel in a single message.

Phase 1 - Preferences (tag-only, no time filter, no query):
  mcp__memory__recall_memory({
    tags: ["preference"],
    limit: 20,
    sort: "updated_desc"
  })

Phase 2 - Task context (ONE semantic query from the user's actual nouns; project-slug gate when unambiguous; 90-day window):
  mcp__memory__recall_memory({
    query: "<proper nouns, product names, people, tools, specific topics from the user's message>",
    tags: ["$PROJECT"],    // drop if slug collides with a common word
    time_query: "last 90 days",
    limit: 30
  })

Project slug: $PROJECT

Notes:
- Tags are a HARD GATE - they filter before scoring. Use only the tag sets above; never invent topic tags. Bare tags only - no namespace prefixes (\`project/*\`, \`lang/*\`).
- Debugging recall is ON-DEMAND: when the user reports an error symptom, recall with the symptom as a semantic query and NO tags (a tag gate hides cross-corpus fixes), limit 20.
- Phase 2 uses ONE targeted query, not \`queries[]\` + \`auto_decompose\`. Sub-queries converge and dedup drops results; reserve \`queries[]\` for genuinely multi-topic questions.
- If the project slug collides with a common topic word (for example \`video\` or \`test\`), drop the Phase 2 tag gate and rely on semantic \`query\` alone.
- Results show created/updated timestamps and importance - prefer fresh, high-importance memories. Fetch a single full record with recall_memory({ memory_id: "<id>" }) when needed.
- Do not re-recall every turn. After turn 1, recall again only for topic shifts, new proper nouns, or active debugging.
- If recall fails or returns nothing, continue without memory - do not mention the failure to the user.
</automem_session_context>
EOF
