From 4e28cedfa67915e8caaacbb7bd9469c8d5d1fcb9 Mon Sep 17 00:00:00 2001 From: Codex Local Date: Thu, 30 Jul 2026 02:22:30 +0800 Subject: [PATCH] feat(c1): add companion identity and bridge contract --- _conf_schema.json | 16 +- bot_personal_contract.py | 270 +++++++++++++++++++++++ config_migration.py | 3 + main.py | 36 ++- memory_companion_adapter.py | 183 +++++++++++++-- plugin_identity.py | 64 ++++++ runtime_compat.py | 132 +++++++++++ tests/test_c1_contract.py | 91 ++++++++ tests/test_c1_dual_plugin_link.py | 81 +++++++ tests/test_c1_identity_runtime.py | 54 +++++ tests/test_c1_livingmemory_decoupling.py | 110 +++++++++ 11 files changed, 1018 insertions(+), 22 deletions(-) create mode 100644 bot_personal_contract.py create mode 100644 plugin_identity.py create mode 100644 runtime_compat.py create mode 100644 tests/test_c1_contract.py create mode 100644 tests/test_c1_dual_plugin_link.py create mode 100644 tests/test_c1_identity_runtime.py create mode 100644 tests/test_c1_livingmemory_decoupling.py diff --git a/_conf_schema.json b/_conf_schema.json index 82dae51..3cb07b5 100644 --- a/_conf_schema.json +++ b/_conf_schema.json @@ -6155,6 +6155,12 @@ "hint": "统一控制已适配的外部记忆插件协同,不只对应 LivingMemory。检测到“我会牢牢记住你”/MemoryCompanion 或 LivingMemory 时,在私聊和群聊提示词中按各自能力使用记忆上下文或召回工具;本插件继续负责人格、状态、关系和群聊气氛。", "default": true }, + "enable_memory_companion_bridge": { + "description": "独立启用 MemoryCompanion Bridge", + "type": "bool", + "hint": "仅控制 MemoryCompanion Bridge;关闭后陪伴侧本地聊天和本地记忆继续工作。缺失时按开启兼容旧配置。", + "default": true + }, "livingmemory_tool_name": { "description": "记忆召回工具名", "type": "string", @@ -6175,7 +6181,7 @@ "step": 0.1 }, "condition": { - "enable_livingmemory_integration": true + "enable_memory_companion_bridge": true } }, "enable_memory_companion_emotional_drift": { @@ -6184,7 +6190,7 @@ "hint": "从“我会牢牢记住你”拉取待处理情绪事件(伤痕触动/温暖回忆/脆弱共鸣),按安全阀应用到 Bot 当前能量和心情底色。每次私聊和主动消息生成前触发。", "default": true, "condition": { - "enable_livingmemory_integration": true + "enable_memory_companion_bridge": true } }, "enable_memory_companion_cross_window_emotion": { @@ -6202,7 +6208,7 @@ "hint": "日记生成后将首条梦境碎片写入“我会牢牢记住你”,带上 dream_fragment 标签和查询锚点,支持跨会话梦境连续性。", "default": true, "condition": { - "enable_livingmemory_integration": true + "enable_memory_companion_bridge": true } }, "enable_memory_companion_open_loop_search": { @@ -6211,7 +6217,7 @@ "hint": "主动消息生成前从“我会牢牢记住你”检索未完成的承诺和话题,注入到主动消息提示词中,形成承诺兑现闭环。", "default": true, "condition": { - "enable_livingmemory_integration": true + "enable_memory_companion_bridge": true } }, "enable_memory_companion_feature_context": { @@ -6220,7 +6226,7 @@ "hint": "主动消息生成/复核、当前状态问答、每日穿搭、自然语言生图、QQ 空间互动、群聊主动插话、私下创作和陪伴答疑等链路按需读取“我会牢牢记住你”的结构化上下文。关闭后这些链路不会主动召回记忆。", "default": true, "condition": { - "enable_livingmemory_integration": true + "enable_memory_companion_bridge": true } }, "enable_memory_companion_private_recall": { diff --git a/bot_personal_contract.py b/bot_personal_contract.py new file mode 100644 index 0000000..8e82778 --- /dev/null +++ b/bot_personal_contract.py @@ -0,0 +1,270 @@ +# -*- coding: utf-8 -*- +"""跨插件共享合同:Bot 个人归档 + 日程分级(陪伴分支) + +⚠️ 这个文件在两个插件里**各有一份,必须逐字相同**: + 陪伴插件:astrbot_plugin_private_companion/bot_personal_contract.py + 记忆插件:astrbot_plugin_memory_companion/core/bot_personal_contract.py + 权威副本在 peiban/doc/shared/bot_personal_contract.py。 + + 两个插件是独立的 AstrBot 插件包,互相不能 import,所以「共享常量」只能靠 + 「同一份文件复制两份 + 启动时指纹互校」来保证。任何改动必须同时满足三条: + + ① 两侧同一次提交(不允许一侧先合) + ② 升 CONTRACT_REVISION + ③ 重算并更新 CONTRACT_FINGERPRINT(python bot_personal_contract.py 会打印) + + 只依赖标准库。不要在这里 import 任何插件内部模块,否则复制到对侧会炸。 + +修改规则与背景见:peiban/doc/跨插件共享合同.md +""" +from __future__ import annotations + +import hashlib +import json + +CONTRACT_NAME = "bot_personal_archive" +CONTRACT_REVISION = 1 + +# --------------------------------------------------------------------------- +# 一、日程分级(原「四段」→ 陪伴分支五段) +# +# 这是**唯一定义源**。两侧任何地方需要窗口划分,都必须从这张表派生,不允许再写 +# 第二份硬编码——OPS 分支就是因为存在四份互不派生的副本,改一处改不动全部。 +# +# 边界与原版已持久化的主动配额桶(user["proactive_daypart_counts"], +# constants.py:489)完全对齐,所以「日程窗口」与「主动配额桶」共享切点, +# 但**仍是两套独立存储**:配额桶是计数器,窗口是快照/归档的维度,不要合并。 +# +# 字段:(slug, 中文名, 起始分钟, 结束分钟)。结束分钟 <= 起始分钟表示跨午夜。 +# --------------------------------------------------------------------------- +SCHEDULE_WINDOWS: tuple[tuple[str, str, int, int], ...] = ( + ("late_night", "深夜", 21 * 60, 6 * 60), # 21:00 - 次日 06:00 + ("morning", "早晨", 6 * 60, 11 * 60), # 06:00 - 11:00 + ("noon", "中午", 11 * 60, 14 * 60 + 30), # 11:00 - 14:30 + ("afternoon", "下午", 14 * 60 + 30, 18 * 60), # 14:30 - 18:00 + ("evening", "晚上", 18 * 60, 21 * 60), # 18:00 - 21:00 +) + +WINDOW_SLUGS: tuple[str, ...] = tuple(item[0] for item in SCHEDULE_WINDOWS) +WINDOW_NAMES: tuple[str, ...] = tuple(item[1] for item in SCHEDULE_WINDOWS) +WINDOW_SLUG_BY_NAME: dict[str, str] = {item[1]: item[0] for item in SCHEDULE_WINDOWS} +WINDOW_NAME_BY_SLUG: dict[str, str] = {item[0]: item[1] for item in SCHEDULE_WINDOWS} + +# 记忆侧 validate_bot_personal_envelope 用它做**硬校验**:不在集合里 → invalid_window, +# 归档静默失败。所以它必须由上表派生,不能手写。 +BOT_PERSONAL_WINDOWS = frozenset(WINDOW_SLUGS) + +# LLM 与用户口语里的窗口别名 → slug。只做输入归一,不参与判定。 +WINDOW_ALIASES: dict[str, str] = { + "深夜": "late_night", "凌晨": "late_night", "半夜": "late_night", "夜里": "late_night", + "早晨": "morning", "早上": "morning", "清晨": "morning", "上午": "morning", + "中午": "noon", "正午": "noon", "午间": "noon", "晌午": "noon", + "下午": "afternoon", + "晚上": "evening", "傍晚": "evening", "晚间": "evening", +} + +# 旧四段(OPS 22/06/12/18)→ 新五段的迁移映射。 +# 值为 None 表示「靠窗口名判不出来,必须看时间戳」,见 migrate_legacy_window()。 +LEGACY_WINDOW_MIGRATION: dict[str, str | None] = { + "late_night": "late_night", # 旧 22:00-06:00 ⊂ 新 21:00-06:00,可直接沿用 + "morning": None, # 旧 06:00-12:00 → 新 morning(06-11) + noon(11-12) + "afternoon": None, # 旧 12:00-18:00 → 新 noon(12-14:30) + afternoon(14:30-18) + "evening": None, # 旧 18:00-22:00 → 新 evening(18-21) + late_night(21-22) +} + + +def window_for_minutes(minutes: int) -> str: + """把「当日分钟数」归入窗口 slug。跨午夜的窗口拆成两截判定。 + + 这是**唯一判定实现**。带日期的判定(跨午夜时 window_date 归属哪一天)留在 + 陪伴侧 agenda_contracts.window_for_datetime,但它必须调用本函数取窗口名, + 不允许自己再判一次阈值。 + """ + try: + value = int(minutes) % (24 * 60) + except (TypeError, ValueError): + return "" + for slug, _name, start, end in SCHEDULE_WINDOWS: + if start < end: + if start <= value < end: + return slug + elif value >= start or value < end: + return slug + return "" + + +def normalize_window(value: object) -> str: + """把窗口名/别名/slug 归一成 slug;无法识别返回空串(**不要猜**)。""" + text = str(value or "").strip() + if not text: + return "" + lowered = text.lower() + if lowered in BOT_PERSONAL_WINDOWS: + return lowered + return WINDOW_ALIASES.get(text, "") + + +def migrate_legacy_window(old_window: object, minutes: object = None) -> str: + """旧四段窗口值 → 新五段 slug。 + + 拿得到当日分钟数就按时间重算;拿不到且旧值本身不唯一对应新值时返回空串, + 调用方应当**按旧名保留、只读不重算**,不要猜——猜错会让历史快照的窗口归属 + 和它内部的时间戳自相矛盾。 + """ + old = normalize_window(old_window) or str(old_window or "").strip().lower() + if minutes is not None: + recomputed = window_for_minutes(minutes) + if recomputed: + return recomputed + return LEGACY_WINDOW_MIGRATION.get(old) or "" + + +# --------------------------------------------------------------------------- +# 二、Bot 个人归档域 +# +# memory_domain 保持 OPS 时期的取值 "bot_self_schedule":它描述的是「Bot 自有 +# 日程域」,不含运维语义,改名要同步两侧 7 处 + 存量数据迁移,收益为零。 +# --------------------------------------------------------------------------- +BOT_PERSONAL_MEMORY_DOMAIN = "bot_self_schedule" +BOT_PERSONAL_SUBJECT = "bot_self" +BOT_PERSONAL_SESSION_ID = "bot_personal" +BOT_PERSONAL_SCOPE = "private" +BOT_PERSONAL_VISIBILITY = "bot_self" +BOT_PERSONAL_MAX_PAYLOAD_BYTES = 16 * 1024 + +# payload 结构本身未变 → 保持 1.0。 +BOT_PERSONAL_PAYLOAD_SCHEMA_VERSION = "1.0" +# 信封字段 window 的**值域**变了(四段→五段)→ 能力版本必升,且必须在能力探测里 +# 回传 windows,让调用方启动时就能发现两侧值域不一致,而不是等到归档 invalid_window。 +BOT_PERSONAL_CAPABILITY_SCHEMA_VERSION = "1.1" + +BOT_PERSONAL_MEMORY_TYPES: tuple[str, ...] = ( + "bot_schedule_plan", + "bot_observed_activity", + "bot_schedule_reconciliation", + "bot_window_snapshot", + "bot_daily_diary", + "bot_creative_work", + "bot_media_memory", + "bot_subjective_memory", + "bot_shared_activity", + "bot_detail_fragment", + "bot_calendar_event", + "bot_proactive_message", +) + +# memory_type → (source_kind, 默认 evidence_level, 默认 status)。 +# 记忆侧一律用合同 source_kind 覆盖调用方上报值,所以两侧必须同表, +# 否则创作/梦境/日历会被标成「真实观察」。 +TYPE_CONTRACTS: dict[str, tuple[str, str, str]] = { + "bot_schedule_plan": ("planned", "L0", "planned"), + "bot_observed_activity": ("observed", "L2", "active"), + "bot_schedule_reconciliation": ("reconciled", "L3", "completed"), + "bot_window_snapshot": ("projection", "L2", "completed"), + "bot_daily_diary": ("subjective", "L1", "completed"), + "bot_creative_work": ("creative", "L1", "active"), + "bot_media_memory": ("media", "L1", "active"), + "bot_subjective_memory": ("subjective", "L1", "active"), + "bot_shared_activity": ("shared", "L1", "active"), + "bot_detail_fragment": ("detail", "L1", "active"), + "bot_calendar_event": ("calendar", "L1", "active"), + "bot_proactive_message": ("proactive", "L1", "active"), +} + +EVIDENCE_LEVELS: tuple[str, ...] = ("L0", "L1", "L2", "L3") + +# 幂等键前缀表。归档链路每条写入都要落在这些前缀之一下,方便对账与去重排查。 +# ⚠️ agenda_snapshot / reconciliation 两类的 id 内部含窗口 slug,改分级后新旧 key +# 不同源:**旧 key 不重写,新记录用新 slug**(见迁移策略)。 +IDEMPOTENCY_KEY_PREFIXES: tuple[str, ...] = ( + "agenda_snapshot", # agenda_snapshot:{snapshot_id} 含窗口 slug + "reconciliation", # reconciliation:{reconciliation_id} 含窗口 slug + "observed", # observed:{activity_id} + "daily_plan", # daily_plan:{date} + "detail", # detail:{date}:{start}:{end} + "diary", # diary:{date} + "calendar", # calendar:{event_id}:{action} + "proactive", # proactive:{user_id}:{action}:{content[:80]} + "creative", # creative:{project_id|title}:{chunks} + "photo", # photo:{media_id} + "daily_outfit", # daily_outfit:{date} + "dream", # dream:{text[:120]}:{mood} + "qzone", # qzone:{tid|content[:100]} ← 娱乐能力,陪伴分支保留 +) + + +def capability_descriptor(*, available: bool = True, read_only: bool = False) -> dict[str, object]: + """记忆侧 probe_bot_personal_memory_capabilities 的标准返回骨架。 + + windows / memory_types / contract_fingerprint 三个字段是给陪伴侧做启动自检用的: + 对不上就说明两侧合同文件漂移了,应当直接告警并停用归档,而不是带着不一致跑。 + """ + return { + "available": bool(available), + "read_only": bool(read_only), + "memory_domain": BOT_PERSONAL_MEMORY_DOMAIN, + "contract_name": CONTRACT_NAME, + "contract_revision": CONTRACT_REVISION, + "contract_fingerprint": CONTRACT_FINGERPRINT, + "capability_schema_version": BOT_PERSONAL_CAPABILITY_SCHEMA_VERSION, + "payload_schema_version": BOT_PERSONAL_PAYLOAD_SCHEMA_VERSION, + "windows": list(WINDOW_SLUGS), + "memory_types": list(BOT_PERSONAL_MEMORY_TYPES), + "max_payload_bytes": BOT_PERSONAL_MAX_PAYLOAD_BYTES, + "warnings": [], + } + + +def _fingerprint_source() -> str: + """参与指纹的只有**跨插件必须一致**的值。注释、别名表、辅助函数不参与—— + 别名只影响本地输入归一,两侧不一致不会造成数据不一致。""" + canonical = { + "contract_name": CONTRACT_NAME, + "contract_revision": CONTRACT_REVISION, + "windows": [[slug, name, start, end] for slug, name, start, end in SCHEDULE_WINDOWS], + "memory_domain": BOT_PERSONAL_MEMORY_DOMAIN, + "subject": BOT_PERSONAL_SUBJECT, + "session_id": BOT_PERSONAL_SESSION_ID, + "scope": BOT_PERSONAL_SCOPE, + "visibility": BOT_PERSONAL_VISIBILITY, + "max_payload_bytes": BOT_PERSONAL_MAX_PAYLOAD_BYTES, + "payload_schema_version": BOT_PERSONAL_PAYLOAD_SCHEMA_VERSION, + "capability_schema_version": BOT_PERSONAL_CAPABILITY_SCHEMA_VERSION, + "memory_types": list(BOT_PERSONAL_MEMORY_TYPES), + "type_contracts": {k: list(v) for k, v in TYPE_CONTRACTS.items()}, + "evidence_levels": list(EVIDENCE_LEVELS), + "idempotency_key_prefixes": list(IDEMPOTENCY_KEY_PREFIXES), + } + return json.dumps(canonical, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + + +def compute_contract_fingerprint() -> str: + return hashlib.sha256(_fingerprint_source().encode("utf-8")).hexdigest()[:16] + + +# 由 compute_contract_fingerprint() 生成。改了上面任何常量都要重跑本文件更新它。 +CONTRACT_FINGERPRINT = "5b8a97c1527dcc62" + + +def contract_self_check() -> list[str]: + """两侧启动时各自跑一遍,再互相比对 CONTRACT_FINGERPRINT。""" + problems: list[str] = [] + if CONTRACT_FINGERPRINT != compute_contract_fingerprint(): + problems.append("contract_fingerprint_stale: 常量改过但没重算指纹") + if len(set(WINDOW_SLUGS)) != len(WINDOW_SLUGS): + problems.append("duplicate_window_slug") + if set(TYPE_CONTRACTS) != set(BOT_PERSONAL_MEMORY_TYPES): + problems.append("type_contracts_out_of_sync") + covered = {window_for_minutes(m) for m in range(0, 24 * 60)} + if covered != set(WINDOW_SLUGS): + problems.append(f"window_coverage_gap: 未覆盖或多余 {covered ^ set(WINDOW_SLUGS)}") + for alias, slug in WINDOW_ALIASES.items(): + if slug not in BOT_PERSONAL_WINDOWS: + problems.append(f"alias_points_to_unknown_window: {alias}->{slug}") + return problems + + +if __name__ == "__main__": # pragma: no cover + print("CONTRACT_FINGERPRINT =", compute_contract_fingerprint()) + issues = contract_self_check() + print("self_check:", "OK" if not issues else issues) diff --git a/config_migration.py b/config_migration.py index 1842c1a..bd081e1 100644 --- a/config_migration.py +++ b/config_migration.py @@ -61,6 +61,9 @@ LEGACY_KEY_ALIASES: dict[str, tuple[str, ...]] = { "response_review_mode": ("passive_review_mode",), } +# Independent from the legacy LivingMemory compatibility switch. +MEMORY_COMPANION_BRIDGE_KEY = "enable_memory_companion_bridge" + LEGACY_PROACTIVE_ACTION_FLAG_KEYS: dict[str, str] = { "photo_text": "enable_photo_text_action", "screen_peek": "enable_screen_glance_action", diff --git a/main.py b/main.py index 9b750c9..8e8c69c 100644 --- a/main.py +++ b/main.py @@ -122,6 +122,14 @@ from .helpers import ( _today_key, ) from .config_migration import migrate_flat_config_into_schema_groups +from .bot_personal_contract import capability_descriptor, contract_self_check +from .plugin_identity import ( + PLUGIN_ID, + PLUGIN_VERSION, + is_module_path_for_package, + plugin_identity_snapshot, +) +from .runtime_compat import probe_runtime_capabilities from .user_rest_gate import UserRestGateMixin from .busy_reply_gate import BusyReplyGateMixin from .memory_companion_adapter import MemoryCompanionAdapterMixin @@ -1030,6 +1038,23 @@ class PrivateCompanionPlugin( self._external_realtime_activities: dict[str, dict[str, Any]] = {} self.config = config c = config + self.plugin_identity = plugin_identity_snapshot() + self.runtime_capabilities = probe_runtime_capabilities( + context=context, + plugin_name=PLUGIN_ID, + plugin_version=PLUGIN_VERSION, + ) + contract_issues = tuple(contract_self_check()) + self.bot_personal_capabilities = capability_descriptor(available=not contract_issues, read_only=False) + self.bot_personal_capabilities.update( + { + "state": "ready" if not contract_issues else "degraded", + "degraded": bool(contract_issues), + "warnings": list(contract_issues), + } + ) + if contract_issues: + logger.warning("[PrivateCompanion] Bot Personal 合同自检降级: %s", ";".join(contract_issues)) self.data_dir = StarTools.get_data_dir(PLUGIN_NAME) os.makedirs(self.data_dir, exist_ok=True) self.data_file = os.path.join(self.data_dir, "companions.json") @@ -2167,6 +2192,15 @@ class PrivateCompanionPlugin( self.page_api = None self._register_page_api_if_available() + def plugin_identity_status(self) -> dict[str, Any]: + return dict(self.plugin_identity) + + def runtime_compatibility_status(self) -> dict[str, Any]: + return self.runtime_capabilities.to_dict() + + def bot_personal_capability_status(self) -> dict[str, Any]: + return dict(self.bot_personal_capabilities) + def _sqlite_wal_candidate_paths(self) -> list[Path]: data_root = Path(get_astrbot_data_path()) candidates = [ @@ -2320,7 +2354,7 @@ class PrivateCompanionPlugin( repaired = 0 for handler in list(star_handlers_registry): handler_module_path = str(getattr(handler, "handler_module_path", "") or "") - if not handler_module_path.startswith(package_prefix): + if not is_module_path_for_package(handler_module_path, package_prefix): continue handler_name = str(getattr(handler, "handler_name", "") or "") if not handler_name: diff --git a/memory_companion_adapter.py b/memory_companion_adapter.py index b1be5ad..69f1184 100644 --- a/memory_companion_adapter.py +++ b/memory_companion_adapter.py @@ -11,6 +11,15 @@ from typing import Any from astrbot.api import logger +from .bot_personal_contract import ( + BOT_PERSONAL_CAPABILITY_SCHEMA_VERSION, + BOT_PERSONAL_MEMORY_DOMAIN, + BOT_PERSONAL_MEMORY_TYPES, + BOT_PERSONAL_PAYLOAD_SCHEMA_VERSION, + CONTRACT_FINGERPRINT, + CONTRACT_REVISION, + WINDOW_SLUGS, +) from .helpers import _missing_optional_model_dependency, _path_text, _safe_float, _safe_int, _single_line @@ -33,6 +42,62 @@ class MemoryCompanionAdapterMixin: _BRIDGE_CACHE_TTL: float = 30.0 _bridge_dependency_failure_until: float = 0.0 _bridge_dependency_failure_module: str = "" + _bridge_last_status: dict[str, Any] = {} + + @staticmethod + def _memory_companion_coerce_bool(value: Any, default: bool = True) -> bool: + if isinstance(value, str): + normalized = value.strip().lower() + if normalized in {"1", "true", "yes", "on", "enabled"}: + return True + if normalized in {"0", "false", "no", "off", "disabled"}: + return False + if value is None: + return default + return bool(value) + + def _memory_companion_bridge_enabled(self) -> bool: + """Read the Bridge switch without consulting the legacy LivingMemory switch.""" + for attr in ("enable_memory_companion_bridge", "memory_companion_bridge_enabled"): + if hasattr(self, attr): + return self._memory_companion_coerce_bool(getattr(self, attr), True) + config = getattr(self, "config", None) + marker = object() + for key in ( + "enable_memory_companion_bridge", + "memory_companion_bridge.enabled", + "private_companion_bridge.enabled", + ): + value: Any = marker + if isinstance(config, dict): + current: Any = config + for part in key.split("."): + if not isinstance(current, dict) or part not in current: + current = marker + break + current = current[part] + value = current + else: + getter = getattr(config, "get", None) + if callable(getter): + try: + value = getter(key, marker) + except Exception: + value = marker + if value is not marker: + return self._memory_companion_coerce_bool(value, True) + return True + + def _memory_companion_degraded_status(self, reason: str, **extra: Any) -> dict[str, Any]: + status = { + "available": False, + "state": "local_only" if reason == "bridge_disabled" else "degraded", + "degraded": reason != "bridge_disabled", + "reason": reason, + } + status.update({key: value for key, value in extra.items() if value is not None}) + self._bridge_last_status = status + return status def _memory_companion_optional_dependency_failed(self, exc: BaseException, *, where: str = "") -> bool: module = _missing_optional_model_dependency(exc) @@ -42,6 +107,11 @@ class MemoryCompanionAdapterMixin: self._bridge_cache_ts = 0.0 self._bridge_dependency_failure_until = time.monotonic() + 300.0 self._bridge_dependency_failure_module = module + self._memory_companion_degraded_status( + "optional_dependency_missing", + module=module, + where=_single_line(where, 80) or "-", + ) logger.warning( "[PrivateCompanion] 记忆插件可选模型依赖缺失,已临时降级 MemoryCompanion 桥接: module=%s where=%s err=%s", module, @@ -51,16 +121,38 @@ class MemoryCompanionAdapterMixin: return True def _memory_companion_bridge(self) -> Any | None: - if not getattr(self, "enable_livingmemory_integration", True): + if not self._memory_companion_bridge_enabled(): + self._memory_companion_degraded_status("bridge_disabled") return None now = time.monotonic() if now < self._bridge_dependency_failure_until: return None if self._bridge_cache is not None and (now - self._bridge_cache_ts) < self._BRIDGE_CACHE_TTL: return self._bridge_cache + if ( + self._bridge_cache is None + and (now - self._bridge_cache_ts) < self._BRIDGE_CACHE_TTL + and self._bridge_last_status.get("reason") + in { + "bridge_missing", + "capability_probe_missing", + "capability_probe_exception", + "capability_probe_invalid", + "capability_contract_mismatch", + } + ): + return None + self._bridge_last_status = {} bridge = self._memory_companion_bridge_uncached() + if bridge is not None: + capability_status = self._memory_companion_probe_capabilities(bridge) + self._bridge_last_status = capability_status + if not capability_status.get("available", False): + bridge = None self._bridge_cache = bridge self._bridge_cache_ts = now + if bridge is None and not self._bridge_last_status: + self._memory_companion_degraded_status("bridge_missing") return bridge def _memory_companion_bridge_uncached(self) -> Any | None: @@ -74,15 +166,6 @@ class MemoryCompanionAdapterMixin: bridge = self._memory_companion_bridge_from_module(module) if bridge is not None: return bridge - for module in list(sys.modules.values()): - module_vars = getattr(module, "__dict__", {}) if module is not None else {} - if not isinstance(module_vars, dict): - continue - if module_vars.get("PLUGIN_NAME", "") not in {"astrbot_plugin_memory_companion", "astrbot_plugin_remember_you", "我会牢牢记住你", "RememberYou"}: - continue - bridge = self._memory_companion_bridge_from_module(module) - if bridge is not None: - return bridge return None def _memory_companion_bridge_from_module(self, module: Any | None) -> Any | None: @@ -96,21 +179,89 @@ class MemoryCompanionAdapterMixin: self._memory_companion_optional_dependency_failed(exc, where="get_active_bridge") return None + def _memory_companion_probe_capabilities(self, bridge: Any) -> dict[str, Any]: + try: + getter = getattr(bridge, "probe_bot_personal_memory_capabilities", None) + except Exception: + return self._memory_companion_degraded_status("capability_probe_exception") + if not callable(getter): + return self._memory_companion_degraded_status("capability_probe_missing") + try: + result = getter() + except Exception as exc: + if self._memory_companion_optional_dependency_failed(exc, where="capability_probe"): + return dict(self._bridge_last_status) + return self._memory_companion_degraded_status("capability_probe_exception") + if not isinstance(result, dict): + return self._memory_companion_degraded_status("capability_probe_invalid") + + expected_windows = list(WINDOW_SLUGS) + expected_memory_types = list(BOT_PERSONAL_MEMORY_TYPES) + observed_windows = result.get("windows") + observed_memory_types = result.get("memory_types") + observed_domain = result.get("memory_domain", result.get("domain", "")) + mismatches: list[str] = [] + if result.get("contract_fingerprint") != CONTRACT_FINGERPRINT: + mismatches.append("contract_fingerprint") + if result.get("contract_revision") != CONTRACT_REVISION: + mismatches.append("contract_revision") + if result.get("capability_schema_version") != BOT_PERSONAL_CAPABILITY_SCHEMA_VERSION: + mismatches.append("capability_schema_version") + if result.get("payload_schema_version") != BOT_PERSONAL_PAYLOAD_SCHEMA_VERSION: + mismatches.append("payload_schema_version") + if observed_domain != BOT_PERSONAL_MEMORY_DOMAIN: + mismatches.append("memory_domain") + if observed_windows != expected_windows: + mismatches.append("windows") + if observed_memory_types != expected_memory_types: + mismatches.append("memory_types") + if result.get("available") is not True: + mismatches.append("available") + if mismatches: + return self._memory_companion_degraded_status( + "capability_contract_mismatch", + mismatches=tuple(mismatches), + ) + + status = dict(result) + status.setdefault("state", "ready") + status.setdefault("degraded", False) + status.setdefault("available", True) + self._bridge_last_status = status + return status + def _memory_companion_coordination_status(self) -> dict[str, Any]: bridge = self._memory_companion_bridge() if bridge is None: - return {"available": False} - getter = getattr(bridge, "coordination_status", None) + return dict(self._bridge_last_status or self._memory_companion_degraded_status("bridge_missing")) + if self._bridge_last_status.get("reason") in { + "capability_probe_missing", + "capability_probe_exception", + "capability_probe_invalid", + "capability_contract_mismatch", + }: + return dict(self._bridge_last_status) + try: + getter = getattr(bridge, "coordination_status", None) + except Exception: + return self._memory_companion_degraded_status("bridge_exception") if not callable(getter): - return {"available": True} + return self._memory_companion_degraded_status("method_missing", method="coordination_status") try: status = getter() except Exception as exc: if self._memory_companion_optional_dependency_failed(exc, where="coordination_status"): - return {"available": False, "error": f"missing optional dependency: {self._bridge_dependency_failure_module}"} + return dict(self._bridge_last_status) logger.debug("[PrivateCompanion] MemoryCompanion 协同状态读取失败: %s", _single_line(exc, 120)) - return {"available": True, "error": _single_line(exc, 120)} - return status if isinstance(status, dict) else {"available": True} + return self._memory_companion_degraded_status("bridge_exception", error=_single_line(exc, 120)) + if not isinstance(status, dict): + return self._memory_companion_degraded_status("invalid_status", status_type=type(status).__name__) + result = dict(status) + result.setdefault("available", True) + result.setdefault("state", "ready") + result.setdefault("degraded", False) + self._bridge_last_status = result + return result def _memory_companion_token_usage_summary(self) -> dict[str, Any]: bridge = self._memory_companion_bridge() diff --git a/plugin_identity.py b/plugin_identity.py new file mode 100644 index 0000000..22b8caf --- /dev/null +++ b/plugin_identity.py @@ -0,0 +1,64 @@ +from __future__ import annotations + +import re +from typing import Any + + +PLUGIN_ID = "astrbot_plugin_private_companion" +PLUGIN_DISPLAY_NAME = "我会永远陪着你" +PLUGIN_VERSION = "5.10.6" +PLUGIN_DATA_DIRECTORY_KEY = PLUGIN_ID + +_IDENTITY_SEPARATORS = re.compile(r"[.:/\\]+") + + +def _identity_text(value: Any, *, limit: int = 240) -> str: + return " ".join(str(value or "").split())[:limit] + + +def _identity_segments(value: Any) -> tuple[str, ...]: + text = _identity_text(value) + if not text: + return () + return tuple(part for part in _IDENTITY_SEPARATORS.split(text) if part) + + +def is_exact_plugin_id(value: Any, expected: str = PLUGIN_ID) -> bool: + """Match an ID only as a complete token, never as a raw prefix.""" + + candidate = _identity_text(value) + target = _identity_text(expected, limit=120) + if not candidate or not target: + return False + return candidate == target or target in _identity_segments(candidate) + + +def is_module_path_for_package(module_path: Any, package_prefix: Any) -> bool: + """Accept a package and its descendants while rejecting similarly named packages.""" + + module = _identity_text(module_path, limit=320).replace("/", ".").replace("\\", ".") + package = _identity_text(package_prefix, limit=240).replace("/", ".").replace("\\", ".") + if not module or not package: + return False + return module == package or module.startswith(f"{package}.") + + +def plugin_identity_snapshot() -> dict[str, str]: + return { + "plugin_id": PLUGIN_ID, + "display_name": PLUGIN_DISPLAY_NAME, + "version": PLUGIN_VERSION, + "data_directory": PLUGIN_DATA_DIRECTORY_KEY, + "match_rule": "exact_id_or_module_segment", + } + + +__all__ = [ + "PLUGIN_DATA_DIRECTORY_KEY", + "PLUGIN_DISPLAY_NAME", + "PLUGIN_ID", + "PLUGIN_VERSION", + "is_exact_plugin_id", + "is_module_path_for_package", + "plugin_identity_snapshot", +] diff --git a/runtime_compat.py b/runtime_compat.py new file mode 100644 index 0000000..efdedba --- /dev/null +++ b/runtime_compat.py @@ -0,0 +1,132 @@ +from __future__ import annotations + +import importlib +import importlib.metadata +from dataclasses import asdict, dataclass, field +from typing import Any + + +_REQUIRED_CAPABILITIES = ( + "star_base", + "data_dir", + "event_hooks", + "provider_request", + "message_components", +) + + +@dataclass(frozen=True) +class RuntimeCapabilities: + plugin_name: str + plugin_version: str + astrbot_version: str = "unknown" + api_generation: str = "unknown" + compatibility_level: str = "unsupported" + capabilities: dict[str, bool] = field(default_factory=dict) + missing_required: tuple[str, ...] = () + warnings: tuple[str, ...] = () + + def to_dict(self) -> dict[str, Any]: + result = asdict(self) + result["missing_required"] = list(self.missing_required) + result["warnings"] = list(self.warnings) + return result + + +def _probe_import(module_name: str, attribute_name: str) -> bool: + try: + module = importlib.import_module(module_name) + return hasattr(module, attribute_name) + except Exception: + return False + + +def _version_from_module() -> str: + for module_name in ("astrbot", "astrbot.core"): + try: + module = importlib.import_module(module_name) + except Exception: + continue + for attr_name in ("__version__", "VERSION", "version"): + value = getattr(module, attr_name, "") + if value: + return str(value) + for distribution_name in ("astrbot", "AstrBot"): + try: + return importlib.metadata.version(distribution_name) + except importlib.metadata.PackageNotFoundError: + continue + except Exception: + break + return "unknown" + + +def _probe_event_hooks() -> dict[str, bool]: + try: + module = importlib.import_module("astrbot.api.event") + event_filter = getattr(module, "filter", None) + except Exception: + event_filter = None + return { + "event_hooks": event_filter is not None, + "llm_request_hook": callable(getattr(event_filter, "on_llm_request", None)), + "llm_response_hook": callable(getattr(event_filter, "on_llm_response", None)), + "event_message_type": callable(getattr(event_filter, "event_message_type", None)), + "command_group": callable(getattr(event_filter, "command_group", None)), + } + + +def probe_runtime_capabilities( + *, + context: Any = None, + event: Any = None, + plugin_name: str = "", + plugin_version: str = "", +) -> RuntimeCapabilities: + """Probe optional AstrBot APIs without making import-time decisions.""" + + capabilities = { + "star_base": _probe_import("astrbot.api.star", "Star"), + "data_dir": _probe_import("astrbot.api.star", "StarTools"), + "provider_request": _probe_import("astrbot.api.provider", "ProviderRequest"), + "message_components": _probe_import("astrbot.api.message_components", "Plain") + or _probe_import("astrbot.core.message.components", "Plain"), + } + capabilities.update(_probe_event_hooks()) + capabilities["web_api"] = callable(getattr(context, "register_web_api", None)) + capabilities["platform_manager"] = getattr(context, "platform_manager", None) is not None + capabilities["event_unified_msg_origin"] = bool(event is not None and hasattr(event, "unified_msg_origin")) + capabilities["event_send"] = any( + callable(getattr(event, name, None)) for name in ("send", "send_message", "plain_result") + ) + capabilities["event_stop"] = callable(getattr(event, "stop_event", None)) + + missing_required = tuple(name for name in _REQUIRED_CAPABILITIES if not capabilities.get(name, False)) + warnings: list[str] = [] + if not capabilities.get("web_api"): + warnings.append("runtime_web_api_unavailable") + if not capabilities.get("platform_manager"): + warnings.append("runtime_platform_manager_unavailable") + if not capabilities.get("event_unified_msg_origin"): + warnings.append("runtime_event_scope_unavailable_until_event") + if missing_required: + level = "unsupported" + elif warnings: + level = "degraded" + else: + level = "full" + version = _version_from_module() + api_generation = "4.x" if version.startswith("4.") else "unknown" + return RuntimeCapabilities( + plugin_name=plugin_name, + plugin_version=plugin_version, + astrbot_version=version, + api_generation=api_generation, + compatibility_level=level, + capabilities=capabilities, + missing_required=missing_required, + warnings=tuple(warnings), + ) + + +__all__ = ["RuntimeCapabilities", "probe_runtime_capabilities"] diff --git a/tests/test_c1_contract.py b/tests/test_c1_contract.py new file mode 100644 index 0000000..cab434d --- /dev/null +++ b/tests/test_c1_contract.py @@ -0,0 +1,91 @@ +from __future__ import annotations + +import hashlib +import importlib.util +from pathlib import Path + + +COMPANION_ROOT = Path(__file__).resolve().parents[1] +PEIBAN_ROOT = COMPANION_ROOT.parents[1] +CONTRACT_PATH = COMPANION_ROOT / "bot_personal_contract.py" +MEMORY_CONTRACT_PATH = PEIBAN_ROOT / "astrbot_plugin_memory_companion-main" / "core" / "bot_personal_contract.py" +SHARED_CONTRACT_PATH = PEIBAN_ROOT / "doc" / "shared" / "bot_personal_contract.py" + + +def load_contract(path: Path, name: str): + spec = importlib.util.spec_from_file_location(name, path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +contract = load_contract(CONTRACT_PATH, "companion_bot_personal_contract") +memory_contract = load_contract(MEMORY_CONTRACT_PATH, "memory_bot_personal_contract") + + +def test_contract_bytes_match_authority_and_other_side(): + expected = SHARED_CONTRACT_PATH.read_bytes() + assert CONTRACT_PATH.read_bytes() == expected + assert MEMORY_CONTRACT_PATH.read_bytes() == expected + assert hashlib.sha256(CONTRACT_PATH.read_bytes()).digest() == hashlib.sha256( + MEMORY_CONTRACT_PATH.read_bytes() + ).digest() + + +def test_frozen_contract_values_and_self_check(): + for module in (contract, memory_contract): + assert module.CONTRACT_FINGERPRINT == "5b8a97c1527dcc62" + assert module.CONTRACT_REVISION == 1 + assert module.BOT_PERSONAL_CAPABILITY_SCHEMA_VERSION == "1.1" + assert module.BOT_PERSONAL_PAYLOAD_SCHEMA_VERSION == "1.0" + assert module.BOT_PERSONAL_MEMORY_DOMAIN == "bot_self_schedule" + assert len(module.BOT_PERSONAL_MEMORY_TYPES) == 12 + assert set(module.TYPE_CONTRACTS) == set(module.BOT_PERSONAL_MEMORY_TYPES) + assert module.contract_self_check() == [] + assert module.compute_contract_fingerprint() == module.CONTRACT_FINGERPRINT + + +def test_five_window_boundaries_and_midnight_wrap(): + expected = { + 0: "late_night", + 359: "late_night", + 360: "morning", + 659: "morning", + 660: "noon", + 869: "noon", + 870: "afternoon", + 1079: "afternoon", + 1080: "evening", + 1259: "evening", + 1260: "late_night", + 1439: "late_night", + } + for minutes, slug in expected.items(): + assert contract.window_for_minutes(minutes) == slug + assert contract.window_for_minutes(-1) == "late_night" + assert contract.window_for_minutes(24 * 60) == "late_night" + + +def test_normalize_window_and_legacy_migration_never_guesses_without_timestamp(): + assert contract.normalize_window(" MORNING ") == "morning" + assert contract.normalize_window("凌晨") == "late_night" + assert contract.normalize_window("unknown") == "" + assert contract.migrate_legacy_window("late_night") == "late_night" + assert contract.migrate_legacy_window("morning") == "" + assert contract.migrate_legacy_window("afternoon") == "" + assert contract.migrate_legacy_window("evening") == "" + assert contract.migrate_legacy_window("morning", 11 * 60) == "noon" + + +def test_descriptor_fields_and_cross_side_descriptor_equality(): + companion = contract.capability_descriptor() + memory = memory_contract.capability_descriptor() + assert companion == memory + assert companion["contract_fingerprint"] == "5b8a97c1527dcc62" + assert companion["contract_revision"] == 1 + assert companion["capability_schema_version"] == "1.1" + assert companion["payload_schema_version"] == "1.0" + assert companion["memory_domain"] == "bot_self_schedule" + assert companion["windows"] == list(contract.WINDOW_SLUGS) + assert len(companion["memory_types"]) == 12 diff --git a/tests/test_c1_dual_plugin_link.py b/tests/test_c1_dual_plugin_link.py new file mode 100644 index 0000000..f93da78 --- /dev/null +++ b/tests/test_c1_dual_plugin_link.py @@ -0,0 +1,81 @@ +from __future__ import annotations + +import importlib.util +import sys +import types +from pathlib import Path +from types import SimpleNamespace + + +ROOT = Path(__file__).resolve().parents[1] +PEIBAN_ROOT = ROOT.parents[1] +MEMORY_ROOT = PEIBAN_ROOT / "astrbot_plugin_memory_companion-main" + +if "astrbot.api" not in sys.modules: + astrbot = types.ModuleType("astrbot") + api = types.ModuleType("astrbot.api") + api.logger = SimpleNamespace(warning=lambda *args, **kwargs: None, debug=lambda *args, **kwargs: None) + sys.modules["astrbot"] = astrbot + sys.modules["astrbot.api"] = api + + +def _load_companion_adapter(): + package_name = "c1_dual_companion" + package = types.ModuleType(package_name) + package.__path__ = [str(ROOT)] + sys.modules[package_name] = package + spec = importlib.util.spec_from_file_location( + f"{package_name}.memory_companion_adapter", + ROOT / "memory_companion_adapter.py", + ) + assert spec and spec.loader + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module.MemoryCompanionAdapterMixin + + +def _load_memory_bridge(): + package = types.ModuleType("c1_dual_memory") + package.__path__ = [str(MEMORY_ROOT)] + sys.modules[package.__name__] = package + core = types.ModuleType("c1_dual_memory.core") + core.__path__ = [str(MEMORY_ROOT / "core")] + sys.modules[core.__name__] = core + spec = importlib.util.spec_from_file_location( + "c1_dual_memory.core.bridge", + MEMORY_ROOT / "core" / "bridge.py", + ) + assert spec and spec.loader + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module.MemoryCompanionBridge + + +MemoryCompanionAdapterMixin = _load_companion_adapter() +MemoryCompanionBridge = _load_memory_bridge() + + +class _Companion(MemoryCompanionAdapterMixin): + def __init__(self, bridge): + self.enable_memory_companion_bridge = True + self.bridge = bridge + + def _memory_companion_bridge_uncached(self): + return self.bridge + + +def test_chat_companion_accepts_chat_memory_capability_contract(): + bridge = MemoryCompanionBridge( + SimpleNamespace(companion_coordination_status=lambda: {"available": True, "state": "ready"}) + ) + companion = _Companion(bridge) + + assert companion._memory_companion_bridge() is bridge + probe = bridge.probe_bot_personal_memory_capabilities() + assert companion._bridge_last_status["contract_fingerprint"] == probe["contract_fingerprint"] + status = companion._memory_companion_coordination_status() + assert status["available"] is True + assert status["state"] == "ready" + assert probe["available"] is True diff --git a/tests/test_c1_identity_runtime.py b/tests/test_c1_identity_runtime.py new file mode 100644 index 0000000..246c027 --- /dev/null +++ b/tests/test_c1_identity_runtime.py @@ -0,0 +1,54 @@ +from __future__ import annotations + +import importlib.util +import sys +from pathlib import Path +from types import SimpleNamespace + +ROOT = Path(__file__).resolve().parents[1] + + +def _load_module(name: str, path: Path): + spec = importlib.util.spec_from_file_location(name, path) + assert spec and spec.loader + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + spec.loader.exec_module(module) + return module + + +identity = _load_module("c1_plugin_identity", ROOT / "plugin_identity.py") +runtime = _load_module("c1_runtime_compat", ROOT / "runtime_compat.py") +PLUGIN_ID = identity.PLUGIN_ID + + +def test_plugin_identity_uses_complete_tokens(): + assert identity.is_exact_plugin_id(PLUGIN_ID) + assert identity.is_exact_plugin_id(f"data.plugins.{PLUGIN_ID}.main") + assert not identity.is_exact_plugin_id(f"{PLUGIN_ID}_ops") + assert not identity.is_exact_plugin_id(f"{PLUGIN_ID}2") + assert not identity.is_exact_plugin_id("astrbot_plugin_memory_companion") + + +def test_handler_package_boundary_rejects_similarly_named_package(): + assert identity.is_module_path_for_package("astrbot_plugin_private_companion.main", PLUGIN_ID) + assert identity.is_module_path_for_package("astrbot_plugin_private_companion.pages.api", PLUGIN_ID) + assert not identity.is_module_path_for_package("astrbot_plugin_private_companion_ops.main", PLUGIN_ID) + + +def test_identity_snapshot_freezes_public_name_and_data_key(): + snapshot = identity.plugin_identity_snapshot() + assert snapshot["plugin_id"] == PLUGIN_ID + assert snapshot["data_directory"] == PLUGIN_ID + assert snapshot["match_rule"] == "exact_id_or_module_segment" + + +def test_runtime_probe_is_non_blocking_and_structured(): + status = runtime.probe_runtime_capabilities(context=SimpleNamespace(), event=None, plugin_name=PLUGIN_ID, plugin_version="5.10.6") + payload = status.to_dict() + assert payload["plugin_name"] == PLUGIN_ID + assert payload["plugin_version"] == "5.10.6" + assert payload["compatibility_level"] in {"full", "degraded", "unsupported"} + assert isinstance(payload["capabilities"], dict) + assert isinstance(payload["missing_required"], list) + assert isinstance(payload["warnings"], list) diff --git a/tests/test_c1_livingmemory_decoupling.py b/tests/test_c1_livingmemory_decoupling.py new file mode 100644 index 0000000..6097720 --- /dev/null +++ b/tests/test_c1_livingmemory_decoupling.py @@ -0,0 +1,110 @@ +from __future__ import annotations + +import importlib.util +import sys +import types +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] + +if "astrbot.api" not in sys.modules: + astrbot = types.ModuleType("astrbot") + api = types.ModuleType("astrbot.api") + api.logger = types.SimpleNamespace(warning=lambda *args, **kwargs: None, debug=lambda *args, **kwargs: None) + sys.modules["astrbot"] = astrbot + sys.modules["astrbot.api"] = api + + +def _load_adapter(): + package_name = "c1_private_companion" + package = types.ModuleType(package_name) + package.__path__ = [str(ROOT)] + sys.modules[package_name] = package + spec = importlib.util.spec_from_file_location( + f"{package_name}.memory_companion_adapter", + ROOT / "memory_companion_adapter.py", + ) + assert spec and spec.loader + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module.MemoryCompanionAdapterMixin + + +MemoryCompanionAdapterMixin = _load_adapter() + + +def _load_contract(): + spec = importlib.util.spec_from_file_location("c1_companion_contract", ROOT / "bot_personal_contract.py") + assert spec and spec.loader + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +CONTRACT = _load_contract() + + +class _ProbeBridge: + def probe_bot_personal_memory_capabilities(self): + result = CONTRACT.capability_descriptor() + result.update({"available": True, "state": "ready", "degraded": False}) + return result + + +class _Plugin(MemoryCompanionAdapterMixin): + def __init__(self, bridge=True, livingmemory=True, bridge_object=None): + self.enable_memory_companion_bridge = bridge + self.enable_livingmemory_integration = livingmemory + self.bridge_object = _ProbeBridge() if bridge_object is True else bridge_object + + def _memory_companion_bridge_uncached(self): + return self.bridge_object + + +def test_bridge_and_livingmemory_switches_are_orthogonal(): + bridge = _ProbeBridge() + assert _Plugin(True, True, bridge)._memory_companion_bridge() is bridge + assert _Plugin(True, False, bridge)._memory_companion_bridge() is bridge + assert _Plugin(False, True, bridge)._memory_companion_bridge() is None + assert _Plugin(False, False, bridge)._memory_companion_bridge() is None + + +def test_missing_bridge_is_observable_local_only(): + plugin = _Plugin(True, False, None) + status = plugin._memory_companion_coordination_status() + assert status["available"] is False + assert status["state"] == "degraded" + assert status["reason"] == "bridge_missing" + + +def test_missing_or_mismatched_capability_probe_is_degraded_without_remote_use(): + missing = _Plugin(True, False, object()) + assert missing._memory_companion_bridge() is None + assert missing._memory_companion_coordination_status()["reason"] == "capability_probe_missing" + + class _MismatchedBridge(_ProbeBridge): + def probe_bot_personal_memory_capabilities(self): + result = super().probe_bot_personal_memory_capabilities() + result["contract_fingerprint"] = "wrong" + return result + + mismatched = _Plugin(True, False, _MismatchedBridge()) + assert mismatched._memory_companion_bridge() is None + status = mismatched._memory_companion_coordination_status() + assert status["reason"] == "capability_contract_mismatch" + assert "contract_fingerprint" in status["mismatches"] + + +def test_prefixed_or_livingmemory_modules_do_not_drive_bridge(monkeypatch): + module = types.ModuleType("third_party_livingmemory_prefix") + module.PLUGIN_NAME = "astrbot_plugin_memory_companion_extra" + module.get_active_bridge = lambda: object() + monkeypatch.setitem(sys.modules, module.__name__, module) + plugin = _Plugin(True, False, None) + assert MemoryCompanionAdapterMixin._memory_companion_bridge_uncached(plugin) is None + + +def test_legacy_livingmemory_migration_entrypoint_remains(): + assert (ROOT / "integration_status.py").exists()