diff --git a/scripts/memory_guardian.py b/scripts/memory_guardian.py new file mode 100644 index 0000000..70ef6f2 --- /dev/null +++ b/scripts/memory_guardian.py @@ -0,0 +1,97 @@ +#!/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 main(): + print(f"记忆守卫 | {datetime.now().strftime('%Y-%m-%d %H:%M')}") + print() + + check_memory_md() + check_shared_memory() + check_memory_tool() + + 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()