Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion docs/specs/S02-memory-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |

Expand Down Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions docs/specs/S06-storage.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 不额外传实现私有参数。
3 changes: 3 additions & 0 deletions jiuwen_memory/api/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` 配置检查辅助,
Expand Down
10 changes: 9 additions & 1 deletion jiuwen_memory/api/memory_api_impl/md_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -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})
Expand All @@ -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)
Expand Down
3 changes: 3 additions & 0 deletions jiuwen_memory/config/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@

负责装配配置解析/合并,以及运行时晚绑定配置来源 `ConfigSource`。

RoutingDomainStore 的共享画像编辑通过 `edit_shared_profile` 委托当前活动数据面;
活动插件未实现时保留可选契约的能力不支持错误,不回退普通编辑。

## 模块地图

| 文件/目录 | 职责 |
Expand Down
14 changes: 14 additions & 0 deletions jiuwen_memory/config/routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down
10 changes: 8 additions & 2 deletions jiuwen_memory/construction/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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→复用上述整理归纳流程一次
Expand Down Expand Up @@ -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.<key>` 和 `user_metadata.<key>`。
Expand Down
4 changes: 4 additions & 0 deletions jiuwen_memory/construction/evolver_impl/dynamic_evolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
53 changes: 53 additions & 0 deletions jiuwen_memory/construction/evolver_impl/orchestrating_evolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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:
Expand Down
4 changes: 4 additions & 0 deletions jiuwen_memory/control/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` 在授权回调返回的完整条目集合上筛选来源、
Expand Down
7 changes: 4 additions & 3 deletions jiuwen_memory/control/engine_impl/agent_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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:
Expand Down
7 changes: 4 additions & 3 deletions jiuwen_memory/control/engine_impl/cloud_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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:
Expand Down
20 changes: 18 additions & 2 deletions jiuwen_memory/control/engine_impl/doc_mode_support.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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"]
Expand Down
9 changes: 9 additions & 0 deletions jiuwen_memory/storage/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` 在开关开启时验证完整
Expand Down
Loading
Loading