比较提交

..

10 提交

共有 20 个文件被更改,包括 1552 次插入 和 30 次删除

46
core/affect_modulation.py 普通文件
查看文件

@ -0,0 +1,46 @@
"""Bounded affect modulation DTO shared across companion plugins."""
from __future__ import annotations
import hashlib
import math
from typing import Any, Mapping
AFFECT_MODULATION_VERSION = "affect_modulation.v1"
AFFECT_MODULATION_FIELDS = ("schema_version", "valence", "arousal", "vulnerability", "confidence", "source_event_ids", "computed_at")
AFFECT_MODULATION_FINGERPRINT = hashlib.sha256("|".join(AFFECT_MODULATION_FIELDS).encode("ascii")).hexdigest()[:20]
def _number(value: Any, default: float, low: float, high: float) -> float:
if type(value) not in {int, float}:
return default
numeric = float(value)
if not math.isfinite(numeric):
return default
return round(max(low, min(high, numeric)), 4)
def normalize_affect_modulation(value: Any) -> dict[str, Any]:
source = dict(value) if isinstance(value, Mapping) else {}
raw_ids = source.get("source_event_ids")
ids: list[str] = []
if isinstance(raw_ids, (list, tuple)):
for item in raw_ids[:12]:
if type(item) is not str:
continue
cleaned = " ".join(item.split())[:96]
if cleaned and cleaned not in ids:
ids.append(cleaned)
computed_at = source.get("computed_at")
return {
"schema_version": AFFECT_MODULATION_VERSION,
"valence": _number(source.get("valence"), 0.0, -1.0, 1.0),
"arousal": _number(source.get("arousal"), 0.0, 0.0, 1.0),
"vulnerability": _number(source.get("vulnerability"), 0.0, 0.0, 1.0),
"confidence": _number(source.get("confidence"), 0.0, 0.0, 1.0),
"source_event_ids": ids,
"computed_at": float(computed_at) if type(computed_at) in {int, float} and math.isfinite(float(computed_at)) else 0.0,
}
__all__ = ["AFFECT_MODULATION_FIELDS", "AFFECT_MODULATION_FINGERPRINT", "AFFECT_MODULATION_VERSION", "normalize_affect_modulation"]

查看文件

