feat(ops-ui): expose safe memory coordination status

这个提交存在于:
YokiiroBW 2026-07-30 21:48:46 +08:00
父节点 60a49976d1
当前提交 fc55d73fca
共有 8 个文件被更改,包括 615 次插入 和 19 次删除

204
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",
]

查看文件

@ -1,5 +1,5 @@
name: astrbot_plugin_memory_companion_ops name: astrbot_plugin_memory_companion_ops
display_name: 我会牢牢记住你・运维记忆 display_name: 雪色的我会永远记住你-运维版
author: menglimi author: menglimi
author_url: https://github.com/menglimi author_url: https://github.com/menglimi
version: 1.6.2-ops.2 version: 1.6.2-ops.2

查看文件

@ -29,6 +29,7 @@ try:
PORTABLE_EXPORT_SINK, PORTABLE_EXPORT_SINK,
p5c_gate_reason, p5c_gate_reason,
) )
from .core.coordination_status import build_coordination_status, project_p6_status
from .core.user_memory_boundary import USER_MEMORY_DOMAIN from .core.user_memory_boundary import USER_MEMORY_DOMAIN
except ImportError: except ImportError:
from core.bot_profiles import describe_bot_profiles from core.bot_profiles import describe_bot_profiles
@ -42,6 +43,7 @@ except ImportError:
PORTABLE_EXPORT_SINK, PORTABLE_EXPORT_SINK,
p5c_gate_reason, p5c_gate_reason,
) )
from core.coordination_status import build_coordination_status, project_p6_status
from core.user_memory_boundary import USER_MEMORY_DOMAIN from core.user_memory_boundary import USER_MEMORY_DOMAIN
try: try:
@ -116,6 +118,7 @@ class PluginPageApi:
("/config/module/update", self.config_module_update, ["POST"], "MemoryCompanion Page config module update"), ("/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"), ("/retrieval/config/update", self.retrieval_config_update, ["POST"], "MemoryCompanion Page retrieval config update"),
("/operations/diagnostics", self.operations_diagnostics, ["GET"], "MemoryCompanion operations diagnostics"), ("/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"), ("/operations/preset", self.operations_preset, ["GET", "POST"], "MemoryCompanion operations preset"),
("/data/export", self.data_export, ["POST"], "MemoryCompanion portable data export"), ("/data/export", self.data_export, ["POST"], "MemoryCompanion portable data export"),
("/data/import/preview", self.data_import_preview, ["GET"], "MemoryCompanion portable data preview"), ("/data/import/preview", self.data_import_preview, ["GET"], "MemoryCompanion portable data preview"),
@ -157,6 +160,62 @@ class PluginPageApi:
except Exception as exc: except Exception as exc:
return self._err(f"运维诊断失败: {exc}", 500) 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): async def operations_preset(self):
if request.method == "GET": if request.method == "GET":
return self._ok({"preset": self.plugin.service.operation_preset_status()}) return self._ok({"preset": self.plugin.service.operation_preset_status()})

查看文件

