From 61c8ced8260fbe37707480ad79e93d34eee762f0 Mon Sep 17 00:00:00 2001 From: YokiiroBW Date: Thu, 30 Jul 2026 23:45:08 +0800 Subject: [PATCH] feat(reply): compose relationship temperature and panel --- main.py | 43 ++++- memory_companion_adapter.py | 25 +++ page_api.py | 102 +++++++++++- page_api_users_groups.py | 6 + pages/陪伴面板/app.js | 45 +++-- reply_temperature.py | 245 ++++++++++++++++++++++++++++ tests/test_ops_status_projection.py | 15 ++ tests/test_reply_temperature.py | 92 +++++++++++ 8 files changed, 555 insertions(+), 18 deletions(-) create mode 100644 reply_temperature.py create mode 100644 tests/test_reply_temperature.py diff --git a/main.py b/main.py index 65784fa..579f472 100644 --- a/main.py +++ b/main.py @@ -152,6 +152,7 @@ from .p4_manual_review import ( ) from . import p4_live_runtime from .p4_runtime_gate import apply_confinement_gate, build_warmth_projection +from .reply_temperature import compose_reply_temperature from .segmented_message import flatten_component_chunks, split_plain_component_chain_detailed from .token_budget import TokenBudgetMixin from .balance_awareness import BalanceAwarenessMixin @@ -10171,8 +10172,36 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge if not runtime_state or runtime_state.get("confinement_state") == "active": return projection = build_warmth_projection(runtime_state) - tier = _single_line(projection.get("tier"), 20) - boundary = _single_line(projection.get("boundary"), 120) + p4_tier = _single_line(projection.get("tier"), 20) + if not p4_tier: + return + daily_state = getattr(self, "data", {}).get("daily_state") if isinstance(getattr(self, "data", None), dict) else {} + schedule = "" + segment_getter = getattr(self, "_current_detail_segment_for_update", None) + if callable(segment_getter): + try: + segment = segment_getter() + except Exception: + segment = None + if isinstance(segment, dict): + schedule = " ".join( + _single_line(segment.get(key), 80) + for key in ("title", "name", "summary", "activity", "location") + if _single_line(segment.get(key), 80) + )[:240] + context = _single_line( + getattr(event, "message_str", "") or getattr(event, "private_companion_group_text", ""), + 280, + ) + composed = compose_reply_temperature( + p4_tier, + energy=daily_state.get("energy") if isinstance(daily_state, dict) else None, + mood=(daily_state.get("mood_bias") or daily_state.get("mood")) if isinstance(daily_state, dict) else None, + schedule=schedule, + context=context, + ) + tier = _single_line(composed.get("tier"), 20) + boundary = _single_line(composed.get("instruction"), 120) if not tier or not boundary: return marker = "" @@ -10181,7 +10210,8 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge if marker in current_prompt or marker in current_turn_prompt: return text = ( - "【关系温度】只用于调整表达亲近度,不改变安全权限。" + "【最终回复温度】综合用户关系好感的安全上限与 Bot 当前日程、心情和本轮上下文," + "只用于调整表达亲近度、长短和节奏,不改变安全权限。" f"当前表达档位:{tier}。{boundary}" ) placement = "prompt" if self._append_turn_prompt_fragment_by_position( @@ -10196,7 +10226,12 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge text=text, source="p4_warmth", mode="private" if self._safe_event_is_private(event) else "group", - metadata={"tier": tier, "placement": placement}, + metadata={ + "tier": tier, + "p4_cap": _single_line(composed.get("cap_tier"), 20), + "contextual_tier": _single_line(composed.get("state_tier"), 20), + "placement": placement, + }, ) @staticmethod diff --git a/memory_companion_adapter.py b/memory_companion_adapter.py index 709b9e0..1f1d26f 100644 --- a/memory_companion_adapter.py +++ b/memory_companion_adapter.py @@ -2127,3 +2127,28 @@ class MemoryCompanionAdapterMixin: except Exception as exc: self._memory_companion_optional_dependency_failed(exc, where="get_relationship_phase") return {"phase": "unknown", "momentum": 0.0} + + def _memory_companion_peek_relationship_phase(self, *, session_id: str = "") -> dict[str, Any]: + """Read the Memory relationship phase without creating a default state.""" + bridge = self._memory_companion_bridge() + if bridge is None: + return {"observed": False, "phase": "unknown", "momentum_band": "unknown", "status": "unavailable"} + getter = getattr(bridge, "peek_relationship_phase", None) + if not callable(getter): + return {"observed": False, "phase": "unknown", "momentum_band": "unknown", "status": "unsupported"} + try: + result = getter(session_id=session_id, scope="private") + except Exception as exc: + self._memory_companion_optional_dependency_failed(exc, where="peek_relationship_phase") + return {"observed": False, "phase": "unknown", "momentum_band": "unknown", "status": "unavailable"} + if not isinstance(result, dict): + return {"observed": False, "phase": "unknown", "momentum_band": "unknown", "status": "invalid"} + phase = _single_line(result.get("phase"), 40) or "unknown" + status = "observed" if bool(result.get("observed")) and phase != "unknown" else "not_observed" + return { + "observed": status == "observed", + "phase": phase, + "momentum_band": _single_line(result.get("momentum_band"), 20) or "unknown", + "touch_count": max(0, min(256, int(result.get("touch_count") or 0))), + "status": status, + } diff --git a/page_api.py b/page_api.py index cf6dd4b..cbb0717 100644 --- a/page_api.py +++ b/page_api.py @@ -9164,6 +9164,15 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiUsersGroupsMixin): relationship_state = self._emotion_relationship_state_summary(rel_state) pending_emotion_judgement = self._emotion_pending_judgement_summary(user.get("pending_emotion_judgement")) last_emotion_judgement_error = self._single_line(user.get("last_emotion_judgement_error"), 160) + relationship_score = self._int(user.get("relationship_score")) + relationship_basis = { + "value": relationship_score, + "band": ( + "亲近基础" if relationship_score >= 55 + else "熟悉基础" if relationship_score >= 3 + else "初始基础" + ), + } return { "user_id": user_id_text, "display_name": display_name, @@ -9233,7 +9242,7 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiUsersGroupsMixin): "inbound_count": user.get("inbound_count", 0), "reply_count": user.get("reply_count", 0), "proactive_sent_count": user.get("proactive_sent_count", 0), - "relationship_score": user.get("relationship_score", 0), + "relationship_basis": relationship_basis, "relationship_stage": relationship_stage, "relationship_state": relationship_state, "pending_emotion_judgement": pending_emotion_judgement, @@ -9253,6 +9262,97 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiUsersGroupsMixin): ], } + def _relationship_panel( + self, + user_id: str, + user: dict[str, Any], + *, + relationship_stage: str, + worldbook_member: dict[str, Any] | None, + ) -> dict[str, Any]: + """Build a safe, user-scoped relationship display projection.""" + score = self._int(user.get("relationship_score")) + inbound = max(0, self._int(user.get("inbound_count"))) + proactive = max(0, self._int(user.get("proactive_sent_count"))) + replies = max(0, self._int(user.get("reply_count"))) + reply_rate = replies / proactive if proactive else 0.0 + if proactive <= 0: + reply_band = "暂无主动样本" + elif reply_rate >= 0.65: + reply_band = "回应稳定" + elif reply_rate >= 0.30: + reply_band = "有回应" + else: + reply_band = "回应较少" + + memory_phase = { + "status": "unavailable", + "label": "记忆关系阶段暂不可用", + "momentum_band": "unknown", + } + session_id = self._single_line(user.get("umo"), 200) + getter = getattr(self.plugin, "_memory_companion_peek_relationship_phase", None) + if session_id and callable(getter): + try: + raw_phase = getter(session_id=session_id) + except Exception: + raw_phase = {} + if isinstance(raw_phase, dict): + phase_labels = { + "acquaintance": "陌生", + "familiar": "熟悉", + "close": "亲近", + "intimate": "亲密", + "deeply_bonded": "深度连接", + } + phase = self._single_line(raw_phase.get("phase"), 32) + phase_status = self._single_line(raw_phase.get("status"), 24) + if phase_status == "observed" and phase in phase_labels: + memory_phase = { + "status": "observed", + "label": phase_labels[phase], + "momentum_band": self._single_line(raw_phase.get("momentum_band"), 20) or "steady", + } + elif phase_status in {"not_observed", "unsupported", "unavailable", "invalid"}: + memory_phase = { + "status": phase_status, + "label": "尚未观察到记忆关系阶段" if phase_status == "not_observed" else "记忆关系阶段暂不可用", + "momentum_band": "unknown", + } + + network_status = "已登记节点" if isinstance(worldbook_member, dict) else "未登记节点" + network_linked = False + pending_count = 0 + if isinstance(worldbook_member, dict): + network_linked = bool( + worldbook_member.get("linked_qq_user_id") + or worldbook_member.get("linked_bili_profile_id") + or worldbook_member.get("external_ids") + ) + pending_count = max(0, self._int(worldbook_member.get("pending_observation_count"))) + return { + "relationship_basis": { + "value": score, + "band": "亲近基础" if score >= 55 else "熟悉基础" if score >= 3 else "初始基础", + }, + "relationship_stage": self._single_line(relationship_stage, 20) or "未分层", + "interaction": { + "inbound_count": inbound, + "reply_count": replies, + "reply_band": reply_band, + }, + "memory_phase": memory_phase, + "network": { + "status": network_status, + "linked_identity": network_linked, + "pending_observation_count": pending_count, + }, + "reply_temperature": { + "status": "live_chat_only", + "label": "真实聊天时由好感上限与当前日程、心情、上下文合成", + }, + } + def _emotion_relationship_state_summary(self, state: Any) -> dict[str, Any]: if not isinstance(state, dict): return {} diff --git a/page_api_users_groups.py b/page_api_users_groups.py index 3d86f94..037e39d 100644 --- a/page_api_users_groups.py +++ b/page_api_users_groups.py @@ -43,6 +43,12 @@ class PrivateCompanionPageApiUsersGroupsMixin: if not isinstance(user, dict): return self._error("用户不存在") detail = self._user_summary(user_id, user) + detail["relationship_panel"] = self._relationship_panel( + user_id, + user, + relationship_stage=str(detail.get("relationship_stage") or ""), + worldbook_member=worldbook_member, + ) route_status_getter = getattr(self.plugin, "_private_delivery_route_status", None) delivery_route = route_status_getter(user_id, user) if callable(route_status_getter) else {} detail.update( diff --git a/pages/陪伴面板/app.js b/pages/陪伴面板/app.js index 235874d..4b70441 100644 --- a/pages/陪伴面板/app.js +++ b/pages/陪伴面板/app.js @@ -5203,7 +5203,7 @@ const setupGuideSteps = [ { tab: "worldbook", groupIndex: 2, - title: "关系网词条", + title: "关系网节点", tag: "主动功能与其他配置", body: "这里可配置第一条关系网用户词条。关系网不是首次可用的前提;没有资料时可先跳过,之后再到关系网页补充。", checks: ["填写身份 QQ 与名称", "补充别名和关系资料", "确认自登记说明"], @@ -7497,7 +7497,7 @@ function setupGuideWorldbookDraftHtml() { ${setupGuideText("worldbookBoundaryNote", "互动边界", "例如:不公开聊隐私;不拿某个话题开玩笑。", true)}
- 完成引导时会写入关系网词条;确认按钮用于标记你已经检查过草稿。 + 完成引导时会写入关系网节点;确认按钮用于标记你已经检查过草稿。
@@ -7803,10 +7803,10 @@ function setupGuideRunThroughItems(overview = state.overview || {}) { }, { level: hasWorldbookDraft ? "info" : "skip", - title: "关系网词条", + title: "关系网节点", tab: "worldbook", action: "准备一条关系网用户词条。", - pass: hasWorldbookDraft ? "已填写关系网词条草稿。" : "关系网词条未填写,可以稍后补充。", + pass: hasWorldbookDraft ? "已填写关系网节点草稿。" : "关系网节点未填写,可以稍后补充。", }, { level: draft.proactivePrivate && requiredQuickProvidersReady ? "info" : "warn", @@ -12054,7 +12054,7 @@ function renderUsers() { ? rows.map((user) => ` ${escapeHtml(user.display_name || user.nickname || user.user_id)} ${userPlatformBadge(user)}${Array.isArray(user.alias_user_ids) && user.alias_user_ids.length ? ` 已合并 ${escapeHtml(user.alias_user_ids.length)} 个身份` : ""}
${escapeHtml(user.user_id)} - ${escapeHtml(user.enabled ? "启用" : "停用")} ${escapeHtml(user.relationship_role_label || "次要用户")} ${escapeHtml(user.relationship_stage || "未分层")}
分数 ${escapeHtml(user.relationship_score)} + ${escapeHtml(user.enabled ? "启用" : "停用")} ${escapeHtml(user.relationship_role_label || "次要用户")} ${escapeHtml(user.relationship_stage || "未分层")}
关系基础 ${escapeHtml(user.relationship_basis?.band || "初始基础")} 入站 ${escapeHtml(user.inbound_count)} · 回复 ${escapeHtml(user.reply_count)}
记忆 ${escapeHtml(user.memory_items)} 条 今日 ${escapeHtml(user.sent_today)} · 总计 ${escapeHtml(user.proactive_sent_count)}
${escapeHtml(user.next_proactive)} ${escapeHtml(user.last_seen)}
上次主动 ${escapeHtml(user.last_sent)} @@ -12125,13 +12125,14 @@ async function renderUserDetail(forceFetch = false) {
- ${scoreGauge("关系分", detail.relationship_score || 0, -20, 40)} + ${scoreGauge("关系基础", detail.relationship_basis?.value || 0, -20, 40)} ${scoreGauge("今日主动", detail.sent_today || 0, 0, proactiveGaugeMax(detail.sent_today, detail.effective_daily_limit, detail.effective_daily_limit_unlimited, state.overview?.private?.max_daily_messages || 8))} ${miniStat("片段", detail.dialogue_episode_count || (detail.dialogue_episodes || []).length)} ${miniStat("未完话头", Array.isArray(detail.open_loops) ? activeOpenLoopItems(detail.open_loops).length : (detail.open_loop_count || 0))} ${miniStat("习惯", detail.habit_count || detail.behavior_habits?.items?.length || 0)}
+ ${renderRelationshipPanel(detail.relationship_panel)} ${detailBlock("关系和主动", detail.formatted?.relationship || "", [["角色", detail.relationship_role_label || ""], ["有效主动上限", `${detail.effective_daily_limit_text || formatProactiveLimit(detail.effective_daily_limit, detail.effective_daily_limit_unlimited)} / 天`], ["下次主动", detail.formatted?.next_proactive || detail.next_proactive], ["动作偏好", detail.formatted?.action_affinity || ""]])} ${renderPrivateDeliveryRoute(detail)} ${renderPrivateBehaviorHabits(detail)} @@ -12148,6 +12149,24 @@ async function renderUserDetail(forceFetch = false) { bindUserActions(detail); } +function renderRelationshipPanel(panel) { + const data = panel && typeof panel === "object" ? panel : {}; + const basis = data.relationship_basis && typeof data.relationship_basis === "object" ? data.relationship_basis : {}; + const interaction = data.interaction && typeof data.interaction === "object" ? data.interaction : {}; + const memory = data.memory_phase && typeof data.memory_phase === "object" ? data.memory_phase : {}; + const network = data.network && typeof data.network === "object" ? data.network : {}; + const reply = data.reply_temperature && typeof data.reply_temperature === "object" ? data.reply_temperature : {}; + const momentumLabels = { rising: "正在升温", cooling: "正在降温", steady: "保持稳定", unknown: "暂不可确认" }; + return detailBlock("关系面板", "好感、当前状态和上下文会在真实聊天中合成为本轮最终回复温度。", [ + ["关系基础", basis.band || "初始基础"], + ["陪伴阶段", data.relationship_stage || "未分层"], + ["互动回应", `${interaction.reply_band || "暂无样本"} · 入站 ${Number(interaction.inbound_count || 0)} / 回复 ${Number(interaction.reply_count || 0)}`], + ["记忆关系阶段", `${memory.label || "暂不可用"} · ${momentumLabels[memory.momentum_band] || "暂不可确认"}`], + ["关系网节点", `${network.status || "未登记节点"}${network.linked_identity ? " · 已绑定身份" : ""}${Number(network.pending_observation_count || 0) ? ` · 待确认 ${Number(network.pending_observation_count || 0)} 条` : ""}`], + ["最终回复温度", reply.label || "仅在真实聊天中合成"], + ]); +} + function renderUserP4RuntimeStatus(status) { const p4 = status && typeof status === "object" ? status : {}; const warmthLabels = { @@ -12175,9 +12194,9 @@ function renderUserP4RuntimeStatus(status) { const unavailable = p4.action_available === true ? "当前页面不提供审核操作。" : "页面没有 AstrBot 的实时宿主身份验证,不能代替聊天事件确认身份或提交审核。"; - return detailBlock("回复保护", unavailable, [ + return detailBlock("安全回复保护", unavailable, [ ["运行状态", p4.runtime_enabled ? "已启用" : "未启用"], - ["温度档位", warmthLabels[p4.warmth_band] || "暂不可确认"], + ["安全温度档位", warmthLabels[p4.warmth_band] || "暂不可确认"], ["黑屋状态", confinementLabels[p4.confinement_state] || "暂不可确认"], ["黑屋到期", expiry], ["第三次黑屋审核", `${reviewLabels[p4.review_status] || "暂不可核验"} · ${Number(p4.review_candidate_count || 0)} 项`], @@ -12237,8 +12256,8 @@ function userWorldbookBlock(item) { if (!item) { return `
-

关系网词条

-
暂无对应关系节点
+

关系网节点

+
暂无已登记的正式关系节点;记忆中的待确认观察不会自动出现在这里。
`; } @@ -12255,7 +12274,7 @@ function userWorldbookBlock(item) {
-

关系网词条

+

关系网节点

${escapeHtml(item.name || item.user_id || "未命名成员")}

${escapeHtml(item.enabled ? "启用" : "停用")} @@ -20765,8 +20784,8 @@ const featureDetailGuides = { enable_relationship_analysis: { summary: "阶段性使用完整人格和互动数据,由模型复核关系层级与打扰偏好。", trigger: "首次建立关系画像、明确长期边界、互动阶段或回复率跨档,以及累计一段新互动后。", - enabled: "按变化调用关系分析模型,并保存陌生/熟悉/亲近、打扰偏好、关系分和简短理由供其他陪伴功能读取。", - disabled: "停止全部“关系分析”模型调用;已有结果继续可用,没有结果时使用本地互动次数、回复率和关系分兜底。", + enabled: "按变化调用关系分析模型,并保存陌生/熟悉/亲近、打扰偏好、关系基础和简短理由供其他陪伴功能读取。", + disabled: "停止全部“关系分析”模型调用;已有结果继续可用,没有结果时使用本地互动次数、回复率和关系基础兜底。", }, enable_relationship_state_machine: { summary: "维护 Bot 和用户之间的距离感,让回复和主动行为随亲近、冷淡、边界、长期未联系和主动消息回应情况自然变化。", diff --git a/reply_temperature.py b/reply_temperature.py new file mode 100644 index 0000000..c6bf619 --- /dev/null +++ b/reply_temperature.py @@ -0,0 +1,245 @@ +# -*- coding: utf-8 -*- +"""Pure composition of the final reply temperature. + +The P4 warmth tier is an authoritative ceiling. Daily state and bounded +context cues only express the temperature that would be preferred for this +turn; they never grant permission to exceed that ceiling. This module has no +AstrBot, persistence, identity, or ledger dependencies so it can be tested and +used as a small projection at the reply boundary. +""" +from __future__ import annotations + +from math import isfinite +from typing import Any, Iterable + + +REPLY_TEMPERATURE_TIERS = ("guarded", "neutral", "warm", "close") +_TIER_INDEX = {tier: index for index, tier in enumerate(REPLY_TEMPERATURE_TIERS)} +_TIER_SCORE = { + "guarded": 0.15, + "neutral": 0.45, + "warm": 0.70, + "close": 0.90, +} + +_UP_MOOD_WORDS = frozenset({ + "happy", "good", "positive", "joy", "calm", "开心", "高兴", "愉快", "轻松", + "积极", "满足", "安心", "兴奋", "顺利", "温柔", +}) +_DOWN_MOOD_WORDS = frozenset({ + "sad", "bad", "negative", "angry", "anxious", "tense", "tired", "sleepy", + "难过", "低落", "生气", "焦虑", "紧张", "疲惫", "疲劳", "困", "烦", "受伤", +}) +_UP_SCHEDULE_WORDS = frozenset({ + "free", "leisure", "rest", "relaxed", "闲", "空闲", "休闲", "放松", "散步", "周末", +}) +_DOWN_SCHEDULE_WORDS = frozenset({ + "sleep", "sleeping", "busy", "work", "meeting", "class", "commute", "resting", + "睡", "睡觉", "休息", "忙", "工作", "会议", "上课", "通勤", "值班", +}) +_BOUNDARY_CONTEXT_WORDS = frozenset({ + "别聊", "不要聊", "不想聊", "别问", "不用回复", "不要回复", "停下", "停止", + "换个话题", "到此为止", "睡了", "晚安", "忙着", "忙", "边界", +}) +_SECURITY_CONTEXT_WORDS = frozenset({ + "忽略之前", "忽略上文", "系统提示", "开发者消息", "越权", "授权", "密码", "密钥", + "注入", "jailbreak", "ignore previous", "system prompt", +}) +_NEGATIVE_CONTEXT_WORDS = frozenset({ + "难过", "生气", "焦虑", "紧张", "疲惫", "累", "困", "不舒服", "失望", "抱歉", +}) +_POSITIVE_CONTEXT_WORDS = frozenset({ + "谢谢", "感谢", "想你", "陪伴", "喜欢", "爱你", "开心", "好呀", "太好了", "顺利", + "轻松", "温柔", "thank", "thanks", "love", "miss you", "happy", +}) + + +def compose_reply_temperature( + p4_tier: Any, + *, + energy: Any = None, + mood: Any = None, + schedule: Any = None, + context: Any = None, +) -> dict[str, Any]: + """Compose one bounded, JSON-safe reply-temperature projection. + + ``p4_tier`` is normalized fail-closed to ``guarded``. Other inputs are + advisory signals: malformed values never increase the result, and raw + input text is never returned. The returned mapping is newly allocated on + every call and contains only primitive JSON-compatible values. + """ + + cap_tier, p4_valid = _normalize_p4_tier(p4_tier) + energy_delta, energy_label = _energy_signal(energy) + mood_delta, mood_label = _mood_signal(mood) + schedule_delta, schedule_label = _schedule_signal(schedule) + context_delta, context_label = _context_signal(context) + + state_index = _clamp_index(1 + energy_delta + mood_delta + schedule_delta) + desired_index = _clamp_index(state_index + context_delta) + final_index = min(_TIER_INDEX[cap_tier], desired_index) + tier = REPLY_TEMPERATURE_TIERS[final_index] + + codes: list[str] = [] + if not p4_valid: + codes.append("p4_invalid_fail_closed") + else: + codes.append(f"p4_cap_{cap_tier}") + codes.extend(( + f"energy_{energy_label}", + f"mood_{mood_label}", + f"schedule_{schedule_label}", + f"context_{context_label}", + )) + if final_index < desired_index: + codes.append("p4_cap_applied") + + return { + "tier": tier, + "score": _TIER_SCORE[tier], + "cap_tier": cap_tier, + "state_tier": REPLY_TEMPERATURE_TIERS[state_index], + "context_adjustment": context_delta, + "signals": { + "energy": energy_label, + "mood": mood_label, + "schedule": schedule_label, + "context": context_label, + }, + "codes": codes, + "instruction": _instruction_for(tier), + } + + +def _normalize_p4_tier(value: Any) -> tuple[str, bool]: + if type(value) is str: + candidate = value.strip().lower() + if candidate in _TIER_INDEX: + return candidate, True + return "guarded", False + + +def _clamp_index(value: int) -> int: + return max(0, min(len(REPLY_TEMPERATURE_TIERS) - 1, int(value))) + + +def _number(value: Any) -> float | None: + if isinstance(value, bool) or not isinstance(value, (int, float)): + return None + numeric = float(value) + return numeric if isfinite(numeric) else None + + +def _energy_signal(value: Any) -> tuple[int, str]: + numeric = _number(value) + if numeric is None: + return (0, "missing") if value is None else (-1, "invalid") + if numeric < 30: + return -1, "low" + if numeric >= 80: + return 1, "high" + return 0, "medium" + + +def _mood_signal(value: Any) -> tuple[int, str]: + numeric = _number(value) + if numeric is not None: + if numeric <= -35: + return -1, "down" + if numeric >= 35: + return 1, "up" + return 0, "neutral" + text = _extract_text(value, keys=("mood", "label", "name", "state")) + if text is None: + return (0, "missing") if value is None else (-1, "invalid") + label = _match_label(text, _UP_MOOD_WORDS, _DOWN_MOOD_WORDS) + if label == "up": + return 1, "up" + if label == "down": + return -1, "down" + return 0, "neutral" + + +def _schedule_signal(value: Any) -> tuple[int, str]: + text = _extract_text(value, keys=("schedule", "activity", "phase", "status", "title", "label")) + if text is None: + return (0, "missing") if value is None else (-1, "invalid") + label = _match_label(text, _UP_SCHEDULE_WORDS, _DOWN_SCHEDULE_WORDS) + if label == "up": + return 1, "open" + if label == "down": + return -1, "constrained" + return 0, "ordinary" + + +def _context_signal(value: Any) -> tuple[int, str]: + texts = list(_extract_texts(value, keys=("context", "cue", "cues", "intent", "text", "message"))) + if value is None: + return 0, "missing" + if not texts: + return -1, "invalid" + text = " ".join(texts).lower() + if _contains_any(text, _SECURITY_CONTEXT_WORDS): + return -2, "security_boundary" + if _contains_any(text, _BOUNDARY_CONTEXT_WORDS): + return -1, "boundary" + if _contains_any(text, _NEGATIVE_CONTEXT_WORDS): + return -1, "down" + if _contains_any(text, _POSITIVE_CONTEXT_WORDS): + return 1, "up" + return 0, "ordinary" + + +def _extract_text(value: Any, *, keys: Iterable[str]) -> str | None: + if type(value) is str: + return value[:512] + if type(value) is dict: + for key in keys: + candidate = value.get(key) + if type(candidate) is str: + return candidate[:512] + return None + return None + + +def _extract_texts(value: Any, *, keys: Iterable[str]) -> Iterable[str]: + if type(value) is str: + return (value[:512],) + if type(value) is dict: + found: list[str] = [] + for key in keys: + candidate = value.get(key) + if type(candidate) is str: + found.append(candidate[:512]) + elif type(candidate) is list: + found.extend(item[:256] for item in candidate if type(item) is str) + return tuple(found[:8]) + if type(value) is list: + return tuple(item[:256] for item in value[:8] if type(item) is str) + return () + + +def _match_label(text: str, positive: frozenset[str], negative: frozenset[str]) -> str: + normalized = text.lower() + if _contains_any(normalized, negative): + return "down" + if _contains_any(normalized, positive): + return "up" + return "neutral" + + +def _contains_any(text: str, words: Iterable[str]) -> bool: + return any(word in text for word in words) + + +def _instruction_for(tier: str) -> str: + return { + "guarded": "保持简短、尊重边界,不主动扩展。", + "neutral": "保持自然、克制的交流。", + "warm": "可以温和回应,保持尊重与分寸。", + "close": "可以更亲近地回应,但保持尊重与分寸。", + }[tier] + + +__all__ = ["REPLY_TEMPERATURE_TIERS", "compose_reply_temperature"] diff --git a/tests/test_ops_status_projection.py b/tests/test_ops_status_projection.py index 7ec4687..8ce4e8d 100644 --- a/tests/test_ops_status_projection.py +++ b/tests/test_ops_status_projection.py @@ -135,6 +135,21 @@ class OpsStatusProjectionTests(unittest.TestCase): class OpsStatusPageWiringTests(unittest.TestCase): + def test_relationship_panel_and_final_temperature_wiring_are_present(self) -> None: + page_api = (ROOT / "page_api.py").read_text(encoding="utf-8") + users_api = (ROOT / "page_api_users_groups.py").read_text(encoding="utf-8") + app_js = (ROOT / "pages" / "陪伴面板" / "app.js").read_text(encoding="utf-8") + main_py = (ROOT / "main.py").read_text(encoding="utf-8") + + self.assertIn('"relationship_panel"', users_api) + self.assertIn("def _relationship_panel", page_api) + self.assertIn("function renderRelationshipPanel", app_js) + self.assertIn("最终回复温度", app_js) + self.assertIn("关系网节点", app_js) + self.assertIn("compose_reply_temperature(", main_py) + self.assertIn("p4_cap", main_py) + self.assertNotIn("relationship_score", app_js[app_js.index("function renderUserDetail"):app_js.index("function renderPrivateDeliveryRoute")]) + 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") diff --git a/tests/test_reply_temperature.py b/tests/test_reply_temperature.py new file mode 100644 index 0000000..e34ad6a --- /dev/null +++ b/tests/test_reply_temperature.py @@ -0,0 +1,92 @@ +from __future__ import annotations + +from copy import deepcopy +from pathlib import Path +import sys +import unittest + + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from reply_temperature import compose_reply_temperature # noqa: E402 + + +class ReplyTemperatureTests(unittest.TestCase): + def test_p4_is_a_hard_cap(self) -> None: + result = compose_reply_temperature( + "neutral", + energy=100, + mood="开心", + schedule="空闲", + context="谢谢你,想你", + ) + self.assertEqual("neutral", result["tier"]) + self.assertEqual("neutral", result["cap_tier"]) + self.assertIn("p4_cap_applied", result["codes"]) + + def test_guarded_and_invalid_p4_cannot_be_upgraded(self) -> None: + for p4_tier in ("guarded", "unknown", None, 3): + result = compose_reply_temperature( + p4_tier, + energy=100, + mood=100, + schedule="空闲", + context="谢谢你", + ) + self.assertEqual("guarded", result["tier"]) + self.assertEqual("guarded", result["cap_tier"]) + + def test_low_energy_and_boundary_context_reduce_temperature(self) -> None: + result = compose_reply_temperature( + "close", + energy=10, + mood="疲惫", + schedule="睡觉", + context="不用回复,晚安", + ) + self.assertEqual("guarded", result["tier"]) + self.assertEqual(-1, result["context_adjustment"]) + self.assertEqual("low", result["signals"]["energy"]) + self.assertEqual("boundary", result["signals"]["context"]) + + def test_positive_state_and_context_can_raise_within_cap(self) -> None: + result = compose_reply_temperature( + "close", + energy=95, + mood="开心", + schedule="空闲", + context="谢谢你,想你", + ) + self.assertEqual("close", result["tier"]) + self.assertEqual("up", result["signals"]["context"]) + self.assertGreaterEqual(result["score"], 0.0) + self.assertLessEqual(result["score"], 1.0) + + def test_malformed_advisory_inputs_do_not_raise_or_upgrade(self) -> None: + result = compose_reply_temperature( + "warm", + energy=object(), + mood={"bad": object()}, + schedule=object(), + context=object(), + ) + self.assertEqual("guarded", result["tier"]) + self.assertEqual("invalid", result["signals"]["context"]) + + def test_inputs_are_not_mutated_and_output_is_json_shaped(self) -> None: + payload = { + "mood": "开心", + "schedule": "空闲", + "cues": ["谢谢你"], + } + before = deepcopy(payload) + result = compose_reply_temperature("warm", energy=85, mood=payload, schedule=payload, context=payload) + self.assertEqual(before, payload) + self.assertIsInstance(result["signals"], dict) + self.assertIsInstance(result["codes"], list) + self.assertTrue(all(isinstance(code, str) for code in result["codes"])) + self.assertIsInstance(result["instruction"], str) + + +if __name__ == "__main__": + unittest.main()