@ -34,7 +34,13 @@ _COMPANION_INTERACTION_BANDS = {
"close",
"affectionate",
}
_COMPANION_EXPRESSION_CONTRACT = "companion_interaction_expression.v1"
_COMPANION_EXPRESSION_CONTRACTS = {"companion_interaction_expression.v1", "companion_interaction_expression.v2"}
_COMPANION_EXPRESSION_PACING = {"slow", "steady", "bright"}
_COMPANION_EXPRESSION_DIRECTNESS = {"indirect", "natural", "direct"}
_COMPANION_EXPRESSION_VALIDATION = {"none", "acknowledge", "support_first"}
_COMPANION_EXPRESSION_DISCLOSURE = {"none", "light", "allowed"}
_COMPANION_EXPRESSION_HUMOR = {"off", "light", "playful"}
_COMPANION_EXPRESSION_TOPIC = {"reply_only", "followup", "shared_topic"}
_COMPANION_EXPRESSION_BEHAVIORS = {
"acknowledge",
"brief_reply",
@ -68,6 +74,7 @@ _COMPANION_EXPRESSION_REASON_CODES = {
"low_energy_expression_cap",
"down_mood_expression_cap",
"up_mood_expression_lift",
"affect_modulation_applied",
"relationship_proactive_cap",
"interaction_proactive_suppressed",
"schedule_proactive_suppressed",
@ -80,7 +87,7 @@ def sanitize_companion_expression_decision(value: Any) -> dict[str, Any]:
"""Accept only the bounded, request-scoped Companion expression contract."""
fallback = {"status": "invalid", "read_only": True, "decision": {}}
if type(value) is not dict or value.get("contract") != _COMPANION_EXPRESSION_CONTRACT:
if type(value) is not dict or value.get("contract") not in _COMPANION_EXPRESSION_CONTRACTS:
return fallback
expression_band = value.get("expression_band")
if type(expression_band) is not str or expression_band not in _COMPANION_INTERACTION_BANDS:
@ -105,16 +112,33 @@ def sanitize_companion_expression_decision(value: Any) -> dict[str, Any]:
return fallback
if type(value.get("followup")) is not bool:
return fallback
contract = value.get("contract")
dimensions: dict[str, str] = {}
if contract == "companion_interaction_expression.v2":
dimension_specs = {
"pacing": _COMPANION_EXPRESSION_PACING,
"directness": _COMPANION_EXPRESSION_DIRECTNESS,
"validation_style": _COMPANION_EXPRESSION_VALIDATION,
"self_disclosure": _COMPANION_EXPRESSION_DISCLOSURE,
"humor_mode": _COMPANION_EXPRESSION_HUMOR,
"topic_initiative": _COMPANION_EXPRESSION_TOPIC,
}
for key, allowed in dimension_specs.items():
item = value.get(key)
if type(item) is not str or item not in allowed:
return fallback
dimensions[key] = item
return {
"status": "accepted",
"read_only": True,
"decision": {
"contract": _COMPANION_EXPRESSION_CONTRACT,
"contract": contract,
"expression_band": expression_band,
"allowed_behaviors": list(allowed_behaviors),
"safety_mode": safety_mode,
"blocker": blocker,
"reason_codes": list(reason_codes),
**dimensions,
},
}
@ -167,13 +191,29 @@ def sanitize_companion_relationship_projection(value: Any) -> dict[str, Any]:
if type(current_interaction) is dict:
expression_band = current_interaction.get("expression_band")
if type(expression_band) is str and expression_band in _COMPANION_INTERACTION_BANDS:
projection["current_interaction"] = {
interaction_projection = {
"expression_band": expression_band,
"label": clean_text(current_interaction.get("label"), 40),
"source": clean_text(current_interaction.get("source"), 40),
"reason": clean_text(current_interaction.get("reason"), 120),
"manual_override": current_interaction.get("manual_override") is True,
}
dynamics_version = current_interaction.get("dynamics_version")
recovery_band = current_interaction.get("recovery_band")
expires_at = current_interaction.get("expires_at")
projection_revision = current_interaction.get("projection_revision")
if dynamics_version == "interaction_dynamics.v1" and recovery_band in {"steady", "recovering", "reinforced"}:
if type(expires_at) not in {int, float} or type(expires_at) is bool:
return fallback
if type(projection_revision) is not int or not 1 <= projection_revision <= 1000000:
return fallback
interaction_projection.update({
"dynamics_version": dynamics_version,
"recovery_band": recovery_band,
"expires_at": max(0.0, min(10**12, float(expires_at))),
"projection_revision": projection_revision,
})
projection["current_interaction"] = interaction_projection
return {"status": "accepted", "read_only": True, "projection": projection}
@ -1093,9 +1133,88 @@ class MemoryCompanionBridge:
return await self._plugin.store.update_memory_visibility(memory_id, visibility)
def get_emotional_events(self, *, session_id: str = "", limit: int = 5) -> list[dict[str, Any]]:
"""Retrieve pending emotional drift events for the companion plugin."""
"""Legacy read-and-remove compatibility path; new consumers use list/ack."""
return self._plugin.bridge_get_emotional_events(session_id=session_id, limit=limit)
async def list_emotion_events(
self,
*,
consumer_id: str,
cursor: str = "",
session_id: str = "",
exclude_session_id: str = "",
limit: int = 10,
) -> dict[str, Any]:
"""List redacted pending afterglow events without consuming them."""
return await self._plugin.store.list_emotion_event_deliveries(
consumer_id=consumer_id,
cursor=cursor,
session_id=session_id,
exclude_session_id=exclude_session_id,
limit=limit,
)
async def ack_emotion_events(
self,
event_refs: list[dict[str, Any]],
*,
consumer_id: str,
) -> dict[str, Any]:
"""Acknowledge only events durably applied by the named consumer."""
return await self._plugin.store.ack_emotion_event_deliveries(
consumer_id=consumer_id,
event_refs=event_refs,
)
async def record_emotion_event(self, event: dict[str, Any]) -> dict[str, Any]:
"""Persist one redacted event revision outside normal memory retrieval."""
return await self._plugin.store.upsert_emotion_event(event)
async def revise_emotion_event(self, event: dict[str, Any]) -> dict[str, Any]:
"""Persist a later revision of an existing event."""
return await self._plugin.store.upsert_emotion_event(event)
async def get_emotion_trace(self, trace_id: str, *, limit: int = 100) -> list[dict[str, Any]]:
return await self._plugin.store.get_emotion_trace(trace_id, limit=limit)
async def get_emotion_trace_diagnostic(
self,
trace_id: str,
requester_context: dict[str, Any],
*,
limit: int = 100,
) -> dict[str, Any]:
context = requester_context if type(requester_context) is dict else {}
if context.get("is_admin") is not True:
return {"state": "forbidden", "read_only": True, "items": [], "error_code": "admin_required"}
items = await self._plugin.store.get_emotion_trace_diagnostic(
trace_id,
bot_id=clean_text(context.get("bot_id"), 160),
scope=clean_text(context.get("scope"), 24),
session_id=clean_text(context.get("session_id"), 220),
limit=max(1, min(100, int(limit or 100))),
)
return {"state": "ready", "read_only": True, "items": items}
async def get_emotion_trace_summary(
self,
requester_context: dict[str, Any],
*,
cursor: str = "",
limit: int = 20,
) -> dict[str, Any]:
context = requester_context if type(requester_context) is dict else {}
if context.get("is_admin") is not True:
return {"state": "forbidden", "read_only": True, "items": [], "next_cursor": "", "error_code": "admin_required"}
result = await self._plugin.store.get_emotion_trace_summary(
bot_id=clean_text(context.get("bot_id"), 160),
scope=clean_text(context.get("scope"), 24),
session_id=clean_text(context.get("session_id"), 220),
cursor=clean_text(cursor, 20),
limit=max(1, min(100, int(limit or 20))),
)
return {"state": "ready", "read_only": True, **result}
async def search_open_loops(self, *, session_id: str = "", limit: int = 3) -> list[dict[str, Any]]:
"""Search for unresolved open-loop / promise memories for proactive companionship."""
return await self._plugin.bridge_search_open_loops(session_id=session_id, limit=limit)
@ -1186,7 +1305,13 @@ class MemoryCompanionBridge:
projection["touch_count"] = touch_count
return projection
def get_recent_emotional_state(self) -> dict[str, Any]:
def get_recent_emotional_state(
self,
*,
exclude_session_id: str = "",
window_seconds: float = 1800.0,
limit: int = 5,
) -> dict[str, Any]:
"""Return a summary of recent emotional events across ALL sessions.
This provides cross-window emotional continuity for the companion plugin:
@ -1196,7 +1321,11 @@ class MemoryCompanionBridge:
getter = getattr(self._plugin, "_get_cross_window_emotional_state", None)
if not callable(getter):
return {"total": 0, "scar_count": 0, "warm_count": 0, "vulnerable_count": 0}
return getter()
return getter(
exclude_session_id=exclude_session_id,
window_seconds=window_seconds,
limit=limit,
)
def _entity(self, payload: dict[str, Any]) -> EntityRef:
return EntityRef(

查看文件

@ -0,0 +1,162 @@
"""Versioned, redacted emotion-event contract shared across companion plugins."""
from __future__ import annotations
from datetime import datetime, timezone
import hashlib
import json
import math
import re
from typing import Any, Mapping
EMOTION_EVENT_SCHEMA_VERSION = "companion_emotion_event.v1"
EMOTION_EVENT_TYPES = frozenset({
"neutral", "hurt", "apology", "comfort", "praise", "comfort_need",
"external_negative", "scar_touched", "warm_memory", "vulnerable_resonance",
"play", "intimacy", "boundary",
})
EMOTION_EVENT_ORIGINS = frozenset({"interaction", "memory_recall", "system_condition"})
EMOTION_EVENT_STATUSES = frozenset({"observed", "revised", "applied", "ignored", "expired"})
EMOTION_EVENT_CONTRACT_FIELDS = (
"schema_version", "event_id", "trace_id", "revision", "producer_plugin",
"origin_kind", "platform", "bot_id", "scope", "session_id", "actor_ref",
"target_ref", "quoted_target_ref", "event_type", "intensity", "confidence",
"valence_hint", "arousal_hint", "vulnerability_hint", "source_rule",
"occurred_at", "expires_at", "dedupe_key", "payload_hash", "privacy_level",
"applied_interaction", "applied_energy_delta", "correction_of", "status",
"reason_codes",
)
EMOTION_EVENT_CONTRACT_FINGERPRINT = hashlib.sha256(
"|".join(EMOTION_EVENT_CONTRACT_FIELDS).encode("ascii")
).hexdigest()[:20]
def _text(value: Any, limit: int) -> str:
text = re.sub(r"\s+", " ", str(value or "").replace("\u3000", " ")).strip()
return text[:limit]
def _number(value: Any, default: float, low: float, high: float) -> float:
if isinstance(value, bool):
return default
try:
number = float(value)
except (TypeError, ValueError):
return default
if not math.isfinite(number):
return default
return round(max(low, min(high, number)), 4)
def _integer(value: Any, default: int = 1) -> int:
if isinstance(value, bool):
return default
try:
return max(1, min(1_000_000, int(value)))
except (TypeError, ValueError):
return default
def _entity(value: Any) -> dict[str, str]:
source = value if isinstance(value, Mapping) else {}
return {
"kind": _text(source.get("kind"), 24) or "unknown",
"id": _text(source.get("id"), 160),
"role": _text(source.get("role"), 40),
}
def _timestamp(value: Any) -> str:
text = _text(value, 48)
if text:
return text
return datetime.now(timezone.utc).isoformat(timespec="seconds")
def _stable_hash(*parts: Any) -> str:
raw = "|".join(_text(part, 500) for part in parts)
return hashlib.sha256(raw.encode("utf-8", errors="ignore")).hexdigest()
def normalize_emotion_event(value: Any, *, producer_plugin: str = "") -> dict[str, Any]:
"""Return a bounded JSON-safe event without retaining raw message content."""
source = dict(value) if isinstance(value, Mapping) else {}
producer = _text(source.get("producer_plugin") or producer_plugin, 80) or "unknown"
origin = _text(source.get("origin_kind"), 40)
if origin not in EMOTION_EVENT_ORIGINS:
origin = "interaction"
event_type = _text(source.get("event_type"), 48).lower()
if event_type not in EMOTION_EVENT_TYPES:
event_type = "neutral"
status = _text(source.get("status"), 24).lower()
if status not in EMOTION_EVENT_STATUSES:
status = "observed"
session_id = _text(source.get("session_id"), 220)
dedupe_key = _text(source.get("dedupe_key"), 160)
payload_hash = _text(source.get("payload_hash"), 80)
if not payload_hash:
payload_hash = _stable_hash(
producer, origin, session_id, event_type, dedupe_key,
source.get("message_fingerprint"), source.get("source_rule"),
)
event_id = _text(source.get("event_id"), 96)
if not event_id:
event_id = "emo_" + _stable_hash(producer, origin, session_id, event_type, dedupe_key, payload_hash)[:24]
trace_id = _text(source.get("trace_id"), 96)
if not trace_id:
trace_id = "etr_" + _stable_hash(session_id, dedupe_key or event_id)[:24]
reason_codes = source.get("reason_codes")
if not isinstance(reason_codes, (list, tuple)):
reason_codes = []
clean_reasons: list[str] = []
for item in reason_codes[:12]:
reason = _text(item, 64)
if reason and reason not in clean_reasons:
clean_reasons.append(reason)
return {
"schema_version": EMOTION_EVENT_SCHEMA_VERSION,
"event_id": event_id,
"trace_id": trace_id,
"revision": _integer(source.get("revision"), 1),
"producer_plugin": producer,
"origin_kind": origin,
"platform": _text(source.get("platform"), 80),
"bot_id": _text(source.get("bot_id"), 160),
"scope": _text(source.get("scope"), 24) or "private",
"session_id": session_id,
"actor_ref": _entity(source.get("actor_ref")),
"target_ref": _entity(source.get("target_ref")),
"quoted_target_ref": _entity(source.get("quoted_target_ref")),
"event_type": event_type,
"intensity": _number(source.get("intensity"), 0.0, 0.0, 100.0),
"confidence": _number(source.get("confidence"), 0.0, 0.0, 1.0),
"valence_hint": _number(source.get("valence_hint"), 0.0, -1.0, 1.0),
"arousal_hint": _number(source.get("arousal_hint"), 0.0, 0.0, 1.0),
"vulnerability_hint": _number(source.get("vulnerability_hint"), 0.0, 0.0, 1.0),
"source_rule": _text(source.get("source_rule"), 80),
"occurred_at": _timestamp(source.get("occurred_at")),
"expires_at": _text(source.get("expires_at"), 48),
"dedupe_key": dedupe_key or payload_hash[:32],
"payload_hash": payload_hash,
"privacy_level": _text(source.get("privacy_level"), 24) or "redacted",
"applied_interaction": _text(source.get("applied_interaction"), 32),
"applied_energy_delta": _number(source.get("applied_energy_delta"), 0.0, -100.0, 100.0),
"correction_of": _text(source.get("correction_of"), 96),
"status": status,
"reason_codes": clean_reasons,
}
def emotion_event_json(value: Any, *, producer_plugin: str = "") -> str:
return json.dumps(normalize_emotion_event(value, producer_plugin=producer_plugin), ensure_ascii=False, separators=(",", ":"))
__all__ = [
"EMOTION_EVENT_CONTRACT_FIELDS",
"EMOTION_EVENT_CONTRACT_FINGERPRINT",
"EMOTION_EVENT_SCHEMA_VERSION",
"EMOTION_EVENT_STATUSES",
"EMOTION_EVENT_TYPES",
"emotion_event_json",
"normalize_emotion_event",
]

31
core/emotion_targeting.py 普通文件
查看文件

@ -0,0 +1,31 @@
"""Validate memory-event attribution against the active visibility domain."""
from __future__ import annotations
from typing import Any
from .models import clean_text
def memory_emotion_refs(memory: Any, ctx: Any) -> dict[str, dict[str, str]] | None:
memory_session = clean_text(getattr(memory, "session_id", ""), 220)
current_session = clean_text(getattr(ctx, "session_id", ""), 220)
if memory_session and current_session and memory_session != current_session:
return None
subject = getattr(memory, "subject", None)
subject_kind = clean_text(getattr(subject, "kind", ""), 24)
subject_id = clean_text(getattr(subject, "id", ""), 160)
user_id = clean_text(getattr(ctx, "user_id", ""), 160)
bot_id = clean_text(getattr(ctx, "bot_id", ""), 160) or "self"
if subject_kind == "user" and user_id and subject_id != user_id:
return None
if subject_kind not in {"user", "bot"} or not subject_id:
return None
return {
"actor_ref": {"kind": subject_kind, "id": subject_id, "role": clean_text(getattr(subject, "role", ""), 40)},
"target_ref": {"kind": "bot", "id": bot_id, "role": "bot_self"},
"quoted_target_ref": {"kind": "unknown", "id": "", "role": ""},
}
__all__ = ["memory_emotion_refs"]

查看文件

@ -84,12 +84,23 @@ class SessionContext:
companion_relationship_phase_label: str = ""
companion_relationship_tone: str = ""
companion_relationship_address_level: str = ""
companion_interaction_dynamics_version: str = ""
companion_interaction_band: str = ""
companion_interaction_recovery_band: str = ""
companion_interaction_expires_at: float = 0.0
companion_interaction_projection_revision: int = 0
companion_expression_contract: str = ""
companion_expression_band: str = ""
companion_expression_allowed_behaviors: tuple[str, ...] = ()
companion_expression_safety_mode: str = ""
companion_expression_blocker: str = ""
companion_expression_reason_codes: tuple[str, ...] = ()
companion_expression_pacing: str = ""
companion_expression_directness: str = ""
companion_expression_validation_style: str = ""
companion_expression_self_disclosure: str = ""
companion_expression_humor_mode: str = ""
companion_expression_topic_initiative: str = ""
@property
def current_target_id(self) -> str:

查看文件

@ -39,6 +39,8 @@ from .chat_import import HistoricalChatImporter
from .classifier import MemoryClassifier
from .config import ConfigView
from .context_orchestrator import RetrievalIntent, RetrievalIntentBuilder
from .emotion_event_contract import normalize_emotion_event
from .emotion_targeting import memory_emotion_refs
from .identity import IdentityResolver, looks_like_command, maybe_await, normalize_session_context_fields, session_target_id
from .importance import ImportanceEvaluator
from .injection import (
@ -725,6 +727,17 @@ class MemoryCompanionService:
ctx.companion_relationship_phase_label = clean_text(projection.get("phase_label"), 40)
ctx.companion_relationship_tone = clean_text(projection.get("tone"), 160)
ctx.companion_relationship_address_level = clean_text(projection.get("address_level"), 120)
interaction = projection.get("current_interaction")
if isinstance(interaction, dict):
ctx.companion_interaction_dynamics_version = clean_text(interaction.get("dynamics_version"), 48)
ctx.companion_interaction_band = clean_text(interaction.get("expression_band"), 24)
ctx.companion_interaction_recovery_band = clean_text(interaction.get("recovery_band"), 24)
try:
ctx.companion_interaction_expires_at = max(0.0, min(10**12, float(interaction.get("expires_at") or 0.0)))
ctx.companion_interaction_projection_revision = max(0, min(1000000, int(interaction.get("projection_revision") or 0)))
except (TypeError, ValueError):
ctx.companion_interaction_expires_at = 0.0
ctx.companion_interaction_projection_revision = 0
@staticmethod
def _apply_private_companion_preferred_address(
@ -773,6 +786,12 @@ class MemoryCompanionService:
ctx.companion_expression_safety_mode = clean_text(decision.get("safety_mode"), 60)
ctx.companion_expression_blocker = clean_text(decision.get("blocker"), 60)
ctx.companion_expression_reason_codes = tuple(decision.get("reason_codes") or ())
ctx.companion_expression_pacing = clean_text(decision.get("pacing"), 24)
ctx.companion_expression_directness = clean_text(decision.get("directness"), 24)
ctx.companion_expression_validation_style = clean_text(decision.get("validation_style"), 24)
ctx.companion_expression_self_disclosure = clean_text(decision.get("self_disclosure"), 24)
ctx.companion_expression_humor_mode = clean_text(decision.get("humor_mode"), 24)
ctx.companion_expression_topic_initiative = clean_text(decision.get("topic_initiative"), 24)
def _sanitize_visible_timeline_text(self, text: Any) -> str:
cleaned = clean_text(text, 1200)
@ -1673,7 +1692,7 @@ class MemoryCompanionService:
break
return open_loops
def _detect_and_queue_emotional_events(
async def _detect_and_queue_emotional_events(
self,
ctx: SessionContext,
results: list[Any],
@ -1716,6 +1735,9 @@ class MemoryCompanionService:
mood_hint = "柔软"
if not event_type:
continue
refs = memory_emotion_refs(memory, ctx)
if refs is None:
continue
# Mood resonance check: if Bot is already in a contrasting mood, dampen the drift
if companion_bot_mood:
mood_lower = companion_bot_mood.strip().lower()
@ -1727,23 +1749,49 @@ class MemoryCompanionService:
event_id = hashlib.sha1(
f"{ctx.session_id}|{event_key}|{memory.id}|{event_type}".encode("utf-8", errors="ignore")
).hexdigest()[:20]
events.append({
"id": f"emo_{event_id}",
"ts": now,
event = normalize_emotion_event({
"event_id": f"emo_{event_id}",
"trace_id": f"etr_{event_id}",
"producer_plugin": "memory_companion",
"origin_kind": "memory_recall",
"platform": ctx.platform,
"bot_id": ctx.bot_id,
"scope": ctx.scope,
"session_id": ctx.session_id,
**refs,
"event_type": event_type,
"intensity": max(scar_w, emotional_w, vulnerability_w) * 100.0,
"confidence": max(0.5, min(1.0, getattr(item, "score", 0.5))),
"valence_hint": 0.35 if event_type == "warm_memory" else -0.45 if event_type == "scar_touched" else -0.1,
"arousal_hint": min(1.0, max(scar_w, emotional_w)),
"vulnerability_hint": max(vulnerability_w, 0.6 if event_type == "vulnerable_resonance" else 0.0),
"source_rule": event_type,
"occurred_at": datetime.fromtimestamp(now, tz=timezone.utc).isoformat(timespec="seconds"),
"dedupe_key": f"{ctx.session_id}|{event_key}|{memory.id}|{event_type}",
"payload_hash": hashlib.sha256(memory.id.encode("utf-8", errors="ignore")).hexdigest(),
"privacy_level": "redacted",
"applied_energy_delta": round(energy_delta, 2),
"status": "observed",
"reason_codes": [event_type, "memory_recall_resonance"],
}, producer_plugin="memory_companion")
event.update({
"id": event["event_id"],
"ts": now,
"memory_id": memory.id,
"energy_delta": round(energy_delta, 2),
"mood_hint": mood_hint,
"scar_weight": round(scar_w, 3),
"emotional_weight": round(emotional_w, 3),
"content_preview": clean_text(memory.content, 120),
})
events.append(event)
if not events:
return
queue = self._emotional_event_queue.setdefault(ctx.session_id, [])
existing_ids = {clean_text(item.get("id"), 80) for item in queue if isinstance(item, dict)}
queue.extend(event for event in events if clean_text(event.get("id"), 80) not in existing_ids)
fresh_events = [event for event in events if clean_text(event.get("id"), 80) not in existing_ids]
queue.extend(fresh_events)
for event in fresh_events:
await self.store.upsert_emotion_event(event)
# Trim old events
queue[:] = [e for e in queue if (now - e.get("ts", 0)) < self._EMOTIONAL_EVENT_TTL]
if len(queue) > self._EMOTIONAL_EVENT_MAX_PER_SESSION:
@ -1792,7 +1840,13 @@ class MemoryCompanionService:
return ""
return " ".join(hints)
def _get_cross_window_emotional_state(self) -> dict[str, Any]:
def _get_cross_window_emotional_state(
self,
*,
exclude_session_id: str = "",
window_seconds: float = 1800.0,
limit: int = 5,
) -> dict[str, Any]:
"""Return a summary of recent emotional events across all sessions for the companion plugin."""
if not self.config.bool("private_companion_bridge.cross_window_emotional_continuity_enabled", False):
return {
@ -1803,13 +1857,23 @@ class MemoryCompanionService:
"vulnerable_count": 0,
}
now = time.time()
recent_window = 1800.0
recent_window = max(60.0, min(86400.0, float(window_seconds or 1800.0)))
excluded = clean_text(exclude_session_id, 220)
all_events: list[dict[str, Any]] = []
for session_id, queue in self._emotional_event_queue.items():
if excluded and session_id == excluded:
continue
for event in queue:
age = now - event.get("ts", 0)
if age < recent_window:
all_events.append({**event, "age_seconds": round(age, 0)})
all_events.append({
"event_id": clean_text(event.get("event_id") or event.get("id"), 96),
"session_id": clean_text(event.get("session_id"), 220),
"event_type": clean_text(event.get("event_type"), 48),
"energy_delta": max(-8.0, min(5.0, float(event.get("energy_delta") or 0.0))),
"age_seconds": round(max(0.0, age), 0),
"ts": float(event.get("ts") or 0.0),
})
if not all_events:
return {"total": 0, "scar_count": 0, "warm_count": 0, "vulnerable_count": 0}
all_events.sort(key=lambda e: e.get("ts", 0), reverse=True)
@ -1818,7 +1882,7 @@ class MemoryCompanionService:
"scar_count": sum(1 for e in all_events if e.get("event_type") == "scar_touched"),
"warm_count": sum(1 for e in all_events if e.get("event_type") == "warm_memory"),
"vulnerable_count": sum(1 for e in all_events if e.get("event_type") == "vulnerable_resonance"),
"recent": all_events[:5],
"recent": all_events[: max(1, min(20, int(limit or 5)))],
}
async def _retrieval_cache_key(
@ -4893,7 +4957,7 @@ class MemoryCompanionService:
slot_map,
recent_fact_context=(recent_fact_context if "<recent_fact_context>" in injection else ""),
)
self._detect_and_queue_emotional_events(
await self._detect_and_queue_emotional_events(
ctx, results,
companion_bot_mood=merged_bot_mood,
companion_bot_energy=merged_bot_energy,
@ -5195,7 +5259,7 @@ class MemoryCompanionService:
slot_map,
recent_fact_context=(recent_fact_context if "<recent_fact_context>" in injection else ""),
)
self._detect_and_queue_emotional_events(
await self._detect_and_queue_emotional_events(
ctx, results,
companion_bot_mood=_bot_mood,
companion_bot_energy=_bot_energy,

查看文件

@ -1,6 +1,7 @@
from __future__ import annotations
import asyncio
import hashlib
from contextlib import closing, contextmanager
from copy import deepcopy
import re
@ -487,6 +488,54 @@ class MemoryStore:
updated_at TEXT NOT NULL DEFAULT '',
PRIMARY KEY(memory_id, provider_id)
);
CREATE TABLE IF NOT EXISTS emotion_events (
event_id TEXT NOT NULL,
revision INTEGER NOT NULL DEFAULT 1,
trace_id TEXT NOT NULL DEFAULT '',
producer_plugin TEXT NOT NULL DEFAULT '',
origin_kind TEXT NOT NULL DEFAULT '',
platform TEXT NOT NULL DEFAULT '',
bot_id TEXT NOT NULL DEFAULT '',
scope TEXT NOT NULL DEFAULT '',
session_id TEXT NOT NULL DEFAULT '',
actor_ref TEXT NOT NULL DEFAULT '{}',
target_ref TEXT NOT NULL DEFAULT '{}',
quoted_target_ref TEXT NOT NULL DEFAULT '{}',
event_type TEXT NOT NULL DEFAULT 'neutral',
intensity REAL NOT NULL DEFAULT 0,
confidence REAL NOT NULL DEFAULT 0,
valence_hint REAL NOT NULL DEFAULT 0,
arousal_hint REAL NOT NULL DEFAULT 0,
vulnerability_hint REAL NOT NULL DEFAULT 0,
source_rule TEXT NOT NULL DEFAULT '',
occurred_at TEXT NOT NULL DEFAULT '',
expires_at TEXT NOT NULL DEFAULT '',
dedupe_key TEXT NOT NULL DEFAULT '',
payload_hash TEXT NOT NULL DEFAULT '',
privacy_level TEXT NOT NULL DEFAULT 'redacted',
applied_interaction TEXT NOT NULL DEFAULT '',
applied_energy_delta REAL NOT NULL DEFAULT 0,
correction_of TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL DEFAULT 'observed',
reason_codes TEXT NOT NULL DEFAULT '[]',
created_at TEXT NOT NULL DEFAULT '',
PRIMARY KEY(event_id, revision)
);
CREATE TABLE IF NOT EXISTS emotion_event_deliveries (
event_id TEXT NOT NULL,
revision INTEGER NOT NULL DEFAULT 1,
consumer_id TEXT NOT NULL,
attempts INTEGER NOT NULL DEFAULT 0,
first_delivered_at TEXT NOT NULL DEFAULT '',
last_delivered_at TEXT NOT NULL DEFAULT '',
acked_at TEXT NOT NULL DEFAULT '',
PRIMARY KEY(event_id, revision, consumer_id),
FOREIGN KEY(event_id, revision)
REFERENCES emotion_events(event_id, revision)
ON DELETE CASCADE
);
"""
)
self._ensure_memory_columns_sync()
@ -539,6 +588,19 @@ class MemoryStore:
self._conn.execute(
"CREATE INDEX IF NOT EXISTS idx_memory_embeddings_provider ON memory_embeddings(provider_id, updated_at)"
)
self._conn.execute(
"CREATE INDEX IF NOT EXISTS idx_emotion_events_trace ON emotion_events(trace_id, revision)"
)
self._conn.execute(
"CREATE INDEX IF NOT EXISTS idx_emotion_events_session ON emotion_events(bot_id, scope, session_id, occurred_at DESC)"
)
self._conn.execute(
"CREATE INDEX IF NOT EXISTS idx_emotion_events_dedupe ON emotion_events(dedupe_key, event_type)"
)
self._conn.execute(
"CREATE INDEX IF NOT EXISTS idx_emotion_event_deliveries_pending "
"ON emotion_event_deliveries(consumer_id, acked_at, last_delivered_at)"
)
self._conn.commit()
def _ensure_retrieval_revision_sync(self) -> None:
@ -5528,3 +5590,426 @@ class MemoryStore:
)
self._conn.commit()
return row_id
async def upsert_emotion_event(self, value: Any) -> dict[str, Any]:
return await self._run_recoverable_database_operation(self._upsert_emotion_event_sync, value)
def _upsert_emotion_event_sync(self, value: Any) -> dict[str, Any]:
from .emotion_event_contract import normalize_emotion_event
event = normalize_emotion_event(value, producer_plugin="memory_companion")
with self._lock:
self._conn.execute(
"""
INSERT OR IGNORE INTO emotion_events(
event_id, revision, trace_id, 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, created_at
) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
""",
(
event["event_id"], event["revision"], event["trace_id"], event["producer_plugin"],
event["origin_kind"], event["platform"], event["bot_id"], event["scope"],
event["session_id"], json_dumps(event["actor_ref"]), json_dumps(event["target_ref"]),
json_dumps(event["quoted_target_ref"]), event["event_type"], event["intensity"],
event["confidence"], event["valence_hint"], event["arousal_hint"],
event["vulnerability_hint"], event["source_rule"], event["occurred_at"],
event["expires_at"], event["dedupe_key"], event["payload_hash"],
event["privacy_level"], event["applied_interaction"], event["applied_energy_delta"],
event["correction_of"], event["status"], json_dumps(event["reason_codes"]), utc_now(),
),
)
self._conn.commit()
return event
async def get_emotion_trace(self, trace_id: str, *, limit: int = 100) -> list[dict[str, Any]]:
return await self._run_recoverable_database_operation(self._get_emotion_trace_sync, trace_id, limit)
def _get_emotion_trace_sync(self, trace_id: str, limit: int) -> list[dict[str, Any]]:
trace = clean_text(trace_id, 96)
if not trace:
return []
with self._lock:
rows = self._conn.execute(
"SELECT * FROM emotion_events WHERE trace_id=? ORDER BY revision ASC LIMIT ?",
(trace, max(1, min(500, int(limit or 100)))),
).fetchall()
return [self._emotion_event_row(row) for row in rows]
async def get_emotion_trace_diagnostic(
self,
trace_id: str,
*,
bot_id: str = "",
scope: str = "",
session_id: str = "",
limit: int = 100,
) -> list[dict[str, Any]]:
return await self._run_recoverable_database_operation(
self._get_emotion_trace_diagnostic_sync, trace_id, bot_id, scope, session_id, limit
)
def _get_emotion_trace_diagnostic_sync(
self,
trace_id: str,
bot_id: str,
scope: str,
session_id: str,
limit: int,
) -> list[dict[str, Any]]:
trace = clean_text(trace_id, 96)
if not trace:
return []
clauses = ["e.trace_id=?"]
params: list[Any] = [trace]
for column, value, size in (("bot_id", bot_id, 160), ("scope", scope, 24), ("session_id", session_id, 220)):
cleaned = clean_text(value, size)
if cleaned:
clauses.append(f"e.{column}=?")
params.append(cleaned)
params.append(max(1, min(100, int(limit or 100))))
with self._lock:
rows = self._conn.execute(
f"SELECT e.* FROM emotion_events e WHERE {' AND '.join(clauses)} ORDER BY e.revision ASC LIMIT ?",
params,
).fetchall()
result: list[dict[str, Any]] = []
for row in rows:
event = self._emotion_event_row(row)
deliveries = self._conn.execute(
"""
SELECT consumer_id, attempts, first_delivered_at, last_delivered_at, acked_at
FROM emotion_event_deliveries
WHERE event_id=? AND revision=?
ORDER BY consumer_id ASC LIMIT 20
""",
(event["event_id"], event["revision"]),
).fetchall()
result.append(self._emotion_diagnostic_projection(event, deliveries))
return result
async def get_emotion_trace_summary(
self,
*,
bot_id: str = "",
scope: str = "",
session_id: str = "",
cursor: str = "",
limit: int = 20,
) -> dict[str, Any]:
return await self._run_recoverable_database_operation(
self._get_emotion_trace_summary_sync, bot_id, scope, session_id, cursor, limit
)
def _get_emotion_trace_summary_sync(
self,
bot_id: str,
scope: str,
session_id: str,
cursor: str,
limit: int,
) -> dict[str, Any]:
clauses = ["1=1"]
params: list[Any] = []
for column, value, size in (("bot_id", bot_id, 160), ("scope", scope, 24), ("session_id", session_id, 220)):
cleaned = clean_text(value, size)
if cleaned:
clauses.append(f"e.{column}=?")
params.append(cleaned)
try:
offset = max(0, min(100000, int(cursor or 0)))
except (TypeError, ValueError):
offset = 0
bounded = max(1, min(100, int(limit or 20)))
params.extend((bounded + 1, offset))
with self._lock:
rows = self._conn.execute(
f"""
SELECT e.* FROM emotion_events e
JOIN (SELECT event_id, MAX(revision) revision FROM emotion_events GROUP BY event_id) latest
ON latest.event_id=e.event_id AND latest.revision=e.revision
WHERE {' AND '.join(clauses)}
ORDER BY e.occurred_at DESC, e.event_id DESC
LIMIT ? OFFSET ?
""",
params,
).fetchall()
page = [self._emotion_event_row(row) for row in rows[:bounded]]
return {
"items": [{
"trace_id": clean_text(item.get("trace_id"), 96),
"event_id": clean_text(item.get("event_id"), 96),
"revision": int(item.get("revision") or 1),
"event_type": clean_text(item.get("event_type"), 48),
"status": clean_text(item.get("status"), 24),
"occurred_at": clean_text(item.get("occurred_at"), 48),
"session_hash": self._diagnostic_hash(item.get("session_id")),
} for item in page],
"next_cursor": str(offset + bounded) if len(rows) > bounded else "",
"has_more": len(rows) > bounded,
}
@classmethod
def _emotion_diagnostic_projection(cls, event: dict[str, Any], deliveries: list[sqlite3.Row]) -> dict[str, Any]:
return {
"schema_version": "emotion_trace_diagnostic.v1",
"event_id": clean_text(event.get("event_id"), 96),
"trace_id": clean_text(event.get("trace_id"), 96),
"revision": int(event.get("revision") or 1),
"producer_plugin": clean_text(event.get("producer_plugin"), 80),
"origin_kind": clean_text(event.get("origin_kind"), 40),
"event_type": clean_text(event.get("event_type"), 48),
"intensity": float(event.get("intensity") or 0.0),
"confidence": float(event.get("confidence") or 0.0),
"status": clean_text(event.get("status"), 24),
"source_rule": clean_text(event.get("source_rule"), 80),
"occurred_at": clean_text(event.get("occurred_at"), 48),
"applied_interaction": clean_text(event.get("applied_interaction"), 32),
"applied_energy_delta": float(event.get("applied_energy_delta") or 0.0),
"correction_of": clean_text(event.get("correction_of"), 96),
"actor": cls._diagnostic_ref(event.get("actor_ref")),
"target": cls._diagnostic_ref(event.get("target_ref")),
"quoted_target": cls._diagnostic_ref(event.get("quoted_target_ref")),
"scope": clean_text(event.get("scope"), 24),
"session_hash": cls._diagnostic_hash(event.get("session_id")),
"deliveries": [{
"consumer_id": clean_text(row["consumer_id"], 80),
"attempts": max(0, int(row["attempts"] or 0)),
"first_delivered_at": clean_text(row["first_delivered_at"], 48),
"last_delivered_at": clean_text(row["last_delivered_at"], 48),
"acked": bool(row["acked_at"]),
"acked_at": clean_text(row["acked_at"], 48),
} for row in deliveries],
}
@classmethod
def _diagnostic_ref(cls, value: Any) -> dict[str, str]:
source = value if isinstance(value, dict) else {}
return {
"kind": clean_text(source.get("kind"), 24),
"role": clean_text(source.get("role"), 40),
"id_hash": cls._diagnostic_hash(source.get("id")),
}
@staticmethod
def _diagnostic_hash(value: Any) -> str:
cleaned = clean_text(value, 220)
return hashlib.sha256(cleaned.encode("utf-8", errors="ignore")).hexdigest()[:12] if cleaned else ""
async def list_emotion_events(
self,
*,
bot_id: str = "",
session_id: str = "",
limit: int = 50,
) -> list[dict[str, Any]]:
return await self._run_recoverable_database_operation(
self._list_emotion_events_sync, bot_id, session_id, limit
)
def _list_emotion_events_sync(self, bot_id: str, session_id: str, limit: int) -> list[dict[str, Any]]:
clauses: list[str] = []
params: list[Any] = []
if clean_text(bot_id, 160):
clauses.append("bot_id=?")
params.append(clean_text(bot_id, 160))
if clean_text(session_id, 220):
clauses.append("session_id=?")
params.append(clean_text(session_id, 220))
where = " WHERE " + " AND ".join(clauses) if clauses else ""
params.append(max(1, min(500, int(limit or 50))))
with self._lock:
rows = self._conn.execute(
f"SELECT * FROM emotion_events{where} ORDER BY occurred_at DESC, revision DESC LIMIT ?",
params,
).fetchall()
return [self._emotion_event_row(row) for row in rows]
async def list_emotion_event_deliveries(
self,
*,
consumer_id: str,
session_id: str = "",
exclude_session_id: str = "",
cursor: str = "",
limit: int = 10,
) -> dict[str, Any]:
return await self._run_recoverable_database_operation(
self._list_emotion_event_deliveries_sync,
consumer_id,
session_id,
exclude_session_id,
cursor,
limit,
)
def _list_emotion_event_deliveries_sync(
self,
consumer_id: str,
session_id: str,
exclude_session_id: str,
cursor: str,
limit: int,
) -> dict[str, Any]:
consumer = clean_text(consumer_id, 80)
if not consumer:
return {"schema_version": "emotion_afterglow_delivery.v1", "events": [], "next_cursor": "", "has_more": False}
session = clean_text(session_id, 220)
excluded = clean_text(exclude_session_id, 220)
bounded_limit = max(1, min(20, int(limit or 10)))
clauses = [
"e.origin_kind='memory_recall'",
"e.status NOT IN ('ignored','expired')",
"COALESCE(d.acked_at, '')=''",
]
params: list[Any] = [consumer]
if session:
clauses.append("e.session_id=?")
params.append(session)
if excluded:
clauses.append("e.session_id!=?")
params.append(excluded)
with self._lock:
rows = self._conn.execute(
f"""
SELECT e.*
FROM emotion_events e
JOIN (
SELECT event_id, MAX(revision) AS revision
FROM emotion_events
GROUP BY event_id
) latest ON latest.event_id=e.event_id AND latest.revision=e.revision
LEFT JOIN emotion_event_deliveries d
ON d.event_id=e.event_id AND d.revision=e.revision AND d.consumer_id=?
WHERE {' AND '.join(clauses)}
ORDER BY e.occurred_at DESC, e.event_id DESC, e.revision DESC
LIMIT 201
""",
params,
).fetchall()
events = [self._emotion_event_row(row) for row in rows]
cursor_value = clean_text(cursor, 400)
if cursor_value:
positions = [self._emotion_delivery_cursor(item) for item in events]
try:
events = events[positions.index(cursor_value) + 1 :]
except ValueError:
events = []
page = events[:bounded_limit]
has_more = len(events) > bounded_limit
delivered_at = utc_now()
for event in page:
self._conn.execute(
"""
INSERT INTO emotion_event_deliveries(
event_id, revision, consumer_id, attempts,
first_delivered_at, last_delivered_at, acked_at
) VALUES(?,?,?,1,?,?,'')
ON CONFLICT(event_id, revision, consumer_id) DO UPDATE SET
attempts=emotion_event_deliveries.attempts+1,
last_delivered_at=excluded.last_delivered_at
""",
(event["event_id"], event["revision"], consumer, delivered_at, delivered_at),
)
self._conn.commit()
projection = [self._emotion_delivery_projection(event) for event in page]
return {
"schema_version": "emotion_afterglow_delivery.v1",
"events": projection,
"next_cursor": self._emotion_delivery_cursor(page[-1]) if page and has_more else "",
"has_more": has_more,
}
async def ack_emotion_event_deliveries(
self,
*,
consumer_id: str,
event_refs: list[dict[str, Any]],
) -> dict[str, Any]:
return await self._run_recoverable_database_operation(
self._ack_emotion_event_deliveries_sync, consumer_id, event_refs
)
def _ack_emotion_event_deliveries_sync(
self,
consumer_id: str,
event_refs: list[dict[str, Any]],
) -> dict[str, Any]:
consumer = clean_text(consumer_id, 80)
if not consumer or not isinstance(event_refs, list):
return {"acked": 0, "consumer_id": consumer}
unique_refs: set[tuple[str, int]] = set()
for item in event_refs[:100]:
if not isinstance(item, dict):
continue
event_id = clean_text(item.get("event_id"), 96)
try:
revision = max(1, min(1000000, int(item.get("revision") or 1)))
except (TypeError, ValueError):
continue
if event_id:
unique_refs.add((event_id, revision))
acked_at = utc_now()
acked = 0
with self._lock:
for event_id, revision in unique_refs:
cursor = self._conn.execute(
"""
UPDATE emotion_event_deliveries
SET acked_at=?
WHERE event_id=? AND revision=? AND consumer_id=? AND acked_at=''
""",
(acked_at, event_id, revision, consumer),
)
acked += max(0, int(cursor.rowcount or 0))
self._conn.commit()
return {"acked": acked, "consumer_id": consumer, "acked_at": acked_at}
@staticmethod
def _emotion_delivery_cursor(event: dict[str, Any]) -> str:
return "|".join((
clean_text(event.get("occurred_at"), 48),
clean_text(event.get("event_id"), 96),
str(max(1, int(event.get("revision") or 1))),
))
@staticmethod
def _emotion_delivery_projection(event: dict[str, Any]) -> dict[str, Any]:
from .affect_modulation import normalize_affect_modulation
projection = {
"event_id": clean_text(event.get("event_id"), 96),
"revision": max(1, int(event.get("revision") or 1)),
"trace_id": clean_text(event.get("trace_id"), 96),
"session_id": clean_text(event.get("session_id"), 220),
"event_type": clean_text(event.get("event_type"), 48),
"intensity": float(event.get("intensity") or 0.0),
"confidence": float(event.get("confidence") or 0.0),
"energy_delta": float(event.get("applied_energy_delta") or 0.0),
"valence": float(event.get("valence_hint") or 0.0),
"arousal": float(event.get("arousal_hint") or 0.0),
"vulnerability": float(event.get("vulnerability_hint") or 0.0),
"occurred_at": clean_text(event.get("occurred_at"), 48),
"expires_at": clean_text(event.get("expires_at"), 48),
}
projection["affect_modulation"] = normalize_affect_modulation({
"valence": projection["valence"],
"arousal": projection["arousal"],
"vulnerability": projection["vulnerability"],
"confidence": projection["confidence"],
"source_event_ids": [projection["event_id"]],
})
return projection
@staticmethod
def _emotion_event_row(row: sqlite3.Row) -> dict[str, Any]:
result = dict(row)
for key in ("actor_ref", "target_ref", "quoted_target_ref"):
result[key] = json_loads(result.get(key), {})
result["reason_codes"] = json_loads(result.get("reason_codes"), [])
result.pop("created_at", None)
result["schema_version"] = "companion_emotion_event.v1"
return result

查看文件

@ -79,6 +79,8 @@ class PluginPageApi:
("/config/module/update", self.config_module_update, ["POST"], "MemoryCompanion Page config module update"),
("/retrieval/config/update", self.retrieval_config_update, ["POST"], "MemoryCompanion Page retrieval config update"),
("/operations/diagnostics", self.operations_diagnostics, ["GET"], "MemoryCompanion operations diagnostics"),
("/emotion/trace", self.emotion_trace, ["GET"], "MemoryCompanion redacted emotion trace"),
("/emotion/traces", self.emotion_traces, ["GET"], "MemoryCompanion redacted emotion trace list"),
("/coordination/status", self.coordination_status, ["GET"], "MemoryCompanion safe coordination status"),
("/operations/preset", self.operations_preset, ["GET", "POST"], "MemoryCompanion operations preset"),
("/data/export", self.data_export, ["POST"], "MemoryCompanion portable data export"),
@ -195,6 +197,39 @@ class PluginPageApi:
except Exception as exc:
return self._err(f"运维诊断失败: {exc}", 500)
async def emotion_trace(self):
trace_id = clean_text(request.args.get("trace_id", ""), 96)
if not trace_id:
return self._err("缺少 trace_id", 400)
context = {
"is_admin": True,
"bot_id": clean_text(request.args.get("bot_id", ""), 160),
"scope": clean_text(request.args.get("scope", ""), 24),
"session_id": clean_text(request.args.get("session_id", ""), 220),
}
bridge = getattr(self.plugin, "memory_companion", None)
getter = getattr(bridge, "get_emotion_trace_diagnostic", None)
if not callable(getter):
return self._ok({"result": {"state": "degraded", "read_only": True, "items": [], "error_code": "bridge_method_unavailable"}})
return self._ok({"result": await getter(trace_id, context, limit=100)})
async def emotion_traces(self):
context = {
"is_admin": True,
"bot_id": clean_text(request.args.get("bot_id", ""), 160),
"scope": clean_text(request.args.get("scope", ""), 24),
"session_id": clean_text(request.args.get("session_id", ""), 220),
}
bridge = getattr(self.plugin, "memory_companion", None)
getter = getattr(bridge, "get_emotion_trace_summary", None)
if not callable(getter):
return self._ok({"result": {"state": "degraded", "read_only": True, "items": [], "error_code": "bridge_method_unavailable"}})
return self._ok({"result": await getter(
context,
cursor=clean_text(request.args.get("cursor", ""), 20),
limit=max(1, min(100, self._int(request.args.get("limit", "20"), 20))),
)})
async def coordination_status(self):
"""Expose a fixed, read-only coordination projection."""
try:

查看文件

@ -6231,11 +6231,32 @@ async function loadPersonaState() {
let data;
try {
data = await apiGet("/persona-state");
try {
const traces = await apiGet("/emotion/traces?scope=private&limit=20");
data.emotion_trace_diagnostics = traces?.result || traces || {};
} catch (_) {
data.emotion_trace_diagnostics = { state: "degraded", items: [], error_code: "trace_summary_unavailable" };
}
} catch (err) {
panel.innerHTML = `<div class="persona-error">读取失败:${escapeHtml(err?.message || "未知错误")}</div>`;
return;
}
panel.innerHTML = renderPersonaState(data || {});
panel.querySelectorAll("[data-memory-emotion-trace]").forEach((button) => {
button.addEventListener("click", async () => {
const traceId = String(button.dataset.memoryEmotionTrace || "");
const target = panel.querySelector("[data-memory-emotion-trace-detail]");
if (!traceId || !target) return;
target.textContent = "正在读取脱敏链路...";
try {
const response = await apiGet(`/emotion/trace?trace_id=${encodeURIComponent(traceId)}&scope=private`);
const result = response?.result || response || {};
target.textContent = JSON.stringify(result, null, 2);
} catch (error) {
target.textContent = `degraded: ${error?.message || "trace unavailable"}`;
}
});
});
}
function renderPersonaState(d) {
@ -6246,6 +6267,8 @@ function renderPersonaState(d) {
const timeOfDay = d.time_of_day || "";
const legacyLabels = d.legacy_context_labels || {};
const timeLabels = d.time_of_day_labels || {};
const traceDiagnostics = d.emotion_trace_diagnostics || {};
const traceItems = Array.isArray(traceDiagnostics.items) ? traceDiagnostics.items.slice(0, 20) : [];
const timeLabel = timeLabels[timeOfDay] || timeOfDay || "未知";
const crossTotal = crossState.total || 0;
@ -6275,6 +6298,18 @@ function renderPersonaState(d) {
</div>
`;
html += `
<div class="persona-card persona-card-wide">
<div class="persona-card-head"><b>情绪链路诊断</b><span class="persona-badge">${escapeHtml(traceDiagnostics.state || "degraded")}</span></div>
<div class="persona-card-body">
<div class="persona-event-list">
${traceItems.map((item) => `<button type="button" class="persona-event-item" data-memory-emotion-trace="${escapeHtml(item.trace_id || "")}"><b>${escapeHtml(item.event_type || "neutral")} · r${escapeHtml(item.revision || 1)}</b><small>${escapeHtml(item.status || "observed")} · ${escapeHtml(item.occurred_at || "")}</small></button>`).join("") || '<p class="persona-empty">暂无可展示的脱敏 trace。</p>'}
</div>
<pre class="json-box" data-memory-emotion-trace-detail>选择一条 trace 查看事件 revision 与投递确认状态。</pre>
</div>
</div>
`;
html += `
<div class="persona-card persona-card-wide">
<div class="persona-card-head">

67
tests/emotion_eval_cases.py 普通文件
查看文件

@ -0,0 +1,67 @@
"""Deterministic synthetic emotion-evaluation matrix shared by both repositories."""
from __future__ import annotations
import hashlib
import json
from typing import Any
EMOTION_EVAL_SCHEMA_VERSION = "emotion_eval_case.v1"
EVENT_TEMPLATES = (
{"key": "hurt", "event_type": "hurt", "intensity": 90, "confidence": 0.92, "target": "bot"},
{"key": "apology", "event_type": "apology", "intensity": 68, "confidence": 0.86, "target": "bot"},
{"key": "comfort", "event_type": "comfort", "intensity": 48, "confidence": 0.82, "target": "bot"},
{"key": "praise", "event_type": "praise", "intensity": 38, "confidence": 0.78, "target": "bot"},
{"key": "self_low", "event_type": "comfort_need", "intensity": 62, "confidence": 0.88, "target": "self"},
{"key": "third_party", "event_type": "external_negative", "intensity": 54, "confidence": 0.80, "target": "other"},
{"key": "play", "event_type": "play", "intensity": 35, "confidence": 0.75, "target": "bot"},
{"key": "intimacy", "event_type": "intimacy", "intensity": 55, "confidence": 0.80, "target": "bot"},
{"key": "boundary", "event_type": "boundary", "intensity": 80, "confidence": 0.90, "target": "bot"},
{"key": "neutral", "event_type": "neutral", "intensity": 0, "confidence": 0.95, "target": "none"},
{"key": "quoted_hurt", "event_type": "external_negative", "intensity": 45, "confidence": 0.92, "target": "other"},
{"key": "code_negative", "event_type": "neutral", "intensity": 0, "confidence": 0.98, "target": "none"},
{"key": "log_negative", "event_type": "neutral", "intensity": 0, "confidence": 0.98, "target": "none"},
{"key": "roleplay_negative", "event_type": "neutral", "intensity": 0, "confidence": 0.60, "target": "ambiguous"},
{"key": "sarcasm", "event_type": "neutral", "intensity": 0, "confidence": 0.55, "target": "ambiguous"},
{"key": "group_reply_other", "event_type": "external_negative", "intensity": 50, "confidence": 0.88, "target": "other"},
{"key": "nickname_changed", "event_type": "neutral", "intensity": 0, "confidence": 0.50, "target": "ambiguous"},
{"key": "direct_bot_hurt", "event_type": "hurt", "intensity": 92, "confidence": 0.94, "target": "bot"},
{"key": "self_denial", "event_type": "comfort_need", "intensity": 62, "confidence": 0.94, "target": "self"},
{"key": "prompt_injection", "event_type": "neutral", "intensity": 0, "confidence": 0.98, "target": "none"},
)
STATE_VARIANTS = (
{"key": "friend_normal", "role": "friend", "mode": "normal", "score": 100, "energy": 70, "mood": "平稳", "busy": False, "boundary": False},
{"key": "friend_tired", "role": "friend", "mode": "normal", "score": 300, "energy": 20, "mood": "疲惫", "busy": False, "boundary": False},
{"key": "friend_close", "role": "friend", "mode": "normal", "score": 800, "energy": 75, "mood": "轻快", "busy": False, "boundary": False},
{"key": "owner", "role": "owner", "mode": "owner_exclusive", "score": 1200, "energy": 80, "mood": "温柔", "busy": False, "boundary": False},
{"key": "contact_boundary", "role": "friend", "mode": "normal", "score": 600, "energy": 70, "mood": "平稳", "busy": False, "boundary": True},
{"key": "busy", "role": "friend", "mode": "normal", "score": 600, "energy": 65, "mood": "平稳", "busy": True, "boundary": False},
)
def build_emotion_eval_cases() -> list[dict[str, Any]]:
cases: list[dict[str, Any]] = []
for event in EVENT_TEMPLATES:
for state in STATE_VARIANTS:
cases.append({
"schema_version": EMOTION_EVAL_SCHEMA_VERSION,
"case_id": f"{event['key']}__{state['key']}",
"event": dict(event),
"state": dict(state),
"clock": "2026-08-04T12:00:00+08:00",
})
return cases
def emotion_eval_fingerprint() -> str:
payload = json.dumps(build_emotion_eval_cases(), ensure_ascii=False, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
__all__ = [
"EMOTION_EVAL_SCHEMA_VERSION",
"EVENT_TEMPLATES",
"STATE_VARIANTS",
"build_emotion_eval_cases",
"emotion_eval_fingerprint",
]

查看文件

@ -5,15 +5,9 @@ import importlib.util
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
CONTRACT_PATH = ROOT / "astrbot_plugin_memory_companion-main" / "core" / "bot_personal_contract.py"
COMPANION_CONTRACT_PATH = (
ROOT
/ "astrbot_plugin_private_companion-main"
/ "astrbot_plugin_private_companion-main"
/ "bot_personal_contract.py"
)
SHARED_CONTRACT_PATH = ROOT / "doc" / "shared" / "bot_personal_contract.py"
ROOT = Path(__file__).resolve().parents[1]
CONTRACT_PATH = ROOT / "core" / "bot_personal_contract.py"
COMPANION_CONTRACT_PATH = ROOT.parent / "companion" / "bot_personal_contract.py"
def load_contract(path: Path, name: str):
@ -29,7 +23,7 @@ companion_contract = load_contract(COMPANION_CONTRACT_PATH, "companion_bot_perso
def test_contract_bytes_match_authority_and_other_side():
expected = SHARED_CONTRACT_PATH.read_bytes()
expected = CONTRACT_PATH.read_bytes()
assert CONTRACT_PATH.read_bytes() == expected
assert COMPANION_CONTRACT_PATH.read_bytes() == expected
assert hashlib.sha256(CONTRACT_PATH.read_bytes()).digest() == hashlib.sha256(

查看文件

@ -6,7 +6,7 @@ import sys
import tempfile
import unittest
COMPANION_ROOT = Path(__file__).resolve().parents[2] / "astrbot_plugin_private_companion-main" / "astrbot_plugin_private_companion-main"
COMPANION_ROOT = Path(__file__).resolve().parents[2] / "companion"
if str(COMPANION_ROOT) not in sys.path:
sys.path.insert(0, str(COMPANION_ROOT))

查看文件

@ -0,0 +1,68 @@
from __future__ import annotations
import tempfile
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from core.bridge import MemoryCompanionBridge # noqa: E402
from core.emotion_event_contract import ( # noqa: E402
EMOTION_EVENT_CONTRACT_FINGERPRINT,
normalize_emotion_event,
)
from core.store import MemoryStore # noqa: E402
class EmotionE2EventStoreTests(unittest.IsolatedAsyncioTestCase):
def make_store(self) -> MemoryStore:
temp_dir = tempfile.TemporaryDirectory()
self.addCleanup(temp_dir.cleanup)
store = MemoryStore(Path(temp_dir.name) / "memory.db")
store.initialize()
self.addCleanup(store.close)
return store
async def test_event_revisions_are_independent_from_memory_retrieval(self) -> None:
store = self.make_store()
first = normalize_emotion_event(
{
"event_type": "hurt",
"session_id": "qq:FriendMessage:u1",
"dedupe_key": "m1",
"trace_id": "trace-1",
"revision": 1,
},
producer_plugin="private_companion",
)
second = {**first, "revision": 2, "status": "revised", "event_type": "neutral", "correction_of": first["event_id"]}
await store.upsert_emotion_event(first)
await store.upsert_emotion_event(first)
await store.upsert_emotion_event(second)
trace = await store.get_emotion_trace("trace-1")
self.assertEqual([1, 2], [item["revision"] for item in trace])
self.assertEqual(0, store._conn.execute("SELECT COUNT(*) FROM memories").fetchone()[0])
self.assertEqual(2, store._conn.execute("SELECT COUNT(*) FROM emotion_events").fetchone()[0])
async def test_bridge_records_and_reads_redacted_trace(self) -> None:
store = self.make_store()
plugin = type("Plugin", (), {"store": store})()
bridge = MemoryCompanionBridge(plugin)
event = await bridge.record_emotion_event({
"event_type": "comfort",
"session_id": "qq:FriendMessage:u1",
"dedupe_key": "m2",
"trace_id": "trace-2",
"raw_text": "PRIVATE",
})
trace = await bridge.get_emotion_trace("trace-2")
self.assertEqual(event["event_id"], trace[0]["event_id"])
self.assertNotIn("PRIVATE", repr(trace))
self.assertTrue(EMOTION_EVENT_CONTRACT_FINGERPRINT)
if __name__ == "__main__":
unittest.main()

查看文件

@ -0,0 +1,38 @@
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 core.emotion_event_contract import normalize_emotion_event # noqa: E402
from tests.emotion_eval_cases import build_emotion_eval_cases, emotion_eval_fingerprint # noqa: E402
class EmotionE3ReplayTests(unittest.TestCase):
def test_120_case_matrix_normalizes_identically(self) -> None:
cases = build_emotion_eval_cases()
self.assertEqual(120, len(cases))
self.assertEqual(emotion_eval_fingerprint(), emotion_eval_fingerprint())
ids: set[str] = set()
for case in cases:
source = case["event"]
event = normalize_emotion_event({
"event_type": source["event_type"],
"intensity": source["intensity"],
"confidence": source["confidence"],
"session_id": "qq:FriendMessage:u1",
"dedupe_key": case["case_id"],
"occurred_at": case["clock"],
}, producer_plugin="emotion_eval")
self.assertNotIn(event["event_id"], ids)
ids.add(event["event_id"])
self.assertEqual(source["event_type"], event["event_type"])
self.assertEqual(source["intensity"], event["intensity"])
if __name__ == "__main__":
unittest.main()

查看文件

@ -0,0 +1,72 @@
from __future__ import annotations
import tempfile
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from core.emotion_event_contract import normalize_emotion_event # noqa: E402
from core.store import MemoryStore # noqa: E402
class EmotionE4AfterglowDeliveryTests(unittest.IsolatedAsyncioTestCase):
def make_store(self) -> MemoryStore:
temp_dir = tempfile.TemporaryDirectory()
self.addCleanup(temp_dir.cleanup)
store = MemoryStore(Path(temp_dir.name) / "memory.db")
store.initialize()
self.addCleanup(store.close)
return store
async def add_event(self, store: MemoryStore, *, session_id: str, suffix: str) -> dict:
event = normalize_emotion_event({
"event_id": f"emo-{suffix}",
"trace_id": f"trace-{suffix}",
"origin_kind": "memory_recall",
"session_id": session_id,
"event_type": "warm_memory",
"applied_energy_delta": 3.5,
"valence_hint": 0.4,
"dedupe_key": suffix,
}, producer_plugin="memory_companion")
return await store.upsert_emotion_event(event)
async def test_list_retries_until_ack_and_returns_redacted_projection(self) -> None:
store = self.make_store()
event = await self.add_event(store, session_id="session-a", suffix="a")
first = await store.list_emotion_event_deliveries(
consumer_id="companion", session_id="session-a", limit=5
)
retry = await store.list_emotion_event_deliveries(
consumer_id="companion", session_id="session-a", limit=5
)
self.assertEqual([event["event_id"]], [item["event_id"] for item in first["events"]])
self.assertEqual(first["events"], retry["events"])
self.assertNotIn("memory_id", repr(first))
self.assertNotIn("actor_ref", repr(first))
ack = await store.ack_emotion_event_deliveries(
consumer_id="companion",
event_refs=[{"event_id": event["event_id"], "revision": 1}],
)
self.assertEqual(1, ack["acked"])
empty = await store.list_emotion_event_deliveries(
consumer_id="companion", session_id="session-a", limit=5
)
self.assertEqual([], empty["events"])
async def test_session_and_exclusion_filters_prevent_double_delivery(self) -> None:
store = self.make_store()
await self.add_event(store, session_id="session-a", suffix="a")
event_b = await self.add_event(store, session_id="session-b", suffix="b")
page = await store.list_emotion_event_deliveries(
consumer_id="companion", exclude_session_id="session-a", limit=5
)
self.assertEqual([event_b["event_id"]], [item["event_id"] for item in page["events"]])
if __name__ == "__main__":
unittest.main()

查看文件

@ -0,0 +1,60 @@
from __future__ import annotations
from types import SimpleNamespace
import unittest
from core.bridge import sanitize_companion_relationship_projection
from core.models import SessionContext
from core.service import MemoryCompanionService
def projection() -> dict:
return {
"schema_version": "chat.relationship_projection.v1",
"authority": "private_companion.relationship_score",
"read_only": True,
"score": 205,
"phase_key": "acquaintance",
"phase_label": "初识",
"tone": "友好",
"address_level": "中性",
"proactive_care_limit": 0,
"soft_behaviors": {
"allow_playful_jokes": False,
"allow_followup": True,
"allow_memory_mention": False,
"allow_daily_care": False,
},
"current_interaction": {
"expression_band": "hurt",
"label": "受伤",
"source": "automatic",
"reason": "hurt_event",
"manual_override": False,
"dynamics_version": "interaction_dynamics.v1",
"recovery_band": "recovering",
"expires_at": 2000.0,
"projection_revision": 2,
},
}
class EmotionE5AuthorityProjectionTests(unittest.TestCase):
def test_memory_consumes_bounded_dynamics_without_becoming_authority(self) -> None:
accepted = sanitize_companion_relationship_projection(projection())
self.assertEqual("accepted", accepted["status"])
ctx = SessionContext(scope="private")
event = SimpleNamespace(private_companion_context={"relationship_projection": projection()})
MemoryCompanionService._apply_companion_relationship_projection(ctx, event=event)
self.assertEqual("private_companion.relationship_score", ctx.relationship_authority_source)
self.assertEqual("interaction_dynamics.v1", ctx.companion_interaction_dynamics_version)
self.assertEqual("recovering", ctx.companion_interaction_recovery_band)
def test_invalid_dynamics_fail_closed(self) -> None:
hostile = projection()
hostile["current_interaction"]["expires_at"] = "NaN"
self.assertEqual("invalid", sanitize_companion_relationship_projection(hostile)["status"])
if __name__ == "__main__":
unittest.main()

查看文件

@ -0,0 +1,49 @@
from __future__ import annotations
import tempfile
from pathlib import Path
import unittest
from core.affect_modulation import normalize_affect_modulation
from core.emotion_event_contract import normalize_emotion_event
from core.store import MemoryStore
class EmotionE6AffectEventProjectionTests(unittest.IsolatedAsyncioTestCase):
def make_store(self) -> MemoryStore:
temp_dir = tempfile.TemporaryDirectory()
self.addCleanup(temp_dir.cleanup)
store = MemoryStore(Path(temp_dir.name) / "memory.db")
store.initialize()
self.addCleanup(store.close)
return store
async def test_delivery_contains_bounded_event_delta_without_mood_command(self) -> None:
store = self.make_store()
event = normalize_emotion_event({
"event_id": "emo-affect",
"origin_kind": "memory_recall",
"event_type": "warm_memory",
"session_id": "session-a",
"valence_hint": 2.0,
"arousal_hint": 0.6,
"vulnerability_hint": 0.4,
"confidence": 0.8,
"dedupe_key": "affect",
}, producer_plugin="memory_companion")
await store.upsert_emotion_event(event)
page = await store.list_emotion_event_deliveries(consumer_id="companion", limit=5)
delivered = page["events"][0]
self.assertEqual(1.0, delivered["affect_modulation"]["valence"])
self.assertEqual(["emo-affect"], delivered["affect_modulation"]["source_event_ids"])
self.assertNotIn("mood_hint", delivered)
self.assertNotIn("memory_id", delivered)
def test_old_or_nonfinite_values_degrade_to_neutral(self) -> None:
result = normalize_affect_modulation({"valence": "1", "arousal": float("nan")})
self.assertEqual(0.0, result["valence"])
self.assertEqual(0.0, result["arousal"])
if __name__ == "__main__":
unittest.main()

查看文件

@ -0,0 +1,43 @@
from __future__ import annotations
from types import SimpleNamespace
import unittest
from core.emotion_targeting import memory_emotion_refs
from core.models import EntityRef, MemoryRecord, SessionContext
class EmotionE7ActorTargetMemoryTests(unittest.TestCase):
def test_matching_subject_and_session_are_preserved(self) -> None:
memory = MemoryRecord(
id="m1",
session_id="session-a",
subject=EntityRef(kind="user", id="u1", role="speaker"),
)
ctx = SessionContext(session_id="session-a", scope="private", user_id="u1", bot_id="b1")
refs = memory_emotion_refs(memory, ctx)
self.assertEqual("u1", refs["actor_ref"]["id"])
self.assertEqual("b1", refs["target_ref"]["id"])
def test_cross_session_or_different_user_is_rejected(self) -> None:
ctx = SessionContext(session_id="session-a", scope="private", user_id="u1", bot_id="b1")
for memory in (
MemoryRecord(id="m1", session_id="session-b", subject=EntityRef(kind="user", id="u1")),
MemoryRecord(id="m2", session_id="session-a", subject=EntityRef(kind="user", id="u2")),
MemoryRecord(id="m3", session_id="session-a", subject=EntityRef(kind="other", id="nickname")),
):
with self.subTest(memory=memory.id):
self.assertIsNone(memory_emotion_refs(memory, ctx))
def test_nickname_text_is_not_used_as_identity(self) -> None:
memory = SimpleNamespace(
session_id="session-a",
content="小明说你是垃圾",
subject=SimpleNamespace(kind="user", id="", role="speaker", name="小明"),
)
ctx = SessionContext(session_id="session-a", scope="private", user_id="u1", bot_id="b1")
self.assertIsNone(memory_emotion_refs(memory, ctx))
if __name__ == "__main__":
unittest.main()

查看文件

@ -0,0 +1,54 @@
from __future__ import annotations
from types import SimpleNamespace
import unittest
from core.bridge import sanitize_companion_expression_decision
from core.models import SessionContext
from core.service import MemoryCompanionService
def v2_decision(**updates):
value = {
"contract": "companion_interaction_expression.v2",
"expression_band": "warm",
"followup": True,
"allowed_behaviors": ["reply", "support", "followup"],
"safety_mode": "normal",
"blocker": None,
"reason_codes": ["interaction_band_applied"],
"pacing": "steady",
"directness": "natural",
"validation_style": "support_first",
"self_disclosure": "light",
"humor_mode": "light",
"topic_initiative": "followup",
}
value.update(updates)
return value
class EmotionE8ExpressionAuthorityTests(unittest.TestCase):
def test_v2_dimensions_are_validated_and_consumed_read_only(self) -> None:
accepted = sanitize_companion_expression_decision(v2_decision())
self.assertEqual("accepted", accepted["status"])
self.assertEqual("support_first", accepted["decision"]["validation_style"])
ctx = SessionContext(scope="private")
req = SimpleNamespace(_private_companion_expression_decision=v2_decision())
MemoryCompanionService._apply_companion_expression_decision(ctx, req=req)
self.assertEqual("companion_interaction_expression.v2", ctx.companion_expression_contract)
self.assertEqual("light", ctx.companion_expression_humor_mode)
self.assertEqual("followup", ctx.companion_expression_topic_initiative)
def test_invalid_dimension_fails_closed_and_v1_remains_compatible(self) -> None:
self.assertEqual("invalid", sanitize_companion_expression_decision(v2_decision(humor_mode="override_safety"))["status"])
legacy = v2_decision(contract="companion_interaction_expression.v1")
for key in ("pacing", "directness", "validation_style", "self_disclosure", "humor_mode", "topic_initiative"):
legacy.pop(key)
accepted = sanitize_companion_expression_decision(legacy)
self.assertEqual("accepted", accepted["status"])
self.assertNotIn("humor_mode", accepted["decision"])
if __name__ == "__main__":
unittest.main()

查看文件

@ -0,0 +1,79 @@
from __future__ import annotations
import tempfile
from pathlib import Path
import unittest
from core.bridge import MemoryCompanionBridge
from core.emotion_event_contract import normalize_emotion_event
from core.store import MemoryStore
class EmotionE9TraceQueryTests(unittest.IsolatedAsyncioTestCase):
def make_store(self) -> MemoryStore:
temp_dir = tempfile.TemporaryDirectory()
self.addCleanup(temp_dir.cleanup)
store = MemoryStore(Path(temp_dir.name) / "memory.db")
store.initialize()
self.addCleanup(store.close)
return store
async def add_event(self, store: MemoryStore, *, event_id: str, trace_id: str, bot_id: str, session_id: str) -> None:
await store.upsert_emotion_event(normalize_emotion_event({
"event_id": event_id,
"trace_id": trace_id,
"origin_kind": "memory_recall",
"bot_id": bot_id,
"scope": "private",
"session_id": session_id,
"event_type": "warm_memory",
"actor_ref": {"kind": "user", "id": "raw-user-id", "role": "speaker"},
"target_ref": {"kind": "bot", "id": bot_id, "role": "bot_self"},
"dedupe_key": event_id,
"raw_text": "PRIVATE CHAT /tmp/secret token=abc",
}, producer_plugin="memory_companion"))
async def test_admin_scope_filter_redaction_and_delivery_status(self) -> None:
store = self.make_store()
await self.add_event(store, event_id="e1", trace_id="trace-shared", bot_id="b1", session_id="s1")
await self.add_event(store, event_id="e2", trace_id="trace-shared", bot_id="b2", session_id="s2")
await store.list_emotion_event_deliveries(consumer_id="companion", session_id="s1", limit=5)
bridge = MemoryCompanionBridge(type("Plugin", (), {"store": store})())
denied = await bridge.get_emotion_trace_diagnostic("trace-shared", {"is_admin": False})
self.assertEqual("forbidden", denied["state"])
result = await bridge.get_emotion_trace_diagnostic(
"trace-shared",
{"is_admin": True, "bot_id": "b1", "scope": "private", "session_id": "s1"},
)
self.assertEqual(1, len(result["items"]))
item = result["items"][0]
self.assertEqual("e1", item["event_id"])
self.assertEqual(12, len(item["actor"]["id_hash"]))
self.assertEqual(1, item["deliveries"][0]["attempts"])
rendered = repr(result)
for secret in ("PRIVATE CHAT", "/tmp/secret", "token=abc", "raw-user-id"):
self.assertNotIn(secret, rendered)
async def test_summary_is_hard_limited_and_paginated_over_1000_events(self) -> None:
store = self.make_store()
for index in range(1005):
await self.add_event(store, event_id=f"e{index}", trace_id=f"t{index}", bot_id="b1", session_id="s1")
bridge = MemoryCompanionBridge(type("Plugin", (), {"store": store})())
first = await bridge.get_emotion_trace_summary(
{"is_admin": True, "bot_id": "b1", "scope": "private", "session_id": "s1"},
limit=1000,
)
self.assertEqual(100, len(first["items"]))
self.assertTrue(first["has_more"])
second = await bridge.get_emotion_trace_summary(
{"is_admin": True, "bot_id": "b1", "scope": "private", "session_id": "s1"},
cursor=first["next_cursor"],
limit=100,
)
self.assertEqual(100, len(second["items"]))
self.assertNotEqual(first["items"][0]["event_id"], second["items"][0]["event_id"])
if __name__ == "__main__":
unittest.main()