#!/usr/bin/env bash
# auto-checkpoint.sh — 会话 checkpoint（compact 前自动调用）
# 把当前会话的关键信息刷出对话历史，减少上下文膨胀带来的 token 开销

WORKSPACE="$(cd "$(dirname "$0")/.." && pwd)"
MEMORY_SERVER="http://111.229.145.18"
DAILY="$WORKSPACE/memory/daily/$(date +%Y-%m-%d).md"
NOW=$(date +%H:%M)

# 生成一条会话摘要（从 daily 最后一段提取）
SUMMARY=$(tail -20 "$DAILY" 2>/dev/null | grep '^\[' | tail -1 | sed 's/^\[//;s/\]//;s/^[^:]*://' | head -c 300)

# 如果 daily 没有合适的摘要，手动给一个
if [ -z "$SUMMARY" ]; then
    SUMMARY="[$NOW] 会话 checkpoint — 上下文已 compact"
fi

# 写进 daily
echo "" >> "$DAILY"
echo "[checkpoint $NOW] $SUMMARY" >> "$DAILY"

# 推送远程记忆
curl -s --max-time 5 -X POST "$MEMORY_SERVER/api/v2/add" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: xl_134…220f" \
  -d "{\"content\":\"$SUMMARY\",\"type\":\"checkpoint\",\"project\":\"xiaolong\",\"source\":\"auto-checkpoint\"}" > /dev/null 2>&1

echo "✅ Checkpoint done: $SUMMARY"
