feat(group): create observation-only member profiles

这个提交存在于:
YokiiroBW 2026-08-01 02:54:25 +08:00
父节点 3679b95fe8
当前提交 69800b8b03
共有 6 个文件被更改,包括 350 次插入 和 12 次删除

查看文件

@ -3672,6 +3672,33 @@ Bot 近期回复:
return session_id
return ""
def _sender_qq_nickname(self, event: AstrMessageEvent) -> str:
"""Read the account nickname without treating a group card as global identity."""
message_obj = getattr(event, "message_obj", None)
sender = getattr(message_obj, "sender", None) if message_obj is not None else None
raw_message = getattr(message_obj, "raw_message", None) if message_obj is not None else None
sources = [sender]
if isinstance(raw_message, dict):
sources.append(raw_message.get("sender"))
event_raw = getattr(event, "raw_message", None)
if isinstance(event_raw, dict):
sources.append(event_raw.get("sender"))
for source in sources:
if isinstance(source, dict):
value = source.get("nickname")
else:
value = getattr(source, "nickname", None) if source is not None else None
value = _single_line(value, 30)
if value:
return value
getter = getattr(event, "get_sender_nickname", None)
if callable(getter):
try:
return _single_line(getter(), 30)
except Exception:
pass
return ""
def _sender_display_name(self, event: AstrMessageEvent) -> str:
for name in ("get_sender_name", "get_sender_nickname"):
func = getattr(event, name, None)

查看文件

@ -662,6 +662,23 @@ class GroupObservationMixin:
group["last_group_name_seen_at"] = now
group["last_seen"] = now
group["message_count"] = _safe_int(group.get("message_count"), 0, 0) + 1
qq_nickname = ""
nickname_getter = getattr(self, "_sender_qq_nickname", None)
if callable(nickname_getter) and event is not None:
try:
qq_nickname = _single_line(nickname_getter(event), 40)
except Exception:
qq_nickname = ""
if self.enable_group_member_profiles:
profile_ensurer = getattr(self, "_ensure_worldbook_group_observation_profile", None)
if callable(profile_ensurer):
profile_ensurer(
group_id=str(group_id or group.get("group_id") or ""),
sender_id=sender_id,
qq_nickname=qq_nickname,
group_card=sender_name,
now=now,
)
recent = group.setdefault("recent_messages", [])
if not isinstance(recent, list):
@ -672,7 +689,7 @@ class GroupObservationMixin:
"sender_id": sender_id,
"name": _single_line(sender_name, 30) or sender_id,
"identity_name": self._group_member_identity_name(sender_id, sender_name, limit=30),
"identity_known": bool(self._worldbook_profile_by_user_id(sender_id)),
"identity_known": bool(self._worldbook_profile_by_user_id(sender_id, include_observation=True)),
"text": cleaned,
"message_id": _single_line(message_id, 120),
"injection_guard_blocked": blocked_by_guard,
@ -731,8 +748,9 @@ class GroupObservationMixin:
events.append({"ts": now, "old": previous_display_name, "new": display_name})
del events[:-12]
member["name"] = _single_line(sender_name, 30) or member.get("name") or sender_id
member["qq_nickname"] = qq_nickname or _single_line(member.get("qq_nickname"), 30)
member["identity_name"] = self._group_member_identity_name(sender_id, sender_name, limit=30)
member["identity_known"] = bool(self._worldbook_profile_by_user_id(sender_id))
member["identity_known"] = bool(self._worldbook_profile_by_user_id(sender_id, include_observation=True))
member.pop("identity_note", None)
member.pop("boundary_note", None)
member["count"] = _safe_int(member.get("count"), 0, 0) + 1
@ -1731,7 +1749,7 @@ class GroupObservationMixin:
add(member.get("display_name"))
add(member.get("nickname"))
add(member.get("card"))
profile = self._worldbook_profile_by_user_id(str(user_id))
profile = self._worldbook_profile_by_user_id(str(user_id), include_observation=True)
if isinstance(profile, dict):
add(profile.get("name"))
for key in ("aliases", "observed_names"):
@ -2093,7 +2111,7 @@ class GroupObservationMixin:
"sender_id": sender_id,
"name": _single_line(sender_name, 30) or sender_id,
"identity_name": self._group_member_identity_name(sender_id, sender_name, limit=30),
"identity_known": bool(self._worldbook_profile_by_user_id(sender_id)),
"identity_known": bool(self._worldbook_profile_by_user_id(sender_id, include_observation=True)),
"ts": now,
"text": _single_line(text, 80),
}

