feat(memory): consume companion expression decisions
这个提交存在于:
父节点
a747cdd095
当前提交
67c3d2d756
共有 8 个文件被更改,包括 449 次插入 和 120 次删除
106
core/bridge.py
106
core/bridge.py
|
|
@ -25,6 +25,98 @@ _COMPANION_RELATIONSHIP_PHASES = {
|
|||
"intimate",
|
||||
"deeply_bonded",
|
||||
}
|
||||
_COMPANION_INTERACTION_BANDS = {
|
||||
"avoidant",
|
||||
"hurt",
|
||||
"relaxed",
|
||||
"lively",
|
||||
"warm",
|
||||
"close",
|
||||
"affectionate",
|
||||
}
|
||||
_COMPANION_EXPRESSION_CONTRACT = "companion_interaction_expression.v1"
|
||||
_COMPANION_EXPRESSION_BEHAVIORS = {
|
||||
"acknowledge",
|
||||
"brief_reply",
|
||||
"give_space",
|
||||
"reply",
|
||||
"clarify",
|
||||
"light_humor",
|
||||
"followup",
|
||||
"support",
|
||||
"shared_ritual",
|
||||
"affectionate_expression",
|
||||
}
|
||||
_COMPANION_EXPRESSION_SAFETY_MODES = {
|
||||
"normal",
|
||||
"contact_boundary_passive",
|
||||
"contact_boundary",
|
||||
"p4_blocked",
|
||||
}
|
||||
_COMPANION_EXPRESSION_BLOCKERS = {"contact_boundary", "p4_safety"}
|
||||
_COMPANION_EXPRESSION_REASON_CODES = {
|
||||
"relationship_baseline_retained",
|
||||
"interaction_band_applied",
|
||||
"administrator_override_applied",
|
||||
"owner_role_required",
|
||||
"contact_boundary_passive_reengagement",
|
||||
"p4_warmth_cap_applied",
|
||||
"relationship_tone_applied",
|
||||
"relationship_address_applied",
|
||||
"relationship_followup_cap",
|
||||
"intent_followup_suppressed",
|
||||
"low_energy_expression_cap",
|
||||
"down_mood_expression_cap",
|
||||
"up_mood_expression_lift",
|
||||
"relationship_proactive_cap",
|
||||
"interaction_proactive_suppressed",
|
||||
"schedule_proactive_suppressed",
|
||||
"p4_blocked",
|
||||
"contact_boundary",
|
||||
}
|
||||
|
||||
|
||||
def sanitize_companion_expression_decision(value: Any) -> dict[str, Any]:
|
||||
"""Accept only the bounded, request-scoped Companion expression contract."""
|
||||
|
||||
fallback = {"status": "invalid", "read_only": True, "decision": {}}
|
||||
if type(value) is not dict or value.get("contract") != _COMPANION_EXPRESSION_CONTRACT:
|
||||
return fallback
|
||||
expression_band = value.get("expression_band")
|
||||
if type(expression_band) is not str or expression_band not in _COMPANION_INTERACTION_BANDS:
|
||||
return fallback
|
||||
allowed_behaviors = value.get("allowed_behaviors")
|
||||
if type(allowed_behaviors) not in {list, tuple} or len(allowed_behaviors) > 12:
|
||||
return fallback
|
||||
if any(type(item) is not str or item not in _COMPANION_EXPRESSION_BEHAVIORS for item in allowed_behaviors):
|
||||
return fallback
|
||||
if len(set(allowed_behaviors)) != len(allowed_behaviors):
|
||||
return fallback
|
||||
safety_mode = value.get("safety_mode")
|
||||
if type(safety_mode) is not str or safety_mode not in _COMPANION_EXPRESSION_SAFETY_MODES:
|
||||
return fallback
|
||||
blocker = value.get("blocker")
|
||||
if blocker is not None and (type(blocker) is not str or blocker not in _COMPANION_EXPRESSION_BLOCKERS):
|
||||
return fallback
|
||||
reason_codes = value.get("reason_codes")
|
||||
if type(reason_codes) not in {list, tuple} or len(reason_codes) > 24:
|
||||
return fallback
|
||||
if any(type(item) is not str or item not in _COMPANION_EXPRESSION_REASON_CODES for item in reason_codes):
|
||||
return fallback
|
||||
if type(value.get("followup")) is not bool:
|
||||
return fallback
|
||||
return {
|
||||
"status": "accepted",
|
||||
"read_only": True,
|
||||
"decision": {
|
||||
"contract": _COMPANION_EXPRESSION_CONTRACT,
|
||||
"expression_band": expression_band,
|
||||
"allowed_behaviors": list(allowed_behaviors),
|
||||
"safety_mode": safety_mode,
|
||||
"blocker": blocker,
|
||||
"reason_codes": list(reason_codes),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def sanitize_companion_relationship_projection(value: Any) -> dict[str, Any]:
|
||||
|
|
@ -68,6 +160,20 @@ def sanitize_companion_relationship_projection(value: Any) -> dict[str, Any]:
|
|||
)
|
||||
},
|
||||
}
|
||||
relationship_mode = value.get("relationship_mode")
|
||||
if relationship_mode in {"normal", "owner_exclusive"}:
|
||||
projection["relationship_mode"] = relationship_mode
|
||||
current_interaction = value.get("current_interaction")
|
||||
if type(current_interaction) is dict:
|
||||
expression_band = current_interaction.get("expression_band")
|
||||
if type(expression_band) is str and expression_band in _COMPANION_INTERACTION_BANDS:
|
||||
projection["current_interaction"] = {
|
||||
"expression_band": expression_band,
|
||||
"label": clean_text(current_interaction.get("label"), 40),
|
||||
"source": clean_text(current_interaction.get("source"), 40),
|
||||
"reason": clean_text(current_interaction.get("reason"), 120),
|
||||
"manual_override": current_interaction.get("manual_override") is True,
|
||||
}
|
||||
return {"status": "accepted", "read_only": True, "projection": projection}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -642,7 +642,7 @@ class InjectionComposer:
|
|||
scar = 0.0
|
||||
hints: list[str] = []
|
||||
if phase and phase != "neutral":
|
||||
hints.append(f"关系阶段={phase}")
|
||||
hints.append(f"当时关系情境={phase}")
|
||||
if scar >= 0.45:
|
||||
hints.append("伤痕感=高")
|
||||
try:
|
||||
|
|
|
|||
|
|
@ -84,6 +84,12 @@ class SessionContext:
|
|||
companion_relationship_phase_label: str = ""
|
||||
companion_relationship_tone: str = ""
|
||||
companion_relationship_address_level: str = ""
|
||||
companion_expression_contract: str = ""
|
||||
companion_expression_band: str = ""
|
||||
companion_expression_allowed_behaviors: tuple[str, ...] = ()
|
||||
companion_expression_safety_mode: str = ""
|
||||
companion_expression_blocker: str = ""
|
||||
companion_expression_reason_codes: tuple[str, ...] = ()
|
||||
|
||||
@property
|
||||
def current_target_id(self) -> str:
|
||||
|
|
|
|||
|
|
@ -23,7 +23,11 @@ from .astrbot_compat import (
|
|||
remove_temp_text,
|
||||
sanitize_request_history,
|
||||
)
|
||||
from .bridge import sanitize_companion_relationship_projection, serialize_memory
|
||||
from .bridge import (
|
||||
sanitize_companion_expression_decision,
|
||||
sanitize_companion_relationship_projection,
|
||||
serialize_memory,
|
||||
)
|
||||
from .bot_personal_dto import (
|
||||
BotPersonalArchiveDTO,
|
||||
BotPersonalValidationError,
|
||||
|
|
@ -388,6 +392,7 @@ class MemoryCompanionService:
|
|||
ctx = await self.identity.resolve_event_context(event)
|
||||
self._sanitize_session_context_message_text(ctx)
|
||||
self._apply_companion_relationship_projection(ctx, event=event, req=req)
|
||||
self._apply_companion_expression_decision(ctx, event=event, req=req)
|
||||
self._apply_private_companion_preferred_address(ctx, req=req, event=event)
|
||||
if self._private_companion_internal_generation_event(event):
|
||||
return
|
||||
|
|
@ -733,6 +738,34 @@ class MemoryCompanionService:
|
|||
or getattr(event, "_private_companion_preferred_address_locked", False)
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _apply_companion_expression_decision(
|
||||
ctx: SessionContext,
|
||||
*,
|
||||
event: Any = None,
|
||||
req: Any = None,
|
||||
) -> None:
|
||||
if ctx.scope != "private":
|
||||
return
|
||||
raw_decision: Any = None
|
||||
for target in (req, event):
|
||||
if target is None:
|
||||
continue
|
||||
candidate = getattr(target, "_private_companion_expression_decision", None)
|
||||
if candidate is not None:
|
||||
raw_decision = candidate
|
||||
break
|
||||
consumed = sanitize_companion_expression_decision(raw_decision)
|
||||
decision = consumed.get("decision") if isinstance(consumed, dict) else None
|
||||
if not isinstance(decision, dict):
|
||||
return
|
||||
ctx.companion_expression_contract = clean_text(decision.get("contract"), 80)
|
||||
ctx.companion_expression_band = clean_text(decision.get("expression_band"), 40)
|
||||
ctx.companion_expression_allowed_behaviors = tuple(decision.get("allowed_behaviors") or ())
|
||||
ctx.companion_expression_safety_mode = clean_text(decision.get("safety_mode"), 60)
|
||||
ctx.companion_expression_blocker = clean_text(decision.get("blocker"), 60)
|
||||
ctx.companion_expression_reason_codes = tuple(decision.get("reason_codes") or ())
|
||||
|
||||
def _sanitize_visible_timeline_text(self, text: Any) -> str:
|
||||
cleaned = clean_text(text, 1200)
|
||||
if not cleaned:
|
||||
|
|
@ -7117,6 +7150,9 @@ class MemoryCompanionService:
|
|||
return "uncertain", "low_confidence"
|
||||
text = clean_text(query_text or ctx.message_text, 800)
|
||||
explicit_memory = self._message_is_contextual_memory_request(text) or self._message_requests_temporal_aggregate(text)
|
||||
companion_cap_reason = self._companion_memory_mention_cap(ctx, explicit_memory=explicit_memory)
|
||||
if companion_cap_reason:
|
||||
return "tone", companion_cap_reason
|
||||
short_rest_check = self._message_is_short_rest_check(text)
|
||||
metadata = memory.metadata if isinstance(memory.metadata, dict) else {}
|
||||
mention_policy = clean_text(metadata.get("mention_policy"), 60)
|
||||
|
|
@ -7185,6 +7221,23 @@ class MemoryCompanionService:
|
|||
return "tone", "indirect_memory"
|
||||
return "mention", "direct_relevance"
|
||||
|
||||
@staticmethod
|
||||
def _companion_memory_mention_cap(ctx: SessionContext, *, explicit_memory: bool) -> str:
|
||||
"""Return a reason when Companion limits unsolicited memory expression."""
|
||||
|
||||
if explicit_memory or ctx.scope != "private" or not ctx.companion_expression_contract:
|
||||
return ""
|
||||
if ctx.companion_expression_blocker:
|
||||
return "companion_expression:blocker"
|
||||
if ctx.companion_expression_safety_mode != "normal":
|
||||
return f"companion_expression:safety_{ctx.companion_expression_safety_mode}"
|
||||
if ctx.companion_expression_band in {"avoidant", "hurt"}:
|
||||
return f"companion_expression:band_{ctx.companion_expression_band}"
|
||||
mention_capable = {"support", "followup", "shared_ritual"}
|
||||
if not mention_capable.intersection(ctx.companion_expression_allowed_behaviors):
|
||||
return "companion_expression:behavior_cap"
|
||||
return ""
|
||||
|
||||
def _memory_age_days(self, memory: MemoryRecord) -> float | None:
|
||||
timestamp = clean_text(memory.occurred_at or memory.updated_at or memory.created_at, 80)
|
||||
parsed = self._parse_utc_datetime(timestamp)
|
||||
|
|
@ -7930,6 +7983,11 @@ class MemoryCompanionService:
|
|||
message_id = clean_text(message_id or ctx.message_id, 160)
|
||||
if not message_id:
|
||||
return False
|
||||
if (
|
||||
ctx.relationship_authority_source == "private_companion.relationship_score"
|
||||
or ctx.companion_expression_contract
|
||||
):
|
||||
return False
|
||||
state = self._get_relationship_phase(ctx)
|
||||
recent_ids = state.get("recent_touch_message_ids")
|
||||
if not isinstance(recent_ids, list):
|
||||
|
|
@ -7954,12 +8012,7 @@ class MemoryCompanionService:
|
|||
recent_ids.append(message_id)
|
||||
state["recent_touch_message_ids"] = recent_ids[-self._RELATIONSHIP_TOUCH_HISTORY_LIMIT :]
|
||||
state["updated_at"] = utc_now()
|
||||
if ctx.relationship_authority_source == "private_companion.relationship_score":
|
||||
state["companion_phase_key"] = clean_text(ctx.companion_relationship_phase_key, 40)
|
||||
state["companion_phase_label"] = clean_text(ctx.companion_relationship_phase_label, 40)
|
||||
state["phase_authority"] = "private_companion.relationship_score"
|
||||
else:
|
||||
self._maybe_transition_phase(ctx, state)
|
||||
self._maybe_transition_phase(ctx, state)
|
||||
self._save_relationship_phase_state()
|
||||
return True
|
||||
|
||||
|
|
@ -8034,6 +8087,11 @@ class MemoryCompanionService:
|
|||
|
||||
def _update_address_evolution(self, ctx: SessionContext, text: str) -> None:
|
||||
"""Track address evolution in the relationship phase state."""
|
||||
if (
|
||||
ctx.relationship_authority_source == "private_companion.relationship_score"
|
||||
or ctx.companion_expression_contract
|
||||
):
|
||||
return
|
||||
phase = self._detect_address_phase(text)
|
||||
if not phase:
|
||||
return
|
||||
|
|
@ -8068,6 +8126,8 @@ class MemoryCompanionService:
|
|||
"不必每句都带称呼;关系阶段建议、历史称呼、显示名和旧记忆只作识别资料,"
|
||||
"不能另造或追加亲昵称呼。若对方本轮明确要求改称呼,以本轮最新要求为准。"
|
||||
)
|
||||
if ctx.companion_expression_contract:
|
||||
return ""
|
||||
if ctx.relationship_authority_source == "private_companion.relationship_score":
|
||||
label = clean_text(ctx.companion_relationship_phase_label, 40) or clean_text(
|
||||
ctx.companion_relationship_phase_key,
|
||||
|
|
|
|||
51
page_api.py
51
page_api.py
|
|
@ -339,10 +339,10 @@ class PluginPageApi:
|
|||
return self._err(f"历史对话导入回滚失败: {exc}", 500)
|
||||
|
||||
async def persona_state(self):
|
||||
"""Return persona state: relationship phases, emotional events, address evolution, cross-window state."""
|
||||
"""Return read-only expression coordination and memory-touch diagnostics."""
|
||||
try:
|
||||
service = self.plugin.service
|
||||
phases: list[dict[str, Any]] = []
|
||||
touch_trends: list[dict[str, Any]] = []
|
||||
phase_state = getattr(service, "_relationship_phase_state", None)
|
||||
if isinstance(phase_state, dict):
|
||||
for key, state in phase_state.items():
|
||||
|
|
@ -358,19 +358,19 @@ class PluginPageApi:
|
|||
member_id = clean_text(identity.get("member_id"), 120)
|
||||
if member_id:
|
||||
identity_parts.append(f"member={member_id}")
|
||||
phases.append({
|
||||
raw_momentum = state.get("momentum", 0.0)
|
||||
momentum = float(raw_momentum) if type(raw_momentum) in {int, float} else 0.0
|
||||
trend_band = "rising" if momentum >= 0.08 else "cooling" if momentum <= -0.08 else "steady"
|
||||
touch_trends.append({
|
||||
"session_key": key,
|
||||
"session_label": " / ".join(part for part in identity_parts if part) or key,
|
||||
"phase": state.get("phase", "acquaintance"),
|
||||
"momentum": round(state.get("momentum", 0.0), 3),
|
||||
"trend_band": trend_band,
|
||||
"touch_count": state.get("touch_count", 0),
|
||||
"last_transition_at": state.get("last_transition_at", ""),
|
||||
"legacy_context": clean_text(state.get("phase"), 40),
|
||||
"updated_at": state.get("updated_at", ""),
|
||||
"current_address_phase": state.get("current_address_phase", ""),
|
||||
"address_log": (state.get("address_log") or [])[-5:],
|
||||
})
|
||||
phases.sort(key=lambda p: p.get("updated_at", ""), reverse=True)
|
||||
pending_emotional_events: list[dict[str, Any]] = []
|
||||
touch_trends.sort(key=lambda item: item.get("updated_at", ""), reverse=True)
|
||||
memory_touch_events: list[dict[str, Any]] = []
|
||||
event_queue = getattr(service, "_emotional_event_queue", None)
|
||||
if isinstance(event_queue, dict):
|
||||
for session_id, queue in event_queue.items():
|
||||
|
|
@ -379,7 +379,7 @@ class PluginPageApi:
|
|||
for event in queue[-3:]:
|
||||
if not isinstance(event, dict):
|
||||
continue
|
||||
pending_emotional_events.append({
|
||||
memory_touch_events.append({
|
||||
"session_id": session_id,
|
||||
"event_type": event.get("event_type"),
|
||||
"energy_delta": event.get("energy_delta"),
|
||||
|
|
@ -393,24 +393,18 @@ class PluginPageApi:
|
|||
cross_window_state: dict[str, Any] = {"total": 0, "scar_count": 0, "warm_count": 0, "vulnerable_count": 0}
|
||||
if hasattr(service, "_get_cross_window_emotional_state"):
|
||||
cross_window_state = service._get_cross_window_emotional_state()
|
||||
phases_list = getattr(service, "_PHASES", ["acquaintance", "familiar", "close", "intimate", "deeply_bonded"])
|
||||
thresholds = getattr(service, "_PHASE_THRESHOLDS", [0.0, 0.20, 0.45, 0.65, 0.85])
|
||||
bot_suggestions = getattr(service, "_BOT_ADDRESS_SUGGESTIONS", {})
|
||||
return self._ok({
|
||||
"phases": phases[:20],
|
||||
"pending_emotional_events": pending_emotional_events[:15],
|
||||
"expression_coordination": {
|
||||
"contract": "companion_interaction_expression.v1",
|
||||
"mode": "request_scoped_read_only",
|
||||
"expression_authority": "private_companion",
|
||||
"memory_role": "recall_visibility_and_mention_cap",
|
||||
"persistent": False,
|
||||
},
|
||||
"memory_touch_trends": touch_trends[:20],
|
||||
"memory_touch_events": memory_touch_events[:15],
|
||||
"time_of_day": time_of_day,
|
||||
"phase_definitions": {
|
||||
"phases": phases_list,
|
||||
"thresholds": thresholds,
|
||||
},
|
||||
"cross_window_emotional_state": cross_window_state,
|
||||
"address_phase_labels": {
|
||||
"formal": "正式",
|
||||
"casual": "随意",
|
||||
"intimate": "亲密",
|
||||
"playful": "玩笑",
|
||||
},
|
||||
"time_of_day_labels": {
|
||||
"late_night": "深夜",
|
||||
"dawn": "凌晨",
|
||||
|
|
@ -419,8 +413,7 @@ class PluginPageApi:
|
|||
"evening": "傍晚",
|
||||
"night": "夜间",
|
||||
},
|
||||
"bot_address_suggestions": bot_suggestions,
|
||||
"phase_labels": {
|
||||
"legacy_context_labels": {
|
||||
"acquaintance": "初识",
|
||||
"familiar": "熟悉",
|
||||
"close": "亲近",
|
||||
|
|
@ -429,7 +422,7 @@ class PluginPageApi:
|
|||
},
|
||||
})
|
||||
except Exception as exc:
|
||||
return self._err(f"拟人维度数据读取失败: {exc}", 500)
|
||||
return self._err(f"互动协同数据读取失败: {exc}", 500)
|
||||
|
||||
async def acl_matrix(self):
|
||||
"""Return all windows, ACL rules and policies in one shot for topology visualization."""
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ const PAGE_ENDPOINT_PREFIX = "page";
|
|||
const TRANSPARENT_IMAGE = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
|
||||
|
||||
const VIEWS = {
|
||||
objects: { title: "知识图谱", hint: "查看关系边、跨窗口线程、时间线、记忆节点和拟人维度概览。" },
|
||||
objects: { title: "知识图谱", hint: "查看关系边、跨窗口线程、时间线、记忆节点和互动协同概览。" },
|
||||
film: { title: "群聊记忆", hint: "查看群聊范围内可召回、可管理的结构化记忆。" },
|
||||
microscope: { title: "记忆显微镜", hint: "对比全库管理检索与指定会话中的实际召回和过滤。" },
|
||||
relations: { title: "用户记忆", hint: "聚焦用户画像、偏好、称呼和关系声明。" },
|
||||
|
|
@ -36,7 +36,7 @@ const SECONDARY_NAV = {
|
|||
{ id: "relations", label: "图谱边", sublabel: "人物、话题、事实与记忆关联", badge: "图谱" },
|
||||
{ id: "threads", label: "跨窗口线程", sublabel: "不同私聊/群聊之间的待办线索", badge: "线程" },
|
||||
{ id: "timeline", label: "时间线", sublabel: "最近记录的事件节点", badge: "时间" },
|
||||
{ id: "persona", label: "拟人维度", sublabel: "关系阶段 · 情绪连续性 · 称呼演进", badge: "拟人" },
|
||||
{ id: "persona", label: "互动协同", sublabel: "表达权威 · 记忆触动 · 情绪连续性", badge: "协同" },
|
||||
],
|
||||
microscope: [
|
||||
{ id: "query", label: "召回测试", sublabel: "输入一句话模拟检索", badge: "测试" },
|
||||
|
|
@ -4445,7 +4445,7 @@ function renderMemoryStructuredMetadata(memory) {
|
|||
<div class="memory-diagnostics-grid">
|
||||
${policy ? `<span><em>策略</em><strong>${escapeHtml(mentionPolicyLabel(policy))}</strong></span>` : ""}
|
||||
${mentionability !== undefined && mentionability !== null ? `<span><em>可提及性</em><strong>${escapeHtml(percentLabel(mentionability))}</strong></span>` : ""}
|
||||
${phase ? `<span><em>关系阶段</em><strong>${escapeHtml(phase)}</strong></span>` : ""}
|
||||
${phase ? `<span><em>当时关系情境</em><strong>${escapeHtml(phase)}</strong></span>` : ""}
|
||||
${decayMode ? `<span><em>衰减</em><strong>${escapeHtml(decayModeLabel(decayMode))}</strong></span>` : ""}
|
||||
${feedback.last_reaction ? `<span><em>上次反馈</em><strong>${escapeHtml(reactionLabel(feedback.last_reaction))}</strong></span>` : ""}
|
||||
</div>
|
||||
|
|
@ -5718,7 +5718,7 @@ function renderHistoricalChatStatus(result) {
|
|||
<span>重要事件 ${number(memoryCounts.important_event)}</span>
|
||||
<span>日摘要 ${number(memoryCounts.daily_digest)}</span>
|
||||
<span>稳定事实 ${number(memoryCounts.stable_fact)}</span>
|
||||
<span>阶段摘要 ${number(memoryCounts.relationship_phase_summary)}</span>
|
||||
<span>相处经历摘要 ${number(memoryCounts.relationship_phase_summary)}</span>
|
||||
</div>
|
||||
` : ""}
|
||||
${batch.stats?.embedding?.enabled ? `<small class="chat-import-embedding-note">向量索引 ${number(batch.stats.embedding.indexed)}/${number(batch.stats.embedding.eligible)} · ${escapeHtml(batch.stats.embedding.status || "处理中")}</small>` : ""}
|
||||
|
|
@ -6186,7 +6186,7 @@ function bindActions() {
|
|||
async function loadPersonaState() {
|
||||
const panel = $("#personaStatePanel");
|
||||
if (!panel) return;
|
||||
panel.innerHTML = `<div class="persona-loading">正在读取拟人维度数据...</div>`;
|
||||
panel.innerHTML = `<div class="persona-loading">正在读取互动协同数据...</div>`;
|
||||
let data;
|
||||
try {
|
||||
data = await apiGet("/persona-state");
|
||||
|
|
@ -6198,17 +6198,13 @@ async function loadPersonaState() {
|
|||
}
|
||||
|
||||
function renderPersonaState(d) {
|
||||
const phases = d.phases || [];
|
||||
const events = d.pending_emotional_events || [];
|
||||
const coordination = d.expression_coordination || {};
|
||||
const trends = d.memory_touch_trends || [];
|
||||
const events = d.memory_touch_events || [];
|
||||
const crossState = d.cross_window_emotional_state || {};
|
||||
const timeOfDay = d.time_of_day || "";
|
||||
const phaseLabels = d.phase_labels || {};
|
||||
const addressLabels = d.address_phase_labels || {};
|
||||
const legacyLabels = d.legacy_context_labels || {};
|
||||
const timeLabels = d.time_of_day_labels || {};
|
||||
const botAddress = d.bot_address_suggestions || {};
|
||||
const phaseDefs = d.phase_definitions || {};
|
||||
const allPhases = phaseDefs.phases || ["acquaintance", "familiar", "close", "intimate", "deeply_bonded"];
|
||||
const thresholds = phaseDefs.thresholds || [0.0, 0.20, 0.45, 0.65, 0.85];
|
||||
|
||||
const timeLabel = timeLabels[timeOfDay] || timeOfDay || "未知";
|
||||
const crossTotal = crossState.total || 0;
|
||||
|
|
@ -6218,7 +6214,26 @@ function renderPersonaState(d) {
|
|||
|
||||
let html = '<div class="persona-grid">';
|
||||
|
||||
// 1. Time-of-day and cross-window summary card
|
||||
html += `
|
||||
<div class="persona-card persona-card-wide">
|
||||
<div class="persona-card-head">
|
||||
<b>陪伴表达协同状态</b>
|
||||
<span class="persona-badge">只读</span>
|
||||
</div>
|
||||
<div class="persona-card-body">
|
||||
<div class="persona-cross-window">
|
||||
<span class="persona-cw-label">最终语气、称呼、互动档位由陪伴插件统一决定</span>
|
||||
<div class="persona-cw-stats">
|
||||
<span class="persona-cw-stat is-active">${escapeHtml(coordination.contract || "未检测到合同")}</span>
|
||||
<span class="persona-cw-stat">请求级消费</span>
|
||||
<span class="persona-cw-stat">不持久化表达状态</span>
|
||||
</div>
|
||||
<small class="persona-cw-empty">记忆插件只负责事实、可见性、召回和记忆提及上限,不会建立第二套好感度、互动状态或称呼系统。</small>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
html += `
|
||||
<div class="persona-card persona-card-wide">
|
||||
<div class="persona-card-head">
|
||||
|
|
@ -6240,38 +6255,37 @@ function renderPersonaState(d) {
|
|||
</div>
|
||||
`;
|
||||
|
||||
// 2. Relationship phases
|
||||
if (phases.length === 0) {
|
||||
if (trends.length === 0) {
|
||||
html += `
|
||||
<div class="persona-card persona-card-wide">
|
||||
<div class="persona-card-head"><b>关系阶段</b></div>
|
||||
<div class="persona-card-head"><b>记忆触动趋势</b></div>
|
||||
<div class="persona-card-body">
|
||||
<p class="persona-empty">还没有足够的关系互动数据。随着对话积累,关系阶段会自然演进。</p>
|
||||
<p class="persona-empty">暂无历史记忆触动记录。该区域只反映记忆被触动的趋势,不代表当前好感度或互动状态。</p>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
} else {
|
||||
html += `
|
||||
<div class="persona-card persona-card-wide">
|
||||
<div class="persona-card-head"><b>关系阶段演进</b><span class="persona-badge">${phases.length} 个会话</span></div>
|
||||
<div class="persona-card-head"><b>记忆触动趋势</b><span class="persona-badge">${trends.length} 个会话</span></div>
|
||||
<div class="persona-card-body">
|
||||
<div class="persona-phase-list">
|
||||
${phases.map(p => renderPersonaPhaseItem(p, allPhases, thresholds, phaseLabels, addressLabels, botAddress)).join('')}
|
||||
${trends.map(item => renderMemoryTouchTrend(item, legacyLabels)).join('')}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
// 3. Pending emotional events
|
||||
if (events.length > 0) {
|
||||
html += `
|
||||
<div class="persona-card persona-card-wide">
|
||||
<div class="persona-card-head"><b>情绪事件队列</b><span class="persona-badge">${events.length} 条待处理</span></div>
|
||||
<div class="persona-card-head"><b>记忆触动事件</b><span class="persona-badge">${events.length} 条待处理</span></div>
|
||||
<div class="persona-card-body">
|
||||
<div class="persona-event-list">
|
||||
${events.map(e => renderPersonaEventItem(e)).join('')}
|
||||
</div>
|
||||
<small class="persona-cw-empty">这些事件只作为陪伴插件 Bot 心情与精力的输入,最终表达仍由陪伴插件裁决。</small>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
|
@ -6281,80 +6295,38 @@ function renderPersonaState(d) {
|
|||
return html;
|
||||
}
|
||||
|
||||
function renderPersonaPhaseItem(p, allPhases, thresholds, phaseLabels, addressLabels, botAddress) {
|
||||
const phase = p.phase || 'acquaintance';
|
||||
const momentum = p.momentum || 0;
|
||||
const phaseLabel = phaseLabels[phase] || phase;
|
||||
function renderMemoryTouchTrend(p, legacyLabels) {
|
||||
const trend = p.trend_band || 'steady';
|
||||
const trendLabels = { rising: '升温触动', steady: '平稳触动', cooling: '降温触动' };
|
||||
const trendLabel = trendLabels[trend] || trend;
|
||||
const trendPercent = trend === 'rising' ? 82 : trend === 'cooling' ? 24 : 52;
|
||||
const trendClass = trend === 'rising' ? 'is-high' : trend === 'cooling' ? 'is-low' : 'is-mid';
|
||||
const touchCount = p.touch_count || 0;
|
||||
const addressPhase = p.current_address_phase || '';
|
||||
const addressLabel = addressLabels[addressPhase] || '';
|
||||
const legacyContext = p.legacy_context || '';
|
||||
const legacyLabel = legacyLabels[legacyContext] || legacyContext;
|
||||
const updatedAt = p.updated_at || '';
|
||||
const sessionKey = p.session_label || p.session_key || '';
|
||||
const shortSession = sessionKey.length > 40 ? sessionKey.slice(0, 37) + '...' : sessionKey;
|
||||
|
||||
// Find current phase index for progress bar
|
||||
const phaseIdx = allPhases.indexOf(phase);
|
||||
const phasePercent = phaseIdx >= 0 ? ((phaseIdx + 1) / allPhases.length) * 100 : 20;
|
||||
|
||||
// Momentum bar: map [-0.3, 1.0] to [0%, 100%]
|
||||
const momentumPercent = Math.max(0, Math.min(100, ((momentum + 0.3) / 1.3) * 100));
|
||||
const momentumClass = momentum >= 0.45 ? 'is-high' : momentum >= 0.15 ? 'is-mid' : momentum < 0 ? 'is-low' : '';
|
||||
|
||||
// Bot address suggestion
|
||||
const botSuggestion = botAddress[phase] || {};
|
||||
const botTone = botSuggestion.tone || '';
|
||||
const botHint = botSuggestion.hint || '';
|
||||
|
||||
// Address log
|
||||
const addressLog = p.address_log || [];
|
||||
const hasAddressLog = addressLog.length > 0;
|
||||
|
||||
return `
|
||||
<div class="persona-phase-item">
|
||||
<div class="persona-phase-header">
|
||||
<div class="persona-phase-info">
|
||||
<span class="persona-phase-name">${escapeHtml(phaseLabel)}</span>
|
||||
<span class="persona-phase-name">${escapeHtml(trendLabel)}</span>
|
||||
<small class="persona-phase-session">${escapeHtml(shortSession)}</small>
|
||||
</div>
|
||||
<div class="persona-phase-meta">
|
||||
<span class="persona-phase-touch">${touchCount} 次触动</span>
|
||||
${addressLabel ? `<span class="persona-phase-address">称呼:${escapeHtml(addressLabel)}</span>` : ''}
|
||||
</div>
|
||||
</div>
|
||||
<div class="persona-phase-progress">
|
||||
<div class="persona-phase-bar">
|
||||
<div class="persona-phase-bar-fill" style="width:${phasePercent}%"></div>
|
||||
</div>
|
||||
<div class="persona-phase-steps">
|
||||
${allPhases.map((ph, i) => `<span class="persona-phase-step ${i <= phaseIdx ? 'is-active' : ''}">${escapeHtml(phaseLabels[ph] || ph)}</span>`).join('')}
|
||||
${legacyLabel ? `<span class="persona-phase-address">历史情境:${escapeHtml(legacyLabel)}</span>` : ''}
|
||||
</div>
|
||||
</div>
|
||||
<div class="persona-momentum">
|
||||
<span class="persona-momentum-label">动量</span>
|
||||
<span class="persona-momentum-label">触动趋势</span>
|
||||
<div class="persona-momentum-bar">
|
||||
<div class="persona-momentum-fill ${momentumClass}" style="width:${momentumPercent}%"></div>
|
||||
<div class="persona-momentum-fill ${trendClass}" style="width:${trendPercent}%"></div>
|
||||
</div>
|
||||
<span class="persona-momentum-value">${momentum.toFixed(3)}</span>
|
||||
<span class="persona-momentum-value">${escapeHtml(trendLabel)}</span>
|
||||
</div>
|
||||
${botTone ? `
|
||||
<div class="persona-bot-address">
|
||||
<span class="persona-bot-tone">${escapeHtml(botTone)}</span>
|
||||
${botHint ? `<small class="persona-bot-hint">${escapeHtml(botHint)}</small>` : ''}
|
||||
</div>
|
||||
` : ''}
|
||||
${hasAddressLog ? `
|
||||
<details class="persona-address-log">
|
||||
<summary>称呼演变记录 (${addressLog.length})</summary>
|
||||
<div class="persona-address-timeline">
|
||||
${addressLog.map(log => `
|
||||
<div class="persona-address-entry">
|
||||
<span class="persona-address-time">${escapeHtml((log.ts || '').slice(0, 16))}</span>
|
||||
<span class="persona-address-change">${escapeHtml(addressLabels[log.previous] || log.previous || '—')} → ${escapeHtml(addressLabels[log.phase] || log.phase || '')}</span>
|
||||
</div>
|
||||
`).join('')}
|
||||
</div>
|
||||
</details>
|
||||
` : ''}
|
||||
${updatedAt ? `<small class="persona-phase-updated">更新于 ${escapeHtml(updatedAt.slice(0, 16))}</small>` : ''}
|
||||
</div>
|
||||
`;
|
||||
|
|
|
|||
|
|
@ -26,6 +26,14 @@ def valid_projection() -> dict:
|
|||
"tone": "温暖、自然",
|
||||
"address_level": "使用已确认昵称",
|
||||
"proactive_care_limit": 2,
|
||||
"relationship_mode": "owner_exclusive",
|
||||
"current_interaction": {
|
||||
"expression_band": "affectionate",
|
||||
"label": "爱意",
|
||||
"source": "manual",
|
||||
"reason": "administrator_manual_override",
|
||||
"manual_override": True,
|
||||
},
|
||||
"soft_behaviors": {
|
||||
"allow_playful_jokes": True,
|
||||
"allow_followup": True,
|
||||
|
|
@ -45,6 +53,9 @@ class Req027RelationshipAuthorityTests(unittest.TestCase):
|
|||
self.assertEqual("private_companion.relationship_score", accepted["authority"])
|
||||
self.assertTrue(accepted["read_only"])
|
||||
self.assertEqual("close", accepted["phase_key"])
|
||||
self.assertEqual("owner_exclusive", accepted["relationship_mode"])
|
||||
self.assertEqual("affectionate", accepted["current_interaction"]["expression_band"])
|
||||
self.assertTrue(accepted["current_interaction"]["manual_override"])
|
||||
for forbidden in ("owner", "cross_user_query", "p4_bypass"):
|
||||
self.assertNotIn(forbidden, accepted)
|
||||
|
||||
|
|
@ -80,7 +91,7 @@ class Req027RelationshipAuthorityTests(unittest.TestCase):
|
|||
self.assertEqual("", group.relationship_authority_source)
|
||||
self.assertEqual("", group.companion_relationship_phase_key)
|
||||
|
||||
def test_companion_authority_stops_memory_phase_transition_but_keeps_momentum(self) -> None:
|
||||
def test_companion_authority_stops_memory_phase_state_writes(self) -> None:
|
||||
service = MemoryCompanionService.__new__(MemoryCompanionService)
|
||||
state = {
|
||||
"phase": "acquaintance",
|
||||
|
|
@ -108,11 +119,10 @@ class Req027RelationshipAuthorityTests(unittest.TestCase):
|
|||
companion_relationship_phase_key="close",
|
||||
companion_relationship_phase_label="亲近",
|
||||
)
|
||||
self.assertTrue(service._update_relationship_phase_momentum(authoritative, touch_type="warm"))
|
||||
self.assertGreater(state["momentum"], 0)
|
||||
self.assertFalse(service._update_relationship_phase_momentum(authoritative, touch_type="warm"))
|
||||
self.assertEqual(0.0, state["momentum"])
|
||||
self.assertEqual(0, calls["transition"])
|
||||
self.assertEqual("private_companion.relationship_score", state["phase_authority"])
|
||||
self.assertEqual("close", state["companion_phase_key"])
|
||||
self.assertEqual(0, calls["save"])
|
||||
|
||||
fallback = SessionContext(
|
||||
session_id="telegram:FriendMessage:u2",
|
||||
|
|
@ -122,7 +132,7 @@ class Req027RelationshipAuthorityTests(unittest.TestCase):
|
|||
)
|
||||
self.assertTrue(service._update_relationship_phase_momentum(fallback, touch_type="warm"))
|
||||
self.assertEqual(1, calls["transition"])
|
||||
self.assertEqual(2, calls["save"])
|
||||
self.assertEqual(1, calls["save"])
|
||||
|
||||
def test_address_hint_uses_companion_phase_and_memory_declares_trend_only(self) -> None:
|
||||
service = MemoryCompanionService.__new__(MemoryCompanionService)
|
||||
|
|
|
|||
182
tests/test_req028_expression_sync.py
普通文件
182
tests/test_req028_expression_sync.py
普通文件
|
|
@ -0,0 +1,182 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from types import MethodType, SimpleNamespace
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from core.bridge import sanitize_companion_expression_decision
|
||||
from core.models import MemoryRecord, SearchResult, SessionContext
|
||||
from core.service import MemoryCompanionService, MemoryRouteDecision
|
||||
from core.time_intent import TimeIntent
|
||||
|
||||
|
||||
def valid_expression_decision(**updates) -> dict:
|
||||
decision = {
|
||||
"contract": "companion_interaction_expression.v1",
|
||||
"expression_band": "warm",
|
||||
"tone": "gentle",
|
||||
"warmth": 76,
|
||||
"distance": 28,
|
||||
"address_style": "warm",
|
||||
"response_length": "balanced",
|
||||
"followup": True,
|
||||
"initiative": "passive_only",
|
||||
"proactive_budget": 0,
|
||||
"tts_style": "warm",
|
||||
"allowed_behaviors": ["reply", "support", "followup"],
|
||||
"safety_mode": "normal",
|
||||
"blocker": None,
|
||||
"reason_codes": ["interaction_band_applied"],
|
||||
}
|
||||
decision.update(updates)
|
||||
return decision
|
||||
|
||||
|
||||
def memory_item() -> tuple[MemoryRecord, SearchResult]:
|
||||
memory = MemoryRecord(
|
||||
id="mem-1",
|
||||
memory_type="user_profile",
|
||||
scope="private",
|
||||
session_id="qq:FriendMessage:u1",
|
||||
visibility="private",
|
||||
sayability="direct",
|
||||
reality_level="real_user_fact",
|
||||
content="用户的生日是八月一日",
|
||||
confidence=0.95,
|
||||
importance=0.8,
|
||||
metadata={},
|
||||
)
|
||||
return memory, SearchResult(memory=memory, score=1.2, reason="")
|
||||
|
||||
|
||||
class Req028ExpressionSyncTests(unittest.TestCase):
|
||||
def test_expression_contract_is_strict_and_redacted(self) -> None:
|
||||
accepted = sanitize_companion_expression_decision(valid_expression_decision(owner_id="secret"))
|
||||
self.assertEqual("accepted", accepted["status"])
|
||||
self.assertEqual("warm", accepted["decision"]["expression_band"])
|
||||
self.assertNotIn("owner_id", accepted["decision"])
|
||||
|
||||
hostile_values = (
|
||||
valid_expression_decision(contract="companion_interaction_expression.v2"),
|
||||
valid_expression_decision(expression_band="forged"),
|
||||
valid_expression_decision(followup="true"),
|
||||
valid_expression_decision(allowed_behaviors=["reply", "memory_override"]),
|
||||
valid_expression_decision(safety_mode="bypass"),
|
||||
valid_expression_decision(blocker="owner_override"),
|
||||
valid_expression_decision(reason_codes=["unknown_reason"]),
|
||||
)
|
||||
for value in hostile_values:
|
||||
with self.subTest(value=value):
|
||||
self.assertEqual("invalid", sanitize_companion_expression_decision(value)["status"])
|
||||
|
||||
def test_private_context_consumes_request_scoped_decision_and_group_ignores_it(self) -> None:
|
||||
req = SimpleNamespace(_private_companion_expression_decision=valid_expression_decision())
|
||||
private = SessionContext(scope="private", session_id="qq:FriendMessage:u1", user_id="u1")
|
||||
MemoryCompanionService._apply_companion_expression_decision(private, req=req)
|
||||
self.assertEqual("companion_interaction_expression.v1", private.companion_expression_contract)
|
||||
self.assertEqual("warm", private.companion_expression_band)
|
||||
self.assertEqual(("reply", "support", "followup"), private.companion_expression_allowed_behaviors)
|
||||
|
||||
group = SessionContext(scope="group", session_id="qq:GroupMessage:g1", group_id="g1", user_id="u1")
|
||||
MemoryCompanionService._apply_companion_expression_decision(group, req=req)
|
||||
self.assertEqual("", group.companion_expression_contract)
|
||||
self.assertEqual("", group.companion_expression_band)
|
||||
|
||||
def test_companion_caps_unsolicited_mentions_but_explicit_recall_still_reads_fact(self) -> None:
|
||||
service = MemoryCompanionService.__new__(MemoryCompanionService)
|
||||
memory, item = memory_item()
|
||||
route = MemoryRouteDecision()
|
||||
restricted = SessionContext(
|
||||
scope="private",
|
||||
message_text="今天过得怎么样",
|
||||
companion_expression_contract="companion_interaction_expression.v1",
|
||||
companion_expression_band="hurt",
|
||||
companion_expression_allowed_behaviors=("acknowledge", "brief_reply", "give_space"),
|
||||
companion_expression_safety_mode="normal",
|
||||
)
|
||||
expression, reason = service._memory_expression_decision(
|
||||
restricted, memory, item, "user_profile", route, TimeIntent(), query_text=restricted.message_text
|
||||
)
|
||||
self.assertEqual("tone", expression)
|
||||
self.assertEqual("companion_expression:band_hurt", reason)
|
||||
|
||||
restricted.message_text = "你还记得我的生日吗"
|
||||
expression, reason = service._memory_expression_decision(
|
||||
restricted, memory, item, "user_profile", route, TimeIntent(), query_text=restricted.message_text
|
||||
)
|
||||
self.assertEqual("mention", expression)
|
||||
self.assertEqual("stable_user_fact", reason)
|
||||
|
||||
def test_allowed_behaviors_are_a_maximum_not_a_memory_override(self) -> None:
|
||||
service = MemoryCompanionService.__new__(MemoryCompanionService)
|
||||
memory, item = memory_item()
|
||||
route = MemoryRouteDecision()
|
||||
relaxed = SessionContext(
|
||||
scope="private",
|
||||
message_text="随便聊聊",
|
||||
companion_expression_contract="companion_interaction_expression.v1",
|
||||
companion_expression_band="relaxed",
|
||||
companion_expression_allowed_behaviors=("reply", "clarify"),
|
||||
companion_expression_safety_mode="normal",
|
||||
)
|
||||
self.assertEqual(
|
||||
("tone", "companion_expression:behavior_cap"),
|
||||
service._memory_expression_decision(relaxed, memory, item, "user_profile", route, TimeIntent()),
|
||||
)
|
||||
relaxed.companion_expression_band = "warm"
|
||||
relaxed.companion_expression_allowed_behaviors = ("reply", "support")
|
||||
self.assertEqual(
|
||||
("mention", "stable_user_fact"),
|
||||
service._memory_expression_decision(relaxed, memory, item, "user_profile", route, TimeIntent()),
|
||||
)
|
||||
|
||||
def test_paired_mode_does_not_inject_second_tone_or_write_legacy_state(self) -> None:
|
||||
service = MemoryCompanionService.__new__(MemoryCompanionService)
|
||||
ctx = SessionContext(
|
||||
scope="private",
|
||||
session_id="qq:FriendMessage:u1",
|
||||
user_id="u1",
|
||||
message_id="m1",
|
||||
relationship_authority_source="private_companion.relationship_score",
|
||||
companion_expression_contract="companion_interaction_expression.v1",
|
||||
companion_expression_band="warm",
|
||||
companion_expression_allowed_behaviors=("reply", "support"),
|
||||
companion_expression_safety_mode="normal",
|
||||
)
|
||||
calls = {"get": 0, "save": 0}
|
||||
service._get_relationship_phase = MethodType(
|
||||
lambda _self, _ctx: calls.__setitem__("get", calls["get"] + 1) or {}, service
|
||||
)
|
||||
service._save_relationship_phase_state = MethodType(
|
||||
lambda _self: calls.__setitem__("save", calls["save"] + 1), service
|
||||
)
|
||||
self.assertEqual("", service._address_hint_for_injection(ctx))
|
||||
service._update_address_evolution(ctx, "宝贝")
|
||||
self.assertFalse(service._update_relationship_phase_momentum(ctx, touch_type="warm"))
|
||||
self.assertEqual({"get": 0, "save": 0}, calls)
|
||||
|
||||
def test_standalone_fallback_remains_available(self) -> None:
|
||||
service = MemoryCompanionService.__new__(MemoryCompanionService)
|
||||
service._BOT_ADDRESS_SUGGESTIONS = {"acquaintance": {"hint": "standalone address hint"}}
|
||||
service._get_relationship_phase = MethodType(
|
||||
lambda _self, _ctx: {"phase": "acquaintance", "current_address_phase": ""}, service
|
||||
)
|
||||
ctx = SessionContext(scope="private", session_id="qq:FriendMessage:u1", user_id="u1")
|
||||
self.assertEqual("standalone address hint", service._address_hint_for_injection(ctx))
|
||||
|
||||
def test_page_source_exposes_coordination_without_second_relationship_authority(self) -> None:
|
||||
source = (ROOT / "pages" / "记忆面板" / "app.js").read_text(encoding="utf-8")
|
||||
for retired in ("关系阶段演进", "情绪事件队列", "称呼演变记录", "Bot 称呼建议"):
|
||||
self.assertNotIn(retired, source)
|
||||
for required in ("陪伴表达协同状态", "记忆触动趋势", "记忆触动事件", "当时关系情境"):
|
||||
self.assertIn(required, source)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
正在加载…
添加表格
在新工单中引用