diff --git a/constants.py b/constants.py index 404c2a5..bb7eeaa 100644 --- a/constants.py +++ b/constants.py @@ -3,7 +3,7 @@ from __future__ import annotations import re PLUGIN_NAME = "astrbot_plugin_private_companion_ops" -PLUGIN_DISPLAY_NAME = "我会永远陪着你・运维人格" +PLUGIN_DISPLAY_NAME = "雪色的我会永远陪着你-运维版" PLUGIN_VERSION = "5.10.4-ops.1" PLUGIN_REPO = "https://forgejo.yokiirobw.top:55443/YokiiroBW/astrbot_plugin_private_companion_ops" DATA_VERSION = 1 diff --git a/metadata.yaml b/metadata.yaml index 2fb2116..de3c2a7 100644 --- a/metadata.yaml +++ b/metadata.yaml @@ -1,5 +1,5 @@ name: astrbot_plugin_private_companion_ops -display_name: 我会永远陪着你・运维人格 +display_name: 雪色的我会永远陪着你-运维版 author: menglimi author_url: https://github.com/menglimi description: astrbot_plugin_private_companion_ops 是面向专用 AstrBot VM 运维平台的人格与陪伴编排插件。它把人格连续性、生活状态、日程细化、私聊关系、群聊观察、QQ 关系网、主动消息、图片/语音/转发理解、长期创作、模型 Provider 和扩展页排障组织到同一套体验里,让 Bot 不只是临时回复,而是有状态、有记忆、有边界地生活和互动。 diff --git a/ops_status_projection.py b/ops_status_projection.py new file mode 100644 index 0000000..0aa73f8 --- /dev/null +++ b/ops_status_projection.py @@ -0,0 +1,204 @@ +"""Safe, versioned status DTOs for the Companion management page. + +These projections deliberately expose only fixed labels, switches and bounded +counts. They must not become another path to P4 ledgers, P5 source material, +P3 carriers, review records or unified-person identities. +""" +from __future__ import annotations + +from typing import Any + +try: # Package import for the plugin; direct import for focused tests. + from .context_orchestration import CONTRACT_VERSION as P3_CONTRACT_VERSION + from .p4_live_runtime import project_warmth_band + from .p6_readonly_projection import build_p6_readonly_status +except ImportError: # pragma: no cover - exercised by unittest discovery. + from context_orchestration import CONTRACT_VERSION as P3_CONTRACT_VERSION # type: ignore + from p4_live_runtime import project_warmth_band # type: ignore + from p6_readonly_projection import build_p6_readonly_status # type: ignore + + +OPS_STATUS_SCHEMA_VERSION = "ops.page_status.v1" +P4_USER_STATUS_SCHEMA_VERSION = "ops.page_user_p4_status.v1" + +_MAX_REVIEW_COUNT = 10_000_000 +_P5_GROUP_FLAGS = { + "b": ( + "enable_p5_b1_recall_gate", + "enable_p5_b1_bridge_gate", + "enable_p5_b1_forward_quote_prompt_gate", + "enable_p5_b1_private_reply_vision_gate", + ), + "c": ( + "enable_p5c_raw_image_provider_gate", + "enable_p5c_group_image_vision_gate", + "enable_p5c_context_image_caption_gate", + "enable_p5c_tool_parameter_gate", + ), + "d": ( + "enable_p5d_cross_turn_correlation", + "enable_p5d_manual_recovery", + ), +} +_WARMTH_BANDS = ("unknown", "confinement", "guarded", "reserved", "neutral", "warm", "close", "very_warm") + + +def build_ops_status_projection( + *, + p4_runtime_enabled: Any, + p4_manual_review_enabled: Any, + p4_review_container: Any, + p4_effect_container: Any, + p5_source_observer_enabled: Any, + p5_protection_flags: Any, + p6_registry_status: Any, +) -> dict[str, Any]: + """Return the exact, page-safe cross-stage status DTO. + + Callers may pass the internal P4 review container and registry status, but + this function reads neither candidate records nor any ledger/audit body. + The returned structure is allowlist-only and contains no identifiers, + scores, source content, capabilities, attestations or credentials. + """ + runtime_enabled = bool(p4_runtime_enabled) + review_enabled = bool(p4_manual_review_enabled) + review = _review_queue_summary(p4_review_container, enabled=review_enabled) + runtime = _p4_runtime_aggregate(p4_effect_container, enabled=runtime_enabled) + p5_group_counts = _p5_group_counts(p5_protection_flags) + protected_sink_count = sum(p5_group_counts.values()) + observer_enabled = bool(p5_source_observer_enabled) + if protected_sink_count: + p5_status = "protected" + elif observer_enabled: + p5_status = "observing" + else: + p5_status = "disabled" + p6 = build_p6_readonly_status(p6_registry_status) + return { + "schema_version": OPS_STATUS_SCHEMA_VERSION, + "p3": { + "contract_version": P3_CONTRACT_VERSION, + "status": "available", + }, + "p4": { + "runtime_enabled": runtime_enabled, + "protection_status": "protected" if runtime_enabled else "disabled", + "review_enabled": review_enabled, + "review_candidate_count": review["candidate_count"], + "review_status": review["status"], + "runtime_status": runtime["status"], + "warmth_band_counts": dict(runtime["warmth_band_counts"]), + "active_confinement_count": runtime["active_confinement_count"], + }, + "p5": { + "source_observer_enabled": observer_enabled, + "b_gate_count": p5_group_counts["b"], + "c_gate_count": p5_group_counts["c"], + "d_gate_count": p5_group_counts["d"], + "protected_sink_count": protected_sink_count, + "protection_status": p5_status, + }, + "p6": { + "health": p6["health"], + "reason_code": p6["reason_code"], + "counts": dict(p6["counts"]), + }, + } + + +def build_user_p4_status_projection(*, runtime_enabled: Any) -> dict[str, Any]: + """Return a user-page P4 status without attempting identity resolution. + + A web page has no authenticated AstrBot event principal. It therefore + cannot safely bind a stored user record to a P4 person or issue a review + decision. The explicit unavailable state is safer than guessing from an + ID, alias, nickname, ledger, or configured owner list. + """ + return { + "schema_version": P4_USER_STATUS_SCHEMA_VERSION, + "runtime_enabled": bool(runtime_enabled), + "warmth_band": "unknown", + "confinement_state": "unknown", + "confinement_until": "", + "review_candidate_count": 0, + "review_status": "identity_not_verifiably_linked", + "action_available": False, + "action_unavailable_reason": "host_principal_unavailable", + } + + +def _review_queue_summary(container: Any, *, enabled: bool) -> dict[str, Any]: + if not enabled: + return {"candidate_count": 0, "status": "disabled"} + if container is None: + return {"candidate_count": 0, "status": "no_pending"} + if type(container) is not dict or container.get("version") != 1: + return {"candidate_count": 0, "status": "unverifiable"} + candidates = container.get("candidates") + decisions = container.get("decisions") + event_index = container.get("event_index") + if type(candidates) is not dict or type(decisions) is not dict or type(event_index) is not dict: + return {"candidate_count": 0, "status": "unverifiable"} + if len(candidates) > _MAX_REVIEW_COUNT or len(decisions) > _MAX_REVIEW_COUNT: + return {"candidate_count": 0, "status": "unverifiable"} + pending_count = sum(1 for candidate_id in candidates if candidate_id not in decisions) + return { + "candidate_count": pending_count, + "status": "pending" if pending_count else "no_pending", + } + + +def _p5_group_counts(value: Any) -> dict[str, int]: + if type(value) is not dict: + return {group: 0 for group in _P5_GROUP_FLAGS} + return { + group: sum(bool(value.get(key)) for key in flags) + for group, flags in _P5_GROUP_FLAGS.items() + } + + +def _p4_runtime_aggregate(container: Any, *, enabled: bool) -> dict[str, Any]: + counts = {band: 0 for band in _WARMTH_BANDS} + if not enabled: + return {"status": "disabled", "warmth_band_counts": counts, "active_confinement_count": 0} + if container is None: + return {"status": "no_runtime_data", "warmth_band_counts": counts, "active_confinement_count": 0} + if type(container) is not dict or type(container.get("people")) is not dict: + return {"status": "unverifiable", "warmth_band_counts": counts, "active_confinement_count": 0} + people = container["people"] + if len(people) > _MAX_REVIEW_COUNT: + return {"status": "unverifiable", "warmth_band_counts": counts, "active_confinement_count": 0} + active_confinement_count = 0 + invalid_count = 0 + for entry in people.values(): + state = entry.get("state") if type(entry) is dict else None + if type(state) is not dict: + invalid_count += 1 + continue + working = dict(state) + if working.get("mode") == "effect_preparation": + working["mode"] = "shadow" + try: + band = project_warmth_band(working).get("warmth_band") + except Exception: + band = "unknown" + if band not in counts: + band = "unknown" + counts[band] += 1 + if band == "confinement": + active_confinement_count += 1 + if invalid_count: + counts["unknown"] += invalid_count + return { + "status": "degraded" if invalid_count else "ready", + "warmth_band_counts": counts, + "active_confinement_count": active_confinement_count, + } + + +__all__ = [ + "OPS_STATUS_SCHEMA_VERSION", + "P4_USER_STATUS_SCHEMA_VERSION", + "build_ops_status_projection", + "build_user_p4_status_projection", +] diff --git a/page_api.py b/page_api.py index 64ea2c3..cf6dd4b 100644 --- a/page_api.py +++ b/page_api.py @@ -30,6 +30,7 @@ from .config_migration import _ensure_config_parent_dir from .agenda_contracts import WINDOW_SLUGS, window_for_plan_minutes from .helpers import _flat_get, _normalize_timezone_name, _redact_outbound_secrets, _safe_int, _set_into_config, _set_today_key_timezone, _strip_internal_message_blocks, _text_looks_garbled, _text_similarity, _today_key from .page_api_users_groups import PrivateCompanionPageApiUsersGroupsMixin +from .ops_status_projection import build_ops_status_projection, build_user_p4_status_projection from .planning import evaluate_daily_plan_quality, generate_daily_plan, generate_detail_enhancement from .memo_notes import ( apply_memo_note_action, @@ -208,6 +209,7 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiUsersGroupsMixin): register = self.plugin.context.register_web_api routes = [ ("/overview", self.get_overview, ["GET"], "Private Companion Page overview"), + ("/ops/status", self.get_ops_status, ["GET"], "Private Companion Page safe operations status"), ("/bot-self/summary", self.get_bot_self_summary, ["GET"], "Private Companion Bot self storage summary"), ("/bot-self/timeline", self.get_bot_self_timeline, ["GET"], "Private Companion Bot self timeline"), ("/bot-self/agenda", self.get_bot_self_agenda, ["GET"], "Private Companion Bot self agenda history"), @@ -504,6 +506,64 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiUsersGroupsMixin): logger.error(f"[PrivateCompanionPage] 获取总览失败: {exc}", exc_info=True) return self._error(str(exc)) + async def get_ops_status(self) -> dict[str, Any]: + """Return the page-safe P3--P6 operational status projection only.""" + try: + async with self.plugin._data_lock: + data = self.plugin.data if isinstance(self.plugin.data, dict) else {} + projection = self._ops_status_projection_locked(data) + return self._ok(projection) + except Exception as exc: + logger.error("[PrivateCompanionPage] safe ops status failed: %s", exc, exc_info=True) + # A status error must not turn this projection into an incidental + # recovery path for internal data or exception detail. + return self._error("安全状态暂不可用") + + def _ops_status_projection_locked(self, data: dict[str, Any]) -> dict[str, Any]: + """Build the only P3--P6 status shape that may leave the page API.""" + root_available = type(data.get("unified_person")) is dict + root = data.get("unified_person") if root_available else {} + p4_review = root.get("p4_review") if type(root) is dict else None + p4_effect = root.get("p4_effect") if type(root) is dict else None + p6_status = None + if root_available: + p6_status = { + "profiles": len(root.get("profiles") or {}) if type(root.get("profiles")) is dict else 0, + "identity_links": len(root.get("identity_links") or {}) if type(root.get("identity_links")) is dict else 0, + "audit_events": len(root.get("audit_events") or []) if type(root.get("audit_events")) is list else 0, + "operations": len(root.get("operations") or {}) if type(root.get("operations")) is dict else 0, + } + p5_flags = { + key: bool(getattr(self.plugin, key, False)) + for key in ( + "enable_p5_b1_recall_gate", + "enable_p5_b1_bridge_gate", + "enable_p5_b1_forward_quote_prompt_gate", + "enable_p5_b1_private_reply_vision_gate", + "enable_p5c_raw_image_provider_gate", + "enable_p5c_group_image_vision_gate", + "enable_p5c_context_image_caption_gate", + "enable_p5c_tool_parameter_gate", + "enable_p5d_cross_turn_correlation", + "enable_p5d_manual_recovery", + ) + } + return build_ops_status_projection( + p4_runtime_enabled=getattr(self.plugin, "enable_p4_live_runtime", False), + p4_manual_review_enabled=getattr(self.plugin, "enable_p4_manual_review", False), + p4_review_container=p4_review, + p4_effect_container=p4_effect, + p5_source_observer_enabled=getattr(self.plugin, "enable_p5_source_observer", False), + p5_protection_flags=p5_flags, + p6_registry_status=p6_status, + ) + + def _user_p4_status_projection(self) -> dict[str, Any]: + """Never resolve a page user to a P4 principal without a host event.""" + return build_user_p4_status_projection( + runtime_enabled=getattr(self.plugin, "enable_p4_live_runtime", False), + ) + def _token_overview_payload(self, usage: Any, balance_state: Any = None) -> dict[str, Any]: if not isinstance(usage, dict): usage = {} diff --git a/page_api_users_groups.py b/page_api_users_groups.py index 67e9a33..3d86f94 100644 --- a/page_api_users_groups.py +++ b/page_api_users_groups.py @@ -58,6 +58,7 @@ class PrivateCompanionPageApiUsersGroupsMixin: "last_user_message": self._display_message_text(user.get("last_user_message"), 500), "last_companion_message": self._display_message_text(user.get("last_companion_message"), 500), "delivery_route": delivery_route if isinstance(delivery_route, dict) else {}, + "p4_runtime": self._user_p4_status_projection(), "worldbook_member": worldbook_member, "formatted": { "relationship": self.plugin._format_relationship_summary(user), diff --git a/pages/陪伴面板/app.js b/pages/陪伴面板/app.js index 8cdcc2b..235874d 100644 --- a/pages/陪伴面板/app.js +++ b/pages/陪伴面板/app.js @@ -130,7 +130,7 @@ const state = { pageFontFamily: "original", pageTheme: "classic", overviewRefreshedAt: 0, - opsCenter: { loaded: false, loading: false, error: "", summary: null, timeline: null, agenda: null, persona: null, boundary: null }, + opsCenter: { loaded: false, loading: false, error: "", summary: null, timeline: null, agenda: null, persona: null, boundary: null, protection: null }, uxReviewShowAll: false, selectedFoodMenuIds: new Set(), }; @@ -1052,7 +1052,7 @@ const featureGroups = [ ], }, { - title: "私聊陪伴", + title: "用户陪伴", note: "关系、记忆、回复策略、主动终审和自然表达。", keys: [ "enable_mai_style_integration", @@ -1329,8 +1329,8 @@ const safeFeatureKeys = [ ]; const configLabels = { - enabled_user_count: "启用私聊对象", - user_count: "私聊对象总数", + enabled_user_count: "启用用户", + user_count: "用户总数", require_opt_in: "是否需要私聊确认", default_style: "默认语气", reply_style_prompt: "回复风格提示词", @@ -4855,9 +4855,10 @@ async function loadOpsCenter(force = false) { fetchJson("/agenda/reconciliation").catch((error) => ({ __error: error.message })), fetchJson("/bot-self/persona").catch((error) => ({ __error: error.message })), fetchJson("/memory-boundary/status").catch((error) => ({ __error: error.message })), + fetchJson("/ops/status").catch((error) => ({ __error: error.message })), ]); const clean = (value) => value && !value.__error ? value : null; - [state.opsCenter.summary, state.opsCenter.timeline, state.opsCenter.agenda, state.opsCenter.persona, state.opsCenter.boundary] = requests.map(clean); + [state.opsCenter.summary, state.opsCenter.timeline, state.opsCenter.agenda, state.opsCenter.persona, state.opsCenter.boundary, state.opsCenter.protection] = requests.map(clean); const errors = requests.filter((item) => item?.__error).map((item) => item.__error); state.opsCenter.error = errors.length ? errors.join(";") : ""; state.opsCenter.loaded = true; @@ -4873,6 +4874,7 @@ function renderOpsCenter() { const boundary = center.boundary || {}; const persona = center.persona || {}; const timeline = center.timeline || {}; + const protection = center.protection || {}; const overview = state.overview || {}; const put = (id, html) => { const node = document.getElementById(id); if (node) node.innerHTML = html; }; const text = (id, value) => { const node = document.getElementById(id); if (node) node.textContent = value; }; @@ -4897,6 +4899,35 @@ function renderOpsCenter() { put("opsBoundarySummary", `
用户记忆仅保存用户数据
Bot 数据外写${boundary.bot_self_external_write === false ? "已拦截" : "未确认"}
记忆插件${boundary.bridge_available ? opsSafe(boundary.bridge_name, "已连接") : "暂不可用"}
最近检查${opsTimeLabel(boundary.checked_at)}

