diff --git a/_conf_schema.json b/_conf_schema.json index 1cefac7..6f8bced 100644 --- a/_conf_schema.json +++ b/_conf_schema.json @@ -657,7 +657,7 @@ } }, "private_companion_bridge": { - "description": "陪伴插件协同", + "description": "记忆插件协同", "hint": "与主动陪伴插件协调记忆、连续对话和自我时间线,减少重复注入和提示词污染。", "type": "object", "items": { diff --git a/core/bridge.py b/core/bridge.py index a22d099..f120882 100644 --- a/core/bridge.py +++ b/core/bridge.py @@ -15,6 +15,61 @@ from .profile_api import build_profile_result LOCAL_TZ = ZoneInfo("Asia/Shanghai") +_COMPANION_RELATIONSHIP_PHASES = { + "deeply_distant", + "strongly_distant", + "distant", + "acquaintance", + "familiar", + "close", + "intimate", + "deeply_bonded", +} + + +def sanitize_companion_relationship_projection(value: Any) -> dict[str, Any]: + fallback = {"status": "invalid", "read_only": True, "projection": {}} + if type(value) is not dict: + return fallback + if value.get("schema_version") != "chat.relationship_projection.v1": + return fallback + if value.get("authority") != "private_companion.relationship_score" or value.get("read_only") is not True: + return fallback + phase_key = value.get("phase_key") + if type(phase_key) is not str or phase_key not in _COMPANION_RELATIONSHIP_PHASES: + return fallback + score = value.get("score") + if type(score) is not int or not -1200 <= score <= 1200: + return fallback + soft = value.get("soft_behaviors") + if type(soft) is not dict or any(type(item) is not bool for item in soft.values()): + return fallback + try: + proactive_care_limit = int(value.get("proactive_care_limit") or 0) + except (TypeError, ValueError): + proactive_care_limit = 0 + projection = { + "schema_version": "chat.relationship_projection.v1", + "authority": "private_companion.relationship_score", + "read_only": True, + "score": score, + "phase_key": phase_key, + "phase_label": clean_text(value.get("phase_label"), 40), + "tone": clean_text(value.get("tone"), 160), + "address_level": clean_text(value.get("address_level"), 120), + "proactive_care_limit": max(0, min(30, proactive_care_limit)), + "soft_behaviors": { + key: bool(soft.get(key, False)) + for key in ( + "allow_playful_jokes", + "allow_followup", + "allow_memory_mention", + "allow_daily_care", + ) + }, + } + return {"status": "accepted", "read_only": True, "projection": projection} + def _local_time_label(value: Any) -> str: text = clean_text(value, 80) @@ -41,6 +96,10 @@ class MemoryCompanionBridge: self._plugin = plugin self._capability_cache = CapabilityCache() + def consume_relationship_projection(self, projection: Any) -> dict[str, Any]: + """Validate a read-only Companion relationship projection without persisting it.""" + return sanitize_companion_relationship_projection(projection) + async def record_event( self, *, diff --git a/core/models.py b/core/models.py index 1abd397..9194db9 100644 --- a/core/models.py +++ b/core/models.py @@ -78,6 +78,12 @@ class SessionContext: strict_session_only: bool = False preferred_address: str = "" preferred_address_locked: bool = False + relationship_authority_source: str = "" + companion_relationship_score: int = 0 + companion_relationship_phase_key: str = "" + companion_relationship_phase_label: str = "" + companion_relationship_tone: str = "" + companion_relationship_address_level: str = "" @property def current_target_id(self) -> str: diff --git a/core/service.py b/core/service.py index 5ff69ef..b7fc6de 100644 --- a/core/service.py +++ b/core/service.py @@ -23,7 +23,7 @@ from .astrbot_compat import ( remove_temp_text, sanitize_request_history, ) -from .bridge import serialize_memory +from .bridge import sanitize_companion_relationship_projection, serialize_memory from .bot_personal_dto import ( BotPersonalArchiveDTO, BotPersonalValidationError, @@ -387,6 +387,7 @@ class MemoryCompanionService: async def handle_llm_request(self, event: Any, req: Any) -> None: ctx = await self.identity.resolve_event_context(event) self._sanitize_session_context_message_text(ctx) + self._apply_companion_relationship_projection(ctx, event=event, req=req) self._apply_private_companion_preferred_address(ctx, req=req, event=event) if self._private_companion_internal_generation_event(event): return @@ -677,6 +678,41 @@ class MemoryCompanionService: drop, ) + @staticmethod + def _apply_companion_relationship_projection( + ctx: SessionContext, + *, + event: Any = None, + req: Any = None, + ) -> None: + if ctx.scope != "private": + return + raw_projection: Any = None + for target in (event, req): + if target is None: + continue + for attr in ( + "private_companion_context", + "companion_context", + "memory_companion_context", + ): + payload = getattr(target, attr, None) + if isinstance(payload, dict) and isinstance(payload.get("relationship_projection"), dict): + raw_projection = payload.get("relationship_projection") + break + if raw_projection is not None: + break + consumed = sanitize_companion_relationship_projection(raw_projection) + projection = consumed.get("projection") if isinstance(consumed, dict) else None + if not isinstance(projection, dict): + return + ctx.relationship_authority_source = "private_companion.relationship_score" + ctx.companion_relationship_score = int(projection.get("score") or 0) + ctx.companion_relationship_phase_key = clean_text(projection.get("phase_key"), 40) + ctx.companion_relationship_phase_label = clean_text(projection.get("phase_label"), 40) + ctx.companion_relationship_tone = clean_text(projection.get("tone"), 160) + ctx.companion_relationship_address_level = clean_text(projection.get("address_level"), 120) + @staticmethod def _apply_private_companion_preferred_address( ctx: SessionContext, @@ -7918,7 +7954,12 @@ class MemoryCompanionService: recent_ids.append(message_id) state["recent_touch_message_ids"] = recent_ids[-self._RELATIONSHIP_TOUCH_HISTORY_LIMIT :] state["updated_at"] = utc_now() - self._maybe_transition_phase(ctx, state) + if ctx.relationship_authority_source == "private_companion.relationship_score": + state["companion_phase_key"] = clean_text(ctx.companion_relationship_phase_key, 40) + state["companion_phase_label"] = clean_text(ctx.companion_relationship_phase_label, 40) + state["phase_authority"] = "private_companion.relationship_score" + else: + self._maybe_transition_phase(ctx, state) self._save_relationship_phase_state() return True @@ -8027,6 +8068,18 @@ class MemoryCompanionService: "不必每句都带称呼;关系阶段建议、历史称呼、显示名和旧记忆只作识别资料," "不能另造或追加亲昵称呼。若对方本轮明确要求改称呼,以本轮最新要求为准。" ) + if ctx.relationship_authority_source == "private_companion.relationship_score": + label = clean_text(ctx.companion_relationship_phase_label, 40) or clean_text( + ctx.companion_relationship_phase_key, + 40, + ) + tone = clean_text(ctx.companion_relationship_tone, 160) + address = clean_text(ctx.companion_relationship_address_level, 120) + return ( + f"陪伴插件是长期亲密度权威:当前阶段为“{label or '未标注'}”。" + f"基础语气按“{tone or '自然、尊重当前节奏'}”,称呼尺度按“{address or '沿用已确认称呼'}”。" + "Memory 仅提供记忆触动趋势和相关事实,不得用自身阶段另行升级称呼、语气或权限。" + ) state = self._get_relationship_phase(ctx) user_address_phase = state.get("current_address_phase", "") relationship_phase = state.get("phase", "acquaintance") diff --git a/pages/记忆面板/app.js b/pages/记忆面板/app.js index 7d44ce8..35b5506 100644 --- a/pages/记忆面板/app.js +++ b/pages/记忆面板/app.js @@ -60,7 +60,7 @@ const SECONDARY_NAV = { { id: "retrieval", label: "检索召回", sublabel: "候选、Embedding、Rerank", badge: "召回" }, { id: "config:memory_injection", label: "记忆注入", sublabel: "注入数量、字数与日志", badge: "注入" }, { id: "config:context_orchestration", label: "注入编排", sublabel: "分槽调度与当前状态保护", badge: "编排" }, - { id: "config:private_companion_bridge", label: "陪伴协同", sublabel: "桥接、去重与提示清理", badge: "联动" }, + { id: "config:private_companion_bridge", label: "记忆插件协同", sublabel: "与陪伴插件桥接、去重和清理提示", badge: "联动" }, { id: "config:visibility", label: "可见性", sublabel: "跨窗口默认边界", badge: "权限" }, { id: "topology", label: "权限拓扑", sublabel: "可视化记忆权限矩阵", badge: "拓扑" }, { id: "config:knowledge_graph", label: "图谱关联", sublabel: "节点、边与检索扩展", badge: "图谱" }, diff --git a/tests/test_req027_relationship_authority.py b/tests/test_req027_relationship_authority.py new file mode 100644 index 0000000..e48ab34 --- /dev/null +++ b/tests/test_req027_relationship_authority.py @@ -0,0 +1,147 @@ +from __future__ import annotations + +import sys +from pathlib import Path +from types import MethodType, SimpleNamespace +import unittest + + +ROOT = Path(__file__).resolve().parents[1] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + +from core.bridge import sanitize_companion_relationship_projection +from core.models import SessionContext +from core.service import MemoryCompanionService + + +def valid_projection() -> dict: + return { + "schema_version": "chat.relationship_projection.v1", + "authority": "private_companion.relationship_score", + "read_only": True, + "score": 620, + "phase_key": "close", + "phase_label": "亲近", + "tone": "温暖、自然", + "address_level": "使用已确认昵称", + "proactive_care_limit": 2, + "soft_behaviors": { + "allow_playful_jokes": True, + "allow_followup": True, + "allow_memory_mention": True, + "allow_daily_care": True, + }, + } + + +class Req027RelationshipAuthorityTests(unittest.TestCase): + def test_bridge_accepts_only_the_read_only_fixed_contract(self) -> None: + projection = valid_projection() + projection.update({"owner": True, "cross_user_query": True, "p4_bypass": True}) + result = sanitize_companion_relationship_projection(projection) + self.assertEqual("accepted", result["status"]) + accepted = result["projection"] + self.assertEqual("private_companion.relationship_score", accepted["authority"]) + self.assertTrue(accepted["read_only"]) + self.assertEqual("close", accepted["phase_key"]) + for forbidden in ("owner", "cross_user_query", "p4_bypass"): + self.assertNotIn(forbidden, accepted) + + for mutation in ( + {"schema_version": "chat.relationship_projection.v2"}, + {"authority": "memory.relationship_phase"}, + {"read_only": False}, + {"score": 1201}, + {"phase_key": "forged"}, + {"soft_behaviors": {"allow_followup": "true"}}, + ): + with self.subTest(mutation=mutation): + hostile = valid_projection() + hostile.update(mutation) + self.assertEqual("invalid", sanitize_companion_relationship_projection(hostile)["status"]) + + malformed_limit = valid_projection() + malformed_limit["proactive_care_limit"] = {"owner": True} + sanitized = sanitize_companion_relationship_projection(malformed_limit) + self.assertEqual("accepted", sanitized["status"]) + self.assertEqual(0, sanitized["projection"]["proactive_care_limit"]) + + def test_private_context_consumes_projection_but_group_context_does_not(self) -> None: + event = SimpleNamespace(private_companion_context={"relationship_projection": valid_projection()}) + private = SessionContext(session_id="telegram:FriendMessage:u1", scope="private", user_id="u1") + MemoryCompanionService._apply_companion_relationship_projection(private, event=event) + self.assertEqual("private_companion.relationship_score", private.relationship_authority_source) + self.assertEqual(620, private.companion_relationship_score) + self.assertEqual("close", private.companion_relationship_phase_key) + + group = SessionContext(session_id="telegram:GroupMessage:g1", scope="group", group_id="g1", user_id="u1") + MemoryCompanionService._apply_companion_relationship_projection(group, event=event) + self.assertEqual("", group.relationship_authority_source) + self.assertEqual("", group.companion_relationship_phase_key) + + def test_companion_authority_stops_memory_phase_transition_but_keeps_momentum(self) -> None: + service = MemoryCompanionService.__new__(MemoryCompanionService) + state = { + "phase": "acquaintance", + "momentum": 0.0, + "touch_count": 0, + "recent_touch_message_ids": [], + } + calls = {"transition": 0, "save": 0} + service._get_relationship_phase = MethodType(lambda _self, _ctx: state, service) + service._maybe_transition_phase = MethodType( + lambda _self, _ctx, _state: calls.__setitem__("transition", calls["transition"] + 1), + service, + ) + service._save_relationship_phase_state = MethodType( + lambda _self: calls.__setitem__("save", calls["save"] + 1), + service, + ) + + authoritative = SessionContext( + session_id="telegram:FriendMessage:u1", + scope="private", + user_id="u1", + message_id="m1", + relationship_authority_source="private_companion.relationship_score", + companion_relationship_phase_key="close", + companion_relationship_phase_label="亲近", + ) + self.assertTrue(service._update_relationship_phase_momentum(authoritative, touch_type="warm")) + self.assertGreater(state["momentum"], 0) + self.assertEqual(0, calls["transition"]) + self.assertEqual("private_companion.relationship_score", state["phase_authority"]) + self.assertEqual("close", state["companion_phase_key"]) + + fallback = SessionContext( + session_id="telegram:FriendMessage:u2", + scope="private", + user_id="u2", + message_id="m2", + ) + self.assertTrue(service._update_relationship_phase_momentum(fallback, touch_type="warm")) + self.assertEqual(1, calls["transition"]) + self.assertEqual(2, calls["save"]) + + def test_address_hint_uses_companion_phase_and_memory_declares_trend_only(self) -> None: + service = MemoryCompanionService.__new__(MemoryCompanionService) + ctx = SessionContext( + session_id="telegram:FriendMessage:u1", + scope="private", + user_id="u1", + relationship_authority_source="private_companion.relationship_score", + companion_relationship_phase_key="close", + companion_relationship_phase_label="亲近", + companion_relationship_tone="温暖、自然", + companion_relationship_address_level="使用已确认昵称", + ) + hint = service._address_hint_for_injection(ctx) + self.assertIn("陪伴插件是长期亲密度权威", hint) + self.assertIn("亲近", hint) + self.assertIn("温暖、自然", hint) + self.assertIn("Memory 仅提供记忆触动趋势", hint) + + +if __name__ == "__main__": + unittest.main()