#!/bin/bash
# AutoMem Stop hook - one-shot LLM-judged storage nudge.
# If no mcp__memory__store_memory call happened this session (tracked by
# automem-track-store.sh via the automem-stored-<session_id> sentinel),
# emits hookSpecificOutput.additionalContext asking Claude once to consider
# storing durable facts. The top-level suppressOutput:true keeps the JSON out
# of the user-visible transcript while Claude still receives the nudge.
# Advisory only: never blocks, never exits 2.
# Generated by scripts/sync-memory-policy.ts. Do not edit by hand.

SESSION_ID=""
EVENT_NAME="Stop"
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_-')
  EVENT_RAW=$(printf '%s' "$HOOK_INPUT" | sed -n 's/.*"hook_event_name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n 1)
  if [ "$EVENT_RAW" = "SubagentStop" ]; then
    EVENT_NAME="SubagentStop"
  fi
fi

# No session_id -> no dedup possible. Stay silent rather than risk a
# nudge -> conversation continues -> Stop -> nudge loop.
if [ -z "$SESSION_ID" ]; then
  exit 0
fi

# Stored sentinel: a store_memory call already happened -> nothing to nudge.
# Nudged sentinel: we already nudged once -> stay silent on re-entry.
STORED_SENTINEL="${TMPDIR:-/tmp}/automem-stored-${SESSION_ID}"
NUDGED_SENTINEL="${TMPDIR:-/tmp}/automem-stop-nudged-${SESSION_ID}"
if [ -e "$STORED_SENTINEL" ] || [ -e "$NUDGED_SENTINEL" ]; then
  exit 0
fi
# Write the sentinel before emitting so a re-entrant Stop sees it. If it
# can't be created (e.g. TMPDIR not writable), the once-per-session guarantee
# is gone, so stay silent rather than nudge on every Stop.
if ! : > "$NUDGED_SENTINEL" 2>/dev/null; then
  exit 0
fi

printf '{"suppressOutput":true,"hookSpecificOutput":{"hookEventName":"%s","additionalContext":%s}}\n' "$EVENT_NAME" '"Before stopping: no memories were stored this session. Check whether any durable facts emerged.\n\nStore via mcp__memory__store_memory ONLY if one of these fired:\n- A user correction or preference override -> type \"Preference\", importance 0.9, tag \"correction\"\n- A decision that survived discussion -> type \"Decision\", importance 0.85-0.9\n- A pattern the user articulated -> type \"Pattern\", importance 0.8\n- A root-cause insight from debugging -> type \"Insight\", importance 0.75, tags \"bugfix\" + \"solution\"\n\nUse bare tags (category + project slug). Run the atomic ritual: recall related -> store -> verify -> associate.\n\nIf nothing durable came up, stop normally - do NOT store session summaries, progress reports, or confirmations."'

# Advisory hook: always succeed even if printf hit a write error, so Claude
# Code never treats the Stop hook as failed and discards the JSON.
exit 0
