Workspace
diff --git a/core/bridge.py b/core/bridge.py index 3470fc8..f2189a7 100644 --- a/core/bridge.py +++ b/core/bridge.py @@ -480,6 +480,86 @@ class MemoryCompanionBridge: "items": safe_items, } + async def read_user_memory_summary( + self, + user_id: str, + *, + session_id: str = "", + limit: int = 6, + ) -> dict[str, Any]: + """Read a strict, exact-user Memory summary without exposing memory text.""" + + identity = clean_text(user_id, 120) + safe_session = clean_text(session_id, 200) + base = { + "contract": "memory.user_memory_summary.v1", + "ok": False, + "read_only": True, + "state": "degraded", + "degraded": True, + "pending": True, + "user_id": identity, + "session_id": safe_session, + "counts": {"profile": 0, "preference": 0, "relationship": 0, "private_conversation": 0, "other": 0, "total": 0}, + "summaries": [], + "workspace": {"kind": "memory_user_workspace", "route_hint": "user_memory", "user_id": identity}, + } + if not identity: + return {**base, "error_code": "missing_user_id"} + try: + getter = getattr(self._plugin, "read_user_memory_summary", None) + except Exception: + getter = None + if not callable(getter): + return {**base, "error_code": "bridge_method_unavailable"} + try: + result = await getter(identity, session_id=safe_session, limit=limit) + except Exception: + return {**base, "error_code": "bridge_exception"} + if not isinstance(result, dict) or result.get("contract") != base["contract"]: + return {**base, "error_code": "invalid_bridge_response"} + + counts = dict(base["counts"]) + raw_counts = result.get("counts") if isinstance(result.get("counts"), dict) else {} + for key in counts: + try: + counts[key] = max(0, int(raw_counts.get(key, 0))) + except (TypeError, ValueError, OverflowError): + counts[key] = 0 + summaries: list[dict[str, Any]] = [] + for item in result.get("summaries", []) if isinstance(result.get("summaries"), list) else []: + if not isinstance(item, dict): + continue + category = clean_text(item.get("category"), 40) + if category not in {"profile", "preference", "relationship", "private_conversation", "other"}: + continue + summaries.append( + { + "category": category, + "memory_type": clean_text(item.get("memory_type"), 80), + "occurred_at": clean_text(item.get("occurred_at"), 80), + "summary": clean_text(item.get("summary"), 100), + "content_redacted": True, + "truncated": True, + } + ) + if len(summaries) >= 8: + break + state = clean_text(result.get("state"), 40) + return { + **base, + "ok": bool(result.get("ok")) and state == "ready", + "state": "ready" if state == "ready" else "degraded", + "degraded": state != "ready" or bool(result.get("degraded", False)), + "pending": state != "ready" or bool(result.get("pending", False)), + "user_id": identity, + "session_id": safe_session, + "counts": counts, + "summaries": summaries, + "workspace": base["workspace"], + **({"error_code": clean_text(result.get("error_code"), 80)} if state != "ready" and clean_text(result.get("error_code"), 80) else {}), + } + async def search_bot_personal_profile(self, query: str = "", *, limit: int = 10) -> dict[str, Any]: return await self.read_bot_personal_profile(query=query, limit=limit) diff --git a/core/service.py b/core/service.py index b92fc29..b46dfcb 100644 --- a/core/service.py +++ b/core/service.py @@ -70,6 +70,14 @@ from .visibility import VisibilityPolicy LOCAL_TZ = ZoneInfo("Asia/Shanghai") +USER_MEMORY_SUMMARY_VERSION = "memory.user_memory_summary.v1" +_USER_MEMORY_PROFILE_TYPES = frozenset({"user_profile", "user_habit", "manual_memory"}) +_USER_MEMORY_PREFERENCE_TYPES = frozenset({"user_preference"}) +_USER_MEMORY_RELATIONSHIP_TYPES = frozenset({"relationship_claim", "relationship_phase_summary"}) +_USER_MEMORY_CONVERSATION_TYPES = frozenset( + {"conversation_event", "conversation_summary", "important_event", "memory_decay_summary", "self_action"} +) + _RECENT_FACT_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = ( ("meal", re.compile(r"吃过|吃完|吃了|没吃|还没吃|正在吃|吃饭|早饭|早餐|午饭|午餐|晚饭|晚餐|夜宵")), @@ -1054,6 +1062,127 @@ class MemoryCompanionService: }) return {"ok": True, "read_only": True, "state": "ready", "degraded": False, "pending": False, "items": items[:max(1, min(100, int(limit or 10)))]} + async def read_user_memory_summary( + self, + user_id: str, + *, + session_id: str = "", + limit: int = 6, + ) -> dict[str, Any]: + """Return a bounded, content-free Memory workspace projection for one user. + + Companion remains the authority for relationship and interaction state. + This method only reports exact-user Memory categories and opaque, redacted + anchors that can be used to open the Memory workspace. + """ + + identity = clean_text(user_id, 120) + requested_session = clean_text(session_id, 200) + base = self._user_memory_summary_base(identity, requested_session) + if not identity: + return {**base, "error_code": "missing_user_id"} + if requested_session and session_target_id(requested_session, "private") != identity: + return {**base, "error_code": "session_identity_mismatch"} + try: + bridge_enabled = self.config.bridge_enabled() + except Exception: + return {**base, "error_code": "bridge_config_unavailable"} + if bridge_enabled is not True: + return {**base, "error_code": "bridge_disabled"} + store = getattr(self, "store", None) + reader = getattr(store, "read_user_memory_summary_records", None) + if not callable(reader): + return {**base, "error_code": "store_unavailable"} + try: + safe_limit = max(1, min(8, int(limit or 6))) + except (TypeError, ValueError, OverflowError): + safe_limit = 6 + try: + raw = await reader(identity, session_id=requested_session, limit=safe_limit) + except Exception: + return {**base, "error_code": "store_query_failed"} + if not isinstance(raw, dict): + return {**base, "error_code": "invalid_store_response"} + + type_counts = raw.get("type_counts") if isinstance(raw.get("type_counts"), dict) else {} + counts = {"profile": 0, "preference": 0, "relationship": 0, "private_conversation": 0, "other": 0, "total": 0} + for memory_type, value in type_counts.items(): + try: + count = max(0, int(value)) + except (TypeError, ValueError, OverflowError): + continue + counts[self._user_memory_category(memory_type)] += count + counts["total"] += count + + summaries: list[dict[str, Any]] = [] + records = raw.get("records") if isinstance(raw.get("records"), list) else [] + for record in records[:safe_limit]: + if not isinstance(record, MemoryRecord): + continue + memory_type = clean_text(record.memory_type, 80) + category = self._user_memory_category(memory_type) + summaries.append( + { + "category": category, + "memory_type": memory_type, + "occurred_at": clean_text(record.occurred_at or record.created_at, 80), + "summary": f"{self._user_memory_category_label(category)}(内容已脱敏)", + "content_redacted": True, + "truncated": True, + } + ) + return { + **base, + "ok": True, + "state": "ready", + "degraded": False, + "pending": False, + "counts": counts, + "summaries": summaries, + } + + @staticmethod + def _user_memory_summary_base(user_id: str, session_id: str) -> dict[str, Any]: + return { + "contract": USER_MEMORY_SUMMARY_VERSION, + "ok": False, + "read_only": True, + "state": "degraded", + "degraded": True, + "pending": True, + "user_id": user_id, + "session_id": session_id, + "counts": {"profile": 0, "preference": 0, "relationship": 0, "private_conversation": 0, "other": 0, "total": 0}, + "summaries": [], + "workspace": { + "kind": "memory_user_workspace", + "route_hint": "user_memory", + "user_id": user_id, + }, + } + + @staticmethod + def _user_memory_category(memory_type: Any) -> str: + normalized = clean_text(memory_type, 80).lower() + if normalized in _USER_MEMORY_PROFILE_TYPES: + return "profile" + if normalized in _USER_MEMORY_PREFERENCE_TYPES: + return "preference" + if normalized in _USER_MEMORY_RELATIONSHIP_TYPES: + return "relationship" + if normalized in _USER_MEMORY_CONVERSATION_TYPES: + return "private_conversation" + return "other" + + @staticmethod + def _user_memory_category_label(category: str) -> str: + return { + "profile": "用户画像记忆", + "preference": "用户偏好记忆", + "relationship": "关系线索记忆", + "private_conversation": "私聊连续性记忆", + }.get(category, "其他用户记忆") + async def read_bot_profile( self, profile: str, diff --git a/core/store.py b/core/store.py index 9440b27..47911f3 100644 --- a/core/store.py +++ b/core/store.py @@ -3768,6 +3768,110 @@ class MemoryStore: ).fetchall() return [MemoryRecord.from_row(row) for row in rows] + async def read_user_memory_summary_records( + self, + user_id: str, + *, + session_id: str = "", + limit: int = 8, + ) -> dict[str, Any]: + """Read a bounded, exact-identity private-memory set for a bridge DTO. + + This is deliberately not a general search: it accepts no display name, + has no cross-window expansion, and never reads group rows. A supplied + session must itself resolve to the same private user identity. + """ + + return await self._run_recoverable_database_operation( + self._read_user_memory_summary_records_sync, + user_id, + session_id, + limit, + ) + + def _read_user_memory_summary_records_sync( + self, + user_id: str, + session_id: str, + limit: int, + ) -> dict[str, Any]: + identity = clean_text(user_id, 120) + requested_session = clean_text(session_id, 200) + empty = {"records": [], "total": 0, "type_counts": {}} + if not identity: + return empty + if requested_session: + scope, target_id = parse_scope_from_session(requested_session) + if scope != "private" or clean_text(target_id, 120) != identity: + return empty + + try: + safe_limit = max(1, min(12, int(limit or 8))) + except (TypeError, ValueError, OverflowError): + safe_limit = 8 + session_filters = [ + "%:friendmessage:" + self._escape_like_suffix(identity), + "%:privatemessage:" + self._escape_like_suffix(identity), + "%:friend:" + self._escape_like_suffix(identity), + "%:private:" + self._escape_like_suffix(identity), + ] + identity_clause = " OR ".join( + ["subject_id=?", "object_id=?", *("LOWER(session_id) LIKE ? ESCAPE '\\'" for _ in session_filters)] + ) + params: list[Any] = [identity, identity, *session_filters] + session_clause = "" + if requested_session: + session_clause = " AND session_id=?" + params.append(requested_session) + where = ( + "scope='private' AND review_status!='pending' " + "AND visibility IN ('private_pair', 'shareable') " + f"AND ({identity_clause}){session_clause}" + ) + with self._lock: + rows = self._conn.execute( + f""" + SELECT * FROM memories + WHERE {where} + ORDER BY occurred_at DESC, created_at DESC + LIMIT ? + """, + [*params, safe_limit], + ).fetchall() + total_row = self._conn.execute( + f"SELECT COUNT(*) AS count FROM memories WHERE {where}", + params, + ).fetchone() + type_rows = self._conn.execute( + f"SELECT memory_type, COUNT(*) AS count FROM memories WHERE {where} GROUP BY memory_type", + params, + ).fetchall() + + records: list[MemoryRecord] = [] + for row in rows: + record = MemoryRecord.from_row(row) + parsed_scope, parsed_target = parse_scope_from_session(clean_text(record.session_id, 200)) + direct_identity = identity in {clean_text(record.subject.id, 120), clean_text(record.object.id, 120)} + session_identity = parsed_scope == "private" and clean_text(parsed_target, 120) == identity + if requested_session and record.session_id != requested_session: + continue + if direct_identity or session_identity: + records.append(record) + type_counts = { + clean_text(row["memory_type"], 80): max(0, int(row["count"] or 0)) + for row in type_rows + if clean_text(row["memory_type"], 80) + } + return { + "records": records, + "total": max(0, int(total_row["count"] or 0)) if total_row else 0, + "type_counts": type_counts, + } + + @staticmethod + def _escape_like_suffix(value: str) -> str: + return clean_text(value, 120).lower().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + async def list_memory_buckets( self, limit: int = 160, diff --git a/page_api.py b/page_api.py index 24e5ffe..d1da978 100644 --- a/page_api.py +++ b/page_api.py @@ -93,6 +93,7 @@ class PluginPageApi: ("/conversation-import/resume", self.conversation_import_resume, ["POST"], "MemoryCompanion historical chat resume"), ("/conversation-import/rollback", self.conversation_import_rollback, ["POST"], "MemoryCompanion historical chat rollback"), ("/profiles", self.profiles, ["GET"], "MemoryCompanion Bot Profiles"), + ("/user-memory-summary", self.user_memory_summary, ["GET"], "MemoryCompanion User Memory workspace summary"), ("/capabilities/bot-personal", self.bot_personal_capabilities, ["GET"], "MemoryCompanion Bot Personal capability"), ("/companion/personal-memory", self.companion_personal_memory, ["GET"], "MemoryCompanion Page companion personal memory"), ("/companion/personal-photo", self.companion_personal_photo, ["GET"], "MemoryCompanion Page companion personal photo"), @@ -135,6 +136,49 @@ class PluginPageApi: ) return self._ok({"result": result}) + async def user_memory_summary(self): + user_id = clean_text(request.args.get("user_id", ""), 120) + session_id = clean_text(request.args.get("session_id", ""), 200) + try: + limit = max(1, min(8, int(request.args.get("limit", "6")))) + except (TypeError, ValueError): + limit = 6 + reader = getattr(getattr(self.plugin, "service", None), "read_user_memory_summary", None) + if not callable(reader): + result = { + "contract": "memory.user_memory_summary.v1", + "ok": False, + "read_only": True, + "state": "degraded", + "degraded": True, + "pending": True, + "user_id": user_id, + "session_id": session_id, + "counts": {"profile": 0, "preference": 0, "relationship": 0, "private_conversation": 0, "other": 0, "total": 0}, + "summaries": [], + "workspace": {"kind": "memory_user_workspace", "route_hint": "user_memory", "user_id": user_id}, + "error_code": "bridge_method_unavailable", + } + else: + try: + result = await reader(user_id, session_id=session_id, limit=limit) + except Exception: + result = { + "contract": "memory.user_memory_summary.v1", + "ok": False, + "read_only": True, + "state": "degraded", + "degraded": True, + "pending": True, + "user_id": user_id, + "session_id": session_id, + "counts": {"profile": 0, "preference": 0, "relationship": 0, "private_conversation": 0, "other": 0, "total": 0}, + "summaries": [], + "workspace": {"kind": "memory_user_workspace", "route_hint": "user_memory", "user_id": user_id}, + "error_code": "summary_unavailable", + } + return self._ok({"result": result}) + async def bot_personal_capabilities(self): getter = getattr(self.plugin, "bot_personal_capability_status", None) result = getter() if callable(getter) else { diff --git a/pages/记忆面板/app.css b/pages/记忆面板/app.css index d239a1c..448d8a4 100644 --- a/pages/记忆面板/app.css +++ b/pages/记忆面板/app.css @@ -1493,6 +1493,33 @@ pre{white-space:pre-wrap;overflow-wrap:anywhere} align-items:center; gap:8px; } + +.user-memory-filter{ + display:flex; + flex-wrap:wrap; + gap:8px; + margin:0 0 14px; + padding:8px; + border:1px solid var(--line); + border-radius:14px; + background:color-mix(in srgb,var(--panel) 88%,transparent); +} +.user-memory-filter button{ + min-height:34px; + padding:7px 13px; + border:1px solid transparent; + border-radius:999px; + background:transparent; + color:var(--muted); + cursor:pointer; +} +.user-memory-filter button:hover, +.user-memory-filter button.is-active{ + border-color:color-mix(in srgb,var(--accent) 42%,var(--line)); + background:color-mix(in srgb,var(--accent) 13%,var(--panel)); + color:var(--text); +} +.compatibility-note{color:var(--muted);font-size:13px} .scoped-clear-actions{ max-width:520px; } diff --git a/pages/记忆面板/app.js b/pages/记忆面板/app.js index 632c4e8..d8cef87 100644 --- a/pages/记忆面板/app.js +++ b/pages/记忆面板/app.js @@ -6,7 +6,7 @@ const VIEWS = { objects: { title: "知识图谱", hint: "查看关系边、跨窗口线程、时间线、记忆节点和互动协同概览。" }, film: { title: "群聊记忆", hint: "查看群聊范围内可召回、可管理的结构化记忆。" }, microscope: { title: "记忆显微镜", hint: "对比全库管理检索与指定会话中的实际召回和过滤。" }, - relations: { title: "用户记忆", hint: "聚焦用户画像、偏好、称呼和关系声明。" }, + relations: { title: "用户档案与记忆", hint: "按用户统一查看私聊、画像、偏好、称呼和关系记忆。" }, review: { title: "个人记忆", hint: "查看 Bot 自身的每日生活日程、相册、主观记忆和细化片段。" }, archive: { title: "维护 / 迁移 / 配置", hint: "执行维护、迁移、清理和导入修复。" }, maintain: { title: "私聊记忆", hint: "查看私聊范围内的对话、偏好、事实和稳定记忆。" }, @@ -43,13 +43,6 @@ const SECONDARY_NAV = { { id: "hits", label: "命中记忆", sublabel: "查看检索结果", badge: "命中" }, { id: "blocked", label: "过滤原因", sublabel: "查看被挡下的记忆", badge: "过滤" }, ], - relations: [ - { id: "all", label: "全部用户记忆", sublabel: "画像、偏好与关系", badge: "全部" }, - { id: "profile", label: "用户画像", sublabel: "稳定画像片段", badge: "画像" }, - { id: "preference", label: "偏好", sublabel: "喜好、习惯、倾向", badge: "偏好" }, - { id: "relationship", label: "关系声明", sublabel: "身份和关系线索", badge: "关系" }, - { id: "explicit", label: "明确记住", sublabel: "用户主动要求记住", badge: "记住" }, - ], archive: [ { id: "maintenance", label: "维护 / 迁移 / 清理", sublabel: "维护、修复、导入与清理", badge: "维护" }, { id: "conversation-import", label: "历史聊天导入", sublabel: "QQ 直读、文件与最近任务", badge: "导入" }, @@ -166,6 +159,7 @@ const state = { overviewLayout: document.documentElement.dataset.overviewLayout === "cinema" ? "cinema" : "standard", activeView: "objects", activeBucketId: "all", + userMemoryFilter: "all", microscopeBucketId: "all", microscopeSearchToken: 0, bucketLoadToken: 0, @@ -1223,18 +1217,21 @@ function bindBucketListInteractions() { function currentRailScope() { if (state.activeView === "film") return "group"; + if (state.activeView === "relations") return "private"; if (state.activeView === "maintain") return "private"; return ""; } function scopedViewScope(view = state.activeView) { if (view === "film") return "group"; + if (view === "relations") return "private"; if (view === "maintain") return "private"; return ""; } function scopedViewTarget(view = state.activeView) { if (view === "film") return "#groupMemoryList"; + if (view === "relations") return "#relationList"; if (view === "maintain") return "#privateMemoryList"; return ""; } @@ -1242,15 +1239,15 @@ function scopedViewTarget(view = state.activeView) { function renderScopedModeControls(view = state.activeView) { const scope = scopedViewScope(view); if (!scope) return; - const title = view === "film" ? $("#groupMemoryTitle") : $("#privateMemoryTitle"); - const hint = view === "film" ? $("#groupMemoryHint") : $("#privateMemoryHint"); - if (title) title.textContent = `${windowKindLabel(scope)}记忆`; + const title = view === "film" ? $("#groupMemoryTitle") : view === "relations" ? $("#userMemoryTitle") : $("#privateMemoryTitle"); + const hint = view === "film" ? $("#groupMemoryHint") : view === "relations" ? $("#userMemoryHint") : $("#privateMemoryHint"); + if (title) title.textContent = view === "relations" ? "用户档案与记忆" : `${windowKindLabel(scope)}记忆`; if (hint) hint.textContent = VIEWS[view]?.hint || ""; updateScopedClearButton(view); } function updateScopedClearButton(view = state.activeView) { - const button = view === "film" ? $("#clearCurrentGroupMemoryBtn") : view === "maintain" ? $("#clearCurrentPrivateMemoryBtn") : null; + const button = view === "film" ? $("#clearCurrentGroupMemoryBtn") : ["relations", "maintain"].includes(view) ? $("#clearCurrentPrivateMemoryBtn") : null; const bucket = activeBucket(); const scope = scopedViewScope(view); const canClear = Boolean(bucket && bucket.id !== "all" && bucket.scope === scope && bucket.target_id); @@ -1736,6 +1733,11 @@ async function playRailRefreshTransition(task) { } async function openView(view, { preserveBucket = false } = {}) { + if (view === "maintain") { + view = "relations"; + state.userMemoryFilter = "private"; + preserveBucket = true; + } const app = $("#app"); const wasWorkspace = app.classList.contains("is-workspace"); const switchingWorkspaceView = wasWorkspace && state.activeView !== view; @@ -1775,7 +1777,7 @@ async function openView(view, { preserveBucket = false } = {}) { renderScopedModeControls(view); if (view === "film") { renderScopedBucketRail("group"); - } else if (view === "maintain") { + } else if (view === "relations" || view === "maintain") { renderScopedBucketRail("private"); } else if (view !== "review") { renderSecondaryNav(view, !switchingWorkspaceView); @@ -2007,14 +2009,30 @@ function renderMemoryList(selector, memories, emptyText) { } function relationTypesForSecondary() { - const active = activeSecondaryNav("relations"); + const active = state.userMemoryFilter || "all"; const map = { profile: ["user_profile"], preference: ["user_preference"], relationship: ["relationship_claim"], explicit: ["explicit_memory"], }; - return map[active] || ["user_profile", "user_preference", "explicit_memory", "relationship_claim"]; + return map[active] || []; +} + +function syncUserMemoryFilterControls() { + $$('[data-user-memory-filter]').forEach((button) => { + if (!button.closest('#view-relations')) return; + const active = button.dataset.userMemoryFilter === state.userMemoryFilter; + button.classList.toggle('is-active', active); + button.setAttribute('aria-selected', active ? 'true' : 'false'); + }); +} + +async function selectUserMemoryFilter(filter) { + const allowed = new Set(['all', 'profile', 'preference', 'relationship', 'explicit', 'private']); + state.userMemoryFilter = allowed.has(filter) ? filter : 'all'; + syncUserMemoryFilterControls(); + if (state.activeView === 'relations') await loadUserMemory(); } async function loadScopedMemories(selector, scope, loadingText, emptyText, extra = {}) { @@ -2432,10 +2450,25 @@ function renderContextLogs(logs) { async function loadUserMemory() { const target = $("#relationList"); if (!target) return; - target.innerHTML = loadingState("正在读取用户记忆..."); + syncUserMemoryFilterControls(); + target.innerHTML = loadingState("正在读取用户档案与记忆..."); const types = relationTypesForSecondary(); - const memories = (await loadMemories({ limit: 160 })).filter((memory) => hasMemoryType(memory, types)); - renderMemoryList("#relationList", memories, "当前范围还没有用户画像、偏好或关系声明。"); + const { params, incompatible } = scopedMemoryParams("private", { limit: 180 }); + if (incompatible) { + target.innerHTML = '
Workspace