Repository navigation
feat(memory): 支持定时生成记忆摘要和在 Portal 中查看与编辑摘要 - #737
openjiuwen-sync-bot[bot] wants to merge 1 commit into
Conversation
|
|
1 similar comment
|
|
|
head_sha: 变更摘要本 PR 在文档记忆模式下新增「用户记忆摘要」能力:通过新增演进模式 主要改动
|
|
head_sha: 代码审查审查结论
💬 仅评论 |
| await service.start() | ||
| except BaseException: | ||
| await service.close() | ||
| raise |
There was a problem hiding this comment.
head_sha: dda5843c7f1559d70be1fdc4849337dee6fc9a14
🟡 Medium Priority
start_memory_background(memory_background.py:184-200)先在 _RUNTIMES[root] 占位/登记 service,再 await service.start();启动失败时调用 await service.close() 回滚。但 MemoryBackground.close()(第 124-132 行)是“先 self._closing = True,再 await self._client.close(),最后才在 _RUNTIMES 中删除自己”。若 self._client.close() 抛异常(_InProcessClient 在 strict_close=True 下会把 runtime 关闭失败重新抛出,见 agent_memory_provider.py:4074-4087),则 _RUNTIMES 的删除不会执行,异常继续向上;同时 _closing 已被置 True。
失败模式:一次启动失败(或运行期关闭失败)后,_RUNTIMES[root] 永久残留该 service,此后同一文档根的任何 start_memory_background 都会在第 185-186 行抛 ValidationError("Document memory background runtime is already running"),服务无法重启后台记忆;对残留 service 再调 close() 也会因 _closing 已 True 直接 return,永远不会清理登记项。属于可复现的“脏状态 + 无法恢复”可靠性问题。
建议:在 MemoryBackground.close() 中用 try/finally 保证 _RUNTIMES 登记项一定被删除(先删登记再 await client.close()),start_memory_background 的失败回滚路径也保证登记项被清理。
| profile_summary = ( | ||
| UserProfileSummary(lambda: LlmProducer.build_named("default", ctx), document_store) | ||
| if document_mode and document_store is not None else None | ||
| ) |
There was a problem hiding this comment.
head_sha: dda5843c7f1559d70be1fdc4849337dee6fc9a14
🟡 Medium Priority
变更行 assembly.py:1040-1044 用 getattr(engine, "document_store", None) 取文档存储后,仅判 document_store is not None 就构造 UserProfileSummary(...);而同批新增的 AgentEngine.document_store 属性(agent_engine.py:294-296)标注的返回类型是 DomainStore,UserProfileSummary.__init__(user_profile_summary.py:69)要求的是 CompositeDomainStore。
契约不一致证据:getattr(..., None) 这种防御式取值本身说明装配期不能确定引擎一定带该属性;而 UserProfileSummary.read/edit/summary 直接调用 self._store.profile_snapshot(...) / profile_input_window(...) / profile_inputs(...) / publish_profile(...),这些只在 CompositeDomainStore 上存在(composite_domain_store.py:676/685/716/723)。
建议:把装配判据从 is not None 改为类型判据:isinstance(document_store, CompositeDomainStore)(或校验 profile_snapshot 能力),不满足时置 None/报错;同时把 AgentEngine.document_store 的返回类型标注为实际需要的 composite 类型。
| )) | ||
| if self.cancellation_signal.is_set(): | ||
| raise JobCancelledError("memory consolidation cancelled", detail=detail) | ||
| return JobInfo(scope=self.scope, status=JobStatus.SUCCEEDED, detail=detail) |
There was a problem hiding this comment.
head_sha: dda5843c7f1559d70be1fdc4849337dee6fc9a14
🟡 Medium Priority
变更行(evolve_job.py:107-113)在 MEMORY_CONSOLIDATE 分支里先用 _result_detail(..., cancelled=False) 组装 detail,随后才判断 self.cancellation_signal.is_set() 并抛 JobCancelledError(detail=detail)。而同一函数中其它两条取消路径(第 140-152、162-174 行)都用 cancelled=True 组装 detail,从而带上 partial_write 与 retry_requires_reconciliation 两个恢复语义字段。
失败模式:evolver.evolve 已在线程中提交写入后才发生取消时,返回值 detail 中的 created_ids/updated_ids 非空,但缺少 partial_write/retry_requires_reconciliation,消费该 detail 的恢复/对账逻辑会把这次取消当成“无部分写入”,从而跳过对账、以 CANCELLED 状态收尾,实际落盘记录与任务状态不一致(数据一致性回归)。
建议:取消分支复用 cancelled=True 的 detail 组装方式:先把 cancellation 检查与 detail 生成合并,确保抛 JobCancelledError 时 detail 含 partial_write/retry_requires_reconciliation。
| ) | ||
| self._authorize(security, scope, Action.READ, "summary") | ||
| self._ensure_space_writable(scope) | ||
| self._ensure_audit_integrity_healthy() |
There was a problem hiding this comment.
head_sha: dda5843c7f1559d70be1fdc4849337dee6fc9a14
🟡 Medium Priority
变更行(query_ops.py:1672-1685)新增的 _summarize_profile 只做 profile_document.profile_id(scope) 校验 + 空间级 _authorize(WRITE, "summary", space_action=SpaceAction.UPDATE),没有复用同文件 _authorize_profile_owner(1638-1643)里的 scope != Scope(org=actor.org, space=actor.space, user=actor.user) 判据。
契约不一致:同一次改动中 read_profile_summary / edit_profile_summary 都要求「scope 必须等于操作者身份」,而面向后台任务与 MemoryAPI.summary 的生成路径只要求空间 UPDATE 权限。
建议:在 _summarize_profile 开头加入与 read_profile_summary/edit_profile_summary 一致的 owner 判据(例如复用 _authorize_profile_owner(scope, security)),使后台定时任务、MemoryAPI.summary 与 Portal 读写路径使用同一身份契约。
| self, scope: Scope, body: str, revision: str, *, security: RequestSecurityContext, | ||
| ) -> tuple[str, str]: | ||
| """Replace the owner's Markdown body if its revision still matches.""" | ||
| raise NotImplementedError("Profile summary requires document memory") |
There was a problem hiding this comment.
head_sha: dda5843c7f1559d70be1fdc4849337dee6fc9a14
🟡 Medium Priority
变更行:memory_api.py:489-493 新增 edit_profile_summary 默认实现 raise NotImplementedError("Profile summary requires document memory")。
契约冲突证据:
- 同一次提交里
query_ops.py:1658-1659对完全相同的条件(self._profile_summary is None,即非文档模式)抛的是ValidationError(同一句 message)。基类与实现给出两个不同异常类型,调用方无法用一套 except 处理。 - 本文件既有约定是"未装配能力默认拒绝时抛领域错误":
begin_human_view在 memory_api.py:119 抛ValidationError,prepare_video_ingest在 570-574 抛UnsupportedCapabilityError(storage/kv.py、graph.py、fs.py 同样如此)。api_key_authenticator.py:85 的注释还明确写了"避免让调用方在首个请求才发现 NotImplementedError(500)"。 - 与同一 hunk 的
read_profile_summary(返回 None,配合 S02 的available:false语义)也不对称:读取路径优雅降级、写入路径直接抛非领域异常。
失败模式:任何未覆盖该方法的 MemoryAPI 实现(third-party/远端代理适配器)在 Portal 保存摘要时抛 NotImplementedError。它不在 AgentMemoryError 层级内,HTTP/Portal 层的领域错误映射不会命中,最终变成 500 内部错误而不是 4xx,同时 -> tuple[str, str] 的返回声明失效、调用方拿到异常而非可呈现给用户的失败原因;同一后端在"读"与"写"两条路径上给出的可诊断性也不一致。
建议:把裸 NotImplementedError 换成与实现层一致的领域错误(ValidationError),并在 docstring 中写明未启用文档模式的失败语义与 revision 冲突时的错误类型。
| raise NotImplementedError("Profile summary requires document memory") | |
| raise ValidationError("Profile summary requires document memory") |
| summarize_profile=partial(self._summarize_profile, self.check_cancelled, groups) | ||
| if self._summarize_profile is not None else None, | ||
| ) | ||
| result = await asyncio.to_thread(self._evolver.evolve, request) |
There was a problem hiding this comment.
head_sha: dda5843c7f1559d70be1fdc4849337dee6fc9a14
🟡 Medium Priority
新增分支(evolve_job.py:94-104)把 resolver 产出的所有 group.units 直接摊平为 units,然后一次性 self._evolver.evolve(request),不再经过 _evolve_group(第 219-234 行)。而 _evolve_group 里存在的三条过滤在此被跳过:system_metadata["middle"] == "true" 的条目、continuity_kind == "relation"、continuity_event;此外 FORGET 模式下的 self._evolver.retains(u) 过滤也缺失。
失败模式:类注释(第 39-40 行)明确声明 “middle 排除留在链条——该类 unit 由 MiddleToLongJob 专门处理,避免同一原文被两次处理”。一旦 dreaming 驱动以 MEMORY_CONSOLIDATE 提交且候选源包含 middle 条目(PredicateResolver/list 全量默认就会带出),这批中间记忆会被记忆整合与 MiddleToLongJob 各处理一次,产生重复写入/重复摘要;关系型连续事件(relation/continuity_event)也会被当作待整合正文送进整合链。是否真正重复取决于 evolver 内部是否二次过滤,但从本文件契约看已经出现行为分叉。
建议:抽出/复用 _evolve_group 中的 middle、continuity_kind=="relation"、continuity_event 以及 FORGET retains 过滤,在摊平 units 之后、构造 EvolveRequest 之前应用。
dda5843 to
2710e4b
Compare
2710e4b to
3bd1353
Compare
3bd1353 to
307fafa
Compare
307fafa to
73b9e96
Compare
| | 能力 | 行为 | | ||
| |---|---| | ||
| | 记忆概览 | 查看各状态记录数、来源应用数、近 365 天每日新增和来源分布,点击记录数量或来源可查看对应列表 | | ||
| | 记忆摘要 | 在记忆概览底部查看 Dreaming 生成的完整摘要,编辑并保存 Markdown 正文。保存后直接写回当前用户的摘要;若 Dreaming 已更新文件,页面保留草稿并提示冲突 | |
There was a problem hiding this comment.
head_sha: 73b9e96210df7d0d6d74774791e62669417c9bf2
-
[P1] 摘要读写绕过存储授权插件。
composite_domain_store.py:716 (jiuwen_memory/storage/domain_store_impl/
composite_domain_store.py:716) 的 profile_snapshot、publish_profile 没有 access 参
数,也不调用 _authorize,取得根目录后直接读写文件。因此即使存储安全插件拒绝读取或
更新,API 层允许后仍可操作摘要。违反 S09 §11;应保留领域存储层的授权边界。 -
[P1] 新能力绑定具体实现,无法通过注册和配置替换。
assembly.py:1041 (jiuwen_memory/api/memory_api_impl/assembly.py:1041) 使用
isinstance(..., CompositeDomainStore),直接构造 UserProfileSummary,固定选择
llm.default。替换 DomainStore 后能力静默消失;已有 CloudEngine 也因没有该属性而无
法装配摘要。违反 S09 §1、§3、§7、§9。摘要算法应通过契约注入,存储支持情况应通过显
式能力判断。 -
[P2] 新增存储协议只写在 SQLite 实现中。
composite_domain_store.py:680 (jiuwen_memory/storage/domain_store_impl/
composite_domain_store.py:680) 调用三个 profile_input_* 方法,但
DocumentShadowIndex 没有这些契约,也没有装配期能力校验。替换成满足原接口的后端,首
次生成摘要才会报错。违反 S09 §6、§8、§10。 -
[P2] 修改已有记忆不会触发摘要更新。
sqlite_shadow_index.py:1125 (jiuwen_memory/storage/shadow_impl/
sqlite_shadow_index.py:1125) 只跟踪 INSERT/DELETE。记忆被摘要消费后,再通过
OVERWRITE 修正文案,UPDATE 不产生新序号,后续增量摘要会漏掉纠正。应补充更新事件及
对应回归测试。
针对新增 API,我的具体判断是:
新增接口 必要性与扩展性判断
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
read_profile_summary 合理,可保留。 完整摘要读取与现有按块读取不
同,但应依赖摘要能力契约。
───────────────────────────────────── ──────────────────────────────────────────────
edit_profile_summary 合理,可保留。 整份文档的 revision 并发检查
有价值,需补齐存储授权。
───────────────────────────────────── ──────────────────────────────────────────────
summary(scope) 当前没有充分必要性。 与
evolve(MEMORY_CONSOLIDATE) 重复,又增加同步
执行入口,缺少任务状态和取消语义。建议复用
evolve;确需同步入口时应明确独立需求。
───────────────────────────────────── ──────────────────────────────────────────────
ensure_memory_consolidation 幂等登记有价值,接口位置不完整。 目前只存在
于具体实现,宿主直接调用或用 getattr 探测,
未进入公共契约。
───────────────────────────────────── ──────────────────────────────────────────────
bind_memory_consolidation_readiness 更适合作为装配依赖。 当前运行时 setter 会替
换共享回调,多宿主协作和生命周期责任不清晰。
───────────────────────────────────── ──────────────────────────────────────────────
导出的三个配置辅助函数 不宜作为业务 API 扩展。 document_root、周期
解析、调度器配置改写暴露具体配置结构,宜归入
明确的宿主装配接口。
此外,MemoryAPI:479 (jiuwen_memory/api/memory_api.py:479) 对不支持的生成、读取返回
None,编辑却抛 ValidationError,没有统一能力声明。此次 S02 虽写入了这种行为,但它与
S09 §6 的统一不支持错误要求存在冲突,需要协调,不能仅靠修改业务 spec 消除契约问题。
建议收敛为:API 保留授权和摘要读改入口;生成复用演进任务;摘要算法与存储能力通过明确
契约装配。 这样替换算法、模型或后端时,才不需要再次修改 API、Engine、Job 多层。
|
|
||
| ## 决策 | ||
|
|
||
| ### 用户画像的文档位置 |
There was a problem hiding this comment.
head_sha: 73b9e96210df7d0d6d74774791e62669417c9bf2
🔴 必须修改
- 新增画像存储接口绕过存储层统一授权,且不在 DomainStore 契约内
composite_domain_store.py 新增的 profile_snapshot / publish_profile / profile_input_* 都不接收 access: StorageAccessContext,也不调用 _authorize,取得文档根后直接读写文件。这与同类中所有既有接口的做法相反:read_md_file(base 文件 696 行)与 edit_md_file(734 行)都先 self._authorize(access, scope, StorageAction.X, "memory_unit")。
S06 不变量 26 明确"DomainStore 领域接口……统一授权不可绕过",S09 §11 要求"领域门面和其暴露的底层能力端口执行一致的安全约束"。当前只在 API 层做本人校验,任何其他调用方(引擎、后续子系统、测试)直接经 engine.document_store 调用即可读写任意 scope 的画像文件,且替换掉 API 层校验后不会留下任何存储层兜底。建议给新接口补 access 参数并做 _authorize(读 GET / 写 UPDATE),由 QueryOpsMixin 传入,同时在 S06 中记录新接口与授权语义。
- 摘要能力按具体实现类型装配,替代后端/CloudEngine 静默失效
assembly.py 用 getattr(engine, "document_store", None) + isinstance(document_store, CompositeDomainStore) 直接构造 UserProfileSummary,而 AgentEngine.document_store(agent_engine.py 新增属性)标注返回 DomainStore,与 UserProfileSummary.init 要求的 CompositeDomainStore 不一致;CloudEngine 有 _domain_store 但没有该属性,因此云引擎即使文档存储支持画像也拿不到能力,Portal 只显示 available:false,无可观测原因。
S09 §9 原文即"需要 isinstance(ConcretePlugin) 才能完成的绑定,说明公共契约或装配协议尚不完整";§6 要求能力显式声明、§12 要求降级显式。上一轮把 is not None 改成 isinstance 只消除了运行期 AttributeError,没有解决契约问题。建议在 DomainStore 上声明可选画像能力(或独立端口)并在装配期做能力判定,UserProfileSummary 通过契约注入。
- profile_input_* 仅存在于 SQLite 影子实现,未进入 DocumentShadowIndex 契约
shadow.py 的 DocumentShadowIndex 没有声明 profile_input_high_watermark/page/owner_scopes,但 composite_domain_store.py 在 _raw_shadow_index()(类型即该 ABC)上直接调用。任何满足现有契约的替代影子后端都会在第一次生成摘要时抛 AttributeError,且没有装配期能力校验——违反 S09 §6/§8。
建议在 DocumentShadowIndex 增加带默认实现的画像增量端口(未支持时 NotImplementedError/能力 False),装配期显式判定;若短期只支持 SQLite,应在装配期 fail fast 并写入 S06。
🟡 建议修改
4. UPDATE 不产生新序号,纠正后的记忆不会重新进入增量摘要
sqlite_shadow_index.py 新增的 profile_input 触发器只覆盖 memory_unit 的 INSERT/DELETE,而 update_units 的 _update_one(同文件 979 行)是对 memory_unit 原地 UPDATE(rowid 不变)。因此一条记忆被摘要消费后,再经 Portal 纠正/OVERWRITE 修改正文,序号不变、游标不推进,后续增量摘要永远看不到这次纠正,只有手工编辑摘要才能体现。建议补 UPDATE 触发器(判定 content_hash 变化后重新入队)或改为在 _update_one 中显式登记,并补回归测试。
- 默认开启且静默改写常驻宿主的调度器,升级影响面需要明确
document_dreaming.py 中 memory_consolidation.enabled 默认 True;with_consolidation_scheduler 在文档模式下把 scheduler.default 从 in_process 改成 async_timer,并注入一个名为 memory_background 的 SQLite KV(同名 kv_store.memory_background 配置会被覆盖)。HTTP/MCP/local 常驻宿主又会对每个认证用户首次成功请求自动登记 4 小时摘要任务。请确认这是有意默认开启,并写清:升级后行为变化、如何关闭、调度器被替换的可观测性、以及不要占用用户自定义的 kv_store.memory_background 名字。
- 成功响应路径依赖画像登记,可能把已成功的请求变成 500
http_server/main.py 在 invoke_api 之后、send(200) 之前调用 srv.register_profile_owner(security);core/server.py 只捕获 AgentMemoryError,而 ensure_memory_consolidation 内部会走 scheduler.validate / asyncio.run(scheduler.submit),非领域异常会落入外层 except Exception → 返回 InternalError,用户的记忆写入已经落盘却看到失败。MCP 与 local 也在结果之后调用同一入口。另外 _profile_lock 内执行 restore_dreaming + 注册(同步 IO),会把不同用户首次登记的请求串行化。建议登记改为 best-effort:捕获 Exception 记日志,或移动到响应发送之后/后台任务执行。
- 文档双向同步仍有缺口
api/AGENTS.md 第 51 行的 memory_api.py 方法清单和 query_ops.py 职责(59 行)未加入 summary / read_profile_summary / edit_profile_summary;
jiuwenswarm/AGENTS.md 的模块地图没有新增的 memory_background.py;
S06 只补了画像路径,没有记录新增的画像存储接口,且不改动的不变量 26 与当前实现相冲突(与意见 1 同源)。
73b9e96 to
c390270
Compare
|
head_sha:
|
c390270 to
c038ae0
Compare
Paired: GitHub #737 ↔ GitCode !525
在文档记忆模式下,Swarm 初始化记忆功能后会为当前用户登记摘要 Dreaming 定时任务。指定候选记忆时,只使用有权限的候选材料,并保留默认增量游标。
Portal 概览支持查看和编辑 Markdown 摘要。如果后台生成了新版本,保存时会提示冲突并保留用户草稿。
验证通过:27 个 Python 定向测试、Portal 前端行为检查及 git diff --check。
Linked Closing Issues: