Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

fix(server): restore flash identity and memory fallback

Nephamaster1d771c555a7d
diff --git a/jiuwenswarm/agents/harness/flash/tools/flash_memory_tool.py b/jiuwenswarm/agents/harness/flash/tools/flash_memory_tool.py
index f0d71c0334..0f803f6097 100644
--- a/jiuwenswarm/agents/harness/flash/tools/flash_memory_tool.py
+++ b/jiuwenswarm/agents/harness/flash/tools/flash_memory_tool.py
@@ -39,8 +39,8 @@ def _unified_memory_description(language: str) -> str:
"[mode=write] Write content to path; append=true to append instead of overwrite.\n"
"[mode=edit] Replace old_text with new_text in path (old_text must be unique in the file).\n"
"[mode=read] Read memory file with offset/limit pagination.\n"
- "[mode=search] Semantic vector search by query. Requires embedding config; "
- "returns disabled if not configured.\n\n"
+ "[mode=search] Search by query using keywords and, when embedding is configured, "
+ "semantic similarity.\n\n"
"[Path security] Paths must start with memory/ (e.g. memory/USER.md, "
"memory/daily_memory/2026-09-10.md). Paths outside this prefix are rejected.\n\n"
"[Read-only mode] In cron/heartbeat/group-chat digital-avatar mode, "
@@ -50,13 +50,13 @@ def _unified_memory_description(language: str) -> str:
"and prevents traversal, the general file tools do not."
)
return (
- "统一记忆工具(跨会话持久化)。用 mode 选写、编辑、读取或语义检索。\n\n"
+ "统一记忆工具(跨会话持久化)。用 mode 选写、编辑、读取或检索。\n\n"
"【存储】memory/USER.md(用户画像、稳定偏好)、memory/MEMORY.md(长期事实、重要决策)、"
"memory/daily_memory/YYYY-MM-DD.md(每日记录、任务进展)。\n\n"
"【mode=write】把 content 写入 path;append=true 追加而非覆盖。\n"
"【mode=edit】在 path 文件中将 old_text 精确替换为 new_text(old_text 须在该文件中唯一出现)。\n"
"【mode=read】分页读取记忆文件(offset/limit)。\n"
- "【mode=search】按 query 语义检索记忆(向量相似度)。依赖 embedding 配置;未配置时返回 disabled。\n\n"
+ "【mode=search】按 query 检索记忆;支持关键词检索,配置 embedding 后还可进行语义检索。\n\n"
"【路径安全】path 必须以 memory/ 开头(如 memory/USER.md、memory/daily_memory/2026-09-10.md)。"
"越界路径会被拒绝。\n\n"
"【只读态】定时任务/心跳/群聊数字分身模式下,write/edit 被拒(read/search 可用)。\n\n"
@@ -79,8 +79,8 @@ def _unified_memory_input_params(language: str) -> dict:
"type": "string",
"enum": ["write", "edit", "read", "search"],
"description": d(
- "操作模式:write=写入/追加;edit=精确替换;read=分页读取;search=语义检索",
- "write=write/append; edit=exact replace; read=paginated read; search=semantic search",
+ "操作模式:write=写入/追加;edit=精确替换;read=分页读取;search=检索",
+ "write=write/append; edit=exact replace; read=paginated read; search=search",
),
},
"path": {
@@ -252,7 +252,7 @@ class FlashMemoryTool(Tool):
success=False,
error=str(
result.get("error")
- or "Semantic search is disabled (embedding not configured). "
+ or "Memory search is unavailable. "
"Use memory(mode=read) or read_file/grep to find specific content."
),
)
diff --git a/jiuwenswarm/server/docs/bugfix/B_03_flash-identity-memory.md b/jiuwenswarm/server/docs/bugfix/B_03_flash-identity-memory.md
new file mode 100644
index 0000000000..399805b0db
--- /dev/null
+++ b/jiuwenswarm/server/docs/bugfix/B_03_flash-identity-memory.md
@@ -0,0 +1,36 @@
+# Flash 未注入工作区身份且缺少 embedding 时无法使用内置记忆
+
+## 元信息
+
+| 项 | 值 |
+|---|---|
+| 日期 | 2026-10-30 |
+| 范围 | Flash 适配器、Flash 记忆工具说明及对应测试 |
+| 关联 spec | [S_03 runtime-agent-management](../specs/S_03_runtime-agent-management.md) |
+
+## 现象与根因
+
+Flash 默认不会把工作区的 `USER.md` 等身份文件带入模型输入:请求准备未创建身份上下文组件,动态组件清理也不保留它。组件读取的是当前 agent 工作区,与外部记忆和云画像是不同来源。
+
+另一个独立问题是:启用内置记忆但没有完整 embedding 配置时,Flash 仍以空值构造必填配置,校验失败后放弃创建整个记忆工具。MaaS 未配置独立 embedding 时,上游有意不复用聊天地址,下游应允许 SDK 的关键词检索路径工作。
+
+agent-core 的共享索引还存在必要的配套缺陷:索引重开时将自身创建的 `tokenize='trigram'` 表误认为旧表并清空,但迁移标记又使重建被跳过。于是无 embedding 场景下即使首次能够关键词检索,重新打开索引后仍会返回空结果。该问题也影响其他使用同一 SDK 索引的模式。
+
+## 决策
+
+- Flash 在请求准备时复用 SDK 现有的上下文装配组件,并在其保留清单中保留该组件;注册时传入禁用工具和渐进式工具可见列表。
+- 串行化首次挂载,注册失败时回滚部分注册;热重载保留已有组件,避免 SDK 对同一个组件重复注册回调,并在后续请求绑定当前工作区及文件操作对象。
+- 内置记忆在 embedding 地址、模型或凭据缺失时传入无有效凭据的配置,让 SDK 使用已有关键词索引;完整配置仍原样传递。Flash 工具说明同步表述关键词与语义检索。
+- 本次不修改 agent-core。Flash 仅传递无有效 embedding 的配置,索引的持久化、迁移与恢复继续由 SDK 负责。
+
+## 拒绝的方案
+
+- 只增加保留清单:首次请求仍不会创建身份上下文组件。
+- 调用普通 agent 的完整装配流程:会把本次身份修复无关的动态组件带入 Flash。
+- 把 MaaS 聊天网关当作 embedding 服务:上游已明确区分两者,聊天接口不一定提供 embedding。
+
+## 验证与边界
+
+`tests/unit_tests/agentserver/test_flash_identity_memory.py` 验证合成工作区身份在真实 SDK 模型调用边界可见、跨工作区隔离、重载后回调不重复;同时验证无 embedding 的真实 SQLite 关键词写入、检索与重开,以及与模拟外部记忆和画像服务共存。未修改 SDK 下,相关 Flash 定向回归为 **115 passed、1 failed**;锁定 SDK 下关键组合为 **24 passed、1 failed**。两者均在索引重开后的检索断言失败,该用例继续保留,不能把关键词记忆的持久可用性视为通过。模型及远端 HTTP 为模拟,未执行真实 OfficeAce 服务或 Windows 实机验收。
+
+普通 agent 的无 embedding 构造入口仍存在相同问题,本次未修改;用户自定义的任意身份文件也未加入自动装配清单。SDK 的索引重开缺陷尚未修复,因而相关组合测试仍失败,也可能阻塞包含该测试的 CI。现场安装包版本和故障请求的完整模型输入尚未取得,不能仅凭隔离测试宣布原现场问题闭环。
diff --git a/jiuwenswarm/server/docs/specs/S_03_runtime-agent-management.md b/jiuwenswarm/server/docs/specs/S_03_runtime-agent-management.md
index 97e9e9a3d9..4b8888e541 100644
--- a/jiuwenswarm/server/docs/specs/S_03_runtime-agent-management.md
+++ b/jiuwenswarm/server/docs/specs/S_03_runtime-agent-management.md
@@ -7,7 +7,7 @@
| 类型 | spec |
| 编号 / slug | S_03 / runtime-agent-management |
| 关联模块 | jiuwenswarm/server/runtime/{agent_manager.py, tenant_agent_pool.py, agent_warm_pool.py, agent_adapter/, a2ui/, debug_trace/, session/, skill/, workspace/, agent_config_service.py, prewarm.py, proactive_adapter.py, team_binding_store.py, team_entity_store.py, team_snapshot_refresh.py} |
-| 最近一次修订日期 | 2026-10-26 |
+| 最近一次修订日期 | 2026-10-30 |
| 关联 feature | 暂无 |
## 范围 / 边界
@@ -46,6 +46,7 @@
9. **AgentManager 单进程单默认实例**:非 enterprise 进程内至多一个裸 AgentManager(由 AgentWebSocketServer 构造),不要在其他模块私自 AgentManager()。
10. **企业版冷加载 best-effort**:每个 `reload_*_from_gateway_db` 调用失败只记 warning,不阻断 AgentServer 启动——用户配置 PVC 缺表或缺字段不应让进程起不来。
11. **code.normal/plan 首建与重载共享工具懒加载策略**:首次创建的 None/空白 sub_mode 默认 normal;后续 `create_instance(sub_mode=None)` 沿用保存的 profile,并把有效 sub_mode 传入 rail 装配及后续 session 子 adapter,显式 normal/空白可切回 normal。首建按入参规范化后的 sub_mode 排队并显式传给 builder,配置热重载未传该参数时使用 `_session_instance_sub_mode`;仅 normal/plan 装配 `ProgressiveToolRail`。code.team 对齐普通 team,首建和完整/部分重载均不新增该 rail;历史误挂实例在 configure 成功后注销。单 agent 复用 `react.tool_lazy_load` 的开关、模型白名单及请求级 MCP allowlist,配置缺省重载保持既有 rail;编码记忆、LSP、模式切换与计划审批工具保持 eager,最终可见性仍受模式、技能门控及 `disabled_tools` 约束。一次 code 挂载仅记录一条带 `[JiuwenSwarmCodeAdapter]` 和规范化 sub_mode 的适配器日志。普通 agent/team 的装配、日志及重载策略不因此改变。
+12. **Flash 身份文件与内置记忆**:请求准备须保留并装配当前工作区的身份上下文,同时遵守禁用工具与渐进式工具可见范围;不同工作区不能共享身份内容。开启内置记忆时,完整 embedding 配置照常使用;配置缺失时不得因此丢失整个记忆工具,按 SDK 的无 embedding 接口进入关键词检索路径。当前 SDK 的索引重开仍有已知缺陷,不能据此认定该检索跨重开可用。
## 接口契约
@@ -167,6 +168,7 @@ UsageReconciler: start_usage_reconciler()(启动周期回收)
- **新增 agent_adapter 接口** → 确认归哪一路(deep/code/flash)→ AgentWebSocketServer._resolve_adapter 里加分支 → 默认路径 fallback 里跑双接口一致性测试。
- **改 code 工具装配或懒加载策略** → 验证首次模型调用已过滤大量 MCP schema、编码工具仍可见、deferred 工具可搜索调用;确认关闭开关、模型白名单、禁用工具及热重载替换行为。
+- **改 Flash 身份上下文或内置记忆装配** → 检查首次与连续请求、重载、工作区隔离和工具可见性;分别验证完整及缺失 embedding 配置下的记忆工具行为。
- **改 AgentWarmPool WarmKey 结构** → 同步 sync() 里的重建条件 → 排除 acp/a2a 分支不被意外打破 → 跑预热池一致性测试。
- **改 prewarm 阶段** → 确认阶段 3 仍是独立 fire-and-forget,不被阶段 1/2 兜底 await 阻塞 → mock_model 默认 True 不消耗 token。
- **增删 skilldev 阶段** → pipeline.py 编排顺序同步 → service.py 的 stage 实例化清单同步 → 阶段 base.py 接口签名不变。
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_flash.py b/jiuwenswarm/server/runtime/agent_adapter/interface_flash.py
index 6aa043ca76..d7c4261cde 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_flash.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_flash.py
@@ -43,7 +43,7 @@ flash 行为由类常量定义:
- :meth:`_update_rails_for_mode` — 每请求调用(interface_deep.py:10596)。父类会调
``_update_agent_rails()`` 动态注册 context_assemble / memory 等 rail,绕过
``_instantiate_rails`` 的白名单裁剪——flash 覆盖此方法不调 ``_update_agent_rails()``,
- 只卸载白名单外的动态 rail,闭合白名单。
+ 单独装配身份上下文和记忆,并卸载白名单外的动态 rail。
- :meth:`try_start_dreaming` / :meth:`try_stop_dreaming` — no-op。flash 是「无自演进」
profile,memory dreaming(被动记忆巩固)属自演进范畴,不挂。
@@ -72,6 +72,7 @@ skill_credential / skill_active_state / disabled_tools)全部在 keep 白名
from __future__ import annotations
+import asyncio
import copy
import hashlib
import logging
@@ -138,6 +139,7 @@ from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (
_CRON_TOOL_NAMES,
_DEFAULT_PROGRESSIVE_EAGER_TOOLS,
_RailBuildInfo,
+ _build_context_assemble_rail,
_resolve_instance_config_base,
acp_chat,
create_vision_tools,
@@ -275,6 +277,8 @@ class JiuwenSwarmFlashAdapter(JiuWenSwarmDeepAdapter):
# 这两个,本仓决策保留)。
"_skill_active_state_rail",
"_skill_authorization_rail",
+ # Workspace identity files are assembled on the request path.
+ "_context_assemble_rail",
# _memory_rail: FlashMemoryRail(flash override,统一 memory 工具)挂在
# 动态挂载路径上,进 keep 才不会被 _drop_non_whitelist_dynamic_rails
# 卸载;闸门是 modes.agent.memory.enabled(flash 记忆档归一 agent)。
@@ -319,6 +323,8 @@ class JiuwenSwarmFlashAdapter(JiuWenSwarmDeepAdapter):
) -> None:
super().__init__(workspace_dir=workspace_dir, agent_id=agent_id, service_id=service_id)
self._flash_startup_preparations = {}
+ self._flash_context_rail_lock = asyncio.Lock()
+ self._flash_context_agent_sysop = None
@contextmanager
def _prepare_flash_startup(self, request=None):
@@ -905,6 +911,9 @@ class JiuwenSwarmFlashAdapter(JiuWenSwarmDeepAdapter):
def _get_current_agent_rails(self, config, config_base):
rails, removed = super()._get_current_agent_rails(config, config_base)
+ # The SDK retains callbacks when reconfiguring with the same rail
+ # instance, so requeueing it would register its callbacks again.
+ rails = [rail for rail in rails if rail is not self._context_assemble_rail]
old = getattr(self, "_flash_skill_selection_rail", None)
selection = self._build_flash_skill_selection_rail(config_base)
if selection is not None:
@@ -926,9 +935,10 @@ class JiuwenSwarmFlashAdapter(JiuWenSwarmDeepAdapter):
``_memory_rail`` / ``_external_memory_rail`` 等 rail——这些大多不在 flash 白名单
内,却会绕过 ``_instantiate_rails`` 的冷启动裁剪被挂上,使白名单形同虚设。
- flash 覆盖此方法:**不调** ``_update_agent_rails()``,只做三件事——
+ flash 覆盖此方法:**不调** ``_update_agent_rails()``,仅装配身份上下文和记忆,
+ 并卸载白名单外的动态 rail——
1. 记 ``_last_mode``(父类首行本就做);
- 2. 记忆 rail:flash 的统一 memory 工具(FlashMemoryRail)走动态挂载路径,
+ 2. 身份上下文及记忆 rail:flash 的统一 memory 工具(FlashMemoryRail)走动态挂载路径,
这里按归一后的 agent 档调 ``_handle_memory_rail_by_config``(闸门
``modes.agent.memory.enabled``,未开启则卸载);``_memory_rail`` 在 keep
白名单内,不会被后续卸载步骤误删。外接记忆与云画像沿用父类的
@@ -946,12 +956,68 @@ class JiuwenSwarmFlashAdapter(JiuWenSwarmDeepAdapter):
重建」的 churn(参见 PR6431 review #4 修正)。
"""
self._last_mode = mode
+ await self._ensure_flash_context_rail()
await self._handle_memory_rail_by_config("agent")
await self._handle_external_memory_rail_by_config()
await self._handle_office_ace_user_profile_rail_by_config()
await self._drop_non_whitelist_dynamic_rails()
self._refresh_rail_observability_snapshot()
+ async def _ensure_flash_context_rail(self) -> None:
+ """Attach workspace identity without enabling the full agent profile."""
+ async with self._flash_context_rail_lock:
+ if self._context_assemble_rail is not None:
+ is_registered = getattr(self._instance, "is_registered_rail", None)
+ is_pending = getattr(self._instance, "is_pending_rail", None)
+ if not callable(is_registered) or is_registered(self._context_assemble_rail) or (
+ callable(is_pending) and is_pending(self._context_assemble_rail)
+ ):
+ self._sync_flash_context_bindings()
+ return
+ self._context_assemble_rail = None
+ self._context_assemble_mode = None
+ disabled = getattr(self._disabled_tools_rail, "_disabled_tools", None)
+ if disabled:
+ disabled = [str(name).strip() for name in disabled if str(name).strip()]
+ else:
+ disabled = resolve_string_or_list_config((self._config_cache or {}).get("disabled_tools"))
+ progressive = self._progressive_tool_rail
+ rail = _build_context_assemble_rail(
+ disabled_tools=disabled or None,
+ tool_name_allowlist=list(progressive.eager_tools) if progressive is not None else None,
+ )
+ if rail is None:
+ return
+ try:
+ await self._instance.register_rail(rail)
+ except BaseException:
+ # Registration may have installed some callbacks before failing.
+ try:
+ await self._instance.unregister_rail(rail)
+ except Exception:
+ logger.warning("[FlashAdapter] context rail rollback failed", exc_info=True)
+ raise
+ self._context_assemble_rail = rail
+ self._context_assemble_mode = "agent"
+ config = getattr(self._instance, "deep_config", None)
+ self._flash_context_agent_sysop = getattr(config, "sys_operation", None)
+ self._rebind_late_read_rails_to_local()
+
+ def _sync_flash_context_bindings(self) -> None:
+ """Refresh retained context bindings after an agent reconfiguration."""
+ rail = self._context_assemble_rail
+ config = getattr(self._instance, "deep_config", None)
+ if rail is None or config is None:
+ return
+ workspace = getattr(config, "workspace", None)
+ sysop = getattr(config, "sys_operation", None)
+ if rail.workspace is workspace and self._flash_context_agent_sysop is sysop:
+ return
+ rail.set_workspace(workspace)
+ rail.set_sys_operation(sysop)
+ self._flash_context_agent_sysop = sysop
+ self._rebind_late_read_rails_to_local()
+
async def try_start_dreaming(self, busy_checker=None) -> None:
"""no-op:flash 不启 memory dreaming.
@@ -1058,9 +1124,16 @@ class JiuwenSwarmFlashAdapter(JiuWenSwarmDeepAdapter):
has_model = embed_config.get("model")
if not all([has_api_key, has_base_url, has_model]):
logger.warning(
- "[JiuwenSwarmFlashAdapter] FlashMemoryRail create failed: "
- "No available embedding config"
+ "[JiuwenSwarmFlashAdapter] Incomplete embedding config; "
+ "FlashMemoryRail will attempt keyword search"
)
+ # The SDK uses an absent key to select its no-embedding provider.
+ # Keep the required string fields valid without using partial credentials.
+ embed_config = {
+ "model": has_model or "",
+ "base_url": has_base_url or "",
+ "api_key": None,
+ }
self._is_proactive_memory = is_proactive_memory(mode, config)
memory_rail = FlashMemoryRail(
embedding_config=EmbeddingConfig(
diff --git a/tests/unit_tests/agentserver/test_flash_adapter_rails.py b/tests/unit_tests/agentserver/test_flash_adapter_rails.py
index 676d2a74d1..5f36cb7ec4 100644
--- a/tests/unit_tests/agentserver/test_flash_adapter_rails.py
+++ b/tests/unit_tests/agentserver/test_flash_adapter_rails.py
@@ -10,7 +10,7 @@ Covers the review findings on PR6431:
``react.disabled_tools`` policy as agent / code.
- #4 dynamic registration via ``_update_rails_for_mode`` must not penetrate the
whitelist: rails outside ``_FLASH_RAIL_KEEP`` ∪ ``_PROFILE_PROTECTED_RAILS``
- (e.g. ``_context_assemble_rail``, ``_memory_rail``) are unregistered. The
+ are unregistered; workspace context and memory rails are retained. The
dead ``_ask_user_rail`` keep entry was removed (gated by ``agent`` prefix at
build time, never built for flash).
- #6 flash does not start memory dreaming (``try_start_dreaming`` /
@@ -81,7 +81,7 @@ def test_keep_whitelist_keeps_protected_and_drops_others():
_info("_skill_authorization_rail"), # in KEEP(本仓决策:授权门禁保留)
_info("_memory_rail"), # in KEEP(本仓决策:统一 memory 工具)
_info("_ask_user_rail"), # in KEEP (interactive dynamic mount)
- _info("_context_assemble_rail"), # neither (dynamic reg target)
+ _info("_context_assemble_rail"), # in KEEP (workspace identity)
_info("_external_memory_rail"), # in KEEP (config-driven)
_info("_office_ace_user_profile_rail"), # in KEEP (config-driven)
_info("_symphony_orchestration_rail"), # neither
@@ -100,6 +100,7 @@ def test_keep_whitelist_keeps_protected_and_drops_others():
"_skill_active_state_rail",
"_skill_authorization_rail",
"_memory_rail",
+ "_context_assemble_rail",
"_external_memory_rail",
"_office_ace_user_profile_rail",
"_ask_user_rail",
@@ -178,10 +179,7 @@ async def test_update_rails_for_mode_drops_non_whitelist_dynamic_rails():
# whitelisted (#4 corrected / unified-memory design), so the drop skips
# them; ask_user's lifecycle is owned by _set_user_interaction_enabled,
# memory's by _handle_memory_rail_by_config via the agent-profile gate.)
- leaked = {
- "_context_assemble_rail": SimpleNamespace(name="context_assemble"),
- "_skill_create_rail": SimpleNamespace(name="skill_create"),
- }
+ leaked = {"_skill_create_rail": SimpleNamespace(name="skill_create")}
for attr, rail in leaked.items():
setattr(adapter, attr, rail)
@@ -191,6 +189,7 @@ async def test_update_rails_for_mode_drops_non_whitelist_dynamic_rails():
# _ask_user_rail (kept, so dropped-skip applies to it too) and _memory_rail
# (kept; flash mounts the unified memory rail itself before the drop).
adapter._task_planning_rail = SimpleNamespace(name="keep-me")
+ adapter._context_assemble_rail = SimpleNamespace(name="keep-context")
adapter._context_processor_rail = SimpleNamespace(name="keep-me-2")
adapter._skill_rail = SimpleNamespace(name="keep-me-skill")
adapter._ask_user_rail = SimpleNamespace(name="keep-me-ask-user")
@@ -213,6 +212,7 @@ async def test_update_rails_for_mode_drops_non_whitelist_dynamic_rails():
for rail in leaked.values():
assert unregistered.count(rail) == 1
assert adapter._task_planning_rail is not None
+ assert adapter._context_assemble_rail is not None
assert adapter._context_processor_rail is not None
assert adapter._skill_rail is not None
assert adapter._ask_user_rail is not None # kept, not churned
@@ -228,7 +228,7 @@ async def test_update_rails_for_mode_drops_non_whitelist_dynamic_rails():
async def test_update_rails_for_mode_does_not_call_update_agent_rails():
"""Flash must not invoke the parent's full dynamic-registration path."""
adapter = JiuwenSwarmFlashAdapter()
- adapter._instance = SimpleNamespace(unregister_rail=AsyncMock())
+ adapter._instance = SimpleNamespace(register_rail=AsyncMock(), unregister_rail=AsyncMock())
with pytest.MonkeyPatch.context() as mp:
called = {"n": 0}
@@ -237,6 +237,7 @@ async def test_update_rails_for_mode_does_not_call_update_agent_rails():
called["n"] += 1
mp.setattr(adapter, "_update_agent_rails", _nope)
+ mp.setattr(adapter, "_rebind_late_read_rails_to_local", Mock())
await adapter._update_rails_for_mode("flash")
assert called["n"] == 0
@@ -251,7 +252,7 @@ def test_flash_rail_snapshot_is_stable_and_fingerprint_is_stable():
snapshot = adapter._rail_snapshot()
fingerprint = adapter._profile_fingerprint()
- assert snapshot == "task_planning_rail,memory_rail"
+ assert snapshot == "task_planning_rail,context_assemble_rail,memory_rail"
assert fingerprint == adapter._profile_fingerprint()
assert len(fingerprint) == 12
diff --git a/tests/unit_tests/agentserver/test_flash_external_memory_integration.py b/tests/unit_tests/agentserver/test_flash_external_memory_integration.py
index f555065191..9fa9f18d7a 100644
--- a/tests/unit_tests/agentserver/test_flash_external_memory_integration.py
+++ b/tests/unit_tests/agentserver/test_flash_external_memory_integration.py
@@ -43,7 +43,8 @@ def flash_memory(monkeypatch):
monkeypatch.setattr(memory_module, "get_memory_section", lambda cfg=None: (cfg or config)["memory"])
adapter = JiuwenSwarmFlashAdapter()
adapter._instance = RecordingAgent()
- # Isolate built-in memory, not the existing external configuration gates.
+ # Isolate workspace context and built-in memory from the external gates.
+ monkeypatch.setattr(adapter, "_ensure_flash_context_rail", AsyncMock())
monkeypatch.setattr(adapter, "_handle_memory_rail_by_config", AsyncMock())
external = SimpleNamespace(kind="external", _provider=SimpleNamespace(on_session_end=AsyncMock()))
profile = SimpleNamespace(kind="profile")
diff --git a/tests/unit_tests/agentserver/test_flash_identity_memory.py b/tests/unit_tests/agentserver/test_flash_identity_memory.py
new file mode 100644
index 0000000000..3298d42c04
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_flash_identity_memory.py
@@ -0,0 +1,475 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+"""Flash workspace identity and local-memory regression tests."""
+
+import asyncio
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, Mock
+from uuid import uuid4
+
+import httpx
+import pytest
+import tiktoken
+from openjiuwen.core.foundation.llm import AssistantMessageChunk
+from openjiuwen.core.foundation.tool import ToolCard
+from openjiuwen.core.memory.lite.manager import INDEX_CACHE
+from openjiuwen.core.runner import Runner
+from openjiuwen.core.single_agent import AgentCard
+from openjiuwen.core.single_agent.rail.base import AgentCallbackEvent
+from openjiuwen.core.sys_operation import (
+ LocalWorkConfig,
+ OperationMode,
+ SysOperationCard,
+)
+from openjiuwen.harness.deep_agent import DeepAgent
+from openjiuwen.harness.rails.base import DeepAgentRail
+from openjiuwen.harness.schema.config import DeepAgentConfig
+from openjiuwen.harness.schema.interaction import SendInputRequest
+from openjiuwen.harness.workspace.workspace import Workspace
+
+from jiuwenswarm.agents.harness.common.memory import config as memory_config
+from jiuwenswarm.server.runtime.agent_adapter import interface_deep, interface_flash
+from jiuwenswarm.server.runtime.agent_adapter.interface_flash import (
+ JiuwenSwarmFlashAdapter,
+)
+
+
+class _DisabledToolsForContext(DeepAgentRail):
+ def __init__(self, names):
+ super().__init__()
+ self._disabled_tools = names
+
+
+def _isolate_other_rails(monkeypatch, adapter):
+ for name in (
+ "_handle_memory_rail_by_config",
+ "_handle_external_memory_rail_by_config",
+ "_handle_office_ace_user_profile_rail_by_config",
+ ):
+ monkeypatch.setattr(adapter, name, AsyncMock())
+ monkeypatch.setattr(adapter, "_rebind_late_read_rails_to_local", Mock())
+
+
+async def test_context_rail_survives_consecutive_flash_requests(monkeypatch):
+ adapter = JiuwenSwarmFlashAdapter()
+ adapter._config_cache = {"disabled_tools": ["blocked_tool"]}
+ adapter._progressive_tool_rail = SimpleNamespace(eager_tools=["read_file", "blocked_tool"])
+ adapter._instance = SimpleNamespace(register_rail=AsyncMock(), unregister_rail=AsyncMock())
+ _isolate_other_rails(monkeypatch, adapter)
+
+ await adapter._update_rails_for_mode("flash")
+ context_rail = adapter._context_assemble_rail
+ assert context_rail is not None
+ assert context_rail._disabled_tools == {"blocked_tool"}
+ assert context_rail._tool_name_allowlist == ["read_file", "blocked_tool"]
+ await adapter._update_rails_for_mode("flash")
+
+ assert adapter._context_assemble_rail is context_rail
+ adapter._instance.register_rail.assert_awaited_once_with(context_rail)
+ adapter._instance.unregister_rail.assert_not_awaited()
+
+
+async def test_context_registration_failure_rolls_back_and_can_retry(monkeypatch):
+ adapter = JiuwenSwarmFlashAdapter()
+ adapter._instance = SimpleNamespace(
+ register_rail=AsyncMock(side_effect=[RuntimeError("synthetic failure"), None]),
+ unregister_rail=AsyncMock(),
+ )
+ _isolate_other_rails(monkeypatch, adapter)
+
+ with pytest.raises(RuntimeError, match="synthetic failure"):
+ await adapter._update_rails_for_mode("flash")
+ assert adapter._context_assemble_rail is None
+ adapter._instance.unregister_rail.assert_awaited_once()
+ await adapter._update_rails_for_mode("flash")
+ assert adapter._context_assemble_rail is not None
+ assert adapter._instance.register_rail.await_count == 2
+
+
+async def test_concurrent_flash_requests_do_not_duplicate_context_rail(monkeypatch):
+ adapter = JiuwenSwarmFlashAdapter()
+ registrations = []
+
+ async def register(rail):
+ await asyncio.sleep(0)
+ registrations.append(rail)
+
+ adapter._instance = SimpleNamespace(register_rail=register, unregister_rail=AsyncMock())
+ _isolate_other_rails(monkeypatch, adapter)
+ await asyncio.gather(*(adapter._update_rails_for_mode("flash") for _ in range(3)))
+ assert registrations == [adapter._context_assemble_rail]
+
+
+def test_complete_embedding_is_forwarded_unchanged(monkeypatch):
+ values = {"model": "synthetic-model", "base_url": "https://embed.invalid", "api_key": "test"}
+ adapter = JiuwenSwarmFlashAdapter()
+ adapter._startup_config_base = {"embed": {}}
+ monkeypatch.setattr(interface_flash, "get_embed_config", lambda: dict(values))
+ rail = adapter._build_memory_rail("agent")
+ assert rail._embedding_config.model_name == values["model"]
+ assert rail._embedding_config.base_url == values["base_url"]
+ assert rail._embedding_config.api_key == values["api_key"]
+
+
[email protected]("missing", ["base_url", "api_key", "model"])
+def test_incomplete_embedding_still_constructs_flash_memory(monkeypatch, missing):
+ values = {"model": "synthetic-model", "base_url": "https://embed.invalid", "api_key": "test"}
+ values[missing] = None
+ adapter = JiuwenSwarmFlashAdapter()
+ adapter._startup_config_base = {"embed": {
+ "embed_model": values["model"],
+ "embed_base_url": values["base_url"],
+ "embed_api_key": values["api_key"],
+ }}
+ monkeypatch.setattr(interface_flash, "get_embed_config", lambda: dict(values))
+
+ rail = adapter._build_memory_rail("agent")
+ assert rail is not None
+ assert not rail._embedding_config.api_key
+
+
+async def test_flash_memory_rebuilds_when_embedding_configuration_changes(monkeypatch):
+ config = {
+ "memory": {"mode": "local", "engine": "builtin"},
+ "modes": {"agent": {"memory": {"enabled": True}}},
+ "embed": {"embed_model": "synthetic-model", "embed_base_url": None, "embed_api_key": None},
+ }
+ adapter = JiuwenSwarmFlashAdapter()
+ adapter._startup_config_base = config
+ adapter._instance = SimpleNamespace(register_rail=AsyncMock(), unregister_rail=AsyncMock())
+ monkeypatch.setattr(adapter, "_schedule_memory_reindex", Mock())
+ monkeypatch.setattr(interface_flash, "get_embed_config", lambda: {
+ "model": config["embed"]["embed_model"],
+ "base_url": config["embed"]["embed_base_url"],
+ "api_key": config["embed"]["embed_api_key"],
+ })
+
+ await adapter._handle_memory_rail_by_config("agent")
+ keyword_rail = adapter._memory_rail
+ assert keyword_rail is not None and not keyword_rail._embedding_config.api_key
+
+ config["embed"].update(embed_base_url="https://embed.invalid", embed_api_key="test")
+ await adapter._handle_memory_rail_by_config("agent")
+ vector_rail = adapter._memory_rail
+ assert vector_rail is not keyword_rail
+ assert vector_rail._embedding_config.api_key == "test"
+
+ config["embed"]["embed_base_url"] = None
+ await adapter._handle_memory_rail_by_config("agent")
+ assert adapter._memory_rail is not vector_rail
+ assert not adapter._memory_rail._embedding_config.api_key
+ assert adapter._instance.register_rail.await_count == 3
+ assert adapter._instance.unregister_rail.await_count == 2
+
+
+async def test_real_model_input_keeps_workspace_identity_across_reload(monkeypatch, tmp_path):
+ """Two workspaces and a reload use the real SDK model-input boundary."""
+ monkeypatch.setattr(tiktoken, "get_encoding", lambda _: SimpleNamespace(
+ encode=lambda text, **kwargs: list(range(max(1, len(text) // 4))),
+ ))
+ agents = []
+ sysop_ids = []
+ await Runner.start()
+
+ async def build(label):
+ root = tmp_path / label
+ root.mkdir()
+ (root / "USER.md").write_text(f"# User\n- Name: SYNTHETIC_{label}_IDENTITY\n", encoding="utf-8")
+ card = SysOperationCard(
+ id="identity-test-" + uuid4().hex, mode=OperationMode.LOCAL,
+ work_config=LocalWorkConfig(work_dir=str(tmp_path)),
+ )
+ Runner.resource_mgr.add_sys_operation(card)
+ sysop_ids.append(card.id)
+ sysop = Runner.resource_mgr.get_sys_operation(card.id)
+ workspace = Workspace(root_path=str(root))
+ agent = DeepAgent(AgentCard(id="identity-test-" + uuid4().hex, name=label))
+ agents.append(agent)
+ agent.configure(DeepAgentConfig(
+ rails=[], workspace=workspace, sys_operation=sysop, system_prompt="Synthetic identity test.",
+ enable_task_loop=False, enable_read_image_multimodal=False, max_iterations=2,
+ ))
+ await agent.ensure_initialized()
+ for name in ("visible_marker", "blocked_marker", "deferred_marker"):
+ agent.ability_manager.add(ToolCard(
+ id=f"{label}-{name}", name=name, description=f"Synthetic {name}",
+ input_params={"type": "object", "properties": {}},
+ ))
+ adapter = JiuwenSwarmFlashAdapter(workspace_dir=str(root))
+ adapter._instance = agent
+ adapter._parent_session_id = "identity-" + uuid4().hex
+ adapter._disabled_tools_rail = _DisabledToolsForContext(["blocked_marker"])
+ adapter._progressive_tool_rail = SimpleNamespace(eager_tools=["visible_marker", "blocked_marker"])
+ _isolate_other_rails(monkeypatch, adapter)
+ observed = []
+
+ async def model(*, messages, **kwargs):
+ observed.append("\n".join(str(message.content) for message in messages if message.role == "system"))
+ yield AssistantMessageChunk(content="ok")
+
+ monkeypatch.setattr(agent._react_agent, "_get_llm", lambda: SimpleNamespace(stream=model))
+ await adapter._update_rails_for_mode("flash")
+ await adapter.start_interaction(adapter._parent_session_id)
+ return adapter, agent, workspace, sysop, observed
+
+ async def turn(adapter, agent):
+ stream = await agent.attach_output()
+ assert stream is not None
+ try:
+ await agent.send_input(SendInputRequest(
+ request_id=uuid4().hex,
+ inputs={"query": "Who am I?", "conversation_id": adapter._parent_session_id},
+ ))
+ async with asyncio.timeout(15):
+ async for _ in stream:
+ pass
+ finally:
+ await stream.close(abort_active_round=False)
+
+ try:
+ alice, alice_agent, _, alice_sysop, alice_inputs = await build("ALICE")
+ bob, bob_agent, _, _, bob_inputs = await build("BOB")
+ await turn(alice, alice_agent)
+ await turn(bob, bob_agent)
+ assert "SYNTHETIC_ALICE_IDENTITY" in alice_inputs[-1]
+ assert "SYNTHETIC_BOB_IDENTITY" not in alice_inputs[-1]
+ assert "SYNTHETIC_BOB_IDENTITY" in bob_inputs[-1]
+ assert "SYNTHETIC_ALICE_IDENTITY" not in bob_inputs[-1]
+ assert "visible_marker" in alice_inputs[-1]
+ assert "blocked_marker" not in alice_inputs[-1]
+ assert "deferred_marker" not in alice_inputs[-1]
+
+ replacement = tmp_path / "ALICE_RELOADED"
+ replacement.mkdir()
+ (replacement / "USER.md").write_text(
+ "# User\n- Name: SYNTHETIC_ALICE_RELOADED_IDENTITY\n", encoding="utf-8",
+ )
+ for name in (
+ "_build_skill_rail", "_build_skill_credential_injection_rail",
+ "_build_skill_active_state_rail", "_build_flash_skill_selection_rail",
+ ):
+ monkeypatch.setattr(alice, name, lambda *args, **kwargs: None)
+ monkeypatch.setattr(alice, "_update_permission_rail", Mock())
+ monkeypatch.setattr(
+ alice, "_build_disabled_tools_rail", lambda config: _DisabledToolsForContext(config["disabled_tools"]),
+ )
+ rails, _ = alice._get_current_agent_rails({"disabled_tools": ["visible_marker"]}, {"react": {}})
+ alice_agent.configure(DeepAgentConfig(
+ rails=rails, workspace=Workspace(root_path=str(replacement)), sys_operation=alice_sysop,
+ system_prompt="Synthetic reloaded identity test.", enable_task_loop=False,
+ enable_read_image_multimodal=False, max_iterations=2,
+ ))
+ await alice_agent.ensure_initialized()
+ await alice._update_rails_for_mode("flash")
+ event = alice_agent._react_agent.agent_callback_manager._get_agent_event(
+ AgentCallbackEvent.BEFORE_MODEL_CALL,
+ )
+ callbacks = Runner.callback_framework._callbacks[event]
+ assert sum(getattr(info.callback, "__self__", None) is alice._context_assemble_rail for info in callbacks) == 1
+ await turn(alice, alice_agent)
+ assert "SYNTHETIC_ALICE_RELOADED_IDENTITY" in alice_inputs[-1]
+ assert "SYNTHETIC_BOB_IDENTITY" not in alice_inputs[-1]
+ assert "visible_marker" not in alice_inputs[-1]
+ assert "blocked_marker" in alice_inputs[-1]
+ assert "deferred_marker" not in alice_inputs[-1]
+ finally:
+ for agent in agents:
+ await agent.stop()
+ await agent.aclose()
+ for sysop_id in sysop_ids:
+ Runner.resource_mgr.remove_sys_operation(sysop_id)
+ await Runner.stop()
+
+
+async def test_flash_memory_writes_and_finds_keyword_without_embedding(monkeypatch, tmp_path):
+ """Exercise the real Flash tool and SDK SQLite index in a disposable workspace."""
+ monkeypatch.setattr(interface_flash, "get_embed_config", lambda: {
+ "model": "synthetic-model", "base_url": None, "api_key": None,
+ })
+ adapter = JiuwenSwarmFlashAdapter(workspace_dir=str(tmp_path))
+ adapter._startup_config_base = {"embed": {"embed_model": "synthetic-model"}}
+ rail = adapter._build_memory_rail("agent")
+ assert rail is not None
+
+ workspace = Workspace(root_path=str(tmp_path))
+ workspace.get_node_path("memory").mkdir(parents=True, exist_ok=True)
+ card = SysOperationCard(
+ id="memory-test-" + uuid4().hex,
+ mode=OperationMode.LOCAL,
+ work_config=LocalWorkConfig(work_dir=str(tmp_path)),
+ )
+ agent = DeepAgent(AgentCard(id="memory-test-" + uuid4().hex, name="flash"))
+ manager = None
+ await Runner.start()
+ try:
+ Runner.resource_mgr.add_sys_operation(card)
+ sysop = Runner.resource_mgr.get_sys_operation(card.id)
+ agent.configure(DeepAgentConfig(
+ rails=[], workspace=workspace, sys_operation=sysop, system_prompt="test",
+ enable_task_loop=False, enable_read_image_multimodal=False,
+ ))
+ await agent.ensure_initialized()
+ await agent.register_rail(rail)
+ tool = rail._unified_tool
+ assert tool is not None
+
+ written = await tool.invoke({
+ "mode": "write", "path": "memory/notes.md",
+ "content": "The synthetic project codename is heliotropenimbus. 项目别名翠竹星河。",
+ })
+ assert written.success, written.error
+ found = await tool.invoke({"mode": "search", "query": "heliotropenimbus"})
+ manager = rail._tool_ctx.manager
+ assert found.success, found.error
+ assert manager is not None and manager.provider is None and manager.fts_available
+ assert any("heliotropenimbus" in result["snippet"] for result in found.data["results"])
+ found_chinese = await tool.invoke({"mode": "search", "query": "翠竹星河"})
+ assert found_chinese.success
+ assert any("翠竹星河" in result["snippet"] for result in found_chinese.data["results"])
+
+ old_manager = manager
+ await old_manager.close()
+ found_after_reopen = await tool.invoke({"mode": "search", "query": "heliotropenimbus"})
+ manager = rail._tool_ctx.manager
+ assert manager is not old_manager
+ assert found_after_reopen.success
+ assert any("heliotropenimbus" in result["snippet"] for result in found_after_reopen.data["results"])
+ finally:
+ if manager is not None:
+ for key, cached in list(INDEX_CACHE.items()):
+ if cached is manager:
+ INDEX_CACHE.pop(key, None)
+ await manager.close()
+ await agent.stop()
+ await agent.aclose()
+ Runner.resource_mgr.remove_sys_operation(card.id)
+ await Runner.stop()
+
+
+async def test_identity_builtin_and_cloud_memory_coexist(monkeypatch, tmp_path):
+ """Exercise actual Flash rails together with simulated model and cloud HTTP."""
+ monkeypatch.setenv("OFFICE_ACE_DEPLOYMENT", "pc")
+ monkeypatch.setenv("OFFICE_CLAW_GLOBAL_CONFIG_ROOT", str(tmp_path / "profile-cache"))
+ monkeypatch.setattr(tiktoken, "get_encoding", lambda _: SimpleNamespace(
+ encode=lambda text, **kwargs: list(range(max(1, len(text) // 4))),
+ ))
+ config = {
+ "memory": {
+ "mode": "local", "engine": "both",
+ "external": {
+ "provider": "officeace_cloud", "user_id": "synthetic-user",
+ "scope_id": "synthetic-scope",
+ "officeace_cloud": {"base_url": "https://memory.invalid", "api_key": "test"},
+ },
+ "office_ace_user_profile": {"endpoint": "https://memory.invalid", "api_key": "test"},
+ },
+ "modes": {"agent": {"memory": {"enabled": True}}},
+ "embed": {"embed_model": "synthetic-model"},
+ }
+ monkeypatch.setattr(interface_deep, "get_config", lambda: config)
+ monkeypatch.setattr(memory_config, "get_memory_section", lambda cfg=None: (cfg or config)["memory"])
+ monkeypatch.setattr(interface_flash, "get_embed_config", lambda: {
+ "model": "synthetic-model", "base_url": None, "api_key": None,
+ })
+ requests = []
+
+ async def service(request):
+ assert request.url.host == "memory.invalid"
+ requests.append(request.url.path)
+ if request.url.path.endswith("/search"):
+ return httpx.Response(200, json={"results": [{"content": "SYNTHETIC_CLOUD_RECALL", "score": 0.9}]})
+ if request.url.path.endswith("/user-profile"):
+ return httpx.Response(200, json={"content": "SYNTHETIC_CLOUD_PROFILE"})
+ assert "/pc-threads/" in request.url.path
+ return httpx.Response(200, json={"ok": True})
+
+ client = httpx.AsyncClient
+
+ def simulated_client(*args, **kwargs):
+ kwargs["transport"] = httpx.MockTransport(service)
+ return client(*args, **kwargs)
+
+ monkeypatch.setattr(httpx, "AsyncClient", simulated_client)
+ root = tmp_path / "workspace"
+ root.mkdir()
+ (root / "USER.md").write_text("# User\nName: SYNTHETIC_WORKSPACE_USER\n", encoding="utf-8")
+ workspace = Workspace(root_path=str(root))
+ workspace.get_node_path("memory").mkdir(parents=True, exist_ok=True)
+ card = SysOperationCard(
+ id="identity-cloud-" + uuid4().hex, mode=OperationMode.LOCAL,
+ work_config=LocalWorkConfig(work_dir=str(root)),
+ )
+ agent = DeepAgent(AgentCard(id="identity-cloud-" + uuid4().hex, name="flash"))
+ adapter = JiuwenSwarmFlashAdapter(workspace_dir=str(root))
+ adapter._startup_config_base = config
+ adapter._parent_session_id = "identity-cloud-" + uuid4().hex
+ adapter._parent_thread_id = "synthetic-thread"
+ monkeypatch.setattr(adapter, "_rebind_late_read_rails_to_local", Mock())
+ observed = []
+ manager = None
+ await Runner.start()
+ try:
+ Runner.resource_mgr.add_sys_operation(card)
+ sysop = Runner.resource_mgr.get_sys_operation(card.id)
+ agent.configure(DeepAgentConfig(
+ rails=[], workspace=workspace, sys_operation=sysop, system_prompt="Synthetic combined test.",
+ enable_task_loop=False, enable_read_image_multimodal=False, max_iterations=2,
+ ))
+ await agent.ensure_initialized()
+ adapter._instance = agent
+ await adapter._update_rails_for_mode("flash")
+ assert adapter._context_assemble_rail is not None
+ assert adapter._memory_rail is not None
+ assert adapter._external_memory_rail_registered
+ assert adapter._office_ace_user_profile_rail_registered
+ tool = adapter._memory_rail._unified_tool
+ written = await tool.invoke({
+ "mode": "write", "path": "memory/notes.md",
+ "content": "Synthetic local recall: heliotropenimbus.",
+ })
+ assert written.success, written.error
+
+ async def model(*, messages, **kwargs):
+ observed.append([(message.role, str(message.content)) for message in messages])
+ yield AssistantMessageChunk(content="ok")
+
+ monkeypatch.setattr(agent._react_agent, "_get_llm", lambda: SimpleNamespace(stream=model))
+ await adapter.start_interaction(adapter._parent_session_id)
+ stream = await agent.attach_output()
+ try:
+ await agent.send_input(SendInputRequest(
+ request_id=uuid4().hex,
+ inputs={"query": "Who is the user?", "conversation_id": adapter._parent_session_id},
+ ))
+ async with asyncio.timeout(15):
+ async for _ in stream:
+ pass
+ finally:
+ await stream.close(abort_active_round=False)
+ if adapter._external_memory_rail._sync_task is not None:
+ await adapter._external_memory_rail._sync_task
+ system = "\n".join(content for role, content in observed[-1] if role == "system")
+ all_messages = "\n".join(content for _, content in observed[-1])
+ assert "SYNTHETIC_WORKSPACE_USER" in system
+ assert "SYNTHETIC_CLOUD_RECALL" in all_messages
+ assert "SYNTHETIC_CLOUD_PROFILE" in all_messages
+ found = await tool.invoke({"mode": "search", "query": "heliotropenimbus"})
+ manager = adapter._memory_rail._tool_ctx.manager
+ assert found.success and any("heliotropenimbus" in item["snippet"] for item in found.data["results"])
+ assert any(path.endswith("/search") for path in requests)
+ assert any(path.endswith("/user-profile") for path in requests)
+ finally:
+ if manager is None and adapter._memory_rail is not None and adapter._memory_rail._tool_ctx is not None:
+ manager = adapter._memory_rail._tool_ctx.manager
+ if manager is not None:
+ await manager.close()
+ await agent.stop()
+ await agent.aclose()
+ Runner.resource_mgr.remove_sys_operation(card.id)
+ await Runner.stop()