📝 添加新记忆日志和脚本 - 2026-03-23

This commit is contained in:
huan
2026-03-23 15:44:04 +08:00
parent 3746d9410a
commit 427d63563c
4 changed files with 353 additions and 0 deletions
+77
View File
@@ -0,0 +1,77 @@
#!/usr/bin/env python3
"""
上下文使用量检测脚本
当任一 session 上下文使用量 >= 90% 时自动保存记忆
"""
import subprocess
import re
import os
from datetime import datetime
# 加载环境变量
os.environ["SILICONFLOW_API_KEY"] = "sk-fpjdtxbxrhtekshircjhegstloxaodriekotjdyzzktyegcl"
def log(msg):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"[{timestamp}] {msg}")
def main():
log("========== 上下文使用量检测 ==========")
# 获取 OpenClaw 状态
result = subprocess.run(["openclaw", "status"], capture_output=True, text=True)
status_output = result.stdout
# 提取所有上下文使用量百分比
# 格式: "109k/200k (54%)" - 括号内是使用量
max_usage = 0
for line in status_output.split('\n'):
# 跳过表头和无关行
if '│ Tokens' in line or '' in line or '│ Key' in line:
continue
if 'FAQ:' in line or 'Troubleshooting:' in line:
continue
if 'Sessions' in line and '200k ctx' in line:
continue
# 查找类似 "109k/200k (54%)" 的模式
match = re.search(r'(\d+)k/200k \((\d+)%\)', line)
if match:
usage = int(match.group(2))
if usage > max_usage:
max_usage = usage
log(f"📊 当前最高上下文使用量: {max_usage}%")
if max_usage >= 90:
log(f"⚠️ 上下文使用量达到 {max_usage}%,开始保存记忆...")
# 1. 保存文件记忆
memory_file = f"{os.path.expanduser('~')}/.openclaw/workspace/memory/{datetime.now().strftime('%Y-%m-%d')}.md"
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(memory_file, "a") as f:
f.write(f"\n## 🔄 上下文自动保存 ({timestamp})\n\n")
f.write(f"**触发原因**: 上下文使用量达到 {max_usage}%\n\n")
log("✅ 文件记忆已更新")
# 2. 保存向量记忆
os.chdir(os.path.expanduser("~/openclaw-memory-vector"))
subprocess.run([
"python3", "memory_cli.py", "add",
f"【自动保存】上下文使用量达到 {max_usage}%,系统自动保存记忆。时间: {timestamp}",
"--tag", "auto-save,context-90"
], capture_output=True, text=True)
log("✅ 向量记忆已保存")
log("✅ 记忆保存完成")
else:
log(f"✅ 上下文使用量正常 ({max_usage}%),无需保存")
log("========== 检测完成 ==========\n")
if __name__ == "__main__":
main()
+79
View File
@@ -0,0 +1,79 @@
#!/bin/bash
# ============================================
# 上下文使用量检测 & 记忆自动保存脚本
# 当任一 session 上下文使用量 >= 90% 时自动保存记忆
# ============================================
set -e
# 加载环境变量
export SILICONFLOW_API_KEY="sk-fpjdtxbxrhtekshircjhegstloxaodriekotjdyzzktyegcl"
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. 保存向量记忆
cd ~/openclaw-memory-vector && python3 memory_cli.py add \
"【自动保存】上下文使用量达到 ${MAX_USAGE}%,系统自动保存记忆。时间: ${TIMESTAMP}" \
--tag "auto-save,context-90" 2>&1 | tail -1
log "✅ 向量记忆已保存"
log "✅ 记忆保存完成"
else
log "✅ 上下文使用量正常 (${MAX_USAGE}%),无需保存"
fi
log "========== 检测完成 ==========\n"