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 = `
当前观察对象不属于${escapeHtml(label)}范围。请选择${escapeHtml(label)}对象或切回全部。
`; return; } @@ -4515,6 +4515,119 @@ async function runOperationsDiagnostics() { showToast("运维诊断已生成"); } +function coordinationHealthMeta(value) { + const map = { + ready: { label: "正常", tone: "teal" }, + degraded: { label: "需关注", tone: "gold" }, + unverifiable: { label: "不可验证", tone: "red" }, + }; + return map[value] || map.unverifiable; +} + +function coordinationReasonLabel(code) { + const labels = { + coordination_ready: "协同输入已通过只读检查", + coordination_degraded: "存在降级组件,请查看各项状态", + coordination_input_unverifiable: "有组件无法安全确认,已按不可验证处理", + runtime_compatible: "AstrBot 运行时兼容", + runtime_degraded: "运行时能力部分降级", + runtime_unsupported: "运行时能力无法确认", + bridge_disabled: "陪伴桥接已关闭", + companion_bridge_available: "陪伴插件只读状态可用", + companion_api_unavailable: "未检测到可用的陪伴插件状态接口", + companion_p6_producer_unavailable: "陪伴插件未提供 P6 状态生产者", + companion_p6_producer_unreadable: "陪伴插件 P6 状态暂不可读取", + companion_p6_unverifiable: "陪伴插件 P6 状态未通过协议校验", + bridge_config_unavailable: "桥接配置不可读取", + bridge_config_unreadable: "桥接配置读取失败", + bridge_config_invalid: "桥接配置格式无效", + p6_status_unavailable: "P6 状态生产者不可用或返回格式无效", + default_off: "默认关闭", + configured: "已配置", + partial_coverage: "部分覆盖", + config_unavailable: "配置不可读取", + config_unreadable: "配置读取失败", + config_value_invalid: "配置值无效", + manifest_registry_unavailable: "四包清单注册表尚未接入", + }; + return labels[code] || "状态原因未登记"; +} + +function coordinationModeLabel(mode) { + return { + default_off: "默认关闭", + enabled: "已配置", + partial: "部分覆盖", + unverifiable: "不可验证", + }[mode] || "不可验证"; +} + +function coordinationStatusCard(title, status = {}, detail = "") { + const meta = coordinationHealthMeta(status.health); + return ` +
+
${escapeHtml(title)}${escapeHtml(meta.label)}
+ ${escapeHtml(detail || coordinationReasonLabel(status.reason_code))} + ${escapeHtml(coordinationReasonLabel(status.reason_code))} +
+ `; +} + +function coordinationP5Card(title, group = {}) { + const detail = `${coordinationModeLabel(group.mode)} · ${number(group.enabled_count)}/${number(group.total_count)} 项`; + return coordinationStatusCard(title, group, detail); +} + +function renderCoordinationStatus(raw) { + const target = $("#coordinationStatus"); + if (!target) return; + const status = raw && typeof raw === "object" ? raw : {}; + const p5 = status.p5 && typeof status.p5 === "object" ? status.p5 : {}; + const p6 = status.p6 && typeof status.p6 === "object" ? status.p6 : {}; + const counts = p6.counts && typeof p6.counts === "object" ? p6.counts : {}; + const overall = coordinationHealthMeta(status.health); + const p6Detail = p6.health === "ready" + ? `画像 ${number(counts.profiles)} · 身份关联 ${number(counts.identity_links)} · 审计事件 ${number(counts.audit_events)} · 运行操作 ${number(counts.operations)}` + : "不读取跨插件明细,仅保留零值聚合"; + target.innerHTML = ` +
+ ${escapeHtml(overall.label)} + ${escapeHtml(coordinationReasonLabel(status.reason_code))} + 本卡片不提供启用、迁移、恢复或权限变更操作。 +
+
+ ${coordinationStatusCard("页面接口", status.page_api || {})} + ${coordinationStatusCard("AstrBot 运行时", status.runtime || {})} + ${coordinationStatusCard("陪伴桥接", status.bridge || {})} + ${coordinationP5Card("P5 回忆证明门禁", p5.attestation_read || {})} + ${coordinationP5Card("P5 输入/输出边界", p5.sink_boundary || {})} + ${coordinationP5Card("P5 安全事件恢复边界", p5.security_recovery || {})} + ${coordinationStatusCard("P6 跨插件状态", p6, p6Detail)} + ${coordinationStatusCard("四包协议清单", status.four_package || {}, `预期 ${number(status.four_package?.expected_package_count)} 个包 · ${coordinationReasonLabel(status.four_package?.reason_code)}`)} +
+ `; +} + +async function loadCoordinationStatus() { + const target = $("#coordinationStatus"); + if (target) 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 += ` 群聊 - 私聊`; + 用户`; // Nodes for (const n of nodes) { @@ -6340,6 +6454,7 @@ async function init() { bindActions(); playInitialOverviewEntrance(); await loadConfiguredTheme(); + await loadCoordinationStatus(); try { await loadCompanionAvailability(); await loadStats(); diff --git a/pages/记忆面板/index.html b/pages/记忆面板/index.html index 656e241..8120c86 100644 --- a/pages/记忆面板/index.html +++ b/pages/记忆面板/index.html @@ -54,7 +54,7 @@
记忆--
记忆大小--
-
私聊记忆--
+
用户记忆--
群聊记忆--
@@ -70,7 +70,7 @@
- +
@@ -250,8 +250,8 @@
-

私聊记忆

-

查看私聊范围内的对话、偏好、事实和稳定记忆。

+

用户记忆

+

查看用户范围内的对话、偏好、事实和稳定记忆。

@@ -272,6 +272,18 @@

维护 / 迁移 / 清理

推荐先选择运行预设并查看诊断,再执行迁移或维护。所有导入与清空操作都会先备份数据库。

+
+
+ + 安全与协同状态 + 只读汇总 P5 门禁、运行时兼容性、陪伴桥接与 P6 协议;不显示记忆正文、身份、会话或审计记录。 + + +
+
+

正在读取安全与协同状态...

+
+
1. 运行预设 diff --git a/plugin_identity.py b/plugin_identity.py index 4dd1e75..801c5eb 100644 --- a/plugin_identity.py +++ b/plugin_identity.py @@ -1,7 +1,7 @@ from __future__ import annotations PLUGIN_NAME = "astrbot_plugin_memory_companion_ops" -PLUGIN_DISPLAY_NAME = "我会牢牢记住你・运维记忆" +PLUGIN_DISPLAY_NAME = "雪色的我会永远记住你-运维版" PLUGIN_VERSION = "1.6.2-ops.2" PLUGIN_REPO = "https://forgejo.yokiirobw.top:55443/YokiiroBW/astrbot_plugin_memory_companion_ops" PRIVATE_COMPANION_PLUGIN_NAMES = ( diff --git a/tests/test_coordination_status.py b/tests/test_coordination_status.py new file mode 100644 index 0000000..4166438 --- /dev/null +++ b/tests/test_coordination_status.py @@ -0,0 +1,166 @@ +from __future__ import annotations + +import asyncio +import sys +import types +import unittest +from pathlib import Path +from types import SimpleNamespace + +from core.coordination_status import ( + COORDINATION_STATUS_SCHEMA, + build_coordination_status, + build_p5_status, + project_p6_status, +) +from core.p6_readonly_projection import ( + P6_READONLY_STATUS_FINGERPRINT, + P6_READONLY_STATUS_SCHEMA, +) + + +if "quart" not in sys.modules: + quart_stub = types.ModuleType("quart") + quart_stub.jsonify = lambda body: body + quart_stub.request = types.SimpleNamespace(args={}) + quart_stub.send_file = lambda *_args, **_kwargs: None + sys.modules["quart"] = quart_stub + +import page_api as page_api_module + + +class _Config: + def __init__(self, values: dict[str, bool] | None = None) -> None: + self.values = values or {} + + def bool(self, key: str, default: bool) -> bool: + return self.values.get(key, default) + + +def _p6_status(**extra: object) -> dict[str, object]: + result: dict[str, object] = { + "schema_version": P6_READONLY_STATUS_SCHEMA, + "source_plugin": "private_companion", + "contract_fingerprint": P6_READONLY_STATUS_FINGERPRINT, + "health": "ready", + "reason_code": "", + "counts": {"profiles": 3, "identity_links": 4, "audit_events": 5, "operations": 6}, + } + result.update(extra) + return result + + +class CoordinationStatusProjectionTests(unittest.TestCase): + def test_p5_is_aggregate_only_and_handles_nested_p5c_switches(self) -> None: + result = build_p5_status(_Config({ + "enable_p5_b1_recall_gate": True, + "p5c_safety.enable_p5c_file_ingest_gate": True, + "p5d_safety.enable_p5d_manual_recovery": True, + })) + self.assertEqual({"attestation_read", "sink_boundary", "security_recovery"}, set(result)) + self.assertEqual(1, result["attestation_read"]["enabled_count"]) + self.assertEqual(1, result["sink_boundary"]["enabled_count"]) + self.assertEqual(1, result["security_recovery"]["enabled_count"]) + self.assertNotIn("enable_p5_b1_recall_gate", repr(result)) + + def test_invalid_p6_producer_fails_closed_without_sensitive_reflection(self) -> None: + result = project_p6_status(_p6_status(memory_body="do-not-leak", identity_handle="do-not-leak")) + self.assertEqual("unverifiable", result["health"]) + self.assertEqual("p6_status_unavailable", result["reason_code"]) + self.assertEqual({"profiles": 0, "identity_links": 0, "audit_events": 0, "operations": 0}, result["counts"]) + self.assertNotIn("do-not-leak", repr(result)) + + def test_complete_projection_has_only_allowlisted_sections_and_degrades(self) -> None: + result = build_coordination_status( + config=None, + runtime=None, + bridge={"health": "unverifiable", "reason_code": "bridge_status_unavailable", "session_id": "do-not-leak"}, + p6_raw={"memory_body": "do-not-leak"}, + ) + self.assertEqual(COORDINATION_STATUS_SCHEMA, result["schema_version"]) + self.assertEqual( + {"schema_version", "contract_fingerprint", "health", "reason_code", "page_api", "runtime", "bridge", "p5", "p6", "four_package"}, + set(result), + ) + self.assertEqual("unverifiable", result["health"]) + self.assertEqual("unverifiable", result["p6"]["health"]) + self.assertNotIn("do-not-leak", repr(result)) + + +class CoordinationStatusApiTests(unittest.TestCase): + def setUp(self) -> None: + self.original_jsonify = page_api_module.jsonify + page_api_module.jsonify = lambda body: body + + def tearDown(self) -> None: + page_api_module.jsonify = self.original_jsonify + + def test_route_is_get_only_and_returns_aggregates(self) -> None: + registered: list[tuple[str, tuple[str, ...]]] = [] + extension_api = SimpleNamespace(get_p6_readonly_status=lambda: _p6_status()) + companion = SimpleNamespace(extension_api=extension_api) + service = SimpleNamespace(config=_Config({"private_companion_bridge.enabled": True})) + api = page_api_module.PluginPageApi(SimpleNamespace( + service=service, + runtime_capabilities=SimpleNamespace(compatibility_level="full"), + context=SimpleNamespace(register_web_api=lambda path, _handler, methods, _desc: registered.append((path, tuple(methods)))), + )) + api._private_companion_status = lambda: {"available": True, "plugin": companion} + response = asyncio.run(api.coordination_status()) + + self.assertEqual("ready", response["status"]["runtime"]["health"]) + self.assertEqual("ready", response["status"]["bridge"]["health"]) + self.assertEqual({"profiles": 3, "identity_links": 4, "audit_events": 5, "operations": 6}, response["status"]["p6"]["counts"]) + api.register_routes() + route_methods = dict(registered) + coordination_paths = [path for path in route_methods if path.endswith("/coordination/status")] + self.assertEqual(1, len(coordination_paths)) + self.assertEqual(("GET",), route_methods[coordination_paths[0]]) + + def test_missing_companion_producer_returns_safe_degraded_projection(self) -> None: + service = SimpleNamespace(config=_Config({"private_companion_bridge.enabled": True})) + api = page_api_module.PluginPageApi(SimpleNamespace(service=service, runtime_capabilities=None)) + api._private_companion_status = lambda: {"available": False, "plugin": "do-not-leak"} + response = asyncio.run(api.coordination_status()) + + status = response["status"] + self.assertEqual("unverifiable", status["bridge"]["health"]) + self.assertEqual("companion_api_unavailable", status["bridge"]["reason_code"]) + self.assertEqual("p6_status_unavailable", status["p6"]["reason_code"]) + self.assertNotIn("do-not-leak", repr(status)) + + +class CoordinationStatusFrontendTests(unittest.TestCase): + def test_panel_uses_get_only_readonly_status_card(self) -> None: + root = Path(__file__).resolve().parents[1] + page_path = next((root / "pages").glob("*/index.html")) + page = page_path.read_text(encoding="utf-8") + script = (page_path.parent / "app.js").read_text(encoding="utf-8") + styles = (page_path.parent / "app.css").read_text(encoding="utf-8") + + self.assertIn('id="coordinationStatus"', page) + self.assertIn('id="coordinationStatusRefreshBtn"', page) + start = script.index("async function loadCoordinationStatus") + end = script.index("async function applyOperationPreset", start) + status_block = script[start:end] + self.assertIn('apiGet("/coordination/status")', status_block) + self.assertNotIn("apiPost(", status_block) + self.assertIn("本卡片不提供启用、迁移、恢复或权限变更操作", script) + self.assertIn(".coordination-status-card", styles) + + + def test_primary_private_memory_scope_is_presented_as_users(self) -> None: + root = Path(__file__).resolve().parents[1] + page_path = next((root / "pages").glob("*/index.html")) + page = page_path.read_text(encoding="utf-8") + script = (page_path.parent / "app.js").read_text(encoding="utf-8") + + self.assertIn("用户记忆", page) + self.assertIn('data-tip-title="用户记忆"', page) + self.assertIn('maintain: { title: "用户记忆"', script) + self.assertIn('return scope === "group" ? "群聊" : "用户";', script) + self.assertIn("只读取该好友与你当前 Bot 的私聊历史。", page) + + +if __name__ == "__main__": + unittest.main()