From 46364455ee64ecaceeec5a9ffd21e179e8a09e86 Mon Sep 17 00:00:00 2001 From: Codex Local Date: Thu, 30 Jul 2026 04:50:15 +0800 Subject: [PATCH] feat(c4): add bot profile bridge facade --- memory_companion_adapter.py | 75 ++++++++++++++++++ tests/test_c4_dual_plugin_profile_link.py | 92 +++++++++++++++++++++++ 2 files changed, 167 insertions(+) create mode 100644 tests/test_c4_dual_plugin_profile_link.py diff --git a/memory_companion_adapter.py b/memory_companion_adapter.py index 500ac29..29fa7ac 100644 --- a/memory_companion_adapter.py +++ b/memory_companion_adapter.py @@ -366,6 +366,81 @@ class MemoryCompanionAdapterMixin: self._bridge_last_status = status return status + async def _memory_companion_read_profile( + self, + profile: str, + *, + query: str = "", + limit: int = 10, + current_date: str = "", + current_window: str = "", + authorized: bool = False, + ) -> dict[str, Any]: + """Select one named Bot Profile without sending storage filters downstream.""" + + safe_profile = _single_line(profile, 80) + base = { + "ok": False, + "read_only": True, + "state": "degraded", + "degraded": True, + "pending": True, + "profile": safe_profile, + "items": [], + "warnings": [], + } + bridge = self._memory_companion_bridge() + if bridge is None: + return {**base, "state": self._bridge_last_status.get("state", "degraded"), "error_code": "bridge_unavailable"} + getter = getattr(bridge, "read_bot_profile", None) + if not callable(getter): + return {**base, "error_code": "profile_method_missing"} + try: + result = getter( + safe_profile, + query=_single_line(query, 240), + limit=max(1, min(100, int(limit or 10))), + current_date=_single_line(current_date, 20), + current_window=_single_line(current_window, 40), + authorized=bool(authorized), + ) + if asyncio.iscoroutine(result) or hasattr(result, "__await__"): + result = await result + except Exception as exc: + if self._memory_companion_optional_dependency_failed(exc, where="read_profile"): + return dict(self._bridge_last_status) + return {**base, "error_code": "profile_bridge_exception"} + if not isinstance(result, dict): + return {**base, "error_code": "invalid_profile_response"} + safe_item_keys = { + "record_id", "memory_domain", "memory_type", "subject", "date", "window", + "occurred_at", "source_kind", "source_refs", "evidence_level", "status", + "version", "summary", "reference", + } + safe_items: list[dict[str, Any]] = [] + for item in result.get("items", []) if isinstance(result.get("items"), list) else []: + if not isinstance(item, dict): + continue + safe_items.append({key: item[key] for key in safe_item_keys if key in item}) + self._bridge_last_status = { + **getattr(self, "_bridge_last_status", {}), + "last_profile": safe_profile, + } + return { + "ok": bool(result.get("ok", True)), + "read_only": True, + "state": _single_line(result.get("state"), 40) or "ready", + "degraded": bool(result.get("degraded", False)), + "pending": bool(result.get("pending", False)), + "profile": _single_line(result.get("profile") or safe_profile, 80), + "items": safe_items, + "warnings": [ + _single_line(item, 160) + for item in (result.get("warnings") or []) + if _single_line(item, 160) + ][:8], + } + def _memory_companion_coordination_status(self) -> dict[str, Any]: bridge = self._memory_companion_bridge() if bridge is None: diff --git a/tests/test_c4_dual_plugin_profile_link.py b/tests/test_c4_dual_plugin_profile_link.py new file mode 100644 index 0000000..9b995ea --- /dev/null +++ b/tests/test_c4_dual_plugin_profile_link.py @@ -0,0 +1,92 @@ +from __future__ import annotations + +import asyncio +import importlib +from pathlib import Path +import sys +import tempfile +import types + + +COMPANION_ROOT = Path(__file__).resolve().parents[1] +MEMORY_ROOT = COMPANION_ROOT.parents[1] / "astrbot_plugin_memory_companion-main" + + +def _load_modules(): + 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 + + companion_name = "c4_dual_companion" + companion = types.ModuleType(companion_name) + companion.__path__ = [str(COMPANION_ROOT)] + sys.modules[companion_name] = companion + adapter = importlib.import_module(f"{companion_name}.memory_companion_adapter") + + memory_name = "c4_dual_memory" + memory = types.ModuleType(memory_name) + memory.__path__ = [str(MEMORY_ROOT)] + sys.modules[memory_name] = memory + core = types.ModuleType(f"{memory_name}.core") + core.__path__ = [str(MEMORY_ROOT / "core")] + sys.modules[core.__name__] = core + bridge = importlib.import_module(f"{memory_name}.core.bridge") + service = importlib.import_module(f"{memory_name}.core.service") + store = importlib.import_module(f"{memory_name}.core.store") + return adapter.MemoryCompanionAdapterMixin, bridge.MemoryCompanionBridge, service.MemoryCompanionService, store.MemoryStore + + +def test_companion_profile_facade_reads_memory_profile_without_raw_payload_leak(): + mixin, bridge_type, service_type, store_type = _load_modules() + + class Companion(mixin): + def __init__(self, bridge): + self.enable_memory_companion_bridge = True + self.bridge = bridge + + def _memory_companion_bridge_uncached(self): + return self.bridge + + with tempfile.TemporaryDirectory() as temporary: + service = object.__new__(service_type) + service.store = store_type(Path(temporary) / "memory.db") + service.store.initialize() + service._schedule_memory_embedding = lambda *args, **kwargs: None + bridge = bridge_type(service) + + async def run(): + archived = await bridge.record_bot_personal_archive({ + "memory_type": "bot_creative_work", + "date": "2026-07-30", + "window": "afternoon", + "occurred_at": "2026-07-30T15:00:00+08:00", + "source_refs": ["companion:c4:creative"], + "idempotency_key": "c4:dual:creative", + "payload": {"summary": "raw creative detail must remain internal"}, + }) + companion = Companion(bridge) + result = await companion._memory_companion_read_profile( + "bot_creative", + query="creative", + current_date="2026-07-30", + current_window="afternoon", + ) + denied = await companion._memory_companion_read_profile("locked_frame_personal") + return archived, result, denied + + try: + archived, result, denied = asyncio.run(run()) + assert archived["ok"] is True + assert result["ok"] is True and result["read_only"] is True + assert len(result["items"]) == 1 + assert all("payload" not in item and "content" not in item and "evidence" not in item for item in result["items"]) + assert "raw creative detail" not in str(result) + assert denied["state"] == "forbidden" + finally: + service.store.close()