Files
openclaw-home-pc/scripts/context_memory_guard.sh
T

73 lines
2.2 KiB
Bash
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/bin/bash
# ============================================
# 上下文使用量检测 & 记忆自动保存脚本
# 当任一 session 上下文使用量 >= 90% 时自动保存记忆
# ============================================
set -e
LOG_FILE="/tmp/openclaw/context_memory_check.log"
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
log() {
echo "[$TIMESTAMP] $1" | tee -a "$LOG_FILE"
}
log "========== 上下文使用量检测 =========="
# 获取 OpenClaw 状态中的 Tokens 信息
STATUS_OUTPUT=$(openclaw status 2>&1)
# 提取所有会话的上下文使用量(排除 cached 百分比)
# 格式: "109k/200k (54%)" - 括号内的数字是上下文使用量
# cached 格式: "🗄️ 42% cached" - 这不是上下文使用量
MAX_USAGE=0
# 逐行处理
while IFS= read -r line; do
# 跳过表头和分隔符
if echo "$line" | grep -q "│.*Tokens"; then
continue
fi
if echo "$line" | grep -q "├"; then
continue
fi
if echo "$line" | grep -q "│ Key"; then
continue
fi
if echo "$line" | grep -q "FAQ:\|Troubleshooting:"; then
continue
fi
# 提取 "XXXk/YYYk (NN%)" 格式中的数字
# 格式如: 109k/200k (54%)
usage=$(echo "$line" | grep -oE '[0-9]+k/[0-9]+k \([0-9]+\)%' | grep -oE '\([0-9]+\)' | tr -d '()' || true)
if [ -n "$usage" ]; then
if [ "$usage" -gt "$MAX_USAGE" ]; then
MAX_USAGE=$usage
fi
fi
done <<< "$STATUS_OUTPUT"
log "📊 当前最高上下文使用量: ${MAX_USAGE}%"
# 检查是否达到 90% 阈值
if [ "$MAX_USAGE" -ge 90 ]; then
log "⚠️ 上下文使用量达到 ${MAX_USAGE}%,开始保存记忆..."
# 1. 保存文件记忆
MEMORY_FILE="$HOME/.openclaw/workspace/memory/$(date '+%Y-%m-%d').md"
echo -e "\n## 🔄 上下文自动保存 (${TIMESTAMP})\n\n**触发原因**: 上下文使用量达到 ${MAX_USAGE}%\n" >> "$MEMORY_FILE"
log "✅ 文件记忆已更新"
# 2. 文件记忆已保存(向量记忆统一走 main.sqlite
log "✅ 文件记忆已更新"
log "✅ 记忆保存完成"
else
log "✅ 上下文使用量正常 (${MAX_USAGE}%),无需保存"
fi
log "========== 检测完成 ==========\n"