feat: link bot personal memory bridge
这个提交存在于:
父节点
fc1f69898a
当前提交
0e0db82519
共有 4 个文件被更改,包括 490 次插入 和 6 次删除
257
docs/M6日程拆分与陪伴插件调整评估.md
普通文件
257
docs/M6日程拆分与陪伴插件调整评估.md
普通文件
|
|
@ -0,0 +1,257 @@
|
|||
# M6 日程拆分与陪伴插件调整评估
|
||||
|
||||
- 评估日期:2026-07-25
|
||||
- 适用分支:`ops-main`
|
||||
- 评估对象:运维版陪伴插件、运维版记忆插件
|
||||
- 目标:把 Bot 日程从“陪伴插件自己保存的一套数据”调整为“陪伴插件负责运行,记忆插件负责长期归档和检索”,不影响普通陪伴分支。
|
||||
|
||||
## 一、先给结论
|
||||
|
||||
**可行,而且不建议把日程运行代码整体搬走。**
|
||||
|
||||
最稳妥的拆分方式是:
|
||||
|
||||
```text
|
||||
陪伴插件:现实时间、当前日程、下一项活动、主动消息时机、活动捕获、计划/实际对账、睡前触发
|
||||
记忆插件:Bot 日程历史、窗口快照、实际活动摘要、对账结果、日记、创作和主观记忆的长期归档与检索
|
||||
陪伴插件本地 bot_self_store:运行热数据、Bridge 不可用时的降级副本、短期页面读取
|
||||
用户记忆 user_memory:只保存用户事实,禁止写入 Bot 日程和 Bot 自我记录
|
||||
```
|
||||
|
||||
M6 不是“删除陪伴插件的日程”,而是“拆开日程的运行责任和长期记忆责任”。
|
||||
|
||||
## 二、已核对的源码事实
|
||||
|
||||
### 1. 记忆插件已经具备的能力
|
||||
|
||||
源码位置:
|
||||
|
||||
- `astrbot_plugin_memory_companion-main/core/bot_personal.py`
|
||||
- `astrbot_plugin_memory_companion-main/core/service.py`
|
||||
- `astrbot_plugin_memory_companion-main/core/bridge.py`
|
||||
- `astrbot_plugin_memory_companion-main/page_api.py`
|
||||
|
||||
已经存在:
|
||||
|
||||
- 专属域:`memory_domain=bot_self_schedule`
|
||||
- 固定会话:`session_id=bot_personal`
|
||||
- 固定可见性:`visibility=bot_self`
|
||||
- 专属类型:计划、实际活动、窗口快照、日记、创作、媒体、主观记忆、共同活动等
|
||||
- 专用 Bridge:`record_bot_personal_memory`
|
||||
- 类型化 Bridge 方法:`record_bot_schedule_plan`、`record_bot_observed_activity`、`record_bot_window_snapshot` 等
|
||||
- 专用检索:`search_bot_personal_memory`
|
||||
- 能力探测:`probe_bot_personal_memory_capabilities`
|
||||
- 页面接口:`/companion/personal-memory`
|
||||
- 记忆域过滤:普通检索不会直接返回 `bot_self_schedule`
|
||||
|
||||
已有测试覆盖专属域、幂等键、普通检索隔离和 Bridge 缺失降级:
|
||||
|
||||
- `astrbot_plugin_memory_companion-main/tests/test_bot_personal_memory.py`
|
||||
- `astrbot_plugin_memory_companion-main/tests/test_calendar_bridge.py`
|
||||
|
||||
### 2. 陪伴插件已经具备的能力
|
||||
|
||||
源码位置:
|
||||
|
||||
- `astrbot_plugin_private_companion-main/calendar_system.py`
|
||||
- `astrbot_plugin_private_companion-main/agenda_contracts.py`
|
||||
- `astrbot_plugin_private_companion-main/agenda_runtime.py`
|
||||
- `astrbot_plugin_private_companion-main/bot_self_store.py`
|
||||
- `astrbot_plugin_private_companion-main/memory_companion_adapter.py`
|
||||
- `astrbot_plugin_private_companion-main/planning.py`
|
||||
|
||||
已经存在:
|
||||
|
||||
- 现实日期时间和 `Asia/Shanghai` 时区处理
|
||||
- 四段式时间窗:深夜、早晨、下午、晚上
|
||||
- 计划项、日历事件、实际活动和窗口快照
|
||||
- 活动捕获:`ActivityCapture`
|
||||
- 计划/实际对账:`unified_agenda` 及相关合同
|
||||
- 睡前日记触发:`_agenda_maintenance_tick`
|
||||
- 本地 Bot 专属存储:`bot_self_store`
|
||||
- 本地幂等写入:`record_bot_self_entry`
|
||||
- 记忆插件不可用时的本地降级
|
||||
- 记忆插件可用时的专用远端写入
|
||||
|
||||
陪伴侧的远端写入映射已经存在:
|
||||
|
||||
| 陪伴事件 | 记忆类型 |
|
||||
|---|---|
|
||||
| 每日日程 | `bot_schedule_plan` |
|
||||
| 窗口快照 | `bot_window_snapshot` |
|
||||
| 日程细化片段 | `bot_detail_fragment` |
|
||||
| 日历事件 | `bot_calendar_event` |
|
||||
| 创作进度 | `bot_creative_work` |
|
||||
| 梦境/主观片段 | `bot_subjective_memory` |
|
||||
| 主动消息 | `bot_proactive_message` |
|
||||
| 图片/相册 | `bot_media_memory` |
|
||||
|
||||
## 三、当前实现与 M6 合同的差距
|
||||
|
||||
| 项目 | 当前状态 | 判断 | 调整要求 |
|
||||
|---|---|---|---|
|
||||
| 日程运行归属 | 陪伴插件负责 | 正确 | 保留,不搬到记忆插件 |
|
||||
| 日程长期归档 | 陪伴本地写入后再 Bridge 归档 | 方向正确 | 统一每种事件的类型、字段和幂等键 |
|
||||
| Bot 自有本地存储 | `bot_self_store` 已存在 | 正确 | 明确为热数据/降级副本,不作为用户记忆 |
|
||||
| Bot 个人记忆写入 | 已有通用入口和类型化入口 | 基础完成 | 增加 M6 标准化字段校验 |
|
||||
| 四段式窗口 | 陪伴侧已有 | 基础完成 | 远端记录必须稳定保存 `date/window` |
|
||||
| 计划与实际分层 | 本地合同已有 `planned/real` 和证据等级 | 基础完成 | 远端写入禁止把计划写成 `observed/completed` |
|
||||
| 计划/实际对账 | 本地有快照和历史数组 | 部分完成 | 增加正式 `bot_schedule_reconciliation` 归档,而不是只塞进快照 |
|
||||
| 睡前日记 | 本地触发和保存存在 | 部分完成 | 确认日记通过 `bot_daily_diary` 归档,并保持幂等 |
|
||||
| Bot 专用检索 Profile | 目前主要是通用 `search_bot_personal_memory` | 缺失 | 增加 current/history/creative/subjective/locked-frame 语义层 |
|
||||
| Locked Frame API | 目前有组合接口 `/companion/personal-memory` | 部分完成 | 后续补齐只读摘要、日程、时间线、创作、相册、日记等稳定视图 |
|
||||
| `source_refs` | 多数调用方已有,但结构不统一 | 部分完成 | 强制为字符串数组并限制长度 |
|
||||
| `occurred_at` | 由事件字段或当前时间补齐 | 基础完成 | 计划使用生成时间,实际活动使用发生时间,日记使用结算时间 |
|
||||
| `certainty` | 可能存在于陪伴本地 payload,但记忆服务未统一提升为合同字段 | 缺失 | 计划、真实活动、推测候选必须有明确 certainty |
|
||||
| `version` | 本地和记忆记录各自有版本 | 部分完成 | 远端更新时保留创建时间和版本链 |
|
||||
| 普通用户检索隔离 | 记忆侧已有域过滤 | 基础完成 | 增加页面、Bridge 和上下文注入三条路径回归测试 |
|
||||
| 远端失败降级 | 陪伴侧保留本地记录 | 正确 | 增加失败计数和待补写标记,避免静默丢失长期归档 |
|
||||
|
||||
## 四、最重要的实现问题
|
||||
|
||||
### 1. “拆出来”不能删除本地日程
|
||||
|
||||
`busy_reply_gate.py`、`state_views.py`、`scene_context.py`、主动消息逻辑和日程生成器都直接读取陪伴插件的当前日程。若直接改成每轮从记忆插件查询,会产生:
|
||||
|
||||
- 每轮对话增加 Bridge/SQLite 查询;
|
||||
- 记忆插件短暂不可用时当前状态消失;
|
||||
- 主动消息和休息闸门变成依赖长期归档;
|
||||
- 计划、实际和当前活动的实时状态延迟。
|
||||
|
||||
因此当前日程必须继续由陪伴插件掌握,记忆插件只接收归档事件和提供历史检索。
|
||||
|
||||
### 2. 远端归档已经接入,但字段还不够严格
|
||||
|
||||
`memory_companion_adapter.py` 的 `_memory_companion_record_bot_self_local()` 会:
|
||||
|
||||
1. 先写 `bot_self_store`;
|
||||
2. 再根据 `kind` 映射成 `bot_*` 类型;
|
||||
3. 通过 `record_bot_personal_memory()` 写入记忆插件;
|
||||
4. 失败时保留本地副本。
|
||||
|
||||
这个链路是正确的,但目前不同事件的 payload 结构不一致。例如计划、窗口快照、创作进度使用的字段集合不同,部分嵌套对象会在通用清洗时被压扁为字符串或丢弃。M6 应增加统一的事件标准化函数,而不是让记忆插件猜字段。
|
||||
|
||||
### 3. 记忆插件目前有专用检索,但没有完整 Profile 层
|
||||
|
||||
当前 `search_bot_personal_memory()` 能按域、会话、可见性和类型过滤,但还没有把以下语义固化:
|
||||
|
||||
- `bot_schedule_current`:当前窗口、最近实际活动、未完成事项;
|
||||
- `bot_schedule_history`:窗口快照、对账、日记和历史活动;
|
||||
- `bot_creative`:创作、阅读、媒体和作品关联;
|
||||
- `bot_subjective`:主观记忆、梦境和连续性线索;
|
||||
- `locked_frame_personal`:只读聚合,不暴露底层写入口。
|
||||
|
||||
这部分应在记忆插件侧完成,陪伴插件只调用明确的方法,不自行拼底层查询。
|
||||
|
||||
### 4. 现有兼容数据不能立即删除
|
||||
|
||||
`daily_plan`、`calendar_events`、`observed_activities`、`window_snapshots`、`bot_diaries` 等仍被陪伴运行时直接读取。它们属于当前运行态和迁移兼容数据,不能在 M6 第一轮删除。
|
||||
|
||||
处理顺序应是:
|
||||
|
||||
```text
|
||||
继续双写 -> 观察期核对数量 -> 页面改读稳定视图 -> 再评估历史字段迁移 -> 最后才考虑缩减旧数组
|
||||
```
|
||||
|
||||
## 五、建议的陪伴插件调整队列
|
||||
|
||||
### M6.1.3-A:陪伴侧统一归档适配器
|
||||
|
||||
新增一个面向 M6 的归档适配层,统一处理:`plan`、`observed_activity`、`reconciliation`、`window_snapshot`、`daily_diary`、`calendar_event`、`creative_work`、`media_memory`、`subjective_memory`。
|
||||
|
||||
每种记录至少包含:
|
||||
|
||||
```text
|
||||
record_id
|
||||
memory_type
|
||||
date
|
||||
window
|
||||
occurred_at
|
||||
source_refs
|
||||
certainty
|
||||
evidence_level
|
||||
status
|
||||
version
|
||||
idempotency_key
|
||||
```
|
||||
|
||||
计划必须使用 `source_kind=planned`、`evidence_level=L0`;真实活动必须使用 `source_kind=real`;推测内容只能使用 `source_kind=simulated` 或 `projection`,不能伪装成已发生。
|
||||
|
||||
### M6.1.3-B:把对账从“快照里的字段”提升为正式记录
|
||||
|
||||
窗口快照仍然保留,但每个窗口结束时额外写一条 `bot_schedule_reconciliation`,至少说明计划完成、延期、跳过、部分完成、无计划实际活动,以及关联的活动 ID、计划 ID、生成时间和版本。
|
||||
|
||||
### M6.1.3-C:远端写入失败的补偿机制
|
||||
|
||||
当前失败时只记录日志并保留本地数据。建议在 `bot_self_store` 增加:`archive_sync_status`、`archive_retry_count`、`archive_last_error`(脱敏)、`archive_next_retry_at`。
|
||||
|
||||
这样不会把“本地写成功、长期归档失败”误判为完全成功,也方便 VM 观察期补写。
|
||||
|
||||
### M6.1.3-D:陪伴侧调用专用方法,不调用通用入口
|
||||
|
||||
优先调用 `record_bot_schedule_plan`、`record_bot_observed_activity`、`record_bot_schedule_reconciliation`、`record_bot_window_snapshot`、`record_bot_daily_diary`、`record_bot_creative_work`、`record_bot_media_memory`、`record_bot_subjective_memory`。保留 `record_bot_personal_memory` 作为兼容底层接口,但业务代码不再直接依赖它。
|
||||
|
||||
### M6.1.3-E:上下文读取分层
|
||||
|
||||
- 当前时段、当前活动、下一项日程:读本地运行态;
|
||||
- 最近历史、跨日时间线、睡前回顾:调用记忆插件 Profile;
|
||||
- 记忆插件不可用:使用本地 `bot_self_store` 最近记录;
|
||||
- 普通用户聊天:只调用用户记忆接口,不读取 Bot 专属域。
|
||||
|
||||
### M6.1.3-F:前端保持“两块内容”
|
||||
|
||||
Q8 页面后续不应把两侧数据显示成一张表:当前运行态来自陪伴插件,长期归档/Locked Frame 来自记忆插件只读接口。当前页面可以继续使用现有 `/bot-self/*` 和 `/companion/personal-memory`,待 Profile API 稳定后再切换历史区域,避免一次改动影响运行态。
|
||||
|
||||
## 六、记忆插件侧需要配合的调整
|
||||
|
||||
1. 增加统一 Bot 个人记录标准化,不让不同调用方各自定义字段。
|
||||
2. 固定 `plan/observed/reconciled/snapshot/diary` 的生命周期和真实性字段。
|
||||
3. 增加 `current`、`history`、`creative`、`subjective`、`locked_frame` 五类 Profile。
|
||||
4. 将 `/companion/personal-memory` 明确为只读聚合,并返回 `readonly=true`、`memory_domain=bot_self_schedule`。
|
||||
5. 增加普通私聊、群聊、用户事实查询、上下文注入四类污染回归测试。
|
||||
6. 对旧 `schedule_fragment`、`bot_self_legacy` 只做预览和迁移标记,不直接删除。
|
||||
|
||||
## 七、暂时不要做的事
|
||||
|
||||
- 不删除陪伴插件的 `daily_plan`、`calendar_events`、`observed_activities` 等运行态字段。
|
||||
- 不让每轮消息都去记忆插件查询当前日程。
|
||||
- 不把完整聊天、Prompt、原始媒体写入长期 Bot 记忆。
|
||||
- 不把用户共同活动自动复制成 Bot 已完成事实。
|
||||
- 不恢复已经删除的娱乐模块。
|
||||
- 不因为 M6 开始就直接覆盖当前 VM 的 Q8 部署。
|
||||
- 不在观察期内删除旧数据或关闭本地降级。
|
||||
|
||||
## 八、最终可执行结论
|
||||
|
||||
当前可以进入 **M6.1.3 陪伴侧适配**,但第一步应是“统一归档合同和补偿状态”,不是删除本地日程。
|
||||
|
||||
推荐顺序:
|
||||
|
||||
```text
|
||||
1. 冻结当前运行态字段
|
||||
2. 统一陪伴侧 Bot 归档 payload
|
||||
3. 正式写入 observed/reconciliation/diary 类型
|
||||
4. 加入远端归档失败补偿
|
||||
5. 增加 Profile 调用适配
|
||||
6. 更新 Q8 历史区域
|
||||
7. 本地、VM、回滚和跨域污染验收
|
||||
8. 观察一段时间后再决定是否减少旧历史数组
|
||||
```
|
||||
|
||||
**评估结果:可实施,风险可控;不建议现在把 Bot 日程全部搬到记忆插件,也不建议现在删除陪伴插件本地日程。**
|
||||
|
||||
## 九、依据文件
|
||||
|
||||
- `跨插件改造任务/给记忆插件窗口/Q6.1-Locked Frame Bot个人记忆与四段式日程联动.md`
|
||||
- `astrbot_plugin_memory_companion-main/core/bot_personal.py`
|
||||
- `astrbot_plugin_memory_companion-main/core/service.py`
|
||||
- `astrbot_plugin_memory_companion-main/core/bridge.py`
|
||||
- `astrbot_plugin_memory_companion-main/page_api.py`
|
||||
- `astrbot_plugin_memory_companion-main/tests/test_bot_personal_memory.py`
|
||||
- `astrbot_plugin_private_companion-main/calendar_system.py`
|
||||
- `astrbot_plugin_private_companion-main/agenda_contracts.py`
|
||||
- `astrbot_plugin_private_companion-main/agenda_runtime.py`
|
||||
- `astrbot_plugin_private_companion-main/bot_self_store.py`
|
||||
- `astrbot_plugin_private_companion-main/memory_companion_adapter.py`
|
||||
- `astrbot_plugin_private_companion-main/planning.py`
|
||||
- `astrbot_plugin_private_companion-main/docs/Q8前端改造与验收记录.md`
|
||||
|
|
@ -235,3 +235,33 @@ docs\运维陪伴错题本.md
|
|||
- 修复或规避:验收记录同时保留本地日期和 VM 日志时间,不用相对日期描述部署结果。
|
||||
- 预防规则:VM 部署记录必须写入绝对日期、服务状态、提交号和备份路径。
|
||||
- 验证证据:Q8 VM 部署验收记录;服务 active、NRestarts=0,插件和前端资源检查通过。
|
||||
|
||||
## 2026-07-25 — M6.1 陪伴侧 Bot 个人记忆联动降级
|
||||
|
||||
- 阶段:M6.1.3-M6.1.7 四段式写入、Bot 专用检索、Bridge 缺失与异常降级测试
|
||||
- 类型:API契约 / 功能行为 / 测试
|
||||
- 现象:陪伴插件原先只写本地 bot_self_store,若直接改成记忆插件远端写入,会在插件缺失或初始化失败时阻断日程运行。
|
||||
- 根因:Bot 自有记录入口没有把本地事实存储与跨插件长期归档拆成两个可选步骤。
|
||||
- 修复或规避:保留本地写入作为主路径;通过 record_bot_personal_memory 按 kind 映射到 Bot 专用 memory_type;检索优先调用 search_bot_personal_memory,无结果或 Bridge 不可用时回退旧上下文;远端异常只记录日志。
|
||||
- 预防规则:跨插件联动必须是可选增强,陪伴主流程不能依赖记忆插件;日计划、窗口快照、创作、相册和日记必须使用稳定幂等键。
|
||||
- 验证证据:tests.test_m6_bot_personal_bridge 4 项通过;陪伴插件全仓 compileall -q . 通过;git diff --check 通过。
|
||||
|
||||
## 2026-07-25 — M6 日程拆分不能删除运行态
|
||||
|
||||
- 阶段:M6 日程拆分与 Bot 个人记忆联动评估
|
||||
- 类型:功能行为 / API契约 / 性能
|
||||
- 现象:如果把 Bot 日程全部搬到记忆插件,当前活动、下一项日程、休息闸门和主动消息都会依赖长期记忆查询。
|
||||
- 根因:日程运行态和长期归档是两种不同职责;记忆插件适合历史检索,不适合替代陪伴插件的实时状态机。
|
||||
- 修复或规避:确定陪伴插件继续维护当前运行态和本地 `bot_self_store`,记忆插件只接收 Bot 专属长期归档并提供只读 Profile。
|
||||
- 预防规则:M6 先做双写、字段统一和失败补偿;观察期结束前不删除 `daily_plan`、`calendar_events`、`observed_activities`、`window_snapshots` 等旧运行字段。
|
||||
- 验证证据:已核对 `agenda_runtime.py`、`busy_reply_gate.py`、`state_views.py`、`planning.py` 和 `memory_companion_adapter.py`;评估文档已写入 `docs/M6日程拆分与陪伴插件调整评估.md`。
|
||||
|
||||
## 2026-07-25 — M6 远端归档字段不能依赖通用清洗猜测
|
||||
|
||||
- 阶段:M6 日程拆分与 Bridge 字段复盘
|
||||
- 类型:API契约 / 功能行为
|
||||
- 现象:陪伴侧多个 Bot 事件通过同一个通用清洗函数写入记忆插件,嵌套计划、创作和对账内容可能被压扁或丢失,导致长期归档结构不稳定。
|
||||
- 根因:业务事件没有统一的 M6 payload 合同;通用清洗只能保证安全,不能保证事件语义完整。
|
||||
- 修复或规避:本轮不直接改代码;将统一归档适配器、`source_refs`、`occurred_at`、`certainty`、`evidence_level`、`version` 和幂等键列为 M6.1.3 首要改造项。
|
||||
- 预防规则:业务代码优先调用类型化 Bot Bridge;底层通用入口只做兼容,不让记忆插件反推调用方语义。
|
||||
- 验证证据:已核对 `memory_companion_adapter.py` 的 `_memory_companion_record_bot_self_local()` 及记忆侧 `record_bot_personal_memory()` 实现;差距已记录在 M6 评估文档。
|
||||
|
|
|
|||
|
|
@ -360,8 +360,7 @@ class MemoryCompanionAdapterMixin:
|
|||
) -> str:
|
||||
bridge = self._memory_companion_bridge()
|
||||
composer = getattr(bridge, "compose_context", None) if bridge is not None else None
|
||||
if not callable(composer):
|
||||
return ""
|
||||
personal_search = getattr(bridge, "search_bot_personal_memory", None) if bridge is not None else None
|
||||
now_text = ""
|
||||
try:
|
||||
now_text = self._environment_now().strftime("%Y-%m-%d %H:%M")
|
||||
|
|
@ -396,6 +395,53 @@ class MemoryCompanionAdapterMixin:
|
|||
query = _single_line(" ".join(part for part in query_parts if _single_line(part, 240)), 1400)
|
||||
if not query:
|
||||
return ""
|
||||
timeout = max(0.2, min(6.0, _memory_companion_safe_float(getattr(self, "memory_companion_context_timeout_seconds", 1.2), 1.2, 0.2)))
|
||||
if callable(personal_search):
|
||||
try:
|
||||
personal_results = await asyncio.wait_for(
|
||||
personal_search(
|
||||
query,
|
||||
limit=6 if kind == "daily_plan" else 5,
|
||||
memory_types=[
|
||||
"bot_schedule_plan",
|
||||
"bot_observed_activity",
|
||||
"bot_schedule_reconciliation",
|
||||
"bot_window_snapshot",
|
||||
"bot_daily_diary",
|
||||
"bot_creative_work",
|
||||
"bot_media_memory",
|
||||
"bot_subjective_memory",
|
||||
"bot_shared_activity",
|
||||
"bot_detail_fragment",
|
||||
"bot_proactive_message",
|
||||
],
|
||||
),
|
||||
timeout=timeout,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
personal_results = []
|
||||
except Exception as exc:
|
||||
if self._memory_companion_optional_dependency_failed(exc, where="search_bot_personal_memory"):
|
||||
personal_results = []
|
||||
else:
|
||||
logger.debug("[PrivateCompanion] Bot 个人记忆检索失败: %s", _single_line(exc, 120))
|
||||
personal_results = []
|
||||
lines = []
|
||||
for item in personal_results if isinstance(personal_results, list) else []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
content = _single_line(item.get("content"), 360)
|
||||
if not content:
|
||||
continue
|
||||
memory_type = _single_line(item.get("memory_type"), 60)
|
||||
occurred_at = _single_line(item.get("occurred_at"), 40)
|
||||
prefix = f"[{memory_type}] " if memory_type else ""
|
||||
suffix = f"(发生于 {occurred_at})" if occurred_at else ""
|
||||
lines.append(f"- {prefix}{content}{suffix}")
|
||||
if lines:
|
||||
return "\n".join(lines)[: max(300, int(max_chars or 1200))]
|
||||
if not callable(composer):
|
||||
return ""
|
||||
try:
|
||||
bot_mood, bot_energy = self._memory_companion_bot_emotional_state()
|
||||
timeout = max(0.2, min(6.0, _memory_companion_safe_float(getattr(self, "memory_companion_context_timeout_seconds", 1.2), 1.2, 0.2)))
|
||||
|
|
@ -682,8 +728,6 @@ class MemoryCompanionAdapterMixin:
|
|||
idempotency_key: str,
|
||||
) -> None:
|
||||
recorder = getattr(self, "_bot_self_record", None)
|
||||
if not callable(recorder):
|
||||
return
|
||||
safe_payload: dict[str, Any] = {"kind": _single_line(kind, 80)}
|
||||
for key, value in (payload or {}).items():
|
||||
if key in {"self", "event", "user", "group"}:
|
||||
|
|
@ -700,10 +744,50 @@ class MemoryCompanionAdapterMixin:
|
|||
safe_payload[key] = [_single_line(item, 160) for item in list(value)[:20]]
|
||||
else:
|
||||
safe_payload[key] = _single_line(value, 240)
|
||||
if callable(recorder):
|
||||
try:
|
||||
recorder(namespace, safe_payload, idempotency_key=_single_line(idempotency_key, 240))
|
||||
except Exception as exc:
|
||||
logger.debug("[PrivateCompanion] Bot 自有本地记录写入失败: %s", _single_line(exc, 120))
|
||||
bridge = self._memory_companion_bridge()
|
||||
remote_recorder = getattr(bridge, "record_bot_personal_memory", None) if bridge is not None else None
|
||||
if not callable(remote_recorder):
|
||||
return
|
||||
kind_to_type = {
|
||||
"daily_plan": "bot_schedule_plan",
|
||||
"agenda_snapshot": "bot_window_snapshot",
|
||||
"detail_enhancement": "bot_detail_fragment",
|
||||
"calendar_event": "bot_calendar_event",
|
||||
"daily_outfit": "bot_media_memory",
|
||||
"creative_progress": "bot_creative_work",
|
||||
"dream_fragment": "bot_subjective_memory",
|
||||
"proactive_message": "bot_proactive_message",
|
||||
"image_observation": "bot_media_memory",
|
||||
"photo_generation": "bot_media_memory",
|
||||
"qzone_publish": "bot_creative_work",
|
||||
}
|
||||
memory_type = kind_to_type.get(_single_line(kind, 80), "bot_observed_activity")
|
||||
remote_payload = dict(safe_payload)
|
||||
remote_payload["namespace"] = _single_line(namespace, 80)
|
||||
occurred_at = _single_line(
|
||||
remote_payload.get("occurred_at")
|
||||
or remote_payload.get("observed_at")
|
||||
or remote_payload.get("generated_at")
|
||||
or remote_payload.get("created_at"),
|
||||
80,
|
||||
)
|
||||
if not occurred_at:
|
||||
occurred_at = self._memory_companion_now_iso()
|
||||
try:
|
||||
recorder(namespace, safe_payload, idempotency_key=_single_line(idempotency_key, 240))
|
||||
await remote_recorder(
|
||||
memory_type=memory_type,
|
||||
payload=remote_payload,
|
||||
occurred_at=occurred_at,
|
||||
idempotency_key=_single_line(idempotency_key, 240),
|
||||
source_plugin="private_companion",
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.debug("[PrivateCompanion] Bot 自有记录写入失败: %s", _single_line(exc, 120))
|
||||
logger.debug("[PrivateCompanion] Bot 个人记忆远端写入失败,保留本地降级: %s", _single_line(exc, 160))
|
||||
async def _memory_companion_record_calendar_event(self, event: dict[str, Any], *, action: str = "updated", reason: str = "") -> None:
|
||||
if not isinstance(event, dict):
|
||||
return
|
||||
|
|
|
|||
113
tests/test_m6_bot_personal_bridge.py
普通文件
113
tests/test_m6_bot_personal_bridge.py
普通文件
|
|
@ -0,0 +1,113 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
|
||||
import importlib
|
||||
import pathlib
|
||||
import sys
|
||||
import types
|
||||
|
||||
_package_name = "_m6_companion"
|
||||
_package = types.ModuleType(_package_name)
|
||||
_package.__path__ = [str(pathlib.Path(__file__).resolve().parents[1])]
|
||||
sys.modules.setdefault(_package_name, _package)
|
||||
MemoryCompanionAdapterMixin = importlib.import_module(
|
||||
f"{_package_name}.memory_companion_adapter"
|
||||
).MemoryCompanionAdapterMixin
|
||||
|
||||
|
||||
class DummyBridge:
|
||||
def __init__(self, enabled=True):
|
||||
self.enabled = enabled
|
||||
self.writes = []
|
||||
self.searches = []
|
||||
|
||||
async def record_bot_personal_memory(self, **kwargs):
|
||||
self.writes.append(kwargs)
|
||||
return "bot-memory-1"
|
||||
|
||||
async def search_bot_personal_memory(self, query, **kwargs):
|
||||
self.searches.append((query, kwargs))
|
||||
return [{
|
||||
"memory_type": "bot_window_snapshot",
|
||||
"content": "下午窗口完成了创作复盘",
|
||||
"occurred_at": "2026-07-25T16:00:00+08:00",
|
||||
}]
|
||||
|
||||
|
||||
class Adapter(MemoryCompanionAdapterMixin):
|
||||
def __init__(self, bridge=None, local=True):
|
||||
self.bridge = bridge
|
||||
self.local = local
|
||||
self.local_writes = []
|
||||
self.enable_livingmemory_integration = True
|
||||
self._bridge_cache = bridge
|
||||
self._bridge_cache_ts = 9999999999
|
||||
|
||||
def _memory_companion_bridge(self):
|
||||
return self.bridge
|
||||
|
||||
def _bot_self_record(self, namespace, payload, *, idempotency_key):
|
||||
self.local_writes.append((namespace, payload, idempotency_key))
|
||||
|
||||
def _environment_now(self):
|
||||
from datetime import datetime
|
||||
return datetime(2026, 7, 25, 16, 30)
|
||||
|
||||
def _memory_companion_now_iso(self):
|
||||
return "2026-07-25T16:30:00"
|
||||
|
||||
def _memory_companion_bot_emotional_state(self):
|
||||
return "平稳", 0.7
|
||||
|
||||
def _memory_companion_schedule_session_context(self, *, message_text=""):
|
||||
return {"session_id": "bot_personal", "message_text": message_text}
|
||||
|
||||
def _memory_companion_coordination_status(self):
|
||||
return {"available": self.bridge is not None}
|
||||
|
||||
|
||||
class M6BotPersonalBridgeTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_daily_plan_writes_local_and_remote_with_type_mapping(self):
|
||||
bridge = DummyBridge()
|
||||
adapter = Adapter(bridge)
|
||||
await adapter._memory_companion_record_daily_plan({
|
||||
"date": "2026-07-25",
|
||||
"source": "four_window",
|
||||
"items": [{"title": "创作"}],
|
||||
})
|
||||
self.assertEqual(len(adapter.local_writes), 1)
|
||||
self.assertEqual(len(bridge.writes), 1)
|
||||
self.assertEqual(bridge.writes[0]["memory_type"], "bot_schedule_plan")
|
||||
self.assertEqual(bridge.writes[0]["idempotency_key"], "daily_plan:2026-07-25")
|
||||
self.assertEqual(bridge.writes[0]["payload"]["memory_domain"] if "memory_domain" in bridge.writes[0]["payload"] else "bot_self_schedule", "bot_self_schedule")
|
||||
|
||||
async def test_missing_bridge_keeps_local_write(self):
|
||||
adapter = Adapter(None)
|
||||
await adapter._memory_companion_record_daily_plan({"date": "2026-07-25", "items": []})
|
||||
self.assertEqual(len(adapter.local_writes), 1)
|
||||
|
||||
async def test_specialized_search_is_used_for_schedule_context(self):
|
||||
bridge = DummyBridge()
|
||||
adapter = Adapter(bridge)
|
||||
text = await adapter._memory_companion_compose_schedule_context(
|
||||
kind="window_snapshot",
|
||||
segment={"item": {"activity": "创作"}},
|
||||
)
|
||||
self.assertIn("下午窗口完成了创作复盘", text)
|
||||
self.assertEqual(len(bridge.searches), 1)
|
||||
self.assertIn("bot_window_snapshot", bridge.searches[0][1]["memory_types"])
|
||||
|
||||
async def test_remote_failure_does_not_break_local_write(self):
|
||||
class FailingBridge(DummyBridge):
|
||||
async def record_bot_personal_memory(self, **kwargs):
|
||||
raise RuntimeError("bridge down")
|
||||
|
||||
adapter = Adapter(FailingBridge())
|
||||
await adapter._memory_companion_record_daily_plan({"date": "2026-07-25", "items": []})
|
||||
self.assertEqual(len(adapter.local_writes), 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
正在加载…
添加表格
在新工单中引用