diff --git a/core/coordination_status.py b/core/coordination_status.py new file mode 100644 index 0000000..3184936 --- /dev/null +++ b/core/coordination_status.py @@ -0,0 +1,204 @@ +"""Allowlist-only status for the Memory operations page. + +The page is an observation surface, not a capability channel. In particular, +it must never return memory text, identity values, session identifiers, audit +records, provider details, or opaque cross-plugin handles. +""" +from __future__ import annotations + +import hashlib +import json +from typing import Any + +from .p5c_guard import P5C_SINK_FLAGS +from .p5d_security_events import P5D_OPERATION_FLAGS +from .p6_four_package_manifest import FOUR_PACKAGE_IDS, manifest_contract +from .p6_readonly_projection import ( + P6_READONLY_STATUS_FINGERPRINT, + P6_READONLY_STATUS_SCHEMA, +) + + +COORDINATION_STATUS_SCHEMA = "ops.memory.coordination_status.v1" +_HEALTH = frozenset({"ready", "degraded", "unverifiable"}) +_P5_B_FLAGS = ( + "enable_p5_b1_recall_gate", + "enable_p5_b1_bridge_gate", + "enable_p5_b1_tool_recall_gate", + "enable_p5_b2_archive_read_gate", + "enable_p5_b2_cross_user_read_gate", +) +_P6_FIELDS = ("profiles", "identity_links", "audit_events", "operations") +_P6_REASON_CODES = frozenset({"", "registry_status_unavailable", "invalid_reason_code"}) + + +def _fingerprint() -> str: + payload = { + "schema_version": COORDINATION_STATUS_SCHEMA, + "sections": ("page_api", "runtime", "bridge", "p5", "p6", "four_package"), + } + encoded = json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(",", ":")).encode("utf-8") + return hashlib.sha256(encoded).hexdigest() + + +COORDINATION_STATUS_FINGERPRINT = _fingerprint() + + +def _status(health: str, reason_code: str) -> dict[str, str]: + return { + "health": health if health in _HEALTH else "unverifiable", + "reason_code": reason_code, + } + + +def _config_group( + config: Any, + flags: tuple[str, ...], + *, + fallback_flags: tuple[str, ...] = (), +) -> dict[str, Any]: + """Read only documented switches; an unavailable source is not assumed off.""" + + getter = getattr(config, "bool", None) + if not callable(getter): + return {"health": "unverifiable", "mode": "unverifiable", "enabled_count": 0, "total_count": len(flags), "reason_code": "config_unavailable"} + values: list[bool] = [] + for index, flag in enumerate(flags): + try: + value = getter(flag, False) + if type(value) is not bool: + return {"health": "unverifiable", "mode": "unverifiable", "enabled_count": 0, "total_count": len(flags), "reason_code": "config_value_invalid"} + if value is False and fallback_flags: + value = getter(fallback_flags[index], False) + except Exception: + return {"health": "unverifiable", "mode": "unverifiable", "enabled_count": 0, "total_count": len(flags), "reason_code": "config_unreadable"} + if type(value) is not bool: + return {"health": "unverifiable", "mode": "unverifiable", "enabled_count": 0, "total_count": len(flags), "reason_code": "config_value_invalid"} + values.append(value) + enabled_count = sum(values) + if enabled_count == 0: + return {"health": "ready", "mode": "default_off", "enabled_count": 0, "total_count": len(flags), "reason_code": "default_off"} + if enabled_count == len(flags): + return {"health": "ready", "mode": "enabled", "enabled_count": enabled_count, "total_count": len(flags), "reason_code": "configured"} + return {"health": "degraded", "mode": "partial", "enabled_count": enabled_count, "total_count": len(flags), "reason_code": "partial_coverage"} + + +def build_p5_status(config: Any) -> dict[str, dict[str, Any]]: + """Return aggregate P5 modes only; no individual switch values leave the service.""" + + return { + "attestation_read": _config_group(config, _P5_B_FLAGS), + "sink_boundary": _config_group( + config, + tuple(f"p5c_safety.{flag}" for flag in P5C_SINK_FLAGS.values()), + fallback_flags=tuple(P5C_SINK_FLAGS.values()), + ), + "security_recovery": _config_group( + config, + tuple(f"p5d_safety.{flag}" for flag in P5D_OPERATION_FLAGS.values()), + fallback_flags=tuple(P5D_OPERATION_FLAGS.values()), + ), + } + + +def project_runtime_health(runtime: Any) -> dict[str, str]: + """Reduce runtime compatibility to a static status without host detail text.""" + + try: + if type(runtime) is dict: + level = runtime.get("compatibility_level") + else: + level = getattr(runtime, "compatibility_level", None) + except Exception: + return _status("unverifiable", "runtime_status_unavailable") + if level == "full": + return _status("ready", "runtime_compatible") + if level == "degraded": + return _status("degraded", "runtime_degraded") + return _status("unverifiable", "runtime_unsupported") + + +def project_p6_status(raw: Any) -> dict[str, Any]: + """Validate a Companion P6 status before copying its fixed fields. + + P6 is intentionally accepted only in its exact current contract shape. A + malformed, extended, or unavailable producer is represented as zeroed + counts and ``unverifiable`` rather than reflected into the operations page. + """ + + fallback = { + "schema_version": P6_READONLY_STATUS_SCHEMA, + "contract_fingerprint": P6_READONLY_STATUS_FINGERPRINT, + "health": "unverifiable", + "reason_code": "p6_status_unavailable", + "counts": {field: 0 for field in _P6_FIELDS}, + } + if type(raw) is not dict: + return fallback + if set(raw) != {"schema_version", "source_plugin", "contract_fingerprint", "health", "reason_code", "counts"}: + return fallback + if raw.get("schema_version") != P6_READONLY_STATUS_SCHEMA: + return fallback + if raw.get("source_plugin") != "private_companion": + return fallback + if raw.get("contract_fingerprint") != P6_READONLY_STATUS_FINGERPRINT: + return fallback + health = raw.get("health") + reason_code = raw.get("reason_code") + counts = raw.get("counts") + if health not in _HEALTH or reason_code not in _P6_REASON_CODES or type(counts) is not dict: + return fallback + if set(counts) != set(_P6_FIELDS): + return fallback + if any(type(counts[field]) is not int or not 0 <= counts[field] <= 10_000_000 for field in _P6_FIELDS): + return fallback + return { + "schema_version": P6_READONLY_STATUS_SCHEMA, + "contract_fingerprint": P6_READONLY_STATUS_FINGERPRINT, + "health": health, + "reason_code": reason_code, + "counts": {field: counts[field] for field in _P6_FIELDS}, + } + + +def build_coordination_status(*, config: Any, runtime: Any, bridge: dict[str, str], p6_raw: Any) -> dict[str, Any]: + """Create the complete versioned operations-page projection.""" + + p5 = build_p5_status(config) + p6 = project_p6_status(p6_raw) + manifest = manifest_contract() + components = [project_runtime_health(runtime), bridge, {"health": p6["health"], "reason_code": p6["reason_code"]}] + if any(component.get("health") == "unverifiable" for component in components): + health, reason_code = "unverifiable", "coordination_input_unverifiable" + elif any(component.get("health") == "degraded" for component in components): + health, reason_code = "degraded", "coordination_degraded" + else: + health, reason_code = "ready", "coordination_ready" + return { + "schema_version": COORDINATION_STATUS_SCHEMA, + "contract_fingerprint": COORDINATION_STATUS_FINGERPRINT, + "health": health, + "reason_code": reason_code, + "page_api": _status("ready", "page_api_registered"), + "runtime": project_runtime_health(runtime), + "bridge": _status(bridge.get("health", "unverifiable"), bridge.get("reason_code", "bridge_status_unavailable")), + "p5": p5, + "p6": p6, + "four_package": { + "schema_version": manifest["schema"], + "contract_fingerprint": manifest["contract_fingerprint"], + "health": "unverifiable", + "reason_code": "manifest_registry_unavailable", + "expected_package_count": len(FOUR_PACKAGE_IDS), + }, + } + + +__all__ = [ + "COORDINATION_STATUS_FINGERPRINT", + "COORDINATION_STATUS_SCHEMA", + "build_coordination_status", + "build_p5_status", + "project_p6_status", + "project_runtime_health", +] diff --git a/metadata.yaml b/metadata.yaml index d5a8c8f..9f39084 100644 --- a/metadata.yaml +++ b/metadata.yaml @@ -1,5 +1,5 @@ name: astrbot_plugin_memory_companion_ops -display_name: 我会牢牢记住你・运维记忆 +display_name: 雪色的我会永远记住你-运维版 author: menglimi author_url: https://github.com/menglimi version: 1.6.2-ops.2 diff --git a/page_api.py b/page_api.py index 505d7ec..adea16b 100644 --- a/page_api.py +++ b/page_api.py @@ -29,6 +29,7 @@ try: PORTABLE_EXPORT_SINK, p5c_gate_reason, ) + from .core.coordination_status import build_coordination_status, project_p6_status from .core.user_memory_boundary import USER_MEMORY_DOMAIN except ImportError: from core.bot_profiles import describe_bot_profiles @@ -42,6 +43,7 @@ except ImportError: PORTABLE_EXPORT_SINK, p5c_gate_reason, ) + from core.coordination_status import build_coordination_status, project_p6_status from core.user_memory_boundary import USER_MEMORY_DOMAIN try: @@ -116,6 +118,7 @@ class PluginPageApi: ("/config/module/update", self.config_module_update, ["POST"], "MemoryCompanion Page config module update"), ("/retrieval/config/update", self.retrieval_config_update, ["POST"], "MemoryCompanion Page retrieval config update"), ("/operations/diagnostics", self.operations_diagnostics, ["GET"], "MemoryCompanion operations diagnostics"), + ("/coordination/status", self.coordination_status, ["GET"], "MemoryCompanion safe coordination status"), ("/operations/preset", self.operations_preset, ["GET", "POST"], "MemoryCompanion operations preset"), ("/data/export", self.data_export, ["POST"], "MemoryCompanion portable data export"), ("/data/import/preview", self.data_import_preview, ["GET"], "MemoryCompanion portable data preview"), @@ -157,6 +160,62 @@ class PluginPageApi: except Exception as exc: return self._err(f"运维诊断失败: {exc}", 500) + async def coordination_status(self): + """Expose one strictly read-only, allowlist-only coordination projection.""" + + try: + service = getattr(self.plugin, "service", None) + p6_raw, bridge = self._companion_p6_status(service) + status = build_coordination_status( + config=getattr(service, "config", None), + runtime=getattr(self.plugin, "runtime_capabilities", None), + bridge=bridge, + p6_raw=p6_raw, + ) + except Exception: + # Do not turn a status failure into a broad diagnostic or echo an + # exception: a status page is never an information-recovery path. + status = build_coordination_status( + config=None, + runtime=None, + bridge={"health": "unverifiable", "reason_code": "bridge_status_unavailable"}, + p6_raw=None, + ) + return self._ok({"status": status}) + + def _companion_p6_status(self, service: Any) -> tuple[Any, dict[str, str]]: + """Read the Companion's P6 aggregate status without reflecting its objects.""" + + config = getattr(service, "config", None) + getter = getattr(config, "bool", None) + if not callable(getter): + return None, {"health": "unverifiable", "reason_code": "bridge_config_unavailable"} + try: + bridge_enabled = getter("private_companion_bridge.enabled", True) + except Exception: + return None, {"health": "unverifiable", "reason_code": "bridge_config_unreadable"} + if type(bridge_enabled) is not bool: + return None, {"health": "unverifiable", "reason_code": "bridge_config_invalid"} + if bridge_enabled is False: + return None, {"health": "degraded", "reason_code": "bridge_disabled"} + + companion = self._private_companion_status() + if type(companion) is not dict or companion.get("available") is not True: + return None, {"health": "unverifiable", "reason_code": "companion_api_unavailable"} + plugin = companion.get("plugin") + extension_api = getattr(plugin, "extension_api", None) + status_getter = getattr(extension_api, "get_p6_readonly_status", None) + if not callable(status_getter): + return None, {"health": "unverifiable", "reason_code": "companion_p6_producer_unavailable"} + try: + p6_raw = status_getter() + except Exception: + return None, {"health": "unverifiable", "reason_code": "companion_p6_producer_unreadable"} + p6 = project_p6_status(p6_raw) + if p6["health"] == "ready": + return p6_raw, {"health": "ready", "reason_code": "companion_bridge_available"} + return p6_raw, {"health": "degraded", "reason_code": "companion_p6_unverifiable"} + async def operations_preset(self): if request.method == "GET": return self._ok({"preset": self.plugin.service.operation_preset_status()}) diff --git a/pages/记忆面板/app.css b/pages/记忆面板/app.css index 97cb747..c491aa7 100644 --- a/pages/记忆面板/app.css +++ b/pages/记忆面板/app.css @@ -3320,6 +3320,46 @@ pre{white-space:pre-wrap;overflow-wrap:anywhere} color:var(--accent-strong); font-size:14px; } +.coordination-status-card{ + display:grid; + gap:10px; + border:1px solid rgba(var(--edge-rgb),.20); + border-radius:var(--radius); + background:linear-gradient(135deg,rgba(var(--light-rgb),.88),rgba(var(--edge-rgb),.055)); + padding:13px; +} +.coordination-status-head{display:flex;align-items:flex-start;justify-content:space-between;gap:12px} +.coordination-status-head>span{display:grid;gap:4px;min-width:0} +.coordination-status-head b{color:var(--accent-strong);font-size:15px} +.coordination-status-head small{color:var(--muted);font-size:12px;line-height:1.5} +.coordination-status-head button{flex:0 0 auto} +.coordination-status-grid{display:grid;gap:10px} +.coordination-status-summary{ + display:flex;align-items:center;flex-wrap:wrap;gap:7px; + border-left:3px solid var(--line-soft);border-radius:7px; + background:rgba(var(--light-rgb),.62);padding:9px 10px; +} +.coordination-status-summary.is-teal{border-left-color:var(--teal)} +.coordination-status-summary.is-gold{border-left-color:var(--gold)} +.coordination-status-summary.is-red{border-left-color:var(--red)} +.coordination-status-summary b{color:var(--ink);font-size:13px} +.coordination-status-summary small{margin-left:auto;color:var(--muted);font-size:11px} +.coordination-status-items{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px} +.coordination-status-item{ + display:grid;gap:5px;min-width:0; + border:1px solid rgba(var(--edge-rgb),.14);border-radius:8px; + background:rgba(var(--light-rgb),.68);padding:9px; +} +.coordination-status-item>div{display:flex;align-items:center;justify-content:space-between;gap:8px} +.coordination-status-item b{color:var(--ink);font-size:12px} +.coordination-status-item strong{color:var(--accent-strong);font-size:12px;font-weight:700;line-height:1.42;overflow-wrap:anywhere} +.coordination-status-item small{color:var(--muted);font-size:10px;line-height:1.38;overflow-wrap:anywhere} +@media(max-width:640px){ + .coordination-status-head{display:grid} + .coordination-status-head button{justify-self:start} + .coordination-status-summary small{width:100%;margin-left:0} + .coordination-status-items{grid-template-columns:1fr} +} .visually-hidden{ position:absolute!important; width:1px!important; diff --git a/pages/记忆面板/app.js b/pages/记忆面板/app.js index b8bfa37..d6b8c77 100644 --- a/pages/记忆面板/app.js +++ b/pages/记忆面板/app.js @@ -9,7 +9,7 @@ const VIEWS = { relations: { title: "用户记忆", hint: "聚焦用户画像、偏好、称呼和关系声明。" }, review: { title: "个人记忆", hint: "查看 Bot 自身的每日生活日程、相册、主观记忆和细化片段。" }, archive: { title: "维护 / 迁移 / 配置", hint: "执行维护、迁移、清理和导入修复。" }, - maintain: { title: "私聊记忆", hint: "查看私聊范围内的对话、偏好、事实和稳定记忆。" }, + maintain: { title: "用户记忆", hint: "查看用户范围内的对话、偏好、事实和稳定记忆。" }, }; const PERSONAL_MEMORY_VIEW = { @@ -593,7 +593,7 @@ function isWindowBucket(bucket) { } function windowKindLabel(scope) { - return scope === "group" ? "群聊" : "私聊"; + return scope === "group" ? "群聊" : "用户"; } function bucketByWindow(scope, id) { @@ -634,7 +634,7 @@ function splitWindowBucketTitle(bucket = {}) { : rawLabel; const explicitName = cleanWindowDisplayName(bucket.target_name || bucket.display_name || ""); const inferredName = cleanWindowDisplayName(nameFromLabel || ""); - const genericNames = new Set(["群聊", "私聊", "用户", "好友", "旧 Live2D 会话", "旧私聊会话", "内部会话", "私聊会话"]); + const genericNames = new Set(["群聊", "私聊", "用户", "好友", "旧 Live2D 会话", "旧私聊会话", "旧用户会话", "内部会话", "私聊会话", "用户会话"]); const name = explicitName || (genericNames.has(inferredName) ? "" : inferredName); if (scope === "group") { return { @@ -937,7 +937,7 @@ function memoryStatsItems(stats) { value: formatFileSize(storageBytes), title: `数据库 ${formatFileSize(databaseBytes)} · WAL ${formatFileSize(walBytes)} · SHM ${formatFileSize(shmBytes)}`, }, - { key: "private-memory", label: "私聊记忆", value: stats.by_scope?.private ?? 0 }, + { key: "private-memory", label: "用户记忆", value: stats.by_scope?.private ?? 0 }, { key: "group-memory", label: "群聊记忆", value: stats.by_scope?.group ?? 0 }, ]; } @@ -1009,13 +1009,13 @@ function renderStandardRecentBuckets() { const windows = state.buckets.filter(isWindowBucket); const privateCount = windows.filter((bucket) => bucket.scope === "private").length; const groupCount = windows.filter((bucket) => bucket.scope === "group").length; - if (meta) meta.textContent = `${privateCount} 个私聊 · ${groupCount} 个群聊`; + if (meta) meta.textContent = `${privateCount} 位用户 · ${groupCount} 个群聊`; const recent = [...windows] .sort((left, right) => String(right.latest_at || "").localeCompare(String(left.latest_at || ""))) .slice(0, 5); if (!recent.length) { - host.innerHTML = '
还没有私聊或群聊记忆
'; + host.innerHTML = '还没有用户或群聊记忆
'; return; } host.innerHTML = recent.map((bucket) => { @@ -1058,7 +1058,7 @@ function scopedRailConfig(scope) { if (scope === "group") { return { title: "群聊列表", clear: "全部群聊", label: "全部群聊", sublabel: "不限定群聊", badge: "群聊" }; } - return { title: "私聊用户", clear: "全部私聊", label: "全部私聊", sublabel: "不限定用户", badge: "私聊" }; + return { title: "用户", clear: "全部用户", label: "全部用户", sublabel: "不限定用户", badge: "用户" }; } function bindBucketListInteractions() { @@ -1110,7 +1110,7 @@ function updateScopedClearButton(view = state.activeView) { const canClear = Boolean(bucket && bucket.id !== "all" && bucket.scope === scope && bucket.target_id); if (button) { button.disabled = !canClear; - button.title = canClear ? `清空 ${bucket.label} 的记忆` : `请先选择具体${scope === "group" ? "群聊" : "私聊用户"}`; + button.title = canClear ? `清空 ${bucket.label} 的记忆` : `请先选择具体${scope === "group" ? "群聊" : "用户"}`; } if (view === "film") { const memberInput = $("#clearGroupMemberUserId"); @@ -1680,7 +1680,7 @@ async function loadActiveView() { } else if (state.activeView === "review") { await loadPersonalMemory(); } else if (state.activeView === "maintain") { - await loadScopedMemories("#privateMemoryList", "private", "正在读取私聊记忆...", "还没有私聊范围内的记忆。"); + await loadScopedMemories("#privateMemoryList", "private", "正在读取用户记忆...", "还没有用户范围内的记忆。"); } else if (state.activeView === "archive") { await loadArchive(); } @@ -1863,7 +1863,7 @@ async function loadScopedMemories(selector, scope, loadingText, emptyText, extra target.innerHTML = loadingState(loadingText); const { params, incompatible } = scopedMemoryParams(scope, { limit: 120, ...extra }); if (incompatible) { - const label = scope === "group" ? "群聊" : "私聊"; + const label = scope === "group" ? "群聊" : "用户"; target.innerHTML = `正在读取安全与协同状态...
'; + try { + const data = await apiGet("/coordination/status"); + renderCoordinationStatus(data.status); + } catch (_) { + renderCoordinationStatus({ + health: "unverifiable", + reason_code: "coordination_input_unverifiable", + page_api: { health: "unverifiable", reason_code: "coordination_input_unverifiable" }, + runtime: { health: "unverifiable", reason_code: "runtime_unsupported" }, + bridge: { health: "unverifiable", reason_code: "companion_api_unavailable" }, + p5: {}, + p6: { health: "unverifiable", reason_code: "p6_status_unavailable", counts: {} }, + four_package: { health: "unverifiable", reason_code: "manifest_registry_unavailable", expected_package_count: 4 }, + }); + } +} + async function applyOperationPreset(preset) { const labels = { light: "轻量", standard: "标准", companion: "陪伴" }; const label = labels[preset] || preset; @@ -5585,7 +5698,7 @@ async function executeScopedClearMemory(payload) { async function clearCurrentScopedMemory(scope) { const payload = scopedClearPayload(scope); if (!payload) { - const message = scope === "group_member" ? "请先选择具体群聊并填写群成员 QQ" : `请先选择具体${scope === "group" ? "群聊" : "私聊用户"}`; + const message = scope === "group_member" ? "请先选择具体群聊并填写群成员 QQ" : `请先选择具体${scope === "group" ? "群聊" : "用户"}`; showToast(message, "error"); return; } @@ -5694,6 +5807,7 @@ function bindActions() { $("#runSearchBtn").addEventListener("click", (event) => withButton(event.currentTarget, "检索中", runSearch)); $("#maintenanceBtn").addEventListener("click", () => withBusy("正在运行维护...", runMaintenance)); $("#operationsDiagnosticsBtn").addEventListener("click", () => withBusy("正在生成运维诊断...", runOperationsDiagnostics)); + $("#coordinationStatusRefreshBtn").addEventListener("click", () => withBusy("正在刷新安全与协同状态...", loadCoordinationStatus)); $$('[data-operation-preset]').forEach((button) => { button.addEventListener("click", () => withBusy("正在应用运行预设...", () => applyOperationPreset(button.dataset.operationPreset))); }); @@ -6176,7 +6290,7 @@ function renderAclTopology(data) { // Column headers nodesHtml += `