@ -3320,6 +3320,46 @@ pre{white-space:pre-wrap;overflow-wrap:anywhere}
color:var(--accent-strong); color:var(--accent-strong);
font-size:14px; 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{ .visually-hidden{
position:absolute!important; position:absolute!important;
width:1px!important; width:1px!important;

查看文件

@ -9,7 +9,7 @@ const VIEWS = {
relations: { title: "用户记忆", hint: "聚焦用户画像、偏好、称呼和关系声明。" }, relations: { title: "用户记忆", hint: "聚焦用户画像、偏好、称呼和关系声明。" },
review: { title: "个人记忆", hint: "查看 Bot 自身的每日生活日程、相册、主观记忆和细化片段。" }, review: { title: "个人记忆", hint: "查看 Bot 自身的每日生活日程、相册、主观记忆和细化片段。" },
archive: { title: "维护 / 迁移 / 配置", hint: "执行维护、迁移、清理和导入修复。" }, archive: { title: "维护 / 迁移 / 配置", hint: "执行维护、迁移、清理和导入修复。" },
maintain: { title: "私聊记忆", hint: "查看私聊范围内的对话、偏好、事实和稳定记忆。" }, maintain: { title: "用户记忆", hint: "查看用户范围内的对话、偏好、事实和稳定记忆。" },
}; };
const PERSONAL_MEMORY_VIEW = { const PERSONAL_MEMORY_VIEW = {
@ -593,7 +593,7 @@ function isWindowBucket(bucket) {
} }
function windowKindLabel(scope) { function windowKindLabel(scope) {
return scope === "group" ? "群聊" : "私聊"; return scope === "group" ? "群聊" : "用户";
} }
function bucketByWindow(scope, id) { function bucketByWindow(scope, id) {
@ -634,7 +634,7 @@ function splitWindowBucketTitle(bucket = {}) {
: rawLabel; : rawLabel;
const explicitName = cleanWindowDisplayName(bucket.target_name || bucket.display_name || ""); const explicitName = cleanWindowDisplayName(bucket.target_name || bucket.display_name || "");
const inferredName = cleanWindowDisplayName(nameFromLabel || ""); const inferredName = cleanWindowDisplayName(nameFromLabel || "");
const genericNames = new Set(["群聊", "私聊", "用户", "好友", "旧 Live2D 会话", "旧私聊会话", "内部会话", "私聊会话"]); const genericNames = new Set(["群聊", "私聊", "用户", "好友", "旧 Live2D 会话", "旧私聊会话", "旧用户会话", "内部会话", "私聊会话", "用户会话"]);
const name = explicitName || (genericNames.has(inferredName) ? "" : inferredName); const name = explicitName || (genericNames.has(inferredName) ? "" : inferredName);
if (scope === "group") { if (scope === "group") {
return { return {
@ -937,7 +937,7 @@ function memoryStatsItems(stats) {
value: formatFileSize(storageBytes), value: formatFileSize(storageBytes),
title: `数据库 ${formatFileSize(databaseBytes)} · WAL ${formatFileSize(walBytes)} · SHM ${formatFileSize(shmBytes)}`, 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 }, { key: "group-memory", label: "群聊记忆", value: stats.by_scope?.group ?? 0 },
]; ];
} }
@ -1009,13 +1009,13 @@ function renderStandardRecentBuckets() {
const windows = state.buckets.filter(isWindowBucket); const windows = state.buckets.filter(isWindowBucket);
const privateCount = windows.filter((bucket) => bucket.scope === "private").length; const privateCount = windows.filter((bucket) => bucket.scope === "private").length;
const groupCount = windows.filter((bucket) => bucket.scope === "group").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] const recent = [...windows]
.sort((left, right) => String(right.latest_at || "").localeCompare(String(left.latest_at || ""))) .sort((left, right) => String(right.latest_at || "").localeCompare(String(left.latest_at || "")))
.slice(0, 5); .slice(0, 5);
if (!recent.length) { if (!recent.length) {
host.innerHTML = '<p class="overview-empty">还没有私聊或群聊记忆</p>'; host.innerHTML = '<p class="overview-empty">还没有用户或群聊记忆</p>';
return; return;
} }
host.innerHTML = recent.map((bucket) => { host.innerHTML = recent.map((bucket) => {
@ -1058,7 +1058,7 @@ function scopedRailConfig(scope) {
if (scope === "group") { if (scope === "group") {
return { title: "群聊列表", clear: "全部群聊", label: "全部群聊", sublabel: "不限定群聊", badge: "群聊" }; return { title: "群聊列表", clear: "全部群聊", label: "全部群聊", sublabel: "不限定群聊", badge: "群聊" };
} }
return { title: "私聊用户", clear: "全部私聊", label: "全部私聊", sublabel: "不限定用户", badge: "私聊" }; return { title: "用户", clear: "全部用户", label: "全部用户", sublabel: "不限定用户", badge: "用户" };
} }
function bindBucketListInteractions() { function bindBucketListInteractions() {
@ -1110,7 +1110,7 @@ function updateScopedClearButton(view = state.activeView) {
const canClear = Boolean(bucket && bucket.id !== "all" && bucket.scope === scope && bucket.target_id); const canClear = Boolean(bucket && bucket.id !== "all" && bucket.scope === scope && bucket.target_id);
if (button) { if (button) {
button.disabled = !canClear; button.disabled = !canClear;
button.title = canClear ? `清空 ${bucket.label} 的记忆` : `请先选择具体${scope === "group" ? "群聊" : "私聊用户"}`; button.title = canClear ? `清空 ${bucket.label} 的记忆` : `请先选择具体${scope === "group" ? "群聊" : "用户"}`;
} }
if (view === "film") { if (view === "film") {
const memberInput = $("#clearGroupMemberUserId"); const memberInput = $("#clearGroupMemberUserId");
@ -1680,7 +1680,7 @@ async function loadActiveView() {
} else if (state.activeView === "review") { } else if (state.activeView === "review") {
await loadPersonalMemory(); await loadPersonalMemory();
} else if (state.activeView === "maintain") { } else if (state.activeView === "maintain") {
await loadScopedMemories("#privateMemoryList", "private", "正在读取私聊记忆...", "还没有私聊范围内的记忆。"); await loadScopedMemories("#privateMemoryList", "private", "正在读取用户记忆...", "还没有用户范围内的记忆。");
} else if (state.activeView === "archive") { } else if (state.activeView === "archive") {
await loadArchive(); await loadArchive();
} }
@ -1863,7 +1863,7 @@ async function loadScopedMemories(selector, scope, loadingText, emptyText, extra
target.innerHTML = loadingState(loadingText); target.innerHTML = loadingState(loadingText);
const { params, incompatible } = scopedMemoryParams(scope, { limit: 120, ...extra }); const { params, incompatible } = scopedMemoryParams(scope, { limit: 120, ...extra });
if (incompatible) { if (incompatible) {
const label = scope === "group" ? "群聊" : "私聊"; const label = scope === "group" ? "群聊" : "用户";
target.innerHTML = `<div class="empty-state">当前观察对象不属于${escapeHtml(label)}范围。请选择${escapeHtml(label)}对象或切回全部。</div>`; target.innerHTML = `<div class="empty-state">当前观察对象不属于${escapeHtml(label)}范围。请选择${escapeHtml(label)}对象或切回全部。</div>`;
return; return;
} }
@ -4515,6 +4515,119 @@ async function runOperationsDiagnostics() {
showToast("运维诊断已生成"); 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 `
<article class="coordination-status-item is-${escapeHtml(meta.tone)}">
<div><b>${escapeHtml(title)}</b><span class="badge ${escapeHtml(meta.tone)}">${escapeHtml(meta.label)}</span></div>
<strong>${escapeHtml(detail || coordinationReasonLabel(status.reason_code))}</strong>
<small>${escapeHtml(coordinationReasonLabel(status.reason_code))}</small>
</article>
`;
}
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 = `
<div class="coordination-status-summary is-${escapeHtml(overall.tone)}">
<span class="badge ${escapeHtml(overall.tone)}">${escapeHtml(overall.label)}</span>
<b>${escapeHtml(coordinationReasonLabel(status.reason_code))}</b>
<small>本卡片不提供启用、迁移、恢复或权限变更操作。</small>
</div>
<div class="coordination-status-items">
${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)}`)}
</div>
`;
}
async function loadCoordinationStatus() {
const target = $("#coordinationStatus");
if (target) target.innerHTML = '<p class="empty-state">正在读取安全与协同状态...</p>';
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) { async function applyOperationPreset(preset) {
const labels = { light: "轻量", standard: "标准", companion: "陪伴" }; const labels = { light: "轻量", standard: "标准", companion: "陪伴" };
const label = labels[preset] || preset; const label = labels[preset] || preset;
@ -5585,7 +5698,7 @@ async function executeScopedClearMemory(payload) {
async function clearCurrentScopedMemory(scope) { async function clearCurrentScopedMemory(scope) {
const payload = scopedClearPayload(scope); const payload = scopedClearPayload(scope);
if (!payload) { if (!payload) {
const message = scope === "group_member" ? "请先选择具体群聊并填写群成员 QQ" : `请先选择具体${scope === "group" ? "群聊" : "私聊用户"}`; const message = scope === "group_member" ? "请先选择具体群聊并填写群成员 QQ" : `请先选择具体${scope === "group" ? "群聊" : "用户"}`;
showToast(message, "error"); showToast(message, "error");
return; return;
} }
@ -5694,6 +5807,7 @@ function bindActions() {
$("#runSearchBtn").addEventListener("click", (event) => withButton(event.currentTarget, "检索中", runSearch)); $("#runSearchBtn").addEventListener("click", (event) => withButton(event.currentTarget, "检索中", runSearch));
$("#maintenanceBtn").addEventListener("click", () => withBusy("正在运行维护...", runMaintenance)); $("#maintenanceBtn").addEventListener("click", () => withBusy("正在运行维护...", runMaintenance));
$("#operationsDiagnosticsBtn").addEventListener("click", () => withBusy("正在生成运维诊断...", runOperationsDiagnostics)); $("#operationsDiagnosticsBtn").addEventListener("click", () => withBusy("正在生成运维诊断...", runOperationsDiagnostics));
$("#coordinationStatusRefreshBtn").addEventListener("click", () => withBusy("正在刷新安全与协同状态...", loadCoordinationStatus));
$$('[data-operation-preset]').forEach((button) => { $$('[data-operation-preset]').forEach((button) => {
button.addEventListener("click", () => withBusy("正在应用运行预设...", () => applyOperationPreset(button.dataset.operationPreset))); button.addEventListener("click", () => withBusy("正在应用运行预设...", () => applyOperationPreset(button.dataset.operationPreset)));
}); });
@ -6176,7 +6290,7 @@ function renderAclTopology(data) {
// Column headers // Column headers
nodesHtml += ` nodesHtml += `
<text class="topo-col-header" x="120" y="30" text-anchor="middle">群聊</text> <text class="topo-col-header" x="120" y="30" text-anchor="middle">群聊</text>
<text class="topo-col-header" x="620" y="30" text-anchor="middle">私聊</text>`; <text class="topo-col-header" x="620" y="30" text-anchor="middle">用户</text>`;
// Nodes // Nodes
for (const n of nodes) { for (const n of nodes) {
@ -6340,6 +6454,7 @@ async function init() {
bindActions(); bindActions();
playInitialOverviewEntrance(); playInitialOverviewEntrance();
await loadConfiguredTheme(); await loadConfiguredTheme();
await loadCoordinationStatus();
try { try {
await loadCompanionAvailability(); await loadCompanionAvailability();
await loadStats(); await loadStats();

查看文件

@ -54,7 +54,7 @@
<section id="standardStats" class="overview-kpi-grid" aria-label="记忆库统计" aria-live="polite"> <section id="standardStats" class="overview-kpi-grid" aria-label="记忆库统计" aria-live="polite">
<article class="overview-kpi is-loading"><span>记忆</span><b>--</b></article> <article class="overview-kpi is-loading"><span>记忆</span><b>--</b></article>
<article class="overview-kpi is-loading"><span>记忆大小</span><b>--</b></article> <article class="overview-kpi is-loading"><span>记忆大小</span><b>--</b></article>
<article class="overview-kpi is-loading"><span>私聊记忆</span><b>--</b></article> <article class="overview-kpi is-loading"><span>用户记忆</span><b>--</b></article>
<article class="overview-kpi is-loading"><span>群聊记忆</span><b>--</b></article> <article class="overview-kpi is-loading"><span>群聊记忆</span><b>--</b></article>
</section> </section>
@ -70,7 +70,7 @@
<div class="overview-entry-grid"> <div class="overview-entry-grid">
<button class="overview-entry is-private" data-overview-view="maintain" type="button"> <button class="overview-entry is-private" data-overview-view="maintain" type="button">
<span class="overview-entry-index">01</span> <span class="overview-entry-index">01</span>
<span class="overview-entry-copy"><b>私聊记忆</b><small>对话 · 偏好 · 稳定事实</small></span> <span class="overview-entry-copy"><b>用户记忆</b><small>对话 · 偏好 · 稳定事实</small></span>
<span class="overview-entry-arrow" aria-hidden="true">&rsaquo;</span> <span class="overview-entry-arrow" aria-hidden="true">&rsaquo;</span>
</button> </button>
<button class="overview-entry is-group" data-overview-view="film" type="button"> <button class="overview-entry is-group" data-overview-view="film" type="button">
@ -143,7 +143,7 @@
<button class="filmstrip" style="--a:14deg; --z:5;--off:-225px;--tx:-440px" data-view="relations" data-tip-title="用户记忆" data-tip-sub="用户画像 · 偏好 · 关系" type="button"><span class="strip-label" style="--label-edge:380px"><b>用户记忆</b><small>画像 · 偏好</small></span></button> <button class="filmstrip" style="--a:14deg; --z:5;--off:-225px;--tx:-440px" data-view="relations" data-tip-title="用户记忆" data-tip-sub="用户画像 · 偏好 · 关系" type="button"><span class="strip-label" style="--label-edge:380px"><b>用户记忆</b><small>画像 · 偏好</small></span></button>
<button class="filmstrip" style="--a:162deg;--z:1;--off:215px;--tx:-260px" data-view="review" data-tip-title="个人记忆" data-tip-sub="Bot 日程 · 生活细化" type="button"><span class="strip-label is-flipped"><b>个人记忆</b><small>日程 · 细化</small></span></button> <button class="filmstrip" style="--a:162deg;--z:1;--off:215px;--tx:-260px" data-view="review" data-tip-title="个人记忆" data-tip-sub="Bot 日程 · 生活细化" type="button"><span class="strip-label is-flipped"><b>个人记忆</b><small>日程 · 细化</small></span></button>
<button class="filmstrip" style="--a:136deg;--z:3;--off:-390px" data-view="archive" data-tip-title="维护/迁移/配置" data-tip-sub="工具 · 迁移 · 配置" type="button"><span class="strip-label is-flipped"><b>维护/迁移/配置</b><small>工具 · 配置</small></span></button> <button class="filmstrip" style="--a:136deg;--z:3;--off:-390px" data-view="archive" data-tip-title="维护/迁移/配置" data-tip-sub="工具 · 迁移 · 配置" type="button"><span class="strip-label is-flipped"><b>维护/迁移/配置</b><small>工具 · 配置</small></span></button>
<button class="filmstrip" style="--a:106deg;--z:6;--off:220px" data-view="maintain" data-tip-title="私聊记忆" data-tip-sub="私聊范围内的记忆" type="button"><span class="strip-label is-flipped"><b>私聊记忆</b><small>私聊 · 记忆</small></span></button> <button class="filmstrip" style="--a:106deg;--z:6;--off:220px" data-view="maintain" data-tip-title="用户记忆" data-tip-sub="用户范围内的记忆" type="button"><span class="strip-label is-flipped"><b>用户记忆</b><small>用户 · 记忆</small></span></button>
<section class="overview-core" aria-live="polite"> <section class="overview-core" aria-live="polite">
<div class="core-ring"></div> <div class="core-ring"></div>
@ -250,8 +250,8 @@
<section id="view-maintain" class="view"> <section id="view-maintain" class="view">
<div class="section-head"> <div class="section-head">
<div> <div>
<h3 id="privateMemoryTitle">私聊记忆</h3> <h3 id="privateMemoryTitle">用户记忆</h3>
<p id="privateMemoryHint">查看私聊范围内的对话、偏好、事实和稳定记忆。</p> <p id="privateMemoryHint">查看用户范围内的对话、偏好、事实和稳定记忆。</p>
</div> </div>
<button id="clearCurrentPrivateMemoryBtn" class="danger subtle" type="button" disabled>清空当前用户</button> <button id="clearCurrentPrivateMemoryBtn" class="danger subtle" type="button" disabled>清空当前用户</button>
</div> </div>
@ -272,6 +272,18 @@
<h4>维护 / 迁移 / 清理</h4> <h4>维护 / 迁移 / 清理</h4>
<div class="maintenance-box"> <div class="maintenance-box">
<p class="archive-note">推荐先选择运行预设并查看诊断,再执行迁移或维护。所有导入与清空操作都会先备份数据库。</p> <p class="archive-note">推荐先选择运行预设并查看诊断,再执行迁移或维护。所有导入与清空操作都会先备份数据库。</p>
<section class="coordination-status-card" aria-labelledby="coordinationStatusTitle">
<div class="coordination-status-head">
<span>
<b id="coordinationStatusTitle">安全与协同状态</b>
<small>只读汇总 P5 门禁、运行时兼容性、陪伴桥接与 P6 协议;不显示记忆正文、身份、会话或审计记录。</small>
</span>
<button id="coordinationStatusRefreshBtn" class="subtle" type="button">刷新状态</button>
</div>
<div id="coordinationStatus" class="coordination-status-grid" aria-live="polite">
<p class="empty-state">正在读取安全与协同状态...</p>
</div>
</section>
<div class="maintenance-tool-grid"> <div class="maintenance-tool-grid">
<section class="maintenance-action"> <section class="maintenance-action">
<b>1. 运行预设</b> <b>1. 运行预设</b>

查看文件

@ -1,7 +1,7 @@
from __future__ import annotations from __future__ import annotations
PLUGIN_NAME = "astrbot_plugin_memory_companion_ops" PLUGIN_NAME = "astrbot_plugin_memory_companion_ops"
PLUGIN_DISPLAY_NAME = "我会牢牢记住你・运维记忆" PLUGIN_DISPLAY_NAME = "雪色的我会永远记住你-运维版"
PLUGIN_VERSION = "1.6.2-ops.2" PLUGIN_VERSION = "1.6.2-ops.2"
PLUGIN_REPO = "https://forgejo.yokiirobw.top:55443/YokiiroBW/astrbot_plugin_memory_companion_ops" PLUGIN_REPO = "https://forgejo.yokiirobw.top:55443/YokiiroBW/astrbot_plugin_memory_companion_ops"
PRIVATE_COMPANION_PLUGIN_NAMES = ( PRIVATE_COMPANION_PLUGIN_NAMES = (

查看文件

@ -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("<b>用户记忆</b>", 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()