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(agentserver): 代码模式不推迟建库,并加固空库模板落盘

zhangxiangyu525d5c0de1903a
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index 31ab2fa017..942384c589 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -568,6 +568,8 @@ from jiuwenswarm.server.runtime.agent_adapter.sysop_builder import (
create_local_sysop_card,
create_sandbox_sysop_card,
)
+from jiuwenswarm.server.runtime.context_read_patch import apply_context_read_patch
+from jiuwenswarm.server.runtime.memory_init_patch import apply_memory_init_patch
from jiuwenswarm.agents.harness.common.auto_harness.service import _HARNESS_PACKAGES_FILE
from jiuwenswarm.agents.harness.common.plugins.rail_manager import get_rail_manager
from jiuwenswarm.server.runtime.runtime_scope import RuntimeScopeKey
@@ -2407,6 +2409,11 @@ class JiuWenSwarmDeepAdapter:
# 与索引全写进 agent_default。agent_id / service_id 保持企业语义不变
# (个人版的租户身份经 env 命名空间传递,不走这两个字段)。
enterprise = is_enterprise()
+ if enterprise:
+ # 空记忆库拷模板、建库放线程、第一句回复不等建库。仅企业版。
+ apply_memory_init_patch()
+ # 读人设文件时跳过跨进程读写锁。仅企业版。
+ apply_context_read_patch()
if workspace_dir:
self._workspace_dir: str = str(
collapse_nested_agent_workspace_dir(workspace_dir)
@@ -7535,6 +7542,37 @@ class JiuWenSwarmDeepAdapter:
(time.monotonic() - _t0) * 1000,
)
+ def _rebind_late_read_rails_to_local(self) -> None:
+ """把请求期才注册的读盘 rail 从沙箱通道切回本地。
+
+ ``register_rail`` 会用 agent 自己的 sysop(留给写文件、跑命令)覆盖 rail。
+ 只换 rail 自己的通道,给今日/昨日日记这类只读。记忆工具手里那份通道
+ 仍跟沙箱,搜索和写入不离开沙箱。
+ """
+ if not agent_file_read_backend_is_local():
+ return
+ local_sysop = self._create_local_sys_operation()
+ if local_sysop is None:
+ return
+ rebound: list[str] = []
+ for rail in (
+ self._context_assemble_rail,
+ self._memory_rail,
+ self._external_memory_rail,
+ ):
+ if rail is None or self._is_sandbox_bound_rail(rail):
+ continue
+ if not self._set_rail_sys_operation(rail, local_sysop):
+ continue
+ rebound.append(type(rail).__name__)
+ if not rebound:
+ return
+ logger.info(
+ "[SandboxPerf] late_read_rails local: agent_id=%s rails=%s",
+ self._agent_id,
+ ",".join(rebound),
+ )
+
async def _init_workspace_on_host(self) -> None:
"""在宿主机初始化工作区,避免沙箱 DirectoryBuilder 串行建目录。
@@ -11257,6 +11295,8 @@ class JiuWenSwarmDeepAdapter:
logger.warning(
"[JiuWenSwarmDeepAdapter] memory rail refresh on reload failed: %s", e
)
+ # register_rail 会把记忆通道绑回沙箱,热更新后也要把只读切回本地。
+ self._rebind_late_read_rails_to_local()
if first_unregister_error is not None:
raise first_unregister_error
@@ -11785,6 +11825,9 @@ class JiuWenSwarmDeepAdapter:
self._skill_create_rail = None
logger.info("[JiuWenSwarmDeepAdapter] SkillCreateRail unregistered (skill_create=false)")
+ # register_rail 会把后挂的 ContextAssemble / Memory 绑回沙箱,读盘再切本地。
+ self._rebind_late_read_rails_to_local()
+
@staticmethod
def _acp_runtime_tools_enabled(
request_metadata: dict[str, Any] | None,
diff --git a/jiuwenswarm/server/runtime/context_read_patch.py b/jiuwenswarm/server/runtime/context_read_patch.py
new file mode 100644
index 0000000000..0f7a6b7e9d
--- /dev/null
+++ b/jiuwenswarm/server/runtime/context_read_patch.py
@@ -0,0 +1,78 @@
+# coding: utf-8
+"""读人设文件时跳过跨进程读写锁。
+
+AGENT.md、SOUL.md 这类说明文件只是读进提示词。每个会话的文件还不一样,
+不需要为了「别的进程正在写同一份」去领一把 sqlite 锁。
+那把锁的领锁窗口是全局的,20 个会话会排成一队。
+
+``only_read=True`` 是本地读文件函数已有的开关,表示跳过这把锁。
+写文件的路径不改。
+"""
+from __future__ import annotations
+
+from contextvars import ContextVar, Token
+from typing import Any, Callable, Optional
+
+from openjiuwen.core.common.logging import logger
+
+__all__ = [
+ "apply_context_read_patch",
+ "remove_context_read_patch",
+]
+
+_PATCHED = False
+_skip_lock: ContextVar[bool] = ContextVar("context_read_skip_lock", default=False)
+_original_read_file: Optional[Callable] = None
+_original_read_context_file: Optional[Callable] = None
+
+
+async def _read_file_skip_lock(self: Any, path: str, *args: Any, **kwargs: Any) -> Any:
+ """人设读取进行中时,强制只读、不上锁。其它调用保持原样。"""
+ if _skip_lock.get():
+ kwargs["only_read"] = True
+ return await _original_read_file(self, path, *args, **kwargs)
+
+
+async def _read_context_file_skip_lock(
+ sys_operation: Any,
+ workspace: Any,
+ file_key: str,
+) -> Any:
+ token: Token[bool] = _skip_lock.set(True)
+ try:
+ return await _original_read_context_file(sys_operation, workspace, file_key)
+ finally:
+ _skip_lock.reset(token)
+
+
+def apply_context_read_patch() -> None:
+ """安装补丁。重复调用无效果。"""
+ global _PATCHED, _original_read_file, _original_read_context_file
+ if _PATCHED:
+ return
+
+ import openjiuwen.harness.prompts.sections.context as context_mod
+ from openjiuwen.core.sys_operation.local.fs_operation import FsOperation
+
+ _original_read_file = getattr(FsOperation, "read_file")
+ _original_read_context_file = getattr(context_mod, "_read_context_file")
+ setattr(FsOperation, "read_file", _read_file_skip_lock)
+ setattr(context_mod, "_read_context_file", _read_context_file_skip_lock)
+ _PATCHED = True
+ logger.info("[ContextRead] patch applied (persona files read with only_read=True)")
+
+
+def remove_context_read_patch() -> None:
+ """卸下补丁。只给单测用。"""
+ global _PATCHED, _original_read_file, _original_read_context_file
+ if not _PATCHED:
+ return
+
+ import openjiuwen.harness.prompts.sections.context as context_mod
+ from openjiuwen.core.sys_operation.local.fs_operation import FsOperation
+
+ setattr(FsOperation, "read_file", _original_read_file)
+ setattr(context_mod, "_read_context_file", _original_read_context_file)
+ _original_read_file = None
+ _original_read_context_file = None
+ _PATCHED = False
diff --git a/jiuwenswarm/server/runtime/enterprise_config/loader.py b/jiuwenswarm/server/runtime/enterprise_config/loader.py
index 1e5df319fc..3a40bcd9d5 100644
--- a/jiuwenswarm/server/runtime/enterprise_config/loader.py
+++ b/jiuwenswarm/server/runtime/enterprise_config/loader.py
@@ -306,7 +306,11 @@ async def _fetch_slot_entities(
slot: str,
template_ids: list[str],
) -> list[dict[str, Any]]:
- entities = await _template_entity_cache.get_by_ids(slot, template_ids)
+ # 进程级 TTL/单飞缓存只给企业版;个人版每次直查,保持原路径。
+ if is_enterprise():
+ entities = await _template_entity_cache.get_by_ids(slot, template_ids)
+ else:
+ entities = await db_queries.fetch_templates_by_slot(slot, template_ids)
requested = {str(tid or "").strip() for tid in template_ids} - {""}
id_field = (
"policy_id"
@@ -336,6 +340,8 @@ async def _fetch_instance_agent_resource(resource_id: str) -> dict[str, Any] | N
)
return rows[0] if rows else None
+ if not is_enterprise():
+ return await _load()
return await _resource_row_cache.get_or_fetch(f"iar:{rid}", _load)
@@ -351,6 +357,8 @@ async def _fetch_agent_template_row(template_id: str) -> dict[str, Any] | None:
)
return rows[0] if rows else None
+ if not is_enterprise():
+ return await _load()
return await _agent_template_cache.get_or_fetch(f"at:{tid}", _load)
diff --git a/jiuwenswarm/server/runtime/memory_init_patch.py b/jiuwenswarm/server/runtime/memory_init_patch.py
new file mode 100644
index 0000000000..28623f11c1
--- /dev/null
+++ b/jiuwenswarm/server/runtime/memory_init_patch.py
@@ -0,0 +1,370 @@
+# coding: utf-8
+"""记忆库初始化:空库拷模板、建库离开事件循环、第一句回复不等建库。
+
+事件循环可以理解成「服务员一次只能干一件事」。原来每个新会话都在这个服务员
+手里现场建 sqlite 库(建表、试全文索引、加载向量插件、全量扫文件),20 个会话
+会把第一句回复堵在后面。
+
+本补丁做三件事:
+
+1. 进程里先备好一份空的 memory.db(表和元数据都写好),新会话缺文件时拷贝,
+ 不再现场 CREATE。
+2. 拷贝、打开、建表、加载向量插件都放进线程,不占用事件循环。
+3. MemoryRail(对话记忆)在第一句回复前不再建库。模型真正调用记忆搜索时,
+ 工具自己会初始化(ensure_manager)。今日/昨日日记仍按原逻辑直接读文件,
+ 不依赖这个库。
+
+代码模式(CodingMemoryRail)不推迟建库,避免自动召回整会话失效。
+补丁是进程级的:装上后对本进程所有 MemoryRail 生效,直到 remove。
+"""
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+import shutil
+import tempfile
+import threading
+from typing import Any, Callable, Optional
+
+from openjiuwen.core.common.logging import logger
+from openjiuwen.core.memory.lite.config import MemorySettings
+from openjiuwen.core.memory.lite.manager import MemoryIndexManager
+
+__all__ = [
+ "apply_memory_init_patch",
+ "remove_memory_init_patch",
+]
+
+_PATCHED = False
+_META_KEY = "memory_index_meta_v1"
+
+_original_initialize: Optional[Callable] = None
+_original_open_database: Optional[Callable] = None
+_original_ensure_schema: Optional[Callable] = None
+_original_load_vector: Optional[Callable] = None
+_original_needs_rebuild: Optional[Callable] = None
+_original_init_manager: Optional[Callable] = None
+
+_template_lock = threading.Lock()
+_conn_lock = threading.Lock()
+_cached_template: Optional[str] = None
+_ready_conns: dict[str, Any] = {}
+_skip_schema_paths: set[str] = set()
+_skip_vector_paths: set[str] = set()
+_build_guard = threading.local()
+
+
+class _EmptyMemoryWorkspace:
+ """只给模板库用的空工作区,里面没有记忆文件。"""
+
+ def __init__(self, memory_dir: str) -> None:
+ self.root_path = os.path.dirname(memory_dir)
+ self.memory_dir = memory_dir
+ self.daily_rel: Optional[str] = None
+
+ def get_node_path(self, node_name: str) -> Optional[str]:
+ if node_name == "memory":
+ return self.memory_dir
+ return None
+
+ def get_directory(self, name: str) -> Optional[str]:
+ if name == "daily_memory":
+ return self.daily_rel
+ return None
+
+
+def _db_file_missing(path: str) -> bool:
+ if not os.path.isfile(path):
+ return True
+ try:
+ size = os.path.getsize(path)
+ except OSError:
+ return True
+ return size == 0
+
+
+def _remove_sidecars(path: str) -> None:
+ for suffix in ("-wal", "-shm"):
+ side = path + suffix
+ if not os.path.isfile(side):
+ continue
+ try:
+ os.remove(side)
+ except OSError as exc:
+ logger.debug("memory db sidecar remove failed: %s", exc)
+
+
+def _remove_path_quiet(path: str) -> None:
+ try:
+ if os.path.isfile(path):
+ os.remove(path)
+ except OSError as exc:
+ logger.debug("memory db temp remove failed: %s", exc)
+
+
+def _copy_sqlite_file(src: str, dest: str) -> None:
+ parent = os.path.dirname(dest)
+ if parent:
+ os.makedirs(parent, exist_ok=True)
+ tmp_path = dest + ".copying"
+ try:
+ shutil.copy2(src, tmp_path)
+ os.replace(tmp_path, dest)
+ except Exception:
+ _remove_path_quiet(tmp_path)
+ raise
+ _remove_sidecars(dest)
+
+
+def _template_stable_path() -> str:
+ """进程私有模板路径,避免多进程共用 /tmp 固定文件名互相踩。"""
+ return os.path.join(
+ tempfile.gettempdir(),
+ f"jws_empty_memory_{os.getpid()}.db",
+ )
+
+
+def _build_template_db() -> str:
+ """用正式初始化跑一遍空目录,得到可拷贝的空库文件。"""
+ root = tempfile.mkdtemp(prefix="jws_mem_tpl_")
+ memory_dir = os.path.join(root, "memory")
+ os.makedirs(memory_dir, exist_ok=True)
+ settings = MemorySettings()
+ settings.sync = {
+ **settings.sync,
+ "watch": False,
+ "intervalMinutes": 0,
+ }
+ manager = MemoryIndexManager(
+ "template",
+ _EmptyMemoryWorkspace(memory_dir),
+ settings,
+ "memory",
+ )
+ _build_guard.active = True
+ stable = _template_stable_path()
+ staging_fd, staging = tempfile.mkstemp(
+ prefix=f"jws_empty_memory_{os.getpid()}_",
+ suffix=".db",
+ )
+ os.close(staging_fd)
+ try:
+ asyncio.run(_original_initialize(manager))
+ db = manager.db
+ if db is not None:
+ db.execute("PRAGMA wal_checkpoint(TRUNCATE)")
+ src = manager.db_path
+ asyncio.run(manager.close())
+ _copy_sqlite_file(src, staging)
+ os.replace(staging, stable)
+ except Exception:
+ _remove_path_quiet(staging)
+ raise
+ finally:
+ _build_guard.active = False
+ shutil.rmtree(root, ignore_errors=True)
+
+ logger.info("[MemoryInit] empty memory.db template ready: %s", stable)
+ return stable
+
+
+def _ensure_template_db() -> str:
+ global _cached_template
+ with _template_lock:
+ cached = _cached_template
+ if cached and os.path.isfile(cached):
+ return cached
+ built = _build_template_db()
+ _cached_template = built
+ return built
+
+
+def _seed_empty_db(manager: MemoryIndexManager, db_path: str) -> None:
+ """在线程里拷模板、打开连接、补表结构、加载向量插件。"""
+ _copy_sqlite_file(_ensure_template_db(), db_path)
+ manager.db_path = db_path
+ manager.db = _original_open_database(db_path)
+ try:
+ _original_ensure_schema(manager)
+ asyncio.run(_original_load_vector(manager))
+ except Exception:
+ db = manager.db
+ manager.db = None
+ if db is not None:
+ try:
+ db.close()
+ except Exception as exc:
+ logger.debug("seed memory db close failed: %s", exc)
+ raise
+ with _conn_lock:
+ _ready_conns[db_path] = manager.db
+ _skip_schema_paths.add(db_path)
+ _skip_vector_paths.add(db_path)
+ logger.info("[MemoryInit] copied empty memory.db template to %s", db_path)
+
+
+def _open_database_reuse(db_path: str) -> Any:
+ with _conn_lock:
+ ready = _ready_conns.pop(db_path, None)
+ if ready is not None:
+ return ready
+ return _original_open_database(db_path)
+
+
+def _ensure_schema_once(self: MemoryIndexManager) -> None:
+ if self.db_path in _skip_schema_paths:
+ return
+ _original_ensure_schema(self)
+
+
+async def _load_vector_off_loop(self: MemoryIndexManager) -> None:
+ if self.db_path in _skip_vector_paths:
+ return
+
+ def _run() -> None:
+ asyncio.run(_original_load_vector(self))
+
+ await asyncio.to_thread(_run)
+
+
+async def _needs_rebuild_none_safe(self: MemoryIndexManager) -> bool:
+ """没配向量模型时,上游会读 provider.id 然后报错。这里改成按「没有模型」比较。"""
+ if self.provider is not None:
+ return await _original_needs_rebuild(self)
+ try:
+ cursor = self.db.execute(
+ "SELECT value FROM meta WHERE key = ?",
+ (_META_KEY,),
+ )
+ row = cursor.fetchone()
+ if not row:
+ return False
+ meta = json.loads(row["value"])
+ except Exception as exc:
+ logger.warning("Failed to check meta for rebuild: %s", exc)
+ return False
+ provider_changed = meta.get("provider") is not None
+ model_changed = meta.get("model") is not None
+ if provider_changed or model_changed:
+ return True
+ key_changed = meta.get("providerKey") != self.provider_key
+ chunk_changed = meta.get("chunkTokens") != self.settings.chunking.get("tokens")
+ if key_changed or chunk_changed:
+ return True
+ return False
+
+
+def _drop_leftover_conn(manager: MemoryIndexManager, db_path: str) -> None:
+ with _conn_lock:
+ leftover = _ready_conns.pop(db_path, None)
+ if leftover is None:
+ return
+ if leftover is manager.db:
+ return
+ try:
+ leftover.close()
+ except Exception as exc:
+ logger.debug("leftover memory db close failed: %s", exc)
+
+
+async def _initialize_from_template(self: MemoryIndexManager) -> None:
+ if getattr(_build_guard, "active", False):
+ await _original_initialize(self)
+ return
+ resolve = getattr(self, "_resolve_db_path")
+ db_path = resolve()
+ self.db_path = db_path
+ if _db_file_missing(db_path):
+ await asyncio.to_thread(_seed_empty_db, self, db_path)
+ try:
+ await _original_initialize(self)
+ finally:
+ _skip_schema_paths.discard(db_path)
+ _skip_vector_paths.discard(db_path)
+ _drop_leftover_conn(self, db_path)
+
+
+async def _defer_memory_index(self: Any, ctx: Any) -> None:
+ """第一句回复前不建库。记忆工具被调用时才会初始化。"""
+ _ = (self, ctx)
+ logger.info("[MemoryInit] defer index build until a memory tool runs")
+
+
+def apply_memory_init_patch() -> None:
+ """安装记忆初始化补丁。重复调用无效果。
+
+ 只推迟对话 MemoryRail 建库;CodingMemoryRail 保持原路径,避免自动召回失效。
+ """
+ global _PATCHED
+ global _original_initialize, _original_open_database
+ global _original_ensure_schema, _original_load_vector
+ global _original_needs_rebuild, _original_init_manager
+ if _PATCHED:
+ return
+
+ import openjiuwen.core.memory.lite.manager as memory_manager_mod
+ from openjiuwen.harness.rails.memory.memory_rail import MemoryRail
+
+ _original_initialize = MemoryIndexManager.initialize
+ _original_open_database = getattr(memory_manager_mod, "_open_database")
+ _original_ensure_schema = getattr(MemoryIndexManager, "_ensure_schema")
+ _original_load_vector = getattr(MemoryIndexManager, "_load_vector_extension")
+ _original_needs_rebuild = getattr(
+ MemoryIndexManager, "_needs_rebuild_on_config_change"
+ )
+ _original_init_manager = getattr(MemoryRail, "_init_memory_manager")
+
+ setattr(memory_manager_mod, "_open_database", _open_database_reuse)
+ setattr(MemoryIndexManager, "initialize", _initialize_from_template)
+ setattr(MemoryIndexManager, "_ensure_schema", _ensure_schema_once)
+ setattr(MemoryIndexManager, "_load_vector_extension", _load_vector_off_loop)
+ setattr(
+ MemoryIndexManager,
+ "_needs_rebuild_on_config_change",
+ _needs_rebuild_none_safe,
+ )
+ setattr(MemoryRail, "_init_memory_manager", _defer_memory_index)
+ _PATCHED = True
+ logger.info(
+ "[MemoryInit] patch applied "
+ "(template copy, off-loop open, defer MemoryRail until memory tool; "
+ "CodingMemoryRail unchanged)"
+ )
+
+
+def remove_memory_init_patch() -> None:
+ """卸下补丁。只给单测用。"""
+ global _PATCHED
+ global _original_initialize, _original_open_database
+ global _original_ensure_schema, _original_load_vector
+ global _original_needs_rebuild, _original_init_manager
+ global _cached_template
+ if not _PATCHED:
+ return
+
+ import openjiuwen.core.memory.lite.manager as memory_manager_mod
+ from openjiuwen.harness.rails.memory.memory_rail import MemoryRail
+
+ setattr(memory_manager_mod, "_open_database", _original_open_database)
+ setattr(MemoryIndexManager, "initialize", _original_initialize)
+ setattr(MemoryIndexManager, "_ensure_schema", _original_ensure_schema)
+ setattr(MemoryIndexManager, "_load_vector_extension", _original_load_vector)
+ setattr(
+ MemoryIndexManager,
+ "_needs_rebuild_on_config_change",
+ _original_needs_rebuild,
+ )
+ setattr(MemoryRail, "_init_memory_manager", _original_init_manager)
+ _original_initialize = None
+ _original_open_database = None
+ _original_ensure_schema = None
+ _original_load_vector = None
+ _original_needs_rebuild = None
+ _original_init_manager = None
+ _cached_template = None
+ _skip_schema_paths.clear()
+ _skip_vector_paths.clear()
+ with _conn_lock:
+ _ready_conns.clear()
+ _PATCHED = False
diff --git a/tests/unit_tests/agentserver/test_context_read_patch.py b/tests/unit_tests/agentserver/test_context_read_patch.py
new file mode 100644
index 0000000000..a2cc4370fe
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_context_read_patch.py
@@ -0,0 +1,89 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""人设文件读取跳过跨进程读写锁。"""
+
+from __future__ import annotations
+
+from contextlib import asynccontextmanager
+
+import pytest
+
+from openjiuwen.core.sys_operation.base import OperationMode
+from openjiuwen.core.sys_operation.config import LocalWorkConfig
+from openjiuwen.core.sys_operation.local.fs_operation import FsOperation
+from openjiuwen.core.sys_operation.sys_operation import SysOperation, SysOperationCard
+from openjiuwen.harness.prompts.sections import context as context_mod
+
+from jiuwenswarm.server.runtime.context_read_patch import (
+ apply_context_read_patch,
+ remove_context_read_patch,
+)
+
+
+class _Workspace:
+ """只提供人设文件路径。"""
+
+ def __init__(self, agent_md) -> None:
+ self._agent_md = agent_md
+
+ def get_node_path(self, node_name: str):
+ if node_name == "AGENT.md":
+ return self._agent_md
+ return None
+
+
+def _local_sys_op(name: str) -> SysOperation:
+ card = SysOperationCard(id=name, mode=OperationMode.LOCAL, work_config=LocalWorkConfig())
+ return SysOperation(card)
+
+
+def context_read_patch():
+ apply_context_read_patch()
+ yield
+ remove_context_read_patch()
+ getattr(context_mod, "_CONTEXT_FILE_CACHE").clear()
+
+
+def _install_lock_spy(monkeypatch) -> list[bool]:
+ """记下有没有跳过锁,避免测试真的去建 sqlite 锁。"""
+ skipped: list[bool] = []
+
+ @classmethod
+ @asynccontextmanager
+ async def _spy(cls, file_path, timeout, *, skip_lock=False):
+ del cls, file_path, timeout
+ skipped.append(bool(skip_lock))
+ yield
+
+ monkeypatch.setattr(FsOperation, "_maybe_read_lock", _spy)
+ return skipped
+
+
+async def test_persona_read_skips_cross_process_lock(
+ context_read_patch, tmp_path, monkeypatch
+):
+ """读 AGENT.md 时跳过跨进程锁。"""
+ agent_md = tmp_path / "AGENT.md"
+ agent_md.write_text("这是已经填好的助手说明,不是空白模板。\n", encoding="utf-8")
+ skipped = _install_lock_spy(monkeypatch)
+ text = await context_mod._read_context_file(
+ _local_sys_op("ctx-read-test"),
+ _Workspace(agent_md),
+ "AGENT.md",
+ )
+ assert text is not None
+ assert skipped == [True]
+
+
+async def test_other_reads_still_take_the_lock(context_read_patch, tmp_path, monkeypatch):
+ """普通读文件仍然加锁。"""
+ note = tmp_path / "note.txt"
+ note.write_text("plain", encoding="utf-8")
+ skipped = _install_lock_spy(monkeypatch)
+ result = await _local_sys_op("ctx-read-other").fs().read_file(str(note))
+ assert result.code == 0
+ assert result.data.content == "plain"
+ assert skipped == [False]
diff --git a/tests/unit_tests/agentserver/test_late_read_rail_rebind.py b/tests/unit_tests/agentserver/test_late_read_rail_rebind.py
new file mode 100644
index 0000000000..0b17abcc0d
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_late_read_rail_rebind.py
@@ -0,0 +1,50 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""请求期读盘 rail 从沙箱切回本地。"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+_INTERFACE_DEEP = (
+ Path(__file__).resolve().parents[3]
+ / "jiuwenswarm"
+ / "server"
+ / "runtime"
+ / "agent_adapter"
+ / "interface_deep.py"
+)
+
+
+def _interface_deep_source() -> str:
+ return _INTERFACE_DEEP.read_text(encoding="utf-8")
+
+
+def _slice_after(text: str, marker: str) -> str:
+ start = text.find(marker)
+ if start < 0:
+ return ""
+ return text[start:]
+
+
+def test_rebind_does_not_copy_tool_channel() -> None:
+ """只换 rail 通道,不摸工具手里那份 sys_operation。"""
+ body = _slice_after(_interface_deep_source(), "def _rebind_late_read_rails_to_local")
+ assert body
+ body = body[:1600]
+ assert "_set_rail_sys_operation" in body
+ assert "_tool_ctx" not in body
+ assert "tool_ctx.sys_operation" not in body
+
+
+def test_reload_rebinds_after_memory_rail_refresh() -> None:
+ """热更新刷新记忆 rail 后必须再切回本地。"""
+ reload_src = _slice_after(_interface_deep_source(), "async def reload_agent_config")
+ next_def = reload_src.find("\n def ", 1)
+ if next_def != -1:
+ reload_src = reload_src[:next_def]
+ mem_at = reload_src.find("_handle_memory_rail_by_config")
+ rebind_at = reload_src.find("_rebind_late_read_rails_to_local")
+ assert mem_at != -1
+ assert rebind_at != -1
+ assert mem_at < rebind_at
diff --git a/tests/unit_tests/agentserver/test_memory_init_patch.py b/tests/unit_tests/agentserver/test_memory_init_patch.py
new file mode 100644
index 0000000000..a513563b7a
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_memory_init_patch.py
@@ -0,0 +1,345 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""空记忆库拷模板、建库离开事件循环、第一句回复不等建库。"""
+
+from __future__ import annotations
+
+import asyncio
+import os
+import sqlite3
+from pathlib import Path
+from typing import Optional
+
+import pytest
+
+from openjiuwen.core.memory.lite.config import MemorySettings
+from openjiuwen.core.memory.lite.manager import (
+ MemoryIndexManager,
+ clear_memory_manager_cache,
+)
+from openjiuwen.harness.rails.memory.coding_memory_rail import CodingMemoryRail
+from openjiuwen.harness.rails.memory.memory_rail import MemoryRail
+
+from jiuwenswarm.server.runtime import memory_init_patch
+from jiuwenswarm.server.runtime.memory_init_patch import (
+ apply_memory_init_patch,
+ remove_memory_init_patch,
+)
+
+
+class _DirWorkspace:
+ """单测用的最小工作区,只提供记忆目录。"""
+
+ def __init__(self, memory_dir: str) -> None:
+ self.root_path = os.path.dirname(memory_dir)
+ self.memory_dir = memory_dir
+ self.daily_rel: Optional[str] = None
+
+ def get_node_path(self, node_name: str) -> Optional[str]:
+ if node_name == "memory":
+ return self.memory_dir
+ return None
+
+ def get_directory(self, name: str) -> Optional[str]:
+ if name == "daily_memory":
+ return self.daily_rel
+ return None
+
+
+def memory_patch():
+ apply_memory_init_patch()
+ yield
+ remove_memory_init_patch()
+ clear_memory_manager_cache()
+
+
+async def test_before_invoke_does_not_build_memory_db(memory_patch, monkeypatch):
+ """第一句回复前不调用建库。"""
+ called = {"n": 0}
+
+ async def _boom(*_args, **_kwargs):
+ called["n"] += 1
+ raise AssertionError("should not init memory before the first reply")
+
+ monkeypatch.setattr(
+ "openjiuwen.harness.rails.memory.memory_rail.init_memory_manager_async",
+ _boom,
+ )
+ rail = MemoryRail.__new__(MemoryRail)
+ rail._initialized = False
+ await rail.before_invoke(type("Ctx", (), {"inputs": object()})())
+ assert called["n"] == 0
+ assert rail._initialized is True
+
+
+def test_seed_closes_db_when_schema_fails(memory_patch, tmp_path, monkeypatch):
+ """建表失败时关掉已经打开的连接,避免泄漏。"""
+ template = tmp_path / "template.db"
+ template.write_bytes(b"")
+ dest = tmp_path / "memory" / "memory.db"
+ closed = {"n": 0}
+
+ class _Conn:
+ def close(self) -> None:
+ closed["n"] += 1
+
+ monkeypatch.setattr(memory_init_patch, "_ensure_template_db", lambda: str(template))
+ monkeypatch.setattr(memory_init_patch, "_original_open_database", lambda _path: _Conn())
+
+ def _boom(_manager):
+ raise RuntimeError("schema failed")
+
+ monkeypatch.setattr(memory_init_patch, "_original_ensure_schema", _boom)
+ manager = MemoryIndexManager.__new__(MemoryIndexManager)
+ manager.db = None
+ manager.db_path = None
+ with pytest.raises(RuntimeError, match="schema failed"):
+ memory_init_patch._seed_empty_db(manager, str(dest))
+ assert closed["n"] == 1
+ assert manager.db is None
+
+
+async def test_coding_before_invoke_still_builds_memory_db(memory_patch, monkeypatch):
+ """代码模式不推迟建库,自动召回仍可用。"""
+ called = {"n": 0}
+
+ async def _fake_init(*_args, **_kwargs):
+ called["n"] += 1
+ return object()
+
+ monkeypatch.setattr(
+ "openjiuwen.harness.rails.memory.coding_memory_rail.init_memory_manager_async",
+ _fake_init,
+ )
+ rail = CodingMemoryRail.__new__(CodingMemoryRail)
+ rail._manager_initialized = False
+ rail._manager = None
+ rail._tool_ctx = None
+ rail._recalled_content = None
+ rail._prefetch_task = None
+ rail._coding_memory_dir = ""
+ rail.workspace = None
+ rail._embedding_config = None
+ rail.sys_operation = None
+
+ class _Agent:
+ card = type("Card", (), {"id": "agent-1"})()
+
+ def _get_llm(self):
+ return None
+
+ class _Inputs:
+ def is_cron(self):
+ return False
+
+ def is_heartbeat(self):
+ return False
+
+ ctx = type("Ctx", (), {"inputs": _Inputs(), "agent": _Agent()})()
+ await rail.before_invoke(ctx)
+ assert called["n"] == 1
+ assert rail._manager_initialized is True
+ assert rail._manager is not None
+
+
+def test_coding_memory_rail_is_not_deferred(memory_patch):
+ """补丁不得替换 CodingMemoryRail 的建库入口。"""
+ assert (
+ CodingMemoryRail._init_coding_memory_manager
+ is not memory_init_patch._defer_memory_index
+ )
+
+
+def test_template_stable_path_is_process_private():
+ path = memory_init_patch._template_stable_path()
+ assert f"jws_empty_memory_{os.getpid()}.db" in path
+
+
+def test_copy_sqlite_file_removes_temp_on_failure(tmp_path, monkeypatch):
+ """拷贝失败时清掉 .copying,避免临时文件残留。"""
+ src = tmp_path / "src.db"
+ src.write_bytes(b"ok")
+ dest = tmp_path / "dest.db"
+ copying = Path(str(dest) + ".copying")
+
+ def _boom(_s, _d):
+ copying.write_bytes(b"partial")
+ raise OSError("disk full")
+
+ monkeypatch.setattr(memory_init_patch.shutil, "copy2", _boom)
+ with pytest.raises(OSError, match="disk full"):
+ memory_init_patch._copy_sqlite_file(str(src), str(dest))
+ assert not copying.exists()
+ assert not dest.exists()
+
+
+async def test_missing_db_is_copied_off_the_event_loop(memory_patch, tmp_path, monkeypatch):
+ """缺库时在线程里拷模板,而不是在事件循环上现场建。"""
+ thread_names: list[str] = []
+ real_to_thread = asyncio.to_thread
+
+ async def _spy(func, *args, **kwargs):
+ thread_names.append(getattr(func, "__name__", ""))
+ return await real_to_thread(func, *args, **kwargs)
+
+ monkeypatch.setattr(memory_init_patch.asyncio, "to_thread", _spy)
+ memory_dir = tmp_path / "memory"
+ memory_dir.mkdir()
+ manager = MemoryIndexManager(
+ "agent-new",
+ _DirWorkspace(str(memory_dir)),
+ MemorySettings(),
+ "memory",
+ )
+ await manager.initialize()
+ try:
+ db_path = memory_dir / "memory.db"
+ assert db_path.is_file()
+ assert db_path.stat().st_size > 0
+ assert "_seed_empty_db" in thread_names
+ conn = sqlite3.connect(db_path)
+ try:
+ row = conn.execute(
+ "SELECT value FROM meta WHERE key = ?",
+ ("memory_index_meta_v1",),
+ ).fetchone()
+ finally:
+ conn.close()
+ assert row is not None
+ assert "none:no-embedding" in row[0]
+ finally:
+ await manager.close()
+
+
+async def test_existing_db_is_not_replaced(memory_patch, tmp_path, monkeypatch):
+ """已经有库时不覆盖。"""
+ thread_names: list[str] = []
+ real_to_thread = asyncio.to_thread
+
+ async def _spy(func, *args, **kwargs):
+ thread_names.append(getattr(func, "__name__", ""))
+ return await real_to_thread(func, *args, **kwargs)
+
+ monkeypatch.setattr(memory_init_patch.asyncio, "to_thread", _spy)
+ memory_dir = tmp_path / "memory"
+ memory_dir.mkdir()
+ db_path = memory_dir / "memory.db"
+ conn = sqlite3.connect(db_path)
+ conn.execute("CREATE TABLE marker (id INTEGER)")
+ conn.execute("INSERT INTO marker VALUES (7)")
+ conn.commit()
+ conn.close()
+
+ manager = MemoryIndexManager(
+ "agent-old",
+ _DirWorkspace(str(memory_dir)),
+ MemorySettings(),
+ "memory",
+ )
+ await manager.initialize()
+ try:
+ assert "_seed_empty_db" not in thread_names
+ conn = sqlite3.connect(db_path)
+ try:
+ row = conn.execute("SELECT id FROM marker").fetchone()
+ finally:
+ conn.close()
+ assert row == (7,)
+ finally:
+ await manager.close()
+
+
+def test_adapter_init_defers_memory_only_on_enterprise() -> None:
+ """个人版不装推迟建库补丁,保持上游原路径。"""
+ src = (
+ Path(__file__).resolve().parents[3]
+ / "jiuwenswarm"
+ / "server"
+ / "runtime"
+ / "agent_adapter"
+ / "interface_deep.py"
+ ).read_text(encoding="utf-8")
+ start = src.find("apply_deepagent_task_plan_binding_patch()")
+ body = src[start : start + 1200]
+ enterprise_at = body.find("enterprise = is_enterprise()")
+ if_at = body.find("if enterprise:")
+ mem_at = body.find("apply_memory_init_patch()")
+ ctx_at = body.find("apply_context_read_patch()")
+ assert enterprise_at != -1
+ assert if_at != -1
+ assert mem_at != -1
+ assert ctx_at != -1
+ assert enterprise_at < if_at < mem_at < ctx_at
+
+
+def test_non_enterprise_adapter_skips_memory_patches(monkeypatch):
+ """运行时:非企业版构造 adapter 不安装 memory / context 补丁。"""
+ import jiuwenswarm.server.runtime.agent_adapter.interface_deep as deep_mod
+
+ calls: list[str] = []
+ monkeypatch.setattr(deep_mod, "is_enterprise", lambda: False)
+ monkeypatch.setattr(
+ deep_mod, "apply_mcp_call_timeout_patch", lambda: None
+ )
+ monkeypatch.setattr(
+ deep_mod, "apply_deepagent_task_plan_binding_patch", lambda: None
+ )
+ monkeypatch.setattr(
+ deep_mod,
+ "apply_memory_init_patch",
+ lambda: calls.append("memory"),
+ )
+ monkeypatch.setattr(
+ deep_mod,
+ "apply_context_read_patch",
+ lambda: calls.append("context"),
+ )
+ monkeypatch.setattr(deep_mod, "get_agent_workspace_dir", lambda: "/tmp/ws")
+ monkeypatch.setattr(
+ deep_mod,
+ "collapse_nested_agent_workspace_dir",
+ lambda path: path,
+ )
+
+ adapter = deep_mod.JiuWenSwarmDeepAdapter.__new__(deep_mod.JiuWenSwarmDeepAdapter)
+ deep_mod.JiuWenSwarmDeepAdapter.__init__(adapter)
+ assert calls == []
+
+
+def test_enterprise_adapter_applies_memory_patches(monkeypatch):
+ """运行时:企业版构造 adapter 会安装 memory / context 补丁。"""
+ import jiuwenswarm.server.runtime.agent_adapter.interface_deep as deep_mod
+
+ calls: list[str] = []
+ monkeypatch.setattr(deep_mod, "is_enterprise", lambda: True)
+ monkeypatch.setattr(
+ deep_mod, "apply_mcp_call_timeout_patch", lambda: None
+ )
+ monkeypatch.setattr(
+ deep_mod, "apply_deepagent_task_plan_binding_patch", lambda: None
+ )
+ monkeypatch.setattr(
+ deep_mod,
+ "apply_memory_init_patch",
+ lambda: calls.append("memory"),
+ )
+ monkeypatch.setattr(
+ deep_mod,
+ "apply_context_read_patch",
+ lambda: calls.append("context"),
+ )
+ monkeypatch.setattr(deep_mod, "get_agent_workspace_dir", lambda: "/tmp/ws")
+ monkeypatch.setattr(
+ deep_mod,
+ "collapse_nested_agent_workspace_dir",
+ lambda path: path,
+ )
+
+ adapter = deep_mod.JiuWenSwarmDeepAdapter.__new__(deep_mod.JiuWenSwarmDeepAdapter)
+ deep_mod.JiuWenSwarmDeepAdapter.__init__(adapter, workspace_dir="/tmp/ws")
+ assert calls == ["memory", "context"]
diff --git a/tests/unit_tests/agentserver/test_template_entity_cache.py b/tests/unit_tests/agentserver/test_template_entity_cache.py
index a648452ac4..0dcea51ffa 100644
--- a/tests/unit_tests/agentserver/test_template_entity_cache.py
+++ b/tests/unit_tests/agentserver/test_template_entity_cache.py
@@ -187,3 +187,63 @@ async def test_invalidate_during_fetch_does_not_write_stale(
assert len(fetch_calls) == fetch_before + 1
finally:
mod.db_queries.fetch_templates_by_slot = original # type: ignore[method-assign]
+
+
+async def test_fetch_slot_entities_uses_cache_on_enterprise(
+ template_cache, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ mod, fetch_calls = template_cache
+ monkeypatch.setattr(mod, "is_enterprise", lambda: True)
+ await mod._fetch_slot_entities("default_model", ["m1"])
+ await mod._fetch_slot_entities("default_model", ["m1"])
+ assert len(fetch_calls) == 1
+
+
+async def test_fetch_slot_entities_skips_cache_when_not_enterprise(
+ template_cache, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ mod, fetch_calls = template_cache
+ monkeypatch.setattr(mod, "is_enterprise", lambda: False)
+ await mod._fetch_slot_entities("default_model", ["m1"])
+ await mod._fetch_slot_entities("default_model", ["m1"])
+ assert len(fetch_calls) == 2
+ assert mod._template_entity_cache._entries == {}
+
+
+async def test_fetch_resource_row_skips_cache_when_not_enterprise(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ calls: list[str] = []
+
+ async def _fake_list_records(table: str, filters: dict[str, Any]) -> list[dict[str, Any]]:
+ calls.append(str(filters.get("resource_id") or ""))
+ return [{"resource_id": filters.get("resource_id"), "enabled": True}]
+
+ monkeypatch.setattr(loader_mod, "is_enterprise", lambda: False)
+ monkeypatch.setattr(loader_mod.db_queries, "list_records", _fake_list_records)
+ loader_mod.invalidate_enterprise_config_caches()
+ first = await loader_mod._fetch_instance_agent_resource("rid-1")
+ second = await loader_mod._fetch_instance_agent_resource("rid-1")
+ assert first == second
+ assert calls == ["rid-1", "rid-1"]
+
+
+async def test_fetch_resource_row_uses_cache_on_enterprise(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ calls: list[str] = []
+
+ async def _fake_list_records(table: str, filters: dict[str, Any]) -> list[dict[str, Any]]:
+ calls.append(str(filters.get("resource_id") or ""))
+ return [{"resource_id": filters.get("resource_id"), "enabled": True}]
+
+ monkeypatch.setattr(loader_mod, "is_enterprise", lambda: True)
+ monkeypatch.setattr(loader_mod.db_queries, "list_records", _fake_list_records)
+ loader_mod.invalidate_enterprise_config_caches()
+ await loader_mod._fetch_instance_agent_resource("rid-1")
+ await loader_mod._fetch_instance_agent_resource("rid-1")
+ assert calls == ["rid-1"]