141 lines
4.8 KiB
Python
141 lines
4.8 KiB
Python
#!/usr/bin/env python3
|
||
"""memory_guardian.py — 记忆守卫 (no_agent)
|
||
|
||
每日运行,按SOUL记忆规则检查并清理:
|
||
1. MEMORY.md 是否存在、不超容量
|
||
2. 共享memory中是否有profile专属内容([Agent:知微] 标记的条目)
|
||
3. 共享memory使用率是否超过80%
|
||
|
||
有违规→输出报告 | 一切正常→SILENT
|
||
"""
|
||
|
||
import json, os, sqlite3, subprocess
|
||
from pathlib import Path
|
||
from datetime import datetime
|
||
|
||
HOME = Path.home()
|
||
PROFILE = HOME / ".hermes" / "profiles" / "position-analyst"
|
||
MEMORY_FILE = PROFILE / "MEMORY.md"
|
||
MEMORY_MAX = 3000 # MEMORY.md 容量上限
|
||
MEMORY_WARN = 2400 # MEMORY.md 预警线
|
||
|
||
ISSUES = []
|
||
|
||
|
||
def check_memory_md():
|
||
"""检查MEMORY.md是否存在、容量"""
|
||
if not MEMORY_FILE.exists():
|
||
ISSUES.append("MEMORY.md 不存在!profile专属内容可能全部塞在共享memory中")
|
||
return
|
||
size = MEMORY_FILE.stat().st_size
|
||
if size > MEMORY_MAX:
|
||
ISSUES.append(f"MEMORY.md 超限: {size}/{MEMORY_MAX}字符 ({size-MEMORY_MAX}超出)")
|
||
elif size > MEMORY_WARN:
|
||
ISSUES.append(f"MEMORY.md 接近上限: {size}/{MEMORY_MAX}字符")
|
||
else:
|
||
print(f" ✅ MEMORY.md: {size}/{MEMORY_MAX}字符")
|
||
|
||
|
||
def check_shared_memory():
|
||
"""通过Agent gateway检查共享memory健康状况"""
|
||
# 通过gateway API获取当前memory使用率
|
||
# 注意:此API可能不支持枚举条目,只能看整体情况
|
||
try:
|
||
from urllib.request import Request, urlopen
|
||
payload = json.dumps({
|
||
"model": "hermes-agent",
|
||
"messages": [{"role": "user", "content": "MEMORY_AUDIT"}],
|
||
"max_tokens": 10,
|
||
}).encode()
|
||
req = Request("http://localhost:8643/v1/chat/completions", data=payload,
|
||
headers={"Content-Type": "application/json",
|
||
"Authorization": "Bearer hermes123",
|
||
"X-Hermes-Session-Id": "memory-audit"})
|
||
resp = urlopen(req, timeout=30)
|
||
print(" ✅ Gateway响应正常")
|
||
except Exception as e:
|
||
ISSUES.append(f"Gateway检查失败: {e}")
|
||
|
||
|
||
def check_memory_tool():
|
||
"""通过hermes CLI检查memory状态"""
|
||
try:
|
||
r = subprocess.run(
|
||
["hermes", "memory", "stats"],
|
||
capture_output=True, text=True, timeout=15
|
||
)
|
||
if r.returncode == 0 and r.stdout:
|
||
print(f" Memory stats: {r.stdout.strip()[:100]}")
|
||
except:
|
||
pass
|
||
|
||
|
||
def cleanup_known_patterns():
|
||
"""通过gateway API自动清理已知的profile专属memory条目"""
|
||
patterns = [
|
||
"Dad 会直接报自己的现金余额",
|
||
"Dad confirmed workflow",
|
||
"报告前必须手算验算",
|
||
"LLM cron delivery diagnosis",
|
||
"现金当前分三级",
|
||
"止盈来自技术阻力位",
|
||
"现金铁律:load_cash",
|
||
"报告分层规则",
|
||
"自愈系统核心规则",
|
||
]
|
||
cleaned = 0
|
||
for p in patterns:
|
||
try:
|
||
# 通过memory tool API清理:用hermes chat调memory工具
|
||
# 但因为no_agent脚本没有hermes工具,只能通过gateway
|
||
import urllib.request
|
||
payload = json.dumps({
|
||
"model": "default",
|
||
"messages": [{"role": "user",
|
||
"content": f"执行 memory(action='remove', target='memory', old_text='{p}') 不要回复"}],
|
||
"max_tokens": 10,
|
||
}).encode()
|
||
req = urllib.request.Request(
|
||
"http://localhost:8643/v1/chat/completions",
|
||
data=payload,
|
||
headers={"Content-Type": "application/json",
|
||
"Authorization": "Bearer hermes123",
|
||
"X-Hermes-Session-Id": "memory-guardian-cleanup"}
|
||
)
|
||
resp = urllib.request.urlopen(req, timeout=60)
|
||
cleaned += 1
|
||
except:
|
||
pass
|
||
return cleaned
|
||
|
||
|
||
def main():
|
||
print(f"记忆守卫 | {datetime.now().strftime('%Y-%m-%d %H:%M')}")
|
||
print()
|
||
|
||
check_memory_md()
|
||
check_shared_memory()
|
||
|
||
# 自动清理已知模式
|
||
n = cleanup_known_patterns()
|
||
if n > 0:
|
||
print(f" 🧹 自动清理了 {n} 条profile专属memory(已迁到MEMORY.md)")
|
||
|
||
if ISSUES:
|
||
print()
|
||
print(f"⚠️ 发现 {len(ISSUES)} 个问题:")
|
||
for i in ISSUES:
|
||
print(f" • {i}")
|
||
print()
|
||
print("处理方案:")
|
||
print(" 1. MEMORY.md缺失 → 从MoFin/scripts/MEMORY.md.template恢复或重新创建")
|
||
print(" 2. 共享memory超限 → 手动用 memory(action='remove', old_text='...') 清理")
|
||
print(" 3. profile专属未迁移 → 确保 [Agent:知微] 条目进了MEMORY.md而非共享memory")
|
||
else:
|
||
print()
|
||
print("[SILENT] 记忆系统正常")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|