比较提交
没有共同的提交。830cd92f4cf1652b19f6424fd508a98887089805 和 05a200be8e9483089d5c1b7b464f4c33db2c34e0 的历史完全不同。
830cd92f4c
...
05a200be8e
共有 39 个文件被更改,包括 114 次插入 和 1867 次删除
|
|
@ -1,47 +0,0 @@
|
|||
"""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"]
|
||||
|
|
@ -1,46 +0,0 @@
|
|||
"""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,17 +12,8 @@ from dataclasses import asdict, dataclass
|
|||
from enum import Enum
|
||||
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.v2"
|
||||
EXPRESSION_CONTRACT_VERSION = "companion_interaction_expression.v1"
|
||||
CONTENT_TIERS = ("normal", "flirt", "adult")
|
||||
CONTENT_TIER_LABELS = {"normal": "日常", "flirt": "含蓄暧昧", "adult": "成人私密"}
|
||||
_CONTENT_STAGE_INDEX = {
|
||||
|
|
@ -99,13 +90,6 @@ class ExpressionDecision:
|
|||
initiative: str
|
||||
proactive_budget: int
|
||||
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, ...]
|
||||
safety_mode: str
|
||||
blocker: str | None
|
||||
|
|
@ -527,24 +511,6 @@ def build_expression_decision(input_data: ExpressionInput | Mapping[str, Any] |
|
|||
warmth = min(100, warmth + 5)
|
||||
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"))
|
||||
budget = _candidate_budget(_mapping(source.get("proactive_candidate")))
|
||||
if "proactive_care_limit" in relationship_baseline:
|
||||
|
|
@ -576,16 +542,6 @@ def build_expression_decision(input_data: ExpressionInput | Mapping[str, Any] |
|
|||
owner_exclusive=owner_exclusive,
|
||||
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(
|
||||
contract=EXPRESSION_CONTRACT_VERSION,
|
||||
expression_band=band.value,
|
||||
|
|
@ -600,13 +556,6 @@ def build_expression_decision(input_data: ExpressionInput | Mapping[str, Any] |
|
|||
initiative=initiative,
|
||||
proactive_budget=budget,
|
||||
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,
|
||||
safety_mode="contact_boundary_passive" if contact_boundary else "normal",
|
||||
blocker=None,
|
||||
|
|
@ -631,10 +580,6 @@ def current_interaction_projection(
|
|||
) -> dict[str, Any]:
|
||||
"""Normalize persisted and legacy interaction state for runtime/page use."""
|
||||
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
|
||||
role = _text(relationship_role)
|
||||
score = _bounded_int(raw.get("relationship_score", relationship_score), 0, -1200, 1200)
|
||||
|
|
@ -651,14 +596,15 @@ def current_interaction_projection(
|
|||
band = normal_cap_band
|
||||
reason_codes.append("normal_interaction_band_cap_applied")
|
||||
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")
|
||||
if not dynamics and expires_at and current_ts and current_ts >= expires_at:
|
||||
if expires_at and current_ts and current_ts >= expires_at:
|
||||
band = ExpressionBand.RELAXED
|
||||
manual = False
|
||||
reason_codes.append("interaction_expired")
|
||||
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]
|
||||
projection = {
|
||||
return {
|
||||
"expression_band": band.value,
|
||||
"label": EXPRESSION_BAND_LABELS[band.value],
|
||||
"source": source,
|
||||
|
|
@ -670,22 +616,7 @@ def current_interaction_projection(
|
|||
"normal_interaction_band_cap": normal_cap,
|
||||
"allowed_bands": list(allowed),
|
||||
"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:
|
||||
|
|
@ -702,19 +633,12 @@ def expression_decision_prompt(value: ExpressionDecision | Mapping[str, Any]) ->
|
|||
content_instruction = "内容尺度=含蓄暧昧;可以亲密和调情,但保持非露骨,不描写成人性行为"
|
||||
else:
|
||||
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 (
|
||||
f"当前互动表达:{EXPRESSION_BAND_LABELS[band.value]};"
|
||||
f"语气={str(decision.get('tone') or 'steady')[:24]},"
|
||||
f"称呼距离={str(decision.get('address_style') or 'neutral')[:24]},"
|
||||
f"回复长度={str(decision.get('response_length') or 'balanced')[:24]};"
|
||||
f"{followup};{initiative};{dimensions};{content_instruction}。"
|
||||
f"{followup};{initiative};{content_instruction}。"
|
||||
)
|
||||
|
||||
|
||||
|
|
@ -740,13 +664,6 @@ def _blocked_decision(reason: str, blocker: str, inherited_reasons: list[str]) -
|
|||
initiative="blocked",
|
||||
proactive_budget=0,
|
||||
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=(),
|
||||
safety_mode=reason,
|
||||
blocker=blocker,
|
||||
|
|
|
|||
|
|
@ -395,8 +395,6 @@ _DEFAULT_USER_TEMPLATE = {
|
|||
"relationship_decay_settled_day": "",
|
||||
"relationship_last_decay_stage_drop_at": 0,
|
||||
"current_interaction": {},
|
||||
"emotion_event_ledger": [],
|
||||
"last_emotion_event": {},
|
||||
"proactive_daily_limit": -1,
|
||||
"proactive_idle_minutes": -1,
|
||||
"proactive_min_interval_minutes": -1,
|
||||
|
|
|
|||
|
|
@ -106,7 +106,6 @@ from .dreaming import (
|
|||
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 .affect_modulation import compose_affect_modulation
|
||||
from .memo_notes import memo_note_due_state, memo_note_sort_key, normalize_memo_note
|
||||
from .planning import (
|
||||
build_daily_plan_prompt,
|
||||
|
|
@ -6679,20 +6678,16 @@ class DailyStateMixin:
|
|||
values = self._base_state_values(profile)
|
||||
weather_text = self._weather_summary_text(weather)
|
||||
energy = 75
|
||||
composed_at = _now_ts()
|
||||
mood_candidates = []
|
||||
health_cause = ""
|
||||
for cond in active:
|
||||
kind = str(cond.get("kind") or "")
|
||||
if kind in values:
|
||||
values[kind] = _single_line(cond.get("label"), 80)
|
||||
energy += self._condition_effective_energy_delta(cond, now=composed_at)
|
||||
energy += _safe_int(cond.get("energy_delta"), 0, -100, 100)
|
||||
mood = _single_line(cond.get("mood"), 20)
|
||||
if mood and mood != "平稳":
|
||||
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))
|
||||
mood_candidates.append((mood, _safe_int(cond.get("intensity"), 50, 0, 100)))
|
||||
if kind == "health" and not health_cause:
|
||||
health_cause = _single_line(cond.get("cause"), 120)
|
||||
remembered_dream = self._remembered_daily_dream_label()
|
||||
|
|
@ -6733,28 +6728,12 @@ class DailyStateMixin:
|
|||
"energy": energy,
|
||||
"note": note,
|
||||
"conditions": active,
|
||||
"affect_modulation": compose_affect_modulation(active, now=composed_at),
|
||||
}
|
||||
if override_active:
|
||||
result["location_override_ts"] = existing_override_ts
|
||||
result["location_source"] = "dialogue_override"
|
||||
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(
|
||||
self,
|
||||
sleep: str,
|
||||
|
|
|
|||
|
|
@ -1,119 +0,0 @@
|
|||
"""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"]
|
||||
|
|
@ -1,162 +0,0 @@
|
|||
"""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",
|
||||
]
|
||||
|
|
@ -1,62 +0,0 @@
|
|||
"""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"]
|
||||
|
|
@ -1,46 +0,0 @@
|
|||
"""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"]
|
||||
|
|
@ -1,119 +0,0 @@
|
|||
"""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 .relationship_policy import normalize_relationship_stage_policy
|
||||
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, current_interaction_projection, expression_decision_prompt
|
||||
from .companion_interaction_expression import build_expression_decision, content_intent_from_text, expression_decision_prompt
|
||||
from .user_rest_gate import UserRestGateMixin
|
||||
from .busy_reply_gate import BusyReplyGateMixin
|
||||
from .memory_companion_adapter import MemoryCompanionAdapterMixin
|
||||
|
|
@ -6484,10 +6484,9 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
|
|||
*,
|
||||
priority: int = 50,
|
||||
source: str = "",
|
||||
force_dynamic: bool = False,
|
||||
) -> bool:
|
||||
position = self._normalize_passive_injection_position(getattr(self, "passive_injection_position", "prompt"))
|
||||
if position == "system_prompt" and not force_dynamic:
|
||||
if position == "system_prompt":
|
||||
return False
|
||||
content = str(text or "").strip()
|
||||
if not content:
|
||||
|
|
@ -9631,15 +9630,8 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
|
|||
except Exception:
|
||||
pass
|
||||
instruction = expression_decision_prompt(expression_projection)
|
||||
if 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,
|
||||
)
|
||||
if instruction and hasattr(req, "system_prompt"):
|
||||
req.system_prompt = f"{str(getattr(req, 'system_prompt', '') or '').rstrip()}\n\n[Companion expression]\n{instruction}"
|
||||
|
||||
@filter.on_llm_request(priority=-22000)
|
||||
async def prepare_p5_memory_attestation(self, event: AstrMessageEvent, req: ProviderRequest, *args, **kwargs):
|
||||
|
|
@ -12347,7 +12339,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:
|
||||
self._schedule_next_proactive(fast_user, now=received_ts)
|
||||
try:
|
||||
await self._memory_companion_apply_emotional_drift(session_id=event.unified_msg_origin or "")
|
||||
self._memory_companion_apply_emotional_drift(session_id=event.unified_msg_origin or "")
|
||||
self._memory_companion_attach_private_context(
|
||||
event,
|
||||
user_id=user_id,
|
||||
|
|
@ -12780,23 +12772,10 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
|
|||
user["intent_profile"] = 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.
|
||||
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"] = {
|
||||
"text": _single_line(text, 240),
|
||||
"created_at": _now_ts(),
|
||||
"local": deepcopy(intent_profile),
|
||||
"observed_event": observed_event or {},
|
||||
}
|
||||
self._create_lifecycle_background_task(
|
||||
self._refine_inbound_emotion_with_model(user_id, text, deepcopy(intent_profile)),
|
||||
|
|
|
|||
|
|
@ -93,18 +93,6 @@ class MemoryCompanionAdapterMixin:
|
|||
return self._memory_companion_coerce_bool(value, 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]:
|
||||
status = {
|
||||
"available": False,
|
||||
|
|
@ -1482,12 +1470,7 @@ class MemoryCompanionAdapterMixin:
|
|||
if bool(getattr(self, "enable_custom_relationship_stage_policy", False))
|
||||
else None
|
||||
)
|
||||
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")
|
||||
projection = relationship_projection_for_bridge(user.get("relationship_score", 0), policy)
|
||||
role_getter = getattr(self, "_private_user_role", None)
|
||||
try:
|
||||
role = role_getter(user, user_id) if callable(role_getter) else str(user.get("relationship_role") or "friend")
|
||||
|
|
@ -2181,125 +2164,100 @@ class MemoryCompanionAdapterMixin:
|
|||
return
|
||||
logger.debug("[PrivateCompanion] MemoryCompanion QQ 空间发布写入失败: %s", _single_line(exc, 120))
|
||||
|
||||
async def _memory_companion_apply_emotional_drift(self, *, session_id: str = "") -> None:
|
||||
"""Durably project pending memory events into Daily State conditions."""
|
||||
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.
|
||||
|
||||
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):
|
||||
return
|
||||
bridge = self._memory_companion_bridge()
|
||||
if bridge is None:
|
||||
return
|
||||
lister = getattr(bridge, "list_emotion_events", None)
|
||||
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:
|
||||
getter = getattr(bridge, "get_emotional_events", None)
|
||||
if not callable(getter):
|
||||
return
|
||||
try:
|
||||
delivery = await lister(
|
||||
consumer_id=consumer_id,
|
||||
session_id="" if cross_window else session_id,
|
||||
exclude_session_id="",
|
||||
cursor="",
|
||||
limit=6,
|
||||
)
|
||||
events = getter(session_id=session_id, limit=3)
|
||||
except Exception as exc:
|
||||
if self._memory_companion_optional_dependency_failed(exc, where="list_emotion_events"):
|
||||
if self._memory_companion_optional_dependency_failed(exc, where="get_emotional_events"):
|
||||
return
|
||||
logger.debug("[PrivateCompanion] 情绪余波拉取失败: %s", _single_line(exc, 120))
|
||||
logger.debug("[PrivateCompanion] 情绪漂移拉取失败: %s", _single_line(exc, 120))
|
||||
return
|
||||
events = delivery.get("events", []) if isinstance(delivery, dict) else []
|
||||
if not isinstance(events, list) or not events:
|
||||
# Cross-window emotional residue: check if there are recent emotional events
|
||||
# from OTHER sessions that should subtly influence the current state
|
||||
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
|
||||
data = getattr(self, "data", None)
|
||||
if not isinstance(data, dict):
|
||||
return
|
||||
conditions = data.setdefault("state_conditions", [])
|
||||
if not isinstance(conditions, list):
|
||||
conditions = []
|
||||
data["state_conditions"] = conditions
|
||||
now = time.time()
|
||||
applied_refs: list[dict[str, Any]] = []
|
||||
applied_keys: set[tuple[str, int]] = set()
|
||||
state = data.get("daily_state")
|
||||
if not isinstance(state, dict):
|
||||
state = {}
|
||||
data["daily_state"] = state
|
||||
try:
|
||||
current_energy = float(state.get("energy") or 0.0)
|
||||
except Exception:
|
||||
current_energy = 0.0
|
||||
total_delta = 0.0
|
||||
mood_hints: list[str] = []
|
||||
for event in events:
|
||||
if not isinstance(event, dict):
|
||||
continue
|
||||
condition = self._memory_companion_afterglow_condition(event, now=now)
|
||||
if not condition:
|
||||
continue
|
||||
event_id = condition["source_event_id"]
|
||||
replaced = False
|
||||
for index, existing in enumerate(conditions):
|
||||
if isinstance(existing, dict) and existing.get("kind") == "memory_afterglow" and existing.get("source_event_id") == event_id:
|
||||
conditions[index] = condition
|
||||
replaced = True
|
||||
break
|
||||
if not replaced:
|
||||
conditions.append(condition)
|
||||
ref_key = (event_id, condition["source_revision"])
|
||||
if ref_key not in applied_keys:
|
||||
applied_keys.add(ref_key)
|
||||
applied_refs.append({"event_id": event_id, "revision": condition["source_revision"]})
|
||||
if not applied_refs:
|
||||
return
|
||||
composer = getattr(self, "_compose_state_from_conditions", None)
|
||||
saver = getattr(self, "_save_data_sync", None)
|
||||
if not callable(composer) or not callable(saver):
|
||||
return
|
||||
data["daily_state"] = composer(data.get("daily_weather", {}))
|
||||
saver()
|
||||
try:
|
||||
await acker(applied_refs, consumer_id=consumer_id)
|
||||
except Exception as exc:
|
||||
self._memory_companion_optional_dependency_failed(exc, where="ack_emotion_events")
|
||||
return
|
||||
logger.debug("[PrivateCompanion] 已应用并确认记忆情绪余波: count=%s", len(applied_refs))
|
||||
|
||||
def _memory_companion_afterglow_condition(self, event: dict[str, Any], *, now: float) -> dict[str, Any] | None:
|
||||
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))),
|
||||
},
|
||||
}
|
||||
delta = float(event.get("energy_delta") or 0.0)
|
||||
total_delta += delta
|
||||
hint = _single_line(event.get("mood_hint"), 40)
|
||||
if hint:
|
||||
mood_hints.append(hint)
|
||||
# Add cross-window residue (already dampened)
|
||||
total_delta += cross_window_delta
|
||||
mood_hints.extend(cross_window_hints)
|
||||
# Safety valve: clamp total drift per cycle
|
||||
total_delta = max(-10.0, min(6.0, total_delta))
|
||||
new_energy = max(0.0, min(100.0, current_energy + total_delta))
|
||||
state["energy"] = round(new_energy, 1)
|
||||
# Apply mood drift with safety valve: only shift if hint is significant
|
||||
if mood_hints:
|
||||
current_mood = _single_line(state.get("mood_bias"), 80)
|
||||
dominant_hint = mood_hints[0]
|
||||
if current_mood and dominant_hint not in current_mood:
|
||||
state["mood_bias"] = _single_line(f"{current_mood},偏{dominant_hint}", 80)
|
||||
elif not current_mood:
|
||||
state["mood_bias"] = dominant_hint
|
||||
drift_log = state.get("mood_drift_log")
|
||||
if not isinstance(drift_log, list):
|
||||
drift_log = []
|
||||
state["mood_drift_log"] = drift_log
|
||||
drift_log.append({
|
||||
"ts": self._memory_companion_now_iso(),
|
||||
"events": [{"type": e.get("event_type"), "delta": e.get("energy_delta"), "hint": _single_line(e.get("mood_hint"), 40)} for e in events],
|
||||
"cross_window_delta": round(cross_window_delta, 2),
|
||||
"total_delta": round(total_delta, 2),
|
||||
})
|
||||
if len(drift_log) > 20:
|
||||
drift_log[:] = drift_log[-20:]
|
||||
logger.debug(
|
||||
"[PrivateCompanion] 情绪漂移已应用: energy=%.1f->%.1f delta=%.1f cross_delta=%.1f hints=%s",
|
||||
current_energy, new_energy, total_delta, cross_window_delta, mood_hints,
|
||||
)
|
||||
|
||||
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."""
|
||||
|
|
@ -2319,26 +2277,6 @@ class MemoryCompanionAdapterMixin:
|
|||
logger.debug("[PrivateCompanion] open-loop 搜索失败: %s", _single_line(exc, 120))
|
||||
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(
|
||||
self,
|
||||
*,
|
||||
|
|
|
|||
|
|
@ -202,7 +202,7 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
|
|||
now=time.time(),
|
||||
)
|
||||
expression_projection = {
|
||||
"contract": "companion_interaction_expression.v2",
|
||||
"contract": "companion_interaction_expression.v1",
|
||||
"status": "configured_projection",
|
||||
"expression_band": current_interaction.get("expression_band") or "relaxed",
|
||||
"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 {})
|
||||
expression_projection.update(
|
||||
{
|
||||
"contract": self._single_line(raw_projection.get("contract"), 80) or "companion_interaction_expression.v2",
|
||||
"contract": self._single_line(raw_projection.get("contract"), 80) or "companion_interaction_expression.v1",
|
||||
"expression_band": self._single_line(raw_projection.get("expression_band"), 24) or "relaxed",
|
||||
"tone": self._single_line(raw_projection.get("tone"), 24) or "steady",
|
||||
"response_length": self._single_line(raw_projection.get("response_length"), 24) or "balanced",
|
||||
|
|
|
|||
|
|
@ -12,7 +12,6 @@ from quart import request
|
|||
|
||||
from .companion_interaction_expression import allowed_expression_bands, current_interaction_projection
|
||||
from .helpers import _safe_int
|
||||
from .emotion_diagnostics import build_emotion_trace_projection, emotion_trace_summary
|
||||
from .relationship_ledger import (
|
||||
is_owner_exclusive,
|
||||
normalize_relationship_mode,
|
||||
|
|
@ -283,19 +282,6 @@ class PrivateCompanionPageApiUsersGroupsMixin:
|
|||
detail["memory_summary"] = await memory_reader(user_id, limit=3)
|
||||
else:
|
||||
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)
|
||||
except Exception as exc:
|
||||
logger.error(f"[PrivateCompanionPage] 获取用户详情失败: {exc}", exc_info=True)
|
||||
|
|
|
|||
|
|
@ -27345,10 +27345,3 @@ pre {
|
|||
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,7 +12633,6 @@ async function renderUserDetail(forceFetch = false) {
|
|||
<div class="detail-grid">
|
||||
${renderRelationshipPanel(detail.relationship_panel)}
|
||||
${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 ? "按真实聊天安全门判断" : "不参与"]])}
|
||||
${renderPrivateDeliveryRoute(detail)}
|
||||
${renderPrivateBehaviorHabits(detail)}
|
||||
|
|
@ -12806,23 +12805,6 @@ function memorySummaryCount(summary, key) {
|
|||
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) {
|
||||
return String(value || "")
|
||||
.replace(/[\r\n\t]+/g, " ")
|
||||
|
|
@ -14046,23 +14028,6 @@ 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) {
|
||||
const refreshSelectedUserDetail = async () => {
|
||||
if (state.selectedUserId === detail.user_id) {
|
||||
|
|
@ -14072,7 +14037,6 @@ function bindUserActions(detail) {
|
|||
const scoreForm = $("#relationshipScoreForm");
|
||||
const scoreNumber = $("#relationshipScoreNumber");
|
||||
const stageForm = $("#relationshipStageForm");
|
||||
bindEmotionTraceButtons(detail);
|
||||
stageForm?.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const form = new FormData(event.currentTarget);
|
||||
|
|
|
|||
|
|
@ -3210,7 +3210,7 @@ class ProactiveMessageMixin:
|
|||
return ""
|
||||
# Pull cross-session emotional drift before generating proactive message
|
||||
try:
|
||||
await self._memory_companion_apply_emotional_drift(session_id="")
|
||||
self._memory_companion_apply_emotional_drift(session_id="")
|
||||
except Exception:
|
||||
pass
|
||||
prompt = await self._build_framework_proactive_prompt(
|
||||
|
|
@ -3366,10 +3366,6 @@ class ProactiveMessageMixin:
|
|||
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('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"主动额度={_safe_int(expression_decision.get('proactive_budget'), 0, 0)}。"
|
||||
)
|
||||
|
|
|
|||
|
|
@ -187,13 +187,7 @@ def normalize_relationship_stage_policy(value: Any) -> list[dict[str, Any]]:
|
|||
return normalized
|
||||
|
||||
|
||||
def relationship_stage_for_score(
|
||||
value: Any,
|
||||
policy: Any = None,
|
||||
*,
|
||||
previous_stage_key: Any = "",
|
||||
hysteresis_margin: int = 20,
|
||||
) -> dict[str, Any]:
|
||||
def relationship_stage_for_score(value: Any, policy: Any = None) -> dict[str, Any]:
|
||||
try:
|
||||
score = int(value)
|
||||
except (TypeError, ValueError):
|
||||
|
|
@ -205,22 +199,6 @@ def relationship_stage_for_score(
|
|||
if stage["min"] <= score <= stage["max"]:
|
||||
stage_index = index
|
||||
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])
|
||||
span = max(0, int(stage["max"]) - int(stage["min"]))
|
||||
within = 1.0 if span == 0 else (score - int(stage["min"])) / span
|
||||
|
|
@ -240,13 +218,8 @@ def relationship_stage_for_score(
|
|||
}
|
||||
|
||||
|
||||
def relationship_projection_for_bridge(
|
||||
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)
|
||||
def relationship_projection_for_bridge(value: Any, policy: Any = None) -> dict[str, Any]:
|
||||
projection = relationship_stage_for_score(value, policy)
|
||||
phase = projection["phase"]
|
||||
return {
|
||||
"schema_version": projection["schema_version"],
|
||||
|
|
|
|||
|
|
@ -1,67 +0,0 @@
|
|||
"""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,7 +8,8 @@ from pathlib import Path
|
|||
COMPANION_ROOT = Path(__file__).resolve().parents[1]
|
||||
PEIBAN_ROOT = COMPANION_ROOT.parents[1]
|
||||
CONTRACT_PATH = COMPANION_ROOT / "bot_personal_contract.py"
|
||||
MEMORY_CONTRACT_PATH = PEIBAN_ROOT / "product" / "memory" / "core" / "bot_personal_contract.py"
|
||||
MEMORY_CONTRACT_PATH = PEIBAN_ROOT / "astrbot_plugin_memory_companion-main" / "core" / "bot_personal_contract.py"
|
||||
SHARED_CONTRACT_PATH = PEIBAN_ROOT / "doc" / "shared" / "bot_personal_contract.py"
|
||||
|
||||
|
||||
def load_contract(path: Path, name: str):
|
||||
|
|
@ -24,7 +25,7 @@ memory_contract = load_contract(MEMORY_CONTRACT_PATH, "memory_bot_personal_contr
|
|||
|
||||
|
||||
def test_contract_bytes_match_authority_and_other_side():
|
||||
expected = CONTRACT_PATH.read_bytes()
|
||||
expected = SHARED_CONTRACT_PATH.read_bytes()
|
||||
assert CONTRACT_PATH.read_bytes() == expected
|
||||
assert MEMORY_CONTRACT_PATH.read_bytes() == expected
|
||||
assert hashlib.sha256(CONTRACT_PATH.read_bytes()).digest() == hashlib.sha256(
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ from types import SimpleNamespace
|
|||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PEIBAN_ROOT = ROOT.parents[1]
|
||||
MEMORY_ROOT = ROOT.parent / "memory"
|
||||
MEMORY_ROOT = PEIBAN_ROOT / "astrbot_plugin_memory_companion-main"
|
||||
|
||||
if "astrbot.api" not in sys.modules:
|
||||
astrbot = types.ModuleType("astrbot")
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ from pathlib import Path
|
|||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PEIBAN_ROOT = ROOT.parents[1]
|
||||
MEMORY_ROOT = ROOT.parent / "memory"
|
||||
MEMORY_ROOT = PEIBAN_ROOT / "astrbot_plugin_memory_companion-main"
|
||||
|
||||
|
||||
def _load_memory_package():
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ import types
|
|||
|
||||
|
||||
COMPANION_ROOT = Path(__file__).resolve().parents[1]
|
||||
MEMORY_ROOT = COMPANION_ROOT.parent / "memory"
|
||||
MEMORY_ROOT = COMPANION_ROOT.parents[1] / "astrbot_plugin_memory_companion-main"
|
||||
|
||||
|
||||
def _load_companion_package():
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ import types
|
|||
|
||||
|
||||
COMPANION_ROOT = Path(__file__).resolve().parents[1]
|
||||
MEMORY_ROOT = COMPANION_ROOT.parent / "memory"
|
||||
MEMORY_ROOT = COMPANION_ROOT.parents[1] / "astrbot_plugin_memory_companion-main"
|
||||
|
||||
|
||||
def _load_modules():
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ from pathlib import Path
|
|||
|
||||
|
||||
COMPANION_ROOT = Path(__file__).resolve().parents[1]
|
||||
MEMORY_ROOT = COMPANION_ROOT.parent / "memory"
|
||||
MEMORY_ROOT = COMPANION_ROOT.parents[1] / "astrbot_plugin_memory_companion-main"
|
||||
|
||||
|
||||
def _register_package_alias(name: str, root: Path) -> None:
|
||||
|
|
|
|||
|
|
@ -68,7 +68,6 @@ class ReplyTemperatureTests(unittest.TestCase):
|
|||
self.assertEqual([], legacy_calls)
|
||||
self.assertIn("_private_companion_expression_decision", source)
|
||||
self.assertNotIn("_private_companion_reply_temperature", source)
|
||||
self.assertIn("private_companion_expression_decision_v2", source)
|
||||
helper = next(
|
||||
node for node in ast.walk(tree)
|
||||
if isinstance(node, ast.FunctionDef) and node.name == "_bounded_expression_state_signals"
|
||||
|
|
|
|||
|
|
@ -1,60 +0,0 @@
|
|||
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()
|
||||
|
|
@ -1,60 +0,0 @@
|
|||
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()
|
||||
|
|
@ -1,63 +0,0 @@
|
|||
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()
|
||||
|
|
@ -1,121 +0,0 @@
|
|||
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()
|
||||
|
|
@ -1,57 +0,0 @@
|
|||
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()
|
||||
|
|
@ -1,70 +0,0 @@
|
|||
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()
|
||||
|
|
@ -1,37 +0,0 @@
|
|||
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()
|
||||
|
|
@ -1,81 +0,0 @@
|
|||
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()
|
||||
|
|
@ -1,71 +0,0 @@
|
|||
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,7 +20,6 @@ from relationship_ledger import ( # noqa: E402
|
|||
record_manual_relationship_change,
|
||||
relationship_positive_score_cap,
|
||||
)
|
||||
from interaction_dynamics import settle_interaction_dynamics # noqa: E402
|
||||
|
||||
|
||||
class _Request:
|
||||
|
|
@ -78,7 +77,6 @@ def _load_update_user() -> Any:
|
|||
"current_interaction_projection": current_interaction_projection,
|
||||
"deepcopy": copy.deepcopy,
|
||||
"logger": _Logger(),
|
||||
"settle_interaction_dynamics": settle_interaction_dynamics,
|
||||
"normalize_relationship_mode": normalize_relationship_mode,
|
||||
"is_owner_exclusive": is_owner_exclusive,
|
||||
"record_manual_relationship_change": record_manual_relationship_change,
|
||||
|
|
@ -107,7 +105,6 @@ def _load_interaction_settler() -> Any:
|
|||
"current_interaction_projection": current_interaction_projection,
|
||||
"deepcopy": copy.deepcopy,
|
||||
"logger": _Logger(),
|
||||
"settle_interaction_dynamics": settle_interaction_dynamics,
|
||||
"_now_ts": time.time,
|
||||
"_safe_float": _safe_float,
|
||||
"_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:
|
||||
assert EXPRESSION_CONTRACT_VERSION == "companion_interaction_expression.v2"
|
||||
assert EXPRESSION_CONTRACT_VERSION == "companion_interaction_expression.v1"
|
||||
assert content_intent_from_text("我同意,开启成人模式并继续") == {
|
||||
"requested_content_tier": "adult",
|
||||
"turn_consent": True,
|
||||
|
|
|
|||
|
|
@ -1786,20 +1786,6 @@ TTS 朗读文本:
|
|||
return True
|
||||
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:
|
||||
lang = self._tts_language_label()
|
||||
mode = getattr(self, "tts_generation_mode", "fast_tag")
|
||||
|
|
@ -2903,7 +2889,6 @@ TTS 朗读文本:
|
|||
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 ""
|
||||
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> 内")
|
||||
if not emotion_rule:
|
||||
emotion_rule = "不要加入方括号情绪标签。"
|
||||
|
|
@ -2935,7 +2920,6 @@ TTS 朗读文本:
|
|||
Provider 规则:{emotion_rule}
|
||||
补充要求:{extra or "无"}
|
||||
{persona_context}
|
||||
{expression_context}
|
||||
|
||||
原回复:
|
||||
{source}
|
||||
|
|
@ -2973,7 +2957,6 @@ Provider 规则:{emotion_rule}
|
|||
if not extra:
|
||||
extra = self._legacy_nondefault_tts_prompt()
|
||||
persona_context = await self._format_tts_persona_voice_context(event)
|
||||
expression_context = self._tts_expression_style_context(event)
|
||||
if voice_lang == "zh":
|
||||
language_rule = "voice_text 必须是自然中文。"
|
||||
visible_rule = "visible_text 仍是最终可见中文文本;如果和 voice_text 一样,可以保持同一句。"
|
||||
|
|
@ -3006,7 +2989,6 @@ Provider 规则:{emotion_rule}
|
|||
本轮自动语音概率线索:{probability_hint}
|
||||
补充规则:{extra or "无"}
|
||||
{persona_context}
|
||||
{expression_context}
|
||||
|
||||
判断规则:
|
||||
- 你要自己根据用户原话、规则线索和回复内容判断用户是否在要求或期待语音;规则快判只是线索,不是最终结论。
|
||||
|
|
|
|||
181
user_memory.py
181
user_memory.py
|
|
@ -110,9 +110,6 @@ from .companion_interaction_expression import (
|
|||
current_interaction_projection,
|
||||
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 (
|
||||
build_daily_plan_prompt,
|
||||
build_detail_enhancement_prompt,
|
||||
|
|
@ -321,13 +318,7 @@ class UserMemoryMixin:
|
|||
if bool(getattr(self, "enable_custom_relationship_stage_policy", False))
|
||||
else None
|
||||
)
|
||||
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 = relationship_stage_for_score(score, policy)["phase"]
|
||||
stage_key = str(stage.get("key") or "acquaintance")
|
||||
if stage_key in {"deeply_distant", "strongly_distant", "distant"}:
|
||||
level = "陌生"
|
||||
|
|
@ -4337,7 +4328,6 @@ class UserMemoryMixin:
|
|||
"emotion_target": emotion_event.get("target", "none"),
|
||||
"emotion_rule": emotion_event.get("rule", ""),
|
||||
"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,
|
||||
"playful_or_ambiguous": playful_or_ambiguous,
|
||||
"text": cleaned,
|
||||
|
|
@ -4350,11 +4340,6 @@ class UserMemoryMixin:
|
|||
return {"event": "neutral", "intensity": 0, "reason": "", "target": "none", "rule": "", "confidence": 1.0}
|
||||
if self._is_structured_or_diagnostic_text(cleaned):
|
||||
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)
|
||||
if callable(atrelay_checker):
|
||||
try:
|
||||
|
|
@ -4385,8 +4370,6 @@ class UserMemoryMixin:
|
|||
or "不想理你" in cleaned
|
||||
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(
|
||||
re.search(r"(玻璃心|假装|演的|装的|设定|工具人|没感情|别装|别演|虚拟的|假的)", cleaned)
|
||||
and target_hint
|
||||
|
|
@ -4413,7 +4396,6 @@ class UserMemoryMixin:
|
|||
"target": "bot" if direct_bot_negative else "ambiguous",
|
||||
"rule": "severe_hurt",
|
||||
"confidence": confidence,
|
||||
"attribution": attribution,
|
||||
}
|
||||
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}
|
||||
|
|
@ -4441,9 +4423,6 @@ class UserMemoryMixin:
|
|||
return False
|
||||
if self._is_structured_or_diagnostic_text(text):
|
||||
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 "")
|
||||
if bool(intent.get("playful_or_ambiguous")) or source in {"weak_boundary_ignored", "soft_boundary_play_rule", "single_turn_boundary"}:
|
||||
return False
|
||||
|
|
@ -4575,13 +4554,6 @@ Local classifier result:
|
|||
if _single_line(pending.get("text"), 240) != cleaned:
|
||||
return
|
||||
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:
|
||||
user["intent_profile"] = intent_to_apply
|
||||
self._update_relationship_state_from_intent(user, intent_to_apply)
|
||||
|
|
@ -4600,94 +4572,10 @@ Local classifier result:
|
|||
user["last_emotion_judgement_error"] = _single_line(raw, 160) if raw else "empty_or_invalid"
|
||||
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:
|
||||
if not isinstance(intent, dict):
|
||||
return
|
||||
# companion_interaction_expression.v2 settles new events directly into
|
||||
# companion_interaction_expression.v1 settles new events directly into
|
||||
# the single short-term authority. relationship_state/mood_score and
|
||||
# the old Izard/Plutchik/Gross projections remain read-only legacy data.
|
||||
emotion_enabled = bool(getattr(self, "enable_emotion_simulation", True))
|
||||
|
|
@ -4757,16 +4645,7 @@ Local classifier result:
|
|||
"updated_at": 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),
|
||||
)
|
||||
if existing.get("manual_override") and (not existing.get("expires_at") or _safe_float(existing.get("expires_at"), 0) > now):
|
||||
user["current_interaction"] = existing
|
||||
return
|
||||
|
||||
|
|
@ -4803,58 +4682,18 @@ Local classifier result:
|
|||
and _safe_float(existing.get("expires_at"), 0) > now
|
||||
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
|
||||
return
|
||||
|
||||
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 = {
|
||||
user["current_interaction"] = current_interaction_projection(
|
||||
{
|
||||
"expression_band": band,
|
||||
"source": "automatic",
|
||||
"reason": reason_code,
|
||||
"updated_at": now,
|
||||
"expires_at": expires_at,
|
||||
"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_mode=relationship_mode,
|
||||
relationship_score=user.get("relationship_score"),
|
||||
|
|
@ -6390,13 +6229,7 @@ bot_promises 只记录 Bot 明确承诺要提醒、记住、转述、发送或
|
|||
if bool(getattr(self, "enable_custom_relationship_stage_policy", False))
|
||||
else None
|
||||
)
|
||||
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")
|
||||
stage = relationship_stage_for_score(user.get("relationship_score", 0), policy)["phase"]
|
||||
relationship_baseline = {
|
||||
"stage_key": stage.get("key"),
|
||||
"tone": stage.get("tone"),
|
||||
|
|
|
|||
正在加载…
添加表格
在新工单中引用