${escapeHtml(opsSafe(boundary.boundary_note, "Bot 的日程、人格、创作和自我时间线不会写入用户记忆。"))}

`); const recordCount = summary.namespaces && typeof summary.namespaces === "object" ? Object.values(summary.namespaces).reduce((total, item) => total + Number(item?.count || 0), 0) : Number(summary.total_records || 0); put("opsSelfSummary", `
所有者Bot 自己
存储空间陪伴插件自有空间
记录数量${recordCount} 条
最近更新${opsTimeLabel(summary.latest_at)}

这里只读展示 Bot 的人格、日程、创作和自我时间线摘要,不提供直接改库入口。

`); + const p3 = protection.p3 || {}; + const p4 = protection.p4 || {}; + const p5 = protection.p5 || {}; + const p6 = protection.p6 || {}; + const p6Counts = p6.counts && typeof p6.counts === "object" ? p6.counts : {}; + const warmthCounts = p4.warmth_band_counts && typeof p4.warmth_band_counts === "object" ? p4.warmth_band_counts : {}; + const reviewStatusLabels = { + disabled: "未开启", + no_pending: "暂无候选", + pending: "有待处理候选", + unverifiable: "暂不可核验", + }; + const p5StatusLabels = { + protected: "保护已启用", + observing: "仅观察", + disabled: "未启用", + }; + const p6HealthLabels = { + ready: "健康", + degraded: "降级", + unverifiable: "暂不可核验", + }; + const protectionReady = Boolean(p4.runtime_enabled) && p6.health === "ready"; + const protectionBadge = document.getElementById("opsProtectionBadge"); + if (protectionBadge) { + protectionBadge.textContent = protectionReady ? "保护运行中" : "需要关注"; + protectionBadge.dataset.state = protectionReady ? "ok" : "warn"; + } + put("opsProtectionSummary", `
P3 上下文契约${escapeHtml(p3.status === "available" ? `版本 ${p3.contract_version || "-"}` : "暂不可用")}
P4 回复保护${escapeHtml(p4.runtime_enabled ? "已启用" : "未启用")}
P4 温度汇总${escapeHtml(`温和 ${Number(warmthCounts.warm || 0)} · 亲近 ${Number(warmthCounts.close || 0) + Number(warmthCounts.very_warm || 0)} · 克制 ${Number(warmthCounts.guarded || 0) + Number(warmthCounts.reserved || 0)}`)}
P4 黑屋保护${escapeHtml(`黑屋中 ${Number(p4.active_confinement_count || 0)} · ${p4.runtime_status === "ready" ? "状态已核验" : "状态待核验"}`)}
P4 第三次黑屋审核${escapeHtml(`${reviewStatusLabels[p4.review_status] || "暂不可核验"} · ${Number(p4.review_candidate_count || 0)} 项`)}
P5 输入保护${escapeHtml(`${p5StatusLabels[p5.protection_status] || "暂不可核验"} · B ${Number(p5.b_gate_count || 0)} / C ${Number(p5.c_gate_count || 0)} / D ${Number(p5.d_gate_count || 0)}`)}
P6 契约健康${escapeHtml(p6HealthLabels[p6.health] || "暂不可核验")}
P6 受控统计${escapeHtml(`资料 ${Number(p6Counts.profiles || 0)} · 关联 ${Number(p6Counts.identity_links || 0)} · 操作 ${Number(p6Counts.operations || 0)}`)}

