From bbd94d35a951b73793cc22d43a45e794609e9a80 Mon Sep 17 00:00:00 2001 From: YokiiroBW Date: Sun, 26 Jul 2026 03:14:04 +0800 Subject: [PATCH] feat: add bot personal memory bridge --- core/bot_personal.py | 47 ++++++++++++++ core/bridge.py | 84 ++++++++++++++++++++++++ core/service.py | 89 +++++++++++++++++++++++++- docs/运维记忆错题本.md | 10 +++ page_api.py | 36 +++++++++-- tests/test_bot_personal_memory.py | 103 ++++++++++++++++++++++++++++++ 6 files changed, 361 insertions(+), 8 deletions(-) create mode 100644 core/bot_personal.py create mode 100644 tests/test_bot_personal_memory.py diff --git a/core/bot_personal.py b/core/bot_personal.py new file mode 100644 index 0000000..03935b5 --- /dev/null +++ b/core/bot_personal.py @@ -0,0 +1,47 @@ +from __future__ import annotations + +from typing import Any + +from .models import clean_text, json_dumps + +BOT_PERSONAL_MEMORY_DOMAIN = "bot_self_schedule" +BOT_PERSONAL_SESSION_ID = "bot_personal" +BOT_PERSONAL_SCOPE = "private" +BOT_PERSONAL_VISIBILITY = "bot_self" + +BOT_PERSONAL_MEMORY_TYPES = { + "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", +} + + +def normalize_bot_personal_payload(value: Any, limit: int = 1200) -> dict[str, Any]: + if not isinstance(value, dict): + return {} + result: dict[str, Any] = {} + for key, item in list(value.items())[:32]: + name = clean_text(key, 80) + if not name or name in {"user", "group", "event", "raw_message", "prompt"}: + continue + if isinstance(item, (str, int, float, bool)) or item is None: + result[name] = clean_text(item, limit) if isinstance(item, str) else item + elif isinstance(item, dict): + result[name] = normalize_bot_personal_payload(item, 320) + elif isinstance(item, (list, tuple)): + result[name] = [clean_text(entry, 240) if isinstance(entry, str) else entry for entry in list(item)[:24]] + return result + + +def bot_personal_content(memory_type: str, payload: dict[str, Any]) -> str: + label = clean_text(memory_type, 80) + return f"Bot个人记忆[{label}]:{json_dumps(normalize_bot_personal_payload(payload, 800))}" \ No newline at end of file diff --git a/core/bridge.py b/core/bridge.py index f02a534..5357289 100644 --- a/core/bridge.py +++ b/core/bridge.py @@ -291,6 +291,90 @@ class MemoryCompanionBridge: async def record_schedule_fragment(self, *, content: str, **kwargs: Any) -> str: raise RuntimeError("bot_self_memory_rejected:user_memory_contract") + def probe_bot_personal_memory_capabilities(self) -> dict[str, Any]: + getter = getattr(self._plugin, "bridge_probe_bot_personal_memory_capabilities", None) + if not callable(getter): + return {"available": False, "read_only": False, "memory_domain": "bot_self_schedule", "warnings": ["bridge_method_unavailable"]} + return getter() + + async def record_bot_personal_memory( + self, + *, + memory_type: str, + payload: dict[str, Any] | None = None, + occurred_at: str = "", + idempotency_key: str = "", + **kwargs: Any, + ) -> str: + recorder = getattr(self._plugin, "record_bot_personal_memory", None) + if not callable(recorder): + raise RuntimeError("bot_personal_memory_unavailable") + return await recorder( + memory_type=memory_type, + payload=payload or {}, + occurred_at=occurred_at, + idempotency_key=idempotency_key, + **kwargs, + ) + + async def _record_bot_personal_type( + self, + memory_type: str, + *, + payload: dict[str, Any] | None = None, + occurred_at: str = "", + idempotency_key: str = "", + **kwargs: Any, + ) -> str: + return await self.record_bot_personal_memory( + memory_type=memory_type, + payload=payload, + occurred_at=occurred_at, + idempotency_key=idempotency_key, + **kwargs, + ) + + async def record_bot_schedule_plan(self, **kwargs: Any) -> str: + return await self._record_bot_personal_type("bot_schedule_plan", **kwargs) + + async def record_bot_observed_activity(self, **kwargs: Any) -> str: + return await self._record_bot_personal_type("bot_observed_activity", **kwargs) + + async def record_bot_schedule_reconciliation(self, **kwargs: Any) -> str: + return await self._record_bot_personal_type("bot_schedule_reconciliation", **kwargs) + + async def record_bot_window_snapshot(self, **kwargs: Any) -> str: + return await self._record_bot_personal_type("bot_window_snapshot", **kwargs) + + async def record_bot_daily_diary(self, **kwargs: Any) -> str: + return await self._record_bot_personal_type("bot_daily_diary", **kwargs) + + async def record_bot_creative_work(self, **kwargs: Any) -> str: + return await self._record_bot_personal_type("bot_creative_work", **kwargs) + + async def record_bot_media_memory(self, **kwargs: Any) -> str: + return await self._record_bot_personal_type("bot_media_memory", **kwargs) + + async def record_bot_subjective_memory(self, **kwargs: Any) -> str: + return await self._record_bot_personal_type("bot_subjective_memory", **kwargs) + + async def record_bot_shared_activity(self, **kwargs: Any) -> str: + return await self._record_bot_personal_type("bot_shared_activity", **kwargs) + + async def record_bot_detail_fragment(self, **kwargs: Any) -> str: + return await self._record_bot_personal_type("bot_detail_fragment", **kwargs) + + async def search_bot_personal_memory( + self, + query: str = "", + *, + limit: int = 10, + memory_types: list[str] | None = None, + ) -> list[dict[str, Any]]: + getter = getattr(self._plugin, "search_bot_personal_memory", None) + if not callable(getter): + return [] + return await getter(query, limit=limit, memory_types=memory_types) async def search( self, query: str, diff --git a/core/service.py b/core/service.py index b327eb3..4a0bc99 100644 --- a/core/service.py +++ b/core/service.py @@ -29,6 +29,15 @@ from .astrbot_compat import ( sanitize_request_history, ) from .bridge import serialize_memory +from .bot_personal import ( + BOT_PERSONAL_MEMORY_DOMAIN, + BOT_PERSONAL_MEMORY_TYPES, + BOT_PERSONAL_SCOPE, + BOT_PERSONAL_SESSION_ID, + BOT_PERSONAL_VISIBILITY, + bot_personal_content, + normalize_bot_personal_payload, +) from .temporal_context import build_reply_delay from .chat_import import HistoricalChatImporter from .classifier import MemoryClassifier @@ -714,7 +723,7 @@ class MemoryCompanionService: kwargs.get("source_plugin", "external"), ) raise - elif memory_domain not in {"calendar_history", "shared_or_mixed"}: + elif memory_domain not in {"calendar_history", "shared_or_mixed", BOT_PERSONAL_MEMORY_DOMAIN}: raise UserMemoryBoundaryError(f"memory_domain:{memory_domain or 'unknown'}") else: record.memory_domain = memory_domain @@ -855,6 +864,73 @@ class MemoryCompanionService: occurred_at=event_occurred_at, ) + async def record_bot_personal_memory( + self, + *, + memory_type: str, + payload: dict[str, Any] | None = None, + occurred_at: str = "", + idempotency_key: str = "", + source_plugin: str = "private_companion", + importance: float = 0.55, + confidence: float = 0.82, + ) -> str: + normalized_type = clean_text(memory_type, 80).lower() + if normalized_type not in BOT_PERSONAL_MEMORY_TYPES: + raise UserMemoryBoundaryError(f"bot_personal_memory_type:{normalized_type or 'unknown'}") + safe_payload = normalize_bot_personal_payload(payload or {}) + key = clean_text(idempotency_key, 240) + memory_id = self.stable_id("bot_personal", key or normalized_type, json_dumps(safe_payload)) + metadata = dict(safe_payload) + metadata.update({ + "memory_domain": BOT_PERSONAL_MEMORY_DOMAIN, + "bot_personal": True, + "idempotency_key": key, + "source_refs": safe_payload.get("source_refs", []), + "epistemic_type": "subjective" if normalized_type == "bot_subjective_memory" else "observed", + }) + reality_level = "persona_life" if normalized_type in {"bot_subjective_memory", "bot_daily_diary"} else "bot_action" + return await self.record_external_event( + memory_id=memory_id, + content=bot_personal_content(normalized_type, safe_payload), + memory_type=normalized_type, + memory_domain=BOT_PERSONAL_MEMORY_DOMAIN, + scope=BOT_PERSONAL_SCOPE, + session_id=BOT_PERSONAL_SESSION_ID, + visibility=BOT_PERSONAL_VISIBILITY, + sayability="indirect", + reality_level=reality_level, + lifecycle="stable_memory", + confidence=confidence, + importance=importance, + tags=["bot_personal", normalized_type], + metadata=metadata, + source_plugin=source_plugin, + occurred_at=clean_text(occurred_at, 80), + ) + + async def search_bot_personal_memory( + self, + query: str = "", + *, + limit: int = 10, + memory_types: list[str] | None = None, + ) -> list[dict[str, Any]]: + allowed_types = {clean_text(item, 80).lower() for item in (memory_types or []) if clean_text(item, 80)} + records = await self.store.list_memories( + limit=max(1, min(100, int(limit or 10) * 5)), + include_pending=False, + query=clean_text(query, 500), + scope=BOT_PERSONAL_SCOPE, + visibility=BOT_PERSONAL_VISIBILITY, + session_id=BOT_PERSONAL_SESSION_ID, + ) + selected = [ + record for record in records + if record.memory_domain == BOT_PERSONAL_MEMORY_DOMAIN + and (not allowed_types or record.memory_type in allowed_types) + ][: max(1, min(100, int(limit or 10)))] + return [serialize_memory(record, reason="bot_personal_profile") for record in selected] async def bridge_search( self, query: str, @@ -869,6 +945,17 @@ class MemoryCompanionService: def bridge_probe_archive_capabilities(self) -> dict[str, Any]: return archive_capabilities() + def bridge_probe_bot_personal_memory_capabilities(self) -> dict[str, Any]: + return { + "available": True, + "read_only": False, + "memory_domain": BOT_PERSONAL_MEMORY_DOMAIN, + "accepted_memory_types": sorted(BOT_PERSONAL_MEMORY_TYPES), + "four_window_schedule": True, + "daily_diary": True, + "idempotent_writes": True, + "user_memory_isolation": True, + } def bridge_probe_user_fact_query_capabilities(self) -> dict[str, Any]: return user_fact_query_capabilities() diff --git a/docs/运维记忆错题本.md b/docs/运维记忆错题本.md index 55f8e65..524dfc9 100644 --- a/docs/运维记忆错题本.md +++ b/docs/运维记忆错题本.md @@ -145,3 +145,13 @@ - 修复或规避:部署结果以独立只读命令复核;后续远程脚本必须使用 BOM-free 字节流;关键步骤使用 `set -euo pipefail` 并检查每个阶段退出码。 - 预防规则:远程 shell 脚本禁止直接使用可能带 BOM 的中文 PowerShell 字符串;部署后必须独立核对包哈希、备份、数据目录、服务状态、重启次数、插件加载、Archivist 和 traceback。 - 验证证据:提交 `7530774` 已部署;包 SHA-256 一致;备份和 `memory_companion.db` 存在;`astrbot.service active`;`NRestarts=0`;`Traceback=0`;`Q6_VM_SMOKE_OK`;Archivist `available=True search=True`。 + +## 2026-07-25 — M6.1 Bot 个人记忆域与 Locked Frame 收口 + +- 阶段:M6.1.1-M6.1.7 Bot 个人记忆模型、专用 Bridge、检索 Profile、只读观察窗与隔离测试 +- 类型:API契约 / 功能行为 / 测试 +- 现象:Locked Frame“个人记忆”原有分类主要依赖旧的 schedule/action/tag 类型,无法稳定识别四段式日程、睡前日记、创作、相册和主观记忆的新域。 +- 根因:Bot 自身数据与用户记忆、日历历史虽已在服务层分域,但页面入口未按 memory_domain=bot_self_schedule 做最终收口;陪伴侧也缺少专用远端写入和检索调用。 +- 修复或规避:新增 Bot 个人类型白名单和显式 Bridge 包装;默认检索继续阻止 Bot 域;Locked Frame 只读页面只接收 Bot 个人域或陪伴旧本地记录;远端 Bridge 失败时不阻断陪伴侧本地写入。 +- 预防规则:任何 Bot 自身日程读取必须显式使用 Bot personal profile;页面、Bridge、服务三层都要检查域、主体、可见性和来源,不能只看标签。 +- 验证证据:M6_MEMORY_TESTS_OK;compileall -q core tests page_api.py;git diff --check;专用 Bridge、幂等写入、默认检索隔离和观察窗分类已复核。 diff --git a/page_api.py b/page_api.py index 079a01a..2250640 100644 --- a/page_api.py +++ b/page_api.py @@ -1138,6 +1138,7 @@ class PluginPageApi: query=query, visibility="bot_self", ) + records = [record for record in records if self._is_bot_personal_record(record)] dates = self._private_companion_dates(status.get("plugin"), records) if not selected_date: selected_date = dates[0] if dates else "" @@ -1151,12 +1152,14 @@ class PluginPageApi: visibility="bot_self", ) records = self._merge_records_by_id(records, date_records) + records = [record for record in records if self._is_bot_personal_record(record)] payload["selected_date"] = selected_date payload["dates"] = dates payload["snapshot"] = self._private_companion_snapshot(status.get("plugin"), selected_date, records) payload.pop("plugin", None) filtered = [record for record in records if self._memory_date_key(record) == selected_date] if selected_date else records + filtered = [record for record in filtered if self._is_bot_personal_record(record)] payload["actions"] = [serialize_memory(record) for record in filtered if self._is_personal_action(record)][:limit] return self._ok(payload) @@ -1698,6 +1701,14 @@ class PluginPageApi: return "" return datetime.fromtimestamp(ts, ZoneInfo("Asia/Shanghai")).strftime("%Y-%m-%d %H:%M") + def _is_bot_personal_record(self, record: Any) -> bool: + if getattr(record, "visibility", "") != "bot_self": + return False + memory_domain = clean_text(getattr(record, "memory_domain", ""), 80) + if memory_domain == "bot_self_schedule": + return True + return getattr(record, "source_plugin", "") == "private_companion" + def _is_personal_action(self, record: Any) -> bool: tags = getattr(record, "tags", []) or [] tag_set = {clean_text(tag, 80) for tag in tags if clean_text(tag, 80)} @@ -1733,7 +1744,7 @@ class PluginPageApi: } memory_type = getattr(record, "memory_type", "") return ( - getattr(record, "visibility", "") == "bot_self" + self._is_bot_personal_record(record) and ( memory_type in action_types or bool(tag_set & positive_action_tags) @@ -1753,9 +1764,17 @@ class PluginPageApi: metadata = {} content = clean_text(getattr(record, "content", ""), 360) return ( - getattr(record, "visibility", "") == "bot_self" + self._is_bot_personal_record(record) and ( - getattr(record, "memory_type", "") == "schedule_fragment" + getattr(record, "memory_type", "") in { + "schedule_fragment", + "bot_schedule_plan", + "bot_observed_activity", + "bot_schedule_reconciliation", + "bot_window_snapshot", + "bot_detail_fragment", + "bot_calendar_event", + } or "schedule" in tag_set or "daily_plan" in tag_set or "daily_detail" in tag_set @@ -1766,7 +1785,7 @@ class PluginPageApi: ) def _is_personal_album_memory(self, record: Any) -> bool: - if getattr(record, "visibility", "") != "bot_self": + if not self._is_bot_personal_record(record): return False metadata = getattr(record, "metadata", {}) or {} if not isinstance(metadata, dict): @@ -1775,16 +1794,19 @@ class PluginPageApi: return False tags = {clean_text(tag, 80) for tag in (getattr(record, "tags", []) or []) if clean_text(tag, 80)} return ( - getattr(record, "memory_type", "") in {"image_action", "persona_life"} + getattr(record, "memory_type", "") in {"image_action", "persona_life", "bot_media_memory"} or bool(tags & {"daily_outfit", "outfit", "life_photo", "image", "current_state"}) or getattr(record, "source_plugin", "") == "private_companion" ) def _is_personal_subjective_memory(self, record: Any) -> bool: - if getattr(record, "visibility", "") != "bot_self": + if not self._is_bot_personal_record(record): return False tags = {clean_text(tag, 80) for tag in (getattr(record, "tags", []) or []) if clean_text(tag, 80)} - return bool(tags & {"dream", "dream_fragment", "subjective_memory", "bot_diary"}) + return ( + getattr(record, "memory_type", "") in {"bot_daily_diary", "bot_subjective_memory"} + or bool(tags & {"dream", "dream_fragment", "subjective_memory", "bot_diary"}) + ) def _compact_plan(self, plan: dict[str, Any]) -> dict[str, Any]: items = plan.get("items", []) diff --git a/tests/test_bot_personal_memory.py b/tests/test_bot_personal_memory.py new file mode 100644 index 0000000..182d66e --- /dev/null +++ b/tests/test_bot_personal_memory.py @@ -0,0 +1,103 @@ +import asyncio +import tempfile +from pathlib import Path + +from core.bridge import MemoryCompanionBridge +from core.models import EntityRef, MemoryRecord +from core.service import MemoryCompanionService +from core.store import MemoryStore +from core.visibility import VisibilityPolicy +from core.retrieval import RetrievalEngine + + +def test_bot_personal_capability_contract(): + service = object.__new__(MemoryCompanionService) + payload = service.bridge_probe_bot_personal_memory_capabilities() + assert payload["available"] is True + assert payload["memory_domain"] == "bot_self_schedule" + assert payload["four_window_schedule"] is True + assert payload["user_memory_isolation"] is True + + +def test_bot_personal_write_forces_domain_and_stable_idempotency(): + service = object.__new__(MemoryCompanionService) + calls = [] + + async def fake_record_external_event(**kwargs): + calls.append(kwargs) + return kwargs["memory_id"] + + service.record_external_event = fake_record_external_event + first = asyncio.run(service.record_bot_personal_memory( + memory_type="bot_window_snapshot", + payload={"date": "2026-07-25", "window": "morning", "source_refs": ["snapshot:1"]}, + occurred_at="2026-07-25T12:00:00+08:00", + idempotency_key="window_snapshot:2026-07-25:morning", + )) + second = asyncio.run(service.record_bot_personal_memory( + memory_type="bot_window_snapshot", + payload={"date": "2026-07-25", "window": "morning", "source_refs": ["snapshot:1"]}, + occurred_at="2026-07-25T12:00:00+08:00", + idempotency_key="window_snapshot:2026-07-25:morning", + )) + assert first == second + assert calls[0]["memory_domain"] == "bot_self_schedule" + assert calls[0]["visibility"] == "bot_self" + assert calls[0]["session_id"] == "bot_personal" + + +def test_bot_personal_search_excludes_user_memory(): + with tempfile.TemporaryDirectory() as temp: + store = MemoryStore(Path(temp) / "memory.db") + store.initialize() + store_records = [ + MemoryRecord( + id="bot-1", + memory_type="bot_daily_diary", + memory_domain="bot_self_schedule", + subject=EntityRef.bot_self(), + scope="private", + session_id="bot_personal", + visibility="bot_self", + reality_level="persona_life", + content="Bot 今天完成了创作。", + occurred_at="2026-07-25T21:00:00+08:00", + ), + MemoryRecord( + id="user-1", + memory_type="user_fact", + memory_domain="user_memory", + subject=EntityRef(kind="user", id="u1"), + scope="private", + session_id="private:u1", + visibility="private_pair", + reality_level="real_user_fact", + content="用户也喜欢创作。", + ), + ] + for record in store_records: + asyncio.run(store.insert_memory(record)) + service = object.__new__(MemoryCompanionService) + service.store = store + results = asyncio.run(service.search_bot_personal_memory("创作", limit=10)) + assert [item["id"] for item in results] == ["bot-1"] + store.close() + + +def test_default_retrieval_blocks_bot_personal_domain(): + engine = RetrievalEngine(MemoryStore(Path(tempfile.gettempdir()) / "unused-m6.db"), VisibilityPolicy()) + assert engine._memory_domain_block_reason(MemoryRecord(memory_domain="bot_self_schedule")) == "missing_user_subject" + + +def test_bridge_missing_bot_personal_write_degrades_explicitly(): + bridge = MemoryCompanionBridge(object()) + try: + asyncio.run(bridge.record_bot_personal_memory( + memory_type="bot_daily_diary", + payload={"date": "2026-07-25"}, + idempotency_key="diary:2026-07-25", + )) + except RuntimeError as exc: + assert str(exc) == "bot_personal_memory_unavailable" + else: + raise AssertionError("missing Bot personal Bridge must fail explicitly")