#!/bin/bash
# PreCompact hook: save session state before Claude Code compacts conversation context
# When compaction happens, earlier conversation details can be lost.
# This hook snapshots key state so it can be recovered.
# NOTE: This script needs chmod +x to be executable
PROJECT_DIR="$(cd "$(dirname "$0")/../.." && pwd)"
DATE=$(date +%Y-%m-%d)
TIME=$(date +%H:%M:%S)

# Only run if .session/ exists (session is active)
if [ ! -d "$PROJECT_DIR/.session" ]; then
    exit 0
fi

PRECOMPACT="$PROJECT_DIR/.session/pre-compact.md"

# Read current state file for goals and progress
STATE_CONTENT=""
if [ -f "$PROJECT_DIR/.session/state.md" ]; then
    STATE_CONTENT=$(cat "$PROJECT_DIR/.session/state.md")
fi

# Read checkpoint for files modified
CHECKPOINT_CONTENT=""
if [ -f "$PROJECT_DIR/.session/checkpoint.md" ]; then
    CHECKPOINT_CONTENT=$(cat "$PROJECT_DIR/.session/checkpoint.md")
fi

# Get recent git changes in this session
RECENT_COMMITS=$(git -C "$PROJECT_DIR" log --oneline -5 2>/dev/null || echo "(no commits)")

# Write pre-compaction snapshot
cat > "$PRECOMPACT" << EOF
# Pre-Compaction Snapshot

**Saved at:** $DATE $TIME
**Reason:** Context compaction detected — saving state before details are lost

## Session State at Time of Compaction
$STATE_CONTENT

## Checkpoint at Time of Compaction
$CHECKPOINT_CONTENT

## Recent Commits
$RECENT_COMMITS

## Recovery Note
If you're reading this after a compaction, the above captures what was happening
before context was compressed. Read .session/state.md for goals and
.session/checkpoint.md for the last action taken.
EOF