查看文件

@ -17336,6 +17336,16 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
"linked_qq_user_id": self._single_line(item.get("linked_qq_user_id") or item.get("merged_into_user_id"), 40),
"linked_bili_profile_id": self._single_line(item.get("linked_bili_profile_id"), 80),
"auto_registration_pending": bool(item.get("auto_registration_pending", False)),
"profile_origin": self._single_line(item.get("profile_origin"), 40),
"observation_only": bool(item.get("observation_only", False)),
"proactive_contact_enabled": bool(item.get("proactive_contact_enabled", False)),
"relationship_state": self._single_line(item.get("relationship_state"), 24) or "neutral",
"affinity_score": self._int(item.get("affinity_score")),
"observed_group_count": len(
item.get("group_observation_scope_ids")
if isinstance(item.get("group_observation_scope_ids"), list)
else []
),
"content": self._single_line(item.get("content"), 260),
"identity_note": self._single_line(item.get("identity_note") or item.get("note") or item.get("content"), 500),
"boundary_note": self._single_line(item.get("boundary_note"), 500),

查看文件

@ -14483,6 +14483,7 @@ function worldbookMemberCard(item) {
const detailId = `worldbook-editor-${String(item.user_id || "").replace(/[^A-Za-z0-9_-]/g, "_")}`;
const previewItems = worldbookMemberPreviewItems(item, memories);
const isExternal = item.identity_type === "external" || !/^\d+$/.test(String(item.user_id || ""));
const observationOnly = Boolean(item.observation_only);
const identityLabel = isExternal ? "外部身份" : "身份 QQ";
const genderText = String(item.gender || "").trim();
const bindLine = item.linked_qq_user_id
@ -14496,7 +14497,7 @@ function worldbookMemberCard(item) {
<span>${identityLabel} ${escapeHtml(item.user_id || "-")} · 优先级 ${escapeHtml(item.priority ?? "-")}${bindLine}</span>
</div>
<div class="worldbook-card-actions">
<button type="button" data-worldbook-living-memory="${escapeHtml(item.user_id || "")}">长期记忆</button>
${observationOnly ? "" : `<button type="button" data-worldbook-living-memory="${escapeHtml(item.user_id || "")}">长期记忆</button>`}
<button type="button" data-worldbook-edit="${escapeHtml(detailId)}">编辑</button>
<button type="button" data-worldbook-member="${escapeHtml(item.user_id || "")}" data-enabled="${item.enabled ? "0" : "1"}">
${escapeHtml(item.enabled ? "停用" : "启用")}
@ -14512,6 +14513,7 @@ function worldbookMemberCard(item) {
<span>${escapeHtml((item.important_memories || []).length)} 条记忆</span>
${pending.length ? `<span>${escapeHtml(pending.length)} 条待确认观察</span>` : ""}
${sourceEntries.length ? `<span>${escapeHtml(sourceEntries.slice(0, 2).join(" / "))}</span>` : ""}
${observationOnly ? `<span>仅观察 · ${escapeHtml(item.observed_group_count || 0)} 个白名单群</span><span>亲密度:中性</span><span>不主动触达</span>` : ""}
</div>
${previewItems.length ? `
<div class="worldbook-member-preview-list">

查看文件

@ -0,0 +1,147 @@
from __future__ import annotations
import ast
import copy
from pathlib import Path
import re
from types import SimpleNamespace
from typing import Any
import unittest
ROOT = Path(__file__).resolve().parents[1]
def _single_line(value: Any, limit: int = 1000) -> str:
return re.sub(r"\s+", " ", str(value or "")).strip()[:limit]
def _load_methods(filename: str, class_name: str, names: set[str]) -> dict[str, Any]:
source = (ROOT / filename).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 == class_name)
namespace: dict[str, Any] = {
"Any": Any,
"AstrMessageEvent": Any,
"re": re,
"_single_line": _single_line,
"_now_ts": lambda: 123.0,
}
for node in owner.body:
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in names:
module = ast.Module(body=[copy.deepcopy(node)], type_ignores=[])
ast.fix_missing_locations(module)
exec(compile(module, str(ROOT / filename), "exec"), namespace)
return {name: namespace[name] for name in names}
WORLD_BOOK_METHODS = _load_methods(
"worldbook.py",
"WorldbookMixin",
{
"_ensure_worldbook_group_observation_profile",
"_confirm_worldbook_observation_profile_name",
"_worldbook_profile_by_user_id",
},
)
EVENT_METHODS = _load_methods("event_dispatch.py", "EventDispatchMixin", {"_sender_qq_nickname"})
class _WorldbookHost:
enable_worldbook_member_recognition = True
def __init__(self) -> None:
self.data: dict[str, Any] = {}
for _name, _method in WORLD_BOOK_METHODS.items():
setattr(_WorldbookHost, _name, _method)
class GroupObservationProfileTests(unittest.TestCase):
def test_qq_nickname_precedes_group_card(self) -> None:
event = SimpleNamespace(
message_obj=SimpleNamespace(
sender=SimpleNamespace(nickname="QQ昵称", card="很抽象的群名片"),
raw_message={"sender": {"nickname": "另一个昵称", "card": "群名片"}},
),
raw_message={},
get_sender_nickname=lambda: "回退昵称",
)
self.assertEqual("QQ昵称", EVENT_METHODS["_sender_qq_nickname"](object(), event))
def test_observed_profile_is_neutral_and_not_a_private_or_proactive_target(self) -> None:
host = _WorldbookHost()
profile = host._ensure_worldbook_group_observation_profile(
group_id="group-a", sender_id="10001", qq_nickname="QQ昵称", group_card="群名片"
)
self.assertIsNotNone(profile)
self.assertEqual("QQ昵称", profile["name"])
self.assertEqual(["群名片"], profile["group_aliases"]["group-a"])
self.assertTrue(profile["observation_only"])
self.assertFalse(profile["proactive_contact_enabled"])
self.assertFalse(profile["private_memory_enabled"])
self.assertFalse(profile["cross_group_memory_enabled"])
self.assertFalse(profile["p4_eligible"])
self.assertEqual(0, profile["affinity_score"])
self.assertEqual("neutral", profile["relationship_state"])
self.assertNotIn("users", host.data)
self.assertIsNone(host._worldbook_profile_by_user_id("10001"))
self.assertEqual("QQ昵称", host._worldbook_profile_by_user_id("10001", include_observation=True)["name"])
def test_repeat_and_cross_group_observation_are_idempotent_and_group_scoped(self) -> None:
host = _WorldbookHost()
first = host._ensure_worldbook_group_observation_profile(
group_id="group-a", sender_id="10001", qq_nickname="QQ昵称", group_card="甲群名片"
)
again = host._ensure_worldbook_group_observation_profile(
group_id="group-a", sender_id="10001", qq_nickname="QQ昵称", group_card="甲群名片"
)
second_group = host._ensure_worldbook_group_observation_profile(
group_id="group-b", sender_id="10001", qq_nickname="QQ昵称", group_card="乙群名片"
)
self.assertIs(first, again)
self.assertIs(first, second_group)
self.assertEqual(["10001"], list(host.data["worldbook_member_profiles"]))
self.assertEqual(["甲群名片"], first["group_aliases"]["group-a"])
self.assertEqual(["乙群名片"], first["group_aliases"]["group-b"])
self.assertEqual({"group-a", "group-b"}, set(first["group_observation_scope_ids"]))
def test_explicit_name_confirmation_preserves_neutral_observation_boundaries(self) -> None:
host = _WorldbookHost()
profile = host._ensure_worldbook_group_observation_profile(
group_id="group-a", sender_id="10001", qq_nickname="QQ昵称", group_card="群名片"
)
before = {key: profile[key] for key in ("affinity_score", "relationship_state", "group_aliases")}
self.assertTrue(
host._confirm_worldbook_observation_profile_name(
profile, sender_id="10001", name="小雪", aliases=["雪雪", "QQ昵称"]
)
)
self.assertEqual("小雪", profile["name"])
self.assertIn("QQ昵称", profile["aliases"])
self.assertEqual(before["affinity_score"], profile["affinity_score"])
self.assertEqual(before["relationship_state"], profile["relationship_state"])
self.assertEqual(before["group_aliases"], profile["group_aliases"])
self.assertFalse(profile["proactive_contact_enabled"])
self.assertFalse(profile["p4_eligible"])
def test_group_path_and_panel_keep_observation_profiles_local_only(self) -> None:
group_source = (ROOT / "group_observation.py").read_text(encoding="utf-8")
worldbook_source = (ROOT / "worldbook.py").read_text(encoding="utf-8")
api_source = (ROOT / "page_api.py").read_text(encoding="utf-8")
panel_source = (ROOT / "pages" / "陪伴面板" / "app.js").read_text(encoding="utf-8")
self.assertIn("_ensure_worldbook_group_observation_profile", group_source)
self.assertIn("include_observation=True", group_source)
self.assertIn("profile.get(\"observation_only\")", worldbook_source)
self.assertIn('"proactive_contact_enabled": bool(item.get("proactive_contact_enabled", False))', api_source)
self.assertIn("仅观察", panel_source)
self.assertNotIn("self._get_user(sender_id)", group_source)
if __name__ == "__main__":
unittest.main()

查看文件

@ -449,6 +449,10 @@ class WorldbookMixin:
profile = profiles.get(user_id)
if not isinstance(profile, dict):
return
if bool(profile.get("observation_only")):
# Group cards belong to their group scope and must not become a
# global alias that can be injected into another conversation.
return
observed = profile.setdefault("observed_names", [])
if not isinstance(observed, list):
observed = []
@ -457,7 +461,128 @@ class WorldbookMixin:
observed.append(name)
del observed[:-8]
def _worldbook_profile_by_user_id(self, user_id: str) -> dict[str, Any] | None:
def _ensure_worldbook_group_observation_profile(
self,
*,
group_id: str,
sender_id: str,
qq_nickname: str = "",
group_card: str = "",
now: float | None = None,
) -> dict[str, Any] | None:
"""Create the non-authoritative role card for an observed group speaker.
This profile is intentionally excluded from normal worldbook lookup. It
exists for the relationship view and the current group observation only;
it cannot become a private target, a proactive recipient, or cross-group
memory merely because the sender spoke once in a whitelisted group.
"""
sender_id = _single_line(sender_id, 40)
group_id = _single_line(group_id, 80)
if not sender_id or not group_id:
return None
qq_nickname = _single_line(qq_nickname, 40)
group_card = _single_line(group_card, 40)
display_name = qq_nickname or group_card or sender_id
now = float(now or _now_ts())
profiles = self.data.setdefault("worldbook_member_profiles", {})
if not isinstance(profiles, dict):
profiles = {}
self.data["worldbook_member_profiles"] = profiles
profile = profiles.get(sender_id)
if not isinstance(profile, dict):
profile = {
"user_id": sender_id,
"name": display_name,
"gender": "",
"aliases": [],
"observed_names": [],
"content": "白名单群内实际发言自动建立的仅观察角色档案。",
"identity_note": f"QQ {sender_id},仅观察角色档案。",
"boundary_note": "仅用于当前群观察和关系展示;不用于私聊、主动触达、跨群记忆、P4 计分或黑屋。",
"important_memories": [],
"enabled": True,
"priority": 0,
"source_entries": ["白名单群观察"],
"profile_origin": "group_observation",
"observation_only": True,
"proactive_contact_enabled": False,
"private_memory_enabled": False,
"cross_group_memory_enabled": False,
"p4_eligible": False,
"affinity_score": 0,
"relationship_state": "neutral",
"auto_registered_ts": now,
}
profiles[sender_id] = profile
if not bool(profile.get("observation_only")):
# An explicit profile keeps its own identity and permissions. We
# only retain the group-scoped alias below.
return profile
profile["user_id"] = sender_id
profile["proactive_contact_enabled"] = False
profile["private_memory_enabled"] = False
profile["cross_group_memory_enabled"] = False
profile["p4_eligible"] = False
profile.setdefault("affinity_score", 0)
profile.setdefault("relationship_state", "neutral")
profile.setdefault("profile_origin", "group_observation")
profile.setdefault("source_entries", ["白名单群观察"])
profile.setdefault("observation_only", True)
aliases_by_group = profile.setdefault("group_aliases", {})
if not isinstance(aliases_by_group, dict):
aliases_by_group = {}
profile["group_aliases"] = aliases_by_group
aliases = aliases_by_group.setdefault(group_id, [])
if not isinstance(aliases, list):
aliases = []
aliases_by_group[group_id] = aliases
if group_card and group_card not in aliases and group_card != profile.get("name"):
aliases.append(group_card)
del aliases[:-8]
scopes = profile.setdefault("group_observation_scope_ids", [])
if not isinstance(scopes, list):
scopes = []
profile["group_observation_scope_ids"] = scopes
if group_id not in scopes:
scopes.append(group_id)
del scopes[:-32]
profile["last_observed_at"] = now
return profile
def _confirm_worldbook_observation_profile_name(
self,
profile: dict[str, Any],
*,
sender_id: str,
name: str,
aliases: list[str],
) -> bool:
"""Apply an explicit @Bot name confirmation without granting authority."""
if not isinstance(profile, dict) or not bool(profile.get("observation_only")):
return False
sender_id = _single_line(sender_id, 40)
name = _single_line(name, 40)
if not sender_id or not name:
return False
previous_name = _single_line(profile.get("name"), 40)
existing_aliases = profile.get("aliases") if isinstance(profile.get("aliases"), list) else []
merged_aliases = [
_single_line(item, 40)
for item in [*existing_aliases, previous_name, *aliases]
if _single_line(item, 40) and _single_line(item, 40) != name and _single_line(item, 40) != sender_id
]
profile["name"] = name
profile["aliases"] = list(dict.fromkeys(merged_aliases))[:8]
profile["name_source"] = "self_registration"
profile["name_confirmed_at"] = _now_ts()
profile["proactive_contact_enabled"] = False
profile["private_memory_enabled"] = False
profile["cross_group_memory_enabled"] = False
profile["p4_eligible"] = False
return True
def _worldbook_profile_by_user_id(self, user_id: str, *, include_observation: bool = False) -> dict[str, Any] | None:
if not self.enable_worldbook_member_recognition:
return None
user_id = str(user_id or "").strip()
@ -467,12 +592,12 @@ class WorldbookMixin:
if not isinstance(profiles, dict):
return None
profile = profiles.get(user_id)
if isinstance(profile, dict) and profile.get("enabled", True):
if isinstance(profile, dict) and profile.get("enabled", True) and (include_observation or not profile.get("observation_only")):
view = dict(profile)
view["user_id"] = _single_line(profile.get("linked_qq_user_id") or profile.get("user_id") or user_id, 40)
return view
for profile_key, item in profiles.items():
if not isinstance(item, dict) or not item.get("enabled", True):
if not isinstance(item, dict) or not item.get("enabled", True) or (item.get("observation_only") and not include_observation):
continue
linked_id = _single_line(item.get("linked_qq_user_id") or item.get("user_id") or profile_key, 40)
if linked_id == user_id:
@ -482,7 +607,7 @@ class WorldbookMixin:
return None
def _group_member_identity_name(self, user_id: str, fallback: str = "", *, limit: int = 30) -> str:
profile = self._worldbook_profile_by_user_id(user_id)
profile = self._worldbook_profile_by_user_id(user_id, include_observation=True)
if isinstance(profile, dict):
name = _single_line(profile.get("name"), limit)
if name and name != str(user_id or ""):
@ -522,7 +647,7 @@ class WorldbookMixin:
return ";".join(lines)
def _group_member_identity_note(self, user_id: str, *, limit: int = 120) -> str:
profile = self._worldbook_profile_by_user_id(user_id)
profile = self._worldbook_profile_by_user_id(user_id, include_observation=True)
if not isinstance(profile, dict):
return ""
gender = _single_line(profile.get("gender"), 40)
@ -555,7 +680,7 @@ class WorldbookMixin:
return []
matches: list[dict[str, Any]] = []
for user_id, profile in profiles.items():
if not isinstance(profile, dict) or not profile.get("enabled", True):
if not isinstance(profile, dict) or not profile.get("enabled", True) or profile.get("observation_only"):
continue
profile_uid = _single_line(profile.get("linked_qq_user_id") or profile.get("user_id") or user_id, 40)
if str(user_id) == query or profile_uid == query or self._worldbook_member_matches_name(profile, query):
@ -926,7 +1051,8 @@ class WorldbookMixin:
payload["confirm_reply"] = f"好,那我记住你是{name}。"
return payload
existing_profiles = self.data.get("worldbook_member_profiles")
if isinstance(existing_profiles, dict) and isinstance(existing_profiles.get(sender_id), dict):
existing_profile = existing_profiles.get(sender_id) if isinstance(existing_profiles, dict) else None
if isinstance(existing_profile, dict) and not bool(existing_profile.get("observation_only")):
return None
if not self._group_message_explicitly_ats_bot(event):
return None
@ -966,6 +1092,14 @@ class WorldbookMixin:
conflict,
)
return {"blocked_reply": self._worldbook_self_registration_block_reply_text()}
if isinstance(existing_profile, dict):
if self._confirm_worldbook_observation_profile_name(
existing_profile,
sender_id=sender_id,
name=name,
aliases=aliases,
):
return {"confirm_reply": f"好,以后我叫你{name}。", "updated_observation_profile": True}
profiles = self.data.setdefault("worldbook_member_profiles", {})
if not isinstance(profiles, dict):
profiles = {}