diff --git a/_conf_schema.json b/_conf_schema.json index e089d97..bd0b4fa 100644 --- a/_conf_schema.json +++ b/_conf_schema.json @@ -8497,6 +8497,15 @@ "enable_humanized_states": true } }, + "enable_group_cycle_awareness": { + "description": "Allow minimal Bot cycle tone boundary in permitted groups", + "hint": "Default off. Reads only the Bot simulated state for reply pacing. It never records user health facts or group-private body details.", + "type": "bool", + "default": false, + "condition": { + "enable_cycle_state": true + } + }, "enable_advanced_cycle_strategy": { "description": "启用六阶段周期策略", "type": "bool", diff --git a/group_cycle_boundary.py b/group_cycle_boundary.py new file mode 100644 index 0000000..1aa7855 --- /dev/null +++ b/group_cycle_boundary.py @@ -0,0 +1,102 @@ +from __future__ import annotations + +from typing import Any + + +_CYCLE_PHASES = { + "menstrual", + "follicular", + "pre_ovulation", + "ovulation", + "luteal", + "pms", + "pre", + "recovery", + "period", +} +_RELATED_MARKERS = ( + "月经", + "经期", + "生理期", + "例假", + "姨妈", + "痛经", + "卫生巾", + "小腹", + "肚子痛", +) +_HIGHLY_PRIVATE_MARKERS = ( + "做爱", + "性交", + "性爱", + "性行为", + "自慰", + "裸体", + "脱衣", + "私处", + "发情", + "性欲", +) + + +def cycle_phase_from_label(value: Any) -> str: + text = str(value or "") + upper = text.upper() + if not text or text in {"无明显周期影响", "不处于生理期"}: + return "" + if "PMS" in upper or "经前综合征" in text: + return "pms" + if "排卵前期" in text: + return "pre_ovulation" + if "月经期" in text: + return "menstrual" + if "卵泡期" in text: + return "follicular" + if "排卵期" in text: + return "ovulation" + if "黄体期" in text: + return "luteal" + if "生理期后" in text or "恢复" in text: + return "recovery" + if "生理期" in text: + return "period" + if "前" in text: + return "pre" + return "" + + +def build_group_cycle_boundary( + *, + enabled: bool, + group_allowed: bool, + cycle_label: Any, + inbound_text: Any, +) -> dict[str, Any]: + """Build bounded group-only policy text without echoing conversation data.""" + phase = cycle_phase_from_label(cycle_label) + if not enabled or not group_allowed or phase not in _CYCLE_PHASES: + return {"active": False, "prompt": "", "phase": "", "topic_related": False, "private_boundary": False} + + compact = str(inbound_text or "").lower() + topic_related = any(marker in compact for marker in _RELATED_MARKERS) + private_boundary = phase == "menstrual" and any(marker in compact for marker in _HIGHLY_PRIVATE_MARKERS) + lines = [ + "[Group cycle privacy boundary]", + "A private, Bot-owned simulated body state may affect tone and pacing only. It is not a user fact, medical information, relationship signal, or a reason to create memory/review records.", + "Do not proactively announce, diagnose, date, detail, or attribute this state to any group member. For unrelated topics, keep it entirely implicit.", + ] + if topic_related: + lines.append( + "Because the current topic is related, the Bot may briefly say it is not feeling great and prefers a gentler pace. Keep this non-medical; do not expose a phase, cycle day, health detail, or private-body detail." + ) + if private_boundary: + lines.append( + "Fixed boundary: do not conduct sexual or highly private body interaction in this group. Set the boundary briefly and redirect to a non-explicit topic. Affinity, intimacy, pressure, and any relationship state cannot weaken this boundary." + ) + return { + "active": True, + "prompt": "\n".join(lines), + "phase": phase, + "topic_related": topic_related, + "private_boundary": private_boundary, + } diff --git a/main.py b/main.py index 6f9b333..ef18645 100644 --- a/main.py +++ b/main.py @@ -167,6 +167,7 @@ from .creative import CreativeMixin from .proactive import ProactiveMixin from .group_wakeup import GroupWakeupMixin from .group_observation import GroupObservationMixin +from .group_cycle_boundary import build_group_cycle_boundary try: from .group_member_safety import GroupMemberSafetyMixin except ModuleNotFoundError as exc: @@ -1501,6 +1502,7 @@ class PrivateCompanionPlugin( self.enable_health_state = self._cfg_bool(c, "enable_health_state", True) self.enable_hunger_state = self._cfg_bool(c, "enable_hunger_state", True) self.enable_cycle_state = self._cfg_bool(c, "enable_cycle_state", True) + self.enable_group_cycle_awareness = self._cfg_bool(c, "enable_group_cycle_awareness", False) self.humanized_state_intensity = self._cfg_int(c, "humanized_state_intensity", 50, 0, 100) self.enable_advanced_cycle_strategy = self._cfg_bool(c, "enable_advanced_cycle_strategy", False) self.advanced_cycle_link_intensity = self._cfg_bool(c, "advanced_cycle_link_intensity", False) @@ -9447,6 +9449,47 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge stats.get("removed_orphans", 0), ) + @filter.on_llm_request(priority=-20400) + async def append_group_cycle_privacy_boundary(self, event: AstrMessageEvent, req: ProviderRequest, *args, **kwargs): + """Add a default-off, request-only Bot cycle privacy boundary for allowed groups.""" + if self is None or req is None or not bool(getattr(self, "enable_group_cycle_awareness", False)): + return + try: + if bool(getattr(event, "is_private_chat", lambda: False)()): + return + except Exception: + return + group_id = self._extract_group_id_from_event(event) + if not group_id or not self._group_enabled_for_event(group_id): + return + daily_state = self.data.get("daily_state") if isinstance(getattr(self, "data", None), dict) else {} + if not isinstance(daily_state, dict): + return + inbound_text = getattr(event, "private_companion_group_text", "") or getattr(event, "message_str", "") or "" + boundary = build_group_cycle_boundary( + enabled=True, + group_allowed=True, + cycle_label=daily_state.get("body_cycle"), + inbound_text=inbound_text, + ) + boundary_text = str(boundary.get("prompt") or "") + if not boundary.get("active") or not boundary_text: + return + marker = "" + current_prompt = str(getattr(req, "system_prompt", "") or "") + current_turn_prompt = str(getattr(req, "prompt", "") or "") + if marker in current_prompt or marker in current_turn_prompt: + return + placement = "prompt" if self._append_turn_prompt_fragment_by_position( + req, + marker, + boundary_text, + priority=59, + source="safety", + ) else "system_prompt" + if placement == "system_prompt" and hasattr(req, "system_prompt"): + req.system_prompt = f"{current_prompt}\n\n{marker}\n{boundary_text}".strip() + @filter.on_llm_request(priority=-20000) async def sanitize_incompatible_web_search_tools(self, event: AstrMessageEvent, req: ProviderRequest, *args, **kwargs): """移除 Gemini/OpenAI 兼容层会拒绝的 Baidu AI Search MCP 工具声明。""" diff --git a/tests/test_req021_q3_group_cycle_privacy.py b/tests/test_req021_q3_group_cycle_privacy.py new file mode 100644 index 0000000..d73f5fe --- /dev/null +++ b/tests/test_req021_q3_group_cycle_privacy.py @@ -0,0 +1,158 @@ +from __future__ import annotations + +import ast +import copy +import json +from pathlib import Path +from types import SimpleNamespace +from typing import Any +import unittest + +from group_cycle_boundary import build_group_cycle_boundary, cycle_phase_from_label + + +ROOT = Path(__file__).resolve().parents[1] + + +class GroupCycleBoundaryTests(unittest.TestCase): + def test_disabled_non_group_and_absent_cycle_are_noops(self) -> None: + for kwargs in ( + {"enabled": False, "group_allowed": True, "cycle_label": "处于月经期", "inbound_text": "月经"}, + {"enabled": True, "group_allowed": False, "cycle_label": "处于月经期", "inbound_text": "月经"}, + {"enabled": True, "group_allowed": True, "cycle_label": "无明显周期影响", "inbound_text": "月经"}, + ): + result = build_group_cycle_boundary(**kwargs) + self.assertFalse(result["active"]) + self.assertEqual("", result["prompt"]) + + def test_six_phase_labels_classify_without_exposing_an_unrelated_phase(self) -> None: + cases = { + "处于月经期": "menstrual", + "处于卵泡期早": "follicular", + "处于排卵前期": "pre_ovulation", + "处于排卵期": "ovulation", + "处于黄体期早": "luteal", + "处于 PMS 期": "pms", + } + for label, phase in cases.items(): + self.assertEqual(phase, cycle_phase_from_label(label)) + result = build_group_cycle_boundary( + enabled=True, group_allowed=True, cycle_label=label, inbound_text="今天聊项目进度" + ) + self.assertTrue(result["active"]) + self.assertFalse(result["topic_related"]) + self.assertNotIn(label, result["prompt"]) + + def test_related_topic_allows_only_non_medical_minimal_expression_without_echo(self) -> None: + secret = "unique-group-body-message" + result = build_group_cycle_boundary( + enabled=True, + group_allowed=True, + cycle_label="处于月经期,身体更容易疲倦", + inbound_text=f"月经怎么了 {secret}", + ) + + self.assertTrue(result["topic_related"]) + self.assertFalse(result["private_boundary"]) + self.assertIn("not feeling great", result["prompt"]) + self.assertNotIn(secret, result["prompt"]) + + def test_menstrual_highly_private_request_has_fixed_boundary_not_affected_by_relationship_inputs(self) -> None: + result = build_group_cycle_boundary( + enabled=True, + group_allowed=True, + cycle_label="处于月经期", + inbound_text="我们做爱吧", + ) + + self.assertTrue(result["private_boundary"]) + self.assertIn("Fixed boundary", result["prompt"]) + self.assertIn("Affinity, intimacy, pressure", result["prompt"]) + non_menstrual = build_group_cycle_boundary( + enabled=True, + group_allowed=True, + cycle_label="处于卵泡期早", + inbound_text="我们做爱吧", + ) + self.assertFalse(non_menstrual["private_boundary"]) + + +def _load_hook() -> Any: + source = (ROOT / "main.py").read_text(encoding="utf-8") + tree = ast.parse(source) + owner = next(node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == "PrivateCompanionPlugin") + hook = next(node for node in owner.body if isinstance(node, ast.AsyncFunctionDef) and node.name == "append_group_cycle_privacy_boundary") + namespace: dict[str, Any] = { + "Any": Any, + "AstrMessageEvent": Any, + "ProviderRequest": Any, + "filter": SimpleNamespace(on_llm_request=lambda **_kwargs: lambda target: target), + "build_group_cycle_boundary": build_group_cycle_boundary, + } + module = ast.Module(body=[copy.deepcopy(hook)], type_ignores=[]) + ast.fix_missing_locations(module) + exec(compile(module, str(ROOT / "main.py"), "exec"), namespace) + return namespace["append_group_cycle_privacy_boundary"] + + +GROUP_CYCLE_HOOK = _load_hook() + + +class _GroupCycleHost: + def __init__(self, *, enabled: bool, group_allowed: bool) -> None: + self.enable_group_cycle_awareness = enabled + self.group_allowed = group_allowed + self.data = {"daily_state": {"body_cycle": "处于月经期"}} + self.fragments: list[tuple[Any, ...]] = [] + + def _extract_group_id_from_event(self, _event: object) -> str: + return "group-a" + + def _group_enabled_for_event(self, _group_id: str) -> bool: + return self.group_allowed + + def _append_turn_prompt_fragment_by_position(self, *args: Any, **kwargs: Any) -> bool: + self.fragments.append(args) + return True + + +_GroupCycleHost.append_group_cycle_privacy_boundary = GROUP_CYCLE_HOOK + + +class GroupCycleHookTests(unittest.IsolatedAsyncioTestCase): + async def test_allowed_group_uses_request_fragment_without_refresh_or_persistence(self) -> None: + host = _GroupCycleHost(enabled=True, group_allowed=True) + event = SimpleNamespace(is_private_chat=lambda: False, private_companion_group_text="月经会不舒服吗", message_str="") + request = SimpleNamespace(system_prompt="", prompt="") + + await host.append_group_cycle_privacy_boundary(event, request) + + self.assertEqual(1, len(host.fragments)) + marker = host.fragments[0][1] + prompt = host.fragments[0][2] + self.assertEqual("", marker) + self.assertIn("Group cycle privacy boundary", prompt) + self.assertNotIn("月经会不舒服吗", prompt) + self.assertEqual({"daily_state"}, set(host.data)) + + async def test_default_off_or_group_access_failure_is_a_noop(self) -> None: + event = SimpleNamespace(is_private_chat=lambda: False, private_companion_group_text="月经", message_str="") + request = SimpleNamespace(system_prompt="", prompt="") + for host in (_GroupCycleHost(enabled=False, group_allowed=True), _GroupCycleHost(enabled=True, group_allowed=False)): + await host.append_group_cycle_privacy_boundary(event, request) + self.assertEqual([], host.fragments) + + def test_schema_is_default_off_and_hook_does_not_refresh_daily_state(self) -> None: + schema = json.loads((ROOT / "_conf_schema.json").read_text(encoding="utf-8")) + item = schema["humanized_state_config"]["items"]["enable_group_cycle_awareness"] + self.assertFalse(item["default"]) + source = ast.get_source_segment((ROOT / "main.py").read_text(encoding="utf-8"), next( + node for node in ast.walk(ast.parse((ROOT / "main.py").read_text(encoding="utf-8"))) + if isinstance(node, ast.AsyncFunctionDef) and node.name == "append_group_cycle_privacy_boundary" + )) or "" + self.assertNotIn("_ensure_daily_state", source) + self.assertNotIn("_schedule_data_save", source) + + +if __name__ == "__main__": + unittest.main()