From d4a4ed48d29740b252199272cd93546a4a174ef0 Mon Sep 17 00:00:00 2001 From: ToNy_St4rk Date: Mon, 30 Nov 2026 19:23:57 +0800 Subject: [PATCH] =?UTF-8?q?fix(memory):=20=E4=BF=AE=E5=A4=8D=20USER.md=20?= =?UTF-8?q?=E7=BC=96=E8=BE=91=E5=90=8E=E6=97=A7=E4=BA=8B=E5=AE=9E=E5=9B=9E?= =?UTF-8?q?=E6=B5=81=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修复多 agent 画像副本失效及动态抽取回注问题,并保持存储编辑接口兼容。 Refs: #7124 Issue: https://gitcode.com/openJiuwen/jiuwenswarm/issues/7124 --- docs/specs/S02-memory-api.md | 13 +- docs/specs/S06-storage.md | 8 ++ jiuwen_memory/api/AGENTS.md | 3 + jiuwen_memory/api/memory_api_impl/md_ops.py | 10 +- jiuwen_memory/config/AGENTS.md | 3 + jiuwen_memory/config/routing.py | 14 +++ jiuwen_memory/construction/AGENTS.md | 10 +- .../evolver_impl/dynamic_evolver.py | 4 + .../evolver_impl/orchestrating_evolver.py | 53 +++++++++ jiuwen_memory/control/AGENTS.md | 4 + .../control/engine_impl/agent_engine.py | 7 +- .../control/engine_impl/cloud_engine.py | 7 +- .../control/engine_impl/doc_mode_support.py | 20 +++- jiuwen_memory/storage/AGENTS.md | 9 ++ jiuwen_memory/storage/domain_store.py | 16 +++ .../composite_domain_store.py | 62 +++++++++- .../unit/api/test_local_memory_api_md_ops.py | 48 ++++++++ .../test_evolver_grouped_extract.py | 78 +++++++++++- .../control/test_document_edit_contract.py | 89 ++++++++++++++ .../storage/test_composite_domain_store.py | 111 ++++++++++++++++++ 20 files changed, 550 insertions(+), 19 deletions(-) create mode 100644 tests/unit/control/test_document_edit_contract.py diff --git a/docs/specs/S02-memory-api.md b/docs/specs/S02-memory-api.md index acf60a5e1..e50252667 100644 --- a/docs/specs/S02-memory-api.md +++ b/docs/specs/S02-memory-api.md @@ -5,7 +5,7 @@ | 项 | 值 | |---|---| | 关联模块 | jiuwen_memory/api/ | -| 最近一次修订日期 | 2026-11-28 | +| 最近一次修订日期 | 2026-11-30 | | 关联特性补充 | docs/features/api/F04-memory-metadata-separation.md,docs/features/api/F05-http-memory-api-alignment.md,docs/features/api/F06-access-parameter-forwarding.md,docs/features/api/F07-access-surface-error-semantics.md,docs/features/api/F09-sdk-runtime-logging.md,docs/features/F05-personal-memory-portal.md | | 关联特性文档 | docs/features/api/F01-memory-api-impl-design.md,docs/features/api/F02-write-infer-extract.md,docs/features/api/F03-batch-write-api.md,docs/features/api/F04-memory-metadata-separation.md,docs/features/api/F05-http-memory-api-alignment.md,docs/features/api/F06-access-parameter-forwarding.md,docs/features/api/F07-access-surface-error-semantics.md,docs/features/api/F09-sdk-runtime-logging.md,docs/features/api/F10-batch-update-api.md,docs/features/F01-system-spec-design.md,docs/features/construction/F02-dynamic-extraction-consolidation.md,docs/features/construction/F04-cc-memory-compat.md,docs/features/construction/F05-construction-spec-multimodal-design.md,docs/features/construction/F08-entity-schema-extension.md,docs/features/common/F01-memory-layer.md,docs/features/common/F03-scope-space-isolation.md,docs/features/common/F08-memory-tree.md,docs/features/common/F09-log-privacy.md,docs/features/retrieval/F03-metadata-filtering.md,docs/features/retrieval/F09-query-rewrite.md,docs/features/control/F04-permission-context-routing.md,docs/features/control/F05-cloud-engine-design.md,docs/features/config/F01-config-source.md,docs/features/control/F07-collective-memory-design.md,docs/features/construction/F13-dreaming.md,docs/features/ingest/F02-assets-ingestor-boundary.md、[F04 安全能力与设计决策](../features/common/F04-security-interfaces-and-encryption.md),docs/features/common/F11-new-trace.md,docs/features/control/F10-async-write-orchestration.md | @@ -1140,8 +1140,19 @@ def read_md_file( 路由装配下(`_routing_enabled()`),API 层把反查 scope 折算为空间级 `Scope(org, space)`(`md_filename → memory_class` 的 space_template 经 `principal.kernel_coords(coords, identity)` 渲染),与写入侧 `RouteDecision` 落盘形态(org+space、主体维空)对齐,避免 5 段等值反查因 space/user 两段错位静默返空。**折算出的空间级 scope 同时是鉴权(READ)与审计(`target_scope`)的 target**——与写入侧「先定落点、对落盘空间判权 + 审计」对称:调用方须对该空间有读权,空 `scope.space` 不再绕过空间轴判权,审计记录实际访问的空间而非 raw scope。路由未启用、坐标缺失或模板渲染不出时退回 raw scope,判权/审计/反查三者同轴(F08 D5.1)。 +`read_md_file` 只返回 ACTIVE / ARCHIVED 块,不因正文再次出现而回显历史失效版本。 + #### edit_md_file +编辑取代的旧块全部标记失效,包括同正文的重复索引记录。USER.md 共享画像编辑由 API +对同一 `(org, space, user, session)` 的各 agent Scope 逐个鉴权后,显式传递授权集合; +存储层仅在该集合内同步旧副本,普通编辑仍限定原 Scope。相同正文的多个索引记录 +视为一个物理块,不同正文或路径仍要求唯一命中。 +对 USER.md 的显式纠错优先于自动抽取:被编辑取代的精确正文不得由轮末抽取重新写回。 +自动抽取按同一 `(org, space, user, session)` 共享画像范围汇总失效标记和可见恢复正文, +包括此前尚无记录的新 agent;不作模糊语义匹配,不跨组织、空间、用户或 session, +不限制任一合法 agent 的显式写入或再次编辑恢复原值。 + **状态:已实现**(F08,仅文档模式可用——非文档模式 `InMemoryEngine` 抛 `ValidationError`)。 ```python diff --git a/docs/specs/S06-storage.md b/docs/specs/S06-storage.md index c9c1dc915..db835fc0f 100644 --- a/docs/specs/S06-storage.md +++ b/docs/specs/S06-storage.md @@ -1092,3 +1092,11 @@ Swarm 内置 SDK 的经验文档模式将可用技能直接写入宿主技能库 经验文档数据面按完整作用域读写,普通文档列表不合并经验条目。 经验 Markdown 写正文列表;同目录隐藏元数据文件记录条目顺序、ID、作用域和重建索引所需字段。 读取和重建时配对校验;可唯一匹配剩余条目的 Markdown 删除会同步移除索引。 + +### 共享画像编辑的可选数据面契约 + +`DomainStore.edit_shared_profile(scope, old_text, new_text, *, profile_scopes, access=None)` +仅用于 API 逐个鉴权后的 USER.md 共享编辑。实现须校验同 org/space/user/session 边界、 +失效授权集合内的全部旧副本,并保证失败时不留下部分更新。默认实现抛 +`UnsupportedStorageCapabilityError`,不降级为单 Scope 编辑。RoutingDomainStore 委托 +活动数据面的同名契约。普通 `edit_md_file` 的原参数保持不变,Engine 不额外传实现私有参数。 diff --git a/jiuwen_memory/api/AGENTS.md b/jiuwen_memory/api/AGENTS.md index 4cae45fd6..3770875d3 100644 --- a/jiuwen_memory/api/AGENTS.md +++ b/jiuwen_memory/api/AGENTS.md @@ -34,6 +34,9 @@ HTTP 和 SDK 使用 `open_config_overlay` 定位配置库。文件路径由可 私有 `_should_write_document` 重导出现有配置归一函数,供内置适配器判断文档流程装配, 不新增 MemoryAPI 方法,也不公开底层配置对象。 +USER.md 共享编辑按物理正文合并重复命中,对各 agent Scope 逐个 WRITE 鉴权后 +注入内部 `_authorized_profile_scopes`;外部传入该键时拒绝,边界以 S02 为准。 + ## 模块地图 `runtime_configuration.py` 提供公开的 `sdk_continuity_runtime_identity` 配置检查辅助, diff --git a/jiuwen_memory/api/memory_api_impl/md_ops.py b/jiuwen_memory/api/memory_api_impl/md_ops.py index 757dfef3d..49e51d60f 100644 --- a/jiuwen_memory/api/memory_api_impl/md_ops.py +++ b/jiuwen_memory/api/memory_api_impl/md_ops.py @@ -160,10 +160,16 @@ def _edit_shared_document(self, paths, scopes, filename, old_text, new_text, sec matches.extend((path, unit) for unit in units if old_text in unit.content) if not matches: raise NotFoundError(message="No matching visible document memory") - if len(matches) != 1: + shared_profile = filename == "USER.md" and all(path == "USER.md" for path, _ in matches) + distinct_blocks = {(path, unit.content) for path, unit in matches} + if len(matches) != 1 and (not shared_profile or len(distinct_blocks) != 1): raise ValidationError("Shared document edit requires one visible original memory") path, original = matches[0] target = Context(scope=original.scope, extensions={"_authorized_collective_document": path}) + if shared_profile: + for scope in scopes: + self._authorize(security, scope, Action.WRITE, "edit_md_file") + target.extensions["_authorized_profile_scopes"] = scopes units = asyncio.run(self._commands.edit_md_file(target, filename, old_text, new_text)) self._log(security.auth.actor, "edit_md_file", target_scope=target.scope, detail={"previous_unit": original.id, "document": path}) @@ -173,6 +179,8 @@ def _edit_shared_document(self, paths, scopes, filename, old_text, new_text, sec def _reject_internal_document_options(context): if "_authorized_collective_document" in context.extensions: raise ValidationError("Invalid document options") + if "_authorized_profile_scopes" in context.extensions: + raise ValidationError("Invalid document options") def _collective_document_scope(self, context, filename, security, action): self._reject_internal_document_options(context) diff --git a/jiuwen_memory/config/AGENTS.md b/jiuwen_memory/config/AGENTS.md index 1001e3091..758758db5 100644 --- a/jiuwen_memory/config/AGENTS.md +++ b/jiuwen_memory/config/AGENTS.md @@ -6,6 +6,9 @@ 负责装配配置解析/合并,以及运行时晚绑定配置来源 `ConfigSource`。 +RoutingDomainStore 的共享画像编辑通过 `edit_shared_profile` 委托当前活动数据面; +活动插件未实现时保留可选契约的能力不支持错误,不回退普通编辑。 + ## 模块地图 | 文件/目录 | 职责 | diff --git a/jiuwen_memory/config/routing.py b/jiuwen_memory/config/routing.py index 7a9e8ed8c..424bdb0ef 100644 --- a/jiuwen_memory/config/routing.py +++ b/jiuwen_memory/config/routing.py @@ -804,6 +804,20 @@ def edit_md_file( scope, md_basename, old_text, new_text, project=project, access=access ) + def edit_shared_profile( + self, + scope: Scope, + old_text: str, + new_text: str, + *, + profile_scopes: list[Scope], + access: StorageAccessContext | None = None, + ) -> list[MemoryUnit]: + """Forward the optional shared-profile contract to the active domain.""" + return self._active_domain().edit_shared_profile( + scope, old_text, new_text, profile_scopes=profile_scopes, access=access, + ) + def health(self) -> None: self._active_domain().health() diff --git a/jiuwen_memory/construction/AGENTS.md b/jiuwen_memory/construction/AGENTS.md index e2f00caa0..b4e52b3e7 100644 --- a/jiuwen_memory/construction/AGENTS.md +++ b/jiuwen_memory/construction/AGENTS.md @@ -82,9 +82,9 @@ trace 均使用 common/log 的敏感参数标记,不能因调试文档路径 infer=true 由 Engine 等待抽取;显式 evolve/dreaming 经 Scheduler 执行: Evolver.evolve(units, mode): EXTRACT → [orchestrating] _evolve_extract: (可选)appraise→proceed=False短路 | - context→extract→prepare→route→annotate→按配置直写/去重写→(可选)finalize + context→extract→prepare→route→显式画像编辑复核(非procedural)→annotate→按配置直写/去重写→(可选)finalize → [dynamic] _evolve_extract: (可选)appraise→短路 | - context→extract→prepare→route→annotate→consolidate(判定)→reflect→落盘→(可选)finalize + context→extract→prepare→route→annotate→consolidate(判定)→reflect→显式画像编辑复核→落盘→(可选)finalize → [schema] _evolve_extract: Source-first→属性抽取→属性落盘→Source entities 写回 CONSOLIDATE → _evolve_consolidate: (可选)curate→abstract→prepare→annotate→按产物契约直写/去重写 EXPERIENCE_CONSOLIDATE → 校验经验类型与 Curator→复用上述整理归纳流程一次 @@ -115,6 +115,12 @@ prompt_guard 对受保护 unit 的内容分批保留原子引用,过小的正 ## 行为铁律 +Orchestrating 的 `_commit_candidates` 在路由后、去重及落盘前调用 `_filter_edited_profiles`; +Dynamic 的 `_persist_decisions` 在反思完成后对实际待提交候选执行同一复核, +通过写入方绑定的 DomainStore 在同一共享画像范围(org/space/user/session)查询 +`md_edit_superseded` 标记并复核各 agent 当前可见正文。 +精确匹配、恢复及作用域边界以 S02 的 `edit_md_file` 规约为准。 + 0. **派生 metadata 按来源合并**:单源复制 `user_metadata`,多源只保留相等交集; `infer` / `procedural` / `middle` 不传播。IndexBuilder 分别投影 `system_metadata.` 和 `user_metadata.`。 diff --git a/jiuwen_memory/construction/evolver_impl/dynamic_evolver.py b/jiuwen_memory/construction/evolver_impl/dynamic_evolver.py index 4a97e1e4d..fffd2f194 100644 --- a/jiuwen_memory/construction/evolver_impl/dynamic_evolver.py +++ b/jiuwen_memory/construction/evolver_impl/dynamic_evolver.py @@ -313,7 +313,11 @@ def _persist_decisions( ) -> EvolveResult: result = EvolveResult() successors: dict[tuple[str, str, str, str, str, str], MemoryUnit] = {} + accepted = self._filter_edited_profiles([decision.candidate for decision in decisions]) + accepted_ids = {candidate.id for candidate in accepted} for decision in decisions: + if decision.candidate.id not in accepted_ids: + continue self._apply_decision( decision.candidate, decision.decision, diff --git a/jiuwen_memory/construction/evolver_impl/orchestrating_evolver.py b/jiuwen_memory/construction/evolver_impl/orchestrating_evolver.py index ceca7fe13..de2a826f3 100644 --- a/jiuwen_memory/construction/evolver_impl/orchestrating_evolver.py +++ b/jiuwen_memory/construction/evolver_impl/orchestrating_evolver.py @@ -72,6 +72,7 @@ messages_key, ) from jiuwen_memory.common.type_def.chat import ChatMessage +from jiuwen_memory.common.type_def.filter import FilterClause, FilterOp from jiuwen_memory.common.type_def.memory import ROUTE_CTX_KEY, Segment from jiuwen_memory.common.type_def.memory_codec import dumps, loads from jiuwen_memory.config.document_flag import resolve_index_builder_default @@ -1829,6 +1830,8 @@ def _commit_candidates(self, state: ExtractState) -> EvolveResult: if state.candidates: self._prepare_extract_candidates(state) state.candidates = self._route(state.sources, state.candidates) + if not state.procedural: + state.candidates = self._filter_edited_profiles(state.candidates) if not state.candidates: return EvolveResult() self._annotate_layers(state.candidates) @@ -1837,6 +1840,56 @@ def _commit_candidates(self, state: ExtractState) -> EvolveResult: return EvolveResult(created_ids=created, created_units=list(state.candidates)) return self._dedup_batch(state.candidates) + def _filter_edited_profiles(self, candidates: list[MemoryUnit]) -> list[MemoryUnit]: + """Automatic extraction must not undo an explicit USER.md correction. + + Match exact normalized bodies within the user's shared profile. Explicit writes and + edits still allow the user to restore a previous fact deliberately. + """ + if self._read_domain is None: + return candidates + + def profile_key(scope: Scope) -> tuple[str, str, str, str]: + return scope.org, scope.space, scope.user, scope.session + + blocked_by_scope: dict[tuple[str, str, str, str], set[str]] = {} + known_scopes = None + accepted = [] + for candidate in candidates: + if candidate.system_metadata.get("memory_class") != "user_profile": + accepted.append(candidate) + continue + scope = candidate.scope + key = profile_key(scope) + if key not in blocked_by_scope: + if known_scopes is None: + known_scopes = self._read_domain.scopes() + related_scopes = [item for item in known_scopes if profile_key(item) == key] + if scope not in related_scopes: + related_scopes.append(scope) + blocked = set() + for related in related_scopes: + edited = self._read_domain.list( + related, limit=1_000_000, filters=FilterClause( + "system_metadata.md_edit_superseded", FilterOp.EQ, True, + ), + ).items + for unit in edited: + if unit.lifecycle is not LifecycleState.SUPERSEDED: + continue + if unit.system_metadata.get("md_filename") == "USER.md": + blocked.add(" ".join(unit.content.split())) + if blocked: + for related in related_scopes: + visible = self._read_domain.read_md_file(related, "USER.md") + blocked.difference_update( + " ".join(unit.content.split()) for unit in visible + ) + blocked_by_scope[key] = blocked + if " ".join(candidate.content.split()) not in blocked_by_scope[key]: + accepted.append(candidate) + return accepted + def _appraise(self, units: list[MemoryUnit]) -> Appraisal | None: """抽取前准入评价;未配置评价算子返回 ``None``(appraise 自身的异常照常冒泡)。""" if self._appraiser is None: diff --git a/jiuwen_memory/control/AGENTS.md b/jiuwen_memory/control/AGENTS.md index 58c96e8f6..0de5408f9 100644 --- a/jiuwen_memory/control/AGENTS.md +++ b/jiuwen_memory/control/AGENTS.md @@ -12,6 +12,10 @@ Engine 摄入后补入调用方标签,原文及标签交给可信分类、抽 提前替换。MemoryUnit 在 IndexBuilder 生成持久化索引前统一保护,直接 KV 原文消息 写保护副本;真源私有关联提交和删除由 KV 边界负责,preview 不覆盖待处理业务输入。 +AgentEngine / CloudEngine 共用 `doc_mode_support.edit_document`:普通编辑维持 +`DomainStore.edit_md_file` 原签名;仅 API 注入授权画像 Scope 集合时调用可选 +`edit_shared_profile` 契约,不自行枚举或扩大共享范围,具体边界见 S02 / S06。 + ## 模块地图 个人聚合辅助 `application/personal_memory.py` 在授权回调返回的完整条目集合上筛选来源、 diff --git a/jiuwen_memory/control/engine_impl/agent_engine.py b/jiuwen_memory/control/engine_impl/agent_engine.py index b07db22cb..9e9b7ed70 100644 --- a/jiuwen_memory/control/engine_impl/agent_engine.py +++ b/jiuwen_memory/control/engine_impl/agent_engine.py @@ -77,6 +77,7 @@ from jiuwen_memory.control.engine import EngineProducer, MemoryEngine from jiuwen_memory.control.engine_impl.doc_mode_support import ( document_options, + edit_document, restore_coords_from_md_filename, ) from jiuwen_memory.control.engine_impl.evolve_dispatch import ( @@ -1026,12 +1027,12 @@ async def edit_md_file( scope 由 API 层鉴权后传入,Engine 信任)。 """ return await asyncio.to_thread( - self._domain_store.edit_md_file, - context.scope, + edit_document, + self._domain_store, + context, md_filename, old_text, new_text, - **document_options(context), ) def _write_binding(self, units: list[MemoryUnit]) -> PipelineBinding | None: diff --git a/jiuwen_memory/control/engine_impl/cloud_engine.py b/jiuwen_memory/control/engine_impl/cloud_engine.py index c06b4dec4..0551bed95 100644 --- a/jiuwen_memory/control/engine_impl/cloud_engine.py +++ b/jiuwen_memory/control/engine_impl/cloud_engine.py @@ -51,6 +51,7 @@ from jiuwen_memory.control.engine import EngineProducer, MemoryEngine from jiuwen_memory.control.engine_impl.doc_mode_support import ( document_options, + edit_document, restore_coords_from_md_filename, ) from jiuwen_memory.control.engine_impl.evolve_dispatch import ( @@ -1089,12 +1090,12 @@ async def edit_md_file( 内部完成写窗保护 + edit_content 原子替换 + 继承式 SUPERSEDE 同步 shadow。 """ return await asyncio.to_thread( - self._domain_store.edit_md_file, - context.scope, + edit_document, + self._domain_store, + context, md_filename, old_text, new_text, - **document_options(context), ) def _load(self, scope: Scope, unit_id: str) -> MemoryUnit: diff --git a/jiuwen_memory/control/engine_impl/doc_mode_support.py b/jiuwen_memory/control/engine_impl/doc_mode_support.py index abf323061..13055de8c 100644 --- a/jiuwen_memory/control/engine_impl/doc_mode_support.py +++ b/jiuwen_memory/control/engine_impl/doc_mode_support.py @@ -11,7 +11,25 @@ from __future__ import annotations +from jiuwen_memory.common.errors import ValidationError from jiuwen_memory.common.type_def import COORDS_KEY, MD_FILENAME_KEY, Context, MemoryUnit +from jiuwen_memory.storage.domain_store import DomainStore + + +def edit_document( + domain: DomainStore, context: Context, filename: str, old_text: str, new_text: str, +) -> list[MemoryUnit]: + """Dispatch shared edits through their optional contract, preserving legacy edits.""" + scopes = context.extensions.get("_authorized_profile_scopes") + if scopes is not None: + if filename != "USER.md": + raise ValidationError("Shared profile editing requires USER.md") + return domain.edit_shared_profile( + context.scope, old_text, new_text, profile_scopes=scopes, + ) + return domain.edit_md_file( + context.scope, filename, old_text, new_text, **document_options(context), + ) def project_from_context(context: Context) -> str: @@ -71,8 +89,6 @@ def document_options(context: Context) -> dict[str, str]: options = {"project": project_from_context(context)} coords = context.extensions.get(COORDS_KEY) if isinstance(coords, dict) and coords.get("team"): - from jiuwen_memory.common.errors import ValidationError - if not isinstance(coords["team"], str): raise ValidationError("Team coordinate must be a string") options["team"] = coords["team"] diff --git a/jiuwen_memory/storage/AGENTS.md b/jiuwen_memory/storage/AGENTS.md index 10abe79be..fcf7307e7 100644 --- a/jiuwen_memory/storage/AGENTS.md +++ b/jiuwen_memory/storage/AGENTS.md @@ -76,6 +76,15 @@ ## 行为铁律 +`DomainStore.edit_shared_profile` 是独立可选契约,默认抛能力不支持错误; +CompositeDomainStore 将其委托到 USER.md 的授权集合编辑,普通插件的 +`edit_md_file` 签名保持不变。 + +`_supersede_shadow_for_md` 按正文哈希选有效代表继承元数据,并逐条更新待失效副本; +USER.md 旧块写入 `md_edit_superseded=true`;仅显式传入 API 授权的 `profile_scopes` 时, +才收集同 org/space/user/session 的其他 agent 副本,由影子索引单事务统一失效。`read_md_file` 在组装结果时检查生命周期。 +文件读改的可见性与副本失效契约见 S02 的 `read_md_file` / `edit_md_file`。 + - **显式维护能力**:内置 KV 通过公开 migration_identity、原子 compare_exchange 和声明过的有界 migration_records 迭代支持受控维护,不回退全量 scan。内存 KV 的读写、枚举和 CAS 在实例方法内持有同一把锁,过期清理也在锁内;SQLite 的 insert/CAS 在取得实例锁和数据库写锁后检查状态与到期时间,冲突插入不覆盖。EncryptedKV 的扫描/迁移能力不用于正常读取,保留到期语义且不复活扫描后消失的记录。缺少可靠枚举/CAS 时明确不支持。 - **统一静态加密准入**:`StoreManagerProducer.resolve` 在开关开启时验证完整 diff --git a/jiuwen_memory/storage/domain_store.py b/jiuwen_memory/storage/domain_store.py index 917bf7624..684f9f3a8 100644 --- a/jiuwen_memory/storage/domain_store.py +++ b/jiuwen_memory/storage/domain_store.py @@ -281,6 +281,22 @@ def edit_md_file( 新 unit_id 返回。非文档模式抛 ``ValidationError``。 """ + def edit_shared_profile( + self, + scope: Scope, + old_text: str, + new_text: str, + *, + profile_scopes: list[Scope], + access: StorageAccessContext | None = None, + ) -> list[MemoryUnit]: + """Optionally edit USER.md across explicitly authorized agent scopes. + + Implementations must validate the shared user boundary and update all + old copies atomically. Ordinary edit_md_file plugins remain compatible. + """ + raise UnsupportedStorageCapabilityError("Shared profile editing is not supported") + @abstractmethod def health(self) -> None: ... diff --git a/jiuwen_memory/storage/domain_store_impl/composite_domain_store.py b/jiuwen_memory/storage/domain_store_impl/composite_domain_store.py index 5670019ad..5d4c9c384 100644 --- a/jiuwen_memory/storage/domain_store_impl/composite_domain_store.py +++ b/jiuwen_memory/storage/domain_store_impl/composite_domain_store.py @@ -710,8 +710,28 @@ def read_md_file( for ch, _, _ in blocks: unit_ids.extend(shadow.find_unit_ids_by_content_hash(scope, ch)) rel_path = collective_path or MarkdownStore.resolve_md_path(md_basename, project, team=team) - return [unit for unit in shadow.get_units(scope, unit_ids) - if unit.system_metadata.get(MD_FILENAME_KEY) == rel_path] + visible_units = [] + for unit in shadow.get_units(scope, unit_ids): + if unit.system_metadata.get(MD_FILENAME_KEY) != rel_path: + continue + if unit.lifecycle in (LifecycleState.ACTIVE, LifecycleState.ARCHIVED): + visible_units.append(unit) + return visible_units + + def edit_shared_profile( + self, + scope: Scope, + old_text: str, + new_text: str, + *, + profile_scopes: list[Scope], + access: StorageAccessContext | None = None, + ) -> list[MemoryUnit]: + """Edit the shared profile using the API-authorized scope collection.""" + return self.edit_md_file( + scope, "USER.md", old_text, new_text, access=access, + collective_path="USER.md", profile_scopes=profile_scopes, + ) def edit_md_file( self, @@ -724,6 +744,7 @@ def edit_md_file( access: StorageAccessContext | None = None, team: str = "", collective_path: str = "", + profile_scopes: list[Scope] | None = None, ) -> list[MemoryUnit]: """md 文件级唯一替换 + 继承式 SUPERSEDE 同步 shadow,返回新 unit(F08 §D4/§D5)。 @@ -739,6 +760,18 @@ def edit_md_file( md = self._raw_markdown() shadow = self._raw_shadow_index() rel_path = collective_path or MarkdownStore.resolve_md_path(md_basename, project, team=team) + if profile_scopes is not None: + if rel_path != "USER.md" or scope not in profile_scopes: + raise ValidationError( + "Shared profile edit requires USER.md and its original scope" + ) + home = (scope.org, scope.space, scope.user, scope.session) + for related in profile_scopes: + if (related.org, related.space, related.user, related.session) != home: + raise ValidationError( + "Shared profile edit cannot cross user identity or session" + ) + self._authorize(access, related, StorageAction.ADD, "memory_unit") document_options = {"project": project, **({"team": team} if team else {})} if collective_path: document_options["collective_path"] = collective_path @@ -769,7 +802,7 @@ def edit_md_file( and content_hash(unit.content) == old_hash ): owners.append(unit) - if len(owners) != 1: + if len(owners) != 1 and not (profile_scopes and owners): raise ValidationError( "Collective edit could not identify the original active unit" ) @@ -798,6 +831,7 @@ def edit_md_file( new_unit_ids = self._supersede_shadow_for_md( scope, rel_path, old_full, new_full, shadow, new_titles=new_titles, old_titles=old_titles, + profile_scopes=profile_scopes, ) except Exception: # md 侧补偿:md 已改成 new 态、shadow 同步失败时,回写旧全文让 md 回到 @@ -823,6 +857,7 @@ def _supersede_shadow_for_md( *, new_titles: dict[tuple[str, int], str] | None = None, old_titles: dict[tuple[str, int], str] | None = None, + profile_scopes: list[Scope] | None = None, ) -> list[str]: """继承式 SUPERSEDE 同步 shadow(F08 §D4):md 已改好,只动 shadow 表。 @@ -846,8 +881,15 @@ def _supersede_shadow_for_md( # scope 命中——跨 scope 的 uid 因 scope WHERE 不匹配被省略,实现 scope 隔离)。 old_pairs = shadow.list_units_by_md(scope, rel_path) old_units = shadow.get_units(scope, [uid for uid, _ in old_pairs]) + for related in profile_scopes or []: + if related != scope: + old_units.extend(shadow.get_units(related, [uid for uid, _ in old_pairs])) old_by_hash: dict[str, MemoryUnit] = {} for u in old_units: + if u.scope != scope: + continue + if u.lifecycle not in (LifecycleState.ACTIVE, LifecycleState.ARCHIVED): + continue ch = content_hash(u.segments[0].content if u.segments else "") old_by_hash[ch] = u @@ -857,7 +899,13 @@ def _supersede_shadow_for_md( truly_inserted_hashes = new_full_hashes - old_full_hashes truly_superseded_full_hashes = old_full_hashes - new_full_hashes # 当前 scope 旧 unit 中块消失的(superseded),与 edit 新增的块(inserted)。 - superseded_units = [ + superseded_units = [] + for old_unit in old_units: + if old_unit.lifecycle not in (LifecycleState.ACTIVE, LifecycleState.ARCHIVED): + continue + if content_hash(old_unit.content) in truly_superseded_full_hashes: + superseded_units.append(old_unit) + superseded_representatives = [ u for h, u in old_by_hash.items() if h in truly_superseded_full_hashes ] inserted_blocks = [ @@ -871,11 +919,11 @@ def _supersede_shadow_for_md( # 统一先算齐整批,再一次性落库——把原「逐条 insert + 逐条 update」的 N+M 个 # 独立事务收进 2 个事务,失败中间态从「插一半/标一半」降到「要么全插/全标、 # 要么全没插/全没标」(见下方自回滚)。 - if inserted_blocks and len(superseded_units) == len(inserted_blocks): + if inserted_blocks and len(superseded_representatives) == len(inserted_blocks): # D4.1 对齐:块数一致,按 block_index 一一继承对应旧 unit 全部元数据。 old_block_idx = {h: idx for h, _, idx in old_full} superseded_sorted = sorted( - superseded_units, + superseded_representatives, key=lambda u: old_block_idx.get( content_hash(u.segments[0].content if u.segments else ""), 0 ), @@ -963,6 +1011,8 @@ def _supersede_shadow_for_md( for old in superseded_units: old.lifecycle = LifecycleState.SUPERSEDED old.temporal.t_invalid = now + if rel_path == "USER.md": + old.system_metadata["md_edit_superseded"] = True try: shadow_updates = [*superseded_units, *title_changed_units] if shadow_updates: diff --git a/tests/unit/api/test_local_memory_api_md_ops.py b/tests/unit/api/test_local_memory_api_md_ops.py index 7eb75bd3a..b0380db11 100644 --- a/tests/unit/api/test_local_memory_api_md_ops.py +++ b/tests/unit/api/test_local_memory_api_md_ops.py @@ -46,6 +46,54 @@ SCOPE = Scope(org="acme", user="u1") +@pytest.mark.parametrize("deny_sibling", [False, True]) +def test_shared_profile_edit_authorizes_and_forwards_all_agent_scopes(deny_sibling): + from dataclasses import replace + + scopes = [SCOPE, replace(SCOPE, agent="another")] + originals = [MemoryUnit(id=str(index), scope=scope, segments=[Segment(content="old fact")]) + for index, scope in enumerate(scopes)] + authorized = [] + forwarded = [] + + async def edit(context, *_args): + forwarded.append(context) + return [] + + def authorize(_security, scope, *_args): + authorized.append(scope) + if deny_sibling and scope == scopes[1]: + raise PermissionDeniedError("sibling denied") + + api = SimpleNamespace( + _collective_document_units=lambda *_args: originals, + _authorize=authorize, + _commands=SimpleNamespace(edit_md_file=edit), + _log=lambda *_args, **_kwargs: None, + ) + security = SimpleNamespace(auth=SimpleNamespace(actor="user")) + if deny_sibling: + with pytest.raises(PermissionDeniedError, match="sibling denied"): + MdOpsMixin._edit_shared_document( + api, ["USER.md"], scopes, "USER.md", "old fact", "new fact", security, + ) + assert not forwarded + return + MdOpsMixin._edit_shared_document( + api, ["USER.md"], scopes, "USER.md", "old fact", "new fact", security, + ) + assert authorized == scopes + assert forwarded[0].extensions["_authorized_profile_scopes"] == scopes + + +def test_profile_scope_injection_is_rejected(): + from jiuwen_memory.common.errors import ValidationError + + context = Context(scope=SCOPE, extensions={"_authorized_profile_scopes": [SCOPE]}) + with pytest.raises(ValidationError, match="Invalid document options"): + MdOpsMixin._reject_internal_document_options(context) + + class _FakeEngine: """记录调用;返回带瞬态键的 unit 以验证出口剥离。""" diff --git a/tests/unit/construction/test_evolver_grouped_extract.py b/tests/unit/construction/test_evolver_grouped_extract.py index 1712b5aa5..99c6b1c16 100644 --- a/tests/unit/construction/test_evolver_grouped_extract.py +++ b/tests/unit/construction/test_evolver_grouped_extract.py @@ -144,10 +144,11 @@ def _evolver( llm: LLM | None = None, extractor_fails: bool = False, builder=None, + evolver_type=OrchestratingEvolver, ) -> OrchestratingEvolver: manager = make_storage(kv=kv) index = builder or ForwardIndexBuilder(manager) - return OrchestratingEvolver( + return evolver_type( extractor=_Extractor(derived, fail=extractor_fails), abstractor=_NoopAbstractor(), associator=_NoopAssociator(), @@ -161,6 +162,81 @@ def _evolver( ) +@pytest.mark.parametrize("dedup_enabled", [True, False]) +@pytest.mark.parametrize("evolver_kind", ["orchestrating", "dynamic"]) +def test_extract_cannot_reintroduce_explicitly_edited_profile( + tmp_path, dedup_enabled, evolver_kind, +) -> None: + from jiuwen_memory.construction.evolver import EvolveMode + from jiuwen_memory.construction.evolver_impl.dynamic_evolver import DynamicEvolver + from jiuwen_memory.construction.index_builder_impl.document_index_builder import ( + DocumentIndexBuilder, + ) + from jiuwen_memory.storage.kv_impl.in_memory_kv_store import InMemoryKVStore + from tests.unit.storage.test_composite_domain_store import _build_doc_store, _write_unit + + domain = _build_doc_store(tmp_path) + old = "用户的居住城市是呼伦贝尔。" + new = "用户的居住城市是克拉玛依。" + profile = {"memory_class": "user_profile"} + _write_unit(domain, "old", old, scope=_SCOPE, metadata=profile) + domain.edit_md_file(_SCOPE, "USER.md", old, new) + replay = _unit("replay", old, provenance=["src"]) + replay.system_metadata.update(profile) + fresh = _unit("fresh", "用户喜欢游泳。", provenance=["src"]) + fresh.system_metadata.update(profile) + evolver = _evolver(InMemoryKVStore(), derived=[replay, fresh], hits={}, + builder=DocumentIndexBuilder(domain), + evolver_type=DynamicEvolver if evolver_kind == "dynamic" + else OrchestratingEvolver) + evolver._dedup_extract = dedup_enabled + + result = evolver.evolve([_unit("src", f"将{old}改为{new}")], EvolveMode.EXTRACT) + + assert "replay" not in result.created_ids + assert "fresh" in result.created_ids + assert {unit.content for unit in domain.read_md_file(_SCOPE, "USER.md")} == { + new, "用户喜欢游泳。", + } + # Explicit restoration is still allowed, and is not a historical duplicate. + _write_unit(domain, "restored", old, scope=_SCOPE, metadata=profile) + assert "restored" in {unit.id for unit in domain.read_md_file(_SCOPE, "USER.md")} + assert evolver._filter_edited_profiles([replay]) == [replay] + + +@pytest.mark.parametrize("axis", ["org", "space", "user", "agent", "session"]) +def test_edited_profile_does_not_block_another_scope(tmp_path, axis) -> None: + from dataclasses import replace + + from jiuwen_memory.construction.evolver import EvolveMode + from jiuwen_memory.construction.index_builder_impl.document_index_builder import ( + DocumentIndexBuilder, + ) + from jiuwen_memory.storage.kv_impl.in_memory_kv_store import InMemoryKVStore + from tests.unit.storage.test_composite_domain_store import _build_doc_store, _write_unit + + domain = _build_doc_store(tmp_path) + profile = {"memory_class": "user_profile"} + _write_unit(domain, "old", "用户居住呼伦贝尔。", scope=_SCOPE, metadata=profile) + domain.edit_md_file(_SCOPE, "USER.md", "呼伦贝尔", "克拉玛依") + other = replace(_SCOPE, **{axis: "another"}) + candidate = _unit("other", "用户居住呼伦贝尔。", provenance=["source"]) + candidate.scope = other + candidate.system_metadata.update(profile) + source = _unit("source", candidate.content) + source.scope = other + evolver = _evolver(InMemoryKVStore(), derived=[candidate], hits={}, + builder=DocumentIndexBuilder(domain)) + + result = evolver.evolve([source], EvolveMode.EXTRACT) + + if axis == "agent": + assert "other" not in result.created_ids + else: + assert "other" in result.created_ids + assert domain.get(_SCOPE, ["old"])[0].lifecycle.value == "superseded" + + def test_sources_cover_add_and_update() -> None: from jiuwen_memory.storage.kv_impl.in_memory_kv_store import InMemoryKVStore diff --git a/tests/unit/control/test_document_edit_contract.py b/tests/unit/control/test_document_edit_contract.py new file mode 100644 index 000000000..88b27a673 --- /dev/null +++ b/tests/unit/control/test_document_edit_contract.py @@ -0,0 +1,89 @@ +"""Engine document edits preserve legacy plugins and use the optional shared contract.""" + +import asyncio +from types import SimpleNamespace + +import pytest + +from jiuwen_memory.common.errors import UnsupportedStorageCapabilityError +from jiuwen_memory.common.type_def import Context, Scope +from jiuwen_memory.control.engine_impl.agent_engine import AgentEngine +from jiuwen_memory.control.engine_impl.cloud_engine import CloudEngine +from jiuwen_memory.storage.domain_store import DomainStore + +pytestmark = pytest.mark.unit + + +class LegacyDocumentStore: + """Implement exactly the original document editing signature.""" + + edit_shared_profile = DomainStore.edit_shared_profile + + def __init__(self): + self.calls = [] + + def edit_md_file(self, scope, filename, old_text, new_text, *, project="", access=None, + team=""): + self.calls.append((scope, filename, old_text, new_text, project)) + return [] + + +@pytest.mark.parametrize("engine_type", [AgentEngine, CloudEngine]) +@pytest.mark.parametrize("filename", ["USER.md", "MEMORY.md"]) +def test_ordinary_edits_keep_original_plugin_signature(engine_type, filename): + domain = LegacyDocumentStore() + engine = SimpleNamespace(_domain_store=domain) + context = Context(scope=Scope(org="org", user="user")) + + result = asyncio.run(engine_type.edit_md_file(engine, context, filename, "old", "new")) + + assert result == [] + assert domain.calls == [(context.scope, filename, "old", "new", "")] + + +@pytest.mark.parametrize("engine_type", [AgentEngine, CloudEngine]) +def test_unsupported_shared_edit_fails_explicitly_before_writing(engine_type): + domain = LegacyDocumentStore() + engine = SimpleNamespace(_domain_store=domain) + scope = Scope(org="org", user="user") + context = Context(scope=scope, extensions={"_authorized_profile_scopes": [scope]}) + + with pytest.raises(UnsupportedStorageCapabilityError, match="Shared profile"): + asyncio.run(engine_type.edit_md_file(engine, context, "USER.md", "old", "new")) + + assert not domain.calls + + +@pytest.mark.parametrize("engine_type", [AgentEngine, CloudEngine]) +def test_shared_edits_use_optional_contract(engine_type, tmp_path): + from tests.unit.storage.test_composite_domain_store import _build_doc_store, _write_unit + + domain = _build_doc_store(tmp_path) + scope = Scope(org="org", user="user") + _write_unit(domain, "old", "old fact", scope=scope, + metadata={"memory_class": "user_profile"}) + context = Context(scope=scope, extensions={"_authorized_profile_scopes": [scope]}) + engine = SimpleNamespace(_domain_store=domain) + + result = asyncio.run(engine_type.edit_md_file(engine, context, "USER.md", "old", "new")) + + assert [unit.content for unit in result] == ["new fact"] + + +def test_routing_domain_forwards_shared_edit_to_active_plugin(): + from jiuwen_memory.config.routing import RoutingDomainStore + + calls = [] + + def edit_shared(scope, old, new, *, profile_scopes, access=None): + calls.append((scope, old, new, profile_scopes, access)) + return [] + + manager = SimpleNamespace(domain_store=lambda _name: SimpleNamespace( + edit_shared_profile=edit_shared, + )) + router = RoutingDomainStore(SimpleNamespace(get=lambda: manager)) + scope = Scope(org="org", user="user") + + assert router.edit_shared_profile(scope, "old", "new", profile_scopes=[scope]) == [] + assert calls == [(scope, "old", "new", [scope], None)] diff --git a/tests/unit/storage/test_composite_domain_store.py b/tests/unit/storage/test_composite_domain_store.py index 1d7c40ca9..bbd2507a1 100644 --- a/tests/unit/storage/test_composite_domain_store.py +++ b/tests/unit/storage/test_composite_domain_store.py @@ -184,6 +184,117 @@ def test_read_md_file_rejects_non_document_mode(tmp_path) -> None: # -- edit_md_file:继承式 SUPERSEDE(F08 §D4)------------------------------- # +def test_profile_read_excludes_superseded_version_when_body_is_restored(tmp_path) -> None: + ds = _build_doc_store(tmp_path) + metadata = {MEMORY_CLASS_KEY: "user_profile"} + _write_unit(ds, "old", "用户的居住城市是呼伦贝尔。", metadata=metadata) + ds.edit_md_file(SCOPE, "USER.md", "呼伦贝尔", "克拉玛依") + _write_unit(ds, "restored", "用户的居住城市是呼伦贝尔。", metadata=metadata) + + units = ds.read_md_file(SCOPE, "USER.md") + assert {unit.content for unit in units} == { + "用户的居住城市是呼伦贝尔。", "用户的居住城市是克拉玛依。", + } + assert "old" not in {unit.id for unit in units} + + +def test_profile_edit_supersedes_all_duplicate_versions_in_own_scope(tmp_path) -> None: + ds = _build_doc_store(tmp_path) + metadata = {MEMORY_CLASS_KEY: "user_profile", MD_TITLE_KEY: "居住城市"} + _write_unit(ds, "old1", "用户的居住城市是呼伦贝尔。", metadata=metadata) + duplicate = MemoryUnit( + id="old2", scope=SCOPE, segments=[Segment(content="用户的居住城市是呼伦贝尔。")], + system_metadata={**metadata, "md_filename": "USER.md"}, + ) + ds._raw_shadow_index().insert_units(SCOPE, [duplicate]) + other = Scope(org="acme", user="u2") + other_unit = MemoryUnit(id="other", scope=other, segments=[Segment(content=duplicate.content)], + system_metadata={**metadata, "md_filename": "USER.md"}) + ds._raw_shadow_index().insert_units(other, [other_unit]) + + (updated,) = ds.edit_md_file(SCOPE, "USER.md", "呼伦贝尔", "克拉玛依") + + assert updated.supersedes in {"old1", "old2"} + assert updated.system_metadata[MD_TITLE_KEY] == "居住城市" + assert all(unit.lifecycle is LifecycleState.SUPERSEDED + for unit in ds.get(SCOPE, ["old1", "old2"])) + assert all(unit.temporal.t_invalid is not None + for unit in ds.get(SCOPE, ["old1", "old2"])) + assert ds.get(other, ["other"])[0].lifecycle is LifecycleState.ACTIVE + + +def test_profile_edit_inherits_active_metadata_instead_of_later_history(tmp_path) -> None: + from datetime import UTC, datetime + + ds = _build_doc_store(tmp_path) + metadata = {MEMORY_CLASS_KEY: "user_profile", MD_TITLE_KEY: "current"} + _write_unit(ds, "active", "用户住在上海。", metadata=metadata) + historical = MemoryUnit( + id="historical", scope=SCOPE, segments=[Segment(content="用户住在上海。")], + lifecycle=LifecycleState.SUPERSEDED, + system_metadata={**metadata, MD_TITLE_KEY: "stale", "md_filename": "USER.md"}, + ) + historical.temporal.t_invalid = datetime.now(UTC) + ds._raw_shadow_index().insert_units(SCOPE, [historical]) + + (updated,) = ds.edit_md_file(SCOPE, "USER.md", "上海", "杭州") + + assert updated.supersedes == "active" + assert updated.system_metadata[MD_TITLE_KEY] == "current" + + +@pytest.mark.parametrize("fail_update", [False, True]) +def test_authorized_profile_edit_updates_all_agents_atomically(tmp_path, monkeypatch, fail_update): + from dataclasses import replace + + ds = _build_doc_store(tmp_path) + sibling = replace(SCOPE, agent="a2") + metadata = {MEMORY_CLASS_KEY: "user_profile", "md_filename": "USER.md"} + _write_unit(ds, "a1", "用户住在上海。", metadata=metadata) + shadow = ds._raw_shadow_index() + shadow.insert_units(sibling, [MemoryUnit( + id="a2", scope=sibling, segments=[Segment(content="用户住在上海。")], + system_metadata=metadata, + )]) + if fail_update: + original = shadow._store._update_one + + def fail_second(conn, unit): + if unit.id == "a2": + raise RuntimeError("second agent update failed") + return original(conn, unit) + + monkeypatch.setattr(shadow._store, "_update_one", fail_second) + with pytest.raises(RuntimeError, match="second agent"): + ds.edit_md_file(SCOPE, "USER.md", "上海", "杭州", + collective_path="USER.md", profile_scopes=[SCOPE, sibling]) + assert shadow.get_units(SCOPE, ["a1"])[0].lifecycle is LifecycleState.ACTIVE + assert shadow.get_units(sibling, ["a2"])[0].lifecycle is LifecycleState.ACTIVE + assert "上海" in ds._raw_markdown().read_content(SCOPE, "USER.md") + assert len(shadow.list_units_by_md(SCOPE, "USER.md")) == 2 + return + + ds.edit_md_file(SCOPE, "USER.md", "上海", "杭州", + collective_path="USER.md", profile_scopes=[SCOPE, sibling]) + for scope, uid in ((SCOPE, "a1"), (sibling, "a2")): + old = shadow.get_units(scope, [uid])[0] + assert old.lifecycle is LifecycleState.SUPERSEDED + assert old.system_metadata["md_edit_superseded"] is True + + +@pytest.mark.parametrize("axis", ["org", "space", "user", "session"]) +def test_shared_profile_edit_rejects_unrelated_scope(tmp_path, axis): + from dataclasses import replace + + ds = _build_doc_store(tmp_path) + _write_unit(ds, "old", "用户住在上海。", metadata={MEMORY_CLASS_KEY: "user_profile"}) + unrelated = replace(SCOPE, **{axis: "another"}) + with pytest.raises(ValidationError, match="cannot cross"): + ds.edit_md_file(SCOPE, "USER.md", "上海", "杭州", + profile_scopes=[SCOPE, unrelated]) + assert ds.get(SCOPE, ["old"])[0].lifecycle is LifecycleState.ACTIVE + + @pytest.mark.parametrize("memory_class,filename", [ ("user_profile", "USER.md"), ("long_term_memory", "MEMORY.md"), ])