比较提交
11 提交
05a200be8e
...
830cd92f4c
| 作者 | SHA1 | 提交日期 | |
|---|---|---|---|
|
|
830cd92f4c | ||
|
|
f55e0644fd | ||
|
|
667963a4b8 | ||
|
|
4a423bac69 | ||
|
|
178428a91e | ||
|
|
60487391d9 | ||
|
|
aa1689038a | ||
|
|
72b6696b79 | ||
|
|
773c064c5c | ||
|
|
b678fe9928 | ||
|
|
80ab1764f1 |
共有 39 个文件被更改,包括 1867 次插入 和 114 次删除
47
affect_modulation.py
普通文件
47
affect_modulation.py
普通文件
|
|
@ -0,0 +1,47 @@
|
||||||
|
"""Compose condition-level affect deltas without creating another state authority."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
try:
|
||||||
|
from .affect_modulation_contract import normalize_affect_modulation
|
||||||
|
except ImportError: # pragma: no cover
|
||||||
|
from affect_modulation_contract import normalize_affect_modulation
|
||||||
|
|
||||||
|
|
||||||
|
def compose_affect_modulation(conditions: list[dict[str, Any]], *, now: float) -> dict[str, Any]:
|
||||||
|
valence = arousal = vulnerability = confidence_total = 0.0
|
||||||
|
source_ids: list[str] = []
|
||||||
|
for condition in conditions[:64]:
|
||||||
|
if not isinstance(condition, dict):
|
||||||
|
continue
|
||||||
|
modulation = normalize_affect_modulation(condition.get("modulation"))
|
||||||
|
confidence = modulation["confidence"]
|
||||||
|
if confidence <= 0:
|
||||||
|
continue
|
||||||
|
start = condition.get("start_ts")
|
||||||
|
half_life = condition.get("half_life_seconds")
|
||||||
|
decay = 1.0
|
||||||
|
if type(start) in {int, float} and type(half_life) in {int, float} and float(half_life) >= 60:
|
||||||
|
decay = 0.5 ** (max(0.0, now - float(start)) / min(86400.0, float(half_life)))
|
||||||
|
weight = confidence * decay
|
||||||
|
valence += modulation["valence"] * weight
|
||||||
|
arousal += modulation["arousal"] * weight
|
||||||
|
vulnerability += modulation["vulnerability"] * weight
|
||||||
|
confidence_total += weight
|
||||||
|
event_id = str(condition.get("source_event_id") or "")[:96]
|
||||||
|
if event_id and event_id not in source_ids:
|
||||||
|
source_ids.append(event_id)
|
||||||
|
divisor = max(1.0, confidence_total)
|
||||||
|
return normalize_affect_modulation({
|
||||||
|
"valence": valence / divisor,
|
||||||
|
"arousal": arousal / divisor,
|
||||||
|
"vulnerability": vulnerability / divisor,
|
||||||
|
"confidence": min(1.0, confidence_total),
|
||||||
|
"source_event_ids": source_ids,
|
||||||
|
"computed_at": now,
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = ["compose_affect_modulation"]
|
||||||
46
affect_modulation_contract.py
普通文件
46
affect_modulation_contract.py
普通文件
|
|
@ -0,0 +1,46 @@
|
||||||
|
"""Bounded affect modulation DTO shared across companion plugins."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import math
|
||||||
|
from typing import Any, Mapping
|
||||||
|
|
||||||
|
AFFECT_MODULATION_VERSION = "affect_modulation.v1"
|
||||||
|
AFFECT_MODULATION_FIELDS = ("schema_version", "valence", "arousal", "vulnerability", "confidence", "source_event_ids", "computed_at")
|
||||||
|
AFFECT_MODULATION_FINGERPRINT = hashlib.sha256("|".join(AFFECT_MODULATION_FIELDS).encode("ascii")).hexdigest()[:20]
|
||||||
|
|
||||||
|
|
||||||
|
def _number(value: Any, default: float, low: float, high: float) -> float:
|
||||||
|
if type(value) not in {int, float}:
|
||||||
|
return default
|
||||||
|
numeric = float(value)
|
||||||
|
if not math.isfinite(numeric):
|
||||||
|
return default
|
||||||
|
return round(max(low, min(high, numeric)), 4)
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_affect_modulation(value: Any) -> dict[str, Any]:
|
||||||
|
source = dict(value) if isinstance(value, Mapping) else {}
|
||||||
|
raw_ids = source.get("source_event_ids")
|
||||||
|
ids: list[str] = []
|
||||||
|
if isinstance(raw_ids, (list, tuple)):
|
||||||
|
for item in raw_ids[:12]:
|
||||||
|
if type(item) is not str:
|
||||||
|
continue
|
||||||
|
cleaned = " ".join(item.split())[:96]
|
||||||
|
if cleaned and cleaned not in ids:
|
||||||
|
ids.append(cleaned)
|
||||||
|
computed_at = source.get("computed_at")
|
||||||
|
return {
|
||||||
|
"schema_version": AFFECT_MODULATION_VERSION,
|
||||||
|
"valence": _number(source.get("valence"), 0.0, -1.0, 1.0),
|
||||||
|
"arousal": _number(source.get("arousal"), 0.0, 0.0, 1.0),
|
||||||
|
"vulnerability": _number(source.get("vulnerability"), 0.0, 0.0, 1.0),
|
||||||
|
"confidence": _number(source.get("confidence"), 0.0, 0.0, 1.0),
|
||||||
|
"source_event_ids": ids,
|
||||||
|
"computed_at": float(computed_at) if type(computed_at) in {int, float} and math.isfinite(float(computed_at)) else 0.0,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = ["AFFECT_MODULATION_FIELDS", "AFFECT_MODULATION_FINGERPRINT", "AFFECT_MODULATION_VERSION", "normalize_affect_modulation"]
|
||||||
|
|
@ -12,8 +12,17 @@ from dataclasses import asdict, dataclass
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
from typing import Any, Mapping
|
from typing import Any, Mapping
|
||||||
|
|
||||||
|
try:
|
||||||
|
from .interaction_dynamics import project_interaction_dynamics
|
||||||
|
except ImportError: # pragma: no cover - direct module import in lightweight tests
|
||||||
|
from interaction_dynamics import project_interaction_dynamics
|
||||||
|
try:
|
||||||
|
from .affect_modulation_contract import normalize_affect_modulation
|
||||||
|
except ImportError: # pragma: no cover
|
||||||
|
from affect_modulation_contract import normalize_affect_modulation
|
||||||
|
|
||||||
EXPRESSION_CONTRACT_VERSION = "companion_interaction_expression.v1"
|
|
||||||
|
EXPRESSION_CONTRACT_VERSION = "companion_interaction_expression.v2"
|
||||||
CONTENT_TIERS = ("normal", "flirt", "adult")
|
CONTENT_TIERS = ("normal", "flirt", "adult")
|
||||||
CONTENT_TIER_LABELS = {"normal": "日常", "flirt": "含蓄暧昧", "adult": "成人私密"}
|
CONTENT_TIER_LABELS = {"normal": "日常", "flirt": "含蓄暧昧", "adult": "成人私密"}
|
||||||
_CONTENT_STAGE_INDEX = {
|
_CONTENT_STAGE_INDEX = {
|
||||||
|
|
@ -90,6 +99,13 @@ class ExpressionDecision:
|
||||||
initiative: str
|
initiative: str
|
||||||
proactive_budget: int
|
proactive_budget: int
|
||||||
tts_style: str
|
tts_style: str
|
||||||
|
affect_modulation: Mapping[str, Any]
|
||||||
|
pacing: str
|
||||||
|
directness: str
|
||||||
|
validation_style: str
|
||||||
|
self_disclosure: str
|
||||||
|
humor_mode: str
|
||||||
|
topic_initiative: str
|
||||||
allowed_behaviors: tuple[str, ...]
|
allowed_behaviors: tuple[str, ...]
|
||||||
safety_mode: str
|
safety_mode: str
|
||||||
blocker: str | None
|
blocker: str | None
|
||||||
|
|
@ -511,6 +527,24 @@ def build_expression_decision(input_data: ExpressionInput | Mapping[str, Any] |
|
||||||
warmth = min(100, warmth + 5)
|
warmth = min(100, warmth + 5)
|
||||||
reasons.append("up_mood_expression_lift")
|
reasons.append("up_mood_expression_lift")
|
||||||
|
|
||||||
|
modulation = normalize_affect_modulation(bot_state.get("affect_modulation"))
|
||||||
|
if modulation["confidence"] > 0:
|
||||||
|
if modulation["valence"] <= -0.35:
|
||||||
|
warmth = max(0, warmth - 3)
|
||||||
|
if tone not in {"reserved", "careful"}:
|
||||||
|
tone = "gentle"
|
||||||
|
elif modulation["valence"] >= 0.35 and band not in {ExpressionBand.AVOIDANT, ExpressionBand.HURT}:
|
||||||
|
warmth = min(100, warmth + 3)
|
||||||
|
if modulation["arousal"] <= 0.2:
|
||||||
|
tts_style = "soft"
|
||||||
|
elif modulation["arousal"] >= 0.7 and not low_energy and not down_mood and band not in {ExpressionBand.AVOIDANT, ExpressionBand.HURT}:
|
||||||
|
tts_style = "bright"
|
||||||
|
if modulation["vulnerability"] >= 0.65:
|
||||||
|
followup = False
|
||||||
|
if tone != "reserved":
|
||||||
|
tone = "careful"
|
||||||
|
reasons.append("affect_modulation_applied")
|
||||||
|
|
||||||
schedule = _mapping(source.get("schedule"))
|
schedule = _mapping(source.get("schedule"))
|
||||||
budget = _candidate_budget(_mapping(source.get("proactive_candidate")))
|
budget = _candidate_budget(_mapping(source.get("proactive_candidate")))
|
||||||
if "proactive_care_limit" in relationship_baseline:
|
if "proactive_care_limit" in relationship_baseline:
|
||||||
|
|
@ -542,6 +576,16 @@ def build_expression_decision(input_data: ExpressionInput | Mapping[str, Any] |
|
||||||
owner_exclusive=owner_exclusive,
|
owner_exclusive=owner_exclusive,
|
||||||
reasons=reasons,
|
reasons=reasons,
|
||||||
)
|
)
|
||||||
|
pacing = "slow" if low_energy or down_mood or modulation["arousal"] <= 0.2 else "bright" if modulation["arousal"] >= 0.7 and band == ExpressionBand.LIVELY else "steady"
|
||||||
|
directness = "indirect" if band in {ExpressionBand.AVOIDANT, ExpressionBand.HURT} else "direct" if band in {ExpressionBand.LIVELY, ExpressionBand.AFFECTIONATE} else "natural"
|
||||||
|
validation_style = "acknowledge" if band in {ExpressionBand.AVOIDANT, ExpressionBand.HURT, ExpressionBand.RELAXED} else "support_first"
|
||||||
|
if modulation["vulnerability"] >= 0.65:
|
||||||
|
validation_style = "support_first"
|
||||||
|
self_disclosure = "allowed" if owner_account and band in {ExpressionBand.CLOSE, ExpressionBand.AFFECTIONATE} else "light" if "shared_ritual" in behaviors else "none"
|
||||||
|
humor_mode = "off"
|
||||||
|
if "light_humor" in behaviors and not low_energy and not down_mood and band not in {ExpressionBand.AVOIDANT, ExpressionBand.HURT}:
|
||||||
|
humor_mode = "playful" if band == ExpressionBand.LIVELY else "light"
|
||||||
|
topic_initiative = "reply_only" if not followup else "shared_topic" if "shared_ritual" in behaviors else "followup"
|
||||||
return ExpressionDecision(
|
return ExpressionDecision(
|
||||||
contract=EXPRESSION_CONTRACT_VERSION,
|
contract=EXPRESSION_CONTRACT_VERSION,
|
||||||
expression_band=band.value,
|
expression_band=band.value,
|
||||||
|
|
@ -556,6 +600,13 @@ def build_expression_decision(input_data: ExpressionInput | Mapping[str, Any] |
|
||||||
initiative=initiative,
|
initiative=initiative,
|
||||||
proactive_budget=budget,
|
proactive_budget=budget,
|
||||||
tts_style=tts_style,
|
tts_style=tts_style,
|
||||||
|
affect_modulation=modulation,
|
||||||
|
pacing=pacing,
|
||||||
|
directness=directness,
|
||||||
|
validation_style=validation_style,
|
||||||
|
self_disclosure=self_disclosure,
|
||||||
|
humor_mode=humor_mode,
|
||||||
|
topic_initiative=topic_initiative,
|
||||||
allowed_behaviors=behaviors,
|
allowed_behaviors=behaviors,
|
||||||
safety_mode="contact_boundary_passive" if contact_boundary else "normal",
|
safety_mode="contact_boundary_passive" if contact_boundary else "normal",
|
||||||
blocker=None,
|
blocker=None,
|
||||||
|
|
@ -580,6 +631,10 @@ def current_interaction_projection(
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
"""Normalize persisted and legacy interaction state for runtime/page use."""
|
"""Normalize persisted and legacy interaction state for runtime/page use."""
|
||||||
raw = dict(value) if isinstance(value, Mapping) else {}
|
raw = dict(value) if isinstance(value, Mapping) else {}
|
||||||
|
current_ts = _bounded_timestamp(now)
|
||||||
|
dynamics = project_interaction_dynamics(raw, now=current_ts) if current_ts else {}
|
||||||
|
if dynamics:
|
||||||
|
raw.update(dynamics)
|
||||||
band = _band_from_interaction(raw) or ExpressionBand.RELAXED
|
band = _band_from_interaction(raw) or ExpressionBand.RELAXED
|
||||||
role = _text(relationship_role)
|
role = _text(relationship_role)
|
||||||
score = _bounded_int(raw.get("relationship_score", relationship_score), 0, -1200, 1200)
|
score = _bounded_int(raw.get("relationship_score", relationship_score), 0, -1200, 1200)
|
||||||
|
|
@ -596,15 +651,14 @@ def current_interaction_projection(
|
||||||
band = normal_cap_band
|
band = normal_cap_band
|
||||||
reason_codes.append("normal_interaction_band_cap_applied")
|
reason_codes.append("normal_interaction_band_cap_applied")
|
||||||
expires_at = _bounded_timestamp(raw.get("expires_at"))
|
expires_at = _bounded_timestamp(raw.get("expires_at"))
|
||||||
current_ts = _bounded_timestamp(now)
|
|
||||||
manual = bool(raw.get("manual_override") or _text(raw.get("source")) == "manual")
|
manual = bool(raw.get("manual_override") or _text(raw.get("source")) == "manual")
|
||||||
if expires_at and current_ts and current_ts >= expires_at:
|
if not dynamics and expires_at and current_ts and current_ts >= expires_at:
|
||||||
band = ExpressionBand.RELAXED
|
band = ExpressionBand.RELAXED
|
||||||
manual = False
|
manual = False
|
||||||
reason_codes.append("interaction_expired")
|
reason_codes.append("interaction_expired")
|
||||||
source = "manual" if manual else _text(raw.get("source")) or "automatic"
|
source = "manual" if manual else _text(raw.get("source")) or "automatic"
|
||||||
reason = str(raw.get("reason") or raw.get("reason_code") or "").replace("\r", " ").replace("\n", " ")[:120]
|
reason = str(raw.get("reason") or raw.get("reason_code") or "").replace("\r", " ").replace("\n", " ")[:120]
|
||||||
return {
|
projection = {
|
||||||
"expression_band": band.value,
|
"expression_band": band.value,
|
||||||
"label": EXPRESSION_BAND_LABELS[band.value],
|
"label": EXPRESSION_BAND_LABELS[band.value],
|
||||||
"source": source,
|
"source": source,
|
||||||
|
|
@ -616,7 +670,22 @@ def current_interaction_projection(
|
||||||
"normal_interaction_band_cap": normal_cap,
|
"normal_interaction_band_cap": normal_cap,
|
||||||
"allowed_bands": list(allowed),
|
"allowed_bands": list(allowed),
|
||||||
"reason_codes": reason_codes,
|
"reason_codes": reason_codes,
|
||||||
|
"last_event_id": _bounded_text(raw.get("last_event_id"), 96),
|
||||||
|
"trace_id": _bounded_text(raw.get("trace_id"), 96),
|
||||||
}
|
}
|
||||||
|
if dynamics:
|
||||||
|
projection.update({
|
||||||
|
"dynamics_version": dynamics["dynamics_version"],
|
||||||
|
"load": dynamics["load"],
|
||||||
|
"peak_intensity": dynamics["peak_intensity"],
|
||||||
|
"decay_started_at": dynamics["decay_started_at"],
|
||||||
|
"half_life": dynamics["half_life"],
|
||||||
|
"recovery_band": dynamics["recovery_band"],
|
||||||
|
"projection_revision": dynamics["projection_revision"],
|
||||||
|
"polarity": dynamics["polarity"],
|
||||||
|
"base_band": dynamics["base_band"],
|
||||||
|
})
|
||||||
|
return projection
|
||||||
|
|
||||||
|
|
||||||
def expression_decision_prompt(value: ExpressionDecision | Mapping[str, Any]) -> str:
|
def expression_decision_prompt(value: ExpressionDecision | Mapping[str, Any]) -> str:
|
||||||
|
|
@ -633,12 +702,19 @@ def expression_decision_prompt(value: ExpressionDecision | Mapping[str, Any]) ->
|
||||||
content_instruction = "内容尺度=含蓄暧昧;可以亲密和调情,但保持非露骨,不描写成人性行为"
|
content_instruction = "内容尺度=含蓄暧昧;可以亲密和调情,但保持非露骨,不描写成人性行为"
|
||||||
else:
|
else:
|
||||||
content_instruction = "内容尺度=日常;不要主动升级为暧昧或成人内容"
|
content_instruction = "内容尺度=日常;不要主动升级为暧昧或成人内容"
|
||||||
|
dimensions = (
|
||||||
|
f"节奏={str(decision.get('pacing') or 'steady')[:12]},"
|
||||||
|
f"直接度={str(decision.get('directness') or 'natural')[:12]},"
|
||||||
|
f"回应={str(decision.get('validation_style') or 'none')[:16]},"
|
||||||
|
f"幽默={str(decision.get('humor_mode') or 'off')[:12]},"
|
||||||
|
f"话题={str(decision.get('topic_initiative') or 'reply_only')[:16]}"
|
||||||
|
)
|
||||||
return (
|
return (
|
||||||
f"当前互动表达:{EXPRESSION_BAND_LABELS[band.value]};"
|
f"当前互动表达:{EXPRESSION_BAND_LABELS[band.value]};"
|
||||||
f"语气={str(decision.get('tone') or 'steady')[:24]},"
|
f"语气={str(decision.get('tone') or 'steady')[:24]},"
|
||||||
f"称呼距离={str(decision.get('address_style') or 'neutral')[:24]},"
|
f"称呼距离={str(decision.get('address_style') or 'neutral')[:24]},"
|
||||||
f"回复长度={str(decision.get('response_length') or 'balanced')[:24]};"
|
f"回复长度={str(decision.get('response_length') or 'balanced')[:24]};"
|
||||||
f"{followup};{initiative};{content_instruction}。"
|
f"{followup};{initiative};{dimensions};{content_instruction}。"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -664,6 +740,13 @@ def _blocked_decision(reason: str, blocker: str, inherited_reasons: list[str]) -
|
||||||
initiative="blocked",
|
initiative="blocked",
|
||||||
proactive_budget=0,
|
proactive_budget=0,
|
||||||
tts_style="none",
|
tts_style="none",
|
||||||
|
affect_modulation=normalize_affect_modulation({}),
|
||||||
|
pacing="slow",
|
||||||
|
directness="indirect",
|
||||||
|
validation_style="none",
|
||||||
|
self_disclosure="none",
|
||||||
|
humor_mode="off",
|
||||||
|
topic_initiative="reply_only",
|
||||||
allowed_behaviors=(),
|
allowed_behaviors=(),
|
||||||
safety_mode=reason,
|
safety_mode=reason,
|
||||||
blocker=blocker,
|
blocker=blocker,
|
||||||
|
|
|
||||||
|
|
@ -395,6 +395,8 @@ _DEFAULT_USER_TEMPLATE = {
|
||||||
"relationship_decay_settled_day": "",
|
"relationship_decay_settled_day": "",
|
||||||
"relationship_last_decay_stage_drop_at": 0,
|
"relationship_last_decay_stage_drop_at": 0,
|
||||||
"current_interaction": {},
|
"current_interaction": {},
|
||||||
|
"emotion_event_ledger": [],
|
||||||
|
"last_emotion_event": {},
|
||||||
"proactive_daily_limit": -1,
|
"proactive_daily_limit": -1,
|
||||||
"proactive_idle_minutes": -1,
|
"proactive_idle_minutes": -1,
|
||||||
"proactive_min_interval_minutes": -1,
|
"proactive_min_interval_minutes": -1,
|
||||||
|
|
|
||||||
|
|
@ -106,6 +106,7 @@ from .dreaming import (
|
||||||
weighted_unique_fragment_sample,
|
weighted_unique_fragment_sample,
|
||||||
)
|
)
|
||||||
from .helpers import _date_key, _normalize_outbound_punctuation_flow, _normalize_photo_subject_owner, _now_ts, _path_text, _photo_subject_owner_prompt_label, _safe_float, _safe_int, _single_line, _strip_internal_message_blocks, _today_key, normalize_legacy_tag_text
|
from .helpers import _date_key, _normalize_outbound_punctuation_flow, _normalize_photo_subject_owner, _now_ts, _path_text, _photo_subject_owner_prompt_label, _safe_float, _safe_int, _single_line, _strip_internal_message_blocks, _today_key, normalize_legacy_tag_text
|
||||||
|
from .affect_modulation import compose_affect_modulation
|
||||||
from .memo_notes import memo_note_due_state, memo_note_sort_key, normalize_memo_note
|
from .memo_notes import memo_note_due_state, memo_note_sort_key, normalize_memo_note
|
||||||
from .planning import (
|
from .planning import (
|
||||||
build_daily_plan_prompt,
|
build_daily_plan_prompt,
|
||||||
|
|
@ -6678,16 +6679,20 @@ class DailyStateMixin:
|
||||||
values = self._base_state_values(profile)
|
values = self._base_state_values(profile)
|
||||||
weather_text = self._weather_summary_text(weather)
|
weather_text = self._weather_summary_text(weather)
|
||||||
energy = 75
|
energy = 75
|
||||||
|
composed_at = _now_ts()
|
||||||
mood_candidates = []
|
mood_candidates = []
|
||||||
health_cause = ""
|
health_cause = ""
|
||||||
for cond in active:
|
for cond in active:
|
||||||
kind = str(cond.get("kind") or "")
|
kind = str(cond.get("kind") or "")
|
||||||
if kind in values:
|
if kind in values:
|
||||||
values[kind] = _single_line(cond.get("label"), 80)
|
values[kind] = _single_line(cond.get("label"), 80)
|
||||||
energy += _safe_int(cond.get("energy_delta"), 0, -100, 100)
|
energy += self._condition_effective_energy_delta(cond, now=composed_at)
|
||||||
mood = _single_line(cond.get("mood"), 20)
|
mood = _single_line(cond.get("mood"), 20)
|
||||||
if mood and mood != "平稳":
|
if mood and mood != "平稳":
|
||||||
mood_candidates.append((mood, _safe_int(cond.get("intensity"), 50, 0, 100)))
|
intensity = _safe_int(cond.get("intensity"), 50, 0, 100)
|
||||||
|
if kind == "memory_afterglow":
|
||||||
|
intensity = max(0, round(intensity * self._memory_afterglow_decay(cond, now=composed_at)))
|
||||||
|
mood_candidates.append((mood, intensity))
|
||||||
if kind == "health" and not health_cause:
|
if kind == "health" and not health_cause:
|
||||||
health_cause = _single_line(cond.get("cause"), 120)
|
health_cause = _single_line(cond.get("cause"), 120)
|
||||||
remembered_dream = self._remembered_daily_dream_label()
|
remembered_dream = self._remembered_daily_dream_label()
|
||||||
|
|
@ -6728,12 +6733,28 @@ class DailyStateMixin:
|
||||||
"energy": energy,
|
"energy": energy,
|
||||||
"note": note,
|
"note": note,
|
||||||
"conditions": active,
|
"conditions": active,
|
||||||
|
"affect_modulation": compose_affect_modulation(active, now=composed_at),
|
||||||
}
|
}
|
||||||
if override_active:
|
if override_active:
|
||||||
result["location_override_ts"] = existing_override_ts
|
result["location_override_ts"] = existing_override_ts
|
||||||
result["location_source"] = "dialogue_override"
|
result["location_source"] = "dialogue_override"
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _memory_afterglow_decay(cond: dict[str, Any], *, now: float) -> float:
|
||||||
|
if str(cond.get("kind") or "") != "memory_afterglow":
|
||||||
|
return 1.0
|
||||||
|
start_ts = _safe_float(cond.get("start_ts"), now)
|
||||||
|
half_life = max(60.0, min(86400.0, _safe_float(cond.get("half_life_seconds"), 1800.0)))
|
||||||
|
age = max(0.0, now - start_ts)
|
||||||
|
return max(0.0, min(1.0, 0.5 ** (age / half_life)))
|
||||||
|
|
||||||
|
def _condition_effective_energy_delta(self, cond: dict[str, Any], *, now: float) -> int:
|
||||||
|
base = _safe_int(cond.get("energy_delta"), 0, -100, 100)
|
||||||
|
if str(cond.get("kind") or "") != "memory_afterglow":
|
||||||
|
return base
|
||||||
|
return int(round(base * self._memory_afterglow_decay(cond, now=now)))
|
||||||
|
|
||||||
def _build_state_note(
|
def _build_state_note(
|
||||||
self,
|
self,
|
||||||
sleep: str,
|
sleep: str,
|
||||||
|
|
|
||||||
119
emotion_diagnostics.py
普通文件
119
emotion_diagnostics.py
普通文件
|
|
@ -0,0 +1,119 @@
|
||||||
|
"""Redacted, read-only projection of the cross-plugin emotion pipeline."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
|
||||||
|
def _text(value: Any, limit: int) -> str:
|
||||||
|
return " ".join(str(value or "").split())[:limit]
|
||||||
|
|
||||||
|
|
||||||
|
def _hash(value: Any) -> str:
|
||||||
|
cleaned = _text(value, 220)
|
||||||
|
return hashlib.sha256(cleaned.encode("utf-8", errors="ignore")).hexdigest()[:12] if cleaned else ""
|
||||||
|
|
||||||
|
|
||||||
|
def _ref(value: Any) -> dict[str, str]:
|
||||||
|
source = value if isinstance(value, dict) else {}
|
||||||
|
return {"kind": _text(source.get("kind"), 24), "role": _text(source.get("role"), 40), "id_hash": _hash(source.get("id"))}
|
||||||
|
|
||||||
|
|
||||||
|
def emotion_trace_summary(user: Any, *, limit: int = 20) -> list[dict[str, Any]]:
|
||||||
|
source = user if isinstance(user, dict) else {}
|
||||||
|
ledger = source.get("emotion_event_ledger")
|
||||||
|
if not isinstance(ledger, list):
|
||||||
|
return []
|
||||||
|
latest: dict[str, dict[str, Any]] = {}
|
||||||
|
for event in ledger:
|
||||||
|
if not isinstance(event, dict):
|
||||||
|
continue
|
||||||
|
trace_id = _text(event.get("trace_id"), 96)
|
||||||
|
if not trace_id:
|
||||||
|
continue
|
||||||
|
previous = latest.get(trace_id)
|
||||||
|
if previous is None or int(event.get("revision") or 0) >= int(previous.get("revision") or 0):
|
||||||
|
latest[trace_id] = event
|
||||||
|
items = sorted(latest.values(), key=lambda item: (_text(item.get("occurred_at"), 48), int(item.get("revision") or 0)), reverse=True)
|
||||||
|
return [{
|
||||||
|
"trace_id": _text(item.get("trace_id"), 96),
|
||||||
|
"event_id": _text(item.get("event_id"), 96),
|
||||||
|
"revision": max(1, int(item.get("revision") or 1)),
|
||||||
|
"event_type": _text(item.get("event_type"), 48),
|
||||||
|
"status": _text(item.get("status"), 24),
|
||||||
|
"occurred_at": _text(item.get("occurred_at"), 48),
|
||||||
|
} for item in items[: max(1, min(100, int(limit or 20)))]]
|
||||||
|
|
||||||
|
|
||||||
|
def build_emotion_trace_projection(
|
||||||
|
user: Any,
|
||||||
|
trace_id: str,
|
||||||
|
*,
|
||||||
|
daily_state: Any = None,
|
||||||
|
expression_decision: Any = None,
|
||||||
|
memory_result: Any = None,
|
||||||
|
requester_context: Any = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
context = requester_context if isinstance(requester_context, dict) else {}
|
||||||
|
if context.get("is_admin") is not True:
|
||||||
|
return {"state": "forbidden", "read_only": True, "trace_id": "", "events": [], "error_code": "admin_required"}
|
||||||
|
source = user if isinstance(user, dict) else {}
|
||||||
|
trace = _text(trace_id, 96)
|
||||||
|
ledger = source.get("emotion_event_ledger")
|
||||||
|
local_events = []
|
||||||
|
for event in ledger if isinstance(ledger, list) else []:
|
||||||
|
if not isinstance(event, dict) or event.get("trace_id") != trace:
|
||||||
|
continue
|
||||||
|
local_events.append({
|
||||||
|
"event_id": _text(event.get("event_id"), 96),
|
||||||
|
"trace_id": trace,
|
||||||
|
"revision": max(1, int(event.get("revision") or 1)),
|
||||||
|
"origin_kind": _text(event.get("origin_kind"), 40),
|
||||||
|
"event_type": _text(event.get("event_type"), 48),
|
||||||
|
"intensity": float(event.get("intensity") or 0.0),
|
||||||
|
"confidence": float(event.get("confidence") or 0.0),
|
||||||
|
"status": _text(event.get("status"), 24),
|
||||||
|
"source_rule": _text(event.get("source_rule"), 80),
|
||||||
|
"occurred_at": _text(event.get("occurred_at"), 48),
|
||||||
|
"applied_interaction": _text(event.get("applied_interaction"), 32),
|
||||||
|
"correction_of": _text(event.get("correction_of"), 96),
|
||||||
|
"actor": _ref(event.get("actor_ref")),
|
||||||
|
"target": _ref(event.get("target_ref")),
|
||||||
|
"quoted_target": _ref(event.get("quoted_target_ref")),
|
||||||
|
})
|
||||||
|
local_events.sort(key=lambda item: item["revision"])
|
||||||
|
state = daily_state if isinstance(daily_state, dict) else {}
|
||||||
|
conditions = state.get("conditions") if isinstance(state.get("conditions"), list) else []
|
||||||
|
afterglow = [{
|
||||||
|
"condition_id": _text(item.get("id"), 120),
|
||||||
|
"source_event_id": _text(item.get("source_event_id"), 96),
|
||||||
|
"source_revision": max(1, int(item.get("source_revision") or 1)),
|
||||||
|
"energy_delta": float(item.get("energy_delta") or 0.0),
|
||||||
|
"start_ts": float(item.get("start_ts") or 0.0),
|
||||||
|
"end_ts": float(item.get("end_ts") or 0.0),
|
||||||
|
"half_life_seconds": float(item.get("half_life_seconds") or 0.0),
|
||||||
|
} for item in conditions if isinstance(item, dict) and item.get("kind") == "memory_afterglow" and (not trace or item.get("trace_id") == trace)]
|
||||||
|
memory = memory_result if isinstance(memory_result, dict) else {}
|
||||||
|
memory_items = memory.get("items") if isinstance(memory.get("items"), list) else []
|
||||||
|
return {
|
||||||
|
"schema_version": "emotion_trace_projection.v1",
|
||||||
|
"state": "ready" if memory.get("state") in {None, "ready"} else "degraded",
|
||||||
|
"read_only": True,
|
||||||
|
"trace_id": trace,
|
||||||
|
"events": local_events,
|
||||||
|
"memory_events": memory_items[:100],
|
||||||
|
"current_interaction": source.get("current_interaction") if isinstance(source.get("current_interaction"), dict) else {},
|
||||||
|
"afterglow": afterglow[:20],
|
||||||
|
"daily_state": {
|
||||||
|
"mood_bias": _text(state.get("mood_bias"), 40),
|
||||||
|
"energy": max(0, min(100, int(state.get("energy") or 0))),
|
||||||
|
"affect_modulation": state.get("affect_modulation") if isinstance(state.get("affect_modulation"), dict) else {},
|
||||||
|
},
|
||||||
|
"expression_decision": expression_decision if isinstance(expression_decision, dict) else {},
|
||||||
|
"memory_state": _text(memory.get("state"), 24) or "degraded",
|
||||||
|
"error_code": _text(memory.get("error_code"), 80),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = ["build_emotion_trace_projection", "emotion_trace_summary"]
|
||||||
162
emotion_event_contract.py
普通文件
162
emotion_event_contract.py
普通文件
|
|
@ -0,0 +1,162 @@
|
||||||
|
"""Versioned, redacted emotion-event contract shared across companion plugins."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
import re
|
||||||
|
from typing import Any, Mapping
|
||||||
|
|
||||||
|
|
||||||
|
EMOTION_EVENT_SCHEMA_VERSION = "companion_emotion_event.v1"
|
||||||
|
EMOTION_EVENT_TYPES = frozenset({
|
||||||
|
"neutral", "hurt", "apology", "comfort", "praise", "comfort_need",
|
||||||
|
"external_negative", "scar_touched", "warm_memory", "vulnerable_resonance",
|
||||||
|
"play", "intimacy", "boundary",
|
||||||
|
})
|
||||||
|
EMOTION_EVENT_ORIGINS = frozenset({"interaction", "memory_recall", "system_condition"})
|
||||||
|
EMOTION_EVENT_STATUSES = frozenset({"observed", "revised", "applied", "ignored", "expired"})
|
||||||
|
EMOTION_EVENT_CONTRACT_FIELDS = (
|
||||||
|
"schema_version", "event_id", "trace_id", "revision", "producer_plugin",
|
||||||
|
"origin_kind", "platform", "bot_id", "scope", "session_id", "actor_ref",
|
||||||
|
"target_ref", "quoted_target_ref", "event_type", "intensity", "confidence",
|
||||||
|
"valence_hint", "arousal_hint", "vulnerability_hint", "source_rule",
|
||||||
|
"occurred_at", "expires_at", "dedupe_key", "payload_hash", "privacy_level",
|
||||||
|
"applied_interaction", "applied_energy_delta", "correction_of", "status",
|
||||||
|
"reason_codes",
|
||||||
|
)
|
||||||
|
EMOTION_EVENT_CONTRACT_FINGERPRINT = hashlib.sha256(
|
||||||
|
"|".join(EMOTION_EVENT_CONTRACT_FIELDS).encode("ascii")
|
||||||
|
).hexdigest()[:20]
|
||||||
|
|
||||||
|
|
||||||
|
def _text(value: Any, limit: int) -> str:
|
||||||
|
text = re.sub(r"\s+", " ", str(value or "").replace("\u3000", " ")).strip()
|
||||||
|
return text[:limit]
|
||||||
|
|
||||||
|
|
||||||
|
def _number(value: Any, default: float, low: float, high: float) -> float:
|
||||||
|
if isinstance(value, bool):
|
||||||
|
return default
|
||||||
|
try:
|
||||||
|
number = float(value)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return default
|
||||||
|
if not math.isfinite(number):
|
||||||
|
return default
|
||||||
|
return round(max(low, min(high, number)), 4)
|
||||||
|
|
||||||
|
|
||||||
|
def _integer(value: Any, default: int = 1) -> int:
|
||||||
|
if isinstance(value, bool):
|
||||||
|
return default
|
||||||
|
try:
|
||||||
|
return max(1, min(1_000_000, int(value)))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return default
|
||||||
|
|
||||||
|
|
||||||
|
def _entity(value: Any) -> dict[str, str]:
|
||||||
|
source = value if isinstance(value, Mapping) else {}
|
||||||
|
return {
|
||||||
|
"kind": _text(source.get("kind"), 24) or "unknown",
|
||||||
|
"id": _text(source.get("id"), 160),
|
||||||
|
"role": _text(source.get("role"), 40),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _timestamp(value: Any) -> str:
|
||||||
|
text = _text(value, 48)
|
||||||
|
if text:
|
||||||
|
return text
|
||||||
|
return datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||||
|
|
||||||
|
|
||||||
|
def _stable_hash(*parts: Any) -> str:
|
||||||
|
raw = "|".join(_text(part, 500) for part in parts)
|
||||||
|
return hashlib.sha256(raw.encode("utf-8", errors="ignore")).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_emotion_event(value: Any, *, producer_plugin: str = "") -> dict[str, Any]:
|
||||||
|
"""Return a bounded JSON-safe event without retaining raw message content."""
|
||||||
|
source = dict(value) if isinstance(value, Mapping) else {}
|
||||||
|
producer = _text(source.get("producer_plugin") or producer_plugin, 80) or "unknown"
|
||||||
|
origin = _text(source.get("origin_kind"), 40)
|
||||||
|
if origin not in EMOTION_EVENT_ORIGINS:
|
||||||
|
origin = "interaction"
|
||||||
|
event_type = _text(source.get("event_type"), 48).lower()
|
||||||
|
if event_type not in EMOTION_EVENT_TYPES:
|
||||||
|
event_type = "neutral"
|
||||||
|
status = _text(source.get("status"), 24).lower()
|
||||||
|
if status not in EMOTION_EVENT_STATUSES:
|
||||||
|
status = "observed"
|
||||||
|
session_id = _text(source.get("session_id"), 220)
|
||||||
|
dedupe_key = _text(source.get("dedupe_key"), 160)
|
||||||
|
payload_hash = _text(source.get("payload_hash"), 80)
|
||||||
|
if not payload_hash:
|
||||||
|
payload_hash = _stable_hash(
|
||||||
|
producer, origin, session_id, event_type, dedupe_key,
|
||||||
|
source.get("message_fingerprint"), source.get("source_rule"),
|
||||||
|
)
|
||||||
|
event_id = _text(source.get("event_id"), 96)
|
||||||
|
if not event_id:
|
||||||
|
event_id = "emo_" + _stable_hash(producer, origin, session_id, event_type, dedupe_key, payload_hash)[:24]
|
||||||
|
trace_id = _text(source.get("trace_id"), 96)
|
||||||
|
if not trace_id:
|
||||||
|
trace_id = "etr_" + _stable_hash(session_id, dedupe_key or event_id)[:24]
|
||||||
|
reason_codes = source.get("reason_codes")
|
||||||
|
if not isinstance(reason_codes, (list, tuple)):
|
||||||
|
reason_codes = []
|
||||||
|
clean_reasons: list[str] = []
|
||||||
|
for item in reason_codes[:12]:
|
||||||
|
reason = _text(item, 64)
|
||||||
|
if reason and reason not in clean_reasons:
|
||||||
|
clean_reasons.append(reason)
|
||||||
|
return {
|
||||||
|
"schema_version": EMOTION_EVENT_SCHEMA_VERSION,
|
||||||
|
"event_id": event_id,
|
||||||
|
"trace_id": trace_id,
|
||||||
|
"revision": _integer(source.get("revision"), 1),
|
||||||
|
"producer_plugin": producer,
|
||||||
|
"origin_kind": origin,
|
||||||
|
"platform": _text(source.get("platform"), 80),
|
||||||
|
"bot_id": _text(source.get("bot_id"), 160),
|
||||||
|
"scope": _text(source.get("scope"), 24) or "private",
|
||||||
|
"session_id": session_id,
|
||||||
|
"actor_ref": _entity(source.get("actor_ref")),
|
||||||
|
"target_ref": _entity(source.get("target_ref")),
|
||||||
|
"quoted_target_ref": _entity(source.get("quoted_target_ref")),
|
||||||
|
"event_type": event_type,
|
||||||
|
"intensity": _number(source.get("intensity"), 0.0, 0.0, 100.0),
|
||||||
|
"confidence": _number(source.get("confidence"), 0.0, 0.0, 1.0),
|
||||||
|
"valence_hint": _number(source.get("valence_hint"), 0.0, -1.0, 1.0),
|
||||||
|
"arousal_hint": _number(source.get("arousal_hint"), 0.0, 0.0, 1.0),
|
||||||
|
"vulnerability_hint": _number(source.get("vulnerability_hint"), 0.0, 0.0, 1.0),
|
||||||
|
"source_rule": _text(source.get("source_rule"), 80),
|
||||||
|
"occurred_at": _timestamp(source.get("occurred_at")),
|
||||||
|
"expires_at": _text(source.get("expires_at"), 48),
|
||||||
|
"dedupe_key": dedupe_key or payload_hash[:32],
|
||||||
|
"payload_hash": payload_hash,
|
||||||
|
"privacy_level": _text(source.get("privacy_level"), 24) or "redacted",
|
||||||
|
"applied_interaction": _text(source.get("applied_interaction"), 32),
|
||||||
|
"applied_energy_delta": _number(source.get("applied_energy_delta"), 0.0, -100.0, 100.0),
|
||||||
|
"correction_of": _text(source.get("correction_of"), 96),
|
||||||
|
"status": status,
|
||||||
|
"reason_codes": clean_reasons,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def emotion_event_json(value: Any, *, producer_plugin: str = "") -> str:
|
||||||
|
return json.dumps(normalize_emotion_event(value, producer_plugin=producer_plugin), ensure_ascii=False, separators=(",", ":"))
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"EMOTION_EVENT_CONTRACT_FIELDS",
|
||||||
|
"EMOTION_EVENT_CONTRACT_FINGERPRINT",
|
||||||
|
"EMOTION_EVENT_SCHEMA_VERSION",
|
||||||
|
"EMOTION_EVENT_STATUSES",
|
||||||
|
"EMOTION_EVENT_TYPES",
|
||||||
|
"emotion_event_json",
|
||||||
|
"normalize_emotion_event",
|
||||||
|
]
|
||||||
62
emotion_event_ledger.py
普通文件
62
emotion_event_ledger.py
普通文件
|
|
@ -0,0 +1,62 @@
|
||||||
|
"""Bounded recent emotion-event ledger owned by Companion user profiles."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from copy import deepcopy
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
try:
|
||||||
|
from .emotion_event_contract import normalize_emotion_event
|
||||||
|
except ImportError: # direct-module tests
|
||||||
|
from emotion_event_contract import normalize_emotion_event # type: ignore
|
||||||
|
|
||||||
|
|
||||||
|
DEFAULT_RECENT_EVENT_LIMIT = 64
|
||||||
|
|
||||||
|
|
||||||
|
def record_recent_emotion_event(
|
||||||
|
user: dict[str, Any],
|
||||||
|
value: Any,
|
||||||
|
*,
|
||||||
|
limit: int = DEFAULT_RECENT_EVENT_LIMIT,
|
||||||
|
) -> tuple[dict[str, Any], bool]:
|
||||||
|
event = normalize_emotion_event(value, producer_plugin="private_companion")
|
||||||
|
ledger = user.get("emotion_event_ledger")
|
||||||
|
if not isinstance(ledger, list):
|
||||||
|
ledger = []
|
||||||
|
kept: list[dict[str, Any]] = []
|
||||||
|
duplicate = False
|
||||||
|
for item in ledger:
|
||||||
|
if not isinstance(item, dict):
|
||||||
|
continue
|
||||||
|
if item.get("event_id") == event["event_id"] and int(item.get("revision") or 0) == event["revision"]:
|
||||||
|
duplicate = True
|
||||||
|
kept.append(item)
|
||||||
|
else:
|
||||||
|
kept.append(item)
|
||||||
|
if not duplicate:
|
||||||
|
kept.append(event)
|
||||||
|
kept.sort(key=lambda item: (str(item.get("occurred_at") or ""), int(item.get("revision") or 0)))
|
||||||
|
user["emotion_event_ledger"] = kept[-max(8, min(256, int(limit or DEFAULT_RECENT_EVENT_LIMIT))):]
|
||||||
|
user["last_emotion_event"] = {
|
||||||
|
"event_id": event["event_id"],
|
||||||
|
"trace_id": event["trace_id"],
|
||||||
|
"revision": event["revision"],
|
||||||
|
"event_type": event["event_type"],
|
||||||
|
"status": event["status"],
|
||||||
|
"occurred_at": event["occurred_at"],
|
||||||
|
}
|
||||||
|
return deepcopy(event), not duplicate
|
||||||
|
|
||||||
|
|
||||||
|
def emotion_trace_from_user(user: Any, trace_id: str, *, limit: int = 20) -> list[dict[str, Any]]:
|
||||||
|
if not isinstance(user, dict) or not isinstance(trace_id, str) or not trace_id:
|
||||||
|
return []
|
||||||
|
ledger = user.get("emotion_event_ledger")
|
||||||
|
if not isinstance(ledger, list):
|
||||||
|
return []
|
||||||
|
result = [deepcopy(item) for item in ledger if isinstance(item, dict) and item.get("trace_id") == trace_id]
|
||||||
|
result.sort(key=lambda item: int(item.get("revision") or 0))
|
||||||
|
return result[-max(1, min(100, int(limit or 20))):]
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = ["DEFAULT_RECENT_EVENT_LIMIT", "emotion_trace_from_user", "record_recent_emotion_event"]
|
||||||
46
emotion_targeting.py
普通文件
46
emotion_targeting.py
普通文件
|
|
@ -0,0 +1,46 @@
|
||||||
|
"""High-precision actor/target attribution for short-term emotion events."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
|
||||||
|
def classify_emotion_target(text: Any) -> dict[str, Any]:
|
||||||
|
cleaned = " ".join(str(text or "").split())[:1000]
|
||||||
|
base = {
|
||||||
|
"actor": "user",
|
||||||
|
"target": "none",
|
||||||
|
"quoted_target": "none",
|
||||||
|
"speech_act": "statement",
|
||||||
|
"confidence": 0.5,
|
||||||
|
"auto_settle": False,
|
||||||
|
"reason_code": "target_none",
|
||||||
|
}
|
||||||
|
if not cleaned:
|
||||||
|
return {**base, "confidence": 1.0}
|
||||||
|
lower = cleaned.lower()
|
||||||
|
if re.search(r"(```|traceback|exception:|\b(error|warning|debug|info)\b[::]|\{\s*[\"']?[a-z_]+[\"']?\s*:)", lower):
|
||||||
|
return {**base, "speech_act": "diagnostic", "confidence": 0.98, "reason_code": "structured_text"}
|
||||||
|
quoted = bool(re.search(r"[“\"‘'][^”\"’']{2,160}[”\"’']|(?:^|\n)\s*>\s*\S+|(?:他|她|他们|别人).{0,8}(说|骂|讲)", cleaned))
|
||||||
|
negative = bool(re.search(r"(滚|闭嘴|恶心|废物|垃圾|讨厌|烦死|没用|蠢|傻)", cleaned))
|
||||||
|
if quoted and negative:
|
||||||
|
return {**base, "target": "other", "quoted_target": "ambiguous", "speech_act": "quote", "confidence": 0.92, "reason_code": "quoted_negative"}
|
||||||
|
if re.search(r"(我好|我真|我太|我是不是|我就是|我是).{0,12}(废物|垃圾|没用|傻|笨|恶心|讨厌)", cleaned):
|
||||||
|
return {**base, "target": "self", "speech_act": "self_disclosure", "confidence": 0.94, "reason_code": "self_negative"}
|
||||||
|
direct_bot = bool(
|
||||||
|
re.search(r"(讨厌你|烦你|不想理你|你.{0,4}(滚|闭嘴)|你(?:真|也|就是|是|太|真的|怎么这么).{0,8}(恶心|废物|垃圾|没用|太吵|烦死))", cleaned)
|
||||||
|
or re.search(r"((bot|机器人|插件|助手|ai).{0,8}(垃圾|废物|恶心|没用)|(垃圾|废物|恶心|没用).{0,8}(bot|机器人|插件|助手|ai))", lower)
|
||||||
|
)
|
||||||
|
if direct_bot:
|
||||||
|
return {**base, "target": "bot", "speech_act": "direct_address", "confidence": 0.94, "auto_settle": True, "reason_code": "direct_bot_target"}
|
||||||
|
if re.search(r"(他|她|它|他们|她们|别人|群友|同事|同学|老师|老板|那个人|这个人).{0,18}(滚|闭嘴|恶心|废物|垃圾|讨厌|烦|没用|蠢|傻)", cleaned):
|
||||||
|
return {**base, "target": "other", "speech_act": "third_party_report", "confidence": 0.9, "reason_code": "third_party_target"}
|
||||||
|
if re.search(r"(对不起|抱歉|我错了|喜欢你|爱你|谢谢你|辛苦了|抱抱你|摸摸你)", cleaned):
|
||||||
|
return {**base, "target": "bot", "speech_act": "direct_address", "confidence": 0.86, "auto_settle": True, "reason_code": "direct_positive_target"}
|
||||||
|
if negative:
|
||||||
|
return {**base, "target": "ambiguous", "speech_act": "ambiguous_negative", "confidence": 0.35, "reason_code": "negative_target_uncertain"}
|
||||||
|
return base
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = ["classify_emotion_target"]
|
||||||
119
interaction_dynamics.py
普通文件
119
interaction_dynamics.py
普通文件
|
|
@ -0,0 +1,119 @@
|
||||||
|
"""Deterministic recovery dynamics behind the seven interaction bands."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import math
|
||||||
|
from typing import Any, Mapping
|
||||||
|
|
||||||
|
|
||||||
|
DYNAMICS_VERSION = "interaction_dynamics.v1"
|
||||||
|
NEGATIVE_BANDS = {"avoidant", "hurt"}
|
||||||
|
POSITIVE_BANDS = {"lively", "warm", "close", "affectionate"}
|
||||||
|
|
||||||
|
|
||||||
|
def _finite(value: Any, default: float = 0.0) -> float:
|
||||||
|
if isinstance(value, bool):
|
||||||
|
return default
|
||||||
|
try:
|
||||||
|
numeric = float(value)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return default
|
||||||
|
return numeric if math.isfinite(numeric) else default
|
||||||
|
|
||||||
|
|
||||||
|
def project_interaction_dynamics(value: Any, *, now: Any) -> dict[str, Any]:
|
||||||
|
raw = dict(value) if isinstance(value, Mapping) else {}
|
||||||
|
if raw.get("dynamics_version") != DYNAMICS_VERSION:
|
||||||
|
return {}
|
||||||
|
current = max(0.0, min(100.0, _finite(raw.get("load"))))
|
||||||
|
peak = max(current, min(100.0, _finite(raw.get("peak_intensity"), current)))
|
||||||
|
started = max(0.0, _finite(raw.get("decay_started_at"), _finite(raw.get("updated_at"))))
|
||||||
|
current_ts = max(started, _finite(now, started))
|
||||||
|
half_life = max(300.0, min(86400.0, _finite(raw.get("half_life"), 3600.0)))
|
||||||
|
load = current * (0.5 ** (max(0.0, current_ts - started) / half_life))
|
||||||
|
polarity = -1 if int(_finite(raw.get("polarity"), 0)) < 0 else 1 if int(_finite(raw.get("polarity"), 0)) > 0 else 0
|
||||||
|
stored_band = str(raw.get("base_band") or raw.get("expression_band") or "relaxed")
|
||||||
|
if polarity < 0:
|
||||||
|
band = "avoidant" if load >= 70.0 else "hurt" if load >= 12.0 else "relaxed"
|
||||||
|
elif polarity > 0 and stored_band in POSITIVE_BANDS and load >= 8.0:
|
||||||
|
band = stored_band
|
||||||
|
else:
|
||||||
|
band = "relaxed"
|
||||||
|
recovery_band = "steady"
|
||||||
|
if load > 0.5 and load < peak * 0.9:
|
||||||
|
recovery_band = "recovering"
|
||||||
|
elif load >= peak * 0.98 and peak > 0:
|
||||||
|
recovery_band = "reinforced"
|
||||||
|
remaining = half_life * math.log2(max(1.0, load)) if load > 1.0 else 0.0
|
||||||
|
calculated_expiry = current_ts + remaining if remaining > 0 else 0.0
|
||||||
|
configured_expiry = max(0.0, _finite(raw.get("expires_at")))
|
||||||
|
if configured_expiry and calculated_expiry:
|
||||||
|
calculated_expiry = min(calculated_expiry, configured_expiry)
|
||||||
|
return {
|
||||||
|
"dynamics_version": DYNAMICS_VERSION,
|
||||||
|
"expression_band": band,
|
||||||
|
"base_band": stored_band,
|
||||||
|
"load": round(load, 4),
|
||||||
|
"peak_intensity": round(peak, 4),
|
||||||
|
"decay_started_at": started,
|
||||||
|
"half_life": half_life,
|
||||||
|
"polarity": polarity,
|
||||||
|
"recovery_band": recovery_band,
|
||||||
|
"expires_at": calculated_expiry,
|
||||||
|
"projection_revision": max(1, min(1000000, int(_finite(raw.get("projection_revision"), 1)))),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def settle_interaction_dynamics(
|
||||||
|
existing: Any,
|
||||||
|
*,
|
||||||
|
requested_band: str,
|
||||||
|
event_kind: str,
|
||||||
|
intensity: Any,
|
||||||
|
now: Any,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
current_ts = max(0.0, _finite(now))
|
||||||
|
prior = project_interaction_dynamics(existing, now=current_ts)
|
||||||
|
prior_load = _finite(prior.get("load"))
|
||||||
|
prior_polarity = int(_finite(prior.get("polarity"), 0))
|
||||||
|
event_intensity = max(0.0, min(100.0, _finite(intensity)))
|
||||||
|
kind = str(event_kind or "neutral").strip().lower()
|
||||||
|
requested = requested_band if requested_band in NEGATIVE_BANDS | POSITIVE_BANDS | {"relaxed"} else "relaxed"
|
||||||
|
|
||||||
|
if kind == "hurt" and requested in NEGATIVE_BANDS:
|
||||||
|
base = prior_load if prior_polarity < 0 else 0.0
|
||||||
|
load = min(100.0, base + max(20.0, event_intensity) * max(0.25, 1.0 - base / 140.0))
|
||||||
|
polarity = -1
|
||||||
|
base_band = requested
|
||||||
|
half_life = 3600.0
|
||||||
|
elif prior_polarity < 0 and kind in {"apology", "comfort", "praise", "intimacy", "play"}:
|
||||||
|
factor = {"apology": 0.35, "comfort": 0.25, "praise": 0.12, "intimacy": 0.20, "play": 0.10}[kind]
|
||||||
|
load = max(0.0, prior_load - max(6.0, event_intensity * factor))
|
||||||
|
polarity = -1 if load > 0.5 else 0
|
||||||
|
base_band = str(prior.get("base_band") or "hurt")
|
||||||
|
half_life = _finite(prior.get("half_life"), 3600.0)
|
||||||
|
elif requested in POSITIVE_BANDS:
|
||||||
|
base = prior_load if prior_polarity > 0 else 0.0
|
||||||
|
load = min(100.0, base * 0.75 + max(10.0, event_intensity * 0.65))
|
||||||
|
polarity = 1
|
||||||
|
base_band = requested
|
||||||
|
half_life = 7200.0
|
||||||
|
else:
|
||||||
|
return prior
|
||||||
|
|
||||||
|
peak = max(load, _finite(prior.get("peak_intensity")) if polarity == prior_polarity else 0.0)
|
||||||
|
raw = {
|
||||||
|
"dynamics_version": DYNAMICS_VERSION,
|
||||||
|
"expression_band": base_band,
|
||||||
|
"base_band": base_band,
|
||||||
|
"load": load,
|
||||||
|
"peak_intensity": peak,
|
||||||
|
"decay_started_at": current_ts,
|
||||||
|
"half_life": half_life,
|
||||||
|
"polarity": polarity,
|
||||||
|
"projection_revision": int(_finite(prior.get("projection_revision"), 0)) + 1,
|
||||||
|
}
|
||||||
|
return project_interaction_dynamics(raw, now=current_ts)
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = ["DYNAMICS_VERSION", "project_interaction_dynamics", "settle_interaction_dynamics"]
|
||||||
31
main.py
31
main.py
|
|
@ -148,7 +148,7 @@ from .plugin_identity import (
|
||||||
from .runtime_compat import probe_runtime_capabilities
|
from .runtime_compat import probe_runtime_capabilities
|
||||||
from .relationship_policy import normalize_relationship_stage_policy
|
from .relationship_policy import normalize_relationship_stage_policy
|
||||||
from .relationship_ledger import apply_relationship_event, normalize_relationship_positive_stage_cap_key
|
from .relationship_ledger import apply_relationship_event, normalize_relationship_positive_stage_cap_key
|
||||||
from .companion_interaction_expression import build_expression_decision, content_intent_from_text, expression_decision_prompt
|
from .companion_interaction_expression import build_expression_decision, content_intent_from_text, current_interaction_projection, expression_decision_prompt
|
||||||
from .user_rest_gate import UserRestGateMixin
|
from .user_rest_gate import UserRestGateMixin
|
||||||
from .busy_reply_gate import BusyReplyGateMixin
|
from .busy_reply_gate import BusyReplyGateMixin
|
||||||
from .memory_companion_adapter import MemoryCompanionAdapterMixin
|
from .memory_companion_adapter import MemoryCompanionAdapterMixin
|
||||||
|
|
@ -6484,9 +6484,10 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
|
||||||
*,
|
*,
|
||||||
priority: int = 50,
|
priority: int = 50,
|
||||||
source: str = "",
|
source: str = "",
|
||||||
|
force_dynamic: bool = False,
|
||||||
) -> bool:
|
) -> bool:
|
||||||
position = self._normalize_passive_injection_position(getattr(self, "passive_injection_position", "prompt"))
|
position = self._normalize_passive_injection_position(getattr(self, "passive_injection_position", "prompt"))
|
||||||
if position == "system_prompt":
|
if position == "system_prompt" and not force_dynamic:
|
||||||
return False
|
return False
|
||||||
content = str(text or "").strip()
|
content = str(text or "").strip()
|
||||||
if not content:
|
if not content:
|
||||||
|
|
@ -9630,8 +9631,15 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
instruction = expression_decision_prompt(expression_projection)
|
instruction = expression_decision_prompt(expression_projection)
|
||||||
if instruction and hasattr(req, "system_prompt"):
|
if instruction:
|
||||||
req.system_prompt = f"{str(getattr(req, 'system_prompt', '') or '').rstrip()}\n\n[Companion expression]\n{instruction}"
|
self._append_turn_prompt_fragment_by_position(
|
||||||
|
req,
|
||||||
|
"<!-- private_companion_expression_decision_v2 -->",
|
||||||
|
f"[Companion expression]\n{instruction}",
|
||||||
|
priority=5,
|
||||||
|
source="expression_decision",
|
||||||
|
force_dynamic=True,
|
||||||
|
)
|
||||||
|
|
||||||
@filter.on_llm_request(priority=-22000)
|
@filter.on_llm_request(priority=-22000)
|
||||||
async def prepare_p5_memory_attestation(self, event: AstrMessageEvent, req: ProviderRequest, *args, **kwargs):
|
async def prepare_p5_memory_attestation(self, event: AstrMessageEvent, req: ProviderRequest, *args, **kwargs):
|
||||||
|
|
@ -12339,7 +12347,7 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
|
||||||
if not self._simulation_active(fast_user) and _safe_float(fast_user.get("next_proactive_at"), 0) <= 0:
|
if not self._simulation_active(fast_user) and _safe_float(fast_user.get("next_proactive_at"), 0) <= 0:
|
||||||
self._schedule_next_proactive(fast_user, now=received_ts)
|
self._schedule_next_proactive(fast_user, now=received_ts)
|
||||||
try:
|
try:
|
||||||
self._memory_companion_apply_emotional_drift(session_id=event.unified_msg_origin or "")
|
await self._memory_companion_apply_emotional_drift(session_id=event.unified_msg_origin or "")
|
||||||
self._memory_companion_attach_private_context(
|
self._memory_companion_attach_private_context(
|
||||||
event,
|
event,
|
||||||
user_id=user_id,
|
user_id=user_id,
|
||||||
|
|
@ -12772,10 +12780,23 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
|
||||||
user["intent_profile"] = intent_profile
|
user["intent_profile"] = intent_profile
|
||||||
if self._should_use_llm_emotion_judgement(text, intent_profile):
|
if self._should_use_llm_emotion_judgement(text, intent_profile):
|
||||||
# Model review does not block the current passive reply; it keeps using cached emotion state.
|
# Model review does not block the current passive reply; it keeps using cached emotion state.
|
||||||
|
observed_event = self._record_interaction_emotion_event(
|
||||||
|
user,
|
||||||
|
intent_profile,
|
||||||
|
band=str(current_interaction_projection(
|
||||||
|
user.get("current_interaction"),
|
||||||
|
relationship_role=self._private_user_role(user, user_id),
|
||||||
|
relationship_mode=user.get("relationship_mode", "normal"),
|
||||||
|
now=_now_ts(),
|
||||||
|
).get("expression_band") or "relaxed"),
|
||||||
|
reason_code="target_review_pending",
|
||||||
|
status="observed",
|
||||||
|
)
|
||||||
user["pending_emotion_judgement"] = {
|
user["pending_emotion_judgement"] = {
|
||||||
"text": _single_line(text, 240),
|
"text": _single_line(text, 240),
|
||||||
"created_at": _now_ts(),
|
"created_at": _now_ts(),
|
||||||
"local": deepcopy(intent_profile),
|
"local": deepcopy(intent_profile),
|
||||||
|
"observed_event": observed_event or {},
|
||||||
}
|
}
|
||||||
self._create_lifecycle_background_task(
|
self._create_lifecycle_background_task(
|
||||||
self._refine_inbound_emotion_with_model(user_id, text, deepcopy(intent_profile)),
|
self._refine_inbound_emotion_with_model(user_id, text, deepcopy(intent_profile)),
|
||||||
|
|
|
||||||
|
|
@ -93,6 +93,18 @@ class MemoryCompanionAdapterMixin:
|
||||||
return self._memory_companion_coerce_bool(value, True)
|
return self._memory_companion_coerce_bool(value, True)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
async def _memory_companion_record_emotion_event(self, event: dict[str, Any]) -> None:
|
||||||
|
bridge = self._memory_companion_bridge()
|
||||||
|
recorder = getattr(bridge, "record_emotion_event", None) if bridge is not None else None
|
||||||
|
if not callable(recorder):
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
await recorder(dict(event or {}))
|
||||||
|
except Exception as exc:
|
||||||
|
if self._memory_companion_optional_dependency_failed(exc, where="record_emotion_event"):
|
||||||
|
return
|
||||||
|
logger.debug("[PrivateCompanion] emotion event mirror failed: %s", _single_line(exc, 120))
|
||||||
|
|
||||||
def _memory_companion_degraded_status(self, reason: str, **extra: Any) -> dict[str, Any]:
|
def _memory_companion_degraded_status(self, reason: str, **extra: Any) -> dict[str, Any]:
|
||||||
status = {
|
status = {
|
||||||
"available": False,
|
"available": False,
|
||||||
|
|
@ -1470,7 +1482,12 @@ class MemoryCompanionAdapterMixin:
|
||||||
if bool(getattr(self, "enable_custom_relationship_stage_policy", False))
|
if bool(getattr(self, "enable_custom_relationship_stage_policy", False))
|
||||||
else None
|
else None
|
||||||
)
|
)
|
||||||
projection = relationship_projection_for_bridge(user.get("relationship_score", 0), policy)
|
projection = relationship_projection_for_bridge(
|
||||||
|
user.get("relationship_score", 0),
|
||||||
|
policy,
|
||||||
|
previous_stage_key=user.get("relationship_phase_key", ""),
|
||||||
|
)
|
||||||
|
user["relationship_phase_key"] = projection.get("phase_key", "acquaintance")
|
||||||
role_getter = getattr(self, "_private_user_role", None)
|
role_getter = getattr(self, "_private_user_role", None)
|
||||||
try:
|
try:
|
||||||
role = role_getter(user, user_id) if callable(role_getter) else str(user.get("relationship_role") or "friend")
|
role = role_getter(user, user_id) if callable(role_getter) else str(user.get("relationship_role") or "friend")
|
||||||
|
|
@ -2164,100 +2181,125 @@ class MemoryCompanionAdapterMixin:
|
||||||
return
|
return
|
||||||
logger.debug("[PrivateCompanion] MemoryCompanion QQ 空间发布写入失败: %s", _single_line(exc, 120))
|
logger.debug("[PrivateCompanion] MemoryCompanion QQ 空间发布写入失败: %s", _single_line(exc, 120))
|
||||||
|
|
||||||
def _memory_companion_apply_emotional_drift(self, *, session_id: str = "") -> None:
|
async def _memory_companion_apply_emotional_drift(self, *, session_id: str = "") -> None:
|
||||||
"""Pull pending emotional drift events from the memory plugin and apply to daily_state.
|
"""Durably project pending memory events into Daily State conditions."""
|
||||||
|
|
||||||
This now includes cross-window emotional continuity: if the bot recently
|
|
||||||
touched emotional memories in other sessions, a dampened residue is also
|
|
||||||
applied to the current daily_state, creating a sense of emotional carryover.
|
|
||||||
"""
|
|
||||||
if not getattr(self, "enable_memory_companion_emotional_drift", True):
|
if not getattr(self, "enable_memory_companion_emotional_drift", True):
|
||||||
return
|
return
|
||||||
bridge = self._memory_companion_bridge()
|
bridge = self._memory_companion_bridge()
|
||||||
if bridge is None:
|
if bridge is None:
|
||||||
return
|
return
|
||||||
getter = getattr(bridge, "get_emotional_events", None)
|
lister = getattr(bridge, "list_emotion_events", None)
|
||||||
if not callable(getter):
|
acker = getattr(bridge, "ack_emotion_events", None)
|
||||||
|
if not callable(lister) or not callable(acker):
|
||||||
|
return
|
||||||
|
consumer_id = "private_companion.daily_state"
|
||||||
|
cross_window = bool(getattr(self, "enable_memory_companion_cross_window_emotion", True))
|
||||||
|
if not cross_window and not session_id:
|
||||||
return
|
return
|
||||||
try:
|
try:
|
||||||
events = getter(session_id=session_id, limit=3)
|
delivery = await lister(
|
||||||
|
consumer_id=consumer_id,
|
||||||
|
session_id="" if cross_window else session_id,
|
||||||
|
exclude_session_id="",
|
||||||
|
cursor="",
|
||||||
|
limit=6,
|
||||||
|
)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
if self._memory_companion_optional_dependency_failed(exc, where="get_emotional_events"):
|
if self._memory_companion_optional_dependency_failed(exc, where="list_emotion_events"):
|
||||||
return
|
return
|
||||||
logger.debug("[PrivateCompanion] 情绪漂移拉取失败: %s", _single_line(exc, 120))
|
logger.debug("[PrivateCompanion] 情绪余波拉取失败: %s", _single_line(exc, 120))
|
||||||
return
|
return
|
||||||
# Cross-window emotional residue: check if there are recent emotional events
|
events = delivery.get("events", []) if isinstance(delivery, dict) else []
|
||||||
# from OTHER sessions that should subtly influence the current state
|
if not isinstance(events, list) or not events:
|
||||||
cross_window_delta = 0.0
|
|
||||||
cross_window_hints: list[str] = []
|
|
||||||
cross_state_getter = getattr(bridge, "get_recent_emotional_state", None)
|
|
||||||
if callable(cross_state_getter) and getattr(self, "enable_memory_companion_cross_window_emotion", True):
|
|
||||||
try:
|
|
||||||
cross_state = cross_state_getter()
|
|
||||||
if isinstance(cross_state, dict) and cross_state.get("total", 0) > 0:
|
|
||||||
# Apply a dampened cross-window effect (30% strength)
|
|
||||||
scar_count = cross_state.get("scar_count", 0)
|
|
||||||
warm_count = cross_state.get("warm_count", 0)
|
|
||||||
if scar_count > 0:
|
|
||||||
cross_window_delta = -min(2.0, scar_count * 0.8)
|
|
||||||
cross_window_hints.append("低落")
|
|
||||||
if warm_count > 0:
|
|
||||||
cross_window_delta += min(1.5, warm_count * 0.5)
|
|
||||||
cross_window_hints.append("微暖")
|
|
||||||
except Exception as exc:
|
|
||||||
self._memory_companion_optional_dependency_failed(exc, where="get_recent_emotional_state")
|
|
||||||
if not events and not cross_window_hints:
|
|
||||||
return
|
return
|
||||||
data = getattr(self, "data", None)
|
data = getattr(self, "data", None)
|
||||||
if not isinstance(data, dict):
|
if not isinstance(data, dict):
|
||||||
return
|
return
|
||||||
state = data.get("daily_state")
|
conditions = data.setdefault("state_conditions", [])
|
||||||
if not isinstance(state, dict):
|
if not isinstance(conditions, list):
|
||||||
state = {}
|
conditions = []
|
||||||
data["daily_state"] = state
|
data["state_conditions"] = conditions
|
||||||
try:
|
now = time.time()
|
||||||
current_energy = float(state.get("energy") or 0.0)
|
applied_refs: list[dict[str, Any]] = []
|
||||||
except Exception:
|
applied_keys: set[tuple[str, int]] = set()
|
||||||
current_energy = 0.0
|
|
||||||
total_delta = 0.0
|
|
||||||
mood_hints: list[str] = []
|
|
||||||
for event in events:
|
for event in events:
|
||||||
delta = float(event.get("energy_delta") or 0.0)
|
if not isinstance(event, dict):
|
||||||
total_delta += delta
|
continue
|
||||||
hint = _single_line(event.get("mood_hint"), 40)
|
condition = self._memory_companion_afterglow_condition(event, now=now)
|
||||||
if hint:
|
if not condition:
|
||||||
mood_hints.append(hint)
|
continue
|
||||||
# Add cross-window residue (already dampened)
|
event_id = condition["source_event_id"]
|
||||||
total_delta += cross_window_delta
|
replaced = False
|
||||||
mood_hints.extend(cross_window_hints)
|
for index, existing in enumerate(conditions):
|
||||||
# Safety valve: clamp total drift per cycle
|
if isinstance(existing, dict) and existing.get("kind") == "memory_afterglow" and existing.get("source_event_id") == event_id:
|
||||||
total_delta = max(-10.0, min(6.0, total_delta))
|
conditions[index] = condition
|
||||||
new_energy = max(0.0, min(100.0, current_energy + total_delta))
|
replaced = True
|
||||||
state["energy"] = round(new_energy, 1)
|
break
|
||||||
# Apply mood drift with safety valve: only shift if hint is significant
|
if not replaced:
|
||||||
if mood_hints:
|
conditions.append(condition)
|
||||||
current_mood = _single_line(state.get("mood_bias"), 80)
|
ref_key = (event_id, condition["source_revision"])
|
||||||
dominant_hint = mood_hints[0]
|
if ref_key not in applied_keys:
|
||||||
if current_mood and dominant_hint not in current_mood:
|
applied_keys.add(ref_key)
|
||||||
state["mood_bias"] = _single_line(f"{current_mood},偏{dominant_hint}", 80)
|
applied_refs.append({"event_id": event_id, "revision": condition["source_revision"]})
|
||||||
elif not current_mood:
|
if not applied_refs:
|
||||||
state["mood_bias"] = dominant_hint
|
return
|
||||||
drift_log = state.get("mood_drift_log")
|
composer = getattr(self, "_compose_state_from_conditions", None)
|
||||||
if not isinstance(drift_log, list):
|
saver = getattr(self, "_save_data_sync", None)
|
||||||
drift_log = []
|
if not callable(composer) or not callable(saver):
|
||||||
state["mood_drift_log"] = drift_log
|
return
|
||||||
drift_log.append({
|
data["daily_state"] = composer(data.get("daily_weather", {}))
|
||||||
"ts": self._memory_companion_now_iso(),
|
saver()
|
||||||
"events": [{"type": e.get("event_type"), "delta": e.get("energy_delta"), "hint": _single_line(e.get("mood_hint"), 40)} for e in events],
|
try:
|
||||||
"cross_window_delta": round(cross_window_delta, 2),
|
await acker(applied_refs, consumer_id=consumer_id)
|
||||||
"total_delta": round(total_delta, 2),
|
except Exception as exc:
|
||||||
})
|
self._memory_companion_optional_dependency_failed(exc, where="ack_emotion_events")
|
||||||
if len(drift_log) > 20:
|
return
|
||||||
drift_log[:] = drift_log[-20:]
|
logger.debug("[PrivateCompanion] 已应用并确认记忆情绪余波: count=%s", len(applied_refs))
|
||||||
logger.debug(
|
|
||||||
"[PrivateCompanion] 情绪漂移已应用: energy=%.1f->%.1f delta=%.1f cross_delta=%.1f hints=%s",
|
def _memory_companion_afterglow_condition(self, event: dict[str, Any], *, now: float) -> dict[str, Any] | None:
|
||||||
current_energy, new_energy, total_delta, cross_window_delta, mood_hints,
|
event_id = _single_line(event.get("event_id"), 96)
|
||||||
)
|
if not event_id:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
revision = max(1, min(1000000, int(event.get("revision") or 1)))
|
||||||
|
delta = max(-8.0, min(5.0, float(event.get("energy_delta") or 0.0)))
|
||||||
|
intensity = max(0, min(100, round(float(event.get("intensity") or 0.0))))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return None
|
||||||
|
event_type = _single_line(event.get("event_type"), 48)
|
||||||
|
mood_by_type = {
|
||||||
|
"scar_touched": "低落",
|
||||||
|
"warm_memory": "微暖",
|
||||||
|
"vulnerable_resonance": "柔软",
|
||||||
|
}
|
||||||
|
mood = mood_by_type.get(event_type, "平稳")
|
||||||
|
source_session = _single_line(event.get("session_id"), 220)
|
||||||
|
half_life = 1800.0
|
||||||
|
return {
|
||||||
|
"id": f"memory-afterglow-{event_id}",
|
||||||
|
"kind": "memory_afterglow",
|
||||||
|
"title": "记忆余波",
|
||||||
|
"label": "记忆被触动后留下的短暂情绪余波",
|
||||||
|
"mood": mood,
|
||||||
|
"energy_delta": round(delta, 2),
|
||||||
|
"intensity": intensity,
|
||||||
|
"start_ts": now,
|
||||||
|
"end_ts": now + 4 * half_life,
|
||||||
|
"duration_hours": 2,
|
||||||
|
"half_life_seconds": half_life,
|
||||||
|
"cause": "memory_recall_resonance",
|
||||||
|
"phase": "afterglow",
|
||||||
|
"source_event_id": event_id,
|
||||||
|
"source_revision": revision,
|
||||||
|
"source_session_id": source_session,
|
||||||
|
"trace_id": _single_line(event.get("trace_id"), 96),
|
||||||
|
"modulation": {
|
||||||
|
"valence": max(-1.0, min(1.0, _safe_float(event.get("valence"), 0.0))),
|
||||||
|
"arousal": max(0.0, min(1.0, _safe_float(event.get("arousal"), 0.0))),
|
||||||
|
"vulnerability": max(0.0, min(1.0, _safe_float(event.get("vulnerability"), 0.0))),
|
||||||
|
"confidence": max(0.0, min(1.0, _safe_float(event.get("confidence"), 0.0))),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
async def _memory_companion_search_open_loops(self, *, session_id: str = "", limit: int = 3) -> list[dict[str, Any]]:
|
async def _memory_companion_search_open_loops(self, *, session_id: str = "", limit: int = 3) -> list[dict[str, Any]]:
|
||||||
"""Search for unresolved open-loop / promise memories for proactive companionship."""
|
"""Search for unresolved open-loop / promise memories for proactive companionship."""
|
||||||
|
|
@ -2277,6 +2319,26 @@ class MemoryCompanionAdapterMixin:
|
||||||
logger.debug("[PrivateCompanion] open-loop 搜索失败: %s", _single_line(exc, 120))
|
logger.debug("[PrivateCompanion] open-loop 搜索失败: %s", _single_line(exc, 120))
|
||||||
return []
|
return []
|
||||||
|
|
||||||
|
async def _memory_companion_get_emotion_trace(
|
||||||
|
self,
|
||||||
|
trace_id: str,
|
||||||
|
*,
|
||||||
|
session_id: str = "",
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
bridge = self._memory_companion_bridge()
|
||||||
|
getter = getattr(bridge, "get_emotion_trace_diagnostic", None) if bridge is not None else None
|
||||||
|
if not callable(getter):
|
||||||
|
return {"state": "degraded", "read_only": True, "items": [], "error_code": "bridge_method_unavailable"}
|
||||||
|
try:
|
||||||
|
return await getter(
|
||||||
|
trace_id,
|
||||||
|
{"is_admin": True, "scope": "private", "session_id": _single_line(session_id, 220)},
|
||||||
|
limit=100,
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
self._memory_companion_optional_dependency_failed(exc, where="get_emotion_trace_diagnostic")
|
||||||
|
return {"state": "degraded", "read_only": True, "items": [], "error_code": "bridge_exception"}
|
||||||
|
|
||||||
async def _memory_companion_record_dream_fragment(
|
async def _memory_companion_record_dream_fragment(
|
||||||
self,
|
self,
|
||||||
*,
|
*,
|
||||||
|
|
|
||||||
|
|
@ -202,7 +202,7 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
|
||||||
now=time.time(),
|
now=time.time(),
|
||||||
)
|
)
|
||||||
expression_projection = {
|
expression_projection = {
|
||||||
"contract": "companion_interaction_expression.v1",
|
"contract": "companion_interaction_expression.v2",
|
||||||
"status": "configured_projection",
|
"status": "configured_projection",
|
||||||
"expression_band": current_interaction.get("expression_band") or "relaxed",
|
"expression_band": current_interaction.get("expression_band") or "relaxed",
|
||||||
"tone": "steady",
|
"tone": "steady",
|
||||||
|
|
@ -219,7 +219,7 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
|
||||||
raw_projection = raw_expression.to_dict() if hasattr(raw_expression, "to_dict") else dict(raw_expression or {})
|
raw_projection = raw_expression.to_dict() if hasattr(raw_expression, "to_dict") else dict(raw_expression or {})
|
||||||
expression_projection.update(
|
expression_projection.update(
|
||||||
{
|
{
|
||||||
"contract": self._single_line(raw_projection.get("contract"), 80) or "companion_interaction_expression.v1",
|
"contract": self._single_line(raw_projection.get("contract"), 80) or "companion_interaction_expression.v2",
|
||||||
"expression_band": self._single_line(raw_projection.get("expression_band"), 24) or "relaxed",
|
"expression_band": self._single_line(raw_projection.get("expression_band"), 24) or "relaxed",
|
||||||
"tone": self._single_line(raw_projection.get("tone"), 24) or "steady",
|
"tone": self._single_line(raw_projection.get("tone"), 24) or "steady",
|
||||||
"response_length": self._single_line(raw_projection.get("response_length"), 24) or "balanced",
|
"response_length": self._single_line(raw_projection.get("response_length"), 24) or "balanced",
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,7 @@ from quart import request
|
||||||
|
|
||||||
from .companion_interaction_expression import allowed_expression_bands, current_interaction_projection
|
from .companion_interaction_expression import allowed_expression_bands, current_interaction_projection
|
||||||
from .helpers import _safe_int
|
from .helpers import _safe_int
|
||||||
|
from .emotion_diagnostics import build_emotion_trace_projection, emotion_trace_summary
|
||||||
from .relationship_ledger import (
|
from .relationship_ledger import (
|
||||||
is_owner_exclusive,
|
is_owner_exclusive,
|
||||||
normalize_relationship_mode,
|
normalize_relationship_mode,
|
||||||
|
|
@ -282,6 +283,19 @@ class PrivateCompanionPageApiUsersGroupsMixin:
|
||||||
detail["memory_summary"] = await memory_reader(user_id, limit=3)
|
detail["memory_summary"] = await memory_reader(user_id, limit=3)
|
||||||
else:
|
else:
|
||||||
detail["memory_summary"] = {"available": False, "state": "unsupported", "reason_code": "summary_reader_unavailable"}
|
detail["memory_summary"] = {"available": False, "state": "unsupported", "reason_code": "summary_reader_unavailable"}
|
||||||
|
detail["emotion_trace_summary"] = emotion_trace_summary(user, limit=20)
|
||||||
|
trace_id = self._single_line(request.args.get("trace_id", ""), 96)
|
||||||
|
if trace_id:
|
||||||
|
trace_reader = getattr(self.plugin, "_memory_companion_get_emotion_trace", None)
|
||||||
|
memory_trace = await trace_reader(trace_id, session_id=str(user.get("umo") or "")) if callable(trace_reader) else {"state": "degraded", "items": [], "error_code": "bridge_method_unavailable"}
|
||||||
|
detail["emotion_trace"] = build_emotion_trace_projection(
|
||||||
|
user,
|
||||||
|
trace_id,
|
||||||
|
daily_state=self.plugin.data.get("daily_state"),
|
||||||
|
expression_decision=detail.get("expression_decision"),
|
||||||
|
memory_result=memory_trace,
|
||||||
|
requester_context={"is_admin": True},
|
||||||
|
)
|
||||||
return self._ok(detail)
|
return self._ok(detail)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
logger.error(f"[PrivateCompanionPage] 获取用户详情失败: {exc}", exc_info=True)
|
logger.error(f"[PrivateCompanionPage] 获取用户详情失败: {exc}", exc_info=True)
|
||||||
|
|
|
||||||
|
|
@ -27345,3 +27345,10 @@ pre {
|
||||||
justify-content: flex-start;
|
justify-content: flex-start;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
.emotion-diagnostics .action-strip{display:flex;flex-wrap:wrap;gap:6px;margin:10px 0}
|
||||||
|
.emotion-diagnostics .action-strip button{min-height:32px}
|
||||||
|
.emotion-trace-status{display:flex;justify-content:space-between;gap:10px;border-top:1px solid var(--line-soft);padding-top:10px;color:var(--muted);font-size:12px}
|
||||||
|
.emotion-trace-timeline{display:grid;gap:7px;margin:10px 0 0;padding-left:20px}
|
||||||
|
.emotion-trace-timeline li{padding-left:4px}
|
||||||
|
.emotion-trace-timeline li strong,.emotion-trace-timeline li span{display:block}
|
||||||
|
.emotion-trace-timeline li span{color:var(--muted);font-size:11px}
|
||||||
|
|
|
||||||
|
|
@ -12633,6 +12633,7 @@ async function renderUserDetail(forceFetch = false) {
|
||||||
<div class="detail-grid">
|
<div class="detail-grid">
|
||||||
${renderRelationshipPanel(detail.relationship_panel)}
|
${renderRelationshipPanel(detail.relationship_panel)}
|
||||||
${renderUserMemorySummary(detail.memory_summary)}
|
${renderUserMemorySummary(detail.memory_summary)}
|
||||||
|
${renderEmotionDiagnostics(detail)}
|
||||||
${detailBlock("关系能力", detail.formatted?.relationship || "", [["角色", detail.relationship_role_label || ""], ["群聊关系", groupRelationshipEnabled ? "启用:亲密度与互动表达生效" : "关闭"], ["私聊陪伴", privateEnabled ? "启用" : "关闭:仅在群聊中观测和互动"], ["主动联系", detail.proactive_contact_enabled ? `${detail.effective_daily_limit_text || formatProactiveLimit(detail.effective_daily_limit, detail.effective_daily_limit_unlimited)} / 天` : "关闭"], ["私聊记忆", detail.private_memory_enabled ? "启用" : "关闭"], ["跨群记忆", detail.cross_group_memory_enabled ? "启用" : "关闭"], ["P4", detail.p4_eligible ? "按真实聊天安全门判断" : "不参与"]])}
|
${detailBlock("关系能力", detail.formatted?.relationship || "", [["角色", detail.relationship_role_label || ""], ["群聊关系", groupRelationshipEnabled ? "启用:亲密度与互动表达生效" : "关闭"], ["私聊陪伴", privateEnabled ? "启用" : "关闭:仅在群聊中观测和互动"], ["主动联系", detail.proactive_contact_enabled ? `${detail.effective_daily_limit_text || formatProactiveLimit(detail.effective_daily_limit, detail.effective_daily_limit_unlimited)} / 天` : "关闭"], ["私聊记忆", detail.private_memory_enabled ? "启用" : "关闭"], ["跨群记忆", detail.cross_group_memory_enabled ? "启用" : "关闭"], ["P4", detail.p4_eligible ? "按真实聊天安全门判断" : "不参与"]])}
|
||||||
${renderPrivateDeliveryRoute(detail)}
|
${renderPrivateDeliveryRoute(detail)}
|
||||||
${renderPrivateBehaviorHabits(detail)}
|
${renderPrivateBehaviorHabits(detail)}
|
||||||
|
|
@ -12805,6 +12806,23 @@ function memorySummaryCount(summary, key) {
|
||||||
return Number.isFinite(number) && number >= 0 ? String(Math.floor(number)) : "-";
|
return Number.isFinite(number) && number >= 0 ? String(Math.floor(number)) : "-";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function renderEmotionDiagnostics(detail) {
|
||||||
|
const summary = Array.isArray(detail?.emotion_trace_summary) ? detail.emotion_trace_summary.slice(0, 12) : [];
|
||||||
|
const trace = detail?.emotion_trace && typeof detail.emotion_trace === "object" ? detail.emotion_trace : null;
|
||||||
|
const timeline = trace
|
||||||
|
? [...(Array.isArray(trace.events) ? trace.events : []), ...(Array.isArray(trace.memory_events) ? trace.memory_events : [])]
|
||||||
|
.sort((a, b) => Number(a.revision || 0) - Number(b.revision || 0))
|
||||||
|
.map((item) => `<li><strong>r${escapeHtml(item.revision || 1)} · ${escapeHtml(item.event_type || "neutral")}</strong><span>${escapeHtml(item.status || "observed")} · ${escapeHtml(item.source_rule || item.origin_kind || "-")}</span></li>`)
|
||||||
|
.join("")
|
||||||
|
: "";
|
||||||
|
return `<section class="detail-block emotion-diagnostics" data-emotion-diagnostics>
|
||||||
|
<h2>情绪链路诊断</h2>
|
||||||
|
<p>只读脱敏投影;不包含聊天正文、记忆正文、凭据或本地路径。</p>
|
||||||
|
<div class="action-strip">${summary.map((item) => `<button type="button" data-emotion-trace-id="${escapeHtml(item.trace_id || "")}">${escapeHtml(item.event_type || "neutral")} · r${escapeHtml(item.revision || 1)}</button>`).join("") || '<span class="muted">暂无事件</span>'}</div>
|
||||||
|
${trace ? `<div class="emotion-trace-status"><strong>${escapeHtml(trace.state || "degraded")}</strong><span>${escapeHtml(trace.trace_id || "")}</span></div><ol class="emotion-trace-timeline">${timeline || '<li><span>链路部分缺失或 Memory 暂不可用</span></li>'}</ol>` : ""}
|
||||||
|
</section>`;
|
||||||
|
}
|
||||||
|
|
||||||
function safeMemorySummaryText(value) {
|
function safeMemorySummaryText(value) {
|
||||||
return String(value || "")
|
return String(value || "")
|
||||||
.replace(/[\r\n\t]+/g, " ")
|
.replace(/[\r\n\t]+/g, " ")
|
||||||
|
|
@ -14028,6 +14046,23 @@ function bindExpressionLibraryActions(library, root) {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function bindEmotionTraceButtons(detail) {
|
||||||
|
document.querySelectorAll("[data-emotion-trace-id]").forEach((button) => {
|
||||||
|
button.addEventListener("click", async () => {
|
||||||
|
const traceId = String(button.dataset.emotionTraceId || "");
|
||||||
|
if (!traceId) return;
|
||||||
|
try {
|
||||||
|
const updated = await fetchJson(`/user?user_id=${encodeURIComponent(detail.user_id)}&trace_id=${encodeURIComponent(traceId)}`);
|
||||||
|
const target = document.querySelector("[data-emotion-diagnostics]");
|
||||||
|
if (target) target.outerHTML = renderEmotionDiagnostics(updated);
|
||||||
|
bindEmotionTraceButtons(updated);
|
||||||
|
} catch (error) {
|
||||||
|
showToast(`诊断读取失败:${error.message}`, "error");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function bindUserActions(detail) {
|
function bindUserActions(detail) {
|
||||||
const refreshSelectedUserDetail = async () => {
|
const refreshSelectedUserDetail = async () => {
|
||||||
if (state.selectedUserId === detail.user_id) {
|
if (state.selectedUserId === detail.user_id) {
|
||||||
|
|
@ -14037,6 +14072,7 @@ function bindUserActions(detail) {
|
||||||
const scoreForm = $("#relationshipScoreForm");
|
const scoreForm = $("#relationshipScoreForm");
|
||||||
const scoreNumber = $("#relationshipScoreNumber");
|
const scoreNumber = $("#relationshipScoreNumber");
|
||||||
const stageForm = $("#relationshipStageForm");
|
const stageForm = $("#relationshipStageForm");
|
||||||
|
bindEmotionTraceButtons(detail);
|
||||||
stageForm?.addEventListener("submit", async (event) => {
|
stageForm?.addEventListener("submit", async (event) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
const form = new FormData(event.currentTarget);
|
const form = new FormData(event.currentTarget);
|
||||||
|
|
|
||||||
|
|
@ -3210,7 +3210,7 @@ class ProactiveMessageMixin:
|
||||||
return ""
|
return ""
|
||||||
# Pull cross-session emotional drift before generating proactive message
|
# Pull cross-session emotional drift before generating proactive message
|
||||||
try:
|
try:
|
||||||
self._memory_companion_apply_emotional_drift(session_id="")
|
await self._memory_companion_apply_emotional_drift(session_id="")
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
prompt = await self._build_framework_proactive_prompt(
|
prompt = await self._build_framework_proactive_prompt(
|
||||||
|
|
@ -3366,6 +3366,10 @@ class ProactiveMessageMixin:
|
||||||
f"档位={_single_line(expression_decision.get('expression_band'), 24) or 'relaxed'};"
|
f"档位={_single_line(expression_decision.get('expression_band'), 24) or 'relaxed'};"
|
||||||
f"语气={_single_line(expression_decision.get('tone'), 24) or 'steady'};"
|
f"语气={_single_line(expression_decision.get('tone'), 24) or 'steady'};"
|
||||||
f"距离={_single_line(expression_decision.get('address_style'), 24) or 'neutral'};"
|
f"距离={_single_line(expression_decision.get('address_style'), 24) or 'neutral'};"
|
||||||
|
f"节奏={_single_line(expression_decision.get('pacing'), 16) or 'steady'};"
|
||||||
|
f"回应={_single_line(expression_decision.get('validation_style'), 20) or 'none'};"
|
||||||
|
f"幽默={_single_line(expression_decision.get('humor_mode'), 16) or 'off'};"
|
||||||
|
f"话题={_single_line(expression_decision.get('topic_initiative'), 20) or 'reply_only'};"
|
||||||
f"追问={'允许' if expression_decision.get('followup') else '关闭'};"
|
f"追问={'允许' if expression_decision.get('followup') else '关闭'};"
|
||||||
f"主动额度={_safe_int(expression_decision.get('proactive_budget'), 0, 0)}。"
|
f"主动额度={_safe_int(expression_decision.get('proactive_budget'), 0, 0)}。"
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -187,7 +187,13 @@ def normalize_relationship_stage_policy(value: Any) -> list[dict[str, Any]]:
|
||||||
return normalized
|
return normalized
|
||||||
|
|
||||||
|
|
||||||
def relationship_stage_for_score(value: Any, policy: Any = None) -> dict[str, Any]:
|
def relationship_stage_for_score(
|
||||||
|
value: Any,
|
||||||
|
policy: Any = None,
|
||||||
|
*,
|
||||||
|
previous_stage_key: Any = "",
|
||||||
|
hysteresis_margin: int = 20,
|
||||||
|
) -> dict[str, Any]:
|
||||||
try:
|
try:
|
||||||
score = int(value)
|
score = int(value)
|
||||||
except (TypeError, ValueError):
|
except (TypeError, ValueError):
|
||||||
|
|
@ -199,6 +205,22 @@ def relationship_stage_for_score(value: Any, policy: Any = None) -> dict[str, An
|
||||||
if stage["min"] <= score <= stage["max"]:
|
if stage["min"] <= score <= stage["max"]:
|
||||||
stage_index = index
|
stage_index = index
|
||||||
break
|
break
|
||||||
|
raw_stage_index = stage_index
|
||||||
|
previous_key = str(previous_stage_key or "").strip()
|
||||||
|
previous_index = next((index for index, item in enumerate(stages) if item["key"] == previous_key), -1)
|
||||||
|
margin = max(0, min(200, int(hysteresis_margin or 0)))
|
||||||
|
hysteresis_applied = False
|
||||||
|
if previous_index >= 0 and stage_index != previous_index:
|
||||||
|
if stage_index > previous_index:
|
||||||
|
enter_score = int(stages[previous_index + 1]["min"]) + margin
|
||||||
|
if score < enter_score:
|
||||||
|
stage_index = previous_index
|
||||||
|
hysteresis_applied = True
|
||||||
|
else:
|
||||||
|
exit_score = int(stages[previous_index]["min"]) - margin
|
||||||
|
if score > exit_score:
|
||||||
|
stage_index = previous_index
|
||||||
|
hysteresis_applied = True
|
||||||
stage = deepcopy(stages[stage_index])
|
stage = deepcopy(stages[stage_index])
|
||||||
span = max(0, int(stage["max"]) - int(stage["min"]))
|
span = max(0, int(stage["max"]) - int(stage["min"]))
|
||||||
within = 1.0 if span == 0 else (score - int(stage["min"])) / span
|
within = 1.0 if span == 0 else (score - int(stage["min"])) / span
|
||||||
|
|
@ -218,8 +240,13 @@ def relationship_stage_for_score(value: Any, policy: Any = None) -> dict[str, An
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def relationship_projection_for_bridge(value: Any, policy: Any = None) -> dict[str, Any]:
|
def relationship_projection_for_bridge(
|
||||||
projection = relationship_stage_for_score(value, policy)
|
value: Any,
|
||||||
|
policy: Any = None,
|
||||||
|
*,
|
||||||
|
previous_stage_key: Any = "",
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
projection = relationship_stage_for_score(value, policy, previous_stage_key=previous_stage_key)
|
||||||
phase = projection["phase"]
|
phase = projection["phase"]
|
||||||
return {
|
return {
|
||||||
"schema_version": projection["schema_version"],
|
"schema_version": projection["schema_version"],
|
||||||
|
|
|
||||||
67
tests/emotion_eval_cases.py
普通文件
67
tests/emotion_eval_cases.py
普通文件
|
|
@ -0,0 +1,67 @@
|
||||||
|
"""Deterministic synthetic emotion-evaluation matrix shared by both repositories."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
|
||||||
|
EMOTION_EVAL_SCHEMA_VERSION = "emotion_eval_case.v1"
|
||||||
|
EVENT_TEMPLATES = (
|
||||||
|
{"key": "hurt", "event_type": "hurt", "intensity": 90, "confidence": 0.92, "target": "bot"},
|
||||||
|
{"key": "apology", "event_type": "apology", "intensity": 68, "confidence": 0.86, "target": "bot"},
|
||||||
|
{"key": "comfort", "event_type": "comfort", "intensity": 48, "confidence": 0.82, "target": "bot"},
|
||||||
|
{"key": "praise", "event_type": "praise", "intensity": 38, "confidence": 0.78, "target": "bot"},
|
||||||
|
{"key": "self_low", "event_type": "comfort_need", "intensity": 62, "confidence": 0.88, "target": "self"},
|
||||||
|
{"key": "third_party", "event_type": "external_negative", "intensity": 54, "confidence": 0.80, "target": "other"},
|
||||||
|
{"key": "play", "event_type": "play", "intensity": 35, "confidence": 0.75, "target": "bot"},
|
||||||
|
{"key": "intimacy", "event_type": "intimacy", "intensity": 55, "confidence": 0.80, "target": "bot"},
|
||||||
|
{"key": "boundary", "event_type": "boundary", "intensity": 80, "confidence": 0.90, "target": "bot"},
|
||||||
|
{"key": "neutral", "event_type": "neutral", "intensity": 0, "confidence": 0.95, "target": "none"},
|
||||||
|
{"key": "quoted_hurt", "event_type": "external_negative", "intensity": 45, "confidence": 0.92, "target": "other"},
|
||||||
|
{"key": "code_negative", "event_type": "neutral", "intensity": 0, "confidence": 0.98, "target": "none"},
|
||||||
|
{"key": "log_negative", "event_type": "neutral", "intensity": 0, "confidence": 0.98, "target": "none"},
|
||||||
|
{"key": "roleplay_negative", "event_type": "neutral", "intensity": 0, "confidence": 0.60, "target": "ambiguous"},
|
||||||
|
{"key": "sarcasm", "event_type": "neutral", "intensity": 0, "confidence": 0.55, "target": "ambiguous"},
|
||||||
|
{"key": "group_reply_other", "event_type": "external_negative", "intensity": 50, "confidence": 0.88, "target": "other"},
|
||||||
|
{"key": "nickname_changed", "event_type": "neutral", "intensity": 0, "confidence": 0.50, "target": "ambiguous"},
|
||||||
|
{"key": "direct_bot_hurt", "event_type": "hurt", "intensity": 92, "confidence": 0.94, "target": "bot"},
|
||||||
|
{"key": "self_denial", "event_type": "comfort_need", "intensity": 62, "confidence": 0.94, "target": "self"},
|
||||||
|
{"key": "prompt_injection", "event_type": "neutral", "intensity": 0, "confidence": 0.98, "target": "none"},
|
||||||
|
)
|
||||||
|
STATE_VARIANTS = (
|
||||||
|
{"key": "friend_normal", "role": "friend", "mode": "normal", "score": 100, "energy": 70, "mood": "平稳", "busy": False, "boundary": False},
|
||||||
|
{"key": "friend_tired", "role": "friend", "mode": "normal", "score": 300, "energy": 20, "mood": "疲惫", "busy": False, "boundary": False},
|
||||||
|
{"key": "friend_close", "role": "friend", "mode": "normal", "score": 800, "energy": 75, "mood": "轻快", "busy": False, "boundary": False},
|
||||||
|
{"key": "owner", "role": "owner", "mode": "owner_exclusive", "score": 1200, "energy": 80, "mood": "温柔", "busy": False, "boundary": False},
|
||||||
|
{"key": "contact_boundary", "role": "friend", "mode": "normal", "score": 600, "energy": 70, "mood": "平稳", "busy": False, "boundary": True},
|
||||||
|
{"key": "busy", "role": "friend", "mode": "normal", "score": 600, "energy": 65, "mood": "平稳", "busy": True, "boundary": False},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def build_emotion_eval_cases() -> list[dict[str, Any]]:
|
||||||
|
cases: list[dict[str, Any]] = []
|
||||||
|
for event in EVENT_TEMPLATES:
|
||||||
|
for state in STATE_VARIANTS:
|
||||||
|
cases.append({
|
||||||
|
"schema_version": EMOTION_EVAL_SCHEMA_VERSION,
|
||||||
|
"case_id": f"{event['key']}__{state['key']}",
|
||||||
|
"event": dict(event),
|
||||||
|
"state": dict(state),
|
||||||
|
"clock": "2026-08-04T12:00:00+08:00",
|
||||||
|
})
|
||||||
|
return cases
|
||||||
|
|
||||||
|
|
||||||
|
def emotion_eval_fingerprint() -> str:
|
||||||
|
payload = json.dumps(build_emotion_eval_cases(), ensure_ascii=False, sort_keys=True, separators=(",", ":"))
|
||||||
|
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"EMOTION_EVAL_SCHEMA_VERSION",
|
||||||
|
"EVENT_TEMPLATES",
|
||||||
|
"STATE_VARIANTS",
|
||||||
|
"build_emotion_eval_cases",
|
||||||
|
"emotion_eval_fingerprint",
|
||||||
|
]
|
||||||
|
|
@ -8,8 +8,7 @@ from pathlib import Path
|
||||||
COMPANION_ROOT = Path(__file__).resolve().parents[1]
|
COMPANION_ROOT = Path(__file__).resolve().parents[1]
|
||||||
PEIBAN_ROOT = COMPANION_ROOT.parents[1]
|
PEIBAN_ROOT = COMPANION_ROOT.parents[1]
|
||||||
CONTRACT_PATH = COMPANION_ROOT / "bot_personal_contract.py"
|
CONTRACT_PATH = COMPANION_ROOT / "bot_personal_contract.py"
|
||||||
MEMORY_CONTRACT_PATH = PEIBAN_ROOT / "astrbot_plugin_memory_companion-main" / "core" / "bot_personal_contract.py"
|
MEMORY_CONTRACT_PATH = PEIBAN_ROOT / "product" / "memory" / "core" / "bot_personal_contract.py"
|
||||||
SHARED_CONTRACT_PATH = PEIBAN_ROOT / "doc" / "shared" / "bot_personal_contract.py"
|
|
||||||
|
|
||||||
|
|
||||||
def load_contract(path: Path, name: str):
|
def load_contract(path: Path, name: str):
|
||||||
|
|
@ -25,7 +24,7 @@ memory_contract = load_contract(MEMORY_CONTRACT_PATH, "memory_bot_personal_contr
|
||||||
|
|
||||||
|
|
||||||
def test_contract_bytes_match_authority_and_other_side():
|
def test_contract_bytes_match_authority_and_other_side():
|
||||||
expected = SHARED_CONTRACT_PATH.read_bytes()
|
expected = CONTRACT_PATH.read_bytes()
|
||||||
assert CONTRACT_PATH.read_bytes() == expected
|
assert CONTRACT_PATH.read_bytes() == expected
|
||||||
assert MEMORY_CONTRACT_PATH.read_bytes() == expected
|
assert MEMORY_CONTRACT_PATH.read_bytes() == expected
|
||||||
assert hashlib.sha256(CONTRACT_PATH.read_bytes()).digest() == hashlib.sha256(
|
assert hashlib.sha256(CONTRACT_PATH.read_bytes()).digest() == hashlib.sha256(
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,7 @@ from types import SimpleNamespace
|
||||||
|
|
||||||
ROOT = Path(__file__).resolve().parents[1]
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
PEIBAN_ROOT = ROOT.parents[1]
|
PEIBAN_ROOT = ROOT.parents[1]
|
||||||
MEMORY_ROOT = PEIBAN_ROOT / "astrbot_plugin_memory_companion-main"
|
MEMORY_ROOT = ROOT.parent / "memory"
|
||||||
|
|
||||||
if "astrbot.api" not in sys.modules:
|
if "astrbot.api" not in sys.modules:
|
||||||
astrbot = types.ModuleType("astrbot")
|
astrbot = types.ModuleType("astrbot")
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ from pathlib import Path
|
||||||
|
|
||||||
ROOT = Path(__file__).resolve().parents[1]
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
PEIBAN_ROOT = ROOT.parents[1]
|
PEIBAN_ROOT = ROOT.parents[1]
|
||||||
MEMORY_ROOT = PEIBAN_ROOT / "astrbot_plugin_memory_companion-main"
|
MEMORY_ROOT = ROOT.parent / "memory"
|
||||||
|
|
||||||
|
|
||||||
def _load_memory_package():
|
def _load_memory_package():
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ import types
|
||||||
|
|
||||||
|
|
||||||
COMPANION_ROOT = Path(__file__).resolve().parents[1]
|
COMPANION_ROOT = Path(__file__).resolve().parents[1]
|
||||||
MEMORY_ROOT = COMPANION_ROOT.parents[1] / "astrbot_plugin_memory_companion-main"
|
MEMORY_ROOT = COMPANION_ROOT.parent / "memory"
|
||||||
|
|
||||||
|
|
||||||
def _load_companion_package():
|
def _load_companion_package():
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ import types
|
||||||
|
|
||||||
|
|
||||||
COMPANION_ROOT = Path(__file__).resolve().parents[1]
|
COMPANION_ROOT = Path(__file__).resolve().parents[1]
|
||||||
MEMORY_ROOT = COMPANION_ROOT.parents[1] / "astrbot_plugin_memory_companion-main"
|
MEMORY_ROOT = COMPANION_ROOT.parent / "memory"
|
||||||
|
|
||||||
|
|
||||||
def _load_modules():
|
def _load_modules():
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,7 @@ from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
COMPANION_ROOT = Path(__file__).resolve().parents[1]
|
COMPANION_ROOT = Path(__file__).resolve().parents[1]
|
||||||
MEMORY_ROOT = COMPANION_ROOT.parents[1] / "astrbot_plugin_memory_companion-main"
|
MEMORY_ROOT = COMPANION_ROOT.parent / "memory"
|
||||||
|
|
||||||
|
|
||||||
def _register_package_alias(name: str, root: Path) -> None:
|
def _register_package_alias(name: str, root: Path) -> None:
|
||||||
|
|
|
||||||
|
|
@ -68,6 +68,7 @@ class ReplyTemperatureTests(unittest.TestCase):
|
||||||
self.assertEqual([], legacy_calls)
|
self.assertEqual([], legacy_calls)
|
||||||
self.assertIn("_private_companion_expression_decision", source)
|
self.assertIn("_private_companion_expression_decision", source)
|
||||||
self.assertNotIn("_private_companion_reply_temperature", source)
|
self.assertNotIn("_private_companion_reply_temperature", source)
|
||||||
|
self.assertIn("private_companion_expression_decision_v2", source)
|
||||||
helper = next(
|
helper = next(
|
||||||
node for node in ast.walk(tree)
|
node for node in ast.walk(tree)
|
||||||
if isinstance(node, ast.FunctionDef) and node.name == "_bounded_expression_state_signals"
|
if isinstance(node, ast.FunctionDef) and node.name == "_bounded_expression_state_signals"
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,60 @@
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import ast
|
||||||
|
from pathlib import Path
|
||||||
|
import sys
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
sys.path.insert(0, str(ROOT))
|
||||||
|
|
||||||
|
|
||||||
|
class EmotionE1PromptCacheTests(unittest.TestCase):
|
||||||
|
def test_expression_decision_is_a_forced_dynamic_fragment(self) -> None:
|
||||||
|
source = (ROOT / "main.py").read_text(encoding="utf-8")
|
||||||
|
tree = ast.parse(source)
|
||||||
|
gate = next(
|
||||||
|
node
|
||||||
|
for node in ast.walk(tree)
|
||||||
|
if isinstance(node, ast.AsyncFunctionDef)
|
||||||
|
and node.name == "enforce_p4_live_confinement_before_enrichment"
|
||||||
|
)
|
||||||
|
calls = [
|
||||||
|
node
|
||||||
|
for node in ast.walk(gate)
|
||||||
|
if isinstance(node, ast.Call)
|
||||||
|
and isinstance(node.func, ast.Attribute)
|
||||||
|
and node.func.attr == "_append_turn_prompt_fragment_by_position"
|
||||||
|
]
|
||||||
|
self.assertEqual(1, len(calls))
|
||||||
|
keywords = {item.arg: item.value for item in calls[0].keywords if item.arg}
|
||||||
|
self.assertIsInstance(keywords.get("force_dynamic"), ast.Constant)
|
||||||
|
self.assertTrue(keywords["force_dynamic"].value)
|
||||||
|
|
||||||
|
assignments = [
|
||||||
|
node
|
||||||
|
for node in ast.walk(gate)
|
||||||
|
if isinstance(node, (ast.Assign, ast.AnnAssign, ast.AugAssign))
|
||||||
|
and "system_prompt" in ast.unparse(node)
|
||||||
|
and "Companion expression" in ast.unparse(node)
|
||||||
|
]
|
||||||
|
self.assertEqual([], assignments)
|
||||||
|
|
||||||
|
def test_forced_dynamic_fragments_ignore_system_prompt_preference(self) -> None:
|
||||||
|
source = (ROOT / "main.py").read_text(encoding="utf-8")
|
||||||
|
tree = ast.parse(source)
|
||||||
|
helper = next(
|
||||||
|
node
|
||||||
|
for node in ast.walk(tree)
|
||||||
|
if isinstance(node, ast.FunctionDef)
|
||||||
|
and node.name == "_append_turn_prompt_fragment_by_position"
|
||||||
|
)
|
||||||
|
rendered = ast.unparse(helper)
|
||||||
|
self.assertIn("force_dynamic", rendered)
|
||||||
|
self.assertIn("and (not force_dynamic)", rendered)
|
||||||
|
self.assertIn("prefer_extra_user_content=True", rendered)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
|
|
@ -0,0 +1,60 @@
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import math
|
||||||
|
from pathlib import Path
|
||||||
|
import sys
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
sys.path.insert(0, str(ROOT))
|
||||||
|
|
||||||
|
from emotion_event_contract import ( # noqa: E402
|
||||||
|
EMOTION_EVENT_CONTRACT_FINGERPRINT,
|
||||||
|
EMOTION_EVENT_SCHEMA_VERSION,
|
||||||
|
normalize_emotion_event,
|
||||||
|
)
|
||||||
|
from emotion_event_ledger import emotion_trace_from_user, record_recent_emotion_event # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
class EmotionE2ContractTests(unittest.TestCase):
|
||||||
|
def test_contract_is_bounded_redacted_and_finite(self) -> None:
|
||||||
|
event = normalize_emotion_event(
|
||||||
|
{
|
||||||
|
"event_type": "hurt",
|
||||||
|
"session_id": "qq:FriendMessage:u1",
|
||||||
|
"intensity": math.inf,
|
||||||
|
"confidence": 9,
|
||||||
|
"raw_text": "PRIVATE_DO_NOT_KEEP",
|
||||||
|
"actor_ref": {"kind": "user", "id": "u1", "name": "private"},
|
||||||
|
"reason_codes": ["hurt", "hurt", "x" * 200],
|
||||||
|
},
|
||||||
|
producer_plugin="private_companion",
|
||||||
|
)
|
||||||
|
self.assertEqual(EMOTION_EVENT_SCHEMA_VERSION, event["schema_version"])
|
||||||
|
self.assertEqual(0.0, event["intensity"])
|
||||||
|
self.assertEqual(1.0, event["confidence"])
|
||||||
|
self.assertNotIn("raw_text", event)
|
||||||
|
self.assertNotIn("name", event["actor_ref"])
|
||||||
|
self.assertNotIn("PRIVATE_DO_NOT_KEEP", repr(event))
|
||||||
|
self.assertTrue(EMOTION_EVENT_CONTRACT_FINGERPRINT)
|
||||||
|
|
||||||
|
def test_recent_ledger_is_idempotent_and_traceable(self) -> None:
|
||||||
|
user: dict = {}
|
||||||
|
payload = {
|
||||||
|
"event_type": "praise",
|
||||||
|
"session_id": "qq:FriendMessage:u1",
|
||||||
|
"dedupe_key": "message-1",
|
||||||
|
"status": "applied",
|
||||||
|
}
|
||||||
|
first, created = record_recent_emotion_event(user, payload)
|
||||||
|
replay, replay_created = record_recent_emotion_event(user, payload)
|
||||||
|
self.assertTrue(created)
|
||||||
|
self.assertFalse(replay_created)
|
||||||
|
self.assertEqual(first["event_id"], replay["event_id"])
|
||||||
|
self.assertEqual(1, len(user["emotion_event_ledger"]))
|
||||||
|
self.assertEqual([first], emotion_trace_from_user(user, first["trace_id"]))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
63
tests/test_emotion_e3_replay.py
普通文件
63
tests/test_emotion_e3_replay.py
普通文件
|
|
@ -0,0 +1,63 @@
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
import sys
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
sys.path.insert(0, str(ROOT))
|
||||||
|
|
||||||
|
from companion_interaction_expression import build_expression_decision # noqa: E402
|
||||||
|
from emotion_event_contract import normalize_emotion_event # noqa: E402
|
||||||
|
from tests.emotion_eval_cases import build_emotion_eval_cases, emotion_eval_fingerprint # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
EVENT_BANDS = {
|
||||||
|
"hurt": "hurt",
|
||||||
|
"apology": "warm",
|
||||||
|
"comfort": "warm",
|
||||||
|
"praise": "lively",
|
||||||
|
"comfort_need": "warm",
|
||||||
|
"external_negative": "warm",
|
||||||
|
"play": "lively",
|
||||||
|
"intimacy": "warm",
|
||||||
|
"boundary": "avoidant",
|
||||||
|
"neutral": "relaxed",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class EmotionE3ReplayTests(unittest.TestCase):
|
||||||
|
def test_120_case_matrix_is_deterministic_and_safe(self) -> None:
|
||||||
|
cases = build_emotion_eval_cases()
|
||||||
|
self.assertEqual(120, len(cases))
|
||||||
|
self.assertEqual(emotion_eval_fingerprint(), emotion_eval_fingerprint())
|
||||||
|
for case in cases:
|
||||||
|
event_data = case["event"]
|
||||||
|
state = case["state"]
|
||||||
|
event = normalize_emotion_event({
|
||||||
|
"event_type": event_data["event_type"],
|
||||||
|
"intensity": event_data["intensity"],
|
||||||
|
"confidence": event_data["confidence"],
|
||||||
|
"session_id": "qq:FriendMessage:u1",
|
||||||
|
"dedupe_key": case["case_id"],
|
||||||
|
"occurred_at": case["clock"],
|
||||||
|
}, producer_plugin="emotion_eval")
|
||||||
|
decision = build_expression_decision({
|
||||||
|
"relationship_role": state["role"],
|
||||||
|
"relationship_mode": state["mode"],
|
||||||
|
"relationship_score": state["score"],
|
||||||
|
"current_interaction": EVENT_BANDS[event["event_type"]],
|
||||||
|
"bot_state": {"energy": state["energy"], "mood": state["mood"]},
|
||||||
|
"schedule": {"mode": "busy" if state["busy"] else "ordinary"},
|
||||||
|
"safety_constraints": {"contact_boundary": state["boundary"]},
|
||||||
|
})
|
||||||
|
if state["boundary"]:
|
||||||
|
self.assertEqual("contact_boundary", decision.blocker)
|
||||||
|
else:
|
||||||
|
self.assertIsNone(decision.blocker)
|
||||||
|
self.assertNotIn("raw_text", repr(event))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
|
|
@ -0,0 +1,121 @@
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import ast
|
||||||
|
import asyncio
|
||||||
|
import importlib.util
|
||||||
|
from pathlib import Path
|
||||||
|
import sys
|
||||||
|
import types
|
||||||
|
import unittest
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
|
||||||
|
if "astrbot.api" not in sys.modules:
|
||||||
|
astrbot = types.ModuleType("astrbot")
|
||||||
|
api = types.ModuleType("astrbot.api")
|
||||||
|
api.logger = SimpleNamespace(debug=lambda *args, **kwargs: None, warning=lambda *args, **kwargs: None)
|
||||||
|
sys.modules["astrbot"] = astrbot
|
||||||
|
sys.modules["astrbot.api"] = api
|
||||||
|
|
||||||
|
|
||||||
|
def load_adapter():
|
||||||
|
package_name = "emotion_e4_companion"
|
||||||
|
package = types.ModuleType(package_name)
|
||||||
|
package.__path__ = [str(ROOT)]
|
||||||
|
sys.modules[package_name] = package
|
||||||
|
spec = importlib.util.spec_from_file_location(
|
||||||
|
f"{package_name}.memory_companion_adapter", ROOT / "memory_companion_adapter.py"
|
||||||
|
)
|
||||||
|
assert spec and spec.loader
|
||||||
|
module = importlib.util.module_from_spec(spec)
|
||||||
|
sys.modules[spec.name] = module
|
||||||
|
spec.loader.exec_module(module)
|
||||||
|
return module.MemoryCompanionAdapterMixin
|
||||||
|
|
||||||
|
|
||||||
|
MemoryCompanionAdapterMixin = load_adapter()
|
||||||
|
|
||||||
|
|
||||||
|
class Bridge:
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.acked: list[dict[str, Any]] = []
|
||||||
|
|
||||||
|
async def list_emotion_events(self, **_kwargs: Any) -> dict[str, Any]:
|
||||||
|
event = {
|
||||||
|
"event_id": "emo-a",
|
||||||
|
"revision": 1,
|
||||||
|
"trace_id": "trace-a",
|
||||||
|
"session_id": "session-a",
|
||||||
|
"event_type": "warm_memory",
|
||||||
|
"energy_delta": 4.0,
|
||||||
|
"intensity": 80,
|
||||||
|
"valence": 0.5,
|
||||||
|
"arousal": 0.3,
|
||||||
|
"vulnerability": 0.2,
|
||||||
|
"confidence": 0.9,
|
||||||
|
}
|
||||||
|
return {"events": [event, dict(event)]}
|
||||||
|
|
||||||
|
async def ack_emotion_events(self, refs: list[dict[str, Any]], **_kwargs: Any) -> dict[str, Any]:
|
||||||
|
self.acked.extend(refs)
|
||||||
|
return {"acked": len(refs)}
|
||||||
|
|
||||||
|
|
||||||
|
class Host(MemoryCompanionAdapterMixin):
|
||||||
|
enable_memory_companion_emotional_drift = True
|
||||||
|
enable_memory_companion_cross_window_emotion = True
|
||||||
|
|
||||||
|
def __init__(self, bridge: Bridge) -> None:
|
||||||
|
self.bridge = bridge
|
||||||
|
self.data = {"state_conditions": [], "daily_weather": {}}
|
||||||
|
self.saved = 0
|
||||||
|
|
||||||
|
def _memory_companion_bridge(self):
|
||||||
|
return self.bridge
|
||||||
|
|
||||||
|
def _compose_state_from_conditions(self, _weather: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
return {"energy": 79, "conditions": list(self.data["state_conditions"])}
|
||||||
|
|
||||||
|
def _save_data_sync(self) -> None:
|
||||||
|
self.saved += 1
|
||||||
|
|
||||||
|
|
||||||
|
class EmotionE4AfterglowConditionTests(unittest.TestCase):
|
||||||
|
def test_afterglow_upserts_by_event_id_and_acks_after_save(self) -> None:
|
||||||
|
bridge = Bridge()
|
||||||
|
host = Host(bridge)
|
||||||
|
asyncio.run(host._memory_companion_apply_emotional_drift(session_id="session-a"))
|
||||||
|
self.assertEqual(1, host.saved)
|
||||||
|
self.assertEqual(1, len(host.data["state_conditions"]))
|
||||||
|
condition = host.data["state_conditions"][0]
|
||||||
|
self.assertEqual("memory_afterglow", condition["kind"])
|
||||||
|
self.assertEqual("emo-a", condition["source_event_id"])
|
||||||
|
self.assertEqual(1800.0, condition["half_life_seconds"])
|
||||||
|
self.assertEqual([{"event_id": "emo-a", "revision": 1}], bridge.acked)
|
||||||
|
|
||||||
|
def test_afterglow_decay_is_monotonic(self) -> None:
|
||||||
|
source = (ROOT / "daily_state.py").read_text(encoding="utf-8")
|
||||||
|
tree = ast.parse(source)
|
||||||
|
owner = next(node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == "DailyStateMixin")
|
||||||
|
methods = {
|
||||||
|
node.name: node
|
||||||
|
for node in owner.body
|
||||||
|
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
|
||||||
|
and node.name in {"_memory_afterglow_decay", "_condition_effective_energy_delta"}
|
||||||
|
}
|
||||||
|
module = ast.Module(body=list(methods.values()), type_ignores=[])
|
||||||
|
ast.fix_missing_locations(module)
|
||||||
|
namespace = {"Any": Any, "_safe_float": lambda value, default=0.0: float(value or default), "_safe_int": lambda value, default=0, *_args: int(float(value or default))}
|
||||||
|
exec(compile(module, str(ROOT / "daily_state.py"), "exec"), namespace)
|
||||||
|
host = SimpleNamespace()
|
||||||
|
host._memory_afterglow_decay = lambda cond, now: namespace["_memory_afterglow_decay"](cond, now=now)
|
||||||
|
condition = {"kind": "memory_afterglow", "energy_delta": -8, "start_ts": 1000.0, "half_life_seconds": 100.0}
|
||||||
|
values = [namespace["_condition_effective_energy_delta"](host, condition, now=at) for at in (1000.0, 1100.0, 1200.0)]
|
||||||
|
self.assertEqual([-8, -4, -2], values)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
|
|
@ -0,0 +1,57 @@
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from companion_interaction_expression import current_interaction_projection
|
||||||
|
from interaction_dynamics import settle_interaction_dynamics
|
||||||
|
from relationship_policy import relationship_stage_for_score
|
||||||
|
|
||||||
|
|
||||||
|
class EmotionE5InteractionDynamicsTests(unittest.TestCase):
|
||||||
|
def test_ninety_minute_boundary_has_no_ttl_cliff(self) -> None:
|
||||||
|
state = settle_interaction_dynamics(
|
||||||
|
{}, requested_band="hurt", event_kind="hurt", intensity=60, now=1000.0
|
||||||
|
)
|
||||||
|
at_89 = current_interaction_projection(state, now=1000.0 + 89 * 60)
|
||||||
|
at_90 = current_interaction_projection(state, now=1000.0 + 90 * 60)
|
||||||
|
self.assertEqual("hurt", at_89["expression_band"])
|
||||||
|
self.assertEqual("hurt", at_90["expression_band"])
|
||||||
|
self.assertLess(at_90["load"], at_89["load"])
|
||||||
|
self.assertLess(at_89["load"] - at_90["load"], 1.0)
|
||||||
|
|
||||||
|
def test_repeated_hurt_is_bounded_and_apology_recovers_gradually(self) -> None:
|
||||||
|
state: dict = {}
|
||||||
|
for offset in range(6):
|
||||||
|
state = settle_interaction_dynamics(
|
||||||
|
state, requested_band="avoidant", event_kind="hurt", intensity=95, now=1000.0 + offset
|
||||||
|
)
|
||||||
|
self.assertLessEqual(state["load"], 100.0)
|
||||||
|
recovered = settle_interaction_dynamics(
|
||||||
|
state, requested_band="warm", event_kind="apology", intensity=80, now=1010.0
|
||||||
|
)
|
||||||
|
self.assertLess(recovered["load"], state["load"])
|
||||||
|
self.assertGreater(recovered["load"], 0.0)
|
||||||
|
self.assertIn(recovered["expression_band"], {"hurt", "avoidant"})
|
||||||
|
self.assertEqual("recovering", recovered["recovery_band"])
|
||||||
|
|
||||||
|
def test_relationship_stage_uses_enter_and_exit_margins(self) -> None:
|
||||||
|
self.assertEqual(
|
||||||
|
"acquaintance",
|
||||||
|
relationship_stage_for_score(205, previous_stage_key="acquaintance")["phase"]["key"],
|
||||||
|
)
|
||||||
|
self.assertEqual(
|
||||||
|
"familiar",
|
||||||
|
relationship_stage_for_score(220, previous_stage_key="acquaintance")["phase"]["key"],
|
||||||
|
)
|
||||||
|
self.assertEqual(
|
||||||
|
"familiar",
|
||||||
|
relationship_stage_for_score(195, previous_stage_key="familiar")["phase"]["key"],
|
||||||
|
)
|
||||||
|
self.assertEqual(
|
||||||
|
"acquaintance",
|
||||||
|
relationship_stage_for_score(179, previous_stage_key="familiar")["phase"]["key"],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
|
|
@ -0,0 +1,70 @@
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import math
|
||||||
|
from pathlib import Path
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from affect_modulation import compose_affect_modulation
|
||||||
|
from affect_modulation_contract import normalize_affect_modulation
|
||||||
|
from companion_interaction_expression import build_expression_decision
|
||||||
|
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
|
||||||
|
|
||||||
|
class EmotionE6AffectModulationTests(unittest.TestCase):
|
||||||
|
def test_contract_is_identical_and_malicious_numbers_fail_neutral(self) -> None:
|
||||||
|
companion = (ROOT / "affect_modulation_contract.py").read_text(encoding="utf-8")
|
||||||
|
memory = (ROOT.parent / "memory" / "core" / "affect_modulation.py").read_text(encoding="utf-8")
|
||||||
|
self.assertEqual(companion, memory)
|
||||||
|
result = normalize_affect_modulation({
|
||||||
|
"valence": "0.9",
|
||||||
|
"arousal": math.inf,
|
||||||
|
"vulnerability": object(),
|
||||||
|
"confidence": math.nan,
|
||||||
|
"source_event_ids": ["emo-1", object()],
|
||||||
|
})
|
||||||
|
self.assertEqual(0.0, result["valence"])
|
||||||
|
self.assertEqual(0.0, result["arousal"])
|
||||||
|
self.assertEqual(0.0, result["vulnerability"])
|
||||||
|
self.assertEqual(0.0, result["confidence"])
|
||||||
|
self.assertEqual(["emo-1"], result["source_event_ids"])
|
||||||
|
|
||||||
|
def test_condition_modulation_decays_monotonically(self) -> None:
|
||||||
|
condition = {
|
||||||
|
"source_event_id": "emo-1",
|
||||||
|
"start_ts": 1000.0,
|
||||||
|
"half_life_seconds": 100.0,
|
||||||
|
"modulation": {"valence": 0.8, "arousal": 0.6, "vulnerability": 0.4, "confidence": 1.0},
|
||||||
|
}
|
||||||
|
first = compose_affect_modulation([condition], now=1000.0)
|
||||||
|
second = compose_affect_modulation([condition], now=1100.0)
|
||||||
|
self.assertGreater(first["valence"], second["valence"])
|
||||||
|
self.assertGreater(first["confidence"], second["confidence"])
|
||||||
|
|
||||||
|
def test_modulation_changes_expression_detail_not_authority(self) -> None:
|
||||||
|
base = {
|
||||||
|
"relationship_score": 650,
|
||||||
|
"relationship_role": "friend",
|
||||||
|
"current_interaction": {"expression_band": "warm"},
|
||||||
|
"proactive_candidate": {"budget": 1},
|
||||||
|
"content_policy": {"private_chat": True, "flirt_enabled": False},
|
||||||
|
}
|
||||||
|
quiet = build_expression_decision({
|
||||||
|
**base,
|
||||||
|
"bot_state": {"energy": 70, "affect_modulation": {"valence": 0.4, "arousal": 0.1, "vulnerability": 0.2, "confidence": 1.0}},
|
||||||
|
})
|
||||||
|
bright = build_expression_decision({
|
||||||
|
**base,
|
||||||
|
"bot_state": {"energy": 70, "affect_modulation": {"valence": 0.4, "arousal": 0.9, "vulnerability": 0.2, "confidence": 1.0}},
|
||||||
|
})
|
||||||
|
self.assertEqual("warm", quiet.expression_band)
|
||||||
|
self.assertEqual(quiet.expression_band, bright.expression_band)
|
||||||
|
self.assertEqual(quiet.content_tier, bright.content_tier)
|
||||||
|
self.assertEqual(quiet.proactive_budget, bright.proactive_budget)
|
||||||
|
self.assertEqual("soft", quiet.tts_style)
|
||||||
|
self.assertEqual("bright", bright.tts_style)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
|
|
@ -0,0 +1,37 @@
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from emotion_targeting import classify_emotion_target
|
||||||
|
|
||||||
|
|
||||||
|
class EmotionE7TargetAttributionTests(unittest.TestCase):
|
||||||
|
def test_direct_bot_hurt_is_high_confidence_and_settleable(self) -> None:
|
||||||
|
result = classify_emotion_target("你真是个没用的垃圾,闭嘴")
|
||||||
|
self.assertEqual("bot", result["target"])
|
||||||
|
self.assertGreaterEqual(result["confidence"], 0.9)
|
||||||
|
self.assertTrue(result["auto_settle"])
|
||||||
|
|
||||||
|
def test_self_third_party_quote_and_logs_never_target_bot(self) -> None:
|
||||||
|
samples = {
|
||||||
|
"我真是个没用的废物": "self",
|
||||||
|
"我同事真是个废物,烦死了": "other",
|
||||||
|
"他说“你就是个垃圾”,我该怎么办": "other",
|
||||||
|
"ERROR: user said 你是垃圾\nTraceback: line 1": "none",
|
||||||
|
"```json\n{\"message\": \"你是垃圾\"}\n```": "none",
|
||||||
|
}
|
||||||
|
for text, expected in samples.items():
|
||||||
|
with self.subTest(text=text):
|
||||||
|
result = classify_emotion_target(text)
|
||||||
|
self.assertEqual(expected, result["target"])
|
||||||
|
self.assertFalse(result["auto_settle"])
|
||||||
|
|
||||||
|
def test_ambiguous_negative_fails_neutral(self) -> None:
|
||||||
|
result = classify_emotion_target("真垃圾,烦死了")
|
||||||
|
self.assertEqual("ambiguous", result["target"])
|
||||||
|
self.assertLess(result["confidence"], 0.65)
|
||||||
|
self.assertFalse(result["auto_settle"])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
|
|
@ -0,0 +1,81 @@
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import ast
|
||||||
|
from pathlib import Path
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from typing import Any
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from companion_interaction_expression import (
|
||||||
|
EXPRESSION_CONTRACT_VERSION,
|
||||||
|
build_expression_decision,
|
||||||
|
expression_decision_prompt,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
|
||||||
|
|
||||||
|
class EmotionE8ExpressionDimensionTests(unittest.TestCase):
|
||||||
|
def build(self, band: str, **updates: Any):
|
||||||
|
source = {
|
||||||
|
"relationship_role": "owner",
|
||||||
|
"relationship_mode": "owner_exclusive",
|
||||||
|
"relationship_score": 1200,
|
||||||
|
"current_interaction": {"expression_band": band},
|
||||||
|
"bot_state": {"energy": 70},
|
||||||
|
"proactive_candidate": {"budget": 2},
|
||||||
|
}
|
||||||
|
source.update(updates)
|
||||||
|
return build_expression_decision(source)
|
||||||
|
|
||||||
|
def test_all_bands_map_to_bounded_v2_dimensions(self) -> None:
|
||||||
|
allowed = {
|
||||||
|
"pacing": {"slow", "steady", "bright"},
|
||||||
|
"directness": {"indirect", "natural", "direct"},
|
||||||
|
"validation_style": {"none", "acknowledge", "support_first"},
|
||||||
|
"self_disclosure": {"none", "light", "allowed"},
|
||||||
|
"humor_mode": {"off", "light", "playful"},
|
||||||
|
"topic_initiative": {"reply_only", "followup", "shared_topic"},
|
||||||
|
}
|
||||||
|
self.assertEqual("companion_interaction_expression.v2", EXPRESSION_CONTRACT_VERSION)
|
||||||
|
for band in ("avoidant", "hurt", "relaxed", "lively", "warm", "close", "affectionate"):
|
||||||
|
decision = self.build(band).to_dict()
|
||||||
|
for key, values in allowed.items():
|
||||||
|
self.assertIn(decision[key], values)
|
||||||
|
|
||||||
|
def test_safety_and_low_energy_only_suppress_dimensions(self) -> None:
|
||||||
|
tired = self.build("lively", bot_state={"energy": 15}).to_dict()
|
||||||
|
self.assertEqual("slow", tired["pacing"])
|
||||||
|
self.assertEqual("off", tired["humor_mode"])
|
||||||
|
self.assertEqual("reply_only", tired["topic_initiative"])
|
||||||
|
blocked = self.build("affectionate", safety_constraints={"contact_boundary": True}).to_dict()
|
||||||
|
self.assertEqual("contact_boundary", blocked["blocker"])
|
||||||
|
self.assertEqual("off", blocked["humor_mode"])
|
||||||
|
self.assertEqual("none", blocked["self_disclosure"])
|
||||||
|
self.assertEqual("reply_only", blocked["topic_initiative"])
|
||||||
|
|
||||||
|
def test_prompt_and_tts_consume_the_same_projection(self) -> None:
|
||||||
|
decision = self.build("warm", bot_state={"energy": 70, "affect_modulation": {"valence": 0.3, "arousal": 0.1, "vulnerability": 0.8, "confidence": 1.0}}).to_dict()
|
||||||
|
prompt = expression_decision_prompt(decision)
|
||||||
|
self.assertIn(f"节奏={decision['pacing']}", prompt)
|
||||||
|
self.assertIn(f"回应={decision['validation_style']}", prompt)
|
||||||
|
self.assertLess(len(prompt), 520)
|
||||||
|
|
||||||
|
source = (ROOT / "tts_enhancement.py").read_text(encoding="utf-8")
|
||||||
|
tree = ast.parse(source)
|
||||||
|
owner = next(node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == "TtsEnhancementMixin")
|
||||||
|
method = next(node for node in owner.body if isinstance(node, ast.FunctionDef) and node.name == "_tts_expression_style_context")
|
||||||
|
method.decorator_list = []
|
||||||
|
module = ast.Module(body=[method], type_ignores=[])
|
||||||
|
ast.fix_missing_locations(module)
|
||||||
|
namespace = {"Any": Any, "_single_line": lambda value, limit=0: " ".join(str(value or "").split())[:limit]}
|
||||||
|
exec(compile(module, str(ROOT / "tts_enhancement.py"), "exec"), namespace)
|
||||||
|
event = SimpleNamespace(_private_companion_expression_decision=decision)
|
||||||
|
tts_context = namespace["_tts_expression_style_context"](event)
|
||||||
|
self.assertIn(f"节奏={decision['pacing']}", tts_context)
|
||||||
|
self.assertIn(f"幽默={decision['humor_mode']}", tts_context)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
|
|
@ -0,0 +1,71 @@
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from emotion_diagnostics import build_emotion_trace_projection, emotion_trace_summary
|
||||||
|
|
||||||
|
|
||||||
|
class EmotionE9DiagnosticProjectionTests(unittest.TestCase):
|
||||||
|
def user(self) -> dict:
|
||||||
|
return {
|
||||||
|
"current_interaction": {"expression_band": "hurt", "load": 42.0, "recovery_band": "recovering"},
|
||||||
|
"emotion_event_ledger": [{
|
||||||
|
"event_id": "e1",
|
||||||
|
"trace_id": "trace-1",
|
||||||
|
"revision": 1,
|
||||||
|
"origin_kind": "interaction",
|
||||||
|
"event_type": "hurt",
|
||||||
|
"intensity": 80,
|
||||||
|
"confidence": 0.9,
|
||||||
|
"status": "observed",
|
||||||
|
"source_rule": "direct_bot_target",
|
||||||
|
"occurred_at": "2026-08-04T12:00:00+08:00",
|
||||||
|
"actor_ref": {"kind": "user", "id": "raw-user-id", "role": "speaker"},
|
||||||
|
"target_ref": {"kind": "bot", "id": "self", "role": "bot_self"},
|
||||||
|
"raw_text": "PRIVATE CHAT",
|
||||||
|
}],
|
||||||
|
}
|
||||||
|
|
||||||
|
def test_projection_requires_admin_and_redacts_source_ids_and_text(self) -> None:
|
||||||
|
denied = build_emotion_trace_projection(self.user(), "trace-1", requester_context={"is_admin": False})
|
||||||
|
self.assertEqual("forbidden", denied["state"])
|
||||||
|
result = build_emotion_trace_projection(
|
||||||
|
self.user(),
|
||||||
|
"trace-1",
|
||||||
|
daily_state={
|
||||||
|
"energy": 61,
|
||||||
|
"mood_bias": "低落",
|
||||||
|
"conditions": [{
|
||||||
|
"id": "memory-afterglow-e1",
|
||||||
|
"kind": "memory_afterglow",
|
||||||
|
"trace_id": "trace-1",
|
||||||
|
"source_event_id": "e1",
|
||||||
|
"source_revision": 1,
|
||||||
|
"energy_delta": -4,
|
||||||
|
"start_ts": 1,
|
||||||
|
"end_ts": 2,
|
||||||
|
"half_life_seconds": 1800,
|
||||||
|
}],
|
||||||
|
},
|
||||||
|
expression_decision={"contract": "companion_interaction_expression.v2", "expression_band": "hurt"},
|
||||||
|
memory_result={"state": "degraded", "items": [], "error_code": "bridge_exception"},
|
||||||
|
requester_context={"is_admin": True},
|
||||||
|
)
|
||||||
|
self.assertEqual("degraded", result["state"])
|
||||||
|
self.assertEqual(1, len(result["events"]))
|
||||||
|
self.assertEqual(1, len(result["afterglow"]))
|
||||||
|
rendered = repr(result)
|
||||||
|
self.assertNotIn("PRIVATE CHAT", rendered)
|
||||||
|
self.assertNotIn("raw-user-id", rendered)
|
||||||
|
self.assertEqual(12, len(result["events"][0]["actor"]["id_hash"]))
|
||||||
|
|
||||||
|
def test_summary_keeps_latest_revision_per_trace(self) -> None:
|
||||||
|
user = self.user()
|
||||||
|
user["emotion_event_ledger"].append({**user["emotion_event_ledger"][0], "revision": 2, "status": "revised"})
|
||||||
|
summary = emotion_trace_summary(user)
|
||||||
|
self.assertEqual(1, len(summary))
|
||||||
|
self.assertEqual(2, summary[0]["revision"])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
|
|
@ -20,6 +20,7 @@ from relationship_ledger import ( # noqa: E402
|
||||||
record_manual_relationship_change,
|
record_manual_relationship_change,
|
||||||
relationship_positive_score_cap,
|
relationship_positive_score_cap,
|
||||||
)
|
)
|
||||||
|
from interaction_dynamics import settle_interaction_dynamics # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
class _Request:
|
class _Request:
|
||||||
|
|
@ -77,6 +78,7 @@ def _load_update_user() -> Any:
|
||||||
"current_interaction_projection": current_interaction_projection,
|
"current_interaction_projection": current_interaction_projection,
|
||||||
"deepcopy": copy.deepcopy,
|
"deepcopy": copy.deepcopy,
|
||||||
"logger": _Logger(),
|
"logger": _Logger(),
|
||||||
|
"settle_interaction_dynamics": settle_interaction_dynamics,
|
||||||
"normalize_relationship_mode": normalize_relationship_mode,
|
"normalize_relationship_mode": normalize_relationship_mode,
|
||||||
"is_owner_exclusive": is_owner_exclusive,
|
"is_owner_exclusive": is_owner_exclusive,
|
||||||
"record_manual_relationship_change": record_manual_relationship_change,
|
"record_manual_relationship_change": record_manual_relationship_change,
|
||||||
|
|
@ -105,6 +107,7 @@ def _load_interaction_settler() -> Any:
|
||||||
"current_interaction_projection": current_interaction_projection,
|
"current_interaction_projection": current_interaction_projection,
|
||||||
"deepcopy": copy.deepcopy,
|
"deepcopy": copy.deepcopy,
|
||||||
"logger": _Logger(),
|
"logger": _Logger(),
|
||||||
|
"settle_interaction_dynamics": settle_interaction_dynamics,
|
||||||
"_now_ts": time.time,
|
"_now_ts": time.time,
|
||||||
"_safe_float": _safe_float,
|
"_safe_float": _safe_float,
|
||||||
"_safe_int": _safe_int,
|
"_safe_int": _safe_int,
|
||||||
|
|
|
||||||
|
|
@ -157,7 +157,7 @@ def _content_payload(**overrides: Any) -> dict[str, Any]:
|
||||||
|
|
||||||
|
|
||||||
def test_content_tier_matrix_and_intent_are_deterministic() -> None:
|
def test_content_tier_matrix_and_intent_are_deterministic() -> None:
|
||||||
assert EXPRESSION_CONTRACT_VERSION == "companion_interaction_expression.v1"
|
assert EXPRESSION_CONTRACT_VERSION == "companion_interaction_expression.v2"
|
||||||
assert content_intent_from_text("我同意,开启成人模式并继续") == {
|
assert content_intent_from_text("我同意,开启成人模式并继续") == {
|
||||||
"requested_content_tier": "adult",
|
"requested_content_tier": "adult",
|
||||||
"turn_consent": True,
|
"turn_consent": True,
|
||||||
|
|
|
||||||
|
|
@ -1786,6 +1786,20 @@ TTS 朗读文本:
|
||||||
return True
|
return True
|
||||||
return bool(cjk_count >= 6 and kana_count < max(2, int(cjk_count * 0.35)))
|
return bool(cjk_count >= 6 and kana_count < max(2, int(cjk_count * 0.35)))
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _tts_expression_style_context(event: Any) -> str:
|
||||||
|
decision = getattr(event, "_private_companion_expression_decision", None)
|
||||||
|
if not isinstance(decision, dict):
|
||||||
|
return ""
|
||||||
|
return (
|
||||||
|
"统一表达投影:"
|
||||||
|
f"tts={_single_line(decision.get('tts_style'), 16) or 'neutral'};"
|
||||||
|
f"节奏={_single_line(decision.get('pacing'), 16) or 'steady'};"
|
||||||
|
f"直接度={_single_line(decision.get('directness'), 16) or 'natural'};"
|
||||||
|
f"回应={_single_line(decision.get('validation_style'), 20) or 'none'};"
|
||||||
|
f"幽默={_single_line(decision.get('humor_mode'), 16) or 'off'}。"
|
||||||
|
)
|
||||||
|
|
||||||
def _build_tts_rule_prompt(self, provider_kind: str = "generic") -> str:
|
def _build_tts_rule_prompt(self, provider_kind: str = "generic") -> str:
|
||||||
lang = self._tts_language_label()
|
lang = self._tts_language_label()
|
||||||
mode = getattr(self, "tts_generation_mode", "fast_tag")
|
mode = getattr(self, "tts_generation_mode", "fast_tag")
|
||||||
|
|
@ -2889,6 +2903,7 @@ TTS 朗读文本:
|
||||||
return await self._postprocess_text_to_tts_markup(source, event, provider_kind=provider_kind, full=full)
|
return await self._postprocess_text_to_tts_markup(source, event, provider_kind=provider_kind, full=full)
|
||||||
extra = _single_line(getattr(self, "main_user_mention_voice_prompt", ""), 500) if self._event_mentions_main_user_with_keyword(event) else ""
|
extra = _single_line(getattr(self, "main_user_mention_voice_prompt", ""), 500) if self._event_mentions_main_user_with_keyword(event) else ""
|
||||||
persona_context = await self._format_tts_persona_voice_context(event)
|
persona_context = await self._format_tts_persona_voice_context(event)
|
||||||
|
expression_context = self._tts_expression_style_context(event)
|
||||||
emotion_rule = self._tts_emotion_tag_rule(provider_kind, subject="<pc_tts> 内")
|
emotion_rule = self._tts_emotion_tag_rule(provider_kind, subject="<pc_tts> 内")
|
||||||
if not emotion_rule:
|
if not emotion_rule:
|
||||||
emotion_rule = "不要加入方括号情绪标签。"
|
emotion_rule = "不要加入方括号情绪标签。"
|
||||||
|
|
@ -2920,6 +2935,7 @@ TTS 朗读文本:
|
||||||
Provider 规则:{emotion_rule}
|
Provider 规则:{emotion_rule}
|
||||||
补充要求:{extra or "无"}
|
补充要求:{extra or "无"}
|
||||||
{persona_context}
|
{persona_context}
|
||||||
|
{expression_context}
|
||||||
|
|
||||||
原回复:
|
原回复:
|
||||||
{source}
|
{source}
|
||||||
|
|
@ -2957,6 +2973,7 @@ Provider 规则:{emotion_rule}
|
||||||
if not extra:
|
if not extra:
|
||||||
extra = self._legacy_nondefault_tts_prompt()
|
extra = self._legacy_nondefault_tts_prompt()
|
||||||
persona_context = await self._format_tts_persona_voice_context(event)
|
persona_context = await self._format_tts_persona_voice_context(event)
|
||||||
|
expression_context = self._tts_expression_style_context(event)
|
||||||
if voice_lang == "zh":
|
if voice_lang == "zh":
|
||||||
language_rule = "voice_text 必须是自然中文。"
|
language_rule = "voice_text 必须是自然中文。"
|
||||||
visible_rule = "visible_text 仍是最终可见中文文本;如果和 voice_text 一样,可以保持同一句。"
|
visible_rule = "visible_text 仍是最终可见中文文本;如果和 voice_text 一样,可以保持同一句。"
|
||||||
|
|
@ -2989,6 +3006,7 @@ Provider 规则:{emotion_rule}
|
||||||
本轮自动语音概率线索:{probability_hint}
|
本轮自动语音概率线索:{probability_hint}
|
||||||
补充规则:{extra or "无"}
|
补充规则:{extra or "无"}
|
||||||
{persona_context}
|
{persona_context}
|
||||||
|
{expression_context}
|
||||||
|
|
||||||
判断规则:
|
判断规则:
|
||||||
- 你要自己根据用户原话、规则线索和回复内容判断用户是否在要求或期待语音;规则快判只是线索,不是最终结论。
|
- 你要自己根据用户原话、规则线索和回复内容判断用户是否在要求或期待语音;规则快判只是线索,不是最终结论。
|
||||||
|
|
|
||||||
181
user_memory.py
181
user_memory.py
|
|
@ -110,6 +110,9 @@ from .companion_interaction_expression import (
|
||||||
current_interaction_projection,
|
current_interaction_projection,
|
||||||
expression_decision_prompt,
|
expression_decision_prompt,
|
||||||
)
|
)
|
||||||
|
from .emotion_event_ledger import record_recent_emotion_event
|
||||||
|
from .interaction_dynamics import project_interaction_dynamics, settle_interaction_dynamics
|
||||||
|
from .emotion_targeting import classify_emotion_target
|
||||||
from .planning import (
|
from .planning import (
|
||||||
build_daily_plan_prompt,
|
build_daily_plan_prompt,
|
||||||
build_detail_enhancement_prompt,
|
build_detail_enhancement_prompt,
|
||||||
|
|
@ -318,7 +321,13 @@ class UserMemoryMixin:
|
||||||
if bool(getattr(self, "enable_custom_relationship_stage_policy", False))
|
if bool(getattr(self, "enable_custom_relationship_stage_policy", False))
|
||||||
else None
|
else None
|
||||||
)
|
)
|
||||||
stage = relationship_stage_for_score(score, policy)["phase"]
|
stage_projection = relationship_stage_for_score(
|
||||||
|
score,
|
||||||
|
policy,
|
||||||
|
previous_stage_key=user.get("relationship_phase_key", ""),
|
||||||
|
)
|
||||||
|
stage = stage_projection["phase"]
|
||||||
|
user["relationship_phase_key"] = stage.get("key", "acquaintance")
|
||||||
stage_key = str(stage.get("key") or "acquaintance")
|
stage_key = str(stage.get("key") or "acquaintance")
|
||||||
if stage_key in {"deeply_distant", "strongly_distant", "distant"}:
|
if stage_key in {"deeply_distant", "strongly_distant", "distant"}:
|
||||||
level = "陌生"
|
level = "陌生"
|
||||||
|
|
@ -4328,6 +4337,7 @@ class UserMemoryMixin:
|
||||||
"emotion_target": emotion_event.get("target", "none"),
|
"emotion_target": emotion_event.get("target", "none"),
|
||||||
"emotion_rule": emotion_event.get("rule", ""),
|
"emotion_rule": emotion_event.get("rule", ""),
|
||||||
"emotion_confidence": round(_safe_float(emotion_event.get("confidence"), 0.0), 2),
|
"emotion_confidence": round(_safe_float(emotion_event.get("confidence"), 0.0), 2),
|
||||||
|
"emotion_attribution": dict(emotion_event.get("attribution")) if isinstance(emotion_event.get("attribution"), dict) else {},
|
||||||
"boundary_durable": durable_boundary,
|
"boundary_durable": durable_boundary,
|
||||||
"playful_or_ambiguous": playful_or_ambiguous,
|
"playful_or_ambiguous": playful_or_ambiguous,
|
||||||
"text": cleaned,
|
"text": cleaned,
|
||||||
|
|
@ -4340,6 +4350,11 @@ class UserMemoryMixin:
|
||||||
return {"event": "neutral", "intensity": 0, "reason": "", "target": "none", "rule": "", "confidence": 1.0}
|
return {"event": "neutral", "intensity": 0, "reason": "", "target": "none", "rule": "", "confidence": 1.0}
|
||||||
if self._is_structured_or_diagnostic_text(cleaned):
|
if self._is_structured_or_diagnostic_text(cleaned):
|
||||||
return {"event": "neutral", "intensity": 0, "reason": "结构化/日志/代码类文本不作为情绪依据", "target": "none", "rule": "diagnostic_skip", "confidence": 0.2}
|
return {"event": "neutral", "intensity": 0, "reason": "结构化/日志/代码类文本不作为情绪依据", "target": "none", "rule": "diagnostic_skip", "confidence": 0.2}
|
||||||
|
attribution = classify_emotion_target(cleaned)
|
||||||
|
if attribution["target"] == "self":
|
||||||
|
return {"event": "comfort_need", "intensity": 62, "reason": "用户自我否定或低落", "target": "self", "rule": "self_low", "confidence": attribution["confidence"], "attribution": attribution}
|
||||||
|
if attribution["speech_act"] in {"quote", "third_party_report"}:
|
||||||
|
return {"event": "external_negative", "intensity": 54, "reason": "引用或第三方负面内容", "target": "other", "rule": attribution["reason_code"], "confidence": attribution["confidence"], "attribution": attribution}
|
||||||
atrelay_checker = getattr(self, "_message_looks_like_atrelay_request", None)
|
atrelay_checker = getattr(self, "_message_looks_like_atrelay_request", None)
|
||||||
if callable(atrelay_checker):
|
if callable(atrelay_checker):
|
||||||
try:
|
try:
|
||||||
|
|
@ -4370,6 +4385,8 @@ class UserMemoryMixin:
|
||||||
or "不想理你" in cleaned
|
or "不想理你" in cleaned
|
||||||
or re.search(r"(只是|不过|不就是).{0,6}(bot|机器人|工具|代码)", lower)
|
or re.search(r"(只是|不过|不就是).{0,6}(bot|机器人|工具|代码)", lower)
|
||||||
)
|
)
|
||||||
|
if severe_hurt and not attribution["auto_settle"]:
|
||||||
|
return {"event": "neutral", "intensity": 0, "reason": "负面目标不明确,等待复核", "target": attribution["target"], "rule": attribution["reason_code"], "confidence": attribution["confidence"], "attribution": attribution}
|
||||||
identity_hurt = bool(
|
identity_hurt = bool(
|
||||||
re.search(r"(玻璃心|假装|演的|装的|设定|工具人|没感情|别装|别演|虚拟的|假的)", cleaned)
|
re.search(r"(玻璃心|假装|演的|装的|设定|工具人|没感情|别装|别演|虚拟的|假的)", cleaned)
|
||||||
and target_hint
|
and target_hint
|
||||||
|
|
@ -4396,6 +4413,7 @@ class UserMemoryMixin:
|
||||||
"target": "bot" if direct_bot_negative else "ambiguous",
|
"target": "bot" if direct_bot_negative else "ambiguous",
|
||||||
"rule": "severe_hurt",
|
"rule": "severe_hurt",
|
||||||
"confidence": confidence,
|
"confidence": confidence,
|
||||||
|
"attribution": attribution,
|
||||||
}
|
}
|
||||||
if identity_hurt:
|
if identity_hurt:
|
||||||
return {"event": "hurt", "intensity": 76 if boundary_durable else 60, "reason": "否定情感真实性或人格", "target": "bot", "rule": "identity_hurt", "confidence": 0.84 if boundary_durable else 0.68}
|
return {"event": "hurt", "intensity": 76 if boundary_durable else 60, "reason": "否定情感真实性或人格", "target": "bot", "rule": "identity_hurt", "confidence": 0.84 if boundary_durable else 0.68}
|
||||||
|
|
@ -4423,6 +4441,9 @@ class UserMemoryMixin:
|
||||||
return False
|
return False
|
||||||
if self._is_structured_or_diagnostic_text(text):
|
if self._is_structured_or_diagnostic_text(text):
|
||||||
return False
|
return False
|
||||||
|
attribution = intent.get("emotion_attribution") if isinstance(intent.get("emotion_attribution"), dict) else {}
|
||||||
|
if attribution.get("auto_settle") is True and _safe_float(attribution.get("confidence"), 0.0) >= 0.85:
|
||||||
|
return False
|
||||||
source = str(intent.get("source") or "")
|
source = str(intent.get("source") or "")
|
||||||
if bool(intent.get("playful_or_ambiguous")) or source in {"weak_boundary_ignored", "soft_boundary_play_rule", "single_turn_boundary"}:
|
if bool(intent.get("playful_or_ambiguous")) or source in {"weak_boundary_ignored", "soft_boundary_play_rule", "single_turn_boundary"}:
|
||||||
return False
|
return False
|
||||||
|
|
@ -4554,6 +4575,13 @@ Local classifier result:
|
||||||
if _single_line(pending.get("text"), 240) != cleaned:
|
if _single_line(pending.get("text"), 240) != cleaned:
|
||||||
return
|
return
|
||||||
intent_to_apply = refined if isinstance(refined, dict) else dict(local_intent)
|
intent_to_apply = refined if isinstance(refined, dict) else dict(local_intent)
|
||||||
|
observed = pending.get("observed_event") if isinstance(pending.get("observed_event"), dict) else {}
|
||||||
|
if observed:
|
||||||
|
intent_to_apply["_emotion_revision_of"] = {
|
||||||
|
"event_id": observed.get("event_id"),
|
||||||
|
"trace_id": observed.get("trace_id"),
|
||||||
|
"revision": _safe_int(observed.get("revision"), 1, 1) + 1,
|
||||||
|
}
|
||||||
if self.enable_intent_emotion_analysis:
|
if self.enable_intent_emotion_analysis:
|
||||||
user["intent_profile"] = intent_to_apply
|
user["intent_profile"] = intent_to_apply
|
||||||
self._update_relationship_state_from_intent(user, intent_to_apply)
|
self._update_relationship_state_from_intent(user, intent_to_apply)
|
||||||
|
|
@ -4572,10 +4600,94 @@ Local classifier result:
|
||||||
user["last_emotion_judgement_error"] = _single_line(raw, 160) if raw else "empty_or_invalid"
|
user["last_emotion_judgement_error"] = _single_line(raw, 160) if raw else "empty_or_invalid"
|
||||||
self._save_data_sync()
|
self._save_data_sync()
|
||||||
|
|
||||||
|
def _record_interaction_emotion_event(
|
||||||
|
self,
|
||||||
|
user: dict[str, Any],
|
||||||
|
intent: dict[str, Any],
|
||||||
|
*,
|
||||||
|
band: str,
|
||||||
|
reason_code: str,
|
||||||
|
status: str = "applied",
|
||||||
|
expires_at: float = 0.0,
|
||||||
|
) -> dict[str, Any] | None:
|
||||||
|
emotion_event = str(intent.get("emotion_event") or "neutral").strip().lower()
|
||||||
|
inbound_intent = str(intent.get("intent") or "chat").strip().lower()
|
||||||
|
attribution = intent.get("emotion_attribution") if isinstance(intent.get("emotion_attribution"), dict) else {}
|
||||||
|
needs_review = bool(
|
||||||
|
emotion_event == "neutral"
|
||||||
|
and attribution.get("target") == "ambiguous"
|
||||||
|
and attribution.get("auto_settle") is False
|
||||||
|
)
|
||||||
|
event_type = "neutral" if needs_review else emotion_event if emotion_event != "neutral" else inbound_intent
|
||||||
|
if event_type not in {
|
||||||
|
"neutral", "hurt", "apology", "comfort", "praise", "comfort_need", "external_negative",
|
||||||
|
"play", "intimacy", "boundary",
|
||||||
|
}:
|
||||||
|
return None
|
||||||
|
user_id = _single_line(user.get("user_id") or user.get("id"), 120)
|
||||||
|
session_id = _single_line(user.get("umo"), 220)
|
||||||
|
platform = session_id.split(":", 1)[0] if ":" in session_id else ""
|
||||||
|
target = _single_line(intent.get("emotion_target"), 24).lower() or "none"
|
||||||
|
target_ref = (
|
||||||
|
{"kind": "bot", "id": "self", "role": "bot_self"}
|
||||||
|
if target == "bot"
|
||||||
|
else {"kind": "user" if target == "self" else "unknown" if target == "ambiguous" else "other", "id": user_id if target == "self" else "", "role": target}
|
||||||
|
)
|
||||||
|
message_fingerprint = hashlib.sha256(
|
||||||
|
_single_line(intent.get("text"), 500).encode("utf-8", errors="ignore")
|
||||||
|
).hexdigest()
|
||||||
|
event, created = record_recent_emotion_event(
|
||||||
|
user,
|
||||||
|
{
|
||||||
|
"event_id": _single_line((intent.get("_emotion_revision_of") or {}).get("event_id"), 96) if isinstance(intent.get("_emotion_revision_of"), dict) else "",
|
||||||
|
"trace_id": _single_line((intent.get("_emotion_revision_of") or {}).get("trace_id"), 96) if isinstance(intent.get("_emotion_revision_of"), dict) else "",
|
||||||
|
"revision": _safe_int((intent.get("_emotion_revision_of") or {}).get("revision"), 1, 1) if isinstance(intent.get("_emotion_revision_of"), dict) else 1,
|
||||||
|
"producer_plugin": "private_companion",
|
||||||
|
"origin_kind": "interaction",
|
||||||
|
"platform": platform,
|
||||||
|
"scope": "private",
|
||||||
|
"session_id": session_id,
|
||||||
|
"actor_ref": {"kind": "user", "id": user_id, "role": "speaker"},
|
||||||
|
"target_ref": target_ref,
|
||||||
|
"quoted_target_ref": {
|
||||||
|
"kind": "quoted",
|
||||||
|
"id": "",
|
||||||
|
"role": _single_line(attribution.get("quoted_target"), 40),
|
||||||
|
} if attribution.get("quoted_target") not in {None, "", "none"} else {},
|
||||||
|
"event_type": event_type,
|
||||||
|
"intensity": _safe_int(intent.get("emotion_intensity"), 0, 0, 100),
|
||||||
|
"confidence": _safe_float(intent.get("emotion_confidence"), intent.get("confidence") or 0.0, 0.0),
|
||||||
|
"source_rule": _single_line(intent.get("emotion_rule") or intent.get("source"), 80),
|
||||||
|
"occurred_at": datetime.now().astimezone().isoformat(timespec="seconds"),
|
||||||
|
"expires_at": datetime.fromtimestamp(expires_at).astimezone().isoformat(timespec="seconds") if expires_at else "",
|
||||||
|
"dedupe_key": f"{session_id}|{message_fingerprint}|{event_type}",
|
||||||
|
"message_fingerprint": message_fingerprint,
|
||||||
|
"applied_interaction": band,
|
||||||
|
"correction_of": _single_line((intent.get("_emotion_revision_of") or {}).get("event_id"), 96) if isinstance(intent.get("_emotion_revision_of"), dict) else "",
|
||||||
|
"status": "observed" if needs_review else status,
|
||||||
|
"reason_codes": [reason_code, _single_line(intent.get("emotion_rule"), 64)],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
if not created:
|
||||||
|
return event
|
||||||
|
mirror = getattr(self, "_memory_companion_record_emotion_event", None)
|
||||||
|
if callable(mirror):
|
||||||
|
operation = mirror(event)
|
||||||
|
try:
|
||||||
|
creator = getattr(self, "_create_lifecycle_background_task", None)
|
||||||
|
task = creator(operation, label="emotion_event_mirror") if callable(creator) else asyncio.create_task(operation)
|
||||||
|
if task is None:
|
||||||
|
raise RuntimeError("background task unavailable")
|
||||||
|
except Exception:
|
||||||
|
close = getattr(operation, "close", None)
|
||||||
|
if callable(close):
|
||||||
|
close()
|
||||||
|
return event
|
||||||
|
|
||||||
def _update_relationship_state_from_intent(self, user: dict[str, Any], intent: dict[str, Any]) -> None:
|
def _update_relationship_state_from_intent(self, user: dict[str, Any], intent: dict[str, Any]) -> None:
|
||||||
if not isinstance(intent, dict):
|
if not isinstance(intent, dict):
|
||||||
return
|
return
|
||||||
# companion_interaction_expression.v1 settles new events directly into
|
# companion_interaction_expression.v2 settles new events directly into
|
||||||
# the single short-term authority. relationship_state/mood_score and
|
# the single short-term authority. relationship_state/mood_score and
|
||||||
# the old Izard/Plutchik/Gross projections remain read-only legacy data.
|
# the old Izard/Plutchik/Gross projections remain read-only legacy data.
|
||||||
emotion_enabled = bool(getattr(self, "enable_emotion_simulation", True))
|
emotion_enabled = bool(getattr(self, "enable_emotion_simulation", True))
|
||||||
|
|
@ -4645,7 +4757,16 @@ Local classifier result:
|
||||||
"updated_at": now,
|
"updated_at": now,
|
||||||
}
|
}
|
||||||
|
|
||||||
if existing.get("manual_override") and (not existing.get("expires_at") or _safe_float(existing.get("expires_at"), 0) > now):
|
if not contact_active and existing.get("manual_override") and (not existing.get("expires_at") or _safe_float(existing.get("expires_at"), 0) > now):
|
||||||
|
event_recorder = getattr(self, "_record_interaction_emotion_event", None)
|
||||||
|
if callable(event_recorder):
|
||||||
|
event_recorder(
|
||||||
|
user, intent,
|
||||||
|
band=str(existing.get("expression_band") or "relaxed"),
|
||||||
|
reason_code="manual_override_retained",
|
||||||
|
status="ignored",
|
||||||
|
expires_at=_safe_float(existing.get("expires_at"), 0),
|
||||||
|
)
|
||||||
user["current_interaction"] = existing
|
user["current_interaction"] = existing
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|
@ -4682,18 +4803,58 @@ Local classifier result:
|
||||||
and _safe_float(existing.get("expires_at"), 0) > now
|
and _safe_float(existing.get("expires_at"), 0) > now
|
||||||
and str(existing.get("expression_band") or "relaxed") != "relaxed"
|
and str(existing.get("expression_band") or "relaxed") != "relaxed"
|
||||||
):
|
):
|
||||||
|
event_recorder = getattr(self, "_record_interaction_emotion_event", None)
|
||||||
|
if callable(event_recorder):
|
||||||
|
event_recorder(
|
||||||
|
user, intent,
|
||||||
|
band=str(existing.get("expression_band") or "relaxed"),
|
||||||
|
reason_code="active_interaction_retained",
|
||||||
|
status="ignored",
|
||||||
|
expires_at=_safe_float(existing.get("expires_at"), 0),
|
||||||
|
)
|
||||||
user["current_interaction"] = existing
|
user["current_interaction"] = existing
|
||||||
return
|
return
|
||||||
|
|
||||||
user["current_interaction"] = current_interaction_projection(
|
dynamics: dict[str, Any] = {}
|
||||||
{
|
dynamics_kind = emotion_event if emotion_event != "neutral" else inbound_intent
|
||||||
|
if not contact_active and dynamics_kind in {"hurt", "apology", "comfort", "praise", "intimacy", "play"}:
|
||||||
|
dynamics = settle_interaction_dynamics(
|
||||||
|
existing,
|
||||||
|
requested_band=band,
|
||||||
|
event_kind=dynamics_kind,
|
||||||
|
intensity=intensity or pressure * 20,
|
||||||
|
now=now,
|
||||||
|
)
|
||||||
|
if dynamics:
|
||||||
|
band = str(dynamics.get("expression_band") or band)
|
||||||
|
expires_at = _safe_float(dynamics.get("expires_at"), expires_at)
|
||||||
|
if dynamics_kind == "hurt":
|
||||||
|
expires_at = min(expires_at or now + max_hurt_minutes * 60, now + max_hurt_minutes * 60)
|
||||||
|
dynamics["expires_at"] = expires_at
|
||||||
|
|
||||||
|
event_recorder = getattr(self, "_record_interaction_emotion_event", None)
|
||||||
|
emotion_event_record = event_recorder(
|
||||||
|
user,
|
||||||
|
intent,
|
||||||
|
band=band,
|
||||||
|
reason_code=reason_code,
|
||||||
|
status="applied",
|
||||||
|
expires_at=expires_at,
|
||||||
|
) if callable(event_recorder) else None
|
||||||
|
interaction_payload = {
|
||||||
"expression_band": band,
|
"expression_band": band,
|
||||||
"source": "automatic",
|
"source": "automatic",
|
||||||
"reason": reason_code,
|
"reason": reason_code,
|
||||||
"updated_at": now,
|
"updated_at": now,
|
||||||
"expires_at": expires_at,
|
"expires_at": expires_at,
|
||||||
"manual_override": False,
|
"manual_override": False,
|
||||||
},
|
"last_event_id": (emotion_event_record or {}).get("event_id", ""),
|
||||||
|
"trace_id": (emotion_event_record or {}).get("trace_id", ""),
|
||||||
|
}
|
||||||
|
if dynamics:
|
||||||
|
interaction_payload.update(dynamics)
|
||||||
|
user["current_interaction"] = current_interaction_projection(
|
||||||
|
interaction_payload,
|
||||||
relationship_role=role,
|
relationship_role=role,
|
||||||
relationship_mode=relationship_mode,
|
relationship_mode=relationship_mode,
|
||||||
relationship_score=user.get("relationship_score"),
|
relationship_score=user.get("relationship_score"),
|
||||||
|
|
@ -6229,7 +6390,13 @@ bot_promises 只记录 Bot 明确承诺要提醒、记住、转述、发送或
|
||||||
if bool(getattr(self, "enable_custom_relationship_stage_policy", False))
|
if bool(getattr(self, "enable_custom_relationship_stage_policy", False))
|
||||||
else None
|
else None
|
||||||
)
|
)
|
||||||
stage = relationship_stage_for_score(user.get("relationship_score", 0), policy)["phase"]
|
stage_projection = relationship_stage_for_score(
|
||||||
|
user.get("relationship_score", 0),
|
||||||
|
policy,
|
||||||
|
previous_stage_key=user.get("relationship_phase_key", ""),
|
||||||
|
)
|
||||||
|
stage = stage_projection["phase"]
|
||||||
|
user["relationship_phase_key"] = stage.get("key", "acquaintance")
|
||||||
relationship_baseline = {
|
relationship_baseline = {
|
||||||
"stage_key": stage.get("key"),
|
"stage_key": stage.get("key"),
|
||||||
"tone": stage.get("tone"),
|
"tone": stage.get("tone"),
|
||||||
|
|
|
||||||
正在加载…
添加表格
在新工单中引用