feat(emotion-e4): project memory afterglow conditions

这个提交存在于:
agent 2026-08-05 00:21:04 +08:00
父节点 773c064c5c
当前提交 72b6696b79
共有 5 个文件被更改,包括 248 次插入 和 83 次删除

查看文件

@ -6678,16 +6678,20 @@ class DailyStateMixin:
values = self._base_state_values(profile) values = self._base_state_values(profile)
weather_text = self._weather_summary_text(weather) weather_text = self._weather_summary_text(weather)
energy = 75 energy = 75
composed_at = _now_ts()
mood_candidates = [] mood_candidates = []
health_cause = "" health_cause = ""
for cond in active: for cond in active:
kind = str(cond.get("kind") or "") kind = str(cond.get("kind") or "")
if kind in values: if kind in values:
values[kind] = _single_line(cond.get("label"), 80) values[kind] = _single_line(cond.get("label"), 80)
energy += _safe_int(cond.get("energy_delta"), 0, -100, 100) energy += self._condition_effective_energy_delta(cond, now=composed_at)
mood = _single_line(cond.get("mood"), 20) mood = _single_line(cond.get("mood"), 20)
if mood and mood != "平稳": if mood and mood != "平稳":
mood_candidates.append((mood, _safe_int(cond.get("intensity"), 50, 0, 100))) intensity = _safe_int(cond.get("intensity"), 50, 0, 100)
if kind == "memory_afterglow":
intensity = max(0, round(intensity * self._memory_afterglow_decay(cond, now=composed_at)))
mood_candidates.append((mood, intensity))
if kind == "health" and not health_cause: if kind == "health" and not health_cause:
health_cause = _single_line(cond.get("cause"), 120) health_cause = _single_line(cond.get("cause"), 120)
remembered_dream = self._remembered_daily_dream_label() remembered_dream = self._remembered_daily_dream_label()
@ -6734,6 +6738,21 @@ class DailyStateMixin:
result["location_source"] = "dialogue_override" result["location_source"] = "dialogue_override"
return result return result
@staticmethod
def _memory_afterglow_decay(cond: dict[str, Any], *, now: float) -> float:
if str(cond.get("kind") or "") != "memory_afterglow":
return 1.0
start_ts = _safe_float(cond.get("start_ts"), now)
half_life = max(60.0, min(86400.0, _safe_float(cond.get("half_life_seconds"), 1800.0)))
age = max(0.0, now - start_ts)
return max(0.0, min(1.0, 0.5 ** (age / half_life)))
def _condition_effective_energy_delta(self, cond: dict[str, Any], *, now: float) -> int:
base = _safe_int(cond.get("energy_delta"), 0, -100, 100)
if str(cond.get("kind") or "") != "memory_afterglow":
return base
return int(round(base * self._memory_afterglow_decay(cond, now=now)))
def _build_state_note( def _build_state_note(
self, self,
sleep: str, sleep: str,

查看文件

@ -12347,7 +12347,7 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
if not self._simulation_active(fast_user) and _safe_float(fast_user.get("next_proactive_at"), 0) <= 0: if not self._simulation_active(fast_user) and _safe_float(fast_user.get("next_proactive_at"), 0) <= 0:
self._schedule_next_proactive(fast_user, now=received_ts) self._schedule_next_proactive(fast_user, now=received_ts)
try: try:
self._memory_companion_apply_emotional_drift(session_id=event.unified_msg_origin or "") await self._memory_companion_apply_emotional_drift(session_id=event.unified_msg_origin or "")
self._memory_companion_attach_private_context( self._memory_companion_attach_private_context(
event, event,
user_id=user_id, user_id=user_id,

查看文件

@ -2176,100 +2176,125 @@ class MemoryCompanionAdapterMixin:
return return
logger.debug("[PrivateCompanion] MemoryCompanion QQ 空间发布写入失败: %s", _single_line(exc, 120)) logger.debug("[PrivateCompanion] MemoryCompanion QQ 空间发布写入失败: %s", _single_line(exc, 120))
def _memory_companion_apply_emotional_drift(self, *, session_id: str = "") -> None: async def _memory_companion_apply_emotional_drift(self, *, session_id: str = "") -> None:
"""Pull pending emotional drift events from the memory plugin and apply to daily_state. """Durably project pending memory events into Daily State conditions."""
This now includes cross-window emotional continuity: if the bot recently
touched emotional memories in other sessions, a dampened residue is also
applied to the current daily_state, creating a sense of emotional carryover.
"""
if not getattr(self, "enable_memory_companion_emotional_drift", True): if not getattr(self, "enable_memory_companion_emotional_drift", True):
return return
bridge = self._memory_companion_bridge() bridge = self._memory_companion_bridge()
if bridge is None: if bridge is None:
return return
getter = getattr(bridge, "get_emotional_events", None) lister = getattr(bridge, "list_emotion_events", None)
if not callable(getter): acker = getattr(bridge, "ack_emotion_events", None)
if not callable(lister) or not callable(acker):
return
consumer_id = "private_companion.daily_state"
cross_window = bool(getattr(self, "enable_memory_companion_cross_window_emotion", True))
if not cross_window and not session_id:
return return
try: try:
events = getter(session_id=session_id, limit=3) delivery = await lister(
consumer_id=consumer_id,
session_id="" if cross_window else session_id,
exclude_session_id="",
cursor="",
limit=6,
)
except Exception as exc: except Exception as exc:
if self._memory_companion_optional_dependency_failed(exc, where="get_emotional_events"): if self._memory_companion_optional_dependency_failed(exc, where="list_emotion_events"):
return return
logger.debug("[PrivateCompanion] 情绪漂移拉取失败: %s", _single_line(exc, 120)) logger.debug("[PrivateCompanion] 情绪余波拉取失败: %s", _single_line(exc, 120))
return return
# Cross-window emotional residue: check if there are recent emotional events events = delivery.get("events", []) if isinstance(delivery, dict) else []
# from OTHER sessions that should subtly influence the current state if not isinstance(events, list) or not events:
cross_window_delta = 0.0
cross_window_hints: list[str] = []
cross_state_getter = getattr(bridge, "get_recent_emotional_state", None)
if callable(cross_state_getter) and getattr(self, "enable_memory_companion_cross_window_emotion", True):
try:
cross_state = cross_state_getter()
if isinstance(cross_state, dict) and cross_state.get("total", 0) > 0:
# Apply a dampened cross-window effect (30% strength)
scar_count = cross_state.get("scar_count", 0)
warm_count = cross_state.get("warm_count", 0)
if scar_count > 0:
cross_window_delta = -min(2.0, scar_count * 0.8)
cross_window_hints.append("低落")
if warm_count > 0:
cross_window_delta += min(1.5, warm_count * 0.5)
cross_window_hints.append("微暖")
except Exception as exc:
self._memory_companion_optional_dependency_failed(exc, where="get_recent_emotional_state")
if not events and not cross_window_hints:
return return
data = getattr(self, "data", None) data = getattr(self, "data", None)
if not isinstance(data, dict): if not isinstance(data, dict):
return return
state = data.get("daily_state") conditions = data.setdefault("state_conditions", [])
if not isinstance(state, dict): if not isinstance(conditions, list):
state = {} conditions = []
data["daily_state"] = state data["state_conditions"] = conditions
try: now = time.time()
current_energy = float(state.get("energy") or 0.0) applied_refs: list[dict[str, Any]] = []
except Exception: applied_keys: set[tuple[str, int]] = set()
current_energy = 0.0
total_delta = 0.0
mood_hints: list[str] = []
for event in events: for event in events:
delta = float(event.get("energy_delta") or 0.0) if not isinstance(event, dict):
total_delta += delta continue
hint = _single_line(event.get("mood_hint"), 40) condition = self._memory_companion_afterglow_condition(event, now=now)
if hint: if not condition:
mood_hints.append(hint) continue
# Add cross-window residue (already dampened) event_id = condition["source_event_id"]
total_delta += cross_window_delta replaced = False
mood_hints.extend(cross_window_hints) for index, existing in enumerate(conditions):
# Safety valve: clamp total drift per cycle if isinstance(existing, dict) and existing.get("kind") == "memory_afterglow" and existing.get("source_event_id") == event_id:
total_delta = max(-10.0, min(6.0, total_delta)) conditions[index] = condition
new_energy = max(0.0, min(100.0, current_energy + total_delta)) replaced = True
state["energy"] = round(new_energy, 1) break
# Apply mood drift with safety valve: only shift if hint is significant if not replaced:
if mood_hints: conditions.append(condition)
current_mood = _single_line(state.get("mood_bias"), 80) ref_key = (event_id, condition["source_revision"])
dominant_hint = mood_hints[0] if ref_key not in applied_keys:
if current_mood and dominant_hint not in current_mood: applied_keys.add(ref_key)
state["mood_bias"] = _single_line(f"{current_mood},偏{dominant_hint}", 80) applied_refs.append({"event_id": event_id, "revision": condition["source_revision"]})
elif not current_mood: if not applied_refs:
state["mood_bias"] = dominant_hint return
drift_log = state.get("mood_drift_log") composer = getattr(self, "_compose_state_from_conditions", None)
if not isinstance(drift_log, list): saver = getattr(self, "_save_data_sync", None)
drift_log = [] if not callable(composer) or not callable(saver):
state["mood_drift_log"] = drift_log return
drift_log.append({ data["daily_state"] = composer(data.get("daily_weather", {}))
"ts": self._memory_companion_now_iso(), saver()
"events": [{"type": e.get("event_type"), "delta": e.get("energy_delta"), "hint": _single_line(e.get("mood_hint"), 40)} for e in events], try:
"cross_window_delta": round(cross_window_delta, 2), await acker(applied_refs, consumer_id=consumer_id)
"total_delta": round(total_delta, 2), except Exception as exc:
}) self._memory_companion_optional_dependency_failed(exc, where="ack_emotion_events")
if len(drift_log) > 20: return
drift_log[:] = drift_log[-20:] logger.debug("[PrivateCompanion] 已应用并确认记忆情绪余波: count=%s", len(applied_refs))
logger.debug(
"[PrivateCompanion] 情绪漂移已应用: energy=%.1f->%.1f delta=%.1f cross_delta=%.1f hints=%s", def _memory_companion_afterglow_condition(self, event: dict[str, Any], *, now: float) -> dict[str, Any] | None:
current_energy, new_energy, total_delta, cross_window_delta, mood_hints, event_id = _single_line(event.get("event_id"), 96)
) if not event_id:
return None
try:
revision = max(1, min(1000000, int(event.get("revision") or 1)))
delta = max(-8.0, min(5.0, float(event.get("energy_delta") or 0.0)))
intensity = max(0, min(100, round(float(event.get("intensity") or 0.0))))
except (TypeError, ValueError):
return None
event_type = _single_line(event.get("event_type"), 48)
mood_by_type = {
"scar_touched": "低落",
"warm_memory": "微暖",
"vulnerable_resonance": "柔软",
}
mood = mood_by_type.get(event_type, "平稳")
source_session = _single_line(event.get("session_id"), 220)
half_life = 1800.0
return {
"id": f"memory-afterglow-{event_id}",
"kind": "memory_afterglow",
"title": "记忆余波",
"label": "记忆被触动后留下的短暂情绪余波",
"mood": mood,
"energy_delta": round(delta, 2),
"intensity": intensity,
"start_ts": now,
"end_ts": now + 4 * half_life,
"duration_hours": 2,
"half_life_seconds": half_life,
"cause": "memory_recall_resonance",
"phase": "afterglow",
"source_event_id": event_id,
"source_revision": revision,
"source_session_id": source_session,
"trace_id": _single_line(event.get("trace_id"), 96),
"modulation": {
"valence": max(-1.0, min(1.0, _safe_float(event.get("valence"), 0.0))),
"arousal": max(0.0, min(1.0, _safe_float(event.get("arousal"), 0.0))),
"vulnerability": max(0.0, min(1.0, _safe_float(event.get("vulnerability"), 0.0))),
"confidence": max(0.0, min(1.0, _safe_float(event.get("confidence"), 0.0))),
},
}
async def _memory_companion_search_open_loops(self, *, session_id: str = "", limit: int = 3) -> list[dict[str, Any]]: async def _memory_companion_search_open_loops(self, *, session_id: str = "", limit: int = 3) -> list[dict[str, Any]]:
"""Search for unresolved open-loop / promise memories for proactive companionship.""" """Search for unresolved open-loop / promise memories for proactive companionship."""

查看文件

@ -3210,7 +3210,7 @@ class ProactiveMessageMixin:
return "" return ""
# Pull cross-session emotional drift before generating proactive message # Pull cross-session emotional drift before generating proactive message
try: try:
self._memory_companion_apply_emotional_drift(session_id="") await self._memory_companion_apply_emotional_drift(session_id="")
except Exception: except Exception:
pass pass
prompt = await self._build_framework_proactive_prompt( prompt = await self._build_framework_proactive_prompt(

查看文件

@ -0,0 +1,121 @@
from __future__ import annotations
import ast
import asyncio
import importlib.util
from pathlib import Path
import sys
import types
import unittest
from types import SimpleNamespace
from typing import Any
ROOT = Path(__file__).resolve().parents[1]
if "astrbot.api" not in sys.modules:
astrbot = types.ModuleType("astrbot")
api = types.ModuleType("astrbot.api")
api.logger = SimpleNamespace(debug=lambda *args, **kwargs: None, warning=lambda *args, **kwargs: None)
sys.modules["astrbot"] = astrbot
sys.modules["astrbot.api"] = api
def load_adapter():
package_name = "emotion_e4_companion"
package = types.ModuleType(package_name)
package.__path__ = [str(ROOT)]
sys.modules[package_name] = package
spec = importlib.util.spec_from_file_location(
f"{package_name}.memory_companion_adapter", ROOT / "memory_companion_adapter.py"
)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = module
spec.loader.exec_module(module)
return module.MemoryCompanionAdapterMixin
MemoryCompanionAdapterMixin = load_adapter()
class Bridge:
def __init__(self) -> None:
self.acked: list[dict[str, Any]] = []
async def list_emotion_events(self, **_kwargs: Any) -> dict[str, Any]:
event = {
"event_id": "emo-a",
"revision": 1,
"trace_id": "trace-a",
"session_id": "session-a",
"event_type": "warm_memory",
"energy_delta": 4.0,
"intensity": 80,
"valence": 0.5,
"arousal": 0.3,
"vulnerability": 0.2,
"confidence": 0.9,
}
return {"events": [event, dict(event)]}
async def ack_emotion_events(self, refs: list[dict[str, Any]], **_kwargs: Any) -> dict[str, Any]:
self.acked.extend(refs)
return {"acked": len(refs)}
class Host(MemoryCompanionAdapterMixin):
enable_memory_companion_emotional_drift = True
enable_memory_companion_cross_window_emotion = True
def __init__(self, bridge: Bridge) -> None:
self.bridge = bridge
self.data = {"state_conditions": [], "daily_weather": {}}
self.saved = 0
def _memory_companion_bridge(self):
return self.bridge
def _compose_state_from_conditions(self, _weather: dict[str, Any]) -> dict[str, Any]:
return {"energy": 79, "conditions": list(self.data["state_conditions"])}
def _save_data_sync(self) -> None:
self.saved += 1
class EmotionE4AfterglowConditionTests(unittest.TestCase):
def test_afterglow_upserts_by_event_id_and_acks_after_save(self) -> None:
bridge = Bridge()
host = Host(bridge)
asyncio.run(host._memory_companion_apply_emotional_drift(session_id="session-a"))
self.assertEqual(1, host.saved)
self.assertEqual(1, len(host.data["state_conditions"]))
condition = host.data["state_conditions"][0]
self.assertEqual("memory_afterglow", condition["kind"])
self.assertEqual("emo-a", condition["source_event_id"])
self.assertEqual(1800.0, condition["half_life_seconds"])
self.assertEqual([{"event_id": "emo-a", "revision": 1}], bridge.acked)
def test_afterglow_decay_is_monotonic(self) -> None:
source = (ROOT / "daily_state.py").read_text(encoding="utf-8")
tree = ast.parse(source)
owner = next(node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == "DailyStateMixin")
methods = {
node.name: node
for node in owner.body
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
and node.name in {"_memory_afterglow_decay", "_condition_effective_energy_delta"}
}
module = ast.Module(body=list(methods.values()), type_ignores=[])
ast.fix_missing_locations(module)
namespace = {"Any": Any, "_safe_float": lambda value, default=0.0: float(value or default), "_safe_int": lambda value, default=0, *_args: int(float(value or default))}
exec(compile(module, str(ROOT / "daily_state.py"), "exec"), namespace)
host = SimpleNamespace()
host._memory_afterglow_decay = lambda cond, now: namespace["_memory_afterglow_decay"](cond, now=now)
condition = {"kind": "memory_afterglow", "energy_delta": -8, "start_ts": 1000.0, "half_life_seconds": 100.0}
values = [namespace["_condition_effective_energy_delta"](host, condition, now=at) for at in (1000.0, 1100.0, 1200.0)]
self.assertEqual([-8, -4, -2], values)
if __name__ == "__main__":
unittest.main()