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(PromptAttachment): split prompt attachment sections by stability

MengHan1818478dd098ad
diff --git a/jiuwenswarm/agents/harness/common/rails/avatar_rail.py b/jiuwenswarm/agents/harness/common/rails/avatar_rail.py
index eedb63fb2e..3e10a36db1 100644
--- a/jiuwenswarm/agents/harness/common/rails/avatar_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/avatar_rail.py
@@ -3,7 +3,7 @@
"""AvatarPromptRail - 数字分身 Rail.
处理所有 per-request 的 avatar 逻辑:
-1. before_model_call: 根据 ContextVar 动态写入/清理 TURN prompt attachment
+1. before_model_call: 根据 ContextVar 动态注入/移除 avatar 相关 PromptSection
2. before_tool_call: 拦截群聊记忆禁写 + enable_memory=False 场景
"""
@@ -12,9 +12,6 @@ from __future__ import annotations
from openjiuwen.core.foundation.llm import ToolMessage
from openjiuwen.core.single_agent.rail.base import AgentCallbackContext
from openjiuwen.harness.prompts import PromptSection
-from openjiuwen.harness.prompts.prompt_attachment_manager import (
- PromptAttachmentKind,
-)
from openjiuwen.harness.rails.base import DeepAgentRail
from jiuwenswarm.agents.harness.common.rails.permissions.owner_scopes import (
@@ -25,20 +22,13 @@ from jiuwenswarm.common.utils import logger
_MEMORY_WRITE_TOOLS = frozenset({"write_memory", "edit_memory"})
_AVATAR_PROMPT_PRIORITY = 110
-_AVATAR_SECTION_PRIORITIES = {
- "avatar_identity": _AVATAR_PROMPT_PRIORITY,
- "group_chat_memory_notice": _AVATAR_PROMPT_PRIORITY + 1,
- "memory_fully_disabled": _AVATAR_PROMPT_PRIORITY + 2,
- "forbidden_memory": _AVATAR_PROMPT_PRIORITY + 3,
- "interaction_guidance": _AVATAR_PROMPT_PRIORITY + 4,
-}
class AvatarPromptRail(DeepAgentRail):
"""数字分身 Rail — 处理所有 per-request 的 avatar 逻辑。
职责:
- 1. before_model_call: 根据 ContextVar 动态写入/清理 TURN prompt attachment
+ 1. before_model_call: 根据 ContextVar 动态注入/移除 avatar 相关 PromptSection
2. before_tool_call: 拦截群聊记忆禁写 + enable_memory=False 场景
"""
@@ -46,14 +36,7 @@ class AvatarPromptRail(DeepAgentRail):
def __init__(self) -> None:
super().__init__()
- self.attachment_manager = None
-
- def init(self, agent) -> None:
- self.attachment_manager = getattr(agent, "prompt_attachment_manager", None)
-
- def uninit(self, agent) -> None:
- del agent
- self.attachment_manager = None
+ self._injected_sections: set[str] = set()
async def before_model_call(self, ctx: AgentCallbackContext) -> None:
builder = getattr(
@@ -61,35 +44,44 @@ class AvatarPromptRail(DeepAgentRail):
"system_prompt_builder",
None,
)
- language = getattr(builder, "language", "cn") if builder is not None else "cn"
- language = language or "cn"
- sections: list[PromptSection] = []
+ if builder is None:
+ return
+
+ for name in list(self._injected_sections):
+ builder.remove_section(name)
+ self._injected_sections.clear()
+
+ language = getattr(builder, "language", "cn") or "cn"
try:
from jiuwenswarm.agents.harness.common.memory.forbidden import get_forbidden_memory_prompt
forbidden = get_forbidden_memory_prompt(language)
if forbidden:
- sections.append(PromptSection(
+ section = PromptSection(
name="forbidden_memory",
content={language: forbidden},
- priority=_AVATAR_SECTION_PRIORITIES["forbidden_memory"],
- ))
+ priority=_AVATAR_PROMPT_PRIORITY + 3,
+ )
+ builder.add_section(section)
+ self._injected_sections.add("forbidden_memory")
except Exception as e:
logger.debug("[AvatarRail] 加载 forbidden_memory 失败: %s", e)
perm_ctx = TOOL_PERMISSION_CONTEXT.get()
if perm_ctx is None:
- await self._sync_avatar_sections(ctx, sections, language=language)
return
# 数字分身身份提示词(仅群聊数字分身模式)
if perm_ctx.group_digital_avatar and perm_ctx.avatar_mode:
display_name = perm_ctx.avatar_principal_name or perm_ctx.principal_user_id
- sections.append(PromptSection(
+ avatar_content = _build_avatar_prompt(display_name, language)
+ section = PromptSection(
name="avatar_identity",
- content={language: _build_avatar_prompt(display_name, language)},
- priority=_AVATAR_SECTION_PRIORITIES["avatar_identity"],
- ))
+ content={language: avatar_content},
+ priority=_AVATAR_PROMPT_PRIORITY,
+ )
+ builder.add_section(section)
+ self._injected_sections.add("avatar_identity")
# 判断是否为群聊数字分身模式(三个条件同时满足)
is_group_digital_avatar = (
@@ -104,11 +96,13 @@ class AvatarPromptRail(DeepAgentRail):
if language == "cn"
else "\n[Group chat mode: write_memory/edit_memory calls are prohibited]\n"
)
- sections.append(PromptSection(
+ section = PromptSection(
name="group_chat_memory_notice",
content={language: notice},
- priority=_AVATAR_SECTION_PRIORITIES["group_chat_memory_notice"],
- ))
+ priority=_AVATAR_PROMPT_PRIORITY + 1,
+ )
+ builder.add_section(section)
+ self._injected_sections.add("group_chat_memory_notice")
# 记忆完全禁用(三个条件同时满足:enable_memory=False + group_digital_avatar=True + 群聊消息)
should_disable_memory = (
@@ -117,20 +111,24 @@ class AvatarPromptRail(DeepAgentRail):
and perm_ctx.avatar_mode
)
if should_disable_memory:
- sections.append(PromptSection(
+ disabled_content = _build_memory_fully_disabled_prompt(language)
+ section = PromptSection(
name="memory_fully_disabled",
- content={language: _build_memory_fully_disabled_prompt(language)},
- priority=_AVATAR_SECTION_PRIORITIES["memory_fully_disabled"],
- ))
+ content={language: disabled_content},
+ priority=_AVATAR_PROMPT_PRIORITY + 2,
+ )
+ builder.add_section(section)
+ self._injected_sections.add("memory_fully_disabled")
if is_group_digital_avatar:
- sections.append(PromptSection(
+ interaction_content = _build_interaction_prompt(language)
+ section = PromptSection(
name="interaction_guidance",
- content={language: _build_interaction_prompt(language)},
- priority=_AVATAR_SECTION_PRIORITIES["interaction_guidance"],
- ))
-
- await self._sync_avatar_sections(ctx, sections, language=language)
+ content={language: interaction_content},
+ priority=_AVATAR_PROMPT_PRIORITY + 4,
+ )
+ builder.add_section(section)
+ self._injected_sections.add("interaction_guidance")
async def before_tool_call(self, ctx: AgentCallbackContext) -> None:
"""拦截记忆工具调用。
@@ -183,33 +181,6 @@ class AvatarPromptRail(DeepAgentRail):
ctx.inputs.tool_result = message
ctx.inputs.tool_msg = ToolMessage(content=message, tool_call_id=tool_call_id)
- async def _sync_avatar_sections(
- self,
- ctx: AgentCallbackContext,
- sections: list[PromptSection],
- *,
- language: str,
- ) -> None:
- if self.attachment_manager is None:
- logger.warning("[AvatarRail] skip avatar context: prompt attachment manager unavailable")
- return
- try:
- writer = self.attachment_manager.bind_context(ctx)
- for section in _AVATAR_SECTION_PRIORITIES:
- await writer.clear_section(section)
- for section in sections:
- await writer.add_from_prompt_section(
- section=section,
- kind=PromptAttachmentKind.RUNTIME,
- source=f"jiuwenswarm.avatar.{section.name}",
- language=language,
- content_kind="text/markdown",
- )
- except ValueError as exc:
- logger.warning("[AvatarRail] skip avatar context prompt attachment: %s", exc)
-
-
-
def _build_avatar_prompt(principal_user_id: str | None, language: str) -> str:
"""数字分身身份提示词。文案复用自 agentserver/prompt_builder.py 的 _avatar_prompt()。"""
diff --git a/jiuwenswarm/agents/harness/common/rails/project_memory_rail.py b/jiuwenswarm/agents/harness/common/rails/project_memory_rail.py
index e792cccd1b..380109ddd5 100644
--- a/jiuwenswarm/agents/harness/common/rails/project_memory_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/project_memory_rail.py
@@ -2,10 +2,10 @@
# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
"""ProjectMemoryRail -- jiuwenswarm product-side rail.
-On every ``before_model_call``, rebuild the session-scoped ``project_memory``
-prompt attachment from cached discovery results. Cache invalidation happens
-explicitly on write-like tool calls, mode/workspace switches, and also falls
-back to a lightweight filesystem snapshot check for correctness.
+On every ``before_model_call``, rebuild the ``project_memory`` section from
+cached discovery results. Cache invalidation happens explicitly on write-like
+tool calls, mode/workspace switches, and also falls back to a lightweight
+filesystem snapshot check for correctness.
This rail lives in jiuwenswarm (not agent-core) so that:
@@ -18,9 +18,6 @@ import os
from typing import TYPE_CHECKING
from openjiuwen.core.single_agent.rail.base import AgentCallbackContext
-from openjiuwen.harness.prompts.prompt_attachment_manager import (
- PromptAttachmentKind,
-)
from openjiuwen.harness.rails.base import DeepAgentRail
from jiuwenswarm.agents.harness.common.rails.project_memory import (
@@ -37,7 +34,7 @@ if TYPE_CHECKING:
class ProjectMemoryRail(DeepAgentRail):
- """Auto-load project memory files and inject them as a prompt attachment.
+ """Auto-load project memory files and inject them into the system prompt.
Loaded sources (all read-only; only ``JIUWENSWARM.md`` and
``JIUWENSWARM.local.md`` are written by ``/init``):
@@ -83,19 +80,17 @@ class ProjectMemoryRail(DeepAgentRail):
self._language: str = language
self._max_chars: int = max_chars
self._additional_directories: tuple[str, ...] = tuple(additional_directories or ())
- self._agent = None
- self.attachment_manager = None
+ self._system_prompt_builder = None
# ------------------------------------------------------------------
# Lifecycle
# ------------------------------------------------------------------
def init(self, agent: "DeepAgent") -> None:
- self._agent = agent
- self.attachment_manager = getattr(agent, "prompt_attachment_manager", None)
- if self.attachment_manager is None:
+ self._system_prompt_builder = getattr(agent, "system_prompt_builder", None)
+ if self._system_prompt_builder is None:
logger.warning(
- "[ProjectMemoryRail] agent has no prompt attachment manager; disabled"
+ "[ProjectMemoryRail] agent has no system_prompt_builder; disabled"
)
return
logger.info(
@@ -105,11 +100,10 @@ class ProjectMemoryRail(DeepAgentRail):
)
def uninit(self, agent: "DeepAgent") -> None:
- """Clear discovery cache on rail swap."""
- del agent
+ """Clear the injected section to avoid stale content on rail swap."""
clear_project_memory_cache(self.resolve_workspace_path())
- self._agent = None
- self.attachment_manager = None
+ if self._system_prompt_builder is not None:
+ self._system_prompt_builder.remove_section(SECTION_NAME)
# ------------------------------------------------------------------
# Public knobs (per-request hot updates, parallel to RuntimePromptRail)
@@ -146,9 +140,9 @@ class ProjectMemoryRail(DeepAgentRail):
# Hook
# ------------------------------------------------------------------
- async def before_model_call(self, ctx: AgentCallbackContext) -> None: # noqa: ARG002
- """Refresh the session-scoped ``project_memory`` attachment."""
- if self._agent is None:
+ async def before_model_call(self, ctx: AgentCallbackContext) -> None:
+ """Refresh the ``project_memory`` section from cached discovery state."""
+ if self._system_prompt_builder is None:
return
workspace_path = self.resolve_workspace_path()
@@ -173,8 +167,10 @@ class ProjectMemoryRail(DeepAgentRail):
merged = merge_memory_content(files, max_chars=self._max_chars)
+ # Always drop the previous section so the current state of disk wins.
+ self._system_prompt_builder.remove_section(SECTION_NAME)
+
if not merged.strip():
- await self._clear_prompt_attachment(ctx)
return
section = build_project_memory_section(
@@ -183,7 +179,7 @@ class ProjectMemoryRail(DeepAgentRail):
priority=self.SECTION_PRIORITY,
)
if section is not None:
- await self._upsert_prompt_attachment(ctx, section)
+ self._system_prompt_builder.add_section(section)
async def after_tool_call(self, ctx: AgentCallbackContext) -> None:
"""Explicitly invalidate memory discovery cache after write-like tools."""
@@ -211,30 +207,5 @@ class ProjectMemoryRail(DeepAgentRail):
return str(root)
return self._workspace_path
- async def _upsert_prompt_attachment(self, ctx: AgentCallbackContext, section) -> None:
- if self.attachment_manager is None:
- logger.warning("[ProjectMemoryRail] skip project memory: prompt attachment manager unavailable")
- return
- try:
- await self.attachment_manager.bind_context(ctx).add_from_prompt_section(
- prompt_section=section,
- kind=PromptAttachmentKind.MEMORY,
- source="jiuwenswarm.project_memory",
- priority=self.SECTION_PRIORITY,
- language=self._language,
- metadata={"workspace": self.resolve_workspace_path()},
- content_kind="text/markdown",
- )
- except ValueError as exc:
- logger.warning("[ProjectMemoryRail] skip project memory prompt attachment: %s", exc)
-
- async def _clear_prompt_attachment(self, ctx: AgentCallbackContext) -> None:
- if self.attachment_manager is None:
- return
- try:
- await self.attachment_manager.bind_context(ctx).clear_section(SECTION_NAME)
- except ValueError as exc:
- logger.warning("[ProjectMemoryRail] skip clearing project memory prompt attachment: %s", exc)
-
__all__ = ["ProjectMemoryRail"]
diff --git a/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.py b/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.py
index 98a075934f..ad23166522 100644
--- a/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.py
@@ -60,12 +60,10 @@ class RuntimePromptRail(DeepAgentRail):
"""清理注入的 section 并释放引用。"""
if self.system_prompt_builder is not None:
self.system_prompt_builder.remove_section("time")
- self.system_prompt_builder.remove_section("runtime")
+ self.system_prompt_builder.remove_section("runtime.model_answer_policy")
self.system_prompt_builder.remove_section("language_output")
self.system_prompt_builder.remove_section("env")
- self.system_prompt_builder.remove_section("git_status")
self.system_prompt_builder.remove_section("browser_tool_policy")
- self.system_prompt_builder.remove_section("trusted_dirs_policy")
self.system_prompt_builder = None
self.attachment_manager = None
@@ -133,9 +131,15 @@ class RuntimePromptRail(DeepAgentRail):
if not self.system_prompt_builder:
return
- for name in ("runtime", "language_output", "env", "git_status", "trusted_dirs_policy"):
+ for name in (
+ "time",
+ "runtime.model_answer_policy",
+ "language_output",
+ "env",
+ "browser_tool_policy"):
self.system_prompt_builder.remove_section(name)
+ # ── time ──
if not self._force_english and self._language == "cn":
time_content = (
f"# 时间说明\n\n"
@@ -155,6 +159,7 @@ class RuntimePromptRail(DeepAgentRail):
priority=92,
))
+ # ── runtime ──
runtime_state: dict[str, Any] = {}
try:
with open(get_config_dir() / "runtime_state.yaml", encoding="utf-8") as f:
@@ -179,9 +184,12 @@ class RuntimePromptRail(DeepAgentRail):
f"- 当前模型:{model}\n"
f"- 当前模式:{mode}\n"
f"- 当前语言:{language_val}\n"
- f"- 当前渠道:{channel}\n"
+ f"- 当前渠道:{channel}"
+ )
+ model_answer_policy = (
+ "# 模型名称回答策略\n\n"
"- 当用户询问「你是什么模型」「当前用的是哪个模型」等问题时,"
- "直接用上方「当前模型」的值回答,只说模型名称,不要介绍身份或列出能力"
+ "直接使用 `runtime.setting` 中的当前模型值回答,只说模型名称,不要介绍身份或列出能力。"
)
else:
runtime_content = (
@@ -189,18 +197,26 @@ class RuntimePromptRail(DeepAgentRail):
f"- Current model: {model}\n"
f"- Current mode: {mode}\n"
f"- Current language: {language_val}\n"
- f"- Current channel: {channel}\n"
- "- When the user asks \"what model are you\" or similar questions, "
- "answer with only the model name above in one sentence — "
- "do NOT introduce yourself or list capabilities."
+ f"- Current channel: {channel}"
+ )
+ model_answer_policy = (
+ "# Model Name Answer Policy\n\n"
+ "- When the user asks what model you are using, answer with only the current model "
+ "value from `runtime.setting`. Do not introduce yourself or list capabilities."
)
+ self.system_prompt_builder.add_section(PromptSection(
+ name="runtime.model_answer_policy",
+ content={"cn": model_answer_policy, "en": model_answer_policy},
+ priority=95,
+ ))
+
+ await self._clear_prompt_attachment(ctx, section="runtime.setting")
await self._upsert_prompt_attachment(
ctx,
- section="runtime",
+ section="runtime.setting",
content=runtime_content,
kind=PromptAttachmentKind.RUNTIME,
- source="jiuwenswarm.runtime_prompt.runtime",
priority=95,
)
@@ -214,14 +230,11 @@ class RuntimePromptRail(DeepAgentRail):
f"Technical terms and code identifiers should remain "
f"in their original form."
)
- await self._upsert_prompt_attachment(
- ctx,
- section="language_output",
- content=language_output_content,
- kind=PromptAttachmentKind.RUNTIME,
- source="jiuwenswarm.runtime_prompt.language_output",
+ self.system_prompt_builder.add_section(PromptSection(
+ name="language_output",
+ content={"cn": language_output_content, "en": language_output_content},
priority=93,
- )
+ ))
# ── Platform / OS environment section ──
os_type = sys.platform
@@ -323,7 +336,6 @@ class RuntimePromptRail(DeepAgentRail):
section="git_status",
content=git_content,
kind=PromptAttachmentKind.WORKSPACE_DELTA,
- source="jiuwenswarm.runtime_prompt.git_status",
priority=87,
)
else:
@@ -332,7 +344,7 @@ class RuntimePromptRail(DeepAgentRail):
section="git_status",
)
- self.system_prompt_builder.remove_section("browser_tool_policy")
+ # ── Channel: browser_tool_policy or trusted_dirs_policy──
if self._channel == "web":
browser_tool_policy = (
"# Browser Tool Policy\n\n"
@@ -345,19 +357,11 @@ class RuntimePromptRail(DeepAgentRail):
"- If `spawn_sub_agent` or `browser_agent` is unavailable, say that the browser "
"subagent is unavailable before trying to start a browser through commands."
)
- await self._upsert_prompt_attachment(
- ctx,
- section="browser_tool_policy",
- content=browser_tool_policy,
- kind=PromptAttachmentKind.RUNTIME,
- source="jiuwenswarm.runtime_prompt.browser_tool_policy",
+ self.system_prompt_builder.add_section(PromptSection(
+ name="browser_tool_policy",
+ content={"cn": browser_tool_policy, "en": browser_tool_policy},
priority=98,
- )
- else:
- await self._clear_prompt_attachment(
- ctx,
- section="browser_tool_policy",
- )
+ ))
if self._channel == "tui":
# Trusted directories policy for TUI mode
@@ -418,17 +422,15 @@ class RuntimePromptRail(DeepAgentRail):
)
await self._upsert_prompt_attachment(
ctx,
- section="trusted_dirs",
+ section="trusted_dirs_policy",
content=trusted_dirs_content,
kind=PromptAttachmentKind.WORKSPACE_DELTA,
- source="jiuwenswarm.runtime_prompt.trusted_dirs",
priority=90,
)
else:
- self.system_prompt_builder.remove_section("trusted_dirs_policy")
- await self._clear_prompt_attachment(ctx, section="trusted_dirs")
+ await self._clear_prompt_attachment(ctx, section="trusted_dirs_policy")
else:
- await self._clear_prompt_attachment(ctx, section="trusted_dirs")
+ await self._clear_prompt_attachment(ctx, section="trusted_dirs_policy")
async def _upsert_prompt_attachment(
self,
@@ -437,7 +439,6 @@ class RuntimePromptRail(DeepAgentRail):
section: str,
content: str,
kind: PromptAttachmentKind,
- source: str,
priority: int,
) -> None:
if self.attachment_manager is None:
@@ -452,7 +453,7 @@ class RuntimePromptRail(DeepAgentRail):
section=section,
content=content,
kind=kind,
- source=source,
+ source="jiuwenswarm.runtime_prompt_rail",
priority=priority,
content_kind="text/markdown",
)
diff --git a/tests/system_tests/test_project_memory.py b/tests/system_tests/test_project_memory.py
index bd0c9cb91a..ed1490fe16 100644
--- a/tests/system_tests/test_project_memory.py
+++ b/tests/system_tests/test_project_memory.py
@@ -15,8 +15,6 @@ from unittest.mock import MagicMock
import pytest
-from openjiuwen.harness.prompts.prompt_attachment_manager import PromptAttachmentManager
-
from jiuwenswarm.server.runtime.agent_adapter.interface_code import JiuwenSwarmCodeAdapter
from jiuwenswarm.server.runtime.agent_adapter.interface_deep import JiuWenSwarmDeepAdapter
from jiuwenswarm.agents.harness.common.rails.project_memory import (
@@ -61,7 +59,6 @@ def _make_agent_with_builder() -> MagicMock:
builder.remove_section = MagicMock(side_effect=_remove)
agent = MagicMock()
agent.system_prompt_builder = builder
- agent.prompt_attachment_manager = PromptAttachmentManager()
return agent
@@ -74,15 +71,18 @@ def _make_ctx(agent: MagicMock, session_id: str = "sess1") -> SimpleNamespace:
)
-async def _project_memory_attachment(agent: MagicMock, session_id: str = "sess1"):
- items = await agent.prompt_attachment_manager.collect_for_session(session_id)
- project_items = [item for item in items if item.id.endswith(".project_memory")]
- return project_items[-1] if project_items else None
+async def _project_memory_section(agent: MagicMock):
+ for section in reversed(agent.system_prompt_builder.added_sections):
+ if section.name == "project_memory":
+ return section
+ return None
-async def _project_memory_body(agent: MagicMock, session_id: str = "sess1") -> str:
- item = await _project_memory_attachment(agent, session_id)
- return item.content if item is not None else ""
+async def _project_memory_body(agent: MagicMock, language: str = "en") -> str:
+ for section in reversed(agent.system_prompt_builder.added_sections):
+ if section.name == "project_memory":
+ return section.render(language)
+ return ""
@pytest.fixture(autouse=True)
@@ -111,10 +111,9 @@ class TestProjectMemoryRailEndToEnd:
rail.init(agent)
await rail.before_model_call(ctx=_make_ctx(agent))
- section = await _project_memory_attachment(agent)
+ section = await _project_memory_section(agent)
assert section is not None
- assert section.id == "session.sess1.project_memory"
- assert "PROJECT-RULE-1" in section.content
+ assert "PROJECT-RULE-1" in section.render("en")
@pytest.mark.asyncio
async def test_rail_reloads_after_file_change(self):
@@ -137,22 +136,6 @@ class TestProjectMemoryRailEndToEnd:
assert "VERSION-2" in body2
assert "VERSION-1" not in body2
- @pytest.mark.asyncio
- async def test_rail_removes_section_on_uninit(self):
- with tempfile.TemporaryDirectory() as td:
- root = Path(td)
- _touch(root, ".git/HEAD", "")
- _touch(root, "JIUWENSWARM.md", "BEFORE-UNINIT")
-
- rail = ProjectMemoryRail(workspace=str(root), language="en")
- agent = _make_agent_with_builder()
- rail.init(agent)
- await rail.before_model_call(ctx=_make_ctx(agent))
- assert await _project_memory_attachment(agent) is not None
-
- rail.uninit(agent)
- assert rail.attachment_manager is None
-
@pytest.mark.asyncio
async def test_rail_no_section_when_workspace_empty(self):
with tempfile.TemporaryDirectory() as td:
@@ -164,7 +147,7 @@ class TestProjectMemoryRailEndToEnd:
rail.init(agent)
await rail.before_model_call(ctx=_make_ctx(agent))
- assert await _project_memory_attachment(agent) is None
+ assert await _project_memory_section(agent) is None
@pytest.mark.asyncio
async def test_rail_additional_directories_via_env(self, monkeypatch):
@@ -701,7 +684,7 @@ class TestProjectMemoryRailLanguagePropagation:
rail.init(agent)
await rail.before_model_call(ctx=_make_ctx(agent))
- cn_body = await _project_memory_body(agent)
+ cn_body = await _project_memory_body(agent, "cn")
assert "项目记忆" in cn_body
# Switch to English
@@ -709,7 +692,7 @@ class TestProjectMemoryRailLanguagePropagation:
assert rail.get_language() == "en"
await rail.before_model_call(ctx=_make_ctx(agent))
- en_body = await _project_memory_body(agent)
+ en_body = await _project_memory_body(agent, "en")
assert "Project Memory" in en_body
@pytest.mark.asyncio
diff --git a/tests/unit_tests/agentserver/rails/test_project_memory_rail.py b/tests/unit_tests/agentserver/rails/test_project_memory_rail.py
index dc862036b4..5aee4397e3 100644
--- a/tests/unit_tests/agentserver/rails/test_project_memory_rail.py
+++ b/tests/unit_tests/agentserver/rails/test_project_memory_rail.py
@@ -11,8 +11,6 @@ from unittest.mock import MagicMock
import pytest
-from openjiuwen.harness.prompts.prompt_attachment_manager import PromptAttachmentManager
-
from jiuwenswarm.agents.harness.common.rails import project_memory_rail as _rail_mod
from jiuwenswarm.agents.harness.common.rails.project_memory import SECTION_NAME
from jiuwenswarm.agents.harness.common.rails.project_memory import (
@@ -60,7 +58,6 @@ def _make_agent_with_builder() -> MagicMock:
builder.remove_section = MagicMock(side_effect=_remove)
agent = MagicMock()
agent.system_prompt_builder = builder
- agent.prompt_attachment_manager = PromptAttachmentManager()
return agent
@@ -73,19 +70,18 @@ def _make_ctx(agent: MagicMock, session_id: str = "sess1") -> SimpleNamespace:
)
-async def _project_memory_attachment(agent: MagicMock, session_id: str = "sess1"):
- items = await agent.prompt_attachment_manager.collect_for_session(session_id)
- project_items = [item for item in items if item.id.endswith(".project_memory")]
- return project_items[-1] if project_items else None
+async def _project_memory_section(agent: MagicMock):
+ for section in reversed(agent.system_prompt_builder.added_sections):
+ if section.name == SECTION_NAME:
+ return section
+ return None
async def _project_memory_body(agent: MagicMock, language: str = "en") -> str:
- item = await _project_memory_attachment(agent)
- if item is None:
- return ""
- if language == "cn" and "## Project Memory" in item.content:
- return item.content
- return item.content
+ for section in reversed(agent.system_prompt_builder.added_sections):
+ if section.name == SECTION_NAME:
+ return section.render(language)
+ return ""
@pytest.mark.asyncio
@@ -100,11 +96,10 @@ async def test_loads_jiuwenswarm_md_from_root():
rail.init(agent)
await rail.before_model_call(ctx=_make_ctx(agent))
- section = await _project_memory_attachment(agent)
+ section = await _project_memory_section(agent)
assert section is not None
- assert section.id == "session.sess1.project_memory"
- assert "PROJECT RULE 1" in section.content
- agent.system_prompt_builder.add_section.assert_not_called()
+ assert "PROJECT RULE 1" in section.render("en")
+ agent.system_prompt_builder.add_section.assert_called()
@pytest.mark.asyncio
@@ -119,9 +114,9 @@ async def test_section_is_bilingual_with_localized_headers():
rail.init(agent)
await rail.before_model_call(ctx=_make_ctx(agent))
- section = await _project_memory_attachment(agent)
+ section = await _project_memory_section(agent)
assert section is not None
- assert "Project Memory" in section.content
+ assert "Project Memory" in section.render("en")
@pytest.mark.asyncio
@@ -170,7 +165,7 @@ async def test_empty_directory_no_section():
rail.init(agent)
await rail.before_model_call(ctx=_make_ctx(agent))
- assert await _project_memory_attachment(agent) is None
+ assert await _project_memory_section(agent) is None
@pytest.mark.asyncio
@@ -225,7 +220,7 @@ async def test_ignores_legacy_runtime_files():
rail.init(agent)
await rail.before_model_call(ctx=_make_ctx(agent))
- assert await _project_memory_attachment(agent) is None
+ assert await _project_memory_section(agent) is None
@pytest.mark.asyncio
@@ -332,7 +327,7 @@ async def test_conditional_rule_skips_nonmatching_workspace():
rail.init(agent)
await rail.before_model_call(ctx=_make_ctx(agent))
- assert await _project_memory_attachment(agent) is None
+ assert await _project_memory_section(agent) is None
@pytest.mark.asyncio
@@ -369,7 +364,7 @@ async def test_frontmatter_at_end_of_file_stripped():
rail.init(agent)
await rail.before_model_call(ctx=_make_ctx(agent))
- assert await _project_memory_attachment(agent) is None
+ assert await _project_memory_section(agent) is None
@pytest.mark.asyncio
@@ -383,10 +378,11 @@ async def test_uninit_clears_section():
agent = _make_agent_with_builder()
rail.init(agent)
await rail.before_model_call(ctx=_make_ctx(agent))
- assert await _project_memory_attachment(agent) is not None
+ assert await _project_memory_section(agent) is not None
rail.uninit(agent)
- assert agent.system_prompt_builder.remove_section.call_count == 0
+ agent.system_prompt_builder.remove_section.assert_any_call(SECTION_NAME)
+ assert await _project_memory_section(agent) is None
@pytest.mark.asyncio
@@ -510,9 +506,9 @@ async def test_b1_parent_set_workspace_does_not_break_path_resolution():
rail.init(agent)
await rail.before_model_call(ctx=_make_ctx(agent))
- section = await _project_memory_attachment(agent)
+ section = await _project_memory_section(agent)
assert section is not None
- assert "STILL-WORKING" in section.content
+ assert "STILL-WORKING" in section.render("en")
@pytest.mark.asyncio
@@ -529,9 +525,9 @@ async def test_b1_no_workspace_falls_back_to_constructor_path():
rail.init(agent)
await rail.before_model_call(ctx=_make_ctx(agent))
- section = await _project_memory_attachment(agent)
+ section = await _project_memory_section(agent)
assert section is not None
- assert "FROM-CTOR-PATH" in section.content
+ assert "FROM-CTOR-PATH" in section.render("en")
@pytest.mark.asyncio
diff --git a/tests/unit_tests/agentserver/test_prompt_attachment_loader.py b/tests/unit_tests/agentserver/test_prompt_attachment_loader.py
index 3c235e6ad7..4fefadf6a0 100644
--- a/tests/unit_tests/agentserver/test_prompt_attachment_loader.py
+++ b/tests/unit_tests/agentserver/test_prompt_attachment_loader.py
@@ -236,8 +236,10 @@ async def test_file_loaded_attachments_render_and_inject(tmp_path):
assert messages[-1].content == "original query"
assert injected[0].content == "STATIC_SYSTEM_PROMPT"
+ assert injected[1].content == "original query"
assert "SESSION_FILE_MARKER" not in injected[0].content
- assert "original query" in injected[-1].content
+ assert isinstance(injected[-1], UserMessage)
+ assert "original query" not in injected[-1].content
assert "<system-reminder>" in injected[-1].content
assert "SESSION_FILE_MARKER" in injected[-1].content
diff --git a/tests/unit_tests/agentserver/test_system_prompt_restructure.py b/tests/unit_tests/agentserver/test_system_prompt_restructure.py
index a19361d196..07a1a5195c 100644
--- a/tests/unit_tests/agentserver/test_system_prompt_restructure.py
+++ b/tests/unit_tests/agentserver/test_system_prompt_restructure.py
@@ -101,7 +101,9 @@ async def test_runtime_time_section_participates_in_priority_order():
]
positions = [prompt.index(marker) for marker in ordered_markers]
assert positions == sorted(positions)
- assert "当前模型" not in prompt
+ assert builder.has_section("runtime.model_answer_policy")
+ assert not builder.has_section("runtime")
+ assert "# 运行时状态" not in prompt
@pytest.mark.asyncio
@@ -125,20 +127,16 @@ async def test_runtime_dynamic_sections_go_to_prompt_attachment_when_manager_ava
prompt = builder.build()
assert "# Time Description" in prompt
assert "# Runtime State" not in prompt
- assert "# Language" not in prompt
- assert "# Browser Tool Policy" not in prompt
+ assert "# Language" in prompt
+ assert "# Browser Tool Policy" in prompt
assert "# Environment" in prompt
items = await agent.prompt_attachment_manager.collect_for_session("sess1")
- assert [item.id for item in items] == [
- "session.sess1.language_output",
- "session.sess1.runtime",
- "session.sess1.browser_tool_policy",
- ]
+ assert [item.id for item in items] == ["session.sess1.runtime.setting"]
rendered = agent.prompt_attachment_manager.render(items)
assert "model-x" in rendered
- assert "Always respond in English" in rendered
- assert "# Browser Tool Policy" in rendered
+ assert "Always respond in English" in prompt
+ assert "# Browser Tool Policy" in prompt
@pytest.mark.asyncio
@@ -234,11 +232,11 @@ async def test_runtime_prompt_language_output_prefers_rail_language_over_runtime
await runtime_rail.before_model_call(ctx)
prompt = builder.build()
- assert "Always respond in Chinese." not in prompt
+ assert "Always respond in Chinese." in prompt
rendered = agent.prompt_attachment_manager.render(
await agent.prompt_attachment_manager.collect_for_session("sess1")
)
- assert "Always respond in Chinese." in rendered
+ assert "Always respond in Chinese." not in rendered
assert "Always respond in English." not in rendered
assert "Always respond in English." not in prompt
assert "当前语言:cn" in rendered
diff --git a/uv.lock b/uv.lock
index bf215c0763..52df10c666 100644
--- a/uv.lock
+++ b/uv.lock
@@ -2656,7 +2656,7 @@ wheels = [
[[package]]
name = "openjiuwen"
version = "0.1.14"
-source = { git = "https://gitcode.com/openJiuwen/agent-core.git?rev=develop#3585aaf1062fb379fcad950cd28b9e315acdcfd0" }
+source = { git = "https://gitcode.com/openJiuwen/agent-core.git?rev=develop#ee92d08bb27c758cf0abd4453852bfcce395ad50" }
dependencies = [
{ name = "aiofiles" },
{ name = "aiohttp" },