feat: add calendar-aware ops memory history
这个提交存在于:
父节点
efd6fab38b
当前提交
bcd9d9aba0
共有 13 个文件被更改,包括 918 次插入 和 13 次删除
|
|
@ -47,6 +47,16 @@ class MemoryCompanionBridge:
|
||||||
def probe_ops_contract(self) -> dict[str, Any]:
|
def probe_ops_contract(self) -> dict[str, Any]:
|
||||||
return OpsDomainContract.to_dict()
|
return OpsDomainContract.to_dict()
|
||||||
|
|
||||||
|
def probe_calendar_contract(self) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"version": "1.0",
|
||||||
|
"available": callable(getattr(self._plugin, "record_calendar_event", None)),
|
||||||
|
"write_mode": "history_only",
|
||||||
|
"calendar_owner": "private_companion_calendar_store",
|
||||||
|
"memory_role": "historical_context",
|
||||||
|
"dynamic_age_persisted": False,
|
||||||
|
}
|
||||||
|
|
||||||
def normalize_ops_event(self, value: Any) -> dict[str, Any]:
|
def normalize_ops_event(self, value: Any) -> dict[str, Any]:
|
||||||
return normalize_ops_event(value)
|
return normalize_ops_event(value)
|
||||||
|
|
||||||
|
|
@ -104,6 +114,44 @@ class MemoryCompanionBridge:
|
||||||
occurred_at=occurred_at,
|
occurred_at=occurred_at,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
async def record_calendar_event(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
event_id: str,
|
||||||
|
calendar: str = "personal_agenda",
|
||||||
|
title: str = "",
|
||||||
|
summary: str = "",
|
||||||
|
start_at: str = "",
|
||||||
|
end_at: str = "",
|
||||||
|
timezone: str = "Asia/Shanghai",
|
||||||
|
status: str = "planned",
|
||||||
|
source: str = "bot_generated",
|
||||||
|
related_task_id: str = "",
|
||||||
|
occurred_at: str = "",
|
||||||
|
change_reason: str = "",
|
||||||
|
metadata: dict[str, Any] | None = None,
|
||||||
|
source_plugin: str = "astrbot_plugin_private_companion",
|
||||||
|
) -> str:
|
||||||
|
recorder = getattr(self._plugin, "record_calendar_event", None)
|
||||||
|
if not callable(recorder):
|
||||||
|
raise RuntimeError("\u8bb0\u5fc6\u63d2\u4ef6\u4e0d\u652f\u6301\u65e5\u5386\u5386\u53f2 Bridge")
|
||||||
|
return await recorder(
|
||||||
|
event_id=event_id,
|
||||||
|
calendar=calendar,
|
||||||
|
title=title,
|
||||||
|
summary=summary,
|
||||||
|
start_at=start_at,
|
||||||
|
end_at=end_at,
|
||||||
|
timezone=timezone,
|
||||||
|
status=status,
|
||||||
|
source=source,
|
||||||
|
related_task_id=related_task_id,
|
||||||
|
occurred_at=occurred_at,
|
||||||
|
change_reason=change_reason,
|
||||||
|
metadata=metadata or {},
|
||||||
|
source_plugin=source_plugin,
|
||||||
|
)
|
||||||
|
|
||||||
async def record_bot_action(self, *, content: str, **kwargs: Any) -> str:
|
async def record_bot_action(self, *, content: str, **kwargs: Any) -> str:
|
||||||
kwargs.setdefault("memory_type", "self_action")
|
kwargs.setdefault("memory_type", "self_action")
|
||||||
kwargs.setdefault("visibility", "bot_self")
|
kwargs.setdefault("visibility", "bot_self")
|
||||||
|
|
@ -557,13 +605,20 @@ def serialize_memory(record: MemoryRecord, score: float | None = None, reason: s
|
||||||
"updated_at_local": _local_time_label(record.updated_at),
|
"updated_at_local": _local_time_label(record.updated_at),
|
||||||
"occurred_at": record.occurred_at,
|
"occurred_at": record.occurred_at,
|
||||||
"occurred_at_local": _local_time_label(record.occurred_at),
|
"occurred_at_local": _local_time_label(record.occurred_at),
|
||||||
|
"time_source": clean_text(metadata.get("time_source"), 80),
|
||||||
|
"time_precision": clean_text(metadata.get("time_precision"), 40),
|
||||||
|
"occurred_at_estimated": bool(metadata.get("occurred_at_estimated", False)),
|
||||||
|
"memory_layer": clean_text(metadata.get("memory_layer"), 80),
|
||||||
|
"calendar_event_id": clean_text(metadata.get("calendar_event_id"), 120),
|
||||||
|
"calendar_status": clean_text(metadata.get("status"), 40),
|
||||||
|
"historical_only": clean_text(metadata.get("memory_layer"), 80) == "calendar_history",
|
||||||
"temporal": build_temporal_memory_meta(record),
|
"temporal": build_temporal_memory_meta(record),
|
||||||
"time_range": {
|
"time_range": {
|
||||||
"start_at": clean_text(metadata.get("start_at"), 80),
|
"start_at": clean_text(metadata.get("start_at"), 80),
|
||||||
"end_at": clean_text(metadata.get("end_at"), 80),
|
"end_at": clean_text(metadata.get("end_at"), 80),
|
||||||
"start_at_local": clean_text(metadata.get("start_at_local"), 80) or _local_time_label(metadata.get("start_at")),
|
"start_at_local": clean_text(metadata.get("start_at_local"), 80) or _local_time_label(metadata.get("start_at")),
|
||||||
"end_at_local": clean_text(metadata.get("end_at_local"), 80) or _local_time_label(metadata.get("end_at")),
|
"end_at_local": clean_text(metadata.get("end_at_local"), 80) or _local_time_label(metadata.get("end_at")),
|
||||||
"timezone": "Asia/Shanghai",
|
"timezone": clean_text(metadata.get("timezone"), 80) or "Asia/Shanghai",
|
||||||
},
|
},
|
||||||
"subject": {
|
"subject": {
|
||||||
"kind": record.subject.kind,
|
"kind": record.subject.kind,
|
||||||
|
|
|
||||||
|
|
@ -332,6 +332,8 @@ class InjectionComposer:
|
||||||
source_label = self._safe_text(self._source_label(memory), 100)
|
source_label = self._safe_text(self._source_label(memory), 100)
|
||||||
temporal = build_temporal_memory_meta(memory, now)
|
temporal = build_temporal_memory_meta(memory, now)
|
||||||
usage = self._expression_usage(item) if not compact else f"表达:{self._expression_label(item)}"
|
usage = self._expression_usage(item) if not compact else f"表达:{self._expression_label(item)}"
|
||||||
|
is_calendar_history = clean_text(getattr(memory, "memory_type", ""), 80).lower() == "calendar_event"
|
||||||
|
calendar_status = self._safe_text(metadata.get("status"), 24)
|
||||||
parts = [f"内容:{detail}"]
|
parts = [f"内容:{detail}"]
|
||||||
if compact:
|
if compact:
|
||||||
parts.extend([
|
parts.extend([
|
||||||
|
|
@ -340,6 +342,7 @@ class InjectionComposer:
|
||||||
f"跨日:{'是' if temporal.get('crossed_date') else '否'}",
|
f"跨日:{'是' if temporal.get('crossed_date') else '否'}",
|
||||||
f"状态:{'不能代表当前实时事实' if temporal.get('stale') else '历史背景' if temporal.get('age_label') not in {'just_now', 'recent', 'same_day'} else '近期参考'}",
|
f"状态:{'不能代表当前实时事实' if temporal.get('stale') else '历史背景' if temporal.get('age_label') not in {'just_now', 'recent', 'same_day'} else '近期参考'}",
|
||||||
f"来源:{source_label}",
|
f"来源:{source_label}",
|
||||||
|
*(["\u8bb0\u5fc6\u5c42\uff1a\u65e5\u5386\u5386\u53f2\uff08\u4ec5\u4f5c\u5386\u53f2\u80cc\u666f\uff09", f"\u65e5\u5386\u72b6\u6001\uff1a{calendar_status or 'unknown'}"] if is_calendar_history else []),
|
||||||
])
|
])
|
||||||
else:
|
else:
|
||||||
parts.extend([
|
parts.extend([
|
||||||
|
|
@ -353,6 +356,7 @@ class InjectionComposer:
|
||||||
f"时间来源:{self._safe_text(temporal.get('time_source'), 32)}",
|
f"时间来源:{self._safe_text(temporal.get('time_source'), 32)}",
|
||||||
f"时间精度:{self._safe_text(temporal.get('time_precision'), 16)}",
|
f"时间精度:{self._safe_text(temporal.get('time_precision'), 16)}",
|
||||||
f"来源:{source_label}",
|
f"来源:{source_label}",
|
||||||
|
*(["\u8bb0\u5fc6\u5c42\uff1a\u65e5\u5386\u5386\u53f2\uff08\u4ec5\u4f5c\u5386\u53f2\u80cc\u666f\uff09", f"\u65e5\u5386\u72b6\u6001\uff1a{calendar_status or 'unknown'}"] if is_calendar_history else []),
|
||||||
])
|
])
|
||||||
if compact:
|
if compact:
|
||||||
parts.extend(
|
parts.extend(
|
||||||
|
|
|
||||||
102
core/service.py
102
core/service.py
|
|
@ -625,7 +625,7 @@ class MemoryCompanionService:
|
||||||
|
|
||||||
async def record_external_event(self, **kwargs: Any) -> str:
|
async def record_external_event(self, **kwargs: Any) -> str:
|
||||||
if not self.config.bool("private_companion_bridge.accept_external_records", True):
|
if not self.config.bool("private_companion_bridge.accept_external_records", True):
|
||||||
raise RuntimeError("外部记忆写入已关闭")
|
raise RuntimeError("外部记息写入已关闭")
|
||||||
|
|
||||||
explicit_id = clean_text(kwargs.pop("memory_id", "") or kwargs.pop("id", ""), 120)
|
explicit_id = clean_text(kwargs.pop("memory_id", "") or kwargs.pop("id", ""), 120)
|
||||||
record = self.classifier.external_record(**kwargs)
|
record = self.classifier.external_record(**kwargs)
|
||||||
|
|
@ -662,6 +662,106 @@ class MemoryCompanionService:
|
||||||
)
|
)
|
||||||
return memory_id
|
return memory_id
|
||||||
|
|
||||||
|
async def record_calendar_event(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
event_id: str,
|
||||||
|
calendar: str = "personal_agenda",
|
||||||
|
title: str = "",
|
||||||
|
summary: str = "",
|
||||||
|
start_at: str = "",
|
||||||
|
end_at: str = "",
|
||||||
|
timezone: str = "Asia/Shanghai",
|
||||||
|
status: str = "planned",
|
||||||
|
source: str = "bot_generated",
|
||||||
|
related_task_id: str = "",
|
||||||
|
occurred_at: str = "",
|
||||||
|
change_reason: str = "",
|
||||||
|
metadata: dict[str, Any] | None = None,
|
||||||
|
source_plugin: str = "astrbot_plugin_private_companion",
|
||||||
|
) -> str:
|
||||||
|
if not self.config.bool("private_companion_bridge.accept_external_records", True):
|
||||||
|
raise RuntimeError("外部记息写入已关闭")
|
||||||
|
|
||||||
|
allowed_calendars = {
|
||||||
|
"personal_agenda",
|
||||||
|
"work_agenda",
|
||||||
|
"maintenance_agenda",
|
||||||
|
"external_schedule",
|
||||||
|
}
|
||||||
|
allowed_statuses = {"planned", "active", "completed", "cancelled"}
|
||||||
|
event_id = clean_text(event_id, 120)
|
||||||
|
calendar = clean_text(calendar, 40).lower() or "personal_agenda"
|
||||||
|
title = clean_text(title, 240)
|
||||||
|
summary = clean_text(summary, 1000)
|
||||||
|
start_at = clean_text(start_at, 80)
|
||||||
|
end_at = clean_text(end_at, 80)
|
||||||
|
timezone_name = clean_text(timezone, 80) or "Asia/Shanghai"
|
||||||
|
status = clean_text(status, 40).lower() or "planned"
|
||||||
|
source = clean_text(source, 120) or "unknown"
|
||||||
|
related_task_id = clean_text(related_task_id, 160)
|
||||||
|
occurred_at = clean_text(occurred_at, 80)
|
||||||
|
change_reason = clean_text(change_reason, 500)
|
||||||
|
if not event_id:
|
||||||
|
raise ValueError("event_id is required")
|
||||||
|
if not title and not summary:
|
||||||
|
raise ValueError("title or summary is required")
|
||||||
|
if calendar not in allowed_calendars:
|
||||||
|
raise ValueError(f"unsupported calendar: {calendar}")
|
||||||
|
if status not in allowed_statuses:
|
||||||
|
raise ValueError(f"unsupported calendar status: {status}")
|
||||||
|
try:
|
||||||
|
ZoneInfo(timezone_name)
|
||||||
|
except Exception:
|
||||||
|
timezone_name = "Asia/Shanghai"
|
||||||
|
start_dt = self._parse_iso(start_at)
|
||||||
|
end_dt = self._parse_iso(end_at)
|
||||||
|
if start_dt is None or end_dt is None or end_dt <= start_dt:
|
||||||
|
raise ValueError("start_at and end_at must be valid, and end_at must be after start_at")
|
||||||
|
event_occurred_at = occurred_at or start_at
|
||||||
|
event_metadata = dict(metadata or {})
|
||||||
|
event_metadata.update(
|
||||||
|
{
|
||||||
|
"memory_layer": "calendar_history",
|
||||||
|
"calendar_event_id": event_id,
|
||||||
|
"calendar": calendar,
|
||||||
|
"title": title,
|
||||||
|
"summary": summary,
|
||||||
|
"start_at": start_at,
|
||||||
|
"end_at": end_at,
|
||||||
|
"timezone": timezone_name,
|
||||||
|
"status": status,
|
||||||
|
"source": source,
|
||||||
|
"related_task_id": related_task_id,
|
||||||
|
"change_reason": change_reason,
|
||||||
|
"time_source": "calendar_event",
|
||||||
|
"time_precision": "second" if event_occurred_at[11:].count(":") >= 2 else "minute",
|
||||||
|
"occurred_at_estimated": not bool(occurred_at),
|
||||||
|
"historical_only": True,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
content = f"日历历史:{title or summary}\n状态:{status}\n时间:{start_at} - {end_at}"
|
||||||
|
if change_reason:
|
||||||
|
content += f"\n变更原因:{change_reason}"
|
||||||
|
memory_id = self.stable_id("calendar_event", event_id)
|
||||||
|
return await self.record_external_event(
|
||||||
|
memory_id=memory_id,
|
||||||
|
content=content,
|
||||||
|
memory_type="calendar_event",
|
||||||
|
scope="private",
|
||||||
|
session_id="calendar_history",
|
||||||
|
visibility="bot_self",
|
||||||
|
sayability="indirect",
|
||||||
|
reality_level="calendar_history",
|
||||||
|
lifecycle="stable_memory",
|
||||||
|
confidence=0.95,
|
||||||
|
importance=0.55,
|
||||||
|
tags=["calendar_event", "calendar_history"],
|
||||||
|
metadata=event_metadata,
|
||||||
|
source_plugin=source_plugin,
|
||||||
|
occurred_at=event_occurred_at,
|
||||||
|
)
|
||||||
|
|
||||||
async def bridge_search(
|
async def bridge_search(
|
||||||
self,
|
self,
|
||||||
query: str,
|
query: str,
|
||||||
|
|
|
||||||
139
core/store.py
139
core/store.py
|
|
@ -1210,7 +1210,11 @@ class MemoryStore:
|
||||||
data = record.to_db()
|
data = record.to_db()
|
||||||
columns = ", ".join(data.keys())
|
columns = ", ".join(data.keys())
|
||||||
placeholders = ", ".join(f":{key}" for key in data.keys())
|
placeholders = ", ".join(f":{key}" for key in data.keys())
|
||||||
updates = ", ".join(f"{key}=excluded.{key}" for key in data.keys() if key != "id")
|
updates = ", ".join(
|
||||||
|
f"{key}=excluded.{key}"
|
||||||
|
for key in data.keys()
|
||||||
|
if key not in {"id", "created_at"}
|
||||||
|
)
|
||||||
with self._lock:
|
with self._lock:
|
||||||
duplicate = None
|
duplicate = None
|
||||||
if record.content_fingerprint:
|
if record.content_fingerprint:
|
||||||
|
|
@ -1837,6 +1841,139 @@ class MemoryStore:
|
||||||
).fetchall()
|
).fetchall()
|
||||||
return [dict(row) for row in rows]
|
return [dict(row) for row in rows]
|
||||||
|
|
||||||
|
async def knowledge_graph_observation(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
limit: int = 180,
|
||||||
|
scope: str = "",
|
||||||
|
session_id: str = "",
|
||||||
|
group_id: str = "",
|
||||||
|
node: str = "",
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
return await asyncio.to_thread(
|
||||||
|
self._knowledge_graph_observation_sync,
|
||||||
|
limit,
|
||||||
|
scope,
|
||||||
|
session_id,
|
||||||
|
group_id,
|
||||||
|
node,
|
||||||
|
)
|
||||||
|
|
||||||
|
def _knowledge_graph_observation_sync(
|
||||||
|
self,
|
||||||
|
limit: int,
|
||||||
|
scope: str,
|
||||||
|
session_id: str,
|
||||||
|
group_id: str,
|
||||||
|
node: str,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
limit = max(1, min(500, int(limit or 180)))
|
||||||
|
scope = clean_text(scope, 40)
|
||||||
|
session_id = clean_text(session_id, 200)
|
||||||
|
group_id = clean_text(group_id, 120)
|
||||||
|
node = clean_text(node, 160)
|
||||||
|
edge_where = "1=1"
|
||||||
|
edge_params: list[Any] = []
|
||||||
|
node_where = "1=1"
|
||||||
|
node_params: list[Any] = []
|
||||||
|
if scope:
|
||||||
|
edge_where += " AND e.scope=?"
|
||||||
|
edge_params.append(scope)
|
||||||
|
node_where += " AND n.scope=?"
|
||||||
|
node_params.append(scope)
|
||||||
|
if session_id:
|
||||||
|
edge_where += " AND e.session_id=?"
|
||||||
|
edge_params.append(session_id)
|
||||||
|
node_where += " AND n.session_id=?"
|
||||||
|
node_params.append(session_id)
|
||||||
|
if group_id:
|
||||||
|
edge_where += " AND e.group_id=?"
|
||||||
|
edge_params.append(group_id)
|
||||||
|
node_where += " AND n.group_id=?"
|
||||||
|
node_params.append(group_id)
|
||||||
|
if node:
|
||||||
|
like = f"%{node}%"
|
||||||
|
edge_where += " AND (s.label LIKE ? OR t.label LIKE ?)"
|
||||||
|
edge_params.extend([like, like])
|
||||||
|
node_where += " AND n.label LIKE ?"
|
||||||
|
node_params.append(like)
|
||||||
|
with self._lock:
|
||||||
|
edges = self._conn.execute(
|
||||||
|
f"""
|
||||||
|
SELECT e.*, s.node_type AS source_type, s.label AS source_label,
|
||||||
|
t.node_type AS target_type, t.label AS target_label
|
||||||
|
FROM knowledge_edges e
|
||||||
|
LEFT JOIN knowledge_nodes s ON s.id=e.source_node_id
|
||||||
|
LEFT JOIN knowledge_nodes t ON t.id=e.target_node_id
|
||||||
|
WHERE {edge_where}
|
||||||
|
ORDER BY e.updated_at DESC
|
||||||
|
LIMIT ?
|
||||||
|
""",
|
||||||
|
edge_params + [limit],
|
||||||
|
).fetchall()
|
||||||
|
nodes = self._conn.execute(
|
||||||
|
f"""
|
||||||
|
SELECT n.*
|
||||||
|
FROM knowledge_nodes n
|
||||||
|
WHERE {node_where}
|
||||||
|
ORDER BY n.updated_at DESC
|
||||||
|
LIMIT ?
|
||||||
|
""",
|
||||||
|
node_params + [min(500, max(60, limit * 2))],
|
||||||
|
).fetchall()
|
||||||
|
memory_where = ["lifecycle != 'archived'"]
|
||||||
|
memory_params: list[Any] = []
|
||||||
|
if scope:
|
||||||
|
memory_where.append("scope=?")
|
||||||
|
memory_params.append(scope)
|
||||||
|
if session_id:
|
||||||
|
memory_where.append("session_id=?")
|
||||||
|
memory_params.append(session_id)
|
||||||
|
if group_id:
|
||||||
|
memory_where.append("group_id=?")
|
||||||
|
memory_params.append(group_id)
|
||||||
|
memory_filter = " AND ".join(memory_where)
|
||||||
|
memory_count = self._conn.execute(
|
||||||
|
f"SELECT COUNT(*) FROM memories WHERE {memory_filter}", memory_params
|
||||||
|
).fetchone()[0]
|
||||||
|
node_count = self._conn.execute(
|
||||||
|
f"SELECT COUNT(*) FROM knowledge_nodes n WHERE {node_where}", node_params
|
||||||
|
).fetchone()[0]
|
||||||
|
edge_count = self._conn.execute(
|
||||||
|
f"SELECT COUNT(*) FROM knowledge_edges e WHERE {edge_where}", edge_params
|
||||||
|
).fetchone()[0]
|
||||||
|
session_where = ["session_id!=''"]
|
||||||
|
session_params: list[Any] = []
|
||||||
|
if scope:
|
||||||
|
session_where.append("scope=?")
|
||||||
|
session_params.append(scope)
|
||||||
|
if session_id:
|
||||||
|
session_where.append("session_id=?")
|
||||||
|
session_params.append(session_id)
|
||||||
|
if group_id:
|
||||||
|
session_where.append("group_id=?")
|
||||||
|
session_params.append(group_id)
|
||||||
|
active_sessions = self._conn.execute(
|
||||||
|
f"SELECT COUNT(DISTINCT session_id) FROM memories WHERE {' AND '.join(session_where)}",
|
||||||
|
session_params,
|
||||||
|
).fetchone()[0]
|
||||||
|
return {
|
||||||
|
"items": [dict(row) for row in edges],
|
||||||
|
"nodes": [dict(row) for row in nodes],
|
||||||
|
"stats": {
|
||||||
|
"memories": int(memory_count or 0),
|
||||||
|
"nodes": int(node_count or 0),
|
||||||
|
"edges": int(edge_count or 0),
|
||||||
|
"active_sessions": int(active_sessions or 0),
|
||||||
|
},
|
||||||
|
"readonly": True,
|
||||||
|
"filters": {
|
||||||
|
"scope": scope,
|
||||||
|
"session_id": session_id,
|
||||||
|
"group_id": group_id,
|
||||||
|
"node": node,
|
||||||
|
},
|
||||||
|
}
|
||||||
async def related_knowledge_terms(
|
async def related_knowledge_terms(
|
||||||
self,
|
self,
|
||||||
terms: list[str],
|
terms: list[str],
|
||||||
|
|
|
||||||
273
docs/记忆插件源码审计与优化档案.md
普通文件
273
docs/记忆插件源码审计与优化档案.md
普通文件
|
|
@ -0,0 +1,273 @@
|
||||||
|
# 运维版记忆插件源码审计与优化档案
|
||||||
|
|
||||||
|
> 审计日期:2026-07-24
|
||||||
|
> 审计对象:`astrbot_plugin_memory_companion_ops`(工作目录:`astrbot_plugin_memory_companion-main`)
|
||||||
|
> 当前分支:`ops-main`
|
||||||
|
> 当前版本:`1.6.2-ops.2`
|
||||||
|
> 审计性质:源码、数据模型、运行链路、面板 API、测试与部署文档的全量结构化复盘;本档案不替代生产验收记录。
|
||||||
|
|
||||||
|
## 1. 结论摘要
|
||||||
|
|
||||||
|
这个插件已经具备“可投入运维场景”的完整骨架:长期记忆、时间线、分层检索、Embedding/Rerank、权限隔离、自然衰减、导入导出、LivingMemory 迁移、Archivist Bridge、Q3 运维事实合同和 Q4 时间感知均已落地,并有较完整的回归测试与 VM 验收证据。
|
||||||
|
|
||||||
|
当前最值得优化的不是再堆一个“记忆类型”,而是把已有能力从“能运行”提升为“可解释、可纠错、可治理”:
|
||||||
|
|
||||||
|
1. 重要性、置信度、新鲜度和人格价值仍然共同影响一个排序分数,缺少独立的事实可信度与召回解释层。
|
||||||
|
2. 记忆可以被 `supersedes_id` 标记,但没有形成完整的冲突检测、版本链、当前有效版本查询和用户可见纠错流程。
|
||||||
|
3. 动态时间元数据已实现,但检索缓存命中后只做权限复验,不重新计算年龄、过期状态或排序分数。
|
||||||
|
4. 维护、导入、导出、迁移能力很丰富,但缺少统一的 dry-run、校验和、分页/流式处理、失败恢复与审计结果模型。
|
||||||
|
5. 观测面板能展示不少运行指标,但还没有“召回质量、误召回、过期事实命中、冲突记忆、注入收益”的闭环指标。
|
||||||
|
|
||||||
|
总体评级:**架构能力强,生产边界清晰;数据治理和质量度量处于下一阶段建设期。**
|
||||||
|
|
||||||
|
## 2. 审计范围与证据
|
||||||
|
|
||||||
|
### 2.1 主要源码范围
|
||||||
|
|
||||||
|
- 数据模型与规范化:`core/models.py`、`core/config.py`
|
||||||
|
- 记忆价值评估:`core/importance.py`
|
||||||
|
- 检索与重排:`core/retrieval.py`
|
||||||
|
- Prompt 注入:`core/injection.py`
|
||||||
|
- 服务编排与维护:`core/service.py`
|
||||||
|
- SQLite 持久化:`core/store.py`
|
||||||
|
- Bridge/Archivist:`core/bridge.py`、`core/archive_contract.py`
|
||||||
|
- 运维合同:`core/ops_domain.py`、`core/operations.py`
|
||||||
|
- 历史导入与 LivingMemory 迁移:`core/chat_import.py`、`core/migration_livingmemory.py`
|
||||||
|
- 面板 HTTP API:`page_api.py`、`pages/记忆面板/app.js`
|
||||||
|
- 测试:`tests/` 全部测试模块
|
||||||
|
|
||||||
|
### 2.2 版本和验收证据
|
||||||
|
|
||||||
|
- Q4 时间感知实现:提交 `8d21776`
|
||||||
|
- Q4 VM 验收文档:提交 `b227a7e`
|
||||||
|
- Q4 完整回归证据:提交 `efd6fab`
|
||||||
|
- 现有验收记录显示:VM 服务 active、`NRestarts=0`、定向测试 `20 passed`、完整回归 `155 passed, 1 warning`,Archivist 发现运维版 `1.6.2-ops.2`。
|
||||||
|
- 本次审计以源码为准;README 或验收文档中未能由源码、测试或实机证据互相印证的内容,均标记为“需补证”。
|
||||||
|
|
||||||
|
## 3. 整体架构与数据流
|
||||||
|
|
||||||
|
```text
|
||||||
|
AstrBot 事件
|
||||||
|
-> identity/session 解析
|
||||||
|
-> classifier / time_intent / reply_chain
|
||||||
|
-> timeline 原始事件
|
||||||
|
-> summarizer / importance evaluator
|
||||||
|
-> memories + relationship_edges + knowledge graph
|
||||||
|
-> retrieval: 当前窗口 / 时间窗口 / FTS / 关键词 / 向量 / 图扩展
|
||||||
|
-> visibility + ACL + mutable-fact collapse + source dedupe
|
||||||
|
-> slot orchestration
|
||||||
|
-> injection composer + temporal metadata
|
||||||
|
-> LLM 请求
|
||||||
|
|
||||||
|
外部路径:
|
||||||
|
Controller 事实 -> Q3 OpsFactRef/OpsEvent -> Bridge/人格层
|
||||||
|
LivingMemory/QQ 历史 -> preview -> import batch -> 记忆/时间线/关系
|
||||||
|
面板 -> page_api -> service/store -> 维护、导出、审查、修复
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.1 数据模型优点
|
||||||
|
|
||||||
|
`MemoryRecord` 已明确区分 `occurred_at`、`created_at`、`updated_at`、`last_accessed_at`,并保存 `confidence`、`importance`、`visibility`、`lifecycle`、`review_status`、`supersedes_id` 和 `metadata`(`core/models.py:97-167`)。这为时间感知、事实等级和后续版本链提供了正确基础。
|
||||||
|
|
||||||
|
SQLite 层启用 WAL、外键和 busy timeout,并有事务、连接恢复、删除级联和 revision 机制(`core/store.py:35-45`、`core/store.py:184-236`)。这是生产稳定性的良好基础。
|
||||||
|
|
||||||
|
## 4. 能力矩阵
|
||||||
|
|
||||||
|
| 能力 | 状态 | 证据/说明 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 长期记忆与时间线 | 已实现 | `MemoryRecord`、`timeline` 表、阶段总结链路 |
|
||||||
|
| 重要性评估 | 已实现但需治理 | `core/importance.py:15-78`,多维人格价值评分 |
|
||||||
|
| 置信度与审查队列 | 部分实现 | 字段和 review queue 存在,但缺少统一人工校准流程 |
|
||||||
|
| 分层检索 | 已实现 | `core/retrieval.py:878-1025`,当前窗口/时间窗口/FTS/关键词/向量 |
|
||||||
|
| Rerank/Embedding | 已实现 | 配置、候选缓存、超时与降级路径存在 |
|
||||||
|
| 权限与 ACL | 已实现 | 可见性、scope、session、group、ACL 复验和缓存失效测试 |
|
||||||
|
| 记忆去重 | 部分实现 | fingerprint、mutable fact collapse、LivingMemory source dedupe;通用语义去重不足 |
|
||||||
|
| 冲突/替代 | 部分实现 | `supersedes_id`、归档原因存在,但没有完整冲突图和当前版本查询 |
|
||||||
|
| 时间感知 | 已实现 | `core/temporal_context.py`,动态 age/stale/relative label |
|
||||||
|
| Prompt 注入预算 | 已实现 | slot 编排、compact 模式、字符上限;缺少 token 级质量度量 |
|
||||||
|
| 自然衰减 | 已实现但有误伤风险 | `core/service.py:3760-3880`,按保护类型/标签/权重筛选 |
|
||||||
|
| LivingMemory 迁移 | 已实现 | preview、批次、修复路径和回滚能力存在 |
|
||||||
|
| JSONL 迁移 | 已实现但规模有限 | `core/operations.py:303-631`,64 MiB 上限、整批载入 |
|
||||||
|
| 运维事实合同 | 已实现 | `core/ops_domain.py:37-325`,只校验不执行外部操作 |
|
||||||
|
| 运行时兼容 | 已实现 | capability probe 与降级状态 |
|
||||||
|
| 面板管理 | 已实现 | `page_api.py:68-113`,记忆、维护、导入、ACL、Bridge 路由 |
|
||||||
|
| 可观测性 | 部分实现 | 有耗时、Token、缓存、WAL、路径诊断;缺少质量指标 |
|
||||||
|
|
||||||
|
## 5. 已实现且建议保留的设计
|
||||||
|
|
||||||
|
### 5.1 时间与事实边界
|
||||||
|
|
||||||
|
Q4 的动态时间合同是正确方向:年龄、相对标签、跨日、过期原因在输出时计算,不写死到数据库;`MemoryRecord.ensure_defaults()` 只写入来源、时区、精度和估算标记(`core/models.py:129-146`)。`build_temporal_memory_meta()` 输出 `age_seconds`、`age_label`、`relative_label`、`stale`、`time_source` 等字段(`core/temporal_context.py:166-197`)。
|
||||||
|
|
||||||
|
Q3 规定 Controller 事实优先于记忆,且合同层不执行 Shell/SSH/Docker,是运维插件必须坚持的安全边界。
|
||||||
|
|
||||||
|
### 5.2 权限与跨窗口隔离
|
||||||
|
|
||||||
|
检索前做 visibility/ACL 过滤,缓存命中后还会重新读取当前记录并复验权限(`core/retrieval.py:94-142`)。跨窗口、群聊/私聊和 Bot 自我时间线已有专门测试,明显优于“把所有历史拼成一个 prompt”的实现。
|
||||||
|
|
||||||
|
### 5.3 存储一致性与可恢复性
|
||||||
|
|
||||||
|
删除记忆有级联和事务回滚测试;WAL、busy timeout、连接恢复、revision 和 embedding 表设计较完整。`tests/test_store_consistency.py` 与 `tests/test_security_cache.py` 已覆盖多项高风险边界。
|
||||||
|
|
||||||
|
### 5.4 迁移可逆性
|
||||||
|
|
||||||
|
LivingMemory 和历史聊天导入都带批次概念;JSONL 导入前备份,历史聊天有 rollback 路由。这使插件具备从旧生态迁移而不直接破坏主库的能力。
|
||||||
|
|
||||||
|
## 6. 重点欠缺与优化清单
|
||||||
|
|
||||||
|
优先级定义:P0=会造成严重数据/权限/生产风险;P1=会造成明显事实错误或维护成本;P2=质量、效率和产品体验提升。
|
||||||
|
|
||||||
|
### P1-01:重要性分数承担了过多语义
|
||||||
|
|
||||||
|
- 现象:一个 `importance` 同时承载长期价值、人格意义、内容类型、生命周期和部分新鲜度;检索又直接把 `importance` 乘以 `0.55`,同时叠加 `confidence*0.25`、recency、persona、dynamics(`core/importance.py:49-78`、`core/retrieval.py:2191-2254`)。
|
||||||
|
- 根因:没有把“是否值得记住”“是否可信”“是否适合当前提及”“是否仍是当前事实”拆成独立可解释信号。
|
||||||
|
- 影响:高重要但过期的服务状态可能仍有较强召回;低重要但与当前问题高度匹配的事实可能被压下去;分数变化难以向用户解释。
|
||||||
|
- 建议:新增 `memory_value`、`fact_confidence`、`mentionability`、`freshness_state` 四个逻辑维度;保留旧 `importance` 作为兼容字段,检索改用可解释的分桶/门控。
|
||||||
|
- 可实施性:可以立即做合同和评分单元测试,下一阶段再替换排序公式。
|
||||||
|
|
||||||
|
### P1-02:人工重要性修改没有形成“覆盖层”
|
||||||
|
|
||||||
|
- 证据:面板更新接口直接接受 `importance`、`confidence`、`lifecycle` 等字段(`page_api.py:454-470`);评估器在 `calibrate()` 中用 `metadata.setdefault("base_importance", ...)` 保存基线(`core/importance.py:15-47`)。
|
||||||
|
- 风险:人工调整与自动重算的关系不清楚;重跑校准时可能继续使用旧基线,用户无法知道“手动 0.9”是否被模型覆盖或只影响一次。
|
||||||
|
- 建议:增加 `manual_importance_override`、`override_reason`、`override_by`、`override_at`、`calibration_version`;UI 显示“自动分/人工分/最终分”。
|
||||||
|
- 可实施性:中等,属于数据契约扩展,可先只写 metadata,无需立即迁移表结构。
|
||||||
|
|
||||||
|
### P1-03:缓存命中后不重新计算时间状态和排序
|
||||||
|
|
||||||
|
- 证据:服务把结果按 revision/config/query/time intent 缓存(`core/service.py:1450-1516`),命中后调用 `revalidate_cached_results()`,该函数只刷新记录并复验权限,不重新跑 `_score()`、过期门控或 `temporal`(`core/retrieval.py:94-116`;`core/service.py:1618-1628`)。
|
||||||
|
- 影响:短 TTL 内跨过天气/服务状态 TTL 时,旧结果仍可能保留;缓存中的 `score` 和 `reason` 反映命中时刻而不是当前时刻。
|
||||||
|
- 建议:缓存命中后至少执行:动态 stale 门控、age bucket 变化检查、可变事实 collapse;若 age bucket 或 stale 状态变化则重新排序或放弃缓存。
|
||||||
|
- 可实施性:高,优先级高,风险低。
|
||||||
|
|
||||||
|
### P1-04:冲突与版本链不完整
|
||||||
|
|
||||||
|
- 现状:模型有 `supersedes_id`,维护归档会写入 `decay_archived`(`core/models.py:127`、`core/store.py:4853-4888`),检索对 mutable fact 有特定 collapse,但这不是通用事实冲突治理。
|
||||||
|
- 欠缺:没有统一的 `conflict_set_id`、`superseded_by`、生效时间区间、冲突原因和当前版本查询;无法可靠回答“哪个是最新事实、旧事实为什么失效”。
|
||||||
|
- 建议:为偏好、账号、地址、服务状态、计划等可变事实建立 conflict family;写入时检测同 owner/subject/key 的候选,旧版本标记 `superseded`,保留证据和替代关系;检索默认只返回当前有效版本,历史查询显式展开。
|
||||||
|
- 可实施性:中高;先覆盖运维服务状态、计划和联系方式,避免一次性推广到所有文本记忆。
|
||||||
|
|
||||||
|
### P1-05:衰减策略保护规则偏硬,缺少 dry-run 与人工复核
|
||||||
|
|
||||||
|
- 证据:`_decay_candidate()` 通过类型、标签、权重、phase、visibility 直接跳过或纳入衰减(`core/service.py:3760-3804`);分组后达到最小条数才调用摘要(`core/service.py:3718-3758`)。
|
||||||
|
- 风险:保护类型列表与 metadata 可能漂移;低频但重要的关系/创作片段可能因分类错误进入压缩;摘要失败时只能记录错误,缺少逐组重试和人工预览。
|
||||||
|
- 建议:维护接口增加 `dry_run=true`,返回候选、排除原因、预计摘要内容和影响范围;实际执行使用确认 token;每个摘要保留 `source_memory_ids`、摘要版本和可逆恢复入口。
|
||||||
|
- 可实施性:高,先做 dry-run 和报告即可明显降低运维风险。
|
||||||
|
|
||||||
|
### P1-06:导入/导出路径适合中小库,不适合大库
|
||||||
|
|
||||||
|
- 证据:JSONL 导出一次性读取最多 `1_000_000` 条记忆、时间线、关系和 ACL(`core/operations.py:309-315`);单文件上限为 64 MiB,导入读取后把全部记录放进内存(`core/operations.py:15-17`、`602-631`)。
|
||||||
|
- 影响:库变大后内存峰值、导出耗时和失败重试成本明显上升;导入没有逐段 checkpoint,长任务中断后只能整体重来。
|
||||||
|
- 建议:改为分页/游标式导出;JSONL 按块写入并带 SHA-256、记录数和 schema 版本;导入按 record_type 分批提交,保存 checkpoint,支持断点续传和单类回滚。
|
||||||
|
- 可实施性:中等,适合下一阶段数据治理版本。
|
||||||
|
|
||||||
|
### P1-07:迁移/导入的“选择哪一个源库”仍较隐式
|
||||||
|
|
||||||
|
- 证据:LivingMemory `preview()` 枚举候选路径,`import_data()` 使用 `preview["candidates"][0]` 作为导入源(`core/migration_livingmemory.py:72-95`)。
|
||||||
|
- 风险:同一环境存在多个旧库、备份库或测试库时,可能导入错误候选;用户只能在事后从批次记录发现来源。
|
||||||
|
- 建议:预览返回候选排序依据、文件大小、mtime、表计数和健康检查;导入必须携带明确 `source_path` 或候选 ID,默认拒绝隐式第一项。
|
||||||
|
- 可实施性:高。
|
||||||
|
|
||||||
|
### P1-08:外部事实的 TTL 已有合同,但通用记忆检索没有统一 stale gate
|
||||||
|
|
||||||
|
- 证据:Q3 `OpsFactRef` 有 `expires_at`/`stale_after_seconds`;Q4 `temporal_context` 能判断天气、服务状态等主题过期;但核心 `_score()` 主要使用 recency bonus,未把 `stale` 作为通用硬门控(`core/retrieval.py:2237-2247`)。
|
||||||
|
- 影响:Bridge 出口能告诉调用方“过期”,主检索路径仍可能先选出再注入,取决于上层是否额外处理。
|
||||||
|
- 建议:把 `stale_policy` 写入检索结果:`exclude`、`background_only`、`allow_with_warning`;运维状态、天气、人体状态默认为 exclude/background-only。
|
||||||
|
- 可实施性:高,先在运维记忆类型和 topic_expiry 上启用。
|
||||||
|
|
||||||
|
### P2-01:检索解释还不够面向运维排查
|
||||||
|
|
||||||
|
- 现状:reason 字符串包含 hits、bm25、vector、importance、persona、recency(`core/retrieval.py:2250-2254`),但没有显示“为何被过滤、为何比另一个候选高、是否因 stale/冲突被降级”。
|
||||||
|
- 建议:输出结构化 `score_breakdown`、`filter_decisions`、`source_path`、`freshness_decision`,字符串只作为兼容展示。
|
||||||
|
|
||||||
|
### P2-02:注入预算以字符为主,缺少真实 token 预算与收益统计
|
||||||
|
|
||||||
|
- 证据:注入器使用 `max_chars`、section 限额和 compact 模式控制包大小(`core/injection.py:15-100`)。
|
||||||
|
- 欠缺:中文、代码、表格、不同模型 tokenizer 的实际 token 成本不同;没有记录每个 slot 的 token 占用、命中后是否被模型使用或造成重复。
|
||||||
|
- 建议:增加 tokenizer 可选适配;至少记录估算 token、slot、被截断原因和最终响应任务类型,建立“每 1k token 带来的有效命中”指标。
|
||||||
|
|
||||||
|
### P2-03:通用语义去重弱于特定场景去重
|
||||||
|
|
||||||
|
- 现状:有 content fingerprint、mutable fact collapse 和 LivingMemory source dedupe,但不是通用语义级 merge;同一事实来自消息、导入摘要、人工笔记和外部插件时,可能保留多份。
|
||||||
|
- 建议:建立 canonical fact key、来源优先级和合并策略;保留证据列表,不直接覆盖原文。
|
||||||
|
|
||||||
|
### P2-04:关系阶段状态是文件级 JSON,缺少数据库治理
|
||||||
|
|
||||||
|
- 证据:关系阶段状态从文件加载并原子替换保存(`core/service.py:7465-7484`)。
|
||||||
|
- 风险:多进程/多实例同时写入时没有锁、版本号或合并策略;备份、迁移和按用户清理也不随 SQLite 事务统一完成。
|
||||||
|
- 建议:迁移到 SQLite 独立表或至少增加 file lock、revision、冲突恢复和备份纳入范围。
|
||||||
|
|
||||||
|
### P2-05:面板危险操作需要更强的二次确认与审计
|
||||||
|
|
||||||
|
- 证据:页面直接暴露 `/maintenance/clear_all`、`/maintenance/clear_scope`、`/memory/delete` 等路由(`page_api.py:68-113`)。
|
||||||
|
- 建议:所有清空/批量归档/导入/恢复操作使用 preview -> confirm token -> execute;记录 actor、scope、数量、备份路径、结果和失败原因;默认禁止跨 scope 的管理请求。
|
||||||
|
|
||||||
|
### P2-06:测试偏合同和单元,缺少规模、故障和质量回归
|
||||||
|
|
||||||
|
- 已有:时间合同、权限缓存、存储一致性、历史导入、运维合同、运行时兼容、面板回归等测试。
|
||||||
|
- 欠缺:没有稳定的真实数据集评测召回 precision/recall;没有 10 万级 SQLite 压测、长时间衰减、导入中断恢复、多进程写入、WAL 膨胀、Embedding provider 慢/挂的故障矩阵。
|
||||||
|
- 建议:建立脱敏 fixture 和基准集;每次评分/过滤规则修改自动输出 top-k 命中、过期命中、跨 scope 泄露、注入 token 和 p95 延迟。
|
||||||
|
|
||||||
|
## 7. 按阶段的优化队列
|
||||||
|
|
||||||
|
### 阶段 A:低风险、立即可做
|
||||||
|
|
||||||
|
1. 缓存命中时重新检查 stale、age bucket 和 mutable fact。
|
||||||
|
2. LivingMemory 导入必须显式选择候选源库。
|
||||||
|
3. 维护增加 dry-run、候选排除原因和确认 token。
|
||||||
|
4. 检索结果增加结构化 `score_breakdown` 与 `freshness_decision`。
|
||||||
|
5. 面板危险操作增加 preview/confirm/audit。
|
||||||
|
6. 为上述行为补齐单元测试和一条 VM 回归脚本。
|
||||||
|
|
||||||
|
### 阶段 B:事实治理增强
|
||||||
|
|
||||||
|
1. 引入人工重要性覆盖层和版本化校准元数据。
|
||||||
|
2. 建立 conflict family、superseded 状态、有效期和当前版本查询。
|
||||||
|
3. 为服务状态、天气、身体状态、临时计划启用 stale gate。
|
||||||
|
4. 将摘要压缩结果与源记忆建立可恢复的证据链。
|
||||||
|
|
||||||
|
### 阶段 C:规模化与质量度量
|
||||||
|
|
||||||
|
1. JSONL 导入导出分页化、校验和、断点续传。
|
||||||
|
2. SQLite 大库基准、WAL/备份/恢复演练和多进程写入测试。
|
||||||
|
3. 脱敏召回基准集,追踪 precision@k、stale hit rate、conflict hit rate、cross-scope block rate、injection token p95。
|
||||||
|
4. 评估将关系阶段状态迁移到数据库。
|
||||||
|
|
||||||
|
## 8. 不能在本次源码审计中确认的事项
|
||||||
|
|
||||||
|
- 生产环境真实记忆规模、每日增长量和 WAL 膨胀曲线未在本地源码中确认。
|
||||||
|
- 当前配置是否启用 Embedding/Rerank、各 Provider 实际 p95 和失败率,需要从 VM 运行指标或日志取证。
|
||||||
|
- 真实用户数据下的召回准确率、过期事实命中率和注入收益没有基准集,不能由单元测试推断。
|
||||||
|
- 面板路由是否由宿主统一鉴权、是否存在反向代理层 CSRF 防护,需结合 AstrBot/部署配置审计。
|
||||||
|
|
||||||
|
## 9. 最终判断
|
||||||
|
|
||||||
|
运维版记忆插件的核心方向是正确的:它已经不是简单的“聊天记录检索器”,而是一个带权限、时间、事实边界、迁移和跨插件合同的记忆中枢。
|
||||||
|
|
||||||
|
下一阶段的关键不是继续增加更多记忆类型,而是完成三件事:
|
||||||
|
|
||||||
|
1. **让每次召回都能解释**:为什么选中、为什么过滤、为什么过期、为什么当前不能当事实。
|
||||||
|
2. **让每条事实都能纠错**:谁写入、来自哪里、何时生效、被谁替代、如何恢复。
|
||||||
|
3. **让维护操作可预演可回滚**:先看影响,再确认执行,结果有审计,失败可恢复。
|
||||||
|
|
||||||
|
完成阶段 A 后,插件的生产可运维性会有明显提升;完成阶段 B/C 后,才适合把它作为长期的个人运维知识与陪伴记忆底座。
|
||||||
|
|
||||||
|
## 10. 参考文件
|
||||||
|
|
||||||
|
- `README.md`
|
||||||
|
- `core/models.py`
|
||||||
|
- `core/importance.py`
|
||||||
|
- `core/retrieval.py`
|
||||||
|
- `core/injection.py`
|
||||||
|
- `core/temporal_context.py`
|
||||||
|
- `core/store.py`
|
||||||
|
- `core/service.py`
|
||||||
|
- `core/operations.py`
|
||||||
|
- `core/migration_livingmemory.py`
|
||||||
|
- `core/ops_domain.py`
|
||||||
|
- `core/archive_contract.py`
|
||||||
|
- `core/bridge.py`
|
||||||
|
- `page_api.py`
|
||||||
|
- `tests/`
|
||||||
|
- 项目根目录:`Q3_运维事件与数据模型说明.md`、`Q4_记忆插件时间感知改造要求.md`、`Q4_VM部署验收记录.md`
|
||||||
|
|
||||||
|
> 本档案只记录源码审计发现,不自动修改业务代码;实施优化前应以阶段 A 的合同测试和 dry-run 结果为准。
|
||||||
87
docs/运维记忆错题本.md
普通文件
87
docs/运维记忆错题本.md
普通文件
|
|
@ -0,0 +1,87 @@
|
||||||
|
# 运维记忆插件错题本
|
||||||
|
|
||||||
|
> 适用仓库:`astrbot_plugin_memory_companion-main`
|
||||||
|
> 分支:`ops-main`
|
||||||
|
> 说明:这里只记录运维记忆插件自身的存储、检索、时间感知、Bridge、归档、权限和面板问题;陪伴人格问题记录在另一份错题本中。
|
||||||
|
|
||||||
|
## 2026-07-24 — 动态时间年龄不能写入数据库
|
||||||
|
|
||||||
|
- 阶段:Q4 记忆时间感知改造
|
||||||
|
- 类型:API契约 / 数据安全
|
||||||
|
- 现象:记忆如果只保存“几小时前”“隔了几天”等年龄文本,下一次读取就会过期或失真。
|
||||||
|
- 根因:时间年龄是读取时相对于当前时间计算的动态结果,不是事件本身的永久属性。
|
||||||
|
- 修复或规避:持久化事件发生时间、入库时间、来源、时区和精度;检索时动态生成 `temporal` 信息。
|
||||||
|
- 预防规则:不得把 `age_seconds`、`delay_label` 等动态字段作为永久事实写入数据库;当前运维状态必须重新查询 Controller。
|
||||||
|
- 验证证据:Q4 时间合同测试、`时间感知兼容说明.md` 和 VM 验收记录已覆盖该边界。
|
||||||
|
|
||||||
|
## 2026-07-24 — 长期记忆不能冒充当前运维事实
|
||||||
|
|
||||||
|
- 阶段:运维记忆与 Controller 边界
|
||||||
|
- 类型:安全 / 功能行为
|
||||||
|
- 现象:历史记忆中的“服务正常”“备份完成”可能被模型误认为现在仍然成立。
|
||||||
|
- 根因:记忆系统保存的是历史背景,不能替代本轮实时观察。
|
||||||
|
- 修复或规避:记忆只提供历史摘要、决策理由、任务背景和事实引用;当前服务、任务和备份状态必须来自本轮授权 Controller 结果。
|
||||||
|
- 预防规则:任何“当前正常”“已经完成”“现在运行中”的结论都必须带本轮来源和观察时间。
|
||||||
|
- 验证证据:运维事件合同要求事实引用包含来源、来源编号和观察时间。
|
||||||
|
|
||||||
|
## 2026-07-24 — Archivist 必须在宿主加载完成后重新发现 Bridge
|
||||||
|
|
||||||
|
- 阶段:跨插件联动与 VM 验收
|
||||||
|
- 类型:API契约 / 部署
|
||||||
|
- 现象:Memory Archivist 初始可能报告记忆源不可用,但记忆插件随后已经正常加载。
|
||||||
|
- 根因:Archivist 初始化早于 MemoryCompanion 实例化,只在初始化阶段探测会得到空结果。
|
||||||
|
- 修复或规避:在 AstrBot 宿主加载完成 Hook 中重新解析记忆源,并优先复用当前进程已经加载的 ops Bridge 实例。
|
||||||
|
- 预防规则:跨插件联动必须验证生命周期顺序、实例复用和实机 capability,不只测试模块能否 import。
|
||||||
|
- 验证证据:VM 已验证 `source=memory_companion`、`available=True`、`search=True`。
|
||||||
|
|
||||||
|
## 2026-07-24 — 测试包名必须与运维插件身份一致
|
||||||
|
|
||||||
|
- 阶段:源码复盘与回归验证
|
||||||
|
- 类型:测试 / 构建
|
||||||
|
- 现象:测试仍引用旧包名时,会在收集阶段报 `ModuleNotFoundError`,导致业务测试根本没有执行。
|
||||||
|
- 根因:源码目录、metadata、正式插件包名和测试导入路径没有同步更新。
|
||||||
|
- 修复或规避:测试前先检查正式包名和导入映射;不能把测试收集失败当作测试通过。
|
||||||
|
- 预防规则:插件改名或建立 `_ops` 身份后,必须做全仓旧包名扫描,并在干净环境验证测试收集。
|
||||||
|
- 验证证据:记忆插件既有错题本记录了旧包名导入阻塞及临时别名验证过程。
|
||||||
|
|
||||||
|
## 2026-07-24 — 只读观察窗不能混入写操作
|
||||||
|
|
||||||
|
- 阶段:记忆面板与运维观察
|
||||||
|
- 类型:功能行为 / 安全
|
||||||
|
- 现象:知识图谱、记忆统计和事实观察如果直接混入编辑或删除入口,用户容易误以为观察动作会修改记忆。
|
||||||
|
- 根因:观察数据合同和记忆写操作合同没有在界面与 API 层分开。
|
||||||
|
- 修复或规避:观察窗只返回只读数据和 `readonly=true`;删除、编辑、合并等操作必须单独设计确认、审计和回滚。
|
||||||
|
- 预防规则:所有运维观察能力默认只读;写入能力不能从只读接口隐式派生。
|
||||||
|
- 验证证据:面板回归测试、Node 检查和临时 SQLite 验证已通过。
|
||||||
|
|
||||||
|
|
||||||
|
## 2026-07-24 - Q4.2 calendar history Bridge and stable deduplication
|
||||||
|
|
||||||
|
- Phase: Q4.2 memory temporal fields and calendar linkage
|
||||||
|
- Type: API contract / behavior / test
|
||||||
|
- Symptom: calendar status updates could be mixed with chat or operations facts, and repeated sync could overwrite the first ingestion timestamp.
|
||||||
|
- Root cause: CalendarStore belongs to the companion plugin; the memory side lacked a dedicated historical layer, stable event key, and an insert-time preservation rule.
|
||||||
|
- Fix/workaround: added `record_calendar_event`; stored `memory_type=calendar_event`, `memory_layer=calendar_history`, source and time metadata; derived a stable memory id from `event_id`; SQLite conflict updates now exclude `created_at` and update status plus `updated_at` only.
|
||||||
|
- Prevention rule: calendar linkage uses only the standard Bridge; dynamic age is computed at retrieval time; one event id reuses one memory id; current operations facts still come from Controller/NAS Ops.
|
||||||
|
- Validation evidence: `tests.test_calendar_bridge`, temporal, Bridge and panel regression tests passed; the focused test verifies `created_at` preservation, `updated_at` change, layer isolation and no persisted `age_seconds`.
|
||||||
|
|
||||||
|
## 2026-07-24 - PowerShell stdin can corrupt Chinese source literals
|
||||||
|
|
||||||
|
- Phase: Q4.2 implementation and encoding repair
|
||||||
|
- Type: build / environment
|
||||||
|
- Symptom: Chinese literals added through a PowerShell Python here-string became question marks.
|
||||||
|
- Root cause: the command channel code page is not a reliable UTF-8 transport for Chinese script stdin.
|
||||||
|
- Fix/workaround: all source reads and writes use explicit Python UTF-8; edit scripts use Unicode escapes or `chr()` for Chinese; post-write scans check for question marks and `py_compile`.
|
||||||
|
- Prevention rule: never use PowerShell default encoding to write Chinese source; always verify UTF-8 readability, compilation and `git diff --check`.
|
||||||
|
- Validation evidence: modified Python files read as UTF-8 and pass compilation and focused tests.
|
||||||
|
|
||||||
|
|
||||||
|
## 2026-07-24 - Full discovery includes an unrelated companion dependency
|
||||||
|
|
||||||
|
- Phase: full regression validation
|
||||||
|
- Type: test / environment
|
||||||
|
- Symptom: full `unittest discover` ran 137 test entries, with 136 passing and `test_security_cache` failing during collection because it imports the ordinary companion branch and the environment has no `astrbot` package.
|
||||||
|
- Root cause: the existing test module resolves `page_api` from `astrbot_plugin_private_companion-main`; this ops-only task must not modify that branch, and the local unit-test environment does not provide AstrBot runtime dependencies.
|
||||||
|
- Fix/workaround: kept the ordinary branch unchanged; validated all relevant ops, temporal, Bridge, storage, injection and panel tests separately, and will run discovery excluding only this unrelated module.
|
||||||
|
- Prevention rule: separate pure unit tests from host-runtime integration tests; do not treat a host dependency collection error as a product regression.
|
||||||
|
- Validation evidence: focused suite passed 16/16; `compileall -q core tests` and `git diff --check` passed.
|
||||||
19
docs/错题本.md
19
docs/错题本.md
|
|
@ -181,3 +181,22 @@
|
||||||
- 修复或规避:新增 `core/temporal_context.py`,在检索/注入/Bridge/Archivist 出口动态生成 `temporal`;metadata 只补来源、时区、精度和估算标记;增加 `bridge_get_reply_delay()`,群聊默认不产生私密等待情绪。
|
- 修复或规避:新增 `core/temporal_context.py`,在检索/注入/Bridge/Archivist 出口动态生成 `temporal`;metadata 只补来源、时区、精度和估算标记;增加 `bridge_get_reply_delay()`,群聊默认不产生私密等待情绪。
|
||||||
- 预防规则:不得用 `last_accessed_at` 代替事件时间;不得把 `age_seconds` 写入数据库;运维当前状态必须重新取 Controller 事实,旧记忆只作历史背景。
|
- 预防规则:不得用 `last_accessed_at` 代替事件时间;不得把 `age_seconds` 写入数据库;运维当前状态必须重新取 Controller 事实,旧记忆只作历史背景。
|
||||||
- 验证证据:时间合同测试 13 项通过;非宿主依赖的 unittest 130 项通过;`compileall` 通过;数据库无需迁移,版本升至 `1.6.2-ops.2`。VM 定向测试 `20 passed`,完整回归在双插件 `PYTHONPATH` 下为 `155 passed`;服务 `active` 且 `NRestarts=0`,Archivist 已发现 `1.6.2-ops.2`。
|
- 验证证据:时间合同测试 13 项通过;非宿主依赖的 unittest 130 项通过;`compileall` 通过;数据库无需迁移,版本升至 `1.6.2-ops.2`。VM 定向测试 `20 passed`,完整回归在双插件 `PYTHONPATH` 下为 `155 passed`;服务 `active` 且 `NRestarts=0`,Archivist 已发现 `1.6.2-ops.2`。
|
||||||
|
## 2026-07-24 — 运维版记忆插件源码全量审计
|
||||||
|
|
||||||
|
- 阶段:源码审计与优化规划
|
||||||
|
- 类型:其他 / API契约 / 功能行为 / 运维
|
||||||
|
- 现象:插件已具备重要性、检索、时间感知、权限、迁移、衰减和运维合同,但这些能力的质量与生产边界分散在多个模块,容易把“已实现”误认为“已闭环”。
|
||||||
|
- 根因:重要性、置信度、新鲜度、提及策略和冲突版本尚未拆成统一质量合同;缓存、迁移、维护和危险面板操作也缺少统一的预演、审计和恢复模型。
|
||||||
|
- 修复或规避:完成源码、测试、Q3/Q4 文档和提交记录的交叉审计,形成 `docs/记忆插件源码审计与优化档案.md`;将缓存 stale、冲突版本、导入源选择、衰减 dry-run、结构化评分解释和质量基准列为后续优先队列。
|
||||||
|
- 预防规则:以后新增记忆能力必须同时回答“来源、时效、置信度、冲突、可解释性、可回滚性、测试证据”七项;仅有 README 或单元测试通过不能视为生产闭环。
|
||||||
|
- 验证证据:审计覆盖 `core/`、`page_api.py`、`pages/记忆面板`、`tests/`;既有 Q4 回归记录为 VM 定向 `20 passed`、完整回归 `155 passed, 1 warning`,未对本阶段报告新增业务代码。
|
||||||
|
|
||||||
|
## 2026-07-24 — 只读记忆观察窗必须与写操作隔离
|
||||||
|
|
||||||
|
- 阶段:记忆观察窗实现
|
||||||
|
- 类型:功能行为 / API契约 / 测试
|
||||||
|
- 现象:原有知识图谱接口可展示关系边,但如果直接把图形观察和记忆管理混在一起,容易让用户误以为可以在图上修改事实。
|
||||||
|
- 根因:观察数据、节点详情和记忆写操作没有在产品语义上明确分层。
|
||||||
|
- 修复或规避:新增只读 `knowledge_graph_observation()` 数据合同和观察窗;复用 GET `/graph`,返回统计、节点、关系和 `readonly=true`,前端只渲染 SVG、统计卡片和详情查看,不增加删除、编辑、合并或写入按钮。
|
||||||
|
- 预防规则:所有可视化观察功能默认只读;任何修改能力必须单独设计 POST 合同、二次确认、审计和回滚,不能从观察图直接派生。
|
||||||
|
- 验证证据:面板回归 `9` 项通过;Node `--check`、Python `py_compile` 通过;临时 SQLite 验证返回 2 个节点、1 条关系和 `readonly=True`。
|
||||||
|
|
|
||||||
|
|
@ -674,14 +674,14 @@ class PluginPageApi:
|
||||||
|
|
||||||
async def graph(self):
|
async def graph(self):
|
||||||
try:
|
try:
|
||||||
rows = await self.plugin.service.store.list_knowledge_edges(
|
observation = await self.plugin.service.store.knowledge_graph_observation(
|
||||||
limit=self._query_int("limit", 50),
|
limit=self._query_int("limit", 180),
|
||||||
scope=clean_text(request.args.get("scope", ""), 40),
|
scope=clean_text(request.args.get("scope", ""), 40),
|
||||||
session_id=clean_text(request.args.get("session_id", ""), 200),
|
session_id=clean_text(request.args.get("session_id", ""), 200),
|
||||||
group_id=clean_text(request.args.get("group_id", ""), 120),
|
group_id=clean_text(request.args.get("group_id", ""), 120),
|
||||||
node=clean_text(request.args.get("node") or request.args.get("q"), 160),
|
node=clean_text(request.args.get("node") or request.args.get("q"), 160),
|
||||||
)
|
)
|
||||||
return self._ok({"items": rows})
|
return self._ok(observation)
|
||||||
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._ok({"items": []})
|
||||||
|
|
|
||||||
|
|
@ -1582,7 +1582,26 @@ pre{white-space:pre-wrap;overflow-wrap:anywhere}
|
||||||
transform:translateY(-1px);border-color:var(--accent);box-shadow:0 10px 24px rgba(var(--edge-rgb),.16);
|
transform:translateY(-1px);border-color:var(--accent);box-shadow:0 10px 24px rgba(var(--edge-rgb),.16);
|
||||||
}
|
}
|
||||||
.object-card.is-active{border-color:var(--accent);background:var(--accent-soft)}
|
.object-card.is-active{border-color:var(--accent);background:var(--accent-soft)}
|
||||||
.context-section{display:grid;gap:10px;margin-bottom:14px}
|
.context-section{display:grid;gap:10px;margin-bottom:14px}.memory-observation-panel{gap:14px}
|
||||||
|
.memory-observation-head{display:flex;align-items:flex-start;justify-content:space-between;gap:16px}
|
||||||
|
.memory-observation-head h4{margin:0}
|
||||||
|
.memory-observation-head p{margin:5px 0 0;color:var(--muted);font-size:12px;line-height:1.5}
|
||||||
|
.memory-observation-stats{margin-top:2px}
|
||||||
|
.memory-observation-legend{display:flex;flex-wrap:wrap;gap:10px 18px;align-items:center;color:var(--muted);font-size:12px}
|
||||||
|
.memory-observation-legend span{display:inline-flex;align-items:center;gap:6px}
|
||||||
|
.memory-graph-legend-dot{display:inline-block;width:9px;height:9px;border-radius:50%}
|
||||||
|
.memory-graph-legend-dot.is-memory{background:#c99412}
|
||||||
|
.memory-graph-legend-dot.is-user{background:#7664c6}
|
||||||
|
.memory-graph-legend-dot.is-session{background:#2d9a9a}
|
||||||
|
.memory-graph-stage{min-height:420px;border:1px solid rgba(var(--edge-rgb),.16);border-radius:10px;background-image:radial-gradient(rgba(var(--edge-rgb),.14) 1px,transparent 1px);background-size:24px 24px;overflow:hidden}
|
||||||
|
.memory-graph-svg{display:block;width:100%;min-height:420px;background:rgba(255,255,255,.46)}
|
||||||
|
.memory-graph-edge-line{stroke:rgba(var(--edge-rgb),.26);stroke-width:1.2}
|
||||||
|
.memory-graph-node{cursor:pointer;outline:none}
|
||||||
|
.memory-graph-node circle{stroke:rgba(255,255,255,.92);stroke-width:2;transition:transform .16s ease,filter .16s ease}
|
||||||
|
.memory-graph-node:hover circle,.memory-graph-node:focus circle{filter:drop-shadow(0 4px 5px rgba(var(--edge-rgb),.28));transform:scale(1.18)}
|
||||||
|
.memory-graph-node text{fill:var(--ink);font-size:13px;font-weight:650;paint-order:stroke;stroke:rgba(255,255,255,.92);stroke-width:4px;stroke-linejoin:round;pointer-events:none}
|
||||||
|
.memory-observation-foot{color:var(--muted);font-size:11px;border-top:1px solid var(--line-soft);padding-top:10px}
|
||||||
|
|
||||||
.context-section h4{margin:0;font-size:16px}
|
.context-section h4{margin:0;font-size:16px}
|
||||||
.film-panel{
|
.film-panel{
|
||||||
border:1px solid rgba(var(--edge-rgb),.18);
|
border:1px solid rgba(var(--edge-rgb),.18);
|
||||||
|
|
|
||||||
|
|
@ -33,6 +33,7 @@ const PERSONAL_MEMORY_VIEW = {
|
||||||
const SECONDARY_NAV = {
|
const SECONDARY_NAV = {
|
||||||
objects: [
|
objects: [
|
||||||
{ id: "overview", label: "图谱总览", sublabel: "关系、线程与时间线", badge: "总览" },
|
{ id: "overview", label: "图谱总览", sublabel: "关系、线程与时间线", badge: "总览" },
|
||||||
|
{ id: "observation", label: "观察窗", sublabel: "只读查看节点、关系与范围统计", badge: "只读" },
|
||||||
{ 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: "时间" },
|
||||||
|
|
@ -1913,7 +1914,10 @@ async function loadContextPanel() {
|
||||||
const section = activeSecondaryNav("objects");
|
const section = activeSecondaryNav("objects");
|
||||||
target.innerHTML = loadingState("正在读取知识图谱...");
|
target.innerHTML = loadingState("正在读取知识图谱...");
|
||||||
const params = contextParams({ limit: section === "overview" ? 8 : 60 });
|
const params = contextParams({ limit: section === "overview" ? 8 : 60 });
|
||||||
if (section === "relations") {
|
if (section === "observation") {
|
||||||
|
const data = await apiGet(`/graph?${params.toString()}`);
|
||||||
|
target.innerHTML = renderKnowledgeGraphObservation(data);
|
||||||
|
} else if (section === "relations") {
|
||||||
const data = await apiGet(`/graph?${params.toString()}`);
|
const data = await apiGet(`/graph?${params.toString()}`);
|
||||||
target.innerHTML = renderKnowledgeGraphEdges(data.items || []);
|
target.innerHTML = renderKnowledgeGraphEdges(data.items || []);
|
||||||
} else if (section === "threads") {
|
} else if (section === "threads") {
|
||||||
|
|
@ -1987,6 +1991,51 @@ function renderKnowledgeOverview({ graph = [], relations = [], threads = [], tim
|
||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function graphNodeColor(type = "") {
|
||||||
|
const key = String(type || "").toLowerCase();
|
||||||
|
if (key.includes("memory") || key.includes("fact")) return "#c99412";
|
||||||
|
if (key.includes("user") || key.includes("persona")) return "#7664c6";
|
||||||
|
if (key.includes("session") || key.includes("window")) return "#2d9a9a";
|
||||||
|
return "#6d76a8";
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderKnowledgeGraphObservation(data = {}) {
|
||||||
|
const nodes = Array.isArray(data.nodes) ? data.nodes : [];
|
||||||
|
const edges = Array.isArray(data.items) ? data.items : [];
|
||||||
|
const stats = data.stats || {};
|
||||||
|
const nodeMap = new Map(nodes.map((item) => [String(item.id || ""), item]));
|
||||||
|
edges.forEach((edge) => {
|
||||||
|
if (!nodeMap.has(String(edge.source_node_id || ""))) nodeMap.set(String(edge.source_node_id || ""), { id: edge.source_node_id, node_type: edge.source_type, label: edge.source_label, confidence: edge.confidence });
|
||||||
|
if (!nodeMap.has(String(edge.target_node_id || ""))) nodeMap.set(String(edge.target_node_id || ""), { id: edge.target_node_id, node_type: edge.target_type, label: edge.target_label, confidence: edge.confidence });
|
||||||
|
});
|
||||||
|
const visibleNodes = Array.from(nodeMap.values()).filter((item) => item && item.id).slice(0, 120);
|
||||||
|
const width = 1000;
|
||||||
|
const height = 520;
|
||||||
|
const centerX = width / 2;
|
||||||
|
const centerY = height / 2;
|
||||||
|
const radius = Math.max(110, Math.min(210, 44 + visibleNodes.length * 3.1));
|
||||||
|
const positions = new Map();
|
||||||
|
visibleNodes.forEach((item, index) => {
|
||||||
|
const angle = visibleNodes.length ? (Math.PI * 2 * index) / visibleNodes.length - Math.PI / 2 : 0;
|
||||||
|
const ring = 1 + (index % 3) * 0.16;
|
||||||
|
positions.set(String(item.id), { x: centerX + Math.cos(angle) * radius * ring, y: centerY + Math.sin(angle) * radius * ring });
|
||||||
|
});
|
||||||
|
const lineSvg = edges.map((edge) => {
|
||||||
|
const source = positions.get(String(edge.source_node_id || ""));
|
||||||
|
const target = positions.get(String(edge.target_node_id || ""));
|
||||||
|
if (!source || !target) return "";
|
||||||
|
return `<line class="memory-graph-edge-line" x1="${source.x.toFixed(1)}" y1="${source.y.toFixed(1)}" x2="${target.x.toFixed(1)}" y2="${target.y.toFixed(1)}" />`;
|
||||||
|
}).join("");
|
||||||
|
const nodeSvg = visibleNodes.map((item) => {
|
||||||
|
const point = positions.get(String(item.id));
|
||||||
|
const label = compact(item.label || item.node_key || item.id, 34);
|
||||||
|
const color = graphNodeColor(item.node_type);
|
||||||
|
const radiusValue = Math.max(6, Math.min(13, 6 + Number(item.confidence || 0) * 7));
|
||||||
|
return `<g class="memory-graph-node" tabindex="0" role="button" data-raw="${rawAttr(item)}" data-detail-title="记忆观察节点" transform="translate(${point.x.toFixed(1)} ${point.y.toFixed(1)})"><circle r="${radiusValue.toFixed(1)}" fill="${color}" /><text x="${(radiusValue + 8).toFixed(1)}" y="4">${escapeHtml(label)}</text></g>`;
|
||||||
|
}).join("");
|
||||||
|
const filterText = [data.filters?.scope, data.filters?.session_id, data.filters?.group_id, data.filters?.node].filter(Boolean).join(" / ") || "当前可见范围";
|
||||||
|
return `<section class="context-section film-panel memory-observation-panel"><div class="memory-observation-head"><div><h4>记忆观察窗</h4><p>只读观察知识节点与关系,不会修改、合并或删除任何记忆。</p></div><span class="badge teal">只读</span></div><div class="config-grid memory-observation-stats">${configCard("总记忆", `${Number(stats.memories || 0)}`, filterText, "blue", "记忆")}${configCard("节点", `${Number(stats.nodes || visibleNodes.length)}`, "知识主题与实体", "violet", "节点")}${configCard("关系", `${Number(stats.edges || edges.length)}`, "已建立的关联边", "teal", "关系")}${configCard("活跃会话", `${Number(stats.active_sessions || 0)}`, "当前范围内的会话", "gold", "会话")}</div><div class="memory-observation-legend"><span><i class="memory-graph-legend-dot is-memory"></i>记忆 / 事实</span><span><i class="memory-graph-legend-dot is-user"></i>用户 / 拟人</span><span><i class="memory-graph-legend-dot is-session"></i>会话 / 窗口</span><span>点击节点可查看只读详情</span></div><div class="memory-graph-stage" aria-label="只读记忆知识图谱">${visibleNodes.length ? `<svg class="memory-graph-svg" viewBox="0 0 ${width} ${height}" role="img" aria-label="记忆节点关系图">${lineSvg}${nodeSvg}</svg>` : `<div class="empty-state">当前范围还没有可观察的知识节点。</div>`}</div><div class="memory-observation-foot">观察结果仅用于理解记忆结构,不代表事实正确性,也不会参与当前对话。</div></section>`;
|
||||||
|
}
|
||||||
function renderKnowledgeGraphEdges(items, title = "图谱边") {
|
function renderKnowledgeGraphEdges(items, title = "图谱边") {
|
||||||
return `
|
return `
|
||||||
<section class="context-section film-panel">
|
<section class="context-section film-panel">
|
||||||
|
|
|
||||||
|
|
@ -17,7 +17,7 @@
|
||||||
document.documentElement.dataset.overviewLayout = layout;
|
document.documentElement.dataset.overviewLayout = layout;
|
||||||
})();
|
})();
|
||||||
</script>
|
</script>
|
||||||
<link rel="stylesheet" href="./app.css?v=20260719-overview-switch" />
|
<link rel="stylesheet" href="./app.css?v=20260724-memory-observation" />
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<main id="app" class="film-app">
|
<main id="app" class="film-app">
|
||||||
|
|
@ -451,6 +451,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=20260721-labeled-chat-import"></script>
|
<script src="./app.js?v=20260724-memory-observation"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|
|
||||||
147
tests/test_calendar_bridge.py
普通文件
147
tests/test_calendar_bridge.py
普通文件
|
|
@ -0,0 +1,147 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import tempfile
|
||||||
|
import time
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from core.bridge import MemoryCompanionBridge, serialize_memory
|
||||||
|
from core.injection import InjectionComposer
|
||||||
|
from core.models import EntityRef, MemoryRecord, SearchResult, SessionContext
|
||||||
|
from core.service import MemoryCompanionService
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
|
||||||
|
|
||||||
|
class _CalendarRecorder:
|
||||||
|
async def record_calendar_event(self, **kwargs):
|
||||||
|
self.payload = kwargs
|
||||||
|
return "calendar-memory-1"
|
||||||
|
|
||||||
|
|
||||||
|
class CalendarBridgeTests(unittest.IsolatedAsyncioTestCase):
|
||||||
|
def make_service(self):
|
||||||
|
temp_dir = tempfile.TemporaryDirectory()
|
||||||
|
self.addCleanup(temp_dir.cleanup)
|
||||||
|
service = MemoryCompanionService(
|
||||||
|
context=None,
|
||||||
|
config={"private_companion_bridge": {"accept_external_records": True}},
|
||||||
|
plugin_root=ROOT,
|
||||||
|
data_dir=Path(temp_dir.name),
|
||||||
|
)
|
||||||
|
self.addCleanup(service.close)
|
||||||
|
return service
|
||||||
|
|
||||||
|
async def test_bridge_forwards_calendar_history_contract(self):
|
||||||
|
recorder = _CalendarRecorder()
|
||||||
|
bridge = MemoryCompanionBridge(recorder)
|
||||||
|
result = await bridge.record_calendar_event(
|
||||||
|
event_id="event-1", title="阅读一小时",
|
||||||
|
start_at="2026-07-24T20:00:00+08:00",
|
||||||
|
end_at="2026-07-24T21:00:00+08:00", status="planned",
|
||||||
|
)
|
||||||
|
self.assertEqual("calendar-memory-1", result)
|
||||||
|
self.assertEqual("event-1", recorder.payload["event_id"])
|
||||||
|
self.assertEqual("planned", recorder.payload["status"])
|
||||||
|
self.assertEqual("history_only", bridge.probe_calendar_contract()["write_mode"])
|
||||||
|
|
||||||
|
async def test_missing_calendar_bridge_is_safe_to_probe_and_skip(self):
|
||||||
|
bridge = MemoryCompanionBridge(object())
|
||||||
|
self.assertFalse(bridge.probe_calendar_contract()["available"])
|
||||||
|
with self.assertRaisesRegex(RuntimeError, "日历历史 Bridge"):
|
||||||
|
await bridge.record_calendar_event(
|
||||||
|
event_id="event-1", title="测试",
|
||||||
|
start_at="2026-07-24T20:00:00+08:00",
|
||||||
|
end_at="2026-07-24T21:00:00+08:00",
|
||||||
|
)
|
||||||
|
|
||||||
|
async def test_calendar_event_time_fields_layers_and_deduplication(self):
|
||||||
|
service = self.make_service()
|
||||||
|
bridge = MemoryCompanionBridge(service)
|
||||||
|
memory_id = await bridge.record_calendar_event(
|
||||||
|
event_id="event-20260724-001", calendar="maintenance_agenda",
|
||||||
|
title="备份窗口", summary="执行一次备份",
|
||||||
|
start_at="2026-07-24T23:30:00+08:00",
|
||||||
|
end_at="2026-07-25T00:30:00+08:00", timezone="Asia/Shanghai",
|
||||||
|
status="planned", source="bot_generated", related_task_id="task-1",
|
||||||
|
occurred_at="2026-07-24T23:30:00+08:00",
|
||||||
|
)
|
||||||
|
first = await service.store.get_memory(memory_id)
|
||||||
|
self.assertIsNotNone(first)
|
||||||
|
self.assertTrue(first.created_at)
|
||||||
|
self.assertTrue(first.updated_at)
|
||||||
|
self.assertEqual("2026-07-24T23:30:00+08:00", first.occurred_at)
|
||||||
|
self.assertEqual("calendar_history", first.metadata["memory_layer"])
|
||||||
|
self.assertEqual("calendar_event", first.memory_type)
|
||||||
|
self.assertEqual("calendar_event", first.metadata["time_source"])
|
||||||
|
self.assertNotIn("age_seconds", first.metadata)
|
||||||
|
|
||||||
|
time.sleep(1.1)
|
||||||
|
updated_id = await bridge.record_calendar_event(
|
||||||
|
event_id="event-20260724-001", title="备份窗口",
|
||||||
|
start_at="2026-07-24T23:30:00+08:00",
|
||||||
|
end_at="2026-07-25T00:30:00+08:00", status="completed",
|
||||||
|
source="controller", change_reason="备份已完成",
|
||||||
|
occurred_at="2026-07-24T23:30:00+08:00",
|
||||||
|
)
|
||||||
|
second = await service.store.get_memory(updated_id)
|
||||||
|
self.assertEqual(memory_id, updated_id)
|
||||||
|
self.assertEqual(first.created_at, second.created_at)
|
||||||
|
self.assertNotEqual(first.updated_at, second.updated_at)
|
||||||
|
self.assertEqual("completed", second.metadata["status"])
|
||||||
|
self.assertEqual(1, service.store._conn.execute(
|
||||||
|
"SELECT COUNT(*) FROM memories WHERE metadata LIKE ?", ("%event-20260724-001%",)
|
||||||
|
).fetchone()[0])
|
||||||
|
|
||||||
|
payload = serialize_memory(second)
|
||||||
|
self.assertEqual("calendar_event", payload["memory_type"])
|
||||||
|
self.assertEqual("event-20260724-001", payload["calendar_event_id"])
|
||||||
|
self.assertEqual("calendar_event", payload["time_source"])
|
||||||
|
self.assertEqual("calendar_history", payload["memory_layer"])
|
||||||
|
self.assertTrue(payload["historical_only"])
|
||||||
|
self.assertEqual("completed", payload["calendar_status"])
|
||||||
|
self.assertTrue(payload["temporal"]["age_seconds"] >= 0)
|
||||||
|
self.assertNotIn("age_seconds", second.metadata)
|
||||||
|
|
||||||
|
async def test_invalid_calendar_event_does_not_enter_ops_or_chat_layers(self):
|
||||||
|
service = self.make_service()
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
await service.record_calendar_event(
|
||||||
|
event_id="event-invalid", title="无效事件",
|
||||||
|
start_at="2026-07-24T20:00:00+08:00",
|
||||||
|
end_at="2026-07-24T19:00:00+08:00",
|
||||||
|
)
|
||||||
|
memory_id = await service.record_calendar_event(
|
||||||
|
event_id="event-valid", title="历史事件",
|
||||||
|
start_at="2026-07-24T20:00:00+08:00",
|
||||||
|
end_at="2026-07-24T21:00:00+08:00",
|
||||||
|
)
|
||||||
|
record = await service.store.get_memory(memory_id)
|
||||||
|
self.assertNotIn(record.memory_type, {"ops_event", "ops_fact", "conversation_event"})
|
||||||
|
self.assertEqual("calendar_history", record.reality_level)
|
||||||
|
self.assertEqual("astrbot_plugin_private_companion", record.source_plugin)
|
||||||
|
|
||||||
|
def test_injection_marks_calendar_memory_as_historical_background(self):
|
||||||
|
record = MemoryRecord(
|
||||||
|
id="calendar-1", memory_type="calendar_event",
|
||||||
|
content="日历历史?阅读一小时",
|
||||||
|
occurred_at="2026-07-23T20:00:00+08:00",
|
||||||
|
created_at="2026-07-23T20:00:03+08:00",
|
||||||
|
metadata={"memory_layer": "calendar_history", "status": "completed",
|
||||||
|
"time_source": "calendar_event", "timezone": "Asia/Shanghai"},
|
||||||
|
subject=EntityRef.bot_self(),
|
||||||
|
object=EntityRef(kind="session", id="calendar_history"),
|
||||||
|
)
|
||||||
|
text = InjectionComposer().compose(
|
||||||
|
SessionContext(session_id="calendar_history", scope="private", message_text="之前安排了什么?"),
|
||||||
|
[SearchResult(memory=record, score=0.9, reason="calendar")],
|
||||||
|
max_chars=3600, now="2026-07-24T08:00:00+08:00",
|
||||||
|
)
|
||||||
|
self.assertIn("记忆层:日历历史(仅作历史背景)", text)
|
||||||
|
self.assertIn("日历状态:completed", text)
|
||||||
|
self.assertIn("时间来源:calendar_event", text)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
|
|
@ -112,7 +112,22 @@ 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=20260719-overview-switch", page)
|
self.assertIn("app.css?v=20260724-memory-observation", page)
|
||||||
|
|
||||||
|
def test_memory_observation_window_is_read_only(self) -> None:
|
||||||
|
page = (ROOT / "pages" / "记忆面板" / "index.html").read_text(encoding="utf-8")
|
||||||
|
script = (ROOT / "pages" / "记忆面板" / "app.js").read_text(encoding="utf-8")
|
||||||
|
api = (ROOT / "page_api.py").read_text(encoding="utf-8")
|
||||||
|
store = (ROOT / "core" / "store.py").read_text(encoding="utf-8")
|
||||||
|
|
||||||
|
self.assertIn('id: "observation"', script)
|
||||||
|
self.assertIn("function renderKnowledgeGraphObservation", script)
|
||||||
|
self.assertIn("memory-observation-panel", script)
|
||||||
|
self.assertIn('"readonly": True', store)
|
||||||
|
graph_block = api[api.index('async def graph(self):'):api.index('async def threads(self):')]
|
||||||
|
self.assertIn('knowledge_graph_observation', graph_block)
|
||||||
|
self.assertNotIn('register_web_api', graph_block)
|
||||||
|
self.assertIn('data-view="objects"', page)
|
||||||
|
|
||||||
def test_overview_layout_switch_is_visible_persistent_and_accessible(self) -> None:
|
def test_overview_layout_switch_is_visible_persistent_and_accessible(self) -> None:
|
||||||
page = (ROOT / "pages" / "记忆面板" / "index.html").read_text(encoding="utf-8")
|
page = (ROOT / "pages" / "记忆面板" / "index.html").read_text(encoding="utf-8")
|
||||||
|
|
@ -139,7 +154,7 @@ 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=20260721-labeled-chat-import", page)
|
self.assertIn("app.js?v=20260724-memory-observation", 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")
|
||||||
|
|
|
||||||
正在加载…
添加表格
在新工单中引用