feat(emotion-e2): add auditable interaction event ledger
这个提交存在于:
父节点
80ab1764f1
当前提交
b678fe9928
共有 7 个文件被更改,包括 399 次插入 和 0 次删除
|
|
@ -616,6 +616,8 @@ 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),
|
||||
}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -395,6 +395,8 @@ _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,
|
||||
|
|
|
|||
162
emotion_event_contract.py
普通文件
162
emotion_event_contract.py
普通文件
|
|
@ -0,0 +1,162 @@
|
|||
"""Versioned, redacted emotion-event contract shared with MemoryCompanion."""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
from typing import Any, Mapping
|
||||
|
||||
|
||||
EMOTION_EVENT_SCHEMA_VERSION = "companion_emotion_event.v1"
|
||||
EMOTION_EVENT_TYPES = frozenset({
|
||||
"neutral", "hurt", "apology", "comfort", "praise", "comfort_need",
|
||||
"external_negative", "scar_touched", "warm_memory", "vulnerable_resonance",
|
||||
"play", "intimacy", "boundary",
|
||||
})
|
||||
EMOTION_EVENT_ORIGINS = frozenset({"interaction", "memory_recall", "system_condition"})
|
||||
EMOTION_EVENT_STATUSES = frozenset({"observed", "revised", "applied", "ignored", "expired"})
|
||||
EMOTION_EVENT_CONTRACT_FIELDS = (
|
||||
"schema_version", "event_id", "trace_id", "revision", "producer_plugin",
|
||||
"origin_kind", "platform", "bot_id", "scope", "session_id", "actor_ref",
|
||||
"target_ref", "quoted_target_ref", "event_type", "intensity", "confidence",
|
||||
"valence_hint", "arousal_hint", "vulnerability_hint", "source_rule",
|
||||
"occurred_at", "expires_at", "dedupe_key", "payload_hash", "privacy_level",
|
||||
"applied_interaction", "applied_energy_delta", "correction_of", "status",
|
||||
"reason_codes",
|
||||
)
|
||||
EMOTION_EVENT_CONTRACT_FINGERPRINT = hashlib.sha256(
|
||||
"|".join(EMOTION_EVENT_CONTRACT_FIELDS).encode("ascii")
|
||||
).hexdigest()[:20]
|
||||
|
||||
|
||||
def _text(value: Any, limit: int) -> str:
|
||||
text = re.sub(r"\s+", " ", str(value or "").replace("\u3000", " ")).strip()
|
||||
return text[:limit]
|
||||
|
||||
|
||||
def _number(value: Any, default: float, low: float, high: float) -> float:
|
||||
if isinstance(value, bool):
|
||||
return default
|
||||
try:
|
||||
number = float(value)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
if not math.isfinite(number):
|
||||
return default
|
||||
return round(max(low, min(high, number)), 4)
|
||||
|
||||
|
||||
def _integer(value: Any, default: int = 1) -> int:
|
||||
if isinstance(value, bool):
|
||||
return default
|
||||
try:
|
||||
return max(1, min(1_000_000, int(value)))
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def _entity(value: Any) -> dict[str, str]:
|
||||
source = value if isinstance(value, Mapping) else {}
|
||||
return {
|
||||
"kind": _text(source.get("kind"), 24) or "unknown",
|
||||
"id": _text(source.get("id"), 160),
|
||||
"role": _text(source.get("role"), 40),
|
||||
}
|
||||
|
||||
|
||||
def _timestamp(value: Any) -> str:
|
||||
text = _text(value, 48)
|
||||
if text:
|
||||
return text
|
||||
return datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
|
||||
|
||||
def _stable_hash(*parts: Any) -> str:
|
||||
raw = "|".join(_text(part, 500) for part in parts)
|
||||
return hashlib.sha256(raw.encode("utf-8", errors="ignore")).hexdigest()
|
||||
|
||||
|
||||
def normalize_emotion_event(value: Any, *, producer_plugin: str = "") -> dict[str, Any]:
|
||||
"""Return a bounded JSON-safe event without retaining raw message content."""
|
||||
source = dict(value) if isinstance(value, Mapping) else {}
|
||||
producer = _text(source.get("producer_plugin") or producer_plugin, 80) or "unknown"
|
||||
origin = _text(source.get("origin_kind"), 40)
|
||||
if origin not in EMOTION_EVENT_ORIGINS:
|
||||
origin = "interaction"
|
||||
event_type = _text(source.get("event_type"), 48).lower()
|
||||
if event_type not in EMOTION_EVENT_TYPES:
|
||||
event_type = "neutral"
|
||||
status = _text(source.get("status"), 24).lower()
|
||||
if status not in EMOTION_EVENT_STATUSES:
|
||||
status = "observed"
|
||||
session_id = _text(source.get("session_id"), 220)
|
||||
dedupe_key = _text(source.get("dedupe_key"), 160)
|
||||
payload_hash = _text(source.get("payload_hash"), 80)
|
||||
if not payload_hash:
|
||||
payload_hash = _stable_hash(
|
||||
producer, origin, session_id, event_type, dedupe_key,
|
||||
source.get("message_fingerprint"), source.get("source_rule"),
|
||||
)
|
||||
event_id = _text(source.get("event_id"), 96)
|
||||
if not event_id:
|
||||
event_id = "emo_" + _stable_hash(producer, origin, session_id, event_type, dedupe_key, payload_hash)[:24]
|
||||
trace_id = _text(source.get("trace_id"), 96)
|
||||
if not trace_id:
|
||||
trace_id = "etr_" + _stable_hash(session_id, dedupe_key or event_id)[:24]
|
||||
reason_codes = source.get("reason_codes")
|
||||
if not isinstance(reason_codes, (list, tuple)):
|
||||
reason_codes = []
|
||||
clean_reasons: list[str] = []
|
||||
for item in reason_codes[:12]:
|
||||
reason = _text(item, 64)
|
||||
if reason and reason not in clean_reasons:
|
||||
clean_reasons.append(reason)
|
||||
return {
|
||||
"schema_version": EMOTION_EVENT_SCHEMA_VERSION,
|
||||
"event_id": event_id,
|
||||
"trace_id": trace_id,
|
||||
"revision": _integer(source.get("revision"), 1),
|
||||
"producer_plugin": producer,
|
||||
"origin_kind": origin,
|
||||
"platform": _text(source.get("platform"), 80),
|
||||
"bot_id": _text(source.get("bot_id"), 160),
|
||||
"scope": _text(source.get("scope"), 24) or "private",
|
||||
"session_id": session_id,
|
||||
"actor_ref": _entity(source.get("actor_ref")),
|
||||
"target_ref": _entity(source.get("target_ref")),
|
||||
"quoted_target_ref": _entity(source.get("quoted_target_ref")),
|
||||
"event_type": event_type,
|
||||
"intensity": _number(source.get("intensity"), 0.0, 0.0, 100.0),
|
||||
"confidence": _number(source.get("confidence"), 0.0, 0.0, 1.0),
|
||||
"valence_hint": _number(source.get("valence_hint"), 0.0, -1.0, 1.0),
|
||||
"arousal_hint": _number(source.get("arousal_hint"), 0.0, 0.0, 1.0),
|
||||
"vulnerability_hint": _number(source.get("vulnerability_hint"), 0.0, 0.0, 1.0),
|
||||
"source_rule": _text(source.get("source_rule"), 80),
|
||||
"occurred_at": _timestamp(source.get("occurred_at")),
|
||||
"expires_at": _text(source.get("expires_at"), 48),
|
||||
"dedupe_key": dedupe_key or payload_hash[:32],
|
||||
"payload_hash": payload_hash,
|
||||
"privacy_level": _text(source.get("privacy_level"), 24) or "redacted",
|
||||
"applied_interaction": _text(source.get("applied_interaction"), 32),
|
||||
"applied_energy_delta": _number(source.get("applied_energy_delta"), 0.0, -100.0, 100.0),
|
||||
"correction_of": _text(source.get("correction_of"), 96),
|
||||
"status": status,
|
||||
"reason_codes": clean_reasons,
|
||||
}
|
||||
|
||||
|
||||
def emotion_event_json(value: Any, *, producer_plugin: str = "") -> str:
|
||||
return json.dumps(normalize_emotion_event(value, producer_plugin=producer_plugin), ensure_ascii=False, separators=(",", ":"))
|
||||
|
||||
|
||||
__all__ = [
|
||||
"EMOTION_EVENT_CONTRACT_FIELDS",
|
||||
"EMOTION_EVENT_CONTRACT_FINGERPRINT",
|
||||
"EMOTION_EVENT_SCHEMA_VERSION",
|
||||
"EMOTION_EVENT_STATUSES",
|
||||
"EMOTION_EVENT_TYPES",
|
||||
"emotion_event_json",
|
||||
"normalize_emotion_event",
|
||||
]
|
||||
62
emotion_event_ledger.py
普通文件
62
emotion_event_ledger.py
普通文件
|
|
@ -0,0 +1,62 @@
|
|||
"""Bounded recent emotion-event ledger owned by Companion user profiles."""
|
||||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
from typing import Any
|
||||
|
||||
try:
|
||||
from .emotion_event_contract import normalize_emotion_event
|
||||
except ImportError: # direct-module tests
|
||||
from emotion_event_contract import normalize_emotion_event # type: ignore
|
||||
|
||||
|
||||
DEFAULT_RECENT_EVENT_LIMIT = 64
|
||||
|
||||
|
||||
def record_recent_emotion_event(
|
||||
user: dict[str, Any],
|
||||
value: Any,
|
||||
*,
|
||||
limit: int = DEFAULT_RECENT_EVENT_LIMIT,
|
||||
) -> tuple[dict[str, Any], bool]:
|
||||
event = normalize_emotion_event(value, producer_plugin="private_companion")
|
||||
ledger = user.get("emotion_event_ledger")
|
||||
if not isinstance(ledger, list):
|
||||
ledger = []
|
||||
kept: list[dict[str, Any]] = []
|
||||
duplicate = False
|
||||
for item in ledger:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
if item.get("event_id") == event["event_id"] and int(item.get("revision") or 0) == event["revision"]:
|
||||
duplicate = True
|
||||
kept.append(item)
|
||||
else:
|
||||
kept.append(item)
|
||||
if not duplicate:
|
||||
kept.append(event)
|
||||
kept.sort(key=lambda item: (str(item.get("occurred_at") or ""), int(item.get("revision") or 0)))
|
||||
user["emotion_event_ledger"] = kept[-max(8, min(256, int(limit or DEFAULT_RECENT_EVENT_LIMIT))):]
|
||||
user["last_emotion_event"] = {
|
||||
"event_id": event["event_id"],
|
||||
"trace_id": event["trace_id"],
|
||||
"revision": event["revision"],
|
||||
"event_type": event["event_type"],
|
||||
"status": event["status"],
|
||||
"occurred_at": event["occurred_at"],
|
||||
}
|
||||
return deepcopy(event), not duplicate
|
||||
|
||||
|
||||
def emotion_trace_from_user(user: Any, trace_id: str, *, limit: int = 20) -> list[dict[str, Any]]:
|
||||
if not isinstance(user, dict) or not isinstance(trace_id, str) or not trace_id:
|
||||
return []
|
||||
ledger = user.get("emotion_event_ledger")
|
||||
if not isinstance(ledger, list):
|
||||
return []
|
||||
result = [deepcopy(item) for item in ledger if isinstance(item, dict) and item.get("trace_id") == trace_id]
|
||||
result.sort(key=lambda item: int(item.get("revision") or 0))
|
||||
return result[-max(1, min(100, int(limit or 20))):]
|
||||
|
||||
|
||||
__all__ = ["DEFAULT_RECENT_EVENT_LIMIT", "emotion_trace_from_user", "record_recent_emotion_event"]
|
||||
|
|
@ -93,6 +93,18 @@ 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,
|
||||
|
|
|
|||
|
|
@ -0,0 +1,60 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from emotion_event_contract import ( # noqa: E402
|
||||
EMOTION_EVENT_CONTRACT_FINGERPRINT,
|
||||
EMOTION_EVENT_SCHEMA_VERSION,
|
||||
normalize_emotion_event,
|
||||
)
|
||||
from emotion_event_ledger import emotion_trace_from_user, record_recent_emotion_event # noqa: E402
|
||||
|
||||
|
||||
class EmotionE2ContractTests(unittest.TestCase):
|
||||
def test_contract_is_bounded_redacted_and_finite(self) -> None:
|
||||
event = normalize_emotion_event(
|
||||
{
|
||||
"event_type": "hurt",
|
||||
"session_id": "qq:FriendMessage:u1",
|
||||
"intensity": math.inf,
|
||||
"confidence": 9,
|
||||
"raw_text": "PRIVATE_DO_NOT_KEEP",
|
||||
"actor_ref": {"kind": "user", "id": "u1", "name": "private"},
|
||||
"reason_codes": ["hurt", "hurt", "x" * 200],
|
||||
},
|
||||
producer_plugin="private_companion",
|
||||
)
|
||||
self.assertEqual(EMOTION_EVENT_SCHEMA_VERSION, event["schema_version"])
|
||||
self.assertEqual(0.0, event["intensity"])
|
||||
self.assertEqual(1.0, event["confidence"])
|
||||
self.assertNotIn("raw_text", event)
|
||||
self.assertNotIn("name", event["actor_ref"])
|
||||
self.assertNotIn("PRIVATE_DO_NOT_KEEP", repr(event))
|
||||
self.assertTrue(EMOTION_EVENT_CONTRACT_FINGERPRINT)
|
||||
|
||||
def test_recent_ledger_is_idempotent_and_traceable(self) -> None:
|
||||
user: dict = {}
|
||||
payload = {
|
||||
"event_type": "praise",
|
||||
"session_id": "qq:FriendMessage:u1",
|
||||
"dedupe_key": "message-1",
|
||||
"status": "applied",
|
||||
}
|
||||
first, created = record_recent_emotion_event(user, payload)
|
||||
replay, replay_created = record_recent_emotion_event(user, payload)
|
||||
self.assertTrue(created)
|
||||
self.assertFalse(replay_created)
|
||||
self.assertEqual(first["event_id"], replay["event_id"])
|
||||
self.assertEqual(1, len(user["emotion_event_ledger"]))
|
||||
self.assertEqual([first], emotion_trace_from_user(user, first["trace_id"]))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
@ -110,6 +110,7 @@ from .companion_interaction_expression import (
|
|||
current_interaction_projection,
|
||||
expression_decision_prompt,
|
||||
)
|
||||
from .emotion_event_ledger import record_recent_emotion_event
|
||||
from .planning import (
|
||||
build_daily_plan_prompt,
|
||||
build_detail_enhancement_prompt,
|
||||
|
|
@ -4572,6 +4573,75 @@ 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()
|
||||
event_type = emotion_event if emotion_event != "neutral" else inbound_intent
|
||||
if event_type not in {
|
||||
"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 in {"bot", "ambiguous"}
|
||||
else {"kind": "user" if target == "self" 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,
|
||||
{
|
||||
"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,
|
||||
"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,
|
||||
"status": 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
|
||||
|
|
@ -4646,6 +4716,15 @@ Local classifier result:
|
|||
}
|
||||
|
||||
if existing.get("manual_override") and (not existing.get("expires_at") or _safe_float(existing.get("expires_at"), 0) > now):
|
||||
event_recorder = getattr(self, "_record_interaction_emotion_event", None)
|
||||
if callable(event_recorder):
|
||||
event_recorder(
|
||||
user, intent,
|
||||
band=str(existing.get("expression_band") or "relaxed"),
|
||||
reason_code="manual_override_retained",
|
||||
status="ignored",
|
||||
expires_at=_safe_float(existing.get("expires_at"), 0),
|
||||
)
|
||||
user["current_interaction"] = existing
|
||||
return
|
||||
|
||||
|
|
@ -4682,9 +4761,27 @@ 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
|
||||
|
||||
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
|
||||
user["current_interaction"] = current_interaction_projection(
|
||||
{
|
||||
"expression_band": band,
|
||||
|
|
@ -4693,6 +4790,8 @@ Local classifier result:
|
|||
"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", ""),
|
||||
},
|
||||
relationship_role=role,
|
||||
relationship_mode=relationship_mode,
|
||||
|
|
|
|||
正在加载…
添加表格
在新工单中引用