比较提交
10 提交
44b9359d59
...
7ce121be59
| 作者 | SHA1 | 提交日期 | |
|---|---|---|---|
| 7ce121be59 | |||
| 67c3d2d756 | |||
| a747cdd095 | |||
|
|
f26eaa0270 | ||
|
|
d01da7b050 | ||
|
|
eda74f0d60 | ||
|
|
aae4565c84 | ||
|
|
4b0219eac2 | ||
|
|
5705a44be3 | ||
|
|
159bf5a63d |
共有 36 个文件被更改,包括 4403 次插入 和 237 次删除
|
|
@ -1,9 +1,9 @@
|
||||||
# 我会牢牢记住你
|
# 雪色的记忆插件-聊天侧
|
||||||
|
|
||||||
`astrbot_plugin_memory_companion` 是面向 AstrBot 陪伴体系的记忆陪伴中枢。它不把聊天记录粗暴塞回模型,而是把当前消息、连续对话、长期记忆、Bot 自我时间线、群聊/私聊权限和外部陪伴插件线索分层整理,再在每轮 LLM 请求前生成一份临时、可解释、可排查的记忆包。
|
`astrbot_plugin_memory_companion` 是面向 AstrBot 陪伴体系的记忆陪伴中枢。它不把聊天记录粗暴塞回模型,而是把当前消息、连续对话、长期记忆、Bot 自我时间线、群聊/私聊权限和外部陪伴插件线索分层整理,再在每轮 LLM 请求前生成一份临时、可解释、可排查的记忆包。
|
||||||
|
|
||||||
- 插件名:`astrbot_plugin_memory_companion`
|
- 插件名:`astrbot_plugin_memory_companion`
|
||||||
- 中文名:`我会牢牢记住你`
|
- 中文名:`雪色的记忆插件-聊天侧`
|
||||||
- 版本:`1.6.5`
|
- 版本:`1.6.5`
|
||||||
- 适配平台:`aiocqhttp`
|
- 适配平台:`aiocqhttp`
|
||||||
- AstrBot 版本:`>=4.22.0`
|
- AstrBot 版本:`>=4.22.0`
|
||||||
|
|
|
||||||
|
|
@ -657,7 +657,7 @@
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"private_companion_bridge": {
|
"private_companion_bridge": {
|
||||||
"description": "陪伴插件协同",
|
"description": "记忆插件协同",
|
||||||
"hint": "与主动陪伴插件协调记忆、连续对话和自我时间线,减少重复注入和提示词污染。",
|
"hint": "与主动陪伴插件协调记忆、连续对话和自我时间线,减少重复注入和提示词污染。",
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"items": {
|
"items": {
|
||||||
|
|
@ -667,6 +667,18 @@
|
||||||
"type": "bool",
|
"type": "bool",
|
||||||
"default": true
|
"default": true
|
||||||
},
|
},
|
||||||
|
"enable_p5_b1_recall_gate": {
|
||||||
|
"description": "启用 P5-B1 召回闸门",
|
||||||
|
"hint": "默认关闭。开启后普通记忆注入和主动 recall 需要陪伴侧当前请求的一次性 attestation;无效时返回明确 degraded。",
|
||||||
|
"type": "bool",
|
||||||
|
"default": false
|
||||||
|
},
|
||||||
|
"enable_p5_b1_bridge_gate": {
|
||||||
|
"description": "启用 P5-B1 Bridge 闸门",
|
||||||
|
"hint": "默认关闭。开启后 Bridge 搜索、上下文和序列化入口需要一次性 attestation;不会删除原版娱乐写入。",
|
||||||
|
"type": "bool",
|
||||||
|
"default": false
|
||||||
|
},
|
||||||
"schedule_fast_context_enabled": {
|
"schedule_fast_context_enabled": {
|
||||||
"description": "启用日程快速上下文",
|
"description": "启用日程快速上下文",
|
||||||
"hint": "让陪伴插件读取日程连续性时使用本地只读候选,不调用 Embedding 或 Rerank;关闭后回退完整检索。",
|
"hint": "让陪伴插件读取日程连续性时使用本地只读候选,不调用 Embedding 或 Rerank;关闭后回退完整检索。",
|
||||||
|
|
|
||||||
434
core/bridge.py
434
core/bridge.py
|
|
@ -15,6 +15,167 @@ from .profile_api import build_profile_result
|
||||||
|
|
||||||
LOCAL_TZ = ZoneInfo("Asia/Shanghai")
|
LOCAL_TZ = ZoneInfo("Asia/Shanghai")
|
||||||
|
|
||||||
|
_COMPANION_RELATIONSHIP_PHASES = {
|
||||||
|
"deeply_distant",
|
||||||
|
"strongly_distant",
|
||||||
|
"distant",
|
||||||
|
"acquaintance",
|
||||||
|
"familiar",
|
||||||
|
"close",
|
||||||
|
"intimate",
|
||||||
|
"deeply_bonded",
|
||||||
|
}
|
||||||
|
_COMPANION_INTERACTION_BANDS = {
|
||||||
|
"avoidant",
|
||||||
|
"hurt",
|
||||||
|
"relaxed",
|
||||||
|
"lively",
|
||||||
|
"warm",
|
||||||
|
"close",
|
||||||
|
"affectionate",
|
||||||
|
}
|
||||||
|
_COMPANION_EXPRESSION_CONTRACT = "companion_interaction_expression.v1"
|
||||||
|
_COMPANION_EXPRESSION_BEHAVIORS = {
|
||||||
|
"acknowledge",
|
||||||
|
"brief_reply",
|
||||||
|
"give_space",
|
||||||
|
"reply",
|
||||||
|
"clarify",
|
||||||
|
"light_humor",
|
||||||
|
"followup",
|
||||||
|
"support",
|
||||||
|
"shared_ritual",
|
||||||
|
"affectionate_expression",
|
||||||
|
}
|
||||||
|
_COMPANION_EXPRESSION_SAFETY_MODES = {
|
||||||
|
"normal",
|
||||||
|
"contact_boundary_passive",
|
||||||
|
"contact_boundary",
|
||||||
|
"p4_blocked",
|
||||||
|
}
|
||||||
|
_COMPANION_EXPRESSION_BLOCKERS = {"contact_boundary", "p4_safety"}
|
||||||
|
_COMPANION_EXPRESSION_REASON_CODES = {
|
||||||
|
"relationship_baseline_retained",
|
||||||
|
"interaction_band_applied",
|
||||||
|
"administrator_override_applied",
|
||||||
|
"owner_role_required",
|
||||||
|
"contact_boundary_passive_reengagement",
|
||||||
|
"p4_warmth_cap_applied",
|
||||||
|
"relationship_tone_applied",
|
||||||
|
"relationship_address_applied",
|
||||||
|
"relationship_followup_cap",
|
||||||
|
"intent_followup_suppressed",
|
||||||
|
"low_energy_expression_cap",
|
||||||
|
"down_mood_expression_cap",
|
||||||
|
"up_mood_expression_lift",
|
||||||
|
"relationship_proactive_cap",
|
||||||
|
"interaction_proactive_suppressed",
|
||||||
|
"schedule_proactive_suppressed",
|
||||||
|
"p4_blocked",
|
||||||
|
"contact_boundary",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
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:
|
||||||
|
return fallback
|
||||||
|
expression_band = value.get("expression_band")
|
||||||
|
if type(expression_band) is not str or expression_band not in _COMPANION_INTERACTION_BANDS:
|
||||||
|
return fallback
|
||||||
|
allowed_behaviors = value.get("allowed_behaviors")
|
||||||
|
if type(allowed_behaviors) not in {list, tuple} or len(allowed_behaviors) > 12:
|
||||||
|
return fallback
|
||||||
|
if any(type(item) is not str or item not in _COMPANION_EXPRESSION_BEHAVIORS for item in allowed_behaviors):
|
||||||
|
return fallback
|
||||||
|
if len(set(allowed_behaviors)) != len(allowed_behaviors):
|
||||||
|
return fallback
|
||||||
|
safety_mode = value.get("safety_mode")
|
||||||
|
if type(safety_mode) is not str or safety_mode not in _COMPANION_EXPRESSION_SAFETY_MODES:
|
||||||
|
return fallback
|
||||||
|
blocker = value.get("blocker")
|
||||||
|
if blocker is not None and (type(blocker) is not str or blocker not in _COMPANION_EXPRESSION_BLOCKERS):
|
||||||
|
return fallback
|
||||||
|
reason_codes = value.get("reason_codes")
|
||||||
|
if type(reason_codes) not in {list, tuple} or len(reason_codes) > 24:
|
||||||
|
return fallback
|
||||||
|
if any(type(item) is not str or item not in _COMPANION_EXPRESSION_REASON_CODES for item in reason_codes):
|
||||||
|
return fallback
|
||||||
|
if type(value.get("followup")) is not bool:
|
||||||
|
return fallback
|
||||||
|
return {
|
||||||
|
"status": "accepted",
|
||||||
|
"read_only": True,
|
||||||
|
"decision": {
|
||||||
|
"contract": _COMPANION_EXPRESSION_CONTRACT,
|
||||||
|
"expression_band": expression_band,
|
||||||
|
"allowed_behaviors": list(allowed_behaviors),
|
||||||
|
"safety_mode": safety_mode,
|
||||||
|
"blocker": blocker,
|
||||||
|
"reason_codes": list(reason_codes),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def sanitize_companion_relationship_projection(value: Any) -> dict[str, Any]:
|
||||||
|
fallback = {"status": "invalid", "read_only": True, "projection": {}}
|
||||||
|
if type(value) is not dict:
|
||||||
|
return fallback
|
||||||
|
if value.get("schema_version") != "chat.relationship_projection.v1":
|
||||||
|
return fallback
|
||||||
|
if value.get("authority") != "private_companion.relationship_score" or value.get("read_only") is not True:
|
||||||
|
return fallback
|
||||||
|
phase_key = value.get("phase_key")
|
||||||
|
if type(phase_key) is not str or phase_key not in _COMPANION_RELATIONSHIP_PHASES:
|
||||||
|
return fallback
|
||||||
|
score = value.get("score")
|
||||||
|
if type(score) is not int or not -1200 <= score <= 1200:
|
||||||
|
return fallback
|
||||||
|
soft = value.get("soft_behaviors")
|
||||||
|
if type(soft) is not dict or any(type(item) is not bool for item in soft.values()):
|
||||||
|
return fallback
|
||||||
|
try:
|
||||||
|
proactive_care_limit = int(value.get("proactive_care_limit") or 0)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
proactive_care_limit = 0
|
||||||
|
projection = {
|
||||||
|
"schema_version": "chat.relationship_projection.v1",
|
||||||
|
"authority": "private_companion.relationship_score",
|
||||||
|
"read_only": True,
|
||||||
|
"score": score,
|
||||||
|
"phase_key": phase_key,
|
||||||
|
"phase_label": clean_text(value.get("phase_label"), 40),
|
||||||
|
"tone": clean_text(value.get("tone"), 160),
|
||||||
|
"address_level": clean_text(value.get("address_level"), 120),
|
||||||
|
"proactive_care_limit": max(0, min(30, proactive_care_limit)),
|
||||||
|
"soft_behaviors": {
|
||||||
|
key: bool(soft.get(key, False))
|
||||||
|
for key in (
|
||||||
|
"allow_playful_jokes",
|
||||||
|
"allow_followup",
|
||||||
|
"allow_memory_mention",
|
||||||
|
"allow_daily_care",
|
||||||
|
)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
relationship_mode = value.get("relationship_mode")
|
||||||
|
if relationship_mode in {"normal", "owner_exclusive"}:
|
||||||
|
projection["relationship_mode"] = relationship_mode
|
||||||
|
current_interaction = value.get("current_interaction")
|
||||||
|
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"] = {
|
||||||
|
"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,
|
||||||
|
}
|
||||||
|
return {"status": "accepted", "read_only": True, "projection": projection}
|
||||||
|
|
||||||
|
|
||||||
def _local_time_label(value: Any) -> str:
|
def _local_time_label(value: Any) -> str:
|
||||||
text = clean_text(value, 80)
|
text = clean_text(value, 80)
|
||||||
|
|
@ -41,6 +202,10 @@ class MemoryCompanionBridge:
|
||||||
self._plugin = plugin
|
self._plugin = plugin
|
||||||
self._capability_cache = CapabilityCache()
|
self._capability_cache = CapabilityCache()
|
||||||
|
|
||||||
|
def consume_relationship_projection(self, projection: Any) -> dict[str, Any]:
|
||||||
|
"""Validate a read-only Companion relationship projection without persisting it."""
|
||||||
|
return sanitize_companion_relationship_projection(projection)
|
||||||
|
|
||||||
async def record_event(
|
async def record_event(
|
||||||
self,
|
self,
|
||||||
*,
|
*,
|
||||||
|
|
@ -315,6 +480,86 @@ class MemoryCompanionBridge:
|
||||||
"items": safe_items,
|
"items": safe_items,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async def read_user_memory_summary(
|
||||||
|
self,
|
||||||
|
user_id: str,
|
||||||
|
*,
|
||||||
|
session_id: str = "",
|
||||||
|
limit: int = 6,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Read a strict, exact-user Memory summary without exposing memory text."""
|
||||||
|
|
||||||
|
identity = clean_text(user_id, 120)
|
||||||
|
safe_session = clean_text(session_id, 200)
|
||||||
|
base = {
|
||||||
|
"contract": "memory.user_memory_summary.v1",
|
||||||
|
"ok": False,
|
||||||
|
"read_only": True,
|
||||||
|
"state": "degraded",
|
||||||
|
"degraded": True,
|
||||||
|
"pending": True,
|
||||||
|
"user_id": identity,
|
||||||
|
"session_id": safe_session,
|
||||||
|
"counts": {"profile": 0, "preference": 0, "relationship": 0, "private_conversation": 0, "other": 0, "total": 0},
|
||||||
|
"summaries": [],
|
||||||
|
"workspace": {"kind": "memory_user_workspace", "route_hint": "user_memory", "user_id": identity},
|
||||||
|
}
|
||||||
|
if not identity:
|
||||||
|
return {**base, "error_code": "missing_user_id"}
|
||||||
|
try:
|
||||||
|
getter = getattr(self._plugin, "read_user_memory_summary", None)
|
||||||
|
except Exception:
|
||||||
|
getter = None
|
||||||
|
if not callable(getter):
|
||||||
|
return {**base, "error_code": "bridge_method_unavailable"}
|
||||||
|
try:
|
||||||
|
result = await getter(identity, session_id=safe_session, limit=limit)
|
||||||
|
except Exception:
|
||||||
|
return {**base, "error_code": "bridge_exception"}
|
||||||
|
if not isinstance(result, dict) or result.get("contract") != base["contract"]:
|
||||||
|
return {**base, "error_code": "invalid_bridge_response"}
|
||||||
|
|
||||||
|
counts = dict(base["counts"])
|
||||||
|
raw_counts = result.get("counts") if isinstance(result.get("counts"), dict) else {}
|
||||||
|
for key in counts:
|
||||||
|
try:
|
||||||
|
counts[key] = max(0, int(raw_counts.get(key, 0)))
|
||||||
|
except (TypeError, ValueError, OverflowError):
|
||||||
|
counts[key] = 0
|
||||||
|
summaries: list[dict[str, Any]] = []
|
||||||
|
for item in result.get("summaries", []) if isinstance(result.get("summaries"), list) else []:
|
||||||
|
if not isinstance(item, dict):
|
||||||
|
continue
|
||||||
|
category = clean_text(item.get("category"), 40)
|
||||||
|
if category not in {"profile", "preference", "relationship", "private_conversation", "other"}:
|
||||||
|
continue
|
||||||
|
summaries.append(
|
||||||
|
{
|
||||||
|
"category": category,
|
||||||
|
"memory_type": clean_text(item.get("memory_type"), 80),
|
||||||
|
"occurred_at": clean_text(item.get("occurred_at"), 80),
|
||||||
|
"summary": clean_text(item.get("summary"), 100),
|
||||||
|
"content_redacted": True,
|
||||||
|
"truncated": True,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
if len(summaries) >= 8:
|
||||||
|
break
|
||||||
|
state = clean_text(result.get("state"), 40)
|
||||||
|
return {
|
||||||
|
**base,
|
||||||
|
"ok": bool(result.get("ok")) and state == "ready",
|
||||||
|
"state": "ready" if state == "ready" else "degraded",
|
||||||
|
"degraded": state != "ready" or bool(result.get("degraded", False)),
|
||||||
|
"pending": state != "ready" or bool(result.get("pending", False)),
|
||||||
|
"user_id": identity,
|
||||||
|
"session_id": safe_session,
|
||||||
|
"counts": counts,
|
||||||
|
"summaries": summaries,
|
||||||
|
"workspace": base["workspace"],
|
||||||
|
**({"error_code": clean_text(result.get("error_code"), 80)} if state != "ready" and clean_text(result.get("error_code"), 80) else {}),
|
||||||
|
}
|
||||||
|
|
||||||
async def search_bot_personal_profile(self, query: str = "", *, limit: int = 10) -> dict[str, Any]:
|
async def search_bot_personal_profile(self, query: str = "", *, limit: int = 10) -> dict[str, Any]:
|
||||||
return await self.read_bot_personal_profile(query=query, limit=limit)
|
return await self.read_bot_personal_profile(query=query, limit=limit)
|
||||||
|
|
||||||
|
|
@ -393,8 +638,16 @@ class MemoryCompanionBridge:
|
||||||
*,
|
*,
|
||||||
session_context: SessionContext | dict[str, Any] | None = None,
|
session_context: SessionContext | dict[str, Any] | None = None,
|
||||||
top_k: int | None = None,
|
top_k: int | None = None,
|
||||||
|
p5_attestation: Any = None,
|
||||||
|
p5_attestation_consumer: Any = None,
|
||||||
) -> list[dict[str, Any]]:
|
) -> list[dict[str, Any]]:
|
||||||
return await self._plugin.bridge_search(query, session_context=session_context, top_k=top_k)
|
return await self._plugin.bridge_search(
|
||||||
|
query,
|
||||||
|
session_context=session_context,
|
||||||
|
top_k=top_k,
|
||||||
|
p5_attestation=p5_attestation,
|
||||||
|
p5_attestation_consumer=p5_attestation_consumer,
|
||||||
|
)
|
||||||
|
|
||||||
async def compose_injection(
|
async def compose_injection(
|
||||||
self,
|
self,
|
||||||
|
|
@ -405,6 +658,8 @@ class MemoryCompanionBridge:
|
||||||
max_chars: int | None = None,
|
max_chars: int | None = None,
|
||||||
companion_bot_mood: str = "",
|
companion_bot_mood: str = "",
|
||||||
companion_bot_energy: float = 0.0,
|
companion_bot_energy: float = 0.0,
|
||||||
|
p5_attestation: Any = None,
|
||||||
|
p5_attestation_consumer: Any = None,
|
||||||
) -> str:
|
) -> str:
|
||||||
return await self._plugin.bridge_compose_injection(
|
return await self._plugin.bridge_compose_injection(
|
||||||
query,
|
query,
|
||||||
|
|
@ -413,6 +668,8 @@ class MemoryCompanionBridge:
|
||||||
max_chars=max_chars,
|
max_chars=max_chars,
|
||||||
companion_bot_mood=companion_bot_mood,
|
companion_bot_mood=companion_bot_mood,
|
||||||
companion_bot_energy=companion_bot_energy,
|
companion_bot_energy=companion_bot_energy,
|
||||||
|
p5_attestation=p5_attestation,
|
||||||
|
p5_attestation_consumer=p5_attestation_consumer,
|
||||||
)
|
)
|
||||||
|
|
||||||
async def compose_context(
|
async def compose_context(
|
||||||
|
|
@ -425,6 +682,8 @@ class MemoryCompanionBridge:
|
||||||
companion_bot_mood: str = "",
|
companion_bot_mood: str = "",
|
||||||
companion_bot_energy: float = 0.0,
|
companion_bot_energy: float = 0.0,
|
||||||
retrieval_profile: str = "",
|
retrieval_profile: str = "",
|
||||||
|
p5_attestation: Any = None,
|
||||||
|
p5_attestation_consumer: Any = None,
|
||||||
) -> str:
|
) -> str:
|
||||||
return await self._plugin.bridge_compose_context(
|
return await self._plugin.bridge_compose_context(
|
||||||
query=query,
|
query=query,
|
||||||
|
|
@ -434,13 +693,74 @@ class MemoryCompanionBridge:
|
||||||
companion_bot_mood=companion_bot_mood,
|
companion_bot_mood=companion_bot_mood,
|
||||||
companion_bot_energy=companion_bot_energy,
|
companion_bot_energy=companion_bot_energy,
|
||||||
retrieval_profile=retrieval_profile,
|
retrieval_profile=retrieval_profile,
|
||||||
|
p5_attestation=p5_attestation,
|
||||||
|
p5_attestation_consumer=p5_attestation_consumer,
|
||||||
)
|
)
|
||||||
|
|
||||||
async def remember(self, *, event: Any, content: str, note_type: str = "memory") -> dict[str, Any]:
|
async def remember(self, *, event: Any, content: str, note_type: str = "memory") -> dict[str, Any]:
|
||||||
return await self._plugin.tool_remember(event, content, note_type=note_type)
|
return await self._plugin.tool_remember(event, content, note_type=note_type)
|
||||||
|
|
||||||
async def recall(self, *, event: Any, query: str, top_k: int = 5) -> dict[str, Any]:
|
async def recall(
|
||||||
return await self._plugin.tool_recall(event, query, top_k=top_k)
|
self,
|
||||||
|
*,
|
||||||
|
event: Any,
|
||||||
|
query: str,
|
||||||
|
top_k: int = 5,
|
||||||
|
p5_attestation: Any = None,
|
||||||
|
p5_attestation_consumer: Any = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
return await self._plugin.tool_recall(
|
||||||
|
event,
|
||||||
|
query,
|
||||||
|
top_k=top_k,
|
||||||
|
p5_attestation=p5_attestation,
|
||||||
|
p5_attestation_consumer=p5_attestation_consumer,
|
||||||
|
)
|
||||||
|
|
||||||
|
def p5_capability_status(self) -> dict[str, Any]:
|
||||||
|
getter = getattr(self._plugin, "p5_capability_status", None)
|
||||||
|
if not callable(getter):
|
||||||
|
return {"state": "degraded", "error_code": "p5_status_unavailable"}
|
||||||
|
try:
|
||||||
|
result = getter()
|
||||||
|
except Exception:
|
||||||
|
return {"state": "degraded", "error_code": "p5_status_exception"}
|
||||||
|
return dict(result) if isinstance(result, dict) else {"state": "degraded", "error_code": "p5_status_invalid"}
|
||||||
|
|
||||||
|
def provenance_snapshot(self) -> dict[str, Any]:
|
||||||
|
getter = getattr(self._plugin, "provenance_snapshot", None)
|
||||||
|
if not callable(getter):
|
||||||
|
return {"records": {}, "operation_count": 0, "state": "degraded"}
|
||||||
|
result = getter()
|
||||||
|
return dict(result) if isinstance(result, dict) else {"records": {}, "operation_count": 0, "state": "degraded"}
|
||||||
|
|
||||||
|
def provenance_preview(self, candidates: list[dict[str, Any]], *, operation_ref_hash: str) -> dict[str, Any]:
|
||||||
|
getter = getattr(self._plugin, "provenance_preview", None)
|
||||||
|
if not callable(getter):
|
||||||
|
return {"mode": "preview", "readonly": True, "write_count": 0, "error_codes": ["unavailable"]}
|
||||||
|
result = getter(candidates, operation_ref_hash=operation_ref_hash)
|
||||||
|
return dict(result) if isinstance(result, dict) else {"mode": "preview", "readonly": True, "write_count": 0, "error_codes": ["invalid_result"]}
|
||||||
|
|
||||||
|
async def provenance_apply(self, operation: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
getter = getattr(self._plugin, "provenance_apply", None)
|
||||||
|
if not callable(getter):
|
||||||
|
return {"ok": False, "state": "degraded", "error_code": "unavailable"}
|
||||||
|
result = await getter(operation)
|
||||||
|
return dict(result) if isinstance(result, dict) else {"ok": False, "state": "degraded", "error_code": "invalid_result"}
|
||||||
|
|
||||||
|
async def provenance_backup(self) -> dict[str, Any]:
|
||||||
|
getter = getattr(self._plugin, "provenance_backup", None)
|
||||||
|
if not callable(getter):
|
||||||
|
return {"ok": False, "state": "degraded", "error_code": "unavailable"}
|
||||||
|
result = await getter()
|
||||||
|
return dict(result) if isinstance(result, dict) else {"ok": False, "state": "degraded", "error_code": "invalid_result"}
|
||||||
|
|
||||||
|
async def provenance_rollback(self, operation: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
getter = getattr(self._plugin, "provenance_rollback", None)
|
||||||
|
if not callable(getter):
|
||||||
|
return {"ok": False, "state": "degraded", "error_code": "unavailable"}
|
||||||
|
result = await getter(operation)
|
||||||
|
return dict(result) if isinstance(result, dict) else {"ok": False, "state": "degraded", "error_code": "invalid_result"}
|
||||||
|
|
||||||
async def create_note(self, *, event: Any, title: str, content: str = "") -> dict[str, Any]:
|
async def create_note(self, *, event: Any, title: str, content: str = "") -> dict[str, Any]:
|
||||||
return await self._plugin.tool_note_create(event, title, content)
|
return await self._plugin.tool_note_create(event, title, content)
|
||||||
|
|
@ -517,22 +837,22 @@ class MemoryCompanionBridge:
|
||||||
read_only=False,
|
read_only=False,
|
||||||
)
|
)
|
||||||
except Exception:
|
except Exception:
|
||||||
return self._degraded_personal_capability_probe("contract_descriptor_exception")
|
return self._negative_personal_capability_probe("contract_descriptor_exception")
|
||||||
|
|
||||||
if not isinstance(descriptor, dict):
|
if not isinstance(descriptor, dict):
|
||||||
return self._degraded_personal_capability_probe("contract_descriptor_invalid")
|
return self._negative_personal_capability_probe("contract_descriptor_invalid")
|
||||||
|
|
||||||
result = dict(descriptor)
|
result = dict(descriptor)
|
||||||
try:
|
try:
|
||||||
problems = bot_personal_contract.contract_self_check()
|
problems = bot_personal_contract.contract_self_check()
|
||||||
except Exception:
|
except Exception:
|
||||||
return self._degraded_personal_capability_probe(
|
return self._negative_personal_capability_probe(
|
||||||
"contract_self_check_exception",
|
"contract_self_check_exception",
|
||||||
base=result,
|
base=result,
|
||||||
)
|
)
|
||||||
|
|
||||||
if not isinstance(problems, list):
|
if not isinstance(problems, list):
|
||||||
return self._degraded_personal_capability_probe(
|
return self._negative_personal_capability_probe(
|
||||||
"contract_self_check_invalid",
|
"contract_self_check_invalid",
|
||||||
base=result,
|
base=result,
|
||||||
)
|
)
|
||||||
|
|
@ -549,7 +869,7 @@ class MemoryCompanionBridge:
|
||||||
code = str(problem).split(":", 1)[0]
|
code = str(problem).split(":", 1)[0]
|
||||||
if code in known_codes and code not in warnings:
|
if code in known_codes and code not in warnings:
|
||||||
warnings.append(code)
|
warnings.append(code)
|
||||||
return self._degraded_personal_capability_probe(
|
return self._negative_personal_capability_probe(
|
||||||
"contract_self_check_failed",
|
"contract_self_check_failed",
|
||||||
base=result,
|
base=result,
|
||||||
warnings=warnings,
|
warnings=warnings,
|
||||||
|
|
@ -574,6 +894,9 @@ class MemoryCompanionBridge:
|
||||||
result["capability_schema_version"] = bot_personal_contract.BOT_PERSONAL_CAPABILITY_SCHEMA_VERSION
|
result["capability_schema_version"] = bot_personal_contract.BOT_PERSONAL_CAPABILITY_SCHEMA_VERSION
|
||||||
result["payload_schema_version"] = bot_personal_contract.BOT_PERSONAL_PAYLOAD_SCHEMA_VERSION
|
result["payload_schema_version"] = bot_personal_contract.BOT_PERSONAL_PAYLOAD_SCHEMA_VERSION
|
||||||
result["capability_state"] = "available"
|
result["capability_state"] = "available"
|
||||||
|
# Capability discovery must remain static: callers use it before the
|
||||||
|
# plugin service is safe to query, and C1 guarantees no storage access.
|
||||||
|
result["p5"] = {"state": "unprobed", "error_code": "p5_status_not_probed"}
|
||||||
self._capability_cache.mark_available(c4_snapshot)
|
self._capability_cache.mark_available(c4_snapshot)
|
||||||
result.setdefault("warnings", [])
|
result.setdefault("warnings", [])
|
||||||
return result
|
return result
|
||||||
|
|
@ -634,6 +957,12 @@ class MemoryCompanionBridge:
|
||||||
"consume_context_projection",
|
"consume_context_projection",
|
||||||
"read_bot_profile",
|
"read_bot_profile",
|
||||||
"read_profile",
|
"read_profile",
|
||||||
|
"p5_capability_status",
|
||||||
|
"provenance_snapshot",
|
||||||
|
"provenance_preview",
|
||||||
|
"provenance_apply",
|
||||||
|
"provenance_backup",
|
||||||
|
"provenance_rollback",
|
||||||
"probe_capability_snapshot",
|
"probe_capability_snapshot",
|
||||||
"probe_bot_personal_memory_capabilities",
|
"probe_bot_personal_memory_capabilities",
|
||||||
],
|
],
|
||||||
|
|
@ -642,6 +971,34 @@ class MemoryCompanionBridge:
|
||||||
result.setdefault("schema_version", str(result.get("capability_schema_version", "")))
|
result.setdefault("schema_version", str(result.get("capability_schema_version", "")))
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
def _negative_personal_capability_probe(
|
||||||
|
self,
|
||||||
|
reason: str,
|
||||||
|
*,
|
||||||
|
base: dict[str, Any] | None = None,
|
||||||
|
warnings: list[str] | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Return a bounded failure and suppress repeated probes for the TTL."""
|
||||||
|
|
||||||
|
safe_reason = clean_text(reason, 120) or "capability_negative"
|
||||||
|
result = self._degraded_personal_capability_probe(
|
||||||
|
safe_reason,
|
||||||
|
base=base,
|
||||||
|
warnings=warnings,
|
||||||
|
)
|
||||||
|
cached = self._capability_cache.mark_negative(safe_reason)
|
||||||
|
for key in ("available", "state", "degraded", "pending", "error_code"):
|
||||||
|
if key in cached:
|
||||||
|
result[key] = cached[key]
|
||||||
|
result["available"] = False
|
||||||
|
result["state"] = "negative"
|
||||||
|
result["capability_state"] = "negative"
|
||||||
|
result["degraded"] = True
|
||||||
|
result["pending"] = False
|
||||||
|
result["error_code"] = safe_reason
|
||||||
|
result["p5"] = {"state": "degraded", "error_code": safe_reason}
|
||||||
|
return result
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _degraded_personal_capability_probe(
|
def _degraded_personal_capability_probe(
|
||||||
reason: str,
|
reason: str,
|
||||||
|
|
@ -697,6 +1054,7 @@ class MemoryCompanionBridge:
|
||||||
bot_personal_contract, "BOT_PERSONAL_PAYLOAD_SCHEMA_VERSION", ""
|
bot_personal_contract, "BOT_PERSONAL_PAYLOAD_SCHEMA_VERSION", ""
|
||||||
)
|
)
|
||||||
result["capability_state"] = "degraded"
|
result["capability_state"] = "degraded"
|
||||||
|
result["p5"] = {"state": "degraded", "error_code": reason}
|
||||||
return result
|
return result
|
||||||
|
|
||||||
def get_token_usage_summary(self) -> dict[str, Any]:
|
def get_token_usage_summary(self) -> dict[str, Any]:
|
||||||
|
|
@ -768,6 +1126,66 @@ class MemoryCompanionBridge:
|
||||||
ctx = normalizer(payload) if callable(normalizer) else SessionContext(**payload)
|
ctx = normalizer(payload) if callable(normalizer) else SessionContext(**payload)
|
||||||
return getter(ctx)
|
return getter(ctx)
|
||||||
|
|
||||||
|
def peek_relationship_phase(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
session_id: str = "",
|
||||||
|
scope: str = "private",
|
||||||
|
platform: str = "",
|
||||||
|
user_id: str = "",
|
||||||
|
group_id: str = "",
|
||||||
|
bot_id: str = "",
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Read an existing phase projection without creating default state."""
|
||||||
|
fallback = {"observed": False, "phase": "unknown", "momentum_band": "unknown"}
|
||||||
|
payload = {
|
||||||
|
"session_id": session_id,
|
||||||
|
"scope": scope,
|
||||||
|
"platform": platform,
|
||||||
|
"user_id": user_id,
|
||||||
|
"group_id": group_id,
|
||||||
|
"bot_id": bot_id,
|
||||||
|
}
|
||||||
|
if any(type(value) is not str for value in payload.values()):
|
||||||
|
return fallback
|
||||||
|
try:
|
||||||
|
getter = getattr(self._plugin, "_peek_relationship_phase", None)
|
||||||
|
if not callable(getter):
|
||||||
|
return fallback
|
||||||
|
normalizer = getattr(self._plugin, "session_context_from_bridge", None)
|
||||||
|
ctx = normalizer(payload) if callable(normalizer) else SessionContext(**payload)
|
||||||
|
result = getter(ctx)
|
||||||
|
except Exception:
|
||||||
|
return fallback
|
||||||
|
if type(result) is not dict:
|
||||||
|
return fallback
|
||||||
|
for key in result:
|
||||||
|
if type(key) is not str:
|
||||||
|
return fallback
|
||||||
|
|
||||||
|
observed = result.get("observed")
|
||||||
|
phase = result.get("phase")
|
||||||
|
momentum_band = result.get("momentum_band")
|
||||||
|
if type(observed) is not bool or type(phase) is not str or type(momentum_band) is not str:
|
||||||
|
return fallback
|
||||||
|
if phase not in {"acquaintance", "familiar", "close", "intimate", "deeply_bonded"}:
|
||||||
|
return fallback
|
||||||
|
if momentum_band not in {"rising", "cooling", "steady"}:
|
||||||
|
return fallback
|
||||||
|
if not observed:
|
||||||
|
return fallback
|
||||||
|
projection: dict[str, Any] = {
|
||||||
|
"observed": True,
|
||||||
|
"phase": phase,
|
||||||
|
"momentum_band": momentum_band,
|
||||||
|
}
|
||||||
|
touch_count = result.get("touch_count")
|
||||||
|
if touch_count is not None:
|
||||||
|
if type(touch_count) is not int or not 0 <= touch_count <= 256:
|
||||||
|
return fallback
|
||||||
|
projection["touch_count"] = touch_count
|
||||||
|
return projection
|
||||||
|
|
||||||
def get_recent_emotional_state(self) -> dict[str, Any]:
|
def get_recent_emotional_state(self) -> dict[str, Any]:
|
||||||
"""Return a summary of recent emotional events across ALL sessions.
|
"""Return a summary of recent emotional events across ALL sessions.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -637,6 +637,7 @@ class HistoricalChatImporter:
|
||||||
IDENTITY_LINKS_VERSION = 2
|
IDENTITY_LINKS_VERSION = 2
|
||||||
SUMMARY_PERSPECTIVE_VERSION = 1
|
SUMMARY_PERSPECTIVE_VERSION = 1
|
||||||
DETAIL_SCHEMA_VERSION = 1
|
DETAIL_SCHEMA_VERSION = 1
|
||||||
|
STAGED_DATA_ERROR = "历史导入暂存数据损坏,请重新上传或清理该预览"
|
||||||
|
|
||||||
def __init__(self, service: Any) -> None:
|
def __init__(self, service: Any) -> None:
|
||||||
self.service = service
|
self.service = service
|
||||||
|
|
@ -1276,17 +1277,32 @@ class HistoricalChatImporter:
|
||||||
manifest_path = self._upload_dir(upload_id) / "manifest.json"
|
manifest_path = self._upload_dir(upload_id) / "manifest.json"
|
||||||
if not manifest_path.is_file():
|
if not manifest_path.is_file():
|
||||||
raise ValueError("上传预览不存在或已被清理")
|
raise ValueError("上传预览不存在或已被清理")
|
||||||
return json.loads(manifest_path.read_text(encoding="utf-8"))
|
try:
|
||||||
|
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||||
|
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
|
||||||
|
raise ValueError(self.STAGED_DATA_ERROR) from exc
|
||||||
|
if not isinstance(manifest, dict):
|
||||||
|
raise ValueError(self.STAGED_DATA_ERROR)
|
||||||
|
if clean_text(manifest.get("upload_id"), 120) != clean_text(upload_id, 120):
|
||||||
|
raise ValueError(self.STAGED_DATA_ERROR)
|
||||||
|
return manifest
|
||||||
|
|
||||||
def _load_upload_messages(self, upload_id: str) -> tuple[dict[str, Any], list[dict[str, Any]]]:
|
def _load_upload_messages(self, upload_id: str) -> tuple[dict[str, Any], list[dict[str, Any]]]:
|
||||||
manifest = self.preview_upload(upload_id)
|
manifest = self.preview_upload(upload_id)
|
||||||
parsed_path = self._upload_dir(upload_id) / "parsed.jsonl"
|
parsed_path = self._upload_dir(upload_id) / "parsed.jsonl"
|
||||||
messages: list[dict[str, Any]] = []
|
messages: list[dict[str, Any]] = []
|
||||||
for raw in parsed_path.read_text(encoding="utf-8").splitlines():
|
try:
|
||||||
if raw.strip():
|
for line_no, raw in enumerate(parsed_path.read_text(encoding="utf-8").splitlines(), 1):
|
||||||
|
if not raw.strip():
|
||||||
|
continue
|
||||||
value = json.loads(raw)
|
value = json.loads(raw)
|
||||||
if isinstance(value, dict):
|
if not isinstance(value, dict):
|
||||||
messages.append(value)
|
raise ValueError(f"line={line_no}")
|
||||||
|
messages.append(value)
|
||||||
|
except (OSError, UnicodeError, json.JSONDecodeError, ValueError) as exc:
|
||||||
|
raise ValueError(self.STAGED_DATA_ERROR) from exc
|
||||||
|
if not messages:
|
||||||
|
raise ValueError(self.STAGED_DATA_ERROR)
|
||||||
return manifest, messages
|
return manifest, messages
|
||||||
|
|
||||||
def _private_api(self) -> Any | None:
|
def _private_api(self) -> Any | None:
|
||||||
|
|
@ -1986,7 +2002,12 @@ class HistoricalChatImporter:
|
||||||
batch["id"], statuses={"completed", "archived_only"}
|
batch["id"], statuses={"completed", "archived_only"}
|
||||||
)
|
)
|
||||||
memory_counts = await self.store.chat_import_memory_counts(batch["id"])
|
memory_counts = await self.store.chat_import_memory_counts(batch["id"])
|
||||||
checkpoint = max((int(item.get("segment_index") or 0) + 1 for item in completed_segments), default=0)
|
current_checkpoint = max(0, int(batch.get("checkpoint_segment") or 0))
|
||||||
|
computed_checkpoint = max(
|
||||||
|
(int(item.get("segment_index") or 0) + 1 for item in completed_segments),
|
||||||
|
default=0,
|
||||||
|
)
|
||||||
|
checkpoint = max(current_checkpoint, computed_checkpoint)
|
||||||
await self.store.update_chat_import_batch(
|
await self.store.update_chat_import_batch(
|
||||||
batch["id"],
|
batch["id"],
|
||||||
checkpoint_segment=checkpoint,
|
checkpoint_segment=checkpoint,
|
||||||
|
|
|
||||||
|
|
@ -16,7 +16,7 @@ class MemoryCompanionCommandHandler:
|
||||||
sleep = self.service.sleep_status()
|
sleep = self.service.sleep_status()
|
||||||
by_scope = ", ".join(f"{key or 'unknown'}={value}" for key, value in stats["by_scope"].items()) or "none"
|
by_scope = ", ".join(f"{key or 'unknown'}={value}" for key, value in stats["by_scope"].items()) or "none"
|
||||||
return (
|
return (
|
||||||
"我会牢牢记住你:运行中\n"
|
"雪色的记忆插件-聊天侧:运行中\n"
|
||||||
f"版本:{self.version}\n"
|
f"版本:{self.version}\n"
|
||||||
f"记忆:{stats['total_memories']} 条,稳定 {stats['stable_memories']} 条\n"
|
f"记忆:{stats['total_memories']} 条,稳定 {stats['stable_memories']} 条\n"
|
||||||
f"身份:{stats['identities']} 个;关系边:{stats['relationships']} 条;自我时间线:{stats['timeline_events']} 条\n"
|
f"身份:{stats['identities']} 个;关系边:{stats['relationships']} 条;自我时间线:{stats['timeline_events']} 条\n"
|
||||||
|
|
@ -414,7 +414,7 @@ class MemoryCompanionCommandHandler:
|
||||||
|
|
||||||
def help(self) -> str:
|
def help(self) -> str:
|
||||||
return (
|
return (
|
||||||
"我会牢牢记住你命令:\n"
|
"雪色的记忆插件-聊天侧命令:\n"
|
||||||
"主入口 /mcomp。\n"
|
"主入口 /mcomp。\n"
|
||||||
"/mcomp status\n"
|
"/mcomp status\n"
|
||||||
"/mcomp search 关键词\n"
|
"/mcomp search 关键词\n"
|
||||||
|
|
|
||||||
221
core/coordination_status.py
普通文件
221
core/coordination_status.py
普通文件
|
|
@ -0,0 +1,221 @@
|
||||||
|
"""Allowlist-only coordination status for the Memory page.
|
||||||
|
|
||||||
|
This projection is observational. It never returns memory text, identity
|
||||||
|
values, session identifiers, audit bodies, provider details, or handles.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
try:
|
||||||
|
from .p5c_guard import P5C_SINK_FLAGS
|
||||||
|
except ImportError:
|
||||||
|
P5C_SINK_FLAGS = {}
|
||||||
|
try:
|
||||||
|
from .p5d_security_events import P5D_OPERATION_FLAGS
|
||||||
|
except ImportError:
|
||||||
|
P5D_OPERATION_FLAGS = {}
|
||||||
|
|
||||||
|
from .p6_four_package_manifest import FOUR_PACKAGE_IDS, manifest_contract
|
||||||
|
from .p6_readonly_projection import P6_READONLY_STATUS_FINGERPRINT, P6_READONLY_STATUS_SCHEMA
|
||||||
|
|
||||||
|
|
||||||
|
COORDINATION_STATUS_SCHEMA = "ops.memory.coordination_status.v1"
|
||||||
|
_HEALTH = frozenset({"ready", "degraded", "unverifiable"})
|
||||||
|
_P5_B_FLAGS = (
|
||||||
|
"enable_p5_b1_recall_gate",
|
||||||
|
"enable_p5_b1_bridge_gate",
|
||||||
|
"enable_p5_b1_tool_recall_gate",
|
||||||
|
"enable_p5_b2_archive_read_gate",
|
||||||
|
"enable_p5_b2_cross_user_read_gate",
|
||||||
|
)
|
||||||
|
_P6_FIELDS = ("profiles", "identity_links", "audit_events", "operations")
|
||||||
|
_P6_REASON_CODES = frozenset({"", "registry_status_unavailable", "invalid_reason_code"})
|
||||||
|
_BRIDGE_REASON_CODES = frozenset({
|
||||||
|
"bridge_status_unavailable",
|
||||||
|
"bridge_config_unavailable",
|
||||||
|
"bridge_config_unreadable",
|
||||||
|
"bridge_config_invalid",
|
||||||
|
"bridge_disabled",
|
||||||
|
"companion_api_unavailable",
|
||||||
|
"companion_p6_producer_unavailable",
|
||||||
|
"companion_p6_producer_unreadable",
|
||||||
|
"companion_p6_unverifiable",
|
||||||
|
"companion_bridge_available",
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
def _has_exact_str_fields(value: dict[Any, Any], fields: frozenset[str]) -> bool:
|
||||||
|
if len(value) != len(fields):
|
||||||
|
return False
|
||||||
|
for key in value:
|
||||||
|
if type(key) is not str or key not in fields:
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def _fingerprint() -> str:
|
||||||
|
payload = {"schema_version": COORDINATION_STATUS_SCHEMA, "sections": ("page_api", "runtime", "bridge", "p5", "p6", "four_package")}
|
||||||
|
encoded = json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(",", ":")).encode("utf-8")
|
||||||
|
return hashlib.sha256(encoded).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
COORDINATION_STATUS_FINGERPRINT = _fingerprint()
|
||||||
|
|
||||||
|
|
||||||
|
def _status(health: str, reason_code: str) -> dict[str, str]:
|
||||||
|
return {
|
||||||
|
"health": health if type(health) is str and health in _HEALTH else "unverifiable",
|
||||||
|
"reason_code": reason_code if type(reason_code) is str and len(reason_code) <= 80 else "status_unavailable",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _project_bridge_status(raw: Any) -> dict[str, str]:
|
||||||
|
if type(raw) is not dict or not _has_exact_str_fields(raw, frozenset({"health", "reason_code"})):
|
||||||
|
return _status("unverifiable", "bridge_status_unavailable")
|
||||||
|
health = raw.get("health")
|
||||||
|
reason_code = raw.get("reason_code")
|
||||||
|
if type(health) is not str or health not in _HEALTH:
|
||||||
|
return _status("unverifiable", "bridge_status_unavailable")
|
||||||
|
if type(reason_code) is not str or reason_code not in _BRIDGE_REASON_CODES:
|
||||||
|
return _status("unverifiable", "bridge_status_unavailable")
|
||||||
|
return _status(health, reason_code)
|
||||||
|
|
||||||
|
|
||||||
|
def _unavailable_group(total_count: int) -> dict[str, Any]:
|
||||||
|
return {"health": "unverifiable", "mode": "unavailable", "enabled_count": 0, "total_count": total_count, "reason_code": "contract_not_available"}
|
||||||
|
|
||||||
|
|
||||||
|
def _config_group(config: Any, flags: tuple[str, ...], *, fallback_flags: tuple[str, ...] = ()) -> dict[str, Any]:
|
||||||
|
if not flags:
|
||||||
|
return _unavailable_group(0)
|
||||||
|
getter = getattr(config, "bool", None)
|
||||||
|
if not callable(getter):
|
||||||
|
return {"health": "unverifiable", "mode": "unverifiable", "enabled_count": 0, "total_count": len(flags), "reason_code": "config_unavailable"}
|
||||||
|
values: list[bool] = []
|
||||||
|
for index, flag in enumerate(flags):
|
||||||
|
try:
|
||||||
|
value = getter(flag, False)
|
||||||
|
if type(value) is not bool:
|
||||||
|
return {"health": "unverifiable", "mode": "unverifiable", "enabled_count": 0, "total_count": len(flags), "reason_code": "config_value_invalid"}
|
||||||
|
if value is False and fallback_flags:
|
||||||
|
fallback = getter(fallback_flags[index], False)
|
||||||
|
if type(fallback) is not bool:
|
||||||
|
return {"health": "unverifiable", "mode": "unverifiable", "enabled_count": 0, "total_count": len(flags), "reason_code": "config_value_invalid"}
|
||||||
|
value = fallback
|
||||||
|
except Exception:
|
||||||
|
return {"health": "unverifiable", "mode": "unverifiable", "enabled_count": 0, "total_count": len(flags), "reason_code": "config_unreadable"}
|
||||||
|
values.append(value)
|
||||||
|
enabled_count = sum(values)
|
||||||
|
if enabled_count == 0:
|
||||||
|
return {"health": "ready", "mode": "default_off", "enabled_count": 0, "total_count": len(flags), "reason_code": "default_off"}
|
||||||
|
if enabled_count == len(flags):
|
||||||
|
return {"health": "ready", "mode": "enabled", "enabled_count": enabled_count, "total_count": len(flags), "reason_code": "configured"}
|
||||||
|
return {"health": "degraded", "mode": "partial", "enabled_count": enabled_count, "total_count": len(flags), "reason_code": "partial_coverage"}
|
||||||
|
|
||||||
|
|
||||||
|
def build_p5_status(config: Any) -> dict[str, dict[str, Any]]:
|
||||||
|
return {
|
||||||
|
"attestation_read": _config_group(config, _P5_B_FLAGS),
|
||||||
|
"sink_boundary": _config_group(config, tuple(f"p5c_safety.{flag}" for flag in P5C_SINK_FLAGS.values()), fallback_flags=tuple(P5C_SINK_FLAGS.values())),
|
||||||
|
"security_recovery": _config_group(config, tuple(f"p5d_safety.{flag}" for flag in P5D_OPERATION_FLAGS.values()), fallback_flags=tuple(P5D_OPERATION_FLAGS.values())),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def project_runtime_health(runtime: Any) -> dict[str, str]:
|
||||||
|
try:
|
||||||
|
if type(runtime) is dict:
|
||||||
|
for key in runtime:
|
||||||
|
if type(key) is not str:
|
||||||
|
return _status("unverifiable", "runtime_unsupported")
|
||||||
|
if len(runtime) != 1 or "compatibility_level" not in runtime:
|
||||||
|
return _status("unverifiable", "runtime_unsupported")
|
||||||
|
level = runtime.get("compatibility_level")
|
||||||
|
else:
|
||||||
|
level = getattr(runtime, "compatibility_level", None)
|
||||||
|
except Exception:
|
||||||
|
return _status("unverifiable", "runtime_status_unavailable")
|
||||||
|
if type(level) is not str:
|
||||||
|
return _status("unverifiable", "runtime_unsupported")
|
||||||
|
if level == "full":
|
||||||
|
return _status("ready", "runtime_compatible")
|
||||||
|
if level == "degraded":
|
||||||
|
return _status("degraded", "runtime_degraded")
|
||||||
|
return _status("unverifiable", "runtime_unsupported")
|
||||||
|
|
||||||
|
|
||||||
|
def project_p6_status(raw: Any) -> dict[str, Any]:
|
||||||
|
fallback = {
|
||||||
|
"schema_version": P6_READONLY_STATUS_SCHEMA,
|
||||||
|
"contract_fingerprint": P6_READONLY_STATUS_FINGERPRINT,
|
||||||
|
"health": "unverifiable",
|
||||||
|
"reason_code": "p6_status_unavailable",
|
||||||
|
"counts": {field: 0 for field in _P6_FIELDS},
|
||||||
|
}
|
||||||
|
if type(raw) is not dict or not _has_exact_str_fields(raw, frozenset({"schema_version", "source_plugin", "contract_fingerprint", "health", "reason_code", "counts"})):
|
||||||
|
return fallback
|
||||||
|
schema_version = raw.get("schema_version")
|
||||||
|
source_plugin = raw.get("source_plugin")
|
||||||
|
contract_fingerprint = raw.get("contract_fingerprint")
|
||||||
|
if (
|
||||||
|
type(schema_version) is not str
|
||||||
|
or type(source_plugin) is not str
|
||||||
|
or type(contract_fingerprint) is not str
|
||||||
|
or schema_version != P6_READONLY_STATUS_SCHEMA
|
||||||
|
or source_plugin != "private_companion"
|
||||||
|
or contract_fingerprint != P6_READONLY_STATUS_FINGERPRINT
|
||||||
|
):
|
||||||
|
return fallback
|
||||||
|
health, reason_code, counts = raw.get("health"), raw.get("reason_code"), raw.get("counts")
|
||||||
|
if type(health) is not str or health not in _HEALTH:
|
||||||
|
return fallback
|
||||||
|
if type(reason_code) is not str or reason_code not in _P6_REASON_CODES:
|
||||||
|
return fallback
|
||||||
|
if type(counts) is not dict or not _has_exact_str_fields(counts, frozenset(_P6_FIELDS)):
|
||||||
|
return fallback
|
||||||
|
if any(type(counts[field]) is not int or not 0 <= counts[field] <= 10_000_000 for field in _P6_FIELDS):
|
||||||
|
return fallback
|
||||||
|
return {
|
||||||
|
"schema_version": P6_READONLY_STATUS_SCHEMA,
|
||||||
|
"contract_fingerprint": P6_READONLY_STATUS_FINGERPRINT,
|
||||||
|
"health": health,
|
||||||
|
"reason_code": reason_code,
|
||||||
|
"counts": {field: counts[field] for field in _P6_FIELDS},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def build_coordination_status(*, config: Any, runtime: Any, bridge: dict[str, str], p6_raw: Any) -> dict[str, Any]:
|
||||||
|
p5 = build_p5_status(config)
|
||||||
|
p6 = project_p6_status(p6_raw)
|
||||||
|
manifest = manifest_contract()
|
||||||
|
bridge_status = _project_bridge_status(bridge)
|
||||||
|
components = [project_runtime_health(runtime), bridge_status, {"health": p6["health"], "reason_code": p6["reason_code"]}]
|
||||||
|
if any(item["health"] == "unverifiable" for item in components):
|
||||||
|
health, reason_code = "unverifiable", "coordination_input_unverifiable"
|
||||||
|
elif any(item["health"] == "degraded" for item in components):
|
||||||
|
health, reason_code = "degraded", "coordination_degraded"
|
||||||
|
else:
|
||||||
|
health, reason_code = "ready", "coordination_ready"
|
||||||
|
return {
|
||||||
|
"schema_version": COORDINATION_STATUS_SCHEMA,
|
||||||
|
"contract_fingerprint": COORDINATION_STATUS_FINGERPRINT,
|
||||||
|
"health": health,
|
||||||
|
"reason_code": reason_code,
|
||||||
|
"page_api": _status("ready", "page_api_registered"),
|
||||||
|
"runtime": project_runtime_health(runtime),
|
||||||
|
"bridge": bridge_status,
|
||||||
|
"p5": p5,
|
||||||
|
"p6": p6,
|
||||||
|
"four_package": {
|
||||||
|
"schema_version": manifest["schema"],
|
||||||
|
"contract_fingerprint": manifest["contract_fingerprint"],
|
||||||
|
"health": "unverifiable",
|
||||||
|
"reason_code": "manifest_registry_unavailable",
|
||||||
|
"expected_package_count": len(FOUR_PACKAGE_IDS),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = ["COORDINATION_STATUS_FINGERPRINT", "COORDINATION_STATUS_SCHEMA", "build_coordination_status", "build_p5_status", "project_p6_status", "project_runtime_health"]
|
||||||
|
|
@ -642,7 +642,7 @@ class InjectionComposer:
|
||||||
scar = 0.0
|
scar = 0.0
|
||||||
hints: list[str] = []
|
hints: list[str] = []
|
||||||
if phase and phase != "neutral":
|
if phase and phase != "neutral":
|
||||||
hints.append(f"关系阶段={phase}")
|
hints.append(f"当时关系情境={phase}")
|
||||||
if scar >= 0.45:
|
if scar >= 0.45:
|
||||||
hints.append("伤痕感=高")
|
hints.append("伤痕感=高")
|
||||||
try:
|
try:
|
||||||
|
|
|
||||||
|
|
@ -78,6 +78,18 @@ class SessionContext:
|
||||||
strict_session_only: bool = False
|
strict_session_only: bool = False
|
||||||
preferred_address: str = ""
|
preferred_address: str = ""
|
||||||
preferred_address_locked: bool = False
|
preferred_address_locked: bool = False
|
||||||
|
relationship_authority_source: str = ""
|
||||||
|
companion_relationship_score: int = 0
|
||||||
|
companion_relationship_phase_key: str = ""
|
||||||
|
companion_relationship_phase_label: str = ""
|
||||||
|
companion_relationship_tone: str = ""
|
||||||
|
companion_relationship_address_level: str = ""
|
||||||
|
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, ...] = ()
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def current_target_id(self) -> str:
|
def current_target_id(self) -> str:
|
||||||
|
|
|
||||||
|
|
@ -15,6 +15,7 @@ from .models import EntityRef, MemoryRecord, clean_text, json_loads
|
||||||
PORTABLE_FORMAT = "astrbot-memory-jsonl"
|
PORTABLE_FORMAT = "astrbot-memory-jsonl"
|
||||||
PORTABLE_VERSION = 1
|
PORTABLE_VERSION = 1
|
||||||
MAX_PORTABLE_BYTES = 64 * 1024 * 1024
|
MAX_PORTABLE_BYTES = 64 * 1024 * 1024
|
||||||
|
PORTABLE_EXPORT_PAGE_SIZE = 500
|
||||||
|
|
||||||
|
|
||||||
PRESETS: dict[str, dict[str, Any]] = {
|
PRESETS: dict[str, dict[str, Any]] = {
|
||||||
|
|
@ -302,17 +303,14 @@ class PortableMemoryArchive:
|
||||||
self.export_dir = self.data_dir / "exports"
|
self.export_dir = self.data_dir / "exports"
|
||||||
|
|
||||||
async def export(self) -> dict[str, Any]:
|
async def export(self) -> dict[str, Any]:
|
||||||
memories = await self.store.list_memories(limit=1_000_000)
|
stats = await self.store.stats()
|
||||||
identities = await self.store.list_identities(limit=1_000_000)
|
|
||||||
relationships = await self.store.list_relationships(limit=1_000_000)
|
|
||||||
timeline = await self.store.recent_timeline(limit=1_000_000)
|
|
||||||
acl_rules = await self.store.list_acl_rules()
|
acl_rules = await self.store.list_acl_rules()
|
||||||
acl_policies = await self.store.list_acl_policies()
|
acl_policies = await self.store.list_acl_policies()
|
||||||
counts = {
|
counts = {
|
||||||
"memory": len(memories),
|
"memory": int(stats.get("total_memories") or 0),
|
||||||
"identity": len(identities),
|
"identity": int(stats.get("identities") or 0),
|
||||||
"relationship": len(relationships),
|
"relationship": int(stats.get("relationships") or 0),
|
||||||
"timeline": len(timeline),
|
"timeline": int(stats.get("timeline_events") or 0),
|
||||||
"acl_rule": len(acl_rules),
|
"acl_rule": len(acl_rules),
|
||||||
"acl_policy": len(acl_policies),
|
"acl_policy": len(acl_policies),
|
||||||
}
|
}
|
||||||
|
|
@ -333,15 +331,26 @@ class PortableMemoryArchive:
|
||||||
try:
|
try:
|
||||||
with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle:
|
with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle:
|
||||||
self._write_line(handle, header)
|
self._write_line(handle, header)
|
||||||
for memory in memories:
|
for record_type, loader, normalizer in (
|
||||||
self._write_line(handle, {"record_type": "memory", "data": self._memory_payload(memory)})
|
("memory", self.store.list_memories, self._memory_payload),
|
||||||
for kind, rows in (
|
("identity", self.store.list_identities, self._normalized_row),
|
||||||
("identity", identities),
|
("relationship", self.store.list_relationships, self._normalized_row),
|
||||||
("relationship", relationships),
|
("timeline", self.store.recent_timeline, self._normalized_row),
|
||||||
("timeline", timeline),
|
|
||||||
("acl_rule", acl_rules),
|
|
||||||
("acl_policy", acl_policies),
|
|
||||||
):
|
):
|
||||||
|
offset = 0
|
||||||
|
while True:
|
||||||
|
rows = await loader(limit=PORTABLE_EXPORT_PAGE_SIZE, offset=offset)
|
||||||
|
if not rows:
|
||||||
|
break
|
||||||
|
for row in rows:
|
||||||
|
self._write_line(
|
||||||
|
handle,
|
||||||
|
{"record_type": record_type, "data": normalizer(row)},
|
||||||
|
)
|
||||||
|
offset += len(rows)
|
||||||
|
if len(rows) < PORTABLE_EXPORT_PAGE_SIZE:
|
||||||
|
break
|
||||||
|
for kind, rows in (("acl_rule", acl_rules), ("acl_policy", acl_policies)):
|
||||||
for row in rows:
|
for row in rows:
|
||||||
self._write_line(handle, {"record_type": kind, "data": self._normalized_row(row)})
|
self._write_line(handle, {"record_type": kind, "data": self._normalized_row(row)})
|
||||||
os.replace(temp_name, path)
|
os.replace(temp_name, path)
|
||||||
|
|
|
||||||
106
core/p6_four_package_manifest.py
普通文件
106
core/p6_four_package_manifest.py
普通文件
|
|
@ -0,0 +1,106 @@
|
||||||
|
"""Pure validation for the shared P6 four-package manifest contract."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
|
||||||
|
|
||||||
|
FOUR_PACKAGE_MANIFEST_SCHEMA = "ops.p6.four_package_manifest.v1"
|
||||||
|
FOUR_PACKAGE_MANIFEST_REPORT_SCHEMA = "ops.p6.four_package_manifest_report.v1"
|
||||||
|
FOUR_PACKAGE_IDS = ("companion", "memory", "ops_archive", "peiban")
|
||||||
|
|
||||||
|
_REQUIRED_MANIFEST_FIELDS = (
|
||||||
|
"schema",
|
||||||
|
"package_id",
|
||||||
|
"manifest_version",
|
||||||
|
"package_fingerprint",
|
||||||
|
"compatibility_fingerprint",
|
||||||
|
)
|
||||||
|
_MANIFEST_VERSION_PATTERN = re.compile(r"^[1-9]\d*\.[0-9]+$")
|
||||||
|
_SHA256_PATTERN = re.compile(r"^[0-9a-f]{64}$")
|
||||||
|
|
||||||
|
|
||||||
|
def _contract_payload() -> dict[str, object]:
|
||||||
|
return {
|
||||||
|
"schema": FOUR_PACKAGE_MANIFEST_SCHEMA,
|
||||||
|
"report_schema": FOUR_PACKAGE_MANIFEST_REPORT_SCHEMA,
|
||||||
|
"package_ids": list(FOUR_PACKAGE_IDS),
|
||||||
|
"required_manifest_fields": list(_REQUIRED_MANIFEST_FIELDS),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def manifest_contract() -> dict[str, object]:
|
||||||
|
descriptor = _contract_payload()
|
||||||
|
canonical = json.dumps(descriptor, ensure_ascii=True, sort_keys=True, separators=(",", ":")).encode("utf-8")
|
||||||
|
descriptor["contract_fingerprint"] = hashlib.sha256(canonical).hexdigest()
|
||||||
|
return descriptor
|
||||||
|
|
||||||
|
|
||||||
|
def _unverifiable_report(reason_code: str) -> dict[str, object]:
|
||||||
|
return {
|
||||||
|
"schema": FOUR_PACKAGE_MANIFEST_REPORT_SCHEMA,
|
||||||
|
"status": "unverifiable",
|
||||||
|
"reason_code": reason_code,
|
||||||
|
"expected_package_ids": list(FOUR_PACKAGE_IDS),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _verified_report() -> dict[str, object]:
|
||||||
|
return {
|
||||||
|
"schema": FOUR_PACKAGE_MANIFEST_REPORT_SCHEMA,
|
||||||
|
"status": "verified",
|
||||||
|
"reason_code": "four_package_manifest_verified",
|
||||||
|
"expected_package_ids": list(FOUR_PACKAGE_IDS),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def verify_four_package_manifests(manifests: object) -> dict[str, object]:
|
||||||
|
"""Verify values only; no package object or runtime is inspected."""
|
||||||
|
if type(manifests) is not dict:
|
||||||
|
return _unverifiable_report("manifest_collection_not_exact_dict")
|
||||||
|
for package_id in manifests:
|
||||||
|
if type(package_id) is not str or package_id not in FOUR_PACKAGE_IDS:
|
||||||
|
return _unverifiable_report("unexpected_package_manifest")
|
||||||
|
for package_id in FOUR_PACKAGE_IDS:
|
||||||
|
if package_id not in manifests:
|
||||||
|
return _unverifiable_report("missing_package_manifest")
|
||||||
|
|
||||||
|
common_compatibility_fingerprint = None
|
||||||
|
for package_id in FOUR_PACKAGE_IDS:
|
||||||
|
package_manifest = manifests[package_id]
|
||||||
|
if type(package_manifest) is not dict:
|
||||||
|
return _unverifiable_report("package_manifest_not_exact_dict")
|
||||||
|
for field_name in package_manifest:
|
||||||
|
if type(field_name) is not str or field_name not in _REQUIRED_MANIFEST_FIELDS:
|
||||||
|
return _unverifiable_report("unexpected_manifest_field")
|
||||||
|
for field_name in _REQUIRED_MANIFEST_FIELDS:
|
||||||
|
if field_name not in package_manifest:
|
||||||
|
return _unverifiable_report("missing_manifest_field")
|
||||||
|
if type(package_manifest["schema"]) is not str or package_manifest["schema"] != FOUR_PACKAGE_MANIFEST_SCHEMA:
|
||||||
|
return _unverifiable_report("manifest_schema_mismatch")
|
||||||
|
if type(package_manifest["package_id"]) is not str or package_manifest["package_id"] != package_id:
|
||||||
|
return _unverifiable_report("manifest_package_id_mismatch")
|
||||||
|
version = package_manifest["manifest_version"]
|
||||||
|
if type(version) is not str or _MANIFEST_VERSION_PATTERN.fullmatch(version) is None:
|
||||||
|
return _unverifiable_report("manifest_version_invalid")
|
||||||
|
package_fingerprint = package_manifest["package_fingerprint"]
|
||||||
|
if type(package_fingerprint) is not str or _SHA256_PATTERN.fullmatch(package_fingerprint) is None:
|
||||||
|
return _unverifiable_report("package_fingerprint_invalid")
|
||||||
|
compatibility_fingerprint = package_manifest["compatibility_fingerprint"]
|
||||||
|
if type(compatibility_fingerprint) is not str or _SHA256_PATTERN.fullmatch(compatibility_fingerprint) is None:
|
||||||
|
return _unverifiable_report("compatibility_fingerprint_invalid")
|
||||||
|
if common_compatibility_fingerprint is None:
|
||||||
|
common_compatibility_fingerprint = compatibility_fingerprint
|
||||||
|
elif compatibility_fingerprint != common_compatibility_fingerprint:
|
||||||
|
return _unverifiable_report("compatibility_fingerprint_mismatch")
|
||||||
|
return _verified_report()
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"FOUR_PACKAGE_IDS",
|
||||||
|
"FOUR_PACKAGE_MANIFEST_REPORT_SCHEMA",
|
||||||
|
"FOUR_PACKAGE_MANIFEST_SCHEMA",
|
||||||
|
"manifest_contract",
|
||||||
|
"verify_four_package_manifests",
|
||||||
|
]
|
||||||
51
core/p6_readonly_projection.py
普通文件
51
core/p6_readonly_projection.py
普通文件
|
|
@ -0,0 +1,51 @@
|
||||||
|
"""P6 minimal read-only status projection."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
|
||||||
|
P6_READONLY_STATUS_SCHEMA = "ops.p6.read_only_status.v1"
|
||||||
|
_STATUS_FIELDS = ("profiles", "identity_links", "audit_events", "operations")
|
||||||
|
_HEALTH = frozenset({"ready", "degraded", "unverifiable"})
|
||||||
|
|
||||||
|
|
||||||
|
def _fingerprint() -> str:
|
||||||
|
payload = {"schema_version": P6_READONLY_STATUS_SCHEMA, "count_fields": _STATUS_FIELDS}
|
||||||
|
encoded = json.dumps(payload, ensure_ascii=True, separators=(",", ":"), sort_keys=True).encode("utf-8")
|
||||||
|
return hashlib.sha256(encoded).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
P6_READONLY_STATUS_FINGERPRINT = _fingerprint()
|
||||||
|
|
||||||
|
|
||||||
|
def _count(value: Any) -> int:
|
||||||
|
return value if type(value) is int and 0 <= value <= 10_000_000 else 0
|
||||||
|
|
||||||
|
|
||||||
|
def build_p6_readonly_status(status: Any, *, health: str = "ready", reason_code: str = "") -> dict[str, Any]:
|
||||||
|
"""Return bounded counts only; P4 and identity authority never crosses this boundary."""
|
||||||
|
status_available = type(status) is dict
|
||||||
|
if status_available:
|
||||||
|
for key in status:
|
||||||
|
if type(key) is not str:
|
||||||
|
status_available = False
|
||||||
|
break
|
||||||
|
source = status if status_available else {}
|
||||||
|
normalized_health = health if type(health) is str and health in _HEALTH else "unverifiable"
|
||||||
|
normalized_reason = reason_code if type(reason_code) is str and len(reason_code) <= 80 else "invalid_reason_code"
|
||||||
|
if not status_available:
|
||||||
|
normalized_health = "unverifiable"
|
||||||
|
normalized_reason = "registry_status_unavailable"
|
||||||
|
return {
|
||||||
|
"schema_version": P6_READONLY_STATUS_SCHEMA,
|
||||||
|
"source_plugin": "memory_companion",
|
||||||
|
"contract_fingerprint": P6_READONLY_STATUS_FINGERPRINT,
|
||||||
|
"health": normalized_health,
|
||||||
|
"reason_code": normalized_reason,
|
||||||
|
"counts": {field: _count(source.get(field)) for field in _STATUS_FIELDS},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = ["P6_READONLY_STATUS_SCHEMA", "P6_READONLY_STATUS_FINGERPRINT", "build_p6_readonly_status"]
|
||||||
530
core/provenance.py
普通文件
530
core/provenance.py
普通文件
|
|
@ -0,0 +1,530 @@
|
||||||
|
"""Pure chat-side provenance contract and in-memory migration projection.
|
||||||
|
|
||||||
|
The module accepts metadata only. It never reads or stores prompt text,
|
||||||
|
conversation content, media, credentials, paths, or arbitrary source prose,
|
||||||
|
and it performs no I/O. A later SQLite adapter may use the plans and CAS
|
||||||
|
results, but this module deliberately has no knowledge of that adapter.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import Iterable, Mapping
|
||||||
|
from copy import deepcopy
|
||||||
|
from dataclasses import asdict, is_dataclass
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
|
||||||
|
PROVENANCE_CONTRACT_NAME = "ops.p5.provenance.v1"
|
||||||
|
PROVENANCE_CONTRACT_VERSION = "1.0"
|
||||||
|
P3_CONTRACT_NAME = "ops.context_orchestration.v1"
|
||||||
|
P3_CONTRACT_VERSION = "1.0"
|
||||||
|
P3_CONTRACT_FINGERPRINT = "3bb7a12af05bb4d9a47cef9f31e78752cec512b90b1d50ae49feef54470974f8"
|
||||||
|
COMPANION_ATTESTATION_ISSUER = "private_companion"
|
||||||
|
ATTESTATION_SCHEMA_VERSION = "ops.p5.attestation.v1"
|
||||||
|
|
||||||
|
TRUST_LEVELS = ("T0", "T1", "T2", "T3", "T4")
|
||||||
|
PROVENANCE_STATES = ("observed", "legacy_unresolved", "owner_recovered", "invalid")
|
||||||
|
SOURCE_KINDS = (
|
||||||
|
"policy_config", "verified_authorization", "current_user_intent",
|
||||||
|
"forwarded_text", "quoted_text", "vision_summary", "tool_output",
|
||||||
|
"web_extract", "memory_recall", "derived_summary", "legacy_memory", "unknown",
|
||||||
|
)
|
||||||
|
FIREWALL_STATUSES = (
|
||||||
|
"allowed", "sanitized", "blocked", "rejected", "quarantined", "unavailable", "unknown",
|
||||||
|
)
|
||||||
|
DISPOSITIONS = ("allow", "shadow_quarantine", "deny_high_risk")
|
||||||
|
HASH_FORMAT = "sha256_hex_lower"
|
||||||
|
|
||||||
|
RECORD_FIELDS = (
|
||||||
|
"contract_name", "contract_version", "contract_fingerprint", "memory_id",
|
||||||
|
"source_kind", "source_trust", "firewall_status", "source_event_ref_hash",
|
||||||
|
"authority_attestation_ref_hash", "provenance_state", "migration_operation_ref",
|
||||||
|
"recovery_operation_ref", "record_revision",
|
||||||
|
)
|
||||||
|
OPERATION_FIELDS = (
|
||||||
|
"contract_name", "contract_version", "contract_fingerprint", "operation_kind",
|
||||||
|
"operation_ref_hash", "memory_id", "expected_revision", "before_record_digest",
|
||||||
|
"after_record_digest", "before_record", "after_record",
|
||||||
|
)
|
||||||
|
|
||||||
|
_SOURCE_KIND_SET = frozenset(SOURCE_KINDS)
|
||||||
|
_TRUST_SET = frozenset(TRUST_LEVELS)
|
||||||
|
_FIREWALL_SET = frozenset(FIREWALL_STATUSES)
|
||||||
|
_DISPOSITION_SET = frozenset(DISPOSITIONS)
|
||||||
|
_SINKS = frozenset({
|
||||||
|
"prompt_forward_quote", "prompt_vision_summary", "memory_recall",
|
||||||
|
"bridge_serialization", "tool_retrieval", "external_export", "cross_user_read",
|
||||||
|
})
|
||||||
|
_MEMORY_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,119}$")
|
||||||
|
_SHA256_RE = re.compile(r"^[0-9a-fA-F]{64}$")
|
||||||
|
_TOKEN_RE = re.compile(r"^[a-z][a-z0-9_]{0,63}$")
|
||||||
|
_FORBIDDEN_RAW_FIELDS = frozenset({
|
||||||
|
"body", "content", "text", "message", "prompt", "conversation", "media",
|
||||||
|
"raw_id", "source_id", "source_event_id", "event_id", "attestation_id",
|
||||||
|
"authority_attestation_id", "request_id", "session_id", "credential",
|
||||||
|
"credentials", "password", "secret", "token", "path", "absolute_path", "url",
|
||||||
|
})
|
||||||
|
_SNAPSHOT_FIELDS = frozenset({
|
||||||
|
"schema_version", "contract_name", "contract_version", "contract_fingerprint",
|
||||||
|
"issuer", "issuer_epoch", "p3_contract_name", "p3_contract_version",
|
||||||
|
"p3_contract_fingerprint", "source_kind", "source_trust", "trust", "firewall_status",
|
||||||
|
"source_event_ref_hash", "source_hash", "authority_attestation_ref_hash",
|
||||||
|
"attestation_ref_hash", "disposition", "reason_codes", "request_hash", "session_hash",
|
||||||
|
"derived_hash", "derived_from_ref_hash", "provenance_state", "sink",
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
def _canonical_json(value: Any) -> str:
|
||||||
|
return json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(",", ":"))
|
||||||
|
|
||||||
|
|
||||||
|
def _digest(value: Mapping[str, Any]) -> str:
|
||||||
|
return hashlib.sha256(_canonical_json(value).encode("utf-8")).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def contract_descriptor() -> dict[str, Any]:
|
||||||
|
"""Return a fresh, closed, JSON-safe descriptor."""
|
||||||
|
|
||||||
|
return {
|
||||||
|
"contract_name": PROVENANCE_CONTRACT_NAME,
|
||||||
|
"contract_version": PROVENANCE_CONTRACT_VERSION,
|
||||||
|
"record_fields": list(RECORD_FIELDS),
|
||||||
|
"provenance_states": list(PROVENANCE_STATES),
|
||||||
|
"trust_levels": list(TRUST_LEVELS),
|
||||||
|
"source_kinds": list(SOURCE_KINDS),
|
||||||
|
"firewall_statuses": list(FIREWALL_STATUSES),
|
||||||
|
"dispositions": list(DISPOSITIONS),
|
||||||
|
"hash_format": HASH_FORMAT,
|
||||||
|
"attestation_issuer": COMPANION_ATTESTATION_ISSUER,
|
||||||
|
"p3_contract_name": P3_CONTRACT_NAME,
|
||||||
|
"p3_contract_version": P3_CONTRACT_VERSION,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def contract_fingerprint() -> str:
|
||||||
|
"""Return the canonical descriptor SHA-256 fingerprint."""
|
||||||
|
|
||||||
|
return _digest(contract_descriptor())
|
||||||
|
|
||||||
|
|
||||||
|
provenance_contract_descriptor = contract_descriptor
|
||||||
|
provenance_contract_fingerprint = contract_fingerprint
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_memory_id(value: Any) -> str:
|
||||||
|
return value if isinstance(value, str) and _MEMORY_ID_RE.fullmatch(value) else ""
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_hash(value: Any) -> str:
|
||||||
|
return value if isinstance(value, str) and _SHA256_RE.fullmatch(value) and value == value.lower() else ""
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_hash(value: Any) -> str:
|
||||||
|
if not isinstance(value, str):
|
||||||
|
return ""
|
||||||
|
raw = value[7:] if value.startswith("sha256:") else value
|
||||||
|
return raw.lower() if _SHA256_RE.fullmatch(raw) else ""
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_revision(value: Any) -> int | None:
|
||||||
|
return value if isinstance(value, int) and not isinstance(value, bool) and value >= 0 else None
|
||||||
|
|
||||||
|
|
||||||
|
def _known(value: Any, allowed: frozenset[str] | tuple[str, ...]) -> bool:
|
||||||
|
return isinstance(value, str) and value in allowed
|
||||||
|
|
||||||
|
|
||||||
|
def _forbidden(value: Mapping[str, Any]) -> bool:
|
||||||
|
return any(key in value for key in _FORBIDDEN_RAW_FIELDS)
|
||||||
|
|
||||||
|
|
||||||
|
def _error_result(*codes: str) -> dict[str, Any]:
|
||||||
|
return {"ok": False, "error_codes": sorted(set(codes))}
|
||||||
|
|
||||||
|
|
||||||
|
def _blank_record(memory_id: Any = "", *, revision: int = 0, state: str = "invalid") -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"contract_name": PROVENANCE_CONTRACT_NAME,
|
||||||
|
"contract_version": PROVENANCE_CONTRACT_VERSION,
|
||||||
|
"contract_fingerprint": contract_fingerprint(),
|
||||||
|
"memory_id": _safe_memory_id(memory_id),
|
||||||
|
"source_kind": "unknown",
|
||||||
|
"source_trust": "T4",
|
||||||
|
"firewall_status": "unknown",
|
||||||
|
"source_event_ref_hash": "",
|
||||||
|
"authority_attestation_ref_hash": "",
|
||||||
|
"provenance_state": state,
|
||||||
|
"migration_operation_ref": "",
|
||||||
|
"recovery_operation_ref": "",
|
||||||
|
"record_revision": revision if _safe_revision(revision) is not None else 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def validate_provenance_record(record: Mapping[str, Any] | None) -> dict[str, Any]:
|
||||||
|
"""Return static validation errors or a deep-copied safe record.
|
||||||
|
|
||||||
|
Invalid input values are never returned, so a caller can safely serialize
|
||||||
|
the result without leaking hostile identifiers or source prose.
|
||||||
|
"""
|
||||||
|
|
||||||
|
if not isinstance(record, Mapping):
|
||||||
|
return _error_result("record_not_mapping")
|
||||||
|
errors: list[str] = []
|
||||||
|
if _forbidden(record):
|
||||||
|
errors.append("forbidden_raw_field")
|
||||||
|
if set(record) != set(RECORD_FIELDS):
|
||||||
|
errors.append("record_fields_mismatch")
|
||||||
|
if record.get("contract_name") != PROVENANCE_CONTRACT_NAME:
|
||||||
|
errors.append("contract_name_mismatch")
|
||||||
|
if record.get("contract_version") != PROVENANCE_CONTRACT_VERSION:
|
||||||
|
errors.append("contract_version_mismatch")
|
||||||
|
if record.get("contract_fingerprint") != contract_fingerprint():
|
||||||
|
errors.append("contract_fingerprint_mismatch")
|
||||||
|
if not _safe_memory_id(record.get("memory_id")):
|
||||||
|
errors.append("memory_id_invalid")
|
||||||
|
if not _known(record.get("source_kind"), _SOURCE_KIND_SET):
|
||||||
|
errors.append("source_kind_invalid")
|
||||||
|
if not _known(record.get("source_trust"), _TRUST_SET):
|
||||||
|
errors.append("source_trust_invalid")
|
||||||
|
if not _known(record.get("firewall_status"), _FIREWALL_SET):
|
||||||
|
errors.append("firewall_status_invalid")
|
||||||
|
if not _known(record.get("provenance_state"), PROVENANCE_STATES):
|
||||||
|
errors.append("provenance_state_invalid")
|
||||||
|
if _safe_revision(record.get("record_revision")) is None:
|
||||||
|
errors.append("record_revision_invalid")
|
||||||
|
|
||||||
|
source = record.get("source_event_ref_hash")
|
||||||
|
authority = record.get("authority_attestation_ref_hash")
|
||||||
|
source_hash = _safe_hash(source)
|
||||||
|
authority_hash = _safe_hash(authority)
|
||||||
|
if source != "" and not source_hash:
|
||||||
|
errors.append("source_event_ref_hash_invalid")
|
||||||
|
if authority != "" and not authority_hash:
|
||||||
|
errors.append("authority_attestation_ref_hash_invalid")
|
||||||
|
migration = record.get("migration_operation_ref")
|
||||||
|
recovery = record.get("recovery_operation_ref")
|
||||||
|
if migration != "" and not _safe_hash(migration):
|
||||||
|
errors.append("migration_operation_ref_invalid")
|
||||||
|
if recovery != "" and not _safe_hash(recovery):
|
||||||
|
errors.append("recovery_operation_ref_invalid")
|
||||||
|
|
||||||
|
state = record.get("provenance_state")
|
||||||
|
if state == "legacy_unresolved":
|
||||||
|
if (record.get("source_kind"), record.get("source_trust"), record.get("firewall_status")) != ("unknown", "T4", "unknown"):
|
||||||
|
errors.append("legacy_defaults_required")
|
||||||
|
if source != "" or authority != "":
|
||||||
|
errors.append("legacy_hashes_forbidden")
|
||||||
|
elif state in {"observed", "owner_recovered"}:
|
||||||
|
if record.get("source_kind") == "unknown":
|
||||||
|
errors.append("observed_source_kind_required")
|
||||||
|
if not source_hash or not authority_hash:
|
||||||
|
errors.append("attestation_hashes_required")
|
||||||
|
if source_hash and source_hash == authority_hash:
|
||||||
|
errors.append("attestation_hashes_conflict")
|
||||||
|
if state == "owner_recovered" and not _safe_hash(recovery):
|
||||||
|
errors.append("recovery_operation_ref_required")
|
||||||
|
elif state == "invalid" and (source_hash or authority_hash):
|
||||||
|
errors.append("invalid_hashes_forbidden")
|
||||||
|
if errors:
|
||||||
|
return _error_result(*errors)
|
||||||
|
return {"ok": True, "record": deepcopy(dict(record))}
|
||||||
|
|
||||||
|
|
||||||
|
def legacy_unresolved(memory_id: str, *, record_revision: int = 0) -> dict[str, Any]:
|
||||||
|
"""Represent a historical record without guessing its provenance."""
|
||||||
|
|
||||||
|
result = _blank_record(memory_id, revision=record_revision, state="legacy_unresolved")
|
||||||
|
return result if result["memory_id"] and validate_provenance_record(result)["ok"] else _blank_record(state="invalid")
|
||||||
|
|
||||||
|
|
||||||
|
def _snapshot_mapping(snapshot: Any) -> Mapping[str, Any] | None:
|
||||||
|
if isinstance(snapshot, Mapping):
|
||||||
|
return snapshot
|
||||||
|
if is_dataclass(snapshot):
|
||||||
|
value = asdict(snapshot)
|
||||||
|
return value if isinstance(value, Mapping) else None
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _paired_hash(snapshot: Mapping[str, Any], *keys: str) -> tuple[str, str]:
|
||||||
|
values = [_normalize_hash(snapshot[key]) for key in keys if key in snapshot]
|
||||||
|
if not values:
|
||||||
|
return "missing", ""
|
||||||
|
if not all(values):
|
||||||
|
return "invalid", ""
|
||||||
|
return ("present", values[0]) if len(set(values)) == 1 else ("conflict", "")
|
||||||
|
|
||||||
|
|
||||||
|
def _paired_label(snapshot: Mapping[str, Any], allowed: frozenset[str], *keys: str) -> tuple[str, str]:
|
||||||
|
values = [snapshot[key] for key in keys if key in snapshot]
|
||||||
|
if not values:
|
||||||
|
return "missing", ""
|
||||||
|
if not all(_known(value, allowed) for value in values):
|
||||||
|
return "invalid", ""
|
||||||
|
return ("present", values[0]) if len(set(values)) == 1 else ("conflict", "")
|
||||||
|
|
||||||
|
|
||||||
|
def _snapshot_safe(snapshot: Mapping[str, Any]) -> bool:
|
||||||
|
if set(snapshot) - _SNAPSHOT_FIELDS or _forbidden(snapshot):
|
||||||
|
return False
|
||||||
|
if not _known(snapshot.get("disposition"), _DISPOSITION_SET):
|
||||||
|
return False
|
||||||
|
codes = snapshot.get("reason_codes", ())
|
||||||
|
if not isinstance(codes, (list, tuple)) or len(codes) > 16:
|
||||||
|
return False
|
||||||
|
if not all(isinstance(code, str) and _TOKEN_RE.fullmatch(code) for code in codes):
|
||||||
|
return False
|
||||||
|
for key in ("request_hash", "session_hash", "issuer_epoch"):
|
||||||
|
if not _normalize_hash(snapshot.get(key)):
|
||||||
|
return False
|
||||||
|
derived = [snapshot[key] for key in ("derived_hash", "derived_from_ref_hash") if key in snapshot and snapshot[key] != ""]
|
||||||
|
if derived and (any(not _normalize_hash(value) for value in derived) or len({_normalize_hash(value) for value in derived}) != 1):
|
||||||
|
return False
|
||||||
|
return snapshot.get("provenance_state") == "observed" and _known(snapshot.get("sink"), _SINKS)
|
||||||
|
|
||||||
|
|
||||||
|
def observed_from_companion_snapshot(memory_id: str, snapshot: Any, *, record_revision: int = 0) -> dict[str, Any]:
|
||||||
|
"""Create ``observed`` only from a complete, attested Companion snapshot."""
|
||||||
|
|
||||||
|
safe_id = _safe_memory_id(memory_id)
|
||||||
|
revision = _safe_revision(record_revision)
|
||||||
|
data = _snapshot_mapping(snapshot)
|
||||||
|
if not safe_id or revision is None or data is None or not _snapshot_safe(data):
|
||||||
|
return _blank_record(safe_id, revision=revision or 0)
|
||||||
|
expected = {
|
||||||
|
"schema_version": ATTESTATION_SCHEMA_VERSION,
|
||||||
|
"issuer": COMPANION_ATTESTATION_ISSUER,
|
||||||
|
"contract_name": PROVENANCE_CONTRACT_NAME,
|
||||||
|
"contract_version": PROVENANCE_CONTRACT_VERSION,
|
||||||
|
"contract_fingerprint": contract_fingerprint(),
|
||||||
|
"p3_contract_name": P3_CONTRACT_NAME,
|
||||||
|
"p3_contract_version": P3_CONTRACT_VERSION,
|
||||||
|
"p3_contract_fingerprint": P3_CONTRACT_FINGERPRINT,
|
||||||
|
}
|
||||||
|
if any(data.get(key) != value for key, value in expected.items()):
|
||||||
|
return _blank_record(safe_id, revision=revision)
|
||||||
|
source_status, source_hash = _paired_hash(data, "source_event_ref_hash", "source_hash")
|
||||||
|
authority_status, authority_hash = _paired_hash(data, "authority_attestation_ref_hash", "attestation_ref_hash")
|
||||||
|
trust_status, trust = _paired_label(data, _TRUST_SET, "source_trust", "trust")
|
||||||
|
source_kind = data.get("source_kind")
|
||||||
|
firewall = data.get("firewall_status")
|
||||||
|
if (
|
||||||
|
source_status != "present" or authority_status != "present" or trust_status != "present"
|
||||||
|
or source_hash == authority_hash or not _known(source_kind, _SOURCE_KIND_SET - {"unknown"})
|
||||||
|
or not _known(firewall, _FIREWALL_SET)
|
||||||
|
):
|
||||||
|
return _blank_record(safe_id, revision=revision)
|
||||||
|
record = _blank_record(safe_id, revision=revision, state="observed")
|
||||||
|
record.update({
|
||||||
|
"source_kind": source_kind, "source_trust": trust, "firewall_status": firewall,
|
||||||
|
"source_event_ref_hash": source_hash, "authority_attestation_ref_hash": authority_hash,
|
||||||
|
})
|
||||||
|
return record if validate_provenance_record(record)["ok"] else _blank_record(safe_id, revision=revision)
|
||||||
|
|
||||||
|
|
||||||
|
def provenance_record_digest(record: Mapping[str, Any] | None) -> str:
|
||||||
|
checked = validate_provenance_record(record)
|
||||||
|
return _digest(checked["record"]) if checked["ok"] else ""
|
||||||
|
|
||||||
|
|
||||||
|
def _record_or_none(value: Any) -> dict[str, Any] | None:
|
||||||
|
checked = validate_provenance_record(value if isinstance(value, Mapping) else None)
|
||||||
|
return deepcopy(checked["record"]) if checked["ok"] else None
|
||||||
|
|
||||||
|
|
||||||
|
def _operation(*, operation_kind: str, operation_ref_hash: str, before_record: Mapping[str, Any] | None, after_record: Mapping[str, Any]) -> dict[str, Any] | None:
|
||||||
|
before = _record_or_none(before_record)
|
||||||
|
after = _record_or_none(after_record)
|
||||||
|
reference = _safe_hash(operation_ref_hash)
|
||||||
|
if operation_kind not in {"migration", "recovery"} or not reference or after is None:
|
||||||
|
return None
|
||||||
|
if before is not None and before["memory_id"] != after["memory_id"]:
|
||||||
|
return None
|
||||||
|
expected = before["record_revision"] if before is not None else after["record_revision"] - 1
|
||||||
|
if expected < 0 or after["record_revision"] != expected + 1:
|
||||||
|
return None
|
||||||
|
operation = {
|
||||||
|
"contract_name": PROVENANCE_CONTRACT_NAME, "contract_version": PROVENANCE_CONTRACT_VERSION,
|
||||||
|
"contract_fingerprint": contract_fingerprint(), "operation_kind": operation_kind,
|
||||||
|
"operation_ref_hash": reference, "memory_id": after["memory_id"], "expected_revision": expected,
|
||||||
|
"before_record_digest": _digest(before) if before is not None else "",
|
||||||
|
"after_record_digest": _digest(after), "before_record": before, "after_record": after,
|
||||||
|
}
|
||||||
|
return operation if validate_operation(operation)["ok"] else None
|
||||||
|
|
||||||
|
|
||||||
|
def validate_operation(operation: Mapping[str, Any] | None) -> dict[str, Any]:
|
||||||
|
if not isinstance(operation, Mapping):
|
||||||
|
return _error_result("operation_not_mapping")
|
||||||
|
errors: list[str] = []
|
||||||
|
if _forbidden(operation):
|
||||||
|
errors.append("forbidden_raw_field")
|
||||||
|
if set(operation) != set(OPERATION_FIELDS):
|
||||||
|
errors.append("operation_fields_mismatch")
|
||||||
|
if operation.get("contract_name") != PROVENANCE_CONTRACT_NAME:
|
||||||
|
errors.append("contract_name_mismatch")
|
||||||
|
if operation.get("contract_version") != PROVENANCE_CONTRACT_VERSION:
|
||||||
|
errors.append("contract_version_mismatch")
|
||||||
|
if operation.get("contract_fingerprint") != contract_fingerprint():
|
||||||
|
errors.append("contract_fingerprint_mismatch")
|
||||||
|
if operation.get("operation_kind") not in {"migration", "recovery"}:
|
||||||
|
errors.append("operation_kind_invalid")
|
||||||
|
if not _safe_hash(operation.get("operation_ref_hash")):
|
||||||
|
errors.append("operation_ref_invalid")
|
||||||
|
if not _safe_memory_id(operation.get("memory_id")):
|
||||||
|
errors.append("memory_id_invalid")
|
||||||
|
expected = _safe_revision(operation.get("expected_revision"))
|
||||||
|
if expected is None:
|
||||||
|
errors.append("expected_revision_invalid")
|
||||||
|
before = _record_or_none(operation.get("before_record"))
|
||||||
|
after = _record_or_none(operation.get("after_record"))
|
||||||
|
if operation.get("before_record") is not None and before is None:
|
||||||
|
errors.append("before_record_invalid")
|
||||||
|
if after is None:
|
||||||
|
errors.append("after_record_invalid")
|
||||||
|
if before is None and operation.get("before_record_digest") != "":
|
||||||
|
errors.append("before_digest_required_empty")
|
||||||
|
if before is not None and operation.get("before_record_digest") != _digest(before):
|
||||||
|
errors.append("before_digest_mismatch")
|
||||||
|
if after is not None and operation.get("after_record_digest") != _digest(after):
|
||||||
|
errors.append("after_digest_mismatch")
|
||||||
|
if after is not None:
|
||||||
|
if operation.get("memory_id") != after["memory_id"]:
|
||||||
|
errors.append("memory_id_mismatch")
|
||||||
|
if expected is not None and after["record_revision"] != expected + 1:
|
||||||
|
errors.append("revision_progression_invalid")
|
||||||
|
ref_field = "migration_operation_ref" if operation.get("operation_kind") == "migration" else "recovery_operation_ref"
|
||||||
|
if after.get(ref_field) != operation.get("operation_ref_hash"):
|
||||||
|
errors.append("operation_ref_not_bound")
|
||||||
|
if before is not None and after is not None:
|
||||||
|
if before["memory_id"] != after["memory_id"]:
|
||||||
|
errors.append("before_after_memory_mismatch")
|
||||||
|
if expected is not None and before["record_revision"] != expected:
|
||||||
|
errors.append("before_revision_mismatch")
|
||||||
|
return _error_result(*errors) if errors else {"ok": True, "operation": deepcopy(dict(operation))}
|
||||||
|
|
||||||
|
|
||||||
|
def plan_legacy_migration(records: Iterable[Mapping[str, Any]], *, operation_ref_hash: str) -> dict[str, Any]:
|
||||||
|
"""Return a non-mutating preview for unresolved legacy records."""
|
||||||
|
|
||||||
|
reference = _safe_hash(operation_ref_hash)
|
||||||
|
result: dict[str, Any] = {
|
||||||
|
"mode": "preview", "readonly": True, "write_count": 0,
|
||||||
|
"operation_ref_hash": reference, "operations": [], "skipped": [], "error_codes": [],
|
||||||
|
}
|
||||||
|
if not reference:
|
||||||
|
result["error_codes"].append("operation_ref_invalid")
|
||||||
|
return result
|
||||||
|
if isinstance(records, (str, bytes)) or not isinstance(records, Iterable):
|
||||||
|
result["error_codes"].append("records_not_iterable")
|
||||||
|
return result
|
||||||
|
for candidate in records:
|
||||||
|
if not isinstance(candidate, Mapping) or _forbidden(candidate):
|
||||||
|
result["error_codes"].append("candidate_invalid")
|
||||||
|
continue
|
||||||
|
existing = _record_or_none(candidate)
|
||||||
|
if existing is not None:
|
||||||
|
result["skipped"].append({"memory_id": existing["memory_id"], "reason_code": "already_provenanced"})
|
||||||
|
continue
|
||||||
|
if set(candidate) != {"memory_id", "record_revision"}:
|
||||||
|
result["error_codes"].append("candidate_fields_mismatch")
|
||||||
|
continue
|
||||||
|
memory_id = _safe_memory_id(candidate.get("memory_id"))
|
||||||
|
revision = _safe_revision(candidate.get("record_revision"))
|
||||||
|
if not memory_id or revision is None:
|
||||||
|
result["error_codes"].append("candidate_invalid")
|
||||||
|
continue
|
||||||
|
after = legacy_unresolved(memory_id, record_revision=revision + 1)
|
||||||
|
after["migration_operation_ref"] = reference
|
||||||
|
operation = _operation(operation_kind="migration", operation_ref_hash=reference, before_record=None, after_record=after)
|
||||||
|
if operation is None:
|
||||||
|
result["error_codes"].append("operation_invalid")
|
||||||
|
else:
|
||||||
|
result["operations"].append(operation)
|
||||||
|
result["error_codes"] = sorted(set(result["error_codes"]))
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _minimal_current(current: Mapping[str, Any] | None) -> tuple[str, int | None, dict[str, Any] | None, str]:
|
||||||
|
if not isinstance(current, Mapping) or _forbidden(current):
|
||||||
|
return "", None, None, "current_invalid"
|
||||||
|
record = _record_or_none(current)
|
||||||
|
if record is not None:
|
||||||
|
return record["memory_id"], record["record_revision"], record, ""
|
||||||
|
if set(current) != {"memory_id", "record_revision"}:
|
||||||
|
return "", None, None, "current_fields_mismatch"
|
||||||
|
return _safe_memory_id(current.get("memory_id")), _safe_revision(current.get("record_revision")), None, ""
|
||||||
|
|
||||||
|
|
||||||
|
def apply_planned_operation(current: Mapping[str, Any] | None, operation: Mapping[str, Any] | None) -> dict[str, Any]:
|
||||||
|
"""Apply a plan to an in-memory mapping with exact revision CAS."""
|
||||||
|
|
||||||
|
checked = validate_operation(operation)
|
||||||
|
if not checked["ok"]:
|
||||||
|
return {"ok": False, "mode": "apply", "status": "invalid_operation", "error_codes": checked["error_codes"]}
|
||||||
|
op = checked["operation"]
|
||||||
|
memory_id, revision, current_record, error = _minimal_current(current)
|
||||||
|
if error or not memory_id or revision is None:
|
||||||
|
return {"ok": False, "mode": "apply", "status": "invalid_current", "error_codes": [error or "current_invalid"]}
|
||||||
|
if current_record is not None and _digest(current_record) == op["after_record_digest"]:
|
||||||
|
return {"ok": True, "mode": "apply", "status": "idempotent", "record": deepcopy(op["after_record"]), "changed": False}
|
||||||
|
if memory_id != op["memory_id"] or revision != op["expected_revision"]:
|
||||||
|
return {"ok": False, "mode": "apply", "status": "revision_conflict", "error_codes": ["revision_or_memory_mismatch"]}
|
||||||
|
before = op["before_record"]
|
||||||
|
if before is None:
|
||||||
|
if current_record is not None:
|
||||||
|
return {"ok": False, "mode": "apply", "status": "revision_conflict", "error_codes": ["unexpected_existing_provenance"]}
|
||||||
|
elif current_record is None or _digest(current_record) != op["before_record_digest"]:
|
||||||
|
return {"ok": False, "mode": "apply", "status": "revision_conflict", "error_codes": ["before_record_mismatch"]}
|
||||||
|
return {"ok": True, "mode": "apply", "status": "applied", "record": deepcopy(op["after_record"]), "changed": True}
|
||||||
|
|
||||||
|
|
||||||
|
def rollback_planned_operation(current: Mapping[str, Any] | None, operation: Mapping[str, Any] | None) -> dict[str, Any]:
|
||||||
|
"""Rollback only when the current record still matches the plan's CAS."""
|
||||||
|
|
||||||
|
checked = validate_operation(operation)
|
||||||
|
if not checked["ok"]:
|
||||||
|
return {"ok": False, "mode": "rollback", "status": "invalid_operation", "error_codes": checked["error_codes"]}
|
||||||
|
op = checked["operation"]
|
||||||
|
memory_id, revision, current_record, error = _minimal_current(current)
|
||||||
|
if error or current_record is None or revision is None:
|
||||||
|
return {"ok": False, "mode": "rollback", "status": "invalid_current", "error_codes": [error or "current_invalid"]}
|
||||||
|
if memory_id != op["memory_id"] or revision != op["after_record"]["record_revision"] or _digest(current_record) != op["after_record_digest"]:
|
||||||
|
return {"ok": False, "mode": "rollback", "status": "revision_conflict", "error_codes": ["concurrent_update_protected"]}
|
||||||
|
before = op["before_record"]
|
||||||
|
return {"ok": True, "mode": "rollback", "status": "rolled_back", "record": deepcopy(before) if before is not None else None, "removed": before is None, "changed": True}
|
||||||
|
|
||||||
|
|
||||||
|
def plan_owner_recovery(current: Mapping[str, Any], snapshot: Mapping[str, Any], *, recovery_operation_ref_hash: str) -> dict[str, Any]:
|
||||||
|
"""Plan attested owner recovery for one legacy-unresolved record."""
|
||||||
|
|
||||||
|
existing = _record_or_none(current)
|
||||||
|
reference = _safe_hash(recovery_operation_ref_hash)
|
||||||
|
if existing is None or existing["provenance_state"] != "legacy_unresolved" or not reference:
|
||||||
|
return {"ok": False, "mode": "preview", "error_codes": ["recovery_precondition_failed"]}
|
||||||
|
after = observed_from_companion_snapshot(existing["memory_id"], snapshot, record_revision=existing["record_revision"] + 1)
|
||||||
|
if after["provenance_state"] != "observed":
|
||||||
|
return {"ok": False, "mode": "preview", "error_codes": ["companion_snapshot_invalid"]}
|
||||||
|
after["provenance_state"] = "owner_recovered"
|
||||||
|
after["migration_operation_ref"] = existing["migration_operation_ref"]
|
||||||
|
after["recovery_operation_ref"] = reference
|
||||||
|
operation = _operation(operation_kind="recovery", operation_ref_hash=reference, before_record=existing, after_record=after)
|
||||||
|
if operation is None:
|
||||||
|
return {"ok": False, "mode": "preview", "error_codes": ["operation_invalid"]}
|
||||||
|
return {"ok": True, "mode": "preview", "readonly": True, "write_count": 0, "operation": operation}
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"ATTESTATION_SCHEMA_VERSION", "COMPANION_ATTESTATION_ISSUER", "DISPOSITIONS",
|
||||||
|
"FIREWALL_STATUSES", "HASH_FORMAT", "OPERATION_FIELDS", "P3_CONTRACT_FINGERPRINT",
|
||||||
|
"P3_CONTRACT_NAME", "P3_CONTRACT_VERSION", "PROVENANCE_CONTRACT_NAME",
|
||||||
|
"PROVENANCE_CONTRACT_VERSION", "PROVENANCE_STATES", "RECORD_FIELDS", "SOURCE_KINDS",
|
||||||
|
"TRUST_LEVELS", "apply_planned_operation", "contract_descriptor", "contract_fingerprint",
|
||||||
|
"legacy_unresolved", "observed_from_companion_snapshot", "plan_legacy_migration",
|
||||||
|
"plan_owner_recovery", "provenance_contract_descriptor", "provenance_contract_fingerprint",
|
||||||
|
"provenance_record_digest", "rollback_planned_operation", "validate_operation",
|
||||||
|
"validate_provenance_record",
|
||||||
|
]
|
||||||
280
core/provenance_store.py
普通文件
280
core/provenance_store.py
普通文件
|
|
@ -0,0 +1,280 @@
|
||||||
|
"""Small append-only provenance ledger for the chat-side memory plugin.
|
||||||
|
|
||||||
|
The ledger stores only validated provenance records and migration audit
|
||||||
|
metadata. It never accepts prompt text, conversation content, media,
|
||||||
|
credentials, or arbitrary source prose. Writes are atomic and every mutation
|
||||||
|
creates a backup before the current projection changes.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from copy import deepcopy
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import shutil
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from typing import Any, Mapping
|
||||||
|
|
||||||
|
from .provenance import (
|
||||||
|
apply_planned_operation,
|
||||||
|
plan_legacy_migration,
|
||||||
|
provenance_record_digest,
|
||||||
|
rollback_planned_operation,
|
||||||
|
validate_operation,
|
||||||
|
validate_provenance_record,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
LEDGER_SCHEMA_VERSION = "ops.p5.provenance.ledger.v1"
|
||||||
|
|
||||||
|
|
||||||
|
class ProvenanceLedger:
|
||||||
|
"""Persist validated provenance projections with CAS-protected writes."""
|
||||||
|
|
||||||
|
def __init__(self, path: Path):
|
||||||
|
self.path = Path(path)
|
||||||
|
self._lock = threading.RLock()
|
||||||
|
|
||||||
|
def _empty(self) -> dict[str, Any]:
|
||||||
|
return {"schema_version": LEDGER_SCHEMA_VERSION, "records": {}, "operations": [], "observations": []}
|
||||||
|
|
||||||
|
def _load_locked(self) -> dict[str, Any]:
|
||||||
|
if not self.path.is_file():
|
||||||
|
return self._empty()
|
||||||
|
try:
|
||||||
|
raw = json.loads(self.path.read_text(encoding="utf-8"))
|
||||||
|
except (OSError, ValueError, TypeError):
|
||||||
|
return self._empty()
|
||||||
|
if not isinstance(raw, dict) or raw.get("schema_version") != LEDGER_SCHEMA_VERSION:
|
||||||
|
return self._empty()
|
||||||
|
records: dict[str, dict[str, Any]] = {}
|
||||||
|
raw_records = raw.get("records")
|
||||||
|
if isinstance(raw_records, dict):
|
||||||
|
for memory_id, value in raw_records.items():
|
||||||
|
checked = validate_provenance_record(value if isinstance(value, Mapping) else None)
|
||||||
|
if checked.get("ok") and checked.get("record", {}).get("memory_id") == memory_id:
|
||||||
|
records[memory_id] = deepcopy(checked["record"])
|
||||||
|
operations: list[dict[str, Any]] = []
|
||||||
|
raw_operations = raw.get("operations")
|
||||||
|
if isinstance(raw_operations, list):
|
||||||
|
for value in raw_operations:
|
||||||
|
checked = validate_operation(value if isinstance(value, Mapping) else None)
|
||||||
|
if checked.get("ok"):
|
||||||
|
operations.append(deepcopy(checked["operation"]))
|
||||||
|
elif isinstance(value, dict) and value.get("kind") == "rollback":
|
||||||
|
safe = self._safe_rollback_audit(value)
|
||||||
|
if safe is not None:
|
||||||
|
operations.append(safe)
|
||||||
|
observations: list[dict[str, Any]] = []
|
||||||
|
raw_observations = raw.get("observations")
|
||||||
|
if isinstance(raw_observations, list):
|
||||||
|
for value in raw_observations:
|
||||||
|
safe = self._safe_observation(value)
|
||||||
|
if safe is not None:
|
||||||
|
observations.append(safe)
|
||||||
|
return {
|
||||||
|
"schema_version": LEDGER_SCHEMA_VERSION,
|
||||||
|
"records": records,
|
||||||
|
"operations": operations,
|
||||||
|
"observations": observations,
|
||||||
|
}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _safe_observation(value: Any) -> dict[str, Any] | None:
|
||||||
|
if not isinstance(value, Mapping) or set(value) != {
|
||||||
|
"memory_id", "record_digest", "record_revision", "source_event_ref_hash",
|
||||||
|
"authority_attestation_ref_hash", "provenance_state",
|
||||||
|
}:
|
||||||
|
return None
|
||||||
|
if (
|
||||||
|
not isinstance(value.get("memory_id"), str)
|
||||||
|
or not value["memory_id"]
|
||||||
|
or not isinstance(value.get("record_digest"), str)
|
||||||
|
or len(value["record_digest"]) != 64
|
||||||
|
or not isinstance(value.get("source_event_ref_hash"), str)
|
||||||
|
or len(value["source_event_ref_hash"]) != 64
|
||||||
|
or not isinstance(value.get("authority_attestation_ref_hash"), str)
|
||||||
|
or len(value["authority_attestation_ref_hash"]) != 64
|
||||||
|
or not isinstance(value.get("record_revision"), int)
|
||||||
|
or value["record_revision"] < 1
|
||||||
|
or value.get("provenance_state") not in {"observed", "owner_recovered"}
|
||||||
|
):
|
||||||
|
return None
|
||||||
|
return {
|
||||||
|
"memory_id": value["memory_id"][:120],
|
||||||
|
"record_digest": value["record_digest"].lower(),
|
||||||
|
"record_revision": value["record_revision"],
|
||||||
|
"source_event_ref_hash": value["source_event_ref_hash"].lower(),
|
||||||
|
"authority_attestation_ref_hash": value["authority_attestation_ref_hash"].lower(),
|
||||||
|
"provenance_state": value["provenance_state"],
|
||||||
|
}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _safe_rollback_audit(value: Mapping[str, Any]) -> dict[str, Any] | None:
|
||||||
|
memory_id = value.get("memory_id")
|
||||||
|
before_digest = value.get("before_digest")
|
||||||
|
after_digest = value.get("after_digest")
|
||||||
|
from_revision = value.get("from_revision")
|
||||||
|
to_revision = value.get("to_revision")
|
||||||
|
if (
|
||||||
|
not isinstance(memory_id, str)
|
||||||
|
or not memory_id
|
||||||
|
or not isinstance(before_digest, str)
|
||||||
|
or len(before_digest) != 64
|
||||||
|
or not isinstance(after_digest, str)
|
||||||
|
or len(after_digest) != 64
|
||||||
|
or not isinstance(from_revision, int)
|
||||||
|
or from_revision < 0
|
||||||
|
or not isinstance(to_revision, int)
|
||||||
|
or to_revision < 0
|
||||||
|
):
|
||||||
|
return None
|
||||||
|
return {
|
||||||
|
"kind": "rollback",
|
||||||
|
"memory_id": memory_id[:120],
|
||||||
|
"before_digest": before_digest.lower(),
|
||||||
|
"after_digest": after_digest.lower(),
|
||||||
|
"from_revision": from_revision,
|
||||||
|
"to_revision": to_revision,
|
||||||
|
}
|
||||||
|
|
||||||
|
def _write_locked(self, document: Mapping[str, Any]) -> None:
|
||||||
|
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
temporary = self.path.with_name(f".{self.path.name}.{threading.get_ident()}.tmp")
|
||||||
|
temporary.write_text(
|
||||||
|
json.dumps(document, ensure_ascii=True, sort_keys=True, separators=(",", ":")),
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
temporary.replace(self.path)
|
||||||
|
|
||||||
|
def _backup_locked(self) -> bool:
|
||||||
|
if not self.path.is_file():
|
||||||
|
return False
|
||||||
|
backup = self.path.with_name(f"{self.path.name}.backup.{time.time_ns()}")
|
||||||
|
try:
|
||||||
|
shutil.copy2(self.path, backup)
|
||||||
|
return True
|
||||||
|
except OSError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _minimal_current(memory_id: str, record: Mapping[str, Any] | None) -> dict[str, Any]:
|
||||||
|
if isinstance(record, Mapping):
|
||||||
|
return deepcopy(dict(record))
|
||||||
|
return {"memory_id": memory_id, "record_revision": 0}
|
||||||
|
|
||||||
|
def snapshot(self) -> dict[str, Any]:
|
||||||
|
with self._lock:
|
||||||
|
document = self._load_locked()
|
||||||
|
return {
|
||||||
|
"schema_version": LEDGER_SCHEMA_VERSION,
|
||||||
|
"records": deepcopy(document["records"]),
|
||||||
|
"operation_count": len(document["operations"]),
|
||||||
|
"observation_count": len(document["observations"]),
|
||||||
|
"path_present": self.path.is_file(),
|
||||||
|
}
|
||||||
|
|
||||||
|
def preview_legacy(self, candidates: list[Mapping[str, Any]], *, operation_ref_hash: str) -> dict[str, Any]:
|
||||||
|
return plan_legacy_migration(candidates, operation_ref_hash=operation_ref_hash)
|
||||||
|
|
||||||
|
def backup(self) -> dict[str, Any]:
|
||||||
|
with self._lock:
|
||||||
|
if not self.path.is_file():
|
||||||
|
return {"ok": True, "state": "nothing_to_backup", "created": False}
|
||||||
|
created = self._backup_locked()
|
||||||
|
return {"ok": created, "state": "backed_up" if created else "degraded", "created": created}
|
||||||
|
|
||||||
|
def apply(self, operation: Mapping[str, Any]) -> dict[str, Any]:
|
||||||
|
checked = validate_operation(operation)
|
||||||
|
if not checked.get("ok"):
|
||||||
|
return {"ok": False, "state": "invalid", "error_codes": checked.get("error_codes", [])}
|
||||||
|
op = checked["operation"]
|
||||||
|
with self._lock:
|
||||||
|
document = self._load_locked()
|
||||||
|
current = self._minimal_current(op["memory_id"], document["records"].get(op["memory_id"]))
|
||||||
|
result = apply_planned_operation(current, op)
|
||||||
|
if not result.get("ok") or not result.get("changed"):
|
||||||
|
return {**result, "backup_created": False}
|
||||||
|
backup_created = self._backup_locked()
|
||||||
|
document["records"][op["memory_id"]] = deepcopy(result["record"])
|
||||||
|
document["operations"].append(deepcopy(op))
|
||||||
|
self._write_locked(document)
|
||||||
|
return {**result, "backup_created": backup_created, "operation_count": len(document["operations"])}
|
||||||
|
|
||||||
|
def rollback(self, operation: Mapping[str, Any]) -> dict[str, Any]:
|
||||||
|
checked = validate_operation(operation)
|
||||||
|
if not checked.get("ok"):
|
||||||
|
return {"ok": False, "state": "invalid", "error_codes": checked.get("error_codes", [])}
|
||||||
|
op = checked["operation"]
|
||||||
|
with self._lock:
|
||||||
|
document = self._load_locked()
|
||||||
|
current = document["records"].get(op["memory_id"])
|
||||||
|
result = rollback_planned_operation(current, op)
|
||||||
|
if not result.get("ok"):
|
||||||
|
return {**result, "backup_created": False}
|
||||||
|
backup_created = self._backup_locked()
|
||||||
|
if result.get("removed"):
|
||||||
|
document["records"].pop(op["memory_id"], None)
|
||||||
|
else:
|
||||||
|
document["records"][op["memory_id"]] = deepcopy(result["record"])
|
||||||
|
document["operations"].append(
|
||||||
|
{
|
||||||
|
"kind": "rollback",
|
||||||
|
"memory_id": op["memory_id"],
|
||||||
|
"before_digest": op["after_record_digest"],
|
||||||
|
"after_digest": provenance_record_digest(result.get("record")) if result.get("record") else "0" * 64,
|
||||||
|
"from_revision": op["after_record"]["record_revision"],
|
||||||
|
"to_revision": result.get("record", {}).get("record_revision", 0) if result.get("record") else 0,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
self._write_locked(document)
|
||||||
|
return {**result, "backup_created": backup_created, "operation_count": len(document["operations"])}
|
||||||
|
|
||||||
|
def record_observed(self, memory_ids: list[str], snapshot: Any) -> dict[str, Any]:
|
||||||
|
"""Append observed metadata for selected memories without raw payloads."""
|
||||||
|
|
||||||
|
from .provenance import observed_from_companion_snapshot
|
||||||
|
|
||||||
|
safe_ids = [item for item in memory_ids if isinstance(item, str) and item][:64]
|
||||||
|
if not safe_ids:
|
||||||
|
return {"ok": False, "state": "invalid", "error_code": "memory_ids_empty", "written": 0}
|
||||||
|
with self._lock:
|
||||||
|
document = self._load_locked()
|
||||||
|
updates: dict[str, dict[str, Any]] = {}
|
||||||
|
for memory_id in safe_ids:
|
||||||
|
current = document["records"].get(memory_id)
|
||||||
|
revision = int(current.get("record_revision", 0)) if isinstance(current, dict) else 0
|
||||||
|
record = observed_from_companion_snapshot(memory_id, snapshot, record_revision=revision + 1)
|
||||||
|
checked = validate_provenance_record(record)
|
||||||
|
if not checked.get("ok"):
|
||||||
|
continue
|
||||||
|
if isinstance(current, dict) and current == checked["record"]:
|
||||||
|
continue
|
||||||
|
updates[memory_id] = deepcopy(checked["record"])
|
||||||
|
if not updates:
|
||||||
|
return {"ok": True, "state": "deduplicated", "written": 0, "backup_created": False}
|
||||||
|
backup_created = self._backup_locked()
|
||||||
|
document["records"].update(updates)
|
||||||
|
for record in updates.values():
|
||||||
|
document["observations"].append(
|
||||||
|
{
|
||||||
|
"memory_id": record["memory_id"],
|
||||||
|
"record_digest": provenance_record_digest(record),
|
||||||
|
"record_revision": record["record_revision"],
|
||||||
|
"source_event_ref_hash": record["source_event_ref_hash"],
|
||||||
|
"authority_attestation_ref_hash": record["authority_attestation_ref_hash"],
|
||||||
|
"provenance_state": record["provenance_state"],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
self._write_locked(document)
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"state": "written",
|
||||||
|
"written": len(updates),
|
||||||
|
"memory_ids": list(updates),
|
||||||
|
"backup_created": backup_created,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = ["LEDGER_SCHEMA_VERSION", "ProvenanceLedger"]
|
||||||
|
|
@ -16,6 +16,7 @@ from .visibility import VisibilityPolicy
|
||||||
|
|
||||||
|
|
||||||
class RetrievalEngine:
|
class RetrievalEngine:
|
||||||
|
DEFAULT_MATERIALIZE_LIMIT = 2000
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
store: MemoryStore,
|
store: MemoryStore,
|
||||||
|
|
@ -900,7 +901,11 @@ class RetrievalEngine:
|
||||||
)
|
)
|
||||||
expanded_terms = self._merge_terms(terms, graph_terms)
|
expanded_terms = self._merge_terms(terms, graph_terms)
|
||||||
include_pending = not self.policy.hide_pending_review
|
include_pending = not self.policy.hide_pending_review
|
||||||
ranked_candidates = await self.store.list_candidate_memories(limit=2000, include_pending=include_pending)
|
# Keep the broad priority scan explicitly bounded.
|
||||||
|
ranked_candidates = await self.store.list_candidate_memories(
|
||||||
|
limit=self.DEFAULT_MATERIALIZE_LIMIT,
|
||||||
|
include_pending=include_pending,
|
||||||
|
)
|
||||||
current_window_candidates = await self.store.list_current_window_candidate_memories(
|
current_window_candidates = await self.store.list_current_window_candidate_memories(
|
||||||
scope=ctx.scope,
|
scope=ctx.scope,
|
||||||
session_id=ctx.session_id,
|
session_id=ctx.session_id,
|
||||||
|
|
|
||||||
536
core/service.py
536
core/service.py
|
|
@ -1,6 +1,7 @@
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import math
|
||||||
import time
|
import time
|
||||||
from collections import Counter, defaultdict
|
from collections import Counter, defaultdict
|
||||||
from copy import deepcopy
|
from copy import deepcopy
|
||||||
|
|
@ -11,7 +12,7 @@ import inspect
|
||||||
import re
|
import re
|
||||||
from datetime import datetime, timedelta, timezone
|
from datetime import datetime, timedelta, timezone
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any
|
from typing import Any, Mapping
|
||||||
from zoneinfo import ZoneInfo
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
from .astrbot_compat import (
|
from .astrbot_compat import (
|
||||||
|
|
@ -22,7 +23,11 @@ from .astrbot_compat import (
|
||||||
remove_temp_text,
|
remove_temp_text,
|
||||||
sanitize_request_history,
|
sanitize_request_history,
|
||||||
)
|
)
|
||||||
from .bridge import serialize_memory
|
from .bridge import (
|
||||||
|
sanitize_companion_expression_decision,
|
||||||
|
sanitize_companion_relationship_projection,
|
||||||
|
serialize_memory,
|
||||||
|
)
|
||||||
from .bot_personal_dto import (
|
from .bot_personal_dto import (
|
||||||
BotPersonalArchiveDTO,
|
BotPersonalArchiveDTO,
|
||||||
BotPersonalValidationError,
|
BotPersonalValidationError,
|
||||||
|
|
@ -51,6 +56,8 @@ from .operations import (
|
||||||
detect_preset,
|
detect_preset,
|
||||||
persist_runtime_config,
|
persist_runtime_config,
|
||||||
)
|
)
|
||||||
|
from .provenance import observed_from_companion_snapshot
|
||||||
|
from .provenance_store import ProvenanceLedger
|
||||||
from .qq_history import QQHistoryReader
|
from .qq_history import QQHistoryReader
|
||||||
from .reply_chain import ReplyChainResolver
|
from .reply_chain import ReplyChainResolver
|
||||||
from .retrieval import RetrievalEngine
|
from .retrieval import RetrievalEngine
|
||||||
|
|
@ -61,6 +68,17 @@ from .turn_signal import analyze_turn_signal, message_terms
|
||||||
from .visibility import VisibilityPolicy
|
from .visibility import VisibilityPolicy
|
||||||
|
|
||||||
|
|
||||||
|
LOCAL_TZ = ZoneInfo("Asia/Shanghai")
|
||||||
|
|
||||||
|
USER_MEMORY_SUMMARY_VERSION = "memory.user_memory_summary.v1"
|
||||||
|
_USER_MEMORY_PROFILE_TYPES = frozenset({"user_profile", "user_habit", "manual_memory"})
|
||||||
|
_USER_MEMORY_PREFERENCE_TYPES = frozenset({"user_preference"})
|
||||||
|
_USER_MEMORY_RELATIONSHIP_TYPES = frozenset({"relationship_claim", "relationship_phase_summary"})
|
||||||
|
_USER_MEMORY_CONVERSATION_TYPES = frozenset(
|
||||||
|
{"conversation_event", "conversation_summary", "important_event", "memory_decay_summary", "self_action"}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
_RECENT_FACT_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = (
|
_RECENT_FACT_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = (
|
||||||
("meal", re.compile(r"吃过|吃完|吃了|没吃|还没吃|正在吃|吃饭|早饭|早餐|午饭|午餐|晚饭|晚餐|夜宵")),
|
("meal", re.compile(r"吃过|吃完|吃了|没吃|还没吃|正在吃|吃饭|早饭|早餐|午饭|午餐|晚饭|晚餐|夜宵")),
|
||||||
("bath", re.compile(r"洗澡|洗完澡|冲澡|沐浴")),
|
("bath", re.compile(r"洗澡|洗完澡|冲澡|沐浴")),
|
||||||
|
|
@ -178,6 +196,152 @@ class MemoryCompanionService:
|
||||||
self._relationship_phase_state: dict[str, dict[str, Any]] = {}
|
self._relationship_phase_state: dict[str, dict[str, Any]] = {}
|
||||||
self._RELATIONSHIP_PHASE_FILE = self.data_dir / "memory_companion_relationship_phase.json"
|
self._RELATIONSHIP_PHASE_FILE = self.data_dir / "memory_companion_relationship_phase.json"
|
||||||
self._load_relationship_phase_state()
|
self._load_relationship_phase_state()
|
||||||
|
self.provenance_ledger = ProvenanceLedger(self.data_dir / "provenance_ledger.json")
|
||||||
|
self._last_p5_gate_status: dict[str, Any] = {"state": "disabled", "enabled": False}
|
||||||
|
|
||||||
|
def _p5_gate_enabled(self, sink: str) -> bool:
|
||||||
|
key = (
|
||||||
|
"private_companion_bridge.enable_p5_b1_recall_gate"
|
||||||
|
if sink == "memory_recall"
|
||||||
|
else "private_companion_bridge.enable_p5_b1_bridge_gate"
|
||||||
|
)
|
||||||
|
return self.config.bool(key, False)
|
||||||
|
|
||||||
|
async def _p5_gate(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
event: Any = None,
|
||||||
|
sink: str,
|
||||||
|
attestation: Any = None,
|
||||||
|
consumer: Any = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
if not self._p5_gate_enabled(sink):
|
||||||
|
if attestation is not None and callable(consumer):
|
||||||
|
try:
|
||||||
|
consumed = consumer(attestation, sink)
|
||||||
|
if inspect.isawaitable(consumed):
|
||||||
|
await consumed
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
result = {"ok": True, "state": "legacy", "legacy": True, "enabled": False}
|
||||||
|
self._last_p5_gate_status = result
|
||||||
|
return result
|
||||||
|
if attestation is None and event is not None:
|
||||||
|
issuer = getattr(event, "private_companion_p5_issue_attestation", None)
|
||||||
|
if callable(issuer):
|
||||||
|
try:
|
||||||
|
issued = issuer(sink)
|
||||||
|
except Exception:
|
||||||
|
issued = None
|
||||||
|
if isinstance(issued, tuple) and len(issued) == 2:
|
||||||
|
attestation, consumer = issued
|
||||||
|
if attestation is None or not callable(consumer):
|
||||||
|
result = {
|
||||||
|
"ok": False,
|
||||||
|
"state": "degraded",
|
||||||
|
"enabled": True,
|
||||||
|
"error_code": "p5_attestation_required",
|
||||||
|
"warnings": ["legacy_call_not_attested"],
|
||||||
|
}
|
||||||
|
self._last_p5_gate_status = result
|
||||||
|
return result
|
||||||
|
try:
|
||||||
|
snapshot = consumer(attestation, sink)
|
||||||
|
if inspect.isawaitable(snapshot):
|
||||||
|
snapshot = await snapshot
|
||||||
|
except Exception:
|
||||||
|
snapshot = None
|
||||||
|
snapshot_record = observed_from_companion_snapshot("p5_gate", snapshot)
|
||||||
|
snapshot_sink = getattr(snapshot, "sink", None)
|
||||||
|
if snapshot_sink is None and isinstance(snapshot, Mapping):
|
||||||
|
snapshot_sink = snapshot.get("sink")
|
||||||
|
if snapshot_record.get("provenance_state") != "observed" or snapshot_sink != sink:
|
||||||
|
result = {
|
||||||
|
"ok": False,
|
||||||
|
"state": "denied",
|
||||||
|
"enabled": True,
|
||||||
|
"error_code": "p5_attestation_invalid",
|
||||||
|
"warnings": ["invalid_or_replayed_attestation"],
|
||||||
|
}
|
||||||
|
self._last_p5_gate_status = result
|
||||||
|
return result
|
||||||
|
disposition = str(getattr(snapshot, "disposition", "") or "")
|
||||||
|
trust = str(getattr(snapshot, "source_trust", "") or "")
|
||||||
|
if isinstance(snapshot, Mapping):
|
||||||
|
disposition = str(snapshot.get("disposition") or disposition)
|
||||||
|
trust = str(snapshot.get("source_trust") or snapshot.get("trust") or trust)
|
||||||
|
if disposition == "deny_high_risk":
|
||||||
|
state = "denied"
|
||||||
|
error_code = "p5_high_risk_denied"
|
||||||
|
allowed = False
|
||||||
|
elif disposition != "allow" or trust in {"T3", "T4"}:
|
||||||
|
state = "shadow"
|
||||||
|
error_code = "p5_source_shadowed"
|
||||||
|
allowed = False
|
||||||
|
else:
|
||||||
|
state = "allowed"
|
||||||
|
error_code = ""
|
||||||
|
allowed = True
|
||||||
|
result = {
|
||||||
|
"ok": allowed,
|
||||||
|
"state": state,
|
||||||
|
"enabled": True,
|
||||||
|
"snapshot": snapshot,
|
||||||
|
"error_code": error_code or None,
|
||||||
|
"warnings": [] if allowed else [error_code],
|
||||||
|
}
|
||||||
|
self._last_p5_gate_status = {
|
||||||
|
key: value for key, value in result.items() if key != "snapshot"
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
|
||||||
|
def p5_capability_status(self) -> dict[str, Any]:
|
||||||
|
ledger = getattr(self, "provenance_ledger", None)
|
||||||
|
snapshot = ledger.snapshot() if isinstance(ledger, ProvenanceLedger) else {"operation_count": 0, "observation_count": 0, "path_present": False}
|
||||||
|
return {
|
||||||
|
"schema_version": "ops.p5.provenance.v1",
|
||||||
|
"recall_gate": self._p5_gate_enabled("memory_recall"),
|
||||||
|
"bridge_gate": self._p5_gate_enabled("bridge_serialization"),
|
||||||
|
"last_gate_state": str(getattr(self, "_last_p5_gate_status", {}).get("state") or "disabled"),
|
||||||
|
"provenance_records": len(snapshot.get("records", {})),
|
||||||
|
"provenance_operations": int(snapshot.get("operation_count", 0) or 0),
|
||||||
|
"provenance_observations": int(snapshot.get("observation_count", 0) or 0),
|
||||||
|
"provenance_file_present": bool(snapshot.get("path_present", False)),
|
||||||
|
}
|
||||||
|
|
||||||
|
async def _p5_record_observed(self, memory_ids: list[str], snapshot: Any) -> dict[str, Any]:
|
||||||
|
ledger = getattr(self, "provenance_ledger", None)
|
||||||
|
if not isinstance(ledger, ProvenanceLedger):
|
||||||
|
return {"ok": False, "state": "degraded", "error_code": "provenance_ledger_unavailable"}
|
||||||
|
return await asyncio.to_thread(ledger.record_observed, memory_ids, snapshot)
|
||||||
|
|
||||||
|
def provenance_snapshot(self) -> dict[str, Any]:
|
||||||
|
ledger = getattr(self, "provenance_ledger", None)
|
||||||
|
return ledger.snapshot() if isinstance(ledger, ProvenanceLedger) else {"records": {}, "operation_count": 0}
|
||||||
|
|
||||||
|
def provenance_preview(self, candidates: list[Mapping[str, Any]], *, operation_ref_hash: str) -> dict[str, Any]:
|
||||||
|
ledger = getattr(self, "provenance_ledger", None)
|
||||||
|
if not isinstance(ledger, ProvenanceLedger):
|
||||||
|
return {"mode": "preview", "readonly": True, "write_count": 0, "error_codes": ["ledger_unavailable"]}
|
||||||
|
return ledger.preview_legacy(candidates, operation_ref_hash=operation_ref_hash)
|
||||||
|
|
||||||
|
async def provenance_backup(self) -> dict[str, Any]:
|
||||||
|
ledger = getattr(self, "provenance_ledger", None)
|
||||||
|
if not isinstance(ledger, ProvenanceLedger):
|
||||||
|
return {"ok": False, "state": "degraded", "error_code": "ledger_unavailable"}
|
||||||
|
return await asyncio.to_thread(ledger.backup)
|
||||||
|
|
||||||
|
async def provenance_apply(self, operation: Mapping[str, Any]) -> dict[str, Any]:
|
||||||
|
ledger = getattr(self, "provenance_ledger", None)
|
||||||
|
if not isinstance(ledger, ProvenanceLedger):
|
||||||
|
return {"ok": False, "state": "degraded", "error_code": "ledger_unavailable"}
|
||||||
|
return await asyncio.to_thread(ledger.apply, operation)
|
||||||
|
|
||||||
|
async def provenance_rollback(self, operation: Mapping[str, Any]) -> dict[str, Any]:
|
||||||
|
ledger = getattr(self, "provenance_ledger", None)
|
||||||
|
if not isinstance(ledger, ProvenanceLedger):
|
||||||
|
return {"ok": False, "state": "degraded", "error_code": "ledger_unavailable"}
|
||||||
|
return await asyncio.to_thread(ledger.rollback, operation)
|
||||||
|
|
||||||
def preview_historical_chat_upload(
|
def preview_historical_chat_upload(
|
||||||
self,
|
self,
|
||||||
|
|
@ -235,6 +399,8 @@ class MemoryCompanionService:
|
||||||
async def handle_llm_request(self, event: Any, req: Any) -> None:
|
async def handle_llm_request(self, event: Any, req: Any) -> None:
|
||||||
ctx = await self.identity.resolve_event_context(event)
|
ctx = await self.identity.resolve_event_context(event)
|
||||||
self._sanitize_session_context_message_text(ctx)
|
self._sanitize_session_context_message_text(ctx)
|
||||||
|
self._apply_companion_relationship_projection(ctx, event=event, req=req)
|
||||||
|
self._apply_companion_expression_decision(ctx, event=event, req=req)
|
||||||
self._apply_private_companion_preferred_address(ctx, req=req, event=event)
|
self._apply_private_companion_preferred_address(ctx, req=req, event=event)
|
||||||
if self._private_companion_internal_generation_event(event):
|
if self._private_companion_internal_generation_event(event):
|
||||||
return
|
return
|
||||||
|
|
@ -525,6 +691,41 @@ class MemoryCompanionService:
|
||||||
drop,
|
drop,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _apply_companion_relationship_projection(
|
||||||
|
ctx: SessionContext,
|
||||||
|
*,
|
||||||
|
event: Any = None,
|
||||||
|
req: Any = None,
|
||||||
|
) -> None:
|
||||||
|
if ctx.scope != "private":
|
||||||
|
return
|
||||||
|
raw_projection: Any = None
|
||||||
|
for target in (event, req):
|
||||||
|
if target is None:
|
||||||
|
continue
|
||||||
|
for attr in (
|
||||||
|
"private_companion_context",
|
||||||
|
"companion_context",
|
||||||
|
"memory_companion_context",
|
||||||
|
):
|
||||||
|
payload = getattr(target, attr, None)
|
||||||
|
if isinstance(payload, dict) and isinstance(payload.get("relationship_projection"), dict):
|
||||||
|
raw_projection = payload.get("relationship_projection")
|
||||||
|
break
|
||||||
|
if raw_projection is not None:
|
||||||
|
break
|
||||||
|
consumed = sanitize_companion_relationship_projection(raw_projection)
|
||||||
|
projection = consumed.get("projection") if isinstance(consumed, dict) else None
|
||||||
|
if not isinstance(projection, dict):
|
||||||
|
return
|
||||||
|
ctx.relationship_authority_source = "private_companion.relationship_score"
|
||||||
|
ctx.companion_relationship_score = int(projection.get("score") or 0)
|
||||||
|
ctx.companion_relationship_phase_key = clean_text(projection.get("phase_key"), 40)
|
||||||
|
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)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _apply_private_companion_preferred_address(
|
def _apply_private_companion_preferred_address(
|
||||||
ctx: SessionContext,
|
ctx: SessionContext,
|
||||||
|
|
@ -545,6 +746,34 @@ class MemoryCompanionService:
|
||||||
or getattr(event, "_private_companion_preferred_address_locked", False)
|
or getattr(event, "_private_companion_preferred_address_locked", False)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _apply_companion_expression_decision(
|
||||||
|
ctx: SessionContext,
|
||||||
|
*,
|
||||||
|
event: Any = None,
|
||||||
|
req: Any = None,
|
||||||
|
) -> None:
|
||||||
|
if ctx.scope != "private":
|
||||||
|
return
|
||||||
|
raw_decision: Any = None
|
||||||
|
for target in (req, event):
|
||||||
|
if target is None:
|
||||||
|
continue
|
||||||
|
candidate = getattr(target, "_private_companion_expression_decision", None)
|
||||||
|
if candidate is not None:
|
||||||
|
raw_decision = candidate
|
||||||
|
break
|
||||||
|
consumed = sanitize_companion_expression_decision(raw_decision)
|
||||||
|
decision = consumed.get("decision") if isinstance(consumed, dict) else None
|
||||||
|
if not isinstance(decision, dict):
|
||||||
|
return
|
||||||
|
ctx.companion_expression_contract = clean_text(decision.get("contract"), 80)
|
||||||
|
ctx.companion_expression_band = clean_text(decision.get("expression_band"), 40)
|
||||||
|
ctx.companion_expression_allowed_behaviors = tuple(decision.get("allowed_behaviors") or ())
|
||||||
|
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 ())
|
||||||
|
|
||||||
def _sanitize_visible_timeline_text(self, text: Any) -> str:
|
def _sanitize_visible_timeline_text(self, text: Any) -> str:
|
||||||
cleaned = clean_text(text, 1200)
|
cleaned = clean_text(text, 1200)
|
||||||
if not cleaned:
|
if not cleaned:
|
||||||
|
|
@ -833,6 +1062,127 @@ class MemoryCompanionService:
|
||||||
})
|
})
|
||||||
return {"ok": True, "read_only": True, "state": "ready", "degraded": False, "pending": False, "items": items[:max(1, min(100, int(limit or 10)))]}
|
return {"ok": True, "read_only": True, "state": "ready", "degraded": False, "pending": False, "items": items[:max(1, min(100, int(limit or 10)))]}
|
||||||
|
|
||||||
|
async def read_user_memory_summary(
|
||||||
|
self,
|
||||||
|
user_id: str,
|
||||||
|
*,
|
||||||
|
session_id: str = "",
|
||||||
|
limit: int = 6,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Return a bounded, content-free Memory workspace projection for one user.
|
||||||
|
|
||||||
|
Companion remains the authority for relationship and interaction state.
|
||||||
|
This method only reports exact-user Memory categories and opaque, redacted
|
||||||
|
anchors that can be used to open the Memory workspace.
|
||||||
|
"""
|
||||||
|
|
||||||
|
identity = clean_text(user_id, 120)
|
||||||
|
requested_session = clean_text(session_id, 200)
|
||||||
|
base = self._user_memory_summary_base(identity, requested_session)
|
||||||
|
if not identity:
|
||||||
|
return {**base, "error_code": "missing_user_id"}
|
||||||
|
if requested_session and session_target_id(requested_session, "private") != identity:
|
||||||
|
return {**base, "error_code": "session_identity_mismatch"}
|
||||||
|
try:
|
||||||
|
bridge_enabled = self.config.bridge_enabled()
|
||||||
|
except Exception:
|
||||||
|
return {**base, "error_code": "bridge_config_unavailable"}
|
||||||
|
if bridge_enabled is not True:
|
||||||
|
return {**base, "error_code": "bridge_disabled"}
|
||||||
|
store = getattr(self, "store", None)
|
||||||
|
reader = getattr(store, "read_user_memory_summary_records", None)
|
||||||
|
if not callable(reader):
|
||||||
|
return {**base, "error_code": "store_unavailable"}
|
||||||
|
try:
|
||||||
|
safe_limit = max(1, min(8, int(limit or 6)))
|
||||||
|
except (TypeError, ValueError, OverflowError):
|
||||||
|
safe_limit = 6
|
||||||
|
try:
|
||||||
|
raw = await reader(identity, session_id=requested_session, limit=safe_limit)
|
||||||
|
except Exception:
|
||||||
|
return {**base, "error_code": "store_query_failed"}
|
||||||
|
if not isinstance(raw, dict):
|
||||||
|
return {**base, "error_code": "invalid_store_response"}
|
||||||
|
|
||||||
|
type_counts = raw.get("type_counts") if isinstance(raw.get("type_counts"), dict) else {}
|
||||||
|
counts = {"profile": 0, "preference": 0, "relationship": 0, "private_conversation": 0, "other": 0, "total": 0}
|
||||||
|
for memory_type, value in type_counts.items():
|
||||||
|
try:
|
||||||
|
count = max(0, int(value))
|
||||||
|
except (TypeError, ValueError, OverflowError):
|
||||||
|
continue
|
||||||
|
counts[self._user_memory_category(memory_type)] += count
|
||||||
|
counts["total"] += count
|
||||||
|
|
||||||
|
summaries: list[dict[str, Any]] = []
|
||||||
|
records = raw.get("records") if isinstance(raw.get("records"), list) else []
|
||||||
|
for record in records[:safe_limit]:
|
||||||
|
if not isinstance(record, MemoryRecord):
|
||||||
|
continue
|
||||||
|
memory_type = clean_text(record.memory_type, 80)
|
||||||
|
category = self._user_memory_category(memory_type)
|
||||||
|
summaries.append(
|
||||||
|
{
|
||||||
|
"category": category,
|
||||||
|
"memory_type": memory_type,
|
||||||
|
"occurred_at": clean_text(record.occurred_at or record.created_at, 80),
|
||||||
|
"summary": f"{self._user_memory_category_label(category)}(内容已脱敏)",
|
||||||
|
"content_redacted": True,
|
||||||
|
"truncated": True,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
**base,
|
||||||
|
"ok": True,
|
||||||
|
"state": "ready",
|
||||||
|
"degraded": False,
|
||||||
|
"pending": False,
|
||||||
|
"counts": counts,
|
||||||
|
"summaries": summaries,
|
||||||
|
}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _user_memory_summary_base(user_id: str, session_id: str) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"contract": USER_MEMORY_SUMMARY_VERSION,
|
||||||
|
"ok": False,
|
||||||
|
"read_only": True,
|
||||||
|
"state": "degraded",
|
||||||
|
"degraded": True,
|
||||||
|
"pending": True,
|
||||||
|
"user_id": user_id,
|
||||||
|
"session_id": session_id,
|
||||||
|
"counts": {"profile": 0, "preference": 0, "relationship": 0, "private_conversation": 0, "other": 0, "total": 0},
|
||||||
|
"summaries": [],
|
||||||
|
"workspace": {
|
||||||
|
"kind": "memory_user_workspace",
|
||||||
|
"route_hint": "user_memory",
|
||||||
|
"user_id": user_id,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _user_memory_category(memory_type: Any) -> str:
|
||||||
|
normalized = clean_text(memory_type, 80).lower()
|
||||||
|
if normalized in _USER_MEMORY_PROFILE_TYPES:
|
||||||
|
return "profile"
|
||||||
|
if normalized in _USER_MEMORY_PREFERENCE_TYPES:
|
||||||
|
return "preference"
|
||||||
|
if normalized in _USER_MEMORY_RELATIONSHIP_TYPES:
|
||||||
|
return "relationship"
|
||||||
|
if normalized in _USER_MEMORY_CONVERSATION_TYPES:
|
||||||
|
return "private_conversation"
|
||||||
|
return "other"
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _user_memory_category_label(category: str) -> str:
|
||||||
|
return {
|
||||||
|
"profile": "用户画像记忆",
|
||||||
|
"preference": "用户偏好记忆",
|
||||||
|
"relationship": "关系线索记忆",
|
||||||
|
"private_conversation": "私聊连续性记忆",
|
||||||
|
}.get(category, "其他用户记忆")
|
||||||
|
|
||||||
async def read_bot_profile(
|
async def read_bot_profile(
|
||||||
self,
|
self,
|
||||||
profile: str,
|
profile: str,
|
||||||
|
|
@ -917,10 +1267,23 @@ class MemoryCompanionService:
|
||||||
*,
|
*,
|
||||||
session_context: SessionContext | dict[str, Any] | None = None,
|
session_context: SessionContext | dict[str, Any] | None = None,
|
||||||
top_k: int | None = None,
|
top_k: int | None = None,
|
||||||
|
p5_attestation: Any = None,
|
||||||
|
p5_attestation_consumer: Any = None,
|
||||||
) -> list[dict[str, Any]]:
|
) -> list[dict[str, Any]]:
|
||||||
|
gate = await self._p5_gate(
|
||||||
|
sink="bridge_serialization",
|
||||||
|
attestation=p5_attestation,
|
||||||
|
consumer=p5_attestation_consumer,
|
||||||
|
)
|
||||||
|
if not gate.get("ok"):
|
||||||
|
return []
|
||||||
ctx = self.session_context_from_bridge(session_context)
|
ctx = self.session_context_from_bridge(session_context)
|
||||||
results = await self.search(query, ctx, top_k or self.config.int("memory_injection.top_k", 6))
|
results = await self.search(query, ctx, top_k or self.config.int("memory_injection.top_k", 6))
|
||||||
return [serialize_memory(item.memory, item.score, item.reason) for item in results]
|
serialized = [serialize_memory(item.memory, item.score, item.reason) for item in results]
|
||||||
|
snapshot = gate.get("snapshot")
|
||||||
|
if snapshot is not None:
|
||||||
|
await self._p5_record_observed([item.memory.id for item in results], snapshot)
|
||||||
|
return serialized
|
||||||
|
|
||||||
async def bridge_compose_injection(
|
async def bridge_compose_injection(
|
||||||
self,
|
self,
|
||||||
|
|
@ -931,7 +1294,18 @@ class MemoryCompanionService:
|
||||||
max_chars: int | None = None,
|
max_chars: int | None = None,
|
||||||
companion_bot_mood: str = "",
|
companion_bot_mood: str = "",
|
||||||
companion_bot_energy: float = 0.0,
|
companion_bot_energy: float = 0.0,
|
||||||
|
p5_attestation: Any = None,
|
||||||
|
p5_attestation_consumer: Any = None,
|
||||||
|
_p5_gate_passed: bool = False,
|
||||||
) -> str:
|
) -> str:
|
||||||
|
if not _p5_gate_passed:
|
||||||
|
gate = await self._p5_gate(
|
||||||
|
sink="bridge_serialization",
|
||||||
|
attestation=p5_attestation,
|
||||||
|
consumer=p5_attestation_consumer,
|
||||||
|
)
|
||||||
|
if not gate.get("ok"):
|
||||||
|
return ""
|
||||||
ctx = self.session_context_from_bridge(session_context)
|
ctx = self.session_context_from_bridge(session_context)
|
||||||
query_text = clean_text(query or ctx.message_text, 1400)
|
query_text = clean_text(query or ctx.message_text, 1400)
|
||||||
if not query_text:
|
if not query_text:
|
||||||
|
|
@ -957,7 +1331,16 @@ class MemoryCompanionService:
|
||||||
companion_bot_mood: str = "",
|
companion_bot_mood: str = "",
|
||||||
companion_bot_energy: float = 0.0,
|
companion_bot_energy: float = 0.0,
|
||||||
retrieval_profile: str = "",
|
retrieval_profile: str = "",
|
||||||
|
p5_attestation: Any = None,
|
||||||
|
p5_attestation_consumer: Any = None,
|
||||||
) -> str:
|
) -> str:
|
||||||
|
gate = await self._p5_gate(
|
||||||
|
sink="bridge_serialization",
|
||||||
|
attestation=p5_attestation,
|
||||||
|
consumer=p5_attestation_consumer,
|
||||||
|
)
|
||||||
|
if not gate.get("ok"):
|
||||||
|
return ""
|
||||||
profile = clean_text(retrieval_profile, 40).lower()
|
profile = clean_text(retrieval_profile, 40).lower()
|
||||||
fast_profile_enabled = {
|
fast_profile_enabled = {
|
||||||
"schedule_fast": self.config.bool(
|
"schedule_fast": self.config.bool(
|
||||||
|
|
@ -986,6 +1369,7 @@ class MemoryCompanionService:
|
||||||
max_chars=max_chars,
|
max_chars=max_chars,
|
||||||
companion_bot_mood=companion_bot_mood,
|
companion_bot_mood=companion_bot_mood,
|
||||||
companion_bot_energy=companion_bot_energy,
|
companion_bot_energy=companion_bot_energy,
|
||||||
|
_p5_gate_passed=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
async def _bridge_compose_schedule_fast_context(
|
async def _bridge_compose_schedule_fast_context(
|
||||||
|
|
@ -1959,7 +2343,7 @@ class MemoryCompanionService:
|
||||||
payload.update(
|
payload.update(
|
||||||
{
|
{
|
||||||
"available": True,
|
"available": True,
|
||||||
"display_name": "我会牢牢记住你",
|
"display_name": "雪色的记忆插件-聊天侧",
|
||||||
"plugin_name": "astrbot_plugin_memory_companion",
|
"plugin_name": "astrbot_plugin_memory_companion",
|
||||||
"counted_in_private_companion_budget": False,
|
"counted_in_private_companion_budget": False,
|
||||||
"note": "仅展示记忆插件自身模型消耗,不计入陪伴插件每日 Token 限额。",
|
"note": "仅展示记忆插件自身模型消耗,不计入陪伴插件每日 Token 限额。",
|
||||||
|
|
@ -2096,7 +2480,7 @@ class MemoryCompanionService:
|
||||||
error: str = "",
|
error: str = "",
|
||||||
) -> None:
|
) -> None:
|
||||||
usage = self._extract_token_usage(resp, prompt, completion)
|
usage = self._extract_token_usage(resp, prompt, completion)
|
||||||
now_dt = datetime.now()
|
now_dt = datetime.now(LOCAL_TZ)
|
||||||
now_ts = time.time()
|
now_ts = time.time()
|
||||||
day = now_dt.strftime("%Y-%m-%d")
|
day = now_dt.strftime("%Y-%m-%d")
|
||||||
hour = now_dt.strftime("%Y-%m-%dT%H:00")
|
hour = now_dt.strftime("%Y-%m-%dT%H:00")
|
||||||
|
|
@ -2259,9 +2643,13 @@ class MemoryCompanionService:
|
||||||
provider_id = clean_text(provider_id, 160)
|
provider_id = clean_text(provider_id, 160)
|
||||||
indexed = 0
|
indexed = 0
|
||||||
try:
|
try:
|
||||||
|
batch_size = max(
|
||||||
|
1,
|
||||||
|
min(200, self.config.int("retrieval.embedding_backfill_batch_size", 50)),
|
||||||
|
)
|
||||||
records = await self.store.list_memories_missing_embeddings(
|
records = await self.store.list_memories_missing_embeddings(
|
||||||
provider_id=provider_id,
|
provider_id=provider_id,
|
||||||
limit=self.config.int("retrieval.embedding_backfill_batch_size", 50),
|
limit=batch_size,
|
||||||
include_pending=self.config.bool("retrieval.embedding_index_pending", False),
|
include_pending=self.config.bool("retrieval.embedding_index_pending", False),
|
||||||
)
|
)
|
||||||
for record in records:
|
for record in records:
|
||||||
|
|
@ -3379,14 +3767,39 @@ class MemoryCompanionService:
|
||||||
self._schedule_memory_embedding(memory_id, record)
|
self._schedule_memory_embedding(memory_id, record)
|
||||||
return {"ok": True, "memory_id": memory_id, "review_status": record.review_status}
|
return {"ok": True, "memory_id": memory_id, "review_status": record.review_status}
|
||||||
|
|
||||||
async def tool_recall(self, event: Any, query: str, top_k: int = 5) -> dict[str, Any]:
|
async def tool_recall(
|
||||||
|
self,
|
||||||
|
event: Any,
|
||||||
|
query: str,
|
||||||
|
top_k: int = 5,
|
||||||
|
*,
|
||||||
|
p5_attestation: Any = None,
|
||||||
|
p5_attestation_consumer: Any = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
ctx = await self.identity.resolve_event_context(event)
|
ctx = await self.identity.resolve_event_context(event)
|
||||||
query = clean_text(query, 1000)
|
query = clean_text(query, 1000)
|
||||||
if not query:
|
if not query:
|
||||||
return {"ok": False, "error": "empty query", "memories": []}
|
return {"ok": False, "error": "empty query", "memories": []}
|
||||||
|
p5_gate = await self._p5_gate(
|
||||||
|
event=event,
|
||||||
|
sink="memory_recall",
|
||||||
|
attestation=p5_attestation,
|
||||||
|
consumer=p5_attestation_consumer,
|
||||||
|
)
|
||||||
|
if not p5_gate.get("ok"):
|
||||||
|
return {
|
||||||
|
"ok": False,
|
||||||
|
"state": p5_gate.get("state", "degraded"),
|
||||||
|
"error": p5_gate.get("error_code", "p5_attestation_required"),
|
||||||
|
"memories": [],
|
||||||
|
}
|
||||||
results = await self.search(query, ctx, max(1, min(10, int(top_k or 5))))
|
results = await self.search(query, ctx, max(1, min(10, int(top_k or 5))))
|
||||||
|
snapshot = p5_gate.get("snapshot")
|
||||||
|
if snapshot is not None:
|
||||||
|
await self._p5_record_observed([item.memory.id for item in results], snapshot)
|
||||||
return {
|
return {
|
||||||
"ok": True,
|
"ok": True,
|
||||||
|
"state": p5_gate.get("state", "legacy"),
|
||||||
"memories": [serialize_memory(item.memory, item.score, item.reason) for item in results],
|
"memories": [serialize_memory(item.memory, item.score, item.reason) for item in results],
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -4519,6 +4932,22 @@ class MemoryCompanionService:
|
||||||
if self.config.bool("memory_injection.debug_log_injection_enabled", False):
|
if self.config.bool("memory_injection.debug_log_injection_enabled", False):
|
||||||
logger.info("[MemoryCompanion] 记忆注入已关闭: session=%s", ctx.session_id)
|
logger.info("[MemoryCompanion] 记忆注入已关闭: session=%s", ctx.session_id)
|
||||||
return
|
return
|
||||||
|
p5_gate = await self._p5_gate(event=event, sink="memory_recall")
|
||||||
|
if not p5_gate.get("ok"):
|
||||||
|
self._mark_memory_companion_injection_state(
|
||||||
|
event,
|
||||||
|
req,
|
||||||
|
injected=False,
|
||||||
|
conversation_memory=False,
|
||||||
|
slot_map={},
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
"[MemoryCompanion] P5 召回闸门未放行本轮记忆注入: session=%s state=%s error=%s",
|
||||||
|
ctx.session_id,
|
||||||
|
p5_gate.get("state"),
|
||||||
|
p5_gate.get("error_code"),
|
||||||
|
)
|
||||||
|
return
|
||||||
self._sanitize_request_history_for_companion(ctx, req)
|
self._sanitize_request_history_for_companion(ctx, req)
|
||||||
recent_fact_context = await self._recent_fact_guard_context(ctx)
|
recent_fact_context = await self._recent_fact_guard_context(ctx)
|
||||||
recent_cross_window_context = await self._recent_cross_window_context(ctx)
|
recent_cross_window_context = await self._recent_cross_window_context(ctx)
|
||||||
|
|
@ -6850,6 +7279,9 @@ class MemoryCompanionService:
|
||||||
return "uncertain", "low_confidence"
|
return "uncertain", "low_confidence"
|
||||||
text = clean_text(query_text or ctx.message_text, 800)
|
text = clean_text(query_text or ctx.message_text, 800)
|
||||||
explicit_memory = self._message_is_contextual_memory_request(text) or self._message_requests_temporal_aggregate(text)
|
explicit_memory = self._message_is_contextual_memory_request(text) or self._message_requests_temporal_aggregate(text)
|
||||||
|
companion_cap_reason = self._companion_memory_mention_cap(ctx, explicit_memory=explicit_memory)
|
||||||
|
if companion_cap_reason:
|
||||||
|
return "tone", companion_cap_reason
|
||||||
short_rest_check = self._message_is_short_rest_check(text)
|
short_rest_check = self._message_is_short_rest_check(text)
|
||||||
metadata = memory.metadata if isinstance(memory.metadata, dict) else {}
|
metadata = memory.metadata if isinstance(memory.metadata, dict) else {}
|
||||||
mention_policy = clean_text(metadata.get("mention_policy"), 60)
|
mention_policy = clean_text(metadata.get("mention_policy"), 60)
|
||||||
|
|
@ -6918,6 +7350,23 @@ class MemoryCompanionService:
|
||||||
return "tone", "indirect_memory"
|
return "tone", "indirect_memory"
|
||||||
return "mention", "direct_relevance"
|
return "mention", "direct_relevance"
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _companion_memory_mention_cap(ctx: SessionContext, *, explicit_memory: bool) -> str:
|
||||||
|
"""Return a reason when Companion limits unsolicited memory expression."""
|
||||||
|
|
||||||
|
if explicit_memory or ctx.scope != "private" or not ctx.companion_expression_contract:
|
||||||
|
return ""
|
||||||
|
if ctx.companion_expression_blocker:
|
||||||
|
return "companion_expression:blocker"
|
||||||
|
if ctx.companion_expression_safety_mode != "normal":
|
||||||
|
return f"companion_expression:safety_{ctx.companion_expression_safety_mode}"
|
||||||
|
if ctx.companion_expression_band in {"avoidant", "hurt"}:
|
||||||
|
return f"companion_expression:band_{ctx.companion_expression_band}"
|
||||||
|
mention_capable = {"support", "followup", "shared_ritual"}
|
||||||
|
if not mention_capable.intersection(ctx.companion_expression_allowed_behaviors):
|
||||||
|
return "companion_expression:behavior_cap"
|
||||||
|
return ""
|
||||||
|
|
||||||
def _memory_age_days(self, memory: MemoryRecord) -> float | None:
|
def _memory_age_days(self, memory: MemoryRecord) -> float | None:
|
||||||
timestamp = clean_text(memory.occurred_at or memory.updated_at or memory.created_at, 80)
|
timestamp = clean_text(memory.occurred_at or memory.updated_at or memory.created_at, 80)
|
||||||
parsed = self._parse_utc_datetime(timestamp)
|
parsed = self._parse_utc_datetime(timestamp)
|
||||||
|
|
@ -6960,7 +7409,7 @@ class MemoryCompanionService:
|
||||||
if not check_like:
|
if not check_like:
|
||||||
return False
|
return False
|
||||||
try:
|
try:
|
||||||
hour = datetime.now().hour
|
hour = datetime.now(LOCAL_TZ).hour
|
||||||
except Exception:
|
except Exception:
|
||||||
return True
|
return True
|
||||||
return hour >= 23 or hour < 7
|
return hour >= 23 or hour < 7
|
||||||
|
|
@ -7465,7 +7914,7 @@ class MemoryCompanionService:
|
||||||
def _compute_time_of_day(self) -> str:
|
def _compute_time_of_day(self) -> str:
|
||||||
"""Compute time-of-day category for atmosphere hints."""
|
"""Compute time-of-day category for atmosphere hints."""
|
||||||
try:
|
try:
|
||||||
hour = datetime.now().hour
|
hour = datetime.now(LOCAL_TZ).hour
|
||||||
except Exception:
|
except Exception:
|
||||||
return ""
|
return ""
|
||||||
if 23 <= hour or hour < 4:
|
if 23 <= hour or hour < 4:
|
||||||
|
|
@ -7604,6 +8053,51 @@ class MemoryCompanionService:
|
||||||
state["_identity"] = identity
|
state["_identity"] = identity
|
||||||
return state
|
return state
|
||||||
|
|
||||||
|
def _peek_relationship_phase(self, ctx: SessionContext) -> dict[str, Any]:
|
||||||
|
"""Project an existing phase without creating or saving state."""
|
||||||
|
fallback = {"observed": False, "phase": "unknown", "momentum_band": "unknown"}
|
||||||
|
try:
|
||||||
|
identity = self._phase_identity(ctx)
|
||||||
|
key = self._phase_key(ctx)
|
||||||
|
state = self._relationship_phase_state.get(key)
|
||||||
|
if type(state) is not dict and not identity["bot_id"]:
|
||||||
|
matches = [
|
||||||
|
candidate
|
||||||
|
for candidate in self._relationship_phase_state.values()
|
||||||
|
if type(candidate) is dict
|
||||||
|
and type(candidate.get("_identity")) is dict
|
||||||
|
and all(candidate["_identity"].get(field, "") == identity[field] for field in ("platform", "scope", "target_id", "member_id"))
|
||||||
|
]
|
||||||
|
if len(matches) == 1:
|
||||||
|
state = matches[0]
|
||||||
|
if type(state) is not dict:
|
||||||
|
legacy_key = clean_text(f"{ctx.scope}:{ctx.current_target_id or ctx.session_id}", 120)
|
||||||
|
legacy_state = self._relationship_phase_state.get(legacy_key)
|
||||||
|
if type(legacy_state) is dict:
|
||||||
|
state = legacy_state
|
||||||
|
if type(state) is not dict:
|
||||||
|
return fallback
|
||||||
|
phase = state.get("phase")
|
||||||
|
momentum = state.get("momentum")
|
||||||
|
touch_count = state.get("touch_count")
|
||||||
|
if type(phase) is not str or phase not in self._PHASES:
|
||||||
|
return fallback
|
||||||
|
if type(momentum) not in {int, float} or type(momentum) is bool:
|
||||||
|
return fallback
|
||||||
|
if not math.isfinite(momentum):
|
||||||
|
return fallback
|
||||||
|
if type(touch_count) is not int:
|
||||||
|
return fallback
|
||||||
|
except Exception:
|
||||||
|
return fallback
|
||||||
|
momentum_band = "rising" if momentum >= 0.08 else "cooling" if momentum <= -0.08 else "steady"
|
||||||
|
return {
|
||||||
|
"observed": True,
|
||||||
|
"phase": phase,
|
||||||
|
"momentum_band": momentum_band,
|
||||||
|
"touch_count": max(0, min(256, touch_count)),
|
||||||
|
}
|
||||||
|
|
||||||
def _update_relationship_phase_momentum(
|
def _update_relationship_phase_momentum(
|
||||||
self,
|
self,
|
||||||
ctx: SessionContext,
|
ctx: SessionContext,
|
||||||
|
|
@ -7618,6 +8112,11 @@ class MemoryCompanionService:
|
||||||
message_id = clean_text(message_id or ctx.message_id, 160)
|
message_id = clean_text(message_id or ctx.message_id, 160)
|
||||||
if not message_id:
|
if not message_id:
|
||||||
return False
|
return False
|
||||||
|
if (
|
||||||
|
ctx.relationship_authority_source == "private_companion.relationship_score"
|
||||||
|
or ctx.companion_expression_contract
|
||||||
|
):
|
||||||
|
return False
|
||||||
state = self._get_relationship_phase(ctx)
|
state = self._get_relationship_phase(ctx)
|
||||||
recent_ids = state.get("recent_touch_message_ids")
|
recent_ids = state.get("recent_touch_message_ids")
|
||||||
if not isinstance(recent_ids, list):
|
if not isinstance(recent_ids, list):
|
||||||
|
|
@ -7717,6 +8216,11 @@ class MemoryCompanionService:
|
||||||
|
|
||||||
def _update_address_evolution(self, ctx: SessionContext, text: str) -> None:
|
def _update_address_evolution(self, ctx: SessionContext, text: str) -> None:
|
||||||
"""Track address evolution in the relationship phase state."""
|
"""Track address evolution in the relationship phase state."""
|
||||||
|
if (
|
||||||
|
ctx.relationship_authority_source == "private_companion.relationship_score"
|
||||||
|
or ctx.companion_expression_contract
|
||||||
|
):
|
||||||
|
return
|
||||||
phase = self._detect_address_phase(text)
|
phase = self._detect_address_phase(text)
|
||||||
if not phase:
|
if not phase:
|
||||||
return
|
return
|
||||||
|
|
@ -7751,6 +8255,20 @@ class MemoryCompanionService:
|
||||||
"不必每句都带称呼;关系阶段建议、历史称呼、显示名和旧记忆只作识别资料,"
|
"不必每句都带称呼;关系阶段建议、历史称呼、显示名和旧记忆只作识别资料,"
|
||||||
"不能另造或追加亲昵称呼。若对方本轮明确要求改称呼,以本轮最新要求为准。"
|
"不能另造或追加亲昵称呼。若对方本轮明确要求改称呼,以本轮最新要求为准。"
|
||||||
)
|
)
|
||||||
|
if ctx.companion_expression_contract:
|
||||||
|
return ""
|
||||||
|
if ctx.relationship_authority_source == "private_companion.relationship_score":
|
||||||
|
label = clean_text(ctx.companion_relationship_phase_label, 40) or clean_text(
|
||||||
|
ctx.companion_relationship_phase_key,
|
||||||
|
40,
|
||||||
|
)
|
||||||
|
tone = clean_text(ctx.companion_relationship_tone, 160)
|
||||||
|
address = clean_text(ctx.companion_relationship_address_level, 120)
|
||||||
|
return (
|
||||||
|
f"陪伴插件是长期亲密度权威:当前阶段为“{label or '未标注'}”。"
|
||||||
|
f"基础语气按“{tone or '自然、尊重当前节奏'}”,称呼尺度按“{address or '沿用已确认称呼'}”。"
|
||||||
|
"Memory 仅提供记忆触动趋势和相关事实,不得用自身阶段另行升级称呼、语气或权限。"
|
||||||
|
)
|
||||||
state = self._get_relationship_phase(ctx)
|
state = self._get_relationship_phase(ctx)
|
||||||
user_address_phase = state.get("current_address_phase", "")
|
user_address_phase = state.get("current_address_phase", "")
|
||||||
relationship_phase = state.get("phase", "acquaintance")
|
relationship_phase = state.get("phase", "acquaintance")
|
||||||
|
|
|
||||||
173
core/store.py
173
core/store.py
|
|
@ -14,6 +14,8 @@ from .models import EntityRef, MemoryRecord, clean_text, json_dumps, json_loads,
|
||||||
|
|
||||||
|
|
||||||
class MemoryStore:
|
class MemoryStore:
|
||||||
|
EMBEDDING_CANDIDATE_CACHE_MAX = 64
|
||||||
|
|
||||||
def __init__(self, db_path: Path):
|
def __init__(self, db_path: Path):
|
||||||
self.db_path = Path(db_path)
|
self.db_path = Path(db_path)
|
||||||
self.db_path.parent.mkdir(parents=True, exist_ok=True)
|
self.db_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
@ -1421,14 +1423,14 @@ class MemoryStore:
|
||||||
self._conn.commit()
|
self._conn.commit()
|
||||||
return row_id
|
return row_id
|
||||||
|
|
||||||
async def list_identities(self, limit: int = 1000) -> list[dict[str, Any]]:
|
async def list_identities(self, limit: int = 1000, *, offset: int = 0) -> list[dict[str, Any]]:
|
||||||
return await asyncio.to_thread(self._list_identities_sync, limit)
|
return await asyncio.to_thread(self._list_identities_sync, limit, offset)
|
||||||
|
|
||||||
def _list_identities_sync(self, limit: int) -> list[dict[str, Any]]:
|
def _list_identities_sync(self, limit: int, offset: int) -> list[dict[str, Any]]:
|
||||||
with self._lock:
|
with self._lock:
|
||||||
rows = self._conn.execute(
|
rows = self._conn.execute(
|
||||||
"SELECT * FROM identities ORDER BY updated_at DESC LIMIT ?",
|
"SELECT * FROM identities ORDER BY updated_at DESC LIMIT ? OFFSET ?",
|
||||||
(max(1, int(limit)),),
|
(max(1, int(limit)), max(0, int(offset))),
|
||||||
).fetchall()
|
).fetchall()
|
||||||
result: list[dict[str, Any]] = []
|
result: list[dict[str, Any]] = []
|
||||||
for row in rows:
|
for row in rows:
|
||||||
|
|
@ -1563,6 +1565,8 @@ class MemoryStore:
|
||||||
scope: str = "",
|
scope: str = "",
|
||||||
session_id: str = "",
|
session_id: str = "",
|
||||||
group_id: str = "",
|
group_id: str = "",
|
||||||
|
*,
|
||||||
|
offset: int = 0,
|
||||||
) -> list[dict[str, Any]]:
|
) -> list[dict[str, Any]]:
|
||||||
return await asyncio.to_thread(
|
return await asyncio.to_thread(
|
||||||
self._list_relationships_sync,
|
self._list_relationships_sync,
|
||||||
|
|
@ -1571,6 +1575,7 @@ class MemoryStore:
|
||||||
scope,
|
scope,
|
||||||
session_id,
|
session_id,
|
||||||
group_id,
|
group_id,
|
||||||
|
offset,
|
||||||
)
|
)
|
||||||
|
|
||||||
def _list_relationships_sync(
|
def _list_relationships_sync(
|
||||||
|
|
@ -1580,6 +1585,7 @@ class MemoryStore:
|
||||||
scope: str,
|
scope: str,
|
||||||
session_id: str,
|
session_id: str,
|
||||||
group_id: str,
|
group_id: str,
|
||||||
|
offset: int,
|
||||||
) -> list[dict[str, Any]]:
|
) -> list[dict[str, Any]]:
|
||||||
params: list[Any] = []
|
params: list[Any] = []
|
||||||
where = "1=1"
|
where = "1=1"
|
||||||
|
|
@ -1601,9 +1607,9 @@ class MemoryStore:
|
||||||
SELECT * FROM relationship_edges
|
SELECT * FROM relationship_edges
|
||||||
WHERE {where}
|
WHERE {where}
|
||||||
ORDER BY updated_at DESC
|
ORDER BY updated_at DESC
|
||||||
LIMIT ?
|
LIMIT ? OFFSET ?
|
||||||
""",
|
""",
|
||||||
params + [max(1, int(limit))],
|
params + [max(1, int(limit)), max(0, int(offset))],
|
||||||
).fetchall()
|
).fetchall()
|
||||||
return [dict(row) for row in rows]
|
return [dict(row) for row in rows]
|
||||||
|
|
||||||
|
|
@ -1814,8 +1820,8 @@ class MemoryStore:
|
||||||
params.append(clean_text(group_id, 120))
|
params.append(clean_text(group_id, 120))
|
||||||
node = clean_text(node, 160)
|
node = clean_text(node, 160)
|
||||||
if node:
|
if node:
|
||||||
where += " AND (s.label LIKE ? OR t.label LIKE ?)"
|
where += " AND (s.label LIKE ? ESCAPE '\\' OR t.label LIKE ? ESCAPE '\\')"
|
||||||
like = f"%{node}%"
|
like = self._like_pattern(node)
|
||||||
params.extend([like, like])
|
params.extend([like, like])
|
||||||
with self._lock:
|
with self._lock:
|
||||||
rows = self._conn.execute(
|
rows = self._conn.execute(
|
||||||
|
|
@ -1880,8 +1886,8 @@ class MemoryStore:
|
||||||
if group_id:
|
if group_id:
|
||||||
scope_filter += " AND (n.group_id='' OR n.group_id=?)"
|
scope_filter += " AND (n.group_id='' OR n.group_id=?)"
|
||||||
params.append(group_id)
|
params.append(group_id)
|
||||||
like_sql = " OR ".join(["lower(n.label) LIKE ?" for _ in cleaned_terms])
|
like_sql = " OR ".join(["lower(n.label) LIKE ? ESCAPE '\\'" for _ in cleaned_terms])
|
||||||
like_params = [f"%{term}%" for term in cleaned_terms]
|
like_params = [self._like_pattern(term) for term in cleaned_terms]
|
||||||
with self._lock:
|
with self._lock:
|
||||||
matched = self._conn.execute(
|
matched = self._conn.execute(
|
||||||
f"""
|
f"""
|
||||||
|
|
@ -2684,8 +2690,17 @@ class MemoryStore:
|
||||||
scope: str = "",
|
scope: str = "",
|
||||||
session_id: str = "",
|
session_id: str = "",
|
||||||
entity_id: str = "",
|
entity_id: str = "",
|
||||||
|
*,
|
||||||
|
offset: int = 0,
|
||||||
) -> list[dict[str, Any]]:
|
) -> list[dict[str, Any]]:
|
||||||
return await asyncio.to_thread(self._recent_timeline_sync, limit, scope, session_id, entity_id)
|
return await asyncio.to_thread(
|
||||||
|
self._recent_timeline_sync,
|
||||||
|
limit,
|
||||||
|
scope,
|
||||||
|
session_id,
|
||||||
|
entity_id,
|
||||||
|
offset,
|
||||||
|
)
|
||||||
|
|
||||||
def _recent_timeline_sync(
|
def _recent_timeline_sync(
|
||||||
self,
|
self,
|
||||||
|
|
@ -2693,6 +2708,7 @@ class MemoryStore:
|
||||||
scope: str,
|
scope: str,
|
||||||
session_id: str,
|
session_id: str,
|
||||||
entity_id: str,
|
entity_id: str,
|
||||||
|
offset: int,
|
||||||
) -> list[dict[str, Any]]:
|
) -> list[dict[str, Any]]:
|
||||||
params: list[Any] = []
|
params: list[Any] = []
|
||||||
where = "1=1"
|
where = "1=1"
|
||||||
|
|
@ -2711,9 +2727,9 @@ class MemoryStore:
|
||||||
SELECT * FROM timeline
|
SELECT * FROM timeline
|
||||||
WHERE {where}
|
WHERE {where}
|
||||||
ORDER BY occurred_at DESC, created_at DESC
|
ORDER BY occurred_at DESC, created_at DESC
|
||||||
LIMIT ?
|
LIMIT ? OFFSET ?
|
||||||
""",
|
""",
|
||||||
params + [max(1, int(limit))],
|
params + [max(1, int(limit)), max(0, int(offset))],
|
||||||
).fetchall()
|
).fetchall()
|
||||||
return [dict(row) for row in rows]
|
return [dict(row) for row in rows]
|
||||||
|
|
||||||
|
|
@ -3660,6 +3676,7 @@ class MemoryStore:
|
||||||
self,
|
self,
|
||||||
*,
|
*,
|
||||||
limit: int = 50,
|
limit: int = 50,
|
||||||
|
offset: int = 0,
|
||||||
include_pending: bool = True,
|
include_pending: bool = True,
|
||||||
query: str = "",
|
query: str = "",
|
||||||
memory_type: str = "",
|
memory_type: str = "",
|
||||||
|
|
@ -3674,6 +3691,7 @@ class MemoryStore:
|
||||||
return await self._run_recoverable_database_operation(
|
return await self._run_recoverable_database_operation(
|
||||||
self._list_memories_sync,
|
self._list_memories_sync,
|
||||||
limit,
|
limit,
|
||||||
|
offset,
|
||||||
include_pending,
|
include_pending,
|
||||||
query,
|
query,
|
||||||
memory_type,
|
memory_type,
|
||||||
|
|
@ -3689,6 +3707,7 @@ class MemoryStore:
|
||||||
def _list_memories_sync(
|
def _list_memories_sync(
|
||||||
self,
|
self,
|
||||||
limit: int,
|
limit: int,
|
||||||
|
offset: int,
|
||||||
include_pending: bool,
|
include_pending: bool,
|
||||||
query: str,
|
query: str,
|
||||||
memory_type: str,
|
memory_type: str,
|
||||||
|
|
@ -3705,11 +3724,11 @@ class MemoryStore:
|
||||||
if not include_pending:
|
if not include_pending:
|
||||||
where += " AND review_status != 'pending'"
|
where += " AND review_status != 'pending'"
|
||||||
if query:
|
if query:
|
||||||
like = f"%{clean_text(query, 500)}%"
|
like = self._like_pattern(query)
|
||||||
where += (
|
where += (
|
||||||
" AND (id LIKE ? OR content LIKE ? OR evidence LIKE ? OR subject_id LIKE ?"
|
" AND (id LIKE ? ESCAPE '\\' OR content LIKE ? ESCAPE '\\' OR evidence LIKE ? ESCAPE '\\' OR subject_id LIKE ? ESCAPE '\\'"
|
||||||
" OR subject_name LIKE ? OR object_id LIKE ? OR object_name LIKE ?"
|
" OR subject_name LIKE ? ESCAPE '\\' OR object_id LIKE ? ESCAPE '\\' OR object_name LIKE ? ESCAPE '\\'"
|
||||||
" OR session_id LIKE ? OR group_id LIKE ?)"
|
" OR session_id LIKE ? ESCAPE '\\' OR group_id LIKE ? ESCAPE '\\')"
|
||||||
)
|
)
|
||||||
params.extend([like] * 9)
|
params.extend([like] * 9)
|
||||||
if memory_type:
|
if memory_type:
|
||||||
|
|
@ -3735,8 +3754,80 @@ class MemoryStore:
|
||||||
params.append(clean_text(group_id, 120))
|
params.append(clean_text(group_id, 120))
|
||||||
if entity_id:
|
if entity_id:
|
||||||
entity = clean_text(entity_id, 120)
|
entity = clean_text(entity_id, 120)
|
||||||
where += " AND (subject_id=? OR object_id=? OR group_id=? OR session_id LIKE ?)"
|
where += " AND (subject_id=? OR object_id=? OR group_id=? OR session_id LIKE ? ESCAPE '\\')"
|
||||||
params.extend([entity, entity, entity, f"%{entity}%"])
|
params.extend([entity, entity, entity, self._like_pattern(entity)])
|
||||||
|
with self._lock:
|
||||||
|
rows = self._conn.execute(
|
||||||
|
f"""
|
||||||
|
SELECT * FROM memories
|
||||||
|
WHERE {where}
|
||||||
|
ORDER BY occurred_at DESC, created_at DESC
|
||||||
|
LIMIT ? OFFSET ?
|
||||||
|
""",
|
||||||
|
params + [max(1, int(limit)), max(0, int(offset))],
|
||||||
|
).fetchall()
|
||||||
|
return [MemoryRecord.from_row(row) for row in rows]
|
||||||
|
|
||||||
|
async def read_user_memory_summary_records(
|
||||||
|
self,
|
||||||
|
user_id: str,
|
||||||
|
*,
|
||||||
|
session_id: str = "",
|
||||||
|
limit: int = 8,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Read a bounded, exact-identity private-memory set for a bridge DTO.
|
||||||
|
|
||||||
|
This is deliberately not a general search: it accepts no display name,
|
||||||
|
has no cross-window expansion, and never reads group rows. A supplied
|
||||||
|
session must itself resolve to the same private user identity.
|
||||||
|
"""
|
||||||
|
|
||||||
|
return await self._run_recoverable_database_operation(
|
||||||
|
self._read_user_memory_summary_records_sync,
|
||||||
|
user_id,
|
||||||
|
session_id,
|
||||||
|
limit,
|
||||||
|
)
|
||||||
|
|
||||||
|
def _read_user_memory_summary_records_sync(
|
||||||
|
self,
|
||||||
|
user_id: str,
|
||||||
|
session_id: str,
|
||||||
|
limit: int,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
identity = clean_text(user_id, 120)
|
||||||
|
requested_session = clean_text(session_id, 200)
|
||||||
|
empty = {"records": [], "total": 0, "type_counts": {}}
|
||||||
|
if not identity:
|
||||||
|
return empty
|
||||||
|
if requested_session:
|
||||||
|
scope, target_id = parse_scope_from_session(requested_session)
|
||||||
|
if scope != "private" or clean_text(target_id, 120) != identity:
|
||||||
|
return empty
|
||||||
|
|
||||||
|
try:
|
||||||
|
safe_limit = max(1, min(12, int(limit or 8)))
|
||||||
|
except (TypeError, ValueError, OverflowError):
|
||||||
|
safe_limit = 8
|
||||||
|
session_filters = [
|
||||||
|
"%:friendmessage:" + self._escape_like_suffix(identity),
|
||||||
|
"%:privatemessage:" + self._escape_like_suffix(identity),
|
||||||
|
"%:friend:" + self._escape_like_suffix(identity),
|
||||||
|
"%:private:" + self._escape_like_suffix(identity),
|
||||||
|
]
|
||||||
|
identity_clause = " OR ".join(
|
||||||
|
["subject_id=?", "object_id=?", *("LOWER(session_id) LIKE ? ESCAPE '\\'" for _ in session_filters)]
|
||||||
|
)
|
||||||
|
params: list[Any] = [identity, identity, *session_filters]
|
||||||
|
session_clause = ""
|
||||||
|
if requested_session:
|
||||||
|
session_clause = " AND session_id=?"
|
||||||
|
params.append(requested_session)
|
||||||
|
where = (
|
||||||
|
"scope='private' AND review_status!='pending' "
|
||||||
|
"AND visibility IN ('private_pair', 'shareable') "
|
||||||
|
f"AND ({identity_clause}){session_clause}"
|
||||||
|
)
|
||||||
with self._lock:
|
with self._lock:
|
||||||
rows = self._conn.execute(
|
rows = self._conn.execute(
|
||||||
f"""
|
f"""
|
||||||
|
|
@ -3745,9 +3836,41 @@ class MemoryStore:
|
||||||
ORDER BY occurred_at DESC, created_at DESC
|
ORDER BY occurred_at DESC, created_at DESC
|
||||||
LIMIT ?
|
LIMIT ?
|
||||||
""",
|
""",
|
||||||
params + [max(1, int(limit))],
|
[*params, safe_limit],
|
||||||
).fetchall()
|
).fetchall()
|
||||||
return [MemoryRecord.from_row(row) for row in rows]
|
total_row = self._conn.execute(
|
||||||
|
f"SELECT COUNT(*) AS count FROM memories WHERE {where}",
|
||||||
|
params,
|
||||||
|
).fetchone()
|
||||||
|
type_rows = self._conn.execute(
|
||||||
|
f"SELECT memory_type, COUNT(*) AS count FROM memories WHERE {where} GROUP BY memory_type",
|
||||||
|
params,
|
||||||
|
).fetchall()
|
||||||
|
|
||||||
|
records: list[MemoryRecord] = []
|
||||||
|
for row in rows:
|
||||||
|
record = MemoryRecord.from_row(row)
|
||||||
|
parsed_scope, parsed_target = parse_scope_from_session(clean_text(record.session_id, 200))
|
||||||
|
direct_identity = identity in {clean_text(record.subject.id, 120), clean_text(record.object.id, 120)}
|
||||||
|
session_identity = parsed_scope == "private" and clean_text(parsed_target, 120) == identity
|
||||||
|
if requested_session and record.session_id != requested_session:
|
||||||
|
continue
|
||||||
|
if direct_identity or session_identity:
|
||||||
|
records.append(record)
|
||||||
|
type_counts = {
|
||||||
|
clean_text(row["memory_type"], 80): max(0, int(row["count"] or 0))
|
||||||
|
for row in type_rows
|
||||||
|
if clean_text(row["memory_type"], 80)
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
"records": records,
|
||||||
|
"total": max(0, int(total_row["count"] or 0)) if total_row else 0,
|
||||||
|
"type_counts": type_counts,
|
||||||
|
}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _escape_like_suffix(value: str) -> str:
|
||||||
|
return clean_text(value, 120).lower().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||||
|
|
||||||
async def list_memory_buckets(
|
async def list_memory_buckets(
|
||||||
self,
|
self,
|
||||||
|
|
@ -3778,12 +3901,12 @@ class MemoryStore:
|
||||||
MAX(COALESCE(NULLIF(occurred_at, ''), created_at)) AS latest_at
|
MAX(COALESCE(NULLIF(occurred_at, ''), created_at)) AS latest_at
|
||||||
FROM memories
|
FROM memories
|
||||||
WHERE scope='private' AND session_id!=''
|
WHERE scope='private' AND session_id!=''
|
||||||
AND (subject_id=? OR object_id=? OR session_id LIKE ?)
|
AND (subject_id=? OR object_id=? OR session_id LIKE ? ESCAPE '\\')
|
||||||
GROUP BY session_id
|
GROUP BY session_id
|
||||||
ORDER BY native_count DESC, total_count DESC, latest_at DESC
|
ORDER BY native_count DESC, total_count DESC, latest_at DESC
|
||||||
LIMIT 64
|
LIMIT 64
|
||||||
""",
|
""",
|
||||||
(user_id, user_id, f"%{user_id}%"),
|
(user_id, user_id, self._like_pattern(user_id)),
|
||||||
).fetchall()
|
).fetchall()
|
||||||
for row in rows:
|
for row in rows:
|
||||||
parsed_scope, parsed_target = parse_scope_from_session(clean_text(row["session_id"], 200))
|
parsed_scope, parsed_target = parse_scope_from_session(clean_text(row["session_id"], 200))
|
||||||
|
|
@ -5243,6 +5366,8 @@ class MemoryStore:
|
||||||
result.append((MemoryRecord.from_row(row), vector, clean_text(row["embedding_text_hash"], 80)))
|
result.append((MemoryRecord.from_row(row), vector, clean_text(row["embedding_text_hash"], 80)))
|
||||||
with self._lock:
|
with self._lock:
|
||||||
self._embedding_candidate_cache[cache_key] = result
|
self._embedding_candidate_cache[cache_key] = result
|
||||||
|
while len(self._embedding_candidate_cache) > self.EMBEDDING_CANDIDATE_CACHE_MAX:
|
||||||
|
self._embedding_candidate_cache.pop(next(iter(self._embedding_candidate_cache)), None)
|
||||||
return deepcopy(result)
|
return deepcopy(result)
|
||||||
|
|
||||||
async def list_memories_missing_embeddings(
|
async def list_memories_missing_embeddings(
|
||||||
|
|
|
||||||
8
main.py
8
main.py
|
|
@ -16,7 +16,7 @@ from .core.models import json_dumps
|
||||||
from .core.service import MemoryCompanionService
|
from .core.service import MemoryCompanionService
|
||||||
|
|
||||||
PLUGIN_NAME = "astrbot_plugin_memory_companion"
|
PLUGIN_NAME = "astrbot_plugin_memory_companion"
|
||||||
PLUGIN_VERSION = "1.6.5"
|
PLUGIN_VERSION = "1.6.8"
|
||||||
|
|
||||||
_ACTIVE_BRIDGE: MemoryCompanionBridge | None = None
|
_ACTIVE_BRIDGE: MemoryCompanionBridge | None = None
|
||||||
|
|
||||||
|
|
@ -38,7 +38,7 @@ def _prepare_data_dir() -> Path:
|
||||||
@register(
|
@register(
|
||||||
"MemoryCompanion",
|
"MemoryCompanion",
|
||||||
"menglimi",
|
"menglimi",
|
||||||
"我会牢牢记住你:结构化长期记忆、共同自我时间线和关系隔离。",
|
"雪色的记忆插件-聊天侧:结构化长期记忆、共同自我时间线和关系隔离。",
|
||||||
PLUGIN_VERSION,
|
PLUGIN_VERSION,
|
||||||
"https://github.com/menglimi/astrbot_plugin_memory_companion",
|
"https://github.com/menglimi/astrbot_plugin_memory_companion",
|
||||||
)
|
)
|
||||||
|
|
@ -67,7 +67,7 @@ class MemoryCompanionPlugin(Star):
|
||||||
_ACTIVE_BRIDGE = self.memory_companion if self.service.config.bridge_enabled() else None
|
_ACTIVE_BRIDGE = self.memory_companion if self.service.config.bridge_enabled() else None
|
||||||
self._register_page_api_if_available()
|
self._register_page_api_if_available()
|
||||||
|
|
||||||
logger.info("[MemoryCompanion] 我会牢牢记住你 已启动,数据目录=%s", self.service.data_dir)
|
logger.info("[MemoryCompanion] 雪色的记忆插件-聊天侧 已启动,数据目录=%s", self.service.data_dir)
|
||||||
|
|
||||||
def bot_personal_capability_status(self) -> dict[str, Any]:
|
def bot_personal_capability_status(self) -> dict[str, Any]:
|
||||||
return dict(self.bot_personal_capabilities)
|
return dict(self.bot_personal_capabilities)
|
||||||
|
|
@ -345,4 +345,4 @@ class MemoryCompanionPlugin(Star):
|
||||||
if _ACTIVE_BRIDGE is self.memory_companion:
|
if _ACTIVE_BRIDGE is self.memory_companion:
|
||||||
_ACTIVE_BRIDGE = None
|
_ACTIVE_BRIDGE = None
|
||||||
await self.service.aclose()
|
await self.service.aclose()
|
||||||
logger.info("[MemoryCompanion] 我会牢牢记住你 已停止")
|
logger.info("[MemoryCompanion] 雪色的记忆插件-聊天侧 已停止")
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,9 @@
|
||||||
name: astrbot_plugin_memory_companion
|
name: astrbot_plugin_memory_companion
|
||||||
display_name: 我会牢牢记住你
|
display_name: 雪色的记忆插件-聊天侧
|
||||||
author: menglimi
|
author: menglimi
|
||||||
author_url: https://github.com/menglimi
|
author_url: https://github.com/menglimi
|
||||||
version: 1.6.5
|
version: 1.6.8
|
||||||
description: 我会牢牢记住你是面向 AstrBot 陪伴体系的记忆陪伴中枢。它统一管理长期记忆、历史对话整理、群聊连续对话记忆、主链注入、权限边界、知识图谱、陪伴插件桥接、自然衰减、可移植数据和运行诊断。
|
description: 雪色的记忆插件-聊天侧是面向 AstrBot 陪伴体系的记忆陪伴中枢。它统一管理长期记忆、历史对话整理、群聊连续对话记忆、主链注入、权限边界、知识图谱、陪伴插件桥接、自然衰减、可移植数据和运行诊断。
|
||||||
desc: 为 AstrBot 提供主链记忆注入、历史聊天整理导入、连续对话记忆、陪伴插件协同、主动记忆/回忆工具、知识图谱、权限边界、自我时间线、自然衰减、迁移导出和成本诊断。
|
desc: 为 AstrBot 提供主链记忆注入、历史聊天整理导入、连续对话记忆、陪伴插件协同、主动记忆/回忆工具、知识图谱、权限边界、自我时间线、自然衰减、迁移导出和成本诊断。
|
||||||
repo: https://github.com/menglimi/astrbot_plugin_memory_companion
|
repo: https://github.com/menglimi/astrbot_plugin_memory_companion
|
||||||
category: AI 增强
|
category: AI 增强
|
||||||
|
|
|
||||||
157
page_api.py
157
page_api.py
|
|
@ -18,6 +18,7 @@ from zoneinfo import ZoneInfo
|
||||||
from quart import jsonify, request, send_file
|
from quart import jsonify, request, send_file
|
||||||
|
|
||||||
from .core.bridge import serialize_memory
|
from .core.bridge import serialize_memory
|
||||||
|
from .core.coordination_status import build_coordination_status, project_p6_status
|
||||||
from .core.identity import normalize_session_context_fields, parse_scope_from_session
|
from .core.identity import normalize_session_context_fields, parse_scope_from_session
|
||||||
from .core.models import SessionContext, clean_text
|
from .core.models import SessionContext, clean_text
|
||||||
|
|
||||||
|
|
@ -78,6 +79,7 @@ class PluginPageApi:
|
||||||
("/config/module/update", self.config_module_update, ["POST"], "MemoryCompanion Page config module update"),
|
("/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"),
|
("/retrieval/config/update", self.retrieval_config_update, ["POST"], "MemoryCompanion Page retrieval config update"),
|
||||||
("/operations/diagnostics", self.operations_diagnostics, ["GET"], "MemoryCompanion operations diagnostics"),
|
("/operations/diagnostics", self.operations_diagnostics, ["GET"], "MemoryCompanion operations diagnostics"),
|
||||||
|
("/coordination/status", self.coordination_status, ["GET"], "MemoryCompanion safe coordination status"),
|
||||||
("/operations/preset", self.operations_preset, ["GET", "POST"], "MemoryCompanion operations preset"),
|
("/operations/preset", self.operations_preset, ["GET", "POST"], "MemoryCompanion operations preset"),
|
||||||
("/data/export", self.data_export, ["POST"], "MemoryCompanion portable data export"),
|
("/data/export", self.data_export, ["POST"], "MemoryCompanion portable data export"),
|
||||||
("/data/import/preview", self.data_import_preview, ["GET"], "MemoryCompanion portable data preview"),
|
("/data/import/preview", self.data_import_preview, ["GET"], "MemoryCompanion portable data preview"),
|
||||||
|
|
@ -91,6 +93,7 @@ class PluginPageApi:
|
||||||
("/conversation-import/resume", self.conversation_import_resume, ["POST"], "MemoryCompanion historical chat resume"),
|
("/conversation-import/resume", self.conversation_import_resume, ["POST"], "MemoryCompanion historical chat resume"),
|
||||||
("/conversation-import/rollback", self.conversation_import_rollback, ["POST"], "MemoryCompanion historical chat rollback"),
|
("/conversation-import/rollback", self.conversation_import_rollback, ["POST"], "MemoryCompanion historical chat rollback"),
|
||||||
("/profiles", self.profiles, ["GET"], "MemoryCompanion Bot Profiles"),
|
("/profiles", self.profiles, ["GET"], "MemoryCompanion Bot Profiles"),
|
||||||
|
("/user-memory-summary", self.user_memory_summary, ["GET"], "MemoryCompanion User Memory workspace summary"),
|
||||||
("/capabilities/bot-personal", self.bot_personal_capabilities, ["GET"], "MemoryCompanion Bot Personal capability"),
|
("/capabilities/bot-personal", self.bot_personal_capabilities, ["GET"], "MemoryCompanion Bot Personal capability"),
|
||||||
("/companion/personal-memory", self.companion_personal_memory, ["GET"], "MemoryCompanion Page companion personal memory"),
|
("/companion/personal-memory", self.companion_personal_memory, ["GET"], "MemoryCompanion Page companion personal memory"),
|
||||||
("/companion/personal-photo", self.companion_personal_photo, ["GET"], "MemoryCompanion Page companion personal photo"),
|
("/companion/personal-photo", self.companion_personal_photo, ["GET"], "MemoryCompanion Page companion personal photo"),
|
||||||
|
|
@ -133,6 +136,49 @@ class PluginPageApi:
|
||||||
)
|
)
|
||||||
return self._ok({"result": result})
|
return self._ok({"result": result})
|
||||||
|
|
||||||
|
async def user_memory_summary(self):
|
||||||
|
user_id = clean_text(request.args.get("user_id", ""), 120)
|
||||||
|
session_id = clean_text(request.args.get("session_id", ""), 200)
|
||||||
|
try:
|
||||||
|
limit = max(1, min(8, int(request.args.get("limit", "6"))))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
limit = 6
|
||||||
|
reader = getattr(getattr(self.plugin, "service", None), "read_user_memory_summary", None)
|
||||||
|
if not callable(reader):
|
||||||
|
result = {
|
||||||
|
"contract": "memory.user_memory_summary.v1",
|
||||||
|
"ok": False,
|
||||||
|
"read_only": True,
|
||||||
|
"state": "degraded",
|
||||||
|
"degraded": True,
|
||||||
|
"pending": True,
|
||||||
|
"user_id": user_id,
|
||||||
|
"session_id": session_id,
|
||||||
|
"counts": {"profile": 0, "preference": 0, "relationship": 0, "private_conversation": 0, "other": 0, "total": 0},
|
||||||
|
"summaries": [],
|
||||||
|
"workspace": {"kind": "memory_user_workspace", "route_hint": "user_memory", "user_id": user_id},
|
||||||
|
"error_code": "bridge_method_unavailable",
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
result = await reader(user_id, session_id=session_id, limit=limit)
|
||||||
|
except Exception:
|
||||||
|
result = {
|
||||||
|
"contract": "memory.user_memory_summary.v1",
|
||||||
|
"ok": False,
|
||||||
|
"read_only": True,
|
||||||
|
"state": "degraded",
|
||||||
|
"degraded": True,
|
||||||
|
"pending": True,
|
||||||
|
"user_id": user_id,
|
||||||
|
"session_id": session_id,
|
||||||
|
"counts": {"profile": 0, "preference": 0, "relationship": 0, "private_conversation": 0, "other": 0, "total": 0},
|
||||||
|
"summaries": [],
|
||||||
|
"workspace": {"kind": "memory_user_workspace", "route_hint": "user_memory", "user_id": user_id},
|
||||||
|
"error_code": "summary_unavailable",
|
||||||
|
}
|
||||||
|
return self._ok({"result": result})
|
||||||
|
|
||||||
async def bot_personal_capabilities(self):
|
async def bot_personal_capabilities(self):
|
||||||
getter = getattr(self.plugin, "bot_personal_capability_status", None)
|
getter = getattr(self.plugin, "bot_personal_capability_status", None)
|
||||||
result = getter() if callable(getter) else {
|
result = getter() if callable(getter) else {
|
||||||
|
|
@ -149,6 +195,56 @@ class PluginPageApi:
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
return self._err(f"运维诊断失败: {exc}", 500)
|
return self._err(f"运维诊断失败: {exc}", 500)
|
||||||
|
|
||||||
|
async def coordination_status(self):
|
||||||
|
"""Expose a fixed, read-only coordination projection."""
|
||||||
|
try:
|
||||||
|
service = getattr(self.plugin, "service", None)
|
||||||
|
p6_raw, bridge = self._companion_p6_status(service)
|
||||||
|
status = build_coordination_status(
|
||||||
|
config=getattr(service, "config", None),
|
||||||
|
runtime={"compatibility_level": "full"},
|
||||||
|
bridge=bridge,
|
||||||
|
p6_raw=p6_raw,
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
status = build_coordination_status(
|
||||||
|
config=None,
|
||||||
|
runtime=None,
|
||||||
|
bridge={"health": "unverifiable", "reason_code": "bridge_status_unavailable"},
|
||||||
|
p6_raw=None,
|
||||||
|
)
|
||||||
|
return self._ok({"status": status})
|
||||||
|
|
||||||
|
def _companion_p6_status(self, service: Any) -> tuple[Any, dict[str, str]]:
|
||||||
|
config = getattr(service, "config", None)
|
||||||
|
getter = getattr(config, "bool", None)
|
||||||
|
if not callable(getter):
|
||||||
|
return None, {"health": "unverifiable", "reason_code": "bridge_config_unavailable"}
|
||||||
|
try:
|
||||||
|
enabled = getter("private_companion_bridge.enabled", True)
|
||||||
|
except Exception:
|
||||||
|
return None, {"health": "unverifiable", "reason_code": "bridge_config_unreadable"}
|
||||||
|
if type(enabled) is not bool:
|
||||||
|
return None, {"health": "unverifiable", "reason_code": "bridge_config_invalid"}
|
||||||
|
if not enabled:
|
||||||
|
return None, {"health": "degraded", "reason_code": "bridge_disabled"}
|
||||||
|
companion = self._private_companion_status()
|
||||||
|
if type(companion) is not dict or companion.get("available") is not True:
|
||||||
|
return None, {"health": "unverifiable", "reason_code": "companion_api_unavailable"}
|
||||||
|
plugin = companion.get("plugin")
|
||||||
|
extension_api = getattr(plugin, "extension_api", None)
|
||||||
|
status_getter = getattr(extension_api, "get_p6_readonly_status", None)
|
||||||
|
if not callable(status_getter):
|
||||||
|
return None, {"health": "unverifiable", "reason_code": "companion_p6_producer_unavailable"}
|
||||||
|
try:
|
||||||
|
p6_raw = status_getter()
|
||||||
|
except Exception:
|
||||||
|
return None, {"health": "unverifiable", "reason_code": "companion_p6_producer_unreadable"}
|
||||||
|
p6 = project_p6_status(p6_raw)
|
||||||
|
if p6["health"] == "ready":
|
||||||
|
return p6_raw, {"health": "ready", "reason_code": "companion_bridge_available"}
|
||||||
|
return p6_raw, {"health": "degraded", "reason_code": "companion_p6_unverifiable"}
|
||||||
|
|
||||||
async def operations_preset(self):
|
async def operations_preset(self):
|
||||||
if request.method == "GET":
|
if request.method == "GET":
|
||||||
return self._ok({"preset": self.plugin.service.operation_preset_status()})
|
return self._ok({"preset": self.plugin.service.operation_preset_status()})
|
||||||
|
|
@ -287,10 +383,10 @@ class PluginPageApi:
|
||||||
return self._err(f"历史对话导入回滚失败: {exc}", 500)
|
return self._err(f"历史对话导入回滚失败: {exc}", 500)
|
||||||
|
|
||||||
async def persona_state(self):
|
async def persona_state(self):
|
||||||
"""Return persona state: relationship phases, emotional events, address evolution, cross-window state."""
|
"""Return read-only expression coordination and memory-touch diagnostics."""
|
||||||
try:
|
try:
|
||||||
service = self.plugin.service
|
service = self.plugin.service
|
||||||
phases: list[dict[str, Any]] = []
|
touch_trends: list[dict[str, Any]] = []
|
||||||
phase_state = getattr(service, "_relationship_phase_state", None)
|
phase_state = getattr(service, "_relationship_phase_state", None)
|
||||||
if isinstance(phase_state, dict):
|
if isinstance(phase_state, dict):
|
||||||
for key, state in phase_state.items():
|
for key, state in phase_state.items():
|
||||||
|
|
@ -306,19 +402,19 @@ class PluginPageApi:
|
||||||
member_id = clean_text(identity.get("member_id"), 120)
|
member_id = clean_text(identity.get("member_id"), 120)
|
||||||
if member_id:
|
if member_id:
|
||||||
identity_parts.append(f"member={member_id}")
|
identity_parts.append(f"member={member_id}")
|
||||||
phases.append({
|
raw_momentum = state.get("momentum", 0.0)
|
||||||
|
momentum = float(raw_momentum) if type(raw_momentum) in {int, float} else 0.0
|
||||||
|
trend_band = "rising" if momentum >= 0.08 else "cooling" if momentum <= -0.08 else "steady"
|
||||||
|
touch_trends.append({
|
||||||
"session_key": key,
|
"session_key": key,
|
||||||
"session_label": " / ".join(part for part in identity_parts if part) or key,
|
"session_label": " / ".join(part for part in identity_parts if part) or key,
|
||||||
"phase": state.get("phase", "acquaintance"),
|
"trend_band": trend_band,
|
||||||
"momentum": round(state.get("momentum", 0.0), 3),
|
|
||||||
"touch_count": state.get("touch_count", 0),
|
"touch_count": state.get("touch_count", 0),
|
||||||
"last_transition_at": state.get("last_transition_at", ""),
|
"legacy_context": clean_text(state.get("phase"), 40),
|
||||||
"updated_at": state.get("updated_at", ""),
|
"updated_at": state.get("updated_at", ""),
|
||||||
"current_address_phase": state.get("current_address_phase", ""),
|
|
||||||
"address_log": (state.get("address_log") or [])[-5:],
|
|
||||||
})
|
})
|
||||||
phases.sort(key=lambda p: p.get("updated_at", ""), reverse=True)
|
touch_trends.sort(key=lambda item: item.get("updated_at", ""), reverse=True)
|
||||||
pending_emotional_events: list[dict[str, Any]] = []
|
memory_touch_events: list[dict[str, Any]] = []
|
||||||
event_queue = getattr(service, "_emotional_event_queue", None)
|
event_queue = getattr(service, "_emotional_event_queue", None)
|
||||||
if isinstance(event_queue, dict):
|
if isinstance(event_queue, dict):
|
||||||
for session_id, queue in event_queue.items():
|
for session_id, queue in event_queue.items():
|
||||||
|
|
@ -327,7 +423,7 @@ class PluginPageApi:
|
||||||
for event in queue[-3:]:
|
for event in queue[-3:]:
|
||||||
if not isinstance(event, dict):
|
if not isinstance(event, dict):
|
||||||
continue
|
continue
|
||||||
pending_emotional_events.append({
|
memory_touch_events.append({
|
||||||
"session_id": session_id,
|
"session_id": session_id,
|
||||||
"event_type": event.get("event_type"),
|
"event_type": event.get("event_type"),
|
||||||
"energy_delta": event.get("energy_delta"),
|
"energy_delta": event.get("energy_delta"),
|
||||||
|
|
@ -341,24 +437,18 @@ class PluginPageApi:
|
||||||
cross_window_state: dict[str, Any] = {"total": 0, "scar_count": 0, "warm_count": 0, "vulnerable_count": 0}
|
cross_window_state: dict[str, Any] = {"total": 0, "scar_count": 0, "warm_count": 0, "vulnerable_count": 0}
|
||||||
if hasattr(service, "_get_cross_window_emotional_state"):
|
if hasattr(service, "_get_cross_window_emotional_state"):
|
||||||
cross_window_state = service._get_cross_window_emotional_state()
|
cross_window_state = service._get_cross_window_emotional_state()
|
||||||
phases_list = getattr(service, "_PHASES", ["acquaintance", "familiar", "close", "intimate", "deeply_bonded"])
|
|
||||||
thresholds = getattr(service, "_PHASE_THRESHOLDS", [0.0, 0.20, 0.45, 0.65, 0.85])
|
|
||||||
bot_suggestions = getattr(service, "_BOT_ADDRESS_SUGGESTIONS", {})
|
|
||||||
return self._ok({
|
return self._ok({
|
||||||
"phases": phases[:20],
|
"expression_coordination": {
|
||||||
"pending_emotional_events": pending_emotional_events[:15],
|
"contract": "companion_interaction_expression.v1",
|
||||||
|
"mode": "request_scoped_read_only",
|
||||||
|
"expression_authority": "private_companion",
|
||||||
|
"memory_role": "recall_visibility_and_mention_cap",
|
||||||
|
"persistent": False,
|
||||||
|
},
|
||||||
|
"memory_touch_trends": touch_trends[:20],
|
||||||
|
"memory_touch_events": memory_touch_events[:15],
|
||||||
"time_of_day": time_of_day,
|
"time_of_day": time_of_day,
|
||||||
"phase_definitions": {
|
|
||||||
"phases": phases_list,
|
|
||||||
"thresholds": thresholds,
|
|
||||||
},
|
|
||||||
"cross_window_emotional_state": cross_window_state,
|
"cross_window_emotional_state": cross_window_state,
|
||||||
"address_phase_labels": {
|
|
||||||
"formal": "正式",
|
|
||||||
"casual": "随意",
|
|
||||||
"intimate": "亲密",
|
|
||||||
"playful": "玩笑",
|
|
||||||
},
|
|
||||||
"time_of_day_labels": {
|
"time_of_day_labels": {
|
||||||
"late_night": "深夜",
|
"late_night": "深夜",
|
||||||
"dawn": "凌晨",
|
"dawn": "凌晨",
|
||||||
|
|
@ -367,8 +457,7 @@ class PluginPageApi:
|
||||||
"evening": "傍晚",
|
"evening": "傍晚",
|
||||||
"night": "夜间",
|
"night": "夜间",
|
||||||
},
|
},
|
||||||
"bot_address_suggestions": bot_suggestions,
|
"legacy_context_labels": {
|
||||||
"phase_labels": {
|
|
||||||
"acquaintance": "初识",
|
"acquaintance": "初识",
|
||||||
"familiar": "熟悉",
|
"familiar": "熟悉",
|
||||||
"close": "亲近",
|
"close": "亲近",
|
||||||
|
|
@ -377,7 +466,7 @@ class PluginPageApi:
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
return self._err(f"拟人维度数据读取失败: {exc}", 500)
|
return self._err(f"互动协同数据读取失败: {exc}", 500)
|
||||||
|
|
||||||
async def acl_matrix(self):
|
async def acl_matrix(self):
|
||||||
"""Return all windows, ACL rules and policies in one shot for topology visualization."""
|
"""Return all windows, ACL rules and policies in one shot for topology visualization."""
|
||||||
|
|
@ -717,7 +806,7 @@ class PluginPageApi:
|
||||||
return self._ok({"items": rows})
|
return self._ok({"items": rows})
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
logger.warning("[MemoryCompanion] timeline 端点异常: %s", exc, exc_info=True)
|
logger.warning("[MemoryCompanion] timeline 端点异常: %s", exc, exc_info=True)
|
||||||
return self._ok({"items": []})
|
return self._err("timeline_unavailable", 500)
|
||||||
|
|
||||||
async def relations(self):
|
async def relations(self):
|
||||||
try:
|
try:
|
||||||
|
|
@ -731,7 +820,7 @@ class PluginPageApi:
|
||||||
return self._ok({"items": rows})
|
return self._ok({"items": rows})
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
logger.warning("[MemoryCompanion] relations 端点异常: %s", exc, exc_info=True)
|
logger.warning("[MemoryCompanion] relations 端点异常: %s", exc, exc_info=True)
|
||||||
return self._ok({"items": []})
|
return self._err("relations_unavailable", 500)
|
||||||
|
|
||||||
async def graph(self):
|
async def graph(self):
|
||||||
try:
|
try:
|
||||||
|
|
@ -745,7 +834,7 @@ class PluginPageApi:
|
||||||
return self._ok({"items": rows})
|
return self._ok({"items": rows})
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
logger.warning("[MemoryCompanion] graph 端点异常: %s", exc, exc_info=True)
|
logger.warning("[MemoryCompanion] graph 端点异常: %s", exc, exc_info=True)
|
||||||
return self._ok({"items": []})
|
return self._err("graph_unavailable", 500)
|
||||||
|
|
||||||
async def threads(self):
|
async def threads(self):
|
||||||
try:
|
try:
|
||||||
|
|
@ -757,7 +846,7 @@ class PluginPageApi:
|
||||||
return self._ok({"items": rows})
|
return self._ok({"items": rows})
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
logger.warning("[MemoryCompanion] threads 端点异常: %s", exc, exc_info=True)
|
logger.warning("[MemoryCompanion] threads 端点异常: %s", exc, exc_info=True)
|
||||||
return self._ok({"items": []})
|
return self._err("threads_unavailable", 500)
|
||||||
|
|
||||||
async def thread_status(self):
|
async def thread_status(self):
|
||||||
payload = await self._json()
|
payload = await self._json()
|
||||||
|
|
@ -788,7 +877,7 @@ class PluginPageApi:
|
||||||
return self._ok({"items": rows})
|
return self._ok({"items": rows})
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
logger.warning("[MemoryCompanion] logs 端点异常: %s", exc, exc_info=True)
|
logger.warning("[MemoryCompanion] logs 端点异常: %s", exc, exc_info=True)
|
||||||
return self._ok({"items": []})
|
return self._err("logs_unavailable", 500)
|
||||||
|
|
||||||
async def context_config(self):
|
async def context_config(self):
|
||||||
config = self.plugin.service.config
|
config = self.plugin.service.config
|
||||||
|
|
|
||||||
|
|
@ -1493,6 +1493,33 @@ pre{white-space:pre-wrap;overflow-wrap:anywhere}
|
||||||
align-items:center;
|
align-items:center;
|
||||||
gap:8px;
|
gap:8px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.user-memory-filter{
|
||||||
|
display:flex;
|
||||||
|
flex-wrap:wrap;
|
||||||
|
gap:8px;
|
||||||
|
margin:0 0 14px;
|
||||||
|
padding:8px;
|
||||||
|
border:1px solid var(--line);
|
||||||
|
border-radius:14px;
|
||||||
|
background:color-mix(in srgb,var(--panel) 88%,transparent);
|
||||||
|
}
|
||||||
|
.user-memory-filter button{
|
||||||
|
min-height:34px;
|
||||||
|
padding:7px 13px;
|
||||||
|
border:1px solid transparent;
|
||||||
|
border-radius:999px;
|
||||||
|
background:transparent;
|
||||||
|
color:var(--muted);
|
||||||
|
cursor:pointer;
|
||||||
|
}
|
||||||
|
.user-memory-filter button:hover,
|
||||||
|
.user-memory-filter button.is-active{
|
||||||
|
border-color:color-mix(in srgb,var(--accent) 42%,var(--line));
|
||||||
|
background:color-mix(in srgb,var(--accent) 13%,var(--panel));
|
||||||
|
color:var(--text);
|
||||||
|
}
|
||||||
|
.compatibility-note{color:var(--muted);font-size:13px}
|
||||||
.scoped-clear-actions{
|
.scoped-clear-actions{
|
||||||
max-width:520px;
|
max-width:520px;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,10 +3,10 @@ const PAGE_ENDPOINT_PREFIX = "page";
|
||||||
const TRANSPARENT_IMAGE = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
|
const TRANSPARENT_IMAGE = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
|
||||||
|
|
||||||
const VIEWS = {
|
const VIEWS = {
|
||||||
objects: { title: "知识图谱", hint: "查看关系边、跨窗口线程、时间线、记忆节点和拟人维度概览。" },
|
objects: { title: "知识图谱", hint: "查看关系边、跨窗口线程、时间线、记忆节点和互动协同概览。" },
|
||||||
film: { title: "群聊记忆", hint: "查看群聊范围内可召回、可管理的结构化记忆。" },
|
film: { title: "群聊记忆", hint: "查看群聊范围内可召回、可管理的结构化记忆。" },
|
||||||
microscope: { title: "记忆显微镜", hint: "对比全库管理检索与指定会话中的实际召回和过滤。" },
|
microscope: { title: "记忆显微镜", hint: "对比全库管理检索与指定会话中的实际召回和过滤。" },
|
||||||
relations: { title: "用户记忆", hint: "聚焦用户画像、偏好、称呼和关系声明。" },
|
relations: { title: "用户档案与记忆", hint: "按用户统一查看私聊、画像、偏好、称呼和关系记忆。" },
|
||||||
review: { title: "个人记忆", hint: "查看 Bot 自身的每日生活日程、相册、主观记忆和细化片段。" },
|
review: { title: "个人记忆", hint: "查看 Bot 自身的每日生活日程、相册、主观记忆和细化片段。" },
|
||||||
archive: { title: "维护 / 迁移 / 配置", hint: "执行维护、迁移、清理和导入修复。" },
|
archive: { title: "维护 / 迁移 / 配置", hint: "执行维护、迁移、清理和导入修复。" },
|
||||||
maintain: { title: "私聊记忆", hint: "查看私聊范围内的对话、偏好、事实和稳定记忆。" },
|
maintain: { title: "私聊记忆", hint: "查看私聊范围内的对话、偏好、事实和稳定记忆。" },
|
||||||
|
|
@ -36,20 +36,13 @@ const SECONDARY_NAV = {
|
||||||
{ id: "relations", label: "图谱边", sublabel: "人物、话题、事实与记忆关联", badge: "图谱" },
|
{ id: "relations", label: "图谱边", sublabel: "人物、话题、事实与记忆关联", badge: "图谱" },
|
||||||
{ id: "threads", label: "跨窗口线程", sublabel: "不同私聊/群聊之间的待办线索", badge: "线程" },
|
{ id: "threads", label: "跨窗口线程", sublabel: "不同私聊/群聊之间的待办线索", badge: "线程" },
|
||||||
{ id: "timeline", label: "时间线", sublabel: "最近记录的事件节点", badge: "时间" },
|
{ id: "timeline", label: "时间线", sublabel: "最近记录的事件节点", badge: "时间" },
|
||||||
{ id: "persona", label: "拟人维度", sublabel: "关系阶段 · 情绪连续性 · 称呼演进", badge: "拟人" },
|
{ id: "persona", label: "互动协同", sublabel: "表达权威 · 记忆触动 · 情绪连续性", badge: "协同" },
|
||||||
],
|
],
|
||||||
microscope: [
|
microscope: [
|
||||||
{ id: "query", label: "召回测试", sublabel: "输入一句话模拟检索", badge: "测试" },
|
{ id: "query", label: "召回测试", sublabel: "输入一句话模拟检索", badge: "测试" },
|
||||||
{ id: "hits", label: "命中记忆", sublabel: "查看检索结果", badge: "命中" },
|
{ id: "hits", label: "命中记忆", sublabel: "查看检索结果", badge: "命中" },
|
||||||
{ id: "blocked", label: "过滤原因", sublabel: "查看被挡下的记忆", badge: "过滤" },
|
{ id: "blocked", label: "过滤原因", sublabel: "查看被挡下的记忆", badge: "过滤" },
|
||||||
],
|
],
|
||||||
relations: [
|
|
||||||
{ id: "all", label: "全部用户记忆", sublabel: "画像、偏好与关系", badge: "全部" },
|
|
||||||
{ id: "profile", label: "用户画像", sublabel: "稳定画像片段", badge: "画像" },
|
|
||||||
{ id: "preference", label: "偏好", sublabel: "喜好、习惯、倾向", badge: "偏好" },
|
|
||||||
{ id: "relationship", label: "关系声明", sublabel: "身份和关系线索", badge: "关系" },
|
|
||||||
{ id: "explicit", label: "明确记住", sublabel: "用户主动要求记住", badge: "记住" },
|
|
||||||
],
|
|
||||||
archive: [
|
archive: [
|
||||||
{ id: "maintenance", label: "维护 / 迁移 / 清理", sublabel: "维护、修复、导入与清理", badge: "维护" },
|
{ id: "maintenance", label: "维护 / 迁移 / 清理", sublabel: "维护、修复、导入与清理", badge: "维护" },
|
||||||
{ id: "conversation-import", label: "历史聊天导入", sublabel: "QQ 直读、文件与最近任务", badge: "导入" },
|
{ id: "conversation-import", label: "历史聊天导入", sublabel: "QQ 直读、文件与最近任务", badge: "导入" },
|
||||||
|
|
@ -60,7 +53,7 @@ const SECONDARY_NAV = {
|
||||||
{ id: "retrieval", label: "检索召回", sublabel: "候选、Embedding、Rerank", badge: "召回" },
|
{ id: "retrieval", label: "检索召回", sublabel: "候选、Embedding、Rerank", badge: "召回" },
|
||||||
{ id: "config:memory_injection", label: "记忆注入", sublabel: "注入数量、字数与日志", badge: "注入" },
|
{ id: "config:memory_injection", label: "记忆注入", sublabel: "注入数量、字数与日志", badge: "注入" },
|
||||||
{ id: "config:context_orchestration", label: "注入编排", sublabel: "分槽调度与当前状态保护", badge: "编排" },
|
{ id: "config:context_orchestration", label: "注入编排", sublabel: "分槽调度与当前状态保护", badge: "编排" },
|
||||||
{ id: "config:private_companion_bridge", label: "陪伴协同", sublabel: "桥接、去重与提示清理", badge: "联动" },
|
{ id: "config:private_companion_bridge", label: "记忆插件协同", sublabel: "与陪伴插件桥接、去重和清理提示", badge: "联动" },
|
||||||
{ id: "config:visibility", label: "可见性", sublabel: "跨窗口默认边界", badge: "权限" },
|
{ id: "config:visibility", label: "可见性", sublabel: "跨窗口默认边界", badge: "权限" },
|
||||||
{ id: "topology", label: "权限拓扑", sublabel: "可视化记忆权限矩阵", badge: "拓扑" },
|
{ id: "topology", label: "权限拓扑", sublabel: "可视化记忆权限矩阵", badge: "拓扑" },
|
||||||
{ id: "config:knowledge_graph", label: "图谱关联", sublabel: "节点、边与检索扩展", badge: "图谱" },
|
{ id: "config:knowledge_graph", label: "图谱关联", sublabel: "节点、边与检索扩展", badge: "图谱" },
|
||||||
|
|
@ -166,6 +159,7 @@ const state = {
|
||||||
overviewLayout: document.documentElement.dataset.overviewLayout === "cinema" ? "cinema" : "standard",
|
overviewLayout: document.documentElement.dataset.overviewLayout === "cinema" ? "cinema" : "standard",
|
||||||
activeView: "objects",
|
activeView: "objects",
|
||||||
activeBucketId: "all",
|
activeBucketId: "all",
|
||||||
|
userMemoryFilter: "all",
|
||||||
microscopeBucketId: "all",
|
microscopeBucketId: "all",
|
||||||
microscopeSearchToken: 0,
|
microscopeSearchToken: 0,
|
||||||
bucketLoadToken: 0,
|
bucketLoadToken: 0,
|
||||||
|
|
@ -192,6 +186,8 @@ const state = {
|
||||||
historicalChatPreviewSource: "",
|
historicalChatPreviewSource: "",
|
||||||
historicalChatBatchId: "",
|
historicalChatBatchId: "",
|
||||||
historicalChatPollTimer: 0,
|
historicalChatPollTimer: 0,
|
||||||
|
historicalChatPollAttempts: 0,
|
||||||
|
historicalChatPollStartedAt: 0,
|
||||||
historicalChatFile: null,
|
historicalChatFile: null,
|
||||||
conversationImportSource: "qq",
|
conversationImportSource: "qq",
|
||||||
qqHistoryCapabilities: null,
|
qqHistoryCapabilities: null,
|
||||||
|
|
@ -493,7 +489,21 @@ async function httpRequest(path, method, body) {
|
||||||
headers: body ? { "Content-Type": "application/json" } : undefined,
|
headers: body ? { "Content-Type": "application/json" } : undefined,
|
||||||
body: body ? JSON.stringify(body) : undefined,
|
body: body ? JSON.stringify(body) : undefined,
|
||||||
});
|
});
|
||||||
return response.json();
|
let data = null;
|
||||||
|
try {
|
||||||
|
data = await response.json();
|
||||||
|
} catch (error) {
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`请求失败(HTTP ${response.status})`);
|
||||||
|
}
|
||||||
|
throw new Error("页面 API 返回了无效 JSON");
|
||||||
|
}
|
||||||
|
if (!response.ok || data?.success === false) {
|
||||||
|
const error = new Error(data?.error || `请求失败(HTTP ${response.status})`);
|
||||||
|
error.status = response.status;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
function sleep(ms) {
|
function sleep(ms) {
|
||||||
|
|
@ -1207,18 +1217,21 @@ function bindBucketListInteractions() {
|
||||||
|
|
||||||
function currentRailScope() {
|
function currentRailScope() {
|
||||||
if (state.activeView === "film") return "group";
|
if (state.activeView === "film") return "group";
|
||||||
|
if (state.activeView === "relations") return "private";
|
||||||
if (state.activeView === "maintain") return "private";
|
if (state.activeView === "maintain") return "private";
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
function scopedViewScope(view = state.activeView) {
|
function scopedViewScope(view = state.activeView) {
|
||||||
if (view === "film") return "group";
|
if (view === "film") return "group";
|
||||||
|
if (view === "relations") return "private";
|
||||||
if (view === "maintain") return "private";
|
if (view === "maintain") return "private";
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
function scopedViewTarget(view = state.activeView) {
|
function scopedViewTarget(view = state.activeView) {
|
||||||
if (view === "film") return "#groupMemoryList";
|
if (view === "film") return "#groupMemoryList";
|
||||||
|
if (view === "relations") return "#relationList";
|
||||||
if (view === "maintain") return "#privateMemoryList";
|
if (view === "maintain") return "#privateMemoryList";
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
|
|
@ -1226,15 +1239,15 @@ function scopedViewTarget(view = state.activeView) {
|
||||||
function renderScopedModeControls(view = state.activeView) {
|
function renderScopedModeControls(view = state.activeView) {
|
||||||
const scope = scopedViewScope(view);
|
const scope = scopedViewScope(view);
|
||||||
if (!scope) return;
|
if (!scope) return;
|
||||||
const title = view === "film" ? $("#groupMemoryTitle") : $("#privateMemoryTitle");
|
const title = view === "film" ? $("#groupMemoryTitle") : view === "relations" ? $("#userMemoryTitle") : $("#privateMemoryTitle");
|
||||||
const hint = view === "film" ? $("#groupMemoryHint") : $("#privateMemoryHint");
|
const hint = view === "film" ? $("#groupMemoryHint") : view === "relations" ? $("#userMemoryHint") : $("#privateMemoryHint");
|
||||||
if (title) title.textContent = `${windowKindLabel(scope)}记忆`;
|
if (title) title.textContent = view === "relations" ? "用户档案与记忆" : `${windowKindLabel(scope)}记忆`;
|
||||||
if (hint) hint.textContent = VIEWS[view]?.hint || "";
|
if (hint) hint.textContent = VIEWS[view]?.hint || "";
|
||||||
updateScopedClearButton(view);
|
updateScopedClearButton(view);
|
||||||
}
|
}
|
||||||
|
|
||||||
function updateScopedClearButton(view = state.activeView) {
|
function updateScopedClearButton(view = state.activeView) {
|
||||||
const button = view === "film" ? $("#clearCurrentGroupMemoryBtn") : view === "maintain" ? $("#clearCurrentPrivateMemoryBtn") : null;
|
const button = view === "film" ? $("#clearCurrentGroupMemoryBtn") : ["relations", "maintain"].includes(view) ? $("#clearCurrentPrivateMemoryBtn") : null;
|
||||||
const bucket = activeBucket();
|
const bucket = activeBucket();
|
||||||
const scope = scopedViewScope(view);
|
const scope = scopedViewScope(view);
|
||||||
const canClear = Boolean(bucket && bucket.id !== "all" && bucket.scope === scope && bucket.target_id);
|
const canClear = Boolean(bucket && bucket.id !== "all" && bucket.scope === scope && bucket.target_id);
|
||||||
|
|
@ -1720,6 +1733,11 @@ async function playRailRefreshTransition(task) {
|
||||||
}
|
}
|
||||||
|
|
||||||
async function openView(view, { preserveBucket = false } = {}) {
|
async function openView(view, { preserveBucket = false } = {}) {
|
||||||
|
if (view === "maintain") {
|
||||||
|
view = "relations";
|
||||||
|
state.userMemoryFilter = "private";
|
||||||
|
preserveBucket = true;
|
||||||
|
}
|
||||||
const app = $("#app");
|
const app = $("#app");
|
||||||
const wasWorkspace = app.classList.contains("is-workspace");
|
const wasWorkspace = app.classList.contains("is-workspace");
|
||||||
const switchingWorkspaceView = wasWorkspace && state.activeView !== view;
|
const switchingWorkspaceView = wasWorkspace && state.activeView !== view;
|
||||||
|
|
@ -1759,7 +1777,7 @@ async function openView(view, { preserveBucket = false } = {}) {
|
||||||
renderScopedModeControls(view);
|
renderScopedModeControls(view);
|
||||||
if (view === "film") {
|
if (view === "film") {
|
||||||
renderScopedBucketRail("group");
|
renderScopedBucketRail("group");
|
||||||
} else if (view === "maintain") {
|
} else if (view === "relations" || view === "maintain") {
|
||||||
renderScopedBucketRail("private");
|
renderScopedBucketRail("private");
|
||||||
} else if (view !== "review") {
|
} else if (view !== "review") {
|
||||||
renderSecondaryNav(view, !switchingWorkspaceView);
|
renderSecondaryNav(view, !switchingWorkspaceView);
|
||||||
|
|
@ -1991,14 +2009,30 @@ function renderMemoryList(selector, memories, emptyText) {
|
||||||
}
|
}
|
||||||
|
|
||||||
function relationTypesForSecondary() {
|
function relationTypesForSecondary() {
|
||||||
const active = activeSecondaryNav("relations");
|
const active = state.userMemoryFilter || "all";
|
||||||
const map = {
|
const map = {
|
||||||
profile: ["user_profile"],
|
profile: ["user_profile"],
|
||||||
preference: ["user_preference"],
|
preference: ["user_preference"],
|
||||||
relationship: ["relationship_claim"],
|
relationship: ["relationship_claim"],
|
||||||
explicit: ["explicit_memory"],
|
explicit: ["explicit_memory"],
|
||||||
};
|
};
|
||||||
return map[active] || ["user_profile", "user_preference", "explicit_memory", "relationship_claim"];
|
return map[active] || [];
|
||||||
|
}
|
||||||
|
|
||||||
|
function syncUserMemoryFilterControls() {
|
||||||
|
$$('[data-user-memory-filter]').forEach((button) => {
|
||||||
|
if (!button.closest('#view-relations')) return;
|
||||||
|
const active = button.dataset.userMemoryFilter === state.userMemoryFilter;
|
||||||
|
button.classList.toggle('is-active', active);
|
||||||
|
button.setAttribute('aria-selected', active ? 'true' : 'false');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function selectUserMemoryFilter(filter) {
|
||||||
|
const allowed = new Set(['all', 'profile', 'preference', 'relationship', 'explicit', 'private']);
|
||||||
|
state.userMemoryFilter = allowed.has(filter) ? filter : 'all';
|
||||||
|
syncUserMemoryFilterControls();
|
||||||
|
if (state.activeView === 'relations') await loadUserMemory();
|
||||||
}
|
}
|
||||||
|
|
||||||
async function loadScopedMemories(selector, scope, loadingText, emptyText, extra = {}) {
|
async function loadScopedMemories(selector, scope, loadingText, emptyText, extra = {}) {
|
||||||
|
|
@ -2074,20 +2108,34 @@ async function loadContextPanel() {
|
||||||
apiGet(`/timeline?${params.toString()}`),
|
apiGet(`/timeline?${params.toString()}`),
|
||||||
apiGet(`/logs?${params.toString()}`),
|
apiGet(`/logs?${params.toString()}`),
|
||||||
]);
|
]);
|
||||||
const settled = (idx) => results[idx].status === "fulfilled" ? (results[idx].value?.items || []) : [];
|
const settled = (idx) => {
|
||||||
const failures = results.filter(r => r.status === "rejected");
|
const result = results[idx];
|
||||||
|
if (result.status === "fulfilled") {
|
||||||
|
return { items: Array.isArray(result.value?.items) ? result.value.items : [], error: "" };
|
||||||
|
}
|
||||||
|
return { items: [], error: result.reason?.message || "读取失败,请稍后重试" };
|
||||||
|
};
|
||||||
|
const sections = results.map((_, idx) => settled(idx));
|
||||||
|
const failures = sections.filter((item) => item.error);
|
||||||
if (failures.length === results.length) {
|
if (failures.length === results.length) {
|
||||||
throw results[0].reason || new Error("所有知识图谱 API 请求失败");
|
throw results[0].reason || new Error("所有知识图谱 API 请求失败");
|
||||||
}
|
}
|
||||||
target.innerHTML = renderKnowledgeOverview({
|
target.innerHTML = renderKnowledgeOverview({
|
||||||
graph: settled(0),
|
graph: sections[0].items,
|
||||||
relations: settled(1),
|
relations: sections[1].items,
|
||||||
threads: settled(2),
|
threads: sections[2].items,
|
||||||
timeline: settled(3),
|
timeline: sections[3].items,
|
||||||
logs: settled(4),
|
logs: sections[4].items,
|
||||||
|
errors: {
|
||||||
|
graph: sections[0].error,
|
||||||
|
relations: sections[1].error,
|
||||||
|
threads: sections[2].error,
|
||||||
|
timeline: sections[3].error,
|
||||||
|
logs: sections[4].error,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
if (failures.length > 0) {
|
if (failures.length > 0) {
|
||||||
const failedNames = ["图谱边", "身份关系", "跨窗口线程", "时间线", "注入日志"].filter((_, i) => results[i].status === "rejected");
|
const failedNames = ["图谱边", "身份关系", "跨窗口线程", "时间线", "注入日志"].filter((_, i) => sections[i].error);
|
||||||
showToast(`${failedNames.join("、")}加载失败,已显示可用数据`, "error");
|
showToast(`${failedNames.join("、")}加载失败,已显示可用数据`, "error");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -2107,7 +2155,16 @@ function rawAttr(value) {
|
||||||
return escapeHtml(JSON.stringify(value || {}));
|
return escapeHtml(JSON.stringify(value || {}));
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderKnowledgeOverview({ graph = [], relations = [], threads = [], timeline = [], logs = [] } = {}) {
|
function renderContextPanelErrors(errors = {}) {
|
||||||
|
const labels = { graph: "图谱边", relations: "身份关系", threads: "跨窗口线程", timeline: "时间线", logs: "注入日志" };
|
||||||
|
const rows = Object.entries(errors)
|
||||||
|
.filter(([, message]) => message)
|
||||||
|
.map(([key, message]) => `<div class="empty-state error-state"><b>${escapeHtml(labels[key] || key)}读取失败</b><span>${escapeHtml(message)}</span></div>`)
|
||||||
|
.join("");
|
||||||
|
return rows ? `<section class="context-section film-panel"><h4>部分数据暂不可用</h4>${rows}</section>` : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderKnowledgeOverview({ graph = [], relations = [], threads = [], timeline = [], logs = [], errors = {} } = {}) {
|
||||||
const activeThreads = threads.filter((item) => (item.status || "open") === "open").length;
|
const activeThreads = threads.filter((item) => (item.status || "open") === "open").length;
|
||||||
return `
|
return `
|
||||||
<section class="context-section film-panel">
|
<section class="context-section film-panel">
|
||||||
|
|
@ -2119,6 +2176,7 @@ function renderKnowledgeOverview({ graph = [], relations = [], threads = [], tim
|
||||||
${configCard("时间线节点", `${timeline.length} 条`, "最近记录的事件、消息和整理结果", "blue", "时间")}
|
${configCard("时间线节点", `${timeline.length} 条`, "最近记录的事件、消息和整理结果", "blue", "时间")}
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
${renderContextPanelErrors(errors)}
|
||||||
${renderKnowledgeGraphEdges(graph, "最近图谱边")}
|
${renderKnowledgeGraphEdges(graph, "最近图谱边")}
|
||||||
${renderKnowledgeRelations(relations, "最近身份关系")}
|
${renderKnowledgeRelations(relations, "最近身份关系")}
|
||||||
${renderKnowledgeThreads(threads, "最近跨窗口线程")}
|
${renderKnowledgeThreads(threads, "最近跨窗口线程")}
|
||||||
|
|
@ -2392,10 +2450,25 @@ function renderContextLogs(logs) {
|
||||||
async function loadUserMemory() {
|
async function loadUserMemory() {
|
||||||
const target = $("#relationList");
|
const target = $("#relationList");
|
||||||
if (!target) return;
|
if (!target) return;
|
||||||
target.innerHTML = loadingState("正在读取用户记忆...");
|
syncUserMemoryFilterControls();
|
||||||
|
target.innerHTML = loadingState("正在读取用户档案与记忆...");
|
||||||
const types = relationTypesForSecondary();
|
const types = relationTypesForSecondary();
|
||||||
const memories = (await loadMemories({ limit: 160 })).filter((memory) => hasMemoryType(memory, types));
|
const { params, incompatible } = scopedMemoryParams("private", { limit: 180 });
|
||||||
renderMemoryList("#relationList", memories, "当前范围还没有用户画像、偏好或关系声明。");
|
if (incompatible) {
|
||||||
|
target.innerHTML = '<div class="empty-state">当前对象不是私聊用户,请从左侧选择用户。</div>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 用户工作区按精确用户身份聚合其全部私聊窗口;会话 ID 只用于旧私聊入口,
|
||||||
|
// 不能把同一用户在其他私聊窗口中的画像/偏好切掉。
|
||||||
|
if (activeBucket()?.target_id) params.delete("session_id");
|
||||||
|
const data = await apiGet(`/memories?${params.toString()}`);
|
||||||
|
const allMemories = data.memories || [];
|
||||||
|
let memories = allMemories;
|
||||||
|
if (types.length) memories = allMemories.filter((memory) => hasMemoryType(memory, types));
|
||||||
|
if (state.userMemoryFilter === 'private') {
|
||||||
|
memories = allMemories.filter((memory) => memory.scope === 'private');
|
||||||
|
}
|
||||||
|
renderMemoryList("#relationList", memories, "当前用户在这个分类下还没有记忆。");
|
||||||
}
|
}
|
||||||
|
|
||||||
async function loadPersonalMemory() {
|
async function loadPersonalMemory() {
|
||||||
|
|
@ -4405,7 +4478,7 @@ function renderMemoryStructuredMetadata(memory) {
|
||||||
<div class="memory-diagnostics-grid">
|
<div class="memory-diagnostics-grid">
|
||||||
${policy ? `<span><em>策略</em><strong>${escapeHtml(mentionPolicyLabel(policy))}</strong></span>` : ""}
|
${policy ? `<span><em>策略</em><strong>${escapeHtml(mentionPolicyLabel(policy))}</strong></span>` : ""}
|
||||||
${mentionability !== undefined && mentionability !== null ? `<span><em>可提及性</em><strong>${escapeHtml(percentLabel(mentionability))}</strong></span>` : ""}
|
${mentionability !== undefined && mentionability !== null ? `<span><em>可提及性</em><strong>${escapeHtml(percentLabel(mentionability))}</strong></span>` : ""}
|
||||||
${phase ? `<span><em>关系阶段</em><strong>${escapeHtml(phase)}</strong></span>` : ""}
|
${phase ? `<span><em>当时关系情境</em><strong>${escapeHtml(phase)}</strong></span>` : ""}
|
||||||
${decayMode ? `<span><em>衰减</em><strong>${escapeHtml(decayModeLabel(decayMode))}</strong></span>` : ""}
|
${decayMode ? `<span><em>衰减</em><strong>${escapeHtml(decayModeLabel(decayMode))}</strong></span>` : ""}
|
||||||
${feedback.last_reaction ? `<span><em>上次反馈</em><strong>${escapeHtml(reactionLabel(feedback.last_reaction))}</strong></span>` : ""}
|
${feedback.last_reaction ? `<span><em>上次反馈</em><strong>${escapeHtml(reactionLabel(feedback.last_reaction))}</strong></span>` : ""}
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -5569,7 +5642,16 @@ async function refreshHistoricalChatStatus() {
|
||||||
|
|
||||||
function scheduleHistoricalChatPoll() {
|
function scheduleHistoricalChatPoll() {
|
||||||
stopHistoricalChatPoll();
|
stopHistoricalChatPoll();
|
||||||
|
state.historicalChatPollAttempts = 0;
|
||||||
|
state.historicalChatPollStartedAt = Date.now();
|
||||||
state.historicalChatPollTimer = window.setInterval(() => {
|
state.historicalChatPollTimer = window.setInterval(() => {
|
||||||
|
state.historicalChatPollAttempts += 1;
|
||||||
|
const elapsed = Date.now() - state.historicalChatPollStartedAt;
|
||||||
|
if (state.historicalChatPollAttempts > 120 || elapsed > 10 * 60 * 1000) {
|
||||||
|
stopHistoricalChatPoll();
|
||||||
|
showToast("历史导入轮询已达到上限,请手动刷新任务状态", "error");
|
||||||
|
return;
|
||||||
|
}
|
||||||
refreshHistoricalChatStatus().catch(() => stopHistoricalChatPoll());
|
refreshHistoricalChatStatus().catch(() => stopHistoricalChatPoll());
|
||||||
}, 3000);
|
}, 3000);
|
||||||
}
|
}
|
||||||
|
|
@ -5577,6 +5659,7 @@ function scheduleHistoricalChatPoll() {
|
||||||
function stopHistoricalChatPoll() {
|
function stopHistoricalChatPoll() {
|
||||||
if (state.historicalChatPollTimer) window.clearInterval(state.historicalChatPollTimer);
|
if (state.historicalChatPollTimer) window.clearInterval(state.historicalChatPollTimer);
|
||||||
state.historicalChatPollTimer = 0;
|
state.historicalChatPollTimer = 0;
|
||||||
|
state.historicalChatPollStartedAt = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
function historicalChatSegmentStatusLabel(value) {
|
function historicalChatSegmentStatusLabel(value) {
|
||||||
|
|
@ -5668,7 +5751,7 @@ function renderHistoricalChatStatus(result) {
|
||||||
<span>重要事件 ${number(memoryCounts.important_event)}</span>
|
<span>重要事件 ${number(memoryCounts.important_event)}</span>
|
||||||
<span>日摘要 ${number(memoryCounts.daily_digest)}</span>
|
<span>日摘要 ${number(memoryCounts.daily_digest)}</span>
|
||||||
<span>稳定事实 ${number(memoryCounts.stable_fact)}</span>
|
<span>稳定事实 ${number(memoryCounts.stable_fact)}</span>
|
||||||
<span>阶段摘要 ${number(memoryCounts.relationship_phase_summary)}</span>
|
<span>相处经历摘要 ${number(memoryCounts.relationship_phase_summary)}</span>
|
||||||
</div>
|
</div>
|
||||||
` : ""}
|
` : ""}
|
||||||
${batch.stats?.embedding?.enabled ? `<small class="chat-import-embedding-note">向量索引 ${number(batch.stats.embedding.indexed)}/${number(batch.stats.embedding.eligible)} · ${escapeHtml(batch.stats.embedding.status || "处理中")}</small>` : ""}
|
${batch.stats?.embedding?.enabled ? `<small class="chat-import-embedding-note">向量索引 ${number(batch.stats.embedding.indexed)}/${number(batch.stats.embedding.eligible)} · ${escapeHtml(batch.stats.embedding.status || "处理中")}</small>` : ""}
|
||||||
|
|
@ -5976,6 +6059,7 @@ function bindActions() {
|
||||||
if (!button || !$("#standardOverview").contains(button)) return;
|
if (!button || !$("#standardOverview").contains(button)) return;
|
||||||
const view = button.dataset.overviewView;
|
const view = button.dataset.overviewView;
|
||||||
if (!VIEWS[view]) return;
|
if (!VIEWS[view]) return;
|
||||||
|
if (button.dataset.userMemoryFilter) state.userMemoryFilter = button.dataset.userMemoryFilter;
|
||||||
const bucketId = button.dataset.overviewBucket || "";
|
const bucketId = button.dataset.overviewBucket || "";
|
||||||
if (bucketId && state.buckets.some((bucket) => bucket.id === bucketId)) {
|
if (bucketId && state.buckets.some((bucket) => bucket.id === bucketId)) {
|
||||||
state.activeBucketId = bucketId;
|
state.activeBucketId = bucketId;
|
||||||
|
|
@ -6021,7 +6105,10 @@ function bindActions() {
|
||||||
strip.style.transition = "transform .95s cubic-bezier(.18,.88,.22,1)";
|
strip.style.transition = "transform .95s cubic-bezier(.18,.88,.22,1)";
|
||||||
strip.style.transform = `rotate(${ang}deg) translateY(${off}px) translateX(${initialAxis}px)`;
|
strip.style.transform = `rotate(${ang}deg) translateY(${off}px) translateX(${initialAxis}px)`;
|
||||||
});
|
});
|
||||||
strip.addEventListener("click", () => openView(strip.dataset.view));
|
strip.addEventListener("click", () => {
|
||||||
|
if (strip.dataset.userMemoryFilter) state.userMemoryFilter = strip.dataset.userMemoryFilter;
|
||||||
|
openView(strip.dataset.view);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
$("#backHomeBtn").addEventListener("click", returnHome);
|
$("#backHomeBtn").addEventListener("click", returnHome);
|
||||||
$("#refreshBtn").addEventListener("click", () => playRailRefreshTransition(refreshAll));
|
$("#refreshBtn").addEventListener("click", () => playRailRefreshTransition(refreshAll));
|
||||||
|
|
@ -6038,6 +6125,10 @@ function bindActions() {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
$("#runSearchBtn").addEventListener("click", runSearch);
|
$("#runSearchBtn").addEventListener("click", runSearch);
|
||||||
|
$$('[data-user-memory-filter]').forEach((button) => {
|
||||||
|
if (!button.closest('#view-relations')) return;
|
||||||
|
button.addEventListener('click', () => selectUserMemoryFilter(button.dataset.userMemoryFilter));
|
||||||
|
});
|
||||||
$("#microscopeContext")?.addEventListener("change", (event) => {
|
$("#microscopeContext")?.addEventListener("change", (event) => {
|
||||||
state.microscopeBucketId = event.currentTarget.value || "all";
|
state.microscopeBucketId = event.currentTarget.value || "all";
|
||||||
updateMicroscopeContextMeta();
|
updateMicroscopeContextMeta();
|
||||||
|
|
@ -6136,7 +6227,7 @@ function bindActions() {
|
||||||
async function loadPersonaState() {
|
async function loadPersonaState() {
|
||||||
const panel = $("#personaStatePanel");
|
const panel = $("#personaStatePanel");
|
||||||
if (!panel) return;
|
if (!panel) return;
|
||||||
panel.innerHTML = `<div class="persona-loading">正在读取拟人维度数据...</div>`;
|
panel.innerHTML = `<div class="persona-loading">正在读取互动协同数据...</div>`;
|
||||||
let data;
|
let data;
|
||||||
try {
|
try {
|
||||||
data = await apiGet("/persona-state");
|
data = await apiGet("/persona-state");
|
||||||
|
|
@ -6148,17 +6239,13 @@ async function loadPersonaState() {
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderPersonaState(d) {
|
function renderPersonaState(d) {
|
||||||
const phases = d.phases || [];
|
const coordination = d.expression_coordination || {};
|
||||||
const events = d.pending_emotional_events || [];
|
const trends = d.memory_touch_trends || [];
|
||||||
|
const events = d.memory_touch_events || [];
|
||||||
const crossState = d.cross_window_emotional_state || {};
|
const crossState = d.cross_window_emotional_state || {};
|
||||||
const timeOfDay = d.time_of_day || "";
|
const timeOfDay = d.time_of_day || "";
|
||||||
const phaseLabels = d.phase_labels || {};
|
const legacyLabels = d.legacy_context_labels || {};
|
||||||
const addressLabels = d.address_phase_labels || {};
|
|
||||||
const timeLabels = d.time_of_day_labels || {};
|
const timeLabels = d.time_of_day_labels || {};
|
||||||
const botAddress = d.bot_address_suggestions || {};
|
|
||||||
const phaseDefs = d.phase_definitions || {};
|
|
||||||
const allPhases = phaseDefs.phases || ["acquaintance", "familiar", "close", "intimate", "deeply_bonded"];
|
|
||||||
const thresholds = phaseDefs.thresholds || [0.0, 0.20, 0.45, 0.65, 0.85];
|
|
||||||
|
|
||||||
const timeLabel = timeLabels[timeOfDay] || timeOfDay || "未知";
|
const timeLabel = timeLabels[timeOfDay] || timeOfDay || "未知";
|
||||||
const crossTotal = crossState.total || 0;
|
const crossTotal = crossState.total || 0;
|
||||||
|
|
@ -6168,7 +6255,26 @@ function renderPersonaState(d) {
|
||||||
|
|
||||||
let html = '<div class="persona-grid">';
|
let html = '<div class="persona-grid">';
|
||||||
|
|
||||||
// 1. Time-of-day and cross-window summary card
|
html += `
|
||||||
|
<div class="persona-card persona-card-wide">
|
||||||
|
<div class="persona-card-head">
|
||||||
|
<b>陪伴表达协同状态</b>
|
||||||
|
<span class="persona-badge">只读</span>
|
||||||
|
</div>
|
||||||
|
<div class="persona-card-body">
|
||||||
|
<div class="persona-cross-window">
|
||||||
|
<span class="persona-cw-label">最终语气、称呼、互动档位由陪伴插件统一决定</span>
|
||||||
|
<div class="persona-cw-stats">
|
||||||
|
<span class="persona-cw-stat is-active">${escapeHtml(coordination.contract || "未检测到合同")}</span>
|
||||||
|
<span class="persona-cw-stat">请求级消费</span>
|
||||||
|
<span class="persona-cw-stat">不持久化表达状态</span>
|
||||||
|
</div>
|
||||||
|
<small class="persona-cw-empty">记忆插件只负责事实、可见性、召回和记忆提及上限,不会建立第二套好感度、互动状态或称呼系统。</small>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
|
||||||
html += `
|
html += `
|
||||||
<div class="persona-card persona-card-wide">
|
<div class="persona-card persona-card-wide">
|
||||||
<div class="persona-card-head">
|
<div class="persona-card-head">
|
||||||
|
|
@ -6190,38 +6296,37 @@ function renderPersonaState(d) {
|
||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
|
|
||||||
// 2. Relationship phases
|
if (trends.length === 0) {
|
||||||
if (phases.length === 0) {
|
|
||||||
html += `
|
html += `
|
||||||
<div class="persona-card persona-card-wide">
|
<div class="persona-card persona-card-wide">
|
||||||
<div class="persona-card-head"><b>关系阶段</b></div>
|
<div class="persona-card-head"><b>记忆触动趋势</b></div>
|
||||||
<div class="persona-card-body">
|
<div class="persona-card-body">
|
||||||
<p class="persona-empty">还没有足够的关系互动数据。随着对话积累,关系阶段会自然演进。</p>
|
<p class="persona-empty">暂无历史记忆触动记录。该区域只反映记忆被触动的趋势,不代表当前好感度或互动状态。</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
} else {
|
} else {
|
||||||
html += `
|
html += `
|
||||||
<div class="persona-card persona-card-wide">
|
<div class="persona-card persona-card-wide">
|
||||||
<div class="persona-card-head"><b>关系阶段演进</b><span class="persona-badge">${phases.length} 个会话</span></div>
|
<div class="persona-card-head"><b>记忆触动趋势</b><span class="persona-badge">${trends.length} 个会话</span></div>
|
||||||
<div class="persona-card-body">
|
<div class="persona-card-body">
|
||||||
<div class="persona-phase-list">
|
<div class="persona-phase-list">
|
||||||
${phases.map(p => renderPersonaPhaseItem(p, allPhases, thresholds, phaseLabels, addressLabels, botAddress)).join('')}
|
${trends.map(item => renderMemoryTouchTrend(item, legacyLabels)).join('')}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Pending emotional events
|
|
||||||
if (events.length > 0) {
|
if (events.length > 0) {
|
||||||
html += `
|
html += `
|
||||||
<div class="persona-card persona-card-wide">
|
<div class="persona-card persona-card-wide">
|
||||||
<div class="persona-card-head"><b>情绪事件队列</b><span class="persona-badge">${events.length} 条待处理</span></div>
|
<div class="persona-card-head"><b>记忆触动事件</b><span class="persona-badge">${events.length} 条待处理</span></div>
|
||||||
<div class="persona-card-body">
|
<div class="persona-card-body">
|
||||||
<div class="persona-event-list">
|
<div class="persona-event-list">
|
||||||
${events.map(e => renderPersonaEventItem(e)).join('')}
|
${events.map(e => renderPersonaEventItem(e)).join('')}
|
||||||
</div>
|
</div>
|
||||||
|
<small class="persona-cw-empty">这些事件只作为陪伴插件 Bot 心情与精力的输入,最终表达仍由陪伴插件裁决。</small>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
|
|
@ -6231,80 +6336,38 @@ function renderPersonaState(d) {
|
||||||
return html;
|
return html;
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderPersonaPhaseItem(p, allPhases, thresholds, phaseLabels, addressLabels, botAddress) {
|
function renderMemoryTouchTrend(p, legacyLabels) {
|
||||||
const phase = p.phase || 'acquaintance';
|
const trend = p.trend_band || 'steady';
|
||||||
const momentum = p.momentum || 0;
|
const trendLabels = { rising: '升温触动', steady: '平稳触动', cooling: '降温触动' };
|
||||||
const phaseLabel = phaseLabels[phase] || phase;
|
const trendLabel = trendLabels[trend] || trend;
|
||||||
|
const trendPercent = trend === 'rising' ? 82 : trend === 'cooling' ? 24 : 52;
|
||||||
|
const trendClass = trend === 'rising' ? 'is-high' : trend === 'cooling' ? 'is-low' : 'is-mid';
|
||||||
const touchCount = p.touch_count || 0;
|
const touchCount = p.touch_count || 0;
|
||||||
const addressPhase = p.current_address_phase || '';
|
const legacyContext = p.legacy_context || '';
|
||||||
const addressLabel = addressLabels[addressPhase] || '';
|
const legacyLabel = legacyLabels[legacyContext] || legacyContext;
|
||||||
const updatedAt = p.updated_at || '';
|
const updatedAt = p.updated_at || '';
|
||||||
const sessionKey = p.session_label || p.session_key || '';
|
const sessionKey = p.session_label || p.session_key || '';
|
||||||
const shortSession = sessionKey.length > 40 ? sessionKey.slice(0, 37) + '...' : sessionKey;
|
const shortSession = sessionKey.length > 40 ? sessionKey.slice(0, 37) + '...' : sessionKey;
|
||||||
|
|
||||||
// Find current phase index for progress bar
|
|
||||||
const phaseIdx = allPhases.indexOf(phase);
|
|
||||||
const phasePercent = phaseIdx >= 0 ? ((phaseIdx + 1) / allPhases.length) * 100 : 20;
|
|
||||||
|
|
||||||
// Momentum bar: map [-0.3, 1.0] to [0%, 100%]
|
|
||||||
const momentumPercent = Math.max(0, Math.min(100, ((momentum + 0.3) / 1.3) * 100));
|
|
||||||
const momentumClass = momentum >= 0.45 ? 'is-high' : momentum >= 0.15 ? 'is-mid' : momentum < 0 ? 'is-low' : '';
|
|
||||||
|
|
||||||
// Bot address suggestion
|
|
||||||
const botSuggestion = botAddress[phase] || {};
|
|
||||||
const botTone = botSuggestion.tone || '';
|
|
||||||
const botHint = botSuggestion.hint || '';
|
|
||||||
|
|
||||||
// Address log
|
|
||||||
const addressLog = p.address_log || [];
|
|
||||||
const hasAddressLog = addressLog.length > 0;
|
|
||||||
|
|
||||||
return `
|
return `
|
||||||
<div class="persona-phase-item">
|
<div class="persona-phase-item">
|
||||||
<div class="persona-phase-header">
|
<div class="persona-phase-header">
|
||||||
<div class="persona-phase-info">
|
<div class="persona-phase-info">
|
||||||
<span class="persona-phase-name">${escapeHtml(phaseLabel)}</span>
|
<span class="persona-phase-name">${escapeHtml(trendLabel)}</span>
|
||||||
<small class="persona-phase-session">${escapeHtml(shortSession)}</small>
|
<small class="persona-phase-session">${escapeHtml(shortSession)}</small>
|
||||||
</div>
|
</div>
|
||||||
<div class="persona-phase-meta">
|
<div class="persona-phase-meta">
|
||||||
<span class="persona-phase-touch">${touchCount} 次触动</span>
|
<span class="persona-phase-touch">${touchCount} 次触动</span>
|
||||||
${addressLabel ? `<span class="persona-phase-address">称呼:${escapeHtml(addressLabel)}</span>` : ''}
|
${legacyLabel ? `<span class="persona-phase-address">历史情境:${escapeHtml(legacyLabel)}</span>` : ''}
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="persona-phase-progress">
|
|
||||||
<div class="persona-phase-bar">
|
|
||||||
<div class="persona-phase-bar-fill" style="width:${phasePercent}%"></div>
|
|
||||||
</div>
|
|
||||||
<div class="persona-phase-steps">
|
|
||||||
${allPhases.map((ph, i) => `<span class="persona-phase-step ${i <= phaseIdx ? 'is-active' : ''}">${escapeHtml(phaseLabels[ph] || ph)}</span>`).join('')}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="persona-momentum">
|
<div class="persona-momentum">
|
||||||
<span class="persona-momentum-label">动量</span>
|
<span class="persona-momentum-label">触动趋势</span>
|
||||||
<div class="persona-momentum-bar">
|
<div class="persona-momentum-bar">
|
||||||
<div class="persona-momentum-fill ${momentumClass}" style="width:${momentumPercent}%"></div>
|
<div class="persona-momentum-fill ${trendClass}" style="width:${trendPercent}%"></div>
|
||||||
</div>
|
</div>
|
||||||
<span class="persona-momentum-value">${momentum.toFixed(3)}</span>
|
<span class="persona-momentum-value">${escapeHtml(trendLabel)}</span>
|
||||||
</div>
|
</div>
|
||||||
${botTone ? `
|
|
||||||
<div class="persona-bot-address">
|
|
||||||
<span class="persona-bot-tone">${escapeHtml(botTone)}</span>
|
|
||||||
${botHint ? `<small class="persona-bot-hint">${escapeHtml(botHint)}</small>` : ''}
|
|
||||||
</div>
|
|
||||||
` : ''}
|
|
||||||
${hasAddressLog ? `
|
|
||||||
<details class="persona-address-log">
|
|
||||||
<summary>称呼演变记录 (${addressLog.length})</summary>
|
|
||||||
<div class="persona-address-timeline">
|
|
||||||
${addressLog.map(log => `
|
|
||||||
<div class="persona-address-entry">
|
|
||||||
<span class="persona-address-time">${escapeHtml((log.ts || '').slice(0, 16))}</span>
|
|
||||||
<span class="persona-address-change">${escapeHtml(addressLabels[log.previous] || log.previous || '—')} → ${escapeHtml(addressLabels[log.phase] || log.phase || '')}</span>
|
|
||||||
</div>
|
|
||||||
`).join('')}
|
|
||||||
</div>
|
|
||||||
</details>
|
|
||||||
` : ''}
|
|
||||||
${updatedAt ? `<small class="persona-phase-updated">更新于 ${escapeHtml(updatedAt.slice(0, 16))}</small>` : ''}
|
${updatedAt ? `<small class="persona-phase-updated">更新于 ${escapeHtml(updatedAt.slice(0, 16))}</small>` : ''}
|
||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
|
|
|
||||||
|
|
@ -17,7 +17,7 @@
|
||||||
document.documentElement.dataset.overviewLayout = layout;
|
document.documentElement.dataset.overviewLayout = layout;
|
||||||
})();
|
})();
|
||||||
</script>
|
</script>
|
||||||
<link rel="stylesheet" href="./app.css?v=1.6.5" />
|
<link rel="stylesheet" href="./app.css?v=1.6.6" />
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<main id="app" class="film-app">
|
<main id="app" class="film-app">
|
||||||
|
|
@ -33,7 +33,7 @@
|
||||||
|
|
||||||
<header class="topbar">
|
<header class="topbar">
|
||||||
<div>
|
<div>
|
||||||
<p class="eyebrow">我会牢牢记住你</p>
|
<p class="eyebrow">雪色的记忆插件-聊天侧</p>
|
||||||
<h1>记忆放映馆</h1>
|
<h1>记忆放映馆</h1>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
@ -65,12 +65,12 @@
|
||||||
<p class="eyebrow">Workspace</p>
|
<p class="eyebrow">Workspace</p>
|
||||||
<h2 id="overviewDestinationsTitle">功能入口</h2>
|
<h2 id="overviewDestinationsTitle">功能入口</h2>
|
||||||
</div>
|
</div>
|
||||||
<span>7 个工作区</span>
|
<span>6 个工作区 · 1 个兼容入口</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="overview-entry-grid">
|
<div class="overview-entry-grid">
|
||||||
<button class="overview-entry is-private" data-overview-view="maintain" type="button">
|
<button class="overview-entry is-private" data-overview-view="relations" data-user-memory-filter="private" type="button">
|
||||||
<span class="overview-entry-index">01</span>
|
<span class="overview-entry-index">01</span>
|
||||||
<span class="overview-entry-copy"><b>私聊记忆</b><small>对话 · 偏好 · 稳定事实</small></span>
|
<span class="overview-entry-copy"><b>用户档案与记忆</b><small>私聊 · 画像 · 偏好 · 关系</small></span>
|
||||||
<span class="overview-entry-arrow" aria-hidden="true">›</span>
|
<span class="overview-entry-arrow" aria-hidden="true">›</span>
|
||||||
</button>
|
</button>
|
||||||
<button class="overview-entry is-group" data-overview-view="film" type="button">
|
<button class="overview-entry is-group" data-overview-view="film" type="button">
|
||||||
|
|
@ -78,9 +78,9 @@
|
||||||
<span class="overview-entry-copy"><b>群聊记忆</b><small>群聊 · 成员 · 上下文</small></span>
|
<span class="overview-entry-copy"><b>群聊记忆</b><small>群聊 · 成员 · 上下文</small></span>
|
||||||
<span class="overview-entry-arrow" aria-hidden="true">›</span>
|
<span class="overview-entry-arrow" aria-hidden="true">›</span>
|
||||||
</button>
|
</button>
|
||||||
<button class="overview-entry is-user" data-overview-view="relations" type="button">
|
<button class="overview-entry is-user" data-overview-view="relations" data-user-memory-filter="all" type="button">
|
||||||
<span class="overview-entry-index">03</span>
|
<span class="overview-entry-index">03</span>
|
||||||
<span class="overview-entry-copy"><b>用户记忆</b><small>画像 · 偏好 · 关系</small></span>
|
<span class="overview-entry-copy"><b>用户档案与记忆</b><small>按用户统一查看全部记忆</small></span>
|
||||||
<span class="overview-entry-arrow" aria-hidden="true">›</span>
|
<span class="overview-entry-arrow" aria-hidden="true">›</span>
|
||||||
</button>
|
</button>
|
||||||
<button class="overview-entry is-personal" data-overview-view="review" type="button">
|
<button class="overview-entry is-personal" data-overview-view="review" type="button">
|
||||||
|
|
@ -140,10 +140,10 @@
|
||||||
<button class="filmstrip" style="--a:-18deg;--z:2;--off:240px" data-view="objects" data-tip-title="知识图谱" data-tip-sub="关系 · 线程 · 时间线" type="button"><span class="strip-label"><b>知识图谱</b><small>关系 · 节点</small></span></button>
|
<button class="filmstrip" style="--a:-18deg;--z:2;--off:240px" data-view="objects" data-tip-title="知识图谱" data-tip-sub="关系 · 线程 · 时间线" type="button"><span class="strip-label"><b>知识图谱</b><small>关系 · 节点</small></span></button>
|
||||||
<button class="filmstrip" style="--a:76deg; --z:4;--off:-200px" data-view="film" data-tip-title="群聊记忆" data-tip-sub="群聊范围内的记忆" type="button"><span class="strip-label"><b>群聊记忆</b><small>群聊 · 记忆</small></span></button>
|
<button class="filmstrip" style="--a:76deg; --z:4;--off:-200px" data-view="film" data-tip-title="群聊记忆" data-tip-sub="群聊范围内的记忆" type="button"><span class="strip-label"><b>群聊记忆</b><small>群聊 · 记忆</small></span></button>
|
||||||
<button class="filmstrip" style="--a:44deg; --z:7;--off:260px" data-view="microscope" data-tip-title="记忆显微镜" data-tip-sub="模拟召回 · 检查注入" type="button"><span class="strip-label" style="--label-edge:-260px"><b>记忆显微镜</b><small>模拟召回</small></span></button>
|
<button class="filmstrip" style="--a:44deg; --z:7;--off:260px" data-view="microscope" data-tip-title="记忆显微镜" data-tip-sub="模拟召回 · 检查注入" type="button"><span class="strip-label" style="--label-edge:-260px"><b>记忆显微镜</b><small>模拟召回</small></span></button>
|
||||||
<button class="filmstrip" style="--a:14deg; --z:5;--off:-225px;--tx:-440px" data-view="relations" data-tip-title="用户记忆" data-tip-sub="用户画像 · 偏好 · 关系" type="button"><span class="strip-label" style="--label-edge:380px"><b>用户记忆</b><small>画像 · 偏好</small></span></button>
|
<button class="filmstrip" style="--a:14deg; --z:5;--off:-225px;--tx:-440px" data-view="relations" data-user-memory-filter="all" data-tip-title="用户档案与记忆" data-tip-sub="私聊 · 画像 · 偏好 · 关系" type="button"><span class="strip-label" style="--label-edge:380px"><b>用户档案与记忆</b><small>按用户统一查看</small></span></button>
|
||||||
<button class="filmstrip" style="--a:162deg;--z:1;--off:215px;--tx:-260px" data-view="review" data-tip-title="个人记忆" data-tip-sub="Bot 日程 · 生活细化" type="button"><span class="strip-label is-flipped"><b>个人记忆</b><small>日程 · 细化</small></span></button>
|
<button class="filmstrip" style="--a:162deg;--z:1;--off:215px;--tx:-260px" data-view="review" data-tip-title="个人记忆" data-tip-sub="Bot 日程 · 生活细化" type="button"><span class="strip-label is-flipped"><b>个人记忆</b><small>日程 · 细化</small></span></button>
|
||||||
<button class="filmstrip" style="--a:136deg;--z:3;--off:-390px" data-view="archive" data-tip-title="维护/迁移/配置" data-tip-sub="工具 · 迁移 · 配置" type="button"><span class="strip-label is-flipped"><b>维护/迁移/配置</b><small>工具 · 配置</small></span></button>
|
<button class="filmstrip" style="--a:136deg;--z:3;--off:-390px" data-view="archive" data-tip-title="维护/迁移/配置" data-tip-sub="工具 · 迁移 · 配置" type="button"><span class="strip-label is-flipped"><b>维护/迁移/配置</b><small>工具 · 配置</small></span></button>
|
||||||
<button class="filmstrip" style="--a:106deg;--z:6;--off:220px" data-view="maintain" data-tip-title="私聊记忆" data-tip-sub="私聊范围内的记忆" type="button"><span class="strip-label is-flipped"><b>私聊记忆</b><small>私聊 · 记忆</small></span></button>
|
<button class="filmstrip" style="--a:106deg;--z:6;--off:220px" data-view="relations" data-user-memory-filter="private" data-tip-title="私聊记忆(兼容入口)" data-tip-sub="进入用户档案与记忆" type="button"><span class="strip-label is-flipped"><b>私聊记忆</b><small>进入统一工作区</small></span></button>
|
||||||
|
|
||||||
<section class="overview-core" aria-live="polite">
|
<section class="overview-core" aria-live="polite">
|
||||||
<div class="core-ring"></div>
|
<div class="core-ring"></div>
|
||||||
|
|
@ -242,8 +242,19 @@
|
||||||
|
|
||||||
<section id="view-relations" class="view">
|
<section id="view-relations" class="view">
|
||||||
<div class="section-head">
|
<div class="section-head">
|
||||||
<h3>用户记忆</h3>
|
<div>
|
||||||
<p>聚焦用户画像、偏好、称呼、关系声明等以用户为核心的记忆。</p>
|
<h3 id="userMemoryTitle">用户档案与记忆</h3>
|
||||||
|
<p id="userMemoryHint">选择左侧用户后,在同一工作区查看私聊、画像、偏好和关系记忆。</p>
|
||||||
|
</div>
|
||||||
|
<button id="clearCurrentPrivateMemoryBtn" class="danger subtle" type="button" disabled>清空当前用户</button>
|
||||||
|
</div>
|
||||||
|
<div class="user-memory-filter" role="tablist" aria-label="用户记忆分类">
|
||||||
|
<button class="is-active" data-user-memory-filter="all" type="button" role="tab" aria-selected="true">全部</button>
|
||||||
|
<button data-user-memory-filter="profile" type="button" role="tab" aria-selected="false">画像</button>
|
||||||
|
<button data-user-memory-filter="preference" type="button" role="tab" aria-selected="false">偏好</button>
|
||||||
|
<button data-user-memory-filter="relationship" type="button" role="tab" aria-selected="false">关系</button>
|
||||||
|
<button data-user-memory-filter="explicit" type="button" role="tab" aria-selected="false">明确记住</button>
|
||||||
|
<button data-user-memory-filter="private" type="button" role="tab" aria-selected="false">私聊记忆</button>
|
||||||
</div>
|
</div>
|
||||||
<div id="relationList" class="row-list"></div>
|
<div id="relationList" class="row-list"></div>
|
||||||
</section>
|
</section>
|
||||||
|
|
@ -262,7 +273,7 @@
|
||||||
<h3 id="privateMemoryTitle">私聊记忆</h3>
|
<h3 id="privateMemoryTitle">私聊记忆</h3>
|
||||||
<p id="privateMemoryHint">查看私聊范围内的对话、偏好、事实和稳定记忆。</p>
|
<p id="privateMemoryHint">查看私聊范围内的对话、偏好、事实和稳定记忆。</p>
|
||||||
</div>
|
</div>
|
||||||
<button id="clearCurrentPrivateMemoryBtn" class="danger subtle" type="button" disabled>清空当前用户</button>
|
<span class="compatibility-note">此旧入口已合并到“用户档案与记忆”。</span>
|
||||||
</div>
|
</div>
|
||||||
<div id="privateMemoryList" class="row-list"></div>
|
<div id="privateMemoryList" class="row-list"></div>
|
||||||
</section>
|
</section>
|
||||||
|
|
@ -461,6 +472,6 @@ Bot: 12-14 15:10:30
|
||||||
<div id="toast" class="toast" role="status" aria-live="polite"></div>
|
<div id="toast" class="toast" role="status" aria-live="polite"></div>
|
||||||
</main>
|
</main>
|
||||||
<script src="/api/plugin/page/bridge-sdk.js"></script>
|
<script src="/api/plugin/page/bridge-sdk.js"></script>
|
||||||
<script src="./app.js?v=1.6.5"></script>
|
<script src="./app.js?v=1.6.6"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|
|
||||||
|
|
@ -41,20 +41,21 @@ def test_probe_returns_ready_contract_snapshot_without_plugin_or_database_access
|
||||||
assert result["max_payload_bytes"] == bot_personal_contract.BOT_PERSONAL_MAX_PAYLOAD_BYTES
|
assert result["max_payload_bytes"] == bot_personal_contract.BOT_PERSONAL_MAX_PAYLOAD_BYTES
|
||||||
|
|
||||||
|
|
||||||
def test_probe_returns_stable_degraded_shape_when_contract_self_check_fails(monkeypatch):
|
def test_probe_returns_stable_negative_shape_when_contract_self_check_fails(monkeypatch):
|
||||||
monkeypatch.setattr(bot_personal_contract, "contract_self_check", lambda: ["contract_fingerprint_stale: hidden"])
|
monkeypatch.setattr(bot_personal_contract, "contract_self_check", lambda: ["contract_fingerprint_stale: hidden"])
|
||||||
|
|
||||||
result = MemoryCompanionBridge(_PluginMustNotBeTouched()).probe_bot_personal_memory_capabilities()
|
result = MemoryCompanionBridge(_PluginMustNotBeTouched()).probe_bot_personal_memory_capabilities()
|
||||||
|
|
||||||
assert result["available"] is False
|
assert result["available"] is False
|
||||||
assert result["state"] == "degraded"
|
assert result["state"] == "negative"
|
||||||
|
assert result["capability_state"] == "negative"
|
||||||
assert result["degraded"] is True
|
assert result["degraded"] is True
|
||||||
assert "contract_self_check_failed" in result["warnings"]
|
assert "contract_self_check_failed" in result["warnings"]
|
||||||
assert "contract_fingerprint_stale" in result["warnings"]
|
assert "contract_fingerprint_stale" in result["warnings"]
|
||||||
assert "hidden" not in result["warnings"]
|
assert "hidden" not in result["warnings"]
|
||||||
|
|
||||||
|
|
||||||
def test_probe_converts_contract_check_exception_to_degraded_result(monkeypatch):
|
def test_probe_converts_contract_check_exception_to_negative_result(monkeypatch):
|
||||||
def broken_check():
|
def broken_check():
|
||||||
raise RuntimeError("raw prompt, user identity, session content, database object")
|
raise RuntimeError("raw prompt, user identity, session content, database object")
|
||||||
|
|
||||||
|
|
@ -63,7 +64,8 @@ def test_probe_converts_contract_check_exception_to_degraded_result(monkeypatch)
|
||||||
result = MemoryCompanionBridge(_PluginMustNotBeTouched()).probe_bot_personal_memory_capabilities()
|
result = MemoryCompanionBridge(_PluginMustNotBeTouched()).probe_bot_personal_memory_capabilities()
|
||||||
|
|
||||||
assert result["available"] is False
|
assert result["available"] is False
|
||||||
assert result["state"] == "degraded"
|
assert result["state"] == "negative"
|
||||||
|
assert result["capability_state"] == "negative"
|
||||||
assert result["degraded"] is True
|
assert result["degraded"] is True
|
||||||
assert result["warnings"] == ["contract_self_check_exception"]
|
assert result["warnings"] == ["contract_self_check_exception"]
|
||||||
assert all(secret not in str(result) for secret in ("raw prompt", "user identity", "database object"))
|
assert all(secret not in str(result) for secret in ("raw prompt", "user identity", "database object"))
|
||||||
|
|
|
||||||
129
tests/test_c5_bridge_gate.py
普通文件
129
tests/test_c5_bridge_gate.py
普通文件
|
|
@ -0,0 +1,129 @@
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
from pathlib import Path
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
COMPANION_ROOT = Path(__file__).resolve().parents[2] / "astrbot_plugin_private_companion-main" / "astrbot_plugin_private_companion-main"
|
||||||
|
if str(COMPANION_ROOT) not in sys.path:
|
||||||
|
sys.path.insert(0, str(COMPANION_ROOT))
|
||||||
|
|
||||||
|
from p5_attestation import P5AttestationRegistry # noqa: E402
|
||||||
|
|
||||||
|
from core.config import ConfigView # noqa: E402
|
||||||
|
from core.provenance_store import ProvenanceLedger # noqa: E402
|
||||||
|
from core.service import MemoryCompanionService # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
def run(coro):
|
||||||
|
return asyncio.run(coro)
|
||||||
|
|
||||||
|
|
||||||
|
def make_service(*, bridge_gate: bool = True, recall_gate: bool = True):
|
||||||
|
service = object.__new__(MemoryCompanionService)
|
||||||
|
service.config = ConfigView(
|
||||||
|
{
|
||||||
|
"private_companion_bridge": {
|
||||||
|
"enable_p5_b1_bridge_gate": bridge_gate,
|
||||||
|
"enable_p5_b1_recall_gate": recall_gate,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
service._last_p5_gate_status = {}
|
||||||
|
return service
|
||||||
|
|
||||||
|
|
||||||
|
def mint(registry, *, request, event, p3, source_kind="current_user_intent", trust="T2", disposition="allow", sink="bridge_serialization"):
|
||||||
|
handle = registry.mint(
|
||||||
|
request,
|
||||||
|
event,
|
||||||
|
p3,
|
||||||
|
request_hash="a" * 64,
|
||||||
|
session_hash="b" * 64,
|
||||||
|
source_kind=source_kind,
|
||||||
|
source_trust=trust,
|
||||||
|
firewall_status="allowed",
|
||||||
|
disposition=disposition,
|
||||||
|
reason_codes=("evidence_only_nonexecuting",) if disposition == "allow" else ("untrusted_source_shadowed", "p5_nonexecuting"),
|
||||||
|
source_event_ref_hash="c" * 64,
|
||||||
|
sinks=(sink,),
|
||||||
|
)
|
||||||
|
return handle, lambda candidate, requested_sink=sink: registry.consume(candidate, request, event, p3, requested_sink)
|
||||||
|
|
||||||
|
|
||||||
|
class C5BridgeGateTests(unittest.TestCase):
|
||||||
|
def test_bridge_gate_accepts_current_user_attestation_and_rejects_replay(self):
|
||||||
|
service = make_service()
|
||||||
|
registry = P5AttestationRegistry()
|
||||||
|
request, event, p3 = object(), object(), object()
|
||||||
|
handle, consumer = mint(registry, request=request, event=event, p3=p3)
|
||||||
|
allowed = run(service._p5_gate(sink="bridge_serialization", attestation=handle, consumer=consumer))
|
||||||
|
replay = run(service._p5_gate(sink="bridge_serialization", attestation=handle, consumer=consumer))
|
||||||
|
self.assertTrue(allowed["ok"])
|
||||||
|
self.assertEqual(allowed["state"], "allowed")
|
||||||
|
self.assertFalse(replay["ok"])
|
||||||
|
self.assertEqual(replay["error_code"], "p5_attestation_invalid")
|
||||||
|
|
||||||
|
def test_shadow_source_is_not_allowed_to_expand_recall(self):
|
||||||
|
service = make_service()
|
||||||
|
registry = P5AttestationRegistry()
|
||||||
|
request, event, p3 = object(), object(), object()
|
||||||
|
handle, consumer = mint(
|
||||||
|
registry,
|
||||||
|
request=request,
|
||||||
|
event=event,
|
||||||
|
p3=p3,
|
||||||
|
source_kind="forwarded_text",
|
||||||
|
trust="T3",
|
||||||
|
disposition="shadow_quarantine",
|
||||||
|
)
|
||||||
|
result = run(service._p5_gate(sink="bridge_serialization", attestation=handle, consumer=consumer))
|
||||||
|
self.assertFalse(result["ok"])
|
||||||
|
self.assertEqual(result["state"], "shadow")
|
||||||
|
|
||||||
|
def test_disabled_gate_preserves_legacy_behavior(self):
|
||||||
|
service = make_service(bridge_gate=False, recall_gate=False)
|
||||||
|
result = run(service._p5_gate(sink="memory_recall"))
|
||||||
|
self.assertEqual(result, {"ok": True, "state": "legacy", "legacy": True, "enabled": False})
|
||||||
|
|
||||||
|
def test_ledger_preview_apply_backup_and_cas_rollback(self):
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
ledger = ProvenanceLedger(Path(directory) / "provenance_ledger.json")
|
||||||
|
preview = ledger.preview_legacy(
|
||||||
|
[{"memory_id": "memory-1", "record_revision": 0}],
|
||||||
|
operation_ref_hash="d" * 64,
|
||||||
|
)
|
||||||
|
self.assertTrue(preview["readonly"])
|
||||||
|
self.assertEqual(preview["write_count"], 0)
|
||||||
|
operation = preview["operations"][0]
|
||||||
|
applied = ledger.apply(operation)
|
||||||
|
self.assertTrue(applied["ok"])
|
||||||
|
self.assertEqual(applied["status"], "applied")
|
||||||
|
self.assertTrue(ledger.backup()["created"])
|
||||||
|
self.assertEqual(ledger.snapshot()["records"]["memory-1"]["provenance_state"], "legacy_unresolved")
|
||||||
|
conflict = ledger.rollback({**operation, "after_record_digest": "e" * 64})
|
||||||
|
self.assertFalse(conflict["ok"])
|
||||||
|
rolled_back = ledger.rollback(operation)
|
||||||
|
self.assertTrue(rolled_back["ok"])
|
||||||
|
self.assertEqual(rolled_back["status"], "rolled_back")
|
||||||
|
|
||||||
|
def test_dual_plugin_snapshot_is_recorded_without_raw_payload(self):
|
||||||
|
service = make_service(bridge_gate=True, recall_gate=False)
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
service.provenance_ledger = ProvenanceLedger(Path(directory) / "provenance_ledger.json")
|
||||||
|
registry = P5AttestationRegistry()
|
||||||
|
request, event, p3 = object(), object(), object()
|
||||||
|
handle, consumer = mint(registry, request=request, event=event, p3=p3)
|
||||||
|
gate = run(service._p5_gate(sink="bridge_serialization", attestation=handle, consumer=consumer))
|
||||||
|
result = run(service._p5_record_observed(["memory-1"], gate["snapshot"]))
|
||||||
|
snapshot = service.provenance_snapshot()
|
||||||
|
self.assertTrue(result["ok"])
|
||||||
|
self.assertEqual(snapshot["records"]["memory-1"]["provenance_state"], "observed")
|
||||||
|
self.assertNotIn("content", str(snapshot))
|
||||||
|
self.assertNotIn("prompt", str(snapshot))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
140
tests/test_c5_provenance.py
普通文件
140
tests/test_c5_provenance.py
普通文件
|
|
@ -0,0 +1,140 @@
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import copy
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from core.provenance import (
|
||||||
|
ATTESTATION_SCHEMA_VERSION,
|
||||||
|
COMPANION_ATTESTATION_ISSUER,
|
||||||
|
P3_CONTRACT_FINGERPRINT,
|
||||||
|
P3_CONTRACT_NAME,
|
||||||
|
P3_CONTRACT_VERSION,
|
||||||
|
PROVENANCE_CONTRACT_NAME,
|
||||||
|
PROVENANCE_CONTRACT_VERSION,
|
||||||
|
apply_planned_operation,
|
||||||
|
contract_descriptor,
|
||||||
|
contract_fingerprint,
|
||||||
|
legacy_unresolved,
|
||||||
|
observed_from_companion_snapshot,
|
||||||
|
plan_legacy_migration,
|
||||||
|
rollback_planned_operation,
|
||||||
|
validate_provenance_record,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _hash(value: str) -> str:
|
||||||
|
return hashlib.sha256(value.encode("utf-8")).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def _snapshot(**overrides: object) -> dict[str, object]:
|
||||||
|
value: dict[str, object] = {
|
||||||
|
"schema_version": ATTESTATION_SCHEMA_VERSION,
|
||||||
|
"contract_name": PROVENANCE_CONTRACT_NAME,
|
||||||
|
"contract_version": PROVENANCE_CONTRACT_VERSION,
|
||||||
|
"contract_fingerprint": contract_fingerprint(),
|
||||||
|
"issuer": COMPANION_ATTESTATION_ISSUER,
|
||||||
|
"issuer_epoch": _hash("issuer-epoch"),
|
||||||
|
"p3_contract_name": P3_CONTRACT_NAME,
|
||||||
|
"p3_contract_version": P3_CONTRACT_VERSION,
|
||||||
|
"p3_contract_fingerprint": P3_CONTRACT_FINGERPRINT,
|
||||||
|
"source_kind": "forwarded_text",
|
||||||
|
"source_trust": "T3",
|
||||||
|
"firewall_status": "sanitized",
|
||||||
|
"disposition": "shadow_quarantine",
|
||||||
|
"reason_codes": ("p5b_attested",),
|
||||||
|
"source_event_ref_hash": _hash("source-event"),
|
||||||
|
"authority_attestation_ref_hash": _hash("authority-attestation"),
|
||||||
|
"request_hash": _hash("request"),
|
||||||
|
"session_hash": _hash("session"),
|
||||||
|
"derived_from_ref_hash": "",
|
||||||
|
"provenance_state": "observed",
|
||||||
|
"sink": "memory_recall",
|
||||||
|
}
|
||||||
|
value.update(overrides)
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
class C5ProvenanceTests(unittest.TestCase):
|
||||||
|
def test_descriptor_fingerprint_is_closed_and_stable(self) -> None:
|
||||||
|
descriptor = contract_descriptor()
|
||||||
|
canonical = json.dumps(descriptor, ensure_ascii=True, sort_keys=True, separators=(",", ":"))
|
||||||
|
self.assertEqual(_hash(canonical), contract_fingerprint())
|
||||||
|
self.assertEqual(13, len(descriptor["record_fields"]))
|
||||||
|
json.dumps(descriptor, ensure_ascii=True)
|
||||||
|
|
||||||
|
def test_legacy_unresolved_is_conservative_and_valid(self) -> None:
|
||||||
|
record = legacy_unresolved("memory-42", record_revision=4)
|
||||||
|
self.assertEqual("legacy_unresolved", record["provenance_state"])
|
||||||
|
self.assertEqual(("unknown", "T4", "unknown"), (record["source_kind"], record["source_trust"], record["firewall_status"]))
|
||||||
|
self.assertTrue(validate_provenance_record(record)["ok"])
|
||||||
|
|
||||||
|
def test_valid_snapshot_becomes_observed_and_invalid_snapshot_is_safe(self) -> None:
|
||||||
|
record = observed_from_companion_snapshot("memory-42", _snapshot(), record_revision=7)
|
||||||
|
self.assertEqual("observed", record["provenance_state"])
|
||||||
|
self.assertTrue(validate_provenance_record(record)["ok"])
|
||||||
|
self.assertEqual(_hash("source-event"), record["source_event_ref_hash"])
|
||||||
|
|
||||||
|
invalid = observed_from_companion_snapshot("memory-42", _snapshot(source_trust="T9"))
|
||||||
|
self.assertEqual("invalid", invalid["provenance_state"])
|
||||||
|
invalid = observed_from_companion_snapshot("memory-42", _snapshot(content="raw prose"))
|
||||||
|
self.assertEqual("invalid", invalid["provenance_state"])
|
||||||
|
|
||||||
|
def test_record_and_preview_reject_raw_fields_without_echoing_them(self) -> None:
|
||||||
|
record = legacy_unresolved("memory-42")
|
||||||
|
record["content"] = "do not retain this"
|
||||||
|
result = validate_provenance_record(record)
|
||||||
|
rendered = json.dumps(result, ensure_ascii=False, sort_keys=True)
|
||||||
|
self.assertFalse(result["ok"])
|
||||||
|
self.assertIn("forbidden_raw_field", result["error_codes"])
|
||||||
|
self.assertNotIn("do not retain this", rendered)
|
||||||
|
|
||||||
|
hostile = [{"memory_id": "memory-secret", "record_revision": 0, "prompt": "secret prompt"}]
|
||||||
|
preview = plan_legacy_migration(hostile, operation_ref_hash=_hash("migration"))
|
||||||
|
self.assertEqual([], preview["operations"])
|
||||||
|
self.assertNotIn("secret prompt", json.dumps(preview, ensure_ascii=False))
|
||||||
|
|
||||||
|
def test_preview_is_immutable_and_apply_returns_a_new_record(self) -> None:
|
||||||
|
source = [{"memory_id": "memory-42", "record_revision": 4}]
|
||||||
|
before = copy.deepcopy(source)
|
||||||
|
preview = plan_legacy_migration(source, operation_ref_hash=_hash("migration-42"))
|
||||||
|
self.assertEqual(before, source)
|
||||||
|
self.assertEqual(("preview", True, 0), (preview["mode"], preview["readonly"], preview["write_count"]))
|
||||||
|
operation = preview["operations"][0]
|
||||||
|
applied = apply_planned_operation({"memory_id": "memory-42", "record_revision": 4}, operation)
|
||||||
|
self.assertEqual((True, "applied", True), (applied["ok"], applied["status"], applied["changed"]))
|
||||||
|
self.assertIsNot(applied["record"], operation["after_record"])
|
||||||
|
|
||||||
|
def test_apply_is_idempotent_and_rollback_uses_cas(self) -> None:
|
||||||
|
operation = plan_legacy_migration(
|
||||||
|
[{"memory_id": "memory-42", "record_revision": 4}], operation_ref_hash=_hash("migration-42")
|
||||||
|
)["operations"][0]
|
||||||
|
applied = apply_planned_operation({"memory_id": "memory-42", "record_revision": 4}, operation)
|
||||||
|
retry = apply_planned_operation(applied["record"], operation)
|
||||||
|
self.assertEqual((True, "idempotent", False), (retry["ok"], retry["status"], retry["changed"]))
|
||||||
|
|
||||||
|
concurrent = copy.deepcopy(applied["record"])
|
||||||
|
concurrent["record_revision"] += 1
|
||||||
|
conflict = rollback_planned_operation(concurrent, operation)
|
||||||
|
self.assertEqual((False, "revision_conflict"), (conflict["ok"], conflict["status"]))
|
||||||
|
|
||||||
|
rolled_back = rollback_planned_operation(applied["record"], operation)
|
||||||
|
self.assertEqual((True, "rolled_back", True), (rolled_back["ok"], rolled_back["status"], rolled_back["removed"]))
|
||||||
|
self.assertIsNone(rolled_back["record"])
|
||||||
|
|
||||||
|
def test_owner_recovery_is_preview_only_and_requires_attested_snapshot(self) -> None:
|
||||||
|
legacy = legacy_unresolved("memory-42", record_revision=2)
|
||||||
|
from core.provenance import plan_owner_recovery
|
||||||
|
|
||||||
|
planned = plan_owner_recovery(legacy, _snapshot(), recovery_operation_ref_hash=_hash("recovery"))
|
||||||
|
self.assertTrue(planned["ok"])
|
||||||
|
self.assertEqual("owner_recovered", planned["operation"]["after_record"]["provenance_state"])
|
||||||
|
rejected = plan_owner_recovery(
|
||||||
|
legacy, _snapshot(p3_contract_fingerprint=_hash("wrong-p3")), recovery_operation_ref_hash=_hash("recovery-2")
|
||||||
|
)
|
||||||
|
self.assertEqual(["companion_snapshot_invalid"], rejected["error_codes"])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
|
|
@ -0,0 +1,240 @@
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from core import bot_personal_contract
|
||||||
|
from core.bridge import MemoryCompanionBridge
|
||||||
|
from core.capability_probe import CapabilityCache, build_capability_snapshot
|
||||||
|
from core.models import MemoryRecord
|
||||||
|
from core.service import MemoryCompanionService
|
||||||
|
from core.store import MemoryStore
|
||||||
|
|
||||||
|
|
||||||
|
def run(coro):
|
||||||
|
return asyncio.run(coro)
|
||||||
|
|
||||||
|
|
||||||
|
def archive(index: str = "1", **overrides):
|
||||||
|
value = {
|
||||||
|
"memory_type": "bot_observed_activity",
|
||||||
|
"memory_domain": bot_personal_contract.BOT_PERSONAL_MEMORY_DOMAIN,
|
||||||
|
"subject": "bot_self",
|
||||||
|
"date": "2026-07-30",
|
||||||
|
"window": "afternoon",
|
||||||
|
"occurred_at": "2026-07-30T15:00:00+08:00",
|
||||||
|
"source_kind": "observed",
|
||||||
|
"source_refs": [f"companion:event:{index}"],
|
||||||
|
"certainty": 0.9,
|
||||||
|
"evidence_level": "L2",
|
||||||
|
"status": "active",
|
||||||
|
"version": 1,
|
||||||
|
"idempotency_key": f"c6:test:{index}",
|
||||||
|
"payload_schema_version": bot_personal_contract.BOT_PERSONAL_PAYLOAD_SCHEMA_VERSION,
|
||||||
|
"payload": {"summary": "safe archive summary", "activity": "rest"},
|
||||||
|
}
|
||||||
|
value.update(overrides)
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
class _Recorder:
|
||||||
|
def __init__(self, result=None):
|
||||||
|
self.calls = []
|
||||||
|
self.result = result or {"ok": True, "record_id": "c6-record", "version": 1}
|
||||||
|
|
||||||
|
async def record_external_event(self, **kwargs):
|
||||||
|
self.calls.append(kwargs)
|
||||||
|
return "external-record"
|
||||||
|
|
||||||
|
async def record_bot_personal_archive(self, dto):
|
||||||
|
self.calls.append(dto)
|
||||||
|
return self.result
|
||||||
|
|
||||||
|
|
||||||
|
class _ProfileProvider:
|
||||||
|
async def read_bot_personal_profile(self, **_kwargs):
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"state": "ready",
|
||||||
|
"items": [
|
||||||
|
{
|
||||||
|
"record_id": "bot-1",
|
||||||
|
"memory_domain": bot_personal_contract.BOT_PERSONAL_MEMORY_DOMAIN,
|
||||||
|
"memory_type": "bot_observed_activity",
|
||||||
|
"summary": "safe summary",
|
||||||
|
"payload": {"secret": "must not cross"},
|
||||||
|
"content": "raw content must not cross",
|
||||||
|
}
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class C6DualPluginBoundaryTests(unittest.TestCase):
|
||||||
|
def test_capability_probe_exposes_contract_domain_version_types_and_pending(self):
|
||||||
|
bridge = MemoryCompanionBridge(object())
|
||||||
|
pending = bridge.capability_status()
|
||||||
|
self.assertEqual("unprobed", pending["capability_state"])
|
||||||
|
self.assertTrue(pending["pending"])
|
||||||
|
self.assertFalse(pending["available"])
|
||||||
|
|
||||||
|
snapshot = bridge.probe_capability_snapshot()
|
||||||
|
self.assertEqual("available", snapshot["capability_state"])
|
||||||
|
self.assertTrue(snapshot["available"])
|
||||||
|
self.assertFalse(snapshot["degraded"])
|
||||||
|
self.assertEqual(bot_personal_contract.BOT_PERSONAL_MEMORY_DOMAIN, snapshot["domain"])
|
||||||
|
self.assertEqual(str(bot_personal_contract.CONTRACT_REVISION), snapshot["contract_version"])
|
||||||
|
self.assertEqual(
|
||||||
|
list(bot_personal_contract.BOT_PERSONAL_MEMORY_TYPES), snapshot["memory_types"]
|
||||||
|
)
|
||||||
|
self.assertEqual(list(bot_personal_contract.WINDOW_SLUGS), snapshot["windows"])
|
||||||
|
self.assertIn("record_bot_personal_archive", snapshot["methods"])
|
||||||
|
|
||||||
|
def test_missing_contract_metadata_is_bounded_and_degraded(self):
|
||||||
|
snapshot = build_capability_snapshot(
|
||||||
|
contract_module=object(), state="degraded", warnings=["contract_missing"], error_code="bridge_missing"
|
||||||
|
)
|
||||||
|
self.assertEqual("degraded", snapshot["state"])
|
||||||
|
self.assertTrue(snapshot["degraded"])
|
||||||
|
self.assertFalse(snapshot["pending"])
|
||||||
|
self.assertEqual("bridge_missing", snapshot["error_code"])
|
||||||
|
self.assertEqual([], snapshot["domains"])
|
||||||
|
self.assertEqual([], snapshot["memory_types"])
|
||||||
|
self.assertEqual(["contract_missing"], snapshot["warnings"])
|
||||||
|
self.assertTrue(all(isinstance(value, (str, bool, list, dict)) for value in snapshot.values()))
|
||||||
|
|
||||||
|
def test_compatibility_writes_keep_bot_user_and_group_contexts_separate(self):
|
||||||
|
recorder = _Recorder()
|
||||||
|
bridge = MemoryCompanionBridge(recorder)
|
||||||
|
|
||||||
|
run(bridge.record_creative_work(content="C6 creative", session_id="bot:creative"))
|
||||||
|
run(
|
||||||
|
bridge.record_event(
|
||||||
|
content="user fact",
|
||||||
|
memory_type="user_fact",
|
||||||
|
scope="private",
|
||||||
|
session_id="private:user-1",
|
||||||
|
visibility="private_pair",
|
||||||
|
reality_level="real_user_fact",
|
||||||
|
subject={"kind": "user", "id": "user-1", "role": "current_sender"},
|
||||||
|
)
|
||||||
|
)
|
||||||
|
run(
|
||||||
|
bridge.record_event(
|
||||||
|
content="group fact",
|
||||||
|
memory_type="group_memory",
|
||||||
|
scope="group",
|
||||||
|
session_id="group:42",
|
||||||
|
group_id="42",
|
||||||
|
visibility="group_public",
|
||||||
|
reality_level="observed_utterance",
|
||||||
|
subject={"kind": "user", "id": "user-2", "role": "group_member"},
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
creative, user, group = recorder.calls
|
||||||
|
self.assertEqual(("creative_work", "bot_self", "fictional_content"),
|
||||||
|
(creative["memory_type"], creative["visibility"], creative["reality_level"]))
|
||||||
|
self.assertEqual(("private", "private:user-1", ""),
|
||||||
|
(user["scope"], user["session_id"], user["group_id"]))
|
||||||
|
self.assertEqual(("group", "group:42", "42"),
|
||||||
|
(group["scope"], group["session_id"], group["group_id"]))
|
||||||
|
self.assertNotEqual(creative["visibility"], user["visibility"])
|
||||||
|
self.assertNotEqual(user["scope"], group["scope"])
|
||||||
|
self.assertNotEqual(user["session_id"], group["session_id"])
|
||||||
|
|
||||||
|
def test_entertainment_compatibility_writes_remain_bot_personal_records(self):
|
||||||
|
recorder = _Recorder()
|
||||||
|
bridge = MemoryCompanionBridge(recorder)
|
||||||
|
|
||||||
|
run(bridge.record_search_action(content="news summary", session_id="bot:news"))
|
||||||
|
run(bridge.record_image_action(content="image summary", session_id="bot:image"))
|
||||||
|
run(bridge.record_qzone_action(content="qzone summary", session_id="bot:qzone"))
|
||||||
|
run(bridge.record_reading(content="reading summary", session_id="bot:reading"))
|
||||||
|
run(bridge.record_schedule_fragment(content="outfit summary", session_id="bot:outfit"))
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
["search_action", "image_action", "qzone_action", "reading_memory", "schedule_fragment"],
|
||||||
|
[item["memory_type"] for item in recorder.calls],
|
||||||
|
)
|
||||||
|
self.assertTrue(all(item["visibility"] == "bot_self" for item in recorder.calls))
|
||||||
|
self.assertEqual(
|
||||||
|
["bot_action", "bot_action", "bot_action", "bot_action", "persona_life"],
|
||||||
|
[item["reality_level"] for item in recorder.calls],
|
||||||
|
)
|
||||||
|
self.assertTrue(all(item["source_plugin"] == "external" for item in recorder.calls))
|
||||||
|
|
||||||
|
def test_bot_personal_archive_is_read_only_and_isolated_from_user_and_group_records(self):
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
service = object.__new__(MemoryCompanionService)
|
||||||
|
service.store = MemoryStore(Path(directory) / "memory.db")
|
||||||
|
service.store.initialize()
|
||||||
|
service._schedule_memory_embedding = lambda *args, **kwargs: None
|
||||||
|
try:
|
||||||
|
bot = run(service.record_bot_personal_archive(archive("bot")))
|
||||||
|
run(service.store.insert_memory(MemoryRecord(
|
||||||
|
id="user-1", memory_type="user_fact", scope="private", session_id="private:user",
|
||||||
|
visibility="private_pair", content="user fact", metadata={"memory_domain": "user_memory"},
|
||||||
|
)))
|
||||||
|
run(service.store.insert_memory(MemoryRecord(
|
||||||
|
id="group-1", memory_type="group_memory", scope="group", session_id="group:42",
|
||||||
|
group_id="42", visibility="group_public", content="group fact",
|
||||||
|
metadata={"memory_domain": "group_memory"},
|
||||||
|
)))
|
||||||
|
profile = run(service.read_bot_personal_profile(limit=10))
|
||||||
|
self.assertTrue(profile["read_only"])
|
||||||
|
self.assertEqual([bot["record_id"]], [item["record_id"] for item in profile["items"]])
|
||||||
|
self.assertTrue(all(item["memory_domain"] == bot_personal_contract.BOT_PERSONAL_MEMORY_DOMAIN
|
||||||
|
for item in profile["items"]))
|
||||||
|
self.assertNotIn("payload", profile["items"][0])
|
||||||
|
self.assertNotIn("content", profile["items"][0])
|
||||||
|
finally:
|
||||||
|
service.store.close()
|
||||||
|
|
||||||
|
def test_bridge_failure_states_are_identifiable_without_leaking_exception_text(self):
|
||||||
|
missing = run(MemoryCompanionBridge(object()).record_bot_personal_archive(archive()))
|
||||||
|
self.assertEqual(("degraded", "bridge_method_unavailable"),
|
||||||
|
(missing["state"], missing["error_code"]))
|
||||||
|
|
||||||
|
class Broken:
|
||||||
|
async def record_bot_personal_archive(self, _dto):
|
||||||
|
raise asyncio.TimeoutError()
|
||||||
|
|
||||||
|
timed_out = run(MemoryCompanionBridge(Broken()).record_bot_personal_archive(archive("timeout")))
|
||||||
|
self.assertEqual(("degraded", "bridge_exception"),
|
||||||
|
(timed_out["state"], timed_out["error_code"]))
|
||||||
|
self.assertNotIn("TimeoutError", str(timed_out))
|
||||||
|
|
||||||
|
failed = _Recorder({"ok": False, "state": "failed", "error_code": "archive_failed"})
|
||||||
|
failed_result = run(MemoryCompanionBridge(failed).record_bot_personal_archive(archive("failed")))
|
||||||
|
self.assertEqual(("failed", "archive_failed"),
|
||||||
|
(failed_result["state"], failed_result["error_code"]))
|
||||||
|
|
||||||
|
def test_profile_bridge_preserves_pending_degraded_and_filters_archive_payload(self):
|
||||||
|
ready = run(MemoryCompanionBridge(_ProfileProvider()).read_bot_personal_profile())
|
||||||
|
self.assertTrue(ready["read_only"])
|
||||||
|
self.assertEqual("ready", ready["state"])
|
||||||
|
self.assertEqual(["bot-1"], [item["record_id"] for item in ready["items"]])
|
||||||
|
self.assertNotIn("payload", ready["items"][0])
|
||||||
|
self.assertNotIn("content", ready["items"][0])
|
||||||
|
|
||||||
|
unavailable = run(MemoryCompanionBridge(object()).read_bot_personal_profile())
|
||||||
|
self.assertEqual("degraded", unavailable["state"])
|
||||||
|
self.assertTrue(unavailable["pending"])
|
||||||
|
self.assertEqual("bridge_method_unavailable", unavailable["error_code"])
|
||||||
|
|
||||||
|
def test_capability_probe_failure_keeps_negative_contract_fields(self):
|
||||||
|
with patch.object(bot_personal_contract, "capability_descriptor", side_effect=RuntimeError("boom")):
|
||||||
|
result = MemoryCompanionBridge(object()).probe_capability_snapshot()
|
||||||
|
self.assertEqual("negative", result["capability_state"])
|
||||||
|
self.assertTrue(result["degraded"])
|
||||||
|
self.assertFalse(result["available"])
|
||||||
|
self.assertEqual("contract_descriptor_exception", result["error_code"])
|
||||||
|
self.assertEqual(bot_personal_contract.BOT_PERSONAL_MEMORY_DOMAIN, result["domain"])
|
||||||
|
self.assertIn("contract_descriptor_exception", result["warnings"])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
|
|
@ -0,0 +1,69 @@
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import inspect
|
||||||
|
from pathlib import Path
|
||||||
|
import time
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from core import bot_personal_contract
|
||||||
|
from core.bridge import MemoryCompanionBridge
|
||||||
|
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
|
||||||
|
|
||||||
|
class BridgeNegativeProbeTests(unittest.TestCase):
|
||||||
|
def test_contract_failure_is_negative_cached_and_not_reprobed(self):
|
||||||
|
bridge = MemoryCompanionBridge(object())
|
||||||
|
with patch.object(
|
||||||
|
bot_personal_contract,
|
||||||
|
"contract_self_check",
|
||||||
|
side_effect=[RuntimeError("private prompt must not escape"), []],
|
||||||
|
) as checker:
|
||||||
|
first = bridge.probe_capability_snapshot()
|
||||||
|
second = bridge.probe_capability_snapshot()
|
||||||
|
|
||||||
|
self.assertEqual("negative", first["capability_state"])
|
||||||
|
self.assertEqual("negative", first["state"])
|
||||||
|
self.assertFalse(first["available"])
|
||||||
|
self.assertEqual("contract_self_check_exception", first["error_code"])
|
||||||
|
self.assertEqual(1, checker.call_count)
|
||||||
|
self.assertEqual("negative", second["capability_state"])
|
||||||
|
|
||||||
|
def test_negative_probe_expires_and_allows_recovery(self):
|
||||||
|
bridge = MemoryCompanionBridge(object())
|
||||||
|
with patch.object(bot_personal_contract, "contract_self_check", side_effect=RuntimeError("broken")):
|
||||||
|
first = bridge.probe_capability_snapshot()
|
||||||
|
self.assertEqual("negative", first["state"])
|
||||||
|
|
||||||
|
bridge._capability_cache._negative_at = time.monotonic() - 61.0
|
||||||
|
with patch.object(bot_personal_contract, "contract_self_check", return_value=[]):
|
||||||
|
recovered = bridge.probe_capability_snapshot()
|
||||||
|
self.assertEqual("available", recovered["state"])
|
||||||
|
self.assertTrue(recovered["available"])
|
||||||
|
|
||||||
|
|
||||||
|
class C7StaticBoundaryTests(unittest.TestCase):
|
||||||
|
def test_service_uses_configured_local_timezone_for_wall_clock_checks(self):
|
||||||
|
source = (ROOT / "core" / "service.py").read_text(encoding="utf-8")
|
||||||
|
self.assertIn('LOCAL_TZ = ZoneInfo("Asia/Shanghai")', source)
|
||||||
|
self.assertIn("datetime.now(LOCAL_TZ)", source)
|
||||||
|
self.assertNotIn("datetime.now()", source)
|
||||||
|
|
||||||
|
def test_page_endpoints_return_real_errors_without_exception_text(self):
|
||||||
|
source = (ROOT / "page_api.py").read_text(encoding="utf-8")
|
||||||
|
for endpoint in ("timeline", "relations", "graph", "threads", "logs"):
|
||||||
|
self.assertIn(f'self._err("{endpoint}_unavailable", 500)', source)
|
||||||
|
self.assertNotIn('return self._ok({"items": []})', source)
|
||||||
|
|
||||||
|
def test_frontend_http_and_partial_context_errors_are_visible(self):
|
||||||
|
source = (ROOT / "pages" / "记忆面板" / "app.js").read_text(encoding="utf-8")
|
||||||
|
self.assertIn("if (!response.ok || data?.success === false)", source)
|
||||||
|
self.assertIn("renderContextPanelErrors", source)
|
||||||
|
self.assertIn("errors: {", source)
|
||||||
|
self.assertIn("已显示可用数据", source)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
186
tests/test_c7_import_retrieval.py
普通文件
186
tests/test_c7_import_retrieval.py
普通文件
|
|
@ -0,0 +1,186 @@
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import types
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
if "astrbot_plugin_remember_you" not in sys.modules:
|
||||||
|
package = types.ModuleType("astrbot_plugin_remember_you")
|
||||||
|
package.__path__ = [str(ROOT)]
|
||||||
|
sys.modules["astrbot_plugin_remember_you"] = package
|
||||||
|
if str(ROOT.parent) not in sys.path:
|
||||||
|
sys.path.insert(0, str(ROOT.parent))
|
||||||
|
|
||||||
|
from astrbot_plugin_remember_you.core.chat_import import HistoricalChatImporter
|
||||||
|
from astrbot_plugin_remember_you.core.models import MemoryRecord
|
||||||
|
from astrbot_plugin_remember_you.core.operations import PORTABLE_EXPORT_PAGE_SIZE, PortableMemoryArchive
|
||||||
|
from astrbot_plugin_remember_you.core.retrieval import RetrievalEngine
|
||||||
|
from astrbot_plugin_remember_you.core.store import MemoryStore
|
||||||
|
|
||||||
|
|
||||||
|
class _Config:
|
||||||
|
def int(self, _key: str, default: int) -> int:
|
||||||
|
return default
|
||||||
|
|
||||||
|
|
||||||
|
class _ResumeStore:
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.batch = {"id": "batch-1", "state": "running", "checkpoint_segment": 7}
|
||||||
|
self.segments = [{"id": "seg-1", "segment_index": 1, "status": "processing", "attempts": 2}]
|
||||||
|
self.updates: list[tuple[str, dict]] = []
|
||||||
|
|
||||||
|
async def get_chat_import_batch(self, _batch_id: str):
|
||||||
|
return dict(self.batch)
|
||||||
|
|
||||||
|
async def chat_import_segments(self, _batch_id: str, *, statuses=None):
|
||||||
|
if statuses is None:
|
||||||
|
return list(self.segments)
|
||||||
|
return [item for item in self.segments if item["status"] in statuses]
|
||||||
|
|
||||||
|
async def update_chat_import_segment(self, segment_id: str, **changes):
|
||||||
|
self.updates.append((segment_id, changes))
|
||||||
|
for item in self.segments:
|
||||||
|
if item["id"] == segment_id:
|
||||||
|
item.update(changes)
|
||||||
|
return dict(self.segments[0])
|
||||||
|
|
||||||
|
async def update_chat_import_batch(self, _batch_id: str, **changes):
|
||||||
|
self.batch.update(changes)
|
||||||
|
return dict(self.batch)
|
||||||
|
|
||||||
|
|
||||||
|
class C7ImportRecoveryTests(unittest.IsolatedAsyncioTestCase):
|
||||||
|
def test_corrupt_manifest_has_stable_redacted_error(self) -> None:
|
||||||
|
with tempfile.TemporaryDirectory() as temp:
|
||||||
|
importer = HistoricalChatImporter(SimpleNamespace(data_dir=Path(temp), store=object()))
|
||||||
|
upload_id = "chatup_" + "a" * 24
|
||||||
|
upload_dir = importer._upload_dir(upload_id)
|
||||||
|
upload_dir.mkdir(parents=True)
|
||||||
|
(upload_dir / "manifest.json").write_text("{broken", encoding="utf-8")
|
||||||
|
with self.assertRaisesRegex(ValueError, "历史导入暂存数据损坏") as raised:
|
||||||
|
importer.preview_upload(upload_id)
|
||||||
|
self.assertNotIn(str(upload_dir), str(raised.exception))
|
||||||
|
|
||||||
|
def test_corrupt_parsed_jsonl_does_not_become_empty_import(self) -> None:
|
||||||
|
with tempfile.TemporaryDirectory() as temp:
|
||||||
|
importer = HistoricalChatImporter(SimpleNamespace(data_dir=Path(temp), store=object()))
|
||||||
|
upload_id = "chatup_" + "b" * 24
|
||||||
|
upload_dir = importer._upload_dir(upload_id)
|
||||||
|
upload_dir.mkdir(parents=True)
|
||||||
|
(upload_dir / "manifest.json").write_text(
|
||||||
|
json.dumps({"upload_id": upload_id}), encoding="utf-8"
|
||||||
|
)
|
||||||
|
(upload_dir / "parsed.jsonl").write_text('{"message_id":"ok"}\n{broken\n', encoding="utf-8")
|
||||||
|
with self.assertRaisesRegex(ValueError, "历史导入暂存数据损坏"):
|
||||||
|
importer._load_upload_messages(upload_id)
|
||||||
|
|
||||||
|
async def test_processing_segment_is_retried_only_without_active_worker(self) -> None:
|
||||||
|
store = _ResumeStore()
|
||||||
|
service = SimpleNamespace(data_dir=Path(tempfile.gettempdir()), store=store, config=_Config())
|
||||||
|
importer = HistoricalChatImporter(service)
|
||||||
|
importer._start_worker = lambda _batch_id: None
|
||||||
|
result = await importer.resume_batch("batch-1")
|
||||||
|
self.assertEqual("retry", store.segments[0]["status"])
|
||||||
|
self.assertEqual("running", result["batch"]["state"])
|
||||||
|
self.assertEqual(0, store.segments[0]["attempts"])
|
||||||
|
|
||||||
|
|
||||||
|
class C7RetrievalBoundaryTests(unittest.TestCase):
|
||||||
|
def test_materialize_limit_is_explicit_and_bounded(self) -> None:
|
||||||
|
self.assertGreater(RetrievalEngine.DEFAULT_MATERIALIZE_LIMIT, 0)
|
||||||
|
self.assertLessEqual(RetrievalEngine.DEFAULT_MATERIALIZE_LIMIT, 2000)
|
||||||
|
|
||||||
|
def test_panel_polling_has_attempt_and_time_bounds(self) -> None:
|
||||||
|
panel = (ROOT / "pages" / "记忆面板" / "app.js").read_text(encoding="utf-8")
|
||||||
|
self.assertIn("historicalChatPollAttempts > 120", panel)
|
||||||
|
self.assertIn("elapsed > 10 * 60 * 1000", panel)
|
||||||
|
self.assertIn("历史导入轮询已达到上限", panel)
|
||||||
|
|
||||||
|
|
||||||
|
class C7PerformanceBoundaryTests(unittest.IsolatedAsyncioTestCase):
|
||||||
|
async def test_embedding_candidate_cache_is_bounded(self) -> None:
|
||||||
|
with tempfile.TemporaryDirectory() as temp:
|
||||||
|
store = MemoryStore(Path(temp) / "memory.db")
|
||||||
|
store.initialize()
|
||||||
|
try:
|
||||||
|
for index in range(store.EMBEDDING_CANDIDATE_CACHE_MAX + 1):
|
||||||
|
await store.list_embedding_candidate_rows(
|
||||||
|
provider_id=f"provider-{index}",
|
||||||
|
limit=1,
|
||||||
|
)
|
||||||
|
self.assertLessEqual(
|
||||||
|
len(store._embedding_candidate_cache),
|
||||||
|
store.EMBEDDING_CANDIDATE_CACHE_MAX,
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
store.close()
|
||||||
|
|
||||||
|
async def test_portable_export_pages_large_memory_sets_without_materializing_all_rows(self) -> None:
|
||||||
|
records = [
|
||||||
|
MemoryRecord(
|
||||||
|
id=f"memory-{index}",
|
||||||
|
memory_type="user_fact",
|
||||||
|
scope="private",
|
||||||
|
visibility="private_pair",
|
||||||
|
content=f"content-{index}",
|
||||||
|
)
|
||||||
|
for index in range(PORTABLE_EXPORT_PAGE_SIZE + 1)
|
||||||
|
]
|
||||||
|
|
||||||
|
class PagedStore:
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.memory_calls: list[tuple[int, int]] = []
|
||||||
|
|
||||||
|
async def stats(self):
|
||||||
|
return {
|
||||||
|
"total_memories": len(records),
|
||||||
|
"identities": 0,
|
||||||
|
"relationships": 0,
|
||||||
|
"timeline_events": 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
async def list_memories(self, *, limit, offset=0):
|
||||||
|
self.memory_calls.append((limit, offset))
|
||||||
|
return records[offset : offset + limit]
|
||||||
|
|
||||||
|
async def list_identities(self, *, limit, offset=0):
|
||||||
|
return []
|
||||||
|
|
||||||
|
async def list_relationships(self, *, limit, offset=0):
|
||||||
|
return []
|
||||||
|
|
||||||
|
async def recent_timeline(self, *, limit, offset=0):
|
||||||
|
return []
|
||||||
|
|
||||||
|
async def list_acl_rules(self):
|
||||||
|
return []
|
||||||
|
|
||||||
|
async def list_acl_policies(self):
|
||||||
|
return []
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as temp:
|
||||||
|
store = PagedStore()
|
||||||
|
result = await PortableMemoryArchive(store, Path(temp)).export()
|
||||||
|
self.assertEqual(
|
||||||
|
[
|
||||||
|
(PORTABLE_EXPORT_PAGE_SIZE, 0),
|
||||||
|
(PORTABLE_EXPORT_PAGE_SIZE, PORTABLE_EXPORT_PAGE_SIZE),
|
||||||
|
],
|
||||||
|
store.memory_calls,
|
||||||
|
)
|
||||||
|
self.assertEqual(len(records), result["counts"]["memory"])
|
||||||
|
self.assertEqual(
|
||||||
|
len(records) + 1,
|
||||||
|
len(Path(result["path"]).read_text(encoding="utf-8").splitlines()),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
56
tests/test_c7_like_security.py
普通文件
56
tests/test_c7_like_security.py
普通文件
|
|
@ -0,0 +1,56 @@
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
from pathlib import Path
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from core.models import MemoryRecord
|
||||||
|
from core.store import MemoryStore
|
||||||
|
|
||||||
|
|
||||||
|
def run(coro):
|
||||||
|
return asyncio.run(coro)
|
||||||
|
|
||||||
|
|
||||||
|
class LikeSecurityTests(unittest.TestCase):
|
||||||
|
def test_like_pattern_escapes_wildcards_and_backslashes(self):
|
||||||
|
self.assertEqual(r"%100\%\_ready\\now%", MemoryStore._like_pattern("100%_ready\\now"))
|
||||||
|
|
||||||
|
def test_memory_query_treats_percent_and_underscore_as_literal(self):
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
store = MemoryStore(Path(directory) / "memory.db")
|
||||||
|
store.initialize()
|
||||||
|
try:
|
||||||
|
run(store.insert_memory(MemoryRecord(
|
||||||
|
id="literal",
|
||||||
|
scope="private",
|
||||||
|
session_id="private:user-1",
|
||||||
|
content="needle%_literal",
|
||||||
|
)))
|
||||||
|
run(store.insert_memory(MemoryRecord(
|
||||||
|
id="wildcard",
|
||||||
|
scope="private",
|
||||||
|
session_id="private:user-1",
|
||||||
|
content="needleXliteral",
|
||||||
|
)))
|
||||||
|
rows = run(store.list_memories(query="needle%_literal", limit=10))
|
||||||
|
self.assertEqual(["literal"], [row.id for row in rows])
|
||||||
|
finally:
|
||||||
|
store.close()
|
||||||
|
|
||||||
|
def test_knowledge_term_search_treats_percent_and_underscore_as_literal(self):
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
store = MemoryStore(Path(directory) / "memory.db")
|
||||||
|
store.initialize()
|
||||||
|
try:
|
||||||
|
run(store.upsert_knowledge_node(node_type="topic", label="alpha%_literal"))
|
||||||
|
run(store.upsert_knowledge_node(node_type="topic", label="alphaXliteral"))
|
||||||
|
labels = run(store.related_knowledge_terms(["alpha%_literal"], limit=10))
|
||||||
|
self.assertEqual(["alpha%_literal"], labels)
|
||||||
|
finally:
|
||||||
|
store.close()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
|
|
@ -0,0 +1,223 @@
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
import types
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
if "astrbot_plugin_remember_you" not in sys.modules:
|
||||||
|
package = types.ModuleType("astrbot_plugin_remember_you")
|
||||||
|
package.__path__ = [str(ROOT)]
|
||||||
|
sys.modules["astrbot_plugin_remember_you"] = package
|
||||||
|
if str(ROOT.parent) not in sys.path:
|
||||||
|
sys.path.insert(0, str(ROOT.parent))
|
||||||
|
|
||||||
|
from astrbot_plugin_remember_you.core.bridge import MemoryCompanionBridge
|
||||||
|
from astrbot_plugin_remember_you.core.coordination_status import build_coordination_status, project_p6_status, project_runtime_health
|
||||||
|
from astrbot_plugin_remember_you.core.p6_four_package_manifest import (
|
||||||
|
FOUR_PACKAGE_IDS,
|
||||||
|
FOUR_PACKAGE_MANIFEST_SCHEMA,
|
||||||
|
verify_four_package_manifests,
|
||||||
|
)
|
||||||
|
from astrbot_plugin_remember_you.core.p6_readonly_projection import (
|
||||||
|
P6_READONLY_STATUS_FINGERPRINT,
|
||||||
|
P6_READONLY_STATUS_SCHEMA,
|
||||||
|
build_p6_readonly_status,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _manifest_set() -> dict[str, dict[str, str]]:
|
||||||
|
return {
|
||||||
|
package_id: {
|
||||||
|
"schema": FOUR_PACKAGE_MANIFEST_SCHEMA,
|
||||||
|
"package_id": package_id,
|
||||||
|
"manifest_version": "1.0",
|
||||||
|
"package_fingerprint": "a" * 64,
|
||||||
|
"compatibility_fingerprint": "b" * 64,
|
||||||
|
}
|
||||||
|
for package_id in FOUR_PACKAGE_IDS
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _p6_raw(**changes):
|
||||||
|
result = {
|
||||||
|
"schema_version": P6_READONLY_STATUS_SCHEMA,
|
||||||
|
"source_plugin": "private_companion",
|
||||||
|
"contract_fingerprint": P6_READONLY_STATUS_FINGERPRINT,
|
||||||
|
"health": "ready",
|
||||||
|
"reason_code": "",
|
||||||
|
"counts": {"profiles": 1, "identity_links": 2, "audit_events": 3, "operations": 4},
|
||||||
|
}
|
||||||
|
result.update(changes)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
class OpsParityP6RelationshipTests(unittest.TestCase):
|
||||||
|
class _HashCollisionKey:
|
||||||
|
def __init__(self, field: str) -> None:
|
||||||
|
self._field = field
|
||||||
|
self.hash_calls = 0
|
||||||
|
self.eq_calls = 0
|
||||||
|
self.str_calls = 0
|
||||||
|
|
||||||
|
def __hash__(self) -> int:
|
||||||
|
self.hash_calls += 1
|
||||||
|
return hash(self._field)
|
||||||
|
|
||||||
|
def __eq__(self, other: object) -> bool:
|
||||||
|
self.eq_calls += 1
|
||||||
|
raise AssertionError("hostile key was compared")
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
self.str_calls += 1
|
||||||
|
raise AssertionError("hostile key was stringified")
|
||||||
|
|
||||||
|
class _HostileValue:
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.hash_calls = 0
|
||||||
|
self.eq_calls = 0
|
||||||
|
self.str_calls = 0
|
||||||
|
|
||||||
|
def __hash__(self) -> int:
|
||||||
|
self.hash_calls += 1
|
||||||
|
raise AssertionError("hostile value was hashed")
|
||||||
|
|
||||||
|
def __eq__(self, other: object) -> bool:
|
||||||
|
self.eq_calls += 1
|
||||||
|
raise AssertionError("hostile value was compared")
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
self.str_calls += 1
|
||||||
|
raise AssertionError("hostile value was stringified")
|
||||||
|
|
||||||
|
def test_p6_manifest_and_readonly_projection_reject_extensions_and_conflicts(self):
|
||||||
|
self.assertEqual("verified", verify_four_package_manifests(_manifest_set())["status"])
|
||||||
|
extended = _manifest_set()
|
||||||
|
extended["memory"]["identity"] = "must-not-project"
|
||||||
|
self.assertEqual("unverifiable", verify_four_package_manifests(extended)["status"])
|
||||||
|
|
||||||
|
conflict = _manifest_set()
|
||||||
|
conflict["peiban"]["compatibility_fingerprint"] = "c" * 64
|
||||||
|
self.assertEqual("compatibility_fingerprint_mismatch", verify_four_package_manifests(conflict)["reason_code"])
|
||||||
|
|
||||||
|
self.assertEqual("ready", project_p6_status(_p6_raw())["health"])
|
||||||
|
self.assertEqual("unverifiable", project_p6_status(_p6_raw(extra="must-not-project"))["health"])
|
||||||
|
self.assertEqual("unverifiable", project_p6_status(_p6_raw(contract_fingerprint="x" * 64))["health"])
|
||||||
|
|
||||||
|
def test_p6_enum_checks_reject_hostile_values_before_hooks(self):
|
||||||
|
for field in ("schema_version", "source_plugin", "contract_fingerprint", "health", "reason_code"):
|
||||||
|
raw = _p6_raw(**{field: self._HostileValue()})
|
||||||
|
self.assertEqual("unverifiable", project_p6_status(raw)["health"])
|
||||||
|
hostile = self._HostileValue()
|
||||||
|
self.assertEqual("unverifiable", build_p6_readonly_status({}, health=hostile)["health"])
|
||||||
|
self.assertEqual("invalid_reason_code", build_p6_readonly_status({}, reason_code=hostile)["reason_code"])
|
||||||
|
|
||||||
|
def test_p6_and_bridge_reject_hash_collision_hostile_keys_before_hooks(self):
|
||||||
|
raw_key = self._HashCollisionKey("schema_version")
|
||||||
|
counts_key = self._HashCollisionKey("profiles")
|
||||||
|
bridge_key = self._HashCollisionKey("health")
|
||||||
|
self.assertEqual("unverifiable", project_p6_status({raw_key: "not-reached"})["health"])
|
||||||
|
self.assertEqual("unverifiable", project_p6_status({**_p6_raw(), "counts": {counts_key: 1}})["health"])
|
||||||
|
status = build_coordination_status(
|
||||||
|
config=None,
|
||||||
|
runtime={"compatibility_level": "full"},
|
||||||
|
bridge={bridge_key: "not-reached"},
|
||||||
|
p6_raw=_p6_raw(),
|
||||||
|
)
|
||||||
|
self.assertEqual({"health": "unverifiable", "reason_code": "bridge_status_unavailable"}, status["bridge"])
|
||||||
|
|
||||||
|
def test_p6_projection_rejects_hash_collision_hostile_keys_before_hooks(self):
|
||||||
|
hostile = self._HashCollisionKey("profiles")
|
||||||
|
status = {hostile: 1}
|
||||||
|
hash_calls_before_projection = hostile.hash_calls
|
||||||
|
|
||||||
|
projection = build_p6_readonly_status(status)
|
||||||
|
|
||||||
|
self.assertEqual("unverifiable", projection["health"])
|
||||||
|
self.assertEqual("registry_status_unavailable", projection["reason_code"])
|
||||||
|
self.assertEqual(
|
||||||
|
{"profiles": 0, "identity_links": 0, "audit_events": 0, "operations": 0},
|
||||||
|
projection["counts"],
|
||||||
|
)
|
||||||
|
self.assertEqual(hash_calls_before_projection, hostile.hash_calls)
|
||||||
|
self.assertEqual(0, hostile.eq_calls)
|
||||||
|
self.assertEqual(0, hostile.str_calls)
|
||||||
|
|
||||||
|
def test_relationship_peek_fails_closed_and_filters_untrusted_fields(self):
|
||||||
|
class Broken:
|
||||||
|
def _peek_relationship_phase(self, _ctx):
|
||||||
|
raise RuntimeError("broken")
|
||||||
|
|
||||||
|
class Extended:
|
||||||
|
def _peek_relationship_phase(self, _ctx):
|
||||||
|
return {
|
||||||
|
"observed": True,
|
||||||
|
"phase": "close",
|
||||||
|
"momentum_band": "rising",
|
||||||
|
"touch_count": 7,
|
||||||
|
"momentum": 0.9,
|
||||||
|
"person_id": "must-not-project",
|
||||||
|
}
|
||||||
|
|
||||||
|
fallback = {"observed": False, "phase": "unknown", "momentum_band": "unknown"}
|
||||||
|
self.assertEqual(fallback, MemoryCompanionBridge(Broken()).peek_relationship_phase(session_id="s"))
|
||||||
|
projection = MemoryCompanionBridge(Extended()).peek_relationship_phase(session_id="s")
|
||||||
|
self.assertEqual({"observed": True, "phase": "close", "momentum_band": "rising", "touch_count": 7}, projection)
|
||||||
|
self.assertNotIn("momentum", projection)
|
||||||
|
self.assertNotIn("person_id", projection)
|
||||||
|
|
||||||
|
hostile_key = self._HashCollisionKey("observed")
|
||||||
|
hostile_value = self._HostileValue()
|
||||||
|
hostile_result = {hostile_key: hostile_value}
|
||||||
|
hash_calls_before_peek = hostile_key.hash_calls
|
||||||
|
projection = MemoryCompanionBridge(
|
||||||
|
types.SimpleNamespace(_peek_relationship_phase=lambda _ctx: hostile_result)
|
||||||
|
).peek_relationship_phase(session_id="s")
|
||||||
|
self.assertEqual(fallback, projection)
|
||||||
|
self.assertEqual(hash_calls_before_peek, hostile_key.hash_calls)
|
||||||
|
self.assertEqual(0, hostile_key.eq_calls)
|
||||||
|
self.assertEqual(0, hostile_key.str_calls)
|
||||||
|
self.assertEqual(0, hostile_value.hash_calls)
|
||||||
|
self.assertEqual(0, hostile_value.eq_calls)
|
||||||
|
self.assertEqual(0, hostile_value.str_calls)
|
||||||
|
self.assertNotIn("hostile", repr(projection))
|
||||||
|
|
||||||
|
def test_runtime_health_rejects_hostile_dict_keys_and_values_before_hooks(self):
|
||||||
|
self.assertEqual(
|
||||||
|
{"health": "unverifiable", "reason_code": "runtime_unsupported"},
|
||||||
|
project_runtime_health({"compatibility_level": "full", "extra": "must-not-project"}),
|
||||||
|
)
|
||||||
|
|
||||||
|
hostile_key = self._HashCollisionKey("compatibility_level")
|
||||||
|
hostile_runtime = {hostile_key: "full"}
|
||||||
|
hash_calls_before_projection = hostile_key.hash_calls
|
||||||
|
self.assertEqual(
|
||||||
|
{"health": "unverifiable", "reason_code": "runtime_unsupported"},
|
||||||
|
project_runtime_health(hostile_runtime),
|
||||||
|
)
|
||||||
|
self.assertEqual(hash_calls_before_projection, hostile_key.hash_calls)
|
||||||
|
self.assertEqual(0, hostile_key.eq_calls)
|
||||||
|
self.assertEqual(0, hostile_key.str_calls)
|
||||||
|
|
||||||
|
hostile_value = self._HostileValue()
|
||||||
|
self.assertEqual(
|
||||||
|
{"health": "unverifiable", "reason_code": "runtime_unsupported"},
|
||||||
|
project_runtime_health({"compatibility_level": hostile_value}),
|
||||||
|
)
|
||||||
|
self.assertEqual(0, hostile_value.hash_calls)
|
||||||
|
self.assertEqual(0, hostile_value.eq_calls)
|
||||||
|
self.assertEqual(0, hostile_value.str_calls)
|
||||||
|
|
||||||
|
def test_coordination_status_degrades_for_invalid_bridge_and_p6_without_leaking_fields(self):
|
||||||
|
status = build_coordination_status(
|
||||||
|
config=None,
|
||||||
|
runtime={"compatibility_level": "full"},
|
||||||
|
bridge={"health": "ready", "reason_code": "companion_bridge_available", "session_id": "must-not-project"},
|
||||||
|
p6_raw=_p6_raw(extra="must-not-project"),
|
||||||
|
)
|
||||||
|
self.assertEqual("unverifiable", status["health"])
|
||||||
|
self.assertEqual({"health": "unverifiable", "reason_code": "bridge_status_unavailable"}, status["bridge"])
|
||||||
|
self.assertEqual("unverifiable", status["p6"]["health"])
|
||||||
|
self.assertNotIn("must-not-project", repr(status))
|
||||||
|
|
@ -120,7 +120,7 @@ class PanelRegressionTests(unittest.TestCase):
|
||||||
self.assertIn("height:calc(100% - 16px)", image_block.group(1))
|
self.assertIn("height:calc(100% - 16px)", image_block.group(1))
|
||||||
self.assertIn("object-fit:contain", image_block.group(1))
|
self.assertIn("object-fit:contain", image_block.group(1))
|
||||||
self.assertIn("height:clamp(480px, 62vh, 820px)", drawer_block.group(1))
|
self.assertIn("height:clamp(480px, 62vh, 820px)", drawer_block.group(1))
|
||||||
self.assertIn("app.css?v=1.6.5", page)
|
self.assertIn("app.css?v=1.6.6", page)
|
||||||
|
|
||||||
def test_microscope_has_explicit_context_and_non_overlapping_results(self) -> None:
|
def test_microscope_has_explicit_context_and_non_overlapping_results(self) -> None:
|
||||||
page = (ROOT / "pages" / "记忆面板" / "index.html").read_text(encoding="utf-8")
|
page = (ROOT / "pages" / "记忆面板" / "index.html").read_text(encoding="utf-8")
|
||||||
|
|
@ -240,11 +240,27 @@ class PanelRegressionTests(unittest.TestCase):
|
||||||
self.assertIn(':root[data-overview-layout="standard"] .projection-stage', styles)
|
self.assertIn(':root[data-overview-layout="standard"] .projection-stage', styles)
|
||||||
self.assertIn(".film-app.is-workspace .overview-layout-switch", styles)
|
self.assertIn(".film-app.is-workspace .overview-layout-switch", styles)
|
||||||
self.assertIn("@media(max-width:760px)", styles)
|
self.assertIn("@media(max-width:760px)", styles)
|
||||||
self.assertIn("app.js?v=1.6.5", page)
|
self.assertIn("app.js?v=1.6.6", page)
|
||||||
|
|
||||||
ids = re.findall(r'\bid="([^"]+)"', page)
|
ids = re.findall(r'\bid="([^"]+)"', page)
|
||||||
self.assertEqual(len(ids), len(set(ids)), "记忆面板不能包含重复 HTML id")
|
self.assertEqual(len(ids), len(set(ids)), "记忆面板不能包含重复 HTML id")
|
||||||
|
|
||||||
|
def test_user_profile_and_private_memory_share_one_user_workspace(self) -> None:
|
||||||
|
page = (ROOT / "pages" / "记忆面板" / "index.html").read_text(encoding="utf-8")
|
||||||
|
script = (ROOT / "pages" / "记忆面板" / "app.js").read_text(encoding="utf-8")
|
||||||
|
|
||||||
|
self.assertIn("用户档案与记忆", page)
|
||||||
|
self.assertIn('data-overview-view="relations" data-user-memory-filter="private"', page)
|
||||||
|
self.assertIn('id="userMemoryTitle"', page)
|
||||||
|
self.assertIn('data-user-memory-filter="profile"', page)
|
||||||
|
self.assertIn('data-user-memory-filter="private"', page)
|
||||||
|
self.assertIn('if (view === "maintain")', script)
|
||||||
|
self.assertIn('view = "relations"', script)
|
||||||
|
self.assertIn('if (state.activeView === "relations") return "private"', script)
|
||||||
|
self.assertIn('scopedMemoryParams("private", { limit: 180 })', script)
|
||||||
|
self.assertIn('params.delete("session_id")', script)
|
||||||
|
self.assertNotIn('id="clearCurrentPrivateMemoryBtn" class="danger subtle" type="button" disabled>清空当前用户</button>\n </div>\n <div id="privateMemoryList"', page)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,20 @@
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
|
||||||
|
|
||||||
|
def test_chat_side_display_name_preserves_stable_plugin_identity():
|
||||||
|
metadata = (ROOT / "metadata.yaml").read_text(encoding="utf-8")
|
||||||
|
main = (ROOT / "main.py").read_text(encoding="utf-8")
|
||||||
|
commands = (ROOT / "core" / "commands.py").read_text(encoding="utf-8")
|
||||||
|
service = (ROOT / "core" / "service.py").read_text(encoding="utf-8")
|
||||||
|
panel = (ROOT / "pages" / "记忆面板" / "index.html").read_text(encoding="utf-8")
|
||||||
|
|
||||||
|
assert "name: astrbot_plugin_memory_companion" in metadata
|
||||||
|
assert "display_name: 雪色的记忆插件-聊天侧" in metadata
|
||||||
|
assert 'version: 1.6.8' in metadata
|
||||||
|
assert 'PLUGIN_VERSION = "1.6.8"' in main
|
||||||
|
for source in (commands, service, panel):
|
||||||
|
assert "雪色的记忆插件-聊天侧" in source
|
||||||
|
assert "我会牢牢记住你" not in source
|
||||||
|
|
@ -0,0 +1,157 @@
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
from types import MethodType, SimpleNamespace
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
if str(ROOT) not in sys.path:
|
||||||
|
sys.path.insert(0, str(ROOT))
|
||||||
|
|
||||||
|
from core.bridge import sanitize_companion_relationship_projection
|
||||||
|
from core.models import SessionContext
|
||||||
|
from core.service import MemoryCompanionService
|
||||||
|
|
||||||
|
|
||||||
|
def valid_projection() -> dict:
|
||||||
|
return {
|
||||||
|
"schema_version": "chat.relationship_projection.v1",
|
||||||
|
"authority": "private_companion.relationship_score",
|
||||||
|
"read_only": True,
|
||||||
|
"score": 620,
|
||||||
|
"phase_key": "close",
|
||||||
|
"phase_label": "亲近",
|
||||||
|
"tone": "温暖、自然",
|
||||||
|
"address_level": "使用已确认昵称",
|
||||||
|
"proactive_care_limit": 2,
|
||||||
|
"relationship_mode": "owner_exclusive",
|
||||||
|
"current_interaction": {
|
||||||
|
"expression_band": "affectionate",
|
||||||
|
"label": "爱意",
|
||||||
|
"source": "manual",
|
||||||
|
"reason": "administrator_manual_override",
|
||||||
|
"manual_override": True,
|
||||||
|
},
|
||||||
|
"soft_behaviors": {
|
||||||
|
"allow_playful_jokes": True,
|
||||||
|
"allow_followup": True,
|
||||||
|
"allow_memory_mention": True,
|
||||||
|
"allow_daily_care": True,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class Req027RelationshipAuthorityTests(unittest.TestCase):
|
||||||
|
def test_bridge_accepts_only_the_read_only_fixed_contract(self) -> None:
|
||||||
|
projection = valid_projection()
|
||||||
|
projection.update({"owner": True, "cross_user_query": True, "p4_bypass": True})
|
||||||
|
result = sanitize_companion_relationship_projection(projection)
|
||||||
|
self.assertEqual("accepted", result["status"])
|
||||||
|
accepted = result["projection"]
|
||||||
|
self.assertEqual("private_companion.relationship_score", accepted["authority"])
|
||||||
|
self.assertTrue(accepted["read_only"])
|
||||||
|
self.assertEqual("close", accepted["phase_key"])
|
||||||
|
self.assertEqual("owner_exclusive", accepted["relationship_mode"])
|
||||||
|
self.assertEqual("affectionate", accepted["current_interaction"]["expression_band"])
|
||||||
|
self.assertTrue(accepted["current_interaction"]["manual_override"])
|
||||||
|
for forbidden in ("owner", "cross_user_query", "p4_bypass"):
|
||||||
|
self.assertNotIn(forbidden, accepted)
|
||||||
|
|
||||||
|
for mutation in (
|
||||||
|
{"schema_version": "chat.relationship_projection.v2"},
|
||||||
|
{"authority": "memory.relationship_phase"},
|
||||||
|
{"read_only": False},
|
||||||
|
{"score": 1201},
|
||||||
|
{"phase_key": "forged"},
|
||||||
|
{"soft_behaviors": {"allow_followup": "true"}},
|
||||||
|
):
|
||||||
|
with self.subTest(mutation=mutation):
|
||||||
|
hostile = valid_projection()
|
||||||
|
hostile.update(mutation)
|
||||||
|
self.assertEqual("invalid", sanitize_companion_relationship_projection(hostile)["status"])
|
||||||
|
|
||||||
|
malformed_limit = valid_projection()
|
||||||
|
malformed_limit["proactive_care_limit"] = {"owner": True}
|
||||||
|
sanitized = sanitize_companion_relationship_projection(malformed_limit)
|
||||||
|
self.assertEqual("accepted", sanitized["status"])
|
||||||
|
self.assertEqual(0, sanitized["projection"]["proactive_care_limit"])
|
||||||
|
|
||||||
|
def test_private_context_consumes_projection_but_group_context_does_not(self) -> None:
|
||||||
|
event = SimpleNamespace(private_companion_context={"relationship_projection": valid_projection()})
|
||||||
|
private = SessionContext(session_id="telegram:FriendMessage:u1", scope="private", user_id="u1")
|
||||||
|
MemoryCompanionService._apply_companion_relationship_projection(private, event=event)
|
||||||
|
self.assertEqual("private_companion.relationship_score", private.relationship_authority_source)
|
||||||
|
self.assertEqual(620, private.companion_relationship_score)
|
||||||
|
self.assertEqual("close", private.companion_relationship_phase_key)
|
||||||
|
|
||||||
|
group = SessionContext(session_id="telegram:GroupMessage:g1", scope="group", group_id="g1", user_id="u1")
|
||||||
|
MemoryCompanionService._apply_companion_relationship_projection(group, event=event)
|
||||||
|
self.assertEqual("", group.relationship_authority_source)
|
||||||
|
self.assertEqual("", group.companion_relationship_phase_key)
|
||||||
|
|
||||||
|
def test_companion_authority_stops_memory_phase_state_writes(self) -> None:
|
||||||
|
service = MemoryCompanionService.__new__(MemoryCompanionService)
|
||||||
|
state = {
|
||||||
|
"phase": "acquaintance",
|
||||||
|
"momentum": 0.0,
|
||||||
|
"touch_count": 0,
|
||||||
|
"recent_touch_message_ids": [],
|
||||||
|
}
|
||||||
|
calls = {"transition": 0, "save": 0}
|
||||||
|
service._get_relationship_phase = MethodType(lambda _self, _ctx: state, service)
|
||||||
|
service._maybe_transition_phase = MethodType(
|
||||||
|
lambda _self, _ctx, _state: calls.__setitem__("transition", calls["transition"] + 1),
|
||||||
|
service,
|
||||||
|
)
|
||||||
|
service._save_relationship_phase_state = MethodType(
|
||||||
|
lambda _self: calls.__setitem__("save", calls["save"] + 1),
|
||||||
|
service,
|
||||||
|
)
|
||||||
|
|
||||||
|
authoritative = SessionContext(
|
||||||
|
session_id="telegram:FriendMessage:u1",
|
||||||
|
scope="private",
|
||||||
|
user_id="u1",
|
||||||
|
message_id="m1",
|
||||||
|
relationship_authority_source="private_companion.relationship_score",
|
||||||
|
companion_relationship_phase_key="close",
|
||||||
|
companion_relationship_phase_label="亲近",
|
||||||
|
)
|
||||||
|
self.assertFalse(service._update_relationship_phase_momentum(authoritative, touch_type="warm"))
|
||||||
|
self.assertEqual(0.0, state["momentum"])
|
||||||
|
self.assertEqual(0, calls["transition"])
|
||||||
|
self.assertEqual(0, calls["save"])
|
||||||
|
|
||||||
|
fallback = SessionContext(
|
||||||
|
session_id="telegram:FriendMessage:u2",
|
||||||
|
scope="private",
|
||||||
|
user_id="u2",
|
||||||
|
message_id="m2",
|
||||||
|
)
|
||||||
|
self.assertTrue(service._update_relationship_phase_momentum(fallback, touch_type="warm"))
|
||||||
|
self.assertEqual(1, calls["transition"])
|
||||||
|
self.assertEqual(1, calls["save"])
|
||||||
|
|
||||||
|
def test_address_hint_uses_companion_phase_and_memory_declares_trend_only(self) -> None:
|
||||||
|
service = MemoryCompanionService.__new__(MemoryCompanionService)
|
||||||
|
ctx = SessionContext(
|
||||||
|
session_id="telegram:FriendMessage:u1",
|
||||||
|
scope="private",
|
||||||
|
user_id="u1",
|
||||||
|
relationship_authority_source="private_companion.relationship_score",
|
||||||
|
companion_relationship_phase_key="close",
|
||||||
|
companion_relationship_phase_label="亲近",
|
||||||
|
companion_relationship_tone="温暖、自然",
|
||||||
|
companion_relationship_address_level="使用已确认昵称",
|
||||||
|
)
|
||||||
|
hint = service._address_hint_for_injection(ctx)
|
||||||
|
self.assertIn("陪伴插件是长期亲密度权威", hint)
|
||||||
|
self.assertIn("亲近", hint)
|
||||||
|
self.assertIn("温暖、自然", hint)
|
||||||
|
self.assertIn("Memory 仅提供记忆触动趋势", hint)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
182
tests/test_req028_expression_sync.py
普通文件
182
tests/test_req028_expression_sync.py
普通文件
|
|
@ -0,0 +1,182 @@
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
from types import MethodType, SimpleNamespace
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
if str(ROOT) not in sys.path:
|
||||||
|
sys.path.insert(0, str(ROOT))
|
||||||
|
|
||||||
|
from core.bridge import sanitize_companion_expression_decision
|
||||||
|
from core.models import MemoryRecord, SearchResult, SessionContext
|
||||||
|
from core.service import MemoryCompanionService, MemoryRouteDecision
|
||||||
|
from core.time_intent import TimeIntent
|
||||||
|
|
||||||
|
|
||||||
|
def valid_expression_decision(**updates) -> dict:
|
||||||
|
decision = {
|
||||||
|
"contract": "companion_interaction_expression.v1",
|
||||||
|
"expression_band": "warm",
|
||||||
|
"tone": "gentle",
|
||||||
|
"warmth": 76,
|
||||||
|
"distance": 28,
|
||||||
|
"address_style": "warm",
|
||||||
|
"response_length": "balanced",
|
||||||
|
"followup": True,
|
||||||
|
"initiative": "passive_only",
|
||||||
|
"proactive_budget": 0,
|
||||||
|
"tts_style": "warm",
|
||||||
|
"allowed_behaviors": ["reply", "support", "followup"],
|
||||||
|
"safety_mode": "normal",
|
||||||
|
"blocker": None,
|
||||||
|
"reason_codes": ["interaction_band_applied"],
|
||||||
|
}
|
||||||
|
decision.update(updates)
|
||||||
|
return decision
|
||||||
|
|
||||||
|
|
||||||
|
def memory_item() -> tuple[MemoryRecord, SearchResult]:
|
||||||
|
memory = MemoryRecord(
|
||||||
|
id="mem-1",
|
||||||
|
memory_type="user_profile",
|
||||||
|
scope="private",
|
||||||
|
session_id="qq:FriendMessage:u1",
|
||||||
|
visibility="private",
|
||||||
|
sayability="direct",
|
||||||
|
reality_level="real_user_fact",
|
||||||
|
content="用户的生日是八月一日",
|
||||||
|
confidence=0.95,
|
||||||
|
importance=0.8,
|
||||||
|
metadata={},
|
||||||
|
)
|
||||||
|
return memory, SearchResult(memory=memory, score=1.2, reason="")
|
||||||
|
|
||||||
|
|
||||||
|
class Req028ExpressionSyncTests(unittest.TestCase):
|
||||||
|
def test_expression_contract_is_strict_and_redacted(self) -> None:
|
||||||
|
accepted = sanitize_companion_expression_decision(valid_expression_decision(owner_id="secret"))
|
||||||
|
self.assertEqual("accepted", accepted["status"])
|
||||||
|
self.assertEqual("warm", accepted["decision"]["expression_band"])
|
||||||
|
self.assertNotIn("owner_id", accepted["decision"])
|
||||||
|
|
||||||
|
hostile_values = (
|
||||||
|
valid_expression_decision(contract="companion_interaction_expression.v2"),
|
||||||
|
valid_expression_decision(expression_band="forged"),
|
||||||
|
valid_expression_decision(followup="true"),
|
||||||
|
valid_expression_decision(allowed_behaviors=["reply", "memory_override"]),
|
||||||
|
valid_expression_decision(safety_mode="bypass"),
|
||||||
|
valid_expression_decision(blocker="owner_override"),
|
||||||
|
valid_expression_decision(reason_codes=["unknown_reason"]),
|
||||||
|
)
|
||||||
|
for value in hostile_values:
|
||||||
|
with self.subTest(value=value):
|
||||||
|
self.assertEqual("invalid", sanitize_companion_expression_decision(value)["status"])
|
||||||
|
|
||||||
|
def test_private_context_consumes_request_scoped_decision_and_group_ignores_it(self) -> None:
|
||||||
|
req = SimpleNamespace(_private_companion_expression_decision=valid_expression_decision())
|
||||||
|
private = SessionContext(scope="private", session_id="qq:FriendMessage:u1", user_id="u1")
|
||||||
|
MemoryCompanionService._apply_companion_expression_decision(private, req=req)
|
||||||
|
self.assertEqual("companion_interaction_expression.v1", private.companion_expression_contract)
|
||||||
|
self.assertEqual("warm", private.companion_expression_band)
|
||||||
|
self.assertEqual(("reply", "support", "followup"), private.companion_expression_allowed_behaviors)
|
||||||
|
|
||||||
|
group = SessionContext(scope="group", session_id="qq:GroupMessage:g1", group_id="g1", user_id="u1")
|
||||||
|
MemoryCompanionService._apply_companion_expression_decision(group, req=req)
|
||||||
|
self.assertEqual("", group.companion_expression_contract)
|
||||||
|
self.assertEqual("", group.companion_expression_band)
|
||||||
|
|
||||||
|
def test_companion_caps_unsolicited_mentions_but_explicit_recall_still_reads_fact(self) -> None:
|
||||||
|
service = MemoryCompanionService.__new__(MemoryCompanionService)
|
||||||
|
memory, item = memory_item()
|
||||||
|
route = MemoryRouteDecision()
|
||||||
|
restricted = SessionContext(
|
||||||
|
scope="private",
|
||||||
|
message_text="今天过得怎么样",
|
||||||
|
companion_expression_contract="companion_interaction_expression.v1",
|
||||||
|
companion_expression_band="hurt",
|
||||||
|
companion_expression_allowed_behaviors=("acknowledge", "brief_reply", "give_space"),
|
||||||
|
companion_expression_safety_mode="normal",
|
||||||
|
)
|
||||||
|
expression, reason = service._memory_expression_decision(
|
||||||
|
restricted, memory, item, "user_profile", route, TimeIntent(), query_text=restricted.message_text
|
||||||
|
)
|
||||||
|
self.assertEqual("tone", expression)
|
||||||
|
self.assertEqual("companion_expression:band_hurt", reason)
|
||||||
|
|
||||||
|
restricted.message_text = "你还记得我的生日吗"
|
||||||
|
expression, reason = service._memory_expression_decision(
|
||||||
|
restricted, memory, item, "user_profile", route, TimeIntent(), query_text=restricted.message_text
|
||||||
|
)
|
||||||
|
self.assertEqual("mention", expression)
|
||||||
|
self.assertEqual("stable_user_fact", reason)
|
||||||
|
|
||||||
|
def test_allowed_behaviors_are_a_maximum_not_a_memory_override(self) -> None:
|
||||||
|
service = MemoryCompanionService.__new__(MemoryCompanionService)
|
||||||
|
memory, item = memory_item()
|
||||||
|
route = MemoryRouteDecision()
|
||||||
|
relaxed = SessionContext(
|
||||||
|
scope="private",
|
||||||
|
message_text="随便聊聊",
|
||||||
|
companion_expression_contract="companion_interaction_expression.v1",
|
||||||
|
companion_expression_band="relaxed",
|
||||||
|
companion_expression_allowed_behaviors=("reply", "clarify"),
|
||||||
|
companion_expression_safety_mode="normal",
|
||||||
|
)
|
||||||
|
self.assertEqual(
|
||||||
|
("tone", "companion_expression:behavior_cap"),
|
||||||
|
service._memory_expression_decision(relaxed, memory, item, "user_profile", route, TimeIntent()),
|
||||||
|
)
|
||||||
|
relaxed.companion_expression_band = "warm"
|
||||||
|
relaxed.companion_expression_allowed_behaviors = ("reply", "support")
|
||||||
|
self.assertEqual(
|
||||||
|
("mention", "stable_user_fact"),
|
||||||
|
service._memory_expression_decision(relaxed, memory, item, "user_profile", route, TimeIntent()),
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_paired_mode_does_not_inject_second_tone_or_write_legacy_state(self) -> None:
|
||||||
|
service = MemoryCompanionService.__new__(MemoryCompanionService)
|
||||||
|
ctx = SessionContext(
|
||||||
|
scope="private",
|
||||||
|
session_id="qq:FriendMessage:u1",
|
||||||
|
user_id="u1",
|
||||||
|
message_id="m1",
|
||||||
|
relationship_authority_source="private_companion.relationship_score",
|
||||||
|
companion_expression_contract="companion_interaction_expression.v1",
|
||||||
|
companion_expression_band="warm",
|
||||||
|
companion_expression_allowed_behaviors=("reply", "support"),
|
||||||
|
companion_expression_safety_mode="normal",
|
||||||
|
)
|
||||||
|
calls = {"get": 0, "save": 0}
|
||||||
|
service._get_relationship_phase = MethodType(
|
||||||
|
lambda _self, _ctx: calls.__setitem__("get", calls["get"] + 1) or {}, service
|
||||||
|
)
|
||||||
|
service._save_relationship_phase_state = MethodType(
|
||||||
|
lambda _self: calls.__setitem__("save", calls["save"] + 1), service
|
||||||
|
)
|
||||||
|
self.assertEqual("", service._address_hint_for_injection(ctx))
|
||||||
|
service._update_address_evolution(ctx, "宝贝")
|
||||||
|
self.assertFalse(service._update_relationship_phase_momentum(ctx, touch_type="warm"))
|
||||||
|
self.assertEqual({"get": 0, "save": 0}, calls)
|
||||||
|
|
||||||
|
def test_standalone_fallback_remains_available(self) -> None:
|
||||||
|
service = MemoryCompanionService.__new__(MemoryCompanionService)
|
||||||
|
service._BOT_ADDRESS_SUGGESTIONS = {"acquaintance": {"hint": "standalone address hint"}}
|
||||||
|
service._get_relationship_phase = MethodType(
|
||||||
|
lambda _self, _ctx: {"phase": "acquaintance", "current_address_phase": ""}, service
|
||||||
|
)
|
||||||
|
ctx = SessionContext(scope="private", session_id="qq:FriendMessage:u1", user_id="u1")
|
||||||
|
self.assertEqual("standalone address hint", service._address_hint_for_injection(ctx))
|
||||||
|
|
||||||
|
def test_page_source_exposes_coordination_without_second_relationship_authority(self) -> None:
|
||||||
|
source = (ROOT / "pages" / "记忆面板" / "app.js").read_text(encoding="utf-8")
|
||||||
|
for retired in ("关系阶段演进", "情绪事件队列", "称呼演变记录", "Bot 称呼建议"):
|
||||||
|
self.assertNotIn(retired, source)
|
||||||
|
for required in ("陪伴表达协同状态", "记忆触动趋势", "记忆触动事件", "当时关系情境"):
|
||||||
|
self.assertIn(required, source)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
|
|
@ -0,0 +1,179 @@
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
if str(ROOT) not in sys.path:
|
||||||
|
sys.path.insert(0, str(ROOT))
|
||||||
|
|
||||||
|
from core.bridge import MemoryCompanionBridge
|
||||||
|
from core.models import EntityRef, MemoryRecord
|
||||||
|
from core.service import MemoryCompanionService, USER_MEMORY_SUMMARY_VERSION
|
||||||
|
from core.store import MemoryStore
|
||||||
|
|
||||||
|
|
||||||
|
class _Config:
|
||||||
|
def __init__(self, enabled: bool = True) -> None:
|
||||||
|
self.enabled = enabled
|
||||||
|
|
||||||
|
def bridge_enabled(self) -> bool:
|
||||||
|
return self.enabled
|
||||||
|
|
||||||
|
|
||||||
|
class Req029UserMemorySummaryBridgeTests(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_private_memory(
|
||||||
|
self,
|
||||||
|
store: MemoryStore,
|
||||||
|
*,
|
||||||
|
record_id: str,
|
||||||
|
user_id: str,
|
||||||
|
memory_type: str,
|
||||||
|
content: str,
|
||||||
|
session_id: str | None = None,
|
||||||
|
) -> None:
|
||||||
|
await store.insert_memory(
|
||||||
|
MemoryRecord(
|
||||||
|
id=record_id,
|
||||||
|
memory_type=memory_type,
|
||||||
|
subject=EntityRef(kind="user", id=user_id),
|
||||||
|
object=EntityRef.bot_self(),
|
||||||
|
scope="private",
|
||||||
|
session_id=session_id or f"qq:FriendMessage:{user_id}",
|
||||||
|
visibility="private_pair",
|
||||||
|
lifecycle="stable_memory",
|
||||||
|
content=content,
|
||||||
|
occurred_at="2026-08-02T10:00:00+00:00",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
async def test_exact_identity_query_counts_categories_and_excludes_other_users(self) -> None:
|
||||||
|
store = self.make_store()
|
||||||
|
for record_id, memory_type in (
|
||||||
|
("profile", "user_profile"),
|
||||||
|
("preference", "user_preference"),
|
||||||
|
("relation", "relationship_claim"),
|
||||||
|
("conversation", "conversation_summary"),
|
||||||
|
):
|
||||||
|
await self.add_private_memory(
|
||||||
|
store,
|
||||||
|
record_id=record_id,
|
||||||
|
user_id="u1",
|
||||||
|
memory_type=memory_type,
|
||||||
|
content=f"u1-private-{record_id}",
|
||||||
|
)
|
||||||
|
await self.add_private_memory(
|
||||||
|
store,
|
||||||
|
record_id="other-user",
|
||||||
|
user_id="u2",
|
||||||
|
memory_type="user_profile",
|
||||||
|
content="u2-private-only",
|
||||||
|
)
|
||||||
|
await store.insert_memory(
|
||||||
|
MemoryRecord(
|
||||||
|
id="group-u1",
|
||||||
|
memory_type="user_profile",
|
||||||
|
subject=EntityRef(kind="user", id="u1"),
|
||||||
|
object=EntityRef(kind="group", id="g1"),
|
||||||
|
scope="group",
|
||||||
|
session_id="qq:GroupMessage:g1",
|
||||||
|
group_id="g1",
|
||||||
|
visibility="group_public",
|
||||||
|
content="group-only",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
service = MemoryCompanionService.__new__(MemoryCompanionService)
|
||||||
|
service.config = _Config(True)
|
||||||
|
service.store = store
|
||||||
|
result = await service.read_user_memory_summary("u1", session_id="qq:FriendMessage:u1", limit=8)
|
||||||
|
|
||||||
|
self.assertEqual(USER_MEMORY_SUMMARY_VERSION, result["contract"])
|
||||||
|
self.assertTrue(result["ok"])
|
||||||
|
self.assertEqual("ready", result["state"])
|
||||||
|
self.assertEqual(
|
||||||
|
{"profile": 1, "preference": 1, "relationship": 1, "private_conversation": 1, "other": 0, "total": 4},
|
||||||
|
result["counts"],
|
||||||
|
)
|
||||||
|
rendered = repr(result["summaries"])
|
||||||
|
for forbidden in ("u1-private", "u2-private-only", "group-only"):
|
||||||
|
self.assertNotIn(forbidden, rendered)
|
||||||
|
self.assertTrue(all(item["content_redacted"] and item["truncated"] for item in result["summaries"]))
|
||||||
|
|
||||||
|
async def test_session_mismatch_fails_closed_without_cross_user_fallback(self) -> None:
|
||||||
|
store = self.make_store()
|
||||||
|
await self.add_private_memory(
|
||||||
|
store,
|
||||||
|
record_id="u1-profile",
|
||||||
|
user_id="u1",
|
||||||
|
memory_type="user_profile",
|
||||||
|
content="private-u1",
|
||||||
|
)
|
||||||
|
service = MemoryCompanionService.__new__(MemoryCompanionService)
|
||||||
|
service.config = _Config(True)
|
||||||
|
service.store = store
|
||||||
|
|
||||||
|
result = await service.read_user_memory_summary("u1", session_id="qq:FriendMessage:u2")
|
||||||
|
self.assertFalse(result["ok"])
|
||||||
|
self.assertEqual("degraded", result["state"])
|
||||||
|
self.assertEqual("session_identity_mismatch", result["error_code"])
|
||||||
|
self.assertEqual(0, result["counts"]["total"])
|
||||||
|
|
||||||
|
async def test_bridge_contract_redacts_records_and_degrades_for_disabled_or_failed_queries(self) -> None:
|
||||||
|
store = self.make_store()
|
||||||
|
await self.add_private_memory(
|
||||||
|
store,
|
||||||
|
record_id="secret-profile",
|
||||||
|
user_id="u1",
|
||||||
|
memory_type="user_profile",
|
||||||
|
content="TOKEN=PRIVATE_CONTEXT_MUST_NOT_LEAK " + "x" * 500,
|
||||||
|
)
|
||||||
|
service = MemoryCompanionService.__new__(MemoryCompanionService)
|
||||||
|
service.config = _Config(True)
|
||||||
|
service.store = store
|
||||||
|
bridge = MemoryCompanionBridge(service)
|
||||||
|
|
||||||
|
ready = await bridge.read_user_memory_summary("u1", limit=99)
|
||||||
|
self.assertTrue(ready["ok"])
|
||||||
|
self.assertEqual(USER_MEMORY_SUMMARY_VERSION, ready["contract"])
|
||||||
|
self.assertLessEqual(len(ready["summaries"]), 8)
|
||||||
|
self.assertNotIn("PRIVATE_CONTEXT_MUST_NOT_LEAK", repr(ready))
|
||||||
|
self.assertNotIn("content", ready["summaries"][0])
|
||||||
|
|
||||||
|
service.config = _Config(False)
|
||||||
|
disabled = await bridge.read_user_memory_summary("u1")
|
||||||
|
self.assertFalse(disabled["ok"])
|
||||||
|
self.assertEqual("bridge_disabled", disabled["error_code"])
|
||||||
|
self.assertEqual(0, disabled["counts"]["total"])
|
||||||
|
|
||||||
|
class _BrokenService:
|
||||||
|
async def read_user_memory_summary(self, *_args, **_kwargs):
|
||||||
|
raise RuntimeError("sensitive failure details")
|
||||||
|
|
||||||
|
broken = await MemoryCompanionBridge(_BrokenService()).read_user_memory_summary("u1")
|
||||||
|
self.assertFalse(broken["ok"])
|
||||||
|
self.assertEqual("bridge_exception", broken["error_code"])
|
||||||
|
self.assertNotIn("sensitive failure details", repr(broken))
|
||||||
|
|
||||||
|
def test_bridge_and_page_api_expose_only_the_read_only_workspace_contract(self) -> None:
|
||||||
|
bridge_source = (ROOT / "core" / "bridge.py").read_text(encoding="utf-8")
|
||||||
|
page_source = (ROOT / "page_api.py").read_text(encoding="utf-8")
|
||||||
|
self.assertIn("async def read_user_memory_summary", bridge_source)
|
||||||
|
self.assertIn('"/user-memory-summary"', page_source)
|
||||||
|
self.assertIn("content_redacted", bridge_source)
|
||||||
|
self.assertNotIn("write_user_memory_summary", bridge_source)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
|
|
@ -938,6 +938,75 @@ class SummaryAndRelationshipTests(unittest.IsolatedAsyncioTestCase):
|
||||||
bridged = bridge.get_relationship_phase(session_id=private.session_id, scope="private")
|
bridged = bridge.get_relationship_phase(session_id=private.session_id, scope="private")
|
||||||
self.assertIs(state, bridged)
|
self.assertIs(state, bridged)
|
||||||
|
|
||||||
|
async def test_peek_relationship_phase_is_read_only_and_fails_closed(self) -> None:
|
||||||
|
service = self.make_service()
|
||||||
|
ctx = SessionContext(
|
||||||
|
session_id="qq:FriendMessage:ambiguous-user",
|
||||||
|
scope="private",
|
||||||
|
platform="qq",
|
||||||
|
user_id="ambiguous-user",
|
||||||
|
)
|
||||||
|
fallback = {"observed": False, "phase": "unknown", "momentum_band": "unknown"}
|
||||||
|
self.assertEqual(fallback, service._peek_relationship_phase(ctx))
|
||||||
|
self.assertEqual({}, service._relationship_phase_state)
|
||||||
|
self.assertFalse(service._RELATIONSHIP_PHASE_FILE.exists())
|
||||||
|
|
||||||
|
identity = service._phase_identity(ctx)
|
||||||
|
service._relationship_phase_state = {
|
||||||
|
"candidate-a": {"_identity": dict(identity), "phase": "close", "momentum": 0.2, "touch_count": 1},
|
||||||
|
"candidate-b": {"_identity": dict(identity), "phase": "close", "momentum": 0.2, "touch_count": 1},
|
||||||
|
}
|
||||||
|
before = json.loads(json.dumps(service._relationship_phase_state))
|
||||||
|
self.assertEqual(fallback, service._peek_relationship_phase(ctx))
|
||||||
|
self.assertEqual(before, service._relationship_phase_state)
|
||||||
|
|
||||||
|
service._relationship_phase_state = {
|
||||||
|
service._phase_key(ctx): {"phase": "close", "momentum": "not-a-number", "touch_count": 1}
|
||||||
|
}
|
||||||
|
before = json.loads(json.dumps(service._relationship_phase_state))
|
||||||
|
self.assertEqual(fallback, service._peek_relationship_phase(ctx))
|
||||||
|
self.assertEqual(before, service._relationship_phase_state)
|
||||||
|
self.assertFalse(service._RELATIONSHIP_PHASE_FILE.exists())
|
||||||
|
|
||||||
|
async def test_peek_relationship_phase_rejects_nonfinite_momentum_without_writing(self) -> None:
|
||||||
|
service = self.make_service()
|
||||||
|
ctx = SessionContext(
|
||||||
|
session_id="qq:FriendMessage:nonfinite-user",
|
||||||
|
scope="private",
|
||||||
|
platform="qq",
|
||||||
|
user_id="nonfinite-user",
|
||||||
|
)
|
||||||
|
fallback = {"observed": False, "phase": "unknown", "momentum_band": "unknown"}
|
||||||
|
|
||||||
|
for momentum in (float("nan"), float("inf"), float("-inf")):
|
||||||
|
service._relationship_phase_state = {
|
||||||
|
service._phase_key(ctx): {"phase": "close", "momentum": momentum, "touch_count": 1}
|
||||||
|
}
|
||||||
|
before = json.dumps(service._relationship_phase_state, sort_keys=True)
|
||||||
|
self.assertEqual(fallback, service._peek_relationship_phase(ctx))
|
||||||
|
self.assertEqual(before, json.dumps(service._relationship_phase_state, sort_keys=True))
|
||||||
|
self.assertFalse(service._RELATIONSHIP_PHASE_FILE.exists())
|
||||||
|
|
||||||
|
async def test_peek_relationship_phase_preserves_finite_momentum_bands(self) -> None:
|
||||||
|
service = self.make_service()
|
||||||
|
ctx = SessionContext(
|
||||||
|
session_id="qq:FriendMessage:finite-user",
|
||||||
|
scope="private",
|
||||||
|
platform="qq",
|
||||||
|
user_id="finite-user",
|
||||||
|
)
|
||||||
|
|
||||||
|
for momentum, momentum_band in ((-0.08, "cooling"), (0, "steady"), (0.08, "rising")):
|
||||||
|
service._relationship_phase_state = {
|
||||||
|
service._phase_key(ctx): {"phase": "close", "momentum": momentum, "touch_count": 1}
|
||||||
|
}
|
||||||
|
before = json.dumps(service._relationship_phase_state, sort_keys=True)
|
||||||
|
self.assertEqual(
|
||||||
|
{"observed": True, "phase": "close", "momentum_band": momentum_band, "touch_count": 1},
|
||||||
|
service._peek_relationship_phase(ctx),
|
||||||
|
)
|
||||||
|
self.assertEqual(before, json.dumps(service._relationship_phase_state, sort_keys=True))
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|
|
||||||
正在加载…
添加表格
在新工单中引用