diff --git a/scripts/memory_guardian.py b/scripts/memory_guardian.py index f22d701..2190673 100644 --- a/scripts/memory_guardian.py +++ b/scripts/memory_guardian.py @@ -3,27 +3,25 @@ 每日运行,按SOUL记忆规则检查并清理: 1. MEMORY.md 是否存在、不超容量 -2. 共享memory中是否有profile专属内容([Agent:知微] 标记的条目) -3. 共享memory使用率是否超过80% +2. 通过gateway自动清理共享memory中带[Agent:知微]的profile专属条目 +3. 报告结果给Dad 有违规→输出报告 | 一切正常→SILENT """ -import json, os, sqlite3, subprocess +import json, subprocess, urllib.request 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 预警线 - +MEMORY_MAX = 3000 +MEMORY_WARN = 2400 ISSUES = [] def check_memory_md(): - """检查MEMORY.md是否存在、容量""" if not MEMORY_FILE.exists(): ISSUES.append("MEMORY.md 不存在!profile专属内容可能全部塞在共享memory中") return @@ -36,101 +34,46 @@ def check_memory_md(): print(f" ✅ MEMORY.md: {size}/{MEMORY_MAX}字符") -def check_shared_memory(): - """通过Agent gateway检查共享memory健康状况""" - # 通过gateway API获取当前memory使用率 - # 注意:此API可能不支持枚举条目,只能看整体情况 +def cleanup_memory(): + """通过gateway自动清理共享memory中profile专属条目""" try: - from urllib.request import Request, urlopen payload = json.dumps({ - "model": "hermes-agent", - "messages": [{"role": "user", "content": "MEMORY_AUDIT"}], - "max_tokens": 10, + "model": "default", + "messages": [{"role": "user", + "content": "清理共享memory中所有带[Agent:知微]标签或Session:2026的条目。" + "这些应该放在MEMORY.md而非共享memory。" + "用memory(action='remove', old_text='唯一子串')逐条删除。" + "完成后回复'清理完成'。"}], + "max_tokens": 100, }).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 + 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"} ) - 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 + resp = urllib.request.urlopen(req, timeout=120) + result = json.loads(resp.read()) + reply = result["choices"][0]["message"]["content"] + return "清理完成" in reply, reply[:200] + except Exception as e: + return False, str(e)[:200] 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)") + + ok, detail = cleanup_memory() + print(f" {'✅' if ok else '⚠️'} 共享memory清理: {'已完成' if ok else detail}") 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] 记忆系统正常")