只展示版本、开关和受控数量;不会展示用户身份、消息、分数、账本、审核内容或访问凭据。

`); const personaItems = Array.isArray(persona.items) ? persona.items : []; put("opsPersonaSummary", personaItems.length ? `` : `
暂无独立人格记录;当前人格继续由 AstrBot 与插件配置共同提供。
`); const timelineItems = Array.isArray(timeline.items) ? timeline.items : []; @@ -8203,7 +8234,7 @@ function renderStats() { const energyNumber = daily.energy === undefined || daily.energy === "" ? "" : `${formatNumber(Number(daily.energy || 0))}/100`; const mood = normalizeRoleplayStateText(daily.mood_bias) || daily.note || "暂无状态"; $("#stats").innerHTML = [ - statCard(`私聊 ${privateInfo.enabled_user_count || 0} · 群聊 ${groupInfo.enabled_group_count || 0}`, `总数:对象 ${privateInfo.user_count || 0} · 群聊 ${groupInfo.group_count || 0}`, "private"), + statCard(`用户 ${privateInfo.enabled_user_count || 0} · 群聊 ${groupInfo.enabled_group_count || 0}`, `总数:用户 ${privateInfo.user_count || 0} · 群聊 ${groupInfo.group_count || 0}`, "private"), statCard(dailyLimit > 0 ? `${formatCompactNumber(dailyUsed)} / ${formatCompactNumber(dailyLimit)}` : `${formatCompactNumber(dailyUsed)} / 不限`, "今日 Token 消耗 / 上限", "tokens"), statCard(energyLabel || "-", `心理能量${energyNumber ? ` ${energyNumber}` : ""} · ${mood}`, "memory"), statCard(`${enabledFeatures}/${featureKeys.length}`, "开启主开关 / 主开关总数", "config"), @@ -8514,8 +8545,8 @@ function renderDashboardLifeDesk(overview = {}) { const capabilities = [ { tab: "private", - label: "私聊陪伴", - value: `${privateInfo.enabled_user_count || 0}/${privateInfo.user_count || 0} 个对象`, + label: "用户陪伴", + value: `${privateInfo.enabled_user_count || 0}/${privateInfo.user_count || 0} 位用户`, ready: Number(privateInfo.enabled_user_count || 0) > 0, }, { @@ -12105,6 +12136,7 @@ async function renderUserDetail(forceFetch = false) { ${renderPrivateDeliveryRoute(detail)} ${renderPrivateBehaviorHabits(detail)} ${emotionGateBlock(detail)} + ${renderUserP4RuntimeStatus(detail.p4_runtime)} ${userWorldbookBlock(detail.worldbook_member)} ${detailBlock("最近对话", "", [["用户消息", detail.last_user_message || ""], ["陪伴回复", detail.last_companion_message || ""]])} ${renderOpenLoopBlock(detail)} @@ -12116,6 +12148,42 @@ async function renderUserDetail(forceFetch = false) { bindUserActions(detail); } +function renderUserP4RuntimeStatus(status) { + const p4 = status && typeof status === "object" ? status : {}; + const warmthLabels = { + unknown: "暂不可确认", + guarded: "克制", + neutral: "平和", + warm: "温和", + close: "亲近", + }; + const confinementLabels = { + unknown: "暂不可确认", + none: "未处于黑屋", + active: "黑屋中", + released: "已解除", + }; + const reviewLabels = { + identity_not_verifiably_linked: "未核验到可用身份关联", + host_principal_unavailable: "需要宿主身份核验", + disabled: "未开启", + no_pending: "暂无候选", + pending: "有待处理候选", + unverifiable: "暂不可核验", + }; + const expiry = String(p4.confinement_until || "").trim() || "-"; + const unavailable = p4.action_available === true + ? "当前页面不提供审核操作。" + : "页面没有 AstrBot 的实时宿主身份验证,不能代替聊天事件确认身份或提交审核。"; + return detailBlock("回复保护", unavailable, [ + ["运行状态", p4.runtime_enabled ? "已启用" : "未启用"], + ["温度档位", warmthLabels[p4.warmth_band] || "暂不可确认"], + ["黑屋状态", confinementLabels[p4.confinement_state] || "暂不可确认"], + ["黑屋到期", expiry], + ["第三次黑屋审核", `${reviewLabels[p4.review_status] || "暂不可核验"} · ${Number(p4.review_candidate_count || 0)} 项`], + ]); +} + function renderPrivateDeliveryRoute(detail) { const route = detail?.delivery_route && typeof detail.delivery_route === "object" ? detail.delivery_route : {}; const recentError = String(route.recent_error || "").trim(); diff --git a/pages/陪伴面板/index.html b/pages/陪伴面板/index.html index bd845f9..2aec5b9 100644 --- a/pages/陪伴面板/index.html +++ b/pages/陪伴面板/index.html @@ -109,7 +109,7 @@ - + @@ -189,11 +189,11 @@
- 互动与主动私聊、群聊和长线主动策略 + 互动与主动用户、群聊和长线主动策略
-

私聊策略

+

用户策略

@@ -209,11 +209,11 @@
- 关系与运行记录私聊关系、群聊观察和近期活跃情况 + 关系与运行记录用户关系、群聊观察和近期活跃情况
-

私聊关系分布

+

用户关系分布

@@ -247,6 +247,7 @@
CALENDAR / RECONCILIATION

计划与实际

MEMORY / SAFETY

记忆边界

检查中
+
P3 / P4 / P5 / P6

回复与契约保护

检查中
BOT / PRIVATE SPACE

Bot 自有空间

只读摘要
PERSONA / CONTEXT

人格与上下文

@@ -478,8 +479,8 @@ QQ空间 = 公开札记
-

私聊对象

-

管理关系角色、主动额度、行为习惯、陪伴状态和已整理的对话片段。

+

用户

+

管理用户关系角色、主动额度、行为习惯、陪伴状态和已整理的对话片段。

@@ -744,7 +745,7 @@ QQ空间 = 公开札记
-

私聊记忆构成

+

用户记忆构成

diff --git a/tests/test_ops_status_projection.py b/tests/test_ops_status_projection.py new file mode 100644 index 0000000..7ec4687 --- /dev/null +++ b/tests/test_ops_status_projection.py @@ -0,0 +1,168 @@ +from __future__ import annotations + +import importlib.util +import json +from pathlib import Path +import unittest + + +ROOT = Path(__file__).resolve().parents[1] +MODULE_PATH = ROOT / "ops_status_projection.py" +SPEC = importlib.util.spec_from_file_location("ops_status_projection_under_test", MODULE_PATH) +assert SPEC and SPEC.loader +projection = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(projection) + +AFFINITY_SPEC = importlib.util.spec_from_file_location( + "p4_affinity_confinement_for_ops_status_test", ROOT / "p4_affinity_confinement.py" +) +assert AFFINITY_SPEC and AFFINITY_SPEC.loader +affinity = importlib.util.module_from_spec(AFFINITY_SPEC) +AFFINITY_SPEC.loader.exec_module(affinity) + + +def _effect_state(*, warmth_score: int = 1, confined: bool = False) -> dict: + state = affinity.new_shadow_state() + state["mode"] = "effect_preparation" + state["score"] = -1200 if confined else warmth_score + state["warning_stage"] = "confinement" if confined else "none" + state["confinement_state"] = "active" if confined else "none" + state["confinement_round"] = 3 if confined else 0 + state["confinement_until"] = "2099-01-01T00:00:00Z" if confined else "" + state["confinement_duration_days"] = 9 if confined else 0 + return state + + +class OpsStatusProjectionTests(unittest.TestCase): + def test_p3_to_p6_projection_contains_only_allowlisted_summary_fields(self) -> None: + result = projection.build_ops_status_projection( + p4_runtime_enabled=True, + p4_manual_review_enabled=True, + p4_review_container={ + "version": 1, + "candidates": { + "candidate-secret": {"person_id": "person-secret", "raw": "must-not-leak"}, + }, + "event_index": {"event-secret": {"candidate_id": "candidate-secret"}}, + "decisions": {}, + }, + p4_effect_container={ + "people": { + "person-secret": {"state": _effect_state(warmth_score=1)}, + "person-confined": {"state": _effect_state(confined=True)}, + }, + }, + p5_source_observer_enabled=True, + p5_protection_flags={ + "enable_p5_b1_recall_gate": True, + "enable_p5_b1_bridge_gate": True, + "enable_p5c_tool_parameter_gate": True, + "enable_p5d_manual_recovery": True, + "unused": True, + }, + p6_registry_status={ + "profiles": 2, + "identity_links": 3, + "audit_events": 4, + "operations": 5, + "person_id": "person-secret", + "ledger": {"raw": "must-not-leak"}, + }, + ) + + self.assertEqual( + {"schema_version", "p3", "p4", "p5", "p6"}, + set(result), + ) + self.assertEqual({"contract_version", "status"}, set(result["p3"])) + self.assertEqual( + { + "runtime_enabled", "protection_status", "review_enabled", "review_candidate_count", + "review_status", "runtime_status", "warmth_band_counts", "active_confinement_count", + }, + set(result["p4"]), + ) + self.assertEqual(1, result["p4"]["review_candidate_count"]) + self.assertEqual(1, result["p4"]["warmth_band_counts"]["warm"]) + self.assertEqual(1, result["p4"]["warmth_band_counts"]["confinement"]) + self.assertEqual(1, result["p4"]["active_confinement_count"]) + self.assertEqual({"source_observer_enabled", "b_gate_count", "c_gate_count", "d_gate_count", "protected_sink_count", "protection_status"}, set(result["p5"])) + self.assertEqual((2, 1, 1, 4), (result["p5"]["b_gate_count"], result["p5"]["c_gate_count"], result["p5"]["d_gate_count"], result["p5"]["protected_sink_count"])) + self.assertEqual({"health", "reason_code", "counts"}, set(result["p6"])) + + serialized = json.dumps(result, ensure_ascii=True, sort_keys=True) + for forbidden in ("person-secret", "person-confined", "candidate-secret", "event-secret", "must-not-leak", '"score"', '"ledger"', '"attestation"', '"credential"'): + self.assertNotIn(forbidden, serialized) + + def test_user_projection_does_not_guess_a_p4_principal_or_offer_actions(self) -> None: + result = projection.build_user_p4_status_projection(runtime_enabled=True) + self.assertEqual( + { + "schema_version", "runtime_enabled", "warmth_band", "confinement_state", + "confinement_until", "review_candidate_count", "review_status", + "action_available", "action_unavailable_reason", + }, + set(result), + ) + self.assertTrue(result["runtime_enabled"]) + self.assertEqual("identity_not_verifiably_linked", result["review_status"]) + self.assertFalse(result["action_available"]) + self.assertEqual("host_principal_unavailable", result["action_unavailable_reason"]) + serialized = json.dumps(result, ensure_ascii=True, sort_keys=True) + for forbidden in ("person_id", "event_id", "score", "ledger", "attestation", "credential"): + self.assertNotIn(forbidden, serialized) + + def test_missing_p6_registry_is_unverifiable_not_a_healthy_zero(self) -> None: + result = projection.build_ops_status_projection( + p4_runtime_enabled=True, + p4_manual_review_enabled=False, + p4_review_container=None, + p4_effect_container=None, + p5_source_observer_enabled=False, + p5_protection_flags=None, + p6_registry_status=None, + ) + self.assertEqual("unverifiable", result["p6"]["health"]) + self.assertEqual("registry_status_unavailable", result["p6"]["reason_code"]) + + def test_status_api_failure_message_is_not_derived_from_exception_detail(self) -> None: + page_api = (ROOT / "page_api.py").read_text(encoding="utf-8") + start = page_api.index("async def get_ops_status") + end = page_api.index("def _ops_status_projection_locked", start) + status_api = page_api[start:end] + self.assertIn('return self._error("安全状态暂不可用")', status_api) + self.assertNotIn("return self._error(str(exc))", status_api) + + +class OpsStatusPageWiringTests(unittest.TestCase): + def test_page_route_and_safe_ui_bindings_are_present(self) -> None: + page_api = (ROOT / "page_api.py").read_text(encoding="utf-8") + app_js = (ROOT / "pages" / "陪伴面板" / "app.js").read_text(encoding="utf-8") + index_html = (ROOT / "pages" / "陪伴面板" / "index.html").read_text(encoding="utf-8") + + self.assertIn('(\"/ops/status\", self.get_ops_status, [\"GET\"]', page_api) + self.assertIn('"p4_runtime": self._user_p4_status_projection()', (ROOT / "page_api_users_groups.py").read_text(encoding="utf-8")) + self.assertIn('fetchJson("/ops/status")', app_js) + self.assertIn('id="opsProtectionSummary"', index_html) + self.assertIn('data-tab="private">04用户', index_html) + + start = app_js.index("function renderUserP4RuntimeStatus") + end = app_js.index("\nfunction renderPrivateDeliveryRoute", start) + user_p4_renderer = app_js[start:end] + self.assertIn("identity_not_verifiably_linked", user_p4_renderer) + for forbidden in ("relationship_score", "person_id", "event_id", "candidate_id", "audit", "ledger", "attestation", "credential"): + self.assertNotIn(forbidden, user_p4_renderer) + + def test_primary_private_scope_is_presented_as_users(self) -> None: + 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('data-tab="private">04用户', page) + self.assertIn("

用户关系分布

", page) + self.assertIn("statCard(`用户 ${privateInfo.enabled_user_count", script) + self.assertIn('label: "用户陪伴"', script) + + +if __name__ == "__main__": + unittest.main()