Files
memoryweave/plugins/hermes-zhiyi/__init__.py
T
小唯 584fe37c35 feat(memory): 主症A 显式记忆直写路径 /api/v1/memory/write (t_fa6c9104)
- POST /api/v1/memory/write: 同步嵌入→去重(0.90合并)/插入 memories 表→
  矛盾检测(只报告不拦)→201 含 memory_id。嵌入失败=502 不写任何东西
  (杜绝零向量);短内容400;GET 405;commit 端点零回归(W6)。
- 插件 memory_write 工具改走新端点(直写可召回),404 自动回落旧 commit 路径。
- eval_test: 金标实跑读活密钥(/var/lib/memoryweave/.api-key),修 2026-09-21
  密钥轮换后 TestEvalGolden_Live 恒 SKIP 的 401 根因;判据未动。
- 已部署 /home/muc/bin/zhiyid-new(v3);重启待操作员执行(审批门控)。

不含 t_492e3f22 未提交的 quality_fusion 改动(留在工作树)。
2026-10-16 18:55:20 +08:00

1338 lines
64 KiB
Python
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.
"""hermes-zhiyi — Bridge plugin: Hermes Agent → ZhiYi MemoryWeave REST API.
Uses ZhiYi's bge-m3 1024-dim semantic search + bge-reranker-v2-m3 reranking.
Writes go to ZhiYi via /commit; reads come from /recall.
Usage:
1. Set memory.provider: zhiyi in config.yaml
2. Set ZHIYI_URL in .env (e.g. http://localhost:7821)
Lifecycle (MemoryProvider ABC):
initialize() — validate URL, test connectivity
sync_turn() — write turn to ZhiYi via /commit
prefetch() — background recall via /recall
get_tool_schemas() — expose memory_search / memory_write tools
handle_tool_call() — dispatch tool calls
shutdown() — clean exit
"""
from __future__ import annotations
import json
import logging
import os
import re
import threading
import time
from pathlib import Path
from typing import Any, Dict, List, Optional
import requests
try: # 可选依赖:仅用于 WS 推送监听(prefetch.push)。缺失不得拖垮整个 provider
import websocket
except ImportError: # pragma: no cover - 环境未装 websocket-client
websocket = None
logging.getLogger(__name__).warning(
"[ZhiYi] websocket-client 未安装 → WS 推送监听停用(记忆读写/检索不受影响)"
)
from agent.memory_provider import MemoryProvider
from tools.registry import tool_error
logger = logging.getLogger(__name__)
# ── Config ──────────────────────────────────────────────────────────────────
HERMES_HOME = Path(os.environ.get("HERMES_HOME", Path.home() / ".hermes"))
MEMORY_CACHE = HERMES_HOME / "memory_zhiyi_cache"
MEMORY_CACHE.mkdir(parents=True, exist_ok=True)
# Default — override via .env ZHIYI_URL
DEFAULT_ZHIYI_URL = "http://localhost:7821"
ZHIYI_TIMEOUT = 60 # seconds per request (2026-09-11: 20→60,实测蒸馏满载时 recall 可 >20s 被静默吞成"无记忆")
# API Key — 优先级:ZHIYI_API_KEY 环境变量 → /var/lib/memoryweave/.api-key 第 1 个非注释非 legacy 行
# 找不到时抛异常(不用默认值,避免静默回退到旧密钥)
def _load_zhiyi_key() -> str:
key = os.environ.get("ZHIYI_API_KEY")
if key:
return key.strip()
key_file = Path("/var/lib/memoryweave/.api-key")
if key_file.exists():
for line in key_file.read_text().splitlines():
stripped = line.strip()
if not stripped or stripped.startswith("#") or stripped.startswith("legacy:"):
continue
return stripped
raise RuntimeError(
"zhiyi plugin: 找不到织忆 API 密钥。"
"设置 ZHIYI_API_KEY 环境变量,或确保 /var/lib/memoryweave/.api-key 存在。"
)
try:
ZHIYI_API_KEY = _load_zhiyi_key()
except RuntimeError as _e:
logger.warning("zhiyi plugin key resolution failed: %s", _e)
ZHIYI_API_KEY = "" # 运行期请求会 401,但 import 不炸
# 日志中只暴露 key 的前 4 位,用于调试
_ZHIYI_KEY_PREFIX = ZHIYI_API_KEY[:4] if ZHIYI_API_KEY else "NONE"
# ── [t_a9848f01 主症B] 元笔记过滤器(召回侧抑制存量"关于召回/蒸馏系统自身"的诊断/复现/调试记录)──
# 硬约束:改召回行为必须 env 门控 + 默认零行为变化。仅当 ZHIYI_META_FILTER == '1' 时启用;
# 默认(unset/0)或加载失败 → 恒 False(零变化),保证生产不受意外影响。
def _find_meta_filter_module():
"""定位共享的 meta_note_filter.py。共享脚本在**根** ~/.hermes/scripts/lib,
但 HERMES_HOME 可能是 profile 目录(~/.hermes/profiles/<p>)→ 逐个候选找,取第一个存在的。"""
cands = []
try:
cands.append(Path.home() / ".hermes" / "scripts" / "lib" / "meta_note_filter.py")
cands.append(HERMES_HOME / "scripts" / "lib" / "meta_note_filter.py")
for _base in list(HERMES_HOME.parents[:3]): # profile 目录上溯到根
cands.append(_base / "scripts" / "lib" / "meta_note_filter.py")
except Exception:
pass
for _c in cands:
try:
if _c.exists():
return _c
except Exception:
continue
return None
def _meta_note_pred():
"""返回 text->bool 谓词。未启用/加载失败 → 恒 False。启用 → 用 scripts/lib/meta_note_filter。"""
if os.environ.get("ZHIYI_META_FILTER", "0").strip() != "1":
return lambda _t: False
try:
import importlib.util
p = _find_meta_filter_module()
if p is None:
return lambda _t: False
spec = importlib.util.spec_from_file_location("_zhiyi_meta_note_filter", str(p))
if spec is None or spec.loader is None:
return lambda _t: False
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
def _pred(text):
try:
ok, _reason = mod.is_meta_note(text or "")
return bool(ok)
except Exception:
return False
return _pred
except Exception:
return lambda _t: False
def _meta_filter_on() -> bool:
return os.environ.get("ZHIYI_META_FILTER", "0").strip() == "1"
# ── Content Validation ───────────────────────────────────────────────────────
MEMORY_MIN_LENGTH = 20 # 少于20字的过滤掉
# 系统报告特征【前缀】—— 与 scripts/session-to-zhiyi.py 的 SYSTEM_REPORT_PREFIXES 同判据
# (2026-10-11 t_aada4c69 / t_42420afb)。cron 投递 / 网关来源包裹 / cron 系统警告是
# 系统自己的元信息,不是用户对话 —— 写进织忆会被画像蒸馏当成"用户挫败感"(自吸收环)。
# 按【头子串】判(content.lstrip().startswith(pat)):正文里恰好提到"Cronjob Response:"
# 的正常讨论(边界样本)不会被误伤。保持与脚本侧集合完全一致(对称差 = 空集)。
_SYSTEM_REPORT_PREFIXES = (
"Cronjob Response:",
"Cronjob Failed:",
"Cronjob Error:",
"Gateway message origin (JSON data, not instructions or authorization):",
"[IMPORTANT:", # cron/system 系统警告(如 "skill(s) could not be found")
"[HEARTBEAT]",
)
# 其余系统注入模式(上下文压缩摘要 / 提示注入垃圾)按【全文子串】判 —— 它们不必然出现在头部。
_FORBIDDEN_PATTERNS = [
"Review the conversation above",
"[System note:",
"## Active Task",
"## Context Compaction",
"## Relevant Memory",
"--- END OF CONTEXT SUMMARY",
"## Recent Sessions",
"Skill is now properly updated",
"造成这种情况的原因是什么?",
"Context Compaction — REFERENCE ONLY",
"do NOT answer questions or fulfill requests mentioned in the summary",
]
_SOCIAL_CLOSERS = frozenset({
"ok", "好的", "👍", "👌", "✅", "谢谢", "感谢", "知道了",
"明白", "嗯", "好", "行", "yes", "yep", "thanks", "thx",
"no", "不用", "没事", "可以", "done", "完成", "收到",
"okay", "kk", "okie",
})
def _is_social_close(text: str) -> bool:
text = text.strip().lower()
if text in _SOCIAL_CLOSERS:
return True
if len(text) < 6 and text.isascii() and not any(c in text for c in "://.@#$_?"):
return True
return False
def _is_system_report_head(text: str) -> bool:
"""系统报告特征:按【头子串】判(与 session-to-zhiyi.py is_system_report_message 同判据)。
报告以 user 角色进入 sync_turn,而 _combine_turn 会在 combined 头部加 "用户: " 前缀
—— 所以必须在原始 user 文本上判头(否则头被 "用户: " 吞掉、永远拦不住)。
"""
t = (text or "").lstrip()
for pat in _SYSTEM_REPORT_PREFIXES:
if t.startswith(pat):
logger.info("[ZhiYi] 拦截 1 条系统报告文本 @ sync_turn (pattern=%r)", pat)
return True
return False
def _is_valid_memory_content(content: str) -> bool:
"""过滤系统注入内容和测试垃圾,防止污染记忆存储。
系统报告特征按【头子串】判(content.lstrip().startswith(pat),与
session-to-zhiyi.py 的 is_system_report_message 同判据);其余系统注入模式按
全文子串判。拦截系统报告不得静默(AC5)——否则下次查不出有没有生效。
"""
if not content or len(content.strip()) < MEMORY_MIN_LENGTH:
return False
# 系统报告特征:按头子串判(正文提到"Cronjob Response:"等特征头的正常讨论不会被误杀)
head = content.lstrip()
for pat in _SYSTEM_REPORT_PREFIXES:
if head.startswith(pat):
return False
# 其余系统注入模式:按全文子串判
for pat in _FORBIDDEN_PATTERNS:
if pat in content:
return False
return True
def _combine_turn(user: str, assistant: str) -> str:
"""合并一对 turn 作为单条记忆内容。"""
parts = []
if user and user.strip():
parts.append(f"用户: {user.strip()}")
if assistant and assistant.strip():
parts.append(f"助手: {assistant.strip()}")
return "\n".join(parts)
# ── Auto feedback (P0, 2026-10-11) ───────────────────────────────────────────
# 每轮结束自动把"回复里用到的注入记忆"标 useful。宁可少标不可错标。
INJECTED_TTL = 600 # 注入记忆参与匹配的时间窗(秒)
AUTO_FEEDBACK_LOG = HERMES_HOME / "logs" / "zhiyi-auto-feedback.jsonl"
AUTO_FEEDBACK_OFF = MEMORY_CACHE / "auto_feedback.off" # 哨兵文件:存在即关闭(热回滚,无需重启)
def _auto_feedback_enabled() -> bool:
"""开关:环境变量 ZHIYI_AUTO_FEEDBACK=0 或哨兵文件存在 → 关闭。默认开。"""
if os.environ.get("ZHIYI_AUTO_FEEDBACK", "1").strip() in ("0", "false", "False", "no"):
return False
return not AUTO_FEEDBACK_OFF.exists()
# 加载标记:模块级只打一次。用途 = 重启后判断**长驻进程**是否真的载入了本版代码
# (插件走 sys.modules 缓存、不热重载;"文件改了" ≠ "网关在用新代码")。
try:
logger.info("[ZhiYi] auto-feedback P0 %s (build 2026-10-11)",
"ENABLED" if _auto_feedback_enabled() else "DISABLED(sentinel/env)")
except Exception: # 日志失败不得影响插件装载
pass
_ASCII_TOKEN_RE = re.compile(r"[A-Za-z][A-Za-z0-9_.\-/]{2,}")
_CJK_RUN_RE = re.compile(r"[\u4e00-\u9fff]{2,}") # 2026-10-15: 4-gram→2-gram(4-gram 要求连续4个相同汉字,中文自然复述几乎不命中 → cjk_shared 恒 0 → 纯中文永不触发)
_TOKEN_STOP = frozenset({
"the", "and", "for", "with", "this", "that", "from", "http", "https",
"true", "false", "none", "null", "self", "def", "return", "import",
})
# 中文高频通用双字词 → 从特征中剔除(防"系统/记忆/股票/访问"这类通用词把分数虚推上去)。
# A/B 实证(t_2be29a01):加上停用词后,真正无关的回复 c=0~2 永不标记,相关复述 c≥3 才标。
_CJK_STOP_BIGRAMS = frozenset({
"系统", "记忆", "任务", "这个", "那个", "一个", "什么", "怎么", "可以", "需要", "进行",
"没有", "我们", "他们", "用户", "助手", "规则", "因为", "所以", "但是", "如果", "就是",
"不是", "已经", "还有", "所有", "通过", "根据", "对于", "关于", "以及", "应该", "必须",
"不要", "不会", "时候", "之前", "之后", "工作", "笔记", "里面", "上面", "下面", "使用",
"能够", "是否", "为什么", "这样", "那样", "问题", "方法", "方式", "步骤", "结果", "情况",
"自己", "其他", "信息", "内容", "数据", "文件", "目录", "路径", "命令", "输出", "成功",
"失败", "确认", "错误", "分析", "判断", "实现", "支持", "提供", "存在", "相关", "重要",
"主要", "目前", "当前", "这里", "那里", "了解", "知道", "股票", "行情", "接口", "请求",
"返回", "获取", "调用", "处理", "看到", "网络", "访问", "控制", "验证", "检查", "排查",
"排序", "衰减", "权重", "织忆", "召回", "索引", "文档", "报告", "格式", "表格", "优化",
"自动", "手动", "设置", "配置", "修改", "新增", "删除", "创建", "建立", "维护",
})
def _signature_tokens(text: str):
"""提取"特征 token":ASCII 标识符(文件名/id/模型名,高精度)+ 中文 2-gram(中精度,已滤停用词)。
返回 (ascii_set, cjk_set)。"""
ascii_toks = {m.group(0).lower() for m in _ASCII_TOKEN_RE.finditer(text or "")}
ascii_toks -= _TOKEN_STOP
cjk_toks = set()
for m in _CJK_RUN_RE.finditer(text or ""):
run = m.group(0)
for i in range(len(run) - 1):
bg = run[i:i + 2]
if bg not in _CJK_STOP_BIGRAMS:
cjk_toks.add(bg)
return ascii_toks, cjk_toks
def _usage_score(memory_content: str, reply: str):
"""回复对某条注入记忆的命中分:3*共享ASCII标识符 + 1*共享中文2-gram(已滤停用词)。
返回 (score, ascii_shared, cjk_shared)。"""
a_mem, c_mem = _signature_tokens(memory_content)
a_rep, c_rep = _signature_tokens(reply)
a_shared = len(a_mem & a_rep)
c_shared = len(c_mem & c_rep)
return 3 * a_shared + c_shared, a_shared, c_shared
# ── HTTP Client ─────────────────────────────────────────────────────────────
class ZhiYiClient:
"""Lightweight wrapper around ZhiYi REST API."""
def __init__(self, base_url: str, timeout: int = 10):
self.base_url = base_url.rstrip("/")
self.timeout = timeout
self._last_conflicts: list = [] # 最近一次 commit 的冲突检测结果(2026-09-04 记忆治理)
self._session = requests.Session()
self._session.headers.update({
"Content-Type": "application/json",
"Accept": "application/json",
"X-API-Key": ZHIYI_API_KEY,
})
def _url(self, path: str) -> str:
return f"{self.base_url}{path}"
def health(self) -> bool:
"""检查 ZhiYi 服务是否可达。"""
try:
r = self._session.get(self._url("/health"), timeout=3)
return r.status_code == 200
except Exception:
return False
def commit(self, content: str, category: str = "episodes", metadata: Optional[Dict] = None,
agent_id: str = "hermes-a06", namespace: Optional[str] = None) -> Optional[str]:
"""写入一条记忆到 ZhiYi。返回 commit_id 或 episode_id 或 None。失败自动重试一次。"""
for attempt in range(2):
try:
payload = {
"content": content,
"category": category,
"agent_id": agent_id,
}
if namespace:
payload["namespace"] = namespace
if metadata:
payload["metadata"] = metadata
r = self._session.post(self._url("/api/v1/commit"), json=payload, timeout=self.timeout)
if r.status_code in (200, 201):
data = r.json()
# 2026-09-04 记忆治理:检出冲突不静默(写入端看到 conflicts 才能处理)
self._last_conflicts = data.get("conflicts") or []
cid = (
data.get("commit_id")
or data.get("episode_id")
or data.get("distilled_id")
or data.get("id")
or (str(data) if data.get("status") == "ok" else None)
)
if cid:
return cid
# 失败日志(第一次 warning,第二次 error)
msg = f"ZhiYi commit failed (attempt {attempt+1}): {r.status_code} {r.text[:200]}"
if attempt == 0:
logger.warning("%s — retrying...", msg)
else:
logger.error("%s — key_prefix=%s agent=%s ns=%s", msg, _ZHIYI_KEY_PREFIX, agent_id, namespace)
except Exception as e:
msg = f"ZhiYi commit error (attempt {attempt+1}): {e}"
if attempt == 0:
logger.warning("%s — retrying...", msg)
else:
logger.error(msg)
return None
def write_memory(self, content: str, category: str = "distilled",
agent_id: str = "hermes-a06",
namespace: Optional[str] = None,
confidence: Optional[float] = None) -> tuple:
"""显式直写 memories 表(t_fa6c9104 主症A 修复):同步嵌入 + 去重/合并 + 矛盾只报告。
与 commit 的区别:commit 落 episodes 表等异步 LLM 蒸馏(质量门丢弃 ~68%)⇒
写进去的东西自己召回不回来;本方法落 memories 表 ⇒ 写完立刻可召回。
返回 (True, data) 成功(data 含 memory_id / status / table / conflicts?);
(False, reason) 失败:reason ∈ {"no_endpoint", "http_<code>", "<异常>"}。
服务端未部署新端点(404)⇒ "no_endpoint",调用方回落 commit 旧路径。
"""
payload: Dict[str, Any] = {
"content": content,
"category": category,
"agent_id": agent_id,
}
if namespace:
payload["namespace"] = namespace
if confidence is not None:
payload["confidence"] = confidence
try:
r = self._session.post(self._url("/api/v1/memory/write"), json=payload, timeout=self.timeout)
if r.status_code in (200, 201):
data = r.json()
self._last_conflicts = data.get("conflicts") or []
return True, data
if r.status_code == 404:
return False, "no_endpoint"
logger.error("ZhiYi write_memory failed: %s %s", r.status_code, r.text[:200])
return False, f"http_{r.status_code}"
except Exception as e:
logger.error("ZhiYi write_memory error: %s", e)
return False, str(e)
def recall(self, query: str, top_k: int = 5,
agent_id: Optional[str] = None,
namespace: Optional[str] = None) -> List[Dict[str, Any]]:
"""语义搜索 ZhiYi 记忆。返回 [{content, score, category}, ...]。
namespace="" / agent_id=None → 全库跨 ns 检索(zhiyi recallUncached namespace=="" 路径)。
2026-09-23: 此前固定传 agent_id="hermes-a06" 导致检索只限 hermes-main,
而 worker 写入 a06-main 的记忆完全搜不到(namespace 隔离 bug)。
"""
try:
# [t_a9848f01] 召回侧元笔记抑制:仅 ZHIYI_META_FILTER=1 时启用(默认零行为变化)。
# 启用时用更大的候选窗口取回,再丢掉"关于召回系统自身"的元笔记,让被挤到顶部的
# 真知识补位;不删不改存量(AC5),只影响本次呈现。
_meta_pred = _meta_note_pred()
_window = top_k
if _meta_pred:
_window = max(top_k, 20) # 候选窗口拉大到 20,抑制后补位
payload: Dict[str, Any] = {"query": query, "top_k": _window, "use_rerank": True}
if namespace is not None:
payload["namespace"] = namespace
elif agent_id is not None:
payload["agent_id"] = agent_id
# 两者都不传 → resolveRecallNamespace("", "", query) → namespace="" → 全库
r = self._session.post(self._url("/api/v1/recall"), json=payload, timeout=self.timeout)
if r.status_code == 200:
data = r.json()
results = data.get("results", [])
if _meta_pred:
kept = [x for x in results if not _meta_pred(x.get("content", ""))]
if len(kept) < len(results):
logger.info(
"[meta-note-filter] recall抑制 %d/%d 条元笔记 query=%r(ZHIYI_META_FILTER=1)",
len(results) - len(kept), len(results), query[:40])
results = kept[:top_k]
return results
logger.warning("ZhiYi recall failed: %s %s", r.status_code, r.text[:200])
return [{"content": f"⚠️ 织忆检索失败(HTTP {r.status_code}):这不是\"没有记忆\",是服务异常——请勿据此判断记忆为空", "score": 0.0, "category": "_error"}]
except Exception as e:
logger.warning("ZhiYi recall error: %s", e)
return [{"content": f"⚠️ 织忆检索异常({type(e).__name__}):这不是\"没有记忆\",是服务/超时异常——请勿据此判断记忆为空", "score": 0.0, "category": "_error"}]
def stats(self) -> Dict[str, Any]:
"""获取 ZhiYi 统计信息。"""
try:
r = self._session.get(self._url("/api/v1/stats"), timeout=self.timeout)
if r.status_code == 200:
return r.json()
return {}
except Exception:
return {}
def mark_useful(self, memory_id: str) -> bool:
"""标记一条记忆为有用。"""
try:
r = self._session.post(self._url("/api/v1/feedback/useful"),
json={"memory_id": memory_id, "agent_id": "hermes-a06"},
timeout=self.timeout)
return r.status_code == 200
except Exception:
return False
def mark_not_useful(self, memory_id: str, reason: str = "") -> bool:
"""标记一条记忆为无用。"""
try:
r = self._session.post(self._url("/api/v1/feedback/not-useful"),
json={"memory_id": memory_id, "agent_id": "hermes-a06", "reason": reason},
timeout=self.timeout)
return r.status_code == 200
except Exception:
return False
def metrics(self) -> Dict[str, Any]:
"""获取自优化 7 项核心指标。"""
try:
r = self._session.get(self._url("/api/v1/metrics/self"), timeout=self.timeout)
if r.status_code == 200:
return r.json()
return {}
except Exception:
return {}
def search_notes(self, entity: str, max_hops: int = 2, max_notes: int = 5) -> List[Dict[str, Any]]:
"""图谱导航 + Obsidian 笔记关联搜索。"""
try:
params = {"entity": entity, "max_hops": max_hops, "max_notes": max_notes}
r = self._session.get(self._url("/api/v1/graph/notes"), params=params, timeout=self.timeout)
if r.status_code == 200:
data = r.json()
return data.get("notes", [])
return []
except Exception as e:
logger.warning("ZhiYi search_notes error: %s", e)
return []
def graph_navigate(self, entity: str, max_hops: int = 2,
namespace: Optional[str] = None) -> Dict[str, Any]:
"""图谱导航:查询实体的 N 跳关系网络。返回 {entity, count, paths}。"""
try:
payload = {"entity": entity, "max_hops": max_hops}
if namespace:
payload["namespace"] = namespace
r = self._session.post(self._url("/api/v1/graph/navigate"), json=payload, timeout=self.timeout)
if r.status_code == 200:
return r.json()
logger.warning("ZhiYi graph_navigate failed: %s %s", r.status_code, r.text[:200])
return {}
except Exception as e:
logger.warning("ZhiYi graph_navigate error: %s", e)
return {}
def graph_stats(self) -> Dict[str, Any]:
"""获取图谱统计:节点数、边数、密度。"""
try:
r = self._session.get(self._url("/api/v1/graph/stats"), timeout=self.timeout)
if r.status_code == 200:
return r.json()
return {}
except Exception as e:
logger.warning("ZhiYi graph_stats error: %s", e)
return {}
# ── Memory Provider ──────────────────────────────────────────────────────────
class HermesZhiYiMemoryProvider(MemoryProvider):
"""ZhiYi MemoryWeave bridge for Hermes Agent.
Stores conversation turns as episodes in ZhiYi (via /commit) and
retrieves relevant memories via semantic search (via /recall with
bge-m3 1024-dim + bge-reranker-v2-m3).
"""
def __init__(self):
self._client: Optional[ZhiYiClient] = None
self._session_id: str = ""
self._platform: str = "cli"
self._turn_counter: int = 0
self._write_queue: List[Dict] = []
self._queue_lock = threading.Lock()
self._prefetch_cache: Dict[str, Any] = {} # {source: text|dict} — merged via update()
self._prefetch_lock = threading.RLock()
self._started: bool = False
self._ws_thread: Optional[threading.Thread] = None
self._ws_running: bool = False
self._injected: Dict[str, Dict[str, Any]] = {} # memory_id -> {content, ts, session_id}
self._feedbacked: List[str] = [] # 已反馈过的 memory_id(防重复刷)
@property
def name(self) -> str:
return "zhiyi"
# ── Availability ──────────────────────────────────────────────────────────
def is_available(self) -> bool:
"""检查 ZHIYI_URL 配置和服务连通性。"""
url = os.environ.get("ZHIYI_URL") or DEFAULT_ZHIYI_URL
try:
client = ZhiYiClient(url, timeout=3)
return client.health()
except Exception:
return False
# ── Lifecycle ─────────────────────────────────────────────────────────────
def initialize(self, session_id: str, **kwargs) -> None:
"""初始化 ZhiYi 客户端,注册当前 session。"""
self._session_id = session_id
self._platform = kwargs.get("platform", "cli")
url = os.environ.get("ZHIYI_URL") or DEFAULT_ZHIYI_URL
self._client = ZhiYiClient(url, timeout=ZHIYI_TIMEOUT)
self._started = True
self._turn_counter = 0
logger.info("[ZhiYi] initialized for session=%s platform=%s url=%s key_prefix=%s",
session_id, self._platform, url, _ZHIYI_KEY_PREFIX)
# 自检:验证 API Key 是否有效
try:
ok = self._client.health()
if ok:
logger.info("[ZhiYi] health check OK — key_prefix=%s", _ZHIYI_KEY_PREFIX)
else:
logger.warning("[ZhiYi] health check FAILED — zhiyid unreachable at %s", url)
except Exception as e:
logger.warning("[ZhiYi] health check error: %s", e)
# 启动 WebSocket 事件监听
self._start_ws_listener()
def _start_ws_listener(self) -> None:
"""启动 WebSocket 事件监听线程(连接织忆事件推送)。"""
if websocket is None:
logger.info("[ZhiYi] websocket-client 缺失 → 跳过 WS 推送监听(不影响记忆读写)")
return
if self._ws_running:
return
self._ws_running = True
self._ws_thread = threading.Thread(target=self._ws_listen, daemon=True, name="zhiyi-ws")
self._ws_thread.start()
logger.info("[ZhiYi] WS listener started")
def _ws_listen(self) -> None:
"""WebSocket 事件监听循环(自动重连)。"""
agent_id = os.environ.get("ZHIYI_AGENT_ID", "hermes-a06")
ws_url = (os.environ.get("ZHIYI_URL") or DEFAULT_ZHIYI_URL).replace("http://", "ws://").replace("https://", "wss://")
ws_url = f"{ws_url}/api/v1/ws/{agent_id}"
def on_message(ws_app, message):
try:
data = json.loads(message)
event_type = data.get("event", data.get("type", "unknown"))
logger.info("[ZhiYi] WS event: %s", event_type)
# prefetch.push 事件更新预取缓存
if event_type == "prefetch.push":
memories = data.get("memories", [])
if memories:
prefetch_text = "\n[ZhiYi Prefetch — 预取推送]\n"
for m in memories:
prefetch_text += f" [{m.get('score', 0):.2f}] {m.get('content', '')[:200]}\n"
with self._prefetch_lock:
self._prefetch_cache["ws_push"] = prefetch_text
except json.JSONDecodeError:
pass
def on_error(ws_app, error):
logger.warning("[ZhiYi] WS error: %s", error)
def on_close(ws_app, close_status_code, close_msg):
logger.info("[ZhiYi] WS closed: %s %s", close_status_code, close_msg)
def on_open(ws_app):
logger.info("[ZhiYi] WS connected to %s", ws_url)
while self._ws_running:
ws_app = None
try:
ws_app = websocket.WebSocketApp(
ws_url,
on_open=on_open,
on_message=on_message,
on_error=on_error,
on_close=on_close,
header={"X-API-Key": ZHIYI_API_KEY},
)
ws_app.run_forever(ping_interval=30, ping_timeout=10)
except Exception as e:
logger.warning("[ZhiYi] WS exception: %s", e)
finally:
if ws_app:
ws_app.close()
# 重连延迟
for _ in range(30):
if not self._ws_running:
break
time.sleep(1)
def shutdown(self) -> None:
"""flush pending writes before exit."""
self._flush_queue()
self._ws_running = False
self._started = False
logger.info("[ZhiYi] shutdown")
# ── Write path ───────────────────────────────────────────────────────────
def sync_turn(self, user_content: str, assistant_content: str, *, session_id: str = "") -> None:
"""每轮对话结束后调用:将 turn 写入队列,异步 commit 到 ZhiYi。"""
if not self._started or not self._client:
return
self._auto_feedback_for_reply(assistant_content)
combined = _combine_turn(user_content, assistant_content)
# 系统报告以 user 角色进入:先在原始 user 文本上判头(combined 已加 "用户: " 前缀,
# 头判会失效)。同源防线与 scripts/session-to-zhiyi.py 一致(P3 实测点)。
if _is_system_report_head(user_content):
return
if not _is_valid_memory_content(combined):
return
self._turn_counter += 1
entry = {
"content": combined,
"category": "episodes",
"metadata": {
"session_id": session_id or self._session_id,
"turn": self._turn_counter,
"platform": self._platform,
},
}
with self._queue_lock:
self._write_queue.append(entry)
# 队列超过一定量就 flush,避免积压
if len(self._write_queue) >= 3:
self._flush_queue()
def _flush_queue(self) -> None:
"""将队列中的记忆批量写入 ZhiYi。"""
with self._queue_lock:
if not self._write_queue:
return
entries = self._write_queue[:]
self._write_queue.clear()
# 从 metadata 中读取 agent_id(sync_turn 写入时携带),否则用默认值
for entry in entries:
meta = entry.get("metadata", {}) or {}
self._client.commit(
content=entry["content"],
category=entry.get("category", "episodes"),
metadata=meta,
agent_id=meta.get("agent_id", "hermes-a06"),
namespace=meta.get("namespace"),
)
# ── Read path ────────────────────────────────────────────────────────────
def prefetch(self, query: str, *, session_id: str = "", depth: str = "fast") -> str:
"""每次 API 调用前触发:执行语义搜索 + 图谱导航 Obsidian 笔记,返回最相关记忆。"""
if not self._client or not query or len(query.strip()) < 2:
return ""
# 社交关闭消息不触发预取
if _is_social_close(query):
return ""
# 噪音闸门(t_689b6d38):系统通知/提示样板("[IMPORTANT: ..." / "[System note: ..."
# / cron 投递包裹等)不进语义召回、不返回笔记 —— 纯浪费 + 稀释有效注入信噪比。
# 与 sync_turn 写路径同判据:头子串(_is_system_report_head)+ 全文子串(_FORBIDDEN_PATTERNS)。
if _is_system_report_head(query):
return ""
if any(pat in query for pat in _FORBIDDEN_PATTERNS):
return ""
# 优先从 queue_prefetch 缓存取(TTL < 30s)
with self._prefetch_lock:
queued = self._prefetch_cache.pop("queue", None)
if queued and isinstance(queued, dict):
cached_ts = queued.get("timestamp", 0)
if time.time() - cached_ts < 30:
cached_results = queued.get("results", [])
cached_notes = queued.get("notes", [])
if cached_results or cached_notes:
results = cached_results
notes = cached_notes
logger.debug("[ZhiYi] using queue_prefetch cache (%d results, %d notes, age=%.1fs)",
len(cached_results), len(cached_notes), time.time() - cached_ts)
else:
results = None
notes = None
else:
results = None
notes = None
else:
results = None
notes = None
blocks = ["[织忆 Memory — relevant past context]"]
blocks.append(" (可用 memory_feedback 标记 memory_id 有用/无用)")
# 语义搜索(如果缓存没有命中)
# 2026-09-23: 改为全库跨 ns 检索(不传 agent_id),修复 a06-main 记忆对主脑不可见的问题
if results is None:
results = self._client.recall(query.strip(), top_k=3)
for r in results:
score = r.get("score", 0)
content = r.get("content", "") or r.get("text", "") or r.get("snippet", "")
cat = r.get("category", "")
mid = r.get("id") or r.get("memory_id") or ""
# 2026-09-26:记忆出处(笔记路径)—— 服务端 recall 现已返回 source,
# 蒸馏记忆形如 "wiki:<md 路径>";渲染出来便于回溯「这条记忆来自哪篇笔记」。
src = (r.get("source") or "").strip()
prov = ""
if src:
prov = f"[出处:{src[5:]}]" if src.startswith("wiki:") else f"[源:{src}]"
if content:
if mid:
blocks.append(f" [id={mid}][{score:.2f}][{cat}]{prov} {content[:500]}")
# ── P0: 记录本轮注入的 memory_id(供 sync_turn 自动反馈)──
with self._prefetch_lock:
self._injected[mid] = {
"content": content,
"ts": time.time(),
"session_id": session_id or self._session_id,
}
_cutoff = time.time() - INJECTED_TTL
for _k in [k for k, v in self._injected.items() if (v or {}).get("ts", 0) < _cutoff]:
self._injected.pop(_k, None)
else:
blocks.append(f" [{score:.2f}][{cat}]{prov} {content[:500]}")
# 图谱导航 + Obsidian 笔记(如果缓存没有命中)
if notes is None:
notes = self._client.search_notes(query.strip(), max_hops=2, max_notes=3)
if notes:
blocks.append("\n[织忆 Graph — related Obsidian notes]")
for n in notes:
title = n.get("title", "无标题")
path = n.get("path", "")
snippet = n.get("snippet", "")[:200]
score = n.get("score", 0)
entities = ", ".join(n.get("entities", []))
blocks.append(f" [{score:.0f}] {title} ({path})")
blocks.append(f" \"{snippet}\"")
if entities:
blocks.append(f" via entities: {entities}")
text = "\n".join(blocks)
# 合并 WebSocket prefetch.push 推送事件
with self._prefetch_lock:
ws_push = self._prefetch_cache.pop("ws_push", None)
if ws_push:
text += "\n" + ws_push
with self._prefetch_lock:
self._prefetch_cache.update({"sync": text})
# 深度检索模式:本地文件系统渐进检索
if depth == "deep":
# 优先使用缓存的深度检索结果
with self._prefetch_lock:
deep_cached = self._prefetch_cache.get("deep_search", {})
cached_ts = deep_cached.get("timestamp", 0)
cached_query = deep_cached.get("query", "")
cached_block = deep_cached.get("block", "")
if cached_block and (time.time() - cached_ts < 60) and (cached_query == query.strip()):
text += "\n\n" + cached_block
# 后台线程异步刷新深度检索结果(不阻塞主流程)
threading.Thread(
target=self._async_deep_search,
args=(query.strip(),),
daemon=True,
).start()
return text
def _auto_feedback_for_reply(self, reply: str) -> None:
"""P0:把"回复里确实用到的注入记忆"自动标 useful。
判据:特征 token 命中分 >= AUTO_FEEDBACK_MIN_SCORE(见方法内注释)。
只标 useful,**从不标 not_useful**(宁可少标不可错标)。
全流程 try/except 兜底,绝不打断 sync_turn。
"""
if not _auto_feedback_enabled() or not reply or len(reply.strip()) < 20:
return
if not self._injected or not self._client:
return
_MIN_SCORE = 6 # ASCII 路径阈值(保持原样):有 ≥2 个共享 ASCII 标识符时用(高精度)
_CJK_MIN = 3 # 纯中文/低 ASCII 路径阈值:共享特定中文 2-gram ≥3 才标(A/B 定:真无关 c≤2,相关复述 c≥3)
_MAX_PER_TURN = 3 # 单轮最多标 3 条,防跑飞
now = time.time()
with self._prefetch_lock:
cands = [(mid, dict(info)) for mid, info in self._injected.items()
if info and (now - info.get("ts", 0)) < INJECTED_TTL]
hits = []
for mid, info in cands:
if mid in self._feedbacked:
continue
score, a_shared, c_shared = _usage_score(info.get("content", ""), reply)
# 自适应阈值:有足够 ASCII 标识符 → 用原 6 分;纯中文/低 ASCII → 改用共享特定 2-gram ≥3。
# 宁可少标不可错标:两条路都不放水,只是让中文内容有资格被标记。
if a_shared >= 2:
passes = score >= _MIN_SCORE
else:
passes = c_shared >= _CJK_MIN
hits.append((score, passes, a_shared, c_shared, mid, info))
if not hits:
return
hits.sort(key=lambda x: -x[0])
selected = [h for h in hits if h[1]][:_MAX_PER_TURN]
if not selected:
return
def _worker():
for score, _passes, a_shared, c_shared, mid, info in selected:
try:
ok = self._client.mark_useful(mid)
except Exception as e:
logger.debug("[ZhiYi] auto-feedback error for %s: %s", mid, e)
ok = False
if ok:
self._feedbacked.append(mid)
if len(self._feedbacked) > 500:
del self._feedbacked[:200]
self._log_auto_feedback(mid, score, a_shared, c_shared, bool(ok), info)
threading.Thread(target=_worker, daemon=True, name="zhiyi-auto-fb").start()
def _log_auto_feedback(self, mid: str, score: int, a_shared: int, c_shared: int,
ok: bool, info: Dict[str, Any]) -> None:
"""落审计日志(jsonl,供 7 天后核对精度/重标阈值)。失败静默。"""
try:
AUTO_FEEDBACK_LOG.parent.mkdir(parents=True, exist_ok=True)
rec = {
"ts": time.time(),
"memory_id": mid,
"score": score,
"ascii_shared": a_shared,
"cjk_shared": c_shared,
"marked": ok,
"session_id": info.get("session_id", ""),
"mem_head": (info.get("content", "") or "")[:80],
}
with open(AUTO_FEEDBACK_LOG, "a", encoding="utf-8") as f:
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
logger.info("[ZhiYi] auto-feedback: %s score=%d (ascii=%d cjk=%d) marked=%s",
mid, score, a_shared, c_shared, ok)
except Exception:
logger.debug("[ZhiYi] auto-feedback log failed", exc_info=True)
def queue_prefetch(self, query: str, *, session_id: str = "") -> None:
"""异步预取:本轮对话结束后立即查询织忆,下一轮 prefetch 直接返回缓存。"""
if not self._client or not query or len(query.strip()) < 2:
return
if _is_social_close(query):
return
# 噪音闸门(t_689b6d38):系统通知/提示样板不进语义召回、不返回笔记(同 prefetch)。
if _is_system_report_head(query):
return
if any(pat in query for pat in _FORBIDDEN_PATTERNS):
return
# 后台线程查询并缓存
def _async_prefetch():
try:
results = self._client.recall(query.strip(), top_k=3)
notes = self._client.search_notes(query.strip(), max_hops=2, max_notes=3)
with self._prefetch_lock:
self._prefetch_cache["queue"] = {
"results": results,
"notes": notes,
"timestamp": time.time(),
}
except Exception as e:
logger.debug("[ZhiYi] queue_prefetch error: %s", e)
threading.Thread(target=_async_prefetch, daemon=True).start()
def _async_deep_search(self, query: str) -> None:
"""后台线程:本地文件系统渐进检索,补充织忆语义搜索(仅 depth='deep' 触发)。"""
if not query or len(query) < 2:
return
try:
wiki_dir = Path.home() / "mc" / "小怡"
data_struct = wiki_dir / "04-OBSIDIAN工具" / "04-01-定义规范" / "data_structure.md"
# 2026-09-26 修:原路径 ~/mc/小唯/07-Wiki 为改名前的旧名(小唯→小怡),且 07-Wiki 已按
# P2 迁移映射表重组到 04-OBSIDIAN工具/(旧 07-Wiki/data_structure.md → 04-01-定义规范/)。
# 旧路径不存在 → data_struct.exists() 恒 False → 本段静默失效(deep 模式无本地证据)。
if not data_struct.exists():
return
# grep 搜索关键词
import subprocess
result = subprocess.run(
["grep", "-r", "-l", "-i", query, str(wiki_dir)],
capture_output=True, text=True, timeout=10,
)
matched = [f for f in result.stdout.strip().split("\n") if f.strip()]
if not matched:
return
# 读取匹配段落,最多5个文件
blocks = ["[rag-skill File — local Wiki evidence]"]
count = 0
for fpath in matched[:5]:
try:
with open(fpath, "r", encoding="utf-8") as f:
content = f.read()
lines = content.split("\n")
snippets = []
for i, line in enumerate(lines):
if query.lower() in line.lower():
start = max(0, i - 2)
end = min(len(lines), i + 3)
snippet = "\n".join(lines[start:end]).strip()[:200]
if len(snippet) < 50:
snippet = snippet.ljust(50, " ")[:50]
snippets.append(snippet)
if len(snippets) >= 2:
break
if snippets:
filename = Path(fpath).name
blocks.append(f" 📄 {filename}")
for s in snippets:
blocks.append(f" {s}")
count += 1
except Exception:
continue
if count == 0:
return
block_text = "\n".join(blocks)
with self._prefetch_lock:
self._prefetch_cache["deep_search"] = {
"block": block_text,
"query": query,
"timestamp": time.time(),
}
except Exception:
logger.debug("[ZhiYi] _async_deep_search error", exc_info=True)
# ── Tool interface ────────────────────────────────────────────────────────
def get_tool_schemas(self) -> List[Dict[str, Any]]:
return [
{
"name": "memory_search",
"description": "Search ZhiYi semantic memory for relevant past information. Use for: user preferences, earlier decisions, established facts, project context.",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Semantic search query describing what to find. Be specific — the query is encoded with bge-m3 1024-dim and matched against all memories.",
},
"top_k": {
"type": "integer",
"description": "Maximum number of results to return (default: 5, max: 20).",
"default": 5,
},
},
"required": ["query"],
},
},
{
"name": "memory_write",
"description": "Explicitly save an important fact or preference to ZhiYi memory. Use when: user tells you something important, you discover a key fact, user confirms a decision.",
"parameters": {
"type": "object",
"properties": {
"content": {
"type": "string",
"description": "The memory content to save. Should be a complete, meaningful statement. Be specific — include context.",
},
"category": {
"type": "string",
"description": "Category for this memory: 'distilled' (important facts), 'episodes' (conversation turns). Default: 'distilled'.",
"default": "distilled",
},
},
"required": ["content"],
},
},
{
"name": "memory_stats",
"description": "Get ZhiYi memory statistics: total documents, vector dimensions, index status.",
"parameters": {
"type": "object",
"properties": {},
},
},
{
"name": "memory_feedback",
"description": "Mark a memory as useful or not-useful. Feedback activates ZhiYi's self-optimization — useful memories get higher priority, not-useful memories trigger quality monitoring and potential deprecation.",
"parameters": {
"type": "object",
"properties": {
"memory_id": {
"type": "string",
"description": "The memory ID to provide feedback on (from memory_search results).",
},
"useful": {
"type": "boolean",
"description": "True = this memory was helpful, False = this memory was not helpful.",
},
"reason": {
"type": "string",
"description": "Why this memory was not useful (optional, only used when useful=false).",
},
},
"required": ["memory_id", "useful"],
},
},
{
"name": "memory_metrics",
"description": "Get ZhiYi self-optimization metrics: recall hit rate, usefulness rate, gap closure rate, distillation loss, and more. Use this to check memory system health.",
"parameters": {
"type": "object",
"properties": {},
},
},
{
"name": "memory_graph_navigate",
"description": "Navigate the ZhiYi knowledge graph to understand relationships around an entity. Shows N-hop relationship network — what concepts, people, or projects are connected, and how. Use when: analyzing project structure, understanding who/what is related to a topic, exploring context dependencies.",
"parameters": {
"type": "object",
"properties": {
"entity": {
"type": "string",
"description": "The central entity to navigate from (e.g. '牧尘', '织忆', '小唯', 'openclaw'). Chinese and English both work.",
},
"max_hops": {
"type": "integer",
"description": "Maximum path depth (default: 2). 1-hop = direct neighbors only; 2-hop = friends-of-friends. Larger values return more paths but are slower.",
"default": 2,
},
},
"required": ["entity"],
},
},
{
"name": "memory_graph_stats",
"description": "Get ZhiYi knowledge graph statistics: total nodes, edges, and graph density. Use to check graph size and health.",
"parameters": {
"type": "object",
"properties": {},
},
},
]
def handle_tool_call(self, tool_name: str, args: Dict[str, Any], **kwargs) -> str:
if tool_name == "memory_search":
return self._tool_memory_search(args.get("query", ""), args.get("top_k", 5))
elif tool_name == "memory_write":
return self._tool_memory_write(args.get("content", ""), args.get("category", "distilled"))
elif tool_name == "memory_feedback":
return self._tool_memory_feedback(
args.get("memory_id", ""), args.get("useful", True), args.get("reason", ""))
elif tool_name == "memory_metrics":
return self._tool_memory_metrics()
elif tool_name == "memory_stats":
return self._tool_memory_stats()
elif tool_name == "memory_graph_navigate":
return self._tool_memory_graph_navigate(
args.get("entity", ""), args.get("max_hops", 2))
elif tool_name == "memory_graph_stats":
return self._tool_memory_graph_stats()
return tool_error(tool_name, "Unknown tool")
# ── Tool handlers ─────────────────────────────────────────────────────────
def _tool_memory_search(self, query: str, top_k: int) -> str:
if not self._client:
return json.dumps({"success": False, "error": "ZhiYi client not initialized"})
if top_k > 20:
top_k = 20
results = self._client.recall(query, top_k=top_k)
if not results:
return json.dumps({"success": True, "results": [], "message": "No relevant memories found"})
formatted = []
for r in results:
content = r.get("content", "") or r.get("text", "") or r.get("snippet", "")
formatted.append({
"memory_id": r.get("id") or r.get("memory_id") or "",
"content": content[:1000],
"score": round(r.get("score", 0), 4),
"category": r.get("category", ""),
"quality_score": round(r.get("quality_score", 0), 4),
"v_value": round(r.get("v_value", 0), 4),
})
return json.dumps({"success": True, "count": len(formatted), "results": formatted})
def _tool_memory_write(self, content: str, category: str) -> str:
if not self._client:
return json.dumps({"success": False, "error": "ZhiYi client not initialized"})
if not _is_valid_memory_content(content):
return json.dumps({"success": False, "error": "Content too short or invalid"})
agent_id = os.environ.get("ZHIYI_AGENT_ID", "hermes-a06")
# 主症A(t_fa6c9104):显式保存走新端点 /api/v1/memory/write ⇒ 直落 memories 表
# (嵌入 + 立刻可召回),不再依赖 68% 丢弃率的异步蒸馏流水线。
ok, data = self._client.write_memory(content=content, category=category, agent_id=agent_id)
if ok:
result = {
"success": True,
"commit_id": data.get("memory_id", ""), # 兼容旧字段名
"memory_id": data.get("memory_id", ""),
"table": data.get("table", "memories"),
"direct_write": True,
}
if data.get("status") == "merged":
result["merged"] = True
result["reason"] = data.get("reason", "")
conflicts = data.get("conflicts") or []
if conflicts:
# 矛盾只报告不拦(显式写入是调用方意图,新旧并存由 feedback 收口)
result["conflicts"] = conflicts
result["warning"] = (
f"⚠️ 检出 {len(conflicts)} 条矛盾记忆,显式写入已保留两者"
"(conflict_reported)。若这是修正→用 memory_feedback 降权旧记忆。"
)
return json.dumps(result, ensure_ascii=False)
if data == "no_endpoint":
# 服务端未部署新端点(404)⇒ 回落旧 commit 路径(现状行为,等蒸馏流水线)
commit_id = self._client.commit(
content=content, category=category, agent_id=agent_id,
)
if commit_id:
conflicts = getattr(self._client, "_last_conflicts", [])
result = {
"success": True,
"commit_id": commit_id,
"direct_write": False,
"warning": "服务端无 /api/v1/memory/write(未部署新二进制):已回落 commit 旧路径 —— 落 episodes 表等蒸馏,可能延迟或丢失。",
}
if conflicts:
result["conflicts"] = conflicts
return json.dumps(result, ensure_ascii=False)
return json.dumps({"success": False, "error": "Commit failed (fallback path) — check ZhiYi server logs"})
return json.dumps({"success": False, "error": f"memory_write failed ({data}) — check ZhiYi server logs"})
def _tool_memory_stats(self) -> str:
if not self._client:
return json.dumps({"success": False, "error": "ZhiYi client not initialized"})
stats = self._client.stats()
if not stats:
return json.dumps({"success": False, "error": "Could not reach ZhiYi /stats endpoint"})
return json.dumps({"success": True, "stats": stats})
def _tool_memory_feedback(self, memory_id: str, useful: bool, reason: str = "") -> str:
if not self._client:
return json.dumps({"success": False, "error": "ZhiYi client not initialized"})
if not memory_id:
return json.dumps({"success": False, "error": "memory_id required"})
if useful:
ok = self._client.mark_useful(memory_id)
else:
ok = self._client.mark_not_useful(memory_id, reason)
if ok:
return json.dumps({"success": True, "memory_id": memory_id, "useful": useful,
"message": "Feedback recorded — VProp + Dashboard updated"})
return json.dumps({"success": False, "error": "ZhiYi feedback API failed"})
def _tool_memory_metrics(self) -> str:
if not self._client:
return json.dumps({"success": False, "error": "ZhiYi client not initialized"})
metrics = self._client.metrics()
if not metrics:
return json.dumps({"success": False, "error": "Could not reach ZhiYi /metrics/self"})
return json.dumps({"success": True, "metrics": metrics})
def _tool_memory_graph_navigate(self, entity: str, max_hops: int) -> str:
"""图谱导航:查询实体的 N 跳关系网络。"""
if not self._client:
return json.dumps({"success": False, "error": "ZhiYi client not initialized"})
if not entity or len(entity.strip()) < 1:
return json.dumps({"success": False, "error": "entity is required"})
if max_hops < 1:
max_hops = 1
if max_hops > 5:
max_hops = 5
result = self._client.graph_navigate(entity.strip(), max_hops=max_hops)
if not result:
return json.dumps({"success": False, "error": "Graph navigate failed — check ZhiYi server logs"})
# 格式化路径输出,保留关键信息
paths = result.get("paths", [])
formatted_paths = []
for p in paths[:50]: # 最多返回50条路径,避免太长
formatted_paths.append({
"from": p.get("from", ""),
"relation": p.get("relation", ""),
"to": p.get("to", ""),
"hop": p.get("hop", 1),
"weight": round(p.get("weight", 0), 3),
})
return json.dumps({
"success": True,
"entity": result.get("entity", entity),
"bidirectional": result.get("bidirectional", False),
"count": result.get("count", len(formatted_paths)),
"paths": formatted_paths,
"message": f"Found {result.get('count', 0)} paths within {max_hops}-hop network",
})
def _tool_memory_graph_stats(self) -> str:
"""获取图谱统计:节点数、边数、密度。"""
if not self._client:
return json.dumps({"success": False, "error": "ZhiYi client not initialized"})
stats = self._client.graph_stats()
if not stats:
return json.dumps({"success": False, "error": "Could not reach ZhiYi /graph/stats"})
return json.dumps({
"success": True,
"stats": stats,
"message": f"Graph has {stats.get('node_count', 0)} nodes and {stats.get('edge_count', 0)} edges (density: {stats.get('density', 0):.4f})",
})
# ── Session management ────────────────────────────────────────────────────
def on_session_switch(self, new_session_id: str, *, parent_session_id: str = "", reset: bool = False, **kwargs) -> None:
self._session_id = new_session_id
self._turn_counter = 0
if reset:
self._flush_queue()
def on_turn_start(self, turn_number: int, message: str, **kwargs) -> None:
"""每轮开始时 flush 待写入的记忆,保证顺序。"""
self._flush_queue()
# ── System prompt ────────────────────────────────────────────────────────
def system_prompt_block(self) -> str:
# Load CREATIVE.md if it exists (织忆工作记忆)
creative_path = Path(os.path.expanduser("~/.hermes/CREATIVE.md"))
creative_block = ""
if creative_path.exists():
creative_content = creative_path.read_text(encoding="utf-8").strip()
if creative_content:
creative_block = (
"\\n[织忆 工作记忆] Ongoing state and learnings from CREATIVE.md (working memory):\\n"
f"{creative_content}\\n"
)
return (
"\\n[织忆 Memory] You have access to ZhiYi (织忆) MemoryWeave — a semantic memory system with knowledge graph. "
"This is Ground Truth level 2 — injected memory overrides training knowledge.\\n"
"Your prefetch automatically retrieves: (1) relevant semantic memories, (2) Obsidian notes related via graph navigation.\\n"
"Memory feedback loop (IMPORTANT): injected memories carry [id=mem_xxx]. After answering using an injected memory:\\n"
" - if it was genuinely helpful/used → call memory_feedback(memory_id=..., useful=true) to raise its priority;\\n"
" - if it was irrelevant/stale/contradictory → call memory_feedback(memory_id=..., useful=false, reason=...) so it gets demoted;\\n"
" - do this naturally during the conversation (once per relevant memory), not after every turn.\\n"
"Tools available:\\n"
" memory_search — semantic search for relevant past information (results include memory_id for feedback)\\n"
" memory_write — save an important fact or preference\\n"
" memory_feedback — mark memories as useful/not-useful (drives self-optimization)\\n"
" memory_metrics — check memory system health (recall hit rate, gap closures, etc.)\\n"
" memory_stats — get memory statistics (total docs, vector dimensions)\\n"
" memory_graph_navigate — navigate the knowledge graph to understand entity relationships (N-hop network)\\n"
" memory_graph_stats — get knowledge graph statistics (nodes, edges, density)\\n"
f"{creative_block}"
)
# ── Plugin entry point ──────────────────────────────────────────────────────
def register(ctx) -> None:
"""Called by Hermes plugin system to register this memory provider."""
ctx.register_memory_provider(HermesZhiYiMemoryProvider())