From fa0241ff9921b279766c2fe50cee7ab953e0fc91 Mon Sep 17 00:00:00 2001 From: agent-bot Date: Mon, 27 Jul 2026 02:11:18 +0800 Subject: [PATCH] fix: decouple MemoryCompanion bridge from LivingMemory switch; drop LivingMemory MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 关键修复:_memory_companion_bridge() 此前以 enable_livingmemory_integration 为总闸,而运维版把该开关硬编码成 False(原意只是「VM 不用 LivingMemory」), 把唯一长期记忆源一起关掉——Bot 个人归档链路在 VM 上整条静默停摆, 记忆库零条记录,页面显示「记忆插件 暂不可用」。改用独立的 enable_memory_companion_bridge(默认开启)。 同时删除全部 LivingMemory 代码:integration_status 的 7 个函数、 page_api 的 9 个函数与路由、main 的提示词槽位/关系网触发/状态命令/ WAL 候选路径/命令别名、group_observation 的群聊指引。 测试 178 项通过(新增 4 项钉住开关拆分与代码零残留)。 Co-Authored-By: Claude Opus 5 --- _conf_schema.json | 2 +- group_observation.py | 9 - integration_status.py | 162 -------------- llm_tool_actions.py | 2 +- main.py | 36 +-- memory_companion_adapter.py | 6 +- page_api.py | 329 +--------------------------- tests/test_m6_r7_privacy_residue.py | 54 +++++ 8 files changed, 73 insertions(+), 527 deletions(-) diff --git a/_conf_schema.json b/_conf_schema.json index f015625..ed65c6b 100644 --- a/_conf_schema.json +++ b/_conf_schema.json @@ -5632,7 +5632,7 @@ "external_memory_config": { "description": "外部记忆插件协同", "type": "object", - "hint": "统一接入已适配的外部长期记忆插件。当前支持“我会牢牢记住你”/MemoryCompanion 与 LivingMemory;检测到不同插件时会展开各自适用的协同配置。", + "hint": "统一接入已适配的外部长期记忆插件。当前支持“我会牢牢记住你”/MemoryCompanion。", "items": { "memory_companion_context_timeout_seconds": { "description": "记忆上下文超时(秒)", diff --git a/group_observation.py b/group_observation.py index 2054212..633a227 100644 --- a/group_observation.py +++ b/group_observation.py @@ -2356,15 +2356,6 @@ class GroupObservationMixin: lines.append( "群聊边界:私聊记忆、用户私聊偏好和内部记录只作避错背景,不要说到群里。" ) - livingmemory_guidance = ( - "" - if getattr(self, "_memory_companion_should_defer_prompt_section", lambda *_args, **_kwargs: False)( - "livingmemory_guidance" - ) - else self._format_livingmemory_guidance(scope="group") - ) - if livingmemory_guidance: - lines.append(livingmemory_guidance) if len(lines) <= 1: return "" return "\n".join(lines) diff --git a/integration_status.py b/integration_status.py index 743cdd8..1626a72 100644 --- a/integration_status.py +++ b/integration_status.py @@ -255,24 +255,6 @@ class IntegrationStatusMixin: except Exception as e: logger.warning(f"[PrivateCompanion] 插件拓展页面 API 注册失败: {e}", exc_info=True) - def _patch_livingmemory_processor_compat(self) -> None: - """Work around LivingMemory versions whose MemoryProcessor lacks config.""" - if not self.enable_livingmemory_integration: - return - module = ( - sys.modules.get("data.plugins.astrbot_plugin_livingmemory.core.processors.memory_processor") - or sys.modules.get("astrbot_plugin_livingmemory.core.processors.memory_processor") - ) - if module is None: - return - processor_cls = getattr(module, "MemoryProcessor", None) - if processor_cls is None or hasattr(processor_cls, "config"): - return - try: - setattr(processor_cls, "config", {"atom_enabled": True}) - logger.info("[PrivateCompanion] 已为 LivingMemory MemoryProcessor 添加 config 兼容兜底") - except Exception as exc: - logger.debug("[PrivateCompanion] LivingMemory 兼容补丁应用失败: %s", _single_line(exc, 120)) def _integrated_plugin_installed(self, *names: str) -> bool: roots = [ @@ -408,155 +390,11 @@ class IntegrationStatusMixin: base.append(knowledge_context) return "\n".join(base) - def _livingmemory_plugin_dir(self) -> Path: - candidates = [ - Path(__file__).resolve().parent.parent / "astrbot_plugin_livingmemory", - Path(self.data_dir).parent / "astrbot_plugin_livingmemory", - Path(self.data_dir).parent.parent / "plugins" / "astrbot_plugin_livingmemory", - ] - for path in candidates: - if (path / "main.py").exists(): - return path - return candidates[0] - def _livingmemory_tool_available(self) -> bool | None: - """Return tool availability when AstrBot exposes its runtime tool registry. - ``None`` means the host is too old to expose a tool manager. A tool is - usable only when it is active and its handler belongs to LivingMemory; - a directory on disk is not evidence that the plugin is loaded. - """ - tool_name = _single_line(getattr(self, "livingmemory_tool_name", ""), 60) or "recall_long_term_memory" - context = getattr(self, "context", None) - manager = None - getter = getattr(context, "get_llm_tool_manager", None) - if callable(getter): - try: - manager = getter() - except Exception: - manager = None - if manager is None: - provider_manager = getattr(context, "provider_manager", None) - manager = getattr(provider_manager, "llm_tools", None) - if manager is None: - return None - candidates: list[Any] = [] - get_func = getattr(manager, "get_func", None) - if callable(get_func): - try: - tool = get_func(tool_name) - if tool is not None: - candidates.append(tool) - except Exception: - pass - try: - candidates.extend( - tool - for tool in list(getattr(manager, "func_list", []) or []) - if str(getattr(tool, "name", "") or "") == tool_name - ) - except Exception: - pass - for tool in candidates: - if not bool(getattr(tool, "active", True)): - continue - module_path = str(getattr(tool, "handler_module_path", "") or "") - if not module_path: - handler = getattr(tool, "handler", None) - module_path = str(getattr(handler, "__module__", "") or "") - if "livingmemory" in module_path.lower(): - return True - return False - @staticmethod - def _livingmemory_module_loaded() -> bool: - prefixes = ( - "astrbot_plugin_livingmemory", - "data.plugins.astrbot_plugin_livingmemory", - ) - return any( - module is not None - and any(name == prefix or name.startswith(f"{prefix}.") for prefix in prefixes) - for name, module in sys.modules.items() - ) - - def _livingmemory_available(self) -> bool: - runtime_available = self._livingmemory_tool_available() - if runtime_available is not None: - return runtime_available - # Compatibility fallback for old AstrBot versions without a tool manager. - return self._livingmemory_module_loaded() - - def _format_livingmemory_guidance(self, *, scope: str = "private") -> str: - if not self.enable_livingmemory_integration or not self._livingmemory_available(): - return "" - tool_name = _single_line(self.livingmemory_tool_name, 60) or "recall_long_term_memory" - if scope == "group": - boundary = "群聊只查当前群可公开使用的旧事。" - else: - boundary = "私聊可查当前用户相关的旧约定、偏好和共同经历。" - return ( - "【长期记忆检索】\n" - f"上下文不够时可用 `{tool_name}` 查记忆。只有当前工具列表确实提供该工具时才调用;工具未出现时不要猜测、重试或输出工具调用。{boundary}结果只作接话背景。\n" - "召回结果里出现人名、昵称、QQ 或群成员别名时,不要直接当作稳定身份;能查关系网时先用关系网确认,不能确认就按召回文本里的具体说话人原样转述。\n" - "如果召回到 Bot 曾说自己在吃饭、整理、犯困、路上、创作等状态/日程,只能理解为当时 Bot 的拟人化表达或历史自称;不要写成用户事实、现实证据或持续状态。" - ) - - def _format_livingmemory_status(self) -> str: - # Check for "我会牢牢记住你" (RememberYou) bridge first - companion_bridge = None - try: - companion_bridge = self._memory_companion_bridge() # type: ignore[attr-defined] - except Exception: - pass - if companion_bridge is not None: - display_name = getattr(companion_bridge, "display_name", "") or "我会牢牢记住你" - return ( - f"记忆插件协同:已检测到{display_name}。\n" - f"协同开关:{'开启' if self.enable_livingmemory_integration else '关闭'}\n" - f"情绪漂移联动:{'开启' if getattr(self, 'enable_memory_companion_emotional_drift', True) else '关闭'}\n" - f"跨窗口情绪连续性:{'开启' if getattr(self, 'enable_memory_companion_cross_window_emotion', True) else '关闭'}\n" - f"梦境碎片写入:{'开启' if getattr(self, 'enable_memory_companion_dream_fragment', True) else '关闭'}\n" - f"未完成话题取材:{'开启' if getattr(self, 'enable_memory_companion_open_loop_search', True) else '关闭'}\n" - f"功能上下文读取:{'开启' if getattr(self, 'enable_memory_companion_feature_context', True) else '关闭'}\n" - "用途:长期记忆沉淀、短上下文补充、情绪漂移、梦境碎片和跨会话连续性。\n" - "建议:保留本插件的生活状态/关系/群聊气氛层,把大规模长期检索交给记忆插件。" - ) - plugin_dir = self._livingmemory_plugin_dir() - if not plugin_dir.exists(): - return ( - "记忆插件协同:未检测到\"我会牢牢记住你\"或 LivingMemory。\n" - "当前会继续使用本插件内置的轻量记忆、片段记忆和群聊观察。" - ) - metadata = plugin_dir / "metadata.yaml" - version = "" - if metadata.exists(): - try: - text = metadata.read_text(encoding="utf-8") - match = re.search(r"version:\s*([^\n]+)", text) - if match: - version = match.group(1).strip() - except Exception: - version = "" - if not self._livingmemory_available(): - return ( - "记忆插件协同:检测到 LivingMemory 文件,但插件未加载或召回工具未启用。\n" - f"路径:{plugin_dir}\n" - f"版本:{version or '未知'}\n" - f"协同开关:{'开启' if self.enable_livingmemory_integration else '关闭'}\n" - "当前不会注入 LivingMemory 召回提示;启用插件及其召回工具后会自动恢复。" - ) - return ( - "记忆插件协同:已检测到 LivingMemory。\n" - f"路径:{plugin_dir}\n" - f"版本:{version or '未知'}\n" - f"协同开关:{'开启' if self.enable_livingmemory_integration else '关闭'}\n" - f"召回工具名:{self.livingmemory_tool_name or 'recall_long_term_memory'}\n" - "用途:长期记忆、BM25/Faiss 混合检索、图谱记忆和 Agent 主动回忆。\n" - "建议:保留本插件的生活状态/关系/群聊气氛层,把大规模长期检索交给 LivingMemory。" - ) def _llmperception_plugin_dir(self) -> Path: candidates = [ diff --git a/llm_tool_actions.py b/llm_tool_actions.py index 9645f8d..1b9c6a3 100644 --- a/llm_tool_actions.py +++ b/llm_tool_actions.py @@ -188,7 +188,7 @@ class LlmToolActionsMixin: return """ 【关系网查询】 用户明确要求“查一下关系网/帮我查某个 QQ 或昵称”时,可以用 `pc_query_relation_person` 查询关系网。 -- 如果刚用 LivingMemory/长期记忆召回到某个人名、昵称、QQ 或群成员别名,并且需要判断 TA 是谁、和用户什么关系、能不能套用某段关系时,也可以先查关系网再回答。 +- 如果刚用长期记忆召回到某个人名、昵称、QQ 或群成员别名,并且需要判断 TA 是谁、和用户什么关系、能不能套用某段关系时,也可以先查关系网再回答。 - 只用于确认是否认识和读取稳定称呼、别名、简短身份备注;不要发送消息。 - 参数用 keyword 传 QQ 号、昵称、别名或用户原话里最像名字的部分。 - 查不到就自然说明没在关系网里确认过,不要编造。 diff --git a/main.py b/main.py index d6590b0..7dacfa1 100644 --- a/main.py +++ b/main.py @@ -824,10 +824,8 @@ _PROACTIVE_ONLY_TEMP_UNLOCK_ALIASES = { "互动查询": "enable_cross_user_memory_bridge", "跨群转述": "enable_atrelay_tools", "转述工具": "enable_atrelay_tools", - "livingmemory": "enable_livingmemory_integration", - "lmem": "enable_livingmemory_integration", - "记忆插件": "enable_livingmemory_integration", - "记忆协同": "enable_livingmemory_integration", + "记忆插件": "enable_memory_companion_bridge", + "记忆协同": "enable_memory_companion_bridge", } _PROACTIVE_ONLY_TEMP_UNLOCK_LABELS = { "all": "全部被动链路", @@ -848,7 +846,7 @@ _PROACTIVE_ONLY_TEMP_UNLOCK_LABELS = { "enable_worldbook_member_recognition": "关系网成员识别", "enable_cross_user_memory_bridge": "跨用户记忆互通", "enable_atrelay_tools": "跨群转述工具", - "enable_livingmemory_integration": "记忆插件被动引导", + "enable_memory_companion_bridge": "记忆插件归档协同", "enable_tts_enhancement": "TTS 后处理", "enable_segmented_proactive_reply": "普通 LLM 分段", } @@ -878,7 +876,7 @@ _PROACTIVE_ONLY_TEMP_UNLOCK_GROUPS = { "enable_private_reading_preference_influence", "enable_worldbook_member_recognition", "enable_cross_user_memory_bridge", - "enable_livingmemory_integration", + "enable_memory_companion_bridge", }, "pc_tools": { "enable_atrelay_tools", @@ -1874,9 +1872,10 @@ class PrivateCompanionPlugin( self.group_episode_provider_id = self._cfg_str(c, "GROUP_EPISODE_PROVIDER_ID", "") self.group_slang_provider_id = self._cfg_str(c, "GROUP_SLANG_PROVIDER_ID", "") self.group_followup_judge_provider_id = self._cfg_str(c, "GROUP_FOLLOWUP_JUDGE_PROVIDER_ID", "") - self.enable_livingmemory_integration = False - self.livingmemory_disabled_reason = "运维版 VM 不使用 LivingMemory;仅保留历史迁移代码" - self.livingmemory_tool_name = self._cfg_str(c, "livingmemory_tool_name", "recall_long_term_memory", "recall_long_term_memory") + # MemoryCompanion 桥的独立开关。此前它复用 enable_livingmemory_integration, + # 而运维版把那个开关硬编码成 False(原意只是「不用 LivingMemory」), + # 结果把唯一长期记忆源也一起关掉,Bot 个人归档链路在 VM 上整条静默停摆。 + self.enable_memory_companion_bridge = self._cfg_bool(c, "enable_memory_companion_bridge", True) self.memory_companion_context_timeout_seconds = self._cfg_float(c, "memory_companion_context_timeout_seconds", 1.2, 0.2) self.enable_memory_companion_emotional_drift = self._cfg_bool(c, "enable_memory_companion_emotional_drift", True) self.enable_memory_companion_cross_window_emotion = self._cfg_bool(c, "enable_memory_companion_cross_window_emotion", True) @@ -2025,7 +2024,6 @@ class PrivateCompanionPlugin( self.allow_poke_action = self.enable_poke_action self.allow_voice_action = self.enable_voice_action - self._patch_livingmemory_processor_compat() self._report_integrated_feature_conflicts() self._data_lock = asyncio.Lock() self._conversation_db_lock = asyncio.Lock() @@ -2069,9 +2067,6 @@ class PrivateCompanionPlugin( data_root = Path(get_astrbot_data_path()) candidates = [ data_root / "data_v4.db", - data_root / "plugin_data" / "astrbot_plugin_livingmemory" / "conversations.db", - data_root / "plugin_data" / "astrbot_plugin_livingmemory" / "livingmemory.db", - data_root / "plugin_data" / "astrbot_plugin_livingmemory" / "livingmemory_graph_documents.db", data_root / "knowledge_base" / "kb.db", ] seen: set[str] = set() @@ -5937,8 +5932,6 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge metadata={"范围": "当前私聊会话", "触发": "记忆线索"}, ) add_spec("companion.planner", "companion", 80, lambda: self._format_companion_planner_injection(current_user)) - if not self._memory_companion_should_defer_prompt_section("livingmemory_guidance", event, req): - add_spec("livingmemory.guidance", "livingmemory", 90, lambda: self._format_livingmemory_guidance(scope="private" if is_private_chat else "group")) add_spec("detail.injection", "daily_detail", 40, self._format_detail_injection) current_user_id = "" @@ -6087,12 +6080,7 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge or any(token in message_text for token in ("这个人", "这人", "那个人", "那人", "是谁", "认识")) ) ) - livingmemory_relation_context = ( - relation_private - and bool(getattr(self, "enable_livingmemory_integration", False)) - and bool(getattr(self, "_livingmemory_available", lambda: False)()) - ) - if relation_private and relation_instruction and relation_marker not in current_prompt and relation_marker not in current_turn_prompt and (relation_query or livingmemory_relation_context): + if relation_private and relation_instruction and relation_marker not in current_prompt and relation_marker not in current_turn_prompt and relation_query: placement = "prompt" if self._append_turn_prompt_fragment_by_position( req, relation_marker, @@ -6110,7 +6098,7 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge text=relation_instruction, source="tools", mode="conditional", - metadata={"注入位置": placement, "触发原因": "livingmemory" if livingmemory_relation_context and not relation_query else "query"}, + metadata={"注入位置": placement, "触发原因": "query"}, ) schedule_management_instruction = self._schedule_management_tool_instruction() current_prompt = req.system_prompt or "" @@ -7950,7 +7938,7 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge "enable_skill_growth_passive_injection", "enable_private_reading_preference_influence", "enable_worldbook_member_recognition", - "enable_livingmemory_integration", + "enable_memory_companion_bridge", } return bool(full_path_keys & unlocks) @@ -10432,8 +10420,6 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge elif action in {"话头删除", "删除话头", "未完话头删除", "删除未完话头"}: response = self._remove_open_loop_entry(user, value) self._save_data_sync() - elif action in {"长期记忆", "livingmemory", "lmem", "向量记忆"}: - response = self._format_livingmemory_status() elif action in {"日记", "bot日记", "小记"}: response = self._format_diaries() elif action in {"书柜密码", "夹层密码", "抽屉密码", "书柜暗格"}: diff --git a/memory_companion_adapter.py b/memory_companion_adapter.py index 3d88292..1c14428 100644 --- a/memory_companion_adapter.py +++ b/memory_companion_adapter.py @@ -87,7 +87,11 @@ class MemoryCompanionAdapterMixin: return True def _memory_companion_bridge(self) -> Any | None: - if not getattr(self, "enable_livingmemory_integration", True): + # 这道闸门曾经复用 enable_livingmemory_integration。运维版把那个开关硬编码成 False + # (原意是「VM 不用 LivingMemory」),却把 MemoryCompanion 桥一起关掉了—— + # 而同一份决策恰恰规定 MemoryCompanion 是唯一长期记忆源。结果是整条 Bot 个人归档链路 + # 在 VM 上静默停摆,记忆库一条也写不进去。两者必须是各自独立的开关。 + if not getattr(self, "enable_memory_companion_bridge", True): return None now = time.monotonic() if now < self._bridge_dependency_failure_until: diff --git a/page_api.py b/page_api.py index 2f2cb92..009a134 100644 --- a/page_api.py +++ b/page_api.py @@ -47,7 +47,7 @@ from .q7_backend_contracts import ( PAGE_API_PREFIX = f"/{PLUGIN_NAME}/page" OPS_REMOVED_CONFIG_EXACT = { - "QZONE_COOKIE", "enable_livingmemory_integration", "livingmemory_tool_name", + "QZONE_COOKIE", "enable_ai_daily_watch", "ai_daily_source_uid", "ai_daily_prefer_text_version", "enable_food_menu_recommendation", "enable_meal_care_proactive", "enable_poke_action", "allow_poke_action", "enable_qq_presence_sync", @@ -271,7 +271,6 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiUsersGroupsMixin): ("/creative/project/rebuild_memory", self.rebuild_creative_memory, ["POST"], "Private Companion Page rebuild creative memory"), ("/creative/project/delete", self.delete_creative_project, ["POST"], "Private Companion Page delete creative project"), ("/worldbook/import", self.import_worldbook, ["POST"], "Private Companion Page import worldbook"), - ("/worldbook/member/livingmemory", self.get_worldbook_member_livingmemory, ["GET"], "Private Companion Page worldbook member LivingMemory"), ("/worldbook/member/update", self.update_worldbook_member, ["POST"], "Private Companion Page update worldbook member"), ("/worldbook/observations/clear", self.clear_worldbook_pending_observations, ["POST"], "Private Companion Page clear worldbook pending observations"), ("/worldbook/group/update", self.update_worldbook_group, ["POST"], "Private Companion Page update worldbook group"), @@ -5731,52 +5730,6 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiUsersGroupsMixin): logger.error(f"[PrivateCompanionPage] 更新关系节点失败: {exc}", exc_info=True) return self._error(str(exc)) - async def get_worldbook_member_livingmemory(self) -> dict[str, Any]: - user_id = self._normalize_worldbook_member_id(self._single_line(request.args.get("user_id"), 80)) - if not user_id: - return self._error("缺少 user_id") - limit = self._query_int("limit", 20, 1, 60) - try: - async with self.plugin._data_lock: - profiles = self.plugin.data.get("worldbook_member_profiles") if isinstance(self.plugin.data.get("worldbook_member_profiles"), dict) else {} - profile = profiles.get(user_id) - if not isinstance(profile, dict): - return self._error("没有找到对应关系节点") - profile_copy = deepcopy(profile) - token_bundle = self._worldbook_member_livingmemory_tokens(user_id, profile_copy) - tokens = token_bundle.get("tokens", []) - db_path = self._livingmemory_db_path() - if not db_path: - return self._ok( - { - "available": False, - "user_id": user_id, - "tokens": tokens, - "items": [], - "total": 0, - "message": "未找到 LivingMemory 数据库", - } - ) - items = await asyncio.to_thread(self._query_livingmemory_for_tokens, db_path, token_bundle, limit) - return self._ok( - { - "available": True, - "user_id": user_id, - "tokens": tokens, - "primary_tokens": token_bundle.get("primary_tokens", []), - "support_tokens": token_bundle.get("support_tokens", []), - "items": items, - "total": len(items), - "filter_note": "默认仅召回命中 QQ 或绑定身份键的记忆;名称、别名和群名片不单独作为召回依据。", - "message": f"已找到 {len(items)} 条 LivingMemory 相关记忆", - } - ) - except sqlite3.OperationalError as exc: - logger.warning(f"[PrivateCompanionPage] 查询 LivingMemory 失败: {exc}") - return self._error(f"LivingMemory 数据库暂时不可读:{exc}") - except Exception as exc: - logger.error(f"[PrivateCompanionPage] 查询关系节点 LivingMemory 失败: {exc}", exc_info=True) - return self._error(str(exc)) async def clear_worldbook_pending_observations(self) -> dict[str, Any]: payload = await request.get_json(silent=True) or {} @@ -11085,7 +11038,6 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiUsersGroupsMixin): "enable_worldbook_member_recognition", "enable_cross_user_memory_bridge", "enable_atrelay_tools", - "enable_livingmemory_integration", "enable_bilibili_integration", "enable_bilibili_boredom_watch", "enable_news_integration", @@ -11127,7 +11079,6 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiUsersGroupsMixin): private_reading_available = bool(getattr(self.plugin, "_jm_cosmos_available", lambda: False)()) except Exception: private_reading_available = False - values["enable_livingmemory_integration"] = bool(getattr(self.plugin, "enable_livingmemory_integration", False)) values["enable_bilibili_integration"] = bool(bilibili_available and getattr(self.plugin, "enable_bilibili_integration", False)) values["enable_bilibili_boredom_watch"] = bool(bilibili_available and getattr(self.plugin, "enable_bilibili_boredom_watch", False)) values["enable_qzone_integration"] = bool(getattr(self.plugin, "enable_qzone_integration", False)) @@ -11170,7 +11121,6 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiUsersGroupsMixin): "enable_private_reading_preference_influence", "enable_worldbook_member_recognition", "enable_atrelay_tools", - "enable_livingmemory_integration", "enable_tts_enhancement", "enable_segmented_proactive_reply", ] @@ -13474,22 +13424,6 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiUsersGroupsMixin): else: add("info", "通用表达学习已关闭", "不会继续归纳或注入表达规则") - if features.get("enable_livingmemory_integration"): - living_summary = self._livingmemory_summary() - living_level = "warn" if living_summary.get("conflict") else ("ok" if living_summary.get("compatible_available") else "warn") - if living_summary.get("conflict_warning"): - living_text = str(living_summary.get("conflict_warning") or "") - elif living_summary.get("selected_plugin_name"): - living_text = f"当前使用:{living_summary.get('selected_plugin_name')}" - else: - living_text = "已启用协同,但当前未检测到可用记忆插件" - add( - living_level, - "记忆插件协同", - living_text, - warning_code="memory.integration_conflict" if living_summary.get("conflict") else "memory.integration_unavailable", - ) - if features.get("enable_bilibili_integration"): bili_available = bool(getattr(self.plugin, "_bilibili_available", lambda: False)()) add( @@ -13978,7 +13912,6 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiUsersGroupsMixin): "enable_expression_learning": True, "enable_passive_response_review": True, "enable_proactive_message_review": True, - "enable_livingmemory_integration": True, }, }, "standard": { @@ -14728,7 +14661,6 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiUsersGroupsMixin): "enable_group_scene_awareness", "enable_group_reality_promise_guard", "enable_atrelay_tools", - "enable_livingmemory_integration", "enable_bilibili_integration", "enable_bilibili_boredom_watch", "enable_news_integration", @@ -16655,18 +16587,6 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiUsersGroupsMixin): memories.sort(key=lambda item: (item.get("enabled", True), item.get("weight", 50), item.get("updated_at", 0)), reverse=True) return memories[:8] - def _livingmemory_summary(self) -> dict[str, Any]: - return { - "enabled": False, - "configured_enabled": False, - "compatible_available": False, - "available": False, - "status": "Ops removed LivingMemory runtime compatibility; memory plugin bridge remains.", - "active_plugins": [], - "selected_plugin": None, - "conflict": False, - "migration_check": "not_required", - } def _screen_companion_available(self) -> bool: getter = getattr(self.plugin, "_get_screen_companion_plugin", None) @@ -19544,60 +19464,7 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiUsersGroupsMixin): count += 1 return count - def _livingmemory_db_path(self) -> Path | None: - return None - def _worldbook_member_livingmemory_tokens(self, user_id: str, profile: dict[str, Any]) -> dict[str, list[str]]: - primary_raw: list[Any] = [ - user_id, - profile.get("linked_qq_user_id"), - profile.get("merged_into_user_id"), - profile.get("linked_bili_profile_id"), - ] - external_ids = profile.get("external_ids") - if isinstance(external_ids, list): - primary_raw.extend(external_ids) - support_raw: list[Any] = [] - for key in ("name", "aliases", "observed_names"): - value = profile.get(key) - if isinstance(value, list): - support_raw.extend(value) - - def normalize(raw_items: list[Any], seen: set[str]) -> list[str]: - tokens: list[str] = [] - for raw in raw_items: - text = self._single_line(raw, 80) - if not text or text in seen: - continue - if text.isdigit(): - if len(text) < 5: - continue - elif len(text) < 2: - continue - seen.add(text) - tokens.append(text) - return tokens - - def stable_support(raw_items: list[Any]) -> list[Any]: - stable: list[Any] = [] - for raw in raw_items: - text = self._single_line(raw, 40) - if not text or len(text) > 16: - continue - if any(mark in text for mark in (",", ",", "。", "!", "?", " ", ":", ":", "|", "\n")): - continue - stable.append(text) - return stable - - seen_tokens: set[str] = set() - primary_tokens = normalize(primary_raw, seen_tokens) - support_tokens = normalize(stable_support(support_raw), seen_tokens) - tokens = [*primary_tokens, *support_tokens] - return { - "tokens": tokens[:18], - "primary_tokens": primary_tokens[:8], - "support_tokens": support_tokens[:12], - } @staticmethod def _sqlite_like_pattern(token: str) -> str: @@ -19635,204 +19502,10 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiUsersGroupsMixin): except (TypeError, ValueError): return default - def _livingmemory_match_info(self, content: str, metadata_text: str, token_bundle: dict[str, list[str]]) -> dict[str, Any]: - haystack = f"{content}\n{metadata_text}".lower() - score = 0.0 - primary_tokens = token_bundle.get("primary_tokens", []) - support_tokens = token_bundle.get("support_tokens", []) - matched_primary: list[str] = [] - matched_support: list[str] = [] - for token in primary_tokens: - text = token.lower() - if not text or text not in haystack: - continue - count = max(1, haystack.count(text)) - if token.isdigit(): - score += 9.0 + min(count, 4) - else: - score += min(8.0, 3.5 + len(token) * 0.65) + min(count - 1, 3) * 0.7 - matched_primary.append(token) - for token in support_tokens: - text = token.lower() - if not text or text not in haystack: - continue - count = max(1, haystack.count(text)) - score += min(3.0, 0.8 + len(token) * 0.25) + min(count - 1, 2) * 0.25 - matched_support.append(token) - accepted = bool(matched_primary) or (not primary_tokens and len(matched_support) >= 2) - return { - "accepted": accepted, - "score": round(score, 3), - "matched_tokens": [*matched_primary, *matched_support][:8], - "primary_hits": len(matched_primary), - "support_hits": len(matched_support), - } - def _livingmemory_item_from_document(self, row: sqlite3.Row, token_bundle: dict[str, list[str]]) -> dict[str, Any] | None: - metadata = self._json_dict(row["metadata"]) - content = str(row["text"] or "").strip() - match = self._livingmemory_match_info(content, str(row["metadata"] or ""), token_bundle) - if not match.get("accepted"): - return None - create_time = self._coerce_float(metadata.get("create_time")) - last_access = self._coerce_float(metadata.get("last_access_time")) - topics = metadata.get("topics") if isinstance(metadata.get("topics"), list) else [] - key_facts = metadata.get("key_facts") if isinstance(metadata.get("key_facts"), list) else [] - return { - "source": "documents", - "source_label": "长期记忆文档", - "id": row["doc_id"] or row["id"], - "score": match.get("score"), - "matched_tokens": match.get("matched_tokens", []), - "primary_hits": match.get("primary_hits", 0), - "support_hits": match.get("support_hits", 0), - "session_id": self._single_line(metadata.get("session_id"), 80), - "persona_id": self._single_line(metadata.get("persona_id"), 80), - "importance": metadata.get("importance"), - "created_at": str(row["created_at"] or ""), - "updated_at": str(row["updated_at"] or ""), - "create_time": create_time, - "last_access_time": last_access, - "topics": [self._single_line(item, 40) for item in topics[:8] if self._single_line(item, 40)], - "key_facts": [self._single_line(item, 120) for item in key_facts[:8] if self._single_line(item, 120)], - "preview": self._single_line(metadata.get("canonical_summary") or content, 260), - "content": content[:1800], - } - def _livingmemory_item_from_atom(self, row: sqlite3.Row, token_bundle: dict[str, list[str]]) -> dict[str, Any] | None: - content = str(row["content"] or "").strip() - entities = self._json_list(row["entities"]) - metadata = self._json_dict(row["metadata"]) - metadata_text = " ".join([str(row["entities"] or ""), str(row["metadata"] or "")]) - match = self._livingmemory_match_info(content, metadata_text, token_bundle) - if not match.get("accepted"): - return None - return { - "source": "atoms", - "source_label": "原子记忆", - "id": row["id"], - "parent_memory_id": row["parent_memory_id"], - "score": match.get("score"), - "matched_tokens": match.get("matched_tokens", []), - "primary_hits": match.get("primary_hits", 0), - "support_hits": match.get("support_hits", 0), - "session_id": self._single_line(row["session_id"], 80), - "persona_id": self._single_line(row["persona_id"], 80), - "importance": row["importance"], - "confidence": row["confidence"], - "created_at": str(row["created_at"] or ""), - "create_time": self._coerce_float(row["created_at"]), - "last_access_time": self._coerce_float(row["last_accessed_at"]), - "topics": [self._single_line(item, 40) for item in entities[:8] if self._single_line(item, 40)], - "key_facts": [self._single_line(item, 120) for item in metadata.get("key_facts", [])[:6]] if isinstance(metadata.get("key_facts"), list) else [], - "preview": self._single_line(content, 260), - "content": content[:1200], - } - def _livingmemory_item_from_graph_entry(self, row: sqlite3.Row, token_bundle: dict[str, list[str]]) -> dict[str, Any] | None: - metadata = self._json_dict(row["metadata"]) - content = str(row["content"] or "").strip() - match = self._livingmemory_match_info(content, str(row["metadata"] or ""), token_bundle) - if not match.get("accepted"): - return None - return { - "source": "graph", - "source_label": "关系图谱", - "id": row["entry_key"] or row["id"], - "parent_memory_id": row["source_memory_id"], - "score": match.get("score"), - "matched_tokens": match.get("matched_tokens", []), - "primary_hits": match.get("primary_hits", 0), - "support_hits": match.get("support_hits", 0), - "session_id": self._single_line(row["session_id"] or metadata.get("session_id"), 80), - "persona_id": self._single_line(row["persona_id"] or metadata.get("persona_id"), 80), - "importance": metadata.get("importance"), - "created_at": str(row["created_at"] or ""), - "updated_at": str(row["updated_at"] or ""), - "create_time": self._coerce_float(metadata.get("create_time")), - "last_access_time": self._coerce_float(metadata.get("last_access_time")), - "topics": [], - "key_facts": [], - "preview": self._single_line(content, 260), - "content": content[:1600], - } - def _query_livingmemory_for_tokens(self, db_path: Path, token_bundle: dict[str, list[str]], limit: int) -> list[dict[str, Any]]: - tokens = token_bundle.get("primary_tokens") or token_bundle.get("tokens", []) - if not tokens: - return [] - db_uri = f"file:{db_path.as_posix()}?mode=ro" - conn = sqlite3.connect(db_uri, uri=True, timeout=2.0) - conn.row_factory = sqlite3.Row - try: - conn.execute("PRAGMA query_only=ON") - conn.execute("PRAGMA busy_timeout=1500") - like_tokens = [self._sqlite_like_pattern(token) for token in tokens] - table_limit = max(80, limit * 8) - items: list[dict[str, Any]] = [] - - def where_for(columns: list[str]) -> tuple[str, list[str]]: - parts: list[str] = [] - params: list[str] = [] - for pattern in like_tokens: - sub = [] - for column in columns: - sub.append(f"{column} LIKE ? ESCAPE '\\'") - params.append(pattern) - parts.append("(" + " OR ".join(sub) + ")") - return " OR ".join(parts), params - - if self._sqlite_table_exists(conn, "documents"): - where, params = where_for(["text", "metadata"]) - for row in conn.execute( - f"SELECT id, doc_id, text, metadata, created_at, updated_at FROM documents WHERE {where} ORDER BY id DESC LIMIT ?", - [*params, table_limit], - ).fetchall(): - item = self._livingmemory_item_from_document(row, token_bundle) - if item: - items.append(item) - - if self._sqlite_table_exists(conn, "memory_atoms"): - where, params = where_for(["content", "entities", "metadata"]) - for row in conn.execute( - f"""SELECT id, parent_memory_id, atom_type, content, entities, importance, confidence, - created_at, last_accessed_at, session_id, persona_id, metadata - FROM memory_atoms - WHERE (status IS NULL OR status != 'expired') AND ({where}) - ORDER BY id DESC LIMIT ?""", - [*params, table_limit], - ).fetchall(): - item = self._livingmemory_item_from_atom(row, token_bundle) - if item: - items.append(item) - - if self._sqlite_table_exists(conn, "graph_entries"): - where, params = where_for(["content", "metadata", "session_id"]) - for row in conn.execute( - f"""SELECT id, entry_key, source_memory_id, session_id, persona_id, entry_type, - relation_type, content, metadata, created_at, updated_at - FROM graph_entries - WHERE {where} - ORDER BY id DESC LIMIT ?""", - [*params, table_limit], - ).fetchall(): - item = self._livingmemory_item_from_graph_entry(row, token_bundle) - if item: - items.append(item) - - seen: set[tuple[str, str]] = set() - unique: list[dict[str, Any]] = [] - for item in sorted(items, key=lambda entry: (entry.get("score") or 0, entry.get("last_access_time") or entry.get("create_time") or 0), reverse=True): - key = (str(item.get("source") or ""), str(item.get("id") or "")) - if key in seen: - continue - seen.add(key) - unique.append(item) - if len(unique) >= limit: - break - return unique - finally: - conn.close() @staticmethod def _sqlite_table_exists(conn: sqlite3.Connection, table: str) -> bool: diff --git a/tests/test_m6_r7_privacy_residue.py b/tests/test_m6_r7_privacy_residue.py index 8940f87..392a060 100644 --- a/tests/test_m6_r7_privacy_residue.py +++ b/tests/test_m6_r7_privacy_residue.py @@ -206,3 +206,57 @@ class R7RetiredEntryTests(unittest.TestCase): if __name__ == "__main__": unittest.main() + + +class R7BridgeGateTests(unittest.TestCase): + """桥的开关必须独立于 LivingMemory。 + + 运维版曾把 `enable_livingmemory_integration` 硬编码成 False(原意只是「不用 + LivingMemory」),而它同时是 MemoryCompanion 桥的总闸——同一份决策却规定 + MemoryCompanion 是唯一长期记忆源。结果整条 Bot 个人归档链路在 VM 上静默停摆, + 记忆库一条也写不进去,页面显示「记忆插件 暂不可用」。 + """ + + def make(self, **attrs): + # 必须用真实的 _memory_companion_bridge(走发现路径),不能用上面那个 + # 覆盖了该方法的 Adapter——覆盖版会把要测的闸门整个绕过去。 + class Bare(MemoryCompanionAdapterMixin): + pass + + adapter = Bare() + adapter.__dict__.update(attrs) + adapter._bridge_cache = adapter_mod._BRIDGE_UNPROBED + adapter._bridge_cache_ts = 0.0 + adapter._bridge_dependency_failure_until = 0.0 + return adapter + + def setUp(self): + # 按生产发现路径发布一个桥,否则「默认开启」也拿不到对象 + module = types.ModuleType("astrbot_plugin_memory_companion.main") + module.get_active_bridge = lambda: object() + sys.modules["astrbot_plugin_memory_companion"] = types.ModuleType("astrbot_plugin_memory_companion") + sys.modules["astrbot_plugin_memory_companion.main"] = module + self.addCleanup(sys.modules.pop, "astrbot_plugin_memory_companion.main", None) + self.addCleanup(sys.modules.pop, "astrbot_plugin_memory_companion", None) + + def test_livingmemory_flag_no_longer_gates_the_bridge(self): + adapter = self.make(enable_livingmemory_integration=False) + # 该开关已随 LivingMemory 一并移除,即使有人把它塞回来也不该影响桥 + self.assertIsNotNone(adapter._memory_companion_bridge()) + + def test_dedicated_flag_still_gates_the_bridge(self): + self.assertIsNone(self.make(enable_memory_companion_bridge=False)._memory_companion_bridge()) + + def test_bridge_is_on_by_default(self): + self.assertIsNotNone(self.make()._memory_companion_bridge()) + + def test_livingmemory_is_fully_removed_from_the_codebase(self): + root = pathlib.Path(__file__).resolve().parents[1] + offenders = [] + for path in root.rglob("*.py"): + if "tests" in path.parts or ".tmp" in path.parts or "__pycache__" in path.parts: + continue + for num, line in enumerate(path.read_text(encoding="utf-8", errors="ignore").splitlines(), 1): + if "livingmemory" in line.lower() and not line.strip().startswith("#"): + offenders.append(f"{path.name}:{num}") + self.assertEqual(offenders, [], f"仍有 LivingMemory 代码残留: {offenders}")